@enbox/dids 0.0.2 → 0.0.3

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 (68) hide show
  1. package/README.md +41 -1
  2. package/dist/browser.js +6 -10
  3. package/dist/browser.js.map +4 -4
  4. package/dist/browser.mjs +6 -10
  5. package/dist/browser.mjs.map +4 -4
  6. package/dist/esm/bearer-did.js +5 -5
  7. package/dist/esm/bearer-did.js.map +1 -1
  8. package/dist/esm/did.js +13 -6
  9. package/dist/esm/did.js.map +1 -1
  10. package/dist/esm/methods/did-dht.js +34 -25
  11. package/dist/esm/methods/did-dht.js.map +1 -1
  12. package/dist/esm/methods/did-ion.js +9 -7
  13. package/dist/esm/methods/did-ion.js.map +1 -1
  14. package/dist/esm/methods/did-jwk.js +3 -3
  15. package/dist/esm/methods/did-jwk.js.map +1 -1
  16. package/dist/esm/methods/did-key.js +12 -240
  17. package/dist/esm/methods/did-key.js.map +1 -1
  18. package/dist/esm/methods/did-web.js +3 -2
  19. package/dist/esm/methods/did-web.js.map +1 -1
  20. package/dist/esm/resolver/resolver-cache-level.js +1 -1
  21. package/dist/esm/resolver/resolver-cache-level.js.map +1 -1
  22. package/dist/esm/resolver/resolver-cache-noop.js +10 -10
  23. package/dist/esm/resolver/resolver-cache-noop.js.map +1 -1
  24. package/dist/esm/resolver/universal-resolver.js +3 -3
  25. package/dist/esm/resolver/universal-resolver.js.map +1 -1
  26. package/dist/esm/utils.js +37 -21
  27. package/dist/esm/utils.js.map +1 -1
  28. package/dist/types/bearer-did.d.ts +3 -2
  29. package/dist/types/bearer-did.d.ts.map +1 -1
  30. package/dist/types/did.d.ts.map +1 -1
  31. package/dist/types/methods/did-dht.d.ts +4 -4
  32. package/dist/types/methods/did-dht.d.ts.map +1 -1
  33. package/dist/types/methods/did-ion.d.ts +3 -2
  34. package/dist/types/methods/did-ion.d.ts.map +1 -1
  35. package/dist/types/methods/did-jwk.d.ts +2 -2
  36. package/dist/types/methods/did-jwk.d.ts.map +1 -1
  37. package/dist/types/methods/did-key.d.ts +3 -52
  38. package/dist/types/methods/did-key.d.ts.map +1 -1
  39. package/dist/types/methods/did-method.d.ts +3 -3
  40. package/dist/types/methods/did-method.d.ts.map +1 -1
  41. package/dist/types/resolver/resolver-cache-level.d.ts.map +1 -1
  42. package/dist/types/resolver/universal-resolver.d.ts +2 -2
  43. package/dist/types/resolver/universal-resolver.d.ts.map +1 -1
  44. package/dist/types/types/did-core.d.ts +1 -1
  45. package/dist/types/types/did-core.d.ts.map +1 -1
  46. package/dist/types/utils.d.ts +8 -5
  47. package/dist/types/utils.d.ts.map +1 -1
  48. package/dist/utils.js +1 -5
  49. package/dist/utils.js.map +4 -4
  50. package/package.json +30 -40
  51. package/src/bearer-did.ts +12 -11
  52. package/src/did.ts +8 -6
  53. package/src/methods/did-dht.ts +35 -35
  54. package/src/methods/did-ion.ts +12 -11
  55. package/src/methods/did-jwk.ts +6 -6
  56. package/src/methods/did-key.ts +24 -305
  57. package/src/methods/did-method.ts +3 -3
  58. package/src/methods/did-web.ts +2 -2
  59. package/src/resolver/resolver-cache-level.ts +4 -4
  60. package/src/resolver/resolver-cache-noop.ts +10 -10
  61. package/src/resolver/universal-resolver.ts +5 -5
  62. package/src/types/did-core.ts +3 -3
  63. package/src/utils.ts +28 -26
  64. package/dist/cjs/index.js +0 -6303
  65. package/dist/cjs/index.js.map +0 -7
  66. package/dist/cjs/package.json +0 -1
  67. package/dist/cjs/utils.js +0 -245
  68. package/dist/cjs/utils.js.map +0 -7
