@enbox/dids 0.0.3 → 0.0.5

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.
Files changed (77) hide show
  1. package/dist/browser.mjs +1 -1
  2. package/dist/browser.mjs.map +4 -4
  3. package/dist/esm/index.js +2 -0
  4. package/dist/esm/index.js.map +1 -1
  5. package/dist/esm/methods/did-dht-dns.js +455 -0
  6. package/dist/esm/methods/did-dht-dns.js.map +1 -0
  7. package/dist/esm/methods/did-dht-pkarr.js +168 -0
  8. package/dist/esm/methods/did-dht-pkarr.js.map +1 -0
  9. package/dist/esm/methods/did-dht-types.js +116 -0
  10. package/dist/esm/methods/did-dht-types.js.map +1 -0
  11. package/dist/esm/methods/did-dht-utils.js +143 -0
  12. package/dist/esm/methods/did-dht-utils.js.map +1 -0
  13. package/dist/esm/methods/did-dht.js +65 -842
  14. package/dist/esm/methods/did-dht.js.map +1 -1
  15. package/dist/esm/methods/did-ion-utils.js +161 -0
  16. package/dist/esm/methods/did-ion-utils.js.map +1 -0
  17. package/dist/esm/methods/did-ion.js +4 -151
  18. package/dist/esm/methods/did-ion.js.map +1 -1
  19. package/dist/esm/methods/did-jwk.js.map +1 -1
  20. package/dist/esm/methods/did-key-utils.js +235 -0
  21. package/dist/esm/methods/did-key-utils.js.map +1 -0
  22. package/dist/esm/methods/did-key.js +6 -222
  23. package/dist/esm/methods/did-key.js.map +1 -1
  24. package/dist/esm/resolver/resolver-cache-memory.js +77 -0
  25. package/dist/esm/resolver/resolver-cache-memory.js.map +1 -0
  26. package/dist/esm/utils.js +25 -0
  27. package/dist/esm/utils.js.map +1 -1
  28. package/dist/types/bearer-did.d.ts +4 -4
  29. package/dist/types/bearer-did.d.ts.map +1 -1
  30. package/dist/types/index.d.ts +2 -0
  31. package/dist/types/index.d.ts.map +1 -1
  32. package/dist/types/methods/did-dht-dns.d.ts +114 -0
  33. package/dist/types/methods/did-dht-dns.d.ts.map +1 -0
  34. package/dist/types/methods/did-dht-pkarr.d.ts +56 -0
  35. package/dist/types/methods/did-dht-pkarr.d.ts.map +1 -0
  36. package/dist/types/methods/did-dht-types.d.ts +286 -0
  37. package/dist/types/methods/did-dht-types.d.ts.map +1 -0
  38. package/dist/types/methods/did-dht-utils.d.ts +54 -0
  39. package/dist/types/methods/did-dht-utils.d.ts.map +1 -0
  40. package/dist/types/methods/did-dht.d.ts +45 -460
  41. package/dist/types/methods/did-dht.d.ts.map +1 -1
  42. package/dist/types/methods/did-ion-utils.d.ts +86 -0
  43. package/dist/types/methods/did-ion-utils.d.ts.map +1 -0
  44. package/dist/types/methods/did-ion.d.ts +4 -84
  45. package/dist/types/methods/did-ion.d.ts.map +1 -1
  46. package/dist/types/methods/did-jwk.d.ts +4 -4
  47. package/dist/types/methods/did-jwk.d.ts.map +1 -1
  48. package/dist/types/methods/did-key-utils.d.ts +138 -0
  49. package/dist/types/methods/did-key-utils.d.ts.map +1 -0
  50. package/dist/types/methods/did-key.d.ts +6 -127
  51. package/dist/types/methods/did-key.d.ts.map +1 -1
  52. package/dist/types/methods/did-method.d.ts +3 -3
  53. package/dist/types/methods/did-method.d.ts.map +1 -1
  54. package/dist/types/resolver/resolver-cache-memory.d.ts +58 -0
  55. package/dist/types/resolver/resolver-cache-memory.d.ts.map +1 -0
  56. package/dist/types/utils.d.ts +19 -0
  57. package/dist/types/utils.d.ts.map +1 -1
  58. package/dist/utils.js +1 -1
  59. package/dist/utils.js.map +4 -4
  60. package/package.json +11 -13
  61. package/src/bearer-did.ts +4 -4
  62. package/src/index.ts +2 -0
  63. package/src/methods/did-dht-dns.ts +516 -0
  64. package/src/methods/did-dht-pkarr.ts +192 -0
  65. package/src/methods/did-dht-types.ts +316 -0
  66. package/src/methods/did-dht-utils.ts +157 -0
  67. package/src/methods/did-dht.ts +125 -1131
  68. package/src/methods/did-ion-utils.ts +186 -0
  69. package/src/methods/did-ion.ts +16 -185
  70. package/src/methods/did-jwk.ts +4 -4
  71. package/src/methods/did-key-utils.ts +258 -0
  72. package/src/methods/did-key.ts +20 -272
  73. package/src/methods/did-method.ts +3 -3
  74. package/src/resolver/resolver-cache-memory.ts +84 -0
  75. package/src/utils.ts +27 -0
  76. package/dist/browser.js +0 -73
  77. package/dist/browser.js.map +0 -7
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../node_modules/.bun/base64-js@1.5.1/node_modules/base64-js/index.js", "../../../node_modules/.bun/ieee754@1.2.1/node_modules/ieee754/index.js", "../../../node_modules/.bun/buffer@6.0.3/node_modules/buffer/index.js", "../build/buffer-polyfill.cjs", "../../../node_modules/.bun/@isaacs+ttlcache@1.4.1/node_modules/@isaacs/ttlcache/index.js", "../../../node_modules/.bun/level-supports@4.0.1/node_modules/level-supports/index.js", "../../../node_modules/.bun/module-error@1.0.2/node_modules/module-error/index.js", "../../../node_modules/.bun/level-transcoder@1.0.1/node_modules/level-transcoder/lib/text-endec.js", "../../../node_modules/.bun/level-transcoder@1.0.1/node_modules/level-transcoder/lib/encoding.js", "../../../node_modules/.bun/level-transcoder@1.0.1/node_modules/level-transcoder/lib/formats.js", "../../../node_modules/.bun/level-transcoder@1.0.1/node_modules/level-transcoder/lib/encodings.js", "../../../node_modules/.bun/level-transcoder@1.0.1/node_modules/level-transcoder/index.js", "../../../node_modules/.bun/events@3.3.0/node_modules/events/events.js", "../../../node_modules/.bun/catering@2.1.1/node_modules/catering/next-tick-browser.js", "../../../node_modules/.bun/catering@2.1.1/node_modules/catering/index.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/lib/common.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/abstract-iterator.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/lib/default-kv-iterator.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/lib/deferred-iterator.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/abstract-chained-batch.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/lib/default-chained-batch.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/lib/range-options.js", "../../../node_modules/.bun/queue-microtask@1.2.3/node_modules/queue-microtask/index.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/lib/next-tick-browser.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/lib/abstract-sublevel-iterator.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/lib/abstract-sublevel.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/abstract-level.js", "../../../node_modules/.bun/abstract-level@1.0.4/node_modules/abstract-level/index.js", "../../../node_modules/.bun/run-parallel-limit@1.1.0/node_modules/run-parallel-limit/index.js", "../../../node_modules/.bun/browser-level@1.0.1/node_modules/browser-level/util/key-range.js", "../../../node_modules/.bun/browser-level@1.0.1/node_modules/browser-level/util/deserialize.js", "../../../node_modules/.bun/browser-level@1.0.1/node_modules/browser-level/iterator.js", "../../../node_modules/.bun/browser-level@1.0.1/node_modules/browser-level/util/clear.js", "../../../node_modules/.bun/browser-level@1.0.1/node_modules/browser-level/index.js", "../../../node_modules/.bun/level@8.0.1/node_modules/level/browser.js", "../../../node_modules/.bun/uri-js@4.4.1/node_modules/uri-js/src/index.ts", "../../../node_modules/.bun/uri-js@4.4.1/node_modules/uri-js/src/schemes/urn-uuid.ts", "../../../node_modules/.bun/uri-js@4.4.1/node_modules/uri-js/src/schemes/urn.ts", "../../../node_modules/.bun/uri-js@4.4.1/node_modules/uri-js/src/schemes/mailto.ts", "../../../node_modules/.bun/uri-js@4.4.1/node_modules/uri-js/src/schemes/wss.ts", "../../../node_modules/.bun/uri-js@4.4.1/node_modules/uri-js/src/schemes/ws.ts", "../../../node_modules/.bun/uri-js@4.4.1/node_modules/uri-js/src/schemes/https.ts", "../../../node_modules/.bun/uri-js@4.4.1/node_modules/uri-js/src/schemes/http.ts", "../../../node_modules/.bun/uri-js@4.4.1/node_modules/uri-js/src/uri.ts", "../../../node_modules/.bun/uri-js@4.4.1/node_modules/uri-js/node_modules/punycode/punycode.es6.js", "../../../node_modules/.bun/uri-js@4.4.1/node_modules/uri-js/src/regexps-iri.ts", "../../../node_modules/.bun/uri-js@4.4.1/node_modules/uri-js/src/regexps-uri.ts", "../../../node_modules/.bun/uri-js@4.4.1/node_modules/uri-js/src/util.ts", "../../../node_modules/.bun/canonicalize@2.1.0/node_modules/canonicalize/lib/canonicalize.js", "../../../node_modules/.bun/ms@2.1.3/node_modules/ms/index.js", "../src/index.ts", "../src/types/did-core.ts", "../src/types/did-resolution.ts", "../src/did.ts", "../src/did-error.ts", "../src/bearer-did.ts", "../../crypto/src/index.ts", "../../crypto/src/crypto-error.ts", "../../common/src/index.ts", "../../common/src/cache.ts", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/bases/base32.ts", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/bases/base.ts", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/bytes.ts", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/vendor/base-x.js", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/bases/base58.ts", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/bases/base64.ts", "../../common/src/type-utils.ts", "../../common/src/convert.ts", "../../common/src/logger.ts", "../../common/src/multicodec.ts", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/index.ts", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/cid.ts", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/hashes/digest.ts", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/varint.ts", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/vendor/varint.js", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/link/interface.ts", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/hashes/hasher.ts", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/interface.ts", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/bases/interface.ts", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/src/hashes/interface.ts", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/dist/src/codecs/interface.js", "../../../node_modules/.bun/multiformats@13.1.0/node_modules/multiformats/dist/src/block/interface.js", "../../common/src/object.ts", "../../common/src/stores.ts", "../../crypto/src/algorithms/crypto-algorithm.ts", "../../../node_modules/.bun/@noble+curves@1.3.0/node_modules/@noble/curves/src/abstract/utils.ts", "../../../node_modules/.bun/@noble+curves@1.3.0/node_modules/@noble/curves/src/secp256k1.ts", "../../../node_modules/.bun/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/sha256.ts", "../../../node_modules/.bun/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/_sha2.ts", "../../../node_modules/.bun/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/_assert.ts", "../../../node_modules/.bun/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/utils.ts", "../../../node_modules/.bun/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/crypto.ts", "../../../node_modules/.bun/@noble+curves@1.3.0/node_modules/@noble/curves/src/abstract/modular.ts", "../../../node_modules/.bun/@noble+curves@1.3.0/node_modules/@noble/curves/src/abstract/weierstrass.ts", "../../../node_modules/.bun/@noble+curves@1.3.0/node_modules/@noble/curves/src/abstract/curve.ts", "../../../node_modules/.bun/@noble+curves@1.3.0/node_modules/@noble/curves/src/_shortw_utils.ts", "../../../node_modules/.bun/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/hmac.ts", "../../../node_modules/.bun/@noble+hashes@1.4.0/node_modules/@noble/hashes/src/sha256.ts", "../../../node_modules/.bun/@noble+hashes@1.4.0/node_modules/@noble/hashes/src/_md.ts", "../../../node_modules/.bun/@noble+hashes@1.4.0/node_modules/@noble/hashes/src/_assert.ts", "../../../node_modules/.bun/@noble+hashes@1.4.0/node_modules/@noble/hashes/src/utils.ts", "../../../node_modules/.bun/@noble+hashes@1.4.0/node_modules/@noble/hashes/src/crypto.ts", "../../crypto/src/jose/utils.ts", "../../crypto/src/primitives/sha256.ts", "../../crypto/src/jose/jwk.ts", "../../crypto/src/primitives/secp256k1.ts", "../../../node_modules/.bun/@noble+curves@1.3.0/node_modules/@noble/curves/src/p256.ts", "../../crypto/src/primitives/secp256r1.ts", "../../crypto/src/algorithms/ecdsa.ts", "../../../node_modules/.bun/@noble+curves@1.3.0/node_modules/@noble/curves/src/ed25519.ts", "../../../node_modules/.bun/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/sha512.ts", "../../../node_modules/.bun/@noble+hashes@1.3.3/node_modules/@noble/hashes/src/_u64.ts", "../../../node_modules/.bun/@noble+curves@1.3.0/node_modules/@noble/curves/src/abstract/edwards.ts", "../../../node_modules/.bun/@noble+curves@1.3.0/node_modules/@noble/curves/src/abstract/montgomery.ts", "../../crypto/src/primitives/ed25519.ts", "../../crypto/src/algorithms/eddsa.ts", "../../crypto/src/algorithms/sha-2.ts", "../../crypto/src/local-key-manager.ts", "../../crypto/src/utils.ts", "../../crypto/dist/esm/jose/jwe.js", "../../crypto/dist/esm/jose/jws.js", "../../crypto/dist/esm/jose/jwt.js", "../../crypto/src/primitives/x25519.ts", "../src/utils.ts", "../src/methods/did-dht.ts", "../../../node_modules/.bun/bencode@4.0.0/node_modules/bencode/index.js", "../../../node_modules/.bun/bencode@4.0.0/node_modules/bencode/lib/encode.js", "../../../node_modules/.bun/uint8-util@2.2.6/node_modules/uint8-util/browser.js", "../../../node_modules/.bun/uint8-util@2.2.6/node_modules/uint8-util/util.js", "../../../node_modules/.bun/base64-arraybuffer@1.0.2/node_modules/src/index.ts", "../../../node_modules/.bun/bencode@4.0.0/node_modules/bencode/lib/util.js", "../../../node_modules/.bun/bencode@4.0.0/node_modules/bencode/lib/decode.js", "../../../node_modules/.bun/bencode@4.0.0/node_modules/bencode/lib/encoding-length.js", "../../../node_modules/.bun/@dnsquery+dns-packet@6.1.1/node_modules/@dnsquery/dns-packet/index.mjs", "../../../node_modules/.bun/@leichtgewicht+ip-codec@2.0.5/node_modules/@leichtgewicht/ip-codec/index.mjs", "../../../node_modules/.bun/@dnsquery+dns-packet@6.1.1/node_modules/@dnsquery/dns-packet/types.mjs", "../../../node_modules/.bun/@dnsquery+dns-packet@6.1.1/node_modules/@dnsquery/dns-packet/rcodes.mjs", "../../../node_modules/.bun/@dnsquery+dns-packet@6.1.1/node_modules/@dnsquery/dns-packet/opcodes.mjs", "../../../node_modules/.bun/@dnsquery+dns-packet@6.1.1/node_modules/@dnsquery/dns-packet/classes.mjs", "../../../node_modules/.bun/@dnsquery+dns-packet@6.1.1/node_modules/@dnsquery/dns-packet/optioncodes.mjs", "../../../node_modules/.bun/@dnsquery+dns-packet@6.1.1/node_modules/@dnsquery/dns-packet/buffer_utils.mjs", "../../../node_modules/.bun/utf8-codec@1.0.0/node_modules/utf8-codec/index.mjs", "../src/methods/did-method.ts", "../src/methods/did-ion.ts", "../../../node_modules/.bun/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/index.ts", "../../../node_modules/.bun/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/Encoder.ts", "../../../node_modules/.bun/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/ErrorCode.ts", "../../../node_modules/.bun/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/IonError.ts", "../../../node_modules/.bun/multiformats@12.1.3/node_modules/multiformats/src/bases/base64.js", "../../../node_modules/.bun/multiformats@12.1.3/node_modules/multiformats/src/bases/base.js", "../../../node_modules/.bun/multiformats@12.1.3/node_modules/multiformats/vendor/base-x.js", "../../../node_modules/.bun/multiformats@12.1.3/node_modules/multiformats/src/bytes.js", "../../../node_modules/.bun/multiformats@12.1.3/node_modules/multiformats/src/bases/interface.js", "../../../node_modules/.bun/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/IonRequest.ts", "../../../node_modules/.bun/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/InputValidator.ts", "../../../node_modules/.bun/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/enums/OperationKeyType.ts", "../../../node_modules/.bun/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/IonSdkConfig.ts", "../../../node_modules/.bun/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/JsonCanonicalizer.ts", "../../../node_modules/.bun/multiformats@12.1.3/node_modules/multiformats/src/hashes/digest.js", "../../../node_modules/.bun/multiformats@12.1.3/node_modules/multiformats/src/varint.js", "../../../node_modules/.bun/multiformats@12.1.3/node_modules/multiformats/vendor/varint.js", "../../../node_modules/.bun/multiformats@12.1.3/node_modules/multiformats/src/hashes/sha2-browser.js", "../../../node_modules/.bun/multiformats@12.1.3/node_modules/multiformats/src/hashes/hasher.js", "../../../node_modules/.bun/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/Multihash.ts", "../../../node_modules/.bun/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/enums/OperationType.ts", "../../../node_modules/.bun/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/enums/PatchAction.ts", "../../../node_modules/.bun/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/IonDid.ts", "../../../node_modules/.bun/@noble+ed25519@2.0.0/node_modules/@noble/ed25519/index.js", "../../../node_modules/.bun/@noble+secp256k1@2.0.0/node_modules/@noble/secp256k1/index.js", "../../../node_modules/.bun/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/enums/IonNetwork.ts", "../../../node_modules/.bun/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/enums/IonPublicKeyPurpose.ts", "../src/methods/did-jwk.ts", "../src/methods/did-key.ts", "../src/methods/did-web.ts", "../src/resolver/resolver-cache-level.ts", "../src/resolver/resolver-cache-noop.ts", "../src/resolver/universal-resolver.ts"],
4
- "sourcesContent": ["'use strict'\n\nexports.byteLength = byteLength\nexports.toByteArray = toByteArray\nexports.fromByteArray = fromByteArray\n\nvar lookup = []\nvar revLookup = []\nvar Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array\n\nvar code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'\nfor (var i = 0, len = code.length; i < len; ++i) {\n lookup[i] = code[i]\n revLookup[code.charCodeAt(i)] = i\n}\n\n// Support decoding URL-safe base64 strings, as Node.js does.\n// See: https://en.wikipedia.org/wiki/Base64#URL_applications\nrevLookup['-'.charCodeAt(0)] = 62\nrevLookup['_'.charCodeAt(0)] = 63\n\nfunction getLens (b64) {\n var len = b64.length\n\n if (len % 4 > 0) {\n throw new Error('Invalid string. Length must be a multiple of 4')\n }\n\n // Trim off extra bytes after placeholder bytes are found\n // See: https://github.com/beatgammit/base64-js/issues/42\n var validLen = b64.indexOf('=')\n if (validLen === -1) validLen = len\n\n var placeHoldersLen = validLen === len\n ? 0\n : 4 - (validLen % 4)\n\n return [validLen, placeHoldersLen]\n}\n\n// base64 is 4/3 + up to two characters of the original data\nfunction byteLength (b64) {\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction _byteLength (b64, validLen, placeHoldersLen) {\n return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen\n}\n\nfunction toByteArray (b64) {\n var tmp\n var lens = getLens(b64)\n var validLen = lens[0]\n var placeHoldersLen = lens[1]\n\n var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))\n\n var curByte = 0\n\n // if there are placeholders, only get up to the last complete 4 chars\n var len = placeHoldersLen > 0\n ? validLen - 4\n : validLen\n\n var i\n for (i = 0; i < len; i += 4) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 18) |\n (revLookup[b64.charCodeAt(i + 1)] << 12) |\n (revLookup[b64.charCodeAt(i + 2)] << 6) |\n revLookup[b64.charCodeAt(i + 3)]\n arr[curByte++] = (tmp >> 16) & 0xFF\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 2) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 2) |\n (revLookup[b64.charCodeAt(i + 1)] >> 4)\n arr[curByte++] = tmp & 0xFF\n }\n\n if (placeHoldersLen === 1) {\n tmp =\n (revLookup[b64.charCodeAt(i)] << 10) |\n (revLookup[b64.charCodeAt(i + 1)] << 4) |\n (revLookup[b64.charCodeAt(i + 2)] >> 2)\n arr[curByte++] = (tmp >> 8) & 0xFF\n arr[curByte++] = tmp & 0xFF\n }\n\n return arr\n}\n\nfunction tripletToBase64 (num) {\n return lookup[num >> 18 & 0x3F] +\n lookup[num >> 12 & 0x3F] +\n lookup[num >> 6 & 0x3F] +\n lookup[num & 0x3F]\n}\n\nfunction encodeChunk (uint8, start, end) {\n var tmp\n var output = []\n for (var i = start; i < end; i += 3) {\n tmp =\n ((uint8[i] << 16) & 0xFF0000) +\n ((uint8[i + 1] << 8) & 0xFF00) +\n (uint8[i + 2] & 0xFF)\n output.push(tripletToBase64(tmp))\n }\n return output.join('')\n}\n\nfunction fromByteArray (uint8) {\n var tmp\n var len = uint8.length\n var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes\n var parts = []\n var maxChunkLength = 16383 // must be multiple of 3\n\n // go through the array every three bytes, we'll deal with trailing stuff later\n for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {\n parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))\n }\n\n // pad the end with zeros, but make sure to not forget the extra bytes\n if (extraBytes === 1) {\n tmp = uint8[len - 1]\n parts.push(\n lookup[tmp >> 2] +\n lookup[(tmp << 4) & 0x3F] +\n '=='\n )\n } else if (extraBytes === 2) {\n tmp = (uint8[len - 2] << 8) + uint8[len - 1]\n parts.push(\n lookup[tmp >> 10] +\n lookup[(tmp >> 4) & 0x3F] +\n lookup[(tmp << 2) & 0x3F] +\n '='\n )\n }\n\n return parts.join('')\n}\n", "/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */\nexports.read = function (buffer, offset, isLE, mLen, nBytes) {\n var e, m\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var nBits = -7\n var i = isLE ? (nBytes - 1) : 0\n var d = isLE ? -1 : 1\n var s = buffer[offset + i]\n\n i += d\n\n e = s & ((1 << (-nBits)) - 1)\n s >>= (-nBits)\n nBits += eLen\n for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n m = e & ((1 << (-nBits)) - 1)\n e >>= (-nBits)\n nBits += mLen\n for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}\n\n if (e === 0) {\n e = 1 - eBias\n } else if (e === eMax) {\n return m ? NaN : ((s ? -1 : 1) * Infinity)\n } else {\n m = m + Math.pow(2, mLen)\n e = e - eBias\n }\n return (s ? -1 : 1) * m * Math.pow(2, e - mLen)\n}\n\nexports.write = function (buffer, value, offset, isLE, mLen, nBytes) {\n var e, m, c\n var eLen = (nBytes * 8) - mLen - 1\n var eMax = (1 << eLen) - 1\n var eBias = eMax >> 1\n var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)\n var i = isLE ? 0 : (nBytes - 1)\n var d = isLE ? 1 : -1\n var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0\n\n value = Math.abs(value)\n\n if (isNaN(value) || value === Infinity) {\n m = isNaN(value) ? 1 : 0\n e = eMax\n } else {\n e = Math.floor(Math.log(value) / Math.LN2)\n if (value * (c = Math.pow(2, -e)) < 1) {\n e--\n c *= 2\n }\n if (e + eBias >= 1) {\n value += rt / c\n } else {\n value += rt * Math.pow(2, 1 - eBias)\n }\n if (value * c >= 2) {\n e++\n c /= 2\n }\n\n if (e + eBias >= eMax) {\n m = 0\n e = eMax\n } else if (e + eBias >= 1) {\n m = ((value * c) - 1) * Math.pow(2, mLen)\n e = e + eBias\n } else {\n m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)\n e = 0\n }\n }\n\n for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}\n\n e = (e << mLen) | m\n eLen += mLen\n for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}\n\n buffer[offset + i - d] |= s * 128\n}\n", "/*!\n * The buffer module from node.js, for the browser.\n *\n * @author Feross Aboukhadijeh <https://feross.org>\n * @license MIT\n */\n/* eslint-disable no-proto */\n\n'use strict'\n\nconst base64 = require('base64-js')\nconst ieee754 = require('ieee754')\nconst customInspectSymbol =\n (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation\n ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation\n : null\n\nexports.Buffer = Buffer\nexports.SlowBuffer = SlowBuffer\nexports.INSPECT_MAX_BYTES = 50\n\nconst K_MAX_LENGTH = 0x7fffffff\nexports.kMaxLength = K_MAX_LENGTH\n\n/**\n * If `Buffer.TYPED_ARRAY_SUPPORT`:\n * === true Use Uint8Array implementation (fastest)\n * === false Print warning and recommend using `buffer` v4.x which has an Object\n * implementation (most compatible, even IE6)\n *\n * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,\n * Opera 11.6+, iOS 4.2+.\n *\n * We report that the browser does not support typed arrays if the are not subclassable\n * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`\n * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support\n * for __proto__ and has a buggy typed array implementation.\n */\nBuffer.TYPED_ARRAY_SUPPORT = typedArraySupport()\n\nif (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&\n typeof console.error === 'function') {\n console.error(\n 'This browser lacks typed array (Uint8Array) support which is required by ' +\n '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'\n )\n}\n\nfunction typedArraySupport () {\n // Can typed array instances can be augmented?\n try {\n const arr = new Uint8Array(1)\n const proto = { foo: function () { return 42 } }\n Object.setPrototypeOf(proto, Uint8Array.prototype)\n Object.setPrototypeOf(arr, proto)\n return arr.foo() === 42\n } catch (e) {\n return false\n }\n}\n\nObject.defineProperty(Buffer.prototype, 'parent', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.buffer\n }\n})\n\nObject.defineProperty(Buffer.prototype, 'offset', {\n enumerable: true,\n get: function () {\n if (!Buffer.isBuffer(this)) return undefined\n return this.byteOffset\n }\n})\n\nfunction createBuffer (length) {\n if (length > K_MAX_LENGTH) {\n throw new RangeError('The value \"' + length + '\" is invalid for option \"size\"')\n }\n // Return an augmented `Uint8Array` instance\n const buf = new Uint8Array(length)\n Object.setPrototypeOf(buf, Buffer.prototype)\n return buf\n}\n\n/**\n * The Buffer constructor returns instances of `Uint8Array` that have their\n * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of\n * `Uint8Array`, so the returned instances will have all the node `Buffer` methods\n * and the `Uint8Array` methods. Square bracket notation works as expected -- it\n * returns a single octet.\n *\n * The `Uint8Array` prototype remains unmodified.\n */\n\nfunction Buffer (arg, encodingOrOffset, length) {\n // Common case.\n if (typeof arg === 'number') {\n if (typeof encodingOrOffset === 'string') {\n throw new TypeError(\n 'The \"string\" argument must be of type string. Received type number'\n )\n }\n return allocUnsafe(arg)\n }\n return from(arg, encodingOrOffset, length)\n}\n\nBuffer.poolSize = 8192 // not used by this implementation\n\nfunction from (value, encodingOrOffset, length) {\n if (typeof value === 'string') {\n return fromString(value, encodingOrOffset)\n }\n\n if (ArrayBuffer.isView(value)) {\n return fromArrayView(value)\n }\n\n if (value == null) {\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n }\n\n if (isInstance(value, ArrayBuffer) ||\n (value && isInstance(value.buffer, ArrayBuffer))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof SharedArrayBuffer !== 'undefined' &&\n (isInstance(value, SharedArrayBuffer) ||\n (value && isInstance(value.buffer, SharedArrayBuffer)))) {\n return fromArrayBuffer(value, encodingOrOffset, length)\n }\n\n if (typeof value === 'number') {\n throw new TypeError(\n 'The \"value\" argument must not be of type number. Received type number'\n )\n }\n\n const valueOf = value.valueOf && value.valueOf()\n if (valueOf != null && valueOf !== value) {\n return Buffer.from(valueOf, encodingOrOffset, length)\n }\n\n const b = fromObject(value)\n if (b) return b\n\n if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&\n typeof value[Symbol.toPrimitive] === 'function') {\n return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length)\n }\n\n throw new TypeError(\n 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +\n 'or Array-like Object. Received type ' + (typeof value)\n )\n}\n\n/**\n * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError\n * if value is a number.\n * Buffer.from(str[, encoding])\n * Buffer.from(array)\n * Buffer.from(buffer)\n * Buffer.from(arrayBuffer[, byteOffset[, length]])\n **/\nBuffer.from = function (value, encodingOrOffset, length) {\n return from(value, encodingOrOffset, length)\n}\n\n// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:\n// https://github.com/feross/buffer/pull/148\nObject.setPrototypeOf(Buffer.prototype, Uint8Array.prototype)\nObject.setPrototypeOf(Buffer, Uint8Array)\n\nfunction assertSize (size) {\n if (typeof size !== 'number') {\n throw new TypeError('\"size\" argument must be of type number')\n } else if (size < 0) {\n throw new RangeError('The value \"' + size + '\" is invalid for option \"size\"')\n }\n}\n\nfunction alloc (size, fill, encoding) {\n assertSize(size)\n if (size <= 0) {\n return createBuffer(size)\n }\n if (fill !== undefined) {\n // Only pay attention to encoding if it's a string. This\n // prevents accidentally sending in a number that would\n // be interpreted as a start offset.\n return typeof encoding === 'string'\n ? createBuffer(size).fill(fill, encoding)\n : createBuffer(size).fill(fill)\n }\n return createBuffer(size)\n}\n\n/**\n * Creates a new filled Buffer instance.\n * alloc(size[, fill[, encoding]])\n **/\nBuffer.alloc = function (size, fill, encoding) {\n return alloc(size, fill, encoding)\n}\n\nfunction allocUnsafe (size) {\n assertSize(size)\n return createBuffer(size < 0 ? 0 : checked(size) | 0)\n}\n\n/**\n * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.\n * */\nBuffer.allocUnsafe = function (size) {\n return allocUnsafe(size)\n}\n/**\n * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.\n */\nBuffer.allocUnsafeSlow = function (size) {\n return allocUnsafe(size)\n}\n\nfunction fromString (string, encoding) {\n if (typeof encoding !== 'string' || encoding === '') {\n encoding = 'utf8'\n }\n\n if (!Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n\n const length = byteLength(string, encoding) | 0\n let buf = createBuffer(length)\n\n const actual = buf.write(string, encoding)\n\n if (actual !== length) {\n // Writing a hex string, for example, that contains invalid characters will\n // cause everything after the first invalid character to be ignored. (e.g.\n // 'abxxcd' will be treated as 'ab')\n buf = buf.slice(0, actual)\n }\n\n return buf\n}\n\nfunction fromArrayLike (array) {\n const length = array.length < 0 ? 0 : checked(array.length) | 0\n const buf = createBuffer(length)\n for (let i = 0; i < length; i += 1) {\n buf[i] = array[i] & 255\n }\n return buf\n}\n\nfunction fromArrayView (arrayView) {\n if (isInstance(arrayView, Uint8Array)) {\n const copy = new Uint8Array(arrayView)\n return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength)\n }\n return fromArrayLike(arrayView)\n}\n\nfunction fromArrayBuffer (array, byteOffset, length) {\n if (byteOffset < 0 || array.byteLength < byteOffset) {\n throw new RangeError('\"offset\" is outside of buffer bounds')\n }\n\n if (array.byteLength < byteOffset + (length || 0)) {\n throw new RangeError('\"length\" is outside of buffer bounds')\n }\n\n let buf\n if (byteOffset === undefined && length === undefined) {\n buf = new Uint8Array(array)\n } else if (length === undefined) {\n buf = new Uint8Array(array, byteOffset)\n } else {\n buf = new Uint8Array(array, byteOffset, length)\n }\n\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(buf, Buffer.prototype)\n\n return buf\n}\n\nfunction fromObject (obj) {\n if (Buffer.isBuffer(obj)) {\n const len = checked(obj.length) | 0\n const buf = createBuffer(len)\n\n if (buf.length === 0) {\n return buf\n }\n\n obj.copy(buf, 0, 0, len)\n return buf\n }\n\n if (obj.length !== undefined) {\n if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {\n return createBuffer(0)\n }\n return fromArrayLike(obj)\n }\n\n if (obj.type === 'Buffer' && Array.isArray(obj.data)) {\n return fromArrayLike(obj.data)\n }\n}\n\nfunction checked (length) {\n // Note: cannot use `length < K_MAX_LENGTH` here because that fails when\n // length is NaN (which is otherwise coerced to zero.)\n if (length >= K_MAX_LENGTH) {\n throw new RangeError('Attempt to allocate Buffer larger than maximum ' +\n 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')\n }\n return length | 0\n}\n\nfunction SlowBuffer (length) {\n if (+length != length) { // eslint-disable-line eqeqeq\n length = 0\n }\n return Buffer.alloc(+length)\n}\n\nBuffer.isBuffer = function isBuffer (b) {\n return b != null && b._isBuffer === true &&\n b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false\n}\n\nBuffer.compare = function compare (a, b) {\n if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)\n if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)\n if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {\n throw new TypeError(\n 'The \"buf1\", \"buf2\" arguments must be one of type Buffer or Uint8Array'\n )\n }\n\n if (a === b) return 0\n\n let x = a.length\n let y = b.length\n\n for (let i = 0, len = Math.min(x, y); i < len; ++i) {\n if (a[i] !== b[i]) {\n x = a[i]\n y = b[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\nBuffer.isEncoding = function isEncoding (encoding) {\n switch (String(encoding).toLowerCase()) {\n case 'hex':\n case 'utf8':\n case 'utf-8':\n case 'ascii':\n case 'latin1':\n case 'binary':\n case 'base64':\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return true\n default:\n return false\n }\n}\n\nBuffer.concat = function concat (list, length) {\n if (!Array.isArray(list)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n }\n\n if (list.length === 0) {\n return Buffer.alloc(0)\n }\n\n let i\n if (length === undefined) {\n length = 0\n for (i = 0; i < list.length; ++i) {\n length += list[i].length\n }\n }\n\n const buffer = Buffer.allocUnsafe(length)\n let pos = 0\n for (i = 0; i < list.length; ++i) {\n let buf = list[i]\n if (isInstance(buf, Uint8Array)) {\n if (pos + buf.length > buffer.length) {\n if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)\n buf.copy(buffer, pos)\n } else {\n Uint8Array.prototype.set.call(\n buffer,\n buf,\n pos\n )\n }\n } else if (!Buffer.isBuffer(buf)) {\n throw new TypeError('\"list\" argument must be an Array of Buffers')\n } else {\n buf.copy(buffer, pos)\n }\n pos += buf.length\n }\n return buffer\n}\n\nfunction byteLength (string, encoding) {\n if (Buffer.isBuffer(string)) {\n return string.length\n }\n if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {\n return string.byteLength\n }\n if (typeof string !== 'string') {\n throw new TypeError(\n 'The \"string\" argument must be one of type string, Buffer, or ArrayBuffer. ' +\n 'Received type ' + typeof string\n )\n }\n\n const len = string.length\n const mustMatch = (arguments.length > 2 && arguments[2] === true)\n if (!mustMatch && len === 0) return 0\n\n // Use a for loop to avoid recursion\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'ascii':\n case 'latin1':\n case 'binary':\n return len\n case 'utf8':\n case 'utf-8':\n return utf8ToBytes(string).length\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return len * 2\n case 'hex':\n return len >>> 1\n case 'base64':\n return base64ToBytes(string).length\n default:\n if (loweredCase) {\n return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8\n }\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\nBuffer.byteLength = byteLength\n\nfunction slowToString (encoding, start, end) {\n let loweredCase = false\n\n // No need to verify that \"this.length <= MAX_UINT32\" since it's a read-only\n // property of a typed array.\n\n // This behaves neither like String nor Uint8Array in that we set start/end\n // to their upper/lower bounds if the value passed is out of range.\n // undefined is handled specially as per ECMA-262 6th Edition,\n // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.\n if (start === undefined || start < 0) {\n start = 0\n }\n // Return early if start > this.length. Done here to prevent potential uint32\n // coercion fail below.\n if (start > this.length) {\n return ''\n }\n\n if (end === undefined || end > this.length) {\n end = this.length\n }\n\n if (end <= 0) {\n return ''\n }\n\n // Force coercion to uint32. This will also coerce falsey/NaN values to 0.\n end >>>= 0\n start >>>= 0\n\n if (end <= start) {\n return ''\n }\n\n if (!encoding) encoding = 'utf8'\n\n while (true) {\n switch (encoding) {\n case 'hex':\n return hexSlice(this, start, end)\n\n case 'utf8':\n case 'utf-8':\n return utf8Slice(this, start, end)\n\n case 'ascii':\n return asciiSlice(this, start, end)\n\n case 'latin1':\n case 'binary':\n return latin1Slice(this, start, end)\n\n case 'base64':\n return base64Slice(this, start, end)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return utf16leSlice(this, start, end)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = (encoding + '').toLowerCase()\n loweredCase = true\n }\n }\n}\n\n// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)\n// to detect a Buffer instance. It's not possible to use `instanceof Buffer`\n// reliably in a browserify context because there could be multiple different\n// copies of the 'buffer' package in use. This method works even for Buffer\n// instances that were created from another copy of the `buffer` package.\n// See: https://github.com/feross/buffer/issues/154\nBuffer.prototype._isBuffer = true\n\nfunction swap (b, n, m) {\n const i = b[n]\n b[n] = b[m]\n b[m] = i\n}\n\nBuffer.prototype.swap16 = function swap16 () {\n const len = this.length\n if (len % 2 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 16-bits')\n }\n for (let i = 0; i < len; i += 2) {\n swap(this, i, i + 1)\n }\n return this\n}\n\nBuffer.prototype.swap32 = function swap32 () {\n const len = this.length\n if (len % 4 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 32-bits')\n }\n for (let i = 0; i < len; i += 4) {\n swap(this, i, i + 3)\n swap(this, i + 1, i + 2)\n }\n return this\n}\n\nBuffer.prototype.swap64 = function swap64 () {\n const len = this.length\n if (len % 8 !== 0) {\n throw new RangeError('Buffer size must be a multiple of 64-bits')\n }\n for (let i = 0; i < len; i += 8) {\n swap(this, i, i + 7)\n swap(this, i + 1, i + 6)\n swap(this, i + 2, i + 5)\n swap(this, i + 3, i + 4)\n }\n return this\n}\n\nBuffer.prototype.toString = function toString () {\n const length = this.length\n if (length === 0) return ''\n if (arguments.length === 0) return utf8Slice(this, 0, length)\n return slowToString.apply(this, arguments)\n}\n\nBuffer.prototype.toLocaleString = Buffer.prototype.toString\n\nBuffer.prototype.equals = function equals (b) {\n if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')\n if (this === b) return true\n return Buffer.compare(this, b) === 0\n}\n\nBuffer.prototype.inspect = function inspect () {\n let str = ''\n const max = exports.INSPECT_MAX_BYTES\n str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()\n if (this.length > max) str += ' ... '\n return '<Buffer ' + str + '>'\n}\nif (customInspectSymbol) {\n Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect\n}\n\nBuffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {\n if (isInstance(target, Uint8Array)) {\n target = Buffer.from(target, target.offset, target.byteLength)\n }\n if (!Buffer.isBuffer(target)) {\n throw new TypeError(\n 'The \"target\" argument must be one of type Buffer or Uint8Array. ' +\n 'Received type ' + (typeof target)\n )\n }\n\n if (start === undefined) {\n start = 0\n }\n if (end === undefined) {\n end = target ? target.length : 0\n }\n if (thisStart === undefined) {\n thisStart = 0\n }\n if (thisEnd === undefined) {\n thisEnd = this.length\n }\n\n if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {\n throw new RangeError('out of range index')\n }\n\n if (thisStart >= thisEnd && start >= end) {\n return 0\n }\n if (thisStart >= thisEnd) {\n return -1\n }\n if (start >= end) {\n return 1\n }\n\n start >>>= 0\n end >>>= 0\n thisStart >>>= 0\n thisEnd >>>= 0\n\n if (this === target) return 0\n\n let x = thisEnd - thisStart\n let y = end - start\n const len = Math.min(x, y)\n\n const thisCopy = this.slice(thisStart, thisEnd)\n const targetCopy = target.slice(start, end)\n\n for (let i = 0; i < len; ++i) {\n if (thisCopy[i] !== targetCopy[i]) {\n x = thisCopy[i]\n y = targetCopy[i]\n break\n }\n }\n\n if (x < y) return -1\n if (y < x) return 1\n return 0\n}\n\n// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,\n// OR the last index of `val` in `buffer` at offset <= `byteOffset`.\n//\n// Arguments:\n// - buffer - a Buffer to search\n// - val - a string, Buffer, or number\n// - byteOffset - an index into `buffer`; will be clamped to an int32\n// - encoding - an optional encoding, relevant is val is a string\n// - dir - true for indexOf, false for lastIndexOf\nfunction bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {\n // Empty buffer means no match\n if (buffer.length === 0) return -1\n\n // Normalize byteOffset\n if (typeof byteOffset === 'string') {\n encoding = byteOffset\n byteOffset = 0\n } else if (byteOffset > 0x7fffffff) {\n byteOffset = 0x7fffffff\n } else if (byteOffset < -0x80000000) {\n byteOffset = -0x80000000\n }\n byteOffset = +byteOffset // Coerce to Number.\n if (numberIsNaN(byteOffset)) {\n // byteOffset: it it's undefined, null, NaN, \"foo\", etc, search whole buffer\n byteOffset = dir ? 0 : (buffer.length - 1)\n }\n\n // Normalize byteOffset: negative offsets start from the end of the buffer\n if (byteOffset < 0) byteOffset = buffer.length + byteOffset\n if (byteOffset >= buffer.length) {\n if (dir) return -1\n else byteOffset = buffer.length - 1\n } else if (byteOffset < 0) {\n if (dir) byteOffset = 0\n else return -1\n }\n\n // Normalize val\n if (typeof val === 'string') {\n val = Buffer.from(val, encoding)\n }\n\n // Finally, search either indexOf (if dir is true) or lastIndexOf\n if (Buffer.isBuffer(val)) {\n // Special case: looking for empty string/buffer always fails\n if (val.length === 0) {\n return -1\n }\n return arrayIndexOf(buffer, val, byteOffset, encoding, dir)\n } else if (typeof val === 'number') {\n val = val & 0xFF // Search for a byte value [0-255]\n if (typeof Uint8Array.prototype.indexOf === 'function') {\n if (dir) {\n return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)\n } else {\n return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)\n }\n }\n return arrayIndexOf(buffer, [val], byteOffset, encoding, dir)\n }\n\n throw new TypeError('val must be string, number or Buffer')\n}\n\nfunction arrayIndexOf (arr, val, byteOffset, encoding, dir) {\n let indexSize = 1\n let arrLength = arr.length\n let valLength = val.length\n\n if (encoding !== undefined) {\n encoding = String(encoding).toLowerCase()\n if (encoding === 'ucs2' || encoding === 'ucs-2' ||\n encoding === 'utf16le' || encoding === 'utf-16le') {\n if (arr.length < 2 || val.length < 2) {\n return -1\n }\n indexSize = 2\n arrLength /= 2\n valLength /= 2\n byteOffset /= 2\n }\n }\n\n function read (buf, i) {\n if (indexSize === 1) {\n return buf[i]\n } else {\n return buf.readUInt16BE(i * indexSize)\n }\n }\n\n let i\n if (dir) {\n let foundIndex = -1\n for (i = byteOffset; i < arrLength; i++) {\n if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {\n if (foundIndex === -1) foundIndex = i\n if (i - foundIndex + 1 === valLength) return foundIndex * indexSize\n } else {\n if (foundIndex !== -1) i -= i - foundIndex\n foundIndex = -1\n }\n }\n } else {\n if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength\n for (i = byteOffset; i >= 0; i--) {\n let found = true\n for (let j = 0; j < valLength; j++) {\n if (read(arr, i + j) !== read(val, j)) {\n found = false\n break\n }\n }\n if (found) return i\n }\n }\n\n return -1\n}\n\nBuffer.prototype.includes = function includes (val, byteOffset, encoding) {\n return this.indexOf(val, byteOffset, encoding) !== -1\n}\n\nBuffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, true)\n}\n\nBuffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {\n return bidirectionalIndexOf(this, val, byteOffset, encoding, false)\n}\n\nfunction hexWrite (buf, string, offset, length) {\n offset = Number(offset) || 0\n const remaining = buf.length - offset\n if (!length) {\n length = remaining\n } else {\n length = Number(length)\n if (length > remaining) {\n length = remaining\n }\n }\n\n const strLen = string.length\n\n if (length > strLen / 2) {\n length = strLen / 2\n }\n let i\n for (i = 0; i < length; ++i) {\n const parsed = parseInt(string.substr(i * 2, 2), 16)\n if (numberIsNaN(parsed)) return i\n buf[offset + i] = parsed\n }\n return i\n}\n\nfunction utf8Write (buf, string, offset, length) {\n return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nfunction asciiWrite (buf, string, offset, length) {\n return blitBuffer(asciiToBytes(string), buf, offset, length)\n}\n\nfunction base64Write (buf, string, offset, length) {\n return blitBuffer(base64ToBytes(string), buf, offset, length)\n}\n\nfunction ucs2Write (buf, string, offset, length) {\n return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)\n}\n\nBuffer.prototype.write = function write (string, offset, length, encoding) {\n // Buffer#write(string)\n if (offset === undefined) {\n encoding = 'utf8'\n length = this.length\n offset = 0\n // Buffer#write(string, encoding)\n } else if (length === undefined && typeof offset === 'string') {\n encoding = offset\n length = this.length\n offset = 0\n // Buffer#write(string, offset[, length][, encoding])\n } else if (isFinite(offset)) {\n offset = offset >>> 0\n if (isFinite(length)) {\n length = length >>> 0\n if (encoding === undefined) encoding = 'utf8'\n } else {\n encoding = length\n length = undefined\n }\n } else {\n throw new Error(\n 'Buffer.write(string, encoding, offset[, length]) is no longer supported'\n )\n }\n\n const remaining = this.length - offset\n if (length === undefined || length > remaining) length = remaining\n\n if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {\n throw new RangeError('Attempt to write outside buffer bounds')\n }\n\n if (!encoding) encoding = 'utf8'\n\n let loweredCase = false\n for (;;) {\n switch (encoding) {\n case 'hex':\n return hexWrite(this, string, offset, length)\n\n case 'utf8':\n case 'utf-8':\n return utf8Write(this, string, offset, length)\n\n case 'ascii':\n case 'latin1':\n case 'binary':\n return asciiWrite(this, string, offset, length)\n\n case 'base64':\n // Warning: maxLength not taken into account in base64Write\n return base64Write(this, string, offset, length)\n\n case 'ucs2':\n case 'ucs-2':\n case 'utf16le':\n case 'utf-16le':\n return ucs2Write(this, string, offset, length)\n\n default:\n if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)\n encoding = ('' + encoding).toLowerCase()\n loweredCase = true\n }\n }\n}\n\nBuffer.prototype.toJSON = function toJSON () {\n return {\n type: 'Buffer',\n data: Array.prototype.slice.call(this._arr || this, 0)\n }\n}\n\nfunction base64Slice (buf, start, end) {\n if (start === 0 && end === buf.length) {\n return base64.fromByteArray(buf)\n } else {\n return base64.fromByteArray(buf.slice(start, end))\n }\n}\n\nfunction utf8Slice (buf, start, end) {\n end = Math.min(buf.length, end)\n const res = []\n\n let i = start\n while (i < end) {\n const firstByte = buf[i]\n let codePoint = null\n let bytesPerSequence = (firstByte > 0xEF)\n ? 4\n : (firstByte > 0xDF)\n ? 3\n : (firstByte > 0xBF)\n ? 2\n : 1\n\n if (i + bytesPerSequence <= end) {\n let secondByte, thirdByte, fourthByte, tempCodePoint\n\n switch (bytesPerSequence) {\n case 1:\n if (firstByte < 0x80) {\n codePoint = firstByte\n }\n break\n case 2:\n secondByte = buf[i + 1]\n if ((secondByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)\n if (tempCodePoint > 0x7F) {\n codePoint = tempCodePoint\n }\n }\n break\n case 3:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)\n if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {\n codePoint = tempCodePoint\n }\n }\n break\n case 4:\n secondByte = buf[i + 1]\n thirdByte = buf[i + 2]\n fourthByte = buf[i + 3]\n if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {\n tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)\n if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {\n codePoint = tempCodePoint\n }\n }\n }\n }\n\n if (codePoint === null) {\n // we did not generate a valid codePoint so insert a\n // replacement char (U+FFFD) and advance only 1 byte\n codePoint = 0xFFFD\n bytesPerSequence = 1\n } else if (codePoint > 0xFFFF) {\n // encode to utf16 (surrogate pair dance)\n codePoint -= 0x10000\n res.push(codePoint >>> 10 & 0x3FF | 0xD800)\n codePoint = 0xDC00 | codePoint & 0x3FF\n }\n\n res.push(codePoint)\n i += bytesPerSequence\n }\n\n return decodeCodePointsArray(res)\n}\n\n// Based on http://stackoverflow.com/a/22747272/680742, the browser with\n// the lowest limit is Chrome, with 0x10000 args.\n// We go 1 magnitude less, for safety\nconst MAX_ARGUMENTS_LENGTH = 0x1000\n\nfunction 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\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\nfunction asciiSlice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i] & 0x7F)\n }\n return ret\n}\n\nfunction latin1Slice (buf, start, end) {\n let ret = ''\n end = Math.min(buf.length, end)\n\n for (let i = start; i < end; ++i) {\n ret += String.fromCharCode(buf[i])\n }\n return ret\n}\n\nfunction hexSlice (buf, start, end) {\n const len = buf.length\n\n if (!start || start < 0) start = 0\n if (!end || end < 0 || end > len) end = len\n\n let out = ''\n for (let i = start; i < end; ++i) {\n out += hexSliceLookupTable[buf[i]]\n }\n return out\n}\n\nfunction utf16leSlice (buf, start, end) {\n const bytes = buf.slice(start, end)\n let res = ''\n // If bytes.length is odd, the last 8 bits must be ignored (same as node.js)\n for (let i = 0; i < bytes.length - 1; i += 2) {\n res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))\n }\n return res\n}\n\nBuffer.prototype.slice = function slice (start, end) {\n const len = this.length\n start = ~~start\n end = end === undefined ? len : ~~end\n\n if (start < 0) {\n start += len\n if (start < 0) start = 0\n } else if (start > len) {\n start = len\n }\n\n if (end < 0) {\n end += len\n if (end < 0) end = 0\n } else if (end > len) {\n end = len\n }\n\n if (end < start) end = start\n\n const newBuf = this.subarray(start, end)\n // Return an augmented `Uint8Array` instance\n Object.setPrototypeOf(newBuf, Buffer.prototype)\n\n return newBuf\n}\n\n/*\n * Need to make sure that buffer isn't trying to write out of bounds.\n */\nfunction checkOffset (offset, ext, length) {\n if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')\n if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')\n}\n\nBuffer.prototype.readUintLE =\nBuffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUintBE =\nBuffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n checkOffset(offset, byteLength, this.length)\n }\n\n let val = this[offset + --byteLength]\n let mul = 1\n while (byteLength > 0 && (mul *= 0x100)) {\n val += this[offset + --byteLength] * mul\n }\n\n return val\n}\n\nBuffer.prototype.readUint8 =\nBuffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n return this[offset]\n}\n\nBuffer.prototype.readUint16LE =\nBuffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return this[offset] | (this[offset + 1] << 8)\n}\n\nBuffer.prototype.readUint16BE =\nBuffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n return (this[offset] << 8) | this[offset + 1]\n}\n\nBuffer.prototype.readUint32LE =\nBuffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return ((this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16)) +\n (this[offset + 3] * 0x1000000)\n}\n\nBuffer.prototype.readUint32BE =\nBuffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] * 0x1000000) +\n ((this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n this[offset + 3])\n}\n\nBuffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const lo = first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24\n\n const hi = this[++offset] +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n last * 2 ** 24\n\n return BigInt(lo) + (BigInt(hi) << BigInt(32))\n})\n\nBuffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const hi = first * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n const lo = this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last\n\n return (BigInt(hi) << BigInt(32)) + BigInt(lo)\n})\n\nBuffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let val = this[offset]\n let mul = 1\n let i = 0\n while (++i < byteLength && (mul *= 0x100)) {\n val += this[offset + i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) checkOffset(offset, byteLength, this.length)\n\n let i = byteLength\n let mul = 1\n let val = this[offset + --i]\n while (i > 0 && (mul *= 0x100)) {\n val += this[offset + --i] * mul\n }\n mul *= 0x80\n\n if (val >= mul) val -= Math.pow(2, 8 * byteLength)\n\n return val\n}\n\nBuffer.prototype.readInt8 = function readInt8 (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 1, this.length)\n if (!(this[offset] & 0x80)) return (this[offset])\n return ((0xff - this[offset] + 1) * -1)\n}\n\nBuffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset] | (this[offset + 1] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 2, this.length)\n const val = this[offset + 1] | (this[offset] << 8)\n return (val & 0x8000) ? val | 0xFFFF0000 : val\n}\n\nBuffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset]) |\n (this[offset + 1] << 8) |\n (this[offset + 2] << 16) |\n (this[offset + 3] << 24)\n}\n\nBuffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n\n return (this[offset] << 24) |\n (this[offset + 1] << 16) |\n (this[offset + 2] << 8) |\n (this[offset + 3])\n}\n\nBuffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = this[offset + 4] +\n this[offset + 5] * 2 ** 8 +\n this[offset + 6] * 2 ** 16 +\n (last << 24) // Overflow\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(first +\n this[++offset] * 2 ** 8 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 24)\n})\n\nBuffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) {\n offset = offset >>> 0\n validateNumber(offset, 'offset')\n const first = this[offset]\n const last = this[offset + 7]\n if (first === undefined || last === undefined) {\n boundsError(offset, this.length - 8)\n }\n\n const val = (first << 24) + // Overflow\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n this[++offset]\n\n return (BigInt(val) << BigInt(32)) +\n BigInt(this[++offset] * 2 ** 24 +\n this[++offset] * 2 ** 16 +\n this[++offset] * 2 ** 8 +\n last)\n})\n\nBuffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, true, 23, 4)\n}\n\nBuffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 4, this.length)\n return ieee754.read(this, offset, false, 23, 4)\n}\n\nBuffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, true, 52, 8)\n}\n\nBuffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {\n offset = offset >>> 0\n if (!noAssert) checkOffset(offset, 8, this.length)\n return ieee754.read(this, offset, false, 52, 8)\n}\n\nfunction checkInt (buf, value, offset, ext, max, min) {\n if (!Buffer.isBuffer(buf)) throw new TypeError('\"buffer\" argument must be a Buffer instance')\n if (value > max || value < min) throw new RangeError('\"value\" argument is out of bounds')\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n}\n\nBuffer.prototype.writeUintLE =\nBuffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let mul = 1\n let i = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUintBE =\nBuffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n byteLength = byteLength >>> 0\n if (!noAssert) {\n const maxBytes = Math.pow(2, 8 * byteLength) - 1\n checkInt(this, value, offset, byteLength, maxBytes, 0)\n }\n\n let i = byteLength - 1\n let mul = 1\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n this[offset + i] = (value / mul) & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeUint8 =\nBuffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeUint16LE =\nBuffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeUint16BE =\nBuffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeUint32LE =\nBuffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset + 3] = (value >>> 24)\n this[offset + 2] = (value >>> 16)\n this[offset + 1] = (value >>> 8)\n this[offset] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeUint32BE =\nBuffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nfunction wrtBigUInt64LE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n lo = lo >> 8\n buf[offset++] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n hi = hi >> 8\n buf[offset++] = hi\n return offset\n}\n\nfunction wrtBigUInt64BE (buf, value, offset, min, max) {\n checkIntBI(value, min, max, buf, offset, 7)\n\n let lo = Number(value & BigInt(0xffffffff))\n buf[offset + 7] = lo\n lo = lo >> 8\n buf[offset + 6] = lo\n lo = lo >> 8\n buf[offset + 5] = lo\n lo = lo >> 8\n buf[offset + 4] = lo\n let hi = Number(value >> BigInt(32) & BigInt(0xffffffff))\n buf[offset + 3] = hi\n hi = hi >> 8\n buf[offset + 2] = hi\n hi = hi >> 8\n buf[offset + 1] = hi\n hi = hi >> 8\n buf[offset] = hi\n return offset + 8\n}\n\nBuffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff'))\n})\n\nBuffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = 0\n let mul = 1\n let sub = 0\n this[offset] = value & 0xFF\n while (++i < byteLength && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n const limit = Math.pow(2, (8 * byteLength) - 1)\n\n checkInt(this, value, offset, byteLength, limit - 1, -limit)\n }\n\n let i = byteLength - 1\n let mul = 1\n let sub = 0\n this[offset + i] = value & 0xFF\n while (--i >= 0 && (mul *= 0x100)) {\n if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {\n sub = 1\n }\n this[offset + i] = ((value / mul) >> 0) - sub & 0xFF\n }\n\n return offset + byteLength\n}\n\nBuffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)\n if (value < 0) value = 0xff + value + 1\n this[offset] = (value & 0xff)\n return offset + 1\n}\n\nBuffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n return offset + 2\n}\n\nBuffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)\n this[offset] = (value >>> 8)\n this[offset + 1] = (value & 0xff)\n return offset + 2\n}\n\nBuffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n this[offset] = (value & 0xff)\n this[offset + 1] = (value >>> 8)\n this[offset + 2] = (value >>> 16)\n this[offset + 3] = (value >>> 24)\n return offset + 4\n}\n\nBuffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)\n if (value < 0) value = 0xffffffff + value + 1\n this[offset] = (value >>> 24)\n this[offset + 1] = (value >>> 16)\n this[offset + 2] = (value >>> 8)\n this[offset + 3] = (value & 0xff)\n return offset + 4\n}\n\nBuffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) {\n return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nBuffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) {\n return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff'))\n})\n\nfunction checkIEEE754 (buf, value, offset, ext, max, min) {\n if (offset + ext > buf.length) throw new RangeError('Index out of range')\n if (offset < 0) throw new RangeError('Index out of range')\n}\n\nfunction writeFloat (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)\n }\n ieee754.write(buf, value, offset, littleEndian, 23, 4)\n return offset + 4\n}\n\nBuffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {\n return writeFloat(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {\n return writeFloat(this, value, offset, false, noAssert)\n}\n\nfunction writeDouble (buf, value, offset, littleEndian, noAssert) {\n value = +value\n offset = offset >>> 0\n if (!noAssert) {\n checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)\n }\n ieee754.write(buf, value, offset, littleEndian, 52, 8)\n return offset + 8\n}\n\nBuffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {\n return writeDouble(this, value, offset, true, noAssert)\n}\n\nBuffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {\n return writeDouble(this, value, offset, false, noAssert)\n}\n\n// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)\nBuffer.prototype.copy = function copy (target, targetStart, start, end) {\n if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')\n if (!start) start = 0\n if (!end && end !== 0) end = this.length\n if (targetStart >= target.length) targetStart = target.length\n if (!targetStart) targetStart = 0\n if (end > 0 && end < start) end = start\n\n // Copy 0 bytes; we're done\n if (end === start) return 0\n if (target.length === 0 || this.length === 0) return 0\n\n // Fatal error conditions\n if (targetStart < 0) {\n throw new RangeError('targetStart out of bounds')\n }\n if (start < 0 || start >= this.length) throw new RangeError('Index out of range')\n if (end < 0) throw new RangeError('sourceEnd out of bounds')\n\n // Are we oob?\n if (end > this.length) end = this.length\n if (target.length - targetStart < end - start) {\n end = target.length - targetStart + start\n }\n\n const len = end - start\n\n if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {\n // Use built-in when available, missing from IE11\n this.copyWithin(targetStart, start, end)\n } else {\n Uint8Array.prototype.set.call(\n target,\n this.subarray(start, end),\n targetStart\n )\n }\n\n return len\n}\n\n// Usage:\n// buffer.fill(number[, offset[, end]])\n// buffer.fill(buffer[, offset[, end]])\n// buffer.fill(string[, offset[, end]][, encoding])\nBuffer.prototype.fill = function fill (val, start, end, encoding) {\n // Handle string cases:\n if (typeof val === 'string') {\n if (typeof start === 'string') {\n encoding = start\n start = 0\n end = this.length\n } else if (typeof end === 'string') {\n encoding = end\n end = this.length\n }\n if (encoding !== undefined && typeof encoding !== 'string') {\n throw new TypeError('encoding must be a string')\n }\n if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {\n throw new TypeError('Unknown encoding: ' + encoding)\n }\n if (val.length === 1) {\n const code = val.charCodeAt(0)\n if ((encoding === 'utf8' && code < 128) ||\n encoding === 'latin1') {\n // Fast path: If `val` fits into a single byte, use that numeric value.\n val = code\n }\n }\n } else if (typeof val === 'number') {\n val = val & 255\n } else if (typeof val === 'boolean') {\n val = Number(val)\n }\n\n // Invalid ranges are not set to a default, so can range check early.\n if (start < 0 || this.length < start || this.length < end) {\n throw new RangeError('Out of range index')\n }\n\n if (end <= start) {\n return this\n }\n\n start = start >>> 0\n end = end === undefined ? this.length : end >>> 0\n\n if (!val) val = 0\n\n let i\n if (typeof val === 'number') {\n for (i = start; i < end; ++i) {\n this[i] = val\n }\n } else {\n const bytes = Buffer.isBuffer(val)\n ? val\n : Buffer.from(val, encoding)\n const len = bytes.length\n if (len === 0) {\n throw new TypeError('The value \"' + val +\n '\" is invalid for argument \"value\"')\n }\n for (i = 0; i < end - start; ++i) {\n this[i + start] = bytes[i % len]\n }\n }\n\n return this\n}\n\n// CUSTOM ERRORS\n// =============\n\n// Simplified versions from Node, changed for Buffer-only usage\nconst errors = {}\nfunction E (sym, getMessage, Base) {\n errors[sym] = class NodeError extends Base {\n constructor () {\n super()\n\n Object.defineProperty(this, 'message', {\n value: getMessage.apply(this, arguments),\n writable: true,\n configurable: true\n })\n\n // Add the error code to the name to include it in the stack trace.\n this.name = `${this.name} [${sym}]`\n // Access the stack to generate the error message including the error code\n // from the name.\n this.stack // eslint-disable-line no-unused-expressions\n // Reset the name to the actual name.\n delete this.name\n }\n\n get code () {\n return sym\n }\n\n set code (value) {\n Object.defineProperty(this, 'code', {\n configurable: true,\n enumerable: true,\n value,\n writable: true\n })\n }\n\n toString () {\n return `${this.name} [${sym}]: ${this.message}`\n }\n }\n}\n\nE('ERR_BUFFER_OUT_OF_BOUNDS',\n function (name) {\n if (name) {\n return `${name} is outside of buffer bounds`\n }\n\n return 'Attempt to access memory outside buffer bounds'\n }, RangeError)\nE('ERR_INVALID_ARG_TYPE',\n function (name, actual) {\n return `The \"${name}\" argument must be of type number. Received type ${typeof actual}`\n }, TypeError)\nE('ERR_OUT_OF_RANGE',\n function (str, range, input) {\n let msg = `The value of \"${str}\" is out of range.`\n let received = input\n if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) {\n received = addNumericalSeparator(String(input))\n } else if (typeof input === 'bigint') {\n received = String(input)\n if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) {\n received = addNumericalSeparator(received)\n }\n received += 'n'\n }\n msg += ` It must be ${range}. Received ${received}`\n return msg\n }, RangeError)\n\nfunction addNumericalSeparator (val) {\n let res = ''\n let i = val.length\n const start = val[0] === '-' ? 1 : 0\n for (; i >= start + 4; i -= 3) {\n res = `_${val.slice(i - 3, i)}${res}`\n }\n return `${val.slice(0, i)}${res}`\n}\n\n// CHECK FUNCTIONS\n// ===============\n\nfunction checkBounds (buf, offset, byteLength) {\n validateNumber(offset, 'offset')\n if (buf[offset] === undefined || buf[offset + byteLength] === undefined) {\n boundsError(offset, buf.length - (byteLength + 1))\n }\n}\n\nfunction checkIntBI (value, min, max, buf, offset, byteLength) {\n if (value > max || value < min) {\n const n = typeof min === 'bigint' ? 'n' : ''\n let range\n if (byteLength > 3) {\n if (min === 0 || min === BigInt(0)) {\n range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`\n } else {\n range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` +\n `${(byteLength + 1) * 8 - 1}${n}`\n }\n } else {\n range = `>= ${min}${n} and <= ${max}${n}`\n }\n throw new errors.ERR_OUT_OF_RANGE('value', range, value)\n }\n checkBounds(buf, offset, byteLength)\n}\n\nfunction validateNumber (value, name) {\n if (typeof value !== 'number') {\n throw new errors.ERR_INVALID_ARG_TYPE(name, 'number', value)\n }\n}\n\nfunction boundsError (value, length, type) {\n if (Math.floor(value) !== value) {\n validateNumber(value, type)\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset', 'an integer', value)\n }\n\n if (length < 0) {\n throw new errors.ERR_BUFFER_OUT_OF_BOUNDS()\n }\n\n throw new errors.ERR_OUT_OF_RANGE(type || 'offset',\n `>= ${type ? 1 : 0} and <= ${length}`,\n value)\n}\n\n// HELPER FUNCTIONS\n// ================\n\nconst INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g\n\nfunction base64clean (str) {\n // Node takes equal signs as end of the Base64 encoding\n str = str.split('=')[0]\n // Node strips out invalid characters like \\n and \\t from the string, base64-js does not\n str = str.trim().replace(INVALID_BASE64_RE, '')\n // Node converts strings with length < 2 to ''\n if (str.length < 2) return ''\n // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not\n while (str.length % 4 !== 0) {\n str = str + '='\n }\n return str\n}\n\nfunction utf8ToBytes (string, units) {\n units = units || Infinity\n let codePoint\n const length = string.length\n let leadSurrogate = null\n const bytes = []\n\n for (let i = 0; i < length; ++i) {\n codePoint = string.charCodeAt(i)\n\n // is surrogate component\n if (codePoint > 0xD7FF && codePoint < 0xE000) {\n // last char was a lead\n if (!leadSurrogate) {\n // no lead yet\n if (codePoint > 0xDBFF) {\n // unexpected trail\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n } else if (i + 1 === length) {\n // unpaired lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n continue\n }\n\n // valid lead\n leadSurrogate = codePoint\n\n continue\n }\n\n // 2 leads in a row\n if (codePoint < 0xDC00) {\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n leadSurrogate = codePoint\n continue\n }\n\n // valid surrogate pair\n codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000\n } else if (leadSurrogate) {\n // valid bmp char, but last char was a lead\n if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)\n }\n\n leadSurrogate = null\n\n // encode utf8\n if (codePoint < 0x80) {\n if ((units -= 1) < 0) break\n bytes.push(codePoint)\n } else if (codePoint < 0x800) {\n if ((units -= 2) < 0) break\n bytes.push(\n codePoint >> 0x6 | 0xC0,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x10000) {\n if ((units -= 3) < 0) break\n bytes.push(\n codePoint >> 0xC | 0xE0,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else if (codePoint < 0x110000) {\n if ((units -= 4) < 0) break\n bytes.push(\n codePoint >> 0x12 | 0xF0,\n codePoint >> 0xC & 0x3F | 0x80,\n codePoint >> 0x6 & 0x3F | 0x80,\n codePoint & 0x3F | 0x80\n )\n } else {\n throw new Error('Invalid code point')\n }\n }\n\n return bytes\n}\n\nfunction asciiToBytes (str) {\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n // Node's code seems to be doing this and not & 0x7F..\n byteArray.push(str.charCodeAt(i) & 0xFF)\n }\n return byteArray\n}\n\nfunction utf16leToBytes (str, units) {\n let c, hi, lo\n const byteArray = []\n for (let i = 0; i < str.length; ++i) {\n if ((units -= 2) < 0) break\n\n c = str.charCodeAt(i)\n hi = c >> 8\n lo = c % 256\n byteArray.push(lo)\n byteArray.push(hi)\n }\n\n return byteArray\n}\n\nfunction base64ToBytes (str) {\n return base64.toByteArray(base64clean(str))\n}\n\nfunction blitBuffer (src, dst, offset, length) {\n let i\n for (i = 0; i < length; ++i) {\n if ((i + offset >= dst.length) || (i >= src.length)) break\n dst[i + offset] = src[i]\n }\n return i\n}\n\n// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass\n// the `instanceof` check but they should be treated as of that type.\n// See: https://github.com/feross/buffer/issues/166\nfunction isInstance (obj, type) {\n return obj instanceof type ||\n (obj != null && obj.constructor != null && obj.constructor.name != null &&\n obj.constructor.name === type.name)\n}\nfunction numberIsNaN (obj) {\n // For IE11 support\n return obj !== obj // eslint-disable-line no-self-compare\n}\n\n// Create lookup table for `toString('hex')`\n// See: https://github.com/feross/buffer/issues/219\nconst hexSliceLookupTable = (function () {\n const alphabet = '0123456789abcdef'\n const table = new Array(256)\n for (let i = 0; i < 16; ++i) {\n const i16 = i * 16\n for (let j = 0; j < 16; ++j) {\n table[i16 + j] = alphabet[i] + alphabet[j]\n }\n }\n return table\n})()\n\n// Return not function with Error if BigInt not supported\nfunction defineBigIntMethod (fn) {\n return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn\n}\n\nfunction BufferBigIntNotDefined () {\n throw new Error('BigInt not supported')\n}\n", "/* eslint-disable @typescript-eslint/no-require-imports */\nconst polyfilledBuffer = require('buffer/').Buffer;\nconst { Buffer } = require('buffer');\n\n// monkeypatch writeBigUInt64BE in polyfill bc its borked\n// can remove this if/when this PR is merged: https://github.com/feross/buffer/pull/280\npolyfilledBuffer.prototype.writeBigUInt64BE = Buffer.prototype.writeBigUInt64BE;\nglobalThis.Buffer = polyfilledBuffer;\n", "// A simple TTL cache with max capacity option, ms resolution,\n// autopurge, and reasonably optimized performance\n// Relies on the fact that integer Object keys are kept sorted,\n// and managed very efficiently by V8.\n\n/* istanbul ignore next */\nconst perf =\n typeof performance === 'object' &&\n performance &&\n typeof performance.now === 'function'\n ? performance\n : Date\n\nconst now = () => perf.now()\nconst isPosInt = n => n && n === Math.floor(n) && n > 0 && isFinite(n)\nconst isPosIntOrInf = n => n === Infinity || isPosInt(n)\n\nclass TTLCache {\n constructor({\n max = Infinity,\n ttl,\n updateAgeOnGet = false,\n checkAgeOnGet = false,\n noUpdateTTL = false,\n dispose,\n noDisposeOnSet = false,\n } = {}) {\n // {[expirationTime]: [keys]}\n this.expirations = Object.create(null)\n // {key=>val}\n this.data = new Map()\n // {key=>expiration}\n this.expirationMap = new Map()\n if (ttl !== undefined && !isPosIntOrInf(ttl)) {\n throw new TypeError(\n 'ttl must be positive integer or Infinity if set'\n )\n }\n if (!isPosIntOrInf(max)) {\n throw new TypeError('max must be positive integer or Infinity')\n }\n this.ttl = ttl\n this.max = max\n this.updateAgeOnGet = !!updateAgeOnGet\n this.checkAgeOnGet = !!checkAgeOnGet\n this.noUpdateTTL = !!noUpdateTTL\n this.noDisposeOnSet = !!noDisposeOnSet\n if (dispose !== undefined) {\n if (typeof dispose !== 'function') {\n throw new TypeError('dispose must be function if set')\n }\n this.dispose = dispose\n }\n\n this.timer = undefined\n this.timerExpiration = undefined\n }\n\n setTimer(expiration, ttl) {\n if (this.timerExpiration < expiration) {\n return\n }\n\n if (this.timer) {\n clearTimeout(this.timer)\n }\n\n const t = setTimeout(() => {\n this.timer = undefined\n this.timerExpiration = undefined\n this.purgeStale()\n for (const exp in this.expirations) {\n this.setTimer(exp, exp - now())\n break\n }\n }, ttl)\n\n /* istanbul ignore else - affordance for non-node envs */\n if (t.unref) t.unref()\n\n this.timerExpiration = expiration\n this.timer = t\n }\n\n // hang onto the timer so we can clearTimeout if all items\n // are deleted. Deno doesn't have Timer.unref(), so it\n // hangs otherwise.\n cancelTimer() {\n if (this.timer) {\n clearTimeout(this.timer)\n this.timerExpiration = undefined\n this.timer = undefined\n }\n }\n\n /* istanbul ignore next */\n cancelTimers() {\n process.emitWarning(\n 'TTLCache.cancelTimers has been renamed to ' +\n 'TTLCache.cancelTimer (no \"s\"), and will be removed in the next ' +\n 'major version update'\n )\n return this.cancelTimer()\n }\n\n clear() {\n const entries =\n this.dispose !== TTLCache.prototype.dispose ? [...this] : []\n this.data.clear()\n this.expirationMap.clear()\n // no need for any purging now\n this.cancelTimer()\n this.expirations = Object.create(null)\n for (const [key, val] of entries) {\n this.dispose(val, key, 'delete')\n }\n }\n\n setTTL(key, ttl = this.ttl) {\n const current = this.expirationMap.get(key)\n if (current !== undefined) {\n // remove from the expirations list, so it isn't purged\n const exp = this.expirations[current]\n if (!exp || exp.length <= 1) {\n delete this.expirations[current]\n } else {\n this.expirations[current] = exp.filter(k => k !== key)\n }\n }\n\n if (ttl !== Infinity) {\n const expiration = Math.floor(now() + ttl)\n this.expirationMap.set(key, expiration)\n if (!this.expirations[expiration]) {\n this.expirations[expiration] = []\n this.setTimer(expiration, ttl)\n }\n this.expirations[expiration].push(key)\n } else {\n this.expirationMap.set(key, Infinity)\n }\n }\n\n set(\n key,\n val,\n {\n ttl = this.ttl,\n noUpdateTTL = this.noUpdateTTL,\n noDisposeOnSet = this.noDisposeOnSet,\n } = {}\n ) {\n if (!isPosIntOrInf(ttl)) {\n throw new TypeError('ttl must be positive integer or Infinity')\n }\n if (this.expirationMap.has(key)) {\n if (!noUpdateTTL) {\n this.setTTL(key, ttl)\n }\n // has old value\n const oldValue = this.data.get(key)\n if (oldValue !== val) {\n this.data.set(key, val)\n if (!noDisposeOnSet) {\n this.dispose(oldValue, key, 'set')\n }\n }\n } else {\n this.setTTL(key, ttl)\n this.data.set(key, val)\n }\n\n while (this.size > this.max) {\n this.purgeToCapacity()\n }\n\n return this\n }\n\n has(key) {\n return this.data.has(key)\n }\n\n getRemainingTTL(key) {\n const expiration = this.expirationMap.get(key)\n return expiration === Infinity\n ? expiration\n : expiration !== undefined\n ? Math.max(0, Math.ceil(expiration - now()))\n : 0\n }\n\n get(\n key,\n {\n updateAgeOnGet = this.updateAgeOnGet,\n ttl = this.ttl,\n checkAgeOnGet = this.checkAgeOnGet,\n } = {}\n ) {\n const val = this.data.get(key)\n if (checkAgeOnGet && this.getRemainingTTL(key) === 0) {\n this.delete(key)\n return undefined\n }\n if (updateAgeOnGet) {\n this.setTTL(key, ttl)\n }\n return val\n }\n\n dispose(_, __) {}\n\n delete(key) {\n const current = this.expirationMap.get(key)\n if (current !== undefined) {\n const value = this.data.get(key)\n this.data.delete(key)\n this.expirationMap.delete(key)\n const exp = this.expirations[current]\n if (exp) {\n if (exp.length <= 1) {\n delete this.expirations[current]\n } else {\n this.expirations[current] = exp.filter(k => k !== key)\n }\n }\n this.dispose(value, key, 'delete')\n if (this.size === 0) {\n this.cancelTimer()\n }\n return true\n }\n return false\n }\n\n purgeToCapacity() {\n for (const exp in this.expirations) {\n const keys = this.expirations[exp]\n if (this.size - keys.length >= this.max) {\n delete this.expirations[exp]\n const entries = []\n for (const key of keys) {\n entries.push([key, this.data.get(key)])\n this.data.delete(key)\n this.expirationMap.delete(key)\n }\n for (const [key, val] of entries) {\n this.dispose(val, key, 'evict')\n }\n } else {\n const s = this.size - this.max\n const entries = []\n for (const key of keys.splice(0, s)) {\n entries.push([key, this.data.get(key)])\n this.data.delete(key)\n this.expirationMap.delete(key)\n }\n for (const [key, val] of entries) {\n this.dispose(val, key, 'evict')\n }\n return\n }\n }\n }\n\n get size() {\n return this.data.size\n }\n\n purgeStale() {\n const n = Math.ceil(now())\n for (const exp in this.expirations) {\n if (exp === 'Infinity' || exp > n) {\n return\n }\n\n /* istanbul ignore next\n * mysterious need for a guard here?\n * https://github.com/isaacs/ttlcache/issues/26 */\n const keys = [...(this.expirations[exp] || [])]\n const entries = []\n delete this.expirations[exp]\n for (const key of keys) {\n entries.push([key, this.data.get(key)])\n this.data.delete(key)\n this.expirationMap.delete(key)\n }\n for (const [key, val] of entries) {\n this.dispose(val, key, 'stale')\n }\n }\n if (this.size === 0) {\n this.cancelTimer()\n }\n }\n\n *entries() {\n for (const exp in this.expirations) {\n for (const key of this.expirations[exp]) {\n yield [key, this.data.get(key)]\n }\n }\n }\n *keys() {\n for (const exp in this.expirations) {\n for (const key of this.expirations[exp]) {\n yield key\n }\n }\n }\n *values() {\n for (const exp in this.expirations) {\n for (const key of this.expirations[exp]) {\n yield this.data.get(key)\n }\n }\n }\n [Symbol.iterator]() {\n return this.entries()\n }\n}\n\nmodule.exports = TTLCache\n", "'use strict'\n\nexports.supports = function supports (...manifests) {\n const manifest = manifests.reduce((acc, m) => Object.assign(acc, m), {})\n\n return Object.assign(manifest, {\n snapshots: manifest.snapshots || false,\n permanence: manifest.permanence || false,\n seek: manifest.seek || false,\n clear: manifest.clear || false,\n getMany: manifest.getMany || false,\n keyIterator: manifest.keyIterator || false,\n valueIterator: manifest.valueIterator || false,\n iteratorNextv: manifest.iteratorNextv || false,\n iteratorAll: manifest.iteratorAll || false,\n status: manifest.status || false,\n createIfMissing: manifest.createIfMissing || false,\n errorIfExists: manifest.errorIfExists || false,\n deferredOpen: manifest.deferredOpen || false,\n promises: manifest.promises || false,\n streams: manifest.streams || false,\n encodings: Object.assign({}, manifest.encodings),\n events: Object.assign({}, manifest.events),\n additionalMethods: Object.assign({}, manifest.additionalMethods)\n })\n}\n", "'use strict'\n\nmodule.exports = class ModuleError extends Error {\n /**\n * @param {string} message Error message\n * @param {{ code?: string, cause?: Error, expected?: boolean, transient?: boolean }} [options]\n */\n constructor (message, options) {\n super(message || '')\n\n if (typeof options === 'object' && options !== null) {\n if (options.code) this.code = String(options.code)\n if (options.expected) this.expected = true\n if (options.transient) this.transient = true\n if (options.cause) this.cause = options.cause\n }\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor)\n }\n }\n}\n", "'use strict'\n\n/** @type {{ textEncoder: TextEncoder, textDecoder: TextDecoder }|null} */\nlet lazy = null\n\n/**\n * Get semi-global instances of TextEncoder and TextDecoder.\n * @returns {{ textEncoder: TextEncoder, textDecoder: TextDecoder }}\n */\nmodule.exports = function () {\n if (lazy === null) {\n lazy = {\n textEncoder: new TextEncoder(),\n textDecoder: new TextDecoder()\n }\n }\n\n return lazy\n}\n", "'use strict'\n\nconst ModuleError = require('module-error')\nconst formats = new Set(['buffer', 'view', 'utf8'])\n\n/**\n * @template TIn, TFormat, TOut\n * @abstract\n */\nclass Encoding {\n /**\n * @param {IEncoding<TIn,TFormat,TOut>} options\n */\n constructor (options) {\n /** @type {(data: TIn) => TFormat} */\n this.encode = options.encode || this.encode\n\n /** @type {(data: TFormat) => TOut} */\n this.decode = options.decode || this.decode\n\n /** @type {string} */\n this.name = options.name || this.name\n\n /** @type {string} */\n this.format = options.format || this.format\n\n if (typeof this.encode !== 'function') {\n throw new TypeError(\"The 'encode' property must be a function\")\n }\n\n if (typeof this.decode !== 'function') {\n throw new TypeError(\"The 'decode' property must be a function\")\n }\n\n this.encode = this.encode.bind(this)\n this.decode = this.decode.bind(this)\n\n if (typeof this.name !== 'string' || this.name === '') {\n throw new TypeError(\"The 'name' property must be a string\")\n }\n\n if (typeof this.format !== 'string' || !formats.has(this.format)) {\n throw new TypeError(\"The 'format' property must be one of 'buffer', 'view', 'utf8'\")\n }\n\n if (options.createViewTranscoder) {\n this.createViewTranscoder = options.createViewTranscoder\n }\n\n if (options.createBufferTranscoder) {\n this.createBufferTranscoder = options.createBufferTranscoder\n }\n\n if (options.createUTF8Transcoder) {\n this.createUTF8Transcoder = options.createUTF8Transcoder\n }\n }\n\n get commonName () {\n return /** @type {string} */ (this.name.split('+')[0])\n }\n\n /** @return {BufferFormat<TIn,TOut>} */\n createBufferTranscoder () {\n throw new ModuleError(`Encoding '${this.name}' cannot be transcoded to 'buffer'`, {\n code: 'LEVEL_ENCODING_NOT_SUPPORTED'\n })\n }\n\n /** @return {ViewFormat<TIn,TOut>} */\n createViewTranscoder () {\n throw new ModuleError(`Encoding '${this.name}' cannot be transcoded to 'view'`, {\n code: 'LEVEL_ENCODING_NOT_SUPPORTED'\n })\n }\n\n /** @return {UTF8Format<TIn,TOut>} */\n createUTF8Transcoder () {\n throw new ModuleError(`Encoding '${this.name}' cannot be transcoded to 'utf8'`, {\n code: 'LEVEL_ENCODING_NOT_SUPPORTED'\n })\n }\n}\n\nexports.Encoding = Encoding\n\n/**\n * @typedef {import('./encoding').IEncoding<TIn,TFormat,TOut>} IEncoding\n * @template TIn, TFormat, TOut\n */\n\n/**\n * @typedef {import('./formats').BufferFormat<TIn,TOut>} BufferFormat\n * @template TIn, TOut\n */\n\n/**\n * @typedef {import('./formats').ViewFormat<TIn,TOut>} ViewFormat\n * @template TIn, TOut\n */\n\n/**\n * @typedef {import('./formats').UTF8Format<TIn,TOut>} UTF8Format\n * @template TIn, TOut\n */\n", "'use strict'\n\nconst { Buffer } = require('buffer') || {}\nconst { Encoding } = require('./encoding')\nconst textEndec = require('./text-endec')\n\n/**\n * @template TIn, TOut\n * @extends {Encoding<TIn,Buffer,TOut>}\n */\nclass BufferFormat extends Encoding {\n /**\n * @param {Omit<IEncoding<TIn, Buffer, TOut>, 'format'>} options\n */\n constructor (options) {\n super({ ...options, format: 'buffer' })\n }\n\n /** @override */\n createViewTranscoder () {\n return new ViewFormat({\n encode: this.encode, // Buffer is a view (UInt8Array)\n decode: (data) => this.decode(\n Buffer.from(data.buffer, data.byteOffset, data.byteLength)\n ),\n name: `${this.name}+view`\n })\n }\n\n /** @override */\n createBufferTranscoder () {\n return this\n }\n}\n\n/**\n * @extends {Encoding<TIn,Uint8Array,TOut>}\n * @template TIn, TOut\n */\nclass ViewFormat extends Encoding {\n /**\n * @param {Omit<IEncoding<TIn, Uint8Array, TOut>, 'format'>} options\n */\n constructor (options) {\n super({ ...options, format: 'view' })\n }\n\n /** @override */\n createBufferTranscoder () {\n return new BufferFormat({\n encode: (data) => {\n const view = this.encode(data)\n return Buffer.from(view.buffer, view.byteOffset, view.byteLength)\n },\n decode: this.decode, // Buffer is a view (UInt8Array)\n name: `${this.name}+buffer`\n })\n }\n\n /** @override */\n createViewTranscoder () {\n return this\n }\n}\n\n/**\n * @extends {Encoding<TIn,string,TOut>}\n * @template TIn, TOut\n */\nclass UTF8Format extends Encoding {\n /**\n * @param {Omit<IEncoding<TIn, string, TOut>, 'format'>} options\n */\n constructor (options) {\n super({ ...options, format: 'utf8' })\n }\n\n /** @override */\n createBufferTranscoder () {\n return new BufferFormat({\n encode: (data) => Buffer.from(this.encode(data), 'utf8'),\n decode: (data) => this.decode(data.toString('utf8')),\n name: `${this.name}+buffer`\n })\n }\n\n /** @override */\n createViewTranscoder () {\n const { textEncoder, textDecoder } = textEndec()\n\n return new ViewFormat({\n encode: (data) => textEncoder.encode(this.encode(data)),\n decode: (data) => this.decode(textDecoder.decode(data)),\n name: `${this.name}+view`\n })\n }\n\n /** @override */\n createUTF8Transcoder () {\n return this\n }\n}\n\nexports.BufferFormat = BufferFormat\nexports.ViewFormat = ViewFormat\nexports.UTF8Format = UTF8Format\n\n/**\n * @typedef {import('./encoding').IEncoding<TIn,TFormat,TOut>} IEncoding\n * @template TIn, TFormat, TOut\n */\n", "'use strict'\n\nconst { Buffer } = require('buffer') || { Buffer: { isBuffer: () => false } }\nconst { textEncoder, textDecoder } = require('./text-endec')()\nconst { BufferFormat, ViewFormat, UTF8Format } = require('./formats')\n\n/** @type {<T>(v: T) => v} */\nconst identity = (v) => v\n\n/**\n * @type {typeof import('./encodings').utf8}\n */\nexports.utf8 = new UTF8Format({\n encode: function (data) {\n // On node 16.9.1 buffer.toString() is 5x faster than TextDecoder\n return Buffer.isBuffer(data)\n ? data.toString('utf8')\n : ArrayBuffer.isView(data)\n ? textDecoder.decode(data)\n : String(data)\n },\n decode: identity,\n name: 'utf8',\n createViewTranscoder () {\n return new ViewFormat({\n encode: function (data) {\n return ArrayBuffer.isView(data) ? data : textEncoder.encode(data)\n },\n decode: function (data) {\n return textDecoder.decode(data)\n },\n name: `${this.name}+view`\n })\n },\n createBufferTranscoder () {\n return new BufferFormat({\n encode: function (data) {\n return Buffer.isBuffer(data)\n ? data\n : ArrayBuffer.isView(data)\n ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)\n : Buffer.from(String(data), 'utf8')\n },\n decode: function (data) {\n return data.toString('utf8')\n },\n name: `${this.name}+buffer`\n })\n }\n})\n\n/**\n * @type {typeof import('./encodings').json}\n */\nexports.json = new UTF8Format({\n encode: JSON.stringify,\n decode: JSON.parse,\n name: 'json'\n})\n\n/**\n * @type {typeof import('./encodings').buffer}\n */\nexports.buffer = new BufferFormat({\n encode: function (data) {\n return Buffer.isBuffer(data)\n ? data\n : ArrayBuffer.isView(data)\n ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)\n : Buffer.from(String(data), 'utf8')\n },\n decode: identity,\n name: 'buffer',\n createViewTranscoder () {\n return new ViewFormat({\n encode: function (data) {\n return ArrayBuffer.isView(data) ? data : Buffer.from(String(data), 'utf8')\n },\n decode: function (data) {\n return Buffer.from(data.buffer, data.byteOffset, data.byteLength)\n },\n name: `${this.name}+view`\n })\n }\n})\n\n/**\n * @type {typeof import('./encodings').view}\n */\nexports.view = new ViewFormat({\n encode: function (data) {\n return ArrayBuffer.isView(data) ? data : textEncoder.encode(data)\n },\n decode: identity,\n name: 'view',\n createBufferTranscoder () {\n return new BufferFormat({\n encode: function (data) {\n return Buffer.isBuffer(data)\n ? data\n : ArrayBuffer.isView(data)\n ? Buffer.from(data.buffer, data.byteOffset, data.byteLength)\n : Buffer.from(String(data), 'utf8')\n },\n decode: identity,\n name: `${this.name}+buffer`\n })\n }\n})\n\n/**\n * @type {typeof import('./encodings').hex}\n */\nexports.hex = new BufferFormat({\n encode: function (data) {\n return Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'hex')\n },\n decode: function (buffer) {\n return buffer.toString('hex')\n },\n name: 'hex'\n})\n\n/**\n * @type {typeof import('./encodings').base64}\n */\nexports.base64 = new BufferFormat({\n encode: function (data) {\n return Buffer.isBuffer(data) ? data : Buffer.from(String(data), 'base64')\n },\n decode: function (buffer) {\n return buffer.toString('base64')\n },\n name: 'base64'\n})\n", "'use strict'\n\nconst ModuleError = require('module-error')\nconst encodings = require('./lib/encodings')\nconst { Encoding } = require('./lib/encoding')\nconst { BufferFormat, ViewFormat, UTF8Format } = require('./lib/formats')\n\nconst kFormats = Symbol('formats')\nconst kEncodings = Symbol('encodings')\nconst validFormats = new Set(['buffer', 'view', 'utf8'])\n\n/** @template T */\nclass Transcoder {\n /**\n * @param {Array<'buffer'|'view'|'utf8'>} formats\n */\n constructor (formats) {\n if (!Array.isArray(formats)) {\n throw new TypeError(\"The first argument 'formats' must be an array\")\n } else if (!formats.every(f => validFormats.has(f))) {\n // Note: we only only support aliases in key- and valueEncoding options (where we already did)\n throw new TypeError(\"Format must be one of 'buffer', 'view', 'utf8'\")\n }\n\n /** @type {Map<string|MixedEncoding<any, any, any>, Encoding<any, any, any>>} */\n this[kEncodings] = new Map()\n this[kFormats] = new Set(formats)\n\n // Register encodings (done early in order to populate encodings())\n for (const k in encodings) {\n try {\n this.encoding(k)\n } catch (err) {\n /* istanbul ignore if: assertion */\n if (err.code !== 'LEVEL_ENCODING_NOT_SUPPORTED') throw err\n }\n }\n }\n\n /**\n * @returns {Array<Encoding<any,T,any>>}\n */\n encodings () {\n return Array.from(new Set(this[kEncodings].values()))\n }\n\n /**\n * @param {string|MixedEncoding<any, any, any>} encoding\n * @returns {Encoding<any, T, any>}\n */\n encoding (encoding) {\n let resolved = this[kEncodings].get(encoding)\n\n if (resolved === undefined) {\n if (typeof encoding === 'string' && encoding !== '') {\n resolved = lookup[encoding]\n\n if (!resolved) {\n throw new ModuleError(`Encoding '${encoding}' is not found`, {\n code: 'LEVEL_ENCODING_NOT_FOUND'\n })\n }\n } else if (typeof encoding !== 'object' || encoding === null) {\n throw new TypeError(\"First argument 'encoding' must be a string or object\")\n } else {\n resolved = from(encoding)\n }\n\n const { name, format } = resolved\n\n if (!this[kFormats].has(format)) {\n if (this[kFormats].has('view')) {\n resolved = resolved.createViewTranscoder()\n } else if (this[kFormats].has('buffer')) {\n resolved = resolved.createBufferTranscoder()\n } else if (this[kFormats].has('utf8')) {\n resolved = resolved.createUTF8Transcoder()\n } else {\n throw new ModuleError(`Encoding '${name}' cannot be transcoded`, {\n code: 'LEVEL_ENCODING_NOT_SUPPORTED'\n })\n }\n }\n\n for (const k of [encoding, name, resolved.name, resolved.commonName]) {\n this[kEncodings].set(k, resolved)\n }\n }\n\n return resolved\n }\n}\n\nexports.Transcoder = Transcoder\n\n/**\n * @param {MixedEncoding<any, any, any>} options\n * @returns {Encoding<any, any, any>}\n */\nfunction from (options) {\n if (options instanceof Encoding) {\n return options\n }\n\n // Loosely typed for ecosystem compatibility\n const maybeType = 'type' in options && typeof options.type === 'string' ? options.type : undefined\n const name = options.name || maybeType || `anonymous-${anonymousCount++}`\n\n switch (detectFormat(options)) {\n case 'view': return new ViewFormat({ ...options, name })\n case 'utf8': return new UTF8Format({ ...options, name })\n case 'buffer': return new BufferFormat({ ...options, name })\n default: {\n throw new TypeError(\"Format must be one of 'buffer', 'view', 'utf8'\")\n }\n }\n}\n\n/**\n * If format is not provided, fallback to detecting `level-codec`\n * or `multiformats` encodings, else assume a format of buffer.\n * @param {MixedEncoding<any, any, any>} options\n * @returns {string}\n */\nfunction detectFormat (options) {\n if ('format' in options && options.format !== undefined) {\n return options.format\n } else if ('buffer' in options && typeof options.buffer === 'boolean') {\n return options.buffer ? 'buffer' : 'utf8' // level-codec\n } else if ('code' in options && Number.isInteger(options.code)) {\n return 'view' // multiformats\n } else {\n return 'buffer'\n }\n}\n\n/**\n * @typedef {import('./lib/encoding').MixedEncoding<TIn,TFormat,TOut>} MixedEncoding\n * @template TIn, TFormat, TOut\n */\n\n/**\n * @type {Object.<string, Encoding<any, any, any>>}\n */\nconst aliases = {\n binary: encodings.buffer,\n 'utf-8': encodings.utf8\n}\n\n/**\n * @type {Object.<string, Encoding<any, any, any>>}\n */\nconst lookup = {\n ...encodings,\n ...aliases\n}\n\nlet anonymousCount = 0\n", "// Copyright Joyent, Inc. and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n'use strict';\n\nvar R = typeof Reflect === 'object' ? Reflect : null\nvar ReflectApply = R && typeof R.apply === 'function'\n ? R.apply\n : function ReflectApply(target, receiver, args) {\n return Function.prototype.apply.call(target, receiver, args);\n }\n\nvar ReflectOwnKeys\nif (R && typeof R.ownKeys === 'function') {\n ReflectOwnKeys = R.ownKeys\n} else if (Object.getOwnPropertySymbols) {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target)\n .concat(Object.getOwnPropertySymbols(target));\n };\n} else {\n ReflectOwnKeys = function ReflectOwnKeys(target) {\n return Object.getOwnPropertyNames(target);\n };\n}\n\nfunction ProcessEmitWarning(warning) {\n if (console && console.warn) console.warn(warning);\n}\n\nvar NumberIsNaN = Number.isNaN || function NumberIsNaN(value) {\n return value !== value;\n}\n\nfunction EventEmitter() {\n EventEmitter.init.call(this);\n}\nmodule.exports = EventEmitter;\nmodule.exports.once = once;\n\n// Backwards-compat with node 0.10.x\nEventEmitter.EventEmitter = EventEmitter;\n\nEventEmitter.prototype._events = undefined;\nEventEmitter.prototype._eventsCount = 0;\nEventEmitter.prototype._maxListeners = undefined;\n\n// By default EventEmitters will print a warning if more than 10 listeners are\n// added to it. This is a useful default which helps finding memory leaks.\nvar defaultMaxListeners = 10;\n\nfunction checkListener(listener) {\n if (typeof listener !== 'function') {\n throw new TypeError('The \"listener\" argument must be of type Function. Received type ' + typeof listener);\n }\n}\n\nObject.defineProperty(EventEmitter, 'defaultMaxListeners', {\n enumerable: true,\n get: function() {\n return defaultMaxListeners;\n },\n set: function(arg) {\n if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {\n throw new RangeError('The value of \"defaultMaxListeners\" is out of range. It must be a non-negative number. Received ' + arg + '.');\n }\n defaultMaxListeners = arg;\n }\n});\n\nEventEmitter.init = function() {\n\n if (this._events === undefined ||\n this._events === Object.getPrototypeOf(this)._events) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n }\n\n this._maxListeners = this._maxListeners || undefined;\n};\n\n// Obviously not all Emitters should be limited to 10. This function allows\n// that to be increased. Set to zero for unlimited.\nEventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {\n if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {\n throw new RangeError('The value of \"n\" is out of range. It must be a non-negative number. Received ' + n + '.');\n }\n this._maxListeners = n;\n return this;\n};\n\nfunction _getMaxListeners(that) {\n if (that._maxListeners === undefined)\n return EventEmitter.defaultMaxListeners;\n return that._maxListeners;\n}\n\nEventEmitter.prototype.getMaxListeners = function getMaxListeners() {\n return _getMaxListeners(this);\n};\n\nEventEmitter.prototype.emit = function emit(type) {\n var args = [];\n for (var i = 1; i < arguments.length; i++) args.push(arguments[i]);\n var doError = (type === 'error');\n\n var events = this._events;\n if (events !== undefined)\n doError = (doError && events.error === undefined);\n else if (!doError)\n return false;\n\n // If there is no 'error' event listener then throw.\n if (doError) {\n var er;\n if (args.length > 0)\n er = args[0];\n if (er instanceof Error) {\n // Note: The comments on the `throw` lines are intentional, they show\n // up in Node's output if this results in an unhandled exception.\n throw er; // Unhandled 'error' event\n }\n // At least give some kind of context to the user\n var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : ''));\n err.context = er;\n throw err; // Unhandled 'error' event\n }\n\n var handler = events[type];\n\n if (handler === undefined)\n return false;\n\n if (typeof handler === 'function') {\n ReflectApply(handler, this, args);\n } else {\n var len = handler.length;\n var listeners = arrayClone(handler, len);\n for (var i = 0; i < len; ++i)\n ReflectApply(listeners[i], this, args);\n }\n\n return true;\n};\n\nfunction _addListener(target, type, listener, prepend) {\n var m;\n var events;\n var existing;\n\n checkListener(listener);\n\n events = target._events;\n if (events === undefined) {\n events = target._events = Object.create(null);\n target._eventsCount = 0;\n } else {\n // To avoid recursion in the case that type === \"newListener\"! Before\n // adding it to the listeners, first emit \"newListener\".\n if (events.newListener !== undefined) {\n target.emit('newListener', type,\n listener.listener ? listener.listener : listener);\n\n // Re-assign `events` because a newListener handler could have caused the\n // this._events to be assigned to a new object\n events = target._events;\n }\n existing = events[type];\n }\n\n if (existing === undefined) {\n // Optimize the case of one listener. Don't need the extra array object.\n existing = events[type] = listener;\n ++target._eventsCount;\n } else {\n if (typeof existing === 'function') {\n // Adding the second element, need to change to array.\n existing = events[type] =\n prepend ? [listener, existing] : [existing, listener];\n // If we've already got an array, just append.\n } else if (prepend) {\n existing.unshift(listener);\n } else {\n existing.push(listener);\n }\n\n // Check for listener leak\n m = _getMaxListeners(target);\n if (m > 0 && existing.length > m && !existing.warned) {\n existing.warned = true;\n // No error code for this since it is a Warning\n // eslint-disable-next-line no-restricted-syntax\n var w = new Error('Possible EventEmitter memory leak detected. ' +\n existing.length + ' ' + String(type) + ' listeners ' +\n 'added. Use emitter.setMaxListeners() to ' +\n 'increase limit');\n w.name = 'MaxListenersExceededWarning';\n w.emitter = target;\n w.type = type;\n w.count = existing.length;\n ProcessEmitWarning(w);\n }\n }\n\n return target;\n}\n\nEventEmitter.prototype.addListener = function addListener(type, listener) {\n return _addListener(this, type, listener, false);\n};\n\nEventEmitter.prototype.on = EventEmitter.prototype.addListener;\n\nEventEmitter.prototype.prependListener =\n function prependListener(type, listener) {\n return _addListener(this, type, listener, true);\n };\n\nfunction onceWrapper() {\n if (!this.fired) {\n this.target.removeListener(this.type, this.wrapFn);\n this.fired = true;\n if (arguments.length === 0)\n return this.listener.call(this.target);\n return this.listener.apply(this.target, arguments);\n }\n}\n\nfunction _onceWrap(target, type, listener) {\n var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };\n var wrapped = onceWrapper.bind(state);\n wrapped.listener = listener;\n state.wrapFn = wrapped;\n return wrapped;\n}\n\nEventEmitter.prototype.once = function once(type, listener) {\n checkListener(listener);\n this.on(type, _onceWrap(this, type, listener));\n return this;\n};\n\nEventEmitter.prototype.prependOnceListener =\n function prependOnceListener(type, listener) {\n checkListener(listener);\n this.prependListener(type, _onceWrap(this, type, listener));\n return this;\n };\n\n// Emits a 'removeListener' event if and only if the listener was removed.\nEventEmitter.prototype.removeListener =\n function removeListener(type, listener) {\n var list, events, position, i, originalListener;\n\n checkListener(listener);\n\n events = this._events;\n if (events === undefined)\n return this;\n\n list = events[type];\n if (list === undefined)\n return this;\n\n if (list === listener || list.listener === listener) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else {\n delete events[type];\n if (events.removeListener)\n this.emit('removeListener', type, list.listener || listener);\n }\n } else if (typeof list !== 'function') {\n position = -1;\n\n for (i = list.length - 1; i >= 0; i--) {\n if (list[i] === listener || list[i].listener === listener) {\n originalListener = list[i].listener;\n position = i;\n break;\n }\n }\n\n if (position < 0)\n return this;\n\n if (position === 0)\n list.shift();\n else {\n spliceOne(list, position);\n }\n\n if (list.length === 1)\n events[type] = list[0];\n\n if (events.removeListener !== undefined)\n this.emit('removeListener', type, originalListener || listener);\n }\n\n return this;\n };\n\nEventEmitter.prototype.off = EventEmitter.prototype.removeListener;\n\nEventEmitter.prototype.removeAllListeners =\n function removeAllListeners(type) {\n var listeners, events, i;\n\n events = this._events;\n if (events === undefined)\n return this;\n\n // not listening for removeListener, no need to emit\n if (events.removeListener === undefined) {\n if (arguments.length === 0) {\n this._events = Object.create(null);\n this._eventsCount = 0;\n } else if (events[type] !== undefined) {\n if (--this._eventsCount === 0)\n this._events = Object.create(null);\n else\n delete events[type];\n }\n return this;\n }\n\n // emit removeListener for all listeners on all events\n if (arguments.length === 0) {\n var keys = Object.keys(events);\n var key;\n for (i = 0; i < keys.length; ++i) {\n key = keys[i];\n if (key === 'removeListener') continue;\n this.removeAllListeners(key);\n }\n this.removeAllListeners('removeListener');\n this._events = Object.create(null);\n this._eventsCount = 0;\n return this;\n }\n\n listeners = events[type];\n\n if (typeof listeners === 'function') {\n this.removeListener(type, listeners);\n } else if (listeners !== undefined) {\n // LIFO order\n for (i = listeners.length - 1; i >= 0; i--) {\n this.removeListener(type, listeners[i]);\n }\n }\n\n return this;\n };\n\nfunction _listeners(target, type, unwrap) {\n var events = target._events;\n\n if (events === undefined)\n return [];\n\n var evlistener = events[type];\n if (evlistener === undefined)\n return [];\n\n if (typeof evlistener === 'function')\n return unwrap ? [evlistener.listener || evlistener] : [evlistener];\n\n return unwrap ?\n unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);\n}\n\nEventEmitter.prototype.listeners = function listeners(type) {\n return _listeners(this, type, true);\n};\n\nEventEmitter.prototype.rawListeners = function rawListeners(type) {\n return _listeners(this, type, false);\n};\n\nEventEmitter.listenerCount = function(emitter, type) {\n if (typeof emitter.listenerCount === 'function') {\n return emitter.listenerCount(type);\n } else {\n return listenerCount.call(emitter, type);\n }\n};\n\nEventEmitter.prototype.listenerCount = listenerCount;\nfunction listenerCount(type) {\n var events = this._events;\n\n if (events !== undefined) {\n var evlistener = events[type];\n\n if (typeof evlistener === 'function') {\n return 1;\n } else if (evlistener !== undefined) {\n return evlistener.length;\n }\n }\n\n return 0;\n}\n\nEventEmitter.prototype.eventNames = function eventNames() {\n return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : [];\n};\n\nfunction arrayClone(arr, n) {\n var copy = new Array(n);\n for (var i = 0; i < n; ++i)\n copy[i] = arr[i];\n return copy;\n}\n\nfunction spliceOne(list, index) {\n for (; index + 1 < list.length; index++)\n list[index] = list[index + 1];\n list.pop();\n}\n\nfunction unwrapListeners(arr) {\n var ret = new Array(arr.length);\n for (var i = 0; i < ret.length; ++i) {\n ret[i] = arr[i].listener || arr[i];\n }\n return ret;\n}\n\nfunction once(emitter, name) {\n return new Promise(function (resolve, reject) {\n function errorListener(err) {\n emitter.removeListener(name, resolver);\n reject(err);\n }\n\n function resolver() {\n if (typeof emitter.removeListener === 'function') {\n emitter.removeListener('error', errorListener);\n }\n resolve([].slice.call(arguments));\n };\n\n eventTargetAgnosticAddListener(emitter, name, resolver, { once: true });\n if (name !== 'error') {\n addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true });\n }\n });\n}\n\nfunction addErrorHandlerIfEventEmitter(emitter, handler, flags) {\n if (typeof emitter.on === 'function') {\n eventTargetAgnosticAddListener(emitter, 'error', handler, flags);\n }\n}\n\nfunction eventTargetAgnosticAddListener(emitter, name, listener, flags) {\n if (typeof emitter.on === 'function') {\n if (flags.once) {\n emitter.once(name, listener);\n } else {\n emitter.on(name, listener);\n }\n } else if (typeof emitter.addEventListener === 'function') {\n // EventTarget does not have `error` event semantics like Node\n // EventEmitters, we do not listen for `error` events here.\n emitter.addEventListener(name, function wrapListener(arg) {\n // IE does not have builtin `{ once: true }` support so we\n // have to do it manually.\n if (flags.once) {\n emitter.removeEventListener(name, wrapListener);\n }\n listener(arg);\n });\n } else {\n throw new TypeError('The \"emitter\" argument must be of type EventEmitter. Received type ' + typeof emitter);\n }\n}\n", "module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn)\n", "'use strict'\n\nvar nextTick = require('./next-tick')\n\nexports.fromCallback = function (callback, symbol) {\n if (callback === undefined) {\n var promise = new Promise(function (resolve, reject) {\n callback = function (err, res) {\n if (err) reject(err)\n else resolve(res)\n }\n })\n\n callback[symbol !== undefined ? symbol : 'promise'] = promise\n } else if (typeof callback !== 'function') {\n throw new TypeError('Callback must be a function')\n }\n\n return callback\n}\n\nexports.fromPromise = function (promise, callback) {\n if (callback === undefined) return promise\n\n promise\n .then(function (res) { nextTick(() => callback(null, res)) })\n .catch(function (err) { nextTick(() => callback(err)) })\n}\n", "'use strict'\n\nexports.getCallback = function (options, callback) {\n return typeof options === 'function' ? options : callback\n}\n\nexports.getOptions = function (options, def) {\n if (typeof options === 'object' && options !== null) {\n return options\n }\n\n if (def !== undefined) {\n return def\n }\n\n return {}\n}\n", "'use strict'\n\nconst { fromCallback } = require('catering')\nconst ModuleError = require('module-error')\nconst { getOptions, getCallback } = require('./lib/common')\n\nconst kPromise = Symbol('promise')\nconst kCallback = Symbol('callback')\nconst kWorking = Symbol('working')\nconst kHandleOne = Symbol('handleOne')\nconst kHandleMany = Symbol('handleMany')\nconst kAutoClose = Symbol('autoClose')\nconst kFinishWork = Symbol('finishWork')\nconst kReturnMany = Symbol('returnMany')\nconst kClosing = Symbol('closing')\nconst kHandleClose = Symbol('handleClose')\nconst kClosed = Symbol('closed')\nconst kCloseCallbacks = Symbol('closeCallbacks')\nconst kKeyEncoding = Symbol('keyEncoding')\nconst kValueEncoding = Symbol('valueEncoding')\nconst kAbortOnClose = Symbol('abortOnClose')\nconst kLegacy = Symbol('legacy')\nconst kKeys = Symbol('keys')\nconst kValues = Symbol('values')\nconst kLimit = Symbol('limit')\nconst kCount = Symbol('count')\n\nconst emptyOptions = Object.freeze({})\nconst noop = () => {}\nlet warnedEnd = false\n\n// This class is an internal utility for common functionality between AbstractIterator,\n// AbstractKeyIterator and AbstractValueIterator. It's not exported.\nclass CommonIterator {\n constructor (db, options, legacy) {\n if (typeof db !== 'object' || db === null) {\n const hint = db === null ? 'null' : typeof db\n throw new TypeError(`The first argument must be an abstract-level database, received ${hint}`)\n }\n\n if (typeof options !== 'object' || options === null) {\n throw new TypeError('The second argument must be an options object')\n }\n\n this[kClosed] = false\n this[kCloseCallbacks] = []\n this[kWorking] = false\n this[kClosing] = false\n this[kAutoClose] = false\n this[kCallback] = null\n this[kHandleOne] = this[kHandleOne].bind(this)\n this[kHandleMany] = this[kHandleMany].bind(this)\n this[kHandleClose] = this[kHandleClose].bind(this)\n this[kKeyEncoding] = options[kKeyEncoding]\n this[kValueEncoding] = options[kValueEncoding]\n this[kLegacy] = legacy\n this[kLimit] = Number.isInteger(options.limit) && options.limit >= 0 ? options.limit : Infinity\n this[kCount] = 0\n\n // Undocumented option to abort pending work on close(). Used by the\n // many-level module as a temporary solution to a blocked close().\n // TODO (next major): consider making this the default behavior. Native\n // implementations should have their own logic to safely close iterators.\n this[kAbortOnClose] = !!options.abortOnClose\n\n this.db = db\n this.db.attachResource(this)\n this.nextTick = db.nextTick\n }\n\n get count () {\n return this[kCount]\n }\n\n get limit () {\n return this[kLimit]\n }\n\n next (callback) {\n let promise\n\n if (callback === undefined) {\n promise = new Promise((resolve, reject) => {\n callback = (err, key, value) => {\n if (err) reject(err)\n else if (!this[kLegacy]) resolve(key)\n else if (key === undefined && value === undefined) resolve()\n else resolve([key, value])\n }\n })\n } else if (typeof callback !== 'function') {\n throw new TypeError('Callback must be a function')\n }\n\n if (this[kClosing]) {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call next() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n } else if (this[kWorking]) {\n this.nextTick(callback, new ModuleError('Iterator is busy: cannot call next() until previous call has completed', {\n code: 'LEVEL_ITERATOR_BUSY'\n }))\n } else {\n this[kWorking] = true\n this[kCallback] = callback\n\n if (this[kCount] >= this[kLimit]) this.nextTick(this[kHandleOne], null)\n else this._next(this[kHandleOne])\n }\n\n return promise\n }\n\n _next (callback) {\n this.nextTick(callback)\n }\n\n nextv (size, options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, emptyOptions)\n\n if (!Number.isInteger(size)) {\n this.nextTick(callback, new TypeError(\"The first argument 'size' must be an integer\"))\n return callback[kPromise]\n }\n\n if (this[kClosing]) {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call nextv() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n } else if (this[kWorking]) {\n this.nextTick(callback, new ModuleError('Iterator is busy: cannot call nextv() until previous call has completed', {\n code: 'LEVEL_ITERATOR_BUSY'\n }))\n } else {\n if (size < 1) size = 1\n if (this[kLimit] < Infinity) size = Math.min(size, this[kLimit] - this[kCount])\n\n this[kWorking] = true\n this[kCallback] = callback\n\n if (size <= 0) this.nextTick(this[kHandleMany], null, [])\n else this._nextv(size, options, this[kHandleMany])\n }\n\n return callback[kPromise]\n }\n\n _nextv (size, options, callback) {\n const acc = []\n const onnext = (err, key, value) => {\n if (err) {\n return callback(err)\n } else if (this[kLegacy] ? key === undefined && value === undefined : key === undefined) {\n return callback(null, acc)\n }\n\n acc.push(this[kLegacy] ? [key, value] : key)\n\n if (acc.length === size) {\n callback(null, acc)\n } else {\n this._next(onnext)\n }\n }\n\n this._next(onnext)\n }\n\n all (options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, emptyOptions)\n\n if (this[kClosing]) {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call all() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n } else if (this[kWorking]) {\n this.nextTick(callback, new ModuleError('Iterator is busy: cannot call all() until previous call has completed', {\n code: 'LEVEL_ITERATOR_BUSY'\n }))\n } else {\n this[kWorking] = true\n this[kCallback] = callback\n this[kAutoClose] = true\n\n if (this[kCount] >= this[kLimit]) this.nextTick(this[kHandleMany], null, [])\n else this._all(options, this[kHandleMany])\n }\n\n return callback[kPromise]\n }\n\n _all (options, callback) {\n // Must count here because we're directly calling _nextv()\n let count = this[kCount]\n const acc = []\n\n const nextv = () => {\n // Not configurable, because implementations should optimize _all().\n const size = this[kLimit] < Infinity ? Math.min(1e3, this[kLimit] - count) : 1e3\n\n if (size <= 0) {\n this.nextTick(callback, null, acc)\n } else {\n this._nextv(size, emptyOptions, onnextv)\n }\n }\n\n const onnextv = (err, items) => {\n if (err) {\n callback(err)\n } else if (items.length === 0) {\n callback(null, acc)\n } else {\n acc.push.apply(acc, items)\n count += items.length\n nextv()\n }\n }\n\n nextv()\n }\n\n [kFinishWork] () {\n const cb = this[kCallback]\n\n // Callback will be null if work was aborted on close\n if (this[kAbortOnClose] && cb === null) return noop\n\n this[kWorking] = false\n this[kCallback] = null\n\n if (this[kClosing]) this._close(this[kHandleClose])\n\n return cb\n }\n\n [kReturnMany] (cb, err, items) {\n if (this[kAutoClose]) {\n this.close(cb.bind(null, err, items))\n } else {\n cb(err, items)\n }\n }\n\n seek (target, options) {\n options = getOptions(options, emptyOptions)\n\n if (this[kClosing]) {\n // Don't throw here, to be kind to implementations that wrap\n // another db and don't necessarily control when the db is closed\n } else if (this[kWorking]) {\n throw new ModuleError('Iterator is busy: cannot call seek() until next() has completed', {\n code: 'LEVEL_ITERATOR_BUSY'\n })\n } else {\n const keyEncoding = this.db.keyEncoding(options.keyEncoding || this[kKeyEncoding])\n const keyFormat = keyEncoding.format\n\n if (options.keyEncoding !== keyFormat) {\n options = { ...options, keyEncoding: keyFormat }\n }\n\n const mapped = this.db.prefixKey(keyEncoding.encode(target), keyFormat)\n this._seek(mapped, options)\n }\n }\n\n _seek (target, options) {\n throw new ModuleError('Iterator does not support seek()', {\n code: 'LEVEL_NOT_SUPPORTED'\n })\n }\n\n close (callback) {\n callback = fromCallback(callback, kPromise)\n\n if (this[kClosed]) {\n this.nextTick(callback)\n } else if (this[kClosing]) {\n this[kCloseCallbacks].push(callback)\n } else {\n this[kClosing] = true\n this[kCloseCallbacks].push(callback)\n\n if (!this[kWorking]) {\n this._close(this[kHandleClose])\n } else if (this[kAbortOnClose]) {\n // Don't wait for work to finish. Subsequently ignore the result.\n const cb = this[kFinishWork]()\n\n cb(new ModuleError('Aborted on iterator close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n }\n }\n\n return callback[kPromise]\n }\n\n _close (callback) {\n this.nextTick(callback)\n }\n\n [kHandleClose] () {\n this[kClosed] = true\n this.db.detachResource(this)\n\n const callbacks = this[kCloseCallbacks]\n this[kCloseCallbacks] = []\n\n for (const cb of callbacks) {\n cb()\n }\n }\n\n async * [Symbol.asyncIterator] () {\n try {\n let item\n\n while ((item = (await this.next())) !== undefined) {\n yield item\n }\n } finally {\n if (!this[kClosed]) await this.close()\n }\n }\n}\n\n// For backwards compatibility this class is not (yet) called AbstractEntryIterator.\nclass AbstractIterator extends CommonIterator {\n constructor (db, options) {\n super(db, options, true)\n this[kKeys] = options.keys !== false\n this[kValues] = options.values !== false\n }\n\n [kHandleOne] (err, key, value) {\n const cb = this[kFinishWork]()\n if (err) return cb(err)\n\n try {\n key = this[kKeys] && key !== undefined ? this[kKeyEncoding].decode(key) : undefined\n value = this[kValues] && value !== undefined ? this[kValueEncoding].decode(value) : undefined\n } catch (err) {\n return cb(new IteratorDecodeError('entry', err))\n }\n\n if (!(key === undefined && value === undefined)) {\n this[kCount]++\n }\n\n cb(null, key, value)\n }\n\n [kHandleMany] (err, entries) {\n const cb = this[kFinishWork]()\n if (err) return this[kReturnMany](cb, err)\n\n try {\n for (const entry of entries) {\n const key = entry[0]\n const value = entry[1]\n\n entry[0] = this[kKeys] && key !== undefined ? this[kKeyEncoding].decode(key) : undefined\n entry[1] = this[kValues] && value !== undefined ? this[kValueEncoding].decode(value) : undefined\n }\n } catch (err) {\n return this[kReturnMany](cb, new IteratorDecodeError('entries', err))\n }\n\n this[kCount] += entries.length\n this[kReturnMany](cb, null, entries)\n }\n\n end (callback) {\n if (!warnedEnd && typeof console !== 'undefined') {\n warnedEnd = true\n console.warn(new ModuleError(\n 'The iterator.end() method was renamed to close() and end() is an alias that will be removed in a future version',\n { code: 'LEVEL_LEGACY' }\n ))\n }\n\n return this.close(callback)\n }\n}\n\nclass AbstractKeyIterator extends CommonIterator {\n constructor (db, options) {\n super(db, options, false)\n }\n\n [kHandleOne] (err, key) {\n const cb = this[kFinishWork]()\n if (err) return cb(err)\n\n try {\n key = key !== undefined ? this[kKeyEncoding].decode(key) : undefined\n } catch (err) {\n return cb(new IteratorDecodeError('key', err))\n }\n\n if (key !== undefined) this[kCount]++\n cb(null, key)\n }\n\n [kHandleMany] (err, keys) {\n const cb = this[kFinishWork]()\n if (err) return this[kReturnMany](cb, err)\n\n try {\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n keys[i] = key !== undefined ? this[kKeyEncoding].decode(key) : undefined\n }\n } catch (err) {\n return this[kReturnMany](cb, new IteratorDecodeError('keys', err))\n }\n\n this[kCount] += keys.length\n this[kReturnMany](cb, null, keys)\n }\n}\n\nclass AbstractValueIterator extends CommonIterator {\n constructor (db, options) {\n super(db, options, false)\n }\n\n [kHandleOne] (err, value) {\n const cb = this[kFinishWork]()\n if (err) return cb(err)\n\n try {\n value = value !== undefined ? this[kValueEncoding].decode(value) : undefined\n } catch (err) {\n return cb(new IteratorDecodeError('value', err))\n }\n\n if (value !== undefined) this[kCount]++\n cb(null, value)\n }\n\n [kHandleMany] (err, values) {\n const cb = this[kFinishWork]()\n if (err) return this[kReturnMany](cb, err)\n\n try {\n for (let i = 0; i < values.length; i++) {\n const value = values[i]\n values[i] = value !== undefined ? this[kValueEncoding].decode(value) : undefined\n }\n } catch (err) {\n return this[kReturnMany](cb, new IteratorDecodeError('values', err))\n }\n\n this[kCount] += values.length\n this[kReturnMany](cb, null, values)\n }\n}\n\n// Internal utility, not typed or exported\nclass IteratorDecodeError extends ModuleError {\n constructor (subject, cause) {\n super(`Iterator could not decode ${subject}`, {\n code: 'LEVEL_DECODE_ERROR',\n cause\n })\n }\n}\n\n// To help migrating to abstract-level\nfor (const k of ['_ended property', '_nexting property', '_end method']) {\n Object.defineProperty(AbstractIterator.prototype, k.split(' ')[0], {\n get () { throw new ModuleError(`The ${k} has been removed`, { code: 'LEVEL_LEGACY' }) },\n set () { throw new ModuleError(`The ${k} has been removed`, { code: 'LEVEL_LEGACY' }) }\n })\n}\n\n// Exposed so that AbstractLevel can set these options\nAbstractIterator.keyEncoding = kKeyEncoding\nAbstractIterator.valueEncoding = kValueEncoding\n\nexports.AbstractIterator = AbstractIterator\nexports.AbstractKeyIterator = AbstractKeyIterator\nexports.AbstractValueIterator = AbstractValueIterator\n", "'use strict'\n\nconst { AbstractKeyIterator, AbstractValueIterator } = require('../abstract-iterator')\n\nconst kIterator = Symbol('iterator')\nconst kCallback = Symbol('callback')\nconst kHandleOne = Symbol('handleOne')\nconst kHandleMany = Symbol('handleMany')\n\nclass DefaultKeyIterator extends AbstractKeyIterator {\n constructor (db, options) {\n super(db, options)\n\n this[kIterator] = db.iterator({ ...options, keys: true, values: false })\n this[kHandleOne] = this[kHandleOne].bind(this)\n this[kHandleMany] = this[kHandleMany].bind(this)\n }\n}\n\nclass DefaultValueIterator extends AbstractValueIterator {\n constructor (db, options) {\n super(db, options)\n\n this[kIterator] = db.iterator({ ...options, keys: false, values: true })\n this[kHandleOne] = this[kHandleOne].bind(this)\n this[kHandleMany] = this[kHandleMany].bind(this)\n }\n}\n\nfor (const Iterator of [DefaultKeyIterator, DefaultValueIterator]) {\n const keys = Iterator === DefaultKeyIterator\n const mapEntry = keys ? (entry) => entry[0] : (entry) => entry[1]\n\n Iterator.prototype._next = function (callback) {\n this[kCallback] = callback\n this[kIterator].next(this[kHandleOne])\n }\n\n Iterator.prototype[kHandleOne] = function (err, key, value) {\n const callback = this[kCallback]\n if (err) callback(err)\n else callback(null, keys ? key : value)\n }\n\n Iterator.prototype._nextv = function (size, options, callback) {\n this[kCallback] = callback\n this[kIterator].nextv(size, options, this[kHandleMany])\n }\n\n Iterator.prototype._all = function (options, callback) {\n this[kCallback] = callback\n this[kIterator].all(options, this[kHandleMany])\n }\n\n Iterator.prototype[kHandleMany] = function (err, entries) {\n const callback = this[kCallback]\n if (err) callback(err)\n else callback(null, entries.map(mapEntry))\n }\n\n Iterator.prototype._seek = function (target, options) {\n this[kIterator].seek(target, options)\n }\n\n Iterator.prototype._close = function (callback) {\n this[kIterator].close(callback)\n }\n}\n\n// Internal utilities, should be typed as AbstractKeyIterator and AbstractValueIterator\nexports.DefaultKeyIterator = DefaultKeyIterator\nexports.DefaultValueIterator = DefaultValueIterator\n", "'use strict'\n\nconst { AbstractIterator, AbstractKeyIterator, AbstractValueIterator } = require('../abstract-iterator')\nconst ModuleError = require('module-error')\n\nconst kNut = Symbol('nut')\nconst kUndefer = Symbol('undefer')\nconst kFactory = Symbol('factory')\n\nclass DeferredIterator extends AbstractIterator {\n constructor (db, options) {\n super(db, options)\n\n this[kNut] = null\n this[kFactory] = () => db.iterator(options)\n\n this.db.defer(() => this[kUndefer]())\n }\n}\n\nclass DeferredKeyIterator extends AbstractKeyIterator {\n constructor (db, options) {\n super(db, options)\n\n this[kNut] = null\n this[kFactory] = () => db.keys(options)\n\n this.db.defer(() => this[kUndefer]())\n }\n}\n\nclass DeferredValueIterator extends AbstractValueIterator {\n constructor (db, options) {\n super(db, options)\n\n this[kNut] = null\n this[kFactory] = () => db.values(options)\n\n this.db.defer(() => this[kUndefer]())\n }\n}\n\nfor (const Iterator of [DeferredIterator, DeferredKeyIterator, DeferredValueIterator]) {\n Iterator.prototype[kUndefer] = function () {\n if (this.db.status === 'open') {\n this[kNut] = this[kFactory]()\n }\n }\n\n Iterator.prototype._next = function (callback) {\n if (this[kNut] !== null) {\n this[kNut].next(callback)\n } else if (this.db.status === 'opening') {\n this.db.defer(() => this._next(callback))\n } else {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call next() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n }\n }\n\n Iterator.prototype._nextv = function (size, options, callback) {\n if (this[kNut] !== null) {\n this[kNut].nextv(size, options, callback)\n } else if (this.db.status === 'opening') {\n this.db.defer(() => this._nextv(size, options, callback))\n } else {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call nextv() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n }\n }\n\n Iterator.prototype._all = function (options, callback) {\n if (this[kNut] !== null) {\n this[kNut].all(callback)\n } else if (this.db.status === 'opening') {\n this.db.defer(() => this._all(options, callback))\n } else {\n this.nextTick(callback, new ModuleError('Iterator is not open: cannot call all() after close()', {\n code: 'LEVEL_ITERATOR_NOT_OPEN'\n }))\n }\n }\n\n Iterator.prototype._seek = function (target, options) {\n if (this[kNut] !== null) {\n // TODO: explain why we need _seek() rather than seek() here\n this[kNut]._seek(target, options)\n } else if (this.db.status === 'opening') {\n this.db.defer(() => this._seek(target, options))\n }\n }\n\n Iterator.prototype._close = function (callback) {\n if (this[kNut] !== null) {\n this[kNut].close(callback)\n } else if (this.db.status === 'opening') {\n this.db.defer(() => this._close(callback))\n } else {\n this.nextTick(callback)\n }\n }\n}\n\nexports.DeferredIterator = DeferredIterator\nexports.DeferredKeyIterator = DeferredKeyIterator\nexports.DeferredValueIterator = DeferredValueIterator\n", "'use strict'\n\nconst { fromCallback } = require('catering')\nconst ModuleError = require('module-error')\nconst { getCallback, getOptions } = require('./lib/common')\n\nconst kPromise = Symbol('promise')\nconst kStatus = Symbol('status')\nconst kOperations = Symbol('operations')\nconst kFinishClose = Symbol('finishClose')\nconst kCloseCallbacks = Symbol('closeCallbacks')\n\nclass AbstractChainedBatch {\n constructor (db) {\n if (typeof db !== 'object' || db === null) {\n const hint = db === null ? 'null' : typeof db\n throw new TypeError(`The first argument must be an abstract-level database, received ${hint}`)\n }\n\n this[kOperations] = []\n this[kCloseCallbacks] = []\n this[kStatus] = 'open'\n this[kFinishClose] = this[kFinishClose].bind(this)\n\n this.db = db\n this.db.attachResource(this)\n this.nextTick = db.nextTick\n }\n\n get length () {\n return this[kOperations].length\n }\n\n put (key, value, options) {\n if (this[kStatus] !== 'open') {\n throw new ModuleError('Batch is not open: cannot call put() after write() or close()', {\n code: 'LEVEL_BATCH_NOT_OPEN'\n })\n }\n\n const err = this.db._checkKey(key) || this.db._checkValue(value)\n if (err) throw err\n\n const db = options && options.sublevel != null ? options.sublevel : this.db\n const original = options\n const keyEncoding = db.keyEncoding(options && options.keyEncoding)\n const valueEncoding = db.valueEncoding(options && options.valueEncoding)\n const keyFormat = keyEncoding.format\n\n // Forward encoding options\n options = { ...options, keyEncoding: keyFormat, valueEncoding: valueEncoding.format }\n\n // Prevent double prefixing\n if (db !== this.db) {\n options.sublevel = null\n }\n\n const mappedKey = db.prefixKey(keyEncoding.encode(key), keyFormat)\n const mappedValue = valueEncoding.encode(value)\n\n this._put(mappedKey, mappedValue, options)\n this[kOperations].push({ ...original, type: 'put', key, value })\n\n return this\n }\n\n _put (key, value, options) {}\n\n del (key, options) {\n if (this[kStatus] !== 'open') {\n throw new ModuleError('Batch is not open: cannot call del() after write() or close()', {\n code: 'LEVEL_BATCH_NOT_OPEN'\n })\n }\n\n const err = this.db._checkKey(key)\n if (err) throw err\n\n const db = options && options.sublevel != null ? options.sublevel : this.db\n const original = options\n const keyEncoding = db.keyEncoding(options && options.keyEncoding)\n const keyFormat = keyEncoding.format\n\n // Forward encoding options\n options = { ...options, keyEncoding: keyFormat }\n\n // Prevent double prefixing\n if (db !== this.db) {\n options.sublevel = null\n }\n\n this._del(db.prefixKey(keyEncoding.encode(key), keyFormat), options)\n this[kOperations].push({ ...original, type: 'del', key })\n\n return this\n }\n\n _del (key, options) {}\n\n clear () {\n if (this[kStatus] !== 'open') {\n throw new ModuleError('Batch is not open: cannot call clear() after write() or close()', {\n code: 'LEVEL_BATCH_NOT_OPEN'\n })\n }\n\n this._clear()\n this[kOperations] = []\n\n return this\n }\n\n _clear () {}\n\n write (options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options)\n\n if (this[kStatus] !== 'open') {\n this.nextTick(callback, new ModuleError('Batch is not open: cannot call write() after write() or close()', {\n code: 'LEVEL_BATCH_NOT_OPEN'\n }))\n } else if (this.length === 0) {\n this.close(callback)\n } else {\n this[kStatus] = 'writing'\n this._write(options, (err) => {\n this[kStatus] = 'closing'\n this[kCloseCallbacks].push(() => callback(err))\n\n // Emit after setting 'closing' status, because event may trigger a\n // db close which in turn triggers (idempotently) closing this batch.\n if (!err) this.db.emit('batch', this[kOperations])\n\n this._close(this[kFinishClose])\n })\n }\n\n return callback[kPromise]\n }\n\n _write (options, callback) {}\n\n close (callback) {\n callback = fromCallback(callback, kPromise)\n\n if (this[kStatus] === 'closing') {\n this[kCloseCallbacks].push(callback)\n } else if (this[kStatus] === 'closed') {\n this.nextTick(callback)\n } else {\n this[kCloseCallbacks].push(callback)\n\n if (this[kStatus] !== 'writing') {\n this[kStatus] = 'closing'\n this._close(this[kFinishClose])\n }\n }\n\n return callback[kPromise]\n }\n\n _close (callback) {\n this.nextTick(callback)\n }\n\n [kFinishClose] () {\n this[kStatus] = 'closed'\n this.db.detachResource(this)\n\n const callbacks = this[kCloseCallbacks]\n this[kCloseCallbacks] = []\n\n for (const cb of callbacks) {\n cb()\n }\n }\n}\n\nexports.AbstractChainedBatch = AbstractChainedBatch\n", "'use strict'\n\nconst { AbstractChainedBatch } = require('../abstract-chained-batch')\nconst ModuleError = require('module-error')\nconst kEncoded = Symbol('encoded')\n\n// Functional default for chained batch, with support of deferred open\nclass DefaultChainedBatch extends AbstractChainedBatch {\n constructor (db) {\n super(db)\n this[kEncoded] = []\n }\n\n _put (key, value, options) {\n this[kEncoded].push({ ...options, type: 'put', key, value })\n }\n\n _del (key, options) {\n this[kEncoded].push({ ...options, type: 'del', key })\n }\n\n _clear () {\n this[kEncoded] = []\n }\n\n // Assumes this[kEncoded] cannot change after write()\n _write (options, callback) {\n if (this.db.status === 'opening') {\n this.db.defer(() => this._write(options, callback))\n } else if (this.db.status === 'open') {\n if (this[kEncoded].length === 0) this.nextTick(callback)\n else this.db._batch(this[kEncoded], options, callback)\n } else {\n this.nextTick(callback, new ModuleError('Batch is not open: cannot call write() after write() or close()', {\n code: 'LEVEL_BATCH_NOT_OPEN'\n }))\n }\n }\n}\n\nexports.DefaultChainedBatch = DefaultChainedBatch\n", "'use strict'\n\nconst ModuleError = require('module-error')\nconst hasOwnProperty = Object.prototype.hasOwnProperty\nconst rangeOptions = new Set(['lt', 'lte', 'gt', 'gte'])\n\nmodule.exports = function (options, keyEncoding) {\n const result = {}\n\n for (const k in options) {\n if (!hasOwnProperty.call(options, k)) continue\n if (k === 'keyEncoding' || k === 'valueEncoding') continue\n\n if (k === 'start' || k === 'end') {\n throw new ModuleError(`The legacy range option '${k}' has been removed`, {\n code: 'LEVEL_LEGACY'\n })\n } else if (k === 'encoding') {\n // To help migrating to abstract-level\n throw new ModuleError(\"The levelup-style 'encoding' alias has been removed, use 'valueEncoding' instead\", {\n code: 'LEVEL_LEGACY'\n })\n }\n\n if (rangeOptions.has(k)) {\n // Note that we don't reject nullish and empty options here. While\n // those types are invalid as keys, they are valid as range options.\n result[k] = keyEncoding.encode(options[k])\n } else {\n result[k] = options[k]\n }\n }\n\n result.reverse = !!result.reverse\n result.limit = Number.isInteger(result.limit) && result.limit >= 0 ? result.limit : -1\n\n return result\n}\n", "/*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */\nlet promise\n\nmodule.exports = typeof queueMicrotask === 'function'\n ? queueMicrotask.bind(typeof window !== 'undefined' ? window : global)\n // reuse resolved promise, and allocate it lazily\n : cb => (promise || (promise = Promise.resolve()))\n .then(cb)\n .catch(err => setTimeout(() => { throw err }, 0))\n", "'use strict'\n\nconst queueMicrotask = require('queue-microtask')\n\nmodule.exports = function (fn, ...args) {\n if (args.length === 0) {\n queueMicrotask(fn)\n } else {\n queueMicrotask(() => fn(...args))\n }\n}\n", "'use strict'\n\nconst { AbstractIterator, AbstractKeyIterator, AbstractValueIterator } = require('../abstract-iterator')\n\nconst kUnfix = Symbol('unfix')\nconst kIterator = Symbol('iterator')\nconst kHandleOne = Symbol('handleOne')\nconst kHandleMany = Symbol('handleMany')\nconst kCallback = Symbol('callback')\n\n// TODO: unfix natively if db supports it\nclass AbstractSublevelIterator extends AbstractIterator {\n constructor (db, options, iterator, unfix) {\n super(db, options)\n\n this[kIterator] = iterator\n this[kUnfix] = unfix\n this[kHandleOne] = this[kHandleOne].bind(this)\n this[kHandleMany] = this[kHandleMany].bind(this)\n this[kCallback] = null\n }\n\n [kHandleOne] (err, key, value) {\n const callback = this[kCallback]\n if (err) return callback(err)\n if (key !== undefined) key = this[kUnfix](key)\n callback(err, key, value)\n }\n\n [kHandleMany] (err, entries) {\n const callback = this[kCallback]\n if (err) return callback(err)\n\n for (const entry of entries) {\n const key = entry[0]\n if (key !== undefined) entry[0] = this[kUnfix](key)\n }\n\n callback(err, entries)\n }\n}\n\nclass AbstractSublevelKeyIterator extends AbstractKeyIterator {\n constructor (db, options, iterator, unfix) {\n super(db, options)\n\n this[kIterator] = iterator\n this[kUnfix] = unfix\n this[kHandleOne] = this[kHandleOne].bind(this)\n this[kHandleMany] = this[kHandleMany].bind(this)\n this[kCallback] = null\n }\n\n [kHandleOne] (err, key) {\n const callback = this[kCallback]\n if (err) return callback(err)\n if (key !== undefined) key = this[kUnfix](key)\n callback(err, key)\n }\n\n [kHandleMany] (err, keys) {\n const callback = this[kCallback]\n if (err) return callback(err)\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n if (key !== undefined) keys[i] = this[kUnfix](key)\n }\n\n callback(err, keys)\n }\n}\n\nclass AbstractSublevelValueIterator extends AbstractValueIterator {\n constructor (db, options, iterator) {\n super(db, options)\n this[kIterator] = iterator\n }\n}\n\nfor (const Iterator of [AbstractSublevelIterator, AbstractSublevelKeyIterator]) {\n Iterator.prototype._next = function (callback) {\n this[kCallback] = callback\n this[kIterator].next(this[kHandleOne])\n }\n\n Iterator.prototype._nextv = function (size, options, callback) {\n this[kCallback] = callback\n this[kIterator].nextv(size, options, this[kHandleMany])\n }\n\n Iterator.prototype._all = function (options, callback) {\n this[kCallback] = callback\n this[kIterator].all(options, this[kHandleMany])\n }\n}\n\nfor (const Iterator of [AbstractSublevelValueIterator]) {\n Iterator.prototype._next = function (callback) {\n this[kIterator].next(callback)\n }\n\n Iterator.prototype._nextv = function (size, options, callback) {\n this[kIterator].nextv(size, options, callback)\n }\n\n Iterator.prototype._all = function (options, callback) {\n this[kIterator].all(options, callback)\n }\n}\n\nfor (const Iterator of [AbstractSublevelIterator, AbstractSublevelKeyIterator, AbstractSublevelValueIterator]) {\n Iterator.prototype._seek = function (target, options) {\n this[kIterator].seek(target, options)\n }\n\n Iterator.prototype._close = function (callback) {\n this[kIterator].close(callback)\n }\n}\n\nexports.AbstractSublevelIterator = AbstractSublevelIterator\nexports.AbstractSublevelKeyIterator = AbstractSublevelKeyIterator\nexports.AbstractSublevelValueIterator = AbstractSublevelValueIterator\n", "'use strict'\n\nconst ModuleError = require('module-error')\nconst { Buffer } = require('buffer') || {}\nconst {\n AbstractSublevelIterator,\n AbstractSublevelKeyIterator,\n AbstractSublevelValueIterator\n} = require('./abstract-sublevel-iterator')\n\nconst kPrefix = Symbol('prefix')\nconst kUpperBound = Symbol('upperBound')\nconst kPrefixRange = Symbol('prefixRange')\nconst kParent = Symbol('parent')\nconst kUnfix = Symbol('unfix')\n\nconst textEncoder = new TextEncoder()\nconst defaults = { separator: '!' }\n\n// Wrapped to avoid circular dependency\nmodule.exports = function ({ AbstractLevel }) {\n class AbstractSublevel extends AbstractLevel {\n static defaults (options) {\n // To help migrating from subleveldown to abstract-level\n if (typeof options === 'string') {\n throw new ModuleError('The subleveldown string shorthand for { separator } has been removed', {\n code: 'LEVEL_LEGACY'\n })\n } else if (options && options.open) {\n throw new ModuleError('The subleveldown open option has been removed', {\n code: 'LEVEL_LEGACY'\n })\n }\n\n if (options == null) {\n return defaults\n } else if (!options.separator) {\n return { ...options, separator: '!' }\n } else {\n return options\n }\n }\n\n // TODO: add autoClose option, which if true, does parent.attachResource(this)\n constructor (db, name, options) {\n // Don't forward AbstractSublevel options to AbstractLevel\n const { separator, manifest, ...forward } = AbstractSublevel.defaults(options)\n name = trim(name, separator)\n\n // Reserve one character between separator and name to give us an upper bound\n const reserved = separator.charCodeAt(0) + 1\n const parent = db[kParent] || db\n\n // Keys should sort like ['!a!', '!a!!a!', '!a\"', '!aa!', '!b!'].\n // Use ASCII for consistent length between string, Buffer and Uint8Array\n if (!textEncoder.encode(name).every(x => x > reserved && x < 127)) {\n throw new ModuleError(`Prefix must use bytes > ${reserved} < ${127}`, {\n code: 'LEVEL_INVALID_PREFIX'\n })\n }\n\n super(mergeManifests(parent, manifest), forward)\n\n const prefix = (db.prefix || '') + separator + name + separator\n const upperBound = prefix.slice(0, -1) + String.fromCharCode(reserved)\n\n this[kParent] = parent\n this[kPrefix] = new MultiFormat(prefix)\n this[kUpperBound] = new MultiFormat(upperBound)\n this[kUnfix] = new Unfixer()\n\n this.nextTick = parent.nextTick\n }\n\n prefixKey (key, keyFormat) {\n if (keyFormat === 'utf8') {\n return this[kPrefix].utf8 + key\n } else if (key.byteLength === 0) {\n // Fast path for empty key (no copy)\n return this[kPrefix][keyFormat]\n } else if (keyFormat === 'view') {\n const view = this[kPrefix].view\n const result = new Uint8Array(view.byteLength + key.byteLength)\n\n result.set(view, 0)\n result.set(key, view.byteLength)\n\n return result\n } else {\n const buffer = this[kPrefix].buffer\n return Buffer.concat([buffer, key], buffer.byteLength + key.byteLength)\n }\n }\n\n // Not exposed for now.\n [kPrefixRange] (range, keyFormat) {\n if (range.gte !== undefined) {\n range.gte = this.prefixKey(range.gte, keyFormat)\n } else if (range.gt !== undefined) {\n range.gt = this.prefixKey(range.gt, keyFormat)\n } else {\n range.gte = this[kPrefix][keyFormat]\n }\n\n if (range.lte !== undefined) {\n range.lte = this.prefixKey(range.lte, keyFormat)\n } else if (range.lt !== undefined) {\n range.lt = this.prefixKey(range.lt, keyFormat)\n } else {\n range.lte = this[kUpperBound][keyFormat]\n }\n }\n\n get prefix () {\n return this[kPrefix].utf8\n }\n\n get db () {\n return this[kParent]\n }\n\n _open (options, callback) {\n // The parent db must open itself or be (re)opened by the user because\n // a sublevel should not initiate state changes on the rest of the db.\n this[kParent].open({ passive: true }, callback)\n }\n\n _put (key, value, options, callback) {\n this[kParent].put(key, value, options, callback)\n }\n\n _get (key, options, callback) {\n this[kParent].get(key, options, callback)\n }\n\n _getMany (keys, options, callback) {\n this[kParent].getMany(keys, options, callback)\n }\n\n _del (key, options, callback) {\n this[kParent].del(key, options, callback)\n }\n\n _batch (operations, options, callback) {\n this[kParent].batch(operations, options, callback)\n }\n\n _clear (options, callback) {\n // TODO (refactor): move to AbstractLevel\n this[kPrefixRange](options, options.keyEncoding)\n this[kParent].clear(options, callback)\n }\n\n _iterator (options) {\n // TODO (refactor): move to AbstractLevel\n this[kPrefixRange](options, options.keyEncoding)\n const iterator = this[kParent].iterator(options)\n const unfix = this[kUnfix].get(this[kPrefix].utf8.length, options.keyEncoding)\n return new AbstractSublevelIterator(this, options, iterator, unfix)\n }\n\n _keys (options) {\n this[kPrefixRange](options, options.keyEncoding)\n const iterator = this[kParent].keys(options)\n const unfix = this[kUnfix].get(this[kPrefix].utf8.length, options.keyEncoding)\n return new AbstractSublevelKeyIterator(this, options, iterator, unfix)\n }\n\n _values (options) {\n this[kPrefixRange](options, options.keyEncoding)\n const iterator = this[kParent].values(options)\n return new AbstractSublevelValueIterator(this, options, iterator)\n }\n }\n\n return { AbstractSublevel }\n}\n\nconst mergeManifests = function (parent, manifest) {\n return {\n // Inherit manifest of parent db\n ...parent.supports,\n\n // Disable unsupported features\n createIfMissing: false,\n errorIfExists: false,\n\n // Unset additional events because we're not forwarding them\n events: {},\n\n // Unset additional methods (like approximateSize) which we can't support here unless\n // the AbstractSublevel class is overridden by an implementation of `abstract-level`.\n additionalMethods: {},\n\n // Inherit manifest of custom AbstractSublevel subclass. Such a class is not\n // allowed to override encodings.\n ...manifest,\n\n encodings: {\n utf8: supportsEncoding(parent, 'utf8'),\n buffer: supportsEncoding(parent, 'buffer'),\n view: supportsEncoding(parent, 'view')\n }\n }\n}\n\nconst supportsEncoding = function (parent, encoding) {\n // Prefer a non-transcoded encoding for optimal performance\n return parent.supports.encodings[encoding]\n ? parent.keyEncoding(encoding).name === encoding\n : false\n}\n\nclass MultiFormat {\n constructor (key) {\n this.utf8 = key\n this.view = textEncoder.encode(key)\n this.buffer = Buffer ? Buffer.from(this.view.buffer, 0, this.view.byteLength) : {}\n }\n}\n\nclass Unfixer {\n constructor () {\n this.cache = new Map()\n }\n\n get (prefixLength, keyFormat) {\n let unfix = this.cache.get(keyFormat)\n\n if (unfix === undefined) {\n if (keyFormat === 'view') {\n unfix = function (prefixLength, key) {\n // Avoid Uint8Array#slice() because it copies\n return key.subarray(prefixLength)\n }.bind(null, prefixLength)\n } else {\n unfix = function (prefixLength, key) {\n // Avoid Buffer#subarray() because it's slow\n return key.slice(prefixLength)\n }.bind(null, prefixLength)\n }\n\n this.cache.set(keyFormat, unfix)\n }\n\n return unfix\n }\n}\n\nconst trim = function (str, char) {\n let start = 0\n let end = str.length\n\n while (start < end && str[start] === char) start++\n while (end > start && str[end - 1] === char) end--\n\n return str.slice(start, end)\n}\n", "'use strict'\n\nconst { supports } = require('level-supports')\nconst { Transcoder } = require('level-transcoder')\nconst { EventEmitter } = require('events')\nconst { fromCallback } = require('catering')\nconst ModuleError = require('module-error')\nconst { AbstractIterator } = require('./abstract-iterator')\nconst { DefaultKeyIterator, DefaultValueIterator } = require('./lib/default-kv-iterator')\nconst { DeferredIterator, DeferredKeyIterator, DeferredValueIterator } = require('./lib/deferred-iterator')\nconst { DefaultChainedBatch } = require('./lib/default-chained-batch')\nconst { getCallback, getOptions } = require('./lib/common')\nconst rangeOptions = require('./lib/range-options')\n\nconst kPromise = Symbol('promise')\nconst kLanded = Symbol('landed')\nconst kResources = Symbol('resources')\nconst kCloseResources = Symbol('closeResources')\nconst kOperations = Symbol('operations')\nconst kUndefer = Symbol('undefer')\nconst kDeferOpen = Symbol('deferOpen')\nconst kOptions = Symbol('options')\nconst kStatus = Symbol('status')\nconst kDefaultOptions = Symbol('defaultOptions')\nconst kTranscoder = Symbol('transcoder')\nconst kKeyEncoding = Symbol('keyEncoding')\nconst kValueEncoding = Symbol('valueEncoding')\nconst noop = () => {}\n\nclass AbstractLevel extends EventEmitter {\n constructor (manifest, options) {\n super()\n\n if (typeof manifest !== 'object' || manifest === null) {\n throw new TypeError(\"The first argument 'manifest' must be an object\")\n }\n\n options = getOptions(options)\n const { keyEncoding, valueEncoding, passive, ...forward } = options\n\n this[kResources] = new Set()\n this[kOperations] = []\n this[kDeferOpen] = true\n this[kOptions] = forward\n this[kStatus] = 'opening'\n\n this.supports = supports(manifest, {\n status: true,\n promises: true,\n clear: true,\n getMany: true,\n deferredOpen: true,\n\n // TODO (next major): add seek\n snapshots: manifest.snapshots !== false,\n permanence: manifest.permanence !== false,\n\n // TODO: remove from level-supports because it's always supported\n keyIterator: true,\n valueIterator: true,\n iteratorNextv: true,\n iteratorAll: true,\n\n encodings: manifest.encodings || {},\n events: Object.assign({}, manifest.events, {\n opening: true,\n open: true,\n closing: true,\n closed: true,\n put: true,\n del: true,\n batch: true,\n clear: true\n })\n })\n\n this[kTranscoder] = new Transcoder(formats(this))\n this[kKeyEncoding] = this[kTranscoder].encoding(keyEncoding || 'utf8')\n this[kValueEncoding] = this[kTranscoder].encoding(valueEncoding || 'utf8')\n\n // Add custom and transcoder encodings to manifest\n for (const encoding of this[kTranscoder].encodings()) {\n if (!this.supports.encodings[encoding.commonName]) {\n this.supports.encodings[encoding.commonName] = true\n }\n }\n\n this[kDefaultOptions] = {\n empty: Object.freeze({}),\n entry: Object.freeze({\n keyEncoding: this[kKeyEncoding].commonName,\n valueEncoding: this[kValueEncoding].commonName\n }),\n key: Object.freeze({\n keyEncoding: this[kKeyEncoding].commonName\n })\n }\n\n // Let subclass finish its constructor\n this.nextTick(() => {\n if (this[kDeferOpen]) {\n this.open({ passive: false }, noop)\n }\n })\n }\n\n get status () {\n return this[kStatus]\n }\n\n keyEncoding (encoding) {\n return this[kTranscoder].encoding(encoding != null ? encoding : this[kKeyEncoding])\n }\n\n valueEncoding (encoding) {\n return this[kTranscoder].encoding(encoding != null ? encoding : this[kValueEncoding])\n }\n\n open (options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n\n options = { ...this[kOptions], ...getOptions(options) }\n\n options.createIfMissing = options.createIfMissing !== false\n options.errorIfExists = !!options.errorIfExists\n\n const maybeOpened = (err) => {\n if (this[kStatus] === 'closing' || this[kStatus] === 'opening') {\n // Wait until pending state changes are done\n this.once(kLanded, err ? () => maybeOpened(err) : maybeOpened)\n } else if (this[kStatus] !== 'open') {\n callback(new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN',\n cause: err\n }))\n } else {\n callback()\n }\n }\n\n if (options.passive) {\n if (this[kStatus] === 'opening') {\n this.once(kLanded, maybeOpened)\n } else {\n this.nextTick(maybeOpened)\n }\n } else if (this[kStatus] === 'closed' || this[kDeferOpen]) {\n this[kDeferOpen] = false\n this[kStatus] = 'opening'\n this.emit('opening')\n\n this._open(options, (err) => {\n if (err) {\n this[kStatus] = 'closed'\n\n // Resources must be safe to close in any db state\n this[kCloseResources](() => {\n this.emit(kLanded)\n maybeOpened(err)\n })\n\n this[kUndefer]()\n return\n }\n\n this[kStatus] = 'open'\n this[kUndefer]()\n this.emit(kLanded)\n\n // Only emit public event if pending state changes are done\n if (this[kStatus] === 'open') this.emit('open')\n\n // TODO (next major): remove this alias\n if (this[kStatus] === 'open') this.emit('ready')\n\n maybeOpened()\n })\n } else if (this[kStatus] === 'open') {\n this.nextTick(maybeOpened)\n } else {\n this.once(kLanded, () => this.open(options, callback))\n }\n\n return callback[kPromise]\n }\n\n _open (options, callback) {\n this.nextTick(callback)\n }\n\n close (callback) {\n callback = fromCallback(callback, kPromise)\n\n const maybeClosed = (err) => {\n if (this[kStatus] === 'opening' || this[kStatus] === 'closing') {\n // Wait until pending state changes are done\n this.once(kLanded, err ? maybeClosed(err) : maybeClosed)\n } else if (this[kStatus] !== 'closed') {\n callback(new ModuleError('Database is not closed', {\n code: 'LEVEL_DATABASE_NOT_CLOSED',\n cause: err\n }))\n } else {\n callback()\n }\n }\n\n if (this[kStatus] === 'open') {\n this[kStatus] = 'closing'\n this.emit('closing')\n\n const cancel = (err) => {\n this[kStatus] = 'open'\n this[kUndefer]()\n this.emit(kLanded)\n maybeClosed(err)\n }\n\n this[kCloseResources](() => {\n this._close((err) => {\n if (err) return cancel(err)\n\n this[kStatus] = 'closed'\n this[kUndefer]()\n this.emit(kLanded)\n\n // Only emit public event if pending state changes are done\n if (this[kStatus] === 'closed') this.emit('closed')\n\n maybeClosed()\n })\n })\n } else if (this[kStatus] === 'closed') {\n this.nextTick(maybeClosed)\n } else {\n this.once(kLanded, () => this.close(callback))\n }\n\n return callback[kPromise]\n }\n\n [kCloseResources] (callback) {\n if (this[kResources].size === 0) {\n return this.nextTick(callback)\n }\n\n let pending = this[kResources].size\n let sync = true\n\n const next = () => {\n if (--pending === 0) {\n // We don't have tests for generic resources, so dezalgo\n if (sync) this.nextTick(callback)\n else callback()\n }\n }\n\n // In parallel so that all resources know they are closed\n for (const resource of this[kResources]) {\n resource.close(next)\n }\n\n sync = false\n this[kResources].clear()\n }\n\n _close (callback) {\n this.nextTick(callback)\n }\n\n get (key, options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].entry)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.get(key, options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n const err = this._checkKey(key)\n\n if (err) {\n this.nextTick(callback, err)\n return callback[kPromise]\n }\n\n const keyEncoding = this.keyEncoding(options.keyEncoding)\n const valueEncoding = this.valueEncoding(options.valueEncoding)\n const keyFormat = keyEncoding.format\n const valueFormat = valueEncoding.format\n\n // Forward encoding options to the underlying store\n if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) {\n // Avoid spread operator because of https://bugs.chromium.org/p/chromium/issues/detail?id=1204540\n options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat })\n }\n\n this._get(this.prefixKey(keyEncoding.encode(key), keyFormat), options, (err, value) => {\n if (err) {\n // Normalize not found error for backwards compatibility with abstract-leveldown and level(up)\n if (err.code === 'LEVEL_NOT_FOUND' || err.notFound || /NotFound/i.test(err)) {\n if (!err.code) err.code = 'LEVEL_NOT_FOUND' // Preferred way going forward\n if (!err.notFound) err.notFound = true // Same as level-errors\n if (!err.status) err.status = 404 // Same as level-errors\n }\n\n return callback(err)\n }\n\n try {\n value = valueEncoding.decode(value)\n } catch (err) {\n return callback(new ModuleError('Could not decode value', {\n code: 'LEVEL_DECODE_ERROR',\n cause: err\n }))\n }\n\n callback(null, value)\n })\n\n return callback[kPromise]\n }\n\n _get (key, options, callback) {\n this.nextTick(callback, new Error('NotFound'))\n }\n\n getMany (keys, options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].entry)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.getMany(keys, options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n if (!Array.isArray(keys)) {\n this.nextTick(callback, new TypeError(\"The first argument 'keys' must be an array\"))\n return callback[kPromise]\n }\n\n if (keys.length === 0) {\n this.nextTick(callback, null, [])\n return callback[kPromise]\n }\n\n const keyEncoding = this.keyEncoding(options.keyEncoding)\n const valueEncoding = this.valueEncoding(options.valueEncoding)\n const keyFormat = keyEncoding.format\n const valueFormat = valueEncoding.format\n\n // Forward encoding options\n if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) {\n options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat })\n }\n\n const mappedKeys = new Array(keys.length)\n\n for (let i = 0; i < keys.length; i++) {\n const key = keys[i]\n const err = this._checkKey(key)\n\n if (err) {\n this.nextTick(callback, err)\n return callback[kPromise]\n }\n\n mappedKeys[i] = this.prefixKey(keyEncoding.encode(key), keyFormat)\n }\n\n this._getMany(mappedKeys, options, (err, values) => {\n if (err) return callback(err)\n\n try {\n for (let i = 0; i < values.length; i++) {\n if (values[i] !== undefined) {\n values[i] = valueEncoding.decode(values[i])\n }\n }\n } catch (err) {\n return callback(new ModuleError(`Could not decode one or more of ${values.length} value(s)`, {\n code: 'LEVEL_DECODE_ERROR',\n cause: err\n }))\n }\n\n callback(null, values)\n })\n\n return callback[kPromise]\n }\n\n _getMany (keys, options, callback) {\n this.nextTick(callback, null, new Array(keys.length).fill(undefined))\n }\n\n put (key, value, options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].entry)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.put(key, value, options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n const err = this._checkKey(key) || this._checkValue(value)\n\n if (err) {\n this.nextTick(callback, err)\n return callback[kPromise]\n }\n\n const keyEncoding = this.keyEncoding(options.keyEncoding)\n const valueEncoding = this.valueEncoding(options.valueEncoding)\n const keyFormat = keyEncoding.format\n const valueFormat = valueEncoding.format\n\n // Forward encoding options\n if (options.keyEncoding !== keyFormat || options.valueEncoding !== valueFormat) {\n options = Object.assign({}, options, { keyEncoding: keyFormat, valueEncoding: valueFormat })\n }\n\n const mappedKey = this.prefixKey(keyEncoding.encode(key), keyFormat)\n const mappedValue = valueEncoding.encode(value)\n\n this._put(mappedKey, mappedValue, options, (err) => {\n if (err) return callback(err)\n this.emit('put', key, value)\n callback()\n })\n\n return callback[kPromise]\n }\n\n _put (key, value, options, callback) {\n this.nextTick(callback)\n }\n\n del (key, options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].key)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.del(key, options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n const err = this._checkKey(key)\n\n if (err) {\n this.nextTick(callback, err)\n return callback[kPromise]\n }\n\n const keyEncoding = this.keyEncoding(options.keyEncoding)\n const keyFormat = keyEncoding.format\n\n // Forward encoding options\n if (options.keyEncoding !== keyFormat) {\n options = Object.assign({}, options, { keyEncoding: keyFormat })\n }\n\n this._del(this.prefixKey(keyEncoding.encode(key), keyFormat), options, (err) => {\n if (err) return callback(err)\n this.emit('del', key)\n callback()\n })\n\n return callback[kPromise]\n }\n\n _del (key, options, callback) {\n this.nextTick(callback)\n }\n\n batch (operations, options, callback) {\n if (!arguments.length) {\n if (this[kStatus] === 'opening') return new DefaultChainedBatch(this)\n if (this[kStatus] !== 'open') {\n throw new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN'\n })\n }\n return this._chainedBatch()\n }\n\n if (typeof operations === 'function') callback = operations\n else callback = getCallback(options, callback)\n\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].empty)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.batch(operations, options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n if (!Array.isArray(operations)) {\n this.nextTick(callback, new TypeError(\"The first argument 'operations' must be an array\"))\n return callback[kPromise]\n }\n\n if (operations.length === 0) {\n this.nextTick(callback)\n return callback[kPromise]\n }\n\n const mapped = new Array(operations.length)\n const { keyEncoding: ke, valueEncoding: ve, ...forward } = options\n\n for (let i = 0; i < operations.length; i++) {\n if (typeof operations[i] !== 'object' || operations[i] === null) {\n this.nextTick(callback, new TypeError('A batch operation must be an object'))\n return callback[kPromise]\n }\n\n const op = Object.assign({}, operations[i])\n\n if (op.type !== 'put' && op.type !== 'del') {\n this.nextTick(callback, new TypeError(\"A batch operation must have a type property that is 'put' or 'del'\"))\n return callback[kPromise]\n }\n\n const err = this._checkKey(op.key)\n\n if (err) {\n this.nextTick(callback, err)\n return callback[kPromise]\n }\n\n const db = op.sublevel != null ? op.sublevel : this\n const keyEncoding = db.keyEncoding(op.keyEncoding || ke)\n const keyFormat = keyEncoding.format\n\n op.key = db.prefixKey(keyEncoding.encode(op.key), keyFormat)\n op.keyEncoding = keyFormat\n\n if (op.type === 'put') {\n const valueErr = this._checkValue(op.value)\n\n if (valueErr) {\n this.nextTick(callback, valueErr)\n return callback[kPromise]\n }\n\n const valueEncoding = db.valueEncoding(op.valueEncoding || ve)\n\n op.value = valueEncoding.encode(op.value)\n op.valueEncoding = valueEncoding.format\n }\n\n // Prevent double prefixing\n if (db !== this) {\n op.sublevel = null\n }\n\n mapped[i] = op\n }\n\n this._batch(mapped, forward, (err) => {\n if (err) return callback(err)\n this.emit('batch', operations)\n callback()\n })\n\n return callback[kPromise]\n }\n\n _batch (operations, options, callback) {\n this.nextTick(callback)\n }\n\n sublevel (name, options) {\n return this._sublevel(name, AbstractSublevel.defaults(options))\n }\n\n _sublevel (name, options) {\n return new AbstractSublevel(this, name, options)\n }\n\n prefixKey (key, keyFormat) {\n return key\n }\n\n clear (options, callback) {\n callback = getCallback(options, callback)\n callback = fromCallback(callback, kPromise)\n options = getOptions(options, this[kDefaultOptions].empty)\n\n if (this[kStatus] === 'opening') {\n this.defer(() => this.clear(options, callback))\n return callback[kPromise]\n }\n\n if (maybeError(this, callback)) {\n return callback[kPromise]\n }\n\n const original = options\n const keyEncoding = this.keyEncoding(options.keyEncoding)\n\n options = rangeOptions(options, keyEncoding)\n options.keyEncoding = keyEncoding.format\n\n if (options.limit === 0) {\n this.nextTick(callback)\n } else {\n this._clear(options, (err) => {\n if (err) return callback(err)\n this.emit('clear', original)\n callback()\n })\n }\n\n return callback[kPromise]\n }\n\n _clear (options, callback) {\n this.nextTick(callback)\n }\n\n iterator (options) {\n const keyEncoding = this.keyEncoding(options && options.keyEncoding)\n const valueEncoding = this.valueEncoding(options && options.valueEncoding)\n\n options = rangeOptions(options, keyEncoding)\n options.keys = options.keys !== false\n options.values = options.values !== false\n\n // We need the original encoding options in AbstractIterator in order to decode data\n options[AbstractIterator.keyEncoding] = keyEncoding\n options[AbstractIterator.valueEncoding] = valueEncoding\n\n // Forward encoding options to private API\n options.keyEncoding = keyEncoding.format\n options.valueEncoding = valueEncoding.format\n\n if (this[kStatus] === 'opening') {\n return new DeferredIterator(this, options)\n } else if (this[kStatus] !== 'open') {\n throw new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN'\n })\n }\n\n return this._iterator(options)\n }\n\n _iterator (options) {\n return new AbstractIterator(this, options)\n }\n\n keys (options) {\n // Also include valueEncoding (though unused) because we may fallback to _iterator()\n const keyEncoding = this.keyEncoding(options && options.keyEncoding)\n const valueEncoding = this.valueEncoding(options && options.valueEncoding)\n\n options = rangeOptions(options, keyEncoding)\n\n // We need the original encoding options in AbstractKeyIterator in order to decode data\n options[AbstractIterator.keyEncoding] = keyEncoding\n options[AbstractIterator.valueEncoding] = valueEncoding\n\n // Forward encoding options to private API\n options.keyEncoding = keyEncoding.format\n options.valueEncoding = valueEncoding.format\n\n if (this[kStatus] === 'opening') {\n return new DeferredKeyIterator(this, options)\n } else if (this[kStatus] !== 'open') {\n throw new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN'\n })\n }\n\n return this._keys(options)\n }\n\n _keys (options) {\n return new DefaultKeyIterator(this, options)\n }\n\n values (options) {\n const keyEncoding = this.keyEncoding(options && options.keyEncoding)\n const valueEncoding = this.valueEncoding(options && options.valueEncoding)\n\n options = rangeOptions(options, keyEncoding)\n\n // We need the original encoding options in AbstractValueIterator in order to decode data\n options[AbstractIterator.keyEncoding] = keyEncoding\n options[AbstractIterator.valueEncoding] = valueEncoding\n\n // Forward encoding options to private API\n options.keyEncoding = keyEncoding.format\n options.valueEncoding = valueEncoding.format\n\n if (this[kStatus] === 'opening') {\n return new DeferredValueIterator(this, options)\n } else if (this[kStatus] !== 'open') {\n throw new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN'\n })\n }\n\n return this._values(options)\n }\n\n _values (options) {\n return new DefaultValueIterator(this, options)\n }\n\n defer (fn) {\n if (typeof fn !== 'function') {\n throw new TypeError('The first argument must be a function')\n }\n\n this[kOperations].push(fn)\n }\n\n [kUndefer] () {\n if (this[kOperations].length === 0) {\n return\n }\n\n const operations = this[kOperations]\n this[kOperations] = []\n\n for (const op of operations) {\n op()\n }\n }\n\n // TODO: docs and types\n attachResource (resource) {\n if (typeof resource !== 'object' || resource === null ||\n typeof resource.close !== 'function') {\n throw new TypeError('The first argument must be a resource object')\n }\n\n this[kResources].add(resource)\n }\n\n // TODO: docs and types\n detachResource (resource) {\n this[kResources].delete(resource)\n }\n\n _chainedBatch () {\n return new DefaultChainedBatch(this)\n }\n\n _checkKey (key) {\n if (key === null || key === undefined) {\n return new ModuleError('Key cannot be null or undefined', {\n code: 'LEVEL_INVALID_KEY'\n })\n }\n }\n\n _checkValue (value) {\n if (value === null || value === undefined) {\n return new ModuleError('Value cannot be null or undefined', {\n code: 'LEVEL_INVALID_VALUE'\n })\n }\n }\n}\n\n// Expose browser-compatible nextTick for dependents\n// TODO: after we drop node 10, also use queueMicrotask in node\nAbstractLevel.prototype.nextTick = require('./lib/next-tick')\n\nconst { AbstractSublevel } = require('./lib/abstract-sublevel')({ AbstractLevel })\n\nexports.AbstractLevel = AbstractLevel\nexports.AbstractSublevel = AbstractSublevel\n\nconst maybeError = function (db, callback) {\n if (db[kStatus] !== 'open') {\n db.nextTick(callback, new ModuleError('Database is not open', {\n code: 'LEVEL_DATABASE_NOT_OPEN'\n }))\n return true\n }\n\n return false\n}\n\nconst formats = function (db) {\n return Object.keys(db.supports.encodings)\n .filter(k => !!db.supports.encodings[k])\n}\n", "'use strict'\n\nexports.AbstractLevel = require('./abstract-level').AbstractLevel\nexports.AbstractSublevel = require('./abstract-level').AbstractSublevel\nexports.AbstractIterator = require('./abstract-iterator').AbstractIterator\nexports.AbstractKeyIterator = require('./abstract-iterator').AbstractKeyIterator\nexports.AbstractValueIterator = require('./abstract-iterator').AbstractValueIterator\nexports.AbstractChainedBatch = require('./abstract-chained-batch').AbstractChainedBatch\n", "/*! run-parallel-limit. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */\nmodule.exports = runParallelLimit\n\nconst queueMicrotask = require('queue-microtask')\n\nfunction runParallelLimit (tasks, limit, cb) {\n if (typeof limit !== 'number') throw new Error('second argument must be a Number')\n let results, len, pending, keys, isErrored\n let isSync = true\n let next\n\n if (Array.isArray(tasks)) {\n results = []\n pending = len = tasks.length\n } else {\n keys = Object.keys(tasks)\n results = {}\n pending = len = keys.length\n }\n\n function done (err) {\n function end () {\n if (cb) cb(err, results)\n cb = null\n }\n if (isSync) queueMicrotask(end)\n else end()\n }\n\n function each (i, err, result) {\n results[i] = result\n if (err) isErrored = true\n if (--pending === 0 || err) {\n done(err)\n } else if (!isErrored && next < len) {\n let key\n if (keys) {\n key = keys[next]\n next += 1\n tasks[key](function (err, result) { each(key, err, result) })\n } else {\n key = next\n next += 1\n tasks[key](function (err, result) { each(key, err, result) })\n }\n }\n }\n\n next = limit\n if (!pending) {\n // empty\n done(null)\n } else if (keys) {\n // object\n keys.some(function (key, i) {\n tasks[key](function (err, result) { each(key, err, result) })\n if (i === limit - 1) return true // early return\n return false\n })\n } else {\n // array\n tasks.some(function (task, i) {\n task(function (err, result) { each(i, err, result) })\n if (i === limit - 1) return true // early return\n return false\n })\n }\n\n isSync = false\n}\n", "/* global IDBKeyRange */\n\n'use strict'\n\nmodule.exports = function createKeyRange (options) {\n const lower = options.gte !== undefined ? options.gte : options.gt !== undefined ? options.gt : undefined\n const upper = options.lte !== undefined ? options.lte : options.lt !== undefined ? options.lt : undefined\n const lowerExclusive = options.gte === undefined\n const upperExclusive = options.lte === undefined\n\n if (lower !== undefined && upper !== undefined) {\n return IDBKeyRange.bound(lower, upper, lowerExclusive, upperExclusive)\n } else if (lower !== undefined) {\n return IDBKeyRange.lowerBound(lower, lowerExclusive)\n } else if (upper !== undefined) {\n return IDBKeyRange.upperBound(upper, upperExclusive)\n } else {\n return null\n }\n}\n", "'use strict'\n\nconst textEncoder = new TextEncoder()\n\nmodule.exports = function (data) {\n if (data instanceof Uint8Array) {\n return data\n } else if (data instanceof ArrayBuffer) {\n return new Uint8Array(data)\n } else {\n // Non-binary data stored with an old version (level-js < 5.0.0)\n return textEncoder.encode(data)\n }\n}\n", "'use strict'\n\nconst { AbstractIterator } = require('abstract-level')\nconst createKeyRange = require('./util/key-range')\nconst deserialize = require('./util/deserialize')\n\nconst kCache = Symbol('cache')\nconst kFinished = Symbol('finished')\nconst kOptions = Symbol('options')\nconst kCurrentOptions = Symbol('currentOptions')\nconst kPosition = Symbol('position')\nconst kLocation = Symbol('location')\nconst kFirst = Symbol('first')\nconst emptyOptions = {}\n\nclass Iterator extends AbstractIterator {\n constructor (db, location, options) {\n super(db, options)\n\n this[kCache] = []\n this[kFinished] = this.limit === 0\n this[kOptions] = options\n this[kCurrentOptions] = { ...options }\n this[kPosition] = undefined\n this[kLocation] = location\n this[kFirst] = true\n }\n\n // Note: if called by _all() then size can be Infinity. This is an internal\n // detail; by design AbstractIterator.nextv() does not support Infinity.\n _nextv (size, options, callback) {\n this[kFirst] = false\n\n if (this[kFinished]) {\n return this.nextTick(callback, null, [])\n } else if (this[kCache].length > 0) {\n // TODO: mixing next and nextv is not covered by test suite\n size = Math.min(size, this[kCache].length)\n return this.nextTick(callback, null, this[kCache].splice(0, size))\n }\n\n // Adjust range by what we already visited\n if (this[kPosition] !== undefined) {\n if (this[kOptions].reverse) {\n this[kCurrentOptions].lt = this[kPosition]\n this[kCurrentOptions].lte = undefined\n } else {\n this[kCurrentOptions].gt = this[kPosition]\n this[kCurrentOptions].gte = undefined\n }\n }\n\n let keyRange\n\n try {\n keyRange = createKeyRange(this[kCurrentOptions])\n } catch (_) {\n // The lower key is greater than the upper key.\n // IndexedDB throws an error, but we'll just return 0 results.\n this[kFinished] = true\n return this.nextTick(callback, null, [])\n }\n\n const transaction = this.db.db.transaction([this[kLocation]], 'readonly')\n const store = transaction.objectStore(this[kLocation])\n const entries = []\n\n if (!this[kOptions].reverse) {\n let keys\n let values\n\n const complete = () => {\n // Wait for both requests to complete\n if (keys === undefined || values === undefined) return\n\n const length = Math.max(keys.length, values.length)\n\n if (length === 0 || size === Infinity) {\n this[kFinished] = true\n } else {\n this[kPosition] = keys[length - 1]\n }\n\n // Resize\n entries.length = length\n\n // Merge keys and values\n for (let i = 0; i < length; i++) {\n const key = keys[i]\n const value = values[i]\n\n entries[i] = [\n this[kOptions].keys && key !== undefined ? deserialize(key) : undefined,\n this[kOptions].values && value !== undefined ? deserialize(value) : undefined\n ]\n }\n\n maybeCommit(transaction)\n }\n\n // If keys were not requested and size is Infinity, we don't have to keep\n // track of position and can thus skip getting keys.\n if (this[kOptions].keys || size < Infinity) {\n store.getAllKeys(keyRange, size < Infinity ? size : undefined).onsuccess = (ev) => {\n keys = ev.target.result\n complete()\n }\n } else {\n keys = []\n this.nextTick(complete)\n }\n\n if (this[kOptions].values) {\n store.getAll(keyRange, size < Infinity ? size : undefined).onsuccess = (ev) => {\n values = ev.target.result\n complete()\n }\n } else {\n values = []\n this.nextTick(complete)\n }\n } else {\n // Can't use getAll() in reverse, so use a slower cursor that yields one item at a time\n // TODO: test if all target browsers support openKeyCursor\n const method = !this[kOptions].values && store.openKeyCursor ? 'openKeyCursor' : 'openCursor'\n\n store[method](keyRange, 'prev').onsuccess = (ev) => {\n const cursor = ev.target.result\n\n if (cursor) {\n const { key, value } = cursor\n this[kPosition] = key\n\n entries.push([\n this[kOptions].keys && key !== undefined ? deserialize(key) : undefined,\n this[kOptions].values && value !== undefined ? deserialize(value) : undefined\n ])\n\n if (entries.length < size) {\n cursor.continue()\n } else {\n maybeCommit(transaction)\n }\n } else {\n this[kFinished] = true\n }\n }\n }\n\n // If an error occurs (on the request), the transaction will abort.\n transaction.onabort = () => {\n callback(transaction.error || new Error('aborted by user'))\n callback = null\n }\n\n transaction.oncomplete = () => {\n callback(null, entries)\n callback = null\n }\n }\n\n _next (callback) {\n if (this[kCache].length > 0) {\n const [key, value] = this[kCache].shift()\n this.nextTick(callback, null, key, value)\n } else if (this[kFinished]) {\n this.nextTick(callback)\n } else {\n let size = Math.min(100, this.limit - this.count)\n\n if (this[kFirst]) {\n // It's common to only want one entry initially or after a seek()\n this[kFirst] = false\n size = 1\n }\n\n this._nextv(size, emptyOptions, (err, entries) => {\n if (err) return callback(err)\n this[kCache] = entries\n this._next(callback)\n })\n }\n }\n\n _all (options, callback) {\n this[kFirst] = false\n\n // TODO: mixing next and all is not covered by test suite\n const cache = this[kCache].splice(0, this[kCache].length)\n const size = this.limit - this.count - cache.length\n\n if (size <= 0) {\n return this.nextTick(callback, null, cache)\n }\n\n this._nextv(size, emptyOptions, (err, entries) => {\n if (err) return callback(err)\n if (cache.length > 0) entries = cache.concat(entries)\n callback(null, entries)\n })\n }\n\n _seek (target, options) {\n this[kFirst] = true\n this[kCache] = []\n this[kFinished] = false\n this[kPosition] = undefined\n\n // TODO: not covered by test suite\n this[kCurrentOptions] = { ...this[kOptions] }\n\n let keyRange\n\n try {\n keyRange = createKeyRange(this[kOptions])\n } catch (_) {\n this[kFinished] = true\n return\n }\n\n if (keyRange !== null && !keyRange.includes(target)) {\n this[kFinished] = true\n } else if (this[kOptions].reverse) {\n this[kCurrentOptions].lte = target\n } else {\n this[kCurrentOptions].gte = target\n }\n }\n}\n\nexports.Iterator = Iterator\n\nfunction maybeCommit (transaction) {\n // Commit (meaning close) now instead of waiting for auto-commit\n if (typeof transaction.commit === 'function') {\n transaction.commit()\n }\n}\n", "'use strict'\n\nmodule.exports = function clear (db, location, keyRange, options, callback) {\n if (options.limit === 0) return db.nextTick(callback)\n\n const transaction = db.db.transaction([location], 'readwrite')\n const store = transaction.objectStore(location)\n let count = 0\n\n transaction.oncomplete = function () {\n callback()\n }\n\n transaction.onabort = function () {\n callback(transaction.error || new Error('aborted by user'))\n }\n\n // A key cursor is faster (skips reading values) but not supported by IE\n // TODO: we no longer support IE. Test others\n const method = store.openKeyCursor ? 'openKeyCursor' : 'openCursor'\n const direction = options.reverse ? 'prev' : 'next'\n\n store[method](keyRange, direction).onsuccess = function (ev) {\n const cursor = ev.target.result\n\n if (cursor) {\n // Wait for a request to complete before continuing, saving CPU.\n store.delete(cursor.key).onsuccess = function () {\n if (options.limit <= 0 || ++count < options.limit) {\n cursor.continue()\n }\n }\n }\n }\n}\n", "/* global indexedDB */\n\n'use strict'\n\nconst { AbstractLevel } = require('abstract-level')\nconst ModuleError = require('module-error')\nconst parallel = require('run-parallel-limit')\nconst { fromCallback } = require('catering')\nconst { Iterator } = require('./iterator')\nconst deserialize = require('./util/deserialize')\nconst clear = require('./util/clear')\nconst createKeyRange = require('./util/key-range')\n\n// Keep as-is for compatibility with existing level-js databases\nconst DEFAULT_PREFIX = 'level-js-'\n\nconst kIDB = Symbol('idb')\nconst kNamePrefix = Symbol('namePrefix')\nconst kLocation = Symbol('location')\nconst kVersion = Symbol('version')\nconst kStore = Symbol('store')\nconst kOnComplete = Symbol('onComplete')\nconst kPromise = Symbol('promise')\n\nclass BrowserLevel extends AbstractLevel {\n constructor (location, options, _) {\n // To help migrating to abstract-level\n if (typeof options === 'function' || typeof _ === 'function') {\n throw new ModuleError('The levelup-style callback argument has been removed', {\n code: 'LEVEL_LEGACY'\n })\n }\n\n const { prefix, version, ...forward } = options || {}\n\n super({\n encodings: { view: true },\n snapshots: false,\n createIfMissing: false,\n errorIfExists: false,\n seek: true\n }, forward)\n\n if (typeof location !== 'string') {\n throw new Error('constructor requires a location string argument')\n }\n\n // TODO (next major): remove default prefix\n this[kLocation] = location\n this[kNamePrefix] = prefix == null ? DEFAULT_PREFIX : prefix\n this[kVersion] = parseInt(version || 1, 10)\n this[kIDB] = null\n }\n\n get location () {\n return this[kLocation]\n }\n\n get namePrefix () {\n return this[kNamePrefix]\n }\n\n get version () {\n return this[kVersion]\n }\n\n // Exposed for backwards compat and unit tests\n get db () {\n return this[kIDB]\n }\n\n get type () {\n return 'browser-level'\n }\n\n _open (options, callback) {\n const req = indexedDB.open(this[kNamePrefix] + this[kLocation], this[kVersion])\n\n req.onerror = function () {\n callback(req.error || new Error('unknown error'))\n }\n\n req.onsuccess = () => {\n this[kIDB] = req.result\n callback()\n }\n\n req.onupgradeneeded = (ev) => {\n const db = ev.target.result\n\n if (!db.objectStoreNames.contains(this[kLocation])) {\n db.createObjectStore(this[kLocation])\n }\n }\n }\n\n [kStore] (mode) {\n const transaction = this[kIDB].transaction([this[kLocation]], mode)\n return transaction.objectStore(this[kLocation])\n }\n\n [kOnComplete] (request, callback) {\n const transaction = request.transaction\n\n // Take advantage of the fact that a non-canceled request error aborts\n // the transaction. I.e. no need to listen for \"request.onerror\".\n transaction.onabort = function () {\n callback(transaction.error || new Error('aborted by user'))\n }\n\n transaction.oncomplete = function () {\n callback(null, request.result)\n }\n }\n\n _get (key, options, callback) {\n const store = this[kStore]('readonly')\n let req\n\n try {\n req = store.get(key)\n } catch (err) {\n return this.nextTick(callback, err)\n }\n\n this[kOnComplete](req, function (err, value) {\n if (err) return callback(err)\n\n if (value === undefined) {\n return callback(new ModuleError('Entry not found', {\n code: 'LEVEL_NOT_FOUND'\n }))\n }\n\n callback(null, deserialize(value))\n })\n }\n\n _getMany (keys, options, callback) {\n const store = this[kStore]('readonly')\n const tasks = keys.map((key) => (next) => {\n let request\n\n try {\n request = store.get(key)\n } catch (err) {\n return next(err)\n }\n\n request.onsuccess = () => {\n const value = request.result\n next(null, value === undefined ? value : deserialize(value))\n }\n\n request.onerror = (ev) => {\n ev.stopPropagation()\n next(request.error)\n }\n })\n\n parallel(tasks, 16, callback)\n }\n\n _del (key, options, callback) {\n const store = this[kStore]('readwrite')\n let req\n\n try {\n req = store.delete(key)\n } catch (err) {\n return this.nextTick(callback, err)\n }\n\n this[kOnComplete](req, callback)\n }\n\n _put (key, value, options, callback) {\n const store = this[kStore]('readwrite')\n let req\n\n try {\n // Will throw a DataError or DataCloneError if the environment\n // does not support serializing the key or value respectively.\n req = store.put(value, key)\n } catch (err) {\n return this.nextTick(callback, err)\n }\n\n this[kOnComplete](req, callback)\n }\n\n // TODO: implement key and value iterators\n _iterator (options) {\n return new Iterator(this, this[kLocation], options)\n }\n\n _batch (operations, options, callback) {\n const store = this[kStore]('readwrite')\n const transaction = store.transaction\n let index = 0\n let error\n\n transaction.onabort = function () {\n callback(error || transaction.error || new Error('aborted by user'))\n }\n\n transaction.oncomplete = function () {\n callback()\n }\n\n // Wait for a request to complete before making the next, saving CPU.\n function loop () {\n const op = operations[index++]\n const key = op.key\n\n let req\n\n try {\n req = op.type === 'del' ? store.delete(key) : store.put(op.value, key)\n } catch (err) {\n error = err\n transaction.abort()\n return\n }\n\n if (index < operations.length) {\n req.onsuccess = loop\n } else if (typeof transaction.commit === 'function') {\n // Commit now instead of waiting for auto-commit\n transaction.commit()\n }\n }\n\n loop()\n }\n\n _clear (options, callback) {\n let keyRange\n let req\n\n try {\n keyRange = createKeyRange(options)\n } catch (e) {\n // The lower key is greater than the upper key.\n // IndexedDB throws an error, but we'll just do nothing.\n return this.nextTick(callback)\n }\n\n if (options.limit >= 0) {\n // IDBObjectStore#delete(range) doesn't have such an option.\n // Fall back to cursor-based implementation.\n return clear(this, this[kLocation], keyRange, options, callback)\n }\n\n try {\n const store = this[kStore]('readwrite')\n req = keyRange ? store.delete(keyRange) : store.clear()\n } catch (err) {\n return this.nextTick(callback, err)\n }\n\n this[kOnComplete](req, callback)\n }\n\n _close (callback) {\n this[kIDB].close()\n this.nextTick(callback)\n }\n}\n\nBrowserLevel.destroy = function (location, prefix, callback) {\n if (typeof prefix === 'function') {\n callback = prefix\n prefix = DEFAULT_PREFIX\n }\n\n callback = fromCallback(callback, kPromise)\n const request = indexedDB.deleteDatabase(prefix + location)\n\n request.onsuccess = function () {\n callback()\n }\n\n request.onerror = function (err) {\n callback(err)\n }\n\n return callback[kPromise]\n}\n\nexports.BrowserLevel = BrowserLevel\n", "exports.Level = require('browser-level').BrowserLevel\n", "import { SCHEMES } from \"./uri\";\n\nimport http from \"./schemes/http\";\nSCHEMES[http.scheme] = http;\n\nimport https from \"./schemes/https\";\nSCHEMES[https.scheme] = https;\n\nimport ws from \"./schemes/ws\";\nSCHEMES[ws.scheme] = ws;\n\nimport wss from \"./schemes/wss\";\nSCHEMES[wss.scheme] = wss;\n\nimport mailto from \"./schemes/mailto\";\nSCHEMES[mailto.scheme] = mailto;\n\nimport urn from \"./schemes/urn\";\nSCHEMES[urn.scheme] = urn;\n\nimport uuid from \"./schemes/urn-uuid\";\nSCHEMES[uuid.scheme] = uuid;\n\nexport * from \"./uri\";\n", "import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport { URNComponents } from \"./urn\";\nimport { SCHEMES } from \"../uri\";\n\nexport interface UUIDComponents extends URNComponents {\n\tuuid?: string;\n}\n\nconst UUID = /^[0-9A-Fa-f]{8}(?:\\-[0-9A-Fa-f]{4}){3}\\-[0-9A-Fa-f]{12}$/;\nconst UUID_PARSE = /^[0-9A-Fa-f\\-]{36}/;\n\n//RFC 4122\nconst handler:URISchemeHandler<UUIDComponents, URIOptions, URNComponents> = {\n\tscheme : \"urn:uuid\",\n\n\tparse : function (urnComponents:URNComponents, options:URIOptions):UUIDComponents {\n\t\tconst uuidComponents = urnComponents as UUIDComponents;\n\t\tuuidComponents.uuid = uuidComponents.nss;\n\t\tuuidComponents.nss = undefined;\n\n\t\tif (!options.tolerant && (!uuidComponents.uuid || !uuidComponents.uuid.match(UUID))) {\n\t\t\tuuidComponents.error = uuidComponents.error || \"UUID is not valid.\";\n\t\t}\n\n\t\treturn uuidComponents;\n\t},\n\n\tserialize : function (uuidComponents:UUIDComponents, options:URIOptions):URNComponents {\n\t\tconst urnComponents = uuidComponents as URNComponents;\n\t\t//normalize UUID\n\t\turnComponents.nss = (uuidComponents.uuid || \"\").toLowerCase();\n\t\treturn urnComponents;\n\t},\n};\n\nexport default handler;", "import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport { pctEncChar, SCHEMES } from \"../uri\";\n\nexport interface URNComponents extends URIComponents {\n\tnid?:string;\n\tnss?:string;\n}\n\nexport interface URNOptions extends URIOptions {\n\tnid?:string;\n}\n\nconst NID$ = \"(?:[0-9A-Za-z][0-9A-Za-z\\\\-]{1,31})\";\nconst PCT_ENCODED$ = \"(?:\\\\%[0-9A-Fa-f]{2})\";\nconst TRANS$$ = \"[0-9A-Za-z\\\\(\\\\)\\\\+\\\\,\\\\-\\\\.\\\\:\\\\=\\\\@\\\\;\\\\$\\\\_\\\\!\\\\*\\\\'\\\\/\\\\?\\\\#]\";\nconst NSS$ = \"(?:(?:\" + PCT_ENCODED$ + \"|\" + TRANS$$ + \")+)\";\nconst URN_SCHEME = new RegExp(\"^urn\\\\:(\" + NID$ + \")$\");\nconst URN_PATH = new RegExp(\"^(\" + NID$ + \")\\\\:(\" + NSS$ + \")$\");\nconst URN_PARSE = /^([^\\:]+)\\:(.*)/;\nconst URN_EXCLUDED = /[\\x00-\\x20\\\\\\\"\\&\\<\\>\\[\\]\\^\\`\\{\\|\\}\\~\\x7F-\\xFF]/g;\n\n//RFC 2141\nconst handler:URISchemeHandler<URNComponents,URNOptions> = {\n\tscheme : \"urn\",\n\n\tparse : function (components:URIComponents, options:URNOptions):URNComponents {\n\t\tconst matches = components.path && components.path.match(URN_PARSE);\n\t\tlet urnComponents = components as URNComponents;\n\n\t\tif (matches) {\n\t\t\tconst scheme = options.scheme || urnComponents.scheme || \"urn\";\n\t\t\tconst nid = matches[1].toLowerCase();\n\t\t\tconst nss = matches[2];\n\t\t\tconst urnScheme = `${scheme}:${options.nid || nid}`;\n\t\t\tconst schemeHandler = SCHEMES[urnScheme];\n\n\t\t\turnComponents.nid = nid;\n\t\t\turnComponents.nss = nss;\n\t\t\turnComponents.path = undefined;\n\n\t\t\tif (schemeHandler) {\n\t\t\t\turnComponents = schemeHandler.parse(urnComponents, options) as URNComponents;\n\t\t\t}\n\t\t} else {\n\t\t\turnComponents.error = urnComponents.error || \"URN can not be parsed.\";\n\t\t}\n\n\t\treturn urnComponents;\n\t},\n\n\tserialize : function (urnComponents:URNComponents, options:URNOptions):URIComponents {\n\t\tconst scheme = options.scheme || urnComponents.scheme || \"urn\";\n\t\tconst nid = urnComponents.nid;\n\t\tconst urnScheme = `${scheme}:${options.nid || nid}`;\n\t\tconst schemeHandler = SCHEMES[urnScheme];\n\n\t\tif (schemeHandler) {\n\t\t\turnComponents = schemeHandler.serialize(urnComponents, options) as URNComponents;\n\t\t}\n\n\t\tconst uriComponents = urnComponents as URIComponents;\n\t\tconst nss = urnComponents.nss;\n\t\turiComponents.path = `${nid || options.nid}:${nss}`;\n\n\t\treturn uriComponents;\n\t},\n};\n\nexport default handler;", "import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport { pctEncChar, pctDecChars, unescapeComponent } from \"../uri\";\nimport punycode from \"punycode\";\nimport { merge, subexp, toUpperCase, toArray } from \"../util\";\n\nexport interface MailtoHeaders {\n\t[hfname:string]:string\n}\n\nexport interface MailtoComponents extends URIComponents {\n\tto:Array<string>,\n\theaders?:MailtoHeaders,\n\tsubject?:string,\n\tbody?:string\n}\n\nconst O:MailtoHeaders = {};\nconst isIRI = true;\n\n//RFC 3986\nconst UNRESERVED$$ = \"[A-Za-z0-9\\\\-\\\\.\\\\_\\\\~\" + (isIRI ? \"\\\\xA0-\\\\u200D\\\\u2010-\\\\u2029\\\\u202F-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF\" : \"\") + \"]\";\nconst HEXDIG$$ = \"[0-9A-Fa-f]\"; //case-insensitive\nconst PCT_ENCODED$ = subexp(subexp(\"%[EFef]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%[89A-Fa-f]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%\" + HEXDIG$$ + HEXDIG$$)); //expanded\n\n//RFC 5322, except these symbols as per RFC 6068: @ : / ? # [ ] & ; =\n//const ATEXT$$ = \"[A-Za-z0-9\\\\!\\\\#\\\\$\\\\%\\\\&\\\\'\\\\*\\\\+\\\\-\\\\/\\\\=\\\\?\\\\^\\\\_\\\\`\\\\{\\\\|\\\\}\\\\~]\";\n//const WSP$$ = \"[\\\\x20\\\\x09]\";\n//const OBS_QTEXT$$ = \"[\\\\x01-\\\\x08\\\\x0B\\\\x0C\\\\x0E-\\\\x1F\\\\x7F]\"; //(%d1-8 / %d11-12 / %d14-31 / %d127)\n//const QTEXT$$ = merge(\"[\\\\x21\\\\x23-\\\\x5B\\\\x5D-\\\\x7E]\", OBS_QTEXT$$); //%d33 / %d35-91 / %d93-126 / obs-qtext\n//const VCHAR$$ = \"[\\\\x21-\\\\x7E]\";\n//const WSP$$ = \"[\\\\x20\\\\x09]\";\n//const OBS_QP$ = subexp(\"\\\\\\\\\" + merge(\"[\\\\x00\\\\x0D\\\\x0A]\", OBS_QTEXT$$)); //%d0 / CR / LF / obs-qtext\n//const FWS$ = subexp(subexp(WSP$$ + \"*\" + \"\\\\x0D\\\\x0A\") + \"?\" + WSP$$ + \"+\");\n//const QUOTED_PAIR$ = subexp(subexp(\"\\\\\\\\\" + subexp(VCHAR$$ + \"|\" + WSP$$)) + \"|\" + OBS_QP$);\n//const QUOTED_STRING$ = subexp('\\\\\"' + subexp(FWS$ + \"?\" + QCONTENT$) + \"*\" + FWS$ + \"?\" + '\\\\\"');\nconst ATEXT$$ = \"[A-Za-z0-9\\\\!\\\\$\\\\%\\\\'\\\\*\\\\+\\\\-\\\\^\\\\_\\\\`\\\\{\\\\|\\\\}\\\\~]\";\nconst QTEXT$$ = \"[\\\\!\\\\$\\\\%\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,\\\\-\\\\.0-9\\\\<\\\\>A-Z\\\\x5E-\\\\x7E]\";\nconst VCHAR$$ = merge(QTEXT$$, \"[\\\\\\\"\\\\\\\\]\");\nconst DOT_ATOM_TEXT$ = subexp(ATEXT$$ + \"+\" + subexp(\"\\\\.\" + ATEXT$$ + \"+\") + \"*\");\nconst QUOTED_PAIR$ = subexp(\"\\\\\\\\\" + VCHAR$$);\nconst QCONTENT$ = subexp(QTEXT$$ + \"|\" + QUOTED_PAIR$);\nconst QUOTED_STRING$ = subexp('\\\\\"' + QCONTENT$ + \"*\" + '\\\\\"');\n\n//RFC 6068\nconst DTEXT_NO_OBS$$ = \"[\\\\x21-\\\\x5A\\\\x5E-\\\\x7E]\"; //%d33-90 / %d94-126\nconst SOME_DELIMS$$ = \"[\\\\!\\\\$\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,\\\\;\\\\:\\\\@]\";\nconst QCHAR$ = subexp(UNRESERVED$$ + \"|\" + PCT_ENCODED$ + \"|\" + SOME_DELIMS$$);\nconst DOMAIN$ = subexp(DOT_ATOM_TEXT$ + \"|\" + \"\\\\[\" + DTEXT_NO_OBS$$ + \"*\" + \"\\\\]\");\nconst LOCAL_PART$ = subexp(DOT_ATOM_TEXT$ + \"|\" + QUOTED_STRING$);\nconst ADDR_SPEC$ = subexp(LOCAL_PART$ + \"\\\\@\" + DOMAIN$);\nconst TO$ = subexp(ADDR_SPEC$ + subexp(\"\\\\,\" + ADDR_SPEC$) + \"*\");\nconst HFNAME$ = subexp(QCHAR$ + \"*\");\nconst HFVALUE$ = HFNAME$;\nconst HFIELD$ = subexp(HFNAME$ + \"\\\\=\" + HFVALUE$);\nconst HFIELDS2$ = subexp(HFIELD$ + subexp(\"\\\\&\" + HFIELD$) + \"*\");\nconst HFIELDS$ = subexp(\"\\\\?\" + HFIELDS2$);\nconst MAILTO_URI = new RegExp(\"^mailto\\\\:\" + TO$ + \"?\" + HFIELDS$ + \"?$\");\n\nconst UNRESERVED = new RegExp(UNRESERVED$$, \"g\");\nconst PCT_ENCODED = new RegExp(PCT_ENCODED$, \"g\");\nconst NOT_LOCAL_PART = new RegExp(merge(\"[^]\", ATEXT$$, \"[\\\\.]\", '[\\\\\"]', VCHAR$$), \"g\");\nconst NOT_DOMAIN = new RegExp(merge(\"[^]\", ATEXT$$, \"[\\\\.]\", \"[\\\\[]\", DTEXT_NO_OBS$$, \"[\\\\]]\"), \"g\");\nconst NOT_HFNAME = new RegExp(merge(\"[^]\", UNRESERVED$$, SOME_DELIMS$$), \"g\");\nconst NOT_HFVALUE = NOT_HFNAME;\nconst TO = new RegExp(\"^\" + TO$ + \"$\");\nconst HFIELDS = new RegExp(\"^\" + HFIELDS2$ + \"$\");\n\nfunction decodeUnreserved(str:string):string {\n\tconst decStr = pctDecChars(str);\n\treturn (!decStr.match(UNRESERVED) ? str : decStr);\n}\n\nconst handler:URISchemeHandler<MailtoComponents> = {\n\tscheme : \"mailto\",\n\n\tparse : function (components:URIComponents, options:URIOptions):MailtoComponents {\n\t\tconst mailtoComponents = components as MailtoComponents;\n\t\tconst to = mailtoComponents.to = (mailtoComponents.path ? mailtoComponents.path.split(\",\") : []);\n\t\tmailtoComponents.path = undefined;\n\n\t\tif (mailtoComponents.query) {\n\t\t\tlet unknownHeaders = false\n\t\t\tconst headers:MailtoHeaders = {};\n\t\t\tconst hfields = mailtoComponents.query.split(\"&\");\n\n\t\t\tfor (let x = 0, xl = hfields.length; x < xl; ++x) {\n\t\t\t\tconst hfield = hfields[x].split(\"=\");\n\n\t\t\t\tswitch (hfield[0]) {\n\t\t\t\t\tcase \"to\":\n\t\t\t\t\t\tconst toAddrs = hfield[1].split(\",\");\n\t\t\t\t\t\tfor (let x = 0, xl = toAddrs.length; x < xl; ++x) {\n\t\t\t\t\t\t\tto.push(toAddrs[x]);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"subject\":\n\t\t\t\t\t\tmailtoComponents.subject = unescapeComponent(hfield[1], options);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tcase \"body\":\n\t\t\t\t\t\tmailtoComponents.body = unescapeComponent(hfield[1], options);\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tdefault:\n\t\t\t\t\t\tunknownHeaders = true;\n\t\t\t\t\t\theaders[unescapeComponent(hfield[0], options)] = unescapeComponent(hfield[1], options);\n\t\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (unknownHeaders) mailtoComponents.headers = headers;\n\t\t}\n\n\t\tmailtoComponents.query = undefined;\n\n\t\tfor (let x = 0, xl = to.length; x < xl; ++x) {\n\t\t\tconst addr = to[x].split(\"@\");\n\n\t\t\taddr[0] = unescapeComponent(addr[0]);\n\n\t\t\tif (!options.unicodeSupport) {\n\t\t\t\t//convert Unicode IDN -> ASCII IDN\n\t\t\t\ttry {\n\t\t\t\t\taddr[1] = punycode.toASCII(unescapeComponent(addr[1], options).toLowerCase());\n\t\t\t\t} catch (e) {\n\t\t\t\t\tmailtoComponents.error = mailtoComponents.error || \"Email address's domain name can not be converted to ASCII via punycode: \" + e;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\taddr[1] = unescapeComponent(addr[1], options).toLowerCase();\n\t\t\t}\n\n\t\t\tto[x] = addr.join(\"@\");\n\t\t}\n\n\t\treturn mailtoComponents;\n\t},\n\n\tserialize : function (mailtoComponents:MailtoComponents, options:URIOptions):URIComponents {\n\t\tconst components = mailtoComponents as URIComponents;\n\t\tconst to = toArray(mailtoComponents.to);\n\t\tif (to) {\n\t\t\tfor (let x = 0, xl = to.length; x < xl; ++x) {\n\t\t\t\tconst toAddr = String(to[x]);\n\t\t\t\tconst atIdx = toAddr.lastIndexOf(\"@\");\n\t\t\t\tconst localPart = (toAddr.slice(0, atIdx)).replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_LOCAL_PART, pctEncChar);\n\t\t\t\tlet domain = toAddr.slice(atIdx + 1);\n\n\t\t\t\t//convert IDN via punycode\n\t\t\t\ttry {\n\t\t\t\t\tdomain = (!options.iri ? punycode.toASCII(unescapeComponent(domain, options).toLowerCase()) : punycode.toUnicode(domain));\n\t\t\t\t} catch (e) {\n\t\t\t\t\tcomponents.error = components.error || \"Email address's domain name can not be converted to \" + (!options.iri ? \"ASCII\" : \"Unicode\") + \" via punycode: \" + e;\n\t\t\t\t}\n\n\t\t\t\tto[x] = localPart + \"@\" + domain;\n\t\t\t}\n\n\t\t\tcomponents.path = to.join(\",\");\n\t\t}\n\n\t\tconst headers = mailtoComponents.headers = mailtoComponents.headers || {};\n\n\t\tif (mailtoComponents.subject) headers[\"subject\"] = mailtoComponents.subject;\n\t\tif (mailtoComponents.body) headers[\"body\"] = mailtoComponents.body;\n\n\t\tconst fields = [];\n\t\tfor (const name in headers) {\n\t\t\tif (headers[name] !== O[name]) {\n\t\t\t\tfields.push(\n\t\t\t\t\tname.replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFNAME, pctEncChar) +\n\t\t\t\t\t\"=\" +\n\t\t\t\t\theaders[name].replace(PCT_ENCODED, decodeUnreserved).replace(PCT_ENCODED, toUpperCase).replace(NOT_HFVALUE, pctEncChar)\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (fields.length) {\n\t\t\tcomponents.query = fields.join(\"&\");\n\t\t}\n\n\t\treturn components;\n\t}\n}\n\nexport default handler;", "import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport ws from \"./ws\";\n\nconst handler:URISchemeHandler = {\n\tscheme : \"wss\",\n\tdomainHost : ws.domainHost,\n\tparse : ws.parse,\n\tserialize : ws.serialize\n}\n\nexport default handler;", "import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\n\nexport interface WSComponents extends URIComponents {\n\tresourceName?: string;\n\tsecure?: boolean;\n}\n\nfunction isSecure(wsComponents:WSComponents):boolean {\n\treturn typeof wsComponents.secure === 'boolean' ? wsComponents.secure : String(wsComponents.scheme).toLowerCase() === \"wss\";\n}\n\n//RFC 6455\nconst handler:URISchemeHandler = {\n\tscheme : \"ws\",\n\n\tdomainHost : true,\n\n\tparse : function (components:URIComponents, options:URIOptions):WSComponents {\n\t\tconst wsComponents = components as WSComponents;\n\n\t\t//indicate if the secure flag is set\n\t\twsComponents.secure = isSecure(wsComponents);\n\n\t\t//construct resouce name\n\t\twsComponents.resourceName = (wsComponents.path || '/') + (wsComponents.query ? '?' + wsComponents.query : '');\n\t\twsComponents.path = undefined;\n\t\twsComponents.query = undefined;\n\n\t\treturn wsComponents;\n\t},\n\n\tserialize : function (wsComponents:WSComponents, options:URIOptions):URIComponents {\n\t\t//normalize the default port\n\t\tif (wsComponents.port === (isSecure(wsComponents) ? 443 : 80) || wsComponents.port === \"\") {\n\t\t\twsComponents.port = undefined;\n\t\t}\n\n\t\t//ensure scheme matches secure flag\n\t\tif (typeof wsComponents.secure === 'boolean') {\n\t\t\twsComponents.scheme = (wsComponents.secure ? 'wss' : 'ws');\n\t\t\twsComponents.secure = undefined;\n\t\t}\n\n\t\t//reconstruct path from resource name\n\t\tif (wsComponents.resourceName) {\n\t\t\tconst [path, query] = wsComponents.resourceName.split('?');\n\t\t\twsComponents.path = (path && path !== '/' ? path : undefined);\n\t\t\twsComponents.query = query;\n\t\t\twsComponents.resourceName = undefined;\n\t\t}\n\n\t\t//forbid fragment component\n\t\twsComponents.fragment = undefined;\n\n\t\treturn wsComponents;\n\t}\n};\n\nexport default handler;", "import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\nimport http from \"./http\";\n\nconst handler:URISchemeHandler = {\n\tscheme : \"https\",\n\tdomainHost : http.domainHost,\n\tparse : http.parse,\n\tserialize : http.serialize\n}\n\nexport default handler;", "import { URISchemeHandler, URIComponents, URIOptions } from \"../uri\";\n\nconst handler:URISchemeHandler = {\n\tscheme : \"http\",\n\n\tdomainHost : true,\n\n\tparse : function (components:URIComponents, options:URIOptions):URIComponents {\n\t\t//report missing host\n\t\tif (!components.host) {\n\t\t\tcomponents.error = components.error || \"HTTP URIs must have a host.\";\n\t\t}\n\n\t\treturn components;\n\t},\n\n\tserialize : function (components:URIComponents, options:URIOptions):URIComponents {\n\t\tconst secure = String(components.scheme).toLowerCase() === \"https\";\n\n\t\t//normalize the default port\n\t\tif (components.port === (secure ? 443 : 80) || components.port === \"\") {\n\t\t\tcomponents.port = undefined;\n\t\t}\n\t\t\n\t\t//normalize the empty path\n\t\tif (!components.path) {\n\t\t\tcomponents.path = \"/\";\n\t\t}\n\n\t\t//NOTE: We do not parse query strings for HTTP URIs\n\t\t//as WWW Form Url Encoded query strings are part of the HTML4+ spec,\n\t\t//and not the HTTP spec.\n\n\t\treturn components;\n\t}\n};\n\nexport default handler;", "/**\n * URI.js\n *\n * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript.\n * @author <a href=\"mailto:gary.court@gmail.com\">Gary Court</a>\n * @see http://github.com/garycourt/uri-js\n */\n\n/**\n * Copyright 2011 Gary Court. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are\n * permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this list of\n * conditions and the following disclaimer.\n *\n * 2. Redistributions in binary form must reproduce the above copyright notice, this list\n * of conditions and the following disclaimer in the documentation and/or other materials\n * provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY GARY COURT ``AS IS'' AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND\n * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GARY COURT OR\n * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\n * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF\n * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are those of the\n * authors and should not be interpreted as representing official policies, either expressed\n * or implied, of Gary Court.\n */\n\nimport URI_PROTOCOL from \"./regexps-uri\";\nimport IRI_PROTOCOL from \"./regexps-iri\";\nimport punycode from \"punycode\";\nimport { toUpperCase, typeOf, assign } from \"./util\";\n\nexport interface URIComponents {\n\tscheme?:string;\n\tuserinfo?:string;\n\thost?:string;\n\tport?:number|string;\n\tpath?:string;\n\tquery?:string;\n\tfragment?:string;\n\treference?:string;\n\terror?:string;\n}\n\nexport interface URIOptions {\n\tscheme?:string;\n\treference?:string;\n\ttolerant?:boolean;\n\tabsolutePath?:boolean;\n\tiri?:boolean;\n\tunicodeSupport?:boolean;\n\tdomainHost?:boolean;\n}\n\nexport interface URISchemeHandler<Components extends URIComponents = URIComponents, Options extends URIOptions = URIOptions, ParentComponents extends URIComponents = URIComponents> {\n\tscheme:string;\n\tparse(components:ParentComponents, options:Options):Components;\n\tserialize(components:Components, options:Options):ParentComponents;\n\tunicodeSupport?:boolean;\n\tdomainHost?:boolean;\n\tabsolutePath?:boolean;\n}\n\nexport interface URIRegExps {\n\tNOT_SCHEME : RegExp,\n\tNOT_USERINFO : RegExp,\n\tNOT_HOST : RegExp,\n\tNOT_PATH : RegExp,\n\tNOT_PATH_NOSCHEME : RegExp,\n\tNOT_QUERY : RegExp,\n\tNOT_FRAGMENT : RegExp,\n\tESCAPE : RegExp,\n\tUNRESERVED : RegExp,\n\tOTHER_CHARS : RegExp,\n\tPCT_ENCODED : RegExp,\n\tIPV4ADDRESS : RegExp,\n\tIPV6ADDRESS : RegExp,\n}\n\nexport const SCHEMES:{[scheme:string]:URISchemeHandler} = {};\n\nexport function pctEncChar(chr:string):string {\n\tconst c = chr.charCodeAt(0);\n\tlet e:string;\n\n\tif (c < 16) e = \"%0\" + c.toString(16).toUpperCase();\n\telse if (c < 128) e = \"%\" + c.toString(16).toUpperCase();\n\telse if (c < 2048) e = \"%\" + ((c >> 6) | 192).toString(16).toUpperCase() + \"%\" + ((c & 63) | 128).toString(16).toUpperCase();\n\telse e = \"%\" + ((c >> 12) | 224).toString(16).toUpperCase() + \"%\" + (((c >> 6) & 63) | 128).toString(16).toUpperCase() + \"%\" + ((c & 63) | 128).toString(16).toUpperCase();\n\n\treturn e;\n}\n\nexport function pctDecChars(str:string):string {\n\tlet newStr = \"\";\n\tlet i = 0;\n\tconst il = str.length;\n\n\twhile (i < il) {\n\t\tconst c = parseInt(str.substr(i + 1, 2), 16);\n\n\t\tif (c < 128) {\n\t\t\tnewStr += String.fromCharCode(c);\n\t\t\ti += 3;\n\t\t}\n\t\telse if (c >= 194 && c < 224) {\n\t\t\tif ((il - i) >= 6) {\n\t\t\t\tconst c2 = parseInt(str.substr(i + 4, 2), 16);\n\t\t\t\tnewStr += String.fromCharCode(((c & 31) << 6) | (c2 & 63));\n\t\t\t} else {\n\t\t\t\tnewStr += str.substr(i, 6);\n\t\t\t}\n\t\t\ti += 6;\n\t\t}\n\t\telse if (c >= 224) {\n\t\t\tif ((il - i) >= 9) {\n\t\t\t\tconst c2 = parseInt(str.substr(i + 4, 2), 16);\n\t\t\t\tconst c3 = parseInt(str.substr(i + 7, 2), 16);\n\t\t\t\tnewStr += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));\n\t\t\t} else {\n\t\t\t\tnewStr += str.substr(i, 9);\n\t\t\t}\n\t\t\ti += 9;\n\t\t}\n\t\telse {\n\t\t\tnewStr += str.substr(i, 3);\n\t\t\ti += 3;\n\t\t}\n\t}\n\n\treturn newStr;\n}\n\nfunction _normalizeComponentEncoding(components:URIComponents, protocol:URIRegExps) {\n\tfunction decodeUnreserved(str:string):string {\n\t\tconst decStr = pctDecChars(str);\n\t\treturn (!decStr.match(protocol.UNRESERVED) ? str : decStr);\n\t}\n\n\tif (components.scheme) components.scheme = String(components.scheme).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME, \"\");\n\tif (components.userinfo !== undefined) components.userinfo = String(components.userinfo).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_USERINFO, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.host !== undefined) components.host = String(components.host).replace(protocol.PCT_ENCODED, decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.path !== undefined) components.path = String(components.path).replace(protocol.PCT_ENCODED, decodeUnreserved).replace((components.scheme ? protocol.NOT_PATH : protocol.NOT_PATH_NOSCHEME), pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.query !== undefined) components.query = String(components.query).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_QUERY, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\tif (components.fragment !== undefined) components.fragment = String(components.fragment).replace(protocol.PCT_ENCODED, decodeUnreserved).replace(protocol.NOT_FRAGMENT, pctEncChar).replace(protocol.PCT_ENCODED, toUpperCase);\n\n\treturn components;\n};\n\nfunction _stripLeadingZeros(str:string):string {\n\treturn str.replace(/^0*(.*)/, \"$1\") || \"0\";\n}\n\nfunction _normalizeIPv4(host:string, protocol:URIRegExps):string {\n\tconst matches = host.match(protocol.IPV4ADDRESS) || [];\n\tconst [, address] = matches;\n\t\n\tif (address) {\n\t\treturn address.split(\".\").map(_stripLeadingZeros).join(\".\");\n\t} else {\n\t\treturn host;\n\t}\n}\n\nfunction _normalizeIPv6(host:string, protocol:URIRegExps):string {\n\tconst matches = host.match(protocol.IPV6ADDRESS) || [];\n\tconst [, address, zone] = matches;\n\n\tif (address) {\n\t\tconst [last, first] = address.toLowerCase().split('::').reverse();\n\t\tconst firstFields = first ? first.split(\":\").map(_stripLeadingZeros) : [];\n\t\tconst lastFields = last.split(\":\").map(_stripLeadingZeros);\n\t\tconst isLastFieldIPv4Address = protocol.IPV4ADDRESS.test(lastFields[lastFields.length - 1]);\n\t\tconst fieldCount = isLastFieldIPv4Address ? 7 : 8;\n\t\tconst lastFieldsStart = lastFields.length - fieldCount;\n\t\tconst fields = Array<string>(fieldCount);\n\n\t\tfor (let x = 0; x < fieldCount; ++x) {\n\t\t\tfields[x] = firstFields[x] || lastFields[lastFieldsStart + x] || '';\n\t\t}\n\n\t\tif (isLastFieldIPv4Address) {\n\t\t\tfields[fieldCount - 1] = _normalizeIPv4(fields[fieldCount - 1], protocol);\n\t\t}\n\n\t\tconst allZeroFields = fields.reduce<Array<{index:number,length:number}>>((acc, field, index) => {\n\t\t\tif (!field || field === \"0\") {\n\t\t\t\tconst lastLongest = acc[acc.length - 1];\n\t\t\t\tif (lastLongest && lastLongest.index + lastLongest.length === index) {\n\t\t\t\t\tlastLongest.length++;\n\t\t\t\t} else {\n\t\t\t\t\tacc.push({ index, length : 1 });\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn acc;\n\t\t}, []);\n\n\t\tconst longestZeroFields = allZeroFields.sort((a, b) => b.length - a.length)[0];\n\n\t\tlet newHost:string;\n\t\tif (longestZeroFields && longestZeroFields.length > 1) {\n\t\t\tconst newFirst = fields.slice(0, longestZeroFields.index) ;\n\t\t\tconst newLast = fields.slice(longestZeroFields.index + longestZeroFields.length);\n\t\t\tnewHost = newFirst.join(\":\") + \"::\" + newLast.join(\":\");\n\t\t} else {\n\t\t\tnewHost = fields.join(\":\");\n\t\t}\n\n\t\tif (zone) {\n\t\t\tnewHost += \"%\" + zone;\n\t\t}\n\n\t\treturn newHost;\n\t} else {\n\t\treturn host;\n\t}\n}\n\nconst URI_PARSE = /^(?:([^:\\/?#]+):)?(?:\\/\\/((?:([^\\/?#@]*)@)?(\\[[^\\/?#\\]]+\\]|[^\\/?#:]*)(?:\\:(\\d*))?))?([^?#]*)(?:\\?([^#]*))?(?:#((?:.|\\n|\\r)*))?/i;\nconst NO_MATCH_IS_UNDEFINED = (<RegExpMatchArray>(\"\").match(/(){0}/))[1] === undefined;\n\nexport function parse(uriString:string, options:URIOptions = {}):URIComponents {\n\tconst components:URIComponents = {};\n\tconst protocol = (options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL);\n\n\tif (options.reference === \"suffix\") uriString = (options.scheme ? options.scheme + \":\" : \"\") + \"//\" + uriString;\n\n\tconst matches = uriString.match(URI_PARSE);\n\n\tif (matches) {\n\t\tif (NO_MATCH_IS_UNDEFINED) {\n\t\t\t//store each component\n\t\t\tcomponents.scheme = matches[1];\n\t\t\tcomponents.userinfo = matches[3];\n\t\t\tcomponents.host = matches[4];\n\t\t\tcomponents.port = parseInt(matches[5], 10);\n\t\t\tcomponents.path = matches[6] || \"\";\n\t\t\tcomponents.query = matches[7];\n\t\t\tcomponents.fragment = matches[8];\n\n\t\t\t//fix port number\n\t\t\tif (isNaN(components.port)) {\n\t\t\t\tcomponents.port = matches[5];\n\t\t\t}\n\t\t} else { //IE FIX for improper RegExp matching\n\t\t\t//store each component\n\t\t\tcomponents.scheme = matches[1] || undefined;\n\t\t\tcomponents.userinfo = (uriString.indexOf(\"@\") !== -1 ? matches[3] : undefined);\n\t\t\tcomponents.host = (uriString.indexOf(\"//\") !== -1 ? matches[4] : undefined);\n\t\t\tcomponents.port = parseInt(matches[5], 10);\n\t\t\tcomponents.path = matches[6] || \"\";\n\t\t\tcomponents.query = (uriString.indexOf(\"?\") !== -1 ? matches[7] : undefined);\n\t\t\tcomponents.fragment = (uriString.indexOf(\"#\") !== -1 ? matches[8] : undefined);\n\n\t\t\t//fix port number\n\t\t\tif (isNaN(components.port)) {\n\t\t\t\tcomponents.port = (uriString.match(/\\/\\/(?:.|\\n)*\\:(?:\\/|\\?|\\#|$)/) ? matches[4] : undefined);\n\t\t\t}\n\t\t}\n\n\t\tif (components.host) {\n\t\t\t//normalize IP hosts\n\t\t\tcomponents.host = _normalizeIPv6(_normalizeIPv4(components.host, protocol), protocol);\n\t\t}\n\n\t\t//determine reference type\n\t\tif (components.scheme === undefined && components.userinfo === undefined && components.host === undefined && components.port === undefined && !components.path && components.query === undefined) {\n\t\t\tcomponents.reference = \"same-document\";\n\t\t} else if (components.scheme === undefined) {\n\t\t\tcomponents.reference = \"relative\";\n\t\t} else if (components.fragment === undefined) {\n\t\t\tcomponents.reference = \"absolute\";\n\t\t} else {\n\t\t\tcomponents.reference = \"uri\";\n\t\t}\n\n\t\t//check for reference errors\n\t\tif (options.reference && options.reference !== \"suffix\" && options.reference !== components.reference) {\n\t\t\tcomponents.error = components.error || \"URI is not a \" + options.reference + \" reference.\";\n\t\t}\n\n\t\t//find scheme handler\n\t\tconst schemeHandler = SCHEMES[(options.scheme || components.scheme || \"\").toLowerCase()];\n\n\t\t//check if scheme can't handle IRIs\n\t\tif (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {\n\t\t\t//if host component is a domain name\n\t\t\tif (components.host && (options.domainHost || (schemeHandler && schemeHandler.domainHost))) {\n\t\t\t\t//convert Unicode IDN -> ASCII IDN\n\t\t\t\ttry {\n\t\t\t\t\tcomponents.host = punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase());\n\t\t\t\t} catch (e) {\n\t\t\t\t\tcomponents.error = components.error || \"Host's domain name can not be converted to ASCII via punycode: \" + e;\n\t\t\t\t}\n\t\t\t}\n\t\t\t//convert IRI -> URI\n\t\t\t_normalizeComponentEncoding(components, URI_PROTOCOL);\n\t\t} else {\n\t\t\t//normalize encodings\n\t\t\t_normalizeComponentEncoding(components, protocol);\n\t\t}\n\n\t\t//perform scheme specific parsing\n\t\tif (schemeHandler && schemeHandler.parse) {\n\t\t\tschemeHandler.parse(components, options);\n\t\t}\n\t} else {\n\t\tcomponents.error = components.error || \"URI can not be parsed.\";\n\t}\n\n\treturn components;\n};\n\nfunction _recomposeAuthority(components:URIComponents, options:URIOptions):string|undefined {\n\tconst protocol = (options.iri !== false ? IRI_PROTOCOL : URI_PROTOCOL);\n\tconst uriTokens:Array<string> = [];\n\n\tif (components.userinfo !== undefined) {\n\t\turiTokens.push(components.userinfo);\n\t\turiTokens.push(\"@\");\n\t}\n\n\tif (components.host !== undefined) {\n\t\t//normalize IP hosts, add brackets and escape zone separator for IPv6\n\t\turiTokens.push(_normalizeIPv6(_normalizeIPv4(String(components.host), protocol), protocol).replace(protocol.IPV6ADDRESS, (_, $1, $2) => \"[\" + $1 + ($2 ? \"%25\" + $2 : \"\") + \"]\"));\n\t}\n\n\tif (typeof components.port === \"number\" || typeof components.port === \"string\") {\n\t\turiTokens.push(\":\");\n\t\turiTokens.push(String(components.port));\n\t}\n\n\treturn uriTokens.length ? uriTokens.join(\"\") : undefined;\n};\n\nconst RDS1 = /^\\.\\.?\\//;\nconst RDS2 = /^\\/\\.(\\/|$)/;\nconst RDS3 = /^\\/\\.\\.(\\/|$)/;\nconst RDS4 = /^\\.\\.?$/;\nconst RDS5 = /^\\/?(?:.|\\n)*?(?=\\/|$)/;\n\nexport function removeDotSegments(input:string):string {\n\tconst output:Array<string> = [];\n\n\twhile (input.length) {\n\t\tif (input.match(RDS1)) {\n\t\t\tinput = input.replace(RDS1, \"\");\n\t\t} else if (input.match(RDS2)) {\n\t\t\tinput = input.replace(RDS2, \"/\");\n\t\t} else if (input.match(RDS3)) {\n\t\t\tinput = input.replace(RDS3, \"/\");\n\t\t\toutput.pop();\n\t\t} else if (input === \".\" || input === \"..\") {\n\t\t\tinput = \"\";\n\t\t} else {\n\t\t\tconst im = input.match(RDS5);\n\t\t\tif (im) {\n\t\t\t\tconst s = im[0];\n\t\t\t\tinput = input.slice(s.length);\n\t\t\t\toutput.push(s);\n\t\t\t} else {\n\t\t\t\tthrow new Error(\"Unexpected dot segment condition\");\n\t\t\t}\n\t\t}\n\t}\n\n\treturn output.join(\"\");\n};\n\nexport function serialize(components:URIComponents, options:URIOptions = {}):string {\n\tconst protocol = (options.iri ? IRI_PROTOCOL : URI_PROTOCOL);\n\tconst uriTokens:Array<string> = [];\n\n\t//find scheme handler\n\tconst schemeHandler = SCHEMES[(options.scheme || components.scheme || \"\").toLowerCase()];\n\n\t//perform scheme specific serialization\n\tif (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(components, options);\n\n\tif (components.host) {\n\t\t//if host component is an IPv6 address\n\t\tif (protocol.IPV6ADDRESS.test(components.host)) {\n\t\t\t//TODO: normalize IPv6 address as per RFC 5952\n\t\t}\n\n\t\t//if host component is a domain name\n\t\telse if (options.domainHost || (schemeHandler && schemeHandler.domainHost)) {\n\t\t\t//convert IDN via punycode\n\t\t\ttry {\n\t\t\t\tcomponents.host = (!options.iri ? punycode.toASCII(components.host.replace(protocol.PCT_ENCODED, pctDecChars).toLowerCase()) : punycode.toUnicode(components.host));\n\t\t\t} catch (e) {\n\t\t\t\tcomponents.error = components.error || \"Host's domain name can not be converted to \" + (!options.iri ? \"ASCII\" : \"Unicode\") + \" via punycode: \" + e;\n\t\t\t}\n\t\t}\n\t}\n\n\t//normalize encoding\n\t_normalizeComponentEncoding(components, protocol);\n\n\tif (options.reference !== \"suffix\" && components.scheme) {\n\t\turiTokens.push(components.scheme);\n\t\turiTokens.push(\":\");\n\t}\n\n\tconst authority = _recomposeAuthority(components, options);\n\tif (authority !== undefined) {\n\t\tif (options.reference !== \"suffix\") {\n\t\t\turiTokens.push(\"//\");\n\t\t}\n\n\t\turiTokens.push(authority);\n\n\t\tif (components.path && components.path.charAt(0) !== \"/\") {\n\t\t\turiTokens.push(\"/\");\n\t\t}\n\t}\n\n\tif (components.path !== undefined) {\n\t\tlet s = components.path;\n\n\t\tif (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {\n\t\t\ts = removeDotSegments(s);\n\t\t}\n\n\t\tif (authority === undefined) {\n\t\t\ts = s.replace(/^\\/\\//, \"/%2F\"); //don't allow the path to start with \"//\"\n\t\t}\n\n\t\turiTokens.push(s);\n\t}\n\n\tif (components.query !== undefined) {\n\t\turiTokens.push(\"?\");\n\t\turiTokens.push(components.query);\n\t}\n\n\tif (components.fragment !== undefined) {\n\t\turiTokens.push(\"#\");\n\t\turiTokens.push(components.fragment);\n\t}\n\n\treturn uriTokens.join(\"\"); //merge tokens into a string\n};\n\nexport function resolveComponents(base:URIComponents, relative:URIComponents, options:URIOptions = {}, skipNormalization?:boolean):URIComponents {\n\tconst target:URIComponents = {};\n\n\tif (!skipNormalization) {\n\t\tbase = parse(serialize(base, options), options); //normalize base components\n\t\trelative = parse(serialize(relative, options), options); //normalize relative components\n\t}\n\toptions = options || {};\n\n\tif (!options.tolerant && relative.scheme) {\n\t\ttarget.scheme = relative.scheme;\n\t\t//target.authority = relative.authority;\n\t\ttarget.userinfo = relative.userinfo;\n\t\ttarget.host = relative.host;\n\t\ttarget.port = relative.port;\n\t\ttarget.path = removeDotSegments(relative.path || \"\");\n\t\ttarget.query = relative.query;\n\t} else {\n\t\tif (relative.userinfo !== undefined || relative.host !== undefined || relative.port !== undefined) {\n\t\t\t//target.authority = relative.authority;\n\t\t\ttarget.userinfo = relative.userinfo;\n\t\t\ttarget.host = relative.host;\n\t\t\ttarget.port = relative.port;\n\t\t\ttarget.path = removeDotSegments(relative.path || \"\");\n\t\t\ttarget.query = relative.query;\n\t\t} else {\n\t\t\tif (!relative.path) {\n\t\t\t\ttarget.path = base.path;\n\t\t\t\tif (relative.query !== undefined) {\n\t\t\t\t\ttarget.query = relative.query;\n\t\t\t\t} else {\n\t\t\t\t\ttarget.query = base.query;\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tif (relative.path.charAt(0) === \"/\") {\n\t\t\t\t\ttarget.path = removeDotSegments(relative.path);\n\t\t\t\t} else {\n\t\t\t\t\tif ((base.userinfo !== undefined || base.host !== undefined || base.port !== undefined) && !base.path) {\n\t\t\t\t\t\ttarget.path = \"/\" + relative.path;\n\t\t\t\t\t} else if (!base.path) {\n\t\t\t\t\t\ttarget.path = relative.path;\n\t\t\t\t\t} else {\n\t\t\t\t\t\ttarget.path = base.path.slice(0, base.path.lastIndexOf(\"/\") + 1) + relative.path;\n\t\t\t\t\t}\n\t\t\t\t\ttarget.path = removeDotSegments(target.path);\n\t\t\t\t}\n\t\t\t\ttarget.query = relative.query;\n\t\t\t}\n\t\t\t//target.authority = base.authority;\n\t\t\ttarget.userinfo = base.userinfo;\n\t\t\ttarget.host = base.host;\n\t\t\ttarget.port = base.port;\n\t\t}\n\t\ttarget.scheme = base.scheme;\n\t}\n\n\ttarget.fragment = relative.fragment;\n\n\treturn target;\n};\n\nexport function resolve(baseURI:string, relativeURI:string, options?:URIOptions):string {\n\tconst schemelessOptions = assign({ scheme : 'null' }, options);\n\treturn serialize(resolveComponents(parse(baseURI, schemelessOptions), parse(relativeURI, schemelessOptions), schemelessOptions, true), schemelessOptions);\n};\n\nexport function normalize(uri:string, options?:URIOptions):string;\nexport function normalize(uri:URIComponents, options?:URIOptions):URIComponents;\nexport function normalize(uri:any, options?:URIOptions):any {\n\tif (typeof uri === \"string\") {\n\t\turi = serialize(parse(uri, options), options);\n\t} else if (typeOf(uri) === \"object\") {\n\t\turi = parse(serialize(<URIComponents>uri, options), options);\n\t}\n\n\treturn uri;\n};\n\nexport function equal(uriA:string, uriB:string, options?: URIOptions):boolean;\nexport function equal(uriA:URIComponents, uriB:URIComponents, options?:URIOptions):boolean;\nexport function equal(uriA:any, uriB:any, options?:URIOptions):boolean {\n\tif (typeof uriA === \"string\") {\n\t\turiA = serialize(parse(uriA, options), options);\n\t} else if (typeOf(uriA) === \"object\") {\n\t\turiA = serialize(<URIComponents>uriA, options);\n\t}\n\n\tif (typeof uriB === \"string\") {\n\t\turiB = serialize(parse(uriB, options), options);\n\t} else if (typeOf(uriB) === \"object\") {\n\t\turiB = serialize(<URIComponents>uriB, options);\n\t}\n\n\treturn uriA === uriB;\n};\n\nexport function escapeComponent(str:string, options?:URIOptions):string {\n\treturn str && str.toString().replace((!options || !options.iri ? URI_PROTOCOL.ESCAPE : IRI_PROTOCOL.ESCAPE), pctEncChar);\n};\n\nexport function unescapeComponent(str:string, options?:URIOptions):string {\n\treturn str && str.toString().replace((!options || !options.iri ? URI_PROTOCOL.PCT_ENCODED : IRI_PROTOCOL.PCT_ENCODED), pctDecChars);\n};\n", "'use strict';\n\n/** Highest positive signed 32-bit float value */\nconst maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1\n\n/** Bootstring parameters */\nconst base = 36;\nconst tMin = 1;\nconst tMax = 26;\nconst skew = 38;\nconst damp = 700;\nconst initialBias = 72;\nconst initialN = 128; // 0x80\nconst delimiter = '-'; // '\\x2D'\n\n/** Regular expressions */\nconst regexPunycode = /^xn--/;\nconst regexNonASCII = /[^\\0-\\x7E]/; // non-ASCII chars\nconst regexSeparators = /[\\x2E\\u3002\\uFF0E\\uFF61]/g; // RFC 3490 separators\n\n/** Error messages */\nconst errors = {\n\t'overflow': 'Overflow: input needs wider integers to process',\n\t'not-basic': 'Illegal input >= 0x80 (not a basic code point)',\n\t'invalid-input': 'Invalid input'\n};\n\n/** Convenience shortcuts */\nconst baseMinusTMin = base - tMin;\nconst floor = Math.floor;\nconst stringFromCharCode = String.fromCharCode;\n\n/*--------------------------------------------------------------------------*/\n\n/**\n * A generic error utility function.\n * @private\n * @param {String} type The error type.\n * @returns {Error} Throws a `RangeError` with the applicable error message.\n */\nfunction error(type) {\n\tthrow new RangeError(errors[type]);\n}\n\n/**\n * A generic `Array#map` utility function.\n * @private\n * @param {Array} array The array to iterate over.\n * @param {Function} callback The function that gets called for every array\n * item.\n * @returns {Array} A new array of values returned by the callback function.\n */\nfunction map(array, fn) {\n\tconst result = [];\n\tlet length = array.length;\n\twhile (length--) {\n\t\tresult[length] = fn(array[length]);\n\t}\n\treturn result;\n}\n\n/**\n * A simple `Array#map`-like wrapper to work with domain name strings or email\n * addresses.\n * @private\n * @param {String} domain The domain name or email address.\n * @param {Function} callback The function that gets called for every\n * character.\n * @returns {Array} A new string of characters returned by the callback\n * function.\n */\nfunction mapDomain(string, fn) {\n\tconst parts = string.split('@');\n\tlet result = '';\n\tif (parts.length > 1) {\n\t\t// In email addresses, only the domain name should be punycoded. Leave\n\t\t// the local part (i.e. everything up to `@`) intact.\n\t\tresult = parts[0] + '@';\n\t\tstring = parts[1];\n\t}\n\t// Avoid `split(regex)` for IE8 compatibility. See #17.\n\tstring = string.replace(regexSeparators, '\\x2E');\n\tconst labels = string.split('.');\n\tconst encoded = map(labels, fn).join('.');\n\treturn result + encoded;\n}\n\n/**\n * Creates an array containing the numeric code points of each Unicode\n * character in the string. While JavaScript uses UCS-2 internally,\n * this function will convert a pair of surrogate halves (each of which\n * UCS-2 exposes as separate characters) into a single code point,\n * matching UTF-16.\n * @see `punycode.ucs2.encode`\n * @see <https://mathiasbynens.be/notes/javascript-encoding>\n * @memberOf punycode.ucs2\n * @name decode\n * @param {String} string The Unicode input string (UCS-2).\n * @returns {Array} The new array of code points.\n */\nfunction ucs2decode(string) {\n\tconst output = [];\n\tlet counter = 0;\n\tconst length = string.length;\n\twhile (counter < length) {\n\t\tconst value = string.charCodeAt(counter++);\n\t\tif (value >= 0xD800 && value <= 0xDBFF && counter < length) {\n\t\t\t// It's a high surrogate, and there is a next character.\n\t\t\tconst extra = string.charCodeAt(counter++);\n\t\t\tif ((extra & 0xFC00) == 0xDC00) { // Low surrogate.\n\t\t\t\toutput.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);\n\t\t\t} else {\n\t\t\t\t// It's an unmatched surrogate; only append this code unit, in case the\n\t\t\t\t// next code unit is the high surrogate of a surrogate pair.\n\t\t\t\toutput.push(value);\n\t\t\t\tcounter--;\n\t\t\t}\n\t\t} else {\n\t\t\toutput.push(value);\n\t\t}\n\t}\n\treturn output;\n}\n\n/**\n * Creates a string based on an array of numeric code points.\n * @see `punycode.ucs2.decode`\n * @memberOf punycode.ucs2\n * @name encode\n * @param {Array} codePoints The array of numeric code points.\n * @returns {String} The new Unicode string (UCS-2).\n */\nconst ucs2encode = array => String.fromCodePoint(...array);\n\n/**\n * Converts a basic code point into a digit/integer.\n * @see `digitToBasic()`\n * @private\n * @param {Number} codePoint The basic numeric code point value.\n * @returns {Number} The numeric value of a basic code point (for use in\n * representing integers) in the range `0` to `base - 1`, or `base` if\n * the code point does not represent a value.\n */\nconst basicToDigit = function(codePoint) {\n\tif (codePoint - 0x30 < 0x0A) {\n\t\treturn codePoint - 0x16;\n\t}\n\tif (codePoint - 0x41 < 0x1A) {\n\t\treturn codePoint - 0x41;\n\t}\n\tif (codePoint - 0x61 < 0x1A) {\n\t\treturn codePoint - 0x61;\n\t}\n\treturn base;\n};\n\n/**\n * Converts a digit/integer into a basic code point.\n * @see `basicToDigit()`\n * @private\n * @param {Number} digit The numeric value of a basic code point.\n * @returns {Number} The basic code point whose value (when used for\n * representing integers) is `digit`, which needs to be in the range\n * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is\n * used; else, the lowercase form is used. The behavior is undefined\n * if `flag` is non-zero and `digit` has no uppercase form.\n */\nconst digitToBasic = function(digit, flag) {\n\t// 0..25 map to ASCII a..z or A..Z\n\t// 26..35 map to ASCII 0..9\n\treturn digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);\n};\n\n/**\n * Bias adaptation function as per section 3.4 of RFC 3492.\n * https://tools.ietf.org/html/rfc3492#section-3.4\n * @private\n */\nconst adapt = function(delta, numPoints, firstTime) {\n\tlet k = 0;\n\tdelta = firstTime ? floor(delta / damp) : delta >> 1;\n\tdelta += floor(delta / numPoints);\n\tfor (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {\n\t\tdelta = floor(delta / baseMinusTMin);\n\t}\n\treturn floor(k + (baseMinusTMin + 1) * delta / (delta + skew));\n};\n\n/**\n * Converts a Punycode string of ASCII-only symbols to a string of Unicode\n * symbols.\n * @memberOf punycode\n * @param {String} input The Punycode string of ASCII-only symbols.\n * @returns {String} The resulting string of Unicode symbols.\n */\nconst decode = function(input) {\n\t// Don't use UCS-2.\n\tconst output = [];\n\tconst inputLength = input.length;\n\tlet i = 0;\n\tlet n = initialN;\n\tlet bias = initialBias;\n\n\t// Handle the basic code points: let `basic` be the number of input code\n\t// points before the last delimiter, or `0` if there is none, then copy\n\t// the first basic code points to the output.\n\n\tlet basic = input.lastIndexOf(delimiter);\n\tif (basic < 0) {\n\t\tbasic = 0;\n\t}\n\n\tfor (let j = 0; j < basic; ++j) {\n\t\t// if it's not a basic code point\n\t\tif (input.charCodeAt(j) >= 0x80) {\n\t\t\terror('not-basic');\n\t\t}\n\t\toutput.push(input.charCodeAt(j));\n\t}\n\n\t// Main decoding loop: start just after the last delimiter if any basic code\n\t// points were copied; start at the beginning otherwise.\n\n\tfor (let index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {\n\n\t\t// `index` is the index of the next character to be consumed.\n\t\t// Decode a generalized variable-length integer into `delta`,\n\t\t// which gets added to `i`. The overflow checking is easier\n\t\t// if we increase `i` as we go, then subtract off its starting\n\t\t// value at the end to obtain `delta`.\n\t\tlet oldi = i;\n\t\tfor (let w = 1, k = base; /* no condition */; k += base) {\n\n\t\t\tif (index >= inputLength) {\n\t\t\t\terror('invalid-input');\n\t\t\t}\n\n\t\t\tconst digit = basicToDigit(input.charCodeAt(index++));\n\n\t\t\tif (digit >= base || digit > floor((maxInt - i) / w)) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\n\t\t\ti += digit * w;\n\t\t\tconst t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n\n\t\t\tif (digit < t) {\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tconst baseMinusT = base - t;\n\t\t\tif (w > floor(maxInt / baseMinusT)) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\n\t\t\tw *= baseMinusT;\n\n\t\t}\n\n\t\tconst out = output.length + 1;\n\t\tbias = adapt(i - oldi, out, oldi == 0);\n\n\t\t// `i` was supposed to wrap around from `out` to `0`,\n\t\t// incrementing `n` each time, so we'll fix that now:\n\t\tif (floor(i / out) > maxInt - n) {\n\t\t\terror('overflow');\n\t\t}\n\n\t\tn += floor(i / out);\n\t\ti %= out;\n\n\t\t// Insert `n` at position `i` of the output.\n\t\toutput.splice(i++, 0, n);\n\n\t}\n\n\treturn String.fromCodePoint(...output);\n};\n\n/**\n * Converts a string of Unicode symbols (e.g. a domain name label) to a\n * Punycode string of ASCII-only symbols.\n * @memberOf punycode\n * @param {String} input The string of Unicode symbols.\n * @returns {String} The resulting Punycode string of ASCII-only symbols.\n */\nconst encode = function(input) {\n\tconst output = [];\n\n\t// Convert the input in UCS-2 to an array of Unicode code points.\n\tinput = ucs2decode(input);\n\n\t// Cache the length.\n\tlet inputLength = input.length;\n\n\t// Initialize the state.\n\tlet n = initialN;\n\tlet delta = 0;\n\tlet bias = initialBias;\n\n\t// Handle the basic code points.\n\tfor (const currentValue of input) {\n\t\tif (currentValue < 0x80) {\n\t\t\toutput.push(stringFromCharCode(currentValue));\n\t\t}\n\t}\n\n\tlet basicLength = output.length;\n\tlet handledCPCount = basicLength;\n\n\t// `handledCPCount` is the number of code points that have been handled;\n\t// `basicLength` is the number of basic code points.\n\n\t// Finish the basic string with a delimiter unless it's empty.\n\tif (basicLength) {\n\t\toutput.push(delimiter);\n\t}\n\n\t// Main encoding loop:\n\twhile (handledCPCount < inputLength) {\n\n\t\t// All non-basic code points < n have been handled already. Find the next\n\t\t// larger one:\n\t\tlet m = maxInt;\n\t\tfor (const currentValue of input) {\n\t\t\tif (currentValue >= n && currentValue < m) {\n\t\t\t\tm = currentValue;\n\t\t\t}\n\t\t}\n\n\t\t// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,\n\t\t// but guard against overflow.\n\t\tconst handledCPCountPlusOne = handledCPCount + 1;\n\t\tif (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {\n\t\t\terror('overflow');\n\t\t}\n\n\t\tdelta += (m - n) * handledCPCountPlusOne;\n\t\tn = m;\n\n\t\tfor (const currentValue of input) {\n\t\t\tif (currentValue < n && ++delta > maxInt) {\n\t\t\t\terror('overflow');\n\t\t\t}\n\t\t\tif (currentValue == n) {\n\t\t\t\t// Represent delta as a generalized variable-length integer.\n\t\t\t\tlet q = delta;\n\t\t\t\tfor (let k = base; /* no condition */; k += base) {\n\t\t\t\t\tconst t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);\n\t\t\t\t\tif (q < t) {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tconst qMinusT = q - t;\n\t\t\t\t\tconst baseMinusT = base - t;\n\t\t\t\t\toutput.push(\n\t\t\t\t\t\tstringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))\n\t\t\t\t\t);\n\t\t\t\t\tq = floor(qMinusT / baseMinusT);\n\t\t\t\t}\n\n\t\t\t\toutput.push(stringFromCharCode(digitToBasic(q, 0)));\n\t\t\t\tbias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);\n\t\t\t\tdelta = 0;\n\t\t\t\t++handledCPCount;\n\t\t\t}\n\t\t}\n\n\t\t++delta;\n\t\t++n;\n\n\t}\n\treturn output.join('');\n};\n\n/**\n * Converts a Punycode string representing a domain name or an email address\n * to Unicode. Only the Punycoded parts of the input will be converted, i.e.\n * it doesn't matter if you call it on a string that has already been\n * converted to Unicode.\n * @memberOf punycode\n * @param {String} input The Punycoded domain name or email address to\n * convert to Unicode.\n * @returns {String} The Unicode representation of the given Punycode\n * string.\n */\nconst toUnicode = function(input) {\n\treturn mapDomain(input, function(string) {\n\t\treturn regexPunycode.test(string)\n\t\t\t? decode(string.slice(4).toLowerCase())\n\t\t\t: string;\n\t});\n};\n\n/**\n * Converts a Unicode string representing a domain name or an email address to\n * Punycode. Only the non-ASCII parts of the domain name will be converted,\n * i.e. it doesn't matter if you call it with a domain that's already in\n * ASCII.\n * @memberOf punycode\n * @param {String} input The domain name or email address to convert, as a\n * Unicode string.\n * @returns {String} The Punycode representation of the given domain name or\n * email address.\n */\nconst toASCII = function(input) {\n\treturn mapDomain(input, function(string) {\n\t\treturn regexNonASCII.test(string)\n\t\t\t? 'xn--' + encode(string)\n\t\t\t: string;\n\t});\n};\n\n/*--------------------------------------------------------------------------*/\n\n/** Define the public API */\nconst punycode = {\n\t/**\n\t * A string representing the current Punycode.js version number.\n\t * @memberOf punycode\n\t * @type String\n\t */\n\t'version': '2.1.0',\n\t/**\n\t * An object of methods to convert from JavaScript's internal character\n\t * representation (UCS-2) to Unicode code points, and back.\n\t * @see <https://mathiasbynens.be/notes/javascript-encoding>\n\t * @memberOf punycode\n\t * @type Object\n\t */\n\t'ucs2': {\n\t\t'decode': ucs2decode,\n\t\t'encode': ucs2encode\n\t},\n\t'decode': decode,\n\t'encode': encode,\n\t'toASCII': toASCII,\n\t'toUnicode': toUnicode\n};\n\nexport default punycode;\n", "import { URIRegExps } from \"./uri\";\nimport { buildExps } from \"./regexps-uri\";\n\nexport default buildExps(true);\n", "import { URIRegExps } from \"./uri\";\nimport { merge, subexp } from \"./util\";\n\nexport function buildExps(isIRI:boolean):URIRegExps {\n\tconst\n\t\tALPHA$$ = \"[A-Za-z]\",\n\t\tCR$ = \"[\\\\x0D]\",\n\t\tDIGIT$$ = \"[0-9]\",\n\t\tDQUOTE$$ = \"[\\\\x22]\",\n\t\tHEXDIG$$ = merge(DIGIT$$, \"[A-Fa-f]\"), //case-insensitive\n\t\tLF$$ = \"[\\\\x0A]\",\n\t\tSP$$ = \"[\\\\x20]\",\n\t\tPCT_ENCODED$ = subexp(subexp(\"%[EFef]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%[89A-Fa-f]\" + HEXDIG$$ + \"%\" + HEXDIG$$ + HEXDIG$$) + \"|\" + subexp(\"%\" + HEXDIG$$ + HEXDIG$$)), //expanded\n\t\tGEN_DELIMS$$ = \"[\\\\:\\\\/\\\\?\\\\#\\\\[\\\\]\\\\@]\",\n\t\tSUB_DELIMS$$ = \"[\\\\!\\\\$\\\\&\\\\'\\\\(\\\\)\\\\*\\\\+\\\\,\\\\;\\\\=]\",\n\t\tRESERVED$$ = merge(GEN_DELIMS$$, SUB_DELIMS$$),\n\t\tUCSCHAR$$ = isIRI ? \"[\\\\xA0-\\\\u200D\\\\u2010-\\\\u2029\\\\u202F-\\\\uD7FF\\\\uF900-\\\\uFDCF\\\\uFDF0-\\\\uFFEF]\" : \"[]\", //subset, excludes bidi control characters\n\t\tIPRIVATE$$ = isIRI ? \"[\\\\uE000-\\\\uF8FF]\" : \"[]\", //subset\n\t\tUNRESERVED$$ = merge(ALPHA$$, DIGIT$$, \"[\\\\-\\\\.\\\\_\\\\~]\", UCSCHAR$$),\n\t\tSCHEME$ = subexp(ALPHA$$ + merge(ALPHA$$, DIGIT$$, \"[\\\\+\\\\-\\\\.]\") + \"*\"),\n\t\tUSERINFO$ = subexp(subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:]\")) + \"*\"),\n\t\tDEC_OCTET$ = subexp(subexp(\"25[0-5]\") + \"|\" + subexp(\"2[0-4]\" + DIGIT$$) + \"|\" + subexp(\"1\" + DIGIT$$ + DIGIT$$) + \"|\" + subexp(\"[1-9]\" + DIGIT$$) + \"|\" + DIGIT$$),\n\t\tDEC_OCTET_RELAXED$ = subexp(subexp(\"25[0-5]\") + \"|\" + subexp(\"2[0-4]\" + DIGIT$$) + \"|\" + subexp(\"1\" + DIGIT$$ + DIGIT$$) + \"|\" + subexp(\"0?[1-9]\" + DIGIT$$) + \"|0?0?\" + DIGIT$$), //relaxed parsing rules\n\t\tIPV4ADDRESS$ = subexp(DEC_OCTET_RELAXED$ + \"\\\\.\" + DEC_OCTET_RELAXED$ + \"\\\\.\" + DEC_OCTET_RELAXED$ + \"\\\\.\" + DEC_OCTET_RELAXED$),\n\t\tH16$ = subexp(HEXDIG$$ + \"{1,4}\"),\n\t\tLS32$ = subexp(subexp(H16$ + \"\\\\:\" + H16$) + \"|\" + IPV4ADDRESS$),\n\t\tIPV6ADDRESS1$ = subexp( subexp(H16$ + \"\\\\:\") + \"{6}\" + LS32$), // 6( h16 \":\" ) ls32\n\t\tIPV6ADDRESS2$ = subexp( \"\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{5}\" + LS32$), // \"::\" 5( h16 \":\" ) ls32\n\t\tIPV6ADDRESS3$ = subexp(subexp( H16$) + \"?\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{4}\" + LS32$), //[ h16 ] \"::\" 4( h16 \":\" ) ls32\n\t\tIPV6ADDRESS4$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,1}\" + H16$) + \"?\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{3}\" + LS32$), //[ *1( h16 \":\" ) h16 ] \"::\" 3( h16 \":\" ) ls32\n\t\tIPV6ADDRESS5$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,2}\" + H16$) + \"?\\\\:\\\\:\" + subexp(H16$ + \"\\\\:\") + \"{2}\" + LS32$), //[ *2( h16 \":\" ) h16 ] \"::\" 2( h16 \":\" ) ls32\n\t\tIPV6ADDRESS6$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,3}\" + H16$) + \"?\\\\:\\\\:\" + H16$ + \"\\\\:\" + LS32$), //[ *3( h16 \":\" ) h16 ] \"::\" h16 \":\" ls32\n\t\tIPV6ADDRESS7$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,4}\" + H16$) + \"?\\\\:\\\\:\" + LS32$), //[ *4( h16 \":\" ) h16 ] \"::\" ls32\n\t\tIPV6ADDRESS8$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,5}\" + H16$) + \"?\\\\:\\\\:\" + H16$ ), //[ *5( h16 \":\" ) h16 ] \"::\" h16\n\t\tIPV6ADDRESS9$ = subexp(subexp(subexp(H16$ + \"\\\\:\") + \"{0,6}\" + H16$) + \"?\\\\:\\\\:\" ), //[ *6( h16 \":\" ) h16 ] \"::\"\n\t\tIPV6ADDRESS$ = subexp([IPV6ADDRESS1$, IPV6ADDRESS2$, IPV6ADDRESS3$, IPV6ADDRESS4$, IPV6ADDRESS5$, IPV6ADDRESS6$, IPV6ADDRESS7$, IPV6ADDRESS8$, IPV6ADDRESS9$].join(\"|\")),\n\t\tZONEID$ = subexp(subexp(UNRESERVED$$ + \"|\" + PCT_ENCODED$) + \"+\"), //RFC 6874\n\t\tIPV6ADDRZ$ = subexp(IPV6ADDRESS$ + \"\\\\%25\" + ZONEID$), //RFC 6874\n\t\tIPV6ADDRZ_RELAXED$ = subexp(IPV6ADDRESS$ + subexp(\"\\\\%25|\\\\%(?!\" + HEXDIG$$ + \"{2})\") + ZONEID$), //RFC 6874, with relaxed parsing rules\n\t\tIPVFUTURE$ = subexp(\"[vV]\" + HEXDIG$$ + \"+\\\\.\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:]\") + \"+\"),\n\t\tIP_LITERAL$ = subexp(\"\\\\[\" + subexp(IPV6ADDRZ_RELAXED$ + \"|\" + IPV6ADDRESS$ + \"|\" + IPVFUTURE$) + \"\\\\]\"), //RFC 6874\n\t\tREG_NAME$ = subexp(subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$)) + \"*\"),\n\t\tHOST$ = subexp(IP_LITERAL$ + \"|\" + IPV4ADDRESS$ + \"(?!\" + REG_NAME$ + \")\" + \"|\" + REG_NAME$),\n\t\tPORT$ = subexp(DIGIT$$ + \"*\"),\n\t\tAUTHORITY$ = subexp(subexp(USERINFO$ + \"@\") + \"?\" + HOST$ + subexp(\"\\\\:\" + PORT$) + \"?\"),\n\t\tPCHAR$ = subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:\\\\@]\")),\n\t\tSEGMENT$ = subexp(PCHAR$ + \"*\"),\n\t\tSEGMENT_NZ$ = subexp(PCHAR$ + \"+\"),\n\t\tSEGMENT_NZ_NC$ = subexp(subexp(PCT_ENCODED$ + \"|\" + merge(UNRESERVED$$, SUB_DELIMS$$, \"[\\\\@]\")) + \"+\"),\n\t\tPATH_ABEMPTY$ = subexp(subexp(\"\\\\/\" + SEGMENT$) + \"*\"),\n\t\tPATH_ABSOLUTE$ = subexp(\"\\\\/\" + subexp(SEGMENT_NZ$ + PATH_ABEMPTY$) + \"?\"), //simplified\n\t\tPATH_NOSCHEME$ = subexp(SEGMENT_NZ_NC$ + PATH_ABEMPTY$), //simplified\n\t\tPATH_ROOTLESS$ = subexp(SEGMENT_NZ$ + PATH_ABEMPTY$), //simplified\n\t\tPATH_EMPTY$ = \"(?!\" + PCHAR$ + \")\",\n\t\tPATH$ = subexp(PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_NOSCHEME$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$),\n\t\tQUERY$ = subexp(subexp(PCHAR$ + \"|\" + merge(\"[\\\\/\\\\?]\", IPRIVATE$$)) + \"*\"),\n\t\tFRAGMENT$ = subexp(subexp(PCHAR$ + \"|[\\\\/\\\\?]\") + \"*\"),\n\t\tHIER_PART$ = subexp(subexp(\"\\\\/\\\\/\" + AUTHORITY$ + PATH_ABEMPTY$) + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$),\n\t\tURI$ = subexp(SCHEME$ + \"\\\\:\" + HIER_PART$ + subexp(\"\\\\?\" + QUERY$) + \"?\" + subexp(\"\\\\#\" + FRAGMENT$) + \"?\"),\n\t\tRELATIVE_PART$ = subexp(subexp(\"\\\\/\\\\/\" + AUTHORITY$ + PATH_ABEMPTY$) + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_NOSCHEME$ + \"|\" + PATH_EMPTY$),\n\t\tRELATIVE$ = subexp(RELATIVE_PART$ + subexp(\"\\\\?\" + QUERY$) + \"?\" + subexp(\"\\\\#\" + FRAGMENT$) + \"?\"),\n\t\tURI_REFERENCE$ = subexp(URI$ + \"|\" + RELATIVE$),\n\t\tABSOLUTE_URI$ = subexp(SCHEME$ + \"\\\\:\" + HIER_PART$ + subexp(\"\\\\?\" + QUERY$) + \"?\"),\n\n\t\tGENERIC_REF$ = \"^(\" + SCHEME$ + \")\\\\:\" + subexp(subexp(\"\\\\/\\\\/(\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?)\") + \"?(\" + PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$ + \")\") + subexp(\"\\\\?(\" + QUERY$ + \")\") + \"?\" + subexp(\"\\\\#(\" + FRAGMENT$ + \")\") + \"?$\",\n\t\tRELATIVE_REF$ = \"^(){0}\" + subexp(subexp(\"\\\\/\\\\/(\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?)\") + \"?(\" + PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_NOSCHEME$ + \"|\" + PATH_EMPTY$ + \")\") + subexp(\"\\\\?(\" + QUERY$ + \")\") + \"?\" + subexp(\"\\\\#(\" + FRAGMENT$ + \")\") + \"?$\",\n\t\tABSOLUTE_REF$ = \"^(\" + SCHEME$ + \")\\\\:\" + subexp(subexp(\"\\\\/\\\\/(\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?)\") + \"?(\" + PATH_ABEMPTY$ + \"|\" + PATH_ABSOLUTE$ + \"|\" + PATH_ROOTLESS$ + \"|\" + PATH_EMPTY$ + \")\") + subexp(\"\\\\?(\" + QUERY$ + \")\") + \"?$\",\n\t\tSAMEDOC_REF$ = \"^\" + subexp(\"\\\\#(\" + FRAGMENT$ + \")\") + \"?$\",\n\t\tAUTHORITY_REF$ = \"^\" + subexp(\"(\" + USERINFO$ + \")@\") + \"?(\" + HOST$ + \")\" + subexp(\"\\\\:(\" + PORT$ + \")\") + \"?$\"\n\t;\n\n\treturn {\n\t\tNOT_SCHEME : new RegExp(merge(\"[^]\", ALPHA$$, DIGIT$$, \"[\\\\+\\\\-\\\\.]\"), \"g\"),\n\t\tNOT_USERINFO : new RegExp(merge(\"[^\\\\%\\\\:]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_HOST : new RegExp(merge(\"[^\\\\%\\\\[\\\\]\\\\:]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_PATH : new RegExp(merge(\"[^\\\\%\\\\/\\\\:\\\\@]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_PATH_NOSCHEME : new RegExp(merge(\"[^\\\\%\\\\/\\\\@]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tNOT_QUERY : new RegExp(merge(\"[^\\\\%]\", UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:\\\\@\\\\/\\\\?]\", IPRIVATE$$), \"g\"),\n\t\tNOT_FRAGMENT : new RegExp(merge(\"[^\\\\%]\", UNRESERVED$$, SUB_DELIMS$$, \"[\\\\:\\\\@\\\\/\\\\?]\"), \"g\"),\n\t\tESCAPE : new RegExp(merge(\"[^]\", UNRESERVED$$, SUB_DELIMS$$), \"g\"),\n\t\tUNRESERVED : new RegExp(UNRESERVED$$, \"g\"),\n\t\tOTHER_CHARS : new RegExp(merge(\"[^\\\\%]\", UNRESERVED$$, RESERVED$$), \"g\"),\n\t\tPCT_ENCODED : new RegExp(PCT_ENCODED$, \"g\"),\n\t\tIPV4ADDRESS : new RegExp(\"^(\" + IPV4ADDRESS$ + \")$\"),\n\t\tIPV6ADDRESS : new RegExp(\"^\\\\[?(\" + IPV6ADDRESS$ + \")\" + subexp(subexp(\"\\\\%25|\\\\%(?!\" + HEXDIG$$ + \"{2})\") + \"(\" + ZONEID$ + \")\") + \"?\\\\]?$\") //RFC 6874, with relaxed parsing rules\n\t};\n}\n\nexport default buildExps(false);\n", "export function merge(...sets:Array<string>):string {\n\tif (sets.length > 1) {\n\t\tsets[0] = sets[0].slice(0, -1);\n\t\tconst xl = sets.length - 1;\n\t\tfor (let x = 1; x < xl; ++x) {\n\t\t\tsets[x] = sets[x].slice(1, -1);\n\t\t}\n\t\tsets[xl] = sets[xl].slice(1);\n\t\treturn sets.join('');\n\t} else {\n\t\treturn sets[0];\n\t}\n}\n\nexport function subexp(str:string):string {\n\treturn \"(?:\" + str + \")\";\n}\n\nexport function typeOf(o:any):string {\n\treturn o === undefined ? \"undefined\" : (o === null ? \"null\" : Object.prototype.toString.call(o).split(\" \").pop().split(\"]\").shift().toLowerCase());\n}\n\nexport function toUpperCase(str:string):string {\n\treturn str.toUpperCase();\n}\n\nexport function toArray(obj:any):Array<any> {\n\treturn obj !== undefined && obj !== null ? (obj instanceof Array ? obj : (typeof obj.length !== \"number\" || obj.split || obj.setInterval || obj.call ? [obj] : Array.prototype.slice.call(obj))) : [];\n}\n\n\nexport function assign(target: object, source: any): any {\n\tconst obj = target as any;\n\tif (source) {\n\t\tfor (const key in source) {\n\t\t\tobj[key] = source[key];\n\t\t}\n\t}\n\treturn obj;\n}", "/* jshint esversion: 6 */\n/* jslint node: true */\n'use strict';\n\nmodule.exports = function serialize (object) {\n if (typeof object === 'number' && isNaN(object)) {\n throw new Error('NaN is not allowed');\n }\n\n if (typeof object === 'number' && !isFinite(object)) {\n throw new Error('Infinity is not allowed');\n }\n\n if (object === null || typeof object !== 'object') {\n return JSON.stringify(object);\n }\n\n if (object.toJSON instanceof Function) {\n return serialize(object.toJSON());\n }\n\n if (Array.isArray(object)) {\n const values = object.reduce((t, cv, ci) => {\n const comma = ci === 0 ? '' : ',';\n const value = cv === undefined || typeof cv === 'symbol' ? null : cv;\n return `${t}${comma}${serialize(value)}`;\n }, '');\n return `[${values}]`;\n }\n\n const values = Object.keys(object).sort().reduce((t, cv) => {\n if (object[cv] === undefined ||\n typeof object[cv] === 'symbol') {\n return t;\n }\n const comma = t.length === 0 ? '' : ',';\n return `${t}${comma}${serialize(cv)}:${serialize(object[cv])}`;\n }, '');\n return `{${values}}`;\n};\n", "/**\n * Helpers.\n */\n\nvar s = 1000;\nvar m = s * 60;\nvar h = m * 60;\nvar d = h * 24;\nvar w = d * 7;\nvar y = d * 365.25;\n\n/**\n * Parse or format the given `val`.\n *\n * Options:\n *\n * - `long` verbose formatting [false]\n *\n * @param {String|Number} val\n * @param {Object} [options]\n * @throws {Error} throw an error if val is not a non-empty string or a number\n * @return {String|Number}\n * @api public\n */\n\nmodule.exports = function (val, options) {\n options = options || {};\n var type = typeof val;\n if (type === 'string' && val.length > 0) {\n return parse(val);\n } else if (type === 'number' && isFinite(val)) {\n return options.long ? fmtLong(val) : fmtShort(val);\n }\n throw new Error(\n 'val is not a non-empty string or a valid number. val=' +\n JSON.stringify(val)\n );\n};\n\n/**\n * Parse the given `str` and return milliseconds.\n *\n * @param {String} str\n * @return {Number}\n * @api private\n */\n\nfunction parse(str) {\n str = String(str);\n if (str.length > 100) {\n return;\n }\n var match = /^(-?(?:\\d+)?\\.?\\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(\n str\n );\n if (!match) {\n return;\n }\n var n = parseFloat(match[1]);\n var type = (match[2] || 'ms').toLowerCase();\n switch (type) {\n case 'years':\n case 'year':\n case 'yrs':\n case 'yr':\n case 'y':\n return n * y;\n case 'weeks':\n case 'week':\n case 'w':\n return n * w;\n case 'days':\n case 'day':\n case 'd':\n return n * d;\n case 'hours':\n case 'hour':\n case 'hrs':\n case 'hr':\n case 'h':\n return n * h;\n case 'minutes':\n case 'minute':\n case 'mins':\n case 'min':\n case 'm':\n return n * m;\n case 'seconds':\n case 'second':\n case 'secs':\n case 'sec':\n case 's':\n return n * s;\n case 'milliseconds':\n case 'millisecond':\n case 'msecs':\n case 'msec':\n case 'ms':\n return n;\n default:\n return undefined;\n }\n}\n\n/**\n * Short format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtShort(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return Math.round(ms / d) + 'd';\n }\n if (msAbs >= h) {\n return Math.round(ms / h) + 'h';\n }\n if (msAbs >= m) {\n return Math.round(ms / m) + 'm';\n }\n if (msAbs >= s) {\n return Math.round(ms / s) + 's';\n }\n return ms + 'ms';\n}\n\n/**\n * Long format for `ms`.\n *\n * @param {Number} ms\n * @return {String}\n * @api private\n */\n\nfunction fmtLong(ms) {\n var msAbs = Math.abs(ms);\n if (msAbs >= d) {\n return plural(ms, msAbs, d, 'day');\n }\n if (msAbs >= h) {\n return plural(ms, msAbs, h, 'hour');\n }\n if (msAbs >= m) {\n return plural(ms, msAbs, m, 'minute');\n }\n if (msAbs >= s) {\n return plural(ms, msAbs, s, 'second');\n }\n return ms + ' ms';\n}\n\n/**\n * Pluralization helper.\n */\n\nfunction plural(ms, msAbs, n, name) {\n var isPlural = msAbs >= n * 1.5;\n return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : '');\n}\n", "export * from './types/did-core.js';\nexport * from './types/did-resolution.js';\nexport type * from './types/multibase.js';\nexport type * from './types/portable-did.js';\n\nexport * from './did.js';\nexport * from './did-error.js';\nexport * from './bearer-did.js';\n\nexport * from './methods/did-dht.js';\nexport * from './methods/did-ion.js';\nexport * from './methods/did-jwk.js';\nexport * from './methods/did-key.js';\nexport * from './methods/did-method.js';\nexport * from './methods/did-web.js';\n\nexport * from './resolver/resolver-cache-level.js';\nexport * from './resolver/resolver-cache-noop.js';\nexport * from './resolver/universal-resolver.js';\n\nexport * as utils from './utils.js';", "import type { Jwk } from '@enbox/crypto';\n\n/**\n * Represents metadata related to the process of DID dereferencing.\n *\n * This type includes fields that provide information about the outcome of a DID dereferencing operation,\n * including the content type of the returned resource and any errors that occurred during the dereferencing process.\n *\n * @see {@link https://www.w3.org/TR/did-core/#did-url-dereferencing-metadata | DID Core Specification, \u00A7 DID URL Dereferencing Metadata}\n */\nexport type DidDereferencingMetadata = {\n /**\n * The Media Type of the returned contentStream SHOULD be expressed using this property if\n * dereferencing is successful.\n */\n contentType?: string;\n\n /**\n * The error code from the dereferencing process. This property is REQUIRED when there is an\n * error in the dereferencing process. The value of this property MUST be a single keyword\n * expressed as an ASCII string. The possible property values of this field SHOULD be registered\n * in the {@link https://www.w3.org/TR/did-spec-registries/ | DID Specification Registries}.\n * The DID Core specification defines the following common error values:\n *\n * - `invalidDidUrl`: The DID URL supplied to the DID URL dereferencing function does not conform\n * to valid syntax.\n * - `notFound`: The DID URL dereferencer was unable to find the `contentStream` resulting from\n * this dereferencing request.\n *\n * @see {@link https://www.w3.org/TR/did-core/#did-url-dereferencing-metadata | DID Core Specification, \u00A7 DID URL Dereferencing Metadata}\n */\n error?: string;\n\n // Additional output metadata generated during DID Resolution.\n [key: string]: any;\n};\n\n/**\n * Represents the options that can be used during the process of DID dereferencing.\n *\n * This interface allows the caller to specify preferences and additional parameters for the DID\n * dereferencing operation.\n *\n * @see {@link https://www.w3.org/TR/did-core/#did-url-dereferencing-options}\n */\nexport interface DidDereferencingOptions {\n /** The Media Type that the caller prefers for contentStream. */\n accept?: string;\n\n /** Additional properties used during DID dereferencing. */\n [key: string]: any;\n}\n\n/**\n * Represents the result of a DID dereferencing operation.\n *\n * This type encapsulates the outcomes of the DID URL dereferencing process, including metadata\n * about the dereferencing operation, the content stream retrieved (if any), and metadata about the\n * content stream.\n *\n * @see {@link https://www.w3.org/TR/did-core/#did-url-dereferencing | DID Core Specification, \u00A7 DID URL Dereferencing}\n */\nexport type DidDereferencingResult = {\n /**\n * A metadata structure consisting of values relating to the results of the DID URL dereferencing\n * process. This structure is REQUIRED, and in the case of an error in the dereferencing process,\n * this MUST NOT be empty. Properties defined by this specification are in 7.2.2 DID URL\n * Dereferencing Metadata. If the dereferencing is not successful, this structure MUST contain an\n * `error` property describing the error.\n */\n dereferencingMetadata: DidDereferencingMetadata;\n\n /**\n * If the `dereferencing` function was called and successful, this MUST contain a resource\n * corresponding to the DID URL. The contentStream MAY be a resource such as:\n * - a DID document that is serializable in one of the conformant representations\n * - a Verification Method\n * - a service.\n * - any other resource format that can be identified via a Media Type and obtained through the\n * resolution process.\n *\n * If the dereferencing is unsuccessful, this value MUST be empty.\n */\n contentStream: DidResource | null;\n\n /**\n * If the dereferencing is successful, this MUST be a metadata structure, but the structure MAY be\n * empty. This structure contains metadata about the contentStream. If the contentStream is a DID\n * document, this MUST be a didDocumentMetadata structure as described in DID Resolution. If the\n * dereferencing is unsuccessful, this output MUST be an empty metadata structure.\n */\n contentMetadata: DidDocumentMetadata;\n};\n\n/**\n * A set of data describing the Decentralized Identifierr (DID) subject.\n *\n * A DID Document contains information associated with the DID, such as cryptographic public keys\n * and service endpoints, enabling trustable interactions associated with the DID subject.\n *\n * - Cryptographic public keys - Used by the DID subject or a DID delegate to authenticate itself\n * and prove its association with the DID.\n * - Service endpoints - Used to communicate or interact with the DID subject or associated\n * entities. Examples include discovery, agent, social networking, file\n * storage, and verifiable credential repository services.\n *\n * A DID Document can be retrieved by resolving a DID, as described in\n * {@link https://www.w3.org/TR/did-core/#did-resolution | DID Core Specification, \u00A7 DID Resolution}.\n */\nexport interface DidDocument {\n /**\n * A JSON-LD context link, which provides a JSON-LD processor with the information necessary to\n * interpret the DID document JSON. The default context URL is 'https://www.w3.org/ns/did/v1'.\n */\n '@context'?: 'https://www.w3.org/ns/did/v1' | string | (string | Record<string, any>)[];\n\n /**\n * The DID Subject to which this DID Document pertains.\n *\n * The `id` property is REQUIRED and must be a valid DID.\n *\n * @see {@link https://www.w3.org/TR/did-core/#did-subject | DID Core Specification, \u00A7 DID Subject}\n */\n id: string;\n\n /**\n * A DID subject can have multiple identifiers for different purposes, or at different times.\n * The assertion that two or more DIDs (or other types of URI) refer to the same DID subject can\n * be made using the `alsoKnownAs` property.\n *\n * @see {@link https://www.w3.org/TR/did-core/#also-known-as | DID Core Specification, \u00A7 Also Known As}\n */\n alsoKnownAs?: string[];\n\n /**\n * A DID controller is an entity that is authorized to make changes to a DID document. Typically,\n * only the DID Subject (i.e., the value of `id` property in the DID document) is authoritative.\n * However, another DID can be specified as the DID controller, and when doing so, any\n * verification methods contained in the DID document for the other DID should be accepted as\n * authoritative. In other words, proofs created by the controller DID should be considered\n * equivalent to proofs created by the DID Subject.\n *\n * @see {@link https://www.w3.org/TR/did-core/#did-controller | DID Core Specification, \u00A7 DID Controller}\n */\n controller?: string | string[];\n\n /**\n * A DID document can express verification methods, such as cryptographic public keys, which can\n * be used to authenticate or authorize interactions with the DID subject or associated parties.\n *\n * @see {@link https://www.w3.org/TR/did-core/#verification-methods | DID Core Specification, \u00A7 Verification Methods}\n */\n verificationMethod?: DidVerificationMethod[];\n\n /**\n * The `assertionMethod` verification relationship is used to specify how the DID subject is\n * expected to express claims, such as for the purposes of issuing a Verifiable Credential.\n *\n * @see {@link https://www.w3.org/TR/did-core/#assertion | DID Core Specification, \u00A7 Assertion}\n */\n assertionMethod?: (DidVerificationMethod | string)[];\n\n /**\n * The `authentication` verification relationship is used to specify how the DID subject is expected\n * to be authenticated, for purposes such as logging into a website or engaging in any sort of\n * challenge-response protocol.\n\n * @see {@link https://www.w3.org/TR/did-core/#authentication | DID Core Specification, \u00A7 Authentication}\n */\n authentication?: (DidVerificationMethod | string)[];\n\n /**\n * The `keyAgreement` verification relationship is used to specify how an entity can generate\n * encryption material in order to transmit confidential information intended for the DID\n * subject, such as for the purposes of establishing a secure communication channel with the\n * recipient.\n *\n * @see {@link https://www.w3.org/TR/did-core/#key-agreement | DID Core Specification, \u00A7 Key Agreement}\n */\n keyAgreement?: (DidVerificationMethod | string)[];\n\n /**\n * The `capabilityDelegation` verification relationship is used to specify a mechanism that might\n * be used by the DID subject to delegate a cryptographic capability to another party, such as\n * delegating the authority to access a specific HTTP API to a subordinate.\n *\n * @see {@link https://www.w3.org/TR/did-core/#capability-delegation | DID Core Specification, \u00A7 Capability Delegation}\n */\n capabilityDelegation?: (DidVerificationMethod | string)[];\n\n /**\n * The `capabilityInvocation` verification relationship is used to specify a verification method\n * that might be used by the DID subject to invoke a cryptographic capability, such as the\n * authorization to update the DID Document.\n */\n capabilityInvocation?: (DidVerificationMethod | string)[];\n\n /**\n * Services are used in DID documents to express ways of communicating with the DID subject or\n * associated entities. A service can be any type of service the DID subject wants to advertise,\n * including decentralized identity management services for further discovery, authentication,\n * authorization, or interaction.\n *\n * @see {@link https://www.w3.org/TR/did-core/#services | DID Core Specification, \u00A7 Services}\n */\n service?: DidService[];\n}\n\n/**\n * Represents metadata about the DID document resulting from a DID resolution operation.\n *\n * This metadata typically does not change between invocations of the `resolve` and\n * `resolveRepresentation` functions unless the DID document changes, as it represents metadata\n * about the DID document.\n *\n * @see {@link https://www.w3.org/TR/did-core/#did-document-metadata | DID Core Specification, \u00A7 DID Document Metadata}\n */\nexport interface DidDocumentMetadata {\n /**\n * Timestamp of the Create operation.\n *\n * The value of the property MUST be a string formatted as an XML Datetime normalized to\n * UTC 00:00:00 and without sub-second decimal precision. For example: `2020-12-20T19:17:47Z`.\n */\n created?: string;\n\n /**\n * Timestamp of the last Update operation for the document version which was resolved.\n *\n * The value of the property MUST follow the same formatting rules as the `created` property.\n * The `updated` property is omitted if an Update operation has never been performed on the DID\n * document. If an `updated` property exists, it can be the same value as the `created` property\n * when the difference between the two timestamps is less than one second.\n */\n updated?: string;\n\n /**\n * Whether the DID has been deactivated.\n *\n * If a DID has been deactivated, DID document metadata MUST include this property with the\n * boolean value `true`. If a DID has not been deactivated, this properrty is OPTIONAL, but if\n * present, MUST have the boolean value `false`.\n */\n deactivated?: boolean;\n\n /**\n * Version ID of the last Update operation for the document version which was resolved.\n */\n versionId?: string;\n\n /**\n * Timestamp of the next Update operation if the resolved document version is not the latest\n * version of the document.\n *\n * The value of the property MUST follow the same formatting rules as the `created` property.\n */\n nextUpdate?: string;\n\n /**\n * Version ID of the next Update operation if the resolved document version is not the latest\n * version of the document.\n */\n nextVersionId?: string;\n\n /**\n * A DID method can define different forms of a DID that are logically equivalent. An example is\n * when a DID takes one form prior to registration in a verifiable data registry and another form\n * after such registration. In this case, the DID method specification might need to express one\n * or more DIDs that are logically equivalent to the resolved DID as a property of the DID\n * document. This is the purpose of the `equivalentId` property.\n *\n * A requesting party is expected to retain the values from the id and equivalentId properties to\n * ensure any subsequent interactions with any of the values they contain are correctly handled as\n * logically equivalent (e.g., retain all variants in a database so an interaction with any one\n * maps to the same underlying account).\n *\n * @see {@link https://www.w3.org/TR/did-core/#dfn-equivalentid | DID Core Specification, \u00A7 DID Document Metadata}\n */\n equivalentId?: string[];\n\n /**\n * The `canonicalId` property is identical to the `equivalentId` property except:\n * - it is associated with a single value rather than a set\n * - the DID is defined to be the canonical ID for the DID subject within the scope of the\n * containing DID document.\n *\n * A requesting party is expected to use the `canonicalId` value as its primary ID value for the\n * DID subject and treat all other equivalent values as secondary aliases (e.g., update\n * corresponding primary references in their systems to reflect the new canonical ID directive).\n *\n * @see {@link https://www.w3.org/TR/did-core/#dfn-canonicalid | DID Core Specification, \u00A7 DID Document Metadata}\n */\n canonicalId?: string;\n\n // Additional output metadata generated during DID Resolution.\n [key: string]: any;\n}\n\n/**\n * Represents metadata related to the result of a DID resolution operation.\n *\n * This type includes fields that provide information about the outcome of a DID resolution process,\n * including the content type of the returned DID document and any errors that occurred during the\n * resolution process.\n *\n * This metadata typically changes between invocations of the `resolve` and `resolveRepresentation`\n * functions, as it represents data about the resolution process itself.\n *\n * @see {@link https://www.w3.org/TR/did-core/#did-resolution-metadata | DID Core Specification, \u00A7 DID Resolution Metadata}\n */\nexport type DidResolutionMetadata = {\n /**\n * The Media Type of the returned `didDocumentStream`.\n *\n * This property is REQUIRED if resolution is successful and if the `resolveRepresentation`\n * function was called. This property MUST NOT be present if the `resolve` function was called.\n * The value of this property MUST be an ASCII string that is the Media Type of the conformant\n * representations. The caller of the `resolveRepresentation` function MUST use this value when\n * determining how to parse and process the `didDocumentStream` returned by this function into the\n * data model.\n */\n contentType?: string;\n\n /**\n * An error code indicating issues encountered during the DID Resolution or DID URL\n * Dereferencing process.\n *\n * Defined error codes include:\n * - `internalError`: An unexpected error occurred during DID Resolution or DID URL\n * dereferencing process.\n * - `invalidDid`: The provided DID is invalid.\n * - `methodNotSupported`: The DID method specified is not supported.\n * - `notFound`: The DID or DID URL does not exist.\n * - `representationNotSupported`: The DID document representation is not supported.\n * - Custom error codes can also be provided as strings.\n *\n * @see {@link https://www.w3.org/TR/did-core/#did-resolution-metadata | DID Core Specification, \u00A7 DID Resolution Metadata}\n * @see {@link https://www.w3.org/TR/did-spec-registries/#error | DID Specification Registries, \u00A7 Error}\n */\n error?: string;\n\n // Additional output metadata generated during DID Resolution.\n [key: string]: any;\n};\n\n/**\n * DID Resolution input metadata.\n*\n* The DID Core specification defines the following common properties:\n* - `accept`: The Media Type that the caller prefers for the returned representation of the DID\n* Document.\n*\n* The possible properties within this structure and their possible values are registered in the\n* {@link https://www.w3.org/TR/did-spec-registries/#did-resolution-options | DID Specification Registries}.\n *\n * @see {@link https://www.w3.org/TR/did-core/#did-resolution-options | DID Core Specification, \u00A7 DID Resolution Options}\n */\nexport interface DidResolutionOptions {\n /**\n * The Media Type that the caller prefers for the returned representation of the DID Document.\n *\n * This property is REQUIRED if the `resolveRepresentation` function was called. This property\n * MUST NOT be present if the `resolve` function was called.\n *\n * The value of this property MUST be an ASCII string that is the Media Type of the conformant\n * representations. The caller of the `resolveRepresentation` function MUST use this value when\n * determining how to parse and process the `didDocumentStream` returned by this function into the\n * data model.\n *\n * @see {@link https://www.w3.org/TR/did-core/#did-resolution-options | DID Core Specification, \u00A7 DID Resolution Options}\n */\n accept?: string;\n\n // Additional properties used during DID Resolution.\n [key: string]: any;\n}\n\n/**\n * Represents the result of a Decentralized Identifier (DID) resolution operation.\n *\n * This type encapsulates the complete outcome of resolving a DID, including the resolution metadata,\n * the DID document (if resolution is successful), and metadata about the DID document.\n *\n * @see {@link https://www.w3.org/TR/did-core/#did-resolution | DID Core Specification, \u00A7 DID Resolution}\n */\nexport type DidResolutionResult = {\n /**\n * A JSON-LD context link, which provides the JSON-LD processor with the information necessary to\n * interpret the resolution result JSON. The default context URL is\n * 'https://w3id.org/did-resolution/v1'.\n */\n '@context'?: 'https://w3id.org/did-resolution/v1' | string | (string | Record<string, any>)[];\n\n /**\n * A metadata structure consisting of values relating to the results of the DID resolution\n * process.\n *\n * This structure is REQUIRED, and in the case of an error in the resolution process,\n * this MUST NOT be empty. If the resolution is not successful, this structure MUST contain an\n * `error` property describing the error.\n *\n * @see {@link https://www.w3.org/TR/did-core/#dfn-didresolutionmetadata | DID Core Specification, \u00A7 DID Resolution Metadata}\n */\n didResolutionMetadata: DidResolutionMetadata;\n\n /**\n * The DID document resulting from the resolution process, if successful.\n *\n * If the `resolve` function was called and successful, this MUST contain a DID document\n * corresponding to the DID. If the resolution is unsuccessful, this value MUST be empty.\n *\n * @see {@link https://www.w3.org/TR/did-core/#dfn-diddocument | DID Core Specification, \u00A7 DID Document}\n */\n didDocument: DidDocument | null;\n\n /**\n * Metadata about the DID Document.\n *\n * This structure contains information about the DID Document like creation and update timestamps,\n * deactivation status, versioning information, and other details relevant to the DID Document.\n *\n * @see {@link https://www.w3.org/TR/did-core/#dfn-diddocumentmetadata | DID Core Specification, \u00A7 DID Document Metadata}\n */\n didDocumentMetadata: DidDocumentMetadata;\n};\n\n/**\n * A DID Resource is either a DID Document, a DID Verification method or a DID Service\n */\nexport type DidResource = DidDocument | DidService | DidVerificationMethod;\n\n/**\n * Services are used in DID documents to express ways of communicating with the DID subject or\n * associated entities. A service can be any type of service the DID subject wants to advertise.\n *\n * @see {@link https://www.w3.org/TR/did-core/#services}\n */\nexport type DidService = {\n /**\n * Identifier of the service.\n *\n * The `id` property is REQUIRED. It MUST be a URI conforming to\n * {@link https://datatracker.ietf.org/doc/html/rfc3986 | RFC3986} and MUST be unique within the\n * DID document.\n */\n id: string;\n\n /**\n * The type of service being described.\n *\n * The `type` property is REQUIRED. It MUST be a string. To maximize interoperability, the value\n * SHOULD be registered in the\n * {@link https://www.w3.org/TR/did-spec-registries/ | DID Specification Registries}. Examples of\n * service types can be found in\n * {@link https://www.w3.org/TR/did-spec-registries/#service-types | \u00A7 Service Types}.\n */\n type: string;\n\n /**\n * A URI that can be used to interact with the DID service.\n *\n * The value of the `serviceEndpoint` property MUST be a string, an object containing key/value\n * pairs, or an array composed of strings or objects. All string values MUST be valid URIs\n * conforming to {@link https://datatracker.ietf.org/doc/html/rfc3986 | RFC3986}.\n */\n serviceEndpoint: DidServiceEndpoint | DidServiceEndpoint[];\n\n // DID methods MAY include additional service properties.\n [key: string]: any;\n};\n\n/**\n * A service endpoint is a URI (Uniform Resource Identifier) that can be used to interact with the\n * DID service.\n *\n * The value of the `serviceEndpoint` property MUST be a string or an object containing key/value\n * pairs. All string values MUST be valid URIs conforming to\n * {@link https://datatracker.ietf.org/doc/html/rfc3986 | RFC3986}.\n *\n * @see {@link https://www.w3.org/TR/did-core/#dfn-serviceendpoint | RFC3986, \u00A7 5.4 Services}\n */\nexport type DidServiceEndpoint = string | Record<string, any>;\n\n/**\n * Represents a verification method in the context of a DID document.\n *\n * A verification method is a mechanism by which a DID controller can cryptographically assert proof\n * of ownership or control over a DID or DID document. This can include, but is not limited to,\n * cryptographic public keys or other data that can be used to authenticate or authorize actions.\n *\n * @see {@link https://www.w3.org/TR/did-core/#verification-methods | DID Core Specification, \u00A7 Verification Methods}\n */\nexport interface DidVerificationMethod {\n /**\n * The identifier of the verification method, which must be a URI.\n */\n id: string;\n\n /**\n * The type of the verification method.\n *\n * To maximize interoperability this value SHOULD be one of the valid verification method types\n * registered in the {@link https://www.w3.org/TR/did-spec-registries/#verification-method-types | DID Specification Registries}.\n */\n type: string;\n\n /**\n * The DID of the entity that controls this verification method.\n */\n controller: string;\n\n /**\n * (Optional) A public key in JWK format.\n *\n * A JSON Web Key (JWK) that conforms to {@link https://datatracker.ietf.org/doc/html/rfc7517 | RFC 7517}.\n */\n publicKeyJwk?: Jwk;\n\n /**\n * (Optional) A public key in Multibase format.\n *\n * A multibase key that conforms to the draft\n * {@link https://datatracker.ietf.org/doc/draft-multiformats-multibase/ | Multibase specification}.\n */\n publicKeyMultibase?: string;\n}\n\n/**\n * Represents the various verification relationships defined in a DID document.\n *\n * These verification relationships indicate the intended usage of verification methods within a DID\n * document. Each relationship signifies a different purpose or context in which a verification\n * method can be used, such as authentication, assertionMethod, keyAgreement, capabilityDelegation,\n * and capabilityInvocation. The array provides a standardized set of relationship names for\n * consistent referencing and implementation across different DID methods.\n *\n * @see {@link https://www.w3.org/TR/did-core/#verification-relationships | DID Core Specification, \u00A7 Verification Relationships}\n */\nexport enum DidVerificationRelationship {\n /**\n * Specifies how the DID subject is expected to be authenticated. This is commonly used for\n * purposes like logging into a website or participating in challenge-response protocols.\n *\n * @see {@link https://www.w3.org/TR/did-core/#authentication | DID Core Specification, \u00A7 Authentication}\n */\n authentication = 'authentication',\n\n /**\n * Specifies how the DID subject is expected to express claims, such as for issuing Verifiable\n * Credentials. This relationship is typically used when the DID subject is the issuer of a\n * credential.\n *\n * @see {@link https://www.w3.org/TR/did-core/#assertion | DID Core Specification, \u00A7 Assertion}\n */\n assertionMethod = 'assertionMethod',\n\n /**\n * Specifies how an entity can generate encryption material to communicate confidentially with the\n * DID subject. Often used in scenarios requiring secure communication channels.\n *\n * @see {@link https://www.w3.org/TR/did-core/#key-agreement | DID Core Specification, \u00A7 Key Agreement}\n */\n keyAgreement = 'keyAgreement',\n\n /**\n * Specifies a verification method used by the DID subject to invoke a cryptographic capability.\n * This is frequently associated with authorization actions, like updating the DID Document.\n *\n * @see {@link https://www.w3.org/TR/did-core/#capability-invocation | DID Core Specification, \u00A7 Capability Invocation}\n */\n capabilityInvocation = 'capabilityInvocation',\n\n /**\n * Specifies a mechanism used by the DID subject to delegate a cryptographic capability to another\n * party. This can include delegating access to a specific resource or API.\n *\n * @see {@link https://www.w3.org/TR/did-core/#capability-delegation | DID Core Specification, \u00A7 Capability Delegation}\n */\n capabilityDelegation = 'capabilityDelegation',\n}", "import type { KeyValueStore } from '@enbox/common';\n\nimport type { DidDereferencingOptions, DidDereferencingResult, DidResolutionOptions, DidResolutionResult } from './did-core.js';\n\n/**\n * Represents the interface for resolving a Decentralized Identifier (DID) to its corresponding DID\n * document.\n *\n * The `DidResolver` interface defines a single method, `resolve`, which takes a DID URL as input\n * and returns a `Promise` that resolves to a `DidResolutionResult`. This result contains the DID\n * document associated with the given DID, along with metadata about the resolution process.\n *\n * Implementations of this interface are expected to support resolution of DIDs according to the\n * specific rules and methods defined by the DID scheme in use.\n *\n * More information on DID URL dereferencing can be found in the\n * {@link https://www.w3.org/TR/did-core/#did-resolution | DID Core specification}.\n *\n * @example\n * ```typescript\n * const resolutionResult = await didResolver.resolve('did:example:123456789abcdefghi');\n * ```\n */\nexport interface DidResolver {\n /**\n * Resolves a DID URI to a DID document and associated metadata.\n *\n * This function should resolve the DID URI in accordance with the relevant DID method\n * specification, using the provided `options`.\n *\n * @param didUri - The DID URI to be resolved.\n * @param options - Optional. The options used for resolving the DID.\n * @returns A {@link DidResolutionResult} object containing the DID document and metadata or an\n * error.\n */\n resolve(didUrl: string, options?: DidResolutionOptions): Promise<DidResolutionResult>;\n}\n\n/**\n * Interface for cache implementations used by to store resolved DID documents.\n */\nexport interface DidResolverCache extends KeyValueStore<string, DidResolutionResult | void> {}\n\n/**\n * Represents the interface for dereferencing a DID URL to a specific resource within a DID\n * document.\n *\n * The `DidUrlDereferencer` interface defines a single method, `dereference`, which takes a DID URL\n * as input and returns a `Promise` that resolves to a `DidDereferencingResult`. This result\n * includes the dereferenced resource (if found) and metadata about the dereferencing process.\n *\n * Dereferencing a DID URL involves parsing the URL to identify the specific part of the DID\n * document being referenced, which could be a verification method, a service endpoint, or the\n * entire document itself.\n *\n * Implementations of this interface must adhere to the dereferencing mechanisms defined in the DID\n * Core specifications, handling various components of the DID URL including the DID itself, path,\n * query, and fragment.\n *\n * More information on DID URL dereferencing can be found in the\n * {@link https://www.w3.org/TR/did-core/#did-url-dereferencing | DID Core specification}.\n *\n * @example\n * ```typescript\n * const dereferenceResult = await didUrlDereferencer.dereference('did:example:123456789abcdefghi#keys-1');\n * ```\n */\nexport interface DidUrlDereferencer {\n /**\n * Dereferences a DID (Decentralized Identifier) URL to a corresponding DID resource.\n *\n * This method interprets the DID URL's components, which include the DID method, method-specific\n * identifier, path, query, and fragment, and retrieves the related resource as per the DID Core\n * specifications.\n *\n * @param didUrl - The DID URL string to dereference.\n * @param options - Input options to the dereference function. Optional.\n * @returns a {@link DidDereferencingResult}\n */\n dereference(didUrl: string, options?: DidDereferencingOptions): Promise<DidDereferencingResult>;\n}\n\n/**\n * A constant representing an empty DID Resolution Result. This object is used as the basis for a\n * result of DID resolution and is typically augmented with additional properties by the\n * DID method resolver.\n */\nexport const EMPTY_DID_RESOLUTION_RESULT: DidResolutionResult = {\n '@context' : 'https://w3id.org/did-resolution/v1',\n didResolutionMetadata : {},\n didDocument : null,\n didDocumentMetadata : {},\n};", "/**\n * The `Did` class represents a Decentralized Identifier (DID) Uniform Resource Identifier (URI).\n *\n * This class provides a method for parsing a DID URI string into its component parts, as well as a\n * method for serializing a DID URI object into a string.\n *\n * A DID URI is composed of the following components:\n * - scheme\n * - method\n * - id\n * - path\n * - query\n * - fragment\n * - params\n *\n * @see {@link https://www.w3.org/TR/did-core/#did-syntax | DID Core Specification, \u00A7 DID Syntax}\n */\nexport class Did {\n /** Regular expression pattern for matching the method component of a DID URI. */\n static readonly METHOD_PATTERN = '([a-z0-9]+)';\n /** Regular expression pattern for matching percent-encoded characters in a method identifier. */\n static readonly PCT_ENCODED_PATTERN = '(?:%[0-9a-fA-F]{2})';\n /** Regular expression pattern for matching the characters allowed in a method identifier. */\n static readonly ID_CHAR_PATTERN = `(?:[a-zA-Z0-9._-]|${Did.PCT_ENCODED_PATTERN})`;\n /** Regular expression pattern for matching the method identifier component of a DID URI. */\n static readonly METHOD_ID_PATTERN = `((?:${Did.ID_CHAR_PATTERN}*:)*(${Did.ID_CHAR_PATTERN}+))`;\n /** Regular expression pattern for matching the path component of a DID URI. */\n static readonly PATH_PATTERN = `(/[^#?]*)?`;\n /** Regular expression pattern for matching the query component of a DID URI. */\n static readonly QUERY_PATTERN = `([?][^#]*)?`;\n /** Regular expression pattern for matching the fragment component of a DID URI. */\n static readonly FRAGMENT_PATTERN = `(#.*)?`;\n /** Regular expression pattern for matching all of the components of a DID URI. */\n static readonly DID_URI_PATTERN = new RegExp(\n '^did:(?<method>' + Did.METHOD_PATTERN + '):(?<id>' + Did.METHOD_ID_PATTERN + ')' +\n '(?<path>' + Did.PATH_PATTERN + ')(?<query>' + Did.QUERY_PATTERN + ')' +\n '(?<fragment>' + Did.FRAGMENT_PATTERN + ')$'\n );\n\n /**\n * A string representation of the DID.\n *\n * A DID is a URI composed of three parts: the scheme `did:`, a method identifier, and a unique,\n * method-specific identifier specified by the DID method.\n *\n * @example\n * did:dht:h4d3ixkwt6q5a455tucw7j14jmqyghdtbr6cpiz6on5oxj5bpr3o\n */\n uri: string;\n\n /**\n * The name of the DID method.\n *\n * Examples of DID method names are `dht`, `jwk`, and `web`, among others.\n */\n method: string;\n\n /**\n * The DID method identifier.\n *\n * @example\n * h4d3ixkwt6q5a455tucw7j14jmqyghdtbr6cpiz6on5oxj5bpr3o\n */\n id: string;\n\n /**\n * Optional path component of the DID URI.\n *\n * @example\n * did:web:tbd.website/path\n */\n path?: string;\n\n /**\n * Optional query component of the DID URI.\n *\n * @example\n * did:web:tbd.website?versionId=1\n */\n query?: string;\n\n /**\n * Optional fragment component of the DID URI.\n *\n * @example\n * did:web:tbd.website#key-1\n */\n fragment?: string;\n\n /**\n * Optional query parameters in the DID URI.\n *\n * @example\n * did:web:tbd.website?service=files&relativeRef=/whitepaper.pdf\n */\n params?: Record<string, string>;\n\n /**\n * Constructs a new `Did` instance from individual components.\n *\n * @param params - An object containing the parameters to be included in the DID URI.\n * @param params.method - The name of the DID method.\n * @param params.id - The DID method identifier.\n * @param params.path - Optional. The path component of the DID URI.\n * @param params.query - Optional. The query component of the DID URI.\n * @param params.fragment - Optional. The fragment component of the DID URI.\n * @param params.params - Optional. The query parameters in the DID URI.\n */\n constructor({ method, id, path, query, fragment, params }: {\n method: string,\n id: string,\n path?: string,\n query?: string,\n fragment?: string,\n params?: Record<string, string>\n }) {\n this.uri = `did:${method}:${id}`;\n this.method = method;\n this.id = id;\n this.path = path;\n this.query = query;\n this.fragment = fragment;\n this.params = params;\n }\n\n /**\n * Parses a DID URI string into its individual components.\n *\n * @example\n * ```ts\n * const did = Did.parse('did:example:123?service=agent&relativeRef=/credentials#degree');\n *\n * console.log(did.uri) // Output: 'did:example:123'\n * console.log(did.method) // Output: 'example'\n * console.log(did.id) // Output: '123'\n * console.log(did.query) // Output: 'service=agent&relativeRef=/credentials'\n * console.log(did.fragment) // Output: 'degree'\n * console.log(did.params) // Output: { service: 'agent', relativeRef: '/credentials' }\n * ```\n *\n * @params didUri - The DID URI string to be parsed.\n * @returns A `Did` object representing the parsed DID URI, or `null` if the input string is not a valid DID URI.\n */\n static parse(didUri: string): Did | null {\n // Return null if the input string is empty or not provided.\n if (!didUri) {return null;}\n\n // Execute the regex pattern on the input string to extract URI components.\n const match = Did.DID_URI_PATTERN.exec(didUri);\n\n // If the pattern does not match, or if the required groups are not found, return null.\n if (!match || !match.groups) {return null;}\n\n // Extract the method, id, params, path, query, and fragment from the regex match groups.\n const { method, id, path, query, fragment } = match.groups;\n\n // Initialize a new Did object with the uri, method and id.\n const did: Did = {\n uri: `did:${method}:${id}`,\n method,\n id,\n };\n\n // If path is present, add it to the Did object.\n if (path) {did.path = path;}\n\n // If query is present, add it to the Did object, removing the leading '?'.\n if (query) {did.query = query.slice(1);}\n\n // If fragment is present, add it to the Did object, removing the leading '#'.\n if (fragment) {did.fragment = fragment.slice(1);}\n\n // If query params are present, parse them into a key-value object and add to the Did object.\n if (query) {\n const parsedParams = {} as Record<string, string>;\n // Split the query string by '&' to get individual parameter strings.\n const paramPairs = query.slice(1).split('&');\n for (const pair of paramPairs) {\n // Split each parameter string by '=' to separate keys and values.\n const [key, value] = pair.split('=');\n parsedParams[key] = value;\n }\n did.params = parsedParams;\n }\n\n return did;\n }\n}", "/**\n * A custom error class for DID-related errors.\n */\nexport class DidError extends Error {\n /**\n * Constructs an instance of DidError, a custom error class for handling DID-related errors.\n *\n * @param code - A {@link DidErrorCode} representing the specific type of error encountered.\n * @param message - A human-readable description of the error.\n */\n constructor(public code: DidErrorCode, message: string) {\n super(`${code}: ${message}`);\n this.name = 'DidError';\n\n // Ensures that instanceof works properly, the correct prototype chain when using inheritance,\n // and that V8 stack traces (like Chrome, Edge, and Node.js) are more readable and relevant.\n Object.setPrototypeOf(this, new.target.prototype);\n\n // Captures the stack trace in V8 engines (like Chrome, Edge, and Node.js).\n // In non-V8 environments, the stack trace will still be captured.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, DidError);\n }\n }\n}\n\n/**\n * An enumeration of possible DID error codes.\n */\nexport enum DidErrorCode {\n /** The DID supplied does not conform to valid syntax. */\n InvalidDid = 'invalidDid',\n\n /** The supplied method name is not supported by the DID method and/or DID resolver implementation. */\n MethodNotSupported = 'methodNotSupported',\n\n /** An unexpected error occurred during the requested DID operation. */\n InternalError = 'internalError',\n\n /** The DID document supplied does not conform to valid syntax. */\n InvalidDidDocument = 'invalidDidDocument',\n\n /** The byte length of a DID document does not match the expected value. */\n InvalidDidDocumentLength = 'invalidDidDocumentLength',\n\n /** The DID URL supplied to the dereferencing function does not conform to valid syntax. */\n InvalidDidUrl = 'invalidDidUrl',\n\n /** The given proof of a previous DID is invalid */\n InvalidPreviousDidProof = 'invalidPreviousDidProof',\n\n /** An invalid public key is detected during a DID operation. */\n InvalidPublicKey = 'invalidPublicKey',\n\n /** The byte length of a public key does not match the expected value. */\n InvalidPublicKeyLength = 'invalidPublicKeyLength',\n\n /** An invalid public key type was detected during a DID operation. */\n InvalidPublicKeyType = 'invalidPublicKeyType',\n\n /** Verification of a signature failed during a DID operation. */\n InvalidSignature = 'invalidSignature',\n\n /** The DID resolver was unable to find the DID document resulting from the resolution request. */\n NotFound = 'notFound',\n\n /**\n * The representation requested via the `accept` input metadata property is not supported by the\n * DID method and/or DID resolver implementation.\n */\n RepresentationNotSupported = 'representationNotSupported',\n\n /** The type of a public key is not supported by the DID method and/or DID resolver implementation. */\n UnsupportedPublicKeyType = 'unsupportedPublicKeyType',\n}", "import type {\n CryptoApi,\n EnclosedSignParams,\n EnclosedVerifyParams,\n Jwk,\n KeyIdentifier,\n KeyImporterExporter,\n KmsExportKeyParams,\n KmsImportKeyParams,\n Signer,\n} from '@enbox/crypto';\n\nimport { CryptoUtils, LocalKeyManager } from '@enbox/crypto';\n\nimport type { DidDocument } from './types/did-core.js';\nimport type { DidMetadata, PortableDid } from './types/portable-did.js';\n\nimport { DidError, DidErrorCode } from './did-error.js';\nimport { extractDidFragment, getVerificationMethods } from './utils.js';\n\n/**\n * A `BearerDidSigner` extends the {@link Signer} interface to include specific properties for\n * signing with a Decentralized Identifier (DID). It encapsulates the algorithm and key identifier,\n * which are often needed when signing JWTs, JWSs, JWEs, and other data structures.\n *\n * Typically, the algorithm and key identifier are used to populate the `alg` and `kid` fields of a\n * JWT or JWS header.\n */\nexport interface BearerDidSigner extends Signer {\n /**\n * The cryptographic algorithm identifier used for signing operations.\n *\n * Typically, this value is used to populate the `alg` field of a JWT or JWS header. The\n * registered algorithm names are defined in the\n * {@link https://www.iana.org/assignments/jose/jose.xhtml#web-signature-encryption-algorithms |\n * IANA JSON Web Signature and Encryption Algorithms registry}.\n *\n * @example\n * \"ES256\" // ECDSA using P-256 and SHA-256\n */\n algorithm: string;\n\n /**\n * The unique identifier of the key within the DID document that is used for signing and\n * verification operations.\n *\n * This identifier must be a DID URI with a fragment (e.g., did:method:123#key-0) that references\n * a specific verification method in the DID document. It allows users of a `BearerDidSigner` to\n * determine the DID and key that will be used for signing and verification operations.\n *\n * @example\n * \"did:dht:123#key-1\" // A fragment identifier referring to a key in the DID document\n */\n keyId: string;\n}\n\n/**\n * Represents a Decentralized Identifier (DID) along with its DID document, key manager, metadata,\n * and convenience functions.\n */\nexport class BearerDid {\n /** {@inheritDoc Did#uri} */\n uri: string;\n\n /**\n * The DID document associated with this DID.\n *\n * @see {@link https://www.w3.org/TR/did-core/#dfn-diddocument | DID Core Specification, \u00A7 DID Document}\n */\n document: DidDocument;\n\n /** {@inheritDoc DidMetadata} */\n metadata: DidMetadata;\n\n /**\n * Key Management System (KMS) used to manage the DIDs keys and sign data.\n *\n * Each DID method requires at least one key be present in the provided `keyManager`.\n */\n keyManager: CryptoApi;\n\n constructor({ uri, document, metadata, keyManager }: {\n uri: string,\n document: DidDocument,\n metadata: DidMetadata,\n keyManager: CryptoApi\n }) {\n this.uri = uri;\n this.document = document;\n this.metadata = metadata;\n this.keyManager = keyManager;\n }\n\n /**\n * Converts a `BearerDid` object to a portable format containing the URI and verification methods\n * associated with the DID.\n *\n * This method is useful when you need to represent the key material and metadata associated with\n * a DID in format that can be used independently of the specific DID method implementation. It\n * extracts both public and private keys from the DID's key manager and organizes them into a\n * `PortableDid` structure.\n *\n * @remarks\n * If the DID's key manager does not allow private keys to be exported, the `PortableDid` returned\n * will not contain a `privateKeys` property. This enables the importing and exporting DIDs that\n * use the same underlying KMS even if the KMS does not support exporting private keys. Examples\n * include hardware security modules (HSMs) and cloud-based KMS services like AWS KMS.\n *\n * If the DID's key manager does support exporting private keys, the resulting `PortableDid` will\n * include a `privateKeys` property which contains the same number of entries as there are\n * verification methods as the DID document, each with its associated private key and the\n * purpose(s) for which the key can be used (e.g., `authentication`, `assertionMethod`, etc.).\n *\n * @example\n * ```ts\n * // Assuming `did` is an instance of BearerDid\n * const portableDid = await did.export();\n * // portableDid now contains the DID URI, document, metadata, and optionally, private keys.\n * ```\n *\n * @returns A `PortableDid` containing the URI, DID document, metadata, and optionally private\n * keys associated with the `BearerDid`.\n * @throws An error if the DID document does not contain any verification methods or the keys for\n * any verification method are missing in the key manager.\n */\n public async export(): Promise<PortableDid> {\n // Verify the DID document contains at least one verification method.\n if (!(Array.isArray(this.document.verificationMethod) && this.document.verificationMethod.length > 0)) {\n throw new Error(`DID document for '${this.uri}' is missing verification methods`);\n }\n\n // Create a new `PortableDid` copy object to store the exported data.\n const portableDid: PortableDid = JSON.parse(JSON.stringify({\n uri : this.uri,\n document : this.document,\n metadata : this.metadata\n }));\n\n // If the BearerDid's key manager supports exporting private keys, add them to the portable DID.\n if ('exportKey' in this.keyManager && typeof this.keyManager.exportKey === 'function') {\n const privateKeys: Jwk[] = [];\n for (const vm of this.document.verificationMethod) {\n if (!vm.publicKeyJwk) {\n throw new Error(`Verification method '${vm.id}' does not contain a public key in JWK format`);\n }\n\n // Compute the key URI of the verification method's public key.\n const keyUri = await this.keyManager.getKeyUri({ key: vm.publicKeyJwk });\n\n // Retrieve the private key from the key manager.\n const privateKey = await this.keyManager.exportKey({ keyUri }) as Jwk;\n\n // Add the verification method to the key set.\n privateKeys.push({ ...privateKey });\n }\n portableDid.privateKeys = privateKeys;\n }\n\n return portableDid;\n }\n\n /**\n * Return a {@link Signer} that can be used to sign messages, credentials, or arbitrary data.\n *\n * If given, the `methodId` parameter is used to select a key from the verification methods\n * present in the DID Document.\n *\n * If `methodID` is not given, the first verification method intended for signing claims is used.\n *\n * @param params - The parameters for the `getSigner` operation.\n * @param params.methodId - ID of the verification method key that will be used for sign and\n * verify operations. Optional.\n * @returns An instantiated {@link Signer} that can be used to sign and verify data.\n */\n public async getSigner(params?: { methodId: string }): Promise<BearerDidSigner> {\n // Attempt to find a verification method that matches the given method ID, or if not given,\n // find the first verification method intended for signing claims.\n const verificationMethod = this.document.verificationMethod?.find(\n vm => extractDidFragment(vm.id) === (extractDidFragment(params?.methodId) ?? extractDidFragment(this.document.assertionMethod?.[0]))\n );\n\n if (!(verificationMethod && verificationMethod.publicKeyJwk)) {\n throw new DidError(DidErrorCode.InternalError, 'A verification method intended for signing could not be determined from the DID Document');\n }\n\n // Compute the expected key URI of the signing key.\n const keyUri = await this.keyManager.getKeyUri({ key: verificationMethod.publicKeyJwk });\n\n // Get the public key to be used for verify operations, which also verifies that the key is\n // present in the key manager's store.\n const publicKey = await this.keyManager.getPublicKey({ keyUri });\n\n // Bind the DID's key manager to the signer.\n const keyManager = this.keyManager;\n\n // Determine the signing algorithm.\n const algorithm = CryptoUtils.getJoseSignatureAlgorithmFromPublicKey(publicKey);\n\n return {\n algorithm : algorithm,\n keyId : verificationMethod.id,\n\n async sign({ data }: EnclosedSignParams): Promise<Uint8Array> {\n const signature = await keyManager.sign({ data, keyUri: keyUri! }); // `keyUri` is guaranteed to be defined at this point.\n return signature;\n },\n\n async verify({ data, signature }: EnclosedVerifyParams): Promise<boolean> {\n const isValid = await keyManager.verify({ data, key: publicKey!, signature }); // `publicKey` is guaranteed to be defined at this point.\n return isValid;\n }\n };\n }\n\n /**\n * Instantiates a {@link BearerDid} object from a given {@link PortableDid}.\n *\n * This method allows for the creation of a `BearerDid` object using a previously created DID's\n * key material, DID document, and metadata.\n *\n * @example\n * ```ts\n * // Export an existing BearerDid to PortableDid format.\n * const portableDid = await did.export();\n * // Reconstruct a BearerDid object from the PortableDid.\n * const did = await BearerDid.import({ portableDid });\n * ```\n *\n * @param params - The parameters for the import operation.\n * @param params.portableDid - The PortableDid object to import.\n * @param params.keyManager - Optionally specify an external Key Management System (KMS) used to\n * generate keys and sign data. If not given, a new\n * {@link LocalKeyManager} instance will be created and\n * used.\n * @returns A Promise resolving to a `BearerDid` object representing the DID formed from the\n * provided PortableDid.\n * @throws An error if the PortableDid document does not contain any verification methods or the\n * keys for any verification method are missing in the key manager.\n */\n public static async import({ portableDid, keyManager = new LocalKeyManager() }: {\n keyManager?: CryptoApi & KeyImporterExporter<KmsImportKeyParams, KeyIdentifier, KmsExportKeyParams>;\n portableDid: PortableDid;\n }): Promise<BearerDid> {\n\n // Get all verification methods from the given DID document, including embedded methods.\n const verificationMethods = getVerificationMethods({ didDocument: portableDid.document });\n\n // Validate that the DID document contains at least one verification method.\n if (verificationMethods.length === 0) {\n throw new DidError(DidErrorCode.InvalidDidDocument, `At least one verification method is required but 0 were given`);\n }\n\n // If given, import the private key material into the key manager.\n for (const key of portableDid.privateKeys ?? []) {\n\n // confirm th key does not already exist before importing it to avoid failures from the key manager\n const keyUri = await keyManager.getKeyUri({ key });\n const keyExists = await keyManager.getPublicKey({ keyUri }).then(() => true).catch(() => false);\n if (!keyExists) {\n await keyManager.importKey({ key });\n }\n }\n\n // Validate that the key material for every verification method in the DID document is present\n // in the key manager.\n for (const vm of verificationMethods) {\n if (!vm.publicKeyJwk) {\n throw new Error(`Verification method '${vm.id}' does not contain a public key in JWK format`);\n }\n\n // Compute the key URI of the verification method's public key.\n const keyUri = await keyManager.getKeyUri({ key: vm.publicKeyJwk });\n\n // Verify that the key is present in the key manager. If not, an error is thrown.\n await keyManager.getPublicKey({ keyUri });\n }\n\n // Use the given PortableDid to construct the BearerDid object.\n const did = new BearerDid({\n uri : portableDid.uri,\n document : portableDid.document,\n metadata : portableDid.metadata,\n keyManager\n });\n\n return did;\n }\n}", "export * from './crypto-error.js';\nexport * from './local-key-manager.js';\nexport * from './utils.js';\n\nexport * from './algorithms/aes-ctr.js';\nexport * from './algorithms/aes-gcm.js';\nexport * from './algorithms/crypto-algorithm.js';\nexport * from './algorithms/ecdsa.js';\nexport * from './algorithms/eddsa.js';\nexport * from './algorithms/sha-2.js';\n\nexport * from './jose/jwe.js';\nexport * from './jose/jwk.js';\nexport * from './jose/jws.js';\nexport * from './jose/jwt.js';\nexport * from './jose/utils.js';\n\nexport * from './primitives/aes-ctr.js';\nexport * from './primitives/aes-gcm.js';\nexport * from './primitives/aes-kw.js';\nexport * from './primitives/concat-kdf.js';\nexport * from './primitives/ed25519.js';\nexport * from './primitives/hkdf.js';\nexport * from './primitives/secp256r1.js';\nexport * from './primitives/pbkdf2.js';\nexport * from './primitives/secp256k1.js';\nexport * from './primitives/sha256.js';\nexport * from './primitives/x25519.js';\nexport * from './primitives/xchacha20.js';\nexport * from './primitives/xchacha20-poly1305.js';\n\nexport type * from './types/cipher.js';\nexport type * from './types/crypto-api.js';\nexport type * from './types/hasher.js';\nexport type * from './types/identifier.js';\nexport type * from './types/key-compressor.js';\nexport type * from './types/key-converter.js';\nexport type * from './types/key-deriver.js';\nexport type * from './types/key-generator.js';\nexport type * from './types/key-io.js';\nexport type * from './types/key-wrapper.js';\nexport type * from './types/params-direct.js';\nexport type * from './types/params-enclosed.js';\nexport type * from './types/params-kms.js';\nexport type * from './types/signer.js';", "/**\n * A custom error class for Crypto-related errors.\n */\nexport class CryptoError extends Error {\n /**\n * Constructs an instance of CryptoError, a custom error class for handling Crypto-related errors.\n *\n * @param code - A {@link CryptoErrorCode} representing the specific type of error encountered.\n * @param message - A human-readable description of the error.\n */\n constructor(public code: CryptoErrorCode, message: string) {\n super(message);\n this.name = 'CryptoError';\n\n // Ensures that instanceof works properly, the correct prototype chain when using inheritance,\n // and that V8 stack traces (like Chrome, Edge, and Node.js) are more readable and relevant.\n Object.setPrototypeOf(this, new.target.prototype);\n\n // Captures the stack trace in V8 engines (like Chrome, Edge, and Node.js).\n // In non-V8 environments, the stack trace will still be captured.\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, CryptoError);\n }\n }\n}\n\n/**\n * An enumeration of possible Crypto error codes.\n */\nexport enum CryptoErrorCode {\n /** The supplied algorithm identifier is not supported by the implementation. */\n AlgorithmNotSupported = 'algorithmNotSupported',\n\n /** The encoding operation (either encoding or decoding) failed. */\n EncodingError = 'encodingError',\n\n /** The JWE supplied does not conform to valid syntax. */\n InvalidJwe = 'invalidJwe',\n\n /** The JWK supplied does not conform to valid syntax. */\n InvalidJwk = 'invalidJwk',\n\n /** The requested operation is not supported by the implementation. */\n OperationNotSupported = 'operationNotSupported',\n}\n", "export type * from './types.js';\n\nexport * from './cache.js';\nexport * from './convert.js';\nexport * from './logger.js';\nexport * from './multicodec.js';\nexport * from './object.js';\nexport * from './stores.js';\nexport * from './stream.js';\nexport * from './type-utils.js';", "import TTLCache from '@isaacs/ttlcache';\nexport { TTLCache as TtlCache };", "import { rfc4648 } from './base.js'\n\nexport const base32 = rfc4648({\n prefix: 'b',\n name: 'base32',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567',\n bitsPerChar: 5\n})\n\nexport const base32upper = rfc4648({\n prefix: 'B',\n name: 'base32upper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567',\n bitsPerChar: 5\n})\n\nexport const base32pad = rfc4648({\n prefix: 'c',\n name: 'base32pad',\n alphabet: 'abcdefghijklmnopqrstuvwxyz234567=',\n bitsPerChar: 5\n})\n\nexport const base32padupper = rfc4648({\n prefix: 'C',\n name: 'base32padupper',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=',\n bitsPerChar: 5\n})\n\nexport const base32hex = rfc4648({\n prefix: 'v',\n name: 'base32hex',\n alphabet: '0123456789abcdefghijklmnopqrstuv',\n bitsPerChar: 5\n})\n\nexport const base32hexupper = rfc4648({\n prefix: 'V',\n name: 'base32hexupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV',\n bitsPerChar: 5\n})\n\nexport const base32hexpad = rfc4648({\n prefix: 't',\n name: 'base32hexpad',\n alphabet: '0123456789abcdefghijklmnopqrstuv=',\n bitsPerChar: 5\n})\n\nexport const base32hexpadupper = rfc4648({\n prefix: 'T',\n name: 'base32hexpadupper',\n alphabet: '0123456789ABCDEFGHIJKLMNOPQRSTUV=',\n bitsPerChar: 5\n})\n\nexport const base32z = rfc4648({\n prefix: 'h',\n name: 'base32z',\n alphabet: 'ybndrfg8ejkmcpqxot1uwisza345h769',\n bitsPerChar: 5\n})\n", "import { coerce } from '../bytes.js'\nimport basex from '../vendor/base-x.js'\nimport type { BaseCodec, BaseDecoder, BaseEncoder, CombobaseDecoder, Multibase, MultibaseCodec, MultibaseDecoder, MultibaseEncoder, UnibaseDecoder } from './interface.js'\n\ninterface EncodeFn { (bytes: Uint8Array): string }\ninterface DecodeFn { (text: string): Uint8Array }\n\n/**\n * Class represents both BaseEncoder and MultibaseEncoder meaning it\n * can be used to encode to multibase or base encode without multibase\n * prefix.\n */\nclass Encoder<Base extends string, Prefix extends string> implements MultibaseEncoder<Prefix>, BaseEncoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n encode (bytes: Uint8Array): Multibase<Prefix> {\n if (bytes instanceof Uint8Array) {\n return `${this.prefix}${this.baseEncode(bytes)}`\n } else {\n throw Error('Unknown type, must be binary type')\n }\n }\n}\n\n/**\n * Class represents both BaseDecoder and MultibaseDecoder so it could be used\n * to decode multibases (with matching prefix) or just base decode strings\n * with corresponding base encoding.\n */\nclass Decoder<Base extends string, Prefix extends string> implements MultibaseDecoder<Prefix>, UnibaseDecoder<Prefix>, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseDecode: DecodeFn\n private readonly prefixCodePoint: number\n\n constructor (name: Base, prefix: Prefix, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n this.prefixCodePoint = prefix.codePointAt(0) as number\n this.baseDecode = baseDecode\n }\n\n decode (text: string): Uint8Array {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n or<OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n}\n\ntype Decoders<Prefix extends string> = Record<Prefix, UnibaseDecoder<Prefix>>\n\nclass ComposedDecoder<Prefix extends string> implements MultibaseDecoder<Prefix>, CombobaseDecoder<Prefix> {\n readonly decoders: Decoders<Prefix>\n\n constructor (decoders: Decoders<Prefix>) {\n this.decoders = decoders\n }\n\n or <OtherPrefix extends string> (decoder: UnibaseDecoder<OtherPrefix> | ComposedDecoder<OtherPrefix>): ComposedDecoder<Prefix | OtherPrefix> {\n return or(this, decoder)\n }\n\n decode (input: string): Uint8Array {\n const prefix = input[0] as Prefix\n const decoder = this.decoders[prefix]\n if (decoder != null) {\n return decoder.decode(input)\n } else {\n throw RangeError(`Unable to decode multibase string ${JSON.stringify(input)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)\n }\n }\n}\n\nexport function or <L extends string, R extends string> (left: UnibaseDecoder<L> | CombobaseDecoder<L>, right: UnibaseDecoder<R> | CombobaseDecoder<R>): ComposedDecoder<L | R> {\n // eslint-disable-next-line @typescript-eslint/consistent-type-assertions\n return new ComposedDecoder({\n ...(left.decoders ?? { [(left as UnibaseDecoder<L>).prefix]: left }),\n ...(right.decoders ?? { [(right as UnibaseDecoder<R>).prefix]: right })\n } as Decoders<L | R>)\n}\n\nexport class Codec<Base extends string, Prefix extends string> implements MultibaseCodec<Prefix>, MultibaseEncoder<Prefix>, MultibaseDecoder<Prefix>, BaseCodec, BaseEncoder, BaseDecoder {\n readonly name: Base\n readonly prefix: Prefix\n readonly baseEncode: EncodeFn\n readonly baseDecode: DecodeFn\n readonly encoder: Encoder<Base, Prefix>\n readonly decoder: Decoder<Base, Prefix>\n\n constructor (name: Base, prefix: Prefix, baseEncode: EncodeFn, baseDecode: DecodeFn) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n encode (input: Uint8Array): string {\n return this.encoder.encode(input)\n }\n\n decode (input: string): Uint8Array {\n return this.decoder.decode(input)\n }\n}\n\nexport function from <Base extends string, Prefix extends string> ({ name, prefix, encode, decode }: { name: Base, prefix: Prefix, encode: EncodeFn, decode: DecodeFn }): Codec<Base, Prefix> {\n return new Codec(name, prefix, encode, decode)\n}\n\nexport function baseX <Base extends string, Prefix extends string> ({ name, prefix, alphabet }: { name: Base, prefix: Prefix, alphabet: string }): Codec<Base, Prefix> {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n decode: (text: string): Uint8Array => coerce(decode(text))\n })\n}\n\nfunction decode (string: string, alphabet: string, bitsPerChar: number, name: string): Uint8Array {\n // Build the character lookup table:\n const codes: Record<string, number> = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\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 = codes[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\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 return from({\n prefix,\n name,\n encode (input: Uint8Array): string {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input: string): Uint8Array {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n", "export const empty = new Uint8Array(0)\n\nexport function toHex (d: Uint8Array): string {\n return d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n}\n\nexport function fromHex (hex: string): Uint8Array {\n const hexes = hex.match(/../g)\n return hexes != null ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\nexport function equals (aa: Uint8Array, bb: Uint8Array): boolean {\n if (aa === bb) return true\n if (aa.byteLength !== bb.byteLength) {\n return false\n }\n\n for (let ii = 0; ii < aa.byteLength; ii++) {\n if (aa[ii] !== bb[ii]) {\n return false\n }\n }\n\n return true\n}\n\nexport function coerce (o: ArrayBufferView | ArrayBuffer | Uint8Array): Uint8Array {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\nexport function isBinary (o: unknown): o is ArrayBuffer | ArrayBufferView {\n return o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n}\n\nexport function fromString (str: string): Uint8Array {\n return new TextEncoder().encode(str)\n}\n\nexport function toString (b: Uint8Array): string {\n return new TextDecoder().decode(b)\n}\n", "/* eslint-disable */\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n/**\n * @param {string} ALPHABET\n * @param {any} name\n */\nfunction base (ALPHABET, name) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256);\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255;\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i);\n var xc = x.charCodeAt(0);\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i;\n }\n var BASE = ALPHABET.length;\n var LEADER = ALPHABET.charAt(0);\n var FACTOR = Math.log(BASE) / Math.log(256); // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE); // log(256) / log(BASE), rounded up\n /**\n * @param {any[] | Iterable<number>} source\n */\n function encode (source) {\n // @ts-ignore\n if (source instanceof Uint8Array) ; else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength);\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source);\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0;\n var length = 0;\n var pbegin = 0;\n var pend = source.length;\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++;\n zeroes++;\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0;\n var b58 = new Uint8Array(size);\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin];\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0;\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0;\n b58[it1] = (carry % BASE) >>> 0;\n carry = (carry / BASE) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n pbegin++;\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length;\n while (it2 !== size && b58[it2] === 0) {\n it2++;\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes);\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]); }\n return str\n }\n /**\n * @param {string | string[]} source\n */\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n var psz = 0;\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0;\n var length = 0;\n while (source[psz] === LEADER) {\n zeroes++;\n psz++;\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0; // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size);\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)];\n // Invalid character\n if (carry === 255) { return }\n var i = 0;\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0;\n b256[it3] = (carry % 256) >>> 0;\n carry = (carry / 256) >>> 0;\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i;\n psz++;\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length;\n while (it4 !== size && b256[it4] === 0) {\n it4++;\n }\n var vch = new Uint8Array(zeroes + (size - it4));\n var j = zeroes;\n while (it4 !== size) {\n vch[j++] = b256[it4++];\n }\n return vch\n }\n /**\n * @param {string | string[]} string\n */\n function decode (string) {\n var buffer = decodeUnsafe(string);\n if (buffer) { return buffer }\n throw new Error(`Non-${name} character`)\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nvar src = base;\n\nvar _brrp__multiformats_scope_baseX = src;\n\nexport default _brrp__multiformats_scope_baseX;\n", "import { baseX } from './base.js'\n\nexport const base58btc = baseX({\n name: 'base58btc',\n prefix: 'z',\n alphabet: '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n})\n\nexport const base58flickr = baseX({\n name: 'base58flickr',\n prefix: 'Z',\n alphabet: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ'\n})\n", "import { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n", "/**\n * Represents an array of a fixed length, preventing modifications to its size.\n *\n * The `FixedLengthArray` utility type transforms a standard array into a variant where\n * methods that could alter the length are omitted. It leverages TypeScript's advanced types,\n * such as conditional types and mapped types, to ensure that the array cannot be resized\n * through methods like `push`, `pop`, `splice`, `shift`, and `unshift`. The utility type\n * maintains all other characteristics of a standard array, including indexing, iteration,\n * and type checking for its elements.\n *\n * Note: The type does not prevent direct assignment to indices, even if it would exceed\n * the original length. However, such actions would lead to TypeScript type errors.\n *\n * @example\n * ```ts\n * // Declare a variable with a type of fixed-length array of three strings.\n * let myFixedLengthArray: FixedLengthArray< [string, string, string]>;\n *\n * // Array declaration tests\n * myFixedLengthArray = [ 'a', 'b', 'c' ]; // OK\n * myFixedLengthArray = [ 'a', 'b', 123 ]; // TYPE ERROR\n * myFixedLengthArray = [ 'a' ]; // LENGTH ERROR\n * myFixedLengthArray = [ 'a', 'b' ]; // LENGTH ERROR\n *\n * // Index assignment tests\n * myFixedLengthArray[1] = 'foo'; // OK\n * myFixedLengthArray[1000] = 'foo'; // INVALID INDEX ERROR\n *\n * // Methods that mutate array length\n * myFixedLengthArray.push('foo'); // MISSING METHOD ERROR\n * myFixedLengthArray.pop(); // MISSING METHOD ERROR\n *\n * // Direct length manipulation\n * myFixedLengthArray.length = 123; // READ-ONLY ERROR\n *\n * // Destructuring\n * let [ a ] = myFixedLengthArray; // OK\n * let [ a, b ] = myFixedLengthArray; // OK\n * let [ a, b, c ] = myFixedLengthArray; // OK\n * let [ a, b, c, d ] = myFixedLengthArray; // INVALID INDEX ERROR\n * ```\n *\n * @template T extends any[] - The array type to be transformed.\n */\nexport type FixedLengthArray<T extends any[]> =\n Pick<T, Exclude<keyof T, ArrayLengthMutationKeys>>\n & {\n /**\n * Custom iterator for the `FixedLengthArray` type.\n *\n * This iterator allows the `FixedLengthArray` to be used in standard iteration\n * contexts, such as `for...of` loops and spread syntax. It ensures that even though\n * the array is of a fixed length with disabled mutation methods, it still retains\n * iterable behavior similar to a regular array.\n *\n * @returns An IterableIterator for the array items.\n */\n [Symbol.iterator]: () => IterableIterator<ArrayItems<T>>\n };\n\n/** Helper types for {@link FixedLengthArray} */\ntype ArrayLengthMutationKeys = 'splice' | 'push' | 'pop' | 'shift' | 'unshift' | number;\ntype ArrayItems<T extends Array<any>> = T extends Array<infer TItems> ? TItems : never;\n\n/**\n * isArrayBufferSlice\n *\n * Checks if the ArrayBufferView represents a slice (subarray or a subview)\n * of an ArrayBuffer.\n *\n * An ArrayBufferView (TypedArray or DataView) can represent a portion of an\n * ArrayBuffer - such a view is said to be a \"slice\" of the original buffer.\n * This can occur when the `subarray` or `slice` method is called on a\n * TypedArray or when a DataView is created with a byteOffset and/or\n * byteLength that doesn't cover the full ArrayBuffer.\n *\n * @param arrayBufferView - The ArrayBufferView to be checked\n * @returns true if the ArrayBufferView represents a slice of an ArrayBuffer; false otherwise.\n */\nexport function isArrayBufferSlice(arrayBufferView: ArrayBufferView): boolean {\n return arrayBufferView.byteOffset !== 0 || arrayBufferView.byteLength !== arrayBufferView.buffer.byteLength;\n}\n\n/**\n * Checks if the given object is an AsyncIterable.\n *\n * An AsyncIterable is an object that implements the AsyncIterable protocol,\n * which means it has a [Symbol.asyncIterator] method. This function checks\n * if the provided object conforms to this protocol by verifying the presence\n * and type of the [Symbol.asyncIterator] method.\n *\n * @param obj - The object to be checked for AsyncIterable conformity.\n * @returns True if the object is an AsyncIterable, false otherwise.\n *\n * @example\n * ```ts\n * // Returns true for a valid AsyncIterable\n * const asyncIterable = {\n * async *[Symbol.asyncIterator]() {\n * yield 1;\n * yield 2;\n * }\n * };\n * console.log(isAsyncIterable(asyncIterable)); // true\n * ```\n *\n * @example\n * ```ts\n * // Returns false for a regular object\n * console.log(isAsyncIterable({ a: 1, b: 2 })); // false\n * ```\n */\nexport function isAsyncIterable(obj: any): obj is AsyncIterable<any> {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n return typeof obj[Symbol.asyncIterator] === 'function';\n}\n\n/**\n * isDefined\n *\n * Utility function to check if a variable is neither null nor undefined.\n * This function helps in making TypeScript infer the type of the variable\n * as being defined, excluding `null` and `undefined`.\n *\n * The function uses strict equality (`!==`) for the comparison, ensuring\n * that the variable is not just falsy (like an empty string or zero),\n * but is truly either `null` or `undefined`.\n *\n * @param arg - The variable to be checked\n * @returns true if the variable is neither `null` nor `undefined`\n */\nexport function isDefined<T>(arg: T): arg is Exclude<T, null | undefined> {\n return arg !== null && typeof arg !== 'undefined';\n}\n\n/**\n * Utility type that transforms a type `T` to have only certain keys `K` as required, while the\n * rest remain optional, except for keys specified in `O`, which are omitted entirely.\n *\n * This type is useful when you need a variation of a type where only specific properties are\n * required, and others are either optional or not included at all. It allows for more flexible type\n * definitions based on existing types without the need to redefine them.\n *\n * @template T - The original type to be transformed.\n * @template K - The keys of `T` that should be required.\n * @template O - The keys of `T` that should be omitted from the resulting type (optional).\n *\n * @example\n * ```ts\n * // Given an interface\n * interface Example {\n * requiredProp: string;\n * optionalProp?: number;\n * anotherOptionalProp?: boolean;\n * }\n *\n * // Making 'optionalProp' required and omitting 'anotherOptionalProp'\n * type ModifiedExample = RequireOnly<Example, 'optionalProp', 'anotherOptionalProp'>;\n * // Result: { requiredProp?: string; optionalProp: number; }\n * ```\n */\nexport type RequireOnly<T, K extends keyof T, O extends keyof T = never> = Required<Pick<T, K>> & Omit<Partial<T>, O>;\n\n/**\n * universalTypeOf\n *\n * Why does this function exist?\n *\n * You can typically check if a value is of a particular type, such as\n * Uint8Array or ArrayBuffer, by using the `instanceof` operator. The\n * `instanceof` operator checks the prototype property of a constructor\n * in the object's prototype chain.\n *\n * However, there is a caveat with the `instanceof` check if the value\n * was created from a different JavaScript context (like an iframe or\n * a web worker). In those cases, the `instanceof` check might fail\n * because each context has a different global object, and therefore,\n * different built-in constructor functions.\n *\n * The `typeof` operator provides information about the type of the\n * operand in a less detailed way. For basic data types like number,\n * string, boolean, and undefined, the `typeof` operator works as\n * expected. However, for objects, including arrays and null,\n * it always returns \"object\". For functions, it returns \"function\".\n * So, while `typeof` is good for basic type checking, it doesn't\n * give detailed information about complex data types.\n *\n * Unlike `instanceof` and `typeof`, `Object.prototype.toString.call(value)`\n * can ensure a consistent result across different JavaScript\n * contexts.\n *\n * Credit for inspiration:\n * Angus Croll\n * https://github.com/angus-c\n * https://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/\n */\nexport function universalTypeOf(value: unknown): string {\n // Returns '[Object Type]' string.\n const typeString = Object.prototype.toString.call(value);\n // Returns ['Object', 'Type'] array or null.\n const match = typeString.match(/\\s([a-zA-Z0-9]+)/);\n // Deconstructs the array and gets just the type from index 1.\n const [_, type] = match as RegExpMatchArray;\n\n return type;\n}\n\n/**\n * Utility type to extract the type resolved by a Promise.\n *\n * This type unwraps the type `T` from `Promise<T>` if `T` is a Promise, otherwise returns `T` as\n * is. It's useful in situations where you need to handle the type returned by a promise-based\n * function in a synchronous context, such as defining types for test vectors or handling return\n * types in non-async code blocks.\n *\n * @template T - The type to unwrap from the Promise.\n *\n * @example\n * ```ts\n * // For a Promise type, it extracts the resolved type.\n * type AsyncNumber = Promise<number>;\n * type UnwrappedNumber = UnwrapPromise<AsyncNumber>; // number\n *\n * // For a non-Promise type, it returns the type as is.\n * type StringValue = string;\n * type UnwrappedString = UnwrapPromise<StringValue>; // string\n * ```\n */\nexport type UnwrapPromise<T> = T extends Promise<infer U> ? U : T;", "import type { Multibase } from 'multiformats';\n\nimport { base32z } from 'multiformats/bases/base32';\nimport { base58btc } from 'multiformats/bases/base58';\nimport { base64url } from 'multiformats/bases/base64';\n\nimport { isArrayBufferSlice, isAsyncIterable, universalTypeOf } from './type-utils.js';\n\nconst textEncoder = new TextEncoder();\nconst textDecoder = new TextDecoder();\n\nexport class Convert {\n data: any;\n format: string;\n\n constructor(data: any, format: string) {\n this.data = data;\n this.format = format;\n }\n\n static arrayBuffer(data: ArrayBuffer): Convert {\n return new Convert(data, 'ArrayBuffer');\n }\n\n static asyncIterable(data: AsyncIterable<any>): Convert {\n if (!isAsyncIterable(data)) {\n throw new TypeError('Input must be of type AsyncIterable.');\n }\n return new Convert(data, 'AsyncIterable');\n }\n\n static base32Z(data: string): Convert {\n return new Convert(data, 'Base32Z');\n }\n\n static base58Btc(data: string): Convert {\n return new Convert(data, 'Base58Btc');\n }\n\n static base64Url(data: string): Convert {\n return new Convert(data, 'Base64Url');\n }\n\n /**\n * Reference:\n * The BufferSource type is a TypeScript type that represents an ArrayBuffer\n * or one of the ArrayBufferView types, such a TypedArray (e.g., Uint8Array)\n * or a DataView.\n */\n static bufferSource(data: BufferSource): Convert {\n return new Convert(data, 'BufferSource');\n }\n\n static hex(data: string): Convert {\n if (typeof data !== 'string') {\n throw new TypeError('Hex input must be a string.');\n }\n if (data.length % 2 !== 0) {\n throw new TypeError('Hex input must have an even number of characters.');\n }\n return new Convert(data, 'Hex');\n }\n\n static multibase(data: string): Convert {\n return new Convert(data, 'Multibase');\n }\n\n static object(data: Record<string, any>): Convert {\n return new Convert(data, 'Object');\n }\n\n static string(data: string): Convert {\n return new Convert(data, 'String');\n }\n\n static uint8Array(data: Uint8Array): Convert {\n return new Convert(data, 'Uint8Array');\n }\n\n toArrayBuffer(): ArrayBuffer {\n switch (this.format) {\n\n case 'Base58Btc': {\n return base58btc.baseDecode(this.data).buffer;\n }\n\n case 'Base64Url': {\n return base64url.baseDecode(this.data).buffer;\n }\n\n case 'BufferSource': {\n const dataType = universalTypeOf(this.data);\n if (dataType === 'ArrayBuffer') {\n // Data is already an ArrayBuffer, No conversion is necessary.\n return this.data;\n } else if (ArrayBuffer.isView(this.data)) {\n // Data is a DataView or a different TypedArray (e.g., Uint16Array).\n if (isArrayBufferSlice(this.data)) {\n // Data is a slice of an ArrayBuffer. Return a new ArrayBuffer or ArrayBufferView of the same slice.\n return this.data.buffer.slice(this.data.byteOffset, this.data.byteOffset + this.data.byteLength);\n } else {\n // Data is a whole ArrayBuffer viewed as a different TypedArray or DataView. Return the whole ArrayBuffer.\n return this.data.buffer;\n }\n } else {\n throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`);\n }\n }\n\n case 'Hex': {\n return this.toUint8Array().buffer;\n }\n\n case 'String': {\n return this.toUint8Array().buffer;\n }\n\n case 'Uint8Array': {\n return this.data.buffer;\n }\n\n default:\n throw new TypeError(`Conversion from ${this.format} to ArrayBuffer is not supported.`);\n }\n }\n\n async toArrayBufferAsync(): Promise<ArrayBuffer> {\n switch (this.format) {\n case 'AsyncIterable': {\n const blob = await this.toBlobAsync();\n return await blob.arrayBuffer();\n }\n\n default:\n throw new TypeError(`Asynchronous conversion from ${this.format} to ArrayBuffer is not supported.`);\n }\n }\n\n toBase32Z(): string {\n switch (this.format) {\n\n case 'Uint8Array': {\n return base32z.baseEncode(this.data);\n }\n\n default:\n throw new TypeError(`Conversion from ${this.format} to Base64Z is not supported.`);\n }\n }\n\n toBase58Btc(): string {\n switch (this.format) {\n\n case 'ArrayBuffer': {\n const u8a = new Uint8Array(this.data);\n return base58btc.baseEncode(u8a);\n }\n\n case 'Multibase': {\n return this.data.substring(1);\n }\n\n case 'Uint8Array': {\n return base58btc.baseEncode(this.data);\n }\n\n default:\n throw new TypeError(`Conversion from ${this.format} to Base58Btc is not supported.`);\n }\n }\n\n toBase64Url(): string {\n switch (this.format) {\n\n case 'ArrayBuffer': {\n const u8a = new Uint8Array(this.data);\n return base64url.baseEncode(u8a);\n }\n\n case 'BufferSource': {\n const u8a = this.toUint8Array();\n return base64url.baseEncode(u8a);\n }\n\n case 'Object': {\n const string = JSON.stringify(this.data);\n const u8a = textEncoder.encode(string);\n return base64url.baseEncode(u8a);\n }\n\n case 'String': {\n const u8a = textEncoder.encode(this.data);\n return base64url.baseEncode(u8a);\n }\n\n case 'Uint8Array': {\n return base64url.baseEncode(this.data);\n }\n\n default:\n throw new TypeError(`Conversion from ${this.format} to Base64Url is not supported.`);\n }\n }\n\n async toBlobAsync(): Promise<Blob> {\n switch (this.format) {\n case 'AsyncIterable': {\n // Initialize an array to hold the chunks from the AsyncIterable.\n const chunks = [];\n\n // Asynchronously iterate over each chunk in the AsyncIterable.\n for await (const chunk of (this.data as AsyncIterable<any>)) {\n // Append each chunk to the chunks array. These chunks can be of any type, typically binary data or text.\n chunks.push(chunk);\n }\n\n // Create a new Blob from the aggregated chunks.\n // The Blob constructor combines these chunks into a single Blob object.\n const blob = new Blob(chunks);\n\n return blob;\n }\n\n default:\n throw new TypeError(`Asynchronous conversion from ${this.format} to Blob is not supported.`);\n }\n }\n\n toHex(): string {\n // pre-calculating Hex values improves runtime by 6-10x.\n const hexes = Array.from({ length: 256 }, (v, i) => i.toString(16).padStart(2, '0'));\n\n switch (this.format) {\n\n case 'ArrayBuffer': {\n const u8a = this.toUint8Array();\n return Convert.uint8Array(u8a).toHex();\n }\n\n case 'Base64Url': {\n const u8a = this.toUint8Array();\n return Convert.uint8Array(u8a).toHex();\n }\n\n case 'Uint8Array': {\n let hex = '';\n for (let i = 0; i < this.data.length; i++) {\n hex += hexes[this.data[i]];\n }\n return hex;\n }\n\n default:\n throw new TypeError(`Conversion from ${this.format} to Hex is not supported.`);\n }\n }\n\n toMultibase(): Multibase<any> {\n switch (this.format) {\n case 'Base58Btc': {\n return `z${this.data}`;\n }\n\n default:\n throw new TypeError(`Conversion from ${this.format} to Multibase is not supported.`);\n }\n }\n\n toObject(): object {\n switch (this.format) {\n\n case 'Base64Url': {\n const u8a = base64url.baseDecode(this.data);\n const text = textDecoder.decode(u8a);\n return JSON.parse(text);\n }\n\n case 'String': {\n return JSON.parse(this.data);\n }\n\n case 'Uint8Array': {\n const text = textDecoder.decode(this.data);\n return JSON.parse(text);\n }\n\n default:\n throw new TypeError(`Conversion from ${this.format} to Object is not supported.`);\n }\n }\n\n async toObjectAsync(): Promise<any> {\n switch (this.format) {\n case 'AsyncIterable': {\n // Convert the AsyncIterable to a String.\n const text = await this.toStringAsync();\n\n // Parse the string as JSON. This step assumes that the string represents a valid JSON structure.\n // JSON.parse() will convert the string into a corresponding JavaScript object.\n const json = JSON.parse(text);\n\n // Return the parsed JavaScript object. The type of this object will depend on the structure\n // of the JSON in the stream. It could be an object, array, string, number, etc.\n return json;\n }\n\n default:\n throw new TypeError(`Asynchronous conversion from ${this.format} to Object is not supported.`);\n }\n }\n\n toString(): string {\n switch (this.format) {\n\n case 'ArrayBuffer': {\n return textDecoder.decode(this.data);\n }\n\n case 'Base64Url': {\n const u8a = base64url.baseDecode(this.data);\n return textDecoder.decode(u8a);\n }\n\n case 'Object': {\n return JSON.stringify(this.data);\n }\n\n case 'Uint8Array': {\n return textDecoder.decode(this.data);\n }\n\n default:\n throw new TypeError(`Conversion from ${this.format} to String is not supported.`);\n }\n }\n\n async toStringAsync(): Promise<string> {\n switch (this.format) {\n case 'AsyncIterable': {\n // Initialize an empty string to accumulate the decoded text.\n let str = '';\n\n // Iterate over the chunks from the AsyncIterable.\n for await (const chunk of (this.data as AsyncIterable<any>)) {\n // If the chunk is already a string, concatenate it directly.\n if (typeof chunk === 'string')\n {str += chunk;}\n else\n // If the chunk is a Uint8Array or similar, use the decoder to convert it to a string.\n // The `stream: true` option lets the decoder handle multi-byte characters spanning\n // multiple chunks.\n {str += textDecoder.decode(chunk, { stream: true });}\n }\n\n // Finalize the decoding process to handle any remaining bytes and signal the end of the stream.\n // The `stream: false` option flushes the decoder's internal state.\n str += textDecoder.decode(undefined, { stream: false });\n\n // Return the accumulated string.\n return str;\n }\n\n default:\n throw new TypeError(`Asynchronous conversion from ${this.format} to String is not supported.`);\n }\n }\n\n toUint8Array(): Uint8Array {\n switch (this.format) {\n\n case 'ArrayBuffer': {\n // \u00C7reate Uint8Array as a view on the ArrayBuffer.\n // Note: The Uint8Array shares the same memory as the ArrayBuffer, so this operation is very efficient.\n return new Uint8Array(this.data);\n }\n\n case 'Base32Z': {\n return base32z.baseDecode(this.data);\n }\n\n case 'Base58Btc': {\n return base58btc.baseDecode(this.data);\n }\n\n case 'Base64Url': {\n return base64url.baseDecode(this.data);\n }\n\n case 'BufferSource': {\n const dataType = universalTypeOf(this.data);\n if (dataType === 'Uint8Array') {\n // Data is already a Uint8Array. No conversion is necessary.\n // Note: Uint8Array is a type of BufferSource.\n return this.data;\n } else if (dataType === 'ArrayBuffer') {\n // Data is an ArrayBuffer, create Uint8Array as a view on the ArrayBuffer.\n // Note: The Uint8Array shares the same memory as the ArrayBuffer, so this operation is very efficient.\n return new Uint8Array(this.data);\n } else if (ArrayBuffer.isView(this.data)) {\n // Data is a DataView or a different TypedArray (e.g., Uint16Array).\n return new Uint8Array(this.data.buffer, this.data.byteOffset, this.data.byteLength);\n } else {\n throw new TypeError(`${this.format} value is not of type: ArrayBuffer, DataView, or TypedArray.`);\n }\n }\n\n case 'Hex': {\n const u8a = new Uint8Array(this.data.length / 2);\n for (let i = 0; i < this.data.length; i += 2) {\n const byteValue = parseInt(this.data.substring(i, i + 2), 16);\n if (isNaN(byteValue)) {\n throw new TypeError('Input is not a valid hexadecimal string.');\n }\n u8a[i / 2] = byteValue;\n }\n return u8a;\n }\n\n case 'Object': {\n const string = JSON.stringify(this.data);\n return textEncoder.encode(string);\n }\n\n case 'String': {\n return textEncoder.encode(this.data);\n }\n\n default:\n throw new TypeError(`Conversion from ${this.format} to Uint8Array is not supported.`);\n }\n }\n\n async toUint8ArrayAsync(): Promise<Uint8Array> {\n switch (this.format) {\n case 'AsyncIterable': {\n const arrayBuffer = await this.toArrayBufferAsync();\n return new Uint8Array(arrayBuffer);\n }\n\n default:\n throw new TypeError(`Asynchronous conversion from ${this.format} to Uint8Array is not supported.`);\n }\n }\n}", "/**\n * Web5 logger level.\n */\nexport enum Web5LogLevel {\n Debug = 'debug',\n Silent = 'silent',\n}\n\n/**\n * Web5 logger interface.\n */\nexport interface Web5LoggerInterface {\n\n /**\n * Sets the log verbose level.\n */\n setLogLevel(logLevel: Web5LogLevel): void;\n\n /**\n * Same as `info()`.\n * Logs an informational message.\n */\n log (message: string): void;\n\n /**\n * Logs an informational message.\n */\n info(message: string): void;\n\n /**\n * Logs an error message.\n */\n error(message: string): void;\n}\n\n/**\n * A Web5 logger implementation.\n */\nclass Web5Logger implements Web5LoggerInterface {\n private logLevel: Web5LogLevel = Web5LogLevel.Silent; // Default to silent/no-op log level\n\n setLogLevel(logLevel: Web5LogLevel): void {\n this.logLevel = logLevel;\n }\n\n public log(message: string): void {\n this.info(message);\n }\n\n public info(message: string): void {\n if (this.logLevel === Web5LogLevel.Silent) { return; }\n\n console.info(message);\n }\n\n public error(message: string): void {\n if (this.logLevel === Web5LogLevel.Silent) { return; }\n\n console.error(message);\n }\n}\n\n// Export a singleton logger instance\nexport const logger = new Web5Logger();\n\n// Attach logger to the global window object in browser environment for easy access to the logger instance.\n// e.g. can call `web5logger.setLogLevel('debug');` directly in browser console.\ndeclare global {\n interface Window { web5logger?: Web5Logger }\n}\n\nif (typeof window !== 'undefined') {\n window.web5logger = logger;\n}", "import { varint } from 'multiformats';\n\nexport type MulticodecCode = number;\n\nexport type MulticodecDefinition<MulticodecCode> = {\n code: MulticodecCode;\n // codeBytes: Uint8Array;\n name: string;\n};\n\n/**\n * The `Multicodec` class provides an interface to prepend binary data\n * with a prefix that identifies the data that follows.\n * https://github.com/multiformats/multicodec/blob/master/table.csv\n *\n * Multicodec is a self-describing multiformat, it wraps other formats with\n * a tiny bit of self-description. A multicodec identifier is a\n * varint (variable integer) that indicates the format of the data.\n *\n * The canonical table of multicodecs can be access at the following URL:\n * https://github.com/multiformats/multicodec/blob/master/table.csv\n *\n * Example usage:\n *\n * ```ts\n * Multicodec.registerCodec({ code: 0xed, name: 'ed25519-pub' });\n * const prefixedData = Multicodec.addPrefix({ code: 0xed, data: new Uint8Array(32) });\n * ```\n */\nexport class Multicodec {\n /**\n * A static field containing a map of codec codes to their corresponding names.\n */\n static codeToName = new Map<MulticodecCode, string>();\n\n /**\n * A static field containing a map of codec names to their corresponding codes.\n */\n static nameToCode = new Map<string, MulticodecCode>();\n\n /**\n * Adds a multicodec prefix to input data.\n *\n * @param options - The options for adding a prefix.\n * @param options.code - The codec code. Either the code or name must be provided.\n * @param options.name - The codec name. Either the code or name must be provided.\n * @param options.data - The data to be prefixed.\n * @returns The data with the added prefix as a Uint8Array.\n */\n public static addPrefix(options: {\n code?: MulticodecCode,\n data: Uint8Array,\n name?: string,\n }): Uint8Array {\n let { code, data, name } = options;\n\n if (!(name ? !code : code)) {\n throw new Error(`Either 'name' or 'code' must be defined, but not both.`);\n }\n\n // If code was given, confirm it exists, or lookup code by name.\n code = Multicodec.codeToName.has(code!) ? code : Multicodec.nameToCode.get(name!);\n\n // Throw error if a registered Codec wasn't found.\n if (code === undefined) {\n throw new Error(`Unsupported multicodec: ${options.name ?? options.code}`);\n }\n\n // Create a new array to store the prefix and input data.\n const prefixLength = varint.encodingLength(code);\n const dataWithPrefix = new Uint8Array(prefixLength + data.byteLength);\n dataWithPrefix.set(data, prefixLength);\n\n // Prepend the prefix.\n varint.encodeTo(code, dataWithPrefix);\n\n return dataWithPrefix;\n }\n\n /**\n * Get the Multicodec code from given prefixed data.\n *\n * @param options - The options for getting the codec code.\n * @param options.prefixedData - The data to extract the codec code from.\n * @returns - The Multicodec code as a number.\n */\n public static getCodeFromData(options: {\n prefixedData: Uint8Array\n }): MulticodecCode {\n const { prefixedData } = options;\n const [code, _] = varint.decode(prefixedData);\n\n return code;\n }\n\n /**\n * Get the Multicodec code from given Multicodec name.\n *\n * @param options - The options for getting the codec code.\n * @param options.name - The name to lookup.\n * @returns - The Multicodec code as a number.\n */\n public static getCodeFromName(options: {\n name: string\n }): MulticodecCode {\n const { name } = options;\n\n // Throw error if a registered Codec wasn't found.\n const code = Multicodec.nameToCode.get(name);\n if (code === undefined) {\n throw new Error(`Unsupported multicodec: ${name}`);\n }\n\n return code;\n }\n\n /**\n * Get the Multicodec name from given Multicodec code.\n *\n * @param options - The options for getting the codec name.\n * @param options.name - The code to lookup.\n * @returns - The Multicodec name as a string.\n */\n public static getNameFromCode(options: {\n code: MulticodecCode\n }): string {\n const { code } = options;\n\n // Throw error if a registered Codec wasn't found.\n const name = Multicodec.codeToName.get(code);\n if (name === undefined) {\n throw new Error(`Unsupported multicodec: ${code}`);\n }\n\n return name;\n }\n\n /**\n * Registers a new codec in the Multicodec class.\n *\n * @param codec - The codec to be registered.\n */\n public static registerCodec(codec: MulticodecDefinition<MulticodecCode>): void {\n Multicodec.codeToName.set(codec.code, codec.name);\n Multicodec.nameToCode.set(codec.name, codec.code);\n }\n\n /**\n * Returns the data with the Multicodec prefix removed.\n *\n * @param refixedData - The data to extract the codec code from.\n * @returns {Uint8Array}\n */\n public static removePrefix(options: {\n prefixedData: Uint8Array\n }): { code: MulticodecCode, name: string, data: Uint8Array } {\n const { prefixedData } = options;\n const [code, codeByteLength] = varint.decode(prefixedData);\n\n // Throw error if a registered Codec wasn't found.\n const name = Multicodec.codeToName.get(code);\n if (name === undefined) {\n throw new Error(`Unsupported multicodec: ${code}`);\n }\n\n return { code, data: prefixedData.slice(codeByteLength), name };\n }\n}\n\n// Pre-defined registered codecs:\nMulticodec.registerCodec({ code: 0xed, name: 'ed25519-pub' });\nMulticodec.registerCodec({ code: 0x1300, name: 'ed25519-priv' });\nMulticodec.registerCodec({ code: 0xec, name: 'x25519-pub' });\nMulticodec.registerCodec({ code: 0x1302, name: 'x25519-priv' });\nMulticodec.registerCodec({ code: 0xe7, name: 'secp256k1-pub' });\nMulticodec.registerCodec({ code: 0x1301, name: 'secp256k1-priv' });", "/**\n * @packageDocumentation\n *\n * This library defines common interfaces and low level building blocks for various interrelated multiformat technologies (multicodec, multihash, multibase, and CID). They can be used to implement custom base encoders / decoders / codecs, codec encoders /decoders and multihash hashers that comply to the interface that layers above assume.\n *\n * This library provides implementations for most basics and many others can be found in linked repositories.\n *\n * ```TypeScript\n * import { CID } from 'multiformats/cid'\n * import * as json from 'multiformats/codecs/json'\n * import { sha256 } from 'multiformats/hashes/sha2'\n *\n * const bytes = json.encode({ hello: 'world' })\n *\n * const hash = await sha256.digest(bytes)\n * const cid = CID.create(1, json.code, hash)\n * //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)\n * ```\n *\n * ## Creating Blocks\n *\n * ```TypeScript\n * import * as Block from 'multiformats/block'\n * import * as codec from '@ipld/dag-cbor'\n * import { sha256 as hasher } from 'multiformats/hashes/sha2'\n *\n * const value = { hello: 'world' }\n *\n * // encode a block\n * let block = await Block.encode({ value, codec, hasher })\n *\n * block.value // { hello: 'world' }\n * block.bytes // Uint8Array\n * block.cid // CID() w/ sha2-256 hash address and dag-cbor codec\n *\n * // you can also decode blocks from their binary state\n * block = await Block.decode({ bytes: block.bytes, codec, hasher })\n *\n * // if you have the cid you can also verify the hash on decode\n * block = await Block.create({ bytes: block.bytes, cid: block.cid, codec, hasher })\n * ```\n *\n * ## Multibase Encoders / Decoders / Codecs\n *\n * CIDs can be serialized to string representation using multibase encoders that implement [`MultibaseEncoder`](https://github.com/multiformats/js-multiformats/blob/master/src/bases/interface.ts) interface. This library provides quite a few implementations that can be imported:\n *\n * ```TypeScript\n * import { base64 } from \"multiformats/bases/base64\"\n * cid.toString(base64.encoder)\n * //> 'mAYAEEiCTojlxqRTl6svwqNJRVM2jCcPBxy+7mRTUfGDzy2gViA'\n * ```\n *\n * Parsing CID string serialized CIDs requires multibase decoder that implements [`MultibaseDecoder`](https://github.com/multiformats/js-multiformats/blob/master/src/bases/interface.ts) interface. This library provides a decoder for every encoder it provides:\n *\n * ```TypeScript\n * CID.parse('mAYAEEiCTojlxqRTl6svwqNJRVM2jCcPBxy+7mRTUfGDzy2gViA', base64.decoder)\n * //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)\n * ```\n *\n * Dual of multibase encoder & decoder is defined as multibase codec and it exposes\n * them as `encoder` and `decoder` properties. For added convenience codecs also\n * implement `MultibaseEncoder` and `MultibaseDecoder` interfaces so they could be\n * used as either or both:\n *\n * ```TypeScript\n * cid.toString(base64)\n * CID.parse(cid.toString(base64), base64)\n * ```\n *\n * **Note:** CID implementation comes bundled with `base32` and `base58btc`\n * multibase codecs so that CIDs can be base serialized to (version specific)\n * default base encoding and parsed without having to supply base encoders/decoders:\n *\n * ```TypeScript\n * const v1 = CID.parse('bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea')\n * v1.toString()\n * //> 'bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea'\n *\n * const v0 = CID.parse('QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n')\n * v0.toString()\n * //> 'QmdfTbBqBPQ7VNxZEYEj14VmRuZBkqFbiwReogJgS1zR1n'\n * v0.toV1().toString()\n * //> 'bafybeihdwdcefgh4dqkjv67uzcmw7ojee6xedzdetojuzjevtenxquvyku'\n * ```\n *\n * ## Multicodec Encoders / Decoders / Codecs\n *\n * This library defines [`BlockEncoder`, `BlockDecoder` and `BlockCodec` interfaces](https://github.com/multiformats/js-multiformats/blob/master/src/codecs/interface.ts).\n * Codec implementations should conform to the `BlockCodec` interface which implements both `BlockEncoder` and `BlockDecoder`.\n * Here is an example implementation of JSON `BlockCodec`.\n *\n * ```TypeScript\n * export const { name, code, encode, decode } = {\n * name: 'json',\n * code: 0x0200,\n * encode: json => new TextEncoder().encode(JSON.stringify(json)),\n * decode: bytes => JSON.parse(new TextDecoder().decode(bytes))\n * }\n * ```\n *\n * ## Multihash Hashers\n *\n * This library defines [`MultihashHasher` and `MultihashDigest` interfaces](https://github.com/multiformats/js-multiformats/blob/master/src/hashes/interface.ts) and convinient function for implementing them:\n *\n * ```TypeScript\n * import * as hasher from 'multiformats/hashes/hasher'\n *\n * const sha256 = hasher.from({\n * // As per multiformats table\n * // https://github.com/multiformats/multicodec/blob/master/table.csv#L9\n * name: 'sha2-256',\n * code: 0x12,\n *\n * encode: (input) => new Uint8Array(crypto.createHash('sha256').update(input).digest())\n * })\n *\n * const hash = await sha256.digest(json.encode({ hello: 'world' }))\n * CID.create(1, json.code, hash)\n *\n * //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)\n * ```\n *\n * ## Traversal\n *\n * This library contains higher-order functions for traversing graphs of data easily.\n *\n * `walk()` walks through the links in each block of a DAG calling a user-supplied loader function for each one, in depth-first order with no duplicate block visits. The loader should return a `Block` object and can be used to inspect and collect block ordering for a full DAG walk. The loader should `throw` on error, and return `null` if a block should be skipped by `walk()`.\n *\n * ```TypeScript\n * import { walk } from 'multiformats/traversal'\n * import * as Block from 'multiformats/block'\n * import * as codec from 'multiformats/codecs/json'\n * import { sha256 as hasher } from 'multiformats/hashes/sha2'\n *\n * // build a DAG (a single block for this simple example)\n * const value = { hello: 'world' }\n * const block = await Block.encode({ value, codec, hasher })\n * const { cid } = block\n * console.log(cid)\n * //> CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)\n *\n * // create a loader function that also collects CIDs of blocks in\n * // their traversal order\n * const load = (cid, blocks) => async (cid) => {\n * // fetch a block using its cid\n * // e.g.: const block = await fetchBlockByCID(cid)\n * blocks.push(cid)\n * return block\n * }\n *\n * // collect blocks in this DAG starting from the root `cid`\n * const blocks = []\n * await walk({ cid, load: load(cid, blocks) })\n *\n * console.log(blocks)\n * //> [CID(bagaaierasords4njcts6vs7qvdjfcvgnume4hqohf65zsfguprqphs3icwea)]\n * ```\n *\n * ## Legacy interface\n *\n * [`blockcodec-to-ipld-format`](https://github.com/ipld/js-blockcodec-to-ipld-format) converts a multiformats [`BlockCodec`](https://github.com/multiformats/js-multiformats/blob/master/src/codecs/interface.ts#L21) into an\n * [`interface-ipld-format`](https://github.com/ipld/interface-ipld-format) for use with the [`ipld`](https://github.com/ipld/ipld) package. This can help bridge IPLD codecs implemented using the structure and interfaces defined here to existing code that assumes, or requires `interface-ipld-format`. This bridge also includes the relevant TypeScript definitions.\n *\n * ## Implementations\n *\n * By default, no base encodings (other than base32 & base58btc), hash functions,\n * or codec implementations are exposed by `multiformats`, you need to\n * import the ones you need yourself.\n *\n * ### Multibase codecs\n *\n * | bases | import | repo |\n * | ------------------------------------------------------------- | --------------------------- | ------------------------------------------------------------------------------------------------- |\n * | `base16` | `multiformats/bases/base16` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |\n * | `base32`, `base32pad`, `base32hex`, `base32hexpad`, `base32z` | `multiformats/bases/base32` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |\n * | `base64`, `base64pad`, `base64url`, `base64urlpad` | `multiformats/bases/base64` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |\n * | `base58btc`, `base58flick4` | `multiformats/bases/base58` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) |\n *\n * Other (less useful) bases implemented in [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/bases) include: `base2`, `base8`, `base10`, `base36` and `base256emoji`.\n *\n * ### Multihash hashers\n *\n * | hashes | import | repo |\n * | ------------------------------------------------------------------------------------------------------------------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------ |\n * | `sha2-256`, `sha2-512` | `multiformats/hashes/sha2` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/hashes) |\n * | `sha3-224`, `sha3-256`, `sha3-384`,`sha3-512`, `shake-128`, `shake-256`, `keccak-224`, `keccak-256`, `keccak-384`, `keccak-512` | `@multiformats/sha3` | [multiformats/js-sha3](https://github.com/multiformats/js-sha3) |\n * | `identity` | `multiformats/hashes/identity` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/hashes/identity.js) |\n * | `murmur3-128`, `murmur3-32` | `@multiformats/murmur3` | [multiformats/js-murmur3](https://github.com/multiformats/js-murmur3) |\n * | `blake2b-*`, `blake2s-*` | `@multiformats/blake2` | [multiformats/js-blake2](https://github.com/multiformats/js-blake2) |\n *\n * ### IPLD codecs (multicodec)\n *\n * | codec | import | repo |\n * | ---------- | -------------------------- | ------------------------------------------------------------------------------------------------------ |\n * | `raw` | `multiformats/codecs/raw` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/codecs) |\n * | `json` | `multiformats/codecs/json` | [multiformats/js-multiformats](https://github.com/multiformats/js-multiformats/tree/master/src/codecs) |\n * | `dag-cbor` | `@ipld/dag-cbor` | [ipld/js-dag-cbor](https://github.com/ipld/js-dag-cbor) |\n * | `dag-json` | `@ipld/dag-json` | [ipld/js-dag-json](https://github.com/ipld/js-dag-json) |\n * | `dag-pb` | `@ipld/dag-pb` | [ipld/js-dag-pb](https://github.com/ipld/js-dag-pb) |\n * | `dag-jose` | `dag-jose` | [ceramicnetwork/js-dag-jose](https://github.com/ceramicnetwork/js-dag-jose) |\n */\n\nimport * as bytes from './bytes.js'\nimport { CID } from './cid.js'\nimport * as digest from './hashes/digest.js'\nimport * as hasher from './hashes/hasher.js'\nimport * as varint from './varint.js'\n\n// This way TS will also expose all the types from module\nexport * from './interface.js'\n\nexport { CID, hasher, digest, varint, bytes }\n", "import { base32 } from './bases/base32.js'\nimport { base58btc } from './bases/base58.js'\nimport { coerce } from './bytes.js'\nimport * as Digest from './hashes/digest.js'\nimport * as varint from './varint.js'\nimport type * as API from './link/interface.js'\n\n// This way TS will also expose all the types from module\nexport * from './link/interface.js'\n\nexport function format <T extends API.Link<unknown, number, number, API.Version>, Prefix extends string> (link: T, base?: API.MultibaseEncoder<Prefix>): API.ToString<T, Prefix> {\n const { bytes, version } = link\n switch (version) {\n case 0:\n return toStringV0(\n bytes,\n baseCache(link),\n base as API.MultibaseEncoder<'z'> ?? base58btc.encoder\n )\n default:\n return toStringV1(\n bytes,\n baseCache(link),\n (base ?? base32.encoder) as API.MultibaseEncoder<Prefix>\n )\n }\n}\n\nexport function toJSON <Link extends API.UnknownLink> (link: Link): API.LinkJSON<Link> {\n return {\n '/': format(link)\n }\n}\n\nexport function fromJSON <Link extends API.UnknownLink> (json: API.LinkJSON<Link>): CID<unknown, number, number, API.Version> {\n return CID.parse(json['/'])\n}\n\nconst cache = new WeakMap<API.UnknownLink, Map<string, string>>()\n\nfunction baseCache (cid: API.UnknownLink): Map<string, string> {\n const baseCache = cache.get(cid)\n if (baseCache == null) {\n const baseCache = new Map()\n cache.set(cid, baseCache)\n return baseCache\n }\n return baseCache\n}\n\nexport class CID<Data = unknown, Format extends number = number, Alg extends number = number, Version extends API.Version = API.Version> implements API.Link<Data, Format, Alg, Version> {\n readonly code: Format\n readonly version: Version\n readonly multihash: API.MultihashDigest<Alg>\n readonly bytes: Uint8Array\n readonly '/': Uint8Array\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param multihash - (Multi)hash of the of the content.\n */\n constructor (version: Version, code: Format, multihash: API.MultihashDigest<Alg>, bytes: Uint8Array) {\n this.code = code\n this.version = version\n this.multihash = multihash\n this.bytes = bytes\n\n // flag to serializers that this is a CID and\n // should be treated specially\n this['/'] = bytes\n }\n\n /**\n * Signalling `cid.asCID === cid` has been replaced with `cid['/'] === cid.bytes`\n * please either use `CID.asCID(cid)` or switch to new signalling mechanism\n *\n * @deprecated\n */\n get asCID (): this {\n return this\n }\n\n // ArrayBufferView\n get byteOffset (): number {\n return this.bytes.byteOffset\n }\n\n // ArrayBufferView\n get byteLength (): number {\n return this.bytes.byteLength\n }\n\n toV0 (): CID<Data, API.DAG_PB, API.SHA_256, 0> {\n switch (this.version) {\n case 0: {\n return this as CID<Data, API.DAG_PB, API.SHA_256, 0>\n }\n case 1: {\n const { code, multihash } = this\n\n if (code !== DAG_PB_CODE) {\n throw new Error('Cannot convert a non dag-pb CID to CIDv0')\n }\n\n // sha2-256\n if (multihash.code !== SHA_256_CODE) {\n throw new Error('Cannot convert non sha2-256 multihash CID to CIDv0')\n }\n\n return (\n CID.createV0(\n multihash as API.MultihashDigest<API.SHA_256>\n )\n )\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 0. This is a bug please report`\n )\n }\n }\n }\n\n toV1 (): CID<Data, Format, Alg, 1> {\n switch (this.version) {\n case 0: {\n const { code, digest } = this.multihash\n const multihash = Digest.create(code, digest)\n return (\n CID.createV1(this.code, multihash)\n )\n }\n case 1: {\n return this as CID<Data, Format, Alg, 1>\n }\n default: {\n throw Error(\n `Can not convert CID version ${this.version} to version 1. This is a bug please report`\n )\n }\n }\n }\n\n equals (other: unknown): other is CID<Data, Format, Alg, Version> {\n return CID.equals(this, other)\n }\n\n static equals <Data, Format extends number, Alg extends number, Version extends API.Version>(self: API.Link<Data, Format, Alg, Version>, other: unknown): other is CID {\n const unknown = other as { code?: unknown, version?: unknown, multihash?: unknown }\n return (\n unknown != null &&\n self.code === unknown.code &&\n self.version === unknown.version &&\n Digest.equals(self.multihash, unknown.multihash)\n )\n }\n\n toString (base?: API.MultibaseEncoder<string>): string {\n return format(this, base)\n }\n\n toJSON (): API.LinkJSON<this> {\n return { '/': format(this) }\n }\n\n link (): this {\n return this\n }\n\n readonly [Symbol.toStringTag] = 'CID';\n\n // Legacy\n\n [Symbol.for('nodejs.util.inspect.custom')] (): string {\n return `CID(${this.toString()})`\n }\n\n /**\n * Takes any input `value` and returns a `CID` instance if it was\n * a `CID` otherwise returns `null`. If `value` is instanceof `CID`\n * it will return value back. If `value` is not instance of this CID\n * class, but is compatible CID it will return new instance of this\n * `CID` class. Otherwise returns null.\n *\n * This allows two different incompatible versions of CID library to\n * co-exist and interop as long as binary interface is compatible.\n */\n static asCID <Data, Format extends number, Alg extends number, Version extends API.Version, U>(input: API.Link<Data, Format, Alg, Version> | U): CID<Data, Format, Alg, Version> | null {\n if (input == null) {\n return null\n }\n\n const value = input as any\n if (value instanceof CID) {\n // If value is instance of CID then we're all set.\n return value\n } else if ((value['/'] != null && value['/'] === value.bytes) || value.asCID === value) {\n // If value isn't instance of this CID class but `this.asCID === this` or\n // `value['/'] === value.bytes` is true it is CID instance coming from a\n // different implementation (diff version or duplicate). In that case we\n // rebase it to this `CID` implementation so caller is guaranteed to get\n // instance with expected API.\n const { version, code, multihash, bytes } = value\n return new CID(\n version,\n code,\n multihash as API.MultihashDigest<Alg>,\n bytes ?? encodeCID(version, code, multihash.bytes)\n )\n } else if (value[cidSymbol] === true) {\n // If value is a CID from older implementation that used to be tagged via\n // symbol we still rebase it to the this `CID` implementation by\n // delegating that to a constructor.\n const { version, multihash, code } = value\n const digest = Digest.decode(multihash) as API.MultihashDigest<Alg>\n return CID.create(version, code, digest)\n } else {\n // Otherwise value is not a CID (or an incompatible version of it) in\n // which case we return `null`.\n return null\n }\n }\n\n /**\n * @param version - Version of the CID\n * @param code - Code of the codec content is encoded in, see https://github.com/multiformats/multicodec/blob/master/table.csv\n * @param digest - (Multi)hash of the of the content.\n */\n static create <Data, Format extends number, Alg extends number, Version extends API.Version>(version: Version, code: Format, digest: API.MultihashDigest<Alg>): CID<Data, Format, Alg, Version> {\n if (typeof code !== 'number') {\n throw new Error('String codecs are no longer supported')\n }\n\n if (!(digest.bytes instanceof Uint8Array)) {\n throw new Error('Invalid digest')\n }\n\n switch (version) {\n case 0: {\n if (code !== DAG_PB_CODE) {\n throw new Error(\n `Version 0 CID must use dag-pb (code: ${DAG_PB_CODE}) block encoding`\n )\n } else {\n return new CID(version, code, digest, digest.bytes)\n }\n }\n case 1: {\n const bytes = encodeCID(version, code, digest.bytes)\n return new CID(version, code, digest, bytes)\n }\n default: {\n throw new Error('Invalid version')\n }\n }\n }\n\n /**\n * Simplified version of `create` for CIDv0.\n */\n static createV0 <T = unknown>(digest: API.MultihashDigest<typeof SHA_256_CODE>): CID<T, typeof DAG_PB_CODE, typeof SHA_256_CODE, 0> {\n return CID.create(0, DAG_PB_CODE, digest)\n }\n\n /**\n * Simplified version of `create` for CIDv1.\n *\n * @param code - Content encoding format code.\n * @param digest - Multihash of the content.\n */\n static createV1 <Data, Code extends number, Alg extends number>(code: Code, digest: API.MultihashDigest<Alg>): CID<Data, Code, Alg, 1> {\n return CID.create(1, code, digest)\n }\n\n /**\n * Decoded a CID from its binary representation. The byte array must contain\n * only the CID with no additional bytes.\n *\n * An error will be thrown if the bytes provided do not contain a valid\n * binary representation of a CID.\n */\n static decode <Data, Code extends number, Alg extends number, Version extends API.Version>(bytes: API.ByteView<API.Link<Data, Code, Alg, Version>>): CID<Data, Code, Alg, Version> {\n const [cid, remainder] = CID.decodeFirst(bytes)\n if (remainder.length !== 0) {\n throw new Error('Incorrect length')\n }\n return cid\n }\n\n /**\n * Decoded a CID from its binary representation at the beginning of a byte\n * array.\n *\n * Returns an array with the first element containing the CID and the second\n * element containing the remainder of the original byte array. The remainder\n * will be a zero-length byte array if the provided bytes only contained a\n * binary CID representation.\n */\n static decodeFirst <T, C extends number, A extends number, V extends API.Version>(bytes: API.ByteView<API.Link<T, C, A, V>>): [CID<T, C, A, V>, Uint8Array] {\n const specs = CID.inspectBytes(bytes)\n const prefixSize = specs.size - specs.multihashSize\n const multihashBytes = coerce(\n bytes.subarray(prefixSize, prefixSize + specs.multihashSize)\n )\n if (multihashBytes.byteLength !== specs.multihashSize) {\n throw new Error('Incorrect length')\n }\n const digestBytes = multihashBytes.subarray(\n specs.multihashSize - specs.digestSize\n )\n const digest = new Digest.Digest(\n specs.multihashCode,\n specs.digestSize,\n digestBytes,\n multihashBytes\n )\n const cid =\n specs.version === 0\n ? CID.createV0(digest as API.MultihashDigest<API.SHA_256>)\n : CID.createV1(specs.codec, digest)\n return [cid as CID<T, C, A, V>, bytes.subarray(specs.size)]\n }\n\n /**\n * Inspect the initial bytes of a CID to determine its properties.\n *\n * Involves decoding up to 4 varints. Typically this will require only 4 to 6\n * bytes but for larger multicodec code values and larger multihash digest\n * lengths these varints can be quite large. It is recommended that at least\n * 10 bytes be made available in the `initialBytes` argument for a complete\n * inspection.\n */\n static inspectBytes <T, C extends number, A extends number, V extends API.Version>(initialBytes: API.ByteView<API.Link<T, C, A, V>>): { version: V, codec: C, multihashCode: A, digestSize: number, multihashSize: number, size: number } {\n let offset = 0\n const next = (): number => {\n const [i, length] = varint.decode(initialBytes.subarray(offset))\n offset += length\n return i\n }\n\n let version = next() as V\n let codec = DAG_PB_CODE as C\n if (version as number === 18) {\n // CIDv0\n version = 0 as V\n offset = 0\n } else {\n codec = next() as C\n }\n\n if (version !== 0 && version !== 1) {\n throw new RangeError(`Invalid CID version ${version}`)\n }\n\n const prefixSize = offset\n const multihashCode = next() as A // multihash code\n const digestSize = next() // multihash length\n const size = offset + digestSize\n const multihashSize = size - prefixSize\n\n return { version, codec, multihashCode, digestSize, multihashSize, size }\n }\n\n /**\n * Takes cid in a string representation and creates an instance. If `base`\n * decoder is not provided will use a default from the configuration. It will\n * throw an error if encoding of the CID is not compatible with supplied (or\n * a default decoder).\n */\n static parse <Prefix extends string, Data, Code extends number, Alg extends number, Version extends API.Version>(source: API.ToString<API.Link<Data, Code, Alg, Version>, Prefix>, base?: API.MultibaseDecoder<Prefix>): CID<Data, Code, Alg, Version> {\n const [prefix, bytes] = parseCIDtoBytes(source, base)\n\n const cid = CID.decode(bytes)\n\n if (cid.version === 0 && source[0] !== 'Q') {\n throw Error('Version 0 CID string must not include multibase prefix')\n }\n\n // Cache string representation to avoid computing it on `this.toString()`\n baseCache(cid).set(prefix, source)\n\n return cid\n }\n}\n\nfunction parseCIDtoBytes <Prefix extends string, Data, Code extends number, Alg extends number, Version extends API.Version> (source: API.ToString<API.Link<Data, Code, Alg, Version>, Prefix>, base?: API.MultibaseDecoder<Prefix>): [Prefix, API.ByteView<API.Link<Data, Code, Alg, Version>>] {\n switch (source[0]) {\n // CIDv0 is parsed differently\n case 'Q': {\n const decoder = base ?? base58btc\n return [\n base58btc.prefix as Prefix,\n decoder.decode(`${base58btc.prefix}${source}`)\n ]\n }\n case base58btc.prefix: {\n const decoder = base ?? base58btc\n return [base58btc.prefix as Prefix, decoder.decode(source)]\n }\n case base32.prefix: {\n const decoder = base ?? base32\n return [base32.prefix as Prefix, decoder.decode(source)]\n }\n default: {\n if (base == null) {\n throw Error(\n 'To parse non base32 or base58btc encoded CID multibase decoder must be provided'\n )\n }\n return [source[0] as Prefix, base.decode(source)]\n }\n }\n}\n\nfunction toStringV0 (bytes: Uint8Array, cache: Map<string, string>, base: API.MultibaseEncoder<'z'>): string {\n const { prefix } = base\n if (prefix !== base58btc.prefix) {\n throw Error(`Cannot string encode V0 in ${base.name} encoding`)\n }\n\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes).slice(1)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nfunction toStringV1 <Prefix extends string> (bytes: Uint8Array, cache: Map<string, string>, base: API.MultibaseEncoder<Prefix>): string {\n const { prefix } = base\n const cid = cache.get(prefix)\n if (cid == null) {\n const cid = base.encode(bytes)\n cache.set(prefix, cid)\n return cid\n } else {\n return cid\n }\n}\n\nconst DAG_PB_CODE = 0x70\nconst SHA_256_CODE = 0x12\n\nfunction encodeCID (version: API.Version, code: number, multihash: Uint8Array): Uint8Array {\n const codeOffset = varint.encodingLength(version)\n const hashOffset = codeOffset + varint.encodingLength(code)\n const bytes = new Uint8Array(hashOffset + multihash.byteLength)\n varint.encodeTo(version, bytes, 0)\n varint.encodeTo(code, bytes, codeOffset)\n bytes.set(multihash, hashOffset)\n return bytes\n}\n\nconst cidSymbol = Symbol.for('@ipld/js-cid/CID')\n", "import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\nimport type { MultihashDigest } from './interface.js'\n\n/**\n * Creates a multihash digest.\n */\nexport function create <Code extends number> (code: Code, digest: Uint8Array): Digest<Code, number> {\n const size = digest.byteLength\n const sizeOffset = varint.encodingLength(code)\n const digestOffset = sizeOffset + varint.encodingLength(size)\n\n const bytes = new Uint8Array(digestOffset + size)\n varint.encodeTo(code, bytes, 0)\n varint.encodeTo(size, bytes, sizeOffset)\n bytes.set(digest, digestOffset)\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * Turns bytes representation of multihash digest into an instance.\n */\nexport function decode (multihash: Uint8Array): MultihashDigest {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\nexport function equals (a: MultihashDigest, b: unknown): b is MultihashDigest {\n if (a === b) {\n return true\n } else {\n const data = b as { code?: unknown, size?: unknown, bytes?: unknown }\n\n return (\n a.code === data.code &&\n a.size === data.size &&\n data.bytes instanceof Uint8Array &&\n equalBytes(a.bytes, data.bytes)\n )\n }\n}\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\nexport class Digest<Code extends number, Size extends number> implements MultihashDigest {\n readonly code: Code\n readonly size: Size\n readonly digest: Uint8Array\n readonly bytes: Uint8Array\n\n /**\n * Creates a multihash digest.\n */\n constructor (code: Code, size: Size, digest: Uint8Array, bytes: Uint8Array) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n", "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", "/* 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", "/* eslint-disable @typescript-eslint/no-unnecessary-type-constraint */\n/* eslint-disable no-use-before-define */\n\nimport type { MultibaseEncoder, MultibaseDecoder, Multibase } from '../bases/interface.js'\nimport type { Phantom, ByteView } from '../block/interface.js'\nimport type { MultihashDigest } from '../hashes/interface.js'\n\nexport type { MultihashDigest, MultibaseEncoder, MultibaseDecoder }\nexport type Version = 0 | 1\n\nexport type DAG_PB = 0x70\nexport type SHA_256 = 0x12\n\n/**\n * Represents an IPLD link to a specific data of type `T`.\n *\n * @template T - Logical type of the data being linked to.\n * @template C - multicodec code corresponding to a codec linked data is encoded with\n * @template A - multicodec code corresponding to the hashing algorithm of the CID\n * @template V - CID version\n */\nexport interface Link<\n Data extends unknown = unknown,\n Format extends number = number,\n Alg extends number = number,\n V extends Version = 1\n > extends Phantom<Data> {\n readonly version: V\n readonly code: Format\n readonly multihash: MultihashDigest<Alg>\n\n readonly byteOffset: number\n readonly byteLength: number\n readonly bytes: ByteView<Link<Data, Format, Alg, V>>\n\n equals(other: unknown): other is Link<Data, Format, Alg, Version>\n\n toString<Prefix extends string>(base?: MultibaseEncoder<Prefix>): ToString<Link<Data, Format, Alg, Version>, Prefix>\n link(): Link<Data, Format, Alg, V>\n\n toV1(): Link<Data, Format, Alg, 1>\n}\n\nexport interface LinkJSON<T extends UnknownLink = UnknownLink> {\n '/': ToString<T>\n}\n\nexport interface LegacyLink<T extends unknown = unknown> extends Link<T, DAG_PB, SHA_256, 0> {\n}\n\nexport type UnknownLink =\n | LegacyLink<unknown>\n | Link<unknown, number, number, Version>\n\nexport type ToString<T, Prefix extends string = string> = Multibase<Prefix> & Phantom<T>\n\nexport type { ByteView }\n", "import * as Digest from './digest.js'\nimport type { MultihashHasher } from './interface.js'\n\ntype Await<T> = Promise<T> | T\n\nexport function from <Name extends string, Code extends number> ({ name, code, encode }: { name: Name, code: Code, encode(input: Uint8Array): Await<Uint8Array> }): Hasher<Name, Code> {\n return new Hasher(name, code, encode)\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport class Hasher<Name extends string, Code extends number> implements MultihashHasher<Code> {\n readonly name: Name\n readonly code: Code\n readonly encode: (input: Uint8Array) => Await<Uint8Array>\n\n constructor (name: Name, code: Code, encode: (input: Uint8Array) => Await<Uint8Array>) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n digest (input: Uint8Array): Await<Digest.Digest<Code, number>> {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n", "export * from './bases/interface.js'\nexport * from './hashes/interface.js'\nexport * from './codecs/interface.js'\nexport * from './link/interface.js'\nexport * from './block/interface.js'\n", "// Base encoders / decoders just base encode / decode between binary and\n// textual representation. They are unaware of multibase.\n\n/**\n * Base encoder just encodes bytes into base encoded string.\n */\nexport interface BaseEncoder {\n /**\n * Base encodes to a **plain** (and not a multibase) string. Unlike\n * `encode` no multibase prefix is added.\n */\n baseEncode(bytes: Uint8Array): string\n}\n\n/**\n * Base decoder decodes encoded with matching base encoding into bytes.\n */\nexport interface BaseDecoder {\n /**\n * Decodes **plain** (and not a multibase) string. Unlike\n * decode\n */\n baseDecode(text: string): Uint8Array\n}\n\n/**\n * Base codec is just dual of encoder and decoder.\n */\nexport interface BaseCodec {\n encoder: BaseEncoder\n decoder: BaseDecoder\n}\n\n/**\n * Multibase represents base encoded strings with a prefix first character\n * describing it's encoding.\n */\nexport type Multibase<Prefix extends string> =\n | string\n | string & { [0]: Prefix }\n\n/**\n * Multibase encoder for the specific base encoding encodes bytes into\n * multibase of that encoding.\n */\nexport interface MultibaseEncoder<Prefix extends string> {\n /**\n * Name of the encoding.\n */\n name: string\n /**\n * Prefix character for that base encoding.\n */\n prefix: Prefix\n /**\n * Encodes binary data into **multibase** string (which will have a\n * prefix added).\n */\n encode(bytes: Uint8Array): Multibase<Prefix>\n}\n\n/**\n * Interface implemented by multibase decoder, that takes multibase strings\n * to bytes. It may support single encoding like base32 or multiple encodings\n * like base32, base58btc, base64. If passed multibase is incompatible it will\n * throw an exception.\n */\nexport interface MultibaseDecoder<Prefix extends string> {\n /**\n * Decodes **multibase** string (which must have a multibase prefix added).\n * If prefix does not match\n */\n decode(multibase: Multibase<Prefix>): Uint8Array\n}\n\n/**\n * Dual of multibase encoder and decoder.\n */\nexport interface MultibaseCodec<Prefix extends string> {\n name: string\n prefix: Prefix\n encoder: MultibaseEncoder<Prefix>\n decoder: MultibaseDecoder<Prefix>\n}\n\nexport interface UnibaseDecoder<Prefix extends string> extends MultibaseDecoder<Prefix> {\n // Reserve this property so it can be used to derive type.\n readonly decoders?: null\n\n readonly prefix: Prefix\n}\n\nexport interface CombobaseDecoder<Prefix extends string> extends MultibaseDecoder<Prefix> {\n readonly decoders: Record<Prefix, UnibaseDecoder<Prefix>>\n}\n", "// # Multihash\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n */\n// Note: In the current version there is no first class multihash\n// representation (plain Uint8Array is used instead) instead there seems to be\n// a bunch of places that parse it to extract (code, digest, size). By creating\n// this first class representation we avoid reparsing and things generally fit\n// really nicely.\nexport interface MultihashDigest<Code extends number = number> {\n /**\n * Code of the multihash\n */\n code: Code\n\n /**\n * Raw digest (without a hashing algorithm info)\n */\n digest: Uint8Array\n\n /**\n * byte length of the `this.digest`\n */\n size: number\n\n /**\n * Binary representation of this multihash digest.\n */\n bytes: Uint8Array\n}\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n */\nexport interface MultihashHasher<Code extends number = number> {\n /**\n * Takes binary `input` and returns it (multi) hash digest. Return value is\n * either promise of a digest or a digest. This way general use can `await`\n * while performance critical code may asses return value to decide whether\n * await is needed.\n */\n digest(input: Uint8Array): Promise<MultihashDigest<Code>> | MultihashDigest<Code>\n\n /**\n * Name of the multihash\n */\n name: string\n\n /**\n * Code of the multihash\n */\n code: Code\n}\n\n/**\n * Sync variant of `MultihashHasher` that refines return type of the `digest`\n * to `MultihashDigest`. It is subtype of `MultihashHasher` so implementations\n * of this interface can be passed anywhere `MultihashHasher` is expected,\n * allowing consumer to either `await` or check the return type to decide\n * whether to await or proceed with return value.\n *\n * `SyncMultihashHasher` is useful in certain APIs where async hashing would be\n * impractical e.g. implementation of Hash Array Mapped Trie (HAMT).\n */\nexport interface SyncMultihashHasher<Code extends number = number> extends MultihashHasher<Code> {\n digest(input: Uint8Array): MultihashDigest<Code>\n}\n", "export {};\n//# sourceMappingURL=interface.js.map", "export {};\n//# sourceMappingURL=interface.js.map", "/**\n * Checks whether the given object has any properties.\n */\nexport function isEmptyObject(obj: unknown): boolean {\n if (typeof obj !== 'object' || obj === null) {\n return false;\n }\n\n if (Object.getOwnPropertySymbols(obj).length > 0) {\n return false;\n }\n\n return Object.keys(obj).length === 0;\n}\n\n/**\n * Recursively removes all properties with an empty object or array as its value from the given object.\n */\nexport function removeEmptyObjects(obj: Record<string, unknown>): void {\n Object.keys(obj).forEach(key => {\n if (typeof(obj[key]) === 'object') {\n // recursive remove empty object or array properties in nested objects\n removeEmptyObjects(obj[key] as Record<string, unknown>);\n }\n\n if (isEmptyObject(obj[key])) {\n delete obj[key];\n }\n });\n}\n\n/**\n * Recursively removes all properties with `undefined` as its value from the given object.\n */\nexport function removeUndefinedProperties(obj: Record<string, unknown>): void {\n Object.keys(obj).forEach(key => {\n if (obj[key] === undefined) {\n delete obj[key];\n } else if (typeof(obj[key]) === 'object') {\n removeUndefinedProperties(obj[key] as Record<string, unknown>); // recursive remove `undefined` properties in nested objects\n }\n });\n}", "import type { AbstractLevel } from 'abstract-level';\n\nimport { Level } from 'level';\n\nimport type { KeyValueStore } from './types.js';\n\nexport class LevelStore<K = string, V = any> implements KeyValueStore<K, V> {\n private store: AbstractLevel<string | Buffer | Uint8Array, K, V>;\n\n constructor({ db, location = 'DATASTORE' }: {\n db?: AbstractLevel<string | Buffer | Uint8Array, K, V>;\n location?: string;\n } = {}) {\n this.store = db ?? new Level<K, V>(location);\n }\n\n async clear(): Promise<void> {\n await this.store.clear();\n }\n\n async close(): Promise<void> {\n await this.store.close();\n }\n\n async delete(key: K): Promise<void> {\n await this.store.del(key);\n }\n\n async get(key: K): Promise<V | undefined> {\n try {\n return await this.store.get(key);\n } catch (error: any) {\n // Don't throw when a key wasn't found.\n if (error.notFound) {return undefined;}\n throw error;\n }\n }\n\n async set(key: K, value: V): Promise<void> {\n await this.store.put(key, value);\n }\n}\n\n/**\n * The `MemoryStore` class is an implementation of\n * `KeyValueStore` that holds data in memory.\n *\n * It provides a basic key-value store that works synchronously and keeps all\n * data in memory. This can be used for testing, or for handling small amounts\n * of data with simple key-value semantics.\n *\n * Example usage:\n *\n * ```ts\n * const memoryStore = new MemoryStore<string, number>();\n * await memoryStore.set(\"key1\", 1);\n * const value = await memoryStore.get(\"key1\");\n * console.log(value); // 1\n * ```\n *\n * @public\n */\nexport class MemoryStore<K, V> implements KeyValueStore<K, V> {\n /**\n * A private field that contains the Map used as the key-value store.\n */\n private store: Map<K, V> = new Map();\n\n /**\n * Clears all entries in the key-value store.\n *\n * @returns A Promise that resolves when the operation is complete.\n */\n async clear(): Promise<void> {\n this.store.clear();\n }\n\n /**\n * This operation is no-op for `MemoryStore`\n * and will log a warning if called.\n */\n async close(): Promise<void> {\n /** no-op */\n }\n\n /**\n * Deletes an entry from the key-value store by its key.\n *\n * @param id - The key of the entry to delete.\n * @returns A Promise that resolves to a boolean indicating whether the entry was successfully deleted.\n */\n async delete(id: K): Promise<boolean> {\n return this.store.delete(id);\n }\n\n /**\n * Retrieves the value of an entry by its key.\n *\n * @param id - The key of the entry to retrieve.\n * @returns A Promise that resolves to the value of the entry, or `undefined` if the entry does not exist.\n */\n async get(id: K): Promise<V | undefined> {\n return this.store.get(id);\n }\n\n /**\n * Checks for the presence of an entry by key.\n *\n * @param id - The key to check for the existence of.\n * @returns A Promise that resolves to a boolean indicating whether an element with the specified key exists or not.\n */\n async has(id: K): Promise<boolean> {\n return this.store.has(id);\n }\n\n /**\n * Retrieves all values in the key-value store.\n *\n * @returns A Promise that resolves to an array of all values in the store.\n */\n async list(): Promise<V[]> {\n return Array.from(this.store.values());\n }\n\n /**\n * Sets the value of an entry in the key-value store.\n *\n * @param id - The key of the entry to set.\n * @param key - The new value for the entry.\n * @returns A Promise that resolves when the operation is complete.\n */\n async set(id: K, key: V): Promise<void> {\n this.store.set(id, key);\n }\n}", "/**\n * Base class for all cryptographic algorithm implementations.\n */\nexport abstract class CryptoAlgorithm {}", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// 100 lines of code in the file are duplicated from noble-hashes (utils).\n// This is OK: `abstract` directory does not use noble-hashes.\n// User may opt-in into using different hashing library. This way, noble-hashes\n// won't be included into their bundle.\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nexport type Hex = Uint8Array | string; // hex strings are accepted for simplicity\nexport type PrivKey = Hex | bigint; // bigints are accepted to ease learning curve\nexport type CHash = {\n (message: Uint8Array | string): Uint8Array;\n blockLen: number;\n outputLen: number;\n create(opts?: { dkLen?: number }): any; // For shake\n};\nexport type FHash = (message: Uint8Array | string) => Uint8Array;\n\nexport function isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n if (!isBytes(bytes)) throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\nexport function numberToHexUnpadded(num: number | bigint): string {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n}\n\nexport function hexToNumber(hex: string): bigint {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n // Big Endian\n return BigInt(hex === '' ? '0' : `0x${hex}`);\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 } as const;\nfunction asciiToBase16(char: number): number | undefined {\n if (char >= asciis._0 && char <= asciis._9) return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10);\n return;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n\n// BE: Big Endian, LE: Little Endian\nexport function bytesToNumberBE(bytes: Uint8Array): bigint {\n return hexToNumber(bytesToHex(bytes));\n}\nexport function bytesToNumberLE(bytes: Uint8Array): bigint {\n if (!isBytes(bytes)) throw new Error('Uint8Array expected');\n return hexToNumber(bytesToHex(Uint8Array.from(bytes).reverse()));\n}\n\nexport function numberToBytesBE(n: number | bigint, len: number): Uint8Array {\n return hexToBytes(n.toString(16).padStart(len * 2, '0'));\n}\nexport function numberToBytesLE(n: number | bigint, len: number): Uint8Array {\n return numberToBytesBE(n, len).reverse();\n}\n// Unpadded, rarely used\nexport function numberToVarBytesBE(n: number | bigint): Uint8Array {\n return hexToBytes(numberToHexUnpadded(n));\n}\n\n/**\n * Takes hex string or Uint8Array, converts to Uint8Array.\n * Validates output length.\n * Will throw error for other types.\n * @param title descriptive title for an error e.g. 'private key'\n * @param hex hex string or Uint8Array\n * @param expectedLength optional, will compare to result array's length\n * @returns\n */\nexport function ensureBytes(title: string, hex: Hex, expectedLength?: number): Uint8Array {\n let res: Uint8Array;\n if (typeof hex === 'string') {\n try {\n res = hexToBytes(hex);\n } catch (e) {\n throw new Error(`${title} must be valid hex string, got \"${hex}\". Cause: ${e}`);\n }\n } else if (isBytes(hex)) {\n // Uint8Array.from() instead of hash.slice() because node.js Buffer\n // is instance of Uint8Array, and its slice() creates **mutable** copy\n res = Uint8Array.from(hex);\n } else {\n throw new Error(`${title} must be hex string or Uint8Array`);\n }\n const len = res.length;\n if (typeof expectedLength === 'number' && len !== expectedLength)\n throw new Error(`${title} expected ${expectedLength} bytes, got ${len}`);\n return res;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n if (!isBytes(a)) throw new Error('Uint8Array expected');\n sum += a.length;\n }\n let res = new Uint8Array(sum);\n let pad = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n// Compares 2 u8a-s in kinda constant time\nexport function equalBytes(a: Uint8Array, b: Uint8Array) {\n if (a.length !== b.length) return false;\n let diff = 0;\n for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];\n return diff === 0;\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\n// Bit operations\n\n/**\n * Calculates amount of bits in a bigint.\n * Same as `n.toString(2).length`\n */\nexport function bitLen(n: bigint) {\n let len;\n for (len = 0; n > _0n; n >>= _1n, len += 1);\n return len;\n}\n\n/**\n * Gets single bit at position.\n * NOTE: first bit position is 0 (same as arrays)\n * Same as `!!+Array.from(n.toString(2)).reverse()[pos]`\n */\nexport function bitGet(n: bigint, pos: number) {\n return (n >> BigInt(pos)) & _1n;\n}\n\n/**\n * Sets single bit at position.\n */\nexport const bitSet = (n: bigint, pos: number, value: boolean) => {\n return n | ((value ? _1n : _0n) << BigInt(pos));\n};\n\n/**\n * Calculate mask for N bits. Not using ** operator with bigints because of old engines.\n * Same as BigInt(`0b${Array(i).fill('1').join('')}`)\n */\nexport const bitMask = (n: number) => (_2n << BigInt(n - 1)) - _1n;\n\n// DRBG\n\nconst u8n = (data?: any) => new Uint8Array(data); // creates Uint8Array\nconst u8fr = (arr: any) => Uint8Array.from(arr); // another shortcut\ntype Pred<T> = (v: Uint8Array) => T | undefined;\n/**\n * Minimal HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n * @returns function that will call DRBG until 2nd arg returns something meaningful\n * @example\n * const drbg = createHmacDRBG<Key>(32, 32, hmac);\n * drbg(seed, bytesToKey); // bytesToKey must return Key or undefined\n */\nexport function createHmacDrbg<T>(\n hashLen: number,\n qByteLen: number,\n hmacFn: (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array\n): (seed: Uint8Array, predicate: Pred<T>) => T {\n if (typeof hashLen !== 'number' || hashLen < 2) throw new Error('hashLen must be a number');\n if (typeof qByteLen !== 'number' || qByteLen < 2) throw new Error('qByteLen must be a number');\n if (typeof hmacFn !== 'function') throw new Error('hmacFn must be a function');\n // Step B, Step C: set hashLen to 8*ceil(hlen/8)\n let v = u8n(hashLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(hashLen); // Steps B and C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => {\n v.fill(1);\n k.fill(0);\n i = 0;\n };\n const h = (...b: Uint8Array[]) => hmacFn(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = (seed = u8n()) => {\n // HMAC-DRBG reseed() function. Steps D-G\n k = h(u8fr([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0) return;\n k = h(u8fr([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n // HMAC-DRBG generate() function\n if (i++ >= 1000) throw new Error('drbg: tried 1000 values');\n let len = 0;\n const out: Uint8Array[] = [];\n while (len < qByteLen) {\n v = h();\n const sl = v.slice();\n out.push(sl);\n len += v.length;\n }\n return concatBytes(...out);\n };\n const genUntil = (seed: Uint8Array, pred: Pred<T>): T => {\n reset();\n reseed(seed); // Steps D-G\n let res: T | undefined = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen()))) reseed();\n reset();\n return res;\n };\n return genUntil;\n}\n\n// Validating curves and fields\n\nconst validatorFns = {\n bigint: (val: any) => typeof val === 'bigint',\n function: (val: any) => typeof val === 'function',\n boolean: (val: any) => typeof val === 'boolean',\n string: (val: any) => typeof val === 'string',\n stringOrUint8Array: (val: any) => typeof val === 'string' || isBytes(val),\n isSafeInteger: (val: any) => Number.isSafeInteger(val),\n array: (val: any) => Array.isArray(val),\n field: (val: any, object: any) => (object as any).Fp.isValid(val),\n hash: (val: any) => typeof val === 'function' && Number.isSafeInteger(val.outputLen),\n} as const;\ntype Validator = keyof typeof validatorFns;\ntype ValMap<T extends Record<string, any>> = { [K in keyof T]?: Validator };\n// type Record<K extends string | number | symbol, T> = { [P in K]: T; }\n\nexport function validateObject<T extends Record<string, any>>(\n object: T,\n validators: ValMap<T>,\n optValidators: ValMap<T> = {}\n) {\n const checkField = (fieldName: keyof T, type: Validator, isOptional: boolean) => {\n const checkVal = validatorFns[type];\n if (typeof checkVal !== 'function')\n throw new Error(`Invalid validator \"${type}\", expected function`);\n\n const val = object[fieldName as keyof typeof object];\n if (isOptional && val === undefined) return;\n if (!checkVal(val, object)) {\n throw new Error(\n `Invalid param ${String(fieldName)}=${val} (${typeof val}), expected ${type}`\n );\n }\n };\n for (const [fieldName, type] of Object.entries(validators)) checkField(fieldName, type!, false);\n for (const [fieldName, type] of Object.entries(optValidators)) checkField(fieldName, type!, true);\n return object;\n}\n// validate type tests\n// const o: { a: number; b: number; c: number } = { a: 1, b: 5, c: 6 };\n// const z0 = validateObject(o, { a: 'isSafeInteger' }, { c: 'bigint' }); // Ok!\n// // Should fail type-check\n// const z1 = validateObject(o, { a: 'tmp' }, { c: 'zz' });\n// const z2 = validateObject(o, { a: 'isSafeInteger' }, { c: 'zz' });\n// const z3 = validateObject(o, { test: 'boolean', z: 'bug' });\n// const z4 = validateObject(o, { a: 'boolean', z: 'bug' });\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha256 } from '@noble/hashes/sha256';\nimport { randomBytes } from '@noble/hashes/utils';\nimport { Field, mod, pow2 } from './abstract/modular.js';\nimport { ProjPointType as PointType, mapToCurveSimpleSWU } from './abstract/weierstrass.js';\nimport type { Hex, PrivKey } from './abstract/utils.js';\nimport { bytesToNumberBE, concatBytes, ensureBytes, numberToBytesBE } from './abstract/utils.js';\nimport { createHasher, isogenyMap } from './abstract/hash-to-curve.js';\nimport { createCurve } from './_shortw_utils.js';\n\nconst secp256k1P = BigInt('0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f');\nconst secp256k1N = BigInt('0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141');\nconst _1n = BigInt(1);\nconst _2n = BigInt(2);\nconst divNearest = (a: bigint, b: bigint) => (a + b / _2n) / b;\n\n/**\n * \u221An = n^((p+1)/4) for fields p = 3 mod 4. We unwrap the loop and multiply bit-by-bit.\n * (P+1n/4n).toString(2) would produce bits [223x 1, 0, 22x 1, 4x 0, 11, 00]\n */\nfunction sqrtMod(y: bigint): bigint {\n const P = secp256k1P;\n // prettier-ignore\n const _3n = BigInt(3), _6n = BigInt(6), _11n = BigInt(11), _22n = BigInt(22);\n // prettier-ignore\n const _23n = BigInt(23), _44n = BigInt(44), _88n = BigInt(88);\n const b2 = (y * y * y) % P; // x^3, 11\n const b3 = (b2 * b2 * y) % P; // x^7\n const b6 = (pow2(b3, _3n, P) * b3) % P;\n const b9 = (pow2(b6, _3n, P) * b3) % P;\n const b11 = (pow2(b9, _2n, P) * b2) % P;\n const b22 = (pow2(b11, _11n, P) * b11) % P;\n const b44 = (pow2(b22, _22n, P) * b22) % P;\n const b88 = (pow2(b44, _44n, P) * b44) % P;\n const b176 = (pow2(b88, _88n, P) * b88) % P;\n const b220 = (pow2(b176, _44n, P) * b44) % P;\n const b223 = (pow2(b220, _3n, P) * b3) % P;\n const t1 = (pow2(b223, _23n, P) * b22) % P;\n const t2 = (pow2(t1, _6n, P) * b2) % P;\n const root = pow2(t2, _2n, P);\n if (!Fp.eql(Fp.sqr(root), y)) throw new Error('Cannot find square root');\n return root;\n}\n\nconst Fp = Field(secp256k1P, undefined, undefined, { sqrt: sqrtMod });\n\nexport const secp256k1 = createCurve(\n {\n a: BigInt(0), // equation params: a, b\n b: BigInt(7), // Seem to be rigid: bitcointalk.org/index.php?topic=289795.msg3183975#msg3183975\n Fp, // Field's prime: 2n**256n - 2n**32n - 2n**9n - 2n**8n - 2n**7n - 2n**6n - 2n**4n - 1n\n n: secp256k1N, // Curve order, total count of valid points in the field\n // Base point (x, y) aka generator point\n Gx: BigInt('55066263022277343669578718895168534326250603453777594175500187360389116729240'),\n Gy: BigInt('32670510020758816978083085130507043184471273380659243275938904335757337482424'),\n h: BigInt(1), // Cofactor\n lowS: true, // Allow only low-S signatures by default in sign() and verify()\n /**\n * secp256k1 belongs to Koblitz curves: it has efficiently computable endomorphism.\n * Endomorphism uses 2x less RAM, speeds up precomputation by 2x and ECDH / key recovery by 20%.\n * For precomputed wNAF it trades off 1/2 init time & 1/3 ram for 20% perf hit.\n * Explanation: https://gist.github.com/paulmillr/eb670806793e84df628a7c434a873066\n */\n endo: {\n beta: BigInt('0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee'),\n splitScalar: (k: bigint) => {\n const n = secp256k1N;\n const a1 = BigInt('0x3086d221a7d46bcde86c90e49284eb15');\n const b1 = -_1n * BigInt('0xe4437ed6010e88286f547fa90abfe4c3');\n const a2 = BigInt('0x114ca50f7a8e2f3f657c1108d9d44cfd8');\n const b2 = a1;\n const POW_2_128 = BigInt('0x100000000000000000000000000000000'); // (2n**128n).toString(16)\n\n const c1 = divNearest(b2 * k, n);\n const c2 = divNearest(-b1 * k, n);\n let k1 = mod(k - c1 * a1 - c2 * a2, n);\n let k2 = mod(-c1 * b1 - c2 * b2, n);\n const k1neg = k1 > POW_2_128;\n const k2neg = k2 > POW_2_128;\n if (k1neg) k1 = n - k1;\n if (k2neg) k2 = n - k2;\n if (k1 > POW_2_128 || k2 > POW_2_128) {\n throw new Error('splitScalar: Endomorphism failed, k=' + k);\n }\n return { k1neg, k1, k2neg, k2 };\n },\n },\n },\n sha256\n);\n\n// Schnorr signatures are superior to ECDSA from above. Below is Schnorr-specific BIP0340 code.\n// https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki\nconst _0n = BigInt(0);\nconst fe = (x: bigint) => typeof x === 'bigint' && _0n < x && x < secp256k1P;\nconst ge = (x: bigint) => typeof x === 'bigint' && _0n < x && x < secp256k1N;\n/** An object mapping tags to their tagged hash prefix of [SHA256(tag) | SHA256(tag)] */\nconst TAGGED_HASH_PREFIXES: { [tag: string]: Uint8Array } = {};\nfunction taggedHash(tag: string, ...messages: Uint8Array[]): Uint8Array {\n let tagP = TAGGED_HASH_PREFIXES[tag];\n if (tagP === undefined) {\n const tagH = sha256(Uint8Array.from(tag, (c) => c.charCodeAt(0)));\n tagP = concatBytes(tagH, tagH);\n TAGGED_HASH_PREFIXES[tag] = tagP;\n }\n return sha256(concatBytes(tagP, ...messages));\n}\n\n// ECDSA compact points are 33-byte. Schnorr is 32: we strip first byte 0x02 or 0x03\nconst pointToBytes = (point: PointType<bigint>) => point.toRawBytes(true).slice(1);\nconst numTo32b = (n: bigint) => numberToBytesBE(n, 32);\nconst modP = (x: bigint) => mod(x, secp256k1P);\nconst modN = (x: bigint) => mod(x, secp256k1N);\nconst Point = secp256k1.ProjectivePoint;\nconst GmulAdd = (Q: PointType<bigint>, a: bigint, b: bigint) =>\n Point.BASE.multiplyAndAddUnsafe(Q, a, b);\n\n// Calculate point, scalar and bytes\nfunction schnorrGetExtPubKey(priv: PrivKey) {\n let d_ = secp256k1.utils.normPrivateKeyToScalar(priv); // same method executed in fromPrivateKey\n let p = Point.fromPrivateKey(d_); // P = d'\u22C5G; 0 < d' < n check is done inside\n const scalar = p.hasEvenY() ? d_ : modN(-d_);\n return { scalar: scalar, bytes: pointToBytes(p) };\n}\n/**\n * lift_x from BIP340. Convert 32-byte x coordinate to elliptic curve point.\n * @returns valid point checked for being on-curve\n */\nfunction lift_x(x: bigint): PointType<bigint> {\n if (!fe(x)) throw new Error('bad x: need 0 < x < p'); // Fail if x \u2265 p.\n const xx = modP(x * x);\n const c = modP(xx * x + BigInt(7)); // Let c = x\u00B3 + 7 mod p.\n let y = sqrtMod(c); // Let y = c^(p+1)/4 mod p.\n if (y % _2n !== _0n) y = modP(-y); // Return the unique point P such that x(P) = x and\n const p = new Point(x, y, _1n); // y(P) = y if y mod 2 = 0 or y(P) = p-y otherwise.\n p.assertValidity();\n return p;\n}\n/**\n * Create tagged hash, convert it to bigint, reduce modulo-n.\n */\nfunction challenge(...args: Uint8Array[]): bigint {\n return modN(bytesToNumberBE(taggedHash('BIP0340/challenge', ...args)));\n}\n\n/**\n * Schnorr public key is just `x` coordinate of Point as per BIP340.\n */\nfunction schnorrGetPublicKey(privateKey: Hex): Uint8Array {\n return schnorrGetExtPubKey(privateKey).bytes; // d'=int(sk). Fail if d'=0 or d'\u2265n. Ret bytes(d'\u22C5G)\n}\n\n/**\n * Creates Schnorr signature as per BIP340. Verifies itself before returning anything.\n * auxRand is optional and is not the sole source of k generation: bad CSPRNG won't be dangerous.\n */\nfunction schnorrSign(\n message: Hex,\n privateKey: PrivKey,\n auxRand: Hex = randomBytes(32)\n): Uint8Array {\n const m = ensureBytes('message', message);\n const { bytes: px, scalar: d } = schnorrGetExtPubKey(privateKey); // checks for isWithinCurveOrder\n const a = ensureBytes('auxRand', auxRand, 32); // Auxiliary random data a: a 32-byte array\n const t = numTo32b(d ^ bytesToNumberBE(taggedHash('BIP0340/aux', a))); // Let t be the byte-wise xor of bytes(d) and hash/aux(a)\n const rand = taggedHash('BIP0340/nonce', t, px, m); // Let rand = hash/nonce(t || bytes(P) || m)\n const k_ = modN(bytesToNumberBE(rand)); // Let k' = int(rand) mod n\n if (k_ === _0n) throw new Error('sign failed: k is zero'); // Fail if k' = 0.\n const { bytes: rx, scalar: k } = schnorrGetExtPubKey(k_); // Let R = k'\u22C5G.\n const e = challenge(rx, px, m); // Let e = int(hash/challenge(bytes(R) || bytes(P) || m)) mod n.\n const sig = new Uint8Array(64); // Let sig = bytes(R) || bytes((k + ed) mod n).\n sig.set(rx, 0);\n sig.set(numTo32b(modN(k + e * d)), 32);\n // If Verify(bytes(P), m, sig) (see below) returns failure, abort\n if (!schnorrVerify(sig, m, px)) throw new Error('sign: Invalid signature produced');\n return sig;\n}\n\n/**\n * Verifies Schnorr signature.\n * Will swallow errors & return false except for initial type validation of arguments.\n */\nfunction schnorrVerify(signature: Hex, message: Hex, publicKey: Hex): boolean {\n const sig = ensureBytes('signature', signature, 64);\n const m = ensureBytes('message', message);\n const pub = ensureBytes('publicKey', publicKey, 32);\n try {\n const P = lift_x(bytesToNumberBE(pub)); // P = lift_x(int(pk)); fail if that fails\n const r = bytesToNumberBE(sig.subarray(0, 32)); // Let r = int(sig[0:32]); fail if r \u2265 p.\n if (!fe(r)) return false;\n const s = bytesToNumberBE(sig.subarray(32, 64)); // Let s = int(sig[32:64]); fail if s \u2265 n.\n if (!ge(s)) return false;\n const e = challenge(numTo32b(r), pointToBytes(P), m); // int(challenge(bytes(r)||bytes(P)||m))%n\n const R = GmulAdd(P, s, modN(-e)); // R = s\u22C5G - e\u22C5P\n if (!R || !R.hasEvenY() || R.toAffine().x !== r) return false; // -eP == (n-e)P\n return true; // Fail if is_infinite(R) / not has_even_y(R) / x(R) \u2260 r.\n } catch (error) {\n return false;\n }\n}\n\nexport const schnorr = /* @__PURE__ */ (() => ({\n getPublicKey: schnorrGetPublicKey,\n sign: schnorrSign,\n verify: schnorrVerify,\n utils: {\n randomPrivateKey: secp256k1.utils.randomPrivateKey,\n lift_x,\n pointToBytes,\n numberToBytesBE,\n bytesToNumberBE,\n taggedHash,\n mod,\n },\n}))();\n\nconst isoMap = /* @__PURE__ */ (() =>\n isogenyMap(\n Fp,\n [\n // xNum\n [\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa8c7',\n '0x7d3d4c80bc321d5b9f315cea7fd44c5d595d2fc0bf63b92dfff1044f17c6581',\n '0x534c328d23f234e6e2a413deca25caece4506144037c40314ecbd0b53d9dd262',\n '0x8e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38e38daaaaa88c',\n ],\n // xDen\n [\n '0xd35771193d94918a9ca34ccbb7b640dd86cd409542f8487d9fe6b745781eb49b',\n '0xedadc6f64383dc1df7c4b2d51b54225406d36b641f5e41bbc52a56612a8c6d14',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n // yNum\n [\n '0x4bda12f684bda12f684bda12f684bda12f684bda12f684bda12f684b8e38e23c',\n '0xc75e0c32d5cb7c0fa9d0a54b12a0a6d5647ab046d686da6fdffc90fc201d71a3',\n '0x29a6194691f91a73715209ef6512e576722830a201be2018a765e85a9ecee931',\n '0x2f684bda12f684bda12f684bda12f684bda12f684bda12f684bda12f38e38d84',\n ],\n // yDen\n [\n '0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffff93b',\n '0x7a06534bb8bdb49fd5e9e6632722c2989467c1bfc8e8d978dfb425d2685c2573',\n '0x6484aa716545ca2cf3a70c3fa8fe337e0a3d21162f0d6299a7bf8192bfd2a76f',\n '0x0000000000000000000000000000000000000000000000000000000000000001', // LAST 1\n ],\n ].map((i) => i.map((j) => BigInt(j))) as [bigint[], bigint[], bigint[], bigint[]]\n ))();\nconst mapSWU = /* @__PURE__ */ (() =>\n mapToCurveSimpleSWU(Fp, {\n A: BigInt('0x3f8731abdd661adca08a5558f0f5d272e953d363cb6f0e5d405447c01a444533'),\n B: BigInt('1771'),\n Z: Fp.create(BigInt('-11')),\n }))();\nconst htf = /* @__PURE__ */ (() =>\n createHasher(\n secp256k1.ProjectivePoint,\n (scalars: bigint[]) => {\n const { x, y } = mapSWU(Fp.create(scalars[0]));\n return isoMap(x, y);\n },\n {\n DST: 'secp256k1_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'secp256k1_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n }\n ))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n", "import { SHA2 } from './_sha2.js';\nimport { rotr, wrapConstructor } from './utils.js';\n\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n\n// Choice: a ? b : c\nconst Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c);\n// Majority function, true if any two inpust is true\nconst Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c);\n\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n// Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n// prettier-ignore\nconst IV = /* @__PURE__ */new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nclass SHA256 extends SHA2<SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = IV[0] | 0;\n B = IV[1] | 0;\n C = IV[2] | 0;\n D = IV[3] | 0;\n E = IV[4] | 0;\n F = IV[5] | 0;\n G = IV[6] | 0;\n H = IV[7] | 0;\n\n constructor() {\n super(64, 32, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n A = 0xc1059ed8 | 0;\n B = 0x367cd507 | 0;\n C = 0x3070dd17 | 0;\n D = 0xf70e5939 | 0;\n E = 0xffc00b31 | 0;\n F = 0x68581511 | 0;\n G = 0x64f98fa7 | 0;\n H = 0xbefa4fa4 | 0;\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n", "import { exists, output } from './_assert.js';\nimport { Hash, createView, Input, toBytes } from './utils.js';\n\n// Polyfill for Safari 14\nfunction setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n// Base SHA2 class (RFC 6234)\nexport abstract class SHA2<T extends SHA2<T>> extends Hash<T> {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(\n readonly blockLen: number,\n public outputLen: number,\n readonly padOffset: number,\n readonly isLE: boolean\n ) {\n super();\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array) {\n exists(this);\n output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n}\n", "function number(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error(`Wrong positive integer: ${n}`);\n}\n\nfunction bool(b: boolean) {\n if (typeof b !== 'boolean') throw new Error(`Expected boolean, not ${b}`);\n}\n\n// copied from utils\nfunction isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\nfunction bytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!isBytes(b)) throw new Error('Expected Uint8Array');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Expected Uint8Array of length ${lengths}, not of length=${b.length}`);\n}\n\ntype Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nfunction hash(hash: Hash) {\n if (typeof hash !== 'function' || typeof hash.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(hash.outputLen);\n number(hash.blockLen);\n}\n\nfunction exists(instance: any, checkFinished = true) {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\nfunction output(out: any, instance: any) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\n\nexport { number, bool, bytes, hash, exists, output };\n\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n", "/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n// Cast array to different type\nexport const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr: TypedArray) =>\n new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\nfunction isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\n// Cast array to view\nexport const createView = (arr: TypedArray) =>\n new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word: number, shift: number) => (word << (32 - shift)) | (word >>> shift);\n\n// big-endian hardware is rare. Just in case someone still decides to run hashes:\n// early-throw an error because we don't support BE yet.\n// Other libraries would silently corrupt the data instead of throwing an error,\n// when they don't support it.\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\nif (!isLE) throw new Error('Non little-endian hardware is not supported');\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n if (!isBytes(bytes)) throw new Error('Uint8Array expected');\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 } as const;\nfunction asciiToBase16(char: number): number | undefined {\n if (char >= asciis._0 && char <= asciis._9) return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10);\n return;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => {};\n\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n if (!isBytes(data)) throw new Error(`expected Uint8Array, got ${typeof data}`);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n if (!isBytes(a)) throw new Error('Uint8Array expected');\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n// For runtime check if class implements interface\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\nconst toStr = {}.toString;\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\nexport type CHash = ReturnType<typeof wrapConstructor>;\n\nexport function wrapConstructor<T extends Hash<T>>(hashCons: () => Hash<T>) {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function wrapConstructorWithOpts<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\nexport function wrapXOFConstructorWithOpts<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n", "// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// See utils.ts for details.\ndeclare const globalThis: Record<string, any> | undefined;\nexport const crypto =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Utilities for modular arithmetics and finite fields\nimport {\n bitMask,\n numberToBytesBE,\n numberToBytesLE,\n bytesToNumberBE,\n bytesToNumberLE,\n ensureBytes,\n validateObject,\n} from './utils.js';\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);\n// prettier-ignore\nconst _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);\n// prettier-ignore\nconst _9n = BigInt(9), _16n = BigInt(16);\n\n// Calculates a modulo b\nexport function mod(a: bigint, b: bigint): bigint {\n const result = a % b;\n return result >= _0n ? result : b + result;\n}\n/**\n * Efficiently raise num to power and do modular division.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n * @example\n * pow(2n, 6n, 11n) // 64n % 11n == 9n\n */\n// TODO: use field version && remove\nexport function pow(num: bigint, power: bigint, modulo: bigint): bigint {\n if (modulo <= _0n || power < _0n) throw new Error('Expected power/modulo > 0');\n if (modulo === _1n) return _0n;\n let res = _1n;\n while (power > _0n) {\n if (power & _1n) res = (res * num) % modulo;\n num = (num * num) % modulo;\n power >>= _1n;\n }\n return res;\n}\n\n// Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)\nexport function pow2(x: bigint, power: bigint, modulo: bigint): bigint {\n let res = x;\n while (power-- > _0n) {\n res *= res;\n res %= modulo;\n }\n return res;\n}\n\n// Inverses number over modulo\nexport function invert(number: bigint, modulo: bigint): bigint {\n if (number === _0n || modulo <= _0n) {\n throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);\n }\n // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/\n // Fermat's little theorem \"CT-like\" version inv(n) = n^(m-2) mod m is 30x slower.\n let a = mod(number, modulo);\n let b = modulo;\n // prettier-ignore\n let x = _0n, y = _1n, u = _1n, v = _0n;\n while (a !== _0n) {\n // JIT applies optimization if those two lines follow each other\n const q = b / a;\n const r = b % a;\n const m = x - u * q;\n const n = y - v * q;\n // prettier-ignore\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n const gcd = b;\n if (gcd !== _1n) throw new Error('invert: does not exist');\n return mod(x, modulo);\n}\n\n/**\n * Tonelli-Shanks square root search algorithm.\n * 1. https://eprint.iacr.org/2012/685.pdf (page 12)\n * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks\n * Will start an infinite loop if field order P is not prime.\n * @param P field order\n * @returns function that takes field Fp (created from P) and number n\n */\nexport function tonelliShanks(P: bigint) {\n // Legendre constant: used to calculate Legendre symbol (a | p),\n // which denotes the value of a^((p-1)/2) (mod p).\n // (a | p) \u2261 1 if a is a square (mod p)\n // (a | p) \u2261 -1 if a is not a square (mod p)\n // (a | p) \u2261 0 if a \u2261 0 (mod p)\n const legendreC = (P - _1n) / _2n;\n\n let Q: bigint, S: number, Z: bigint;\n // Step 1: By factoring out powers of 2 from p - 1,\n // find q and s such that p - 1 = q*(2^s) with q odd\n for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++);\n\n // Step 2: Select a non-square z such that (z | p) \u2261 -1 and set c \u2261 zq\n for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++);\n\n // Fast-path\n if (S === 1) {\n const p1div4 = (P + _1n) / _4n;\n return function tonelliFast<T>(Fp: IField<T>, n: T) {\n const root = Fp.pow(n, p1div4);\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Slow-path\n const Q1div2 = (Q + _1n) / _2n;\n return function tonelliSlow<T>(Fp: IField<T>, n: T): T {\n // Step 0: Check that n is indeed a square: (n | p) should not be \u2261 -1\n if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE)) throw new Error('Cannot find square root');\n let r = S;\n // TODO: will fail at Fp2/etc\n let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b\n let x = Fp.pow(n, Q1div2); // first guess at the square root\n let b = Fp.pow(n, Q); // first guess at the fudge factor\n\n while (!Fp.eql(b, Fp.ONE)) {\n if (Fp.eql(b, Fp.ZERO)) return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)\n // Find m such b^(2^m)==1\n let m = 1;\n for (let t2 = Fp.sqr(b); m < r; m++) {\n if (Fp.eql(t2, Fp.ONE)) break;\n t2 = Fp.sqr(t2); // t2 *= t2\n }\n // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow\n const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)\n g = Fp.sqr(ge); // g = ge * ge\n x = Fp.mul(x, ge); // x *= ge\n b = Fp.mul(b, g); // b *= g\n r = m;\n }\n return x;\n };\n}\n\nexport function FpSqrt(P: bigint) {\n // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.\n // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).\n\n // P \u2261 3 (mod 4)\n // \u221An = n^((P+1)/4)\n if (P % _4n === _3n) {\n // Not all roots possible!\n // const ORDER =\n // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;\n // const NUM = 72057594037927816n;\n const p1div4 = (P + _1n) / _4n;\n return function sqrt3mod4<T>(Fp: IField<T>, n: T) {\n const root = Fp.pow(n, p1div4);\n // Throw if root**2 != n\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // Atkin algorithm for q \u2261 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)\n if (P % _8n === _5n) {\n const c1 = (P - _5n) / _8n;\n return function sqrt5mod8<T>(Fp: IField<T>, n: T) {\n const n2 = Fp.mul(n, _2n);\n const v = Fp.pow(n2, c1);\n const nv = Fp.mul(n, v);\n const i = Fp.mul(Fp.mul(nv, _2n), v);\n const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));\n if (!Fp.eql(Fp.sqr(root), n)) throw new Error('Cannot find square root');\n return root;\n };\n }\n\n // P \u2261 9 (mod 16)\n if (P % _16n === _9n) {\n // NOTE: tonelli is too slow for bls-Fp2 calculations even on start\n // Means we cannot use sqrt for constants at all!\n //\n // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F\n // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F\n // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F\n // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic\n // sqrt = (x) => {\n // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4\n // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1\n // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1\n // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1\n // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x\n // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x\n // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x\n // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x\n // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x\n // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2\n // }\n }\n\n // Other cases: Tonelli-Shanks algorithm\n return tonelliShanks(P);\n}\n\n// Little-endian check for first LE bit (last BE bit);\nexport const isNegativeLE = (num: bigint, modulo: bigint) => (mod(num, modulo) & _1n) === _1n;\n\n// Field is not always over prime: for example, Fp2 has ORDER(q)=p^m\nexport interface IField<T> {\n ORDER: bigint;\n BYTES: number;\n BITS: number;\n MASK: bigint;\n ZERO: T;\n ONE: T;\n // 1-arg\n create: (num: T) => T;\n isValid: (num: T) => boolean;\n is0: (num: T) => boolean;\n neg(num: T): T;\n inv(num: T): T;\n sqrt(num: T): T;\n sqr(num: T): T;\n // 2-args\n eql(lhs: T, rhs: T): boolean;\n add(lhs: T, rhs: T): T;\n sub(lhs: T, rhs: T): T;\n mul(lhs: T, rhs: T | bigint): T;\n pow(lhs: T, power: bigint): T;\n div(lhs: T, rhs: T | bigint): T;\n // N for NonNormalized (for now)\n addN(lhs: T, rhs: T): T;\n subN(lhs: T, rhs: T): T;\n mulN(lhs: T, rhs: T | bigint): T;\n sqrN(num: T): T;\n\n // Optional\n // Should be same as sgn0 function in\n // [RFC9380](https://www.rfc-editor.org/rfc/rfc9380#section-4.1).\n // NOTE: sgn0 is 'negative in LE', which is same as odd. And negative in LE is kinda strange definition anyway.\n isOdd?(num: T): boolean; // Odd instead of even since we have it for Fp2\n // legendre?(num: T): T;\n pow(lhs: T, power: bigint): T;\n invertBatch: (lst: T[]) => T[];\n toBytes(num: T): Uint8Array;\n fromBytes(bytes: Uint8Array): T;\n // If c is False, CMOV returns a, otherwise it returns b.\n cmov(a: T, b: T, c: boolean): T;\n}\n// prettier-ignore\nconst FIELD_FIELDS = [\n 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',\n 'eql', 'add', 'sub', 'mul', 'pow', 'div',\n 'addN', 'subN', 'mulN', 'sqrN'\n] as const;\nexport function validateField<T>(field: IField<T>) {\n const initial = {\n ORDER: 'bigint',\n MASK: 'bigint',\n BYTES: 'isSafeInteger',\n BITS: 'isSafeInteger',\n } as Record<string, string>;\n const opts = FIELD_FIELDS.reduce((map, val: string) => {\n map[val] = 'function';\n return map;\n }, initial);\n return validateObject(field, opts);\n}\n\n// Generic field functions\n\n/**\n * Same as `pow` but for Fp: non-constant-time.\n * Unsafe in some contexts: uses ladder, so can expose bigint bits.\n */\nexport function FpPow<T>(f: IField<T>, num: T, power: bigint): T {\n // Should have same speed as pow for bigints\n // TODO: benchmark!\n if (power < _0n) throw new Error('Expected power > 0');\n if (power === _0n) return f.ONE;\n if (power === _1n) return num;\n let p = f.ONE;\n let d = num;\n while (power > _0n) {\n if (power & _1n) p = f.mul(p, d);\n d = f.sqr(d);\n power >>= _1n;\n }\n return p;\n}\n\n/**\n * Efficiently invert an array of Field elements.\n * `inv(0)` will return `undefined` here: make sure to throw an error.\n */\nexport function FpInvertBatch<T>(f: IField<T>, nums: T[]): T[] {\n const tmp = new Array(nums.length);\n // Walk from first to last, multiply them by each other MOD p\n const lastMultiplied = nums.reduce((acc, num, i) => {\n if (f.is0(num)) return acc;\n tmp[i] = acc;\n return f.mul(acc, num);\n }, f.ONE);\n // Invert last element\n const inverted = f.inv(lastMultiplied);\n // Walk from last to first, multiply them by inverted each other MOD p\n nums.reduceRight((acc, num, i) => {\n if (f.is0(num)) return acc;\n tmp[i] = f.mul(acc, tmp[i]);\n return f.mul(acc, num);\n }, inverted);\n return tmp;\n}\n\nexport function FpDiv<T>(f: IField<T>, lhs: T, rhs: T | bigint): T {\n return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));\n}\n\n// This function returns True whenever the value x is a square in the field F.\nexport function FpIsSquare<T>(f: IField<T>) {\n const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic\n return (x: T): boolean => {\n const p = f.pow(x, legendreConst);\n return f.eql(p, f.ZERO) || f.eql(p, f.ONE);\n };\n}\n\n// CURVE.n lengths\nexport function nLength(n: bigint, nBitLength?: number) {\n // Bit size, byte size of CURVE.n\n const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;\n const nByteLength = Math.ceil(_nBitLength / 8);\n return { nBitLength: _nBitLength, nByteLength };\n}\n\ntype FpField = IField<bigint> & Required<Pick<IField<bigint>, 'isOdd'>>;\n/**\n * Initializes a finite field over prime. **Non-primes are not supported.**\n * Do not init in loop: slow. Very fragile: always run a benchmark on a change.\n * Major performance optimizations:\n * * a) denormalized operations like mulN instead of mul\n * * b) same object shape: never add or remove keys\n * * c) Object.freeze\n * @param ORDER prime positive bigint\n * @param bitLen how many bits the field consumes\n * @param isLE (def: false) if encoding / decoding should be in little-endian\n * @param redef optional faster redefinitions of sqrt and other methods\n */\nexport function Field(\n ORDER: bigint,\n bitLen?: number,\n isLE = false,\n redef: Partial<IField<bigint>> = {}\n): Readonly<FpField> {\n if (ORDER <= _0n) throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);\n const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);\n if (BYTES > 2048) throw new Error('Field lengths over 2048 bytes are not supported');\n const sqrtP = FpSqrt(ORDER);\n const f: Readonly<FpField> = Object.freeze({\n ORDER,\n BITS,\n BYTES,\n MASK: bitMask(BITS),\n ZERO: _0n,\n ONE: _1n,\n create: (num) => mod(num, ORDER),\n isValid: (num) => {\n if (typeof num !== 'bigint')\n throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);\n return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible\n },\n is0: (num) => num === _0n,\n isOdd: (num) => (num & _1n) === _1n,\n neg: (num) => mod(-num, ORDER),\n eql: (lhs, rhs) => lhs === rhs,\n\n sqr: (num) => mod(num * num, ORDER),\n add: (lhs, rhs) => mod(lhs + rhs, ORDER),\n sub: (lhs, rhs) => mod(lhs - rhs, ORDER),\n mul: (lhs, rhs) => mod(lhs * rhs, ORDER),\n pow: (num, power) => FpPow(f, num, power),\n div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),\n\n // Same as above, but doesn't normalize\n sqrN: (num) => num * num,\n addN: (lhs, rhs) => lhs + rhs,\n subN: (lhs, rhs) => lhs - rhs,\n mulN: (lhs, rhs) => lhs * rhs,\n\n inv: (num) => invert(num, ORDER),\n sqrt: redef.sqrt || ((n) => sqrtP(f, n)),\n invertBatch: (lst) => FpInvertBatch(f, lst),\n // TODO: do we really need constant cmov?\n // We don't have const-time bigints anyway, so probably will be not very useful\n cmov: (a, b, c) => (c ? b : a),\n toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),\n fromBytes: (bytes) => {\n if (bytes.length !== BYTES)\n throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);\n return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);\n },\n } as FpField);\n return Object.freeze(f);\n}\n\nexport function FpSqrtOdd<T>(Fp: IField<T>, elm: T) {\n if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? root : Fp.neg(root);\n}\n\nexport function FpSqrtEven<T>(Fp: IField<T>, elm: T) {\n if (!Fp.isOdd) throw new Error(`Field doesn't have isOdd`);\n const root = Fp.sqrt(elm);\n return Fp.isOdd(root) ? Fp.neg(root) : root;\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).\n * Which makes it slightly more biased, less secure.\n * @deprecated use mapKeyToField instead\n */\nexport function hashToPrivateScalar(\n hash: string | Uint8Array,\n groupOrder: bigint,\n isLE = false\n): bigint {\n hash = ensureBytes('privateHash', hash);\n const hashLen = hash.length;\n const minLen = nLength(groupOrder).nByteLength + 8;\n if (minLen < 24 || hashLen < minLen || hashLen > 1024)\n throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);\n const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);\n return mod(num, groupOrder - _1n) + _1n;\n}\n\n/**\n * Returns total number of bytes consumed by the field element.\n * For example, 32 bytes for usual 256-bit weierstrass curve.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of field\n */\nexport function getFieldBytesLength(fieldOrder: bigint): number {\n if (typeof fieldOrder !== 'bigint') throw new Error('field order must be bigint');\n const bitLength = fieldOrder.toString(2).length;\n return Math.ceil(bitLength / 8);\n}\n\n/**\n * Returns minimal amount of bytes that can be safely reduced\n * by field order.\n * Should be 2^-128 for 128-bit curve such as P256.\n * @param fieldOrder number of field elements, usually CURVE.n\n * @returns byte length of target hash\n */\nexport function getMinHashLength(fieldOrder: bigint): number {\n const length = getFieldBytesLength(fieldOrder);\n return length + Math.ceil(length / 2);\n}\n\n/**\n * \"Constant-time\" private key generation utility.\n * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF\n * and convert them into private scalar, with the modulo bias being negligible.\n * Needs at least 48 bytes of input for 32-byte private key.\n * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/\n * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final\n * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5\n * @param hash hash output from SHA3 or a similar function\n * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)\n * @param isLE interpret hash bytes as LE num\n * @returns valid private scalar\n */\nexport function mapHashToField(key: Uint8Array, fieldOrder: bigint, isLE = false): Uint8Array {\n const len = key.length;\n const fieldLen = getFieldBytesLength(fieldOrder);\n const minLen = getMinHashLength(fieldOrder);\n // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.\n if (len < 16 || len < minLen || len > 1024)\n throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);\n const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);\n // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0\n const reduced = mod(num, fieldOrder - _1n) + _1n;\n return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Short Weierstrass curve. The formula is: y\u00B2 = x\u00B3 + ax + b\nimport * as mod from './modular.js';\nimport * as ut from './utils.js';\nimport { CHash, Hex, PrivKey, ensureBytes } from './utils.js';\nimport { Group, GroupConstructor, wNAF, BasicCurve, validateBasic, AffinePoint } from './curve.js';\n\nexport type { AffinePoint };\ntype HmacFnSync = (key: Uint8Array, ...messages: Uint8Array[]) => Uint8Array;\ntype EndomorphismOpts = {\n beta: bigint;\n splitScalar: (k: bigint) => { k1neg: boolean; k1: bigint; k2neg: boolean; k2: bigint };\n};\nexport type BasicWCurve<T> = BasicCurve<T> & {\n // Params: a, b\n a: T;\n b: T;\n\n // Optional params\n allowedPrivateKeyLengths?: readonly number[]; // for P521\n wrapPrivateKey?: boolean; // bls12-381 requires mod(n) instead of rejecting keys >= n\n endo?: EndomorphismOpts; // Endomorphism options for Koblitz curves\n // When a cofactor != 1, there can be an effective methods to:\n // 1. Determine whether a point is torsion-free\n isTorsionFree?: (c: ProjConstructor<T>, point: ProjPointType<T>) => boolean;\n // 2. Clear torsion component\n clearCofactor?: (c: ProjConstructor<T>, point: ProjPointType<T>) => ProjPointType<T>;\n};\n\ntype Entropy = Hex | true;\nexport type SignOpts = { lowS?: boolean; extraEntropy?: Entropy; prehash?: boolean };\nexport type VerOpts = { lowS?: boolean; prehash?: boolean };\n\n/**\n * ### Design rationale for types\n *\n * * Interaction between classes from different curves should fail:\n * `k256.Point.BASE.add(p256.Point.BASE)`\n * * For this purpose we want to use `instanceof` operator, which is fast and works during runtime\n * * Different calls of `curve()` would return different classes -\n * `curve(params) !== curve(params)`: if somebody decided to monkey-patch their curve,\n * it won't affect others\n *\n * TypeScript can't infer types for classes created inside a function. Classes is one instance of nominative types in TypeScript and interfaces only check for shape, so it's hard to create unique type for every function call.\n *\n * We can use generic types via some param, like curve opts, but that would:\n * 1. Enable interaction between `curve(params)` and `curve(params)` (curves of same params)\n * which is hard to debug.\n * 2. Params can be generic and we can't enforce them to be constant value:\n * if somebody creates curve from non-constant params,\n * it would be allowed to interact with other curves with non-constant params\n *\n * TODO: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-7.html#unique-symbol\n */\n\n// Instance for 3d XYZ points\nexport interface ProjPointType<T> extends Group<ProjPointType<T>> {\n readonly px: T;\n readonly py: T;\n readonly pz: T;\n get x(): T;\n get y(): T;\n multiply(scalar: bigint): ProjPointType<T>;\n toAffine(iz?: T): AffinePoint<T>;\n isTorsionFree(): boolean;\n clearCofactor(): ProjPointType<T>;\n assertValidity(): void;\n hasEvenY(): boolean;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n\n multiplyUnsafe(scalar: bigint): ProjPointType<T>;\n multiplyAndAddUnsafe(Q: ProjPointType<T>, a: bigint, b: bigint): ProjPointType<T> | undefined;\n _setWindowSize(windowSize: number): void;\n}\n// Static methods for 3d XYZ points\nexport interface ProjConstructor<T> extends GroupConstructor<ProjPointType<T>> {\n new (x: T, y: T, z: T): ProjPointType<T>;\n fromAffine(p: AffinePoint<T>): ProjPointType<T>;\n fromHex(hex: Hex): ProjPointType<T>;\n fromPrivateKey(privateKey: PrivKey): ProjPointType<T>;\n normalizeZ(points: ProjPointType<T>[]): ProjPointType<T>[];\n}\n\nexport type CurvePointsType<T> = BasicWCurve<T> & {\n // Bytes\n fromBytes?: (bytes: Uint8Array) => AffinePoint<T>;\n toBytes?: (c: ProjConstructor<T>, point: ProjPointType<T>, isCompressed: boolean) => Uint8Array;\n};\n\nfunction validatePointOpts<T>(curve: CurvePointsType<T>) {\n const opts = validateBasic(curve);\n ut.validateObject(\n opts,\n {\n a: 'field',\n b: 'field',\n },\n {\n allowedPrivateKeyLengths: 'array',\n wrapPrivateKey: 'boolean',\n isTorsionFree: 'function',\n clearCofactor: 'function',\n allowInfinityPoint: 'boolean',\n fromBytes: 'function',\n toBytes: 'function',\n }\n );\n const { endo, Fp, a } = opts;\n if (endo) {\n if (!Fp.eql(a, Fp.ZERO)) {\n throw new Error('Endomorphism can only be defined for Koblitz curves that have a=0');\n }\n if (\n typeof endo !== 'object' ||\n typeof endo.beta !== 'bigint' ||\n typeof endo.splitScalar !== 'function'\n ) {\n throw new Error('Expected endomorphism with beta: bigint and splitScalar: function');\n }\n }\n return Object.freeze({ ...opts } as const);\n}\n\nexport type CurvePointsRes<T> = {\n CURVE: ReturnType<typeof validatePointOpts<T>>;\n ProjectivePoint: ProjConstructor<T>;\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n weierstrassEquation: (x: T) => T;\n isWithinCurveOrder: (num: bigint) => boolean;\n};\n\n// ASN.1 DER encoding utilities\nconst { bytesToNumberBE: b2n, hexToBytes: h2b } = ut;\nexport const DER = {\n // asn.1 DER encoding utils\n Err: class DERErr extends Error {\n constructor(m = '') {\n super(m);\n }\n },\n _parseInt(data: Uint8Array): { d: bigint; l: Uint8Array } {\n const { Err: E } = DER;\n if (data.length < 2 || data[0] !== 0x02) throw new E('Invalid signature integer tag');\n const len = data[1];\n const res = data.subarray(2, len + 2);\n if (!len || res.length !== len) throw new E('Invalid signature integer: wrong length');\n // https://crypto.stackexchange.com/a/57734 Leftmost bit of first byte is 'negative' flag,\n // since we always use positive integers here. It must always be empty:\n // - add zero byte if exists\n // - if next byte doesn't have a flag, leading zero is not allowed (minimal encoding)\n if (res[0] & 0b10000000) throw new E('Invalid signature integer: negative');\n if (res[0] === 0x00 && !(res[1] & 0b10000000))\n throw new E('Invalid signature integer: unnecessary leading zero');\n return { d: b2n(res), l: data.subarray(len + 2) }; // d is data, l is left\n },\n toSig(hex: string | Uint8Array): { r: bigint; s: bigint } {\n // parse DER signature\n const { Err: E } = DER;\n const data = typeof hex === 'string' ? h2b(hex) : hex;\n if (!ut.isBytes(data)) throw new Error('ui8a expected');\n let l = data.length;\n if (l < 2 || data[0] != 0x30) throw new E('Invalid signature tag');\n if (data[1] !== l - 2) throw new E('Invalid signature: incorrect length');\n const { d: r, l: sBytes } = DER._parseInt(data.subarray(2));\n const { d: s, l: rBytesLeft } = DER._parseInt(sBytes);\n if (rBytesLeft.length) throw new E('Invalid signature: left bytes after parsing');\n return { r, s };\n },\n hexFromSig(sig: { r: bigint; s: bigint }): string {\n // Add leading zero if first byte has negative bit enabled. More details in '_parseInt'\n const slice = (s: string): string => (Number.parseInt(s[0], 16) & 0b1000 ? '00' + s : s);\n const h = (num: number | bigint) => {\n const hex = num.toString(16);\n return hex.length & 1 ? `0${hex}` : hex;\n };\n const s = slice(h(sig.s));\n const r = slice(h(sig.r));\n const shl = s.length / 2;\n const rhl = r.length / 2;\n const sl = h(shl);\n const rl = h(rhl);\n return `30${h(rhl + shl + 4)}02${rl}${r}02${sl}${s}`;\n },\n};\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3), _4n = BigInt(4);\n\nexport function weierstrassPoints<T>(opts: CurvePointsType<T>): CurvePointsRes<T> {\n const CURVE = validatePointOpts(opts);\n const { Fp } = CURVE; // All curves has same field / group length as for now, but they can differ\n\n const toBytes =\n CURVE.toBytes ||\n ((_c: ProjConstructor<T>, point: ProjPointType<T>, _isCompressed: boolean) => {\n const a = point.toAffine();\n return ut.concatBytes(Uint8Array.from([0x04]), Fp.toBytes(a.x), Fp.toBytes(a.y));\n });\n const fromBytes =\n CURVE.fromBytes ||\n ((bytes: Uint8Array) => {\n // const head = bytes[0];\n const tail = bytes.subarray(1);\n // if (head !== 0x04) throw new Error('Only non-compressed encoding is supported');\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n });\n\n /**\n * y\u00B2 = x\u00B3 + ax + b: Short weierstrass curve formula\n * @returns y\u00B2\n */\n function weierstrassEquation(x: T): T {\n const { a, b } = CURVE;\n const x2 = Fp.sqr(x); // x * x\n const x3 = Fp.mul(x2, x); // x2 * x\n return Fp.add(Fp.add(x3, Fp.mul(x, a)), b); // x3 + a * x + b\n }\n // Validate whether the passed curve params are valid.\n // We check if curve equation works for generator point.\n // `assertValidity()` won't work: `isTorsionFree()` is not available at this point in bls12-381.\n // ProjectivePoint class has not been initialized yet.\n if (!Fp.eql(Fp.sqr(CURVE.Gy), weierstrassEquation(CURVE.Gx)))\n throw new Error('bad generator point: equation left != right');\n\n // Valid group elements reside in range 1..n-1\n function isWithinCurveOrder(num: bigint): boolean {\n return typeof num === 'bigint' && _0n < num && num < CURVE.n;\n }\n function assertGE(num: bigint) {\n if (!isWithinCurveOrder(num)) throw new Error('Expected valid bigint: 0 < bigint < curve.n');\n }\n // Validates if priv key is valid and converts it to bigint.\n // Supports options allowedPrivateKeyLengths and wrapPrivateKey.\n function normPrivateKeyToScalar(key: PrivKey): bigint {\n const { allowedPrivateKeyLengths: lengths, nByteLength, wrapPrivateKey, n } = CURVE;\n if (lengths && typeof key !== 'bigint') {\n if (ut.isBytes(key)) key = ut.bytesToHex(key);\n // Normalize to hex string, pad. E.g. P521 would norm 130-132 char hex to 132-char bytes\n if (typeof key !== 'string' || !lengths.includes(key.length)) throw new Error('Invalid key');\n key = key.padStart(nByteLength * 2, '0');\n }\n let num: bigint;\n try {\n num =\n typeof key === 'bigint'\n ? key\n : ut.bytesToNumberBE(ensureBytes('private key', key, nByteLength));\n } catch (error) {\n throw new Error(`private key must be ${nByteLength} bytes, hex or bigint, not ${typeof key}`);\n }\n if (wrapPrivateKey) num = mod.mod(num, n); // disabled by default, enabled for BLS\n assertGE(num); // num in range [1..N-1]\n return num;\n }\n\n const pointPrecomputes = new Map<Point, Point[]>();\n function assertPrjPoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ProjectivePoint expected');\n }\n /**\n * Projective Point works in 3d / projective (homogeneous) coordinates: (x, y, z) \u220B (x=x/z, y=y/z)\n * Default Point works in 2d / affine coordinates: (x, y)\n * We're doing calculations in projective, because its operations don't require costly inversion.\n */\n class Point implements ProjPointType<T> {\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, Fp.ONE);\n static readonly ZERO = new Point(Fp.ZERO, Fp.ONE, Fp.ZERO);\n\n constructor(\n readonly px: T,\n readonly py: T,\n readonly pz: T\n ) {\n if (px == null || !Fp.isValid(px)) throw new Error('x required');\n if (py == null || !Fp.isValid(py)) throw new Error('y required');\n if (pz == null || !Fp.isValid(pz)) throw new Error('z required');\n }\n\n // Does not validate if the point is on-curve.\n // Use fromHex instead, or call assertValidity() later.\n static fromAffine(p: AffinePoint<T>): Point {\n const { x, y } = p || {};\n if (!p || !Fp.isValid(x) || !Fp.isValid(y)) throw new Error('invalid affine point');\n if (p instanceof Point) throw new Error('projective point not allowed');\n const is0 = (i: T) => Fp.eql(i, Fp.ZERO);\n // fromAffine(x:0, y:0) would produce (x:0, y:0, z:1), but we need (x:0, y:1, z:0)\n if (is0(x) && is0(y)) return Point.ZERO;\n return new Point(x, y, Fp.ONE);\n }\n\n get x(): T {\n return this.toAffine().x;\n }\n get y(): T {\n return this.toAffine().y;\n }\n\n /**\n * Takes a bunch of Projective Points but executes only one\n * inversion on all of them. Inversion is very slow operation,\n * so this improves performance massively.\n * Optimization: converts a list of projective points to a list of identical points with Z=1.\n */\n static normalizeZ(points: Point[]): Point[] {\n const toInv = Fp.invertBatch(points.map((p) => p.pz));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n\n /**\n * Converts hash string or Uint8Array to Point.\n * @param hex short/long ECDSA hex\n */\n static fromHex(hex: Hex): Point {\n const P = Point.fromAffine(fromBytes(ensureBytes('pointHex', hex)));\n P.assertValidity();\n return P;\n }\n\n // Multiplies generator point by privateKey.\n static fromPrivateKey(privateKey: PrivKey) {\n return Point.BASE.multiply(normPrivateKeyToScalar(privateKey));\n }\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n _WINDOW_SIZE?: number;\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n\n // A point on curve is valid if it conforms to equation.\n assertValidity(): void {\n if (this.is0()) {\n // (0, 1, 0) aka ZERO is invalid in most contexts.\n // In BLS, ZERO can be serialized, so we allow it.\n // (0, 0, 0) is wrong representation of ZERO and is always invalid.\n if (CURVE.allowInfinityPoint && !Fp.is0(this.py)) return;\n throw new Error('bad point: ZERO');\n }\n // Some 3rd-party test vectors require different wording between here & `fromCompressedHex`\n const { x, y } = this.toAffine();\n // Check if x, y are valid field elements\n if (!Fp.isValid(x) || !Fp.isValid(y)) throw new Error('bad point: x or y not FE');\n const left = Fp.sqr(y); // y\u00B2\n const right = weierstrassEquation(x); // x\u00B3 + ax + b\n if (!Fp.eql(left, right)) throw new Error('bad point: equation left != right');\n if (!this.isTorsionFree()) throw new Error('bad point: not in prime-order subgroup');\n }\n hasEvenY(): boolean {\n const { y } = this.toAffine();\n if (Fp.isOdd) return !Fp.isOdd(y);\n throw new Error(\"Field doesn't support isOdd\");\n }\n\n /**\n * Compare one point to another.\n */\n equals(other: Point): boolean {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n const U1 = Fp.eql(Fp.mul(X1, Z2), Fp.mul(X2, Z1));\n const U2 = Fp.eql(Fp.mul(Y1, Z2), Fp.mul(Y2, Z1));\n return U1 && U2;\n }\n\n /**\n * Flips point to one corresponding to (x, -y) in Affine coordinates.\n */\n negate(): Point {\n return new Point(this.px, Fp.neg(this.py), this.pz);\n }\n\n // Renes-Costello-Batina exception-free doubling formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 3\n // Cost: 8M + 3S + 3*a + 2*b3 + 15add.\n double() {\n const { a, b } = CURVE;\n const b3 = Fp.mul(b, _3n);\n const { px: X1, py: Y1, pz: Z1 } = this;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n let t0 = Fp.mul(X1, X1); // step 1\n let t1 = Fp.mul(Y1, Y1);\n let t2 = Fp.mul(Z1, Z1);\n let t3 = Fp.mul(X1, Y1);\n t3 = Fp.add(t3, t3); // step 5\n Z3 = Fp.mul(X1, Z1);\n Z3 = Fp.add(Z3, Z3);\n X3 = Fp.mul(a, Z3);\n Y3 = Fp.mul(b3, t2);\n Y3 = Fp.add(X3, Y3); // step 10\n X3 = Fp.sub(t1, Y3);\n Y3 = Fp.add(t1, Y3);\n Y3 = Fp.mul(X3, Y3);\n X3 = Fp.mul(t3, X3);\n Z3 = Fp.mul(b3, Z3); // step 15\n t2 = Fp.mul(a, t2);\n t3 = Fp.sub(t0, t2);\n t3 = Fp.mul(a, t3);\n t3 = Fp.add(t3, Z3);\n Z3 = Fp.add(t0, t0); // step 20\n t0 = Fp.add(Z3, t0);\n t0 = Fp.add(t0, t2);\n t0 = Fp.mul(t0, t3);\n Y3 = Fp.add(Y3, t0);\n t2 = Fp.mul(Y1, Z1); // step 25\n t2 = Fp.add(t2, t2);\n t0 = Fp.mul(t2, t3);\n X3 = Fp.sub(X3, t0);\n Z3 = Fp.mul(t2, t1);\n Z3 = Fp.add(Z3, Z3); // step 30\n Z3 = Fp.add(Z3, Z3);\n return new Point(X3, Y3, Z3);\n }\n\n // Renes-Costello-Batina exception-free addition formula.\n // There is 30% faster Jacobian formula, but it is not complete.\n // https://eprint.iacr.org/2015/1060, algorithm 1\n // Cost: 12M + 0S + 3*a + 3*b3 + 23add.\n add(other: Point): Point {\n assertPrjPoint(other);\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = other;\n let X3 = Fp.ZERO, Y3 = Fp.ZERO, Z3 = Fp.ZERO; // prettier-ignore\n const a = CURVE.a;\n const b3 = Fp.mul(CURVE.b, _3n);\n let t0 = Fp.mul(X1, X2); // step 1\n let t1 = Fp.mul(Y1, Y2);\n let t2 = Fp.mul(Z1, Z2);\n let t3 = Fp.add(X1, Y1);\n let t4 = Fp.add(X2, Y2); // step 5\n t3 = Fp.mul(t3, t4);\n t4 = Fp.add(t0, t1);\n t3 = Fp.sub(t3, t4);\n t4 = Fp.add(X1, Z1);\n let t5 = Fp.add(X2, Z2); // step 10\n t4 = Fp.mul(t4, t5);\n t5 = Fp.add(t0, t2);\n t4 = Fp.sub(t4, t5);\n t5 = Fp.add(Y1, Z1);\n X3 = Fp.add(Y2, Z2); // step 15\n t5 = Fp.mul(t5, X3);\n X3 = Fp.add(t1, t2);\n t5 = Fp.sub(t5, X3);\n Z3 = Fp.mul(a, t4);\n X3 = Fp.mul(b3, t2); // step 20\n Z3 = Fp.add(X3, Z3);\n X3 = Fp.sub(t1, Z3);\n Z3 = Fp.add(t1, Z3);\n Y3 = Fp.mul(X3, Z3);\n t1 = Fp.add(t0, t0); // step 25\n t1 = Fp.add(t1, t0);\n t2 = Fp.mul(a, t2);\n t4 = Fp.mul(b3, t4);\n t1 = Fp.add(t1, t2);\n t2 = Fp.sub(t0, t2); // step 30\n t2 = Fp.mul(a, t2);\n t4 = Fp.add(t4, t2);\n t0 = Fp.mul(t1, t4);\n Y3 = Fp.add(Y3, t0);\n t0 = Fp.mul(t5, t4); // step 35\n X3 = Fp.mul(t3, X3);\n X3 = Fp.sub(X3, t0);\n t0 = Fp.mul(t3, t1);\n Z3 = Fp.mul(t5, Z3);\n Z3 = Fp.add(Z3, t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n\n subtract(other: Point) {\n return this.add(other.negate());\n }\n\n private is0() {\n return this.equals(Point.ZERO);\n }\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, pointPrecomputes, n, (comp: Point[]) => {\n const toInv = Fp.invertBatch(comp.map((p) => p.pz));\n return comp.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n });\n }\n\n /**\n * Non-constant-time multiplication. Uses double-and-add algorithm.\n * It's faster, but should only be used when you don't care about\n * an exposed private key e.g. sig verification, which works over *public* keys.\n */\n multiplyUnsafe(n: bigint): Point {\n const I = Point.ZERO;\n if (n === _0n) return I;\n assertGE(n); // Will throw on 0\n if (n === _1n) return this;\n const { endo } = CURVE;\n if (!endo) return wnaf.unsafeLadder(this, n);\n\n // Apply endomorphism\n let { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let k1p = I;\n let k2p = I;\n let d: Point = this;\n while (k1 > _0n || k2 > _0n) {\n if (k1 & _1n) k1p = k1p.add(d);\n if (k2 & _1n) k2p = k2p.add(d);\n d = d.double();\n k1 >>= _1n;\n k2 >>= _1n;\n }\n if (k1neg) k1p = k1p.negate();\n if (k2neg) k2p = k2p.negate();\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n return k1p.add(k2p);\n }\n\n /**\n * Constant time multiplication.\n * Uses wNAF method. Windowed method may be 10% faster,\n * but takes 2x longer to generate and consumes 2x memory.\n * Uses precomputes when available.\n * Uses endomorphism for Koblitz curves.\n * @param scalar by which the point would be multiplied\n * @returns New point\n */\n multiply(scalar: bigint): Point {\n assertGE(scalar);\n let n = scalar;\n let point: Point, fake: Point; // Fake point is used to const-time mult\n const { endo } = CURVE;\n if (endo) {\n const { k1neg, k1, k2neg, k2 } = endo.splitScalar(n);\n let { p: k1p, f: f1p } = this.wNAF(k1);\n let { p: k2p, f: f2p } = this.wNAF(k2);\n k1p = wnaf.constTimeNegate(k1neg, k1p);\n k2p = wnaf.constTimeNegate(k2neg, k2p);\n k2p = new Point(Fp.mul(k2p.px, endo.beta), k2p.py, k2p.pz);\n point = k1p.add(k2p);\n fake = f1p.add(f2p);\n } else {\n const { p, f } = this.wNAF(n);\n point = p;\n fake = f;\n }\n // Normalize `z` for both points, but return only real one\n return Point.normalizeZ([point, fake])[0];\n }\n\n /**\n * Efficiently calculate `aP + bQ`. Unsafe, can expose private key, if used incorrectly.\n * Not using Strauss-Shamir trick: precomputation tables are faster.\n * The trick could be useful if both P and Q are not G (not in our case).\n * @returns non-zero affine point\n */\n multiplyAndAddUnsafe(Q: Point, a: bigint, b: bigint): Point | undefined {\n const G = Point.BASE; // No Strauss-Shamir trick: we have 10% faster G precomputes\n const mul = (\n P: Point,\n a: bigint // Select faster multiply() method\n ) => (a === _0n || a === _1n || !P.equals(G) ? P.multiplyUnsafe(a) : P.multiply(a));\n const sum = mul(this, a).add(mul(Q, b));\n return sum.is0() ? undefined : sum;\n }\n\n // Converts Projective point to affine (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n // (x, y, z) \u220B (x=x/z, y=y/z)\n toAffine(iz?: T): AffinePoint<T> {\n const { px: x, py: y, pz: z } = this;\n const is0 = this.is0();\n // If invZ was 0, we return zero point. However we still want to execute\n // all operations, so we replace invZ with a random number, 1.\n if (iz == null) iz = is0 ? Fp.ONE : Fp.inv(z);\n const ax = Fp.mul(x, iz);\n const ay = Fp.mul(y, iz);\n const zz = Fp.mul(z, iz);\n if (is0) return { x: Fp.ZERO, y: Fp.ZERO };\n if (!Fp.eql(zz, Fp.ONE)) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n }\n isTorsionFree(): boolean {\n const { h: cofactor, isTorsionFree } = CURVE;\n if (cofactor === _1n) return true; // No subgroups, always torsion-free\n if (isTorsionFree) return isTorsionFree(Point, this);\n throw new Error('isTorsionFree() has not been declared for the elliptic curve');\n }\n clearCofactor(): Point {\n const { h: cofactor, clearCofactor } = CURVE;\n if (cofactor === _1n) return this; // Fast-path\n if (clearCofactor) return clearCofactor(Point, this) as Point;\n return this.multiplyUnsafe(CURVE.h);\n }\n\n toRawBytes(isCompressed = true): Uint8Array {\n this.assertValidity();\n return toBytes(Point, this, isCompressed);\n }\n\n toHex(isCompressed = true): string {\n return ut.bytesToHex(this.toRawBytes(isCompressed));\n }\n }\n const _bits = CURVE.nBitLength;\n const wnaf = wNAF(Point, CURVE.endo ? Math.ceil(_bits / 2) : _bits);\n // Validate if generator point is on curve\n return {\n CURVE,\n ProjectivePoint: Point as ProjConstructor<T>,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n };\n}\n\n// Instance\nexport interface SignatureType {\n readonly r: bigint;\n readonly s: bigint;\n readonly recovery?: number;\n assertValidity(): void;\n addRecoveryBit(recovery: number): RecoveredSignatureType;\n hasHighS(): boolean;\n normalizeS(): SignatureType;\n recoverPublicKey(msgHash: Hex): ProjPointType<bigint>;\n toCompactRawBytes(): Uint8Array;\n toCompactHex(): string;\n // DER-encoded\n toDERRawBytes(isCompressed?: boolean): Uint8Array;\n toDERHex(isCompressed?: boolean): string;\n}\nexport type RecoveredSignatureType = SignatureType & {\n readonly recovery: number;\n};\n// Static methods\nexport type SignatureConstructor = {\n new (r: bigint, s: bigint): SignatureType;\n fromCompact(hex: Hex): SignatureType;\n fromDER(hex: Hex): SignatureType;\n};\ntype SignatureLike = { r: bigint; s: bigint };\n\nexport type PubKey = Hex | ProjPointType<bigint>;\n\nexport type CurveType = BasicWCurve<bigint> & {\n hash: CHash; // CHash not FHash because we need outputLen for DRBG\n hmac: HmacFnSync;\n randomBytes: (bytesLength?: number) => Uint8Array;\n lowS?: boolean;\n bits2int?: (bytes: Uint8Array) => bigint;\n bits2int_modN?: (bytes: Uint8Array) => bigint;\n};\n\nfunction validateOpts(curve: CurveType) {\n const opts = validateBasic(curve);\n ut.validateObject(\n opts,\n {\n hash: 'hash',\n hmac: 'function',\n randomBytes: 'function',\n },\n {\n bits2int: 'function',\n bits2int_modN: 'function',\n lowS: 'boolean',\n }\n );\n return Object.freeze({ lowS: true, ...opts } as const);\n}\n\nexport type CurveFn = {\n CURVE: ReturnType<typeof validateOpts>;\n getPublicKey: (privateKey: PrivKey, isCompressed?: boolean) => Uint8Array;\n getSharedSecret: (privateA: PrivKey, publicB: Hex, isCompressed?: boolean) => Uint8Array;\n sign: (msgHash: Hex, privKey: PrivKey, opts?: SignOpts) => RecoveredSignatureType;\n verify: (signature: Hex | SignatureLike, msgHash: Hex, publicKey: Hex, opts?: VerOpts) => boolean;\n ProjectivePoint: ProjConstructor<bigint>;\n Signature: SignatureConstructor;\n utils: {\n normPrivateKeyToScalar: (key: PrivKey) => bigint;\n isValidPrivateKey(privateKey: PrivKey): boolean;\n randomPrivateKey: () => Uint8Array;\n precompute: (windowSize?: number, point?: ProjPointType<bigint>) => ProjPointType<bigint>;\n };\n};\n\nexport function weierstrass(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType<typeof validateOpts>;\n const { Fp, n: CURVE_ORDER } = CURVE;\n const compressedLen = Fp.BYTES + 1; // e.g. 33 for 32\n const uncompressedLen = 2 * Fp.BYTES + 1; // e.g. 65 for 32\n\n function isValidFieldElement(num: bigint): boolean {\n return _0n < num && num < Fp.ORDER; // 0 is banned since it's not invertible FE\n }\n function modN(a: bigint) {\n return mod.mod(a, CURVE_ORDER);\n }\n function invN(a: bigint) {\n return mod.invert(a, CURVE_ORDER);\n }\n\n const {\n ProjectivePoint: Point,\n normPrivateKeyToScalar,\n weierstrassEquation,\n isWithinCurveOrder,\n } = weierstrassPoints({\n ...CURVE,\n toBytes(_c, point, isCompressed: boolean): Uint8Array {\n const a = point.toAffine();\n const x = Fp.toBytes(a.x);\n const cat = ut.concatBytes;\n if (isCompressed) {\n return cat(Uint8Array.from([point.hasEvenY() ? 0x02 : 0x03]), x);\n } else {\n return cat(Uint8Array.from([0x04]), x, Fp.toBytes(a.y));\n }\n },\n fromBytes(bytes: Uint8Array) {\n const len = bytes.length;\n const head = bytes[0];\n const tail = bytes.subarray(1);\n // this.assertValidity() is done inside of fromHex\n if (len === compressedLen && (head === 0x02 || head === 0x03)) {\n const x = ut.bytesToNumberBE(tail);\n if (!isValidFieldElement(x)) throw new Error('Point is not on curve');\n const y2 = weierstrassEquation(x); // y\u00B2 = x\u00B3 + ax + b\n let y = Fp.sqrt(y2); // y = y\u00B2 ^ (p+1)/4\n const isYOdd = (y & _1n) === _1n;\n // ECDSA\n const isHeadOdd = (head & 1) === 1;\n if (isHeadOdd !== isYOdd) y = Fp.neg(y);\n return { x, y };\n } else if (len === uncompressedLen && head === 0x04) {\n const x = Fp.fromBytes(tail.subarray(0, Fp.BYTES));\n const y = Fp.fromBytes(tail.subarray(Fp.BYTES, 2 * Fp.BYTES));\n return { x, y };\n } else {\n throw new Error(\n `Point of length ${len} was invalid. Expected ${compressedLen} compressed bytes or ${uncompressedLen} uncompressed bytes`\n );\n }\n },\n });\n const numToNByteStr = (num: bigint): string =>\n ut.bytesToHex(ut.numberToBytesBE(num, CURVE.nByteLength));\n\n function isBiggerThanHalfOrder(number: bigint) {\n const HALF = CURVE_ORDER >> _1n;\n return number > HALF;\n }\n\n function normalizeS(s: bigint) {\n return isBiggerThanHalfOrder(s) ? modN(-s) : s;\n }\n // slice bytes num\n const slcNum = (b: Uint8Array, from: number, to: number) => ut.bytesToNumberBE(b.slice(from, to));\n\n /**\n * ECDSA signature with its (r, s) properties. Supports DER & compact representations.\n */\n class Signature implements SignatureType {\n constructor(\n readonly r: bigint,\n readonly s: bigint,\n readonly recovery?: number\n ) {\n this.assertValidity();\n }\n\n // pair (bytes of r, bytes of s)\n static fromCompact(hex: Hex) {\n const l = CURVE.nByteLength;\n hex = ensureBytes('compactSignature', hex, l * 2);\n return new Signature(slcNum(hex, 0, l), slcNum(hex, l, 2 * l));\n }\n\n // DER encoded ECDSA signature\n // https://bitcoin.stackexchange.com/questions/57644/what-are-the-parts-of-a-bitcoin-transaction-input-script\n static fromDER(hex: Hex) {\n const { r, s } = DER.toSig(ensureBytes('DER', hex));\n return new Signature(r, s);\n }\n\n assertValidity(): void {\n // can use assertGE here\n if (!isWithinCurveOrder(this.r)) throw new Error('r must be 0 < r < CURVE.n');\n if (!isWithinCurveOrder(this.s)) throw new Error('s must be 0 < s < CURVE.n');\n }\n\n addRecoveryBit(recovery: number): RecoveredSignature {\n return new Signature(this.r, this.s, recovery) as RecoveredSignature;\n }\n\n recoverPublicKey(msgHash: Hex): typeof Point.BASE {\n const { r, s, recovery: rec } = this;\n const h = bits2int_modN(ensureBytes('msgHash', msgHash)); // Truncate hash\n if (rec == null || ![0, 1, 2, 3].includes(rec)) throw new Error('recovery id invalid');\n const radj = rec === 2 || rec === 3 ? r + CURVE.n : r;\n if (radj >= Fp.ORDER) throw new Error('recovery id 2 or 3 invalid');\n const prefix = (rec & 1) === 0 ? '02' : '03';\n const R = Point.fromHex(prefix + numToNByteStr(radj));\n const ir = invN(radj); // r^-1\n const u1 = modN(-h * ir); // -hr^-1\n const u2 = modN(s * ir); // sr^-1\n const Q = Point.BASE.multiplyAndAddUnsafe(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n if (!Q) throw new Error('point at infinify'); // unsafe is fine: no priv data leaked\n Q.assertValidity();\n return Q;\n }\n\n // Signatures should be low-s, to prevent malleability.\n hasHighS(): boolean {\n return isBiggerThanHalfOrder(this.s);\n }\n\n normalizeS() {\n return this.hasHighS() ? new Signature(this.r, modN(-this.s), this.recovery) : this;\n }\n\n // DER-encoded\n toDERRawBytes() {\n return ut.hexToBytes(this.toDERHex());\n }\n toDERHex() {\n return DER.hexFromSig({ r: this.r, s: this.s });\n }\n\n // padded bytes of r, then padded bytes of s\n toCompactRawBytes() {\n return ut.hexToBytes(this.toCompactHex());\n }\n toCompactHex() {\n return numToNByteStr(this.r) + numToNByteStr(this.s);\n }\n }\n type RecoveredSignature = Signature & { recovery: number };\n\n const utils = {\n isValidPrivateKey(privateKey: PrivKey) {\n try {\n normPrivateKeyToScalar(privateKey);\n return true;\n } catch (error) {\n return false;\n }\n },\n normPrivateKeyToScalar: normPrivateKeyToScalar,\n\n /**\n * Produces cryptographically secure private key from random of size\n * (groupLen + ceil(groupLen / 2)) with modulo bias being negligible.\n */\n randomPrivateKey: (): Uint8Array => {\n const length = mod.getMinHashLength(CURVE.n);\n return mod.mapHashToField(CURVE.randomBytes(length), CURVE.n);\n },\n\n /**\n * Creates precompute table for an arbitrary EC point. Makes point \"cached\".\n * Allows to massively speed-up `point.multiply(scalar)`.\n * @returns cached point\n * @example\n * const fast = utils.precompute(8, ProjectivePoint.fromHex(someonesPubKey));\n * fast.multiply(privKey); // much faster ECDH now\n */\n precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3)); // 3 is arbitrary, just need any number here\n return point;\n },\n };\n\n /**\n * Computes public key for a private key. Checks for validity of the private key.\n * @param privateKey private key\n * @param isCompressed whether to return compact (default), or full key\n * @returns Public key, full when isCompressed=false; short when isCompressed=true\n */\n function getPublicKey(privateKey: PrivKey, isCompressed = true): Uint8Array {\n return Point.fromPrivateKey(privateKey).toRawBytes(isCompressed);\n }\n\n /**\n * Quick and dirty check for item being public key. Does not validate hex, or being on-curve.\n */\n function isProbPub(item: PrivKey | PubKey): boolean {\n const arr = ut.isBytes(item);\n const str = typeof item === 'string';\n const len = (arr || str) && (item as Hex).length;\n if (arr) return len === compressedLen || len === uncompressedLen;\n if (str) return len === 2 * compressedLen || len === 2 * uncompressedLen;\n if (item instanceof Point) return true;\n return false;\n }\n\n /**\n * ECDH (Elliptic Curve Diffie Hellman).\n * Computes shared public key from private key and public key.\n * Checks: 1) private key validity 2) shared key is on-curve.\n * Does NOT hash the result.\n * @param privateA private key\n * @param publicB different public key\n * @param isCompressed whether to return compact (default), or full key\n * @returns shared public key\n */\n function getSharedSecret(privateA: PrivKey, publicB: Hex, isCompressed = true): Uint8Array {\n if (isProbPub(privateA)) throw new Error('first arg must be private key');\n if (!isProbPub(publicB)) throw new Error('second arg must be public key');\n const b = Point.fromHex(publicB); // check for being on-curve\n return b.multiply(normPrivateKeyToScalar(privateA)).toRawBytes(isCompressed);\n }\n\n // RFC6979: ensure ECDSA msg is X bytes and < N. RFC suggests optional truncating via bits2octets.\n // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which matches bits2int.\n // bits2int can produce res>N, we can do mod(res, N) since the bitLen is the same.\n // int2octets can't be used; pads small msgs with 0: unacceptatble for trunc as per RFC vectors\n const bits2int =\n CURVE.bits2int ||\n function (bytes: Uint8Array): bigint {\n // For curves with nBitLength % 8 !== 0: bits2octets(bits2octets(m)) !== bits2octets(m)\n // for some cases, since bytes.length * 8 is not actual bitLength.\n const num = ut.bytesToNumberBE(bytes); // check for == u8 done here\n const delta = bytes.length * 8 - CURVE.nBitLength; // truncate to nBitLength leftmost bits\n return delta > 0 ? num >> BigInt(delta) : num;\n };\n const bits2int_modN =\n CURVE.bits2int_modN ||\n function (bytes: Uint8Array): bigint {\n return modN(bits2int(bytes)); // can't use bytesToNumberBE here\n };\n // NOTE: pads output with zero as per spec\n const ORDER_MASK = ut.bitMask(CURVE.nBitLength);\n /**\n * Converts to bytes. Checks if num in `[0..ORDER_MASK-1]` e.g.: `[0..2^256-1]`.\n */\n function int2octets(num: bigint): Uint8Array {\n if (typeof num !== 'bigint') throw new Error('bigint expected');\n if (!(_0n <= num && num < ORDER_MASK))\n throw new Error(`bigint expected < 2^${CURVE.nBitLength}`);\n // works with order, can have different size than numToField!\n return ut.numberToBytesBE(num, CURVE.nByteLength);\n }\n\n // Steps A, D of RFC6979 3.2\n // Creates RFC6979 seed; converts msg/privKey to numbers.\n // Used only in sign, not in verify.\n // NOTE: we cannot assume here that msgHash has same amount of bytes as curve order, this will be wrong at least for P521.\n // Also it can be bigger for P224 + SHA256\n function prepSig(msgHash: Hex, privateKey: PrivKey, opts = defaultSigOpts) {\n if (['recovered', 'canonical'].some((k) => k in opts))\n throw new Error('sign() legacy options not supported');\n const { hash, randomBytes } = CURVE;\n let { lowS, prehash, extraEntropy: ent } = opts; // generates low-s sigs by default\n if (lowS == null) lowS = true; // RFC6979 3.2: we skip step A, because we already provide hash\n msgHash = ensureBytes('msgHash', msgHash);\n if (prehash) msgHash = ensureBytes('prehashed msgHash', hash(msgHash));\n\n // We can't later call bits2octets, since nested bits2int is broken for curves\n // with nBitLength % 8 !== 0. Because of that, we unwrap it here as int2octets call.\n // const bits2octets = (bits) => int2octets(bits2int_modN(bits))\n const h1int = bits2int_modN(msgHash);\n const d = normPrivateKeyToScalar(privateKey); // validate private key, convert to bigint\n const seedArgs = [int2octets(d), int2octets(h1int)];\n // extraEntropy. RFC6979 3.6: additional k' (optional).\n if (ent != null) {\n // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n const e = ent === true ? randomBytes(Fp.BYTES) : ent; // generate random bytes OR pass as-is\n seedArgs.push(ensureBytes('extraEntropy', e)); // check for being bytes\n }\n const seed = ut.concatBytes(...seedArgs); // Step D of RFC6979 3.2\n const m = h1int; // NOTE: no need to call bits2int second time here, it is inside truncateHash!\n // Converts signature params into point w r/s, checks result for validity.\n function k2sig(kBytes: Uint8Array): RecoveredSignature | undefined {\n // RFC 6979 Section 3.2, step 3: k = bits2int(T)\n const k = bits2int(kBytes); // Cannot use fields methods, since it is group element\n if (!isWithinCurveOrder(k)) return; // Important: all mod() calls here must be done over N\n const ik = invN(k); // k^-1 mod n\n const q = Point.BASE.multiply(k).toAffine(); // q = Gk\n const r = modN(q.x); // r = q.x mod n\n if (r === _0n) return;\n // Can use scalar blinding b^-1(bm + bdr) where b \u2208 [1,q\u22121] according to\n // https://tches.iacr.org/index.php/TCHES/article/view/7337/6509. We've decided against it:\n // a) dependency on CSPRNG b) 15% slowdown c) doesn't really help since bigints are not CT\n const s = modN(ik * modN(m + r * d)); // Not using blinding here\n if (s === _0n) return;\n let recovery = (q.x === r ? 0 : 2) | Number(q.y & _1n); // recovery bit (2 or 3, when q.x > n)\n let normS = s;\n if (lowS && isBiggerThanHalfOrder(s)) {\n normS = normalizeS(s); // if lowS was passed, ensure s is always\n recovery ^= 1; // // in the bottom half of N\n }\n return new Signature(r, normS, recovery) as RecoveredSignature; // use normS, not s\n }\n return { seed, k2sig };\n }\n const defaultSigOpts: SignOpts = { lowS: CURVE.lowS, prehash: false };\n const defaultVerOpts: VerOpts = { lowS: CURVE.lowS, prehash: false };\n\n /**\n * Signs message hash with a private key.\n * ```\n * sign(m, d, k) where\n * (x, y) = G \u00D7 k\n * r = x mod n\n * s = (m + dr)/k mod n\n * ```\n * @param msgHash NOT message. msg needs to be hashed to `msgHash`, or use `prehash`.\n * @param privKey private key\n * @param opts lowS for non-malleable sigs. extraEntropy for mixing randomness into k. prehash will hash first arg.\n * @returns signature with recovery param\n */\n function sign(msgHash: Hex, privKey: PrivKey, opts = defaultSigOpts): RecoveredSignature {\n const { seed, k2sig } = prepSig(msgHash, privKey, opts); // Steps A, D of RFC6979 3.2.\n const C = CURVE;\n const drbg = ut.createHmacDrbg<RecoveredSignature>(C.hash.outputLen, C.nByteLength, C.hmac);\n return drbg(seed, k2sig); // Steps B, C, D, E, F, G\n }\n\n // Enable precomputes. Slows down first publicKey computation by 20ms.\n Point.BASE._setWindowSize(8);\n // utils.precompute(8, ProjectivePoint.BASE)\n\n /**\n * Verifies a signature against message hash and public key.\n * Rejects lowS signatures by default: to override,\n * specify option `{lowS: false}`. Implements section 4.1.4 from https://www.secg.org/sec1-v2.pdf:\n *\n * ```\n * verify(r, s, h, P) where\n * U1 = hs^-1 mod n\n * U2 = rs^-1 mod n\n * R = U1\u22C5G - U2\u22C5P\n * mod(R.x, n) == r\n * ```\n */\n function verify(\n signature: Hex | SignatureLike,\n msgHash: Hex,\n publicKey: Hex,\n opts = defaultVerOpts\n ): boolean {\n const sg = signature;\n msgHash = ensureBytes('msgHash', msgHash);\n publicKey = ensureBytes('publicKey', publicKey);\n if ('strict' in opts) throw new Error('options.strict was renamed to lowS');\n const { lowS, prehash } = opts;\n\n let _sig: Signature | undefined = undefined;\n let P: ProjPointType<bigint>;\n try {\n if (typeof sg === 'string' || ut.isBytes(sg)) {\n // Signature can be represented in 2 ways: compact (2*nByteLength) & DER (variable-length).\n // Since DER can also be 2*nByteLength bytes, we check for it first.\n try {\n _sig = Signature.fromDER(sg);\n } catch (derError) {\n if (!(derError instanceof DER.Err)) throw derError;\n _sig = Signature.fromCompact(sg);\n }\n } else if (typeof sg === 'object' && typeof sg.r === 'bigint' && typeof sg.s === 'bigint') {\n const { r, s } = sg;\n _sig = new Signature(r, s);\n } else {\n throw new Error('PARSE');\n }\n P = Point.fromHex(publicKey);\n } catch (error) {\n if ((error as Error).message === 'PARSE')\n throw new Error(`signature must be Signature instance, Uint8Array or hex string`);\n return false;\n }\n if (lowS && _sig.hasHighS()) return false;\n if (prehash) msgHash = CURVE.hash(msgHash);\n const { r, s } = _sig;\n const h = bits2int_modN(msgHash); // Cannot use fields methods, since it is group element\n const is = invN(s); // s^-1\n const u1 = modN(h * is); // u1 = hs^-1 mod n\n const u2 = modN(r * is); // u2 = rs^-1 mod n\n const R = Point.BASE.multiplyAndAddUnsafe(P, u1, u2)?.toAffine(); // R = u1\u22C5G + u2\u22C5P\n if (!R) return false;\n const v = modN(R.x);\n return v === r;\n }\n return {\n CURVE,\n getPublicKey,\n getSharedSecret,\n sign,\n verify,\n ProjectivePoint: Point,\n Signature,\n utils,\n };\n}\n\n/**\n * Implementation of the Shallue and van de Woestijne method for any weierstrass curve.\n * TODO: check if there is a way to merge this with uvRatio in Edwards; move to modular.\n * b = True and y = sqrt(u / v) if (u / v) is square in F, and\n * b = False and y = sqrt(Z * (u / v)) otherwise.\n * @param Fp\n * @param Z\n * @returns\n */\nexport function SWUFpSqrtRatio<T>(Fp: mod.IField<T>, Z: T) {\n // Generic implementation\n const q = Fp.ORDER;\n let l = _0n;\n for (let o = q - _1n; o % _2n === _0n; o /= _2n) l += _1n;\n const c1 = l; // 1. c1, the largest integer such that 2^c1 divides q - 1.\n // We need 2n ** c1 and 2n ** (c1-1). We can't use **; but we can use <<.\n // 2n ** c1 == 2n << (c1-1)\n const _2n_pow_c1_1 = _2n << (c1 - _1n - _1n);\n const _2n_pow_c1 = _2n_pow_c1_1 * _2n;\n const c2 = (q - _1n) / _2n_pow_c1; // 2. c2 = (q - 1) / (2^c1) # Integer arithmetic\n const c3 = (c2 - _1n) / _2n; // 3. c3 = (c2 - 1) / 2 # Integer arithmetic\n const c4 = _2n_pow_c1 - _1n; // 4. c4 = 2^c1 - 1 # Integer arithmetic\n const c5 = _2n_pow_c1_1; // 5. c5 = 2^(c1 - 1) # Integer arithmetic\n const c6 = Fp.pow(Z, c2); // 6. c6 = Z^c2\n const c7 = Fp.pow(Z, (c2 + _1n) / _2n); // 7. c7 = Z^((c2 + 1) / 2)\n let sqrtRatio = (u: T, v: T): { isValid: boolean; value: T } => {\n let tv1 = c6; // 1. tv1 = c6\n let tv2 = Fp.pow(v, c4); // 2. tv2 = v^c4\n let tv3 = Fp.sqr(tv2); // 3. tv3 = tv2^2\n tv3 = Fp.mul(tv3, v); // 4. tv3 = tv3 * v\n let tv5 = Fp.mul(u, tv3); // 5. tv5 = u * tv3\n tv5 = Fp.pow(tv5, c3); // 6. tv5 = tv5^c3\n tv5 = Fp.mul(tv5, tv2); // 7. tv5 = tv5 * tv2\n tv2 = Fp.mul(tv5, v); // 8. tv2 = tv5 * v\n tv3 = Fp.mul(tv5, u); // 9. tv3 = tv5 * u\n let tv4 = Fp.mul(tv3, tv2); // 10. tv4 = tv3 * tv2\n tv5 = Fp.pow(tv4, c5); // 11. tv5 = tv4^c5\n let isQR = Fp.eql(tv5, Fp.ONE); // 12. isQR = tv5 == 1\n tv2 = Fp.mul(tv3, c7); // 13. tv2 = tv3 * c7\n tv5 = Fp.mul(tv4, tv1); // 14. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, isQR); // 15. tv3 = CMOV(tv2, tv3, isQR)\n tv4 = Fp.cmov(tv5, tv4, isQR); // 16. tv4 = CMOV(tv5, tv4, isQR)\n // 17. for i in (c1, c1 - 1, ..., 2):\n for (let i = c1; i > _1n; i--) {\n let tv5 = i - _2n; // 18. tv5 = i - 2\n tv5 = _2n << (tv5 - _1n); // 19. tv5 = 2^tv5\n let tvv5 = Fp.pow(tv4, tv5); // 20. tv5 = tv4^tv5\n const e1 = Fp.eql(tvv5, Fp.ONE); // 21. e1 = tv5 == 1\n tv2 = Fp.mul(tv3, tv1); // 22. tv2 = tv3 * tv1\n tv1 = Fp.mul(tv1, tv1); // 23. tv1 = tv1 * tv1\n tvv5 = Fp.mul(tv4, tv1); // 24. tv5 = tv4 * tv1\n tv3 = Fp.cmov(tv2, tv3, e1); // 25. tv3 = CMOV(tv2, tv3, e1)\n tv4 = Fp.cmov(tvv5, tv4, e1); // 26. tv4 = CMOV(tv5, tv4, e1)\n }\n return { isValid: isQR, value: tv3 };\n };\n if (Fp.ORDER % _4n === _3n) {\n // sqrt_ratio_3mod4(u, v)\n const c1 = (Fp.ORDER - _3n) / _4n; // 1. c1 = (q - 3) / 4 # Integer arithmetic\n const c2 = Fp.sqrt(Fp.neg(Z)); // 2. c2 = sqrt(-Z)\n sqrtRatio = (u: T, v: T) => {\n let tv1 = Fp.sqr(v); // 1. tv1 = v^2\n const tv2 = Fp.mul(u, v); // 2. tv2 = u * v\n tv1 = Fp.mul(tv1, tv2); // 3. tv1 = tv1 * tv2\n let y1 = Fp.pow(tv1, c1); // 4. y1 = tv1^c1\n y1 = Fp.mul(y1, tv2); // 5. y1 = y1 * tv2\n const y2 = Fp.mul(y1, c2); // 6. y2 = y1 * c2\n const tv3 = Fp.mul(Fp.sqr(y1), v); // 7. tv3 = y1^2; 8. tv3 = tv3 * v\n const isQR = Fp.eql(tv3, u); // 9. isQR = tv3 == u\n let y = Fp.cmov(y2, y1, isQR); // 10. y = CMOV(y2, y1, isQR)\n return { isValid: isQR, value: y }; // 11. return (isQR, y) isQR ? y : y*c2\n };\n }\n // No curves uses that\n // if (Fp.ORDER % _8n === _5n) // sqrt_ratio_5mod8\n return sqrtRatio;\n}\n/**\n * Simplified Shallue-van de Woestijne-Ulas Method\n * https://www.rfc-editor.org/rfc/rfc9380#section-6.6.2\n */\nexport function mapToCurveSimpleSWU<T>(\n Fp: mod.IField<T>,\n opts: {\n A: T;\n B: T;\n Z: T;\n }\n) {\n mod.validateField(Fp);\n if (!Fp.isValid(opts.A) || !Fp.isValid(opts.B) || !Fp.isValid(opts.Z))\n throw new Error('mapToCurveSimpleSWU: invalid opts');\n const sqrtRatio = SWUFpSqrtRatio(Fp, opts.Z);\n if (!Fp.isOdd) throw new Error('Fp.isOdd is not implemented!');\n // Input: u, an element of F.\n // Output: (x, y), a point on E.\n return (u: T): { x: T; y: T } => {\n // prettier-ignore\n let tv1, tv2, tv3, tv4, tv5, tv6, x, y;\n tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, opts.Z); // 2. tv1 = Z * tv1\n tv2 = Fp.sqr(tv1); // 3. tv2 = tv1^2\n tv2 = Fp.add(tv2, tv1); // 4. tv2 = tv2 + tv1\n tv3 = Fp.add(tv2, Fp.ONE); // 5. tv3 = tv2 + 1\n tv3 = Fp.mul(tv3, opts.B); // 6. tv3 = B * tv3\n tv4 = Fp.cmov(opts.Z, Fp.neg(tv2), !Fp.eql(tv2, Fp.ZERO)); // 7. tv4 = CMOV(Z, -tv2, tv2 != 0)\n tv4 = Fp.mul(tv4, opts.A); // 8. tv4 = A * tv4\n tv2 = Fp.sqr(tv3); // 9. tv2 = tv3^2\n tv6 = Fp.sqr(tv4); // 10. tv6 = tv4^2\n tv5 = Fp.mul(tv6, opts.A); // 11. tv5 = A * tv6\n tv2 = Fp.add(tv2, tv5); // 12. tv2 = tv2 + tv5\n tv2 = Fp.mul(tv2, tv3); // 13. tv2 = tv2 * tv3\n tv6 = Fp.mul(tv6, tv4); // 14. tv6 = tv6 * tv4\n tv5 = Fp.mul(tv6, opts.B); // 15. tv5 = B * tv6\n tv2 = Fp.add(tv2, tv5); // 16. tv2 = tv2 + tv5\n x = Fp.mul(tv1, tv3); // 17. x = tv1 * tv3\n const { isValid, value } = sqrtRatio(tv2, tv6); // 18. (is_gx1_square, y1) = sqrt_ratio(tv2, tv6)\n y = Fp.mul(tv1, u); // 19. y = tv1 * u -> Z * u^3 * y1\n y = Fp.mul(y, value); // 20. y = y * y1\n x = Fp.cmov(x, tv3, isValid); // 21. x = CMOV(x, tv3, is_gx1_square)\n y = Fp.cmov(y, value, isValid); // 22. y = CMOV(y, y1, is_gx1_square)\n const e1 = Fp.isOdd!(u) === Fp.isOdd!(y); // 23. e1 = sgn0(u) == sgn0(y)\n y = Fp.cmov(Fp.neg(y), y, e1); // 24. y = CMOV(-y, y, e1)\n x = Fp.div(x, tv4); // 25. x = x / tv4\n return { x, y };\n };\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Abelian group utilities\nimport { IField, validateField, nLength } from './modular.js';\nimport { validateObject } from './utils.js';\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\n\nexport type AffinePoint<T> = {\n x: T;\n y: T;\n} & { z?: never; t?: never };\n\nexport interface Group<T extends Group<T>> {\n double(): T;\n negate(): T;\n add(other: T): T;\n subtract(other: T): T;\n equals(other: T): boolean;\n multiply(scalar: bigint): T;\n}\n\nexport type GroupConstructor<T> = {\n BASE: T;\n ZERO: T;\n};\nexport type Mapper<T> = (i: T[]) => T[];\n\n// Elliptic curve multiplication of Point by scalar. Fragile.\n// Scalars should always be less than curve order: this should be checked inside of a curve itself.\n// Creates precomputation tables for fast multiplication:\n// - private scalar is split by fixed size windows of W bits\n// - every window point is collected from window's table & added to accumulator\n// - since windows are different, same point inside tables won't be accessed more than once per calc\n// - each multiplication is 'Math.ceil(CURVE_ORDER / \uD835\uDC4A) + 1' point additions (fixed for any scalar)\n// - +1 window is neccessary for wNAF\n// - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication\n// TODO: Research returning 2d JS array of windows, instead of a single window. This would allow\n// windows to be in different memory locations\nexport function wNAF<T extends Group<T>>(c: GroupConstructor<T>, bits: number) {\n const constTimeNegate = (condition: boolean, item: T): T => {\n const neg = item.negate();\n return condition ? neg : item;\n };\n const opts = (W: number) => {\n const windows = Math.ceil(bits / W) + 1; // +1, because\n const windowSize = 2 ** (W - 1); // -1 because we skip zero\n return { windows, windowSize };\n };\n return {\n constTimeNegate,\n // non-const time multiplication ladder\n unsafeLadder(elm: T, n: bigint) {\n let p = c.ZERO;\n let d: T = elm;\n while (n > _0n) {\n if (n & _1n) p = p.add(d);\n d = d.double();\n n >>= _1n;\n }\n return p;\n },\n\n /**\n * Creates a wNAF precomputation window. Used for caching.\n * Default window size is set by `utils.precompute()` and is equal to 8.\n * Number of precomputed points depends on the curve size:\n * 2^(\uD835\uDC4A\u22121) * (Math.ceil(\uD835\uDC5B / \uD835\uDC4A) + 1), where:\n * - \uD835\uDC4A is the window size\n * - \uD835\uDC5B is the bitlength of the curve order.\n * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.\n * @returns precomputed point tables flattened to a single array\n */\n precomputeWindow(elm: T, W: number): Group<T>[] {\n const { windows, windowSize } = opts(W);\n const points: T[] = [];\n let p: T = elm;\n let base = p;\n for (let window = 0; window < windows; window++) {\n base = p;\n points.push(base);\n // =1, because we skip zero\n for (let i = 1; i < windowSize; i++) {\n base = base.add(p);\n points.push(base);\n }\n p = base.double();\n }\n return points;\n },\n\n /**\n * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.\n * @param W window size\n * @param precomputes precomputed tables\n * @param n scalar (we don't check here, but should be less than curve order)\n * @returns real and fake (for const-time) points\n */\n wNAF(W: number, precomputes: T[], n: bigint): { p: T; f: T } {\n // TODO: maybe check that scalar is less than group order? wNAF behavious is undefined otherwise\n // But need to carefully remove other checks before wNAF. ORDER == bits here\n const { windows, windowSize } = opts(W);\n\n let p = c.ZERO;\n let f = c.BASE;\n\n const mask = BigInt(2 ** W - 1); // Create mask with W ones: 0b1111 for W=4 etc.\n const maxNumber = 2 ** W;\n const shiftBy = BigInt(W);\n\n for (let window = 0; window < windows; window++) {\n const offset = window * windowSize;\n // Extract W bits.\n let wbits = Number(n & mask);\n\n // Shift number by W bits.\n n >>= shiftBy;\n\n // If the bits are bigger than max size, we'll split those.\n // +224 => 256 - 32\n if (wbits > windowSize) {\n wbits -= maxNumber;\n n += _1n;\n }\n\n // This code was first written with assumption that 'f' and 'p' will never be infinity point:\n // since each addition is multiplied by 2 ** W, it cannot cancel each other. However,\n // there is negate now: it is possible that negated element from low value\n // would be the same as high element, which will create carry into next window.\n // It's not obvious how this can fail, but still worth investigating later.\n\n // Check if we're onto Zero point.\n // Add random point inside current window to f.\n const offset1 = offset;\n const offset2 = offset + Math.abs(wbits) - 1; // -1 because we skip zero\n const cond1 = window % 2 !== 0;\n const cond2 = wbits < 0;\n if (wbits === 0) {\n // The most important part for const-time getPublicKey\n f = f.add(constTimeNegate(cond1, precomputes[offset1]));\n } else {\n p = p.add(constTimeNegate(cond2, precomputes[offset2]));\n }\n }\n // JIT-compiler should not eliminate f here, since it will later be used in normalizeZ()\n // Even if the variable is still unused, there are some checks which will\n // throw an exception, so compiler needs to prove they won't happen, which is hard.\n // At this point there is a way to F be infinity-point even if p is not,\n // which makes it less const-time: around 1 bigint multiply.\n return { p, f };\n },\n\n wNAFCached(P: T, precomputesMap: Map<T, T[]>, n: bigint, transform: Mapper<T>): { p: T; f: T } {\n // @ts-ignore\n const W: number = P._WINDOW_SIZE || 1;\n // Calculate precomputes on a first run, reuse them after\n let comp = precomputesMap.get(P);\n if (!comp) {\n comp = this.precomputeWindow(P, W) as T[];\n if (W !== 1) {\n precomputesMap.set(P, transform(comp));\n }\n }\n return this.wNAF(W, comp, n);\n },\n };\n}\n\n// Generic BasicCurve interface: works even for polynomial fields (BLS): P, n, h would be ok.\n// Though generator can be different (Fp2 / Fp6 for BLS).\nexport type BasicCurve<T> = {\n Fp: IField<T>; // Field over which we'll do calculations (Fp)\n n: bigint; // Curve order, total count of valid points in the field\n nBitLength?: number; // bit length of curve order\n nByteLength?: number; // byte length of curve order\n h: bigint; // cofactor. we can assign default=1, but users will just ignore it w/o validation\n hEff?: bigint; // Number to multiply to clear cofactor\n Gx: T; // base point X coordinate\n Gy: T; // base point Y coordinate\n allowInfinityPoint?: boolean; // bls12-381 requires it. ZERO point is valid, but invalid pubkey\n};\n\nexport function validateBasic<FP, T>(curve: BasicCurve<FP> & T) {\n validateField(curve.Fp);\n validateObject(\n curve,\n {\n n: 'bigint',\n h: 'bigint',\n Gx: 'field',\n Gy: 'field',\n },\n {\n nBitLength: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n }\n );\n // Set defaults\n return Object.freeze({\n ...nLength(curve.n, curve.nBitLength),\n ...curve,\n ...{ p: curve.Fp.ORDER },\n } as const);\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { hmac } from '@noble/hashes/hmac';\nimport { concatBytes, randomBytes } from '@noble/hashes/utils';\nimport { weierstrass, CurveType } from './abstract/weierstrass.js';\nimport { CHash } from './abstract/utils.js';\n\n// connects noble-curves to noble-hashes\nexport function getHash(hash: CHash) {\n return {\n hash,\n hmac: (key: Uint8Array, ...msgs: Uint8Array[]) => hmac(hash, key, concatBytes(...msgs)),\n randomBytes,\n };\n}\n// Same API as @noble/hashes, with ability to create curve with custom hash\ntype CurveDef = Readonly<Omit<CurveType, 'hash' | 'hmac' | 'randomBytes'>>;\nexport function createCurve(curveDef: CurveDef, defHash: CHash) {\n const create = (hash: CHash) => weierstrass({ ...curveDef, ...getHash(hash) });\n return Object.freeze({ ...create(defHash), create });\n}\n", "import { hash as assertHash, bytes as assertBytes, exists as assertExists } from './_assert.js';\nimport { Hash, CHash, Input, toBytes } from './utils.js';\n// HMAC (RFC 2104)\nexport class HMAC<T extends Hash<T>> extends Hash<HMAC<T>> {\n oHash: T;\n iHash: T;\n blockLen: number;\n outputLen: number;\n private finished = false;\n private destroyed = false;\n\n constructor(hash: CHash, _key: Input) {\n super();\n assertHash(hash);\n const key = toBytes(_key);\n this.iHash = hash.create() as T;\n if (typeof this.iHash.update !== 'function')\n throw new Error('Expected instance of class which extends utils.Hash');\n this.blockLen = this.iHash.blockLen;\n this.outputLen = this.iHash.outputLen;\n const blockLen = this.blockLen;\n const pad = new Uint8Array(blockLen);\n // blockLen can be bigger than outputLen\n pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36;\n this.iHash.update(pad);\n // By doing update (processing of first block) of outer hash here we can re-use it between multiple calls via clone\n this.oHash = hash.create() as T;\n // Undo internal XOR && apply outer XOR\n for (let i = 0; i < pad.length; i++) pad[i] ^= 0x36 ^ 0x5c;\n this.oHash.update(pad);\n pad.fill(0);\n }\n update(buf: Input) {\n assertExists(this);\n this.iHash.update(buf);\n return this;\n }\n digestInto(out: Uint8Array) {\n assertExists(this);\n assertBytes(out, this.outputLen);\n this.finished = true;\n this.iHash.digestInto(out);\n this.oHash.update(out);\n this.oHash.digestInto(out);\n this.destroy();\n }\n digest() {\n const out = new Uint8Array(this.oHash.outputLen);\n this.digestInto(out);\n return out;\n }\n _cloneInto(to?: HMAC<T>): HMAC<T> {\n // Create new instance without calling constructor since key already in state and we don't know it.\n to ||= Object.create(Object.getPrototypeOf(this), {});\n const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;\n to = to as this;\n to.finished = finished;\n to.destroyed = destroyed;\n to.blockLen = blockLen;\n to.outputLen = outputLen;\n to.oHash = oHash._cloneInto(to.oHash);\n to.iHash = iHash._cloneInto(to.iHash);\n return to;\n }\n destroy() {\n this.destroyed = true;\n this.oHash.destroy();\n this.iHash.destroy();\n }\n}\n\n/**\n * HMAC: RFC2104 message authentication code.\n * @param hash - function that would be used e.g. sha256\n * @param key - message key\n * @param message - message data\n */\nexport const hmac = (hash: CHash, key: Input, message: Input): Uint8Array =>\n new HMAC<any>(hash, key).update(message).digest();\nhmac.create = (hash: CHash, key: Input) => new HMAC<any>(hash, key);\n", "import { HashMD, Chi, Maj } from './_md.js';\nimport { rotr, wrapConstructor } from './utils.js';\n\n// SHA2-256 need to try 2^128 hashes to execute birthday attack.\n// BTC network is doing 2^67 hashes/sec as per early 2023.\n\n// Round constants:\n// first 32 bits of the fractional parts of the cube roots of the first 64 primes 2..311)\n// prettier-ignore\nconst SHA256_K = /* @__PURE__ */ new Uint32Array([\n 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,\n 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,\n 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,\n 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,\n 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,\n 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,\n 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,\n 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2\n]);\n\n// Initial state:\n// first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19\n// prettier-ignore\nconst SHA256_IV = /* @__PURE__ */ new Uint32Array([\n 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n]);\n\n// Temporary buffer, not used to store anything between runs\n// Named this way because it matches specification.\nconst SHA256_W = /* @__PURE__ */ new Uint32Array(64);\nclass SHA256 extends HashMD<SHA256> {\n // We cannot use array here since array allows indexing by variable\n // which means optimizer/compiler cannot use registers.\n A = SHA256_IV[0] | 0;\n B = SHA256_IV[1] | 0;\n C = SHA256_IV[2] | 0;\n D = SHA256_IV[3] | 0;\n E = SHA256_IV[4] | 0;\n F = SHA256_IV[5] | 0;\n G = SHA256_IV[6] | 0;\n H = SHA256_IV[7] | 0;\n\n constructor() {\n super(64, 32, 8, false);\n }\n protected get(): [number, number, number, number, number, number, number, number] {\n const { A, B, C, D, E, F, G, H } = this;\n return [A, B, C, D, E, F, G, H];\n }\n // prettier-ignore\n protected set(\n A: number, B: number, C: number, D: number, E: number, F: number, G: number, H: number\n ) {\n this.A = A | 0;\n this.B = B | 0;\n this.C = C | 0;\n this.D = D | 0;\n this.E = E | 0;\n this.F = F | 0;\n this.G = G | 0;\n this.H = H | 0;\n }\n protected process(view: DataView, offset: number): void {\n // Extend the first 16 words into the remaining 48 words w[16..63] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);\n for (let i = 16; i < 64; i++) {\n const W15 = SHA256_W[i - 15];\n const W2 = SHA256_W[i - 2];\n const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ (W15 >>> 3);\n const s1 = rotr(W2, 17) ^ rotr(W2, 19) ^ (W2 >>> 10);\n SHA256_W[i] = (s1 + SHA256_W[i - 7] + s0 + SHA256_W[i - 16]) | 0;\n }\n // Compression function main loop, 64 rounds\n let { A, B, C, D, E, F, G, H } = this;\n for (let i = 0; i < 64; i++) {\n const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);\n const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const sigma0 = rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22);\n const T2 = (sigma0 + Maj(A, B, C)) | 0;\n H = G;\n G = F;\n F = E;\n E = (D + T1) | 0;\n D = C;\n C = B;\n B = A;\n A = (T1 + T2) | 0;\n }\n // Add the compressed chunk to the current hash value\n A = (A + this.A) | 0;\n B = (B + this.B) | 0;\n C = (C + this.C) | 0;\n D = (D + this.D) | 0;\n E = (E + this.E) | 0;\n F = (F + this.F) | 0;\n G = (G + this.G) | 0;\n H = (H + this.H) | 0;\n this.set(A, B, C, D, E, F, G, H);\n }\n protected roundClean() {\n SHA256_W.fill(0);\n }\n destroy() {\n this.set(0, 0, 0, 0, 0, 0, 0, 0);\n this.buffer.fill(0);\n }\n}\n// Constants from https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf\nclass SHA224 extends SHA256 {\n A = 0xc1059ed8 | 0;\n B = 0x367cd507 | 0;\n C = 0x3070dd17 | 0;\n D = 0xf70e5939 | 0;\n E = 0xffc00b31 | 0;\n F = 0x68581511 | 0;\n G = 0x64f98fa7 | 0;\n H = 0xbefa4fa4 | 0;\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\n/**\n * SHA2-256 hash function\n * @param message - data that would be hashed\n */\nexport const sha256 = /* @__PURE__ */ wrapConstructor(() => new SHA256());\nexport const sha224 = /* @__PURE__ */ wrapConstructor(() => new SHA224());\n", "import { exists, output } from './_assert.js';\nimport { Hash, createView, Input, toBytes } from './utils.js';\n\n// Polyfill for Safari 14\nfunction setBigUint64(view: DataView, byteOffset: number, value: bigint, isLE: boolean): void {\n if (typeof view.setBigUint64 === 'function') return view.setBigUint64(byteOffset, value, isLE);\n const _32n = BigInt(32);\n const _u32_max = BigInt(0xffffffff);\n const wh = Number((value >> _32n) & _u32_max);\n const wl = Number(value & _u32_max);\n const h = isLE ? 4 : 0;\n const l = isLE ? 0 : 4;\n view.setUint32(byteOffset + h, wh, isLE);\n view.setUint32(byteOffset + l, wl, isLE);\n}\n\n// Choice: a ? b : c\nexport const Chi = (a: number, b: number, c: number) => (a & b) ^ (~a & c);\n// Majority function, true if any two inpust is true\nexport const Maj = (a: number, b: number, c: number) => (a & b) ^ (a & c) ^ (b & c);\n\n/**\n * Merkle-Damgard hash construction base class.\n * Could be used to create MD5, RIPEMD, SHA1, SHA2.\n */\nexport abstract class HashMD<T extends HashMD<T>> extends Hash<T> {\n protected abstract process(buf: DataView, offset: number): void;\n protected abstract get(): number[];\n protected abstract set(...args: number[]): void;\n abstract destroy(): void;\n protected abstract roundClean(): void;\n // For partial updates less than block size\n protected buffer: Uint8Array;\n protected view: DataView;\n protected finished = false;\n protected length = 0;\n protected pos = 0;\n protected destroyed = false;\n\n constructor(\n readonly blockLen: number,\n public outputLen: number,\n readonly padOffset: number,\n readonly isLE: boolean\n ) {\n super();\n this.buffer = new Uint8Array(blockLen);\n this.view = createView(this.buffer);\n }\n update(data: Input): this {\n exists(this);\n const { view, buffer, blockLen } = this;\n data = toBytes(data);\n const len = data.length;\n for (let pos = 0; pos < len; ) {\n const take = Math.min(blockLen - this.pos, len - pos);\n // Fast path: we have at least one block in input, cast it to view and process\n if (take === blockLen) {\n const dataView = createView(data);\n for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);\n continue;\n }\n buffer.set(data.subarray(pos, pos + take), this.pos);\n this.pos += take;\n pos += take;\n if (this.pos === blockLen) {\n this.process(view, 0);\n this.pos = 0;\n }\n }\n this.length += data.length;\n this.roundClean();\n return this;\n }\n digestInto(out: Uint8Array) {\n exists(this);\n output(out, this);\n this.finished = true;\n // Padding\n // We can avoid allocation of buffer for padding completely if it\n // was previously not allocated here. But it won't change performance.\n const { buffer, view, blockLen, isLE } = this;\n let { pos } = this;\n // append the bit '1' to the message\n buffer[pos++] = 0b10000000;\n this.buffer.subarray(pos).fill(0);\n // we have less than padOffset left in buffer, so we cannot put length in\n // current block, need process it and pad again\n if (this.padOffset > blockLen - pos) {\n this.process(view, 0);\n pos = 0;\n }\n // Pad until full block byte with zeros\n for (let i = pos; i < blockLen; i++) buffer[i] = 0;\n // Note: sha512 requires length to be 128bit integer, but length in JS will overflow before that\n // You need to write around 2 exabytes (u64_max / 8 / (1024**6)) for this to happen.\n // So we just write lowest 64 bits of that value.\n setBigUint64(view, blockLen - 8, BigInt(this.length * 8), isLE);\n this.process(view, 0);\n const oview = createView(out);\n const len = this.outputLen;\n // NOTE: we do division by 4 later, which should be fused in single op with modulo by JIT\n if (len % 4) throw new Error('_sha2: outputLen should be aligned to 32bit');\n const outLen = len / 4;\n const state = this.get();\n if (outLen > state.length) throw new Error('_sha2: outputLen bigger than state');\n for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE);\n }\n digest() {\n const { buffer, outputLen } = this;\n this.digestInto(buffer);\n const res = buffer.slice(0, outputLen);\n this.destroy();\n return res;\n }\n _cloneInto(to?: T): T {\n to ||= new (this.constructor as any)() as T;\n to.set(...this.get());\n const { blockLen, buffer, length, finished, destroyed, pos } = this;\n to.length = length;\n to.pos = pos;\n to.finished = finished;\n to.destroyed = destroyed;\n if (length % blockLen) to.buffer.set(buffer);\n return to;\n }\n}\n", "function number(n: number) {\n if (!Number.isSafeInteger(n) || n < 0) throw new Error(`positive integer expected, not ${n}`);\n}\n\nfunction bool(b: boolean) {\n if (typeof b !== 'boolean') throw new Error(`boolean expected, not ${b}`);\n}\n\n// copied from utils\nexport function isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\nfunction bytes(b: Uint8Array | undefined, ...lengths: number[]) {\n if (!isBytes(b)) throw new Error('Uint8Array expected');\n if (lengths.length > 0 && !lengths.includes(b.length))\n throw new Error(`Uint8Array expected of length ${lengths}, not of length=${b.length}`);\n}\n\ntype Hash = {\n (data: Uint8Array): Uint8Array;\n blockLen: number;\n outputLen: number;\n create: any;\n};\nfunction hash(h: Hash) {\n if (typeof h !== 'function' || typeof h.create !== 'function')\n throw new Error('Hash should be wrapped by utils.wrapConstructor');\n number(h.outputLen);\n number(h.blockLen);\n}\n\nfunction exists(instance: any, checkFinished = true) {\n if (instance.destroyed) throw new Error('Hash instance has been destroyed');\n if (checkFinished && instance.finished) throw new Error('Hash#digest() has already been called');\n}\nfunction output(out: any, instance: any) {\n bytes(out);\n const min = instance.outputLen;\n if (out.length < min) {\n throw new Error(`digestInto() expects output buffer of length at least ${min}`);\n }\n}\n\nexport { number, bool, bytes, hash, exists, output };\n\nconst assert = { number, bool, bytes, hash, exists, output };\nexport default assert;\n", "/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n\n// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// node.js versions earlier than v19 don't declare it in global scope.\n// For node.js, package.json#exports field mapping rewrites import\n// from `crypto` to `cryptoNode`, which imports native module.\n// Makes the utils un-importable in browsers without a bundler.\n// Once node.js 18 is deprecated (2025-04-30), we can just drop the import.\nimport { crypto } from '@noble/hashes/crypto';\nimport { bytes as abytes } from './_assert.js';\n// export { isBytes } from './_assert.js';\n// We can't reuse isBytes from _assert, because somehow this causes huge perf issues\nexport function isBytes(a: unknown): a is Uint8Array {\n return (\n a instanceof Uint8Array ||\n (a != null && typeof a === 'object' && a.constructor.name === 'Uint8Array')\n );\n}\n\n// prettier-ignore\nexport type TypedArray = Int8Array | Uint8ClampedArray | Uint8Array |\n Uint16Array | Int16Array | Uint32Array | Int32Array;\n\n// Cast array to different type\nexport const u8 = (arr: TypedArray) => new Uint8Array(arr.buffer, arr.byteOffset, arr.byteLength);\nexport const u32 = (arr: TypedArray) =>\n new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));\n\n// Cast array to view\nexport const createView = (arr: TypedArray) =>\n new DataView(arr.buffer, arr.byteOffset, arr.byteLength);\n\n// The rotate right (circular right shift) operation for uint32\nexport const rotr = (word: number, shift: number) => (word << (32 - shift)) | (word >>> shift);\n// The rotate left (circular left shift) operation for uint32\nexport const rotl = (word: number, shift: number) =>\n (word << shift) | ((word >>> (32 - shift)) >>> 0);\n\nexport const isLE = new Uint8Array(new Uint32Array([0x11223344]).buffer)[0] === 0x44;\n// The byte swap operation for uint32\nexport const byteSwap = (word: number) =>\n ((word << 24) & 0xff000000) |\n ((word << 8) & 0xff0000) |\n ((word >>> 8) & 0xff00) |\n ((word >>> 24) & 0xff);\n// Conditionally byte swap if on a big-endian platform\nexport const byteSwapIfBE = isLE ? (n: number) => n : (n: number) => byteSwap(n);\n\n// In place byte swap for Uint32Array\nexport function byteSwap32(arr: Uint32Array) {\n for (let i = 0; i < arr.length; i++) {\n arr[i] = byteSwap(arr[i]);\n }\n}\n\n// Array where index 0xf0 (240) is mapped to string 'f0'\nconst hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) =>\n i.toString(16).padStart(2, '0')\n);\n/**\n * @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'\n */\nexport function bytesToHex(bytes: Uint8Array): string {\n abytes(bytes);\n // pre-caching improves the speed 6x\n let hex = '';\n for (let i = 0; i < bytes.length; i++) {\n hex += hexes[bytes[i]];\n }\n return hex;\n}\n\n// We use optimized technique to convert hex string to byte array\nconst asciis = { _0: 48, _9: 57, _A: 65, _F: 70, _a: 97, _f: 102 } as const;\nfunction asciiToBase16(char: number): number | undefined {\n if (char >= asciis._0 && char <= asciis._9) return char - asciis._0;\n if (char >= asciis._A && char <= asciis._F) return char - (asciis._A - 10);\n if (char >= asciis._a && char <= asciis._f) return char - (asciis._a - 10);\n return;\n}\n\n/**\n * @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])\n */\nexport function hexToBytes(hex: string): Uint8Array {\n if (typeof hex !== 'string') throw new Error('hex string expected, got ' + typeof hex);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2) throw new Error('padded hex string expected, got unpadded hex of length ' + hl);\n const array = new Uint8Array(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n const n1 = asciiToBase16(hex.charCodeAt(hi));\n const n2 = asciiToBase16(hex.charCodeAt(hi + 1));\n if (n1 === undefined || n2 === undefined) {\n const char = hex[hi] + hex[hi + 1];\n throw new Error('hex string expected, got non-hex character \"' + char + '\" at index ' + hi);\n }\n array[ai] = n1 * 16 + n2;\n }\n return array;\n}\n\n// There is no setImmediate in browser and setTimeout is slow.\n// call of async fn will return Promise, which will be fullfiled only on\n// next scheduler queue processing step and this is exactly what we need.\nexport const nextTick = async () => {};\n\n// Returns control to thread each 'tick' ms to avoid blocking\nexport async function asyncLoop(iters: number, tick: number, cb: (i: number) => void) {\n let ts = Date.now();\n for (let i = 0; i < iters; i++) {\n cb(i);\n // Date.now() is not monotonic, so in case if clock goes backwards we return return control too\n const diff = Date.now() - ts;\n if (diff >= 0 && diff < tick) continue;\n await nextTick();\n ts += diff;\n }\n}\n\n// Global symbols in both browsers and Node.js since v11\n// See https://github.com/microsoft/TypeScript/issues/31535\ndeclare const TextEncoder: any;\n\n/**\n * @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])\n */\nexport function utf8ToBytes(str: string): Uint8Array {\n if (typeof str !== 'string') throw new Error(`utf8ToBytes expected string, got ${typeof str}`);\n return new Uint8Array(new TextEncoder().encode(str)); // https://bugzil.la/1681809\n}\n\nexport type Input = Uint8Array | string;\n/**\n * Normalizes (non-hex) string or Uint8Array to Uint8Array.\n * Warning: when Uint8Array is passed, it would NOT get copied.\n * Keep in mind for future mutable operations.\n */\nexport function toBytes(data: Input): Uint8Array {\n if (typeof data === 'string') data = utf8ToBytes(data);\n abytes(data);\n return data;\n}\n\n/**\n * Copies several Uint8Arrays into one.\n */\nexport function concatBytes(...arrays: Uint8Array[]): Uint8Array {\n let sum = 0;\n for (let i = 0; i < arrays.length; i++) {\n const a = arrays[i];\n abytes(a);\n sum += a.length;\n }\n const res = new Uint8Array(sum);\n for (let i = 0, pad = 0; i < arrays.length; i++) {\n const a = arrays[i];\n res.set(a, pad);\n pad += a.length;\n }\n return res;\n}\n\n// For runtime check if class implements interface\nexport abstract class Hash<T extends Hash<T>> {\n abstract blockLen: number; // Bytes per block\n abstract outputLen: number; // Bytes in output\n abstract update(buf: Input): this;\n // Writes digest into buf\n abstract digestInto(buf: Uint8Array): void;\n abstract digest(): Uint8Array;\n /**\n * Resets internal state. Makes Hash instance unusable.\n * Reset is impossible for keyed hashes if key is consumed into state. If digest is not consumed\n * by user, they will need to manually call `destroy()` when zeroing is necessary.\n */\n abstract destroy(): void;\n /**\n * Clones hash instance. Unsafe: doesn't check whether `to` is valid. Can be used as `clone()`\n * when no options are passed.\n * Reasons to use `_cloneInto` instead of clone: 1) performance 2) reuse instance => all internal\n * buffers are overwritten => causes buffer overwrite which is used for digest in some cases.\n * There are no guarantees for clean-up because it's impossible in JS.\n */\n abstract _cloneInto(to?: T): T;\n // Safe version that clones internal state\n clone(): T {\n return this._cloneInto();\n }\n}\n\n/**\n * XOF: streaming API to read digest in chunks.\n * Same as 'squeeze' in keccak/k12 and 'seek' in blake3, but more generic name.\n * When hash used in XOF mode it is up to user to call '.destroy' afterwards, since we cannot\n * destroy state, next call can require more bytes.\n */\nexport type HashXOF<T extends Hash<T>> = Hash<T> & {\n xof(bytes: number): Uint8Array; // Read 'bytes' bytes from digest stream\n xofInto(buf: Uint8Array): Uint8Array; // read buf.length bytes from digest stream into buf\n};\n\nconst toStr = {}.toString;\ntype EmptyObj = {};\nexport function checkOpts<T1 extends EmptyObj, T2 extends EmptyObj>(\n defaults: T1,\n opts?: T2\n): T1 & T2 {\n if (opts !== undefined && toStr.call(opts) !== '[object Object]')\n throw new Error('Options should be object or undefined');\n const merged = Object.assign(defaults, opts);\n return merged as T1 & T2;\n}\n\nexport type CHash = ReturnType<typeof wrapConstructor>;\n\nexport function wrapConstructor<T extends Hash<T>>(hashCons: () => Hash<T>) {\n const hashC = (msg: Input): Uint8Array => hashCons().update(toBytes(msg)).digest();\n const tmp = hashCons();\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = () => hashCons();\n return hashC;\n}\n\nexport function wrapConstructorWithOpts<H extends Hash<H>, T extends Object>(\n hashCons: (opts?: T) => Hash<H>\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\nexport function wrapXOFConstructorWithOpts<H extends HashXOF<H>, T extends Object>(\n hashCons: (opts?: T) => HashXOF<H>\n) {\n const hashC = (msg: Input, opts?: T): Uint8Array => hashCons(opts).update(toBytes(msg)).digest();\n const tmp = hashCons({} as T);\n hashC.outputLen = tmp.outputLen;\n hashC.blockLen = tmp.blockLen;\n hashC.create = (opts: T) => hashCons(opts);\n return hashC;\n}\n\n/**\n * Secure PRNG. Uses `crypto.getRandomValues`, which defers to OS.\n */\nexport function randomBytes(bytesLength = 32): Uint8Array {\n if (crypto && typeof crypto.getRandomValues === 'function') {\n return crypto.getRandomValues(new Uint8Array(bytesLength));\n }\n throw new Error('crypto.getRandomValues must be defined');\n}\n", "// We use WebCrypto aka globalThis.crypto, which exists in browsers and node.js 16+.\n// See utils.ts for details.\ndeclare const globalThis: Record<string, any> | undefined;\nexport const crypto =\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\n", "/**\n * Canonicalizes a given object according to RFC 8785 (https://tools.ietf.org/html/rfc8785),\n * which describes JSON Canonicalization Scheme (JCS). This function sorts the keys of the\n * object and its nested objects alphabetically and then returns a stringified version of it.\n * This method handles nested objects, array values, and null values appropriately.\n *\n * @param obj - The object to canonicalize.\n * @returns The stringified version of the input object with its keys sorted alphabetically\n * per RFC 8785.\n */\nexport function canonicalize(obj: { [key: string]: any }): string {\n /**\n * Recursively sorts the keys of an object.\n *\n * @param obj - The object whose keys are to be sorted.\n * @returns A new object with sorted keys.\n */\n const sortObjKeys = (obj: { [key: string]: any }): { [key: string]: any } => {\n if (obj !== null && typeof obj === 'object' && !Array.isArray(obj)) {\n const sortedKeys = Object.keys(obj).sort();\n const sortedObj: { [key: string]: any } = {};\n for (const key of sortedKeys) {\n // Recursively sort keys of nested objects.\n sortedObj[key] = sortObjKeys(obj[key]);\n }\n return sortedObj;\n }\n return obj;\n };\n\n // Stringify and return the final sorted object.\n const sortedObj = sortObjKeys(obj);\n return JSON.stringify(sortedObj);\n}", "import { sha256 } from '@noble/hashes/sha256';\n\n/**\n * The `Sha256` class provides an interface for generating SHA-256 hash digests.\n *\n * This class utilizes the '@noble/hashes/sha256' function to generate hash digests\n * of the provided data. The SHA-256 algorithm is widely used in cryptographic\n * applications to produce a fixed-size 256-bit (32-byte) hash.\n *\n * The methods of this class are asynchronous and return Promises. They use the Uint8Array\n * type for input data and the resulting digest, ensuring a consistent interface\n * for binary data processing.\n *\n * @example\n * ```ts\n * const data = new Uint8Array([...]);\n * const hash = await Sha256.digest({ data });\n * ```\n */\nexport class Sha256 {\n /**\n * Generates a SHA-256 hash digest for the given data.\n *\n * @remarks\n * This method produces a hash digest using the SHA-256 algorithm. The resultant digest\n * is deterministic, meaning the same data will always produce the same hash, but\n * is computationally infeasible to regenerate the original data from the hash.\n *\n * @example\n * ```ts\n * const data = new Uint8Array([...]);\n * const hash = await Sha256.digest({ data });\n * ```\n *\n * @param params - The parameters for the hashing operation.\n * @param params.data - The data to hash, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to the SHA-256 hash digest of the provided data as a Uint8Array.\n */\n public static async digest({ data }: {\n data: Uint8Array;\n }): Promise<Uint8Array> {\n const hash = sha256(data);\n\n return hash;\n }\n}", "import { Convert, removeUndefinedProperties } from '@enbox/common';\n\nimport { canonicalize } from './utils.js';\nimport { Sha256 } from '../primitives/sha256.js';\n\n/**\n * Constant defining the prefix for JSON Web Keys (JWK) key URIs in this library.\n *\n * The prefix 'urn:jwk:' makes it explicit that a string represents a JWK, referenced by a\n * {@link https://datatracker.ietf.org/doc/html/rfc3986 | URI} (Uniform Resource Identifier),\n * which ensures consistent key referencing across all Web5 Key Management System (KMS)\n * implementations.\n *\n * These key URIs take the form `urn:jwk:<JWK thumbprint>`, where the\n * {@link https://datatracker.ietf.org/doc/html/rfc7638 | JWK thumbprint}, derived from the JWK, is\n * unique to the key's material, unaffected by the order or optional properties in the JWK.\n */\nexport const KEY_URI_PREFIX_JWK = 'urn:jwk:';\n\n/**\n * JSON Web Key Operations\n *\n * The \"key_ops\" (key operations) parameter identifies the operation(s)\n * for which the key is intended to be used. The \"key_ops\" parameter is\n * intended for use cases in which public, private, or symmetric keys\n * may be present.\n *\n * Its value is an array of key operation values. Values defined by\n * {@link https://www.rfc-editor.org/rfc/rfc7517.html#section-4.3 | RFC 7517 Section 4.3} are:\n *\n * - \"decrypt\" : Decrypt content and validate decryption, if applicable\n * - \"deriveBits\" : Derive bits not to be used as a key\n * - \"deriveKey\" : Derive key\n * - \"encrypt\" : Encrypt content\n * - \"sign\" : Compute digital signature or MAC\n * - \"unwrapKey\" : Decrypt key and validate decryption, if applicable\n * - \"verify\" : Verify digital signature or MAC\n * - \"wrapKey\" : Encrypt key\n *\n * Other values MAY be used. The key operation values are case-\n * sensitive strings. Duplicate key operation values MUST NOT be\n * present in the array. Use of the \"key_ops\" member is OPTIONAL,\n * unless the application requires its presence.\n *\n * The \"use\" and \"key_ops\" JWK members SHOULD NOT be used together;\n * however, if both are used, the information they convey MUST be\n * consistent. Applications should specify which of these members they\n * use, if either is to be used by the application.\n */\nexport type JwkOperation = 'encrypt' | 'decrypt' | 'sign' | 'verify' | 'deriveKey' | 'deriveBits' | 'wrapKey' | 'unwrapKey';\n\n/**\n * JSON Web Key Use\n *\n * The \"use\" (public key use) parameter identifies the intended use of\n * the public key. The \"use\" parameter is employed to indicate whether\n * a public key is used for encrypting data or verifying the signature\n * on data.\n *\n * Values defined by {@link https://datatracker.ietf.org/doc/html/rfc7517#section-4.2 | RFC 7517 Section 4.2} are:\n *\n * - \"sig\" (signature)\n * - \"enc\" (encryption)\n *\n * Other values MAY be used. The \"use\" value is a case-sensitive\n * string. Use of the \"use\" member is OPTIONAL, unless the application\n * requires its presence.\n *\n * The \"use\" and \"key_ops\" JWK members SHOULD NOT be used together;\n * however, if both are used, the information they convey MUST be\n * consistent. Applications should specify which of these members they\n * use, if either is to be used by the application.\n *\n * When a key is used to wrap another key and a public key use\n * designation for the first key is desired, the \"enc\" (encryption) key\n * use value is used, since key wrapping is a kind of encryption. The\n * \"enc\" value is also to be used for public keys used for key agreement\n * operations.\n */\nexport type JwkUse = 'sig' | 'enc' | string;\n\n/**\n * JSON Web Key Types\n */\nexport type JwkType =\n /**\n * Elliptic Curve\n * Used with Elliptic Curve Digital Signature Algorithm (ECDSA) and Elliptic\n * Curve Diffie-Hellman (ECDH), including secp256k1, P-256, P-384, and P-521.\n */\n | 'EC'\n /**\n * RSA\n * Widely used for encryption and digital signatures. RSA keys are used in\n * various algorithms like RS256, RS384, RS512, etc.\n */\n | 'RSA'\n /**\n * Octet sequence\n * Used with symmetric signing (e.g., HMAC HS256, HS512, etc.) and\n * symmetric encryption (e.g., A256CBC-HS512, A256GCM, etc.) algorithms.\n */\n | 'oct'\n /**\n * Octet string key pairs (OKP)\n * A type of public key that is used with algorithms such as EdDSA (Ed25519 and\n * Ed448 curves) and ECDH (X25519 and X448 curves).\n */\n | 'OKP';\n\n/**\n * JSON Web Key Elliptic Curve\n */\nexport type JwkNamedCurves =\n // P-256 Curve\n | 'P-256'\n // P-384 Curve\n | 'P-384'\n // P-521 Curve\n | 'P-521'\n // Ed25519 signature algorithm key pairs\n | 'Ed25519'\n // Ed448 signature algorithm key pairs\n | 'Ed448'\n // X25519 function key pairs\n | 'X25519'\n // X448 function key pairs\n | 'X448'\n // SECG secp256k1 curve\n | 'secp256k1';\n\n/**\n * JSON Web Key Parameters\n */\n\n/** Parameters used with any \"kty\" (key type) value. */\nexport type JwkParamsAnyKeyType = {\n /** JWK Algorithm Parameter. The algorithm intended for use with the key. */\n alg?: string;\n /** JWK Extractable Parameter */\n ext?: 'true' | 'false';\n /** JWK Key Operations Parameter */\n key_ops?: JwkOperation[];\n /** JWK Key ID Parameter */\n kid?: string;\n /** JWK Key Type Parameter */\n kty: JwkType;\n /** JWK Public Key Use Parameter */\n use?: JwkUse;\n /** JWK X.509 Certificate Chain Parameter */\n x5c?: string;\n /** JWK X.509 Certificate SHA-1 Thumbprint Parameter */\n x5t?: string;\n /** JWK X.509 Certificate SHA-256 Thumbprint Parameter */\n 'x5t#S256'?: string;\n /** JWK X.509 URL Parameter */\n x5u?: string;\n};\n\n/** Parameters used with \"EC\" (elliptic curve) public keys. */\nexport type JwkParamsEcPublic = Omit<JwkParamsAnyKeyType, 'alg' | 'kty'> & {\n /**\n * The algorithm intended for use with the key.\n * ES256 : ECDSA using P-256 and SHA-256\n * ES256K : ECDSA using secp256k1 curve and SHA-256\n * ES384 : ECDSA using P-384 and SHA-384\n * ES512 : ECDSA using P-521 and SHA-512\n */\n alg?: 'ES256' | 'ES256K' | 'ES384' | 'ES512';\n\n /**\n * Elliptic Curve key pair.\n */\n kty: 'EC';\n\n /**\n * The cryptographic curve used with the key.\n * MUST be present for all EC public keys.\n */\n crv: 'secp256k1' | 'P-256' | 'P-384' | 'P-521';\n\n /**\n * The x-coordinate for the Elliptic Curve point.\n * Represented as the base64url encoding of the octet string\n * representation of the coordinate.\n * MUST be present for all EC public keys\n */\n x: string;\n\n /**\n * The y-coordinate for the Elliptic Curve point.\n * Represented as the base64url encoding of the octet string\n * representation of the coordinate.\n * MUST be present only for secp256k1 public keys.\n */\n y?: string;\n};\n\n/** Parameters used with \"EC\" (elliptic curve) private keys. */\nexport type JwkParamsEcPrivate = JwkParamsEcPublic & {\n /**\n * The d-coordinate for the Elliptic Curve point.\n * Represented as the base64url encoding of the octet string\n * representation of the coordinate.\n * MUST be present for all EC private keys.\n */\n d: string;\n};\n\n/** Parameters used with \"OKP\" (octet key pair) public keys. */\nexport type JwkParamsOkpPublic =\n Omit<JwkParamsAnyKeyType, 'kty' | 'alg' | 'crv'> &\n Pick<JwkParamsEcPublic, 'x'> & {\n /**\n * The algorithm intended for use with the key.\n * EdDSA: Edwards Curve Digital Signature Algorithm\n */\n alg?: 'EdDSA';\n\n /**\n * The cryptographic curve used with the key.\n * MUST be present for all OKP public keys.\n */\n crv: 'Ed25519' | 'Ed448' | 'X25519' | 'X448';\n\n /**\n * Key type\n * OKP (Octet Key Pair) is defined for public key algorithms that use octet\n * strings as private and public keys.\n */\n kty: 'OKP';\n};\n\n/** Parameters used with \"OKP\" (octet key pair) private keys. */\nexport type JwkParamsOkpPrivate = JwkParamsOkpPublic & {\n /**\n * The d-coordinate for the Edwards Curve point.\n * Represented as the base64url encoding of the octet string\n * representation of the coordinate.\n * MUST be present for all EC private keys.\n */\n d: string;\n};\n\n/** Parameters used with \"oct\" (octet sequence) private keys. */\nexport type JwkParamsOctPrivate = Omit<JwkParamsAnyKeyType, 'alg' | 'kty'> & {\n /**\n * The algorithm intended for use with the key.\n * Used with symmetric signing (e.g., HMAC HS256, etc.) and\n * symmetric encryption (e.g., A256GCM, etc.) algorithms.\n */\n alg?:\n // AES CBC using 128-bit key\n | 'A128CBC'\n // AES CBC using 192-bit key\n | 'A192CBC'\n // AES CBC using 256-bit key\n | 'A256CBC'\n // AES CTR using 128-bit key\n | 'A128CTR'\n // AES CTR using 192-bit key\n | 'A192CTR'\n // AES CTR using 256-bit key\n | 'A256CTR'\n // AES GCM using a 128-bit key\n | 'A128GCM'\n // AES GCM using a 192-bit key\n | 'A192GCM'\n // AES GCM using a 256-bit key\n | 'A256GCM'\n // HMAC using SHA-256\n | 'HS256'\n // HMAC using SHA-384\n | 'HS384'\n // HMAC using SHA-512\n | 'HS512'\n\n /**\n * The \"k\" (key value) parameter contains the value of the symmetric\n * (or other single-valued) key. It is represented as the base64url\n * encoding of the octet sequence containing the key value.\n */\n k: string;\n\n /**\n * Key type\n * oct (Octet Sequence) is defined for symmetric encryption and\n * symmetric signature algorithms.\n */\n kty: 'oct';\n};\n\n/** Parameters Used with \"RSA\" public keys. */\nexport type JwkParamsRsaPublic = Omit<JwkParamsAnyKeyType, 'kty'> & {\n /** Public exponent for RSA */\n e: string;\n\n /**\n * Key type\n * RSA is widely used for encryption and digital signatures.\n */\n kty: 'RSA';\n\n /** Modulus for RSA */\n n: string;\n};\n\n/** Parameters used with \"RSA\" private keys. */\nexport type JwkParamsRsaPrivate = JwkParamsRsaPublic & {\n /** Private exponent for RSA */\n d: string;\n /** First prime factor for RSA */\n p?: string;\n /** Second prime factor for RSA */\n q?: string;\n /** First factor's CRT exponent for RSA */\n dp?: string;\n /** Second factor's CRT exponent for RSA */\n dq?: string;\n /** First CRT coefficient for RSA */\n qi?: string;\n /** Other primes information (optional in RFC 7518) */\n oth?: {\n /** Other primes' factor */\n r: string;\n /** Other primes' CRT exponent */\n d: string;\n /** Other primes' CRT coefficient */\n t: string;\n }[];\n};\n\n/** Parameters used with public keys in JWK format. */\nexport type PublicKeyJwk = JwkParamsEcPublic | JwkParamsOkpPublic | JwkParamsRsaPublic;\n\n/** Parameters used with private keys in JWK format. */\nexport type PrivateKeyJwk = JwkParamsEcPrivate | JwkParamsOkpPrivate | JwkParamsOctPrivate | JwkParamsRsaPrivate;\n\n/**\n * JSON Web Key ({@link https://datatracker.ietf.org/doc/html/rfc7517 | JWK}).\n * \"RSA\", \"EC\", \"OKP\", and \"oct\" key types are supported.\n */\nexport interface Jwk {\n // Common properties that apply to all key types.\n\n /** JWK Algorithm Parameter. The algorithm intended for use with the key. */\n alg?: string;\n /** JWK Extractable Parameter */\n ext?: 'true' | 'false';\n /** JWK Key Operations Parameter */\n key_ops?: JwkOperation[];\n /** JWK Key ID Parameter */\n kid?: string;\n /** JWK Key Type Parameter */\n kty: JwkType;\n /** JWK Public Key Use Parameter */\n use?: JwkUse;\n /** JWK X.509 Certificate Chain Parameter */\n x5c?: string;\n /** JWK X.509 Certificate SHA-1 Thumbprint Parameter */\n x5t?: string;\n /** JWK X.509 Certificate SHA-256 Thumbprint Parameter */\n 'x5t#S256'?: string;\n /** JWK X.509 URL Parameter */\n x5u?: string;\n\n // Elliptic Curve (EC or OKP) public key properties.\n\n /** The cryptographic curve used with the key. */\n crv?: string;\n /** The x-coordinate for the Elliptic Curve point. */\n x?: string;\n /** The y-coordinate for the Elliptic Curve point. */\n y?: string;\n\n // Symmetric key properties.\n\n /** The \"k\" (key value) parameter contains the value of the symmetric (or other single-valued) key. */\n k?: string;\n\n // RSA public key properties.\n\n /** Public exponent for RSA */\n e?: string;\n /** Modulus for RSA */\n n?: string;\n /** First prime factor for RSA */\n p?: string;\n /** Second prime factor for RSA */\n q?: string;\n /** First factor's CRT exponent for RSA */\n dp?: string;\n /** Second factor's CRT exponent for RSA */\n dq?: string;\n /** First CRT coefficient for RSA */\n qi?: string;\n /** Other primes information (optional in RFC 7518) */\n oth?: {\n /** Other primes' factor */\n r: string;\n /** Other primes' CRT exponent */\n d: string;\n /** Other primes' CRT coefficient */\n t: string;\n }[];\n\n // Elliptic Curve and RSA private key properties.\n\n /** Private key component for EC, OKP, or RSA keys. */\n d?: string;\n\n // Additional public or private properties.\n [key: string]: unknown;\n}\n\n/**\n * JSON Web Key Set ({@link https://datatracker.ietf.org/doc/html/rfc7517 | JWK Set})\n *\n * @remarks\n * A JWK Set is a JSON object that represents a set of JWKs. The JSON object MUST have a \"keys\"\n * member, with its value being an array of JWKs.\n *\n * Additional members can be present in the JWK Set but member names MUST be unique. If not\n * understood by implementations encountering them, they MUST be ignored. Parameters for\n * representing additional properties of JWK Sets should either be registered in the IANA\n * \"JSON Web Key Set Parameters\" registry or be a value that contains a Collision-Resistant Name.\n */\nexport interface JwkSet {\n /** Array of JWKs */\n keys: Jwk[]\n}\n\n/**\n * Computes the thumbprint of a JSON Web Key (JWK) using the method\n * specified in RFC 7638. This function accepts RSA, EC, OKP, and oct keys\n * and returns the thumbprint as a base64url encoded SHA-256 hash of the\n * JWK's required members, serialized and sorted lexicographically.\n *\n * Purpose:\n * - Uniquely Identifying Keys: The thumbprint allows the unique\n * identification of a specific JWK within a set of JWKs. It provides a\n * deterministic way to generate a value that can be used as a key\n * identifier (kid) or to match a specific key.\n *\n * - Simplifying Key Management: In systems where multiple keys are used,\n * managing and identifying individual keys can become complex. The\n * thumbprint method simplifies this by creating a standardized, unique\n * identifier for each key.\n *\n * - Enabling Interoperability: By standardizing the method to compute a\n * thumbprint, different systems can compute the same thumbprint value for\n * a given JWK. This enables interoperability among systems that use JWKs.\n *\n * - Secure Comparison: The thumbprint provides a way to securely compare\n * JWKs to determine if they are equivalent.\n *\n * @example\n * ```ts\n * const jwk: PublicKeyJwk = {\n * 'kty': 'EC',\n * 'crv': 'secp256k1',\n * 'x': '61iPYuGefxotzBdQZtDvv6cWHZmXrTTscY-u7Y2pFZc',\n * 'y': '88nPCVLfrAY9i-wg5ORcwVbHWC_tbeAd1JE2e0co0lU'\n * };\n *\n * const thumbprint = jwkThumbprint(jwk);\n * console.log(`JWK thumbprint: ${thumbprint}`);\n * ```\n *\n * @see {@link https://datatracker.ietf.org/doc/html/rfc7638 | RFC7638} for\n * the specification of JWK thumbprint computation.\n *\n * @param jwk - The JSON Web Key for which the thumbprint will be computed.\n * This must be an RSA, EC, OKP, or oct key.\n * @returns The thumbprint as a base64url encoded string.\n * @throws Throws an `Error` if the provided key type is unsupported.\n */\nexport async function computeJwkThumbprint({ jwk }: {\n jwk: Jwk\n}): Promise<string> {\n /** Step 1 - Normalization: The JWK is normalized to include only specific\n * members and in lexicographic order.\n */\n const keyType = jwk.kty;\n let normalizedJwk: Jwk;\n if (keyType === 'EC') {\n normalizedJwk = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };\n } else if (keyType === 'oct') {\n normalizedJwk = { k: jwk.k, kty: jwk.kty };\n } else if (keyType === 'OKP') {\n normalizedJwk = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };\n } else if (keyType === 'RSA') {\n normalizedJwk = { e: jwk.e, kty: jwk.kty, n: jwk.n };\n } else {\n throw new Error(`Unsupported key type: ${keyType}`);\n }\n removeUndefinedProperties(normalizedJwk);\n\n /** Step 2 - Serialization: The normalized JWK is serialized to a UTF-8\n * representation of its JSON encoding. */\n const serializedJwk = canonicalize(normalizedJwk);\n\n /** Step 3 - Digest Calculation: A cryptographic hash function\n * (SHA-256 is recommended) is applied to the serialized JWK,\n * resulting in the thumbprint. */\n const utf8Bytes = Convert.string(serializedJwk).toUint8Array();\n const digest = await Sha256.digest({ data: utf8Bytes });\n\n // Encode as Base64Url.\n const thumbprint = Convert.uint8Array(digest).toBase64Url();\n\n return thumbprint;\n}\n\n/**\n * Checks if the provided object is a valid elliptic curve private key in JWK format.\n *\n * @param obj - The object to check.\n * @returns True if the object is a valid EC private JWK; otherwise, false.\n */\nexport function isEcPrivateJwk(obj: unknown): obj is JwkParamsEcPrivate {\n if (!obj || typeof obj !== 'object') {return false;}\n if (!('kty' in obj && 'crv' in obj && 'x' in obj && 'd' in obj)) {return false;}\n if (obj.kty !== 'EC') {return false;}\n if (typeof obj.d !== 'string') {return false;}\n if (typeof obj.x !== 'string') {return false;}\n return true;\n}\n\n/**\n * Checks if the provided object is a valid elliptic curve public key in JWK format.\n *\n * @param obj - The object to check.\n * @returns True if the object is a valid EC public JWK; otherwise, false.\n */\nexport function isEcPublicJwk(obj: unknown): obj is JwkParamsEcPublic {\n if (!obj || typeof obj !== 'object') {return false;}\n if (!('kty' in obj && 'crv' in obj && 'x' in obj)) {return false;}\n if ('d' in obj) {return false;}\n if (obj.kty !== 'EC') {return false;}\n if (typeof obj.x !== 'string') {return false;}\n return true;\n}\n\n/**\n * Checks if the provided object is a valid octet sequence (symmetric key) in JWK format.\n *\n * @param obj - The object to check.\n * @returns True if the object is a valid oct private JWK; otherwise, false.\n */\nexport function isOctPrivateJwk(obj: unknown): obj is JwkParamsOctPrivate {\n if (!obj || typeof obj !== 'object') {return false;}\n if (!('kty' in obj && 'k' in obj)) {return false;}\n if (obj.kty !== 'oct') {return false;}\n if (typeof obj.k !== 'string') {return false;}\n return true;\n}\n\n/**\n * Checks if the provided object is a valid octet key pair private key in JWK format.\n *\n * @param obj - The object to check.\n * @returns True if the object is a valid OKP private JWK; otherwise, false.\n */\nexport function isOkpPrivateJwk(obj: unknown): obj is JwkParamsOkpPrivate {\n if (!obj || typeof obj !== 'object') {return false;}\n if (!('kty' in obj && 'crv' in obj && 'x' in obj && 'd' in obj)) {return false;}\n if (obj.kty !== 'OKP') {return false;}\n if (typeof obj.d !== 'string') {return false;}\n if (typeof obj.x !== 'string') {return false;}\n return true;\n}\n\n/**\n * Checks if the provided object is a valid octet key pair public key in JWK format.\n *\n * @param obj - The object to check.\n * @returns True if the object is a valid OKP public JWK; otherwise, false.\n */\nexport function isOkpPublicJwk(obj: unknown): obj is JwkParamsOkpPublic {\n if (!obj || typeof obj !== 'object') {return false;}\n if ('d' in obj) {return false;}\n if (!('kty' in obj && 'crv' in obj && 'x' in obj)) {return false;}\n if (obj.kty !== 'OKP') {return false;}\n if (typeof obj.x !== 'string') {return false;}\n return true;\n}\n\n/**\n * Checks if the provided object is a valid private key in JWK format of any supported type.\n *\n * @param obj - The object to check.\n * @returns True if the object is a valid private JWK; otherwise, false.\n */\nexport function isPrivateJwk(obj: unknown): obj is PrivateKeyJwk {\n if (!obj || typeof obj !== 'object') {return false;}\n\n const kty = (obj as { kty: string }).kty;\n\n switch (kty) {\n case 'EC':\n case 'OKP':\n case 'RSA':\n return 'd' in obj;\n case 'oct':\n return 'k' in obj;\n default:\n return false;\n }\n}\n\n/**\n * Checks if the provided object is a valid public key in JWK format of any supported type.\n *\n * @param obj - The object to check.\n * @returns True if the object is a valid public JWK; otherwise, false.\n */\nexport function isPublicJwk(obj: unknown): obj is PublicKeyJwk {\n if (!obj || typeof obj !== 'object') {return false;}\n\n const kty = (obj as { kty: string }).kty;\n\n switch (kty) {\n case 'EC':\n case 'OKP':\n return 'x' in obj && !('d' in obj);\n case 'RSA':\n return 'n' in obj && 'e' in obj && !('d' in obj);\n default:\n return false;\n }\n}", "import type { AffinePoint } from '@noble/curves/abstract/weierstrass';\n\nimport { Convert } from '@enbox/common';\nimport { numberToBytesBE } from '@noble/curves/abstract/utils';\nimport { secp256k1 } from '@noble/curves/secp256k1';\nimport { sha256 } from '@noble/hashes/sha256';\n\nimport type { Jwk } from '../jose/jwk.js';\nimport type { ComputePublicKeyParams, GetPublicKeyParams, SignParams, VerifyParams } from '../types/params-direct.js';\n\nimport { computeJwkThumbprint, isEcPrivateJwk, isEcPublicJwk } from '../jose/jwk.js';\n\n/**\n * The `Secp256k1` class provides a comprehensive suite of utilities for working with\n * the secp256k1 elliptic curve, commonly used in blockchain and cryptographic applications.\n * This class includes methods for key generation, conversion, signing, verification, and\n * Elliptic Curve Diffie-Hellman (ECDH) key agreement.\n *\n * The class supports conversions between raw byte formats and JSON Web Key (JWK) formats. It\n * adheres to RFC6979 for ECDSA signing and verification and RFC6090 for ECDH.\n *\n * Key Features:\n * - Key Generation: Generate secp256k1 private keys in JWK format.\n * - Key Conversion: Transform keys between raw byte arrays and JWK formats.\n * - Public Key Derivation: Derive public keys from private keys.\n * - ECDH Shared Secret Computation: Securely derive shared secrets using private and public keys.\n * - ECDSA Signing and Verification: Sign data and verify signatures with secp256k1 keys.\n * - Key Validation: Validate the mathematical correctness of secp256k1 keys.\n *\n * The methods in this class are asynchronous, returning Promises to accommodate various\n * JavaScript environments, and use `Uint8Array` for binary data handling.\n *\n * @example\n * ```ts\n * // Key Generation\n * const privateKey = await Secp256k1.generateKey();\n *\n * // Public Key Derivation\n * const publicKey = await Secp256k1.computePublicKey({ key: privateKey });\n * console.log(publicKey === await Secp256k1.getPublicKey({ key: privateKey })); // Output: true\n *\n * // ECDH Shared Secret Computation\n * const sharedSecret = await Secp256k1.sharedSecret({\n * privateKeyA: privateKey,\n * publicKeyB: anotherPublicKey\n * });\n *\n * // ECDSA Signing\n * const signature = await Secp256k1.sign({\n * key: privateKey,\n * data: new TextEncoder().encode('Message')\n * });\n *\n * // ECDSA Signature Verification\n * const isValid = await Secp256k1.verify({\n * key: publicKey,\n * signature: signature,\n * data: new TextEncoder().encode('Message')\n * });\n *\n * // Key Conversion\n * const publicKeyBytes = await Secp256k1.publicKeyToBytes({ publicKey });\n * const privateKeyBytes = await Secp256k1.privateKeyToBytes({ privateKey });\n * const compressedPublicKey = await Secp256k1.compressPublicKey({ publicKeyBytes });\n * const uncompressedPublicKey = await Secp256k1.decompressPublicKey({ publicKeyBytes });\n *\n * // Key Validation\n * const isPrivateKeyValid = await Secp256k1.validatePrivateKey({ privateKeyBytes });\n * const isPublicKeyValid = await Secp256k1.validatePublicKey({ publicKeyBytes });\n * ```\n */\nexport class Secp256k1 {\n /**\n * Adjusts an ECDSA signature to a normalized, low-S form.\n *\n * @remarks\n * All ECDSA signatures, regardless of the curve, consist of two components, `r` and `s`, both of\n * which are integers. The curve's order (the total number of points on the curve) is denoted by\n * `n`. In a valid ECDSA signature, both `r` and `s` must be in the range [1, n-1]. However, due\n * to the mathematical properties of ECDSA, if `(r, s)` is a valid signature, then `(r, n - s)` is\n * also a valid signature for the same message and public key. In other words, for every\n * signature, there's a \"mirror\" signature that's equally valid. For these elliptic curves:\n *\n * - Low S Signature: A signature where the `s` component is in the lower half of the range,\n * specifically less than or equal to `n/2`.\n *\n * - High S Signature: This is where the `s` component is in the upper half of the range, greater\n * than `n/2`.\n *\n * The practical implication is that a third-party can forge a second valid signature for the same\n * message by negating the `s` component of the original signature, without any knowledge of the\n * private key. This is known as a \"signature malleability\" attack.\n *\n * This type of forgery is not a problem in all systems, but it can be an issue in systems that\n * rely on digital signature uniqueness to ensure transaction integrity. For example, in Bitcoin,\n * transaction malleability is an issue because it allows for the modification of transaction\n * identifiers (and potentially, transactions themselves) after they're signed but before they're\n * confirmed in a block. By enforcing low `s` values, the Bitcoin network reduces the likelihood of\n * this occurring, making the system more secure and predictable.\n *\n * For this reason, it's common practice to normalize ECDSA signatures to a low-S form. This\n * form is considered standard and preferable in some systems and is known as the \"normalized\"\n * form of the signature.\n *\n * This method takes a signature, and if it's high-S, returns the normalized low-S form. If the\n * signature is already low-S, it's returned unmodified. It's important to note that this\n * method does not change the validity of the signature but makes it compliant with systems that\n * enforce low-S signatures.\n *\n * @example\n * ```ts\n * const signature = new Uint8Array([...]); // Your ECDSA signature\n * const adjustedSignature = await Secp256k1.adjustSignatureToLowS({ signature });\n * // Now 'adjustedSignature' is in the low-S form.\n * ```\n *\n * @param params - The parameters for the signature adjustment.\n * @param params.signature - The ECDSA signature as a `Uint8Array`.\n *\n * @returns A Promise that resolves to the adjusted signature in low-S form as a `Uint8Array`.\n */\n public static async adjustSignatureToLowS({ signature }: {\n signature: Uint8Array;\n }): Promise<Uint8Array> {\n // Convert the signature to a `secp256k1.Signature` object.\n const signatureObject = secp256k1.Signature.fromCompact(signature);\n\n if (signatureObject.hasHighS()) {\n // Adjust the signature to low-S format if it's high-S.\n const adjustedSignatureObject = signatureObject.normalizeS();\n\n // Convert the adjusted signature object back to a byte array.\n const adjustedSignature = adjustedSignatureObject.toCompactRawBytes();\n\n return adjustedSignature;\n\n } else {\n // Return the unmodified signature if it is already in low-S format.\n return signature;\n }\n }\n\n /**\n * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n *\n * @remarks\n * This method takes a private key represented as a byte array (Uint8Array) and\n * converts it into a JWK object. The conversion involves extracting the\n * elliptic curve point (x and y coordinates) from the private key and encoding\n * them into base64url format, alongside other JWK parameters.\n *\n * The resulting JWK object includes the following properties:\n * - `kty`: Key Type, set to 'EC' for Elliptic Curve.\n * - `crv`: Curve Name, set to 'secp256k1'.\n * - `d`: The private key component, base64url-encoded.\n * - `x`: The x-coordinate of the public key point, base64url-encoded.\n * - `y`: The y-coordinate of the public key point, base64url-encoded.\n *\n * This method is useful for converting raw public keys into a standardized\n * JSON format, facilitating their use in cryptographic operations and making\n * them easy to share and store.\n *\n * @example\n * ```ts\n * const privateKeyBytes = new Uint8Array([...]); // Replace with actual private key bytes\n * const privateKey = await Secp256k1.bytesToPrivateKey({ privateKeyBytes });\n * ```\n *\n * @param params - The parameters for the private key conversion.\n * @param params.privateKeyBytes - The raw private key as a Uint8Array.\n *\n * @returns A Promise that resolves to the private key in JWK format.\n */\n public static async bytesToPrivateKey({ privateKeyBytes }: {\n privateKeyBytes: Uint8Array;\n }): Promise<Jwk> {\n // Get the elliptic curve point (x and y coordinates) for the provided private key.\n const point = await Secp256k1.getCurvePoint({ keyBytes: privateKeyBytes });\n\n // Construct the private key in JWK format.\n const privateKey: Jwk = {\n kty : 'EC',\n crv : 'secp256k1',\n d : Convert.uint8Array(privateKeyBytes).toBase64Url(),\n x : Convert.uint8Array(point.x).toBase64Url(),\n y : Convert.uint8Array(point.y).toBase64Url()\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Converts a raw public key in bytes to its corresponding JSON Web Key (JWK) format.\n *\n * @remarks\n * This method accepts a public key in a byte array (Uint8Array) format and\n * transforms it to a JWK object. It involves decoding the elliptic curve point\n * (x and y coordinates) from the raw public key bytes and encoding them into\n * base64url format, along with setting appropriate JWK parameters.\n *\n * The resulting JWK object includes the following properties:\n * - `kty`: Key Type, set to 'EC' for Elliptic Curve.\n * - `crv`: Curve Name, set to 'secp256k1'.\n * - `x`: The x-coordinate of the public key point, base64url-encoded.\n * - `y`: The y-coordinate of the public key point, base64url-encoded.\n *\n * This method is useful for converting raw public keys into a standardized\n * JSON format, facilitating their use in cryptographic operations and making\n * them easy to share and store.\n *\n * @example\n * ```ts\n * const publicKeyBytes = new Uint8Array([...]); // Replace with actual public key bytes\n * const publicKey = await Secp256k1.bytesToPublicKey({ publicKeyBytes });\n * ```\n *\n * @param params - The parameters for the public key conversion.\n * @param params.publicKeyBytes - The raw public key as a Uint8Array.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public static async bytesToPublicKey({ publicKeyBytes }: {\n publicKeyBytes: Uint8Array;\n }): Promise<Jwk> {\n // Get the elliptic curve point (x and y coordinates) for the provided public key.\n const point = await Secp256k1.getCurvePoint({ keyBytes: publicKeyBytes });\n\n // Construct the public key in JWK format.\n const publicKey: Jwk = {\n kty : 'EC',\n crv : 'secp256k1',\n x : Convert.uint8Array(point.x).toBase64Url(),\n y : Convert.uint8Array(point.y).toBase64Url()\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Converts a public key to its compressed form.\n *\n * @remarks\n * This method takes a public key represented as a byte array and compresses it. Public key\n * compression is a process that reduces the size of the public key by removing the y-coordinate,\n * making it more efficient for storage and transmission. The compressed key retains the same\n * level of security as the uncompressed key.\n *\n * @example\n * ```ts\n * const uncompressedPublicKeyBytes = new Uint8Array([...]); // Replace with actual uncompressed public key bytes\n * const compressedPublicKey = await Secp256k1.compressPublicKey({\n * publicKeyBytes: uncompressedPublicKeyBytes\n * });\n * ```\n *\n * @param params - The parameters for the public key compression.\n * @param params.publicKeyBytes - The public key as a Uint8Array.\n *\n * @returns A Promise that resolves to the compressed public key as a Uint8Array.\n */\n public static async compressPublicKey({ publicKeyBytes }: {\n publicKeyBytes: Uint8Array;\n }): Promise<Uint8Array> {\n // Decode Weierstrass points from the public key byte array.\n const point = secp256k1.ProjectivePoint.fromHex(publicKeyBytes);\n\n // Return the compressed form of the public key.\n return point.toRawBytes(true);\n }\n\n /**\n * Derives the public key in JWK format from a given private key.\n *\n * @remarks\n * This method takes a private key in JWK format and derives its corresponding public key,\n * also in JWK format. The derivation process involves converting the private key to a raw\n * byte array, then computing the elliptic curve point (x and y coordinates) from this private\n * key. These coordinates are then encoded into base64url format to construct the public key in\n * JWK format.\n *\n * The process ensures that the derived public key correctly corresponds to the given private key,\n * adhering to the secp256k1 elliptic curve standards. This method is useful in cryptographic\n * operations where a public key is needed for operations like signature verification, but only\n * the private key is available.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // A Jwk object representing a secp256k1 private key\n * const publicKey = await Secp256k1.computePublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for the public key derivation.\n * @param params.key - The private key in JWK format from which to derive the public key.\n *\n * @returns A Promise that resolves to the derived public key in JWK format.\n */\n public static async computePublicKey({ key }:\n ComputePublicKeyParams\n ): Promise<Jwk> {\n // Convert the provided private key to a byte array.\n const privateKeyBytes = await Secp256k1.privateKeyToBytes({ privateKey: key });\n\n // Get the elliptic curve point (x and y coordinates) for the provided private key.\n const point = await Secp256k1.getCurvePoint({ keyBytes: privateKeyBytes });\n\n // Construct the public key in JWK format.\n const publicKey: Jwk = {\n kty : 'EC',\n crv : 'secp256k1',\n x : Convert.uint8Array(point.x).toBase64Url(),\n y : Convert.uint8Array(point.y).toBase64Url()\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Converts an ASN.1 DER encoded ECDSA signature to a compact R+S format.\n *\n * @remarks\n * This method is used for converting an ECDSA signature from the ASN.1 DER encoding to the more\n * compact R+S format. This conversion is often required when dealing with ECDSA signatures in\n * certain cryptographic standards such as JWS (JSON Web Signature).\n *\n * The method decodes the DER-encoded signature, extracts the R and S values, and concatenates\n * them into a single byte array. This process involves handling the ASN.1 structure to correctly\n * parse the R and S values, considering padding and integer encoding specifics of DER.\n *\n * @example\n * ```ts\n * const derSignature = new Uint8Array([...]); // Replace with your DER-encoded signature\n * const signature = await Secp256k1.convertDerToCompactSignature({ derSignature });\n * ```\n *\n * @param params - The parameters for the signature conversion.\n * @param params.derSignature - The signature in ASN.1 DER format as a `Uint8Array`.\n *\n * @returns A Promise that resolves to the signature in compact R+S format as a `Uint8Array`.\n */\n public static async convertDerToCompactSignature({ derSignature }: {\n derSignature: Uint8Array;\n }): Promise<Uint8Array> {\n // Convert the DER-encoded signature into a `secp256k1.Signature` object.\n // This involves parsing the ASN.1 DER structure to extract the R and S components.\n const signatureObject = secp256k1.Signature.fromDER(derSignature);\n\n // Convert the signature object into compact R+S format, which concatenates the R and S values\n // into a single byte array.\n const compactSignature = signatureObject.toCompactRawBytes();\n\n return compactSignature;\n }\n\n /**\n * Converts a public key to its uncompressed form.\n *\n * @remarks\n * This method takes a compressed public key represented as a byte array and decompresses it.\n * Public key decompression involves reconstructing the y-coordinate from the x-coordinate,\n * resulting in the full public key. This method is used when the uncompressed key format is\n * required for certain cryptographic operations or interoperability.\n *\n * @example\n * ```ts\n * const compressedPublicKeyBytes = new Uint8Array([...]); // Replace with actual compressed public key bytes\n * const decompressedPublicKey = await Secp256k1.decompressPublicKey({\n * publicKeyBytes: compressedPublicKeyBytes\n * });\n * ```\n *\n * @param params - The parameters for the public key decompression.\n * @param params.publicKeyBytes - The public key as a Uint8Array.\n *\n * @returns A Promise that resolves to the uncompressed public key as a Uint8Array.\n */\n public static async decompressPublicKey({ publicKeyBytes }: {\n publicKeyBytes: Uint8Array;\n }): Promise<Uint8Array> {\n // Decode Weierstrass points from the public key byte array.\n const point = secp256k1.ProjectivePoint.fromHex(publicKeyBytes);\n\n // Return the uncompressed form of the public key.\n return point.toRawBytes(false);\n }\n\n /**\n * Generates a secp256k1 private key in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method creates a new private key suitable for use with the secp256k1\n * elliptic curve. The key is generated using cryptographically secure random\n * number generation to ensure its uniqueness and security. The resulting\n * private key adheres to the JWK format, specifically tailored for secp256k1,\n * making it compatible with common cryptographic standards and easy to use in\n * various cryptographic processes.\n *\n * The private key generated by this method includes the following components:\n * - `kty`: Key Type, set to 'EC' for Elliptic Curve.\n * - `crv`: Curve Name, set to 'secp256k1'.\n * - `d`: The private key component, base64url-encoded.\n * - `x`: The x-coordinate of the public key point, derived from the private key, base64url-encoded.\n * - `y`: The y-coordinate of the public key point, derived from the private key, base64url-encoded.\n *\n * The key is returned in a format suitable for direct use in signin and key agreement operations.\n *\n * @example\n * ```ts\n * const privateKey = await Secp256k1.generateKey();\n * ```\n *\n * @returns A Promise that resolves to the generated private key in JWK format.\n */\n public static async generateKey(): Promise<Jwk> {\n // Generate a random private key.\n const privateKeyBytes = secp256k1.utils.randomPrivateKey();\n\n // Convert private key from bytes to JWK format.\n const privateKey = await Secp256k1.bytesToPrivateKey({ privateKeyBytes });\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Retrieves the public key properties from a given private key in JWK format.\n *\n * @remarks\n * This method extracts the public key portion from a secp256k1 private key in JWK format. It does\n * so by removing the private key property 'd' and making a shallow copy, effectively yielding the\n * public key. The method sets the 'kid' (key ID) property using the JWK thumbprint if it is not\n * already defined. This approach is used under the assumption that a private key in JWK format\n * always contains the corresponding public key properties.\n *\n * Note: This method offers a significant performance advantage, being about 200 times faster\n * than `computePublicKey()`. However, it does not mathematically validate the private key, nor\n * does it derive the public key from the private key. It simply extracts existing public key\n * properties from the private key object. This makes it suitable for scenarios where speed is\n * critical and the private key's integrity is already assured.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // A Jwk object representing a secp256k1 private key\n * const publicKey = await Secp256k1.getPublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for retrieving the public key properties.\n * @param params.key - The private key in JWK format.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public static async getPublicKey({ key }:\n GetPublicKeyParams\n ): Promise<Jwk> {\n // Verify the provided JWK represents an elliptic curve (EC) secp256k1 private key.\n if (!(isEcPrivateJwk(key) && key.crv === 'secp256k1')) {\n throw new Error(`Secp256k1: The provided key is not a secp256k1 private JWK.`);\n }\n\n // Remove the private key property ('d') and make a shallow copy of the provided key.\n const { d, ...publicKey } = key;\n\n // If the key ID is undefined, set it to the JWK thumbprint.\n publicKey.kid ??= await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n *\n * @remarks\n * This method takes a private key in JWK format and extracts its raw byte representation.\n * It specifically focuses on the 'd' parameter of the JWK, which represents the private\n * key component in base64url encoding. The method decodes this value into a byte array.\n *\n * This conversion is essential for operations that require the private key in its raw\n * binary form, such as certain low-level cryptographic operations or when interfacing\n * with systems and libraries that expect keys in a byte array format.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // An X25519 private key in JWK format\n * const privateKeyBytes = await Secp256k1.privateKeyToBytes({ privateKey });\n * ```\n *\n * @param params - The parameters for the private key conversion.\n * @param params.privateKey - The private key in JWK format.\n *\n * @returns A Promise that resolves to the private key as a Uint8Array.\n */\n public static async privateKeyToBytes({ privateKey }: {\n privateKey: Jwk;\n }): Promise<Uint8Array> {\n // Verify the provided JWK represents a valid EC secp256k1 private key.\n if (!isEcPrivateJwk(privateKey)) {\n throw new Error(`Secp256k1: The provided key is not a valid EC private key.`);\n }\n\n // Decode the provided private key to bytes.\n const privateKeyBytes = Convert.base64Url(privateKey.d).toUint8Array();\n\n return privateKeyBytes;\n }\n\n /**\n * Converts a public key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n *\n * @remarks\n * This method accepts a public key in JWK format and converts it into its raw binary\n * form. The conversion process involves decoding the 'x' and 'y' parameters of the JWK\n * (which represent the x and y coordinates of the elliptic curve point, respectively)\n * from base64url format into a byte array. The method then concatenates these values,\n * along with a prefix indicating the key format, to form the full public key.\n *\n * This function is particularly useful for use cases where the public key is needed\n * in its raw byte format, such as for certain cryptographic operations or when\n * interfacing with systems that require raw key formats.\n *\n * @example\n * ```ts\n * const publicKey = { ... }; // A Jwk public key object\n * const publicKeyBytes = await Secp256k1.publicKeyToBytes({ publicKey });\n * ```\n *\n * @param params - The parameters for the public key conversion.\n * @param params.publicKey - The public key in JWK format.\n *\n * @returns A Promise that resolves to the public key as a Uint8Array.\n */\n public static async publicKeyToBytes({ publicKey }: {\n publicKey: Jwk;\n }): Promise<Uint8Array> {\n // Verify the provided JWK represents a valid EC secp256k1 public key, which must have a 'y' value.\n if (!(isEcPublicJwk(publicKey) && publicKey.y)) {\n throw new Error(`Secp256k1: The provided key is not a valid EC public key.`);\n }\n\n // Decode the provided public key to bytes.\n const prefix = new Uint8Array([0x04]); // Designates an uncompressed key.\n const x = Convert.base64Url(publicKey.x).toUint8Array();\n const y = Convert.base64Url(publicKey.y).toUint8Array();\n\n // Concatenate the prefix, x-coordinate, and y-coordinate as a single byte array.\n const publicKeyBytes = new Uint8Array([...prefix, ...x, ...y]);\n\n return publicKeyBytes;\n }\n\n /**\n * Computes an RFC6090-compliant Elliptic Curve Diffie-Hellman (ECDH) shared secret\n * using secp256k1 private and public keys in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method facilitates the ECDH key agreement protocol, which is a method of securely\n * deriving a shared secret between two parties based on their private and public keys.\n * It takes the private key of one party (privateKeyA) and the public key of another\n * party (publicKeyB) to compute a shared secret. The shared secret is derived from the\n * x-coordinate of the elliptic curve point resulting from the multiplication of the\n * public key with the private key.\n *\n * Note: When performing Elliptic Curve Diffie-Hellman (ECDH) key agreement,\n * the resulting shared secret is a point on the elliptic curve, which\n * consists of an x-coordinate and a y-coordinate. With a 256-bit curve like\n * secp256k1, each of these coordinates is 32 bytes (256 bits) long. However,\n * in the ECDH process, it's standard practice to use only the x-coordinate\n * of the shared secret point as the resulting shared key. This is because\n * the y-coordinate does not add to the entropy of the key, and both parties\n * can independently compute the x-coordinate. Consquently, this implementation\n * omits the y-coordinate for simplicity and standard compliance.\n *\n * @example\n * ```ts\n * const privateKeyA = { ... }; // A Jwk private key object for party A\n * const publicKeyB = { ... }; // A Jwk public key object for party B\n * const sharedSecret = await Secp256k1.sharedSecret({\n * privateKeyA,\n * publicKeyB\n * });\n * ```\n *\n * @param params - The parameters for the shared secret computation.\n * @param params.privateKeyA - The private key in JWK format of one party.\n * @param params.publicKeyB - The public key in JWK format of the other party.\n *\n * @returns A Promise that resolves to the computed shared secret as a Uint8Array.\n */\n public static async sharedSecret({ privateKeyA, publicKeyB }: {\n privateKeyA: Jwk;\n publicKeyB: Jwk;\n }): Promise<Uint8Array> {\n // Ensure that keys from the same key pair are not specified.\n if ('x' in privateKeyA && 'x' in publicKeyB && privateKeyA.x === publicKeyB.x) {\n throw new Error(`Secp256k1: ECDH shared secret cannot be computed from a single key pair's public and private keys.`);\n }\n\n // Convert the provided private and public keys to bytes.\n const privateKeyABytes = await Secp256k1.privateKeyToBytes({ privateKey: privateKeyA });\n const publicKeyBBytes = await Secp256k1.publicKeyToBytes({ publicKey: publicKeyB });\n\n // Compute the compact representation shared secret between the public and private keys.\n const sharedSecret = secp256k1.getSharedSecret(privateKeyABytes, publicKeyBBytes, true);\n\n // Remove the leading byte that indicates the sign of the y-coordinate\n // of the point on the elliptic curve. See note above.\n return sharedSecret.slice(1);\n }\n\n /**\n * Generates an RFC6979-compliant ECDSA signature of given data using a secp256k1 private key.\n *\n * @remarks\n * This method signs the provided data with a specified private key using the ECDSA\n * (Elliptic Curve Digital Signature Algorithm) signature algorithm, as defined in RFC6979.\n * The data to be signed is first hashed using the SHA-256 algorithm, and this hash is then\n * signed using the private key. The output is a digital signature in the form of a\n * Uint8Array, which uniquely corresponds to both the data and the private key used for signing.\n *\n * This method is commonly used in cryptographic applications to ensure data integrity and\n * authenticity. The signature can later be verified by parties with access to the corresponding\n * public key, ensuring that the data has not been tampered with and was indeed signed by the\n * holder of the private key.\n *\n * @example\n * ```ts\n * const data = new TextEncoder().encode('Messsage'); // Data to be signed\n * const privateKey = { ... }; // A Jwk object representing a secp256k1 private key\n * const signature = await Secp256k1.sign({\n * key: privateKey,\n * data\n * });\n * ```\n *\n * @param params - The parameters for the signing operation.\n * @param params.key - The private key to use for signing, represented in JWK format.\n * @param params.data - The data to sign, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to the signature as a Uint8Array.\n */\n public static async sign({ data, key }:\n SignParams\n ): Promise<Uint8Array> {\n // Convert the private key from JWK format to bytes.\n const privateKeyBytes = await Secp256k1.privateKeyToBytes({ privateKey: key });\n\n // Generate a digest of the data using the SHA-256 hash function.\n const digest = sha256(data);\n\n // Sign the provided data using the ECDSA algorithm.\n // The `secp256k1.sign` operation returns a signature object with { r, s, recovery } properties.\n const signatureObject = secp256k1.sign(digest, privateKeyBytes);\n\n // Convert the signature object to Uint8Array.\n const signature = signatureObject.toCompactRawBytes();\n\n return signature;\n }\n\n /**\n * Validates a given private key to ensure its compliance with the secp256k1 curve standards.\n *\n * @remarks\n * This method checks whether a provided private key is a valid 32-byte number and falls within\n * the range defined by the secp256k1 curve's order. It is essential for ensuring the private\n * key's mathematical correctness in the context of secp256k1-based cryptographic operations.\n *\n * Note that this validation strictly pertains to the key's format and numerical validity; it does\n * not assess whether the key corresponds to a known entity or its security status (e.g., whether\n * it has been compromised).\n *\n * @example\n * ```ts\n * const privateKeyBytes = new Uint8Array([...]); // A 32-byte private key\n * const isValid = await Secp256k1.validatePrivateKey({ privateKeyBytes });\n * console.log(isValid); // true or false based on the key's validity\n * ```\n *\n * @param params - The parameters for the key validation.\n * @param params.privateKeyBytes - The private key to validate, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to a boolean indicating whether the private key is valid.\n */\n public static async validatePrivateKey({ privateKeyBytes }: {\n privateKeyBytes: Uint8Array;\n }): Promise<boolean> {\n return secp256k1.utils.isValidPrivateKey(privateKeyBytes);\n }\n\n /**\n * Validates a given public key to confirm its mathematical correctness on the secp256k1 curve.\n *\n * @remarks\n * This method checks if the provided public key represents a valid point on the secp256k1 curve.\n * It decodes the key's Weierstrass points (x and y coordinates) and verifies their validity\n * against the curve's parameters. A valid point must lie on the curve and meet specific\n * mathematical criteria defined by the curve's equation.\n *\n * It's important to note that this method does not verify the key's ownership or whether it has\n * been compromised; it solely focuses on the key's adherence to the curve's mathematical\n * principles.\n *\n * @example\n * ```ts\n * const publicKeyBytes = new Uint8Array([...]); // A public key in byte format\n * const isValid = await Secp256k1.validatePublicKey({ publicKeyBytes });\n * console.log(isValid); // true if the key is valid on the secp256k1 curve, false otherwise\n * ```\n *\n * @param params - The parameters for the key validation.\n * @param params.publicKeyBytes - The public key to validate, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to a boolean indicating the public key's validity on\n * the secp256k1 curve.\n */\n public static async validatePublicKey({ publicKeyBytes }: {\n publicKeyBytes: Uint8Array;\n }): Promise<boolean> {\n try {\n // Decode Weierstrass points from key bytes.\n const point = secp256k1.ProjectivePoint.fromHex(publicKeyBytes);\n\n // Check if points are on the Short Weierstrass curve.\n point.assertValidity();\n\n } catch {\n return false;\n }\n\n return true;\n }\n\n /**\n * Verifies an RFC6979-compliant ECDSA signature against given data and a secp256k1 public key.\n *\n * @remarks\n * This method validates a digital signature to ensure that it was generated by the holder of the\n * corresponding private key and that the signed data has not been altered. The signature\n * verification is performed using the ECDSA (Elliptic Curve Digital Signature Algorithm) as\n * specified in RFC6979. The data to be verified is first hashed using the SHA-256 algorithm, and\n * this hash is then used along with the public key to verify the signature.\n *\n * The method returns a boolean value indicating whether the signature is valid. A valid signature\n * proves that the signed data was indeed signed by the owner of the private key corresponding to\n * the provided public key and that the data has not been tampered with since it was signed.\n *\n * Note: The verification process does not consider the malleability of low-s signatures, which\n * may be relevant in certain contexts, such as Bitcoin transactions.\n *\n * @example\n * ```ts\n * const data = new TextEncoder().encode('Messsage'); // Data that was signed\n * const publicKey = { ... }; // Public key in JWK format corresponding to the private key that signed the data\n * const signature = new Uint8Array([...]); // Signature to verify\n * const isSignatureValid = await Secp256k1.verify({\n * key: publicKey,\n * signature,\n * data\n * });\n * console.log(isSignatureValid); // true if the signature is valid, false otherwise\n * ```\n *\n * @param params - The parameters for the signature verification.\n * @param params.key - The public key used for verification, represented in JWK format.\n * @param params.signature - The signature to verify, represented as a Uint8Array.\n * @param params.data - The data that was signed, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to a boolean indicating whether the signature is valid.\n */\n public static async verify({ key, signature, data }:\n VerifyParams\n ): Promise<boolean> {\n // Convert the public key from JWK format to bytes.\n const publicKeyBytes = await Secp256k1.publicKeyToBytes({ publicKey: key });\n\n // Generate a digest of the data using the SHA-256 hash function.\n const digest = sha256(data);\n\n /** Perform the verification of the signature.\n * This verify operation has the malleability check disabled. Guaranteed support\n * for low-s signatures across languages is unlikely especially in the context\n * of SSI. Notable Cloud KMS providers do not natively support it either. It is\n * also worth noting that low-s signatures are a requirement for Bitcoin. */\n const isValid = secp256k1.verify(signature, digest, publicKeyBytes, { lowS: false });\n\n return isValid;\n }\n\n /**\n * Returns the elliptic curve point (x and y coordinates) for a given secp256k1 key.\n *\n * @remarks\n * This method extracts the elliptic curve point from a given secp256k1 key, whether\n * it's a private or a public key. For a private key, the method first computes the\n * corresponding public key and then extracts the x and y coordinates. For a public key,\n * it directly returns these coordinates. The coordinates are represented as Uint8Array.\n *\n * The x and y coordinates represent the key's position on the elliptic curve and can be\n * used in various cryptographic operations, such as digital signatures or key agreement\n * protocols.\n *\n * @example\n * ```ts\n * // For a private key\n * const privateKey = new Uint8Array([...]); // A 32-byte private key\n * const { x: xFromPrivateKey, y: yFromPrivateKey } = await Secp256k1.getCurvePoint({ keyBytes: privateKey });\n *\n * // For a public key\n * const publicKey = new Uint8Array([...]); // A 33-byte or 65-byte public key\n * const { x: xFromPublicKey, y: yFromPublicKey } = await Secp256k1.getCurvePoint({ keyBytes: publicKey });\n * ```\n *\n * @param params - The parameters for the curve point decoding operation.\n * @param params.keyBytes - The key for which to get the elliptic curve point.\n * Can be either a private key or a public key.\n * The key should be passed as a `Uint8Array`.\n *\n * @returns A Promise that resolves to an object with properties 'x' and 'y',\n * each being a Uint8Array representing the x and y coordinates of the key point on the\n * elliptic curve.\n */\n private static async getCurvePoint({ keyBytes }: {\n keyBytes: Uint8Array;\n }): Promise<AffinePoint<Uint8Array>> {\n // If key is a private key, first compute the public key.\n if (keyBytes.byteLength === 32) {\n keyBytes = secp256k1.getPublicKey(keyBytes);\n }\n\n // Decode Weierstrass affine point from key bytes.\n const point = secp256k1.ProjectivePoint.fromHex(keyBytes);\n\n // Get x- and y-coordinate values and convert to Uint8Array.\n const x = numberToBytesBE(point.x, 32);\n const y = numberToBytesBE(point.y, 32);\n\n return { x, y };\n }\n}", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { createCurve } from './_shortw_utils.js';\nimport { sha256 } from '@noble/hashes/sha256';\nimport { Field } from './abstract/modular.js';\nimport { mapToCurveSimpleSWU } from './abstract/weierstrass.js';\nimport { createHasher } from './abstract/hash-to-curve.js';\n\n// NIST secp256r1 aka p256\n// https://www.secg.org/sec2-v2.pdf, https://neuromancer.sk/std/nist/P-256\n\nconst Fp = Field(BigInt('0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff'));\nconst CURVE_A = Fp.create(BigInt('-3'));\nconst CURVE_B = BigInt('0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b');\n\n// prettier-ignore\nexport const p256 = createCurve({\n a: CURVE_A, // Equation params: a, b\n b: CURVE_B,\n Fp, // Field: 2n**224n * (2n**32n-1n) + 2n**192n + 2n**96n-1n\n // Curve order, total count of valid points in the field\n n: BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'),\n // Base (generator) point (x, y)\n Gx: BigInt('0x6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296'),\n Gy: BigInt('0x4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5'),\n h: BigInt(1),\n lowS: false,\n} as const, sha256);\nexport const secp256r1 = p256;\n\nconst mapSWU = /* @__PURE__ */ (() =>\n mapToCurveSimpleSWU(Fp, {\n A: CURVE_A,\n B: CURVE_B,\n Z: Fp.create(BigInt('-10')),\n }))();\n\nconst htf = /* @__PURE__ */ (() =>\n createHasher(secp256r1.ProjectivePoint, (scalars: bigint[]) => mapSWU(scalars[0]), {\n DST: 'P256_XMD:SHA-256_SSWU_RO_',\n encodeDST: 'P256_XMD:SHA-256_SSWU_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha256,\n }))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n", "import type { AffinePoint } from '@noble/curves/abstract/weierstrass';\n\nimport { Convert } from '@enbox/common';\nimport { numberToBytesBE } from '@noble/curves/abstract/utils';\nimport { secp256r1 } from '@noble/curves/p256';\nimport { sha256 } from '@noble/hashes/sha256';\n\nimport type { Jwk } from '../jose/jwk.js';\nimport type { ComputePublicKeyParams, GetPublicKeyParams, SignParams, VerifyParams } from '../types/params-direct.js';\n\nimport { computeJwkThumbprint, isEcPrivateJwk, isEcPublicJwk } from '../jose/jwk.js';\n\n/**\n * The `Secp256r1` class provides a comprehensive suite of utilities for working with\n * the secp256r1 (aka P-256) elliptic curve, commonly used in blockchain and cryptographic\n * applications. This class includes methods for key generation, conversion, signing, verification,\n * and Elliptic Curve Diffie-Hellman (ECDH) key agreement.\n *\n * The class supports conversions between raw byte formats and JSON Web Key (JWK) formats. It\n * adheres to RFC6979 for ECDSA signing and verification and RFC6090 for ECDH.\n *\n * Key Features:\n * - Key Generation: Generate secp256r1 private keys in JWK format.\n * - Key Conversion: Transform keys between raw byte arrays and JWK formats.\n * - Public Key Derivation: Derive public keys from private keys.\n * - ECDH Shared Secret Computation: Securely derive shared secrets using private and public keys.\n * - ECDSA Signing and Verification: Sign data and verify signatures with secp256r1 keys.\n * - Key Validation: Validate the mathematical correctness of secp256r1 keys.\n *\n * The methods in this class are asynchronous, returning Promises to accommodate various\n * JavaScript environments, and use `Uint8Array` for binary data handling.\n *\n * @example\n * ```ts\n * // Key Generation\n * const privateKey = await Secp256r1.generateKey();\n *\n * // Public Key Derivation\n * const publicKey = await Secp256r1.computePublicKey({ key: privateKey });\n * console.log(publicKey === await Secp256r1.getPublicKey({ key: privateKey })); // Output: true\n *\n * // ECDH Shared Secret Computation\n * const sharedSecret = await Secp256r1.sharedSecret({\n * privateKeyA: privateKey,\n * publicKeyB: anotherPublicKey\n * });\n *\n * // ECDSA Signing\n * const signature = await Secp256r1.sign({\n * key: privateKey,\n * data: new TextEncoder().encode('Message')\n * });\n *\n * // ECDSA Signature Verification\n * const isValid = await Secp256r1.verify({\n * key: publicKey,\n * signature: signature,\n * data: new TextEncoder().encode('Message')\n * });\n *\n * // Key Conversion\n * const publicKeyBytes = await Secp256r1.publicKeyToBytes({ publicKey });\n * const privateKeyBytes = await Secp256r1.privateKeyToBytes({ privateKey });\n * const compressedPublicKey = await Secp256r1.compressPublicKey({ publicKeyBytes });\n * const uncompressedPublicKey = await Secp256r1.decompressPublicKey({ publicKeyBytes });\n *\n * // Key Validation\n * const isPrivateKeyValid = await Secp256r1.validatePrivateKey({ privateKeyBytes });\n * const isPublicKeyValid = await Secp256r1.validatePublicKey({ publicKeyBytes });\n * ```\n */\nexport class Secp256r1 {\n/**\n * Adjusts an ECDSA signature to a normalized, low-S form.\n *\n * @remarks\n * All ECDSA signatures, regardless of the curve, consist of two components, `r` and `s`, both of\n * which are integers. The curve's order (the total number of points on the curve) is denoted by\n * `n`. In a valid ECDSA signature, both `r` and `s` must be in the range [1, n-1]. However, due\n * to the mathematical properties of ECDSA, if `(r, s)` is a valid signature, then `(r, n - s)` is\n * also a valid signature for the same message and public key. In other words, for every\n * signature, there's a \"mirror\" signature that's equally valid. For these elliptic curves:\n *\n * - Low S Signature: A signature where the `s` component is in the lower half of the range,\n * specifically less than or equal to `n/2`.\n *\n * - High S Signature: This is where the `s` component is in the upper half of the range, greater\n * than `n/2`.\n *\n * The practical implication is that a third-party can forge a second valid signature for the same\n * message by negating the `s` component of the original signature, without any knowledge of the\n * private key. This is known as a \"signature malleability\" attack.\n *\n * This type of forgery is not a problem in all systems, but it can be an issue in systems that\n * rely on digital signature uniqueness to ensure transaction integrity. For example, in Bitcoin,\n * transaction malleability is an issue because it allows for the modification of transaction\n * identifiers (and potentially, transactions themselves) after they're signed but before they're\n * confirmed in a block. By enforcing low `s` values, the Bitcoin network reduces the likelihood of\n * this occurring, making the system more secure and predictable.\n *\n * For this reason, it's common practice to normalize ECDSA signatures to a low-S form. This\n * form is considered standard and preferable in some systems and is known as the \"normalized\"\n * form of the signature.\n *\n * This method takes a signature, and if it's high-S, returns the normalized low-S form. If the\n * signature is already low-S, it's returned unmodified. It's important to note that this\n * method does not change the validity of the signature but makes it compliant with systems that\n * enforce low-S signatures.\n *\n * @example\n * ```ts\n * const signature = new Uint8Array([...]); // Your ECDSA signature\n * const adjustedSignature = await Secp256r1.adjustSignatureToLowS({ signature });\n * // Now 'adjustedSignature' is in the low-S form.\n * ```\n *\n * @param params - The parameters for the signature adjustment.\n * @param params.signature - The ECDSA signature as a `Uint8Array`.\n *\n * @returns A Promise that resolves to the adjusted signature in low-S form as a `Uint8Array`.\n */\n public static async adjustSignatureToLowS({ signature }: {\n signature: Uint8Array;\n }): Promise<Uint8Array> {\n // Convert the signature to a `Secp256r1.Signature` object.\n const signatureObject = secp256r1.Signature.fromCompact(signature);\n\n if (signatureObject.hasHighS()) {\n // Adjust the signature to low-S format if it's high-S.\n const adjustedSignatureObject = signatureObject.normalizeS();\n\n // Convert the adjusted signature object back to a byte array.\n const adjustedSignature = adjustedSignatureObject.toCompactRawBytes();\n\n return adjustedSignature;\n\n } else {\n // Return the unmodified signature if it is already in low-S format.\n return signature;\n }\n }\n\n /**\n * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n *\n * @remarks\n * This method takes a private key represented as a byte array (Uint8Array) and\n * converts it into a JWK object. The conversion involves extracting the\n * elliptic curve point (x and y coordinates) from the private key and encoding\n * them into base64url format, alongside other JWK parameters.\n *\n * The resulting JWK object includes the following properties:\n * - `kty`: Key Type, set to 'EC' for Elliptic Curve.\n * - `crv`: Curve Name, set to 'P-256'.\n * - `d`: The private key component, base64url-encoded.\n * - `x`: The x-coordinate of the public key point, base64url-encoded.\n * - `y`: The y-coordinate of the public key point, base64url-encoded.\n *\n * This method is useful for converting raw public keys into a standardized\n * JSON format, facilitating their use in cryptographic operations and making\n * them easy to share and store.\n *\n * @example\n * ```ts\n * const privateKeyBytes = new Uint8Array([...]); // Replace with actual private key bytes\n * const privateKey = await Secp256r1.bytesToPrivateKey({ privateKeyBytes });\n * ```\n *\n * @param params - The parameters for the private key conversion.\n * @param params.privateKeyBytes - The raw private key as a Uint8Array.\n *\n * @returns A Promise that resolves to the private key in JWK format.\n */\n public static async bytesToPrivateKey({ privateKeyBytes }: {\n privateKeyBytes: Uint8Array;\n }): Promise<Jwk> {\n // Get the elliptic curve points (x and y coordinates) for the provided private key.\n const point = await Secp256r1.getCurvePoint({ keyBytes: privateKeyBytes });\n\n // Construct the private key in JWK format.\n const privateKey: Jwk = {\n kty : 'EC',\n crv : 'P-256',\n d : Convert.uint8Array(privateKeyBytes).toBase64Url(),\n x : Convert.uint8Array(point.x).toBase64Url(),\n y : Convert.uint8Array(point.y).toBase64Url()\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Converts a raw public key in bytes to its corresponding JSON Web Key (JWK) format.\n *\n * @remarks\n * This method accepts a public key in a byte array (Uint8Array) format and\n * transforms it to a JWK object. It involves decoding the elliptic curve point\n * (x and y coordinates) from the raw public key bytes and encoding them into\n * base64url format, along with setting appropriate JWK parameters.\n *\n * The resulting JWK object includes the following properties:\n * - `kty`: Key Type, set to 'EC' for Elliptic Curve.\n * - `crv`: Curve Name, set to 'P-256'.\n * - `x`: The x-coordinate of the public key point, base64url-encoded.\n * - `y`: The y-coordinate of the public key point, base64url-encoded.\n *\n * This method is useful for converting raw public keys into a standardized\n * JSON format, facilitating their use in cryptographic operations and making\n * them easy to share and store.\n *\n * @example\n * ```ts\n * const publicKeyBytes = new Uint8Array([...]); // Replace with actual public key bytes\n * const publicKey = await Secp256r1.bytesToPublicKey({ publicKeyBytes });\n * ```\n *\n * @param params - The parameters for the public key conversion.\n * @param params.publicKeyBytes - The raw public key as a Uint8Array.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public static async bytesToPublicKey({ publicKeyBytes }: {\n publicKeyBytes: Uint8Array;\n }): Promise<Jwk> {\n // Get the elliptic curve point (x and y coordinates) for the provided public key.\n const point = await Secp256r1.getCurvePoint({ keyBytes: publicKeyBytes });\n\n // Construct the public key in JWK format.\n const publicKey: Jwk = {\n kty : 'EC',\n crv : 'P-256',\n x : Convert.uint8Array(point.x).toBase64Url(),\n y : Convert.uint8Array(point.y).toBase64Url()\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Converts a public key to its compressed form.\n *\n * @remarks\n * This method takes a public key represented as a byte array and compresses it. Public key\n * compression is a process that reduces the size of the public key by removing the y-coordinate,\n * making it more efficient for storage and transmission. The compressed key retains the same\n * level of security as the uncompressed key.\n *\n * @example\n * ```ts\n * const uncompressedPublicKeyBytes = new Uint8Array([...]); // Replace with actual uncompressed public key bytes\n * const compressedPublicKey = await Secp256r1.compressPublicKey({\n * publicKeyBytes: uncompressedPublicKeyBytes\n * });\n * ```\n *\n * @param params - The parameters for the public key compression.\n * @param params.publicKeyBytes - The public key as a Uint8Array.\n *\n * @returns A Promise that resolves to the compressed public key as a Uint8Array.\n */\n public static async compressPublicKey({ publicKeyBytes }: {\n publicKeyBytes: Uint8Array;\n }): Promise<Uint8Array> {\n // Decode Weierstrass points from the public key byte array.\n const point = secp256r1.ProjectivePoint.fromHex(publicKeyBytes);\n\n // Return the compressed form of the public key.\n return point.toRawBytes(true);\n }\n\n /**\n * Derives the public key in JWK format from a given private key.\n *\n * @remarks\n * This method takes a private key in JWK format and derives its corresponding public key,\n * also in JWK format. The derivation process involves converting the private key to a raw\n * byte array, then computing the elliptic curve point (x and y coordinates) from this private\n * key. These coordinates are then encoded into base64url format to construct the public key in\n * JWK format.\n *\n * The process ensures that the derived public key correctly corresponds to the given private key,\n * adhering to the secp256r1 elliptic curve standards. This method is useful in cryptographic\n * operations where a public key is needed for operations like signature verification, but only\n * the private key is available.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // A Jwk object representing a secp256r1 private key\n * const publicKey = await Secp256r1.computePublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for the public key derivation.\n * @param params.key - The private key in JWK format from which to derive the public key.\n *\n * @returns A Promise that resolves to the derived public key in JWK format.\n */\n public static async computePublicKey({ key }:\n ComputePublicKeyParams\n ): Promise<Jwk> {\n // Convert the provided private key to a byte array.\n const privateKeyBytes = await Secp256r1.privateKeyToBytes({ privateKey: key });\n\n // Get the elliptic curve point (x and y coordinates) for the provided private key.\n const point = await Secp256r1.getCurvePoint({ keyBytes: privateKeyBytes });\n\n // Construct the public key in JWK format.\n const publicKey: Jwk = {\n kty : 'EC',\n crv : 'P-256',\n x : Convert.uint8Array(point.x).toBase64Url(),\n y : Convert.uint8Array(point.y).toBase64Url()\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Converts an ASN.1 DER encoded ECDSA signature to a compact R+S format.\n *\n * @remarks\n * This method is used for converting an ECDSA signature from the ASN.1 DER encoding to the more\n * compact R+S format. This conversion is often required when dealing with ECDSA signatures in\n * certain cryptographic standards such as JWS (JSON Web Signature).\n *\n * The method decodes the DER-encoded signature, extracts the R and S values, and concatenates\n * them into a single byte array. This process involves handling the ASN.1 structure to correctly\n * parse the R and S values, considering padding and integer encoding specifics of DER.\n *\n * @example\n * ```ts\n * const derSignature = new Uint8Array([...]); // Replace with your DER-encoded signature\n * const signature = await Secp256r1.convertDerToCompactSignature({ derSignature });\n * ```\n *\n * @param params - The parameters for the signature conversion.\n * @param params.derSignature - The signature in ASN.1 DER format as a `Uint8Array`.\n *\n * @returns A Promise that resolves to the signature in compact R+S format as a `Uint8Array`.\n */\n public static async convertDerToCompactSignature({ derSignature }: {\n derSignature: Uint8Array;\n }): Promise<Uint8Array> {\n // Convert the DER-encoded signature into a `Secp256r1.Signature` object.\n // This involves parsing the ASN.1 DER structure to extract the R and S components.\n const signatureObject = secp256r1.Signature.fromDER(derSignature);\n\n // Convert the signature object into compact R+S format, which concatenates the R and S values\n // into a single byte array.\n const compactSignature = signatureObject.toCompactRawBytes();\n\n return compactSignature;\n }\n\n /**\n * Converts a public key to its uncompressed form.\n *\n * @remarks\n * This method takes a compressed public key represented as a byte array and decompresses it.\n * Public key decompression involves reconstructing the y-coordinate from the x-coordinate,\n * resulting in the full public key. This method is used when the uncompressed key format is\n * required for certain cryptographic operations or interoperability.\n *\n * @example\n * ```ts\n * const compressedPublicKeyBytes = new Uint8Array([...]); // Replace with actual compressed public key bytes\n * const decompressedPublicKey = await Secp256r1.decompressPublicKey({\n * publicKeyBytes: compressedPublicKeyBytes\n * });\n * ```\n *\n * @param params - The parameters for the public key decompression.\n * @param params.publicKeyBytes - The public key as a Uint8Array.\n *\n * @returns A Promise that resolves to the uncompressed public key as a Uint8Array.\n */\n public static async decompressPublicKey({ publicKeyBytes }: {\n publicKeyBytes: Uint8Array;\n }): Promise<Uint8Array> {\n // Decode Weierstrass points from the public key byte array.\n const point = secp256r1.ProjectivePoint.fromHex(publicKeyBytes);\n\n // Return the uncompressed form of the public key.\n return point.toRawBytes(false);\n }\n\n /**\n * Generates a secp256r1 private key in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method creates a new private key suitable for use with the secp256r1\n * elliptic curve. The key is generated using cryptographically secure random\n * number generation to ensure its uniqueness and security. The resulting\n * private key adheres to the JWK format, specifically tailored for secp256r1,\n * making it compatible with common cryptographic standards and easy to use in\n * various cryptographic processes.\n *\n * The private key generated by this method includes the following components:\n * - `kty`: Key Type, set to 'EC' for Elliptic Curve.\n * - `crv`: Curve Name, set to 'P-256'.\n * - `d`: The private key component, base64url-encoded.\n * - `x`: The x-coordinate of the public key point, derived from the private key, base64url-encoded.\n * - `y`: The y-coordinate of the public key point, derived from the private key, base64url-encoded.\n *\n * The key is returned in a format suitable for direct use in signin and key agreement operations.\n *\n * @example\n * ```ts\n * const privateKey = await Secp256r1.generateKey();\n * ```\n *\n * @returns A Promise that resolves to the generated private key in JWK format.\n */\n public static async generateKey(): Promise<Jwk> {\n // Generate a random private key.\n const privateKeyBytes = secp256r1.utils.randomPrivateKey();\n\n // Convert private key from bytes to JWK format.\n const privateKey = await Secp256r1.bytesToPrivateKey({ privateKeyBytes });\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Retrieves the public key properties from a given private key in JWK format.\n *\n * @remarks\n * This method extracts the public key portion from a secp256r1 private key in JWK format. It does\n * so by removing the private key property 'd' and making a shallow copy, effectively yielding the\n * public key. The method sets the 'kid' (key ID) property using the JWK thumbprint if it is not\n * already defined. This approach is used under the assumption that a private key in JWK format\n * always contains the corresponding public key properties.\n *\n * Note: This method offers a significant performance advantage, being about 200 times faster\n * than `computePublicKey()`. However, it does not mathematically validate the private key, nor\n * does it derive the public key from the private key. It simply extracts existing public key\n * properties from the private key object. This makes it suitable for scenarios where speed is\n * critical and the private key's integrity is already assured.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // A Jwk object representing a secp256r1 private key\n * const publicKey = await Secp256r1.getPublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for retrieving the public key properties.\n * @param params.key - The private key in JWK format.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public static async getPublicKey({ key }:\n GetPublicKeyParams\n ): Promise<Jwk> {\n // Verify the provided JWK represents an elliptic curve (EC) secp256r1 private key.\n if (!(isEcPrivateJwk(key) && key.crv === 'P-256')) {\n throw new Error(`Secp256r1: The provided key is not a 'P-256' private JWK.`);\n }\n\n // Remove the private key property ('d') and make a shallow copy of the provided key.\n const { d, ...publicKey } = key;\n\n // If the key ID is undefined, set it to the JWK thumbprint.\n publicKey.kid ??= await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n *\n * @remarks\n * This method takes a private key in JWK format and extracts its raw byte representation.\n * It specifically focuses on the 'd' parameter of the JWK, which represents the private\n * key component in base64url encoding. The method decodes this value into a byte array.\n *\n * This conversion is essential for operations that require the private key in its raw\n * binary form, such as certain low-level cryptographic operations or when interfacing\n * with systems and libraries that expect keys in a byte array format.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // An X25519 private key in JWK format\n * const privateKeyBytes = await Secp256r1.privateKeyToBytes({ privateKey });\n * ```\n *\n * @param params - The parameters for the private key conversion.\n * @param params.privateKey - The private key in JWK format.\n *\n * @returns A Promise that resolves to the private key as a Uint8Array.\n */\n public static async privateKeyToBytes({ privateKey }: {\n privateKey: Jwk;\n }): Promise<Uint8Array> {\n // Verify the provided JWK represents a valid EC P-256 private key.\n if (!isEcPrivateJwk(privateKey)) {\n throw new Error(`Secp256r1: The provided key is not a valid EC private key.`);\n }\n\n // Decode the provided private key to bytes.\n const privateKeyBytes = Convert.base64Url(privateKey.d).toUint8Array();\n\n return privateKeyBytes;\n }\n\n /**\n * Converts a public key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n *\n * @remarks\n * This method accepts a public key in JWK format and converts it into its raw binary\n * form. The conversion process involves decoding the 'x' and 'y' parameters of the JWK\n * (which represent the x and y coordinates of the elliptic curve point, respectively)\n * from base64url format into a byte array. The method then concatenates these values,\n * along with a prefix indicating the key format, to form the full public key.\n *\n * This function is particularly useful for use cases where the public key is needed\n * in its raw byte format, such as for certain cryptographic operations or when\n * interfacing with systems that require raw key formats.\n *\n * @example\n * ```ts\n * const publicKey = { ... }; // A Jwk public key object\n * const publicKeyBytes = await Secp256r1.publicKeyToBytes({ publicKey });\n * ```\n *\n * @param params - The parameters for the public key conversion.\n * @param params.publicKey - The public key in JWK format.\n *\n * @returns A Promise that resolves to the public key as a Uint8Array.\n */\n public static async publicKeyToBytes({ publicKey }: {\n publicKey: Jwk;\n }): Promise<Uint8Array> {\n // Verify the provided JWK represents a valid EC P-256 public key, which must have a 'y' value.\n if (!(isEcPublicJwk(publicKey) && publicKey.y)) {\n throw new Error(`Secp256r1: The provided key is not a valid EC public key.`);\n }\n\n // Decode the provided public key to bytes.\n const prefix = new Uint8Array([0x04]); // Designates an uncompressed key.\n const x = Convert.base64Url(publicKey.x).toUint8Array();\n const y = Convert.base64Url(publicKey.y).toUint8Array();\n\n // Concatenate the prefix, x-coordinate, and y-coordinate as a single byte array.\n const publicKeyBytes = new Uint8Array([...prefix, ...x, ...y]);\n\n return publicKeyBytes;\n }\n\n /**\n * Computes an RFC6090-compliant Elliptic Curve Diffie-Hellman (ECDH) shared secret\n * using secp256r1 private and public keys in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method facilitates the ECDH key agreement protocol, which is a method of securely\n * deriving a shared secret between two parties based on their private and public keys.\n * It takes the private key of one party (privateKeyA) and the public key of another\n * party (publicKeyB) to compute a shared secret. The shared secret is derived from the\n * x-coordinate of the elliptic curve point resulting from the multiplication of the\n * public key with the private key.\n *\n * Note: When performing Elliptic Curve Diffie-Hellman (ECDH) key agreement,\n * the resulting shared secret is a point on the elliptic curve, which\n * consists of an x-coordinate and a y-coordinate. With a 256-bit curve like\n * secp256r1, each of these coordinates is 32 bytes (256 bits) long. However,\n * in the ECDH process, it's standard practice to use only the x-coordinate\n * of the shared secret point as the resulting shared key. This is because\n * the y-coordinate does not add to the entropy of the key, and both parties\n * can independently compute the x-coordinate. Consquently, this implementation\n * omits the y-coordinate for simplicity and standard compliance.\n *\n * @example\n * ```ts\n * const privateKeyA = { ... }; // A Jwk private key object for party A\n * const publicKeyB = { ... }; // A Jwk public key object for party B\n * const sharedSecret = await Secp256r1.sharedSecret({\n * privateKeyA,\n * publicKeyB\n * });\n * ```\n *\n * @param params - The parameters for the shared secret computation.\n * @param params.privateKeyA - The private key in JWK format of one party.\n * @param params.publicKeyB - The public key in JWK format of the other party.\n *\n * @returns A Promise that resolves to the computed shared secret as a Uint8Array.\n */\n public static async sharedSecret({ privateKeyA, publicKeyB }: {\n privateKeyA: Jwk;\n publicKeyB: Jwk;\n }): Promise<Uint8Array> {\n // Ensure that keys from the same key pair are not specified.\n if ('x' in privateKeyA && 'x' in publicKeyB && privateKeyA.x === publicKeyB.x) {\n throw new Error(`Secp256r1: ECDH shared secret cannot be computed from a single key pair's public and private keys.`);\n }\n\n // Convert the provided private and public keys to bytes.\n const privateKeyABytes = await Secp256r1.privateKeyToBytes({ privateKey: privateKeyA });\n const publicKeyBBytes = await Secp256r1.publicKeyToBytes({ publicKey: publicKeyB });\n\n // Compute the compact representation shared secret between the public and private keys.\n const sharedSecret = secp256r1.getSharedSecret(privateKeyABytes, publicKeyBBytes, true);\n\n // Remove the leading byte that indicates the sign of the y-coordinate\n // of the point on the elliptic curve. See note above.\n return sharedSecret.slice(1);\n }\n\n /**\n * Generates an RFC6979-compliant ECDSA signature of given data using a secp256r1 private key.\n *\n * @remarks\n * This method signs the provided data with a specified private key using the ECDSA\n * (Elliptic Curve Digital Signature Algorithm) signature algorithm, as defined in RFC6979.\n * The data to be signed is first hashed using the SHA-256 algorithm, and this hash is then\n * signed using the private key. The output is a digital signature in the form of a\n * Uint8Array, which uniquely corresponds to both the data and the private key used for signing.\n *\n * This method is commonly used in cryptographic applications to ensure data integrity and\n * authenticity. The signature can later be verified by parties with access to the corresponding\n * public key, ensuring that the data has not been tampered with and was indeed signed by the\n * holder of the private key.\n *\n * @example\n * ```ts\n * const data = new TextEncoder().encode('Messsage'); // Data to be signed\n * const privateKey = { ... }; // A Jwk object representing a secp256r1 private key\n * const signature = await Secp256r1.sign({\n * key: privateKey,\n * data\n * });\n * ```\n *\n * @param params - The parameters for the signing operation.\n * @param params.key - The private key to use for signing, represented in JWK format.\n * @param params.data - The data to sign, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to the signature as a Uint8Array.\n */\n public static async sign({ data, key }:\n SignParams\n ): Promise<Uint8Array> {\n // Convert the private key from JWK format to bytes.\n const privateKeyBytes = await Secp256r1.privateKeyToBytes({ privateKey: key });\n\n // Generate a digest of the data using the SHA-256 hash function.\n const digest = sha256(data);\n\n // Sign the provided data using the ECDSA algorithm.\n // The `Secp256r1.sign` operation returns a signature object with { r, s, recovery } properties.\n const signatureObject = secp256r1.sign(digest, privateKeyBytes);\n\n // Convert the signature object to Uint8Array.\n const signature = signatureObject.toCompactRawBytes();\n\n return signature;\n }\n\n /**\n * Validates a given private key to ensure its compliance with the secp256r1 curve standards.\n *\n * @remarks\n * This method checks whether a provided private key is a valid 32-byte number and falls within\n * the range defined by the secp256r1 curve's order. It is essential for ensuring the private\n * key's mathematical correctness in the context of secp256r1-based cryptographic operations.\n *\n * Note that this validation strictly pertains to the key's format and numerical validity; it does\n * not assess whether the key corresponds to a known entity or its security status (e.g., whether\n * it has been compromised).\n *\n * @example\n * ```ts\n * const privateKeyBytes = new Uint8Array([...]); // A 32-byte private key\n * const isValid = await Secp256r1.validatePrivateKey({ privateKeyBytes });\n * console.log(isValid); // true or false based on the key's validity\n * ```\n *\n * @param params - The parameters for the key validation.\n * @param params.privateKeyBytes - The private key to validate, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to a boolean indicating whether the private key is valid.\n */\n public static async validatePrivateKey({ privateKeyBytes }: {\n privateKeyBytes: Uint8Array;\n }): Promise<boolean> {\n return secp256r1.utils.isValidPrivateKey(privateKeyBytes);\n }\n\n /**\n * Validates a given public key to confirm its mathematical correctness on the secp256r1 curve.\n *\n * @remarks\n * This method checks if the provided public key represents a valid point on the secp256r1 curve.\n * It decodes the key's Weierstrass points (x and y coordinates) and verifies their validity\n * against the curve's parameters. A valid point must lie on the curve and meet specific\n * mathematical criteria defined by the curve's equation.\n *\n * It's important to note that this method does not verify the key's ownership or whether it has\n * been compromised; it solely focuses on the key's adherence to the curve's mathematical\n * principles.\n *\n * @example\n * ```ts\n * const publicKeyBytes = new Uint8Array([...]); // A public key in byte format\n * const isValid = await Secp256r1.validatePublicKey({ publicKeyBytes });\n * console.log(isValid); // true if the key is valid on the secp256r1 curve, false otherwise\n * ```\n *\n * @param params - The parameters for the key validation.\n * @param params.publicKeyBytes - The public key to validate, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to a boolean indicating the public key's validity on\n * the secp256r1 curve.\n */\n public static async validatePublicKey({ publicKeyBytes }: {\n publicKeyBytes: Uint8Array;\n }): Promise<boolean> {\n try {\n // Decode Weierstrass points from key bytes.\n const point = secp256r1.ProjectivePoint.fromHex(publicKeyBytes);\n\n // Check if points are on the Short Weierstrass curve.\n point.assertValidity();\n\n } catch {\n return false;\n }\n\n return true;\n }\n\n /**\n * Verifies an RFC6979-compliant ECDSA signature against given data and a secp256r1 public key.\n *\n * @remarks\n * This method validates a digital signature to ensure that it was generated by the holder of the\n * corresponding private key and that the signed data has not been altered. The signature\n * verification is performed using the ECDSA (Elliptic Curve Digital Signature Algorithm) as\n * specified in RFC6979. The data to be verified is first hashed using the SHA-256 algorithm, and\n * this hash is then used along with the public key to verify the signature.\n *\n * The method returns a boolean value indicating whether the signature is valid. A valid signature\n * proves that the signed data was indeed signed by the owner of the private key corresponding to\n * the provided public key and that the data has not been tampered with since it was signed.\n *\n * Note: The verification process does not consider the malleability of low-s signatures, which\n * may be relevant in certain contexts, such as Bitcoin transactions.\n *\n * @example\n * ```ts\n * const data = new TextEncoder().encode('Messsage'); // Data that was signed\n * const publicKey = { ... }; // Public key in JWK format corresponding to the private key that signed the data\n * const signature = new Uint8Array([...]); // Signature to verify\n * const isSignatureValid = await Secp256r1.verify({\n * key: publicKey,\n * signature,\n * data\n * });\n * console.log(isSignatureValid); // true if the signature is valid, false otherwise\n * ```\n *\n * @param params - The parameters for the signature verification.\n * @param params.key - The public key used for verification, represented in JWK format.\n * @param params.signature - The signature to verify, represented as a Uint8Array.\n * @param params.data - The data that was signed, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to a boolean indicating whether the signature is valid.\n */\n public static async verify({ key, signature, data }:\n VerifyParams\n ): Promise<boolean> {\n // Convert the public key from JWK format to bytes.\n const publicKeyBytes = await Secp256r1.publicKeyToBytes({ publicKey: key });\n\n // Generate a digest of the data using the SHA-256 hash function.\n const digest = sha256(data);\n\n /** Perform the verification of the signature.\n * This verify operation has the malleability check disabled. Guaranteed support\n * for low-s signatures across languages is unlikely especially in the context\n * of SSI. Notable Cloud KMS providers do not natively support it either. It is\n * also worth noting that low-s signatures are a requirement for Bitcoin. */\n const isValid = secp256r1.verify(signature, digest, publicKeyBytes, { lowS: false });\n\n return isValid;\n }\n\n /**\n * Returns the elliptic curve point (x and y coordinates) for a given secp256r1 key.\n *\n * @remarks\n * This method extracts the elliptic curve point from a given secp256r1 key, whether\n * it's a private or a public key. For a private key, the method first computes the\n * corresponding public key and then extracts the x and y coordinates. For a public key,\n * it directly returns these coordinates. The coordinates are represented as Uint8Array.\n *\n * The x and y coordinates represent the key's position on the elliptic curve and can be\n * used in various cryptographic operations, such as digital signatures or key agreement\n * protocols.\n *\n * @example\n * ```ts\n * // For a private key\n * const privateKey = new Uint8Array([...]); // A 32-byte private key\n * const { x: xFromPrivateKey, y: yFromPrivateKey } = await Secp256r1.getCurvePoint({ keyBytes: privateKey });\n *\n * // For a public key\n * const publicKey = new Uint8Array([...]); // A 33-byte or 65-byte public key\n * const { x: xFromPublicKey, y: yFromPublicKey } = await Secp256r1.getCurvePoint({ keyBytes: publicKey });\n * ```\n *\n * @param params - The parameters for the curve point decoding operation.\n * @param params.keyBytes - The key for which to get the elliptic curve point.\n * Can be either a private key or a public key.\n * The key should be passed as a `Uint8Array`.\n *\n * @returns A Promise that resolves to an object with properties 'x' and 'y',\n * each being a Uint8Array representing the x and y coordinates of the key point on the\n * elliptic curve.\n */\n private static async getCurvePoint({ keyBytes }: {\n keyBytes: Uint8Array;\n }): Promise<AffinePoint<Uint8Array>> {\n // If key is a private key, first compute the public key.\n if (keyBytes.byteLength === 32) {\n keyBytes = secp256r1.getPublicKey(keyBytes);\n }\n\n // Decode Weierstrass affine point from key bytes.\n const point = secp256r1.ProjectivePoint.fromHex(keyBytes);\n\n // Get x- and y-coordinate values and convert to Uint8Array.\n const x = numberToBytesBE(point.x, 32);\n const y = numberToBytesBE(point.y, 32);\n\n return { x, y };\n }\n}\n\nexport { Secp256r1 as P256 };", "import type { AsymmetricKeyGenerator } from '../types/key-generator.js';\nimport type { Jwk } from '../jose/jwk.js';\nimport type { Signer } from '../types/signer.js';\nimport type {\n ComputePublicKeyParams,\n GenerateKeyParams,\n GetPublicKeyParams,\n SignParams,\n VerifyParams,\n} from '../types/params-direct.js';\n\nimport { CryptoAlgorithm } from './crypto-algorithm.js';\nimport { Secp256k1 } from '../primitives/secp256k1.js';\nimport { Secp256r1 } from '../primitives/secp256r1.js';\nimport { isEcPrivateJwk, isEcPublicJwk } from '../jose/jwk.js';\n\n/**\n * The `EcdsaGenerateKeyParams` interface defines the algorithm-specific parameters that should be\n * passed into the `generateKey()` method when using the ECDSA algorithm.\n */\nexport interface EcdsaGenerateKeyParams extends GenerateKeyParams {\n /**\n * A string defining the type of key to generate. The value must be one of the following:\n * - `\"ES256\"`: ECDSA using the secp256r1 (P-256) curve and SHA-256.\n * - `\"ES256K\"`: ECDSA using the secp256k1 curve and SHA-256.\n * - `\"secp256k1\"`: ECDSA using the secp256k1 curve and SHA-256.\n * - `\"secp256r1\"`: ECDSA using the secp256r1 (P-256) curve and SHA-256.\n */\n algorithm: 'ES256' | 'ES256K' | 'secp256k1' | 'secp256r1';\n}\n\n/**\n * The `EcdsaAlgorithm` class provides a concrete implementation for cryptographic operations using\n * the Elliptic Curve Digital Signature Algorithm (ECDSA). This class implements both\n * {@link Signer | `Signer`} and { @link AsymmetricKeyGenerator | `AsymmetricKeyGenerator`}\n * interfaces, providing private key generation, public key derivation, and creation/verification\n * of signatures.\n *\n * This class is typically accessed through implementations that extend the\n * {@link CryptoApi | `CryptoApi`} interface.\n */\nexport class EcdsaAlgorithm extends CryptoAlgorithm\n implements AsymmetricKeyGenerator<EcdsaGenerateKeyParams, Jwk, GetPublicKeyParams>,\n Signer<SignParams, VerifyParams> {\n\n /**\n * Derives the public key in JWK format from a given private key.\n *\n * @remarks\n * This method takes a private key in JWK format and derives its corresponding public key,\n * also in JWK format. The process ensures that the derived public key correctly corresponds to\n * the given private key.\n *\n * @example\n * ```ts\n * const ecdsa = new EcdsaAlgorithm();\n * const privateKey = { ... }; // A Jwk object representing a private key\n * const publicKey = await ecdsa.computePublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for the public key derivation.\n * @param params.key - The private key in JWK format from which to derive the public key.\n *\n * @returns A Promise that resolves to the derived public key in JWK format.\n */\n public async computePublicKey({ key }:\n ComputePublicKeyParams\n ): Promise<Jwk> {\n if (!isEcPrivateJwk(key)) {throw new TypeError('Invalid key provided. Must be an elliptic curve (EC) private key.');}\n\n switch (key.crv) {\n\n case 'secp256k1': {\n const publicKey = await Secp256k1.computePublicKey({ key });\n publicKey.alg = 'ES256K';\n return publicKey;\n }\n\n case 'P-256': {\n const publicKey = await Secp256r1.computePublicKey({ key });\n publicKey.alg = 'ES256';\n return publicKey;\n }\n\n default: {\n throw new Error(`Unsupported curve: ${key.crv}`);\n }\n }\n }\n\n /**\n * Generates a new private key with the specified algorithm in JSON Web Key (JWK) format.\n *\n * @example\n * ```ts\n * const ecdsa = new EcdsaAlgorithm();\n * const privateKey = await ecdsa.generateKey({ algorithm: 'ES256K' });\n * ```\n *\n * @param params - The parameters for key generation.\n * @param params.algorithm - The algorithm to use for key generation.\n *\n * @returns A Promise that resolves to the generated private key in JWK format.\n */\n public async generateKey({ algorithm }:\n EcdsaGenerateKeyParams\n ): Promise<Jwk> {\n switch (algorithm) {\n\n case 'ES256K':\n case 'secp256k1': {\n const privateKey = await Secp256k1.generateKey();\n privateKey.alg = 'ES256K';\n return privateKey;\n }\n\n case 'ES256':\n case 'secp256r1': {\n const privateKey = await Secp256r1.generateKey();\n privateKey.alg = 'ES256';\n return privateKey;\n }\n }\n }\n\n /**\n * Retrieves the public key properties from a given private key in JWK format.\n *\n * @remarks\n * This method extracts the public key portion from an ECDSA private key in JWK format. It does\n * so by removing the private key property 'd' and making a shallow copy, effectively yielding the\n * public key.\n *\n * Note: This method offers a significant performance advantage, being about 200 times faster\n * than `computePublicKey()`. However, it does not mathematically validate the private key, nor\n * does it derive the public key from the private key. It simply extracts existing public key\n * properties from the private key object. This makes it suitable for scenarios where speed is\n * critical and the private key's integrity is already assured.\n *\n * @example\n * ```ts\n * const ecdsa = new EcdsaAlgorithm();\n * const privateKey = { ... }; // A Jwk object representing a private key\n * const publicKey = await ecdsa.getPublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for retrieving the public key properties.\n * @param params.key - The private key in JWK format.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public async getPublicKey({ key }:\n GetPublicKeyParams\n ): Promise<Jwk> {\n if (!isEcPrivateJwk(key)) {throw new TypeError('Invalid key provided. Must be an elliptic curve (EC) private key.');}\n\n switch (key.crv) {\n\n case 'secp256k1': {\n const publicKey = await Secp256k1.getPublicKey({ key });\n publicKey.alg = 'ES256K';\n return publicKey;\n }\n\n case 'P-256': {\n const publicKey = await Secp256r1.getPublicKey({ key });\n publicKey.alg = 'ES256';\n return publicKey;\n }\n\n default: {\n throw new Error(`Unsupported curve: ${key.crv}`);\n }\n }\n }\n\n /**\n * Generates an ECDSA signature of given data using a private key.\n *\n * @remarks\n * This method uses the signature algorithm determined by the given `algorithm` to sign the\n * provided data.\n *\n * The signature can later be verified by parties with access to the corresponding\n * public key, ensuring that the data has not been tampered with and was indeed signed by the\n * holder of the private key.\n *\n * @example\n * ```ts\n * const ecdsa = new EcdsaAlgorithm();\n * const data = new TextEncoder().encode('Message');\n * const privateKey = { ... }; // A Jwk object representing a private key\n * const signature = await ecdsa.sign({\n * key: privateKey,\n * data\n * });\n * ```\n *\n * @param params - The parameters for the signing operation.\n * @param params.key - The private key to use for signing, represented in JWK format.\n * @param params.data - The data to sign.\n *\n * @returns A Promise resolving to the digital signature as a `Uint8Array`.\n */\n public async sign({ key, data }:\n SignParams\n ): Promise<Uint8Array> {\n if (!isEcPrivateJwk(key)) {throw new TypeError('Invalid key provided. Must be an elliptic curve (EC) private key.');}\n\n switch (key.crv) {\n\n case 'secp256k1': {\n return await Secp256k1.sign({ key, data });\n }\n\n case 'P-256': {\n return await Secp256r1.sign({ key, data });\n }\n\n default: {\n throw new Error(`Unsupported curve: ${key.crv}`);\n }\n }\n }\n\n /**\n * Verifies an ECDSA signature associated with the provided data using the provided key.\n *\n * @remarks\n * This method uses the signature algorithm determined by the `crv` property of the provided key\n * to check the validity of a digital signature against the original data. It confirms whether the\n * signature was created by the holder of the corresponding private key and that the data has not\n * been tampered with.\n *s\n * @example\n * ```ts\n * const ecdsa = new EcdsaAlgorithm();\n * const publicKey = { ... }; // Public key in JWK format corresponding to the private key that signed the data\n * const signature = new Uint8Array([...]); // Signature to verify\n * const data = new TextEncoder().encode('Message');\n * const isValid = await ecdsa.verify({\n * key: publicKey,\n * signature,\n * data\n * });\n * ```\n *\n * @param params - The parameters for the verification operation.\n * @param params.key - The key to use for verification.\n * @param params.signature - The signature to verify.\n * @param params.data - The data to verify.\n *\n * @returns A Promise resolving to a boolean indicating whether the signature is valid.\n */\n public async verify({ key, signature, data }:\n VerifyParams\n ): Promise<boolean> {\n if (!isEcPublicJwk(key)) {throw new TypeError('Invalid key provided. Must be an elliptic curve (EC) public key.');}\n\n switch (key.crv) {\n\n case 'secp256k1': {\n return await Secp256k1.verify({ key, signature, data });\n }\n\n case 'P-256': {\n return await Secp256r1.verify({ key, signature, data });\n }\n\n default: {\n throw new Error(`Unsupported curve: ${key.crv}`);\n }\n }\n }\n}", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { sha512 } from '@noble/hashes/sha512';\nimport { concatBytes, randomBytes, utf8ToBytes } from '@noble/hashes/utils';\nimport { ExtPointType, twistedEdwards } from './abstract/edwards.js';\nimport { montgomery } from './abstract/montgomery.js';\nimport { Field, FpSqrtEven, isNegativeLE, mod, pow2 } from './abstract/modular.js';\nimport {\n bytesToHex,\n bytesToNumberLE,\n ensureBytes,\n equalBytes,\n Hex,\n numberToBytesLE,\n} from './abstract/utils.js';\nimport { createHasher, htfBasicOpts, expand_message_xmd } from './abstract/hash-to-curve.js';\nimport { AffinePoint, Group } from './abstract/curve.js';\n\n/**\n * ed25519 Twisted Edwards curve with following addons:\n * - X25519 ECDH\n * - Ristretto cofactor elimination\n * - Elligator hash-to-group / point indistinguishability\n */\n\nconst ED25519_P = BigInt(\n '57896044618658097711785492504343953926634992332820282019728792003956564819949'\n);\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\nconst ED25519_SQRT_M1 = BigInt(\n '19681161376707505956807079304988542015446066515923890162744021073123829784752'\n);\n\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _5n = BigInt(5);\n// prettier-ignore\nconst _10n = BigInt(10), _20n = BigInt(20), _40n = BigInt(40), _80n = BigInt(80);\n\nfunction ed25519_pow_2_252_3(x: bigint) {\n const P = ED25519_P;\n const x2 = (x * x) % P;\n const b2 = (x2 * x) % P; // x^3, 11\n const b4 = (pow2(b2, _2n, P) * b2) % P; // x^15, 1111\n const b5 = (pow2(b4, _1n, P) * x) % P; // x^31\n const b10 = (pow2(b5, _5n, P) * b5) % P;\n const b20 = (pow2(b10, _10n, P) * b10) % P;\n const b40 = (pow2(b20, _20n, P) * b20) % P;\n const b80 = (pow2(b40, _40n, P) * b40) % P;\n const b160 = (pow2(b80, _80n, P) * b80) % P;\n const b240 = (pow2(b160, _80n, P) * b80) % P;\n const b250 = (pow2(b240, _10n, P) * b10) % P;\n const pow_p_5_8 = (pow2(b250, _2n, P) * x) % P;\n // ^ To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n}\n\nfunction adjustScalarBytes(bytes: Uint8Array): Uint8Array {\n // Section 5: For X25519, in order to decode 32 random bytes as an integer scalar,\n // set the three least significant bits of the first byte\n bytes[0] &= 248; // 0b1111_1000\n // and the most significant bit of the last to zero,\n bytes[31] &= 127; // 0b0111_1111\n // set the second most significant bit of the last byte to 1\n bytes[31] |= 64; // 0b0100_0000\n return bytes;\n}\n\n// sqrt(u/v)\nfunction uvRatio(u: bigint, v: bigint): { isValid: boolean; value: bigint } {\n const P = ED25519_P;\n const v3 = mod(v * v * v, P); // v\u00B3\n const v7 = mod(v3 * v3 * v, P); // v\u2077\n // (p+3)/8 and (p-5)/8\n const pow = ed25519_pow_2_252_3(u * v7).pow_p_5_8;\n let x = mod(u * v3 * pow, P); // (uv\u00B3)(uv\u2077)^(p-5)/8\n const vx2 = mod(v * x * x, P); // vx\u00B2\n const root1 = x; // First root candidate\n const root2 = mod(x * ED25519_SQRT_M1, P); // Second root candidate\n const useRoot1 = vx2 === u; // If vx\u00B2 = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u, P); // If vx\u00B2 = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * ED25519_SQRT_M1, P); // There is no valid root, vx\u00B2 = -u\u221A(-1)\n if (useRoot1) x = root1;\n if (useRoot2 || noRoot) x = root2; // We return root2 anyway, for const-time\n if (isNegativeLE(x, P)) x = mod(-x, P);\n return { isValid: useRoot1 || useRoot2, value: x };\n}\n\n// Just in case\nexport const ED25519_TORSION_SUBGROUP = [\n '0100000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a',\n '0000000000000000000000000000000000000000000000000000000000000080',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05',\n 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f',\n '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85',\n '0000000000000000000000000000000000000000000000000000000000000000',\n 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa',\n];\n\nconst Fp = Field(ED25519_P, undefined, true);\n\nconst ed25519Defaults = {\n // Param: a\n a: BigInt(-1), // Fp.create(-1) is proper; our way still works and is faster\n // d is equal to -121665/121666 over finite field.\n // Negative number is P - number, and division is invert(number, P)\n d: BigInt('37095705934669439343138083508754565189542113879843219016388785533085940283555'),\n // Finite field \uD835\uDD3Dp over which we'll do calculations; 2n**255n - 19n\n Fp,\n // Subgroup order: how many points curve has\n // 2n**252n + 27742317777372353535851937790883648493n;\n n: BigInt('7237005577332262213973186563042994240857116359379907606001950938285454250989'),\n // Cofactor\n h: BigInt(8),\n // Base point (x, y) aka generator point\n Gx: BigInt('15112221349535400772501151409588531511454012693041857206046113283949847762202'),\n Gy: BigInt('46316835694926478169428394003475163141307993866256225615783033603165251855960'),\n hash: sha512,\n randomBytes,\n adjustScalarBytes,\n // dom2\n // Ratio of u to v. Allows us to combine inversion and square root. Uses algo from RFC8032 5.1.3.\n // Constant-time, u/\u221Av\n uvRatio,\n} as const;\n\nexport const ed25519 = /* @__PURE__ */ twistedEdwards(ed25519Defaults);\n\nfunction ed25519_domain(data: Uint8Array, ctx: Uint8Array, phflag: boolean) {\n if (ctx.length > 255) throw new Error('Context is too big');\n return concatBytes(\n utf8ToBytes('SigEd25519 no Ed25519 collisions'),\n new Uint8Array([phflag ? 1 : 0, ctx.length]),\n ctx,\n data\n );\n}\n\nexport const ed25519ctx = /* @__PURE__ */ twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n});\nexport const ed25519ph = /* @__PURE__ */ twistedEdwards({\n ...ed25519Defaults,\n domain: ed25519_domain,\n prehash: sha512,\n});\n\nexport const x25519 = /* @__PURE__ */ (() =>\n montgomery({\n P: ED25519_P,\n a: BigInt(486662),\n montgomeryBits: 255, // n is 253 bits\n nByteLength: 32,\n Gu: BigInt(9),\n powPminus2: (x: bigint): bigint => {\n const P = ED25519_P;\n // x^(p-2) aka x^(2^255-21)\n const { pow_p_5_8, b2 } = ed25519_pow_2_252_3(x);\n return mod(pow2(pow_p_5_8, BigInt(3), P) * b2, P);\n },\n adjustScalarBytes,\n randomBytes,\n }))();\n\n/**\n * Converts ed25519 public key to x25519 public key. Uses formula:\n * * `(u, v) = ((1+y)/(1-y), sqrt(-486664)*u/x)`\n * * `(x, y) = (sqrt(-486664)*u/v, (u-1)/(u+1))`\n * @example\n * const someonesPub = ed25519.getPublicKey(ed25519.utils.randomPrivateKey());\n * const aPriv = x25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(aPriv, edwardsToMontgomeryPub(someonesPub))\n */\nexport function edwardsToMontgomeryPub(edwardsPub: Hex): Uint8Array {\n const { y } = ed25519.ExtendedPoint.fromHex(edwardsPub);\n const _1n = BigInt(1);\n return Fp.toBytes(Fp.create((_1n + y) * Fp.inv(_1n - y)));\n}\nexport const edwardsToMontgomery = edwardsToMontgomeryPub; // deprecated\n\n/**\n * Converts ed25519 secret key to x25519 secret key.\n * @example\n * const someonesPub = x25519.getPublicKey(x25519.utils.randomPrivateKey());\n * const aPriv = ed25519.utils.randomPrivateKey();\n * x25519.getSharedSecret(edwardsToMontgomeryPriv(aPriv), someonesPub)\n */\nexport function edwardsToMontgomeryPriv(edwardsPriv: Uint8Array): Uint8Array {\n const hashed = ed25519Defaults.hash(edwardsPriv.subarray(0, 32));\n return ed25519Defaults.adjustScalarBytes(hashed).subarray(0, 32);\n}\n\n// Hash To Curve Elligator2 Map (NOTE: different from ristretto255 elligator)\n// NOTE: very important part is usage of FpSqrtEven for ELL2_C1_EDWARDS, since\n// SageMath returns different root first and everything falls apart\n\nconst ELL2_C1 = (Fp.ORDER + BigInt(3)) / BigInt(8); // 1. c1 = (q + 3) / 8 # Integer arithmetic\n\nconst ELL2_C2 = Fp.pow(_2n, ELL2_C1); // 2. c2 = 2^c1\nconst ELL2_C3 = Fp.sqrt(Fp.neg(Fp.ONE)); // 3. c3 = sqrt(-1)\nconst ELL2_C4 = (Fp.ORDER - BigInt(5)) / BigInt(8); // 4. c4 = (q - 5) / 8 # Integer arithmetic\nconst ELL2_J = BigInt(486662);\n\n// prettier-ignore\nfunction map_to_curve_elligator2_curve25519(u: bigint) {\n let tv1 = Fp.sqr(u); // 1. tv1 = u^2\n tv1 = Fp.mul(tv1, _2n); // 2. tv1 = 2 * tv1\n let xd = Fp.add(tv1, Fp.ONE); // 3. xd = tv1 + 1 # Nonzero: -1 is square (mod p), tv1 is not\n let x1n = Fp.neg(ELL2_J); // 4. x1n = -J # x1 = x1n / xd = -J / (1 + 2 * u^2)\n let tv2 = Fp.sqr(xd); // 5. tv2 = xd^2\n let gxd = Fp.mul(tv2, xd); // 6. gxd = tv2 * xd # gxd = xd^3\n let gx1 = Fp.mul(tv1, ELL2_J); // 7. gx1 = J * tv1 # x1n + J * xd\n gx1 = Fp.mul(gx1, x1n); // 8. gx1 = gx1 * x1n # x1n^2 + J * x1n * xd\n gx1 = Fp.add(gx1, tv2); // 9. gx1 = gx1 + tv2 # x1n^2 + J * x1n * xd + xd^2\n gx1 = Fp.mul(gx1, x1n); // 10. gx1 = gx1 * x1n # x1n^3 + J * x1n^2 * xd + x1n * xd^2\n let tv3 = Fp.sqr(gxd); // 11. tv3 = gxd^2\n tv2 = Fp.sqr(tv3); // 12. tv2 = tv3^2 # gxd^4\n tv3 = Fp.mul(tv3, gxd); // 13. tv3 = tv3 * gxd # gxd^3\n tv3 = Fp.mul(tv3, gx1); // 14. tv3 = tv3 * gx1 # gx1 * gxd^3\n tv2 = Fp.mul(tv2, tv3); // 15. tv2 = tv2 * tv3 # gx1 * gxd^7\n let y11 = Fp.pow(tv2, ELL2_C4); // 16. y11 = tv2^c4 # (gx1 * gxd^7)^((p - 5) / 8)\n y11 = Fp.mul(y11, tv3); // 17. y11 = y11 * tv3 # gx1*gxd^3*(gx1*gxd^7)^((p-5)/8)\n let y12 = Fp.mul(y11, ELL2_C3); // 18. y12 = y11 * c3\n tv2 = Fp.sqr(y11); // 19. tv2 = y11^2\n tv2 = Fp.mul(tv2, gxd); // 20. tv2 = tv2 * gxd\n let e1 = Fp.eql(tv2, gx1); // 21. e1 = tv2 == gx1\n let y1 = Fp.cmov(y12, y11, e1); // 22. y1 = CMOV(y12, y11, e1) # If g(x1) is square, this is its sqrt\n let x2n = Fp.mul(x1n, tv1); // 23. x2n = x1n * tv1 # x2 = x2n / xd = 2 * u^2 * x1n / xd\n let y21 = Fp.mul(y11, u); // 24. y21 = y11 * u\n y21 = Fp.mul(y21, ELL2_C2); // 25. y21 = y21 * c2\n let y22 = Fp.mul(y21, ELL2_C3); // 26. y22 = y21 * c3\n let gx2 = Fp.mul(gx1, tv1); // 27. gx2 = gx1 * tv1 # g(x2) = gx2 / gxd = 2 * u^2 * g(x1)\n tv2 = Fp.sqr(y21); // 28. tv2 = y21^2\n tv2 = Fp.mul(tv2, gxd); // 29. tv2 = tv2 * gxd\n let e2 = Fp.eql(tv2, gx2); // 30. e2 = tv2 == gx2\n let y2 = Fp.cmov(y22, y21, e2); // 31. y2 = CMOV(y22, y21, e2) # If g(x2) is square, this is its sqrt\n tv2 = Fp.sqr(y1); // 32. tv2 = y1^2\n tv2 = Fp.mul(tv2, gxd); // 33. tv2 = tv2 * gxd\n let e3 = Fp.eql(tv2, gx1); // 34. e3 = tv2 == gx1\n let xn = Fp.cmov(x2n, x1n, e3); // 35. xn = CMOV(x2n, x1n, e3) # If e3, x = x1, else x = x2\n let y = Fp.cmov(y2, y1, e3); // 36. y = CMOV(y2, y1, e3) # If e3, y = y1, else y = y2\n let e4 = Fp.isOdd(y); // 37. e4 = sgn0(y) == 1 # Fix sign of y\n y = Fp.cmov(y, Fp.neg(y), e3 !== e4); // 38. y = CMOV(y, -y, e3 XOR e4)\n return { xMn: xn, xMd: xd, yMn: y, yMd: _1n }; // 39. return (xn, xd, y, 1)\n}\n\nconst ELL2_C1_EDWARDS = FpSqrtEven(Fp, Fp.neg(BigInt(486664))); // sgn0(c1) MUST equal 0\nfunction map_to_curve_elligator2_edwards25519(u: bigint) {\n const { xMn, xMd, yMn, yMd } = map_to_curve_elligator2_curve25519(u); // 1. (xMn, xMd, yMn, yMd) =\n // map_to_curve_elligator2_curve25519(u)\n let xn = Fp.mul(xMn, yMd); // 2. xn = xMn * yMd\n xn = Fp.mul(xn, ELL2_C1_EDWARDS); // 3. xn = xn * c1\n let xd = Fp.mul(xMd, yMn); // 4. xd = xMd * yMn # xn / xd = c1 * xM / yM\n let yn = Fp.sub(xMn, xMd); // 5. yn = xMn - xMd\n let yd = Fp.add(xMn, xMd); // 6. yd = xMn + xMd # (n / d - 1) / (n / d + 1) = (n - d) / (n + d)\n let tv1 = Fp.mul(xd, yd); // 7. tv1 = xd * yd\n let e = Fp.eql(tv1, Fp.ZERO); // 8. e = tv1 == 0\n xn = Fp.cmov(xn, Fp.ZERO, e); // 9. xn = CMOV(xn, 0, e)\n xd = Fp.cmov(xd, Fp.ONE, e); // 10. xd = CMOV(xd, 1, e)\n yn = Fp.cmov(yn, Fp.ONE, e); // 11. yn = CMOV(yn, 1, e)\n yd = Fp.cmov(yd, Fp.ONE, e); // 12. yd = CMOV(yd, 1, e)\n\n const inv = Fp.invertBatch([xd, yd]); // batch division\n return { x: Fp.mul(xn, inv[0]), y: Fp.mul(yn, inv[1]) }; // 13. return (xn, xd, yn, yd)\n}\n\nconst htf = /* @__PURE__ */ (() =>\n createHasher(\n ed25519.ExtendedPoint,\n (scalars: bigint[]) => map_to_curve_elligator2_edwards25519(scalars[0]),\n {\n DST: 'edwards25519_XMD:SHA-512_ELL2_RO_',\n encodeDST: 'edwards25519_XMD:SHA-512_ELL2_NU_',\n p: Fp.ORDER,\n m: 1,\n k: 128,\n expand: 'xmd',\n hash: sha512,\n }\n ))();\nexport const hashToCurve = /* @__PURE__ */ (() => htf.hashToCurve)();\nexport const encodeToCurve = /* @__PURE__ */ (() => htf.encodeToCurve)();\n\nfunction assertRstPoint(other: unknown) {\n if (!(other instanceof RistPoint)) throw new Error('RistrettoPoint expected');\n}\n\n// \u221A(-1) aka \u221A(a) aka 2^((p-1)/4)\nconst SQRT_M1 = ED25519_SQRT_M1;\n// \u221A(ad - 1)\nconst SQRT_AD_MINUS_ONE = BigInt(\n '25063068953384623474111414158702152701244531502492656460079210482610430750235'\n);\n// 1 / \u221A(a-d)\nconst INVSQRT_A_MINUS_D = BigInt(\n '54469307008909316920995813868745141605393597292927456921205312896311721017578'\n);\n// 1-d\u00B2\nconst ONE_MINUS_D_SQ = BigInt(\n '1159843021668779879193775521855586647937357759715417654439879720876111806838'\n);\n// (d-1)\u00B2\nconst D_MINUS_ONE_SQ = BigInt(\n '40440834346308536858101042469323190826248399146238708352240133220865137265952'\n);\n// Calculates 1/\u221A(number)\nconst invertSqrt = (number: bigint) => uvRatio(_1n, number);\n\nconst MAX_255B = BigInt('0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');\nconst bytes255ToNumberLE = (bytes: Uint8Array) =>\n ed25519.CURVE.Fp.create(bytesToNumberLE(bytes) & MAX_255B);\n\ntype ExtendedPoint = ExtPointType;\n\n// Computes Elligator map for Ristretto\n// https://ristretto.group/formulas/elligator.html\nfunction calcElligatorRistrettoMap(r0: bigint): ExtendedPoint {\n const { d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const r = mod(SQRT_M1 * r0 * r0); // 1\n const Ns = mod((r + _1n) * ONE_MINUS_D_SQ); // 2\n let c = BigInt(-1); // 3\n const D = mod((c - d * r) * mod(r + d)); // 4\n let { isValid: Ns_D_is_sq, value: s } = uvRatio(Ns, D); // 5\n let s_ = mod(s * r0); // 6\n if (!isNegativeLE(s_, P)) s_ = mod(-s_);\n if (!Ns_D_is_sq) s = s_; // 7\n if (!Ns_D_is_sq) c = r; // 8\n const Nt = mod(c * (r - _1n) * D_MINUS_ONE_SQ - D); // 9\n const s2 = s * s;\n const W0 = mod((s + s) * D); // 10\n const W1 = mod(Nt * SQRT_AD_MINUS_ONE); // 11\n const W2 = mod(_1n - s2); // 12\n const W3 = mod(_1n + s2); // 13\n return new ed25519.ExtendedPoint(mod(W0 * W3), mod(W2 * W1), mod(W1 * W3), mod(W0 * W2));\n}\n\n/**\n * Each ed25519/ExtendedPoint has 8 different equivalent points. This can be\n * a source of bugs for protocols like ring signatures. Ristretto was created to solve this.\n * Ristretto point operates in X:Y:Z:T extended coordinates like ExtendedPoint,\n * but it should work in its own namespace: do not combine those two.\n * https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-ristretto255-decaf448\n */\nclass RistPoint implements Group<RistPoint> {\n static BASE: RistPoint;\n static ZERO: RistPoint;\n // Private property to discourage combining ExtendedPoint + RistrettoPoint\n // Always use Ristretto encoding/decoding instead.\n constructor(private readonly ep: ExtendedPoint) {}\n\n static fromAffine(ap: AffinePoint<bigint>) {\n return new RistPoint(ed25519.ExtendedPoint.fromAffine(ap));\n }\n\n /**\n * Takes uniform output of 64-byte hash function like sha512 and converts it to `RistrettoPoint`.\n * The hash-to-group operation applies Elligator twice and adds the results.\n * **Note:** this is one-way map, there is no conversion from point to hash.\n * https://ristretto.group/formulas/elligator.html\n * @param hex 64-byte output of a hash function\n */\n static hashToCurve(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHash', hex, 64);\n const r1 = bytes255ToNumberLE(hex.slice(0, 32));\n const R1 = calcElligatorRistrettoMap(r1);\n const r2 = bytes255ToNumberLE(hex.slice(32, 64));\n const R2 = calcElligatorRistrettoMap(r2);\n return new RistPoint(R1.add(R2));\n }\n\n /**\n * Converts ristretto-encoded string to ristretto point.\n * https://ristretto.group/formulas/decoding.html\n * @param hex Ristretto-encoded 32 bytes. Not every 32-byte string is valid ristretto encoding\n */\n static fromHex(hex: Hex): RistPoint {\n hex = ensureBytes('ristrettoHex', hex, 32);\n const { a, d } = ed25519.CURVE;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const emsg = 'RistrettoPoint.fromHex: the hex is not valid encoding of RistrettoPoint';\n const s = bytes255ToNumberLE(hex);\n // 1. Check that s_bytes is the canonical encoding of a field element, or else abort.\n // 3. Check that s is non-negative, or else abort\n if (!equalBytes(numberToBytesLE(s, 32), hex) || isNegativeLE(s, P)) throw new Error(emsg);\n const s2 = mod(s * s);\n const u1 = mod(_1n + a * s2); // 4 (a is -1)\n const u2 = mod(_1n - a * s2); // 5\n const u1_2 = mod(u1 * u1);\n const u2_2 = mod(u2 * u2);\n const v = mod(a * d * u1_2 - u2_2); // 6\n const { isValid, value: I } = invertSqrt(mod(v * u2_2)); // 7\n const Dx = mod(I * u2); // 8\n const Dy = mod(I * Dx * v); // 9\n let x = mod((s + s) * Dx); // 10\n if (isNegativeLE(x, P)) x = mod(-x); // 10\n const y = mod(u1 * Dy); // 11\n const t = mod(x * y); // 12\n if (!isValid || isNegativeLE(t, P) || y === _0n) throw new Error(emsg);\n return new RistPoint(new ed25519.ExtendedPoint(x, y, _1n, t));\n }\n\n /**\n * Encodes ristretto point to Uint8Array.\n * https://ristretto.group/formulas/encoding.html\n */\n toRawBytes(): Uint8Array {\n let { ex: x, ey: y, ez: z, et: t } = this.ep;\n const P = ed25519.CURVE.Fp.ORDER;\n const mod = ed25519.CURVE.Fp.create;\n const u1 = mod(mod(z + y) * mod(z - y)); // 1\n const u2 = mod(x * y); // 2\n // Square root always exists\n const u2sq = mod(u2 * u2);\n const { value: invsqrt } = invertSqrt(mod(u1 * u2sq)); // 3\n const D1 = mod(invsqrt * u1); // 4\n const D2 = mod(invsqrt * u2); // 5\n const zInv = mod(D1 * D2 * t); // 6\n let D: bigint; // 7\n if (isNegativeLE(t * zInv, P)) {\n let _x = mod(y * SQRT_M1);\n let _y = mod(x * SQRT_M1);\n x = _x;\n y = _y;\n D = mod(D1 * INVSQRT_A_MINUS_D);\n } else {\n D = D2; // 8\n }\n if (isNegativeLE(x * zInv, P)) y = mod(-y); // 9\n let s = mod((z - y) * D); // 10 (check footer's note, no sqrt(-a))\n if (isNegativeLE(s, P)) s = mod(-s);\n return numberToBytesLE(s, 32); // 11\n }\n\n toHex(): string {\n return bytesToHex(this.toRawBytes());\n }\n\n toString(): string {\n return this.toHex();\n }\n\n // Compare one point to another.\n equals(other: RistPoint): boolean {\n assertRstPoint(other);\n const { ex: X1, ey: Y1 } = this.ep;\n const { ex: X2, ey: Y2 } = other.ep;\n const mod = ed25519.CURVE.Fp.create;\n // (x1 * y2 == y1 * x2) | (y1 * y2 == x1 * x2)\n const one = mod(X1 * Y2) === mod(Y1 * X2);\n const two = mod(Y1 * Y2) === mod(X1 * X2);\n return one || two;\n }\n\n add(other: RistPoint): RistPoint {\n assertRstPoint(other);\n return new RistPoint(this.ep.add(other.ep));\n }\n\n subtract(other: RistPoint): RistPoint {\n assertRstPoint(other);\n return new RistPoint(this.ep.subtract(other.ep));\n }\n\n multiply(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiply(scalar));\n }\n\n multiplyUnsafe(scalar: bigint): RistPoint {\n return new RistPoint(this.ep.multiplyUnsafe(scalar));\n }\n\n double(): RistPoint {\n return new RistPoint(this.ep.double());\n }\n\n negate(): RistPoint {\n return new RistPoint(this.ep.negate());\n }\n}\nexport const RistrettoPoint = /* @__PURE__ */ (() => {\n if (!RistPoint.BASE) RistPoint.BASE = new RistPoint(ed25519.ExtendedPoint.BASE);\n if (!RistPoint.ZERO) RistPoint.ZERO = new RistPoint(ed25519.ExtendedPoint.ZERO);\n return RistPoint;\n})();\n\n// Hashing to ristretto255. https://www.rfc-editor.org/rfc/rfc9380#appendix-B\nexport const hashToRistretto255 = (msg: Uint8Array, options: htfBasicOpts) => {\n const d = options.DST;\n const DST = typeof d === 'string' ? utf8ToBytes(d) : d;\n const uniform_bytes = expand_message_xmd(msg, DST, 64, sha512);\n const P = RistPoint.hashToCurve(uniform_bytes);\n return P;\n};\nexport const hash_to_ristretto255 = hashToRistretto255; // legacy\n", "import { SHA2 } from './_sha2.js';\nimport u64 from './_u64.js';\nimport { wrapConstructor } from './utils.js';\n\n// Round contants (first 32 bits of the fractional parts of the cube roots of the first 80 primes 2..409):\n// prettier-ignore\nconst [SHA512_Kh, SHA512_Kl] = /* @__PURE__ */ (() => u64.split([\n '0x428a2f98d728ae22', '0x7137449123ef65cd', '0xb5c0fbcfec4d3b2f', '0xe9b5dba58189dbbc',\n '0x3956c25bf348b538', '0x59f111f1b605d019', '0x923f82a4af194f9b', '0xab1c5ed5da6d8118',\n '0xd807aa98a3030242', '0x12835b0145706fbe', '0x243185be4ee4b28c', '0x550c7dc3d5ffb4e2',\n '0x72be5d74f27b896f', '0x80deb1fe3b1696b1', '0x9bdc06a725c71235', '0xc19bf174cf692694',\n '0xe49b69c19ef14ad2', '0xefbe4786384f25e3', '0x0fc19dc68b8cd5b5', '0x240ca1cc77ac9c65',\n '0x2de92c6f592b0275', '0x4a7484aa6ea6e483', '0x5cb0a9dcbd41fbd4', '0x76f988da831153b5',\n '0x983e5152ee66dfab', '0xa831c66d2db43210', '0xb00327c898fb213f', '0xbf597fc7beef0ee4',\n '0xc6e00bf33da88fc2', '0xd5a79147930aa725', '0x06ca6351e003826f', '0x142929670a0e6e70',\n '0x27b70a8546d22ffc', '0x2e1b21385c26c926', '0x4d2c6dfc5ac42aed', '0x53380d139d95b3df',\n '0x650a73548baf63de', '0x766a0abb3c77b2a8', '0x81c2c92e47edaee6', '0x92722c851482353b',\n '0xa2bfe8a14cf10364', '0xa81a664bbc423001', '0xc24b8b70d0f89791', '0xc76c51a30654be30',\n '0xd192e819d6ef5218', '0xd69906245565a910', '0xf40e35855771202a', '0x106aa07032bbd1b8',\n '0x19a4c116b8d2d0c8', '0x1e376c085141ab53', '0x2748774cdf8eeb99', '0x34b0bcb5e19b48a8',\n '0x391c0cb3c5c95a63', '0x4ed8aa4ae3418acb', '0x5b9cca4f7763e373', '0x682e6ff3d6b2b8a3',\n '0x748f82ee5defb2fc', '0x78a5636f43172f60', '0x84c87814a1f0ab72', '0x8cc702081a6439ec',\n '0x90befffa23631e28', '0xa4506cebde82bde9', '0xbef9a3f7b2c67915', '0xc67178f2e372532b',\n '0xca273eceea26619c', '0xd186b8c721c0c207', '0xeada7dd6cde0eb1e', '0xf57d4f7fee6ed178',\n '0x06f067aa72176fba', '0x0a637dc5a2c898a6', '0x113f9804bef90dae', '0x1b710b35131c471b',\n '0x28db77f523047d84', '0x32caab7b40c72493', '0x3c9ebe0a15c9bebc', '0x431d67c49c100d4c',\n '0x4cc5d4becb3e42b6', '0x597f299cfc657e2a', '0x5fcb6fab3ad6faec', '0x6c44198c4a475817'\n].map(n => BigInt(n))))();\n\n// Temporary buffer, not used to store anything between runs\nconst SHA512_W_H = /* @__PURE__ */ new Uint32Array(80);\nconst SHA512_W_L = /* @__PURE__ */ new Uint32Array(80);\nexport class SHA512 extends SHA2<SHA512> {\n // We cannot use array here since array allows indexing by variable which means optimizer/compiler cannot use registers.\n // Also looks cleaner and easier to verify with spec.\n // Initial state (first 32 bits of the fractional parts of the square roots of the first 8 primes 2..19):\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x6a09e667 | 0;\n Al = 0xf3bcc908 | 0;\n Bh = 0xbb67ae85 | 0;\n Bl = 0x84caa73b | 0;\n Ch = 0x3c6ef372 | 0;\n Cl = 0xfe94f82b | 0;\n Dh = 0xa54ff53a | 0;\n Dl = 0x5f1d36f1 | 0;\n Eh = 0x510e527f | 0;\n El = 0xade682d1 | 0;\n Fh = 0x9b05688c | 0;\n Fl = 0x2b3e6c1f | 0;\n Gh = 0x1f83d9ab | 0;\n Gl = 0xfb41bd6b | 0;\n Hh = 0x5be0cd19 | 0;\n Hl = 0x137e2179 | 0;\n\n constructor() {\n super(128, 64, 16, false);\n }\n // prettier-ignore\n protected get(): [\n number, number, number, number, number, number, number, number,\n number, number, number, number, number, number, number, number\n ] {\n const { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n return [Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl];\n }\n // prettier-ignore\n protected set(\n Ah: number, Al: number, Bh: number, Bl: number, Ch: number, Cl: number, Dh: number, Dl: number,\n Eh: number, El: number, Fh: number, Fl: number, Gh: number, Gl: number, Hh: number, Hl: number\n ) {\n this.Ah = Ah | 0;\n this.Al = Al | 0;\n this.Bh = Bh | 0;\n this.Bl = Bl | 0;\n this.Ch = Ch | 0;\n this.Cl = Cl | 0;\n this.Dh = Dh | 0;\n this.Dl = Dl | 0;\n this.Eh = Eh | 0;\n this.El = El | 0;\n this.Fh = Fh | 0;\n this.Fl = Fl | 0;\n this.Gh = Gh | 0;\n this.Gl = Gl | 0;\n this.Hh = Hh | 0;\n this.Hl = Hl | 0;\n }\n protected process(view: DataView, offset: number) {\n // Extend the first 16 words into the remaining 64 words w[16..79] of the message schedule array\n for (let i = 0; i < 16; i++, offset += 4) {\n SHA512_W_H[i] = view.getUint32(offset);\n SHA512_W_L[i] = view.getUint32((offset += 4));\n }\n for (let i = 16; i < 80; i++) {\n // s0 := (w[i-15] rightrotate 1) xor (w[i-15] rightrotate 8) xor (w[i-15] rightshift 7)\n const W15h = SHA512_W_H[i - 15] | 0;\n const W15l = SHA512_W_L[i - 15] | 0;\n const s0h = u64.rotrSH(W15h, W15l, 1) ^ u64.rotrSH(W15h, W15l, 8) ^ u64.shrSH(W15h, W15l, 7);\n const s0l = u64.rotrSL(W15h, W15l, 1) ^ u64.rotrSL(W15h, W15l, 8) ^ u64.shrSL(W15h, W15l, 7);\n // s1 := (w[i-2] rightrotate 19) xor (w[i-2] rightrotate 61) xor (w[i-2] rightshift 6)\n const W2h = SHA512_W_H[i - 2] | 0;\n const W2l = SHA512_W_L[i - 2] | 0;\n const s1h = u64.rotrSH(W2h, W2l, 19) ^ u64.rotrBH(W2h, W2l, 61) ^ u64.shrSH(W2h, W2l, 6);\n const s1l = u64.rotrSL(W2h, W2l, 19) ^ u64.rotrBL(W2h, W2l, 61) ^ u64.shrSL(W2h, W2l, 6);\n // SHA256_W[i] = s0 + s1 + SHA256_W[i - 7] + SHA256_W[i - 16];\n const SUMl = u64.add4L(s0l, s1l, SHA512_W_L[i - 7], SHA512_W_L[i - 16]);\n const SUMh = u64.add4H(SUMl, s0h, s1h, SHA512_W_H[i - 7], SHA512_W_H[i - 16]);\n SHA512_W_H[i] = SUMh | 0;\n SHA512_W_L[i] = SUMl | 0;\n }\n let { Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl } = this;\n // Compression function main loop, 80 rounds\n for (let i = 0; i < 80; i++) {\n // S1 := (e rightrotate 14) xor (e rightrotate 18) xor (e rightrotate 41)\n const sigma1h = u64.rotrSH(Eh, El, 14) ^ u64.rotrSH(Eh, El, 18) ^ u64.rotrBH(Eh, El, 41);\n const sigma1l = u64.rotrSL(Eh, El, 14) ^ u64.rotrSL(Eh, El, 18) ^ u64.rotrBL(Eh, El, 41);\n //const T1 = (H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i]) | 0;\n const CHIh = (Eh & Fh) ^ (~Eh & Gh);\n const CHIl = (El & Fl) ^ (~El & Gl);\n // T1 = H + sigma1 + Chi(E, F, G) + SHA512_K[i] + SHA512_W[i]\n // prettier-ignore\n const T1ll = u64.add5L(Hl, sigma1l, CHIl, SHA512_Kl[i], SHA512_W_L[i]);\n const T1h = u64.add5H(T1ll, Hh, sigma1h, CHIh, SHA512_Kh[i], SHA512_W_H[i]);\n const T1l = T1ll | 0;\n // S0 := (a rightrotate 28) xor (a rightrotate 34) xor (a rightrotate 39)\n const sigma0h = u64.rotrSH(Ah, Al, 28) ^ u64.rotrBH(Ah, Al, 34) ^ u64.rotrBH(Ah, Al, 39);\n const sigma0l = u64.rotrSL(Ah, Al, 28) ^ u64.rotrBL(Ah, Al, 34) ^ u64.rotrBL(Ah, Al, 39);\n const MAJh = (Ah & Bh) ^ (Ah & Ch) ^ (Bh & Ch);\n const MAJl = (Al & Bl) ^ (Al & Cl) ^ (Bl & Cl);\n Hh = Gh | 0;\n Hl = Gl | 0;\n Gh = Fh | 0;\n Gl = Fl | 0;\n Fh = Eh | 0;\n Fl = El | 0;\n ({ h: Eh, l: El } = u64.add(Dh | 0, Dl | 0, T1h | 0, T1l | 0));\n Dh = Ch | 0;\n Dl = Cl | 0;\n Ch = Bh | 0;\n Cl = Bl | 0;\n Bh = Ah | 0;\n Bl = Al | 0;\n const All = u64.add3L(T1l, sigma0l, MAJl);\n Ah = u64.add3H(All, T1h, sigma0h, MAJh);\n Al = All | 0;\n }\n // Add the compressed chunk to the current hash value\n ({ h: Ah, l: Al } = u64.add(this.Ah | 0, this.Al | 0, Ah | 0, Al | 0));\n ({ h: Bh, l: Bl } = u64.add(this.Bh | 0, this.Bl | 0, Bh | 0, Bl | 0));\n ({ h: Ch, l: Cl } = u64.add(this.Ch | 0, this.Cl | 0, Ch | 0, Cl | 0));\n ({ h: Dh, l: Dl } = u64.add(this.Dh | 0, this.Dl | 0, Dh | 0, Dl | 0));\n ({ h: Eh, l: El } = u64.add(this.Eh | 0, this.El | 0, Eh | 0, El | 0));\n ({ h: Fh, l: Fl } = u64.add(this.Fh | 0, this.Fl | 0, Fh | 0, Fl | 0));\n ({ h: Gh, l: Gl } = u64.add(this.Gh | 0, this.Gl | 0, Gh | 0, Gl | 0));\n ({ h: Hh, l: Hl } = u64.add(this.Hh | 0, this.Hl | 0, Hh | 0, Hl | 0));\n this.set(Ah, Al, Bh, Bl, Ch, Cl, Dh, Dl, Eh, El, Fh, Fl, Gh, Gl, Hh, Hl);\n }\n protected roundClean() {\n SHA512_W_H.fill(0);\n SHA512_W_L.fill(0);\n }\n destroy() {\n this.buffer.fill(0);\n this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);\n }\n}\n\nclass SHA512_224 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x8c3d37c8 | 0;\n Al = 0x19544da2 | 0;\n Bh = 0x73e19966 | 0;\n Bl = 0x89dcd4d6 | 0;\n Ch = 0x1dfab7ae | 0;\n Cl = 0x32ff9c82 | 0;\n Dh = 0x679dd514 | 0;\n Dl = 0x582f9fcf | 0;\n Eh = 0x0f6d2b69 | 0;\n El = 0x7bd44da8 | 0;\n Fh = 0x77e36f73 | 0;\n Fl = 0x04c48942 | 0;\n Gh = 0x3f9d85a8 | 0;\n Gl = 0x6a1d36c8 | 0;\n Hh = 0x1112e6ad | 0;\n Hl = 0x91d692a1 | 0;\n\n constructor() {\n super();\n this.outputLen = 28;\n }\n}\n\nclass SHA512_256 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0x22312194 | 0;\n Al = 0xfc2bf72c | 0;\n Bh = 0x9f555fa3 | 0;\n Bl = 0xc84c64c2 | 0;\n Ch = 0x2393b86b | 0;\n Cl = 0x6f53b151 | 0;\n Dh = 0x96387719 | 0;\n Dl = 0x5940eabd | 0;\n Eh = 0x96283ee2 | 0;\n El = 0xa88effe3 | 0;\n Fh = 0xbe5e1e25 | 0;\n Fl = 0x53863992 | 0;\n Gh = 0x2b0199fc | 0;\n Gl = 0x2c85b8aa | 0;\n Hh = 0x0eb72ddc | 0;\n Hl = 0x81c52ca2 | 0;\n\n constructor() {\n super();\n this.outputLen = 32;\n }\n}\n\nclass SHA384 extends SHA512 {\n // h -- high 32 bits, l -- low 32 bits\n Ah = 0xcbbb9d5d | 0;\n Al = 0xc1059ed8 | 0;\n Bh = 0x629a292a | 0;\n Bl = 0x367cd507 | 0;\n Ch = 0x9159015a | 0;\n Cl = 0x3070dd17 | 0;\n Dh = 0x152fecd8 | 0;\n Dl = 0xf70e5939 | 0;\n Eh = 0x67332667 | 0;\n El = 0xffc00b31 | 0;\n Fh = 0x8eb44a87 | 0;\n Fl = 0x68581511 | 0;\n Gh = 0xdb0c2e0d | 0;\n Gl = 0x64f98fa7 | 0;\n Hh = 0x47b5481d | 0;\n Hl = 0xbefa4fa4 | 0;\n\n constructor() {\n super();\n this.outputLen = 48;\n }\n}\n\nexport const sha512 = /* @__PURE__ */ wrapConstructor(() => new SHA512());\nexport const sha512_224 = /* @__PURE__ */ wrapConstructor(() => new SHA512_224());\nexport const sha512_256 = /* @__PURE__ */ wrapConstructor(() => new SHA512_256());\nexport const sha384 = /* @__PURE__ */ wrapConstructor(() => new SHA384());\n", "const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);\nconst _32n = /* @__PURE__ */ BigInt(32);\n\n// We are not using BigUint64Array, because they are extremely slow as per 2022\nfunction fromBig(n: bigint, le = false) {\n if (le) return { h: Number(n & U32_MASK64), l: Number((n >> _32n) & U32_MASK64) };\n return { h: Number((n >> _32n) & U32_MASK64) | 0, l: Number(n & U32_MASK64) | 0 };\n}\n\nfunction split(lst: bigint[], le = false) {\n let Ah = new Uint32Array(lst.length);\n let Al = new Uint32Array(lst.length);\n for (let i = 0; i < lst.length; i++) {\n const { h, l } = fromBig(lst[i], le);\n [Ah[i], Al[i]] = [h, l];\n }\n return [Ah, Al];\n}\n\nconst toBig = (h: number, l: number) => (BigInt(h >>> 0) << _32n) | BigInt(l >>> 0);\n// for Shift in [0, 32)\nconst shrSH = (h: number, _l: number, s: number) => h >>> s;\nconst shrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in [1, 32)\nconst rotrSH = (h: number, l: number, s: number) => (h >>> s) | (l << (32 - s));\nconst rotrSL = (h: number, l: number, s: number) => (h << (32 - s)) | (l >>> s);\n// Right rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotrBH = (h: number, l: number, s: number) => (h << (64 - s)) | (l >>> (s - 32));\nconst rotrBL = (h: number, l: number, s: number) => (h >>> (s - 32)) | (l << (64 - s));\n// Right rotate for shift===32 (just swaps l&h)\nconst rotr32H = (_h: number, l: number) => l;\nconst rotr32L = (h: number, _l: number) => h;\n// Left rotate for Shift in [1, 32)\nconst rotlSH = (h: number, l: number, s: number) => (h << s) | (l >>> (32 - s));\nconst rotlSL = (h: number, l: number, s: number) => (l << s) | (h >>> (32 - s));\n// Left rotate for Shift in (32, 64), NOTE: 32 is special case.\nconst rotlBH = (h: number, l: number, s: number) => (l << (s - 32)) | (h >>> (64 - s));\nconst rotlBL = (h: number, l: number, s: number) => (h << (s - 32)) | (l >>> (64 - s));\n\n// JS uses 32-bit signed integers for bitwise operations which means we cannot\n// simple take carry out of low bit sum by shift, we need to use division.\nfunction add(Ah: number, Al: number, Bh: number, Bl: number) {\n const l = (Al >>> 0) + (Bl >>> 0);\n return { h: (Ah + Bh + ((l / 2 ** 32) | 0)) | 0, l: l | 0 };\n}\n// Addition with more than 2 elements\nconst add3L = (Al: number, Bl: number, Cl: number) => (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0);\nconst add3H = (low: number, Ah: number, Bh: number, Ch: number) =>\n (Ah + Bh + Ch + ((low / 2 ** 32) | 0)) | 0;\nconst add4L = (Al: number, Bl: number, Cl: number, Dl: number) =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0);\nconst add4H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number) =>\n (Ah + Bh + Ch + Dh + ((low / 2 ** 32) | 0)) | 0;\nconst add5L = (Al: number, Bl: number, Cl: number, Dl: number, El: number) =>\n (Al >>> 0) + (Bl >>> 0) + (Cl >>> 0) + (Dl >>> 0) + (El >>> 0);\nconst add5H = (low: number, Ah: number, Bh: number, Ch: number, Dh: number, Eh: number) =>\n (Ah + Bh + Ch + Dh + Eh + ((low / 2 ** 32) | 0)) | 0;\n\n// prettier-ignore\nexport {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\n// prettier-ignore\nconst u64 = {\n fromBig, split, toBig,\n shrSH, shrSL,\n rotrSH, rotrSL, rotrBH, rotrBL,\n rotr32H, rotr32L,\n rotlSH, rotlSL, rotlBH, rotlBL,\n add, add3L, add3H, add4L, add4H, add5H, add5L,\n};\nexport default u64;\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\n// Twisted Edwards curve. The formula is: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2\nimport { mod } from './modular.js';\nimport * as ut from './utils.js';\nimport { ensureBytes, FHash, Hex } from './utils.js';\nimport { Group, GroupConstructor, wNAF, BasicCurve, validateBasic, AffinePoint } from './curve.js';\n\n// Be friendly to bad ECMAScript parsers by not using bigint literals\n// prettier-ignore\nconst _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _8n = BigInt(8);\n\n// Edwards curves must declare params a & d.\nexport type CurveType = BasicCurve<bigint> & {\n a: bigint; // curve param a\n d: bigint; // curve param d\n hash: FHash; // Hashing\n randomBytes: (bytesLength?: number) => Uint8Array; // CSPRNG\n adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array; // clears bits to get valid field elemtn\n domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array; // Used for hashing\n uvRatio?: (u: bigint, v: bigint) => { isValid: boolean; value: bigint }; // Ratio \u221A(u/v)\n prehash?: FHash; // RFC 8032 pre-hashing of messages to sign() / verify()\n mapToCurve?: (scalar: bigint[]) => AffinePoint<bigint>; // for hash-to-curve standard\n};\n\n// verification rule is either zip215 or rfc8032 / nist186-5. Consult fromHex:\nconst VERIFY_DEFAULT = { zip215: true };\n\nfunction validateOpts(curve: CurveType) {\n const opts = validateBasic(curve);\n ut.validateObject(\n curve,\n {\n hash: 'function',\n a: 'bigint',\n d: 'bigint',\n randomBytes: 'function',\n },\n {\n adjustScalarBytes: 'function',\n domain: 'function',\n uvRatio: 'function',\n mapToCurve: 'function',\n }\n );\n // Set defaults\n return Object.freeze({ ...opts } as const);\n}\n\n// Instance of Extended Point with coordinates in X, Y, Z, T\nexport interface ExtPointType extends Group<ExtPointType> {\n readonly ex: bigint;\n readonly ey: bigint;\n readonly ez: bigint;\n readonly et: bigint;\n get x(): bigint;\n get y(): bigint;\n assertValidity(): void;\n multiply(scalar: bigint): ExtPointType;\n multiplyUnsafe(scalar: bigint): ExtPointType;\n isSmallOrder(): boolean;\n isTorsionFree(): boolean;\n clearCofactor(): ExtPointType;\n toAffine(iz?: bigint): AffinePoint<bigint>;\n toRawBytes(isCompressed?: boolean): Uint8Array;\n toHex(isCompressed?: boolean): string;\n}\n// Static methods of Extended Point with coordinates in X, Y, Z, T\nexport interface ExtPointConstructor extends GroupConstructor<ExtPointType> {\n new (x: bigint, y: bigint, z: bigint, t: bigint): ExtPointType;\n fromAffine(p: AffinePoint<bigint>): ExtPointType;\n fromHex(hex: Hex): ExtPointType;\n fromPrivateKey(privateKey: Hex): ExtPointType;\n}\n\nexport type CurveFn = {\n CURVE: ReturnType<typeof validateOpts>;\n getPublicKey: (privateKey: Hex) => Uint8Array;\n sign: (message: Hex, privateKey: Hex, options?: { context?: Hex }) => Uint8Array;\n verify: (\n sig: Hex,\n message: Hex,\n publicKey: Hex,\n options?: { context?: Hex; zip215: boolean }\n ) => boolean;\n ExtendedPoint: ExtPointConstructor;\n utils: {\n randomPrivateKey: () => Uint8Array;\n getExtendedPublicKey: (key: Hex) => {\n head: Uint8Array;\n prefix: Uint8Array;\n scalar: bigint;\n point: ExtPointType;\n pointBytes: Uint8Array;\n };\n };\n};\n\n// It is not generic twisted curve for now, but ed25519/ed448 generic implementation\nexport function twistedEdwards(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef) as ReturnType<typeof validateOpts>;\n const {\n Fp,\n n: CURVE_ORDER,\n prehash: prehash,\n hash: cHash,\n randomBytes,\n nByteLength,\n h: cofactor,\n } = CURVE;\n const MASK = _2n << (BigInt(nByteLength * 8) - _1n);\n const modP = Fp.create; // Function overrides\n\n // sqrt(u/v)\n const uvRatio =\n CURVE.uvRatio ||\n ((u: bigint, v: bigint) => {\n try {\n return { isValid: true, value: Fp.sqrt(u * Fp.inv(v)) };\n } catch (e) {\n return { isValid: false, value: _0n };\n }\n });\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes); // NOOP\n const domain =\n CURVE.domain ||\n ((data: Uint8Array, ctx: Uint8Array, phflag: boolean) => {\n if (ctx.length || phflag) throw new Error('Contexts/pre-hash are not supported');\n return data;\n }); // NOOP\n const inBig = (n: bigint) => typeof n === 'bigint' && _0n < n; // n in [1..]\n const inRange = (n: bigint, max: bigint) => inBig(n) && inBig(max) && n < max; // n in [1..max-1]\n const in0MaskRange = (n: bigint) => n === _0n || inRange(n, MASK); // n in [0..MASK-1]\n function assertInRange(n: bigint, max: bigint) {\n // n in [1..max-1]\n if (inRange(n, max)) return n;\n throw new Error(`Expected valid scalar < ${max}, got ${typeof n} ${n}`);\n }\n function assertGE0(n: bigint) {\n // n in [0..CURVE_ORDER-1]\n return n === _0n ? n : assertInRange(n, CURVE_ORDER); // GE = prime subgroup, not full group\n }\n const pointPrecomputes = new Map<Point, Point[]>();\n function isPoint(other: unknown) {\n if (!(other instanceof Point)) throw new Error('ExtendedPoint expected');\n }\n // Extended Point works in extended coordinates: (x, y, z, t) \u220B (x=x/z, y=y/z, t=xy).\n // https://en.wikipedia.org/wiki/Twisted_Edwards_curve#Extended_coordinates\n class Point implements ExtPointType {\n static readonly BASE = new Point(CURVE.Gx, CURVE.Gy, _1n, modP(CURVE.Gx * CURVE.Gy));\n static readonly ZERO = new Point(_0n, _1n, _1n, _0n); // 0, 1, 1, 0\n\n constructor(\n readonly ex: bigint,\n readonly ey: bigint,\n readonly ez: bigint,\n readonly et: bigint\n ) {\n if (!in0MaskRange(ex)) throw new Error('x required');\n if (!in0MaskRange(ey)) throw new Error('y required');\n if (!in0MaskRange(ez)) throw new Error('z required');\n if (!in0MaskRange(et)) throw new Error('t required');\n }\n\n get x(): bigint {\n return this.toAffine().x;\n }\n get y(): bigint {\n return this.toAffine().y;\n }\n\n static fromAffine(p: AffinePoint<bigint>): Point {\n if (p instanceof Point) throw new Error('extended point not allowed');\n const { x, y } = p || {};\n if (!in0MaskRange(x) || !in0MaskRange(y)) throw new Error('invalid affine point');\n return new Point(x, y, _1n, modP(x * y));\n }\n static normalizeZ(points: Point[]): Point[] {\n const toInv = Fp.invertBatch(points.map((p) => p.ez));\n return points.map((p, i) => p.toAffine(toInv[i])).map(Point.fromAffine);\n }\n\n // We calculate precomputes for elliptic curve point multiplication\n // using windowed method. This specifies window size and\n // stores precomputed values. Usually only base point would be precomputed.\n _WINDOW_SIZE?: number;\n\n // \"Private method\", don't use it directly\n _setWindowSize(windowSize: number) {\n this._WINDOW_SIZE = windowSize;\n pointPrecomputes.delete(this);\n }\n // Not required for fromHex(), which always creates valid points.\n // Could be useful for fromAffine().\n assertValidity(): void {\n const { a, d } = CURVE;\n if (this.is0()) throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax\u00B2 + y\u00B2 = 1 + dx\u00B2y\u00B2\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX\u00B2 + Y\u00B2)Z\u00B2 = Z\u2074 + dX\u00B2Y\u00B2\n const { ex: X, ey: Y, ez: Z, et: T } = this;\n const X2 = modP(X * X); // X\u00B2\n const Y2 = modP(Y * Y); // Y\u00B2\n const Z2 = modP(Z * Z); // Z\u00B2\n const Z4 = modP(Z2 * Z2); // Z\u2074\n const aX2 = modP(X2 * a); // aX\u00B2\n const left = modP(Z2 * modP(aX2 + Y2)); // (aX\u00B2 + Y\u00B2)Z\u00B2\n const right = modP(Z4 + modP(d * modP(X2 * Y2))); // Z\u2074 + dX\u00B2Y\u00B2\n if (left !== right) throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = modP(X * Y);\n const ZT = modP(Z * T);\n if (XY !== ZT) throw new Error('bad point: equation left != right (2)');\n }\n\n // Compare one point to another.\n equals(other: Point): boolean {\n isPoint(other);\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = other;\n const X1Z2 = modP(X1 * Z2);\n const X2Z1 = modP(X2 * Z1);\n const Y1Z2 = modP(Y1 * Z2);\n const Y2Z1 = modP(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n\n protected is0(): boolean {\n return this.equals(Point.ZERO);\n }\n\n negate(): Point {\n // Flips point sign to a negative one (-x, y in affine coords)\n return new Point(modP(-this.ex), this.ey, this.ez, modP(-this.et));\n }\n\n // Fast algo for doubling Extended Point.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n // Cost: 4M + 4S + 1*a + 6add + 1*2.\n double(): Point {\n const { a } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const A = modP(X1 * X1); // A = X12\n const B = modP(Y1 * Y1); // B = Y12\n const C = modP(_2n * modP(Z1 * Z1)); // C = 2*Z12\n const D = modP(a * A); // D = a*A\n const x1y1 = X1 + Y1;\n const E = modP(modP(x1y1 * x1y1) - A - B); // E = (X1+Y1)2-A-B\n const G = D + B; // G = D+B\n const F = G - C; // F = G-C\n const H = D - B; // H = D-B\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n return new Point(X3, Y3, Z3, T3);\n }\n\n // Fast algo for adding 2 Extended Points.\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#addition-add-2008-hwcd\n // Cost: 9M + 1*a + 1*d + 7add.\n add(other: Point) {\n isPoint(other);\n const { a, d } = CURVE;\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = other;\n // Faster algo for adding 2 Extended Points when curve's a=-1.\n // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-4\n // Cost: 8M + 8add + 2*2.\n // Note: It does not check whether the `other` point is valid.\n if (a === BigInt(-1)) {\n const A = modP((Y1 - X1) * (Y2 + X2));\n const B = modP((Y1 + X1) * (Y2 - X2));\n const F = modP(B - A);\n if (F === _0n) return this.double(); // Same point. Tests say it doesn't affect timing\n const C = modP(Z1 * _2n * T2);\n const D = modP(T1 * _2n * Z2);\n const E = D + C;\n const G = B + A;\n const H = D - C;\n const X3 = modP(E * F);\n const Y3 = modP(G * H);\n const T3 = modP(E * H);\n const Z3 = modP(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n const A = modP(X1 * X2); // A = X1*X2\n const B = modP(Y1 * Y2); // B = Y1*Y2\n const C = modP(T1 * d * T2); // C = T1*d*T2\n const D = modP(Z1 * Z2); // D = Z1*Z2\n const E = modP((X1 + Y1) * (X2 + Y2) - A - B); // E = (X1+Y1)*(X2+Y2)-A-B\n const F = D - C; // F = D-C\n const G = D + C; // G = D+C\n const H = modP(B - a * A); // H = B-a*A\n const X3 = modP(E * F); // X3 = E*F\n const Y3 = modP(G * H); // Y3 = G*H\n const T3 = modP(E * H); // T3 = E*H\n const Z3 = modP(F * G); // Z3 = F*G\n\n return new Point(X3, Y3, Z3, T3);\n }\n\n subtract(other: Point): Point {\n return this.add(other.negate());\n }\n\n private wNAF(n: bigint): { p: Point; f: Point } {\n return wnaf.wNAFCached(this, pointPrecomputes, n, Point.normalizeZ);\n }\n\n // Constant-time multiplication.\n multiply(scalar: bigint): Point {\n const { p, f } = this.wNAF(assertInRange(scalar, CURVE_ORDER));\n return Point.normalizeZ([p, f])[0];\n }\n\n // Non-constant-time multiplication. Uses double-and-add algorithm.\n // It's faster, but should only be used when you don't care about\n // an exposed private key e.g. sig verification.\n // Does NOT allow scalars higher than CURVE.n.\n multiplyUnsafe(scalar: bigint): Point {\n let n = assertGE0(scalar); // 0 <= scalar < CURVE.n\n if (n === _0n) return I;\n if (this.equals(I) || n === _1n) return this;\n if (this.equals(G)) return this.wNAF(n).p;\n return wnaf.unsafeLadder(this, n);\n }\n\n // Checks if point is of small order.\n // If you add something to small order point, you will have \"dirty\"\n // point with torsion component.\n // Multiplies point by cofactor and checks if the result is 0.\n isSmallOrder(): boolean {\n return this.multiplyUnsafe(cofactor).is0();\n }\n\n // Multiplies point by curve order and checks if the result is 0.\n // Returns `false` is the point is dirty.\n isTorsionFree(): boolean {\n return wnaf.unsafeLadder(this, CURVE_ORDER).is0();\n }\n\n // Converts Extended point to default (x, y) coordinates.\n // Can accept precomputed Z^-1 - for example, from invertBatch.\n toAffine(iz?: bigint): AffinePoint<bigint> {\n const { ex: x, ey: y, ez: z } = this;\n const is0 = this.is0();\n if (iz == null) iz = is0 ? _8n : (Fp.inv(z) as bigint); // 8 was chosen arbitrarily\n const ax = modP(x * iz);\n const ay = modP(y * iz);\n const zz = modP(z * iz);\n if (is0) return { x: _0n, y: _1n };\n if (zz !== _1n) throw new Error('invZ was invalid');\n return { x: ax, y: ay };\n }\n\n clearCofactor(): Point {\n const { h: cofactor } = CURVE;\n if (cofactor === _1n) return this;\n return this.multiplyUnsafe(cofactor);\n }\n\n // Converts hash string or Uint8Array to Point.\n // Uses algo from RFC8032 5.1.3.\n static fromHex(hex: Hex, zip215 = false): Point {\n const { d, a } = CURVE;\n const len = Fp.BYTES;\n hex = ensureBytes('pointHex', hex, len); // copy hex to a new array\n const normed = hex.slice(); // copy again, we'll manipulate it\n const lastByte = hex[len - 1]; // select last byte\n normed[len - 1] = lastByte & ~0x80; // clear last bit\n const y = ut.bytesToNumberLE(normed);\n if (y === _0n) {\n // y=0 is allowed\n } else {\n // RFC8032 prohibits >= p, but ZIP215 doesn't\n if (zip215) assertInRange(y, MASK); // zip215=true [1..P-1] (2^255-19-1 for ed25519)\n else assertInRange(y, Fp.ORDER); // zip215=false [1..MASK-1] (2^256-1 for ed25519)\n }\n\n // Ed25519: x\u00B2 = (y\u00B2-1)/(dy\u00B2+1) mod p. Ed448: x\u00B2 = (y\u00B2-1)/(dy\u00B2-1) mod p. Generic case:\n // ax\u00B2+y\u00B2=1+dx\u00B2y\u00B2 => y\u00B2-1=dx\u00B2y\u00B2-ax\u00B2 => y\u00B2-1=x\u00B2(dy\u00B2-a) => x\u00B2=(y\u00B2-1)/(dy\u00B2-a)\n const y2 = modP(y * y); // denominator is always non-0 mod p.\n const u = modP(y2 - _1n); // u = y\u00B2 - 1\n const v = modP(d * y2 - a); // v = d y\u00B2 + 1.\n let { isValid, value: x } = uvRatio(u, v); // \u221A(u/v)\n if (!isValid) throw new Error('Point.fromHex: invalid y coordinate');\n const isXOdd = (x & _1n) === _1n; // There are 2 square roots. Use x_0 bit to select proper\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === _0n && isLastByteOdd)\n // if x=0 and x_0 = 1, fail\n throw new Error('Point.fromHex: x=0 and x_0=1');\n if (isLastByteOdd !== isXOdd) x = modP(-x); // if x_0 != x mod 2, set x = p-x\n return Point.fromAffine({ x, y });\n }\n static fromPrivateKey(privKey: Hex) {\n return getExtendedPublicKey(privKey).point;\n }\n toRawBytes(): Uint8Array {\n const { x, y } = this.toAffine();\n const bytes = ut.numberToBytesLE(y, Fp.BYTES); // each y has 2 x values (x, -y)\n bytes[bytes.length - 1] |= x & _1n ? 0x80 : 0; // when compressing, it's enough to store y\n return bytes; // and use the last byte to encode sign of x\n }\n toHex(): string {\n return ut.bytesToHex(this.toRawBytes()); // Same as toRawBytes, but returns string.\n }\n }\n const { BASE: G, ZERO: I } = Point;\n const wnaf = wNAF(Point, nByteLength * 8);\n\n function modN(a: bigint) {\n return mod(a, CURVE_ORDER);\n }\n // Little-endian SHA512 with modulo n\n function modN_LE(hash: Uint8Array): bigint {\n return modN(ut.bytesToNumberLE(hash));\n }\n\n /** Convenience method that creates public key and other stuff. RFC8032 5.1.5 */\n function getExtendedPublicKey(key: Hex) {\n const len = nByteLength;\n key = ensureBytes('private key', key, len);\n // Hash private key with curve's hash function to produce uniformingly random input\n // Check byte lengths: ensure(64, h(ensure(32, key)))\n const hashed = ensureBytes('hashed private key', cHash(key), 2 * len);\n const head = adjustScalarBytes(hashed.slice(0, len)); // clear first half bits, produce FE\n const prefix = hashed.slice(len, 2 * len); // second half is called key prefix (5.1.6)\n const scalar = modN_LE(head); // The actual private scalar\n const point = G.multiply(scalar); // Point on Edwards curve aka public key\n const pointBytes = point.toRawBytes(); // Uint8Array representation\n return { head, prefix, scalar, point, pointBytes };\n }\n\n // Calculates EdDSA pub key. RFC8032 5.1.5. Privkey is hashed. Use first half with 3 bits cleared\n function getPublicKey(privKey: Hex): Uint8Array {\n return getExtendedPublicKey(privKey).pointBytes;\n }\n\n // int('LE', SHA512(dom2(F, C) || msgs)) mod N\n function hashDomainToScalar(context: Hex = new Uint8Array(), ...msgs: Uint8Array[]) {\n const msg = ut.concatBytes(...msgs);\n return modN_LE(cHash(domain(msg, ensureBytes('context', context), !!prehash)));\n }\n\n /** Signs message with privateKey. RFC8032 5.1.6 */\n function sign(msg: Hex, privKey: Hex, options: { context?: Hex } = {}): Uint8Array {\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph etc.\n const { prefix, scalar, pointBytes } = getExtendedPublicKey(privKey);\n const r = hashDomainToScalar(options.context, prefix, msg); // r = dom2(F, C) || prefix || PH(M)\n const R = G.multiply(r).toRawBytes(); // R = rG\n const k = hashDomainToScalar(options.context, R, pointBytes, msg); // R || A || PH(M)\n const s = modN(r + k * scalar); // S = (r + k * s) mod L\n assertGE0(s); // 0 <= s < l\n const res = ut.concatBytes(R, ut.numberToBytesLE(s, Fp.BYTES));\n return ensureBytes('result', res, nByteLength * 2); // 64-byte signature\n }\n\n const verifyOpts: { context?: Hex; zip215?: boolean } = VERIFY_DEFAULT;\n function verify(sig: Hex, msg: Hex, publicKey: Hex, options = verifyOpts): boolean {\n const { context, zip215 } = options;\n const len = Fp.BYTES; // Verifies EdDSA signature against message and public key. RFC8032 5.1.7.\n sig = ensureBytes('signature', sig, 2 * len); // An extended group equation is checked.\n msg = ensureBytes('message', msg);\n if (prehash) msg = prehash(msg); // for ed25519ph, etc\n\n const s = ut.bytesToNumberLE(sig.slice(len, 2 * len));\n // zip215: true is good for consensus-critical apps and allows points < 2^256\n // zip215: false follows RFC8032 / NIST186-5 and restricts points to CURVE.p\n let A, R, SB;\n try {\n A = Point.fromHex(publicKey, zip215);\n R = Point.fromHex(sig.slice(0, len), zip215);\n SB = G.multiplyUnsafe(s); // 0 <= s < l is done inside\n } catch (error) {\n return false;\n }\n if (!zip215 && A.isSmallOrder()) return false;\n\n const k = hashDomainToScalar(context, R.toRawBytes(), A.toRawBytes(), msg);\n const RkA = R.add(A.multiplyUnsafe(k));\n // [8][S]B = [8]R + [8][k]A'\n return RkA.subtract(SB).clearCofactor().equals(Point.ZERO);\n }\n\n G._setWindowSize(8); // Enable precomputes. Slows down first publicKey computation by 20ms.\n\n const utils = {\n getExtendedPublicKey,\n // ed25519 private keys are uniform 32b. No need to check for modulo bias, like in secp256k1.\n randomPrivateKey: (): Uint8Array => randomBytes(Fp.BYTES),\n\n /**\n * We're doing scalar multiplication (used in getPublicKey etc) with precomputed BASE_POINT\n * values. This slows down first getPublicKey() by milliseconds (see Speed section),\n * but allows to speed-up subsequent getPublicKey() calls up to 20x.\n * @param windowSize 2, 4, 8, 16\n */\n precompute(windowSize = 8, point = Point.BASE): typeof Point.BASE {\n point._setWindowSize(windowSize);\n point.multiply(BigInt(3));\n return point;\n },\n };\n\n return {\n CURVE,\n getPublicKey,\n sign,\n verify,\n ExtendedPoint: Point,\n utils,\n };\n}\n", "/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */\nimport { mod, pow } from './modular.js';\nimport { bytesToNumberLE, ensureBytes, numberToBytesLE, validateObject } from './utils.js';\n\nconst _0n = BigInt(0);\nconst _1n = BigInt(1);\ntype Hex = string | Uint8Array;\n\nexport type CurveType = {\n P: bigint; // finite field prime\n nByteLength: number;\n adjustScalarBytes?: (bytes: Uint8Array) => Uint8Array;\n domain?: (data: Uint8Array, ctx: Uint8Array, phflag: boolean) => Uint8Array;\n a: bigint;\n montgomeryBits: number;\n powPminus2?: (x: bigint) => bigint;\n xyToU?: (x: bigint, y: bigint) => bigint;\n Gu: bigint;\n randomBytes?: (bytesLength?: number) => Uint8Array;\n};\nexport type CurveFn = {\n scalarMult: (scalar: Hex, u: Hex) => Uint8Array;\n scalarMultBase: (scalar: Hex) => Uint8Array;\n getSharedSecret: (privateKeyA: Hex, publicKeyB: Hex) => Uint8Array;\n getPublicKey: (privateKey: Hex) => Uint8Array;\n utils: { randomPrivateKey: () => Uint8Array };\n GuBytes: Uint8Array;\n};\n\nfunction validateOpts(curve: CurveType) {\n validateObject(\n curve,\n {\n a: 'bigint',\n },\n {\n montgomeryBits: 'isSafeInteger',\n nByteLength: 'isSafeInteger',\n adjustScalarBytes: 'function',\n domain: 'function',\n powPminus2: 'function',\n Gu: 'bigint',\n }\n );\n // Set defaults\n return Object.freeze({ ...curve } as const);\n}\n\n// NOTE: not really montgomery curve, just bunch of very specific methods for X25519/X448 (RFC 7748, https://www.rfc-editor.org/rfc/rfc7748)\n// Uses only one coordinate instead of two\nexport function montgomery(curveDef: CurveType): CurveFn {\n const CURVE = validateOpts(curveDef);\n const { P } = CURVE;\n const modP = (n: bigint) => mod(n, P);\n const montgomeryBits = CURVE.montgomeryBits;\n const montgomeryBytes = Math.ceil(montgomeryBits / 8);\n const fieldLen = CURVE.nByteLength;\n const adjustScalarBytes = CURVE.adjustScalarBytes || ((bytes: Uint8Array) => bytes);\n const powPminus2 = CURVE.powPminus2 || ((x: bigint) => pow(x, P - BigInt(2), P));\n\n // cswap from RFC7748. But it is not from RFC7748!\n /*\n cswap(swap, x_2, x_3):\n dummy = mask(swap) AND (x_2 XOR x_3)\n x_2 = x_2 XOR dummy\n x_3 = x_3 XOR dummy\n Return (x_2, x_3)\n Where mask(swap) is the all-1 or all-0 word of the same length as x_2\n and x_3, computed, e.g., as mask(swap) = 0 - swap.\n */\n function cswap(swap: bigint, x_2: bigint, x_3: bigint): [bigint, bigint] {\n const dummy = modP(swap * (x_2 - x_3));\n x_2 = modP(x_2 - dummy);\n x_3 = modP(x_3 + dummy);\n return [x_2, x_3];\n }\n\n // Accepts 0 as well\n function assertFieldElement(n: bigint): bigint {\n if (typeof n === 'bigint' && _0n <= n && n < P) return n;\n throw new Error('Expected valid scalar 0 < scalar < CURVE.P');\n }\n\n // x25519 from 4\n // The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519\n const a24 = (CURVE.a - BigInt(2)) / BigInt(4);\n /**\n *\n * @param pointU u coordinate (x) on Montgomery Curve 25519\n * @param scalar by which the point would be multiplied\n * @returns new Point on Montgomery curve\n */\n function montgomeryLadder(pointU: bigint, scalar: bigint): bigint {\n const u = assertFieldElement(pointU);\n // Section 5: Implementations MUST accept non-canonical values and process them as\n // if they had been reduced modulo the field prime.\n const k = assertFieldElement(scalar);\n const x_1 = u;\n let x_2 = _1n;\n let z_2 = _0n;\n let x_3 = u;\n let z_3 = _1n;\n let swap = _0n;\n let sw: [bigint, bigint];\n for (let t = BigInt(montgomeryBits - 1); t >= _0n; t--) {\n const k_t = (k >> t) & _1n;\n swap ^= k_t;\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n swap = k_t;\n\n const A = x_2 + z_2;\n const AA = modP(A * A);\n const B = x_2 - z_2;\n const BB = modP(B * B);\n const E = AA - BB;\n const C = x_3 + z_3;\n const D = x_3 - z_3;\n const DA = modP(D * A);\n const CB = modP(C * B);\n const dacb = DA + CB;\n const da_cb = DA - CB;\n x_3 = modP(dacb * dacb);\n z_3 = modP(x_1 * modP(da_cb * da_cb));\n x_2 = modP(AA * BB);\n z_2 = modP(E * (AA + modP(a24 * E)));\n }\n // (x_2, x_3) = cswap(swap, x_2, x_3)\n sw = cswap(swap, x_2, x_3);\n x_2 = sw[0];\n x_3 = sw[1];\n // (z_2, z_3) = cswap(swap, z_2, z_3)\n sw = cswap(swap, z_2, z_3);\n z_2 = sw[0];\n z_3 = sw[1];\n // z_2^(p - 2)\n const z2 = powPminus2(z_2);\n // Return x_2 * (z_2^(p - 2))\n return modP(x_2 * z2);\n }\n\n function encodeUCoordinate(u: bigint): Uint8Array {\n return numberToBytesLE(modP(u), montgomeryBytes);\n }\n\n function decodeUCoordinate(uEnc: Hex): bigint {\n // Section 5: When receiving such an array, implementations of X25519\n // MUST mask the most significant bit in the final byte.\n const u = ensureBytes('u coordinate', uEnc, montgomeryBytes);\n if (fieldLen === 32) u[31] &= 127; // 0b0111_1111\n return bytesToNumberLE(u);\n }\n function decodeScalar(n: Hex): bigint {\n const bytes = ensureBytes('scalar', n);\n const len = bytes.length;\n if (len !== montgomeryBytes && len !== fieldLen)\n throw new Error(`Expected ${montgomeryBytes} or ${fieldLen} bytes, got ${len}`);\n return bytesToNumberLE(adjustScalarBytes(bytes));\n }\n function scalarMult(scalar: Hex, u: Hex): Uint8Array {\n const pointU = decodeUCoordinate(u);\n const _scalar = decodeScalar(scalar);\n const pu = montgomeryLadder(pointU, _scalar);\n // The result was not contributory\n // https://cr.yp.to/ecdh.html#validate\n if (pu === _0n) throw new Error('Invalid private or public key received');\n return encodeUCoordinate(pu);\n }\n // Computes public key from private. By doing scalar multiplication of base point.\n const GuBytes = encodeUCoordinate(CURVE.Gu);\n function scalarMultBase(scalar: Hex): Uint8Array {\n return scalarMult(scalar, GuBytes);\n }\n\n return {\n scalarMult,\n scalarMultBase,\n getSharedSecret: (privateKey: Hex, publicKey: Hex) => scalarMult(privateKey, publicKey),\n getPublicKey: (privateKey: Hex): Uint8Array => scalarMultBase(privateKey),\n utils: { randomPrivateKey: () => CURVE.randomBytes!(CURVE.nByteLength) },\n GuBytes: GuBytes,\n };\n}\n", "import { Convert } from '@enbox/common';\nimport { ed25519, edwardsToMontgomeryPriv, edwardsToMontgomeryPub, x25519 } from '@noble/curves/ed25519';\n\nimport type { Jwk } from '../jose/jwk.js';\nimport type { ComputePublicKeyParams, GetPublicKeyParams, SignParams, VerifyParams } from '../types/params-direct.js';\n\nimport { computeJwkThumbprint, isOkpPrivateJwk, isOkpPublicJwk } from '../jose/jwk.js';\n\n/**\n * The `Ed25519` class provides a comprehensive suite of utilities for working with the Ed25519\n * elliptic curve, widely used in modern cryptographic applications. This class includes methods for\n * key generation, conversion, signing, verification, and public key derivation.\n *\n * The class supports conversions between raw byte formats and JSON Web Key (JWK) formats. It\n * follows the guidelines and specifications outlined in RFC8032 for EdDSA (Edwards-curve Digital\n * Signature Algorithm) operations.\n *\n * Key Features:\n * - Key Generation: Generate Ed25519 private keys in JWK format.\n * - Key Conversion: Transform keys between raw byte arrays and JWK formats.\n * - Public Key Derivation: Derive public keys from private keys.\n * - Signing and Verification: Sign data and verify signatures with Ed25519 keys.\n * - Key Validation: Validate the mathematical correctness of Ed25519 keys.\n *\n * The methods in this class are asynchronous, returning Promises to accommodate various\n * JavaScript environments, and use `Uint8Array` for binary data handling.\n *\n * @example\n * ```ts\n * // Key Generation\n * const privateKey = await Ed25519.generateKey();\n *\n * // Public Key Derivation\n * const publicKey = await Ed25519.computePublicKey({ key: privateKey });\n * console.log(publicKey === await Ed25519.getPublicKey({ key: privateKey })); // Output: true\n *\n * // EdDSA Signing\n * const signature = await Ed25519.sign({\n * key: privateKey,\n * data: new TextEncoder().encode('Message')\n * });\n *\n * // EdDSA Signature Verification\n * const isValid = await Ed25519.verify({\n * key: publicKey,\n * signature: signature,\n * data: new TextEncoder().encode('Message')\n * });\n *\n * // Key Conversion\n * const privateKeyBytes = await Ed25519.privateKeyToBytes({ privateKey });\n * const publicKeyBytes = await Ed25519.publicKeyToBytes({ publicKey });\n *\n * // Key Validation\n * const isPublicKeyValid = await Ed25519.validatePublicKey({ publicKeyBytes });\n * ```\n */\nexport class Ed25519 {\n /**\n * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n *\n * @remarks\n * This method accepts a private key as a byte array (Uint8Array) for the Curve25519 curve in\n * Twisted Edwards form and transforms it into a JWK object. The process involves first deriving\n * the public key from the private key, then encoding both the private and public keys into\n * base64url format.\n *\n * The resulting JWK object includes the following properties:\n * - `kty`: Key Type, set to 'OKP' for Octet Key Pair.\n * - `crv`: Curve Name, set to 'Ed25519'.\n * - `d`: The private key component, base64url-encoded.\n * - `x`: The computed public key, base64url-encoded.\n *\n * @example\n * ```ts\n * const privateKeyBytes = new Uint8Array([...]); // Replace with actual private key bytes\n * const privateKey = await Ed25519.bytesToPrivateKey({ privateKeyBytes });\n * ```\n *\n * @param params - The parameters for the private key conversion.\n * @param params.privateKeyBytes - The raw private key as a Uint8Array.\n *\n * @returns A Promise that resolves to the private key in JWK format.\n */\n public static async bytesToPrivateKey({ privateKeyBytes }: {\n privateKeyBytes: Uint8Array;\n }): Promise<Jwk> {\n // Derive the public key from the private key.\n const publicKeyBytes = ed25519.getPublicKey(privateKeyBytes);\n\n // Construct the private key in JWK format.\n const privateKey: Jwk = {\n crv : 'Ed25519',\n d : Convert.uint8Array(privateKeyBytes).toBase64Url(),\n kty : 'OKP',\n x : Convert.uint8Array(publicKeyBytes).toBase64Url(),\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n *\n * @remarks\n * This method accepts a public key as a byte array (Uint8Array) for the Curve25519 curve in\n * Twisted Edwards form and transforms it into a JWK object. The process involves encoding the\n * public key bytes into base64url format.\n *\n * The resulting JWK object includes the following properties:\n * - `kty`: Key Type, set to 'OKP' for Octet Key Pair.\n * - `crv`: Curve Name, set to 'X25519'.\n * - `x`: The public key, base64url-encoded.\n *\n * @example\n * ```ts\n * const publicKeyBytes = new Uint8Array([...]); // Replace with actual public key bytes\n * const publicKey = await X25519.bytesToPublicKey({ publicKeyBytes });\n * ```\n *\n * @param params - The parameters for the public key conversion.\n * @param params.publicKeyBytes - The raw public key as a `Uint8Array`.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public static async bytesToPublicKey({ publicKeyBytes }: {\n publicKeyBytes: Uint8Array;\n }): Promise<Jwk> {\n // Construct the public key in JWK format.\n const publicKey: Jwk = {\n kty : 'OKP',\n crv : 'Ed25519',\n x : Convert.uint8Array(publicKeyBytes).toBase64Url(),\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Derives the public key in JWK format from a given Ed25519 private key.\n *\n * @remarks\n * This method takes a private key in JWK format and derives its corresponding public key,\n * also in JWK format. The derivation process involves converting the private key to a\n * raw byte array and then computing the corresponding public key on the Curve25519 curve in\n * Twisted Edwards form. The public key is then encoded into base64url format to construct\n * a JWK representation.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // A Jwk object representing an Ed25519 private key\n * const publicKey = await Ed25519.computePublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for the public key derivation.\n * @param params.key - The private key in JWK format from which to derive the public key.\n *\n * @returns A Promise that resolves to the computed public key in JWK format.\n */\n public static async computePublicKey({ key }:\n ComputePublicKeyParams\n ): Promise<Jwk> {\n // Convert the provided private key to a byte array.\n const privateKeyBytes = await Ed25519.privateKeyToBytes({ privateKey: key });\n\n // Derive the public key from the private key.\n const publicKeyBytes = ed25519.getPublicKey(privateKeyBytes);\n\n // Construct the public key in JWK format.\n const publicKey: Jwk = {\n kty : 'OKP',\n crv : 'Ed25519',\n x : Convert.uint8Array(publicKeyBytes).toBase64Url()\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Converts an Ed25519 private key to its X25519 counterpart.\n *\n * @remarks\n * This method enables the use of the same key pair for both digital signature (Ed25519)\n * and key exchange (X25519) operations. It takes an Ed25519 private key and converts it\n * to the corresponding X25519 format, facilitating interoperability between signing\n * and encryption protocols.\n *\n * @example\n * ```ts\n * const ed25519PrivateKey = { ... }; // An Ed25519 private key in JWK format\n * const x25519PrivateKey = await Ed25519.convertPrivateKeyToX25519({\n * privateKey: ed25519PrivateKey\n * });\n * ```\n *\n * @param params - The parameters for the private key conversion.\n * @param params.privateKey - The Ed25519 private key to convert, in JWK format.\n *\n * @returns A Promise that resolves to the X25519 private key in JWK format.\n */\n public static async convertPrivateKeyToX25519({ privateKey }: {\n privateKey: Jwk;\n }): Promise<Jwk> {\n // Convert the provided Ed25519 private key to bytes.\n const ed25519PrivateKeyBytes = await Ed25519.privateKeyToBytes({ privateKey });\n\n // Convert the Ed25519 private key to an X25519 private key.\n const x25519PrivateKeyBytes = edwardsToMontgomeryPriv(ed25519PrivateKeyBytes);\n\n // Derive the X25519 public key from the X25519 private key.\n const x25519PublicKeyBytes = x25519.getPublicKey(x25519PrivateKeyBytes);\n\n // Construct the X25519 private key in JWK format.\n const x25519PrivateKey: Jwk = {\n kty : 'OKP',\n crv : 'X25519',\n d : Convert.uint8Array(x25519PrivateKeyBytes).toBase64Url(),\n x : Convert.uint8Array(x25519PublicKeyBytes).toBase64Url(),\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n x25519PrivateKey.kid = await computeJwkThumbprint({ jwk: x25519PrivateKey });\n\n return x25519PrivateKey;\n }\n\n /**\n * Converts an Ed25519 public key to its X25519 counterpart.\n *\n * @remarks\n * This method enables the use of the same key pair for both digital signature (Ed25519)\n * and key exchange (X25519) operations. It takes an Ed25519 public key and converts it\n * to the corresponding X25519 format, facilitating interoperability between signing\n * and encryption protocols.\n *\n * @example\n * ```ts\n * const ed25519PublicKey = { ... }; // An Ed25519 public key in JWK format\n * const x25519PublicKey = await Ed25519.convertPublicKeyToX25519({\n * publicKey: ed25519PublicKey\n * });\n * ```\n *\n * @param params - The parameters for the public key conversion.\n * @param params.publicKey - The Ed25519 public key to convert, in JWK format.\n *\n * @returns A Promise that resolves to the X25519 public key in JWK format.\n */\n public static async convertPublicKeyToX25519({ publicKey }: {\n publicKey: Jwk;\n }): Promise<Jwk> {\n // Convert the provided private key to a byte array.\n const ed25519PublicKeyBytes = await Ed25519.publicKeyToBytes({ publicKey });\n\n // Verify Edwards public key is valid.\n const isValid = await Ed25519.validatePublicKey({ publicKeyBytes: ed25519PublicKeyBytes });\n if (!isValid) {\n throw new Error('Ed25519: Invalid public key.');\n }\n\n // Convert the Ed25519 public key to an X25519 private key.\n const x25519PublicKeyBytes = edwardsToMontgomeryPub(ed25519PublicKeyBytes);\n\n // Construct the X25519 private key in JWK format.\n const x25519PublicKey: Jwk = {\n kty : 'OKP',\n crv : 'X25519',\n x : Convert.uint8Array(x25519PublicKeyBytes).toBase64Url(),\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n x25519PublicKey.kid = await computeJwkThumbprint({ jwk: x25519PublicKey });\n\n return x25519PublicKey;\n }\n\n /**\n * Generates an Ed25519 private key in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method creates a new private key suitable for use with the Curve25519 elliptic curve in\n * Twisted Edwards form. The key generation process involves using cryptographically secure\n * random number generation to ensure the uniqueness and security of the key. The resulting\n * private key adheres to the JWK format making it compatible with common cryptographic\n * standards and easy to use in various cryptographic processes.\n *\n * The generated private key in JWK format includes the following components:\n * - `kty`: Key Type, set to 'OKP' for Octet Key Pair.\n * - `crv`: Curve Name, set to 'Ed25519'.\n * - `d`: The private key component, base64url-encoded.\n * - `x`: The derived public key, base64url-encoded.\n *\n * @example\n * ```ts\n * const privateKey = await Ed25519.generateKey();\n * ```\n *\n * @returns A Promise that resolves to the generated private key in JWK format.\n */\n public static async generateKey(): Promise<Jwk> {\n // Generate a random private key.\n const privateKeyBytes = ed25519.utils.randomPrivateKey();\n\n // Convert private key from bytes to JWK format.\n const privateKey = await Ed25519.bytesToPrivateKey({ privateKeyBytes });\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Retrieves the public key properties from a given private key in JWK format.\n *\n * @remarks\n * This method extracts the public key portion from an Ed25519 private key in JWK format. It does\n * so by removing the private key property 'd' and making a shallow copy, effectively yielding the\n * public key. The method sets the 'kid' (key ID) property using the JWK thumbprint if it is not\n * already defined. This approach is used under the assumption that a private key in JWK format\n * always contains the corresponding public key properties.\n *\n * Note: This method offers a significant performance advantage, being about 100 times faster\n * than `computePublicKey()`. However, it does not mathematically validate the private key, nor\n * does it derive the public key from the private key. It simply extracts existing public key\n * properties from the private key object. This makes it suitable for scenarios where speed is\n * critical and the private key's integrity is already assured.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // A Jwk object representing an Ed25519 private key\n * const publicKey = await Ed25519.getPublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for retrieving the public key properties.\n * @param params.key - The private key in JWK format.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public static async getPublicKey({ key }:\n GetPublicKeyParams\n ): Promise<Jwk> {\n // Verify the provided JWK represents an octet key pair (OKP) Ed25519 private key.\n if (!(isOkpPrivateJwk(key) && key.crv === 'Ed25519')) {\n throw new Error(`Ed25519: The provided key is not an Ed25519 private JWK.`);\n }\n\n // Remove the private key property ('d') and make a shallow copy of the provided key.\n const { d, ...publicKey } = key;\n\n // If the key ID is undefined, set it to the JWK thumbprint.\n publicKey.kid ??= await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n *\n * @remarks\n * This method accepts a private key in JWK format and extracts its raw byte representation.\n *\n * This method accepts a public key in JWK format and converts it into its raw binary\n * form. The conversion process involves decoding the 'd' parameter of the JWK\n * from base64url format into a byte array.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // An Ed25519 private key in JWK format\n * const privateKeyBytes = await Ed25519.privateKeyToBytes({ privateKey });\n * ```\n *\n * @param params - The parameters for the private key conversion.\n * @param params.privateKey - The private key in JWK format.\n *\n * @returns A Promise that resolves to the private key as a Uint8Array.\n */\n public static async privateKeyToBytes({ privateKey }: {\n privateKey: Jwk;\n }): Promise<Uint8Array> {\n // Verify the provided JWK represents a valid OKP private key.\n if (!isOkpPrivateJwk(privateKey)) {\n throw new Error(`Ed25519: The provided key is not a valid OKP private key.`);\n }\n\n // Decode the provided private key to bytes.\n const privateKeyBytes = Convert.base64Url(privateKey.d).toUint8Array();\n\n return privateKeyBytes;\n }\n\n /**\n * Converts a public key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n *\n * @remarks\n * This method accepts a public key in JWK format and converts it into its raw binary form.\n * The conversion process involves decoding the 'x' parameter of the JWK (which represent the\n * x coordinate of the elliptic curve point) from base64url format into a byte array.\n *\n * @example\n * ```ts\n * const publicKey = { ... }; // An Ed25519 public key in JWK format\n * const publicKeyBytes = await Ed25519.publicKeyToBytes({ publicKey });\n * ```\n *\n * @param params - The parameters for the public key conversion.\n * @param params.publicKey - The public key in JWK format.\n *\n * @returns A Promise that resolves to the public key as a Uint8Array.\n */\n public static async publicKeyToBytes({ publicKey }: {\n publicKey: Jwk;\n }): Promise<Uint8Array> {\n // Verify the provided JWK represents a valid OKP public key.\n if (!isOkpPublicJwk(publicKey)) {\n throw new Error(`Ed25519: The provided key is not a valid OKP public key.`);\n }\n\n // Decode the provided public key to bytes.\n const publicKeyBytes = Convert.base64Url(publicKey.x).toUint8Array();\n\n return publicKeyBytes;\n }\n\n /**\n * Generates an RFC8032-compliant EdDSA signature of given data using an Ed25519 private key.\n *\n * @remarks\n * This method signs the provided data with a specified private key using the EdDSA\n * (Edwards-curve Digital Signature Algorithm) as defined in RFC8032. It\n * involves converting the private key from JWK format to a byte array and then employing\n * the Ed25519 algorithm to sign the data. The output is a digital signature in the form\n * of a Uint8Array, uniquely corresponding to both the data and the private key used for\n * signing.\n *\n * @example\n * ```ts\n * const data = new TextEncoder().encode('Messsage'); // Data to be signed\n * const privateKey = { ... }; // A Jwk object representing an Ed25519 private key\n * const signature = await Ed25519.sign({ key: privateKey, data });\n * ```\n *\n * @param params - The parameters for the signing operation.\n * @param params.key - The private key to use for signing, represented in JWK format.\n * @param params.data - The data to sign, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to the signature as a Uint8Array.\n */\n public static async sign({ key, data }:\n SignParams\n ): Promise<Uint8Array> {\n // Convert the private key from JWK format to bytes.\n const privateKeyBytes = await Ed25519.privateKeyToBytes({ privateKey: key });\n\n // Sign the provided data using the EdDSA algorithm.\n const signature = ed25519.sign(data, privateKeyBytes);\n\n return signature;\n }\n\n /**\n * Validates a given public key to confirm its mathematical correctness on the Edwards curve.\n *\n * @remarks\n * This method decodes the Edwards points from the key bytes and asserts their validity on the\n * Curve25519 curve in Twisted Edwards form. If the points are not valid, the method returns\n * false. If the points are valid, the method returns true.\n *\n * Note that this validation strictly pertains to the key's format and numerical validity; it does\n * not assess whether the key corresponds to a known entity or its security status (e.g., whether\n * it has been compromised).\n *\n * @example\n * ```ts\n * const publicKeyBytes = new Uint8Array([...]); // A public key in byte format\n * const isValid = await Ed25519.validatePublicKey({ publicKeyBytes });\n * console.log(isValid); // true if the key is valid on the Edwards curve, false otherwise\n * ```\n *\n * @param params - The parameters for the public key validation.\n * @param params.publicKeyBytes - The public key to validate, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to a boolean indicating whether the key\n * corresponds to a valid point on the Edwards curve.\n */\n public static async validatePublicKey({ publicKeyBytes }: {\n publicKeyBytes: Uint8Array;\n }): Promise<boolean> {\n try {\n // Decode Edwards points from key bytes.\n const point = ed25519.ExtendedPoint.fromHex(publicKeyBytes);\n\n // Check if points are on the Twisted Edwards curve.\n point.assertValidity();\n\n } catch {\n return false;\n }\n\n return true;\n }\n\n /**\n * Verifies an RFC8032-compliant EdDSA signature against given data using an Ed25519 public key.\n *\n * @remarks\n * This method validates a digital signature to ensure its authenticity and integrity.\n * It uses the EdDSA (Edwards-curve Digital Signature Algorithm) as specified in RFC8032.\n * The verification process involves converting the public key from JWK format to a raw\n * byte array and using the Ed25519 algorithm to validate the signature against the provided data.\n *\n * @example\n * ```ts\n * const data = new TextEncoder().encode('Messsage'); // Data that was signed\n * const publicKey = { ... }; // A Jwk object representing an Ed25519 public key\n * const signature = new Uint8Array([...]); // Signature to verify\n * const isValid = await Ed25519.verify({ key: publicKey, signature, data });\n * console.log(isValid); // true if the signature is valid, false otherwise\n * ```\n *\n * @param params - The parameters for the signature verification.\n * @param params.key - The public key in JWK format used for verification.\n * @param params.signature - The signature to verify, represented as a Uint8Array.\n * @param params.data - The data that was signed, represented as a Uint8Array.\n *\n * @returns A Promise that resolves to a boolean indicating whether the signature is valid.\n */\n public static async verify({ key, signature, data }:\n VerifyParams\n ): Promise<boolean> {\n // Convert the public key from JWK format to bytes.\n const publicKeyBytes = await Ed25519.publicKeyToBytes({ publicKey: key });\n\n // Perform the verification of the signature.\n const isValid = ed25519.verify(signature, data, publicKeyBytes);\n\n return isValid;\n }\n}", "import type { AsymmetricKeyGenerator } from '../types/key-generator.js';\nimport type { Jwk } from '../jose/jwk.js';\nimport type { Signer } from '../types/signer.js';\nimport type {\n ComputePublicKeyParams,\n GenerateKeyParams,\n GetPublicKeyParams,\n SignParams,\n VerifyParams,\n} from '../types/params-direct.js';\n\nimport { CryptoAlgorithm } from './crypto-algorithm.js';\nimport { Ed25519 } from '../primitives/ed25519.js';\nimport { isOkpPrivateJwk, isOkpPublicJwk } from '../jose/jwk.js';\n\n/**\n * The `EdDsaGenerateKeyParams` interface defines the algorithm-specific parameters that should be\n * passed into the `generateKey()` method when using the EdDSA algorithm.\n */\nexport interface EdDsaGenerateKeyParams extends GenerateKeyParams {\n /**\n * A string defining the type of key to generate. The value must be one of the following:\n * - `\"Ed25519\"`: EdDSA using the Ed25519 curve.\n */\n algorithm: 'Ed25519';\n}\n\n/**\n * The `EdDsaAlgorithm` class provides a concrete implementation for cryptographic operations using\n * the Edwards-curve Digital Signature Algorithm (EdDSA). This class implements both\n * {@link Signer | `Signer`} and { @link AsymmetricKeyGenerator | `AsymmetricKeyGenerator`}\n * interfaces, providing private key generation, public key derivation, and creation/verification\n * of signatures.\n *\n * This class is typically accessed through implementations that extend the\n * {@link CryptoApi | `CryptoApi`} interface.\n */\nexport class EdDsaAlgorithm extends CryptoAlgorithm\n implements AsymmetricKeyGenerator<EdDsaGenerateKeyParams, Jwk, GetPublicKeyParams>,\n Signer<SignParams, VerifyParams> {\n\n /**\n * Derives the public key in JWK format from a given private key.\n *\n * @remarks\n * This method takes a private key in JWK format and derives its corresponding public key,\n * also in JWK format. The process ensures that the derived public key correctly corresponds to\n * the given private key.\n *\n * @example\n * ```ts\n * const eddsa = new EdDsaAlgorithm();\n * const privateKey = { ... }; // A Jwk object representing a private key\n * const publicKey = await eddsa.computePublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for the public key derivation.\n * @param params.key - The private key in JWK format from which to derive the public key.\n *\n * @returns A Promise that resolves to the derived public key in JWK format.\n */\n public async computePublicKey({ key }:\n ComputePublicKeyParams\n ): Promise<Jwk> {\n if (!isOkpPrivateJwk(key)) {throw new TypeError('Invalid key provided. Must be an octet key pair (OKP) private key.');}\n\n switch (key.crv) {\n\n case 'Ed25519': {\n const publicKey = await Ed25519.computePublicKey({ key });\n publicKey.alg = 'EdDSA';\n return publicKey;\n }\n\n default: {\n throw new Error(`Unsupported curve: ${key.crv}`);\n }\n }\n }\n\n /**\n * Generates a new private key with the specified algorithm in JSON Web Key (JWK) format.\n *\n * @example\n * ```ts\n * const eddsa = new EdDsaAlgorithm();\n * const privateKey = await eddsa.generateKey({ algorithm: 'Ed25519' });\n * ```\n *\n * @param params - The parameters for key generation.\n * @param params.algorithm - The algorithm to use for key generation.\n *\n * @returns A Promise that resolves to the generated private key in JWK format.\n */\n async generateKey({ algorithm }:\n EdDsaGenerateKeyParams\n ): Promise<Jwk> {\n switch (algorithm) {\n\n case 'Ed25519': {\n const privateKey = await Ed25519.generateKey();\n privateKey.alg = 'EdDSA';\n return privateKey;\n }\n }\n }\n\n /**\n * Retrieves the public key properties from a given private key in JWK format.\n *\n * @remarks\n * This method extracts the public key portion from an EdDSA private key in JWK format. It does\n * so by removing the private key property 'd' and making a shallow copy, effectively yielding the\n * public key.\n *\n * Note: This method offers a significant performance advantage, being about 100 times faster\n * than `computePublicKey()`. However, it does not mathematically validate the private key, nor\n * does it derive the public key from the private key. It simply extracts existing public key\n * properties from the private key object. This makes it suitable for scenarios where speed is\n * critical and the private key's integrity is already assured.\n *\n * @example\n * ```ts\n * const eddsa = new EdDsaAlgorithm();\n * const privateKey = { ... }; // A Jwk object representing a private key\n * const publicKey = await eddsa.getPublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for retrieving the public key properties.\n * @param params.key - The private key in JWK format.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public async getPublicKey({ key }:\n GetPublicKeyParams\n ): Promise<Jwk> {\n if (!isOkpPrivateJwk(key)) {throw new TypeError('Invalid key provided. Must be an octet key pair (OKP) private key.');}\n\n switch (key.crv) {\n\n case 'Ed25519': {\n const publicKey = await Ed25519.getPublicKey({ key });\n publicKey.alg = 'EdDSA';\n return publicKey;\n }\n\n default: {\n throw new Error(`Unsupported curve: ${key.crv}`);\n }\n }\n }\n\n /**\n * Generates an EdDSA signature of given data using a private key.\n *\n * @remarks\n * This method uses the signature algorithm determined by the given `algorithm` to sign the\n * provided data.\n *\n * The signature can later be verified by parties with access to the corresponding\n * public key, ensuring that the data has not been tampered with and was indeed signed by the\n * holder of the private key.\n *\n * @example\n * ```ts\n * const eddsa = new EdDsaAlgorithm();\n * const data = new TextEncoder().encode('Message');\n * const privateKey = { ... }; // A Jwk object representing a private key\n * const signature = await eddsa.sign({\n * key: privateKey,\n * data\n * });\n * ```\n *\n * @param params - The parameters for the signing operation.\n * @param params.key - The private key to use for signing, represented in JWK format.\n * @param params.data - The data to sign.\n *\n * @returns A Promise resolving to the digital signature as a `Uint8Array`.\n */\n public async sign({ key, data }:\n SignParams\n ): Promise<Uint8Array> {\n if (!isOkpPrivateJwk(key)) {throw new TypeError('Invalid key provided. Must be an octet key pair (OKP) private key.');}\n\n switch (key.crv) {\n\n case 'Ed25519': {\n return await Ed25519.sign({ key, data });\n }\n\n default: {\n throw new Error(`Unsupported curve: ${key.crv}`);\n }\n }\n }\n\n /**\n * Verifies an EdDSA signature associated with the provided data using the provided key.\n *\n * @remarks\n * This method uses the signature algorithm determined by the `crv` property of the provided key\n * to check the validity of a digital signature against the original data. It confirms whether the\n * signature was created by the holder of the corresponding private key and that the data has not\n * been tampered with.\n *s\n * @example\n * ```ts\n * const eddsa = new EdDsaAlgorithm();\n * const publicKey = { ... }; // Public key in JWK format corresponding to the private key that signed the data\n * const signature = new Uint8Array([...]); // Signature to verify\n * const data = new TextEncoder().encode('Message');\n * const isValid = await eddsa.verify({\n * key: publicKey,\n * signature,\n * data\n * });\n * ```\n *\n * @param params - The parameters for the verification operation.\n * @param params.key - The key to use for verification.\n * @param params.signature - The signature to verify.\n * @param params.data - The data to verify.\n *\n * @returns A Promise resolving to a boolean indicating whether the signature is valid.\n */\n public async verify({ key, signature, data }:\n VerifyParams\n ): Promise<boolean> {\n if (!isOkpPublicJwk(key)) {throw new TypeError('Invalid key provided. Must be an octet key pair (OKP) public key.');}\n\n switch (key.crv) {\n\n case 'Ed25519': {\n return await Ed25519.verify({ key, signature, data });\n }\n\n default: {\n throw new Error(`Unsupported curve: ${key.crv}`);\n }\n }\n }\n}", "import type { DigestParams } from '../types/params-direct.js';\nimport type { Hasher } from '../types/hasher.js';\n\nimport { CryptoAlgorithm } from './crypto-algorithm.js';\nimport { Sha256 } from '../primitives/sha256.js';\n\n/**\n * The `Sha2DigestParams` interface defines the algorithm-specific parameters that should be\n * passed into the `digest()` method when using the SHA-2 algorithm.\n */\nexport interface Sha2DigestParams extends DigestParams {\n /**\n * A string defining the name of hash function to use. The value must be one of the following:\n * - `\"SHA-256\"`: Generates a 256-bit digest.\n */\n algorithm: 'SHA-256';\n}\n\n/**\n * The `Sha2Algorithm` class is an implementation of the {@link Hasher | `Hasher`} interface for the\n * SHA-2 family of cryptographic hash functions. The `digest` method takes the algorithm identifier\n * of the hash function and arbitrary data as input and returns the hash digest of the data.\n *\n * This class is typically accessed through implementations that extend the\n * {@link CryptoApi | `CryptoApi`} interface.\n */\nexport class Sha2Algorithm extends CryptoAlgorithm\n implements Hasher<Sha2DigestParams> {\n\n /**\n * Generates a hash digest of the provided data.\n *\n * @remarks\n * A digest is the output of the hash function. It's a fixed-size string of bytes\n * that uniquely represents the data input into the hash function. The digest is often used for\n * data integrity checks, as any alteration in the input data results in a significantly\n * different digest.\n *\n * It takes the algorithm identifier of the hash function and data to digest as input and returns\n * the digest of the data.\n *\n * @example\n * ```ts\n * const sha2 = new Sha2Algorithm();\n * const data = new TextEncoder().encode('Messsage');\n * const digest = await sha2.digest({ data });\n * ```\n *\n * @param params - The parameters for the digest operation.\n * @param params.algorithm - The name of hash function to use.\n * @param params.data - The data to digest.\n *\n * @returns A Promise which will be fulfilled with the hash digest.\n */\n public async digest({ algorithm, data }: Sha2DigestParams): Promise<Uint8Array> {\n switch (algorithm) {\n\n case 'SHA-256': {\n const hash = await Sha256.digest({ data });\n return hash;\n }\n }\n\n }\n}", "import type { KeyValueStore } from '@enbox/common';\nimport { MemoryStore } from '@enbox/common';\n\nimport type { CryptoAlgorithm } from './algorithms/crypto-algorithm.js';\nimport type { CryptoApi } from './types/crypto-api.js';\nimport type { Hasher } from './types/hasher.js';\nimport type { Jwk } from './jose/jwk.js';\nimport type { KeyIdentifier } from './types/identifier.js';\nimport type { KeyImporterExporter } from './types/key-io.js';\nimport type { Signer } from './types/signer.js';\nimport type { AsymmetricKeyGenerator, KeyGenerator } from './types/key-generator.js';\nimport type { GetPublicKeyParams, SignParams, VerifyParams } from './types/params-direct.js';\nimport type {\n KmsDigestParams,\n KmsExportKeyParams,\n KmsGenerateKeyParams,\n KmsGetKeyUriParams,\n KmsGetPublicKeyParams,\n KmsImportKeyParams,\n KmsSignParams,\n KmsVerifyParams,\n} from './types/params-kms.js';\n\nimport { EcdsaAlgorithm } from './algorithms/ecdsa.js';\nimport { EdDsaAlgorithm } from './algorithms/eddsa.js';\nimport { Sha2Algorithm } from './algorithms/sha-2.js';\nimport { computeJwkThumbprint, isPrivateJwk, KEY_URI_PREFIX_JWK } from './jose/jwk.js';\n\n/**\n * `supportedAlgorithms` is an object mapping algorithm names to their respective implementations\n * Each entry in this map specifies the algorithm name and its associated properties, including the\n * implementation class and any relevant names or identifiers for the algorithm. This structure\n * allows for easy retrieval and instantiation of algorithm implementations based on the algorithm\n * name or key specification. It facilitates the support of multiple algorithms within the\n * `LocalKeyManager` class.\n */\nconst supportedAlgorithms = {\n 'Ed25519': {\n implementation : EdDsaAlgorithm,\n names : ['Ed25519'],\n },\n 'secp256k1': {\n implementation : EcdsaAlgorithm,\n names : ['ES256K', 'secp256k1'],\n },\n 'secp256r1': {\n implementation : EcdsaAlgorithm,\n names : ['ES256', 'secp256r1'],\n },\n 'SHA-256': {\n implementation : Sha2Algorithm,\n names : ['SHA-256']\n }\n} satisfies {\n [key: string]: {\n implementation : typeof CryptoAlgorithm;\n names : string[];\n }\n};\n\n/* Helper type for `supportedAlgorithms`. */\ntype SupportedAlgorithm = keyof typeof supportedAlgorithms;\n\n/* Helper type for `supportedAlgorithms` implementations. */\ntype AlgorithmConstructor = typeof supportedAlgorithms[SupportedAlgorithm]['implementation'];\n\n/**\n * The `LocalKeyManagerParams` interface specifies the parameters for initializing an instance of\n * `LocalKeyManager`. It allows the optional inclusion of a `KeyValueStore` instance for key\n * management. If not provided, a default `MemoryStore` instance will be used for storing keys in\n * memory. Note that the `MemoryStore` is not persistent and will be cleared when the application\n * exits.\n */\nexport type LocalKeyManagerParams = {\n /**\n * An optional property to specify a custom `KeyValueStore` instance for key management. If not\n * provided, {@link LocalKeyManager | `LocalKeyManager`} uses a default `MemoryStore` instance.\n * This store is responsible for managing cryptographic keys, allowing them to be retrieved,\n * stored, and managed during cryptographic operations.\n */\n keyStore?: KeyValueStore<KeyIdentifier, Jwk>;\n};\n\n/**\n * The `LocalKeyManagerDigestParams` interface defines the algorithm-specific parameters that should\n * be passed into the {@link LocalKeyManager.digest | `LocalKeyManager.digest()`} method.\n */\nexport interface LocalKeyManagerDigestParams extends KmsDigestParams {\n /**\n * A string defining the name of hash function to use. The value must be one of the following:\n * - `\"SHA-256\"`: Generates a 256-bit digest.\n */\n algorithm: 'SHA-256';\n}\n\n/**\n * The `LocalKeyManagerGenerateKeyParams` interface defines the algorithm-specific parameters that\n * should be passed into the {@link LocalKeyManager.generateKey | `LocalKeyManager.generateKey()`}\n * method when generating a key in the local KMS.\n */\nexport interface LocalKeyManagerGenerateKeyParams extends KmsGenerateKeyParams {\n /**\n * A string defining the type of key to generate. The value must be one of the following:\n * - `\"Ed25519\"`\n * - `\"secp256k1\"`\n */\n algorithm: 'Ed25519' | 'secp256k1' | 'secp256r1';\n}\n\nexport class LocalKeyManager implements\n CryptoApi,\n KeyImporterExporter<KmsImportKeyParams, KeyIdentifier, KmsExportKeyParams> {\n\n /**\n * A private map that stores instances of cryptographic algorithm implementations. Each key in\n * this map is an `AlgorithmConstructor`, and its corresponding value is an instance of a class\n * that implements a specific cryptographic algorithm. This map is used to cache and reuse\n * instances for performance optimization, ensuring that each algorithm is instantiated only once.\n */\n private _algorithmInstances: Map<AlgorithmConstructor, InstanceType<typeof CryptoAlgorithm>> = new Map();\n\n /**\n * The `_keyStore` private variable in `LocalKeyManager` is a `KeyValueStore` instance used for\n * storing and managing cryptographic keys. It allows the `LocalKeyManager` class to save,\n * retrieve, and handle keys efficiently within the local Key Management System (KMS) context.\n * This variable can be configured to use different storage backends, like in-memory storage or\n * persistent storage, providing flexibility in key management according to the application's\n * requirements.\n */\n private _keyStore: KeyValueStore<KeyIdentifier, Jwk>;\n\n constructor(params?: LocalKeyManagerParams) {\n this._keyStore = params?.keyStore ?? new MemoryStore<KeyIdentifier, Jwk>();\n }\n\n /**\n * Generates a hash digest of the provided data.\n *\n * @remarks\n * A digest is the output of the hash function. It's a fixed-size string of bytes\n * that uniquely represents the data input into the hash function. The digest is often used for\n * data integrity checks, as any alteration in the input data results in a significantly\n * different digest.\n *\n * It takes the algorithm identifier of the hash function and data to digest as input and returns\n * the digest of the data.\n *\n * @example\n * ```ts\n * const keyManager = new LocalKeyManager();\n * const data = new Uint8Array([...]);\n * const digest = await keyManager.digest({ algorithm: 'SHA-256', data });\n * ```\n *\n * @param params - The parameters for the digest operation.\n * @param params.algorithm - The name of hash function to use.\n * @param params.data - The data to digest.\n *\n * @returns A Promise which will be fulfilled with the hash digest.\n */\n public async digest({ algorithm, data }:\n LocalKeyManagerDigestParams\n ): Promise<Uint8Array> {\n // Get the hash function implementation based on the specified `algorithm` parameter.\n const hasher = this.getAlgorithm({ algorithm }) as Hasher<KmsDigestParams>;\n\n // Compute the hash.\n const hash = await hasher.digest({ algorithm, data });\n\n return hash;\n }\n\n /**\n * Exports a private key identified by the provided key URI from the local KMS.\n *\n * @remarks\n * This method retrieves the key from the key store and returns it. It is primarily used\n * for extracting keys for backup or transfer purposes.\n *\n * @example\n * ```ts\n * const keyManager = new LocalKeyManager();\n * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n * const privateKey = await keyManager.exportKey({ keyUri });\n * ```\n *\n * @param params - Parameters for exporting the key.\n * @param params.keyUri - The key URI identifying the key to export.\n *\n * @returns A Promise resolving to the JWK representation of the exported key.\n */\n public async exportKey({ keyUri }:\n KmsExportKeyParams\n ): Promise<Jwk> {\n // Get the private key from the key store.\n const privateKey = await this.getPrivateKey({ keyUri });\n\n return privateKey;\n }\n\n /**\n * Generates a new cryptographic key in the local KMS with the specified algorithm and returns a\n * unique key URI which can be used to reference the key in subsequent operations.\n *\n * @example\n * ```ts\n * const keyManager = new LocalKeyManager();\n * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n * console.log(keyUri); // Outputs the key URI\n * ```\n *\n * @param params - The parameters for key generation.\n * @param params.algorithm - The algorithm to use for key generation, defined in `SupportedAlgorithm`.\n *\n * @returns A Promise that resolves to the key URI, a unique identifier for the generated key.\n */\n public async generateKey({ algorithm }:\n LocalKeyManagerGenerateKeyParams\n ): Promise<KeyIdentifier> {\n // Get the key generator implementation based on the specified `algorithm` parameter.\n const keyGenerator = this.getAlgorithm({ algorithm }) as KeyGenerator<LocalKeyManagerGenerateKeyParams, Jwk>;\n\n // Generate the key.\n const key = await keyGenerator.generateKey({ algorithm });\n\n if (key?.kid === undefined) {\n throw new Error('Generated key is missing a required property: kid');\n }\n\n // Construct the key URI.\n const keyUri = `${KEY_URI_PREFIX_JWK}${key.kid}`;\n\n // Store the key in the key store.\n await this._keyStore.set(keyUri, key);\n\n return keyUri;\n }\n\n /**\n * Computes the Key URI for a given public JWK (JSON Web Key).\n *\n * @remarks\n * This method generates a {@link https://datatracker.ietf.org/doc/html/rfc3986 | URI}\n * (Uniform Resource Identifier) for the given JWK, which uniquely identifies the key across all\n * `CryptoApi` implementations. The key URI is constructed by appending the\n * {@link https://datatracker.ietf.org/doc/html/rfc7638 | JWK thumbprint} to the prefix\n * `urn:jwk:`. The JWK thumbprint is deterministically computed from the JWK and is consistent\n * regardless of property order or optional property inclusion in the JWK. This ensures that the\n * same key material represented as a JWK will always yield the same thumbprint, and therefore,\n * the same key URI.\n *\n * @example\n * ```ts\n * const keyManager = new LocalKeyManager();\n * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n * const publicKey = await keyManager.getPublicKey({ keyUri });\n * const keyUriFromPublicKey = await keyManager.getKeyUri({ key: publicKey });\n * console.log(keyUri === keyUriFromPublicKey); // Outputs `true`\n * ```\n *\n * @param params - The parameters for getting the key URI.\n * @param params.key - The JWK for which to compute the key URI.\n *\n * @returns A Promise that resolves to the key URI as a string.\n */\n public async getKeyUri({ key }:\n KmsGetKeyUriParams\n ): Promise<KeyIdentifier> {\n // Compute the JWK thumbprint.\n const jwkThumbprint = await computeJwkThumbprint({ jwk: key });\n\n // Construct the key URI by appending the JWK thumbprint to the key URI prefix.\n const keyUri = `${KEY_URI_PREFIX_JWK}${jwkThumbprint}`;\n\n return keyUri;\n }\n\n /**\n * Retrieves the public key associated with a previously generated private key, identified by\n * the provided key URI.\n *\n * @example\n * ```ts\n * const keyManager = new LocalKeyManager();\n * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n * const publicKey = await keyManager.getPublicKey({ keyUri });\n * ```\n *\n * @param params - The parameters for retrieving the public key.\n * @param params.keyUri - The key URI of the private key to retrieve the public key for.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public async getPublicKey({ keyUri }:\n KmsGetPublicKeyParams\n ): Promise<Jwk> {\n // Get the private key from the key store.\n const privateKey = await this.getPrivateKey({ keyUri });\n\n // Determine the algorithm name based on the JWK's `alg` and `crv` properties.\n const algorithm = this.getAlgorithmName({ key: privateKey });\n\n // Get the key generator based on the algorithm name.\n const keyGenerator = this.getAlgorithm({ algorithm }) as AsymmetricKeyGenerator<LocalKeyManagerGenerateKeyParams, Jwk, GetPublicKeyParams>;\n\n // Get the public key properties from the private JWK.\n const publicKey = await keyGenerator.getPublicKey({ key: privateKey });\n\n return publicKey;\n }\n\n /**\n * Imports a private key into the local KMS.\n *\n * @remarks\n * This method stores the provided JWK in the key store, making it available for subsequent\n * cryptographic operations. It is particularly useful for initializing the KMS with pre-existing\n * keys or for restoring keys from backups.\n *\n * Note that, if defined, the `kid` (key ID) property of the JWK is used as the key URI for the\n * imported key. If the `kid` property is not provided, the key URI is computed from the JWK\n * thumbprint of the key.\n *\n * @example\n * ```ts\n * const keyManager = new LocalKeyManager();\n * const privateKey = { ... } // A private key in JWK format\n * const keyUri = await keyManager.importKey({ key: privateKey });\n * ```\n *\n * @param params - Parameters for importing the key.\n * @param params.key - The private key to import to in JWK format.\n *\n * @returns A Promise resolving to the key URI, uniquely identifying the imported key.\n */\n public async importKey({ key }:\n KmsImportKeyParams\n ): Promise<KeyIdentifier> {\n if (!isPrivateJwk(key)) {throw new TypeError('Invalid key provided. Must be a private key in JWK format.');}\n\n // Make a deep copy of the key to avoid mutating the original.\n const privateKey = structuredClone(key);\n\n // If the key ID is undefined, set it to the JWK thumbprint.\n privateKey.kid ??= await computeJwkThumbprint({ jwk: privateKey });\n\n // Compute the key URI for the key.\n const keyUri = await this.getKeyUri({ key: privateKey });\n\n // Store the key in the key store.\n await this._keyStore.set(keyUri, privateKey);\n\n return keyUri;\n }\n\n /**\n * Signs the provided data using the private key identified by the provided key URI.\n *\n * @remarks\n * This method uses the signature algorithm determined by the `alg` and/or `crv` properties of the\n * private key identified by the provided key URI to sign the provided data. The signature can\n * later be verified by parties with access to the corresponding public key, ensuring that the\n * data has not been tampered with and was indeed signed by the holder of the private key.\n *\n * @example\n * ```ts\n * const keyManager = new LocalKeyManager();\n * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n * const data = new TextEncoder().encode('Message to sign');\n * const signature = await keyManager.sign({ keyUri, data });\n * ```\n *\n * @param params - The parameters for the signing operation.\n * @param params.keyUri - The key URI of the private key to use for signing.\n * @param params.data - The data to sign.\n *\n * @returns A Promise resolving to the digital signature as a `Uint8Array`.\n */\n public async sign({ keyUri, data }:\n KmsSignParams\n ): Promise<Uint8Array> {\n // Get the private key from the key store.\n const privateKey = await this.getPrivateKey({ keyUri });\n\n // Determine the algorithm name based on the JWK's `alg` and `crv` properties.\n const algorithm = this.getAlgorithmName({ key: privateKey });\n\n // Get the signature algorithm based on the algorithm name.\n const signer = this.getAlgorithm({ algorithm }) as Signer<SignParams, VerifyParams>;\n\n // Sign the data.\n const signature = signer.sign({ data, key: privateKey });\n\n return signature;\n }\n\n /**\n * Verifies a digital signature associated the provided data using the provided key.\n *\n * @remarks\n * This method uses the signature algorithm determined by the `alg` and/or `crv` properties of the\n * provided key to check the validity of a digital signature against the original data. It\n * confirms whether the signature was created by the holder of the corresponding private key and\n * that the data has not been tampered with.\n *\n * @example\n * ```ts\n * const keyManager = new LocalKeyManager();\n * const keyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n * const data = new TextEncoder().encode('Message to sign');\n * const signature = await keyManager.sign({ keyUri, data });\n * const isSignatureValid = await keyManager.verify({ keyUri, data, signature });\n * ```\n *\n * @param params - The parameters for the verification operation.\n * @param params.key - The key to use for verification.\n * @param params.signature - The signature to verify.\n * @param params.data - The data to verify.\n *\n * @returns A Promise resolving to a boolean indicating whether the signature is valid.\n */\n public async verify({ key, signature, data }:\n KmsVerifyParams\n ): Promise<boolean> {\n // Determine the algorithm name based on the JWK's `alg` and `crv` properties.\n const algorithm = this.getAlgorithmName({ key });\n\n // Get the signature algorithm based on the algorithm name.\n const signer = this.getAlgorithm({ algorithm }) as Signer<SignParams, VerifyParams>;\n\n // Verify the signature.\n const isSignatureValid = signer.verify({ key, signature, data });\n\n return isSignatureValid;\n }\n\n /**\n * Retrieves an algorithm implementation instance based on the provided algorithm name.\n *\n * @remarks\n * This method checks if the requested algorithm is supported and returns a cached instance\n * if available. If an instance does not exist, it creates and caches a new one. This approach\n * optimizes performance by reusing algorithm instances across cryptographic operations.\n *\n * @example\n * ```ts\n * const signer = this.getAlgorithm({ algorithm: 'Ed25519' });\n * ```\n *\n * @param params - The parameters for retrieving the algorithm implementation.\n * @param params.algorithm - The name of the algorithm to retrieve.\n *\n * @returns An instance of the requested algorithm implementation.\n *\n * @throws Error if the requested algorithm is not supported.\n */\n private getAlgorithm({ algorithm }: {\n algorithm: SupportedAlgorithm;\n }): InstanceType<typeof CryptoAlgorithm> {\n // Check if algorithm is supported.\n const AlgorithmImplementation = supportedAlgorithms[algorithm]?.['implementation'];\n if (!AlgorithmImplementation) {\n throw new Error(`Algorithm not supported: ${algorithm}`);\n }\n\n // Check if instance already exists for the `AlgorithmImplementation`.\n if (!this._algorithmInstances.has(AlgorithmImplementation)) {\n // If not, create a new instance and store it in the cache\n this._algorithmInstances.set(AlgorithmImplementation, new AlgorithmImplementation());\n }\n\n // Return the cached instance\n return this._algorithmInstances.get(AlgorithmImplementation)!;\n }\n\n /**\n * Determines the name of the algorithm based on the key's properties.\n *\n * @remarks\n * This method facilitates the identification of the correct algorithm for cryptographic\n * operations based on the `alg` or `crv` properties of a {@link Jwk | JWK}.\n *\n * @example\n * ```ts\n * const publicKey = { ... }; // Public key in JWK format\n * const algorithm = this.getAlgorithmName({ key: publicKey });\n * ```\n *\n * @param params - The parameters for determining the algorithm name.\n * @param params.key - A JWK containing the `alg` or `crv` properties.\n *\n * @returns The name of the algorithm associated with the key.\n *\n * @throws Error if the algorithm cannot be determined from the provided input.\n */\n private getAlgorithmName({ key }: {\n key: { alg?: string, crv?: string };\n }): SupportedAlgorithm {\n const algProperty = key.alg;\n const crvProperty = key.crv;\n\n for (const algName in supportedAlgorithms) {\n const algorithmInfo = supportedAlgorithms[algName as SupportedAlgorithm];\n if (algProperty && algorithmInfo.names.includes(algProperty)) {\n return algName as SupportedAlgorithm;\n } else if (crvProperty && algorithmInfo.names.includes(crvProperty)) {\n return algName as SupportedAlgorithm;\n }\n }\n\n throw new Error(`Unable to determine algorithm based on provided input: alg=${algProperty}, crv=${crvProperty}`);\n }\n\n /**\n * Retrieves a private key from the key store based on the provided key URI.\n *\n * @example\n * ```ts\n * const privateKey = this.getPrivateKey({ keyUri: 'urn:jwk:...' });\n * ```\n *\n * @param params - Parameters for retrieving the private key.\n * @param params.keyUri - The key URI identifying the private key to retrieve.\n *\n * @returns A Promise resolving to the JWK representation of the private key.\n *\n * @throws Error if the key is not found in the key store.\n */\n private async getPrivateKey({ keyUri }: {\n keyUri: KeyIdentifier;\n }): Promise<Jwk> {\n // Get the private key from the key store.\n const privateKey = await this._keyStore.get(keyUri);\n\n if (!privateKey) {\n throw new Error(`Key not found: ${keyUri}`);\n }\n\n return privateKey;\n }\n}", "import type { Jwk } from './jose/jwk.js';\n\nimport { crypto } from '@noble/hashes/crypto';\nimport { randomBytes as nobleRandomBytes } from '@noble/hashes/utils';\n\n/**\n * A collection of cryptographic utility methods.\n */\nexport class CryptoUtils {\n\n /**\n * Determines the JOSE algorithm identifier of the digital signature algorithm based on the `alg` or\n * `crv` property of a {@link Jwk | JWK}.\n *\n * If the `alg` property is present, its value takes precedence and is returned. Otherwise, the\n * `crv` property is used to determine the algorithm.\n *\n * @memberof CryptoUtils\n * @see {@link https://www.iana.org/assignments/jose/jose.xhtml#web-signature-encryption-algorithms | JOSE Algorithms}\n * @see {@link https://datatracker.ietf.org/doc/draft-ietf-jose-fully-specified-algorithms/ | Fully-Specified Algorithms for JOSE and COSE}\n *\n * @example\n * ```ts\n * const publicKey: Jwk = {\n * \"kty\": \"OKP\",\n * \"crv\": \"Ed25519\",\n * \"x\": \"FEJG7OakZi500EydXxuE8uMc8uaAzEJkmQeG8khXANw\"\n * }\n * const algorithm = getJoseSignatureAlgorithmFromPublicKey(publicKey);\n * console.log(algorithm); // Output: \"EdDSA\"\n * ```\n * @param publicKey - A JWK containing the `alg` and/or `crv` properties.\n * @returns The name of the algorithm associated with the key.\n * @throws Error if the algorithm cannot be determined from the provided input.\n */\n static getJoseSignatureAlgorithmFromPublicKey(publicKey: Jwk): string {\n const curveToJoseAlgorithm: Record<string, string> = {\n 'Ed25519' : 'EdDSA',\n 'P-256' : 'ES256',\n 'P-384' : 'ES384',\n 'P-521' : 'ES512',\n 'secp256k1' : 'ES256K',\n };\n\n // If the key contains an `alg` property that matches a JOSE registered algorithm identifier,\n // return its value.\n if (publicKey.alg && Object.values(curveToJoseAlgorithm).includes(publicKey.alg)) {\n return publicKey.alg;\n }\n\n // If the key contains a `crv` property, return the corresponding algorithm.\n if (publicKey.crv && Object.keys(curveToJoseAlgorithm).includes(publicKey.crv)) {\n return curveToJoseAlgorithm[publicKey.crv];\n }\n\n throw new Error(\n `Unable to determine algorithm based on provided input: alg=${publicKey.alg}, crv=${publicKey.crv}. ` +\n `Supported 'alg' values: ${Object.values(curveToJoseAlgorithm).join(', ')}. ` +\n `Supported 'crv' values: ${Object.keys(curveToJoseAlgorithm).join(', ')}.`\n );\n }\n\n /**\n * Generates secure pseudorandom values of the specified length using\n * `crypto.getRandomValues`, which defers to the operating system.\n *\n * @memberof CryptoUtils\n * @remarks\n * This function is a wrapper around `randomBytes` from the '@noble/hashes'\n * package. It's designed to be cryptographically strong, suitable for\n * generating initialization vectors, nonces, and other random values.\n *\n * @see {@link https://www.npmjs.com/package/@noble/hashes | @noble/hashes on NPM} for more\n * information about the underlying implementation.\n *\n * @example\n * ```ts\n * const bytes = randomBytes(32); // Generates 32 random bytes\n * ```\n *\n * @param bytesLength - The number of bytes to generate.\n * @returns A Uint8Array containing the generated random bytes.\n */\n static randomBytes(bytesLength: number): Uint8Array {\n return nobleRandomBytes(bytesLength);\n }\n\n /**\n * Generates a UUID (Universally Unique Identifier) using a\n * cryptographically strong random number generator following\n * the version 4 format, as specified in RFC 4122.\n *\n * A version 4 UUID is a randomly generated UUID. The 13th character\n * is set to '4' to denote version 4, and the 17th character is one\n * of '8', '9', 'A', or 'B' to comply with the variant 1 format of\n * UUIDs (the high bits are set to '10').\n *\n * The UUID is a 36 character string, including hyphens, and looks like this:\n * xxxxxxxx-xxxx-4xxx-axxx-xxxxxxxxxxxx\n *\n * Note that while UUIDs are not guaranteed to be unique, they are\n * practically unique\" given the large number of possible UUIDs and\n * the randomness of generation.\n * @memberof CryptoUtils\n * @example\n * ```ts\n * const uuid = randomUuid();\n * console.log(uuid); // Outputs a version 4 UUID, e.g., '123e4567-e89b-12d3-a456-426655440000'\n * ```\n *\n * @returns A string containing a randomly generated, 36 character long v4 UUID.\n */\n static randomUuid(): string {\n const uuid = crypto.randomUUID();\n\n return uuid;\n }\n\n\n /**\n * Generates a secure random PIN (Personal Identification Number) of a\n * specified length.\n *\n * This function ensures that the generated PIN is cryptographically secure and\n * uniformly distributed by using rejection sampling. It repeatedly generates\n * random numbers until it gets one in the desired range [0, max]. This avoids\n * bias introduced by simply taking the modulus or truncating the number.\n *\n * Note: The function can generate PINs of 3 to 10 digits in length.\n * Any request for a PIN outside this range will result in an error.\n *\n * Example usage:\n *\n * ```ts\n * const pin = randomPin({ length: 4 });\n * console.log(pin); // Outputs a 4-digit PIN, e.g., \"0231\"\n * ```\n * @memberof CryptoUtils\n * @param options - The options object containing the desired length of the generated PIN.\n * @param options.length - The desired length of the generated PIN. The value should be\n * an integer between 3 and 8 inclusive.\n *\n * @returns A string representing the generated PIN. The PIN will be zero-padded\n * to match the specified length, if necessary.\n *\n * @throws Will throw an error if the requested PIN length is less than 3 or greater than 8.\n */\n static randomPin({ length }: { length: number }): string {\n if (3 > length || length > 10) {\n throw new Error('randomPin() can securely generate a PIN between 3 to 10 digits.');\n }\n\n const max = Math.pow(10, length) - 1;\n\n let pin;\n\n if (length <= 6) {\n const rejectionRange = Math.pow(10, length);\n do {\n // Adjust the byte generation based on length.\n const randomBuffer = CryptoUtils.randomBytes(Math.ceil(length / 2) ); // 2 digits per byte.\n const view = new DataView(randomBuffer.buffer);\n // Convert the buffer to integer and take modulus based on length.\n pin = view.getUint16(0, false) % rejectionRange;\n } while (pin > max);\n } else {\n const rejectionRange = Math.pow(10, 10); // For max 10 digit number.\n do {\n // Generates 4 random bytes.\n const randomBuffer = CryptoUtils.randomBytes(4);\n // Create a DataView to read from the randomBuffer.\n const view = new DataView(randomBuffer.buffer);\n // Transform bytes to number (big endian).\n pin = view.getUint32(0, false) % rejectionRange;\n } while (pin > max); // Reject if the number is outside the desired range.\n }\n\n // Pad the PIN with leading zeros to the desired length.\n return pin.toString().padStart(length, '0');\n }\n}\n", "export {};\n//# sourceMappingURL=jwe.js.map", "export {};\n//# sourceMappingURL=jws.js.map", "export {};\n//# sourceMappingURL=jwt.js.map", "import { Convert } from '@enbox/common';\nimport { x25519 } from '@noble/curves/ed25519';\n\nimport type { Jwk } from '../jose/jwk.js';\nimport type { ComputePublicKeyParams, GetPublicKeyParams } from '../types/params-direct.js';\n\nimport { computeJwkThumbprint, isOkpPrivateJwk, isOkpPublicJwk } from '../jose/jwk.js';\n\n/**\n * The `X25519` class provides a comprehensive suite of utilities for working with the X25519\n * elliptic curve, widely used for key agreement protocols and cryptographic applications. It\n * provides methods for key generation, conversion, and Elliptic Curve Diffie-Hellman (ECDH)\n * key agreement, all aligned with standard cryptographic practices.\n *\n * The class supports conversions between raw byte formats and JSON Web Key (JWK) formats,\n * making it versatile for various cryptographic tasks. It adheres to RFC6090 for ECDH, ensuring\n * secure and effective handling of keys and cryptographic operations.\n *\n * Key Features:\n * - Key Generation: Generate X25519 private keys in JWK format.\n * - Key Conversion: Transform keys between raw byte arrays and JWK formats.\n * - Public Key Derivation: Derive public keys from private keys.\n * - ECDH Shared Secret Computation: Securely derive shared secrets using private and public keys.\n *\n * The methods in this class are asynchronous, returning Promises to accommodate various\n * JavaScript environments.\n *\n * @example\n * ```ts\n * // Key Generation\n * const privateKey = await X25519.generateKey();\n *\n * // Public Key Derivation\n * const publicKey = await X25519.computePublicKey({ key: privateKey });\n * console.log(publicKey === await X25519.getPublicKey({ key: privateKey })); // Output: true\n *\n * // ECDH Shared Secret Computation\n * const sharedSecret = await X25519.sharedSecret({\n * privateKeyA: privateKey,\n * publicKeyB: anotherPublicKey\n * });\n *\n * // Key Conversion\n * const publicKeyBytes = await X25519.publicKeyToBytes({ publicKey });\n * const privateKeyBytes = await X25519.privateKeyToBytes({ privateKey });\n * ```\n */\nexport class X25519 {\n /**\n * Converts a raw private key in bytes to its corresponding JSON Web Key (JWK) format.\n *\n * @remarks\n * This method accepts a private key as a byte array (Uint8Array) for the X25519 elliptic curve\n * and transforms it into a JWK object. The process involves first deriving the public key from\n * the private key, then encoding both the private and public keys into base64url format.\n *\n * The resulting JWK object includes the following properties:\n * - `kty`: Key Type, set to 'OKP' for Octet Key Pair.\n * - `crv`: Curve Name, set to 'X25519'.\n * - `d`: The private key component, base64url-encoded.\n * - `x`: The derived public key, base64url-encoded.\n *\n * This method is useful for converting raw public keys into a standardized\n * JSON format, facilitating their use in cryptographic operations and making\n * them easy to share and store.\n *\n * @example\n * ```ts\n * const privateKeyBytes = new Uint8Array([...]); // Replace with actual private key bytes\n * const privateKey = await X25519.bytesToPrivateKey({ privateKeyBytes });\n * ```\n *\n * @param params - The parameters for the private key conversion.\n * @param params.privateKeyBytes - The raw private key as a Uint8Array.\n *\n * @returns A Promise that resolves to the private key in JWK format.\n */\n public static async bytesToPrivateKey({ privateKeyBytes }: {\n privateKeyBytes: Uint8Array;\n }): Promise<Jwk> {\n // Derive the public key from the private key.\n const publicKeyBytes = x25519.getPublicKey(privateKeyBytes);\n\n // Construct the private key in JWK format.\n const privateKey: Jwk = {\n kty : 'OKP',\n crv : 'X25519',\n d : Convert.uint8Array(privateKeyBytes).toBase64Url(),\n x : Convert.uint8Array(publicKeyBytes).toBase64Url(),\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Converts a raw public key in bytes to its corresponding JSON Web Key (JWK) format.\n *\n * @remarks\n * This method accepts a public key as a byte array (Uint8Array) for the X25519 elliptic curve\n * and transforms it into a JWK object. The conversion process involves encoding the public\n * key bytes into base64url format.\n *\n * The resulting JWK object includes the following properties:\n * - `kty`: Key Type, set to 'OKP' for Octet Key Pair.\n * - `crv`: Curve Name, set to 'X25519'.\n * - `x`: The public key, base64url-encoded.\n *\n * This method is useful for converting raw public keys into a standardized\n * JSON format, facilitating their use in cryptographic operations and making\n * them easy to share and store.\n *\n * @example\n * ```ts\n * const publicKeyBytes = new Uint8Array([...]); // Replace with actual public key bytes\n * const publicKey = await X25519.bytesToPublicKey({ publicKeyBytes });\n * ```\n *\n * @param params - The parameters for the public key conversion.\n * @param params.publicKeyBytes - The raw public key as a Uint8Array.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public static async bytesToPublicKey({ publicKeyBytes }: {\n publicKeyBytes: Uint8Array;\n }): Promise<Jwk> {\n // Construct the public key in JWK format.\n const publicKey: Jwk = {\n kty : 'OKP',\n crv : 'X25519',\n x : Convert.uint8Array(publicKeyBytes).toBase64Url(),\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Derives the public key in JWK format from a given X25519 private key.\n *\n * @remarks\n * This method takes a private key in JWK format and derives its corresponding public key,\n * also in JWK format. The derivation process involves converting the private key to a\n * raw byte array and then computing the corresponding public key on the Curve25519 curve.\n * The public key is then encoded into base64url format to construct a JWK representation.\n *\n * The process ensures that the derived public key correctly corresponds to the given private key,\n * adhering to the Curve25519 elliptic curve in Twisted Edwards form standards. This method is\n * useful in cryptographic operations where a public key is needed for operations like signature\n * verification, but only the private key is available.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // A Jwk object representing an X25519 private key\n * const publicKey = await X25519.computePublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for the public key derivation.\n * @param params.key - The private key in JWK format from which to derive the public key.\n *\n * @returns A Promise that resolves to the derived public key in JWK format.\n */\n public static async computePublicKey({ key }:\n ComputePublicKeyParams\n ): Promise<Jwk> {\n // Convert the provided private key to a byte array.\n const privateKeyBytes = await X25519.privateKeyToBytes({ privateKey: key });\n\n // Derive the public key from the private key.\n const publicKeyBytes = x25519.getPublicKey(privateKeyBytes);\n\n // Construct the public key in JWK format.\n const publicKey: Jwk = {\n kty : 'OKP',\n crv : 'X25519',\n x : Convert.uint8Array(publicKeyBytes).toBase64Url()\n };\n\n // Compute the JWK thumbprint and set as the key ID.\n publicKey.kid = await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Generates an X25519 private key in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method creates a new private key suitable for use with the X25519 elliptic curve.\n * The key generation process involves using cryptographically secure random number generation\n * to ensure the uniqueness and security of the key. The resulting private key adheres to the\n * JWK format making it compatible with common cryptographic standards and easy to use in various\n * cryptographic processes.\n *\n * The generated private key in JWK format includes the following components:\n * - `kty`: Key Type, set to 'OKP' for Octet Key Pair.\n * - `crv`: Curve Name, set to 'X25519'.\n * - `d`: The private key component, base64url-encoded.\n * - `x`: The derived public key, base64url-encoded.\n *\n * The key is returned in a format suitable for direct use in key agreement operations.\n *\n * @example\n * ```ts\n * const privateKey = await X25519.generateKey();\n * ```\n *\n * @returns A Promise that resolves to the generated private key in JWK format.\n */\n public static async generateKey(): Promise<Jwk> {\n // Generate a random private key.\n const privateKeyBytes = x25519.utils.randomPrivateKey();\n\n // Convert private key from bytes to JWK format.\n const privateKey = await X25519.bytesToPrivateKey({ privateKeyBytes });\n\n // Compute the JWK thumbprint and set as the key ID.\n privateKey.kid = await computeJwkThumbprint({ jwk: privateKey });\n\n return privateKey;\n }\n\n /**\n * Retrieves the public key properties from a given private key in JWK format.\n *\n * @remarks\n * This method extracts the public key portion from an X25519 private key in JWK format. It does\n * so by removing the private key property 'd' and making a shallow copy, effectively yielding the\n * public key. The method sets the 'kid' (key ID) property using the JWK thumbprint if it is not\n * already defined. This approach is used under the assumption that a private key in JWK format\n * always contains the corresponding public key properties.\n *\n * Note: This method offers a significant performance advantage, being about 500 times faster\n * than `computePublicKey()`. However, it does not mathematically validate the private key, nor\n * does it derive the public key from the private key. It simply extracts existing public key\n * properties from the private key object. This makes it suitable for scenarios where speed is\n * critical and the private key's integrity is already assured.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // A Jwk object representing an X25519 private key\n * const publicKey = await X25519.getPublicKey({ key: privateKey });\n * ```\n *\n * @param params - The parameters for retrieving the public key properties.\n * @param params.key - The private key in JWK format.\n *\n * @returns A Promise that resolves to the public key in JWK format.\n */\n public static async getPublicKey({ key }:\n GetPublicKeyParams\n ): Promise<Jwk> {\n // Verify the provided JWK represents an octet key pair (OKP) X25519 private key.\n if (!(isOkpPrivateJwk(key) && key.crv === 'X25519')) {\n throw new Error(`X25519: The provided key is not an X25519 private JWK.`);\n }\n\n // Remove the private key property ('d') and make a shallow copy of the provided key.\n const { d, ...publicKey } = key;\n\n // If the key ID is undefined, set it to the JWK thumbprint.\n publicKey.kid ??= await computeJwkThumbprint({ jwk: publicKey });\n\n return publicKey;\n }\n\n /**\n * Converts a private key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n *\n * @remarks\n * This method accepts a private key in JWK format and extracts its raw byte representation.\n *\n * This method accepts a public key in JWK format and converts it into its raw binary\n * form. The conversion process involves decoding the 'd' parameter of the JWK\n * from base64url format into a byte array.\n *\n * This conversion is essential for operations that require the private key in its raw\n * binary form, such as certain low-level cryptographic operations or when interfacing\n * with systems and libraries that expect keys in a byte array format.\n *\n * @example\n * ```ts\n * const privateKey = { ... }; // An X25519 private key in JWK format\n * const privateKeyBytes = await X25519.privateKeyToBytes({ privateKey });\n * ```\n *\n * @param params - The parameters for the private key conversion.\n * @param params.privateKey - The private key in JWK format.\n *\n * @returns A Promise that resolves to the private key as a Uint8Array.\n */\n public static async privateKeyToBytes({ privateKey }: {\n privateKey: Jwk;\n }): Promise<Uint8Array> {\n // Verify the provided JWK represents a valid OKP private key.\n if (!isOkpPrivateJwk(privateKey)) {\n throw new Error(`X25519: The provided key is not a valid OKP private key.`);\n }\n\n // Decode the provided private key to bytes.\n const privateKeyBytes = Convert.base64Url(privateKey.d).toUint8Array();\n\n return privateKeyBytes;\n }\n\n /**\n * Converts a public key from JSON Web Key (JWK) format to a raw byte array (Uint8Array).\n *\n * @remarks\n * This method accepts a public key in JWK format and converts it into its raw binary form.\n * The conversion process involves decoding the 'x' parameter of the JWK (which represent the\n * x coordinate of the elliptic curve point) from base64url format into a byte array.\n *\n * This conversion is essential for operations that require the public key in its raw\n * binary form, such as certain low-level cryptographic operations or when interfacing\n * with systems and libraries that expect keys in a byte array format.\n *\n * @example\n * ```ts\n * const publicKey = { ... }; // An X25519 public key in JWK format\n * const publicKeyBytes = await X25519.publicKeyToBytes({ publicKey });\n * ```\n *\n * @param params - The parameters for the public key conversion.\n * @param params.publicKey - The public key in JWK format.\n *\n * @returns A Promise that resolves to the public key as a Uint8Array.\n */\n public static async publicKeyToBytes({ publicKey }: {\n publicKey: Jwk;\n }): Promise<Uint8Array> {\n // Verify the provided JWK represents a valid OKP public key.\n if (!isOkpPublicJwk(publicKey)) {\n throw new Error(`X25519: The provided key is not a valid OKP public key.`);\n }\n\n // Decode the provided public key to bytes.\n const publicKeyBytes = Convert.base64Url(publicKey.x).toUint8Array();\n\n return publicKeyBytes;\n }\n\n /**\n * Computes an RFC6090-compliant Elliptic Curve Diffie-Hellman (ECDH) shared secret\n * using secp256k1 private and public keys in JSON Web Key (JWK) format.\n *\n * @remarks\n * This method facilitates the ECDH key agreement protocol, which is a method of securely\n * deriving a shared secret between two parties based on their private and public keys.\n * It takes the private key of one party (privateKeyA) and the public key of another\n * party (publicKeyB) to compute a shared secret. The shared secret is derived from the\n * x-coordinate of the elliptic curve point resulting from the multiplication of the\n * public key with the private key.\n *\n * Note: When performing Elliptic Curve Diffie-Hellman (ECDH) key agreement,\n * the resulting shared secret is a point on the elliptic curve, which\n * consists of an x-coordinate and a y-coordinate. With a 256-bit curve like\n * secp256k1, each of these coordinates is 32 bytes (256 bits) long. However,\n * in the ECDH process, it's standard practice to use only the x-coordinate\n * of the shared secret point as the resulting shared key. This is because\n * the y-coordinate does not add to the entropy of the key, and both parties\n * can independently compute the x-coordinate. Consquently, this implementation\n * omits the y-coordinate for simplicity and standard compliance.\n *\n * @example\n * ```ts\n * const privateKeyA = { ... }; // A Jwk object for party A\n * const publicKeyB = { ... }; // A PublicKeyJwk object for party B\n * const sharedSecret = await Secp256k1.sharedSecret({\n * privateKeyA,\n * publicKeyB\n * });\n * ```\n *\n * @param params - The parameters for the shared secret computation.\n * @param params.privateKeyA - The private key in JWK format of one party.\n * @param params.publicKeyB - The public key in JWK format of the other party.\n *\n * @returns A Promise that resolves to the computed shared secret as a Uint8Array.\n */\n public static async sharedSecret({ privateKeyA, publicKeyB }: {\n privateKeyA: Jwk;\n publicKeyB: Jwk;\n }): Promise<Uint8Array> {\n // Ensure that keys from the same key pair are not specified.\n if ('x' in privateKeyA && 'x' in publicKeyB && privateKeyA.x === publicKeyB.x) {\n throw new Error(`X25519: ECDH shared secret cannot be computed from a single key pair's public and private keys.`);\n }\n\n // Convert the provided private and public keys to bytes.\n const privateKeyABytes = await X25519.privateKeyToBytes({ privateKey: privateKeyA });\n const publicKeyBBytes = await X25519.publicKeyToBytes({ publicKey: publicKeyB });\n\n // Compute the shared secret between the public and private keys.\n const sharedSecret = x25519.getSharedSecret(privateKeyABytes, publicKeyBBytes);\n\n return sharedSecret;\n }\n}", "import type { Jwk } from '@enbox/crypto';\nimport type { RequireOnly } from '@enbox/common';\n\nimport { computeJwkThumbprint } from '@enbox/crypto';\nimport { Convert, Multicodec } from '@enbox/common';\n\nimport type { KeyWithMulticodec } from './types/multibase.js';\nimport type {\n DidDocument,\n DidService,\n DidVerificationMethod,\n} from './types/did-core.js';\n\nimport { DidVerificationRelationship } from './types/did-core.js';\nimport { DidError, DidErrorCode } from './did-error.js';\n\n/**\n * Represents a Decentralized Web Node (DWN) service in a DID Document.\n *\n * A DWN DID service is a specialized type of DID service with the `type` set to\n * `DecentralizedWebNode`. It includes specific properties `enc` and `sig` that are used to identify\n * the public keys that can be used to interact with the DID Subject. The values of these properties\n * are strings or arrays of strings containing one or more verification method `id` values present in\n * the same DID document. If the `enc` and/or `sig` properties are an array of strings, an entity\n * interacting with the DID subject is expected to use the verification methods in the order they\n * are listed.\n *\n * @example\n * ```ts\n * const service: DwnDidService = {\n * id: 'did:example:123#dwn',\n * type: 'DecentralizedWebNode',\n * serviceEndpoint: 'https://enbox-dwn.fly.dev',\n * enc: 'did:example:123#key-1',\n * sig: 'did:example:123#key-2'\n * }\n * ```\n *\n * @see {@link https://identity.foundation/decentralized-web-node/spec/ | DIF Decentralized Web Node (DWN) Specification}\n */\nexport interface DwnDidService extends DidService {\n /**\n * One or more verification method `id` values that can be used to encrypt information\n * intended for the DID subject.\n */\n enc?: string | string[];\n\n /**\n * One or more verification method `id` values that will be used by the DID subject to sign data\n * or by another entity to verify signatures created by the DID subject.\n */\n sig: string | string[];\n}\n\n/**\n * Extracts the fragment part of a Decentralized Identifier (DID) verification method identifier.\n *\n * This function takes any input and aims to return only the fragment of a DID identifier,\n * which comes after the '#' symbol in a DID string. It's designed specifically for handling\n * DID verification method identifiers. The function returns undefined for non-string inputs, inputs\n * that do not contain a '#', or complex data structures like objects or arrays, ensuring that only\n * the fragment part of a DID string is extracted when present.\n *\n * @example\n * ```ts\n * console.log(extractDidFragment(\"did:example:123#key-1\")); // Output: \"key-1\"\n * console.log(extractDidFragment(\"did:example:123\")); // Output: undefined\n * console.log(extractDidFragment({ id: \"did:example:123#0\", type: \"JsonWebKey\" })); // Output: undefined\n * console.log(extractDidFragment(undefined)); // Output: undefined\n * ```\n *\n * @param input - The input to be processed. Can be of any type, but the function is designed\n * to work with strings that represent DID verification method identifiers.\n * @returns The fragment part of the DID identifier if the input is a string containing a '#'.\n * Returns an empty string for all other inputs, including non-string types, strings\n * without a '#', and complex data structures.\n */\nexport function extractDidFragment(input: unknown): string | undefined {\n if (typeof input !== 'string') {return undefined;}\n if (input.length === 0) {return undefined;}\n return input.split('#').pop();\n}\n\n/**\n * Retrieves services from a given DID document, optionally filtered by `id` or `type`.\n *\n * If no `id` or `type` filters are provided, all defined services are returned.\n *\n * The given DID Document must adhere to the\n * {@link https://www.w3.org/TR/did-core/ | W3C DID Core Specification}.\n *\n * @example\n * ```ts\n * const didDocument = { ... }; // W3C DID document\n * const services = getServices({ didDocument, type: 'DecentralizedWebNode' });\n * ```\n *\n * @param params - An object containing input parameters for retrieving services.\n * @param params.didDocument - The DID document from which services are retrieved.\n * @param params.id - Optional. A string representing the specific service ID to match. If provided,\n * only the service with this ID will be returned.\n * @param params.type - Optional. A string representing the specific service type to match.\n * If provided, only the service(s) of this type will be returned.\n * @returns An array of services. If no matching service is found, an empty array is returned.\n */\nexport function getServices({ didDocument, id, type }: {\n didDocument: DidDocument;\n id?: string;\n type?: string;\n}): DidService[] {\n return didDocument?.service?.filter(service => {\n if (id && service.id !== id) {return false;}\n if (type && service.type !== type) {return false;}\n return true;\n }) ?? [];\n}\n\n/**\n * Retrieves a verification method object from a DID document if there is a match for the given\n * public key.\n *\n * This function searches the verification methods in a given DID document for a match with the\n * provided public key (either in JWK or multibase format). If a matching verification method is\n * found it is returned. If no match is found `null` is returned.\n *\n *\n * @example\n * ```ts\n * const didDocument = {\n * // ... contents of a DID document ...\n * };\n * const publicKeyJwk = { kty: 'OKP', crv: 'Ed25519', x: '...' };\n *\n * const verificationMethod = await getVerificationMethodByKey({\n * didDocument,\n * publicKeyJwk\n * });\n * ```\n *\n * @param params - An object containing input parameters for retrieving the verification method ID.\n * @param params.didDocument - The DID document to search for the verification method.\n * @param params.publicKeyJwk - The public key in JSON Web Key (JWK) format to match against the verification methods in the DID document.\n * @param params.publicKeyMultibase - The public key as a multibase encoded string to match against the verification methods in the DID document.\n * @returns A promise that resolves with the matching verification method, or `null` if no match is found.\n * @throws Throws an `Error` if the `didDocument` parameter is missing or if the `didDocument` does not contain any verification methods.\n */\nexport async function getVerificationMethodByKey({ didDocument, publicKeyJwk, publicKeyMultibase }: {\n didDocument: DidDocument;\n publicKeyJwk?: Jwk;\n publicKeyMultibase?: string;\n}): Promise<DidVerificationMethod | null> {\n // Collect all verification methods from the DID document.\n const verificationMethods = getVerificationMethods({ didDocument });\n\n for (const method of verificationMethods) {\n if (publicKeyJwk && method.publicKeyJwk) {\n const publicKeyThumbprint = await computeJwkThumbprint({ jwk: publicKeyJwk });\n if (publicKeyThumbprint === await computeJwkThumbprint({ jwk: method.publicKeyJwk })) {\n return method;\n }\n } else if (publicKeyMultibase && method.publicKeyMultibase) {\n if (publicKeyMultibase === method.publicKeyMultibase) {\n return method;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Retrieves all verification methods from a given DID document, including embedded methods.\n *\n * This function consolidates all verification methods into a single array for easy access and\n * processing. It checks both the primary `verificationMethod` array and the individual verification\n * relationship properties `authentication`, `assertionMethod`, `keyAgreement`,\n * `capabilityInvocation`, and `capabilityDelegation` for embedded methods.\n *\n * The given DID Document must adhere to the\n * {@link https://www.w3.org/TR/did-core/ | W3C DID Core Specification}.\n *\n * @example\n * ```ts\n * const didDocument = { ... }; // W3C DID document\n * const verificationMethods = getVerificationMethods({ didDocument });\n * ```\n *\n * @param params - An object containing input parameters for retrieving verification methods.\n * @param params.didDocument - The DID document from which verification methods are retrieved.\n * @returns An array of `DidVerificationMethod`. If no verification methods are found, an empty array is returned.\n * @throws Throws an `TypeError` if the `didDocument` parameter is missing.\n */\nexport function getVerificationMethods({ didDocument }: {\n didDocument: DidDocument;\n}): DidVerificationMethod[] {\n if (!didDocument) {throw new TypeError(`Required parameter missing: 'didDocument'`);}\n\n const verificationMethods: DidVerificationMethod[] = [];\n\n // Check the 'verificationMethod' array.\n verificationMethods.push(...didDocument.verificationMethod?.filter(isDidVerificationMethod) ?? []);\n\n // Check verification relationship properties for embedded verification methods.\n Object.keys(DidVerificationRelationship).forEach((relationship) => {\n verificationMethods.push(\n ...(didDocument[relationship as keyof DidDocument] as (string | DidVerificationMethod)[])\n ?.filter(isDidVerificationMethod) ?? []\n );\n });\n\n return verificationMethods;\n}\n\n/**\n * Retrieves all DID verification method types from a given DID document.\n *\n * The given DID Document must adhere to the\n * {@link https://www.w3.org/TR/did-core/ | W3C DID Core Specification}.\n *\n * @example\n * ```ts\n * const didDocument = {\n * verificationMethod: [\n * {\n * 'id' : 'did:example:123#key-0',\n * 'type' : 'Ed25519VerificationKey2018',\n * 'controller' : 'did:example:123',\n * 'publicKeyBase58' : '3M5RCDjPTWPkKSN3sxUmmMqHbmRPegYP1tjcKyrDbt9J'\n * },\n * {\n * 'id' : 'did:example:123#key-1',\n * 'type' : 'X25519KeyAgreementKey2019',\n * 'controller' : 'did:example:123',\n * 'publicKeyBase58' : 'FbQWLPRhTH95MCkQUeFYdiSoQt8zMwetqfWoxqPgaq7x'\n * },\n * {\n * 'id' : 'did:example:123#key-3',\n * 'type' : 'JsonWebKey2020',\n * 'controller' : 'did:example:123',\n * 'publicKeyJwk' : {\n * 'kty' : 'EC',\n * 'crv' : 'P-256',\n * 'x' : 'Er6KSSnAjI70ObRWhlaMgqyIOQYrDJTE94ej5hybQ2M',\n * 'y' : 'pPVzCOTJwgikPjuUE6UebfZySqEJ0ZtsWFpj7YSPGEk'\n * }\n * }\n * ]\n * },\n * const vmTypes = getVerificationMethodTypes({ didDocument });\n * console.log(vmTypes);\n * // Output: ['Ed25519VerificationKey2018', 'X25519KeyAgreementKey2019', 'JsonWebKey2020']\n * ```\n *\n * @param params - An object containing input parameters for retrieving types.\n * @param params.didDocument - The DID document from which types are retrieved.\n * @returns An array of types. If no types were found, an empty array is returned.\n */\nexport function getVerificationMethodTypes({ didDocument }: {\n didDocument: DidDocument;\n}): string[] {\n // Collect all verification methods from the DID document.\n const verificationMethods = getVerificationMethods({ didDocument });\n\n // Map to extract 'type' from each verification method.\n const types = verificationMethods.map(method => method.type);\n\n return [...new Set(types)]; // Return only unique types.\n}\n\n/**\n * Retrieves a list of DID verification relationships by a specific method ID from a DID document.\n *\n * This function examines the specified DID document to identify any verification relationships\n * (e.g., `authentication`, `assertionMethod`) that reference a verification method by its method ID\n * or contain an embedded verification method matching the method ID. The method ID is typically a\n * fragment of a DID (e.g., `did:example:123#key-1`) that uniquely identifies a verification method\n * within the DID document.\n *\n * The search considers both direct references to verification methods by their IDs and verification\n * methods embedded within the verification relationship arrays. It returns an array of\n * `DidVerificationRelationship` enums corresponding to the verification relationships that contain\n * the specified method ID.\n *\n * @param params - An object containing input parameters for retrieving verification relationships.\n * @param params.didDocument - The DID document to search for verification relationships.\n * @param params.methodId - The method ID to search for within the verification relationships.\n * @returns An array of `DidVerificationRelationship` enums representing the types of verification\n * relationships that reference the specified method ID.\n *\n * @example\n * ```ts\n * const didDocument: DidDocument = {\n * // ...contents of a DID document...\n * };\n *\n * const relationships = getVerificationRelationshipsById({\n * didDocument,\n * methodId: 'key-1'\n * });\n * console.log(relationships);\n * // Output might include ['authentication', 'assertionMethod'] if those relationships\n * // reference or contain the specified method ID.\n * ```\n */\nexport function getVerificationRelationshipsById({ didDocument, methodId }: {\n didDocument: DidDocument;\n methodId: string;\n}): DidVerificationRelationship[] {\n const relationships: DidVerificationRelationship[] = [];\n\n Object.keys(DidVerificationRelationship).forEach((relationship) => {\n if (Array.isArray(didDocument[relationship as keyof DidDocument])) {\n const relationshipMethods = didDocument[relationship as keyof DidDocument] as (string | DidVerificationMethod)[];\n\n const methodIdFragment = extractDidFragment(methodId);\n\n // Check if the verification relationship property contains a matching method ID either\n // directly referenced or as an embedded verification method.\n const containsMethodId = relationshipMethods.some(method => {\n const isByReferenceMatch = extractDidFragment(method) === methodIdFragment;\n const isEmbeddedMethodMatch = isDidVerificationMethod(method) && extractDidFragment(method.id) === methodIdFragment;\n return isByReferenceMatch || isEmbeddedMethodMatch;\n });\n\n if (containsMethodId) {\n relationships.push(relationship as DidVerificationRelationship);\n }\n }\n });\n\n return relationships;\n}\n\n/**\n * Checks if a given object is a {@link DidService}.\n *\n * A {@link DidService} in the context of DID resources must include the properties `id`, `type`,\n * and `serviceEndpoint`. The `serviceEndpoint` can be a `DidServiceEndpoint` or an array of\n * `DidServiceEndpoint` objects.\n *\n * @example\n * ```ts\n * const service = {\n * id: \"did:example:123#service-1\",\n * type: \"OidcService\",\n * serviceEndpoint: \"https://example.com/oidc\"\n * };\n *\n * if (isDidService(service)) {\n * console.log('The object is a DidService');\n * } else {\n * console.log('The object is not a DidService');\n * }\n * ```\n *\n * @param obj - The object to be checked.\n * @returns `true` if `obj` is a `DidService`; otherwise, `false`.\n */\nexport function isDidService(obj: unknown): obj is DidService {\n // Validate that the given value is an object.\n if (!obj || typeof obj !== 'object' || obj === null) {return false;}\n\n // Validate that the object has the necessary properties of DidService.\n return 'id' in obj && 'type' in obj && 'serviceEndpoint' in obj;\n}\n\n/**\n * Checks if a given object is a {@link DwnDidService}.\n *\n * A {@link DwnDidService} is defined as {@link DidService} object with a `type` of\n * \"DecentralizedWebNode\" and `enc` and `sig` properties, where both properties are either strings\n * or arrays of strings.\n *\n * @example\n * ```ts\n * const didDocument: DidDocument = {\n * id: 'did:example:123',\n * verificationMethod: [\n * {\n * id: 'did:example:123#key-1',\n * type: 'JsonWebKey2020',\n * controller: 'did:example:123',\n * publicKeyJwk: { ... }\n * },\n * {\n * id: 'did:example:123#key-2',\n * type: 'JsonWebKey2020',\n * controller: 'did:example:123',\n * publicKeyJwk: { ... }\n * }\n * ],\n * service: [\n * {\n * id: 'did:example:123#dwn',\n * type: 'DecentralizedWebNode',\n * serviceEndpoint: 'https://enbox-dwn.fly.dev',\n * enc: 'did:example:123#key-1',\n * sig: 'did:example:123#key-2'\n * }\n * ]\n * };\n *\n * if (isDwnService(didDocument.service[0])) {\n * console.log('The object is a DwnDidService');\n * } else {\n * console.log('The object is not a DwnDidService');\n * }\n * ```\n *\n * @see {@link https://identity.foundation/decentralized-web-node/spec/ | Decentralized Web Node (DWN) Specification}\n *\n * @param obj - The object to be checked.\n * @returns `true` if `obj` is a DwnDidService; otherwise, `false`.\n */\nexport function isDwnDidService(obj: unknown): obj is DwnDidService {\n // Validate that the given value is a {@link DidService}.\n if (!isDidService(obj)) {return false;}\n\n // Validate that the `type` property is `DecentralizedWebNode`.\n if (obj.type !== 'DecentralizedWebNode') {return false;}\n\n // Validate that the given object has the `enc` and `sig` properties.\n if (!('enc' in obj && 'sig' in obj)) {return false;}\n\n // Validate that the `enc` and `sig` properties are either strings or arrays of strings.\n const isStringOrStringArray = (prop: any): boolean =>\n typeof prop === 'string' || Array.isArray(prop) && prop.every(item => typeof item === 'string');\n return (isStringOrStringArray(obj.enc)) && (isStringOrStringArray(obj.sig));\n}\n\n/**\n * Checks if a given object is a DID Verification Method.\n *\n * A {@link DidVerificationMethod} in the context of DID resources must include the properties `id`,\n * `type`, and `controller`.\n *\n * @example\n * ```ts\n * const resource = {\n * id : \"did:example:123#0\",\n * type : \"JsonWebKey2020\",\n * controller : \"did:example:123\",\n * publicKeyJwk : { ... }\n * };\n *\n * if (isDidVerificationMethod(resource)) {\n * console.log('The resource is a DidVerificationMethod');\n * } else {\n * console.log('The resource is not a DidVerificationMethod');\n * }\n * ```\n *\n * @param obj - The object to be checked.\n * @returns `true` if `obj` is a `DidVerificationMethod`; otherwise, `false`.\n */\nexport function isDidVerificationMethod(obj: unknown): obj is DidVerificationMethod {\n // Validate that the given value is an object.\n if (!obj || typeof obj !== 'object' || obj === null) {return false;}\n\n // Validate that the object has the necessary properties of a DidVerificationMethod.\n if (!('id' in obj && 'type' in obj && 'controller' in obj)) {return false;}\n\n if (typeof obj.id !== 'string') {return false;}\n if (typeof obj.type !== 'string') {return false;}\n if (typeof obj.controller !== 'string') {return false;}\n\n return true;\n}\n\n/**\n * Converts a cryptographic key to a multibase identifier.\n *\n * @remarks\n * This method provides a way to represent a cryptographic key as a multibase identifier.\n * It takes a `Uint8Array` representing the key, and either the multicodec code or multicodec name\n * as input. The method first adds the multicodec prefix to the key, then encodes it into Base58\n * format. Finally, it converts the Base58 encoded key into a multibase identifier.\n *\n * @example\n * ```ts\n * const key = new Uint8Array([...]); // Cryptographic key as Uint8Array\n * const multibaseId = keyBytesToMultibaseId({ key, multicodecName: 'ed25519-pub' });\n * ```\n *\n * @param params - The parameters for the conversion.\n * @returns The multibase identifier as a string.\n */\nexport function keyBytesToMultibaseId({ keyBytes, multicodecCode, multicodecName }:\n RequireOnly<KeyWithMulticodec, 'keyBytes'>\n): string {\n const prefixedKey = Multicodec.addPrefix({\n code : multicodecCode,\n data : keyBytes,\n name : multicodecName\n });\n const prefixedKeyB58 = Convert.uint8Array(prefixedKey).toBase58Btc();\n const multibaseKeyId = Convert.base58Btc(prefixedKeyB58).toMultibase();\n\n return multibaseKeyId;\n}\n\n/**\n * Converts a multibase identifier to a cryptographic key.\n *\n * @remarks\n * This function decodes a multibase identifier back into a cryptographic key. It first decodes the\n * identifier from multibase format into Base58 format, and then converts it into a `Uint8Array`.\n * Afterward, it removes the multicodec prefix, extracting the raw key data along with the\n * multicodec code and name.\n *\n * @example\n * ```ts\n * const multibaseKeyId = '...'; // Multibase identifier of the key\n * const { key, multicodecCode, multicodecName } = multibaseIdToKey({ multibaseKeyId });\n * ```\n *\n * @param params - The parameters for the conversion.\n * @param params.multibaseKeyId - The multibase identifier string of the key.\n * @returns An object containing the key as a `Uint8Array` and its multicodec code and name.\n * @throws `DidError` if the multibase identifier is invalid.\n */\nexport function multibaseIdToKeyBytes({ multibaseKeyId }: {\n multibaseKeyId: string\n}): Required<KeyWithMulticodec> {\n try {\n const prefixedKeyB58 = Convert.multibase(multibaseKeyId).toBase58Btc();\n const prefixedKey = Convert.base58Btc(prefixedKeyB58).toUint8Array();\n const { code, data, name } = Multicodec.removePrefix({ prefixedData: prefixedKey });\n\n return { keyBytes: data, multicodecCode: code, multicodecName: name };\n } catch {\n throw new DidError(DidErrorCode.InvalidDid, `Invalid multibase identifier: ${multibaseKeyId}`);\n }\n}", "import type {\n AsymmetricKeyConverter,\n CryptoApi,\n Jwk,\n KeyIdentifier,\n KeyImporterExporter,\n KmsExportKeyParams,\n KmsImportKeyParams,\n Signer,\n} from '@enbox/crypto';\nimport type { Packet, StringAnswer, TxtAnswer, TxtData } from '@dnsquery/dns-packet';\n\nimport bencode from 'bencode';\nimport { Convert } from '@enbox/common';\nimport { AUTHORITATIVE_ANSWER, decode as dnsPacketDecode, encode as dnsPacketEncode } from '@dnsquery/dns-packet';\nimport { computeJwkThumbprint, Ed25519, LocalKeyManager, Secp256k1, Secp256r1, X25519 } from '@enbox/crypto';\n\nimport type { DidCreateOptions, DidCreateVerificationMethod, DidRegistrationResult } from './did-method.js';\nimport type {\n DidDocument,\n DidResolutionOptions,\n DidResolutionResult,\n DidService,\n DidVerificationMethod,\n} from '../types/did-core.js';\nimport type { DidMetadata, PortableDid } from '../types/portable-did.js';\n\nimport { BearerDid } from '../bearer-did.js';\nimport { Did } from '../did.js';\nimport { DidMethod } from './did-method.js';\nimport { DidVerificationRelationship } from '../types/did-core.js';\nimport { EMPTY_DID_RESOLUTION_RESULT } from '../types/did-resolution.js';\nimport { extractDidFragment } from '../utils.js';\nimport { DidError, DidErrorCode } from '../did-error.js';\n\n/**\n * Represents a BEP44 message, which is used for storing and retrieving data in the Mainline DHT\n * network.\n *\n * A BEP44 message is used primarily in the context of the DID DHT method for publishing and\n * resolving DID documents in the DHT network. This type encapsulates the data structure required\n * for such operations in accordance with BEP44.\n *\n * @see {@link https://www.bittorrent.org/beps/bep_0044.html | BEP44}\n */\nexport interface Bep44Message {\n /**\n * The public key bytes of the Identity Key, which serves as the identifier in the DHT network for\n * the corresponding BEP44 message.\n */\n k: Uint8Array;\n\n /**\n * The sequence number of the message, used to ensure the latest version of the data is retrieved\n * and updated. It's a monotonically increasing number.\n */\n seq: number;\n\n /**\n * The signature of the message, ensuring the authenticity and integrity of the data. It's\n * computed over the bencoded sequence number and value.\n */\n sig: Uint8Array;\n\n /**\n * The actual data being stored or retrieved from the DHT network, typically encoded in a format\n * suitable for DNS packet representation of a DID Document.\n */\n v: Uint8Array;\n}\n\n/**\n * Options for creating a Decentralized Identifier (DID) using the DID DHT method.\n */\nexport interface DidDhtCreateOptions<TKms> extends DidCreateOptions<TKms> {\n /**\n * Optionally specify that the DID Subject is also identified by one or more other DIDs or URIs.\n *\n * A DID subject can have multiple identifiers for different purposes, or at different times.\n * The assertion that two or more DIDs (or other types of URI) refer to the same DID subject can\n * be made using the `alsoKnownAs` property.\n *\n * @see {@link https://www.w3.org/TR/did-core/#also-known-as | DID Core Specification, \u00A7 Also Known As}\n *\n * @example\n * ```ts\n * const did = await DidDht.create({\n * options: {\n * alsoKnownAs: 'did:example:123'\n * };\n * ```\n */\n alsoKnownAs?: string[];\n\n /**\n * Optionally specify which DID (or DIDs) is authorized to make changes to the DID document.\n *\n * A DID controller is an entity that is authorized to make changes to a DID document. Typically,\n * only the DID Subject (i.e., the value of `id` property in the DID document) is authoritative.\n * However, another DID (or DIDs) can be specified as the DID controller, and when doing so, any\n * verification methods contained in the DID document for the other DID should be accepted as\n * authoritative. In other words, proofs created by the controller DID should be considered\n * equivalent to proofs created by the DID Subject.\n *\n * @see {@link https://www.w3.org/TR/did-core/#did-controller | DID Core Specification, \u00A7 DID Controller}\n *\n * @example\n * ```ts\n * const did = await DidDht.create({\n * options: {\n * controller: 'did:example:123'\n * };\n * ```\n */\n controllers?: string | string[];\n\n /**\n * Optional. The URI of a server involved in executing DID method operations. In the context of\n * DID creation, the endpoint is expected to be a DID DHT Gateway or Pkarr relay. If not\n * specified, a default gateway node is used.\n */\n gatewayUri?: string;\n\n /**\n * Optional. Determines whether the created DID should be published to the DHT network.\n *\n * If set to `true` or omitted, the DID is publicly discoverable. If `false`, the DID is not\n * published and cannot be resolved by others. By default, newly created DIDs are published.\n *\n * @see {@link https://did-dht.com | DID DHT Method Specification}\n *\n * @example\n * ```ts\n * const did = await DidDht.create({\n * options: {\n * publish: false\n * };\n * ```\n */\n publish?: boolean;\n\n /**\n * Optional. An array of service endpoints associated with the DID.\n *\n * Services are used in DID documents to express ways of communicating with the DID subject or\n * associated entities. A service can be any type of service the DID subject wants to advertise,\n * including decentralized identity management services for further discovery, authentication,\n * authorization, or interaction.\n *\n * @see {@link https://www.w3.org/TR/did-core/#services | DID Core Specification, \u00A7 Services}\n *\n * @example\n * ```ts\n * const did = await DidDht.create({\n * options: {\n * services: [\n * {\n * id: 'did:dht:i9xkp8ddcbcg8jwq54ox699wuzxyifsqx4jru45zodqu453ksz6y#dwn',\n * type: 'DecentralizedWebNode',\n * serviceEndpoint: ['https://example.com/dwn1', 'https://example/dwn2']\n * }\n * ]\n * };\n * ```\n */\n services?: DidService[];\n\n /**\n * Optionally specify one or more registered DID DHT types to make the DID discovereable.\n *\n * Type indexing is an OPTIONAL feature that enables DIDs to become discoverable. DIDs that wish\n * to be discoverable and resolveable by type can include one or more types when publishing their\n * DID document to a DID DHT Gateway.\n *\n * The registered DID types are published in the {@link https://did-dht.com/registry/index.html#indexed-types | DID DHT Registry}.\n */\n types?: (DidDhtRegisteredDidType | keyof typeof DidDhtRegisteredDidType)[];\n\n /**\n * Optional. An array of verification methods to be included in the DID document.\n *\n * By default, a newly created DID DHT document will contain a single Ed25519 verification method,\n * also known as the {@link https://did-dht.com/#term:identity-key | Identity Key}. Additional\n * verification methods can be added to the DID document using the `verificationMethods` property.\n *\n * @see {@link https://www.w3.org/TR/did-core/#verification-methods | DID Core Specification, \u00A7 Verification Methods}\n *\n * @example\n * ```ts\n * const did = await DidDht.create({\n * options: {\n * verificationMethods: [\n * {\n * algorithm: 'Ed25519',\n * purposes: ['authentication', 'assertionMethod']\n * },\n * {\n * algorithm: 'Ed25519',\n * id: 'dwn-sig',\n * purposes: ['authentication', 'assertionMethod']\n * }\n * ]\n * };\n * ```\n */\n verificationMethods?: DidCreateVerificationMethod<TKms>[];\n}\n\n/**\n * Proof to used to construct the `_prv._did.` DNS record as described in https://did-dht.com/#rotation to link a DID to a previous DID.\n */\nexport type PreviousDidProof = {\n /** The previous DID. */\n previousDid: string;\n\n /** The signature signed using the private Identity Key of the previous DID in Base64URL format. */\n signature: string;\n};\n\n/**\n * The default DID DHT Gateway or Pkarr Relay server to use when publishing and resolving DID\n * documents.\n */\nconst DEFAULT_GATEWAY_URI = process.env.DID_DHT_GATEWAY_URI || 'https://enbox-did-dht.fly.dev';\n\n/**\n * The version of the DID DHT specification that is implemented by this library.\n *\n * When a DID DHT document is published to the DHT network, the version of the specification that\n * was used to create the document is included in the DNS TXT record for the root record. This\n * allows clients to determine whether the DID DHT document is compatible with the client's\n * implementation of the DID DHT specification. The version number is not present in the\n * corresponding DID document.\n *\n * @see {@link https://did-dht.com | DID DHT Method Specification}\n */\nconst DID_DHT_SPECIFICATION_VERSION = 0;\n\n/**\n * The default TTL for DNS records published to the DHT network.\n *\n * The recommended TTL value is 7200 seconds (2 hours) since it matches the default TTL for\n * Mainline DHT records.\n */\nconst DNS_RECORD_TTL = 7200;\n\n/**\n * Character used to separate distinct elements or entries in the DNS packet representation\n * of a DID Document.\n *\n * For example, verification methods, verification relationships, and services are separated by\n * semicolons (`;`) in the root record:\n * ```\n * vm=k1;auth=k1;asm=k2;inv=k3;del=k3;srv=s1\n * ```\n */\nconst PROPERTY_SEPARATOR = ';';\n\n/**\n * Character used to separate distinct values within a single element or entry in the DNS packet\n * representation of a DID Document.\n *\n * For example, multiple key references for the `authentication` verification relationships are\n * separated by commas (`,`):\n * ```\n * auth=0,1,2\n * ```\n */\nconst VALUE_SEPARATOR = ',';\n\n/**\n * Represents an optional extension to a DID Document\u2019s DNS packet representation exposed as a\n * type index.\n *\n * Type indexing is an OPTIONAL feature that enables DIDs to become discoverable. DIDs that wish to\n * be discoverable and resolveable by type can include one or more types when publishing their DID\n * document to a DID DHT Gateway.\n *\n * The registered DID types are published in the {@link https://did-dht.com/registry/index.html#indexed-types | DID DHT Registry}.\n */\nexport enum DidDhtRegisteredDidType {\n /**\n * Type 0 is reserved for DIDs that do not wish to associate themselves with a specific type but\n * wish to make themselves discoverable.\n */\n Discoverable = 0,\n\n /**\n * Organization\n * @see {@link https://schema.org/Organization | schema definition}\n */\n Organization = 1,\n\n /**\n * Government Organization\n * @see {@link https://schema.org/GovernmentOrganization | schema definition}\n */\n Government = 2,\n\n /**\n * Corporation\n * @see {@link https://schema.org/Corporation | schema definition}\n */\n Corporation = 3,\n\n /**\n * Corporation\n * @see {@link https://schema.org/Corporation | schema definition}\n */\n LocalBusiness = 4,\n\n /**\n * Software Package\n * @see {@link https://schema.org/SoftwareSourceCode | schema definition}\n */\n SoftwarePackage = 5,\n\n /**\n * Web App\n * @see {@link https://schema.org/WebApplication | schema definition}\n */\n WebApp = 6,\n\n /**\n * Financial Institution\n * @see {@link https://schema.org/FinancialService | schema definition}\n */\n FinancialInstitution = 7\n}\n\n/**\n * Enumerates the types of keys that can be used in a DID DHT document.\n *\n * The DID DHT method supports various cryptographic key types. These key types are essential for\n * the creation and management of DIDs and their associated cryptographic operations like signing\n * and encryption. The registered key types are published in the DID DHT Registry and each is\n * assigned a unique numerical value for use by client and gateway implementations.\n *\n * The registered key types are published in the {@link https://did-dht.com/registry/index.html#key-type-index | DID DHT Registry}.\n */\nexport enum DidDhtRegisteredKeyType {\n /**\n * Ed25519: A public-key signature system using the EdDSA (Edwards-curve Digital Signature\n * Algorithm) and Curve25519.\n */\n Ed25519 = 0,\n\n /**\n * secp256k1: A cryptographic curve used for digital signatures in a range of decentralized\n * systems.\n */\n secp256k1 = 1,\n\n /**\n * secp256r1: Also known as P-256 or prime256v1, this curve is used for cryptographic operations\n * and is widely supported in various cryptographic libraries and standards.\n */\n secp256r1 = 2,\n\n /**\n * X25519: A public key used for Diffie-Hellman key exchange using Curve25519.\n */\n X25519 = 3,\n}\n\n/**\n * Maps {@link https://www.w3.org/TR/did-core/#verification-relationships | DID Core Verification Relationship}\n * values to the corresponding record name in the DNS packet representation of a DHT DID document.\n */\nexport enum DidDhtVerificationRelationship {\n /**\n * Specifies how the DID subject is expected to be authenticated.\n */\n authentication = 'auth',\n\n /**\n * Specifies how the DID subject is expected to express claims, such as for issuing Verifiable\n * Credentials.\n */\n assertionMethod = 'asm',\n\n /**\n * Specifies a mechanism used by the DID subject to delegate a cryptographic capability to another\n * party\n */\n capabilityDelegation = 'del',\n\n /**\n * Specifies a verification method used by the DID subject to invoke a cryptographic capability.\n */\n capabilityInvocation = 'inv',\n\n /**\n * Specifies how an entity can generate encryption material to communicate confidentially with the\n * DID subject.\n */\n keyAgreement = 'agm'\n}\n\n/**\n * Private helper that maps algorithm identifiers to their corresponding DID DHT\n * {@link DidDhtRegisteredKeyType | registered key type}.\n */\nconst AlgorithmToKeyTypeMap = {\n Ed25519 : DidDhtRegisteredKeyType.Ed25519,\n ES256K : DidDhtRegisteredKeyType.secp256k1,\n ES256 : DidDhtRegisteredKeyType.secp256r1,\n 'P-256' : DidDhtRegisteredKeyType.secp256r1,\n secp256k1 : DidDhtRegisteredKeyType.secp256k1,\n secp256r1 : DidDhtRegisteredKeyType.secp256r1,\n X25519 : DidDhtRegisteredKeyType.X25519,\n} as const;\n\n/**\n * Private helper that maps did dht registered key types to their corresponding default algorithm identifiers.\n */\nconst KeyTypeToDefaultAlgorithmMap = {\n [DidDhtRegisteredKeyType.Ed25519] : 'EdDSA',\n [DidDhtRegisteredKeyType.secp256k1] : 'ES256K',\n [DidDhtRegisteredKeyType.secp256r1] : 'ES256',\n [DidDhtRegisteredKeyType.X25519] : 'ECDH-ES+A256KW',\n};\n\n/**\n * The `DidDht` class provides an implementation of the `did:dht` DID method.\n *\n * Features:\n * - DID Creation: Create new `did:dht` DIDs.\n * - DID Key Management: Instantiate a DID object from an existing verification method keys or\n * or a key in a Key Management System (KMS). If supported by the KMS, a DID's\n * key can be exported to a portable DID format.\n * - DID Resolution: Resolve a `did:dht` to its corresponding DID Document stored in the DHT network.\n * - Signature Operations: Sign and verify messages using keys associated with a DID.\n *\n * @remarks\n * The `did:dht` method leverages the distributed nature of the Mainline DHT network for\n * decentralized identity management. This method allows DIDs to be resolved without relying on\n * centralized registries or ledgers, enhancing privacy and control for users. The DID Document is\n * stored and retrieved from the DHT network, and the method includes optional mechanisms for\n * discovering DIDs by type.\n *\n * The DID URI in the `did:dht` method includes a method-specific identifier called the Identity Key\n * which corresponds to the DID's entry in the DHT network. The Identity Key required to make\n * changes to the DID Document since Mainline DHT nodes validate the signature of each message\n * before storing the value in the DHT.\n *\n * @see {@link https://did-dht.com | DID DHT Method Specification}\n *\n * @example\n * ```ts\n * // DID Creation\n * const did = await DidDht.create();\n *\n * // DID Creation with a KMS\n * const keyManager = new LocalKeyManager();\n * const did = await DidDht.create({ keyManager });\n *\n * // DID Resolution\n * const resolutionResult = await DidDht.resolve({ did: did.uri });\n *\n * // Signature Operations\n * const signer = await did.getSigner();\n * const signature = await signer.sign({ data: new TextEncoder().encode('Message') });\n * const isValid = await signer.verify({ data: new TextEncoder().encode('Message'), signature });\n *\n * // Import / Export\n *\n * // Export a BearerDid object to the PortableDid format.\n * const portableDid = await did.export();\n *\n * // Reconstruct a BearerDid object from a PortableDid\n * const did = await DidDht.import(portableDid);\n * ```\n */\nexport class DidDht extends DidMethod {\n\n /**\n * Name of the DID method, as defined in the DID DHT specification.\n */\n public static methodName = 'dht';\n\n /**\n * Creates a new DID using the `did:dht` method formed from a newly generated key.\n *\n * @remarks\n * The DID URI is formed by z-base-32 encoding the Identity Key public key and prefixing with\n * `did:dht:`.\n *\n * Notes:\n * - If no `options` are given, by default a new Ed25519 key will be generated which serves as the\n * Identity Key.\n *\n * @example\n * ```ts\n * // DID Creation\n * const did = await DidDht.create();\n *\n * // DID Creation with a KMS\n * const keyManager = new LocalKeyManager();\n * const did = await DidDht.create({ keyManager });\n * ```\n *\n * @param params - The parameters for the create operation.\n * @param params.keyManager - Optionally specify a Key Management System (KMS) used to generate\n * keys and sign data.\n * @param params.options - Optional parameters that can be specified when creating a new DID.\n * @returns A Promise resolving to a {@link BearerDid} object representing the new DID.\n */\n public static async create<TKms extends CryptoApi | undefined = undefined>({\n keyManager = new LocalKeyManager(),\n options = {}\n }: {\n keyManager?: TKms;\n options?: DidDhtCreateOptions<TKms>;\n } = {}): Promise<BearerDid> {\n // Before processing the create operation, validate DID-method-specific requirements to prevent\n // keys from being generated unnecessarily.\n\n // Check 1: Validate that the algorithm for any given verification method is supported by the\n // DID DHT specification.\n if (options.verificationMethods?.some(vm => !(vm.algorithm in AlgorithmToKeyTypeMap))) {\n throw new Error('One or more verification method algorithms are not supported');\n }\n\n // Check 2: Validate that the ID for any given verification method is unique.\n const methodIds = options.verificationMethods?.filter(vm => 'id' in vm).map(vm => vm.id);\n if (methodIds && methodIds.length !== new Set(methodIds).size) {\n throw new Error('One or more verification method IDs are not unique');\n }\n\n // Check 3: Validate that the required properties for any given services are present.\n if (options.services?.some(s => !s.id || !s.type || !s.serviceEndpoint)) {\n throw new Error('One or more services are missing required properties');\n }\n\n // Generate random key material for the Identity Key.\n const identityKeyUri = await keyManager.generateKey({ algorithm: 'Ed25519' });\n const identityKey = await keyManager.getPublicKey({ keyUri: identityKeyUri });\n\n // Compute the DID URI from the Identity Key.\n const didUri = await DidDhtUtils.identityKeyToIdentifier({ identityKey });\n\n // Begin constructing the DID Document.\n const document: DidDocument = {\n id: didUri,\n ...options.alsoKnownAs && { alsoKnownAs: options.alsoKnownAs },\n ...options.controllers && { controller: options.controllers }\n };\n\n // If the given verification methods do not contain an Identity Key, add one.\n const verificationMethodsToAdd = [...options.verificationMethods ?? []];\n if (!verificationMethodsToAdd?.some(vm => vm.id?.split('#').pop() === '0')) {\n // Add the Identity Key to the beginning of the key set.\n verificationMethodsToAdd.unshift({\n algorithm : 'Ed25519' as DidCreateVerificationMethod<TKms>['algorithm'],\n id : '0',\n purposes : ['authentication', 'assertionMethod', 'capabilityDelegation', 'capabilityInvocation']\n });\n }\n\n // Generate random key material for the Identity Key and any additional verification methods.\n // Add verification methods to the DID document.\n for (const verificationMethod of verificationMethodsToAdd) {\n // Generate a random key for the verification method, or if its the Identity Key's\n // verification method (`id` is 0) use the key previously generated.\n const keyUri = (verificationMethod.id && verificationMethod.id.split('#').pop() === '0')\n ? identityKeyUri\n : await keyManager.generateKey({ algorithm: verificationMethod.algorithm });\n\n const publicKey = await keyManager.getPublicKey({ keyUri });\n\n // Use the given ID, the key's ID, or the key's thumbprint as the verification method ID.\n let methodId = verificationMethod.id ?? publicKey.kid ?? await computeJwkThumbprint({ jwk: publicKey });\n methodId = `${didUri}#${extractDidFragment(methodId)}`; // Remove fragment prefix, if any.\n\n // Initialize the `verificationMethod` array if it does not already exist.\n document.verificationMethod ??= [];\n\n // Add the verification method to the DID document.\n document.verificationMethod.push({\n id : methodId,\n type : 'JsonWebKey',\n controller : verificationMethod.controller ?? didUri,\n publicKeyJwk : publicKey,\n });\n\n // Add the verification method to the specified purpose properties of the DID document.\n for (const purpose of verificationMethod.purposes ?? []) {\n // Initialize the purpose property if it does not already exist.\n document[purpose] ??= [];\n // Add the verification method to the purpose property.\n document[purpose]!.push(methodId);\n }\n }\n\n // Add services, if any, to the DID document.\n options.services?.forEach(service => {\n document.service ??= [];\n service.id = `${didUri}#${service.id.split('#').pop()}`; // Remove fragment prefix, if any.\n document.service.push(service);\n });\n\n // Create the BearerDid object, including the registered DID types (if any), and specify that\n // the DID has not yet been published.\n const did = new BearerDid({\n uri : didUri,\n document,\n metadata : {\n published: false,\n ...options.types && { types: options.types }\n },\n keyManager\n });\n\n // By default, publish the DID document to a DHT Gateway unless explicitly disabled.\n if (options.publish ?? true) {\n const registrationResult = await DidDht.publish({ did, gatewayUri: options.gatewayUri });\n did.metadata = registrationResult.didDocumentMetadata;\n }\n\n return did;\n }\n\n /**\n * Instantiates a {@link BearerDid} object for the DID DHT method from a given {@link PortableDid}.\n *\n * This method allows for the creation of a `BearerDid` object using a previously created DID's\n * key material, DID document, and metadata.\n *\n * @example\n * ```ts\n * // Export an existing BearerDid to PortableDid format.\n * const portableDid = await did.export();\n * // Reconstruct a BearerDid object from the PortableDid.\n * const did = await DidDht.import({ portableDid });\n * ```\n *\n * @param params - The parameters for the import operation.\n * @param params.portableDid - The PortableDid object to import.\n * @param params.keyManager - Optionally specify an external Key Management System (KMS) used to\n * generate keys and sign data. If not given, a new\n * {@link LocalKeyManager} instance will be created and\n * used.\n * @returns A Promise resolving to a `BearerDid` object representing the DID formed from the\n * provided PortableDid.\n * @throws An error if the PortableDid document does not contain any verification methods, lacks\n * an Identity Key, or the keys for any verification method are missing in the key\n * manager.\n */\n public static async import({ portableDid, keyManager = new LocalKeyManager() }: {\n keyManager?: CryptoApi & KeyImporterExporter<KmsImportKeyParams, KeyIdentifier, KmsExportKeyParams>;\n portableDid: PortableDid;\n }): Promise<BearerDid> {\n // Verify the DID method is supported.\n const parsedDid = Did.parse(portableDid.uri);\n if (parsedDid?.method !== DidDht.methodName) {\n throw new DidError(DidErrorCode.MethodNotSupported, `Method not supported`);\n }\n\n const did = await BearerDid.import({ portableDid, keyManager });\n\n // Validate that the given verification methods contain an Identity Key.\n if (!did.document.verificationMethod?.some(vm => vm.id?.split('#').pop() === '0')) {\n throw new DidError(DidErrorCode.InvalidDidDocument, `DID document must contain an Identity Key`);\n }\n\n return did;\n }\n\n /**\n * Given the W3C DID Document of a `did:dht` DID, return the verification method that will be used\n * for signing messages and credentials. If given, the `methodId` parameter is used to select the\n * verification method. If not given, the Identity Key's verification method with an ID fragment\n * of '#0' is used.\n *\n * @param params - The parameters for the `getSigningMethod` operation.\n * @param params.didDocument - DID Document to get the verification method from.\n * @param params.methodId - ID of the verification method to use for signing.\n * @returns Verification method to use for signing.\n */\n public static async getSigningMethod({ didDocument, methodId = '#0' }: {\n didDocument: DidDocument;\n methodId?: string;\n }): Promise<DidVerificationMethod> {\n // Verify the DID method is supported.\n const parsedDid = Did.parse(didDocument.id);\n if (parsedDid && parsedDid.method !== this.methodName) {\n throw new DidError(DidErrorCode.MethodNotSupported, `Method not supported: ${parsedDid.method}`);\n }\n\n // Attempt to find a verification method that matches the given method ID, or if not given,\n // find the first verification method intended for signing claims.\n const verificationMethod = didDocument.verificationMethod?.find(\n vm => extractDidFragment(vm.id) === (extractDidFragment(methodId) ?? extractDidFragment(didDocument.assertionMethod?.[0]))\n );\n\n if (!(verificationMethod && verificationMethod.publicKeyJwk)) {\n throw new DidError(DidErrorCode.InternalError, 'A verification method intended for signing could not be determined from the DID Document');\n }\n\n return verificationMethod;\n }\n\n /**\n * Publishes a DID to the DHT, making it publicly discoverable and resolvable.\n *\n * This method handles the publication of a DID Document associated with a `did:dht` DID to the\n * Mainline DHT network. The publication process involves storing the DID Document in Mainline DHT\n * via a Pkarr relay server.\n *\n * @remarks\n * - This method is typically invoked automatically during the creation of a new DID unless the\n * `publish` option is set to `false`.\n * - For existing, unpublished DIDs, it can be used to publish the DID Document to Mainline DHT.\n * - The method relies on the specified Pkarr relay server to interface with the DHT network.\n *\n * @example\n * ```ts\n * // Generate a new DID and keys but explicitly disable publishing.\n * const did = await DidDht.create({ options: { publish: false } });\n * // Publish the DID to the DHT.\n * const registrationResult = await DidDht.publish({ did });\n * // `registrationResult.didDocumentMetadata.published` is true if the DID was successfully published.\n * ```\n *\n * @param params - The parameters for the `publish` operation.\n * @param params.did - The `BearerDid` object representing the DID to be published.\n * @param params.gatewayUri - Optional. The URI of a server involved in executing DID method\n * operations. In the context of publishing, the endpoint is expected\n * to be a DID DHT Gateway or Pkarr Relay. If not specified, a default\n * gateway node is used.\n * @returns A promise that resolves to a {@link DidRegistrationResult} object that contains\n * the result of registering the DID with a DID DHT Gateway or Pkarr relay.\n */\n public static async publish({ did, gatewayUri = DEFAULT_GATEWAY_URI }: {\n did: BearerDid;\n gatewayUri?: string;\n }): Promise<DidRegistrationResult> {\n const registrationResult = await DidDhtDocument.put({ did, gatewayUri });\n\n return registrationResult;\n }\n\n /**\n * Resolves a `did:dht` identifier to its corresponding DID document.\n *\n * This method performs the resolution of a `did:dht` DID, retrieving its DID Document from the\n * Mainline DHT network. The process involves querying the DHT network via a Pkarr relay server to\n * retrieve the DID Document that corresponds to the given DID identifier.\n *\n * @remarks\n * - If a `gatewayUri` option is not specified, a default Pkarr relay is used to access the DHT\n * network.\n * - It decodes the DID identifier and retrieves the associated DID Document and metadata.\n * - In case of resolution failure, appropriate error information is returned.\n *\n * @example\n * ```ts\n * const resolutionResult = await DidDht.resolve('did:dht:example');\n * ```\n *\n * @param didUri - The DID to be resolved.\n * @param options - Optional parameters for resolving the DID. Unused by this DID method.\n * @returns A Promise resolving to a {@link DidResolutionResult} object representing the result of\n * the resolution.\n */\n public static async resolve(didUri: string, options: DidResolutionOptions = {}): Promise<DidResolutionResult> {\n // To execute the read method operation, use the given gateway URI or a default.\n const gatewayUri = options?.gatewayUri ?? DEFAULT_GATEWAY_URI;\n\n try {\n // Attempt to decode the z-base-32-encoded identifier.\n await DidDhtUtils.identifierToIdentityKey({ didUri });\n\n // Attempt to retrieve the DID document and metadata from the DHT network.\n const { didDocument, didDocumentMetadata } = await DidDhtDocument.get({ didUri, gatewayUri });\n\n // If the DID document was retrieved successfully, return it.\n return {\n ...EMPTY_DID_RESOLUTION_RESULT,\n didDocument,\n didDocumentMetadata\n };\n\n } catch (error: any) {\n // Rethrow any unexpected errors that are not a `DidError`.\n if (!(error instanceof DidError)) {throw new Error(error);}\n\n // Return a DID Resolution Result with the appropriate error code.\n return {\n ...EMPTY_DID_RESOLUTION_RESULT,\n didResolutionMetadata: {\n error: error.code,\n ...error.message && { errorMessage: error.message }\n }\n };\n }\n }\n}\n\n/**\n * The `DidDhtDocument` class provides functionality for interacting with the DID document stored in\n * Mainline DHT in support of DID DHT method create, resolve, update, and deactivate operations.\n *\n * This class includes methods for retrieving and publishing DID documents to and from the DHT,\n * using DNS packet encoding and DID DHT Gateway or Pkarr Relay servers.\n */\nexport class DidDhtDocument {\n /**\n * Retrieves a DID document and its metadata from the DHT network.\n *\n * @param params - The parameters for the get operation.\n * @param params.didUri - The DID URI containing the Identity Key.\n * @param params.gatewayUri - The DID DHT Gateway or Pkarr Relay URI.\n * @returns A Promise resolving to a {@link DidResolutionResult} object containing the DID\n * document and its metadata.\n */\n public static async get({ didUri, gatewayUri }: {\n didUri: string;\n gatewayUri: string;\n }): Promise<DidResolutionResult> {\n // Decode the z-base-32 DID identifier to public key as a byte array.\n const publicKeyBytes = DidDhtUtils.identifierToIdentityKeyBytes({ didUri });\n\n // Retrieve the signed BEP44 message from a DID DHT Gateway or Pkarr relay.\n const bep44Message = await DidDhtDocument.pkarrGet({ gatewayUri, publicKeyBytes });\n\n // Verify the signature of the BEP44 message and parse the value to a DNS packet.\n const dnsPacket = await DidDhtUtils.parseBep44GetMessage({ bep44Message });\n\n // Convert the DNS packet to a DID document and metadata.\n const resolutionResult = await DidDhtDocument.fromDnsPacket({ didUri, dnsPacket });\n\n // Set the version ID of the DID document metadata to the sequence number of the BEP44 message.\n resolutionResult.didDocumentMetadata.versionId = bep44Message.seq.toString();\n\n return resolutionResult;\n }\n\n /**\n * Publishes a DID document to the DHT network.\n *\n * @param params - The parameters to use when publishing the DID document to the DHT network.\n * @param params.did - The DID object whose DID document will be published.\n * @param params.gatewayUri - The DID DHT Gateway or Pkarr Relay URI.\n * @returns A promise that resolves to a {@link DidRegistrationResult} object that contains\n * the result of registering the DID with a DID DHT Gateway or Pkarr relay.\n */\n public static async put({ did, gatewayUri }: {\n did: BearerDid;\n gatewayUri: string;\n }): Promise<DidRegistrationResult> {\n // Convert the DID document and DID metadata (such as DID types) to a DNS packet.\n const dnsPacket = await DidDhtDocument.toDnsPacket({\n didDocument : did.document,\n didMetadata : did.metadata,\n authoritativeGatewayUris : [gatewayUri]\n });\n\n // Create a signed BEP44 put message from the DNS packet.\n const bep44Message = await DidDhtUtils.createBep44PutMessage({\n dnsPacket,\n publicKeyBytes : DidDhtUtils.identifierToIdentityKeyBytes({ didUri: did.uri }),\n signer : await did.getSigner({ methodId: '0' })\n });\n\n // Publish the DNS packet to the DHT network.\n const putResult = await DidDhtDocument.pkarrPut({ gatewayUri, bep44Message });\n\n // Return the result of processing the PUT operation, including the updated DID metadata with\n // the version ID and the publishing result.\n return {\n didDocument : did.document,\n didDocumentMetadata : {\n ...did.metadata,\n published : putResult,\n versionId : bep44Message.seq.toString()\n },\n didRegistrationMetadata: {}\n };\n }\n\n /**\n * Retrieves a signed BEP44 message from a DID DHT Gateway or Pkarr Relay server.\n *\n * @see {@link https://github.com/Nuhvi/pkarr/blob/main/design/relays.md | Pkarr Relay design}\n *\n * @param params\n * @param params.gatewayUri - The DID DHT Gateway or Pkarr Relay URI.\n * @param params.publicKeyBytes - The public key bytes of the Identity Key, z-base-32 encoded.\n * @returns A promise resolving to a BEP44 message containing the signed DNS packet.\n */\n private static async pkarrGet({ gatewayUri, publicKeyBytes }: {\n publicKeyBytes: Uint8Array;\n gatewayUri: string;\n }): Promise<Bep44Message> {\n // The identifier (key in the DHT) is the z-base-32 encoding of the Identity Key.\n const identifier = Convert.uint8Array(publicKeyBytes).toBase32Z();\n\n // Concatenate the gateway URI with the identifier to form the full URL.\n const url = new URL(identifier, gatewayUri).href;\n\n // Transmit the Get request to the DID DHT Gateway or Pkarr Relay and get the response.\n let response: Response;\n try {\n response = await fetch(url, { method: 'GET' });\n\n if (!response.ok) {\n throw new DidError(DidErrorCode.NotFound, `Pkarr record not found for: ${identifier}`);\n }\n\n } catch (error: any) {\n if (error instanceof DidError) {throw error;}\n throw new DidError(DidErrorCode.InternalError, `Failed to fetch Pkarr record: ${error.message}`);\n }\n\n // Read the Fetch Response stream into a byte array.\n const messageBytes = await response.arrayBuffer();\n\n if (!messageBytes) {\n throw new DidError(DidErrorCode.NotFound, `Pkarr record not found for: ${identifier}`);\n }\n\n if (messageBytes.byteLength < 72) {\n throw new DidError(DidErrorCode.InvalidDidDocumentLength, `Pkarr response must be at least 72 bytes but got: ${messageBytes.byteLength}`);\n }\n\n if (messageBytes.byteLength > 1072) {\n throw new DidError(DidErrorCode.InvalidDidDocumentLength, `Pkarr response exceeds 1000 byte limit: ${messageBytes.byteLength}`);\n }\n\n // Decode the BEP44 message from the byte array.\n const bep44Message: Bep44Message = {\n k : publicKeyBytes,\n seq : Number(new DataView(messageBytes).getBigUint64(64)),\n sig : new Uint8Array(messageBytes, 0, 64),\n v : new Uint8Array(messageBytes, 72)\n };\n\n return bep44Message;\n }\n\n /**\n * Publishes a signed BEP44 message to a DID DHT Gateway or Pkarr Relay server.\n *\n * @see {@link https://github.com/Nuhvi/pkarr/blob/main/design/relays.md | Pkarr Relay design}\n *\n * @param params - The parameters to use when publishing a signed BEP44 message to a Pkarr relay server.\n * @param params.gatewayUri - The DID DHT Gateway or Pkarr Relay URI.\n * @param params.bep44Message - The BEP44 message to be published, containing the signed DNS packet.\n * @returns A promise resolving to `true` if the message was successfully published, otherwise `false`.\n */\n private static async pkarrPut({ gatewayUri, bep44Message }: {\n bep44Message: Bep44Message;\n gatewayUri: string;\n }): Promise<boolean> {\n // The identifier (key in the DHT) is the z-base-32 encoding of the Identity Key.\n const identifier = Convert.uint8Array(bep44Message.k).toBase32Z();\n\n // Concatenate the gateway URI with the identifier to form the full URL.\n const url = new URL(identifier, gatewayUri).href;\n\n // Construct the body of the request according to the Pkarr relay specification.\n const body = new Uint8Array(bep44Message.v.length + 72);\n body.set(bep44Message.sig, 0);\n new DataView(body.buffer).setBigUint64(bep44Message.sig.length, BigInt(bep44Message.seq));\n body.set(bep44Message.v, bep44Message.sig.length + 8);\n\n // Transmit the Put request to the Pkarr relay and get the response.\n let response: Response;\n try {\n response = await fetch(url, {\n method : 'PUT',\n headers : { 'Content-Type': 'application/octet-stream' },\n body\n });\n\n } catch (error: any) {\n throw new DidError(DidErrorCode.InternalError, `Failed to put Pkarr record for identifier ${identifier}: ${error.message}`);\n }\n\n // Return `true` if the DHT request was successful, otherwise return `false`.\n return response.ok;\n }\n\n /**\n * Converts a DNS packet to a DID document according to the DID DHT specification.\n *\n * @see {@link https://did-dht.com/#dids-as-dns-records | DID DHT Specification, \u00A7 DIDs as DNS Records}\n *\n * @param params - The parameters to use when converting a DNS packet to a DID document.\n * @param params.didUri - The DID URI of the DID document.\n * @param params.dnsPacket - The DNS packet to convert to a DID document.\n * @returns A Promise resolving to a {@link DidResolutionResult} object containing the DID\n * document and its metadata.\n */\n public static async fromDnsPacket({ didUri, dnsPacket }: {\n didUri: string;\n dnsPacket: Packet;\n }): Promise<DidResolutionResult> {\n // Begin constructing the DID Document.\n const didDocument: DidDocument = { id: didUri };\n\n // Since the DID document is being retrieved from the DHT, it is considered published.\n const didDocumentMetadata: DidMetadata = {\n published: true\n };\n\n const idLookup = new Map<string, string>();\n\n for (const answer of dnsPacket?.answers ?? []) {\n // DID DHT properties are ONLY present in DNS TXT records.\n if (answer.type !== 'TXT') {continue;}\n\n // Get the DID DHT record identifier (e.g., k0, aka, did, etc.) from the DNS resource name.\n const dnsRecordId = answer.name.split('.')[0].substring(1);\n\n switch (true) {\n // Process an also known as record.\n case dnsRecordId.startsWith('aka'): {\n // Decode the DNS TXT record data value to a string.\n const data = DidDhtUtils.parseTxtDataToString(answer.data);\n\n // Add the 'alsoKnownAs' property to the DID document.\n didDocument.alsoKnownAs = data.split(VALUE_SEPARATOR);\n\n break;\n }\n\n // Process a controller record.\n case dnsRecordId.startsWith('cnt'): {\n // Decode the DNS TXT record data value to a string.\n const data = DidDhtUtils.parseTxtDataToString(answer.data);\n\n // Add the 'controller' property to the DID document.\n didDocument.controller = data.includes(VALUE_SEPARATOR) ? data.split(VALUE_SEPARATOR) : data;\n\n break;\n }\n\n // Process verification methods.\n case dnsRecordId.startsWith('k'): {\n // Get the key type (t), Base64URL-encoded public key (k), algorithm (a), and\n // optionally, controller (c) or Verification Method ID (id) from the decoded TXT record data.\n const { id, t, k, c, a: parsedAlg } = DidDhtUtils.parseTxtDataToObject(answer.data);\n\n // Convert the public key from Base64URL format to a byte array.\n const publicKeyBytes = Convert.base64Url(k).toUint8Array();\n\n // Use the key type integer to look up the cryptographic curve name.\n const namedCurve = DidDhtRegisteredKeyType[Number(t)];\n\n // Convert the public key from a byte array to JWK format.\n const publicKey = await DidDhtUtils.keyConverter(namedCurve).bytesToPublicKey({ publicKeyBytes });\n\n publicKey.alg = parsedAlg || KeyTypeToDefaultAlgorithmMap[Number(t) as DidDhtRegisteredKeyType];\n\n // TODO: when this is complete https://github.com/enboxorg/enbox/issues/638 then we can add this back and\n // update the test vectors kid back to '0'\n // if(dnsRecordId === 'k0') {\n // publicKey.kid = '0';\n // }\n\n // Determine the Verification Method ID: '0' for the identity key,\n // the id from the TXT Data Object, or the JWK thumbprint if an explicity Verification Method ID not defined.\n const vmId = dnsRecordId === 'k0' ? '0' : id !== undefined ? id : await computeJwkThumbprint({ jwk: publicKey });\n\n // Initialize the `verificationMethod` array if it does not already exist.\n didDocument.verificationMethod ??= [];\n\n // Prepend the DID URI to the ID fragment to form the full verification method ID.\n const methodId = `${didUri}#${vmId}`;\n\n // Add the verification method to the DID document.\n didDocument.verificationMethod.push({\n id : methodId,\n type : 'JsonWebKey',\n controller : c ?? didUri,\n publicKeyJwk : publicKey,\n });\n\n // Add a mapping from the DNS record ID (e.g., 'k0', 'k1', etc.) to the verification\n // method ID (e.g., 'did:dht:...#0', etc.).\n idLookup.set(dnsRecordId, methodId);\n\n break;\n }\n\n // Process services.\n case dnsRecordId.startsWith('s'): {\n // Get the service ID fragment (id), type (t), service endpoint (se), and optionally,\n // other properties from the decoded TXT record data.\n const { id, t, se, ...customProperties } = DidDhtUtils.parseTxtDataToObject(answer.data);\n\n // if multi-values: 'a,b,c' -> ['a', 'b', 'c'], if single-value: 'a' -> ['a']\n // NOTE: The service endpoint technically can either be a string or an array of strings,\n // we enforce an array for single-value to simplify verification of vector 3 in the spec: https://did-dht.com/#vector-3\n const serviceEndpoint = se.includes(VALUE_SEPARATOR) ? se.split(VALUE_SEPARATOR) : [se];\n\n // Convert custom property values to either a string or an array of strings.\n const serviceProperties = Object.fromEntries(Object.entries(customProperties).map(\n ([k, v]) => [k, v.includes(VALUE_SEPARATOR) ? v.split(VALUE_SEPARATOR) : v]\n ));\n\n // Initialize the `service` array if it does not already exist.\n didDocument.service ??= [];\n\n didDocument.service.push({\n ...serviceProperties,\n id : `${didUri}#${id}`,\n type : t,\n serviceEndpoint\n });\n\n break;\n }\n\n // Process DID DHT types.\n case dnsRecordId.startsWith('typ'): {\n // Decode the DNS TXT record data value to an object.\n const { id: types } = DidDhtUtils.parseTxtDataToObject(answer.data);\n\n // Add the DID DHT Registered DID Types represented as numbers to DID metadata.\n didDocumentMetadata.types = types.split(VALUE_SEPARATOR).map(typeInteger => Number(typeInteger));\n\n break;\n }\n\n // Process root record.\n case dnsRecordId.startsWith('did'): {\n // Helper function that maps verification relationship values to verification method IDs.\n const recordIdsToMethodIds = (data: string): string[] => data\n .split(VALUE_SEPARATOR)\n .map(dnsRecordId => idLookup.get(dnsRecordId))\n .filter((id): id is string => typeof id === 'string');\n\n // Decode the DNS TXT record data and destructure verification relationship properties.\n const { auth, asm, del, inv, agm } = DidDhtUtils.parseTxtDataToObject(answer.data);\n\n // Add the verification relationships, if any, to the DID document.\n if (auth) {didDocument.authentication = recordIdsToMethodIds(auth);}\n if (asm) {didDocument.assertionMethod = recordIdsToMethodIds(asm);}\n if (del) {didDocument.capabilityDelegation = recordIdsToMethodIds(del);}\n if (inv) {didDocument.capabilityInvocation = recordIdsToMethodIds(inv);}\n if (agm) {didDocument.keyAgreement = recordIdsToMethodIds(agm);}\n\n break;\n }\n }\n }\n\n return { didDocument, didDocumentMetadata, didResolutionMetadata: {} };\n }\n\n /**\n * Converts a DID document to a DNS packet according to the DID DHT specification.\n *\n * @see {@link https://did-dht.com/#dids-as-dns-records | DID DHT Specification, \u00A7 DIDs as DNS Records}\n *\n * @param params - The parameters to use when converting a DID document to a DNS packet.\n * @param params.didDocument - The DID document to convert to a DNS packet.\n * @param params.didMetadata - The DID metadata to include in the DNS packet.\n * @param params.authoritativeGatewayUris - The URIs of the Authoritative Gateways to generate NS records from.\n * @param params.previousDidProof - The signature proof that this DID is linked to the given previous DID.\n * @returns A promise that resolves to a DNS packet.\n */\n public static async toDnsPacket({ didDocument, didMetadata, authoritativeGatewayUris, previousDidProof }: {\n didDocument: DidDocument;\n didMetadata: DidMetadata;\n authoritativeGatewayUris?: string[];\n previousDidProof?: PreviousDidProof;\n }): Promise<Packet> {\n const txtRecords: TxtAnswer[] = [];\n const nsRecords: StringAnswer[] = [];\n const idLookup = new Map<string, string>();\n const serviceIds: string[] = [];\n const verificationMethodIds: string[] = [];\n\n // Add `_prv._did.` TXT record if previous DID proof is provided and valid.\n if (previousDidProof !== undefined) {\n const { signature, previousDid } = previousDidProof;\n\n await DidDhtUtils.validatePreviousDidProof({\n newDid: didDocument.id,\n previousDidProof\n });\n\n txtRecords.push({\n type : 'TXT',\n name : '_prv._did.',\n ttl : DNS_RECORD_TTL,\n data : `id=${previousDid};s=${signature}`\n });\n }\n\n // Add DNS TXT records if the DID document contains an `alsoKnownAs` property.\n if (didDocument.alsoKnownAs) {\n txtRecords.push({\n type : 'TXT',\n name : '_aka._did.',\n ttl : DNS_RECORD_TTL,\n data : didDocument.alsoKnownAs.join(VALUE_SEPARATOR)\n });\n }\n\n // Add DNS TXT records if the DID document contains a `controller` property.\n if (didDocument.controller) {\n const controller = Array.isArray(didDocument.controller)\n ? didDocument.controller.join(VALUE_SEPARATOR)\n : didDocument.controller;\n txtRecords.push({\n type : 'TXT',\n name : '_cnt._did.',\n ttl : DNS_RECORD_TTL,\n data : controller\n });\n }\n\n // Add DNS TXT records for each verification method.\n for (const [index, verificationMethod] of didDocument.verificationMethod?.entries() ?? []) {\n const dnsRecordId = `k${index}`;\n verificationMethodIds.push(dnsRecordId);\n const methodId = verificationMethod.id.split('#').pop()!; // Remove fragment prefix, if any.\n idLookup.set(methodId, dnsRecordId);\n\n const publicKey = verificationMethod.publicKeyJwk;\n\n if (!(publicKey?.crv && publicKey.crv in AlgorithmToKeyTypeMap)) {\n throw new DidError(DidErrorCode.InvalidPublicKeyType, `Verification method '${verificationMethod.id}' contains an unsupported key type: ${publicKey?.crv ?? 'undefined'}`);\n }\n\n // Use the public key's `crv` property to get the DID DHT key type.\n const keyType = DidDhtRegisteredKeyType[publicKey.crv as keyof typeof DidDhtRegisteredKeyType];\n\n // Convert the public key from JWK format to a byte array.\n const publicKeyBytes = await DidDhtUtils.keyConverter(publicKey.crv).publicKeyToBytes({ publicKey });\n\n // Convert the public key from a byte array to Base64URL format.\n const publicKeyBase64Url = Convert.uint8Array(publicKeyBytes).toBase64Url();\n\n // Define the data for the DNS TXT record.\n const txtData = [`t=${keyType}`, `k=${publicKeyBase64Url}`];\n // if the methodId is not the identity key or a thumbprint, explicity define the id within the DNS TXT record.\n // otherwise the id can be inferred from the thumbprint.\n if (methodId !== '0' && await computeJwkThumbprint({ jwk: publicKey }) !== methodId) {\n txtData.unshift(`id=${methodId}`);\n }\n // Only set the algorithm property (`a`) if it differs from the default algorithm for the key type.\n if (publicKey.alg !== KeyTypeToDefaultAlgorithmMap[keyType]) {\n txtData.push(`a=${publicKey.alg}`);\n }\n\n // Add the controller property, if set to a value other than the Identity Key (DID Subject).\n if (verificationMethod.controller !== didDocument.id) {txtData.push(`c=${verificationMethod.controller}`);}\n\n // Add a TXT record for the verification method.\n txtRecords.push({\n type : 'TXT',\n name : `_${dnsRecordId}._did.`,\n ttl : DNS_RECORD_TTL,\n data : txtData.join(PROPERTY_SEPARATOR)\n });\n }\n\n // Add DNS TXT records for each service.\n didDocument.service?.forEach((service, index) => {\n const dnsRecordId = `s${index}`;\n serviceIds.push(dnsRecordId);\n let { id, type: t, serviceEndpoint: se, ...customProperties } = service;\n id = extractDidFragment(id)!;\n se = Array.isArray(se) ? se.join(',') : se;\n\n // Define the data for the DNS TXT record.\n const txtData = Object.entries({ id, t, se, ...customProperties }).map(\n ([key, value]) => `${key}=${value}`\n );\n\n const txtDataString = txtData.join(PROPERTY_SEPARATOR);\n const data = DidDhtUtils.chunkDataIfNeeded(txtDataString);\n\n // Add a TXT record for the verification method.\n txtRecords.push({\n type : 'TXT',\n name : `_${dnsRecordId}._did.`,\n ttl : DNS_RECORD_TTL,\n data\n });\n });\n\n // Initialize the root DNS TXT record with the DID DHT specification version.\n const rootRecord: string[] = [`v=${DID_DHT_SPECIFICATION_VERSION}`];\n\n // Add verification methods to the root record.\n if (verificationMethodIds.length) {\n rootRecord.push(`vm=${verificationMethodIds.join(VALUE_SEPARATOR)}`);\n }\n\n // Add verification relationships to the root record.\n Object.keys(DidVerificationRelationship).forEach(relationship => {\n // Collect the verification method IDs for the given relationship.\n const dnsRecordIds = (didDocument[relationship as keyof DidDocument] as string[] | undefined)\n ?.map((id: string): string | undefined => idLookup.get(id.split('#').pop()!));\n\n // If the relationship includes verification methods, add them to the root record.\n if (dnsRecordIds) {\n const recordName = DidDhtVerificationRelationship[relationship as keyof typeof DidDhtVerificationRelationship];\n rootRecord.push(`${recordName}=${dnsRecordIds.join(VALUE_SEPARATOR)}`);\n }\n });\n\n // Add services to the root record.\n if (serviceIds.length) {\n rootRecord.push(`svc=${serviceIds.join(VALUE_SEPARATOR)}`);\n }\n\n // If defined, add a DNS TXT record for each registered DID type.\n if (didMetadata.types?.length) {\n // DID types can be specified as either a string or a number, so we need to normalize the\n // values to integers.\n const types = didMetadata.types as (DidDhtRegisteredDidType | keyof typeof DidDhtRegisteredDidType)[];\n const typeIntegers = types.map(type => typeof type === 'string' ? DidDhtRegisteredDidType[type] : type);\n\n txtRecords.push({\n type : 'TXT',\n name : '_typ._did.',\n ttl : DNS_RECORD_TTL,\n data : `id=${typeIntegers.join(VALUE_SEPARATOR)}`\n });\n }\n\n // Add a DNS TXT record for the root record.\n txtRecords.push({\n type : 'TXT',\n name : '_did.' + DidDhtDocument.getUniqueDidSuffix(didDocument.id) + '.', // name of a Root Record MUST end in `<ID>.`\n ttl : DNS_RECORD_TTL,\n data : rootRecord.join(PROPERTY_SEPARATOR)\n });\n\n // Add an NS record for each authoritative gateway URI.\n for (const gatewayUri of authoritativeGatewayUris || []) {\n nsRecords.push({\n type : 'NS',\n name : '_did.' + DidDhtDocument.getUniqueDidSuffix(didDocument.id) + '.', // name of an NS record a authoritative gateway MUST end in `<ID>.`\n ttl : DNS_RECORD_TTL,\n data : gatewayUri + '.'\n });\n }\n\n // Create a DNS response packet with the authoritative answer flag set.\n const dnsPacket: Packet = {\n id : 0,\n type : 'response',\n flags : AUTHORITATIVE_ANSWER,\n answers : [...txtRecords, ...nsRecords]\n };\n\n return dnsPacket;\n }\n\n /**\n * Gets the unique portion of the DID identifier after the last `:` character.\n * e.g. `did:dht:example` -> `example`\n *\n * @param did - The DID to extract the unique suffix from.\n */\n private static getUniqueDidSuffix(did: string ): string {\n return did.split(':')[2];\n }\n}\n\n/**\n * The `DidDhtUtils` class provides utility functions to support operations in the DID DHT method.\n * This includes functions for creating and parsing BEP44 messages, handling identity keys, and\n * converting between different formats and representations.\n */\nexport class DidDhtUtils {\n /**\n * Creates a BEP44 put message, which is used to publish a DID document to the DHT network.\n *\n * @param params - The parameters to use when creating the BEP44 put message\n * @param params.dnsPacket - The DNS packet to encode in the BEP44 message.\n * @param params.publicKeyBytes - The public key bytes of the Identity Key.\n * @param params.signer - Signer that can sign and verify data using the Identity Key.\n * @returns A promise that resolves to a BEP44 put message.\n */\n public static async createBep44PutMessage({ dnsPacket, publicKeyBytes, signer }: {\n dnsPacket: Packet;\n publicKeyBytes: Uint8Array;\n signer: Signer;\n }): Promise<Bep44Message> {\n // BEP44 requires that the sequence number be a monotoically increasing integer, so we use the\n // current time in seconds since Unix epoch as a simple solution. Higher precision is not\n // recommended since DID DHT documents are not expected to change frequently and there are\n // small differences in system clocks that can cause issues if multiple clients are publishing\n // updates to the same DID document.\n const sequenceNumber = Math.ceil(Date.now() / 1000);\n\n // Encode the DNS packet into a byte array containing a UDP payload.\n const encodedDnsPacket = dnsPacketEncode(dnsPacket);\n\n // Encode the sequence and DNS byte array to bencode format.\n const bencodedData = bencode.encode({ seq: sequenceNumber, v: encodedDnsPacket }).subarray(1, -1);\n\n if (bencodedData.length > 1000) {\n throw new DidError(DidErrorCode.InvalidDidDocumentLength, `DNS packet exceeds the 1000 byte maximum size: ${bencodedData.length} bytes`);\n }\n\n // Sign the BEP44 message.\n const signature = await signer.sign({ data: bencodedData });\n\n return { k: publicKeyBytes, seq: sequenceNumber, sig: signature, v: encodedDnsPacket };\n }\n\n /**\n * Converts a DID URI to a JSON Web Key (JWK) representing the Identity Key.\n *\n * @param params - The parameters to use for the conversion.\n * @param params.didUri - The DID URI containing the Identity Key.\n * @returns A promise that resolves to a JWK representing the Identity Key.\n */\n public static async identifierToIdentityKey({ didUri }: {\n didUri: string\n }): Promise<Jwk> {\n // Decode the method-specific identifier from z-base-32 to a byte array.\n const identityKeyBytes = DidDhtUtils.identifierToIdentityKeyBytes({ didUri });\n\n // Convert the byte array to a JWK.\n const identityKey = await Ed25519.bytesToPublicKey({ publicKeyBytes: identityKeyBytes });\n\n return identityKey;\n }\n\n /**\n * Converts a DID URI to the byte array representation of the Identity Key.\n *\n * @param params - The parameters to use for the conversion.\n * @param params.didUri - The DID URI containing the Identity Key.\n * @returns A byte array representation of the Identity Key.\n */\n public static identifierToIdentityKeyBytes({ didUri }: {\n didUri: string\n }): Uint8Array {\n // Parse the DID URI.\n const parsedDid = Did.parse(didUri);\n\n // Verify that the DID URI is valid.\n if (!parsedDid) {\n throw new DidError(DidErrorCode.InvalidDid, `Invalid DID URI: ${didUri}`);\n }\n\n // Verify the DID method is supported.\n if (parsedDid.method !== DidDht.methodName) {\n throw new DidError(DidErrorCode.MethodNotSupported, `Method not supported: ${parsedDid.method}`);\n }\n\n // Decode the method-specific identifier from z-base-32 to a byte array.\n let identityKeyBytes: Uint8Array | undefined;\n try {\n identityKeyBytes = Convert.base32Z(parsedDid.id).toUint8Array();\n } catch {\n throw new DidError(DidErrorCode.InvalidPublicKey, `Failed to decode method-specific identifier`);\n }\n\n if (identityKeyBytes.length !== 32) {\n throw new DidError(DidErrorCode.InvalidPublicKeyLength, `Invalid public key length: ${identityKeyBytes.length}`);\n }\n\n return identityKeyBytes;\n }\n\n /**\n * Encodes a DID DHT Identity Key into a DID identifier.\n *\n * This method first z-base-32 encodes the Identity Key. The resulting string is prefixed with\n * `did:dht:` to form the DID identifier.\n *\n * @param params - The parameters to use for the conversion.\n * @param params.identityKey The Identity Key from which the DID identifier is computed.\n * @returns A promise that resolves to a string containing the DID identifier.\n */\n public static async identityKeyToIdentifier({ identityKey }: {\n identityKey: Jwk\n }): Promise<string> {\n // Convert the key from JWK format to a byte array.\n const publicKeyBytes = await Ed25519.publicKeyToBytes({ publicKey: identityKey });\n\n // Encode the byte array as a z-base-32 string.\n const identifier = Convert.uint8Array(publicKeyBytes).toBase32Z();\n\n return `did:${DidDht.methodName}:${identifier}`;\n }\n\n /**\n * Returns the appropriate key converter for the specified cryptographic curve.\n *\n * @param curve - The cryptographic curve to use for the key conversion.\n * @returns An `AsymmetricKeyConverter` for the specified curve.\n */\n public static keyConverter(curve: string): AsymmetricKeyConverter {\n const converters: Record<string, AsymmetricKeyConverter> = {\n 'Ed25519' : Ed25519,\n 'P-256' : {\n // Wrap the key converter which produces uncompressed public key bytes to produce compressed key bytes as required by the DID DHT spec.\n // See https://did-dht.com/#representing-keys for more info.\n publicKeyToBytes: async ({ publicKey }: { publicKey: Jwk }): Promise<Uint8Array> => {\n const publicKeyBytes = await Secp256r1.publicKeyToBytes({ publicKey });\n const compressedPublicKey = await Secp256r1.compressPublicKey({ publicKeyBytes });\n return compressedPublicKey;\n },\n bytesToPublicKey : Secp256r1.bytesToPublicKey,\n privateKeyToBytes : Secp256r1.privateKeyToBytes,\n bytesToPrivateKey : Secp256r1.bytesToPrivateKey,\n },\n 'secp256k1': {\n // Wrap the key converter which produces uncompressed public key bytes to produce compressed key bytes as required by the DID DHT spec.\n // See https://did-dht.com/#representing-keys for more info.\n publicKeyToBytes: async ({ publicKey }: { publicKey: Jwk }): Promise<Uint8Array> => {\n const publicKeyBytes = await Secp256k1.publicKeyToBytes({ publicKey });\n const compressedPublicKey = await Secp256k1.compressPublicKey({ publicKeyBytes });\n return compressedPublicKey;\n },\n bytesToPublicKey : Secp256k1.bytesToPublicKey,\n privateKeyToBytes : Secp256k1.privateKeyToBytes,\n bytesToPrivateKey : Secp256k1.bytesToPrivateKey,\n },\n X25519: X25519,\n };\n\n const converter = converters[curve];\n\n if (!converter) {throw new DidError(DidErrorCode.InvalidPublicKeyType, `Unsupported curve: ${curve}`);}\n\n return converter;\n }\n\n /**\n * Parses and verifies a BEP44 Get message, converting it to a DNS packet.\n *\n * @param params - The parameters to use when verifying and parsing the BEP44 Get response message.\n * @param params.bep44Message - The BEP44 message to verify and parse.\n * @returns A promise that resolves to a DNS packet.\n */\n public static async parseBep44GetMessage({ bep44Message }: {\n bep44Message: Bep44Message;\n }): Promise<Packet> {\n // Convert the public key byte array to JWK format.\n const publicKey = await Ed25519.bytesToPublicKey({ publicKeyBytes: bep44Message.k });\n\n // Encode the sequence and DNS byte array to bencode format.\n const bencodedData = bencode.encode({ seq: bep44Message.seq, v: bep44Message.v }).subarray(1, -1);\n\n // Verify the signature of the BEP44 message.\n const isValid = await Ed25519.verify({\n key : publicKey,\n signature : bep44Message.sig,\n data : bencodedData\n });\n\n if (!isValid) {\n throw new DidError(DidErrorCode.InvalidSignature, `Invalid signature for DHT BEP44 message`);\n }\n\n return dnsPacketDecode(bep44Message.v);\n }\n\n /**\n * Decodes and parses the data value of a DNS TXT record into a key-value object.\n *\n * @param txtData - The data value of a DNS TXT record.\n * @returns An object containing the key/value pairs of the TXT record data.\n */\n public static parseTxtDataToObject(txtData: TxtData): Record<string, string> {\n return this.parseTxtDataToString(txtData).split(PROPERTY_SEPARATOR).reduce((acc, pair) => {\n const [key, value] = pair.split('=');\n acc[key] = value;\n return acc;\n }, {} as Record<string, string>);\n }\n\n /**\n * Decodes and parses the data value of a DNS TXT record into a string.\n *\n * @param txtData - The data value of a DNS TXT record.\n * @returns A string representation of the TXT record data.\n */\n public static parseTxtDataToString(txtData: TxtData): string {\n if (typeof txtData === 'string') {\n return txtData;\n } else if (txtData instanceof Uint8Array) {\n return Convert.uint8Array(txtData).toString();\n } else if (Array.isArray(txtData)) {\n return txtData.map(item => this.parseTxtDataToString(item)).join('');\n } else {\n throw new DidError(DidErrorCode.InternalError, 'Pkarr returned DNS TXT record with invalid data type');\n }\n }\n\n /**\n * Validates the proof of previous DID given.\n *\n * @param params - The parameters to validate the previous DID proof.\n * @param params.newDid - The new DID that the previous DID is linking to.\n * @param params.previousDidProof - The proof of the previous DID, containing the previous DID and signature signed by the previous DID.\n */\n public static async validatePreviousDidProof({ newDid, previousDidProof }: {\n newDid: string,\n previousDidProof: PreviousDidProof,\n }): Promise<void> {\n const key = await DidDhtUtils.identifierToIdentityKey({ didUri: previousDidProof.previousDid });\n const data = DidDhtUtils.identifierToIdentityKeyBytes({ didUri: newDid });\n const signature = Convert.base64Url(previousDidProof.signature).toUint8Array();\n const isValid = await Ed25519.verify({ key, data, signature });\n\n if (!isValid) {\n throw new DidError(DidErrorCode.InvalidPreviousDidProof, 'The previous DID proof is invalid.');\n }\n }\n\n /**\n * Splits a string into chunks of length 255 if the string exceeds length 255.\n * @param data - The string to split into chunks.\n * @returns The original string if its length is less than or equal to 255, otherwise an array of chunked strings.\n */\n public static chunkDataIfNeeded(data: string): string | string[] {\n if (data.length <= 255) {\n return data;\n }\n\n // Split the data into chunks of 255 characters.\n const chunks: string[] = [];\n for (let i = 0; i < data.length; i += 255) {\n chunks.push(data.slice(i, i + 255)); // end index is ignored if it exceeds the length of the string\n }\n\n return chunks;\n }\n}", "import encode from './lib/encode.js'\nimport decode from './lib/decode.js'\nimport byteLength from './lib/encoding-length.js'\n/**\n * Determines the amount of bytes\n * needed to encode the given value\n * @param {Object|Array|Uint8Array|String|Number|Boolean} value\n * @return {Number} byteCount\n */\nconst encodingLength = byteLength\nexport default { encode, decode, byteLength, encodingLength }\n", "import { concat, text2arr } from 'uint8-util'\nimport { getType } from './util.js'\n\n/**\n * Encodes data in bencode.\n *\n * @param {Uint8Array|Array|String|Object|Number|Boolean} data\n * @return {Uint8Array}\n */\nfunction encode (data, buffer, offset) {\n const buffers = []\n let result = null\n\n encode._encode(buffers, data)\n result = concat(buffers)\n encode.bytes = result.length\n\n if (ArrayBuffer.isView(buffer)) {\n buffer.set(result, offset)\n return buffer\n }\n\n return result\n}\n\nencode.bytes = -1\nencode._floatConversionDetected = false\n\nencode._encode = function (buffers, data) {\n if (data == null) { return }\n\n switch (getType(data)) {\n case 'object': encode.dict(buffers, data); break\n case 'map': encode.dictMap(buffers, data); break\n case 'array': encode.list(buffers, data); break\n case 'set': encode.listSet(buffers, data); break\n case 'string': encode.string(buffers, data); break\n case 'number': encode.number(buffers, data); break\n case 'boolean': encode.number(buffers, data); break\n case 'arraybufferview': encode.buffer(buffers, new Uint8Array(data.buffer, data.byteOffset, data.byteLength)); break\n case 'arraybuffer': encode.buffer(buffers, new Uint8Array(data)); break\n }\n}\n\nconst buffE = new Uint8Array([0x65])\nconst buffD = new Uint8Array([0x64])\nconst buffL = new Uint8Array([0x6C])\n\nencode.buffer = function (buffers, data) {\n buffers.push(text2arr(data.length + ':'), data)\n}\n\nencode.string = function (buffers, data) {\n buffers.push(text2arr(text2arr(data).byteLength + ':' + data))\n}\n\nencode.number = function (buffers, data) {\n if (Number.isInteger(data)) return buffers.push(text2arr('i' + BigInt(data) + 'e'))\n\n const maxLo = 0x80000000\n const hi = (data / maxLo) << 0\n const lo = (data % maxLo) << 0\n const val = hi * maxLo + lo\n\n buffers.push(text2arr('i' + val + 'e'))\n\n if (val !== data && !encode._floatConversionDetected) {\n encode._floatConversionDetected = true\n console.warn(\n 'WARNING: Possible data corruption detected with value \"' + data + '\":',\n 'Bencoding only defines support for integers, value was converted to \"' + val + '\"'\n )\n console.trace()\n }\n}\n\nencode.dict = function (buffers, data) {\n buffers.push(buffD)\n\n let j = 0\n let k\n // fix for issue #13 - sorted dicts\n const keys = Object.keys(data).sort()\n const kl = keys.length\n\n for (; j < kl; j++) {\n k = keys[j]\n if (data[k] == null) continue\n encode.string(buffers, k)\n encode._encode(buffers, data[k])\n }\n\n buffers.push(buffE)\n}\n\nencode.dictMap = function (buffers, data) {\n buffers.push(buffD)\n\n const keys = Array.from(data.keys()).sort()\n\n for (const key of keys) {\n if (data.get(key) == null) continue\n ArrayBuffer.isView(key)\n ? encode._encode(buffers, key)\n : encode.string(buffers, String(key))\n encode._encode(buffers, data.get(key))\n }\n\n buffers.push(buffE)\n}\n\nencode.list = function (buffers, data) {\n let i = 0\n const c = data.length\n buffers.push(buffL)\n\n for (; i < c; i++) {\n if (data[i] == null) continue\n encode._encode(buffers, data[i])\n }\n\n buffers.push(buffE)\n}\n\nencode.listSet = function (buffers, data) {\n buffers.push(buffL)\n\n for (const item of data) {\n if (item == null) continue\n encode._encode(buffers, item)\n }\n\n buffers.push(buffE)\n}\n\nexport default encode\n", "import { arr2hex, hex2arr, alphabet } from './util.js'\r\nimport { decode, encode } from 'base64-arraybuffer'\r\n\r\nconst decoder = new TextDecoder()\r\n// 50% slower at < 48 chars, but little impact at 4M OPS/s vs 8M OPS/s\r\nexport const arr2text = (data, enc) => {\r\n if (!enc) return decoder.decode(data)\r\n const dec = new TextDecoder(enc)\r\n return dec.decode(data)\r\n}\r\n\r\n// sacrifice ~20% speed for bundle size\r\nconst encoder = new TextEncoder()\r\nexport const text2arr = str => encoder.encode(str)\r\n\r\nexport const arr2base = data => encode(data)\r\n\r\nexport const base2arr = str => new Uint8Array(decode(str))\r\n\r\nexport const bin2hex = str => {\r\n let res = ''\r\n let c\r\n let i = 0\r\n const len = str.length\r\n\r\n while (i < len) {\r\n c = str.charCodeAt(i++)\r\n res += alphabet[c >> 4] + alphabet[c & 0xF]\r\n }\r\n\r\n return res\r\n}\r\n\r\nconst MAX_ARGUMENTS_LENGTH = 0x10000\r\nexport const hex2bin = hex => {\r\n const points = hex2arr(hex)\r\n if (points.length <= MAX_ARGUMENTS_LENGTH) return String.fromCharCode(...points)\r\n\r\n let res = ''\r\n let i = 0\r\n while (i < points.length) {\r\n res += String.fromCharCode(...points.subarray(i, i += MAX_ARGUMENTS_LENGTH))\r\n }\r\n return res\r\n}\r\n\r\nconst scope = typeof window !== 'undefined' ? window : self\r\nconst crypto = scope.crypto || scope.msCrypto || {}\r\nconst subtle = crypto.subtle || crypto.webkitSubtle\r\n\r\nconst formatMap = {\r\n hex: arr2hex,\r\n base64: arr2base\r\n}\r\n\r\nexport const hash = async (data, format, algo = 'sha-1') => {\r\n if (!subtle) throw new Error('no web crypto support')\r\n if (typeof data === 'string') data = text2arr(data)\r\n const out = new Uint8Array(await subtle.digest(algo, data))\r\n return format ? formatMap[format](out) : out\r\n}\r\n\r\nexport const randomBytes = size => {\r\n const view = new Uint8Array(size)\r\n return crypto.getRandomValues(view)\r\n}\r\n\r\nexport * from './util.js'\r\n", "/* Common package for dealing with hex/string/uint8 conversions (and sha1 hashing)\r\n*\r\n* @author Jimmy W\u00E4rting <jimmy@warting.se> (https://jimmy.warting.se/opensource)\r\n* @license MIT\r\n*/\r\nexport const alphabet = '0123456789abcdef'\r\nconst encodeLookup = []\r\nconst decodeLookup = []\r\n\r\nfor (let i = 0; i < 256; i++) {\r\n encodeLookup[i] = alphabet[i >> 4 & 0xf] + alphabet[i & 0xf]\r\n if (i < 16) {\r\n if (i < 10) {\r\n decodeLookup[0x30 + i] = i\r\n } else {\r\n decodeLookup[0x61 - 10 + i] = i\r\n }\r\n }\r\n}\r\n\r\nexport const arr2hex = data => {\r\n const length = data.length\r\n let string = ''\r\n let i = 0\r\n while (i < length) {\r\n string += encodeLookup[data[i++]]\r\n }\r\n return string\r\n}\r\n\r\nexport const hex2arr = str => {\r\n const sizeof = str.length >> 1\r\n const length = sizeof << 1\r\n const array = new Uint8Array(sizeof)\r\n let n = 0\r\n let i = 0\r\n while (i < length) {\r\n array[n++] = decodeLookup[str.charCodeAt(i++)] << 4 | decodeLookup[str.charCodeAt(i++)]\r\n }\r\n return array\r\n}\r\n\r\nexport const concat = (chunks, size = 0) => {\r\n const length = chunks.length || 0\r\n if (!size) {\r\n let i = length\r\n while (i--) size += chunks[i].length\r\n }\r\n const b = new Uint8Array(size)\r\n let offset = size\r\n let i = length\r\n while (i--) {\r\n offset -= chunks[i].length\r\n b.set(chunks[i], offset)\r\n }\r\n\r\n return b\r\n}\r\n\r\nexport const equal = (a, b) => {\r\n if (a.length !== b.length) return false\r\n for (let i = a.length; i > -1; i -= 1) {\r\n if ((a[i] !== b[i])) return false\r\n }\r\n return true\r\n}\r\n", "const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n\n// Use a lookup table to find the index.\nconst lookup = typeof Uint8Array === 'undefined' ? [] : new Uint8Array(256);\nfor (let i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n}\n\nexport const encode = (arraybuffer: ArrayBuffer): string => {\n let bytes = new Uint8Array(arraybuffer),\n i,\n len = bytes.length,\n base64 = '';\n\n for (i = 0; i < len; i += 3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n\n if (len % 3 === 2) {\n base64 = base64.substring(0, base64.length - 1) + '=';\n } else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + '==';\n }\n\n return base64;\n};\n\nexport const decode = (base64: string): ArrayBuffer => {\n let bufferLength = base64.length * 0.75,\n len = base64.length,\n i,\n p = 0,\n encoded1,\n encoded2,\n encoded3,\n encoded4;\n\n if (base64[base64.length - 1] === '=') {\n bufferLength--;\n if (base64[base64.length - 2] === '=') {\n bufferLength--;\n }\n }\n\n const arraybuffer = new ArrayBuffer(bufferLength),\n bytes = new Uint8Array(arraybuffer);\n\n for (i = 0; i < len; i += 4) {\n encoded1 = lookup[base64.charCodeAt(i)];\n encoded2 = lookup[base64.charCodeAt(i + 1)];\n encoded3 = lookup[base64.charCodeAt(i + 2)];\n encoded4 = lookup[base64.charCodeAt(i + 3)];\n\n bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n }\n\n return arraybuffer;\n};\n", "export function digitCount (value) {\n // Add a digit for negative numbers, as the sign will be prefixed\n const sign = value < 0 ? 1 : 0\n // Guard against negative numbers & zero going into log10(),\n // as that would return -Infinity\n value = Math.abs(Number(value || 1))\n return Math.floor(Math.log10(value)) + 1 + sign\n}\n\nexport function getType (value) {\n if (ArrayBuffer.isView(value)) return 'arraybufferview'\n if (Array.isArray(value)) return 'array'\n if (value instanceof Number) return 'number'\n if (value instanceof Boolean) return 'boolean'\n if (value instanceof Set) return 'set'\n if (value instanceof Map) return 'map'\n if (value instanceof String) return 'string'\n if (value instanceof ArrayBuffer) return 'arraybuffer'\n return typeof value\n}\n", "import { arr2text, text2arr, arr2hex } from 'uint8-util'\n\nconst INTEGER_START = 0x69 // 'i'\nconst STRING_DELIM = 0x3A // ':'\nconst DICTIONARY_START = 0x64 // 'd'\nconst LIST_START = 0x6C // 'l'\nconst END_OF_TYPE = 0x65 // 'e'\n\n/**\n * replaces parseInt(buffer.toString('ascii', start, end)).\n * For strings with less then ~30 charachters, this is actually a lot faster.\n *\n * @param {Uint8Array} data\n * @param {Number} start\n * @param {Number} end\n * @return {Number} calculated number\n */\nfunction getIntFromBuffer (buffer, start, end) {\n let sum = 0\n let sign = 1\n\n for (let i = start; i < end; i++) {\n const num = buffer[i]\n\n if (num < 58 && num >= 48) {\n sum = sum * 10 + (num - 48)\n continue\n }\n\n if (i === start && num === 43) { // +\n continue\n }\n\n if (i === start && num === 45) { // -\n sign = -1\n continue\n }\n\n if (num === 46) { // .\n // its a float. break here.\n break\n }\n\n throw new Error('not a number: buffer[' + i + '] = ' + num)\n }\n\n return sum * sign\n}\n\n/**\n * Decodes bencoded data.\n *\n * @param {Uint8Array} data\n * @param {Number} start (optional)\n * @param {Number} end (optional)\n * @param {String} encoding (optional)\n * @return {Object|Array|Uint8Array|String|Number}\n */\nfunction decode (data, start, end, encoding) {\n if (data == null || data.length === 0) {\n return null\n }\n\n if (typeof start !== 'number' && encoding == null) {\n encoding = start\n start = undefined\n }\n\n if (typeof end !== 'number' && encoding == null) {\n encoding = end\n end = undefined\n }\n\n decode.position = 0\n decode.encoding = encoding || null\n\n decode.data = !(ArrayBuffer.isView(data))\n ? text2arr(data)\n : new Uint8Array(data.slice(start, end))\n\n decode.bytes = decode.data.length\n\n return decode.next()\n}\n\ndecode.bytes = 0\ndecode.position = 0\ndecode.data = null\ndecode.encoding = null\n\ndecode.next = function () {\n switch (decode.data[decode.position]) {\n case DICTIONARY_START:\n return decode.dictionary()\n case LIST_START:\n return decode.list()\n case INTEGER_START:\n return decode.integer()\n default:\n return decode.buffer()\n }\n}\n\ndecode.find = function (chr) {\n let i = decode.position\n const c = decode.data.length\n const d = decode.data\n\n while (i < c) {\n if (d[i] === chr) return i\n i++\n }\n\n throw new Error(\n 'Invalid data: Missing delimiter \"' +\n String.fromCharCode(chr) + '\" [0x' +\n chr.toString(16) + ']'\n )\n}\n\ndecode.dictionary = function () {\n decode.position++\n\n const dict = {}\n\n while (decode.data[decode.position] !== END_OF_TYPE) {\n const buffer = decode.buffer()\n let key = arr2text(buffer)\n if (key.includes('\\uFFFD')) key = arr2hex(buffer)\n dict[key] = decode.next()\n }\n\n decode.position++\n\n return dict\n}\n\ndecode.list = function () {\n decode.position++\n\n const lst = []\n\n while (decode.data[decode.position] !== END_OF_TYPE) {\n lst.push(decode.next())\n }\n\n decode.position++\n\n return lst\n}\n\ndecode.integer = function () {\n const end = decode.find(END_OF_TYPE)\n const number = getIntFromBuffer(decode.data, decode.position + 1, end)\n\n decode.position += end + 1 - decode.position\n\n return number\n}\n\ndecode.buffer = function () {\n let sep = decode.find(STRING_DELIM)\n const length = getIntFromBuffer(decode.data, decode.position, sep)\n const end = ++sep + length\n\n decode.position = end\n\n return decode.encoding\n ? arr2text(decode.data.slice(sep, end))\n : decode.data.slice(sep, end)\n}\n\nexport default decode\n", "import { text2arr } from 'uint8-util'\nimport { digitCount, getType } from './util.js'\n\nfunction listLength (list) {\n let length = 1 + 1 // type marker + end-of-type marker\n\n for (const value of list) {\n length += encodingLength(value)\n }\n\n return length\n}\n\nfunction mapLength (map) {\n let length = 1 + 1 // type marker + end-of-type marker\n\n for (const [key, value] of map) {\n const keyLength = text2arr(key).byteLength\n length += digitCount(keyLength) + 1 + keyLength\n length += encodingLength(value)\n }\n\n return length\n}\n\nfunction objectLength (value) {\n let length = 1 + 1 // type marker + end-of-type marker\n const keys = Object.keys(value)\n\n for (let i = 0; i < keys.length; i++) {\n const keyLength = text2arr(keys[i]).byteLength\n length += digitCount(keyLength) + 1 + keyLength\n length += encodingLength(value[keys[i]])\n }\n\n return length\n}\n\nfunction stringLength (value) {\n const length = text2arr(value).byteLength\n return digitCount(length) + 1 + length\n}\n\nfunction arrayBufferLength (value) {\n const length = value.byteLength - value.byteOffset\n return digitCount(length) + 1 + length\n}\n\nfunction encodingLength (value) {\n const length = 0\n\n if (value == null) return length\n\n const type = getType(value)\n\n switch (type) {\n case 'arraybufferview': return arrayBufferLength(value)\n case 'string': return stringLength(value)\n case 'array': case 'set': return listLength(value)\n case 'number': return 1 + digitCount(Math.floor(value)) + 1\n case 'bigint': return 1 + value.toString().length + 1\n case 'object': return objectLength(value)\n case 'map': return mapLength(value)\n default:\n throw new TypeError(`Unsupported value of type \"${type}\"`)\n }\n}\n\nexport default encodingLength\n", "import * as ip from '@leichtgewicht/ip-codec'\nimport * as types from './types.mjs'\nimport * as rcodes from './rcodes.mjs'\nimport * as opcodes from './opcodes.mjs'\nimport * as classes from './classes.mjs'\nimport * as optioncodes from './optioncodes.mjs'\nimport * as b from './buffer_utils.mjs'\nimport { decode as toUtf8 } from 'utf8-codec'\n\nconst QUERY_FLAG = 0\nconst RESPONSE_FLAG = 1 << 15\nconst FLUSH_MASK = 1 << 15\nconst NOT_FLUSH_MASK = ~FLUSH_MASK\nconst QU_MASK = 1 << 15\nconst NOT_QU_MASK = ~QU_MASK\n\nfunction codec ({ bytes = 0, encode, decode, encodingLength }) {\n encode.bytes = bytes\n decode.bytes = bytes\n return {\n encode,\n decode,\n encodingLength: encodingLength || (() => bytes)\n }\n}\n\nexport const name = codec({\n encode (str, buf, offset) {\n if (!buf) buf = new Uint8Array(name.encodingLength(str))\n if (!offset) offset = 0\n const oldOffset = offset\n\n // strip leading and trailing .\n const n = str.replace(/^\\.|\\.$/gm, '')\n if (n.length) {\n const list = n.split('.')\n\n for (let i = 0; i < list.length; i++) {\n const len = b.write(buf, list[i], offset + 1)\n buf[offset] = len\n offset += len + 1\n }\n }\n\n buf[offset++] = 0\n\n name.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const list = []\n let oldOffset = offset\n let totalLength = 0\n let consumedBytes = 0\n let jumped = false\n\n while (true) {\n if (offset >= buf.length) {\n throw new Error('Cannot decode name (buffer overflow)')\n }\n const len = buf[offset++]\n consumedBytes += jumped ? 0 : 1\n\n if (len === 0) {\n break\n } else if ((len & 0xc0) === 0) {\n if (offset + len > buf.length) {\n throw new Error('Cannot decode name (buffer overflow)')\n }\n totalLength += len + 1\n if (totalLength > 254) {\n throw new Error('Cannot decode name (name too long)')\n }\n list.push(toUtf8(buf, offset, offset + len))\n offset += len\n consumedBytes += jumped ? 0 : len\n } else if ((len & 0xc0) === 0xc0) {\n if (offset + 1 > buf.length) {\n throw new Error('Cannot decode name (buffer overflow)')\n }\n const jumpOffset = b.readUInt16BE(buf, offset - 1) - 0xc000\n if (jumpOffset >= oldOffset) {\n // Allow only pointers to prior data. RFC 1035, section 4.1.4 states:\n // \"[...] an entire domain name or a list of labels at the end of a domain name\n // is replaced with a pointer to a prior occurance (sic) of the same name.\"\n throw new Error('Cannot decode name (bad pointer)')\n }\n offset = jumpOffset\n oldOffset = jumpOffset\n consumedBytes += jumped ? 0 : 1\n jumped = true\n } else {\n throw new Error('Cannot decode name (bad label)')\n }\n }\n\n name.decode.bytes = consumedBytes\n return list.length === 0 ? '.' : list.join('.')\n },\n encodingLength (n) {\n if (n === '.' || n === '..') return 1\n return b.bytelength(n.replace(/^\\.|\\.$/gm, '')) + 2\n }\n})\n\nconst string = codec({\n encode (s, buf, offset) {\n if (!buf) buf = new Uint8Array(string.encodingLength(s))\n if (!offset) offset = 0\n\n const len = b.write(buf, s, offset + 1)\n buf[offset] = len\n string.encode.bytes = len + 1\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = buf[offset]\n const s = toUtf8(buf, offset + 1, offset + 1 + len)\n string.decode.bytes = len + 1\n return s\n },\n encodingLength (s) {\n return b.bytelength(s) + 1\n }\n})\n\nconst header = codec({\n bytes: 12,\n encode (h, buf, offset) {\n if (!buf) buf = new Uint8Array(header.encodingLength(h))\n if (!offset) offset = 0\n\n const flags = (h.flags || 0) & 32767\n const type = h.type === 'response' ? RESPONSE_FLAG : QUERY_FLAG\n\n b.writeUInt16BE(buf, h.id || 0, offset)\n b.writeUInt16BE(buf, flags | type, offset + 2)\n b.writeUInt16BE(buf, h.questions.length, offset + 4)\n b.writeUInt16BE(buf, h.answers.length, offset + 6)\n b.writeUInt16BE(buf, h.authorities.length, offset + 8)\n b.writeUInt16BE(buf, h.additionals.length, offset + 10)\n\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n if (buf.length < 12) throw new Error('Header must be 12 bytes')\n const flags = b.readUInt16BE(buf, offset + 2)\n\n return {\n id: b.readUInt16BE(buf, offset),\n type: flags & RESPONSE_FLAG ? 'response' : 'query',\n flags: flags & 32767,\n flag_qr: ((flags >> 15) & 0x1) === 1,\n opcode: opcodes.toString((flags >> 11) & 0xf),\n flag_aa: ((flags >> 10) & 0x1) === 1,\n flag_tc: ((flags >> 9) & 0x1) === 1,\n flag_rd: ((flags >> 8) & 0x1) === 1,\n flag_ra: ((flags >> 7) & 0x1) === 1,\n flag_z: ((flags >> 6) & 0x1) === 1,\n flag_ad: ((flags >> 5) & 0x1) === 1,\n flag_cd: ((flags >> 4) & 0x1) === 1,\n rcode: rcodes.toString(flags & 0xf),\n questions: new Array(b.readUInt16BE(buf, offset + 4)),\n answers: new Array(b.readUInt16BE(buf, offset + 6)),\n authorities: new Array(b.readUInt16BE(buf, offset + 8)),\n additionals: new Array(b.readUInt16BE(buf, offset + 10))\n }\n },\n encodingLength () {\n return 12\n }\n})\n\nconst runknown = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(runknown.encodingLength(data))\n if (!offset) offset = 0\n\n const dLen = data.length\n b.writeUInt16BE(buf, dLen, offset)\n b.copy(data, buf, offset + 2, 0, dLen)\n\n runknown.encode.bytes = dLen + 2\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = b.readUInt16BE(buf, offset)\n const data = buf.slice(offset + 2, offset + 2 + len)\n runknown.decode.bytes = len + 2\n return data\n },\n encodingLength (data) {\n return data.length + 2\n }\n})\n\nconst rns = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rns.encodingLength(data))\n if (!offset) offset = 0\n\n name.encode(data, buf, offset + 2)\n b.writeUInt16BE(buf, name.encode.bytes, offset)\n rns.encode.bytes = name.encode.bytes + 2\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = b.readUInt16BE(buf, offset)\n const dd = name.decode(buf, offset + 2)\n\n rns.decode.bytes = len + 2\n return dd\n },\n encodingLength (data) {\n return name.encodingLength(data) + 2\n }\n})\n\nconst rsoa = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rsoa.encodingLength(data))\n if (!offset) offset = 0\n\n const oldOffset = offset\n offset += 2\n name.encode(data.mname, buf, offset)\n offset += name.encode.bytes\n name.encode(data.rname, buf, offset)\n offset += name.encode.bytes\n b.writeUInt32BE(buf, data.serial || 0, offset)\n offset += 4\n b.writeUInt32BE(buf, data.refresh || 0, offset)\n offset += 4\n b.writeUInt32BE(buf, data.retry || 0, offset)\n offset += 4\n b.writeUInt32BE(buf, data.expire || 0, offset)\n offset += 4\n b.writeUInt32BE(buf, data.minimum || 0, offset)\n offset += 4\n\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rsoa.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n const data = {}\n offset += 2\n data.mname = name.decode(buf, offset)\n offset += name.decode.bytes\n data.rname = name.decode(buf, offset)\n offset += name.decode.bytes\n data.serial = b.readUInt32BE(buf, offset)\n offset += 4\n data.refresh = b.readUInt32BE(buf, offset)\n offset += 4\n data.retry = b.readUInt32BE(buf, offset)\n offset += 4\n data.expire = b.readUInt32BE(buf, offset)\n offset += 4\n data.minimum = b.readUInt32BE(buf, offset)\n offset += 4\n\n rsoa.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n return 22 + name.encodingLength(data.mname) + name.encodingLength(data.rname)\n }\n})\n\nconst rtxt = codec({\n encode (data, buf, offset) {\n if (!Array.isArray(data)) data = [data]\n for (let i = 0; i < data.length; i++) {\n if (typeof data[i] === 'string') {\n data[i] = b.from(data[i])\n }\n if (!b.isU8Arr(data[i])) {\n throw new Error('Must be a Buffer')\n }\n }\n\n if (!buf) buf = new Uint8Array(rtxt.encodingLength(data))\n if (!offset) offset = 0\n\n const oldOffset = offset\n offset += 2\n\n data.forEach(function (d) {\n buf[offset++] = d.length\n b.copy(d, buf, offset, 0, d.length)\n offset += d.length\n })\n\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rtxt.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n let remaining = b.readUInt16BE(buf, offset)\n offset += 2\n\n const data = []\n while (remaining > 0) {\n const len = buf[offset++]\n --remaining\n if (remaining < len) {\n throw new Error('Buffer overflow')\n }\n data.push(buf.slice(offset, offset + len))\n offset += len\n remaining -= len\n }\n\n rtxt.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n if (!Array.isArray(data)) data = [data]\n let length = 2\n data.forEach(function (buf) {\n if (typeof buf === 'string') {\n length += b.bytelength(buf) + 1\n } else {\n length += buf.length + 1\n }\n })\n return length\n }\n})\n\nconst rnull = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rnull.encodingLength(data))\n if (!offset) offset = 0\n\n if (typeof data === 'string') data = b.from(data)\n if (!data) data = new Uint8Array(0)\n\n const oldOffset = offset\n offset += 2\n\n const len = data.length\n b.copy(data, buf, offset, 0, len)\n offset += len\n\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rnull.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n const len = b.readUInt16BE(buf, offset)\n\n offset += 2\n\n const data = buf.slice(offset, offset + len)\n offset += len\n\n rnull.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n if (!data) return 2\n return (b.isU8Arr(data) ? data.length : b.bytelength(data)) + 2\n }\n})\n\nconst rhinfo = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rhinfo.encodingLength(data))\n if (!offset) offset = 0\n\n const oldOffset = offset\n offset += 2\n string.encode(data.cpu, buf, offset)\n offset += string.encode.bytes\n string.encode(data.os, buf, offset)\n offset += string.encode.bytes\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rhinfo.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n const data = {}\n offset += 2\n data.cpu = string.decode(buf, offset)\n offset += string.decode.bytes\n data.os = string.decode(buf, offset)\n offset += string.decode.bytes\n rhinfo.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n return string.encodingLength(data.cpu) + string.encodingLength(data.os) + 2\n }\n})\n\nconst rptr = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rptr.encodingLength(data))\n if (!offset) offset = 0\n\n name.encode(data, buf, offset + 2)\n b.writeUInt16BE(buf, name.encode.bytes, offset)\n rptr.encode.bytes = name.encode.bytes + 2\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const data = name.decode(buf, offset + 2)\n rptr.decode.bytes = name.decode.bytes + 2\n return data\n },\n encodingLength (data) {\n return name.encodingLength(data) + 2\n }\n})\n\nconst rsrv = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rsrv.encodingLength(data))\n if (!offset) offset = 0\n\n b.writeUInt16BE(buf, data.priority || 0, offset + 2)\n b.writeUInt16BE(buf, data.weight || 0, offset + 4)\n b.writeUInt16BE(buf, data.port || 0, offset + 6)\n name.encode(data.target, buf, offset + 8)\n\n const len = name.encode.bytes + 6\n b.writeUInt16BE(buf, len, offset)\n\n rsrv.encode.bytes = len + 2\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = b.readUInt16BE(buf, offset)\n\n const data = {}\n data.priority = b.readUInt16BE(buf, offset + 2)\n data.weight = b.readUInt16BE(buf, offset + 4)\n data.port = b.readUInt16BE(buf, offset + 6)\n data.target = name.decode(buf, offset + 8)\n\n rsrv.decode.bytes = len + 2\n return data\n },\n encodingLength (data) {\n return 8 + name.encodingLength(data.target)\n }\n})\n\nconst rcaa = codec({\n encode (data, buf, offset) {\n const len = rcaa.encodingLength(data)\n\n if (!buf) buf = new Uint8Array(rcaa.encodingLength(data))\n if (!offset) offset = 0\n\n if (data.issuerCritical) {\n data.flags = rcaa.ISSUER_CRITICAL\n }\n\n b.writeUInt16BE(buf, len - 2, offset)\n offset += 2\n buf[offset] = data.flags || 0\n offset += 1\n string.encode(data.tag, buf, offset)\n offset += string.encode.bytes\n b.write(buf, data.value, offset)\n offset += b.bytelength(data.value)\n\n rcaa.encode.bytes = len\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const len = b.readUInt16BE(buf, offset)\n offset += 2\n\n const oldOffset = offset\n const data = {}\n data.flags = buf[offset]\n offset += 1\n data.tag = string.decode(buf, offset)\n offset += string.decode.bytes\n data.value = toUtf8(buf, offset, oldOffset + len)\n\n data.issuerCritical = !!(data.flags & rcaa.ISSUER_CRITICAL)\n\n rcaa.decode.bytes = len + 2\n\n return data\n },\n encodingLength (data) {\n return string.encodingLength(data.tag) + string.encodingLength(data.value) + 2\n }\n})\n\nrcaa.ISSUER_CRITICAL = 1 << 7\n\nconst rmx = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rmx.encodingLength(data))\n if (!offset) offset = 0\n\n const oldOffset = offset\n offset += 2\n b.writeUInt16BE(buf, data.preference || 0, offset)\n offset += 2\n name.encode(data.exchange, buf, offset)\n offset += name.encode.bytes\n\n b.writeUInt16BE(buf, offset - oldOffset - 2, oldOffset)\n rmx.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n const data = {}\n offset += 2\n data.preference = b.readUInt16BE(buf, offset)\n offset += 2\n data.exchange = name.decode(buf, offset)\n offset += name.decode.bytes\n\n rmx.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n return 4 + name.encodingLength(data.exchange)\n }\n})\n\nconst ra = codec({\n encode (host, buf, offset) {\n if (!buf) buf = new Uint8Array(ra.encodingLength(host))\n if (!offset) offset = 0\n\n b.writeUInt16BE(buf, 4, offset)\n offset += 2\n ip.v4.encode(host, buf, offset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n offset += 2\n const host = ip.v4.decode(buf, offset)\n return host\n },\n bytes: 6\n})\n\nconst raaaa = codec({\n encode (host, buf, offset) {\n if (!buf) buf = new Uint8Array(raaaa.encodingLength(host))\n if (!offset) offset = 0\n\n b.writeUInt16BE(buf, 16, offset)\n offset += 2\n ip.v6.encode(host, buf, offset)\n raaaa.encode.bytes = 18\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n offset += 2\n const host = ip.v6.decode(buf, offset)\n raaaa.decode.bytes = 18\n return host\n },\n bytes: 18\n})\n\nconst alloc = size => new Uint8Array(size)\n\nconst roption = codec({\n encode (option, buf, offset) {\n if (!buf) buf = new Uint8Array(roption.encodingLength(option))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const code = optioncodes.toCode(option.code)\n b.writeUInt16BE(buf, code, offset)\n offset += 2\n if (option.data) {\n b.writeUInt16BE(buf, option.data.length, offset)\n offset += 2\n b.copy(option.data, buf, offset)\n offset += option.data.length\n } else {\n switch (code) {\n // case 3: NSID. No encode makes sense.\n // case 5,6,7: Not implementable\n case 8: // ECS\n {\n // note: do IP math before calling\n const spl = option.sourcePrefixLength || 0\n const fam = option.family || ip.familyOf(option.ip, alloc)\n const ipBuf = ip.encode(option.ip, alloc)\n const ipLen = Math.ceil(spl / 8)\n b.writeUInt16BE(buf, ipLen + 4, offset)\n offset += 2\n b.writeUInt16BE(buf, fam, offset)\n offset += 2\n buf[offset++] = spl\n buf[offset++] = option.scopePrefixLength || 0\n\n b.copy(ipBuf, buf, offset, 0, ipLen)\n offset += ipLen\n }\n break\n // case 9: EXPIRE (experimental)\n // case 10: COOKIE. No encode makes sense.\n case 11: // KEEP-ALIVE\n if (option.timeout) {\n b.writeUInt16BE(buf, 2, offset)\n offset += 2\n b.writeUInt16BE(buf, option.timeout, offset)\n offset += 2\n } else {\n b.writeUInt16BE(buf, 0, offset)\n offset += 2\n }\n break\n case 12: // PADDING\n {\n const len = option.length || 0\n b.writeUInt16BE(buf, len, offset)\n offset += 2\n buf.fill(0, offset, offset + len)\n offset += len\n }\n break\n // case 13: CHAIN. Experimental.\n case 14: // KEY-TAG\n {\n const tagsLen = option.tags.length * 2\n b.writeUInt16BE(buf, tagsLen, offset)\n offset += 2\n for (const tag of option.tags) {\n b.writeUInt16BE(buf, tag, offset)\n offset += 2\n }\n }\n break\n default:\n throw new Error(`Unknown roption code: ${option.code}`)\n }\n }\n\n roption.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const option = {}\n option.code = b.readUInt16BE(buf, offset)\n option.type = optioncodes.toString(option.code)\n offset += 2\n const len = b.readUInt16BE(buf, offset)\n offset += 2\n option.data = buf.slice(offset, offset + len)\n switch (option.code) {\n // case 3: NSID. No decode makes sense.\n case 8: // ECS\n option.family = b.readUInt16BE(buf, offset)\n offset += 2\n option.sourcePrefixLength = buf[offset++]\n option.scopePrefixLength = buf[offset++]\n {\n const padded = new Uint8Array((option.family === 1) ? 4 : 16)\n b.copy(buf, padded, 0, offset, offset + len - 4)\n option.ip = ip.decode(padded)\n }\n break\n // case 12: Padding. No decode makes sense.\n case 11: // KEEP-ALIVE\n if (len > 0) {\n option.timeout = b.readUInt16BE(buf, offset)\n offset += 2\n }\n break\n case 14:\n option.tags = []\n for (let i = 0; i < len; i += 2) {\n option.tags.push(b.readUInt16BE(buf, offset))\n offset += 2\n }\n // don't worry about default. caller will use data if desired\n }\n\n roption.decode.bytes = len + 4\n return option\n },\n encodingLength (option) {\n if (option.data) {\n return option.data.length + 4\n }\n const code = optioncodes.toCode(option.code)\n switch (code) {\n case 8: // ECS\n {\n const spl = option.sourcePrefixLength || 0\n return Math.ceil(spl / 8) + 8\n }\n case 11: // KEEP-ALIVE\n return (typeof option.timeout === 'number') ? 6 : 4\n case 12: // PADDING\n return option.length + 4\n case 14: // KEY-TAG\n return 4 + (option.tags.length * 2)\n }\n throw new Error(`Unknown roption code: ${option.code}`)\n }\n})\n\nconst ropt = codec({\n encode (options, buf, offset) {\n if (!buf) buf = new Uint8Array(ropt.encodingLength(options))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const rdlen = encodingLengthList(options, roption)\n b.writeUInt16BE(buf, rdlen, offset)\n offset = encodeList(options, roption, buf, offset + 2)\n\n ropt.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const options = []\n let rdlen = b.readUInt16BE(buf, offset)\n offset += 2\n let o = 0\n while (rdlen > 0) {\n options[o++] = roption.decode(buf, offset)\n offset += roption.decode.bytes\n rdlen -= roption.decode.bytes\n }\n ropt.decode.bytes = offset - oldOffset\n return options\n },\n encodingLength (options) {\n return 2 + encodingLengthList(options || [], roption)\n }\n})\n\nconst rdnskey = codec({\n encode (key, buf, offset) {\n if (!buf) buf = new Uint8Array(rdnskey.encodingLength(key))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const keydata = key.key\n if (!b.isU8Arr(keydata)) {\n throw new Error('Key must be a Buffer')\n }\n\n offset += 2 // Leave space for length\n b.writeUInt16BE(buf, key.flags, offset)\n offset += 2\n buf[offset] = rdnskey.PROTOCOL_DNSSEC\n offset += 1\n buf[offset] = key.algorithm\n offset += 1\n b.copy(keydata, buf, offset, 0, keydata.length)\n offset += keydata.length\n\n rdnskey.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rdnskey.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const key = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n key.flags = b.readUInt16BE(buf, offset)\n offset += 2\n if (buf[offset] !== rdnskey.PROTOCOL_DNSSEC) {\n throw new Error('Protocol must be 3')\n }\n offset += 1\n key.algorithm = buf[offset]\n offset += 1\n key.key = buf.slice(offset, oldOffset + length + 2)\n offset += key.key.length\n rdnskey.decode.bytes = offset - oldOffset\n return key\n },\n encodingLength (key) {\n return 6 + b.bytelength(key.key)\n }\n})\n\nrdnskey.PROTOCOL_DNSSEC = 3\nrdnskey.ZONE_KEY = 0x80\nrdnskey.SECURE_ENTRYPOINT = 0x8000\n\nconst rrrsig = codec({\n encode (sig, buf, offset) {\n if (!buf) buf = new Uint8Array(rrrsig.encodingLength(sig))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const signature = sig.signature\n if (!b.isU8Arr(signature)) {\n throw new Error('Signature must be a Buffer')\n }\n\n offset += 2 // Leave space for length\n b.writeUInt16BE(buf, types.toType(sig.typeCovered), offset)\n offset += 2\n buf[offset] = sig.algorithm\n offset += 1\n buf[offset] = sig.labels\n offset += 1\n b.writeUInt32BE(buf, sig.originalTTL, offset)\n offset += 4\n b.writeUInt32BE(buf, sig.expiration, offset)\n offset += 4\n b.writeUInt32BE(buf, sig.inception, offset)\n offset += 4\n b.writeUInt16BE(buf, sig.keyTag, offset)\n offset += 2\n name.encode(sig.signersName, buf, offset)\n offset += name.encode.bytes\n b.copy(signature, buf, offset, 0, signature.length)\n offset += signature.length\n\n rrrsig.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rrrsig.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const sig = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n sig.typeCovered = types.toString(b.readUInt16BE(buf, offset))\n offset += 2\n sig.algorithm = buf[offset]\n offset += 1\n sig.labels = buf[offset]\n offset += 1\n sig.originalTTL = b.readUInt32BE(buf, offset)\n offset += 4\n sig.expiration = b.readUInt32BE(buf, offset)\n offset += 4\n sig.inception = b.readUInt32BE(buf, offset)\n offset += 4\n sig.keyTag = b.readUInt16BE(buf, offset)\n offset += 2\n sig.signersName = name.decode(buf, offset)\n offset += name.decode.bytes\n sig.signature = buf.slice(offset, oldOffset + length + 2)\n offset += sig.signature.length\n rrrsig.decode.bytes = offset - oldOffset\n return sig\n },\n encodingLength (sig) {\n return 20 +\n name.encodingLength(sig.signersName) +\n b.bytelength(sig.signature)\n }\n})\nconst rrp = codec({\n encode (data, buf, offset) {\n if (!buf) buf = new Uint8Array(rrp.encodingLength(data))\n if (!offset) offset = 0\n const oldOffset = offset\n\n offset += 2 // Leave space for length\n name.encode(data.mbox || '.', buf, offset)\n offset += name.encode.bytes\n name.encode(data.txt || '.', buf, offset)\n offset += name.encode.bytes\n rrp.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rrp.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const data = {}\n offset += 2\n data.mbox = name.decode(buf, offset) || '.'\n offset += name.decode.bytes\n data.txt = name.decode(buf, offset) || '.'\n offset += name.decode.bytes\n rrp.decode.bytes = offset - oldOffset\n return data\n },\n encodingLength (data) {\n return 2 + name.encodingLength(data.mbox || '.') + name.encodingLength(data.txt || '.')\n }\n})\n\nconst typebitmap = codec({\n encode (typelist, buf, offset) {\n if (!buf) buf = new Uint8Array(typebitmap.encodingLength(typelist))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const typesByWindow = []\n for (let i = 0; i < typelist.length; i++) {\n const typeid = types.toType(typelist[i])\n if (typesByWindow[typeid >> 8] === undefined) {\n typesByWindow[typeid >> 8] = []\n }\n typesByWindow[typeid >> 8][(typeid >> 3) & 0x1F] |= 1 << (7 - (typeid & 0x7))\n }\n\n for (let i = 0; i < typesByWindow.length; i++) {\n if (typesByWindow[i] !== undefined) {\n const windowBuf = b.from(typesByWindow[i])\n buf[offset] = i\n offset += 1\n buf[offset] = windowBuf.length\n offset += 1\n b.copy(windowBuf, buf, offset, 0, windowBuf.length)\n offset += windowBuf.length\n }\n }\n\n typebitmap.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset, length) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const typelist = []\n while (offset - oldOffset < length) {\n const window = buf[offset]\n offset += 1\n const windowLength = buf[offset]\n offset += 1\n for (let i = 0; i < windowLength; i++) {\n const b = buf[offset + i]\n for (let j = 0; j < 8; j++) {\n if (b & (1 << (7 - j))) {\n const typeid = types.toString((window << 8) | (i << 3) | j)\n typelist.push(typeid)\n }\n }\n }\n offset += windowLength\n }\n\n typebitmap.decode.bytes = offset - oldOffset\n return typelist\n },\n encodingLength (typelist) {\n const extents = []\n for (let i = 0; i < typelist.length; i++) {\n const typeid = types.toType(typelist[i])\n extents[typeid >> 8] = Math.max(extents[typeid >> 8] || 0, typeid & 0xFF)\n }\n\n let len = 0\n for (let i = 0; i < extents.length; i++) {\n if (extents[i] !== undefined) {\n len += 2 + Math.ceil((extents[i] + 1) / 8)\n }\n }\n\n return len\n }\n})\n\nconst rnsec = codec({\n encode (record, buf, offset) {\n if (!buf) buf = new Uint8Array(rnsec.encodingLength(record))\n if (!offset) offset = 0\n const oldOffset = offset\n\n offset += 2 // Leave space for length\n name.encode(record.nextDomain, buf, offset)\n offset += name.encode.bytes\n typebitmap.encode(record.rrtypes, buf, offset)\n offset += typebitmap.encode.bytes\n\n rnsec.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rnsec.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const record = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n record.nextDomain = name.decode(buf, offset)\n offset += name.decode.bytes\n record.rrtypes = typebitmap.decode(buf, offset, length - (offset - oldOffset))\n offset += typebitmap.decode.bytes\n\n rnsec.decode.bytes = offset - oldOffset\n return record\n },\n encodingLength (record) {\n return 2 +\n name.encodingLength(record.nextDomain) +\n typebitmap.encodingLength(record.rrtypes)\n }\n})\n\nconst rnsec3 = codec({\n encode (record, buf, offset) {\n if (!buf) buf = new Uint8Array(rnsec3.encodingLength(record))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const salt = record.salt\n if (!b.isU8Arr(salt)) {\n throw new Error('salt must be a Buffer')\n }\n\n const nextDomain = record.nextDomain\n if (!b.isU8Arr(nextDomain)) {\n throw new Error('nextDomain must be a Buffer')\n }\n\n offset += 2 // Leave space for length\n buf[offset] = record.algorithm\n offset += 1\n buf[offset] = record.flags\n offset += 1\n b.writeUInt16BE(buf, record.iterations, offset)\n offset += 2\n buf[offset] = salt.length\n offset += 1\n b.copy(salt, buf, offset, 0, salt.length)\n offset += salt.length\n buf[offset] = nextDomain.length\n offset += 1\n b.copy(nextDomain, buf, offset, 0, nextDomain.length)\n offset += nextDomain.length\n typebitmap.encode(record.rrtypes, buf, offset)\n offset += typebitmap.encode.bytes\n\n rnsec3.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rnsec3.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const record = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n record.algorithm = buf[offset]\n offset += 1\n record.flags = buf[offset]\n offset += 1\n record.iterations = b.readUInt16BE(buf, offset)\n offset += 2\n const saltLength = buf[offset]\n offset += 1\n record.salt = buf.slice(offset, offset + saltLength)\n offset += saltLength\n const hashLength = buf[offset]\n offset += 1\n record.nextDomain = buf.slice(offset, offset + hashLength)\n offset += hashLength\n record.rrtypes = typebitmap.decode(buf, offset, length - (offset - oldOffset))\n offset += typebitmap.decode.bytes\n\n rnsec3.decode.bytes = offset - oldOffset\n return record\n },\n encodingLength (record) {\n return 8 +\n record.salt.length +\n record.nextDomain.length +\n typebitmap.encodingLength(record.rrtypes)\n }\n})\n\nconst rds = codec({\n encode (digest, buf, offset) {\n if (!buf) buf = new Uint8Array(rds.encodingLength(digest))\n if (!offset) offset = 0\n const oldOffset = offset\n\n const digestdata = digest.digest\n if (!b.isU8Arr(digestdata)) {\n throw new Error('Digest must be a Buffer')\n }\n\n offset += 2 // Leave space for length\n b.writeUInt16BE(buf, digest.keyTag, offset)\n offset += 2\n buf[offset] = digest.algorithm\n offset += 1\n buf[offset] = digest.digestType\n offset += 1\n b.copy(digestdata, buf, offset, 0, digestdata.length)\n offset += digestdata.length\n\n rds.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rds.encode.bytes - 2, oldOffset)\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const digest = {}\n const length = b.readUInt16BE(buf, offset)\n offset += 2\n digest.keyTag = b.readUInt16BE(buf, offset)\n offset += 2\n digest.algorithm = buf[offset]\n offset += 1\n digest.digestType = buf[offset]\n offset += 1\n digest.digest = buf.slice(offset, oldOffset + length + 2)\n offset += digest.digest.length\n rds.decode.bytes = offset - oldOffset\n return digest\n },\n encodingLength (digest) {\n return 6 + b.bytelength(digest.digest)\n }\n})\n\nconst rsshfp = codec({\n encode (record, buf, offset) {\n if (!buf) buf = new Uint8Array(rsshfp.encodingLength(record))\n if (!offset) offset = 0\n const oldOffset = offset\n\n offset += 2 // The function call starts with the offset pointer at the RDLENGTH field, not the RDATA one\n buf[offset] = record.algorithm\n offset += 1\n buf[offset] = record.hash\n offset += 1\n\n const fingerprintLength = b.hexLength(record.fingerprint)\n const expectedLength = getFingerprintLengthForHashType(record.hash)\n if (fingerprintLength !== expectedLength) {\n throw new Error(`Invalid length of fingerprint \"${record.fingerprint}\" for hashType=${record.hash}: ${fingerprintLength} != ${expectedLength}`)\n }\n b.writeHex(buf, record.fingerprint, offset, offset += fingerprintLength)\n rsshfp.encode.bytes = offset - oldOffset\n b.writeUInt16BE(buf, rsshfp.encode.bytes - 2, oldOffset)\n\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n const oldOffset = offset\n\n const record = {}\n offset += 2 // Account for the RDLENGTH field\n record.algorithm = buf[offset]\n offset += 1\n record.hash = buf[offset]\n offset += 1\n\n const fingerprintLength = getFingerprintLengthForHashType(record.hash)\n record.fingerprint = b.toHex(buf, offset, offset + fingerprintLength)\n offset += fingerprintLength\n rsshfp.decode.bytes = offset - oldOffset\n return record\n },\n encodingLength (record) {\n return 4 + b.hexLength(record.fingerprint)\n }\n})\nfunction getFingerprintLengthForHashType (hashType) {\n if (hashType === 1) return 20\n if (hashType === 2) return 32\n throw new Error(`Invalid hashType=${hashType}, supported=1,2`)\n}\nrsshfp.getFingerprintLengthForHashType = getFingerprintLengthForHashType\n\nfunction renc (type) {\n switch (type.toUpperCase()) {\n case 'A': return ra\n case 'PTR': return rptr\n case 'CNAME': return rptr\n case 'DNAME': return rptr\n case 'TXT': return rtxt\n case 'NULL': return rnull\n case 'AAAA': return raaaa\n case 'SRV': return rsrv\n case 'HINFO': return rhinfo\n case 'CAA': return rcaa\n case 'NS': return rns\n case 'SOA': return rsoa\n case 'MX': return rmx\n case 'OPT': return ropt\n case 'DNSKEY': return rdnskey\n case 'RRSIG': return rrrsig\n case 'RP': return rrp\n case 'NSEC': return rnsec\n case 'NSEC3': return rnsec3\n case 'SSHFP': return rsshfp\n case 'DS': return rds\n }\n return runknown\n}\n\nexport const answer = codec({\n encode (a, buf, offset) {\n if (!buf) buf = new Uint8Array(answer.encodingLength(a))\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n name.encode(a.name, buf, offset)\n offset += name.encode.bytes\n\n b.writeUInt16BE(buf, types.toType(a.type), offset)\n\n if (a.type.toUpperCase() === 'OPT') {\n if (a.name !== '.') {\n throw new Error('OPT name must be root.')\n }\n b.writeUInt16BE(buf, a.udpPayloadSize || 4096, offset + 2)\n buf[offset + 4] = a.extendedRcode || 0\n buf[offset + 5] = a.ednsVersion || 0\n b.writeUInt16BE(buf, a.flags || 0, offset + 6)\n\n offset += 8\n ropt.encode(a.options || [], buf, offset)\n offset += ropt.encode.bytes\n } else {\n let klass = classes.toClass(a.class === undefined ? 'IN' : a.class)\n if (a.flush) klass |= FLUSH_MASK // the 1st bit of the class is the flush bit\n b.writeUInt16BE(buf, klass, offset + 2)\n b.writeUInt32BE(buf, a.ttl || 0, offset + 4)\n\n offset += 8\n const enc = renc(a.type)\n enc.encode(a.data, buf, offset)\n offset += enc.encode.bytes\n }\n\n answer.encode.bytes = offset - oldOffset\n return buf\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const a = {}\n const oldOffset = offset\n\n a.name = name.decode(buf, offset)\n offset += name.decode.bytes\n a.type = types.toString(b.readUInt16BE(buf, offset))\n if (a.type === 'OPT') {\n a.udpPayloadSize = b.readUInt16BE(buf, offset + 2)\n a.extendedRcode = buf[offset + 4]\n a.ednsVersion = buf[offset + 5]\n a.flags = b.readUInt16BE(buf, offset + 6)\n a.flag_do = ((a.flags >> 15) & 0x1) === 1\n a.options = ropt.decode(buf, offset + 8)\n offset += 8 + ropt.decode.bytes\n } else {\n const klass = b.readUInt16BE(buf, offset + 2)\n a.ttl = b.readUInt32BE(buf, offset + 4)\n\n a.class = classes.toString(klass & NOT_FLUSH_MASK)\n a.flush = !!(klass & FLUSH_MASK)\n\n const enc = renc(a.type)\n a.data = enc.decode(buf, offset + 8)\n offset += 8 + enc.decode.bytes\n }\n\n answer.decode.bytes = offset - oldOffset\n return a\n },\n encodingLength (a) {\n const data = (a.data !== null && a.data !== undefined) ? a.data : a.options\n return name.encodingLength(a.name) + 8 + renc(a.type).encodingLength(data)\n }\n})\n\nexport const question = codec({\n encode (q, buf, offset) {\n if (!buf) buf = new Uint8Array(question.encodingLength(q))\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n name.encode(q.name, buf, offset)\n offset += name.encode.bytes\n\n b.writeUInt16BE(buf, types.toType(q.type), offset)\n offset += 2\n\n b.writeUInt16BE(buf, classes.toClass(q.class === undefined ? 'IN' : q.class), offset)\n offset += 2\n\n question.encode.bytes = offset - oldOffset\n return q\n },\n decode (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n const q = {}\n\n q.name = name.decode(buf, offset)\n offset += name.decode.bytes\n\n q.type = types.toString(b.readUInt16BE(buf, offset))\n offset += 2\n\n q.class = classes.toString(b.readUInt16BE(buf, offset))\n offset += 2\n\n const qu = !!(q.class & QU_MASK)\n if (qu) q.class &= NOT_QU_MASK\n\n question.decode.bytes = offset - oldOffset\n return q\n },\n encodingLength (q) {\n return name.encodingLength(q.name) + 4\n }\n})\n\nexport {\n rsoa as soa,\n rtxt as txt,\n rnull as null,\n runknown as unknown,\n rns as ns,\n rhinfo as hinfo,\n rptr as ptr,\n rptr as cname,\n rptr as dname,\n rsrv as srv,\n rcaa as caa,\n rmx as mx,\n ra as a,\n raaaa as aaaa,\n roption as option,\n ropt as opt,\n rdnskey as dnskey,\n rrrsig as rrsig,\n rrp as rp,\n rnsec as nsec,\n rnsec3 as nsec3,\n rds as ds,\n rsshfp as sshfp,\n renc as enc\n}\n\nexport const AUTHORITATIVE_ANSWER = 1 << 10\nexport const TRUNCATED_RESPONSE = 1 << 9\nexport const RECURSION_DESIRED = 1 << 8\nexport const RECURSION_AVAILABLE = 1 << 7\nexport const AUTHENTIC_DATA = 1 << 5\nexport const CHECKING_DISABLED = 1 << 4\nexport const DNSSEC_OK = 1 << 15\n\nexport const packet = {\n encode: function (result, buf, offset) {\n const allocing = !buf\n\n if (allocing) buf = new Uint8Array(encodingLength(result))\n if (!offset) offset = 0\n\n const oldOffset = offset\n\n if (!result.questions) result.questions = []\n if (!result.answers) result.answers = []\n if (!result.authorities) result.authorities = []\n if (!result.additionals) result.additionals = []\n\n header.encode(result, buf, offset)\n offset += header.encode.bytes\n\n offset = encodeList(result.questions, question, buf, offset)\n offset = encodeList(result.answers, answer, buf, offset)\n offset = encodeList(result.authorities, answer, buf, offset)\n offset = encodeList(result.additionals, answer, buf, offset)\n\n packet.encode.bytes = offset - oldOffset\n\n // just a quick sanity check\n if (allocing && encode.bytes !== buf.length) {\n return buf.slice(0, encode.bytes)\n }\n\n return buf\n },\n decode: function (buf, offset) {\n if (!offset) offset = 0\n\n const oldOffset = offset\n const result = header.decode(buf, offset)\n offset += header.decode.bytes\n\n offset = decodeList(result.questions, question, buf, offset)\n offset = decodeList(result.answers, answer, buf, offset)\n offset = decodeList(result.authorities, answer, buf, offset)\n offset = decodeList(result.additionals, answer, buf, offset)\n\n packet.decode.bytes = offset - oldOffset\n\n return result\n },\n encodingLength: function (result) {\n return header.encodingLength(result) +\n encodingLengthList(result.questions || [], question) +\n encodingLengthList(result.answers || [], answer) +\n encodingLengthList(result.authorities || [], answer) +\n encodingLengthList(result.additionals || [], answer)\n }\n}\npacket.encode.bytes = 0\npacket.decode.bytes = 0\n\nfunction sanitizeSingle (input, type) {\n if (input.questions) {\n throw new Error('Only one .question object expected instead of a .questions array!')\n }\n const sanitized = Object.assign({\n type\n }, input)\n if (sanitized.question) {\n sanitized.questions = [sanitized.question]\n delete sanitized.question\n }\n return sanitized\n}\n\nexport const query = {\n encode: function (result, buf, offset) {\n buf = packet.encode(sanitizeSingle(result, 'query'), buf, offset)\n query.encode.bytes = packet.encode.bytes\n return buf\n },\n decode: function (buf, offset) {\n const res = packet.decode(buf, offset)\n query.decode.bytes = packet.decode.bytes\n if (res.questions) {\n res.question = res.questions[0]\n delete res.questions\n }\n return res\n },\n encodingLength: function (result) {\n return packet.encodingLength(sanitizeSingle(result, 'query'))\n }\n}\nquery.encode.bytes = 0\nquery.decode.bytes = 0\n\nexport const response = {\n encode: function (result, buf, offset) {\n buf = packet.encode(sanitizeSingle(result, 'response'), buf, offset)\n response.encode.bytes = packet.encode.bytes\n return buf\n },\n decode: function (buf, offset) {\n const res = packet.decode(buf, offset)\n response.decode.bytes = packet.decode.bytes\n if (res.questions) {\n res.question = res.questions[0]\n delete res.questions\n }\n return res\n },\n encodingLength: function (result) {\n return packet.encodingLength(sanitizeSingle(result, 'response'))\n }\n}\nresponse.encode.bytes = 0\nresponse.decode.bytes = 0\n\nexport const encode = packet.encode\nexport const decode = packet.decode\nexport const encodingLength = packet.encodingLength\n\nexport function streamEncode (result) {\n const buf = encode(result)\n const combine = new Uint8Array(2 + buf.byteLength)\n b.writeUInt16BE(combine, buf.byteLength)\n b.copy(buf, combine, 2, 0, buf.length)\n streamEncode.bytes = combine.byteLength\n return combine\n}\nstreamEncode.bytes = 0\n\nexport function streamDecode (sbuf) {\n const len = b.readUInt16BE(sbuf, 0)\n if (sbuf.byteLength < len + 2) {\n // not enough data\n return null\n }\n const result = decode(sbuf.slice(2))\n streamDecode.bytes = decode.bytes\n return result\n}\nstreamDecode.bytes = 0\n\nexport function encodingLengthList (list, enc) {\n let len = 0\n for (let i = 0; i < list.length; i++) len += enc.encodingLength(list[i])\n return len\n}\n\nexport function encodeList (list, enc, buf, offset) {\n for (let i = 0; i < list.length; i++) {\n enc.encode(list[i], buf, offset)\n offset += enc.encode.bytes\n }\n return offset\n}\n\nexport function decodeList (list, enc, buf, offset) {\n for (let i = 0; i < list.length; i++) {\n list[i] = enc.decode(buf, offset)\n offset += enc.decode.bytes\n }\n return offset\n}\n", "const v4Regex = /^(\\d{1,3}\\.){3,3}\\d{1,3}$/\nconst v4Size = 4\nconst v6Regex = /^(::)?(((\\d{1,3}\\.){3}(\\d{1,3}){1})?([0-9a-f]){0,4}:{0,2}){1,8}(::)?$/i\nconst v6Size = 16\n\nexport const v4 = {\n name: 'v4',\n size: v4Size,\n isFormat: ip => v4Regex.test(ip),\n encode (ip, buff, offset) {\n offset = ~~offset\n buff = buff || new Uint8Array(offset + v4Size)\n const max = ip.length\n let n = 0\n for (let i = 0; i < max;) {\n const c = ip.charCodeAt(i++)\n if (c === 46) { // \".\"\n buff[offset++] = n\n n = 0\n } else {\n n = n * 10 + (c - 48)\n }\n }\n buff[offset] = n\n return buff\n },\n decode (buff, offset) {\n offset = ~~offset\n return `${buff[offset++]}.${buff[offset++]}.${buff[offset++]}.${buff[offset]}`\n }\n}\n\nexport const v6 = {\n name: 'v6',\n size: v6Size,\n isFormat: ip => ip.length > 0 && v6Regex.test(ip),\n encode (ip, buff, offset) {\n offset = ~~offset\n let end = offset + v6Size\n let fill = -1\n let hexN = 0\n let decN = 0\n let prevColon = true\n let useDec = false\n buff = buff || new Uint8Array(offset + v6Size)\n // Note: This algorithm needs to check if the offset\n // could exceed the buffer boundaries as it supports\n // non-standard compliant encodings that may go beyond\n // the boundary limits. if (offset < end) checks should\n // not be necessary...\n for (let i = 0; i < ip.length; i++) {\n let c = ip.charCodeAt(i)\n if (c === 58) { // :\n if (prevColon) {\n if (fill !== -1) {\n // Not Standard! (standard doesn't allow multiple ::)\n // We need to treat\n if (offset < end) buff[offset] = 0\n if (offset < end - 1) buff[offset + 1] = 0\n offset += 2\n } else if (offset < end) {\n // :: in the middle\n fill = offset\n }\n } else {\n // : ends the previous number\n if (useDec === true) {\n // Non-standard! (ipv4 should be at end only)\n // A ipv4 address should not be found anywhere else but at\n // the end. This codec also support putting characters\n // after the ipv4 address..\n if (offset < end) buff[offset] = decN\n offset++\n } else {\n if (offset < end) buff[offset] = hexN >> 8\n if (offset < end - 1) buff[offset + 1] = hexN & 0xff\n offset += 2\n }\n hexN = 0\n decN = 0\n }\n prevColon = true\n useDec = false\n } else if (c === 46) { // . indicates IPV4 notation\n if (offset < end) buff[offset] = decN\n offset++\n decN = 0\n hexN = 0\n prevColon = false\n useDec = true\n } else {\n prevColon = false\n if (c >= 97) {\n c -= 87 // a-f ... 97~102 -87 => 10~15\n } else if (c >= 65) {\n c -= 55 // A-F ... 65~70 -55 => 10~15\n } else {\n c -= 48 // 0-9 ... starting from charCode 48\n decN = decN * 10 + c\n }\n // We don't know yet if its a dec or hex number\n hexN = (hexN << 4) + c\n }\n }\n if (prevColon === false) {\n // Commiting last number\n if (useDec === true) {\n if (offset < end) buff[offset] = decN\n offset++\n } else {\n if (offset < end) buff[offset] = hexN >> 8\n if (offset < end - 1) buff[offset + 1] = hexN & 0xff\n offset += 2\n }\n } else if (fill === 0) {\n // Not Standard! (standard doesn't allow multiple ::)\n // This means that a : was found at the start AND end which means the\n // end needs to be treated as 0 entry...\n if (offset < end) buff[offset] = 0\n if (offset < end - 1) buff[offset + 1] = 0\n offset += 2\n } else if (fill !== -1) {\n // Non-standard! (standard doens't allow multiple ::)\n // Here we find that there has been a :: somewhere in the middle\n // and the end. To treat the end with priority we need to move all\n // written data two bytes to the right.\n offset += 2\n for (let i = Math.min(offset - 1, end - 1); i >= fill + 2; i--) {\n buff[i] = buff[i - 2]\n }\n buff[fill] = 0\n buff[fill + 1] = 0\n fill = offset\n }\n if (fill !== offset && fill !== -1) {\n // Move the written numbers to the end while filling the everything\n // \"fill\" to the bytes with zeros.\n if (offset > end - 2) {\n // Non Standard support, when the cursor exceeds bounds.\n offset = end - 2\n }\n while (end > fill) {\n buff[--end] = offset < end && offset > fill ? buff[--offset] : 0\n }\n } else {\n // Fill the rest with zeros\n while (offset < end) {\n buff[offset++] = 0\n }\n }\n return buff\n },\n decode (buff, offset) {\n offset = ~~offset\n let result = ''\n for (let i = 0; i < v6Size; i += 2) {\n if (i !== 0) {\n result += ':'\n }\n result += (buff[offset + i] << 8 | buff[offset + i + 1]).toString(16)\n }\n return result\n .replace(/(^|:)0(:0)*:0(:|$)/, '$1::$3')\n .replace(/:{3,4}/, '::')\n }\n}\n\nexport const name = 'ip'\nexport function sizeOf (ip) {\n if (v4.isFormat(ip)) return v4.size\n if (v6.isFormat(ip)) return v6.size\n throw Error(`Invalid ip address: ${ip}`)\n}\n\nexport function familyOf (string) {\n return sizeOf(string) === v4.size ? 1 : 2\n}\n\nexport function encode (ip, buff, offset) {\n offset = ~~offset\n const size = sizeOf(ip)\n if (typeof buff === 'function') {\n buff = buff(offset + size)\n }\n if (size === v4.size) {\n return v4.encode(ip, buff, offset)\n }\n return v6.encode(ip, buff, offset)\n}\n\nexport function decode (buff, offset, length) {\n offset = ~~offset\n length = length || (buff.length - offset)\n if (length === v4.size) {\n return v4.decode(buff, offset, length)\n }\n if (length === v6.size) {\n return v6.decode(buff, offset, length)\n }\n throw Error(`Invalid buffer size needs to be ${v4.size} for v4 or ${v6.size} for v6.`)\n}\n", "export function toString (type) {\n switch (type) {\n case 1: return 'A'\n case 10: return 'NULL'\n case 28: return 'AAAA'\n case 18: return 'AFSDB'\n case 42: return 'APL'\n case 257: return 'CAA'\n case 60: return 'CDNSKEY'\n case 59: return 'CDS'\n case 37: return 'CERT'\n case 5: return 'CNAME'\n case 49: return 'DHCID'\n case 32769: return 'DLV'\n case 39: return 'DNAME'\n case 48: return 'DNSKEY'\n case 43: return 'DS'\n case 55: return 'HIP'\n case 13: return 'HINFO'\n case 45: return 'IPSECKEY'\n case 25: return 'KEY'\n case 36: return 'KX'\n case 29: return 'LOC'\n case 15: return 'MX'\n case 35: return 'NAPTR'\n case 2: return 'NS'\n case 47: return 'NSEC'\n case 50: return 'NSEC3'\n case 51: return 'NSEC3PARAM'\n case 12: return 'PTR'\n case 46: return 'RRSIG'\n case 17: return 'RP'\n case 24: return 'SIG'\n case 6: return 'SOA'\n case 99: return 'SPF'\n case 33: return 'SRV'\n case 44: return 'SSHFP'\n case 32768: return 'TA'\n case 249: return 'TKEY'\n case 52: return 'TLSA'\n case 250: return 'TSIG'\n case 16: return 'TXT'\n case 252: return 'AXFR'\n case 251: return 'IXFR'\n case 41: return 'OPT'\n case 255: return 'ANY'\n }\n return 'UNKNOWN_' + type\n}\n\nexport function toType (name) {\n switch (name.toUpperCase()) {\n case 'A': return 1\n case 'NULL': return 10\n case 'AAAA': return 28\n case 'AFSDB': return 18\n case 'APL': return 42\n case 'CAA': return 257\n case 'CDNSKEY': return 60\n case 'CDS': return 59\n case 'CERT': return 37\n case 'CNAME': return 5\n case 'DHCID': return 49\n case 'DLV': return 32769\n case 'DNAME': return 39\n case 'DNSKEY': return 48\n case 'DS': return 43\n case 'HIP': return 55\n case 'HINFO': return 13\n case 'IPSECKEY': return 45\n case 'KEY': return 25\n case 'KX': return 36\n case 'LOC': return 29\n case 'MX': return 15\n case 'NAPTR': return 35\n case 'NS': return 2\n case 'NSEC': return 47\n case 'NSEC3': return 50\n case 'NSEC3PARAM': return 51\n case 'PTR': return 12\n case 'RRSIG': return 46\n case 'RP': return 17\n case 'SIG': return 24\n case 'SOA': return 6\n case 'SPF': return 99\n case 'SRV': return 33\n case 'SSHFP': return 44\n case 'TA': return 32768\n case 'TKEY': return 249\n case 'TLSA': return 52\n case 'TSIG': return 250\n case 'TXT': return 16\n case 'AXFR': return 252\n case 'IXFR': return 251\n case 'OPT': return 41\n case 'ANY': return 255\n case '*': return 255\n }\n if (name.toUpperCase().startsWith('UNKNOWN_')) return parseInt(name.slice(8))\n return 0\n}\n", "/*\n * Traditional DNS header RCODEs (4-bits) defined by IANA in\n * https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml\n */\n\nexport function toString (rcode) {\n switch (rcode) {\n case 0: return 'NOERROR'\n case 1: return 'FORMERR'\n case 2: return 'SERVFAIL'\n case 3: return 'NXDOMAIN'\n case 4: return 'NOTIMP'\n case 5: return 'REFUSED'\n case 6: return 'YXDOMAIN'\n case 7: return 'YXRRSET'\n case 8: return 'NXRRSET'\n case 9: return 'NOTAUTH'\n case 10: return 'NOTZONE'\n case 11: return 'RCODE_11'\n case 12: return 'RCODE_12'\n case 13: return 'RCODE_13'\n case 14: return 'RCODE_14'\n case 15: return 'RCODE_15'\n }\n return 'RCODE_' + rcode\n}\n\nexport function toRcode (code) {\n switch (code.toUpperCase()) {\n case 'NOERROR': return 0\n case 'FORMERR': return 1\n case 'SERVFAIL': return 2\n case 'NXDOMAIN': return 3\n case 'NOTIMP': return 4\n case 'REFUSED': return 5\n case 'YXDOMAIN': return 6\n case 'YXRRSET': return 7\n case 'NXRRSET': return 8\n case 'NOTAUTH': return 9\n case 'NOTZONE': return 10\n case 'RCODE_11': return 11\n case 'RCODE_12': return 12\n case 'RCODE_13': return 13\n case 'RCODE_14': return 14\n case 'RCODE_15': return 15\n }\n return 0\n}\n", "/*\n * Traditional DNS header OPCODEs (4-bits) defined by IANA in\n * https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-5\n */\n\nexport function toString (opcode) {\n switch (opcode) {\n case 0: return 'QUERY'\n case 1: return 'IQUERY'\n case 2: return 'STATUS'\n case 3: return 'OPCODE_3'\n case 4: return 'NOTIFY'\n case 5: return 'UPDATE'\n case 6: return 'OPCODE_6'\n case 7: return 'OPCODE_7'\n case 8: return 'OPCODE_8'\n case 9: return 'OPCODE_9'\n case 10: return 'OPCODE_10'\n case 11: return 'OPCODE_11'\n case 12: return 'OPCODE_12'\n case 13: return 'OPCODE_13'\n case 14: return 'OPCODE_14'\n case 15: return 'OPCODE_15'\n }\n return 'OPCODE_' + opcode\n}\n\nexport function toOpcode (code) {\n switch (code.toUpperCase()) {\n case 'QUERY': return 0\n case 'IQUERY': return 1\n case 'STATUS': return 2\n case 'OPCODE_3': return 3\n case 'NOTIFY': return 4\n case 'UPDATE': return 5\n case 'OPCODE_6': return 6\n case 'OPCODE_7': return 7\n case 'OPCODE_8': return 8\n case 'OPCODE_9': return 9\n case 'OPCODE_10': return 10\n case 'OPCODE_11': return 11\n case 'OPCODE_12': return 12\n case 'OPCODE_13': return 13\n case 'OPCODE_14': return 14\n case 'OPCODE_15': return 15\n }\n return 0\n}\n", "export function toString (klass) {\n switch (klass) {\n case 1: return 'IN'\n case 2: return 'CS'\n case 3: return 'CH'\n case 4: return 'HS'\n case 255: return 'ANY'\n }\n return 'UNKNOWN_' + klass\n}\n\nexport function toClass (name) {\n switch (name.toUpperCase()) {\n case 'IN': return 1\n case 'CS': return 2\n case 'CH': return 3\n case 'HS': return 4\n case 'ANY': return 255\n }\n return 0\n}\n", "export function toString (type) {\n switch (type) {\n // list at\n // https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-11\n case 1: return 'LLQ'\n case 2: return 'UL'\n case 3: return 'NSID'\n case 5: return 'DAU'\n case 6: return 'DHU'\n case 7: return 'N3U'\n case 8: return 'CLIENT_SUBNET'\n case 9: return 'EXPIRE'\n case 10: return 'COOKIE'\n case 11: return 'TCP_KEEPALIVE'\n case 12: return 'PADDING'\n case 13: return 'CHAIN'\n case 14: return 'KEY_TAG'\n case 26946: return 'DEVICEID'\n }\n if (type < 0) {\n return null\n }\n return `OPTION_${type}`\n}\n\nexport function toCode (name) {\n if (typeof name === 'number') {\n return name\n }\n if (!name) {\n return -1\n }\n switch (name.toUpperCase()) {\n case 'OPTION_0': return 0\n case 'LLQ': return 1\n case 'UL': return 2\n case 'NSID': return 3\n case 'OPTION_4': return 4\n case 'DAU': return 5\n case 'DHU': return 6\n case 'N3U': return 7\n case 'CLIENT_SUBNET': return 8\n case 'EXPIRE': return 9\n case 'COOKIE': return 10\n case 'TCP_KEEPALIVE': return 11\n case 'PADDING': return 12\n case 'CHAIN': return 13\n case 'KEY_TAG': return 14\n case 'DEVICEID': return 26946\n case 'OPTION_65535': return 65535\n }\n const m = name.match(/_(\\d+)$/)\n if (m) {\n return parseInt(m[1], 10)\n }\n return -1\n}\n", "import * as utf8 from 'utf8-codec'\n\nexport const isU8Arr = input => input instanceof Uint8Array\n\nexport function bytelength (input) {\n return typeof input === 'string' ? utf8.encodingLength(input) : input.byteLength\n}\n\nexport function from (input) {\n if (input instanceof Uint8Array) {\n return input\n }\n if (Array.isArray(input)) {\n return new Uint8Array(input)\n }\n return utf8.encode(input)\n}\n\nexport function write (arr, str, start) {\n if (typeof str !== 'string') {\n throw new Error('unknown input type')\n }\n utf8.encode(str, arr, start)\n return utf8.encode.bytes\n}\n\nconst hexNum = {}\nconst numHex = new Array(0xff)\nfor (let b0 = 0; b0 <= 0xf; b0 += 1) {\n const b0L = b0.toString(16)\n const b0U = b0L.toUpperCase()\n for (let b1 = 0; b1 <= 0xf; b1 += 1) {\n const b1L = b1.toString(16)\n const b1U = b1L.toUpperCase()\n const num = b0 << 4 | b1\n const hex = `${b0L}${b1L}`\n numHex[num] = hex\n hexNum[hex] = num\n hexNum[`${b0U}${b1L}`] = num\n hexNum[`${b0L}${b1U}`] = num\n hexNum[`${b0U}${b1U}`] = num\n }\n}\n\nexport function toHex (buf, start, end) {\n let result = ''\n for (let offset = start; offset < end;) {\n const num = buf[offset++]\n result += numHex[num]\n }\n return result\n}\n\nexport function hexLength (string) {\n return string.length >>> 1\n}\n\nexport function writeHex (buf, string, offset, end) {\n let i = 0\n while (offset < end) {\n const hex = string.substr(i, 2)\n const num = hexNum[hex]\n if (num === undefined) return\n buf[offset++] = num\n i += 2\n }\n return buf\n}\n\nconst P_24 = Math.pow(2, 24)\nconst P_16 = Math.pow(2, 16)\nconst P_8 = Math.pow(2, 8)\nexport const readUInt32BE = (buf, offset) => buf[offset] * P_24 +\n buf[offset + 1] * P_16 +\n buf[offset + 2] * P_8 +\n buf[offset + 3]\n\nexport const readUInt16BE = (buf, offset) => (buf[offset] << 8) | buf[offset + 1]\nexport const writeUInt32BE = (buf, value, offset) => {\n value = +value\n buf[offset + 3] = value\n value = value >>> 8\n buf[offset + 2] = value\n value = value >>> 8\n buf[offset + 1] = value\n value = value >>> 8\n buf[offset] = value\n return offset + 4\n}\nexport const writeUInt16BE = (buf, value, offset) => {\n buf[offset] = value >> 8\n buf[offset + 1] = value & 0xFF\n return offset + 2\n}\n\nexport function copy (source, target, targetStart, sourceStart, sourceEnd) {\n if (targetStart < 0) {\n sourceStart -= targetStart\n targetStart = 0\n }\n\n if (sourceStart < 0) {\n sourceStart = 0\n }\n\n if (sourceEnd < 0) {\n return new Uint8Array(0)\n }\n\n if (targetStart >= target.length || sourceStart >= sourceEnd) {\n return 0\n }\n\n return _copyActual(source, target, targetStart, sourceStart, sourceEnd)\n}\n\nfunction _copyActual (source, target, targetStart, sourceStart, sourceEnd) {\n if (sourceEnd - sourceStart > target.length - targetStart) {\n sourceEnd = sourceStart + target.length - targetStart\n }\n\n let nb = sourceEnd - sourceStart\n const sourceLen = source.length - sourceStart\n if (nb > sourceLen) {\n nb = sourceLen\n }\n\n if (sourceStart !== 0 || sourceEnd < source.length) {\n source = new Uint8Array(source.buffer, source.byteOffset + sourceStart, nb)\n }\n\n target.set(source, targetStart)\n\n return nb\n}\n", "const SURROGATE_A = 0b1101100000000000\nconst SURROGATE_B = 0b1101110000000000\n\nexport const name = 'utf8'\n\nexport function encodingLength (str) {\n let len = 0\n const strLen = str.length\n for (let i = 0; i < strLen; i += 1) {\n const code = str.charCodeAt(i)\n if (code <= 0x7F) {\n len += 1\n } else if (code <= 0x07FF) {\n len += 2\n } else if ((code & 0xF800) !== SURROGATE_A) {\n len += 3\n } else {\n const next = i + 1\n if (next === strLen || code >= SURROGATE_B) {\n len += 3\n } else {\n const nextCode = str.charCodeAt(next)\n if ((nextCode & 0xFC00) !== SURROGATE_B) {\n len += 3\n } else {\n i = next\n len += 4\n }\n }\n }\n }\n return len\n}\n\nexport function encode (str, buf, offset) {\n const strLen = str.length\n if (offset === undefined || offset === null) {\n offset = 0\n }\n if (buf === undefined) {\n buf = new Uint8Array(encodingLength(str) + offset)\n }\n let off = offset\n for (let i = 0; i < strLen; i += 1) {\n let code = str.charCodeAt(i)\n if (code <= 0x7F) {\n buf[off++] = code\n } else if (code <= 0x07FF) {\n buf[off++] = 0b11000000 | ((code & 0b11111000000) >> 6)\n buf[off++] = 0b10000000 | (code & 0b00000111111)\n } else if ((code & 0xF800) !== SURROGATE_A) {\n buf[off++] = 0b11100000 | ((code & 0b1111000000000000) >> 12)\n buf[off++] = 0b10000000 | ((code & 0b0000111111000000) >> 6)\n buf[off++] = 0b10000000 | (code & 0b0000000000111111)\n } else {\n const next = i + 1\n if (next === strLen || code >= SURROGATE_B) {\n // Incorrectly started surrogate pair\n buf[off++] = 0xef\n buf[off++] = 0xbf\n buf[off++] = 0xbd\n } else {\n const nextCode = str.charCodeAt(next)\n if ((nextCode & 0xFC00) !== SURROGATE_B) {\n // Incorrect surrogate pair\n buf[off++] = 0xef\n buf[off++] = 0xbf\n buf[off++] = 0xbd\n } else {\n i = next\n code = 0b000010000000000000000 |\n ((code & 0b1111111111) << 10) |\n (nextCode & 0b1111111111)\n buf[off++] = 0b11110000 | ((code & 0b111000000000000000000) >> 18)\n buf[off++] = 0b10000000 | ((code & 0b000111111000000000000) >> 12)\n buf[off++] = 0b10000000 | ((code & 0b000000000111111000000) >> 6)\n buf[off++] = 0b10000000 | (code & 0b000000000000000111111)\n }\n }\n }\n }\n encode.bytes = off - offset\n return buf\n}\nencode.bytes = 0\n\nexport function decode (buf, start, end) {\n let result = ''\n if (start === undefined || start === null) {\n start = 0\n }\n if (end === undefined || end === null) {\n end = buf.length\n }\n for (let offset = start; offset < end;) {\n const code = buf[offset++]\n let num\n if (code <= 128) {\n num = code\n } else if (code > 191 && code < 224) {\n num = ((code & 0b11111) << 6) | (buf[offset++] & 0b111111)\n } else if (code > 239 && code < 365) {\n num = (\n ((code & 0b111) << 18) |\n ((buf[offset++] & 0b111111) << 12) |\n ((buf[offset++] & 0b111111) << 6) |\n (buf[offset++] & 0b111111)\n ) - 0x10000\n const numA = SURROGATE_A | ((num >> 10) & 0b1111111111)\n result += String.fromCharCode(numA)\n num = SURROGATE_B | (num & 0b1111111111)\n } else {\n num = ((code & 0b1111) << 12) |\n ((buf[offset++] & 0b111111) << 6) |\n (buf[offset++] & 0b111111)\n }\n result += String.fromCharCode(num)\n }\n decode.bytes = end - start\n return result\n}\ndecode.bytes = 0\n", "import type {\n CryptoApi,\n InferKeyGeneratorAlgorithm,\n LocalKeyManager,\n} from '@enbox/crypto';\n\nimport type { BearerDid } from '../bearer-did.js';\nimport type { DidMetadata } from '../types/portable-did.js';\nimport type {\n DidDocument,\n DidResolutionOptions,\n DidResolutionResult,\n DidVerificationMethod,\n} from '../types/did-core.js';\n\nimport type { DidVerificationRelationship } from '../types/did-core.js';\n\n/**\n * Represents options during the creation of a Decentralized Identifier (DID).\n *\n * Implementations of this interface may contain properties and methods that provide specific\n * options or metadata during the DID creation processes following specific DID method\n * specifications.\n */\nexport interface DidCreateOptions<TKms> {\n /**\n * Optional. An array of verification methods to be included in the DID document.\n */\n verificationMethods?: DidCreateVerificationMethod<TKms>[];\n}\n\n/**\n * Options for additional verification methods added to the DID Document during the creation of a\n * new Decentralized Identifier (DID).\n */\nexport interface DidCreateVerificationMethod<TKms> extends Pick<Partial<DidVerificationMethod>, 'controller' | 'id' | 'type'> {\n /**\n * The name of the cryptographic algorithm to be used for key generation.\n *\n * Examples might include `Ed25519` and `ES256K` but will vary depending on the DID method\n * specification and the key management system in use.\n *\n * @example\n * ```ts\n * const verificationMethod: DidCreateVerificationMethod = {\n * algorithm: 'Ed25519'\n * };\n * ```\n */\n algorithm: TKms extends CryptoApi\n ? InferKeyGeneratorAlgorithm<TKms>\n : InferKeyGeneratorAlgorithm<LocalKeyManager>;\n\n /**\n * Optionally specify the purposes for which a verification method is intended to be used in a DID\n * document.\n *\n * The `purposes` property defines the specific\n * {@link DidVerificationRelationship | verification relationships} between the DID subject and\n * the verification method. This enables the verification method to be utilized for distinct\n * actions such as authentication, assertion, key agreement, capability delegation, and others. It\n * is important for verifiers to recognize that a verification method must be associated with the\n * relevant purpose in the DID document to be valid for that specific use case.\n *\n * @example\n * ```ts\n * const verificationMethod: DidCreateVerificationMethod = {\n * algorithm: 'Ed25519',\n * controller: 'did:example:1234',\n * purposes: ['authentication', 'assertionMethod']\n * };\n * ```\n */\n purposes?: (DidVerificationRelationship | keyof typeof DidVerificationRelationship)[];\n}\n\n/**\n * Defines the API for a specific DID method. It includes functionalities for creating and resolving\n * DIDs.\n *\n * @typeparam T - The type of the DID instance associated with this method.\n * @typeparam O - The type of the options used for creating the DID.\n */\nexport interface DidMethodApi<\n TKms extends CryptoApi | undefined = CryptoApi,\n TDid extends BearerDid = BearerDid,\n TOptions extends DidCreateOptions<TKms> = DidCreateOptions<TKms>\n > extends DidMethodResolver {\n /**\n * The name of the DID method.\n *\n * For example, in the DID `did:example:123456`, \"example\" would be the method name.\n */\n methodName: string;\n\n new (): DidMethod;\n\n /**\n * Creates a new DID.\n *\n * This function should generate a new DID in accordance with the DID method specification being\n * implemented, using the provided `keyManager`, and optionally, any provided `options`.\n *\n * @param params - The parameters used to create the DID.\n * @param params.keyManager - Optional. The cryptographic API used for key management.\n * @param params.options - Optional. The options used for creating the DID.\n * @returns A promise that resolves to the newly created DID instance.\n */\n create(params: {\n keyManager?: TKms;\n options?: TOptions;\n }): Promise<TDid>;\n\n /**\n * Given a DID Document, return the verification method that will be used for signing messages and\n * credentials.\n *\n * If given, the `methodId` parameter is used to select the verification method. If not given, a\n * DID method specific approach is taken to selecting the verification method to return.\n *\n * @param params - The parameters for the `getSigningMethod` operation.\n * @param params.didDocument - DID Document to get the verification method from.\n * @param params.methodId - ID of the verification method to use for signing.\n * @returns A promise that resolves to the erification method to use for signing.\n */\n getSigningMethod(params: {\n didDocument: DidDocument;\n methodId?: string;\n }): Promise<DidVerificationMethod>;\n}\n\n/**\n * Defines the interface for resolving a DID using a specific DID method.\n *\n * A DID resolver takes a DID URI as input and returns a {@link DidResolutionResult} object.\n *\n * @property {string} methodName - The name of the DID method.\n * @method resolve - Asynchronous method to resolve a DID URI. Takes the DID URI and optional resolution options.\n */\nexport interface DidMethodResolver {\n /**\n * The name of the DID method.\n *\n * For example, in the DID `did:example:123456`, \"example\" would be the method name.\n */\n methodName: string;\n\n new (): DidMethod;\n\n /**\n * Resolves a DID URI.\n *\n * This function should resolve the DID URI in accordance with the DID method specification being\n * implemented, using the provided `options`.\n *\n * @param didUri - The DID URI to be resolved.\n * @param options - Optional. The options used for resolving the DID.\n * @returns A {@link DidResolutionResult} object containing the DID document and metadata or an error.\n */\n resolve(didUri: string, options?: DidResolutionOptions): Promise<DidResolutionResult>;\n}\n\n/**\n * Represents the result of a Decentralized Identifier (DID) registration operation.\n *\n * This type encapsulates the complete outcome of registering a DID, including the registration\n * metadata, the DID document (if registration is successful), and metadata about the DID document.\n */\nexport interface DidRegistrationResult {\n /**\n * The DID document resulting from the registration process, if successful.\n *\n * If the registration operation was successful, this MUST contain a DID document\n * corresponding to the DID. If the registration is unsuccessful, this value MUST be empty.\n *\n * @see {@link https://www.w3.org/TR/did-core/#dfn-diddocument | DID Core Specification, \u00A7 DID Document}\n */\n didDocument: DidDocument | null;\n\n /**\n * Metadata about the DID Document.\n *\n * This structure contains information about the DID Document like creation and update timestamps,\n * deactivation status, versioning information, and other details relevant to the DID Document.\n *\n * @see {@link https://www.w3.org/TR/did-core/#dfn-diddocumentmetadata | DID Core Specification, \u00A7 DID Document Metadata}\n */\n didDocumentMetadata: DidMetadata;\n\n /**\n * A metadata structure consisting of values relating to the results of the DID registration\n * process.\n *\n * This structure is REQUIRED, and in the case of an error in the registration process,\n * this MUST NOT be empty. If the registration is not successful, this structure MUST contain an\n * `error` property describing the error.\n */\n didRegistrationMetadata: DidRegistrationMetadata;\n}\n\n/**\n * Represents metadata related to the result of a DID registration operation.\n *\n * This type includes fields that provide information about the outcome of a DID registration\n * process (e.g., create, update, deactivate), including any errors that occurred.\n *\n * This metadata typically changes between invocations of the `create`, `update`, and `deactivate`\n * functions, as it represents data about the registration process itself.\n */\nexport type DidRegistrationMetadata = {\n /**\n * An error code indicating issues encountered during the DID registration process.\n *\n * While the DID Core specification does not define a specific set of error codes for the result\n * returned by the `create`, `update`, or `deactivate` functions, it is recommended to use the\n * error codes defined in the DID Specification Registries for\n * {@link https://www.w3.org/TR/did-spec-registries/#error | DID Resolution Metadata }.\n *\n * Recommended error codes include:\n * - `internalError`: An unexpected error occurred during DID registration process.\n * - `invalidDid`: The provided DID is invalid.\n * - `invalidDidDocument`: The provided DID document does not conform to valid syntax.\n * - `invalidDidDocumentLength`: The byte length of the provided DID document does not match the expected value.\n * - `invalidSignature`: Verification of a signature failed.\n * - `methodNotSupported`: The DID method specified is not supported.\n * - Custom error codes can also be provided as strings.\n */\n error?: string;\n\n // Additional output metadata generated during DID registration.\n [key: string]: any;\n};\n\n/**\n * Base abstraction for all Decentralized Identifier (DID) method implementations.\n *\n * This base class serves as a foundational structure upon which specific DID methods\n * can be implemented. Subclasses should furnish particular method and data models adherent\n * to various DID methods, taking care to adhere to the\n * {@link https://www.w3.org/TR/did-core/ | W3C DID Core specification} and the\n * respective DID method specifications.\n */\nexport class DidMethod {\n /**\n * MUST be implemented by all DID method implementations that extend {@link DidMethod}.\n *\n * Given the W3C DID Document of a DID, return the verification method that will be used for\n * signing messages and credentials. If given, the `methodId` parameter is used to select the\n * verification method. If not given, each DID method implementation will select a default\n * verification method from the DID Document.\n *\n * @param _params - The parameters for the `getSigningMethod` operation.\n * @param _params.didDocument - DID Document to get the verification method from.\n * @param _params.methodId - ID of the verification method to use for signing.\n * @returns Verification method to use for signing.\n */\n public static async getSigningMethod(_params: {\n didDocument: DidDocument;\n methodId?: string;\n }): Promise<DidVerificationMethod | undefined> {\n throw new Error(`Not implemented: Classes extending DidMethod must implement getSigningMethod()`);\n }\n\n /**\n * MUST be implemented by all DID method implementations that extend {@link DidMethod}.\n *\n * Resolves a DID URI to a DID Document.\n *\n * @param _didUri - The DID to be resolved.\n * @param _options - Optional parameters for resolving the DID.\n * @returns A Promise resolving to a {@link DidResolutionResult} object representing the result of the resolution.\n */\n public static async resolve(_didUri: string, _options?: DidResolutionOptions): Promise<DidResolutionResult> {\n throw new Error(`Not implemented: Classes extending DidMethod must implement resolve()`);\n }\n}", "import type { CryptoApi, Jwk, KeyIdentifier, KeyImporterExporter, KmsExportKeyParams, KmsImportKeyParams } from '@enbox/crypto';\nimport type {\n IonDocumentModel,\n IonPublicKeyModel,\n IonPublicKeyPurpose,\n JwkEs256k,\n} from '@decentralized-identity/ion-sdk';\n\nimport { computeJwkThumbprint, LocalKeyManager } from '@enbox/crypto';\nimport { IonDid, IonRequest } from '@decentralized-identity/ion-sdk';\n\nimport type { PortableDid } from '../types/portable-did.js';\nimport type { DidCreateOptions, DidCreateVerificationMethod, DidRegistrationResult } from '../methods/did-method.js';\nimport type {\n DidDocument,\n DidResolutionOptions,\n DidResolutionResult,\n DidService,\n DidVerificationMethod,\n DidVerificationRelationship,\n} from '../types/did-core.js';\n\nimport { BearerDid } from '../bearer-did.js';\nimport { Did } from '../did.js';\nimport { DidMethod } from '../methods/did-method.js';\nimport { EMPTY_DID_RESOLUTION_RESULT } from '../types/did-resolution.js';\nimport { getVerificationRelationshipsById } from '../utils.js';\nimport { DidError, DidErrorCode } from '../did-error.js';\n\n/**\n * Options for creating a Decentralized Identifier (DID) using the DID ION method.\n */\nexport interface DidIonCreateOptions<TKms> extends DidCreateOptions<TKms> {\n /**\n * Optional. The URI of a server involved in executing DID method operations. In the context of\n * DID creation, the endpoint is expected to be a Sidetree node. If not specified, a default\n * gateway node is used.\n */\n gatewayUri?: string;\n\n /**\n * Optional. Determines whether the created DID should be published to a Sidetree node.\n *\n * If set to `true` or omitted, the DID is publicly discoverable. If `false`, the DID is not\n * published and cannot be resolved by others. By default, newly created DIDs are published.\n *\n * @see {@link https://identity.foundation/sidetree/spec/#create | Sidetree Protocol Specification, \u00A7 Create}\n *\n * @example\n * ```ts\n * const did = await DidIon.create({\n * options: {\n * publish: false\n * };\n * ```\n */\n publish?: boolean;\n\n /**\n * Optional. An array of service endpoints associated with the DID.\n *\n * Services are used in DID documents to express ways of communicating with the DID subject or\n * associated entities. A service can be any type of service the DID subject wants to advertise,\n * including decentralized identity management services for further discovery, authentication,\n * authorization, or interaction.\n *\n * @see {@link https://www.w3.org/TR/did-core/#services | DID Core Specification, \u00A7 Services}\n *\n * @example\n * ```ts\n * const did = await DidIon.create({\n * options: {\n * services: [\n * {\n * id: 'dwn',\n * type: 'DecentralizedWebNode',\n * serviceEndpoint: ['https://example.com/dwn1', 'https://example/dwn2']\n * }\n * ]\n * };\n * ```\n */\n services?: DidService[];\n\n /**\n * Optional. An array of verification methods to be included in the DID document.\n *\n * By default, a newly created DID ION document will contain a single Ed25519 verification method.\n * Additional verification methods can be added to the DID document using the\n * `verificationMethods` property.\n *\n * @see {@link https://www.w3.org/TR/did-core/#verification-methods | DID Core Specification, \u00A7 Verification Methods}\n *\n * @example\n * ```ts\n * const did = await DidIon.create({\n * options: {\n * verificationMethods: [\n * {\n * algorithm: 'Ed25519',\n * purposes: ['authentication', 'assertionMethod']\n * },\n * {\n * algorithm: 'Ed25519',\n * id: 'dwn-sig',\n * purposes: ['authentication', 'assertionMethod']\n * }\n * ]\n * };\n * ```\n */\n verificationMethods?: DidCreateVerificationMethod<TKms>[];\n}\n\n/**\n * Represents the request model for managing DID documents within the ION network, according to the\n * Sidetree protocol specification.\n */\nexport interface DidIonCreateRequest {\n /** The type of operation to perform, which is always 'create' for a Create Operation. */\n type: 'create';\n\n /** Contains properties related to the initial state of the DID document. */\n suffixData: {\n /** A hash of the `delta` object, representing the initial changes to the DID document. */\n deltaHash: string;\n /** A commitment value used for future recovery operations, hashed for security. */\n recoveryCommitment: string;\n };\n\n /** Details the changes to be applied to the DID document in this operation. */\n delta: {\n /** A commitment value used for the next update operation, hashed for security. */\n updateCommitment: string;\n /** An array of patch objects specifying the modifications to apply to the DID document. */\n patches: {\n /** The type of modification to perform (e.g., adding or removing public keys or service\n * endpoints). */\n action: string;\n /** The document state or partial state to apply with this patch. */\n document: IonDocumentModel;\n }[];\n }\n}\n\n/**\n * Represents a {@link DidVerificationMethod | DID verification method} in the context of DID ION\n * create, update, deactivate, and resolve operations.\n *\n * Unlike the DID Core standard {@link DidVerificationMethod} interface, this type is specific to\n * the ION method operations and only includes the `id`, `publicKeyJwk`, and `purposes` properties:\n * - The `id` property is optional and specifies the identifier fragment of the verification method.\n * - The `publicKeyJwk` property is required and represents the public key in JWK format.\n * - The `purposes` property is required and specifies the purposes for which the verification\n * method can be used.\n *\n * @example\n * ```ts\n * const verificationMethod: DidIonVerificationMethod = {\n * id : 'sig',\n * publicKeyJwk : {\n * kty : 'OKP',\n * crv : 'Ed25519',\n * x : 'o40shZrsco-CfEqk6mFsXfcP94ly3Az3gm84PzAUsXo',\n * kid : 'BDp0xim82GswlxnPV8TPtBdUw80wkGIF8gjFbw1x5iQ',\n * },\n * purposes: ['authentication', 'assertionMethod']\n * };\n * ```\n */\nexport interface DidIonVerificationMethod {\n /**\n * Optionally specify the identifier fragment of the verification method.\n *\n * If not specified, the method's ID will be generated from the key's ID or thumbprint.\n *\n * @example\n * ```ts\n * const verificationMethod: DidIonVerificationMethod = {\n * id: 'sig',\n * ...\n * };\n * ```\n */\n id?: string;\n\n /**\n * A public key in JWK format.\n *\n * A JSON Web Key (JWK) that conforms to {@link https://datatracker.ietf.org/doc/html/rfc7517 | RFC 7517}.\n *\n * @example\n * ```ts\n * const verificationMethod: DidIonVerificationMethod = {\n * publicKeyJwk: {\n * kty : \"OKP\",\n * crv : \"X25519\",\n * x : \"7XdJtNmJ9pV_O_3mxWdn6YjiHJ-HhNkdYQARzVU_mwY\",\n * kid : \"xtsuKULPh6VN9fuJMRwj66cDfQyLaxuXHkMlmAe_v6I\"\n * },\n * ...\n * };\n * ```\n */\n publicKeyJwk: Jwk;\n\n /**\n * Specify the purposes for which a verification method is intended to be used in a DID document.\n *\n * The `purposes` property defines the specific\n * {@link DidVerificationRelationship | verification relationships} between the DID subject and\n * the verification method. This enables the verification method to be utilized for distinct\n * actions such as authentication, assertion, key agreement, capability delegation, and others. It\n * is important for verifiers to recognize that a verification method must be associated with the\n * relevant purpose in the DID document to be valid for that specific use case.\n *\n * @example\n * ```ts\n * const verificationMethod: DidIonVerificationMethod = {\n * purposes: ['authentication', 'assertionMethod'],\n * ...\n * };\n * ```\n */\n purposes: (DidVerificationRelationship | keyof typeof DidVerificationRelationship)[];\n}\n\n/**\n * `IonPortableDid` interface extends the {@link PortableDid} interface.\n *\n * It represents a Decentralized Identifier (DID) that is portable and can be used across different\n * domains, including the ION specific recovery and update keys.\n */\nexport interface IonPortableDid extends PortableDid {\n /** The JSON Web Key (JWK) used for recovery purposes. */\n recoveryKey: Jwk;\n\n /** The JSON Web Key (JWK) used for updating the DID. */\n updateKey: Jwk;\n}\n\n/**\n * Enumerates the types of keys that can be used in a DID ION document.\n *\n * The DID ION method supports various cryptographic key types. These key types are essential for\n * the creation and management of DIDs and their associated cryptographic operations like signing\n * and encryption.\n */\nexport enum DidIonRegisteredKeyType {\n /**\n * Ed25519: A public-key signature system using the EdDSA (Edwards-curve Digital Signature\n * Algorithm) and Curve25519.\n */\n Ed25519 = 'Ed25519',\n\n /**\n * secp256k1: A cryptographic curve used for digital signatures in a range of decentralized\n * systems.\n */\n secp256k1 = 'secp256k1',\n\n /**\n * secp256r1: Also known as P-256 or prime256v1, this curve is used for cryptographic operations\n * and is widely supported in various cryptographic libraries and standards.\n */\n secp256r1 = 'secp256r1',\n\n /**\n * X25519: A Diffie-Hellman key exchange algorithm using Curve25519.\n */\n X25519 = 'X25519'\n}\n\n/**\n * Private helper that maps algorithm identifiers to their corresponding DID ION\n * {@link DidIonRegisteredKeyType | registered key type}.\n */\nconst AlgorithmToKeyTypeMap = {\n Ed25519 : DidIonRegisteredKeyType.Ed25519,\n ES256K : DidIonRegisteredKeyType.secp256k1,\n ES256 : DidIonRegisteredKeyType.secp256r1,\n 'P-256' : DidIonRegisteredKeyType.secp256r1,\n secp256k1 : DidIonRegisteredKeyType.secp256k1,\n secp256r1 : DidIonRegisteredKeyType.secp256r1\n} as const;\n\n/**\n * The default node to use as a gateway to the Sidetree newtork when anchoring, updating, and\n * resolving DID documents.\n */\nconst DEFAULT_GATEWAY_URI = 'https://ion.tbd.engineering';\n\n/**\n * The `DidIon` class provides an implementation of the `did:ion` DID method.\n *\n * Features:\n * - DID Creation: Create new `did:ion` DIDs.\n * - DID Key Management: Instantiate a DID object from an existing key in a Key Management System\n * (KMS). If supported by the KMS, a DID's key can be exported to a portable\n * DID format.\n * - DID Resolution: Resolve a `did:ion` to its corresponding DID Document stored in the Sidetree\n * network.\n * - Signature Operations: Sign and verify messages using keys associated with a DID.\n *\n * @see {@link https://identity.foundation/sidetree/spec/ | Sidetree Protocol Specification}\n * @see {@link https://github.com/decentralized-identity/ion/blob/master/docs/design.md | ION Design Document}\n *\n * @example\n * ```ts\n * // DID Creation\n * const did = await DidIon.create();\n *\n * // DID Creation with a KMS\n * const keyManager = new LocalKeyManager();\n * const did = await DidIon.create({ keyManager });\n *\n * // DID Resolution\n * const resolutionResult = await DidIon.resolve({ did: did.uri });\n *\n * // Signature Operations\n * const signer = await did.getSigner();\n * const signature = await signer.sign({ data: new TextEncoder().encode('Message') });\n * const isValid = await signer.verify({ data: new TextEncoder().encode('Message'), signature });\n *\n * // Key Management\n *\n * // Instantiate a DID object for a published DID with existing keys in a KMS\n * const did = await DidIon.fromKeyManager({\n * didUri: 'did:ion:EiAzB7K-xDIKc1csXo5HX2eNBoemK9feNhL3cKwfukYOug',\n * keyManager\n * });\n *\n * // Convert a DID object to a portable format\n * const portableDid = await DidIon.toKeys({ did });\n * ```\n */\n\nexport class DidIon extends DidMethod {\n\n /**\n * Name of the DID method, as defined in the DID ION specification.\n */\n public static methodName = 'ion';\n\n /**\n * Creates a new DID using the `did:ion` method formed from a newly generated key.\n *\n * Notes:\n * - If no `options` are given, by default a new Ed25519 key will be generated.\n *\n * @example\n * ```ts\n * // DID Creation\n * const did = await DidIon.create();\n *\n * // DID Creation with a KMS\n * const keyManager = new LocalKeyManager();\n * const did = await DidIon.create({ keyManager });\n * ```\n *\n * @param params - The parameters for the create operation.\n * @param params.keyManager - Optionally specify a Key Management System (KMS) used to generate\n * keys and sign data.\n * @param params.options - Optional parameters that can be specified when creating a new DID.\n * @returns A Promise resolving to a {@link BearerDid} object representing the new DID.\n */\n public static async create<TKms extends CryptoApi | undefined = undefined>({\n keyManager = new LocalKeyManager(),\n options = {}\n }: {\n keyManager?: TKms;\n options?: DidIonCreateOptions<TKms>;\n } = {}): Promise<BearerDid> {\n // Before processing the create operation, validate DID-method-specific requirements to prevent\n // keys from being generated unnecessarily.\n\n // Check 1: Validate that the algorithm for any given verification method is supported by the\n // DID ION specification.\n if (options.verificationMethods?.some(vm => !(vm.algorithm in AlgorithmToKeyTypeMap))) {\n throw new Error('One or more verification method algorithms are not supported');\n }\n\n // Check 2: Validate that the ID for any given verification method is unique.\n const methodIds = options.verificationMethods?.filter(vm => 'id' in vm).map(vm => vm.id);\n if (methodIds && methodIds.length !== new Set(methodIds).size) {\n throw new Error('One or more verification method IDs are not unique');\n }\n\n // Check 3: Validate that the required properties for any given services are present.\n if (options.services?.some(s => !s.id || !s.type || !s.serviceEndpoint)) {\n throw new Error('One or more services are missing required properties');\n }\n\n // If no verification methods were specified, generate a default Ed25519 verification method.\n const defaultVerificationMethod: DidCreateVerificationMethod<TKms> = {\n algorithm : 'Ed25519' as DidCreateVerificationMethod<TKms>['algorithm'],\n purposes : ['authentication', 'assertionMethod', 'capabilityDelegation', 'capabilityInvocation']\n };\n\n const verificationMethodsToAdd: DidIonVerificationMethod[] = [];\n\n // Generate random key material for additional verification methods, if any.\n for (const vm of options.verificationMethods ?? [defaultVerificationMethod]) {\n // Generate a random key for the verification method.\n const keyUri = await keyManager.generateKey({ algorithm: vm.algorithm });\n const publicKey = await keyManager.getPublicKey({ keyUri });\n\n // Add the verification method to the DID document.\n verificationMethodsToAdd.push({\n id : vm.id,\n publicKeyJwk : publicKey,\n purposes : vm.purposes ?? ['authentication', 'assertionMethod', 'capabilityDelegation', 'capabilityInvocation']\n });\n }\n\n // Generate a random key for the ION Recovery Key. Sidetree requires secp256k1 recovery keys.\n const recoveryKeyUri = await keyManager.generateKey({ algorithm: DidIonRegisteredKeyType.secp256k1 });\n const recoveryKey = await keyManager.getPublicKey({ keyUri: recoveryKeyUri });\n\n // Generate a random key for the ION Update Key. Sidetree requires secp256k1 update keys.\n const updateKeyUri = await keyManager.generateKey({ algorithm: DidIonRegisteredKeyType.secp256k1 });\n const updateKey = await keyManager.getPublicKey({ keyUri: updateKeyUri });\n\n // Compute the Long Form DID URI from the keys and services, if any.\n const longFormDidUri = await DidIonUtils.computeLongFormDidUri({\n recoveryKey,\n updateKey,\n services : options.services ?? [],\n verificationMethods : verificationMethodsToAdd\n });\n\n // Expand the DID URI string to a DID document.\n const { didDocument, didResolutionMetadata } = await DidIon.resolve(longFormDidUri, { gatewayUri: options.gatewayUri });\n if (didDocument === null) {\n throw new Error(`Unable to resolve DID during creation: ${didResolutionMetadata?.error}`);\n }\n\n // Create the BearerDid object, including the \"Short Form\" of the DID URI, the ION update and\n // recovery keys, and specifying that the DID has not yet been published.\n const did = new BearerDid({\n uri : longFormDidUri,\n document : didDocument,\n metadata : {\n published : false,\n canonicalId : longFormDidUri.split(':', 3).join(':'),\n recoveryKey,\n updateKey\n },\n keyManager\n });\n\n // By default, publish the DID document to a Sidetree node unless explicitly disabled.\n if (options.publish ?? true) {\n const registrationResult = await DidIon.publish({ did, gatewayUri: options.gatewayUri });\n did.metadata = registrationResult.didDocumentMetadata;\n }\n\n return did;\n }\n\n /**\n * Given the W3C DID Document of a `did:ion` DID, return the verification method that will be used\n * for signing messages and credentials. If given, the `methodId` parameter is used to select the\n * verification method. If not given, the first verification method in the authentication property\n * in the DID Document is used.\n *\n * @param params - The parameters for the `getSigningMethod` operation.\n * @param params.didDocument - DID Document to get the verification method from.\n * @param params.methodId - ID of the verification method to use for signing.\n * @returns Verification method to use for signing.\n */\n public static async getSigningMethod({ didDocument, methodId }: {\n didDocument: DidDocument;\n methodId?: string;\n }): Promise<DidVerificationMethod> {\n // Verify the DID method is supported.\n const parsedDid = Did.parse(didDocument.id);\n if (parsedDid && parsedDid.method !== this.methodName) {\n throw new DidError(DidErrorCode.MethodNotSupported, `Method not supported: ${parsedDid.method}`);\n }\n\n // Get the verification method with either the specified ID or the first assertion method.\n const verificationMethod = didDocument.verificationMethod?.find(\n vm => vm.id === (methodId ?? didDocument.assertionMethod?.[0])\n );\n\n if (!(verificationMethod && verificationMethod.publicKeyJwk)) {\n throw new DidError(DidErrorCode.InternalError, 'A verification method intended for signing could not be determined from the DID Document');\n }\n\n return verificationMethod;\n }\n\n /**\n * Instantiates a {@link BearerDid} object for the DID ION method from a given {@link PortableDid}.\n *\n * This method allows for the creation of a `BearerDid` object using a previously created DID's\n * key material, DID document, and metadata.\n *\n * @example\n * ```ts\n * // Export an existing BearerDid to PortableDid format.\n * const portableDid = await did.export();\n * // Reconstruct a BearerDid object from the PortableDid.\n * const did = await DidIon.import({ portableDid });\n * ```\n *\n * @param params - The parameters for the import operation.\n * @param params.portableDid - The PortableDid object to import.\n * @param params.keyManager - Optionally specify an external Key Management System (KMS) used to\n * generate keys and sign data. If not given, a new\n * {@link LocalKeyManager} instance will be created and\n * used.\n * @returns A Promise resolving to a `BearerDid` object representing the DID formed from the\n * provided PortableDid.\n * @throws An error if the DID document does not contain any verification methods or the keys for\n * any verification method are missing in the key manager.\n */\n public static async import({ portableDid, keyManager = new LocalKeyManager() }: {\n keyManager?: CryptoApi & KeyImporterExporter<KmsImportKeyParams, KeyIdentifier, KmsExportKeyParams>;\n portableDid: PortableDid;\n }): Promise<BearerDid> {\n // Verify the DID method is supported.\n const parsedDid = Did.parse(portableDid.uri);\n if (parsedDid?.method !== DidIon.methodName) {\n throw new DidError(DidErrorCode.MethodNotSupported, `Method not supported`);\n }\n\n const did = await BearerDid.import({ portableDid, keyManager });\n\n return did;\n }\n\n /**\n * Publishes a DID to a Sidetree node, making it publicly discoverable and resolvable.\n *\n * This method handles the publication of a DID Document associated with a `did:ion` DID to a\n * Sidetree node.\n *\n * @remarks\n * - This method is typically invoked automatically during the creation of a new DID unless the\n * `publish` option is set to `false`.\n * - For existing, unpublished DIDs, it can be used to publish the DID Document to a Sidetree node.\n * - The method relies on the specified Sidetree node to interface with the network.\n *\n * @param params - The parameters for the `publish` operation.\n * @param params.did - The `BearerDid` object representing the DID to be published.\n * @param params.gatewayUri - Optional. The URI of a server involved in executing DID\n * method operations. In the context of publishing, the\n * endpoint is expected to be a Sidetree node. If not\n * specified, a default node is used.\n * @returns A Promise resolving to a boolean indicating whether the publication was successful.\n *\n * @example\n * ```ts\n * // Generate a new DID and keys but explicitly disable publishing.\n * const did = await DidIon.create({ options: { publish: false } });\n * // Publish the DID to the Sidetree network.\n * const isPublished = await DidIon.publish({ did });\n * // `isPublished` is true if the DID was successfully published.\n * ```\n */\n public static async publish({ did, gatewayUri = DEFAULT_GATEWAY_URI }: {\n did: BearerDid;\n gatewayUri?: string;\n }): Promise<DidRegistrationResult> {\n // Construct an ION verification method made up of the id, public key, and purposes from each\n // verification method in the DID document.\n const verificationMethods: DidIonVerificationMethod[] = did.document.verificationMethod?.map(\n vm => ({\n id : vm.id,\n publicKeyJwk : vm.publicKeyJwk!,\n purposes : getVerificationRelationshipsById({ didDocument: did.document, methodId: vm.id })\n })\n ) ?? [];\n\n // Create the ION document.\n const ionDocument = await DidIonUtils.createIonDocument({\n services: did.document.service ?? [],\n verificationMethods\n });\n\n // Construct the ION Create Operation request.\n const createOperation = await DidIonUtils.constructCreateRequest({\n ionDocument,\n recoveryKey : did.metadata.recoveryKey,\n updateKey : did.metadata.updateKey\n });\n\n try {\n // Construct the URL of the SideTree node's operations endpoint.\n const operationsUrl = DidIonUtils.appendPathToUrl({\n baseUrl : gatewayUri,\n path : `/operations`\n });\n\n // Submit the Create Operation to the operations endpoint.\n const response = await fetch(operationsUrl, {\n method : 'POST',\n mode : 'cors',\n headers : { 'Content-Type': 'application/json' },\n body : JSON.stringify(createOperation)\n });\n\n // Return the result of processing the Create operation, including the updated DID metadata\n // with the publishing result.\n return {\n didDocument : did.document,\n didDocumentMetadata : {\n ...did.metadata,\n published: response.ok,\n },\n didRegistrationMetadata: {}\n };\n\n } catch {\n return {\n didDocument : null,\n didDocumentMetadata : {\n published: false,\n },\n didRegistrationMetadata: {\n error : DidErrorCode.InternalError,\n errorMessage : `Failed to publish DID document for: ${did.uri}`\n }\n };\n }\n }\n\n /**\n * Resolves a `did:ion` identifier to its corresponding DID document.\n *\n * This method performs the resolution of a `did:ion` DID, retrieving its DID Document from the\n * Sidetree-based DID overlay network. The process involves querying a Sidetree node to retrieve\n * the DID Document that corresponds to the given DID identifier.\n *\n * @remarks\n * - If a `gatewayUri` option is not specified, a default node is used to access the Sidetree\n * network.\n * - It decodes the DID identifier and retrieves the associated DID Document and metadata.\n * - In case of resolution failure, appropriate error information is returned.\n *\n * @example\n * ```ts\n * const resolutionResult = await DidIon.resolve('did:ion:example');\n * ```\n *\n * @param didUri - The DID to be resolved.\n * @param options - Optional parameters for resolving the DID. Unused by this DID method.\n * @returns A Promise resolving to a {@link DidResolutionResult} object representing the result of the resolution.\n */\n public static async resolve(didUri: string, options: DidResolutionOptions = {}): Promise<DidResolutionResult> {\n // Attempt to parse the DID URI.\n const parsedDid = Did.parse(didUri);\n\n // If parsing failed, the DID is invalid.\n if (!parsedDid) {\n return {\n ...EMPTY_DID_RESOLUTION_RESULT,\n didResolutionMetadata: { error: 'invalidDid' }\n };\n }\n\n // If the DID method is not \"ion\", return an error.\n if (parsedDid.method !== DidIon.methodName) {\n return {\n ...EMPTY_DID_RESOLUTION_RESULT,\n didResolutionMetadata: { error: 'methodNotSupported' }\n };\n }\n\n // To execute the read method operation, use the given gateway URI or a default Sidetree node.\n const gatewayUri = options?.gatewayUri ?? DEFAULT_GATEWAY_URI;\n\n try {\n // Construct the URL to be used in the resolution request.\n const resolutionUrl = DidIonUtils.appendPathToUrl({\n baseUrl : gatewayUri,\n path : `/identifiers/${didUri}`\n });\n\n // Attempt to retrieve the DID document and metadata from the Sidetree node.\n const response = await fetch(resolutionUrl);\n\n // If the DID document was not found, return an error.\n if (!response.ok) {\n throw new DidError(DidErrorCode.NotFound, `Unable to find DID document for: ${didUri}`);\n }\n\n // If the DID document was retrieved successfully, return it.\n const { didDocument, didDocumentMetadata } = await response.json() as DidResolutionResult;\n return {\n ...EMPTY_DID_RESOLUTION_RESULT,\n ...didDocument && { didDocument },\n didDocumentMetadata: {\n published: didDocumentMetadata?.method?.published,\n ...didDocumentMetadata\n }\n };\n\n } catch (error: any) {\n // Rethrow any unexpected errors that are not a `DidError`.\n if (!(error instanceof DidError)) {throw new Error(error);}\n\n // Return a DID Resolution Result with the appropriate error code.\n return {\n ...EMPTY_DID_RESOLUTION_RESULT,\n didResolutionMetadata: {\n error: error.code,\n ...error.message && { errorMessage: error.message }\n }\n };\n }\n }\n}\n\n/**\n * The `DidIonUtils` class provides utility functions to support operations in the DID ION method.\n */\nexport class DidIonUtils {\n /**\n * Appends a specified path to a base URL, ensuring proper formatting of the resulting URL.\n *\n * This method is useful for constructing URLs for accessing various endpoints, such as Sidetree\n * nodes in the ION network. It handles the nuances of URL path concatenation, including the\n * addition or removal of leading/trailing slashes, to create a well-formed URL.\n *\n * @param params - The parameters for URL construction.\n * @param params.baseUrl - The base URL to which the path will be appended.\n * @param params.path - The path to append to the base URL.\n * @returns The fully constructed URL string with the path appended to the base URL.\n */\n public static appendPathToUrl({ baseUrl, path }: {\n baseUrl: string;\n path: string;\n }): string {\n const url = new URL(baseUrl);\n url.pathname = url.pathname.endsWith('/') ? url.pathname : url.pathname + '/';\n url.pathname += path.startsWith('/') ? path.substring(1) : path;\n\n return url.toString();\n }\n\n /**\n * Computes the Long Form DID URI given an ION DID's recovery key, update key, services, and\n * verification methods.\n *\n * @param params - The parameters for computing the Long Form DID URI.\n * @param params.recoveryKey - The ION Recovery Key.\n * @param params.updateKey - The ION Update Key.\n * @param params.services - An array of services associated with the DID.\n * @param params.verificationMethods - An array of verification methods associated with the DID.\n * @returns A Promise resolving to the Long Form DID URI.\n */\n public static async computeLongFormDidUri({ recoveryKey, updateKey, services, verificationMethods }: {\n recoveryKey: Jwk;\n updateKey: Jwk;\n services: DidService[];\n verificationMethods: DidIonVerificationMethod[];\n }): Promise<string> {\n // Create the ION document.\n const ionDocument = await DidIonUtils.createIonDocument({ services, verificationMethods });\n\n // Normalize JWK to onnly include specific members and in lexicographic order.\n const normalizedRecoveryKey = DidIonUtils.normalizeJwk(recoveryKey);\n const normalizedUpdateKey = DidIonUtils.normalizeJwk(updateKey);\n\n // Compute the Long Form DID URI.\n const longFormDidUri = await IonDid.createLongFormDid({\n document : ionDocument,\n recoveryKey : normalizedRecoveryKey as JwkEs256k,\n updateKey : normalizedUpdateKey as JwkEs256k\n });\n\n return longFormDidUri;\n }\n\n /**\n * Constructs a Sidetree Create Operation request for a DID document within the ION network.\n *\n * This method prepares the necessary payload for submitting a Create Operation to a Sidetree\n * node, encapsulating the details of the DID document, recovery key, and update key.\n *\n * @param params - Parameters required to construct the Create Operation request.\n * @param params.ionDocument - The DID document model containing public keys and service endpoints.\n * @param params.recoveryKey - The recovery public key in JWK format.\n * @param params.updateKey - The update public key in JWK format.\n * @returns A promise resolving to the ION Create Operation request model, ready for submission to a Sidetree node.\n */\n public static async constructCreateRequest({ ionDocument, recoveryKey, updateKey }: {\n ionDocument: IonDocumentModel,\n recoveryKey: Jwk,\n updateKey: Jwk\n }): Promise<DidIonCreateRequest> {\n // Create an ION DID create request operation.\n const createRequest = await IonRequest.createCreateRequest({\n document : ionDocument,\n recoveryKey : DidIonUtils.normalizeJwk(recoveryKey) as JwkEs256k,\n updateKey : DidIonUtils.normalizeJwk(updateKey) as JwkEs256k\n }) as DidIonCreateRequest;\n\n return createRequest;\n }\n\n /**\n * Assembles an ION document model from provided services and verification methods\n *\n * This model serves as the foundation for a DID document in the ION network, facilitating the\n * creation and management of decentralized identities. It translates service endpoints and\n * public keys into a format compatible with the Sidetree protocol, ensuring the resulting DID\n * document adheres to the required specifications for ION DIDs. This method is essential for\n * constructing the payload needed to register or update DIDs within the ION network.\n *\n * @param params - The parameters containing the services and verification methods to include in the ION document.\n * @param params.services - A list of service endpoints to be included in the DID document, specifying ways to interact with the DID subject.\n * @param params.verificationMethods - A list of verification methods to be included, detailing the\n * cryptographic keys and their intended uses within the DID document.\n * @returns A Promise resolving to an `IonDocumentModel`, ready for use in Sidetree operations like DID creation and updates.\n */\n public static async createIonDocument({ services, verificationMethods }: {\n services: DidService[];\n verificationMethods: DidIonVerificationMethod[]\n }): Promise<IonDocumentModel> {\n /**\n * STEP 1: Convert verification methods to ION SDK format.\n */\n const ionPublicKeys: IonPublicKeyModel[] = [];\n\n for (const vm of verificationMethods) {\n // Use the given ID, the key's ID, or the key's thumbprint as the verification method ID.\n let methodId = vm.id ?? vm.publicKeyJwk.kid ?? await computeJwkThumbprint({ jwk: vm.publicKeyJwk });\n methodId = `${methodId.split('#').pop()}`; // Remove fragment prefix, if any.\n\n // Convert public key JWK to ION format.\n const publicKey: IonPublicKeyModel = {\n id : methodId,\n publicKeyJwk : DidIonUtils.normalizeJwk(vm.publicKeyJwk),\n purposes : vm.purposes as IonPublicKeyPurpose[],\n type : 'JsonWebKey2020'\n };\n\n ionPublicKeys.push(publicKey);\n }\n\n /**\n * STEP 2: Convert service entries, if any, to ION SDK format.\n */\n const ionServices = services.map(service => ({\n ...service,\n id: `${service.id.split('#').pop()}` // Remove fragment prefix, if any.\n }));\n\n /**\n * STEP 3: Format as ION document.\n */\n const ionDocumentModel: IonDocumentModel = {\n publicKeys : ionPublicKeys,\n services : ionServices\n };\n\n return ionDocumentModel;\n }\n\n /**\n * Normalize the given JWK to include only specific members and in lexicographic order.\n *\n * @param jwk - The JWK to normalize.\n * @returns The normalized JWK.\n */\n private static normalizeJwk(jwk: Jwk): Jwk {\n const keyType = jwk.kty;\n let normalizedJwk: Jwk;\n\n if (keyType === 'EC') {\n normalizedJwk = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y };\n } else if (keyType === 'oct') {\n normalizedJwk = { k: jwk.k, kty: jwk.kty };\n } else if (keyType === 'OKP') {\n normalizedJwk = { crv: jwk.crv, kty: jwk.kty, x: jwk.x };\n } else if (keyType === 'RSA') {\n normalizedJwk = { e: jwk.e, kty: jwk.kty, n: jwk.n };\n } else {\n throw new Error(`Unsupported key type: ${keyType}`);\n }\n\n return normalizedJwk;\n }\n}", null, null, null, null, "// @ts-check\n\nimport { rfc4648 } from './base.js'\n\nexport const base64 = rfc4648({\n prefix: 'm',\n name: 'base64',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/',\n bitsPerChar: 6\n})\n\nexport const base64pad = rfc4648({\n prefix: 'M',\n name: 'base64pad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=',\n bitsPerChar: 6\n})\n\nexport const base64url = rfc4648({\n prefix: 'u',\n name: 'base64url',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_',\n bitsPerChar: 6\n})\n\nexport const base64urlpad = rfc4648({\n prefix: 'U',\n name: 'base64urlpad',\n alphabet: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=',\n bitsPerChar: 6\n})\n", "import basex from '../../vendor/base-x.js'\nimport { coerce } from '../bytes.js'\n// Linter can't see that API is used in types.\n// eslint-disable-next-line\nimport * as API from './interface.js'\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 *\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseEncoder<Prefix>}\n * @implements {API.BaseEncoder}\n */\nclass Encoder {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(bytes:Uint8Array) => string} baseEncode\n */\n constructor (name, prefix, baseEncode) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n }\n\n /**\n * @param {Uint8Array} bytes\n * @returns {API.Multibase<Prefix>}\n */\n encode (bytes) {\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 * @template {string} Prefix\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 *\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseDecoder<Prefix>}\n * @implements {API.UnibaseDecoder<Prefix>}\n * @implements {API.BaseDecoder}\n */\nclass Decoder {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(text:string) => Uint8Array} baseDecode\n */\n constructor (name, prefix, baseDecode) {\n this.name = name\n this.prefix = prefix\n /* c8 ignore next 3 */\n if (prefix.codePointAt(0) === undefined) {\n throw new Error('Invalid prefix character')\n }\n /** @private */\n this.prefixCodePoint = /** @type {number} */ (prefix.codePointAt(0))\n this.baseDecode = baseDecode\n }\n\n /**\n * @param {string} text\n */\n decode (text) {\n if (typeof text === 'string') {\n if (text.codePointAt(0) !== this.prefixCodePoint) {\n throw Error(`Unable to decode multibase string ${JSON.stringify(text)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`)\n }\n return this.baseDecode(text.slice(this.prefix.length))\n } else {\n throw Error('Can only multibase decode strings')\n }\n }\n\n /**\n * @template {string} OtherPrefix\n * @param {API.UnibaseDecoder<OtherPrefix>|ComposedDecoder<OtherPrefix>} decoder\n * @returns {ComposedDecoder<Prefix|OtherPrefix>}\n */\n or (decoder) {\n return or(this, decoder)\n }\n}\n\n/**\n * @template {string} Prefix\n * @typedef {Record<Prefix, API.UnibaseDecoder<Prefix>>} Decoders\n */\n\n/**\n * @template {string} Prefix\n * @implements {API.MultibaseDecoder<Prefix>}\n * @implements {API.CombobaseDecoder<Prefix>}\n */\nclass ComposedDecoder {\n /**\n * @param {Decoders<Prefix>} decoders\n */\n constructor (decoders) {\n this.decoders = decoders\n }\n\n /**\n * @template {string} OtherPrefix\n * @param {API.UnibaseDecoder<OtherPrefix>|ComposedDecoder<OtherPrefix>} decoder\n * @returns {ComposedDecoder<Prefix|OtherPrefix>}\n */\n or (decoder) {\n return or(this, decoder)\n }\n\n /**\n * @param {string} input\n * @returns {Uint8Array}\n */\n decode (input) {\n const prefix = /** @type {Prefix} */ (input[0])\n const decoder = this.decoders[prefix]\n if (decoder) {\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\n/**\n * @template {string} L\n * @template {string} R\n * @param {API.UnibaseDecoder<L>|API.CombobaseDecoder<L>} left\n * @param {API.UnibaseDecoder<R>|API.CombobaseDecoder<R>} right\n * @returns {ComposedDecoder<L|R>}\n */\nexport const or = (left, right) => new ComposedDecoder(/** @type {Decoders<L|R>} */({\n ...(left.decoders || { [/** @type API.UnibaseDecoder<L> */(left).prefix]: left }),\n ...(right.decoders || { [/** @type API.UnibaseDecoder<R> */(right).prefix]: right })\n}))\n\n/**\n * @class\n * @template {string} Base\n * @template {string} Prefix\n * @implements {API.MultibaseCodec<Prefix>}\n * @implements {API.MultibaseEncoder<Prefix>}\n * @implements {API.MultibaseDecoder<Prefix>}\n * @implements {API.BaseCodec}\n * @implements {API.BaseEncoder}\n * @implements {API.BaseDecoder}\n */\nexport class Codec {\n /**\n * @param {Base} name\n * @param {Prefix} prefix\n * @param {(bytes:Uint8Array) => string} baseEncode\n * @param {(text:string) => Uint8Array} baseDecode\n */\n constructor (name, prefix, baseEncode, baseDecode) {\n this.name = name\n this.prefix = prefix\n this.baseEncode = baseEncode\n this.baseDecode = baseDecode\n this.encoder = new Encoder(name, prefix, baseEncode)\n this.decoder = new Decoder(name, prefix, baseDecode)\n }\n\n /**\n * @param {Uint8Array} input\n */\n encode (input) {\n return this.encoder.encode(input)\n }\n\n /**\n * @param {string} input\n */\n decode (input) {\n return this.decoder.decode(input)\n }\n}\n\n/**\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {(bytes:Uint8Array) => string} options.encode\n * @param {(input:string) => Uint8Array} options.decode\n * @returns {Codec<Base, Prefix>}\n */\nexport const from = ({ name, prefix, encode, decode }) =>\n new Codec(name, prefix, encode, decode)\n\n/**\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {string} options.alphabet\n * @returns {Codec<Base, Prefix>}\n */\nexport const baseX = ({ prefix, name, alphabet }) => {\n const { encode, decode } = basex(alphabet, name)\n return from({\n prefix,\n name,\n encode,\n /**\n * @param {string} text\n */\n decode: text => coerce(decode(text))\n })\n}\n\n/**\n * @param {string} string\n * @param {string} alphabet\n * @param {number} bitsPerChar\n * @param {string} name\n * @returns {Uint8Array}\n */\nconst decode = (string, alphabet, bitsPerChar, name) => {\n // Build the character lookup table:\n /** @type {Record<string, number>} */\n const codes = {}\n for (let i = 0; i < alphabet.length; ++i) {\n codes[alphabet[i]] = i\n }\n\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 = codes[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))) {\n throw new SyntaxError('Unexpected end of data')\n }\n\n return out\n}\n\n/**\n * @param {Uint8Array} data\n * @param {string} alphabet\n * @param {number} bitsPerChar\n * @returns {string}\n */\nconst encode = (data, alphabet, bitsPerChar) => {\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) {\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) {\n out += '='\n }\n }\n\n return out\n}\n\n/**\n * RFC4648 Factory\n *\n * @template {string} Base\n * @template {string} Prefix\n * @param {object} options\n * @param {Base} options.name\n * @param {Prefix} options.prefix\n * @param {string} options.alphabet\n * @param {number} options.bitsPerChar\n */\nexport const rfc4648 = ({ name, prefix, bitsPerChar, alphabet }) => {\n return from({\n prefix,\n name,\n encode (input) {\n return encode(input, alphabet, bitsPerChar)\n },\n decode (input) {\n return decode(input, alphabet, bitsPerChar, name)\n }\n })\n}\n", "// 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.\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 function encode (source) {\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 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 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", "const empty = new Uint8Array(0)\n\n/**\n * @param {Uint8Array} d\n */\nconst toHex = d => d.reduce((hex, byte) => hex + byte.toString(16).padStart(2, '0'), '')\n\n/**\n * @param {string} hex\n */\nconst fromHex = hex => {\n const hexes = hex.match(/../g)\n return hexes ? new Uint8Array(hexes.map(b => parseInt(b, 16))) : empty\n}\n\n/**\n * @param {Uint8Array} aa\n * @param {Uint8Array} bb\n */\nconst equals = (aa, bb) => {\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/**\n * @param {ArrayBufferView|ArrayBuffer|Uint8Array} o\n * @returns {Uint8Array}\n */\nconst coerce = o => {\n if (o instanceof Uint8Array && o.constructor.name === 'Uint8Array') return o\n if (o instanceof ArrayBuffer) return new Uint8Array(o)\n if (ArrayBuffer.isView(o)) {\n return new Uint8Array(o.buffer, o.byteOffset, o.byteLength)\n }\n throw new Error('Unknown type, must be binary type')\n}\n\n/**\n * @param {any} o\n * @returns {o is ArrayBuffer|ArrayBufferView}\n */\nconst isBinary = o =>\n o instanceof ArrayBuffer || ArrayBuffer.isView(o)\n\n/**\n * @param {string} str\n * @returns {Uint8Array}\n */\nconst fromString = str => (new TextEncoder()).encode(str)\n\n/**\n * @param {Uint8Array} b\n * @returns {string}\n */\nconst toString = b => (new TextDecoder()).decode(b)\n\nexport { equals, coerce, isBinary, fromHex, toHex, fromString, toString, empty }\n", "// this is dummy module overlayed by interface.ts\n", null, null, null, null, null, "import { coerce, equals as equalBytes } from '../bytes.js'\nimport * as varint from '../varint.js'\n\n/**\n * Creates a multihash digest.\n *\n * @template {number} Code\n * @param {Code} code\n * @param {Uint8Array} digest\n */\nexport const create = (code, digest) => {\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 *\n * @param {Uint8Array} multihash\n * @returns {MultihashDigest}\n */\nexport const decode = (multihash) => {\n const bytes = coerce(multihash)\n const [code, sizeOffset] = varint.decode(bytes)\n const [size, digestOffset] = varint.decode(bytes.subarray(sizeOffset))\n const digest = bytes.subarray(sizeOffset + digestOffset)\n\n if (digest.byteLength !== size) {\n throw new Error('Incorrect length')\n }\n\n return new Digest(code, size, digest, bytes)\n}\n\n/**\n * @param {MultihashDigest} a\n * @param {unknown} b\n * @returns {b is MultihashDigest}\n */\nexport const equals = (a, b) => {\n if (a === b) {\n return true\n } else {\n const data = /** @type {{code?:unknown, size?:unknown, bytes?:unknown}} */(b)\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 * @typedef {import('./interface.js').MultihashDigest} MultihashDigest\n */\n\n/**\n * Represents a multihash digest which carries information about the\n * hashing algorithm and an actual hash digest.\n *\n * @template {number} Code\n * @template {number} Size\n * @class\n * @implements {MultihashDigest}\n */\nexport class Digest {\n /**\n * Creates a multihash digest.\n *\n * @param {Code} code\n * @param {Size} size\n * @param {Uint8Array} digest\n * @param {Uint8Array} bytes\n */\n constructor (code, size, digest, bytes) {\n this.code = code\n this.size = size\n this.digest = digest\n this.bytes = bytes\n }\n}\n", "import varint from '../vendor/varint.js'\n\n/**\n * @param {Uint8Array} data\n * @param {number} [offset=0]\n * @returns {[number, number]}\n */\nexport const decode = (data, offset = 0) => {\n const code = varint.decode(data, offset)\n return [code, varint.decode.bytes]\n}\n\n/**\n * @param {number} int\n * @param {Uint8Array} target\n * @param {number} [offset=0]\n */\nexport const encodeTo = (int, target, offset = 0) => {\n varint.encode(int, target, offset)\n return target\n}\n\n/**\n * @param {number} int\n * @returns {number}\n */\nexport const encodingLength = (int) => {\n return varint.encodingLength(int)\n}\n", "var encode_1 = encode;\n\nvar MSB = 0x80\n , REST = 0x7F\n , MSBALL = ~REST\n , INT = Math.pow(2, 31);\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 encode.bytes = offset - oldOffset + 1;\n \n return out\n}\n\nvar decode = read;\n\nvar MSB$1 = 0x80\n , REST$1 = 0x7F;\n\nfunction read(buf, offset) {\n var res = 0\n , offset = offset || 0\n , shift = 0\n , counter = offset\n , b\n , l = buf.length;\n\n do {\n if (counter >= l) {\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 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 (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", "/* global crypto */\n\nimport { from } from './hasher.js'\n\n/**\n * @param {AlgorithmIdentifier} name\n */\nconst sha = name =>\n /**\n * @param {Uint8Array} data\n */\n async data => new Uint8Array(await crypto.subtle.digest(name, data))\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: sha('SHA-256')\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: sha('SHA-512')\n})\n", "import * as Digest from './digest.js'\n\n/**\n * @template {string} Name\n * @template {number} Code\n * @param {object} options\n * @param {Name} options.name\n * @param {Code} options.code\n * @param {(input: Uint8Array) => Await<Uint8Array>} options.encode\n */\nexport const from = ({ name, code, encode }) => new Hasher(name, code, encode)\n\n/**\n * Hasher represents a hashing algorithm implementation that produces as\n * `MultihashDigest`.\n *\n * @template {string} Name\n * @template {number} Code\n * @class\n * @implements {MultihashHasher<Code>}\n */\nexport class Hasher {\n /**\n *\n * @param {Name} name\n * @param {Code} code\n * @param {(input: Uint8Array) => Await<Uint8Array>} encode\n */\n constructor (name, code, encode) {\n this.name = name\n this.code = code\n this.encode = encode\n }\n\n /**\n * @param {Uint8Array} input\n * @returns {Await<Digest.Digest<Code, number>>}\n */\n digest (input) {\n if (input instanceof Uint8Array) {\n const result = this.encode(input)\n return result instanceof Uint8Array\n ? Digest.create(this.code, result)\n /* c8 ignore next 1 */\n : result.then(digest => Digest.create(this.code, digest))\n } else {\n throw Error('Unknown type, must be binary type')\n /* c8 ignore next 1 */\n }\n }\n}\n\n/**\n * @template {number} Alg\n * @typedef {import('./interface.js').MultihashHasher} MultihashHasher\n */\n\n/**\n * @template T\n * @typedef {Promise<T>|T} Await\n */\n", null, null, null, null, "/*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */\nconst P = 2n ** 255n - 19n; // ed25519 is twisted edwards curve\nconst N = 2n ** 252n + 27742317777372353535851937790883648493n; // curve's (group) order\nconst Gx = 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an; // base point x\nconst Gy = 0x6666666666666666666666666666666666666666666666666666666666666658n; // base point y\nconst CURVE = {\n a: -1n,\n d: 37095705934669439343138083508754565189542113879843219016388785533085940283555n,\n p: P, n: N, h: 8, Gx, Gy // field prime, curve (group) order, cofactor\n};\nconst err = (m = '') => { throw new Error(m); }; // error helper, messes-up stack trace\nconst str = (s) => typeof s === 'string'; // is string\nconst au8 = (a, l) => // is Uint8Array (of specific length)\n !(a instanceof Uint8Array) || (typeof l === 'number' && l > 0 && a.length !== l) ?\n err('Uint8Array expected') : a;\nconst u8n = (data) => new Uint8Array(data); // creates Uint8Array\nconst toU8 = (a, len) => au8(str(a) ? h2b(a) : u8n(a), len); // norm(hex/u8a) to u8a\nconst mod = (a, b = P) => { let r = a % b; return r >= 0n ? r : b + r; }; // mod division\nconst isPoint = (p) => (p instanceof Point ? p : err('Point expected')); // is xyzt point\nlet Gpows = undefined; // precomputes for base point G\nclass Point {\n constructor(ex, ey, ez, et) {\n this.ex = ex;\n this.ey = ey;\n this.ez = ez;\n this.et = et;\n }\n static fromAffine(p) { return new Point(p.x, p.y, 1n, mod(p.x * p.y)); }\n static fromHex(hex, strict = true) {\n const { d } = CURVE;\n hex = toU8(hex, 32);\n const normed = hex.slice(); // copy the array to not mess it up\n normed[31] = hex[31] & ~0x80; // adjust first LE byte = last BE byte\n const y = b2n_LE(normed); // decode as little-endian, convert to num\n if (y === 0n) { // y=0 is valid, proceed\n }\n else {\n if (strict && !(0n < y && y < P))\n err('bad y coord 1'); // strict=true [1..P-1]\n if (!strict && !(0n < y && y < 2n ** 256n))\n err('bad y coord 2'); // strict=false [1..2^256-1]\n }\n const y2 = mod(y * y); // y\u00B2\n const u = mod(y2 - 1n); // u=y\u00B2-1\n const v = mod(d * y2 + 1n); // v=dy\u00B2+1\n let { isValid, value: x } = uvRatio(u, v); // (uv\u00B3)(uv\u2077)^(p-5)/8; square root\n if (!isValid)\n err('bad y coordinate 3'); // not square root: bad point\n const isXOdd = (x & 1n) === 1n; // adjust sign of x coordinate\n const isHeadOdd = (hex[31] & 0x80) !== 0;\n if (isHeadOdd !== isXOdd)\n x = mod(-x);\n return new Point(x, y, 1n, mod(x * y)); // Z=1, T=xy\n }\n get x() { return this.toAffine().x; } // .x, .y will call expensive toAffine.\n get y() { return this.toAffine().y; } // Should be used with care.\n equals(other) {\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = isPoint(other); // isPoint() checks class equality\n const X1Z2 = mod(X1 * Z2), X2Z1 = mod(X2 * Z1);\n const Y1Z2 = mod(Y1 * Z2), Y2Z1 = mod(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() { return this.equals(I); }\n negate() {\n return new Point(mod(-this.ex), this.ey, this.ez, mod(-this.et));\n }\n double() {\n const { ex: X1, ey: Y1, ez: Z1 } = this; // Cost: 4M + 4S + 1*a + 6add + 1*2\n const { a } = CURVE; // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n const A = mod(X1 * X1);\n const B = mod(Y1 * Y1);\n const C = mod(2n * mod(Z1 * Z1));\n const D = mod(a * A);\n const x1y1 = X1 + Y1;\n const E = mod(mod(x1y1 * x1y1) - A - B);\n const G = D + B;\n const F = G - C;\n const H = D - B;\n const X3 = mod(E * F);\n const Y3 = mod(G * H);\n const T3 = mod(E * H);\n const Z3 = mod(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n add(other) {\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this; // Cost: 8M + 1*k + 8add + 1*2.\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = isPoint(other); // doesn't check if other on-curve\n const { a, d } = CURVE; // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-3\n const A = mod(X1 * X2);\n const B = mod(Y1 * Y2);\n const C = mod(T1 * d * T2);\n const D = mod(Z1 * Z2);\n const E = mod((X1 + Y1) * (X2 + Y2) - A - B);\n const F = mod(D - C);\n const G = mod(D + C);\n const H = mod(B - a * A);\n const X3 = mod(E * F);\n const Y3 = mod(G * H);\n const T3 = mod(E * H);\n const Z3 = mod(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n mul(n, safe = true) {\n if (n === 0n)\n return safe === true ? err('cannot multiply by 0') : I;\n if (!(typeof n === 'bigint' && 0n < n && n < N))\n err('invalid scalar, must be < L');\n if (!safe && this.is0() || n === 1n)\n return this; // safe=true bans 0. safe=false allows 0.\n if (this.equals(G))\n return wNAF(n).p; // use wNAF precomputes for base points\n let p = I, f = G; // init result point & fake point\n for (let d = this; n > 0n; d = d.double(), n >>= 1n) { // double-and-add ladder\n if (n & 1n)\n p = p.add(d); // if bit is present, add to point\n else if (safe)\n f = f.add(d); // if not, add to fake for timing safety\n }\n return p;\n }\n multiply(scalar) { return this.mul(scalar); } // Aliases for compatibilty\n clearCofactor() { return this.mul(BigInt(CURVE.h), false); } // multiply by cofactor\n isSmallOrder() { return this.clearCofactor().is0(); } // check if P is small order\n isTorsionFree() {\n let p = this.mul(N / 2n, false).double(); // ensures the point is not \"bad\".\n if (N % 2n)\n p = p.add(this); // P^(N+1) // P*N == (P*(N/2))*2+P\n return p.is0();\n }\n toAffine() {\n const { ex: x, ey: y, ez: z } = this; // (x, y, z, t) \u220B (x=x/z, y=y/z, t=xy)\n if (this.is0())\n return { x: 0n, y: 0n }; // fast-path for zero point\n const iz = invert(z); // z^-1: invert z\n if (mod(z * iz) !== 1n)\n err('invalid inverse'); // (z * z^-1) must be 1, otherwise bad math\n return { x: mod(x * iz), y: mod(y * iz) }; // x = x*z^-1; y = y*z^-1\n }\n toRawBytes() {\n const { x, y } = this.toAffine(); // convert to affine 2d point\n const b = n2b_32LE(y); // encode number to 32 bytes\n b[31] |= x & 1n ? 0x80 : 0; // store sign in first LE byte\n return b;\n }\n toHex() { return b2h(this.toRawBytes()); } // encode to hex string\n}\nPoint.BASE = new Point(Gx, Gy, 1n, mod(Gx * Gy)); // Generator / Base point\nPoint.ZERO = new Point(0n, 1n, 1n, 0n); // Identity / Zero point\nconst { BASE: G, ZERO: I } = Point; // Generator, identity points\nconst padh = (num, pad) => num.toString(16).padStart(pad, '0');\nconst b2h = (b) => Array.from(b).map(e => padh(e, 2)).join(''); // bytes to hex\nconst h2b = (hex) => {\n const l = hex.length; // error if not string,\n if (!str(hex) || l % 2)\n err('hex invalid 1'); // or has odd length like 3, 5.\n const arr = u8n(l / 2); // create result array\n for (let i = 0; i < arr.length; i++) {\n const j = i * 2;\n const h = hex.slice(j, j + 2); // hexByte. slice is faster than substr\n const b = Number.parseInt(h, 16); // byte, created from string part\n if (Number.isNaN(b) || b < 0)\n err('hex invalid 2'); // byte must be valid 0 <= byte < 256\n arr[i] = b;\n }\n return arr;\n};\nconst n2b_32LE = (num) => h2b(padh(num, 32 * 2)).reverse(); // number to bytes LE\nconst b2n_LE = (b) => BigInt('0x' + b2h(u8n(au8(b)).reverse())); // bytes LE to num\nconst concatB = (...arrs) => {\n const r = u8n(arrs.reduce((sum, a) => sum + au8(a).length, 0)); // create u8a of summed length\n let pad = 0; // walk through each array,\n arrs.forEach(a => { r.set(a, pad); pad += a.length; }); // ensure they have proper type\n return r;\n};\nconst invert = (num, md = P) => {\n if (num === 0n || md <= 0n)\n err('no inverse n=' + num + ' mod=' + md); // no neg exponent for now\n let a = mod(num, md), b = md, x = 0n, y = 1n, u = 1n, v = 0n;\n while (a !== 0n) { // uses euclidean gcd algorithm\n const q = b / a, r = b % a; // not constant-time\n const m = x - u * q, n = y - v * q;\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n return b === 1n ? mod(x, md) : err('no inverse'); // b is gcd at this point\n};\nconst pow2 = (x, power) => {\n let r = x;\n while (power-- > 0n) {\n r *= r;\n r %= P;\n }\n return r;\n};\nconst pow_2_252_3 = (x) => {\n const x2 = (x * x) % P; // x^2, bits 1\n const b2 = (x2 * x) % P; // x^3, bits 11\n const b4 = (pow2(b2, 2n) * b2) % P; // x^(2^4-1), bits 1111\n const b5 = (pow2(b4, 1n) * x) % P; // x^(2^5-1), bits 11111\n const b10 = (pow2(b5, 5n) * b5) % P; // x^(2^10)\n const b20 = (pow2(b10, 10n) * b10) % P; // x^(2^20)\n const b40 = (pow2(b20, 20n) * b20) % P; // x^(2^40)\n const b80 = (pow2(b40, 40n) * b40) % P; // x^(2^80)\n const b160 = (pow2(b80, 80n) * b80) % P; // x^(2^160)\n const b240 = (pow2(b160, 80n) * b80) % P; // x^(2^240)\n const b250 = (pow2(b240, 10n) * b10) % P; // x^(2^250)\n const pow_p_5_8 = (pow2(b250, 2n) * x) % P; // < To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n};\nconst RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n; // \u221A-1\nconst uvRatio = (u, v) => {\n const v3 = mod(v * v * v); // v\u00B3\n const v7 = mod(v3 * v3 * v); // v\u2077\n const pow = pow_2_252_3(u * v7).pow_p_5_8; // (uv\u2077)^(p-5)/8\n let x = mod(u * v3 * pow); // (uv\u00B3)(uv\u2077)^(p-5)/8\n const vx2 = mod(v * x * x); // vx\u00B2\n const root1 = x; // First root candidate\n const root2 = mod(x * RM1); // Second root candidate; RM1 is \u221A-1\n const useRoot1 = vx2 === u; // If vx\u00B2 = u (mod p), x is a square root\n const useRoot2 = vx2 === mod(-u); // If vx\u00B2 = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === mod(-u * RM1); // There is no valid root, vx\u00B2 = -u\u221A-1\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2; // We return root2 anyway, for const-time\n if ((mod(x) & 1n) === 1n)\n x = mod(-x); // edIsNegative\n return { isValid: useRoot1 || useRoot2, value: x };\n};\nconst modL_LE = (hash) => mod(b2n_LE(hash), N); // modulo L; but little-endian\nlet _shaS;\nconst sha512a = (...m) => etc.sha512Async(...m); // Async SHA512\nconst sha512s = (...m) => // Sync SHA512, not set by default\n typeof _shaS === 'function' ? _shaS(...m) : err('etc.sha512Sync not set');\nconst hash2extK = (hashed) => {\n const head = hashed.slice(0, 32); // slice creates a copy, unlike subarray\n head[0] &= 248; // Clamp bits: 0b1111_1000,\n head[31] &= 127; // 0b0111_1111,\n head[31] |= 64; // 0b0100_0000\n const prefix = hashed.slice(32, 64); // private key \"prefix\"\n const scalar = modL_LE(head); // modular division over curve order\n const point = G.mul(scalar); // public key point\n const pointBytes = point.toRawBytes(); // point serialized to Uint8Array\n return { head, prefix, scalar, point, pointBytes };\n};\n// RFC8032 5.1.5; getPublicKey async, sync. Hash priv key and extract point.\nconst getExtendedPublicKeyAsync = (priv) => sha512a(toU8(priv, 32)).then(hash2extK);\nconst getExtendedPublicKey = (priv) => hash2extK(sha512s(toU8(priv, 32)));\nconst getPublicKeyAsync = (priv) => getExtendedPublicKeyAsync(priv).then(p => p.pointBytes);\nconst getPublicKey = (priv) => getExtendedPublicKey(priv).pointBytes;\nfunction hashFinish(asynchronous, res) {\n if (asynchronous)\n return sha512a(res.hashable).then(res.finish);\n return res.finish(sha512s(res.hashable));\n}\nconst _sign = (e, rBytes, msg) => {\n const { pointBytes: P, scalar: s } = e;\n const r = modL_LE(rBytes); // r was created outside, reduce it modulo L\n const R = G.mul(r).toRawBytes(); // R = [r]B\n const hashable = concatB(R, P, msg); // dom2(F, C) || R || A || PH(M)\n const finish = (hashed) => {\n const S = mod(r + modL_LE(hashed) * s, N); // S = (r + k * s) mod L; 0 <= s < l\n return au8(concatB(R, n2b_32LE(S)), 64); // 64-byte sig: 32b R.x + 32b LE(S)\n };\n return { hashable, finish };\n};\nconst signAsync = async (msg, privKey) => {\n const m = toU8(msg); // RFC8032 5.1.6: sign msg with key async\n const e = await getExtendedPublicKeyAsync(privKey); // pub,prfx\n const rBytes = await sha512a(e.prefix, m); // r = SHA512(dom2(F, C) || prefix || PH(M))\n return hashFinish(true, _sign(e, rBytes, m)); // gen R, k, S, then 64-byte signature\n};\nconst sign = (msg, privKey) => {\n const m = toU8(msg); // RFC8032 5.1.6: sign msg with key sync\n const e = getExtendedPublicKey(privKey); // pub,prfx\n const rBytes = sha512s(e.prefix, m); // r = SHA512(dom2(F, C) || prefix || PH(M))\n return hashFinish(false, _sign(e, rBytes, m)); // gen R, k, S, then 64-byte signature\n};\nconst _verify = (sig, msg, pub) => {\n msg = toU8(msg); // Message hex str/Bytes\n sig = toU8(sig, 64); // Signature hex str/Bytes, must be 64 bytes\n const A = Point.fromHex(pub, false); // public key A decoded\n const R = Point.fromHex(sig.slice(0, 32), false); // 0 <= R < 2^256: ZIP215 R can be >= P\n const s = b2n_LE(sig.slice(32, 64)); // Decode second half as an integer S\n const SB = G.mul(s, false); // in the range 0 <= s < L\n const hashable = concatB(R.toRawBytes(), A.toRawBytes(), msg); // dom2(F, C) || R || A || PH(M)\n const finish = (hashed) => {\n const k = modL_LE(hashed); // decode in little-endian, modulo L\n const RkA = R.add(A.mul(k, false)); // [8]R + [8][k]A'\n return RkA.add(SB.negate()).clearCofactor().is0(); // [8][S]B = [8]R + [8][k]A'\n };\n return { hashable, finish };\n};\n// RFC8032 5.1.7: verification async, sync\nconst verifyAsync = async (s, m, p) => hashFinish(true, _verify(s, m, p));\nconst verify = (s, m, p) => hashFinish(false, _verify(s, m, p));\nconst cr = () => // We support: 1) browsers 2) node.js 19+\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\nconst etc = {\n bytesToHex: b2h, hexToBytes: h2b, concatBytes: concatB,\n mod, invert,\n randomBytes: (len) => {\n const crypto = cr(); // Can be shimmed in node.js <= 18 to prevent error:\n // import { webcrypto } from 'node:crypto';\n // if (!globalThis.crypto) globalThis.crypto = webcrypto;\n if (!crypto)\n err('crypto.getRandomValues must be defined');\n return crypto.getRandomValues(u8n(len));\n },\n sha512Async: async (...messages) => {\n const crypto = cr();\n if (!crypto)\n err('crypto.subtle or etc.sha512Async must be defined');\n const m = concatB(...messages);\n return u8n(await crypto.subtle.digest('SHA-512', m.buffer));\n },\n sha512Sync: undefined, // Actual logic below\n};\nObject.defineProperties(etc, { sha512Sync: {\n configurable: false, get() { return _shaS; }, set(f) { if (!_shaS)\n _shaS = f; },\n } });\nconst utils = {\n getExtendedPublicKeyAsync, getExtendedPublicKey,\n randomPrivateKey: () => etc.randomBytes(32),\n precompute(w = 8, p = G) { p.multiply(3n); return p; }, // no-op\n};\nconst W = 8; // Precomputes-related code. W = window size\nconst precompute = () => {\n const points = []; // 10x sign(), 2x verify(). To achieve this,\n const windows = 256 / W + 1; // app needs to spend 40ms+ to calculate\n let p = G, b = p; // a lot of points related to base point G.\n for (let w = 0; w < windows; w++) { // Points are stored in array and used\n b = p; // any time Gx multiplication is done.\n points.push(b); // They consume 16-32 MiB of RAM.\n for (let i = 1; i < 2 ** (W - 1); i++) {\n b = b.add(p);\n points.push(b);\n }\n p = b.double(); // Precomputes don't speed-up getSharedKey,\n } // which multiplies user point by scalar,\n return points; // when precomputes are using base point\n};\nconst wNAF = (n) => {\n // Compared to other point mult methods,\n const comp = Gpows || (Gpows = precompute()); // stores 2x less points using subtraction\n const neg = (cnd, p) => { let n = p.negate(); return cnd ? n : p; }; // negate\n let p = I, f = G; // f must be G, or could become I in the end\n const windows = 1 + 256 / W; // W=8 17 windows\n const wsize = 2 ** (W - 1); // W=8 128 window size\n const mask = BigInt(2 ** W - 1); // W=8 will create mask 0b11111111\n const maxNum = 2 ** W; // W=8 256\n const shiftBy = BigInt(W); // W=8 8\n for (let w = 0; w < windows; w++) {\n const off = w * wsize;\n let wbits = Number(n & mask); // extract W bits.\n n >>= shiftBy; // shift number by W bits.\n if (wbits > wsize) {\n wbits -= maxNum;\n n += 1n;\n } // split if bits > max: +224 => 256-32\n const off1 = off, off2 = off + Math.abs(wbits) - 1; // offsets, evaluate both\n const cnd1 = w % 2 !== 0, cnd2 = wbits < 0; // conditions, evaluate both\n if (wbits === 0) {\n f = f.add(neg(cnd1, comp[off1])); // bits are 0: add garbage to fake point\n }\n else { // ^ can't add off2, off2 = I\n p = p.add(neg(cnd2, comp[off2])); // bits are 1: add to result point\n }\n }\n return { p, f }; // return both real and fake points for JIT\n}; // !! you can disable precomputes by commenting-out call of the wNAF() inside Point#mul()\nexport { getPublicKey, getPublicKeyAsync, sign, verify, // Remove the export to easily use in REPL\nsignAsync, verifyAsync, CURVE, etc, utils, Point as ExtendedPoint }; // envs like browser console\n", "/*! noble-secp256k1 - MIT License (c) 2019 Paul Miller (paulmillr.com) */\nconst B256 = 2n ** 256n; // secp256k1 is short weierstrass curve\nconst P = B256 - 0x1000003d1n; // curve's field prime\nconst N = B256 - 0x14551231950b75fc4402da1732fc9bebfn; // curve (group) order\nconst Gx = 0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798n; // base point x\nconst Gy = 0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8n; // base point y\nconst CURVE = { p: P, n: N, a: 0n, b: 7n, Gx, Gy }; // exported variables incl. a, b\nconst fLen = 32; // field / group byte length\nconst crv = (x) => mod(mod(x * x) * x + CURVE.b); // x\u00B3 + ax + b weierstrass formula; no a\nconst err = (m = '') => { throw new Error(m); }; // error helper, messes-up stack trace\nconst big = (n) => typeof n === 'bigint'; // is big integer\nconst str = (s) => typeof s === 'string'; // is string\nconst fe = (n) => big(n) && 0n < n && n < P; // is field element (invertible)\nconst ge = (n) => big(n) && 0n < n && n < N; // is group element\nconst au8 = (a, l) => // is Uint8Array (of specific length)\n !(a instanceof Uint8Array) || (typeof l === 'number' && l > 0 && a.length !== l) ?\n err('Uint8Array expected') : a;\nconst u8n = (data) => new Uint8Array(data); // creates Uint8Array\nconst toU8 = (a, len) => au8(str(a) ? h2b(a) : u8n(a), len); // norm(hex/u8a) to u8a\nconst mod = (a, b = P) => { let r = a % b; return r >= 0n ? r : b + r; }; // mod division\nconst isPoint = (p) => (p instanceof Point ? p : err('Point expected')); // is 3d point\nlet Gpows = undefined; // precomputes for base point G\nclass Point {\n constructor(px, py, pz) {\n this.px = px;\n this.py = py;\n this.pz = pz;\n } //3d=less inversions\n static fromAffine(p) { return new Point(p.x, p.y, 1n); }\n static fromHex(hex) {\n hex = toU8(hex); // convert hex string to Uint8Array\n let p = undefined;\n const head = hex[0], tail = hex.subarray(1); // first byte is prefix, rest is data\n const x = slcNum(tail, 0, fLen), len = hex.length; // next 32 bytes are x coordinate\n if (len === 33 && [0x02, 0x03].includes(head)) { // compressed points: 33b, start\n if (!fe(x))\n err('Point hex invalid: x not FE'); // with byte 0x02 or 0x03. Check if 0<x<P\n let y = sqrt(crv(x)); // x\u00B3 + ax + b is right side of equation\n const isYOdd = (y & 1n) === 1n; // y\u00B2 is equivalent left-side. Calculate y\u00B2:\n const headOdd = (head & 1) === 1; // y = \u221Ay\u00B2; there are two solutions: y, -y\n if (headOdd !== isYOdd)\n y = mod(-y); // determine proper solution\n p = new Point(x, y, 1n); // create point\n } // Uncompressed points: 65b, start with 0x04\n if (len === 65 && head === 0x04)\n p = new Point(x, slcNum(tail, fLen, 2 * fLen), 1n);\n return p ? p.ok() : err('Point is not on curve'); // Verify the result\n }\n static fromPrivateKey(k) { return G.mul(toPriv(k)); } // Create point from a private key.\n get x() { return this.aff().x; } // .x, .y will call expensive toAffine:\n get y() { return this.aff().y; } // should be used with care.\n equals(other) {\n const { px: X1, py: Y1, pz: Z1 } = this;\n const { px: X2, py: Y2, pz: Z2 } = isPoint(other); // isPoint() checks class equality\n const X1Z2 = mod(X1 * Z2), X2Z1 = mod(X2 * Z1);\n const Y1Z2 = mod(Y1 * Z2), Y2Z1 = mod(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n negate() { return new Point(this.px, mod(-this.py), this.pz); } // Flip point over y coord\n double() { return this.add(this); } // Point doubling: P+P, complete formula.\n add(other) {\n const { px: X1, py: Y1, pz: Z1 } = this; // free formula from Renes-Costello-Batina\n const { px: X2, py: Y2, pz: Z2 } = isPoint(other); // https://eprint.iacr.org/2015/1060, algo 1\n const { a, b } = CURVE; // Cost: 12M + 0S + 3*a + 3*b3 + 23add\n let X3 = 0n, Y3 = 0n, Z3 = 0n;\n const b3 = mod(b * 3n);\n let t0 = mod(X1 * X2), t1 = mod(Y1 * Y2), t2 = mod(Z1 * Z2), t3 = mod(X1 + Y1); // step 1\n let t4 = mod(X2 + Y2); // step 5\n t3 = mod(t3 * t4);\n t4 = mod(t0 + t1);\n t3 = mod(t3 - t4);\n t4 = mod(X1 + Z1);\n let t5 = mod(X2 + Z2); // step 10\n t4 = mod(t4 * t5);\n t5 = mod(t0 + t2);\n t4 = mod(t4 - t5);\n t5 = mod(Y1 + Z1);\n X3 = mod(Y2 + Z2); // step 15\n t5 = mod(t5 * X3);\n X3 = mod(t1 + t2);\n t5 = mod(t5 - X3);\n Z3 = mod(a * t4);\n X3 = mod(b3 * t2); // step 20\n Z3 = mod(X3 + Z3);\n X3 = mod(t1 - Z3);\n Z3 = mod(t1 + Z3);\n Y3 = mod(X3 * Z3);\n t1 = mod(t0 + t0); // step 25\n t1 = mod(t1 + t0);\n t2 = mod(a * t2);\n t4 = mod(b3 * t4);\n t1 = mod(t1 + t2);\n t2 = mod(t0 - t2); // step 30\n t2 = mod(a * t2);\n t4 = mod(t4 + t2);\n t0 = mod(t1 * t4);\n Y3 = mod(Y3 + t0);\n t0 = mod(t5 * t4); // step 35\n X3 = mod(t3 * X3);\n X3 = mod(X3 - t0);\n t0 = mod(t3 * t1);\n Z3 = mod(t5 * Z3);\n Z3 = mod(Z3 + t0); // step 40\n return new Point(X3, Y3, Z3);\n }\n mul(n, safe = true) {\n if (!safe && n === 0n)\n return I; // in unsafe mode, allow zero\n if (!ge(n))\n err('invalid scalar'); // must be 0 < n < CURVE.n\n if (this.equals(G))\n return wNAF(n).p; // use precomputes for base point\n let p = I, f = G; // init result point & fake point\n for (let d = this; n > 0n; d = d.double(), n >>= 1n) { // double-and-add ladder\n if (n & 1n)\n p = p.add(d); // if bit is present, add to point\n else if (safe)\n f = f.add(d); // if not, add to fake for timing safety\n }\n return p;\n }\n mulAddQUns(R, u1, u2) {\n return this.mul(u1, false).add(R.mul(u2, false)).ok(); // Unsafe: do NOT use for stuff related\n } // to private keys. Doesn't use Shamir trick\n toAffine() {\n const { px: x, py: y, pz: z } = this; // (x, y, z) \u220B (x=x/z, y=y/z)\n if (this.equals(I))\n return { x: 0n, y: 0n }; // fast-path for zero point\n if (z === 1n)\n return { x, y }; // if z is 1, pass affine coordinates as-is\n const iz = inv(z); // z^-1: invert z\n if (mod(z * iz) !== 1n)\n err('invalid inverse'); // (z * z^-1) must be 1, otherwise bad math\n return { x: mod(x * iz), y: mod(y * iz) }; // x = x*z^-1; y = y*z^-1\n }\n assertValidity() {\n const { x, y } = this.aff(); // convert to 2d xy affine point.\n if (!fe(x) || !fe(y))\n err('Point invalid: x or y'); // x and y must be in range 0 < n < P\n return mod(y * y) === crv(x) ? // y\u00B2 = x\u00B3 + ax + b, must be equal\n this : err('Point invalid: not on curve');\n }\n multiply(n) { return this.mul(n); } // Aliases to compress code\n aff() { return this.toAffine(); }\n ok() { return this.assertValidity(); }\n toHex(isCompressed = true) {\n const { x, y } = this.aff(); // convert to 2d xy affine point\n const head = isCompressed ? ((y & 1n) === 0n ? '02' : '03') : '04'; // 0x02, 0x03, 0x04 prefix\n return head + n2h(x) + (isCompressed ? '' : n2h(y)); // prefix||x and ||y\n }\n toRawBytes(isCompressed = true) {\n return h2b(this.toHex(isCompressed)); // re-use toHex(), convert hex to bytes\n }\n}\nPoint.BASE = new Point(Gx, Gy, 1n); // Generator / base point\nPoint.ZERO = new Point(0n, 1n, 0n); // Identity / zero point\nconst { BASE: G, ZERO: I } = Point; // Generator, identity points\nconst padh = (n, pad) => n.toString(16).padStart(pad, '0');\nconst b2h = (b) => Array.from(b).map(e => padh(e, 2)).join(''); // bytes to hex\nconst h2b = (hex) => {\n const l = hex.length; // error if not string,\n if (!str(hex) || l % 2)\n err('hex invalid 1'); // or has odd length like 3, 5.\n const arr = u8n(l / 2); // create result array\n for (let i = 0; i < arr.length; i++) {\n const j = i * 2;\n const h = hex.slice(j, j + 2); // hexByte. slice is faster than substr\n const b = Number.parseInt(h, 16); // byte, created from string part\n if (Number.isNaN(b) || b < 0)\n err('hex invalid 2'); // byte must be valid 0 <= byte < 256\n arr[i] = b;\n }\n return arr;\n};\nconst b2n = (b) => BigInt('0x' + (b2h(b) || '0')); // bytes to number\nconst slcNum = (b, from, to) => b2n(b.slice(from, to)); // slice bytes num\nconst n2b = (num) => {\n return big(num) && num >= 0n && num < B256 ? h2b(padh(num, 2 * fLen)) : err('bigint expected');\n};\nconst n2h = (num) => b2h(n2b(num)); // number to 32b hex\nconst concatB = (...arrs) => {\n const r = u8n(arrs.reduce((sum, a) => sum + au8(a).length, 0)); // create u8a of summed length\n let pad = 0; // walk through each array,\n arrs.forEach(a => { r.set(a, pad); pad += a.length; }); // ensure they have proper type\n return r;\n};\nconst inv = (num, md = P) => {\n if (num === 0n || md <= 0n)\n err('no inverse n=' + num + ' mod=' + md); // no neg exponent for now\n let a = mod(num, md), b = md, x = 0n, y = 1n, u = 1n, v = 0n;\n while (a !== 0n) { // uses euclidean gcd algorithm\n const q = b / a, r = b % a; // not constant-time\n const m = x - u * q, n = y - v * q;\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n return b === 1n ? mod(x, md) : err('no inverse'); // b is gcd at this point\n};\nconst sqrt = (n) => {\n let r = 1n; // So, a special, fast case. Paper: \"Square Roots from 1;24,51,10 to Dan Shanks\".\n for (let num = n, e = (P + 1n) / 4n; e > 0n; e >>= 1n) { // powMod: modular exponentiation.\n if (e & 1n)\n r = (r * num) % P; // Uses exponentiation by squaring.\n num = (num * num) % P; // Not constant-time.\n }\n return mod(r * r) === n ? r : err('sqrt invalid'); // check if result is valid\n};\nconst toPriv = (p) => {\n if (!big(p))\n p = b2n(toU8(p, fLen)); // convert to bigint when bytes\n return ge(p) ? p : err('private key out of range'); // check if bigint is in range\n};\nconst moreThanHalfN = (n) => n > (N >> 1n); // if a number is bigger than CURVE.n/2\nfunction getPublicKey(privKey, isCompressed = true) {\n return Point.fromPrivateKey(privKey).toRawBytes(isCompressed); // 33b or 65b output\n}\nclass Signature {\n constructor(r, s, recovery) {\n this.r = r;\n this.s = s;\n this.recovery = recovery;\n this.assertValidity(); // recovery bit is optional when\n } // constructed outside.\n static fromCompact(hex) {\n hex = toU8(hex, 64); // compact repr is (32b r)||(32b s)\n return new Signature(slcNum(hex, 0, fLen), slcNum(hex, fLen, 2 * fLen));\n }\n assertValidity() { return ge(this.r) && ge(this.s) ? this : err(); } // 0 < r or s < CURVE.n\n addRecoveryBit(rec) { return new Signature(this.r, this.s, rec); }\n hasHighS() { return moreThanHalfN(this.s); }\n recoverPublicKey(msgh) {\n const { r, s, recovery: rec } = this; // secg.org/sec1-v2.pdf 4.1.6\n if (![0, 1, 2, 3].includes(rec))\n err('recovery id invalid'); // check recovery id\n const h = bits2int_modN(toU8(msgh, 32)); // Truncate hash\n const radj = rec === 2 || rec === 3 ? r + N : r; // If rec was 2 or 3, q.x is bigger than n\n if (radj >= P)\n err('q.x invalid'); // ensure q.x is still a field element\n const head = (rec & 1) === 0 ? '02' : '03'; // head is 0x02 or 0x03\n const R = Point.fromHex(head + n2h(radj)); // concat head + hex repr of r\n const ir = inv(radj, N); // r^-1\n const u1 = mod(-h * ir, N); // -hr^-1\n const u2 = mod(s * ir, N); // sr^-1\n return G.mulAddQUns(R, u1, u2); // (sr^-1)R-(hr^-1)G = -(hr^-1)G + (sr^-1)\n }\n toCompactRawBytes() { return h2b(this.toCompactHex()); } // Uint8Array 64b compact repr\n toCompactHex() { return n2h(this.r) + n2h(this.s); } // hex 64b compact repr\n}\nconst bits2int = (bytes) => {\n const delta = bytes.length * 8 - 256; // RFC suggests optional truncating via bits2octets\n const num = b2n(bytes); // FIPS 186-4 4.6 suggests the leftmost min(nBitLen, outLen) bits, which\n return delta > 0 ? num >> BigInt(delta) : num; // matches bits2int. bits2int can produce res>N.\n};\nconst bits2int_modN = (bytes) => {\n return mod(bits2int(bytes), N); // with 0: BAD for trunc as per RFC vectors\n};\nconst i2o = (num) => n2b(num); // int to octets\nconst cr = () => // We support: 1) browsers 2) node.js 19+ 3) deno, other envs with crypto\n typeof globalThis === 'object' && 'crypto' in globalThis ? globalThis.crypto : undefined;\nlet _hmacSync; // Can be redefined by use in utils; built-ins don't provide it\nconst optS = { lowS: true }; // opts for sign()\nconst optV = { lowS: true }; // standard opts for verify()\nfunction prepSig(msgh, priv, opts = optS) {\n if (['der', 'recovered', 'canonical'].some(k => k in opts)) // Ban legacy options\n err('sign() legacy options not supported');\n let { lowS } = opts; // generates low-s sigs by default\n if (lowS == null)\n lowS = true; // RFC6979 3.2: we skip step A\n const h1i = bits2int_modN(toU8(msgh)); // msg bigint\n const h1o = i2o(h1i); // msg octets\n const d = toPriv(priv); // validate private key, convert to bigint\n const seed = [i2o(d), h1o]; // Step D of RFC6979 3.2\n let ent = opts.extraEntropy; // RFC6979 3.6: additional k' (optional)\n if (ent) { // K = HMAC_K(V || 0x00 || int2octets(x) || bits2octets(h1) || k')\n if (ent === true)\n ent = etc.randomBytes(fLen); // if true, use CSPRNG to generate data\n const e = toU8(ent); // convert Hex|Bytes to Bytes\n if (e.length !== fLen)\n err(); // Expected 32 bytes of extra data\n seed.push(e);\n }\n const m = h1i; // convert msg to bigint\n const k2sig = (kBytes) => {\n const k = bits2int(kBytes); // RFC6979 method.\n if (!ge(k))\n return; // Check 0 < k < CURVE.n\n const ik = inv(k, N); // k^-1 mod n, NOT mod P\n const q = G.mul(k).aff(); // q = Gk\n const r = mod(q.x, N); // r = q.x mod n\n if (r === 0n)\n return; // r=0 invalid\n const s = mod(ik * mod(m + mod(d * r, N), N), N); // s = k^-1(m + rd) mod n\n if (s === 0n)\n return; // s=0 invalid\n let normS = s; // normalized S\n let rec = (q.x === r ? 0 : 2) | Number(q.y & 1n); // recovery bit\n if (lowS && moreThanHalfN(s)) { // if lowS was passed, ensure s is always\n normS = mod(-s, N); // in the bottom half of CURVE.n\n rec ^= 1;\n }\n return new Signature(r, normS, rec); // use normS, not s\n };\n return { seed: concatB(...seed), k2sig };\n}\nfunction hmacDrbg(asynchronous) {\n let v = u8n(fLen); // Minimal non-full-spec HMAC-DRBG from NIST 800-90 for RFC6979 sigs.\n let k = u8n(fLen); // Steps B, C of RFC6979 3.2: set hashLen, in our case always same\n let i = 0; // Iterations counter, will throw when over 1000\n const reset = () => { v.fill(1); k.fill(0); i = 0; };\n const _e = 'drbg: tried 1000 values';\n if (asynchronous) { // asynchronous=true\n const h = (...b) => etc.hmacSha256Async(k, v, ...b); // hmac(k)(v, ...values)\n const reseed = async (seed = u8n()) => {\n k = await h(u8n([0x00]), seed); // k = hmac(K || V || 0x00 || seed)\n v = await h(); // v = hmac(K || V)\n if (seed.length === 0)\n return;\n k = await h(u8n([0x01]), seed); // k = hmac(K || V || 0x01 || seed)\n v = await h(); // v = hmac(K || V)\n };\n const gen = async () => {\n if (i++ >= 1000)\n err(_e);\n v = await h(); // v = hmac(K || V)\n return v;\n };\n return async (seed, pred) => {\n reset(); // the returned fn, don't, it's: 1. slower (JIT). 2. unsafe (async race conditions)\n await reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(await gen())))\n await reseed(); // test predicate until it returns ok\n reset();\n return res;\n };\n }\n else {\n const h = (...b) => {\n const f = _hmacSync;\n if (!f)\n err('etc.hmacSha256Sync not set');\n return f(k, v, ...b); // hmac(k)(v, ...values)\n };\n const reseed = (seed = u8n()) => {\n k = h(u8n([0x00]), seed); // k = hmac(k || v || 0x00 || seed)\n v = h(); // v = hmac(k || v)\n if (seed.length === 0)\n return;\n k = h(u8n([0x01]), seed); // k = hmac(k || v || 0x01 || seed)\n v = h(); // v = hmac(k || v)\n };\n const gen = () => {\n if (i++ >= 1000)\n err(_e);\n v = h(); // v = hmac(k || v)\n return v;\n };\n return (seed, pred) => {\n reset();\n reseed(seed); // Steps D-G\n let res = undefined; // Step H: grind until k is in [1..n-1]\n while (!(res = pred(gen())))\n reseed(); // test predicate until it returns ok\n reset();\n return res;\n };\n }\n}\n// ECDSA signature generation. via secg.org/sec1-v2.pdf 4.1.2 + RFC6979 deterministic k\nasync function signAsync(msgh, priv, opts = optS) {\n const { seed, k2sig } = prepSig(msgh, priv, opts); // Extract arguments for hmac-drbg\n return hmacDrbg(true)(seed, k2sig); // Re-run hmac-drbg until k2sig returns ok\n}\nfunction sign(msgh, priv, opts = optS) {\n const { seed, k2sig } = prepSig(msgh, priv, opts); // Extract arguments for hmac-drbg\n return hmacDrbg(false)(seed, k2sig); // Re-run hmac-drbg until k2sig returns ok\n}\nfunction verify(sig, msgh, pub, opts = optV) {\n let { lowS } = opts; // ECDSA signature verification\n if (lowS == null)\n lowS = true; // Default lowS=true\n if ('strict' in opts)\n err('verify() legacy options not supported'); // legacy param\n let sig_, h, P; // secg.org/sec1-v2.pdf 4.1.4\n const rs = sig && typeof sig === 'object' && 'r' in sig; // Previous ver supported DER sigs. We\n if (!rs && (toU8(sig).length !== 2 * fLen)) // throw error when DER is suspected now.\n err('signature must be 64 bytes');\n try {\n sig_ = rs ? new Signature(sig.r, sig.s).assertValidity() : Signature.fromCompact(sig);\n h = bits2int_modN(toU8(msgh, fLen)); // Truncate hash\n P = pub instanceof Point ? pub.ok() : Point.fromHex(pub); // Validate public key\n }\n catch (e) {\n return false;\n } // Check sig for validity in both cases\n if (!sig_)\n return false;\n const { r, s } = sig_;\n if (lowS && moreThanHalfN(s))\n return false; // lowS bans sig.s >= CURVE.n/2\n let R;\n try {\n const is = inv(s, N); // s^-1\n const u1 = mod(h * is, N); // u1 = hs^-1 mod n\n const u2 = mod(r * is, N); // u2 = rs^-1 mod n\n R = G.mulAddQUns(P, u1, u2).aff(); // R = u1\u22C5G + u2\u22C5P\n }\n catch (error) {\n return false;\n }\n if (!R)\n return false; // stop if R is identity / zero point\n const v = mod(R.x, N); // <== The weird ECDSA part. R.x must be in N's field, not P's\n return v === r; // mod(R.x, n) == r\n}\nfunction getSharedSecret(privA, pubB, isCompressed = true) {\n return Point.fromHex(pubB).mul(toPriv(privA)).toRawBytes(isCompressed); // ECDH\n}\nfunction hashToPrivateKey(hash) {\n hash = toU8(hash); // produces private keys with modulo bias\n const minLen = fLen + 8; // being neglible.\n if (hash.length < minLen || hash.length > 1024)\n err('expected proper params');\n const num = mod(b2n(hash), N - 1n) + 1n; // takes at least n+8 bytes\n return n2b(num);\n}\nconst etc = {\n hexToBytes: h2b, bytesToHex: b2h,\n concatBytes: concatB, bytesToNumberBE: b2n, numberToBytesBE: n2b,\n mod, invert: inv,\n hmacSha256Async: async (key, ...msgs) => {\n const crypto = cr(); // HMAC-SHA256 async. No sync built-in!\n if (!crypto)\n return err('etc.hmacSha256Async not set'); // Uses webcrypto: native cryptography.\n const s = crypto.subtle;\n const k = await s.importKey('raw', key, { name: 'HMAC', hash: { name: 'SHA-256' } }, false, ['sign']);\n return u8n(await s.sign('HMAC', k, concatB(...msgs)));\n },\n hmacSha256Sync: _hmacSync,\n hashToPrivateKey,\n randomBytes: (len) => {\n const crypto = cr(); // Can be shimmed in node.js <= 18 to prevent error:\n // import { webcrypto } from 'node:crypto';\n // if (!globalThis.crypto) globalThis.crypto = webcrypto;\n if (!crypto)\n err('crypto.getRandomValues must be defined');\n return crypto.getRandomValues(u8n(len));\n },\n};\nconst utils = {\n normPrivateKeyToScalar: toPriv,\n isValidPrivateKey: (key) => { try {\n return !!toPriv(key);\n }\n catch (e) {\n return false;\n } },\n randomPrivateKey: () => hashToPrivateKey(etc.randomBytes(fLen + 8)),\n precompute(w = 8, p = G) { p.multiply(3n); return p; }, // no-op\n};\nObject.defineProperties(etc, { hmacSha256Sync: {\n configurable: false, get() { return _hmacSync; }, set(f) { if (!_hmacSync)\n _hmacSync = f; },\n } });\nconst W = 8; // Precomputes-related code. W = window size\nconst precompute = () => {\n const points = []; // 10x sign(), 2x verify(). To achieve this,\n const windows = 256 / W + 1; // app needs to spend 40ms+ to calculate\n let p = G, b = p; // a lot of points related to base point G.\n for (let w = 0; w < windows; w++) { // Points are stored in array and used\n b = p; // any time Gx multiplication is done.\n points.push(b); // They consume 16-32 MiB of RAM.\n for (let i = 1; i < 2 ** (W - 1); i++) {\n b = b.add(p);\n points.push(b);\n }\n p = b.double(); // Precomputes don't speed-up getSharedKey,\n } // which multiplies user point by scalar,\n return points; // when precomputes are using base point\n};\nconst wNAF = (n) => {\n // Compared to other point mult methods,\n const comp = Gpows || (Gpows = precompute()); // stores 2x less points using subtraction\n const neg = (cnd, p) => { let n = p.negate(); return cnd ? n : p; }; // negate\n let p = I, f = G; // f must be G, or could become I in the end\n const windows = 1 + 256 / W; // W=8 17 windows\n const wsize = 2 ** (W - 1); // W=8 128 window size\n const mask = BigInt(2 ** W - 1); // W=8 will create mask 0b11111111\n const maxNum = 2 ** W; // W=8 256\n const shiftBy = BigInt(W); // W=8 8\n for (let w = 0; w < windows; w++) {\n const off = w * wsize;\n let wbits = Number(n & mask); // extract W bits.\n n >>= shiftBy; // shift number by W bits.\n if (wbits > wsize) {\n wbits -= maxNum;\n n += 1n;\n } // split if bits > max: +224 => 256-32\n const off1 = off, off2 = off + Math.abs(wbits) - 1; // offsets, evaluate both\n const cnd1 = w % 2 !== 0, cnd2 = wbits < 0; // conditions, evaluate both\n if (wbits === 0) {\n f = f.add(neg(cnd1, comp[off1])); // bits are 0: add garbage to fake point\n }\n else { // ^ can't add off2, off2 = I\n p = p.add(neg(cnd2, comp[off2])); // bits are 1: add to result point\n }\n }\n return { p, f }; // return both real and fake points for JIT\n}; // !! you can disable precomputes by commenting-out call of the wNAF() inside Point#mul()\nexport { getPublicKey, sign, signAsync, verify, CURVE, // Remove the export to easily use in REPL\ngetSharedSecret, etc, utils, Point as ProjectivePoint, Signature }; // envs like browser console\n", null, null, "import type {\n CryptoApi,\n InferKeyGeneratorAlgorithm,\n Jwk,\n KeyIdentifier,\n KeyImporterExporter,\n KmsExportKeyParams,\n KmsImportKeyParams,\n} from '@enbox/crypto';\n\nimport { Convert } from '@enbox/common';\nimport { LocalKeyManager } from '@enbox/crypto';\n\nimport type { PortableDid } from '../types/portable-did.js';\nimport type { DidCreateOptions, DidCreateVerificationMethod } from './did-method.js';\nimport type { DidDocument, DidResolutionOptions, DidResolutionResult, DidVerificationMethod } from '../types/did-core.js';\n\nimport { BearerDid } from '../bearer-did.js';\nimport { Did } from '../did.js';\nimport { DidMethod } from './did-method.js';\nimport { EMPTY_DID_RESOLUTION_RESULT } from '../types/did-resolution.js';\nimport { DidError, DidErrorCode } from '../did-error.js';\n\n/**\n * Defines the set of options available when creating a new Decentralized Identifier (DID) with the\n * 'did:jwk' method.\n *\n * Either the `algorithm` or `verificationMethods` option can be specified, but not both.\n * - A new key will be generated using the algorithm identifier specified in either the `algorithm`\n * property or the `verificationMethods` object's `algorithm` property.\n * - If `verificationMethods` is given, it must contain exactly one entry since DID JWK only\n * supports a single verification method.\n * - If neither is given, the default is to generate a new Ed25519 key.\n *\n * @example\n * ```ts\n * // DID Creation\n *\n * // By default, when no options are given, a new Ed25519 key will be generated.\n * const did = await DidJwk.create();\n *\n * // The algorithm to use for key generation can be specified as a top-level option.\n * const did = await DidJwk.create({\n * options: { algorithm = 'ES256K' }\n * });\n *\n * // Or, alternatively as a property of the verification method.\n * const did = await DidJwk.create({\n * options: {\n * verificationMethods: [{ algorithm = 'ES256K' }]\n * }\n * });\n *\n * // DID Creation with a KMS\n * const keyManager = new LocalKeyManager();\n * const did = await DidJwk.create({ keyManager });\n *\n * // DID Resolution\n * const resolutionResult = await DidJwk.resolve({ did: did.uri });\n *\n * // Signature Operations\n * const signer = await did.getSigner();\n * const signature = await signer.sign({ data: new TextEncoder().encode('Message') });\n * const isValid = await signer.verify({ data: new TextEncoder().encode('Message'), signature });\n *\n * // Import / Export\n *\n * // Export a BearerDid object to the PortableDid format.\n * const portableDid = await did.export();\n *\n * // Reconstruct a BearerDid object from a PortableDid\n * const did = await DidJwk.import(portableDid);\n * ```\n */\nexport interface DidJwkCreateOptions<TKms> extends DidCreateOptions<TKms> {\n /**\n * Optionally specify the algorithm to be used for key generation.\n */\n algorithm?: TKms extends CryptoApi\n ? InferKeyGeneratorAlgorithm<TKms>\n : InferKeyGeneratorAlgorithm<LocalKeyManager>;\n\n /**\n * Alternatively, specify the algorithm to be used for key generation of the single verification\n * method in the DID Document.\n */\n verificationMethods?: DidCreateVerificationMethod<TKms>[];\n}\n\n/**\n * The `DidJwk` class provides an implementation of the `did:jwk` DID method.\n *\n * Features:\n * - DID Creation: Create new `did:jwk` DIDs.\n * - DID Key Management: Instantiate a DID object from an existing verification method key set or\n * or a key in a Key Management System (KMS). If supported by the KMS, a DID's\n * key can be exported to a portable DID format.\n * - DID Resolution: Resolve a `did:jwk` to its corresponding DID Document.\n * - Signature Operations: Sign and verify messages using keys associated with a DID.\n *\n * @remarks\n * The `did:jwk` DID method uses a single JSON Web Key (JWK) to generate a DID and does not rely\n * on any external system such as a blockchain or centralized database. This characteristic makes\n * it suitable for use cases where a assertions about a DID Subject can be self-verifiable by\n * third parties.\n *\n * The DID URI is formed by Base64URL-encoding the JWK and prefixing with `did:jwk:`. The DID\n * Document of a `did:jwk` DID contains a single verification method, which is the JWK used\n * to generate the DID. The verification method is identified by the key ID `#0`.\n *\n * @see {@link https://github.com/quartzjer/did-jwk/blob/main/spec.md | DID JWK Specification}\n *\n * @example\n * ```ts\n * // DID Creation\n * const did = await DidJwk.create();\n *\n * // DID Creation with a KMS\n * const keyManager = new LocalKeyManager();\n * const did = await DidJwk.create({ keyManager });\n *\n * // DID Resolution\n * const resolutionResult = await DidJwk.resolve({ did: did.uri });\n *\n * // Signature Operations\n * const signer = await did.getSigner();\n * const signature = await signer.sign({ data: new TextEncoder().encode('Message') });\n * const isValid = await signer.verify({ data: new TextEncoder().encode('Message'), signature });\n *\n * // Key Management\n *\n * // Instantiate a DID object from an existing key in a KMS\n * const did = await DidJwk.fromKeyManager({\n * didUri: 'did:jwk:eyJrIjoiT0tQIiwidCI6IkV1c2UyNTYifQ',\n * keyManager\n * });\n *\n * // Instantiate a DID object from an existing verification method key\n * const did = await DidJwk.fromKeys({\n * verificationMethods: [{\n * publicKeyJwk: {\n * kty: 'OKP',\n * crv: 'Ed25519',\n * x: 'cHs7YMLQ3gCWjkacMURBsnEJBcEsvlsE5DfnsfTNDP4'\n * },\n * privateKeyJwk: {\n * kty: 'OKP',\n * crv: 'Ed25519',\n * x: 'cHs7YMLQ3gCWjkacMURBsnEJBcEsvlsE5DfnsfTNDP4',\n * d: 'bdcGE4KzEaekOwoa-ee3gAm1a991WvNj_Eq3WKyqTnE'\n * }\n * }]\n * });\n *\n * // Convert a DID object to a portable format\n * const portableDid = await DidJwk.toKeys({ did });\n *\n * // Reconstruct a DID object from a portable format\n * const did = await DidJwk.fromKeys(portableDid);\n * ```\n */\nexport class DidJwk extends DidMethod {\n\n /**\n * Name of the DID method, as defined in the DID JWK specification.\n */\n public static methodName = 'jwk';\n\n /**\n * Creates a new DID using the `did:jwk` method formed from a newly generated key.\n *\n * @remarks\n * The DID URI is formed by Base64URL-encoding the JWK and prefixing with `did:jwk:`.\n *\n * Notes:\n * - If no `options` are given, by default a new Ed25519 key will be generated.\n * - The `algorithm` and `verificationMethods` options are mutually exclusive. If both are given,\n * an error will be thrown.\n *\n * @example\n * ```ts\n * // DID Creation\n * const did = await DidJwk.create();\n *\n * // DID Creation with a KMS\n * const keyManager = new LocalKeyManager();\n * const did = await DidJwk.create({ keyManager });\n * ```\n *\n * @param params - The parameters for the create operation.\n * @param params.keyManager - Optionally specify a Key Management System (KMS) used to generate\n * keys and sign data.\n * @param params.options - Optional parameters that can be specified when creating a new DID.\n * @returns A Promise resolving to a {@link BearerDid} object representing the new DID.\n */\n public static async create<TKms extends CryptoApi | undefined = undefined>({\n keyManager = new LocalKeyManager(),\n options = {}\n }: {\n keyManager?: TKms;\n options?: DidJwkCreateOptions<TKms>;\n } = {}): Promise<BearerDid> {\n // Before processing the create operation, validate DID-method-specific requirements to prevent\n // keys from being generated unnecessarily.\n\n // Check 1: Validate that `algorithm` or `verificationMethods` options are not both given.\n if (options.algorithm && options.verificationMethods) {\n throw new Error(`The 'algorithm' and 'verificationMethods' options are mutually exclusive`);\n }\n\n // Check 2: If `verificationMethods` is given, it must contain exactly one entry since DID JWK\n // only supports a single verification method.\n if (options.verificationMethods && options.verificationMethods.length !== 1) {\n throw new Error(`The 'verificationMethods' option must contain exactly one entry`);\n }\n\n // Default to Ed25519 key generation if an algorithm is not given.\n const algorithm = options.algorithm ?? options.verificationMethods?.[0]?.algorithm ?? 'Ed25519';\n\n // Generate a new key using the specified `algorithm`.\n const keyUri = await keyManager.generateKey({ algorithm });\n const publicKey = await keyManager.getPublicKey({ keyUri });\n\n // Compute the DID identifier from the public key by serializing the JWK to a UTF-8 string and\n // encoding in Base64URL format.\n const identifier = Convert.object(publicKey).toBase64Url();\n\n // Attach the prefix `did:jwk` to form the complete DID URI.\n const didUri = `did:${DidJwk.methodName}:${identifier}`;\n\n // Expand the DID URI string to a DID document.\n const didResolutionResult = await DidJwk.resolve(didUri);\n const document = didResolutionResult.didDocument as DidDocument;\n\n // Create the BearerDid object from the generated key material.\n const did = new BearerDid({\n uri : didUri,\n document,\n metadata : {},\n keyManager\n });\n\n return did;\n }\n\n /**\n * Given the W3C DID Document of a `did:jwk` DID, return the verification method that will be used\n * for signing messages and credentials. If given, the `methodId` parameter is used to select the\n * verification method. If not given, the first verification method in the DID Document is used.\n *\n * Note that for DID JWK, only one verification method can exist so specifying `methodId` could be\n * considered redundant or unnecessary. The option is provided for consistency with other DID\n * method implementations.\n *\n * @param params - The parameters for the `getSigningMethod` operation.\n * @param params.didDocument - DID Document to get the verification method from.\n * @param params.methodId - ID of the verification method to use for signing.\n * @returns Verification method to use for signing.\n */\n public static async getSigningMethod({ didDocument }: {\n didDocument: DidDocument;\n methodId?: string;\n }): Promise<DidVerificationMethod> {\n // Verify the DID method is supported.\n const parsedDid = Did.parse(didDocument.id);\n if (parsedDid && parsedDid.method !== this.methodName) {\n throw new DidError(DidErrorCode.MethodNotSupported, `Method not supported: ${parsedDid.method}`);\n }\n\n // Attempt to find the verification method in the DID Document.\n const [ verificationMethod ] = didDocument.verificationMethod ?? [];\n\n if (!(verificationMethod && verificationMethod.publicKeyJwk)) {\n throw new DidError(DidErrorCode.InternalError, 'A verification method intended for signing could not be determined from the DID Document');\n }\n\n return verificationMethod;\n }\n\n /**\n * Instantiates a {@link BearerDid} object for the DID JWK method from a given {@link PortableDid}.\n *\n * This method allows for the creation of a `BearerDid` object using a previously created DID's\n * key material, DID document, and metadata.\n *\n * @remarks\n * The `verificationMethod` array of the DID document must contain exactly one key since the\n * `did:jwk` method only supports a single verification method.\n *\n * @example\n * ```ts\n * // Export an existing BearerDid to PortableDid format.\n * const portableDid = await did.export();\n * // Reconstruct a BearerDid object from the PortableDid.\n * const did = await DidJwk.import({ portableDid });\n * ```\n *\n * @param params - The parameters for the import operation.\n * @param params.portableDid - The PortableDid object to import.\n * @param params.keyManager - Optionally specify an external Key Management System (KMS) used to\n * generate keys and sign data. If not given, a new\n * {@link LocalKeyManager} instance will be created and\n * used.\n * @returns A Promise resolving to a `BearerDid` object representing the DID formed from the provided keys.\n * @throws An error if the DID document does not contain exactly one verification method.\n */\n public static async import({ portableDid, keyManager = new LocalKeyManager() }: {\n keyManager?: CryptoApi & KeyImporterExporter<KmsImportKeyParams, KeyIdentifier, KmsExportKeyParams>;\n portableDid: PortableDid;\n }): Promise<BearerDid> {\n // Verify the DID method is supported.\n const parsedDid = Did.parse(portableDid.uri);\n if (parsedDid?.method !== DidJwk.methodName) {\n throw new DidError(DidErrorCode.MethodNotSupported, `Method not supported`);\n }\n\n // Use the given PortableDid to construct the BearerDid object.\n const did = await BearerDid.import({ portableDid, keyManager });\n\n // Validate that the given DID document contains exactly one verification method.\n // Note: The non-undefined assertion is necessary because the type system cannot infer that\n // the `verificationMethod` property is defined -- which is checked by `BearerDid.import()`.\n if (did.document.verificationMethod!.length !== 1) {\n throw new DidError(DidErrorCode.InvalidDidDocument, `DID document must contain exactly one verification method`);\n }\n\n return did;\n }\n\n /**\n * Resolves a `did:jwk` identifier to a DID Document.\n *\n * @param didUri - The DID to be resolved.\n * @param _options - Optional parameters for resolving the DID. Unused by this DID method.\n * @returns A Promise resolving to a {@link DidResolutionResult} object representing the result of the resolution.\n */\n public static async resolve(didUri: string, _options?: DidResolutionOptions): Promise<DidResolutionResult> {\n // Attempt to parse the DID URI.\n const parsedDid = Did.parse(didUri);\n\n // Attempt to decode the Base64URL-encoded JWK.\n let publicKey: Jwk | undefined;\n try {\n publicKey = parsedDid ? Convert.base64Url(parsedDid.id).toObject() as Jwk : undefined;\n } catch { /* Consume the error so that a DID resolution error can be returned later. */ }\n\n // If parsing or decoding failed, the DID is invalid.\n if (!parsedDid || !publicKey) {\n return {\n ...EMPTY_DID_RESOLUTION_RESULT,\n didResolutionMetadata: { error: 'invalidDid' }\n };\n }\n\n // If the DID method is not \"jwk\", return an error.\n if (parsedDid.method !== DidJwk.methodName) {\n return {\n ...EMPTY_DID_RESOLUTION_RESULT,\n didResolutionMetadata: { error: 'methodNotSupported' }\n };\n }\n\n const didDocument: DidDocument = {\n '@context': [\n 'https://www.w3.org/ns/did/v1'\n ],\n id: parsedDid.uri\n };\n\n const keyUri = `${didDocument.id}#0`;\n\n // Set the Verification Method property.\n didDocument.verificationMethod = [{\n id : keyUri,\n type : 'JsonWebKey',\n controller : didDocument.id,\n publicKeyJwk : publicKey\n }];\n\n // Set the Verification Relationship properties.\n didDocument.authentication = [keyUri];\n didDocument.assertionMethod = [keyUri];\n didDocument.capabilityInvocation = [keyUri];\n didDocument.capabilityDelegation = [keyUri];\n didDocument.keyAgreement = [keyUri];\n\n // If the JWK contains a `use` property with the value \"sig\" then the `keyAgreement` property\n // is not included in the DID Document. If the `use` value is \"enc\" then only the `keyAgreement`\n // property is included in the DID Document.\n switch (publicKey.use) {\n case 'sig': {\n delete didDocument.keyAgreement;\n break;\n }\n\n case 'enc': {\n delete didDocument.authentication;\n delete didDocument.assertionMethod;\n delete didDocument.capabilityInvocation;\n delete didDocument.capabilityDelegation;\n break;\n }\n }\n\n return {\n ...EMPTY_DID_RESOLUTION_RESULT,\n didDocument,\n };\n }\n}", "import type {\n AsymmetricKeyConverter,\n CryptoApi,\n InferKeyGeneratorAlgorithm,\n Jwk,\n KeyCompressor,\n KeyIdentifier,\n KeyImporterExporter,\n KmsExportKeyParams,\n KmsImportKeyParams,\n} from '@enbox/crypto';\nimport type { MulticodecCode, MulticodecDefinition } from '@enbox/common';\n\nimport {\n Ed25519,\n LocalKeyManager,\n Secp256k1,\n Secp256r1,\n} from '@enbox/crypto';\nimport { Multicodec, universalTypeOf } from '@enbox/common';\n\nimport type { PortableDid } from '../types/portable-did.js';\nimport type { DidCreateOptions, DidCreateVerificationMethod } from './did-method.js';\nimport type {\n DidDocument,\n DidResolutionOptions,\n DidResolutionResult,\n DidVerificationMethod,\n} from '../types/did-core.js';\n\nimport { BearerDid } from '../bearer-did.js';\nimport { Did } from '../did.js';\nimport { DidMethod } from './did-method.js';\nimport { EMPTY_DID_RESOLUTION_RESULT } from '../types/did-resolution.js';\nimport { DidError, DidErrorCode } from '../did-error.js';\nimport { getVerificationMethodTypes, keyBytesToMultibaseId, multibaseIdToKeyBytes } from '../utils.js';\n\n/**\n * Defines the set of options available when creating a new Decentralized Identifier (DID) with the\n * 'did:key' method.\n *\n * Either the `algorithm` or `verificationMethods` option can be specified, but not both.\n * - A new key will be generated using the algorithm identifier specified in either the `algorithm`\n * property or the `verificationMethods` object's `algorithm` property.\n * - If `verificationMethods` is given, it must contain exactly one entry since DID Key only\n * supports a single verification method.\n * - If neither is given, the default is to generate a new Ed25519 key.\n *\n * @example\n * ```ts\n * // By default, when no options are given, a new Ed25519 key will be generated.\n * const did = await DidKey.create();\n *\n * // The algorithm to use for key generation can be specified as a top-level option.\n * const did = await DidKey.create({\n * options: { algorithm = 'secp256k1' }\n * });\n *\n * // Or, alternatively as a property of the verification method.\n * const did = await DidKey.create({\n * options: {\n * verificationMethods: [{ algorithm = 'secp256k1' }]\n * }\n * });\n *\n * // DID Creation with a KMS\n * const keyManager = new LocalKeyManager();\n * const did = await DidKey.create({ keyManager });\n *\n * // DID Resolution\n * const resolutionResult = await DidKey.resolve({ did: did.uri });\n *\n * // Signature Operations\n * const signer = await did.getSigner();\n * const signature = await signer.sign({ data: new TextEncoder().encode('Message') });\n * const isValid = await signer.verify({ data: new TextEncoder().encode('Message'), signature });\n *\n * // Import / Export\n *\n * // Export a BearerDid object to the PortableDid format.\n * const portableDid = await did.export();\n *\n * // Reconstruct a BearerDid object from a PortableDid\n * const did = await DidKey.import(portableDid);\n * ```\n */\nexport interface DidKeyCreateOptions<TKms> extends DidCreateOptions<TKms> {\n /**\n * Optionally specify the algorithm to be used for key generation.\n */\n algorithm?: TKms extends CryptoApi\n ? InferKeyGeneratorAlgorithm<TKms>\n : InferKeyGeneratorAlgorithm<LocalKeyManager>;\n\n /**\n * Optionally specify an array of JSON-LD context links for the @context property of the DID\n * document.\n *\n * The @context property provides a JSON-LD processor with the information necessary to interpret\n * the DID document JSON. The default context URL is 'https://www.w3.org/ns/did/v1'.\n */\n defaultContext?: string;\n\n /**\n * Optionally enable experimental public key types during DID creation.\n * By default, this option is set to `false`, which means experimental public key types are not\n * supported.\n *\n * Note: This implementation of the DID Key method does not support any experimental public key\n * types.\n */\n enableExperimentalPublicKeyTypes?: boolean;\n\n /**\n * Optionally specify the format of the public key to be used for DID creation.\n */\n publicKeyFormat?: keyof typeof DidKeyVerificationMethodType;\n\n /**\n * Alternatively, specify the algorithm to be used for key generation of the single verification\n * method in the DID Document.\n */\n verificationMethods?: DidCreateVerificationMethod<TKms>[];\n}\n\n/**\n * Enumerates the types of keys that can be used in a DID Key document.\n *\n * The DID Key method supports various cryptographic key types. These key types are essential for\n * the creation and management of DIDs and their associated cryptographic operations like signing\n * and encryption.\n */\nexport enum DidKeyRegisteredKeyType {\n /**\n * Ed25519: A public-key signature system using the EdDSA (Edwards-curve Digital Signature\n * Algorithm) and Curve25519.\n */\n Ed25519 = 'Ed25519',\n\n /**\n * secp256k1: A cryptographic curve used for digital signatures in a range of decentralized\n * systems.\n */\n secp256k1 = 'secp256k1',\n\n /**\n * secp256r1: Also known as P-256 or prime256v1, this curve is used for cryptographic operations\n * and is widely supported in various cryptographic libraries and standards.\n */\n secp256r1 = 'secp256r1',\n}\n\n/**\n * Enumerates the verification method types supported by the DID Key method.\n *\n * This enum defines the URIs associated with common verification methods used in DID Documents.\n * These URIs represent cryptographic suites or key types standardized for use across decentralized\n * identifiers (DIDs).\n */\nexport const DidKeyVerificationMethodType = {\n /** Represents an Ed25519 public key used for digital signatures. */\n Ed25519VerificationKey2020: 'https://w3id.org/security/suites/ed25519-2020/v1',\n\n /** Represents a JSON Web Key (JWK) used for digital signatures and key agreement protocols. */\n JsonWebKey2020: 'https://w3id.org/security/suites/jws-2020/v1',\n} as const;\n\n/**\n * Private helper that maps algorithm identifiers to their corresponding DID Key\n * {@link DidKeyRegisteredKeyType | registered key type}.\n */\nconst AlgorithmToKeyTypeMap = {\n Ed25519 : DidKeyRegisteredKeyType.Ed25519,\n ES256K : DidKeyRegisteredKeyType.secp256k1,\n ES256 : DidKeyRegisteredKeyType.secp256r1,\n 'P-256' : DidKeyRegisteredKeyType.secp256r1,\n secp256k1 : DidKeyRegisteredKeyType.secp256k1,\n secp256r1 : DidKeyRegisteredKeyType.secp256r1,\n} as const;\n\n/**\n * The `DidKey` class provides an implementation of the 'did:key' DID method.\n *\n * Features:\n * - DID Creation: Create new `did:key` DIDs.\n * - DID Key Management: Instantiate a DID object from an existing verification method key set or\n * or a key in a Key Management System (KMS). If supported by the KMS, a DID's\n * key can be exported to a portable DID format.\n * - DID Resolution: Resolve a `did:key` to its corresponding DID Document.\n * - Signature Operations: Sign and verify messages using keys associated with a DID.\n *\n * @remarks\n * The `did:key` DID method uses a single public key to generate a DID and does not rely\n * on any external system such as a blockchain or centralized database. This characteristic makes\n * it suitable for use cases where a assertions about a DID Subject can be self-verifiable by\n * third parties.\n *\n * The method-specific identifier is formed by\n * {@link https://datatracker.ietf.org/doc/html/draft-multiformats-multibase#name-base-58-bitcoin-encoding | Multibase base58-btc}\n * encoding the concatenation of the\n * {@link https://github.com/multiformats/multicodec/blob/master/README.md | Multicodec} identifier\n * for the public key type and the raw public key bytes. To form the DID URI, the method-specific\n * identifier is prefixed with the string 'did:key:'.\n *\n * Note:\n * - The authors of the DID Key specification have indicated that use of this method for long-lived\n * use cases is only recommended when accompanied with high confidence that private keys are\n * securely protected by software or hardware isolation.\n *\n * @see {@link https://w3c-ccg.github.io/did-method-key/ | DID Key Specification}\n *\n* @example\n * ```ts\n * // DID Creation\n * const did = await DidKey.create();\n *\n * // DID Creation with a KMS\n * const keyManager = new LocalKeyManager();\n * const did = await DidKey.create({ keyManager });\n *\n * // DID Resolution\n * const resolutionResult = await DidKey.resolve({ did: did.uri });\n *\n * // Signature Operations\n * const signer = await did.getSigner();\n * const signature = await signer.sign({ data: new TextEncoder().encode('Message') });\n * const isValid = await signer.verify({ data: new TextEncoder().encode('Message'), signature });\n *\n * // Key Management\n *\n * // Instantiate a DID object from an existing key in a KMS\n * const did = await DidKey.fromKeyManager({\n * didUri: 'did:key:z6MkpUzNmYVTGpqhStxK8yRKXWCRNm1bGYz8geAg2zmjYHKX',\n * keyManager\n * });\n *\n * // Instantiate a DID object from an existing verification method key\n * const did = await DidKey.fromKeys({\n * verificationMethods: [{\n * publicKeyJwk: {\n * kty: 'OKP',\n * crv: 'Ed25519',\n * x: 'cHs7YMLQ3gCWjkacMURBsnEJBcEsvlsE5DfnsfTNDP4'\n * },\n * privateKeyJwk: {\n * kty: 'OKP',\n * crv: 'Ed25519',\n * x: 'cHs7YMLQ3gCWjkacMURBsnEJBcEsvlsE5DfnsfTNDP4',\n * d: 'bdcGE4KzEaekOwoa-ee3gAm1a991WvNj_Eq3WKyqTnE'\n * }\n * }]\n * });\n *\n * // Convert a DID object to a portable format\n * const portableDid = await DidKey.toKeys({ did });\n *\n * // Reconstruct a DID object from a portable format\n * const did = await DidKey.fromKeys(portableDid);\n * ```\n */\nexport class DidKey extends DidMethod {\n\n /**\n * Name of the DID method, as defined in the DID Key specification.\n */\n public static methodName = 'key';\n\n /**\n * Creates a new DID using the `did:key` method formed from a newly generated key.\n *\n * @remarks\n * The DID URI is formed by\n * {@link https://datatracker.ietf.org/doc/html/draft-multiformats-multibase#name-base-58-bitcoin-encoding | Multibase base58-btc}\n * encoding the\n * {@link https://github.com/multiformats/multicodec/blob/master/README.md | Multicodec}-encoded\n * public key and prefixing with `did:key:`.\n *\n * Notes:\n * - If no `options` are given, by default a new Ed25519 key will be generated.\n * - The `algorithm` and `verificationMethods` options are mutually exclusive. If both are given,\n * an error will be thrown.\n *\n * @example\n * ```ts\n * // DID Creation\n * const did = await DidKey.create();\n *\n * // DID Creation with a KMS\n * const keyManager = new LocalKeyManager();\n * const did = await DidKey.create({ keyManager });\n * ```\n *\n * @param params - The parameters for the create operation.\n * @param params.keyManager - Key Management System (KMS) used to generate keys and sign data.\n * @param params.options - Optional parameters that can be specified when creating a new DID.\n * @returns A Promise resolving to a {@link BearerDid} object representing the new DID.\n */\n public static async create<TKms extends CryptoApi | undefined = undefined>({\n keyManager = new LocalKeyManager(),\n options = {}\n }: {\n keyManager?: TKms;\n options?: DidKeyCreateOptions<TKms>;\n } = {}): Promise<BearerDid> {\n // Before processing the create operation, validate DID-method-specific requirements to prevent\n // keys from being generated unnecessarily.\n\n // Check 1: Validate that `algorithm` or `verificationMethods` options are not both given.\n if (options.algorithm && options.verificationMethods) {\n throw new Error(`The 'algorithm' and 'verificationMethods' options are mutually exclusive`);\n }\n\n // Check 2: If `verificationMethods` is given, it must contain exactly one entry since DID Key\n // only supports a single verification method.\n if (options.verificationMethods && options.verificationMethods.length !== 1) {\n throw new Error(`The 'verificationMethods' option must contain exactly one entry`);\n }\n\n // Default to Ed25519 key generation if an algorithm is not given.\n const algorithm = options.algorithm ?? options.verificationMethods?.[0]?.algorithm ?? 'Ed25519';\n\n // Generate a new key using the specified `algorithm`.\n const keyUri = await keyManager.generateKey({ algorithm });\n const publicKey = await keyManager.getPublicKey({ keyUri });\n\n // Compute the DID identifier from the public key by converting the JWK to a multibase-encoded\n // multicodec value.\n const identifier = await DidKeyUtils.publicKeyToMultibaseId({ publicKey });\n\n // Attach the prefix `did:key` to form the complete DID URI.\n const didUri = `did:${DidKey.methodName}:${identifier}`;\n\n // Expand the DID URI string to a DID document.\n const didResolutionResult = await DidKey.resolve(didUri, options);\n const document = didResolutionResult.didDocument as DidDocument;\n\n // Create the BearerDid object from the generated key material.\n const did = new BearerDid({\n uri : didUri,\n document,\n metadata : {},\n keyManager\n });\n\n return did;\n }\n\n /**\n * Given the W3C DID Document of a `did:key` DID, return the verification method that will be used\n * for signing messages and credentials. With DID Key, the first verification method in the\n * authentication property in the DID Document is used.\n *\n * Note that for DID Key, only one verification method intended for signing can exist so\n * specifying `methodId` could be considered redundant or unnecessary. The option is provided for\n * consistency with other DID method implementations.\n *\n * @param params - The parameters for the `getSigningMethod` operation.\n * @param params.didDocument - DID Document to get the verification method from.\n * @param params.methodId - ID of the verification method to use for signing.\n * @returns Verification method to use for signing.\n */\n public static async getSigningMethod({ didDocument }: {\n didDocument: DidDocument;\n methodId?: string;\n }): Promise<DidVerificationMethod> {\n // Verify the DID method is supported.\n const parsedDid = Did.parse(didDocument.id);\n if (parsedDid && parsedDid.method !== this.methodName) {\n throw new DidError(DidErrorCode.MethodNotSupported, `Method not supported: ${parsedDid.method}`);\n }\n\n // Attempt to ge the first verification method intended for signing claims.\n const [ methodId ] = didDocument.assertionMethod || [];\n const verificationMethod = didDocument.verificationMethod?.find(vm => vm.id === methodId);\n\n if (!(verificationMethod && verificationMethod.publicKeyJwk)) {\n throw new DidError(DidErrorCode.InternalError, 'A verification method intended for signing could not be determined from the DID Document');\n }\n\n return verificationMethod;\n }\n\n /**\n * Instantiates a {@link BearerDid} object for the DID Key method from a given {@link PortableDid}.\n *\n * This method allows for the creation of a `BearerDid` object using a previously created DID's\n * key material, DID document, and metadata.\n *\n * @remarks\n * The `verificationMethod` array of the DID document must contain exactly one key since the\n * `did:key` method only supports a single verification method.\n *\n * @example\n * ```ts\n * // Export an existing BearerDid to PortableDid format.\n * const portableDid = await did.export();\n * // Reconstruct a BearerDid object from the PortableDid.\n * const did = await DidKey.import({ portableDid });\n * ```\n *\n * @param params - The parameters for the import operation.\n * @param params.portableDid - The PortableDid object to import.\n * @param params.keyManager - Optionally specify an external Key Management System (KMS) used to\n * generate keys and sign data. If not given, a new\n * {@link LocalKeyManager} instance will be created and\n * used.\n * @returns A Promise resolving to a `BearerDid` object representing the DID formed from the provided keys.\n * @throws An error if the DID document does not contain exactly one verification method.\n */\n public static async import({ portableDid, keyManager = new LocalKeyManager() }: {\n keyManager?: CryptoApi & KeyImporterExporter<KmsImportKeyParams, KeyIdentifier, KmsExportKeyParams>;\n portableDid: PortableDid;\n }): Promise<BearerDid> {\n // Verify the DID method is supported.\n const parsedDid = Did.parse(portableDid.uri);\n if (parsedDid?.method !== DidKey.methodName) {\n throw new DidError(DidErrorCode.MethodNotSupported, `Method not supported`);\n }\n\n // Use the given PortableDid to construct the BearerDid object.\n const did = await BearerDid.import({ portableDid, keyManager });\n\n // Validate that the given DID document contains exactly one verification method.\n // Note: The non-undefined assertion is necessary because the type system cannot infer that\n // the `verificationMethod` property is defined -- which is checked by `BearerDid.import()`.\n if (did.document.verificationMethod!.length !== 1) {\n throw new DidError(DidErrorCode.InvalidDidDocument, `DID document must contain exactly one verification method`);\n }\n\n return did;\n }\n\n /**\n * Resolves a `did:key` identifier to a DID Document.\n *\n * @param didUri - The DID to be resolved.\n * @param options - Optional parameters for resolving the DID.\n * @returns A Promise resolving to a {@link DidResolutionResult} object representing the result of the resolution.\n */\n public static async resolve(didUri: string, options?: DidResolutionOptions): Promise<DidResolutionResult> {\n try {\n // Attempt to expand the DID URI string to a DID document.\n const didDocument = await DidKey.createDocument({ didUri, options });\n\n // If the DID document was created successfully, return it.\n return {\n ...EMPTY_DID_RESOLUTION_RESULT,\n didDocument,\n };\n\n } catch (error: any) {\n // Rethrow any unexpected errors that are not a `DidError`.\n if (!(error instanceof DidError)) {throw new Error(error);}\n\n // Return a DID Resolution Result with the appropriate error code.\n return {\n ...EMPTY_DID_RESOLUTION_RESULT,\n didResolutionMetadata: {\n error: error.code,\n ...error.message && { errorMessage: error.message }\n }\n };\n }\n }\n\n /**\n * Expands a did:key identifier to a DID Document.\n *\n * Reference: https://w3c-ccg.github.io/did-method-key/#document-creation-algorithm\n *\n * @param options\n * @returns - A DID dodcument.\n */\n private static async createDocument({ didUri, options = {} }: {\n didUri: string;\n options?: Exclude<DidKeyCreateOptions<CryptoApi>, 'algorithm' | 'verificationMethods'> | DidResolutionOptions;\n }): Promise<DidDocument> {\n const {\n defaultContext = 'https://www.w3.org/ns/did/v1',\n enableExperimentalPublicKeyTypes = false,\n publicKeyFormat = 'JsonWebKey2020'\n } = options;\n\n /**\n * 1. Initialize document to an empty object.\n */\n const didDocument: DidDocument = { id: '' };\n\n /**\n * 2. Using a colon (:) as the delimiter, split the identifier into its\n * components: a scheme, a method, a version, and a multibaseValue.\n * If there are only three components set the version to the string\n * value 1 and use the last value as the multibaseValue.\n */\n const parsedDid = Did.parse(didUri);\n if (!parsedDid) {\n throw new DidError(DidErrorCode.InvalidDid, `Invalid DID URI: ${didUri}`);\n }\n const multibaseValue = parsedDid.id;\n\n /**\n * 3. Check the validity of the input identifier.\n * The scheme MUST be the value did. The method MUST be the value key.\n * The version MUST be convertible to a positive integer value. The\n * multibaseValue MUST be a string and begin with the letter z. If any\n * of these requirements fail, an invalidDid error MUST be raised.\n */\n if (parsedDid.method !== DidKey.methodName) {\n throw new DidError(DidErrorCode.MethodNotSupported, `Method not supported: ${parsedDid.method}`);\n }\n if (!DidKey.validateIdentifier(parsedDid)) {\n throw new DidError(DidErrorCode.InvalidDid, `Invalid DID URI: ${didUri}`);\n }\n\n /**\n * 4. Initialize the signatureVerificationMethod to the result of passing\n * identifier, multibaseValue, and options to a\n * {@link https://w3c-ccg.github.io/did-method-key/#signature-method-creation-algorithm | Signature Method Creation Algorithm}.\n */\n const signatureVerificationMethod = await DidKey.createSignatureMethod({\n didUri,\n multibaseValue,\n options: { enableExperimentalPublicKeyTypes, publicKeyFormat }\n });\n\n /**\n * 5. Set document.id to identifier. If document.id is not a valid DID,\n * an invalidDid error MUST be raised.\n *\n * Note: Identifier was already confirmed to be valid in Step 3, so\n * skipping the redundant validation.\n */\n didDocument.id = parsedDid.uri;\n\n /**\n * 6. Initialize the verificationMethod property in document to an array\n * where the first value is the signatureVerificationMethod.\n */\n didDocument.verificationMethod = [signatureVerificationMethod];\n\n /**\n * 7. Initialize the authentication, assertionMethod, capabilityInvocation,\n * and the capabilityDelegation properties in document to an array where\n * the first item is the value of the id property in\n * signatureVerificationMethod.\n */\n didDocument.authentication = [signatureVerificationMethod.id];\n didDocument.assertionMethod = [signatureVerificationMethod.id];\n didDocument.capabilityInvocation = [signatureVerificationMethod.id];\n didDocument.capabilityDelegation = [signatureVerificationMethod.id];\n\n /**\n * 8. Initialize the @context property in document to the result of passing document and options to the Context\n * Creation algorithm.\n */\n // Set contextArray to an array that is initialized to options.defaultContext.\n const contextArray = [ defaultContext ];\n\n // For every object in every verification relationship listed in document,\n // add a string value to the contextArray based on the object type value,\n // if it doesn't already exist, according to the following table:\n // {@link https://w3c-ccg.github.io/did-method-key/#context-creation-algorithm | Context Type URL}\n const verificationMethodTypes = getVerificationMethodTypes({ didDocument });\n verificationMethodTypes.forEach((typeName: string) => {\n const typeUrl = DidKeyVerificationMethodType[typeName as keyof typeof DidKeyVerificationMethodType];\n contextArray.push(typeUrl);\n });\n didDocument['@context'] = contextArray;\n\n /**\n * 10. Return document.\n */\n return didDocument;\n }\n\n /**\n * Decodes a multibase-encoded multicodec value into a verification method\n * that is suitable for verifying digital signatures.\n * @param options - Signature method creation algorithm inputs.\n * @returns - A verification method.\n */\n private static async createSignatureMethod({ didUri, multibaseValue, options }: {\n didUri: string;\n multibaseValue: string;\n options: Required<Pick<DidKeyCreateOptions<CryptoApi>, 'enableExperimentalPublicKeyTypes' | 'publicKeyFormat'>>\n }): Promise<DidVerificationMethod> {\n const { enableExperimentalPublicKeyTypes, publicKeyFormat } = options;\n\n /**\n * 1. Initialize verificationMethod to an empty object.\n */\n const verificationMethod: DidVerificationMethod = { id: '', type: '', controller: '' };\n\n /**\n * 2. Set multicodecValue and publicKeyBytes to the result of passing\n * multibaseValue and options to a Decode Public Key algorithm.\n */\n const {\n keyBytes: publicKeyBytes,\n multicodecCode: multicodecValue,\n multicodecName\n } = multibaseIdToKeyBytes({ multibaseKeyId: multibaseValue });\n\n /**\n * 3. Ensure the proper key length of publicKeyBytes based on the multicodecValue\n * {@link https://w3c-ccg.github.io/did-method-key/#signature-method-creation-algorithm | table provided}.\n * If the byte length of rawPublicKeyBytes does not match the expected public key length for the\n * associated multicodecValue, an invalidPublicKeyLength error MUST be raised.\n */\n const actualLength = publicKeyBytes.byteLength;\n const expectedLength = DidKeyUtils.MULTICODEC_PUBLIC_KEY_LENGTH[multicodecValue];\n if (actualLength !== expectedLength) {\n throw new DidError(DidErrorCode.InvalidPublicKeyLength, `Expected ${actualLength} bytes. Actual: ${expectedLength}`);\n }\n\n /**\n * 4. Ensure the publicKeyBytes are a proper encoding of the public key type as specified by\n * the multicodecValue. If an invalid public key value is detected, an invalidPublicKey error\n * MUST be raised.\n */\n let isValid = false;\n switch (multicodecName) {\n case 'secp256k1-pub':\n isValid = await Secp256k1.validatePublicKey({ publicKeyBytes });\n break;\n case 'ed25519-pub':\n isValid = await Ed25519.validatePublicKey({ publicKeyBytes });\n break;\n }\n if (!isValid) {\n throw new DidError(DidErrorCode.InvalidPublicKey, 'Invalid public key detected.');\n }\n\n /**\n * 5. Set the verificationMethod.id value by concatenating identifier, a hash character (#), and\n * the multibaseValue. If verificationMethod.id is not a valid DID URL, an invalidDidUrl error\n * MUST be raised.\n */\n verificationMethod.id = `${didUri}#${multibaseValue}`;\n try {\n new URL(verificationMethod.id);\n } catch {\n throw new DidError(DidErrorCode.InvalidDidUrl, 'Verification Method ID is not a valid DID URL.');\n }\n\n /**\n * 6. Set the publicKeyFormat value to the options.publicKeyFormat value.\n * 7. If publicKeyFormat is not known to the implementation, an unsupportedPublicKeyType error\n * MUST be raised.\n */\n if (!(publicKeyFormat in DidKeyVerificationMethodType)) {\n throw new DidError(DidErrorCode.UnsupportedPublicKeyType, `Unsupported format: ${publicKeyFormat}`);\n }\n\n /**\n * 8. If options.enableExperimentalPublicKeyTypes is set to false and publicKeyFormat is not\n * Multikey, JsonWebKey2020, or Ed25519VerificationKey2020, an invalidPublicKeyType error MUST\n * be raised.\n */\n const StandardPublicKeyTypes = ['Multikey', 'JsonWebKey2020', 'Ed25519VerificationKey2020'];\n if (enableExperimentalPublicKeyTypes === false\n && !(StandardPublicKeyTypes.includes(publicKeyFormat))) {\n throw new DidError(\n DidErrorCode.InvalidPublicKeyType,\n `Specified '${publicKeyFormat}' without setting enableExperimentalPublicKeyTypes to true.`\n );\n }\n\n /**\n * 9. Set verificationMethod.type to the publicKeyFormat value.\n */\n verificationMethod.type = publicKeyFormat;\n\n /**\n * 10. Set verificationMethod.controller to the identifier value.\n */\n verificationMethod.controller = didUri;\n\n /**\n * 11. If publicKeyFormat is Multikey or Ed25519VerificationKey2020,\n * set the verificationMethod.publicKeyMultibase value to multibaseValue.\n *\n * Note: This implementation does not currently support the Multikey\n * format.\n */\n if (publicKeyFormat === 'Ed25519VerificationKey2020') {\n verificationMethod.publicKeyMultibase = multibaseValue;\n }\n\n /**\n * 12. If publicKeyFormat is JsonWebKey2020, set the verificationMethod.publicKeyJwk value to\n * the result of passing multicodecValue and rawPublicKeyBytes to a JWK encoding algorithm.\n */\n if (publicKeyFormat === 'JsonWebKey2020') {\n const { crv } = await DidKeyUtils.multicodecToJwk({ code: multicodecValue });\n verificationMethod.publicKeyJwk = await DidKeyUtils.keyConverter(crv!).bytesToPublicKey({ publicKeyBytes });\n }\n\n /**\n * 13. Return verificationMethod.\n */\n return verificationMethod;\n }\n\n\n /**\n * Validates the structure and components of a DID URI against the `did:key` method specification.\n *\n * @param parsedDid - An object representing the parsed components of a DID URI, including the\n * scheme, method, and method-specific identifier.\n * @returns `true` if the DID URI meets the `did:key` method's structural requirements, `false` otherwise.\n *\n */\n private static validateIdentifier(parsedDid: Did): boolean {\n const { method, id: multibaseValue } = parsedDid;\n const [ scheme ] = parsedDid.uri.split(':', 1);\n\n /**\n * Note: The W3C DID specification makes no mention of a version value being part of the DID\n * syntax. Additionally, there does not appear to be any real-world usage of the version\n * number. Consequently, this implementation will ignore the version related guidance in\n * the did:key specification.\n */\n const version = '1';\n\n return (\n scheme === 'did' &&\n method === 'key' &&\n Number(version) > 0 &&\n universalTypeOf(multibaseValue) === 'String' &&\n multibaseValue.startsWith('z')\n );\n }\n}\n\n/**\n * The `DidKeyUtils` class provides utility functions to support operations in the DID Key method.\n */\nexport class DidKeyUtils {\n /**\n * A mapping from JSON Web Key (JWK) property descriptors to multicodec names.\n *\n * This mapping is used to convert keys in JWK (JSON Web Key) format to multicodec format.\n *\n * @remarks\n * The keys of this object are strings that describe the JOSE key type and usage,\n * such as 'Ed25519:public', 'Ed25519:private', etc. The values are the corresponding multicodec\n * names used to represent these key types.\n *\n * @example\n * ```ts\n * const multicodecName = JWK_TO_MULTICODEC['Ed25519:public'];\n * // Returns 'ed25519-pub', the multicodec name for an Ed25519 public key\n * ```\n */\n private static JWK_TO_MULTICODEC: { [key: string]: string } = {\n 'Ed25519:public' : 'ed25519-pub',\n 'Ed25519:private' : 'ed25519-priv',\n 'secp256k1:public' : 'secp256k1-pub',\n 'secp256k1:private' : 'secp256k1-priv',\n };\n\n /**\n * Defines the expected byte lengths for public keys associated with different cryptographic\n * algorithms, indexed by their multicodec code values.\n */\n public static MULTICODEC_PUBLIC_KEY_LENGTH: Record<number, number> = {\n // secp256k1-pub - Secp256k1 public key (compressed) - 33 bytes\n 0xe7: 33,\n\n // ed25519-pub - Ed25519 public key - 32 bytes\n 0xed: 32\n };\n\n /**\n * A mapping from multicodec names to their corresponding JOSE (JSON Object Signing and Encryption)\n * representations. This mapping facilitates the conversion of multicodec key formats to\n * JWK (JSON Web Key) formats.\n *\n * @remarks\n * The keys of this object are multicodec names, such as 'ed25519-pub', 'ed25519-priv', etc.\n * The values are objects representing the corresponding JWK properties for that key type.\n *\n * @example\n * ```ts\n * const joseKey = MULTICODEC_TO_JWK['ed25519-pub'];\n * // Returns a partial JWK for an Ed25519 public key\n * ```\n */\n private static MULTICODEC_TO_JWK: { [key: string]: Jwk } = {\n 'ed25519-pub' : { crv: 'Ed25519', kty: 'OKP', x: '' },\n 'ed25519-priv' : { crv: 'Ed25519', kty: 'OKP', x: '', d: '' },\n 'secp256k1-pub' : { crv: 'secp256k1', kty: 'EC', x: '', y: '' },\n 'secp256k1-priv' : { crv: 'secp256k1', kty: 'EC', x: '', y: '', d: '' },\n };\n\n /**\n * Converts a JWK (JSON Web Key) to a Multicodec code and name.\n *\n * @example\n * ```ts\n * const jwk: Jwk = { crv: 'Ed25519', kty: 'OKP', x: '...' };\n * const { code, name } = await DidKeyUtils.jwkToMulticodec({ jwk });\n * ```\n *\n * @param params - The parameters for the conversion.\n * @param params.jwk - The JSON Web Key to be converted.\n * @returns A promise that resolves to a Multicodec definition.\n */\n public static async jwkToMulticodec({ jwk }: {\n jwk: Jwk\n }): Promise<MulticodecDefinition<MulticodecCode>> {\n const params: string[] = [];\n\n if (jwk.crv) {\n params.push(jwk.crv);\n if (jwk.d) {\n params.push('private');\n } else {\n params.push('public');\n }\n }\n\n const lookupKey = params.join(':');\n const name = DidKeyUtils.JWK_TO_MULTICODEC[lookupKey];\n\n if (name === undefined) {\n throw new Error(`Unsupported JWK to Multicodec conversion: '${lookupKey}'`);\n }\n\n const code = Multicodec.getCodeFromName({ name });\n\n return { code, name };\n }\n\n /**\n * Returns the appropriate public key compressor for the specified cryptographic curve.\n *\n * @param curve - The cryptographic curve to use for the key conversion.\n * @returns A public key compressor for the specified curve.\n */\n public static keyCompressor(\n curve: string\n ): KeyCompressor['compressPublicKey'] {\n // ): ({ publicKeyBytes }: { publicKeyBytes: Uint8Array }) => Promise<Uint8Array> {\n const compressors = {\n 'P-256' : Secp256r1.compressPublicKey,\n 'secp256k1' : Secp256k1.compressPublicKey\n } as Record<string, KeyCompressor['compressPublicKey']>;\n\n const compressor = compressors[curve];\n\n if (!compressor) {throw new DidError(DidErrorCode.InvalidPublicKeyType, `Unsupported curve: ${curve}`);}\n\n return compressor;\n }\n\n /**\n * Returns the appropriate key converter for the specified cryptographic curve.\n *\n * @param curve - The cryptographic curve to use for the key conversion.\n * @returns An `AsymmetricKeyConverter` for the specified curve.\n */\n public static keyConverter(curve: string): AsymmetricKeyConverter {\n const converters: Record<string, AsymmetricKeyConverter> = {\n 'Ed25519' : Ed25519,\n 'P-256' : Secp256r1,\n 'secp256k1' : Secp256k1,\n };\n\n const converter = converters[curve];\n\n if (!converter) {throw new DidError(DidErrorCode.InvalidPublicKeyType, `Unsupported curve: ${curve}`);}\n\n return converter;\n }\n\n /**\n * Converts a Multicodec code or name to parial JWK (JSON Web Key).\n *\n * @example\n * ```ts\n * const partialJwk = await DidKeyUtils.multicodecToJwk({ name: 'ed25519-pub' });\n * ```\n *\n * @param params - The parameters for the conversion.\n * @param params.code - Optional Multicodec code to convert.\n * @param params.name - Optional Multicodec name to convert.\n * @returns A promise that resolves to a JOSE format key.\n */\n public static async multicodecToJwk({ code, name }: {\n code?: MulticodecCode,\n name?: string\n }): Promise<Jwk> {\n // Either code or name must be specified, but not both.\n if (!(name ? !code : code)) {\n throw new Error(`Either 'name' or 'code' must be defined, but not both.`);\n }\n\n // If name is undefined, lookup by code.\n name = (name === undefined ) ? Multicodec.getNameFromCode({ code: code! }) : name;\n\n const lookupKey = name;\n const jose = DidKeyUtils.MULTICODEC_TO_JWK[lookupKey];\n\n if (jose === undefined) {\n throw new Error(`Unsupported Multicodec to JWK conversion`);\n }\n\n return { ...jose };\n }\n\n /**\n * Converts a public key in JWK (JSON Web Key) format to a multibase identifier.\n *\n * @remarks\n * Note: All secp public keys are converted to compressed point encoding\n * before the multibase identifier is computed.\n *\n * Per {@link https://github.com/multiformats/multicodec/blob/master/table.csv | Multicodec table}:\n * Public keys for Elliptic Curve cryptography algorithms (e.g., secp256k1,\n * secp256k1r1, secp384r1, etc.) are always represented with compressed point\n * encoding (e.g., secp256k1-pub, p256-pub, p384-pub, etc.).\n *\n * Per {@link https://datatracker.ietf.org/doc/html/rfc8812#name-jose-and-cose-secp256k1-cur | RFC 8812}:\n * \"As a compressed point encoding representation is not defined for JWK\n * elliptic curve points, the uncompressed point encoding defined there\n * MUST be used. The x and y values represented MUST both be exactly\n * 256 bits, with any leading zeros preserved.\"\n *\n * @example\n * ```ts\n * const publicKey = { crv: 'Ed25519', kty: 'OKP', x: '...' };\n * const multibaseId = await DidKeyUtils.publicKeyToMultibaseId({ publicKey });\n * ```\n *\n * @param params - The parameters for the conversion.\n * @param params.publicKey - The public key in JWK format.\n * @returns A promise that resolves to the multibase identifier.\n */\n public static async publicKeyToMultibaseId({ publicKey }: {\n publicKey: Jwk\n }): Promise<string> {\n if (!(publicKey?.crv && publicKey.crv in AlgorithmToKeyTypeMap)) {\n throw new DidError(DidErrorCode.InvalidPublicKeyType, `Public key contains an unsupported key type: ${publicKey?.crv ?? 'undefined'}`);\n }\n\n // Convert the public key from JWK format to a byte array.\n let publicKeyBytes = await DidKeyUtils.keyConverter(publicKey.crv).publicKeyToBytes({ publicKey });\n\n // Compress the public key if it is an elliptic curve key.\n if (/^(secp256k1|P-256|P-384|P-521)$/.test(publicKey.crv)) {\n publicKeyBytes = await DidKeyUtils.keyCompressor(publicKey.crv)({ publicKeyBytes });\n }\n\n // Convert the JSON Web Key (JWK) parameters to a Multicodec name.\n const { name: multicodecName } = await DidKeyUtils.jwkToMulticodec({ jwk: publicKey });\n\n // Compute the multibase identifier based on the provided key.\n const multibaseId = keyBytesToMultibaseId({\n keyBytes: publicKeyBytes,\n multicodecName\n });\n\n return multibaseId;\n }\n}", "import type { DidDocument, DidResolutionOptions, DidResolutionResult } from '../types/did-core.js';\n\nimport { Did } from '../did.js';\nimport { DidMethod } from './did-method.js';\nimport { EMPTY_DID_RESOLUTION_RESULT } from '../types/did-resolution.js';\n\n/**\n * The `DidWeb` class provides an implementation of the `did:web` DID method.\n *\n * Features:\n * - DID Resolution: Resolve a `did:web` to its corresponding DID Document.\n *\n * @remarks\n * The `did:web` method uses a web domain's existing reputation and aims to integrate decentralized\n * identities with the existing web infrastructure to drive adoption. It leverages familiar web\n * security models and domain ownership to provide accessible, interoperable digital identity\n * management.\n *\n * @see {@link https://w3c-ccg.github.io/did-method-web/ | DID Web Specification}\n *\n * @example\n * ```ts\n * // DID Resolution\n * const resolutionResult = await DidWeb.resolve({ did: did.uri });\n * ```\n */\nexport class DidWeb extends DidMethod {\n\n /**\n * Name of the DID method, as defined in the DID Web specification.\n */\n public static methodName = 'web';\n\n /**\n * Resolves a `did:web` identifier to a DID Document.\n *\n * @param didUri - The DID to be resolved.\n * @param _options - Optional parameters for resolving the DID. Unused by this DID method.\n * @returns A Promise resolving to a {@link DidResolutionResult} object representing the result of the resolution.\n */\n public static async resolve(didUri: string, _options?: DidResolutionOptions): Promise<DidResolutionResult> {\n // Attempt to parse the DID URI.\n const parsedDid = Did.parse(didUri);\n\n // If parsing failed, the DID is invalid.\n if (!parsedDid) {\n return {\n ...EMPTY_DID_RESOLUTION_RESULT,\n didResolutionMetadata: { error: 'invalidDid' }\n };\n }\n\n // If the DID method is not \"web\", return an error.\n if (parsedDid.method !== DidWeb.methodName) {\n return {\n ...EMPTY_DID_RESOLUTION_RESULT,\n didResolutionMetadata: { error: 'methodNotSupported' }\n };\n }\n\n // Replace \":\" with \"/\" in the identifier and prepend \"https://\" to obtain the fully qualified\n // domain name and optional path.\n let baseUrl = `https://${parsedDid.id.replace(/:/g, '/')}`;\n\n // If the domain contains a percent encoded port value, decode the colon.\n baseUrl = decodeURIComponent(baseUrl);\n\n // Append the expected location of the DID document depending on whether a path was specified.\n const didDocumentUrl = parsedDid.id.includes(':') ?\n `${baseUrl}/did.json` :\n `${baseUrl}/.well-known/did.json`;\n\n try {\n // Perform an HTTP GET request to obtain the DID document.\n const response = await fetch(didDocumentUrl);\n\n // If the response status code is not 200, return an error.\n if (!response.ok) {throw new Error('HTTP error status code returned');}\n\n // Parse the DID document.\n const didDocument = await response.json() as DidDocument;\n\n return {\n ...EMPTY_DID_RESOLUTION_RESULT,\n didDocument,\n };\n\n } catch {\n // If the DID document could not be retrieved, return an error.\n return {\n ...EMPTY_DID_RESOLUTION_RESULT,\n didResolutionMetadata: { error: 'notFound' }\n };\n }\n }\n}", "import type { AbstractLevel } from 'abstract-level';\n\nimport { Level } from 'level';\nimport ms from 'ms';\n\nimport type { DidResolutionResult } from '../types/did-core.js';\nimport type { DidResolverCache } from '../types/did-resolution.js';\n\n/**\n * Configuration parameters for creating a LevelDB-based cache for DID resolution results.\n *\n * Allows customization of the underlying database instance, storage location, and cache\n * time-to-live (TTL) settings.\n */\nexport type DidResolverCacheLevelParams = {\n /**\n * Optional. An instance of `AbstractLevel` to use as the database. If not provided, a new\n * LevelDB instance will be created at the specified `location`.\n */\n db?: AbstractLevel<string | Buffer | Uint8Array, string, string>;\n\n /**\n * Optional. The file system path or IndexedDB name where the LevelDB store will be created.\n * Defaults to 'DATA/DID_RESOLVERCACHE' if not specified.\n */\n location?: string;\n\n /**\n * Optional. The time-to-live for cache entries, expressed as a string (e.g., '1h', '15m').\n * Determines how long a cache entry should remain valid before being considered expired. Defaults\n * to '15m' if not specified.\n */\n ttl?: string;\n};\n\n/**\n * Encapsulates a DID resolution result along with its expiration information for caching purposes.\n *\n * This type is used internally by the `DidResolverCacheLevel` to store DID resolution results\n * with an associated time-to-live (TTL) value. The TTL is represented in milliseconds and\n * determines when the cached entry is considered expired and eligible for removal.\n */\ntype CachedDidResolutionResult = {\n /**\n * The expiration time of the cache entry in milliseconds since the Unix epoch.\n *\n * This value is used to calculate whether the cached entry is still valid or has expired.\n */\n ttlMillis: number;\n\n /**\n * The DID resolution result being cached.\n *\n * This object contains the resolved DID document and associated metadata.\n */\n value: DidResolutionResult;\n};\n\n/**\n * A Level-based cache implementation for storing and retrieving DID resolution results.\n *\n * This cache uses LevelDB for storage, allowing data persistence across process restarts or\n * browser refreshes. It's suitable for both Node.js and browser environments.\n *\n * @remarks\n * The LevelDB cache keeps data in memory for fast access and also writes to the filesystem in\n * Node.js or indexedDB in browsers. Time-to-live (TTL) for cache entries is configurable.\n *\n * @example\n * ```\n * const cache = new DidResolverCacheLevel({ ttl: '15m' });\n * ```\n */\nexport class DidResolverCacheLevel implements DidResolverCache {\n /** The underlying LevelDB store used for caching. */\n protected cache;\n\n /** The time-to-live for cache entries in milliseconds. */\n protected ttl: number;\n\n constructor({\n db,\n location = 'DATA/DID_RESOLVERCACHE',\n ttl = '15m'\n }: DidResolverCacheLevelParams = {}) {\n this.cache = db ?? new Level<string, string>(location);\n this.ttl = ms(ttl);\n }\n\n /**\n * Retrieves a DID resolution result from the cache.\n *\n * If the cached item has exceeded its TTL, it's scheduled for deletion and undefined is returned.\n *\n * @param did - The DID string used as the key for retrieving the cached result.\n * @returns The cached DID resolution result or undefined if not found or expired.\n */\n async get(did: string): Promise<DidResolutionResult | void> {\n try {\n const str = await this.cache.get(did);\n const cachedDidResolutionResult: CachedDidResolutionResult = JSON.parse(str);\n\n if (Date.now() >= cachedDidResolutionResult.ttlMillis) {\n // defer deletion to be called in the next tick of the js event loop\n this.cache.nextTick(() => this.cache.del(did));\n\n return;\n } else {\n return cachedDidResolutionResult.value;\n }\n\n } catch (error: any) {\n // Don't throw when a key wasn't found.\n if (error.notFound) {\n return;\n }\n\n throw error;\n }\n }\n\n /**\n * Stores a DID resolution result in the cache with a TTL.\n *\n * @param did - The DID string used as the key for storing the result.\n * @param value - The DID resolution result to be cached.\n * @returns A promise that resolves when the operation is complete.\n */\n set(did: string, value: DidResolutionResult): Promise<void> {\n const cachedDidResolutionResult: CachedDidResolutionResult = { ttlMillis: Date.now() + this.ttl, value };\n const str = JSON.stringify(cachedDidResolutionResult);\n\n return this.cache.put(did, str);\n }\n\n /**\n * Deletes a DID resolution result from the cache.\n *\n * @param did - The DID string used as the key for deletion.\n * @returns A promise that resolves when the operation is complete.\n */\n delete(did: string): Promise<void> {\n return this.cache.del(did);\n }\n\n /**\n * Clears all entries from the cache.\n *\n * @returns A promise that resolves when the operation is complete.\n */\n clear(): Promise<void> {\n return this.cache.clear();\n }\n\n /**\n * Closes the underlying LevelDB store.\n *\n * @returns A promise that resolves when the store is closed.\n */\n close(): Promise<void> {\n return this.cache.close();\n }\n}", "import type { DidResolutionResult } from '../types/did-core.js';\nimport type { DidResolverCache } from '../types/did-resolution.js';\n\n/**\n * No-op cache that is used as the default cache for did-resolver.\n *\n * The motivation behind using a no-op cache as the default stems from the desire to maximize the\n * potential for this library to be used in as many JS runtimes as possible.\n */\nexport const DidResolverCacheNoop: DidResolverCache = {\n get(_key: string): Promise<DidResolutionResult | void> {\n return Promise.resolve(undefined);\n },\n set(_key: string, _value: DidResolutionResult): Promise<void> {\n return Promise.resolve();\n },\n delete(_key: string): Promise<boolean | void> {\n return Promise.resolve();\n },\n clear(): Promise<void> {\n return Promise.resolve();\n },\n close(): Promise<void> {\n return Promise.resolve();\n }\n};", "import type { DidMethodResolver } from '../methods/did-method.js';\nimport type { DidDereferencingOptions, DidDereferencingResult, DidResolutionOptions, DidResolutionResult, DidResource } from '../types/did-core.js';\nimport type { DidResolver, DidResolverCache, DidUrlDereferencer } from '../types/did-resolution.js';\n\nimport { Did } from '../did.js';\nimport { DidErrorCode } from '../did-error.js';\nimport { DidResolverCacheNoop } from './resolver-cache-noop.js';\nimport { EMPTY_DID_RESOLUTION_RESULT } from '../types/did-resolution.js';\n\n/**\n * Parameters for configuring the `UniversalResolver` class, which is responsible for resolving\n * decentralized identifiers (DIDs) to their corresponding DID documents.\n *\n * This type specifies the essential components required by the `UniversalResolver` to perform\n * DID resolution and dereferencing. It includes an array of `DidMethodResolver` instances,\n * each capable of resolving DIDs for a specific method, and optionally, a cache for storing\n * resolved DID documents to improve resolution efficiency.\n */\nexport type UniversalResolverParams = {\n /**\n * An array of `DidMethodResolver` instances.\n *\n * Each resolver in this array is designed to handle a specific DID method, enabling the\n * `DidResolver` to support multiple DID methods simultaneously.\n */\n didResolvers: DidMethodResolver[];\n\n /**\n * An optional `DidResolverCache` instance used for caching resolved DID documents.\n *\n * Providing a cache implementation can significantly enhance resolution performance by avoiding\n * redundant resolutions for previously resolved DIDs. If omitted, a no-operation cache is used,\n * which effectively disables caching.\n */\n cache?: DidResolverCache;\n};\n\n/**\n * The `DidResolver` class provides mechanisms for resolving Decentralized Identifiers (DIDs) to\n * their corresponding DID documents.\n *\n * The class is designed to handle various DID methods by utilizing an array of `DidMethodResolver`\n * instances, each responsible for a specific DID method.\n *\n * Providing a cache implementation can significantly enhance resolution performance by avoiding\n * redundant resolutions for previously resolved DIDs. If omitted, a no-operation cache is used,\n * which effectively disables caching.\n *\n * Usage:\n * - Construct the `DidResolver` with an array of `DidMethodResolver` instances and an optional cache.\n * - Use `resolve` to resolve a DID to its DID Resolution Result.\n * - Use `dereference` to extract specific resources from a DID URL, like service endpoints or verification methods.\n *\n * @example\n * ```ts\n * const resolver = new DidResolver({\n * didResolvers: [<array of DidMethodResolver instances>],\n * cache: new DidResolverCacheNoop()\n * });\n *\n * const resolutionResult = await resolver.resolve('did:example:123456');\n * const dereferenceResult = await resolver.dereference({ didUri: 'did:example:123456#key-1' });\n * ```\n */\nexport class UniversalResolver implements DidResolver, DidUrlDereferencer {\n /**\n * A cache for storing resolved DID documents.\n */\n protected cache: DidResolverCache;\n\n /**\n * A map to store method resolvers against method names.\n */\n private didResolvers: Map<string, DidMethodResolver> = new Map();\n\n /**\n * Constructs a new `DidResolver`.\n *\n * @param params - The parameters for constructing the `DidResolver`.\n */\n constructor({ cache, didResolvers }: UniversalResolverParams) {\n this.cache = cache || DidResolverCacheNoop;\n\n for (const resolver of didResolvers) {\n this.didResolvers.set(resolver.methodName, resolver);\n }\n }\n\n /**\n * Resolves a DID to a DID Resolution Result.\n *\n * If the DID Resolution Result is present in the cache, it returns the cached result. Otherwise,\n * it uses the appropriate method resolver to resolve the DID, stores the resolution result in the\n * cache, and returns the resolultion result.\n *\n * @param didUri - The DID or DID URL to resolve.\n * @returns A promise that resolves to the DID Resolution Result.\n */\n public async resolve(didUri: string, options?: DidResolutionOptions): Promise<DidResolutionResult> {\n\n const parsedDid = Did.parse(didUri);\n if (!parsedDid) {\n return {\n ...EMPTY_DID_RESOLUTION_RESULT,\n didResolutionMetadata: {\n error : DidErrorCode.InvalidDid,\n errorMessage : `Invalid DID URI: ${didUri}`\n }\n };\n }\n\n const resolver = this.didResolvers.get(parsedDid.method);\n if (!resolver) {\n return {\n ...EMPTY_DID_RESOLUTION_RESULT,\n didResolutionMetadata: {\n error : DidErrorCode.MethodNotSupported,\n errorMessage : `Method not supported: ${parsedDid.method}`\n }\n };\n }\n\n const cachedResolutionResult = await this.cache.get(parsedDid.uri);\n\n if (cachedResolutionResult) {\n return cachedResolutionResult;\n } else {\n const resolutionResult = await resolver.resolve(parsedDid.uri, options);\n if (!resolutionResult.didResolutionMetadata.error) {\n // Cache the resolution result if it was successful.\n await this.cache.set(parsedDid.uri, resolutionResult);\n }\n\n return resolutionResult;\n }\n }\n\n /**\n * Dereferences a DID (Decentralized Identifier) URL to a corresponding DID resource.\n *\n * This method interprets the DID URL's components, which include the DID method, method-specific\n * identifier, path, query, and fragment, and retrieves the related resource as per the DID Core\n * specifications.\n *\n * The dereferencing process involves resolving the DID contained in the DID URL to a DID document,\n * and then extracting the specific part of the document identified by the fragment in the DID URL.\n * If no fragment is specified, the entire DID document is returned.\n *\n * This method supports resolution of different components within a DID document such as service\n * endpoints and verification methods, based on their IDs. It accommodates both full and\n * DID URLs as specified in the DID Core specification.\n *\n * More information on DID URL dereferencing can be found in the\n * {@link https://www.w3.org/TR/did-core/#did-url-dereferencing | DID Core specification}.\n *\n * TODO: This is a partial implementation and does not fully implement DID URL dereferencing. (https://github.com/enboxorg/enbox/issues/387)\n *\n * @param didUrl - The DID URL string to dereference.\n * @param [_options] - Input options to the dereference function. Optional.\n * @returns a {@link DidDereferencingResult}\n */\n async dereference(\n didUrl: string,\n _options?: DidDereferencingOptions\n ): Promise<DidDereferencingResult> {\n\n // Validate the given `didUrl` confirms to the DID URL syntax.\n const parsedDidUrl = Did.parse(didUrl);\n\n if (!parsedDidUrl) {\n return {\n dereferencingMetadata : { error: DidErrorCode.InvalidDidUrl },\n contentStream : null,\n contentMetadata : {}\n };\n }\n\n // Obtain the DID document for the input DID by executing DID resolution.\n const { didDocument, didResolutionMetadata, didDocumentMetadata } = await this.resolve(parsedDidUrl.uri);\n\n if (!didDocument) {\n return {\n dereferencingMetadata : { error: didResolutionMetadata.error },\n contentStream : null,\n contentMetadata : {}\n };\n }\n\n // Return the entire DID Document if no query or fragment is present on the DID URL.\n if (!parsedDidUrl.fragment || parsedDidUrl.query) {\n return {\n dereferencingMetadata : { contentType: 'application/did+json' },\n contentStream : didDocument,\n contentMetadata : didDocumentMetadata\n };\n }\n\n const { service = [], verificationMethod = [] } = didDocument;\n\n // Create a set of possible id matches. The DID spec allows for an id to be the entire\n // did#fragment or just #fragment.\n // @see {@link }https://www.w3.org/TR/did-core/#relative-did-urls | Section 3.2.2, Relative DID URLs}.\n // Using a Set for fast string comparison since some DID methods have long identifiers.\n const idSet = new Set([didUrl, parsedDidUrl.fragment, `#${parsedDidUrl.fragment}`]);\n\n let didResource: DidResource | undefined;\n\n // Find the first matching verification method in the DID document.\n for (const vm of verificationMethod) {\n if (idSet.has(vm.id)) {\n didResource = vm;\n break;\n }\n }\n\n // Find the first matching service in the DID document.\n for (const svc of service) {\n if (idSet.has(svc.id)) {\n didResource = svc;\n break;\n }\n }\n\n if (didResource) {\n return {\n dereferencingMetadata : { contentType: 'application/did+json' },\n contentStream : didResource,\n contentMetadata : didResolutionMetadata\n };\n } else {\n return {\n dereferencingMetadata : { error: DidErrorCode.NotFound },\n contentStream : null,\n contentMetadata : {},\n };\n }\n }\n}"],
5
- "mappings": "4pBAAA,IAAAA,GAAAC,GAAAC,IAAA,kBAAAC,GAAA,OAEAD,GAAQ,WAAaE,GACrBF,GAAQ,YAAcG,GACtBH,GAAQ,cAAgBI,GAExB,IAAIC,GAAS,CAAC,EAC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- "names": ["require_base64_js", "__commonJSMin", "exports", "import_buffer_polyfill", "byteLength", "toByteArray", "fromByteArray", "lookup", "revLookup", "Arr", "code", "i", "len", "getLens", "b64", "validLen", "placeHoldersLen", "lens", "_byteLength", "tmp", "arr", "curByte", "tripletToBase64", "num", "encodeChunk", "uint8", "start", "end", "output", "extraBytes", "parts", "maxChunkLength", "len2", "require_ieee754", "__commonJSMin", "exports", "import_buffer_polyfill", "buffer", "offset", "isLE", "mLen", "nBytes", "e", "m", "eLen", "eMax", "eBias", "nBits", "i", "d", "s", "value", "c", "rt", "require_buffer", "__commonJSMin", "exports", "import_buffer_polyfill", "base64", "ieee754", "customInspectSymbol", "Buffer", "SlowBuffer", "K_MAX_LENGTH", "typedArraySupport", "arr", "proto", "createBuffer", "length", "buf", "arg", "encodingOrOffset", "allocUnsafe", "from", "value", "fromString", "fromArrayView", "isInstance", "fromArrayBuffer", "valueOf", "b", "fromObject", "assertSize", "size", "alloc", "fill", "encoding", "checked", "string", "byteLength", "actual", "fromArrayLike", "array", "i", "arrayView", "copy", "byteOffset", "obj", "len", "numberIsNaN", "a", "x", "y", "list", "buffer", "pos", "mustMatch", "loweredCase", "utf8ToBytes", "base64ToBytes", "slowToString", "start", "end", "hexSlice", "utf8Slice", "asciiSlice", "latin1Slice", "base64Slice", "utf16leSlice", "swap", "n", "m", "str", "max", "target", "thisStart", "thisEnd", "thisCopy", "targetCopy", "bidirectionalIndexOf", "val", "dir", "arrayIndexOf", "indexSize", "arrLength", "valLength", "read", "foundIndex", "found", "j", "hexWrite", "offset", "remaining", "strLen", "parsed", "utf8Write", "blitBuffer", "asciiWrite", "asciiToBytes", "base64Write", "ucs2Write", "utf16leToBytes", "res", "firstByte", "codePoint", "bytesPerSequence", "secondByte", "thirdByte", "fourthByte", "tempCodePoint", "decodeCodePointsArray", "MAX_ARGUMENTS_LENGTH", "codePoints", "ret", "out", "hexSliceLookupTable", "bytes", "newBuf", "checkOffset", "ext", "noAssert", "mul", "defineBigIntMethod", "validateNumber", "first", "last", "boundsError", "lo", "hi", "checkInt", "min", "maxBytes", "wrtBigUInt64LE", "checkIntBI", "wrtBigUInt64BE", "limit", "sub", "checkIEEE754", "writeFloat", "littleEndian", "writeDouble", "targetStart", "code", "errors", "E", "sym", "getMessage", "Base", "name", "range", "input", "msg", "received", "addNumericalSeparator", "checkBounds", "type", "INVALID_BASE64_RE", "base64clean", "units", "leadSurrogate", "byteArray", "c", "src", "dst", "alphabet", "table", "i16", "fn", "BufferBigIntNotDefined", "require_buffer_polyfill", "__commonJSMin", "polyfilledBuffer", "Buffer", "require_ttlcache", "__commonJSMin", "exports", "module", "import_buffer_polyfill", "perf", "now", "isPosInt", "n", "isPosIntOrInf", "TTLCache", "_TTLCache", "max", "ttl", "updateAgeOnGet", "checkAgeOnGet", "noUpdateTTL", "dispose", "noDisposeOnSet", "expiration", "t", "exp", "entries", "key", "val", "current", "k", "oldValue", "_", "__", "value", "keys", "s", "require_level_supports", "__commonJSMin", "exports", "import_buffer_polyfill", "manifests", "manifest", "acc", "m", "require_module_error", "__commonJSMin", "exports", "module", "import_buffer_polyfill", "message", "options", "require_text_endec", "__commonJSMin", "exports", "module", "import_buffer_polyfill", "lazy", "require_encoding", "__commonJSMin", "exports", "import_buffer_polyfill", "ModuleError", "formats", "Encoding", "options", "require_formats", "__commonJSMin", "exports", "import_buffer_polyfill", "Buffer", "Encoding", "textEndec", "BufferFormat", "options", "ViewFormat", "data", "view", "UTF8Format", "textEncoder", "textDecoder", "require_encodings", "__commonJSMin", "exports", "import_buffer_polyfill", "Buffer", "textEncoder", "textDecoder", "BufferFormat", "ViewFormat", "UTF8Format", "identity", "v", "data", "buffer", "require_level_transcoder", "__commonJSMin", "exports", "import_buffer_polyfill", "ModuleError", "encodings", "Encoding", "BufferFormat", "ViewFormat", "UTF8Format", "kFormats", "kEncodings", "validFormats", "Transcoder", "formats", "f", "k", "err", "encoding", "resolved", "lookup", "from", "name", "format", "options", "maybeType", "anonymousCount", "detectFormat", "aliases", "require_events", "__commonJSMin", "exports", "module", "import_buffer_polyfill", "R", "ReflectApply", "target", "receiver", "args", "ReflectOwnKeys", "ProcessEmitWarning", "warning", "NumberIsNaN", "value", "EventEmitter", "once", "defaultMaxListeners", "checkListener", "listener", "arg", "n", "_getMaxListeners", "that", "type", "i", "doError", "events", "er", "err", "handler", "len", "listeners", "arrayClone", "_addListener", "prepend", "m", "existing", "w", "onceWrapper", "_onceWrap", "state", "wrapped", "list", "position", "originalListener", "spliceOne", "keys", "key", "_listeners", "unwrap", "evlistener", "unwrapListeners", "emitter", "listenerCount", "arr", "copy", "index", "ret", "name", "resolve", "reject", "errorListener", "resolver", "eventTargetAgnosticAddListener", "addErrorHandlerIfEventEmitter", "flags", "wrapListener", "require_next_tick_browser", "__commonJSMin", "exports", "module", "import_buffer_polyfill", "fn", "require_catering", "__commonJSMin", "exports", "import_buffer_polyfill", "nextTick", "callback", "symbol", "promise", "resolve", "reject", "err", "res", "require_common", "__commonJSMin", "exports", "import_buffer_polyfill", "options", "callback", "def", "require_abstract_iterator", "__commonJSMin", "exports", "import_buffer_polyfill", "fromCallback", "ModuleError", "getOptions", "getCallback", "kPromise", "kCallback", "kWorking", "kHandleOne", "kHandleMany", "kAutoClose", "kFinishWork", "kReturnMany", "kClosing", "kHandleClose", "kClosed", "kCloseCallbacks", "kKeyEncoding", "kValueEncoding", "kAbortOnClose", "kLegacy", "kKeys", "kValues", "kLimit", "kCount", "emptyOptions", "noop", "warnedEnd", "CommonIterator", "db", "options", "legacy", "hint", "callback", "promise", "resolve", "reject", "err", "key", "value", "size", "acc", "onnext", "count", "nextv", "onnextv", "items", "cb", "target", "keyEncoding", "keyFormat", "mapped", "callbacks", "item", "AbstractIterator", "IteratorDecodeError", "entries", "entry", "AbstractKeyIterator", "keys", "AbstractValueIterator", "values", "subject", "cause", "k", "require_default_kv_iterator", "__commonJSMin", "exports", "import_buffer_polyfill", "AbstractKeyIterator", "AbstractValueIterator", "kIterator", "kCallback", "kHandleOne", "kHandleMany", "DefaultKeyIterator", "db", "options", "DefaultValueIterator", "Iterator", "keys", "mapEntry", "entry", "callback", "err", "key", "value", "size", "entries", "target", "require_deferred_iterator", "__commonJSMin", "exports", "import_buffer_polyfill", "AbstractIterator", "AbstractKeyIterator", "AbstractValueIterator", "ModuleError", "kNut", "kUndefer", "kFactory", "DeferredIterator", "db", "options", "DeferredKeyIterator", "DeferredValueIterator", "Iterator", "callback", "size", "target", "require_abstract_chained_batch", "__commonJSMin", "exports", "import_buffer_polyfill", "fromCallback", "ModuleError", "getCallback", "getOptions", "kPromise", "kStatus", "kOperations", "kFinishClose", "kCloseCallbacks", "AbstractChainedBatch", "db", "hint", "key", "value", "options", "err", "original", "keyEncoding", "valueEncoding", "keyFormat", "mappedKey", "mappedValue", "callback", "callbacks", "cb", "require_default_chained_batch", "__commonJSMin", "exports", "import_buffer_polyfill", "AbstractChainedBatch", "ModuleError", "kEncoded", "DefaultChainedBatch", "db", "key", "value", "options", "callback", "require_range_options", "__commonJSMin", "exports", "module", "import_buffer_polyfill", "ModuleError", "hasOwnProperty", "rangeOptions", "options", "keyEncoding", "result", "k", "require_queue_microtask", "__commonJSMin", "exports", "module", "import_buffer_polyfill", "promise", "cb", "err", "require_next_tick_browser", "__commonJSMin", "exports", "module", "import_buffer_polyfill", "queueMicrotask", "fn", "args", "require_abstract_sublevel_iterator", "__commonJSMin", "exports", "import_buffer_polyfill", "AbstractIterator", "AbstractKeyIterator", "AbstractValueIterator", "kUnfix", "kIterator", "kHandleOne", "kHandleMany", "kCallback", "AbstractSublevelIterator", "db", "options", "iterator", "unfix", "err", "key", "value", "callback", "entries", "entry", "AbstractSublevelKeyIterator", "keys", "AbstractSublevelValueIterator", "Iterator", "size", "target", "require_abstract_sublevel", "__commonJSMin", "exports", "module", "import_buffer_polyfill", "ModuleError", "Buffer", "AbstractSublevelIterator", "AbstractSublevelKeyIterator", "AbstractSublevelValueIterator", "kPrefix", "kUpperBound", "kPrefixRange", "kParent", "kUnfix", "textEncoder", "defaults", "AbstractLevel", "AbstractSublevel", "options", "db", "name", "separator", "manifest", "forward", "trim", "reserved", "parent", "x", "mergeManifests", "prefix", "upperBound", "MultiFormat", "Unfixer", "key", "keyFormat", "view", "result", "buffer", "range", "callback", "value", "keys", "operations", "iterator", "unfix", "supportsEncoding", "encoding", "prefixLength", "str", "char", "start", "end", "require_abstract_level", "__commonJSMin", "exports", "import_buffer_polyfill", "supports", "Transcoder", "EventEmitter", "fromCallback", "ModuleError", "AbstractIterator", "DefaultKeyIterator", "DefaultValueIterator", "DeferredIterator", "DeferredKeyIterator", "DeferredValueIterator", "DefaultChainedBatch", "getCallback", "getOptions", "rangeOptions", "kPromise", "kLanded", "kResources", "kCloseResources", "kOperations", "kUndefer", "kDeferOpen", "kOptions", "kStatus", "kDefaultOptions", "kTranscoder", "kKeyEncoding", "kValueEncoding", "noop", "AbstractLevel", "manifest", "options", "keyEncoding", "valueEncoding", "passive", "forward", "formats", "encoding", "callback", "maybeOpened", "err", "maybeClosed", "cancel", "pending", "sync", "next", "resource", "key", "maybeError", "keyFormat", "valueFormat", "value", "keys", "mappedKeys", "i", "values", "mappedKey", "mappedValue", "operations", "mapped", "ke", "ve", "op", "db", "valueErr", "name", "AbstractSublevel", "original", "fn", "k", "require_abstract_level", "__commonJSMin", "exports", "import_buffer_polyfill", "require_run_parallel_limit", "__commonJSMin", "exports", "module", "import_buffer_polyfill", "runParallelLimit", "queueMicrotask", "tasks", "limit", "cb", "results", "len", "pending", "keys", "isErrored", "isSync", "next", "done", "err", "end", "each", "i", "result", "key", "task", "require_key_range", "__commonJSMin", "exports", "module", "import_buffer_polyfill", "options", "lower", "upper", "lowerExclusive", "upperExclusive", "require_deserialize", "__commonJSMin", "exports", "module", "import_buffer_polyfill", "textEncoder", "data", "require_iterator", "__commonJSMin", "exports", "import_buffer_polyfill", "AbstractIterator", "createKeyRange", "deserialize", "kCache", "kFinished", "kOptions", "kCurrentOptions", "kPosition", "kLocation", "kFirst", "emptyOptions", "Iterator", "db", "location", "options", "size", "callback", "keyRange", "transaction", "store", "entries", "method", "ev", "cursor", "key", "value", "maybeCommit", "keys", "values", "complete", "length", "i", "err", "cache", "target", "require_clear", "__commonJSMin", "exports", "module", "import_buffer_polyfill", "db", "location", "keyRange", "options", "callback", "transaction", "store", "count", "method", "direction", "ev", "cursor", "require_browser_level", "__commonJSMin", "exports", "import_buffer_polyfill", "AbstractLevel", "ModuleError", "parallel", "fromCallback", "Iterator", "deserialize", "clear", "createKeyRange", "DEFAULT_PREFIX", "kIDB", "kNamePrefix", "kLocation", "kVersion", "kStore", "kOnComplete", "kPromise", "BrowserLevel", "location", "options", "_", "prefix", "version", "forward", "callback", "req", "ev", "db", "mode", "request", "transaction", "key", "store", "err", "value", "keys", "tasks", "next", "operations", "index", "error", "loop", "op", "keyRange", "require_browser", "__commonJSMin", "exports", "import_buffer_polyfill", "merge", "sets", "_len", "_key", "length", "slice", "xl", "x", "join", "subexp", "str", "typeOf", "o", "undefined", "Object", "prototype", "toString", "call", "split", "pop", "shift", "toLowerCase", "toUpperCase", "toArray", "obj", "Array", "setInterval", "assign", "target", "source", "key", "buildExps", "isIRI", "ALPHA$$", "CR$", "DIGIT$$", "DQUOTE$$", "HEXDIG$$", "SP$$", "PCT_ENCODED$", "SUB_DELIMS$$", "RESERVED$$", "GEN_DELIMS$$", "UCSCHAR$$", "SCHEME$", "USERINFO$", "UNRESERVED$$", "DEC_OCTET$", "DEC_OCTET_RELAXED$", "H16$", "LS32$", "IPV4ADDRESS$", "IPV6ADDRESS1$", "IPV6ADDRESS2$", "IPV6ADDRESS3$", "IPV6ADDRESS4$", "IPV6ADDRESS5$", "IPV6ADDRESS6$", "IPV6ADDRESS7$", "IPV6ADDRESS8$", "IPV6ADDRESS9$", "ZONEID$", "IPV6ADDRESS$", "IP_LITERAL$", "IPV6ADDRZ_RELAXED$", "IPVFUTURE$", "HOST$", "REG_NAME$", "PORT$", "AUTHORITY$", "PCHAR$", "SEGMENT$", "SEGMENT_NZ$", "SEGMENT_NZ_NC$", "PATH_ABEMPTY$", "PATH_ABSOLUTE$", "PATH$", "PATH_NOSCHEME$", "PATH_ROOTLESS$", "PATH_EMPTY$", "QUERY$", "IPRIVATE$$", "FRAGMENT$", "HIER_PART$", "URI$", "RELATIVE_PART$", "RELATIVE$", "URI_REFERENCE$", "ABSOLUTE_URI$", "GENERIC_REF$", "RELATIVE_REF$", "ABSOLUTE_REF$", "SAMEDOC_REF$", "AUTHORITY_REF$", "RegExp", "URI_PROTOCOL", "IRI_PROTOCOL", "maxInt", "base", "tMin", "tMax", "skew", "damp", "initialBias", "initialN", "delimiter", "regexPunycode", "regexNonASCII", "regexSeparators", "errors", "baseMinusTMin", "floor", "Math", "stringFromCharCode", "String", "fromCharCode", "error", "type", "RangeError", "map", "array", "fn", "result", "mapDomain", "string", "parts", "replace", "labels", "encoded", "ucs2decode", "output", "counter", "value", "charCodeAt", "extra", "push", "ucs2encode", "fromCodePoint", "toConsumableArray", "basicToDigit", "codePoint", "digitToBasic", "digit", "flag", "adapt", "delta", "numPoints", "firstTime", "k", "decode", "input", "inputLength", "i", "n", "bias", "basic", "lastIndexOf", "j", "index", "oldi", "w", "t", "baseMinusT", "out", "splice", "encode", "_step", "_iteratorNormalCompletion", "_iterator", "currentValue", "basicLength", "handledCPCount", "m", "_step2", "_iteratorNormalCompletion2", "_iterator2", "handledCPCountPlusOne", "_step3", "_iteratorNormalCompletion3", "_iterator3", "q", "qMinusT", "toUnicode", "test", "toASCII", "punycode", "SCHEMES", "pctEncChar", "chr", "c", "e", "pctDecChars", "newStr", "il", "parseInt", "substr", "c2", "c3", "_normalizeComponentEncoding", "components", "protocol", "decodeUnreserved", "decStr", "match", "UNRESERVED", "scheme", "PCT_ENCODED", "NOT_SCHEME", "userinfo", "NOT_USERINFO", "host", "NOT_HOST", "path", "NOT_PATH", "NOT_PATH_NOSCHEME", "query", "NOT_QUERY", "fragment", "NOT_FRAGMENT", "_stripLeadingZeros", "_normalizeIPv4", "matches", "IPV4ADDRESS", "address", "_matches", "_normalizeIPv6", "IPV6ADDRESS", "_matches2", "zone", "reverse", "last", "_address$toLowerCase$2", "first", "firstFields", "lastFields", "isLastFieldIPv4Address", "fieldCount", "lastFieldsStart", "fields", "allZeroFields", "reduce", "acc", "field", "lastLongest", "longestZeroFields", "sort", "a", "b", "newHost", "newFirst", "newLast", "URI_PARSE", "NO_MATCH_IS_UNDEFINED", "parse", "uriString", "options", "iri", "reference", "port", "isNaN", "indexOf", "schemeHandler", "unicodeSupport", "domainHost", "_recomposeAuthority", "uriTokens", "_", "$1", "$2", "RDS1", "RDS2", "RDS3", "RDS5", "removeDotSegments", "im", "s", "Error", "serialize", "authority", "charAt", "absolutePath", "resolveComponents", "relative", "skipNormalization", "tolerant", "resolve", "baseURI", "relativeURI", "schemelessOptions", "normalize", "uri", "equal", "uriA", "uriB", "escapeComponent", "ESCAPE", "unescapeComponent", "handler", "secure", "http", "isSecure", "wsComponents", "resourceName", "_wsComponents$resourc2", "ws", "O", "ATEXT$$", "QTEXT$$", "VCHAR$$", "SOME_DELIMS$$", "NOT_LOCAL_PART", "NOT_HFNAME", "NOT_HFVALUE", "mailtoComponents", "to", "unknownHeaders", "headers", "hfields", "hfield", "toAddrs", "subject", "body", "addr", "toAddr", "atIdx", "localPart", "domain", "name", "URN_PARSE", "urnComponents", "nid", "nss", "urnScheme", "uriComponents", "UUID", "uuidComponents", "uuid", "https", "wss", "mailto", "urn", "require_canonicalize", "__commonJSMin", "exports", "module", "import_buffer_polyfill", "serialize", "object", "t", "cv", "ci", "comma", "require_ms", "__commonJSMin", "exports", "module", "import_buffer_polyfill", "s", "m", "h", "d", "w", "y", "val", "options", "type", "parse", "fmtLong", "fmtShort", "str", "match", "n", "ms", "msAbs", "plural", "name", "isPlural", "src_exports", "__export", "BearerDid", "Did", "DidDht", "DidDhtDocument", "DidDhtRegisteredDidType", "DidDhtRegisteredKeyType", "DidDhtUtils", "DidDhtVerificationRelationship", "DidError", "DidErrorCode", "DidIon", "DidIonRegisteredKeyType", "DidIonUtils", "DidJwk", "DidKey", "DidKeyRegisteredKeyType", "DidKeyUtils", "DidKeyVerificationMethodType", "DidMethod", "DidResolverCacheLevel", "DidResolverCacheNoop", "DidVerificationRelationship", "DidWeb", "EMPTY_DID_RESOLUTION_RESULT", "UniversalResolver", "utils_exports", "import_buffer_polyfill", "import_buffer_polyfill", "DidVerificationRelationship", "import_buffer_polyfill", "EMPTY_DID_RESOLUTION_RESULT", "import_buffer_polyfill", "_Did", "method", "id", "path", "query", "fragment", "params", "didUri", "match", "did", "parsedParams", "paramPairs", "pair", "key", "value", "Did", "import_buffer_polyfill", "DidError", "_DidError", "code", "message", "DidErrorCode", "import_buffer_polyfill", "import_buffer_polyfill", "import_buffer_polyfill", "CryptoErrorCode", "import_buffer_polyfill", "import_buffer_polyfill", "import_ttlcache", "import_buffer_polyfill", "import_buffer_polyfill", "import_buffer_polyfill", "empty", "equals", "aa", "bb", "ii", "coerce", "o", "import_buffer_polyfill", "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", "text", "decoder", "or", "ComposedDecoder", "decoders", "input", "left", "right", "Codec", "from", "encode", "decode", "baseX", "alphabet", "base_x_default", "coerce", "string", "bitsPerChar", "codes", "i", "end", "out", "bits", "buffer", "written", "value", "data", "pad", "mask", "rfc4648", "base32", "rfc4648", "base32upper", "base32pad", "base32padupper", "base32hex", "base32hexupper", "base32hexpad", "base32hexpadupper", "base32z", "import_buffer_polyfill", "base58btc", "baseX", "base58flickr", "import_buffer_polyfill", "base64", "rfc4648", "base64pad", "base64url", "base64urlpad", "import_buffer_polyfill", "isArrayBufferSlice", "arrayBufferView", "isAsyncIterable", "obj", "universalTypeOf", "value", "match", "_", "type", "textEncoder", "textDecoder", "Convert", "_Convert", "data", "format", "isAsyncIterable", "base58btc", "base64url", "universalTypeOf", "isArrayBufferSlice", "base32z", "u8a", "string", "chunks", "_d", "_e", "__asyncValues", "_f", "_a", "_c", "chunk", "hexes", "v", "i", "hex", "text", "str", "dataType", "byteValue", "arrayBuffer", "import_buffer_polyfill", "Web5LogLevel", "Web5Logger", "logLevel", "message", "logger", "import_buffer_polyfill", "import_buffer_polyfill", "import_buffer_polyfill", "import_buffer_polyfill", "varint_exports", "__export", "decode", "encodeTo", "encodingLength", "import_buffer_polyfill", "import_buffer_polyfill", "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", "import_buffer_polyfill", "format", "link", "base", "bytes", "version", "toStringV0", "baseCache", "base58btc", "toStringV1", "base32", "cache", "baseCache", "cid", "CID", "_CID", "version", "code", "multihash", "bytes", "DAG_PB_CODE", "SHA_256_CODE", "digest", "create", "other", "self", "unknown", "equals", "base", "format", "input", "value", "encodeCID", "cidSymbol", "decode", "remainder", "specs", "prefixSize", "multihashBytes", "coerce", "digestBytes", "Digest", "initialBytes", "offset", "next", "i", "length", "codec", "multihashCode", "digestSize", "size", "multihashSize", "source", "prefix", "parseCIDtoBytes", "decoder", "base58btc", "base32", "toStringV0", "toStringV1", "codeOffset", "encodingLength", "hashOffset", "encodeTo", "import_buffer_polyfill", "import_buffer_polyfill", "import_buffer_polyfill", "import_buffer_polyfill", "import_buffer_polyfill", "import_buffer_polyfill", "Multicodec", "_Multicodec", "options", "code", "data", "name", "_a", "prefixLength", "varint_exports", "dataWithPrefix", "prefixedData", "_", "codec", "codeByteLength", "import_buffer_polyfill", "removeUndefinedProperties", "obj", "key", "import_level", "MemoryStore", "id", "key", "import_buffer_polyfill", "CryptoAlgorithm", "utils_exports", "__export", "bitGet", "bitLen", "bitMask", "bitSet", "bytesToHex", "bytesToNumberBE", "bytesToNumberLE", "concatBytes", "createHmacDrbg", "ensureBytes", "equalBytes", "hexToBytes", "hexToNumber", "isBytes", "numberToBytesBE", "numberToBytesLE", "numberToHexUnpadded", "numberToVarBytesBE", "utf8ToBytes", "validateObject", "import_buffer_polyfill", "_0n", "_1n", "_2n", "a", "hexes", "_", "i", "bytes", "hex", "num", "asciis", "asciiToBase16", "char", "hl", "al", "array", "ai", "hi", "n1", "n2", "n", "len", "title", "expectedLength", "res", "e", "arrays", "sum", "pad", "b", "diff", "str", "pos", "value", "u8n", "data", "u8fr", "arr", "hashLen", "qByteLen", "hmacFn", "v", "k", "reset", "h", "reseed", "seed", "gen", "out", "sl", "pred", "validatorFns", "val", "object", "validators", "optValidators", "checkField", "fieldName", "type", "isOptional", "checkVal", "import_buffer_polyfill", "import_buffer_polyfill", "import_buffer_polyfill", "import_buffer_polyfill", "number", "n", "isBytes", "a", "bytes", "b", "lengths", "hash", "number", "exists", "instance", "checkFinished", "output", "out", "min", "import_buffer_polyfill", "import_buffer_polyfill", "crypto", "isBytes", "a", "createView", "arr", "rotr", "word", "shift", "isLE", "utf8ToBytes", "str", "toBytes", "data", "isBytes", "concatBytes", "arrays", "sum", "i", "a", "res", "pad", "Hash", "toStr", "wrapConstructor", "hashCons", "hashC", "msg", "toBytes", "tmp", "randomBytes", "bytesLength", "crypto", "setBigUint64", "view", "byteOffset", "value", "isLE", "_32n", "_u32_max", "wh", "wl", "h", "l", "SHA2", "Hash", "blockLen", "outputLen", "padOffset", "createView", "data", "exists", "buffer", "toBytes", "len", "pos", "take", "dataView", "out", "output", "i", "oview", "outLen", "state", "res", "to", "length", "finished", "destroyed", "Chi", "a", "b", "c", "Maj", "SHA256_K", "IV", "SHA256_W", "SHA256", "SHA2", "A", "B", "C", "D", "E", "F", "G", "H", "view", "offset", "i", "W15", "W2", "s0", "rotr", "s1", "sigma1", "T1", "T2", "sha256", "wrapConstructor", "SHA256", "import_buffer_polyfill", "_0n", "_1n", "_2n", "_3n", "_4n", "_5n", "_8n", "_9n", "_16n", "mod", "a", "b", "result", "pow", "num", "power", "modulo", "res", "pow2", "x", "invert", "number", "y", "u", "v", "q", "r", "m", "n", "tonelliShanks", "P", "legendreC", "Q", "S", "Z", "p1div4", "Fp", "root", "Q1div2", "g", "t2", "ge", "FpSqrt", "c1", "n2", "nv", "i", "isNegativeLE", "FIELD_FIELDS", "validateField", "field", "initial", "opts", "map", "val", "validateObject", "FpPow", "f", "p", "d", "FpInvertBatch", "nums", "tmp", "lastMultiplied", "acc", "inverted", "nLength", "n", "nBitLength", "_nBitLength", "nByteLength", "Field", "ORDER", "bitLen", "isLE", "redef", "_0n", "BITS", "BYTES", "sqrtP", "FpSqrt", "f", "bitMask", "_1n", "num", "mod", "lhs", "rhs", "power", "FpPow", "invert", "lst", "FpInvertBatch", "a", "b", "c", "numberToBytesLE", "numberToBytesBE", "bytes", "bytesToNumberLE", "bytesToNumberBE", "FpSqrtEven", "Fp", "elm", "root", "getFieldBytesLength", "fieldOrder", "bitLength", "getMinHashLength", "length", "mapHashToField", "key", "isLE", "len", "fieldLen", "minLen", "num", "bytesToNumberBE", "bytesToNumberLE", "reduced", "mod", "_1n", "numberToBytesLE", "numberToBytesBE", "import_buffer_polyfill", "import_buffer_polyfill", "_0n", "_1n", "wNAF", "c", "bits", "constTimeNegate", "condition", "item", "neg", "opts", "W", "windows", "windowSize", "elm", "n", "p", "d", "points", "base", "window", "i", "precomputes", "f", "mask", "maxNumber", "shiftBy", "offset", "wbits", "offset1", "offset2", "cond1", "cond2", "P", "precomputesMap", "transform", "comp", "validateBasic", "curve", "validateField", "validateObject", "nLength", "validatePointOpts", "curve", "opts", "validateBasic", "validateObject", "endo", "Fp", "a", "b2n", "h2b", "utils_exports", "DER", "m", "data", "E", "len", "res", "hex", "isBytes", "l", "r", "sBytes", "rBytesLeft", "sig", "slice", "s", "h", "num", "shl", "rhl", "sl", "rl", "_0n", "_1n", "_2n", "_3n", "_4n", "weierstrassPoints", "CURVE", "toBytes", "_c", "point", "_isCompressed", "concatBytes", "fromBytes", "bytes", "tail", "x", "y", "weierstrassEquation", "b", "x2", "x3", "isWithinCurveOrder", "assertGE", "normPrivateKeyToScalar", "key", "lengths", "nByteLength", "wrapPrivateKey", "n", "bytesToHex", "bytesToNumberBE", "ensureBytes", "mod", "pointPrecomputes", "assertPrjPoint", "other", "Point", "px", "py", "pz", "p", "is0", "i", "points", "toInv", "P", "privateKey", "windowSize", "left", "right", "X1", "Y1", "Z1", "X2", "Y2", "Z2", "U1", "U2", "b3", "X3", "Y3", "Z3", "t0", "t1", "t2", "t3", "t4", "t5", "wnaf", "comp", "I", "k1neg", "k1", "k2neg", "k2", "k1p", "k2p", "d", "scalar", "fake", "f1p", "f2p", "f", "Q", "G", "mul", "sum", "iz", "z", "ax", "ay", "zz", "cofactor", "isTorsionFree", "clearCofactor", "isCompressed", "_bits", "wNAF", "validateOpts", "weierstrass", "curveDef", "CURVE_ORDER", "compressedLen", "uncompressedLen", "isValidFieldElement", "modN", "invN", "invert", "cat", "head", "y2", "isYOdd", "numToNByteStr", "numberToBytesBE", "isBiggerThanHalfOrder", "number", "HALF", "normalizeS", "slcNum", "from", "to", "Signature", "recovery", "msgHash", "rec", "bits2int_modN", "radj", "prefix", "R", "ir", "u1", "u2", "hexToBytes", "utils", "length", "getMinHashLength", "mapHashToField", "getPublicKey", "isProbPub", "item", "arr", "str", "getSharedSecret", "privateA", "publicB", "bits2int", "delta", "ORDER_MASK", "bitMask", "int2octets", "prepSig", "defaultSigOpts", "k", "hash", "randomBytes", "lowS", "prehash", "ent", "h1int", "seedArgs", "e", "seed", "k2sig", "kBytes", "ik", "q", "normS", "defaultVerOpts", "sign", "privKey", "C", "createHmacDrbg", "verify", "signature", "publicKey", "sg", "_sig", "derError", "error", "is", "import_buffer_polyfill", "import_buffer_polyfill", "HMAC", "Hash", "hash", "_key", "key", "toBytes", "blockLen", "pad", "i", "buf", "exists", "out", "bytes", "to", "oHash", "iHash", "finished", "destroyed", "outputLen", "hmac", "message", "getHash", "hash", "key", "msgs", "hmac", "concatBytes", "randomBytes", "createCurve", "curveDef", "defHash", "create", "weierstrass", "secp256k1P", "secp256k1N", "_1n", "_2n", "divNearest", "a", "b", "sqrtMod", "y", "P", "_3n", "_6n", "_11n", "_22n", "_23n", "_44n", "_88n", "b2", "b3", "b6", "pow2", "b9", "b11", "b22", "b44", "b88", "b176", "b220", "b223", "t1", "t2", "root", "Fp", "Field", "secp256k1", "createCurve", "k", "n", "a1", "b1", "a2", "POW_2_128", "c1", "c2", "k1", "mod", "k2", "k1neg", "k2neg", "sha256", "_0n", "Point", "secp256k1", "import_buffer_polyfill", "import_buffer_polyfill", "import_buffer_polyfill", "isBytes", "a", "bytes", "b", "lengths", "exists", "instance", "checkFinished", "output", "out", "bytes", "min", "import_buffer_polyfill", "import_buffer_polyfill", "crypto", "createView", "arr", "rotr", "word", "shift", "isLE", "utf8ToBytes", "str", "toBytes", "data", "bytes", "Hash", "toStr", "wrapConstructor", "hashCons", "hashC", "msg", "toBytes", "tmp", "randomBytes", "bytesLength", "crypto", "setBigUint64", "view", "byteOffset", "value", "isLE", "_32n", "_u32_max", "wh", "wl", "h", "l", "Chi", "a", "b", "c", "Maj", "HashMD", "Hash", "blockLen", "outputLen", "padOffset", "createView", "data", "exists", "buffer", "toBytes", "len", "pos", "take", "dataView", "out", "output", "i", "oview", "outLen", "state", "res", "to", "length", "finished", "destroyed", "SHA256_K", "SHA256_IV", "SHA256_W", "SHA256", "HashMD", "A", "B", "C", "D", "E", "F", "G", "H", "view", "offset", "i", "W15", "W2", "s0", "rotr", "s1", "sigma1", "T1", "Chi", "T2", "Maj", "sha256", "wrapConstructor", "SHA256", "import_buffer_polyfill", "canonicalize", "obj", "sortObjKeys", "sortedKeys", "sortedObj", "key", "Sha256", "_a", "data", "sha256", "KEY_URI_PREFIX_JWK", "computeJwkThumbprint", "_a", "jwk", "keyType", "normalizedJwk", "removeUndefinedProperties", "serializedJwk", "canonicalize", "utf8Bytes", "Convert", "digest", "Sha256", "isEcPrivateJwk", "obj", "isEcPublicJwk", "isOkpPrivateJwk", "obj", "isOkpPublicJwk", "isPrivateJwk", "Secp256k1", "_Secp256k1", "_a", "signature", "signatureObject", "secp256k1", "privateKeyBytes", "point", "privateKey", "Convert", "computeJwkThumbprint", "publicKeyBytes", "publicKey", "key", "derSignature", "isEcPrivateJwk", "d", "__rest", "_b", "isEcPublicJwk", "prefix", "x", "y", "privateKeyA", "publicKeyB", "privateKeyABytes", "publicKeyBBytes", "data", "digest", "sha256", "keyBytes", "numberToBytesBE", "import_buffer_polyfill", "Fp", "Field", "CURVE_A", "CURVE_B", "p256", "createCurve", "sha256", "secp256r1", "Secp256r1", "_Secp256r1", "_a", "signature", "signatureObject", "secp256r1", "privateKeyBytes", "point", "privateKey", "Convert", "computeJwkThumbprint", "publicKeyBytes", "publicKey", "key", "derSignature", "isEcPrivateJwk", "d", "__rest", "_b", "isEcPublicJwk", "prefix", "x", "y", "privateKeyA", "publicKeyB", "privateKeyABytes", "publicKeyBBytes", "data", "digest", "sha256", "keyBytes", "numberToBytesBE", "EcdsaAlgorithm", "CryptoAlgorithm", "_a", "key", "isEcPrivateJwk", "publicKey", "Secp256k1", "Secp256r1", "algorithm", "privateKey", "data", "signature", "isEcPublicJwk", "import_buffer_polyfill", "import_buffer_polyfill", "import_buffer_polyfill", "U32_MASK64", "_32n", "fromBig", "n", "le", "split", "lst", "Ah", "Al", "h", "l", "toBig", "shrSH", "_l", "s", "shrSL", "rotrSH", "rotrSL", "rotrBH", "rotrBL", "rotr32H", "_h", "rotr32L", "rotlSH", "rotlSL", "rotlBH", "rotlBL", "add", "Bh", "Bl", "add3L", "Cl", "add3H", "low", "Ch", "add4L", "Dl", "add4H", "Dh", "add5L", "El", "add5H", "Eh", "u64", "fromBig", "split", "toBig", "shrSH", "shrSL", "rotrSH", "rotrSL", "rotrBH", "rotrBL", "rotr32H", "rotr32L", "rotlSH", "rotlSL", "rotlBH", "rotlBL", "add", "add3L", "add3H", "add4L", "add4H", "add5H", "add5L", "u64_default", "SHA512_Kh", "SHA512_Kl", "u64_default", "n", "SHA512_W_H", "SHA512_W_L", "SHA512", "SHA2", "Ah", "Al", "Bh", "Bl", "Ch", "Cl", "Dh", "Dl", "Eh", "El", "Fh", "Fl", "Gh", "Gl", "Hh", "Hl", "view", "offset", "i", "W15h", "W15l", "s0h", "s0l", "W2h", "W2l", "s1h", "s1l", "SUMl", "SUMh", "sigma1h", "sigma1l", "CHIh", "CHIl", "T1ll", "T1h", "T1l", "sigma0h", "sigma0l", "MAJh", "MAJl", "All", "sha512", "wrapConstructor", "SHA512", "import_buffer_polyfill", "_0n", "_1n", "_2n", "_8n", "VERIFY_DEFAULT", "validateOpts", "curve", "opts", "validateBasic", "validateObject", "twistedEdwards", "curveDef", "CURVE", "Fp", "CURVE_ORDER", "prehash", "cHash", "randomBytes", "nByteLength", "cofactor", "MASK", "modP", "uvRatio", "u", "v", "adjustScalarBytes", "bytes", "domain", "data", "ctx", "phflag", "inBig", "n", "inRange", "max", "in0MaskRange", "assertInRange", "assertGE0", "pointPrecomputes", "isPoint", "other", "Point", "ex", "ey", "ez", "et", "p", "x", "y", "points", "toInv", "i", "windowSize", "a", "d", "X", "Y", "Z", "T", "X2", "Y2", "Z2", "Z4", "aX2", "left", "right", "XY", "ZT", "X1", "Y1", "Z1", "X1Z2", "X2Z1", "Y1Z2", "Y2Z1", "A", "B", "C", "D", "x1y1", "E", "G", "F", "H", "X3", "Y3", "T3", "Z3", "T1", "T2", "wnaf", "scalar", "f", "I", "iz", "z", "is0", "ax", "ay", "zz", "hex", "zip215", "len", "ensureBytes", "normed", "lastByte", "bytesToNumberLE", "y2", "isValid", "isXOdd", "isLastByteOdd", "privKey", "getExtendedPublicKey", "numberToBytesLE", "bytesToHex", "wNAF", "modN", "mod", "modN_LE", "hash", "key", "hashed", "head", "prefix", "point", "pointBytes", "getPublicKey", "hashDomainToScalar", "context", "msgs", "msg", "concatBytes", "sign", "options", "r", "R", "k", "s", "res", "verifyOpts", "verify", "sig", "publicKey", "SB", "import_buffer_polyfill", "_0n", "_1n", "validateOpts", "curve", "validateObject", "montgomery", "curveDef", "CURVE", "P", "modP", "n", "mod", "montgomeryBits", "montgomeryBytes", "fieldLen", "adjustScalarBytes", "bytes", "powPminus2", "x", "pow", "cswap", "swap", "x_2", "x_3", "dummy", "assertFieldElement", "a24", "montgomeryLadder", "pointU", "scalar", "u", "x_1", "z_2", "z_3", "sw", "t", "k_t", "A", "AA", "B", "BB", "E", "C", "D", "DA", "CB", "dacb", "da_cb", "z2", "encodeUCoordinate", "numberToBytesLE", "decodeUCoordinate", "uEnc", "ensureBytes", "bytesToNumberLE", "decodeScalar", "len", "scalarMult", "_scalar", "pu", "GuBytes", "scalarMultBase", "privateKey", "publicKey", "ED25519_P", "ED25519_SQRT_M1", "_0n", "_1n", "_2n", "_5n", "_10n", "_20n", "_40n", "_80n", "ed25519_pow_2_252_3", "x", "P", "b2", "b4", "pow2", "b5", "b10", "b20", "b40", "b80", "b160", "b240", "b250", "adjustScalarBytes", "bytes", "uvRatio", "u", "v", "v3", "mod", "v7", "pow", "vx2", "root1", "root2", "useRoot1", "useRoot2", "noRoot", "isNegativeLE", "Fp", "Field", "ED25519_P", "ed25519Defaults", "sha512", "randomBytes", "adjustScalarBytes", "uvRatio", "ed25519", "twistedEdwards", "ed25519_domain", "data", "ctx", "phflag", "concatBytes", "utf8ToBytes", "ed25519ctx", "ed25519ph", "x25519", "montgomery", "x", "P", "pow_p_5_8", "b2", "ed25519_pow_2_252_3", "mod", "pow2", "edwardsToMontgomeryPub", "edwardsPub", "y", "_1n", "edwardsToMontgomeryPriv", "edwardsPriv", "hashed", "ed25519Defaults", "ELL2_C1", "Fp", "ELL2_C2", "_2n", "ELL2_C3", "ELL2_C4", "ELL2_J", "ELL2_C1_EDWARDS", "FpSqrtEven", "Fp", "SQRT_AD_MINUS_ONE", "INVSQRT_A_MINUS_D", "ONE_MINUS_D_SQ", "D_MINUS_ONE_SQ", "MAX_255B", "Ed25519", "_Ed25519", "_a", "privateKeyBytes", "publicKeyBytes", "ed25519", "privateKey", "Convert", "computeJwkThumbprint", "publicKey", "key", "ed25519PrivateKeyBytes", "x25519PrivateKeyBytes", "edwardsToMontgomeryPriv", "x25519PublicKeyBytes", "x25519", "x25519PrivateKey", "ed25519PublicKeyBytes", "edwardsToMontgomeryPub", "x25519PublicKey", "isOkpPrivateJwk", "d", "__rest", "_b", "isOkpPublicJwk", "data", "signature", "EdDsaAlgorithm", "CryptoAlgorithm", "_a", "key", "isOkpPrivateJwk", "publicKey", "Ed25519", "algorithm", "privateKey", "data", "signature", "isOkpPublicJwk", "Sha2Algorithm", "CryptoAlgorithm", "_a", "algorithm", "data", "Sha256", "supportedAlgorithms", "EdDsaAlgorithm", "EcdsaAlgorithm", "Sha2Algorithm", "LocalKeyManager", "params", "_a", "MemoryStore", "algorithm", "data", "keyUri", "key", "KEY_URI_PREFIX_JWK", "jwkThumbprint", "computeJwkThumbprint", "privateKey", "isPrivateJwk", "_b", "signature", "AlgorithmImplementation", "algProperty", "crvProperty", "algName", "algorithmInfo", "import_buffer_polyfill", "CryptoUtils", "_CryptoUtils", "publicKey", "curveToJoseAlgorithm", "bytesLength", "randomBytes", "crypto", "length", "max", "pin", "rejectionRange", "randomBuffer", "import_buffer_polyfill", "import_buffer_polyfill", "import_buffer_polyfill", "X25519", "_X25519", "_a", "privateKeyBytes", "publicKeyBytes", "x25519", "privateKey", "Convert", "computeJwkThumbprint", "publicKey", "key", "isOkpPrivateJwk", "d", "__rest", "_b", "isOkpPublicJwk", "privateKeyA", "publicKeyB", "privateKeyABytes", "publicKeyBBytes", "utils_exports", "__export", "extractDidFragment", "getServices", "getVerificationMethodByKey", "getVerificationMethodTypes", "getVerificationMethods", "getVerificationRelationshipsById", "isDidService", "isDidVerificationMethod", "isDwnDidService", "keyBytesToMultibaseId", "multibaseIdToKeyBytes", "import_buffer_polyfill", "extractDidFragment", "input", "getServices", "didDocument", "id", "type", "service", "getVerificationMethodByKey", "publicKeyJwk", "publicKeyMultibase", "verificationMethods", "getVerificationMethods", "method", "computeJwkThumbprint", "isDidVerificationMethod", "DidVerificationRelationship", "relationship", "getVerificationMethodTypes", "types", "getVerificationRelationshipsById", "methodId", "relationships", "relationshipMethods", "methodIdFragment", "isByReferenceMatch", "isEmbeddedMethodMatch", "isDidService", "obj", "isDwnDidService", "isStringOrStringArray", "prop", "item", "keyBytesToMultibaseId", "keyBytes", "multicodecCode", "multicodecName", "prefixedKey", "Multicodec", "prefixedKeyB58", "Convert", "multibaseIdToKeyBytes", "multibaseKeyId", "code", "data", "name", "DidError", "BearerDid", "_BearerDid", "uri", "document", "metadata", "keyManager", "portableDid", "privateKeys", "vm", "keyUri", "privateKey", "params", "verificationMethod", "extractDidFragment", "DidError", "publicKey", "CryptoUtils", "data", "signature", "LocalKeyManager", "verificationMethods", "getVerificationMethods", "key", "import_buffer_polyfill", "import_buffer_polyfill", "import_buffer_polyfill", "import_buffer_polyfill", "import_buffer_polyfill", "alphabet", "encodeLookup", "decodeLookup", "i", "arr2hex", "data", "length", "string", "concat", "chunks", "size", "length", "i", "b", "offset", "chars", "lookup", "i", "decoder", "arr2text", "data", "enc", "encoder", "text2arr", "str", "scope", "crypto", "subtle", "import_buffer_polyfill", "digitCount", "value", "sign", "getType", "encode", "data", "buffer", "offset", "buffers", "result", "concat", "getType", "buffE", "buffD", "buffL", "text2arr", "maxLo", "hi", "lo", "val", "j", "k", "keys", "kl", "key", "i", "c", "item", "encode_default", "import_buffer_polyfill", "INTEGER_START", "STRING_DELIM", "DICTIONARY_START", "LIST_START", "END_OF_TYPE", "getIntFromBuffer", "buffer", "start", "end", "sum", "sign", "i", "num", "decode", "data", "encoding", "text2arr", "chr", "c", "d", "dict", "key", "arr2text", "arr2hex", "lst", "number", "sep", "length", "decode_default", "import_buffer_polyfill", "listLength", "list", "length", "value", "encodingLength", "mapLength", "map", "key", "keyLength", "text2arr", "digitCount", "objectLength", "keys", "i", "stringLength", "arrayBufferLength", "type", "getType", "encoding_length_default", "encodingLength", "encoding_length_default", "bencode_default", "encode_default", "decode_default", "import_buffer_polyfill", "import_buffer_polyfill", "v4Regex", "v6Regex", "v4", "ip", "v4Regex", "buff", "offset", "max", "n", "i", "c", "v6", "v6Regex", "end", "fill", "hexN", "decN", "prevColon", "useDec", "result", "sizeOf", "ip", "v4", "v6", "familyOf", "string", "encode", "buff", "offset", "size", "decode", "length", "import_buffer_polyfill", "toString", "type", "toType", "name", "import_buffer_polyfill", "toString", "rcode", "import_buffer_polyfill", "toString", "opcode", "import_buffer_polyfill", "toString", "klass", "toClass", "name", "import_buffer_polyfill", "toString", "type", "toCode", "name", "m", "import_buffer_polyfill", "import_buffer_polyfill", "encodingLength", "str", "len", "strLen", "i", "code", "next", "encode", "buf", "offset", "off", "nextCode", "decode", "start", "end", "result", "num", "numA", "isU8Arr", "input", "bytelength", "encodingLength", "from", "encode", "write", "arr", "str", "start", "hexNum", "numHex", "b0", "b0L", "b0U", "b1", "b1L", "b1U", "num", "hex", "toHex", "buf", "end", "result", "offset", "hexLength", "string", "writeHex", "P_24", "P_16", "P_8", "readUInt32BE", "readUInt16BE", "writeUInt32BE", "value", "writeUInt16BE", "copy", "source", "target", "targetStart", "sourceStart", "sourceEnd", "_copyActual", "nb", "sourceLen", "QUERY_FLAG", "RESPONSE_FLAG", "FLUSH_MASK", "NOT_FLUSH_MASK", "QU_MASK", "NOT_QU_MASK", "codec", "bytes", "encode", "decode", "encodingLength", "name", "str", "buf", "offset", "oldOffset", "n", "list", "i", "len", "write", "totalLength", "consumedBytes", "jumped", "jumpOffset", "readUInt16BE", "bytelength", "string", "s", "header", "h", "flags", "type", "writeUInt16BE", "toString", "runknown", "data", "dLen", "copy", "rns", "dd", "rsoa", "writeUInt32BE", "readUInt32BE", "rtxt", "from", "isU8Arr", "d", "remaining", "length", "rnull", "rhinfo", "rptr", "rsrv", "rcaa", "rmx", "ra", "host", "v4", "raaaa", "v6", "alloc", "size", "roption", "option", "code", "toCode", "spl", "fam", "familyOf", "ipBuf", "ipLen", "tagsLen", "tag", "padded", "ropt", "options", "rdlen", "encodingLengthList", "encodeList", "rdnskey", "key", "keydata", "rrrsig", "sig", "signature", "toType", "rrp", "typebitmap", "typelist", "typesByWindow", "typeid", "windowBuf", "window", "windowLength", "b", "j", "extents", "rnsec", "record", "rnsec3", "salt", "nextDomain", "saltLength", "hashLength", "rds", "digest", "digestdata", "rsshfp", "fingerprintLength", "hexLength", "expectedLength", "getFingerprintLengthForHashType", "writeHex", "toHex", "hashType", "renc", "answer", "a", "klass", "toClass", "enc", "question", "q", "AUTHORITATIVE_ANSWER", "packet", "result", "buf", "offset", "allocing", "encodingLength", "oldOffset", "header", "encodeList", "question", "answer", "encode", "decodeList", "encodingLengthList", "sanitizeSingle", "input", "type", "sanitized", "query", "res", "response", "decode", "streamEncode", "combine", "writeUInt16BE", "copy", "streamDecode", "sbuf", "len", "readUInt16BE", "list", "enc", "i", "import_buffer_polyfill", "DidMethod", "_params", "_didUri", "_options", "DEFAULT_GATEWAY_URI", "DID_DHT_SPECIFICATION_VERSION", "DNS_RECORD_TTL", "PROPERTY_SEPARATOR", "VALUE_SEPARATOR", "DidDhtRegisteredDidType", "DidDhtRegisteredKeyType", "DidDhtVerificationRelationship", "AlgorithmToKeyTypeMap", "KeyTypeToDefaultAlgorithmMap", "_DidDht", "DidMethod", "keyManager", "LocalKeyManager", "options", "vm", "methodIds", "s", "identityKeyUri", "identityKey", "didUri", "DidDhtUtils", "document", "verificationMethodsToAdd", "verificationMethod", "keyUri", "publicKey", "methodId", "computeJwkThumbprint", "extractDidFragment", "purpose", "service", "did", "BearerDid", "registrationResult", "portableDid", "Did", "DidError", "didDocument", "parsedDid", "gatewayUri", "DidDhtDocument", "didDocumentMetadata", "EMPTY_DID_RESOLUTION_RESULT", "error", "DidDht", "_DidDhtDocument", "publicKeyBytes", "bep44Message", "dnsPacket", "resolutionResult", "putResult", "identifier", "Convert", "url", "response", "messageBytes", "body", "idLookup", "answer", "dnsRecordId", "data", "id", "t", "k", "c", "parsedAlg", "namedCurve", "vmId", "se", "customProperties", "serviceEndpoint", "serviceProperties", "v", "types", "typeInteger", "recordIdsToMethodIds", "auth", "asm", "del", "inv", "agm", "didMetadata", "authoritativeGatewayUris", "previousDidProof", "txtRecords", "nsRecords", "serviceIds", "verificationMethodIds", "signature", "previousDid", "controller", "index", "keyType", "publicKeyBase64Url", "txtData", "txtDataString", "key", "value", "rootRecord", "DidVerificationRelationship", "relationship", "dnsRecordIds", "recordName", "typeIntegers", "type", "AUTHORITATIVE_ANSWER", "_DidDhtUtils", "signer", "sequenceNumber", "encodedDnsPacket", "encode", "bencodedData", "bencode_default", "identityKeyBytes", "Ed25519", "curve", "converter", "Secp256r1", "Secp256k1", "X25519", "decode", "acc", "pair", "item", "newDid", "chunks", "i", "import_buffer_polyfill", "import_buffer_polyfill", "import_buffer_polyfill", "import_buffer_polyfill", "ErrorCode_default", "import_buffer_polyfill", "IonError", "code", "message", "import_buffer_polyfill", "import_buffer_polyfill", "import_buffer_polyfill", "import_buffer_polyfill", "empty", "coerce", "o", "import_buffer_polyfill", "Encoder", "name", "prefix", "baseEncode", "bytes", "Decoder", "baseDecode", "text", "decoder", "or", "ComposedDecoder", "decoders", "input", "left", "right", "Codec", "from", "encode", "decode", "decode", "string", "alphabet", "bitsPerChar", "name", "codes", "i", "end", "out", "bits", "buffer", "written", "value", "encode", "data", "pad", "mask", "rfc4648", "prefix", "from", "input", "base64", "rfc4648", "base64pad", "base64url", "base64urlpad", "Encoder", "_Encoder", "content", "base64url", "encodedContent", "inputContextForErrorLogging", "IonError", "ErrorCode_default", "rawBytes", "input", "URI", "import_buffer_polyfill", "import_buffer_polyfill", "OperationKeyType", "OperationKeyType_default", "InputValidator", "operationKeyJwk", "operationKeyType", "allowedProperties", "OperationKeyType_default", "property", "IonError", "ErrorCode_default", "id", "Encoder", "purposes", "processedPurposes", "purpose", "import_buffer_polyfill", "IonSdkConfig", "import_buffer_polyfill", "canonicalize", "JsonCanonicalizer", "_JsonCanonicalizer", "content", "contentWithoutUndefinedProperties", "canonicalizedString", "Encoder", "key", "import_buffer_polyfill", "import_buffer_polyfill", "import_buffer_polyfill", "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", "Digest", "code", "size", "digest", "bytes", "import_buffer_polyfill", "import_buffer_polyfill", "from", "name", "code", "encode", "Hasher", "input", "result", "create", "digest", "sha", "name", "data", "sha256", "from", "sha512", "Multihash", "_Multihash", "content", "hashAlgorithmInMultihashCode", "multihash", "sha256", "IonError", "ErrorCode_default", "hash", "canonicalizedStringBytes", "JsonCanonicalizer", "contentBytes", "intermediateHashBytes", "multihashBytes", "Encoder", "encodedMultihash", "inputContextForErrorLogging", "decode", "IonSdkConfig_default", "import_buffer_polyfill", "OperationType", "OperationType_default", "import_buffer_polyfill", "PatchAction", "PatchAction_default", "IonRequest", "_IonRequest", "input", "recoveryKey", "updateKey", "didDocumentKeys", "services", "InputValidator", "OperationKeyType_default", "hashAlgorithmInMultihashCode", "IonSdkConfig_default", "patches", "PatchAction_default", "delta", "Multihash", "suffixData", "OperationType_default", "revealValue", "dataToBeSigned", "compactJws", "nextUpdateCommitmentHash", "deltaHash", "id", "servicesToAdd", "patch", "idsOfServicesToRemove", "publicKeysToAdd", "idsOfPublicKeysToRemove", "didSuffix", "publicKeys", "publicKeyIdSet", "publicKey", "IonError", "ErrorCode_default", "serviceIdSet", "service", "maxTypeLength", "errorMessage", "deltaBytes", "JsonCanonicalizer", "IonDid", "_IonDid", "input", "createRequest", "IonRequest", "didUniqueSuffix", "shortFormDid", "IonSdkConfig_default", "initialState", "canonicalizedInitialStateBytes", "JsonCanonicalizer", "encodedCanonicalizedInitialStateString", "Encoder", "suffixData", "canonicalizedStringBytes", "multihash", "Multihash", "import_buffer_polyfill", "P", "N", "Gx", "Gy", "CURVE", "err", "m", "str", "s", "au8", "a", "l", "u8n", "data", "toU8", "len", "h2b", "mod", "b", "r", "isPoint", "p", "Point", "Gpows", "_Point", "ex", "ey", "ez", "et", "hex", "strict", "d", "normed", "y", "b2n_LE", "y2", "u", "v", "isValid", "x", "uvRatio", "isXOdd", "other", "X1", "Y1", "Z1", "X2", "Y2", "Z2", "X1Z2", "X2Z1", "Y1Z2", "Y2Z1", "I", "A", "B", "C", "D", "x1y1", "E", "G", "F", "H", "X3", "Y3", "T3", "Z3", "T1", "T2", "n", "safe", "wNAF", "f", "scalar", "z", "iz", "invert", "n2b_32LE", "b2h", "padh", "num", "pad", "arr", "i", "j", "h", "concatB", "arrs", "sum", "md", "q", "pow2", "power", "pow_2_252_3", "b2", "b4", "b5", "b10", "b20", "b40", "b80", "b160", "b240", "b250", "RM1", "v3", "v7", "pow", "vx2", "root1", "root2", "useRoot1", "useRoot2", "noRoot", "_shaS", "cr", "etc", "b2h", "h2b", "concatB", "mod", "invert", "len", "crypto", "err", "u8n", "messages", "m", "_shaS", "f", "W", "precompute", "points", "windows", "p", "G", "b", "w", "i", "wNAF", "n", "comp", "Gpows", "neg", "cnd", "I", "f", "wsize", "mask", "maxNum", "shiftBy", "off", "wbits", "off1", "off2", "cnd1", "cnd2", "import_buffer_polyfill", "B256", "P", "N", "Gx", "Gy", "CURVE", "fLen", "crv", "x", "mod", "err", "m", "big", "n", "str", "s", "fe", "ge", "au8", "a", "l", "u8n", "data", "toU8", "len", "h2b", "b", "r", "isPoint", "p", "Point", "Gpows", "_Point", "px", "py", "pz", "hex", "head", "tail", "slcNum", "y", "sqrt", "isYOdd", "k", "G", "toPriv", "other", "X1", "Y1", "Z1", "X2", "Y2", "Z2", "X1Z2", "X2Z1", "Y1Z2", "Y2Z1", "X3", "Y3", "Z3", "b3", "t0", "t1", "t2", "t3", "t4", "t5", "safe", "I", "wNAF", "f", "d", "R", "u1", "u2", "z", "iz", "inv", "isCompressed", "n2h", "padh", "pad", "b2h", "arr", "i", "j", "h", "b2n", "from", "to", "n2b", "num", "concatB", "arrs", "sum", "md", "u", "v", "q", "e", "cr", "_hmacSync", "hashToPrivateKey", "hash", "toU8", "minLen", "fLen", "err", "num", "mod", "b2n", "N", "n2b", "etc", "h2b", "b2h", "concatB", "inv", "key", "msgs", "crypto", "cr", "s", "k", "u8n", "_hmacSync", "len", "etc", "_hmacSync", "f", "W", "precompute", "points", "windows", "p", "G", "b", "w", "i", "wNAF", "n", "comp", "Gpows", "neg", "cnd", "I", "wsize", "mask", "maxNum", "shiftBy", "off", "wbits", "off1", "off2", "cnd1", "cnd2", "import_buffer_polyfill", "IonNetwork", "import_buffer_polyfill", "IonPublicKeyPurpose", "DidIonRegisteredKeyType", "AlgorithmToKeyTypeMap", "DEFAULT_GATEWAY_URI", "_DidIon", "DidMethod", "keyManager", "LocalKeyManager", "options", "vm", "methodIds", "s", "defaultVerificationMethod", "verificationMethodsToAdd", "keyUri", "publicKey", "recoveryKeyUri", "recoveryKey", "updateKeyUri", "updateKey", "longFormDidUri", "DidIonUtils", "didDocument", "didResolutionMetadata", "did", "BearerDid", "registrationResult", "methodId", "parsedDid", "Did", "DidError", "verificationMethod", "portableDid", "gatewayUri", "verificationMethods", "getVerificationRelationshipsById", "ionDocument", "createOperation", "operationsUrl", "response", "didUri", "EMPTY_DID_RESOLUTION_RESULT", "resolutionUrl", "didDocumentMetadata", "error", "DidIon", "_DidIonUtils", "baseUrl", "path", "url", "services", "normalizedRecoveryKey", "normalizedUpdateKey", "IonDid", "IonRequest", "ionPublicKeys", "computeJwkThumbprint", "ionServices", "service", "jwk", "keyType", "normalizedJwk", "import_buffer_polyfill", "_DidJwk", "DidMethod", "keyManager", "LocalKeyManager", "options", "algorithm", "keyUri", "publicKey", "identifier", "Convert", "didUri", "document", "BearerDid", "didDocument", "parsedDid", "Did", "DidError", "verificationMethod", "portableDid", "did", "_options", "EMPTY_DID_RESOLUTION_RESULT", "DidJwk", "import_buffer_polyfill", "DidKeyRegisteredKeyType", "DidKeyVerificationMethodType", "AlgorithmToKeyTypeMap", "_DidKey", "DidMethod", "keyManager", "LocalKeyManager", "options", "algorithm", "keyUri", "publicKey", "identifier", "DidKeyUtils", "didUri", "document", "BearerDid", "didDocument", "parsedDid", "Did", "DidError", "methodId", "verificationMethod", "vm", "portableDid", "did", "EMPTY_DID_RESOLUTION_RESULT", "error", "defaultContext", "enableExperimentalPublicKeyTypes", "publicKeyFormat", "multibaseValue", "signatureVerificationMethod", "contextArray", "getVerificationMethodTypes", "typeName", "typeUrl", "publicKeyBytes", "multicodecValue", "multicodecName", "multibaseIdToKeyBytes", "actualLength", "expectedLength", "isValid", "Secp256k1", "Ed25519", "crv", "method", "scheme", "universalTypeOf", "DidKey", "_DidKeyUtils", "jwk", "params", "lookupKey", "name", "Multicodec", "curve", "compressor", "Secp256r1", "converter", "code", "jose", "keyBytesToMultibaseId", "import_buffer_polyfill", "_DidWeb", "DidMethod", "didUri", "_options", "parsedDid", "Did", "EMPTY_DID_RESOLUTION_RESULT", "baseUrl", "didDocumentUrl", "response", "didDocument", "DidWeb", "import_buffer_polyfill", "import_level", "import_ms", "DidResolverCacheLevel", "db", "location", "ttl", "ms", "did", "str", "cachedDidResolutionResult", "error", "value", "import_buffer_polyfill", "DidResolverCacheNoop", "_key", "_value", "import_buffer_polyfill", "UniversalResolver", "cache", "didResolvers", "DidResolverCacheNoop", "resolver", "didUri", "options", "parsedDid", "Did", "EMPTY_DID_RESOLUTION_RESULT", "cachedResolutionResult", "resolutionResult", "didUrl", "_options", "parsedDidUrl", "didDocument", "didResolutionMetadata", "didDocumentMetadata", "service", "verificationMethod", "idSet", "didResource", "vm", "svc"]
7
- }