@@ -1,7 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../../../node_modules/.pnpm/uri-js@4.4.1/node_modules/uri-js/src/index.ts", "../../../../node_modules/.pnpm/uri-js@4.4.1/node_modules/uri-js/src/schemes/urn-uuid.ts", "../../../../node_modules/.pnpm/uri-js@4.4.1/node_modules/uri-js/src/schemes/urn.ts", "../../../../node_modules/.pnpm/uri-js@4.4.1/node_modules/uri-js/src/schemes/mailto.ts", "../../../../node_modules/.pnpm/uri-js@4.4.1/node_modules/uri-js/src/schemes/wss.ts", "../../../../node_modules/.pnpm/uri-js@4.4.1/node_modules/uri-js/src/schemes/ws.ts", "../../../../node_modules/.pnpm/uri-js@4.4.1/node_modules/uri-js/src/schemes/https.ts", "../../../../node_modules/.pnpm/uri-js@4.4.1/node_modules/uri-js/src/schemes/http.ts", "../../../../node_modules/.pnpm/uri-js@4.4.1/node_modules/uri-js/src/uri.ts", "../../../../node_modules/.pnpm/uri-js@4.4.1/node_modules/uri-js/node_modules/punycode/punycode.es6.js", "../../../../node_modules/.pnpm/uri-js@4.4.1/node_modules/uri-js/src/regexps-iri.ts", "../../../../node_modules/.pnpm/uri-js@4.4.1/node_modules/uri-js/src/regexps-uri.ts", "../../../../node_modules/.pnpm/uri-js@4.4.1/node_modules/uri-js/src/util.ts", "../../../../node_modules/.pnpm/canonicalize@2.1.0/node_modules/canonicalize/lib/canonicalize.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", "../../src/utils.ts", "../../../../node_modules/.pnpm/uint8-util@2.2.5/node_modules/uint8-util/util.js", "../../../../node_modules/.pnpm/uint8-util@2.2.5/node_modules/uint8-util/_node.js", "../../../../node_modules/.pnpm/bencode@4.0.0/node_modules/bencode/lib/util.js", "../../../../node_modules/.pnpm/bencode@4.0.0/node_modules/bencode/lib/encode.js", "../../../../node_modules/.pnpm/bencode@4.0.0/node_modules/bencode/lib/decode.js", "../../../../node_modules/.pnpm/bencode@4.0.0/node_modules/bencode/lib/encoding-length.js", "../../../../node_modules/.pnpm/bencode@4.0.0/node_modules/bencode/index.js", "../../src/methods/did-dht.ts", "../../src/methods/did-method.ts", "../../../../node_modules/.pnpm/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/ErrorCode.ts", "../../../../node_modules/.pnpm/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/IonError.ts", "../../../../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/bytes.js", "../../../../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/bases/base.js", "../../../../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/bases/base64.js", "../../../../node_modules/.pnpm/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/Encoder.ts", "../../../../node_modules/.pnpm/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/IonRequest.ts", "../../../../node_modules/.pnpm/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/enums/OperationKeyType.ts", "../../../../node_modules/.pnpm/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/InputValidator.ts", "../../../../node_modules/.pnpm/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/IonSdkConfig.ts", "../../../../node_modules/.pnpm/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/JsonCanonicalizer.ts", "../../../../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/vendor/varint.js", "../../../../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/varint.js", "../../../../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/hashes/digest.js", "../../../../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/hashes/sha2.js", "../../../../node_modules/.pnpm/multiformats@12.1.3/node_modules/multiformats/src/hashes/hasher.js", "../../../../node_modules/.pnpm/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/Multihash.ts", "../../../../node_modules/.pnpm/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/enums/OperationType.ts", "../../../../node_modules/.pnpm/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/enums/PatchAction.ts", "../../../../node_modules/.pnpm/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/IonDid.ts", "../../../../node_modules/.pnpm/@noble+ed25519@2.0.0/node_modules/@noble/ed25519/index.js", "../../../../node_modules/.pnpm/@noble+secp256k1@2.0.0/node_modules/@noble/secp256k1/index.js", "../../../../node_modules/.pnpm/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/enums/IonNetwork.ts", "../../../../node_modules/.pnpm/@decentralized-identity+ion-sdk@1.0.4/node_modules/@decentralized-identity/ion-sdk/lib/enums/IonPublicKeyPurpose.ts", "../../src/methods/did-ion.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": ["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", "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 { 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})(?<path>${Did.PATH_PATTERN})(?<query>${Did.QUERY_PATTERN})(?<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 Jwk,\n Signer,\n CryptoApi,\n KeyIdentifier,\n EnclosedSignParams,\n KmsExportKeyParams,\n KmsImportKeyParams,\n KeyImporterExporter,\n EnclosedVerifyParams,\n} from '@enbox/crypto';\n\nimport { LocalKeyManager, CryptoUtils } 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 | 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 let 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 (let 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 (let 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 (let 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}", "import type { Jwk } from '@enbox/crypto';\nimport type { RequireOnly } from '@enbox/common';\n\nimport { Convert, Multicodec } from '@enbox/common';\nimport { computeJwkThumbprint } from '@enbox/crypto';\n\nimport type { KeyWithMulticodec } from './types/multibase.js';\n\nimport { DidError, DidErrorCode } from './did-error.js';\nimport {\n DidService,\n DidDocument,\n DidVerificationMethod,\n DidVerificationRelationship,\n} from './types/did-core.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-production.up.railway.app',\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, only the service with this ID will be returned.\n * @param params.type - Optional. A string representing the specific service type to match. 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 (let 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-production.up.railway.app',\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 (error: any) {\n throw new DidError(DidErrorCode.InvalidDid, `Invalid multibase identifier: ${multibaseKeyId}`);\n }\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", "import { createHash, randomBytes as rand } from 'node:crypto'\r\n\r\nconst decoder = new TextDecoder()\r\nexport const arr2text = (data, enc) => {\r\n if (data.byteLength > 1024) {\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 return Buffer.from(data).toString(enc || 'utf8')\r\n}\r\n\r\nexport const text2arr = str => new Uint8Array(Buffer.from(str, 'utf8'))\r\n\r\nexport const arr2base = data => Buffer.from(data).toString('base64')\r\n\r\nexport const base2arr = str => new Uint8Array(Buffer.from(str, 'base64'))\r\n\r\nexport const hex2bin = hex => Buffer.from(hex, 'hex').toString('binary')\r\n\r\nexport const bin2hex = bin => Buffer.from(bin, 'binary').toString('hex')\r\n\r\nexport const hash = async (data, format, algo = 'sha1') => {\r\n algo = algo.replace('sha-', 'sha')\r\n const out = createHash(algo).update(data)\r\n return format ? out.digest(format) : new Uint8Array(out.digest().buffer)\r\n}\r\n\r\nexport const randomBytes = size => {\r\n return new Uint8Array(rand(size))\r\n}\r\n\r\nexport * from './util.js'\r\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 { 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 { 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 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 type { Packet, StringAnswer, TxtAnswer, TxtData } from '@dnsquery/dns-packet';\nimport type {\n Jwk,\n Signer,\n CryptoApi,\n KeyIdentifier,\n KmsExportKeyParams,\n KmsImportKeyParams,\n KeyImporterExporter,\n AsymmetricKeyConverter,\n} from '@enbox/crypto';\n\nimport bencode from 'bencode';\nimport { Convert } from '@enbox/common';\nimport { computeJwkThumbprint, Ed25519, LocalKeyManager, Secp256k1, Secp256r1, X25519 } from '@enbox/crypto';\nimport { AUTHORITATIVE_ANSWER, decode as dnsPacketDecode, encode as dnsPacketEncode } from '@dnsquery/dns-packet';\n\nimport type { DidMetadata, PortableDid } from '../types/portable-did.js';\nimport type { DidCreateOptions, DidCreateVerificationMethod, DidRegistrationResult } from './did-method.js';\nimport type {\n DidService,\n DidDocument,\n DidResolutionResult,\n DidResolutionOptions,\n DidVerificationMethod,\n} from '../types/did-core.js';\n\nimport { Did } from '../did.js';\nimport { DidMethod } from './did-method.js';\nimport { BearerDid } from '../bearer-did.js';\nimport { extractDidFragment } from '../utils.js';\nimport { DidError, DidErrorCode } from '../did-error.js';\nimport { DidVerificationRelationship } from '../types/did-core.js';\nimport { EMPTY_DID_RESOLUTION_RESULT } from '../types/did-resolution.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 = 'https://did-dht-production.up.railway.app';\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 any,\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 if (!document[purpose]) 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 let publicKey = await DidDhtUtils.keyConverter(namedCurve).bytesToPublicKey({ publicKeyBytes });\n\n publicKey.alg = parsedAlg || KeyTypeToDefaultAlgorithmMap[Number(t) as DidDhtRegisteredKeyType];\n\n // TOOD: when this is complete https://github.com/TBD54566975/web5-js/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 let 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 any[])\n ?.map(id => 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 let 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 type {\n CryptoApi,\n LocalKeyManager,\n InferKeyGeneratorAlgorithm,\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 DidResolutionResult,\n DidResolutionOptions,\n DidVerificationMethod,\n} from '../types/did-core.js';\n\nimport { 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}", null, null, "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", "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", "// @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", null, null, null, null, null, null, "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", "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", "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", "// @ts-check\n\nimport crypto from 'crypto'\nimport { coerce } from '../bytes.js'\nimport { from } from './hasher.js'\n\nexport const sha256 = from({\n name: 'sha2-256',\n code: 0x12,\n encode: (input) => coerce(crypto.createHash('sha256').update(input).digest())\n})\n\nexport const sha512 = from({\n name: 'sha2-512',\n code: 0x13,\n encode: input => coerce(crypto.createHash('sha512').update(input).digest())\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 { CryptoApi, Jwk, KeyIdentifier, KeyImporterExporter, KmsExportKeyParams, KmsImportKeyParams } from '@enbox/crypto';\nimport type {\n JwkEs256k,\n IonDocumentModel,\n IonPublicKeyModel,\n IonPublicKeyPurpose,\n} from '@decentralized-identity/ion-sdk';\n\nimport { IonDid, IonRequest } from '@decentralized-identity/ion-sdk';\nimport { LocalKeyManager, computeJwkThumbprint } from '@enbox/crypto';\n\nimport type { PortableDid } from '../types/portable-did.js';\nimport type { DidCreateOptions, DidCreateVerificationMethod, DidRegistrationResult } from '../methods/did-method.js';\nimport type {\n DidService,\n DidDocument,\n DidResolutionResult,\n DidResolutionOptions,\n DidVerificationMethod,\n DidVerificationRelationship,\n} from '../types/did-core.js';\n\nimport { Did } from '../did.js';\nimport { BearerDid } from '../bearer-did.js';\nimport { DidMethod } from '../methods/did-method.js';\nimport { DidError, DidErrorCode } from '../did-error.js';\nimport { getVerificationRelationshipsById } from '../utils.js';\nimport { EMPTY_DID_RESOLUTION_RESULT } from '../types/did-resolution.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 any,\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 (error: any) {\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 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}", "import type {\n Jwk,\n CryptoApi,\n KeyIdentifier,\n KmsExportKeyParams,\n KmsImportKeyParams,\n KeyImporterExporter,\n InferKeyGeneratorAlgorithm,\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 { Did } from '../did.js';\nimport { DidMethod } from './did-method.js';\nimport { BearerDid } from '../bearer-did.js';\nimport { DidError, DidErrorCode } from '../did-error.js';\nimport { EMPTY_DID_RESOLUTION_RESULT } from '../types/did-resolution.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 = Convert.base64Url(parsedDid!.id).toObject() as Jwk;\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 { MulticodecCode, MulticodecDefinition, RequireOnly } from '@enbox/common';\nimport type {\n Jwk,\n CryptoApi,\n KeyCompressor,\n KeyIdentifier,\n KmsExportKeyParams,\n KmsImportKeyParams,\n KeyImporterExporter,\n AsymmetricKeyConverter,\n InferKeyGeneratorAlgorithm,\n} from '@enbox/crypto';\n\nimport { Multicodec, universalTypeOf } from '@enbox/common';\nimport {\n X25519,\n Ed25519,\n Secp256k1,\n Secp256r1,\n LocalKeyManager,\n} from '@enbox/crypto';\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 { Did } from '../did.js';\nimport { DidMethod } from './did-method.js';\nimport { BearerDid } from '../bearer-did.js';\nimport { DidError, DidErrorCode } from '../did-error.js';\nimport { KeyWithMulticodec } from '../types/multibase.js';\nimport { EMPTY_DID_RESOLUTION_RESULT } from '../types/did-resolution.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 encryption key derivation during DID creation.\n *\n * By default, this option is set to `false`, which means encryption key derivation is not\n * performed unless explicitly enabled.\n *\n * When set to `true`, an `X25519` key will be derived from the `Ed25519` public key used to\n * create the DID. This feature enables the same DID to be used for encrypted communication, in\n * addition to signature verification.\n *\n * Notes:\n * - This option is ONLY applicable when the `algorithm` of the DID's public key is `Ed25519`.\n * - Enabling this introduces specific cryptographic considerations that should be understood\n * before using the same key pair for digital signatures and encrypted communication. See the following for more information:\n */\n enableEncryptionKeyDerivation?: boolean;\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 * X25519: A Diffie-Hellman key exchange algorithm using Curve25519.\n */\n X25519 = 'X25519'\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\n /** Represents an X25519 public key used for key agreement protocols. */\n X25519KeyAgreementKey2020: 'https://w3id.org/security/suites/x25519-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 X25519 : DidKeyRegisteredKeyType.X25519\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 * This method can optionally derive an encryption key from the public key used to create the DID\n * if and only if the public key algorithm is `Ed25519`. This feature enables the same DID to be\n * used for encrypted communication, in addition to signature verification. To enable this\n * feature when calling {@link DidKey.create | `DidKey.create()`}, first specify an `algorithm` of\n * `Ed25519` or provide a `keySet` referencing an `Ed25519` key and then set the\n * `enableEncryptionKeyDerivation` option to `true`.\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 * This method can optionally derive an encryption key from the public key used to create the DID\n * if and only if the public key algorithm is `Ed25519`. This feature enables the same DID to be\n * used for encrypted communication, in addition to signature verification. To enable this\n * feature, specify an `algorithm` of `Ed25519` as either a top-level option or in a\n * `verificationMethod` and set the `enableEncryptionKeyDerivation` option to `true`.\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 enableEncryptionKeyDerivation = false,\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. If options.enableEncryptionKeyDerivation is set to true:\n * Add the encryptionVerificationMethod value to the verificationMethod\n * array. Initialize the keyAgreement property in document to an array\n * where the first item is the value of the id property in\n * encryptionVerificationMethod.\n */\n if (enableEncryptionKeyDerivation === true) {\n /**\n * Although not covered by the did:key method specification, a sensible\n * default will be taken to use the 'X25519KeyAgreementKey2020'\n * verification method type if the given publicKeyFormat is\n * 'Ed25519VerificationKey2020' and 'JsonWebKey2020' otherwise.\n */\n const encryptionPublicKeyFormat =\n (publicKeyFormat === 'Ed25519VerificationKey2020')\n ? 'X25519KeyAgreementKey2020'\n : 'JsonWebKey2020';\n\n /**\n * 8.1 Initialize the encryptionVerificationMethod to the result of\n * passing identifier, multibaseValue, and options to an\n * {@link https://w3c-ccg.github.io/did-method-key/#encryption-method-creation-algorithm | Encryption Method Creation Algorithm}.\n */\n const encryptionVerificationMethod = await this.createEncryptionMethod({\n didUri,\n multibaseValue,\n options: { enableExperimentalPublicKeyTypes, publicKeyFormat: encryptionPublicKeyFormat }\n });\n\n /**\n * 8.2 Add the encryptionVerificationMethod value to the\n * verificationMethod array.\n */\n didDocument.verificationMethod.push(encryptionVerificationMethod);\n\n /**\n * 8.3. Initialize the keyAgreement property in document to an array\n * where the first item is the value of the id property in\n * encryptionVerificationMethod.\n */\n didDocument.keyAgreement = [encryptionVerificationMethod.id];\n }\n\n /**\n * 9. 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 * Decoding a multibase-encoded multicodec value into a verification method\n * that is suitable for verifying that encrypted information will be\n * received by the intended recipient.\n */\n private static async createEncryptionMethod({ 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 raw publicKeyBytes to the result of passing multibaseValue and\n * options to a Derive Encryption Key algorithm.\n */\n const {\n keyBytes: publicKeyBytes,\n multicodecCode: multicodecValue,\n } = await DidKey.deriveEncryptionKey({ multibaseValue });\n\n /**\n * 3. Ensure the proper key length of raw publicKeyBytes based on the multicodecValue table\n * provided below:\n *\n * Multicodec hexadecimal value: 0xec\n *\n * If the byte length of raw publicKeyBytes does not match the expected public key length for\n * the 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. Create the multibaseValue by concatenating the letter 'z' and the\n * base58-btc encoding of the concatenation of the multicodecValue and\n * the raw publicKeyBytes.\n */\n const kemMultibaseValue = keyBytesToMultibaseId({\n keyBytes : publicKeyBytes,\n multicodecCode : multicodecValue\n });\n\n /**\n * 5. Set the verificationMethod.id value by concatenating identifier,\n * a hash character (#), and the multibaseValue. If verificationMethod.id\n * is not a valid DID URL, an invalidDidUrl error MUST be raised.\n */\n verificationMethod.id = `${didUri}#${kemMultibaseValue}`;\n try {\n new URL(verificationMethod.id);\n } catch (error: any) {\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\n * unsupportedPublicKeyType error 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 X25519KeyAgreementKey2020, an invalidPublicKeyType error MUST be\n * raised.\n */\n const StandardPublicKeyTypes = ['Multikey', 'JsonWebKey2020', 'X25519KeyAgreementKey2020'];\n if (enableExperimentalPublicKeyTypes === false\n && !(StandardPublicKeyTypes.includes(publicKeyFormat))) {\n throw new DidError(DidErrorCode.InvalidPublicKeyType, `Specified '${publicKeyFormat}' without setting enableExperimentalPublicKeyTypes to true.`);\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 X25519KeyAgreementKey2020, set the verificationMethod.publicKeyMultibase\n * value to multibaseValue.\n *\n * Note: This implementation does not currently support the Multikey\n * format.\n */\n if (publicKeyFormat === 'X25519KeyAgreementKey2020') {\n verificationMethod.publicKeyMultibase = kemMultibaseValue;\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 * 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 case 'x25519-pub':\n // TODO: Validate key once/if X25519.validatePublicKey() is implemented.\n // isValid = X25519.validatePublicKey({ key: rawPublicKeyBytes})\n isValid = true;\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 (error: any) {\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(DidErrorCode.InvalidPublicKeyType, `Specified '${publicKeyFormat}' without setting enableExperimentalPublicKeyTypes to true.`);\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 * Transform a multibase-encoded multicodec value to public encryption key\n * components that are suitable for encrypting messages to a receiver. A\n * mathematical proof elaborating on the safety of performing this operation\n * is available in:\n * {@link https://eprint.iacr.org/2021/509.pdf | On using the same key pair for Ed25519 and an X25519 based KEM}\n */\n private static async deriveEncryptionKey({ multibaseValue }: {\n multibaseValue: string\n }): Promise<RequireOnly<KeyWithMulticodec, 'keyBytes' | 'multicodecCode'>> {\n /**\n * 1. Set publicEncryptionKey to an empty object.\n */\n let publicEncryptionKey: RequireOnly<KeyWithMulticodec, 'keyBytes' | 'multicodecCode'> = {\n keyBytes : new Uint8Array(),\n multicodecCode : 0\n };\n\n /**\n * 2. Decode multibaseValue using the base58-btc multibase alphabet and\n * set multicodecValue to the multicodec header for the decoded value.\n * Implementers are cautioned to ensure that the multicodecValue is set\n * to the result after performing varint decoding.\n *\n * 3. Set the rawPublicKeyBytes to the bytes remaining after the multicodec\n * header.\n */\n const {\n keyBytes: publicKeyBytes,\n multicodecCode: multicodecValue\n } = multibaseIdToKeyBytes({ multibaseKeyId: multibaseValue });\n\n /**\n * 4. If the multicodecValue is 0xed (Ed25519 public key), derive a public X25519 encryption key\n * by using the raw publicKeyBytes and the algorithm defined in\n * {@link https://datatracker.ietf.org/doc/html/draft-ietf-core-oscore-groupcomm | Group OSCORE - Secure Group Communication for CoAP}\n * for Curve25519 in Section 2.4.2: ECDH with Montgomery Coordinates and set\n * generatedPublicEncryptionKeyBytes to the result.\n */\n if (multicodecValue === 0xed) {\n const ed25519PublicKey = await DidKeyUtils.keyConverter('Ed25519').bytesToPublicKey({\n publicKeyBytes\n });\n const generatedPublicEncryptionKey = await Ed25519.convertPublicKeyToX25519({\n publicKey: ed25519PublicKey\n });\n const generatedPublicEncryptionKeyBytes = await DidKeyUtils.keyConverter('Ed25519').publicKeyToBytes({\n publicKey: generatedPublicEncryptionKey\n });\n\n /**\n * 5. Set multicodecValue to 0xec.\n * 6. Set raw public keyBytes to generatedPublicEncryptionKeyBytes.\n */\n publicEncryptionKey = {\n keyBytes : generatedPublicEncryptionKeyBytes,\n multicodecCode : 0xec\n };\n }\n\n /**\n * 7. Return publicEncryptionKey.\n */\n return publicEncryptionKey;\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 'X25519:public' : 'x25519-pub',\n 'X25519:private' : 'x25519-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 // x25519-pub - Curve25519 public key - 32 bytes\n 0xec: 32,\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 'x25519-pub' : { crv: 'X25519', kty: 'OKP', x: '' },\n 'x25519-priv' : { crv: 'X25519', kty: 'OKP', x: '', 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 '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 * 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 (error: any) {\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 ms from 'ms';\nimport { Level } from 'level';\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: function (_key: string): Promise<DidResolutionResult> {\n return null as any;\n },\n set: function (_key: string, _value: DidResolutionResult): Promise<void> {\n return null as any;\n },\n delete: function (_key: string): Promise<void> {\n return null as any;\n },\n clear: function (): Promise<void> {\n return null as any;\n },\n close: function (): Promise<void> {\n return null as any;\n }\n};", "import type { DidMethodResolver } from '../methods/did-method.js';\nimport type { DidResolver, DidResolverCache, DidUrlDereferencer } from '../types/did-resolution.js';\nimport type { DidDereferencingOptions, DidDereferencingResult, DidResolutionOptions, DidResolutionResult, DidResource } from '../types/did-core.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/TBD54566975/web5-js/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 (let 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 (let 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": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AYAA,eAAAA,QAAA;0CAAyBC,OAAzB,MAAA,IAAA,GAAA,OAAA,GAAA,OAAA,MAAA,QAAA;eAAA,IAAA,IAAA,UAAA,IAAA;;YACKA,KAAKC,SAAS,GAAG;eACf,CAAL,IAAUD,KAAK,CAAL,EAAQE,MAAM,GAAG,EAAjB;cACJC,KAAKH,KAAKC,SAAS;mBAChBG,IAAI,GAAGA,IAAID,IAAI,EAAEC,GAAG;iBACvBA,CAAL,IAAUJ,KAAKI,CAAL,EAAQF,MAAM,GAAG,EAAjB;;eAENC,EAAL,IAAWH,KAAKG,EAAL,EAASD,MAAM,CAAf;iBACJF,KAAKK,KAAK,EAAV;eACD;iBACCL,KAAK,CAAL;;;AAIT,eAAAM,OAAuBC,MAAvB;eACQ,QAAQA,OAAM;;AAGtB,eAAAC,OAAuBC,GAAvB;eACQA,MAAMC,SAAY,cAAeD,MAAM,OAAO,SAASE,OAAOC,UAAUC,SAASC,KAAKL,CAA/B,EAAkCM,MAAM,GAAxC,EAA6CC,IAA7C,EAAmDD,MAAM,GAAzD,EAA8DE,MAA9D,EAAsEC,YAAtE;;AAG/D,eAAAC,YAA4BZ,MAA5B;eACQA,KAAIY,YAAJ;;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,aAAa;AACf,eAAO;UACL,uBAAwB,EAAE,aAAa,uBAAsB;UAC7D,eAAwB;UACxB,iBAAwB;;MAE5B,OAAO;AACL,eAAO;UACL,uBAAwB,EAAE,OAAO,aAAa,SAAQ;UACtD,eAAwB;UACxB,iBAAwB,CAAA;;MAE5B;IACF,CAAC;;;",
6
- "names": ["merge", "sets", "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", "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", "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", "currentValue", "basicLength", "handledCPCount", "m", "handledCPCountPlusOne", "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", "_normalizeIPv6", "IPV6ADDRESS", "zone", "reverse", "last", "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", "IRI_PROTOCOL", "URI_PROTOCOL", "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", "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", "exports", "module", "values", "DidVerificationRelationship", "DidErrorCode", "import_crypto", "_b", "_a", "_a", "length", "length", "i", "str", "length", "length", "encodingLength", "import_common", "import_crypto", "DidDhtRegisteredDidType", "DidDhtRegisteredKeyType", "DidDhtVerificationRelationship", "_a", "_b", "dnsRecordId", "inv", "dnsPacketEncode", "__awaiter", "dnsPacketDecode", "decoder", "encode", "decode", "decode", "alphabet", "encode", "Encoder", "OperationKeyType", "Encoder", "Encoder", "encode", "decode", "decode", "encodingLength", "encodingLength", "decode", "import_crypto", "from", "encode", "from", "crypto", "Encoder", "decode", "OperationType", "PatchAction", "Encoder", "G", "crypto", "p", "n", "P", "N", "Gx", "Gy", "CURVE", "mod", "err", "str", "au8", "u8n", "toU8", "h2b", "isPoint", "Point", "Gpows", "G", "I", "wNAF", "padh", "b2h", "from", "concatB", "cr", "toU8", "err", "mod", "N", "etc", "h2b", "b2h", "concatB", "crypto", "cr", "u8n", "etc", "W", "precompute", "G", "wNAF", "Gpows", "p", "n", "I", "IonNetwork", "IonPublicKeyPurpose", "import_crypto", "DidIonRegisteredKeyType", "AlgorithmToKeyTypeMap", "DEFAULT_GATEWAY_URI", "_a", "import_common", "import_crypto", "import_common", "import_crypto", "DidKeyRegisteredKeyType", "AlgorithmToKeyTypeMap", "crv", "ms", "str"]
7
- }