web-dc-api 0.1.5 → 0.1.6

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 (148) hide show
  1. package/dist/cjs/index.js +1 -1
  2. package/dist/dc.min.js +1 -1
  3. package/dist/esm/index.js +1 -1
  4. package/dist/index.d.ts +934 -878
  5. package/package.json +4 -8
  6. package/dist/cjs/helia-core-B1Xqha7a.js +0 -1
  7. package/dist/cjs/helia-core-D8Uv1KjQ.js +0 -1
  8. package/dist/cjs/polkadot-api-7PhQf3ws.js +0 -1
  9. package/dist/cjs/polkadot-api-CtrJVWuZ.js +0 -1
  10. package/dist/esm/chunks/helia-core-BxMqyK2Y.js +0 -1
  11. package/dist/esm/chunks/helia-core-DMXRpcO-.js +0 -1
  12. package/dist/esm/chunks/polkadot-api-5Y9Bw8VT.js +0 -1
  13. package/dist/esm/chunks/polkadot-api-D69Ioun_.js +0 -1
  14. package/lib/common/blowfish/block.ts +0 -259
  15. package/lib/common/blowfish/cipher.ts +0 -144
  16. package/lib/common/blowfish/const.ts +0 -195
  17. package/lib/common/chain.ts +0 -469
  18. package/lib/common/commonclient.ts +0 -202
  19. package/lib/common/constants.ts +0 -55
  20. package/lib/common/dc-key/ed25519.ts +0 -343
  21. package/lib/common/dc-key/keyManager.ts +0 -424
  22. package/lib/common/dcapi.ts +0 -98
  23. package/lib/common/dcutil.ts +0 -627
  24. package/lib/common/define.ts +0 -70
  25. package/lib/common/error.ts +0 -67
  26. package/lib/common/grpc-dc.ts +0 -104
  27. package/lib/common/module-system.ts +0 -184
  28. package/lib/common/service-worker.ts +0 -234
  29. package/lib/common/types/types.ts +0 -344
  30. package/lib/dc.ts +0 -701
  31. package/lib/implements/account/client.ts +0 -185
  32. package/lib/implements/account/manager.ts +0 -683
  33. package/lib/implements/aiproxy/client.ts +0 -357
  34. package/lib/implements/aiproxy/manager.ts +0 -670
  35. package/lib/implements/cache/client.ts +0 -105
  36. package/lib/implements/cache/manager.ts +0 -127
  37. package/lib/implements/comment/client.ts +0 -982
  38. package/lib/implements/comment/manager.ts +0 -1151
  39. package/lib/implements/dc/client.ts +0 -51
  40. package/lib/implements/dc/manager.ts +0 -33
  41. package/lib/implements/file/client.ts +0 -253
  42. package/lib/implements/file/file-cache-manager.ts +0 -142
  43. package/lib/implements/file/manager.ts +0 -1240
  44. package/lib/implements/file/seekableFileStream.ts +0 -344
  45. package/lib/implements/file/streamwriter.ts +0 -322
  46. package/lib/implements/keyvalue/client.ts +0 -376
  47. package/lib/implements/keyvalue/manager.ts +0 -759
  48. package/lib/implements/message/client.ts +0 -250
  49. package/lib/implements/message/manager.ts +0 -215
  50. package/lib/implements/threaddb/cbor/coding.ts +0 -62
  51. package/lib/implements/threaddb/cbor/event.ts +0 -336
  52. package/lib/implements/threaddb/cbor/node.ts +0 -542
  53. package/lib/implements/threaddb/cbor/record.ts +0 -398
  54. package/lib/implements/threaddb/common/AsyncMutex.ts +0 -24
  55. package/lib/implements/threaddb/common/addrinfo.ts +0 -135
  56. package/lib/implements/threaddb/common/dispatcher.ts +0 -81
  57. package/lib/implements/threaddb/common/idbstore-adapter.ts +0 -260
  58. package/lib/implements/threaddb/common/json-patcher.ts +0 -204
  59. package/lib/implements/threaddb/common/key.ts +0 -290
  60. package/lib/implements/threaddb/common/level-adapter.ts +0 -235
  61. package/lib/implements/threaddb/common/lineReader.ts +0 -79
  62. package/lib/implements/threaddb/common/logstore.ts +0 -215
  63. package/lib/implements/threaddb/common/transformed-datastore.ts +0 -308
  64. package/lib/implements/threaddb/core/app.ts +0 -206
  65. package/lib/implements/threaddb/core/core.ts +0 -230
  66. package/lib/implements/threaddb/core/db.ts +0 -249
  67. package/lib/implements/threaddb/core/event.ts +0 -54
  68. package/lib/implements/threaddb/core/head.ts +0 -89
  69. package/lib/implements/threaddb/core/identity.ts +0 -171
  70. package/lib/implements/threaddb/core/logstore.ts +0 -137
  71. package/lib/implements/threaddb/core/options.ts +0 -14
  72. package/lib/implements/threaddb/core/record.ts +0 -54
  73. package/lib/implements/threaddb/db/collection.ts +0 -1910
  74. package/lib/implements/threaddb/db/db.ts +0 -698
  75. package/lib/implements/threaddb/db/json2Query.ts +0 -192
  76. package/lib/implements/threaddb/db/query.ts +0 -524
  77. package/lib/implements/threaddb/dbclient.ts +0 -543
  78. package/lib/implements/threaddb/dbmanager.ts +0 -1906
  79. package/lib/implements/threaddb/lsstoreds/addr_book.ts +0 -549
  80. package/lib/implements/threaddb/lsstoreds/cache.ts +0 -36
  81. package/lib/implements/threaddb/lsstoreds/cyclic_batch.ts +0 -87
  82. package/lib/implements/threaddb/lsstoreds/global.ts +0 -151
  83. package/lib/implements/threaddb/lsstoreds/headbook.ts +0 -373
  84. package/lib/implements/threaddb/lsstoreds/keybook.ts +0 -297
  85. package/lib/implements/threaddb/lsstoreds/logstore.ts +0 -29
  86. package/lib/implements/threaddb/lsstoreds/metadata.ts +0 -223
  87. package/lib/implements/threaddb/net/define.ts +0 -149
  88. package/lib/implements/threaddb/net/grpcClient.ts +0 -589
  89. package/lib/implements/threaddb/net/grpcserver.ts +0 -146
  90. package/lib/implements/threaddb/net/net.ts +0 -2047
  91. package/lib/implements/threaddb/pb/lstore.proto +0 -38
  92. package/lib/implements/threaddb/pb/lstore.ts +0 -393
  93. package/lib/implements/threaddb/pb/lstore_pb.d.ts +0 -433
  94. package/lib/implements/threaddb/pb/lstore_pb.js +0 -1085
  95. package/lib/implements/threaddb/pb/net.proto +0 -194
  96. package/lib/implements/threaddb/pb/net_pb.d.ts +0 -2349
  97. package/lib/implements/threaddb/pb/net_pb.js +0 -5525
  98. package/lib/implements/threaddb/pb/proto-custom-types.ts +0 -212
  99. package/lib/implements/util/client.ts +0 -72
  100. package/lib/implements/util/manager.ts +0 -146
  101. package/lib/implements/wallet/manager.ts +0 -671
  102. package/lib/index.ts +0 -57
  103. package/lib/interfaces/DCContext.ts +0 -51
  104. package/lib/interfaces/aiproxy-interface.ts +0 -145
  105. package/lib/interfaces/auth-interface.ts +0 -118
  106. package/lib/interfaces/cache-interface.ts +0 -22
  107. package/lib/interfaces/client-interface.ts +0 -11
  108. package/lib/interfaces/comment-interface.ts +0 -167
  109. package/lib/interfaces/components/news-component.ts +0 -0
  110. package/lib/interfaces/database-interface.ts +0 -169
  111. package/lib/interfaces/file-interface.ts +0 -120
  112. package/lib/interfaces/index.ts +0 -10
  113. package/lib/interfaces/keyvalue-interface.ts +0 -156
  114. package/lib/interfaces/message-interface.ts +0 -22
  115. package/lib/interfaces/util-interface.ts +0 -31
  116. package/lib/modules/aiproxy-module.ts +0 -246
  117. package/lib/modules/auth-module.ts +0 -753
  118. package/lib/modules/cache-module.ts +0 -99
  119. package/lib/modules/client-module.ts +0 -71
  120. package/lib/modules/comment-module.ts +0 -429
  121. package/lib/modules/components/news-components.ts +0 -390
  122. package/lib/modules/database-module.ts +0 -598
  123. package/lib/modules/file-module.ts +0 -291
  124. package/lib/modules/index.ts +0 -13
  125. package/lib/modules/keyvalue-module.ts +0 -379
  126. package/lib/modules/message-module.ts +0 -107
  127. package/lib/modules/util-module.ts +0 -148
  128. package/lib/polyfills/process-env-browser.ts +0 -1
  129. package/lib/proto/datasource.ts +0 -93
  130. package/lib/proto/dcnet.proto +0 -1601
  131. package/lib/proto/dcnet_proto.d.ts +0 -22857
  132. package/lib/proto/dcnet_proto.js +0 -55204
  133. package/lib/proto/dcnet_proto_sparse.js +0 -55166
  134. package/lib/proto/oidfetch.proto +0 -25
  135. package/lib/proto/oidfetch_proto.d.ts +0 -585
  136. package/lib/proto/oidfetch_proto.js +0 -1247
  137. package/lib/serverless/babel-browser.ts +0 -39
  138. package/lib/serverless/base_entity.ts +0 -78
  139. package/lib/serverless/base_repository.ts +0 -414
  140. package/lib/serverless/browser_schema_extractor.ts +0 -283
  141. package/lib/serverless/decorator_factory.ts +0 -322
  142. package/lib/util/BrowserLineReader.ts +0 -73
  143. package/lib/util/base64.ts +0 -105
  144. package/lib/util/bcrypt.ts +0 -206
  145. package/lib/util/curve25519Encryption.ts +0 -418
  146. package/lib/util/dccrypt.ts +0 -73
  147. package/lib/util/logger.ts +0 -104
  148. package/lib/util/utils.ts +0 -289
@@ -1 +0,0 @@
1
- "use strict";var e=require("./babel-tools-BoLJtxtW.js"),t=new Uint8Array(0);function r(e){var r=e.match(/../g);return null!=r?new Uint8Array(r.map((e=>parseInt(e,16)))):t}function n(e){if(e instanceof Uint8Array&&"Uint8Array"===e.constructor.name)return e;if(e instanceof ArrayBuffer)return new Uint8Array(e);if(ArrayBuffer.isView(e))return new Uint8Array(e.buffer,e.byteOffset,e.byteLength);throw new Error("Unknown type, must be binary type")}var i=function(e,t){if(e.length>=255)throw new TypeError("Alphabet too long");for(var r=new Uint8Array(256),n=0;n<r.length;n++)r[n]=255;for(var i=0;i<e.length;i++){var o=e.charAt(i),a=o.charCodeAt(0);if(255!==r[a])throw new TypeError(o+" is ambiguous");r[a]=i}var s=e.length,l=e.charAt(0),c=Math.log(s)/Math.log(256),u=Math.log(256)/Math.log(s);function d(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;var t=0;if(" "!==e[t]){for(var n=0,i=0;e[t]===l;)n++,t++;for(var o=(e.length-t)*c+1>>>0,a=new Uint8Array(o);e[t];){var u=r[e.charCodeAt(t)];if(255===u)return;for(var d=0,h=o-1;(0!==u||d<i)&&-1!==h;h--,d++)u+=s*a[h]>>>0,a[h]=u%256>>>0,u=u/256>>>0;if(0!==u)throw new Error("Non-zero carry");i=d,t++}if(" "!==e[t]){for(var p=o-i;p!==o&&0===a[p];)p++;for(var f=new Uint8Array(n+(o-p)),v=n;p!==o;)f[v++]=a[p++];return f}}}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var r=0,n=0,i=0,o=t.length;i!==o&&0===t[i];)i++,r++;for(var a=(o-i)*u+1>>>0,c=new Uint8Array(a);i!==o;){for(var d=t[i],h=0,p=a-1;(0!==d||h<n)&&-1!==p;p--,h++)d+=256*c[p]>>>0,c[p]=d%s>>>0,d=d/s>>>0;if(0!==d)throw new Error("Non-zero carry");n=h,i++}for(var f=a-n;f!==a&&0===c[f];)f++;for(var v=l.repeat(r);f<a;++f)v+=e.charAt(c[f]);return v},decodeUnsafe:d,decode:function(e){var r=d(e);if(r)return r;throw new Error("Non-".concat(t," character"))}}},o=i;let a=class{constructor(t,r,n){e._defineProperty(this,"name",void 0),e._defineProperty(this,"prefix",void 0),e._defineProperty(this,"baseEncode",void 0),this.name=t,this.prefix=r,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return"".concat(this.prefix).concat(this.baseEncode(e));throw Error("Unknown type, must be binary type")}},s=class{constructor(t,r,n){e._defineProperty(this,"name",void 0),e._defineProperty(this,"prefix",void 0),e._defineProperty(this,"baseDecode",void 0),e._defineProperty(this,"prefixCodePoint",void 0),this.name=t,this.prefix=r;var i=r.codePointAt(0);if(void 0===i)throw new Error("Invalid prefix character");this.prefixCodePoint=i,this.baseDecode=n}decode(e){if("string"==typeof e){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error("Unable to decode multibase string ".concat(JSON.stringify(e),", ").concat(this.name," decoder only supports inputs prefixed with ").concat(this.prefix));return this.baseDecode(e.slice(this.prefix.length))}throw Error("Can only multibase decode strings")}or(e){return c(this,e)}};class l{constructor(t){e._defineProperty(this,"decoders",void 0),this.decoders=t}or(e){return c(this,e)}decode(e){var t=e[0],r=this.decoders[t];if(null!=r)return r.decode(e);throw RangeError("Unable to decode multibase string ".concat(JSON.stringify(e),", only inputs prefixed with ").concat(Object.keys(this.decoders)," are supported"))}}function c(t,r){var n,i;return new l(e._objectSpread2(e._objectSpread2({},null!==(n=t.decoders)&&void 0!==n?n:{[t.prefix]:t}),null!==(i=r.decoders)&&void 0!==i?i:{[r.prefix]:r}))}class u{constructor(t,r,n,i){e._defineProperty(this,"name",void 0),e._defineProperty(this,"prefix",void 0),e._defineProperty(this,"baseEncode",void 0),e._defineProperty(this,"baseDecode",void 0),e._defineProperty(this,"encoder",void 0),e._defineProperty(this,"decoder",void 0),this.name=t,this.prefix=r,this.baseEncode=n,this.baseDecode=i,this.encoder=new a(t,r,n),this.decoder=new s(t,r,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}function d(e){var{name:t,prefix:r,encode:n,decode:i}=e;return new u(t,r,n,i)}function h(e){var{name:t,prefix:r,alphabet:i}=e,{encode:a,decode:s}=o(i,t);return d({prefix:r,name:t,encode:a,decode:e=>n(s(e))})}function p(e){var{name:t,prefix:r,bitsPerChar:n,alphabet:i}=e,o=function(e){for(var t={},r=0;r<e.length;++r)t[e[r]]=r;return t}(i);return d({prefix:r,name:t,encode:e=>function(e,t,r){for(var n="="===t[t.length-1],i=(1<<r)-1,o="",a=0,s=0,l=0;l<e.length;++l)for(s=s<<8|e[l],a+=8;a>r;)o+=t[i&s>>(a-=r)];if(0!==a&&(o+=t[i&s<<r-a]),n)for(;o.length*r&7;)o+="=";return o}(e,i,n),decode:e=>function(e,t,r,n){for(var i=e.length;"="===e[i-1];)--i;for(var o=new Uint8Array(i*r/8|0),a=0,s=0,l=0,c=0;c<i;++c){var u=t[e[c]];if(void 0===u)throw new SyntaxError("Non-".concat(n," character"));s=s<<r|u,(a+=r)>=8&&(a-=8,o[l++]=255&s>>a)}if(a>=r||255&s<<8-a)throw new SyntaxError("Unexpected end of data");return o}(e,o,n,t)})}var f=h({prefix:"9",name:"base10",alphabet:"0123456789"}),v=Object.freeze({__proto__:null,base10:f}),y=p({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),g=p({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4}),m=Object.freeze({__proto__:null,base16:y,base16upper:g}),w=p({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1}),b=Object.freeze({__proto__:null,base2:w}),_=Array.from("🚀🪐☄🛰🌌🌑🌒🌓🌔🌕🌖🌗🌘🌍🌏🌎🐉☀💻🖥💾💿😂❤😍🤣😊🙏💕😭😘👍😅👏😁🔥🥰💔💖💙😢🤔😆🙄💪😉☺👌🤗💜😔😎😇🌹🤦🎉💞✌✨🤷😱😌🌸🙌😋💗💚😏💛🙂💓🤩😄😀🖤😃💯🙈👇🎶😒🤭❣😜💋👀😪😑💥🙋😞😩😡🤪👊🥳😥🤤👉💃😳✋😚😝😴🌟😬🙃🍀🌷😻😓⭐✅🥺🌈😈🤘💦✔😣🏃💐☹🎊💘😠☝😕🌺🎂🌻😐🖕💝🙊😹🗣💫💀👑🎵🤞😛🔴😤🌼😫⚽🤙☕🏆🤫👈😮🙆🍻🍃🐶💁😲🌿🧡🎁⚡🌞🎈❌✊👋😰🤨😶🤝🚶💰🍓💢🤟🙁🚨💨🤬✈🎀🍺🤓😙💟🌱😖👶🥴▶➡❓💎💸⬇😨🌚🦋😷🕺⚠🙅😟😵👎🤲🤠🤧📌🔵💅🧐🐾🍒😗🤑🌊🤯🐷☎💧😯💆👆🎤🙇🍑❄🌴💣🐸💌📍🥀🤢👅💡💩👐📸👻🤐🤮🎼🥵🚩🍎🍊👼💍📣🥂"),S=_.reduce(((e,t,r)=>(e[r]=t,e)),[]),P=_.reduce(((e,t,r)=>{var n=t.codePointAt(0);if(null==n)throw new Error("Invalid character: ".concat(t));return e[n]=r,e}),[]);var E=d({prefix:"🚀",name:"base256emoji",encode:function(e){return e.reduce(((e,t)=>e+=S[t]),"")},decode:function(e){var t=[];for(var r of e){var n=r.codePointAt(0);if(null==n)throw new Error("Invalid character: ".concat(r));var i=P[n];if(null==i)throw new Error("Non-base256emoji character: ".concat(r));t.push(i)}return new Uint8Array(t)}}),A=Object.freeze({__proto__:null,base256emoji:E}),k=p({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),x=p({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),T=p({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),I=p({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),C=p({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),B=p({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),N=p({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),D=p({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),G=p({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5}),R=Object.freeze({__proto__:null,base32:k,base32hex:C,base32hexpad:N,base32hexpadupper:D,base32hexupper:B,base32pad:T,base32padupper:I,base32upper:x,base32z:G}),O=h({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),L=h({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"}),M=Object.freeze({__proto__:null,base36:O,base36upper:L}),j=h({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),F=h({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"}),U=Object.freeze({__proto__:null,base58btc:j,base58flickr:F}),z=p({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),V=p({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),q=p({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),H=p({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6}),K=Object.freeze({__proto__:null,base64:z,base64pad:V,base64url:q,base64urlpad:H}),W=p({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3}),Q=Object.freeze({__proto__:null,base8:W}),Y=d({prefix:"\0",name:"identity",encode:e=>{return t=e,(new TextDecoder).decode(t);var t},decode:e=>function(e){return(new TextEncoder).encode(e)}(e)}),J=Object.freeze({__proto__:null,identity:Y}),Z=new TextEncoder,$=new TextDecoder,X=512;function ee(e){return JSON.parse($.decode(e))}var te=Object.freeze({__proto__:null,code:512,decode:ee,encode:function(e){return Z.encode(JSON.stringify(e))},name:"json"}),re=85;var ne=Object.freeze({__proto__:null,code:re,decode:function(e){return n(e)},encode:function(e){return n(e)},name:"raw"}),ie=function e(t,r,n){r=r||[];var i=n=n||0;for(;t>=se;)r[n++]=255&t|oe,t/=128;for(;t&ae;)r[n++]=255&t|oe,t>>>=7;return r[n]=0|t,e.bytes=n-i+1,r},oe=128,ae=-128,se=Math.pow(2,31);var le=function e(t,r){var n,i=0,o=0,a=r=r||0,s=t.length;do{if(a>=s)throw e.bytes=0,new RangeError("Could not decode varint");n=t[a++],i+=o<28?(n&ue)<<o:(n&ue)*Math.pow(2,o),o+=7}while(n>=ce);return e.bytes=a-r,i},ce=128,ue=127;var de=Math.pow(2,7),he=Math.pow(2,14),pe=Math.pow(2,21),fe=Math.pow(2,28),ve=Math.pow(2,35),ye=Math.pow(2,42),ge=Math.pow(2,49),me=Math.pow(2,56),we=Math.pow(2,63),be={encode:ie,decode:le,encodingLength:function(e){return e<de?1:e<he?2:e<pe?3:e<fe?4:e<ve?5:e<ye?6:e<ge?7:e<me?8:e<we?9:10}};function _e(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return[be.decode(e,t),be.decode.bytes]}function Se(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return be.encode(e,t,r),t}function Pe(e){return be.encodingLength(e)}function Ee(e,t){var r=t.byteLength,n=Pe(e),i=n+Pe(r),o=new Uint8Array(i+r);return Se(e,o,0),Se(r,o,n),o.set(t,i),new ke(e,r,t,o)}function Ae(e){var t=n(e),[r,i]=_e(t),[o,a]=_e(t.subarray(i)),s=t.subarray(i+a);if(s.byteLength!==o)throw new Error("Incorrect length");return new ke(r,o,s,t)}class ke{constructor(t,r,n,i){e._defineProperty(this,"code",void 0),e._defineProperty(this,"size",void 0),e._defineProperty(this,"digest",void 0),e._defineProperty(this,"bytes",void 0),this.code=t,this.size=r,this.digest=n,this.bytes=i}}var xe=n;var Te={code:0,name:"identity",encode:xe,digest:function(e){return Ee(0,xe(e))}},Ie=Object.freeze({__proto__:null,identity:Te});function Ce(e){var{name:t,code:r,encode:n}=e;return new Be(t,r,n)}class Be{constructor(t,r,n){e._defineProperty(this,"name",void 0),e._defineProperty(this,"code",void 0),e._defineProperty(this,"encode",void 0),this.name=t,this.code=r,this.encode=n}digest(e){if(e instanceof Uint8Array){var t=this.encode(e);return t instanceof Uint8Array?Ee(this.code,t):t.then((e=>Ee(this.code,e)))}throw Error("Unknown type, must be binary type")}}function Ne(t){return function(){var r=e._asyncToGenerator((function*(e){return new Uint8Array(yield crypto.subtle.digest(t,e))}));return function(e){return r.apply(this,arguments)}}()}var De=Ce({name:"sha2-256",code:18,encode:Ne("SHA-256")}),Ge=Ce({name:"sha2-512",code:19,encode:Ne("SHA-512")}),Re=Object.freeze({__proto__:null,sha256:De,sha512:Ge});function Oe(e,t){var{bytes:r,version:n}=e;return 0===n?function(e,t,r){var{prefix:n}=r;if(n!==j.prefix)throw Error("Cannot string encode V0 in ".concat(r.name," encoding"));var i=t.get(n);if(null==i){var o=r.encode(e).slice(1);return t.set(n,o),o}return i}(r,Me(e),null!=t?t:j.encoder):function(e,t,r){var{prefix:n}=r,i=t.get(n);if(null==i){var o=r.encode(e);return t.set(n,o),o}return i}(r,Me(e),null!=t?t:k.encoder)}var Le=new WeakMap;function Me(e){var t=Le.get(e);if(null==t){var r=new Map;return Le.set(e,r),r}return t}class je{constructor(t,r,n,i){e._defineProperty(this,"code",void 0),e._defineProperty(this,"version",void 0),e._defineProperty(this,"multihash",void 0),e._defineProperty(this,"bytes",void 0),e._defineProperty(this,"/",void 0),e._defineProperty(this,Symbol.toStringTag,"CID"),this.code=r,this.version=t,this.multihash=n,this.bytes=i,this["/"]=i}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:var{code:e,multihash:t}=this;if(e!==Fe)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Ue)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return je.createV0(t);default:throw Error("Can not convert CID version ".concat(this.version," to version 0. This is a bug please report"))}}toV1(){switch(this.version){case 0:var{code:e,digest:t}=this.multihash,r=Ee(e,t);return je.createV1(this.code,r);case 1:return this;default:throw Error("Can not convert CID version ".concat(this.version," to version 1. This is a bug please report"))}}equals(e){return je.equals(this,e)}static equals(e,t){var r=t;return null!=r&&e.code===r.code&&e.version===r.version&&function(e,t){if(e===t)return!0;var r=t;return e.code===r.code&&e.size===r.size&&r.bytes instanceof Uint8Array&&function(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(var r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}(e.bytes,r.bytes)}(e.multihash,r.multihash)}toString(e){return Oe(this,e)}toJSON(){return{"/":Oe(this)}}link(){return this}[Symbol.for("nodejs.util.inspect.custom")](){return"CID(".concat(this.toString(),")")}static asCID(e){if(null==e)return null;var t=e;if(t instanceof je)return t;if(null!=t["/"]&&t["/"]===t.bytes||t.asCID===t){var{version:r,code:n,multihash:i,bytes:o}=t;return new je(r,n,i,null!=o?o:ze(r,n,i.bytes))}if(!0===t[Ve]){var{version:a,multihash:s,code:l}=t,c=Ae(s);return je.create(a,l,c)}return null}static create(e,t,r){if("number"!=typeof t)throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:if(t!==Fe)throw new Error("Version 0 CID must use dag-pb (code: ".concat(Fe,") block encoding"));return new je(e,t,r,r.bytes);case 1:var n=ze(e,t,r.bytes);return new je(e,t,r,n);default:throw new Error("Invalid version")}}static createV0(e){return je.create(0,Fe,e)}static createV1(e,t){return je.create(1,e,t)}static decode(e){var[t,r]=je.decodeFirst(e);if(0!==r.length)throw new Error("Incorrect length");return t}static decodeFirst(e){var t=je.inspectBytes(e),r=t.size-t.multihashSize,i=n(e.subarray(r,r+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");var o=i.subarray(t.multihashSize-t.digestSize),a=new ke(t.multihashCode,t.digestSize,o,i);return[0===t.version?je.createV0(a):je.createV1(t.codec,a),e.subarray(t.size)]}static inspectBytes(e){var t=0,r=()=>{var[r,n]=_e(e.subarray(t));return t+=n,r},n=r(),i=Fe;if(18===n?(n=0,t=0):i=r(),0!==n&&1!==n)throw new RangeError("Invalid CID version ".concat(n));var o=t,a=r(),s=r(),l=t+s;return{version:n,codec:i,multihashCode:a,digestSize:s,multihashSize:l-o,size:l}}static parse(e,t){var[r,n]=function(e,t){switch(e[0]){case"Q":var r=null!=t?t:j;return[j.prefix,r.decode("".concat(j.prefix).concat(e))];case j.prefix:var n=null!=t?t:j;return[j.prefix,n.decode(e)];case k.prefix:var i=null!=t?t:k;return[k.prefix,i.decode(e)];case O.prefix:var o=null!=t?t:O;return[O.prefix,o.decode(e)];default:if(null==t)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[e[0],t.decode(e)]}}(e,t),i=je.decode(n);if(0===i.version&&"Q"!==e[0])throw Error("Version 0 CID string must not include multibase prefix");return Me(i).set(r,e),i}}var Fe=112,Ue=18;function ze(e,t,r){var n=Pe(e),i=n+Pe(t),o=new Uint8Array(i+r.byteLength);return Se(e,o,0),Se(t,o,n),o.set(r,i),o}var Ve=Symbol.for("@ipld/js-cid/CID"),qe=e._objectSpread2(e._objectSpread2(e._objectSpread2(e._objectSpread2(e._objectSpread2(e._objectSpread2(e._objectSpread2(e._objectSpread2(e._objectSpread2(e._objectSpread2({},J),b),Q),v),m),R),M),U),K),A);function He(){return new Uint8Array(arguments.length>0&&void 0!==arguments[0]?arguments[0]:0)}function Ke(){return new Uint8Array(arguments.length>0&&void 0!==arguments[0]?arguments[0]:0)}function We(e,t,r,n){return{name:e,prefix:t,encoder:{name:e,prefix:t,encode:r},decoder:{decode:n}}}e._objectSpread2(e._objectSpread2({},Re),Ie);var Qe=We("utf8","u",(e=>"u"+new TextDecoder("utf8").decode(e)),(e=>(new TextEncoder).encode(e.substring(1)))),Ye=We("ascii","a",(e=>{for(var t="a",r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return t}),(e=>{for(var t=Ke((e=e.substring(1)).length),r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t})),Je=e._objectSpread2({utf8:Qe,"utf-8":Qe,hex:qe.base16,latin1:Ye,ascii:Ye,binary:Ye},qe);function Ze(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"utf8",r=Je[t];if(null==r)throw new Error('Unsupported encoding "'.concat(t,'"'));return r.encoder.encode(e).substring(1)}var $e=Object.freeze({__proto__:null,toString:Ze});let Xe=class extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidMultiaddrError")}};e._defineProperty(Xe,"name","InvalidMultiaddrError");class et extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","ValidationError")}}e._defineProperty(et,"name","ValidationError");let tt=class extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidParametersError")}};e._defineProperty(tt,"name","InvalidParametersError");class rt extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","UnknownProtocolError")}}function nt(e,t){if(e===t)return!0;if(e.byteLength!==t.byteLength)return!1;for(var r=0;r<e.byteLength;r++)if(e[r]!==t[r])return!1;return!0}e._defineProperty(rt,"name","UnknownProtocolError");var it=Object.freeze({__proto__:null,equals:nt});function ot(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"utf8",r=Je[t];if(null==r)throw new Error('Unsupported encoding "'.concat(t,'"'));return r.decoder.decode("".concat(r.prefix).concat(e))}var at=Object.freeze({__proto__:null,fromString:ot}),st=Math.pow(2,7),lt=Math.pow(2,14),ct=Math.pow(2,21),ut=Math.pow(2,28),dt=Math.pow(2,35),ht=Math.pow(2,42),pt=Math.pow(2,49),ft=128,vt=127;function yt(e){if(e<st)return 1;if(e<lt)return 2;if(e<ct)return 3;if(e<ut)return 4;if(e<dt)return 5;if(e<ht)return 6;if(e<pt)return 7;if(null!=Number.MAX_SAFE_INTEGER&&e>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function gt(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;switch(yt(e)){case 8:t[r++]=255&e|ft,e/=128;case 7:t[r++]=255&e|ft,e/=128;case 6:t[r++]=255&e|ft,e/=128;case 5:t[r++]=255&e|ft,e/=128;case 4:t[r++]=255&e|ft,e>>>=7;case 3:t[r++]=255&e|ft,e>>>=7;case 2:t[r++]=255&e|ft,e>>>=7;case 1:t[r++]=255&e,e>>>=7;break;default:throw new Error("unreachable")}return t}function mt(e,t){var r=e[t],n=0;if(n+=r&vt,r<ft)return n;if(n+=((r=e[t+1])&vt)<<7,r<ft)return n;if(n+=((r=e[t+2])&vt)<<14,r<ft)return n;if(n+=((r=e[t+3])&vt)<<21,r<ft)return n;if(n+=((r=e[t+4])&vt)*ut,r<ft)return n;if(n+=((r=e[t+5])&vt)*dt,r<ft)return n;if(n+=((r=e[t+6])&vt)*ht,r<ft)return n;if(n+=((r=e[t+7])&vt)*pt,r<ft)return n;throw new RangeError("Could not decode varint")}function wt(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;return null==t&&(t=Ke(yt(e))),t instanceof Uint8Array?gt(e,t,r):function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;switch(yt(e)){case 8:t.set(r++,255&e|ft),e/=128;case 7:t.set(r++,255&e|ft),e/=128;case 6:t.set(r++,255&e|ft),e/=128;case 5:t.set(r++,255&e|ft),e/=128;case 4:t.set(r++,255&e|ft),e>>>=7;case 3:t.set(r++,255&e|ft),e>>>=7;case 2:t.set(r++,255&e|ft),e>>>=7;case 1:t.set(r++,255&e),e>>>=7;break;default:throw new Error("unreachable")}return t}(e,t,r)}function bt(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return e instanceof Uint8Array?mt(e,t):function(e,t){var r=e.get(t),n=0;if(n+=r&vt,r<ft)return n;if(n+=((r=e.get(t+1))&vt)<<7,r<ft)return n;if(n+=((r=e.get(t+2))&vt)<<14,r<ft)return n;if(n+=((r=e.get(t+3))&vt)<<21,r<ft)return n;if(n+=((r=e.get(t+4))&vt)*ut,r<ft)return n;if(n+=((r=e.get(t+5))&vt)*dt,r<ft)return n;if(n+=((r=e.get(t+6))&vt)*ht,r<ft)return n;if(n+=((r=e.get(t+7))&vt)*pt,r<ft)return n;throw new RangeError("Could not decode varint")}(e,t)}function _t(e,t){null==t&&(t=e.reduce(((e,t)=>e+t.length),0));var r=Ke(t),n=0;for(var i of e)r.set(i,n),n+=i.length;return r}var St=Object.freeze({__proto__:null,concat:_t});var Pt=new class{constructor(){e._defineProperty(this,"index",0),e._defineProperty(this,"input","")}new(e){return this.index=0,this.input=e,this}readAtomically(e){var t=this.index,r=e();return void 0===r&&(this.index=t),r}parseWith(e){var t=e();if(this.index===this.input.length)return t}peekChar(){if(!(this.index>=this.input.length))return this.input[this.index]}readChar(){if(!(this.index>=this.input.length))return this.input[this.index++]}readGivenChar(e){return this.readAtomically((()=>{var t=this.readChar();if(t===e)return t}))}readSeparator(e,t,r){return this.readAtomically((()=>{if(!(t>0&&void 0===this.readGivenChar(e)))return r()}))}readNumber(e,t,r,n){return this.readAtomically((()=>{var i=0,o=0,a=this.peekChar();if(void 0!==a){for(var s="0"===a,l=2**(8*n)-1;;){var c=this.readAtomically((()=>{var t=this.readChar();if(void 0!==t){var r=Number.parseInt(t,e);if(!Number.isNaN(r))return r}}));if(void 0===c)break;if(i*=e,(i+=c)>l)return;if(o+=1,void 0!==t&&o>t)return}return 0===o||!r&&s&&o>1?void 0:i}}))}readIPv4Addr(){return this.readAtomically((()=>{for(var e=new Uint8Array(4),t=0;t<e.length;t++){var r=this.readSeparator(".",t,(()=>this.readNumber(10,3,!1,1)));if(void 0===r)return;e[t]=r}return e}))}readIPv6Addr(){var e=e=>{for(var t=0;t<e.length/2;t++){var r=2*t;if(t<e.length-3){var n=this.readSeparator(":",t,(()=>this.readIPv4Addr()));if(void 0!==n)return e[r]=n[0],e[r+1]=n[1],e[r+2]=n[2],e[r+3]=n[3],[r+4,!0]}var i=this.readSeparator(":",t,(()=>this.readNumber(16,4,!0,2)));if(void 0===i)return[r,!1];e[r]=i>>8,e[r+1]=255&i}return[e.length,!1]};return this.readAtomically((()=>{var t=new Uint8Array(16),[r,n]=e(t);if(16===r)return t;if(!n&&void 0!==this.readGivenChar(":")&&void 0!==this.readGivenChar(":")){var i=new Uint8Array(14),o=16-(r+2),[a]=e(i.subarray(0,o));return t.set(i.subarray(0,a),16-a),t}}))}readIPAddr(){var e;return null!==(e=this.readIPv4Addr())&&void 0!==e?e:this.readIPv6Addr()}};function Et(e){if(!(e.length>15))return Pt.new(e).parseWith((()=>Pt.readIPv4Addr()))}function At(e){if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45))return Pt.new(e).parseWith((()=>Pt.readIPv6Addr()))}function kt(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];if(e.includes("%")&&(e=e.split("%")[0]),!(e.length>45)){var r=Pt.new(e).parseWith((()=>Pt.readIPAddr()));if(r)return t&&4===r.length?Uint8Array.from([0,0,0,0,0,0,0,0,0,0,255,255,r[0],r[1],r[2],r[3]]):r}}function xt(e){return Boolean(Et(e))}function Tt(e){return Boolean(At(e))}function It(e){return t=>Ze(t,e)}function Ct(e){return t=>ot(t,e)}function Bt(e){return new DataView(e.buffer).getUint16(e.byteOffset).toString()}function Nt(e){var t=new ArrayBuffer(2);return new DataView(t).setUint16(0,"string"==typeof e?parseInt(e):e),new Uint8Array(t)}function Dt(e){var t=e.subarray(0,e.length-2),r=e.subarray(e.length-2),n=Ze(t,"base32"),i=Bt(r);return"".concat(n,":").concat(i)}var Gt=function(e){e=e.toString().trim();var t=new Uint8Array(4);return e.split(/\./g).forEach(((e,r)=>{var n=parseInt(e,10);if(isNaN(n)||n<0||n>255)throw new Xe("Invalid byte value in IP address");t[r]=n})),t};var Rt,Ot=Object.values(qe).map((e=>e.decoder)),Lt=(Rt=Ot[0].or(Ot[1]),Ot.slice(2).forEach((e=>Rt=Rt.or(e))),Rt);var Mt,jt=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return e=>{for(var r of t)r(e)}}((function(e){if(parseInt(e).toString()!==e)throw new et("Value must be an integer")}),(function(e){if(e<0)throw new et("Value must be a positive integer, or zero")}),(Mt=65535,e=>{if(e>Mt)throw new et("Value must be smaller than or equal to ".concat(Mt))})),Ft=-1;var Ut=new class{constructor(){e._defineProperty(this,"protocolsByCode",new Map),e._defineProperty(this,"protocolsByName",new Map)}getProtocol(e){var t;if(null==(t="string"==typeof e?this.protocolsByName.get(e):this.protocolsByCode.get(e)))throw new rt("Protocol ".concat(e," was unknown"));return t}addProtocol(e){var t;this.protocolsByCode.set(e.code,e),this.protocolsByName.set(e.name,e),null===(t=e.aliases)||void 0===t||t.forEach((t=>{this.protocolsByName.set(t,e)}))}removeProtocol(e){var t,r=this.protocolsByCode.get(e);null!=r&&(this.protocolsByCode.delete(r.code),this.protocolsByName.delete(r.name),null===(t=r.aliases)||void 0===t||t.forEach((e=>{this.protocolsByName.delete(e)})))}},zt=[{code:4,name:"ip4",size:32,valueToBytes:Gt,bytesToValue:function(e){if(4!==e.byteLength)throw new Xe("IPv4 address was incorrect length");for(var t=[],r=0;r<e.byteLength;r++)t.push(e[r]);return t.join(".")},validate:e=>{if(!xt(e))throw new et('Invalid IPv4 address "'.concat(e,'"'))}},{code:6,name:"tcp",size:16,valueToBytes:Nt,bytesToValue:Bt,validate:jt},{code:273,name:"udp",size:16,valueToBytes:Nt,bytesToValue:Bt,validate:jt},{code:33,name:"dccp",size:16,valueToBytes:Nt,bytesToValue:Bt,validate:jt},{code:41,name:"ip6",size:128,valueToBytes:function(e){var t,r=0,n=(e=e.toString().trim()).split(":",8);for(t=0;t<n.length;t++){var i=void 0;xt(n[t])&&(i=Gt(n[t]),n[t]=Ze(i.subarray(0,2),"base16")),null!=i&&++t<8&&n.splice(t,0,Ze(i.subarray(2,4),"base16"))}if(""===n[0])for(;n.length<8;)n.unshift("0");else if(""===n[n.length-1])for(;n.length<8;)n.push("0");else if(n.length<8){for(t=0;t<n.length&&""!==n[t];t++);var o=[t,1];for(t=9-n.length;t>0;t--)o.push("0");n.splice.apply(n,o)}var a=new Uint8Array(r+16);for(t=0;t<n.length;t++){""===n[t]&&(n[t]="0");var s=parseInt(n[t],16);if(isNaN(s)||s<0||s>65535)throw new Xe("Invalid byte value in IP address");a[r++]=s>>8&255,a[r++]=255&s}return a},bytesToValue:function(e){if(16!==e.byteLength)throw new Xe("IPv6 address was incorrect length");for(var t=[],r=0;r<e.byteLength;r+=2){var n=e[r],i=e[r+1],o="".concat(n.toString(16).padStart(2,"0")).concat(i.toString(16).padStart(2,"0"));t.push(o)}var a=t.join(":");try{var s=new URL("http://[".concat(a,"]"));return s.hostname.substring(1,s.hostname.length-1)}catch(e){throw new Xe('Invalid IPv6 address "'.concat(a,'"'))}},stringToValue:function(e){try{var t=new URL("http://[".concat(e,"]"));return t.hostname.substring(1,t.hostname.length-1)}catch(t){throw new Xe('Invalid IPv6 address "'.concat(e,'"'))}},validate:e=>{if(!Tt(e))throw new et('Invalid IPv6 address "'.concat(e,'"'))}},{code:42,name:"ip6zone",size:Ft},{code:43,name:"ipcidr",size:8,bytesToValue:It("base10"),valueToBytes:Ct("base10")},{code:53,name:"dns",size:Ft,resolvable:!0},{code:54,name:"dns4",size:Ft,resolvable:!0},{code:55,name:"dns6",size:Ft,resolvable:!0},{code:56,name:"dnsaddr",size:Ft,resolvable:!0},{code:132,name:"sctp",size:16,valueToBytes:Nt,bytesToValue:Bt,validate:jt},{code:301,name:"udt"},{code:302,name:"utp"},{code:400,name:"unix",size:Ft,path:!0,stringToValue:e=>decodeURIComponent(e),valueToString:e=>encodeURIComponent(e)},{code:421,name:"p2p",aliases:["ipfs"],size:Ft,bytesToValue:It("base58btc"),valueToBytes:e=>e.startsWith("Q")||e.startsWith("1")?Ct("base58btc")(e):je.parse(e).multihash.bytes},{code:444,name:"onion",size:96,bytesToValue:Dt,valueToBytes:function(e){var t=e.split(":");if(2!==t.length)throw new Error("failed to parse onion addr: [\"'".concat(t.join('", "'),"'\"]' does not contain a port number"));if(16!==t[0].length)throw new Error("failed to parse onion addr: ".concat(t[0]," not a Tor onion address."));var r=ot(t[0],"base32"),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");var i=Nt(n);return _t([r,i],r.length+i.length)}},{code:445,name:"onion3",size:296,bytesToValue:Dt,valueToBytes:function(e){var t=e.split(":");if(2!==t.length)throw new Error("failed to parse onion addr: [\"'".concat(t.join('", "'),"'\"]' does not contain a port number"));if(56!==t[0].length)throw new Error("failed to parse onion addr: ".concat(t[0]," not a Tor onion3 address."));var r=k.decode("b".concat(t[0])),n=parseInt(t[1],10);if(n<1||n>65536)throw new Error("Port number is not in range(1, 65536)");var i=Nt(n);return _t([r,i],r.length+i.length)}},{code:446,name:"garlic64",size:Ft},{code:447,name:"garlic32",size:Ft},{code:448,name:"tls"},{code:449,name:"sni",size:Ft},{code:454,name:"noise"},{code:460,name:"quic"},{code:461,name:"quic-v1"},{code:465,name:"webtransport"},{code:466,name:"certhash",size:Ft,bytesToValue:function(e){return t=>e.encoder.encode(t)}(q),valueToBytes:function(e){return Lt.decode(e)}},{code:480,name:"http"},{code:481,name:"http-path",size:Ft,stringToValue:e=>"/".concat(decodeURIComponent(e)),valueToString:e=>encodeURIComponent(e.substring(1))},{code:443,name:"https"},{code:477,name:"ws"},{code:478,name:"wss"},{code:479,name:"p2p-websocket-star"},{code:277,name:"p2p-stardust"},{code:275,name:"p2p-webrtc-star"},{code:276,name:"p2p-webrtc-direct"},{code:280,name:"webrtc-direct"},{code:281,name:"webrtc"},{code:290,name:"p2p-circuit"},{code:777,name:"memory",size:Ft}];function Vt(e,t,r){return null==e.size||0===e.size?0:e.size>0?e.size/8:bt(t,r)}zt.forEach((e=>{Ut.addProtocol(e)}));var qt=Symbol.for("nodejs.util.inspect.custom"),Ht=Symbol.for("@multiformats/multiaddr"),Kt=[53,54,55,56];class Wt extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No available resolver"),this.name="NoAvailableResolverError"}}function Qt(e){if(null==e&&(e="/"),ar(e))return e.getComponents();if(e instanceof Uint8Array)return function(e){for(var t=[],r=0;r<e.length;){var n=bt(e,r),i=Ut.getProtocol(n),o=yt(n),a=Vt(i,e,r+o),s=0;a>0&&i.size===Ft&&(s=yt(a));var l=o+s+a,c={code:n,name:i.name,bytes:e.subarray(r,r+l)};if(a>0){var u,d,h=r+o+s,p=e.subarray(h,h+a);c.value=null!==(u=null===(d=i.bytesToValue)||void 0===d?void 0:d.call(i,p))&&void 0!==u?u:Ze(p)}t.push(c),r+=l}return t}(e);if("string"==typeof e)return""===(e=e.replace(/\/(\/)+/,"/").replace(/(\/)+$/,""))&&(e="/"),function(e){if("/"!==e.charAt(0))throw new Xe('String multiaddr must start with "/"');for(var t=[],r="protocol",n="",i="",o=1;o<e.length;o++){var a=e.charAt(o);"/"!==a&&("protocol"===r?i+=e.charAt(o):n+=e.charAt(o));var s=o===e.length-1;if("/"===a||s){var l=Ut.getProtocol(i);if("protocol"===r){if(null==l.size||0===l.size){t.push({code:l.code,name:l.name}),n="",i="",r="protocol";continue}if(s)throw new Xe("Component ".concat(i," was missing value"));r="value"}else if("value"===r){var c={code:l.code,name:l.name};if(null!=l.size&&0!==l.size){var u,d;if(""===n)throw new Xe("Component ".concat(i," was missing value"));c.value=null!==(u=null===(d=l.stringToValue)||void 0===d?void 0:d.call(l,n))&&void 0!==u?u:n}t.push(c),n="",i="",r="protocol"}}}if(""!==i&&""!==n)throw new Xe("Incomplete multiaddr");return t}(e);if(Array.isArray(e))return e;throw new Xe("Must be a string, Uint8Array, Component[], or another Multiaddr")}var Yt=new WeakMap,Jt=new WeakMap,Zt=new WeakMap;class $t{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/",r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,Ht,!0),e._classPrivateFieldInitSpec(this,Yt,void 0),e._classPrivateFieldInitSpec(this,Jt,void 0),e._classPrivateFieldInitSpec(this,Zt,void 0),e._classPrivateFieldSet2(Yt,this,Qt(t)),!1!==r.validate&&function(e){e.getComponents().forEach((e=>{var t,r=Ut.getProtocol(e.code);null!=e.value&&(null===(t=r.validate)||void 0===t||t.call(r,e.value))}))}(this)}get bytes(){return null==e._classPrivateFieldGet2(Zt,this)&&e._classPrivateFieldSet2(Zt,this,function(e){var t=0,r=[];for(var n of e){if(null==n.bytes){var i,o,a=Ut.getProtocol(n.code),s=yt(n.code),l=void 0,c=0,u=0;null!=n.value&&(c=(l=null!==(i=null===(o=a.valueToBytes)||void 0===o?void 0:o.call(a,n.value))&&void 0!==i?i:ot(n.value)).byteLength,a.size===Ft&&(u=yt(c)));var d=new Uint8Array(s+u+c),h=0;gt(n.code,d,h),h+=s,null!=l&&(a.size===Ft&&(gt(c,d,h),h+=u),d.set(l,h)),n.bytes=d}r.push(n.bytes),t+=n.bytes.byteLength}return _t(r,t)}(e._classPrivateFieldGet2(Yt,this))),e._classPrivateFieldGet2(Zt,this)}toString(){var t;return null==e._classPrivateFieldGet2(Jt,this)&&e._classPrivateFieldSet2(Jt,this,(t=e._classPrivateFieldGet2(Yt,this),"/".concat(t.flatMap((e=>{var t,r;if(null==e.value)return e.name;var n=Ut.getProtocol(e.code);if(null==n)throw new Xe("Unknown protocol code ".concat(e.code));return[e.name,null!==(t=null===(r=n.valueToString)||void 0===r?void 0:r.call(n,e.value))&&void 0!==t?t:e.value]})).join("/")))),e._classPrivateFieldGet2(Jt,this)}toJSON(){return this.toString()}toOptions(){var t,r,n,i,o="";for(var{code:a,name:s,value:l}of e._classPrivateFieldGet2(Yt,this))42===a&&(o="%".concat(null!=l?l:"")),Kt.includes(a)&&(r="tcp",i=443,n="".concat(null!=l?l:"").concat(o),t=55===a?6:4),6!==a&&273!==a||(r="tcp"===s?"tcp":"udp",i=parseInt(null!=l?l:"")),4!==a&&41!==a||(r="tcp",n="".concat(null!=l?l:"").concat(o),t=41===a?6:4);if(null==t||null==r||null==n||null==i)throw new Error('multiaddr must have a valid format: "/{ip4, ip6, dns4, dns6, dnsaddr}/{address}/{tcp, udp}/{port}".');return{family:t,host:n,transport:r,port:i}}getComponents(){return[...e._classPrivateFieldGet2(Yt,this)]}protos(){return e._classPrivateFieldGet2(Yt,this).map((e=>{var t,{code:r,value:n}=e,i=Ut.getProtocol(r);return{code:r,size:null!==(t=i.size)&&void 0!==t?t:0,name:i.name,resolvable:Boolean(i.resolvable),path:Boolean(i.path)}}))}protoCodes(){return e._classPrivateFieldGet2(Yt,this).map((e=>{var{code:t}=e;return t}))}protoNames(){return e._classPrivateFieldGet2(Yt,this).map((e=>{var{name:t}=e;return t}))}tuples(){return e._classPrivateFieldGet2(Yt,this).map((e=>{var{code:t,value:r}=e;if(null==r)return[t];var n,i,o=Ut.getProtocol(t),a=[t];null!=r&&a.push(null!==(n=null===(i=o.valueToBytes)||void 0===i?void 0:i.call(o,r))&&void 0!==n?n:ot(r));return a}))}stringTuples(){return e._classPrivateFieldGet2(Yt,this).map((e=>{var{code:t,value:r}=e;return null==r?[t]:[t,r]}))}encapsulate(t){var r=new $t(t);return new $t([...e._classPrivateFieldGet2(Yt,this),...r.getComponents()],{validate:!1})}decapsulate(e){var t=e.toString(),r=this.toString(),n=r.lastIndexOf(t);if(n<0)throw new tt("Address ".concat(this.toString()," does not contain subaddress: ").concat(e.toString()));return new $t(r.slice(0,n),{validate:!1})}decapsulateCode(t){for(var r,n=e._classPrivateFieldGet2(Yt,this).length-1;n>-1;n--)if(e._classPrivateFieldGet2(Yt,this)[n].code===t){r=n;break}return new $t(e._classPrivateFieldGet2(Yt,this).slice(0,r),{validate:!1})}getPeerId(){try{var t=[];e._classPrivateFieldGet2(Yt,this).forEach((e=>{var{code:r,value:n}=e;421===r&&t.push([r,n]),290===r&&(t=[])}));var r=t.pop();if(null!=(null==r?void 0:r[1])){var n=r[1];return"Q"===n[0]||"1"===n[0]?Ze(j.decode("z".concat(n)),"base58btc"):Ze(je.parse(n).multihash.bytes,"base58btc")}return null}catch(e){return null}}getPath(){for(var t of e._classPrivateFieldGet2(Yt,this)){var r;if(Ut.getProtocol(t.code).path)return null!==(r=t.value)&&void 0!==r?r:null}return null}equals(e){return nt(this.bytes,e.bytes)}resolve(t){var r=this;return e._asyncToGenerator((function*(){var e=r.protos().find((e=>e.resolvable));if(null==e)return[r];var n=or.get(e.name);if(null==n)throw new Wt("no available resolver for ".concat(e.name));return(yield n(r,t)).map((e=>sr(e)))}))()}nodeAddress(){var e=this.toOptions();if("tcp"!==e.transport&&"udp"!==e.transport)throw new Error('multiaddr must have a valid format - no protocol with name: "'.concat(e.transport,'". Must have a valid transport protocol: "{tcp, udp}"'));return{family:e.family,address:e.host,port:e.port}}isThinWaistAddress(){return 2===e._classPrivateFieldGet2(Yt,this).length&&((4===e._classPrivateFieldGet2(Yt,this)[0].code||41===e._classPrivateFieldGet2(Yt,this)[0].code)&&(6===e._classPrivateFieldGet2(Yt,this)[1].code||273===e._classPrivateFieldGet2(Yt,this)[1].code))}[qt](){return"Multiaddr(".concat(this.toString(),")")}}var Xt=4,er=16,tr=new Uint8Array([0,0,0,0,0,0,0,0,0,0,255,255]);function rr(e,t){t.length===er&&e.length===Xt&&function(e,t,r){var n=0;for(var i of e)if(!(n<t)){if(n>r)break;if(255!==i)return!1;n++}return!0}(t,0,11)&&(t=t.slice(12)),t.length===Xt&&e.length===er&&function(e,t,r,n){var i=0;for(var o of e)if(!(i<r)){if(i>n)break;if(o!==t[i])return!1;i++}return!0}(e,tr,0,11)&&(e=e.slice(12));var r=e.length;if(r!=t.length)throw new Error("Failed to mask ip");for(var n=new Uint8Array(r),i=0;i<r;i++)n[i]=e[i]&t[i];return n}function nr(e,t){if(t!==8*Xt&&t!==8*er)throw new Error("Invalid CIDR mask");if(e<0||e>t)throw new Error("Invalid CIDR mask");for(var r=t/8,n=new Uint8Array(r),i=0;i<r;i++)e>=8?(n[i]=255,e-=8):(n[i]=255-(255>>e),e=0);return n}class ir{constructor(e,t){if(null==t)({network:this.network,mask:this.mask}=function(e){var[t,r]=e.split("/");if(!t||!r)throw new Error("Failed to parse given CIDR: "+e);var n=Xt,i=Et(t);if(null==i&&(n=er,null==(i=At(t))))throw new Error("Failed to parse given CIDR: "+e);var o=parseInt(r,10);if(Number.isNaN(o)||String(o).length!==r.length||o<0||o>8*n)throw new Error("Failed to parse given CIDR: "+e);var a=nr(o,8*n);return{network:rr(i,a),mask:a}}(e));else{var r=kt(e);if(null==r)throw new Error("Failed to parse network");t=String(t);var n=parseInt(t,10);if(Number.isNaN(n)||String(n).length!==t.length||n<0||n>8*r.length){var i=kt(t);if(null==i)throw new Error("Failed to parse mask");this.mask=i}else this.mask=nr(n,8*r.length);this.network=rr(r,this.mask)}}contains(e){return function(e,t){if("string"==typeof t&&(t=kt(t)),null==t)throw new Error("Invalid ip");if(t.length!==e.network.length)return!1;for(var r=0;r<t.length;r++)if((e.network[r]&e.mask[r])!==(t[r]&e.mask[r]))return!1;return!0}({network:this.network,mask:this.mask},e)}toString(){var e=function(e){var t=0;for(var[r,n]of e.entries()){if(255!==n){for(;128&n;)t++,n<<=1;if(128&n)return-1;for(var i=r+1;i<e.length;i++)if(0!=e[i])return-1;break}t+=8}return t}(this.mask),t=-1!==e?String(e):function(e){var t="0x";for(var r of e)t+=(r>>4).toString(16)+(15&r).toString(16);return t}(this.mask);return function(e){switch(e.length){case Xt:return e.join(".");case er:for(var t=[],r=0;r<e.length;r++)r%2==0&&t.push(e[r].toString(16).padStart(2,"0")+e[r+1].toString(16).padStart(2,"0"));return t.join(":");default:throw new Error("Invalid ip length")}}(this.network)+"/"+t}}var or=new Map;function ar(e){return Boolean(null==e?void 0:e[Ht])}function sr(e){return new $t(e)}function lr(e){var t,r=Ut.getProtocol(e);return{code:r.code,size:null!==(t=r.size)&&void 0!==t?t:0,name:r.name,resolvable:Boolean(r.resolvable),path:Boolean(r.path)}}var cr="object"==typeof globalThis&&"crypto"in globalThis?globalThis.crypto:void 0;function ur(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function dr(e){if(!((t=e)instanceof Uint8Array||ArrayBuffer.isView(t)&&"Uint8Array"===t.constructor.name))throw new Error("Uint8Array expected");for(var t,r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];if(n.length>0&&!n.includes(e.length))throw new Error("Uint8Array expected of length "+n+", got length="+e.length)}function hr(e){if("function"!=typeof e||"function"!=typeof e.create)throw new Error("Hash should be wrapped by utils.createHasher");ur(e.outputLen),ur(e.blockLen)}function pr(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function fr(e,t){dr(e);var r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}function vr(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];for(var n=0;n<t.length;n++)t[n].fill(0)}function yr(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function gr(e,t){return e<<32-t|e>>>t}function mr(e,t){return e<<t|e>>>32-t>>>0}var wr=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function br(e){return e<<24&4278190080|e<<8&16711680|e>>>8&65280|e>>>24&255}var _r=wr?e=>e:e=>br(e);var Sr=wr?e=>e:function(e){for(var t=0;t<e.length;t++)e[t]=br(e[t]);return e},Pr=(()=>"function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex)(),Er=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));var Ar=48,kr=57,xr=65,Tr=70,Ir=97,Cr=102;function Br(e){return e>=Ar&&e<=kr?e-Ar:e>=xr&&e<=Tr?e-(xr-10):e>=Ir&&e<=Cr?e-(Ir-10):void 0}var Nr=function(){var t=e._asyncToGenerator((function*(){}));return function(){return t.apply(this,arguments)}}();function Dr(){return Dr=e._asyncToGenerator((function*(e,t,r){for(var n=Date.now(),i=0;i<e;i++){r(i);var o=Date.now()-n;o>=0&&o<t||(yield Nr(),n+=o)}})),Dr.apply(this,arguments)}function Gr(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}function Rr(e){return"string"==typeof e&&(e=Gr(e)),dr(e),e}function Or(e){return"string"==typeof e&&(e=Gr(e)),dr(e),e}function Lr(){for(var e=0,t=0;t<arguments.length;t++){var r=t<0||arguments.length<=t?void 0:arguments[t];dr(r),e+=r.length}for(var n=new Uint8Array(e),i=0,o=0;i<arguments.length;i++){var a=i<0||arguments.length<=i?void 0:arguments[i];n.set(a,o),o+=a.length}return n}class Mr{}function jr(e){var t=t=>e().update(Rr(t)).digest(),r=e();return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=()=>e(),t}function Fr(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:32;if(cr&&"function"==typeof cr.getRandomValues)return cr.getRandomValues(new Uint8Array(e));if(cr&&"function"==typeof cr.randomBytes)return Uint8Array.from(cr.randomBytes(e));throw new Error("crypto.getRandomValues must be defined")}function Ur(e,t,r){return e&t^~e&r}function zr(e,t,r){return e&t^e&r^t&r}class Vr extends Mr{constructor(e,t,r,n){super(),this.finished=!1,this.length=0,this.pos=0,this.destroyed=!1,this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=yr(this.buffer)}update(e){pr(this),dr(e=Rr(e));for(var{view:t,buffer:r,blockLen:n}=this,i=e.length,o=0;o<i;){var a=Math.min(n-this.pos,i-o);if(a!==n)r.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(t,0),this.pos=0);else for(var s=yr(e);n<=i-o;o+=n)this.process(s,o)}return this.length+=e.length,this.roundClean(),this}digestInto(e){pr(this),fr(e,this),this.finished=!0;var{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,vr(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(r,0),o=0);for(var a=o;a<n;a++)t[a]=0;!function(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);var i=BigInt(32),o=BigInt(4294967295),a=Number(r>>i&o),s=Number(r&o),l=n?4:0,c=n?0:4;e.setUint32(t+l,a,n),e.setUint32(t+c,s,n)}(r,n-8,BigInt(8*this.length),i),this.process(r,0);var s=yr(e),l=this.outputLen;if(l%4)throw new Error("_sha2: outputLen should be aligned to 32bit");var c=l/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(var d=0;d<c;d++)s.setUint32(4*d,u[d],i)}digest(){var{buffer:e,outputLen:t}=this;this.digestInto(e);var r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());var{blockLen:t,buffer:r,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}}var qr=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Hr=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Kr=BigInt(2**32-1),Wr=BigInt(32);function Qr(e){return arguments.length>1&&void 0!==arguments[1]&&arguments[1]?{h:Number(e&Kr),l:Number(e>>Wr&Kr)}:{h:0|Number(e>>Wr&Kr),l:0|Number(e&Kr)}}function Yr(e){for(var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=e.length,n=new Uint32Array(r),i=new Uint32Array(r),o=0;o<r;o++){var{h:a,l:s}=Qr(e[o],t);[n[o],i[o]]=[a,s]}return[n,i]}var Jr=(e,t,r)=>e>>>r,Zr=(e,t,r)=>e<<32-r|t>>>r,$r=(e,t,r)=>e>>>r|t<<32-r,Xr=(e,t,r)=>e<<32-r|t>>>r,en=(e,t,r)=>e<<64-r|t>>>r-32,tn=(e,t,r)=>e>>>r-32|t<<64-r;function rn(e,t,r,n){var i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:0|i}}var nn=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),on=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,an=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),sn=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,ln=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),cn=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,un=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),dn=new Uint32Array(64);class hn extends Vr{constructor(){super(64,arguments.length>0&&void 0!==arguments[0]?arguments[0]:32,8,!1),this.A=0|qr[0],this.B=0|qr[1],this.C=0|qr[2],this.D=0|qr[3],this.E=0|qr[4],this.F=0|qr[5],this.G=0|qr[6],this.H=0|qr[7]}get(){var{A:e,B:t,C:r,D:n,E:i,F:o,G:a,H:s}=this;return[e,t,r,n,i,o,a,s]}set(e,t,r,n,i,o,a,s){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|i,this.F=0|o,this.G=0|a,this.H=0|s}process(e,t){for(var r=0;r<16;r++,t+=4)dn[r]=e.getUint32(t,!1);for(var n=16;n<64;n++){var i=dn[n-15],o=dn[n-2],a=gr(i,7)^gr(i,18)^i>>>3,s=gr(o,17)^gr(o,19)^o>>>10;dn[n]=s+dn[n-7]+a+dn[n-16]|0}for(var{A:l,B:c,C:u,D:d,E:h,F:p,G:f,H:v}=this,y=0;y<64;y++){var g=v+(gr(h,6)^gr(h,11)^gr(h,25))+Ur(h,p,f)+un[y]+dn[y]|0,m=(gr(l,2)^gr(l,13)^gr(l,22))+zr(l,c,u)|0;v=f,f=p,p=h,h=d+g|0,d=u,u=c,c=l,l=g+m|0}l=l+this.A|0,c=c+this.B|0,u=u+this.C|0,d=d+this.D|0,h=h+this.E|0,p=p+this.F|0,f=f+this.G|0,v=v+this.H|0,this.set(l,c,u,d,h,p,f,v)}roundClean(){vr(dn)}destroy(){this.set(0,0,0,0,0,0,0,0),vr(this.buffer)}}var pn=(()=>Yr(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map((e=>BigInt(e)))))(),fn=(()=>pn[0])(),vn=(()=>pn[1])(),yn=new Uint32Array(80),gn=new Uint32Array(80);class mn extends Vr{constructor(){super(128,arguments.length>0&&void 0!==arguments[0]?arguments[0]:64,16,!1),this.Ah=0|Hr[0],this.Al=0|Hr[1],this.Bh=0|Hr[2],this.Bl=0|Hr[3],this.Ch=0|Hr[4],this.Cl=0|Hr[5],this.Dh=0|Hr[6],this.Dl=0|Hr[7],this.Eh=0|Hr[8],this.El=0|Hr[9],this.Fh=0|Hr[10],this.Fl=0|Hr[11],this.Gh=0|Hr[12],this.Gl=0|Hr[13],this.Hh=0|Hr[14],this.Hl=0|Hr[15]}get(){var{Ah:e,Al:t,Bh:r,Bl:n,Ch:i,Cl:o,Dh:a,Dl:s,Eh:l,El:c,Fh:u,Fl:d,Gh:h,Gl:p,Hh:f,Hl:v}=this;return[e,t,r,n,i,o,a,s,l,c,u,d,h,p,f,v]}set(e,t,r,n,i,o,a,s,l,c,u,d,h,p,f,v){this.Ah=0|e,this.Al=0|t,this.Bh=0|r,this.Bl=0|n,this.Ch=0|i,this.Cl=0|o,this.Dh=0|a,this.Dl=0|s,this.Eh=0|l,this.El=0|c,this.Fh=0|u,this.Fl=0|d,this.Gh=0|h,this.Gl=0|p,this.Hh=0|f,this.Hl=0|v}process(e,t){for(var r=0;r<16;r++,t+=4)yn[r]=e.getUint32(t),gn[r]=e.getUint32(t+=4);for(var n=16;n<80;n++){var i=0|yn[n-15],o=0|gn[n-15],a=$r(i,o,1)^$r(i,o,8)^Jr(i,0,7),s=Xr(i,o,1)^Xr(i,o,8)^Zr(i,o,7),l=0|yn[n-2],c=0|gn[n-2],u=$r(l,c,19)^en(l,c,61)^Jr(l,0,6),d=Xr(l,c,19)^tn(l,c,61)^Zr(l,c,6),h=an(s,d,gn[n-7],gn[n-16]),p=sn(h,a,u,yn[n-7],yn[n-16]);yn[n]=0|p,gn[n]=0|h}for(var{Ah:f,Al:v,Bh:y,Bl:g,Ch:m,Cl:w,Dh:b,Dl:_,Eh:S,El:P,Fh:E,Fl:A,Gh:k,Gl:x,Hh:T,Hl:I}=this,C=0;C<80;C++){var B=$r(S,P,14)^$r(S,P,18)^en(S,P,41),N=Xr(S,P,14)^Xr(S,P,18)^tn(S,P,41),D=S&E^~S&k,G=ln(I,N,P&A^~P&x,vn[C],gn[C]),R=cn(G,T,B,D,fn[C],yn[C]),O=0|G,L=$r(f,v,28)^en(f,v,34)^en(f,v,39),M=Xr(f,v,28)^tn(f,v,34)^tn(f,v,39),j=f&y^f&m^y&m,F=v&g^v&w^g&w;T=0|k,I=0|x,k=0|E,x=0|A,E=0|S,A=0|P,({h:S,l:P}=rn(0|b,0|_,0|R,0|O)),b=0|m,_=0|w,m=0|y,w=0|g,y=0|f,g=0|v;var U=nn(O,M,F);f=on(U,R,L,j),v=0|U}({h:f,l:v}=rn(0|this.Ah,0|this.Al,0|f,0|v)),({h:y,l:g}=rn(0|this.Bh,0|this.Bl,0|y,0|g)),({h:m,l:w}=rn(0|this.Ch,0|this.Cl,0|m,0|w)),({h:b,l:_}=rn(0|this.Dh,0|this.Dl,0|b,0|_)),({h:S,l:P}=rn(0|this.Eh,0|this.El,0|S,0|P)),({h:E,l:A}=rn(0|this.Fh,0|this.Fl,0|E,0|A)),({h:k,l:x}=rn(0|this.Gh,0|this.Gl,0|k,0|x)),({h:T,l:I}=rn(0|this.Hh,0|this.Hl,0|T,0|I)),this.set(f,v,y,g,m,w,b,_,S,P,E,A,k,x,T,I)}roundClean(){vr(yn,gn)}destroy(){vr(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}}var wn=jr((()=>new hn)),bn=jr((()=>new mn));class _n extends Mr{constructor(e,t){super(),this.finished=!1,this.destroyed=!1,hr(e);var r=Rr(t);if(this.iHash=e.create(),"function"!=typeof this.iHash.update)throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;var n=this.blockLen,i=new Uint8Array(n);i.set(r.length>n?e.create().update(r).digest():r);for(var o=0;o<i.length;o++)i[o]^=54;this.iHash.update(i),this.oHash=e.create();for(var a=0;a<i.length;a++)i[a]^=106;this.oHash.update(i),vr(i)}update(e){return pr(this),this.iHash.update(e),this}digestInto(e){pr(this),dr(e,this.outputLen),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){var e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));var{oHash:t,iHash:r,finished:n,destroyed:i,blockLen:o,outputLen:a}=this;return e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=t._cloneInto(e.oHash),e.iHash=r._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}var Sn=(e,t,r)=>new _n(e,t).update(r).digest();Sn.create=(e,t)=>new _n(e,t);var Pn=BigInt(0),En=BigInt(1);function An(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function kn(e){if(!An(e))throw new Error("Uint8Array expected")}function xn(e,t){if("boolean"!=typeof t)throw new Error(e+" boolean expected, got "+t)}function Tn(e){var t=e.toString(16);return 1&t.length?"0"+t:t}function In(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);return""===e?Pn:BigInt("0x"+e)}var Cn="function"==typeof Uint8Array.from([]).toHex&&"function"==typeof Uint8Array.fromHex,Bn=Array.from({length:256},((e,t)=>t.toString(16).padStart(2,"0")));function Nn(e){if(kn(e),Cn)return e.toHex();for(var t="",r=0;r<e.length;r++)t+=Bn[e[r]];return t}var Dn=48,Gn=57,Rn=65,On=70,Ln=97,Mn=102;function jn(e){return e>=Dn&&e<=Gn?e-Dn:e>=Rn&&e<=On?e-(Rn-10):e>=Ln&&e<=Mn?e-(Ln-10):void 0}function Fn(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Cn)return Uint8Array.fromHex(e);var t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);for(var n=new Uint8Array(r),i=0,o=0;i<r;i++,o+=2){var a=jn(e.charCodeAt(o)),s=jn(e.charCodeAt(o+1));if(void 0===a||void 0===s){var l=e[o]+e[o+1];throw new Error('hex string expected, got non-hex character "'+l+'" at index '+o)}n[i]=16*a+s}return n}function Un(e){return In(Nn(e))}function zn(e){return kn(e),In(Nn(Uint8Array.from(e).reverse()))}function Vn(e,t){return Fn(e.toString(16).padStart(2*t,"0"))}function qn(e,t){return Vn(e,t).reverse()}function Hn(e,t,r){var n;if("string"==typeof t)try{n=Fn(t)}catch(t){throw new Error(e+" must be hex string or Uint8Array, cause: "+t)}else{if(!An(t))throw new Error(e+" must be hex string or Uint8Array");n=Uint8Array.from(t)}var i=n.length;if("number"==typeof r&&i!==r)throw new Error(e+" of length "+r+" expected, got "+i);return n}function Kn(){for(var e=0,t=0;t<arguments.length;t++){var r=t<0||arguments.length<=t?void 0:arguments[t];kn(r),e+=r.length}for(var n=new Uint8Array(e),i=0,o=0;i<arguments.length;i++){var a=i<0||arguments.length<=i?void 0:arguments[i];n.set(a,o),o+=a.length}return n}var Wn=e=>"bigint"==typeof e&&Pn<=e;function Qn(e,t,r){return Wn(e)&&Wn(t)&&Wn(r)&&t<=e&&e<r}function Yn(e,t,r,n){if(!Qn(t,r,n))throw new Error("expected valid "+e+": "+r+" <= n < "+n+", got "+t)}var Jn=e=>(En<<BigInt(e))-En,Zn=e=>new Uint8Array(e),$n=e=>Uint8Array.from(e);var Xn={bigint:e=>"bigint"==typeof e,function:e=>"function"==typeof e,boolean:e=>"boolean"==typeof e,string:e=>"string"==typeof e,stringOrUint8Array:e=>"string"==typeof e||An(e),isSafeInteger:e=>Number.isSafeInteger(e),array:e=>Array.isArray(e),field:(e,t)=>t.Fp.isValid(e),hash:e=>"function"==typeof e&&Number.isSafeInteger(e.outputLen)};function ei(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=(t,r,n)=>{var i=Xn[r];if("function"!=typeof i)throw new Error("invalid validator function");var o=e[t];if(!(n&&void 0===o||i(o,e)))throw new Error("param "+String(t)+" is invalid. Expected "+r+", got "+o)};for(var[i,o]of Object.entries(t))n(i,o,!1);for(var[a,s]of Object.entries(r))n(a,s,!0);return e}function ti(e){var t=new WeakMap;return function(r){var n=t.get(r);if(void 0!==n)return n;for(var i=arguments.length,o=new Array(i>1?i-1:0),a=1;a<i;a++)o[a-1]=arguments[a];var s=e(r,...o);return t.set(r,s),s}}var ri=BigInt(0),ni=BigInt(1),ii=BigInt(2),oi=BigInt(3),ai=BigInt(4),si=BigInt(5),li=BigInt(8);function ci(e,t){var r=e%t;return r>=ri?r:t+r}function ui(e,t,r){for(var n=e;t-- >ri;)n*=n,n%=r;return n}function di(e,t){if(e===ri)throw new Error("invert: expected non-zero number");if(t<=ri)throw new Error("invert: expected positive modulus, got "+t);for(var r=ci(e,t),n=t,i=ri,o=ni;r!==ri;){var a=n%r,s=i-o*(n/r);n=r,r=a,i=o,o=s}if(n!==ni)throw new Error("invert: does not exist");return ci(i,t)}function hi(e,t){var r=(e.ORDER+ni)/ai,n=e.pow(t,r);if(!e.eql(e.sqr(n),t))throw new Error("Cannot find square root");return n}function pi(e,t){var r=(e.ORDER-si)/li,n=e.mul(t,ii),i=e.pow(n,r),o=e.mul(t,i),a=e.mul(e.mul(o,ii),i),s=e.mul(o,e.sub(a,e.ONE));if(!e.eql(e.sqr(s),t))throw new Error("Cannot find square root");return s}function fi(e){return e%ai===oi?hi:e%li===si?pi:function(e){if(e<BigInt(3))throw new Error("sqrt is not defined for small field");for(var t=e-ni,r=0;t%ii===ri;)t/=ii,r++;for(var n=ii,i=wi(e);1===gi(i,n);)if(n++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(1===r)return hi;var o=i.pow(n,t),a=(t+ni)/ii;return function(e,n){if(e.is0(n))return n;if(1!==gi(e,n))throw new Error("Cannot find square root");for(var i=r,s=e.mul(e.ONE,o),l=e.pow(n,t),c=e.pow(n,a);!e.eql(l,e.ONE);){if(e.is0(l))return e.ZERO;for(var u=1,d=e.sqr(l);!e.eql(d,e.ONE);)if(u++,d=e.sqr(d),u===i)throw new Error("Cannot find square root");var h=ni<<BigInt(i-u-1),p=e.pow(s,h);i=u,s=e.sqr(p),l=e.mul(l,s),c=e.mul(c,p)}return c}}(e)}var vi=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function yi(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=new Array(t.length).fill(r?e.ZERO:void 0),i=t.reduce(((t,r,i)=>e.is0(r)?t:(n[i]=t,e.mul(t,r))),e.ONE),o=e.inv(i);return t.reduceRight(((t,r,i)=>e.is0(r)?t:(n[i]=e.mul(t,n[i]),e.mul(t,r))),o),n}function gi(e,t){var r=(e.ORDER-ni)/ii,n=e.pow(t,r),i=e.eql(n,e.ONE),o=e.eql(n,e.ZERO),a=e.eql(n,e.neg(e.ONE));if(!i&&!o&&!a)throw new Error("invalid Legendre symbol result");return i?1:o?0:-1}function mi(e,t){void 0!==t&&ur(t);var r=void 0!==t?t:e.toString(2).length;return{nBitLength:r,nByteLength:Math.ceil(r/8)}}function wi(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};if(e<=ri)throw new Error("invalid field: expected ORDER > 0, got "+e);var i,{nBitLength:o,nByteLength:a}=mi(e,t);if(a>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");var s=Object.freeze({ORDER:e,isLE:r,BITS:o,BYTES:a,MASK:Jn(o),ZERO:ri,ONE:ni,create:t=>ci(t,e),isValid:t=>{if("bigint"!=typeof t)throw new Error("invalid field element: expected bigint, got "+typeof t);return ri<=t&&t<e},is0:e=>e===ri,isOdd:e=>(e&ni)===ni,neg:t=>ci(-t,e),eql:(e,t)=>e===t,sqr:t=>ci(t*t,e),add:(t,r)=>ci(t+r,e),sub:(t,r)=>ci(t-r,e),mul:(t,r)=>ci(t*r,e),pow:(e,t)=>function(e,t,r){if(r<ri)throw new Error("invalid exponent, negatives unsupported");if(r===ri)return e.ONE;if(r===ni)return t;for(var n=e.ONE,i=t;r>ri;)r&ni&&(n=e.mul(n,i)),i=e.sqr(i),r>>=ni;return n}(s,e,t),div:(t,r)=>ci(t*di(r,e),e),sqrN:e=>e*e,addN:(e,t)=>e+t,subN:(e,t)=>e-t,mulN:(e,t)=>e*t,inv:t=>di(t,e),sqrt:n.sqrt||(t=>(i||(i=fi(e)),i(s,t))),toBytes:e=>r?qn(e,a):Vn(e,a),fromBytes:e=>{if(e.length!==a)throw new Error("Field.fromBytes: expected "+a+" bytes, got "+e.length);return r?zn(e):Un(e)},invertBatch:e=>yi(s,e),cmov:(e,t,r)=>r?t:e});return Object.freeze(s)}function bi(e){if("bigint"!=typeof e)throw new Error("field order must be bigint");var t=e.toString(2).length;return Math.ceil(t/8)}function _i(e){var t=bi(e);return t+Math.ceil(t/2)}var Si=BigInt(0),Pi=BigInt(1);function Ei(e,t){var r=t.negate();return e?r:t}function Ai(e,t){if(!Number.isSafeInteger(e)||e<=0||e>t)throw new Error("invalid window size, expected [1.."+t+"], got W="+e)}function ki(e,t){Ai(e,t);var r=2**e;return{windows:Math.ceil(t/e)+1,windowSize:2**(e-1),mask:Jn(e),maxNumber:r,shiftBy:BigInt(e)}}function xi(e,t,r){var{windowSize:n,mask:i,maxNumber:o,shiftBy:a}=r,s=Number(e&i),l=e>>a;s>n&&(s-=o,l+=Pi);var c=t*n;return{nextN:l,offset:c+Math.abs(s)-1,isZero:0===s,isNeg:s<0,isNegF:t%2!=0,offsetF:c}}var Ti=new WeakMap,Ii=new WeakMap;function Ci(e){return Ii.get(e)||1}function Bi(e,t){return{constTimeNegate:Ei,hasPrecomputes:e=>1!==Ci(e),unsafeLadder(t,r){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.ZERO,i=t;r>Si;)r&Pi&&(n=n.add(i)),i=i.double(),r>>=Pi;return n},precomputeWindow(e,r){for(var{windows:n,windowSize:i}=ki(r,t),o=[],a=e,s=a,l=0;l<n;l++){s=a,o.push(s);for(var c=1;c<i;c++)s=s.add(a),o.push(s);a=s.double()}return o},wNAF(r,n,i){for(var o=e.ZERO,a=e.BASE,s=ki(r,t),l=0;l<s.windows;l++){var{nextN:c,offset:u,isZero:d,isNeg:h,isNegF:p,offsetF:f}=xi(i,l,s);i=c,d?a=a.add(Ei(p,n[f])):o=o.add(Ei(h,n[u]))}return{p:o,f:a}},wNAFUnsafe(r,n,i){for(var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:e.ZERO,a=ki(r,t),s=0;s<a.windows&&i!==Si;s++){var{nextN:l,offset:c,isZero:u,isNeg:d}=xi(i,s,a);if(i=l,!u){var h=n[c];o=o.add(d?h.negate():h)}}return o},getPrecomputes(e,t,r){var n=Ti.get(t);return n||(n=this.precomputeWindow(t,e),1!==e&&Ti.set(t,r(n))),n},wNAFCached(e,t,r){var n=Ci(e);return this.wNAF(n,this.getPrecomputes(n,e,r),t)},wNAFCachedUnsafe(e,t,r,n){var i=Ci(e);return 1===i?this.unsafeLadder(e,t,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,r),t,n)},setWindowSize(e,r){Ai(r,t),Ii.set(e,r),Ti.delete(e)}}}function Ni(e,t,r,n){!function(e,t){if(!Array.isArray(e))throw new Error("array expected");e.forEach(((e,r)=>{if(!(e instanceof t))throw new Error("invalid point at index "+r)}))}(r,e),function(e,t){if(!Array.isArray(e))throw new Error("array of scalars expected");e.forEach(((e,r)=>{if(!t.isValid(e))throw new Error("invalid scalar at index "+r)}))}(n,t);var i=r.length,o=n.length;if(i!==o)throw new Error("arrays of points and scalars must have equal length");var a=e.ZERO,s=function(e){var t;for(t=0;e>Pn;e>>=En,t+=1);return t}(BigInt(i)),l=1;s>12?l=s-3:s>4?l=s-2:s>0&&(l=2);for(var c=Jn(l),u=new Array(Number(c)+1).fill(a),d=a,h=Math.floor((t.BITS-1)/l)*l;h>=0;h-=l){u.fill(a);for(var p=0;p<o;p++){var f=n[p],v=Number(f>>BigInt(h)&c);u[v]=u[v].add(r[p])}for(var y=a,g=u.length-1,m=a;g>0;g--)m=m.add(u[g]),y=y.add(m);if(d=d.add(y),0!==h)for(var w=0;w<l;w++)d=d.double()}return d}function Di(t){var r,n;return r=t.Fp,n=vi.reduce(((e,t)=>(e[t]="function",e)),{ORDER:"bigint",MASK:"bigint",BYTES:"isSafeInteger",BITS:"isSafeInteger"}),ei(r,n),ei(t,{n:"bigint",h:"bigint",Gx:"field",Gy:"field"},{nBitLength:"isSafeInteger",nByteLength:"isSafeInteger"}),Object.freeze(e._objectSpread2(e._objectSpread2(e._objectSpread2({},mi(t.n,t.nBitLength)),t),{p:t.Fp.ORDER}))}function Gi(e){void 0!==e.lowS&&xn("lowS",e.lowS),void 0!==e.prehash&&xn("prehash",e.prehash)}class Ri extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"")}}var Oi={Err:Ri,_tlv:{encode:(e,t)=>{var{Err:r}=Oi;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(1&t.length)throw new r("tlv.encode: unpadded data");var n=t.length/2,i=Tn(n);if(i.length/2&128)throw new r("tlv.encode: long form length too big");var o=n>127?Tn(i.length/2|128):"";return Tn(e)+o+i+t},decode(e,t){var{Err:r}=Oi,n=0;if(e<0||e>256)throw new r("tlv.encode: wrong tag");if(t.length<2||t[n++]!==e)throw new r("tlv.decode: wrong tlv");var i=t[n++],o=0;if(!!(128&i)){var a=127&i;if(!a)throw new r("tlv.decode(long): indefinite length not supported");if(a>4)throw new r("tlv.decode(long): byte length is too big");var s=t.subarray(n,n+a);if(s.length!==a)throw new r("tlv.decode: length bytes not complete");if(0===s[0])throw new r("tlv.decode(long): zero leftmost byte");for(var l of s)o=o<<8|l;if(n+=a,o<128)throw new r("tlv.decode(long): not minimal encoding")}else o=i;var c=t.subarray(n,n+o);if(c.length!==o)throw new r("tlv.decode: wrong value length");return{v:c,l:t.subarray(n+o)}}},_int:{encode(e){var{Err:t}=Oi;if(e<Mi)throw new t("integer: negative integers are not allowed");var r=Tn(e);if(8&Number.parseInt(r[0],16)&&(r="00"+r),1&r.length)throw new t("unexpected DER parsing assertion: unpadded hex");return r},decode(e){var{Err:t}=Oi;if(128&e[0])throw new t("invalid signature integer: negative");if(0===e[0]&&!(128&e[1]))throw new t("invalid signature integer: unnecessary leading zero");return Un(e)}},toSig(e){var{Err:t,_int:r,_tlv:n}=Oi,i=Hn("signature",e),{v:o,l:a}=n.decode(48,i);if(a.length)throw new t("invalid signature: left bytes after parsing");var{v:s,l:l}=n.decode(2,o),{v:c,l:u}=n.decode(2,l);if(u.length)throw new t("invalid signature: left bytes after parsing");return{r:r.decode(s),s:r.decode(c)}},hexFromSig(e){var{_tlv:t,_int:r}=Oi,n=t.encode(2,r.encode(e.r))+t.encode(2,r.encode(e.s));return t.encode(48,n)}};function Li(e,t){return Nn(Vn(e,t))}var Mi=BigInt(0),ji=BigInt(1);BigInt(2);var Fi=BigInt(3),Ui=BigInt(4);function zi(t){var r=function(t){var r=Di(t);ei(r,{a:"field",b:"field"},{allowInfinityPoint:"boolean",allowedPrivateKeyLengths:"array",clearCofactor:"function",fromBytes:"function",isTorsionFree:"function",toBytes:"function",wrapPrivateKey:"boolean"});var{endo:n,Fp:i,a:o}=r;if(n){if(!i.eql(o,i.ZERO))throw new Error("invalid endo: CURVE.a must be 0");if("object"!=typeof n||"bigint"!=typeof n.beta||"function"!=typeof n.splitScalar)throw new Error('invalid endo: expected "beta": bigint and "splitScalar": function')}return Object.freeze(e._objectSpread2({},r))}(t),{Fp:n}=r,i=wi(r.n,r.nBitLength),o=r.toBytes||((e,t,r)=>{var i=t.toAffine();return Kn(Uint8Array.from([4]),n.toBytes(i.x),n.toBytes(i.y))}),a=r.fromBytes||(e=>{var t=e.subarray(1);return{x:n.fromBytes(t.subarray(0,n.BYTES)),y:n.fromBytes(t.subarray(n.BYTES,2*n.BYTES))}});function s(e){var{a:t,b:i}=r,o=n.sqr(e),a=n.mul(o,e);return n.add(n.add(a,n.mul(e,t)),i)}function l(e,t){var r=n.sqr(t),i=s(e);return n.eql(r,i)}if(!l(r.Gx,r.Gy))throw new Error("bad curve params: generator point");var c=n.mul(n.pow(r.a,Fi),Ui),u=n.mul(n.sqr(r.b),BigInt(27));if(n.is0(n.add(c,u)))throw new Error("bad curve params: a or b");function d(e){var t,{allowedPrivateKeyLengths:n,nByteLength:i,wrapPrivateKey:o,n:a}=r;if(n&&"bigint"!=typeof e){if(An(e)&&(e=Nn(e)),"string"!=typeof e||!n.includes(e.length))throw new Error("invalid private key");e=e.padStart(2*i,"0")}try{t="bigint"==typeof e?e:Un(Hn("private key",e,i))}catch(t){throw new Error("invalid private key, expected hex or "+i+" bytes, got "+typeof e)}return o&&(t=ci(t,a)),Yn("private key",t,ji,a),t}function h(e){if(!(e instanceof v))throw new Error("ProjectivePoint expected")}var p=ti(((e,t)=>{var{px:r,py:i,pz:o}=e;if(n.eql(o,n.ONE))return{x:r,y:i};var a=e.is0();null==t&&(t=a?n.ONE:n.inv(o));var s=n.mul(r,t),l=n.mul(i,t),c=n.mul(o,t);if(a)return{x:n.ZERO,y:n.ZERO};if(!n.eql(c,n.ONE))throw new Error("invZ was invalid");return{x:s,y:l}})),f=ti((e=>{if(e.is0()){if(r.allowInfinityPoint&&!n.is0(e.py))return;throw new Error("bad point: ZERO")}var{x:t,y:i}=e.toAffine();if(!n.isValid(t)||!n.isValid(i))throw new Error("bad point: x or y not FE");if(!l(t,i))throw new Error("bad point: equation left != right");if(!e.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0}));class v{constructor(e,t,r){if(null==e||!n.isValid(e))throw new Error("x required");if(null==t||!n.isValid(t)||n.is0(t))throw new Error("y required");if(null==r||!n.isValid(r))throw new Error("z required");this.px=e,this.py=t,this.pz=r,Object.freeze(this)}static fromAffine(e){var{x:t,y:r}=e||{};if(!e||!n.isValid(t)||!n.isValid(r))throw new Error("invalid affine point");if(e instanceof v)throw new Error("projective point not allowed");var i=e=>n.eql(e,n.ZERO);return i(t)&&i(r)?v.ZERO:new v(t,r,n.ONE)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static normalizeZ(e){var t=yi(n,e.map((e=>e.pz)));return e.map(((e,r)=>e.toAffine(t[r]))).map(v.fromAffine)}static fromHex(e){var t=v.fromAffine(a(Hn("pointHex",e)));return t.assertValidity(),t}static fromPrivateKey(e){return v.BASE.multiply(d(e))}static msm(e,t){return Ni(v,i,e,t)}_setWindowSize(e){m.setWindowSize(this,e)}assertValidity(){f(this)}hasEvenY(){var{y:e}=this.toAffine();if(n.isOdd)return!n.isOdd(e);throw new Error("Field doesn't support isOdd")}equals(e){h(e);var{px:t,py:r,pz:i}=this,{px:o,py:a,pz:s}=e,l=n.eql(n.mul(t,s),n.mul(o,i)),c=n.eql(n.mul(r,s),n.mul(a,i));return l&&c}negate(){return new v(this.px,n.neg(this.py),this.pz)}double(){var{a:e,b:t}=r,i=n.mul(t,Fi),{px:o,py:a,pz:s}=this,l=n.ZERO,c=n.ZERO,u=n.ZERO,d=n.mul(o,o),h=n.mul(a,a),p=n.mul(s,s),f=n.mul(o,a);return f=n.add(f,f),u=n.mul(o,s),u=n.add(u,u),l=n.mul(e,u),c=n.mul(i,p),c=n.add(l,c),l=n.sub(h,c),c=n.add(h,c),c=n.mul(l,c),l=n.mul(f,l),u=n.mul(i,u),p=n.mul(e,p),f=n.sub(d,p),f=n.mul(e,f),f=n.add(f,u),u=n.add(d,d),d=n.add(u,d),d=n.add(d,p),d=n.mul(d,f),c=n.add(c,d),p=n.mul(a,s),p=n.add(p,p),d=n.mul(p,f),l=n.sub(l,d),u=n.mul(p,h),u=n.add(u,u),u=n.add(u,u),new v(l,c,u)}add(e){h(e);var{px:t,py:i,pz:o}=this,{px:a,py:s,pz:l}=e,c=n.ZERO,u=n.ZERO,d=n.ZERO,p=r.a,f=n.mul(r.b,Fi),y=n.mul(t,a),g=n.mul(i,s),m=n.mul(o,l),w=n.add(t,i),b=n.add(a,s);w=n.mul(w,b),b=n.add(y,g),w=n.sub(w,b),b=n.add(t,o);var _=n.add(a,l);return b=n.mul(b,_),_=n.add(y,m),b=n.sub(b,_),_=n.add(i,o),c=n.add(s,l),_=n.mul(_,c),c=n.add(g,m),_=n.sub(_,c),d=n.mul(p,b),c=n.mul(f,m),d=n.add(c,d),c=n.sub(g,d),d=n.add(g,d),u=n.mul(c,d),g=n.add(y,y),g=n.add(g,y),m=n.mul(p,m),b=n.mul(f,b),g=n.add(g,m),m=n.sub(y,m),m=n.mul(p,m),b=n.add(b,m),y=n.mul(g,b),u=n.add(u,y),y=n.mul(_,b),c=n.mul(w,c),c=n.sub(c,y),y=n.mul(w,g),d=n.mul(_,d),d=n.add(d,y),new v(c,u,d)}subtract(e){return this.add(e.negate())}is0(){return this.equals(v.ZERO)}wNAF(e){return m.wNAFCached(this,e,v.normalizeZ)}multiplyUnsafe(e){var{endo:t,n:i}=r;Yn("scalar",e,Mi,i);var o=v.ZERO;if(e===Mi)return o;if(this.is0()||e===ji)return this;if(!t||m.hasPrecomputes(this))return m.wNAFCachedUnsafe(this,e,v.normalizeZ);for(var{k1neg:a,k1:s,k2neg:l,k2:c}=t.splitScalar(e),u=o,d=o,h=this;s>Mi||c>Mi;)s&ji&&(u=u.add(h)),c&ji&&(d=d.add(h)),h=h.double(),s>>=ji,c>>=ji;return a&&(u=u.negate()),l&&(d=d.negate()),d=new v(n.mul(d.px,t.beta),d.py,d.pz),u.add(d)}multiply(e){var t,i,{endo:o,n:a}=r;if(Yn("scalar",e,ji,a),o){var{k1neg:s,k1:l,k2neg:c,k2:u}=o.splitScalar(e),{p:d,f:h}=this.wNAF(l),{p:p,f:f}=this.wNAF(u);d=m.constTimeNegate(s,d),p=m.constTimeNegate(c,p),p=new v(n.mul(p.px,o.beta),p.py,p.pz),t=d.add(p),i=h.add(f)}else{var{p:y,f:g}=this.wNAF(e);t=y,i=g}return v.normalizeZ([t,i])[0]}multiplyAndAddUnsafe(e,t,r){var n=v.BASE,i=(e,t)=>t!==Mi&&t!==ji&&e.equals(n)?e.multiply(t):e.multiplyUnsafe(t),o=i(this,t).add(i(e,r));return o.is0()?void 0:o}toAffine(e){return p(this,e)}isTorsionFree(){var{h:e,isTorsionFree:t}=r;if(e===ji)return!0;if(t)return t(v,this);throw new Error("isTorsionFree() has not been declared for the elliptic curve")}clearCofactor(){var{h:e,clearCofactor:t}=r;return e===ji?this:t?t(v,this):this.multiplyUnsafe(r.h)}toRawBytes(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return xn("isCompressed",e),this.assertValidity(),o(v,this,e)}toHex(){var e=!(arguments.length>0&&void 0!==arguments[0])||arguments[0];return xn("isCompressed",e),Nn(this.toRawBytes(e))}}v.BASE=new v(r.Gx,r.Gy,n.ONE),v.ZERO=new v(n.ZERO,n.ONE,n.ZERO);var{endo:y,nBitLength:g}=r,m=Bi(v,y?Math.ceil(g/2):g);return{CURVE:r,ProjectivePoint:v,normPrivateKeyToScalar:d,weierstrassEquation:s,isWithinCurveOrder:function(e){return Qn(e,ji,r.n)}}}function Vi(t){var r,n=(ei(r=Di(t),{hash:"hash",hmac:"function",randomBytes:"function"},{bits2int:"function",bits2int_modN:"function",lowS:"boolean"}),Object.freeze(e._objectSpread2({lowS:!0},r))),{Fp:i,n:o,nByteLength:a,nBitLength:s}=n,l=i.BYTES+1,c=2*i.BYTES+1;function u(e){return ci(e,o)}function d(e){return di(e,o)}var{ProjectivePoint:h,normPrivateKeyToScalar:p,weierstrassEquation:f,isWithinCurveOrder:v}=zi(e._objectSpread2(e._objectSpread2({},n),{},{toBytes(e,t,r){var n=t.toAffine(),o=i.toBytes(n.x),a=Kn;return xn("isCompressed",r),r?a(Uint8Array.from([t.hasEvenY()?2:3]),o):a(Uint8Array.from([4]),o,i.toBytes(n.y))},fromBytes(e){var t=e.length,r=e[0],n=e.subarray(1);if(t!==l||2!==r&&3!==r){if(t===c&&4===r)return{x:i.fromBytes(n.subarray(0,i.BYTES)),y:i.fromBytes(n.subarray(i.BYTES,2*i.BYTES))};throw new Error("invalid Point, expected length of "+l+", or uncompressed "+c+", got "+t)}var o=Un(n);if(!Qn(o,ji,i.ORDER))throw new Error("Point is not on curve");var a,s=f(o);try{a=i.sqrt(s)}catch(e){var u=e instanceof Error?": "+e.message:"";throw new Error("Point is not on curve"+u)}return!(1&~r)!==((a&ji)===ji)&&(a=i.neg(a)),{x:o,y:a}}}));function y(e){return e>o>>ji}var g=(e,t,r)=>Un(e.slice(t,r));class m{constructor(e,t,r){Yn("r",e,ji,o),Yn("s",t,ji,o),this.r=e,this.s=t,null!=r&&(this.recovery=r),Object.freeze(this)}static fromCompact(e){var t=a;return e=Hn("compactSignature",e,2*t),new m(g(e,0,t),g(e,t,2*t))}static fromDER(e){var{r:t,s:r}=Oi.toSig(Hn("DER",e));return new m(t,r)}assertValidity(){}addRecoveryBit(e){return new m(this.r,this.s,e)}recoverPublicKey(e){var{r:t,s:r,recovery:o}=this,a=S(Hn("msgHash",e));if(null==o||![0,1,2,3].includes(o))throw new Error("recovery id invalid");var s=2===o||3===o?t+n.n:t;if(s>=i.ORDER)throw new Error("recovery id 2 or 3 invalid");var l=1&o?"03":"02",c=h.fromHex(l+Li(s,i.BYTES)),p=d(s),f=u(-a*p),v=u(r*p),y=h.BASE.multiplyAndAddUnsafe(c,f,v);if(!y)throw new Error("point at infinify");return y.assertValidity(),y}hasHighS(){return y(this.s)}normalizeS(){return this.hasHighS()?new m(this.r,u(-this.s),this.recovery):this}toDERRawBytes(){return Fn(this.toDERHex())}toDERHex(){return Oi.hexFromSig(this)}toCompactRawBytes(){return Fn(this.toCompactHex())}toCompactHex(){var e=a;return Li(this.r,e)+Li(this.s,e)}}var w={isValidPrivateKey(e){try{return p(e),!0}catch(e){return!1}},normPrivateKeyToScalar:p,randomPrivateKey:()=>{var e=_i(n.n);return function(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2],n=e.length,i=bi(t),o=_i(t);if(n<16||n<o||n>1024)throw new Error("expected "+o+"-1024 bytes of input, got "+n);var a=ci(r?zn(e):Un(e),t-ni)+ni;return r?qn(a,i):Vn(a,i)}(n.randomBytes(e),n.n)},precompute(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:8,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:h.BASE;return t._setWindowSize(e),t.multiply(BigInt(3)),t}};function b(e){if("bigint"==typeof e)return!1;if(e instanceof h)return!0;var t=Hn("key",e).length,r=i.BYTES,o=r+1,s=2*r+1;return n.allowedPrivateKeyLengths||a===o?void 0:t===o||t===s}var _=n.bits2int||function(e){if(e.length>8192)throw new Error("input is too large");var t=Un(e),r=8*e.length-s;return r>0?t>>BigInt(r):t},S=n.bits2int_modN||function(e){return u(_(e))},P=Jn(s);function E(e){return Yn("num < 2^"+s,e,Mi,P),Vn(e,a)}function A(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:k;if(["recovered","canonical"].some((e=>e in r)))throw new Error("sign() legacy options not supported");var{hash:o,randomBytes:a}=n,{lowS:s,prehash:l,extraEntropy:c}=r;null==s&&(s=!0),e=Hn("msgHash",e),Gi(r),l&&(e=Hn("prehashed msgHash",o(e)));var f=S(e),g=p(t),w=[E(g),E(f)];if(null!=c&&!1!==c){var b=!0===c?a(i.BYTES):c;w.push(Hn("extraEntropy",b))}var P=Kn(...w),A=f;return{seed:P,k2sig:function(e){var t=_(e);if(v(t)){var r=d(t),n=h.BASE.multiply(t).toAffine(),i=u(n.x);if(i!==Mi){var o=u(r*u(A+i*g));if(o!==Mi){var a=(n.x===i?0:2)|Number(n.y&ji),l=o;return s&&y(o)&&(l=function(e){return y(e)?u(-e):e}(o),a^=1),new m(i,l,a)}}}}}}var k={lowS:n.lowS,prehash:!1},x={lowS:n.lowS,prehash:!1};return h.BASE._setWindowSize(8),{CURVE:n,getPublicKey:function(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];return h.fromPrivateKey(e).toRawBytes(t)},getSharedSecret:function(e,t){var r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];if(!0===b(e))throw new Error("first arg must be private key");if(!1===b(t))throw new Error("second arg must be public key");return h.fromHex(t).multiply(p(e)).toRawBytes(r)},sign:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:k,{seed:i,k2sig:o}=A(e,t,r),a=n,s=function(e,t,r){if("number"!=typeof e||e<2)throw new Error("hashLen must be a number");if("number"!=typeof t||t<2)throw new Error("qByteLen must be a number");if("function"!=typeof r)throw new Error("hmacFn must be a function");var n=Zn(e),i=Zn(e),o=0,a=()=>{n.fill(1),i.fill(0),o=0},s=function(){for(var e=arguments.length,t=new Array(e),o=0;o<e;o++)t[o]=arguments[o];return r(i,n,...t)},l=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Zn(0);i=s($n([0]),e),n=s(),0!==e.length&&(i=s($n([1]),e),n=s())},c=()=>{if(o++>=1e3)throw new Error("drbg: tried 1000 values");for(var e=0,r=[];e<t;){var i=(n=s()).slice();r.push(i),e+=n.length}return Kn(...r)};return(e,t)=>{a(),l(e);for(var r=void 0;!(r=t(c()));)l();return a(),r}}(a.hash.outputLen,a.nByteLength,a.hmac);return s(i,o)},verify:function(e,t,r){var i,o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:x,a=e;t=Hn("msgHash",t),r=Hn("publicKey",r);var{lowS:s,prehash:l,format:c}=o;if(Gi(o),"strict"in o)throw new Error("options.strict was renamed to lowS");if(void 0!==c&&"compact"!==c&&"der"!==c)throw new Error("format must be compact or der");var p="string"==typeof a||An(a),f=!p&&!c&&"object"==typeof a&&null!==a&&"bigint"==typeof a.r&&"bigint"==typeof a.s;if(!p&&!f)throw new Error("invalid signature, expected Uint8Array, hex string or Signature instance");var v,y=void 0;try{if(f&&(y=new m(a.r,a.s)),p){try{"compact"!==c&&(y=m.fromDER(a))}catch(e){if(!(e instanceof Oi.Err))throw e}y||"der"===c||(y=m.fromCompact(a))}v=h.fromHex(r)}catch(e){return!1}if(!y)return!1;if(s&&y.hasHighS())return!1;l&&(t=n.hash(t));var{r:g,s:w}=y,b=S(t),_=d(w),P=u(b*_),E=u(g*_),A=null===(i=h.BASE.multiplyAndAddUnsafe(v,P,E))||void 0===i?void 0:i.toAffine();return!!A&&u(A.x)===g},ProjectivePoint:h,Signature:m,utils:w}}var qi=BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),Hi=BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),Ki=BigInt(0),Wi=BigInt(1),Qi=BigInt(2),Yi=(e,t)=>(e+t/Qi)/t;var Ji=wi(qi,void 0,void 0,{sqrt:function(e){var t=qi,r=BigInt(3),n=BigInt(6),i=BigInt(11),o=BigInt(22),a=BigInt(23),s=BigInt(44),l=BigInt(88),c=e*e*e%t,u=c*c*e%t,d=ui(u,r,t)*u%t,h=ui(d,r,t)*u%t,p=ui(h,Qi,t)*c%t,f=ui(p,i,t)*p%t,v=ui(f,o,t)*f%t,y=ui(v,s,t)*v%t,g=ui(y,l,t)*y%t,m=ui(g,s,t)*v%t,w=ui(m,r,t)*u%t,b=ui(w,a,t)*f%t,_=ui(b,n,t)*c%t,S=ui(_,Qi,t);if(!Ji.eql(Ji.sqr(S),e))throw new Error("Cannot find square root");return S}}),Zi=function(t,r){var n=r=>Vi(e._objectSpread2(e._objectSpread2({},t),function(e){return{hash:e,hmac:function(t){for(var r=arguments.length,n=new Array(r>1?r-1:0),i=1;i<r;i++)n[i-1]=arguments[i];return Sn(e,t,Lr(...n))},randomBytes:Fr}}(r)));return e._objectSpread2(e._objectSpread2({},n(r)),{},{create:n})}({a:Ki,b:BigInt(7),Fp:Ji,n:Hi,Gx:BigInt("55066263022277343669578718895168534326250603453777594175500187360389116729240"),Gy:BigInt("32670510020758816978083085130507043184471273380659243275938904335757337482424"),h:BigInt(1),lowS:!0,endo:{beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),splitScalar:e=>{var t=Hi,r=BigInt("0x3086d221a7d46bcde86c90e49284eb15"),n=-Wi*BigInt("0xe4437ed6010e88286f547fa90abfe4c3"),i=BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),o=r,a=BigInt("0x100000000000000000000000000000000"),s=Yi(o*e,t),l=Yi(-n*e,t),c=ci(e-s*r-l*i,t),u=ci(-s*n-l*o,t),d=c>a,h=u>a;if(d&&(c=t-c),h&&(u=t-u),c>a||u>a)throw new Error("splitScalar: Endomorphism failed, k="+e);return{k1neg:d,k1:c,k2neg:h,k2:u}}}},wn),$i=BigInt(0),Xi=BigInt(1),eo=BigInt(2),to=BigInt(8),ro={zip215:!0};function no(t){var r,n,i=(n=Di(r=t),ei(r,{hash:"function",a:"bigint",d:"bigint",randomBytes:"function"},{adjustScalarBytes:"function",domain:"function",uvRatio:"function",mapToCurve:"function"}),Object.freeze(e._objectSpread2({},n))),{Fp:o,n:a,prehash:s,hash:l,randomBytes:c,nByteLength:u,h:d}=i,h=eo<<BigInt(8*u)-Xi,p=o.create,f=wi(i.n,i.nBitLength);if(!function(e,t){var r=o.sqr(e),n=o.sqr(t),a=o.add(o.mul(i.a,r),n),s=o.add(o.ONE,o.mul(i.d,o.mul(r,n)));return o.eql(a,s)}(i.Gx,i.Gy))throw new Error("bad curve params: generator point");var v=i.uvRatio||((e,t)=>{try{return{isValid:!0,value:o.sqrt(e*o.inv(t))}}catch(e){return{isValid:!1,value:$i}}}),y=i.adjustScalarBytes||(e=>e),g=i.domain||((e,t,r)=>{if(xn("phflag",r),t.length||r)throw new Error("Contexts/pre-hash are not supported");return e});function m(e,t){Yn("coordinate "+e,t,arguments.length>2&&void 0!==arguments[2]&&arguments[2]?Xi:$i,h)}function w(e){if(!(e instanceof S))throw new Error("ExtendedPoint expected")}var b=ti(((e,t)=>{var{ex:r,ey:n,ez:i}=e,a=e.is0();null==t&&(t=a?to:o.inv(i));var s=p(r*t),l=p(n*t),c=p(i*t);if(a)return{x:$i,y:Xi};if(c!==Xi)throw new Error("invZ was invalid");return{x:s,y:l}})),_=ti((e=>{var{a:t,d:r}=i;if(e.is0())throw new Error("bad point: ZERO");var{ex:n,ey:o,ez:a,et:s}=e,l=p(n*n),c=p(o*o),u=p(a*a),d=p(u*u),h=p(l*t);if(p(u*p(h+c))!==p(d+p(r*p(l*c))))throw new Error("bad point: equation left != right (1)");if(p(n*o)!==p(a*s))throw new Error("bad point: equation left != right (2)");return!0}));class S{constructor(e,t,r,n){m("x",e),m("y",t),m("z",r,!0),m("t",n),this.ex=e,this.ey=t,this.ez=r,this.et=n,Object.freeze(this)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}static fromAffine(e){if(e instanceof S)throw new Error("extended point not allowed");var{x:t,y:r}=e||{};return m("x",t),m("y",r),new S(t,r,Xi,p(t*r))}static normalizeZ(e){var t=yi(o,e.map((e=>e.ez)));return e.map(((e,r)=>e.toAffine(t[r]))).map(S.fromAffine)}static msm(e,t){return Ni(S,f,e,t)}_setWindowSize(e){A.setWindowSize(this,e)}assertValidity(){_(this)}equals(e){w(e);var{ex:t,ey:r,ez:n}=this,{ex:i,ey:o,ez:a}=e,s=p(t*a),l=p(i*n),c=p(r*a),u=p(o*n);return s===l&&c===u}is0(){return this.equals(S.ZERO)}negate(){return new S(p(-this.ex),this.ey,this.ez,p(-this.et))}double(){var{a:e}=i,{ex:t,ey:r,ez:n}=this,o=p(t*t),a=p(r*r),s=p(eo*p(n*n)),l=p(e*o),c=t+r,u=p(p(c*c)-o-a),d=l+a,h=d-s,f=l-a,v=p(u*h),y=p(d*f),g=p(u*f),m=p(h*d);return new S(v,y,m,g)}add(e){w(e);var{a:t,d:r}=i,{ex:n,ey:o,ez:a,et:s}=this,{ex:l,ey:c,ez:u,et:d}=e,h=p(n*l),f=p(o*c),v=p(s*r*d),y=p(a*u),g=p((n+o)*(l+c)-h-f),m=y-v,b=y+v,_=p(f-t*h),P=p(g*m),E=p(b*_),A=p(g*_),k=p(m*b);return new S(P,E,k,A)}subtract(e){return this.add(e.negate())}wNAF(e){return A.wNAFCached(this,e,S.normalizeZ)}multiply(e){var t=e;Yn("scalar",t,Xi,a);var{p:r,f:n}=this.wNAF(t);return S.normalizeZ([r,n])[0]}multiplyUnsafe(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:S.ZERO,r=e;return Yn("scalar",r,$i,a),r===$i?E:this.is0()||r===Xi?this:A.wNAFCachedUnsafe(this,r,S.normalizeZ,t)}isSmallOrder(){return this.multiplyUnsafe(d).is0()}isTorsionFree(){return A.unsafeLadder(this,a).is0()}toAffine(e){return b(this,e)}clearCofactor(){var{h:e}=i;return e===Xi?this:this.multiplyUnsafe(e)}static fromHex(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],{d:r,a:n}=i,a=o.BYTES;e=Hn("pointHex",e,a),xn("zip215",t);var s=e.slice(),l=e[a-1];s[a-1]=-129&l;var c=zn(s),u=t?h:o.ORDER;Yn("pointHex.y",c,$i,u);var d=p(c*c),f=p(d-Xi),y=p(r*d-n),{isValid:g,value:m}=v(f,y);if(!g)throw new Error("Point.fromHex: invalid y coordinate");var w=(m&Xi)===Xi,b=!!(128&l);if(!t&&m===$i&&b)throw new Error("Point.fromHex: x=0 and x_0=1");return b!==w&&(m=p(-m)),S.fromAffine({x:m,y:c})}static fromPrivateKey(e){var{scalar:t}=T(e);return P.multiply(t)}toRawBytes(){var{x:e,y:t}=this.toAffine(),r=qn(t,o.BYTES);return r[r.length-1]|=e&Xi?128:0,r}toHex(){return Nn(this.toRawBytes())}}S.BASE=new S(i.Gx,i.Gy,Xi,p(i.Gx*i.Gy)),S.ZERO=new S($i,Xi,Xi,$i);var{BASE:P,ZERO:E}=S,A=Bi(S,8*u);function k(e){return ci(e,a)}function x(e){return k(zn(e))}function T(e){var t=o.BYTES;e=Hn("private key",e,t);var r=Hn("hashed private key",l(e),2*t),n=y(r.slice(0,t));return{head:n,prefix:r.slice(t,2*t),scalar:x(n)}}function I(e){var{head:t,prefix:r,scalar:n}=T(e),i=P.multiply(n),o=i.toRawBytes();return{head:t,prefix:r,scalar:n,point:i,pointBytes:o}}function C(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Uint8Array.of(),t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];var i=Kn(...r);return x(l(g(i,Hn("context",e),!!s)))}var B=ro;P._setWindowSize(8);var N={getExtendedPublicKey:I,randomPrivateKey:()=>c(o.BYTES),precompute(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:8,t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:S.BASE;return t._setWindowSize(e),t.multiply(BigInt(3)),t}};return{CURVE:i,getPublicKey:function(e){return I(e).pointBytes},sign:function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};e=Hn("message",e),s&&(e=s(e));var{prefix:n,scalar:i,pointBytes:l}=I(t),c=C(r.context,n,e),u=P.multiply(c).toRawBytes(),d=k(c+C(r.context,u,l,e)*i);return Yn("signature.s",d,$i,a),Hn("result",Kn(u,qn(d,o.BYTES)),2*o.BYTES)},verify:function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:B,{context:i,zip215:a}=n,l=o.BYTES;e=Hn("signature",e,2*l),t=Hn("message",t),r=Hn("publicKey",r,l),void 0!==a&&xn("zip215",a),s&&(t=s(t));var c,u,d,h=zn(e.slice(l,2*l));try{c=S.fromHex(r,a),u=S.fromHex(e.slice(0,l),a),d=P.multiplyUnsafe(h)}catch(e){return!1}if(!a&&c.isSmallOrder())return!1;var p=C(i,u.toRawBytes(),c.toRawBytes(),t);return u.add(c.multiplyUnsafe(p)).subtract(d).clearCofactor().equals(S.ZERO)},ExtendedPoint:S,utils:N}}var io=BigInt(0),oo=BigInt(1),ao=BigInt(2);function so(t){var r,n=(ei(r=t,{adjustScalarBytes:"function",powPminus2:"function"}),Object.freeze(e._objectSpread2({},r))),{P:i,type:o,adjustScalarBytes:a,powPminus2:s}=n,l="x25519"===o;if(!l&&"x448"!==o)throw new Error("invalid type");var c=l?255:448,u=l?32:56,d=l?BigInt(9):BigInt(5),h=l?BigInt(121665):BigInt(39081),p=l?ao**BigInt(254):ao**BigInt(447),f=l?BigInt(8)*ao**BigInt(251)-oo:BigInt(4)*ao**BigInt(445)-oo,v=p+f+oo,y=e=>ci(e,i),g=m(d);function m(e){return qn(y(e),u)}function w(e,t){var r=function(e,t){Yn("u",e,io,i),Yn("scalar",t,p,v);for(var r=t,n=e,o=oo,a=io,l=e,u=oo,d=io,f=BigInt(c-1);f>=io;f--){var g=r>>f&oo;d^=g,({x_2:o,x_3:l}=_(d,o,l)),({x_2:a,x_3:u}=_(d,a,u)),d=g;var m=o+a,w=y(m*m),b=o-a,S=y(b*b),P=w-S,E=l+u,A=y((l-u)*m),k=y(E*b),x=A+k,T=A-k;l=y(x*x),u=y(n*y(T*T)),o=y(w*S),a=y(P*(w+y(h*P)))}({x_2:o,x_3:l}=_(d,o,l)),({x_2:a,x_3:u}=_(d,a,u));var I=s(a);return y(o*I)}(function(e){var t=Hn("u coordinate",e,u);return l&&(t[31]&=127),y(zn(t))}(t),function(e){return zn(a(Hn("scalar",e,u)))}(e));if(r===io)throw new Error("invalid private or public key received");return m(r)}function b(e){return w(e,g)}function _(e,t,r){var n=y(e*(t-r));return{x_2:t=y(t-n),x_3:r=y(r+n)}}return{scalarMult:w,scalarMultBase:b,getSharedSecret:(e,t)=>w(e,t),getPublicKey:e=>b(e),utils:{randomPrivateKey:()=>n.randomBytes(u)},GuBytes:g.slice()}}var lo=BigInt("57896044618658097711785492504343953926634992332820282019728792003956564819949"),co=BigInt("19681161376707505956807079304988542015446066515923890162744021073123829784752");BigInt(0);var uo=BigInt(1),ho=BigInt(2),po=BigInt(3),fo=BigInt(5),vo=BigInt(8);function yo(e){var t=BigInt(10),r=BigInt(20),n=BigInt(40),i=BigInt(80),o=lo,a=e*e%o*e%o,s=ui(a,ho,o)*a%o,l=ui(s,uo,o)*e%o,c=ui(l,fo,o)*l%o,u=ui(c,t,o)*c%o,d=ui(u,r,o)*u%o,h=ui(d,n,o)*d%o,p=ui(h,i,o)*h%o,f=ui(p,i,o)*h%o,v=ui(f,t,o)*c%o;return{pow_p_5_8:ui(v,ho,o)*e%o,b2:a}}function go(e){return e[0]&=248,e[31]&=127,e[31]|=64,e}function mo(e,t){var r=lo,n=ci(t*t*t,r),i=ci(n*n*t,r),o=ci(e*n*yo(e*i).pow_p_5_8,r),a=ci(t*o*o,r),s=o,l=ci(o*co,r),c=a===e,u=a===ci(-e,r),d=a===ci(-e*co,r);return c&&(o=s),(u||d)&&(o=l),(ci(o,r)&ni)===ni&&(o=ci(-o,r)),{isValid:c||u,value:o}}var wo=(()=>wi(lo,void 0,!0))(),bo=(()=>({a:wo.create(BigInt(-1)),d:BigInt("37095705934669439343138083508754565189542113879843219016388785533085940283555"),Fp:wo,n:BigInt("7237005577332262213973186563042994240857116359379907606001950938285454250989"),h:vo,Gx:BigInt("15112221349535400772501151409588531511454012693041857206046113283949847762202"),Gy:BigInt("46316835694926478169428394003475163141307993866256225615783033603165251855960"),hash:bn,randomBytes:Fr,adjustScalarBytes:go,uvRatio:mo}))(),_o=(()=>no(bo))(),So=(()=>so({P:lo,type:"x25519",powPminus2:e=>{var t=lo,{pow_p_5_8:r,b2:n}=yo(e);return ci(ui(r,po,t)*n,t)},adjustScalarBytes:go,randomBytes:Fr}))(),Po=wn,Eo=bn;function Ao(e,t,r,n){hr(e);var i=function(e,t){if(void 0!==t&&"[object Object]"!=={}.toString.call(t))throw new Error("options should be object or undefined");return Object.assign(e,t)}({dkLen:32,asyncTick:10},n),{c:o,dkLen:a,asyncTick:s}=i;if(ur(o),ur(a),ur(s),o<1)throw new Error("iterations (c) should be >= 1");var l=Or(t),c=Or(r),u=new Uint8Array(a),d=Sn.create(e,l),h=d._cloneInto().update(c);return{c:o,dkLen:a,asyncTick:s,DK:u,PRF:d,PRFSalt:h}}function ko(e,t,r,n,i){return e.destroy(),t.destroy(),n&&n.destroy(),vr(i),r}function xo(e,t,r,n){return To.apply(this,arguments)}function To(){return To=e._asyncToGenerator((function*(e,t,r,n){for(var i,{c:o,dkLen:a,asyncTick:s,DK:l,PRF:c,PRFSalt:u}=Ao(e,t,r,n),d=new Uint8Array(4),h=yr(d),p=new Uint8Array(c.outputLen),f=function*(){var e=l.subarray(y,y+c.outputLen);h.setInt32(0,v,!1),(i=u._cloneInto(i)).update(d).digestInto(p),e.set(p.subarray(0,e.length)),yield function(e,t,r){return Dr.apply(this,arguments)}(o-1,s,(()=>{c._cloneInto(i).update(p).digestInto(p);for(var t=0;t<e.length;t++)e[t]^=p[t]}))},v=1,y=0;y<a;v++,y+=c.outputLen)yield*f();return ko(c,u,l,i,p)})),To.apply(this,arguments)}var Io,Co={exports:{}};var Bo=(Io||(Io=1,function(e){var t=Object.prototype.hasOwnProperty,r="~";function n(){}function i(e,t,r){this.fn=e,this.context=t,this.once=r||!1}function o(e,t,n,o,a){if("function"!=typeof n)throw new TypeError("The listener must be a function");var s=new i(n,o||e,a),l=r?r+t:t;return e._events[l]?e._events[l].fn?e._events[l]=[e._events[l],s]:e._events[l].push(s):(e._events[l]=s,e._eventsCount++),e}function a(e,t){0===--e._eventsCount?e._events=new n:delete e._events[t]}function s(){this._events=new n,this._eventsCount=0}Object.create&&(n.prototype=Object.create(null),(new n).__proto__||(r=!1)),s.prototype.eventNames=function(){var e,n,i=[];if(0===this._eventsCount)return i;for(n in e=this._events)t.call(e,n)&&i.push(r?n.slice(1):n);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(e)):i},s.prototype.listeners=function(e){var t=r?r+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,o=n.length,a=new Array(o);i<o;i++)a[i]=n[i].fn;return a},s.prototype.listenerCount=function(e){var t=r?r+e:e,n=this._events[t];return n?n.fn?1:n.length:0},s.prototype.emit=function(e,t,n,i,o,a){var s=r?r+e:e;if(!this._events[s])return!1;var l,c,u=this._events[s],d=arguments.length;if(u.fn){switch(u.once&&this.removeListener(e,u.fn,void 0,!0),d){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,t),!0;case 3:return u.fn.call(u.context,t,n),!0;case 4:return u.fn.call(u.context,t,n,i),!0;case 5:return u.fn.call(u.context,t,n,i,o),!0;case 6:return u.fn.call(u.context,t,n,i,o,a),!0}for(c=1,l=new Array(d-1);c<d;c++)l[c-1]=arguments[c];u.fn.apply(u.context,l)}else{var h,p=u.length;for(c=0;c<p;c++)switch(u[c].once&&this.removeListener(e,u[c].fn,void 0,!0),d){case 1:u[c].fn.call(u[c].context);break;case 2:u[c].fn.call(u[c].context,t);break;case 3:u[c].fn.call(u[c].context,t,n);break;case 4:u[c].fn.call(u[c].context,t,n,i);break;default:if(!l)for(h=1,l=new Array(d-1);h<d;h++)l[h-1]=arguments[h];u[c].fn.apply(u[c].context,l)}}return!0},s.prototype.on=function(e,t,r){return o(this,e,t,r,!1)},s.prototype.once=function(e,t,r){return o(this,e,t,r,!0)},s.prototype.removeListener=function(e,t,n,i){var o=r?r+e:e;if(!this._events[o])return this;if(!t)return a(this,o),this;var s=this._events[o];if(s.fn)s.fn!==t||i&&!s.once||n&&s.context!==n||a(this,o);else{for(var l=0,c=[],u=s.length;l<u;l++)(s[l].fn!==t||i&&!s[l].once||n&&s[l].context!==n)&&c.push(s[l]);c.length?this._events[o]=1===c.length?c[0]:c:a(this,o)}return this},s.prototype.removeAllListeners=function(e){var t;return e?(t=r?r+e:e,this._events[t]&&a(this,t)):(this._events=new n,this._eventsCount=0),this},s.prototype.off=s.prototype.removeListener,s.prototype.addListener=s.prototype.on,s.prefixed=r,s.EventEmitter=s,e.exports=s}(Co)),Co.exports),No=e.getDefaultExportFromCjs(Bo),Do=function(e,t){return Do=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r])},Do(e,t)};function Go(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Class extends value "+String(t)+" is not a constructor or null");function r(){this.constructor=e}Do(e,t),e.prototype=null===t?Object.create(t):(r.prototype=t.prototype,new r)}function Ro(e,t,r,n){var i,o=arguments.length,a=o<3?t:null===n?n=Object.getOwnPropertyDescriptor(t,r):n;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)a=Reflect.decorate(e,t,r,n);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(a=(o<3?i(a):o>3?i(t,r,a):i(t,r))||a);return o>3&&a&&Object.defineProperty(t,r,a),a}function Oo(e,t,r,n){return new(r||(r=Promise))((function(i,o){function a(e){try{l(n.next(e))}catch(e){o(e)}}function s(e){try{l(n.throw(e))}catch(e){o(e)}}function l(e){var t;e.done?i(e.value):(t=e.value,t instanceof r?t:new r((function(e){e(t)}))).then(a,s)}l((n=n.apply(e,t||[])).next())}))}function Lo(e,t){var r,n,i,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(l){return function(s){if(r)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(o=0)),o;)try{if(r=1,n&&(i=2&s[0]?n.return:s[0]?n.throw||((i=n.return)&&i.call(n),0):n.next)&&!(i=i.call(n,s[1])).done)return i;switch(n=0,i&&(s=[2&s[0],i.value]),s[0]){case 0:case 1:i=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,n=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!(i=o.trys,(i=i.length>0&&i[i.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!i||s[1]>i[0]&&s[1]<i[3])){o.label=s[1];break}if(6===s[0]&&o.label<i[1]){o.label=i[1],i=s;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(s);break}i[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],n=0}finally{r=i=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,l])}}}function Mo(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw new TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}function jo(e,t){var r="function"==typeof Symbol&&e[Symbol.iterator];if(!r)return e;var n,i,o=r.call(e),a=[];try{for(;(void 0===t||t-- >0)&&!(n=o.next()).done;)a.push(n.value)}catch(e){i={error:e}}finally{try{n&&!n.done&&(r=o.return)&&r.call(o)}finally{if(i)throw i.error}}return a}function Fo(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(jo(arguments[t]));return e}function Uo(e){return this instanceof Uo?(this.v=e,this):new Uo(e)}"function"==typeof SuppressedError&&SuppressedError;var zo=Symbol.for("@libp2p/connection"),Vo=Symbol.for("@libp2p/content-routing"),qo=Symbol.for("@libp2p/peer-discovery"),Ho=Symbol.for("@libp2p/peer-id");function Ko(e){return Boolean(null==e?void 0:e[Ho])}var Wo,Qo=Symbol.for("@libp2p/peer-routing"),Yo="keep-alive",Jo=Symbol.for("@libp2p/transport");!function(e){e[e.FATAL_ALL=0]="FATAL_ALL",e[e.NO_FATAL=1]="NO_FATAL"}(Wo||(Wo={}));let Zo=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The operation was aborted"),this.name="AbortError"}};e._defineProperty(Zo,"name","AbortError");class $o extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unexpected Peer"),this.name="UnexpectedPeerError"}}e._defineProperty($o,"name","UnexpectedPeerError");let Xo=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid crypto exchange"),this.name="InvalidCryptoExchangeError"}};e._defineProperty(Xo,"name","InvalidCryptoExchangeError");let ea=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid parameters"),this.name="InvalidParametersError"}};e._defineProperty(ea,"name","InvalidParametersError");class ta extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid public key"),this.name="InvalidPublicKeyError"}}e._defineProperty(ta,"name","InvalidPublicKeyError");class ra extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid private key"),this.name="InvalidPrivateKeyError"}}e._defineProperty(ra,"name","InvalidPrivateKeyError");class na extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unsupported operation"),this.name="UnsupportedOperationError"}}e._defineProperty(na,"name","UnsupportedOperationError");class ia extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The connection is closing"),this.name="ConnectionClosingError"}}e._defineProperty(ia,"name","ConnectionClosingError");class oa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The connection is closed"),this.name="ConnectionClosedError"}}e._defineProperty(oa,"name","ConnectionClosedError");class aa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Connection failed"),this.name="ConnectionFailedError"}}e._defineProperty(aa,"name","ConnectionFailedError");class sa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The muxer is closed"),this.name="MuxerClosedError"}}e._defineProperty(sa,"name","MuxerClosedError");class la extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The stream has been reset"),this.name="StreamResetError"}}e._defineProperty(la,"name","StreamResetError");class ca extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The stream is in an invalid state"),this.name="StreamStateError"}}e._defineProperty(ca,"name","StreamStateError");let ua=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not found"),this.name="NotFoundError"}};e._defineProperty(ua,"name","NotFoundError");class da extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid PeerID"),this.name="InvalidPeerIdError"}}e._defineProperty(da,"name","InvalidPeerIdError");class ha extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid multiaddr"),this.name="InvalidMultiaddrError"}}e._defineProperty(ha,"name","InvalidMultiaddrError");class pa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid CID"),this.name="InvalidCIDError"}}e._defineProperty(pa,"name","InvalidCIDError");class fa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid Multihash"),this.name="InvalidMultihashError"}}e._defineProperty(fa,"name","InvalidMultihashError");class va extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unsupported protocol error"),this.name="UnsupportedProtocolError"}}e._defineProperty(va,"name","UnsupportedProtocolError");class ya extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid message"),this.name="InvalidMessageError"}}e._defineProperty(ya,"name","InvalidMessageError");class ga extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Protocol error"),this.name="ProtocolError"}}e._defineProperty(ga,"name","ProtocolError");let ma=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Timed out"),this.name="TimeoutError"}};e._defineProperty(ma,"name","TimeoutError");class wa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not started"),this.name="NotStartedError"}}e._defineProperty(wa,"name","NotStartedError");class ba extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Already started"),this.name="AlreadyStartedError"}}e._defineProperty(ba,"name","AlreadyStartedError");class _a extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Dial error"),this.name="DialError"}}e._defineProperty(_a,"name","DialError");class Sa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Listen error"),this.name="ListenError"}}e._defineProperty(Sa,"name","ListenError");class Pa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Limited connection"),this.name="LimitedConnectionError"}}e._defineProperty(Pa,"name","LimitedConnectionError");class Ea extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Too many inbound protocol streams"),this.name="TooManyInboundProtocolStreamsError"}}e._defineProperty(Ea,"name","TooManyInboundProtocolStreamsError");class Aa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Too many outbound protocol streams"),this.name="TooManyOutboundProtocolStreamsError"}}e._defineProperty(Aa,"name","TooManyOutboundProtocolStreamsError");class ka extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unsupported key type"),this.name="UnsupportedKeyTypeError"}}e._defineProperty(ka,"name","UnsupportedKeyTypeError");class xa extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not implemented"),this.name="NotImplementedError"}}e._defineProperty(xa,"name","NotImplementedError");var Ta=new WeakMap;let Ia=class extends EventTarget{constructor(){super(),e._classPrivateFieldInitSpec(this,Ta,new Map)}listenerCount(t){var r=e._classPrivateFieldGet2(Ta,this).get(t);return null==r?0:r.length}addEventListener(t,r,n){var i;super.addEventListener(t,r,n);var o=e._classPrivateFieldGet2(Ta,this).get(t);null==o&&(o=[],e._classPrivateFieldGet2(Ta,this).set(t,o)),o.push({callback:r,once:null!==(i=!0!==n&&!1!==n&&(null==n?void 0:n.once))&&void 0!==i&&i})}removeEventListener(t,r,n){super.removeEventListener(t.toString(),null!=r?r:null,n);var i=e._classPrivateFieldGet2(Ta,this).get(t);null!=i&&(i=i.filter((e=>{var{callback:t}=e;return t!==r})),e._classPrivateFieldGet2(Ta,this).set(t,i))}dispatchEvent(t){var r=super.dispatchEvent(t),n=e._classPrivateFieldGet2(Ta,this).get(t.type);return null==n||(n=n.filter((e=>{var{once:t}=e;return!t})),e._classPrivateFieldGet2(Ta,this).set(t.type,n)),r}safeDispatchEvent(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.dispatchEvent(new CustomEvent(e,t))}};function Ca(e){return null!=e&&"function"==typeof e.start&&"function"==typeof e.stop}function Ba(){return Na.apply(this,arguments)}function Na(){return Na=e._asyncToGenerator((function*(){for(var t=[],r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];for(var o of n)Ca(o)&&t.push(o);yield Promise.all(t.map(function(){var t=e._asyncToGenerator((function*(e){null!=e.beforeStart&&(yield e.beforeStart())}));return function(e){return t.apply(this,arguments)}}())),yield Promise.all(t.map(function(){var t=e._asyncToGenerator((function*(e){yield e.start()}));return function(e){return t.apply(this,arguments)}}())),yield Promise.all(t.map(function(){var t=e._asyncToGenerator((function*(e){null!=e.afterStart&&(yield e.afterStart())}));return function(e){return t.apply(this,arguments)}}()))})),Na.apply(this,arguments)}function Da(){return Ga.apply(this,arguments)}function Ga(){return Ga=e._asyncToGenerator((function*(){for(var t=[],r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];for(var o of n)Ca(o)&&t.push(o);yield Promise.all(t.map(function(){var t=e._asyncToGenerator((function*(e){null!=e.beforeStop&&(yield e.beforeStop())}));return function(e){return t.apply(this,arguments)}}())),yield Promise.all(t.map(function(){var t=e._asyncToGenerator((function*(e){yield e.stop()}));return function(e){return t.apply(this,arguments)}}())),yield Promise.all(t.map(function(){var t=e._asyncToGenerator((function*(e){null!=e.afterStop&&(yield e.afterStop())}));return function(e){return t.apply(this,arguments)}}()))})),Ga.apply(this,arguments)}var Ra=Symbol.for("@libp2p/service-capabilities"),Oa=Symbol.for("@libp2p/service-dependencies"),La=Symbol.for("@achingbrain/uint8arraylist");function Ma(e,t){if(null==t||t<0)throw new RangeError("index is out of bounds");var r=0;for(var n of e){var i=r+n.byteLength;if(t<i)return{buf:n,index:t-r};r=i}throw new RangeError("index is out of bounds")}function ja(e){return Boolean(null==e?void 0:e[La])}class Fa{constructor(){e._defineProperty(this,"bufs",void 0),e._defineProperty(this,"length",void 0),e._defineProperty(this,La,!0),this.bufs=[],this.length=0;for(var t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];r.length>0&&this.appendAll(r)}*[Symbol.iterator](){yield*this.bufs}get byteLength(){return this.length}append(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this.appendAll(t)}appendAll(e){var t=0;for(var r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else{if(!ja(r))throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.push(...r.bufs)}this.length+=t}prepend(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];this.prependAll(t)}prependAll(e){var t=0;for(var r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else{if(!ja(r))throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");t+=r.byteLength,this.bufs.unshift(...r.bufs)}this.length+=t}get(e){var t=Ma(this.bufs,e);return t.buf[t.index]}set(e,t){var r=Ma(this.bufs,e);r.buf[r.index]=t}write(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(e instanceof Uint8Array)for(var r=0;r<e.length;r++)this.set(t+r,e[r]);else{if(!ja(e))throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList");for(var n=0;n<e.length;n++)this.set(t+n,e.get(n))}}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength)return this.bufs=[],void(this.length=0);for(;this.bufs.length>0;){if(!(e>=this.bufs[0].byteLength)){this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift()}}}slice(e,t){var{bufs:r,length:n}=this._subList(e,t);return _t(r,n)}subarray(e,t){var{bufs:r,length:n}=this._subList(e,t);return 1===r.length?r[0]:_t(r,n)}sublist(e,t){var{bufs:r,length:n}=this._subList(e,t),i=new Fa;return i.length=n,i.bufs=[...r],i}_subList(e,t){if(e=null!=e?e:0,t=null!=t?t:this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(0===e&&t===this.length)return{bufs:this.bufs,length:this.length};for(var r=[],n=0,i=0;i<this.bufs.length;i++){var o=this.bufs[i],a=n,s=a+o.byteLength;if(n=s,!(e>=s)){var l=e>=a&&e<s,c=t>a&&t<=s;if(l&&c){if(e===a&&t===s){r.push(o);break}var u=e-a;r.push(o.subarray(u,u+(t-e)));break}if(l){if(0===e){r.push(o);continue}r.push(o.subarray(e-a))}else{if(c){if(t===s){r.push(o);break}r.push(o.subarray(0,t-a));break}r.push(o)}}}return{bufs:r,length:t-e}}indexOf(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(!(ja(e)||e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');var r=e instanceof Uint8Array?e:e.subarray();if(t=Number(null!=t?t:0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),0===e.length)return t>this.length?this.length:t;var n=r.byteLength;if(0===n)throw new TypeError("search must be at least 1 byte long");for(var i=new Int32Array(256),o=0;o<256;o++)i[o]=-1;for(var a=0;a<n;a++)i[r[a]]=a;for(var s,l=i,c=this.byteLength-r.byteLength,u=r.byteLength-1,d=t;d<=c;d+=s){s=0;for(var h=u;h>=0;h--){var p=this.get(d+h);if(r[h]!==p){s=Math.max(1,h-l[p]);break}}if(0===s)return d}return-1}getInt8(e){var t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){var r=Ke(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){var r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){var n=He(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt16(0,t,r),this.write(n,e)}getInt32(e,t){var r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){var n=He(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt32(0,t,r),this.write(n,e)}getBigInt64(e,t){var r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){var n=He(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigInt64(0,t,r),this.write(n,e)}getUint8(e){var t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){var r=Ke(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){var r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){var n=He(2);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint16(0,t,r),this.write(n,e)}getUint32(e,t){var r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){var n=He(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint32(0,t,r),this.write(n,e)}getBigUint64(e,t){var r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){var n=He(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setBigUint64(0,t,r),this.write(n,e)}getFloat32(e,t){var r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){var n=He(4);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat32(0,t,r),this.write(n,e)}getFloat64(e,t){var r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){var n=He(8);new DataView(n.buffer,n.byteOffset,n.byteLength).setFloat64(0,t,r),this.write(n,e)}equals(e){if(null==e)return!1;if(!(e instanceof Fa))return!1;if(e.bufs.length!==this.bufs.length)return!1;for(var t=0;t<this.bufs.length;t++)if(!nt(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){var r=new Fa;return r.bufs=e,null==t&&(t=e.reduce(((e,t)=>e+t.byteLength),0)),r.length=t,r}}var Ua=parseInt("11111",2),za=parseInt("10000000",2),Va=parseInt("01111111",2),qa={0:Wa,1:Wa,2:function(e,t){for(var r=Ka(e,t),n=t.offset,i=t.offset+r,o=[],a=n;a<i;a++)a===n&&0===e[a]||o.push(e[a]);return t.offset+=r,Uint8Array.from(o)},3:function(e,t){var r=Ka(e,t),n=e[t.offset];t.offset++;var i=e.subarray(t.offset,t.offset+r-1);if(t.offset+=r,0!==n)throw new Error("Unused bits in bit string is unimplemented");return i},4:function(e,t){var r=Ka(e,t),n=e.subarray(t.offset,t.offset+r);return t.offset+=r,n},5:function(e,t){return t.offset++,null},6:function(e,t){var r=Ka(e,t),n=t.offset+r,i=e[t.offset];t.offset++;var o=0,a=0;i<40?(o=0,a=i):i<80?(o=1,a=i-40):(o=2,a=i-80);var s="".concat(o,".").concat(a),l=[];for(;t.offset<n;){var c=e[t.offset];if(t.offset++,l.push(127&c),c<128){l.reverse();for(var u=0,d=0;d<l.length;d++)u+=l[d]<<7*d;s+=".".concat(u),l=[]}}return s},16:Wa,22:Wa,48:Wa};function Ha(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{offset:0},r=e[t.offset]&Ua;if(t.offset++,null!=qa[r])return qa[r](e,t);throw new Error("No decoder for tag "+r)}function Ka(e,t){var r=0;if((e[t.offset]&za)===za){var n=e[t.offset]&Va,i="0x";t.offset++;for(var o=0;o<n;o++,t.offset++)i+=e[t.offset].toString(16).padStart(2,"0");r=parseInt(i,16)}else r=e[t.offset],t.offset++;return r}function Wa(e,t){Ka(e,t);for(var r=[];!(t.offset>=e.byteLength);){var n=Ha(e,t);if(null===n)break;r.push(n)}return r}function Qa(e){if(e.byteLength<128)return Uint8Array.from([e.byteLength]);var t=function(e){var t=e.toString(16);t.length%2==1&&(t="0"+t);for(var r=new Fa,n=0;n<t.length;n+=2)r.append(Uint8Array.from([parseInt("".concat(t[n]).concat(t[n+1]),16)]));return r}(e.byteLength);return new Fa(Uint8Array.from([t.byteLength|za]),t)}function Ya(e){var t=new Fa;return!(128&~e.subarray()[0])&&t.append(Uint8Array.from([0])),t.append(e),new Fa(Uint8Array.from([2]),Qa(t),t)}function Ja(e){var t=Uint8Array.from([0]),r=new Fa(t,e);return new Fa(Uint8Array.from([3]),Qa(r),r)}function Za(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:48,r=new Fa;for(var n of e)r.append(n);return new Fa(Uint8Array.from([t]),Qa(r),r)}var $a="1.2.840.10045.3.1.7",Xa="1.3.132.0.34",es="1.3.132.0.35";function ts(){return ts=e._asyncToGenerator((function*(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"P-256",t=yield crypto.subtle.generateKey({name:"ECDSA",namedCurve:e},!0,["sign","verify"]);return{publicKey:yield crypto.subtle.exportKey("jwk",t.publicKey),privateKey:yield crypto.subtle.exportKey("jwk",t.privateKey)}})),ts.apply(this,arguments)}function rs(){return(rs=e._asyncToGenerator((function*(e,t){var r,n=yield crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:null!==(r=e.crv)&&void 0!==r?r:"P-256"},!1,["sign"]),i=yield crypto.subtle.sign({name:"ECDSA",hash:{name:"SHA-256"}},n,t.subarray());return new Uint8Array(i,0,i.byteLength)}))).apply(this,arguments)}function ns(){return ns=e._asyncToGenerator((function*(e,t,r){var n,i=yield crypto.subtle.importKey("jwk",e,{name:"ECDSA",namedCurve:null!==(n=e.crv)&&void 0!==n?n:"P-256"},!1,["verify"]);return crypto.subtle.verify({name:"ECDSA",hash:{name:"SHA-256"}},i,t,r.subarray())})),ns.apply(this,arguments)}var is=Uint8Array.from([6,8,42,134,72,206,61,3,1,7]),os=Uint8Array.from([6,5,43,129,4,0,34]),as=Uint8Array.from([6,5,43,129,4,0,35]),ss={ext:!0,kty:"EC",crv:"P-256"},ls={ext:!0,kty:"EC",crv:"P-384"},cs={ext:!0,kty:"EC",crv:"P-521"},us=32,ds=48,hs=66;function ps(t){var r,n,i=t[1],o=Ze(i,"base64url"),a=t[2][1][0];if(i.byteLength===us)return r=Ze(a.subarray(1,33),"base64url"),n=Ze(a.subarray(33),"base64url"),new ws(e._objectSpread2(e._objectSpread2({},ss),{},{key_ops:["sign"],d:o,x:r,y:n}));if(i.byteLength===ds)return r=Ze(a.subarray(1,49),"base64url"),n=Ze(a.subarray(49),"base64url"),new ws(e._objectSpread2(e._objectSpread2({},ls),{},{key_ops:["sign"],d:o,x:r,y:n}));if(i.byteLength===hs)return r=Ze(a.subarray(1,67),"base64url"),n=Ze(a.subarray(67),"base64url"),new ws(e._objectSpread2(e._objectSpread2({},cs),{},{key_ops:["sign"],d:o,x:r,y:n}));throw new ea("Private key length was wrong length, got ".concat(i.byteLength,", expected 32, 48 or 66"))}function fs(e){return vs(Ha(e))}function vs(t){var r,n,i=t[1][1][0];if(65===i.byteLength)return r=Ze(i.subarray(1,33),"base64url"),n=Ze(i.subarray(33),"base64url"),new ms(e._objectSpread2(e._objectSpread2({},ss),{},{key_ops:["verify"],x:r,y:n}));if(97===i.byteLength)return r=Ze(i.subarray(1,49),"base64url"),n=Ze(i.subarray(49),"base64url"),new ms(e._objectSpread2(e._objectSpread2({},ls),{},{key_ops:["verify"],x:r,y:n}));if(133===i.byteLength)return r=Ze(i.subarray(1,67),"base64url"),n=Ze(i.subarray(67),"base64url"),new ms(e._objectSpread2(e._objectSpread2({},cs),{},{key_ops:["verify"],x:r,y:n}));throw new ea("coordinates were wrong length, got ".concat(i.byteLength,", expected 65, 97 or 133"))}function ys(e){if("P-256"===e)return is;if("P-384"===e)return os;if("P-521"===e)return as;throw new ea("Invalid curve ".concat(e))}function gs(){return gs=e._asyncToGenerator((function*(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"P-256",t=yield function(){return ts.apply(this,arguments)}(e);return new ws(t.privateKey)})),gs.apply(this,arguments)}class ms{constructor(t){e._defineProperty(this,"type","ECDSA"),e._defineProperty(this,"jwk",void 0),e._defineProperty(this,"_raw",void 0),this.jwk=t}get raw(){return null==this._raw&&(this._raw=function(e){var t,r;return Za([Ya(Uint8Array.from([1])),Za([ys(e.crv)],160),Za([Ja(new Fa(Uint8Array.from([4]),ot(null!==(t=e.x)&&void 0!==t?t:"","base64url"),ot(null!==(r=e.y)&&void 0!==r?r:"","base64url")))],161)]).subarray()}(this.jwk)),this._raw}toMultihash(){return Te.digest(ql(this))}toCID(){return je.createV1(114,this.toMultihash())}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&nt(this.raw,e.raw)}verify(t,r){var n=this;return e._asyncToGenerator((function*(){return function(e,t,r){return ns.apply(this,arguments)}(n.jwk,r,t)}))()}}class ws{constructor(t){e._defineProperty(this,"type","ECDSA"),e._defineProperty(this,"jwk",void 0),e._defineProperty(this,"publicKey",void 0),e._defineProperty(this,"_raw",void 0),this.jwk=t,this.publicKey=new ms({crv:t.crv,ext:t.ext,key_ops:["verify"],kty:"EC",x:t.x,y:t.y})}get raw(){var e,t,r,n,i;return null==this._raw&&(this._raw=(e=this.jwk,Za([Ya(Uint8Array.from([1])),(i=ot(null!==(t=e.d)&&void 0!==t?t:"","base64url"),new Fa(Uint8Array.from([4]),Qa(i),i)),Za([ys(e.crv)],160),Za([Ja(new Fa(Uint8Array.from([4]),ot(null!==(r=e.x)&&void 0!==r?r:"","base64url"),ot(null!==(n=e.y)&&void 0!==n?n:"","base64url")))],161)]).subarray())),this._raw}equals(e){return null!=e&&e.raw instanceof Uint8Array&&nt(this.raw,e.raw)}sign(t){var r=this;return e._asyncToGenerator((function*(){return function(e,t){return rs.apply(this,arguments)}(r.jwk,t)}))()}}var bs=64;function _s(){var e=_o.utils.randomPrivateKey(),t=_o.getPublicKey(e),r=function(e,t){for(var r=new Uint8Array(bs),n=0;n<32;n++)r[n]=e[n],r[32+n]=t[n];return r}(e,t);return{privateKey:r,publicKey:t}}class Ss{constructor(t){e._defineProperty(this,"type","Ed25519"),e._defineProperty(this,"raw",void 0),this.raw=xs(t,32)}toMultihash(){return Te.digest(ql(this))}toCID(){return je.createV1(114,this.toMultihash())}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&nt(this.raw,e.raw)}verify(e,t){return function(e,t,r){return _o.verify(t,r instanceof Uint8Array?r:r.subarray(),e)}(this.raw,t,e)}}class Ps{constructor(t,r){e._defineProperty(this,"type","Ed25519"),e._defineProperty(this,"raw",void 0),e._defineProperty(this,"publicKey",void 0),this.raw=xs(t,bs),this.publicKey=new Ss(r)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&nt(this.raw,e.raw)}sign(e){return t=this.raw,r=e,n=t.subarray(0,32),_o.sign(r instanceof Uint8Array?r:r.subarray(),n);var t,r,n}}function Es(e){if(e.length>bs){var t=(e=xs(e,96)).subarray(0,bs),r=e.subarray(bs,e.length);return new Ps(t,r)}var n=(e=xs(e,bs)).subarray(0,bs),i=e.subarray(32);return new Ps(n,i)}function As(e){return e=xs(e,32),new Ss(e)}function ks(){return ks=e._asyncToGenerator((function*(){var{privateKey:e,publicKey:t}=_s();return new Ps(e,t)})),ks.apply(this,arguments)}function xs(e,t){if((e=Uint8Array.from(null!=e?e:[])).length!==t)throw new ea("Key must be a Uint8Array of length ".concat(t,", got ").concat(e.length));return e}var Ts=new Float32Array([-0]),Is=new Uint8Array(Ts.buffer);function Cs(e,t,r){Ts[0]=e,t[r]=Is[0],t[r+1]=Is[1],t[r+2]=Is[2],t[r+3]=Is[3]}var Bs=new Float64Array([-0]),Ns=new Uint8Array(Bs.buffer);function Ds(e,t,r){Bs[0]=e,t[r]=Ns[0],t[r+1]=Ns[1],t[r+2]=Ns[2],t[r+3]=Ns[3],t[r+4]=Ns[4],t[r+5]=Ns[5],t[r+6]=Ns[6],t[r+7]=Ns[7]}var Gs=BigInt(Number.MAX_SAFE_INTEGER),Rs=BigInt(Number.MIN_SAFE_INTEGER);class Os{constructor(t,r){e._defineProperty(this,"lo",void 0),e._defineProperty(this,"hi",void 0),this.lo=0|t,this.hi=0|r}toNumber(){if(!(arguments.length>0&&void 0!==arguments[0]&&arguments[0])&&this.hi>>>31>0){var e=1+~this.lo>>>0,t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(e+4294967296*t)}return this.lo+4294967296*this.hi}toBigInt(){if(arguments.length>0&&void 0!==arguments[0]&&arguments[0])return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31!=0){var e=1+~this.lo>>>0,t=~this.hi>>>0;return 0===e&&(t=t+1>>>0),-(BigInt(e)+(BigInt(t)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this.toBigInt(e).toString()}zzEncode(){var e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){var e=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){var e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,r=this.hi>>>24;return 0===r?0===t?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}static fromBigInt(e){if(0n===e)return Ls;if(e<Gs&&e>Rs)return this.fromNumber(Number(e));var t=e<0n;t&&(e=-e);var r=e>>32n,n=e-(r<<32n);return t&&(r=0n|~r,n=0n|~n,++n>Ms&&(n=0n,++r>Ms&&(r=0n))),new Os(Number(n),Number(r))}static fromNumber(e){if(0===e)return Ls;var t=e<0;t&&(e=-e);var r=e>>>0,n=(e-r)/4294967296>>>0;return t&&(n=~n>>>0,r=~r>>>0,++r>4294967295&&(r=0,++n>4294967295&&(n=0))),new Os(r,n)}static from(e){return"number"==typeof e?Os.fromNumber(e):"bigint"==typeof e?Os.fromBigInt(e):"string"==typeof e?Os.fromBigInt(BigInt(e)):null!=e.low||null!=e.high?new Os(e.low>>>0,e.high>>>0):Ls}}var Ls=new Os(0,0);Ls.toBigInt=function(){return 0n},Ls.zzEncode=Ls.zzDecode=function(){return this},Ls.length=function(){return 1};var Ms=4294967296n;function js(e,t,r){for(var n,i,o=r,a=0;a<e.length;++a)(n=e.charCodeAt(a))<128?t[r++]=n:n<2048?(t[r++]=n>>6|192,t[r++]=63&n|128):55296==(64512&n)&&56320==(64512&(i=e.charCodeAt(a+1)))?(n=65536+((1023&n)<<10)+(1023&i),++a,t[r++]=n>>18|240,t[r++]=n>>12&63|128,t[r++]=n>>6&63|128,t[r++]=63&n|128):(t[r++]=n>>12|224,t[r++]=n>>6&63|128,t[r++]=63&n|128);return r-o}function Fs(e,t){return RangeError("index out of range: ".concat(e.pos," + ").concat(null!=t?t:1," > ").concat(e.len))}function Us(e,t){return(e[t-4]|e[t-3]<<8|e[t-2]<<16|e[t-1]<<24)>>>0}class zs{constructor(t){e._defineProperty(this,"buf",void 0),e._defineProperty(this,"pos",void 0),e._defineProperty(this,"len",void 0),e._defineProperty(this,"_slice",Uint8Array.prototype.subarray),this.buf=t,this.pos=0,this.len=t.length}uint32(){var e=4294967295;if(e=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128)return e;if(e=(e|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128)return e;if((this.pos+=5)>this.len)throw this.pos=this.len,Fs(this,10);return e}int32(){return 0|this.uint32()}sint32(){var e=this.uint32();return e>>>1^-(1&e)}bool(){return 0!==this.uint32()}fixed32(){if(this.pos+4>this.len)throw Fs(this,4);return Us(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw Fs(this,4);return 0|Us(this.buf,this.pos+=4)}float(){if(this.pos+4>this.len)throw Fs(this,4);var e=function(e,t){return Is[0]=e[t],Is[1]=e[t+1],Is[2]=e[t+2],Is[3]=e[t+3],Ts[0]}(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw Fs(this,4);var e=function(e,t){return Ns[0]=e[t],Ns[1]=e[t+1],Ns[2]=e[t+2],Ns[3]=e[t+3],Ns[4]=e[t+4],Ns[5]=e[t+5],Ns[6]=e[t+6],Ns[7]=e[t+7],Bs[0]}(this.buf,this.pos);return this.pos+=8,e}bytes(){var e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw Fs(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){var e=this.bytes();return function(e,t,r){var n;if(r-t<1)return"";for(var i,o=[],a=0;t<r;)(i=e[t++])<128?o[a++]=i:i>191&&i<224?o[a++]=(31&i)<<6|63&e[t++]:i>239&&i<365?(i=((7&i)<<18|(63&e[t++])<<12|(63&e[t++])<<6|63&e[t++])-65536,o[a++]=55296+(i>>10),o[a++]=56320+(1023&i)):o[a++]=(15&i)<<12|(63&e[t++])<<6|63&e[t++],a>8191&&((null!=n?n:n=[]).push(String.fromCharCode.apply(String,o)),a=0);return null!=n?(a>0&&n.push(String.fromCharCode.apply(String,o.slice(0,a))),n.join("")):String.fromCharCode.apply(String,o.slice(0,a))}(e,0,e.length)}skip(e){if("number"==typeof e){if(this.pos+e>this.len)throw Fs(this,e);this.pos+=e}else do{if(this.pos>=this.len)throw Fs(this)}while(128&this.buf[this.pos++]);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(e=7&this.uint32());)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error("invalid wire type ".concat(e," at offset ").concat(this.pos))}return this}readLongVarint(){var e=new Os(0,0),t=0;if(!(this.len-this.pos>4)){for(;t<3;++t){if(this.pos>=this.len)throw Fs(this);if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(127&this.buf[this.pos++])<<7*t)>>>0,e}for(;t<4;++t)if(e.lo=(e.lo|(127&this.buf[this.pos])<<7*t)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(127&this.buf[this.pos])<<28)>>>0,e.hi=(e.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return e;if(t=0,this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw Fs(this);if(e.hi=(e.hi|(127&this.buf[this.pos])<<7*t+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw Fs(this,8);var e=Us(this.buf,this.pos+=4),t=Us(this.buf,this.pos+=4);return new Os(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){var e=mt(this.buf,this.pos);return this.pos+=yt(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}function Vs(e,t,r){var n=function(e){return new zs(e instanceof Uint8Array?e:e.subarray())}(e);return t.decode(n,void 0,r)}class qs{constructor(t,r,n){e._defineProperty(this,"fn",void 0),e._defineProperty(this,"len",void 0),e._defineProperty(this,"next",void 0),e._defineProperty(this,"val",void 0),this.fn=t,this.len=r,this.next=void 0,this.val=n}}function Hs(){}class Ks{constructor(t){e._defineProperty(this,"head",void 0),e._defineProperty(this,"tail",void 0),e._defineProperty(this,"len",void 0),e._defineProperty(this,"next",void 0),this.head=t.head,this.tail=t.tail,this.len=t.len,this.next=t.states}}var Ws,Qs,Ys,Js,Zs,$s,Xs,el,tl=(Ys=Qs=8192,function(e){if(e<1||e>4096)return Ke(e);Ys+e>Qs&&(Ws=Ke(Qs),Ys=0);var t=Ws.subarray(Ys,Ys+=e);return 7&Ys&&(Ys=1+(7|Ys)),t});class rl{constructor(){e._defineProperty(this,"len",void 0),e._defineProperty(this,"head",void 0),e._defineProperty(this,"tail",void 0),e._defineProperty(this,"states",void 0),this.len=0,this.head=new qs(Hs,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new qs(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new ol((e>>>=0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(al,10,Os.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){var t=Os.fromBigInt(e);return this._push(al,t.length(),t)}uint64Number(e){return this._push(gt,yt(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){var t=Os.fromBigInt(e).zzEncode();return this._push(al,t.length(),t)}sint64Number(e){var t=Os.fromNumber(e).zzEncode();return this._push(al,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(nl,1,e?1:0)}fixed32(e){return this._push(sl,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){var t=Os.fromBigInt(e);return this._push(sl,4,t.lo)._push(sl,4,t.hi)}fixed64Number(e){var t=Os.fromNumber(e);return this._push(sl,4,t.lo)._push(sl,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(Cs,4,e)}double(e){return this._push(Ds,8,e)}bytes(e){var t=e.length>>>0;return 0===t?this._push(nl,1,0):this.uint32(t)._push(ll,t,e)}string(e){var t=function(e){for(var t=0,r=0,n=0;n<e.length;++n)(r=e.charCodeAt(n))<128?t+=1:r<2048?t+=2:55296==(64512&r)&&56320==(64512&e.charCodeAt(n+1))?(++n,t+=4):t+=3;return t}(e);return 0!==t?this.uint32(t)._push(js,t,e):this._push(nl,1,0)}fork(){return this.states=new Ks(this),this.head=this.tail=new qs(Hs,0,0),this.len=0,this}reset(){return null!=this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new qs(Hs,0,0),this.len=0),this}ldelim(){var e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),0!==r&&(this.tail.next=e.next,this.tail=t,this.len+=r),this}finish(){for(var e,t=this.head.next,r=(e=this.len,null!=globalThis.Buffer?Ke(e):tl(e)),n=0;null!=t;)t.fn(t.val,r,n),n+=t.len,t=t.next;return r}}function nl(e,t,r){t[r]=255&e}function il(e,t,r){for(;e>127;)t[r++]=127&e|128,e>>>=7;t[r]=e}class ol extends qs{constructor(t,r){super(il,t,r),e._defineProperty(this,"next",void 0),this.next=void 0}}function al(e,t,r){for(;0!==e.hi;)t[r++]=127&e.lo|128,e.lo=(e.lo>>>7|e.hi<<25)>>>0,e.hi>>>=7;for(;e.lo>127;)t[r++]=127&e.lo|128,e.lo=e.lo>>>7;t[r++]=e.lo}function sl(e,t,r){t[r]=255&e,t[r+1]=e>>>8&255,t[r+2]=e>>>16&255,t[r+3]=e>>>24}function ll(e,t,r){t.set(e,r)}function cl(e,t,r){t.set(e,r)}function ul(e,t,r){e.length<40?js(e,t,r):null!=t.utf8Write?t.utf8Write(e,r):t.set(ot(e),r)}function dl(e,t){var r=new rl;return t.encode(e,r,{lengthDelimited:!1}),r.finish()}function hl(e,t,r,n){return{name:e,type:t,encode:r,decode:n}}function pl(e){function t(t){if(null==e[t.toString()])throw new Error("Invalid enum value");return e[t]}return hl("enum",Js.VARINT,(function(e,r){var n=t(e);r.int32(n)}),(function(e){return t(e.int32())}))}function fl(e,t){return hl("message",Js.LENGTH_DELIMITED,e,t)}null!=globalThis.Buffer&&(rl.prototype.bytes=function(e){var t=e.length>>>0;return this.uint32(t),t>0&&this._push(cl,t,e),this},rl.prototype.string=function(e){var t=globalThis.Buffer.byteLength(e);return this.uint32(t),t>0&&this._push(ul,t,e),this}),function(e){e[e.VARINT=0]="VARINT",e[e.BIT64=1]="BIT64",e[e.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",e[e.START_GROUP=3]="START_GROUP",e[e.END_GROUP=4]="END_GROUP",e[e.BIT32=5]="BIT32"}(Js||(Js={}));class vl extends Error{constructor(){super(...arguments),e._defineProperty(this,"code","ERR_MAX_LENGTH"),e._defineProperty(this,"name","MaxLengthError")}}class yl extends Error{constructor(){super(...arguments),e._defineProperty(this,"code","ERR_MAX_SIZE"),e._defineProperty(this,"name","MaxSizeError")}}function gl(e){if(isNaN(e)||e<=0)throw new ea("random bytes length must be a Number bigger than 0");return Fr(e)}!function(e){e.RSA="RSA",e.Ed25519="Ed25519",e.secp256k1="secp256k1",e.ECDSA="ECDSA"}(Zs||(Zs={})),function(e){e[e.RSA=0]="RSA",e[e.Ed25519=1]="Ed25519",e[e.secp256k1=2]="secp256k1",e[e.ECDSA=3]="ECDSA"}($s||($s={})),function(e){e.codec=()=>pl($s)}(Zs||(Zs={})),function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Zs.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.Type=Zs.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(Xs||(Xs={})),function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.Type&&(t.uint32(8),Zs.codec().encode(e.Type,t)),null!=e.Data&&(t.uint32(18),t.bytes(e.Data)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.Type=Zs.codec().decode(e);break;case 2:r.Data=e.bytes();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(el||(el={}));class ml extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"An error occurred while signing a message"),this.name="SigningError"}}class wl extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"An error occurred while verifying a message"),this.name="VerificationError"}}class bl extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Missing Web Crypto API"),this.name="WebCryptoMissingError"}}var _l={get(){var e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:globalThis).crypto;if(null==(null==e?void 0:e.subtle))throw new bl("Missing Web Crypto API. The most likely cause of this error is that this page is being accessed from an insecure context (i.e. not HTTPS). For more information and possible resolutions see https://github.com/libp2p/js-libp2p/blob/main/packages/crypto/README.md#web-crypto-api");return e}};let Sl=class{constructor(t,r){e._defineProperty(this,"type","RSA"),e._defineProperty(this,"jwk",void 0),e._defineProperty(this,"_raw",void 0),e._defineProperty(this,"_multihash",void 0),this.jwk=t,this._multihash=r}get raw(){return null==this._raw&&(this._raw=kl(this.jwk)),this._raw}toMultihash(){return this._multihash}toCID(){return je.createV1(114,this._multihash)}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&nt(this.raw,e.raw)}verify(e,t){return function(e,t,r){return Nl.apply(this,arguments)}(this.jwk,t,e)}},Pl=class{constructor(t,r){e._defineProperty(this,"type","RSA"),e._defineProperty(this,"jwk",void 0),e._defineProperty(this,"_raw",void 0),e._defineProperty(this,"publicKey",void 0),this.jwk=t,this.publicKey=r}get raw(){return null==this._raw&&(this._raw=function(e){if(null==e.n||null==e.e||null==e.d||null==e.p||null==e.q||null==e.dp||null==e.dq||null==e.qi)throw new ea("JWK was missing components");return Za([Ya(Uint8Array.from([0])),Ya(ot(e.n,"base64url")),Ya(ot(e.e,"base64url")),Ya(ot(e.d,"base64url")),Ya(ot(e.p,"base64url")),Ya(ot(e.q,"base64url")),Ya(ot(e.dp,"base64url")),Ya(ot(e.dq,"base64url")),Ya(ot(e.qi,"base64url"))]).subarray()}(this.jwk)),this._raw}equals(e){return null!=e&&e.raw instanceof Uint8Array&&nt(this.raw,e.raw)}sign(e){return function(e,t){return Bl.apply(this,arguments)}(this.jwk,e)}};var El=8192,Al=Uint8Array.from([48,13,6,9,42,134,72,134,247,13,1,1,1,5,0]);function kl(e){if(null==e.n||null==e.e)throw new ea("JWK was missing components");return Za([Al,Ja(Za([Ya(ot(e.n,"base64url")),Ya(ot(e.e,"base64url"))]))]).subarray()}function xl(e){var t=function(e){return{n:Ze(e[1],"base64url"),e:Ze(e[2],"base64url"),d:Ze(e[3],"base64url"),p:Ze(e[4],"base64url"),q:Ze(e[5],"base64url"),dp:Ze(e[6],"base64url"),dq:Ze(e[7],"base64url"),qi:Ze(e[8],"base64url"),kty:"RSA"}}(e);return function(e){if(function(e){if("RSA"!==e.kty)throw new ea("invalid key type");if(null==e.n)throw new ea("invalid key modulus");var t=ot(e.n,"base64url");return 8*t.length}(e)>El)throw new ea("Key size is too large");var t=function(e){if(null==e)throw new ea("Missing key parameter");return{privateKey:e,publicKey:{kty:e.kty,n:e.n,e:e.e}}}(e),r=Po(Xs.encode({Type:Zs.RSA,Data:kl(t.publicKey)})),n=Ee(18,r);return new Pl(t.privateKey,new Sl(t.publicKey,n))}(t)}function Tl(e,t,r){var n=function(e){var t=Ha(e[1],{offset:0});return{kty:"RSA",n:Ze(t[0],"base64url"),e:Ze(t[1],"base64url")}}(e);null==r&&(r=Ee(18,Po(Xs.encode({Type:Zs.RSA,Data:t}))));return new Sl(n,r)}function Il(){return Il=e._asyncToGenerator((function*(e){if(e>El)throw new ea("Key size is too large");var t=yield function(e){return Cl.apply(this,arguments)}(e),r=Ee(18,Po(Xs.encode({Type:Zs.RSA,Data:kl(t.publicKey)})));return new Pl(t.privateKey,new Sl(t.publicKey,r))})),Il.apply(this,arguments)}function Cl(){return Cl=e._asyncToGenerator((function*(e){var t=yield _l.get().subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:new Uint8Array([1,0,1]),hash:{name:"SHA-256"}},!0,["sign","verify"]),r=yield function(e){return Dl.apply(this,arguments)}(t);return{privateKey:r[0],publicKey:r[1]}})),Cl.apply(this,arguments)}function Bl(){return(Bl=e._asyncToGenerator((function*(e,t){var r=yield _l.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["sign"]),n=yield _l.get().subtle.sign({name:"RSASSA-PKCS1-v1_5"},r,t instanceof Uint8Array?t:t.subarray());return new Uint8Array(n,0,n.byteLength)}))).apply(this,arguments)}function Nl(){return Nl=e._asyncToGenerator((function*(e,t,r){var n=yield _l.get().subtle.importKey("jwk",e,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!1,["verify"]);return _l.get().subtle.verify({name:"RSASSA-PKCS1-v1_5"},n,t,r instanceof Uint8Array?r:r.subarray())})),Nl.apply(this,arguments)}function Dl(){return Dl=e._asyncToGenerator((function*(e){if(null==e.privateKey||null==e.publicKey)throw new ea("Private and public key are required");return Promise.all([_l.get().subtle.exportKey("jwk",e.privateKey),_l.get().subtle.exportKey("jwk",e.publicKey)])})),Dl.apply(this,arguments)}function Gl(e){return null!=e&&("function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally)}class Rl{constructor(t){e._defineProperty(this,"type","secp256k1"),e._defineProperty(this,"raw",void 0),e._defineProperty(this,"_key",void 0),this._key=function(e){try{return Zi.ProjectivePoint.fromHex(e),e}catch(e){throw new ta(String(e))}}(t),this.raw=function(e){var t=Zi.ProjectivePoint.fromHex(e).toRawBytes(!0);return t}(this._key)}toMultihash(){return Te.digest(ql(this))}toCID(){return je.createV1(114,this.toMultihash())}toString(){return j.encode(this.toMultihash().bytes).substring(1)}equals(e){return null!=e&&e.raw instanceof Uint8Array&&nt(this.raw,e.raw)}verify(e,t){return function(e,t,r){var n=De.digest(r instanceof Uint8Array?r:r.subarray());if(Gl(n))return n.then((r=>{var{digest:n}=r;return Zi.verify(t,n,e)})).catch((e=>{throw new wl(String(e))}));try{return Zi.verify(t,n.digest,e)}catch(e){throw new wl(String(e))}}(this._key,t,e)}}class Ol{constructor(t,r){e._defineProperty(this,"type","secp256k1"),e._defineProperty(this,"raw",void 0),e._defineProperty(this,"publicKey",void 0),this.raw=function(e){try{return Zi.getPublicKey(e,!0),e}catch(e){throw new ra(String(e))}}(t),this.publicKey=new Rl(null!=r?r:function(e){try{return Zi.getPublicKey(e,!0)}catch(e){throw new ra(String(e))}}(t))}equals(e){return null!=e&&e.raw instanceof Uint8Array&&nt(this.raw,e.raw)}sign(e){return function(e,t){var r=De.digest(t instanceof Uint8Array?t:t.subarray());if(Gl(r))return r.then((t=>{var{digest:r}=t;return Zi.sign(r,e).toDERRawBytes()})).catch((e=>{throw new ml(String(e))}));try{return Zi.sign(r.digest,e).toDERRawBytes()}catch(e){throw new ml(String(e))}}(this.raw,e)}}function Ll(e){return new Ol(e)}function Ml(e){return new Rl(e)}function jl(){return(jl=e._asyncToGenerator((function*(){var e=Zi.utils.randomPrivateKey();return new Ol(e)}))).apply(this,arguments)}function Fl(e,t){return Ul.apply(this,arguments)}function Ul(){return Ul=e._asyncToGenerator((function*(e,t){if("Ed25519"===e)return function(){return ks.apply(this,arguments)}();if("secp256k1"===e)return function(){return jl.apply(this,arguments)}();if("RSA"===e)return function(e){return Il.apply(this,arguments)}(function(e){if(null==e)return 2048;return parseInt(e,10)}(t));if("ECDSA"===e)return function(){return gs.apply(this,arguments)}(function(e){if("P-256"===e||null==e)return"P-256";if("P-384"===e)return"P-384";if("P-521"===e)return"P-521";throw new ea("Unsupported curve, should be P-256, P-384 or P-521")}(t));throw new ka})),Ul.apply(this,arguments)}function zl(e,t){var{Type:r,Data:n}=Xs.decode(e),i=null!=n?n:new Uint8Array;switch(r){case Zs.RSA:return function(e,t){if(e.byteLength>=1062)throw new ta("Key size is too large");return Tl(Ha(e,{offset:0}),e,t)}(i,t);case Zs.Ed25519:return As(i);case Zs.secp256k1:return Ml(i);case Zs.ECDSA:return fs(i);default:throw new ka}}function Vl(e){var{Type:t,Data:r}=Xs.decode(e.digest),n=null!=r?r:new Uint8Array;switch(t){case Zs.Ed25519:return As(n);case Zs.secp256k1:return Ml(n);case Zs.ECDSA:return fs(n);default:throw new ka}}function ql(e){return Xs.encode({Type:Zs[e.type],Data:e.raw})}function Hl(e){var t,r=el.decode(e),n=null!==(t=r.Data)&&void 0!==t?t:new Uint8Array;switch(r.Type){case Zs.RSA:return xl(Ha(n));case Zs.Ed25519:return Es(n);case Zs.secp256k1:return Ll(n);case Zs.ECDSA:return function(e){return ps(Ha(e))}(n);default:throw new ka}}function Kl(e){var t;if(e.byteLength===bs)return Es(e);if(32===e.byteLength)return Ll(e);var r=Ha(e),n=null===(t=r[2])||void 0===t?void 0:t[0];if(n===$a||n===Xa||n===es)return ps(r);if(r.length>8)return xl(r);throw new ea("Could not extract private key from raw bytes")}function Wl(e){return el.encode({Type:Zs[e.type],Data:e.raw})}function Ql(e){return Yl.apply(this,arguments)}function Yl(){return(Yl=e._asyncToGenerator((function*(e){if("RSA"===e.type)return{privateKey:yield crypto.subtle.importKey("jwk",e.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["sign"]),publicKey:yield crypto.subtle.importKey("jwk",e.publicKey.jwk,{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}},!0,["verify"])};var t,r;if("ECDSA"===e.type)return{privateKey:yield crypto.subtle.importKey("jwk",e.jwk,{name:"ECDSA",namedCurve:null!==(t=e.jwk.crv)&&void 0!==t?t:"P-256"},!0,["sign"]),publicKey:yield crypto.subtle.importKey("jwk",e.publicKey.jwk,{name:"ECDSA",namedCurve:null!==(r=e.publicKey.jwk.crv)&&void 0!==r?r:"P-256"},!0,["verify"])};throw new ea("Only RSA and ECDSA keys are supported")}))).apply(this,arguments)}var Jl=Symbol.for("nodejs.util.inspect.custom");class Zl{constructor(t){e._defineProperty(this,"type",void 0),e._defineProperty(this,"multihash",void 0),e._defineProperty(this,"publicKey",void 0),e._defineProperty(this,"string",void 0),e._defineProperty(this,Ho,!0),this.type=t.type,this.multihash=t.multihash,Object.defineProperty(this,"string",{enumerable:!1,writable:!0})}get[Symbol.toStringTag](){return"PeerId(".concat(this.toString(),")")}toString(){return null==this.string&&(this.string=j.encode(this.multihash.bytes).slice(1)),this.string}toMultihash(){return this.multihash}toCID(){return je.createV1(114,this.multihash)}toJSON(){return this.toString()}equals(e){var t;if(null==e)return!1;if(e instanceof Uint8Array)return nt(this.multihash.bytes,e);if("string"==typeof e)return this.toString()===e;if(null!=(null==e||null===(t=e.toMultihash())||void 0===t?void 0:t.bytes))return nt(this.multihash.bytes,e.toMultihash().bytes);throw new Error("not valid Id")}[Jl](){return"PeerId(".concat(this.toString(),")")}}class $l extends Zl{constructor(t){super(e._objectSpread2(e._objectSpread2({},t),{},{type:"RSA"})),e._defineProperty(this,"type","RSA"),e._defineProperty(this,"publicKey",void 0),this.publicKey=t.publicKey}}class Xl extends Zl{constructor(t){super(e._objectSpread2(e._objectSpread2({},t),{},{type:"Ed25519"})),e._defineProperty(this,"type","Ed25519"),e._defineProperty(this,"publicKey",void 0),this.publicKey=t.publicKey}}class ec extends Zl{constructor(t){super(e._objectSpread2(e._objectSpread2({},t),{},{type:"secp256k1"})),e._defineProperty(this,"type","secp256k1"),e._defineProperty(this,"publicKey",void 0),this.publicKey=t.publicKey}}class tc{constructor(t){e._defineProperty(this,"type","url"),e._defineProperty(this,"multihash",void 0),e._defineProperty(this,"publicKey",void 0),e._defineProperty(this,"url",void 0),e._defineProperty(this,Ho,!0),this.url=t.toString(),this.multihash=Te.digest(ot(this.url))}[Jl](){return"PeerId(".concat(this.url,")")}toString(){return this.toCID().toString()}toMultihash(){return this.multihash}toCID(){return je.createV1(2336,this.toMultihash())}toJSON(){return this.toString()}equals(e){return null!=e&&(e instanceof Uint8Array&&(e=Ze(e)),e.toString()===this.toString())}}function rc(e,t){if("1"!==e.charAt(0)&&"Q"!==e.charAt(0)){if(e.startsWith("k51qzi5uqu5")||e.startsWith("kzwfwjn5ji4")||e.startsWith("k2k4r8")||e.startsWith("bafz"))return ac(je.parse(e));throw new ea('Please pass a multibase decoder for strings that do not start with "1" or "Q"')}return oc(Ae(j.decode("z".concat(e))))}function nc(e){if("Ed25519"===e.type)return new Xl({multihash:e.toCID().multihash,publicKey:e});if("secp256k1"===e.type)return new ec({multihash:e.toCID().multihash,publicKey:e});if("RSA"===e.type)return new $l({multihash:e.toCID().multihash,publicKey:e});throw new ka}function ic(e){return nc(e.publicKey)}function oc(e){if(function(e){return e.code===De.code}(e))return new $l({multihash:e});if(function(e){return e.code===Te.code}(e))try{var t=Vl(e);if("Ed25519"===t.type)return new Xl({multihash:e,publicKey:t});if("secp256k1"===t.type)return new ec({multihash:e,publicKey:t})}catch(t){var r=Ze(e.digest);return new tc(new URL(r))}throw new fa("Supplied PeerID Multihash is invalid")}function ac(e){if(null==(null==e?void 0:e.multihash)||null==e.version||1===e.version&&114!==e.code&&2336!==e.code)throw new pa("Supplied PeerID CID is invalid");if(2336===e.code){var t=Ze(e.multihash.digest);return new tc(new URL(t))}return oc(e.multihash)}var sc=Uint32Array.from([1732584193,4023233417,2562383102,271733878,3285377520]),lc=new Uint32Array(80);class cc extends Vr{constructor(){super(64,20,8,!1),this.A=0|sc[0],this.B=0|sc[1],this.C=0|sc[2],this.D=0|sc[3],this.E=0|sc[4]}get(){var{A:e,B:t,C:r,D:n,E:i}=this;return[e,t,r,n,i]}set(e,t,r,n,i){this.A=0|e,this.B=0|t,this.C=0|r,this.D=0|n,this.E=0|i}process(e,t){for(var r=0;r<16;r++,t+=4)lc[r]=e.getUint32(t,!1);for(var n=16;n<80;n++)lc[n]=mr(lc[n-3]^lc[n-8]^lc[n-14]^lc[n-16],1);for(var{A:i,B:o,C:a,D:s,E:l}=this,c=0;c<80;c++){var u=void 0,d=void 0;c<20?(u=Ur(o,a,s),d=1518500249):c<40?(u=o^a^s,d=1859775393):c<60?(u=zr(o,a,s),d=2400959708):(u=o^a^s,d=3395469782);var h=mr(i,5)+u+l+d+lc[c]|0;l=s,s=a,a=mr(o,30),o=i,i=h}i=i+this.A|0,o=o+this.B|0,a=a+this.C|0,s=s+this.D|0,l=l+this.E|0,this.set(i,o,a,s,l)}roundClean(){vr(lc)}destroy(){this.set(0,0,0,0,0),vr(this.buffer)}}var uc=jr((()=>new cc)),dc=Uint8Array.from([7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8]),hc=(()=>Uint8Array.from(new Array(16).fill(0).map(((e,t)=>t))))(),pc=(()=>hc.map((e=>(9*e+5)%16)))(),fc=(()=>{for(var e=[[hc],[pc]],t=0;t<4;t++)for(var r of e)r.push(r[t].map((e=>dc[e])));return e})(),vc=(()=>fc[0])(),yc=(()=>fc[1])(),gc=[[11,14,15,12,5,8,7,9,11,13,14,15,6,7,9,8],[12,13,11,15,6,9,9,7,12,15,11,13,7,8,7,7],[13,15,14,11,7,7,6,8,13,14,13,12,5,5,6,9],[14,11,12,14,8,6,5,5,15,12,15,14,9,9,8,6],[15,12,13,13,9,5,8,6,14,11,12,11,8,6,5,5]].map((e=>Uint8Array.from(e))),mc=vc.map(((e,t)=>e.map((e=>gc[t][e])))),wc=yc.map(((e,t)=>e.map((e=>gc[t][e])))),bc=Uint32Array.from([0,1518500249,1859775393,2400959708,2840853838]),_c=Uint32Array.from([1352829926,1548603684,1836072691,2053994217,0]);function Sc(e,t,r,n){return 0===e?t^r^n:1===e?t&r|~t&n:2===e?(t|~r)^n:3===e?t&n|r&~n:t^(r|~n)}var Pc=new Uint32Array(16);class Ec extends Vr{constructor(){super(64,20,8,!0),this.h0=1732584193,this.h1=-271733879,this.h2=-1732584194,this.h3=271733878,this.h4=-1009589776}get(){var{h0:e,h1:t,h2:r,h3:n,h4:i}=this;return[e,t,r,n,i]}set(e,t,r,n,i){this.h0=0|e,this.h1=0|t,this.h2=0|r,this.h3=0|n,this.h4=0|i}process(e,t){for(var r=0;r<16;r++,t+=4)Pc[r]=e.getUint32(t,!0);for(var n=0|this.h0,i=n,o=0|this.h1,a=o,s=0|this.h2,l=s,c=0|this.h3,u=c,d=0|this.h4,h=d,p=0;p<5;p++){for(var f=4-p,v=bc[p],y=_c[p],g=vc[p],m=yc[p],w=mc[p],b=wc[p],_=0;_<16;_++){var S=mr(n+Sc(p,o,s,c)+Pc[g[_]]+v,w[_])+d|0;n=d,d=c,c=0|mr(s,10),s=o,o=S}for(var P=0;P<16;P++){var E=mr(i+Sc(f,a,l,u)+Pc[m[P]]+y,b[P])+h|0;i=h,h=u,u=0|mr(l,10),l=a,a=E}}this.set(this.h1+s+u|0,this.h2+c+h|0,this.h3+d+i|0,this.h4+n+a|0,this.h0+o+l|0)}roundClean(){vr(Pc)}destroy(){this.destroyed=!0,vr(this.buffer),this.set(0,0,0,0,0)}}var Ac=jr((()=>new Ec)),kc={sha1:uc,"sha2-256":Po,"sha2-512":Eo};function xc(e,t,r,n,i){if("sha1"!==i&&"sha2-256"!==i&&"sha2-512"!==i){var o=Object.keys(kc).join(" / ");throw new ea("Hash '".concat(i,"' is unknown or not supported. Must be ").concat(o))}var a=function(e,t,r,n){for(var i,{c:o,dkLen:a,DK:s,PRF:l,PRFSalt:c}=Ao(e,t,r,n),u=new Uint8Array(4),d=yr(u),h=new Uint8Array(l.outputLen),p=1,f=0;f<a;p++,f+=l.outputLen){var v=s.subarray(f,f+l.outputLen);d.setInt32(0,p,!1),(i=c._cloneInto(i)).update(u).digestInto(h),v.set(h.subarray(0,v.length));for(var y=1;y<o;y++){l._cloneInto(i).update(h).digestInto(h);for(var g=0;g<v.length;g++)v[g]^=h[g]}}return ko(l,c,s,i,h)}(kc[i],e,t,{c:r,dkLen:n});return z.encode(a).substring(1)}var Tc="/",Ic=(new TextEncoder).encode(Tc),Cc=Ic[0];class Bc{constructor(t,r){if(e._defineProperty(this,"_buf",void 0),"string"==typeof t)this._buf=ot(t);else{if(!(t instanceof Uint8Array))throw new Error("Invalid key, should be String of Uint8Array");this._buf=t}if(null==r&&(r=!0),r&&this.clean(),0===this._buf.byteLength||this._buf[0]!==Cc)throw new Error("Invalid key")}toString(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"utf8";return Ze(this._buf,e)}uint8Array(){return this._buf}get[Symbol.toStringTag](){return"Key(".concat(this.toString(),")")}static withNamespaces(e){return new Bc(e.join(Tc))}static random(){return new Bc(Math.random().toString().substring(2))}static asKey(e){return e instanceof Uint8Array||"string"==typeof e?new Bc(e):"function"==typeof e.uint8Array?new Bc(e.uint8Array()):null}clean(){if(null!=this._buf&&0!==this._buf.byteLength||(this._buf=Ic),this._buf[0]!==Cc){var e=new Uint8Array(this._buf.byteLength+1);e.fill(Cc,0,1),e.set(this._buf,1),this._buf=e}for(;this._buf.byteLength>1&&this._buf[this._buf.byteLength-1]===Cc;)this._buf=this._buf.subarray(0,-1)}less(e){for(var t=this.list(),r=e.list(),n=0;n<t.length;n++){if(r.length<n+1)return!1;var i=t[n],o=r[n];if(i<o)return!0;if(i>o)return!1}return t.length<r.length}reverse(){return Bc.withNamespaces(this.list().slice().reverse())}namespaces(){return this.list()}baseNamespace(){var e=this.namespaces();return e[e.length-1]}list(){return this.toString().split(Tc).slice(1)}type(){return function(e){var t=e.split(":");if(t.length<2)return"";return t.slice(0,-1).join(":")}(this.baseNamespace())}name(){return e=this.baseNamespace(),(t=e.split(":"))[t.length-1];var e,t}instance(e){return new Bc(this.toString()+":"+e)}path(){var e=this.parent().toString();return e.endsWith(Tc)||(e+=Tc),e+=this.type(),new Bc(e)}parent(){var e=this.list();return 1===e.length?new Bc(Tc):new Bc(e.slice(0,-1).join(Tc))}child(e){return this.toString()===Tc?e:e.toString()===Tc?this:new Bc(this.toString()+e.toString(),!1)}isAncestorOf(e){return e.toString()!==this.toString()&&e.toString().startsWith(this.toString())}isDecendantOf(e){return e.toString()!==this.toString()&&this.toString().startsWith(e.toString())}isTopLevel(){return 1===this.list().length}concat(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return Bc.withNamespaces([...this.namespaces(),...(n=t.map((e=>e.namespaces())),[].concat(...n))]);var n}}function Nc(t){if(null!=t[Symbol.asyncIterator])return e._asyncToGenerator((function*(){var r,n=!1,i=!1;try{for(var o,a=e._asyncIterator(t);n=!(o=yield a.next()).done;n=!1)o.value}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield a.return())}finally{if(i)throw r}}}))();for(var r of t);}function Dc(e){var[t,r]=null!=e[Symbol.asyncIterator]?[e[Symbol.asyncIterator](),Symbol.asyncIterator]:[e[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>t.next(),push:e=>{n.push(e)},next:()=>n.length>0?{done:!1,value:n.shift()}:t.next(),[r](){return this}}}function Gc(t,r){var n=0;if(null!=t[Symbol.asyncIterator])return e._wrapAsyncGenerator((function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;(yield e._awaitAsyncGenerator(r(c,n++)))&&(yield c)}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}))();var i=Dc(t),{value:o,done:a}=i.next();if(!0===a)return function*(){}();var s=r(o,n++);if("function"==typeof s.then)return e._wrapAsyncGenerator((function*(){for(var t of((yield e._awaitAsyncGenerator(s))&&(yield o),i))(yield e._awaitAsyncGenerator(r(t,n++)))&&(yield t)}))();var l=r;return function*(){for(var e of(!0===s&&(yield o),i))l(e,n++)&&(yield e)}()}function Rc(t){if(null!=t[Symbol.asyncIterator])return e._asyncToGenerator((function*(){var r,n=[],i=!1,o=!1;try{for(var a,s=e._asyncIterator(t);i=!(a=yield s.next()).done;i=!1){var l=a.value;n.push(l)}}catch(e){o=!0,r=e}finally{try{i&&null!=s.return&&(yield s.return())}finally{if(o)throw r}}return n}))();var r=[];for(var n of t)r.push(n);return r}function Oc(t,r){return null!=t[Symbol.asyncIterator]?e._wrapAsyncGenerator((function*(){var n=yield e._awaitAsyncGenerator(Rc(t));yield*e._asyncGeneratorDelegate(e._asyncIterator(n.sort(r)))}))():function*(){var e=Rc(t);yield*e.sort(r)}()}function Lc(t,r){return null!=t[Symbol.asyncIterator]?e._wrapAsyncGenerator((function*(){var n=0;if(!(r<1)){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;if(yield c,++n===r)return}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}}))():function*(){var e=0;if(!(r<1))for(var n of t)if(yield n,++e===r)return}()}class Mc{put(e,t,r){return Promise.reject(new Error(".put is not implemented"))}get(e,t){return Promise.reject(new Error(".get is not implemented"))}has(e,t){return Promise.reject(new Error(".has is not implemented"))}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}putMany(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var{key:c,value:u}=s.value;yield e._awaitAsyncGenerator(r.put(c,u,n)),yield c}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}()})).apply(this,arguments)}getMany(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;yield{key:c,value:yield e._awaitAsyncGenerator(r.get(c,n))}}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}()})).apply(this,arguments)}deleteMany(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;yield e._awaitAsyncGenerator(r.delete(c,n)),yield c}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}()})).apply(this,arguments)}batch(){var t,r=this,n=[],i=[];return{put(e,t){n.push({key:e,value:t})},delete(e){i.push(e)},commit:(t=e._asyncToGenerator((function*(e){yield Nc(r.putMany(n,e)),n=[],yield Nc(r.deleteMany(i,e)),i=[]})),function(e){return t.apply(this,arguments)})}}_all(t,r){return e._wrapAsyncGenerator((function*(){throw new Error("._all is not implemented")}))()}_allKeys(t,r){return e._wrapAsyncGenerator((function*(){throw new Error("._allKeys is not implemented")}))()}query(e,t){var r=this._all(e,t);if(null!=e.prefix){var n=e.prefix;r=Gc(r,(e=>e.key.toString().startsWith(n)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>Gc(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>Oc(e,t)),r)),null!=e.offset){var i=0,o=e.offset;r=Gc(r,(()=>i++>=o))}return null!=e.limit&&(r=Lc(r,e.limit)),r}queryKeys(e,t){var r=this._allKeys(e,t);if(null!=e.prefix){var n=e.prefix;r=Gc(r,(e=>e.toString().startsWith(n)))}if(Array.isArray(e.filters)&&(r=e.filters.reduce(((e,t)=>Gc(e,t)),r)),Array.isArray(e.orders)&&(r=e.orders.reduce(((e,t)=>Oc(e,t)),r)),null!=e.offset){var i=e.offset,o=0;r=Gc(r,(()=>o++>=i))}return null!=e.limit&&(r=Lc(r,e.limit)),r}}class jc extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Open failed"),e._defineProperty(this,"name",jc.name),e._defineProperty(this,"code",jc.code)}}e._defineProperty(jc,"name","OpenFailedError"),e._defineProperty(jc,"code","ERR_OPEN_FAILED");class Fc extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Close failed"),e._defineProperty(this,"name",Fc.name),e._defineProperty(this,"code",Fc.code)}}e._defineProperty(Fc,"name","CloseFailedError"),e._defineProperty(Fc,"code","ERR_CLOSE_FAILED");class Uc extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Put failed"),e._defineProperty(this,"name",Uc.name),e._defineProperty(this,"code",Uc.code)}}e._defineProperty(Uc,"name","PutFailedError"),e._defineProperty(Uc,"code","ERR_PUT_FAILED");class zc extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Get failed"),e._defineProperty(this,"name",zc.name),e._defineProperty(this,"code",zc.code)}}e._defineProperty(zc,"name","GetFailedError"),e._defineProperty(zc,"code","ERR_GET_FAILED");class Vc extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Delete failed"),e._defineProperty(this,"name",Vc.name),e._defineProperty(this,"code",Vc.code)}}e._defineProperty(Vc,"name","DeleteFailedError"),e._defineProperty(Vc,"code","ERR_DELETE_FAILED");class qc extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Has failed"),e._defineProperty(this,"name",qc.name),e._defineProperty(this,"code",qc.code)}}e._defineProperty(qc,"name","HasFailedError"),e._defineProperty(qc,"code","ERR_HAS_FAILED");let Hc=class t extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not Found"),e._defineProperty(this,"name",t.name),e._defineProperty(this,"code",t.code)}};e._defineProperty(Hc,"name","NotFoundError"),e._defineProperty(Hc,"code","ERR_NOT_FOUND");let Kc=class t extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Aborted"),e._defineProperty(this,"name",t.name),e._defineProperty(this,"code",t.code)}};e._defineProperty(Kc,"name","AbortError"),e._defineProperty(Kc,"code","ERR_ABORTED");class Wc extends Mc{constructor(){super(),e._defineProperty(this,"data",void 0),this.data=new Map}put(e,t,r){var n;return null==r||null===(n=r.signal)||void 0===n||n.throwIfAborted(),this.data.set(e.toString(),t),e}get(e,t){var r;null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted();var n=this.data.get(e.toString());if(null==n)throw new Hc;return n}has(e,t){var r;return null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),this.data.has(e.toString())}delete(e,t){var r;null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),this.data.delete(e.toString())}*_all(e,t){var r;for(var[n,i]of(null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),this.data.entries())){var o;yield{key:new Bc(n),value:i},null==t||null===(o=t.signal)||void 0===o||o.throwIfAborted()}}*_allKeys(e,t){var r;for(var n of(null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),this.data.keys())){var i;yield new Bc(n),null==t||null===(i=t.signal)||void 0===i||i.throwIfAborted()}}}function Qc(t,r){var n=0;if(null!=t[Symbol.asyncIterator])return e._wrapAsyncGenerator((function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;yield r(c,n++)}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}))();var i=Dc(t),{value:o,done:a}=i.next();if(!0===a)return function*(){}();var s=r(o,n++);if("function"==typeof s.then)return e._wrapAsyncGenerator((function*(){for(var t of(yield yield e._awaitAsyncGenerator(s),i))yield r(t,n++)}))();var l=r;return function*(){for(var e of(yield s,i))yield l(e,n++)}()}function Yc(){var e={};return e.promise=new Promise(((t,r)=>{e.resolve=t,e.reject=r})),e}class Jc{constructor(t){if(e._defineProperty(this,"buffer",void 0),e._defineProperty(this,"mask",void 0),e._defineProperty(this,"top",void 0),e._defineProperty(this,"btm",void 0),e._defineProperty(this,"next",void 0),!(t>0)||t-1&t)throw new Error("Max size for a FixedFIFO should be a power of two");this.buffer=new Array(t),this.mask=t-1,this.top=0,this.btm=0,this.next=null}push(e){return void 0===this.buffer[this.top]&&(this.buffer[this.top]=e,this.top=this.top+1&this.mask,!0)}shift(){var e=this.buffer[this.btm];if(void 0!==e)return this.buffer[this.btm]=void 0,this.btm=this.btm+1&this.mask,e}isEmpty(){return void 0===this.buffer[this.btm]}}class Zc{constructor(){var t,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e._defineProperty(this,"size",void 0),e._defineProperty(this,"hwm",void 0),e._defineProperty(this,"head",void 0),e._defineProperty(this,"tail",void 0),this.hwm=null!==(t=r.splitLimit)&&void 0!==t?t:16,this.head=new Jc(this.hwm),this.tail=this.head,this.size=0}calculateSize(e){return null!=(null==e?void 0:e.byteLength)?e.byteLength:1}push(e){if(null!=(null==e?void 0:e.value)&&(this.size+=this.calculateSize(e.value)),!this.head.push(e)){var t=this.head;this.head=t.next=new Jc(2*this.head.buffer.length),this.head.push(e)}}shift(){var e,t=this.tail.shift();if(void 0===t&&null!=this.tail.next){var r=this.tail.next;this.tail.next=null,this.tail=r,t=this.tail.shift()}return null!=(null===(e=t)||void 0===e?void 0:e.value)&&(this.size-=this.calculateSize(t.value)),t}isEmpty(){return this.head.isEmpty()}}let $c=class extends Error{constructor(t,r){super(null!=t?t:"The operation was aborted"),e._defineProperty(this,"type",void 0),e._defineProperty(this,"code",void 0),this.type="aborted",this.code=null!=r?r:"ABORT_ERR"}};function Xc(){return function(t,r){r=null!=r?r:{};var n,i,o,a=r.onEnd,s=new Zc,l=Yc(),c=function(){var r=e._asyncToGenerator((function*(){try{return s.isEmpty()?o?{done:!0}:yield new Promise(((e,r)=>{i=o=>{i=null,s.push(o);try{e(t(s))}catch(e){r(e)}return n}})):t(s)}finally{s.isEmpty()&&queueMicrotask((()=>{l.resolve(),l=Yc()}))}}));return function(){return r.apply(this,arguments)}}(),u=e=>null!=i?i(e):(s.push(e),n),d=e=>(s=new Zc,null!=i?i({error:e}):(s.push({error:e}),n)),h=e=>{var t;if(o)return n;if(!0!==(null===(t=r)||void 0===t?void 0:t.objectMode)&&null==(null==e?void 0:e.byteLength))throw new Error("objectMode was not true but tried to push non-Uint8Array value");return u({done:!1,value:e})},p=e=>o?n:(o=!0,null!=e?d(e):u({done:!0})),f=()=>(s=new Zc,p(),{done:!0}),v=e=>(p(e),{done:!0});if(n={[Symbol.asyncIterator](){return this},next:c,return:f,throw:v,push:h,end:p,get readableLength(){return s.size},onEmpty:function(){var t=e._asyncToGenerator((function*(e){var t=null==e?void 0:e.signal;if(null==t||t.throwIfAborted(),!s.isEmpty()){var r,n;null!=t&&(r=new Promise(((e,r)=>{n=()=>{r(new $c)},t.addEventListener("abort",n)})));try{yield Promise.race([l.promise,r])}finally{null!=n&&null!=t&&(null==t||t.removeEventListener("abort",n))}}}));function r(e){return t.apply(this,arguments)}return r}()},null==a)return n;var y=n;return n={[Symbol.asyncIterator](){return this},next:()=>y.next(),throw:e=>(y.throw(e),null!=a&&(a(e),a=void 0),{done:!0}),return:()=>(y.return(),null!=a&&(a(),a=void 0),{done:!0}),push:h,end:e=>(y.end(e),null!=a&&(a(e),a=void 0),n),get readableLength(){return y.readableLength},onEmpty:e=>y.onEmpty(e)},n}((e=>{var t=e.shift();if(null==t)return{done:!0};if(null!=t.error)throw t.error;return{done:!0===t.done,value:t.value}}),arguments.length>0&&void 0!==arguments[0]?arguments[0]:{})}let eu=class extends Error{constructor(t,r,n){super(null!=t?t:"The operation was aborted"),e._defineProperty(this,"type",void 0),e._defineProperty(this,"code",void 0),this.type="aborted",this.name=null!=n?n:"AbortError",this.code=null!=r?r:"ABORT_ERR"}};function tu(e,t,r){return ru.apply(this,arguments)}function ru(){return(ru=e._asyncToGenerator((function*(e,t,r){if(null==t)return e;if(t.aborted)return e.catch((()=>{})),Promise.reject(new eu(null==r?void 0:r.errorMessage,null==r?void 0:r.errorCode,null==r?void 0:r.errorName));var n,i=new eu(null==r?void 0:r.errorMessage,null==r?void 0:r.errorCode,null==r?void 0:r.errorName);try{return yield Promise.race([e,new Promise(((e,r)=>{n=()=>{r(i)},t.addEventListener("abort",n)}))])}finally{null!=n&&t.removeEventListener("abort",n)}}))).apply(this,arguments)}let nu=class{constructor(){e._defineProperty(this,"readNext",void 0),e._defineProperty(this,"haveNext",void 0),e._defineProperty(this,"ended",void 0),e._defineProperty(this,"nextResult",void 0),e._defineProperty(this,"error",void 0),this.ended=!1,this.readNext=Yc(),this.haveNext=Yc()}[Symbol.asyncIterator](){return this}next(){var t=this;return e._asyncToGenerator((function*(){if(null==t.nextResult&&(yield t.haveNext.promise),null==t.nextResult)throw new Error("HaveNext promise resolved but nextResult was undefined");var e=t.nextResult;return t.nextResult=void 0,t.readNext.resolve(),t.readNext=Yc(),e}))()}throw(t){var r=this;return e._asyncToGenerator((function*(){return r.ended=!0,r.error=t,null!=t&&(r.haveNext.promise.catch((()=>{})),r.haveNext.reject(t)),{done:!0,value:void 0}}))()}return(){var t=this;return e._asyncToGenerator((function*(){var e={done:!0,value:void 0};return t.ended=!0,t.nextResult=e,t.haveNext.resolve(),e}))()}push(t,r){var n=this;return e._asyncToGenerator((function*(){yield n._push(t,r)}))()}end(t,r){var n=this;return e._asyncToGenerator((function*(){null!=t?yield n.throw(t):yield n._push(void 0,r)}))()}_push(t,r){var n=this;return e._asyncToGenerator((function*(){var e;if(null!=t&&n.ended)throw null!==(e=n.error)&&void 0!==e?e:new Error("Cannot push value onto an ended pushable");for(;null!=n.nextResult;)yield n.readNext.promise;null!=t?n.nextResult={done:!1,value:t}:(n.ended=!0,n.nextResult={done:!0,value:void 0}),n.haveNext.resolve(),n.haveNext=Yc(),yield tu(n.readNext.promise,null==r?void 0:r.signal,r)}))()}};function iu(){return new nu}function ou(){return ou=e._asyncToGenerator((function*(t,r,n){try{yield Promise.all(t.map(function(){var t=e._asyncToGenerator((function*(t){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield l.next()).done;o=!1){var c=s.value;yield r.push(c,{signal:n}),n.throwIfAborted()}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield l.return())}finally{if(a)throw i}}}));return function(e){return t.apply(this,arguments)}}())),yield r.end(void 0,{signal:n})}catch(e){yield r.end(e,{signal:n}).catch((()=>{}))}})),ou.apply(this,arguments)}function au(){return au=e._wrapAsyncGenerator((function*(t){var r=new AbortController,n=iu();(function(e,t,r){return ou.apply(this,arguments)})(t,n,r.signal).catch((()=>{}));try{yield*e._asyncGeneratorDelegate(e._asyncIterator(n),e._awaitAsyncGenerator)}finally{r.abort()}})),au.apply(this,arguments)}function su(){for(var e=[],t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];for(var i of r)null==i[Symbol.asyncIterator]&&e.push(i);return e.length===r.length?function*(e){for(var t of e)yield*t}(e):function(e){return au.apply(this,arguments)}(r)}function lu(e){if(null==e)throw new Error("Empty pipeline");if(hu(e)){var t=e;e=()=>t.source}else if(du(e)||uu(e)){var r=e;e=()=>r}for(var n=arguments.length,i=new Array(n>1?n-1:0),o=1;o<n;o++)i[o-1]=arguments[o];var a=[e,...i];if(a.length>1&&hu(a[a.length-1])&&(a[a.length-1]=a[a.length-1].sink),a.length>2)for(var s=1;s<a.length-1;s++)hu(a[s])&&(a[s]=pu(a[s]));return cu(...a)}var cu=function(){for(var e,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];for(;r.length>0;)e=r.shift()(e);return e},uu=e=>null!=(null==e?void 0:e[Symbol.asyncIterator]),du=e=>null!=(null==e?void 0:e[Symbol.iterator]),hu=e=>null!=e&&(null!=e.sink&&null!=e.source),pu=t=>r=>{var n=t.sink(r);if(null!=(null==n?void 0:n.then)){var i,o=Xc({objectMode:!0});n.then((()=>{o.end()}),(e=>{o.end(e)}));var a=t.source;if(uu(a))i=function(){var t=e._wrapAsyncGenerator((function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(a)),o.end()}));return function(){return t.apply(this,arguments)}}();else{if(!du(a))throw new Error("Unknown duplex source type - must be Iterable or AsyncIterable");i=function*(){yield*a,o.end()}}return su(o,i())}return t.source};new Bc("SHARDING");var fu,vu,yu=1e3,gu=60*yu,mu=60*gu,wu=24*mu,bu=7*wu,_u=365.25*wu;function Su(e,t){try{if("string"==typeof e&&e.length>0)return function(e){if((e=String(e)).length>100)throw new Error("Value exceeds the maximum length of 100 characters.");var t=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return NaN;var r=parseFloat(t[1]),n=(t[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return r*_u;case"weeks":case"week":case"w":return r*bu;case"days":case"day":case"d":return r*wu;case"hours":case"hour":case"hrs":case"hr":case"h":return r*mu;case"minutes":case"minute":case"mins":case"min":case"m":return r*gu;case"seconds":case"second":case"secs":case"sec":case"s":return r*yu;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return r;default:throw new Error("The unit ".concat(n," was matched, but no matching case exists."))}}(e);if("number"==typeof e&&isFinite(e))return null!=t&&t.long?function(e){var t=Math.abs(e);if(t>=wu)return Pu(e,t,wu,"day");if(t>=mu)return Pu(e,t,mu,"hour");if(t>=gu)return Pu(e,t,gu,"minute");if(t>=yu)return Pu(e,t,yu,"second");return"".concat(e," ms")}(e):function(e){var t=Math.abs(e);if(t>=wu)return"".concat(Math.round(e/wu),"d");if(t>=mu)return"".concat(Math.round(e/mu),"h");if(t>=gu)return"".concat(Math.round(e/gu),"m");if(t>=yu)return"".concat(Math.round(e/yu),"s");return"".concat(e,"ms")}(e);throw new Error("Value is not a string or number.")}catch(t){var r=function(e){return"object"==typeof e&&null!==e&&"message"in e}(t)?"".concat(t.message,". value=").concat(JSON.stringify(e)):"An unknown error has occured.";throw new Error(r)}}function Pu(e,t,r,n){var i=t>=1.5*r;return"".concat(Math.round(e/r)," ").concat(n).concat(i?"s":"")}var Eu=function(){try{return localStorage}catch(e){}}();var Au=null!==(fu=null!==(vu=console.debug)&&void 0!==vu?vu:console.log)&&void 0!==fu?fu:()=>{};var ku,xu,Tu=function(e){function t(e){var n,i,o,a=null;function s(){for(var e=arguments.length,r=new Array(e),i=0;i<e;i++)r[i]=arguments[i];if(s.enabled){var o=s,a=Number(new Date),l=a-(n||a);o.diff=l,o.prev=n,o.curr=a,n=a,r[0]=t.coerce(r[0]),"string"!=typeof r[0]&&r.unshift("%O");var c=0;r[0]=r[0].replace(/%([a-zA-Z%])/g,((e,n)=>{if("%%"===e)return"%";c++;var i=t.formatters[n];if("function"==typeof i){var a=r[c];e=i.call(o,a),r.splice(c,1),c--}return e})),t.formatArgs.call(o,r),(o.log||t.log).apply(o,r)}}return s.namespace=e,s.useColors=t.useColors(),s.color=t.selectColor(e),s.extend=r,s.destroy=t.destroy,Object.defineProperty(s,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==a?a:(i!==t.namespaces&&(i=t.namespaces,o=t.enabled(e)),o),set:e=>{a=e}}),"function"==typeof t.init&&t.init(s),s}function r(e,r){var n=t(this.namespace+(void 0===r?":":r)+e);return n.log=this.log,n}function n(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){var t;return e instanceof Error?null!==(t=e.stack)&&void 0!==t?t:e.message:e},t.disable=function(){var e=[...t.names.map(n),...t.skips.map(n).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){var r;t.save(e),t.namespaces=e,t.names=[],t.skips=[];var n=("string"==typeof e?e:"").split(/[\s,]+/),i=n.length;for(r=0;r<i;r++)n[r]&&("-"===(e=n[r].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.substr(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;var r,n;for(r=0,n=t.skips.length;r<n;r++)if(t.skips[r].test(e))return!1;for(r=0,n=t.names.length;r<n;r++)if(t.names[r].test(e))return!0;return!1},t.humanize=Su,t.destroy=function(){},Object.keys(e).forEach((r=>{t[r]=e[r]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){for(var r=0,n=0;n<e.length;n++)r=(r<<5)-r+e.charCodeAt(n),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.setupFormatters(t.formatters),t.enable(t.load()),t}({formatArgs:function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+Su(this.diff),this.useColors){var t="color: "+this.color;e.splice(1,0,t,"color: inherit");var r=0,n=0;e[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(n=r))})),e.splice(n,0,t)}},save:function(e){try{e?null==Eu||Eu.setItem("debug",e):null==Eu||Eu.removeItem("debug")}catch(e){}},load:function(){var e;try{e=null==Eu?void 0:Eu.getItem("debug")}catch(e){}return!e&&void 0!==globalThis.process&&"env"in globalThis.process&&(e=globalThis.process.env.DEBUG),e},useColors:function(){var e,t,r,n;return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||null==(null===(e=navigator.userAgent)||void 0===e?void 0:e.toLowerCase().match(/(edge|trident)\/(\d+)/)))&&("undefined"!=typeof document&&(null===(t=document.documentElement)||void 0===t||null===(t=t.style)||void 0===t?void 0:t.WebkitAppearance)||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&null!=(null===(r=navigator.userAgent)||void 0===r?void 0:r.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&(null===(n=navigator.userAgent)||void 0===n?void 0:n.toLowerCase().match(/applewebkit\/(\d+)/)))},setupFormatters:function(e){e.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},colors:["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],storage:Eu,log:Au});function Iu(){return{forComponent:e=>Cu(e)}}function Cu(e){var t=function(e){var t=()=>{};return t.enabled=!1,t.color="",t.diff=0,t.log=()=>{},t.namespace=e,t.destroy=()=>!0,t.extend=()=>t,t}("".concat(e,":trace"));return Tu.enabled("".concat(e,":trace"))&&null!=Tu.names.map((e=>e.toString())).find((e=>e.includes(":trace")))&&(t=Tu("".concat(e,":trace"))),Object.assign(Tu(e),{error:Tu("".concat(e,":error")),trace:t})}function Bu(e){if(null!=e&&0!==(e=e.trim()).length)return e}Tu.formatters.b=e=>null==e?"undefined":j.baseEncode(e),Tu.formatters.t=e=>null==e?"undefined":k.baseEncode(e),Tu.formatters.m=e=>null==e?"undefined":z.baseEncode(e),Tu.formatters.p=e=>null==e?"undefined":e.toString(),Tu.formatters.c=e=>null==e?"undefined":e.toString(),Tu.formatters.k=e=>null==e?"undefined":e.toString(),Tu.formatters.a=e=>null==e?"undefined":e.toString(),Tu.formatters.e=e=>{var t,r;return null==e?"undefined":null!==(t=null!==(r=Bu(e.stack))&&void 0!==r?r:Bu(e.message))&&void 0!==t?t:e.toString()},Cu("datastore:core:tiered");class Nu{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,r){return Promise.reject(new Error(".put is not implemented"))}putMany(t,r){var n=this;return e._wrapAsyncGenerator((function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var{cid:c,block:u}=s.value;yield e._awaitAsyncGenerator(n.put(c,u,r)),yield c}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}))()}get(e,t){return Promise.reject(new Error(".get is not implemented"))}getMany(t,r){var n=this;return e._wrapAsyncGenerator((function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;yield{cid:c,block:yield e._awaitAsyncGenerator(n.get(c,r))}}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}))()}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}deleteMany(t,r){var n=this;return e._wrapAsyncGenerator((function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;yield e._awaitAsyncGenerator(n.delete(c,r)),yield c}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}))()}getAll(t){return e._wrapAsyncGenerator((function*(){throw new Error(".getAll is not implemented")}))()}}class Du extends Nu{constructor(){super(),e._defineProperty(this,"data",void 0),this.data=new Map}put(e,t,r){var n;return null==r||null===(n=r.signal)||void 0===n||n.throwIfAborted(),this.data.set(k.encode(e.multihash.bytes),t),e}get(e,t){var r;null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted();var n=this.data.get(k.encode(e.multihash.bytes));if(null==n)throw new Hc;return n}has(e,t){var r;return null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),this.data.has(k.encode(e.multihash.bytes))}delete(t,r){var n=this;return e._asyncToGenerator((function*(){var e;null==r||null===(e=r.signal)||void 0===e||e.throwIfAborted(),n.data.delete(k.encode(t.multihash.bytes))}))()}getAll(t){var r=this;return e._wrapAsyncGenerator((function*(){var e;for(var[n,i]of(null==t||null===(e=t.signal)||void 0===e||e.throwIfAborted(),r.data.entries())){var o;yield{cid:je.createV1(re,Ae(k.decode(n))),block:i},null==t||null===(o=t.signal)||void 0===o||o.throwIfAborted()}}))()}}Cu("blockstore:core:tiered"),function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.publicKey&&e.publicKey.byteLength>0&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.payloadType&&e.payloadType.byteLength>0&&(t.uint32(18),t.bytes(e.payloadType)),null!=e.payload&&e.payload.byteLength>0&&(t.uint32(26),t.bytes(e.payload)),null!=e.signature&&e.signature.byteLength>0&&(t.uint32(42),t.bytes(e.signature)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={publicKey:He(0),payloadType:He(0),payload:He(0),signature:He(0)},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.publicKey=e.bytes();break;case 2:r.payloadType=e.bytes();break;case 3:r.payload=e.bytes();break;case 5:r.signature=e.bytes();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(ku||(ku={}));class Gu extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid signature"),this.name="InvalidSignatureError"}}class Ru{constructor(t){e._defineProperty(this,"publicKey",void 0),e._defineProperty(this,"payloadType",void 0),e._defineProperty(this,"payload",void 0),e._defineProperty(this,"signature",void 0),e._defineProperty(this,"marshaled",void 0);var{publicKey:r,payloadType:n,payload:i,signature:o}=t;this.publicKey=r,this.payloadType=n,this.payload=i,this.signature=o}marshal(){return null==this.marshaled&&(this.marshaled=ku.encode({publicKey:ql(this.publicKey),payloadType:this.payloadType,payload:this.payload.subarray(),signature:this.signature})),this.marshaled}equals(e){return null!=e&&nt(this.marshal(),e.marshal())}validate(t){var r=this;return e._asyncToGenerator((function*(){var e=Ou(t,r.payloadType,r.payload);return r.publicKey.verify(e.subarray(),r.signature)}))()}}xu=Ru,e._defineProperty(Ru,"createFromProtobuf",function(){var t=e._asyncToGenerator((function*(e){var t=ku.decode(e),r=zl(t.publicKey);return new xu({publicKey:r,payloadType:t.payloadType,payload:t.payload,signature:t.signature})}));return function(e){return t.apply(this,arguments)}}()),e._defineProperty(Ru,"seal",function(){var t=e._asyncToGenerator((function*(e,t){if(null==t)throw new Error("Missing private key");var r=e.domain,n=e.codec,i=e.marshal(),o=Ou(r,n,i),a=yield t.sign(o.subarray());return new xu({publicKey:t.publicKey,payloadType:n,payload:i,signature:a})}));return function(e,r){return t.apply(this,arguments)}}()),e._defineProperty(Ru,"openAndCertify",function(){var t=e._asyncToGenerator((function*(e,t){var r=yield xu.createFromProtobuf(e);if(!(yield r.validate(t)))throw new Gu("Envelope signature is not valid for the given domain");return r}));return function(e,r){return t.apply(this,arguments)}}());var Ou=(e,t,r)=>{var n=ot(e),i=wt(n.byteLength),o=wt(t.length),a=wt(r.length);return new Fa(i,n,o,t,a,r)};var Lu,Mu,ju=Uint8Array.from([3,1]);!function(e){var t;!function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={multiaddr:He(0)},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();if(i>>>3==1)r.multiaddr=e.bytes();else e.skipType(7&i)}return r}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(e.AddressInfo||(e.AddressInfo={})),e.codec=()=>(null==t&&(t=fl((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==n.lengthDelimited&&r.fork(),null!=t.peerId&&t.peerId.byteLength>0&&(r.uint32(10),r.bytes(t.peerId)),null!=t.seq&&0n!==t.seq&&(r.uint32(16),r.uint64(t.seq)),null!=t.addresses)for(var i of t.addresses)r.uint32(26),e.AddressInfo.codec().encode(i,r);!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i={peerId:He(0),seq:0n,addresses:[]},o=null==r?t.len:t.pos+r;t.pos<o;){var a=t.uint32();switch(a>>>3){case 1:i.peerId=t.bytes();break;case 2:i.seq=t.uint64();break;case 3:var s,l;if(null!=(null===(s=n.limits)||void 0===s?void 0:s.addresses)&&i.addresses.length===n.limits.addresses)throw new vl('Decode error - map field "addresses" had too many elements');i.addresses.push(e.AddressInfo.codec().decode(t,t.uint32(),{limits:null===(l=n.limits)||void 0===l?void 0:l.addresses$}));break;default:t.skipType(7&a)}}return i}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(Lu||(Lu={}));class Fu{constructor(t){e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"multiaddrs",void 0),e._defineProperty(this,"seqNumber",void 0),e._defineProperty(this,"domain",Fu.DOMAIN),e._defineProperty(this,"codec",Fu.CODEC),e._defineProperty(this,"marshaled",void 0);var{peerId:r,multiaddrs:n,seqNumber:i}=t;this.peerId=r,this.multiaddrs=null!=n?n:[],this.seqNumber=null!=i?i:BigInt(Date.now())}marshal(){return null==this.marshaled&&(this.marshaled=Lu.encode({peerId:this.peerId.toMultihash().bytes,seq:BigInt(this.seqNumber),addresses:this.multiaddrs.map((e=>({multiaddr:e.bytes})))})),this.marshaled}equals(e){return e instanceof Fu&&(!!this.peerId.equals(e.peerId)&&(this.seqNumber===e.seqNumber&&!!function(e,t){var r=(e,t)=>e.toString().localeCompare(t.toString());return e.length===t.length&&(t.sort(r),e.sort(r).every(((e,r)=>t[r].equals(e))))}(this.multiaddrs,e.multiaddrs)))}}Mu=Fu,e._defineProperty(Fu,"createFromProtobuf",(e=>{var t,r=Lu.decode(e),n=oc(Ae(r.peerId)),i=(null!==(t=r.addresses)&&void 0!==t?t:[]).map((e=>sr(e.multiaddr))),o=r.seq;return new Mu({peerId:n,multiaddrs:i,seqNumber:o})})),e._defineProperty(Fu,"DOMAIN","libp2p-peer-record"),e._defineProperty(Fu,"CODEC",ju);let Uu=class extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","UnexpectedEOFError"),e._defineProperty(this,"code","ERR_UNEXPECTED_EOF")}};function zu(t,r){var n=iu();t.sink(n).catch(function(){var t=e._asyncToGenerator((function*(e){yield n.end(e)}));return function(e){return t.apply(this,arguments)}}()),t.sink=function(){var t=e._asyncToGenerator((function*(t){var r,i=!1,o=!1;try{for(var a,s=e._asyncIterator(t);i=!(a=yield s.next()).done;i=!1){var l=a.value;yield n.push(l)}}catch(e){o=!0,r=e}finally{try{i&&null!=s.return&&(yield s.return())}finally{if(o)throw r}}yield n.end()}));return function(e){return t.apply(this,arguments)}}();var i=t.source;null!=t.source[Symbol.iterator]?i=t.source[Symbol.iterator]():null!=t.source[Symbol.asyncIterator]&&(i=t.source[Symbol.asyncIterator]());var o,a=new Fa,s={read:function(){var t=e._asyncToGenerator((function*(e){var t;if(null==e||null===(t=e.signal)||void 0===t||t.throwIfAborted(),null==(null==e?void 0:e.bytes)){var{done:r,value:n}=yield tu(i.next(),null==e?void 0:e.signal);return!0===r?null:n}for(;a.byteLength<e.bytes;){var{value:o,done:s}=yield tu(i.next(),null==e?void 0:e.signal);if(!0===s)throw new Uu("unexpected end of input");a.append(o)}var l=a.sublist(0,e.bytes);return a.consume(e.bytes),l}));return function(e){return t.apply(this,arguments)}}(),write:(o=e._asyncToGenerator((function*(e,t){var r;null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),e instanceof Uint8Array?yield n.push(e,t):yield n.push(e.subarray(),t)})),function(e,t){return o.apply(this,arguments)}),unwrap:()=>{if(a.byteLength>0){var n=t.source;t.source=e._wrapAsyncGenerator((function*(){!1===(null==r?void 0:r.yieldBytes)?yield a:yield*e._asyncGeneratorDelegate(e._asyncIterator(a)),yield*e._asyncGeneratorDelegate(e._asyncIterator(n))}))()}return t}};return s}let Vu=class extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidMessageLengthError"),e._defineProperty(this,"code","ERR_INVALID_MSG_LENGTH")}},qu=class extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidDataLengthError"),e._defineProperty(this,"code","ERR_MSG_DATA_TOO_LONG")}},Hu=class extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidDataLengthLengthError"),e._defineProperty(this,"code","ERR_MSG_LENGTH_TOO_LONG")}};function Ku(t){var r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=zu(t,i);null!=i.maxDataLength&&null==i.maxLengthLength&&(i.maxLengthLength=yt(i.maxDataLength));var a,s=null!==(r=null==i?void 0:i.lengthDecoder)&&void 0!==r?r:bt,l=null!==(n=null==i?void 0:i.lengthEncoder)&&void 0!==n?n:wt,c={read:function(){var t=e._asyncToGenerator((function*(t){for(var r=-1,n=new Fa;;){n.append(yield o.read(e._objectSpread2(e._objectSpread2({},t),{},{bytes:1})));try{r=s(n)}catch(e){if(e instanceof RangeError)continue;throw e}if(r<0)throw new Vu("Invalid message length");if(null!=(null==i?void 0:i.maxLengthLength)&&n.byteLength>i.maxLengthLength)throw new Hu("message length length too long");if(r>-1)break}if(null!=(null==i?void 0:i.maxDataLength)&&r>i.maxDataLength)throw new qu("message length too long");return o.read(e._objectSpread2(e._objectSpread2({},t),{},{bytes:r}))}));return function(e){return t.apply(this,arguments)}}(),write:function(){var t=e._asyncToGenerator((function*(e,t){yield o.write(new Fa(l(e.byteLength),e),t)}));return function(e,r){return t.apply(this,arguments)}}(),writeV:(a=e._asyncToGenerator((function*(e,t){var r=new Fa(...e.flatMap((e=>[l(e.byteLength),e])));yield o.write(r,t)})),function(e,t){return a.apply(this,arguments)}),unwrap:()=>o.unwrap()};return c}function Wu(t,r){var n,i=Ku(t,r),o={read:function(){var t=e._asyncToGenerator((function*(e,t){var r=yield i.read(t);return e.decode(r)}));return function(e,r){return t.apply(this,arguments)}}(),write:function(){var t=e._asyncToGenerator((function*(e,t,r){yield i.write(t.encode(e),r)}));return function(e,r,n){return t.apply(this,arguments)}}(),writeV:(n=e._asyncToGenerator((function*(e,t,r){yield i.writeV(e.map((e=>t.encode(e))),r)})),function(e,t,r){return n.apply(this,arguments)}),pb:t=>{return{read:(i=e._asyncToGenerator((function*(e){return o.read(t,e)})),function(e){return i.apply(this,arguments)}),write:(n=e._asyncToGenerator((function*(e,r){return o.write(e,t,r)})),function(e,t){return n.apply(this,arguments)}),writeV:(r=e._asyncToGenerator((function*(e,r){return o.writeV(e,t,r)})),function(e,t){return r.apply(this,arguments)}),unwrap:()=>o};var r,n,i},unwrap:()=>i.unwrap()};return o}var Qu="".concat(Yo,"-circuit-relay");BigInt(1<<17);var Yu,Ju,Zu,$u,Xu,ed,td,rd,nd,id="/libp2p/circuit/relay/0.2.0/hop",od="/libp2p/circuit/relay/0.2.0/stop";!function(e){var t,r;!function(e){e.RESERVE="RESERVE",e.CONNECT="CONNECT",e.STATUS="STATUS"}(e.Type||(e.Type={})),function(e){e[e.RESERVE=0]="RESERVE",e[e.CONNECT=1]="CONNECT",e[e.STATUS=2]="STATUS"}(t||(t={})),function(e){e.codec=()=>pl(t)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=fl((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==n.lengthDelimited&&r.fork(),null!=t.type&&(r.uint32(8),e.Type.codec().encode(t.type,r)),null!=t.peer&&(r.uint32(18),Zu.codec().encode(t.peer,r)),null!=t.reservation&&(r.uint32(26),$u.codec().encode(t.reservation,r)),null!=t.limit&&(r.uint32(34),Xu.codec().encode(t.limit,r)),null!=t.status&&(r.uint32(40),ed.codec().encode(t.status,r)),!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i={},o=null==r?t.len:t.pos+r;t.pos<o;){var a=t.uint32();switch(a>>>3){case 1:i.type=e.Type.codec().decode(t);break;case 2:var s;i.peer=Zu.codec().decode(t,t.uint32(),{limits:null===(s=n.limits)||void 0===s?void 0:s.peer});break;case 3:var l;i.reservation=$u.codec().decode(t,t.uint32(),{limits:null===(l=n.limits)||void 0===l?void 0:l.reservation});break;case 4:var c;i.limit=Xu.codec().decode(t,t.uint32(),{limits:null===(c=n.limits)||void 0===c?void 0:c.limit});break;case 5:i.status=ed.codec().decode(t);break;default:t.skipType(7&a)}}return i}))),r),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(Yu||(Yu={})),function(e){var t,r;!function(e){e.CONNECT="CONNECT",e.STATUS="STATUS"}(e.Type||(e.Type={})),function(e){e[e.CONNECT=0]="CONNECT",e[e.STATUS=1]="STATUS"}(t||(t={})),function(e){e.codec=()=>pl(t)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=fl((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==n.lengthDelimited&&r.fork(),null!=t.type&&(r.uint32(8),e.Type.codec().encode(t.type,r)),null!=t.peer&&(r.uint32(18),Zu.codec().encode(t.peer,r)),null!=t.limit&&(r.uint32(26),Xu.codec().encode(t.limit,r)),null!=t.status&&(r.uint32(32),ed.codec().encode(t.status,r)),!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i={},o=null==r?t.len:t.pos+r;t.pos<o;){var a=t.uint32();switch(a>>>3){case 1:i.type=e.Type.codec().decode(t);break;case 2:var s;i.peer=Zu.codec().decode(t,t.uint32(),{limits:null===(s=n.limits)||void 0===s?void 0:s.peer});break;case 3:var l;i.limit=Xu.codec().decode(t,t.uint32(),{limits:null===(l=n.limits)||void 0===l?void 0:l.limit});break;case 4:i.status=ed.codec().decode(t);break;default:t.skipType(7&a)}}return i}))),r),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(Ju||(Ju={})),function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==r.lengthDelimited&&t.fork(),null!=e.id&&e.id.byteLength>0&&(t.uint32(10),t.bytes(e.id)),null!=e.addrs)for(var n of e.addrs)t.uint32(18),t.bytes(n);!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={id:He(0),addrs:[]},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:n.id=e.bytes();break;case 2:var a;if(null!=(null===(a=r.limits)||void 0===a?void 0:a.addrs)&&n.addrs.length===r.limits.addrs)throw new vl('Decode error - map field "addrs" had too many elements');n.addrs.push(e.bytes());break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(Zu||(Zu={})),function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==r.lengthDelimited&&t.fork(),null!=e.expire&&0n!==e.expire&&(t.uint32(8),t.uint64(e.expire)),null!=e.addrs)for(var n of e.addrs)t.uint32(18),t.bytes(n);null!=e.voucher&&(t.uint32(26),nd.codec().encode(e.voucher,t)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={expire:0n,addrs:[]},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:n.expire=e.uint64();break;case 2:var a;if(null!=(null===(a=r.limits)||void 0===a?void 0:a.addrs)&&n.addrs.length===r.limits.addrs)throw new vl('Decode error - map field "addrs" had too many elements');n.addrs.push(e.bytes());break;case 3:var s;n.voucher=nd.codec().decode(e,e.uint32(),{limits:null===(s=r.limits)||void 0===s?void 0:s.voucher});break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}($u||($u={})),function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.duration&&(t.uint32(8),t.uint32(e.duration)),null!=e.data&&(t.uint32(16),t.uint64(e.data)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.duration=e.uint32();break;case 2:r.data=e.uint64();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(Xu||(Xu={})),function(e){e.UNUSED="UNUSED",e.OK="OK",e.RESERVATION_REFUSED="RESERVATION_REFUSED",e.RESOURCE_LIMIT_EXCEEDED="RESOURCE_LIMIT_EXCEEDED",e.PERMISSION_DENIED="PERMISSION_DENIED",e.CONNECTION_FAILED="CONNECTION_FAILED",e.NO_RESERVATION="NO_RESERVATION",e.MALFORMED_MESSAGE="MALFORMED_MESSAGE",e.UNEXPECTED_MESSAGE="UNEXPECTED_MESSAGE"}(ed||(ed={})),function(e){e[e.UNUSED=0]="UNUSED",e[e.OK=100]="OK",e[e.RESERVATION_REFUSED=200]="RESERVATION_REFUSED",e[e.RESOURCE_LIMIT_EXCEEDED=201]="RESOURCE_LIMIT_EXCEEDED",e[e.PERMISSION_DENIED=202]="PERMISSION_DENIED",e[e.CONNECTION_FAILED=203]="CONNECTION_FAILED",e[e.NO_RESERVATION=204]="NO_RESERVATION",e[e.MALFORMED_MESSAGE=400]="MALFORMED_MESSAGE",e[e.UNEXPECTED_MESSAGE=401]="UNEXPECTED_MESSAGE"}(td||(td={})),function(e){e.codec=()=>pl(td)}(ed||(ed={})),function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.relay&&e.relay.byteLength>0&&(t.uint32(10),t.bytes(e.relay)),null!=e.peer&&e.peer.byteLength>0&&(t.uint32(18),t.bytes(e.peer)),null!=e.expiration&&0n!==e.expiration&&(t.uint32(24),t.uint64(e.expiration)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={relay:He(0),peer:He(0),expiration:0n},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.relay=e.bytes();break;case 2:r.peer=e.bytes();break;case 3:r.expiration=e.uint64();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(rd||(rd={})),function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.publicKey&&e.publicKey.byteLength>0&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.payloadType&&e.payloadType.byteLength>0&&(t.uint32(18),t.bytes(e.payloadType)),null!=e.payload&&(t.uint32(26),rd.codec().encode(e.payload,t)),null!=e.signature&&e.signature.byteLength>0&&(t.uint32(42),t.bytes(e.signature)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={publicKey:He(0),payloadType:He(0),signature:He(0)},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:n.publicKey=e.bytes();break;case 2:n.payloadType=e.bytes();break;case 3:var a;n.payload=rd.codec().decode(e,e.uint32(),{limits:null===(a=r.limits)||void 0===a?void 0:a.payload});break;case 5:n.signature=e.bytes();break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(nd||(nd={}));var ad=e=>({match:t=>!(t.length<1)&&(!!e(t[0])&&t.slice(1)),pattern:"fn"}),sd=e=>({match:t=>ad((t=>t===e)).match(t),pattern:e}),ld=()=>({match:e=>ad((e=>"string"==typeof e)).match(e),pattern:"{string}"}),cd=()=>({match:e=>ad((e=>!isNaN(parseInt(e)))).match(e),pattern:"{number}"}),ud=()=>({match:e=>{if(e.length<2)return!1;if("p2p"!==e[0]&&"ipfs"!==e[0])return!1;if(!e[1].startsWith("Q")&&!e[1].startsWith("1"))return!1;try{j.decode("z".concat(e[1]))}catch(e){return!1}return e.slice(2)},pattern:"/p2p/{peerid}"}),dd=()=>({match:e=>{if(e.length<2)return!1;if("certhash"!==e[0])return!1;try{q.decode(e[1])}catch(e){return!1}return e.slice(2)},pattern:"/certhash/{certhash}"}),hd=e=>({match:t=>{var r=e.match(t);return!1===r?t:r},pattern:"optional(".concat(e.pattern,")")}),pd=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return{match:e=>{var r;for(var n of t){var i=n.match(e);!1!==i&&((null==r||i.length<r.length)&&(r=i))}return null!=r&&r},pattern:"or(".concat(t.map((e=>e.pattern)).join(", "),")")}},fd=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];return{match:e=>{for(var r of t){var n=r.match(e);if(!1===n)return!1;e=n}return e},pattern:"and(".concat(t.map((e=>e.pattern)).join(", "),")")}};function vd(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];function n(e){var r=(e=>e.toString().split("/").slice(1))(e);for(var n of t){var i=n.match(r);if(!1===i)return!1;r=i}return r}return{matchers:t,matches:function(e){return!1!==n(e)},exactMatch:function(e){var t=n(e);return!1!==t&&0===t.length}}}var yd=vd(ud()),gd=fd(sd("dns4"),ld()),md=fd(sd("dns6"),ld()),wd=fd(sd("dnsaddr"),ld()),bd=fd(sd("dns"),ld());vd(gd,hd(ud())),vd(md,hd(ud())),vd(wd,hd(ud()));var _d=vd(pd(bd,wd,gd,md),hd(ud())),Sd=fd(sd("ip4"),ad(xt)),Pd=fd(sd("ip6"),ad(Tt)),Ed=pd(Sd,Pd),Ad=pd(Ed,bd,gd,md,wd),kd=vd(pd(Ed,fd(pd(bd,wd,gd,md),hd(ud())))),xd=vd(Sd),Td=vd(Pd),Id=vd(Ed),Cd=fd(Ad,sd("tcp"),cd()),Bd=fd(Ad,sd("udp"),cd()),Nd=vd(fd(Cd,hd(ud())));vd(Bd);var Dd=fd(Bd,sd("quic"),hd(ud())),Gd=fd(Bd,sd("quic-v1"),hd(ud())),Rd=pd(Dd,Gd);vd(Dd);var Od=vd(Gd),Ld=pd(Ad,Cd,Bd,Dd,Gd),Md=pd(fd(Ld,sd("ws"),hd(ud()))),jd=vd(Md),Fd=pd(fd(Ld,sd("wss"),hd(ud())),fd(Ld,sd("tls"),hd(fd(sd("sni"),ld())),sd("ws"),hd(ud()))),Ud=vd(Fd),zd=fd(Bd,sd("webrtc-direct"),hd(dd()),hd(dd()),hd(ud())),Vd=vd(zd),qd=fd(Gd,sd("webtransport"),hd(dd()),hd(dd()),hd(ud())),Hd=vd(qd),Kd=pd(Md,Fd,fd(Cd,hd(ud())),fd(Rd,hd(ud())),fd(Ad,hd(ud())),zd,qd,ud()),Wd=vd(Kd),Qd=vd(fd(Kd,sd("p2p-circuit"),ud())),Yd=vd(pd(fd(Kd,sd("p2p-circuit"),sd("webrtc"),hd(ud())),fd(Kd,sd("webrtc"),hd(ud())),fd(sd("webrtc"),hd(ud())))),Jd=vd(pd(fd(Ad,sd("tcp"),cd(),sd("http"),hd(ud())),fd(Ad,sd("http"),hd(ud())))),Zd=vd(pd(fd(Ad,sd("tcp"),pd(fd(sd("443"),sd("http")),fd(cd(),sd("https")),fd(cd(),sd("tls"),sd("http"))),hd(ud())),fd(Ad,sd("tls"),sd("http"),hd(ud())),fd(Ad,sd("https"),hd(ud()))));function $d(e){var t=new globalThis.AbortController;function r(){for(var n of(t.abort(),e))null!=(null==n?void 0:n.removeEventListener)&&n.removeEventListener("abort",r)}for(var n of e){if(!0===(null==n?void 0:n.aborted)){r();break}null!=(null==n?void 0:n.addEventListener)&&n.addEventListener("abort",r)}var i=t.signal;return i.clear=function(){for(var t of e)null!=(null==t?void 0:t.removeEventListener)&&t.removeEventListener("abort",r)},i}vd(pd(fd(sd("memory"),ld(),hd(ud()))));class Xd extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","HadEnoughRelaysError")}}e._defineProperty(Xd,"name","HadEnoughRelaysError");class eh extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","DoubleRelayError")}}e._defineProperty(eh,"name","DoubleRelayError");class th extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","RelayQueueFullError")}}function rh(e){var t=e*BigInt(1e3),r=(new Date).getTime();return Number(t-BigInt(r))}e._defineProperty(th,"name","RelayQueueFullError");class nh{constructor(t){e._defineProperty(this,"expires",void 0),e._defineProperty(this,"bytes",void 0),null!=(null==t?void 0:t.duration)&&0!==(null==t?void 0:t.duration)&&(this.expires=Date.now()+1e3*t.duration),this.bytes=null==t?void 0:t.data,0n===this.bytes&&(this.bytes=void 0),this.onData=this.onData.bind(this)}onData(e){null!=this.bytes&&(this.bytes-=BigInt(e.byteLength),this.bytes<0n&&(this.bytes=0n))}getLimits(){if(null!=this.expires||null!=this.bytes){var e={};if(null!=this.bytes){var t=this;Object.defineProperty(e,"bytes",{get:()=>t.bytes})}if(null!=this.expires){var r=this;Object.defineProperty(e,"seconds",{get(){var e;return Math.round(((null!==(e=r.expires)&&void 0!==e?e:0)-Date.now())/1e3)}})}return e}}}var ih=vd(fd(Wd.matchers[0],sd("p2p-circuit"))),oh=vd(sd("p2p-circuit"));function ah(e,t){var r={[Symbol.iterator]:()=>r,next:()=>{var r=e.next(),n=r.value;return!0===r.done||null==n?{done:!0,value:void 0}:{done:!1,value:t(n)}}};return r}function sh(e){return oc(Ae(j.decode("z".concat(e))))}class lh{constructor(t){if(e._defineProperty(this,"map",void 0),this.map=new Map,null!=t)for(var[r,n]of t.entries())this.map.set(r.toString(),{key:r,value:n})}[Symbol.iterator](){return this.entries()}clear(){this.map.clear()}delete(e){return this.map.delete(e.toString())}entries(){return ah(this.map.entries(),(e=>[e[1].key,e[1].value]))}forEach(e){this.map.forEach(((t,r)=>{e(t.value,t.key,this)}))}get(e){var t;return null===(t=this.map.get(e.toString()))||void 0===t?void 0:t.value}has(e){return this.map.has(e.toString())}set(e,t){this.map.set(e.toString(),{key:e,value:t})}keys(){return ah(this.map.values(),(e=>e.key))}values(){return ah(this.map.values(),(e=>e.value))}get size(){return this.map.size}}class ch{constructor(t){if(e._defineProperty(this,"set",void 0),this.set=new Set,null!=t)for(var r of t)this.set.add(r.toString())}get size(){return this.set.size}[Symbol.iterator](){return this.values()}add(e){this.set.add(e.toString())}clear(){this.set.clear()}delete(e){this.set.delete(e.toString())}entries(){return ah(this.set.entries(),(e=>{var t=sh(e[0]);return[t,t]}))}forEach(e){this.set.forEach((t=>{var r=sh(t);e(r,r,this)}))}has(e){return this.set.has(e.toString())}values(){return ah(this.set.values(),(e=>sh(e)))}intersection(e){var t=new ch;for(var r of e)this.has(r)&&t.add(r);return t}difference(e){var t=new ch;for(var r of this)e.has(r)||t.add(r);return t}union(e){var t=new ch;for(var r of e)t.add(r);for(var n of this)t.add(n);return t}}var uh={32:16777619n,64:1099511628211n,128:309485009821345068724781371n,256:374144419156711147060143317175368453031918731002211n,512:35835915874844867368919076489095108449946327955754392558399825615420669938882575126094039892345713852759n,1024:5016456510113118655434598811035278955030765345404790744303017523831112055108147451509157692220295382716162651878526895249385292291816524375083746691371804094271873160484737966720260389217684476157468082573n},dh={32:2166136261n,64:14695981039346656037n,128:144066263297769815596495629667062367629n,256:100029257958052580907070968620625704837092796014241193945225284501741471925557n,512:9659303129496669498009435400716310466090418745672637896108374329434462657994582932197716438449813051892206539805784495328239340083876191928701583869517785n,1024:14197795064947621068722070641403218320880622795441933960878474914617582723252296732303717722150864096521202355549365628174669108571814760471015076148029755969804077320157692458563003215304957150157403644460363550505412711285966361610267868082893823963790439336411086884584107735010676915n},hh=new globalThis.TextEncoder;function ph(e){var{size:t=32,utf8Buffer:r}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!uh[t])throw new Error("The `size` option must be one of 32, 64, 128, 256, 512, or 1024");if("string"==typeof e){if(r)return function(e,t,r){if(0===r.length)throw new Error("The `utf8Buffer` option must have a length greater than zero");for(var n=uh[t],i=dh[t],o=e;o.length>0;){var a=hh.encodeInto(o,r);o=o.slice(a.read);for(var s=0;s<a.written;s++)i^=BigInt(r[s]),i=BigInt.asUintN(t,i*n)}return i}(e,t,r);e=hh.encode(e)}return function(e,t){for(var r=uh[t],n=dh[t],i=0;i<e.length;i++)n^=BigInt(e[i]),n=BigInt.asUintN(t,n*r);return n}(e,t)}var fh={hash:e=>Number(ph(e,{size:32})),hashV:(e,t)=>function(e){var t=e.toString(16);t.length%2==1&&(t="0".concat(t));return ot(t,"base16")}(fh.hash(e,t))};class vh{constructor(t,r,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:2;if(e._defineProperty(this,"fp",void 0),e._defineProperty(this,"h",void 0),e._defineProperty(this,"seed",void 0),i>64)throw new TypeError("Invalid Fingerprint Size");for(var o=r.hashV(t,n),a=He(i),s=0;s<a.length;s++)a[s]=o[s];0===a.length&&(a[0]=7),this.fp=a,this.h=r,this.seed=n}hash(){return this.h.hash(this.fp,this.seed)}equals(e){return(null==e?void 0:e.fp)instanceof Uint8Array&&nt(this.fp,e.fp)}}function yh(e,t){return Math.floor(Math.random()*(t-e))+e}let gh=class{constructor(t){e._defineProperty(this,"contents",void 0),this.contents=new Array(t).fill(null)}has(e){if(!(e instanceof vh))throw new TypeError("Invalid Fingerprint");return this.contents.some((t=>e.equals(t)))}add(e){if(!(e instanceof vh))throw new TypeError("Invalid Fingerprint");for(var t=0;t<this.contents.length;t++)if(null==this.contents[t])return this.contents[t]=e,!0;return!0}swap(e){if(!(e instanceof vh))throw new TypeError("Invalid Fingerprint");var t=yh(0,this.contents.length-1),r=this.contents[t];return this.contents[t]=e,r}remove(e){if(!(e instanceof vh))throw new TypeError("Invalid Fingerprint");var t=this.contents.findIndex((t=>e.equals(t)));return t>-1&&(this.contents[t]=null,!0)}};class mh{constructor(t){var r,n,i,o;e._defineProperty(this,"bucketSize",void 0),e._defineProperty(this,"filterSize",void 0),e._defineProperty(this,"fingerprintSize",void 0),e._defineProperty(this,"buckets",void 0),e._defineProperty(this,"count",void 0),e._defineProperty(this,"hash",void 0),e._defineProperty(this,"seed",void 0),this.filterSize=t.filterSize,this.bucketSize=null!==(r=t.bucketSize)&&void 0!==r?r:4,this.fingerprintSize=null!==(n=t.fingerprintSize)&&void 0!==n?n:2,this.count=0,this.buckets=[],this.hash=null!==(i=t.hash)&&void 0!==i?i:fh,this.seed=null!==(o=t.seed)&&void 0!==o?o:yh(0,Math.pow(2,10))}add(e){"string"==typeof e&&(e=ot(e));var t=new vh(e,this.hash,this.seed,this.fingerprintSize),r=this.hash.hash(e,this.seed)%this.filterSize,n=(r^t.hash())%this.filterSize;if(null==this.buckets[r]&&(this.buckets[r]=new gh(this.bucketSize)),null==this.buckets[n]&&(this.buckets[n]=new gh(this.bucketSize)),this.buckets[r].add(t)||this.buckets[n].add(t))return this.count++,!0;var i=[r,n],o=i[yh(0,i.length-1)];null==this.buckets[o]&&(this.buckets[o]=new gh(this.bucketSize));for(var a=0;a<500;a++){var s=this.buckets[o].swap(t);if(null!=s&&(o=(o^s.hash())%this.filterSize,null==this.buckets[o]&&(this.buckets[o]=new gh(this.bucketSize)),this.buckets[o].add(s)))return this.count++,!0}return!1}has(e){var t,r,n,i;"string"==typeof e&&(e=ot(e));var o=new vh(e,this.hash,this.seed,this.fingerprintSize),a=this.hash.hash(e,this.seed)%this.filterSize,s=null!==(t=null===(r=this.buckets[a])||void 0===r?void 0:r.has(o))&&void 0!==t&&t;if(s)return s;var l=(a^o.hash())%this.filterSize;return null!==(n=null===(i=this.buckets[l])||void 0===i?void 0:i.has(o))&&void 0!==n&&n}remove(e){var t,r,n,i;"string"==typeof e&&(e=ot(e));var o=new vh(e,this.hash,this.seed,this.fingerprintSize),a=this.hash.hash(e,this.seed)%this.filterSize,s=null!==(t=null===(r=this.buckets[a])||void 0===r?void 0:r.remove(o))&&void 0!==t&&t;if(s)return this.count--,s;var l=(a^o.hash())%this.filterSize,c=null!==(n=null===(i=this.buckets[l])||void 0===i?void 0:i.remove(o))&&void 0!==n&&n;return c&&this.count--,c}get reliable(){return Math.floor(this.count/this.filterSize*100)<=90}}var wh={1:.5,2:.84,4:.95,8:.98};class bh{constructor(t){var r,n,i,o,a,s;e._defineProperty(this,"filterSize",void 0),e._defineProperty(this,"bucketSize",void 0),e._defineProperty(this,"fingerprintSize",void 0),e._defineProperty(this,"scale",void 0),e._defineProperty(this,"filterSeries",void 0),e._defineProperty(this,"hash",void 0),e._defineProperty(this,"seed",void 0),this.bucketSize=null!==(r=t.bucketSize)&&void 0!==r?r:4,this.filterSize=null!==(n=t.filterSize)&&void 0!==n?n:(1<<18)/this.bucketSize,this.fingerprintSize=null!==(i=t.fingerprintSize)&&void 0!==i?i:2,this.scale=null!==(o=t.scale)&&void 0!==o?o:2,this.hash=null!==(a=t.hash)&&void 0!==a?a:fh,this.seed=null!==(s=t.seed)&&void 0!==s?s:yh(0,Math.pow(2,10)),this.filterSeries=[new mh({filterSize:this.filterSize,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed})]}add(e){if("string"==typeof e&&(e=ot(e)),this.has(e))return!0;var t=this.filterSeries.find((e=>e.reliable));if(null==t){var r=this.filterSize*Math.pow(this.scale,this.filterSeries.length);t=new mh({filterSize:r,bucketSize:this.bucketSize,fingerprintSize:this.fingerprintSize,hash:this.hash,seed:this.seed}),this.filterSeries.push(t)}return t.add(e)}has(e){"string"==typeof e&&(e=ot(e));for(var t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].has(e))return!0;return!1}remove(e){"string"==typeof e&&(e=ot(e));for(var t=0;t<this.filterSeries.length;t++)if(this.filterSeries[t].remove(e))return!0;return!1}get count(){return this.filterSeries.reduce(((e,t)=>e+t.count),0)}}function _h(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:.001,n=arguments.length>2?arguments[2]:void 0;return new bh(e._objectSpread2(e._objectSpread2({},function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:.001,r=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:.001;return e>.002?2:e>1e-5?4:8}(t),n=wh[r];return{filterSize:Math.round(e/n),bucketSize:r,fingerprintSize:Math.min(Math.ceil(Math.log2(1/t)+Math.log2(2*r)),64)}}(t,r)),null!=n?n:{}))}class Sh{constructor(t,r){e._defineProperty(this,"filter",void 0),this.filter=_h(t,r)}has(e){return this.filter.has(e.toMultihash().bytes)}add(e){this.filter.add(e.toMultihash().bytes)}remove(e){var t,r;null===(t=(r=this.filter).remove)||void 0===t||t.call(r,e.toMultihash().bytes)}}function Ph(e){return new Sh(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:.001)}class Eh extends lh{constructor(t){super(),e._defineProperty(this,"metric",void 0);var{name:r,metrics:n}=t;this.metric=n.registerMetric(r),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){var t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}function Ah(e){var{name:t,metrics:r}=e;return null!=r?new Eh({name:t,metrics:r}):new lh}function kh(e){return null!=(null==e?void 0:e.then)}function xh(t,r){var n=0;if(null!=t[Symbol.asyncIterator])return e._wrapAsyncGenerator((function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value,u=r(c,n++);kh(u)&&(yield e._awaitAsyncGenerator(u)),yield c}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}))();var i=Dc(t),{value:o,done:a}=i.next();if(!0===a)return function*(){}();var s=r(o,n++);if("function"==typeof(null==s?void 0:s.then))return e._wrapAsyncGenerator((function*(){for(var t of(yield o,i)){var a=r(t,n++);kh(a)&&(yield e._awaitAsyncGenerator(a)),yield t}}))();var l=r;return function*(){for(var e of(yield o,i))l(e,n++),yield e}()}function Th(t){var{stream:r,remoteAddr:n,logger:i,onDataRead:o,onDataWrite:a}=t,s=i.forComponent("libp2p:stream:converter"),l=!1,c=!1,u=r.close.bind(r);r.close=function(){var t=e._asyncToGenerator((function*(e){yield u(e),f(!0)}));return function(e){return t.apply(this,arguments)}}();var d=r.abort.bind(r);r.abort=e=>{d(e),f(!0)};var h=r.sink.bind(r);r.sink=function(){var t=e._asyncToGenerator((function*(e){try{yield h(lu(e,(e=>xh(e,(e=>null==a?void 0:a(e))))))}catch(e){"aborted"!==e.type&&s.error("%s error in sink",n,e)}finally{c=!0,f()}}));return function(e){return t.apply(this,arguments)}}();var p={log:s,sink:r.sink,source:e._wrapAsyncGenerator((function*(){try{var t,n=!1,i=!1;try{for(var a,s=e._asyncIterator(r.source);n=!(a=yield e._awaitAsyncGenerator(s.next())).done;n=!1){var c=a.value;null==o||o(c),yield c}}catch(e){i=!0,t=e}finally{try{n&&null!=s.return&&(yield e._awaitAsyncGenerator(s.return()))}finally{if(i)throw t}}}finally{l=!0,f()}}))(),remoteAddr:n,timeline:{open:Date.now(),close:void 0},close:r.close,abort:r.abort};function f(e){!0===e&&(l=!0,c=!0),l&&c&&null==p.timeline.close&&(p.timeline.close=Date.now())}return p}class Ih extends Event{constructor(t,r){super(t),e._defineProperty(this,"type",void 0),e._defineProperty(this,"detail",void 0),this.type=t,this.detail=r}}let Ch=class extends Error{constructor(t,r){super(null!=t?t:"The operation was aborted"),e._defineProperty(this,"type",void 0),e._defineProperty(this,"code",void 0),this.type="aborted",this.name="AbortError",this.code=null!=r?r:"ABORT_ERR"}};function Bh(e,t,r,n){return Nh.apply(this,arguments)}function Nh(){return Nh=e._asyncToGenerator((function*(e,t,r,n){var i=new Ch(null==n?void 0:n.errorMessage,null==n?void 0:n.errorCode);return!0===(null==r?void 0:r.aborted)?Promise.reject(i):new Promise(((o,a)=>{function s(){null==r||r.removeEventListener("abort",u),e.removeEventListener(t,l),null!=(null==n?void 0:n.errorEvent)&&e.removeEventListener(n.errorEvent,c)}var l=e=>{try{var t;if(!1===(null==n||null===(t=n.filter)||void 0===t?void 0:t.call(n,e)))return}catch(e){return s(),void a(e)}s(),o(e)},c=e=>{s(),a(e.detail)},u=()=>{s(),a(i)};null==r||r.addEventListener("abort",u),e.addEventListener(t,l),null!=(null==n?void 0:n.errorEvent)&&e.addEventListener(n.errorEvent,c)}))})),Nh.apply(this,arguments)}function Dh(e,t){var r,n=function(){clearTimeout(r),r=setTimeout((function(){r=void 0,e()}),t)};return n.start=()=>{},n.stop=()=>{clearTimeout(r)},n}class Gh extends Error{constructor(){var t=arguments.length>1?arguments[1]:void 0;super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Rate limit exceeded"),e._defineProperty(this,"remainingPoints",void 0),e._defineProperty(this,"msBeforeNext",void 0),e._defineProperty(this,"consumedPoints",void 0),e._defineProperty(this,"isFirstInDuration",void 0),this.name="RateLimitError",this.remainingPoints=t.remainingPoints,this.msBeforeNext=t.msBeforeNext,this.consumedPoints=t.consumedPoints,this.isFirstInDuration=t.isFirstInDuration}}let Rh=class extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The queue was full"),this.name="QueueFullError"}};e._defineProperty(Rh,"name","QueueFullError");let Oh=class{constructor(t){var r;e._defineProperty(this,"deferred",void 0),e._defineProperty(this,"signal",void 0),this.signal=t,this.deferred=Yc(),this.onAbort=this.onAbort.bind(this),null===(r=this.signal)||void 0===r||r.addEventListener("abort",this.onAbort)}onAbort(){var e,t;this.deferred.reject(null!==(e=null===(t=this.signal)||void 0===t?void 0:t.reason)&&void 0!==e?e:new Zo)}cleanup(){var e;null===(e=this.signal)||void 0===e||e.removeEventListener("abort",this.onAbort)}};let Lh=class{constructor(t,r){e._defineProperty(this,"id",void 0),e._defineProperty(this,"fn",void 0),e._defineProperty(this,"options",void 0),e._defineProperty(this,"recipients",void 0),e._defineProperty(this,"status",void 0),e._defineProperty(this,"timeline",void 0),e._defineProperty(this,"controller",void 0),this.id="".concat(parseInt(String(1e9*Math.random()),10).toString()).concat(Date.now()),this.status="queued",this.fn=t,this.options=r,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){var e=this.recipients.reduce(((e,t)=>{var r;return e&&!0===(null===(r=t.signal)||void 0===r?void 0:r.aborted)}),!0);e&&(this.controller.abort(new Zo),this.cleanup())}join(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var e,n=t.length>0&&void 0!==t[0]?t[0]:{},i=new Oh(n.signal);return r.recipients.push(i),null===(e=n.signal)||void 0===e||e.addEventListener("abort",r.onAbort),i.deferred.promise}))()}run(){var t=this;return e._asyncToGenerator((function*(){t.status="running",t.timeline.started=Date.now();try{var r;t.controller.signal.throwIfAborted();var n=yield tu(t.fn(e._objectSpread2(e._objectSpread2({},null!==(r=t.options)&&void 0!==r?r:{}),{},{signal:t.controller.signal})),t.controller.signal);t.recipients.forEach((e=>{e.deferred.resolve(n)})),t.status="complete"}catch(e){t.recipients.forEach((t=>{t.deferred.reject(e)})),t.status="errored"}finally{t.timeline.finished=Date.now(),t.cleanup()}}))()}cleanup(){this.recipients.forEach((e=>{var t;e.cleanup(),null===(t=e.signal)||void 0===t||t.removeEventListener("abort",this.onAbort)}))}},Mh=class extends Ia{constructor(){var t,r,n,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(super(),e._defineProperty(this,"concurrency",void 0),e._defineProperty(this,"maxSize",void 0),e._defineProperty(this,"queue",void 0),e._defineProperty(this,"pending",void 0),e._defineProperty(this,"sort",void 0),this.concurrency=null!==(t=i.concurrency)&&void 0!==t?t:Number.POSITIVE_INFINITY,this.maxSize=null!==(r=i.maxSize)&&void 0!==r?r:Number.POSITIVE_INFINITY,this.pending=0,null!=i.metricName)&&(null===(n=i.metrics)||void 0===n||n.registerMetricGroup(i.metricName,{calculate:()=>({size:this.queue.length,running:this.pending,queued:this.queue.length-this.pending})}));this.sort=i.sort,this.queue=[],this.emitEmpty=Dh(this.emitEmpty.bind(this),1),this.emitIdle=Dh(this.emitIdle.bind(this),1)}emitEmpty(){0===this.size&&this.safeDispatchEvent("empty")}emitIdle(){0===this.running&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(0===this.size)return this.emitEmpty(),0===this.running&&this.emitIdle(),!1;if(this.pending<this.concurrency){var e;for(var t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(this.safeDispatchEvent("active"),this.pending++,e.run().finally((()=>{for(var t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.tryToStartAnother(),this.safeDispatchEvent("next")})),!0)}return!1}enqueue(e){this.queue.push(e),null!=this.sort&&this.queue.sort(this.sort)}add(t,r){var n=this;return e._asyncToGenerator((function*(){var e;if(null==r||null===(e=r.signal)||void 0===e||e.throwIfAborted(),n.size===n.maxSize)throw new Rh;var i=new Lh(t,r);return n.enqueue(i),n.safeDispatchEvent("add"),n.tryToStartAnother(),i.join(r).then((e=>(n.safeDispatchEvent("completed",{detail:e}),n.safeDispatchEvent("success",{detail:{job:i,result:e}}),e))).catch((e=>{if("queued"===i.status)for(var t=0;t<n.queue.length;t++)if(n.queue[t]===i){n.queue.splice(t,1);break}throw n.safeDispatchEvent("error",{detail:e}),n.safeDispatchEvent("failure",{detail:{job:i,error:e}}),e}))}))()}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach((e=>{e.abort(new Zo)})),this.clear()}onEmpty(t){var r=this;return e._asyncToGenerator((function*(){0!==r.size&&(yield Bh(r,"empty",null==t?void 0:t.signal))}))()}onSizeLessThan(t,r){var n=this;return e._asyncToGenerator((function*(){n.size<t||(yield Bh(n,"next",null==r?void 0:r.signal,{filter:()=>n.size<t}))}))()}onIdle(t){var r=this;return e._asyncToGenerator((function*(){0===r.pending&&0===r.size||(yield Bh(r,"idle",null==t?void 0:t.signal))}))()}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}toGenerator(t){var r=this;return e._wrapAsyncGenerator((function*(){var n,i;null==t||null===(n=t.signal)||void 0===n||n.throwIfAborted();var o=Xc({objectMode:!0}),a=e=>{null!=e?r.abort():r.clear(),o.end(e)},s=e=>{null!=e.detail&&o.push(e.detail)},l=e=>{a(e.detail)},c=()=>{a()},u=()=>{a(new Zo("Queue aborted"))};r.addEventListener("completed",s),r.addEventListener("error",l),r.addEventListener("idle",c),null==t||null===(i=t.signal)||void 0===i||i.addEventListener("abort",u);try{yield*e._asyncGeneratorDelegate(e._asyncIterator(o),e._awaitAsyncGenerator)}finally{var d;r.removeEventListener("completed",s),r.removeEventListener("error",l),r.removeEventListener("idle",c),null==t||null===(d=t.signal)||void 0===d||d.removeEventListener("abort",u),a()}}))()}};class jh extends Mh{has(e){return null!=this.find(e)}find(e){return this.queue.find((t=>e.equals(t.options.peerId)))}}class Fh extends Ia{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"registrar",void 0),e._defineProperty(this,"connectionManager",void 0),e._defineProperty(this,"randomWalk",void 0),e._defineProperty(this,"started",void 0),e._defineProperty(this,"running",void 0),e._defineProperty(this,"topologyId",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"discoveryController",void 0),e._defineProperty(this,"filter",void 0),e._defineProperty(this,"queue",void 0),this.log=t.logger.forComponent("libp2p:circuit-relay:discover-relays"),this.started=!1,this.running=!1,this.peerStore=t.peerStore,this.registrar=t.registrar,this.connectionManager=t.connectionManager,this.randomWalk=t.randomWalk,this.filter=r.filter,this.discoveryController=new AbortController,this.discoveryController.signal}isStarted(){return this.started}start(){var t=this;return e._asyncToGenerator((function*(){t.topologyId=yield t.registrar.register(id,{filter:t.filter,onConnect:e=>{var r,n;t.log.trace("discovered relay %p queue (length: %d, active %d)",e,null===(r=t.queue)||void 0===r?void 0:r.size,null===(n=t.queue)||void 0===n?void 0:n.running),t.safeDispatchEvent("relay:discover",{detail:e})}}),t.started=!0}))()}stop(){var e;null!=this.topologyId&&this.registrar.unregister(this.topologyId),null===(e=this.discoveryController)||void 0===e||e.abort(),this.started=!1}startDiscovery(){var t=this;this.running||(this.log("start discovery"),this.running=!0,this.discoveryController=new AbortController,this.discoveryController.signal,Promise.resolve().then(e._asyncToGenerator((function*(){t.log("searching peer store for relays");var r=yield t.peerStore.all({filters:[e=>e.protocols.includes(id)],orders:[()=>Math.random()<.5?1:-1,(e,t)=>{var r=Uh(e),n=Uh(t);return r>n?-1:n>r?1:0}]});for(var n of r)t.log.trace("found relay peer %p in peer store",n.id),t.safeDispatchEvent("relay:discover",{detail:n.id});t.log("found %d relay peers in peer store",r.length);var i=t.queue=new jh({concurrency:5});t.log("start random walk");var o,a=!1,s=!1;try{for(var l,c=function*(){var r,n=l.value;return t.log.trace("found random peer %p",n.id),i.has(n.id)?(t.log.trace("random peer %p was already in queue",n.id),0):(null===(r=t.connectionManager.getConnections(n.id))||void 0===r?void 0:r.length)>0?(t.log.trace("random peer %p was already connected",n.id),0):(yield t.connectionManager.isDialable(n.multiaddrs))?(i.queued>10&&(t.log.trace("wait for space in queue for %p",n.id),yield i.onSizeLessThan(10,{signal:t.discoveryController.signal})),t.log("adding random peer %p to dial queue (length: %d, active %d)",n.id,i.size,i.running),void i.add(e._asyncToGenerator((function*(){var e=$d([t.discoveryController.signal,AbortSignal.timeout(5e3)]);try{yield t.connectionManager.openConnection(n.id,{signal:e})}finally{e.clear()}})),{peerId:n.id,signal:t.discoveryController.signal}).catch((e=>{t.log.error("error opening connection to random peer %p",n.id,e)}))):(t.log.trace("random peer %p was not dialable",n.id,n.multiaddrs.map((e=>e.toString()))),0)},u=e._asyncIterator(t.randomWalk.walk({signal:t.discoveryController.signal}));a=!(l=yield u.next()).done;a=!1)yield*c()}catch(e){s=!0,o=e}finally{try{a&&null!=u.return&&(yield u.return())}finally{if(s)throw o}}t.log("stop random walk"),yield i.onIdle()}))).catch((e=>{this.discoveryController.signal.aborted||this.log.error("failed when finding relays on the network",e)})))}stopDiscovery(){var e;this.log("stop discovery"),this.running=!1,null===(e=this.discoveryController)||void 0===e||e.abort()}}function Uh(e){var t=e.metadata.get("last-dial-success");return null==t?0:new Date(Ze(t)).getTime()}class zh extends Ia{constructor(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),e._defineProperty(this,"connectionManager",void 0),e._defineProperty(this,"addressManager",void 0),e._defineProperty(this,"reservationStore",void 0),e._defineProperty(this,"listeningAddrs",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"listenTimeout",void 0),e._defineProperty(this,"reservationId",void 0),e._defineProperty(this,"relay",void 0),e._defineProperty(this,"_onRemoveRelayPeer",(e=>{var t,r;this.log("relay removed %p our relay %p",e.detail.relay,this.relay,null===(t=this.relay)||void 0===t?void 0:t.equals(e.detail.relay)),!0===(null===(r=this.relay)||void 0===r?void 0:r.equals(e.detail.relay))&&(this.log("relay peer removed %p",e.detail.relay),this.listeningAddrs.forEach((e=>{this.addressManager.removeObservedAddr(e)})),this.listeningAddrs=[],this.safeDispatchEvent("listening"))})),e._defineProperty(this,"_onAddRelayPeer",(e=>{var{details:t}=e.detail;"configured"!==t.type&&t.id===this.reservationId&&this.addedRelay(e.detail)})),this.log=t.logger.forComponent("libp2p:circuit-relay:transport:listener"),this.connectionManager=t.connectionManager,this.addressManager=t.addressManager,this.reservationStore=t.reservationStore,this.listeningAddrs=[],this.listenTimeout=null!==(r=n.listenTimeout)&&void 0!==r?r:2e3,this.reservationStore.addEventListener("relay:removed",this._onRemoveRelayPeer),this.reservationStore.addEventListener("relay:created-reservation",this._onAddRelayPeer)}listen(t){var r=this;return e._asyncToGenerator((function*(){if(oh.exactMatch(t))r.log("searching for circuit relay servers"),r.reservationId=r.reservationStore.reserveRelay();else{if(!ih.exactMatch(t))throw new Sa('Could not listen on p2p-circuit address "'.concat(t,'"'));r.log("listen on specific relay server %a",t);var e=AbortSignal.timeout(r.listenTimeout),n=t.decapsulate("/p2p-circuit"),i=yield r.connectionManager.openConnection(n,{signal:e});if(!r.reservationStore.hasReservation(i.remotePeer)){r.log("making reservation on peer %p",i.remotePeer);var o=yield r.reservationStore.addRelay(i.remotePeer,"configured");r.addedRelay(o)}}}))()}getAddrs(){return[...this.listeningAddrs.values()].flat()}updateAnnounceAddrs(){}close(){var t=this;return e._asyncToGenerator((function*(){t.reservationStore.cancelReservations(),t.listeningAddrs=[],t.reservationStore.removeEventListener("relay:removed",t._onRemoveRelayPeer),queueMicrotask((()=>{t.safeDispatchEvent("close")}))}))()}addedRelay(e){this.log("relay peer added %p",e.relay),this.relay=e.relay,this.listeningAddrs=e.details.reservation.addrs.map((e=>sr(e).encapsulate("/p2p-circuit"))),this.listeningAddrs.forEach((e=>{this.addressManager.confirmObservedAddr(e,{type:"transport"})})),queueMicrotask((()=>{this.safeDispatchEvent("listening")}))}}var Vh=function(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:21,t="",r=crypto.getRandomValues(new Uint8Array(e|=0));e--;)t+="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict"[63&r[e]];return t},qh=new WeakSet;class Hh extends Ia{constructor(t,r){var n,i,o;super(),e._classPrivateMethodInitSpec(this,qh),e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"connectionManager",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"events",void 0),e._defineProperty(this,"reserveQueue",void 0),e._defineProperty(this,"reservations",void 0),e._defineProperty(this,"pendingReservations",void 0),e._defineProperty(this,"maxReservationQueueLength",void 0),e._defineProperty(this,"reservationCompletionTimeout",void 0),e._defineProperty(this,"started",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"relayFilter",void 0),this.log=t.logger.forComponent("libp2p:circuit-relay:transport:reservation-store"),this.peerId=t.peerId,this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,this.reservations=new lh,this.pendingReservations=[],this.maxReservationQueueLength=null!==(n=null==r?void 0:r.maxReservationQueueLength)&&void 0!==n?n:100,this.reservationCompletionTimeout=null!==(i=null==r?void 0:r.reservationCompletionTimeout)&&void 0!==i?i:2e3,this.started=!1,this.relayFilter=_h(100),this.reserveQueue=new jh({concurrency:null!==(o=null==r?void 0:r.reservationConcurrency)&&void 0!==o?o:1,metricName:"libp2p_relay_reservation_queue",metrics:t.metrics}),this.events.addEventListener("connection:close",(t=>{null!=[...this.reservations.values()].find((e=>e.connection===t.detail.id))&&e._assertClassBrand(qh,this,Qh).call(this,t.detail.remotePeer).catch((e=>{this.log("could not remove relay %p - %e",t.detail,e)}))}))}isStarted(){return this.started}start(){this.started=!0}afterStart(){var t=this;Promise.resolve().then(e._asyncToGenerator((function*(){var r=yield t.peerStore.all({filters:[e=>e.tags.has(Qu)]});t.log("removing tag from %d old relays",r.length),yield Promise.all(r.map(function(){var r=e._asyncToGenerator((function*(e){yield t.peerStore.merge(e.id,{tags:{[Qu]:void 0}})}));return function(e){return r.apply(this,arguments)}}())),t.log("redialing %d old relays",r.length),yield Promise.all(r.map(function(){var r=e._asyncToGenerator((function*(e){return t.addRelay(e.id,"discovered")}));return function(e){return r.apply(this,arguments)}}())),e._assertClassBrand(qh,t,Jh).call(t)}))).catch((e=>{this.log.error(e)}))}stop(){this.reserveQueue.clear(),this.reservations.forEach((e=>{var{timeout:t}=e;clearTimeout(t)})),this.reservations.clear(),this.started=!1}reserveRelay(){var t=Vh();return this.pendingReservations.push(t),e._assertClassBrand(qh,this,Jh).call(this),t}addRelay(t,r){var n=this;return e._asyncToGenerator((function*(){if(n.peerId.equals(t))throw n.log.trace("not trying to use self as relay"),new Sa("Cannot use self as relay");if(n.reserveQueue.size>n.maxReservationQueueLength)throw new th("The reservation queue is full");var i=n.reserveQueue.find(t);if(null!=i)return n.log.trace("potential relay peer %p is already in the reservation queue",t),i.join();if(n.relayFilter.has(t.toMultihash().bytes))throw new Sa("The relay was previously invalid");return n.log.trace("try to reserve relay slot with %p",t),n.reserveQueue.add(e._asyncToGenerator((function*(){var i=Date.now();try{var o=n.reservations.get(t);if(null!=o){var a=n.connectionManager.getConnections(t),s=!1;if(0===a.length&&n.log("already have relay reservation with %p but we are no longer connected",t),a.map((e=>e.id)).includes(o.connection)&&(n.log("already have relay reservation with %p and the original connection is still open",t),s=!0),s&&rh(o.reservation.expire)>6e5)return n.log("already have relay reservation with %p but we are still connected and it does not expire soon",t),{relay:t,details:o};yield e._assertClassBrand(qh,n,Qh).call(n,t)}if("discovered"===r&&0===n.pendingReservations.length)throw new Xd("Not making reservation on discovered relay because we do not need any more relays");var l=AbortSignal.timeout(n.reservationCompletionTimeout),c=yield n.connectionManager.openConnection(t,{signal:l});if(Qd.matches(c.remoteAddr))throw new eh("not creating reservation over relayed connection");var u=yield e._assertClassBrand(qh,n,Kh).call(n,c,{signal:l}),d=rh(u.expire);n.log("created reservation on relay peer %p, expiry date is %s",t,new Date(Date.now()+d).toString());var h,p=Math.min(Math.max(d-3e5,3e4),Math.pow(2,31)-1),f=setTimeout((()=>{n.log("refresh reservation to relay %p",t),n.addRelay(t,r).catch(function(){var r=e._asyncToGenerator((function*(r){n.log.error("could not refresh reservation to relay %p - %e",t,r),yield e._assertClassBrand(qh,n,Qh).call(n,t)}));return function(e){return r.apply(this,arguments)}}()).catch((e=>{n.log.error("could not remove expired reservation to relay %p - %e",t,e)}))}),p);if("discovered"===r){var v=n.pendingReservations.pop();if(null==v)throw new Xd("Made reservation on relay but did not need any more discovered relays");h={timeout:f,reservation:u,type:r,connection:c.id,id:v}}else h={timeout:f,reservation:u,type:r,connection:c.id};n.reservations.set(t,h),yield n.peerStore.merge(t,{tags:{[Qu]:{value:1,ttl:d}}}),e._assertClassBrand(qh,n,Jh).call(n);var y={relay:t,details:h};return n.safeDispatchEvent("relay:created-reservation",{detail:y}),y}catch(o){throw"discovered"===r&&"HadEnoughRelaysError"===o.name||n.log.error("could not reserve slot on %p after %dms - %e",t,Date.now()-i,o),"DialError"!==o.name&&"UnsupportedProtocolError"!==o.name||n.relayFilter.add(t.toMultihash().bytes),e._assertClassBrand(qh,n,Qh).call(n,t).catch((e=>{n.log.error("could not remove reservation on %p after reserving slot failed - %e",t,e)})),o}})),{peerId:t})}))()}hasReservation(e){return this.reservations.has(e)}getReservation(e){var t;return null===(t=this.reservations.get(e))||void 0===t?void 0:t.reservation}reservationCount(e){return null==e?this.reservations.size:[...this.reservations.values()].reduce(((t,r)=>(r.type===e&&t++,t)),0)}cancelReservations(){[...this.reservations.values()].forEach((e=>{clearTimeout(e.timeout)})),this.reservations.clear()}}function Kh(e,t){return Wh.apply(this,arguments)}function Wh(){return Wh=e._asyncToGenerator((function*(e,t){var r,n;null===(r=t.signal)||void 0===r||r.throwIfAborted(),this.log("requesting reservation from %p",e.remotePeer);var i,o=yield e.newStream(id,t),a=Wu(o).pb(Yu);this.log.trace("send RESERVE to %p",e.remotePeer),yield a.write({type:Yu.Type.RESERVE},t);try{this.log.trace("reading response from %p",e.remotePeer),i=yield a.read(t)}catch(e){throw o.abort(e),e}finally{"closed"!==o.status&&(yield o.close(t))}if(this.log.trace("read response %o",i),i.status===ed.OK&&null!=i.reservation){var s=new Set;for(var l of(s.add(e.remoteAddr.toString()),i.reservation.addrs)){var c=sr(l);null==c.getPeerId()&&(c=c.encapsulate("/p2p/".concat(e.remotePeer))),c=sr(c.toString().replace("/p2p/".concat(e.remotePeer,"/p2p/").concat(e.remotePeer),"/p2p/".concat(e.remotePeer))),s.add(c.toString())}return i.reservation.addrs=[...s].map((e=>sr(e).bytes)),i.reservation}var u="reservation failed with status ".concat(null!==(n=i.status)&&void 0!==n?n:"undefined");throw this.log.error(u),new Error(u)})),Wh.apply(this,arguments)}function Qh(e){return Yh.apply(this,arguments)}function Yh(){return Yh=e._asyncToGenerator((function*(t){var r=this.reservations.get(t);null!=r&&(this.log("removing relay reservation with %p from local store",t),clearTimeout(r.timeout),this.reservations.delete(t),"discovered"===r.type&&this.pendingReservations.push(r.id),yield this.peerStore.merge(t,{tags:{[Qu]:void 0}}),this.safeDispatchEvent("relay:removed",{detail:{relay:t,details:r}}),e._assertClassBrand(qh,this,Jh).call(this))})),Yh.apply(this,arguments)}function Jh(){if(0===this.pendingReservations.length)return this.log.trace("have discovered enough relays"),this.reserveQueue.clear(),void this.safeDispatchEvent("relay:found-enough-relays");this.relayFilter=_h(100),this.log("not discovered enough relays %d/%d",this.reservations.size,this.pendingReservations.length),this.safeDispatchEvent("relay:not-enough-relays")}var Zh,$h=300,Xh=300;class ep{constructor(t){var r,n,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"discovery",void 0),e._defineProperty(this,"registrar",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"connectionManager",void 0),e._defineProperty(this,"transportManager",void 0),e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"upgrader",void 0),e._defineProperty(this,"addressManager",void 0),e._defineProperty(this,"connectionGater",void 0),e._defineProperty(this,"reservationStore",void 0),e._defineProperty(this,"logger",void 0),e._defineProperty(this,"maxInboundStopStreams",void 0),e._defineProperty(this,"maxOutboundStopStreams",void 0),e._defineProperty(this,"started",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"shutdownController",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/circuit-relay-v2-transport"),e._defineProperty(this,Ra,["@libp2p/transport","@libp2p/circuit-relay-v2-transport"]),e._defineProperty(this,Jo,!0),this.log=t.logger.forComponent("libp2p:circuit-relay:transport"),this.registrar=t.registrar,this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.transportManager=t.transportManager,this.logger=t.logger,this.peerId=t.peerId,this.upgrader=t.upgrader,this.addressManager=t.addressManager,this.connectionGater=t.connectionGater,this.maxInboundStopStreams=null!==(r=o.maxInboundStopStreams)&&void 0!==r?r:$h,this.maxOutboundStopStreams=null!==(n=o.maxOutboundStopStreams)&&void 0!==n?n:Xh,this.shutdownController=new AbortController,this.discovery=new Fh(t,{filter:null!==(i=o.discoveryFilter)&&void 0!==i?i:Ph(4096,.001)}),this.discovery.addEventListener("relay:discover",(e=>{this.reservationStore.addRelay(e.detail,"discovered").catch((t=>{"HadEnoughRelaysError"!==t.name&&"RelayQueueFullError"!==t.name&&this.log.error("could not add discovered relay %p",e.detail,t)}))})),this.reservationStore=new Hh(t,o),this.reservationStore.addEventListener("relay:not-enough-relays",(()=>{var e;null===(e=this.discovery)||void 0===e||e.startDiscovery()})),this.reservationStore.addEventListener("relay:found-enough-relays",(()=>{var e;null===(e=this.discovery)||void 0===e||e.stopDiscovery()})),this.started=!1}get[Oa](){return null!=this.discovery?["@libp2p/identify"]:[]}isStarted(){return this.started}start(){var t=this;return e._asyncToGenerator((function*(){t.shutdownController=new AbortController,t.shutdownController.signal,yield t.registrar.handle(od,(e=>{var r=t.upgrader.createInboundAbortSignal(t.shutdownController.signal);t.onStop(e,r).catch((r=>{t.log.error("error while handling STOP protocol",r),e.stream.abort(r)})).finally((()=>{r.clear()}))}),{maxInboundStreams:t.maxInboundStopStreams,maxOutboundStreams:t.maxOutboundStopStreams,runOnLimitedConnection:!0}),yield Ba(t.discovery,t.reservationStore),t.started=!0}))()}stop(){var t=this;return e._asyncToGenerator((function*(){t.shutdownController.abort(),yield Da(t.discovery,t.reservationStore),yield t.registrar.unhandle(od),t.started=!1}))()}dial(t,r){var n=this;return e._asyncToGenerator((function*(){if(1!==t.protoCodes().filter((e=>290===e)).length){var i="Invalid circuit relay address";throw n.log.error(i,t),new _a(i)}var o=t.toString().split("/p2p-circuit"),a=sr(o[0]),s=sr(o[o.length-1]),l=a.getPeerId(),c=s.getPeerId();if(null==l||null==c){var u="ircuit relay dial to ".concat(t.toString()," failed as address did not have both relay and destination PeerIDs");throw n.log.error("c".concat(u)),new _a("C".concat(u))}var d,h,p,f=rc(l),v=rc(c),y=n.connectionManager.getConnections(f)[0];null==y?(yield n.peerStore.merge(f,{multiaddrs:[a]}),null===(d=r.onProgress)||void 0===d||d.call(r,new Ih("circuit-relay:open-connection")),y=yield n.connectionManager.openConnection(f,r)):null===(h=r.onProgress)||void 0===h||h.call(r,new Ih("circuit-relay:reuse-connection"));try{var g,m,w;null===(g=r.onProgress)||void 0===g||g.call(r,new Ih("circuit-relay:open-hop-stream"));var b=Wu(p=yield y.newStream(id,r)),_=b.pb(Yu);null===(m=r.onProgress)||void 0===m||m.call(r,new Ih("circuit-relay:write-connect-message")),yield _.write({type:Yu.Type.CONNECT,peer:{id:v.toMultihash().bytes,addrs:[sr(s).bytes]}},r),null===(w=r.onProgress)||void 0===w||w.call(r,new Ih("circuit-relay:read-connect-response"));var S,P,E=yield _.read(r);if(E.status!==ed.OK)throw new ya("failed to connect via relay with status ".concat(null!==(S=null==E||null===(P=E.status)||void 0===P?void 0:P.toString())&&void 0!==S?S:"undefined"));var A=new nh(E.limit),k=Th({stream:b.unwrap(),remoteAddr:t,localAddr:a.encapsulate("/p2p-circuit/p2p/".concat(n.peerId.toString())),logger:n.logger,onDataRead:A.onData,onDataWrite:A.onData});return n.log("new outbound relayed connection %a",k.remoteAddr),yield n.upgrader.upgradeOutbound(k,e._objectSpread2(e._objectSpread2({},r),{},{limits:A.getLimits()}))}catch(e){var x;throw n.log.error("circuit relay dial to destination %p via relay %p failed",v,f,e),null===(x=p)||void 0===x||x.abort(e),e}}))()}createListener(e){return function(e){return new zh(e)}({peerId:this.peerId,connectionManager:this.connectionManager,addressManager:this.addressManager,reservationStore:this.reservationStore,logger:this.logger})}listenFilter(e){return(e=Array.isArray(e)?e:[e]).filter((e=>ih.exactMatch(e)||oh.exactMatch(e)))}dialFilter(e){return(e=Array.isArray(e)?e:[e]).filter((e=>Qd.exactMatch(e)))}onStop(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i,{connection:o,stream:a}=t;if(!n.reservationStore.hasReservation(o.remotePeer))try{n.log("dialed via relay we did not have a reservation on, start listening on that relay address"),yield n.transportManager.listen([o.remoteAddr.encapsulate("/p2p-circuit")])}catch(e){n.log.error("failed to listen on a relay peer we were dialed via but did not have a reservation on",e)}var s=Wu(a).pb(Ju),l=yield s.read({signal:r});if(n.log("new circuit relay v2 stop stream from %p with type %s",o.remotePeer,l.type),void 0===(null==l?void 0:l.type))return n.log.error("type was missing from circuit v2 stop protocol request from %s",o.remotePeer),yield s.write({type:Ju.Type.STATUS,status:ed.MALFORMED_MESSAGE},{signal:r}),void(yield a.close());if(l.type!==Ju.Type.CONNECT)return n.log.error("invalid stop connect request via peer %p",o.remotePeer),yield s.write({type:Ju.Type.STATUS,status:ed.UNEXPECTED_MESSAGE},{signal:r}),void(yield a.close());if(!(e=>{if(null==e.peer)return!1;try{e.peer.addrs.forEach(sr)}catch(e){return!1}return!0})(l))return n.log.error("invalid stop connect request via peer %p",o.remotePeer),yield s.write({type:Ju.Type.STATUS,status:ed.MALFORMED_MESSAGE},{signal:r}),void(yield a.close({signal:r}));var c=oc(Ae(l.peer.id));if(!0===(yield null===(e=(i=n.connectionGater).denyInboundRelayedConnection)||void 0===e?void 0:e.call(i,o.remotePeer,c)))return n.log.error("connection gater denied inbound relayed connection from %p",o.remotePeer),yield s.write({type:Ju.Type.STATUS,status:ed.PERMISSION_DENIED},{signal:r}),void(yield a.close({signal:r}));n.log.trace("sending success response to %p",o.remotePeer),yield s.write({type:Ju.Type.STATUS,status:ed.OK},{signal:r});var u=new nh(l.limit),d=o.remoteAddr.encapsulate("/p2p-circuit/p2p/".concat(c.toString()));n.addressManager.getAddresses()[0];var h=Th({stream:s.unwrap().unwrap(),remoteAddr:d,logger:n.logger,onDataRead:u.onData,onDataWrite:u.onData});n.log("new inbound relayed connection %a",h.remoteAddr),yield n.upgrader.upgradeInbound(h,{limits:u.getLimits(),signal:r}),n.log("%s connection %a upgraded","inbound",h.remoteAddr)}))()}}function tp(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new ep(t,e)}!function(e){var t,r;!function(e){e.FIN="FIN",e.STOP_SENDING="STOP_SENDING",e.RESET="RESET",e.FIN_ACK="FIN_ACK"}(e.Flag||(e.Flag={})),function(e){e[e.FIN=0]="FIN",e[e.STOP_SENDING=1]="STOP_SENDING",e[e.RESET=2]="RESET",e[e.FIN_ACK=3]="FIN_ACK"}(t||(t={})),function(e){e.codec=()=>pl(t)}(e.Flag||(e.Flag={})),e.codec=()=>(null==r&&(r=fl((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==n.lengthDelimited&&r.fork(),null!=t.flag&&(r.uint32(8),e.Flag.codec().encode(t.flag,r)),null!=t.message&&(r.uint32(18),r.bytes(t.message)),!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n={},i=null==r?t.len:t.pos+r;t.pos<i;){var o=t.uint32();switch(o>>>3){case 1:n.flag=e.Flag.codec().decode(t);break;case 2:n.message=t.bytes();break;default:t.skipType(7&o)}}return n}))),r),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(Zh||(Zh={}));var rp=["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478","stun:stun.cloudflare.com:3478","stun:stun.services.mozilla.com:3478"],np=Array.from("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"),ip=16384;var op=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:ip,t=yt(e-yt(e)),r=1+yt(Object.keys(Zh.Flag).length-1);return t+r+1+yt(e-t-r-1)}(),ap="/webrtc",sp="/webrtc-signaling/0.0.1",lp=864e5,cp=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i<o;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))},up=function(e,t,r){this.name=e,this.version=t,this.os=r,this.type="browser"},dp=function(t){this.version=t,this.type="node",this.name="node",this.os=e.process.platform},hp=function(e,t,r,n){this.name=e,this.version=t,this.os=r,this.bot=n,this.type="bot-device"},pp=function(){this.type="bot",this.bot=!0,this.name="bot",this.version=null,this.os=null},fp=function(){this.type="react-native",this.name="react-native",this.version=null,this.os=null},vp=/(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/,yp=[["aol",/AOLShield\/([0-9\._]+)/],["edge",/Edge\/([0-9\._]+)/],["edge-ios",/EdgiOS\/([0-9\._]+)/],["yandexbrowser",/YaBrowser\/([0-9\._]+)/],["kakaotalk",/KAKAOTALK\s([0-9\.]+)/],["samsung",/SamsungBrowser\/([0-9\.]+)/],["silk",/\bSilk\/([0-9._-]+)\b/],["miui",/MiuiBrowser\/([0-9\.]+)$/],["beaker",/BeakerBrowser\/([0-9\.]+)/],["edge-chromium",/EdgA?\/([0-9\.]+)/],["chromium-webview",/(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["chrome",/(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/],["phantomjs",/PhantomJS\/([0-9\.]+)(:?\s|$)/],["crios",/CriOS\/([0-9\.]+)(:?\s|$)/],["firefox",/Firefox\/([0-9\.]+)(?:\s|$)/],["fxios",/FxiOS\/([0-9\.]+)/],["opera-mini",/Opera Mini.*Version\/([0-9\.]+)/],["opera",/Opera\/([0-9\.]+)(?:\s|$)/],["opera",/OPR\/([0-9\.]+)(:?\s|$)/],["pie",/^Microsoft Pocket Internet Explorer\/(\d+\.\d+)$/],["pie",/^Mozilla\/\d\.\d+\s\(compatible;\s(?:MSP?IE|MSInternet Explorer) (\d+\.\d+);.*Windows CE.*\)$/],["netfront",/^Mozilla\/\d\.\d+.*NetFront\/(\d.\d)/],["ie",/Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/],["ie",/MSIE\s([0-9\.]+);.*Trident\/[4-7].0/],["ie",/MSIE\s(7\.0)/],["bb10",/BB10;\sTouch.*Version\/([0-9\.]+)/],["android",/Android\s([0-9\.]+)/],["ios",/Version\/([0-9\._]+).*Mobile.*Safari.*/],["safari",/Version\/([0-9\._]+).*Safari/],["facebook",/FB[AS]V\/([0-9\.]+)/],["instagram",/Instagram\s([0-9\.]+)/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Mobile/],["ios-webview",/AppleWebKit\/([0-9\.]+).*Gecko\)$/],["curl",/^curl\/([0-9\.]+)$/],["searchbot",/alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/]],gp=[["iOS",/iP(hone|od|ad)/],["Android OS",/Android/],["BlackBerry OS",/BlackBerry|BB10/],["Windows Mobile",/IEMobile/],["Amazon OS",/Kindle/],["Windows 3.11",/Win16/],["Windows 95",/(Windows 95)|(Win95)|(Windows_95)/],["Windows 98",/(Windows 98)|(Win98)/],["Windows 2000",/(Windows NT 5.0)|(Windows 2000)/],["Windows XP",/(Windows NT 5.1)|(Windows XP)/],["Windows Server 2003",/(Windows NT 5.2)/],["Windows Vista",/(Windows NT 6.0)/],["Windows 7",/(Windows NT 6.1)/],["Windows 8",/(Windows NT 6.2)/],["Windows 8.1",/(Windows NT 6.3)/],["Windows 10",/(Windows NT 10.0)/],["Windows ME",/Windows ME/],["Windows CE",/Windows CE|WinCE|Microsoft Pocket Internet Explorer/],["Open BSD",/OpenBSD/],["Sun OS",/SunOS/],["Chrome OS",/CrOS/],["Linux",/(Linux)|(X11)/],["Mac OS",/(Mac_PowerPC)|(Macintosh)/],["QNX",/QNX/],["BeOS",/BeOS/],["OS/2",/OS\/2/]];class mp extends Error{constructor(e){super(e),this.name="TimeoutError"}}let wp=class extends Error{constructor(e){super(),this.name="AbortError",this.message=e}};var bp=e=>void 0===globalThis.DOMException?new wp(e):new DOMException(e),_p=e=>{var t=void 0===e.reason?bp("This operation was aborted."):e.reason;return t instanceof Error?t:bp(t)};function Sp(t,r){var n,i,{milliseconds:o,fallback:a,message:s,customTimers:l={setTimeout:setTimeout,clearTimeout:clearTimeout}}=r,c=new Promise(((c,u)=>{if("number"!=typeof o||1!==Math.sign(o))throw new TypeError("Expected `milliseconds` to be a positive number, got `".concat(o,"`"));if(r.signal){var{signal:d}=r;d.aborted&&u(_p(d)),i=()=>{u(_p(d))},d.addEventListener("abort",i,{once:!0})}if(o!==Number.POSITIVE_INFINITY){var h=new mp;n=l.setTimeout.call(void 0,(()=>{if(a)try{c(a())}catch(e){u(e)}else"function"==typeof t.cancel&&t.cancel(),!1===s?c():s instanceof Error?u(s):(h.message=null!=s?s:"Promise timed out after ".concat(o," milliseconds"),u(h))}),o),e._asyncToGenerator((function*(){try{c(yield t)}catch(e){u(e)}}))()}else t.then(c,u)})),u=c.finally((()=>{u.clear(),i&&r.signal&&r.signal.removeEventListener("abort",i)}));return u.clear=()=>{l.clearTimeout.call(void 0,n),n=void 0},u}var Pp="undefined"==typeof document&&"undefined"!=typeof navigator&&"ReactNative"===navigator.product?new fp:"undefined"!=typeof navigator?function(e){var t=function(e){return""!==e&&yp.reduce((function(t,r){var n=r[0],i=r[1];if(t)return t;var o=i.exec(e);return!!o&&[n,o]}),!1)}(e);if(!t)return null;var r=t[0],n=t[1];if("searchbot"===r)return new pp;var i=n[1]&&n[1].split(".").join("_").split("_").slice(0,3);i?i.length<3&&(i=cp(cp([],i,!0),function(e){for(var t=[],r=0;r<e;r++)t.push("0");return t}(3-i.length),!0)):i=[];var o=i.join("."),a=function(e){for(var t=0,r=gp.length;t<r;t++){var n=gp[t],i=n[0];if(n[1].exec(e))return i}return null}(e),s=vp.exec(e);return s&&s[1]?new hp(r,o,a,s[1]):new up(r,o,a)}(navigator.userAgent):void 0!==e.process&&e.process.version?new dp(e.process.version.slice(1)):null,Ep=null!=Pp&&"firefox"===Pp.name,Ap=function(){var t=e._wrapAsyncGenerator((function*(){}));return function(){return t.apply(this,arguments)}}(),kp=function(){var t=e._asyncToGenerator((function*(e){}));return function(e){return t.apply(this,arguments)}}();function xp(e){return Tp.apply(this,arguments)}function Tp(){return(Tp=e._asyncToGenerator((function*(e){var t;return"function"==typeof(e=null!=e?e:{})&&(e=yield e()),e.iceServers=null!==(t=e.iceServers)&&void 0!==t?t:rp.map((e=>({urls:[e]}))),e}))).apply(this,arguments)}class Ip{constructor(t,r){e._defineProperty(this,"log",void 0),e._defineProperty(this,"peerConnection",void 0),e._defineProperty(this,"remoteAddr",void 0),e._defineProperty(this,"timeline",void 0),e._defineProperty(this,"metrics",void 0),e._defineProperty(this,"source",Ap()),e._defineProperty(this,"sink",kp),this.log=t.logger.forComponent("libp2p:webrtc:maconn"),this.remoteAddr=r.remoteAddr,this.timeline=r.timeline,this.peerConnection=r.peerConnection;var n=this.peerConnection,i=n.connectionState;this.peerConnection.onconnectionstatechange=()=>{this.log.trace("peer connection state change",n.connectionState,"initial state",i),"disconnected"!==n.connectionState&&"failed"!==n.connectionState&&"closed"!==n.connectionState||(this.timeline.close=Date.now())}}close(t){var r=this;return e._asyncToGenerator((function*(){var e;r.log.trace("closing connection"),r.peerConnection.close(),r.timeline.close=Date.now(),null===(e=r.metrics)||void 0===e||e.increment({close:!0})}))()}abort(e){var t;this.log.error("closing connection due to error",e),this.peerConnection.close(),this.timeline.close=Date.now(),null===(t=this.metrics)||void 0===t||t.increment({abort:!0})}}function Cp(e){if(null!=e){if("function"==typeof e[Symbol.iterator])return e[Symbol.iterator]();if("function"==typeof e[Symbol.asyncIterator])return e[Symbol.asyncIterator]();if("function"==typeof e.next)return e}throw new Error("argument is not an iterator or iterable")}function Bp(e,t){var r,n,i,o=null===(r=(n=Cp(e)).return)||void 0===r?void 0:r.call(n);null!=(i=o)&&"function"==typeof i.then&&"function"==typeof i.catch&&"function"==typeof i.finally&&o.catch((e=>{t.error("could not cause iterator to return",e)}))}function Np(e){return null!=e&&("function"==typeof e.then&&"function"==typeof e.catch&&"function"==typeof e.finally)}class Dp{constructor(t){var r,n;e._defineProperty(this,"id",void 0),e._defineProperty(this,"direction",void 0),e._defineProperty(this,"timeline",void 0),e._defineProperty(this,"protocol",void 0),e._defineProperty(this,"metadata",void 0),e._defineProperty(this,"source",void 0),e._defineProperty(this,"status",void 0),e._defineProperty(this,"readStatus",void 0),e._defineProperty(this,"writeStatus",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"sinkController",void 0),e._defineProperty(this,"sinkEnd",void 0),e._defineProperty(this,"closed",void 0),e._defineProperty(this,"endErr",void 0),e._defineProperty(this,"streamSource",void 0),e._defineProperty(this,"onEnd",void 0),e._defineProperty(this,"onCloseRead",void 0),e._defineProperty(this,"onCloseWrite",void 0),e._defineProperty(this,"onReset",void 0),e._defineProperty(this,"onAbort",void 0),e._defineProperty(this,"sendCloseWriteTimeout",void 0),e._defineProperty(this,"sendingData",void 0),this.sinkController=new AbortController,this.sinkEnd=Yc(),this.closed=Yc(),this.log=t.log,this.status="open",this.readStatus="ready",this.writeStatus="ready",this.id=t.id,this.metadata=null!==(r=t.metadata)&&void 0!==r?r:{},this.direction=t.direction,this.timeline={open:Date.now()},this.sendCloseWriteTimeout=null!==(n=t.sendCloseWriteTimeout)&&void 0!==n?n:5e3,this.onEnd=t.onEnd,this.onCloseRead=t.onCloseRead,this.onCloseWrite=t.onCloseWrite,this.onReset=t.onReset,this.onAbort=t.onAbort,this.source=this.streamSource=Xc({onEnd:e=>{null!=e?this.log.trace("source ended with error",e):this.log.trace("source ended"),this.onSourceEnd(e)}}),this.sink=this.sink.bind(this)}sink(t){var r=this;return e._asyncToGenerator((function*(){if("ready"!==r.writeStatus)throw new ca('writable end state is "'.concat(r.writeStatus,'" not "ready"'));try{r.writeStatus="writing";var n={signal:r.sinkController.signal};if("outbound"===r.direction){var i=r.sendNewStream(n);Np(i)&&(yield i)}var o=()=>{Bp(t,r.log)};try{r.sinkController.signal.addEventListener("abort",o),r.log.trace("sink reading from source");var a,s=!1,l=!1;try{for(var c,u=e._asyncIterator(t);s=!(c=yield u.next()).done;s=!1){var d=c.value;d=d instanceof Uint8Array?new Fa(d):d;var h=r.sendData(d,n);Np(h)&&(r.sendingData=Yc(),yield h,r.sendingData.resolve(),r.sendingData=void 0)}}catch(e){l=!0,a=e}finally{try{s&&null!=u.return&&(yield u.return())}finally{if(l)throw a}}}finally{r.sinkController.signal.removeEventListener("abort",o)}r.log.trace('sink finished reading from source, write status is "%s"',r.writeStatus),"writing"===r.writeStatus&&(r.writeStatus="closing",r.log.trace("send close write to remote"),yield r.sendCloseWrite({signal:AbortSignal.timeout(r.sendCloseWriteTimeout)}),r.writeStatus="closed"),r.onSinkEnd()}catch(e){throw r.log.trace("sink ended with error, calling abort with error",e),r.abort(e),e}finally{r.log.trace("resolve sink end"),r.sinkEnd.resolve()}}))()}onSourceEnd(e){var t;null==this.timeline.closeRead&&(this.timeline.closeRead=Date.now(),this.readStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),null===(t=this.onCloseRead)||void 0===t||t.call(this),null!=this.timeline.closeWrite?(this.log.trace("source and sink ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("source ended, waiting for sink to end"))}onSinkEnd(e){var t;null==this.timeline.closeWrite&&(this.timeline.closeWrite=Date.now(),this.writeStatus="closed",null!=e&&null==this.endErr&&(this.endErr=e),null===(t=this.onCloseWrite)||void 0===t||t.call(this),null!=this.timeline.closeRead?(this.log.trace("sink and source ended"),this.timeline.close=Date.now(),"aborted"!==this.status&&"reset"!==this.status&&(this.status="closed"),null!=this.onEnd&&this.onEnd(this.endErr),this.closed.resolve()):this.log.trace("sink ended, waiting for source to end"))}close(t){var r=this;return e._asyncToGenerator((function*(){"open"===r.status&&(r.log.trace("closing gracefully"),r.status="closing",yield tu(Promise.all([r.closeWrite(t),r.closeRead(t),r.closed.promise]),null==t?void 0:t.signal),r.status="closed",r.log.trace("closed gracefully"))}))()}closeRead(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var e=t.length>0&&void 0!==t[0]?t[0]:{};if("closing"!==r.readStatus&&"closed"!==r.readStatus){r.log.trace('closing readable end of stream with starting read status "%s"',r.readStatus);var n=r.readStatus;r.readStatus="closing","reset"!==r.status&&"aborted"!==r.status&&null==r.timeline.closeRead&&(r.log.trace("send close read to remote"),yield r.sendCloseRead(e)),"ready"===n&&(r.log.trace("ending internal source queue with %d queued bytes",r.streamSource.readableLength),r.streamSource.end()),r.log.trace("closed readable end of stream")}}))()}closeWrite(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var e=t.length>0&&void 0!==t[0]?t[0]:{};"closing"!==r.writeStatus&&"closed"!==r.writeStatus&&(r.log.trace('closing writable end of stream with starting write status "%s"',r.writeStatus),"ready"===r.writeStatus&&(r.log.trace("sink was never sunk, sink an empty array"),yield tu(r.sink([]),e.signal)),"writing"===r.writeStatus&&(null!=r.sendingData&&(yield tu(r.sendingData.promise,e.signal)),r.log.trace("aborting source passed to .sink"),r.sinkController.abort(),yield tu(r.sinkEnd.promise,e.signal)),r.writeStatus="closed",r.log.trace("closed writable end of stream"))}))()}abort(e){var t;if("closed"!==this.status&&"aborted"!==this.status&&"reset"!==this.status){this.log("abort with error",e),this.log("try to send reset to remote");var r=this.sendReset();Np(r)&&r.catch((e=>{this.log.error("error sending reset message",e)})),this.status="aborted",this.timeline.abort=Date.now(),this._closeSinkAndSource(e),null===(t=this.onAbort)||void 0===t||t.call(this,e)}}reset(){var e;if("closed"!==this.status&&"aborted"!==this.status&&"reset"!==this.status){var t=new la("stream reset");this.status="reset",this.timeline.reset=Date.now(),this._closeSinkAndSource(t),null===(e=this.onReset)||void 0===e||e.call(this)}}_closeSinkAndSource(e){this._closeSink(e),this._closeSource(e)}_closeSink(e){"writing"===this.writeStatus&&(this.log.trace("end sink source"),this.sinkController.abort()),this.onSinkEnd(e)}_closeSource(e){"closing"!==this.readStatus&&"closed"!==this.readStatus&&(this.log.trace("ending source with %d bytes to be read by consumer",this.streamSource.readableLength),this.readStatus="closing",this.streamSource.end(e))}remoteCloseWrite(){"closing"!==this.readStatus&&"closed"!==this.readStatus?(this.log.trace("remote close write"),this._closeSource()):this.log("received remote close write but local source is already closed")}remoteCloseRead(){"closing"!==this.writeStatus&&"closed"!==this.writeStatus?(this.log.trace("remote close read"),this._closeSink()):this.log("received remote close read but local sink is already closed")}destroy(){"closed"!==this.status&&"aborted"!==this.status&&"reset"!==this.status?(this.log.trace("stream destroyed"),this._closeSinkAndSource()):this.log("received destroy but we are already closed")}sourcePush(e){this.streamSource.push(e)}sourceReadableLength(){return this.streamSource.readableLength}}var Gp=4194304;let Rp=class extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidMessageLengthError"),e._defineProperty(this,"code","ERR_INVALID_MSG_LENGTH")}},Op=class extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidDataLengthError"),e._defineProperty(this,"code","ERR_MSG_DATA_TOO_LONG")}},Lp=class extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidDataLengthLengthError"),e._defineProperty(this,"code","ERR_MSG_LENGTH_TOO_LONG")}},Mp=class extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","UnexpectedEOFError"),e._defineProperty(this,"code","ERR_UNEXPECTED_EOF")}};function jp(e){return null!=e[Symbol.asyncIterator]}function Fp(e,t){if(e.byteLength>t)throw new Op("Message length too long")}var Up,zp=e=>{var t=yt(e),r=Ke(t);return wt(e,r),zp.bytes=t,r};function Vp(t,r){var n,i,o,a=null!==(n=(r=null!=r?r:{}).lengthEncoder)&&void 0!==n?n:zp,s=null!==(i=null===(o=r)||void 0===o?void 0:o.maxDataLength)&&void 0!==i?i:Gp;function*l(e){Fp(e,s);var t=a(e.byteLength);t instanceof Uint8Array?yield t:yield*t,e instanceof Uint8Array?yield e:yield*e}return jp(t)?e._wrapAsyncGenerator((function*(){var r,n=!1,i=!1;try{for(var o,a=e._asyncIterator(t);n=!(o=yield e._awaitAsyncGenerator(a.next())).done;n=!1){var s=o.value;yield*e._asyncGeneratorDelegate(e._asyncIterator(l(s)),e._awaitAsyncGenerator)}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield e._awaitAsyncGenerator(a.return()))}finally{if(i)throw r}}}))():function*(){for(var e of t)yield*l(e)}()}zp.bytes=0,Vp.single=(e,t)=>{var r,n,i,o=null!==(r=(t=null!=t?t:{}).lengthEncoder)&&void 0!==r?r:zp;return Fp(e,null!==(n=null===(i=t)||void 0===i?void 0:i.maxDataLength)&&void 0!==n?n:Gp),new Fa(o(e.byteLength),e)},function(e){e[e.LENGTH=0]="LENGTH",e[e.DATA=1]="DATA"}(Up||(Up={}));var qp=e=>{var t=bt(e);return qp.bytes=yt(t),t};function Hp(t,r){var n,i,o,a=new Fa,s=Up.LENGTH,l=-1,c=null!==(n=null==r?void 0:r.lengthDecoder)&&void 0!==n?n:qp,u=null!==(i=null==r?void 0:r.maxLengthLength)&&void 0!==i?i:8,d=null!==(o=null==r?void 0:r.maxDataLength)&&void 0!==o?o:Gp;function*h(){for(;a.byteLength>0;){if(s===Up.LENGTH)try{if((l=c(a))<0)throw new Rp("Invalid message length");if(l>d)throw new Op("Message length too long");var e=c.bytes;a.consume(e),null!=(null==r?void 0:r.onLength)&&r.onLength(l),s=Up.DATA}catch(e){if(e instanceof RangeError){if(a.byteLength>u)throw new Lp("Message length length too long");break}throw e}if(s===Up.DATA){if(a.byteLength<l)break;var t=a.sublist(0,l);a.consume(l),null!=(null==r?void 0:r.onData)&&r.onData(t),yield t,s=Up.LENGTH}}}return jp(t)?e._wrapAsyncGenerator((function*(){var r,n=!1,i=!1;try{for(var o,s=e._asyncIterator(t);n=!(o=yield e._awaitAsyncGenerator(s.next())).done;n=!1){var l=o.value;a.append(l),yield*e._asyncGeneratorDelegate(e._asyncIterator(h()),e._awaitAsyncGenerator)}}catch(e){i=!0,r=e}finally{try{n&&null!=s.return&&(yield e._awaitAsyncGenerator(s.return()))}finally{if(i)throw r}}if(a.byteLength>0)throw new Mp("Unexpected end of input")}))():function*(){for(var e of t)a.append(e),yield*h();if(a.byteLength>0)throw new Mp("Unexpected end of input")}()}qp.bytes=0,Hp.fromReader=(t,r)=>{var n=1;return Hp(e._wrapAsyncGenerator((function*(){for(;;)try{var{done:r,value:i}=yield e._awaitAsyncGenerator(t.next(n));if(!0===r)return;null!=i&&(yield i)}catch(e){if("ERR_UNDER_READ"===e.code)return{done:!0,value:null};throw e}finally{n=1}}))(),e._objectSpread2(e._objectSpread2({},null!=r?r:{}),{},{onLength:e=>{n=e}}))};class Kp extends Dp{constructor(t){var r,n,i,o,a,s,l=t.onEnd;switch(t.onEnd=t=>{this.log.trace('readable and writeable ends closed with status "%s"',this.status),Promise.resolve(e._asyncToGenerator((function*(){if(null==r.timeline.abort&&null===r.timeline.reset)try{yield Sp(r.receiveFinAck.promise,{milliseconds:r.finAckTimeout})}catch(e){r.log.error("error receiving FIN_ACK",e)}}))).then((()=>{this.incomingData.end(),null==l||l(t)})).catch((e=>{this.log.error("error ending stream",e)})).finally((()=>{this.channel.close()}))},super(t),r=this,e._defineProperty(this,"channel",void 0),e._defineProperty(this,"incomingData",void 0),e._defineProperty(this,"maxBufferedAmount",void 0),e._defineProperty(this,"bufferedAmountLowEventTimeout",void 0),e._defineProperty(this,"maxMessageSize",void 0),e._defineProperty(this,"receiveFinAck",void 0),e._defineProperty(this,"finAckTimeout",void 0),e._defineProperty(this,"openTimeout",void 0),e._defineProperty(this,"closeController",void 0),this.channel=t.channel,this.channel.binaryType="arraybuffer",this.incomingData=Xc(),this.bufferedAmountLowEventTimeout=null!==(n=t.bufferedAmountLowEventTimeout)&&void 0!==n?n:3e4,this.maxBufferedAmount=null!==(i=t.maxBufferedAmount)&&void 0!==i?i:2097152,this.maxMessageSize=(null!==(o=t.maxMessageSize)&&void 0!==o?o:ip)-op,this.receiveFinAck=Yc(),this.finAckTimeout=null!==(a=t.closeTimeout)&&void 0!==a?a:5e3,this.openTimeout=null!==(s=t.openTimeout)&&void 0!==s?s:5e3,this.closeController=new AbortController,this.channel.readyState){case"open":this.timeline.open=(new Date).getTime();break;case"closed":case"closing":void 0!==this.timeline.close&&0!==this.timeline.close||(this.timeline.close=Date.now());break;case"connecting":break;default:throw this.log.error("unknown datachannel state %s",this.channel.readyState),new ca("Unknown datachannel state")}this.channel.onopen=e=>{this.timeline.open=(new Date).getTime()},this.channel.onclose=e=>{this.log.trace("received onclose event"),this.closeController.abort(),this.receiveFinAck.resolve(),this.close().catch((e=>{this.log.error("error closing stream after channel closed",e)}))},this.channel.onerror=e=>{this.log.trace("received onerror event"),this.closeController.abort();var t=e.error;this.abort(t)},this.channel.onmessage=function(){var t=e._asyncToGenerator((function*(e){var{data:t}=e;null!==t&&0!==t.byteLength&&r.incomingData.push(new Uint8Array(t,0,t.byteLength))}));return function(e){return t.apply(this,arguments)}}();var c=this;Promise.resolve().then(e._asyncToGenerator((function*(){var t,n=!1,i=!1;try{for(var o,a=e._asyncIterator(Hp(r.incomingData));n=!(o=yield a.next()).done;n=!1){var s=o.value,l=c.processIncomingProtobuf(s);null!=l&&c.sourcePush(new Fa(l))}}catch(e){i=!0,t=e}finally{try{n&&null!=a.return&&(yield a.return())}finally{if(i)throw t}}}))).catch((e=>{this.log.error("error processing incoming data channel messages",e)}))}sendNewStream(){}_sendMessage(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=!(r.length>1&&void 0!==r[1])||r[1];if("closed"===n.channel.readyState||"closing"===n.channel.readyState)throw new ca("Invalid datachannel state - ".concat(n.channel.readyState));if("open"!==n.channel.readyState){var i=AbortSignal.timeout(n.openTimeout),o=$d([n.closeController.signal,i]);try{n.log('channel state is "%s" and not "open", waiting for "open" event before sending data',n.channel.readyState),yield Bh(n.channel,"open",o)}finally{o.clear()}n.log('channel state is now "%s", sending data',n.channel.readyState)}if(e&&n.channel.bufferedAmount>n.maxBufferedAmount){var a=AbortSignal.timeout(n.bufferedAmountLowEventTimeout),s=$d([n.closeController.signal,a]);try{n.log('channel buffer is %d, wait for "bufferedamountlow" event',n.channel.bufferedAmount),yield Bh(n.channel,"bufferedamountlow",s)}catch(e){if(a.aborted)throw new ma("Timed out waiting for DataChannel buffer to clear after ".concat(n.bufferedAmountLowEventTimeout,"ms"));throw e}finally{s.clear()}}try{n.log.trace('sending message, channel state "%s"',n.channel.readyState),n.channel.send(t.subarray())}catch(e){n.log.error("error while sending message",e)}}))()}sendData(t){var r=this;return e._asyncToGenerator((function*(){var e=t.byteLength;for(t=t.sublist();t.byteLength>0;){var n=Math.min(t.byteLength,r.maxMessageSize),i=t.subarray(0,n),o=Zh.encode({message:i}),a=Vp.single(o);r.log.trace("sending %d/%d bytes on channel",i.byteLength,e),yield r._sendMessage(a),t.consume(n)}r.log.trace('finished sending data, channel state "%s"',r.channel.readyState)}))()}sendReset(){var t=this;return e._asyncToGenerator((function*(){try{yield t._sendFlag(Zh.Flag.RESET)}catch(e){t.log.error("failed to send reset - %e",e)}finally{t.channel.close()}}))()}sendCloseWrite(t){var r=this;return e._asyncToGenerator((function*(){if("open"===r.channel.readyState){if(yield r._sendFlag(Zh.Flag.FIN)){r.log.trace("awaiting FIN_ACK");try{yield tu(r.receiveFinAck.promise,null==t?void 0:t.signal,{errorMessage:"sending close-write was aborted before FIN_ACK was received",errorName:"FinAckNotReceivedError"})}catch(e){r.log.error("failed to await FIN_ACK",e)}}else r.log.trace("sending FIN failed, not awaiting FIN_ACK");r.receiveFinAck.resolve()}else r.receiveFinAck.resolve()}))()}sendCloseRead(){var t=this;return e._asyncToGenerator((function*(){"open"===t.channel.readyState&&(yield t._sendFlag(Zh.Flag.STOP_SENDING))}))()}processIncomingProtobuf(e){var t=Zh.decode(e);if(void 0!==t.flag&&(this.log.trace('incoming flag %s, write status "%s", read status "%s"',t.flag,this.writeStatus,this.readStatus),t.flag===Zh.Flag.FIN&&(this.remoteCloseWrite(),this.log.trace("sending FIN_ACK"),this._sendFlag(Zh.Flag.FIN_ACK).catch((e=>{this.log.error("error sending FIN_ACK immediately",e)}))),t.flag===Zh.Flag.RESET&&this.reset(),t.flag===Zh.Flag.STOP_SENDING&&this.remoteCloseRead(),t.flag===Zh.Flag.FIN_ACK&&(this.log.trace("received FIN_ACK"),this.receiveFinAck.resolve())),"ready"===this.readStatus)return t.message}_sendFlag(t){var r=this;return e._asyncToGenerator((function*(){if("open"!==r.channel.readyState)return r.log.trace('not sending flag %s because channel is "%s" and not "open"',t.toString(),r.channel.readyState),!1;r.log.trace("sending flag %s",t.toString());var e=Zh.encode({flag:t}),n=Vp.single(e);try{return yield r._sendMessage(n,!1),!0}catch(e){r.log.error("could not send flag %s - %e",t.toString(),e)}return!1}))()}}function Wp(t){var{channel:r,direction:n,handshake:i}=t;return new Kp(e._objectSpread2({id:"".concat(r.id),log:t.logger.forComponent("libp2p:webrtc:stream:".concat(!0===i?"handshake":n,":").concat(r.id))},t))}class Qp{constructor(t,r){var n,i;e._defineProperty(this,"protocol",void 0),e._defineProperty(this,"peerConnection",void 0),e._defineProperty(this,"bufferedStreams",[]),e._defineProperty(this,"metrics",void 0),e._defineProperty(this,"dataChannelOptions",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"log",void 0),this.components=t,this.peerConnection=r.peerConnection,this.metrics=r.metrics,this.protocol=null!==(n=r.protocol)&&void 0!==n?n:ap,this.dataChannelOptions=null!==(i=r.dataChannelOptions)&&void 0!==i?i:{},this.log=t.logger.forComponent("libp2p:webrtc:muxerfactory"),this.peerConnection.ondatachannel=r=>{var{channel:n}=r;if(this.log.trace('incoming early datachannel with channel id %d and label "%s"',n.id),"init"===n.label)return this.log.trace("closing early init channel"),void n.close();var i={},o=Wp(e._objectSpread2({channel:n,direction:"inbound",onEnd:e=>{i.onEnd(e)},logger:t.logger},this.dataChannelOptions));i.stream=o,i.channel=n,i.onEnd=()=>{this.bufferedStreams=this.bufferedStreams.filter((e=>e.stream.id!==o.id))},this.bufferedStreams.push(i)}}createStreamMuxer(t){return new Jp(this.components,e._objectSpread2(e._objectSpread2({},t),{},{peerConnection:this.peerConnection,dataChannelOptions:this.dataChannelOptions,metrics:this.metrics,streams:this.bufferedStreams,protocol:this.protocol}))}}var Yp=new WeakSet;class Jp{constructor(t,r){var n,i;e._classPrivateMethodInitSpec(this,Yp),e._defineProperty(this,"init",void 0),e._defineProperty(this,"streams",void 0),e._defineProperty(this,"protocol",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"peerConnection",void 0),e._defineProperty(this,"dataChannelOptions",void 0),e._defineProperty(this,"metrics",void 0),e._defineProperty(this,"logger",void 0),e._defineProperty(this,"source",Ap()),e._defineProperty(this,"sink",kp),this.init=r,this.log=t.logger.forComponent("libp2p:webrtc:muxer"),this.logger=t.logger,this.streams=r.streams.map((e=>e.stream)),this.peerConnection=r.peerConnection,this.protocol=null!==(n=r.protocol)&&void 0!==n?n:ap,this.metrics=r.metrics,this.dataChannelOptions=null!==(i=r.dataChannelOptions)&&void 0!==i?i:{},this.peerConnection.ondatachannel=t=>{var n,i,{channel:o}=t;if(this.log.trace("incoming datachannel with channel id %d",o.id),"init"===o.label)return this.log.trace("closing init channel"),void o.close();var a=o.id,s=Wp(e._objectSpread2({channel:o,direction:"inbound",onEnd:()=>{e._assertClassBrand(Yp,this,Zp).call(this,s,o),this.log("incoming channel %s ended",a)},logger:this.logger},this.dataChannelOptions));this.streams.push(s),null===(n=this.metrics)||void 0===n||n.increment({incoming_stream:!0}),null==r||null===(i=r.onIncomingStream)||void 0===i||i.call(r,s)},this.init.streams.length>0&&queueMicrotask((()=>{this.init.streams.forEach((t=>{var r,n,i;t.onEnd=()=>{this.log("incoming early channel %s ended with state %s",t.channel.id,t.channel.readyState),e._assertClassBrand(Yp,this,Zp).call(this,t.stream,t.channel)},null===(r=this.metrics)||void 0===r||r.increment({incoming_stream:!0}),null===(n=this.init)||void 0===n||null===(i=n.onIncomingStream)||void 0===i||i.call(n,t.stream)}))}))}close(t){var r=this;return e._asyncToGenerator((function*(){try{yield Promise.all(r.streams.map(function(){var r=e._asyncToGenerator((function*(e){return e.close(t)}));return function(e){return r.apply(this,arguments)}}()))}catch(e){r.abort(e)}}))()}abort(e){for(var t of this.streams)t.abort(e)}newStream(){var t,r=this.peerConnection.createDataChannel(""),n=r.id;this.log.trace("opened outgoing datachannel with channel id %s",n);var i=Wp(e._objectSpread2({channel:r,direction:"outbound",onEnd:()=>{e._assertClassBrand(Yp,this,Zp).call(this,i,r),this.log("outgoing channel %s ended",n)},logger:this.logger},this.dataChannelOptions));return this.streams.push(i),null===(t=this.metrics)||void 0===t||t.increment({outgoing_stream:!0}),i}}function Zp(t,r){var n,i,o;this.log.trace("stream %s %s %s onEnd",t.direction,t.id,t.protocol),function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:3e4,i=arguments.length>3?arguments[3]:void 0;"open"===t.readyState&&Promise.resolve().then(e._asyncToGenerator((function*(){if(t.bufferedAmount>0){i.log("%s drain channel with %d buffered bytes",r,t.bufferedAmount);var e=Yc(),o=!1;t.bufferedAmountLowThreshold=0;var a=()=>{o||(i.log("%s drain channel closed before drain",r),e.resolve())};t.addEventListener("close",a,{once:!0}),t.addEventListener("bufferedamountlow",(()=>{o=!0,t.removeEventListener("close",a),e.resolve()})),yield Sp(e.promise,{milliseconds:n})}}))).then(e._asyncToGenerator((function*(){"open"===t.readyState&&t.close()}))).catch((e=>{i.log.error("error closing outbound stream",e)}))}(r,"".concat(t.direction," ").concat(t.id," ").concat(t.protocol),this.dataChannelOptions.drainTimeout,{log:this.log}),this.streams=this.streams.filter((e=>e.id!==t.id)),null===(n=this.metrics)||void 0===n||n.increment({stream_end:!0}),null===(i=this.init)||void 0===i||null===(o=i.onStreamEnd)||void 0===o||o.call(i,t)}var $p,Xp=globalThis.RTCPeerConnection,ef=globalThis.RTCSessionDescription,tf=globalThis.RTCIceCandidate;class rf extends Error{constructor(e){super("WebRTC transport error: ".concat(e)),this.name="WebRTCTransportError"}}class nf extends rf{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"SDP handshake failed"),this.name="SDPHandshakeFailedError"}}class of extends rf{constructor(e,t){super('Invalid fingerprint "'.concat(e,'" within ').concat(t)),this.name="WebRTC/InvalidFingerprintError"}}class af extends rf{constructor(e){super("A method (".concat(e,") was called though it has been intentionally left unimplemented.")),this.name="WebRTC/UnimplementedError"}}class sf extends rf{constructor(e){super("unsupported hash algorithm code: ".concat(e," please see the codes at https://github.com/multiformats/multicodec/blob/master/table.csv ")),this.name="WebRTC/UnsupportedHashAlgorithmError"}}!function(e){var t,r;!function(e){e.SDP_OFFER="SDP_OFFER",e.SDP_ANSWER="SDP_ANSWER",e.ICE_CANDIDATE="ICE_CANDIDATE"}(e.Type||(e.Type={})),function(e){e[e.SDP_OFFER=0]="SDP_OFFER",e[e.SDP_ANSWER=1]="SDP_ANSWER",e[e.ICE_CANDIDATE=2]="ICE_CANDIDATE"}(t||(t={})),function(e){e.codec=()=>pl(t)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=fl((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==n.lengthDelimited&&r.fork(),null!=t.type&&(r.uint32(8),e.Type.codec().encode(t.type,r)),null!=t.data&&(r.uint32(18),r.string(t.data)),!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n={},i=null==r?t.len:t.pos+r;t.pos<i;){var o=t.uint32();switch(o>>>3){case 1:n.type=e.Type.codec().decode(t);break;case 2:n.data=t.string();break;default:t.skipType(7&o)}}return n}))),r),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}($p||($p={}));var lf=function(){var t=e._asyncToGenerator((function*(e,t,r){try{var n=Yc();for(!function(e,t){e[Ep?"oniceconnectionstatechange":"onconnectionstatechange"]=r=>{switch(cf(e)){case"connected":t.resolve();break;case"failed":case"disconnected":case"closed":t.reject(new aa("RTCPeerConnection was closed"))}}}(e,n);;){var i,o=yield Promise.race([n.promise,t.read({signal:r.signal}).catch((()=>{}))]);if(null==o){var a;null===(a=r.signal)||void 0===a||a.throwIfAborted();break}if(o.type!==$p.Type.ICE_CANDIDATE)throw new ya("ICE candidate message expected");var s=JSON.parse(null!==(i=o.data)&&void 0!==i?i:"null");if(""!==s&&null!==s){var l=new tf(s);r.log.trace("%s received new ICE candidate %o",r.direction,s);try{var c;null===(c=r.onProgress)||void 0===c||c.call(r,new Ih("webrtc:add-ice-candidate",l.candidate)),yield e.addIceCandidate(l)}catch(e){r.log.error("%s bad candidate received",r.direction,s,e)}}else{var u;null===(u=r.onProgress)||void 0===u||u.call(r,new Ih("webrtc:end-of-ice-candidates")),r.log.trace("end-of-candidates received")}}}catch(t){var d;if(r.log.error("%s error parsing ICE candidate",r.direction,t),!0===(null===(d=r.signal)||void 0===d?void 0:d.aborted)&&"connected"!==cf(e))throw t}}));return function(e,r,n){return t.apply(this,arguments)}}();function cf(e){return Ep?e.iceConnectionState:e.connectionState}function uf(){return uf=e._asyncToGenerator((function*(e){var{rtcConfiguration:t,dataChannel:r,signal:n,metrics:i,multiaddr:o,connectionManager:a,transportManager:s,log:l,logger:c,onProgress:u}=e,{baseAddr:d}=function(e){var t=e.toString().split("/webrtc/");if(2!==t.length)throw new ea("webrtc protocol was not present in multiaddr");if(!t[0].includes("/p2p-circuit"))throw new ea("p2p-circuit protocol was not present in multiaddr");var r=sr(t[0]),n=sr("/"+t[1]).getPeerId();if(null==n)throw new ea("destination peer id was missing");var i=r.protos().pop();if(void 0===i)throw new ea("invalid multiaddr");"p2p"!==i.name&&(r=r.encapsulate("/p2p/".concat(n)));return{baseAddr:r,peerId:rc(n)}}(o);null==i||i.dialerEvents.increment({open:!0}),l.trace("dialing base address: %a",d);var h=d.getPeerId();if(null==h)throw new ea("Relay peer was missing");var p,f=a.getConnections(rc(h)),v=!1;0===f.length?(null==u||u(new Ih("webrtc:dial-relay")),p=yield s.dial(d,{signal:n,onProgress:u}),v=!0):(null==u||u(new Ih("webrtc:reuse-relay-connection")),p=f[0]);try{null==u||u(new Ih("webrtc:open-signaling-stream"));var y=yield p.newStream(sp,{signal:n,runOnLimitedConnection:!0}),g=Wu(y).pb($p),m=new Xp(t),w=new Qp({logger:c},{peerConnection:m,dataChannelOptions:r});try{var b=m.createDataChannel("init");m.onicecandidate=e=>{var t,{candidate:r}=e,i=JSON.stringify(null!==(t=null==r?void 0:r.toJSON())&&void 0!==t?t:null);l.trace("initiator sending ICE candidate %o",r),g.write({type:$p.Type.ICE_CANDIDATE,data:i},{signal:n}).catch((e=>{l.error("error sending ICE candidate",e)}))},m.onicecandidateerror=e=>{l.error("initiator ICE candidate error",e)};var _=yield m.createOffer().catch((e=>{throw l.error("could not execute createOffer",e),new nf("Failed to set createOffer")}));l.trace("initiator send SDP offer %s",_.sdp),null==u||u(new Ih("webrtc:send-sdp-offer")),yield g.write({type:$p.Type.SDP_OFFER,data:_.sdp},{signal:n}),yield m.setLocalDescription(_).catch((e=>{throw l.error("could not execute setLocalDescription",e),new nf("Failed to set localDescription")})),null==u||u(new Ih("webrtc:read-sdp-answer")),l.trace("initiator read SDP answer");var S=yield g.read({signal:n});if(S.type!==$p.Type.SDP_ANSWER)throw new nf("Remote should send an SDP answer");l.trace("initiator received SDP answer %s",S.data);var P=new ef({type:"answer",sdp:S.data});return yield m.setRemoteDescription(P).catch((e=>{throw l.error("could not execute setRemoteDescription",e),new nf("Failed to set remoteDescription")})),l.trace("initiator read candidates until connected"),null==u||u(new Ih("webrtc:read-ice-candidates")),yield lf(m,g,{direction:"initiator",signal:n,log:l,onProgress:u}),l.trace("initiator connected, closing init channel"),b.close(),null==u||u(new Ih("webrtc:close-signaling-stream")),l.trace("closing signaling channel"),yield y.close({signal:n}),l.trace("initiator connected to remote address %s",o),{remoteAddress:o,peerConnection:m,muxerFactory:w}}catch(e){throw l.error("outgoing signaling error",e),m.close(),y.abort(e),e}finally{m.onicecandidate=null,m.onicecandidateerror=null}}finally{if(v)try{yield p.close({signal:n})}catch(e){p.abort(e)}}})),uf.apply(this,arguments)}var df=vd(Wd.matchers[0],sd("p2p-circuit"));class hf extends Ia{constructor(t,r){super(),e._defineProperty(this,"transportManager",void 0),e._defineProperty(this,"shutdownController",void 0),e._defineProperty(this,"events",void 0),this.transportManager=t.transportManager,this.events=t.events,this.shutdownController=r.shutdownController,this.onTransportListening=this.onTransportListening.bind(this)}listen(){var t=this;return e._asyncToGenerator((function*(){t.events.addEventListener("transport:listening",t.onTransportListening)}))()}onTransportListening(e){e.detail.getAddrs().filter((e=>df.exactMatch(e))).map((e=>e.encapsulate("/webrtc"))).length>0&&this.safeDispatchEvent("listening")}getAddrs(){return this.transportManager.getListeners().filter((e=>!(e instanceof hf))).map((e=>e.getAddrs().filter((e=>df.exactMatch(e))).map((e=>e.encapsulate("/webrtc"))))).flat()}updateAnnounceAddrs(){}close(){var t=this;return e._asyncToGenerator((function*(){t.events.removeEventListener("transport:listening",t.onTransportListening),t.shutdownController.abort(),queueMicrotask((()=>{t.safeDispatchEvent("close")}))}))()}}function pf(){return pf=e._asyncToGenerator((function*(e){var{peerConnection:t,stream:r,signal:n,connection:i,log:o}=e;o.trace("new inbound signaling stream");var a=Wu(r).pb($p);try{t.onicecandidate=e=>{var t,{candidate:r}=e,i=JSON.stringify(null!==(t=null==r?void 0:r.toJSON())&&void 0!==t?t:null);o.trace("recipient sending ICE candidate %s",i),a.write({type:$p.Type.ICE_CANDIDATE,data:i},{signal:n}).catch((e=>{o.error("error sending ICE candidate",e)}))},o.trace("recipient read SDP offer");var s,l=yield a.read({signal:n});if(l.type!==$p.Type.SDP_OFFER)throw new nf("expected message type SDP_OFFER, received: ".concat(null!==(s=l.type)&&void 0!==s?s:"undefined"," "));o.trace("recipient received SDP offer %s",l.data);var c=new ef({type:"offer",sdp:l.data});yield t.setRemoteDescription(c).catch((e=>{throw o.error("could not execute setRemoteDescription",e),new nf("Failed to set remoteDescription")}));var u=yield t.createAnswer().catch((e=>{throw o.error("could not execute createAnswer",e),new nf("Failed to create answer")}));o.trace("recipient send SDP answer %s",u.sdp),yield a.write({type:$p.Type.SDP_ANSWER,data:u.sdp},{signal:n}),yield t.setLocalDescription(u).catch((e=>{throw o.error("could not execute setLocalDescription",e),new nf("Failed to set localDescription")})),o.trace("recipient read candidates until connected"),yield lf(t,a,{direction:"recipient",signal:n,log:o})}catch(e){if("connected"!==cf(t))throw o.error("error while handling signaling stream from peer %a",i.remoteAddr,e),t.close(),e;o("error while handling signaling stream from peer %a, ignoring as the RTCPeerConnection is already connected",i.remoteAddr,e)}var d=sr("/webrtc/p2p/".concat(i.remoteAddr.getPeerId()));return o.trace("recipient connected to remote address %s",d),{remoteAddress:d}})),pf.apply(this,arguments)}class ff{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"components",void 0),e._defineProperty(this,"init",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"_started",!1),e._defineProperty(this,"metrics",void 0),e._defineProperty(this,"shutdownController",void 0),e._defineProperty(this,Jo,!0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/webrtc"),e._defineProperty(this,Ra,["@libp2p/transport"]),e._defineProperty(this,Oa,["@libp2p/identify","@libp2p/circuit-relay-v2-transport"]),this.components=t,this.init=r,this.log=t.logger.forComponent("libp2p:webrtc"),this.shutdownController=new AbortController,this.shutdownController.signal,null!=t.metrics&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_dialer_events_total",{label:"event",help:"Total count of WebRTC dialer events by type"}),listenerEvents:t.metrics.registerCounterGroup("libp2p_webrtc_listener_events_total",{label:"event",help:"Total count of WebRTC listener events by type"})})}isStarted(){return this._started}start(){var t=this;return e._asyncToGenerator((function*(){yield t.components.registrar.handle(sp,(e=>{var r=t.components.upgrader.createInboundAbortSignal(t.shutdownController.signal);t._onProtocol(e,r).catch((r=>{t.log.error("failed to handle incoming connect from %p",e.connection.remotePeer,r)})).finally((()=>{r.clear()}))}),{runOnLimitedConnection:!0}),t._started=!0}))()}stop(){var t=this;return e._asyncToGenerator((function*(){yield t.components.registrar.unhandle(sp),t._started=!1}))()}createListener(e){return new hf(this.components,{shutdownController:this.shutdownController})}listenFilter(e){return e.filter(Yd.exactMatch)}dialFilter(e){return this.listenFilter(e)}dial(t,r){var n=this;return e._asyncToGenerator((function*(){var e;n.log.trace("dialing address: %a",t);var{remoteAddress:i,peerConnection:o,muxerFactory:a}=yield function(e){return uf.apply(this,arguments)}({rtcConfiguration:yield xp(n.init.rtcConfiguration),dataChannel:n.init.dataChannel,multiaddr:t,dataChannelOptions:n.init.dataChannel,signal:r.signal,connectionManager:n.components.connectionManager,transportManager:n.components.transportManager,log:n.log,logger:n.components.logger,onProgress:r.onProgress}),s=new Ip(n.components,{peerConnection:o,timeline:{open:Date.now()},remoteAddr:i,metrics:null===(e=n.metrics)||void 0===e?void 0:e.dialerEvents}),l=yield r.upgrader.upgradeOutbound(s,{skipProtection:!0,skipEncryption:!0,muxerFactory:a,onProgress:r.onProgress,signal:r.signal});return n._closeOnShutdown(o,s),l}))()}_onProtocol(t,r){var n=this;return e._asyncToGenerator((function*(){var{connection:e,stream:i}=t,o=new Xp(yield xp(n.init.rtcConfiguration)),a=new Qp(n.components,{peerConnection:o,dataChannelOptions:n.init.dataChannel});try{var s,{remoteAddress:l}=yield function(e){return pf.apply(this,arguments)}({peerConnection:o,connection:e,stream:i,signal:r,log:n.log});yield i.close({signal:r});var c=new Ip(n.components,{peerConnection:o,timeline:{open:(new Date).getTime()},remoteAddr:l,metrics:null===(s=n.metrics)||void 0===s?void 0:s.listenerEvents});yield n.components.upgrader.upgradeInbound(c,{skipEncryption:!0,skipProtection:!0,muxerFactory:a,signal:r}),n._closeOnShutdown(o,c)}catch(e){throw n.log.error("incoming signaling error",e),o.close(),i.abort(e),e}}))()}_closeOnShutdown(e,t){var r=()=>{t.close().catch((e=>{this.log.error("could not close WebRTCMultiaddrConnection",e)}))};this.shutdownController.signal.addEventListener("abort",r),e.addEventListener("close",(()=>{this.shutdownController.signal.removeEventListener("abort",r)}))}}var vf,yf={};!function(){return vf||(vf=1,function(t){!function(){var r="object"==typeof globalThis?globalThis:"object"==typeof e.commonjsGlobal?e.commonjsGlobal:"object"==typeof self?self:"object"==typeof this?this:function(){try{return Function("return this;")()}catch(e){}}()||function(){try{return(0,eval)("(function() { return this; })()")}catch(e){}}(),n=i(t);function i(e,t){return function(r,n){Object.defineProperty(e,r,{configurable:!0,writable:!0,value:n}),t&&t(r,n)}}void 0!==r.Reflect&&(n=i(r.Reflect,n)),function(e,t){var r=Object.prototype.hasOwnProperty,n="function"==typeof Symbol,i=n&&void 0!==Symbol.toPrimitive?Symbol.toPrimitive:"@@toPrimitive",o=n&&void 0!==Symbol.iterator?Symbol.iterator:"@@iterator",a="function"==typeof Object.create,s={__proto__:[]}instanceof Array,l=!a&&!s,c={create:a?function(){return de(Object.create(null))}:s?function(){return de({__proto__:null})}:function(){return de({})},has:l?function(e,t){return r.call(e,t)}:function(e,t){return t in e},get:l?function(e,t){return r.call(e,t)?e[t]:void 0}:function(e,t){return e[t]}},u=Object.getPrototypeOf(Function),d="function"==typeof Map&&"function"==typeof Map.prototype.entries?Map:le(),h="function"==typeof Set&&"function"==typeof Set.prototype.entries?Set:ce(),p="function"==typeof WeakMap?WeakMap:ue(),f=n?Symbol.for("@reflect-metadata:registry"):void 0,v=ie(),y=oe(v);function g(e,t,r,n){if(L(r)){if(!K(e))throw new TypeError;if(!Q(t))throw new TypeError;return x(e,t)}if(!K(e))throw new TypeError;if(!F(t))throw new TypeError;if(!F(n)&&!L(n)&&!M(n))throw new TypeError;return M(n)&&(n=void 0),T(e,t,r=H(r),n)}function m(e,t){function r(r,n){if(!F(r))throw new TypeError;if(!L(n)&&!Y(n))throw new TypeError;D(e,t,r,n)}return r}function w(e,t,r,n){if(!F(r))throw new TypeError;return L(n)||(n=H(n)),D(e,t,r,n)}function b(e,t,r){if(!F(t))throw new TypeError;return L(r)||(r=H(r)),I(e,t,r)}function _(e,t,r){if(!F(t))throw new TypeError;return L(r)||(r=H(r)),C(e,t,r)}function S(e,t,r){if(!F(t))throw new TypeError;return L(r)||(r=H(r)),B(e,t,r)}function P(e,t,r){if(!F(t))throw new TypeError;return L(r)||(r=H(r)),N(e,t,r)}function E(e,t){if(!F(e))throw new TypeError;return L(t)||(t=H(t)),G(e,t)}function A(e,t){if(!F(e))throw new TypeError;return L(t)||(t=H(t)),R(e,t)}function k(e,t,r){if(!F(t))throw new TypeError;if(L(r)||(r=H(r)),!F(t))throw new TypeError;L(r)||(r=H(r));var n=se(t,r,!1);return!L(n)&&n.OrdinaryDeleteMetadata(e,t,r)}function x(e,t){for(var r=e.length-1;r>=0;--r){var n=(0,e[r])(t);if(!L(n)&&!M(n)){if(!Q(n))throw new TypeError;t=n}}return t}function T(e,t,r,n){for(var i=e.length-1;i>=0;--i){var o=(0,e[i])(t,r,n);if(!L(o)&&!M(o)){if(!F(o))throw new TypeError;n=o}}return n}function I(e,t,r){if(C(e,t,r))return!0;var n=re(t);return!M(n)&&I(e,n,r)}function C(e,t,r){var n=se(t,r,!1);return!L(n)&&V(n.OrdinaryHasOwnMetadata(e,t,r))}function B(e,t,r){if(C(e,t,r))return N(e,t,r);var n=re(t);return M(n)?void 0:B(e,n,r)}function N(e,t,r){var n=se(t,r,!1);if(!L(n))return n.OrdinaryGetOwnMetadata(e,t,r)}function D(e,t,r,n){se(r,n,!0).OrdinaryDefineOwnMetadata(e,t,r,n)}function G(e,t){var r=R(e,t),n=re(e);if(null===n)return r;var i=G(n,t);if(i.length<=0)return r;if(r.length<=0)return i;for(var o=new h,a=[],s=0,l=r;s<l.length;s++){var c=l[s];o.has(c)||(o.add(c),a.push(c))}for(var u=0,d=i;u<d.length;u++){c=d[u];o.has(c)||(o.add(c),a.push(c))}return a}function R(e,t){var r=se(e,t,!1);return r?r.OrdinaryOwnMetadataKeys(e,t):[]}function O(e){if(null===e)return 1;switch(typeof e){case"undefined":return 0;case"boolean":return 2;case"string":return 3;case"symbol":return 4;case"number":return 5;case"object":return null===e?1:6;default:return 6}}function L(e){return void 0===e}function M(e){return null===e}function j(e){return"symbol"==typeof e}function F(e){return"object"==typeof e?null!==e:"function"==typeof e}function U(e,t){switch(O(e)){case 0:case 1:case 2:case 3:case 4:case 5:return e}var r="string",n=Z(e,i);if(void 0!==n){var o=n.call(e,r);if(F(o))throw new TypeError;return o}return z(e)}function z(e,t){var r,n,i=e.toString;if(W(i)&&!F(n=i.call(e)))return n;if(W(r=e.valueOf)&&!F(n=r.call(e)))return n;throw new TypeError}function V(e){return!!e}function q(e){return""+e}function H(e){var t=U(e);return j(t)?t:q(t)}function K(e){return Array.isArray?Array.isArray(e):e instanceof Object?e instanceof Array:"[object Array]"===Object.prototype.toString.call(e)}function W(e){return"function"==typeof e}function Q(e){return"function"==typeof e}function Y(e){switch(O(e)){case 3:case 4:return!0;default:return!1}}function J(e,t){return e===t||e!=e&&t!=t}function Z(e,t){var r=e[t];if(null!=r){if(!W(r))throw new TypeError;return r}}function $(e){var t=Z(e,o);if(!W(t))throw new TypeError;var r=t.call(e);if(!F(r))throw new TypeError;return r}function X(e){return e.value}function ee(e){var t=e.next();return!t.done&&t}function te(e){var t=e.return;t&&t.call(e)}function re(e){var t=Object.getPrototypeOf(e);if("function"!=typeof e||e===u)return t;if(t!==u)return t;var r=e.prototype,n=r&&Object.getPrototypeOf(r);if(null==n||n===Object.prototype)return t;var i=n.constructor;return"function"!=typeof i||i===e?t:i}function ne(){var e,r,n,i;L(f)||void 0===t.Reflect||f in t.Reflect||"function"!=typeof t.Reflect.defineMetadata||(e=ae(t.Reflect));var o=new p,a={registerProvider:s,getProvider:c,setProvider:v};return a;function s(t){if(!Object.isExtensible(a))throw new Error("Cannot add provider to a frozen registry.");switch(!0){case e===t:break;case L(r):r=t;break;case r===t:break;case L(n):n=t;break;case n===t:break;default:void 0===i&&(i=new h),i.add(t)}}function l(t,o){if(!L(r)){if(r.isProviderFor(t,o))return r;if(!L(n)){if(n.isProviderFor(t,o))return r;if(!L(i))for(var a=$(i);;){var s=ee(a);if(!s)return;var l=X(s);if(l.isProviderFor(t,o))return te(a),l}}}if(!L(e)&&e.isProviderFor(t,o))return e}function c(e,t){var r,n=o.get(e);return L(n)||(r=n.get(t)),L(r)?(L(r=l(e,t))||(L(n)&&(n=new d,o.set(e,n)),n.set(t,r)),r):r}function u(e){if(L(e))throw new TypeError;return r===e||n===e||!L(i)&&i.has(e)}function v(e,t,r){if(!u(r))throw new Error("Metadata provider not registered.");var n=c(e,t);if(n!==r){if(!L(n))return!1;var i=o.get(e);L(i)&&(i=new d,o.set(e,i)),i.set(t,r)}return!0}}function ie(){var e;return!L(f)&&F(t.Reflect)&&Object.isExtensible(t.Reflect)&&(e=t.Reflect[f]),L(e)&&(e=ne()),!L(f)&&F(t.Reflect)&&Object.isExtensible(t.Reflect)&&Object.defineProperty(t.Reflect,f,{enumerable:!1,configurable:!1,writable:!1,value:e}),e}function oe(e){var t=new p,r={isProviderFor:function(e,r){var n=t.get(e);return!L(n)&&n.has(r)},OrdinaryDefineOwnMetadata:a,OrdinaryHasOwnMetadata:i,OrdinaryGetOwnMetadata:o,OrdinaryOwnMetadataKeys:s,OrdinaryDeleteMetadata:l};return v.registerProvider(r),r;function n(n,i,o){var a=t.get(n),s=!1;if(L(a)){if(!o)return;a=new d,t.set(n,a),s=!0}var l=a.get(i);if(L(l)){if(!o)return;if(l=new d,a.set(i,l),!e.setProvider(n,i,r))throw a.delete(i),s&&t.delete(n),new Error("Wrong provider for target.")}return l}function i(e,t,r){var i=n(t,r,!1);return!L(i)&&V(i.has(e))}function o(e,t,r){var i=n(t,r,!1);if(!L(i))return i.get(e)}function a(e,t,r,i){n(r,i,!0).set(e,t)}function s(e,t){var r=[],i=n(e,t,!1);if(L(i))return r;for(var o=$(i.keys()),a=0;;){var s=ee(o);if(!s)return r.length=a,r;var l=X(s);try{r[a]=l}catch(e){try{te(o)}finally{throw e}}a++}}function l(e,r,i){var o=n(r,i,!1);if(L(o))return!1;if(!o.delete(e))return!1;if(0===o.size){var a=t.get(r);L(a)||(a.delete(i),0===a.size&&t.delete(a))}return!0}}function ae(e){var t=e.defineMetadata,r=e.hasOwnMetadata,n=e.getOwnMetadata,i=e.getOwnMetadataKeys,o=e.deleteMetadata,a=new p;return{isProviderFor:function(e,t){var r=a.get(e);return!(L(r)||!r.has(t))||!!i(e,t).length&&(L(r)&&(r=new h,a.set(e,r)),r.add(t),!0)},OrdinaryDefineOwnMetadata:t,OrdinaryHasOwnMetadata:r,OrdinaryGetOwnMetadata:n,OrdinaryOwnMetadataKeys:i,OrdinaryDeleteMetadata:o}}function se(e,t,r){var n=v.getProvider(e,t);if(!L(n))return n;if(r){if(v.setProvider(e,t,y))return y;throw new Error("Illegal state.")}}function le(){var e={},t=[],r=function(){function e(e,t,r){this._index=0,this._keys=e,this._values=t,this._selector=r}return e.prototype["@@iterator"]=function(){return this},e.prototype[o]=function(){return this},e.prototype.next=function(){var e=this._index;if(e>=0&&e<this._keys.length){var r=this._selector(this._keys[e],this._values[e]);return e+1>=this._keys.length?(this._index=-1,this._keys=t,this._values=t):this._index++,{value:r,done:!1}}return{value:void 0,done:!0}},e.prototype.throw=function(e){throw this._index>=0&&(this._index=-1,this._keys=t,this._values=t),e},e.prototype.return=function(e){return this._index>=0&&(this._index=-1,this._keys=t,this._values=t),{value:e,done:!0}},e}(),n=function(){function t(){this._keys=[],this._values=[],this._cacheKey=e,this._cacheIndex=-2}return Object.defineProperty(t.prototype,"size",{get:function(){return this._keys.length},enumerable:!0,configurable:!0}),t.prototype.has=function(e){return this._find(e,!1)>=0},t.prototype.get=function(e){var t=this._find(e,!1);return t>=0?this._values[t]:void 0},t.prototype.set=function(e,t){var r=this._find(e,!0);return this._values[r]=t,this},t.prototype.delete=function(t){var r=this._find(t,!1);if(r>=0){for(var n=this._keys.length,i=r+1;i<n;i++)this._keys[i-1]=this._keys[i],this._values[i-1]=this._values[i];return this._keys.length--,this._values.length--,J(t,this._cacheKey)&&(this._cacheKey=e,this._cacheIndex=-2),!0}return!1},t.prototype.clear=function(){this._keys.length=0,this._values.length=0,this._cacheKey=e,this._cacheIndex=-2},t.prototype.keys=function(){return new r(this._keys,this._values,i)},t.prototype.values=function(){return new r(this._keys,this._values,a)},t.prototype.entries=function(){return new r(this._keys,this._values,s)},t.prototype["@@iterator"]=function(){return this.entries()},t.prototype[o]=function(){return this.entries()},t.prototype._find=function(e,t){if(!J(this._cacheKey,e)){this._cacheIndex=-1;for(var r=0;r<this._keys.length;r++)if(J(this._keys[r],e)){this._cacheIndex=r;break}}return this._cacheIndex<0&&t&&(this._cacheIndex=this._keys.length,this._keys.push(e),this._values.push(void 0)),this._cacheIndex},t}();return n;function i(e,t){return e}function a(e,t){return t}function s(e,t){return[e,t]}}function ce(){return function(){function e(){this._map=new d}return Object.defineProperty(e.prototype,"size",{get:function(){return this._map.size},enumerable:!0,configurable:!0}),e.prototype.has=function(e){return this._map.has(e)},e.prototype.add=function(e){return this._map.set(e,e),this},e.prototype.delete=function(e){return this._map.delete(e)},e.prototype.clear=function(){this._map.clear()},e.prototype.keys=function(){return this._map.keys()},e.prototype.values=function(){return this._map.keys()},e.prototype.entries=function(){return this._map.entries()},e.prototype["@@iterator"]=function(){return this.keys()},e.prototype[o]=function(){return this.keys()},e}()}function ue(){var e=16,t=c.create(),n=i();return function(){function e(){this._key=i()}return e.prototype.has=function(e){var t=o(e,!1);return void 0!==t&&c.has(t,this._key)},e.prototype.get=function(e){var t=o(e,!1);return void 0!==t?c.get(t,this._key):void 0},e.prototype.set=function(e,t){return o(e,!0)[this._key]=t,this},e.prototype.delete=function(e){var t=o(e,!1);return void 0!==t&&delete t[this._key]},e.prototype.clear=function(){this._key=i()},e}();function i(){var e;do{e="@@WeakMap@@"+l()}while(c.has(t,e));return t[e]=!0,e}function o(e,t){if(!r.call(e,n)){if(!t)return;Object.defineProperty(e,n,{value:c.create()})}return e[n]}function a(e,t){for(var r=0;r<t;++r)e[r]=255*Math.random()|0;return e}function s(e){if("function"==typeof Uint8Array){var t=new Uint8Array(e);return"undefined"!=typeof crypto?crypto.getRandomValues(t):"undefined"!=typeof msCrypto?msCrypto.getRandomValues(t):a(t,e),t}return a(new Array(e),e)}function l(){var t=s(e);t[6]=79&t[6]|64,t[8]=191&t[8]|128;for(var r="",n=0;n<e;++n){var i=t[n];4!==n&&6!==n&&8!==n||(r+="-"),i<16&&(r+="0"),r+=i.toString(16).toLowerCase()}return r}}function de(e){return e.__=void 0,delete e.__,e}e("decorate",g),e("metadata",m),e("defineMetadata",w),e("hasMetadata",b),e("hasOwnMetadata",_),e("getMetadata",S),e("getOwnMetadata",P),e("getMetadataKeys",E),e("getOwnMetadataKeys",A),e("deleteMetadata",k)}(n,r),void 0===r.Reflect&&(r.Reflect=t)}()}(t||(t={}))),yf;var t}();var gf,mf={};var wf=function(){if(gf)return mf;gf=1;class e{static isArrayBuffer(e){return"[object ArrayBuffer]"===Object.prototype.toString.call(e)}static toArrayBuffer(e){return this.isArrayBuffer(e)?e:e.byteLength===e.buffer.byteLength||0===e.byteOffset&&e.byteLength===e.buffer.byteLength?e.buffer:this.toUint8Array(e.buffer).slice(e.byteOffset,e.byteOffset+e.byteLength).buffer}static toUint8Array(e){return this.toView(e,Uint8Array)}static toView(e,t){if(e.constructor===t)return e;if(this.isArrayBuffer(e))return new t(e);if(this.isArrayBufferView(e))return new t(e.buffer,e.byteOffset,e.byteLength);throw new TypeError("The provided value is not of type '(ArrayBuffer or ArrayBufferView)'")}static isBufferSource(e){return this.isArrayBufferView(e)||this.isArrayBuffer(e)}static isArrayBufferView(e){return ArrayBuffer.isView(e)||e&&this.isArrayBuffer(e.buffer)}static isEqual(t,r){var n=e.toUint8Array(t),i=e.toUint8Array(r);if(n.length!==i.byteLength)return!1;for(var o=0;o<n.length;o++)if(n[o]!==i[o])return!1;return!0}static concat(){for(var e,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];e=!Array.isArray(r[0])||r[1]instanceof Function?Array.isArray(r[0])&&r[1]instanceof Function?r[0]:r[r.length-1]instanceof Function?r.slice(0,r.length-1):r:r[0];var i=0;for(var o of e)i+=o.byteLength;var a=new Uint8Array(i),s=0;for(var l of e){var c=this.toUint8Array(l);a.set(c,s),s+=c.length}return r[r.length-1]instanceof Function?this.toView(a,r[r.length-1]):a.buffer}}var t="string",r=/^[0-9a-f\s]+$/i,n=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,i=/^[a-zA-Z0-9-_]+$/;class o{static fromString(e){for(var t=unescape(encodeURIComponent(e)),r=new Uint8Array(t.length),n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r.buffer}static toString(t){for(var r=e.toUint8Array(t),n="",i=0;i<r.length;i++)n+=String.fromCharCode(r[i]);return decodeURIComponent(escape(n))}}class a{static toString(t){for(var r=arguments.length>1&&void 0!==arguments[1]&&arguments[1],n=e.toArrayBuffer(t),i=new DataView(n),o="",a=0;a<n.byteLength;a+=2){var s=i.getUint16(a,r);o+=String.fromCharCode(s)}return o}static fromString(e){for(var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=new ArrayBuffer(2*e.length),n=new DataView(r),i=0;i<e.length;i++)n.setUint16(2*i,e.charCodeAt(i),t);return r}}class s{static isHex(e){return typeof e===t&&r.test(e)}static isBase64(e){return typeof e===t&&n.test(e)}static isBase64Url(e){return typeof e===t&&i.test(e)}static ToString(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"utf8",n=e.toUint8Array(t);switch(r.toLowerCase()){case"utf8":return this.ToUtf8String(n);case"binary":return this.ToBinary(n);case"hex":return this.ToHex(n);case"base64":return this.ToBase64(n);case"base64url":return this.ToBase64Url(n);case"utf16le":return a.toString(n,!0);case"utf16":case"utf16be":return a.toString(n);default:throw new Error("Unknown type of encoding '".concat(r,"'"))}}static FromString(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:"utf8";if(!e)return new ArrayBuffer(0);switch(t.toLowerCase()){case"utf8":return this.FromUtf8String(e);case"binary":return this.FromBinary(e);case"hex":return this.FromHex(e);case"base64":return this.FromBase64(e);case"base64url":return this.FromBase64Url(e);case"utf16le":return a.fromString(e,!0);case"utf16":case"utf16be":return a.fromString(e);default:throw new Error("Unknown type of encoding '".concat(t,"'"))}}static ToBase64(t){var r=e.toUint8Array(t);if("undefined"!=typeof btoa){var n=this.ToString(r,"binary");return btoa(n)}return Buffer.from(r).toString("base64")}static FromBase64(e){var t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!s.isBase64(t))throw new TypeError("Argument 'base64Text' is not Base64 encoded");return"undefined"!=typeof atob?this.FromBinary(atob(t)):new Uint8Array(Buffer.from(t,"base64")).buffer}static FromBase64Url(e){var t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!s.isBase64Url(t))throw new TypeError("Argument 'base64url' is not Base64Url encoded");return this.FromBase64(this.Base64Padding(t.replace(/\-/g,"+").replace(/\_/g,"/")))}static ToBase64Url(e){return this.ToBase64(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/\=/g,"")}static FromUtf8String(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:s.DEFAULT_UTF8_ENCODING;switch(t){case"ascii":return this.FromBinary(e);case"utf8":return o.fromString(e);case"utf16":case"utf16be":return a.fromString(e);case"utf16le":case"usc2":return a.fromString(e,!0);default:throw new Error("Unknown type of encoding '".concat(t,"'"))}}static ToUtf8String(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:s.DEFAULT_UTF8_ENCODING;switch(t){case"ascii":return this.ToBinary(e);case"utf8":return o.toString(e);case"utf16":case"utf16be":return a.toString(e);case"utf16le":case"usc2":return a.toString(e,!0);default:throw new Error("Unknown type of encoding '".concat(t,"'"))}}static FromBinary(e){for(var t=e.length,r=new Uint8Array(t),n=0;n<t;n++)r[n]=e.charCodeAt(n);return r.buffer}static ToBinary(t){for(var r=e.toUint8Array(t),n="",i=0;i<r.length;i++)n+=String.fromCharCode(r[i]);return n}static ToHex(t){for(var r=e.toUint8Array(t),n="",i=r.length,o=0;o<i;o++){var a=r[o];a<16&&(n+="0"),n+=a.toString(16)}return n}static FromHex(e){var t=this.formatString(e);if(!t)return new ArrayBuffer(0);if(!s.isHex(t))throw new TypeError("Argument 'hexString' is not HEX encoded");t.length%2&&(t="0".concat(t));for(var r=new Uint8Array(t.length/2),n=0;n<t.length;n+=2){var i=t.slice(n,n+2);r[n/2]=parseInt(i,16)}return r.buffer}static ToUtf16String(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return a.toString(e,t)}static FromUtf16String(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return a.fromString(e,t)}static Base64Padding(e){var t=4-e.length%4;if(t<4)for(var r=0;r<t;r++)e+="=";return e}static formatString(e){return(null==e?void 0:e.replace(/[\n\r\t ]/g,""))||""}}return s.DEFAULT_UTF8_ENCODING="utf8",mf.BufferSourceConverter=e,mf.Convert=s,mf.assign=function(e){for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];for(var i=arguments[0],o=1;o<arguments.length;o++){var a=arguments[o];for(var s in a)i[s]=a[s]}return i},mf.combine=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];var n=t.map((e=>e.byteLength)).reduce(((e,t)=>e+t)),i=new Uint8Array(n),o=0;return t.map((e=>new Uint8Array(e))).forEach((e=>{for(var t of e)i[o++]=t})),i.buffer},mf.isEqual=function(e,t){if(!e||!t)return!1;if(e.byteLength!==t.byteLength)return!1;for(var r=new Uint8Array(e),n=new Uint8Array(t),i=0;i<e.byteLength;i++)if(r[i]!==n[i])return!1;return!0},mf}();function bf(e,t){var r=0;if(1===e.length)return e[0];for(var n=e.length-1;n>=0;n--)r+=e[e.length-1-n]*Math.pow(2,t*n);return r}function _f(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:-1,n=e,i=0,o=Math.pow(2,t),a=1;a<8;a++){if(e<o){var s=void 0;if(r<0)s=new ArrayBuffer(a),i=a;else{if(r<a)return new ArrayBuffer(0);s=new ArrayBuffer(r),i=r}for(var l=new Uint8Array(s),c=a-1;c>=0;c--){var u=Math.pow(2,c*t);l[i-c-1]=Math.floor(n/u),n-=l[i-c-1]*u}return s}o*=Math.pow(2,t)}return new ArrayBuffer(0)}function Sf(){for(var e=0,t=0,r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];for(var o of n)e+=o.length;var a=new ArrayBuffer(e),s=new Uint8Array(a);for(var l of n)s.set(l,t),t+=l.length;return s}function Pf(){var e=new Uint8Array(this.valueHex);if(this.valueHex.byteLength>=2){var t=255===e[0]&&128&e[1],r=0===e[0]&&!(128&e[1]);(t||r)&&this.warnings.push("Needlessly long format")}for(var n=new ArrayBuffer(this.valueHex.byteLength),i=new Uint8Array(n),o=0;o<this.valueHex.byteLength;o++)i[o]=0;i[0]=128&e[0];for(var a=bf(i,8),s=new ArrayBuffer(this.valueHex.byteLength),l=new Uint8Array(s),c=0;c<this.valueHex.byteLength;c++)l[c]=e[c];return l[0]&=127,bf(l,8)-a}function Ef(e,t){var r=e.toString(10);if(t<r.length)return"";for(var n=t-r.length,i=new Array(n),o=0;o<n;o++)i[o]="0";return i.join("").concat(r)}var Af=["name","optional","primitiveSchema"],kf=["value"],xf=["isHexOnly"],Tf=["value","isIndefiniteForm"],If=["value"],Cf=["isConstructed"],Bf=["idBlock","lenBlock"],Nf=["unusedBits","isConstructed"],Df=["idBlock","lenBlock"],Gf=["value"],Rf=["valueDec","isFirstSid"],Of=["value"],Lf=["valueDec"],Mf=["value"],jf=["value","valueDate"],Ff=["value"],Uf=["value","local"];function zf(){if("undefined"==typeof BigInt)throw new Error("BigInt is not defined. Your environment doesn't implement BigInt.")}function Vf(e){for(var t=0,r=0,n=0;n<e.length;n++){t+=e[n].byteLength}for(var i=new Uint8Array(t),o=0;o<e.length;o++){var a=e[o];i.set(new Uint8Array(a),r),r+=a.byteLength}return i.buffer}function qf(e,t,r,n){return t instanceof Uint8Array?t.byteLength?r<0?(e.error="Wrong parameter: inputOffset less than zero",!1):n<0?(e.error="Wrong parameter: inputLength less than zero",!1):!(t.byteLength-r-n<0)||(e.error="End of input reached before message was fully decoded (inconsistent offset and length values)",!1):(e.error="Wrong parameter: inputBuffer has zero length",!1):(e.error="Wrong parameter: inputBuffer must be 'Uint8Array'",!1)}class Hf{constructor(){this.items=[]}write(e){this.items.push(e)}final(){return Vf(this.items)}}var Kf=[new Uint8Array([1])],Wf="0123456789",Qf="name",Yf="valueHexView",Jf="",Zf=new ArrayBuffer(0),$f=new Uint8Array(0),Xf="EndOfContent",ev="OCTET STRING",tv="BIT STRING";function rv(t){var r;return r=class extends t{get valueHex(){return this.valueHexView.slice().buffer}set valueHex(e){this.valueHexView=new Uint8Array(e)}constructor(){var e;super(...arguments);var t=(arguments.length<=0?void 0:arguments[0])||{};this.isHexOnly=null!==(e=t.isHexOnly)&&void 0!==e&&e,this.valueHexView=t.valueHex?wf.BufferSourceConverter.toUint8Array(t.valueHex):$f}fromBER(e,t,r){var n=e instanceof ArrayBuffer?new Uint8Array(e):e;if(!qf(this,n,t,r))return-1;var i=t+r;return this.valueHexView=n.subarray(t,i),this.valueHexView.length?(this.blockLength=r,i):(this.warnings.push("Zero buffer length"),t)}toBER(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0];return this.isHexOnly?e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.byteLength===this.valueHexView.buffer.byteLength?this.valueHexView.buffer:this.valueHexView.slice().buffer:(this.error="Flag 'isHexOnly' is not set, abort",Zf)}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{isHexOnly:this.isHexOnly,valueHex:wf.Convert.ToHex(this.valueHexView)})}},r.NAME="hexBlock",r}class nv{static blockName(){return this.NAME}get valueBeforeDecode(){return this.valueBeforeDecodeView.slice().buffer}set valueBeforeDecode(e){this.valueBeforeDecodeView=new Uint8Array(e)}constructor(){var{blockLength:e=0,error:t=Jf,warnings:r=[],valueBeforeDecode:n=$f}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.blockLength=e,this.error=t,this.warnings=r,this.valueBeforeDecodeView=wf.BufferSourceConverter.toUint8Array(n)}toJSON(){return{blockName:this.constructor.NAME,blockLength:this.blockLength,error:this.error,warnings:this.warnings,valueBeforeDecode:wf.Convert.ToHex(this.valueBeforeDecodeView)}}}nv.NAME="baseBlock";class iv extends nv{fromBER(e,t,r){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}toBER(e,t){throw TypeError("User need to make a specific function in a class which extends 'ValueBlock'")}}iv.NAME="valueBlock";class ov extends(rv(nv)){constructor(){var e,t,r,n,{idBlock:i={}}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),i?(this.isHexOnly=null!==(e=i.isHexOnly)&&void 0!==e&&e,this.valueHexView=i.valueHex?wf.BufferSourceConverter.toUint8Array(i.valueHex):$f,this.tagClass=null!==(t=i.tagClass)&&void 0!==t?t:-1,this.tagNumber=null!==(r=i.tagNumber)&&void 0!==r?r:-1,this.isConstructed=null!==(n=i.isConstructed)&&void 0!==n&&n):(this.tagClass=-1,this.tagNumber=-1,this.isConstructed=!1)}toBER(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=0;switch(this.tagClass){case 1:t|=0;break;case 2:t|=64;break;case 3:t|=128;break;case 4:t|=192;break;default:return this.error="Unknown tag class",Zf}if(this.isConstructed&&(t|=32),this.tagNumber<31&&!this.isHexOnly){var r=new Uint8Array(1);if(!e){var n=this.tagNumber;t|=n&=31,r[0]=t}return r.buffer}if(!this.isHexOnly){var i=_f(this.tagNumber,7),o=new Uint8Array(i),a=i.byteLength,s=new Uint8Array(a+1);if(s[0]=31|t,!e){for(var l=0;l<a-1;l++)s[l+1]=128|o[l];s[a]=o[a-1]}return s.buffer}var c=new Uint8Array(this.valueHexView.byteLength+1);if(c[0]=31|t,!e){for(var u=this.valueHexView,d=0;d<u.length-1;d++)c[d+1]=128|u[d];c[this.valueHexView.byteLength]=u[u.length-1]}return c.buffer}fromBER(e,t,r){var n=wf.BufferSourceConverter.toUint8Array(e);if(!qf(this,n,t,r))return-1;var i=n.subarray(t,t+r);if(0===i.length)return this.error="Zero buffer length",-1;switch(192&i[0]){case 0:this.tagClass=1;break;case 64:this.tagClass=2;break;case 128:this.tagClass=3;break;case 192:this.tagClass=4;break;default:return this.error="Unknown tag class",-1}this.isConstructed=!(32&~i[0]),this.isHexOnly=!1;var o=31&i[0];if(31!==o)this.tagNumber=o,this.blockLength=1;else{for(var a=1,s=this.valueHexView=new Uint8Array(255),l=255;128&i[a];){if(s[a-1]=127&i[a],++a>=i.length)return this.error="End of input reached before message was fully decoded",-1;if(a===l){l+=255;for(var c=new Uint8Array(l),u=0;u<s.length;u++)c[u]=s[u];s=this.valueHexView=new Uint8Array(l)}}this.blockLength=a+1,s[a-1]=127&i[a];for(var d=new Uint8Array(a),h=0;h<a;h++)d[h]=s[h];(s=this.valueHexView=new Uint8Array(a)).set(d),this.blockLength<=9?this.tagNumber=bf(s,7):(this.isHexOnly=!0,this.warnings.push("Tag too long, represented as hex-coded"))}if(1===this.tagClass&&this.isConstructed)switch(this.tagNumber){case 1:case 2:case 5:case 6:case 9:case 13:case 14:case 23:case 24:case 31:case 32:case 33:case 34:return this.error="Constructed encoding used for primitive type",-1}return t+this.blockLength}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{tagClass:this.tagClass,tagNumber:this.tagNumber,isConstructed:this.isConstructed})}}ov.NAME="identificationBlock";class av extends nv{constructor(){var e,t,r,{lenBlock:n={}}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),this.isIndefiniteForm=null!==(e=n.isIndefiniteForm)&&void 0!==e&&e,this.longFormUsed=null!==(t=n.longFormUsed)&&void 0!==t&&t,this.length=null!==(r=n.length)&&void 0!==r?r:0}fromBER(e,t,r){var n=wf.BufferSourceConverter.toUint8Array(e);if(!qf(this,n,t,r))return-1;var i=n.subarray(t,t+r);if(0===i.length)return this.error="Zero buffer length",-1;if(255===i[0])return this.error="Length block 0xFF is reserved by standard",-1;if(this.isIndefiniteForm=128===i[0],this.isIndefiniteForm)return this.blockLength=1,t+this.blockLength;if(this.longFormUsed=!!(128&i[0]),!1===this.longFormUsed)return this.length=i[0],this.blockLength=1,t+this.blockLength;var o=127&i[0];if(o>8)return this.error="Too big integer",-1;if(o+1>i.length)return this.error="End of input reached before message was fully decoded",-1;var a=t+1,s=n.subarray(a,a+o);return 0===s[o-1]&&this.warnings.push("Needlessly long encoded length"),this.length=bf(s,8),this.longFormUsed&&this.length<=127&&this.warnings.push("Unnecessary usage of long length form"),this.blockLength=o+1,t+this.blockLength}toBER(){var e,t,r=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(this.length>127&&(this.longFormUsed=!0),this.isIndefiniteForm)return e=new ArrayBuffer(1),!1===r&&((t=new Uint8Array(e))[0]=128),e;if(this.longFormUsed){var n=_f(this.length,8);if(n.byteLength>127)return this.error="Too big length",Zf;if(e=new ArrayBuffer(n.byteLength+1),r)return e;var i=new Uint8Array(n);(t=new Uint8Array(e))[0]=128|n.byteLength;for(var o=0;o<n.byteLength;o++)t[o+1]=i[o];return e}return e=new ArrayBuffer(1),!1===r&&((t=new Uint8Array(e))[0]=this.length),e}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{isIndefiniteForm:this.isIndefiniteForm,longFormUsed:this.longFormUsed,length:this.length})}}av.NAME="lengthBlock";var sv,lv,cv,uv,dv,hv={};class pv extends nv{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{name:r=Jf,optional:n=!1,primitiveSchema:i}=t,o=e._objectWithoutProperties(t,Af),a=arguments.length>1?arguments[1]:void 0;super(o),this.name=r,this.optional=n,i&&(this.primitiveSchema=i),this.idBlock=new ov(o),this.lenBlock=new av(o),this.valueBlock=a?new a(o):new iv(o)}fromBER(e,t,r){var n=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===n?(this.error=this.valueBlock.error,n):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),n)}toBER(e,t){var r=t||new Hf;t||fv(this);var n=this.idBlock.toBER(e);if(r.write(n),this.lenBlock.isIndefiniteForm)r.write(new Uint8Array([128]).buffer),this.valueBlock.toBER(e,r),r.write(new ArrayBuffer(2));else{var i=this.valueBlock.toBER(e);this.lenBlock.length=i.byteLength;var o=this.lenBlock.toBER(e);r.write(o),r.write(i)}return t?Zf:r.final()}toJSON(){var t=e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{idBlock:this.idBlock.toJSON(),lenBlock:this.lenBlock.toJSON(),valueBlock:this.valueBlock.toJSON(),name:this.name,optional:this.optional});return this.primitiveSchema&&(t.primitiveSchema=this.primitiveSchema.toJSON()),t}toString(){return"ascii"===(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"ascii")?this.onAsciiEncoding():wf.Convert.ToHex(this.toBER())}onAsciiEncoding(){var e=this.constructor.NAME,t=wf.Convert.ToHex(this.valueBlock.valueBeforeDecodeView);return"".concat(e," : ").concat(t)}isEqual(e){return this===e||e instanceof this.constructor&&function(e,t){if(e.byteLength!==t.byteLength)return!1;for(var r=new Uint8Array(e),n=new Uint8Array(t),i=0;i<r.length;i++)if(r[i]!==n[i])return!1;return!0}(this.toBER(),e.toBER())}}function fv(e){var t;if(e instanceof hv.Constructed)for(var r of e.valueBlock.value)fv(r)&&(e.lenBlock.isIndefiniteForm=!0);return!!(null===(t=e.lenBlock)||void 0===t?void 0:t.isIndefiniteForm)}pv.NAME="BaseBlock";class vv extends pv{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:r=Jf}=t;super(e._objectWithoutProperties(t,kf),arguments.length>1?arguments[1]:void 0),r&&this.fromString(r)}fromBER(e,t,r){var n=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===n?(this.error=this.valueBlock.error,n):(this.fromBuffer(this.valueBlock.valueHexView),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),n)}onAsciiEncoding(){return"".concat(this.constructor.NAME," : '").concat(this.valueBlock.value,"'")}}vv.NAME="BaseStringBlock";class yv extends(rv(iv)){constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{isHexOnly:r=!0}=t;super(e._objectWithoutProperties(t,xf)),this.isHexOnly=r}}yv.NAME="PrimitiveValueBlock";class gv extends pv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},yv),this.idBlock.isConstructed=!1}}function mv(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e.length,n=t,i=new pv({},iv),o=new nv;if(!qf(o,e,t,r))return i.error=o.error,{offset:-1,result:i};if(!e.subarray(t,t+r).length)return i.error="Zero buffer length",{offset:-1,result:i};var a=i.idBlock.fromBER(e,t,r);if(i.idBlock.warnings.length&&i.warnings.concat(i.idBlock.warnings),-1===a)return i.error=i.idBlock.error,{offset:-1,result:i};if(t=a,r-=i.idBlock.blockLength,a=i.lenBlock.fromBER(e,t,r),i.lenBlock.warnings.length&&i.warnings.concat(i.lenBlock.warnings),-1===a)return i.error=i.lenBlock.error,{offset:-1,result:i};if(t=a,r-=i.lenBlock.blockLength,!i.idBlock.isConstructed&&i.lenBlock.isIndefiniteForm)return i.error="Indefinite length form used for primitive encoding form",{offset:-1,result:i};var s=pv;if(1===i.idBlock.tagClass){if(i.idBlock.tagNumber>=37&&!1===i.idBlock.isHexOnly)return i.error="UNIVERSAL 37 and upper tags are reserved by ASN.1 standard",{offset:-1,result:i};switch(i.idBlock.tagNumber){case 0:if(i.idBlock.isConstructed&&i.lenBlock.length>0)return i.error="Type [UNIVERSAL 0] is reserved",{offset:-1,result:i};s=hv.EndOfContent;break;case 1:s=hv.Boolean;break;case 2:s=hv.Integer;break;case 3:s=hv.BitString;break;case 4:s=hv.OctetString;break;case 5:s=hv.Null;break;case 6:s=hv.ObjectIdentifier;break;case 10:s=hv.Enumerated;break;case 12:s=hv.Utf8String;break;case 13:s=hv.RelativeObjectIdentifier;break;case 14:s=hv.TIME;break;case 15:return i.error="[UNIVERSAL 15] is reserved by ASN.1 standard",{offset:-1,result:i};case 16:s=hv.Sequence;break;case 17:s=hv.Set;break;case 18:s=hv.NumericString;break;case 19:s=hv.PrintableString;break;case 20:s=hv.TeletexString;break;case 21:s=hv.VideotexString;break;case 22:s=hv.IA5String;break;case 23:s=hv.UTCTime;break;case 24:s=hv.GeneralizedTime;break;case 25:s=hv.GraphicString;break;case 26:s=hv.VisibleString;break;case 27:s=hv.GeneralString;break;case 28:s=hv.UniversalString;break;case 29:s=hv.CharacterString;break;case 30:s=hv.BmpString;break;case 31:s=hv.DATE;break;case 32:s=hv.TimeOfDay;break;case 33:s=hv.DateTime;break;case 34:s=hv.Duration;break;default:var l=i.idBlock.isConstructed?new hv.Constructed:new hv.Primitive;l.idBlock=i.idBlock,l.lenBlock=i.lenBlock,l.warnings=i.warnings,i=l}}else s=i.idBlock.isConstructed?hv.Constructed:hv.Primitive;return i=function(e,t){if(e instanceof t)return e;var r=new t;return r.idBlock=e.idBlock,r.lenBlock=e.lenBlock,r.warnings=e.warnings,r.valueBeforeDecodeView=e.valueBeforeDecodeView,r}(i,s),a=i.fromBER(e,t,i.lenBlock.isIndefiniteForm?r:i.lenBlock.length),i.valueBeforeDecodeView=e.subarray(n,n+i.blockLength),{offset:a,result:i}}function wv(e){if(!e.byteLength){var t=new pv({},iv);return t.error="Input buffer has zero length",{offset:-1,result:t}}return mv(wf.BufferSourceConverter.toUint8Array(e).slice(),0,e.byteLength)}function bv(e,t){return e?1:t}sv=gv,hv.Primitive=sv,gv.NAME="PRIMITIVE";class _v extends iv{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:r=[],isIndefiniteForm:n=!1}=t;super(e._objectWithoutProperties(t,Tf)),this.value=r,this.isIndefiniteForm=n}fromBER(e,t,r){var n=wf.BufferSourceConverter.toUint8Array(e);if(!qf(this,n,t,r))return-1;if(this.valueBeforeDecodeView=n.subarray(t,t+r),0===this.valueBeforeDecodeView.length)return this.warnings.push("Zero buffer length"),t;for(var i=t;bv(this.isIndefiniteForm,r)>0;){var o=mv(n,i,r);if(-1===o.offset)return this.error=o.result.error,this.warnings.concat(o.result.warnings),-1;if(i=o.offset,this.blockLength+=o.result.blockLength,r-=o.result.blockLength,this.value.push(o.result),this.isIndefiniteForm&&o.result.constructor.NAME===Xf)break}return this.isIndefiniteForm&&(this.value[this.value.length-1].constructor.NAME===Xf?this.value.pop():this.warnings.push("No EndOfContent block encoded")),i}toBER(e,t){for(var r=t||new Hf,n=0;n<this.value.length;n++)this.value[n].toBER(e,r);return t?Zf:r.final()}toJSON(){var t=e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{isIndefiniteForm:this.isIndefiniteForm,value:[]});for(var r of this.value)t.value.push(r.toJSON());return t}}_v.NAME="ConstructedValueBlock";class Sv extends pv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},_v),this.idBlock.isConstructed=!0}fromBER(e,t,r){this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm;var n=this.valueBlock.fromBER(e,t,this.lenBlock.isIndefiniteForm?r:this.lenBlock.length);return-1===n?(this.error=this.valueBlock.error,n):(this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.valueBlock.error.length||(this.blockLength+=this.valueBlock.blockLength),n)}onAsciiEncoding(){var e=[];for(var t of this.valueBlock.value)e.push(t.toString("ascii").split("\n").map((e=>" ".concat(e))).join("\n"));var r=3===this.idBlock.tagClass?"[".concat(this.idBlock.tagNumber,"]"):this.constructor.NAME;return e.length?"".concat(r," :\n").concat(e.join("\n")):"".concat(r," :")}}lv=Sv,hv.Constructed=lv,Sv.NAME="CONSTRUCTED";class Pv extends iv{fromBER(e,t,r){return t}toBER(e){return Zf}}Pv.override="EndOfContentValueBlock";class Ev extends pv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},Pv),this.idBlock.tagClass=1,this.idBlock.tagNumber=0}}cv=Ev,hv.EndOfContent=cv,Ev.NAME=Xf;class Av extends pv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},iv),this.idBlock.tagClass=1,this.idBlock.tagNumber=5}fromBER(e,t,r){return this.lenBlock.length>0&&this.warnings.push("Non-zero length of value block for Null type"),this.idBlock.error.length||(this.blockLength+=this.idBlock.blockLength),this.lenBlock.error.length||(this.blockLength+=this.lenBlock.blockLength),this.blockLength+=r,t+r>e.byteLength?(this.error="End of input reached before message was fully decoded (inconsistent offset and length values)",-1):t+r}toBER(e,t){var r=new ArrayBuffer(2);if(!e){var n=new Uint8Array(r);n[0]=5,n[1]=0}return t&&t.write(r),r}onAsciiEncoding(){return"".concat(this.constructor.NAME)}}uv=Av,hv.Null=uv,Av.NAME="NULL";class kv extends(rv(iv)){get value(){for(var e of this.valueHexView)if(e>0)return!0;return!1}set value(e){this.valueHexView[0]=e?255:0}constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:r}=t,n=e._objectWithoutProperties(t,If);super(n),n.valueHex?this.valueHexView=wf.BufferSourceConverter.toUint8Array(n.valueHex):this.valueHexView=new Uint8Array(1),r&&(this.value=r)}fromBER(e,t,r){var n=wf.BufferSourceConverter.toUint8Array(e);return qf(this,n,t,r)?(this.valueHexView=n.subarray(t,t+r),r>1&&this.warnings.push("Boolean value encoded in more then 1 octet"),this.isHexOnly=!0,Pf.call(this),this.blockLength=r,t+r):-1}toBER(){return this.valueHexView.slice()}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{value:this.value})}}kv.NAME="BooleanValueBlock";let xv=class extends pv{getValue(){return this.valueBlock.value}setValue(e){this.valueBlock.value=e}constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},kv),this.idBlock.tagClass=1,this.idBlock.tagNumber=1}onAsciiEncoding(){return"".concat(this.constructor.NAME," : ").concat(this.getValue)}};dv=xv,hv.Boolean=dv,xv.NAME="BOOLEAN";class Tv extends(rv(_v)){constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{isConstructed:r=!1}=t;super(e._objectWithoutProperties(t,Cf)),this.isConstructed=r}fromBER(e,t,r){var n=0;if(this.isConstructed){if(this.isHexOnly=!1,-1===(n=_v.prototype.fromBER.call(this,e,t,r)))return n;for(var i=0;i<this.value.length;i++){var o=this.value[i].constructor.NAME;if(o===Xf){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, OCTET STRING may consists of OCTET STRINGs only",-1}if(o!==ev)return this.error="OCTET STRING may consists of OCTET STRINGs only",-1}}else this.isHexOnly=!0,n=super.fromBER(e,t,r),this.blockLength=r;return n}toBER(e,t){return this.isConstructed?_v.prototype.toBER.call(this,e,t):e?new ArrayBuffer(this.valueHexView.byteLength):this.valueHexView.slice().buffer}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{isConstructed:this.isConstructed})}}var Iv;Tv.NAME="OctetStringValueBlock";let Cv=class extends pv{constructor(){var t,r,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{idBlock:i={},lenBlock:o={}}=n,a=e._objectWithoutProperties(n,Bf);null!==(t=a.isConstructed)&&void 0!==t||(a.isConstructed=!!(null===(r=a.value)||void 0===r?void 0:r.length)),super(e._objectSpread2({idBlock:e._objectSpread2({isConstructed:a.isConstructed},i),lenBlock:e._objectSpread2(e._objectSpread2({},o),{},{isIndefiniteForm:!!a.isIndefiniteForm})},a),Tv),this.idBlock.tagClass=1,this.idBlock.tagNumber=4}fromBER(e,t,r){if(this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,0===r)return 0===this.idBlock.error.length&&(this.blockLength+=this.idBlock.blockLength),0===this.lenBlock.error.length&&(this.blockLength+=this.lenBlock.blockLength),t;if(!this.valueBlock.isConstructed){var n=(e instanceof ArrayBuffer?new Uint8Array(e):e).subarray(t,t+r);try{if(n.byteLength){var i=mv(n,0,n.byteLength);-1!==i.offset&&i.offset===r&&(this.valueBlock.value=[i.result])}}catch(e){}}return super.fromBER(e,t,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Sv.prototype.onAsciiEncoding.call(this);var e=this.constructor.NAME,t=wf.Convert.ToHex(this.valueBlock.valueHexView);return"".concat(e," : ").concat(t)}getValue(){if(!this.idBlock.isConstructed)return this.valueBlock.valueHexView.slice().buffer;var e=[];for(var t of this.valueBlock.value)t instanceof Iv&&e.push(t.valueBlock.valueHexView);return wf.BufferSourceConverter.concat(e)}};Iv=Cv,hv.OctetString=Iv,Cv.NAME=ev;class Bv extends(rv(_v)){constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{unusedBits:r=0,isConstructed:n=!1}=t;super(e._objectWithoutProperties(t,Nf)),this.unusedBits=r,this.isConstructed=n,this.blockLength=this.valueHexView.byteLength}fromBER(e,t,r){if(!r)return t;var n=-1;if(this.isConstructed){if(-1===(n=_v.prototype.fromBER.call(this,e,t,r)))return n;for(var i of this.value){var o=i.constructor.NAME;if(o===Xf){if(this.isIndefiniteForm)break;return this.error="EndOfContent is unexpected, BIT STRING may consists of BIT STRINGs only",-1}if(o!==tv)return this.error="BIT STRING may consists of BIT STRINGs only",-1;var a=i.valueBlock;if(this.unusedBits>0&&a.unusedBits>0)return this.error='Using of "unused bits" inside constructive BIT STRING allowed for least one only',-1;this.unusedBits=a.unusedBits}return n}var s=wf.BufferSourceConverter.toUint8Array(e);if(!qf(this,s,t,r))return-1;var l=s.subarray(t,t+r);if(this.unusedBits=l[0],this.unusedBits>7)return this.error="Unused bits for BitString must be in range 0-7",-1;if(!this.unusedBits){var c=l.subarray(1);try{if(c.byteLength){var u=mv(c,0,c.byteLength);-1!==u.offset&&u.offset===r-1&&(this.value=[u.result])}}catch(e){}}return this.valueHexView=l.subarray(1),this.blockLength=l.length,t+r}toBER(e,t){if(this.isConstructed)return _v.prototype.toBER.call(this,e,t);if(e)return new ArrayBuffer(this.valueHexView.byteLength+1);if(!this.valueHexView.byteLength)return Zf;var r=new Uint8Array(this.valueHexView.length+1);return r[0]=this.unusedBits,r.set(this.valueHexView,1),r.buffer}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{unusedBits:this.unusedBits,isConstructed:this.isConstructed})}}var Nv;Bv.NAME="BitStringValueBlock";let Dv=class extends pv{constructor(){var t,r,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{idBlock:i={},lenBlock:o={}}=n,a=e._objectWithoutProperties(n,Df);null!==(t=a.isConstructed)&&void 0!==t||(a.isConstructed=!!(null===(r=a.value)||void 0===r?void 0:r.length)),super(e._objectSpread2({idBlock:e._objectSpread2({isConstructed:a.isConstructed},i),lenBlock:e._objectSpread2(e._objectSpread2({},o),{},{isIndefiniteForm:!!a.isIndefiniteForm})},a),Bv),this.idBlock.tagClass=1,this.idBlock.tagNumber=3}fromBER(e,t,r){return this.valueBlock.isConstructed=this.idBlock.isConstructed,this.valueBlock.isIndefiniteForm=this.lenBlock.isIndefiniteForm,super.fromBER(e,t,r)}onAsciiEncoding(){if(this.valueBlock.isConstructed||this.valueBlock.value&&this.valueBlock.value.length)return Sv.prototype.onAsciiEncoding.call(this);var e=[],t=this.valueBlock.valueHexView;for(var r of t)e.push(r.toString(2).padStart(8,"0"));var n=e.join(""),i=this.constructor.NAME,o=n.substring(0,n.length-this.valueBlock.unusedBits);return"".concat(i," : ").concat(o)}};var Gv,Rv,Ov,Lv,Mv,jv,Fv;function Uv(e,t){for(var r=new Uint8Array([0]),n=new Uint8Array(e),i=new Uint8Array(t),o=n.slice(0),a=o.length-1,s=i.slice(0),l=s.length-1,c=0,u=0,d=l<a?a:l;d>=0;d--,u++){if(!0==u<s.length)c=o[a-u]+s[l-u]+r[0];else c=o[a-u]+r[0];if(r[0]=c/10,!0==u>=o.length)o=Sf(new Uint8Array([c%10]),o);else o[a-u]=c%10}return r[0]>0&&(o=Sf(r,o)),o}function zv(e){if(e>=Kf.length)for(var t=Kf.length;t<=e;t++){for(var r=new Uint8Array([0]),n=Kf[t-1].slice(0),i=n.length-1;i>=0;i--){var o=new Uint8Array([(n[i]<<1)+r[0]]);r[0]=o[0]/10,n[i]=o[0]%10}r[0]>0&&(n=Sf(r,n)),Kf.push(n)}return Kf[e]}function Vv(e,t){for(var r,n=0,i=new Uint8Array(e),o=new Uint8Array(t),a=i.slice(0),s=a.length-1,l=o.slice(0),c=l.length-1,u=0,d=c;d>=0;d--,u++)if(!0==(r=a[s-u]-l[c-u]-n)<0)n=1,a[s-u]=r+10;else n=0,a[s-u]=r;if(n>0)for(var h=s-c+1;h>=0;h--,u++){if(!((r=a[s-u]-n)<0)){n=0,a[s-u]=r;break}n=1,a[s-u]=r+10}return a.slice()}Nv=Dv,hv.BitString=Nv,Dv.NAME=tv;class qv extends(rv(iv)){setValueHex(){this.valueHexView.length>=4?(this.warnings.push("Too big Integer for decoding, hex only"),this.isHexOnly=!0,this._valueDec=0):(this.isHexOnly=!1,this.valueHexView.length>0&&(this._valueDec=Pf.call(this)))}constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:r}=t,n=e._objectWithoutProperties(t,Gf);super(n),this._valueDec=0,n.valueHex&&this.setValueHex(),void 0!==r&&(this.valueDec=r)}set valueDec(e){this._valueDec=e,this.isHexOnly=!1,this.valueHexView=new Uint8Array(function(e){for(var t=e<0?-1*e:e,r=128,n=1;n<8;n++){if(t<=r){if(e<0){var i=_f(r-t,8,n);return new Uint8Array(i)[0]|=128,i}var o=_f(t,8,n),a=new Uint8Array(o);if(128&a[0]){var s=o.slice(0),l=new Uint8Array(s);o=new ArrayBuffer(o.byteLength+1),a=new Uint8Array(o);for(var c=0;c<s.byteLength;c++)a[c+1]=l[c];a[0]=0}return o}r*=Math.pow(2,8)}return new ArrayBuffer(0)}(e))}get valueDec(){return this._valueDec}fromDER(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:0,i=this.fromBER(e,t,r);if(-1===i)return i;var o=this.valueHexView;return 0===o[0]&&128&o[1]?this.valueHexView=o.subarray(1):0!==n&&o.length<n&&(n-o.length>1&&(n=o.length+1),this.valueHexView=o.subarray(n-o.length)),i}toDER(){var e=arguments.length>0&&void 0!==arguments[0]&&arguments[0],t=this.valueHexView;switch(!0){case!!(128&t[0]):var r=new Uint8Array(this.valueHexView.length+1);r[0]=0,r.set(t,1),this.valueHexView=r;break;case 0===t[0]&&!(128&t[1]):this.valueHexView=this.valueHexView.subarray(1)}return this.toBER(e)}fromBER(e,t,r){var n=super.fromBER(e,t,r);return-1===n||this.setValueHex(),n}toBER(e){return e?new ArrayBuffer(this.valueHexView.length):this.valueHexView.slice().buffer}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{valueDec:this.valueDec})}toString(){for(var e,t=8*this.valueHexView.length-1,r=new Uint8Array(8*this.valueHexView.length/3),n=0,i=this.valueHexView,o="",a=!1,s=i.byteLength-1;s>=0;s--){e=i[s];for(var l=0;l<8;l++){if(!(1&~e))if(n===t)r=Vv(zv(n),r),o="-";else r=Uv(r,zv(n));n++,e>>=1}}for(var c=0;c<r.length;c++)r[c]&&(a=!0),a&&(o+=Wf.charAt(r[c]));return!1===a&&(o+=Wf.charAt(0)),o}}Gv=qv,qv.NAME="IntegerValueBlock",Object.defineProperty(Gv.prototype,"valueHex",{set:function(e){this.valueHexView=new Uint8Array(e),this.setValueHex()},get:function(){return this.valueHexView.slice().buffer}});class Hv extends pv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},qv),this.idBlock.tagClass=1,this.idBlock.tagNumber=2}toBigInt(){return zf(),BigInt(this.valueBlock.toString())}static fromBigInt(e){zf();var t=BigInt(e),r=new Hf,n=t.toString(16).replace(/^-/,""),i=new Uint8Array(wf.Convert.FromHex(n));if(t<0){var o=new Uint8Array(i.length+(128&i[0]?1:0));o[0]|=128;var a=BigInt("0x".concat(wf.Convert.ToHex(o)))+t,s=wf.BufferSourceConverter.toUint8Array(wf.Convert.FromHex(a.toString(16)));s[0]|=128,r.write(s)}else 128&i[0]&&r.write(new Uint8Array([0])),r.write(i);return new Rv({valueHex:r.final()})}convertToDER(){var e=new Rv({valueHex:this.valueBlock.valueHexView});return e.valueBlock.toDER(),e}convertFromDER(){return new Rv({valueHex:0===this.valueBlock.valueHexView[0]?this.valueBlock.valueHexView.subarray(1):this.valueBlock.valueHexView})}onAsciiEncoding(){return"".concat(this.constructor.NAME," : ").concat(this.valueBlock.toString())}}Rv=Hv,hv.Integer=Rv,Hv.NAME="INTEGER";class Kv extends Hv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=10}}Ov=Kv,hv.Enumerated=Ov,Kv.NAME="ENUMERATED";class Wv extends(rv(iv)){constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{valueDec:r=-1,isFirstSid:n=!1}=t;super(e._objectWithoutProperties(t,Rf)),this.valueDec=r,this.isFirstSid=n}fromBER(e,t,r){if(!r)return t;var n=wf.BufferSourceConverter.toUint8Array(e);if(!qf(this,n,t,r))return-1;var i=n.subarray(t,t+r);this.valueHexView=new Uint8Array(r);for(var o=0;o<r&&(this.valueHexView[o]=127&i[o],this.blockLength++,128&i[o]);o++);for(var a=new Uint8Array(this.blockLength),s=0;s<this.blockLength;s++)a[s]=this.valueHexView[s];return this.valueHexView=a,128&i[this.blockLength-1]?(this.error="End of input reached before message was fully decoded",-1):(0===this.valueHexView[0]&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=bf(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}set valueBigInt(e){zf();for(var t=BigInt(e).toString(2);t.length%7;)t="0"+t;for(var r=new Uint8Array(t.length/7),n=0;n<r.length;n++)r[n]=parseInt(t.slice(7*n,7*n+7),2)+(n+1<r.length?128:0);this.fromBER(r.buffer,0,r.length)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);for(var t=this.valueHexView,r=new Uint8Array(this.blockLength),n=0;n<this.blockLength-1;n++)r[n]=128|t[n];return r[this.blockLength-1]=t[this.blockLength-1],r.buffer}var i=_f(this.valueDec,7);if(0===i.byteLength)return this.error="Error during encoding SID value",Zf;var o=new Uint8Array(i.byteLength);if(!e){for(var a=new Uint8Array(i),s=i.byteLength-1,l=0;l<s;l++)o[l]=128|a[l];o[s]=a[s]}return o}toString(){var e="";if(this.isHexOnly)e=wf.Convert.ToHex(this.valueHexView);else if(this.isFirstSid){var t=this.valueDec;this.valueDec<=39?e="0.":this.valueDec<=79?(e="1.",t-=40):(e="2.",t-=80),e+=t.toString()}else e=this.valueDec.toString();return e}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{valueDec:this.valueDec,isFirstSid:this.isFirstSid})}}Wv.NAME="sidBlock";class Qv extends iv{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:r=Jf}=t;super(e._objectWithoutProperties(t,Of)),this.value=[],r&&this.fromString(r)}fromBER(e,t,r){for(var n=t;r>0;){var i=new Wv;if(-1===(n=i.fromBER(e,n,r)))return this.blockLength=0,this.error=i.error,n;0===this.value.length&&(i.isFirstSid=!0),this.blockLength+=i.blockLength,r-=i.blockLength,this.value.push(i)}return n}toBER(e){for(var t=[],r=0;r<this.value.length;r++){var n=this.value[r].toBER(e);if(0===n.byteLength)return this.error=this.value[r].error,Zf;t.push(n)}return Vf(t)}fromString(e){this.value=[];var t=0,r=0,n="",i=!1;do{if(n=-1===(r=e.indexOf(".",t))?e.substring(t):e.substring(t,r),t=r+1,i){var o=this.value[0],a=0;switch(o.valueDec){case 0:break;case 1:a=40;break;case 2:a=80;break;default:return void(this.value=[])}var s=parseInt(n,10);if(isNaN(s))return;o.valueDec=s+a,i=!1}else{var l=new Wv;if(n>Number.MAX_SAFE_INTEGER){zf();var c=BigInt(n);l.valueBigInt=c}else if(l.valueDec=parseInt(n,10),isNaN(l.valueDec))return;this.value.length||(l.isFirstSid=!0,i=!0),this.value.push(l)}}while(-1!==r)}toString(){for(var e="",t=!1,r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;var n=this.value[r].toString();0!==r&&(e="".concat(e,".")),t?(n="{".concat(n,"}"),this.value[r].isFirstSid?e="2.{".concat(n," - 80}"):e+=n):e+=n}return e}toJSON(){for(var t=e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{value:this.toString(),sidArray:[]}),r=0;r<this.value.length;r++)t.sidArray.push(this.value[r].toJSON());return t}}Qv.NAME="ObjectIdentifierValueBlock";class Yv extends pv{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},Qv),this.idBlock.tagClass=1,this.idBlock.tagNumber=6}onAsciiEncoding(){return"".concat(this.constructor.NAME," : ").concat(this.valueBlock.toString()||"empty")}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{value:this.getValue()})}}Lv=Yv,hv.ObjectIdentifier=Lv,Yv.NAME="OBJECT IDENTIFIER";class Jv extends(rv(nv)){constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{valueDec:r=0}=t;super(e._objectWithoutProperties(t,Lf)),this.valueDec=r}fromBER(e,t,r){if(0===r)return t;var n=wf.BufferSourceConverter.toUint8Array(e);if(!qf(this,n,t,r))return-1;var i=n.subarray(t,t+r);this.valueHexView=new Uint8Array(r);for(var o=0;o<r&&(this.valueHexView[o]=127&i[o],this.blockLength++,128&i[o]);o++);for(var a=new Uint8Array(this.blockLength),s=0;s<this.blockLength;s++)a[s]=this.valueHexView[s];return this.valueHexView=a,128&i[this.blockLength-1]?(this.error="End of input reached before message was fully decoded",-1):(0===this.valueHexView[0]&&this.warnings.push("Needlessly long format of SID encoding"),this.blockLength<=8?this.valueDec=bf(this.valueHexView,7):(this.isHexOnly=!0,this.warnings.push("Too big SID for decoding, hex only")),t+this.blockLength)}toBER(e){if(this.isHexOnly){if(e)return new ArrayBuffer(this.valueHexView.byteLength);for(var t=this.valueHexView,r=new Uint8Array(this.blockLength),n=0;n<this.blockLength-1;n++)r[n]=128|t[n];return r[this.blockLength-1]=t[this.blockLength-1],r.buffer}var i=_f(this.valueDec,7);if(0===i.byteLength)return this.error="Error during encoding SID value",Zf;var o=new Uint8Array(i.byteLength);if(!e){for(var a=new Uint8Array(i),s=i.byteLength-1,l=0;l<s;l++)o[l]=128|a[l];o[s]=a[s]}return o.buffer}toString(){return this.isHexOnly?wf.Convert.ToHex(this.valueHexView):this.valueDec.toString()}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{valueDec:this.valueDec})}}Jv.NAME="relativeSidBlock";class Zv extends iv{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:r=Jf}=t;super(e._objectWithoutProperties(t,Mf)),this.value=[],r&&this.fromString(r)}fromBER(e,t,r){for(var n=t;r>0;){var i=new Jv;if(-1===(n=i.fromBER(e,n,r)))return this.blockLength=0,this.error=i.error,n;this.blockLength+=i.blockLength,r-=i.blockLength,this.value.push(i)}return n}toBER(e,t){for(var r=[],n=0;n<this.value.length;n++){var i=this.value[n].toBER(e);if(0===i.byteLength)return this.error=this.value[n].error,Zf;r.push(i)}return Vf(r)}fromString(e){this.value=[];var t=0,r=0,n="";do{n=-1===(r=e.indexOf(".",t))?e.substring(t):e.substring(t,r),t=r+1;var i=new Jv;if(i.valueDec=parseInt(n,10),isNaN(i.valueDec))return!0;this.value.push(i)}while(-1!==r);return!0}toString(){for(var e="",t=!1,r=0;r<this.value.length;r++){t=this.value[r].isHexOnly;var n=this.value[r].toString();0!==r&&(e="".concat(e,".")),e+=t?n="{".concat(n,"}"):n}return e}toJSON(){for(var t=e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{value:this.toString(),sidArray:[]}),r=0;r<this.value.length;r++)t.sidArray.push(this.value[r].toJSON());return t}}Zv.NAME="RelativeObjectIdentifierValueBlock";class $v extends pv{getValue(){return this.valueBlock.toString()}setValue(e){this.valueBlock.fromString(e)}constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},Zv),this.idBlock.tagClass=1,this.idBlock.tagNumber=13}onAsciiEncoding(){return"".concat(this.constructor.NAME," : ").concat(this.valueBlock.toString()||"empty")}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{value:this.getValue()})}}Mv=$v,hv.RelativeObjectIdentifier=Mv,$v.NAME="RelativeObjectIdentifier";class Xv extends Sv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=16}}jv=Xv,hv.Sequence=jv,Xv.NAME="SEQUENCE";let ey=class extends Sv{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=17}};Fv=ey,hv.Set=Fv,ey.NAME="SET";class ty extends(rv(iv)){constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(e._extends({},(e._objectDestructuringEmpty(t),t))),this.isHexOnly=!0,this.value=Jf}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{value:this.value})}}ty.NAME="StringValueBlock";class ry extends ty{}ry.NAME="SimpleStringValueBlock";class ny extends vv{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(e._extends({},(e._objectDestructuringEmpty(t),t)),ry)}fromBuffer(e){this.valueBlock.value=String.fromCharCode.apply(null,wf.BufferSourceConverter.toUint8Array(e))}fromString(e){for(var t=e.length,r=this.valueBlock.valueHexView=new Uint8Array(t),n=0;n<t;n++)r[n]=e.charCodeAt(n);this.valueBlock.value=e}}ny.NAME="SIMPLE STRING";class iy extends ny{fromBuffer(e){this.valueBlock.valueHexView=wf.BufferSourceConverter.toUint8Array(e);try{this.valueBlock.value=wf.Convert.ToUtf8String(e)}catch(t){this.warnings.push('Error during "decodeURIComponent": '.concat(t,", using raw string")),this.valueBlock.value=wf.Convert.ToBinary(e)}}fromString(e){this.valueBlock.valueHexView=new Uint8Array(wf.Convert.FromUtf8String(e)),this.valueBlock.value=e}}var oy,ay,sy,ly,cy,uy,dy,hy,py,fy,vy,yy,gy,my,wy,by,_y,Sy,Py;iy.NAME="Utf8StringValueBlock";class Ey extends iy{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=12}}oy=Ey,hv.Utf8String=oy,Ey.NAME="UTF8String";class Ay extends ny{fromBuffer(e){this.valueBlock.value=wf.Convert.ToUtf16String(e),this.valueBlock.valueHexView=wf.BufferSourceConverter.toUint8Array(e)}fromString(e){this.valueBlock.value=e,this.valueBlock.valueHexView=new Uint8Array(wf.Convert.FromUtf16String(e))}}Ay.NAME="BmpStringValueBlock";class ky extends Ay{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(e._extends({},(e._objectDestructuringEmpty(t),t))),this.idBlock.tagClass=1,this.idBlock.tagNumber=30}}ay=ky,hv.BmpString=ay,ky.NAME="BMPString";class xy extends ny{fromBuffer(e){for(var t=ArrayBuffer.isView(e)?e.slice().buffer:e.slice(0),r=new Uint8Array(t),n=0;n<r.length;n+=4)r[n]=r[n+3],r[n+1]=r[n+2],r[n+2]=0,r[n+3]=0;this.valueBlock.value=String.fromCharCode.apply(null,new Uint32Array(t))}fromString(e){for(var t=e.length,r=this.valueBlock.valueHexView=new Uint8Array(4*t),n=0;n<t;n++){var i=_f(e.charCodeAt(n),8),o=new Uint8Array(i);if(!(o.length>4))for(var a=4-o.length,s=o.length-1;s>=0;s--)r[4*n+s+a]=o[s]}this.valueBlock.value=e}}xy.NAME="UniversalStringValueBlock";class Ty extends xy{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(e._extends({},(e._objectDestructuringEmpty(t),t))),this.idBlock.tagClass=1,this.idBlock.tagNumber=28}}sy=Ty,hv.UniversalString=sy,Ty.NAME="UniversalString";class Iy extends ny{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=18}}ly=Iy,hv.NumericString=ly,Iy.NAME="NumericString";class Cy extends ny{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=19}}cy=Cy,hv.PrintableString=cy,Cy.NAME="PrintableString";class By extends ny{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=20}}uy=By,hv.TeletexString=uy,By.NAME="TeletexString";class Ny extends ny{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=21}}dy=Ny,hv.VideotexString=dy,Ny.NAME="VideotexString";class Dy extends ny{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=22}}hy=Dy,hv.IA5String=hy,Dy.NAME="IA5String";class Gy extends ny{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=25}}py=Gy,hv.GraphicString=py,Gy.NAME="GraphicString";class Ry extends ny{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=26}}fy=Ry,hv.VisibleString=fy,Ry.NAME="VisibleString";class Oy extends ny{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=27}}vy=Oy,hv.GeneralString=vy,Oy.NAME="GeneralString";class Ly extends ny{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=29}}yy=Ly,hv.CharacterString=yy,Ly.NAME="CharacterString";class My extends Ry{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:r,valueDate:n}=t;if(super(e._objectWithoutProperties(t,jf)),this.year=0,this.month=0,this.day=0,this.hour=0,this.minute=0,this.second=0,r){this.fromString(r),this.valueBlock.valueHexView=new Uint8Array(r.length);for(var i=0;i<r.length;i++)this.valueBlock.valueHexView[i]=r.charCodeAt(i)}n&&(this.fromDate(n),this.valueBlock.valueHexView=new Uint8Array(this.toBuffer())),this.idBlock.tagClass=1,this.idBlock.tagNumber=23}fromBuffer(e){this.fromString(String.fromCharCode.apply(null,wf.BufferSourceConverter.toUint8Array(e)))}toBuffer(){for(var e=this.toString(),t=new ArrayBuffer(e.length),r=new Uint8Array(t),n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return t}fromDate(e){this.year=e.getUTCFullYear(),this.month=e.getUTCMonth()+1,this.day=e.getUTCDate(),this.hour=e.getUTCHours(),this.minute=e.getUTCMinutes(),this.second=e.getUTCSeconds()}toDate(){return new Date(Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second))}fromString(e){var t=/(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})Z/gi.exec(e);if(null!==t){var r=parseInt(t[1],10);this.year=r>=50?1900+r:2e3+r,this.month=parseInt(t[2],10),this.day=parseInt(t[3],10),this.hour=parseInt(t[4],10),this.minute=parseInt(t[5],10),this.second=parseInt(t[6],10)}else this.error="Wrong input string for conversion"}toString(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"iso";if("iso"===e){var t=new Array(7);return t[0]=Ef(this.year<2e3?this.year-1900:this.year-2e3,2),t[1]=Ef(this.month,2),t[2]=Ef(this.day,2),t[3]=Ef(this.hour,2),t[4]=Ef(this.minute,2),t[5]=Ef(this.second,2),t[6]="Z",t.join("")}return super.toString(e)}onAsciiEncoding(){return"".concat(this.constructor.NAME," : ").concat(this.toDate().toISOString())}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{year:this.year,month:this.month,day:this.day,hour:this.hour,minute:this.minute,second:this.second})}}gy=My,hv.UTCTime=gy,My.NAME="UTCTime";class jy extends My{constructor(){var e;super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),null!==(e=this.millisecond)&&void 0!==e||(this.millisecond=0),this.idBlock.tagClass=1,this.idBlock.tagNumber=24}fromDate(e){super.fromDate(e),this.millisecond=e.getUTCMilliseconds()}toDate(){var e=Date.UTC(this.year,this.month-1,this.day,this.hour,this.minute,this.second,this.millisecond);return new Date(e)}fromString(e){var t,r=!1,n="",i="",o=0,a=0,s=0;if("Z"===e[e.length-1])n=e.substring(0,e.length-1),r=!0;else{var l=new Number(e[e.length-1]);if(isNaN(l.valueOf()))throw new Error("Wrong input string for conversion");n=e}if(r){if(-1!==n.indexOf("+"))throw new Error("Wrong input string for conversion");if(-1!==n.indexOf("-"))throw new Error("Wrong input string for conversion")}else{var c=1,u=n.indexOf("+"),d="";if(-1===u&&(u=n.indexOf("-"),c=-1),-1!==u){if(d=n.substring(u+1),n=n.substring(0,u),2!==d.length&&4!==d.length)throw new Error("Wrong input string for conversion");var h=parseInt(d.substring(0,2),10);if(isNaN(h.valueOf()))throw new Error("Wrong input string for conversion");if(a=c*h,4===d.length){if(h=parseInt(d.substring(2,4),10),isNaN(h.valueOf()))throw new Error("Wrong input string for conversion");s=c*h}}}var p=n.indexOf(".");if(-1===p&&(p=n.indexOf(",")),-1!==p){var f=new Number("0".concat(n.substring(p)));if(isNaN(f.valueOf()))throw new Error("Wrong input string for conversion");o=f.valueOf(),i=n.substring(0,p)}else i=n;switch(!0){case 8===i.length:if(t=/(\d{4})(\d{2})(\d{2})/gi,-1!==p)throw new Error("Wrong input string for conversion");break;case 10===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})/gi,-1!==p){var v=60*o;this.minute=Math.floor(v),v=60*(v-this.minute),this.second=Math.floor(v),v=1e3*(v-this.second),this.millisecond=Math.floor(v)}break;case 12===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==p){var y=60*o;this.second=Math.floor(y),y=1e3*(y-this.second),this.millisecond=Math.floor(y)}break;case 14===i.length:if(t=/(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})/gi,-1!==p){var g=1e3*o;this.millisecond=Math.floor(g)}break;default:throw new Error("Wrong input string for conversion")}var m=t.exec(i);if(null===m)throw new Error("Wrong input string for conversion");for(var w=1;w<m.length;w++)switch(w){case 1:this.year=parseInt(m[w],10);break;case 2:this.month=parseInt(m[w],10);break;case 3:this.day=parseInt(m[w],10);break;case 4:this.hour=parseInt(m[w],10)+a;break;case 5:this.minute=parseInt(m[w],10)+s;break;case 6:this.second=parseInt(m[w],10);break;default:throw new Error("Wrong input string for conversion")}if(!1===r){var b=new Date(this.year,this.month,this.day,this.hour,this.minute,this.second,this.millisecond);this.year=b.getUTCFullYear(),this.month=b.getUTCMonth(),this.day=b.getUTCDay(),this.hour=b.getUTCHours(),this.minute=b.getUTCMinutes(),this.second=b.getUTCSeconds(),this.millisecond=b.getUTCMilliseconds()}}toString(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"iso";if("iso"===e){var t=[];return t.push(Ef(this.year,4)),t.push(Ef(this.month,2)),t.push(Ef(this.day,2)),t.push(Ef(this.hour,2)),t.push(Ef(this.minute,2)),t.push(Ef(this.second,2)),0!==this.millisecond&&(t.push("."),t.push(Ef(this.millisecond,3))),t.push("Z"),t.join("")}return super.toString(e)}toJSON(){return e._objectSpread2(e._objectSpread2({},super.toJSON()),{},{millisecond:this.millisecond})}}my=jy,hv.GeneralizedTime=my,jy.NAME="GeneralizedTime";class Fy extends Ey{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=31}}wy=Fy,hv.DATE=wy,Fy.NAME="DATE";class Uy extends Ey{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=32}}by=Uy,hv.TimeOfDay=by,Uy.NAME="TimeOfDay";class zy extends Ey{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=33}}_y=zy,hv.DateTime=_y,zy.NAME="DateTime";class Vy extends Ey{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=34}}Sy=Vy,hv.Duration=Sy,Vy.NAME="Duration";class qy extends Ey{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),this.idBlock.tagClass=1,this.idBlock.tagNumber=14}}Py=qy,hv.TIME=Py,qy.NAME="TIME";class Hy{constructor(){var{name:e=Jf,optional:t=!1}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.name=e,this.optional=t}}class Ky extends Hy{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:r=[]}=t;super(e._objectWithoutProperties(t,Ff)),this.value=r}}class Wy extends Hy{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},{value:r=new Hy,local:n=!1}=t;super(e._objectWithoutProperties(t,Uf)),this.value=r,this.local=n}}function Qy(e,t,r){if(r instanceof Ky){for(var n of r.value){if(Qy(e,t,n).verified)return{verified:!0,result:e}}var i={verified:!1,result:{error:"Wrong values for Choice type"}};return r.hasOwnProperty(Qf)&&(i.name=r.name),i}if(r instanceof Hy)return r.hasOwnProperty(Qf)&&(e[r.name]=t),{verified:!0,result:e};if(e instanceof Object==!1)return{verified:!1,result:{error:"Wrong root object"}};if(t instanceof Object==!1)return{verified:!1,result:{error:"Wrong ASN.1 data"}};if(r instanceof Object==!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if("idBlock"in r==!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if("fromBER"in r.idBlock==!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if("toBER"in r.idBlock==!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};var o=r.idBlock.toBER(!1);if(0===o.byteLength)return{verified:!1,result:{error:"Error encoding idBlock for ASN.1 schema"}};if(-1===r.idBlock.fromBER(o,0,o.byteLength))return{verified:!1,result:{error:"Error decoding idBlock for ASN.1 schema"}};if(!1===r.idBlock.hasOwnProperty("tagClass"))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagClass!==t.idBlock.tagClass)return{verified:!1,result:e};if(!1===r.idBlock.hasOwnProperty("tagNumber"))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.tagNumber!==t.idBlock.tagNumber)return{verified:!1,result:e};if(!1===r.idBlock.hasOwnProperty("isConstructed"))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isConstructed!==t.idBlock.isConstructed)return{verified:!1,result:e};if(!("isHexOnly"in r.idBlock))return{verified:!1,result:{error:"Wrong ASN.1 schema"}};if(r.idBlock.isHexOnly!==t.idBlock.isHexOnly)return{verified:!1,result:e};if(r.idBlock.isHexOnly){if(Yf in r.idBlock==!1)return{verified:!1,result:{error:"Wrong ASN.1 schema"}};var a=r.idBlock.valueHexView,s=t.idBlock.valueHexView;if(a.length!==s.length)return{verified:!1,result:e};for(var l=0;l<a.length;l++)if(a[l]!==s[1])return{verified:!1,result:e}}if(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Jf),r.name&&(e[r.name]=t)),r instanceof hv.Constructed){var c=0,u={verified:!1,result:{error:"Unknown error"}},d=r.valueBlock.value.length;if(d>0&&r.valueBlock.value[0]instanceof Wy&&(d=t.valueBlock.value.length),0===d)return{verified:!0,result:e};if(0===t.valueBlock.value.length&&0!==r.valueBlock.value.length){for(var h=!0,p=0;p<r.valueBlock.value.length;p++)h=h&&(r.valueBlock.value[p].optional||!1);return h?{verified:!0,result:e}:(r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Jf),r.name&&delete e[r.name]),e.error="Inconsistent object length",{verified:!1,result:e})}for(var f=0;f<d;f++)if(f-c>=t.valueBlock.value.length){if(!1===r.valueBlock.value[f].optional){var v={verified:!1,result:e};return e.error="Inconsistent length between ASN.1 data and schema",r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Jf),r.name&&(delete e[r.name],v.name=r.name)),v}}else if(r.valueBlock.value[0]instanceof Wy){if(!1===(u=Qy(e,t.valueBlock.value[f],r.valueBlock.value[0].value)).verified){if(!r.valueBlock.value[0].optional)return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Jf),r.name&&delete e[r.name]),u;c++}if(Qf in r.valueBlock.value[0]&&r.valueBlock.value[0].name.length>0){var y={};void 0===(y="local"in r.valueBlock.value[0]&&r.valueBlock.value[0].local?t:e)[r.valueBlock.value[0].name]&&(y[r.valueBlock.value[0].name]=[]),y[r.valueBlock.value[0].name].push(t.valueBlock.value[f])}}else if(!1===(u=Qy(e,t.valueBlock.value[f-c],r.valueBlock.value[f])).verified){if(!r.valueBlock.value[f].optional)return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Jf),r.name&&delete e[r.name]),u;c++}if(!1===u.verified){var g={verified:!1,result:e};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Jf),r.name&&(delete e[r.name],g.name=r.name)),g}return{verified:!0,result:e}}if(r.primitiveSchema&&Yf in t.valueBlock){var m=mv(t.valueBlock.valueHexView);if(-1===m.offset){var w={verified:!1,result:m.result};return r.name&&(r.name=r.name.replace(/^\s+|\s+$/g,Jf),r.name&&(delete e[r.name],w.name=r.name)),w}return Qy(e,m.result,r.primitiveSchema)}return{verified:!0,result:e}}var Yy,Jy,Zy=Object.freeze({__proto__:null,Any:Hy,BaseBlock:pv,BaseStringBlock:vv,BitString:Dv,BmpString:ky,Boolean:xv,CharacterString:Ly,Choice:Ky,Constructed:Sv,DATE:Fy,DateTime:zy,Duration:Vy,EndOfContent:Ev,Enumerated:Kv,GeneralString:Oy,GeneralizedTime:jy,GraphicString:Gy,HexBlock:rv,IA5String:Dy,Integer:Hv,Null:Av,NumericString:Iy,ObjectIdentifier:Yv,OctetString:Cv,Primitive:gv,PrintableString:Cy,RawData:class{get data(){return this.dataView.slice().buffer}set data(e){this.dataView=wf.BufferSourceConverter.toUint8Array(e)}constructor(){var{data:e=$f}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.dataView=wf.BufferSourceConverter.toUint8Array(e)}fromBER(e,t,r){var n=t+r;return this.dataView=wf.BufferSourceConverter.toUint8Array(e).subarray(t,n),n}toBER(e){return this.dataView.slice().buffer}},RelativeObjectIdentifier:$v,Repeated:Wy,Sequence:Xv,Set:ey,TIME:qy,TeletexString:By,TimeOfDay:Uy,UTCTime:My,UniversalString:Ty,Utf8String:Ey,ValueBlock:iv,VideotexString:Ny,ViewWriter:Hf,VisibleString:Ry,compareSchema:Qy,fromBER:wv,verifySchema:function(e,t){if(t instanceof Object==!1)return{verified:!1,result:{error:"Wrong ASN.1 schema type"}};var r=mv(wf.BufferSourceConverter.toUint8Array(e));return-1===r.offset?{verified:!1,result:r.result}:Qy(r.result,r.result,t)}});!function(e){e[e.Sequence=0]="Sequence",e[e.Set=1]="Set",e[e.Choice=2]="Choice"}(Yy||(Yy={})),function(e){e[e.Any=1]="Any",e[e.Boolean=2]="Boolean",e[e.OctetString=3]="OctetString",e[e.BitString=4]="BitString",e[e.Integer=5]="Integer",e[e.Enumerated=6]="Enumerated",e[e.ObjectIdentifier=7]="ObjectIdentifier",e[e.Utf8String=8]="Utf8String",e[e.BmpString=9]="BmpString",e[e.UniversalString=10]="UniversalString",e[e.NumericString=11]="NumericString",e[e.PrintableString=12]="PrintableString",e[e.TeletexString=13]="TeletexString",e[e.VideotexString=14]="VideotexString",e[e.IA5String=15]="IA5String",e[e.GraphicString=16]="GraphicString",e[e.VisibleString=17]="VisibleString",e[e.GeneralString=18]="GeneralString",e[e.CharacterString=19]="CharacterString",e[e.UTCTime=20]="UTCTime",e[e.GeneralizedTime=21]="GeneralizedTime",e[e.DATE=22]="DATE",e[e.TimeOfDay=23]="TimeOfDay",e[e.DateTime=24]="DateTime",e[e.Duration=25]="Duration",e[e.TIME=26]="TIME",e[e.Null=27]="Null"}(Jy||(Jy={}));class $y{constructor(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(this.unusedBits=0,this.value=new ArrayBuffer(0),e)if("number"==typeof e)this.fromNumber(e);else{if(!wf.BufferSourceConverter.isBufferSource(e))throw TypeError("Unsupported type of 'params' argument for BitString");this.unusedBits=t,this.value=wf.BufferSourceConverter.toArrayBuffer(e)}}fromASN(e){if(!(e instanceof Dv))throw new TypeError("Argument 'asn' is not instance of ASN.1 BitString");return this.unusedBits=e.valueBlock.unusedBits,this.value=e.valueBlock.valueHex,this}toASN(){return new Dv({unusedBits:this.unusedBits,valueHex:this.value})}toSchema(e){return new Dv({name:e})}toNumber(){var e="",t=new Uint8Array(this.value);for(var r of t)e+=r.toString(2).padStart(8,"0");return e=e.split("").reverse().join(""),this.unusedBits&&(e=e.slice(this.unusedBits).padStart(this.unusedBits,"0")),parseInt(e,2)}fromNumber(e){var t=e.toString(2),r=t.length+7>>3;this.unusedBits=(r<<3)-t.length;var n=new Uint8Array(r);t=t.padStart(r<<3,"0").split("").reverse().join("");for(var i=0;i<r;)n[i]=parseInt(t.slice(i<<3,8+(i<<3)),2),i++;this.value=n.buffer}}class Xy{get byteLength(){return this.buffer.byteLength}get byteOffset(){return 0}constructor(e){"number"==typeof e?this.buffer=new ArrayBuffer(e):wf.BufferSourceConverter.isBufferSource(e)?this.buffer=wf.BufferSourceConverter.toArrayBuffer(e):Array.isArray(e)?this.buffer=new Uint8Array(e):this.buffer=new ArrayBuffer(0)}fromASN(e){if(!(e instanceof Cv))throw new TypeError("Argument 'asn' is not instance of ASN.1 OctetString");return this.buffer=e.valueBlock.valueHex,this}toASN(){return new Cv({valueHex:this.buffer})}toSchema(e){return new Cv({name:e})}}var eg={fromASN:e=>e instanceof Av?null:e.valueBeforeDecodeView,toASN:e=>{if(null===e)return new Av;var t=wv(e);if(t.result.error)throw new Error(t.result.error);return t.result}},tg={fromASN:e=>e.valueBlock.valueHexView.byteLength>=4?e.valueBlock.toString():e.valueBlock.valueDec,toASN:e=>new Hv({value:+e})},rg={fromASN:e=>e.valueBlock.valueDec,toASN:e=>new Kv({value:e})},ng={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new Hv({valueHex:e})},ig={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new Dv({valueHex:e})},og={fromASN:e=>e.valueBlock.toString(),toASN:e=>new Yv({value:e})},ag={fromASN:e=>e.valueBlock.value,toASN:e=>new xv({value:e})},sg={fromASN:e=>e.valueBlock.valueHexView,toASN:e=>new Cv({valueHex:e})},lg={fromASN:e=>new Xy(e.getValue()),toASN:e=>e.toASN()};function cg(e){return{fromASN:e=>e.valueBlock.value,toASN:t=>new e({value:t})}}var ug=cg(Ey),dg=cg(ky),hg=cg(Ty),pg=cg(Iy),fg=cg(Cy),vg=cg(By),yg=cg(Ny),gg=cg(Dy),mg=cg(Gy),wg=cg(Ry),bg=cg(Oy),_g=cg(Ly),Sg={fromASN:e=>e.toDate(),toASN:e=>new My({valueDate:e})},Pg={fromASN:e=>e.toDate(),toASN:e=>new jy({valueDate:e})},Eg={fromASN:()=>null,toASN:()=>new Av};function Ag(e){switch(e){case Jy.Any:return eg;case Jy.BitString:return ig;case Jy.BmpString:return dg;case Jy.Boolean:return ag;case Jy.CharacterString:return _g;case Jy.Enumerated:return rg;case Jy.GeneralString:return bg;case Jy.GeneralizedTime:return Pg;case Jy.GraphicString:return mg;case Jy.IA5String:return gg;case Jy.Integer:return tg;case Jy.Null:return Eg;case Jy.NumericString:return pg;case Jy.ObjectIdentifier:return og;case Jy.OctetString:return sg;case Jy.PrintableString:return fg;case Jy.TeletexString:return vg;case Jy.UTCTime:return Sg;case Jy.UniversalString:return hg;case Jy.Utf8String:return ug;case Jy.VideotexString:return yg;case Jy.VisibleString:return wg;default:return null}}function kg(e){return"function"==typeof e&&e.prototype?!(!e.prototype.toASN||!e.prototype.fromASN)||kg(e.prototype):!!(e&&"object"==typeof e&&"toASN"in e&&"fromASN"in e)}function xg(e){var t;if(e){var r=Object.getPrototypeOf(e);return(null===(t=null==r?void 0:r.prototype)||void 0===t?void 0:t.constructor)===Array||xg(r)}return!1}function Tg(e,t){if(!e||!t)return!1;if(e.byteLength!==t.byteLength)return!1;for(var r=new Uint8Array(e),n=new Uint8Array(t),i=0;i<e.byteLength;i++)if(r[i]!==n[i])return!1;return!0}var Ig,Cg,Bg,Ng=new class{constructor(){this.items=new WeakMap}has(e){return this.items.has(e)}get(e){var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=this.items.get(e);if(!r)throw new Error("Cannot get schema for '".concat(e.prototype.constructor.name,"' target"));if(t&&!r.schema)throw new Error("Schema '".concat(e.prototype.constructor.name,"' doesn't contain ASN.1 schema. Call 'AsnSchemaStorage.cache'."));return r}cache(e){var t=this.get(e);t.schema||(t.schema=this.create(e,!0))}createDefault(e){var t={type:Yy.Sequence,items:{}},r=this.findParentSchema(e);return r&&(Object.assign(t,r),t.items=Object.assign({},t.items,r.items)),t}create(e,t){var r=this.items.get(e)||this.createDefault(e),n=[];for(var i in r.items){var o=r.items[i],a=t?i:"",s=void 0;if("number"==typeof o.type){var l=Jy[o.type],c=Zy[l];if(!c)throw new Error("Cannot get ASN1 class by name '".concat(l,"'"));s=new c({name:a})}else if(kg(o.type)){s=(new o.type).toSchema(a)}else if(o.optional){this.get(o.type).type===Yy.Choice?s=new Hy({name:a}):(s=this.create(o.type,!1)).name=a}else s=new Hy({name:a});var u=!!o.optional||void 0!==o.defaultValue;if(o.repeated)s.name="",s=new("set"===o.repeated?ey:Xv)({name:"",value:[new Wy({name:a,value:s})]});if(null!==o.context&&void 0!==o.context)if(o.implicit)if("number"==typeof o.type||kg(o.type)){var d=o.repeated?Sv:gv;n.push(new d({name:a,optional:u,idBlock:{tagClass:3,tagNumber:o.context}}))}else{this.cache(o.type);var h=!!o.repeated,p=h?s:this.get(o.type,!0).schema;p="valueBlock"in p?p.valueBlock.value:p.value,n.push(new Sv({name:h?"":a,optional:u,idBlock:{tagClass:3,tagNumber:o.context},value:p}))}else n.push(new Sv({optional:u,idBlock:{tagClass:3,tagNumber:o.context},value:[s]}));else s.optional=u,n.push(s)}switch(r.type){case Yy.Sequence:return new Xv({value:n,name:""});case Yy.Set:return new ey({value:n,name:""});case Yy.Choice:return new Ky({value:n,name:""});default:throw new Error("Unsupported ASN1 type in use")}}set(e,t){return this.items.set(e,t),this}findParentSchema(e){var t=Object.getPrototypeOf(e);return t?this.items.get(t)||this.findParentSchema(t):null}},Dg=e=>t=>{var r;Ng.has(t)?r=Ng.get(t):(r=Ng.createDefault(t),Ng.set(t,r)),Object.assign(r,e)},Gg=e=>(t,r)=>{var n;Ng.has(t.constructor)?n=Ng.get(t.constructor):(n=Ng.createDefault(t.constructor),Ng.set(t.constructor,n));var i=Object.assign({},e);if("number"==typeof i.type&&!i.converter){var o=Ag(e.type);if(!o)throw new Error("Cannot get default converter for property '".concat(r,"' of ").concat(t.constructor.name));i.converter=o}n.items[r]=i};class Rg extends Error{constructor(){super(...arguments),this.schemas=[]}}class Og{static parse(e,t){var r=wv(e);if(r.result.error)throw new Error(r.result.error);return this.fromASN(r.result,t)}static fromASN(e,t){var r,n=this;try{if(kg(t))return(new t).fromASN(e);var i=Ng.get(t);Ng.cache(t);var o=i.schema;if(e.constructor===Sv&&i.type!==Yy.Choice)for(var a in o=new Sv({idBlock:{tagClass:3,tagNumber:e.idBlock.tagNumber},value:i.schema.valueBlock.value}),i.items)delete e[a];var s=Qy({},e,o);if(!s.verified)throw new Rg("Data does not match to ".concat(t.name," ASN1 schema. ").concat(s.result.error));var l=new t;if(xg(t)){if(!("value"in e.valueBlock)||!Array.isArray(e.valueBlock.value))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");var c=i.itemType;if("number"==typeof c){var u=Ag(c);if(!u)throw new Error("Cannot get default converter for array item of ".concat(t.name," ASN1 schema"));return t.from(e.valueBlock.value,(e=>u.fromASN(e)))}return t.from(e.valueBlock.value,(e=>this.fromASN(e,c)))}var d=function(){var e=s.result[h];if(!e)return 1;var t=i.items[h],o=t.type;if("number"==typeof o||kg(o)){var a=null!==(r=t.converter)&&void 0!==r?r:kg(o)?new o:null;if(!a)throw new Error("Converter is empty");if(t.repeated)if(t.implicit){var c=new("sequence"===t.repeated?Xv:ey);c.valueBlock=e.valueBlock;var u=wv(c.toBER(!1));if(-1===u.offset)throw new Error("Cannot parse the child item. ".concat(u.result.error));if(!("value"in u.result.valueBlock)||!Array.isArray(u.result.valueBlock.value))throw new Error("Cannot get items from the ASN.1 parsed value. ASN.1 object is not constructed.");var d=u.result.valueBlock.value;l[h]=Array.from(d,(e=>a.fromASN(e)))}else l[h]=Array.from(e,(e=>a.fromASN(e)));else{var p=e;if(t.implicit){var f;if(kg(o))f=(new o).toSchema("");else{var v=Jy[o],y=Zy[v];if(!y)throw new Error("Cannot get '".concat(v,"' class from asn1js module"));f=new y}f.valueBlock=p.valueBlock,p=wv(f.toBER(!1)).result}l[h]=a.fromASN(p)}}else if(t.repeated){if(!Array.isArray(e))throw new Error("Cannot get list of items from the ASN.1 parsed value. ASN.1 value should be iterable.");l[h]=Array.from(e,(e=>n.fromASN(e,o)))}else l[h]=n.fromASN(e,o)};for(var h in i.items)d();return l}catch(e){throw e instanceof Rg&&e.schemas.push(t.name),e}}}class Lg{static serialize(e){return e instanceof pv?e.toBER(!1):this.toASN(e).toBER(!1)}static toASN(t){if(t&&"object"==typeof t&&kg(t))return t.toASN();if(!t||"object"!=typeof t)throw new TypeError("Parameter 1 should be type of Object.");var r=t.constructor,n=Ng.get(r);Ng.cache(r);var i,o=[];if(n.itemType){if(!Array.isArray(t))throw new TypeError("Parameter 1 should be type of Array.");if("number"==typeof n.itemType){var a=Ag(n.itemType);if(!a)throw new Error("Cannot get default converter for array item of ".concat(r.name," ASN1 schema"));o=t.map((e=>a.toASN(e)))}else o=t.map((e=>this.toAsnItem({type:n.itemType},"[]",r,e)))}else for(var s in n.items){var l=n.items[s],c=t[s];if(!(void 0===c||l.defaultValue===c||"object"==typeof l.defaultValue&&"object"==typeof c&&Tg(this.serialize(l.defaultValue),this.serialize(c)))){var u=Lg.toAsnItem(l,s,r,c);if("number"==typeof l.context)if(l.implicit)if(l.repeated||"number"!=typeof l.type&&!kg(l.type))o.push(new Sv({optional:l.optional,idBlock:{tagClass:3,tagNumber:l.context},value:u.valueBlock.value}));else{var d={};d.valueHex=u instanceof Av?u.valueBeforeDecodeView:u.valueBlock.toBER(),o.push(new gv(e._objectSpread2({optional:l.optional,idBlock:{tagClass:3,tagNumber:l.context}},d)))}else o.push(new Sv({optional:l.optional,idBlock:{tagClass:3,tagNumber:l.context},value:[u]}));else l.repeated?o=o.concat(u):o.push(u)}}switch(n.type){case Yy.Sequence:i=new Xv({value:o});break;case Yy.Set:i=new ey({value:o});break;case Yy.Choice:if(!o[0])throw new Error("Schema '".concat(r.name,"' has wrong data. Choice cannot be empty."));i=o[0]}return i}static toAsnItem(e,t,r,n){var i;if("number"==typeof e.type){var o=e.converter;if(!o)throw new Error("Property '".concat(t,"' doesn't have converter for type ").concat(Jy[e.type]," in schema '").concat(r.name,"'"));if(e.repeated){if(!Array.isArray(n))throw new TypeError("Parameter 'objProp' should be type of Array.");var a=Array.from(n,(e=>o.toASN(e)));i=new("sequence"===e.repeated?Xv:ey)({value:a})}else i=o.toASN(n)}else if(e.repeated){if(!Array.isArray(n))throw new TypeError("Parameter 'objProp' should be type of Array.");var s=Array.from(n,(e=>this.toASN(e)));i=new("sequence"===e.repeated?Xv:ey)({value:s})}else i=this.toASN(n);return i}}class Mg extends Array{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[];if("number"==typeof e)super(e);else for(var t of(super(),e))this.push(t)}}class jg{static serialize(e){return Lg.serialize(e)}static parse(e,t){return Og.parse(e,t)}static toString(e){var t=wv(wf.BufferSourceConverter.isBufferSource(e)?wf.BufferSourceConverter.toArrayBuffer(e):jg.serialize(e));if(-1===t.offset)throw new Error("Cannot decode ASN.1 data. ".concat(t.result.error));return t.result.toString()}}class Fg{static isIPv4(e){return/^(\d{1,3}\.){3}\d{1,3}$/.test(e)}static parseIPv4(e){var t=e.split(".");if(4!==t.length)throw new Error("Invalid IPv4 address");return t.map((e=>{var t=parseInt(e,10);if(isNaN(t)||t<0||t>255)throw new Error("Invalid IPv4 address part");return t}))}static parseIPv6(e){var t=this.expandIPv6(e).split(":");if(8!==t.length)throw new Error("Invalid IPv6 address");return t.reduce(((e,t)=>{var r=parseInt(t,16);if(isNaN(r)||r<0||r>65535)throw new Error("Invalid IPv6 address part");return e.push(r>>8&255),e.push(255&r),e}),[])}static expandIPv6(e){if(!e.includes("::"))return e;var t=e.split("::");if(t.length>2)throw new Error("Invalid IPv6 address");var r=t[0]?t[0].split(":"):[],n=t[1]?t[1].split(":"):[],i=8-(r.length+n.length);if(i<0)throw new Error("Invalid IPv6 address");return[...r,...Array(i).fill("0"),...n].join(":")}static formatIPv6(e){for(var t=[],r=0;r<16;r+=2)t.push((e[r]<<8|e[r+1]).toString(16));return this.compressIPv6(t.join(":"))}static compressIPv6(e){for(var t=e.split(":"),r=-1,n=0,i=-1,o=0,a=0;a<t.length;a++)"0"===t[a]?(-1===i&&(i=a),o++):(o>n&&(r=i,n=o),i=-1,o=0);if(o>n&&(r=i,n=o),n>1){var s=t.slice(0,r).join(":"),l=t.slice(r+n).join(":");return"".concat(s,"::").concat(l)}return e}static parseCIDR(e){var[t,r]=e.split("/"),n=parseInt(r,10);if(this.isIPv4(t)){if(n<0||n>32)throw new Error("Invalid IPv4 prefix length");return[this.parseIPv4(t),n]}if(n<0||n>128)throw new Error("Invalid IPv6 prefix length");return[this.parseIPv6(t),n]}static decodeIP(e){if(64===e.length&&0===parseInt(e,16))return"::/0";if(16!==e.length)return e;var t=parseInt(e.slice(8),16).toString(2).split("").reduce(((e,t)=>e+ +t),0),r=e.slice(0,8).replace(/(.{2})/g,(e=>"".concat(parseInt(e,16),".")));return r=r.slice(0,-1),"".concat(r,"/").concat(t)}static toString(e){var t=new Uint8Array(e);if(4===t.length)return Array.from(t).join(".");if(16===t.length)return this.formatIPv6(t);if(8===t.length||32===t.length){var r=t.length/2,n=t.slice(0,r),i=t.slice(r);if(t.every((e=>0===e)))return 8===t.length?"0.0.0.0/0":"::/0";var o=i.reduce(((e,t)=>e+(t.toString(2).match(/1/g)||[]).length),0);if(8===t.length){var a=Array.from(n).join(".");return"".concat(a,"/").concat(o)}var s=this.formatIPv6(n);return"".concat(s,"/").concat(o)}return this.decodeIP(wf.Convert.ToHex(e))}static fromString(e){if(e.includes("/")){for(var[t,r]=this.parseCIDR(e),n=new Uint8Array(t.length),i=r,o=0;o<n.length;o++)i>=8?(n[o]=255,i-=8):i>0&&(n[o]=255<<8-i,i=0);var a=new Uint8Array(2*t.length);return a.set(t,0),a.set(n,t.length),a.buffer}var s=this.isIPv4(e)?this.parseIPv4(e):this.parseIPv6(e);return new Uint8Array(s).buffer}}var Ug=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}toString(){return this.bmpString||this.printableString||this.teletexString||this.universalString||this.utf8String||""}};Ro([Gg({type:Jy.TeletexString})],Ug.prototype,"teletexString",void 0),Ro([Gg({type:Jy.PrintableString})],Ug.prototype,"printableString",void 0),Ro([Gg({type:Jy.UniversalString})],Ug.prototype,"universalString",void 0),Ro([Gg({type:Jy.Utf8String})],Ug.prototype,"utf8String",void 0),Ro([Gg({type:Jy.BmpString})],Ug.prototype,"bmpString",void 0),Ug=Ro([Dg({type:Yy.Choice})],Ug);var zg=class extends Ug{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(e),Object.assign(this,e)}toString(){return this.ia5String||(this.anyValue?wf.Convert.ToHex(this.anyValue):super.toString())}};Ro([Gg({type:Jy.IA5String})],zg.prototype,"ia5String",void 0),Ro([Gg({type:Jy.Any})],zg.prototype,"anyValue",void 0),zg=Ro([Dg({type:Yy.Choice})],zg);class Vg{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.type="",this.value=new zg,Object.assign(this,e)}}Ro([Gg({type:Jy.ObjectIdentifier})],Vg.prototype,"type",void 0),Ro([Gg({type:zg})],Vg.prototype,"value",void 0);var qg=Ig=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,Ig.prototype)}};qg=Ig=Ro([Dg({type:Yy.Set,itemType:Vg})],qg);var Hg=Cg=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,Cg.prototype)}};Hg=Cg=Ro([Dg({type:Yy.Sequence,itemType:qg})],Hg);var Kg=Bg=class extends Hg{constructor(e){super(e),Object.setPrototypeOf(this,Bg.prototype)}};Kg=Bg=Ro([Dg({type:Yy.Sequence})],Kg);var Wg={fromASN:e=>Fg.toString(sg.fromASN(e)),toASN:e=>sg.toASN(Fg.fromString(e))};class Qg{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.typeId="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:Jy.ObjectIdentifier})],Qg.prototype,"typeId",void 0),Ro([Gg({type:Jy.Any,context:0})],Qg.prototype,"value",void 0);class Yg{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.partyName=new Ug,Object.assign(this,e)}}Ro([Gg({type:Ug,optional:!0,context:0,implicit:!0})],Yg.prototype,"nameAssigner",void 0),Ro([Gg({type:Ug,context:1,implicit:!0})],Yg.prototype,"partyName",void 0);var Jg=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Ro([Gg({type:Qg,context:0,implicit:!0})],Jg.prototype,"otherName",void 0),Ro([Gg({type:Jy.IA5String,context:1,implicit:!0})],Jg.prototype,"rfc822Name",void 0),Ro([Gg({type:Jy.IA5String,context:2,implicit:!0})],Jg.prototype,"dNSName",void 0),Ro([Gg({type:Jy.Any,context:3,implicit:!0})],Jg.prototype,"x400Address",void 0),Ro([Gg({type:Kg,context:4,implicit:!1})],Jg.prototype,"directoryName",void 0),Ro([Gg({type:Yg,context:5})],Jg.prototype,"ediPartyName",void 0),Ro([Gg({type:Jy.IA5String,context:6,implicit:!0})],Jg.prototype,"uniformResourceIdentifier",void 0),Ro([Gg({type:Jy.OctetString,context:7,implicit:!0,converter:Wg})],Jg.prototype,"iPAddress",void 0),Ro([Gg({type:Jy.ObjectIdentifier,context:8,implicit:!0})],Jg.prototype,"registeredID",void 0),Jg=Ro([Dg({type:Yy.Choice})],Jg);var Zg,$g="1.3.6.1.5.5.7",Xg="".concat($g,".1"),em="".concat($g,".3"),tm="".concat($g,".48"),rm="".concat(tm,".1"),nm="".concat(tm,".2"),im="".concat(tm,".3"),om="".concat(tm,".5"),am="2.5.29",sm="".concat(Xg,".1");class lm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.accessMethod="",this.accessLocation=new Jg,Object.assign(this,e)}}Ro([Gg({type:Jy.ObjectIdentifier})],lm.prototype,"accessMethod",void 0),Ro([Gg({type:Jg})],lm.prototype,"accessLocation",void 0);var cm=Zg=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,Zg.prototype)}};cm=Zg=Ro([Dg({type:Yy.Sequence,itemType:lm})],cm);var um="".concat(am,".35");class dm extends Xy{}class hm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e&&Object.assign(this,e)}}Ro([Gg({type:dm,context:0,optional:!0,implicit:!0})],hm.prototype,"keyIdentifier",void 0),Ro([Gg({type:Jg,context:1,optional:!0,implicit:!0,repeated:"sequence"})],hm.prototype,"authorityCertIssuer",void 0),Ro([Gg({type:Jy.Integer,context:2,optional:!0,implicit:!0,converter:ng})],hm.prototype,"authorityCertSerialNumber",void 0);var pm,fm="".concat(am,".19");class vm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.cA=!1,Object.assign(this,e)}}Ro([Gg({type:Jy.Boolean,defaultValue:!1})],vm.prototype,"cA",void 0),Ro([Gg({type:Jy.Integer,optional:!0})],vm.prototype,"pathLenConstraint",void 0);var ym,gm=pm=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,pm.prototype)}};gm=pm=Ro([Dg({type:Yy.Sequence,itemType:Jg})],gm);var mm,wm=ym=class extends gm{constructor(e){super(e),Object.setPrototypeOf(this,ym.prototype)}};wm=ym=Ro([Dg({type:Yy.Sequence})],wm);var bm="".concat(am,".32"),_m=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}toString(){return this.ia5String||this.visibleString||this.bmpString||this.utf8String||""}};Ro([Gg({type:Jy.IA5String})],_m.prototype,"ia5String",void 0),Ro([Gg({type:Jy.VisibleString})],_m.prototype,"visibleString",void 0),Ro([Gg({type:Jy.BmpString})],_m.prototype,"bmpString",void 0),Ro([Gg({type:Jy.Utf8String})],_m.prototype,"utf8String",void 0),_m=Ro([Dg({type:Yy.Choice})],_m);class Sm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.organization=new _m,this.noticeNumbers=[],Object.assign(this,e)}}Ro([Gg({type:_m})],Sm.prototype,"organization",void 0),Ro([Gg({type:Jy.Integer,repeated:"sequence"})],Sm.prototype,"noticeNumbers",void 0);class Pm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}Ro([Gg({type:Sm,optional:!0})],Pm.prototype,"noticeRef",void 0),Ro([Gg({type:_m,optional:!0})],Pm.prototype,"explicitText",void 0);var Em=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Ro([Gg({type:Jy.IA5String})],Em.prototype,"cPSuri",void 0),Ro([Gg({type:Pm})],Em.prototype,"userNotice",void 0),Em=Ro([Dg({type:Yy.Choice})],Em);class Am{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.policyQualifierId="",this.qualifier=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:Jy.ObjectIdentifier})],Am.prototype,"policyQualifierId",void 0),Ro([Gg({type:Jy.Any})],Am.prototype,"qualifier",void 0);class km{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.policyIdentifier="",Object.assign(this,e)}}Ro([Gg({type:Jy.ObjectIdentifier})],km.prototype,"policyIdentifier",void 0),Ro([Gg({type:Am,repeated:"sequence",optional:!0})],km.prototype,"policyQualifiers",void 0);var xm=mm=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,mm.prototype)}};xm=mm=Ro([Dg({type:Yy.Sequence,itemType:km})],xm);var Tm=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.value=e}};Ro([Gg({type:Jy.Integer})],Tm.prototype,"value",void 0),Tm=Ro([Dg({type:Yy.Choice})],Tm);var Im,Cm=class extends Tm{};Cm=Ro([Dg({type:Yy.Choice})],Cm);var Bm,Nm="".concat(am,".31");!function(e){e[e.unused=1]="unused",e[e.keyCompromise=2]="keyCompromise",e[e.cACompromise=4]="cACompromise",e[e.affiliationChanged=8]="affiliationChanged",e[e.superseded=16]="superseded",e[e.cessationOfOperation=32]="cessationOfOperation",e[e.certificateHold=64]="certificateHold",e[e.privilegeWithdrawn=128]="privilegeWithdrawn",e[e.aACompromise=256]="aACompromise"}(Bm||(Bm={}));class Dm extends $y{toJSON(){var e=[],t=this.toNumber();return t&Bm.aACompromise&&e.push("aACompromise"),t&Bm.affiliationChanged&&e.push("affiliationChanged"),t&Bm.cACompromise&&e.push("cACompromise"),t&Bm.certificateHold&&e.push("certificateHold"),t&Bm.cessationOfOperation&&e.push("cessationOfOperation"),t&Bm.keyCompromise&&e.push("keyCompromise"),t&Bm.privilegeWithdrawn&&e.push("privilegeWithdrawn"),t&Bm.superseded&&e.push("superseded"),t&Bm.unused&&e.push("unused"),e}toString(){return"[".concat(this.toJSON().join(", "),"]")}}var Gm=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Ro([Gg({type:Jg,context:0,repeated:"sequence",implicit:!0})],Gm.prototype,"fullName",void 0),Ro([Gg({type:qg,context:1,implicit:!0})],Gm.prototype,"nameRelativeToCRLIssuer",void 0),Gm=Ro([Dg({type:Yy.Choice})],Gm);class Rm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}Ro([Gg({type:Gm,context:0,optional:!0})],Rm.prototype,"distributionPoint",void 0),Ro([Gg({type:Dm,context:1,optional:!0,implicit:!0})],Rm.prototype,"reasons",void 0),Ro([Gg({type:Jg,context:2,optional:!0,repeated:"sequence",implicit:!0})],Rm.prototype,"cRLIssuer",void 0);var Om,Lm=Im=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,Im.prototype)}};Lm=Im=Ro([Dg({type:Yy.Sequence,itemType:Rm})],Lm);var Mm,jm=Om=class extends Lm{constructor(e){super(e),Object.setPrototypeOf(this,Om.prototype)}};jm=Om=Ro([Dg({type:Yy.Sequence,itemType:Rm})],jm);class Fm{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.onlyContainsUserCerts=Fm.ONLY,this.onlyContainsCACerts=Fm.ONLY,this.indirectCRL=Fm.ONLY,this.onlyContainsAttributeCerts=Fm.ONLY,Object.assign(this,e)}}Fm.ONLY=!1,Ro([Gg({type:Gm,context:0,optional:!0})],Fm.prototype,"distributionPoint",void 0),Ro([Gg({type:Jy.Boolean,context:1,defaultValue:Fm.ONLY,implicit:!0})],Fm.prototype,"onlyContainsUserCerts",void 0),Ro([Gg({type:Jy.Boolean,context:2,defaultValue:Fm.ONLY,implicit:!0})],Fm.prototype,"onlyContainsCACerts",void 0),Ro([Gg({type:Dm,context:3,optional:!0,implicit:!0})],Fm.prototype,"onlySomeReasons",void 0),Ro([Gg({type:Jy.Boolean,context:4,defaultValue:Fm.ONLY,implicit:!0})],Fm.prototype,"indirectCRL",void 0),Ro([Gg({type:Jy.Boolean,context:5,defaultValue:Fm.ONLY,implicit:!0})],Fm.prototype,"onlyContainsAttributeCerts",void 0),function(e){e[e.unspecified=0]="unspecified",e[e.keyCompromise=1]="keyCompromise",e[e.cACompromise=2]="cACompromise",e[e.affiliationChanged=3]="affiliationChanged",e[e.superseded=4]="superseded",e[e.cessationOfOperation=5]="cessationOfOperation",e[e.certificateHold=6]="certificateHold",e[e.removeFromCRL=8]="removeFromCRL",e[e.privilegeWithdrawn=9]="privilegeWithdrawn",e[e.aACompromise=10]="aACompromise"}(Mm||(Mm={}));var Um,zm=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Mm.unspecified;this.reason=Mm.unspecified,this.reason=e}toJSON(){return Mm[this.reason]}toString(){return this.toJSON()}};Ro([Gg({type:Jy.Enumerated})],zm.prototype,"reason",void 0),zm=Ro([Dg({type:Yy.Choice})],zm);var Vm="".concat(am,".37"),qm=Um=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,Um.prototype)}};qm=Um=Ro([Dg({type:Yy.Sequence,itemType:Jy.ObjectIdentifier})],qm);var Hm="".concat(em,".1"),Km="".concat(em,".2"),Wm="".concat(em,".3"),Qm="".concat(em,".4"),Ym="".concat(em,".8"),Jm="".concat(em,".9"),Zm=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new ArrayBuffer(0);this.value=e}};Ro([Gg({type:Jy.Integer,converter:ng})],Zm.prototype,"value",void 0),Zm=Ro([Dg({type:Yy.Choice})],Zm);var $m,Xm=class{constructor(e){this.value=new Date,e&&(this.value=e)}};Ro([Gg({type:Jy.GeneralizedTime})],Xm.prototype,"value",void 0),Xm=Ro([Dg({type:Yy.Choice})],Xm);var ew=$m=class extends gm{constructor(e){super(e),Object.setPrototypeOf(this,$m.prototype)}};ew=$m=Ro([Dg({type:Yy.Sequence})],ew);var tw,rw,nw="".concat(am,".15");!function(e){e[e.digitalSignature=1]="digitalSignature",e[e.nonRepudiation=2]="nonRepudiation",e[e.keyEncipherment=4]="keyEncipherment",e[e.dataEncipherment=8]="dataEncipherment",e[e.keyAgreement=16]="keyAgreement",e[e.keyCertSign=32]="keyCertSign",e[e.cRLSign=64]="cRLSign",e[e.encipherOnly=128]="encipherOnly",e[e.decipherOnly=256]="decipherOnly"}(tw||(tw={}));class iw extends $y{toJSON(){var e=this.toNumber(),t=[];return e&tw.cRLSign&&t.push("crlSign"),e&tw.dataEncipherment&&t.push("dataEncipherment"),e&tw.decipherOnly&&t.push("decipherOnly"),e&tw.digitalSignature&&t.push("digitalSignature"),e&tw.encipherOnly&&t.push("encipherOnly"),e&tw.keyAgreement&&t.push("keyAgreement"),e&tw.keyCertSign&&t.push("keyCertSign"),e&tw.keyEncipherment&&t.push("keyEncipherment"),e&tw.nonRepudiation&&t.push("nonRepudiation"),t}toString(){return"[".concat(this.toJSON().join(", "),"]")}}class ow{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.base=new Jg,this.minimum=0,Object.assign(this,e)}}Ro([Gg({type:Jg})],ow.prototype,"base",void 0),Ro([Gg({type:Jy.Integer,context:0,defaultValue:0,implicit:!0})],ow.prototype,"minimum",void 0),Ro([Gg({type:Jy.Integer,context:1,optional:!0,implicit:!0})],ow.prototype,"maximum",void 0);var aw,sw=rw=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,rw.prototype)}};sw=rw=Ro([Dg({type:Yy.Sequence,itemType:ow})],sw);class lw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}Ro([Gg({type:sw,context:0,optional:!0,implicit:!0})],lw.prototype,"permittedSubtrees",void 0),Ro([Gg({type:sw,context:1,optional:!0,implicit:!0})],lw.prototype,"excludedSubtrees",void 0);class cw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}Ro([Gg({type:Jy.Integer,context:0,implicit:!0,optional:!0,converter:ng})],cw.prototype,"requireExplicitPolicy",void 0),Ro([Gg({type:Jy.Integer,context:1,implicit:!0,optional:!0,converter:ng})],cw.prototype,"inhibitPolicyMapping",void 0);class uw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.issuerDomainPolicy="",this.subjectDomainPolicy="",Object.assign(this,e)}}Ro([Gg({type:Jy.ObjectIdentifier})],uw.prototype,"issuerDomainPolicy",void 0),Ro([Gg({type:Jy.ObjectIdentifier})],uw.prototype,"subjectDomainPolicy",void 0);var dw,hw=aw=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,aw.prototype)}};hw=aw=Ro([Dg({type:Yy.Sequence,itemType:uw})],hw);var pw="".concat(am,".17"),fw=dw=class extends gm{constructor(e){super(e),Object.setPrototypeOf(this,dw.prototype)}};fw=dw=Ro([Dg({type:Yy.Sequence})],fw);let vw=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.type="",this.values=[],Object.assign(this,e)}};var yw;Ro([Gg({type:Jy.ObjectIdentifier})],vw.prototype,"type",void 0),Ro([Gg({type:Jy.Any,repeated:"set"})],vw.prototype,"values",void 0);var gw=yw=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,yw.prototype)}};gw=yw=Ro([Dg({type:Yy.Sequence,itemType:vw})],gw);var mw,ww,bw="".concat(am,".14");class _w extends dm{}class Sw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}Ro([Gg({type:Jy.GeneralizedTime,context:0,implicit:!0,optional:!0})],Sw.prototype,"notBefore",void 0),Ro([Gg({type:Jy.GeneralizedTime,context:1,implicit:!0,optional:!0})],Sw.prototype,"notAfter",void 0),function(e){e[e.keyUpdateAllowed=1]="keyUpdateAllowed",e[e.newExtensions=2]="newExtensions",e[e.pKIXCertificate=4]="pKIXCertificate"}(mw||(mw={}));class Pw extends $y{toJSON(){var e=[],t=this.toNumber();return t&mw.pKIXCertificate&&e.push("pKIXCertificate"),t&mw.newExtensions&&e.push("newExtensions"),t&mw.keyUpdateAllowed&&e.push("keyUpdateAllowed"),e}toString(){return"[".concat(this.toJSON().join(", "),"]")}}class Ew{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.entrustVers="",this.entrustInfoFlags=new Pw,Object.assign(this,e)}}Ro([Gg({type:Jy.GeneralString})],Ew.prototype,"entrustVers",void 0),Ro([Gg({type:Pw})],Ew.prototype,"entrustInfoFlags",void 0);var Aw=ww=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,ww.prototype)}};Aw=ww=Ro([Dg({type:Yy.Sequence,itemType:lm})],Aw);class kw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.algorithm="",Object.assign(this,e)}isEqual(e){return e instanceof kw&&e.algorithm==this.algorithm&&(e.parameters&&this.parameters&&wf.isEqual(e.parameters,this.parameters)||e.parameters===this.parameters)}}Ro([Gg({type:Jy.ObjectIdentifier})],kw.prototype,"algorithm",void 0),Ro([Gg({type:Jy.Any,optional:!0})],kw.prototype,"parameters",void 0);class xw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.algorithm=new kw,this.subjectPublicKey=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:kw})],xw.prototype,"algorithm",void 0),Ro([Gg({type:Jy.BitString})],xw.prototype,"subjectPublicKey",void 0);var Tw,Iw=class{constructor(e){if(e)if("string"==typeof e||"number"==typeof e||e instanceof Date){var t=new Date(e);t.getUTCFullYear()>2049?this.generalTime=t:this.utcTime=t}else Object.assign(this,e)}getTime(){var e=this.utcTime||this.generalTime;if(!e)throw new Error("Cannot get time from CHOICE object");return e}};Ro([Gg({type:Jy.UTCTime})],Iw.prototype,"utcTime",void 0),Ro([Gg({type:Jy.GeneralizedTime})],Iw.prototype,"generalTime",void 0),Iw=Ro([Dg({type:Yy.Choice})],Iw);class Cw{constructor(e){this.notBefore=new Iw(new Date),this.notAfter=new Iw(new Date),e&&(this.notBefore=new Iw(e.notBefore),this.notAfter=new Iw(e.notAfter))}}Ro([Gg({type:Iw})],Cw.prototype,"notBefore",void 0),Ro([Gg({type:Iw})],Cw.prototype,"notAfter",void 0);let Bw=class e{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.extnID="",this.critical=e.CRITICAL,this.extnValue=new Xy,Object.assign(this,t)}};Bw.CRITICAL=!1,Ro([Gg({type:Jy.ObjectIdentifier})],Bw.prototype,"extnID",void 0),Ro([Gg({type:Jy.Boolean,defaultValue:Bw.CRITICAL})],Bw.prototype,"critical",void 0),Ro([Gg({type:Xy})],Bw.prototype,"extnValue",void 0);var Nw,Dw=Tw=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,Tw.prototype)}};Dw=Tw=Ro([Dg({type:Yy.Sequence,itemType:Bw})],Dw),function(e){e[e.v1=0]="v1",e[e.v2=1]="v2",e[e.v3=2]="v3"}(Nw||(Nw={}));class Gw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Nw.v1,this.serialNumber=new ArrayBuffer(0),this.signature=new kw,this.issuer=new Kg,this.validity=new Cw,this.subject=new Kg,this.subjectPublicKeyInfo=new xw,Object.assign(this,e)}}Ro([Gg({type:Jy.Integer,context:0,defaultValue:Nw.v1})],Gw.prototype,"version",void 0),Ro([Gg({type:Jy.Integer,converter:ng})],Gw.prototype,"serialNumber",void 0),Ro([Gg({type:kw})],Gw.prototype,"signature",void 0),Ro([Gg({type:Kg})],Gw.prototype,"issuer",void 0),Ro([Gg({type:Cw})],Gw.prototype,"validity",void 0),Ro([Gg({type:Kg})],Gw.prototype,"subject",void 0),Ro([Gg({type:xw})],Gw.prototype,"subjectPublicKeyInfo",void 0),Ro([Gg({type:Jy.BitString,context:1,implicit:!0,optional:!0})],Gw.prototype,"issuerUniqueID",void 0),Ro([Gg({type:Jy.BitString,context:2,implicit:!0,optional:!0})],Gw.prototype,"subjectUniqueID",void 0),Ro([Gg({type:Dw,context:3,optional:!0})],Gw.prototype,"extensions",void 0);class Rw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.tbsCertificate=new Gw,this.signatureAlgorithm=new kw,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:Gw})],Rw.prototype,"tbsCertificate",void 0),Ro([Gg({type:kw})],Rw.prototype,"signatureAlgorithm",void 0),Ro([Gg({type:Jy.BitString})],Rw.prototype,"signatureValue",void 0);class Ow{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.userCertificate=new ArrayBuffer(0),this.revocationDate=new Iw,Object.assign(this,e)}}Ro([Gg({type:Jy.Integer,converter:ng})],Ow.prototype,"userCertificate",void 0),Ro([Gg({type:Iw})],Ow.prototype,"revocationDate",void 0),Ro([Gg({type:Bw,optional:!0,repeated:"sequence"})],Ow.prototype,"crlEntryExtensions",void 0);class Lw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.signature=new kw,this.issuer=new Kg,this.thisUpdate=new Iw,Object.assign(this,e)}}Ro([Gg({type:Jy.Integer,optional:!0})],Lw.prototype,"version",void 0),Ro([Gg({type:kw})],Lw.prototype,"signature",void 0),Ro([Gg({type:Kg})],Lw.prototype,"issuer",void 0),Ro([Gg({type:Iw})],Lw.prototype,"thisUpdate",void 0),Ro([Gg({type:Iw,optional:!0})],Lw.prototype,"nextUpdate",void 0),Ro([Gg({type:Ow,repeated:"sequence",optional:!0})],Lw.prototype,"revokedCertificates",void 0),Ro([Gg({type:Bw,optional:!0,context:0,repeated:"sequence"})],Lw.prototype,"crlExtensions",void 0);class Mw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.tbsCertList=new Lw,this.signatureAlgorithm=new kw,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:Lw})],Mw.prototype,"tbsCertList",void 0),Ro([Gg({type:kw})],Mw.prototype,"signatureAlgorithm",void 0),Ro([Gg({type:Jy.BitString})],Mw.prototype,"signature",void 0);class jw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.issuer=new Kg,this.serialNumber=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:Kg})],jw.prototype,"issuer",void 0),Ro([Gg({type:Jy.Integer,converter:ng})],jw.prototype,"serialNumber",void 0);var Fw,Uw=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Ro([Gg({type:_w,context:0,implicit:!0})],Uw.prototype,"subjectKeyIdentifier",void 0),Ro([Gg({type:jw})],Uw.prototype,"issuerAndSerialNumber",void 0),Uw=Ro([Dg({type:Yy.Choice})],Uw),function(e){e[e.v0=0]="v0",e[e.v1=1]="v1",e[e.v2=2]="v2",e[e.v3=3]="v3",e[e.v4=4]="v4",e[e.v5=5]="v5"}(Fw||(Fw={}));var zw=class extends kw{};zw=Ro([Dg({type:Yy.Sequence})],zw);var Vw=class extends kw{};Vw=Ro([Dg({type:Yy.Sequence})],Vw);var qw=class extends kw{};qw=Ro([Dg({type:Yy.Sequence})],qw);var Hw=class extends kw{};Hw=Ro([Dg({type:Yy.Sequence})],Hw);var Kw=class extends kw{};Kw=Ro([Dg({type:Yy.Sequence})],Kw);var Ww=class extends kw{};Ww=Ro([Dg({type:Yy.Sequence})],Ww);let Qw=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.attrType="",this.attrValues=[],Object.assign(this,e)}};var Yw;Ro([Gg({type:Jy.ObjectIdentifier})],Qw.prototype,"attrType",void 0),Ro([Gg({type:Jy.Any,repeated:"set"})],Qw.prototype,"attrValues",void 0);class Jw{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Fw.v0,this.sid=new Uw,this.digestAlgorithm=new zw,this.signatureAlgorithm=new Vw,this.signature=new Xy,Object.assign(this,e)}}Ro([Gg({type:Jy.Integer})],Jw.prototype,"version",void 0),Ro([Gg({type:Uw})],Jw.prototype,"sid",void 0),Ro([Gg({type:zw})],Jw.prototype,"digestAlgorithm",void 0),Ro([Gg({type:Qw,repeated:"set",context:0,implicit:!0,optional:!0})],Jw.prototype,"signedAttrs",void 0),Ro([Gg({type:Vw})],Jw.prototype,"signatureAlgorithm",void 0),Ro([Gg({type:Xy})],Jw.prototype,"signature",void 0),Ro([Gg({type:Qw,repeated:"set",context:1,implicit:!0,optional:!0})],Jw.prototype,"unsignedAttrs",void 0);var Zw=Yw=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,Yw.prototype)}};Zw=Yw=Ro([Dg({type:Yy.Set,itemType:Jw})],Zw);var $w=class extends Iw{};$w=Ro([Dg({type:Yy.Choice})],$w);var Xw,eb=class extends Jw{};eb=Ro([Dg({type:Yy.Sequence})],eb);class tb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.acIssuer=new Jg,this.acSerial=0,this.attrs=[],Object.assign(this,e)}}Ro([Gg({type:Jg})],tb.prototype,"acIssuer",void 0),Ro([Gg({type:Jy.Integer})],tb.prototype,"acSerial",void 0),Ro([Gg({type:vw,repeated:"sequence"})],tb.prototype,"attrs",void 0);var rb,nb=Xw=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,Xw.prototype)}};nb=Xw=Ro([Dg({type:Yy.Sequence,itemType:Jy.ObjectIdentifier})],nb);class ib{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.permitUnSpecified=!0,Object.assign(this,e)}}Ro([Gg({type:Jy.Integer,optional:!0})],ib.prototype,"pathLenConstraint",void 0),Ro([Gg({type:nb,implicit:!0,context:0,optional:!0})],ib.prototype,"permittedAttrs",void 0),Ro([Gg({type:nb,implicit:!0,context:1,optional:!0})],ib.prototype,"excludedAttrs",void 0),Ro([Gg({type:Jy.Boolean,defaultValue:!0})],ib.prototype,"permitUnSpecified",void 0);class ob{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.issuer=new gm,this.serial=new ArrayBuffer(0),this.issuerUID=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:gm})],ob.prototype,"issuer",void 0),Ro([Gg({type:Jy.Integer,converter:ng})],ob.prototype,"serial",void 0),Ro([Gg({type:Jy.BitString,optional:!0})],ob.prototype,"issuerUID",void 0),function(e){e[e.publicKey=0]="publicKey",e[e.publicKeyCert=1]="publicKeyCert",e[e.otherObjectTypes=2]="otherObjectTypes"}(rb||(rb={}));class ab{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.digestedObjectType=rb.publicKey,this.digestAlgorithm=new kw,this.objectDigest=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:Jy.Enumerated})],ab.prototype,"digestedObjectType",void 0),Ro([Gg({type:Jy.ObjectIdentifier,optional:!0})],ab.prototype,"otherObjectTypeID",void 0),Ro([Gg({type:kw})],ab.prototype,"digestAlgorithm",void 0),Ro([Gg({type:Jy.BitString})],ab.prototype,"objectDigest",void 0);class sb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}Ro([Gg({type:gm,optional:!0})],sb.prototype,"issuerName",void 0),Ro([Gg({type:ob,context:0,implicit:!0,optional:!0})],sb.prototype,"baseCertificateID",void 0),Ro([Gg({type:ab,context:1,implicit:!0,optional:!0})],sb.prototype,"objectDigestInfo",void 0);var lb,cb,ub,db=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Ro([Gg({type:Jg,repeated:"sequence"})],db.prototype,"v1Form",void 0),Ro([Gg({type:sb,context:0,implicit:!0})],db.prototype,"v2Form",void 0),db=Ro([Dg({type:Yy.Choice})],db);class hb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.notBeforeTime=new Date,this.notAfterTime=new Date,Object.assign(this,e)}}Ro([Gg({type:Jy.GeneralizedTime})],hb.prototype,"notBeforeTime",void 0),Ro([Gg({type:Jy.GeneralizedTime})],hb.prototype,"notAfterTime",void 0);class pb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}Ro([Gg({type:ob,implicit:!0,context:0,optional:!0})],pb.prototype,"baseCertificateID",void 0),Ro([Gg({type:gm,implicit:!0,context:1,optional:!0})],pb.prototype,"entityName",void 0),Ro([Gg({type:ab,implicit:!0,context:2,optional:!0})],pb.prototype,"objectDigestInfo",void 0),function(e){e[e.v2=1]="v2"}(lb||(lb={}));class fb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=lb.v2,this.holder=new pb,this.issuer=new db,this.signature=new kw,this.serialNumber=new ArrayBuffer(0),this.attrCertValidityPeriod=new hb,this.attributes=[],Object.assign(this,e)}}Ro([Gg({type:Jy.Integer})],fb.prototype,"version",void 0),Ro([Gg({type:pb})],fb.prototype,"holder",void 0),Ro([Gg({type:db})],fb.prototype,"issuer",void 0),Ro([Gg({type:kw})],fb.prototype,"signature",void 0),Ro([Gg({type:Jy.Integer,converter:ng})],fb.prototype,"serialNumber",void 0),Ro([Gg({type:hb})],fb.prototype,"attrCertValidityPeriod",void 0),Ro([Gg({type:vw,repeated:"sequence"})],fb.prototype,"attributes",void 0),Ro([Gg({type:Jy.BitString,optional:!0})],fb.prototype,"issuerUniqueID",void 0),Ro([Gg({type:Dw,optional:!0})],fb.prototype,"extensions",void 0);class vb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.acinfo=new fb,this.signatureAlgorithm=new kw,this.signatureValue=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:fb})],vb.prototype,"acinfo",void 0),Ro([Gg({type:kw})],vb.prototype,"signatureAlgorithm",void 0),Ro([Gg({type:Jy.BitString})],vb.prototype,"signatureValue",void 0),function(e){e[e.unmarked=1]="unmarked",e[e.unclassified=2]="unclassified",e[e.restricted=4]="restricted",e[e.confidential=8]="confidential",e[e.secret=16]="secret",e[e.topSecret=32]="topSecret"}(cb||(cb={}));class yb extends $y{}class gb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.type="",this.value=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:Jy.ObjectIdentifier,implicit:!0,context:0})],gb.prototype,"type",void 0),Ro([Gg({type:Jy.Any,implicit:!0,context:1})],gb.prototype,"value",void 0);class mb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.policyId="",this.classList=new yb(cb.unclassified),Object.assign(this,e)}}Ro([Gg({type:Jy.ObjectIdentifier})],mb.prototype,"policyId",void 0),Ro([Gg({type:yb,defaultValue:new yb(cb.unclassified)})],mb.prototype,"classList",void 0),Ro([Gg({type:gb,repeated:"set"})],mb.prototype,"securityCategories",void 0);class wb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}Ro([Gg({type:Xy})],wb.prototype,"cotets",void 0),Ro([Gg({type:Jy.ObjectIdentifier})],wb.prototype,"oid",void 0),Ro([Gg({type:Jy.Utf8String})],wb.prototype,"string",void 0);class bb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.values=[],Object.assign(this,e)}}Ro([Gg({type:gm,implicit:!0,context:0,optional:!0})],bb.prototype,"policyAuthority",void 0),Ro([Gg({type:wb,repeated:"sequence"})],bb.prototype,"values",void 0);class _b{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.targetCertificate=new ob,Object.assign(this,e)}}Ro([Gg({type:ob})],_b.prototype,"targetCertificate",void 0),Ro([Gg({type:Jg,optional:!0})],_b.prototype,"targetName",void 0),Ro([Gg({type:ab,optional:!0})],_b.prototype,"certDigestInfo",void 0);var Sb=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Ro([Gg({type:Jg,context:0,implicit:!0})],Sb.prototype,"targetName",void 0),Ro([Gg({type:Jg,context:1,implicit:!0})],Sb.prototype,"targetGroup",void 0),Ro([Gg({type:_b,context:2,implicit:!0})],Sb.prototype,"targetCert",void 0),Sb=Ro([Dg({type:Yy.Choice})],Sb);var Pb,Eb=ub=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,ub.prototype)}};Eb=ub=Ro([Dg({type:Yy.Sequence,itemType:Sb})],Eb);var Ab,kb=Pb=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,Pb.prototype)}};kb=Pb=Ro([Dg({type:Yy.Sequence,itemType:Eb})],kb);class xb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}Ro([Gg({type:gm,implicit:!0,context:0,optional:!0})],xb.prototype,"roleAuthority",void 0),Ro([Gg({type:Jg,implicit:!0,context:1})],xb.prototype,"roleName",void 0);class Tb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.service=new Jg,this.ident=new Jg,Object.assign(this,e)}}Ro([Gg({type:Jg})],Tb.prototype,"service",void 0),Ro([Gg({type:Jg})],Tb.prototype,"ident",void 0),Ro([Gg({type:Xy,optional:!0})],Tb.prototype,"authInfo",void 0);class Ib{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.otherCertFormat="",this.otherCert=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:Jy.ObjectIdentifier})],Ib.prototype,"otherCertFormat",void 0),Ro([Gg({type:Jy.Any})],Ib.prototype,"otherCert",void 0);var Cb=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Ro([Gg({type:Rw})],Cb.prototype,"certificate",void 0),Ro([Gg({type:vb,context:2,implicit:!0})],Cb.prototype,"v2AttrCert",void 0),Ro([Gg({type:Ib,context:3,implicit:!0})],Cb.prototype,"other",void 0),Cb=Ro([Dg({type:Yy.Choice})],Cb);var Bb=Ab=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,Ab.prototype)}};Bb=Ab=Ro([Dg({type:Yy.Set,itemType:Cb})],Bb);class Nb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.contentType="",this.content=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:Jy.ObjectIdentifier})],Nb.prototype,"contentType",void 0),Ro([Gg({type:Jy.Any,context:0})],Nb.prototype,"content",void 0);var Db=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Ro([Gg({type:Xy})],Db.prototype,"single",void 0),Ro([Gg({type:Jy.Any})],Db.prototype,"any",void 0),Db=Ro([Dg({type:Yy.Choice})],Db);class Gb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.eContentType="",Object.assign(this,e)}}Ro([Gg({type:Jy.ObjectIdentifier})],Gb.prototype,"eContentType",void 0),Ro([Gg({type:Db,context:0,optional:!0})],Gb.prototype,"eContent",void 0);var Rb,Ob=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Ro([Gg({type:Xy,context:0,implicit:!0,optional:!0})],Ob.prototype,"value",void 0),Ro([Gg({type:Xy,converter:lg,context:0,implicit:!0,optional:!0,repeated:"sequence"})],Ob.prototype,"constructedValue",void 0),Ob=Ro([Dg({type:Yy.Choice})],Ob);class Lb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.contentType="",this.contentEncryptionAlgorithm=new Hw,Object.assign(this,e)}}Ro([Gg({type:Jy.ObjectIdentifier})],Lb.prototype,"contentType",void 0),Ro([Gg({type:Hw})],Lb.prototype,"contentEncryptionAlgorithm",void 0),Ro([Gg({type:Ob,optional:!0})],Lb.prototype,"encryptedContent",void 0);class Mb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.keyAttrId="",Object.assign(this,e)}}Ro([Gg({type:Jy.ObjectIdentifier})],Mb.prototype,"keyAttrId",void 0),Ro([Gg({type:Jy.Any,optional:!0})],Mb.prototype,"keyAttr",void 0);class jb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.subjectKeyIdentifier=new _w,Object.assign(this,e)}}Ro([Gg({type:_w})],jb.prototype,"subjectKeyIdentifier",void 0),Ro([Gg({type:Jy.GeneralizedTime,optional:!0})],jb.prototype,"date",void 0),Ro([Gg({type:Mb,optional:!0})],jb.prototype,"other",void 0);var Fb=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Ro([Gg({type:jb,context:0,implicit:!0,optional:!0})],Fb.prototype,"rKeyId",void 0),Ro([Gg({type:jw,optional:!0})],Fb.prototype,"issuerAndSerialNumber",void 0),Fb=Ro([Dg({type:Yy.Choice})],Fb);class Ub{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.rid=new Fb,this.encryptedKey=new Xy,Object.assign(this,e)}}Ro([Gg({type:Fb})],Ub.prototype,"rid",void 0),Ro([Gg({type:Xy})],Ub.prototype,"encryptedKey",void 0);var zb=Rb=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,Rb.prototype)}};zb=Rb=Ro([Dg({type:Yy.Sequence,itemType:Ub})],zb);class Vb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.algorithm=new kw,this.publicKey=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:kw})],Vb.prototype,"algorithm",void 0),Ro([Gg({type:Jy.BitString})],Vb.prototype,"publicKey",void 0);var qb=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Ro([Gg({type:_w,context:0,implicit:!0,optional:!0})],qb.prototype,"subjectKeyIdentifier",void 0),Ro([Gg({type:Vb,context:1,implicit:!0,optional:!0})],qb.prototype,"originatorKey",void 0),Ro([Gg({type:jw,optional:!0})],qb.prototype,"issuerAndSerialNumber",void 0),qb=Ro([Dg({type:Yy.Choice})],qb);class Hb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Fw.v3,this.originator=new qb,this.keyEncryptionAlgorithm=new qw,this.recipientEncryptedKeys=new zb,Object.assign(this,e)}}Ro([Gg({type:Jy.Integer})],Hb.prototype,"version",void 0),Ro([Gg({type:qb,context:0})],Hb.prototype,"originator",void 0),Ro([Gg({type:Xy,context:1,optional:!0})],Hb.prototype,"ukm",void 0),Ro([Gg({type:qw})],Hb.prototype,"keyEncryptionAlgorithm",void 0),Ro([Gg({type:zb})],Hb.prototype,"recipientEncryptedKeys",void 0);var Kb=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Ro([Gg({type:_w,context:0,implicit:!0})],Kb.prototype,"subjectKeyIdentifier",void 0),Ro([Gg({type:jw})],Kb.prototype,"issuerAndSerialNumber",void 0),Kb=Ro([Dg({type:Yy.Choice})],Kb);class Wb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Fw.v0,this.rid=new Kb,this.keyEncryptionAlgorithm=new qw,this.encryptedKey=new Xy,Object.assign(this,e)}}Ro([Gg({type:Jy.Integer})],Wb.prototype,"version",void 0),Ro([Gg({type:Kb})],Wb.prototype,"rid",void 0),Ro([Gg({type:qw})],Wb.prototype,"keyEncryptionAlgorithm",void 0),Ro([Gg({type:Xy})],Wb.prototype,"encryptedKey",void 0);class Qb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.keyIdentifier=new Xy,Object.assign(this,e)}}Ro([Gg({type:Xy})],Qb.prototype,"keyIdentifier",void 0),Ro([Gg({type:Jy.GeneralizedTime,optional:!0})],Qb.prototype,"date",void 0),Ro([Gg({type:Mb,optional:!0})],Qb.prototype,"other",void 0);class Yb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Fw.v4,this.kekid=new Qb,this.keyEncryptionAlgorithm=new qw,this.encryptedKey=new Xy,Object.assign(this,e)}}Ro([Gg({type:Jy.Integer})],Yb.prototype,"version",void 0),Ro([Gg({type:Qb})],Yb.prototype,"kekid",void 0),Ro([Gg({type:qw})],Yb.prototype,"keyEncryptionAlgorithm",void 0),Ro([Gg({type:Xy})],Yb.prototype,"encryptedKey",void 0);class Jb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Fw.v0,this.keyEncryptionAlgorithm=new qw,this.encryptedKey=new Xy,Object.assign(this,e)}}Ro([Gg({type:Jy.Integer})],Jb.prototype,"version",void 0),Ro([Gg({type:Ww,context:0,optional:!0})],Jb.prototype,"keyDerivationAlgorithm",void 0),Ro([Gg({type:qw})],Jb.prototype,"keyEncryptionAlgorithm",void 0),Ro([Gg({type:Xy})],Jb.prototype,"encryptedKey",void 0);class Zb{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.oriType="",this.oriValue=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:Jy.ObjectIdentifier})],Zb.prototype,"oriType",void 0),Ro([Gg({type:Jy.Any})],Zb.prototype,"oriValue",void 0);var $b,Xb=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Ro([Gg({type:Wb,optional:!0})],Xb.prototype,"ktri",void 0),Ro([Gg({type:Hb,context:1,implicit:!0,optional:!0})],Xb.prototype,"kari",void 0),Ro([Gg({type:Yb,context:2,implicit:!0,optional:!0})],Xb.prototype,"kekri",void 0),Ro([Gg({type:Jb,context:3,implicit:!0,optional:!0})],Xb.prototype,"pwri",void 0),Ro([Gg({type:Zb,context:4,implicit:!0,optional:!0})],Xb.prototype,"ori",void 0),Xb=Ro([Dg({type:Yy.Choice})],Xb);var e_,t_=$b=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,$b.prototype)}};t_=$b=Ro([Dg({type:Yy.Set,itemType:Xb})],t_);class r_{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.otherRevInfoFormat="",this.otherRevInfo=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:Jy.ObjectIdentifier})],r_.prototype,"otherRevInfoFormat",void 0),Ro([Gg({type:Jy.Any})],r_.prototype,"otherRevInfo",void 0);var n_=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.other=new r_,Object.assign(this,e)}};Ro([Gg({type:r_,context:1,implicit:!0})],n_.prototype,"other",void 0),n_=Ro([Dg({type:Yy.Choice})],n_);var i_,o_=e_=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,e_.prototype)}};o_=e_=Ro([Dg({type:Yy.Set,itemType:n_})],o_);class a_{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}}Ro([Gg({type:Bb,context:0,implicit:!0,optional:!0})],a_.prototype,"certs",void 0),Ro([Gg({type:o_,context:1,implicit:!0,optional:!0})],a_.prototype,"crls",void 0);var s_=i_=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,i_.prototype)}};s_=i_=Ro([Dg({type:Yy.Set,itemType:Qw})],s_);class l_{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Fw.v0,this.recipientInfos=new t_,this.encryptedContentInfo=new Lb,Object.assign(this,e)}}Ro([Gg({type:Jy.Integer})],l_.prototype,"version",void 0),Ro([Gg({type:a_,context:0,implicit:!0,optional:!0})],l_.prototype,"originatorInfo",void 0),Ro([Gg({type:t_})],l_.prototype,"recipientInfos",void 0),Ro([Gg({type:Lb})],l_.prototype,"encryptedContentInfo",void 0),Ro([Gg({type:s_,context:1,implicit:!0,optional:!0})],l_.prototype,"unprotectedAttrs",void 0);var c_,u_="1.2.840.113549.1.7.2",d_=c_=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,c_.prototype)}};d_=c_=Ro([Dg({type:Yy.Set,itemType:zw})],d_);class h_{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=Fw.v0,this.digestAlgorithms=new d_,this.encapContentInfo=new Gb,this.signerInfos=new Zw,Object.assign(this,e)}}Ro([Gg({type:Jy.Integer})],h_.prototype,"version",void 0),Ro([Gg({type:d_})],h_.prototype,"digestAlgorithms",void 0),Ro([Gg({type:Gb})],h_.prototype,"encapContentInfo",void 0),Ro([Gg({type:Bb,context:0,implicit:!0,optional:!0})],h_.prototype,"certificates",void 0),Ro([Gg({type:o_,context:1,implicit:!0,optional:!0})],h_.prototype,"crls",void 0),Ro([Gg({type:Zw})],h_.prototype,"signerInfos",void 0);var p_="1.2.840.10045.2.1",f_="1.2.840.10045.4.1",v_="1.2.840.10045.4.3.1",y_="1.2.840.10045.4.3.2",g_="1.2.840.10045.4.3.3",m_="1.2.840.10045.4.3.4",w_="1.2.840.10045.3.1.7",b_="1.3.132.0.34",__="1.3.132.0.35";function S_(e){return new kw({algorithm:e})}var P_=S_(f_);S_(v_);var E_=S_(y_),A_=S_(g_),k_=S_(m_),x_=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Ro([Gg({type:Jy.ObjectIdentifier})],x_.prototype,"fieldType",void 0),Ro([Gg({type:Jy.Any})],x_.prototype,"parameters",void 0),x_=Ro([Dg({type:Yy.Sequence})],x_);var T_,I_=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Ro([Gg({type:Jy.OctetString})],I_.prototype,"a",void 0),Ro([Gg({type:Jy.OctetString})],I_.prototype,"b",void 0),Ro([Gg({type:Jy.BitString,optional:!0})],I_.prototype,"seed",void 0),I_=Ro([Dg({type:Yy.Sequence})],I_),function(e){e[e.ecpVer1=1]="ecpVer1"}(T_||(T_={}));var C_=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=T_.ecpVer1,Object.assign(this,e)}};Ro([Gg({type:Jy.Integer})],C_.prototype,"version",void 0),Ro([Gg({type:x_})],C_.prototype,"fieldID",void 0),Ro([Gg({type:I_})],C_.prototype,"curve",void 0),Ro([Gg({type:class extends Xy{}})],C_.prototype,"base",void 0),Ro([Gg({type:Jy.Integer,converter:ng})],C_.prototype,"order",void 0),Ro([Gg({type:Jy.Integer,optional:!0})],C_.prototype,"cofactor",void 0),C_=Ro([Dg({type:Yy.Sequence})],C_);var B_=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};Object.assign(this,e)}};Ro([Gg({type:Jy.ObjectIdentifier})],B_.prototype,"namedCurve",void 0),Ro([Gg({type:Jy.Null})],B_.prototype,"implicitCurve",void 0),Ro([Gg({type:C_})],B_.prototype,"specifiedCurve",void 0),B_=Ro([Dg({type:Yy.Choice})],B_);class N_{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=1,this.privateKey=new Xy,Object.assign(this,e)}}Ro([Gg({type:Jy.Integer})],N_.prototype,"version",void 0),Ro([Gg({type:Xy})],N_.prototype,"privateKey",void 0),Ro([Gg({type:B_,context:0,optional:!0})],N_.prototype,"parameters",void 0),Ro([Gg({type:Jy.BitString,context:1,optional:!0})],N_.prototype,"publicKey",void 0);class D_{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.r=new ArrayBuffer(0),this.s=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:Jy.Integer,converter:ng})],D_.prototype,"r",void 0),Ro([Gg({type:Jy.Integer,converter:ng})],D_.prototype,"s",void 0);var G_="1.2.840.113549.1.1",R_="".concat(G_,".1"),O_="".concat(G_,".7"),L_="".concat(G_,".9"),M_="".concat(G_,".10"),j_="".concat(G_,".2"),F_="".concat(G_,".4"),U_="".concat(G_,".5"),z_="".concat(G_,".14"),V_="".concat(G_,".11"),q_="".concat(G_,".12"),H_="".concat(G_,".13"),K_="".concat(G_,".15"),W_="".concat(G_,".16"),Q_="1.3.14.3.2.26",Y_="2.16.840.1.101.3.4.2.4",J_="2.16.840.1.101.3.4.2.1",Z_="2.16.840.1.101.3.4.2.2",$_="2.16.840.1.101.3.4.2.3",X_="".concat(G_,".8");function eS(e){return new kw({algorithm:e,parameters:null})}eS("1.2.840.113549.2.2"),eS("1.2.840.113549.2.5");var tS=eS(Q_);eS(Y_),eS(J_),eS(Z_),eS($_),eS("2.16.840.1.101.3.4.2.5"),eS("2.16.840.1.101.3.4.2.6");var rS,nS=new kw({algorithm:X_,parameters:jg.serialize(tS)}),iS=new kw({algorithm:L_,parameters:jg.serialize(sg.toASN(new Uint8Array([218,57,163,238,94,107,75,13,50,85,191,239,149,96,24,144,175,216,7,9]).buffer))});eS(R_),eS(j_),eS(F_),eS(U_),eS(K_),eS(W_),eS(q_),eS(H_),eS(K_),eS(W_);class oS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.hashAlgorithm=new kw(tS),this.maskGenAlgorithm=new kw({algorithm:X_,parameters:jg.serialize(tS)}),this.pSourceAlgorithm=new kw(iS),Object.assign(this,e)}}Ro([Gg({type:kw,context:0,defaultValue:tS})],oS.prototype,"hashAlgorithm",void 0),Ro([Gg({type:kw,context:1,defaultValue:nS})],oS.prototype,"maskGenAlgorithm",void 0),Ro([Gg({type:kw,context:2,defaultValue:iS})],oS.prototype,"pSourceAlgorithm",void 0),new kw({algorithm:O_,parameters:jg.serialize(new oS)});class aS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.hashAlgorithm=new kw(tS),this.maskGenAlgorithm=new kw({algorithm:X_,parameters:jg.serialize(tS)}),this.saltLength=20,this.trailerField=1,Object.assign(this,e)}}Ro([Gg({type:kw,context:0,defaultValue:tS})],aS.prototype,"hashAlgorithm",void 0),Ro([Gg({type:kw,context:1,defaultValue:nS})],aS.prototype,"maskGenAlgorithm",void 0),Ro([Gg({type:Jy.Integer,context:2,defaultValue:20})],aS.prototype,"saltLength",void 0),Ro([Gg({type:Jy.Integer,context:3,defaultValue:1})],aS.prototype,"trailerField",void 0),new kw({algorithm:M_,parameters:jg.serialize(new aS)});class sS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.digestAlgorithm=new kw,this.digest=new Xy,Object.assign(this,e)}}Ro([Gg({type:kw})],sS.prototype,"digestAlgorithm",void 0),Ro([Gg({type:Xy})],sS.prototype,"digest",void 0);class lS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.prime=new ArrayBuffer(0),this.exponent=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:Jy.Integer,converter:ng})],lS.prototype,"prime",void 0),Ro([Gg({type:Jy.Integer,converter:ng})],lS.prototype,"exponent",void 0),Ro([Gg({type:Jy.Integer,converter:ng})],lS.prototype,"coefficient",void 0);var cS,uS=rS=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,rS.prototype)}};uS=rS=Ro([Dg({type:Yy.Sequence,itemType:lS})],uS);class dS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=0,this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),this.privateExponent=new ArrayBuffer(0),this.prime1=new ArrayBuffer(0),this.prime2=new ArrayBuffer(0),this.exponent1=new ArrayBuffer(0),this.exponent2=new ArrayBuffer(0),this.coefficient=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:Jy.Integer})],dS.prototype,"version",void 0),Ro([Gg({type:Jy.Integer,converter:ng})],dS.prototype,"modulus",void 0),Ro([Gg({type:Jy.Integer,converter:ng})],dS.prototype,"publicExponent",void 0),Ro([Gg({type:Jy.Integer,converter:ng})],dS.prototype,"privateExponent",void 0),Ro([Gg({type:Jy.Integer,converter:ng})],dS.prototype,"prime1",void 0),Ro([Gg({type:Jy.Integer,converter:ng})],dS.prototype,"prime2",void 0),Ro([Gg({type:Jy.Integer,converter:ng})],dS.prototype,"exponent1",void 0),Ro([Gg({type:Jy.Integer,converter:ng})],dS.prototype,"exponent2",void 0),Ro([Gg({type:Jy.Integer,converter:ng})],dS.prototype,"coefficient",void 0),Ro([Gg({type:uS,optional:!0})],dS.prototype,"otherPrimeInfos",void 0);class hS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.modulus=new ArrayBuffer(0),this.publicExponent=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:Jy.Integer,converter:ng})],hS.prototype,"modulus",void 0),Ro([Gg({type:Jy.Integer,converter:ng})],hS.prototype,"publicExponent",void 0),function(e){e[e.Transient=0]="Transient",e[e.Singleton=1]="Singleton",e[e.ResolutionScoped=2]="ResolutionScoped",e[e.ContainerScoped=3]="ContainerScoped"}(cS||(cS={}));var pS=cS;function fS(e){return!!e.useClass}function vS(e){return!!e.useFactory}var yS=function(){function e(e){this.wrap=e,this.reflectMethods=["get","getPrototypeOf","setPrototypeOf","getOwnPropertyDescriptor","defineProperty","has","set","deleteProperty","apply","construct","ownKeys"]}return e.prototype.createProxy=function(e){var t,r=this,n=!1;return new Proxy({},this.createHandler((function(){return n||(t=e(r.wrap()),n=!0),t})))},e.prototype.createHandler=function(e){var t={};return this.reflectMethods.forEach((function(r){t[r]=function(){for(var t=[],n=0;n<arguments.length;n++)t[n]=arguments[n];return t[0]=e(),Reflect[r].apply(void 0,Fo(t))}})),t},e}();function gS(e){return"string"==typeof e||"symbol"==typeof e}function mS(e){return"object"==typeof e&&"token"in e&&"transform"in e}function wS(e){return!!e.useToken}function bS(e){return null!=e.useValue}var _S=function(){function e(){this._registryMap=new Map}return e.prototype.entries=function(){return this._registryMap.entries()},e.prototype.getAll=function(e){return this.ensure(e),this._registryMap.get(e)},e.prototype.get=function(e){this.ensure(e);var t=this._registryMap.get(e);return t[t.length-1]||null},e.prototype.set=function(e,t){this.ensure(e),this._registryMap.get(e).push(t)},e.prototype.setAll=function(e,t){this._registryMap.set(e,t)},e.prototype.has=function(e){return this.ensure(e),this._registryMap.get(e).length>0},e.prototype.clear=function(){this._registryMap.clear()},e.prototype.ensure=function(e){this._registryMap.has(e)||this._registryMap.set(e,[])},e}(),SS=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Go(t,e),t}(_S),PS=function(){this.scopedResolutions=new Map};function ES(e,t,r){var n,i,o=jo(e.toString().match(/constructor\(([\w, ]+)\)/)||[],2)[1],a=function(e,t){return null===e?"at position #"+t:'"'+e.split(",")[t].trim()+'" at position #'+t}(void 0===o?null:o,t);return n="Cannot inject the dependency "+a+' of "'+e.name+'" constructor. Reason:',void 0===i&&(i=" "),Fo([n],r.message.split("\n").map((function(e){return i+e}))).join("\n")}var AS,kS=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Go(t,e),t}(_S),xS=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Go(t,e),t}(_S),TS=function(){this.preResolution=new kS,this.postResolution=new xS},IS=new Map,CS=function(){function e(e){this.parent=e,this._registry=new SS,this.interceptors=new TS,this.disposed=!1,this.disposables=new Set}return e.prototype.register=function(e,t,r){var n;if(void 0===r&&(r={lifecycle:pS.Transient}),this.ensureNotDisposed(),n=function(e){return fS(e)||bS(e)||wS(e)||vS(e)}(t)?t:{useClass:t},wS(n))for(var i=[e],o=n;null!=o;){var a=o.useToken;if(i.includes(a))throw new Error("Token registration cycle detected! "+Fo(i,[a]).join(" -> "));i.push(a);var s=this._registry.get(a);o=s&&wS(s.provider)?s.provider:null}if((r.lifecycle===pS.Singleton||r.lifecycle==pS.ContainerScoped||r.lifecycle==pS.ResolutionScoped)&&(bS(n)||vS(n)))throw new Error('Cannot use lifecycle "'+pS[r.lifecycle]+'" with ValueProviders or FactoryProviders');return this._registry.set(e,{provider:n,options:r}),this},e.prototype.registerType=function(e,t){return this.ensureNotDisposed(),gS(t)?this.register(e,{useToken:t}):this.register(e,{useClass:t})},e.prototype.registerInstance=function(e,t){return this.ensureNotDisposed(),this.register(e,{useValue:t})},e.prototype.registerSingleton=function(e,t){if(this.ensureNotDisposed(),gS(e)){if(gS(t))return this.register(e,{useToken:t},{lifecycle:pS.Singleton});if(t)return this.register(e,{useClass:t},{lifecycle:pS.Singleton});throw new Error('Cannot register a type name as a singleton without a "to" token')}var r=e;return t&&!gS(t)&&(r=t),this.register(e,{useClass:r},{lifecycle:pS.Singleton})},e.prototype.resolve=function(e,t,r){void 0===t&&(t=new PS),void 0===r&&(r=!1),this.ensureNotDisposed();var n=this.getRegistration(e);if(!n&&gS(e)){if(r)return;throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"Single"),n){var i=this.resolveRegistration(n,t);return this.executePostResolutionInterceptor(e,i,"Single"),i}if(function(e){return"function"==typeof e||e instanceof yS}(e)){i=this.construct(e,t);return this.executePostResolutionInterceptor(e,i,"Single"),i}throw new Error("Attempted to construct an undefined constructor. Could mean a circular dependency problem. Try using `delay` function.")},e.prototype.executePreResolutionInterceptor=function(e,t){var r,n;if(this.interceptors.preResolution.has(e)){var i=[];try{for(var o=Mo(this.interceptors.preResolution.getAll(e)),a=o.next();!a.done;a=o.next()){var s=a.value;"Once"!=s.options.frequency&&i.push(s),s.callback(e,t)}}catch(e){r={error:e}}finally{try{a&&!a.done&&(n=o.return)&&n.call(o)}finally{if(r)throw r.error}}this.interceptors.preResolution.setAll(e,i)}},e.prototype.executePostResolutionInterceptor=function(e,t,r){var n,i;if(this.interceptors.postResolution.has(e)){var o=[];try{for(var a=Mo(this.interceptors.postResolution.getAll(e)),s=a.next();!s.done;s=a.next()){var l=s.value;"Once"!=l.options.frequency&&o.push(l),l.callback(e,t,r)}}catch(e){n={error:e}}finally{try{s&&!s.done&&(i=a.return)&&i.call(a)}finally{if(n)throw n.error}}this.interceptors.postResolution.setAll(e,o)}},e.prototype.resolveRegistration=function(e,t){if(this.ensureNotDisposed(),e.options.lifecycle===pS.ResolutionScoped&&t.scopedResolutions.has(e))return t.scopedResolutions.get(e);var r,n=e.options.lifecycle===pS.Singleton,i=e.options.lifecycle===pS.ContainerScoped,o=n||i;return r=bS(e.provider)?e.provider.useValue:wS(e.provider)?o?e.instance||(e.instance=this.resolve(e.provider.useToken,t)):this.resolve(e.provider.useToken,t):fS(e.provider)?o?e.instance||(e.instance=this.construct(e.provider.useClass,t)):this.construct(e.provider.useClass,t):vS(e.provider)?e.provider.useFactory(this):this.construct(e.provider,t),e.options.lifecycle===pS.ResolutionScoped&&t.scopedResolutions.set(e,r),r},e.prototype.resolveAll=function(e,t,r){var n=this;void 0===t&&(t=new PS),void 0===r&&(r=!1),this.ensureNotDisposed();var i=this.getAllRegistrations(e);if(!i&&gS(e)){if(r)return[];throw new Error('Attempted to resolve unregistered dependency token: "'+e.toString()+'"')}if(this.executePreResolutionInterceptor(e,"All"),i){var o=i.map((function(e){return n.resolveRegistration(e,t)}));return this.executePostResolutionInterceptor(e,o,"All"),o}var a=[this.construct(e,t)];return this.executePostResolutionInterceptor(e,a,"All"),a},e.prototype.isRegistered=function(e,t){return void 0===t&&(t=!1),this.ensureNotDisposed(),this._registry.has(e)||t&&(this.parent||!1)&&this.parent.isRegistered(e,!0)},e.prototype.reset=function(){this.ensureNotDisposed(),this._registry.clear(),this.interceptors.preResolution.clear(),this.interceptors.postResolution.clear()},e.prototype.clearInstances=function(){var e,t;this.ensureNotDisposed();try{for(var r=Mo(this._registry.entries()),n=r.next();!n.done;n=r.next()){var i=jo(n.value,2),o=i[0],a=i[1];this._registry.setAll(o,a.filter((function(e){return!bS(e.provider)})).map((function(e){return e.instance=void 0,e})))}}catch(t){e={error:t}}finally{try{n&&!n.done&&(t=r.return)&&t.call(r)}finally{if(e)throw e.error}}},e.prototype.createChildContainer=function(){var t,r;this.ensureNotDisposed();var n=new e(this);try{for(var i=Mo(this._registry.entries()),o=i.next();!o.done;o=i.next()){var a=jo(o.value,2),s=a[0],l=a[1];l.some((function(e){return e.options.lifecycle===pS.ContainerScoped}))&&n._registry.setAll(s,l.map((function(e){return e.options.lifecycle===pS.ContainerScoped?{provider:e.provider,options:e.options}:e})))}}catch(e){t={error:e}}finally{try{o&&!o.done&&(r=i.return)&&r.call(i)}finally{if(t)throw t.error}}return n},e.prototype.beforeResolution=function(e,t,r){void 0===r&&(r={frequency:"Always"}),this.interceptors.preResolution.set(e,{callback:t,options:r})},e.prototype.afterResolution=function(e,t,r){void 0===r&&(r={frequency:"Always"}),this.interceptors.postResolution.set(e,{callback:t,options:r})},e.prototype.dispose=function(){return Oo(this,void 0,void 0,(function(){var e;return Lo(this,(function(t){switch(t.label){case 0:return this.disposed=!0,e=[],this.disposables.forEach((function(t){var r=t.dispose();r&&e.push(r)})),[4,Promise.all(e)];case 1:return t.sent(),[2]}}))}))},e.prototype.getRegistration=function(e){return this.isRegistered(e)?this._registry.get(e):this.parent?this.parent.getRegistration(e):null},e.prototype.getAllRegistrations=function(e){return this.isRegistered(e)?this._registry.getAll(e):this.parent?this.parent.getAllRegistrations(e):null},e.prototype.construct=function(e,t){var r=this;if(e instanceof yS)return e.createProxy((function(e){return r.resolve(e,t)}));var n,i=function(){var n=IS.get(e);if(!n||0===n.length){if(0===e.length)return new e;throw new Error('TypeInfo not known for "'+e.name+'"')}var i=n.map(r.resolveParams(t,e));return new(e.bind.apply(e,Fo([void 0],i)))}();return"function"!=typeof(n=i).dispose||n.dispose.length>0||this.disposables.add(i),i},e.prototype.resolveParams=function(e,t){var r=this;return function(n,i){var o,a,s,l;try{return"object"==typeof(l=n)&&"token"in l&&"multiple"in l?mS(n)?n.multiple?(o=r.resolve(n.transform)).transform.apply(o,Fo([r.resolveAll(n.token,new PS,n.isOptional)],n.transformArgs)):(a=r.resolve(n.transform)).transform.apply(a,Fo([r.resolve(n.token,e,n.isOptional)],n.transformArgs)):n.multiple?r.resolveAll(n.token,new PS,n.isOptional):r.resolve(n.token,e,n.isOptional):mS(n)?(s=r.resolve(n.transform,e)).transform.apply(s,Fo([r.resolve(n.token,e)],n.transformArgs)):r.resolve(n,e)}catch(e){throw new Error(ES(t,i,e))}}},e.prototype.ensureNotDisposed=function(){if(this.disposed)throw new Error("This container has been disposed, you cannot interact with a disposed container")},e}(),BS=new CS;function NS(e){return function(e){IS.set(e,function(e){var t=Reflect.getMetadata("design:paramtypes",e)||[],r=Reflect.getOwnMetadata("injectionTokens",e)||{};return Object.keys(r).forEach((function(e){t[+e]=r[e]})),t}(e))}}if("undefined"==typeof Reflect||!Reflect.getMetadata)throw new Error("tsyringe requires a reflect polyfill. Please add 'import \"reflect-metadata\"' to the top of your entry point.");class DS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.attrId="",this.attrValues=[],Object.assign(e)}}Ro([Gg({type:Jy.ObjectIdentifier})],DS.prototype,"attrId",void 0),Ro([Gg({type:Jy.Any,repeated:"set"})],DS.prototype,"attrValues",void 0);var GS,RS=AS=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,AS.prototype)}};RS=AS=Ro([Dg({type:Yy.Sequence,itemType:DS})],RS);var OS=GS=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,GS.prototype)}};OS=GS=Ro([Dg({type:Yy.Sequence,itemType:Nb})],OS);class LS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.certId="",this.certValue=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:Jy.ObjectIdentifier})],LS.prototype,"certId",void 0),Ro([Gg({type:Jy.Any,context:0})],LS.prototype,"certValue",void 0);class MS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.crlId="",this.crltValue=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:Jy.ObjectIdentifier})],MS.prototype,"crlId",void 0),Ro([Gg({type:Jy.Any,context:0})],MS.prototype,"crltValue",void 0);class jS extends Xy{}let FS=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.encryptionAlgorithm=new kw,this.encryptedData=new jS,Object.assign(this,e)}};var US,zS;Ro([Gg({type:kw})],FS.prototype,"encryptionAlgorithm",void 0),Ro([Gg({type:jS})],FS.prototype,"encryptedData",void 0),function(e){e[e.v1=0]="v1"}(zS||(zS={}));class VS extends Xy{}var qS=US=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,US.prototype)}};qS=US=Ro([Dg({type:Yy.Sequence,itemType:vw})],qS);class HS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=zS.v1,this.privateKeyAlgorithm=new kw,this.privateKey=new VS,Object.assign(this,e)}}Ro([Gg({type:Jy.Integer})],HS.prototype,"version",void 0),Ro([Gg({type:kw})],HS.prototype,"privateKeyAlgorithm",void 0),Ro([Gg({type:VS})],HS.prototype,"privateKey",void 0),Ro([Gg({type:qS,implicit:!0,context:0,optional:!0})],HS.prototype,"attributes",void 0);var KS=class extends HS{};KS=Ro([Dg({type:Yy.Sequence})],KS);var WS,QS=class extends FS{};QS=Ro([Dg({type:Yy.Sequence})],QS);class YS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.secretTypeId="",this.secretValue=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:Jy.ObjectIdentifier})],YS.prototype,"secretTypeId",void 0),Ro([Gg({type:Jy.Any,context:0})],YS.prototype,"secretValue",void 0);class JS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.mac=new sS,this.macSalt=new Xy,this.iterations=1,Object.assign(this,e)}}Ro([Gg({type:sS})],JS.prototype,"mac",void 0),Ro([Gg({type:Xy})],JS.prototype,"macSalt",void 0),Ro([Gg({type:Jy.Integer,defaultValue:1})],JS.prototype,"iterations",void 0);class ZS{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=3,this.authSafe=new Nb,this.macData=new JS,Object.assign(this,e)}}Ro([Gg({type:Jy.Integer})],ZS.prototype,"version",void 0),Ro([Gg({type:Nb})],ZS.prototype,"authSafe",void 0),Ro([Gg({type:JS,optional:!0})],ZS.prototype,"macData",void 0);class $S{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.bagId="",this.bagValue=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:Jy.ObjectIdentifier})],$S.prototype,"bagId",void 0),Ro([Gg({type:Jy.Any,context:0})],$S.prototype,"bagValue",void 0),Ro([Gg({type:DS,repeated:"set",optional:!0})],$S.prototype,"bagAttributes",void 0);var XS,eP,tP,rP=WS=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,WS.prototype)}};rP=WS=Ro([Dg({type:Yy.Sequence,itemType:$S})],rP);var nP="1.2.840.113549.1.9",iP="".concat(nP,".7"),oP="".concat(nP,".14"),aP=class extends Ug{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{})}toString(){return this.ia5String||super.toString()}};Ro([Gg({type:Jy.IA5String})],aP.prototype,"ia5String",void 0),aP=Ro([Dg({type:Yy.Choice})],aP);var sP=class extends Nb{};sP=Ro([Dg({type:Yy.Sequence})],sP);var lP=class extends ZS{};lP=Ro([Dg({type:Yy.Sequence})],lP);var cP=class extends FS{};cP=Ro([Dg({type:Yy.Sequence})],cP);var uP=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.value=e}toString(){return this.value}};Ro([Gg({type:Jy.IA5String})],uP.prototype,"value",void 0),uP=Ro([Dg({type:Yy.Choice})],uP);var dP=class extends aP{};dP=Ro([Dg({type:Yy.Choice})],dP);var hP=class extends Ug{};hP=Ro([Dg({type:Yy.Choice})],hP);var pP=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:new Date;this.value=e}};Ro([Gg({type:Jy.GeneralizedTime})],pP.prototype,"value",void 0),pP=Ro([Dg({type:Yy.Choice})],pP);var fP=class extends Ug{};fP=Ro([Dg({type:Yy.Choice})],fP);var vP=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"M";this.value=e}toString(){return this.value}};Ro([Gg({type:Jy.PrintableString})],vP.prototype,"value",void 0),vP=Ro([Dg({type:Yy.Choice})],vP);var yP=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.value=e}toString(){return this.value}};Ro([Gg({type:Jy.PrintableString})],yP.prototype,"value",void 0),yP=Ro([Dg({type:Yy.Choice})],yP);var gP=class extends yP{};gP=Ro([Dg({type:Yy.Choice})],gP);var mP=class extends Ug{};mP=Ro([Dg({type:Yy.Choice})],mP);var wP=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.value=e}toString(){return this.value}};Ro([Gg({type:Jy.ObjectIdentifier})],wP.prototype,"value",void 0),wP=Ro([Dg({type:Yy.Choice})],wP);var bP=class extends Iw{};bP=Ro([Dg({type:Yy.Choice})],bP);var _P=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;this.value=e}toString(){return this.value.toString()}};Ro([Gg({type:Jy.Integer})],_P.prototype,"value",void 0),_P=Ro([Dg({type:Yy.Choice})],_P);var SP=class extends Jw{};SP=Ro([Dg({type:Yy.Sequence})],SP);var PP=class extends Ug{};PP=Ro([Dg({type:Yy.Choice})],PP);var EP=XS=class extends Dw{constructor(e){super(e),Object.setPrototypeOf(this,XS.prototype)}};EP=XS=Ro([Dg({type:Yy.Sequence})],EP);var AP=eP=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,eP.prototype)}};AP=eP=Ro([Dg({type:Yy.Set,itemType:Qw})],AP);var kP=class{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"";this.value=e}toString(){return this.value}};Ro([Gg({type:Jy.BmpString})],kP.prototype,"value",void 0),kP=Ro([Dg({type:Yy.Choice})],kP);var xP=class extends kw{};xP=Ro([Dg({type:Yy.Sequence})],xP);var TP,IP=tP=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,tP.prototype)}};IP=tP=Ro([Dg({type:Yy.Sequence,itemType:xP})],IP);var CP=TP=class extends Mg{constructor(e){super(e),Object.setPrototypeOf(this,TP.prototype)}};CP=TP=Ro([Dg({type:Yy.Sequence,itemType:vw})],CP);class BP{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.version=0,this.subject=new Kg,this.subjectPKInfo=new xw,this.attributes=new CP,Object.assign(this,e)}}Ro([Gg({type:Jy.Integer})],BP.prototype,"version",void 0),Ro([Gg({type:Kg})],BP.prototype,"subject",void 0),Ro([Gg({type:xw})],BP.prototype,"subjectPKInfo",void 0),Ro([Gg({type:CP,implicit:!0,context:0})],BP.prototype,"attributes",void 0);class NP{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};this.certificationRequestInfo=new BP,this.signatureAlgorithm=new kw,this.signature=new ArrayBuffer(0),Object.assign(this,e)}}Ro([Gg({type:BP})],NP.prototype,"certificationRequestInfo",void 0),Ro([Gg({type:kw})],NP.prototype,"signatureAlgorithm",void 0),Ro([Gg({type:Jy.BitString})],NP.prototype,"signature",void 0);var DP="crypto.algorithm";var GP,RP="crypto.algorithmProvider";BS.registerSingleton(RP,class{getAlgorithms(){return BS.resolveAll(DP)}toAsnAlgorithm(t){for(var r of(e._objectSpread2({},t),this.getAlgorithms())){var n=r.toAsnAlgorithm(t);if(n)return n}if(/^[0-9.]+$/.test(t.name)){var i=new kw({algorithm:t.name});if("parameters"in t){var o=t;i.parameters=o.parameters}return i}throw new Error("Cannot convert WebCrypto algorithm to ASN.1 algorithm")}toWebAlgorithm(e){for(var t of this.getAlgorithms()){var r=t.toWebAlgorithm(e);if(r)return r}return{name:e.algorithm,parameters:e.parameters}}});var OP="1.3.36.3.3.2.8.1.1",LP="".concat(OP,".1"),MP="".concat(OP,".2"),jP="".concat(OP,".3"),FP="".concat(OP,".4"),UP="".concat(OP,".5"),zP="".concat(OP,".6"),VP="".concat(OP,".7"),qP="".concat(OP,".8"),HP="".concat(OP,".9"),KP="".concat(OP,".10"),WP="".concat(OP,".11"),QP="".concat(OP,".12"),YP="".concat(OP,".13"),JP="".concat(OP,".14"),ZP="brainpoolP160r1",$P="brainpoolP160t1",XP="brainpoolP192r1",eE="brainpoolP192t1",tE="brainpoolP224r1",rE="brainpoolP224t1",nE="brainpoolP256r1",iE="brainpoolP256t1",oE="brainpoolP320r1",aE="brainpoolP320t1",sE="brainpoolP384r1",lE="brainpoolP384t1",cE="brainpoolP512r1",uE="brainpoolP512t1",dE="ECDSA",hE=GP=class{toAsnAlgorithm(e){if(e.name.toLowerCase()===dE.toLowerCase())if("hash"in e)switch(("string"==typeof e.hash?e.hash:e.hash.name).toLowerCase()){case"sha-1":return P_;case"sha-256":return E_;case"sha-384":return A_;case"sha-512":return k_}else if("namedCurve"in e){var t="";switch(e.namedCurve){case"P-256":t=w_;break;case"K-256":t=GP.SECP256K1;break;case"P-384":t=b_;break;case"P-521":t=__;break;case ZP:t=LP;break;case $P:t=MP;break;case XP:t=jP;break;case eE:t=FP;break;case tE:t=UP;break;case rE:t=zP;break;case nE:t=VP;break;case iE:t=qP;break;case oE:t=HP;break;case aE:t=KP;break;case sE:t=WP;break;case lE:t=QP;break;case cE:t=YP;break;case uE:t=JP}if(t)return new kw({algorithm:p_,parameters:jg.serialize(new B_({namedCurve:t}))})}return null}toWebAlgorithm(e){switch(e.algorithm){case f_:return{name:dE,hash:{name:"SHA-1"}};case y_:return{name:dE,hash:{name:"SHA-256"}};case g_:return{name:dE,hash:{name:"SHA-384"}};case m_:return{name:dE,hash:{name:"SHA-512"}};case p_:if(!e.parameters)throw new TypeError("Cannot get required parameters from EC algorithm");switch(jg.parse(e.parameters,B_).namedCurve){case w_:return{name:dE,namedCurve:"P-256"};case GP.SECP256K1:return{name:dE,namedCurve:"K-256"};case b_:return{name:dE,namedCurve:"P-384"};case __:return{name:dE,namedCurve:"P-521"};case LP:return{name:dE,namedCurve:ZP};case MP:return{name:dE,namedCurve:$P};case jP:return{name:dE,namedCurve:XP};case FP:return{name:dE,namedCurve:eE};case UP:return{name:dE,namedCurve:tE};case zP:return{name:dE,namedCurve:rE};case VP:return{name:dE,namedCurve:nE};case qP:return{name:dE,namedCurve:iE};case HP:return{name:dE,namedCurve:oE};case KP:return{name:dE,namedCurve:aE};case WP:return{name:dE,namedCurve:sE};case QP:return{name:dE,namedCurve:lE};case YP:return{name:dE,namedCurve:cE};case JP:return{name:dE,namedCurve:uE}}}return null}};hE.SECP256K1="1.3.132.0.10",hE=GP=Ro([NS()],hE),BS.registerSingleton(DP,hE);var pE,fE=Symbol("name"),vE=Symbol("value");class yE{constructor(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"";for(var n in this[fE]=e,this[vE]=r,t)this[n]=t[n]}}yE.NAME=fE,yE.VALUE=vE;class gE{static toString(e){var t=this.items[e];return t||e}}gE.items={[Q_]:"sha1",[Y_]:"sha224",[J_]:"sha256",[Z_]:"sha384",[$_]:"sha512",[R_]:"rsaEncryption",[U_]:"sha1WithRSAEncryption",[z_]:"sha224WithRSAEncryption",[V_]:"sha256WithRSAEncryption",[q_]:"sha384WithRSAEncryption",[H_]:"sha512WithRSAEncryption",[p_]:"ecPublicKey",[f_]:"ecdsaWithSHA1",[v_]:"ecdsaWithSHA224",[y_]:"ecdsaWithSHA256",[g_]:"ecdsaWithSHA384",[m_]:"ecdsaWithSHA512",[Hm]:"TLS WWW server authentication",[Km]:"TLS WWW client authentication",[Wm]:"Code Signing",[Qm]:"E-mail Protection",[Ym]:"Time Stamping",[Jm]:"OCSP Signing",[u_]:"Signed Data"};class mE{static serialize(e){return this.serializeObj(e).join("\n")}static pad(){return"".padStart(2*(arguments.length>0&&void 0!==arguments[0]?arguments[0]:0)," ")}static serializeObj(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=[],n=this.pad(t++),i="",o=e[yE.VALUE];for(var a in o&&(i=" ".concat(o)),r.push("".concat(n).concat(e[yE.NAME],":").concat(i)),n=this.pad(t),e)if("symbol"!=typeof a){var s=e[a],l=a?"".concat(a,": "):"";if("string"==typeof s||"number"==typeof s||"boolean"==typeof s)r.push("".concat(n).concat(l).concat(s));else if(s instanceof Date)r.push("".concat(n).concat(l).concat(s.toUTCString()));else if(Array.isArray(s))for(var c of s)c[yE.NAME]=a,r.push(...this.serializeObj(c,t));else if(s instanceof yE)s[yE.NAME]=a,r.push(...this.serializeObj(s,t));else if(wf.BufferSourceConverter.isBufferSource(s))a?(r.push("".concat(n).concat(l)),r.push(...this.serializeBufferSource(s,t+1))):r.push(...this.serializeBufferSource(s,t));else{if(!("toTextObject"in s))throw new TypeError("Cannot serialize data in text format. Unsupported type.");var u=s.toTextObject();u[yE.NAME]=a,r.push(...this.serializeObj(u,t))}}return r}static serializeBufferSource(e){for(var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=this.pad(t),n=wf.BufferSourceConverter.toUint8Array(e),i=[],o=0;o<n.length;){for(var a=[],s=0;s<16&&o<n.length;s++){8===s&&a.push("");var l=n[o++].toString(16).padStart(2,"0");a.push(l)}i.push("".concat(r).concat(a.join(" ")))}return i}static serializeAlgorithm(e){return this.algorithmSerializer.toTextObject(e)}}mE.oidSerializer=gE,mE.algorithmSerializer=class{static toTextObject(e){var t=new yE("Algorithm Identifier",{},gE.toString(e.algorithm));if(e.parameters)if(e.algorithm===p_){var r=(new hE).toWebAlgorithm(e);r&&"namedCurve"in r?t["Named Curve"]=r.namedCurve:t.Parameters=e.parameters}else t.Parameters=e.parameters;return t}};class wE{constructor(){if(1===arguments.length){var e=arguments.length<=0?void 0:arguments[0];this.rawData=jg.serialize(e),this.onInit(e)}else{var t=jg.parse(arguments.length<=0?void 0:arguments[0],arguments.length<=1?void 0:arguments[1]);this.rawData=wf.BufferSourceConverter.toArrayBuffer(arguments.length<=0?void 0:arguments[0]),this.onInit(t)}}equal(e){return e instanceof wE&&wf.isEqual(e.rawData,this.rawData)}toString(){switch(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"text"){case"asn":return jg.toString(this.rawData);case"text":return mE.serialize(this.toTextObject());case"hex":return wf.Convert.ToHex(this.rawData);case"base64":return wf.Convert.ToBase64(this.rawData);case"base64url":return wf.Convert.ToBase64Url(this.rawData);default:throw TypeError("Argument 'format' is unsupported value")}}getTextName(){return this.constructor.NAME}toTextObject(){var e=this.toTextObjectEmpty();return e[""]=this.rawData,e}toTextObjectEmpty(e){return new yE(this.getTextName(),{},e)}}wE.NAME="ASN";class bE extends wE{constructor(){super(wf.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])?wf.BufferSourceConverter.toArrayBuffer(arguments.length<=0?void 0:arguments[0]):jg.serialize(new Bw({extnID:arguments.length<=0?void 0:arguments[0],critical:arguments.length<=1?void 0:arguments[1],extnValue:new Xy(wf.BufferSourceConverter.toArrayBuffer(arguments.length<=2?void 0:arguments[2]))})),Bw)}onInit(e){this.type=e.extnID,this.critical=e.critical,this.value=e.extnValue.buffer}toTextObject(){var e=this.toTextObjectWithoutValue();return e[""]=this.value,e}toTextObjectWithoutValue(){var e=this.toTextObjectEmpty(this.critical?"critical":void 0);return e[yE.NAME]===bE.NAME&&(e[yE.NAME]=gE.toString(this.type)),e}}class _E{static isCryptoKeyPair(e){return e&&e.privateKey&&e.publicKey}static isCryptoKey(e){return e&&e.usages&&e.type&&e.algorithm&&void 0!==e.extractable}constructor(){this.items=new Map,this[pE]="CryptoProvider","undefined"!=typeof self&&"undefined"!=typeof crypto?this.set(_E.DEFAULT,crypto):"undefined"!=typeof global&&global.crypto&&global.crypto.subtle&&this.set(_E.DEFAULT,global.crypto)}clear(){this.items.clear()}delete(e){return this.items.delete(e)}forEach(e,t){return this.items.forEach(e,t)}has(e){return this.items.has(e)}get size(){return this.items.size}entries(){return this.items.entries()}keys(){return this.items.keys()}values(){return this.items.values()}[Symbol.iterator](){return this.items[Symbol.iterator]()}get(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:_E.DEFAULT,t=this.items.get(e.toLowerCase());if(!t)throw new Error("Cannot get Crypto by name '".concat(e,"'"));return t}set(e,t){if("string"==typeof e){if(!t)throw new TypeError("Argument 'value' is required");this.items.set(e.toLowerCase(),t)}else this.items.set(_E.DEFAULT,e);return this}}pE=Symbol.toStringTag,_E.DEFAULT="default";var SE=new _E,PE=/^[0-2](?:\.[1-9][0-9]*)+$/;class EE{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};for(var t in this.items={},e)this.register(t,e[t])}get(e){return this.items[e]||null}findId(e){return t=e,new RegExp(PE).test(t)?e:this.get(e);var t}register(e,t){this.items[e]=t,this.items[t]=e}}var AE=new EE;function kE(e,t){return"\\".concat(wf.Convert.ToHex(wf.Convert.FromUtf8String(t)).toUpperCase())}AE.register("CN","2.5.4.3"),AE.register("L","2.5.4.7"),AE.register("ST","2.5.4.8"),AE.register("O","2.5.4.10"),AE.register("OU","2.5.4.11"),AE.register("C","2.5.4.6"),AE.register("DC","0.9.2342.19200300.100.1.25"),AE.register("E","1.2.840.113549.1.9.1"),AE.register("G","2.5.4.42"),AE.register("I","2.5.4.43"),AE.register("SN","2.5.4.4"),AE.register("T","2.5.4.12");class xE{static isASCII(e){for(var t=0;t<e.length;t++){if(e.charCodeAt(t)>255)return!1}return!0}static isPrintableString(e){return/^[A-Za-z0-9 '()+,-./:=?]*$/g.test(e)}constructor(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};for(var r in this.extraNames=new EE,this.asn=new Kg,t)if(Object.prototype.hasOwnProperty.call(t,r)){var n=t[r];this.extraNames.register(r,n)}"string"==typeof e?this.asn=this.fromString(e):e instanceof Kg?this.asn=e:wf.BufferSourceConverter.isBufferSource(e)?this.asn=jg.parse(e,Kg):this.asn=this.fromJSON(e)}getField(e){var t=this.extraNames.findId(e)||AE.findId(e),r=[];for(var n of this.asn)for(var i of n)i.type===t&&r.push(i.value.toString());return r}getName(e){return this.extraNames.get(e)||AE.get(e)}toString(){return this.asn.map((e=>e.map((e=>{var t=this.getName(e.type)||e.type,r=e.value.anyValue?"#".concat(wf.Convert.ToHex(e.value.anyValue)):e.value.toString().replace(/([,+"\\<>;])/g,"\\$1").replace(/^([ #])/,"\\$1").replace(/([ ]$)/,"\\$1").replace(/([\r\n\t])/,kE);return"".concat(t,"=").concat(r)})).join("+"))).join(", ")}toJSON(){var e,t=[];for(var r of this.asn){var n={};for(var i of r){var o=this.getName(i.type)||i.type;null!==(e=n[o])&&void 0!==e||(n[o]=[]),n[o].push(i.value.anyValue?"#".concat(wf.Convert.ToHex(i.value.anyValue)):i.value.toString())}t.push(n)}return t}fromString(e){for(var t=new Kg,r=/(\d\.[\d.]*\d|[A-Za-z]+)=((?:"")|(?:".*?[^\\]")|(?:[^,+].*?(?:[^\\][,+]))|(?:))([,+])?/g,n=null,i=",";n=r.exec("".concat(e,","));){var[,o,a]=n,s=a[a.length-1];","!==s&&"+"!==s||(a=a.slice(0,a.length-1),n[3]=s);var l=n[3];o=this.getTypeOid(o);var c=this.createAttribute(o,a);"+"===i?t[t.length-1].push(c):t.push(new qg([c])),i=l}return t}fromJSON(e){var t=new Kg;for(var r of e){var n=new qg;for(var i in r){var o=this.getTypeOid(i),a=r[i];for(var s of a){var l=this.createAttribute(o,s);n.push(l)}}t.push(n)}return t}getTypeOid(e){if(/[\d.]+/.test(e)||(e=this.getName(e)||""),!e)throw new Error("Cannot get OID for name type '".concat(e,"'"));return e}createAttribute(e,t){var r=new Vg({type:e});if("object"==typeof t)for(var n in t)switch(n){case"ia5String":r.value.ia5String=t[n];break;case"utf8String":r.value.utf8String=t[n];break;case"universalString":r.value.universalString=t[n];break;case"bmpString":r.value.bmpString=t[n];break;case"printableString":r.value.printableString=t[n]}else if("#"===t[0])r.value.anyValue=wf.Convert.FromHex(t.slice(1));else{var i=this.processStringValue(t);e===this.getName("E")||e===this.getName("DC")?r.value.ia5String=i:xE.isPrintableString(i)?r.value.printableString=i:r.value.utf8String=i}return r}processStringValue(e){var t=/"(.*?[^\\])?"/.exec(e);return t&&(e=t[1]),e.replace(/\\0a/gi,"\n").replace(/\\0d/gi,"\r").replace(/\\0g/gi,"\t").replace(/\\(.)/g,"$1")}toArrayBuffer(){return jg.serialize(this.asn)}getThumbprint(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var e,n,i="SHA-1";return t.length>=1&&!(null===(e=t.length<=0?void 0:t[0])||void 0===e?void 0:e.subtle)?(i=(t.length<=0?void 0:t[0])||i,n=(t.length<=1?void 0:t[1])||SE.get()):n=(t.length<=0?void 0:t[0])||SE.get(),yield n.subtle.digest(i,r.toArrayBuffer())}))()}}var TE="Cannot initialize GeneralName from ASN.1 data.",IE="".concat(TE," Unsupported string format in use."),CE="".concat(TE," Value doesn't match to GUID regular expression."),BE=/^([0-9a-f]{8})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{4})-?([0-9a-f]{12})$/i,NE="1.3.6.1.4.1.311.25.1",DE="1.3.6.1.4.1.311.20.2.3",GE="dns",RE="dn",OE="email",LE="ip",ME="url",jE="guid",FE="upn",UE="id";class zE extends wE{constructor(){var e;if(2===arguments.length)switch(arguments.length<=0?void 0:arguments[0]){case RE:var t=new xE(arguments.length<=1?void 0:arguments[1]).toArrayBuffer(),r=jg.parse(t,Kg);e=new Jg({directoryName:r});break;case GE:e=new Jg({dNSName:arguments.length<=1?void 0:arguments[1]});break;case OE:e=new Jg({rfc822Name:arguments.length<=1?void 0:arguments[1]});break;case jE:var n=new RegExp(BE,"i").exec(arguments.length<=1?void 0:arguments[1]);if(!n)throw new Error("Cannot parse GUID value. Value doesn't match to regular expression");var i=n.slice(1).map(((e,t)=>t<3?wf.Convert.ToHex(new Uint8Array(wf.Convert.FromHex(e)).reverse()):e)).join("");e=new Jg({otherName:new Qg({typeId:NE,value:jg.serialize(new Xy(wf.Convert.FromHex(i)))})});break;case LE:e=new Jg({iPAddress:arguments.length<=1?void 0:arguments[1]});break;case UE:e=new Jg({registeredID:arguments.length<=1?void 0:arguments[1]});break;case FE:e=new Jg({otherName:new Qg({typeId:DE,value:jg.serialize(ug.toASN(arguments.length<=1?void 0:arguments[1]))})});break;case ME:e=new Jg({uniformResourceIdentifier:arguments.length<=1?void 0:arguments[1]});break;default:throw new Error("Cannot create GeneralName. Unsupported type of the name")}else e=wf.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])?jg.parse(arguments.length<=0?void 0:arguments[0],Jg):arguments.length<=0?void 0:arguments[0];super(e)}onInit(e){if(null!=e.dNSName)this.type=GE,this.value=e.dNSName;else if(null!=e.rfc822Name)this.type=OE,this.value=e.rfc822Name;else if(null!=e.iPAddress)this.type=LE,this.value=e.iPAddress;else if(null!=e.uniformResourceIdentifier)this.type=ME,this.value=e.uniformResourceIdentifier;else if(null!=e.registeredID)this.type=UE,this.value=e.registeredID;else if(null!=e.directoryName)this.type=RE,this.value=new xE(e.directoryName).toString();else{if(null==e.otherName)throw new Error(IE);if(e.otherName.typeId===NE){this.type=jE;var t=jg.parse(e.otherName.value,Xy),r=new RegExp(BE,"i").exec(wf.Convert.ToHex(t));if(!r)throw new Error(CE);this.value=r.slice(1).map(((e,t)=>t<3?wf.Convert.ToHex(new Uint8Array(wf.Convert.FromHex(e)).reverse()):e)).join("-")}else{if(e.otherName.typeId!==DE)throw new Error(IE);this.type=FE,this.value=jg.parse(e.otherName.value,Ug).toString()}}}toJSON(){return{type:this.type,value:this.value}}toTextObject(){var e;switch(this.type){case RE:case GE:case jE:case LE:case UE:case FE:case ME:e=this.type.toUpperCase();break;case OE:e="Email";break;default:throw new Error("Unsupported GeneralName type")}var t=this.value;return this.type===UE&&(t=gE.toString(t)),new yE(e,void 0,t)}}class VE extends wE{constructor(e){var t;if(e instanceof gm)t=e;else if(Array.isArray(e)){var r=[];for(var n of e)if(n instanceof Jg)r.push(n);else{var i=jg.parse(new zE(n.type,n.value).rawData,Jg);r.push(i)}t=new gm(r)}else{if(!wf.BufferSourceConverter.isBufferSource(e))throw new Error("Cannot initialize GeneralNames. Incorrect incoming arguments");t=jg.parse(e,gm)}super(t)}onInit(e){var t=[];for(var r of e){var n=null;try{n=new zE(r)}catch(e){continue}t.push(n)}this.items=t}toJSON(){return this.items.map((e=>e.toJSON()))}toTextObject(){var e=super.toTextObjectEmpty();for(var t of this.items){var r=t.toTextObject(),n=e[r[yE.NAME]];Array.isArray(n)||(n=[],e[r[yE.NAME]]=n),n.push(r)}return e}}VE.NAME="GeneralNames";var qE,HE,KE="-{5}",WE="\\n",QE="[^".concat(WE,"]+"),YE="".concat(KE,"BEGIN (").concat(QE,"(?=").concat(KE,"))").concat(KE),JE="".concat(KE,"END \\1").concat(KE),ZE="\\n",$E="[^:".concat(WE,"]+"),XE="(?:[^".concat(WE,"]+").concat(ZE,"(?: +[^").concat(WE,"]+").concat(ZE,")*)"),eA="(?:".concat("[a-zA-Z0-9=+/]+").concat(ZE,")+"),tA="".concat(YE).concat(ZE,"(?:((?:").concat($E,": ").concat(XE,")+))?").concat(ZE,"?(").concat(eA,")").concat(JE);class rA{static isPem(e){return"string"==typeof e&&new RegExp(tA,"g").test(e)}static decodeWithHeaders(e){e=e.replace(/\r/g,"");for(var t=new RegExp(tA,"g"),r=[],n=null;n=t.exec(e);){var i=n[3].replace(new RegExp("[".concat(WE,"]+"),"g"),""),o={type:n[1],headers:[],rawData:wf.Convert.FromBase64(i)},a=n[2];if(a){var s=a.split(new RegExp(ZE,"g")),l=null;for(var c of s){var[u,d]=c.split(/:(.*)/);if(void 0===d){if(!l)throw new Error("Cannot parse PEM string. Incorrect header value");l.value+=u.trim()}else l&&o.headers.push(l),l={key:u,value:d.trim()}}l&&o.headers.push(l)}r.push(o)}return r}static decode(e){return this.decodeWithHeaders(e).map((e=>e.rawData))}static decodeFirst(e){var t=this.decode(e);if(!t.length)throw new RangeError("PEM string doesn't contain any objects");return t[0]}static encode(e,t){if(Array.isArray(e)){var r=new Array;return t?e.forEach((e=>{if(!wf.BufferSourceConverter.isBufferSource(e))throw new TypeError("Cannot encode array of BufferSource in PEM format. Not all items of the array are BufferSource");r.push(this.encodeStruct({type:t,rawData:wf.BufferSourceConverter.toArrayBuffer(e)}))})):e.forEach((e=>{if(!("type"in e))throw new TypeError("Cannot encode array of PemStruct in PEM format. Not all items of the array are PemStrut");r.push(this.encodeStruct(e))})),r.join("\n")}if(!t)throw new Error("Required argument 'tag' is missed");return this.encodeStruct({type:t,rawData:wf.BufferSourceConverter.toArrayBuffer(e)})}static encodeStruct(e){var t,r=e.type.toLocaleUpperCase(),n=[];if(n.push("-----BEGIN ".concat(r,"-----")),null===(t=e.headers)||void 0===t?void 0:t.length){for(var i of e.headers)n.push("".concat(i.key,": ").concat(i.value));n.push("")}for(var o,a=wf.Convert.ToBase64(e.rawData),s=0,l=Array();s<a.length&&(a.length-s<64?o=a.substring(s):(o=a.substring(s,s+64),s+=64),0!==o.length)&&(l.push(o),!(o.length<64)););return n.push(...l),n.push("-----END ".concat(r,"-----")),n.join("\n")}}rA.CertificateTag="CERTIFICATE",rA.CrlTag="CRL",rA.CertificateRequestTag="CERTIFICATE REQUEST",rA.PublicKeyTag="PUBLIC KEY",rA.PrivateKeyTag="PRIVATE KEY";class nA extends wE{static isAsnEncoded(e){return wf.BufferSourceConverter.isBufferSource(e)||"string"==typeof e}static toArrayBuffer(e){if("string"==typeof e){if(rA.isPem(e))return rA.decode(e)[0];if(wf.Convert.isHex(e))return wf.Convert.FromHex(e);if(wf.Convert.isBase64(e))return wf.Convert.FromBase64(e);if(wf.Convert.isBase64Url(e))return wf.Convert.FromBase64Url(e);throw new TypeError("Unsupported format of 'raw' argument. Must be one of DER, PEM, HEX, Base64, or Base4Url")}var t=wf.Convert.ToBinary(e);return rA.isPem(t)?rA.decode(t)[0]:wf.Convert.isHex(t)?wf.Convert.FromHex(t):wf.Convert.isBase64(t)?wf.Convert.FromBase64(t):wf.Convert.isBase64Url(t)?wf.Convert.FromBase64Url(t):wf.BufferSourceConverter.toArrayBuffer(e)}constructor(){nA.isAsnEncoded(arguments.length<=0?void 0:arguments[0])?super(nA.toArrayBuffer(arguments.length<=0?void 0:arguments[0]),arguments.length<=1?void 0:arguments[1]):super(arguments.length<=0?void 0:arguments[0])}toString(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"pem";return"pem"===e?rA.encode(this.rawData,this.tag):super.toString(e)}}class iA extends nA{static create(t){var r=arguments;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:SE.get();if(t instanceof iA)return t;if(_E.isCryptoKey(t)){if("public"!==t.type)throw new TypeError("Public key is required");var n=yield e.subtle.exportKey("spki",t);return new iA(n)}if(t.publicKey)return t.publicKey;if(wf.BufferSourceConverter.isBufferSource(t))return new iA(t);throw new TypeError("Unsupported PublicKeyType")}))()}constructor(e){nA.isAsnEncoded(e)?super(e,xw):super(e),this.tag=rA.PublicKeyTag}export(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var n,i=["verify"],o=e._objectSpread2({hash:"SHA-256"},r.algorithm);t.length>1?(o=(t.length<=0?void 0:t[0])||o,i=(t.length<=1?void 0:t[1])||i,n=(t.length<=2?void 0:t[2])||SE.get()):n=(t.length<=0?void 0:t[0])||SE.get();var a=r.rawData,s=jg.parse(r.rawData,xw);return s.algorithm.algorithm===M_&&(a=function(e,t){return e.algorithm=new kw({algorithm:R_,parameters:null}),t=jg.serialize(e),t}(s,a)),n.subtle.importKey("spki",a,o,!0,i)}))()}onInit(e){var t=BS.resolve(RP),r=this.algorithm=t.toWebAlgorithm(e.algorithm);if(e.algorithm.algorithm===R_){var n=jg.parse(e.subjectPublicKey,hS),i=wf.BufferSourceConverter.toUint8Array(n.modulus);r.publicExponent=wf.BufferSourceConverter.toUint8Array(n.publicExponent),r.modulusLength=(i[0]?i:i.slice(1)).byteLength<<3}}getThumbprint(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var e,n,i="SHA-1";return t.length>=1&&!(null===(e=t.length<=0?void 0:t[0])||void 0===e?void 0:e.subtle)?(i=(t.length<=0?void 0:t[0])||i,n=(t.length<=1?void 0:t[1])||SE.get()):n=(t.length<=0?void 0:t[0])||SE.get(),yield n.subtle.digest(i,r.rawData)}))()}getKeyIdentifier(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var e,n="SHA-1";1===t.length?"string"==typeof(t.length<=0?void 0:t[0])?(n=t.length<=0?void 0:t[0],e=SE.get()):e=t.length<=0?void 0:t[0]:2===t.length?(n=t.length<=0?void 0:t[0],e=t.length<=1?void 0:t[1]):e=SE.get();var i=jg.parse(r.rawData,xw);return yield e.subtle.digest(n,i.subjectPublicKey)}))()}toTextObject(){var e=this.toTextObjectEmpty(),t=jg.parse(this.rawData,xw);if(e.Algorithm=mE.serializeAlgorithm(t.algorithm),t.algorithm.algorithm===p_)e["EC Point"]=t.subjectPublicKey;else e["Raw Data"]=t.subjectPublicKey;return e}}class oA extends bE{static create(t){var r=arguments;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]&&r[1],n=r.length>2&&void 0!==r[2]?r[2]:SE.get();if("name"in t&&"serialNumber"in t)return new oA(t,e);var i=yield iA.create(t,n),o=yield i.getKeyIdentifier(n);return new oA(wf.Convert.ToHex(o),e)}))()}constructor(){if(wf.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0]))super(arguments.length<=0?void 0:arguments[0]);else if("string"==typeof(arguments.length<=0?void 0:arguments[0])){var e=new hm({keyIdentifier:new dm(wf.Convert.FromHex(arguments.length<=0?void 0:arguments[0]))});super(um,arguments.length<=1?void 0:arguments[1],jg.serialize(e))}else{var t=arguments.length<=0?void 0:arguments[0],r=t.name instanceof VE?jg.parse(t.name.rawData,gm):t.name,n=new hm({authorityCertIssuer:r,authorityCertSerialNumber:wf.Convert.FromHex(t.serialNumber)});super(um,arguments.length<=1?void 0:arguments[1],jg.serialize(n))}}onInit(e){super.onInit(e);var t=jg.parse(e.extnValue,hm);t.keyIdentifier&&(this.keyId=wf.Convert.ToHex(t.keyIdentifier)),(t.authorityCertIssuer||t.authorityCertSerialNumber)&&(this.certId={name:t.authorityCertIssuer||[],serialNumber:t.authorityCertSerialNumber?wf.Convert.ToHex(t.authorityCertSerialNumber):""})}toTextObject(){var e=this.toTextObjectWithoutValue(),t=jg.parse(this.value,hm);return t.authorityCertIssuer&&(e["Authority Issuer"]=new VE(t.authorityCertIssuer).toTextObject()),t.authorityCertSerialNumber&&(e["Authority Serial Number"]=t.authorityCertSerialNumber),t.keyIdentifier&&(e[""]=t.keyIdentifier),e}}oA.NAME="Authority Key Identifier";class aA extends bE{constructor(){if(wf.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])){super(arguments.length<=0?void 0:arguments[0]);var e=jg.parse(this.value,vm);this.ca=e.cA,this.pathLength=e.pathLenConstraint}else{var t=new vm({cA:arguments.length<=0?void 0:arguments[0],pathLenConstraint:arguments.length<=1?void 0:arguments[1]});super(fm,arguments.length<=2?void 0:arguments[2],jg.serialize(t)),this.ca=arguments.length<=0?void 0:arguments[0],this.pathLength=arguments.length<=1?void 0:arguments[1]}}toTextObject(){var e=this.toTextObjectWithoutValue();return this.ca&&(e.CA=this.ca),void 0!==this.pathLength&&(e["Path Length"]=this.pathLength),e}}aA.NAME="Basic Constraints",function(e){e.serverAuth="1.3.6.1.5.5.7.3.1",e.clientAuth="1.3.6.1.5.5.7.3.2",e.codeSigning="1.3.6.1.5.5.7.3.3",e.emailProtection="1.3.6.1.5.5.7.3.4",e.timeStamping="1.3.6.1.5.5.7.3.8",e.ocspSigning="1.3.6.1.5.5.7.3.9"}(qE||(qE={}));class sA extends bE{constructor(){if(wf.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])){super(arguments.length<=0?void 0:arguments[0]);var e=jg.parse(this.value,qm);this.usages=e.map((e=>e))}else{var t=new qm(arguments.length<=0?void 0:arguments[0]);super(Vm,arguments.length<=1?void 0:arguments[1],jg.serialize(t)),this.usages=arguments.length<=0?void 0:arguments[0]}}toTextObject(){var e=this.toTextObjectWithoutValue();return e[""]=this.usages.map((e=>gE.toString(e))).join(", "),e}}sA.NAME="Extended Key Usages",function(e){e[e.digitalSignature=1]="digitalSignature",e[e.nonRepudiation=2]="nonRepudiation",e[e.keyEncipherment=4]="keyEncipherment",e[e.dataEncipherment=8]="dataEncipherment",e[e.keyAgreement=16]="keyAgreement",e[e.keyCertSign=32]="keyCertSign",e[e.cRLSign=64]="cRLSign",e[e.encipherOnly=128]="encipherOnly",e[e.decipherOnly=256]="decipherOnly"}(HE||(HE={}));class lA extends bE{constructor(){if(wf.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])){super(arguments.length<=0?void 0:arguments[0]);var e=jg.parse(this.value,iw);this.usages=e.toNumber()}else{var t=new iw(arguments.length<=0?void 0:arguments[0]);super(nw,arguments.length<=1?void 0:arguments[1],jg.serialize(t)),this.usages=arguments.length<=0?void 0:arguments[0]}}toTextObject(){var e=this.toTextObjectWithoutValue(),t=jg.parse(this.value,iw);return e[""]=t.toJSON().join(", "),e}}lA.NAME="Key Usages";class cA extends bE{static create(t){var r=arguments;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]&&r[1],n=r.length>2&&void 0!==r[2]?r[2]:SE.get(),i=yield iA.create(t,n),o=yield i.getKeyIdentifier(n);return new cA(wf.Convert.ToHex(o),e)}))()}constructor(){if(wf.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])){super(arguments.length<=0?void 0:arguments[0]);var e=jg.parse(this.value,_w);this.keyId=wf.Convert.ToHex(e)}else{var t="string"==typeof(arguments.length<=0?void 0:arguments[0])?wf.Convert.FromHex(arguments.length<=0?void 0:arguments[0]):arguments.length<=0?void 0:arguments[0],r=new _w(t);super(bw,arguments.length<=1?void 0:arguments[1],jg.serialize(r)),this.keyId=wf.Convert.ToHex(t)}}toTextObject(){var e=this.toTextObjectWithoutValue(),t=jg.parse(this.value,_w);return e[""]=t,e}}cA.NAME="Subject Key Identifier";class uA extends bE{constructor(){wf.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])?super(arguments.length<=0?void 0:arguments[0]):super(pw,arguments.length<=1?void 0:arguments[1],new VE((arguments.length<=0?void 0:arguments[0])||[]).rawData)}onInit(e){super.onInit(e);var t=jg.parse(e.extnValue,fw);this.names=new VE(t)}toTextObject(){var e=this.toTextObjectWithoutValue(),t=this.names.toTextObject();for(var r in t)e[r]=t[r];return e}}uA.NAME="Subject Alternative Name";class dA{static register(e,t){this.items.set(e,t)}static create(e){var t=new bE(e),r=this.items.get(t.type);return r?new r(e):t}}dA.items=new Map;class hA extends bE{constructor(){var e;if(wf.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0])){super(arguments.length<=0?void 0:arguments[0]);var t=jg.parse(this.value,xm);this.policies=t.map((e=>e.policyIdentifier))}else{var r=arguments.length<=0?void 0:arguments[0],n=null!==(e=arguments.length<=1?void 0:arguments[1])&&void 0!==e&&e,i=new xm(r.map((e=>new km({policyIdentifier:e}))));super(bm,n,jg.serialize(i)),this.policies=r}}toTextObject(){var e=this.toTextObjectWithoutValue();return e.Policy=this.policies.map((e=>new yE("",{},gE.toString(e)))),e}}hA.NAME="Certificate Policies",dA.register(bm,hA);class pA extends bE{constructor(){for(var e,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];if(wf.BufferSourceConverter.isBufferSource(r[0]))super(r[0]);else if(Array.isArray(r[0])&&"string"==typeof r[0][0]){var i=r[0].map((e=>new Rm({distributionPoint:new Gm({fullName:[new Jg({uniformResourceIdentifier:e})]})}))),o=new Lm(i);super(Nm,r[1],jg.serialize(o))}else{var a=new Lm(r[0]);super(Nm,r[1],jg.serialize(a))}null!==(e=this.distributionPoints)&&void 0!==e||(this.distributionPoints=[])}onInit(e){super.onInit(e);var t=jg.parse(e.extnValue,Lm);this.distributionPoints=t}toTextObject(){var e=this.toTextObjectWithoutValue();return e["Distribution Point"]=this.distributionPoints.map((e=>{var t,r={};return e.distributionPoint&&(r[""]=null===(t=e.distributionPoint.fullName)||void 0===t?void 0:t.map((e=>new zE(e).toString())).join(", ")),e.reasons&&(r.Reasons=e.reasons.toString()),e.cRLIssuer&&(r["CRL Issuer"]=e.cRLIssuer.map((e=>e.toString())).join(", ")),r})),e}}pA.NAME="CRL Distribution Points";class fA extends bE{constructor(){var e,t,r,n;if(wf.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0]))super(arguments.length<=0?void 0:arguments[0]);else if((arguments.length<=0?void 0:arguments[0])instanceof cm){var i=new cm(arguments.length<=0?void 0:arguments[0]);super(sm,arguments.length<=1?void 0:arguments[1],jg.serialize(i))}else{var o=arguments.length<=0?void 0:arguments[0],a=new cm;yA(a,o,rm,"ocsp"),yA(a,o,nm,"caIssuers"),yA(a,o,im,"timeStamping"),yA(a,o,om,"caRepository"),super(sm,arguments.length<=1?void 0:arguments[1],jg.serialize(a))}null!==(e=this.ocsp)&&void 0!==e||(this.ocsp=[]),null!==(t=this.caIssuers)&&void 0!==t||(this.caIssuers=[]),null!==(r=this.timeStamping)&&void 0!==r||(this.timeStamping=[]),null!==(n=this.caRepository)&&void 0!==n||(this.caRepository=[])}onInit(e){super.onInit(e),this.ocsp=[],this.caIssuers=[],this.timeStamping=[],this.caRepository=[],jg.parse(e.extnValue,cm).forEach((e=>{switch(e.accessMethod){case rm:this.ocsp.push(new zE(e.accessLocation));break;case nm:this.caIssuers.push(new zE(e.accessLocation));break;case im:this.timeStamping.push(new zE(e.accessLocation));break;case om:this.caRepository.push(new zE(e.accessLocation))}}))}toTextObject(){var e=this.toTextObjectWithoutValue();return this.ocsp.length&&vA(e,"OCSP",this.ocsp),this.caIssuers.length&&vA(e,"CA Issuers",this.caIssuers),this.timeStamping.length&&vA(e,"Time Stamping",this.timeStamping),this.caRepository.length&&vA(e,"CA Repository",this.caRepository),e}}function vA(e,t,r){if(1===r.length)e[t]=r[0].toTextObject();else{var n=new yE("");r.forEach(((e,t)=>{var r=e.toTextObject(),i="".concat(r[yE.NAME]," ").concat(t+1),o=n[i];Array.isArray(o)||(o=[],n[i]=o),o.push(r)})),e[t]=n}}function yA(e,t,r,n){var i=t[n];i&&(Array.isArray(i)?i:[i]).forEach((t=>{"string"==typeof t&&(t=new zE("url",t)),e.push(new lm({accessMethod:r,accessLocation:jg.parse(t.rawData,Jg)}))}))}fA.NAME="Authority Info Access";class gA extends wE{constructor(){for(var e,t=arguments.length,r=new Array(t),n=0;n<t;n++)r[n]=arguments[n];if(wf.BufferSourceConverter.isBufferSource(r[0]))e=wf.BufferSourceConverter.toArrayBuffer(r[0]);else{var i=r[0],o=Array.isArray(r[1])?r[1].map((e=>wf.BufferSourceConverter.toArrayBuffer(e))):[];e=jg.serialize(new vw({type:i,values:o}))}super(e,vw)}onInit(e){this.type=e.type,this.values=e.values}toTextObject(){var e=this.toTextObjectWithoutValue();return e.Value=this.values.map((e=>new yE("",{"":e}))),e}toTextObjectWithoutValue(){var e=this.toTextObjectEmpty();return e[yE.NAME]===gA.NAME&&(e[yE.NAME]=gE.toString(this.type)),e}}gA.NAME="Attribute";class mA extends gA{constructor(){var e;if(wf.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0]))super(arguments.length<=0?void 0:arguments[0]);else{var t=new PP({printableString:arguments.length<=0?void 0:arguments[0]});super(iP,[jg.serialize(t)])}null!==(e=this.password)&&void 0!==e||(this.password="")}onInit(e){if(super.onInit(e),this.values[0]){var t=jg.parse(this.values[0],PP);this.password=t.toString()}}toTextObject(){var e=this.toTextObjectWithoutValue();return e[yE.VALUE]=this.password,e}}mA.NAME="Challenge Password";class wA extends gA{constructor(){var e;if(wf.BufferSourceConverter.isBufferSource(arguments.length<=0?void 0:arguments[0]))super(arguments.length<=0?void 0:arguments[0]);else{var t=arguments.length<=0?void 0:arguments[0],r=new Dw;for(var n of t)r.push(jg.parse(n.rawData,Bw));super(oP,[jg.serialize(r)])}null!==(e=this.items)&&void 0!==e||(this.items=[])}onInit(e){if(super.onInit(e),this.values[0]){var t=jg.parse(this.values[0],Dw);this.items=t.map((e=>dA.create(jg.serialize(e))))}}toTextObject(){var e=this.toTextObjectWithoutValue(),t=this.items.map((e=>e.toTextObject()));for(var r of t)e[r[yE.NAME]]=r;return e}}wA.NAME="Extensions";class bA{static register(e,t){this.items.set(e,t)}static create(e){var t=new gA(e),r=this.items.get(t.type);return r?new r(e):t}}bA.items=new Map;var _A,SA="crypto.signatureFormatter";var PA=_A=class{static createPssParams(e,t){var r=_A.getHashAlgorithm(e);return r?new aS({hashAlgorithm:r,maskGenAlgorithm:new kw({algorithm:X_,parameters:jg.serialize(r)}),saltLength:t}):null}static getHashAlgorithm(e){var t=BS.resolve(RP);return"string"==typeof e?t.toAsnAlgorithm({name:e}):"object"==typeof e&&e&&"name"in e?t.toAsnAlgorithm(e):null}toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"rsassa-pkcs1-v1_5":if(!("hash"in e))return new kw({algorithm:R_,parameters:null});var t;if("string"==typeof e.hash)t=e.hash;else{if(!e.hash||"object"!=typeof e.hash||!("name"in e.hash)||"string"!=typeof e.hash.name)throw new Error("Cannot get hash algorithm name");t=e.hash.name.toUpperCase()}switch(t.toLowerCase()){case"sha-1":return new kw({algorithm:U_,parameters:null});case"sha-256":return new kw({algorithm:V_,parameters:null});case"sha-384":return new kw({algorithm:q_,parameters:null});case"sha-512":return new kw({algorithm:H_,parameters:null})}break;case"rsa-pss":if("hash"in e){if(!("saltLength"in e)||"number"!=typeof e.saltLength)throw new Error("Cannot get 'saltLength' from 'alg' argument");var r=_A.createPssParams(e.hash,e.saltLength);if(!r)throw new Error("Cannot create PSS parameters");return new kw({algorithm:M_,parameters:jg.serialize(r)})}return new kw({algorithm:M_,parameters:null})}return null}toWebAlgorithm(e){switch(e.algorithm){case R_:return{name:"RSASSA-PKCS1-v1_5"};case U_:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-1"}};case V_:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-256"}};case q_:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-384"}};case H_:return{name:"RSASSA-PKCS1-v1_5",hash:{name:"SHA-512"}};case M_:if(e.parameters){var t=jg.parse(e.parameters,aS);return{name:"RSA-PSS",hash:BS.resolve(RP).toWebAlgorithm(t.hashAlgorithm),saltLength:t.saltLength}}return{name:"RSA-PSS"}}return null}};PA=_A=Ro([NS()],PA),BS.registerSingleton(DP,PA);var EA=class{toAsnAlgorithm(e){switch(e.name.toLowerCase()){case"sha-1":return new kw({algorithm:Q_});case"sha-256":return new kw({algorithm:J_});case"sha-384":return new kw({algorithm:Z_});case"sha-512":return new kw({algorithm:$_})}return null}toWebAlgorithm(e){switch(e.algorithm){case Q_:return{name:"SHA-1"};case J_:return{name:"SHA-256"};case Z_:return{name:"SHA-384"};case $_:return{name:"SHA-512"}}return null}};EA=Ro([NS()],EA),BS.registerSingleton(DP,EA);class AA{addPadding(e,t){var r=wf.BufferSourceConverter.toUint8Array(t),n=new Uint8Array(e);return n.set(r,e-r.length),n}removePadding(e){for(var t=arguments.length>1&&void 0!==arguments[1]&&arguments[1],r=wf.BufferSourceConverter.toUint8Array(e),n=0;n<r.length;n++)if(r[n]){r=r.slice(n);break}if(t&&r[0]>127){var i=new Uint8Array(r.length+1);return i.set(r,1),i.buffer}return r.buffer}toAsnSignature(e,t){if("ECDSA"===e.name){var r=e.namedCurve,n=AA.namedCurveSize.get(r)||AA.defaultNamedCurveSize,i=new D_,o=wf.BufferSourceConverter.toUint8Array(t);return i.r=this.removePadding(o.slice(0,n),!0),i.s=this.removePadding(o.slice(n,n+n),!0),jg.serialize(i)}return null}toWebSignature(e,t){if("ECDSA"===e.name){var r=jg.parse(t,D_),n=e.namedCurve,i=AA.namedCurveSize.get(n)||AA.defaultNamedCurveSize,o=this.addPadding(i,this.removePadding(r.r)),a=this.addPadding(i,this.removePadding(r.s));return wf.combine(o,a)}return null}}AA.namedCurveSize=new Map,AA.defaultNamedCurveSize=32;var kA,xA,TA="1.3.101.110",IA="1.3.101.111",CA="1.3.101.112",BA="1.3.101.113",NA=class{toAsnAlgorithm(e){var t=null;switch(e.name.toLowerCase()){case"ed25519":t=CA;break;case"x25519":t=TA;break;case"eddsa":switch(e.namedCurve.toLowerCase()){case"ed25519":t=CA;break;case"ed448":t=BA}break;case"ecdh-es":switch(e.namedCurve.toLowerCase()){case"x25519":t=TA;break;case"x448":t=IA}}return t?new kw({algorithm:t}):null}toWebAlgorithm(e){switch(e.algorithm){case CA:return{name:"Ed25519"};case BA:return{name:"EdDSA",namedCurve:"Ed448"};case TA:return{name:"X25519"};case IA:return{name:"ECDH-ES",namedCurve:"X448"}}return null}};NA=Ro([NS()],NA),BS.registerSingleton(DP,NA);(class extends nA{constructor(e){nA.isAsnEncoded(e)?super(e,NP):super(e),this.tag=rA.CertificateRequestTag}onInit(e){this.tbs=jg.serialize(e.certificationRequestInfo),this.publicKey=new iA(e.certificationRequestInfo.subjectPKInfo);var t=BS.resolve(RP);this.signatureAlgorithm=t.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signature,this.attributes=e.certificationRequestInfo.attributes.map((e=>bA.create(jg.serialize(e))));var r=this.getAttribute(oP);this.extensions=[],r instanceof wA&&(this.extensions=r.items),this.subjectName=new xE(e.certificationRequestInfo.subject),this.subject=this.subjectName.toString()}getAttribute(e){for(var t of this.attributes)if(t.type===e)return t;return null}getAttributes(e){return this.attributes.filter((t=>t.type===e))}getExtension(e){for(var t of this.extensions)if(t.type===e)return t;return null}getExtensions(e){return this.extensions.filter((t=>t.type===e))}verify(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var n=t.length>0&&void 0!==t[0]?t[0]:SE.get(),i=e._objectSpread2(e._objectSpread2({},r.publicKey.algorithm),r.signatureAlgorithm),o=yield r.publicKey.export(i,["verify"],n),a=BS.resolveAll(SA).reverse(),s=null;for(var l of a)if(s=l.toWebSignature(i,r.signature))break;if(!s)throw Error("Cannot convert WebCrypto signature value to ASN.1 format");return yield n.subtle.verify(r.signatureAlgorithm,o,s,r.tbs)}))()}toTextObject(){var e=this.toTextObjectEmpty(),t=jg.parse(this.rawData,NP),r=t.certificationRequestInfo,n=new yE("",{Version:"".concat(Nw[r.version]," (").concat(r.version,")"),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(this.attributes.length){var i=new yE("");for(var o of this.attributes){var a=o.toTextObject();i[a[yE.NAME]]=a}n.Attributes=i}return e.Data=n,e.Signature=new yE("",{Algorithm:mE.serializeAlgorithm(t.signatureAlgorithm),"":t.signature}),e}}).NAME="PKCS#10 Certificate Request";class DA extends nA{constructor(e){nA.isAsnEncoded(e)?super(e,Rw):super(e),this.tag=rA.CertificateTag}onInit(e){var t=e.tbsCertificate;this.tbs=jg.serialize(t),this.serialNumber=wf.Convert.ToHex(t.serialNumber),this.subjectName=new xE(t.subject),this.subject=new xE(t.subject).toString(),this.issuerName=new xE(t.issuer),this.issuer=this.issuerName.toString();var r=BS.resolve(RP);this.signatureAlgorithm=r.toWebAlgorithm(e.signatureAlgorithm),this.signature=e.signatureValue;var n=t.validity.notBefore.utcTime||t.validity.notBefore.generalTime;if(!n)throw new Error("Cannot get 'notBefore' value");this.notBefore=n;var i=t.validity.notAfter.utcTime||t.validity.notAfter.generalTime;if(!i)throw new Error("Cannot get 'notAfter' value");this.notAfter=i,this.extensions=[],t.extensions&&(this.extensions=t.extensions.map((e=>dA.create(jg.serialize(e))))),this.publicKey=new iA(t.subjectPublicKeyInfo)}getExtension(e){for(var t of this.extensions)if("string"==typeof e){if(t.type===e)return t}else if(t instanceof e)return t;return null}getExtensions(e){return this.extensions.filter((t=>"string"==typeof e?t.type===e:t instanceof e))}verify(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var n,i,o=t.length>0&&void 0!==t[0]?t[0]:{},a=t.length>1&&void 0!==t[1]?t[1]:SE.get(),s=o.publicKey;try{if(s)if("publicKey"in s)n=e._objectSpread2(e._objectSpread2({},s.publicKey.algorithm),r.signatureAlgorithm),i=yield s.publicKey.export(n,["verify"],a);else if(s instanceof iA)n=e._objectSpread2(e._objectSpread2({},s.algorithm),r.signatureAlgorithm),i=yield s.export(n,["verify"],a);else if(wf.BufferSourceConverter.isBufferSource(s)){var l=new iA(s);n=e._objectSpread2(e._objectSpread2({},l.algorithm),r.signatureAlgorithm),i=yield l.export(n,["verify"],a)}else n=e._objectSpread2(e._objectSpread2({},s.algorithm),r.signatureAlgorithm),i=s;else n=e._objectSpread2(e._objectSpread2({},r.publicKey.algorithm),r.signatureAlgorithm),i=yield r.publicKey.export(n,["verify"],a)}catch(e){return!1}var c=BS.resolveAll(SA).reverse(),u=null;for(var d of c)if(u=d.toWebSignature(n,r.signature))break;if(!u)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");var h=yield a.subtle.verify(r.signatureAlgorithm,i,u,r.tbs);if(o.signatureOnly)return h;var p=(o.date||new Date).getTime();return h&&r.notBefore.getTime()<p&&p<r.notAfter.getTime()}))()}getThumbprint(){var t=arguments,r=this;return e._asyncToGenerator((function*(){for(var e,n="SHA-1",i=t.length,o=new Array(i),a=0;a<i;a++)o[a]=t[a];return o[0]&&(o[0].subtle?e=o[0]:(n=o[0]||n,e=o[1])),null!=e||(e=SE.get()),yield e.subtle.digest(n,r.rawData)}))()}isSelfSigned(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var e=t.length>0&&void 0!==t[0]?t[0]:SE.get();return r.subject===r.issuer&&(yield r.verify({signatureOnly:!0},e))}))()}toTextObject(){var e=this.toTextObjectEmpty(),t=jg.parse(this.rawData,Rw),r=t.tbsCertificate,n=new yE("",{Version:"".concat(Nw[r.version]," (").concat(r.version,")"),"Serial Number":r.serialNumber,"Signature Algorithm":mE.serializeAlgorithm(r.signature),Issuer:this.issuer,Validity:new yE("",{"Not Before":r.validity.notBefore.getTime(),"Not After":r.validity.notAfter.getTime()}),Subject:this.subject,"Subject Public Key Info":this.publicKey});if(r.issuerUniqueID&&(n["Issuer Unique ID"]=r.issuerUniqueID),r.subjectUniqueID&&(n["Subject Unique ID"]=r.subjectUniqueID),this.extensions.length){var i=new yE("");for(var o of this.extensions){var a=o.toTextObject();i[a[yE.NAME]]=a}n.Extensions=i}return e.Data=n,e.Signature=new yE("",{Algorithm:mE.serializeAlgorithm(t.signatureAlgorithm),"":t.signatureValue}),e}}DA.NAME="Certificate";class GA{static createSelfSigned(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:SE.get();if(!t.keys.privateKey)throw new Error("Bad field 'keys' in 'params' argument. 'privateKey' is empty");if(!t.keys.publicKey)throw new Error("Bad field 'keys' in 'params' argument. 'publicKey' is empty");return n.create({serialNumber:t.serialNumber,subject:t.name,issuer:t.name,notBefore:t.notBefore,notAfter:t.notAfter,publicKey:t.keys.publicKey,signingKey:t.keys.privateKey,signingAlgorithm:t.signingAlgorithm,extensions:t.extensions},e)}))()}static create(t){var r=arguments;return e._asyncToGenerator((function*(){var n,i,o=r.length>1&&void 0!==r[1]?r[1]:SE.get();i=t.publicKey instanceof iA?t.publicKey.rawData:"publicKey"in t.publicKey?t.publicKey.publicKey.rawData:wf.BufferSourceConverter.isBufferSource(t.publicKey)?t.publicKey:yield o.subtle.exportKey("spki",t.publicKey);var a=t.serialNumber?wf.BufferSourceConverter.toUint8Array(wf.Convert.FromHex(t.serialNumber)):o.getRandomValues(new Uint8Array(16));a[0]>127&&(a[0]&=127),a.length>1&&0===a[0]&&(a[1]|=128);var s=t.notBefore||new Date,l=t.notAfter||new Date(s.getTime()+31536e6),c=new Rw({tbsCertificate:new Gw({version:Nw.v3,serialNumber:a,validity:new Cw({notBefore:s,notAfter:l}),extensions:new Dw((null===(n=t.extensions)||void 0===n?void 0:n.map((e=>jg.parse(e.rawData,Bw))))||[]),subjectPublicKeyInfo:jg.parse(i,xw)})});if(t.subject){var u=t.subject instanceof xE?t.subject:new xE(t.subject);c.tbsCertificate.subject=jg.parse(u.toArrayBuffer(),Kg)}if(t.issuer){var d=t.issuer instanceof xE?t.issuer:new xE(t.issuer);c.tbsCertificate.issuer=jg.parse(d.toArrayBuffer(),Kg)}var h={hash:"SHA-256"},p="signingKey"in t?e._objectSpread2(e._objectSpread2(e._objectSpread2({},h),t.signingAlgorithm),t.signingKey.algorithm):e._objectSpread2(e._objectSpread2({},h),t.signingAlgorithm),f=BS.resolve(RP);c.tbsCertificate.signature=c.signatureAlgorithm=f.toAsnAlgorithm(p);var v=jg.serialize(c.tbsCertificate),y="signingKey"in t?yield o.subtle.sign(p,t.signingKey,v):t.signature,g=BS.resolveAll(SA).reverse(),m=null;for(var w of g)if(m=w.toAsnSignature(p,y))break;if(!m)throw Error("Cannot convert ASN.1 signature value to WebCrypto format");return c.signatureValue=m,new DA(jg.serialize(c))}))()}}!function(e){e[e.unspecified=0]="unspecified",e[e.keyCompromise=1]="keyCompromise",e[e.cACompromise=2]="cACompromise",e[e.affiliationChanged=3]="affiliationChanged",e[e.superseded=4]="superseded",e[e.cessationOfOperation=5]="cessationOfOperation",e[e.certificateHold=6]="certificateHold",e[e.removeFromCRL=8]="removeFromCRL",e[e.privilegeWithdrawn=9]="privilegeWithdrawn",e[e.aACompromise=10]="aACompromise"}(kA||(kA={})),dA.register(fm,aA),dA.register(Vm,sA),dA.register(nw,lA),dA.register(bw,cA),dA.register(um,oA),dA.register(pw,uA),dA.register(Nm,pA),dA.register(sm,fA),bA.register(iP,mA),bA.register(oP,wA),BS.registerSingleton(SA,class{toAsnSignature(e,t){return wf.BufferSourceConverter.toArrayBuffer(t)}toWebSignature(e,t){return wf.BufferSourceConverter.toArrayBuffer(t)}}),BS.registerSingleton(SA,AA),AA.namedCurveSize.set("P-256",32),AA.namedCurveSize.set("K-256",32),AA.namedCurveSize.set("P-384",48),AA.namedCurveSize.set("P-521",66);class RA extends Ia{listen(){return e._asyncToGenerator((function*(){throw new af("WebRTCTransport.createListener")}))()}getAddrs(){return[]}updateAnnounceAddrs(){}close(){return e._asyncToGenerator((function*(){}))()}}function OA(){var t,r=Yc(),n=!1;return{sink:(t=e._asyncToGenerator((function*(e){if(n)throw new Error("already piped");n=!0,r.resolve(e)})),function(e){return t.apply(this,arguments)}),source:e._wrapAsyncGenerator((function*(){var t=yield e._awaitAsyncGenerator(r.promise);yield*e._asyncGeneratorDelegate(e._asyncIterator(t))}))()}}var LA=65535,MA=Boolean(null===(xA=globalThis.process)||void 0===xA||null===(xA=xA.env)||void 0===xA?void 0:xA.DUMP_SESSION_KEYS);function jA(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&"Uint8Array"===e.constructor.name}function FA(e){if("boolean"!=typeof e)throw new Error("boolean expected, not ".concat(e))}function UA(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("positive integer expected, got "+e)}function zA(e){if(!jA(e))throw new Error("Uint8Array expected");for(var t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];if(r.length>0&&!r.includes(e.length))throw new Error("Uint8Array expected of length "+r+", got length="+e.length)}function VA(e){var t=!(arguments.length>1&&void 0!==arguments[1])||arguments[1];if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function qA(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))}function HA(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];for(var n=0;n<t.length;n++)t[n].fill(0)}var KA=(()=>68===new Uint8Array(new Uint32Array([287454020]).buffer)[0])();function WA(e){if("string"==typeof e)e=function(e){if("string"!=typeof e)throw new Error("string expected");return new Uint8Array((new TextEncoder).encode(e))}(e);else{if(!jA(e))throw new Error("Uint8Array expected, got "+typeof e);e=$A(e)}return e}var QA=(e,t)=>{function r(r){if(zA(r),!KA)throw new Error("Non little-endian hardware is not yet supported");for(var n=arguments.length,i=new Array(n>1?n-1:0),o=1;o<n;o++)i[o-1]=arguments[o];if(void 0!==e.nonceLength){var a=i[0];if(!a)throw new Error("nonce / iv required");e.varSizeNonce?zA(a):zA(a,e.nonceLength)}var s=e.tagLength;s&&void 0!==i[1]&&zA(i[1]);var l=t(r,...i),c=(e,t)=>{if(void 0!==t){if(2!==e)throw new Error("cipher output not supported");zA(t)}},u=!1;return{encrypt(e,t){if(u)throw new Error("cannot encrypt() twice with same key + nonce");return u=!0,zA(e),c(l.encrypt.length,t),l.encrypt(e,t)},decrypt(e,t){if(zA(e),s&&e.length<s)throw new Error("invalid ciphertext length: smaller than tagLength="+s);return c(l.decrypt.length,t),l.decrypt(e,t)}}}return Object.assign(r,e),r};function YA(e,t){var r=!(arguments.length>2&&void 0!==arguments[2])||arguments[2];if(void 0===t)return new Uint8Array(e);if(t.length!==e)throw new Error("invalid output length, expected "+e+", got: "+t.length);if(r&&t.byteOffset%4!=0)throw new Error("invalid output, must be aligned");return t}function JA(e,t,r,n){if("function"==typeof e.setBigUint64)return e.setBigUint64(t,r,n);var i=BigInt(32),o=BigInt(4294967295),a=Number(r>>i&o),s=Number(r&o);e.setUint32(t+4,a,n),e.setUint32(t+0,s,n)}function ZA(e,t,r){FA(r);var n,i=new Uint8Array(16),o=(n=i,new DataView(n.buffer,n.byteOffset,n.byteLength));return JA(o,0,BigInt(t),r),JA(o,8,BigInt(e),r),i}function $A(e){return Uint8Array.from(e)}var XA=e=>Uint8Array.from(e.split("").map((e=>e.charCodeAt(0)))),ek=XA("expand 16-byte k"),tk=XA("expand 32-byte k"),rk=qA(ek),nk=qA(tk);function ik(e,t){return e<<t|e>>>32-t}function ok(e){return e.byteOffset%4==0}var ak=2**32-1,sk=new Uint32Array;function lk(e,t){var{allowShortKeys:r,extendNonceFn:n,counterLength:i,counterRight:o,rounds:a}=function(e,t){if(null==t||"object"!=typeof t)throw new Error("options must be defined");return Object.assign(e,t)}({allowShortKeys:!1,counterLength:8,counterRight:!1,rounds:20},t);if("function"!=typeof e)throw new Error("core must be a function");return UA(i),UA(a),FA(o),FA(r),function(t,s,l,c){var u=arguments.length>4&&void 0!==arguments[4]?arguments[4]:0;zA(t),zA(s),zA(l);var d=l.length;if(void 0===c&&(c=new Uint8Array(d)),zA(c),UA(u),u<0||u>=ak)throw new Error("arx: counter overflow");if(c.length<d)throw new Error("arx: output (".concat(c.length,") is shorter than data (").concat(d,")"));var h,p,f=[],v=t.length;if(32===v)f.push(h=$A(t)),p=nk;else{if(16!==v||!r)throw new Error("arx: invalid 32-byte key, got length=".concat(v));(h=new Uint8Array(32)).set(t),h.set(t,16),p=rk,f.push(h)}ok(s)||f.push(s=$A(s));var y=qA(h);if(n){if(24!==s.length)throw new Error("arx: extended nonce must be 24 bytes");n(p,y,qA(s.subarray(0,16)),y),s=s.subarray(16)}var g=16-i;if(g!==s.length)throw new Error("arx: nonce must be ".concat(g," or 16 bytes"));if(12!==g){var m=new Uint8Array(12);m.set(s,o?0:12-s.length),s=m,f.push(s)}var w=qA(s);return function(e,t,r,n,i,o,a,s){for(var l=i.length,c=new Uint8Array(64),u=qA(c),d=ok(i)&&ok(o),h=d?qA(i):sk,p=d?qA(o):sk,f=0;f<l;a++){if(e(t,r,n,u,a,s),a>=ak)throw new Error("arx: counter overflow");var v=Math.min(64,l-f);if(d&&64===v){var y=f/4;if(f%4!=0)throw new Error("arx: invalid block position");for(var g,m=0;m<16;m++)p[g=y+m]=h[g]^u[m];f+=64}else{for(var w,b=0;b<v;b++)o[w=f+b]=i[w]^c[b];f+=v}}}(e,p,y,w,l,c,u,a),HA(...f),c}}var ck=(e,t)=>255&e[t++]|(255&e[t++])<<8;class uk{constructor(e){this.blockLen=16,this.outputLen=16,this.buffer=new Uint8Array(16),this.r=new Uint16Array(10),this.h=new Uint16Array(10),this.pad=new Uint16Array(8),this.pos=0,this.finished=!1,zA(e=WA(e),32);var t=ck(e,0),r=ck(e,2),n=ck(e,4),i=ck(e,6),o=ck(e,8),a=ck(e,10),s=ck(e,12),l=ck(e,14);this.r[0]=8191&t,this.r[1]=8191&(t>>>13|r<<3),this.r[2]=7939&(r>>>10|n<<6),this.r[3]=8191&(n>>>7|i<<9),this.r[4]=255&(i>>>4|o<<12),this.r[5]=o>>>1&8190,this.r[6]=8191&(o>>>14|a<<2),this.r[7]=8065&(a>>>11|s<<5),this.r[8]=8191&(s>>>8|l<<8),this.r[9]=l>>>5&127;for(var c=0;c<8;c++)this.pad[c]=ck(e,16+2*c)}process(e,t){var r=arguments.length>2&&void 0!==arguments[2]&&arguments[2]?0:2048,{h:n,r:i}=this,o=i[0],a=i[1],s=i[2],l=i[3],c=i[4],u=i[5],d=i[6],h=i[7],p=i[8],f=i[9],v=ck(e,t+0),y=ck(e,t+2),g=ck(e,t+4),m=ck(e,t+6),w=ck(e,t+8),b=ck(e,t+10),_=ck(e,t+12),S=ck(e,t+14),P=n[0]+(8191&v),E=n[1]+(8191&(v>>>13|y<<3)),A=n[2]+(8191&(y>>>10|g<<6)),k=n[3]+(8191&(g>>>7|m<<9)),x=n[4]+(8191&(m>>>4|w<<12)),T=n[5]+(w>>>1&8191),I=n[6]+(8191&(w>>>14|b<<2)),C=n[7]+(8191&(b>>>11|_<<5)),B=n[8]+(8191&(_>>>8|S<<8)),N=n[9]+(S>>>5|r),D=0,G=D+P*o+E*(5*f)+A*(5*p)+k*(5*h)+x*(5*d);D=G>>>13,G&=8191;var R=(D+=(G+=T*(5*u)+I*(5*c)+C*(5*l)+B*(5*s)+N*(5*a))>>>13)+P*a+E*o+A*(5*f)+k*(5*p)+x*(5*h);D=R>>>13,R&=8191,D+=(R+=T*(5*d)+I*(5*u)+C*(5*c)+B*(5*l)+N*(5*s))>>>13,R&=8191;var O=D+P*s+E*a+A*o+k*(5*f)+x*(5*p);D=O>>>13,O&=8191,D+=(O+=T*(5*h)+I*(5*d)+C*(5*u)+B*(5*c)+N*(5*l))>>>13,O&=8191;var L=D+P*l+E*s+A*a+k*o+x*(5*f);D=L>>>13,L&=8191,D+=(L+=T*(5*p)+I*(5*h)+C*(5*d)+B*(5*u)+N*(5*c))>>>13,L&=8191;var M=D+P*c+E*l+A*s+k*a+x*o;D=M>>>13,M&=8191,D+=(M+=T*(5*f)+I*(5*p)+C*(5*h)+B*(5*d)+N*(5*u))>>>13,M&=8191;var j=D+P*u+E*c+A*l+k*s+x*a;D=j>>>13,j&=8191,D+=(j+=T*o+I*(5*f)+C*(5*p)+B*(5*h)+N*(5*d))>>>13,j&=8191;var F=D+P*d+E*u+A*c+k*l+x*s;D=F>>>13,F&=8191,D+=(F+=T*a+I*o+C*(5*f)+B*(5*p)+N*(5*h))>>>13,F&=8191;var U=D+P*h+E*d+A*u+k*c+x*l;D=U>>>13,U&=8191,D+=(U+=T*s+I*a+C*o+B*(5*f)+N*(5*p))>>>13,U&=8191;var z=D+P*p+E*h+A*d+k*u+x*c;D=z>>>13,z&=8191,D+=(z+=T*l+I*s+C*a+B*o+N*(5*f))>>>13,z&=8191;var V=D+P*f+E*p+A*h+k*d+x*u;D=V>>>13,V&=8191,D+=(V+=T*c+I*l+C*s+B*a+N*o)>>>13,V&=8191,G=8191&(D=(D=(D<<2)+D|0)+(G&=8191)|0),R+=D>>>=13,n[0]=G,n[1]=R,n[2]=O,n[3]=L,n[4]=M,n[5]=j,n[6]=F,n[7]=U,n[8]=z,n[9]=V}finalize(){var{h:e,pad:t}=this,r=new Uint16Array(10),n=e[1]>>>13;e[1]&=8191;for(var i=2;i<10;i++)e[i]+=n,n=e[i]>>>13,e[i]&=8191;e[0]+=5*n,n=e[0]>>>13,e[0]&=8191,e[1]+=n,n=e[1]>>>13,e[1]&=8191,e[2]+=n,r[0]=e[0]+5,n=r[0]>>>13,r[0]&=8191;for(var o=1;o<10;o++)r[o]=e[o]+n,n=r[o]>>>13,r[o]&=8191;r[9]-=8192;for(var a=(1^n)-1,s=0;s<10;s++)r[s]&=a;a=~a;for(var l=0;l<10;l++)e[l]=e[l]&a|r[l];e[0]=65535&(e[0]|e[1]<<13),e[1]=65535&(e[1]>>>3|e[2]<<10),e[2]=65535&(e[2]>>>6|e[3]<<7),e[3]=65535&(e[3]>>>9|e[4]<<4),e[4]=65535&(e[4]>>>12|e[5]<<1|e[6]<<14),e[5]=65535&(e[6]>>>2|e[7]<<11),e[6]=65535&(e[7]>>>5|e[8]<<8),e[7]=65535&(e[8]>>>8|e[9]<<5);var c=e[0]+t[0];e[0]=65535&c;for(var u=1;u<8;u++)c=(e[u]+t[u]|0)+(c>>>16)|0,e[u]=65535&c;HA(r)}update(e){VA(this),zA(e=WA(e));for(var{buffer:t,blockLen:r}=this,n=e.length,i=0;i<n;){var o=Math.min(r-this.pos,n-i);if(o!==r)t.set(e.subarray(i,i+o),this.pos),this.pos+=o,i+=o,this.pos===r&&(this.process(t,0,!1),this.pos=0);else for(;r<=n-i;i+=r)this.process(e,i)}return this}destroy(){HA(this.h,this.r,this.buffer,this.pad)}digestInto(e){VA(this),function(e,t){zA(e);var r=t.outputLen;if(e.length<r)throw new Error("digestInto() expects output buffer of length at least "+r)}(e,this),this.finished=!0;var{buffer:t,h:r}=this,{pos:n}=this;if(n){for(t[n++]=1;n<16;n++)t[n]=0;this.process(t,0,!0)}this.finalize();for(var i=0,o=0;o<8;o++)e[i++]=r[o]>>>0,e[i++]=r[o]>>>8;return e}digest(){var{buffer:e,outputLen:t}=this;this.digestInto(e);var r=e.slice(0,t);return this.destroy(),r}}var dk,hk,pk,fk=(hk=(e,t)=>dk(t).update(WA(e)).digest(),pk=(dk=e=>new uk(e))(new Uint8Array(32)),hk.outputLen=pk.outputLen,hk.blockLen=pk.blockLen,hk.create=e=>dk(e),hk);function vk(e,t,r,n,i){for(var o=arguments.length>5&&void 0!==arguments[5]?arguments[5]:20,a=e[0],s=e[1],l=e[2],c=e[3],u=t[0],d=t[1],h=t[2],p=t[3],f=t[4],v=t[5],y=t[6],g=t[7],m=i,w=r[0],b=r[1],_=r[2],S=a,P=s,E=l,A=c,k=u,x=d,T=h,I=p,C=f,B=v,N=y,D=g,G=m,R=w,O=b,L=_,M=0;M<o;M+=2)G=ik(G^(S=S+k|0),16),k=ik(k^(C=C+G|0),12),G=ik(G^(S=S+k|0),8),k=ik(k^(C=C+G|0),7),R=ik(R^(P=P+x|0),16),x=ik(x^(B=B+R|0),12),R=ik(R^(P=P+x|0),8),x=ik(x^(B=B+R|0),7),O=ik(O^(E=E+T|0),16),T=ik(T^(N=N+O|0),12),O=ik(O^(E=E+T|0),8),T=ik(T^(N=N+O|0),7),L=ik(L^(A=A+I|0),16),I=ik(I^(D=D+L|0),12),L=ik(L^(A=A+I|0),8),I=ik(I^(D=D+L|0),7),L=ik(L^(S=S+x|0),16),x=ik(x^(N=N+L|0),12),L=ik(L^(S=S+x|0),8),x=ik(x^(N=N+L|0),7),G=ik(G^(P=P+T|0),16),T=ik(T^(D=D+G|0),12),G=ik(G^(P=P+T|0),8),T=ik(T^(D=D+G|0),7),R=ik(R^(E=E+I|0),16),I=ik(I^(C=C+R|0),12),R=ik(R^(E=E+I|0),8),I=ik(I^(C=C+R|0),7),O=ik(O^(A=A+k|0),16),k=ik(k^(B=B+O|0),12),O=ik(O^(A=A+k|0),8),k=ik(k^(B=B+O|0),7);var j=0;n[j++]=a+S|0,n[j++]=s+P|0,n[j++]=l+E|0,n[j++]=c+A|0,n[j++]=u+k|0,n[j++]=d+x|0,n[j++]=h+T|0,n[j++]=p+I|0,n[j++]=f+C|0,n[j++]=v+B|0,n[j++]=y+N|0,n[j++]=g+D|0,n[j++]=m+G|0,n[j++]=w+R|0,n[j++]=b+O|0,n[j++]=_+L|0}var yk=lk(vk,{counterRight:!1,counterLength:4,allowShortKeys:!1}),gk=new Uint8Array(16),mk=(e,t)=>{e.update(t);var r=t.length%16;r&&e.update(gk.subarray(r))},wk=new Uint8Array(32);function bk(e,t,r,n,i){var o=e(t,r,wk),a=fk.create(o);i&&mk(a,i),mk(a,n);var s=ZA(n.length,i?i.length:0,!0);a.update(s);var l=a.digest();return HA(o,s),l}var _k,Sk=QA({blockSize:64,nonceLength:12,tagLength:16},(_k=yk,(e,t,r)=>{var n=16;return{encrypt(i,o){var a=i.length;(o=YA(a+n,o,!1)).set(i);var s=o.subarray(0,-16);_k(e,t,s,s,1);var l=bk(_k,e,t,s,r);return o.set(l,a),HA(l),o},decrypt(i,o){o=YA(i.length-n,o,!1);var a=i.subarray(0,-16),s=i.subarray(-16),l=bk(_k,e,t,a,r);if(!function(e,t){if(e.length!==t.length)return!1;for(var r=0,n=0;n<e.length;n++)r|=e[n]^t[n];return 0===r}(s,l))throw new Error("invalid tag");return o.set(i.subarray(0,-16)),_k(e,t,o,o,1),HA(l),o}}}));var Pk=Uint8Array.from([0]),Ek=Uint8Array.of();var Ak={hashSHA256:e=>Po(e.subarray()),getHKDF(e,t){var r=function(e,t,r){return hr(e),void 0===r&&(r=new Uint8Array(e.outputLen)),Sn(e,Rr(r),Rr(t))}(Po,t,e),n=function(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:32;hr(e),ur(n);var i=e.outputLen;if(n>255*i)throw new Error("Length should be <= 255*HashLen");var o=Math.ceil(n/i);void 0===r&&(r=Ek);for(var a=new Uint8Array(o*i),s=Sn.create(e,t),l=s._cloneInto(),c=new Uint8Array(s.outputLen),u=0;u<o;u++)Pk[0]=u+1,l.update(0===u?Ek:c).update(r).update(Pk).digestInto(c),a.set(c,i*u),s._cloneInto(l);return s.destroy(),l.destroy(),vr(c,Pk),a.slice(0,n)}(Po,r,void 0,96),i=n;return[i.subarray(0,32),i.subarray(32,64),i.subarray(64,96)]},generateX25519KeyPair(){var e=So.utils.randomPrivateKey();return{publicKey:So.getPublicKey(e),privateKey:e}},generateX25519KeyPairFromSeed:e=>({publicKey:So.getPublicKey(e),privateKey:e}),generateX25519SharedKey:(e,t)=>So.getSharedSecret(e.subarray(),t.subarray()),chaCha20Poly1305Encrypt:(e,t,r,n)=>Sk(n,t,r).encrypt(e.subarray()),chaCha20Poly1305Decrypt:(e,t,r,n,i)=>Sk(n,t,r).decrypt(e.subarray(),i)},kk=Ak;var xk=e=>{var t=Ke(2);return t[0]=e>>8,t[1]=e,t};xk.bytes=2;var Tk=e=>{if(e.length<2)throw RangeError("Could not decode int16BE");if(e instanceof Uint8Array){var t=0;return t+=e[0]<<8,t+=e[1]}return e.getUint16(0)};function Ik(e,t){t.enabled&&MA&&(e?(t("LOCAL_STATIC_PUBLIC_KEY ".concat(Ze(e.publicKey,"hex"))),t("LOCAL_STATIC_PRIVATE_KEY ".concat(Ze(e.privateKey,"hex")))):t("Missing local static keys."))}function Ck(e,t){t.enabled&&MA&&(e?(t("LOCAL_PUBLIC_EPHEMERAL_KEY ".concat(Ze(e.publicKey,"hex"))),t("LOCAL_PRIVATE_EPHEMERAL_KEY ".concat(Ze(e.privateKey,"hex")))):t("Missing local ephemeral keys."))}function Bk(e,t){t.enabled&&MA&&t(e?"REMOTE_EPHEMERAL_PUBLIC_KEY ".concat(Ze(e.subarray(),"hex")):"Missing remote ephemeral keys.")}function Nk(e,t,r){r.enabled&&MA&&(r("CIPHER_STATE_1 ".concat(e.n.getUint64()," ").concat(e.k&&Ze(e.k,"hex"))),r("CIPHER_STATE_2 ".concat(t.n.getUint64()," ").concat(t.k&&Ze(t.k,"hex"))))}function Dk(e,t){if(e.length!==t.length)throw new Error("Inputs should have the same length");for(var r=Ke(e.length),n=0;n<e.length;n++)r[n]=e[n]^t[n];return r}Tk.bytes=2;class Gk extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid crypto exchange"),e._defineProperty(this,"code",void 0),this.code=Gk.code}}e._defineProperty(Gk,"code","ERR_INVALID_CRYPTO_EXCHANGE");class Rk{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:0;e._defineProperty(this,"n",void 0),e._defineProperty(this,"bytes",void 0),e._defineProperty(this,"view",void 0),this.n=t,this.bytes=He(12),this.view=new DataView(this.bytes.buffer,this.bytes.byteOffset,this.bytes.byteLength),this.view.setUint32(4,t,!0)}increment(){this.n++,this.view.setUint32(4,this.n,!0)}getBytes(){return this.bytes}getUint64(){return this.n}assertValue(){if(this.n>4294967295)throw new Error("Cipherstate has reached maximum n, a new handshake must be performed")}}var Ok,Lk,Mk=He(0);class jk{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:void 0,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;e._defineProperty(this,"k",void 0),e._defineProperty(this,"n",void 0),e._defineProperty(this,"crypto",void 0),this.crypto=t,this.k=r,this.n=new Rk(n)}hasKey(){return Boolean(this.k)}encryptWithAd(e,t){if(!this.hasKey())return t;this.n.assertValue();var r=this.crypto.encrypt(t,this.n.getBytes(),e,this.k);return this.n.increment(),r}decryptWithAd(e,t,r){if(!this.hasKey())return t;this.n.assertValue();var n=this.crypto.decrypt(t,this.n.getBytes(),e,this.k,r);return this.n.increment(),n}}class Fk{constructor(t,r){e._defineProperty(this,"cs",void 0),e._defineProperty(this,"ck",void 0),e._defineProperty(this,"h",void 0),e._defineProperty(this,"crypto",void 0),this.crypto=t;var n=ot(r,"utf-8");this.h=function(e,t){if(t.length<=32){var r=He(32);return r.set(t),r}return e.hash(t)}(t,n),this.ck=this.h,this.cs=new jk(t)}mixKey(e){var[t,r]=this.crypto.hkdf(this.ck,e);this.ck=t,this.cs=new jk(this.crypto,r)}mixHash(e){this.h=this.crypto.hash(new Fa(this.h,e))}encryptAndHash(e){var t=this.cs.encryptWithAd(this.h,e);return this.mixHash(t),t}decryptAndHash(e){var t=this.cs.decryptWithAd(this.h,e);return this.mixHash(e),t}split(){var[e,t]=this.crypto.hkdf(this.ck,Mk);return[new jk(this.crypto,e),new jk(this.crypto,t)]}}class Uk{constructor(t){e._defineProperty(this,"ss",void 0),e._defineProperty(this,"s",void 0),e._defineProperty(this,"e",void 0),e._defineProperty(this,"rs",void 0),e._defineProperty(this,"re",void 0),e._defineProperty(this,"initiator",void 0),e._defineProperty(this,"crypto",void 0);var{crypto:r,protocolName:n,prologue:i,initiator:o,s:a,e:s,rs:l,re:c}=t;this.crypto=r,this.ss=new Fk(r,n),this.ss.mixHash(i),this.initiator=o,this.s=a,this.e=s,this.rs=l,this.re=c}writeE(){if(this.e)throw new Error("ephemeral keypair is already set");var e=this.crypto.generateKeypair();return this.ss.mixHash(e.publicKey),this.e=e,e.publicKey}writeS(){if(!this.s)throw new Error("static keypair is not set");return this.ss.encryptAndHash(this.s.publicKey)}writeEE(){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.re))}writeES(){if(this.initiator){if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}else{if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}}writeSE(){if(this.initiator){if(!this.s)throw new Error("static keypair is not set");if(!this.re)throw new Error("remote ephemeral public key is not set");this.ss.mixKey(this.crypto.dh(this.s,this.re))}else{if(!this.e)throw new Error("ephemeral keypair is not set");if(!this.rs)throw new Error("remote static public key is not set");this.ss.mixKey(this.crypto.dh(this.e,this.rs))}}readE(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(this.re)throw new Error("remote ephemeral public key is already set");if(e.byteLength<t+32)throw new Error("message is not long enough");this.re=e.sublist(t,t+32),this.ss.mixHash(this.re)}readS(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;if(this.rs)throw new Error("remote static public key is already set");var r=32+(this.ss.cs.hasKey()?16:0);if(e.byteLength<t+r)throw new Error("message is not long enough");var n=e.sublist(t,t+r);return this.rs=this.ss.decryptAndHash(n),r}readEE(){this.writeEE()}readES(){this.writeES()}readSE(){this.writeSE()}}class zk extends Uk{writeMessageA(e){return new Fa(this.writeE(),this.ss.encryptAndHash(e))}writeMessageB(e){var t=this.writeE();this.writeEE();var r=this.writeS();return this.writeES(),new Fa(t,r,this.ss.encryptAndHash(e))}writeMessageC(e){var t=this.writeS();return this.writeSE(),new Fa(t,this.ss.encryptAndHash(e))}readMessageA(e){try{return this.readE(e),this.ss.decryptAndHash(e.sublist(32))}catch(e){throw new Gk("handshake stage 0 validation fail: ".concat(e.message))}}readMessageB(e){try{this.readE(e),this.readEE();var t=this.readS(e,32);return this.readES(),this.ss.decryptAndHash(e.sublist(32+t))}catch(e){throw new Gk("handshake stage 1 validation fail: ".concat(e.message))}}readMessageC(e){try{var t=this.readS(e);return this.readSE(),this.ss.decryptAndHash(e.sublist(t))}catch(e){throw new Gk("handshake stage 2 validation fail: ".concat(e.message))}}}function Vk(e,t,r){return qk.apply(this,arguments)}function qk(){return(qk=e._asyncToGenerator((function*(e,t,r){var n=yield e.sign(Wk(t));return Lk.encode({identityKey:ql(e.publicKey),identitySig:n,extensions:r})}))).apply(this,arguments)}function Hk(e,t,r){return Kk.apply(this,arguments)}function Kk(){return Kk=e._asyncToGenerator((function*(e,t,r){try{var n=Lk.decode(e),i=zl(n.identityKey);if(!1===(null==r?void 0:r.equals(i)))throw new Error("Payload identity key ".concat(i," does not match expected remote identity key ").concat(r));if(!t)throw new Error("Remote static does not exist");var o=Wk(t);if(!(yield i.verify(o,n.identitySig)))throw new Error("Invalid payload signature");return n}catch(e){throw new $o(e.message)}})),Kk.apply(this,arguments)}function Wk(e){var t=ot("noise-libp2p-static-key:");return e instanceof Uint8Array?_t([t,e],t.length+e.length):(e.prepend(t),e)}function Qk(){return Qk=e._asyncToGenerator((function*(e,t){var{log:r,connection:n,crypto:i,privateKey:o,prologue:a,s:s,remoteIdentityKey:l,extensions:c}=e,u=yield Vk(o,s.publicKey,c),d=new zk({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!0,prologue:a,s:s});Ik(d.s,r),r.trace("Stage 0 - Initiator starting to send first message."),yield n.write(d.writeMessageA(Mk),t),r.trace("Stage 0 - Initiator finished sending first message."),Ck(d.e,r),r.trace("Stage 1 - Initiator waiting to receive first message from responder...");var h,p,f=d.readMessageB(yield n.read(t));r.trace("Stage 1 - Initiator received the message."),Bk(d.re,r),h=d.rs,(p=r).enabled&&MA&&p(h?"REMOTE_STATIC_PUBLIC_KEY ".concat(Ze(h.subarray(),"hex")):"Missing remote static public key."),r.trace("Initiator going to check remote's signature...");var v=yield Hk(f,d.rs,l);r.trace("All good with the signature!"),r.trace("Stage 2 - Initiator sending third handshake message."),yield n.write(d.writeMessageC(u),t),r.trace("Stage 2 - Initiator sent message with signed payload.");var[y,g]=d.ss.split();return Nk(y,g,r),{payload:v,encrypt:e=>y.encryptWithAd(Mk,e),decrypt:(e,t)=>g.decryptWithAd(Mk,e,t)}})),Qk.apply(this,arguments)}function Yk(){return Yk=e._asyncToGenerator((function*(e,t){var{log:r,connection:n,crypto:i,privateKey:o,prologue:a,s:s,remoteIdentityKey:l,extensions:c}=e,u=yield Vk(o,s.publicKey,c),d=new zk({crypto:i,protocolName:"Noise_XX_25519_ChaChaPoly_SHA256",initiator:!1,prologue:a,s:s});Ik(d.s,r),r.trace("Stage 0 - Responder waiting to receive first message."),d.readMessageA(yield n.read(t)),r.trace("Stage 0 - Responder received first message."),Bk(d.re,r),r.trace("Stage 1 - Responder sending out first message with signed payload and static key."),yield n.write(d.writeMessageB(u),t),r.trace("Stage 1 - Responder sent the second handshake message with signed payload."),Ck(d.e,r),r.trace("Stage 2 - Responder waiting for third handshake message...");var h=d.readMessageC(yield n.read(t));r.trace("Stage 2 - Responder received the message, finished handshake.");var p=yield Hk(h,d.rs,l),[f,v]=d.ss.split();return Nk(f,v,r),{payload:p,encrypt:e=>v.encryptWithAd(Mk,e),decrypt:(e,t)=>f.decryptWithAd(Mk,e,t)}})),Yk.apply(this,arguments)}!function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==r.lengthDelimited&&t.fork(),null!=e.webtransportCerthashes)for(var n of e.webtransportCerthashes)t.uint32(10),t.bytes(n);if(null!=e.streamMuxers)for(var i of e.streamMuxers)t.uint32(18),t.string(i);!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={webtransportCerthashes:[],streamMuxers:[]},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:var a;if(null!=(null===(a=r.limits)||void 0===a?void 0:a.webtransportCerthashes)&&n.webtransportCerthashes.length===r.limits.webtransportCerthashes)throw new vl('Decode error - map field "webtransportCerthashes" had too many elements');n.webtransportCerthashes.push(e.bytes());break;case 2:var s;if(null!=(null===(s=r.limits)||void 0===s?void 0:s.streamMuxers)&&n.streamMuxers.length===r.limits.streamMuxers)throw new vl('Decode error - map field "streamMuxers" had too many elements');n.streamMuxers.push(e.string());break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(Ok||(Ok={})),function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.identityKey&&e.identityKey.byteLength>0&&(t.uint32(10),t.bytes(e.identityKey)),null!=e.identitySig&&e.identitySig.byteLength>0&&(t.uint32(18),t.bytes(e.identitySig)),null!=e.extensions&&(t.uint32(34),Ok.codec().encode(e.extensions,t)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={identityKey:He(0),identitySig:He(0)},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:n.identityKey=e.bytes();break;case 2:n.identitySig=e.bytes();break;case 4:var a;n.extensions=Ok.codec().decode(e,e.uint32(),{limits:null===(a=r.limits)||void 0===a?void 0:a.extensions});break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(Lk||(Lk={}));class Jk{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"protocol","/noise"),e._defineProperty(this,"crypto",void 0),e._defineProperty(this,"prologue",void 0),e._defineProperty(this,"staticKey",void 0),e._defineProperty(this,"extensions",void 0),e._defineProperty(this,"metrics",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,Symbol.toStringTag,"@chainsafe/libp2p-noise"),e._defineProperty(this,Ra,["@libp2p/connection-encryption","@chainsafe/libp2p-noise"]);var{staticNoiseKey:n,extensions:i,crypto:o,prologueBytes:a}=r,{metrics:s}=t;this.components=t;var l=null!=o?o:kk;this.crypto=function(e){return{generateKeypair:e.generateX25519KeyPair,dh:(t,r)=>e.generateX25519SharedKey(t.privateKey,r).subarray(0,32),encrypt:e.chaCha20Poly1305Encrypt,decrypt:e.chaCha20Poly1305Decrypt,hash:e.hashSHA256,hkdf:e.getHKDF}}(l),this.extensions=e._objectSpread2({webtransportCerthashes:[]},i),this.metrics=s?function(e){return{xxHandshakeSuccesses:e.registerCounter("libp2p_noise_xxhandshake_successes_total",{help:"Total count of noise xxHandshakes successes_"}),xxHandshakeErrors:e.registerCounter("libp2p_noise_xxhandshake_error_total",{help:"Total count of noise xxHandshakes errors"}),encryptedPackets:e.registerCounter("libp2p_noise_encrypted_packets_total",{help:"Total count of noise encrypted packets successfully"}),decryptedPackets:e.registerCounter("libp2p_noise_decrypted_packets_total",{help:"Total count of noise decrypted packets"}),decryptErrors:e.registerCounter("libp2p_noise_decrypt_errors_total",{help:"Total count of noise decrypt errors"})}}(s):void 0,this.staticKey=n?l.generateX25519KeyPairFromSeed(n):l.generateX25519KeyPair(),this.prologue=null!=a?a:He(0)}secureOutbound(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i,o=Ku(t,{lengthEncoder:xk,lengthDecoder:Tk,maxDataLength:LA}),a=yield n.performHandshakeInitiator(o,n.components.privateKey,null==r||null===(e=r.remotePeer)||void 0===e?void 0:e.publicKey,r),s=yield n.createSecureConnection(o,a);t.source=s.source,t.sink=s.sink;var l=zl(a.payload.identityKey);return{conn:t,remoteExtensions:a.payload.extensions,remotePeer:nc(l),streamMuxer:!0===(null==r?void 0:r.skipStreamMuxerNegotiation)?void 0:n.getStreamMuxer(null===(i=a.payload.extensions)||void 0===i?void 0:i.streamMuxers)}}))()}getStreamMuxer(e){if(null!=e&&0!==e.length){var t=this.components.upgrader.getStreamMuxers();if(null!=t)for(var r of e){var n=t.get(r);if(null!=n)return n}if(e.length)throw new Xo("Early muxer negotiation was requested but the initiator and responder had no common muxers")}}secureInbound(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i,o=Ku(t,{lengthEncoder:xk,lengthDecoder:Tk,maxDataLength:LA}),a=yield n.performHandshakeResponder(o,n.components.privateKey,null==r||null===(e=r.remotePeer)||void 0===e?void 0:e.publicKey,r),s=yield n.createSecureConnection(o,a);t.source=s.source,t.sink=s.sink;var l=zl(a.payload.identityKey);return{conn:t,remoteExtensions:a.payload.extensions,remotePeer:nc(l),streamMuxer:!0===(null==r?void 0:r.skipStreamMuxerNegotiation)?void 0:n.getStreamMuxer(null===(i=a.payload.extensions)||void 0===i?void 0:i.streamMuxers)}}))()}performHandshakeInitiator(t,r,n,i){var o=this;return e._asyncToGenerator((function*(){var a,s=!0===(null==i?void 0:i.skipStreamMuxerNegotiation)?[]:[...o.components.upgrader.getStreamMuxers().keys()];try{var l;a=yield function(e,t){return Qk.apply(this,arguments)}({connection:t,privateKey:r,remoteIdentityKey:n,log:o.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:o.crypto,prologue:o.prologue,s:o.staticKey,extensions:e._objectSpread2({streamMuxers:s,webtransportCerthashes:[]},o.extensions)},i),null===(l=o.metrics)||void 0===l||l.xxHandshakeSuccesses.increment()}catch(e){var c;throw null===(c=o.metrics)||void 0===c||c.xxHandshakeErrors.increment(),e}return a}))()}performHandshakeResponder(t,r,n,i){var o=this;return e._asyncToGenerator((function*(){var a,s=!0===(null==i?void 0:i.skipStreamMuxerNegotiation)?[]:[...o.components.upgrader.getStreamMuxers().keys()];try{var l;a=yield function(e,t){return Yk.apply(this,arguments)}({connection:t,privateKey:r,remoteIdentityKey:n,log:o.components.logger.forComponent("libp2p:noise:xxhandshake"),crypto:o.crypto,prologue:o.prologue,s:o.staticKey,extensions:e._objectSpread2({streamMuxers:s,webtransportCerthashes:[]},o.extensions)},i),null===(l=o.metrics)||void 0===l||l.xxHandshakeSuccesses.increment()}catch(e){var c;throw null===(c=o.metrics)||void 0===c||c.xxHandshakeErrors.increment(),e}return a}))()}createSecureConnection(t,r){var n=this;return e._asyncToGenerator((function*(){var i,o,[a,s]=(i=OA(),o=OA(),[{source:i.source,sink:o.sink},{source:o.source,sink:i.sink}]),l=t.unwrap();return yield lu(a,function(t,r){return function(){var n=e._wrapAsyncGenerator((function*(n){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(n);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1)for(var c=s.value,u=0;u<c.length;u+=65519){var d=u+65519;d>c.length&&(d=c.length);var h=void 0;h=c instanceof Uint8Array?t.encrypt(c.subarray(u,d)):t.encrypt(c.sublist(u,d)),null==r||r.encryptedPackets.increment(),yield new Fa(xk(h.byteLength),h)}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}));return function(e){return n.apply(this,arguments)}}()}(r,n.metrics),l,(e=>Hp(e,{lengthDecoder:Tk})),function(t,r){return function(){var n=e._wrapAsyncGenerator((function*(n){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(n);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1)for(var c=s.value,u=0;u<c.length;u+=LA){var d=u+LA;if(d>c.length&&(d=c.length),d-16<u)throw new Error("Invalid chunk");var h=c.sublist(u,d),p=c.subarray(u,d-16);try{var f=t.decrypt(h,p);null==r||r.decryptedPackets.increment(),yield f}catch(e){throw null==r||r.decryptErrors.increment(),e}}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}));return function(e){return n.apply(this,arguments)}}()}(r,n.metrics),a),s}))()}}function Zk(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new Jk(t,e)}var $k=Object.values(qe).map((e=>e.decoder)).reduce(((e,t)=>e.or(t))),Xk=e._wrapRegExp(/^a=fingerprint:(?:\w+-[0-9]+)\s((:?[0-9a-fA-F]{2})+)$/m,{fingerprint:1});function ex(e){var t=e.stringTuples().filter((e=>466===e[0])).map((e=>e[1]))[0];if(void 0===t||""===t)throw new ea("Couldn't find a certhash component of multiaddr: ".concat(e.toString()));return t}function tx(e){var t=function(e){return Ae($k.decode(e))}(ex(e)),r=function(e){switch(e){case 17:return"sha-1";case 18:return"sha-256";case 19:return"sha-512";default:throw new sf(e)}}(t.code),n=t.digest.reduce(((e,t)=>e+t.toString(16).padStart(2,"0")),""),i=n.match(/.{1,2}/g);if(null==i)throw new of(n,e.toString());return"".concat(r," ").concat(i.join(":").toUpperCase())}function rx(e,t){if(void 0===e.sdp)throw new ea("Can't munge a missing SDP");var r=e.sdp.includes("\r\n")?"\r\n":"\n";return e.sdp=e.sdp.replace(/\na=ice-ufrag:[^\n]*\n/,"\na=ice-ufrag:"+t+r).replace(/\na=ice-pwd:[^\n]*\n/,"\na=ice-pwd:"+t+r),e}var nx=ot("libp2p-webrtc-noise:");var ix=Ep?"iceconnectionstatechange":"connectionstatechange";function ox(){return ox=e._asyncToGenerator((function*(t,r,n){var i=t.createDataChannel("",{negotiated:!0,id:0});try{var o,a,s;if("client"===n.role){n.log.trace("client creating local offer");var l=yield t.createOffer();n.log.trace("client created local offer %s",l.sdp);var c=rx(l,r);n.log.trace("client setting local offer %s",c.sdp),yield t.setLocalDescription(c);var u=function(e,t){var{host:r,port:n,family:i}=e.toOptions(),o=tx(e);return{type:"answer",sdp:"v=0\no=- 0 0 IN IP".concat(i," ").concat(r,"\ns=-\nt=0 0\na=ice-lite\nm=application ").concat(n," UDP/DTLS/SCTP webrtc-datachannel\nc=IN IP").concat(i," ").concat(r,"\na=mid:0\na=ice-options:ice2\na=ice-ufrag:").concat(t,"\na=ice-pwd:").concat(t,"\na=fingerprint:").concat(o,"\na=setup:passive\na=sctp-port:5000\na=max-message-size:").concat(ip,"\na=candidate:1467250027 1 UDP 1467250027 ").concat(r," ").concat(n," typ host\na=end-of-candidates\n")}}(n.remoteAddr,r);n.log.trace("client setting server description %s",u.sdp),yield t.setRemoteDescription(u)}else{var d=function(e,t){var{host:r,port:n,family:i}=e.toOptions();return{type:"offer",sdp:"v=0\no=- 0 0 IN IP".concat(i," ").concat(r,"\ns=-\nc=IN IP").concat(i," ").concat(r,"\nt=0 0\na=ice-options:ice2,trickle\nm=application ").concat(n," UDP/DTLS/SCTP webrtc-datachannel\na=mid:0\na=setup:active\na=ice-ufrag:").concat(t,"\na=ice-pwd:").concat(t,"\na=fingerprint:sha-256 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00\na=sctp-port:5000\na=max-message-size:").concat(ip,"\na=candidate:1467250027 1 UDP 1467250027 ").concat(r," ").concat(n," typ host\na=end-of-candidates\n")}}(n.remoteAddr,r);n.log.trace("server setting client %s %s",d.type,d.sdp),yield t.setRemoteDescription(d),n.log.trace("server creating local answer");var h=yield t.createAnswer();n.log.trace("server created local answer");var p=rx(h,r);n.log.trace("server setting local description %s",h.sdp),yield t.setLocalDescription(p)}if("open"!==i.readyState&&(n.log.trace("%s wait for handshake channel to open, starting status %s",n.role,i.readyState),yield Bh(i,"open",n.signal)),n.log.trace("%s handshake channel opened",n.role),"server"===n.role){var f,v,y=null!==(f=null===(v=t.remoteFingerprint())||void 0===v?void 0:v.value)&&void 0!==f?f:"";n.remoteAddr=n.remoteAddr.encapsulate(function(e){var t=e.split(":").map((e=>parseInt(e,16))),r=Uint8Array.from(t),n=Ee(De.code,r);return sr("/certhash/".concat(q.encode(n.bytes)))}(y))}var g=function(e){var t;if(null!=e){var r=e.match(Xk);return null==r||null===(t=r.groups)||void 0===t?void 0:t.fingerprint}}(null===(o=t.localDescription)||void 0===o?void 0:o.sdp);if(null==g)throw new rf("Could not get fingerprint from local description sdp");n.log.trace("%s performing noise handshake",n.role);var m=function(e,t,r){var n=ot(e.trim().toLowerCase().replaceAll(":",""),"hex"),i=Ee(De.code,n),o=$k.decode(ex(t)),a=nx.byteLength+i.bytes.byteLength+o.byteLength;return _t("server"===r?[nx,o,i.bytes]:[nx,i.bytes,o],a)}(g,n.remoteAddr,n.role),w=Zk({prologueBytes:m})(n),b=Wp(e._objectSpread2({channel:i,direction:"outbound",handshake:!0,logger:n.logger},null!==(a=n.dataChannel)&&void 0!==a?a:{})),_=new Ip(n,{peerConnection:t,remoteAddr:n.remoteAddr,timeline:{open:Date.now()},metrics:n.events});t.addEventListener(ix,(()=>{switch(t.connectionState){case"failed":case"disconnected":case"closed":_.close().catch((e=>{n.log.error("error closing connection",e),_.abort(e)}))}})),null===(s=n.events)||void 0===s||s.increment({peer_connection:!0});var S=new Qp(n,{peerConnection:t,metrics:n.events,dataChannelOptions:n.dataChannel});if("client"===n.role)return n.log.trace("%s secure inbound",n.role),yield w.secureInbound(b,{remotePeer:n.remotePeerId,signal:n.signal,skipStreamMuxerNegotiation:!0}),n.log.trace("%s upgrade outbound",n.role),yield n.upgrader.upgradeOutbound(_,{skipProtection:!0,skipEncryption:!0,muxerFactory:S,signal:n.signal});n.log.trace("%s secure outbound",n.role);var P=yield w.secureOutbound(b,{remotePeer:n.remotePeerId,signal:n.signal,skipStreamMuxerNegotiation:!0});_.remoteAddr=_.remoteAddr.encapsulate("/p2p/".concat(P.remotePeer)),n.log.trace("%s upgrade inbound",n.role),yield n.upgrader.upgradeInbound(_,{skipProtection:!0,skipEncryption:!0,muxerFactory:S,signal:n.signal})}catch(e){throw i.close(),e}})),ox.apply(this,arguments)}function ax(){return(ax=e._asyncToGenerator((function*(t,r,n,i){null==i&&(i=yield RTCPeerConnection.generateCertificate({name:"ECDSA",namedCurve:"P-256"}));var o="function"==typeof n?yield n():n;return new RTCPeerConnection(e._objectSpread2(e._objectSpread2({},null!=o?o:{}),{},{certificates:[i]}))}))).apply(this,arguments)}function sx(e){return lx.apply(this,arguments)}function lx(){return(lx=e._asyncToGenerator((function*(e){var t=yield Ql(e),r=yield crypto.subtle.exportKey("pkcs8",t.privateKey);return["-----BEGIN PRIVATE KEY-----",...Ze(new Uint8Array(r),"base64pad").split(/(.{64})/).filter(Boolean),"-----END PRIVATE KEY-----"].join("\n")}))).apply(this,arguments)}class cx{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(e._defineProperty(this,"log",void 0),e._defineProperty(this,"metrics",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"init",void 0),e._defineProperty(this,"certificate",void 0),e._defineProperty(this,"privateKey",void 0),e._defineProperty(this,"emitter",void 0),e._defineProperty(this,"renewCertificateTask",void 0),e._defineProperty(this,Jo,!0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/webrtc-direct"),e._defineProperty(this,Ra,["@libp2p/transport"]),this.log=t.logger.forComponent("libp2p:webrtc-direct"),this.components=t,this.init=r,this.emitter=new Ia,null!=r.certificateLifespan&&null!=r.certificateRenewalThreshold&&r.certificateRenewalThreshold>=r.certificateLifespan)throw new ea("Certificate renewal threshold must be less than certificate lifespan");null!=t.metrics&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_webrtc-direct_dialer_events_total",{label:"event",help:"Total count of WebRTC-direct dial events by type"})})}start(){var t=this;return e._asyncToGenerator((function*(){t.certificate=yield t.getCertificate()}))()}stop(){var t=this;return e._asyncToGenerator((function*(){null!=t.renewCertificateTask&&clearTimeout(t.renewCertificateTask),t.certificate=void 0}))()}dial(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i;n.log("dial %a",t),r.signal.throwIfAborted();var o=t.getPeerId();null!=o&&(i=rc(o));var a=function(){return"libp2p+webrtc+v1/"+[...Array(arguments.length>0&&void 0!==arguments[0]?arguments[0]:32)].map((()=>np.at(Math.floor(Math.random()*np.length)))).join("")}(),s=yield function(e,t,r,n){return ax.apply(this,arguments)}("client",a,"function"==typeof n.init.rtcConfiguration?yield n.init.rtcConfiguration():null!==(e=n.init.rtcConfiguration)&&void 0!==e?e:{});try{var l;return yield function(e,t,r){return ox.apply(this,arguments)}(s,a,{role:"client",log:n.log,logger:n.components.logger,metrics:n.components.metrics,events:null===(l=n.metrics)||void 0===l?void 0:l.dialerEvents,signal:r.signal,remoteAddr:t,dataChannel:n.init.dataChannel,upgrader:r.upgrader,peerId:n.components.peerId,remotePeerId:i,privateKey:n.components.privateKey})}catch(e){throw s.close(),e}}))()}createListener(t){if(null==this.certificate)throw new wa;return new RA(this.components,e._objectSpread2(e._objectSpread2(e._objectSpread2({},this.init),t),{},{certificate:this.certificate,emitter:this.emitter}))}listenFilter(e){return e.filter(Vd.exactMatch)}dialFilter(e){return this.listenFilter(e)}getCertificate(t){var r=this;return e._asyncToGenerator((function*(){if(function(e){if(null==e)return!1;return"string"==typeof e.privateKey&&"string"==typeof e.pem&&"string"==typeof e.certhash}(r.init.certificate))return r.log("using provided TLS certificate"),r.init.certificate;var e=yield r.loadOrCreatePrivateKey(),{pem:n,certhash:i}=yield r.loadOrCreateCertificate(e,t);return{privateKey:yield sx(e),pem:n,certhash:i}}))()}loadOrCreatePrivateKey(){var t=this;return e._asyncToGenerator((function*(){var e;if(null!=t.privateKey)return t.privateKey;var r=null!==(e=t.init.certificateKeychainName)&&void 0!==e?e:"webrtc-direct-certificate-private-key",n=t.getKeychain();try{if(null==n)throw t.log("no keychain configured - not checking for stored private key"),new ua;t.log.trace("checking for stored private key"),t.privateKey=yield n.exportKey(r)}catch(e){if("NotFoundError"!==e.name)throw e;t.log.trace("generating private key"),t.privateKey=yield Fl("ECDSA","P-256"),null!=n?(t.log.trace("storing private key"),yield n.importKey(r,t.privateKey)):t.log("no keychain configured - not storing private key")}return t.privateKey}))()}loadOrCreateCertificate(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i,o;if(null!=n.certificate&&!0!==r)return n.certificate;var a=new Bc(null!==(e=n.init.certificateDatastoreKey)&&void 0!==e?e:"/libp2p/webrtc-direct/certificate"),s=yield Ql(t);try{if(!0===r)throw n.log.trace("forcing renewal of TLS certificate"),new ua;n.log.trace("checking for stored TLS certificate"),o=yield n.loadCertificate(a,s)}catch(e){if("NotFoundError"!==e.name)throw e;n.log.trace("generating new TLS certificate"),o=yield n.createCertificate(a,s)}var l=o.notAfter.getTime()-(null!==(i=n.init.certificateRenewalThreshold)&&void 0!==i?i:lp)-Date.now();return l<0&&(l=100),n.log("will renew TLS certificate after %d ms",l),n.renewCertificateTask=setTimeout((()=>{n.log("renewing TLS certificate"),n.getCertificate(!0).then((e=>{n.certificate=e,n.emitter.safeDispatchEvent("certificate:renew",{detail:e})})).catch((e=>{n.log.error("could not renew certificate - %e",e)}))}),l),{pem:o.toString("pem"),certhash:q.encode((yield De.digest(new Uint8Array(o.rawData))).bytes)}}))()}loadCertificate(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i=yield n.components.datastore.get(t),o=new DA(i),a=o.notAfter.getTime()-(null!==(e=n.init.certificateRenewalThreshold)&&void 0!==e?e:lp);if(Date.now()>a)throw n.log("stored TLS certificate has expired"),new ua;n.log("loaded certificate, expires in %d ms",a);var s=yield o.publicKey.export(crypto),l=yield crypto.subtle.exportKey("raw",s),c=yield crypto.subtle.exportKey("raw",r.publicKey);if(!nt(new Uint8Array(l,0,l.byteLength),new Uint8Array(c,0,c.byteLength)))throw n.log("stored TLS certificate public key did not match public key from private key"),new ua;return n.log("loaded certificate, expiry time is %o",a),o}))()}createCertificate(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i=new Date,o=new Date(Date.now()+(null!==(e=n.init.certificateLifespan)&&void 0!==e?e:12096e5));i.setMilliseconds(0),o.setMilliseconds(0);var a=yield GA.createSelfSigned({serialNumber:(100000n*BigInt(Math.random().toString().replace(".",""))).toString(16),name:"CN=example.com, C=US, L=CA, O=example, ST=CA",notBefore:i,notAfter:o,keys:r,extensions:[new aA(!1,void 0,!0)]},crypto);return null!=n.getKeychain()?(n.log.trace("storing TLS certificate"),yield n.components.datastore.put(t,ot(a.toString("pem")))):n.log("no keychain is configured so not storing TLS certificate since the private key will not be reused"),a}))()}getKeychain(){try{return this.components.keychain}catch(e){}}}function ux(e){return t=>new cx(t,e)}function dx(e){return t=>new ff(t,e)}var hx,px,fx,vx,yx,gx,mx,wx,bx,_x="/ipfs/bitswap/1.2.0",Sx=4194304,Px=Sx;!function(e){e.WantBlock="WantBlock",e.WantHave="WantHave"}(hx||(hx={})),function(e){e[e.WantBlock=0]="WantBlock",e[e.WantHave=1]="WantHave"}(px||(px={})),function(e){e.codec=()=>pl(px)}(hx||(hx={})),function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.cid&&e.cid.byteLength>0&&(t.uint32(10),t.bytes(e.cid)),null!=e.priority&&0!==e.priority&&(t.uint32(16),t.int32(e.priority)),null!=e.cancel&&(t.uint32(24),t.bool(e.cancel)),null!=e.wantType&&(t.uint32(32),hx.codec().encode(e.wantType,t)),null!=e.sendDontHave&&(t.uint32(40),t.bool(e.sendDontHave)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={cid:He(0),priority:0},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.cid=e.bytes();break;case 2:r.priority=e.int32();break;case 3:r.cancel=e.bool();break;case 4:r.wantType=hx.codec().decode(e);break;case 5:r.sendDontHave=e.bool();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(fx||(fx={})),function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==r.lengthDelimited&&t.fork(),null!=e.entries)for(var n of e.entries)t.uint32(10),fx.codec().encode(n,t);null!=e.full&&(t.uint32(16),t.bool(e.full)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={entries:[]},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:var a,s;if(null!=(null===(a=r.limits)||void 0===a?void 0:a.entries)&&n.entries.length===r.limits.entries)throw new vl('Decode error - map field "entries" had too many elements');n.entries.push(fx.codec().decode(e,e.uint32(),{limits:null===(s=r.limits)||void 0===s?void 0:s.entries$}));break;case 2:n.full=e.bool();break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(vx||(vx={})),function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.prefix&&e.prefix.byteLength>0&&(t.uint32(10),t.bytes(e.prefix)),null!=e.data&&e.data.byteLength>0&&(t.uint32(18),t.bytes(e.data)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={prefix:He(0),data:He(0)},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.prefix=e.bytes();break;case 2:r.data=e.bytes();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(yx||(yx={})),function(e){e.HaveBlock="HaveBlock",e.DoNotHaveBlock="DoNotHaveBlock"}(gx||(gx={})),function(e){e[e.HaveBlock=0]="HaveBlock",e[e.DoNotHaveBlock=1]="DoNotHaveBlock"}(mx||(mx={})),function(e){e.codec=()=>pl(mx)}(gx||(gx={})),function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.cid&&e.cid.byteLength>0&&(t.uint32(10),t.bytes(e.cid)),null!=e.type&&0!==mx[e.type]&&(t.uint32(16),gx.codec().encode(e.type,t)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={cid:He(0),type:gx.HaveBlock},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.cid=e.bytes();break;case 2:r.type=gx.codec().decode(e);break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(wx||(wx={})),function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==r.lengthDelimited&&t.fork(),null!=e.wantlist&&(t.uint32(10),vx.codec().encode(e.wantlist,t)),null!=e.blocks)for(var n of e.blocks)t.uint32(26),yx.codec().encode(n,t);if(null!=e.blockPresences)for(var i of e.blockPresences)t.uint32(34),wx.codec().encode(i,t);null!=e.pendingBytes&&0!==e.pendingBytes&&(t.uint32(40),t.int32(e.pendingBytes)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={blocks:[],blockPresences:[],pendingBytes:0},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:var a;n.wantlist=vx.codec().decode(e,e.uint32(),{limits:null===(a=r.limits)||void 0===a?void 0:a.wantlist});break;case 3:var s,l;if(null!=(null===(s=r.limits)||void 0===s?void 0:s.blocks)&&n.blocks.length===r.limits.blocks)throw new vl('Decode error - map field "blocks" had too many elements');n.blocks.push(yx.codec().decode(e,e.uint32(),{limits:null===(l=r.limits)||void 0===l?void 0:l.blocks$}));break;case 4:var c,u;if(null!=(null===(c=r.limits)||void 0===c?void 0:c.blockPresences)&&n.blockPresences.length===r.limits.blockPresences)throw new vl('Decode error - map field "blockPresences" had too many elements');n.blockPresences.push(wx.codec().decode(e,e.uint32(),{limits:null===(u=r.limits)||void 0===u?void 0:u.blockPresences$}));break;case 5:n.pendingBytes=e.int32();break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(bx||(bx={}));class Ex extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Block too large"),this.name="BlockTooLargeError"}}e._defineProperty(Ex,"name","BlockTooLargeError");function Ax(e,t,r,n,i,o){for(var a=0,s=!1,l=r;l<e.length;l++){var c=e[l],u=o(c);if(u>4193664)throw new Ex("Cannot send block as after encoding it is over the max message size");var d=i+u;if(d>n){s=!0;break}t.push(c),a++,i=d}return{hasMore:s,added:a,newSize:i}}function kx(e){return Ix(3,yx.encode(e))}function xx(e){return Ix(4,wx.encode(e))}function Tx(e){return Ix(1,fx.encode(e))}function Ix(e,t){return yt(e)+yt(t.byteLength)+t.byteLength}let Cx=class extends Ia{constructor(t){var r,n,i,o,a,s,l,c,u,d,h,p=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),e._defineProperty(this,"log",void 0),e._defineProperty(this,"libp2p",void 0),e._defineProperty(this,"routing",void 0),e._defineProperty(this,"protocols",void 0),e._defineProperty(this,"running",void 0),e._defineProperty(this,"maxInboundStreams",void 0),e._defineProperty(this,"maxOutboundStreams",void 0),e._defineProperty(this,"messageReceiveTimeout",void 0),e._defineProperty(this,"registrarIds",void 0),e._defineProperty(this,"metrics",void 0),e._defineProperty(this,"sendQueue",void 0),e._defineProperty(this,"runOnLimitedConnections",void 0),e._defineProperty(this,"maxOutgoingMessageSize",void 0),e._defineProperty(this,"maxIncomingMessageSize",void 0),this.log=t.logger.forComponent("helia:bitswap:network"),this.libp2p=t.libp2p,this.routing=t.routing,this.protocols=null!==(r=p.protocols)&&void 0!==r?r:[_x],this.registrarIds=[],this.running=!1,this._onStream=this._onStream.bind(this),this.maxInboundStreams=null!==(n=p.maxInboundStreams)&&void 0!==n?n:1024,this.maxOutboundStreams=null!==(i=p.maxOutboundStreams)&&void 0!==i?i:1024,this.messageReceiveTimeout=null!==(o=p.messageReceiveTimeout)&&void 0!==o?o:5e3,this.runOnLimitedConnections=null!==(a=p.runOnLimitedConnections)&&void 0!==a&&a,this.maxIncomingMessageSize=null!==(s=p.maxIncomingMessageSize)&&void 0!==s?s:Sx,this.maxOutgoingMessageSize=null!==(l=null!==(c=p.maxOutgoingMessageSize)&&void 0!==c?c:p.maxIncomingMessageSize)&&void 0!==l?l:Px,this.metrics={blocksSent:null===(u=t.metrics)||void 0===u?void 0:u.registerCounter("helia_bitswap_sent_blocks_total"),dataSent:null===(d=t.metrics)||void 0===d?void 0:d.registerCounter("helia_bitswap_sent_data_bytes_total")},this.sendQueue=new jh({concurrency:null!==(h=p.messageSendConcurrency)&&void 0!==h?h:50,metrics:t.metrics,metricName:"helia_bitswap_message_send_queue"}),this.sendQueue.addEventListener("error",(e=>{this.log.error("error sending wantlist to peer",e.detail)}))}start(){var t=this;return e._asyncToGenerator((function*(){if(!t.running){t.running=!0,yield t.libp2p.handle(t.protocols,t._onStream,{maxInboundStreams:t.maxInboundStreams,maxOutboundStreams:t.maxOutboundStreams,runOnLimitedConnection:t.runOnLimitedConnections});var e={onConnect:e=>{t.safeDispatchEvent("peer:connected",{detail:e})},onDisconnect:e=>{t.safeDispatchEvent("peer:disconnected",{detail:e})}};for(var r of(t.registrarIds=[],t.protocols))t.registrarIds.push(yield t.libp2p.register(r,e));t.libp2p.getConnections().forEach((e=>{t.safeDispatchEvent("peer:connected",{detail:e.remotePeer})}))}}))()}stop(){var t=this;return e._asyncToGenerator((function*(){if(t.running=!1,yield t.libp2p.unhandle(t.protocols),null!=t.registrarIds){for(var e of t.registrarIds)t.libp2p.unregister(e);t.registrarIds=[]}}))()}_onStream(t){var r=this;if(this.running){var{stream:n,connection:i}=t;Promise.resolve().then(e._asyncToGenerator((function*(){r.log("incoming new bitswap %s stream from %p",n.protocol,i.remotePeer);var t=()=>{"open"===n.status?n.abort(new ma("Incoming Bitswap stream timed out after ".concat(r.messageReceiveTimeout,"ms"))):r.log("stream aborted with status %s",n.status)},o=AbortSignal.timeout(r.messageReceiveTimeout);o.addEventListener("abort",t),yield n.closeWrite(),yield lu(n,(e=>Hp(e,{maxDataLength:r.maxIncomingMessageSize})),function(){var a=e._asyncToGenerator((function*(a){var s,l=!1,c=!1;try{for(var u,d=e._asyncIterator(a);l=!(u=yield d.next()).done;l=!1){var h=u.value;try{var p=bx.decode(h);r.log("incoming new bitswap %s message from %p on stream",n.protocol,i.remotePeer,n.id),r.safeDispatchEvent("bitswap:message",{detail:{peer:i.remotePeer,message:p}}),o.removeEventListener("abort",t),(o=AbortSignal.timeout(r.messageReceiveTimeout)).addEventListener("abort",t)}catch(e){r.log.error("error reading incoming bitswap message from %p on stream",i.remotePeer,n.id,e),n.abort(e);break}}}catch(e){c=!0,s=e}finally{try{l&&null!=d.return&&(yield d.return())}finally{if(c)throw s}}}));return function(e){return a.apply(this,arguments)}}())}))).catch((e=>{this.log.error("error handling incoming stream from %p",i.remotePeer,e),n.abort(e)}))}}findProviders(t,r){var n=this;return e._wrapAsyncGenerator((function*(){var i;null==r||null===(i=r.onProgress)||void 0===i||i.call(r,new Ih("bitswap:network:find-providers",t));var o,a=!1,s=!1;try{for(var l,c=e._asyncIterator(n.routing.findProviders(t,r));a=!(l=yield e._awaitAsyncGenerator(c.next())).done;a=!1){var u=l.value;(yield e._awaitAsyncGenerator(n.libp2p.isDialable(u.multiaddrs,{runOnLimitedConnection:n.runOnLimitedConnections})))&&(yield u)}}catch(e){s=!0,o=e}finally{try{a&&null!=c.return&&(yield e._awaitAsyncGenerator(c.return()))}finally{if(s)throw o}}}))()}findAndConnect(t,r){var n=this;return e._asyncToGenerator((function*(){var i;null!=(null==r?void 0:r.providers)&&(yield Promise.all(r.providers.map(function(){var t=e._asyncToGenerator((function*(e){return n.connectTo(e).catch((e=>{n.log.error("could not connect to supplied provider - %e",e)}))}));return function(e){return t.apply(this,arguments)}}()))),yield Nc(Qc(Lc(n.findProviders(t,r),null!==(i=null==r?void 0:r.maxProviders)&&void 0!==i?i:3),function(){var t=e._asyncToGenerator((function*(e){return n.connectTo(e.id,r)}));return function(e){return t.apply(this,arguments)}}())).catch((e=>{n.log.error(e)}))}))()}sendMessage(t,r,n){var i=this;return e._asyncToGenerator((function*(){if(!i.running)throw new Error("network isn't running");var o=i.sendQueue.queue.find((e=>t.equals(e.options.peerId)&&"queued"===e.status));if(null!=o)return o.options.message=function(e,t){for(var[r,n]of t.wantlist.entries()){var i,o,a,s=e.wantlist.get(r);null!=s&&(s.priority>n.priority&&(n.priority=s.priority),n.cancel=null!==(i=n.cancel)&&void 0!==i?i:s.cancel,n.wantType=null!==(o=n.wantType)&&void 0!==o?o:s.wantType,n.sendDontHave=null!==(a=n.sendDontHave)&&void 0!==a?a:s.sendDontHave),e.wantlist.set(r,n)}for(var[l,c]of t.blockPresences.entries())e.blockPresences.set(l,c);for(var[u,d]of t.blocks.entries())e.blocks.set(u,d);return t.full&&!e.full&&(e.full=!0),e}(o.options.message,r),void(yield o.join({signal:null==n?void 0:n.signal}));yield i.sendQueue.add(function(){var r=e._asyncToGenerator((function*(e){var r,n=null==e?void 0:e.message;if(null==n)throw new ea("No message to send");i.log("sendMessage to %p",t),null==e||null===(r=e.onProgress)||void 0===r||r.call(e,new Ih("bitswap:network:send-wantlist",t));var o=yield i.libp2p.dialProtocol(t,_x,e);yield o.closeRead();try{yield lu(function*(e,t){for(var r=[...e.wantlist.values()],n=[...e.blockPresences.values()],i=[...e.blocks.values()],o=0,a=0,s=0,l=!1;;){var c,u={wantlist:{full:null!==(c=e.full)&&void 0!==c&&c,entries:[]},blockPresences:[],blocks:[],pendingBytes:0},d=bx.encode(u).byteLength,{added:h,hasMore:p,newSize:f}=Ax(i,u.blocks,s,t,d,kx);s+=h,d=f;var v=p;({added:h,hasMore:p,newSize:f}=Ax(n,u.blockPresences,a,t,d,xx)),a+=h,d=f;var y=p;if(({added:h,hasMore:p,newSize:f}=Ax(r,u.wantlist.entries,o,t,d,Tx)),o+=h,d=f,(l=!v&&!y&&!p)||(u.wantlist.full=!1),yield bx.encode(u),l)break}}(n,i.maxOutgoingMessageSize),(e=>Vp(e)),o),yield o.close(e)}catch(r){var a;null==e||null===(a=e.onProgress)||void 0===a||a.call(e,new Ih("bitswap:network:send-wantlist:error",{peer:t,error:r})),i.log.error("error sending message to %p",t,r),o.abort(r)}i._updateSentStats(n.blocks)}));return function(e){return r.apply(this,arguments)}}(),{peerId:t,signal:null==n?void 0:n.signal,message:r})}))()}connectTo(t,r){var n=this;return e._asyncToGenerator((function*(){var e;if(!n.running)throw new wa("Network isn't running");null==r||null===(e=r.onProgress)||void 0===e||e.call(r,new Ih("bitswap:network:dial",t));var[i]=yield Promise.all([n.libp2p.dial(t,r),Bh(n.libp2p,"peer:identify",null==r?void 0:r.signal,{filter:e=>{if(!e.detail.peerId.equals(t))return!1;if(e.detail.protocols.includes(_x))return!0;throw new va("".concat(t," did not support ").concat(_x))}})]);return i}))()}_updateSentStats(e){var t,r,n=0;for(var i of e.values())n+=i.data.byteLength;null===(t=this.metrics.dataSent)||void 0===t||t.increment(n),null===(r=this.metrics.blocksSent)||void 0===r||r.increment(e.size)}};class Bx{constructor(){var t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];e._defineProperty(this,"full",void 0),e._defineProperty(this,"pendingBytes",void 0),e._defineProperty(this,"wantlist",void 0),e._defineProperty(this,"blocks",void 0),e._defineProperty(this,"blockPresences",void 0),this.full=t,this.wantlist=new Map,this.blocks=new Map,this.blockPresences=new Map,this.pendingBytes=0}addWantlistEntry(e,t){var r=z.encode(e.multihash.bytes);this.wantlist.set(r,t)}addBlockPresence(e,t){var r=z.encode(e.multihash.bytes);this.blockPresences.set(r,t)}addBlock(e,t){var r=z.encode(e.multihash.bytes);this.blocks.set(r,t)}}function Nx(e){return function(e){var t=new Uint8Array(e.reduce(((e,t)=>e+yt(t)),0)),r=0;for(var n of e)t=wt(n,t,r),r+=yt(n);return t}([e.version,e.code,e.multihash.code,e.multihash.digest.byteLength])}class Dx{constructor(t,r){var n;e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"blockstore",void 0),e._defineProperty(this,"network",void 0),e._defineProperty(this,"wants",void 0),e._defineProperty(this,"exchangeCount",void 0),e._defineProperty(this,"bytesSent",void 0),e._defineProperty(this,"bytesReceived",void 0),e._defineProperty(this,"lastExchange",void 0),e._defineProperty(this,"maxSizeReplaceHasWithBlock",void 0),e._defineProperty(this,"log",void 0),this.peerId=t.peerId,this.blockstore=t.blockstore,this.network=t.network,this.wants=new Map,this.log=t.logger.forComponent("helia:bitswap:ledger:".concat(t.peerId)),this.exchangeCount=0,this.bytesSent=0,this.bytesReceived=0,this.maxSizeReplaceHasWithBlock=null!==(n=r.maxSizeReplaceHasWithBlock)&&void 0!==n?n:1024}sentBytes(e){this.exchangeCount++,this.lastExchange=(new Date).getTime(),this.bytesSent+=e}receivedBytes(e){this.exchangeCount++,this.lastExchange=(new Date).getTime(),this.bytesReceived+=e}debtRatio(){return this.bytesSent/(this.bytesReceived+1)}sendBlocksToPeer(t){var r=this;return e._asyncToGenerator((function*(){var e=new Bx,n=new Set;for(var[i,o]of r.wants.entries())try{var a=yield r.blockstore.get(o.cid,t);o.wantType===hx.WantHave?a.byteLength<r.maxSizeReplaceHasWithBlock?(r.log("sending have and block for %c",o.cid),n.add(i),e.addBlock(o.cid,{data:a,prefix:Nx(o.cid)})):(r.log("sending have for %c",o.cid),e.addBlockPresence(o.cid,{cid:o.cid.bytes,type:gx.HaveBlock})):(r.log("sending block for %c",o.cid),n.add(i),e.addBlock(o.cid,{data:a,prefix:Nx(o.cid)}))}catch(t){if("NotFoundError"!==t.name)throw t;if(r.log("do not have block for %c",o.cid),!o.sendDontHave)continue;if(!0===o.sentDoNotHave)continue;o.sentDoNotHave=!0,e.addBlockPresence(o.cid,{cid:o.cid.bytes,type:gx.DoNotHaveBlock})}if(e.blocks.size>0||e.blockPresences.size>0)for(var s of(r.log("sending message"),yield r.network.sendMessage(r.peerId,e,t),r.log("sent message"),r.sentBytes([...e.blocks.values()].reduce(((e,t)=>e+t.data.byteLength),0)),n))r.wants.delete(s)}))()}}class Gx{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"blockstore",void 0),e._defineProperty(this,"network",void 0),e._defineProperty(this,"ledgerMap",void 0),e._defineProperty(this,"maxSizeReplaceHasWithBlock",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"logger",void 0),this.blockstore=t.blockstore,this.network=t.network,this.maxSizeReplaceHasWithBlock=r.maxSizeReplaceHasWithBlock,this.log=t.logger.forComponent("helia:bitswap:peer-want-lists"),this.logger=t.logger,this.ledgerMap=Ah({name:"helia_bitswap_ledger_map",metrics:t.metrics}),this.network.addEventListener("bitswap:message",(e=>{this.receiveMessage(e.detail.peer,e.detail.message).catch((t=>{this.log.error("error receiving bitswap message from %p",e.detail.peer,t)}))})),this.network.addEventListener("peer:disconnected",(e=>{this.peerDisconnected(e.detail)}))}ledgerForPeer(e){var t=this.ledgerMap.get(e);if(null!=t)return{peer:t.peerId,value:t.debtRatio(),sent:t.bytesSent,received:t.bytesReceived,exchanged:t.exchangeCount}}wantListForPeer(e){var t=this.ledgerMap.get(e);if(null!=t)return[...t.wants.values()]}peers(){return Array.from(this.ledgerMap.values()).map((e=>e.peerId))}receiveMessage(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i,o=n.ledgerMap.get(t);if(null==o&&(o=new Dx({peerId:t,blockstore:n.blockstore,network:n.network,logger:n.logger},{maxSizeReplaceHasWithBlock:n.maxSizeReplaceHasWithBlock}),n.ledgerMap.set(t,o)),o.receivedBytes(null!==(e=null===(i=r.blocks)||void 0===i?void 0:i.reduce(((e,t)=>e+t.data.byteLength),0))&&void 0!==e?e:0),null!=r.wantlist)for(var a of(!0===r.wantlist.full&&o.wants.clear(),r.wantlist.entries)){var s,l,c=je.decode(a.cid),u=Ze(c.multihash.bytes,"base64");if(!0===a.cancel)n.log("peer %p cancelled want of block for %c",t,c),o.wants.delete(u);else a.wantType===hx.WantHave?n.log("peer %p wanted block presence for %c",t,c):n.log("peer %p wanted block for %c",t,c),o.wants.set(u,{cid:c,priority:a.priority,wantType:null!==(s=a.wantType)&&void 0!==s?s:hx.WantBlock,sendDontHave:null!==(l=a.sendDontHave)&&void 0!==l&&l})}n.log("send blocks to peer"),yield o.sendBlocksToPeer()}))()}receivedBlock(t,r){var n=this;return e._asyncToGenerator((function*(){var i=Ze(t.multihash.bytes,"base64"),o=[];for(var a of n.ledgerMap.values())a.wants.has(i)&&o.push(a);yield Promise.all(o.map(function(){var t=e._asyncToGenerator((function*(e){return e.sendBlocksToPeer(r)}));return function(e){return t.apply(this,arguments)}}()))}))()}peerDisconnected(e){this.ledgerMap.delete(e)}}var Rx=new WeakMap;let Ox=class{constructor(){e._classPrivateFieldInitSpec(this,Rx,[])}enqueue(t,r){var n={priority:(r=e._objectSpread2({priority:0},r)).priority,id:r.id,run:t};if(0===this.size||e._classPrivateFieldGet2(Rx,this)[this.size-1].priority>=r.priority)e._classPrivateFieldGet2(Rx,this).push(n);else{var i=function(e,t,r){for(var n=0,i=e.length;i>0;){var o=Math.trunc(i/2),a=n+o;r(e[a],t)<=0?(n=++a,i-=o+1):i=o}return n}(e._classPrivateFieldGet2(Rx,this),n,((e,t)=>t.priority-e.priority));e._classPrivateFieldGet2(Rx,this).splice(i,0,n)}}setPriority(t,r){var n=e._classPrivateFieldGet2(Rx,this).findIndex((e=>e.id===t));if(-1===n)throw new ReferenceError('No promise function with the id "'.concat(t,'" exists in the queue.'));var[i]=e._classPrivateFieldGet2(Rx,this).splice(n,1);this.enqueue(i.run,{priority:r,id:t})}dequeue(){var t=e._classPrivateFieldGet2(Rx,this).shift();return null==t?void 0:t.run}filter(t){return e._classPrivateFieldGet2(Rx,this).filter((e=>e.priority===t.priority)).map((e=>e.run))}get size(){return e._classPrivateFieldGet2(Rx,this).length}};var Lx=new WeakMap,Mx=new WeakMap,jx=new WeakMap,Fx=new WeakMap,Ux=new WeakMap,zx=new WeakMap,Vx=new WeakMap,qx=new WeakMap,Hx=new WeakMap,Kx=new WeakMap,Wx=new WeakMap,Qx=new WeakMap,Yx=new WeakMap,Jx=new WeakMap,Zx=new WeakMap,$x=new WeakSet;class Xx extends No{constructor(t){var r,n,i,o;if(super(),e._classPrivateMethodInitSpec(this,$x),e._classPrivateFieldInitSpec(this,Lx,void 0),e._classPrivateFieldInitSpec(this,Mx,void 0),e._classPrivateFieldInitSpec(this,jx,0),e._classPrivateFieldInitSpec(this,Fx,void 0),e._classPrivateFieldInitSpec(this,Ux,void 0),e._classPrivateFieldInitSpec(this,zx,0),e._classPrivateFieldInitSpec(this,Vx,void 0),e._classPrivateFieldInitSpec(this,qx,void 0),e._classPrivateFieldInitSpec(this,Hx,void 0),e._classPrivateFieldInitSpec(this,Kx,void 0),e._classPrivateFieldInitSpec(this,Wx,0),e._classPrivateFieldInitSpec(this,Qx,void 0),e._classPrivateFieldInitSpec(this,Yx,void 0),e._classPrivateFieldInitSpec(this,Jx,void 0),e._classPrivateFieldInitSpec(this,Zx,1n),e._defineProperty(this,"timeout",void 0),!("number"==typeof(t=e._objectSpread2({carryoverConcurrencyCount:!1,intervalCap:Number.POSITIVE_INFINITY,interval:0,concurrency:Number.POSITIVE_INFINITY,autoStart:!0,queueClass:Ox},t)).intervalCap&&t.intervalCap>=1))throw new TypeError("Expected `intervalCap` to be a number from 1 and up, got `".concat(null!==(r=null===(n=t.intervalCap)||void 0===n?void 0:n.toString())&&void 0!==r?r:"","` (").concat(typeof t.intervalCap,")"));if(void 0===t.interval||!(Number.isFinite(t.interval)&&t.interval>=0))throw new TypeError("Expected `interval` to be a finite number >= 0, got `".concat(null!==(i=null===(o=t.interval)||void 0===o?void 0:o.toString())&&void 0!==i?i:"","` (").concat(typeof t.interval,")"));e._classPrivateFieldSet2(Lx,this,t.carryoverConcurrencyCount),e._classPrivateFieldSet2(Mx,this,t.intervalCap===Number.POSITIVE_INFINITY||0===t.interval),e._classPrivateFieldSet2(Fx,this,t.intervalCap),e._classPrivateFieldSet2(Ux,this,t.interval),e._classPrivateFieldSet2(Hx,this,new t.queueClass),e._classPrivateFieldSet2(Kx,this,t.queueClass),this.concurrency=t.concurrency,this.timeout=t.timeout,e._classPrivateFieldSet2(Jx,this,!0===t.throwOnTimeout),e._classPrivateFieldSet2(Yx,this,!1===t.autoStart)}get concurrency(){return e._classPrivateFieldGet2(Qx,this)}set concurrency(t){if(!("number"==typeof t&&t>=1))throw new TypeError("Expected `concurrency` to be a number from 1 and up, got `".concat(t,"` (").concat(typeof t,")"));e._classPrivateFieldSet2(Qx,this,t),e._assertClassBrand($x,this,lT).call(this)}setPriority(t,r){e._classPrivateFieldGet2(Hx,this).setPriority(t,r)}add(t){return e._asyncToGenerator((function*(){var r,n,i,o,a=arguments,s=this,l=a.length>1&&void 0!==a[1]?a[1]:{};return null!==(n=(r=l).id)&&void 0!==n||(r.id=(e._classPrivateFieldSet2(Zx,s,(i=e._classPrivateFieldGet2(Zx,s),o=i++,i)),o).toString()),l=e._objectSpread2({timeout:s.timeout,throwOnTimeout:e._classPrivateFieldGet2(Jx,s)},l),new Promise(((r,n)=>{e._classPrivateFieldGet2(Hx,s).enqueue(e._asyncToGenerator((function*(){var i,o;e._classPrivateFieldSet2(Wx,s,(i=e._classPrivateFieldGet2(Wx,s),++i)),e._classPrivateFieldSet2(jx,s,(o=e._classPrivateFieldGet2(jx,s),++o));try{var a;null===(a=l.signal)||void 0===a||a.throwIfAborted();var c=t({signal:l.signal});l.timeout&&(c=Sp(Promise.resolve(c),{milliseconds:l.timeout})),l.signal&&(c=Promise.race([c,e._assertClassBrand($x,s,cT).call(s,l.signal)]));var u=yield c;r(u),s.emit("completed",u)}catch(e){if(e instanceof mp&&!l.throwOnTimeout)return void r();n(e),s.emit("error",e)}finally{e._assertClassBrand($x,s,rT).call(s)}})),l),s.emit("add"),e._assertClassBrand($x,s,oT).call(s)}))}))()}addAll(t,r){var n=this;return e._asyncToGenerator((function*(){return Promise.all(t.map(function(){var t=e._asyncToGenerator((function*(e){return n.add(e,r)}));return function(e){return t.apply(this,arguments)}}()))}))()}start(){return e._classPrivateFieldGet2(Yx,this)?(e._classPrivateFieldSet2(Yx,this,!1),e._assertClassBrand($x,this,lT).call(this),this):this}pause(){e._classPrivateFieldSet2(Yx,this,!0)}clear(){e._classPrivateFieldSet2(Hx,this,new(e._classPrivateFieldGet2(Kx,this)))}onEmpty(){var t=this;return e._asyncToGenerator((function*(){0!==e._classPrivateFieldGet2(Hx,t).size&&(yield e._assertClassBrand($x,t,dT).call(t,"empty"))}))()}onSizeLessThan(t){var r=this;return e._asyncToGenerator((function*(){e._classPrivateFieldGet2(Hx,r).size<t||(yield e._assertClassBrand($x,r,dT).call(r,"next",(()=>e._classPrivateFieldGet2(Hx,r).size<t)))}))()}onIdle(){var t=this;return e._asyncToGenerator((function*(){0===e._classPrivateFieldGet2(Wx,t)&&0===e._classPrivateFieldGet2(Hx,t).size||(yield e._assertClassBrand($x,t,dT).call(t,"idle"))}))()}get size(){return e._classPrivateFieldGet2(Hx,this).size}sizeBy(t){return e._classPrivateFieldGet2(Hx,this).filter(t).length}get pending(){return e._classPrivateFieldGet2(Wx,this)}get isPaused(){return e._classPrivateFieldGet2(Yx,this)}}function eT(t){return e._classPrivateFieldGet2(Mx,t)||e._classPrivateFieldGet2(jx,t)<e._classPrivateFieldGet2(Fx,t)}function tT(t){return e._classPrivateFieldGet2(Wx,t)<e._classPrivateFieldGet2(Qx,t)}function rT(){var t;e._classPrivateFieldSet2(Wx,this,(t=e._classPrivateFieldGet2(Wx,this),--t)),e._assertClassBrand($x,this,oT).call(this),this.emit("next")}function nT(){e._assertClassBrand($x,this,sT).call(this),e._assertClassBrand($x,this,aT).call(this),e._classPrivateFieldSet2(qx,this,void 0)}function iT(t){var r=Date.now();if(void 0===e._classPrivateFieldGet2(Vx,t)){var n=e._classPrivateFieldGet2(zx,t)-r;if(!(n<0))return void 0===e._classPrivateFieldGet2(qx,t)&&e._classPrivateFieldSet2(qx,t,setTimeout((()=>{e._assertClassBrand($x,t,nT).call(t)}),n)),!0;e._classPrivateFieldSet2(jx,t,e._classPrivateFieldGet2(Lx,t)?e._classPrivateFieldGet2(Wx,t):0)}return!1}function oT(){if(0===e._classPrivateFieldGet2(Hx,this).size)return e._classPrivateFieldGet2(Vx,this)&&clearInterval(e._classPrivateFieldGet2(Vx,this)),e._classPrivateFieldSet2(Vx,this,void 0),this.emit("empty"),0===e._classPrivateFieldGet2(Wx,this)&&this.emit("idle"),!1;if(!e._classPrivateFieldGet2(Yx,this)){var t=!e._classPrivateGetter($x,this,iT);if(e._classPrivateGetter($x,this,eT)&&e._classPrivateGetter($x,this,tT)){var r=e._classPrivateFieldGet2(Hx,this).dequeue();return!!r&&(this.emit("active"),r(),t&&e._assertClassBrand($x,this,aT).call(this),!0)}}return!1}function aT(){e._classPrivateFieldGet2(Mx,this)||void 0!==e._classPrivateFieldGet2(Vx,this)||(e._classPrivateFieldSet2(Vx,this,setInterval((()=>{e._assertClassBrand($x,this,sT).call(this)}),e._classPrivateFieldGet2(Ux,this))),e._classPrivateFieldSet2(zx,this,Date.now()+e._classPrivateFieldGet2(Ux,this)))}function sT(){0===e._classPrivateFieldGet2(jx,this)&&0===e._classPrivateFieldGet2(Wx,this)&&e._classPrivateFieldGet2(Vx,this)&&(clearInterval(e._classPrivateFieldGet2(Vx,this)),e._classPrivateFieldSet2(Vx,this,void 0)),e._classPrivateFieldSet2(jx,this,e._classPrivateFieldGet2(Lx,this)?e._classPrivateFieldGet2(Wx,this):0),e._assertClassBrand($x,this,lT).call(this)}function lT(){for(;e._assertClassBrand($x,this,oT).call(this););}function cT(e){return uT.apply(this,arguments)}function uT(){return(uT=e._asyncToGenerator((function*(e){return new Promise(((t,r)=>{e.addEventListener("abort",(()=>{r(e.reason)}),{once:!0})}))}))).apply(this,arguments)}function dT(e,t){return hT.apply(this,arguments)}function hT(){return hT=e._asyncToGenerator((function*(e,t){return new Promise((r=>{var n=()=>{t&&!t()||(this.off(e,n),r())};this.on(e,n)}))})),hT.apply(this,arguments)}function pT(e){var t=[ST.A];return null==e?t:Array.isArray(e)?0===e.length?t:e:[e]}function fT(e){var t,r,n,i,o,a,s,l,c,u,d,h,p,f,v;return{Status:null!==(t=e.Status)&&void 0!==t?t:0,TC:null!==(r=null!==(n=e.TC)&&void 0!==n?n:e.flag_tc)&&void 0!==r&&r,RD:null!==(i=null!==(o=e.RD)&&void 0!==o?o:e.flag_rd)&&void 0!==i&&i,RA:null!==(a=null!==(s=e.RA)&&void 0!==s?s:e.flag_ra)&&void 0!==a&&a,AD:null!==(l=null!==(c=e.AD)&&void 0!==c?c:e.flag_ad)&&void 0!==l&&l,CD:null!==(u=null!==(d=e.CD)&&void 0!==d?d:e.flag_cd)&&void 0!==u&&u,Question:(null!==(h=null!==(p=e.Question)&&void 0!==p?p:e.questions)&&void 0!==h?h:[]).map((e=>({name:e.name,type:ST[e.type]}))),Answer:(null!==(f=null!==(v=e.Answer)&&void 0!==v?v:e.answers)&&void 0!==f?f:[]).map((e=>{var t,r;return{name:e.name,type:ST[e.type],TTL:null!==(t=null!==(r=e.TTL)&&void 0!==r?r:e.ttl)&&void 0!==t?t:60,data:e.data instanceof Uint8Array?Ze(e.data):e.data}}))}}var vT,yT;function gT(t){var r,n=new Xx({concurrency:null!==(r=(arguments.length>1&&void 0!==arguments[1]?arguments[1]:{}).queryConcurrency)&&void 0!==r?r:4});return function(){var r=e._asyncToGenerator((function*(r){var i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=new URLSearchParams;a.set("name",r),pT(o.types).forEach((e=>{a.append("type",ST[e])})),null===(i=o.onProgress)||void 0===i||i.call(o,new Ih("dns:query",{detail:r}));var s=yield n.add(e._asyncToGenerator((function*(){var e,r=yield fetch("".concat(t,"?").concat(a),{headers:{accept:"application/dns-json"},signal:null==o?void 0:o.signal});if(200!==r.status)throw new Error("Unexpected HTTP status: ".concat(r.status," - ").concat(r.statusText));var n=fT(yield r.json());return null===(e=o.onProgress)||void 0===e||e.call(o,new Ih("dns:response",{detail:n})),n})),{signal:o.signal});if(null==s)throw new Error("No DNS response received");return s}));return function(e){return r.apply(this,arguments)}}()}var mT=(yT||(yT=1,vT=function(e){if(!e)throw Error("hashlru must have a max value, of type number, greater than 0");var t=0,r=Object.create(null),n=Object.create(null);function i(i,o){r[i]=o,++t>=e&&(t=0,n=r,r=Object.create(null))}return{has:function(e){return void 0!==r[e]||void 0!==n[e]},remove:function(e){void 0!==r[e]&&(r[e]=void 0),void 0!==n[e]&&(n[e]=void 0)},get:function(e){var t=r[e];return void 0!==t?t:void 0!==(t=n[e])?(i(e,t),t):void 0},set:function(e,t){void 0!==r[e]?r[e]=t:i(e,t)},clear:function(){r=Object.create(null),n=Object.create(null)}}}),vT),wT=e.getDefaultExportFromCjs(mT);class bT{constructor(t){e._defineProperty(this,"lru",void 0),this.lru=wT(t)}get(e,t){var r=!0,n=[];for(var i of t){var o=this.getAnswers(e,i);if(0===o.length){r=!1;break}n.push(...o)}if(r)return fT({answers:n})}getAnswers(t,r){var n="".concat(t.toLowerCase(),"-").concat(r),i=this.lru.get(n);if(null!=i){var o=i.filter((e=>e.expires>Date.now())).map((t=>{var{expires:r,value:n}=t;return e._objectSpread2(e._objectSpread2({},n),{},{TTL:Math.round((r-Date.now())/1e3),type:ST[n.type]})}));return 0===o.length&&this.lru.remove(n),o}return[]}add(e,t){var r,n,i="".concat(e.toLowerCase(),"-").concat(t.type),o=null!==(r=this.lru.get(i))&&void 0!==r?r:[];o.push({expires:Date.now()+1e3*(null!==(n=t.TTL)&&void 0!==n?n:60),value:t}),this.lru.set(i,o)}remove(e,t){var r="".concat(e.toLowerCase(),"-").concat(t);this.lru.remove(r)}clear(){this.lru.clear()}}let _T=class{constructor(t){var r,n,i;e._defineProperty(this,"resolvers",void 0),e._defineProperty(this,"cache",void 0),this.resolvers={},this.cache=(i=null!==(r=t.cacheSize)&&void 0!==r?r:1e3,new bT(i)),Object.entries(null!==(n=t.resolvers)&&void 0!==n?n:{}).forEach((e=>{var[t,r]=e;Array.isArray(r)||(r=[r]),t.endsWith(".")||(t="".concat(t,".")),this.resolvers[t]=r})),null==this.resolvers["."]&&(this.resolvers["."]=[gT("https://cloudflare-dns.com/dns-query"),gT("https://dns.google/resolve")])}query(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i,o,a=r.length>1&&void 0!==r[1]?r[1]:{},s=pT(a.types),l=!1!==a.cached?n.cache.get(t,s):void 0;if(null!=l)return null===(o=a.onProgress)||void 0===o||o.call(a,new Ih("dns:cache",{detail:l})),l;var c="".concat(t.split(".").pop(),"."),u=(null!==(i=n.resolvers[c])&&void 0!==i?i:n.resolvers["."]).sort((()=>Math.random()>.5?-1:1)),d=[];for(var h of u){var p;if(!0===(null===(p=a.signal)||void 0===p?void 0:p.aborted))break;try{var f=yield h(t,e._objectSpread2(e._objectSpread2({},a),{},{types:s}));for(var v of f.Answer)n.cache.add(t,v);return f}catch(e){var y;d.push(e),null===(y=a.onProgress)||void 0===y||y.call(a,new Ih("dns:error",{detail:e}))}}if(1===d.length)throw d[0];throw new AggregateError(d,"DNS lookup of ".concat(t," ").concat(s," failed"))}))()}};var ST;function PT(){return new _T(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{})}!function(e){e[e.A=1]="A",e[e.CNAME=5]="CNAME",e[e.TXT=16]="TXT",e[e.AAAA=28]="AAAA"}(ST||(ST={}));var ET=["string","number","bigint","symbol"],AT=["Function","Generator","AsyncGenerator","GeneratorFunction","AsyncGeneratorFunction","AsyncFunction","Observable","Array","Buffer","Object","RegExp","Date","Error","Map","Set","WeakMap","WeakSet","ArrayBuffer","SharedArrayBuffer","DataView","Promise","URL","HTMLElement","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","BigInt64Array","BigUint64Array"];function kT(e){if(null===e)return"null";if(void 0===e)return"undefined";if(!0===e||!1===e)return"boolean";var t=typeof e;if(ET.includes(t))return t;if("function"===t)return"Function";if(Array.isArray(e))return"Array";if(function(e){return e&&e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer.call(null,e)}(e))return"Buffer";var r=function(e){var t=Object.prototype.toString.call(e).slice(8,-1);if(AT.includes(t))return t;return}(e);return r||"Object"}class xT{constructor(e,t,r){this.major=e,this.majorEncoded=e<<5,this.name=t,this.terminal=r}toString(){return"Type[".concat(this.major,"].").concat(this.name)}compare(e){return this.major<e.major?-1:this.major>e.major?1:0}}xT.uint=new xT(0,"uint",!0),xT.negint=new xT(1,"negint",!0),xT.bytes=new xT(2,"bytes",!0),xT.string=new xT(3,"string",!0),xT.array=new xT(4,"array",!1),xT.map=new xT(5,"map",!1),xT.tag=new xT(6,"tag",!1),xT.float=new xT(7,"float",!0),xT.false=new xT(7,"false",!0),xT.true=new xT(7,"true",!0),xT.null=new xT(7,"null",!0),xT.undefined=new xT(7,"undefined",!0),xT.break=new xT(7,"break",!0);class TT{constructor(e,t,r){this.type=e,this.value=t,this.encodedLength=r,this.encodedBytes=void 0,this.byteValue=void 0}toString(){return"Token[".concat(this.type,"].").concat(this.value)}}var IT=globalThis.process&&!globalThis.process.browser&&globalThis.Buffer&&"function"==typeof globalThis.Buffer.isBuffer,CT=new TextDecoder,BT=new TextEncoder;function NT(e){return IT&&globalThis.Buffer.isBuffer(e)}function DT(e){return e instanceof Uint8Array?NT(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e:Uint8Array.from(e)}var GT=IT?(e,t,r)=>r-t>64?globalThis.Buffer.from(e.subarray(t,r)).toString("utf8"):UT(e,t,r):(e,t,r)=>r-t>64?CT.decode(e.subarray(t,r)):UT(e,t,r),RT=IT?e=>e.length>64?globalThis.Buffer.from(e):FT(e):e=>e.length>64?BT.encode(e):FT(e),OT=e=>Uint8Array.from(e),LT=IT?(e,t,r)=>NT(e)?new Uint8Array(e.subarray(t,r)):e.slice(t,r):(e,t,r)=>e.slice(t,r),MT=IT?(e,t)=>(e=e.map((e=>e instanceof Uint8Array?e:globalThis.Buffer.from(e))),DT(globalThis.Buffer.concat(e,t))):(e,t)=>{var r=new Uint8Array(t),n=0;for(var i of e)n+i.length>r.length&&(i=i.subarray(0,r.length-n)),r.set(i,n),n+=i.length;return r},jT=IT?e=>globalThis.Buffer.allocUnsafe(e):e=>new Uint8Array(e);function FT(e){for(var t=[],r=0,n=0;n<e.length;n++){var i=e.charCodeAt(n);i<128?t[r++]=i:i<2048?(t[r++]=i>>6|192,t[r++]=63&i|128):55296==(64512&i)&&n+1<e.length&&56320==(64512&e.charCodeAt(n+1))?(i=65536+((1023&i)<<10)+(1023&e.charCodeAt(++n)),t[r++]=i>>18|240,t[r++]=i>>12&63|128,t[r++]=i>>6&63|128,t[r++]=63&i|128):(t[r++]=i>>12|224,t[r++]=i>>6&63|128,t[r++]=63&i|128)}return t}function UT(e,t,r){for(var n=[];t<r;){var i=e[t],o=null,a=i>239?4:i>223?3:i>191?2:1;if(t+a<=r){var s=void 0,l=void 0,c=void 0,u=void 0;switch(a){case 1:i<128&&(o=i);break;case 2:128==(192&(s=e[t+1]))&&(u=(31&i)<<6|63&s)>127&&(o=u);break;case 3:s=e[t+1],l=e[t+2],128==(192&s)&&128==(192&l)&&(u=(15&i)<<12|(63&s)<<6|63&l)>2047&&(u<55296||u>57343)&&(o=u);break;case 4:s=e[t+1],l=e[t+2],c=e[t+3],128==(192&s)&&128==(192&l)&&128==(192&c)&&(u=(15&i)<<18|(63&s)<<12|(63&l)<<6|63&c)>65535&&u<1114112&&(o=u)}}null===o?(o=65533,a=1):o>65535&&(o-=65536,n.push(o>>>10&1023|55296),o=56320|1023&o),n.push(o),t+=a}return VT(n)}var zT=4096;function VT(e){var t=e.length;if(t<=zT)return String.fromCharCode.apply(String,e);for(var r="",n=0;n<t;)r+=String.fromCharCode.apply(String,e.slice(n,n+=zT));return r}class qT{constructor(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:256;this.chunkSize=e,this.cursor=0,this.maxCursor=-1,this.chunks=[],this._initReuseChunk=null}reset(){this.cursor=0,this.maxCursor=-1,this.chunks.length&&(this.chunks=[]),null!==this._initReuseChunk&&(this.chunks.push(this._initReuseChunk),this.maxCursor=this._initReuseChunk.length-1)}push(e){var t=this.chunks[this.chunks.length-1];if(this.cursor+e.length<=this.maxCursor+1){var r=t.length-(this.maxCursor-this.cursor)-1;t.set(e,r)}else{if(t){var n=t.length-(this.maxCursor-this.cursor)-1;n<t.length&&(this.chunks[this.chunks.length-1]=t.subarray(0,n),this.maxCursor=this.cursor-1)}e.length<64&&e.length<this.chunkSize?(t=jT(this.chunkSize),this.chunks.push(t),this.maxCursor+=t.length,null===this._initReuseChunk&&(this._initReuseChunk=t),t.set(e,0)):(this.chunks.push(e),this.maxCursor+=e.length)}this.cursor+=e.length}toBytes(){var e,t=arguments.length>0&&void 0!==arguments[0]&&arguments[0];if(1===this.chunks.length){var r=this.chunks[0];t&&this.cursor>r.length/2?(e=this.cursor===r.length?r:r.subarray(0,this.cursor),this._initReuseChunk=null,this.chunks=[]):e=LT(r,0,this.cursor)}else e=MT(this.chunks,this.cursor);return t&&this.reset(),e}}var HT="CBOR decode error:",KT="CBOR encode error:";function WT(e,t,r){if(e.length-t<r)throw new Error("".concat(HT," not enough data for type"))}var QT=[24,256,65536,4294967296,BigInt("18446744073709551616")];function YT(e,t,r){WT(e,t,1);var n=e[t];if(!0===r.strict&&n<QT[0])throw new Error("".concat(HT," integer encoded in more bytes than necessary (strict decode)"));return n}function JT(e,t,r){WT(e,t,2);var n=e[t]<<8|e[t+1];if(!0===r.strict&&n<QT[1])throw new Error("".concat(HT," integer encoded in more bytes than necessary (strict decode)"));return n}function ZT(e,t,r){WT(e,t,4);var n=16777216*e[t]+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3];if(!0===r.strict&&n<QT[2])throw new Error("".concat(HT," integer encoded in more bytes than necessary (strict decode)"));return n}function $T(e,t,r){WT(e,t,8);var n=16777216*e[t]+(e[t+1]<<16)+(e[t+2]<<8)+e[t+3],i=16777216*e[t+4]+(e[t+5]<<16)+(e[t+6]<<8)+e[t+7],o=(BigInt(n)<<BigInt(32))+BigInt(i);if(!0===r.strict&&o<QT[3])throw new Error("".concat(HT," integer encoded in more bytes than necessary (strict decode)"));if(o<=Number.MAX_SAFE_INTEGER)return Number(o);if(!0===r.allowBigInt)return o;throw new Error("".concat(HT," integers outside of the safe integer range are not supported"))}function XT(e,t){return eI(e,0,t.value)}function eI(e,t,r){if(r<QT[0]){var n=Number(r);e.push([t|n])}else if(r<QT[1]){var i=Number(r);e.push([24|t,i])}else if(r<QT[2]){var o=Number(r);e.push([25|t,o>>>8,255&o])}else if(r<QT[3]){var a=Number(r);e.push([26|t,a>>>24&255,a>>>16&255,a>>>8&255,255&a])}else{var s=BigInt(r);if(!(s<QT[4]))throw new Error("".concat(HT," encountered BigInt larger than allowable range"));var l=[27|t,0,0,0,0,0,0,0],c=Number(s&BigInt(4294967295)),u=Number(s>>BigInt(32)&BigInt(4294967295));l[8]=255&c,c>>=8,l[7]=255&c,c>>=8,l[6]=255&c,c>>=8,l[5]=255&c,l[4]=255&u,u>>=8,l[3]=255&u,u>>=8,l[2]=255&u,u>>=8,l[1]=255&u,e.push(l)}}XT.encodedSize=function(e){return eI.encodedSize(e.value)},eI.encodedSize=function(e){return e<QT[0]?1:e<QT[1]?2:e<QT[2]?3:e<QT[3]?5:9},XT.compareTokens=function(e,t){return e.value<t.value?-1:e.value>t.value?1:0};var tI=BigInt(-1),rI=BigInt(1);function nI(e,t){var r=t.value,n="bigint"==typeof r?r*tI-rI:-1*r-1;eI(e,t.type.majorEncoded,n)}function iI(e,t,r,n){WT(e,t,r+n);var i=LT(e,t+r,t+r+n);return new TT(xT.bytes,i,r+n)}function oI(e,t,r,n){return iI(e,t,1,r)}function aI(e){return void 0===e.encodedBytes&&(e.encodedBytes=e.type===xT.string?RT(e.value):e.value),e.encodedBytes}function sI(e,t){var r=aI(t);eI(e,t.type.majorEncoded,r.length),e.push(r)}function lI(e,t,r,n,i){var o=r+n;WT(e,t,o);var a=new TT(xT.string,GT(e,t+r,t+o),o);return!0===i.retainStringBytes&&(a.byteValue=LT(e,t+r,t+o)),a}function cI(e,t,r,n){return lI(e,t,1,r,n)}nI.encodedSize=function(e){var t=e.value,r="bigint"==typeof t?t*tI-rI:-1*t-1;return r<QT[0]?1:r<QT[1]?2:r<QT[2]?3:r<QT[3]?5:9},nI.compareTokens=function(e,t){return e.value<t.value?1:e.value>t.value?-1:0},sI.encodedSize=function(e){var t=aI(e);return eI.encodedSize(t.length)+t.length},sI.compareTokens=function(e,t){return r=aI(e),n=aI(t),r.length<n.length?-1:r.length>n.length?1:function(e,t){if(NT(e)&&NT(t))return e.compare(t);for(var r=0;r<e.length;r++)if(e[r]!==t[r])return e[r]<t[r]?-1:1;return 0}(r,n);var r,n};var uI=sI;function dI(e,t,r,n){return new TT(xT.array,n,r)}function hI(e,t,r,n){return dI(0,0,1,r)}function pI(e,t){eI(e,xT.array.majorEncoded,t.value)}function fI(e,t,r,n){return new TT(xT.map,n,r)}function vI(e,t,r,n){return fI(0,0,1,r)}function yI(e,t){eI(e,xT.map.majorEncoded,t.value)}function gI(e,t,r,n){return new TT(xT.tag,r,1)}function mI(e,t){eI(e,xT.tag.majorEncoded,t.value)}pI.compareTokens=XT.compareTokens,pI.encodedSize=function(e){return eI.encodedSize(e.value)},yI.compareTokens=XT.compareTokens,yI.encodedSize=function(e){return eI.encodedSize(e.value)},mI.compareTokens=XT.compareTokens,mI.encodedSize=function(e){return eI.encodedSize(e.value)};function wI(e,t,r){if(r){if(!1===r.allowNaN&&Number.isNaN(e))throw new Error("".concat(HT," NaN values are not supported"));if(!1===r.allowInfinity&&(e===1/0||e===-1/0))throw new Error("".concat(HT," Infinity values are not supported"))}return new TT(xT.float,e,t)}function bI(e,t,r){var n,i=t.value;if(!1===i)e.push([20|xT.float.majorEncoded]);else if(!0===i)e.push([21|xT.float.majorEncoded]);else if(null===i)e.push([22|xT.float.majorEncoded]);else if(void 0===i)e.push([23|xT.float.majorEncoded]);else{var o=!1;r&&!0===r.float64||(EI(i),i===AI(PI,1)||Number.isNaN(i)?(PI[0]=249,e.push(PI.slice(0,3)),o=!0):(kI(i),i===xI(PI,1)&&(PI[0]=250,e.push(PI.slice(0,5)),o=!0))),o||(n=i,SI.setFloat64(0,n,!1),TI(PI,1),PI[0]=251,e.push(PI.slice(0,9)))}}bI.encodedSize=function(e,t){var r=e.value;if(!1===r||!0===r||null==r)return 1;if(!t||!0!==t.float64){EI(r);var n=AI(PI,1);if(r===n||Number.isNaN(r))return 3;if(kI(r),r===(n=xI(PI,1)))return 5}return 9};var _I=new ArrayBuffer(9),SI=new DataView(_I,1),PI=new Uint8Array(_I,0);function EI(e){if(e===1/0)SI.setUint16(0,31744,!1);else if(e===-1/0)SI.setUint16(0,64512,!1);else if(Number.isNaN(e))SI.setUint16(0,32256,!1);else{SI.setFloat32(0,e);var t=SI.getUint32(0),r=(2139095040&t)>>23,n=8388607&t;if(255===r)SI.setUint16(0,31744,!1);else if(0===r)SI.setUint16(0,(2147483648&e)>>16|n>>13,!1);else{var i=r-127;i<-24?SI.setUint16(0,0):i<-14?SI.setUint16(0,(2147483648&t)>>16|1<<24+i,!1):SI.setUint16(0,(2147483648&t)>>16|i+15<<10|n>>13,!1)}}}function AI(e,t){if(e.length-t<2)throw new Error("".concat(HT," not enough data for float16"));var r=(e[t]<<8)+e[t+1];if(31744===r)return 1/0;if(64512===r)return-1/0;if(32256===r)return NaN;var n,i=r>>10&31,o=1023&r;return n=0===i?o*2**-24:31!==i?(o+1024)*2**(i-25):0===o?1/0:NaN,32768&r?-n:n}function kI(e){SI.setFloat32(0,e,!1)}function xI(e,t){if(e.length-t<4)throw new Error("".concat(HT," not enough data for float32"));var r=(e.byteOffset||0)+t;return new DataView(e.buffer,r,4).getFloat32(0,!1)}function TI(e,t){if(e.length-t<8)throw new Error("".concat(HT," not enough data for float64"));var r=(e.byteOffset||0)+t;return new DataView(e.buffer,r,8).getFloat64(0,!1)}function II(e,t,r){throw new Error("".concat(HT," encountered invalid minor (").concat(r,") for major ").concat(e[t]>>>5))}function CI(e){return()=>{throw new Error("".concat(HT," ").concat(e))}}bI.compareTokens=XT.compareTokens;for(var BI=[],NI=0;NI<=23;NI++)BI[NI]=II;BI[24]=function(e,t,r,n){return new TT(xT.uint,YT(e,t+1,n),2)},BI[25]=function(e,t,r,n){return new TT(xT.uint,JT(e,t+1,n),3)},BI[26]=function(e,t,r,n){return new TT(xT.uint,ZT(e,t+1,n),5)},BI[27]=function(e,t,r,n){return new TT(xT.uint,$T(e,t+1,n),9)},BI[28]=II,BI[29]=II,BI[30]=II,BI[31]=II;for(var DI=32;DI<=55;DI++)BI[DI]=II;BI[56]=function(e,t,r,n){return new TT(xT.negint,-1-YT(e,t+1,n),2)},BI[57]=function(e,t,r,n){return new TT(xT.negint,-1-JT(e,t+1,n),3)},BI[58]=function(e,t,r,n){return new TT(xT.negint,-1-ZT(e,t+1,n),5)},BI[59]=function(e,t,r,n){var i=$T(e,t+1,n);if("bigint"!=typeof i){var o=-1-i;if(o>=Number.MIN_SAFE_INTEGER)return new TT(xT.negint,o,9)}if(!0!==n.allowBigInt)throw new Error("".concat(HT," integers outside of the safe integer range are not supported"));return new TT(xT.negint,tI-BigInt(i),9)},BI[60]=II,BI[61]=II,BI[62]=II,BI[63]=II;for(var GI=64;GI<=87;GI++)BI[GI]=oI;BI[88]=function(e,t,r,n){return iI(e,t,2,YT(e,t+1,n))},BI[89]=function(e,t,r,n){return iI(e,t,3,JT(e,t+1,n))},BI[90]=function(e,t,r,n){return iI(e,t,5,ZT(e,t+1,n))},BI[91]=function(e,t,r,n){var i=$T(e,t+1,n);if("bigint"==typeof i)throw new Error("".concat(HT," 64-bit integer bytes lengths not supported"));return iI(e,t,9,i)},BI[92]=II,BI[93]=II,BI[94]=II,BI[95]=CI("indefinite length bytes/strings are not supported");for(var RI=96;RI<=119;RI++)BI[RI]=cI;BI[120]=function(e,t,r,n){return lI(e,t,2,YT(e,t+1,n),n)},BI[121]=function(e,t,r,n){return lI(e,t,3,JT(e,t+1,n),n)},BI[122]=function(e,t,r,n){return lI(e,t,5,ZT(e,t+1,n),n)},BI[123]=function(e,t,r,n){var i=$T(e,t+1,n);if("bigint"==typeof i)throw new Error("".concat(HT," 64-bit integer string lengths not supported"));return lI(e,t,9,i,n)},BI[124]=II,BI[125]=II,BI[126]=II,BI[127]=CI("indefinite length bytes/strings are not supported");for(var OI=128;OI<=151;OI++)BI[OI]=hI;BI[152]=function(e,t,r,n){return dI(0,0,2,YT(e,t+1,n))},BI[153]=function(e,t,r,n){return dI(0,0,3,JT(e,t+1,n))},BI[154]=function(e,t,r,n){return dI(0,0,5,ZT(e,t+1,n))},BI[155]=function(e,t,r,n){var i=$T(e,t+1,n);if("bigint"==typeof i)throw new Error("".concat(HT," 64-bit integer array lengths not supported"));return dI(0,0,9,i)},BI[156]=II,BI[157]=II,BI[158]=II,BI[159]=function(e,t,r,n){if(!1===n.allowIndefinite)throw new Error("".concat(HT," indefinite length items not allowed"));return dI(0,0,1,1/0)};for(var LI=160;LI<=183;LI++)BI[LI]=vI;BI[184]=function(e,t,r,n){return fI(0,0,2,YT(e,t+1,n))},BI[185]=function(e,t,r,n){return fI(0,0,3,JT(e,t+1,n))},BI[186]=function(e,t,r,n){return fI(0,0,5,ZT(e,t+1,n))},BI[187]=function(e,t,r,n){var i=$T(e,t+1,n);if("bigint"==typeof i)throw new Error("".concat(HT," 64-bit integer map lengths not supported"));return fI(0,0,9,i)},BI[188]=II,BI[189]=II,BI[190]=II,BI[191]=function(e,t,r,n){if(!1===n.allowIndefinite)throw new Error("".concat(HT," indefinite length items not allowed"));return fI(0,0,1,1/0)};for(var MI=192;MI<=215;MI++)BI[MI]=gI;BI[216]=function(e,t,r,n){return new TT(xT.tag,YT(e,t+1,n),2)},BI[217]=function(e,t,r,n){return new TT(xT.tag,JT(e,t+1,n),3)},BI[218]=function(e,t,r,n){return new TT(xT.tag,ZT(e,t+1,n),5)},BI[219]=function(e,t,r,n){return new TT(xT.tag,$T(e,t+1,n),9)},BI[220]=II,BI[221]=II,BI[222]=II,BI[223]=II;for(var jI=224;jI<=243;jI++)BI[jI]=CI("simple values are not supported");BI[244]=II,BI[245]=II,BI[246]=II,BI[247]=function(e,t,r,n){if(!1===n.allowUndefined)throw new Error("".concat(HT," undefined values are not supported"));return!0===n.coerceUndefinedToNull?new TT(xT.null,null,1):new TT(xT.undefined,void 0,1)},BI[248]=CI("simple values are not supported"),BI[249]=function(e,t,r,n){return wI(AI(e,t+1),3,n)},BI[250]=function(e,t,r,n){return wI(xI(e,t+1),5,n)},BI[251]=function(e,t,r,n){return wI(TI(e,t+1),9,n)},BI[252]=II,BI[253]=II,BI[254]=II,BI[255]=function(e,t,r,n){if(!1===n.allowIndefinite)throw new Error("".concat(HT," indefinite length items not allowed"));return new TT(xT.break,void 0,1)};for(var FI=[],UI=0;UI<24;UI++)FI[UI]=new TT(xT.uint,UI,1);for(var zI=-1;zI>=-24;zI--)FI[31-zI]=new TT(xT.negint,zI,1);FI[64]=new TT(xT.bytes,new Uint8Array(0),1),FI[96]=new TT(xT.string,"",1),FI[128]=new TT(xT.array,0,1),FI[160]=new TT(xT.map,0,1),FI[244]=new TT(xT.false,!1,1),FI[245]=new TT(xT.true,!0,1),FI[246]=new TT(xT.null,null,1);var VI={float64:!1,mapSorter:function(e,t){var r=Array.isArray(e[0])?e[0][0]:e[0],n=Array.isArray(t[0])?t[0][0]:t[0];if(r.type!==n.type)return r.type.compare(n.type);var i=r.type.major,o=HI[i].compareTokens(r,n);return o},quickEncodeToken:function(e){switch(e.type){case xT.false:return OT([244]);case xT.true:return OT([245]);case xT.null:return OT([246]);case xT.bytes:return e.value.length?void 0:OT([64]);case xT.string:return""===e.value?OT([96]):void 0;case xT.array:return 0===e.value?OT([128]):void 0;case xT.map:return 0===e.value?OT([160]):void 0;case xT.uint:return e.value<24?OT([Number(e.value)]):void 0;case xT.negint:if(e.value>=-24)return OT([31-Number(e.value)])}}};var qI,HI=((qI=[])[xT.uint.major]=XT,qI[xT.negint.major]=nI,qI[xT.bytes.major]=sI,qI[xT.string.major]=uI,qI[xT.array.major]=pI,qI[xT.map.major]=yI,qI[xT.tag.major]=mI,qI[xT.float.major]=bI,qI),KI=new qT;class WI{constructor(e,t){this.obj=e,this.parent=t}includes(e){var t=this;do{if(t.obj===e)return!0}while(t=t.parent);return!1}static createCheck(e,t){if(e&&e.includes(t))throw new Error("".concat(KT," object contains circular references"));return new WI(t,e)}}var QI={null:new TT(xT.null,null),undefined:new TT(xT.undefined,void 0),true:new TT(xT.true,!0),false:new TT(xT.false,!1),emptyArray:new TT(xT.array,0),emptyMap:new TT(xT.map,0)},YI={number:(e,t,r,n)=>Number.isInteger(e)&&Number.isSafeInteger(e)?new TT(e>=0?xT.uint:xT.negint,e):new TT(xT.float,e),bigint:(e,t,r,n)=>e>=BigInt(0)?new TT(xT.uint,e):new TT(xT.negint,e),Uint8Array:(e,t,r,n)=>new TT(xT.bytes,e),string:(e,t,r,n)=>new TT(xT.string,e),boolean:(e,t,r,n)=>e?QI.true:QI.false,null:(e,t,r,n)=>QI.null,undefined:(e,t,r,n)=>QI.undefined,ArrayBuffer:(e,t,r,n)=>new TT(xT.bytes,new Uint8Array(e)),DataView:(e,t,r,n)=>new TT(xT.bytes,new Uint8Array(e.buffer,e.byteOffset,e.byteLength)),Array(e,t,r,n){if(!e.length)return!0===r.addBreakTokens?[QI.emptyArray,new TT(xT.break)]:QI.emptyArray;n=WI.createCheck(n,e);var i=[],o=0;for(var a of e)i[o++]=ZI(a,r,n);return r.addBreakTokens?[new TT(xT.array,e.length),i,new TT(xT.break)]:[new TT(xT.array,e.length),i]},Object(e,t,r,n){var i="Object"!==t,o=i?e.keys():Object.keys(e),a=i?e.size:o.length;if(!a)return!0===r.addBreakTokens?[QI.emptyMap,new TT(xT.break)]:QI.emptyMap;n=WI.createCheck(n,e);var s=[],l=0;for(var c of o)s[l++]=[ZI(c,r,n),ZI(i?e.get(c):e[c],r,n)];return function(e,t){t.mapSorter&&e.sort(t.mapSorter)}(s,r),r.addBreakTokens?[new TT(xT.map,a),s,new TT(xT.break)]:[new TT(xT.map,a),s]}};for(var JI of(YI.Map=YI.Object,YI.Buffer=YI.Uint8Array,"Uint8Clamped Uint16 Uint32 Int8 Int16 Int32 BigUint64 BigInt64 Float32 Float64".split(" ")))YI["".concat(JI,"Array")]=YI.DataView;function ZI(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=arguments.length>2?arguments[2]:void 0,n=kT(e),i=t&&t.typeEncoders&&t.typeEncoders[n]||YI[n];if("function"==typeof i){var o=i(e,n,t,r);if(null!=o)return o}var a=YI[n];if(!a)throw new Error("".concat(KT," unsupported type: ").concat(n));return a(e,n,t,r)}function $I(e,t,r,n){if(Array.isArray(t))for(var i of t)$I(e,i,r,n);else r[t.type.major](e,t,n)}function XI(e,t,r){var n=ZI(e,r);if(!Array.isArray(n)&&r.quickEncodeToken){var i=r.quickEncodeToken(n);if(i)return i;var o=t[n.type.major];if(o.encodedSize){var a=o.encodedSize(n,r),s=new qT(a);if(o(s,n,r),1!==s.chunks.length)throw new Error("Unexpected error: pre-calculated length for ".concat(n," was wrong"));return DT(s.chunks[0])}}return KI.reset(),$I(KI,n,t,r),KI.toBytes(!0)}function eC(e,t){return t=Object.assign({},VI,t),XI(e,HI,t)}var tC={strict:!1,allowIndefinite:!0,allowUndefined:!0,allowBigInt:!0};class rC{constructor(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this._pos=0,this.data=e,this.options=t}pos(){return this._pos}done(){return this._pos>=this.data.length}next(){var e=this.data[this._pos],t=FI[e];if(void 0===t){var r=BI[e];if(!r)throw new Error("".concat(HT," no decoder for major type ").concat(e>>>5," (byte 0x").concat(e.toString(16).padStart(2,"0"),")"));var n=31&e;t=r(this.data,this._pos,n,this.options)}return this._pos+=t.encodedLength,t}}var nC=Symbol.for("DONE"),iC=Symbol.for("BREAK");function oC(e,t){if(e.done())return nC;var r=e.next();if(r.type===xT.break)return iC;if(r.type.terminal)return r.value;if(r.type===xT.array)return function(e,t,r){for(var n=[],i=0;i<e.value;i++){var o=oC(t,r);if(o===iC){if(e.value===1/0)break;throw new Error("".concat(HT," got unexpected break to lengthed array"))}if(o===nC)throw new Error("".concat(HT," found array but not enough entries (got ").concat(i,", expected ").concat(e.value,")"));n[i]=o}return n}(r,e,t);if(r.type===xT.map)return function(e,t,r){for(var n=!0===r.useMaps,i=n?void 0:{},o=n?new Map:void 0,a=0;a<e.value;a++){var s=oC(t,r);if(s===iC){if(e.value===1/0)break;throw new Error("".concat(HT," got unexpected break to lengthed map"))}if(s===nC)throw new Error("".concat(HT," found map but not enough entries (got ").concat(a," [no key], expected ").concat(e.value,")"));if(!0!==n&&"string"!=typeof s)throw new Error("".concat(HT," non-string keys not supported (got ").concat(typeof s,")"));if(!0===r.rejectDuplicateMapKeys&&(n&&o.has(s)||!n&&s in i))throw new Error("".concat(HT,' found repeat map key "').concat(s,'"'));var l=oC(t,r);if(l===nC)throw new Error("".concat(HT," found map but not enough entries (got ").concat(a," [no value], expected ").concat(e.value,")"));n?o.set(s,l):i[s]=l}return n?o:i}(r,e,t);if(r.type===xT.tag){if(t.tags&&"function"==typeof t.tags[r.value]){var n=oC(e,t);return t.tags[r.value](n)}throw new Error("".concat(HT," tag not supported (").concat(r.value,")"))}throw new Error("unsupported")}function aC(e,t){var[r,n]=function(e,t){if(!(e instanceof Uint8Array))throw new Error("".concat(HT," data to decode must be a Uint8Array"));var r=(t=Object.assign({},tC,t)).tokenizer||new rC(e,t),n=oC(r,t);if(n===nC)throw new Error("".concat(HT," did not find any content to decode"));if(n===iC)throw new Error("".concat(HT," got unexpected break"));return[n,e.subarray(r.pos())]}(e,t);if(n.length>0)throw new Error("".concat(HT," too many terminals, data makes no sense"));return r}function sC(){var{enumerable:e=!0,configurable:t=!1}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return{enumerable:e,configurable:t,writable:!1}}function*lC(e,t){if(null!=t&&"object"==typeof t)if(Array.isArray(t))for(var[r,n]of t.entries()){var i=[...e,r],o=je.asCID(n);null!=o?yield[i.join("/"),o]:"object"==typeof n&&(yield*cC(n,i))}else{var a=je.asCID(t);null!=a?yield[e.join("/"),a]:yield*cC(t,e)}}function*cC(e,t){if(!(null==e||e instanceof Uint8Array)){var r=je.asCID(e);for(var[n,i]of(null!=r&&(yield[t.join("/"),r]),Object.entries(e))){var o=[...t,n];yield*lC(o,i)}}}function*uC(e,t){if(Array.isArray(t))for(var[r,n]of t.entries()){var i=[...e,r];yield i.join("/"),"object"==typeof n&&null==je.asCID(n)&&(yield*dC(n,i))}else yield*dC(t,e)}function*dC(e,t){if(null!=e&&"object"==typeof e)for(var[r,n]of Object.entries(e)){var i=[...t,r];yield i.join("/"),null==n||n instanceof Uint8Array||"object"!=typeof n||null!=je.asCID(n)||(yield*uC(i,n))}}class hC{constructor(t){var{cid:r,bytes:n,value:i}=t;if(e._defineProperty(this,"cid",void 0),e._defineProperty(this,"bytes",void 0),e._defineProperty(this,"value",void 0),e._defineProperty(this,"asBlock",void 0),null==r||null==n||void 0===i)throw new Error("Missing required argument");this.cid=r,this.bytes=n,this.value=i,this.asBlock=this,Object.defineProperties(this,{cid:sC(),bytes:sC(),value:sC(),asBlock:sC()})}links(){return cC(this.value,[])}tree(){return dC(this.value,[])}get(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"/";return function(e,t){var r=e;for(var[n,i]of t.entries()){if(null==(r=r[i]))throw new Error("Object has no property at ".concat(t.slice(0,n+1).map((e=>"[".concat(JSON.stringify(e),"]"))).join("")));var o=je.asCID(r);if(null!=o)return{value:o,remaining:t.slice(n+1).join("/")}}return{value:r}}(this.value,e.split("/").filter(Boolean))}}var pC="/pin/",fC="/pinned-block/",vC=O;function yC(e){return 0===e.version&&(e=e.toV1()),new Bc("".concat(pC).concat(e.toString(vC)))}var gC=new WeakSet;class mC{constructor(t,r,n){e._classPrivateMethodInitSpec(this,gC),e._defineProperty(this,"datastore",void 0),e._defineProperty(this,"blockstore",void 0),e._defineProperty(this,"getCodec",void 0),this.datastore=t,this.blockstore=r,this.getCodec=n}add(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(i,o){var a=yC(t);if(yield e._awaitAsyncGenerator(r.datastore.has(a)))throw new Error("Already pinned");var s=Math.round(null!==(i=n.depth)&&void 0!==i?i:1/0);if(s<0)throw new Error("Depth must be greater than or equal to 0");var l,c=new Mh({concurrency:1}),u=!1,d=!1;try{for(var h,p=e._asyncIterator(e._assertClassBrand(gC,r,wC).call(r,t,c,e._objectSpread2(e._objectSpread2({},n),{},{depth:s})));u=!(h=yield e._awaitAsyncGenerator(p.next())).done;u=!1){var f=h.value;yield e._awaitAsyncGenerator(e._assertClassBrand(gC,r,bC).call(r,f,(e=>null==e.pinnedBy.find((e=>nt(e,t.bytes)))&&(e.pinCount++,e.pinnedBy.push(t.bytes),!0)),n)),yield f}}catch(e){d=!0,l=e}finally{try{u&&null!=p.return&&(yield e._awaitAsyncGenerator(p.return()))}finally{if(d)throw l}}var v={depth:s,metadata:null!==(o=n.metadata)&&void 0!==o?o:{}};yield e._awaitAsyncGenerator(r.datastore.put(a,eC(v),n))}()})).apply(this,arguments)}rm(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var i=yC(t),o=aC(yield e._awaitAsyncGenerator(r.datastore.get(i,n)));yield e._awaitAsyncGenerator(r.datastore.delete(i,n));var a,s=new Mh({concurrency:1}),l=!1,c=!1;try{for(var u,d=e._asyncIterator(e._assertClassBrand(gC,r,wC).call(r,t,s,e._objectSpread2(e._objectSpread2({},n),{},{depth:o.depth})));l=!(u=yield e._awaitAsyncGenerator(d.next())).done;l=!1){var h=u.value;yield e._awaitAsyncGenerator(e._assertClassBrand(gC,r,bC).call(r,h,(e=>(e.pinCount--,e.pinnedBy=e.pinnedBy.filter((e=>nt(e,t.bytes))),!0)),e._objectSpread2(e._objectSpread2({},n),{},{depth:o.depth}))),yield h}}catch(e){c=!0,a=e}finally{try{l&&null!=d.return&&(yield e._awaitAsyncGenerator(d.return()))}finally{if(c)throw a}}}()})).apply(this,arguments)}ls(){var t=this;return e._wrapAsyncGenerator((function(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var n,i=!1,o=!1;try{for(var a,s=e._asyncIterator(t.datastore.query({prefix:pC+(null!=r.cid?"".concat(r.cid.toString(O)):"")},r));i=!(a=yield e._awaitAsyncGenerator(s.next())).done;i=!1){var{key:l,value:c}=a.value,u=je.parse(l.toString().substring(5),O),d=aC(c);yield e._objectSpread2({cid:u},d)}}catch(e){o=!0,n=e}finally{try{i&&null!=s.return&&(yield e._awaitAsyncGenerator(s.return()))}finally{if(o)throw n}}}()})).apply(this,arguments)}isPinned(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{},i=new Bc("".concat(fC).concat(vC.encode(t.multihash.bytes)));return n.datastore.has(i,e)}))()}get(t,r){var n=this;return e._asyncToGenerator((function*(){var e=yC(t);return aC(yield n.datastore.get(e,r))}))()}setMetadata(t,r,n){var i=this;return e._asyncToGenerator((function*(){var e=yC(t),o=aC(yield i.datastore.get(e,n));o.metadata=null!=r?r:{},yield i.datastore.put(e,eC(o),n)}))()}}function wC(t,r,n){var i=this;return e._wrapAsyncGenerator((function*(){if(-1!==n.depth){var o=yield e._awaitAsyncGenerator(i.getCodec(t.code)),a=function(e){var{bytes:t,cid:r,value:n,codec:i}=e,o=void 0!==n?n:null==i?void 0:i.decode(t);if(void 0===o)throw new Error('Missing required argument, must either provide "value" or "codec"');return new hC({cid:r,bytes:t,value:o})}({bytes:yield e._awaitAsyncGenerator(i.blockstore.get(t,n)),cid:t,codec:o});yield t;var s=function*(t){yield*e._asyncGeneratorDelegate(e._asyncIterator(yield e._awaitAsyncGenerator(r.add(e._asyncToGenerator((function*(){return e._assertClassBrand(gC,i,wC).call(i,t,r,e._objectSpread2(e._objectSpread2({},n),{},{depth:n.depth-1}))}))))))};for(var[,l]of a.links())yield*s(l)}}))()}function bC(e,t,r){return _C.apply(this,arguments)}function _C(){return _C=e._asyncToGenerator((function*(e,t,r){var n,i=new Bc("".concat(fC).concat(vC.encode(e.multihash.bytes))),o={pinCount:0,pinnedBy:[]};try{o=aC(yield this.datastore.get(i,r))}catch(e){if("NotFoundError"!==e.name)throw e}t(o)&&(0===o.pinCount&&(yield this.datastore.has(i))?yield this.datastore.delete(i):(yield this.datastore.put(i,eC(o),r),null===(n=r.onProgress)||void 0===n||n.call(r,new Ih("helia:pin:add",e))))})),_C.apply(this,arguments)}class SC extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Insufficient providers found"),this.name="InsufficientProvidersError"}}e._defineProperty(SC,"name","InsufficientProvidersError");class PC extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No routers available"),this.name="NoRoutersAvailableError"}}e._defineProperty(PC,"name","NoRoutersAvailableError");class EC extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unknown hash algorithm"),this.name="UnknownHashAlgorithmError"}}e._defineProperty(EC,"name","UnknownHashAlgorithmError");class AC extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unknown codec"),this.name="UnknownCodecError"}}e._defineProperty(AC,"name","UnknownCodecError");class kC{constructor(t,r){var n,i,o,a,s,l,c,u,d,h,p,f,v,y,g,m;e._defineProperty(this,"log",void 0),e._defineProperty(this,"routers",void 0),e._defineProperty(this,"providerLookupConcurrency",void 0),this.log=t.logger.forComponent("helia:routing"),this.routers=null!==(n=r.routers)&&void 0!==n?n:[],this.providerLookupConcurrency=null!==(i=r.providerLookupConcurrency)&&void 0!==i?i:5,this.findProviders=null!==(o=null===(a=t.metrics)||void 0===a?void 0:a.traceFunction("helia.routing.findProviders",this.findProviders.bind(this),{optionsIndex:1}))&&void 0!==o?o:this.findProviders,this.provide=null!==(s=null===(l=t.metrics)||void 0===l?void 0:l.traceFunction("helia.routing.provide",this.provide.bind(this),{optionsIndex:1}))&&void 0!==s?s:this.provide,this.cancelReprovide=null!==(c=null===(u=t.metrics)||void 0===u?void 0:u.traceFunction("helia.routing.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1}))&&void 0!==c?c:this.cancelReprovide,this.put=null!==(d=null===(h=t.metrics)||void 0===h?void 0:h.traceFunction("helia.routing.put",this.put.bind(this),{optionsIndex:2}))&&void 0!==d?d:this.put,this.get=null!==(p=null===(f=t.metrics)||void 0===f?void 0:f.traceFunction("helia.routing.get",this.get.bind(this),{optionsIndex:1}))&&void 0!==p?p:this.get,this.findPeer=null!==(v=null===(y=t.metrics)||void 0===y?void 0:y.traceFunction("helia.routing.findPeer",this.findPeer.bind(this),{optionsIndex:1}))&&void 0!==v?v:this.findPeer,this.getClosestPeers=null!==(g=null===(m=t.metrics)||void 0===m?void 0:m.traceFunction("helia.routing.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1}))&&void 0!==g?g:this.getClosestPeers}start(){var t=this;return e._asyncToGenerator((function*(){yield Ba(...t.routers)}))()}stop(){var t=this;return e._asyncToGenerator((function*(){yield Da(...t.routers)}))()}findProviders(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){if(0===r.routers.length)throw new PC("No content routers available");var i=new jh({concurrency:r.providerLookupConcurrency});i.addEventListener("error",(()=>{}));var o,a=!1,s=!1;try{for(var l,c=function*(){var t=l.value;if(null==t)return 0;if(0===t.multiaddrs.length){if(null!=i.find(t.id))return 0;i.add(e._asyncToGenerator((function*(){try{var e=yield r.findPeer(t.id,n);return 0===e.multiaddrs.length?null:e}catch(e){return r.log.error("could not load multiaddrs for peer %p",t.id,e),null}})),{peerId:t.id,signal:n.signal}).catch((e=>{r.log.error("could not load multiaddrs for peer %p",t.id,e)}))}yield t},u=e._asyncIterator(su(i.toGenerator(),...xC(r.routers,"findProviders").map((e=>e.findProviders(t,n)))));a=!(l=yield e._awaitAsyncGenerator(u.next())).done;a=!1)yield*c()}catch(e){s=!0,o=e}finally{try{a&&null!=u.return&&(yield e._awaitAsyncGenerator(u.return()))}finally{if(s)throw o}}}()})).apply(this,arguments)}provide(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i=r.length>1&&void 0!==r[1]?r[1]:{};if(0===n.routers.length)throw new PC("No content routers available");yield Promise.all(xC(n.routers,"provide").map(function(){var r=e._asyncToGenerator((function*(e){yield e.provide(t,i)}));return function(e){return r.apply(this,arguments)}}()))}))()}cancelReprovide(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i=r.length>1&&void 0!==r[1]?r[1]:{};yield Promise.all(xC(n.routers,"cancelReprovide").map(function(){var r=e._asyncToGenerator((function*(e){yield e.cancelReprovide(t,i)}));return function(e){return r.apply(this,arguments)}}()))}))()}put(t,r,n){var i=this;return e._asyncToGenerator((function*(){yield Promise.all(xC(i.routers,"put").map(function(){var i=e._asyncToGenerator((function*(e){yield e.put(t,r,n)}));return function(e){return i.apply(this,arguments)}}()))}))()}get(t,r){var n=this;return e._asyncToGenerator((function*(){return Promise.any(xC(n.routers,"get").map(function(){var n=e._asyncToGenerator((function*(e){return e.get(t,r)}));return function(e){return n.apply(this,arguments)}}()))}))()}findPeer(t,r){var n=this;return e._asyncToGenerator((function*(){if(0===n.routers.length)throw new PC("No peer routers available");var i,o=n,a=su(...xC(n.routers,"findPeer").map((n=>e._wrapAsyncGenerator((function*(){try{yield yield e._awaitAsyncGenerator(n.findPeer(t,r))}catch(e){o.log.error(e)}}))()))),s=!1,l=!1;try{for(var c,u=e._asyncIterator(a);s=!(c=yield u.next()).done;s=!1){var d=c.value;if(null!=d)return d}}catch(e){l=!0,i=e}finally{try{s&&null!=u.return&&(yield u.return())}finally{if(l)throw i}}throw new ua("Could not find peer in routing")}))()}getClosestPeers(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){if(0===r.routers.length)throw new PC("No peer routers available");var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(su(...xC(r.routers,"getClosestPeers").map((e=>e.getClosestPeers(t,n)))));o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;null!=c&&(yield c)}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}()})).apply(this,arguments)}}function xC(e,t){return e.filter((e=>null!=e[t]))}let TC=class extends Error{constructor(){for(var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The operation was aborted",t=arguments.length,r=new Array(t>1?t-1:0),n=1;n<t;n++)r[n-1]=arguments[n];super(e,...r)}};var IC=new WeakMap;class CC extends EventTarget{constructor(){super(),e._classPrivateFieldInitSpec(this,IC,new Map)}listenerCount(t){var r=e._classPrivateFieldGet2(IC,this).get(t);return null==r?0:r.length}addEventListener(t,r,n){var i;super.addEventListener(t,r,n);var o=e._classPrivateFieldGet2(IC,this).get(t);null==o&&(o=[],e._classPrivateFieldGet2(IC,this).set(t,o)),o.push({callback:r,once:null!==(i=!0!==n&&!1!==n&&(null==n?void 0:n.once))&&void 0!==i&&i})}removeEventListener(t,r,n){super.removeEventListener(t.toString(),null!=r?r:null,n);var i=e._classPrivateFieldGet2(IC,this).get(t);null!=i&&(i=i.filter((e=>{var{callback:t}=e;return t!==r})),e._classPrivateFieldGet2(IC,this).set(t,i))}dispatchEvent(t){var r=super.dispatchEvent(t),n=e._classPrivateFieldGet2(IC,this).get(t.type);return null==n||(n=n.filter((e=>{var{once:t}=e;return!t})),e._classPrivateFieldGet2(IC,this).set(t.type,n)),r}safeDispatchEvent(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return this.dispatchEvent(new CustomEvent(e,t))}}class BC extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The queue was full"),this.name="QueueFullError"}}e._defineProperty(BC,"name","QueueFullError");class NC{constructor(t){var r;e._defineProperty(this,"deferred",void 0),e._defineProperty(this,"signal",void 0),this.signal=t,this.deferred=Promise.withResolvers(),this.onAbort=this.onAbort.bind(this),null===(r=this.signal)||void 0===r||r.addEventListener("abort",this.onAbort)}onAbort(){var e,t;this.deferred.reject(null!==(e=null===(t=this.signal)||void 0===t?void 0:t.reason)&&void 0!==e?e:new TC)}cleanup(){var e;null===(e=this.signal)||void 0===e||e.removeEventListener("abort",this.onAbort)}}class DC{constructor(t,r){e._defineProperty(this,"id",void 0),e._defineProperty(this,"fn",void 0),e._defineProperty(this,"options",void 0),e._defineProperty(this,"recipients",void 0),e._defineProperty(this,"status",void 0),e._defineProperty(this,"timeline",void 0),e._defineProperty(this,"controller",void 0),this.id="".concat(parseInt(String(1e9*Math.random()),10).toString()).concat(Date.now()),this.status="queued",this.fn=t,this.options=r,this.recipients=[],this.timeline={created:Date.now()},this.controller=new AbortController,this.controller.signal,this.onAbort=this.onAbort.bind(this)}abort(e){this.controller.abort(e)}onAbort(){var e=this.recipients.reduce(((e,t)=>{var r;return e&&!0===(null===(r=t.signal)||void 0===r?void 0:r.aborted)}),!0);e&&(this.controller.abort(new TC),this.cleanup())}join(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var e,n=t.length>0&&void 0!==t[0]?t[0]:{},i=new NC(n.signal);return r.recipients.push(i),null===(e=n.signal)||void 0===e||e.addEventListener("abort",r.onAbort),i.deferred.promise}))()}run(){var t=this;return e._asyncToGenerator((function*(){t.status="running",t.timeline.started=Date.now();try{var r;t.controller.signal.throwIfAborted();var n=yield tu(t.fn(e._objectSpread2(e._objectSpread2({},null!==(r=t.options)&&void 0!==r?r:{}),{},{signal:t.controller.signal})),t.controller.signal);t.recipients.forEach((e=>{e.deferred.resolve(n)})),t.status="complete"}catch(e){t.recipients.forEach((t=>{t.deferred.reject(e)})),t.status="errored"}finally{t.timeline.finished=Date.now(),t.cleanup()}}))()}cleanup(){this.recipients.forEach((e=>{var t;e.cleanup(),null===(t=e.signal)||void 0===t||t.removeEventListener("abort",this.onAbort)}))}}function GC(e,t){var r,n=function(){clearTimeout(r),r=setTimeout((function(){r=void 0,e()}),t)};return n.start=()=>{},n.stop=()=>{clearTimeout(r)},n}class RC extends CC{constructor(){var t,r,n,i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(),e._defineProperty(this,"concurrency",void 0),e._defineProperty(this,"maxSize",void 0),e._defineProperty(this,"queue",void 0),e._defineProperty(this,"pending",void 0),e._defineProperty(this,"sort",void 0),e._defineProperty(this,"autoStart",void 0),this.concurrency=null!==(t=i.concurrency)&&void 0!==t?t:Number.POSITIVE_INFINITY,this.maxSize=null!==(r=i.maxSize)&&void 0!==r?r:Number.POSITIVE_INFINITY,this.pending=0,this.autoStart=null===(n=i.autoStart)||void 0===n||n,this.sort=i.sort,this.queue=[],this.emitEmpty=GC(this.emitEmpty.bind(this),1),this.emitIdle=GC(this.emitIdle.bind(this),1)}[Symbol.asyncIterator](){return this.toGenerator()}emitEmpty(){0===this.size&&this.safeDispatchEvent("empty")}emitIdle(){0===this.running&&this.safeDispatchEvent("idle")}tryToStartAnother(){if(0===this.size)return this.emitEmpty(),0===this.running&&this.emitIdle(),!1;if(this.pending<this.concurrency){var e;for(var t of this.queue)if("queued"===t.status){e=t;break}return null!=e&&(this.safeDispatchEvent("active"),this.pending++,e.run().finally((()=>{for(var t=0;t<this.queue.length;t++)if(this.queue[t]===e){this.queue.splice(t,1);break}this.pending--,this.safeDispatchEvent("next"),this.autoStart&&this.tryToStartAnother()})),!0)}return!1}enqueue(e){this.queue.push(e),null!=this.sort&&this.queue.sort(this.sort)}start(){!1===this.autoStart&&(this.autoStart=!0,this.tryToStartAnother())}pause(){this.autoStart=!1}add(t,r){var n=this;return e._asyncToGenerator((function*(){var e;if(null==r||null===(e=r.signal)||void 0===e||e.throwIfAborted(),n.size===n.maxSize)throw new BC;var i=new DC(t,r);return n.enqueue(i),n.safeDispatchEvent("add"),n.autoStart&&n.tryToStartAnother(),i.join(r).then((e=>(n.safeDispatchEvent("success",{detail:{job:i,result:e}}),e))).catch((e=>{if("queued"===i.status)for(var t=0;t<n.queue.length;t++)if(n.queue[t]===i){n.queue.splice(t,1);break}throw n.safeDispatchEvent("failure",{detail:{job:i,error:e}}),e}))}))()}clear(){this.queue.splice(0,this.queue.length)}abort(){this.queue.forEach((e=>{e.abort(new TC)})),this.clear()}onEmpty(t){var r=this;return e._asyncToGenerator((function*(){0!==r.size&&(yield Bh(r,"empty",null==t?void 0:t.signal))}))()}onSizeLessThan(t,r){var n=this;return e._asyncToGenerator((function*(){n.size<t||(yield Bh(n,"next",null==r?void 0:r.signal,{filter:()=>n.size<t}))}))()}onIdle(t){var r=this;return e._asyncToGenerator((function*(){0===r.pending&&0===r.size||(yield Bh(r,"idle",null==t?void 0:t.signal))}))()}get size(){return this.queue.length}get queued(){return this.queue.length-this.pending}get running(){return this.pending}toGenerator(t){var r=this;return e._wrapAsyncGenerator((function*(){var n,i;null==t||null===(n=t.signal)||void 0===n||n.throwIfAborted();var o=Xc({objectMode:!0}),a=e=>{null!=e?r.abort():r.clear(),o.end(e)},s=e=>{null!=e.detail&&o.push(e.detail.result)},l=e=>{a(e.detail.error)},c=()=>{a()},u=()=>{a(new TC("Queue aborted"))};r.addEventListener("success",s),r.addEventListener("failure",l),r.addEventListener("idle",c),null==t||null===(i=t.signal)||void 0===i||i.addEventListener("abort",u);try{yield*e._asyncGeneratorDelegate(e._asyncIterator(o),e._awaitAsyncGenerator)}finally{var d;r.removeEventListener("success",s),r.removeEventListener("failure",l),r.removeEventListener("idle",c),null==t||null===(d=t.signal)||void 0===d||d.removeEventListener("abort",u),a()}}))()}}var OC="lock:worker:request-read",LC="lock:worker:abort-read-request",MC="lock:worker:release-read",jC="lock:master:grant-read",FC="lock:master:error-read",UC="lock:worker:request-write",zC="lock:worker:abort-write-request",VC="lock:worker:release-write",qC="lock:master:grant-write",HC="lock:master:error-write",KC="lock:worker:finalize",WC="mortice",QC={singleProcess:!1},YC=(t,r,n,i,o,a,s,l,c)=>u=>{if(null!=u.data){var d,h={type:u.data.type,name:u.data.name,identifier:u.data.identifier};h.type===o&&t.safeDispatchEvent(n,{detail:{name:h.name,identifier:h.identifier,handler:(d=e._asyncToGenerator((function*(){r.postMessage({type:c,name:h.name,identifier:h.identifier}),yield new Promise((e=>{var t=n=>{if(null!=(null==n?void 0:n.data)){var i=n.data.type,o=(n.data.name,n.data.identifier);i===l&&o===h.identifier&&(r.removeEventListener("message",t),e())}};r.addEventListener("message",t)}))})),function(){return d.apply(this,arguments)}),onError:e=>{r.postMessage({type:s,name:h.name,identifier:h.identifier,error:{message:e.message,name:e.name,stack:e.stack}})}}}),h.type===a&&t.safeDispatchEvent(i,{detail:{name:h.name,identifier:h.identifier}}),h.type===KC&&t.safeDispatchEvent("finalizeRequest",{detail:{name:h.name}})}};class JC{constructor(t){e._defineProperty(this,"name",void 0),e._defineProperty(this,"channel",void 0),this.name=t,this.channel=new BroadcastChannel(WC)}readLock(e){return this.sendRequest(OC,LC,jC,FC,MC,e)}writeLock(e){return this.sendRequest(UC,zC,qC,HC,VC,e)}finalize(){this.channel.postMessage({type:KC,name:this.name}),this.channel.close()}sendRequest(t,r,n,i,o,a){var s=this;return e._asyncToGenerator((function*(){var e;null==a||null===(e=a.signal)||void 0===e||e.throwIfAborted();var l=function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:10;return Math.random().toString().substring(2,e+2)}();return s.channel.postMessage({type:t,identifier:l,name:s.name}),new Promise(((e,t)=>{var c,u=()=>{s.channel.postMessage({type:r,identifier:l,name:s.name})};null==a||null===(c=a.signal)||void 0===c||c.addEventListener("abort",u,{once:!0});var d=r=>{var c,h;if((null===(c=r.data)||void 0===c?void 0:c.identifier)===l){var p;if((null===(h=r.data)||void 0===h?void 0:h.type)===n)s.channel.removeEventListener("message",d),null==a||null===(p=a.signal)||void 0===p||p.removeEventListener("abort",u),e((()=>{s.channel.postMessage({type:o,identifier:l,name:s.name})}));if(r.data.type===i){var f;s.channel.removeEventListener("message",d),null==a||null===(f=a.signal)||void 0===f||f.removeEventListener("abort",u);var v=new Error;null!=r.data.error&&(v.message=r.data.error.message,v.name=r.data.error.name,v.stack=r.data.error.stack),t(v)}}};s.channel.addEventListener("message",d)}))}))()}}var ZC,$C=new Map;function XC(e){return"function"==typeof(null==e?void 0:e.readLock)&&"function"==typeof(null==e?void 0:e.writeLock)}function eB(t){if(null==ZC&&(ZC=(e=>{if(e=Object.assign({},QC,e),Boolean(globalThis.document)||e.singleProcess){var t=new BroadcastChannel(WC),r=new CC;return t.addEventListener("message",YC(r,t,"requestReadLock","abortReadLockRequest",OC,LC,FC,MC,jC)),t.addEventListener("message",YC(r,t,"requestWriteLock","abortWriteLockRequest",UC,zC,HC,VC,qC)),r}return new JC(e.name)})(t),!XC(ZC))){var r=ZC;r.addEventListener("requestReadLock",(t=>{var n=t.detail.name,i=t.detail.identifier,o=$C.get(n);if(null!=o){var a=new AbortController,s=e=>{e.detail.name===n&&e.detail.identifier===i&&a.abort()};r.addEventListener("abortReadLockRequest",s),o.readLock({signal:a.signal}).then(function(){var r=e._asyncToGenerator((function*(e){yield t.detail.handler().finally((()=>{e()}))}));return function(e){return r.apply(this,arguments)}}()).catch((e=>{t.detail.onError(e)})).finally((()=>{r.removeEventListener("abortReadLockRequest",s)}))}})),r.addEventListener("requestWriteLock",(t=>{var n=t.detail.name,i=t.detail.identifier,o=$C.get(n);if(null!=o){var a=new AbortController,s=e=>{e.detail.name===n&&e.detail.identifier===i&&a.abort()};r.addEventListener("abortWriteLockRequest",s),o.writeLock({signal:a.signal}).then(function(){var r=e._asyncToGenerator((function*(e){yield t.detail.handler().finally((()=>{e()}))}));return function(e){return r.apply(this,arguments)}}()).catch((e=>{t.detail.onError(e)})).finally((()=>{r.removeEventListener("abortWriteLockRequest",s)}))}})),r.addEventListener("finalizeRequest",(e=>{var t=e.detail.name,r=$C.get(t);null!=r&&r.finalize()}))}return ZC}function tB(e,t){return rB.apply(this,arguments)}function rB(){return rB=e._asyncToGenerator((function*(t,r){var n,i,o,a=new Promise(((e,t)=>{i=e,o=t})),s=()=>{o(new TC)};return null==r||null===(n=r.signal)||void 0===n||n.addEventListener("abort",s,{once:!0}),t.add(e._asyncToGenerator((function*(){yield new Promise((e=>{i((()=>{var t;null==r||null===(t=r.signal)||void 0===t||t.removeEventListener("abort",s),e()}))}))})),{signal:null==r?void 0:r.signal}).catch((e=>{o(e)})),a})),rB.apply(this,arguments)}var nB={name:"lock",concurrency:1/0,singleProcess:!1};function iB(t){var r=Object.assign({},nB,t);return((t,r)=>{var n=$C.get(t);if(null!=n)return n;var i=eB(r);if(XC(i))return n=i,$C.set(t,n),n;var o,a=new RC({concurrency:1});return n={readLock:t=>e._asyncToGenerator((function*(){if(null!=o)return tB(o,t);var n=o=new RC({concurrency:r.concurrency,autoStart:!1}),i=tB(o,t);return a.add(e._asyncToGenerator((function*(){n.start(),yield n.onIdle().then((()=>{o===n&&(o=null)}))}))),i}))(),writeLock:t=>e._asyncToGenerator((function*(){return o=null,tB(a,t)}))(),finalize:()=>{$C.delete(t)},queue:a},$C.set(t,n),n})(r.name,r)}class oB{constructor(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};e._defineProperty(this,"lock",void 0),e._defineProperty(this,"child",void 0),e._defineProperty(this,"pins",void 0),e._defineProperty(this,"started",void 0),this.child=t,this.pins=r,this.lock=iB({singleProcess:n.holdGcLock}),this.started=!1}isStarted(){return this.started}start(){var t=this;return e._asyncToGenerator((function*(){yield Ba(t.child),t.started=!0}))()}stop(){var t=this;return e._asyncToGenerator((function*(){yield Da(t.child),t.started=!1}))()}unwrap(){return this.child}put(t,r){var n=arguments,i=this;return e._asyncToGenerator((function*(){var e,o=n.length>2&&void 0!==n[2]?n[2]:{};null==o||null===(e=o.signal)||void 0===e||e.throwIfAborted();var a=yield i.lock.readLock();try{return yield i.child.put(t,r,o)}finally{a()}}))()}putMany(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(i){null==n||null===(i=n.signal)||void 0===i||i.throwIfAborted();var o=yield e._awaitAsyncGenerator(r.lock.readLock());try{yield*e._asyncGeneratorDelegate(e._asyncIterator(r.child.putMany(t,n)),e._awaitAsyncGenerator)}finally{o()}}()})).apply(this,arguments)}get(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e,i=r.length>1&&void 0!==r[1]?r[1]:{};null==i||null===(e=i.signal)||void 0===e||e.throwIfAborted();var o=yield n.lock.readLock();try{return yield n.child.get(t,i)}finally{o()}}))()}getMany(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(i){null==n||null===(i=n.signal)||void 0===i||i.throwIfAborted();var o=yield e._awaitAsyncGenerator(r.lock.readLock());try{yield*e._asyncGeneratorDelegate(e._asyncIterator(r.child.getMany(t,n)),e._awaitAsyncGenerator)}finally{o()}}()})).apply(this,arguments)}delete(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e,i=r.length>1&&void 0!==r[1]?r[1]:{};null==i||null===(e=i.signal)||void 0===e||e.throwIfAborted();var o=yield n.lock.writeLock();try{if(yield n.pins.isPinned(t))throw new Error("CID was pinned");yield n.child.delete(t,i)}finally{o()}}))()}deleteMany(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(i){null==n||null===(i=n.signal)||void 0===i||i.throwIfAborted();var o=yield e._awaitAsyncGenerator(r.lock.writeLock());try{var a=r;yield*e._asyncGeneratorDelegate(e._asyncIterator(r.child.deleteMany(e._wrapAsyncGenerator((function*(){var r,n=!1,i=!1;try{for(var o,s=e._asyncIterator(t);n=!(o=yield e._awaitAsyncGenerator(s.next())).done;n=!1){var l=o.value;if(yield e._awaitAsyncGenerator(a.pins.isPinned(l)))throw new Error("CID was pinned");yield l}}catch(e){i=!0,r=e}finally{try{n&&null!=s.return&&(yield e._awaitAsyncGenerator(s.return()))}finally{if(i)throw r}}}))(),n)),e._awaitAsyncGenerator)}finally{o()}}()})).apply(this,arguments)}has(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e,i=r.length>1&&void 0!==r[1]?r[1]:{};null==i||null===(e=i.signal)||void 0===e||e.throwIfAborted();var o=yield n.lock.readLock();try{return yield n.child.has(t,i)}finally{o()}}))()}getAll(){var t=this;return e._wrapAsyncGenerator((function(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(n){null==r||null===(n=r.signal)||void 0===n||n.throwIfAborted();var i=yield e._awaitAsyncGenerator(t.lock.readLock());try{yield*e._asyncGeneratorDelegate(e._asyncIterator(t.child.getAll(r)),e._awaitAsyncGenerator)}finally{i()}}()})).apply(this,arguments)}createSession(e,t){var r;return null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),this.child.createSession(e,t)}}var aB=new Bc("/version");function sB(){return(sB=e._asyncToGenerator((function*(e){if(yield e.has(aB)){var t=Ze(yield e.get(aB));if(1!==parseInt(t,10))throw new Error("Unknown datastore version, a datastore migration may be required")}else yield e.put(aB,ot("".concat(1)))}))).apply(this,arguments)}function lB(e){return e instanceof ArrayBuffer?new Uint8Array(e,0,e.byteLength):e}var cB={float64:!0,typeEncoders:{Object:function(e){if(e.asCID!==e&&e["/"]!==e.bytes)return null;var t=je.asCID(e);if(!t)return null;var r=new Uint8Array(t.bytes.byteLength+1);return r.set(t.bytes,1),[new TT(xT.tag,42),new TT(xT.bytes,r)]},undefined:function(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")},number:function(e){if(Number.isNaN(e))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(e===1/0||e===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}}},uB=e._objectSpread2(e._objectSpread2({},cB),{},{typeEncoders:e._objectSpread2({},cB.typeEncoders)});var dB={allowIndefinite:!1,coerceUndefinedToNull:!0,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};dB.tags[42]=function(e){if(0!==e[0])throw new Error("Invalid CID for CBOR tag 42; expected leading 0x00");return je.decode(e.subarray(1))};var hB=e._objectSpread2(e._objectSpread2({},dB),{},{tags:dB.tags.slice()}),pB="dag-cbor",fB=113,vB=e=>eC(e,cB),yB=e=>aC(lB(e),dB),gB=Object.freeze({__proto__:null,code:fB,decode:yB,decodeOptions:hB,encode:vB,encodeOptions:uB,name:pB,toByteView:lB});class mB extends Array{constructor(){super(),this.inRecursive=[]}prefix(e){var t=this.inRecursive[this.inRecursive.length-1];t&&(t.type===xT.array&&(t.elements++,1!==t.elements&&e.push([44])),t.type===xT.map&&(t.elements++,1!==t.elements&&(t.elements%2==1?e.push([44]):e.push([58]))))}[xT.uint.major](e,t){this.prefix(e);for(var r=String(t.value),n=[],i=0;i<r.length;i++)n[i]=r.charCodeAt(i);e.push(n)}[xT.negint.major](e,t){this[xT.uint.major](e,t)}[xT.bytes.major](e,t){throw new Error("".concat(KT," unsupported type: Uint8Array"))}[xT.string.major](e,t){this.prefix(e);var r=RT(JSON.stringify(t.value));e.push(r.length>32?DT(r):r)}[xT.array.major](e,t){this.prefix(e),this.inRecursive.push({type:xT.array,elements:0}),e.push([91])}[xT.map.major](e,t){this.prefix(e),this.inRecursive.push({type:xT.map,elements:0}),e.push([123])}[xT.tag.major](e,t){}[xT.float.major](e,t){if("break"===t.type.name){var r=this.inRecursive.pop();if(r){if(r.type===xT.array)e.push([93]);else{if(r.type!==xT.map)throw new Error("Unexpected recursive type; this should not happen!");e.push([125])}return}throw new Error("Unexpected break; this should not happen!")}if(void 0===t.value)throw new Error("".concat(KT," unsupported type: undefined"));if(this.prefix(e),"true"!==t.type.name)if("false"!==t.type.name)if("null"!==t.type.name){for(var n=String(t.value),i=[],o=!1,a=0;a<n.length;a++)i[a]=n.charCodeAt(a),o||46!==i[a]&&101!==i[a]&&69!==i[a]||(o=!0);o||(i.push(46),i.push(48)),e.push(i)}else e.push([110,117,108,108]);else e.push([102,97,108,115,101]);else e.push([116,114,117,101])}}var wB={addBreakTokens:!0,mapSorter:function(e,t){if(Array.isArray(e[0])||Array.isArray(t[0]))throw new Error("".concat(KT," complex map keys are not supported"));var r=e[0],n=t[0];if(r.type!==xT.string||n.type!==xT.string)throw new Error("".concat(KT," non-string map keys are not supported"));if(r<n)return-1;if(r>n)return 1;throw new Error("".concat(KT," unexpected duplicate map keys, this is not supported"))}};class bB{constructor(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};this._pos=0,this.data=e,this.options=t,this.modeStack=["value"],this.lastToken=""}pos(){return this._pos}done(){return this._pos>=this.data.length}ch(){return this.data[this._pos]}currentMode(){return this.modeStack[this.modeStack.length-1]}skipWhitespace(){for(var e=this.ch();32===e||9===e||13===e||10===e;)e=this.data[++this._pos]}expect(e){if(this.data.length-this._pos<e.length)throw new Error("".concat(HT," unexpected end of input at position ").concat(this._pos));for(var t=0;t<e.length;t++)if(this.data[this._pos++]!==e[t])throw new Error("".concat(HT," unexpected token at position ").concat(this._pos,", expected to find '").concat(String.fromCharCode(...e),"'"))}parseNumber(){var e=this._pos,t=!1,r=!1,n=e=>{for(;!this.done();){var t=this.ch();if(!e.includes(t))break;this._pos++}};if(45===this.ch()&&(t=!0,this._pos++),48===this.ch()){if(this._pos++,46!==this.ch())return new TT(xT.uint,0,this._pos-e);this._pos++,r=!0}if(n([48,49,50,51,52,53,54,55,56,57]),t&&this._pos===e+1)throw new Error("".concat(HT," unexpected token at position ").concat(this._pos));if(!this.done()&&46===this.ch()){if(r)throw new Error("".concat(HT," unexpected token at position ").concat(this._pos));r=!0,this._pos++,n([48,49,50,51,52,53,54,55,56,57])}this.done()||101!==this.ch()&&69!==this.ch()||(r=!0,this._pos++,this.done()||43!==this.ch()&&45!==this.ch()||this._pos++,n([48,49,50,51,52,53,54,55,56,57]));var i=String.fromCharCode.apply(null,this.data.subarray(e,this._pos)),o=parseFloat(i);return r?new TT(xT.float,o,this._pos-e):!0!==this.options.allowBigInt||Number.isSafeInteger(o)?new TT(o>=0?xT.uint:xT.negint,o,this._pos-e):new TT(o>=0?xT.uint:xT.negint,BigInt(i),this._pos-e)}parseString(){if(34!==this.ch())throw new Error("".concat(HT," unexpected character at position ").concat(this._pos,"; this shouldn't happen"));this._pos++;for(var e=this._pos,t=0;e<this.data.length&&t<65536;e++,t++){var r=this.data[e];if(92===r||r<32||r>=128)break;if(34===r){var n=String.fromCharCode.apply(null,this.data.subarray(this._pos,e));return this._pos=e+1,new TT(xT.string,n,t)}}for(var i=this._pos,o=[],a=()=>{if(this._pos+4>=this.data.length)throw new Error("".concat(HT," unexpected end of unicode escape sequence at position ").concat(this._pos));for(var e=0,t=0;t<4;t++){var r=this.ch();if(r>=48&&r<=57)r-=48;else if(r>=97&&r<=102)r=r-97+10;else{if(!(r>=65&&r<=70))throw new Error("".concat(HT," unexpected unicode escape character at position ").concat(this._pos));r=r-65+10}e=16*e+r,this._pos++}return e},s=()=>{var e,t,r,n,i=this.ch(),a=null,s=i>239?4:i>223?3:i>191?2:1;if(this._pos+s>this.data.length)throw new Error("".concat(HT," unexpected unicode sequence at position ").concat(this._pos));switch(s){case 1:i<128&&(a=i);break;case 2:128==(192&(e=this.data[this._pos+1]))&&(n=(31&i)<<6|63&e)>127&&(a=n);break;case 3:e=this.data[this._pos+1],t=this.data[this._pos+2],128==(192&e)&&128==(192&t)&&(n=(15&i)<<12|(63&e)<<6|63&t)>2047&&(n<55296||n>57343)&&(a=n);break;case 4:e=this.data[this._pos+1],t=this.data[this._pos+2],r=this.data[this._pos+3],128==(192&e)&&128==(192&t)&&128==(192&r)&&(n=(15&i)<<18|(63&e)<<12|(63&t)<<6|63&r)>65535&&n<1114112&&(a=n)}null===a?(a=65533,s=1):a>65535&&(a-=65536,o.push(a>>>10&1023|55296),a=56320|1023&a),o.push(a),this._pos+=s};!this.done();){var l=this.ch(),c=void 0;switch(l){case 92:if(this._pos++,this.done())throw new Error("".concat(HT," unexpected string termination at position ").concat(this._pos));switch(c=this.ch(),this._pos++,c){case 34:case 39:case 92:case 47:o.push(c);break;case 98:o.push(8);break;case 116:o.push(9);break;case 110:o.push(10);break;case 102:o.push(12);break;case 114:o.push(13);break;case 117:o.push(a());break;default:throw new Error("".concat(HT," unexpected string escape character at position ").concat(this._pos))}break;case 34:return this._pos++,new TT(xT.string,VT(o),this._pos-i);default:if(l<32)throw new Error("".concat(HT," invalid control character at position ").concat(this._pos));l<128?(o.push(l),this._pos++):s()}}throw new Error("".concat(HT," unexpected end of string at position ").concat(this._pos))}parseValue(){switch(this.ch()){case 123:return this.modeStack.push("obj-start"),this._pos++,new TT(xT.map,1/0,1);case 91:return this.modeStack.push("array-start"),this._pos++,new TT(xT.array,1/0,1);case 34:return this.parseString();case 110:return this.expect([110,117,108,108]),new TT(xT.null,null,4);case 102:return this.expect([102,97,108,115,101]),new TT(xT.false,!1,5);case 116:return this.expect([116,114,117,101]),new TT(xT.true,!0,4);case 45:case 48:case 49:case 50:case 51:case 52:case 53:case 54:case 55:case 56:case 57:return this.parseNumber();default:throw new Error("".concat(HT," unexpected character at position ").concat(this._pos))}}next(){switch(this.skipWhitespace(),this.currentMode()){case"value":return this.modeStack.pop(),this.parseValue();case"array-value":if(this.modeStack.pop(),93===this.ch())return this._pos++,this.skipWhitespace(),new TT(xT.break,void 0,1);if(44!==this.ch())throw new Error("".concat(HT," unexpected character at position ").concat(this._pos,", was expecting array delimiter but found '").concat(String.fromCharCode(this.ch()),"'"));return this._pos++,this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue();case"array-start":return this.modeStack.pop(),93===this.ch()?(this._pos++,this.skipWhitespace(),new TT(xT.break,void 0,1)):(this.modeStack.push("array-value"),this.skipWhitespace(),this.parseValue());case"obj-key":if(125===this.ch())return this.modeStack.pop(),this._pos++,this.skipWhitespace(),new TT(xT.break,void 0,1);if(44!==this.ch())throw new Error("".concat(HT," unexpected character at position ").concat(this._pos,", was expecting object delimiter but found '").concat(String.fromCharCode(this.ch()),"'"));this._pos++,this.skipWhitespace();case"obj-start":if(this.modeStack.pop(),125===this.ch())return this._pos++,this.skipWhitespace(),new TT(xT.break,void 0,1);var e=this.parseString();if(this.skipWhitespace(),58!==this.ch())throw new Error("".concat(HT," unexpected character at position ").concat(this._pos,", was expecting key/value delimiter ':' but found '").concat(String.fromCharCode(this.ch()),"'"));return this._pos++,this.modeStack.push("obj-value"),e;case"obj-value":return this.modeStack.pop(),this.modeStack.push("obj-key"),this.skipWhitespace(),this.parseValue();default:throw new Error("".concat(HT," unexpected parse state at position ").concat(this._pos,"; this shouldn't happen"))}}}function _B(e){var t=z.encode(e).slice(1);return[new TT(xT.map,1/0,1),new TT(xT.string,"/",1),new TT(xT.map,1/0,1),new TT(xT.string,"bytes",5),new TT(xT.string,t,t.length),new TT(xT.break,void 0,1),new TT(xT.break,void 0,1)]}function SB(e){return _B(new Uint8Array(e.buffer,e.byteOffset,e.byteLength))}var PB={typeEncoders:{Object:function(e){if(e.asCID!==e&&e["/"]!==e.bytes)return null;var t=je.asCID(e);if(!t)return null;var r=t.toString();return[new TT(xT.map,1/0,1),new TT(xT.string,"/",1),new TT(xT.string,r,r.length),new TT(xT.break,void 0,1)]},Buffer:_B,Uint8Array:_B,Int8Array:SB,Uint16Array:SB,Int16Array:SB,Uint32Array:SB,Int32Array:SB,Float32Array:SB,Float64Array:SB,Uint8ClampedArray:SB,BigInt64Array:SB,BigUint64Array:SB,DataView:SB,ArrayBuffer:function(e){return _B(new Uint8Array(e))},undefined:function(){throw new Error("`undefined` is not supported by the IPLD Data Model and cannot be encoded")},number:function(e){if(Number.isNaN(e))throw new Error("`NaN` is not supported by the IPLD Data Model and cannot be encoded");if(e===1/0||e===-1/0)throw new Error("`Infinity` and `-Infinity` is not supported by the IPLD Data Model and cannot be encoded");return null}}};class EB extends bB{constructor(e,t){super(e,t),this.tokenBuffer=[]}done(){return 0===this.tokenBuffer.length&&super.done()}_next(){return this.tokenBuffer.length>0?this.tokenBuffer.pop():super.next()}next(){var e=this._next();if(e.type===xT.map){var t=this._next();if(t.type===xT.string&&"/"===t.value){var r=this._next();if(r.type===xT.string){if(this._next().type!==xT.break)throw new Error("Invalid encoded CID form");return this.tokenBuffer.push(r),new TT(xT.tag,42,0)}if(r.type===xT.map){var n=this._next();if(n.type===xT.string&&"bytes"===n.value){var i=this._next();if(i.type===xT.string){for(var o=0;o<2;o++){if(this._next().type!==xT.break)throw new Error("Invalid encoded Bytes form")}var a=z.decode("m".concat(i.value));return new TT(xT.bytes,a,i.value.length)}this.tokenBuffer.push(i)}this.tokenBuffer.push(n)}this.tokenBuffer.push(r)}this.tokenBuffer.push(t)}return e}}var AB={allowIndefinite:!1,allowUndefined:!1,allowNaN:!1,allowInfinity:!1,allowBigInt:!0,strict:!0,useMaps:!1,rejectDuplicateMapKeys:!0,tags:[]};AB.tags[42]=je.parse;var kB=297,xB=e=>function(e,t){return t=Object.assign({},wB,t),XI(e,new mB,t)}(e,PB),TB=e=>{var t=function(e){return e instanceof ArrayBuffer?new Uint8Array(e,0,e.byteLength):e}(e);return function(e,t){return aC(e,t=Object.assign({tokenizer:new bB(e,t)},t))}(t,Object.assign(AB,{tokenizer:new EB(t,AB)}))},IB=e=>CB.decode(xB(e)),CB=new TextDecoder,BB=new TextEncoder,NB=Object.freeze({__proto__:null,code:297,decode:TB,encode:xB,format:IB,name:"dag-json",parse:e=>TB(BB.encode(e)),stringify:IB}),DB=new TextDecoder;function GB(e,t){for(var r=0,n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(t>=e.length)throw new Error("protobuf: unexpected end of data");var i=e[t++];if(r+=n<28?(127&i)<<n:(127&i)*2**n,i<128)break}return[r,t]}function RB(e,t){var r;[r,t]=GB(e,t);var n=t+r;if(r<0||n<0)throw new Error("protobuf: invalid length");if(n>e.length)throw new Error("protobuf: unexpected end of data");return[e.subarray(t,n),n]}function OB(e,t){var r;return[r,t]=GB(e,t),[7&r,r>>3,t]}function LB(e){for(var t={},r=e.length,n=0;n<r;){var i=void 0,o=void 0;if([i,o,n]=OB(e,n),1===o){if(t.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(2!==i)throw new Error("protobuf: (PBLink) wrong wireType (".concat(i,") for Hash"));if(void 0!==t.Name)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(void 0!==t.Tsize)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[t.Hash,n]=RB(e,n)}else if(2===o){if(void 0!==t.Name)throw new Error("protobuf: (PBLink) duplicate Name section");if(2!==i)throw new Error("protobuf: (PBLink) wrong wireType (".concat(i,") for Name"));if(void 0!==t.Tsize)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");var a=void 0;[a,n]=RB(e,n),t.Name=DB.decode(a)}else{if(3!==o)throw new Error("protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ".concat(o));if(void 0!==t.Tsize)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(0!==i)throw new Error("protobuf: (PBLink) wrong wireType (".concat(i,") for Tsize"));[t.Tsize,n]=GB(e,n)}}if(n>r)throw new Error("protobuf: (PBLink) unexpected end of data");return t}var MB=new TextEncoder,jB=2**32,FB=2**31;function UB(e,t){var r=t.length;if("number"==typeof e.Tsize){if(e.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(e.Tsize))throw new Error("Tsize too large for encoding");t[r=qB(t,r,e.Tsize)-1]=24}if("string"==typeof e.Name){var n=MB.encode(e.Name);r-=n.length,t.set(n,r),t[r=qB(t,r,n.length)-1]=18}return e.Hash&&(r-=e.Hash.length,t.set(e.Hash,r),t[r=qB(t,r,e.Hash.length)-1]=10),t.length-r}function zB(e){var t=function(e){var t=0;if(e.Data){var r=e.Data.length;t+=1+r+HB(r)}if(e.Links)for(var n of e.Links){var i=VB(n);t+=1+i+HB(i)}return t}(e),r=new Uint8Array(t),n=t;if(e.Data&&(n-=e.Data.length,r.set(e.Data,n),r[n=qB(r,n,e.Data.length)-1]=10),e.Links)for(var i=e.Links.length-1;i>=0;i--){var o=UB(e.Links[i],r.subarray(0,n));r[n=qB(r,n-=o,o)-1]=18}return r}function VB(e){var t=0;if(e.Hash){var r=e.Hash.length;t+=1+r+HB(r)}if("string"==typeof e.Name){var n=MB.encode(e.Name).length;t+=1+n+HB(n)}return"number"==typeof e.Tsize&&(t+=1+HB(e.Tsize)),t}function qB(e,t,r){for(var n=t-=HB(r);r>=FB;)e[t++]=127&r|128,r/=128;for(;r>=128;)e[t++]=127&r|128,r>>>=7;return e[t]=r,n}function HB(e){return e%2==0&&e++,Math.floor((function(e){var t=0;e>=jB&&(e=Math.floor(e/jB),t=32);e>=65536&&(e>>>=16,t+=16);e>=256&&(e>>>=8,t+=8);return t+KB[e]}(e)+6)/7)}var KB=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8],WB=["Data","Links"],QB=["Hash","Name","Tsize"],YB=new TextEncoder;function JB(e,t){if(e===t)return 0;for(var r=e.Name?YB.encode(e.Name):[],n=t.Name?YB.encode(t.Name):[],i=r.length,o=n.length,a=0,s=Math.min(i,o);a<s;++a)if(r[a]!==n[a]){i=r[a],o=n[a];break}return i<o?-1:o<i?1:0}function ZB(e,t){return!Object.keys(e).some((e=>!t.includes(e)))}function $B(e){if("object"==typeof e.asCID){var t=je.asCID(e);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if("object"!=typeof e||Array.isArray(e))throw new TypeError("Invalid DAG-PB form");var r={};if(e.Hash){var n=je.asCID(e.Hash);try{n||("string"==typeof e.Hash?n=je.parse(e.Hash):e.Hash instanceof Uint8Array&&(n=je.decode(e.Hash)))}catch(e){throw new TypeError("Invalid DAG-PB form: ".concat(e.message))}n&&(r.Hash=n)}if(!r.Hash)throw new TypeError("Invalid DAG-PB form");return"string"==typeof e.Name&&(r.Name=e.Name),"number"==typeof e.Tsize&&(r.Tsize=e.Tsize),r}function XB(e){if((e instanceof Uint8Array||"string"==typeof e)&&(e={Data:e}),"object"!=typeof e||Array.isArray(e))throw new TypeError("Invalid DAG-PB form");var t={};if(void 0!==e.Data)if("string"==typeof e.Data)t.Data=YB.encode(e.Data);else{if(!(e.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form");t.Data=e.Data}if(void 0!==e.Links){if(!Array.isArray(e.Links))throw new TypeError("Invalid DAG-PB form");t.Links=e.Links.map($B),t.Links.sort(JB)}else t.Links=[];return t}function eN(e){if(!e||"object"!=typeof e||Array.isArray(e)||e instanceof Uint8Array||e["/"]&&e["/"]===e.bytes)throw new TypeError("Invalid DAG-PB form");if(!ZB(e,WB))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(void 0!==e.Data&&!(e.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(e.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(var t=0;t<e.Links.length;t++){var r=e.Links[t];if(!r||"object"!=typeof r||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!ZB(r,QB))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(void 0===r.Hash)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(null==r.Hash||!r.Hash["/"]||r.Hash["/"]!==r.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(void 0!==r.Name&&"string"!=typeof r.Name)throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(void 0!==r.Tsize){if("number"!=typeof r.Tsize||r.Tsize%1!=0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(r.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(t>0&&-1===JB(r,e.Links[t-1]))throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}var tN=112;function rN(e){eN(e);var t={};return e.Links&&(t.Links=e.Links.map((e=>{var t={};return e.Hash&&(t.Hash=e.Hash.bytes),void 0!==e.Name&&(t.Name=e.Name),void 0!==e.Tsize&&(t.Tsize=e.Tsize),t}))),e.Data&&(t.Data=e.Data),zB(t)}function nN(e){var t=function(e){for(var t=e.length,r=0,n=void 0,i=!1,o=void 0;r<t;){var a=void 0,s=void 0;if([a,s,r]=OB(e,r),2!==a)throw new Error("protobuf: (PBNode) invalid wireType, expected 2, got ".concat(a));if(1===s){if(o)throw new Error("protobuf: (PBNode) duplicate Data section");[o,r]=RB(e,r),n&&(i=!0)}else{if(2!==s)throw new Error("protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ".concat(s));if(i)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);var l=void 0;[l,r]=RB(e,r),n.push(LB(l))}}if(r>t)throw new Error("protobuf: (PBNode) unexpected end of data");var c={};return o&&(c.Data=o),c.Links=n||[],c}(function(e){return e instanceof ArrayBuffer?new Uint8Array(e,0,e.byteLength):e}(e)),r={};return t.Data&&(r.Data=t.Data),t.Links&&(r.Links=t.Links.map((e=>{var t={};try{t.Hash=je.decode(e.Hash)}catch(e){}if(!t.Hash)throw new Error("Invalid Hash field found in link, expected CID");return void 0!==e.Name&&(t.Name=e.Name),void 0!==e.Tsize&&(t.Tsize=e.Tsize),t}))),r}var iN=Object.freeze({__proto__:null,code:tN,createLink:function(e,t,r){return $B({Hash:r,Name:e,Tsize:t})},createNode:function(e){return XB({Data:e,Links:arguments.length>1&&void 0!==arguments[1]?arguments[1]:[]})},decode:nN,encode:rN,name:"dag-pb",prepare:XB,validate:eN});function oN(e){return null!=(null==e?void 0:e.then)}class aN extends Nu{constructor(t){super(),e._defineProperty(this,"child",void 0),this.child=t}put(e,t,r){var n,i;return 0===e.multihash.code?(null==r||null===(n=r.signal)||void 0===n||n.throwIfAborted(),e):null==this.child?(null==r||null===(i=r.signal)||void 0===i||i.throwIfAborted(),e):this.child.put(e,t,r)}get(e,t){var r,n;if(0===e.multihash.code)return null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),e.multihash.digest;if(null==this.child)throw null==t||null===(n=t.signal)||void 0===n||n.throwIfAborted(),new Hc;return this.child.get(e,t)}has(e,t){var r,n;return 0===e.multihash.code?(null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),!0):null==this.child?(null==t||null===(n=t.signal)||void 0===n||n.throwIfAborted(),!1):this.child.has(e,t)}delete(e,t){var r;if(0!==e.code){if(null!=this.child)return this.child.delete(e,t)}else null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted()}getAll(e){var t;return null!=this.child?this.child.getAll(e):(null==e||null===(t=e.signal)||void 0===t||t.throwIfAborted(),[])}}class sN{constructor(t){e._defineProperty(this,"child",void 0),e._defineProperty(this,"getHasher",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"logger",void 0),e._defineProperty(this,"components",void 0),this.log=t.logger.forComponent("helia:networked-storage"),this.logger=t.logger,this.components=t,this.child=new aN(t.blockstore),this.getHasher=t.getHasher}put(t,r){var n=arguments,i=this;return e._asyncToGenerator((function*(){var o,a,s,l=n.length>2&&void 0!==n[2]?n[2]:{};return(yield i.child.has(t,l))?(null===(s=l.onProgress)||void 0===s||s.call(l,new Ih("blocks:put:duplicate",t)),t):(null===(o=l.onProgress)||void 0===o||o.call(l,new Ih("blocks:put:providers:notify",t)),yield Promise.all(i.components.blockBrokers.map(function(){var n=e._asyncToGenerator((function*(e){var n;return null===(n=e.announce)||void 0===n?void 0:n.call(e,t,r,l)}));return function(e){return n.apply(this,arguments)}}())),null===(a=l.onProgress)||void 0===a||a.call(l,new Ih("blocks:put:blockstore:put",t)),i.child.put(t,r,l))}))()}putMany(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(i){var o=Gc(t,function(){var t=e._asyncToGenerator((function*(e){var t,{cid:i}=e,o=yield r.child.has(i,n);o&&(null===(t=n.onProgress)||void 0===t||t.call(n,new Ih("blocks:put-many:duplicate",i)));return!o}));return function(e){return t.apply(this,arguments)}}()),a=xh(o,function(){var t=e._asyncToGenerator((function*(t){var i,{cid:o,block:a}=t;null===(i=n.onProgress)||void 0===i||i.call(n,new Ih("blocks:put-many:providers:notify",o)),yield Promise.all(r.components.blockBrokers.map(function(){var t=e._asyncToGenerator((function*(e){var t;return null===(t=e.announce)||void 0===t?void 0:t.call(e,o,a,n)}));return function(e){return t.apply(this,arguments)}}()))}));return function(e){return t.apply(this,arguments)}}());null===(i=n.onProgress)||void 0===i||i.call(n,new Ih("blocks:put-many:blockstore:put-many")),yield*e._asyncGeneratorDelegate(e._asyncIterator(r.child.putMany(a,n)))}()})).apply(this,arguments)}get(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i,o=r.length>1&&void 0!==r[1]?r[1]:{};if(!0!==o.offline&&!(yield n.child.has(t,o))){var a,s,l,c=yield n.getHasher(t.multihash.code);null===(a=o.onProgress)||void 0===a||a.call(o,new Ih("blocks:get:providers:get",t));var u=yield hN(t,n.components.blockBrokers,c,e._objectSpread2(e._objectSpread2({},o),{},{log:n.log}));return null===(s=o.onProgress)||void 0===s||s.call(o,new Ih("blocks:get:blockstore:put",t)),yield n.child.put(t,u,o),null===(l=o.onProgress)||void 0===l||l.call(o,new Ih("blocks:get:providers:notify",t)),yield Promise.all(n.components.blockBrokers.map(function(){var r=e._asyncToGenerator((function*(e){var r;return null===(r=e.announce)||void 0===r?void 0:r.call(e,t,u,o)}));return function(e){return r.apply(this,arguments)}}())),u}return null===(i=o.onProgress)||void 0===i||i.call(o,new Ih("blocks:get:blockstore:get",t)),n.child.get(t,o)}))()}getMany(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(i){null===(i=n.onProgress)||void 0===i||i.call(n,new Ih("blocks:get-many:blockstore:get-many")),yield*e._asyncGeneratorDelegate(e._asyncIterator(r.child.getMany(xh(t,function(){var t=e._asyncToGenerator((function*(t){if(!0!==n.offline&&!(yield r.child.has(t,n))){var i,o,a,s=yield r.getHasher(t.multihash.code);null===(i=n.onProgress)||void 0===i||i.call(n,new Ih("blocks:get-many:providers:get",t));var l=yield hN(t,r.components.blockBrokers,s,e._objectSpread2(e._objectSpread2({},n),{},{log:r.log}));null===(o=n.onProgress)||void 0===o||o.call(n,new Ih("blocks:get-many:blockstore:put",t)),yield r.child.put(t,l,n),null===(a=n.onProgress)||void 0===a||a.call(n,new Ih("blocks:get-many:providers:notify",t)),yield Promise.all(r.components.blockBrokers.map(function(){var r=e._asyncToGenerator((function*(e){var r;return null===(r=e.announce)||void 0===r?void 0:r.call(e,t,l,n)}));return function(e){return r.apply(this,arguments)}}()))}}));return function(e){return t.apply(this,arguments)}}()))))}()})).apply(this,arguments)}delete(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e,i=r.length>1&&void 0!==r[1]?r[1]:{};null===(e=i.onProgress)||void 0===e||e.call(i,new Ih("blocks:delete:blockstore:delete",t)),yield n.child.delete(t,i)}))()}deleteMany(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(i){null===(i=n.onProgress)||void 0===i||i.call(n,new Ih("blocks:delete-many:blockstore:delete-many")),yield*e._asyncGeneratorDelegate(e._asyncIterator(r.child.deleteMany(e._wrapAsyncGenerator((function*(){var r,n=!1,i=!1;try{for(var o,a=e._asyncIterator(t);n=!(o=yield e._awaitAsyncGenerator(a.next())).done;n=!1){var s=o.value;yield s}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield e._awaitAsyncGenerator(a.return()))}finally{if(i)throw r}}}))(),n)))}()})).apply(this,arguments)}has(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};return n.child.has(t,e)}))()}getAll(){var t=this;return e._wrapAsyncGenerator((function(){var r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(n){null===(n=r.onProgress)||void 0===n||n.call(r,new Ih("blocks:get-all:blockstore:get-many")),yield*e._asyncGeneratorDelegate(e._asyncIterator(t.child.getAll(r)))}()})).apply(this,arguments)}}class lN extends sN{constructor(t){super(t),e._defineProperty(this,"started",void 0),this.started=!1}isStarted(){return this.started}start(){var t=this;return e._asyncToGenerator((function*(){yield Ba(t.child,...t.components.blockBrokers),t.started=!0}))()}stop(){var t=this;return e._asyncToGenerator((function*(){yield Da(t.child,...t.components.blockBrokers),t.started=!1}))()}unwrap(){return this.child}createSession(e,t){var r=this.components.blockBrokers.map((e=>null==e.createSession?e:e.createSession(t)));return new cN({blockstore:this.child,blockBrokers:r,getHasher:this.getHasher,logger:this.logger},{root:e})}}class cN extends sN{constructor(t,r){super(t),e._defineProperty(this,"closeController",void 0),this.closeController=new AbortController,this.closeController.signal,this.log=t.logger.forComponent("helia:session-storage:".concat(r.root))}close(){this.closeController.abort()}put(t,r){var n=arguments,i=()=>super.put,o=this;return e._asyncToGenerator((function*(){var a=n.length>2&&void 0!==n[2]?n[2]:{},s=$d([o.closeController.signal,a.signal]);try{return yield i().call(o,t,r,e._objectSpread2(e._objectSpread2({},a),{},{signal:s}))}finally{s.clear()}}))()}putMany(t){var r=()=>super.putMany,n=this;return e._wrapAsyncGenerator((function(t){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var o=$d([n.closeController.signal,i.signal]);try{yield*e._asyncGeneratorDelegate(e._asyncIterator(r().call(n,t,e._objectSpread2(e._objectSpread2({},i),{},{signal:o}))),e._awaitAsyncGenerator)}finally{o.clear()}}()})).apply(this,arguments)}get(t){var r=arguments,n=()=>super.get,i=this;return e._asyncToGenerator((function*(){var o=r.length>1&&void 0!==r[1]?r[1]:{},a=$d([i.closeController.signal,o.signal]);try{return yield n().call(i,t,e._objectSpread2(e._objectSpread2({},o),{},{signal:a}))}finally{a.clear()}}))()}getMany(t){var r=()=>super.getMany,n=this;return e._wrapAsyncGenerator((function(t){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var o=$d([n.closeController.signal,i.signal]);try{yield*e._asyncGeneratorDelegate(e._asyncIterator(r().call(n,t,e._objectSpread2(e._objectSpread2({},i),{},{signal:o}))),e._awaitAsyncGenerator)}finally{o.clear()}}()})).apply(this,arguments)}delete(t){var r=arguments,n=()=>super.delete,i=this;return e._asyncToGenerator((function*(){var o=r.length>1&&void 0!==r[1]?r[1]:{},a=$d([i.closeController.signal,o.signal]);try{yield n().call(i,t,e._objectSpread2(e._objectSpread2({},o),{},{signal:a}))}finally{a.clear()}}))()}deleteMany(t){var r=()=>super.deleteMany,n=this;return e._wrapAsyncGenerator((function(t){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var o=$d([n.closeController.signal,i.signal]);try{yield*e._asyncGeneratorDelegate(e._asyncIterator(r().call(n,t,e._objectSpread2(e._objectSpread2({},i),{},{signal:o}))),e._awaitAsyncGenerator)}finally{o.clear()}}()})).apply(this,arguments)}has(t){var r=arguments,n=()=>super.has,i=this;return e._asyncToGenerator((function*(){var o=r.length>1&&void 0!==r[1]?r[1]:{},a=$d([i.closeController.signal,o.signal]);try{return yield n().call(i,t,e._objectSpread2(e._objectSpread2({},o),{},{signal:a}))}finally{a.clear()}}))()}getAll(){var t=()=>super.getAll,r=this;return e._wrapAsyncGenerator((function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(){var i=$d([r.closeController.signal,n.signal]);try{yield*e._asyncGeneratorDelegate(e._asyncIterator(t().call(r,e._objectSpread2(e._objectSpread2({},n),{},{signal:i}))),e._awaitAsyncGenerator)}finally{i.clear()}}()})).apply(this,arguments)}}function uN(e){return"function"==typeof e.retrieve}var dN=(t,r)=>{if(null==r)throw new ea("No hasher configured for multihash code 0x".concat(t.multihash.code.toString(16),", please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv"));return function(){var n=e._asyncToGenerator((function*(e){var n=r.digest(e);if(!nt((oN(n)?yield n:n).digest,t.multihash.digest))throw new fa("Hash of downloaded block did not match multihash from passed CID")}));return function(e){return n.apply(this,arguments)}}()};function hN(e,t,r,n){return pN.apply(this,arguments)}function pN(){return pN=e._asyncToGenerator((function*(t,r,n,i){var o=dN(t,n),a=new AbortController,s=$d([a.signal,i.signal]);a.signal;var l=[];for(var c of r)uN(c)&&l.push(c);try{return yield Promise.any(l.map(function(){var r=e._asyncToGenerator((function*(r){try{var n=!1,a=yield r.retrieve(t,e._objectSpread2(e._objectSpread2({},i),{},{signal:s,validateFn:(l=e._asyncToGenerator((function*(e){yield o(e),n=!0})),function(e){return l.apply(this,arguments)})}));return n||(yield o(a)),a}catch(e){throw i.log.error("could not retrieve verified block for %c",t,e),e}var l}));return function(e){return r.apply(this,arguments)}}()))}finally{a.abort(),s.clear()}})),pN.apply(this,arguments)}class fN extends Ia{constructor(t,r){var n,i,o;super(),e._defineProperty(this,"initialPeerSearchComplete",void 0),e._defineProperty(this,"requests",void 0),e._defineProperty(this,"name",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"logger",void 0),e._defineProperty(this,"minProviders",void 0),e._defineProperty(this,"maxProviders",void 0),e._defineProperty(this,"providers",void 0),e._defineProperty(this,"evictionFilter",void 0),e._defineProperty(this,"initialProviders",void 0),this.name=r.name,this.logger=t.logger,this.log=t.logger.forComponent(this.name),this.requests=new Map,this.minProviders=null!==(n=r.minProviders)&&void 0!==n?n:1,this.maxProviders=null!==(i=r.maxProviders)&&void 0!==i?i:5,this.providers=[],this.evictionFilter=_h(this.maxProviders),this.initialProviders=null!==(o=r.providers)&&void 0!==o?o:[]}retrieve(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i,o=r.length>1&&void 0!==r[1]?r[1]:{},a=z.encode(t.multihash.bytes),s=n.requests.get(a);if(null!=s)return n.log("join existing request for %c",t),s;var l=Yc();if(n.requests.set(a,l.promise),0===n.providers.length){var c=!1;null==n.initialPeerSearchComplete&&(c=!0,n.log=n.logger.forComponent("".concat(n.name,":").concat(t)),n.initialPeerSearchComplete=n.findProviders(t,n.minProviders,o)),yield n.initialPeerSearchComplete,c&&n.log("found initial session peers for %c",t)}var u=!1,d=new Mh({concurrency:n.maxProviders});d.addEventListener("error",(()=>{})),d.addEventListener("failure",(e=>{n.log.error("error querying provider %o, evicting from session",e.detail.job.options.provider,e.detail.error),n.evict(e.detail.job.options.provider)})),d.addEventListener("success",(e=>{u=!0,l.resolve(e.detail.result)})),d.addEventListener("idle",(()=>{var r;u||!0===(null===(r=o.signal)||void 0===r?void 0:r.aborted)?n.log.trace("session idle, found block"):Promise.resolve().then(e._asyncToGenerator((function*(){n.log("no session peers had block for for %c, finding new providers",t);for(var e=0;e<n.minProviders&&0!==n.providers.length;e++){var r=n.providers[Math.floor(Math.random()*n.providers.length)];n.evict(r)}yield n.findProviders(t,n.minProviders,o),n.log("found new providers re-retrieving %c",t),n.requests.delete(a),l.resolve(yield n.retrieve(t,o))}))).catch((e=>{n.log.error("could not find new providers for %c",t,e),l.reject(e)}))}));var h=r=>{d.add(e._asyncToGenerator((function*(){return n.queryProvider(t,r.detail,o)})),{provider:r.detail}).catch((e=>{var r;!0!==(null===(r=o.signal)||void 0===r?void 0:r.aborted)&&n.log.error("error retrieving session block for %c",t,e)}))};n.addEventListener("provider",h),Promise.all([...n.providers].map(function(){var r=e._asyncToGenerator((function*(r){return d.add(e._asyncToGenerator((function*(){return n.queryProvider(t,r,o)})),{provider:r})}));return function(e){return r.apply(this,arguments)}}())).catch((e=>{var r;!0!==(null===(r=o.signal)||void 0===r?void 0:r.aborted)&&n.log.error("error retrieving session block for %c",t,e)}));var p=()=>{var e,t;l.reject(new Zo(null!==(e=null===(t=o.signal)||void 0===t?void 0:t.reason)&&void 0!==e?e:"Session aborted")),d.abort()};null===(i=o.signal)||void 0===i||i.addEventListener("abort",p);try{return yield l.promise}finally{var f;n.removeEventListener("provider",h),null===(f=o.signal)||void 0===f||f.removeEventListener("abort",p),d.clear(),n.requests.delete(a)}}))()}evict(e){this.evictionFilter.add(this.toEvictionKey(e));var t=this.providers.findIndex((t=>this.equals(t,e)));-1!==t&&this.providers.splice(t,1)}isEvicted(e){return this.evictionFilter.has(this.toEvictionKey(e))}hasProvider(e){return null!=this.providers.find((t=>this.equals(t,e)))||!!this.isEvicted(e)}findProviders(t,r,n){var i=this;return e._asyncToGenerator((function*(){var o=Yc(),a=0;return Promise.resolve().then(e._asyncToGenerator((function*(){if(i.log("finding %d-%d new provider(s) for %c",r,i.maxProviders,t),i.initialProviders.length>0)for(;a<r&&i.initialProviders.length>0;){var s,l=i.initialProviders.pop();if(null==l)break;var c=yield i.convertToProvider(l,n);if(!0===(null===(s=n.signal)||void 0===s?void 0:s.aborted))break;if(null!=c&&(!i.hasProvider(c)&&(i.log("found %d/%d new providers",a,i.maxProviders),i.providers.push(c),i.safeDispatchEvent("provider",{detail:c}),++a===r&&(i.log("session is ready"),o.resolve()),i.providers.length===i.maxProviders))){i.log("found max session peers",a);break}}if(a<i.maxProviders){var u,d=!1,h=!1;try{for(var p,f=e._asyncIterator(i.findNewProviders(t,n));d=!(p=yield f.next()).done;d=!1){var v,y=p.value;if(a===i.maxProviders||!0===(null===(v=n.signal)||void 0===v?void 0:v.aborted))break;if(!i.hasProvider(y)&&(i.log("found %d/%d new providers",a,i.maxProviders),i.providers.push(y),i.safeDispatchEvent("provider",{detail:y}),++a===r&&(i.log("session is ready"),o.resolve()),i.providers.length===i.maxProviders)){i.log("found max session peers",a);break}}}catch(e){h=!0,u=e}finally{try{d&&null!=f.return&&(yield f.return())}finally{if(h)throw u}}}if(i.log("found %d/%d new session peers",a,i.maxProviders),a<r)throw new SC("Found ".concat(a," of ").concat(r," ").concat(i.name," providers for ").concat(t))}))).catch((e=>{var r;i.log.error("error searching routing for potential session peers for %c",t,null!==(r=e.errors)&&void 0!==r?r:e),o.reject(e)})),o.promise}))()}}class vN{constructor(t){var r,n,i,o,a;e._defineProperty(this,"blockstore",void 0),e._defineProperty(this,"datastore",void 0),e._defineProperty(this,"pins",void 0),e._defineProperty(this,"logger",void 0),e._defineProperty(this,"routing",void 0),e._defineProperty(this,"getCodec",void 0),e._defineProperty(this,"getHasher",void 0),e._defineProperty(this,"dns",void 0),e._defineProperty(this,"metrics",void 0),e._defineProperty(this,"log",void 0),this.logger=null!==(r=t.logger)&&void 0!==r?r:Iu(),this.log=this.logger.forComponent("helia"),this.getHasher=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],r=arguments.length>1?arguments[1]:void 0,n={[De.code]:De,[Ge.code]:Ge,[Te.code]:Te};return t.forEach((e=>{n[e.code]=e})),function(){var t=e._asyncToGenerator((function*(e){var t=n[e];if(null==t&&null!=r){var i=r(e);t=oN(i)?yield i:i,n[t.code]=t}if(null!=t)return t;throw new EC("No hasher configured for multihash code 0x".concat(e.toString(16),", please configure one. You can look up which hash this is at https://github.com/multiformats/multicodec/blob/master/table.csv"))}));return function(e){return t.apply(this,arguments)}}()}(t.hashers,t.loadHasher),this.getCodec=function(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:[],r=arguments.length>1?arguments[1]:void 0,n={[tN]:iN,[re]:ne,[fB]:gB,[kB]:NB,[X]:te};return t.forEach((e=>{n[e.code]=e})),function(){var t=e._asyncToGenerator((function*(e){var t=n[e];if(null==t&&null!=r){var i=r(e);t=oN(i)?yield i:i,n[t.code]=t}if(null!=t)return t;throw new AC("Could not load codec for ".concat(e))}));return function(e){return t.apply(this,arguments)}}()}(t.codecs,t.loadCodec),this.dns=null!==(n=t.dns)&&void 0!==n?n:PT(),this.metrics=t.metrics;var s=e._objectSpread2({blockstore:t.blockstore,datastore:t.datastore,logger:this.logger,blockBrokers:[],getHasher:this.getHasher,getCodec:this.getCodec,dns:this.dns,metrics:this.metrics},null!==(i=t.components)&&void 0!==i?i:{});this.routing=s.routing=new kC(s,{routers:(null!==(o=t.routers)&&void 0!==o?o:[]).flatMap((e=>{var t=[e];return null!=e[Vo]&&t.push(e[Vo]),null!=e[Qo]&&t.push(e[Qo]),t})),providerLookupConcurrency:t.providerLookupConcurrency});var l=new lN(s);this.pins=new mC(t.datastore,l,this.getCodec),this.blockstore=new oB(l,this.pins,{holdGcLock:null===(a=t.holdGcLock)||void 0===a||a}),this.datastore=t.datastore,s.blockBrokers=t.blockBrokers.map((e=>e(s)))}start(){var t=this;return e._asyncToGenerator((function*(){yield function(e){return sB.apply(this,arguments)}(t.datastore),yield Ba(t.blockstore,t.datastore,t.routing)}))()}stop(){var t=this;return e._asyncToGenerator((function*(){yield Da(t.blockstore,t.datastore,t.routing)}))()}gc(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var n=t.length>0&&void 0!==t[0]?t[0]:{},i=yield r.blockstore.lock.writeLock();try{var o=r,a=r.blockstore.unwrap();r.log("gc start"),yield Nc(a.deleteMany(e._wrapAsyncGenerator((function*(){var t,r=!1,i=!1;try{for(var s,l=e._asyncIterator(a.getAll());r=!(s=yield e._awaitAsyncGenerator(l.next())).done;r=!1){var{cid:c}=s.value;try{var u;if(yield e._awaitAsyncGenerator(o.pins.isPinned(c,n)))continue;yield c,null===(u=n.onProgress)||void 0===u||u.call(n,new Ih("helia:gc:deleted",c))}catch(e){var d;o.log.error("Error during gc",e),null===(d=n.onProgress)||void 0===d||d.call(n,new Ih("helia:gc:error",e))}}}catch(e){i=!0,t=e}finally{try{r&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(i)throw t}}}))()))}finally{i()}r.log("gc finished")}))()}}class yN extends fN{constructor(t,r){super(t,e._objectSpread2(e._objectSpread2({},r),{},{name:"helia:bitswap:session"})),e._defineProperty(this,"wantList",void 0),e._defineProperty(this,"network",void 0),e._defineProperty(this,"libp2p",void 0),this.wantList=t.wantList,this.network=t.network,this.libp2p=t.libp2p}queryProvider(t,r,n){var i=this;return e._asyncToGenerator((function*(){i.log("sending WANT-BLOCK for %c to %p",t,r);var e=yield i.wantList.wantSessionBlock(t,r,n);if(i.log("%p %s %c",r,e.has?"has":"does not have",t),e.has&&null!=e.block)return e.block;throw new Error("Provider did not have block")}))()}findNewProviders(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(r.network.findProviders(t,n));o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;yield c.id}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}()})).apply(this,arguments)}toEvictionKey(e){return e.toMultihash().bytes}equals(e,t){return e.equals(t)}convertToProvider(t,r){var n=this;return e._asyncToGenerator((function*(){return Ko(t)?t:(yield n.libp2p.dial(t,r)).remotePeer}))()}}class gN{constructor(t){var r,n,i,o;e._defineProperty(this,"blocksReceived",void 0),e._defineProperty(this,"duplicateBlocksReceived",void 0),e._defineProperty(this,"dataReceived",void 0),e._defineProperty(this,"duplicateDataReceived",void 0),this.blocksReceived=null===(r=t.metrics)||void 0===r?void 0:r.registerMetricGroup("helia_bitswap_received_blocks"),this.duplicateBlocksReceived=null===(n=t.metrics)||void 0===n?void 0:n.registerMetricGroup("helia_bitswap_duplicate_received_blocks"),this.dataReceived=null===(i=t.metrics)||void 0===i?void 0:i.registerMetricGroup("helia_bitswap_data_received_bytes"),this.duplicateDataReceived=null===(o=t.metrics)||void 0===o?void 0:o.registerMetricGroup("helia_bitswap_duplicate_data_received_bytes")}updateBlocksReceived(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,r=arguments.length>1?arguments[1]:void 0,n={global:t};null!=r&&(n[r.toString()]=t),null===(e=this.blocksReceived)||void 0===e||e.increment(n)}updateDuplicateBlocksReceived(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:1,r=arguments.length>1?arguments[1]:void 0,n={global:t};null!=r&&(n[r.toString()]=t),null===(e=this.duplicateBlocksReceived)||void 0===e||e.increment(n)}updateDataReceived(e,t){var r,n={global:e};null!=t&&(n[t.toString()]=e),null===(r=this.dataReceived)||void 0===r||r.increment(n)}updateDuplicateDataReceived(e,t){var r,n={global:e};null!=t&&(n[t.toString()]=e),null===(r=this.duplicateDataReceived)||void 0===r||r.increment(n)}}class mN extends Map{constructor(t){super(),e._defineProperty(this,"metric",void 0);var{name:r,metrics:n}=t;this.metric=n.registerMetric(r),this.updateComponentMetric()}set(e,t){return super.set(e,t),this.updateComponentMetric(),this}delete(e){var t=super.delete(e);return this.updateComponentMetric(),t}clear(){super.clear(),this.updateComponentMetric()}updateComponentMetric(){this.metric.update(this.size)}}function wN(e){var{name:t,metrics:r}=e;return null!=r?new mN({name:t,metrics:r}):new Map}function bN(e){if(!(e instanceof Uint8Array))throw new Error("arg needs to be a Uint8Array");for(var t=[];e.length>0;){var r=bt(e);t.push(r),e=e.slice(yt(r))}return t}class _N extends Ia{constructor(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),e._defineProperty(this,"peers",void 0),e._defineProperty(this,"wants",void 0),e._defineProperty(this,"network",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"sendMessagesDelay",void 0),e._defineProperty(this,"sendMessagesTimeout",void 0),e._defineProperty(this,"hashLoader",void 0),e._defineProperty(this,"sendingMessages",void 0),this.peers=Ah({name:"helia_bitswap_peers",metrics:t.metrics}),this.wants=wN({name:"helia_bitswap_wantlist",metrics:t.metrics}),this.network=t.network,this.sendMessagesDelay=null!==(r=n.sendMessagesDelay)&&void 0!==r?r:10,this.log=t.logger.forComponent("helia:bitswap:wantlist"),this.hashLoader=n.hashLoader,this.network.addEventListener("bitswap:message",(e=>{this.receiveMessage(e.detail.peer,e.detail.message).catch((t=>{this.log.error("error receiving bitswap message from %p",e.detail.peer,t)}))})),this.network.addEventListener("peer:connected",(e=>{this.peerConnected(e.detail).catch((t=>{this.log.error("error processing newly connected bitswap peer %p",e.detail,t)}))})),this.network.addEventListener("peer:disconnected",(e=>{this.peerDisconnected(e.detail)}))}addEntry(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i,o=Ze(t.multihash.bytes,"base64"),a=n.wants.get(o);null==a&&(a={cid:t,priority:null!==(e=r.priority)&&void 0!==e?e:1,wantType:null!==(i=r.wantType)&&void 0!==i?i:hx.WantBlock,cancel:!1,sendDontHave:!0},n.wants.set(o,a));a.wantType===hx.WantHave&&r.wantType===hx.WantBlock&&(a.wantType=hx.WantBlock),yield n.sendMessagesDebounced();try{if(r.wantType===hx.WantBlock){var s=yield Bh(n,"block",null==r?void 0:r.signal,{filter:e=>nt(t.multihash.digest,e.detail.cid.multihash.digest),errorMessage:"Want was aborted"});return s.detail}return(yield Bh(n,"presence",null==r?void 0:r.signal,{filter:e=>nt(t.multihash.digest,e.detail.cid.multihash.digest),errorMessage:"Want was aborted"})).detail}finally{var l;!0===(null===(l=r.signal)||void 0===l?void 0:l.aborted)&&(n.log("want for %c was aborted, cancelling want",t),a.cancel=!0,yield n.sendMessagesDebounced())}}))()}sendMessagesDebounced(){var t=this;return e._asyncToGenerator((function*(){var e;yield null===(e=t.sendingMessages)||void 0===e?void 0:e.promise,clearTimeout(t.sendMessagesTimeout),t.sendMessagesTimeout=setTimeout((()=>{t.sendMessages().catch((e=>{t.log("error sending messages to peers",e)}))}),t.sendMessagesDelay)}))()}sendMessages(){var t=this;return e._asyncToGenerator((function*(){for(var[r,n]of(t.sendingMessages=Yc(),yield Promise.all([...t.peers.entries()].map(function(){var r=e._asyncToGenerator((function*(e){var[r,n]=e,i=new Set,o=new Bx;for(var[a,s]of t.wants.entries()){n.has(a)||s.cancel||(i.add(a),o.addWantlistEntry(s.cid,{cid:s.cid.bytes,priority:s.priority,wantType:s.wantType,cancel:s.cancel,sendDontHave:s.sendDontHave}))}if(0!==o.wantlist.size)try{for(var l of(yield t.network.sendMessage(r,o),i))n.add(l)}catch(e){t.log.error("error sending full wantlist to new peer",e)}}));return function(e){return r.apply(this,arguments)}}())).catch((e=>{t.log.error("error sending messages",e)})),t.wants))if(n.cancel)for(var i of(t.wants.delete(r),t.peers.values()))i.delete(r);t.sendingMessages.resolve()}))()}has(e){var t=Ze(e.multihash.bytes,"base64");return this.wants.has(t)}wantSessionPresence(t,r){var n=arguments,i=this;return e._asyncToGenerator((function*(){var e=n.length>2&&void 0!==n[2]?n[2]:{},o=new Bx;return o.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:hx.WantHave,priority:1}),yield i.network.sendMessage(r,o),(yield Bh(i,"presence",e.signal,{filter:e=>r.equals(e.detail.sender)&&nt(t.multihash.digest,e.detail.cid.multihash.digest)})).detail}))()}wantBlock(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i=r.length>1&&void 0!==r[1]?r[1]:{};return n.addEntry(t,e._objectSpread2(e._objectSpread2({},i),{},{wantType:hx.WantBlock}))}))()}wantSessionBlock(t,r){var n=arguments,i=this;return e._asyncToGenerator((function*(){var e=n.length>2&&void 0!==n[2]?n[2]:{},o=new Bx;return o.addWantlistEntry(t,{cid:t.bytes,sendDontHave:!0,wantType:hx.WantBlock,priority:1}),yield i.network.sendMessage(r,o),(yield Bh(i,"presence",e.signal,{filter:e=>r.equals(e.detail.sender)&&nt(t.multihash.digest,e.detail.cid.multihash.digest)})).detail}))()}receivedBlock(t,r){var n=this;return e._asyncToGenerator((function*(){var e=Ze(t.multihash.bytes,"base64"),r=n.wants.get(e);null!=r&&(r.cancel=!0,yield n.sendMessagesDebounced())}))()}receiveMessage(t,r){var n=this;return e._asyncToGenerator((function*(){n.log("received message from %p with %d blocks",t,r.blocks.length);var e=!1;for(var i of r.blocks){var o;if(null!=i.prefix&&null!=i.data){var a=bN(i.prefix),s=a[0],l=a[1],c=a[2],u=c===De.code?De:yield null===(o=n.hashLoader)||void 0===o?void 0:o.getHasher(c);if(null!=u){var d=u.digest(i.data);null!=d.then&&(d=yield d);var h=je.create(0===s?0:1,l,d);n.log("received block from %p for %c",t,h),n.safeDispatchEvent("block",{detail:{sender:t,cid:h,block:i.data}}),n.safeDispatchEvent("presence",{detail:{sender:t,cid:h,has:!0,block:i.data}});var p=Ze(h.multihash.bytes,"base64"),f=n.wants.get(p);null!=f&&(f.cancel=!0,e=!0)}else n.log.error("unknown hash algorithm",c)}}for(var{cid:v,type:y}of r.blockPresences){var g=je.decode(v);n.log("received %s from %p for %c",y,t,g),n.safeDispatchEvent("presence",{detail:{sender:t,cid:g,has:y===gx.HaveBlock}})}e&&(yield n.sendMessagesDebounced())}))()}peerConnected(t){var r=this;return e._asyncToGenerator((function*(){var e=new Set,n=new Bx(!0);for(var[i,o]of r.wants.entries())o.cancel||(e.add(i),n.addWantlistEntry(o.cid,{cid:o.cid.bytes,priority:1,wantType:hx.WantBlock,cancel:!1,sendDontHave:!1}));if(0!==n.wantlist.size)try{yield r.network.sendMessage(t,n),r.peers.set(t,e)}catch(e){r.log.error("error sending full wantlist to new peer %p",t,e)}else r.peers.set(t,e)}))()}peerDisconnected(e){this.peers.delete(e)}start(){}stop(){this.peers.clear(),clearTimeout(this.sendMessagesTimeout)}}class SN{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"log",void 0),e._defineProperty(this,"logger",void 0),e._defineProperty(this,"stats",void 0),e._defineProperty(this,"network",void 0),e._defineProperty(this,"blockstore",void 0),e._defineProperty(this,"peerWantLists",void 0),e._defineProperty(this,"wantList",void 0),e._defineProperty(this,"libp2p",void 0),this.logger=t.logger,this.log=t.logger.forComponent("helia:bitswap"),this.blockstore=t.blockstore,this.libp2p=t.libp2p,this.stats=new gN(t),this.network=new Cx(t,r),this.peerWantLists=new Gx(e._objectSpread2(e._objectSpread2({},t),{},{network:this.network}),r),this.wantList=new _N(e._objectSpread2(e._objectSpread2({},t),{},{network:this.network}),r)}createSession(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return e={wantList:this.wantList,network:this.network,logger:this.logger,libp2p:this.libp2p},new yN(e,t)}want(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i=r.length>1&&void 0!==r[1]?r[1]:{},o=new AbortController,a=$d([o.signal,i.signal]);o.signal,n.network.findAndConnect(t,e._objectSpread2(e._objectSpread2({},i),{},{signal:a})).catch((e=>{o.signal.aborted||n.log.error("error during finding and connect for cid %c",t,e)}));try{return(yield n.wantList.wantBlock(t,e._objectSpread2(e._objectSpread2({},i),{},{signal:a}))).block}finally{o.abort(),a.clear()}}))()}notify(t,r){var n=arguments,i=this;return e._asyncToGenerator((function*(){var e=n.length>2&&void 0!==n[2]?n[2]:{};yield Promise.all([i.peerWantLists.receivedBlock(t,e),i.wantList.receivedBlock(t,e)])}))()}getWantlist(){return[...this.wantList.wants.values()].filter((e=>!e.cancel)).map((e=>({cid:e.cid,priority:e.priority,wantType:e.wantType})))}getPeerWantlist(e){return this.peerWantLists.wantListForPeer(e)}start(){var t=this;return e._asyncToGenerator((function*(){t.wantList.start(),yield t.network.start()}))()}stop(){var t=this;return e._asyncToGenerator((function*(){t.wantList.stop(),yield t.network.stop()}))()}}class PN{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"bitswap",void 0),e._defineProperty(this,"started",void 0);var n,{getHasher:i}=t;this.bitswap=function(e){return new SN(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}(t,e._objectSpread2({hashLoader:{getHasher:(n=e._asyncToGenerator((function*(e){return i(e)})),function(e){return n.apply(this,arguments)})}},r)),this.started=!1}isStarted(){return this.started}start(){var t=this;return e._asyncToGenerator((function*(){yield t.bitswap.start(),t.started=!0}))()}stop(){var t=this;return e._asyncToGenerator((function*(){yield t.bitswap.stop(),t.started=!1}))()}announce(t,r,n){var i=this;return e._asyncToGenerator((function*(){yield i.bitswap.notify(t,r,n)}))()}retrieve(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};return n.bitswap.want(t,e)}))()}createSession(t){var r,n,i=this,o=this.bitswap.createSession(t);return{announce:(n=e._asyncToGenerator((function*(e,t,r){yield i.bitswap.notify(e,t,r)})),function(e,t,r){return n.apply(this,arguments)}),retrieve:(r=e._asyncToGenerator((function*(e,t){return o.retrieve(e,t)})),function(e,t){return r.apply(this,arguments)})}}}function EN(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new PN(t,e)}var AN,kN={};var xN=(AN||(AN=1,function(){var e,t,r,n,i,o,a,s;s=function(e){return[(e&255<<24)>>>24,(e&255<<16)>>>16,(65280&e)>>>8,255&e].join(".")},a=function(e){var r,n,i,o,a,s;for(r=[],i=o=0;o<=3&&0!==e.length;i=++o){if(i>0){if("."!==e[0])throw new Error("Invalid IP");e=e.substring(1)}a=(s=t(e))[0],n=s[1],e=e.substring(n),r.push(a)}if(0!==e.length)throw new Error("Invalid IP");switch(r.length){case 1:if(r[0]>4294967295)throw new Error("Invalid IP");return r[0]>>>0;case 2:if(r[0]>255||r[1]>16777215)throw new Error("Invalid IP");return(r[0]<<24|r[1])>>>0;case 3:if(r[0]>255||r[1]>255||r[2]>65535)throw new Error("Invalid IP");return(r[0]<<24|r[1]<<16|r[2])>>>0;case 4:if(r[0]>255||r[1]>255||r[2]>255||r[3]>255)throw new Error("Invalid IP");return(r[0]<<24|r[1]<<16|r[2]<<8|r[3])>>>0;default:throw new Error("Invalid IP")}},n=(r=function(e){return e.charCodeAt(0)})("0"),o=r("a"),i=r("A"),t=function(e){var t,a,s,l,c;for(l=0,t=10,a="9",s=0,e.length>1&&"0"===e[s]&&("x"===e[s+1]||"X"===e[s+1]?(s+=2,t=16):"0"<=e[s+1]&&e[s+1]<="9"&&(s++,t=8,a="7")),c=s;s<e.length;){if("0"<=e[s]&&e[s]<=a)l=l*t+(r(e[s])-n)>>>0;else{if(16!==t)break;if("a"<=e[s]&&e[s]<="f")l=l*t+(10+r(e[s])-o)>>>0;else{if(!("A"<=e[s]&&e[s]<="F"))break;l=l*t+(10+r(e[s])-i)>>>0}}if(l>4294967295)throw new Error("too large");s++}if(s===c)throw new Error("empty octet");return[l,s]},e=function(){function e(e,t){var r,n,i;if("string"!=typeof e)throw new Error("Missing `net' parameter");if(t||(i=e.split("/",2),e=i[0],t=i[1]),t||(t=32),"string"==typeof t&&t.indexOf(".")>-1){try{this.maskLong=a(t)}catch(e){throw new Error("Invalid mask: "+t)}for(r=n=32;n>=0;r=--n)if(this.maskLong===4294967295<<32-r>>>0){this.bitmask=r;break}}else{if(!t&&0!==t)throw new Error("Invalid mask: empty");this.bitmask=parseInt(t,10),this.maskLong=0,this.bitmask>0&&(this.maskLong=4294967295<<32-this.bitmask>>>0)}try{this.netLong=(a(e)&this.maskLong)>>>0}catch(t){throw new Error("Invalid net address: "+e)}if(!(this.bitmask<=32))throw new Error("Invalid mask for ip4: "+t);this.size=Math.pow(2,32-this.bitmask),this.base=s(this.netLong),this.mask=s(this.maskLong),this.hostmask=s(~this.maskLong),this.first=this.bitmask<=30?s(this.netLong+1):this.base,this.last=this.bitmask<=30?s(this.netLong+this.size-2):s(this.netLong+this.size-1),this.broadcast=this.bitmask<=30?s(this.netLong+this.size-1):void 0}return e.prototype.contains=function(t){return"string"==typeof t&&(t.indexOf("/")>0||4!==t.split(".").length)&&(t=new e(t)),t instanceof e?this.contains(t.base)&&this.contains(t.broadcast||t.last):(a(t)&this.maskLong)>>>0==(this.netLong&this.maskLong)>>>0},e.prototype.next=function(t){return null==t&&(t=1),new e(s(this.netLong+this.size*t),this.mask)},e.prototype.forEach=function(e){var t,r,n;for(n=a(this.first),r=a(this.last),t=0;n<=r;)e(s(n),n,t),t++,n++},e.prototype.toString=function(){return this.base+"/"+this.bitmask},e}(),kN.ip2long=a,kN.long2ip=s,kN.Netmask=e}.call(kN)),kN),TN=["0.0.0.0/8","10.0.0.0/8","100.64.0.0/10","127.0.0.0/8","169.254.0.0/16","172.16.0.0/12","192.0.0.0/24","192.0.0.0/29","192.0.0.8/32","192.0.0.9/32","192.0.0.10/32","192.0.0.170/32","192.0.0.171/32","192.0.2.0/24","192.31.196.0/24","192.52.193.0/24","192.88.99.0/24","192.168.0.0/16","192.175.48.0/24","198.18.0.0/15","198.51.100.0/24","203.0.113.0/24","240.0.0.0/4","255.255.255.255/32"].map((e=>new xN.Netmask(e)));function IN(e){for(var t of TN)if(t.contains(e))return!0;return!1}function CN(e){return xt(e)?IN(e):/^::ffff:([0-9a-fA-F]{1,4}):([0-9a-fA-F]{1,4})$/.test(e)?function(e){var t=e.split(":");if(t.length<2)return!1;var r=t[t.length-1].padStart(4,"0"),n=t[t.length-2].padStart(4,"0");return IN("".concat(parseInt(n.substring(0,2),16),".").concat(parseInt(n.substring(2),16),".").concat(parseInt(r.substring(0,2),16),".").concat(parseInt(r.substring(2),16)))}(e):function(e){return/^::ffff:([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)}(e)?function(e){var t=e.split(":");return IN(t[t.length-1])}(e):Tt(e)?function(e){return/^::$/.test(e)||/^::1$/.test(e)||/^64:ff9b::([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/.test(e)||/^100::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001::([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:2[0-9a-fA-F]:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2001:db8:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^2002:([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4}):?([0-9a-fA-F]{0,4})$/.test(e)||/^f[c-d]([0-9a-fA-F]{2,2}):/i.test(e)||/^fe[8-9a-bA-B][0-9a-fA-F]:/i.test(e)||/^ff([0-9a-fA-F]{2,2}):/i.test(e)}(e):void 0}var BN=[lr("tcp").code,lr("dns").code,lr("dnsaddr").code,lr("dns4").code,lr("dns6").code];function NN(e){var t;return null===(t=GN("sni",e))||void 0===t?void 0:t[1]}function DN(e){var t,r=null===(t=GN("tcp",e))||void 0===t?void 0:t[1];return null==r?"":":".concat(r)}function GN(e,t){var r;try{r=lr(e).code}catch(e){return}for(var[n,i]of t)if(n===r&&null!=i)return[n,i]}function RN(e){return e.some((e=>{var[t,r]=e;return t===lr("tls").code}))}function ON(e,t,r){var n=LN[lr(e).name];if(null==n)throw new Error("Can't interpret protocol ".concat(lr(e).name));var i=n(t,r);return e===lr("ip6").code?"[".concat(i,"]"):i}var LN={ip4:(e,t)=>e,ip6:(e,t)=>0===t.length?e:"[".concat(e,"]"),tcp:(e,t)=>{var r,n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return"tcp://".concat(ON(n[0],null!==(r=n[1])&&void 0!==r?r:"",t),":").concat(e)},udp:(e,t)=>{var r,n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return"udp://".concat(ON(n[0],null!==(r=n[1])&&void 0!==r?r:"",t),":").concat(e)},dnsaddr:(e,t)=>e,dns4:(e,t)=>e,dns6:(e,t)=>e,dns:(e,t)=>e,ipfs:(e,t)=>{var r,n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return"".concat(ON(n[0],null!==(r=n[1])&&void 0!==r?r:"",t))},p2p:(e,t)=>{var r,n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return"".concat(ON(n[0],null!==(r=n[1])&&void 0!==r?r:"",t))},http:(e,t)=>{var r,n=RN(t),i=NN(t),o=DN(t);if(n&&null!=i)return"https://".concat(i).concat(o);var a=n?"https://":"http://",s=t.pop();if(null==s)throw new Error("Unexpected end of multiaddr");var l=ON(s[0],null!==(r=s[1])&&void 0!==r?r:"",t);return l=l.replace("tcp://",""),"".concat(a).concat(l)},"http-path":(e,t)=>{var r,n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");var i=ON(n[0],null!==(r=n[1])&&void 0!==r?r:"",t),o=decodeURIComponent(e);return"".concat(i,"/").concat(o)},tls:(e,t)=>{var r,n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return ON(n[0],null!==(r=n[1])&&void 0!==r?r:"",t)},sni:(e,t)=>{var r,n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");return ON(n[0],null!==(r=n[1])&&void 0!==r?r:"",t)},https:(e,t)=>{var r,n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");var i=ON(n[0],null!==(r=n[1])&&void 0!==r?r:"",t);return i=i.replace("tcp://",""),"https://".concat(i)},ws:(e,t)=>{var r,n=RN(t),i=NN(t),o=DN(t);if(n&&null!=i)return"wss://".concat(i).concat(o);var a=n?"wss://":"ws://",s=t.pop();if(null==s)throw new Error("Unexpected end of multiaddr");var l=ON(s[0],null!==(r=s[1])&&void 0!==r?r:"",t);return l=l.replace("tcp://",""),"".concat(a).concat(l)},wss:(e,t)=>{var r,n=t.pop();if(null==n)throw new Error("Unexpected end of multiaddr");var i=ON(n[0],null!==(r=n[1])&&void 0!==r?r:"",t);return i=i.replace("tcp://",""),"wss://".concat(i)}};function MN(e,t){var r,n=sr(e).stringTuples(),i=n.pop();if(null==i)throw new Error("Unexpected end of multiaddr");var o=lr(i[0]),a=LN[o.name];if(null==a)throw new Error("No interpreter found for ".concat(o.name));var s=a(null!==(r=i[1])&&void 0!==r?r:"",n);return BN.includes(i[0])&&(s=s.replace(/^.*:\/\//,""),s="443"===i[1]?"https://".concat(s):"http://".concat(s)),(s.startsWith("http://")||s.startsWith("https://")||s.startsWith("ws://")||s.startsWith("wss://"))&&(s=new URL(s).toString()).endsWith("/")&&(s=s.substring(0,s.length-1)),s}var jN=new WeakMap,FN=new WeakMap,UN=new WeakMap,zN=new WeakMap,VN=new WeakMap,qN=new WeakSet;class HN{constructor(t,r){var{logger:n,transformRequestInit:i}=r;e._classPrivateMethodInitSpec(this,qN),e._defineProperty(this,"url",void 0),e._classPrivateFieldInitSpec(this,jN,0),e._classPrivateFieldInitSpec(this,FN,0),e._classPrivateFieldInitSpec(this,UN,0),e._classPrivateFieldInitSpec(this,zN,0),e._classPrivateFieldInitSpec(this,VN,new Map),e._defineProperty(this,"log",void 0),e._defineProperty(this,"transformRequestInit",void 0),this.url=t instanceof URL?t:new URL(t),this.transformRequestInit=i,this.log=n.forComponent("helia:trustless-gateway-block-broker:".concat(this.url.hostname))}getRawBlock(t,r){var n=this;return e._asyncToGenerator((function*(){var i=new URL(n.url.toString());if(i.pathname="/ipfs/".concat(t.toString()),i.search="?format=raw",!0===(null==r?void 0:r.aborted))throw new Error("Signal to fetch raw block for CID ".concat(t," from gateway ").concat(n.url," was aborted prior to fetch"));var o=e._assertClassBrand(qN,n,KN).call(n,t),a=new AbortController,s=()=>{a.abort()};null==r||r.addEventListener("abort",s);try{var l=e._classPrivateFieldGet2(VN,n).get(o);if(null==l){var c;e._classPrivateFieldSet2(jN,n,(c=e._classPrivateFieldGet2(jN,n),c++,c));var u={signal:a.signal,headers:{Accept:"application/vnd.ipld.raw"},cache:"force-cache"},d=null!=n.transformRequestInit?yield n.transformRequestInit(u):u;l=fetch(i.toString(),d).then(function(){var r=e._asyncToGenerator((function*(r){var o,a;if(n.log("GET %s %d",i,r.status),!r.ok)throw e._classPrivateFieldSet2(FN,n,(a=e._classPrivateFieldGet2(FN,n),a++,a)),new Error("unable to fetch raw block for CID ".concat(t," from gateway ").concat(n.url));return e._classPrivateFieldSet2(zN,n,(o=e._classPrivateFieldGet2(zN,n),o++,o)),new Uint8Array(yield r.arrayBuffer())}));return function(e){return r.apply(this,arguments)}}()),e._classPrivateFieldGet2(VN,n).set(o,l)}return yield l}catch(i){var h;if(!0===(null==r?void 0:r.aborted))throw new Error("fetching raw block for CID ".concat(t," from gateway ").concat(n.url," was aborted"));throw e._classPrivateFieldSet2(FN,n,(h=e._classPrivateFieldGet2(FN,n),++h)),new Error("unable to fetch raw block for CID ".concat(t))}finally{null==r||r.removeEventListener("abort",s),e._classPrivateFieldGet2(VN,n).delete(o)}}))()}reliability(){return 0===e._classPrivateFieldGet2(jN,this)?1:e._classPrivateFieldGet2(UN,this)>0?-1/0:e._classPrivateFieldGet2(zN,this)/(e._classPrivateFieldGet2(jN,this)+3*e._classPrivateFieldGet2(FN,this))}incrementInvalidBlocks(){var t;e._classPrivateFieldSet2(UN,this,(t=e._classPrivateFieldGet2(UN,this),++t))}getStats(){return{attempts:e._classPrivateFieldGet2(jN,this),errors:e._classPrivateFieldGet2(FN,this),invalidBlocks:e._classPrivateFieldGet2(UN,this),successes:e._classPrivateFieldGet2(zN,this),pendingResponses:e._classPrivateFieldGet2(VN,this).size}}}function KN(e){var t=e.multihash.bytes;return z.encode(t)}function WN(e,t,r){return e.filter((e=>{if(Zd.matches(e)||t&&Jd.matches(e))return!!r||(!!_d.matches(e)||!1===CN(e.toOptions().host));if(!t&&r){var{host:n}=e.toOptions();if("127.0.0.1"===n||"localhost"===n||n.endsWith(".localhost"))return!0}return!1}))}function QN(e,t,r,n,i){return YN.apply(this,arguments)}function YN(){return YN=e._wrapAsyncGenerator((function(t,r,n,i,o){var a=arguments.length>5&&void 0!==arguments[5]?arguments[5]:{};return function*(){var s,l=!1,c=!1;try{for(var u,d=e._asyncIterator(r.findProviders(t,a));l=!(u=yield e._awaitAsyncGenerator(d.next())).done;l=!1){var h=WN(u.value.multiaddrs,i,o);if(0!==h.length){var p=MN(h[0]);yield new HN(p,{logger:n,transformRequestInit:a.transformRequestInit})}}}catch(e){c=!0,s=e}finally{try{l&&null!=d.return&&(yield e._awaitAsyncGenerator(d.return()))}finally{if(c)throw s}}}()})),YN.apply(this,arguments)}class JN extends fN{constructor(t,r){var n,i;super(t,e._objectSpread2(e._objectSpread2({},r),{},{name:"helia:trustless-gateway:session"})),e._defineProperty(this,"routing",void 0),e._defineProperty(this,"allowInsecure",void 0),e._defineProperty(this,"allowLocal",void 0),e._defineProperty(this,"transformRequestInit",void 0),this.routing=t.routing,this.allowInsecure=null!==(n=r.allowInsecure)&&void 0!==n?n:$N,this.allowLocal=null!==(i=r.allowLocal)&&void 0!==i?i:XN,this.transformRequestInit=r.transformRequestInit}queryProvider(t,r,n){var i=this;return e._asyncToGenerator((function*(){var e;i.log("fetching BLOCK for %c from %s",t,r.url);var o=yield r.getRawBlock(t,n.signal);return i.log.trace("got block for %c from %s",t,r.url),yield null===(e=n.validateFn)||void 0===e?void 0:e.call(n,o),o}))()}findNewProviders(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(QN(t,r.routing,r.logger,r.allowInsecure,r.allowLocal,e._objectSpread2(e._objectSpread2({},n),{},{transformRequestInit:r.transformRequestInit}))))}()})).apply(this,arguments)}toEvictionKey(e){return e.url.toString()}equals(e,t){return e.url.toString()===t.url.toString()}}class ZN{constructor(t){var r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"allowInsecure",void 0),e._defineProperty(this,"allowLocal",void 0),e._defineProperty(this,"transformRequestInit",void 0),e._defineProperty(this,"routing",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"logger",void 0),this.log=t.logger.forComponent("helia:trustless-gateway-block-broker"),this.logger=t.logger,this.routing=t.routing,this.allowInsecure=null!==(r=i.allowInsecure)&&void 0!==r?r:$N,this.allowLocal=null!==(n=i.allowLocal)&&void 0!==n?n:XN,this.transformRequestInit=i.transformRequestInit}retrieve(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i,o=r.length>1&&void 0!==r[1]?r[1]:{},a=[],s=!1,l=!1;try{for(var c,u=e._asyncIterator(QN(t,n.routing,n.logger,n.allowInsecure,n.allowLocal,e._objectSpread2(e._objectSpread2({},o),{},{transformRequestInit:n.transformRequestInit})));s=!(c=yield u.next()).done;s=!1){var d=c.value;n.log("getting block for %c from %s",t,d.url);try{var h=yield d.getRawBlock(t,o.signal);n.log.trace("got block for %c from %s",t,d.url);try{var p;yield null===(p=o.validateFn)||void 0===p?void 0:p.call(o,h)}catch(e){n.log.error("failed to validate block for %c from %s",t,d.url,e);continue}return h}catch(e){var f;if(n.log.error("failed to get block for %c from %s",t,d.url,e),e instanceof Error?a.push(e):a.push(new Error("Unable to fetch raw block for CID ".concat(t," from gateway ").concat(d.url))),!0===(null===(f=o.signal)||void 0===f?void 0:f.aborted)){n.log.trace("request aborted while fetching raw block for CID %c from gateway %s",t,d.url);break}}}}catch(e){l=!0,i=e}finally{try{s&&null!=u.return&&(yield u.return())}finally{if(l)throw i}}throw a.length>0?new AggregateError(a,"Unable to fetch raw block for CID ".concat(t," from any gateway")):new Error("Unable to fetch raw block for CID ".concat(t," from any gateway"))}))()}createSession(){var t,r,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t={logger:this.logger,routing:this.routing},r=e._objectSpread2(e._objectSpread2({},n),{},{allowLocal:this.allowLocal,allowInsecure:this.allowInsecure,transformRequestInit:this.transformRequestInit}),new JN(t,r)}}var $N=!1,XN=!1;function eD(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new ZN(t,e)}function tD(e){return rD.apply(this,arguments)}function rD(){return rD=e._wrapAsyncGenerator((function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var n=t.getReader();try{for(;;){var i=yield e._awaitAsyncGenerator(n.read());if(i.done)return;yield i.value}}finally{!0!==r.preventCancel&&(yield e._awaitAsyncGenerator(n.cancel())),n.releaseLock()}}()})),rD.apply(this,arguments)}var nD,iD={exports:{}};var oD,aD,sD=(nD||(nD=1,oD=iD,function(){oD.exports=v;var e=86400,t=3200,r=146097*t/400,n=e*r,i=1e3*n,o=864e13,a=4294967296,s=1e6,l="000000000",c=Math.trunc||function(e){var t=e-e%1;return 0==t&&(e<0||0===e&&1/e!=1/0)?-0:t},u=v.prototype,d=(v.fromDate=function(e){return new v(+e)},v.fromInt64BE=b(0,1,2,3,0,4),v.fromInt64LE=b(3,2,1,0,4,0),v.fromString=function(e){var t,r=new v;if(e=(e+="").replace(/^\s*[+\-]?\d+/,(function(e){var t=1970+((e=+e)-1970)%400;return r.year=e-t,t})).replace(/(?:Z|([+\-]\d{2}):?(\d{2}))$/,(function(e,r,n){return r<0&&(n*=-1),t=6e4*(60*+r+ +n),""})).replace(/\.\d+$/,(function(e){return r.nano=+(e+l).substr(1,9),""})).split(/\D+/),1<e.length?e[1]--:e[1]=0,r.time=t=Date.UTC.apply(Date,e)-(t||0),isNaN(t))throw new TypeError("Invalid Date");return y(r)},v.fromTimeT=function(e){return m(e,0)},u.year=0,u.time=0,u.nano=0,u.addNano=function(e){return this.nano+=+e||0,this},u.getNano=function(){var e=y(this);return(e.time%1e3*s+ +e.nano+1e9)%1e9},u.getTimeT=function(){var n=y(this),i=Math.floor(n.time/1e3);return(n=n.year)&&(i+=n*r*e/t),i},u.getYear=function(){return this.toDate().getUTCFullYear()+this.year},u.toDate=function(){return g(y(this).time)},u.toJSON=function(){return this.toString().replace(/0{1,6}Z$/,"Z")},u.toString=function(e){var t=this,r=t.toDate(),n={H:function(){return S(r.getUTCHours())},L:function(){return P(r.getUTCMilliseconds(),3)},M:function(){return S(r.getUTCMinutes())},N:function(){return P(t.getNano(),9)},S:function(){return S(r.getUTCSeconds())},Y:function(){var e=t.getYear();return 999999<e?"+"+e:9999<e?"+"+P(e,6):0<=e?P(e,4):-999999<=e?"-"+P(-e,6):e},a:function(){return p[r.getUTCDay()]},b:function(){return h[r.getUTCMonth()]},d:function(){return S(r.getUTCDate())},e:function(){return function(e){return(9<e?"":" ")+(0|e)}(r.getUTCDate())},m:function(){return S(r.getUTCMonth()+1)}};return function e(t){return t.replace(/%./g,(function(t){var r=t[1],i=f[r];return r=n[r],i?e(i):r?r():t}))}(e||d)},u.writeInt64BE=w(0,1,2,3,0,4),u.writeInt64LE=w(3,2,1,0,4,0),"%Y-%m-%dT%H:%M:%S.%NZ"),h=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],p=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],f={"%":"%",F:"%Y-%m-%d",n:"\n",R:"%H:%M",T:"%H:%M:%S",t:"\t",X:"%T",Z:"GMT",z:"+0000"};return v;function v(e,t,r){var n=this;if(!(n instanceof v))return new v(e,t,r);n.time=+e||0,n.nano=+t||0,n.year=+r||0,y(n)}function y(e){var r,n,a,l=e.year,u=e.time,d=e.nano,h=((d<0||s<=d)&&(d-=(n=Math.floor(d/s))*s,u+=n,n=1),l%t);return(u<-o||o<u||h)&&((r=c(u/i))&&(l+=r*t,u-=r*i),(a=g(u)).setUTCFullYear(h+a.getUTCFullYear()),a=(u=+a)+(r=c((l-=h)/t))*i,r&&-o<=a&&a<=o&&(l-=r*t,u=a),n=1),n&&(e.year=l,e.time=u,e.nano=d),e}function g(e){var t=new Date(0);return t.setTime(e),t}function m(e,r){e=+e||0;var i=c((r=(0|r)*a)/n)+c(e/n);return(e=c((r=r%n+e%n)/n))&&(i+=e,r-=e*n),new v(1e3*r,0,i*t)}function w(n,i,o,s,l,u){return function(n,i){var o=y(this);_(n=n||new Array(8),i|=0);var s=Math.floor(o.time/1e3),h=(o=o.year*(r*e/t),c(o/a)+c(s/a));return o=o%a+s%a,(s=Math.floor(o/a))&&(h+=s,o-=s*a),d(n,i+l,h),d(n,i+u,o),n};function d(e,t,r){e[t+n]=r>>24&255,e[t+i]=r>>16&255,e[t+o]=r>>8&255,e[t+s]=255&r}}function b(e,t,r,n,i,o){return function(e,t){_(e,t|=0);var r=a(e,t+i);return m(a(e,t+o),r)};function a(i,o){return 16777216*i[o+e]+(i[o+t]<<16|i[o+r]<<8|i[o+n])}}function _(e,t){if(null==(e=e&&e.length))throw new TypeError("Invalid Buffer");if(e<t+8)throw new RangeError("Out of range")}function S(e){return(9<e?"":"0")+(0|e)}function P(e,t){return(l+(0|e)).substr(-t)}}()),iD.exports),lD=e.getDefaultExportFromCjs(sD);class cD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Record signature creation failed"),this.name="SignatureCreationError"}}e._defineProperty(cD,"name","SignatureCreationError");class uD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Record signature verification failed"),this.name="SignatureVerificationError"}}e._defineProperty(uD,"name","SignatureVerificationError");class dD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Record has expired"),this.name="RecordExpiredError"}}e._defineProperty(dD,"name","RecordExpiredError");class hD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The validity type is unsupported"),this.name="UnsupportedValidityError"}}e._defineProperty(hD,"name","UnsupportedValidityError");class pD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The record is too large"),this.name="RecordTooLargeError"}}e._defineProperty(pD,"name","RecordTooLargeError");class fD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Value must be a valid content path starting with /"),this.name="InvalidValueError"}}e._defineProperty(fD,"name","InvalidValueError");class vD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid record data"),this.name="InvalidRecordDataError"}}e._defineProperty(vD,"name","InvalidRecordDataError");class yD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid embedded public key"),this.name="InvalidEmbeddedPublicKeyError"}}e._defineProperty(yD,"name","InvalidEmbeddedPublicKeyError"),function(e){var t,r;(e.ValidityType||(e.ValidityType={})).EOL="EOL",function(e){e[e.EOL=0]="EOL"}(t||(t={})),function(e){e.codec=()=>pl(t)}(e.ValidityType||(e.ValidityType={})),e.codec=()=>(null==r&&(r=fl((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==n.lengthDelimited&&r.fork(),null!=t.value&&(r.uint32(10),r.bytes(t.value)),null!=t.signatureV1&&(r.uint32(18),r.bytes(t.signatureV1)),null!=t.validityType&&(r.uint32(24),e.ValidityType.codec().encode(t.validityType,r)),null!=t.validity&&(r.uint32(34),r.bytes(t.validity)),null!=t.sequence&&(r.uint32(40),r.uint64(t.sequence)),null!=t.ttl&&(r.uint32(48),r.uint64(t.ttl)),null!=t.pubKey&&(r.uint32(58),r.bytes(t.pubKey)),null!=t.signatureV2&&(r.uint32(66),r.bytes(t.signatureV2)),null!=t.data&&(r.uint32(74),r.bytes(t.data)),!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n={},i=null==r?t.len:t.pos+r;t.pos<i;){var o=t.uint32();switch(o>>>3){case 1:n.value=t.bytes();break;case 2:n.signatureV1=t.bytes();break;case 3:n.validityType=e.ValidityType.codec().decode(t);break;case 4:n.validity=t.bytes();break;case 5:n.sequence=t.uint64();break;case 6:n.ttl=t.uint64();break;case 7:n.pubKey=t.bytes();break;case 8:n.signatureV2=t.bytes();break;case 9:n.data=t.bytes();break;default:t.skipType(7&o)}}return n}))),r),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(aD||(aD={}));var gD=Cu("ipns:utils"),mD=ot("/ipns/");function wD(e){return"signatureV1"in e?aD.encode({value:ot(e.value),signatureV1:e.signatureV1,validityType:e.validityType,validity:ot(e.validity),sequence:e.sequence,ttl:e.ttl,pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data}):aD.encode({pubKey:e.pubKey,signatureV2:e.signatureV2,data:e.data})}function bD(e){var t=aD.decode(e);if(null!=t.sequence&&(t.sequence=BigInt(t.sequence)),null!=t.ttl&&(t.ttl=BigInt(t.ttl)),null==t.signatureV2||null==t.data)throw new uD("Missing data or signatureV2");var r=PD(t.data),n=function(e){var t=Ze(e).trim();if(t.startsWith("/"))return t;try{return"/ipfs/".concat(je.decode(e).toV1().toString())}catch(e){}try{return"/ipfs/".concat(je.parse(t).toV1().toString())}catch(e){}throw new fD("Value must be a valid content path starting with /")}(r.Value),i=Ze(r.Validity);if(null!=t.value&&null!=t.signatureV1)return function(e){var t,r;if(null==e.data)throw new vD("Record data is missing");var n=PD(e.data);if(!nt(n.Value,null!==(t=e.value)&&void 0!==t?t:new Uint8Array(0)))throw new uD('Field "value" did not match between protobuf and CBOR');if(!nt(n.Validity,null!==(r=e.validity)&&void 0!==r?r:new Uint8Array(0)))throw new uD('Field "validity" did not match between protobuf and CBOR');if(n.ValidityType!==e.validityType)throw new uD('Field "validityType" did not match between protobuf and CBOR');if(n.Sequence!==e.sequence)throw new uD('Field "sequence" did not match between protobuf and CBOR');if(n.TTL!==e.ttl)throw new uD('Field "ttl" did not match between protobuf and CBOR')}(t),{value:n,validityType:aD.ValidityType.EOL,validity:i,sequence:r.Sequence,ttl:r.TTL,pubKey:t.pubKey,signatureV1:t.signatureV1,signatureV2:t.signatureV2,data:t.data};if(null!=t.signatureV2)return{value:n,validityType:aD.ValidityType.EOL,validity:i,sequence:r.Sequence,ttl:r.TTL,pubKey:t.pubKey,signatureV2:t.signatureV2,data:t.data};throw new Error("invalid record: does not include signatureV1 or signatureV2")}function _D(e){return _t([mD,e.bytes])}function SD(e){var t=Ae(e.slice(mD.length));if(!ED(t,0)&&!ED(t,18))throw new fa("Multihash in IPNS key was not identity or sha2-256");return t}function PD(e){var t=aC(e);if(0!==t.ValidityType)throw new hD("The validity type is unsupported");return t.ValidityType=aD.ValidityType.EOL,Number.isInteger(t.Sequence)&&(t.Sequence=BigInt(t.Sequence)),Number.isInteger(t.TTL)&&(t.TTL=BigInt(t.TTL)),t}function ED(e,t){return e.code===t}var AD=Cu("ipns:validator"),kD=function(){var t=e._asyncToGenerator((function*(e,t){var r,n,i=bD(t);try{var o=(n=i.data,_t([ot("ipns-signature:"),n]));r=yield e.verify(o,i.signatureV2)}catch(e){r=!1}if(!r)throw AD.error("record signature verification failed"),new uD("Record signature verification failed");if(i.validityType===aD.ValidityType.EOL){if(lD.fromString(i.validity).toDate().getTime()<Date.now())throw AD.error("record has expired"),new dD("record has expired")}else if(null!=i.validityType)throw AD.error("the validity type is unsupported"),new hD("The validity type is unsupported");AD("ipns record for %s is valid",i.value)}));return function(e,r){return t.apply(this,arguments)}}();function xD(e,t){return TD.apply(this,arguments)}function TD(){return(TD=e._asyncToGenerator((function*(e,t){var r;if(t.byteLength>10240)throw new pD("The record is too large");var n,i=SD(e);ED(i,0)&&(n=Vl(i));var o=null!==(r=function(e){var t;if(null!=e.pubKey)try{t=zl(e.pubKey)}catch(e){throw gD.error(e),e}if(null!=t)return t}(bD(t)))&&void 0!==r?r:n;if(null==o)throw new yD("Could not extract public key from IPNS record or routing key");if(!nt(_D(o.toMultihash()),e))throw new yD("Embedded public key did not match routing key");yield kD(o,t)}))).apply(this,arguments)}let ID=class extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidMessageLengthError"),e._defineProperty(this,"code","ERR_INVALID_MESSAGE_LENGTH")}};function CD(e){return BD.apply(this,arguments)}function BD(){return BD=e._wrapAsyncGenerator((function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var n,i=/\r?\n/,o=new TextDecoder("utf8"),a="",s=!1,l=!1;try{for(var c,u=e._asyncIterator(t);s=!(c=yield e._awaitAsyncGenerator(u.next())).done;s=!1){var d,h,p=c.value;if("string"==typeof p&&(p=(new TextEncoder).encode(p)),ja(p)&&(p=p.subarray()),(a+=o.decode(p,{stream:!0})).length>(null!==(d=null==r?void 0:r.maxMessageLength)&&void 0!==d?d:a.length))throw new ID("Incoming message too long");var f=a.split(i);a=null!==(h=f.pop())&&void 0!==h?h:"";for(var v=0;v<f.length;v++)yield JSON.parse(f[v])}}catch(e){l=!0,n=e}finally{try{s&&null!=u.return&&(yield e._awaitAsyncGenerator(u.return()))}finally{if(l)throw n}}""!==(a+=o.decode())&&(yield JSON.parse(a))}()})),BD.apply(this,arguments)}class ND extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid request"),this.name="InvalidRequestError"}}e._defineProperty(ND,"name","InvalidRequestError");class DD extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Bad response"),this.name="BadResponseError"}}function GD(t){if(null!=t[Symbol.asyncIterator])return e._asyncToGenerator((function*(){var r,n=!1,i=!1;try{for(var o,a=e._asyncIterator(t);n=!(o=yield a.next()).done;n=!1){return o.value}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield a.return())}finally{if(i)throw r}}}))();for(var r of t)return r}e._defineProperty(DD,"name","BadResponseError");var RD=ot("/ipns/");function OD(e){return nt(e.subarray(0,RD.byteLength),RD)}class LD{constructor(t){e._defineProperty(this,"client",void 0),this.client=t}findProviders(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(Qc(r.client.getProviders(t,n),(e=>{var t;return{id:e.ID,multiaddrs:null!==(t=e.Addrs)&&void 0!==t?t:[]}}))))}()})).apply(this,arguments)}provide(){return e._asyncToGenerator((function*(){}))()}cancelReprovide(){return e._asyncToGenerator((function*(){}))()}put(t,r,n){var i=this;return e._asyncToGenerator((function*(){if(OD(t)){var e=SD(t),o=je.createV1(114,e),a=bD(r);yield i.client.putIPNS(o,a,n)}}))()}get(t,r){var n=this;return e._asyncToGenerator((function*(){if(!OD(t))throw new ua("Not found");var e=SD(t),i=je.createV1(114,e);try{return wD(yield n.client.getIPNS(i,r))}catch(e){if("BadResponseError"===e.name)throw new ua("Not found");throw e}}))()}}class MD{constructor(t){e._defineProperty(this,"client",void 0),this.client=t}findPeer(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e,i=r.length>1&&void 0!==r[1]?r[1]:{},o=yield GD(n.client.getPeers(t,i));if(null!=o)return{id:o.ID,multiaddrs:null!==(e=o.Addrs)&&void 0!==e?e:[]};throw new ua("Not found")}))()}getClosestPeers(t){return e._wrapAsyncGenerator((function(e){return function*(){}()})).apply(this,arguments)}}var jD=Cu("delegated-routing-v1-http-api-client"),FD={concurrentRequests:4,timeout:3e4,cacheTTL:3e5,cacheName:"delegated-routing-v1-cache"},UD=new WeakSet;class zD{constructor(t){var r,n,i,o,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._classPrivateMethodInitSpec(this,UD),e._defineProperty(this,"started",void 0),e._defineProperty(this,"httpQueue",void 0),e._defineProperty(this,"shutDownController",void 0),e._defineProperty(this,"clientUrl",void 0),e._defineProperty(this,"timeout",void 0),e._defineProperty(this,"contentRouting",void 0),e._defineProperty(this,"peerRouting",void 0),e._defineProperty(this,"filterAddrs",void 0),e._defineProperty(this,"filterProtocols",void 0),e._defineProperty(this,"inFlightRequests",void 0),e._defineProperty(this,"cacheName",void 0),e._defineProperty(this,"cache",void 0),e._defineProperty(this,"cacheTTL",void 0),this.started=!1,this.shutDownController=new AbortController,this.shutDownController.signal,this.httpQueue=new Xx({concurrency:null!==(r=a.concurrentRequests)&&void 0!==r?r:FD.concurrentRequests}),this.inFlightRequests=new Map,this.clientUrl=t instanceof URL?t:new URL(t),this.timeout=null!==(n=a.timeout)&&void 0!==n?n:FD.timeout,this.filterAddrs=a.filterAddrs,this.filterProtocols=a.filterProtocols,this.contentRouting=new LD(this),this.peerRouting=new MD(this),this.cacheName=null!==(i=a.cacheName)&&void 0!==i?i:FD.cacheName,this.cacheTTL=null!==(o=a.cacheTTL)&&void 0!==o?o:FD.cacheTTL}get[Vo](){return this.contentRouting}get[Qo](){return this.peerRouting}isStarted(){return this.started}start(){var t=this;return e._asyncToGenerator((function*(){var e;t.started||(t.started=!0,t.cacheTTL>0&&(t.cache=yield null===(e=globalThis.caches)||void 0===e?void 0:e.open(t.cacheName),null!=t.cache&&jD("cache enabled with ttl %d",t.cacheTTL)))}))()}stop(){var t=this;return e._asyncToGenerator((function*(){var e;t.httpQueue.clear(),t.shutDownController.abort(),yield null===(e=globalThis.caches)||void 0===e?void 0:e.delete(t.cacheName),t.started=!1}))()}getProviders(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){jD("getProviders starts: %c",t);var i=AbortSignal.timeout(r.timeout),o=$d([r.shutDownController.signal,i,n.signal]),a=Yc(),s=Yc();r.httpQueue.add(e._asyncToGenerator((function*(){return a.resolve(),s.promise})));try{yield e._awaitAsyncGenerator(a.promise);var l=new URL("".concat(r.clientUrl,"routing/v1/providers/").concat(t.toString()));e._assertClassBrand(UD,r,qD).call(r,l,n.filterAddrs,n.filterProtocols);var c={headers:{Accept:"application/x-ndjson"},signal:o},u=yield e._awaitAsyncGenerator(e._assertClassBrand(UD,r,HD).call(r,l.toString(),c));if(null==u)throw new DD("No response received");if(!u.ok){if(404===u.status)throw new ua("No matching records found");if(422===u.status)throw new ND("Request does not conform to schema or semantic constraints");throw new DD("Unexpected status code: ".concat(u.status))}if(null==u.body)throw new DD("Routing response had no body");var d=u.headers.get("Content-Type");if(null==d)throw new DD("No Content-Type header received");if(null!=d&&d.startsWith("application/json")){var h=yield e._awaitAsyncGenerator(u.json());for(var p of h.Providers){var f=e._assertClassBrand(UD,r,VD).call(r,p);null!=f&&(yield f)}}else{if(!d.includes("application/x-ndjson"))throw new DD("Unsupported Content-Type: ".concat(d));var v,y=!1,g=!1;try{for(var m,w=e._asyncIterator(CD(tD(u.body)));y=!(m=yield e._awaitAsyncGenerator(w.next())).done;y=!1){var b=m.value,_=e._assertClassBrand(UD,r,VD).call(r,b);null!=_&&(yield _)}}catch(e){g=!0,v=e}finally{try{y&&null!=w.return&&(yield e._awaitAsyncGenerator(w.return()))}finally{if(g)throw v}}}}finally{o.clear(),s.resolve(),jD("getProviders finished: %c",t)}}()})).apply(this,arguments)}getPeers(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){jD("getPeers starts: %c",t);var i=AbortSignal.timeout(r.timeout),o=$d([r.shutDownController.signal,i,n.signal]),a=Yc(),s=Yc();r.httpQueue.add(e._asyncToGenerator((function*(){return a.resolve(),s.promise})));try{yield e._awaitAsyncGenerator(a.promise);var l=new URL("".concat(r.clientUrl,"routing/v1/peers/").concat(t.toCID().toString()));e._assertClassBrand(UD,r,qD).call(r,l,n.filterAddrs,n.filterProtocols);var c={headers:{Accept:"application/x-ndjson"},signal:o},u=yield e._awaitAsyncGenerator(e._assertClassBrand(UD,r,HD).call(r,l.toString(),c));if(404===u.status)throw new ua("No matching records found");if(422===u.status)throw new ND("Request does not conform to schema or semantic constraints");if(null==u.body)throw new DD("Routing response had no body");if("application/json"===u.headers.get("Content-Type")){var d=yield e._awaitAsyncGenerator(u.json());for(var h of d.Peers){var p=e._assertClassBrand(UD,r,VD).call(r,h);null!=p&&(yield p)}}else{var f,v=!1,y=!1;try{for(var g,m=e._asyncIterator(CD(tD(u.body)));v=!(g=yield e._awaitAsyncGenerator(m.next())).done;v=!1){var w=g.value,b=e._assertClassBrand(UD,r,VD).call(r,w);null!=b&&(yield b)}}catch(e){y=!0,f=e}finally{try{v&&null!=m.return&&(yield e._awaitAsyncGenerator(m.return()))}finally{if(y)throw f}}}}catch(e){jD.error("getPeers errored:",e)}finally{o.clear(),s.resolve(),jD("getPeers finished: %c",t)}}()})).apply(this,arguments)}getIPNS(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i=r.length>1&&void 0!==r[1]?r[1]:{};jD("getIPNS starts: %s",t);var o=AbortSignal.timeout(n.timeout),a=$d([n.shutDownController.signal,o,i.signal]),s=Yc(),l=Yc();n.httpQueue.add(e._asyncToGenerator((function*(){return s.resolve(),l.promise})));var c="".concat(n.clientUrl,"routing/v1/ipns/").concat(t);try{yield s.promise;var u={headers:{Accept:"application/vnd.ipfs.ipns-record"},signal:a},d=yield e._assertClassBrand(UD,n,HD).call(n,c,u);if(jD("getIPNS GET %s %d",c,d.status),404===d.status)throw new ua("No matching records found");if(422===d.status)throw new ND("Request does not conform to schema or semantic constraints");if(null==d.body)throw new DD("GET ipns response had no body");var h=yield d.arrayBuffer(),p=new Uint8Array(h,0,h.byteLength);return!1!==i.validate&&(yield xD(_D(t.multihash),p)),bD(p)}catch(e){throw jD.error("getIPNS GET %s error:",c,e),e}finally{a.clear(),l.resolve(),jD("getIPNS finished: %s",t)}}))()}putIPNS(t,r){var n=arguments,i=this;return e._asyncToGenerator((function*(){var o=n.length>2&&void 0!==n[2]?n[2]:{};jD("putIPNS starts: %c",t);var a=AbortSignal.timeout(i.timeout),s=$d([i.shutDownController.signal,a,o.signal]),l=Yc(),c=Yc();i.httpQueue.add(e._asyncToGenerator((function*(){return l.resolve(),c.promise})));var u="".concat(i.clientUrl,"routing/v1/ipns/").concat(t);try{yield l.promise;var d={method:"PUT",headers:{"Content-Type":"application/vnd.ipfs.ipns-record"},body:wD(r),signal:s},h=yield e._assertClassBrand(UD,i,HD).call(i,u,d);if(jD("putIPNS PUT %s %d",u,h.status),200!==h.status)throw new DD("PUT ipns response had status other than 200")}catch(e){throw jD.error("putIPNS PUT %s error:",u,e.stack),e}finally{s.clear(),c.resolve(),jD("putIPNS finished: %c",t)}}))()}}function VD(t){try{var r,n,i=[],o=null!==(r=null===(n=t.Addrs)||void 0===n?void 0:n.map(sr))&&void 0!==r?r:[];return null!=t.Protocols&&i.push(...t.Protocols),null!=t.Protocol&&(i.push(t.Protocol),delete t.Protocol),e._objectSpread2(e._objectSpread2({},t),{},{Schema:"peer",ID:rc(t.ID),Addrs:o,Protocols:i})}catch(e){jD.error("could not conform record to peer schema",e)}}function qD(e,t,r){if(null!=t||null!=this.filterAddrs){var n,i,o,a=null!==(n=null!==(i=null==t?void 0:t.join(","))&&void 0!==i?i:null===(o=this.filterAddrs)||void 0===o?void 0:o.join(","))&&void 0!==n?n:"";""!==a&&e.searchParams.set("filter-addrs",a)}if(null!=r||null!=this.filterProtocols){var s,l,c,u=null!==(s=null!==(l=null==r?void 0:r.join(","))&&void 0!==l?l:null===(c=this.filterProtocols)||void 0===c?void 0:c.join(","))&&void 0!==s?s:"";""!==u&&e.searchParams.set("filter-protocols",u)}}function HD(e,t){return KD.apply(this,arguments)}function KD(){return KD=e._asyncToGenerator((function*(t,r){var n,i=this,o=null!==(n=r.method)&&void 0!==n?n:"GET",a="".concat(o,"-").concat(t);if("GET"===o){var s,l=yield null===(s=this.cache)||void 0===s?void 0:s.match(t);if(null!=l){var c,u;if(parseInt(null!==(c=l.headers.get("x-cache-expires"))&&void 0!==c?c:"0",10)>Date.now())return jD("returning cached response for %s",a),l;yield null===(u=this.cache)||void 0===u?void 0:u.delete(t)}}var d=this.inFlightRequests.get(a);if(null!=d){var h=yield d;return jD("deduplicating outgoing request for %s",a),h.clone()}var p=fetch(t,r).then(function(){var r=e._asyncToGenerator((function*(e){if(null!=i.cache&&e.ok&&"GET"===o){var r=Date.now()+i.cacheTTL,n=new Headers(e.headers);n.set("x-cache-expires",r.toString());var a=new Response(e.clone().body,{status:e.status,statusText:e.statusText,headers:n});yield i.cache.put(t,a)}return e}));return function(e){return r.apply(this,arguments)}}()).finally((()=>{this.inFlightRequests.delete(a)}));return this.inFlightRequests.set(a,p),yield p})),KD.apply(this,arguments)}var WD="[a-fA-F\\d:]",QD=e=>e&&e.includeBoundaries?"(?:(?<=\\s|^)(?=".concat(WD,")|(?<=").concat(WD,")(?=\\s|$))"):"",YD="(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}",JD="[a-fA-F\\d]{1,4}",ZD="\n(?:\n(?:".concat(JD,":){7}(?:").concat(JD,"|:)| // 1:2:3:4:5:6:7:: 1:2:3:4:5:6:7:8\n(?:").concat(JD,":){6}(?:").concat(YD,"|:").concat(JD,"|:)| // 1:2:3:4:5:6:: 1:2:3:4:5:6::8 1:2:3:4:5:6::8 1:2:3:4:5:6::1.2.3.4\n(?:").concat(JD,":){5}(?::").concat(YD,"|(?::").concat(JD,"){1,2}|:)| // 1:2:3:4:5:: 1:2:3:4:5::7:8 1:2:3:4:5::8 1:2:3:4:5::7:1.2.3.4\n(?:").concat(JD,":){4}(?:(?::").concat(JD,"){0,1}:").concat(YD,"|(?::").concat(JD,"){1,3}|:)| // 1:2:3:4:: 1:2:3:4::6:7:8 1:2:3:4::8 1:2:3:4::6:7:1.2.3.4\n(?:").concat(JD,":){3}(?:(?::").concat(JD,"){0,2}:").concat(YD,"|(?::").concat(JD,"){1,4}|:)| // 1:2:3:: 1:2:3::5:6:7:8 1:2:3::8 1:2:3::5:6:7:1.2.3.4\n(?:").concat(JD,":){2}(?:(?::").concat(JD,"){0,3}:").concat(YD,"|(?::").concat(JD,"){1,5}|:)| // 1:2:: 1:2::4:5:6:7:8 1:2::8 1:2::4:5:6:7:1.2.3.4\n(?:").concat(JD,":){1}(?:(?::").concat(JD,"){0,4}:").concat(YD,"|(?::").concat(JD,"){1,6}|:)| // 1:: 1::3:4:5:6:7:8 1::8 1::3:4:5:6:7:1.2.3.4\n(?::(?:(?::").concat(JD,"){0,5}:").concat(YD,"|(?::").concat(JD,"){1,7}|:)) // ::2:3:4:5:6:7:8 ::2:3:4:5:6:7:8 ::8 ::1.2.3.4\n)(?:%[0-9a-zA-Z]{1,})? // %eth0 %1\n").replace(/\s*\/\/.*$/gm,"").replace(/\n/g,"").trim(),$D=new RegExp("(?:^".concat(YD,"$)|(?:^").concat(ZD,"$)")),XD=new RegExp("^".concat(YD,"$")),eG=new RegExp("^".concat(ZD,"$")),tG=e=>e&&e.exact?$D:new RegExp("(?:".concat(QD(e)).concat(YD).concat(QD(e),")|(?:").concat(QD(e)).concat(ZD).concat(QD(e),")"),"g");tG.v4=e=>e&&e.exact?XD:new RegExp("".concat(QD(e)).concat(YD).concat(QD(e)),"g"),tG.v6=e=>e&&e.exact?eG:new RegExp("".concat(QD(e)).concat(ZD).concat(QD(e)),"g");var{toString:rG}=Object.prototype;var nG={global:"g",ignoreCase:"i",multiline:"m",dotAll:"s",sticky:"y",unicode:"u"};function iG(e){var t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(t=e,"[object RegExp]"!==rG.call(t))throw new TypeError("Expected a RegExp instance");var n=Object.keys(nG).map((t=>("boolean"==typeof r[t]?r[t]:e[t])?nG[t]:"")).join(""),i=new RegExp(r.source||e.source,n);return i.lastIndex="number"==typeof r.lastIndex?r.lastIndex:e.lastIndex,i}function oG(e,t){var r,n,{timeout:i}=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};try{return(r=()=>iG(e).test(t),n=function(){return r(...arguments)},Object.defineProperty(n,"name",{value:"functionTimeout(".concat(r.name||"<anonymous>",")"),configurable:!0}),n)()}catch(e){throw e}}var aG={timeout:400};function sG(e){return!(e.length>45)&&oG(tG.v6({exact:!0}),e,aG)}var lG={http:"80",https:"443",ws:"80",wss:"443"},cG=["http","https","ws","wss"];function uG(e,t){var r,n=null!==(r=(t=null!=t?t:{}).defaultDnsType)&&void 0!==r?r:"dns",{scheme:i,hostname:o,port:a,path:s}=function(e){var[t]=e.split(":");cG.includes(t)||(e="http"+e.substring(t.length));var r,{protocol:n,hostname:i,port:o,pathname:a,search:s}=new URL(e);if(null==o||""===o){var l=function(e){if(null==e||""===e||null==lG[e])return;return lG[e]}(t);null!=l&&(o=l),null==l&&"http:"===n&&(o="80")}null!=a&&""!==a&&"/"!==a&&(a.startsWith("/")&&(a=a.substring(1)),r=a);null!=s&&""!==s&&(r=null!=r?r:"",r+=s);return{scheme:t,hostname:i,port:o,path:r}}(e),l=[dG(o,n),hG(a,i),pG(i)];return null!=s&&l.push(function(e){if(null==e||""===e)return;return["http-path",encodeURIComponent(e)]}(s)),sr("/"+l.filter((e=>Boolean(e))).reduce(((e,t)=>e.concat(t)),[]).join("/"))}function dG(e,t){if(null!=e&&""!==e){if(function(e){return!(e.length>15)&&oG(tG.v4({exact:!0}),e,aG)}(e))return["ip4",e];if(sG(e))return["ip6",e];if("["===e[0]){var r=e.substring(1,e.length-1);if(sG(r))return["ip6",r]}return[t,e]}}function hG(e,t){if(null!=e&&""!==e)return"udp"===t?["udp",e]:["tcp",e]}function pG(e){if(null==e.match(/^tcp$|^udp$/))return"https"===e?["/tls/http"]:"wss"===e?["/tls/ws"]:[e]}var fG=["https://trustless-gateway.link","https://4everland.io"];class vG{constructor(){var t,r,n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e._defineProperty(this,"gateways",void 0),e._defineProperty(this,"shuffle",void 0),this.gateways=(null!==(t=n.gateways)&&void 0!==t?t:fG).map((e=>function(e){return e=e.toString(),{id:ac(je.createV1(2336,Te.digest(ot(e)))),multiaddrs:[uG(e)]}}(e))),this.shuffle=null===(r=n.shuffle)||void 0===r||r}findProviders(t,r){var n=this;return e._wrapAsyncGenerator((function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator((n.shuffle?n.gateways.toSorted((()=>Math.random()>.5?1:-1)):n.gateways).map((t=>e._objectSpread2(e._objectSpread2({},t),{},{protocols:["transport-ipfs-gateway-http"]})))))}))()}}function yG(){return new vG(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{})}class gG{constructor(t){e._defineProperty(this,"libp2p",void 0),this.libp2p=t}provide(t,r){var n=this;return e._asyncToGenerator((function*(){yield n.libp2p.contentRouting.provide(t,r)}))()}cancelReprovide(t,r){var n=this;return e._asyncToGenerator((function*(){yield n.libp2p.contentRouting.cancelReprovide(t,r)}))()}findProviders(t,r){var n=this;return e._wrapAsyncGenerator((function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(n.libp2p.contentRouting.findProviders(t,r)))}))()}put(t,r,n){var i=this;return e._asyncToGenerator((function*(){yield i.libp2p.contentRouting.put(t,r,n)}))()}get(t,r){var n=this;return e._asyncToGenerator((function*(){return n.libp2p.contentRouting.get(t,r)}))()}findPeer(t,r){var n=this;return e._asyncToGenerator((function*(){return n.libp2p.peerRouting.findPeer(t,r)}))()}getClosestPeers(t,r){var n=this;return e._wrapAsyncGenerator((function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(n.libp2p.peerRouting.getClosestPeers(t,r)))}))()}}function mG(e){return new gG(e)}class wG extends vN{constructor(t){super(e._objectSpread2(e._objectSpread2({},t),{},{components:{libp2p:t.libp2p}})),e._defineProperty(this,"libp2p",void 0),this.libp2p=t.libp2p}start(){var t=()=>super.start,r=this;return e._asyncToGenerator((function*(){yield t().call(r),yield r.libp2p.start()}))()}stop(){var t=()=>super.stop,r=this;return e._asyncToGenerator((function*(){yield t().call(r),yield r.libp2p.stop()}))()}}class bG extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"The frame was invalid"),this.name="InvalidFrameError"}}e._defineProperty(bG,"name","InvalidFrameError");class _G extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unrequested ping error"),this.name="UnrequestedPingError"}}e._defineProperty(_G,"name","UnrequestedPingError");class SG extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unrequested ping error"),this.name="NotMatchingPingError"}}e._defineProperty(SG,"name","NotMatchingPingError");class PG extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid state"),this.name="InvalidStateError"}}e._defineProperty(PG,"name","InvalidStateError");class EG extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Strean already exists"),this.name="StreamAlreadyExistsError"}}e._defineProperty(EG,"name","StreamAlreadyExistsError");class AG extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Decode invalid version"),this.name="DecodeInvalidVersionError"}}e._defineProperty(AG,"name","DecodeInvalidVersionError");class kG extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Both clients"),this.name="BothClientsError"}}e._defineProperty(kG,"name","BothClientsError");class xG extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Receive window exceeded"),this.name="ReceiveWindowExceededError"}}e._defineProperty(xG,"name","ReceiveWindowExceededError");var TG,IG,CG=new Set([bG.name,_G.name,SG.name,EG.name,AG.name,kG.name,xG.name]),BG=262144,NG={enableKeepAlive:!0,keepAliveInterval:3e4,maxInboundStreams:1e3,maxOutboundStreams:1e3,initialStreamWindowSize:BG,maxStreamWindowSize:16777216,maxMessageSize:65536};!function(e){e[e.Data=0]="Data",e[e.WindowUpdate=1]="WindowUpdate",e[e.Ping=2]="Ping",e[e.GoAway=3]="GoAway"}(TG||(TG={})),function(e){e[e.SYN=1]="SYN",e[e.ACK=2]="ACK",e[e.FIN=4]="FIN",e[e.RST=8]="RST"}(IG||(IG={})),Object.values(IG).filter((e=>"string"!=typeof e));var DG;!function(e){e[e.NormalTermination=0]="NormalTermination",e[e.ProtocolError=1]="ProtocolError",e[e.InternalError=2]="InternalError"}(DG||(DG={}));var GG=2**24;let RG=class{constructor(t){e._defineProperty(this,"source",void 0),e._defineProperty(this,"buffer",void 0),e._defineProperty(this,"frameInProgress",void 0),this.source=function(e){if(void 0!==e[Symbol.iterator]){var t=e[Symbol.iterator]();return t.return=void 0,{[Symbol.iterator]:()=>t}}if(void 0!==e[Symbol.asyncIterator]){var r=e[Symbol.asyncIterator]();return r.return=void 0,{[Symbol.asyncIterator]:()=>r}}throw new Error("a source must be either an iterable or an async iterable")}(t),this.buffer=new Fa,this.frameInProgress=!1}emitFrames(){var t=this;return e._wrapAsyncGenerator((function*(){var r,n=!1,i=!1;try{for(var o,a=e._asyncIterator(t.source);n=!(o=yield e._awaitAsyncGenerator(a.next())).done;n=!1){var s=o.value;for(t.buffer.append(s);;){var l=t.readHeader();if(void 0===l)break;var{type:c,length:u}=l;c===TG.Data?(t.frameInProgress=!0,yield{header:l,readData:t.readBytes.bind(t,u)}):yield{header:l}}}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield e._awaitAsyncGenerator(a.return()))}finally{if(i)throw r}}}))()}readHeader(){if(this.frameInProgress)throw new PG("decoding frame already in progress");if(!(this.buffer.length<12)){var e=function(e){if(0!==e[0])throw new bG("Invalid frame version");return{type:e[1],flag:(e[2]<<8)+e[3],streamID:e[4]*GG+(e[5]<<16)+(e[6]<<8)+e[7],length:e[8]*GG+(e[9]<<16)+(e[10]<<8)+e[11]}}(this.buffer.subarray(0,12));return this.buffer.consume(12),e}}readBytes(t){var r=this;return e._asyncToGenerator((function*(){if(r.buffer.length<t){var n,i=!1,o=!1;try{for(var a,s=e._asyncIterator(r.source);i=!(a=yield s.next()).done;i=!1){var l=a.value;if(r.buffer.append(l),r.buffer.length>=t)break}}catch(e){o=!0,n=e}finally{try{i&&null!=s.return&&(yield s.return())}finally{if(o)throw n}}}var c=r.buffer.sublist(0,t);return r.buffer.consume(t),r.frameInProgress=!1,c}))()}};function OG(e){var t=new Uint8Array(12);return t[1]=e.type,t[2]=e.flag>>>8,t[3]=e.flag,t[4]=e.streamID>>>24,t[5]=e.streamID>>>16,t[6]=e.streamID>>>8,t[7]=e.streamID,t[8]=e.length>>>24,t[9]=e.length>>>16,t[10]=e.length>>>8,t[11]=e.length,t}var LG;!function(e){e[e.Init=0]="Init",e[e.SYNSent=1]="SYNSent",e[e.SYNReceived=2]="SYNReceived",e[e.Established=3]="Established",e[e.Finished=4]="Finished"}(LG||(LG={}));class MG extends Dp{constructor(t){super(e._objectSpread2(e._objectSpread2({},t),{},{onEnd:e=>{var r;this.state=LG.Finished,null===(r=t.onEnd)||void 0===r||r.call(t,e)}})),e._defineProperty(this,"name",void 0),e._defineProperty(this,"state",void 0),e._defineProperty(this,"config",void 0),e._defineProperty(this,"_id",void 0),e._defineProperty(this,"sendWindowCapacity",void 0),e._defineProperty(this,"sendWindowCapacityUpdate",void 0),e._defineProperty(this,"recvWindow",void 0),e._defineProperty(this,"recvWindowCapacity",void 0),e._defineProperty(this,"epochStart",void 0),e._defineProperty(this,"getRTT",void 0),e._defineProperty(this,"sendFrame",void 0),this.config=t.config,this._id=parseInt(t.id,10),this.name=t.name,this.state=t.state,this.sendWindowCapacity=BG,this.recvWindow=this.config.initialStreamWindowSize,this.recvWindowCapacity=this.recvWindow,this.epochStart=Date.now(),this.getRTT=t.getRTT,this.sendFrame=t.sendFrame,this.source=xh(this.source,(()=>{this.sendWindowUpdate()}))}sendNewStream(){return e._asyncToGenerator((function*(){}))()}sendData(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};for(t=t.sublist();0!==t.byteLength;){var i,o;if(0===n.sendWindowCapacity)if(null===(i=n.log)||void 0===i||i.trace("wait for send window capacity, status %s",n.status),yield n.waitForSendWindowCapacity(e),"closed"===n.status||"aborted"===n.status||"reset"===n.status)return void(null===(o=n.log)||void 0===o||o.trace("%s while waiting for send window capacity",n.status));var a=Math.min(n.sendWindowCapacity,n.config.maxMessageSize-12,t.length),s=n.getSendFlags();n.sendFrame({type:TG.Data,flag:s,streamID:n._id,length:a},t.sublist(0,a)),n.sendWindowCapacity-=a,t.consume(a)}}))()}sendReset(){var t=this;return e._asyncToGenerator((function*(){t.sendFrame({type:TG.WindowUpdate,flag:IG.RST,streamID:t._id,length:0})}))()}sendCloseWrite(){var t=this;return e._asyncToGenerator((function*(){var e=t.getSendFlags()|IG.FIN;t.sendFrame({type:TG.WindowUpdate,flag:e,streamID:t._id,length:0})}))()}sendCloseRead(){return e._asyncToGenerator((function*(){}))()}waitForSendWindowCapacity(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var e,n=t.length>0&&void 0!==t[0]?t[0]:{};if(!(r.sendWindowCapacity>0)){var i,o,a=()=>{"open"===r.status||"closing"===r.status?o(new Zo("Stream aborted")):i()};null===(e=n.signal)||void 0===e||e.addEventListener("abort",a);try{yield new Promise(((e,t)=>{r.sendWindowCapacityUpdate=()=>{e()},o=t,i=e}))}finally{var s;null===(s=n.signal)||void 0===s||s.removeEventListener("abort",a)}}}))()}handleWindowUpdate(e){var t;null===(t=this.log)||void 0===t||t.trace("stream received window update id=%s",this._id),this.processFlags(e.flag);var r,n=this.sendWindowCapacity;(this.sendWindowCapacity+=e.length,0===n&&e.length>0)&&(null===(r=this.sendWindowCapacityUpdate)||void 0===r||r.call(this))}handleData(t,r){var n=this;return e._asyncToGenerator((function*(){var e;if(null===(e=n.log)||void 0===e||e.trace("stream received data id=%s",n._id),n.processFlags(t.flag),n.recvWindowCapacity<t.length)throw new xG("Receive window exceeded");var i=yield r();n.recvWindowCapacity-=t.length,n.sourcePush(i)}))()}processFlags(e){(e&IG.ACK)===IG.ACK&&this.state===LG.SYNSent&&(this.state=LG.Established),(e&IG.FIN)===IG.FIN&&this.remoteCloseWrite(),(e&IG.RST)===IG.RST&&this.reset()}getSendFlags(){switch(this.state){case LG.Init:return this.state=LG.SYNSent,IG.SYN;case LG.SYNReceived:return this.state=LG.Established,IG.ACK;default:return 0}}sendWindowUpdate(){var e=this.getSendFlags(),t=Date.now(),r=this.getRTT();if(0===e&&r>-1&&t-this.epochStart<4*r&&(this.recvWindow=Math.min(2*this.recvWindow,this.config.maxStreamWindowSize)),!(this.recvWindowCapacity>=this.recvWindow&&0===e)){var n=this.recvWindow-this.recvWindowCapacity;this.recvWindowCapacity=this.recvWindow,this.epochStart=t,this.sendFrame({type:TG.WindowUpdate,flag:e,streamID:this._id,length:n})}}}var jG="/yamux/1.0.0";class FG{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"protocol",jG),e._defineProperty(this,"_components",void 0),e._defineProperty(this,"_init",void 0),e._defineProperty(this,Symbol.toStringTag,"@chainsafe/libp2p-yamux"),e._defineProperty(this,Ra,["@libp2p/stream-multiplexing"]),this._components=t,this._init=r}createStreamMuxer(t){return new UG(this._components,e._objectSpread2(e._objectSpread2({},this._init),t))}}class UG{constructor(t,r){var n,i=this;e._defineProperty(this,"protocol",jG),e._defineProperty(this,"source",void 0),e._defineProperty(this,"sink",void 0),e._defineProperty(this,"config",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"logger",void 0),e._defineProperty(this,"closeController",void 0),e._defineProperty(this,"nextStreamID",void 0),e._defineProperty(this,"_streams",void 0),e._defineProperty(this,"nextPingID",void 0),e._defineProperty(this,"activePing",void 0),e._defineProperty(this,"rtt",void 0),e._defineProperty(this,"client",void 0),e._defineProperty(this,"localGoAway",void 0),e._defineProperty(this,"remoteGoAway",void 0),e._defineProperty(this,"numInboundStreams",void 0),e._defineProperty(this,"numOutboundStreams",void 0),e._defineProperty(this,"onIncomingStream",void 0),e._defineProperty(this,"onStreamEnd",void 0),this.client="outbound"===r.direction,this.config=e._objectSpread2(e._objectSpread2({},NG),r),this.logger=t.logger,this.log=this.logger.forComponent("libp2p:yamux"),function(e){if(e.keepAliveInterval<=0)throw new ea("keep-alive interval must be positive");if(e.maxInboundStreams<0)throw new ea("max inbound streams must be larger or equal 0");if(e.maxOutboundStreams<0)throw new ea("max outbound streams must be larger or equal 0");if(e.initialStreamWindowSize<BG)throw new ea("InitialStreamWindowSize must be larger or equal 256 kB");if(e.maxStreamWindowSize<e.initialStreamWindowSize)throw new ea("MaxStreamWindowSize must be larger than the InitialStreamWindowSize");if(e.maxStreamWindowSize>2**32-1)throw new ea("MaxStreamWindowSize must be less than equal MAX_UINT32");if(e.maxMessageSize<1024)throw new ea("MaxMessageSize must be greater than a kilobyte")}(this.config),this.closeController=new AbortController,this.closeController.signal,this.onIncomingStream=r.onIncomingStream,this.onStreamEnd=r.onStreamEnd,this._streams=new Map,this.source=Xc({onEnd:()=>{var e;null===(e=this.log)||void 0===e||e.trace("muxer source ended"),this._streams.forEach((e=>{e.destroy()}))}}),this.sink=function(){var t=e._asyncToGenerator((function*(t){var r,n,o,a=()=>{var e,r=Cp(t);if(null!=r.return){var n=r.return();null!=(e=n)&&"function"==typeof e.then&&n.catch((e=>{var t;null===(t=i.log)||void 0===t||t.call(i,"could not cause sink source to return",e)}))}};try{var s=new RG(t);try{i.closeController.signal.addEventListener("abort",a);var l,c=!1,u=!1;try{for(var d,h=e._asyncIterator(s.emitFrames());c=!(d=yield h.next()).done;c=!1){var p=d.value;yield i.handleFrame(p.header,p.readData)}}catch(e){u=!0,l=e}finally{try{c&&null!=h.return&&(yield h.return())}finally{if(u)throw l}}}finally{i.closeController.signal.removeEventListener("abort",a)}n=DG.NormalTermination}catch(e){var f,v;if(CG.has(e.name))null===(f=i.log)||void 0===f||f.error("protocol error in sink",e),n=DG.ProtocolError;else null===(v=i.log)||void 0===v||v.error("internal error in sink",e),n=DG.InternalError;o=e}null===(r=i.log)||void 0===r||r.trace("muxer sink ended"),null!=o?i.abort(o,n):yield i.close({reason:n})}));return function(e){return t.apply(this,arguments)}}(),this.numInboundStreams=0,this.numOutboundStreams=0,this.nextStreamID=this.client?1:2,this.nextPingID=0,this.rtt=-1,null===(n=this.log)||void 0===n||n.trace("muxer created"),this.config.enableKeepAlive&&this.keepAliveLoop().catch((e=>{var t;return null===(t=this.log)||void 0===t?void 0:t.error("keepalive error: %s",e)})),this.ping().catch((e=>{var t;return null===(t=this.log)||void 0===t?void 0:t.error("ping error: %s",e)}))}get streams(){return Array.from(this._streams.values())}newStream(e){var t;if(void 0!==this.remoteGoAway)throw new sa("Muxer closed remotely");if(void 0!==this.localGoAway)throw new sa("Muxer closed locally");var r=this.nextStreamID;if(this.nextStreamID+=2,this.numOutboundStreams>=this.config.maxOutboundStreams)throw new Aa("max outbound streams exceeded");null===(t=this.log)||void 0===t||t.trace("new outgoing stream id=%s",r);var n=this._newStream(r,e,LG.Init,"outbound");return this._streams.set(r,n),this.numOutboundStreams++,n.sendWindowUpdate(),n}ping(){var t=this;return e._asyncToGenerator((function*(){if(void 0!==t.remoteGoAway)throw new sa("Muxer closed remotely");if(void 0!==t.localGoAway)throw new sa("Muxer closed locally");if(void 0===t.activePing){var e=()=>{};t.activePing={id:t.nextPingID++,promise:new Promise(((r,n)=>{var i=()=>{n(new sa("Muxer closed locally"))};t.closeController.signal.addEventListener("abort",i,{once:!0}),e=()=>{t.closeController.signal.removeEventListener("abort",i),r()}})),resolve:e};var r=Date.now();t.sendPing(t.activePing.id);try{yield t.activePing.promise}finally{delete t.activePing}var n=Date.now();t.rtt=n-r}else yield t.activePing.promise;return t.rtt}))()}getRTT(){return this.rtt}close(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var n,i,o,a=t.length>0&&void 0!==t[0]?t[0]:{};if(!r.closeController.signal.aborted){var s=null!==(n=null===(i=a)||void 0===i?void 0:i.reason)&&void 0!==n?n:DG.NormalTermination;if(null===(o=r.log)||void 0===o||o.trace("muxer close reason=%s",s),null==a.signal){var l=AbortSignal.timeout(500);a=e._objectSpread2(e._objectSpread2({},a),{},{signal:l})}try{yield Promise.all([...r._streams.values()].map(function(){var t=e._asyncToGenerator((function*(e){return e.close(a)}));return function(e){return t.apply(this,arguments)}}())),r.sendGoAway(s),r._closeMuxer()}catch(e){r.abort(e)}}}))()}abort(e,t){var r;if(!this.closeController.signal.aborted){for(var n of(t=null!=t?t:DG.InternalError,null===(r=this.log)||void 0===r||r.error("muxer abort reason=%s error=%s",t,e),this._streams.values()))n.abort(e);this.sendGoAway(t),this._closeMuxer()}}isClosed(){return this.closeController.signal.aborted}_closeMuxer(){this.closeController.abort(),this.source.end()}_newStream(e,t,r,n){if(null!=this._streams.get(e))throw new ea("Stream already exists with that id");var i=new MG({id:e.toString(),name:t,state:r,direction:n,sendFrame:this.sendFrame.bind(this),onEnd:()=>{var t;this.closeStream(e),null===(t=this.onStreamEnd)||void 0===t||t.call(this,i)},log:this.logger.forComponent("libp2p:yamux:".concat(n,":").concat(e)),config:this.config,getRTT:this.getRTT.bind(this)});return i}closeStream(e){this.client===(e%2==0)?this.numInboundStreams--:this.numOutboundStreams--,this._streams.delete(e)}keepAliveLoop(){var t=this;return e._asyncToGenerator((function*(){var e,r=new Promise(((e,r)=>{t.closeController.signal.addEventListener("abort",r,{once:!0})}));null===(e=t.log)||void 0===e||e.trace("muxer keepalive enabled interval=%s",t.config.keepAliveInterval);for(var n,i=function*(){var e;try{yield Promise.race([r,new Promise((r=>{e=setTimeout(r,t.config.keepAliveInterval)}))]),t.ping().catch((e=>{var r;return null===(r=t.log)||void 0===r?void 0:r.error("ping error: %s",e)}))}catch(t){return clearInterval(e),{v:void 0}}};;)if(n=yield*i())return n.v}))()}handleFrame(t,r){var n=this;return e._asyncToGenerator((function*(){var e,{streamID:i,type:o,length:a}=t;if(null===(e=n.log)||void 0===e||e.trace("received frame %o",t),0===i)switch(o){case TG.Ping:return void n.handlePing(t);case TG.GoAway:return void n.handleGoAway(a);default:throw new bG("Invalid frame type")}else switch(t.type){case TG.Data:case TG.WindowUpdate:return void(yield n.handleStreamMessage(t,r));default:throw new bG("Invalid frame type")}}))()}handlePing(e){if(e.flag===IG.SYN){var t;null===(t=this.log)||void 0===t||t.trace("received ping request pingId=%s",e.length),this.sendPing(e.length,IG.ACK)}else{if(e.flag!==IG.ACK)throw new bG("Invalid frame flag");var r;null===(r=this.log)||void 0===r||r.trace("received ping response pingId=%s",e.length),this.handlePingResponse(e.length)}}handlePingResponse(e){if(void 0===this.activePing)throw new _G("ping not requested");if(this.activePing.id!==e)throw new SG("ping doesn't match our id");this.activePing.resolve()}handleGoAway(e){var t,r;for(var n of(null===(t=this.log)||void 0===t||t.trace("received GoAway reason=%s",null!==(r=DG[e])&&void 0!==r?r:"unknown"),this.remoteGoAway=e,this._streams.values()))n.reset();this._closeMuxer()}handleStreamMessage(t,r){var n=this;return e._asyncToGenerator((function*(){var{streamID:e,flag:i,type:o}=t;(i&IG.SYN)===IG.SYN&&n.incomingStream(e);var a=n._streams.get(e);if(void 0!==a)switch(o){case TG.WindowUpdate:return void a.handleWindowUpdate(t);case TG.Data:if(void 0===r)throw new Error("unreachable");return void(yield a.handleData(t,r));default:throw new Error("unreachable")}else if(o===TG.Data){var s;if(null===(s=n.log)||void 0===s||s.call(n,"discarding data for stream id=%s",e),void 0===r)throw new Error("unreachable");yield r()}else{var l;null===(l=n.log)||void 0===l||l.trace("frame for missing stream id=%s",e)}}))()}incomingStream(e){var t,r;if(this.client!==(e%2==0))throw new ea("Both endpoints are clients");if(!this._streams.has(e))if(null===(t=this.log)||void 0===t||t.trace("new incoming stream id=%s",e),void 0===this.localGoAway){var n;if(this.numInboundStreams>=this.config.maxInboundStreams)return null===(n=this.log)||void 0===n||n.call(this,"maxIncomingStreams exceeded, forcing stream reset"),void this.sendFrame({type:TG.WindowUpdate,flag:IG.RST,streamID:e,length:0});var i=this._newStream(e,void 0,LG.SYNReceived,"inbound");this.numInboundStreams++,this._streams.set(e,i),null===(r=this.onIncomingStream)||void 0===r||r.call(this,i)}else this.sendFrame({type:TG.WindowUpdate,flag:IG.RST,streamID:e,length:0})}sendFrame(e,t){var r;if(null===(r=this.log)||void 0===r||r.trace("sending frame %o",e),e.type===TG.Data){if(void 0===t)throw new bG("Invalid frame");this.source.push(new Fa(OG(e),t))}else this.source.push(OG(e))}sendPing(e){var t,r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:IG.SYN;n===IG.SYN?null===(t=this.log)||void 0===t||t.trace("sending ping request pingId=%s",e):null===(r=this.log)||void 0===r||r.trace("sending ping response pingId=%s",e);this.sendFrame({type:TG.Ping,flag:n,streamID:0,length:e})}sendGoAway(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:DG.NormalTermination;null===(e=this.log)||void 0===e||e.call(this,"sending GoAway reason=%s",DG[t]),this.localGoAway=t,this.sendFrame({type:TG.GoAway,flag:0,streamID:0,length:t})}}function zG(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new FG(t,e)}function VG(e){try{var[[t,r]]=e.stringTuples();if(null==r)return!1;if(41===t)return n=r,new ir("2000::/3").contains(n)}catch(e){}var n;return!1}function qG(e){try{var[[t]]=e.stringTuples();return 4===t||41===t}catch(e){}return!1}function HG(e){try{var t;if(!qG(e))return!1;var[[,r]]=e.stringTuples();return null!=r&&(null!==(t=CN(r))&&void 0!==t&&t)}catch(e){}return!0}var KG;!function(e){var t,r,n,i;!function(e){e.DIAL="DIAL",e.DIAL_RESPONSE="DIAL_RESPONSE"}(e.MessageType||(e.MessageType={})),function(e){e[e.DIAL=0]="DIAL",e[e.DIAL_RESPONSE=1]="DIAL_RESPONSE"}(t||(t={})),function(e){e.codec=()=>pl(t)}(e.MessageType||(e.MessageType={})),(r=e.ResponseStatus||(e.ResponseStatus={})).OK="OK",r.E_DIAL_ERROR="E_DIAL_ERROR",r.E_DIAL_REFUSED="E_DIAL_REFUSED",r.E_BAD_REQUEST="E_BAD_REQUEST",r.E_INTERNAL_ERROR="E_INTERNAL_ERROR",function(e){e[e.OK=0]="OK",e[e.E_DIAL_ERROR=100]="E_DIAL_ERROR",e[e.E_DIAL_REFUSED=101]="E_DIAL_REFUSED",e[e.E_BAD_REQUEST=200]="E_BAD_REQUEST",e[e.E_INTERNAL_ERROR=300]="E_INTERNAL_ERROR"}(n||(n={})),function(e){e.codec=()=>pl(n)}(e.ResponseStatus||(e.ResponseStatus={})),function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==r.lengthDelimited&&t.fork(),null!=e.id&&(t.uint32(10),t.bytes(e.id)),null!=e.addrs)for(var n of e.addrs)t.uint32(18),t.bytes(n);!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={addrs:[]},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:n.id=e.bytes();break;case 2:var a;if(null!=(null===(a=r.limits)||void 0===a?void 0:a.addrs)&&n.addrs.length===r.limits.addrs)throw new vl('Decode error - map field "addrs" had too many elements');n.addrs.push(e.bytes());break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(e.PeerInfo||(e.PeerInfo={})),function(t){var r;t.codec=()=>(null==r&&(r=fl((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==n.lengthDelimited&&r.fork(),null!=t.peer&&(r.uint32(10),e.PeerInfo.codec().encode(t.peer,r)),!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i={},o=null==r?t.len:t.pos+r;t.pos<o;){var a,s=t.uint32();if(s>>>3==1)i.peer=e.PeerInfo.codec().decode(t,t.uint32(),{limits:null===(a=n.limits)||void 0===a?void 0:a.peer});else t.skipType(7&s)}return i}))),r),t.encode=e=>dl(e,t.codec()),t.decode=(e,r)=>Vs(e,t.codec(),r)}(e.Dial||(e.Dial={})),function(t){var r;t.codec=()=>(null==r&&(r=fl((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==n.lengthDelimited&&r.fork(),null!=t.status&&(r.uint32(8),e.ResponseStatus.codec().encode(t.status,r)),null!=t.statusText&&(r.uint32(18),r.string(t.statusText)),null!=t.addr&&(r.uint32(26),r.bytes(t.addr)),!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n={},i=null==r?t.len:t.pos+r;t.pos<i;){var o=t.uint32();switch(o>>>3){case 1:n.status=e.ResponseStatus.codec().decode(t);break;case 2:n.statusText=t.string();break;case 3:n.addr=t.bytes();break;default:t.skipType(7&o)}}return n}))),r),t.encode=e=>dl(e,t.codec()),t.decode=(e,r)=>Vs(e,t.codec(),r)}(e.DialResponse||(e.DialResponse={})),e.codec=()=>(null==i&&(i=fl((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==n.lengthDelimited&&r.fork(),null!=t.type&&(r.uint32(8),e.MessageType.codec().encode(t.type,r)),null!=t.dial&&(r.uint32(18),e.Dial.codec().encode(t.dial,r)),null!=t.dialResponse&&(r.uint32(26),e.DialResponse.codec().encode(t.dialResponse,r)),!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i={},o=null==r?t.len:t.pos+r;t.pos<o;){var a=t.uint32();switch(a>>>3){case 1:i.type=e.MessageType.codec().decode(t);break;case 2:var s;i.dial=e.Dial.codec().decode(t,t.uint32(),{limits:null===(s=n.limits)||void 0===s?void 0:s.dial});break;case 3:var l;i.dialResponse=e.DialResponse.codec().decode(t,t.uint32(),{limits:null===(l=n.limits)||void 0===l?void 0:l.dialResponse});break;default:t.skipType(7&a)}}return i}))),i),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(KG||(KG={}));class WG{constructor(t,r){var n,i,o,a,s,l;e._defineProperty(this,"components",void 0),e._defineProperty(this,"protocol",void 0),e._defineProperty(this,"timeout",void 0),e._defineProperty(this,"maxInboundStreams",void 0),e._defineProperty(this,"maxOutboundStreams",void 0),e._defineProperty(this,"maxMessageSize",void 0),e._defineProperty(this,"started",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"topologyId",void 0),e._defineProperty(this,"dialResults",void 0),e._defineProperty(this,"findPeers",void 0),e._defineProperty(this,"addressFilter",void 0),e._defineProperty(this,"connectionThreshold",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/autonat"),e._defineProperty(this,Ra,["@libp2p/autonat"]),this.components=t,this.log=t.logger.forComponent("libp2p:auto-nat"),this.started=!1,this.protocol="/".concat(null!==(n=r.protocolPrefix)&&void 0!==n?n:"libp2p","/").concat("autonat","/").concat("1.0.0"),this.timeout=null!==(i=r.timeout)&&void 0!==i?i:3e4,this.maxInboundStreams=null!==(o=r.maxInboundStreams)&&void 0!==o?o:2,this.maxOutboundStreams=null!==(a=r.maxOutboundStreams)&&void 0!==a?a:20,this.connectionThreshold=null!==(s=r.connectionThreshold)&&void 0!==s?s:80,this.maxMessageSize=null!==(l=r.maxMessageSize)&&void 0!==l?l:8192,this.dialResults=new Map,this.findPeers=function(t,r,n){var i,o;function a(){var s,l={signal:o.signal};if(null!=(null===(s=n)||void 0===s?void 0:s.timeout)){var c=$d([o.signal,AbortSignal.timeout(n.timeout)]);l.signal=c}Promise.resolve().then(e._asyncToGenerator((function*(){yield t(l)}))).catch((()=>{})).finally((()=>{o.signal.aborted||(i=setTimeout(a,r))}))}var s=!1;return{setInterval:e=>{r!==e&&(r=e,null!=i&&(clearTimeout(i),i=setTimeout(a,r)))},setTimeout:e=>{null!=n||(n={}),n.timeout=e},start:()=>{var e;s||(s=!0,(o=new AbortController).signal,!0===(null===(e=n)||void 0===e?void 0:e.runImmediately)?queueMicrotask((()=>{a()})):i=setTimeout(a,r))},stop:()=>{var e;clearTimeout(i),null===(e=o)||void 0===e||e.abort(),s=!1}}}(this.findRandomPeers.bind(this),6e4),this.addressFilter=_h(1024)}get[Oa](){return["@libp2p/identify"]}isStarted(){return this.started}start(){var t=this;return e._asyncToGenerator((function*(){t.started||(yield t.components.registrar.handle(t.protocol,(e=>{t.handleIncomingAutonatStream(e).catch((e=>{t.log.error("error handling incoming autonat stream - %e",e)}))}),{maxInboundStreams:t.maxInboundStreams,maxOutboundStreams:t.maxOutboundStreams}),t.topologyId=yield t.components.registrar.register(t.protocol,{onConnect:(e,r)=>{t.verifyExternalAddresses(r).catch((e=>{t.log.error("could not verify addresses - %e",e)}))}}),t.findPeers.start(),t.started=!0)}))()}stop(){var t=this;return e._asyncToGenerator((function*(){yield t.components.registrar.unhandle(t.protocol),null!=t.topologyId&&(yield t.components.registrar.unhandle(t.topologyId)),t.dialResults.clear(),t.findPeers.stop(),t.started=!1}))()}allAddressesAreVerified(){return this.components.addressManager.getAddressesWithMetadata().every((e=>e.expires>Date.now()||e.verified))}findRandomPeers(t){var r=this;return e._asyncToGenerator((function*(){if(!r.allAddressesAreVerified()){var n=$d([AbortSignal.timeout(1e4),null==t?void 0:t.signal]);try{r.log("starting random walk to find peers to run AutoNAT");var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(r.components.randomWalk.walk({signal:n}));o=!(s=yield l.next()).done;o=!1){var c=s.value;if(yield r.components.connectionManager.isDialable(c.multiaddrs)){try{r.log.trace("dial random peer %p",c.id),yield r.components.connectionManager.openConnection(c.multiaddrs,{signal:n})}catch(e){}if(r.allAddressesAreVerified())return void r.log("stopping random walk, all addresses are verified");if(!r.hasConnectionCapacity())return void r.log("stopping random walk, too close to max connections")}else r.log.trace("random peer %p was not dialable %s",c.id,c.multiaddrs.map((e=>e.toString())).join(", "))}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield l.return())}finally{if(a)throw i}}}catch(e){}}}))()}handleIncomingAutonatStream(t){var r=this;return e._asyncToGenerator((function*(){var e=AbortSignal.timeout(r.timeout),n=Wu(t.stream,{maxDataLength:r.maxMessageSize}).pb(KG);try{var i=yield n.read({signal:e}),o=yield r.handleAutonatMessage(i,t.connection,{signal:e});yield n.write(o,{signal:e}),yield n.unwrap().unwrap().close({signal:e})}catch(e){r.log.error("error handling incoming autonat stream - %e",e),t.stream.abort(e)}}))()}handleAutonatMessage(t,r,n){var i=this;return e._asyncToGenerator((function*(){var e,o=i.components.addressManager.getAddresses().map((e=>e.toOptions().host)),a=t.dial;if(null==a)return i.log.error("dial was missing from message"),{type:KG.MessageType.DIAL_RESPONSE,dialResponse:{status:KG.ResponseStatus.E_BAD_REQUEST,statusText:"No Dial message found in message"}};var s=a.peer;if(null==(null==s?void 0:s.id))return i.log.error("PeerId missing from message"),{type:KG.MessageType.DIAL_RESPONSE,dialResponse:{status:KG.ResponseStatus.E_BAD_REQUEST,statusText:"missing peer info"}};try{var l=Ae(s.id);e=oc(l)}catch(e){return i.log.error("invalid PeerId - %e",e),{type:KG.MessageType.DIAL_RESPONSE,dialResponse:{status:KG.ResponseStatus.E_BAD_REQUEST,statusText:"bad peer id"}}}if(i.log("incoming request from %p",e),!r.remotePeer.equals(e))return i.log("target peer %p did not equal sending peer %p",e,r.remotePeer),{type:KG.MessageType.DIAL_RESPONSE,dialResponse:{status:KG.ResponseStatus.E_BAD_REQUEST,statusText:"peer id mismatch"}};var c=s.addrs.map((e=>sr(e))).filter((e=>{var t=e.toOptions();return!HG(e)&&(t.host!==r.remoteAddr.toOptions().host?(i.log.trace("not dialing %a - target host did not match remote host %a",e,r.remoteAddr),!1):!o.includes(t.host)&&(null!=i.components.transportManager.dialTransportForMultiaddr(e)||(i.log.trace("not dialing %a - transport unsupported",e),!1)))})).map((t=>(null==t.getPeerId()&&(t=t.encapsulate("/p2p/".concat(e.toString()))),t)));if(0===c.length)return i.log("refused to dial all multiaddrs for %p from message",e),{type:KG.MessageType.DIAL_RESPONSE,dialResponse:{status:KG.ResponseStatus.E_DIAL_REFUSED,statusText:"no dialable addresses"}};i.log("dial multiaddrs %s for peer %p",c.map((e=>e.toString())).join(", "),e);var u="",d=c[0];for(var h of c){var p=void 0;d=h;try{if(!(p=yield i.components.connectionManager.openConnection(h,n)).remoteAddr.equals(h))throw i.log.error("tried to dial %a but dialed %a",h,p.remoteAddr),new Error("Unexpected remote address");return i.log("successfully dialed %p via %a",e,h),{type:KG.MessageType.DIAL_RESPONSE,dialResponse:{status:KG.ResponseStatus.OK,addr:p.remoteAddr.decapsulateCode(lr("p2p").code).bytes}}}catch(t){i.log.error("could not dial %p - %e",e,t),u=t.message}finally{null!=p&&(yield p.close())}}return{type:KG.MessageType.DIAL_RESPONSE,dialResponse:{status:KG.ResponseStatus.E_DIAL_ERROR,statusText:u,addr:d.bytes}}}))()}getFirstUnverifiedMultiaddr(e,t){var r=this.components.addressManager.getAddressesWithMetadata().sort(((e,t)=>"observed"===e.type&&"observed"!==t.type?1:"observed"===t.type&&"observed"!==e.type?-1:0)).filter((e=>{if(!(e.expires<Date.now()))return!1;if(6===e.multiaddr.toOptions().family){if(!t)return!1;if(!VG(e.multiaddr))return!1}return!HG(e.multiaddr)}));for(var n of r){var i=n.multiaddr.toString(),o=this.dialResults.get(i);if(null!=o){if(o.networkSegments.includes(e)){this.log.trace("%a already has a network segment result from %s",o.multiaddr,e);continue}if(o.queue.size>10){this.log.trace("%a already has enough peers queued",o.multiaddr);continue}}if(null==o){var a,s,l=n.expires<Date.now();if(l)null===(a=(s=this.addressFilter).remove)||void 0===a||a.call(s,i);if(this.addressFilter.has(i))continue;this.addressFilter.add(i),this.log.trace("creating dial result %s %s",l?"to revalidate":"for",i),o={multiaddr:n.multiaddr,success:0,failure:0,networkSegments:[],verifyingPeers:new ch,queue:new jh({concurrency:3,maxSize:50}),type:n.type,lastVerified:n.lastVerified},this.dialResults.set(i,o)}return o}}removeOutdatedMultiaddrResults(){var e=new Set(this.components.addressManager.getAddressesWithMetadata().filter((e=>{var{expires:t}=e;return t<Date.now()})).map((e=>{var{multiaddr:t}=e;return t.toString()})));for(var t of this.dialResults.keys())e.has(t)||(this.log.trace("remove results for %a",t),this.dialResults.delete(t))}verifyExternalAddresses(t){var r=this;return e._asyncToGenerator((function*(){if(r.isStarted()){r.removeOutdatedMultiaddrResults();var n=(yield r.components.peerStore.get(t.remotePeer)).addresses.some((e=>{var{multiaddr:t}=e;return 6===t.toOptions().family})),i=r.getNetworkSegment(t.remoteAddr),o=r.getFirstUnverifiedMultiaddr(i,n);null!=o?r.hasConnectionCapacity()?o.queue.add(function(){var n=e._asyncToGenerator((function*(e){yield r.askPeerToVerify(t,i,e)}));return function(e){return n.apply(this,arguments)}}(),{peerId:t.remotePeer,multiaddr:o.multiaddr}).catch((e=>{null==(null==o?void 0:o.result)&&r.log.error("error from %p verifying address %a - %e",t.remotePeer,null==o?void 0:o.multiaddr,e)})):null!=o.lastVerified?(r.log("automatically re-verifying %a because we are too close to the connection limit",o.multiaddr),r.confirmAddress(o)):r.log("skipping verifying %a because we are too close to the connection limit",o.multiaddr):r.log.trace("no unverified public addresses found for peer %p to verify, not requesting verification",t.remotePeer)}}))()}askPeerToVerify(t,r,n){var i=this;return e._asyncToGenerator((function*(){var e=i.dialResults.get(n.multiaddr.toString());if(null!=e){var o=AbortSignal.timeout(i.timeout);i.log.trace("asking %p to verify multiaddr %s",t.remotePeer,n.multiaddr);var a=yield t.newStream(i.protocol,{signal:o});try{var s=Wu(a).pb(KG),[,l]=yield Promise.all([s.write({type:KG.MessageType.DIAL,dial:{peer:{id:i.components.peerId.toMultihash().bytes,addrs:[n.multiaddr.bytes]}}},{signal:o}),s.read({signal:o})]);if(l.type!==KG.MessageType.DIAL_RESPONSE||null==l.dialResponse)return void i.log("invalid autonat response from %p - %j",t.remotePeer,l);var c=l.dialResponse.status;if(i.log.trace("autonat response from %p for %a is %s",t.remotePeer,n.multiaddr,c),c!==KG.ResponseStatus.OK&&c!==KG.ResponseStatus.E_DIAL_ERROR)return;if(null==(e=i.dialResults.get(n.multiaddr.toString())))return void i.log.trace("peer reported %a as %s but there is no result object",n.multiaddr,l.dialResponse.status);if(e.networkSegments.includes(r))return void i.log.trace("%a results included network segment %s",n.multiaddr,r);if(null!=e.result)return void i.log.trace("already resolved result for %a, ignoring response from",n.multiaddr,t.remotePeer);if(e.verifyingPeers.has(t.remotePeer))return void i.log.trace("peer %p has already verified %a, ignoring response",t.remotePeer,n.multiaddr);if(e.verifyingPeers.add(t.remotePeer),e.networkSegments.push(r),c===KG.ResponseStatus.OK){if(e.success++,"observed"!==e.type)return void i.confirmAddress(e)}else c===KG.ResponseStatus.E_DIAL_ERROR&&e.failure++;i.log("%a success %d failure %d",e.multiaddr,e.success,e.failure),4===e.success&&i.confirmAddress(e),8===e.failure&&i.unconfirmAddress(e)}finally{try{yield a.close({signal:o})}catch(e){a.abort(e)}}}else i.log("%a was verified while %p was queued",n.multiaddr,t.remotePeer)}))()}hasConnectionCapacity(){return this.components.connectionManager.getConnections().length/this.components.connectionManager.getMaxConnections()*100<this.connectionThreshold}confirmAddress(e){this.log("%s address %a is externally dialable",e.type,e.multiaddr),this.components.addressManager.confirmObservedAddr(e.multiaddr),this.dialResults.delete(e.multiaddr.toString()),e.result=!0,e.queue.abort()}unconfirmAddress(e){this.log("%s address %a is not externally dialable",e.type,e.multiaddr),this.components.addressManager.removeObservedAddr(e.multiaddr),this.dialResults.delete(e.multiaddr.toString()),e.result=!1,e.queue.abort()}getNetworkSegment(e){var t=e.toOptions();return 4===t.family?t.host.split(".")[0].padStart(3,"0"):t.host.split(":")[0].padStart(4,"0")}}function QG(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new WG(t,e)}var YG=kR("dns4"),JG=kR("dns6"),ZG=kR("dnsaddr"),$G=AR(kR("dns"),ZG,YG,JG),XG=AR(kR("ip4"),kR("ip6")),eR=AR(ER(XG,kR("tcp")),ER($G,kR("tcp"))),tR=ER(XG,kR("udp")),rR=ER(tR,kR("utp")),nR=ER(tR,kR("quic")),iR=ER(tR,kR("quic-v1")),oR=AR(ER(eR,kR("ws")),ER($G,kR("ws"))),aR=AR(ER(oR,kR("p2p")),oR),sR=AR(ER(eR,kR("wss")),ER($G,kR("wss")),ER(eR,kR("tls"),kR("ws")),ER($G,kR("tls"),kR("ws"))),lR=AR(ER(sR,kR("p2p")),sR),cR=AR(ER(eR,kR("http")),ER(XG,kR("http")),ER($G,kR("http"))),uR=AR(ER(eR,kR("https")),ER(XG,kR("https")),ER($G,kR("https"))),dR=ER(tR,kR("webrtc-direct"),kR("certhash")),hR=AR(ER(dR,kR("p2p")),dR),pR=ER(iR,kR("webtransport"),kR("certhash"),kR("certhash")),fR=AR(ER(pR,kR("p2p")),pR),vR=AR(ER(aR,kR("p2p-webrtc-star"),kR("p2p")),ER(lR,kR("p2p-webrtc-star"),kR("p2p")),ER(aR,kR("p2p-webrtc-star")),ER(lR,kR("p2p-webrtc-star")));AR(ER(aR,kR("p2p-websocket-star"),kR("p2p")),ER(lR,kR("p2p-websocket-star"),kR("p2p")),ER(aR,kR("p2p-websocket-star")),ER(lR,kR("p2p-websocket-star")));var yR=AR(ER(cR,kR("p2p-webrtc-direct"),kR("p2p")),ER(uR,kR("p2p-webrtc-direct"),kR("p2p")),ER(cR,kR("p2p-webrtc-direct")),ER(uR,kR("p2p-webrtc-direct"))),gR=AR(oR,sR,cR,uR,vR,yR,eR,rR,nR,$G,hR,fR);AR(ER(gR,kR("p2p-stardust"),kR("p2p")),ER(gR,kR("p2p-stardust")));var mR=AR(ER(gR,kR("p2p")),vR,yR,hR,fR,kR("p2p")),wR=AR(ER(mR,kR("p2p-circuit"),mR),ER(mR,kR("p2p-circuit")),ER(kR("p2p-circuit"),mR),ER(gR,kR("p2p-circuit")),ER(kR("p2p-circuit"),gR),kR("p2p-circuit")),bR=()=>AR(ER(wR,bR),wR),_R=bR(),SR=AR(ER(_R,mR,_R),ER(mR,_R),ER(_R,mR),_R,mR);function PR(e){return function(t){var r;try{r=sr(t)}catch(e){return!1}var n=e(r.protoNames());return null!==n&&(!0===n||!1===n?n:0===n.length)}}function ER(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];function n(e){if(e.length<t.length)return null;var r=e;return t.some((t=>(r="function"==typeof t?t().partialMatch(e):t.partialMatch(e),Array.isArray(r)&&(e=r),null===r))),r}return{toString:function(){return"{ "+t.join(" ")+" }"},input:t,matches:PR(n),partialMatch:n}}function AR(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];function n(e){var r=null;return t.some((t=>{var n="function"==typeof t?t().partialMatch(e):t.partialMatch(e);return null!=n&&(r=n,!0)})),r}return{toString:function(){return"{ "+t.join(" ")+" }"},input:t,matches:PR(n),partialMatch:n}}function kR(e){var t=e;return{toString:function(){return t},matches:function(e){var r;try{r=sr(e)}catch(e){return!1}var n=r.protoNames();return 1===n.length&&n[0]===t},partialMatch:function(e){return 0===e.length?null:e[0]===t?e.slice(1):null}}}AR(ER(_R,kR("webrtc"),kR("p2p")),ER(_R,kR("webrtc")),ER(gR,kR("webrtc"),kR("p2p")),ER(gR,kR("webrtc")),kR("webrtc"));class xR extends Ia{constructor(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{list:[]};if(null==n.list||0===n.list.length)throw new Error("Bootstrap requires a list of peer addresses");for(var i of(super(),e._defineProperty(this,"log",void 0),e._defineProperty(this,"timer",void 0),e._defineProperty(this,"list",void 0),e._defineProperty(this,"timeout",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"_init",void 0),e._defineProperty(this,qo,this),e._defineProperty(this,Symbol.toStringTag,"@libp2p/bootstrap"),e._defineProperty(this,Ra,["@libp2p/peer-discovery"]),this.components=t,this.log=t.logger.forComponent("libp2p:bootstrap"),this.timeout=null!==(r=n.timeout)&&void 0!==r?r:1e3,this.list=[],n.list))if(SR.matches(i)){var o=sr(i),a=o.getPeerId();if(null!=a){var s={id:rc(a),multiaddrs:[o]};this.list.push(s)}else this.log.error("Invalid bootstrap multiaddr without peer id")}else this.log.error("Invalid multiaddr");this._init=n}isStarted(){return Boolean(this.timer)}start(){this.isStarted()||(this.log("Starting bootstrap node discovery, discovering peers after %s ms",this.timeout),this.timer=setTimeout((()=>{this._discoverBootstrapPeers().catch((e=>{this.log.error(e)}))}),this.timeout))}_discoverBootstrapPeers(){var t=this;return e._asyncToGenerator((function*(){if(null!=t.timer){var e,r=function*(e){var r,n;if(yield t.components.peerStore.merge(e.id,{tags:{[null!==(r=t._init.tagName)&&void 0!==r?r:"bootstrap"]:{value:null!==(n=t._init.tagValue)&&void 0!==n?n:50,ttl:t._init.tagTTL}},multiaddrs:e.multiaddrs}),null==t.timer)return{v:void 0};t.safeDispatchEvent("peer",{detail:e}),t.components.connectionManager.openConnection(e.id).catch((r=>{t.log.error("could not dial bootstrap peer %p",e.id,r)}))};for(var n of t.list)if(e=yield*r(n))return e.v}}))()}stop(){null!=this.timer&&clearTimeout(this.timer),this.timer=void 0}}e._defineProperty(xR,"tag","bootstrap");var TR=()=>{var e=new Error("Delay aborted");return e.name="AbortError",e},IR=new WeakMap;var CR,BR=function(){var{clearTimeout:e,setTimeout:t}=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function(r){var n,i,o,{value:a,signal:s}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null!=s&&s.aborted)return Promise.reject(TR());var l=null!=e?e:clearTimeout,c=()=>{l(n),o(TR())},u=new Promise(((e,l)=>{i=()=>{s&&s.removeEventListener("abort",c),e(a)},o=l,n=(null!=t?t:setTimeout)(i,r)}));return s&&s.addEventListener("abort",c,{once:!0}),IR.set(u,(()=>{l(n),n=null,i()})),u}}();function NR(e,t){return!Qd.matches(e)&&(null!=t.dialTransportForMultiaddr(e)&&(!!_d.matches(e)||!!Id.matches(e)&&!1===CN(e.toOptions().host)))}!function(e){var t,r;!function(e){e.UNUSED="UNUSED",e.CONNECT="CONNECT",e.SYNC="SYNC"}(e.Type||(e.Type={})),function(e){e[e.UNUSED=0]="UNUSED",e[e.CONNECT=100]="CONNECT",e[e.SYNC=300]="SYNC"}(t||(t={})),function(e){e.codec=()=>pl(t)}(e.Type||(e.Type={})),e.codec=()=>(null==r&&(r=fl((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==n.lengthDelimited&&r.fork(),null!=t.type&&(r.uint32(8),e.Type.codec().encode(t.type,r)),null!=t.observedAddresses)for(var i of t.observedAddresses)r.uint32(18),r.bytes(i);!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i={observedAddresses:[]},o=null==r?t.len:t.pos+r;t.pos<o;){var a=t.uint32();switch(a>>>3){case 1:i.type=e.Type.codec().decode(t);break;case 2:var s;if(null!=(null===(s=n.limits)||void 0===s?void 0:s.observedAddresses)&&i.observedAddresses.length===n.limits.observedAddresses)throw new vl('Decode error - map field "observedAddresses" had too many elements');i.observedAddresses.push(t.bytes());break;default:t.skipType(7&a)}}return i}))),r),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(CR||(CR={}));var DR=5e3,GR=3,RR=1,OR=1;class LR{constructor(t,r){var n,i,o,a;e._defineProperty(this,"started",void 0),e._defineProperty(this,"timeout",void 0),e._defineProperty(this,"retries",void 0),e._defineProperty(this,"maxInboundStreams",void 0),e._defineProperty(this,"maxOutboundStreams",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"registrar",void 0),e._defineProperty(this,"connectionManager",void 0),e._defineProperty(this,"addressManager",void 0),e._defineProperty(this,"transportManager",void 0),e._defineProperty(this,"topologyId",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/dcutr"),e._defineProperty(this,Oa,["@libp2p/identify"]),this.log=t.logger.forComponent("libp2p:dcutr"),this.started=!1,this.peerStore=t.peerStore,this.registrar=t.registrar,this.addressManager=t.addressManager,this.connectionManager=t.connectionManager,this.transportManager=t.transportManager,this.timeout=null!==(n=r.timeout)&&void 0!==n?n:DR,this.retries=null!==(i=r.retries)&&void 0!==i?i:GR,this.maxInboundStreams=null!==(o=r.maxInboundStreams)&&void 0!==o?o:RR,this.maxOutboundStreams=null!==(a=r.maxOutboundStreams)&&void 0!==a?a:OR}isStarted(){return this.started}start(){var t=this;return e._asyncToGenerator((function*(){t.started||(t.topologyId=yield t.registrar.register(jR,{notifyOnLimitedConnection:!0,onConnect:(e,r)=>{Qd.exactMatch(r.remoteAddr)&&"inbound"===r.direction&&t.upgradeInbound(r).catch((e=>{t.log.error("error during outgoing DCUtR attempt",e)}))}}),yield t.registrar.handle(jR,(e=>{t.handleIncomingUpgrade(e.stream,e.connection).catch((r=>{t.log.error("error during incoming DCUtR attempt",r),e.stream.abort(r)}))}),{maxInboundStreams:t.maxInboundStreams,maxOutboundStreams:t.maxOutboundStreams,runOnLimitedConnection:!0}),t.started=!0)}))()}stop(){var t=this;return e._asyncToGenerator((function*(){yield t.registrar.unhandle(jR),null!=t.topologyId&&t.registrar.unregister(t.topologyId),t.started=!1}))()}upgradeInbound(t){var r=this;return e._asyncToGenerator((function*(){if(!(yield r.attemptUnilateralConnectionUpgrade(t)))for(var e,n=0;n<r.retries;n++){var i={signal:AbortSignal.timeout(r.timeout)};try{var o=Wu(e=yield t.newStream([jR],{signal:i.signal,runOnLimitedConnection:!0}),{maxDataLength:4096}).pb(CR);r.log("B sending connect to %p",t.remotePeer);var a=Date.now();yield o.write({type:CR.Type.CONNECT,observedAddresses:r.addressManager.getAddresses().map((e=>e.bytes))},i),r.log("B receiving connect from %p",t.remotePeer);var s=yield o.read(i);if(s.type!==CR.Type.CONNECT)throw r.log("A sent wrong message type"),new ya("DCUtR message type was incorrect");var l=r.getDialableMultiaddrs(s.observedAddresses);if(0===l.length)throw r.log("A did not have any dialable multiaddrs"),new ya("DCUtR connect message had no multiaddrs");var c=Date.now()-a;r.log("A sending sync, rtt %dms",c),yield o.write({type:CR.Type.SYNC,observedAddresses:[]},i),r.log("A waiting for half RTT"),yield BR(c/2),r.log("B dialing",l);var u=yield r.connectionManager.openConnection(l,{signal:i.signal,priority:100,force:!0,initiator:!1});r.log("DCUtR to %p succeeded to address %a, closing relayed connection",t.remotePeer,u.remoteAddr),yield t.close(i);break}catch(t){var d;if(r.log.error("error while attempting DCUtR on attempt %d of %d",n+1,r.retries,t),null===(d=e)||void 0===d||d.abort(t),n===r.retries)throw t}finally{null!=e&&(yield e.close(i))}}}))()}attemptUnilateralConnectionUpgrade(t){var r=this;return e._asyncToGenerator((function*(){var e=(yield r.peerStore.get(t.remotePeer)).addresses.map((e=>{var r=e.multiaddr;return null==r.getPeerId()?r.encapsulate("/p2p/".concat(t.remotePeer)):r})).filter((e=>NR(e,r.transportManager)));if(e.length>0){var n=AbortSignal.timeout(r.timeout);try{r.log("attempting unilateral connection upgrade to %a",e);var i=yield r.connectionManager.openConnection(e,{signal:n,force:!0});if(Qd.exactMatch(i.remoteAddr))throw new Error("Could not open a new, non-limited, connection");return r.log("unilateral connection upgrade to %p succeeded via %a, closing relayed connection",t.remotePeer,i.remoteAddr),yield t.close({signal:n}),!0}catch(n){r.log.error("unilateral connection upgrade to %p on addresses %a failed",t.remotePeer,e,n)}}else r.log("peer %p has no public addresses, not attempting unilateral connection upgrade",t.remotePeer);return!1}))()}handleIncomingUpgrade(t,r){var n=this;return e._asyncToGenerator((function*(){var e={signal:AbortSignal.timeout(n.timeout)};try{var i=Wu(t,{maxDataLength:4096}).pb(CR);n.log("A receiving connect");var o=yield i.read(e);if(o.type!==CR.Type.CONNECT)throw n.log("B sent wrong message type"),new ya("DCUtR message type was incorrect");if(0===o.observedAddresses.length)throw n.log("B sent no multiaddrs"),new ya("DCUtR connect message had no multiaddrs");var a=n.getDialableMultiaddrs(o.observedAddresses);if(0===a.length)throw n.log("B had no dialable multiaddrs"),new ya("DCUtR connect message had no dialable multiaddrs");if(n.log("A sending connect"),yield i.write({type:CR.Type.CONNECT,observedAddresses:n.addressManager.getAddresses().map((e=>e.bytes))}),n.log("A receiving sync"),(yield i.read(e)).type!==CR.Type.SYNC)throw new ya("DCUtR message type was incorrect");n.log("A dialing",a);var s=yield n.connectionManager.openConnection(a,{signal:e.signal,priority:100,force:!0});n.log("DCUtR to %p succeeded via %a, closing relayed connection",r.remotePeer,s.remoteAddr),yield r.close(e)}catch(e){n.log.error("incoming DCUtR from %p failed",r.remotePeer,e),t.abort(e)}finally{yield t.close(e)}}))()}getDialableMultiaddrs(e){var t=[];for(var r of e)if(null!=r&&0!==r.length)try{var n=sr(r);if(!NR(n,this.transportManager))continue;t.push(n)}catch(e){}return t}}var MR,jR="/libp2p/dcutr";function FR(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new LR(t,e)}var UR=null!==(MR=globalThis.CustomEvent)&&void 0!==MR?MR:Event;function zR(e){return VR.apply(this,arguments)}function VR(){return VR=e._wrapAsyncGenerator((function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(n,i){var o=null!==(n=r.concurrency)&&void 0!==n?n:1/0;o<1&&(o=1/0);var a,s=null!==(i=r.ordered)&&void 0!==i&&i,l=new EventTarget,c=[],u=Yc(),d=Yc(),h=!1,p=!1;function f(){var e;return s?null===(e=c[0])||void 0===e?void 0:e.done:Boolean(c.find((e=>e.done)))}function*v(){for(;c.length>0&&c[0].done;){var e=c[0];if(c.shift(),!e.ok)throw p=!0,u.resolve(),e.err;yield e.value,u.resolve()}}function*y(){for(;f();)for(var e=0;e<c.length;e++)if(c[e].done){var t=c[e];if(c.splice(e,1),e--,!t.ok)throw p=!0,u.resolve(),t.err;yield t.value,u.resolve()}}for(l.addEventListener("task-complete",(()=>{d.resolve()})),Promise.resolve().then(e._asyncToGenerator((function*(){try{var r,n=!1,i=!1;try{for(var s,d=function*(){var e=s.value;if(c.length===o&&(u=Yc(),yield u.promise),p)return 1;var t={done:!1};c.push(t),e().then((e=>{t.done=!0,t.ok=!0,t.value=e,l.dispatchEvent(new UR("task-complete"))}),(e=>{t.done=!0,t.err=e,l.dispatchEvent(new UR("task-complete"))}))},f=e._asyncIterator(t);(n=!(s=yield f.next()).done)&&!(yield*d());n=!1);}catch(e){i=!0,r=e}finally{try{n&&null!=f.return&&(yield f.return())}finally{if(i)throw r}}h=!0,l.dispatchEvent(new UR("task-complete"))}catch(e){a=e,l.dispatchEvent(new UR("task-complete"))}})));;){if(f()||(d=Yc(),yield e._awaitAsyncGenerator(d.promise)),null!=a)throw a;if(s?yield*e._asyncGeneratorDelegate(e._asyncIterator(v())):yield*e._asyncGeneratorDelegate(e._asyncIterator(y())),null!=a)throw a;if(h&&0===c.length)break}}()})),VR.apply(this,arguments)}var qR;!function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==r.lengthDelimited&&t.fork(),null!=e.protocolVersion&&(t.uint32(42),t.string(e.protocolVersion)),null!=e.agentVersion&&(t.uint32(50),t.string(e.agentVersion)),null!=e.publicKey&&(t.uint32(10),t.bytes(e.publicKey)),null!=e.listenAddrs)for(var n of e.listenAddrs)t.uint32(18),t.bytes(n);if(null!=e.observedAddr&&(t.uint32(34),t.bytes(e.observedAddr)),null!=e.protocols)for(var i of e.protocols)t.uint32(26),t.string(i);null!=e.signedPeerRecord&&(t.uint32(66),t.bytes(e.signedPeerRecord)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={listenAddrs:[],protocols:[]},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 5:n.protocolVersion=e.string();break;case 6:n.agentVersion=e.string();break;case 1:n.publicKey=e.bytes();break;case 2:var a;if(null!=(null===(a=r.limits)||void 0===a?void 0:a.listenAddrs)&&n.listenAddrs.length===r.limits.listenAddrs)throw new vl('Decode error - map field "listenAddrs" had too many elements');n.listenAddrs.push(e.bytes());break;case 4:n.observedAddr=e.bytes();break;case 3:var s;if(null!=(null===(s=r.limits)||void 0===s?void 0:s.protocols)&&n.protocols.length===r.limits.protocols)throw new vl('Decode error - map field "protocols" had too many elements');n.protocols.push(e.string());break;case 8:n.signedPeerRecord=e.bytes();break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(qR||(qR={}));var HR={protocolPrefix:"ipfs",timeout:5e3,maxInboundStreams:1,maxOutboundStreams:1,maxObservedAddresses:10,maxMessageSize:8192,runOnConnectionOpen:!0,runOnSelfUpdate:!0,runOnLimitedConnection:!0,concurrency:32};function KR(e,t,r,n,i){return WR.apply(this,arguments)}function WR(){return WR=e._asyncToGenerator((function*(e,t,r,n,i){if(r("received identify from %p",n.remotePeer),null==i)throw new ya("message was null or undefined");var o,a={};if(i.listenAddrs.length>0&&(a.addresses=i.listenAddrs.map((e=>({isCertified:!1,multiaddr:sr(e)})))),i.protocols.length>0&&(a.protocols=i.protocols),null!=i.publicKey){var s=zl(i.publicKey);if(!nc(s).equals(n.remotePeer))throw new ya("public key did not match remote PeerId");a.publicKey=s}if(null!=i.signedPeerRecord){r.trace("received signedPeerRecord from %p",n.remotePeer);var l,c=i.signedPeerRecord,u=yield Ru.openAndCertify(c,Fu.DOMAIN),d=Fu.createFromProtobuf(u.payload),h=ac(u.publicKey.toCID());if(!d.peerId.equals(h))throw new ya("signing key does not match PeerId in the PeerRecord");if(!n.remotePeer.equals(d.peerId))throw new ya("signing key does not match remote PeerId");try{l=yield e.get(d.peerId)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=l&&(a.metadata=l.metadata,null!=l.peerRecordEnvelope)){var p=yield Ru.createFromProtobuf(l.peerRecordEnvelope),f=Fu.createFromProtobuf(p.payload);f.seqNumber>=d.seqNumber&&(r("sequence number was lower or equal to existing sequence number - stored: %d received: %d",f.seqNumber,d.seqNumber),d=f,c=l.peerRecordEnvelope)}a.peerRecordEnvelope=c,a.addresses=d.multiaddrs.map((e=>({isCertified:!0,multiaddr:e}))),o={seq:d.seqNumber,addresses:d.multiaddrs}}else r("%p did not send a signed peer record",n.remotePeer);if(r.trace("patching %p with",n.remotePeer,a),yield e.patch(n.remotePeer,a),null!=i.agentVersion||null!=i.protocolVersion){var v={};null!=i.agentVersion&&(v.AgentVersion=ot(i.agentVersion)),null!=i.protocolVersion&&(v.ProtocolVersion=ot(i.protocolVersion)),r.trace("merging %p metadata",n.remotePeer,v),yield e.merge(n.remotePeer,{metadata:v})}var y={peerId:n.remotePeer,protocolVersion:i.protocolVersion,agentVersion:i.agentVersion,publicKey:i.publicKey,listenAddrs:i.listenAddrs.map((e=>sr(e))),observedAddr:null==i.observedAddr?void 0:sr(i.observedAddr),protocols:i.protocols,signedPeerRecord:o,connection:n};return t.safeDispatchEvent("peer:identify",{detail:y}),y})),WR.apply(this,arguments)}class QR{constructor(t,r){var n,i,o,a,s,l,c,u,d;e._defineProperty(this,"host",void 0),e._defineProperty(this,"protocol",void 0),e._defineProperty(this,"started",void 0),e._defineProperty(this,"timeout",void 0),e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"privateKey",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"registrar",void 0),e._defineProperty(this,"addressManager",void 0),e._defineProperty(this,"maxInboundStreams",void 0),e._defineProperty(this,"maxOutboundStreams",void 0),e._defineProperty(this,"maxMessageSize",void 0),e._defineProperty(this,"maxObservedAddresses",void 0),e._defineProperty(this,"events",void 0),e._defineProperty(this,"runOnLimitedConnection",void 0),e._defineProperty(this,"log",void 0),this.protocol=r.protocol,this.started=!1,this.peerId=t.peerId,this.privateKey=t.privateKey,this.peerStore=t.peerStore,this.registrar=t.registrar,this.addressManager=t.addressManager,this.events=t.events,this.log=r.log,this.timeout=null!==(n=r.timeout)&&void 0!==n?n:HR.timeout,this.maxInboundStreams=null!==(i=r.maxInboundStreams)&&void 0!==i?i:HR.maxInboundStreams,this.maxOutboundStreams=null!==(o=r.maxOutboundStreams)&&void 0!==o?o:HR.maxOutboundStreams,this.maxMessageSize=null!==(a=r.maxMessageSize)&&void 0!==a?a:HR.maxMessageSize,this.maxObservedAddresses=null!==(s=r.maxObservedAddresses)&&void 0!==s?s:HR.maxObservedAddresses,this.runOnLimitedConnection=null!==(l=r.runOnLimitedConnection)&&void 0!==l?l:HR.runOnLimitedConnection,this.host={protocolVersion:"".concat(null!==(c=r.protocolPrefix)&&void 0!==c?c:HR.protocolPrefix,"/").concat("0.1.0"),agentVersion:(u=t.nodeInfo,d=r.agentVersion,null!=d?d:u.userAgent)}}isStarted(){return this.started}start(){var t=this;return e._asyncToGenerator((function*(){t.started||(yield t.peerStore.merge(t.peerId,{metadata:{AgentVersion:ot(t.host.agentVersion),ProtocolVersion:ot(t.host.protocolVersion)}}),yield t.registrar.handle(t.protocol,(e=>{t.handleProtocol(e).catch((e=>{t.log.error(e)}))}),{maxInboundStreams:t.maxInboundStreams,maxOutboundStreams:t.maxOutboundStreams,runOnLimitedConnection:t.runOnLimitedConnection}),t.started=!0)}))()}stop(){var t=this;return e._asyncToGenerator((function*(){yield t.registrar.unhandle(t.protocol),t.started=!1}))()}}class YR extends QR{constructor(t){var r,n,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(t,e._objectSpread2(e._objectSpread2({},o),{},{protocol:"/".concat(null!==(r=o.protocolPrefix)&&void 0!==r?r:HR.protocolPrefix,"/").concat("id/push","/").concat("1.0.0"),log:t.logger.forComponent("libp2p:identify-push")})),e._defineProperty(this,"connectionManager",void 0),e._defineProperty(this,"concurrency",void 0),e._defineProperty(this,Ra,["@libp2p/identify-push"]),this.connectionManager=t.connectionManager,this.concurrency=null!==(n=o.concurrency)&&void 0!==n?n:HR.concurrency,(null!==(i=o.runOnSelfUpdate)&&void 0!==i?i:HR.runOnSelfUpdate)&&t.events.addEventListener("self:peer:update",(e=>{this.push().catch((e=>{this.log.error(e)}))}))}push(){var t=this;return e._asyncToGenerator((function*(){var r,n;if(t.isStarted()){var i=t.addressManager.getAddresses().map((e=>e.decapsulateCode(lr("p2p").code))),o=new Fu({peerId:t.peerId,multiaddrs:i}),a=yield Ru.seal(o,t.privateKey),s=t.registrar.getProtocols(),l=yield t.peerStore.get(t.peerId),c=Ze(null!==(r=l.metadata.get("AgentVersion"))&&void 0!==r?r:ot(t.host.agentVersion)),u=Ze(null!==(n=l.metadata.get("ProtocolVersion"))&&void 0!==n?n:ot(t.host.protocolVersion)),d=t;yield Nc(zR(function(){return h.apply(this,arguments)}(),{concurrency:t.concurrency}))}function h(){return(h=e._wrapAsyncGenerator((function*(){var t=function*(t){if(!(yield e._awaitAsyncGenerator(d.peerStore.get(t.remotePeer))).protocols.includes(d.protocol))return 1;yield e._asyncToGenerator((function*(){var e,r=AbortSignal.timeout(d.timeout);try{var n=Wu(e=yield t.newStream(d.protocol,{signal:r,runOnLimitedConnection:d.runOnLimitedConnection}),{maxDataLength:d.maxMessageSize}).pb(qR);yield n.write({listenAddrs:i.map((e=>e.bytes)),signedPeerRecord:a.marshal(),protocols:s,agentVersion:c,protocolVersion:u},{signal:r}),yield e.close({signal:r})}catch(t){var o;d.log.error("could not push identify update to peer",t),null===(o=e)||void 0===o||o.abort(t)}}))};for(var r of d.connectionManager.getConnections())yield*t(r)}))).apply(this,arguments)}}))()}handleProtocol(t){var r=this;return e._asyncToGenerator((function*(){var{connection:e,stream:n}=t;try{if(r.peerId.equals(e.remotePeer))throw new Error("received push from ourselves?");var i={signal:AbortSignal.timeout(r.timeout)},o=Wu(n,{maxDataLength:r.maxMessageSize}).pb(qR),a=yield o.read(i);yield n.close(i),yield KR(r.peerStore,r.events,r.log,e,a)}catch(e){return r.log.error("received invalid message",e),void n.abort(e)}r.log.trace("handled push from %p",e.remotePeer)}))()}}class JR extends QR{constructor(t){var r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(t,e._objectSpread2(e._objectSpread2({},i),{},{protocol:"/".concat(null!==(r=i.protocolPrefix)&&void 0!==r?r:HR.protocolPrefix,"/").concat("id","/").concat("1.0.0"),log:t.logger.forComponent("libp2p:identify")})),e._defineProperty(this,Ra,["@libp2p/identify"]),(null!==(n=i.runOnConnectionOpen)&&void 0!==n?n:HR.runOnConnectionOpen)&&t.events.addEventListener("connection:open",(e=>{var t=e.detail;this.identify(t).catch((e=>{e.name!==va.name&&this.log.error("error during identify trigged by connection:open",e)}))}))}_identify(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i,o=r.length>1&&void 0!==r[1]?r[1]:{};if(null==o.signal){var a=AbortSignal.timeout(n.timeout);o=e._objectSpread2(e._objectSpread2({},o),{},{signal:a})}try{var s=Wu(i=yield t.newStream(n.protocol,e._objectSpread2(e._objectSpread2({},o),{},{runOnLimitedConnection:n.runOnLimitedConnection})),{maxDataLength:n.maxMessageSize}).pb(qR),l=yield s.read(o);return yield i.close(o),l}catch(e){var c;throw null===(c=i)||void 0===c||c.abort(e),e}}))()}identify(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{},i=yield n._identify(t,e),{publicKey:o,protocols:a,observedAddr:s}=i;if(null==o)throw new ya("public key was missing from identify message");var l=ac(zl(o).toCID());if(!t.remotePeer.equals(l))throw new ya("identified peer does not match the expected peer");if(n.peerId.equals(l))throw new ya("identified peer is our own peer id?");return n.maybeAddObservedAddress(s),n.log("identify completed for peer %p and protocols %o",l,a),KR(n.peerStore,n.events,n.log,t,i)}))()}maybeAddObservedAddress(e){var t=function(e){if(null!=e&&e.length>0)try{return sr(e)}catch(e){}}(e);null!=t&&(this.log.trace("our observed address was %a",t),HG(t)?this.log.trace("our observed address was private"):41!==t.stringTuples()[0][0]||VG(t)?Nd.exactMatch(t)||(this.log.trace("storing the observed address"),this.addressManager.addObservedAddr(t)):this.log.trace("our observed address was IPv6 but not a global unicast address"))}handleProtocol(t){var r=this;return e._asyncToGenerator((function*(){var{connection:e,stream:n}=t,i=AbortSignal.timeout(r.timeout);try{var o=yield r.peerStore.get(r.peerId),a=r.addressManager.getAddresses().map((e=>e.decapsulateCode(lr("p2p").code))),s=o.peerRecordEnvelope;if(a.length>0&&null==s){var l=new Fu({peerId:r.peerId,multiaddrs:a});s=(yield Ru.seal(l,r.privateKey)).marshal().subarray()}var c=e.remoteAddr.bytes;kd.matches(e.remoteAddr)||(c=void 0);var u=Wu(n).pb(qR);yield u.write({protocolVersion:r.host.protocolVersion,agentVersion:r.host.agentVersion,publicKey:ql(r.privateKey.publicKey),listenAddrs:a.map((e=>e.bytes)),signedPeerRecord:s,observedAddr:c,protocols:o.protocols},{signal:i}),yield n.close({signal:i})}catch(e){r.log.error("could not respond to identify request",e),n.abort(e)}}))()}}function ZR(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new JR(t,e)}function $R(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new YR(t,e)}var XR,eO,tO,rO,nO,iO,oO,aO,sO=36e5,lO=36*sO,cO=48*sO,uO=sO,dO="".concat(Yo,"-kad-dht");function hO(e){var t=e.getUTCFullYear(),r=String(e.getUTCMonth()+1).padStart(2,"0"),n=String(e.getUTCDate()).padStart(2,"0"),i=String(e.getUTCHours()).padStart(2,"0"),o=String(e.getUTCMinutes()).padStart(2,"0"),a=String(e.getUTCSeconds()).padStart(2,"0"),s=e.getUTCMilliseconds(),l=String(1e3*s*1e3).padStart(9,"0");return"".concat(t,"-").concat(r,"-").concat(n,"T").concat(i,":").concat(o,":").concat(a,".").concat(l,"Z")}!function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.key&&e.key.byteLength>0&&(t.uint32(10),t.bytes(e.key)),null!=e.value&&e.value.byteLength>0&&(t.uint32(18),t.bytes(e.value)),null!=e.timeReceived&&""!==e.timeReceived&&(t.uint32(42),t.string(e.timeReceived)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={key:He(0),value:He(0),timeReceived:""},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.key=e.bytes();break;case 2:r.value=e.bytes();break;case 5:r.timeReceived=e.string();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(XR||(XR={}));class pO{constructor(t,r,n){if(e._defineProperty(this,"key",void 0),e._defineProperty(this,"value",void 0),e._defineProperty(this,"timeReceived",void 0),!(t instanceof Uint8Array))throw new Error("key must be a Uint8Array");if(!(r instanceof Uint8Array))throw new Error("value must be a Uint8Array");this.key=t,this.value=r,this.timeReceived=n}serialize(){return XR.encode(this.prepareSerialize())}prepareSerialize(){return{key:this.key,value:this.value,timeReceived:hO(this.timeReceived)}}static deserialize(e){var t=XR.decode(e);return new pO(t.key,t.value,new Date(t.timeReceived))}static fromDeserialized(e){var t=function(e){var t=new RegExp("(\\d{4})-(\\d{2})-(\\d{2})T(\\d{2}):(\\d{2}):(\\d{2})\\.(\\d+)Z"),r=String(e).trim().match(t);if(null==r)throw new Error("Invalid format");var n=parseInt(r[1],10),i=parseInt(r[2],10)-1,o=parseInt(r[3],10),a=parseInt(r[4],10),s=parseInt(r[5],10),l=parseInt(r[6],10),c=parseInt(r[7].slice(0,-6),10);return new Date(Date.UTC(n,i,o,a,s,l,c))}(e.timeReceived);if(null==e.key)throw new Error("key missing from deserialized object");if(null==e.value)throw new Error("value missing from deserialized object");return new pO(e.key,e.value,t)}}class fO extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Query error"),this.name="QueryError"}}class vO extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Query aborted"),this.name="QueryAbortedError"}}class yO extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid record"),this.name="InvalidRecordError"}}class gO extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No selector function configured for prefix"),this.name="MissingSelectorError"}}function mO(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=e._objectSpread2(e._objectSpread2({},t),{},{name:"SEND_QUERY",type:0,messageName:t.type,messageType:t.type});return null===(r=n.onProgress)||void 0===r||r.call(n,new CustomEvent("kad-dht:query:send-query",{detail:i})),i}function wO(t){var r,n,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=e._objectSpread2(e._objectSpread2({},t),{},{name:"PEER_RESPONSE",type:1,messageName:t.messageType,closer:null!==(r=t.closer)&&void 0!==r?r:[],providers:null!==(n=t.providers)&&void 0!==n?n:[]});return null===(i=o.onProgress)||void 0===i||i.call(o,new CustomEvent("kad-dht:query:peer-response",{detail:a})),a}function bO(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=e._objectSpread2(e._objectSpread2({},t),{},{name:"FINAL_PEER",type:2});return null===(r=n.onProgress)||void 0===r||r.call(n,new CustomEvent("kad-dht:query:final-peer",{detail:i})),i}function _O(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=e._objectSpread2(e._objectSpread2({},t),{},{name:"QUERY_ERROR",type:3});return null===(r=n.onProgress)||void 0===r||r.call(n,new CustomEvent("kad-dht:query:query-error",{detail:i})),i}function SO(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=e._objectSpread2(e._objectSpread2({},t),{},{name:"PROVIDER",type:4});return null===(r=n.onProgress)||void 0===r||r.call(n,new CustomEvent("kad-dht:query:provider",{detail:i})),i}function PO(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=e._objectSpread2(e._objectSpread2({},t),{},{name:"VALUE",type:5});return null===(r=n.onProgress)||void 0===r||r.call(n,new CustomEvent("kad-dht:query:value",{detail:i})),i}function EO(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=e._objectSpread2(e._objectSpread2({},t),{},{name:"DIAL_PEER",type:7});return null===(r=n.onProgress)||void 0===r||r.call(n,new CustomEvent("kad-dht:query:dial-peer",{detail:i})),i}!function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.key&&(t.uint32(10),t.bytes(e.key)),null!=e.value&&(t.uint32(18),t.bytes(e.value)),null!=e.author&&(t.uint32(26),t.bytes(e.author)),null!=e.signature&&(t.uint32(34),t.bytes(e.signature)),null!=e.timeReceived&&(t.uint32(42),t.string(e.timeReceived)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.key=e.bytes();break;case 2:r.value=e.bytes();break;case 3:r.author=e.bytes();break;case 4:r.signature=e.bytes();break;case 5:r.timeReceived=e.string();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(eO||(eO={})),function(e){e.PUT_VALUE="PUT_VALUE",e.GET_VALUE="GET_VALUE",e.ADD_PROVIDER="ADD_PROVIDER",e.GET_PROVIDERS="GET_PROVIDERS",e.FIND_NODE="FIND_NODE",e.PING="PING"}(tO||(tO={})),function(e){e[e.PUT_VALUE=0]="PUT_VALUE",e[e.GET_VALUE=1]="GET_VALUE",e[e.ADD_PROVIDER=2]="ADD_PROVIDER",e[e.GET_PROVIDERS=3]="GET_PROVIDERS",e[e.FIND_NODE=4]="FIND_NODE",e[e.PING=5]="PING"}(rO||(rO={})),function(e){e.codec=()=>pl(rO)}(tO||(tO={})),function(e){e.NOT_CONNECTED="NOT_CONNECTED",e.CONNECTED="CONNECTED",e.CAN_CONNECT="CAN_CONNECT",e.CANNOT_CONNECT="CANNOT_CONNECT"}(nO||(nO={})),function(e){e[e.NOT_CONNECTED=0]="NOT_CONNECTED",e[e.CONNECTED=1]="CONNECTED",e[e.CAN_CONNECT=2]="CAN_CONNECT",e[e.CANNOT_CONNECT=3]="CANNOT_CONNECT"}(iO||(iO={})),function(e){e.codec=()=>pl(iO)}(nO||(nO={})),function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==r.lengthDelimited&&t.fork(),null!=e.id&&e.id.byteLength>0&&(t.uint32(10),t.bytes(e.id)),null!=e.multiaddrs)for(var n of e.multiaddrs)t.uint32(18),t.bytes(n);null!=e.connection&&(t.uint32(24),nO.codec().encode(e.connection,t)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={id:He(0),multiaddrs:[]},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:n.id=e.bytes();break;case 2:var a;if(null!=(null===(a=r.limits)||void 0===a?void 0:a.multiaddrs)&&n.multiaddrs.length===r.limits.multiaddrs)throw new vl('Decode error - map field "multiaddrs" had too many elements');n.multiaddrs.push(e.bytes());break;case 3:n.connection=nO.codec().decode(e);break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(oO||(oO={})),function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==r.lengthDelimited&&t.fork(),null!=e.type&&0!==rO[e.type]&&(t.uint32(8),tO.codec().encode(e.type,t)),null!=e.clusterLevel&&(t.uint32(80),t.int32(e.clusterLevel)),null!=e.key&&(t.uint32(18),t.bytes(e.key)),null!=e.record&&(t.uint32(26),t.bytes(e.record)),null!=e.closer)for(var n of e.closer)t.uint32(66),oO.codec().encode(n,t);if(null!=e.providers)for(var i of e.providers)t.uint32(74),oO.codec().encode(i,t);!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={type:tO.PUT_VALUE,closer:[],providers:[]},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:n.type=tO.codec().decode(e);break;case 10:n.clusterLevel=e.int32();break;case 2:n.key=e.bytes();break;case 3:n.record=e.bytes();break;case 8:var a,s;if(null!=(null===(a=r.limits)||void 0===a?void 0:a.closer)&&n.closer.length===r.limits.closer)throw new vl('Decode error - map field "closer" had too many elements');n.closer.push(oO.codec().decode(e,e.uint32(),{limits:null===(s=r.limits)||void 0===s?void 0:s.closer$}));break;case 9:var l,c;if(null!=(null===(l=r.limits)||void 0===l?void 0:l.providers)&&n.providers.length===r.limits.providers)throw new vl('Decode error - map field "providers" had too many elements');n.providers.push(oO.codec().decode(e,e.uint32(),{limits:null===(c=r.limits)||void 0===c?void 0:c.providers$}));break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(aO||(aO={}));var AO={pk:function(e,t){return 0}};function kO(e,t){return xO.apply(this,arguments)}function xO(){return xO=e._asyncToGenerator((function*(e,t){var r=t.key,n=Ze(r).split("/");if(!(n.length<3)){var i=e[n[1].toString()];if(null==i)throw new ea('No validator available for key type "'.concat(n[1],'"'));yield i(r,t.value)}})),xO.apply(this,arguments)}var TO=function(){var t=e._asyncToGenerator((function*(e,t){if(!(e instanceof Uint8Array))throw new ea('"key" must be a Uint8Array');if(e.byteLength<5)throw new ea("Invalid public key record");if("/pk/"!==Ze(e.subarray(0,4)))throw new ea("key was not prefixed with /pk/");var r=zl(t);if(!nt(e.slice(4),r.toMultihash().bytes))throw new ea("public key does not match passed in key")}));return function(e,r){return t.apply(this,arguments)}}(),IO={pk:TO},CO=ot("/pk/");function BO(t){return e._objectSpread2(e._objectSpread2({},t),{},{multiaddrs:t.multiaddrs.filter((e=>{var[[t,r]]=e.stringTuples();if(53===t||54===t||55===t)return"localhost"!==r;if(4!==t&&6!==t)return!1;if(null==r)return!1;var n=CN(r);return null==n||!n}))})}function NO(e){return DO.apply(this,arguments)}function DO(){return DO=e._asyncToGenerator((function*(e){return(yield De.digest(e)).digest})),DO.apply(this,arguments)}function GO(e){return RO.apply(this,arguments)}function RO(){return RO=e._asyncToGenerator((function*(e){return NO(e.toMultihash().bytes)})),RO.apply(this,arguments)}function OO(e,t){return new Bc("".concat(e,"/").concat(Ze(t,"base32")),!1)}function LO(e,t){var r=new Date;return new pO(e,t,r).serialize()}function MO(e){var t=e.toString().split("/"),r=t.pop(),n=t.pop();if(null==r||null==n)throw new Error("incorrectly formatted provider entry key in datastore: ".concat(e.toString()));return{cid:je.createV1(re,Ae(ot(n,"base32"))),peerId:rc(r)}}function jO(e,t,r){var n=[e,"string"==typeof t?t:Ze(t.multihash.bytes,"base32")];return null!=r&&n.push(r.toString()),new Bc(n.join("/"))}function FO(e){return new Date(bt(e))}function UO(t,r,n){return e._wrapAsyncGenerator((function*(){var i,o,a=null===(i=r.queryTime)||void 0===i?void 0:i.timer(n),s=null===(o=r.errorTime)||void 0===o?void 0:o.timer(n),l=!1;try{var c;null===(c=r.queries)||void 0===c||c.increment({[n]:!0}),yield*e._asyncGeneratorDelegate(e._asyncIterator(t(...arguments)),e._awaitAsyncGenerator)}catch(e){var u;throw l=!0,null==s||s(),null===(u=r.errors)||void 0===u||u.increment({[n]:!0}),e}finally{var d;null===(d=r.queries)||void 0===d||d.decrement({[n]:!0}),l||null==a||a()}}))}function zO(t,r,n){return e._asyncToGenerator((function*(){var e,i,o=null==r||null===(e=r.queryTime)||void 0===e?void 0:e.timer(n),a=null==r||null===(i=r.errorTime)||void 0===i?void 0:i.timer(n),s=!1;try{var l;return null===(l=r.queries)||void 0===l||l.increment({[n]:!0}),yield t(...arguments)}catch(e){var c;throw s=!0,null==a||a(),null===(c=r.errors)||void 0===c||c.increment({[n]:!0}),e}finally{var u;null===(u=r.queries)||void 0===u||u.decrement({[n]:!0}),s||null==o||o()}}))}class VO{constructor(t,r){var n,i,o,a;e._defineProperty(this,"log",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"validators",void 0),e._defineProperty(this,"selectors",void 0),e._defineProperty(this,"peerRouting",void 0),e._defineProperty(this,"queryManager",void 0),e._defineProperty(this,"network",void 0),e._defineProperty(this,"datastorePrefix",void 0);var{validators:s,selectors:l,peerRouting:c,queryManager:u,network:d,logPrefix:h}=r;this.components=t,this.log=t.logger.forComponent("".concat(h,":content-fetching")),this.datastorePrefix="".concat(r.datastorePrefix,"/record"),this.validators=s,this.selectors=l,this.peerRouting=c,this.queryManager=u,this.network=d,this.get=null!==(n=null===(i=t.metrics)||void 0===i?void 0:i.traceFunction("libp2p.kadDHT.get",this.get.bind(this),{optionsIndex:1}))&&void 0!==n?n:this.get,this.put=null!==(o=null===(a=t.metrics)||void 0===a?void 0:a.traceFunction("libp2p.kadDHT.put",this.put.bind(this),{optionsIndex:2}))&&void 0!==o?o:this.put}getLocal(t){var r=this;return e._asyncToGenerator((function*(){r.log("getLocal %b",t);var e=OO(r.datastorePrefix,t);r.log("fetching record for key %k",e);var n=yield r.components.datastore.get(e);r.log("found %k in local datastore",e);var i=pO.deserialize(n);return yield kO(r.validators,i),i}))()}sendCorrectionRecord(t,r,n){var i=this;return e._wrapAsyncGenerator((function(t,r,n){var o=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{};return function*(){i.log("sendCorrection for %b",t);var a=LO(t,n);for(var{value:s,from:l}of r)if(nt(s,n))i.log("record was ok");else if(i.components.peerId.equals(l))try{var c=OO(i.datastorePrefix,t);i.log("Storing corrected record for key ".concat(c.toString())),yield e._awaitAsyncGenerator(i.components.datastore.put(c,a.subarray()))}catch(e){i.log.error("Failed error correcting self",e)}else{var u,d=!1,h={type:tO.PUT_VALUE,key:t,record:a},p=!1,f=!1;try{for(var v,y=e._asyncIterator(i.network.sendRequest(l,h,o));p=!(v=yield e._awaitAsyncGenerator(y.next())).done;p=!1){var g=v.value;"PEER_RESPONSE"===g.name&&null!=g.record&&nt(g.record.value,pO.deserialize(a).value)&&(d=!0),yield g}}catch(e){f=!0,u=e}finally{try{p&&null!=y.return&&(yield e._awaitAsyncGenerator(y.return()))}finally{if(f)throw u}}d||(yield _O({from:l,error:new fO("Value not put correctly")},o)),i.log.error("Failed error correcting entry")}}()})).apply(this,arguments)}put(t,r){var n=this;return e._wrapAsyncGenerator((function(t,r){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){n.log("put key %b value %b",t,r);var o=LO(t,r),a=OO(n.datastorePrefix,t);n.log("storing record for key ".concat(a.toString())),yield e._awaitAsyncGenerator(n.components.datastore.put(a,o.subarray())),yield*e._asyncGeneratorDelegate(e._asyncIterator(lu(n.peerRouting.getClosestPeers(t,e._objectSpread2(e._objectSpread2({},i),{},{signal:i.signal})),(r=>Qc(r,(r=>e._asyncToGenerator((function*(){if("FINAL_PEER"!==r.name)return[r];var a=[],s={type:tO.PUT_VALUE,key:t,record:o};n.log("send put to %p",r.peer.id);var l,c=!1,u=!1;try{for(var d,h=e._asyncIterator(n.network.sendRequest(r.peer.id,s,i));c=!(d=yield h.next()).done;c=!1){var p=d.value;(a.push(p),"PEER_RESPONSE"===p.name)&&(null!=p.record&&nt(p.record.value,pO.deserialize(o).value)||a.push(_O({from:r.peer.id,error:new fO("Value not put correctly")},i)))}}catch(e){u=!0,l=e}finally{try{c&&null!=h.return&&(yield h.return())}finally{if(u)throw l}}return a}))))),(e=>zR(e,{ordered:!1,concurrency:3})),function(){var t=e._wrapAsyncGenerator((function*(t){var r,n=!1,i=!1;try{for(var o,a=e._asyncIterator(t);n=!(o=yield e._awaitAsyncGenerator(a.next())).done;n=!1){var s=o.value;yield*e._asyncGeneratorDelegate(e._asyncIterator(s),e._awaitAsyncGenerator)}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield e._awaitAsyncGenerator(a.return()))}finally{if(i)throw r}}}));return function(e){return t.apply(this,arguments)}}())))}()})).apply(this,arguments)}get(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){r.log("get %b",t);var i,o=[],a=!1,s=!1;try{for(var l,c=e._asyncIterator(r.getMany(t,n));a=!(l=yield e._awaitAsyncGenerator(c.next())).done;a=!1){var u=l.value;"VALUE"===u.name&&o.push(u),yield u}}catch(e){s=!0,i=e}finally{try{a&&null!=c.return&&(yield e._awaitAsyncGenerator(c.return()))}finally{if(s)throw i}}if(0!==o.length){var d=o.map((e=>e.value)),h=0;try{h=function(e,t,r){if(0===r.length)throw new ea("No records given");var n=Ze(t).split("/");if(n.length<3)throw new ea("Record key does not have a selector function");var i=e[n[1].toString()];if(null==i)throw new gO('No selector function configured for key type "'.concat(n[1],'"'));return 1===r.length?0:i(t,r)}(r.selectors,t,d)}catch(e){if("InvalidParametersError"!==e.name)throw e}var p=d[h];if(r.log("GetValue %b %b",t,p),null==p)throw new ua("Best value was not found");yield*e._asyncGeneratorDelegate(e._asyncIterator(r.sendCorrectionRecord(t,o,p,n))),yield o[h]}}()})).apply(this,arguments)}getMany(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){r.log("getMany values for %b",t);try{var i=yield e._awaitAsyncGenerator(r.getLocal(t));yield PO({value:i.value,from:r.components.peerId},n)}catch(e){r.log("error getting local value for %b",t,e)}var o=r,a=function(){var r=e._wrapAsyncGenerator((function(r){var{peer:i,signal:a}=r;return function*(){var r,s=!1,l=!1;try{for(var c,u=e._asyncIterator(o.peerRouting.getValueOrPeers(i,t,e._objectSpread2(e._objectSpread2({},n),{},{signal:a})));s=!(c=yield e._awaitAsyncGenerator(u.next())).done;s=!1){var d=c.value;yield d,"PEER_RESPONSE"===d.name&&null!=d.record&&(yield PO({from:i,value:d.record.value},n))}}catch(e){l=!0,r=e}finally{try{s&&null!=u.return&&(yield e._awaitAsyncGenerator(u.return()))}finally{if(l)throw r}}}()}));return function(e){return r.apply(this,arguments)}}();yield*e._asyncGeneratorDelegate(e._asyncIterator(r.queryManager.run(t,a,n)))}()})).apply(this,arguments)}}function qO(e){var t;if(null==e.id)throw new Error("Invalid peer in message");return{id:oc(Ae(e.id)),multiaddrs:(null!==(t=e.multiaddrs)&&void 0!==t?t:[]).map((e=>sr(e)))}}class HO{constructor(t,r){var n,i,o,a;e._defineProperty(this,"log",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"network",void 0),e._defineProperty(this,"peerRouting",void 0),e._defineProperty(this,"queryManager",void 0),e._defineProperty(this,"routingTable",void 0),e._defineProperty(this,"providers",void 0);var{network:s,peerRouting:l,queryManager:c,routingTable:u,providers:d,logPrefix:h}=r;this.components=t,this.log=t.logger.forComponent("".concat(h,":content-routing")),this.network=s,this.peerRouting=l,this.queryManager=c,this.routingTable=u,this.providers=d,this.findProviders=null!==(n=null===(i=t.metrics)||void 0===i?void 0:i.traceFunction("libp2p.kadDHT.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromYieldedValue:(e,t)=>{var r;"PROVIDER"===e.name&&(null!==(r=t.providers)&&void 0!==r||(t.providers=[]),t.providers.push(...e.providers.map((e=>e.id.toString()))));return t}}))&&void 0!==n?n:this.findProviders,this.provide=null!==(o=null===(a=t.metrics)||void 0===a?void 0:a.traceFunction("libp2p.kadDHT.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromYieldedValue:(e,t)=>{var r;"PEER_RESPONSE"===e.name&&"ADD_PROVIDER"===e.messageName&&(null!==(r=t.providers)&&void 0!==r||(t.providers=[]),t.providers.push(e.from.toString()));return t}}))&&void 0!==o?o:this.provide}provide(t,r){var n=this;return e._wrapAsyncGenerator((function(t,r){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){n.log("provide %s",t);var o=t.multihash.bytes;yield e._awaitAsyncGenerator(n.providers.addProvider(t,n.components.peerId));var a,s,l,c,u={type:tO.ADD_PROVIDER,key:o,providers:[(a={id:n.components.peerId,multiaddrs:r},c={id:a.id.toMultihash().bytes,multiaddrs:(null!==(l=a.multiaddrs)&&void 0!==l?l:[]).map((e=>e.bytes)),connection:s},c)]},d=0;yield*e._asyncGeneratorDelegate(e._asyncIterator(lu(n.peerRouting.getClosestPeers(o,i),(r=>Qc(r,(r=>(r=>e._asyncToGenerator((function*(){if("FINAL_PEER"!==r.name)return[r];var o=[];n.log("putProvider %s to %p",t,r.peer.id);try{n.log("sending provider record for %s to %p",t,r.peer.id);var a,s=!1,l=!1;try{for(var c,h=e._asyncIterator(n.network.sendMessage(r.peer.id,u,i));s=!(c=yield h.next()).done;s=!1){var p=c.value;"PEER_RESPONSE"===p.name&&(n.log("sent provider record for %s to %p",t,r.peer.id),d++),o.push(p)}}catch(e){l=!0,a=e}finally{try{s&&null!=h.return&&(yield h.return())}finally{if(l)throw a}}}catch(e){n.log.error("error sending provide record to peer %p",r.peer.id,e),o.push(_O({from:r.peer.id,error:e},i))}return o})))(r)))),(e=>zR(e,{ordered:!1,concurrency:3})),function(){var t=e._wrapAsyncGenerator((function*(t){var r,n=!1,i=!1;try{for(var o,a=e._asyncIterator(t);n=!(o=yield e._awaitAsyncGenerator(a.next())).done;n=!1){var s=o.value;yield*e._asyncGeneratorDelegate(e._asyncIterator(s),e._awaitAsyncGenerator)}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield e._awaitAsyncGenerator(a.return()))}finally{if(i)throw r}}}));return function(e){return t.apply(this,arguments)}}()))),n.log("sent provider records to %d peers",d)}()})).apply(this,arguments)}findProviders(t,r){var n=this;return e._wrapAsyncGenerator((function*(){var i=n.routingTable.kBucketSize,o=0,a=t.multihash.bytes,s=n;n.log("findProviders %c",t);var l=yield e._awaitAsyncGenerator(n.providers.getProviders(t));if(l.length>0){var c=[];for(var u of l.slice(0,i))try{var d=yield e._awaitAsyncGenerator(n.components.peerStore.get(u));c.push({id:u,multiaddrs:d.addresses.map((e=>{var{multiaddr:t}=e;return t}))})}catch(e){if("NotFoundError"!==e.name)throw e;n.log("no peer store entry for %p",u)}if(yield wO({from:n.components.peerId,messageType:tO.GET_PROVIDERS,providers:c},r),yield SO({from:n.components.peerId,providers:c},r),(o+=c.length)>=i)return}var h,p=function(){var t=e._wrapAsyncGenerator((function(t){var{peer:n,signal:i}=t;return function*(){var t={type:tO.GET_PROVIDERS,key:a};yield*e._asyncGeneratorDelegate(e._asyncIterator(s.network.sendRequest(n,t,e._objectSpread2(e._objectSpread2({},r),{},{signal:i}))))}()}));return function(e){return t.apply(this,arguments)}}(),f=new ch(l),v=!1,y=!1;try{for(var g,m=e._asyncIterator(n.queryManager.run(a,p,r));v=!(g=yield e._awaitAsyncGenerator(m.next())).done;v=!1){var w=g.value;if(yield w,"PEER_RESPONSE"===w.name){n.log("Found %d provider entries for %c and %d closer peers",w.providers.length,t,w.closer.length);var b=[];for(var _ of w.providers)f.has(_.id)||(f.add(_.id),b.push(_));if(b.length>0&&(yield SO({from:w.from,providers:b},r),(o+=b.length)>=i))return}}}catch(e){y=!0,h=e}finally{try{v&&null!=m.return&&(yield e._awaitAsyncGenerator(m.return()))}finally{if(y)throw h}}}))()}}class KO{constructor(t){e._defineProperty(this,"movingAverage",void 0),e._defineProperty(this,"variance",void 0),e._defineProperty(this,"deviation",void 0),e._defineProperty(this,"forecast",void 0),e._defineProperty(this,"timeSpan",void 0),e._defineProperty(this,"previousTime",void 0),this.timeSpan=t,this.movingAverage=0,this.variance=0,this.deviation=0,this.forecast=0}alpha(e,t){return 1-Math.exp(-(e-t)/this.timeSpan)}push(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:Date.now();if(null!=this.previousTime){var r=this.alpha(t,this.previousTime),n=e-this.movingAverage,i=r*n;this.movingAverage=r*e+(1-r)*this.movingAverage,this.variance=(1-r)*(this.variance+n*i),this.deviation=Math.sqrt(this.variance),this.forecast=this.movingAverage+r*n}else this.movingAverage=e;this.previousTime=t}}class WO{constructor(){var t,r,n,i,o,a,s,l=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};(e._defineProperty(this,"success",void 0),e._defineProperty(this,"failure",void 0),e._defineProperty(this,"next",void 0),e._defineProperty(this,"metric",void 0),e._defineProperty(this,"timeoutMultiplier",void 0),e._defineProperty(this,"failureMultiplier",void 0),e._defineProperty(this,"minTimeout",void 0),this.success=new KO(null!==(t=l.interval)&&void 0!==t?t:5e3),this.failure=new KO(null!==(r=l.interval)&&void 0!==r?r:5e3),this.next=new KO(null!==(n=l.interval)&&void 0!==n?n:5e3),this.failureMultiplier=null!==(i=l.failureMultiplier)&&void 0!==i?i:2,this.timeoutMultiplier=null!==(o=l.timeoutMultiplier)&&void 0!==o?o:1.2,this.minTimeout=null!==(a=l.minTimeout)&&void 0!==a?a:5e3,null!=l.metricName)&&(this.metric=null===(s=l.metrics)||void 0===s?void 0:s.registerMetricGroup(l.metricName))}getTimeoutSignal(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r=Math.max(Math.round(this.next.movingAverage*(null!==(e=t.timeoutFactor)&&void 0!==e?e:this.timeoutMultiplier)),this.minTimeout),n=AbortSignal.timeout(r),i=$d([t.signal,n]);return i.start=Date.now(),i.timeout=r,i}cleanUp(e){var t,r,n=Date.now()-e.start;e.aborted?(this.failure.push(n),this.next.push(n*this.failureMultiplier),null===(t=this.metric)||void 0===t||t.update({failureMovingAverage:this.failure.movingAverage,failureDeviation:this.failure.deviation,failureForecast:this.failure.forecast,failureVariance:this.failure.variance,failure:n})):(this.success.push(n),this.next.push(n),null===(r=this.metric)||void 0===r||r.update({successMovingAverage:this.success.movingAverage,successDeviation:this.success.deviation,successForecast:this.success.forecast,successVariance:this.success.variance,success:n}))}}class QO{constructor(){e._defineProperty(this,"readNext",void 0),e._defineProperty(this,"haveNext",void 0),e._defineProperty(this,"ended",void 0),e._defineProperty(this,"nextResult",void 0),this.ended=!1,this.readNext=Yc(),this.haveNext=Yc()}[Symbol.asyncIterator](){return this}next(){var t=this;return e._asyncToGenerator((function*(){if(null==t.nextResult&&(yield t.haveNext.promise),null==t.nextResult)throw new Error("HaveNext promise resolved but nextResult was undefined");var e=t.nextResult;return t.nextResult=void 0,t.readNext.resolve(),t.readNext=Yc(),e}))()}throw(t){var r=this;return e._asyncToGenerator((function*(){return r.ended=!0,null!=t&&(r.haveNext.promise.catch((()=>{})),r.haveNext.reject(t)),{done:!0,value:void 0}}))()}return(){var t=this;return e._asyncToGenerator((function*(){var e={done:!0,value:void 0};return t.ended=!0,t.nextResult=e,t.haveNext.resolve(),e}))()}push(t,r){var n=this;return e._asyncToGenerator((function*(){yield n._push(t,r)}))()}end(t,r){var n=this;return e._asyncToGenerator((function*(){null!=t?yield n.throw(t):yield n._push(void 0,r)}))()}_push(t,r){var n=this;return e._asyncToGenerator((function*(){if(null!=t&&n.ended)throw new Error("Cannot push value onto an ended pushable");for(;null!=n.nextResult;)yield n.readNext.promise;null!=t?n.nextResult={done:!1,value:t}:(n.ended=!0,n.nextResult={done:!0,value:void 0}),n.haveNext.resolve(),n.haveNext=Yc(),yield tu(n.readNext.promise,null==r?void 0:r.signal,r)}))()}}class YO extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","UnexpectedEOFError"),e._defineProperty(this,"code","ERR_UNEXPECTED_EOF")}}class JO extends Error{constructor(t,r){super(t),e._defineProperty(this,"code",void 0),this.code=r}}let ZO=class extends JO{constructor(t){super(t,"ABORT_ERR"),e._defineProperty(this,"type",void 0),this.type="aborted",this.name="AbortError"}};function $O(t,r){var n=new QO;t.sink(n).catch(function(){var t=e._asyncToGenerator((function*(e){yield n.end(e)}));return function(e){return t.apply(this,arguments)}}()),t.sink=function(){var t=e._asyncToGenerator((function*(t){var r,i=!1,o=!1;try{for(var a,s=e._asyncIterator(t);i=!(a=yield s.next()).done;i=!1){var l=a.value;yield n.push(l)}}catch(e){o=!0,r=e}finally{try{i&&null!=s.return&&(yield s.return())}finally{if(o)throw r}}yield n.end()}));return function(e){return t.apply(this,arguments)}}();var i=t.source;null!=t.source[Symbol.iterator]?i=t.source[Symbol.iterator]():null!=t.source[Symbol.asyncIterator]&&(i=t.source[Symbol.asyncIterator]());var o,a=new Fa,s={read:function(){var t=e._asyncToGenerator((function*(e,t){var r,n;null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted();var o=new Promise(((e,r)=>{var i;n=()=>{r(new ZO("Read aborted"))},null==t||null===(i=t.signal)||void 0===i||i.addEventListener("abort",n)}));try{if(null==e){var{done:s,value:l}=yield Promise.race([i.next(),o]);return!0===s?new Fa:l}for(;a.byteLength<e;){var{value:c,done:u}=yield Promise.race([i.next(),o]);if(!0===u)throw new YO("unexpected end of input");a.append(c)}var d=a.sublist(0,e);return a.consume(e),d}finally{var h;if(null!=n)null==t||null===(h=t.signal)||void 0===h||h.removeEventListener("abort",n)}}));return function(e,r){return t.apply(this,arguments)}}(),write:(o=e._asyncToGenerator((function*(e,t){var r;null==t||null===(r=t.signal)||void 0===r||r.throwIfAborted(),e instanceof Uint8Array?yield n.push(e,t):yield n.push(e.subarray(),t)})),function(e,t){return o.apply(this,arguments)}),unwrap:()=>{if(a.byteLength>0){var n=t.source;t.source=e._wrapAsyncGenerator((function*(){!1===(null==r?void 0:r.yieldBytes)?yield a:yield*e._asyncGeneratorDelegate(e._asyncIterator(a)),yield*e._asyncGeneratorDelegate(e._asyncIterator(n))}))()}return t}};return s}class XO extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidMessageLengthError"),e._defineProperty(this,"code","ERR_INVALID_MSG_LENGTH")}}class eL extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidDataLengthError"),e._defineProperty(this,"code","ERR_MSG_DATA_TOO_LONG")}}class tL extends Error{constructor(){super(...arguments),e._defineProperty(this,"name","InvalidDataLengthLengthError"),e._defineProperty(this,"code","ERR_MSG_LENGTH_TOO_LONG")}}function rL(t,r){var n,i=function(t){var r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=$O(t,i);null!=i.maxDataLength&&null==i.maxLengthLength&&(i.maxLengthLength=yt(i.maxDataLength));var a,s=null!==(r=null==i?void 0:i.lengthDecoder)&&void 0!==r?r:bt,l=null!==(n=null==i?void 0:i.lengthEncoder)&&void 0!==n?n:wt,c={read:function(){var t=e._asyncToGenerator((function*(e){for(var t=-1,r=new Fa;;){r.append(yield o.read(1,e));try{t=s(r)}catch(e){if(e instanceof RangeError)continue;throw e}if(t<0)throw new XO("Invalid message length");if(null!=(null==i?void 0:i.maxLengthLength)&&r.byteLength>i.maxLengthLength)throw new tL("message length length too long");if(t>-1)break}if(null!=(null==i?void 0:i.maxDataLength)&&t>i.maxDataLength)throw new eL("message length too long");return o.read(t,e)}));return function(e){return t.apply(this,arguments)}}(),write:function(){var t=e._asyncToGenerator((function*(e,t){yield o.write(new Fa(l(e.byteLength),e),t)}));return function(e,r){return t.apply(this,arguments)}}(),writeV:(a=e._asyncToGenerator((function*(e,t){var r=new Fa(...e.flatMap((e=>[l(e.byteLength),e])));yield o.write(r,t)})),function(e,t){return a.apply(this,arguments)}),unwrap:()=>o.unwrap()};return c}(t,r),o={read:function(){var t=e._asyncToGenerator((function*(e,t){var r=yield i.read(t);return e.decode(r)}));return function(e,r){return t.apply(this,arguments)}}(),write:function(){var t=e._asyncToGenerator((function*(e,t,r){yield i.write(t.encode(e),r)}));return function(e,r,n){return t.apply(this,arguments)}}(),writeV:(n=e._asyncToGenerator((function*(e,t,r){yield i.writeV(e.map((e=>t.encode(e))),r)})),function(e,t,r){return n.apply(this,arguments)}),pb:t=>{return{read:(i=e._asyncToGenerator((function*(e){return o.read(t,e)})),function(e){return i.apply(this,arguments)}),write:(n=e._asyncToGenerator((function*(e,r){return o.write(e,t,r)})),function(e,t){return n.apply(this,arguments)}),writeV:(r=e._asyncToGenerator((function*(e,r){return o.writeV(e,t,r)})),function(e,t){return r.apply(this,arguments)}),unwrap:()=>o};var r,n,i},unwrap:()=>i.unwrap()};return o}class nL extends Ia{constructor(t,r){var n,i,o,a,s,l,c;super(),e._defineProperty(this,"log",void 0),e._defineProperty(this,"protocol",void 0),e._defineProperty(this,"running",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"timeout",void 0),e._defineProperty(this,"metrics",void 0),this.components=t,this.log=t.logger.forComponent("".concat(r.logPrefix,":network")),this.running=!1,this.protocol=r.protocol,this.timeout=new WO(e._objectSpread2(e._objectSpread2({},null!==(n=r.timeout)&&void 0!==n?n:{}),{},{metrics:t.metrics,metricName:"".concat(r.metricsPrefix,"_network_message_send_times_milliseconds")})),this.metrics={operations:null===(i=t.metrics)||void 0===i?void 0:i.registerCounterGroup("".concat(r.metricsPrefix,"_outbound_rpc_requests_total")),errors:null===(o=t.metrics)||void 0===o?void 0:o.registerCounterGroup("".concat(r.metricsPrefix,"_outbound_rpc_errors_total"))},this.sendRequest=null!==(a=null===(s=t.metrics)||void 0===s?void 0:s.traceFunction("libp2p.kadDHT.sendRequest",this.sendRequest.bind(this),{optionsIndex:2,getAttributesFromArgs(t,r){var[n,i]=t;return e._objectSpread2(e._objectSpread2({},r),{},{to:n.toString(),"message type":"".concat(i.type)})},getAttributesFromYieldedValue:(e,t)=>("PEER_RESPONSE"===e.name&&(e.providers.length>0&&e.providers.forEach(((e,r)=>{t["providers-".concat(r)]=e.id.toString()})),e.closer.length>0&&e.closer.forEach(((e,r)=>{t["closer-".concat(r)]=e.id.toString()}))),t)}))&&void 0!==a?a:this.sendRequest,this.sendMessage=null!==(l=null===(c=t.metrics)||void 0===c?void 0:c.traceFunction("libp2p.kadDHT.sendMessage",this.sendMessage.bind(this),{optionsIndex:2,getAttributesFromArgs(t,r){var[n,i]=t;return e._objectSpread2(e._objectSpread2({},r),{},{to:n.toString(),"message type":"".concat(i.type)})},getAttributesFromYieldedValue:(e,t)=>("PEER_RESPONSE"===e.name&&(e.providers.length>0&&e.providers.forEach(((e,r)=>{t["providers-".concat(r)]=e.id.toString()})),e.closer.length>0&&e.closer.forEach(((e,r)=>{t["closer-".concat(r)]=e.id.toString()}))),t)}))&&void 0!==l?l:this.sendMessage}start(){var t=this;return e._asyncToGenerator((function*(){t.running||(t.running=!0)}))()}stop(){var t=this;return e._asyncToGenerator((function*(){t.running=!1}))()}isStarted(){return this.running}sendRequest(t,r){var n=this;return e._wrapAsyncGenerator((function(t,r){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){if(n.running){var o,a=r.type;if(null==a)throw new ea("Message type was missing");n.log("sending %s to %p",r.type,t),yield EO({peer:t},i),yield mO({to:t,type:a},i);var s=n.timeout.getTimeoutSignal(i);i=e._objectSpread2(e._objectSpread2({},i),{},{signal:s});try{var l;null===(l=n.metrics.operations)||void 0===l||l.increment({[a]:!0});var c=yield e._awaitAsyncGenerator(n.components.connectionManager.openConnection(t,i));o=yield e._awaitAsyncGenerator(c.newStream(n.protocol,i));var u=yield e._awaitAsyncGenerator(n._writeReadMessage(o,r,i));o.close(i).catch((e=>{var r;n.log.error("error closing stream to %p",t,e),null===(r=o)||void 0===r||r.abort(e)})),yield wO({from:t,messageType:u.type,closer:u.closer.map(qO),providers:u.providers.map(qO),record:null==u.record?void 0:pO.deserialize(u.record)},i)}catch(e){var d,h,p;null===(d=n.metrics.errors)||void 0===d||d.increment({[a]:!0}),null===(h=o)||void 0===h||h.abort(e),!0!==(null===(p=i.signal)||void 0===p?void 0:p.aborted)&&n.log.error("could not send %s to %p - %e",r.type,t,e),yield _O({from:t,error:e},i)}finally{n.timeout.cleanUp(s)}}}()})).apply(this,arguments)}sendMessage(t,r){var n=this;return e._wrapAsyncGenerator((function(t,r){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){if(n.running){var o,a=r.type;if(null==a)throw new ea("Message type was missing");n.log("sending %s to %p",r.type,t),yield EO({peer:t},i),yield mO({to:t,type:a},i);var s=n.timeout.getTimeoutSignal(i);i=e._objectSpread2(e._objectSpread2({},i),{},{signal:s});try{var l;null===(l=n.metrics.operations)||void 0===l||l.increment({[a]:!0});var c=yield e._awaitAsyncGenerator(n.components.connectionManager.openConnection(t,i));o=yield e._awaitAsyncGenerator(c.newStream(n.protocol,i)),yield e._awaitAsyncGenerator(n._writeMessage(o,r,i)),o.close(i).catch((e=>{var r;n.log.error("error closing stream to %p",t,e),null===(r=o)||void 0===r||r.abort(e)})),yield wO({from:t,messageType:a},i)}catch(e){var u,d;null===(u=n.metrics.errors)||void 0===u||u.increment({[a]:!0}),null===(d=o)||void 0===d||d.abort(e),yield _O({from:t,error:e},i)}finally{n.timeout.cleanUp(s)}}}()})).apply(this,arguments)}_writeMessage(t,r,n){return e._asyncToGenerator((function*(){var e=rL(t);yield e.write(r,aO,n)}))()}_writeReadMessage(t,r,n){var i=this;return e._asyncToGenerator((function*(){var e=rL(t);yield e.write(r,aO,n);var o=yield e.read(aO,n);return o.closer.forEach((e=>{i.safeDispatchEvent("peer",{detail:qO(e)})})),o.providers.forEach((e=>{i.safeDispatchEvent("peer",{detail:qO(e)})})),o}))()}}function iL(e,t){if(e.byteLength!==t.byteLength)throw new Error("Inputs should have the same length");for(var r=0;r<e.byteLength;r++)if(e[r]!==t[r])return e[r]<t[r]?-1:1;return 0}class oL{constructor(t,r){e._defineProperty(this,"originDhtKey",void 0),e._defineProperty(this,"capacity",void 0),e._defineProperty(this,"peerDistances",void 0),this.originDhtKey=t,this.capacity=r,this.peerDistances=[]}get length(){return this.peerDistances.length}get peers(){return this.peerDistances.map((e=>e.peer))}add(t){var r=this;return e._asyncToGenerator((function*(){var e=yield GO(t.id);r.addWithKadId(t,e)}))()}addWithKadId(e,t){if(null==this.peerDistances.find((t=>t.peer.id.equals(e.id)))){for(var r={peer:e,distance:Dk(this.originDhtKey,t)},n=!1,i=0;i<this.peerDistances.length;i++){var o=iL(this.peerDistances[i].distance,r.distance);if(0===o||1===o){n=!0,this.peerDistances.splice(i,0,r);break}}n||this.peerDistances.push(r),this.peerDistances=this.peerDistances.slice(0,this.capacity)}}isCloser(t){var r=this;return e._asyncToGenerator((function*(){return 0===r.length||-1===iL(Dk(yield GO(t),r.originDhtKey),r.peerDistances[r.peerDistances.length-1].distance)}))()}anyCloser(t){var r=this;return e._asyncToGenerator((function*(){return 0!==t.length&&Promise.any(t.map(function(){var t=e._asyncToGenerator((function*(e){return r.isCloser(e)}));return function(e){return t.apply(this,arguments)}}()))}))()}}class aL{constructor(t,r){var n,i,o,a;e._defineProperty(this,"log",void 0),e._defineProperty(this,"routingTable",void 0),e._defineProperty(this,"network",void 0),e._defineProperty(this,"validators",void 0),e._defineProperty(this,"queryManager",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"peerId",void 0),this.routingTable=r.routingTable,this.network=r.network,this.validators=r.validators,this.queryManager=r.queryManager,this.peerStore=t.peerStore,this.peerId=t.peerId,this.log=t.logger.forComponent("".concat(r.logPrefix,":peer-routing")),this.findPeer=null!==(n=null===(i=t.metrics)||void 0===i?void 0:i.traceFunction("libp2p.kadDHT.findPeer",this.findPeer.bind(this),{optionsIndex:1}))&&void 0!==n?n:this.findPeer,this.getClosestPeers=null!==(o=null===(a=t.metrics)||void 0===a?void 0:a.traceFunction("libp2p.kadDHT.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1}))&&void 0!==o?o:this.getClosestPeers}findPeerLocal(t){var r=this;return e._asyncToGenerator((function*(){var e,n=yield r.routingTable.find(t);if(null!=n){r.log("findPeerLocal found %p in routing table",t);try{e=yield r.peerStore.get(n)}catch(e){if("NotFoundError"!==e.name)throw e}}if(null==e)try{e=yield r.peerStore.get(t)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=e)return r.log("findPeerLocal found %p in peer store",t),{id:e.id,multiaddrs:e.addresses.map((e=>e.multiaddr))}}))()}_getValueSingle(t,r){var n=this;return e._wrapAsyncGenerator((function(t,r){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){var o={type:tO.GET_VALUE,key:r};yield*e._asyncGeneratorDelegate(e._asyncIterator(n.network.sendRequest(t,o,i)))}()})).apply(this,arguments)}getPublicKeyFromNode(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var i,o=function(e){return _t([CO,e.toMultihash().bytes])}(t),a=!1,s=!1;try{for(var l,c=e._asyncIterator(r._getValueSingle(t,o,n));a=!(l=yield e._awaitAsyncGenerator(c.next())).done;a=!1){var u=l.value;if(yield u,"PEER_RESPONSE"===u.name&&null!=u.record){var d=nc(zl(u.record.value));if(!d.equals(t))throw new ta("public key does not match id");if(null==d.publicKey)throw new ta("public key missing");yield PO({from:t,value:u.record.value},n)}}}catch(e){s=!0,i=e}finally{try{a&&null!=c.return&&(yield e._awaitAsyncGenerator(c.return()))}finally{if(s)throw i}}throw new fO("Node not responding with its public key: ".concat(t.toString()))}()})).apply(this,arguments)}findPeer(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){if(r.log("findPeer %p",t),!1!==n.useCache){var i=yield e._awaitAsyncGenerator(r.findPeerLocal(t));if(null!=i)return r.log("found local"),void(yield bO({from:r.peerId,peer:i},n))}var o=!1;if(!1!==n.useNetwork){var a,s=r,l=function(){var r=e._wrapAsyncGenerator((function(r){var{peer:i,signal:o}=r;return function*(){var r,a={type:tO.FIND_NODE,key:t.toMultihash().bytes},l=!1,c=!1;try{for(var u,d=e._asyncIterator(s.network.sendRequest(i,a,e._objectSpread2(e._objectSpread2({},n),{},{signal:o})));l=!(u=yield e._awaitAsyncGenerator(d.next())).done;l=!1){var h=u.value;if(yield h,"PEER_RESPONSE"===h.name){var p=h.closer.find((e=>e.id.equals(t)));null!=p&&(yield bO({from:h.from,peer:p},n))}}}catch(e){c=!0,r=e}finally{try{l&&null!=d.return&&(yield e._awaitAsyncGenerator(d.return()))}finally{if(c)throw r}}}()}));return function(e){return r.apply(this,arguments)}}(),c=!1,u=!1;try{for(var d,h=e._asyncIterator(r.queryManager.run(t.toMultihash().bytes,l,n));c=!(d=yield e._awaitAsyncGenerator(h.next())).done;c=!1){var p=d.value;"FINAL_PEER"===p.name&&(o=!0),yield p}}catch(e){u=!0,a=e}finally{try{c&&null!=h.return&&(yield e._awaitAsyncGenerator(h.return()))}finally{if(u)throw a}}}o||(yield _O({from:r.peerId,error:new ua("Not found")},n))}()})).apply(this,arguments)}getClosestPeers(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){r.log("getClosestPeers to %b",t);var i=yield e._awaitAsyncGenerator(NO(t)),o=r.routingTable.closestPeers(i),a=r,s=new oL(i,r.routingTable.kBucketSize);yield e._awaitAsyncGenerator(Promise.all(o.map(function(){var t=e._asyncToGenerator((function*(e){yield s.add({id:e,multiaddrs:[]})}));return function(e){return t.apply(this,arguments)}}())));var l,c=function(){var r=e._wrapAsyncGenerator((function(r){var{peer:i,signal:o}=r;return function*(){a.log("closerPeersSingle %s from %p",Ze(t,"base32"),i);var r={type:tO.FIND_NODE,key:t};yield*e._asyncGeneratorDelegate(e._asyncIterator(a.network.sendRequest(i,r,e._objectSpread2(e._objectSpread2({},n),{},{signal:o}))))}()}));return function(e){return r.apply(this,arguments)}}(),u=!1,d=!1;try{for(var h,p=e._asyncIterator(r.queryManager.run(t,c,n));u=!(h=yield e._awaitAsyncGenerator(p.next())).done;u=!1){var f=h.value;"PEER_RESPONSE"===f.name&&(yield e._awaitAsyncGenerator(Promise.all(f.closer.map(function(){var t=e._asyncToGenerator((function*(e){yield s.add(e)}));return function(e){return t.apply(this,arguments)}}())))),yield f}}catch(e){d=!0,l=e}finally{try{u&&null!=p.return&&(yield e._awaitAsyncGenerator(p.return()))}finally{if(d)throw l}}for(var v of(r.log("found %d peers close to %b",s.length,t),s.peers))yield bO({from:r.peerId,peer:v},n)}()})).apply(this,arguments)}getValueOrPeers(t,r){var n=this;return e._wrapAsyncGenerator((function(t,r){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){var o,a=!1,s=!1;try{for(var l,c=e._asyncIterator(n._getValueSingle(t,r,i));a=!(l=yield e._awaitAsyncGenerator(c.next())).done;a=!1){var u=l.value;if("PEER_RESPONSE"===u.name&&null!=u.record)try{yield e._awaitAsyncGenerator(n._verifyRecordOnline(u.record))}catch(e){var d="invalid record received, discarded";n.log(d),yield _O({from:u.from,error:new fO(d)},i);continue}yield u}}catch(e){s=!0,o=e}finally{try{a&&null!=c.return&&(yield e._awaitAsyncGenerator(c.return()))}finally{if(s)throw o}}}()})).apply(this,arguments)}_verifyRecordOnline(t){var r=this;return e._asyncToGenerator((function*(){if(null==t.timeReceived)throw new yO("invalid record received");yield kO(r.validators,new pO(t.key,t.value,t.timeReceived))}))()}getCloserPeersOffline(t,r){var n=this;return e._asyncToGenerator((function*(){var e=[];try{var i=oc(Ae(t)),o=yield n.peerStore.get(i);e.push({id:o.id,multiaddrs:o.addresses.map((e=>{var{multiaddr:t}=e;return t}))})}catch(e){}var a=yield NO(t),s=n.routingTable.closestPeers(a),l=Dk(yield GO(r),a);for(var c of s){if(-1===iL(Dk(yield GO(c),a),l))try{var u=yield n.peerStore.get(c);e.push({id:c,multiaddrs:u.addresses.map((e=>{var{multiaddr:t}=e;return t}))})}catch(e){if("NotFoundError"!==e.name)throw e}}return e.length>0?n.log("getCloserPeersOffline found %d peer(s) closer to %b than %p",e.length,t,r):n.log("getCloserPeersOffline could not find peer closer to %b than %p with %d peers in the routing table",t,r,n.routingTable.size),e}))()}}class sL{constructor(t,r){e._defineProperty(this,"log",void 0),e._defineProperty(this,"datastore",void 0),e._defineProperty(this,"datastorePrefix",void 0),e._defineProperty(this,"lock",void 0),this.log=t.logger.forComponent("".concat(r.logPrefix,":providers")),this.datastorePrefix="".concat(r.datastorePrefix,"/provider"),this.datastore=t.datastore,this.lock=r.lock}addProvider(t,r){var n=this;return e._asyncToGenerator((function*(){var e=yield n.lock.readLock();try{n.log("%p provides %s",r,t),yield n.writeProviderEntry(t,r)}finally{e()}}))()}removeProvider(t,r){var n=this;return e._asyncToGenerator((function*(){var e=yield n.lock.writeLock();try{var i=jO(n.datastorePrefix,t,r);n.log("%p no longer provides %s",r,t),yield n.datastore.delete(i)}finally{e()}}))()}getProviders(t){var r=this;return e._asyncToGenerator((function*(){var e=yield r.lock.readLock();try{r.log("get providers for %c",t);var n=yield r.loadProviders(t);return r.log("got %d providers for %c",n.size,t),[...n.keys()]}finally{e()}}))()}writeProviderEntry(t,r){var n=arguments,i=this;return e._asyncToGenerator((function*(){var e=n.length>2&&void 0!==n[2]?n[2]:new Date,o=jO(i.datastorePrefix,t,r),a=wt(e.getTime());yield i.datastore.put(o,a)}))()}loadProviders(t){var r=this;return e._asyncToGenerator((function*(){var n,i=new lh,o=jO(r.datastorePrefix,t),a=!1,s=!1;try{for(var l,c=e._asyncIterator(r.datastore.query({prefix:o.toString()}));a=!(l=yield c.next()).done;a=!1){var u=l.value,{peerId:d}=MO(u.key);i.set(d,FO(u.value))}}catch(e){s=!0,n=e}finally{try{a&&null!=c.return&&(yield c.return())}finally{if(s)throw n}}return i}))()}}function lL(){return lL=e._wrapAsyncGenerator((function*(t){var{key:r,startingPeer:n,ourPeerId:i,signal:o,query:a,alpha:s,pathIndex:l,numPaths:c,queryFuncTimeout:u,log:d,peersSeen:h,connectionManager:p}=t,f=new Mh({concurrency:s,sort:(e,t)=>iL(e.options.distance,t.options.distance)}),v=yield e._awaitAsyncGenerator(NO(r));!function n(s,y){if(null!=s){h.add(s);var g=Dk(y,v);f.add(e._asyncToGenerator((function*(){var y=[o];null!=u&&y.push(AbortSignal.timeout(u));var m=$d(y);try{var w,b=!1,_=!1;try{for(var S,P=e._asyncIterator(a(e._objectSpread2(e._objectSpread2({},t),{},{key:r,peer:s,signal:m,pathIndex:l,numPaths:c})));b=!(S=yield P.next()).done;b=!1){var E=S.value;if(m.aborted)return;if("PEER_RESPONSE"===E.name)for(var A of E.closer)if(h.has(A.id))d.trace("already seen %p in query",A.id);else if(i.equals(A.id))d("not querying ourselves");else if(yield p.isDialable(A.multiaddrs)){var k=yield GO(A.id);-1===iL(Dk(k,v),g)?(d.trace("querying closer peer %p",A.id),n(A.id,k)):d.trace("skipping %p as they are not closer to %b than %p",A.id,r,s)}else d("not querying undialable peer");f.safeDispatchEvent("completed",{detail:E})}}catch(e){_=!0,w=e}finally{try{b&&null!=P.return&&(yield P.return())}finally{if(_)throw w}}}catch(e){if(!o.aborted)return _O({from:s,error:e},t)}finally{m.clear()}})),{distance:g}).catch((e=>{d.error(e)}))}}(n,yield e._awaitAsyncGenerator(GO(n)));try{var y,g=!1,m=!1;try{for(var w,b=e._asyncIterator(f.toGenerator({signal:o}));g=!(w=yield e._awaitAsyncGenerator(b.next())).done;g=!1){var _=w.value;null!=_&&(yield _)}}catch(e){m=!0,y=e}finally{try{g&&null!=b.return&&(yield e._awaitAsyncGenerator(b.return()))}finally{if(m)throw y}}}catch(e){if(o.aborted)throw new vO("Query aborted");throw e}})),lL.apply(this,arguments)}class cL{constructor(t,r){var n,i;e._defineProperty(this,"disjointPaths",void 0),e._defineProperty(this,"alpha",void 0),e._defineProperty(this,"shutDownController",void 0),e._defineProperty(this,"running",void 0),e._defineProperty(this,"logger",void 0),e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"connectionManager",void 0),e._defineProperty(this,"routingTable",void 0),e._defineProperty(this,"initialQuerySelfHasRun",void 0),e._defineProperty(this,"logPrefix",void 0),this.logPrefix=r.logPrefix,this.disjointPaths=null!==(n=r.disjointPaths)&&void 0!==n?n:20,this.alpha=null!==(i=r.alpha)&&void 0!==i?i:3,this.initialQuerySelfHasRun=r.initialQuerySelfHasRun,this.routingTable=r.routingTable,this.logger=t.logger,this.peerId=t.peerId,this.connectionManager=t.connectionManager,this.shutDownController=new AbortController,this.shutDownController.signal,this.running=!1}isStarted(){return this.running}start(){var t=this;return e._asyncToGenerator((function*(){t.running||(t.running=!0,t.shutDownController=new AbortController,t.shutDownController.signal)}))()}stop(){var t=this;return e._asyncToGenerator((function*(){t.running=!1,t.shutDownController.abort()}))()}run(t,r){var n=this;return e._wrapAsyncGenerator((function(t,r){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){if(!n.running)throw new Error("QueryManager not started");if(null==i.signal){var o=AbortSignal.timeout(18e4);i=e._objectSpread2(e._objectSpread2({},i),{},{signal:o})}var a=new AbortController,s=$d([n.shutDownController.signal,a.signal,i.signal]);a.signal;var l=n.logger.forComponent("".concat(n.logPrefix,":query:")+Ze(t,"base58btc")),c=!1;try{!0!==i.isSelfQuery&&null!=n.initialQuerySelfHasRun&&(l("waiting for initial query-self query before continuing"),yield e._awaitAsyncGenerator(tu(n.initialQuerySelfHasRun.promise,s)),n.initialQuerySelfHasRun=void 0),l("query:start");var u=yield e._awaitAsyncGenerator(NO(t)),d=n.routingTable.closestPeers(u),h=d.slice(0,Math.min(n.disjointPaths,d.length));if(0===d.length)return void l.error("Running query with no peers");var p,f=new ch,v=h.map(((o,a)=>function(e){return lL.apply(this,arguments)}(e._objectSpread2(e._objectSpread2({},i),{},{key:t,startingPeer:o,ourPeerId:n.peerId,signal:s,query:r,pathIndex:a,numPaths:h.length,alpha:n.alpha,queryFuncTimeout:i.queryFuncTimeout,log:l,peersSeen:f,onProgress:i.onProgress,connectionManager:n.connectionManager})))),y=!1,g=!1;try{for(var m,w=e._asyncIterator(su(...v));y=!(m=yield e._awaitAsyncGenerator(w.next())).done;y=!1){var b=m.value;if("QUERY_ERROR"===b.name&&l.error("query error",b.error),"PEER_RESPONSE"===b.name)for(var _ of[...b.closer,...b.providers])(yield e._awaitAsyncGenerator(n.connectionManager.isDialable(_.multiaddrs)))&&(yield e._awaitAsyncGenerator(n.routingTable.add(_.id)));yield b}}catch(e){g=!0,p=e}finally{try{y&&null!=w.return&&(yield e._awaitAsyncGenerator(w.return()))}finally{if(g)throw p}}c=!0}catch(e){if(n.running||"QueryAbortedError"!==e.name)throw e}finally{c||(l("query exited early"),a.abort()),s.clear(),l("query:done")}}()})).apply(this,arguments)}}function uL(t){if(null!=t[Symbol.asyncIterator])return e._asyncToGenerator((function*(){var r,n=0,i=!1,o=!1;try{for(var a,s=e._asyncIterator(t);i=!(a=yield s.next()).done;i=!1){a.value;n++}}catch(e){o=!0,r=e}finally{try{i&&null!=s.return&&(yield s.return())}finally{if(o)throw r}}return n}))();var r=0;for(var n of t)r++;return r}function dL(t,r,n){var i,o=new Promise(((o,a)=>{var s;if(!((n=e._objectSpread2({rejectionEvents:["error"],multiArgs:!1,resolveImmediately:!1},n)).count>=0)||n.count!==Number.POSITIVE_INFINITY&&!Number.isInteger(n.count))throw new TypeError("The `count` option should be at least 0 or more");null===(s=n.signal)||void 0===s||s.throwIfAborted();var l=[r].flat(),c=[],{addListener:u,removeListener:d}=(e=>{var t=e.addEventListener||e.on||e.addListener,r=e.removeEventListener||e.off||e.removeListener;if(!t||!r)throw new TypeError("Emitter is not compatible");return{addListener:t.bind(e),removeListener:r.bind(e)}})(t),h=function(){for(var e=arguments.length,t=new Array(e),r=0;r<e;r++)t[r]=arguments[r];var a=n.multiArgs?t:t[0];n.filter&&!n.filter(a)||(c.push(a),n.count===c.length&&(i(),o(c)))},p=e=>{i(),a(e)};for(var f of(i=()=>{for(var e of l)d(e,h);for(var t of n.rejectionEvents)d(t,p)},l))u(f,h);for(var v of n.rejectionEvents)u(v,p);n.signal&&n.signal.addEventListener("abort",(()=>{p(n.signal.reason)}),{once:!0}),n.resolveImmediately&&o(c)}));if(o.cancel=i,"number"==typeof n.timeout){var a=Sp(o,{milliseconds:n.timeout});return a.cancel=i,a}return o}class hL{constructor(t,r){var n,i,o,a;e._defineProperty(this,"log",void 0),e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"peerRouting",void 0),e._defineProperty(this,"routingTable",void 0),e._defineProperty(this,"count",void 0),e._defineProperty(this,"interval",void 0),e._defineProperty(this,"initialInterval",void 0),e._defineProperty(this,"queryTimeout",void 0),e._defineProperty(this,"running",void 0),e._defineProperty(this,"timeoutId",void 0),e._defineProperty(this,"controller",void 0),e._defineProperty(this,"initialQuerySelfHasRun",void 0),e._defineProperty(this,"querySelfPromise",void 0),this.peerId=t.peerId,this.log=t.logger.forComponent("".concat(r.logPrefix,":query-self")),this.running=!1,this.peerRouting=r.peerRouting,this.routingTable=r.routingTable,this.count=null!==(n=r.count)&&void 0!==n?n:20,this.interval=null!==(i=r.interval)&&void 0!==i?i:3e5,this.initialInterval=null!==(o=r.initialInterval)&&void 0!==o?o:1e3,this.queryTimeout=null!==(a=r.queryTimeout)&&void 0!==a?a:5e3,this.initialQuerySelfHasRun=r.initialQuerySelfHasRun,this.querySelf=zO(this.querySelf.bind(this),r.operationMetrics,"SELF_QUERY")}isStarted(){return this.running}start(){this.running||(this.running=!0,clearTimeout(this.timeoutId),this.timeoutId=setTimeout((()=>{this.querySelf().catch((e=>{this.log.error("error running self-query",e)}))}),this.initialInterval))}stop(){this.running=!1,null!=this.timeoutId&&clearTimeout(this.timeoutId),null!=this.controller&&this.controller.abort()}querySelf(){var t=this;return e._asyncToGenerator((function*(){if(t.running){if(null!=t.querySelfPromise)return t.log("joining existing self query"),t.querySelfPromise.promise;if(t.querySelfPromise=Yc(),t.running){t.controller=new AbortController;var r=[t.controller.signal];if(null==t.initialQuerySelfHasRun){var n=AbortSignal.timeout(t.queryTimeout);r.push(n)}var i=$d(r);t.controller.signal;try{0===t.routingTable.size&&(t.log("routing table was empty, waiting for some peers before running query"),yield function(t,r,n){"function"==typeof n&&(n={filter:n});var i=dL(t,r,n=e._objectSpread2(e._objectSpread2({},n),{},{count:1,resolveImmediately:!1})),o=i.then((e=>e[0]));return o.cancel=i.cancel,o}(t.routingTable,"peer:add",{signal:i,filter:e=>!t.peerId.equals(e.detail)}),t.log("routing table has peers, continuing with query")),t.log("run self-query, look for %d peers timing out after %dms",t.count,t.queryTimeout);var o=Date.now(),a=yield lu(t.peerRouting.getClosestPeers(t.peerId.toMultihash().bytes,{signal:i,isSelfQuery:!0}),(e=>Lc(e,t.count)),function(){var t=e._asyncToGenerator((function*(e){return uL(e)}));return function(e){return t.apply(this,arguments)}}());t.log("self-query found %d peers in %dms",a,Date.now()-o)}catch(e){t.log.error("self-query error",e)}finally{i.clear(),null!=t.initialQuerySelfHasRun&&(t.initialQuerySelfHasRun.resolve(),t.initialQuerySelfHasRun=void 0)}}t.querySelfPromise.resolve(),t.querySelfPromise=void 0,t.running&&(t.timeoutId=setTimeout((()=>{t.querySelf().catch((e=>{t.log.error("error running self-query",e)}))}),t.interval))}else t.log("skip self-query because we are not started")}))()}}class pL extends Ia{constructor(t,r){var n,i,o,a,s,l;super(),e._defineProperty(this,"log",void 0),e._defineProperty(this,"reprovideQueue",void 0),e._defineProperty(this,"maxQueueSize",void 0),e._defineProperty(this,"datastore",void 0),e._defineProperty(this,"timeout",void 0),e._defineProperty(this,"reprovideTimeout",void 0),e._defineProperty(this,"running",void 0),e._defineProperty(this,"shutdownController",void 0),e._defineProperty(this,"reprovideThreshold",void 0),e._defineProperty(this,"contentRouting",void 0),e._defineProperty(this,"datastorePrefix",void 0),e._defineProperty(this,"addressManager",void 0),e._defineProperty(this,"validity",void 0),e._defineProperty(this,"interval",void 0),e._defineProperty(this,"lock",void 0),e._defineProperty(this,"peerId",void 0),this.log=t.logger.forComponent("".concat(r.logPrefix,":reprovider")),this.peerId=t.peerId,this.reprovideQueue=new Mh({concurrency:null!==(n=r.concurrency)&&void 0!==n?n:10,metrics:t.metrics,metricName:"".concat(r.metricsPrefix,"_reprovide_queue")}),this.reprovideTimeout=new WO(e._objectSpread2(e._objectSpread2({},null!==(i=r.timeout)&&void 0!==i?i:{}),{},{metrics:t.metrics,metricName:"".concat(r.metricsPrefix,"_reprovide_timeout_milliseconds")})),this.datastore=t.datastore,this.addressManager=t.addressManager,this.datastorePrefix="".concat(r.datastorePrefix,"/provider"),this.reprovideThreshold=null!==(o=r.threshold)&&void 0!==o?o:864e5,this.maxQueueSize=null!==(a=r.maxQueueSize)&&void 0!==a?a:16384,this.validity=null!==(s=r.validity)&&void 0!==s?s:cO,this.interval=null!==(l=r.interval)&&void 0!==l?l:uO,this.contentRouting=r.contentRouting,this.lock=r.lock,this.running=!1,this.reprovide=zO(this.reprovide.bind(this),r.operationMetrics,"PROVIDE")}start(){this.running||(this.running=!0,this.shutdownController=new AbortController,this.shutdownController.signal,this.timeout=setTimeout((()=>{this.cleanUp().catch((e=>{this.log.error("error running reprovide/cleanup - %e",e)}))}),this.interval))}stop(){var e;this.running=!1,this.reprovideQueue.clear(),clearTimeout(this.timeout),null===(e=this.shutdownController)||void 0===e||e.abort()}cleanUp(){var t=this;return e._asyncToGenerator((function*(){var r=yield t.lock.writeLock();try{t.safeDispatchEvent("reprovide:start");var n,i=!1,o=!1;try{for(var a,s=function*(){var e=a.value;try{var{cid:r,peerId:n}=MO(e.key),i=FO(e.value).getTime(),o=i+t.validity,s=Date.now(),l=s>o;t.log.trace("comparing: %d < %d = %s %s",i,s-t.validity,l,l?"(expired)":""),l&&(yield t.datastore.delete(e.key)),t.peerId.equals(n)&&s-o<t.reprovideThreshold&&t.queueReprovide(r).catch((e=>{t.log.error("could not reprovide %c - %e",r,e)}))}catch(r){t.log.error("error processing datastore key %s - %e",e.key,r.message)}},l=e._asyncIterator(t.datastore.query({prefix:t.datastorePrefix}));i=!(a=yield l.next()).done;i=!1)yield*s()}catch(e){o=!0,n=e}finally{try{i&&null!=l.return&&(yield l.return())}finally{if(o)throw n}}t.log("reprovide/cleanup successful")}finally{r(),t.safeDispatchEvent("reprovide:end"),t.running&&(t.timeout=setTimeout((()=>{t.cleanUp().catch((e=>{t.log.error("error running re-provide - %e",e)}))}),t.interval))}}))()}queueReprovide(t){var r=this;return e._asyncToGenerator((function*(){var n;if(r.running){r.log.trace("waiting for queue capacity before adding %c to re-provide queue",t),yield r.reprovideQueue.onSizeLessThan(r.maxQueueSize);var i=r.reprovideQueue.queue.find((e=>e.options.cid.equals(t)));if(null!=i)return r.log.trace("not adding %c to re-provide queue - already in queue",t),i.join();r.log.trace("adding %c to re-provide queue",t),r.reprovideQueue.add(function(){var n=e._asyncToGenerator((function*(e){var n;if(null===(n=e.signal)||void 0===n||n.throwIfAborted(),r.running){r.log.trace("re-providing %c",t);var i=r.reprovideTimeout.getTimeoutSignal(e);try{yield r.reprovide(e.cid,e)}finally{r.reprovideTimeout.cleanUp(i)}r.log.trace("re-provided %c",t)}}));return function(e){return n.apply(this,arguments)}}(),{signal:null===(n=r.shutdownController)||void 0===n?void 0:n.signal,cid:t}).catch((e=>{r.log.error("could not re-provide key %c - %e",t,e)}))}}))()}reprovide(t,r){var n=this;return e._asyncToGenerator((function*(){yield Nc(n.contentRouting.provide(t,n.addressManager.getAddresses(),r))}))()}}class fL{constructor(t,r){var n,i,o,a;e._defineProperty(this,"routingTable",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"closestPeers",void 0),e._defineProperty(this,"newPeers",void 0),e._defineProperty(this,"refreshInterval",void 0),e._defineProperty(this,"peerSetSize",void 0),e._defineProperty(this,"timeout",void 0),e._defineProperty(this,"closeTagName",void 0),e._defineProperty(this,"closeTagValue",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"running",void 0),this.components=t,this.log=t.logger.forComponent("".concat(r.logPrefix,":routing-table")),this.routingTable=r.routingTable,this.refreshInterval=null!==(n=r.refreshInterval)&&void 0!==n?n:5e3,this.peerSetSize=null!==(i=r.peerSetSize)&&void 0!==i?i:20,this.closeTagName=null!==(o=r.closeTagName)&&void 0!==o?o:"kad-close",this.closeTagValue=null!==(a=r.closeTagValue)&&void 0!==a?a:50,this.closestPeers=new ch,this.onPeerPing=this.onPeerPing.bind(this),this.running=!1}start(){var t=this;return e._asyncToGenerator((function*(){if(!t.running){t.running=!0;var e=yield GO(t.components.peerId);t.newPeers=new oL(e,t.peerSetSize),t.routingTable.addEventListener("peer:ping",t.onPeerPing),t.timeout=setInterval((()=>{t.updatePeerTags().catch((e=>{t.log.error("error updating peer tags - %e",e)}))}),t.refreshInterval)}}))()}stop(){this.running=!1,this.routingTable.removeEventListener("peer:ping",this.onPeerPing),clearTimeout(this.timeout)}onPeerPing(e){var t;null===(t=this.newPeers)||void 0===t||t.add({id:e.detail,multiaddrs:[]}).catch((e=>{this.log.error("error adding peer to distance list - %e",e)}))}updatePeerTags(){var t=this;return e._asyncToGenerator((function*(){var r,n=new ch(null===(r=t.newPeers)||void 0===r?void 0:r.peers.map((e=>e.id))),i=n.difference(t.closestPeers),o=t.closestPeers.difference(n);t.closestPeers=n,yield Promise.all([...[...i].map(function(){var r=e._asyncToGenerator((function*(e){yield t.components.peerStore.merge(e,{tags:{[t.closeTagName]:{value:t.closeTagValue},[dO]:{value:1}}})}));return function(e){return r.apply(this,arguments)}}()),...[...o].map(function(){var r=e._asyncToGenerator((function*(e){yield t.components.peerStore.merge(e,{tags:{[t.closeTagName]:void 0,[dO]:void 0}})}));return function(e){return r.apply(this,arguments)}}())])}))()}}function vL(e){return Array.isArray(null==e?void 0:e.peers)}class yL{constructor(t){var r,n,i,o,a;e._defineProperty(this,"root",void 0),e._defineProperty(this,"localPeer",void 0),e._defineProperty(this,"prefixLength",void 0),e._defineProperty(this,"splitThreshold",void 0),e._defineProperty(this,"kBucketSize",void 0),e._defineProperty(this,"numberOfNodesToPing",void 0),e._defineProperty(this,"lastPingThreshold",void 0),e._defineProperty(this,"ping",void 0),e._defineProperty(this,"verify",void 0),e._defineProperty(this,"onAdd",void 0),e._defineProperty(this,"onRemove",void 0),e._defineProperty(this,"onMove",void 0),e._defineProperty(this,"addingPeerMap",void 0),this.prefixLength=null!==(r=t.prefixLength)&&void 0!==r?r:mL,this.kBucketSize=null!==(n=t.kBucketSize)&&void 0!==n?n:gL,this.splitThreshold=null!==(i=t.splitThreshold)&&void 0!==i?i:this.kBucketSize,this.numberOfNodesToPing=null!==(o=t.numberOfOldContactsToPing)&&void 0!==o?o:wL,this.lastPingThreshold=null!==(a=t.lastPingThreshold)&&void 0!==a?a:_L,this.ping=t.ping,this.verify=t.verify,this.onAdd=t.onAdd,this.onRemove=t.onRemove,this.addingPeerMap=new lh,this.root={prefix:"",depth:0,peers:[]}}addSelfPeer(t){var r=this;return e._asyncToGenerator((function*(){r.localPeer={peerId:t,kadId:yield GO(t),lastPing:Date.now()}}))()}add(t,r){var n=this;return e._asyncToGenerator((function*(){var e={peerId:t,kadId:yield GO(t),lastPing:0},i=n.addingPeerMap.get(t);if(null!=i)return i;try{var o=n._add(e,r);n.addingPeerMap.set(t,o),yield o}finally{n.addingPeerMap.delete(t)}}))()}_add(t,r){var n=this;return e._asyncToGenerator((function*(){var i=n._determineBucket(t.kadId);if(!(n._indexOf(i,t.kadId)>-1)){if(i.peers.length===n.splitThreshold&&i.depth<n.prefixLength)return yield n._split(i),void(yield n._add(t,r));var o;if(i.peers.length<n.kBucketSize)return function(e,t){return e.lastPing<Date.now()-t}(t,n.lastPingThreshold)?void((yield n.verify(t,r))&&(t.lastPing=Date.now(),yield n._add(t,r))):(i.peers.push(t),void(yield null===(o=n.onAdd)||void 0===o?void 0:o.call(n,t,i)));var a,s=i.peers.filter((e=>{var t;return!e.peerId.equals(null===(t=n.localPeer)||void 0===t?void 0:t.peerId)&&!(e.lastPing>Date.now()-n.lastPingThreshold)})).sort(((e,t)=>e.lastPing<t.lastPing?-1:e.lastPing>t.lastPing?1:0)).slice(0,n.numberOfNodesToPing),l=!1,c=!1,u=!1;try{for(var d,h=e._asyncIterator(n.ping(s,r));c=!(d=yield h.next()).done;c=!1){var p=d.value;l=!0,yield n.remove(p.kadId)}}catch(e){u=!0,a=e}finally{try{c&&null!=h.return&&(yield h.return())}finally{if(u)throw a}}l&&(yield n._add(t,r))}}))()}closest(e){var t=this,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.kBucketSize;return function*(){var n=new oL(e,r);for(var i of t.toIterable())n.addWithKadId({id:i.peerId,multiaddrs:[]},i.kadId);yield*Qc(n.peers,(e=>e.id))}()}count(){return function e(t){if(vL(t))return t.peers.length;var r=0;return null!=t.left&&(r+=e(t.left)),null!=t.right&&(r+=e(t.right)),r}(this.root)}get(e){var t=this._determineBucket(e),r=this._indexOf(t,e);return t.peers[r]}remove(t){var r=this;return e._asyncToGenerator((function*(){var e=r._determineBucket(t),n=r._indexOf(e,t);if(n>-1){var i,o=e.peers.splice(n,1)[0];yield null===(i=r.onRemove)||void 0===i?void 0:i.call(r,o,e)}}))()}*toIterable(){yield*function*e(t){vL(t)?yield*t.peers:(yield*e(t.left),yield*e(t.right))}(this.root)}distance(e,t){return BigInt("0x"+Ze(Dk(e,t),"base16"))}_determineBucket(e){var t=Ze(e,"base2");return function e(r){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0;return vL(r)?r:e("0"===t[n]?r.left:r.right,n+1)}(this.root)}_indexOf(e,t){return e.peers.findIndex((e=>nt(e.kadId,t)))}_split(t){var r=this;return e._asyncToGenerator((function*(){var e={prefix:"0",depth:t.depth+1,peers:[]},n={prefix:"1",depth:t.depth+1,peers:[]};for(var i of t.peers){var o,a;if("0"===Ze(i.kadId,"base2")[t.depth])e.peers.push(i),yield null===(o=r.onMove)||void 0===o?void 0:o.call(r,i,t,e);else n.peers.push(i),yield null===(a=r.onMove)||void 0===a?void 0:a.call(r,i,t,n)}!function(e,t,r){delete e.peers,e.left=t,e.right=r,""===e.prefix&&(delete e.depth,delete e.prefix)}(t,e,n)}))()}}var gL=20,mL=6,wL=3,bL="kad-peer",_L=6e5;class SL extends Ia{constructor(t,r){var n,i,o,a,s,l,c,u,d,h,p;super(),e._defineProperty(this,"kBucketSize",void 0),e._defineProperty(this,"kb",void 0),e._defineProperty(this,"network",void 0),e._defineProperty(this,"closestPeerTagger",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"running",void 0),e._defineProperty(this,"pingNewContactTimeout",void 0),e._defineProperty(this,"pingNewContactQueue",void 0),e._defineProperty(this,"pingOldContactTimeout",void 0),e._defineProperty(this,"pingOldContactQueue",void 0),e._defineProperty(this,"populateFromDatastoreOnStart",void 0),e._defineProperty(this,"populateFromDatastoreLimit",void 0),e._defineProperty(this,"protocol",void 0),e._defineProperty(this,"peerTagName",void 0),e._defineProperty(this,"peerTagValue",void 0),e._defineProperty(this,"metrics",void 0),this.components=t,this.log=t.logger.forComponent("".concat(r.logPrefix,":routing-table")),this.kBucketSize=null!==(n=r.kBucketSize)&&void 0!==n?n:gL,this.running=!1,this.protocol=r.protocol,this.network=r.network,this.peerTagName=null!==(i=r.peerTagName)&&void 0!==i?i:bL,this.peerTagValue=null!==(o=r.peerTagValue)&&void 0!==o?o:1,this.pingOldContacts=this.pingOldContacts.bind(this),this.verifyNewContact=this.verifyNewContact.bind(this),this.peerAdded=this.peerAdded.bind(this),this.peerRemoved=this.peerRemoved.bind(this),this.populateFromDatastoreOnStart=null===(a=r.populateFromDatastoreOnStart)||void 0===a||a,this.populateFromDatastoreLimit=null!==(s=r.populateFromDatastoreLimit)&&void 0!==s?s:1e3,this.pingOldContactQueue=new jh({concurrency:null!==(l=r.pingOldContactConcurrency)&&void 0!==l?l:20,metricName:"".concat(r.metricsPrefix,"_ping_old_contact_queue"),metrics:this.components.metrics,maxSize:null!==(c=r.pingOldContactMaxQueueSize)&&void 0!==c?c:100}),this.pingOldContactTimeout=new WO(e._objectSpread2(e._objectSpread2({},null!==(u=r.pingOldContactTimeout)&&void 0!==u?u:{}),{},{metrics:this.components.metrics,metricName:"".concat(r.metricsPrefix,"_routing_table_ping_old_contact_time_milliseconds")})),this.pingNewContactQueue=new jh({concurrency:null!==(d=r.pingNewContactConcurrency)&&void 0!==d?d:20,metricName:"".concat(r.metricsPrefix,"_ping_new_contact_queue"),metrics:this.components.metrics,maxSize:null!==(h=r.pingNewContactMaxQueueSize)&&void 0!==h?h:100}),this.pingNewContactTimeout=new WO(e._objectSpread2(e._objectSpread2({},null!==(p=r.pingNewContactTimeout)&&void 0!==p?p:{}),{},{metrics:this.components.metrics,metricName:"".concat(r.metricsPrefix,"_routing_table_ping_new_contact_time_milliseconds")})),this.kb=new yL({kBucketSize:r.kBucketSize,prefixLength:r.prefixLength,splitThreshold:r.splitThreshold,numberOfOldContactsToPing:r.numberOfOldContactsToPing,lastPingThreshold:r.lastPingThreshold,ping:this.pingOldContacts,verify:this.verifyNewContact,onAdd:this.peerAdded,onRemove:this.peerRemoved}),this.closestPeerTagger=new fL(this.components,{logPrefix:r.logPrefix,routingTable:this,peerSetSize:r.closestPeerSetSize,refreshInterval:r.closestPeerSetRefreshInterval,closeTagName:r.closeTagName,closeTagValue:r.closeTagValue}),null!=this.components.metrics&&(this.metrics={routingTableSize:this.components.metrics.registerMetric("".concat(r.metricsPrefix,"_routing_table_size")),routingTableKadBucketTotal:this.components.metrics.registerMetric("".concat(r.metricsPrefix,"_routing_table_kad_bucket_total")),routingTableKadBucketAverageOccupancy:this.components.metrics.registerMetric("".concat(r.metricsPrefix,"_routing_table_kad_bucket_average_occupancy")),routingTableKadBucketMinOccupancy:this.components.metrics.registerMetric("".concat(r.metricsPrefix,"_routing_table_kad_bucket_min_occupancy")),routingTableKadBucketMaxOccupancy:this.components.metrics.registerMetric("".concat(r.metricsPrefix,"_routing_table_kad_bucket_max_occupancy")),routingTableKadBucketMaxDepth:this.components.metrics.registerMetric("".concat(r.metricsPrefix,"_routing_table_kad_bucket_max_depth")),kadBucketEvents:this.components.metrics.registerCounterGroup("".concat(r.metricsPrefix,"_kad_bucket_events_total"))})}isStarted(){return this.running}start(){var t=this;return e._asyncToGenerator((function*(){t.running||(t.running=!0,yield Ba(t.closestPeerTagger),yield t.kb.addSelfPeer(t.components.peerId))}))()}afterStart(){var t=this;return e._asyncToGenerator((function*(){Promise.resolve().then(e._asyncToGenerator((function*(){if(t.populateFromDatastoreOnStart){var e=0;for(var r of yield t.components.peerStore.all({filters:[e=>e.protocols.includes(t.protocol)&&e.tags.has(bL)],limit:t.populateFromDatastoreLimit})){if(!t.running)return;try{yield t.add(r.id),e++}catch(e){t.log("failed to add peer %p to routing table, removing kad-dht peer tags - %e"),yield t.components.peerStore.merge(r.id,{tags:{[t.peerTagName]:void 0}})}}t.log("added %d peer store peers to the routing table",e)}}))).catch((e=>{t.log.error("error adding peer store peers to the routing table %e",e)}))}))()}stop(){var t=this;return e._asyncToGenerator((function*(){t.running=!1,yield Da(t.closestPeerTagger),t.pingOldContactQueue.abort(),t.pingNewContactQueue.abort()}))()}peerAdded(t,r){var n=this;return e._asyncToGenerator((function*(){var e;n.components.peerId.equals(t.peerId)||(yield n.components.peerStore.merge(t.peerId,{tags:{[n.peerTagName]:{value:n.peerTagValue}}})),n.updateMetrics(),null===(e=n.metrics)||void 0===e||e.kadBucketEvents.increment({peer_added:!0}),n.safeDispatchEvent("peer:add",{detail:t.peerId})}))()}peerRemoved(t,r){var n=this;return e._asyncToGenerator((function*(){var e;n.components.peerId.equals(t.peerId)||(yield n.components.peerStore.merge(t.peerId,{tags:{[n.peerTagName]:void 0}})),n.updateMetrics(),null===(e=n.metrics)||void 0===e||e.kadBucketEvents.increment({peer_removed:!0}),n.safeDispatchEvent("peer:remove",{detail:t.peerId})}))()}pingOldContacts(t,r){var n=this;return e._wrapAsyncGenerator((function*(){if(n.running){var i=[],o=function*(t){var o;if(null==n.kb.get(t.kadId))return n.log("asked to ping contact %p that was not in routing table",t.peerId),1;null===(o=n.metrics)||void 0===o||o.kadBucketEvents.increment({ping_old_contact:!0}),i.push(e._asyncToGenerator((function*(){var i=n.pingOldContactQueue.find(t.peerId);if(null!=i)return n.log("asked to ping contact %p was already being pinged",t.peerId),(yield i.join(r))?void 0:t;var o=yield n.pingOldContactQueue.add(function(){var r=e._asyncToGenerator((function*(e){var r=n.pingOldContactTimeout.getTimeoutSignal(),i=$d([r,null==e?void 0:e.signal]);try{return yield n.pingContact(t,e)}catch(e){var o;return null===(o=n.metrics)||void 0===o||o.kadBucketEvents.increment({ping_old_contact_error:!0}),!0}finally{n.pingOldContactTimeout.cleanUp(r),i.clear()}}));return function(e){return r.apply(this,arguments)}}(),{peerId:t.peerId,signal:null==r?void 0:r.signal});return o?void 0:t})))};for(var a of t)yield*o(a);var s,l=!1,c=!1;try{for(var u,d=e._asyncIterator(zR(i));l=!(u=yield e._awaitAsyncGenerator(d.next())).done;l=!1){var h=u.value;null!=h&&(yield h)}}catch(e){c=!0,s=e}finally{try{l&&null!=d.return&&(yield e._awaitAsyncGenerator(d.return()))}finally{if(c)throw s}}}}))()}verifyNewContact(t,r){var n=this;return e._asyncToGenerator((function*(){var i=n.pingNewContactTimeout.getTimeoutSignal(),o=$d([i,null==r?void 0:r.signal]);try{var a=n.pingNewContactQueue.find(t.peerId);return null!=a?(n.log("joining existing ping to add new peer %p to routing table",t.peerId),yield a.join({signal:o})):yield n.pingNewContactQueue.add(function(){var r=e._asyncToGenerator((function*(e){var r;return null===(r=n.metrics)||void 0===r||r.kadBucketEvents.increment({ping_new_contact:!0}),n.log("pinging new peer %p before adding to routing table",t.peerId),n.pingContact(t,e)}));return function(e){return r.apply(this,arguments)}}(),{peerId:t.peerId,signal:o})}catch(e){var s;return n.log.trace("tried to add peer %p but they were not online",t.peerId),null===(s=n.metrics)||void 0===s||s.kadBucketEvents.increment({ping_new_contact_error:!0}),!1}finally{n.pingNewContactTimeout.cleanUp(i),o.clear()}}))()}pingContact(t,r){var n=this;return e._asyncToGenerator((function*(){try{n.log("pinging contact %p",t.peerId);var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(n.network.sendRequest(t.peerId,{type:tO.PING},r));o=!(s=yield l.next()).done;o=!1){var c=s.value;if(c.type===RL.PEER_RESPONSE)return c.messageType===tO.PING&&(n.log("contact %p ping ok",t.peerId),n.safeDispatchEvent("peer:ping",{detail:t.peerId}),!0)}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield l.return())}finally{if(a)throw i}}return!1}catch(e){return n.log("error pinging old contact %p - %e",t.peerId,e),!1}}))()}get size(){return null==this.kb?0:this.kb.count()}find(t){var r=this;return e._asyncToGenerator((function*(){var e,n=yield GO(t);return null===(e=r.kb.get(n))||void 0===e?void 0:e.peerId}))()}closestPeer(e){var t=this.closestPeers(e,1);if(t.length>0)return t[0]}closestPeers(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:this.kBucketSize;return null==this.kb?[]:[...this.kb.closest(e,t)]}add(t,r){var n=this;return e._asyncToGenerator((function*(){if(null==n.kb)throw new Error("RoutingTable is not started");yield n.kb.add(t,r)}))()}remove(t){var r=this;return e._asyncToGenerator((function*(){if(null==r.kb)throw new Error("RoutingTable is not started");var e=yield GO(t);yield r.kb.remove(e)}))()}updateMetrics(){if(null!=this.metrics&&null!=this.kb){var e=0,t=0,r=0,n=20,i=0;!function o(a){if(vL(a))return a.depth>r&&(r=a.depth),t++,e+=a.peers.length,a.peers.length<n&&(n=a.peers.length),void(a.peers.length>i&&(i=a.peers.length));o(a.left),o(a.right)}(this.kb.root),this.metrics.routingTableSize.update(e),this.metrics.routingTableKadBucketTotal.update(t),this.metrics.routingTableKadBucketAverageOccupancy.update(Math.round(e/t)),this.metrics.routingTableKadBucketMinOccupancy.update(n),this.metrics.routingTableKadBucketMaxOccupancy.update(i),this.metrics.routingTableKadBucketMaxDepth.update(r)}}}var PL=[77591,22417,43971,28421,740,29829,71467,228973,196661,78537,27689,36431,44415,14362,19456,106025,96308,2882,49509,21149,87173,131409,75844,23676,121838,30291,17492,2953,7564,110620,129477,127283,53113,72417,165166,109690,21200,102125,24049,71504,90342,25307,72039,26812,26715,32264,133800,71161,88956,171987,51779,24425,16671,30251,186294,247761,14202,2121,8465,35024,4876,85917,169730,3638,256836,96184,943,18678,6583,52907,35807,112254,214097,18796,11595,9243,23554,887,268203,382004,24590,111335,11625,16619,29039,102425,69006,97976,92362,32552,63717,41433,128974,137630,59943,10019,13986,35430,33665,108037,43799,43280,38195,29078,58629,18265,14425,46832,235538,40830,77881,110717,58937,3463,325358,51300,47623,117252,19007,10170,20540,91237,294813,4951,79841,56232,36270,128547,69209,66275,100156,32063,73531,34439,80937,28892,44466,88595,216307,32583,49620,16605,82127,45807,21630,78726,20235,40163,111007,96926,5567,72083,21665,58844,39419,179767,48328,42662,51550,5251,37811,49608,81056,50854,55513,20922,18891,197409,164656,32593,71449,220474,58919,85682,67854,13758,35066,3565,61905,214793,119572,141419,21504,10302,27354,67003,46131,32668,15165,64871,34450,17821,2757,11452,34189,5160,12257,85523,560,53385,65887,119549,135620,312353,115979,122356,10867,193231,124537,54783,90675,120791,4715,142253,50943,17271,43358,25331,4917,120566,34580,12878,33786,160528,32523,4869,301307,104817,81491,23276,8832,97911,31265,52065,7998,49622,9715,43998,34091,84587,20664,69041,29419,53205,10838,58288,116145,6185,5154,141795,35924,21307,144738,43730,12085,8279,10002,119,133779,199668,72938,31768,39176,67875,38453,9700,44144,4121,116048,41733,12868,82669,92308,128,34262,11332,7712,90764,36141,13553,71312,77470,117314,96549,49135,23602,54468,28605,6327,62308,17171,67531,21319,14105,894,107722,46157,8503,51069,100472,45138,15246,14577,35609,191464,1757,13364,161349,32067,91705,81144,52339,5408,91066,21983,14157,100545,4372,26630,129112,1423,29676,213626,4397,88436,99190,6877,49958,26122,114348,60661,29818,293118,50042,179738,16400,163423,89627,31040,43973,36638,45952,5153,1894,109322,1898,134021,12402,112077,68309,190269,69866,31938,107383,11522,105232,11248,14868,39852,71707,186525,16530,38162,106212,11700,5130,16608,26998,59586,108399,230033,43683,48135,82179,2073,5015,196684,189293,16378,23452,8301,35640,11632,214551,29240,57644,33137,91949,55157,52384,117313,5090,17717,89668,49363,82238,241035,66216,29066,184088,97206,62820,26595,4241,135635,173672,8202,459,71355,146294,29587,3008,135385,141203,14803,6634,45094,69362,50925,546,51884,62011,83296,234584,44515,56050,89476,87751,19373,12691,149923,19794,13833,35846,87557,58339,2884,19145,25647,12224,11024,77338,64608,122297,53025,7205,36189,36294,170779,21750,7739,173883,75192,35664,224240,113121,30181,26267,27036,117827,92015,106516,55628,203549,67949,60462,60844,35911,20457,1820,920,19773,8738,73173,181993,38521,98254,76257,46008,92796,5384,26868,151566,22124,2411,15919,186872,180021,28099,152961,78811,80237,62352,102653,74259,184890,16792,123702,224945,29940,19512,75283,14059,112691,92811,233329,20411,138569,53341,109802,50600,134528,66747,5529,166531,31578,64732,67189,1596,126357,967,167999,206598,109752,119431,207825,78791,91938,10301,27311,24233,252343,28831,32812,66002,112267,90895,8786,8095,16824,22866,21813,60507,174833,19549,130985,117051,52110,6938,81923,123864,38061,919,18680,53534,46739,112893,161529,85429,26761,11900,81121,91968,15390,217947,56524,1713,6654,37089,85630,138866,61850,16491,75577,16884,98296,73523,6140,44645,6062,36366,29844,57946,37932,42472,5266,20834,19309,33753,127182,134259,35810,41805,45878,312001,14881,47757,49251,120050,44252,3708,25856,107864,120347,1228,36550,41682,34496,47025,8393,173365,246526,12894,161607,35670,90785,126572,2095,124731,157033,58694,554,12786,9642,4817,16136,47864,174698,66992,4639,69284,10625,40710,27763,51738,30404,264105,137904,109882,52487,42824,57514,2740,10479,146799,107390,16586,88038,174951,9410,16185,44158,5568,40658,46108,12763,97385,26175,108859,664,230732,67470,46663,14395,50750,141320,93140,15361,47997,55784,6791,307840,118569,107326,18056,58281,260415,54691,8790,73332,45633,7511,45674,143373,14031,11799,94491,35646,96544,14560,26049,32983,25791,83814,42094,231370,63955,139212,2359,169908,3108,183486,105867,28197,32941,124968,26402,88267,149768,23053,3078,19091,52924,25383,19209,111548,97361,3959,24880,235061,9099,24921,161254,151405,20508,7159,34381,20133,11434,74036,19974,34769,36585,1076,22454,17354,38727,235160,111547,96454,117448,156940,91330,37299,7310,26915,117060,51369,22620,61861,322264,106850,111694,15091,2624,40345,300446,177064,1707,27389,54792,327783,132669,183543,59003,17744,20603,151134,106923,53084,71803,279424,319816,11579,21946,16728,38274,72711,5085,83391,88646,40159,25027,34680,10752,12988,54126,30365,18338,100445,230674,44874,84974,143877,123253,139372,28082,91477,144002,13096,219729,46016,50029,42377,14601,6660,58244,58978,23918,88206,113611,64452,17541,41032,10942,12021,49189,10978,40175,37156,10947,71709,106894,112538,57007,137486,150608,152719,40615,7746,279716,13101,19524,28708,40578,72320,1096,182051,94527,51275,22833,45164,81917,77519,48508,5421,140302,37845,149830,5587,27579,5357,428725,248187,6326,206760,39814,32585,89923,44341,288753,284443,96368,31201,94189,119504,20359,52073,103216,179,27934,32801,96035,34111,34309,101326,18198,20704,210266,37643,27880,141873,106e3,19414,56614,167714,66483,107885,86602,4379,20796,75467,4987,5017,118857,26003,34308,114428,29198,6686,29697,73632,3739,69795,16798,41504,7207,30722,21436,36735,28067,28545,3239,11221,36031,41889,100010,19247,317673,29495,174554,6424,129725,53845,94986,7955,59676,2604,191497,19735,102214,62954,23844,11872,179525,261436,34492,428,78404,142035,16747,17246,27578,37021,33672,57944,26056,135760,2369,61674,122066,31327,19374,157065,40553,130982,69619,71290,38855,72100,92903,95940,51422,165999,65713,57873,50726,7288,20272,2081,42326,22624,81120,57914,79352,19447,1684,72302,11774,302559,161481,96396,13692,414988,3721,79066,56627,46883,21150,11747,12184,5856,113458,176117,84416,52079,27933,3354,59765,141359,2212,216309,2555,23458,196722,142463,45701,44548,28798,19418,215,29916,9396,10574,114226,84475,13520,18694,34056,4524,90302,62930,13539,19407,77209,7728,38088,9535,2263,23875,183945,17750,26274,67172,10585,28042,22199,7478,51331,66030,26774,192929,31434,25850,50197,52926,178158,4679,181256,70184,229600,9959,105594,72158,73974,2726,35085,78087,23284,35568,51713,155676,5401,27254,11966,17569,223253,71993,103357,111477,55722,30504,26034,46774,35392,36285,214814,41143,163465,1051,16094,81044,6636,76489,179102,20712,39178,35683,125177,54219,30617,52994,25324,50123,2543,87529,58995,10688,125199,12388,60158,125481,131646,7642,133350,65874,3438,97277,101450,10075,56344,116821,50778,60547,98016,106135,13859,14255,16300,77373,173521,8285,45932,37426,4054,114295,55947,7703,39114,52,51119,128135,19714,60715,9554,50492,88180,2823,118271,52993,122625,97919,23859,37895,25040,33614,32102,20431,3577,9275,15686,43031,157741,110358,1884,40291,125391,13736,5008,64881,87336,77381,70711,43032,49155,118587,70494,4318,10168,30126,12580,10524,280104,104001,145413,2862,84140,6603,106005,13566,12780,11251,42830,571,179910,82443,13146,469,42714,32591,265217,424024,92553,54721,134100,6007,15242,114681,59030,16718,85465,200214,85982,55174,165013,23493,56964,82529,109150,32706,27568,82442,5350,14976,13165,44890,60021,21343,33978,17264,4655,22328,27819,75730,16567,55483,14510,17926,45827,150609,3704,7385,272531,161543,76904,122163,52405,2039,19165,41623,14423,228354,3369,176360,85491,7122,35789,303724,4465,13628,2233,55311,118771,20713,10006,221519,45115,71021,35650,29775,7337,10864,20665,21142,1746,15080,1624,32449,10905,105743,229797,7701,3940,22997,178467,57208,389057,39683,59403,63344,63125,54847,69691,18336,56448,3362,37202,18282,29648,138224,35867,10495,5911,28814,26653,31514,176702,26550,45621,11734,4525,40543,73944,121080,27858,155561,14887,44670,30742,8796,107455,113472,56369,75581,183777,240095,133699,153299,8768,160464,26058,49078,103971,21875,71486,44888,17156,9678,89541,123019,102337,3972,83930,21245,87852,109660,287918,183019,686,10100,39177,283941,11274,24736,26793,26214,25995,77011,141580,4070,23742,46285,46632,30700,26669,19056,35951,115575,174034,56097,35463,87425,24575,44245,38701,82317,85922,281616,100333,147697,61503,7730,84330,8530,59917,61597,17173,9092,32658,90288,193136,39023,20381,56654,31132,7779,1919,1375,117128,30819,11169,40938,23935,115201,101155,151034,4835,11231,74550,89388,59951,91704,107312,167882,115062,12732,72738,88703,464019,158267,57995,60496,737,14371,123867,4174,243339,159946,7568,16025,134556,110916,38103,191,80226,88794,29688,27230,10454,76308,57647,77409,113483,66864,14745,19808,12023,46583,84805,16015,17102,2231,20611,3547,95740,250131,34559,108894,8498,15853,159169,148920,20942,2813,93160,45188,210613,45531,52587,149062,39782,28194,57849,60965,84954,89766,84453,100927,16501,27658,165311,103841,54192,207341,19558,20084,319622,5672,205467,98462,61849,36279,13609,147177,24726,165015,209489,59591,31157,6551,117580,75060,141146,277310,21072,22023,106474,63041,137443,122965,68371,5383,42146,98961,113467,30863,23794,4843,99630,30392,82679,13699,241612,33601,93146,24319,18643,32155,95669,40440,15333,34089,67799,142144,58245,38633,114531,117400,77861,188726,5507,2568,8853,10987,107222,2663,2421,11530,13345,30075,41785,118661,104786,17459,12490,16281,71936,193555,17431,5944,71758,26485,77317,20803,367167,158,7362,93430,11735,172445,46002,11532,54482,930,62911,2235,23004,179236,4764,101859,208113,22477,55163,95579,14098,67320,162556,90709,156949,3826,57492,4025,34092,87442,104565,6718,186015,28214,14209,10039,107186,233912,58877,81637,55265,39828,6194,145813,50831,105849,4974,88319,122296,10272,197216,95714,51540,72418,23324,91555,8743,140452,250249,51666,34124,7229,38592,129641,78169,174242,22464,149964,51450,14034,10026,95376,26190,120062,14401,8700,265,31386,143573,7203,229889,61567,4227,140981,2466,72052,10787,10062,30958,6099,38471,30103,23202,208101,70847,467,58934,32271,32984,36637,24107,30771,17109,73353,13650,2098,157040,67366,66904,106018,265380,107238,18535,44025,32681,144983,62505,91295,56120,3082,77508,10322,63023,36700,81885,224127,16721,45023,239261,111272,13852,7866,149243,204199,32309,22084,42029,38316,126644,104973,14406,43454,67322,61310,15789,40285,24026,181047,6301,70927,23319,115823,27248,66693,115875,278566,63007,146844,56841,59007,87368,180001,22370,42114,80605,12022,10374,308,25079,14689,12618,63368,7936,264973,212291,136713,95999,105801,18965,32075,48700,52230,35119,96912,32992,8586,16606,101333,101812,14969,39930,759,193090,27387,42914,12937,5058,62646,64528,38624,25743,37502,3716,4435,30352,178687,26461,132611,42002,138442,35833,59582,16345,8048,60319,49349,309,47800,49739,90482,26405,34470,63786,32479,85028,39866,47846,11649,23934,29466,2816,42864,31828,7410,74885,49632,47629,111801,90749,19536,18767,105764,59606,21223,10746,76298,22220,39408,7190,79654,64856,11602,82156,272765,17079,70089,245473,51813,184407,384678,1576,122249,5064,27481,6188,25790,74361,27541,318284,45430,31488,620,93579,45723,192118,22670,51913,4162,70244,35966,26397,16199,50899,209613,121702,287507,2993,36101,132229,67345,33062,76295,118628,78705,52316,34375,107083,107454,44863,127561,33964,3073,154010,190914,55967,39074,6272,31047,5550,41123,26154,98638,47110,19998,148091,50229,31329,59900,195442,19106,61347,73497,70015,682,45850,25776,38022,148951,6288,37411,232526,109277,27286,32342,9262,5220,16651,23175,46740,129438,78614,121925,66914,88710,127952,5563,21500,34521,10739,14863,191006,62956,17359,16749,67027,56284,69134,43301,35039,58883,54466,60823,404451,75743,59856,86979,7923,34273,83785,32142,7693,268986,197428,282681,17049,22346,22990,92245,107180,3357,37104,96724,49153,7683,31197,43267,82231,164276,23696,20848,188364,22309,24821,158707,1018,22514,70922,27792,45589,59709,10765,736,35218,63479,51987,24275,63588,55361,92929,81964,4658,20122,12330,44058,13065,311456,72224,8337,211229,38979,22590,138478,52757,32595,133600,8838,31549,94412,43391,90056,1585,94802,127271,6223,31889,137038,132910,2165,57616,230152,6080,10748,36737,74579,134062,50525,180532,119270,34556,76155,82394,52595,29258,31435,87820,67996,26943,183878,38007,2410,13526,180297,69856,3503,187396,167700,7838,16701,9199,56267,3661,37407,65994,23767,5708,62508,221700,67088,86978,46776,84434,32088,5612,9149,88244,21685,95151,46750,189612,2979,506311,2594,3628,40074,105039,78243,28523,6651,38058,71999,30992,12764,68261,108991,6165,26450,61961,13400,22426,7490,60890,109623,2070,12958,50355,67979,257096,7213,42578,52121,35716,65461,7516,124758,39268,302,64712,14977,1467,219452,2840,34229,11121,21602,19270,63574,8024,1532,17331,79839,78885,52029,180767,57957,6069,91265,61380,55767,8927,32881,287603,22149,35029,68876,6428,199567,46926,13412,104132,21434,366616,45060,110046,81924,128910,45886,52821,130416,29416,77342,21762,67329,121432,79924,11724,38625,81006,102033,28338,13326,3250,82056,82526,38212,21112,12382,111495,3263,7414,86274,93490,40844,30224,45212,24019,48411,71367,24941,76729,57776,3769,38114,202019,197745,31953,237533,33270,201580,255648,100798,44741,32241,98468,106931,10085,15090,170358,33154,66787,18819,69760,25061,234005,82660,6295,131975,16874,9076,4094,25005,17740,40908,19533,220019,44330,99792,50040,19619,13950,55228,24423,31253,95308,103177,184795,28590,82285,5059,3210,75525,49894,70007,56178,10580,36051,139681,21617,98736,3555,106306,164189,37352,63915,47824,24883,145530,61904,28444,11483,19837,145446,30420,112972,85939,11835,191233,2262,20705,58630,1753,148334,1197,144714,6887,11223,107667,60879,77914,4151,57417,81594,96681,169430,1784,20444,95138,254041,27038,596,7117,72808,13759,3353,126776,21074,55322,27081,36942,39547,139830,179275,4453,713,8722,71399,19204,25785,22794,23923,104114,11291,25458,102309,88396,75288,230440,206396,104551,58447,130857,37247,94734,31548,176529,226077,65159,20104,10096,66881,94191,237909,27109,37404,1520,27421,25220,113003,23423,24884,50585,6286,231877,150800,11789,3226,90004,60642,5053,202400,61442,132531,175329,57138,30116,103847,9973,75367,16452,32360,59119,21246,10191,164804,23305,61051,37348,154530,13214,5468,50403,66754,130976,50559,80515,14436,155492,84017,5472,43107,41240,2890,90431,70188,382,76234,48040,50211,281038,237007,32115,142178,1536,22761,96429,1811,31243,1679,49143,55209,17402,235054,61494,7462,77030,34925,87609,78002,9499,9027,73289,201078,101379,63544,27666,5469,10642,30029,49816,132979,95620,58086,351930,116300,2110,2043,30845,6154,11279,16727,4122,2277,27281,4971,3650,39060,61970,65951,39674,75686,38151,11370,130809,177895,32665,63725,122267,7857,39618,118483,44792,157755,178624,136994,24260,41308,22471,12404,21707,12486,30473,52781,50246,20247,39065,909,56825,103158,128603,31542,1089,41935,32744,12428,37963,84420,33134,72921,208449,42622,168151,127335,147107,46699,38216,12591,94342,85814,31423,24944,2605,87542,67473,192551,4496,56321,91819,17630,6300,256183,114569,202090,33209,35289,34897,24967,40520,43470,5344,10199,34810,14283,10381,10017,62923,49924,23233,64539,13051,35686,19698,11570,135555,120868,44924,87065,52318,52335,47586,140906,245885,109834,78668,9065,46990,25258,72022,61243,40838,4545,146387,10537,11557,17470,36930,68104,46711,24264,79401,81043,18225,120488,24746,84338,81652,28266,13776,21878,46973,1047,230465,73357,95777,24973,210160,62210,58404,110633,169651,6937,41870,9909,26822,191062,76553,27519,96256,239070,2478,205678,67955,58532,20601,50120,19148,78501,195724,110740,8249,109665,27446,30568,57631,31425,49752,32820,65504,50079,3663,102256,219898,23849,211315,14645,4359,91767,9528,12449,49366,7941,49763,107848,8930,27086,50686,9744,10447,81935,39513,46514,1670,29229,6172,22312,137280,97759,9806,14445,22976,56458,73391,34983,93760,174219,52573,33149,59747,2429,136277,75123,165263,91040,7446,57632,48633,97140,246081,84766,151684,79918,93268,120346,54059,54875,77858,32996,103590,45276,11968,19600,25849,17159,132907,42828,16817,4913,99462,103303,27395,5737,74184,20749,21160,14377,77062,131403,158735,10999,27799,77785,9320,34366,51593,61070,33746,47048,29268,36675,30262,53297,9832,82e3,20188,122292,39917,7331,18160,68301,185935,134830,15031,4935,10004,165845,185534,46923,30109,44134,122631,18874,22903,112790,26561,18549,348902,82871,140345,255565,135390,63556,103747,145055,179600,145662,296111,61661,211987,23952,52342,126343,48450,32919,44277,82185,9591,62139,205363,376969,394874,108461,18040,120885,14798,39863,16571,16794,58271,81025,55206,14640,118656,6361,44092,85970,6262,153863,108244,180200,72264,79947,38044,10050,5735,61221,80712,5471,115689,11391,11661,184257,20010,60116,30320,19327,134598,45455,27542,18004,125092,452272,1549,91523,46567,180063,156026,2608,11174,58848,37788,65907,80194,30490,5786,40775,119519,106241,11323,156297,8425,61495,2617,29675,2425,59886,112582,49142,59618,4863,50597,86710,50650,168632,27693,85641,83643,18993,25768,84284,28090,93592,36627,312804,43381,9887,9402,100931,97165,3311,173330,66805,28935,4963,184460,3201,78102,19126,21607,37496,24938,22615,16153,32862,134792,153318,61120,6067,2812,12826,12792,23825,37559,64662,202250,102694,155488,85881,149193,46233,65383,15521,106982,11358,176786,25752,39717,34208,24510,32464,77742,39371,72028,138229,60688,71386,102834,132477,2208,11548,63670,271279,28351,30338,38620,32491,99845,143885,152266,13252,2825,178663,108097,1775,78201,14897,113573,163346,62292,171129,22183,96598,38733,64971,166776,117445,9968,146393,44677,74867,20908,97328,12761,25656,26785,9148,112344,26115,99176,110121,22437,49547,6180,79320,5835,31392,43328,33377,75870,119860,69497,80273,7325,155219,43167,111173,28347,20222,3763,71752,55041,47252,14618,28088,15012,97805,194698,54636,2036,41349,6173,96604,61530,51859,43782,13361,24334,22668,24792,7070,23441,16789,3209,36211,208475,26242,32880,122181,182407,21444,31060,88459,29929,77907,12716,10934,97005,20599,31690,8403,58445,30303,22700,10336,86731,103115,337709,72556,46788,112566,47684,67089,53548,36874,56487,41387,125985,26893,40071,106683,73712,18787,40105,72992,67246,137276,50802,36790,70328,138827,22466,39263,183295,29858,50975,9322,57397,10654,24364,30383,55799,41600,23584,127295,296610,129078,143558,244131,86397,36049,1085,80677,3820,108139,5476,34767,24683,7758,13060,7239,131671,250593,59556,103392,29810,4188,252323,39404,116877,7651,43600,40338,13554,157253,39196,25978,144387,61211,234,50104,6129,10449,93777,9240,356378,274148,4439,72970,3724,147770,78680,62570,115877,40027,40547,36817,224392,64609,34795,165027,67440,2477,37206,23431,50754,164797,46018,94995,170982,27051,7957,22767,3674,27900,56419,18930,60701,41302,2692,84749,339721,61996,111094,80221,50129,1045,8153,62945,19202,8250,37208,37418,32560,79477,41106,88569,33963,36693,5892,30570,1581,66471,49647,11922,160717,29442,5643,114865,82962,95982,132098,22633,22838,94726,54556,28566,205039,162340,33216,16849,35847,221339,94851,26533,71469,1805,3804,12935,45483,71020,36310,65381,192960,34240,35165,59773,1248,46954,155332,96864,4246,388800,16129,57133,74592,44807,442014,38203,42574,80818,91592,26377,36424,65760,977,77387,22628,147610,28018,30561,98454,6969,119628,63648,18170,36854,26601,64018,22027,37279,51395,152934,21153,9430,58760,194742,5330,55115,34158,28917,174111,13171,122326,1526,43896,66094,25325,4234,148354,11450,275,18999,112191,44365,22723,68409,8733,57746,96565,75007,14196,108844,29475,88599,177563,100792,106156,86323,93726,14248,135341,194131,40126,47099,14779,8272,39597,95983,171398,65882,28052,10393,47213,40689,22120,72212,106829,34964,109146,753,648,21660,30047,17527,181025,5619,145357,4085,216883,9359,186951,24779,53931,24545,36197,223296,62628,168101,4243,107313,30321,26642,13049,51059,31027,107912,807,73550,26551,84369,122422,165872,49754,74213,234264,33151,52014,33100,87183,22365,52500,40013,23302,5652,72723,21404,26107,48434,587,94049,168493,96418,32871,70860,31709,25128,443,71597,166253,15670,70994,26341,133675,28280,75491,54756,47955,56028,26182,11952,113272,472197,64640,110753,17919,337,50642,22576,142,87371,53391,93210,126694,15285,19642,85667,14148,1506,42092,52962,33243,11970,20734,135843,57044,58880,13002,219134,22876,64754,232519,4257,43120,321573,24799,64526,124728,52579,81472,70831,276848,17403,74359,23021,182101,74597,23744,148267,12055,7976,5349,11772,67540,167347,65318,18720,127832,108238,22828,90233,9987,259080,118185,73209,79270,13775,90100,137742,90799,70569,15699,19961,9087,67475,57872,39731,8810,134897,131868,146849,19898,3334,2281,167061,91073,60356,467742,74712,188,53179,137679,92769,29241,9537,132595,80119,1041,88962,5976,40171,44911,102859,139059,104558,98987,47761,19272,71472,113864,175377,73338,10857,23402,23758,1591,139864,5644,4076,118760,16427,134198,18853,20291,100849,37423,22038,36677,19071,195521,57445,11069,31869,55718,66882,148490,44,41296,75242,49704,166810,9906,20943,122258,49112,105667,15969,10344,6408,187694,21399,72742,58970,14867,14376,81889,41856,23225,15042,56993,16074,131389,74276,72407,53875,383108,53597,37363,68993,44854,122548,430927,198279,38430,80409,12245,2981,628,2818,17760,37437,238229,7968,46892,2200,3730,34190,65983,37959,112291,87850,70827,6522,20750,73913,111621,41652,19587,2780,58668,25916,85259,18200,168962,95781,42445,102050,7776,57662,103313,47742,96358,41964,66174,100396,29069,204735,19679,27978,7479,40264,22534,61183,36081,107436,58223,14680,23002,101311,24716,124108,12908,5646,31750,40380,14215,232799,102772,14122,96775,61398,50917,12096,149880,67833,598749,124194,155871,49216,790,14677,65319,56917,7440,145744,95701,12206,49405,129269,76199,45732,9767,11058,9047,210885,11051,7392,26307,2130,8132,147526,20802,232698,115660,50060,59789,57344,107623,80343,112676,23291,9866,160971,34032,118291,15719,59730,164911,28975,2659,58046,78480,21854,66209,53863,109085,116045,29021,46481,107552,22130,18764,70254,31272,11300,52460,43933,84738,20721,53869,190840,79673,105300,7561,321817,66924,13940,33281,101046,183181,32176,71878,5678,62924,79535,56646,40303,19559,27703,93042,73368,42187,3670,37376,46440,7023,36816,109628,20680,5940,276440,275233,170848,112093,136996,14984,20226,111441,77693,112960,48577,39370,55707,50314,123404,26570,54281,61372,123391,4857,35928,246740,132507,106646,44241,7196,92258,9825,37688,51197,303141,5590,15476,132986,10955,85782,34486,26696,7991,28813,18858,39546,11703,11365,38185,5716,93555,11925,40121,60002,6985,10976,171384,3887,43394,13337,56346,6381,252336,39573,75042,53711,1028,31781,44295,95925,131713,7214,68125,43571,70954,213234,1628,8760,13391,65485,17320,56038,1710,25248,60803,57399,19839,3870,326,281556,50945,72400,21460,316244,75619,56246,98775,481,13513,55765,50427,7388,123519,32929,57908,27124,61316,101097,57467,30228,48792,10788,20402,37318,50526,155730,34456,158065,145305,17832,43733,64052,4506,35072,205355,177028,184004,187081,68616,35938,83703,10367,36892,93186,260137,51934,89970,4985,23445,26755,21558,7948,78741,23376,124405,85594,68596,57536,49351,12619,56593,132668,99924,109728,71844,71935,196018,65464,17617,14987,89701,143773,33997,8687,22701,33258,2914,4436,72108,85610,9671,49067,2327,82988,1361,1672,44033,35777,30269,24057,10605,82236,616,15793,13919,47249,112086,116698,9484,80207,90574,33304,68624,93127,56101,42210,160929,4827,38995,38095,4701,125119,5027,33680,9236,231236,14135,87837,23318,70261,78893,30151,81482,14332,1084,74256,27532,46644,79185,3148,62615,6981,55672,31668,36825,1849,14536,37446,14738,23779,43058,162749,72199,1168,21346,5592,85932,85302,9668,18351,57135,150360,2080,228015,77953,34670,119302,151751,31009,106725,84265,45214,59289,74178,113071,263206,111009,4021,44449,188119,192629,123592,392506,292847,114487,12831,205858,9852,20780,79648,75767,357014,97721,18166,21005,67950,33226,204009,16536,2987,11335,66717,144910,47950,17262,55060,15063,2934,51038,26775,178497,66008,3427,49433,128592,20036,157553,63861,3089,23015,51210,28696,35933,49942,71135,231518,99620,17248,21835,176536,20676,16944,38700,165831,233253,295625,36723,13023,52745,10907,19423,67972,125868,95473,82875,1183,108455,52685,33417,64095,21433,52438,33191,127809,44505,211823,7810,2752,95548,162031,7185,91196,47563,61721,33359,17897,23682,42806,178101,22874,49707,199897,75419,82456,8618,11171,79712,116847,18783,44190,46564,5346,59046,95032,7893,14916,3214,26800,24172,121453,34362,10250,17408,18888,4840,68696,22831,13162,36005,32512,14800,62357,41723,45046,27247,37486,5372,2564,34261,298500,66509,133920,89138,31305,117697,19097,108304,81386,84106,23802,46411,63304,946,51417,41777,41041,19501,115864,60743,294354,37955,94165,18116,1156,17937,20645,57114,90804,58042,48643,92288,9861,2557,88546,61333,101008,12853,5148,87856,4152,144503,73841,18718,9789,147565,10846,42085,12789,30223,8993,56352,67203,2448,28215,6052,23540,126319,75933,36689,80235,23231,23561,21383,38800,77548,102798,21234,31468,158608,46188,63960,191679,8051,67014,11185,170078,42186,28827,34777,41930,212079,12421,34750,24111,110344,73918,45171,70826,141949,40063,23979,24254,37309,26724,27179,24718,83648,54938,14591,17425,29525,102675,48975,48654,12316,8929,60640,41709,50168,63264,89812,50716,48632,38755,138583,160123,55579,71829,24230,233277,46322,39650,166388,34718,24108,98252,7031,106695,62498,18258,35062,217827,78731,34824,33354,19520,60852,2432,60224,8587,2836,62955,702,20227,42285,40560,95592,62486,11094,53035,143291,18842,46177,77994,1770,9657,107422,172915,32655,128716,25886,25164,156740,119928,165875,85817,11007,89110,33956,12652,65156,180266,8494,36889,19958,20955,96,1264,118288,135769,44754,86671,5632,19026,168220,289120,33569,93821,66144,70635,7687,5642,2714,55445,56636,71545,184182,93133,7332,37389,12643,52315,22729,11014,158742,17050,152889,50178,34601,41945,52136,9948,26914,63548,95721,115951,40759,8960,158258,38938,49232,48325,42234,81523,253019,66128,40978,20048,238048,38760,62928,122560,118532,43687,137472,163689,26680,9878,17448,51035,16211,60834,36749,29178,14241,59868,150086,2305,26477,42422,34342,165341,83279,33894,14257,29928,12743,13957,125571,89134,66712,10952,16507,147839,30146,7249,16565,45399,39874,114565,215780,31990,230881,171477,102,196546,44538,10880,84948,281705,86651,10617,31395,2342,453658,43569,60561,132901,21845,17727,58556,258242,22262,58728,4008,77997,11806,37431,30599,81375,109137,185787,114085,217292,97453,169085,30593,60212,11544,102056,65580,2384,91655,4855,95725,7295,157994,16228,20669,53276,141590,105246,17334,25440,76067,17967,39321,38911,11362,28559,63807,21627,26468,85816,40120,1025,15234,58319,69516,66512,124548,75845,78873,22137,46681,51242,85683,32909,76747,35555,43396,101465,1765,73094,1077,2962,39028,66777,57831,42048,15828,13962,36041,63657,52412,5242,58846,2141,5506,219012,134451,3936,182230,17558,17153,152237,22621,49377,170216,35257,68233,65374,6510,11126,212151,7184,2480,22517,3437,33073,30156,16557,3768,55067,86829,91e3,12350,148650,66017,79424,70885,49066,28250,21369,51213,34533,11510,3258,18176,18465,84413,6315,36411,163765,4346,356,107618,598,13727,285026,162695,8749,14583,7132,63521,184253,32378,25991,5604,30961,53675,4874,84693,5086,34811,26978,56564,7904,33519,51221,113942,69253,6664,125563,22055,220680,102008,742,51930,19494,176108,44424,35123,13025,75685,11759,74335,22250,181453,131147,16984,132115,154311,11991,76452,52609,85351,196,30969,9198,74919,2529,56838,71779,29187,116304,3504,62330,41190,86153,28393,254926,104228,105189,13264,84359,3574,12415,8534,57147,10175,188174,59504,60932,66318,16407,107921,17638,99103,49278,28403,39786,145865,8462,3558,43406,142271,29139,21989,36552,93955,72365,7176,13556,106185,37957,321774,17782,129017,51154,27938,24952,1935,39366,2791,33489,41582,56078,24558,9311,5449,218786,27808,190429,68013,36020,86003,29735,3404,87348,119357,115714,2324,86796,81973,40992,43376,93621,28784,16808,36367,2517,2909,191926,24978,55303,53308,205724,60068,3098,21375,64784,23949,26579,63121,12319,80145,39967,97861,6757,70143,67642,37082,34698,69140,122883,46151,62187,80934,429,19437,135071,137885,222647,13331,154065,327,61778,74257,40116,37493,14855,85079,237641,42342,102164,199965,71204,4662,29368,5042,113914,122214,8955,13149,102503,43173,5659,163787,69003,307084,63392,171080,21390,81918,86666,36622,24126,28887,5736,28054,207170,163428,79891,346467,95363,38980,111806,80828,9200,19288,294896,114468,87405,111715,141705,7015,72754,68463,48738,243147,33397,101210,37051,98801,82847,20397,4940,185559,18716,54718,83491,11725,40803,1128,12128,23060,5174,7745,67007,46701,1571,27807,180186,256996,18975,16837,7877,212758,250379,15440,87954,57755,24719,124057,83461,258,50864,8874,29038,71289,31627,15429,9005,4061,113851,107716,82819,13651,79656,117851,17539,111446,12938,39724,190787,4352,15402,21070,62708,8539,23777,73853,13552,38810,86117,16285,56400,1718,75342,142863,29033,378,110113,180321,32586,23606,26393,160984,207987,23783,8406,16904,24596,47274,11693,46539,60524,78595,48423,31718,20170,9009,146268,15183,191060,172765,1349,138436,37365,10970,40509,225817,20021,70394,152138,21541,66559,66544,89352,2725,17258,91345,7313,3815,115868,8660,40362,4071,103524,39388,118275,21950,6549,38226,32754,209574,29201,43495,18028,20296,40597,18370,47520,202450,24134,2219,8195,69545,38041,136934,46374,19041,159811,84865,58620,846,98749,13569,30714,97246,32186,4479,27355,92973,35214,151491,75963,37631,1561,27200,238083,23182,60756,12291,25766,39355,102333,87362,65741,59906,19538,201575,48772,102938,24438,292580,39964,66366,9004,61379,50548,37622,38732,28379,68180,76622,17488,69849,5963,7219,48143,43413,55358,540,58691,29506,19245,52193,48621,5518,13048,118625,44755,191081,42061,89197,2259,60665,66994,71210,51232,3585,142096,55024,7892,8345,58653,463307,65658,64319,137941,136323,53499,12746,43492,6978,95163,29925,60175,5128,7352,41463,184756,121146,20473,18426,4598,5309,54580,14277,121151,10691,56711,43880,63409,76682,11830,172218,264898,32632,66536,81062,31649,25788,92774,60222,11100,63159,9432,224657,25240,53613,152,138620,163829,2397,85345,12501,37507,64932,38575,43522,65789,80198,78796,35226,3851,108891,73311,3060,28391,93671,39663,46142,30982,66041,37281,68157,26553,71872,81142,211527,39747,118119,22695,2859,11066,20232,168911,7933,197005,17066,111071,44434,133994,120798,12766,227798,45756,132852,29917,36076,55352,65281,129800,41958,18944,84678,18580,168093,132621,39997,54092,27740,32354,3770,114118,103242,43918,15899,18574,145944,3190,123469,219903,24169,100571,62403,16776,92779,14535,17168,16475,14304,37231,1712,28218,242754,61688,28980,1318,51359,222657,99200,67989,31772,23932,35351,201251,49041,27306,19128,40135,3986,77333,19649,120683,151927,21081,7076,78375,77501,101599,8011,89585,96715,58179,5378,102138,106793,26051,217276,4197,16297,27014,46721,13322,22806,5278,29629,70632,9647,71519,58818,40603,128530,8903,36770,56900,31483,26935,43845,34265,34920,87658,6114,84767,64250,47318,50720,19264,162514,33357,13117,6705,46696,75032,71054,87004,42035,69138,11903,99854,102328,19611,34525,69312,6431,49842,101600,133178,108751,41829,89939,225664,48916,99556,9195,130387,5960,36857,116724,53518,94002,39077,53996,6945,22261,64291,8314,152785,57588,16522,9091,5048,87671,35441,39509,1945,12423,158923,178413,37549,14095,1475,73188,62878,4819,24012,68534,42606,4010,120809,57497,59564,101758,103718,32701,80116,12345,95834,46918,21468,53213,15665,31200,3867,5140,96013,250744,21016,10069,13968,35449,180829,27683,39704,59956,22893,3115,26293,32785,75934,62445,141162,62720,2018,83638,19949,114012,95006,3330,99829,130935,309272,9565,55874,121727,37017,23586,319858,40970,27602,8625,112329,61060,100088,118525,25922,16232,1907,60671,51583,44553,80993,5262,94679,8676,940,20736,11823,3020,16476,12340,152600,97416,3703,25744,66826,16245,16876,46446,84798,74227,176020,45192,61955,75496,23946,23626,40372,26036,6149,11822,30582,16541,41914,82385,232823,40921,80773,14930,3631,7517,39619,4348,36180,126106,138939,62611,1477,113512,47321,25052,14546,118881,29060,23589,128322,36795,18401,137921,104699,267929,36194,172791,18113,4766,188215,30083,332586,94089,5805,77909,22194,68234,154976,43220,40660,70001,184893,138095,11128,103010,22663,5108,212615,8485,5565,49222,54614,26530,42639,16319,55062,152662,105595,21114,22216,10294,68158,10436,86950,7206,62115,3977,3657,59874,456,118617,18156,106663,112229,80992,17442,8217,55551,5133,34344,251927,51153,39364,201321,7816,66803,23057,156724,145664,14276,95705,979,2796,6875,13429,212525,50602,26276,28284,3424,19465,52397,46963,31420,51399,206476,92317,48851,637,100820,83349,10317,60227,21972,6908,282439,32857,224767,95629,83882,42106,87338,69757,29840,68709,37665,45244,114577,49188,175943,54009,186746,106158,70168,3358,234002,50555,9221,129338,9562,20118,32923,78479,118280,65752,4977,10474,102174,60947,129006,10570,83451,8598,8078,159367,123785,80438,16742,5905,5281,181513,42402,6977,163136,93179,42191,14968,50421,112401,105440,33456,57347,121611,4221,94954,36517,24046,27796,6255,33394,72990,135408,116627,1233,57874,25654,95419,68156,401399,313338,55208,45573,93124,119251,47200,38196,11909,130667,45391,73904,64964,167846,4137,115606,52036,62214,7969,160925,7187,1132,134835,40309,73195,64494,80472,444841,61111,26500,45323,40743,53625,52797,22659,15631,29739,36706,28841,39147,102836,26794,10536,14845,87305,45874,12241,127587,83833,57183,79722,30844,41304,84655,20825,92500,3722,25655,27811,10157,81634,31362,34088,92487,70123,22190,185100,72658,139035,192523,88241,2078,230490,44528,85638,100198,22088,29982,291233,241062,13865,4445,137791,37835,107218,31726,19718,38234,72528,23046,19177,66695,5109,17251,28077,5617,21554,47839,72425,133825,1486,73065,181275,141508,21768,62971,63082,2512,34200,9904,120309,6392,91243,68416,268253,41199,116757,138551,185526,41246,28986,4093,19057,17295,4148,245766,122360,35356,112075,20301,75441,10998,7977,19769,62922,937,63547,100196,26427,157820,20983,236696,22935,8140,90315,156004,47204,140973,7726,45097,52725,22636,23436,257282,105247,522,88389,216031,202204,46812,211666,19693,68828,81691,45925,11256,30292,372,5236,167826,88328,232776,151611,5360,82104,18841,80393,25465,18285,20320,72377,31730,33160,45803,38715,27705,37379,24163,18360,103586,4015,32305,269494,91252,20080,36567,54650,7797,57073,12650,31164,42209,6375,261663,105528,81661,106002,2800,5375,17247,43151,4442,15727,194619,100855,144898,62320,78465,39929,16454,1967,28311,61363,17219,9395,8745,121445,76939,80385,162380,22009,54191,44248,16299,122830,48151,74429,78291,64755,14238,44966,2511,17712,67954,93583,829,105899,49935,84750,11591,33185,85447,42717,27409,208542,28965,62052,52525,5597,25694,65594,16343,63224,276188,12475,9331,127507,38522,57287,24128,133161,79723,105548,133695,48917,27558,43278,46520,13778,141954,110785,83366,17715,46317,105763,66298,147013,41086,94180,16478,220447,44611,730,19722,78975,117889,125643,26254,16574,18480,65006,15806,38549,246418,46052,36056,8440,34984,30170,3163,59800,4458,115442,4283,41970,33507,104078,1653,22,121158,276486,3655,6338,24048,133421,23641,2161,24422,36006,8086,10675,181474,12307,29514,59143,14729,52509,87128,122470,19446,80852,33314,24573,119864,14237,9652,57779,6612,51851,15284,98871,90581,124466,156831,21190,22015,71380,161906,87247,69201,18392,17908,108470,72962,40719,14338,17911,95260,43339,20610,78916,20710,72451,11315,31448,17263,58853,178878,48111,116002,45497,80506,82605,85880,36300,121755,25215,36118,301929,88728,405223,276136,553,34704,212438,49970,78329,922,20711,25036,257130,38295,145369,18128,15385,30829,55656,48345,8012,3561,28004,122041,192900,58338,112508,41085,29976,87040,47117,23905,4336,92061,138880,97407,42083,172121,6256,25192,172671,5,93568,1420,12677,31605,56743,40620,6015,78415,231077,31298,80026,13902,19048,24924,170586,32955,176119,87859,36731,6773,27711,24658,26475,115216,133207,93250,95820,88522,8317,5714,124047,55219,86860,19677,23961,22928,162209,8904,225992,359835,56084,96201,29392,96558,86071,93643,55114,13347,8183,95129,82012,2017,123336,34219,115554,157159,47747,101684,41008,18735,193781,104151,226906,7552,179874,124113,31159,21162,44010,14771,51268,166128,31382,73124,77438,92830,205709,12113,1292,38937,13114,1334,2118,15597,69581,14449,21934,76618,48728,67038,14967,51495,24243,87736,147249,26720,11119,46063,43749,5843,44147,152629,133428,65703,14269,45604,57982,28672,55616,45957,8438,95433,37698,220862,132034,39456,61870,4161,26501,73560,56418,9845,4654,20916,10456,88920,119358,9015,65931,96507,48029,38534,21676,109081,43078,34943,25089,6131,28766,23665,5477,10255,16695,67,45778,42443,42770,29534,23733,100513,62617,42630,48746,14191,43753,50295,26007,8792,57243,43119,54725,164253,58250,112304,131796,25165,4651,3188,24831,47748,3705,19540,13211,102095,5593,18699,23666,32005,117571,33541,60584,74573,86311,99443,25172,27222,168938,7143,11853,53560,18834,19960,86522,28217,53266,117700,72989,34323,18721,66450,34346,74056,47217,202002,46269,9429,68582,75458,37823,82843,96652,32549,145144,27958,19820,158086,31955,201406,135379,31207,192545,12950,51704,9094,248263,76147,64028,110009,79407,89345,99284,223492,47966,26848,15359,201137,2861,110507,71231,72297,31851,118777,71039,151051,240855,16333,50766,14727,7939,4149,80908,418780,88378,59276,1327,7284,38576,79814,65820,42199,84860,49574,62596,12396,70598,40117,8648,7994,16836,7630,14047,359699,106878,525,29037,28064,13380,11675,50669,74216,103539,180314,27449,56299,172344,19274,7301,246099,32043,19422,36506,129317,6806,30140,4614,46639,66926,932,86600,6322,27847,233103,10541,39025,34887,3517,12972,26220,2031,66561,115015,48658,47596,12714,33845,3893,16165,35237,89983,14769,11962,147224,47018,29977,27979,5552,82338,86023,131368,1218,24853,237840,132193,15455,40873,3668,65351,53388,15229,59889,272245,47934,11858,34347,18038,90853,86981,300602,19343,114181,29362,84921,6095,106059,79472,38015,1206,48741,6208,8e4,21916,17423,6002,108083,24479,34931,56661,9511,26995,100694,163853,35997,81254,58321,18919,171890,86877,91341,74503,70477,53412,7027,59281,39892,131302,5864,15947,61301,67466,162369,47956,27874,35624,282324,21270,111847,102548,41482,30955,116737,28264,8592,55458,22301,75090,29821,30697,51709,3041,19208,8038,24634,30467,87509,126428,19389,18814,152686,20701,83474,45832,80891,105808,11378,153223,120770,98186,150633,49838,9141,12755,30962,5260,74490,21256,31678,65062,33326,289838,187831,20595,89768,2805,58535,10844,70085,12090,2451,138068,98544,24461,4511,6754,41684,28203,3383,65355,82833,30161,83924,234361,128424,28921,222594,33975,125491,34069,11508,67464,144226,41850,98703,34371,7901,21254,38398,65651,23549,53883,213340,123269,12028,71764,177701,28758,2623,68395,11549,15232,68603,9660,63116,36079,57093,31198,20475,48467,89984,35619,186847,107469,31389,43631,73867,41949,68841,114250,1605,30564,63403,17588,27680,99533,12641,70325,50428,73426,78379,11855,91651,72081,91720,60198,15743,12065,83398,140046,6761,46598,45900,5068,886,62448,148968,37347,19405,9680,15819,43496,63370,75667,163700,37639,3633,22774,34341,183131,134335,37200,23915,7054,14194,12970,26438,13350,285521,25594,8219,104410,91039,168804,138480,149734,15907,33818,61132,60082,4622,110187,56736,13551,73571,3945,73463,65498,17758,263266,17593,2710,27585,54469,38200,45367,63754,28881,3473,12791,98287,31895,65787,4463,94536,24951,36332,59901,28803,52130,86403,7668,181822,74831,18977,9850,177206,145485,109798,7292,31421,26280,77211,58511,12507,127004,11113,147,8729,56208,43066,79926,129937,31345,83947,39915,46146,98763,42566,1337,13192,18323,105163,80570,117753,16555,72883,11077,159438,40764,70933,83329,26066,12276,72059,21655,173836,126713,69454,153482,91585,70644,102558,110483,6764,127864,190133,3961,101798,20945,71138,82402,90884,69669,44753,923,16939,59700,164258,25969,27082,31399,43846,6306,246093,51342,6153,151581,202801,182731,56475,162188,89426,141356,14355,121815,27536,28023,65257,77523,106668,127314,24947,12790,38796,169698,23555,10725,44573,183083,42088,62716,43265,105958,32050,44067,50118,1668,3874,6243,318411,16599,1691,94999,52378,28671,216728,123258,2059,34969,69225,5913,136280,171443,141515,91662,22175,135282,80020,92270,1663,4808,4482,3495,34691,5226,109830,108512,17342,107488,11606,123190,100247,29666,146527,113014,15794,30894,13224,39585,243192,22351,9903,7836,47699,11078,25468,122291,48821,26780,122679,75521,81450,630,4895,92900,55074,74293,17441,3563,111657,103102,51613,12318,52370,36191,68245,34269,40445,41354,122901,168604,182500,62012,42557,11259,24428,115113,86345,12362,3909,78430,86852,134602,20459,47853,93879,22577,7659,3688,38555,13349,17381,56715,91639,12493,10895,92438,3142,37057,28928,2004,36427,32268,34222,209974,10432,67436,41989,173518,107930,27079,62729,30908,55558,5828,45031,14902,53546,8204,144263,60255,14520,88212,86582,109589,69356,8064,47449,8505,66558,16886,4844,52817,111260,215129,12941,91118,650,20770,6273,73089,40618,62790,2873,35002,14023,97208,19386,102646,36993,143736,135457,35385,113601,17893,32627,84439,100619,56016,6581,57264,172160,45452,111710,203627,70131,24100,322787,1996,35665,70078,22358,90922,83658,4097,63200,58499,14542,99153,52159,6615,12414,63415,31986,16823,1579,65405,137809,8841,16898,48082,259,33014,42375,12260,179850,73667,91389,98882,29532,17311,326251,41092,5928,20742,44964,48019,43505,9317,49265,6643,192712,48424,163487,19861,20113,70848,31928,105333,23685,78563,14638,54755,7158,24142,44018,20774,125255,20331,24280,10163,1285,2336,39851,4299,117269,46714,63816,87779,159624,11731,9971,990,137317,108831,50994,74554,162680,23640,131597,146962,170620,34829,91205,21184,1913,63616,18427,93136,156592,17519,67565,115882,138220,78622,88535,18115,2711,33554,109492,54298,971,24914,25863,36363,45715,27099,194995,14299,178181,111488,72395,322385,157719,130787,11897,81843,83999,11369,49280,118604,40922,61332,110343,53407,75639,40582,300440,54722,25637,13694,48248,48278,194521,56203,52779,48783,72627,10953,376,16733,280238,26351,230789,15132,25168,137270,3588,63704,73376,94031,74284,19443,159557,9697,39901,13351,119050,15406,146455,3460,29556,75195,37673,102524,92329,47289,98413,15311,100684,56345,7116,95480,11590,7200,167,23610,58426,17730,136656,27944,53151,2701,8824,103124,3017,90744,113588,53216,79736,65940,26931,498,29568,80540,143543,21292,1740,59268,16561,180816,42323,50174,40890,52866,10703,57169,4700,17191,4424,93511,49698,166650,26972,48631,165169,82879,69326,202970,4007,2376,231325,139592,22119,62851,37504,68816,58345,67398,186643,43331,277416,53749,15746,23102,17432,4793,151138,48822,54265,48203,198688,14305,54287,2291,18018,113378,123260,7180,97549,87027,120085,2920,76080,8190,102005,5641,64580,14955,59802,54028,58884,19367,81779,412567,85957,97053,103637,78871,29364,27637,141728,4767,30686,112738,130146,42745,12730,105040,14844,232,210944,36581,152317,135543,29744,3129,55647,58149,46319,27265,17499,28005,59948,7170,34138,5702,293047,110892,408,91760,218674,18469,46095,81403,14389,4610,35672,73060,11006,74848,104820,118143,190357,20043,105358,141735,5115,27093,45924,123073,52599,29433,9616,238350,78610,24851,58858,26769,31969,24613,18294,4982,32735,39639,143563,112073,202205,12567,4873,88601,44897,81503,101648,81362,34662,85277,17574,48173,21435,221188,40215,39576,80786,26544,64668,81841,10731,37733,247986,149188,127703,495,18382,54388,72446,43071,30974,198723,89608,41360,190,33045,8386,31658,19992,237838,119015,137622,50890,100913,6460,116233,267230,26621,104129,65114,14190,41542,14888,85962,23342,23041,26453,43725,71809,45186,4770,46452,53894,56616,221286,18973,9038,109299,55365,19366,26863,18808,60909,69353,41738,83463,12100,68561,72860,3980,13796,49340,12332,31311,27418,4255,53430,18976,45523,510,14224,30477,26581,4530,3651,101663,139840,22709,150861,31996,63923,120623,262522,3076,10528,2929,14672,130238,18087,9816,121894,100308,25085,55111,14565,18952,53293,2042,369988,23674,61789,133529,28783,108293,35477,47119,36448,71049,40015,33055,78598,198442,1833,159937,40654,77444,189245,113153,8621,18599,38553,35223,166072,2375,11659,21786,89523,6032,12116,63046,159398,18454,3678,32521,47626,11411,103527,38896,42946,15696,26370,10185,8413,37080,165583,4331,63555,14907,72220,50056,6623,62236,36565,49783,10049,17503,100581,55951,146244,24724,9626,17969,25524,109300,173965,99994,101056,46459,43647,53737,277968,8347,123521,74858,33829,44762,77574,877,81377,222525,123532,30602,43881,53145,2973,16284,81940,61281,127044,63620,9875,14756,114829,19032,9202,52759,119141,23928,120551,19607,3599,33401,76821,73233,117430,39968,36539,7071,5446,121735,194059,15206,45283,6706,15603,65615,1207,165723,92275,34773,104447,8396,32353,205240,164323,13600,60555,79205,25532,22907,33410,57480,107111,69630,32137,47832,70913,33161,20321,2371,117348,10714,86246,1625,11763,17900,268,78457,99175,97940,101092,86660,32221,14041,128504,125080,53744,124263,31017,13897,403,31859,21964,5633,111630,5547,77329,17961,18241,84995,25984,12983,67491,62168,47262,5241,297,51191,7351,8967,147212,82060,16821,782,11033,82431,62957,5026,43459,77963,203477,53528,6247,191852,87774,74164,215654,13467,1522,219964,28589,244104,16242,117821,67725,72570,156792,17186,15979,26990,44128,193014,35276,57125,16212,166451,68017,6905,77608,16364,53777,75921,76426,37975,26203,269296,64099,84122,12077,38533,830,4407,20139,963,43028,38902,42911,37503,83343,85045,16979,1165,60835,137387,58380,86990,110066,134540,56331,193845,81238,17922,163093,38744,110641,12502,56404,34862,26865,125964,12965,111648,25547,7771,27196,136980,9555,29551,107158,57885,18831,37705,35505,101742,13970,102109,62548,124657,23328,11124,89592,146376,248050,6241,22033,18337,80685,29898,11908,216623,67721,106162,146610,21377,15085,91552,42041,62560,122532,125336,102365,121537,142559,29693,223919,11515,110495,18776,22494,5895,185059,103592,229351,51220,100102,37027,257855,29359,54123,36066,106493,12244,79258,32002,432,56205,94836,90182,6726,14762,29391,48938,26864,38083,60364,3310,60192,14766,205567,57504,110760,22649,24666,46333,21517,3430,13135,28873,27052,158809,11597,20529,6695,23138,22960,37137,45574,6545,305877,43423,26153,24769,59844,14501,10430,134352,56169,13213,103432,49523,35181,13435,12408,129475,64620,230854,77390,51990,15653,83248,33466,44571,117828,51481,2187,10559,68019,18021,54895,48247,18354,33737,4554,108595,37288,39767,116707,9175,3726,108877,21616,83684,49862,1938,8543,276466,20134,108498,48770,102254,31914,131520,185291,100559,51890,209,19526,76471,50544,71814,99351,8172,198526,28816,20419,9109,98389,136777,76479,75596,30635,165417,48216,120220,25955,211071,39314,24308,32164,2559,146280,43403,9233,17947,90585,1786,86920,125662,2457,64741,32152,32918,122882,78538,44001,31723,56426,23375,103172,88177,145697,52506,49319,68016,31664,41488,18486,110400,7030,28241,986,109199,19900,42147,56864,65287,49183,7858,24e3,30453,840,16673,25907,68916,89927,6309,158335,36407,199737,130464,13137,59603,201778,195292,21015,42466,179062,172561,89492,11075,180407,31868,72493,20998,60217,9865,19530,39274,130266,54539,21623,12535,13505,40641,73375,4087,85633,2153,3117,70680,55788,92096,47509,98493,37490,271936,151475,3032,16171,96642,34106,78425,125761,19591,3366,19316,54508,24183,50786,194248,91528,33253,34622,108355,41741,705,3814,3883,108929,13203,67831,10142,59754,68208,29128,84820,56880,38794,24972,48571,40821,40476,18137,164254,24064,236309,79181,11282,395,39169,2013,51587,28551,9645,701,109513,115899,113566,12762,62045,58322,103726,41343,40866,244102,143816,2490,70346,40973,52618,15412,30720,104315,38917,42027,93676,17513,107418,20706,123890,13399,97727,24044,87962,65606,44250,98044,65276,74790,101473,19350,91570,1326,87790,172042,7577,100813,86896,85891,41512,108130,27794,14875,71431,12835,156250,58135,3759,22476,42176,115873,34686,56523,73643,108505,51491,20838,12721,32863,45700,29496,13700,34294,55360,29206,155942,123812,7706,163234,203,132720,49358,144431,8130,175788,35818,3270,76832,25710,54095,97274,28779,94621,74396,19092,128242,58067,20885,14670,93255,15107,63291,23654,126900,129421,59294,262659,9798,3251,67344,28600,44629,50672,29072,26999,31526,23183,49175,165843,175455,17282,175411,32022,45989,30298,90690,78118,83156,23749,35636,31317,7069,80381,94561,133756,14960,97404,6138,41065,78041,32843,16601,34123,9559,146529,123377,96395,54441,42012,84257,123541,10745,22139,106459,11720,150883,172651,154996,110538,4728,53447,25704,2009,71152,119354,21166,66604,1429,216162,8637,122250,63520,27180,29172,36124,276428,107787,77184,4680,14952,104903,24418,14793,51561,52931,8371,26342,48526,7118,92066,67280,40653,8847,34597,105438,14198,50163,61188,146286,50315,41205,170829,161496,585,197359,95056,1687,365794,91349,48507,5804,49263,5146,104902,96365,117343,132222,46084,96919,16875,8073,262381,79982,52663,13928,16056,153908,15145,109256,132308,18763,24904,167644,13618,40750,18686,147124,114709,150038,52849,2938,12568,48617,8778,5459,44202,44591,74914,17183,248689,13878,7822,80060,23116,194037,18487,2067,7798,43077,33678,244028,31320,74273,2794,19466,8218,36280,183997,48124,19416,29656,19280,98734,7715,18311,30701,133602,150307,126956,7378,2933,79903,13178,12593,86571,26604,92446,13574,44205,65699,427599,21118,8245,14407,27877,47936,33542,7916,26460,117762,21596,37818,2249,127359,209394,60044,47677,308089,36791,154971,31417,6998,150042,174360,12255,43009,29335,48739,3912,101398,53340,2580,146939,151295,45360,125275,15273,45383,27456,48761,23314,8750,60801,85823,104759,27894,123685,66968,39480,26917,55290,83305,2696,98390,57569,145853,340733,4919,20024,52268,30884,7413,203685,70989,112855,4129,50536,349518,68205,332641,159581,135361,236026,37563,176404,64899,6578,122033,63871,1850,85234,82089,66124,74145,121098,107351,12687,36881,117334,13136,14698,85933,93866,18047,32620,310,15094,46e3,88451,23632,36645,27940,87618,80520,58892,20976,27702,140090,96075,67841,103292,238964,87778,107338,17019,83427,67522,7302,8261,47570,116787,8730,80484,61772,174422,56005,131193,52875,14588,28471,59817,9586,15720,158155,51307,109734,15196,11025,59331,3884,52626,102602,84797,25158,27314,4437,20488,76214,189248,35023,114952,157376,2827,62439,102878,129749,36405,10329,109339,108633,36662,1254,13267,5470,87105,58004,15397,10434,159667,21864,52022,179464,3013,32147,31496,116832,18494,105502,129227,107267,50033,13481,9954,24267,22141,16257,116154,36185,950,115685,11305,176708,2048,178671,112573,287867,162328,497663,95170,50979,193861,50987,30368,136257,31830,46549,15119,169876,23788,17462,249887,57377,1949,35448,14791,43769,210091,3783,34612,282103,88380,245190,5457,20491,98908,11402,86899,117916,16028,162584,60644,320177,156096,31065,55876,22e3,77655,9992,23397,13757,317623,63978,215255,2443,17648,93231,27388,104529,93807,55505,140477,12046,112040,70887,40152,94365,112353,25063,114679,266061,71248,119555,15589,2244,617,14129,211431,70110,100652,7777,4383,85911,89221,21010,120615,58357,86405,37554,41647,18,15143,69662,60491,14714,186134,148344,42347,5410,168175,44535,42449,343894,129417,99682,20659,27272,140483,63455,222159,17536,13722,42637,62324,11976,114691,148109,2283,32057,182393,4295,147364,33705,2075,44303,30274,28331,63740,69740,29148,10346,44862,33716,73937,153333,12930,38784,247159,2515,41053,20256,83368,256189,54639,115240,5096,24661,175419,153552,26516,141,138176,63885,34115,47222,55709,2765,28479,38875,236608,12229,22921,77291,54426,45388,2860,57787,114579,295139,105782,17826,71066,19119,54364,69385,16568,12323,28057,33346,34919,124763,155533,101386,31644,8627,49001,303600,29868,63213,9103,77280,71333,9696,138789,37059,24823,5057,21352,32368,114208,56803,19424,10445,58514,8661,209508,26187,171838,10460,63454,14016,122504,41328,21329,46618,32493,38225,7855,31763,7945,29876,8734,6438,24205,97490,139977,130740,47323,33195,85390,57194,13813,60600,21313,96251,7699,27584,170521,139271,1363,4402,336738,129223,84983,69150,13147,3590,163929,207225,155260,55916,20288,4503,8398,98490,11773,27512,37113,84976,86558,28365,11756,116005,182148,13733,115313,47644,67208,85069,9347,14995,226141,14704,101835,41159,35314,13113,63526,214039,29978,50446,83339,17440,129441,72522,118641,97816,24907,73844,15717,118884,167255,96509,162793,30847,36849,51297,78974,77793,10427,1873,2972,9999,35074,28190,64297,146836,46298,60038,163007,108919,61219,2403,75022,127339,4233,110389,69022,9833,128097,88016,79390,222936,22570,94657,28462,56956,38803,81536,30474,152794,19566,16481,147408,74574,81895,20731,1918,1366,76367,187321,54494,24366,21690,61696,33283,107477,77499,31112,414383,74362,18463,218441,120929,59848,258629,201924,69269,454,19989,13054,59894,3623,58908,20681,35723,78523,102680,38988,184112,108087,50944,132704,52966,21699,18860,96349,201411,82697,85395,95658,5093,6427,177894,44191,32755,26961,155739,6249,31310,81030,26574,84311,120155,86730,113535,7424,48888,13516,45747,98098,20077,183995,81945,43210,26704,40420,75831,45648,11180,6855,57927,65528,124096,34851,2598,156633,107572,127352,38169,123845,60142,62722,105584,232364,23211,68120,1601,22169,89299,747,258039,80572,7258,152249,11862,101204,8834,121434,33761,19175,133142,46343,40178,48723,3589,41977,30210,38868,62257,10087,82658,87827,90646,16415,47552,351723,28298,72225,91146,272760,1701,11295,1652,109651,300747,51863,198800,29446,11794,32345,37538,22356,33102,37590,113544,37970,11478,179743,25454,103417,59905,221970,105196,145604,7817,164809,102360,16974,75840,255333,56902,6659,1954,645,59400,67769,7689,18675,5215,13793,20536,27852,3387,29523,259718,16860,94625,43143,29245,15848,233581,22685,63631,78557,22836,133302,84513,1348,51826,47129,98836,58284,1830,1749,94642,10933,6145,12506,10975,13879,103781,144434,10268,28409,32346,52968,121567,107374,77268,23686,35097,10501,155275,15303,47136,21102,168741,55332,90385,15996,84817,681,137803,25054,142275,6163,38175,8056,124296,240642,65621,4934,178205,16101,62803,60964,18230,100622,76465,44689,14545,9543,47514,16852,93380,28048,12047,107106,37575,101485,77047,57326,34819,96137,76916,6469,46264,115983,75768,87668,69942,13027,165,8373,114231,26434,52844,42799,182044,23580,146254,38081,43236,33883,146220,382894,14606,46035,36481,166621,35417,95382,2957,59384,60428,36358,66343,75378,22267,22950,83528,17577,56474,25285,4619,179691,75355,95836,53295,34588,171410,4487,14679,84208,44015,18562,109133,54101,11531,86052,174479,303157,28095,9953,35642,14564,39802,16145,77606,117406,53038,121117,53624,22062,1212,7632,127157,237292,189087,10478,127345,102515,181997,86752,87623,10966,121602,68783,68681,83042,114380,138349,191305,67176,50085,39016,1427,42384,1412,67118,122616,72389,25260,2237,13576,137346,19938,20304,2191,68759,5373,61364,238507,75814,23931,69565,38993,131741,38364,12528,87762,5679,129853,5310,186831,32653,90338,260176,389531,108118,26843,43985,50175,30563,25106,56965,18130,140428,4542,165503,117991,24219,229605,1819,129663,1240,3797,76093,18398,71339,51919,93043,27175,47060,216257,6483,35051,1217,16512,80798,129064,13225,69339,8548,237079,72298,2575,34280,51379,117910,55671,53345,247552,29486,39328,140821,34681,57045,60177,5004,90269,78522,2479,322607,48474,61296,13057,31558,4678,59271,6699,27044,31988,35944,12503,83480,4389,136508,3781,114121,70279,4488,155829,42214,2898,68191,75695,305850,45041,74344,106509,30087,17429,93292,12477,290,23080,114802,35714,18751,26554,105424,17775,2144,2412,100610,65192,113975,52975,180272,135050,129815,76238,106483,21440,63186,4260,46189,9711,28249,4169,23429,23390,8324,141585,63809,67668,38457,38063,39226,59972,1189,203916,62368,14403,16949,61767,85801,1739,40147,35049,76757,33124,62102,15780,103593,103009,53484,22952,67973,114645,6566,5245,50462,7601,8288,3513,194571,80276,1908,54592,5124,58571,2513,6800,273997,193904,1119,17991,117245,2508,129156,82366,26278,71465,63341,56943,39662,106116,94966,156875,9736,2204,122308,94418,27134,1280,24539,49022,45314,3764,50904,46424,30699,28087,293839,9400,33646,40165,822,147499,50263,116179,29085,11863,31314,5578,17797,5104,12454,1604,15342,219206,10232,67800,94261,25872,13565,90339,78971,75377,26649,41184,47695,11514,35369,20767,14227,41953,309396,148270,147938,33074,14453,27499,109019,39018,25738,240196,158931,52820,8612,95853,21524,137010,84901,70869,70021,116794,48404,38771,6732,1070,70990,187297,49140,5238,576,3564,253975,16027,16483,2811,37775,19034,25259,4053,2e3,70083,95774,19713,33431,92703,91314,42381,288770,48194,95985,3991,77418,13406,241328,245086,56533,35275,62725,9246,51924,70181,95331,16163,31410,79016,39312,120878,119371,275987,80124,27712,9186,220,23598,146167,85209,68238,282190,57048,31273,30555,80913,17594,75779,59160,135002,101219,189377,29225,96735,60126,62522,104e3,27620,86814,17240,147533,11001,5425,43682,410,49460,87270,69480,46315,59448,1816,76201,9431,11788,87960,29063,65539,47347,11678,33846,7008,196704,9895,6753,8633,120892,59970,572824,115934,6646,202559,892,48351,37611,251282,57823,67263,57750,26527,34485,90747,7685,88370,6144,64182,1709,41969,21458,62327,181657,49247,225330,122600,114574,107124,85361,111833,63243,71420,15655,191178,72430,18063,51425,54002,12364,53225,86557,18193,97580,41232,138398,67821,128724,8944,233212,101353,52099,42127,14006,120107,32789,32132,3498,18123,33758,56058,5779,128760,59888,98869,18445,84702,51911,13234,218379,20093,39031,8074,70195,20708,23462,24355,131384,60189,26390,10403,41060,7140,10781,49410,42261,87202,82566,41663,43105,60276,2768,5733,74176,28329,2297,145430,131632,83615,122915,105441,655,224102,5284,136426,67763,16294,188511,32538,61049,27893,3394,13951,159099,28542,17930,145360,9492,190122,32285,78855,26440,13570,58648,73908,4239,124561,2444,74172,53131,11468,10794,73566,11623,35343,64710,30481,4163,10328,38309,29901,10538,154377,76132,92405,24839,11679,3465,13449,11637,7824,2337,57754,1260,14458,41118,19878,38661,13416,159180,37074,163164,54137,28627,52134,184900,8520,40385,29546,30502,22386,66527,107458,6850,24022,47983,30603,35083,8934,304066,39500,9,28261,33026,77251,9374,44833,116312,34990,29236,63563,125639,135405,165398,159055,55690,88141,69643,236964,31983,25572,20436,36746,60896,31850,16179,11828,5888,3043,66368,9750,31167,7915,53111,36430,1333,64344,93659,20061,60596,180191,51630,6792,30244,43509,101058,22409,420,44210,109783,43223,27030,72477,72831,32679,29235,7675,47556,12258,39907,149412,84926,118247,24692,71717,105038,86009,45941,41189,89453,29856,52543,30627,226798,67303,59230,67415,34408,1367,99685,16867,128419,52147,4111,125381,117881,16173,44093,102224,31575,23234,24870,83790,127407,239098,3200,994,1255,100903,242275,117266,55116,38205,16140,29662,11307,40414,208793,123355,56470,4862,75600,30119,58218,70828,24075,26974,7802,192353,4851,5475,78720,66596,3409,28573,64396,30381,30690,59859,88256,5406,99945,103064,34463,37727,24238,86643,60088,4057,23741,5967,162904,38240,28356,93858,25510,122879,6897,3278,7057,11971,4400,35461,211413,21395,59615,39471,87233,55795,128426,3051,22470,41950,14705,3974,180108,80476,78442,204996,91987,15634,67610,139015,142373,35611,51134,10387,4353,153456,57749,181039,14183,68447,151532,21107,36452,20551,3186,46247,46383,129666,88736,140662,146243,2066,8360,7978,64818,106963,17896,47801,10723,114821,223295,74192,3293,3393,16987,74064,11277,91622,4270,29828,27951,387869,103235,1374,61988,120083,477,145892,128378,11779,211263,61354,18221,17869,46530,83061,108538,157981,90608,67199,95080,49064,195814,12302,66307,10348,231346,160732,112859,63633,146558,21271,31037,198802,47622,12862,95710,3910,77850,73961,85585,34752,61e3,4082,24595,103679,71107,8208,79568,150019,16615,24961,139857,32664,197366,4559,54735,32696,4126,162019,75698,13916,70108,159638,19834,9349,24675,175560,49643,18206,52459,27992,10809,88865,401975,133172,29e3,34558,30915,3658,25834,42430,36562,125265,18182,10155,40149,97082,208980,19575,60853,90529,66545,9600,789,46420,2317,88593,55595,98980,115302,5742,169155,1073,177901,3472,11189,63711,78643,65472,50459,127979,93,42202,67053,21720,157650,11145,141378,42033,22824,85705,79114,35584,15974,1510,54172,28562,12451,104226,19190,97151,73024,20948,5151,81741,21499,29006,84183,198074,54003,45120,170125,26240,35177,28389,64863,79974,60778,176915,232183,45342,2038,80253,41564,40703,32689,5430,100689,5366,23007,134279,14266,26712,73993,24934,64242,52113,102887,61801,46415,201049,54251,62133,122757,164883,30815,139966,2319,30842,766,13362,10287,134518,86111,81665,82440,28333,43019,18963,8804,161944,23439,102144,101145,80029,39052,248708,30350,117340,11878,128467,974,138625,63961,5237,74778,61834,67040,43814,13690,65947,33809,232476,115258,181745,28824,94013,9510,10246,93722,81976,7217,114383,3493,16014,69045,72692,12145,80981,9507,6692,1620,60820,330444,35474,33962,4797,7053,295463,46445,27026,12491,77988,49524,35675,90947,29114,166705,101385,133782,32704,6186,84595,176031,185623,45966,151302,63069,1699,107491,947,15458,74452,196212,6046,10498,12163,10239,35191,243951,9277,9090,29539,54460,22820,26514,112549,60372,51753,48756,21812,70861,260326,41,44222,10441,16961,48148,138771,216194,5914,52153,53400,212036,56519,26245,10117,45888,15294,138019,90913,26368,43842,42111,23348,6082,194845,161089,156206,51546,11647,30759,302912,262094,8635,78876,26535,35283,54183,31183,85484,147873,12989,5197,6356,72894,65347,20150,27370,73787,1493,45918,12366,190217,20724,13858,10981,67449,81213,7553,14115,72242,271517,11842,48310,88743,143726,22177,3290,243231,58452,62937,12592,1654,40066,33477,13751,9921,128442,15868,7106,75236,83773,10775,36938,10482,170465,17368,17469,161508,32752,98340,800,19824,264456,3901,87319,2867,26782,9630,113102,185815,24197,44584,86366,40224,3636,140916,31731,267731,9567,53678,72984,29389,27963,17106,50282,284911,60170,8322,12608,23374,89652,5268,39044,229766,8869,151350,31436,177342,12269,183212,120418,116270,2843,78888,69192,7865,184099,1086,129897,18383,70508,20242,18508,229924,124569,35749,50589,55626,9884,83115,40971,30671,18135,14452,38861,17844,201826,5549,26413,17189,13561,38539,10679,143331,3314,36785,171194,49685,187713,67506,4618,104039,17060,195080,50648,33159,19238,67559,134840,28599,157523,17130,38064,117398,94355,31918,13575,34538,40326,13997,3494,348283,62481,26862,3603,104426,244363,153709,112487,304612,199674,41239,35545,54869,293005,28223,26277,26899,4533,18518,15492,38587,80488,70485,160395,263,60162,11382,222152,4696,250751,51921,182609,10707,48463,46243,1227,49111,111564,46502,33342,56846,68541,63559,858,139927,16654,229375,76759,26478,33205,95828,23399,92945,2637,35630,28470,143992,50214,14174,21456,166191,65665,1711,21594,78019,97599,111701,36,147151,110246,189022,43021,30397,40757,131935,42065,73335,48039,26596,28984,15102,2361,7421,202167,69744,43766,52826,3642,83304,33873,75140,63169,192389,36551,92748,13039,123959,233220,21738,84447,77230,20228,187852,19095,25799,92136,108774,29237,53947,2299,118106,2687,8830,42331,202924,33667,2023,73763,30704,19363,19779,16737,35629,48081,24068,101013,162338,291912,13749,24745,328289,167679,70086,48299,23306,16732,17801,43322,54589,3586,63653,43624,53474,925,109177,251316,43805,13082,19511,86565,142182,92461,17117,101033,103319,64589,4022,4351,235897,5352,82705,107142,46391,156084,5860,61365,10558,13045,7717,18357,33922,12590,33065,6928,46993,783,46937,67846,8952,26295,6107,119656,18799,17458,50747,4229,179559,112727,118080,20683,41464,125468,51560,49749,44231,7359,35339,62988,136487,67015,5208,29150,24956,105186,48858,6143,18097,6972,16404,73489,58742,97196,36357,164616,5834,32267,13746,147733,15113,132091,34127,106298,39729,106426,22294,9780,15602,36213,71502,42808,66802,599,60755,5851,39120,67363,108623,126368,72770,91263,32486,30596,151717,7951,52002,43103,11768,68942,40901,39344,24037,127500,116890,48403,16926,86750,17745,48648,159545,34460,58419,5634,114317,67865,31462,23352,24010,98185,125708,69686,68337,13610,26271,70691,2980,4768,27225,102402,75453,28106,8104,6931,1176,6274,6475,112635,22498,6176,238686,26832,28893,90319,14441,15682,15087,39517,45270,109134,104440,45965,47645,81772,7876,52683,87720,12898,4505,185665,2769,113401,15664,57592,105229,137381,97059,119268,6876,43309,33886,128363,35476,144249,67013,143587,83367,25703,91436,59347,53236,2289,16519,19844,46309,58558,99834,23313,218816,231303,36388,51333,183535,109792,139277,54306,90139,18235,8275,32710,37677,82464,86025,92204,88842,117723,37570,128723,234242,76350,73795,34896,148247,58424,11105,11744,45746,63372,17118,49772,199520,81902,38004,22911,33752,3125,1995,53792,4689,26909,108150,146062,69674,41811,161444,84855,8999,28561,16731,93937,3189,21967,24890,22943,1356,145300,51569,28802,517,118679,31703,40607,48098,108854,25003,10233,73969,177495,5248,24516,215347,146192,48712,60626,69188,40735,5866,586,101541,6509,47590,52129,5969,222045,110933,25733,24223,65339,62812,2414,155418,35819,16022,78423,43138,20995,128255,240673,46745,236093,72176,57085,97841,61248,107,36068,193177,105427,55726,215229,20446,47228,100420,87091,14429,121708,23605,21157,187721,21880,2997,203976,99166,95068,25877,7724,98925,83401,4829,13182,18229,13718,239662,38653,116505,153497,30589,89029,38962,181302,43853,78872,180301,4786,248240,7401,106136,112590,77745,19731,60880,77789,125748,135487,5975,48627,34084,12419,215770,47557,254582,10364,106495,21856,67539,88981,38805,21428,48732,42316,12149,16078,52808,25327,51322,33850,51147,12253,122354,46077,56483,254553,115417,81834,150991,94662,86668,7381,12841,100650,18218,15741,22372,68294,50705,15535,84660,61887,22553,72299,31361,24824,17743,46820,64288,31582,77006,111674,116384,30760,80920,86149,77192,51979,79691,60342,122805,103800,240873,160744,233114,78962,54920,8608,3484,316104,72548,24337,5088,230040,21926,10172,36838,26,86221,83458,102176,12062,17571,41929,41170,28428,68239,41750,103930,2634,18313,53019,34825,97837,63115,24606,73157,152474,14715,91439,37033,109806,140259,30668,174760,380,135597,95673,136073,65073,134249,13829,17279,122305,4420,46444,10237,64848,203623,70728,10349,182885,65075,24519,25783,40318,34139,22222,63394,55266,102764,41422,20126,65100,90408,53640,35128,48932,11192,38935,96839,34782,39492,19396,41332,6250,5511,19492,51304,25936,104466,54099,73771,86115,5080,7669,30891,111700,13931,25276,72289,135447,14820,258641,25265,31005,281179,75286,393,95359,14623,13584,6680,101227,80173,44933,76666,54542,13244,39348,458,25379,109451,134348,81143,6959,65554,12027,51311,8716,57589,140731,28467,23316,17272,30458,25980,55229,77197,83798,28302,114784,7428,34548,26241,14712,39336,103304,18928,54080,12870,334,87722,15208,16895,142098,114262,39820,83913,57817,28682,7721,14900,108672,11250,62246,42849,415188,1724,26555,24549,25505,26443,107450,145899,61035,43528,6901,60726,65906,267741,21338,147590,42079,18924,73017,135236,15393,5206,4026,84185,1531,5988,113890,82647,303391,7386,69844,71611,189865,76523,31877,13315,19314,198575,32821,1928,67641,25913,104475,103489,3297,70391,18406,15446,113347,19295,93790,27856,1792,167471,116449,8541,4408,41757,63233,25765,86680,64501,27034,24816,34975,6079,4486,49693,36229,16917,21581,62426,27862,11612,54284,35702,194034,355,24277,48262,87411,70504,310164,118018,12516,47559,43502,57433,107139,9290,66533,80863,14634,34312,91725,28606,21342,67241,72355,43244,375789,37402,174015,105070,8342,44167,67494,1890,16365,11723,271002,1865,47918,8350,45564,27742,25110,125803,8553,49504,81925,62211,4534,15491,19011,80373,206920,667,102405,128623,245524,5553,113309,192739,65766,19567,22832,261958,29679,21293,71134,20962,105123,24721,860,21752,33448,18372,157167,94822,35770,173224,232737,75729,28937,46828,28062,25453,5207,140366,36665,30652,6169,67920,150458,92040,23186,184604,92330,20891,176492,49427,27828,38305,42495,143982,49560,25503,90043,29747,65328,47830,12932,11068,77721,9003,25213,94205,140426,46090,89945,138173,192691,33329,112232,129905,35709,27514,1841,19957,31411,127476,53572,17497,173549,55063,175135,19841,69314,5192,237921,117660,150697,4060,273045,50414,98940,65348,153665,164423,58804,156695,48994,213928,86036,28608,8355,39574,34540,16927,135680,18374,151587,10830,53805,16878,16623,4282,48030,8537,14986,46102,13062,72897,72,33050,108227,39451,45935,651,113320,40535,95176,57450,48843,5003,19019,10407,211163,3848,1068,4988,32091,30095,41692,15099,43602,107434,50744,7627,171349,16313,150832,352665,207750,33937,38256,51091,156e3,87889,90663,84175,24908,114900,50365,31494,83829,5398,169342,47521,54818,18935,8356,43094,41212,174536,10082,92550,6678,60614,23355,69721,14796,34149,128830,58187,3179,208,40325,28399,225029,401412,51150,31580,207268,6657,10993,69818,64282,289845,23308,12961,38447,6681,52944,31855,2572,47646,120728,179148,37240,45196,218274,4816,3695,21961,50084,35209,18073,51452,27004,6100,33941,1377,84831,171214,85,141510,9078,99227,32610,6417,11718,49868,65579,87902,73018,49062,46280,61742,21512,40862,107733,15941,29168,157765,144919,14487,5767,158014,140070,7241,573,71584,16921,223566,40331,179473,35081,47926,140885,41508,52104,59180,42310,32811,29048,123517,102413,80208,10104,14746,12649,153641,126022,37965,113017,4171,83,142592,2809,6362,50416,71323,116894,260776,16204,1524,5760,30351,12658,20703,54403,36083,45408,74772,4946,14485,50759,111222,10890,2195,167147,92962,130534,16283,177256,35016,15472,210156,151187,73922,117691,43250,52051,37392,24811,24358,30830,5775,818,21969,1476,127322,151783,58392,31021,106913,65215,89407,90802,28531,11690,20234,95249,44602,37256,18707,11928,5161,4410,26571,51903,49768,22008,25252,65780,209499,68769,203726,13249,137363,48845,86823,6658,5674,31881,1083,1823,108676,34518,166752,13791,14287,91576,91429,8665,11529,26401,16191,91972,30964,5254,28486,54697,79613,66520,18447,22870,45203,194466,22822,51703,12278,76716,44595,73455,33546,12235,144843,36154,51247,11116,33040,3180,225753,60864,1972,28469,12891,28879,10338,144157,56294,353058,38302,41447,87532,110616,27065,168438,6557,1213,50804,144643,24817,2390,136531,38174,247513,16190,4059,122791,131994,137430,39506,57650,16305,5188,54309,106128,20628,88071,67394,395446,250285,66176,91254,1399,114196,43915,60230,44853,27206,106353,43013,18733,345105,226453,51202,16607,57106,117175,35492,10476,89598,127439,15187,39624,13688,61570,10615,31111,59370,6238,175252,32143,224492,41388,95408,34384,148238,78307,38959,9340,160091,61443,15737,11216,41244,170,38299,102443,113097,26382,14027,33707,3957,76300,66160,19431,18900,6952,1717,108656,82206,188021,257335,27295,43999,41210,31777,46956,57457,12657,11489,15697,48060,204748,53583,82422,284790,30503,137341,8120,19615,220311,15991,10217,63424,9808,67431,70976,98221,4491,15177,28535,144789,751,13230,2394,1504,33977,132104,30316,22230,931,97193,185240,24826,22687,174322,15307,22988,1390,188745,180325,29580,59068,74903,18994,29195,79,15436,7622,38462,11566,138710,44828,45774,37768,99236,68137,84083,19282,22698,17134,74807,126662,173497,46248,16938,119735,3212,28292,213652,49013,9975,32180,45660,86250,4801,68788,95490,77482,113751,11994,44624,94452,46839,128497,100316,5798,58588,73184,202987,65417,37790,88524,1606,43156,97964,105717,34947,11203,100060,37742,130074,93653,107799,94311,196106,41347,8035,10780,16390,27883,118236,167395,1979,25006,19375,31628,18916,144723,78502,114047,103107,86492,107686,5844,20934,206963,23556,22591,16562,146333,20167,10471,117434,33085,2863,9740,36669,41849,37271,22790,18209,28979,8231,12952,54408,21731,25130,45208,55748,138120,75826,414,29593,9925,292865,25999,683,123149,7036,92159,86055,61827,103680,23176,54918,58466,57578,13305,5709,86479,16697,31064,17660,200919,10770,49793,33423,32370,52047,16488,62555,6459,8426,83493,7763,59725,82812,18628,67760,79405,68557,9612,7673,28102,56517,69620,171797,32458,29541,15870,81109,32080,207644,71495,21202,11039,91036,61230,2810,130800,32260,4613,60590,37112,75214,33979,126402,155062,30642,63875,12810,194463,82799,47664,16725,36685,43367,61099,449,172150,102867,21691,301838,36745,7130,18671,57316,34852,38034,54182,35578,65900,99486,19771,3456,2658,16914,99866,28390,28109,8262,21147,34353,20006,4228,137085,1675,203023,283196,198286,214375,163329,290603,152574,40471,83506,30068,14730,23177,131539,34759,27668,32178,71896,104799,116305,85430,119262,42860,25160,8911,23428,49437,105322,6519,16203,6349,74711,1230,38045,8540,75165,44736,25909,51026,317034,4984,32281,91312,27060,44431,17817,45363,155937,239085,35697,59784,91993,29531,126740,213757,76560,167776,285273,24262,8237,65030,41160,74437,48804,118916,13159,37842,1031,75349,1478,11655,108777,23435,277425,101734,67469,70231,124711,43532,28514,65526,54956,1e3,21882,17728,25302,40952,52214,149632,1999,2111,3259,63362,89961,220561,39777,26335,9063,10572,12416,34551,34623,38604,24723,5947,15588,69927,66252,119177,69173,46629,28714,70715,212408,20521,406913,74380,11716,50659,50862,37009,88460,130101,7210,53853,538,65120,151950,55806,163748,52837,13153,21100,16674,64536,6091,138201,44837,58547,3723,163,2177,32288,85454,34033,8497,14282,25742,10535,10741,79559,117493,243787,49337,100718,79495,40139,42956,7551,55433,15421,31509,23034,45081,547,61176,53434,328001,8470,36263,30145,4519,74173,53935,11845,73774,60211,78025,3,4102,73782,109293,315332,48412,26683,13714,6865,20128,18490,104141,325,39470,171970,115860,15707,7268,73301,74336,31370,2368,111827,107757,136231,142844,97138,96638,84053,38691,23801,1588,10573,122098,77039,240,186135,146101,11996,18143,112963,46171,155836,348769,47795,121213,116266,132515,3344,144804,31286,99187,255838,129694,35894,48779,55235,148582,71967,65282,15174,13920,47080,6147,108242,157593,125025,7136,1286,28957,127956,28402,98813,20805,7532,109417,40610,5041,32958,15142,18408,108596,33543,50517,27748,80114,233434,91447,487,37094,100048,30541,43477,10639,89862,155868,37667,8726,60684,237903,73408,99589,12190,38739,97348,3914,13594,2680,149016,13907,30171,28343,23530,115225,61104,35821,147679,14337,4297,244282,24085,326976,56428,7851,21303,131620,71446,83253,68692,111870,5224,15813,38197,49026,45057,13660,3306,76345,40671,27905,91072,996,68527,62085,91351,122634,55109,168209,2024,27560,112707,17352,8306,167115,169921,166958,5031,46020,11844,67284,19130,76185,6920,32849,5450,14610,22451,21002,17392,31872,66682,84796,13709,40210,59898,12029,8719,53564,21462,91884,21647,88379,194428,12754,37797,132826,160016,22567,54383,53186,77611,31107,8339,4694,19185,90355,23597,17222,140675,28442,23668,55977,9128,61555,28774,155229,17658,9390,24379,69357,15752,127381,239631,62460,93181,55913,45133,140155,18676,25249,33164,29581,82837,67223,22362,29975,7317,52813,1943,29613,20012,207130,49617,49651,5636,15334,36313,29226,28084,95247,72072,19e3,224932,15811,114,32127,38097,37508,88507,37225,27359,91626,12193,69279,20608,11055,88156,92808,2152,57259,55275,72789,24475,104414,1708,9882,3818,48661,66897,1631,34806,227930,85815,87753,18321,250664,72733,25107,206797,50891,8082,196411,92596,96764,152823,65514,22819,387277,62176,51225,40329,15563,189,3659,73670,64357,51793,275136,33482,86653,74615,67058,11318,125720,15388,22388,8267,1730,102663,170910,40784,7144,85373,13040,7088,94309,583,44224,140424,77439,18496,164026,36578,4722,9151,5824,63365,26510,35199,40500,79277,32495,44614,35233,9566,203293,152144,7097,2330,183480,98629,13423,330887,44130,68600,30939,97829,31012,345465,56747,94879,4939,160027,149761,99423,46099,32251,15332,8761,96094,128555,5763,235318,222223,55729,30241,55420,201746,3987,81382,8259,49325,23287,7719,24633,251100,92311,18591,110533,64759,170260,393860,7175,21144,132887,3593,75346,101277,91109,16387,259187,11627,57459,173829,44694,55780,49797,89192,120443,62622,3904,14814,23887,1027,112258,64955,99800,11132,66353,36202,48624,18158,88481,96882,43059,11040,2455,7077,21651,181159,99126,100434,61388,68186,19161,110468,120052,8819,55324,41494,7014,37689,3618,87729,92615,207943,9823,128657,12587,15857,6379,67628,51216,71775,157617,63244,1503,3864,218754,110864,5769,21492,7243,1192,87921,85529,31512,18537,42698,35350,73510,84474,34301,8991,21013,35034,566,38832,19838,35586,37216,39413,55006,12178,59742,856,84563,6900,25632,17437,49786,30723,13847,70845,4044,7843,23944,235976,55530,48942,6518,20939,73769,192653,52936,95207,23895,132542,142982,22632,87452,48042,54018,178468,10728,26230,23559,363,81269,142012,5718,346258,31456,84333,246476,51018,66692,101804,120570,39962,30373,70593,2864,60541,19425,54209,104092,7201,31545,48018,25865,15442,46257,40443,8328,6451,111782,47527,97754,33046,470,245116,31095,39,91934,87208,73470,36708,36521,12801,70624,36272,8892,79768,12427,55454,103756,5908,52390,62962,22720,141138,94634,41689,128402,126390,6628,106394,35527,134394,82727,254651,194502,148064,89549,3202,28359,957,21954,27906,49840,142747,8307,24206,48978,1186,71728,133038,71474,91306,6333,110959,74600,70387,18983,62609,56057,22970,1147,135850,1321,28834,3578,59715,102227,32827,81415,99952,55636,257598,390,22702,35701,85872,402916,39216,189795,14929,19467,10112,144422,61514,5279,63421,134686,41436,8424,51925,10598,132295,124416,4604,194739,210929,57866,31829,51626,50007,9976,91878,61906,56168,81906,60918,61859,40017,23059,16887,40927,62064,12785,32893,32913,21782,93965,20169,44387,79084,38463,11457,93950,27127,157050,2697,337088,5116,54128,48255,33279,8821,27352,25515,124022,65710,28906,38557,33390,1722,104435,72215,38551,12094,30978,25113,6671,37355,175109,42862,98024,65406,221276,59624,118012,64637,78760,86697,21426,1639,40350,12584,67193,84144,31396,7863,143011,69629,63112,9454,28666,65798,46372,134721,6314,51402,30837,151922,2847,38676,38008,92823,136245,17540,5504,109295,205242,37606,5211,214892,1586,20670,208711,137743,19328,40652,16995,20023,14657,154919,34422,12996,13918,38221,47690,16398,2959,37680,89122,6721,198469,91876,172043,83898,101992,26084,94570,3635,76958,22853,76497,38266,176590,168403,44464,142840,79180,184594,1984,41806,83147,11985,6546,366068,59732,24533,271505,8736,39084,222992,93429,28962,58985,86665,8432,30028,14548,32439,54424,165029,55175,27458,69046,121277,46168,33732,20661,24581,135574,123110,37556,79260,72611,16957,12939,46162,58238,44907,72936,253758,41324,32518,96480,11949,124438,65280,43256,34107,53533,43531,37037,28366,45970,32741,173438,6121,194202,62969,26355,30314,58370,28455,1848,50519,82830,90393,21761,295490,10936,256940,133568,44050,20269,4089,27457,21610,219460,36743,14821,101388,52005,13124,30979,140816,167362,26054,18458,60789,34917,40447,26606,33422,9066,3452,83614,5761,20263,137238,25038,91310,101,52322,74548,42572,38084,214054,186568,31802,17665,30620,141936,37730,14420,4265,187218,49640,188208,51441,55388,96452,66659,40869,42039,60967,221027,19234,178581,29105,96050,9165,196118,157335,3738,40354,117436,2965,34136,59659,15570,50843,230035,31444,71260,43886,18316,5387,38500,168508,17406,32174,8828,103373,143806,90367,3560,18719,122310,16508,26719,2541,105429,6645,37998,73190,10591,235916,49737,87112,233941,53188,32193,79154,4544,52905,126477,7580,63501,57314,3216,31337,6541,103083,60846,49,9756,15481,1355,43840,14319,13743,27486,10222,73114,230718,418644,16706,6674,279748,23058,45273,295831,86306,2743,5535,88773,21829,35253,120938,31153,3169,16839,42847,8751,80974,33942,36867,35514,16485,26474,77775,56877,5391,48346,3882,108713,31403,27804,55248,26235,43821,136104,40118,175507,28034,203908,18732,1788,34030,106427,36958,54359,7251,44936,15356,69139,455,157915,22173,140291,50348,43275,82066,49621,54952,15216,36226,96695,66855,6936,1987,8227,196087,4631,68827,99004,47541,110265,17953,147605,110242,58520,31312,38724,329975,642,3155,34497,75937,6207,73843,6120,17249,51429,117746,3218,910,68961,319671,14938,29555,34700,1649,66673,72268,9655,76800,153087,6941,210168,27130,35398,1780,73242,3135,56689,19556,165307,8765,35967,121458,13333,70453,17350,117253,22265,13340,44265,39869,441,3742,135025,23581,33309,16543,17731,13291,157637,283005,21408,101360,63887,52312,83873,5338,233779,23759,186949,34531,177320,38069,156465,91004,19353,59852,68160,14891,1338,1072,29823,1950,28901,81407,313445,73038,84807,162348,240257,37162,138934,16111,58013,41253,102951,16457,96056,19541,56402,67217,41638,94381,89674,29481,37456,80815,151579,13937,13683,132537,19699,134545,67020,29816,222341,141235,427578,48868,129557,233342,23077,87871,16213,18728,16184,9469,37913,19680,2798,171356,178328,13216,50049,72690,71904,124644,55455,7504,29052,41036,266546,19899,30391,188755,8659,59469,16,104298,112943,53865,76203,138226,68857,139953,14125,107625,119795,173133,4398,50273,48808,54390,16466,122086,31835,67035,50971,48859,7508,46427,66477,73021,84615,39985,83076,46779,201569,53336,36443,60865,168164,143810,51393,25548,169307,32896,24485,38424,21837,29087,275813,51674,6714,64883,46169,187369,55186,76192,12852,12018,62134,31067,118303,16542,12125,10579,4928,26291,43854,7091,10946,253716,109062,39283,17261,113012,258512,47764,125126,32646,55892,80279,201623,149872,3192,385,1208,48750,5376,58738,22335,5427,82416,47811,32435,143086,38930,94128,59975,156037,37977,38224,62485,7698,50405,71027,16462,21559,136153,34131,107506,162069,63703,3101,215029,40407,4178,3774,9187,80019,17880,97926,67579,2600,18405,8351,47924,86638,70820,92206,86453,29610,42241,119200,3198,15466,67813,57863,35454,4779,99518,4649,104641,144269,33730,38073,65864,6838,109456,193298,154007,5623,45741,30846,182578,25573,157224,1543,58575,138703,146140,44971,49356,18275,59064,20300,13122,11848,24453,11973,9797,86843,2919,25530,49210,1130,161220,76788,75373,85604,34926,36014,17777,17255,51533,11676,92226,51845,119859,21525,5936,18507,28050,1140,31418,14857,34207,47859,10750,36382,32079,106909,59426,87757,38393,110042,15965,97104,33757,35344,97993,53979,33651,45407,41884,82515,173089,7177,58371,35365,47543,51927,35587,10670,23544,29306,84233,39976,76076,62097,9007,8668,28119,78281,120790,19835,143020,54968,18670,64959,20649,34469,42570,33001,136570,87796,120044,1106,58700,63951,127623,12805,83057,40212,31773,49850,7361,54336,347524,101314,23751,19569,48791,29174,49369,20467,7465,75842,38281,623,112457,60210,28849,51003,94720,6426,90047,85560,43761,3579,85105,34607,90410,118528,7224,42907,111163,18168,6960,161135,191298,5247,100584,127552,171568,20121,91173,12636,54615,20199,63730,98105,2396,40387,14438,125012,4765,33235,12865,45299,37728,82098,77872,114037,59253,19675,24838,398016,102561,11446,17069,57508,178277,65836,99941,26114,2585,271882,136866,50126,11027,155648,118367,14585,8910,123015,335383,40434,41016,53021,14439,87098,176860,201543,121888,2358,9286,5739,22666,54270,37884,169381,33984,93859,16124,89364,72207,51639,76366,99029,65812,2198,12147,174891,194289,6986,30252,88822,21284,11445,288337,160821,33034,100869,43852,25761,52882,1144,103809,1924,84458,86079,43411,13542,139276,18141,34978,41298,7276,26481,173800,33210,17951,142652,33616,33677,2210,19941,98568,2486,192414,80136,12058,235883,50963,249638,29572,27221,47034,6124,72107,63346,97620,158513,299699,40388,23235,37176,224244,198386,121323,67992,23827,63170,17838,106622,158590,26807,5345,23489,91891,55474,74834,37981,13058,5977,72552,34706,26828,145172,19904,21367,34043,960,77092,91381,4733,47446,7680,41697,5170,16960,14741,46101,13656,473,51842,37433,11103,11551,121951,13191,97536,165932,50397,51628,129028,9069,44885,6590,59195,47045,32940,225472,90345,21833,13303,29407,96615,141951,5198,6028,18395,7181,3861,14966,156358,167182,36529,55253,25942,173153,30959,27261,50691,150176,162201,38467,48462,80602,42163,118482,168,108756,26011,17166,54149,456538,22512,91374,13816,90358,131615,18132,226707,1824,28139,26860,42253,93877,77351,65575,8980,80574,22020,27948,40422,91324,76376,13528,39281,91685,82215,122541,144066,1983,193851,17283,26320,2739,194978,4790,26845,42627,61300,65815,174612,55133,4200,191130,79771,158321,52280,166796,221620,62461,11278,4067,88152,83409,31717,121367,13522,47325,37945,10406,174348,249321,154101,64912,29938,51775,17220,15776,166138,78890,84425,54121,42861,16368,24572,291647,10197,32073,22651,11677,97509,26952,35787,18424,41910,71614,94977,72318,41594,70024,275419,37702,60199,7335,39107,61315,18271,18394,33768,87884,104277,123724,7277,56288,71981,189803,49320,3352,6798,14240,8954,69220,94433,57372,28620,68863,193727,85575,42309,41667,67689,42081,22543,44824,12719,28540,114236,101553,27638,27296,4300,5353,4663,19379,94098,3758,95888,95144,80344,87320,28447,259518,12718,71391,152731,37063,24132,31911,104896,15672,103782,1521,4945,72541,23717,122632,15619,87175,206120,29428,189780,61416,28350,44457,972,1175,47233,198738,95789,41907,21953,97034,59341,22864,53713,16873,32971,20693,20954,31336,21477,16169,38370,16412,9019,3841,24599,21938,17085,6484,81198,76413,5849,72514,12320,65247,276175,37234,59796,52642,16312,57349,198507,94148,46134,18958,125552,1747,18725,151873,14901,5490,68287,29470,3689,64794,40814,26018,25692,54450,2703,88278,124886,173087,174e3,24159,179477,24276,46004,201876,209202,445,52876,31948,30206,157610,39180,18439,44124,50469,5774,96278,222758,200216,50290,45486,20435,46986,46276,140133,142326,15569,13363,47522,92583,2182,7135,16853,22998,30272,4952,63263,35623,39096,53789,44864,20053,110392,124213,4630,16087,28221,127787,25839,77481,44693,13464,113146,6983,27069,55717,50102,4760,7107,26186,66507,59145,36032,104182,71328,29425,64317,50781,47465,94298,69706,74899,22754,120756,25108,93077,56834,73286,39928,16218,41699,176763,7555,70819,50083,26895,23315,26014,16773,123079,41712,5719,31516,90427,158540,85051,183128,40864,27505,55392,9058,45224,96857,30901,136622,96557,56304,120061,11501,151448,5773,89743,7769,86069,2935,18471,41628,10114,33660,110170,49479,26745,92846,33221,26731,18795,87076,8550,2100,29972,120289,3077,72490,33784,2630,208722,50861,63483,79029,6419,39467,14302,45286,64207,9686,67513,44170,1050,77246,59266,17055,53801,7150,11111,42432,4278,94579,362117,36175,42902,41933,39002,98489,22913,74161,84773,57036,17556,162288,74485,178760,93867,73635,128860,50362,261,67455,80001,46080,35662,4368,25247,19230,74393,22588,1822,27682,235324,13798,85998,13194,235067,23514,71669,147632,23191,134748,214683,105101,1518,25489,247114,7380,54842,26922,3971,26361,20844,68642,170517,77339,123255,8963,77818,150998,48466,36806,2732,23261,11741,236162,18243,126216,28690,50546,16385,92760,197383,246558,201295,88255,67588,71687,176076,172653,169058,33906,63747,24835,157621,43338,30050,46152,132741,2770,51371,94835,6614,15112,11749,56936,1250,19027,399017,58036,100215,23388,55815,308768,124152,94803,9521,64186,8971,28,30427,62163,7616,103838,35079,29203,131235,7743,17389,10882,37420,61460,228512,85363,41581,131077,62822,119647,10130,54445,26925,19968,29016,24446,74028,24176,61448,67185,9254,8563,119129,9771,99184,37716,39514,10532,221512,258753,218630,55980,23394,32141,61924,66749,32411,3741,36475,26678,77010,44946,91203,128749,116953,20476,49625,53116,13735,102335,29376,51946,83407,67892,59212,34685,21083,1546,112982,32972,74397,1078,190545,16082,86140,58591,89611,101531,10061,105104,76319,20035,17551,52611,169061,190842,100780,23907,90413,115619,9675,34710,193435,49443,129734,11183,258877,16318,136182,126808,44635,27304,192375,2599,125648,47051,12091,23814,721,58800,40137,66726,97930,60877,74487,7942,54326,9841,41428,13762,8211,85383,6950,99177,79806,201786,296464,124087,13144,29741,41721,47634,55088,254286,106408,17041,99064,12942,64086,45233,14005,2612,55827,255,7984,13980,38574,12776,46654,73499,249951,2101,26676,25996,132326,116415,119062,50449,31033,23038,11589,179252,20007,14860,129270,21143,17796,144715,60106,70758,69842,34674,282133,44014,16774,57268,38528,24053,46373,201667,28327,471023,51889,102667,21193,114909,84132,69317,96723,67969,16134,68145,15058,28765,32035,2524,101089,98664,25045,76571,14957,86040,118506,262428,154764,81573,39681,283900,73287,127825,544,80448,52347,38512,175971,15180,45467,33086,46552,48894,81107,43213,36672,54025,76703,8053,7608,13299,56619,20752,238099,54164,105133,1444,32942,953,37564,8e3,66316,119463,106817,404,13667,149108,128597,31267,10269,49836,106150,1484,52330,76965,160486,171648,38456,31263,22424,37738,66245,67467,143369,60471,75610,20895,115528,86070,60854,40796,49347,18989,15030,11371,37578,15779,79867,10187,86462,46402,155626,93200,40229,7090,57547,108053,99598,11088,47505,41218,206017,2173,20988,30219,22919,80563,57566,42369,93141,41675,2407,182519,120495,27154,16702,29456,14349,7958,16688,117177,140375,42467,261919,74916,153569,10836,34742,49526,7621,105997,12212,2270,392377,7755,17959,25086,232152,138791,33847,13860,35316,5811,1344,71259,50452,207539,92635,50359,5821,33674,30255,2086,2587,96264,17543,42,6029,9580,43007,139248,82831,12917,29607,25786,51467,42137,85161,100698,31561,88989,121990,278500,3602,109344,37982,15279,116442,28936,30880,87894,58079,128661,126731,67392,28051,146885,4861,16216,97344,42827,147561,153948,22684,21335,47685,1853,43349,15185,59642,10229,25520,187921,108972,5579,98037,24945,6697,19193,63734,137934,75056,89740,19767,224268,56138,63643,151661,39313,70618,84031,89723,84074,13703,85626,35460,8867,64845,3439,57906,99776,63968,49270,81130,34356,16210,23547,36446,34090,140028,72439,2221,22163,57058,363492,113754,18913,95451,48663,54464,54037,176097,68425,3023,34906,29482,117389,341780,80431,58330,16753,92616,60907,94846,147486,4498,48646,7773,46801,7778,18946,464978,47558,33223,177444,7328,15626,63337,94700,11743,9351,255024,39098,16447,42647,96230,39769,58840,10068,63439,35800,65843,58823,413844,9156,51258,7434,61791,85018,6872,3692,28096,7121,33024,6009,75532,31997,192535,9661,3304,9547,14753,31987,25314,55689,15896,20430,39472,31340,99744,25398,115569,54883,28719,205423,23071,57855,64638,149867,25671,82403,37616,20668,39989,77996,74948,140555,175248,64810,36515,46595,4958,248773,24045,28728,136673,168704,20804,114833,100325,27135,21205,96151,153134,45992,7093,13992,76047,1980,19432,145001,75159,87462,17710,1013,45556,34297,144882,20648,26061,11319,129567,108555,18872,464580,33386,22717,65948,167189,5603,135042,79542,8801,202632,18114,91882,5973,5239,67315,4431,60916,47819,71693,32597,32606,18183,45072,80329,76385,24749,51305,40314,156514,14693,130345,13168,66214,18029,12858,34801,27628,14544,10823,40522,40185,33739,148694,23548,9923,61012,28859,17933,19442,34364,99849,164107,141167,30629,21054,6744,36491,8096,42474,41706,155060,30650,10600,163442,1143,96655,61390,52359,7559,51568,64256,203854,4467,22453,14504,436398,7878,6980,8293,63610,293747,16167,35763,19627,147603,15419,18032,110744,51346,33681,54571,40472,48615,39073,21604,13754,173027,92560,11083,47299,63062,11813,52007,29883,9734,139722,15953,1550,20651,13616,49306,16113,90089,92326,7584,30712,72424,164858,6831,152871,55746,197721,34167,196442,6022,112107,55215,7538,123381,4920,43539,77165,8939,50392,34192,20225,79762,22505,58667,40770,29788,97180,82835,4568,8579,13273,363569,35898,49983,436,36598,3237,131691,62418,35591,8101,4073,379438,65218,76072,33887,2968,27573,212619,288680,68278,72851,150504,217896,6913,121339,22017,35340,51072,43616,75043,31437,10833,81487,4364,22968,41454,106687,85446,19863,109625,149241,524,141850,214404,54376,657,237023,9401,108137,53800,32474,49712,53334,126876,27337,45552,177696,8269,15036,12097,42240,2328,125374,119295,99715,2500,19624,39441,27220,102691,60957,94543,39101,18566,67362,13975,78230,25017,34017,239007,90027,39351,41681,35354,43822,1043,916,58587,141983,94818,38799,75459,41114,67432,16195,36606,59568,22272,126769,31424,68659,12287,134302,257977,5756,207285,95637,47248,117689,19583,77451,22373,12200,54993,117118,34244,29386,34562,53819,71267,64172,77665,49368,7716,59301,25749,45426,194789,17297,2650,1766,32501,45198,20403,20984,6600,14171,94604,19037,5402,29896,9938,59935,109708,88081,145182,44844,39167,352626,164173,35374,45982,6122,154,73419,220487,53834,53601,17992,8609,229321,5610,68098,66815,71012,95069,140968,27396,8957,134489,24656,86659,56598,134852,17316,123838,255436,6613,41610,138033,81452,32023,32396,123687,63398,8693,29712,30407,19296,121188,3551,36099,20032,111948,56624,16547,27453,35916,15378,52039,56849,13489,22214,73177,53097,277349,2157,14029,187886,10260,141743,246460,91880,50869,3788,49486,133566,54950,33120,129337,53768,18333,9525,26902,312251,10297,9020,70759,16647,112432,59260,84609,9818,82766,73569,468,46001,75780,55028,52106,11498,43645,108069,17150,17753,29417,16705,31799,9606,289,122254,115975,8620,6133,255357,56908,14456,133464,43554,79224,11247,29630,160,12756,25464,65960,350428,62521,321796,100359,67358,35169,46172,113128,48988,88868,31094,33266,6847,60887,98188,49659,69117,92977,220228,13947,80181,35103,62170,97351,13475,2440,199768,19498,36597,46971,25234,67806,62881,84717,73648,181966,10488,94149,21550,26655,63436,48375,14405,165650,9621,24439,28043,42735,4490,29963,56674,45373,1934,262446,50855,67098,26898,5261,52696,40644,33900,9440,180286,87162,22940,19704,26936,69769,10254,101759,27406,12243,48e3,73926,113215,54935,5726,192787,4312,106216,9366,11550,52949,23457,212271,277152,133895,108374,6191,96477,29980,218916,58024,54696,40853,91124,65894,91170,65908,252552,6793,29212,15389,44516,122515,52617,35058,9017,103536,39510,49136,19242,130652,662077,74699,47024,31422,8517,73351,24399,13867,128360,4810,4434,61779,111983,61036,17798,110240,59722,102960,39688,10001,23803,23039,176498,56659,44814,134295,17188,77577,74466,226175,102472,154333,63900,111747,18062,41171,79669,32773,408933,42562,28931,30907,107388,43487,2946,240310,23938,24354,319,184983,7927,6488,1422,10790,68809,68209,64775,4361,202,17123,59634,51200,44391,18188,17843,2619,74278,3230,9540,47187,21702,36274,56894,43907,16310,34790,16866,6150,5561,13587,107545,108873,126867,86986,28640,33427,19017,5762,80637,17430,46903,2047,131055,25958,13558,5444,47152,13900,44563,122857,45348,70863,39593,54332,38068,33637,318,40310,143467,18502,24520,11377,62013,28942,27246,28269,83545,17999,59015,90707,30065,15161,34720,1263,37008,2012,6060,98575,92933,5721,299,199555,24578,29223,2985,743,115825,109523,136657,47454,26378,53586,3733,174945,93340,244456,5693,37386,28782,89767,27545,23573,18798,136425,34320,84778,20041,48453,38215,7477,71958,40621,8773,5874,187927,105965,51100,43533,18083,8443,10180,43597,2003,183999,69689,12216,129696,146188,62389,34044,68410,12765,43273,26949,266807,3345,34477,79197,5688,47539,213110,21634,22257,50092,32222,42346,39530,63668,98,134978,74022,5152,59088,174145,37220,9934,9545,118937,5724,87240,19875,15784,40143,23263,87513,181654,285152,37881,263241,4966,43934,10433,186657,6470,74416,225854,25908,142677,246262,32280,6192,75890,45546,143264,135305,29742,47013,77787,11732,126658,8763,37950,21806,57557,113464,89465,108995,164574,23894,22996,23169,15369,23117,17642,130607,40503,36239,280990,44666,9981,40427,147487,26869,168452,32886,32991,46798,240839,15111,70502,65697,88548,44145,28701,48767,31139,206777,35659,181164,166262,14554,171445,31786,66523,76607,17956,6507,31279,90476,116611,167918,6560,1243,115324,80128,41867,55897,187323,37069,32596,189444,145931,13390,105530,65709,26805,6999,55714,41300,22915,68951,22138,21120,22264,10058,19945,33635,56123,99085,10032,5818,6016,46649,57476,35264,94413,112522,262288,93686,83038,14341,23204,28807,66084,77987,6101,126673,7133,38126,5923,122091,170240,97772,46874,215746,43948,41622,3272,55596,8332,146411,251315,13533,8561,81521,115449,48616,175175,2063,186556,3036,134537,75772,29728,82360,22973,186559,86348,89100,38388,82297,45610,2613,87082,9986,177812,57884,23591,47485,42543,33582,44713,74439,257444,252451,31825,35631,38540,33066,5147,13973,4343,51830,70378,22827,26448,95560,36896,241741,48067,203953,298860,61620,20450,3220,67272,6586,107662,100160,108684,6929,57226,4762,7457,1320,40404,77204,99309,62750,208653,59977,44e3,74315,34332,5819,172217,64904,114077,18147,84012,1791,98456,90930,21446,116669,103938,7422,85140,59713,5768,326211,16239,75411,13229,29398,10758,236107,1539,112472,95979,152154,151294,306,21196,38146,10700,6891,84282,109646,56492,40539,6589,119491,51354,30685,140209,136906,29622,73617,49553,70525,51671,166869,139616,74395,37439,49595,45678,11959,33211,86560,52434,9282,62690,112155,130810,5243,108261,99970,265613,72551,80049,6391,33365,90721,66737,69872,87011,1860,9032,112544,60905,37371,89015,140351,19076,850,373531,2802,36725,218795,72062,28990,16550,24614,7815,6187,26336,33373,32162,42791,73555,32062,23386,10244,56392,49442,27076,136262,12412,14883,1134,33675,97153,199281,15608,100152,74072,47942,254301,36451,16026,10687,65067,56708,254030,30290,50490,13864,57941,259331,35588,23485,43486,24869,21620,92971,22072,88645,1048,182050,13343,32452,14825,19509,3325,216938,45740,99716,189082,53740,78245,25609,24311,176777,47340,308354,40669,66085,14102,125339,9225,128709,97207,1271,200933,78439,113451,88975,18324,46521,11819,18570,141756,72512,170020,52754,63550,118515,103073,93330,32736,50499,14722,31600,68452,398867,29316,172786,18417,104924,2606,5670,84818,16288,67106,59580,82929,607401,291,85829,359,15897,35830,50696,65630,52672,22115,356968,29895,40837,231192,34024,38957,26722,406,23335,124952,72068,68804,13268,147101,164740,276569,162596,66943,11569,26654,66358,4777,23229,102127,5848,978,2921,59666,5371,28212,90108,42938,39320,2499,4271,108792,33510,125072,71653,65239,38250,66357,38577,13964,86251,35708,50755,36010,29448,12209,3844,38222,206337,100876,67827,137088,14167,252225,84163,195270,1306,5703,54198,779,46802,22028,51124,86759,70560,113164,35685,162145,45471,34561,422,2611,6464,47486,19223,38246,9191,18331,89942,243642,212364,15893,17518,22617,6409,30046,126182,59716,36560,104428,18846,26592,19458,50793,147333,30826,1388,27647,10922,14495,33545,19269,135828,39727,41601,46931,233379,49169,131130,182112,16276,82381,118209,142445,128310,19672,28740,82907,33436,3118,102206,28723,24819,41937,38854,5157,3881,111491,1142,9776,421673,152241,29309,14961,87854,6054,15424,3796,82656,54996,2108,55367,239450,154525,9643,118103,106041,64601,68549,48707,30266,25772,18740,9462,229669,91798,112152,191327,14493,72828,8175,66636,236474,25817,87351,129027,76653,20422,22983,71240,27846,44661,12399,46158,77704,53101,35032,11072,17300,109294,33638,24408,1895,11241,760,17584,82479,125877,63150,141075,34259,23274,81698,15732,43577,48340,91584,14688,16379,24481,150280,96420,262050,48635,43727,61819,56268,72003,88178,17281,79912,13218,122519,125295,166396,11811,2171,118930,67746,17636,178278,174656,95661,173039,83845,79689,17473,98555,127696,203415,54730,22925,232239,9309,12136,175026,20740,180188,10747,39816,314017,266131,10040,175732,112550,220651,31974,37393,888,23008,86799,4303,64905,148467,75337,251,3284,370102,50264,9835,5438,23655,4481,29851,329,12855,7162,64931,78141,12804,42372,296771,83547,18624,34874,86271,3360,48665,77735,88767,11463,63527,28889,22258,29140,194315,113924,25499,6406,31334,1845,4802,49184,43455,35469,127594,92970,61038,115005,38840,87761,106838,8811,20572,55637,11162,96721,132425,108925,2948,125457,36356,3502,75270,27622,127192,2561,123095,49394,61155,16897,110064,9699,89448,53356,19628,220310,21622,83036,9885,112214,6087,26713,17901,161912,91492,3440,68594,9266,92238,8087,6866,150194,72175,80701,13459,31836,43243,239700,95846,44749,50647,21945,230538,120612,132371,244604,5193,105637,34661,41341,68775,85393,1874,8771,33718,49672,77403,595452,99507,6490,58895,128742,7704,39239,73217,43816,62824,37804,199976,22361,80005,87514,94832,14089,4574,139975,59142,75523,100268,43906,53442,15152,2547,186002,17011,19513,204282,3343,60568,128318,119250,4298,51871,41336,71759,21921,45074,98169,145889,99427,11350,1237,5520,28799,7803,53702,21026,136352,38293,128690,12158,90132,44600,10184,26957,39459,126025,78904,82999,59373,39301,150198,120529,153042,20177,50089,14764,271571,30530,123161,38975,101562,22941,5648,124654,109243,69817,71675,49162,106884,21241,107795,30258,16572,188262,141456,7688,60718,8271,11044,32440,104608,103419,236109,93156,43293,128929,42107,67180,25201,115254,185488,130954,72813,167547,20537,39969,38432,22582,184022,1139,27199,5655,17767,97412,122606,209377,27070,35871,326617,188954,42680,73512,80911,22629,3011,95021,315242,157737,383,41821,41808,19335,27950,15674,25677,110950,35375,76835,59108,57370,35262,16569,160415,37706,78086,32041,49691,137143,9782,172080,50148,77917,6323,10110,69172,17711,21795,59511,76184,135114,31046,132319,59105,157578,20549,80778,57649,158421,65143,4575,72235,21899,10797,92745,34035,106079,80159,4508,78304,25350,75457,46458,32937,25623,47,8531,104751,84953,8138,36508,187199,66310,115274,13253,32461,38536,1916,42007,187160,35055,26325,84394,35963,94216,45590,97782];class EL{constructor(t,r){e._defineProperty(this,"log",void 0),e._defineProperty(this,"peerRouting",void 0),e._defineProperty(this,"routingTable",void 0),e._defineProperty(this,"refreshInterval",void 0),e._defineProperty(this,"refreshQueryTimeout",void 0),e._defineProperty(this,"commonPrefixLengthRefreshedAt",void 0),e._defineProperty(this,"refreshTimeoutId",void 0);var{peerRouting:n,routingTable:i,refreshInterval:o,refreshQueryTimeout:a,logPrefix:s}=r;this.log=t.logger.forComponent("".concat(s,":routing-table:refresh")),this.peerRouting=n,this.routingTable=i,this.refreshInterval=null!=o?o:3e5,this.refreshQueryTimeout=null!=a?a:3e4,this.commonPrefixLengthRefreshedAt=[],this.refreshTable=this.refreshTable.bind(this)}afterStart(){var t=this;return e._asyncToGenerator((function*(){t.log("refreshing routing table every ".concat(t.refreshInterval,"ms")),t.refreshTable(!0)}))()}stop(){var t=this;return e._asyncToGenerator((function*(){null!=t.refreshTimeoutId&&clearTimeout(t.refreshTimeoutId)}))()}refreshTable(){var t=this,r=arguments.length>0&&void 0!==arguments[0]&&arguments[0];this.log("refreshing routing table");var n=this._maxCommonPrefix(),i=this._getTrackedCommonPrefixLengthsForRefresh(n);this.log("max common prefix length ".concat(n)),this.log("tracked CPLs [ ".concat(i.map((e=>e.toISOString())).join(", ")," ]")),Promise.all(i.map(function(){var o=e._asyncToGenerator((function*(e,o){try{if(yield t._refreshCommonPrefixLength(o,e,r),0===t._numPeersForCpl(n))for(var a=Math.min(2*(o+1),i.length-1),s=o+1;s<a+1;s++)try{yield t._refreshCommonPrefixLength(s,e,r)}catch(e){t.log.error(e)}}catch(e){t.log.error(e)}}));return function(e,t){return o.apply(this,arguments)}}())).catch((e=>{this.log.error(e)})).then((()=>{this.refreshTimeoutId=setTimeout(this.refreshTable,this.refreshInterval),null!=this.refreshTimeoutId.unref&&this.refreshTimeoutId.unref()})).catch((e=>{this.log.error(e)}))}_refreshCommonPrefixLength(t,r,n){var i=this;return e._asyncToGenerator((function*(){if(!n&&r.getTime()>Date.now()-i.refreshInterval)i.log("not running refresh for cpl %s as time since last refresh not above interval",t);else{var e=yield i._generateRandomPeerId(t);i.log("starting refreshing cpl %s with key %p (routing table size was %s)",t,e,i.routingTable.size);var o=AbortSignal.timeout(i.refreshQueryTimeout),a=yield uL(i.peerRouting.getClosestPeers(e.toMultihash().bytes,{signal:o}));i.log("found ".concat(a," peers that were close to imaginary peer %p"),e),i.log("finished refreshing cpl %s with key %p (routing table size is now %s)",t,e,i.routingTable.size)}}))()}_getTrackedCommonPrefixLengthsForRefresh(e){e>15&&(e=15);for(var t=[],r=0;r<=e;r++){var n;t[r]=null!==(n=this.commonPrefixLengthRefreshedAt[r])&&void 0!==n?n:new Date}return t}_generateRandomPeerId(t){var r=this;return e._asyncToGenerator((function*(){if(null==r.routingTable.kb)throw new Error("Routing table not started");if(null==r.routingTable.kb.localPeer)throw new Error("Local peer not set");var e=gl(2),n=(e[1]<<8)+e[0];return oc(Ae(yield r._makePeerId(r.routingTable.kb.localPeer.kadId,n,t)))}))()}_makePeerId(t,r,n){return e._asyncToGenerator((function*(){if(n>15)throw new Error("Cannot generate peer ID for common prefix length greater than ".concat(15));var e=new DataView(t.buffer,t.byteOffset,t.byteLength).getUint16(0,!1),i=65535<<16-(n+1),o=PL[(e^32768>>n)&i|r&~i],a=new ArrayBuffer(34),s=new DataView(a,0,a.byteLength);return s.setUint8(0,De.code),s.setUint8(1,32),s.setUint32(2,o,!1),new Uint8Array(s.buffer,s.byteOffset,s.byteLength)}))()}_maxCommonPrefix(){var e=0;for(var t of this._prefixLengths())t>e&&(e=t);return e}_numPeersForCpl(e){var t=0;for(var r of this._prefixLengths())r===e&&t++;return t}*_prefixLengths(){var e;if(null!=(null===(e=this.routingTable.kb)||void 0===e?void 0:e.localPeer))for(var{kadId:t}of this.routingTable.kb.toIterable()){var r=Dk(this.routingTable.kb.localPeer.kadId,t),n=0;for(var i of r){if(0!==i)break;n++}yield n}}}class AL{constructor(t,r){e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"providers",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"log",void 0),this.log=t.logger.forComponent("".concat(r.logPrefix,":rpc:handlers:add-provider")),this.peerId=t.peerId,this.providers=r.providers,this.peerStore=t.peerStore}handle(t,r){var n=this;return e._asyncToGenerator((function*(){if(null==r.key||0===r.key.length)throw new ya("Missing key");var i;try{i=je.decode(r.key)}catch(e){throw new ya("Invalid CID")}null!=r.providers&&0!==r.providers.length||n.log.error("no providers found in message"),n.log("%p asked us, %p to store provider record for for %c",t,n.peerId,i),yield Promise.all(r.providers.map(function(){var r=e._asyncToGenerator((function*(e){var r=oc(Ae(e.id)),o=e.multiaddrs.map((e=>sr(e)));t.equals(r)?e.multiaddrs.length<1?n.log("no valid addresses for provider %p. Ignore",t):(n.log.trace("received provider %p for %s (addrs %s)",t,i,o),yield n.providers.addProvider(i,r),yield n.peerStore.merge(r,{multiaddrs:o})):n.log("invalid provider peer %p from %p",e.id,t)}));return function(e){return r.apply(this,arguments)}}()))}))()}}class kL{constructor(t,r){e._defineProperty(this,"peerRouting",void 0),e._defineProperty(this,"peerInfoMapper",void 0),e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"addressManager",void 0),e._defineProperty(this,"log",void 0);var{peerRouting:n,logPrefix:i}=r;this.log=t.logger.forComponent("".concat(i,":rpc:handlers:find-node")),this.peerId=t.peerId,this.addressManager=t.addressManager,this.peerRouting=n,this.peerInfoMapper=r.peerInfoMapper}handle(t,r){var n=this;return e._asyncToGenerator((function*(){if(n.log("incoming request from %p for peers closer to %b",t,r.key),null==r.key)throw new ya("Invalid FIND_NODE message received - key was missing");var e=yield n.peerRouting.getCloserPeersOffline(r.key,t);nt(n.peerId.toMultihash().bytes,r.key)&&e.push({id:n.peerId,multiaddrs:n.addressManager.getAddresses().map((e=>e.decapsulateCode(lr("p2p").code)))});var i={type:tO.FIND_NODE,clusterLevel:r.clusterLevel,closer:e.map(n.peerInfoMapper).filter((e=>{var{multiaddrs:t}=e;return t.length})).map((e=>({id:e.id.toMultihash().bytes,multiaddrs:e.multiaddrs.map((e=>e.bytes))}))),providers:[]};return 0===i.closer.length&&n.log("could not find any peers closer to %b than %p",r.key,t),i}))()}}class xL{constructor(t,r){e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"peerRouting",void 0),e._defineProperty(this,"providers",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"peerInfoMapper",void 0),e._defineProperty(this,"log",void 0);var{peerRouting:n,providers:i,logPrefix:o}=r;this.log=t.logger.forComponent("".concat(o,":rpc:handlers:get-providers")),this.peerId=t.peerId,this.peerStore=t.peerStore,this.peerRouting=n,this.providers=i,this.peerInfoMapper=r.peerInfoMapper}handle(t,r){var n=this;return e._asyncToGenerator((function*(){if(null==r.key)throw new ya("Invalid GET_PROVIDERS message received - key was missing");var i;try{i=je.decode(r.key)}catch(e){throw new ya("Invalid CID")}n.log("%p asking for providers for %s",t,i);var[o,a]=yield Promise.all([Rc(Qc(yield n.providers.getProviders(i),function(){var t=e._asyncToGenerator((function*(e){var t=yield n.peerStore.get(e),r={id:t.id,multiaddrs:t.addresses.map((e=>{var{multiaddr:t}=e;return t}))};return r}));return function(e){return t.apply(this,arguments)}}())),n.peerRouting.getCloserPeersOffline(r.key,n.peerId)]),s={type:tO.GET_PROVIDERS,key:r.key,clusterLevel:r.clusterLevel,closer:a.map(n.peerInfoMapper).filter((e=>{var{id:t,multiaddrs:r}=e;return r.length>0})).map((e=>({id:e.id.toMultihash().bytes,multiaddrs:e.multiaddrs.map((e=>e.bytes))}))),providers:o.map(n.peerInfoMapper).filter((e=>{var{id:t,multiaddrs:r}=e;return r.length>0})).map((e=>({id:e.id.toMultihash().bytes,multiaddrs:e.multiaddrs.map((e=>e.bytes))})))};return n.log("got %s providers %s closerPeers",s.providers.length,s.closer.length),s}))()}_getAddresses(t){return e._asyncToGenerator((function*(){return[]}))()}}class TL{constructor(t,r){e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"datastore",void 0),e._defineProperty(this,"peerRouting",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"datastorePrefix",void 0),this.log=t.logger.forComponent("".concat(r.logPrefix,":rpc:handlers:get-value")),this.datastorePrefix="".concat(r.datastorePrefix,"/record"),this.peerStore=t.peerStore,this.datastore=t.datastore,this.peerRouting=r.peerRouting}handle(t,r){var n=this;return e._asyncToGenerator((function*(){var e=r.key;if(n.log("%p asked for key %b",t,e),null==e||0===e.length)throw new ya("Invalid key");var i={type:tO.GET_VALUE,key:e,clusterLevel:r.clusterLevel,closer:[],providers:[]};if(function(e){return"/pk/"===Ze(e.subarray(0,4))}(e)){n.log("is public key");var o,a=function(e){return oc(Ae(e.subarray(4)))}(e);try{var s=yield n.peerStore.get(a);if(null==s.id.publicKey)throw new ua("No public key found in key book");o=ql(s.id.publicKey)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=o)return n.log("returning found public key"),i.record=new pO(e,o,new Date).serialize(),i}var[l,c]=yield Promise.all([n._checkLocalDatastore(e),n.peerRouting.getCloserPeersOffline(e,t)]);return null!=l&&(n.log("had record for %b in local datastore",e),i.record=l.serialize()),c.length>0&&(n.log("had %s closer peers in routing table",c.length),i.closer=c.map((e=>({id:e.id.toMultihash().bytes,multiaddrs:e.multiaddrs.map((e=>e.bytes))})))),i}))()}_checkLocalDatastore(t){var r=this;return e._asyncToGenerator((function*(){r.log("checkLocalDatastore looking for %b",t);var e,n=OO(r.datastorePrefix,t);try{e=yield r.datastore.get(n)}catch(e){if("NotFoundError"===e.name)return;throw e}var i=pO.deserialize(e);if(!(null==i.timeReceived||Date.now()-i.timeReceived.getTime()>lO))return i;yield r.datastore.delete(n)}))()}}class IL{constructor(t,r){e._defineProperty(this,"log",void 0),this.log=t.logger.forComponent("".concat(r.logPrefix,":rpc:handlers:ping"))}handle(t,r){var n=this;return e._asyncToGenerator((function*(){return n.log("ping from %p",t),r}))()}}class CL{constructor(t,r){e._defineProperty(this,"components",void 0),e._defineProperty(this,"validators",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"datastorePrefix",void 0);var{validators:n}=r;this.components=t,this.log=t.logger.forComponent("".concat(r.logPrefix,":rpc:handlers:put-value")),this.datastorePrefix="".concat(r.datastorePrefix,"/record"),this.validators=n}handle(t,r){var n=this;return e._asyncToGenerator((function*(){var e=r.key;if(n.log("%p asked us to store value for key %b",t,e),null==r.record){var i="Empty record from: ".concat(t.toString());throw n.log.error(i),new ya(i)}try{var o=pO.deserialize(r.record);yield kO(n.validators,o),o.timeReceived=new Date;var a=OO(n.datastorePrefix,o.key);yield n.components.datastore.put(a,o.serialize().subarray()),n.log("put record for %b into datastore under key %k",e,a)}catch(t){n.log("did not put record for key %b into datastore %o",e,t)}return r}))()}}class BL{constructor(t,r){var n,i;e._defineProperty(this,"handlers",void 0),e._defineProperty(this,"routingTable",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"metrics",void 0),this.metrics={operations:null===(n=t.metrics)||void 0===n?void 0:n.registerCounterGroup("".concat(r.metricsPrefix,"_inbound_rpc_requests_total")),errors:null===(i=t.metrics)||void 0===i?void 0:i.registerCounterGroup("".concat(r.metricsPrefix,"_inbound_rpc_errors_total"))},this.log=t.logger.forComponent("".concat(r.logPrefix,":rpc")),this.routingTable=r.routingTable,this.handlers={[tO.GET_VALUE.toString()]:new TL(t,r),[tO.PUT_VALUE.toString()]:new CL(t,r),[tO.FIND_NODE.toString()]:new kL(t,r),[tO.ADD_PROVIDER.toString()]:new AL(t,r),[tO.GET_PROVIDERS.toString()]:new xL(t,r),[tO.PING.toString()]:new IL(t,r)}}handleMessage(t,r){var n=this;return e._asyncToGenerator((function*(){var e=n.handlers[r.type];if(null!=e)try{var i;return null===(i=n.metrics.operations)||void 0===i||i.increment({[r.type]:!0}),yield e.handle(t,r)}catch(e){var o;null===(o=n.metrics.errors)||void 0===o||o.increment({[r.type]:!0})}else n.log.error("no handler found for message type: ".concat(r.type))}))()}onIncomingStream(t){var r=this,n="unknown";Promise.resolve().then(e._asyncToGenerator((function*(){var{stream:i,connection:o}=t,a=o.remotePeer,s=r;yield lu(i,(e=>Hp(e)),function(){var t=e._wrapAsyncGenerator((function*(t){var r,i=!1,o=!1;try{for(var l,c=e._asyncIterator(t);i=!(l=yield e._awaitAsyncGenerator(c.next())).done;i=!1){var u=l.value,d=aO.decode(u);n=d.type,s.log("incoming %s from %p",d.type,a);var h=yield e._awaitAsyncGenerator(s.handleMessage(a,d));null!=h&&(yield aO.encode(h))}}catch(e){o=!0,r=e}finally{try{i&&null!=c.return&&(yield e._awaitAsyncGenerator(c.return()))}finally{if(o)throw r}}}));return function(e){return t.apply(this,arguments)}}(),(e=>Vp(e)),i)}))).catch((e=>{this.log.error("error handling %s RPC message from %p - %e",n,t.connection.remotePeer,e)}))}}class NL extends Ia{constructor(t,r){super(),e._defineProperty(this,"log",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"protocol",void 0),e._defineProperty(this,"running",void 0),e._defineProperty(this,"registrarId",void 0);var{protocol:n,logPrefix:i}=r;this.components=t,this.log=t.logger.forComponent("".concat(i,":topology-listener")),this.running=!1,this.protocol=n}isStarted(){return this.running}start(){var t=this;return e._asyncToGenerator((function*(){t.running||(t.running=!0,t.registrarId=yield t.components.registrar.register(t.protocol,{onConnect:e=>{t.log("observed peer %p with protocol %s",e,t.protocol),t.dispatchEvent(new CustomEvent("peer",{detail:e}))}}))}))()}stop(){var t=this;return e._asyncToGenerator((function*(){t.running=!1,null!=t.registrarId&&(t.components.registrar.unregister(t.registrarId),t.registrarId=void 0)}))()}}class DL{constructor(t){e._defineProperty(this,"dht",void 0),this.dht=t}provide(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};yield Nc(n.dht.provide(t,e))}))()}cancelReprovide(t){var r=this;return e._asyncToGenerator((function*(){yield r.dht.cancelReprovide(t)}))()}findProviders(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(r.dht.findProviders(t,n));o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;"PROVIDER"===c.name&&(yield*e._asyncGeneratorDelegate(e._asyncIterator(c.providers),e._awaitAsyncGenerator))}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}()})).apply(this,arguments)}put(t,r,n){var i=this;return e._asyncToGenerator((function*(){yield Nc(i.dht.put(t,r,n))}))()}get(t,r){var n=this;return e._asyncToGenerator((function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(n.dht.get(t,r));o=!(s=yield l.next()).done;o=!1){var c=s.value;if("VALUE"===c.name)return c.value}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield l.return())}finally{if(a)throw i}}throw new ua("Could not find value for key")}))()}}class GL{constructor(t){e._defineProperty(this,"dht",void 0),this.dht=t}findPeer(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i,o=r.length>1&&void 0!==r[1]?r[1]:{},a=!1,s=!1;try{for(var l,c=e._asyncIterator(n.dht.findPeer(t,o));a=!(l=yield c.next()).done;a=!1){var u=l.value;if("FINAL_PEER"===u.name)return u.peer}}catch(e){s=!0,i=e}finally{try{a&&null!=c.return&&(yield c.return())}finally{if(s)throw i}}throw new ua("Peer not found")}))()}getClosestPeers(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(r.dht.getClosestPeers(t,n));o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;"FINAL_PEER"===c.name&&(yield c.peer)}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}()})).apply(this,arguments)}}var RL;class OL extends Ia{constructor(t){var r,n,i,o,a,s,l,c,u,d,h,p,f,v,y=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};super(),v=this,e._defineProperty(this,"protocol",void 0),e._defineProperty(this,"routingTable",void 0),e._defineProperty(this,"providers",void 0),e._defineProperty(this,"network",void 0),e._defineProperty(this,"peerRouting",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"running",void 0),e._defineProperty(this,"kBucketSize",void 0),e._defineProperty(this,"clientMode",void 0),e._defineProperty(this,"validators",void 0),e._defineProperty(this,"selectors",void 0),e._defineProperty(this,"queryManager",void 0),e._defineProperty(this,"contentFetching",void 0),e._defineProperty(this,"contentRouting",void 0),e._defineProperty(this,"routingTableRefresh",void 0),e._defineProperty(this,"rpc",void 0),e._defineProperty(this,"topologyListener",void 0),e._defineProperty(this,"querySelf",void 0),e._defineProperty(this,"maxInboundStreams",void 0),e._defineProperty(this,"maxOutboundStreams",void 0),e._defineProperty(this,"dhtContentRouting",void 0),e._defineProperty(this,"dhtPeerRouting",void 0),e._defineProperty(this,"peerInfoMapper",void 0),e._defineProperty(this,"reprovider",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/kad-dht"),e._defineProperty(this,Ra,["@libp2p/content-routing","@libp2p/peer-routing","@libp2p/peer-discovery"]),e._defineProperty(this,Oa,["@libp2p/identify"]);var g=null!==(r=y.logPrefix)&&void 0!==r?r:"libp2p:kad-dht",m=null!==(n=y.datastorePrefix)&&void 0!==n?n:"/dht",w=null!==(i=y.metricsPrefix)&&void 0!==i?i:"libp2p_kad_dht",b={queries:null===(o=t.metrics)||void 0===o?void 0:o.registerMetricGroup("".concat(w,"_operations_total"),{label:"operation"}),errors:null===(a=t.metrics)||void 0===a?void 0:a.registerCounterGroup("".concat(w,"_operation_errors_total"),{label:"operation"}),queryTime:null===(s=t.metrics)||void 0===s?void 0:s.registerMetricGroup("".concat(w,"_operation_time_seconds"),{label:"operation"}),errorTime:null===(l=t.metrics)||void 0===l?void 0:l.registerMetricGroup("".concat(w,"_operation_error_time_seconds"),{label:"operation"})};this.running=!1,this.components=t,this.log=t.logger.forComponent(g),this.protocol=null!==(c=y.protocol)&&void 0!==c?c:"/ipfs/kad/1.0.0",this.kBucketSize=null!==(u=y.kBucketSize)&&void 0!==u?u:20,this.clientMode=null===(d=y.clientMode)||void 0===d||d,this.maxInboundStreams=null!==(h=y.maxInboundStreams)&&void 0!==h?h:32,this.maxOutboundStreams=null!==(p=y.maxOutboundStreams)&&void 0!==p?p:64,this.peerInfoMapper=null!==(f=y.peerInfoMapper)&&void 0!==f?f:BO;var _=iB();this.providers=new sL(t,e._objectSpread2(e._objectSpread2({},y.providers),{},{logPrefix:g,datastorePrefix:m,lock:_})),this.validators=e._objectSpread2(e._objectSpread2({},IO),y.validators),this.selectors=e._objectSpread2(e._objectSpread2({},AO),y.selectors),this.network=new nL(t,{protocol:this.protocol,logPrefix:g,metricsPrefix:w}),this.routingTable=new SL(t,{kBucketSize:y.kBucketSize,pingOldContactTimeout:y.pingOldContactTimeout,pingOldContactConcurrency:y.pingOldContactConcurrency,pingOldContactMaxQueueSize:y.pingOldContactMaxQueueSize,pingNewContactTimeout:y.pingNewContactTimeout,pingNewContactConcurrency:y.pingNewContactConcurrency,pingNewContactMaxQueueSize:y.pingNewContactMaxQueueSize,protocol:this.protocol,logPrefix:g,metricsPrefix:w,prefixLength:y.prefixLength,splitThreshold:y.kBucketSplitThreshold,network:this.network});var S=Yc();!0===y.allowQueryWithZeroPeers&&S.resolve(),this.queryManager=new cL(t,{disjointPaths:Math.ceil(this.kBucketSize/2),logPrefix:g,metricsPrefix:w,initialQuerySelfHasRun:S,routingTable:this.routingTable}),this.peerRouting=new aL(t,{routingTable:this.routingTable,network:this.network,validators:this.validators,queryManager:this.queryManager,logPrefix:g}),this.contentFetching=new VO(t,{validators:this.validators,selectors:this.selectors,peerRouting:this.peerRouting,queryManager:this.queryManager,network:this.network,logPrefix:g,datastorePrefix:m}),this.contentRouting=new HO(t,{network:this.network,peerRouting:this.peerRouting,queryManager:this.queryManager,routingTable:this.routingTable,providers:this.providers,logPrefix:g}),this.routingTableRefresh=new EL(t,{peerRouting:this.peerRouting,routingTable:this.routingTable,logPrefix:g}),this.rpc=new BL(t,{routingTable:this.routingTable,providers:this.providers,peerRouting:this.peerRouting,validators:this.validators,logPrefix:g,metricsPrefix:w,datastorePrefix:m,peerInfoMapper:this.peerInfoMapper}),this.topologyListener=new NL(t,{protocol:this.protocol,logPrefix:g}),this.querySelf=new hL(t,{peerRouting:this.peerRouting,interval:y.querySelfInterval,initialInterval:y.initialQuerySelfInterval,logPrefix:g,initialQuerySelfHasRun:S,routingTable:this.routingTable,operationMetrics:b}),this.reprovider=new pL(t,e._objectSpread2(e._objectSpread2({},y.reprovide),{},{logPrefix:g,metricsPrefix:w,datastorePrefix:m,contentRouting:this.contentRouting,lock:_,operationMetrics:b})),this.network.addEventListener("peer",(e=>{var t=e.detail;this.onPeerConnect(t).catch((e=>{this.log.error("could not add %p to routing table",t.id,e)})),this.dispatchEvent(new CustomEvent("peer",{detail:t}))})),this.topologyListener.addEventListener("peer",(t=>{var r=t.detail;Promise.resolve().then(e._asyncToGenerator((function*(){var e=yield v.components.peerStore.get(r),t={id:r,multiaddrs:e.addresses.map((e=>{var{multiaddr:t}=e;return t})),protocols:e.protocols};yield v.onPeerConnect(t)}))).catch((e=>{this.log.error("could not add %p to routing table - %e",r,e)}))})),this.dhtPeerRouting=new GL(this),this.dhtContentRouting=new DL(this),null==y.clientMode&&t.events.addEventListener("self:peer:update",(t=>{this.log("received update of self-peer info"),Promise.resolve().then(e._asyncToGenerator((function*(){var e=t.detail.peer.addresses.some((e=>{var{multiaddr:t}=e;return function(e){var t=e.stringTuples();for(var r of t)if(290===r[0])return!1;if(54===t[0][0]||55===t[0][0]||56===t[0][0])return!0;if(4===t[0][0]||41===t[0][0]){var n=CN("".concat(t[0][1]));return null==n||!n}return!1}(t)})),r=v.getMode();e&&"client"===r?yield v.setMode("server"):"server"!==r||e||(yield v.setMode("client"))}))).catch((e=>{this.log.error("error setting dht server mode",e)}))})),this.get=UO(this.get.bind(this),b,"GET_VALUE"),this.findProviders=UO(this.findProviders.bind(this),b,"FIND_PROVIDERS"),this.findPeer=UO(this.findPeer.bind(this),b,"FIND_PEER"),this.getClosestPeers=UO(this.getClosestPeers.bind(this),b,"GET_CLOSEST_PEERS"),this.provide=UO(this.provide.bind(this),b,"PROVIDE"),this.put=UO(this.put.bind(this),b,"PUT_VALUE")}get[Vo](){return this.dhtContentRouting}get[Qo](){return this.dhtPeerRouting}get[qo](){return this}onPeerConnect(t){var r=this;return e._asyncToGenerator((function*(){if(r.log.trace("peer %p connected",t.id),0!==(t=r.peerInfoMapper(t)).multiaddrs.length)try{yield r.routingTable.add(t.id)}catch(e){r.log.error("could not add %p to routing table",t.id,e)}else r.log.trace("ignoring %p as there were no valid addresses in %s after filtering",t.id,t.multiaddrs.map((e=>e.toString())))}))()}isStarted(){return this.running}getMode(){return this.clientMode?"client":"server"}setMode(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]&&r[1];t!==n.getMode()||e?(yield n.components.registrar.unhandle(n.protocol),t!==n.getMode()||e?"client"===t?(n.log("enabling client mode while in %s mode",n.getMode()),n.clientMode=!0):(n.log("enabling server mode while in %s mode",n.getMode()),n.clientMode=!1,yield n.components.registrar.handle(n.protocol,n.rpc.onIncomingStream.bind(n.rpc),{maxInboundStreams:n.maxInboundStreams,maxOutboundStreams:n.maxOutboundStreams})):n.log("already in %s mode",t)):n.log("already in %s mode",t)}))()}start(){var t=this;return e._asyncToGenerator((function*(){t.running||(t.running=!0,yield t.setMode(t.clientMode?"client":"server",!0),yield Ba(t.routingTable,t.queryManager,t.network,t.topologyListener,t.routingTableRefresh,t.reprovider),yield Ba(t.querySelf))}))()}stop(){var t=this;return e._asyncToGenerator((function*(){t.running=!1,yield Da(t.querySelf,t.queryManager,t.network,t.routingTable,t.routingTableRefresh,t.topologyListener,t.reprovider)}))()}put(t,r){var n=this;return e._wrapAsyncGenerator((function(t,r){var i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(n.contentFetching.put(t,r,i)))}()})).apply(this,arguments)}get(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(r.contentFetching.get(t,n)))}()})).apply(this,arguments)}provide(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(r.contentRouting.provide(t,r.components.addressManager.getAddresses(),n)))}()})).apply(this,arguments)}cancelReprovide(t){var r=this;return e._asyncToGenerator((function*(){yield r.providers.removeProvider(t,r.components.peerId)}))()}findProviders(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(r.contentRouting.findProviders(t,n)))}()})).apply(this,arguments)}findPeer(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(r.peerRouting.findPeer(t,n)))}()})).apply(this,arguments)}getClosestPeers(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(r.peerRouting.getClosestPeers(t,n)))}()})).apply(this,arguments)}refreshRoutingTable(){var t=this;return e._asyncToGenerator((function*(){t.routingTableRefresh.refreshTable(!0)}))()}}function LL(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new OL(t,e)}function ML(e){if("object"!=typeof e||null===e)return!1;var t=Object.getPrototypeOf(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||Symbol.toStringTag in e||Symbol.iterator in e)}!function(e){e[e.SEND_QUERY=0]="SEND_QUERY",e[e.PEER_RESPONSE=1]="PEER_RESPONSE",e[e.FINAL_PEER=2]="FINAL_PEER",e[e.QUERY_ERROR=3]="QUERY_ERROR",e[e.PROVIDER=4]="PROVIDER",e[e.VALUE=5]="VALUE",e[e.ADD_PEER=6]="ADD_PEER",e[e.DIAL_PEER=7]="DIAL_PEER"}(RL||(RL={}));var{hasOwnProperty:jL}=Object.prototype,{propertyIsEnumerable:FL}=Object,UL=(e,t,r)=>{Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})},zL={concatArrays:!1,ignoreUndefined:!1},VL=e=>{var t=[];for(var r in e)jL.call(e,r)&&t.push(r);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);for(var i of n)FL.call(e,i)&&t.push(i)}return t};function qL(e){return Array.isArray(e)?(r=(t=e).slice(0,0),VL(t).forEach((e=>{UL(r,e,qL(t[e]))})),r):ML(e)?function(e){var t=null===Object.getPrototypeOf(e)?Object.create(null):{};return VL(e).forEach((r=>{UL(t,r,qL(e[r]))})),t}(e):e;var t,r}var HL,KL,WL,QL,YL,JL,ZL,$L,XL=(e,t,r,n)=>(r.forEach((r=>{void 0===t[r]&&n.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?UL(e,r,tM(e[r],t[r],n)):UL(e,r,qL(t[r])))})),e),eM=(e,t,r)=>{var n=e.slice(0,0),i=0;return[e,t].forEach((t=>{for(var o=[],a=0;a<t.length;a++)jL.call(t,a)&&(o.push(String(a)),UL(n,i++,t===e?t[a]:qL(t[a])));n=XL(n,t,VL(t).filter((e=>!o.includes(e))),r)})),n};function tM(e,t,r){return r.concatArrays&&Array.isArray(e)&&Array.isArray(t)?eM(e,t,r):ML(t)&&ML(e)?XL(e,t,VL(t),r):qL(t)}function rM(){for(var e=tM(qL(zL),undefined!==this&&this||{},zL),t={_:{}},r=arguments.length,n=new Array(r),i=0;i<r;i++)n[i]=arguments[i];for(var o of n)if(void 0!==o){if(!ML(o))throw new TypeError("`"+o+"` is not an Option Object");t=tM(t,{_:o},e)}return t._}function nM(){if(KL)return HL;function e(e){return e>=55296&&e<=56319}function t(e){return e>=56320&&e<=57343}return KL=1,HL=function(r,n,i){if("string"!=typeof n)throw new Error("Input must be string");for(var o,a,s=n.length,l=0,c=0;c<s;c+=1){if(o=n.charCodeAt(c),a=n[c],e(o)&&t(n.charCodeAt(c+1))&&(a+=n[c+=1]),(l+=r(a))===i)return n.slice(0,c+1);if(l>i)return n.slice(0,c-a.length+1)}return n},HL}function iM(){if(JL)return YL;JL=1;var e=nM(),t=function(){if(QL)return WL;function e(e){return e>=55296&&e<=56319}function t(e){return e>=56320&&e<=57343}return QL=1,WL=function(r){if("string"!=typeof r)throw new Error("Input must be string");for(var n=r.length,i=0,o=null,a=null,s=0;s<n;s++)t(o=r.charCodeAt(s))?null!=a&&e(a)?i+=1:i+=3:o<=127?i+=1:o>=128&&o<=2047?i+=2:o>=2048&&o<=65535&&(i+=3),a=o;return i},WL}();return YL=e.bind(null,t)}var oM=function(){if($L)return ZL;$L=1;var e=iM(),t=/[\/\?<>\\:\*\|"]/g,r=/[\x00-\x1f\x80-\x9f]/g,n=/^\.+$/,i=/^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\..*)?$/i,o=/[\. ]+$/;function a(a,s){if("string"!=typeof a)throw new Error("Input must be string");var l=a.replace(t,s).replace(r,s).replace(n,s).replace(i,s).replace(o,s);return e(l,255)}return ZL=function(e,t){var r=t&&t.replacement||"",n=a(e,r);return""===r?n:a(n,"")},ZL}(),aM=e.getDefaultExportFromCjs(oM),sM={alg:"A128GCM",ext:!0,k:"scm9jmO_4BJAgdwWGVulLg",key_ops:["encrypt","decrypt"],kty:"oct"};function lM(t){var r="AES-GCM",n=16,i=12,o="SHA-256",a=16,s=32767,l=_l.get();function c(){return(c=e._asyncToGenerator((function*(e,t){var c,u=l.getRandomValues(new Uint8Array(a)),d=l.getRandomValues(new Uint8Array(i)),h={name:r,iv:d};if("string"==typeof t&&(t=ot(t)),0===t.length){c=yield l.subtle.importKey("jwk",sM,{name:"AES-GCM"},!0,["encrypt"]);try{var p={name:"PBKDF2",salt:u,iterations:s,hash:{name:o}},f=yield l.subtle.importKey("raw",t,{name:"PBKDF2"},!1,["deriveKey"]);c=yield l.subtle.deriveKey(p,f,{name:r,length:n},!0,["encrypt"])}catch(e){c=yield l.subtle.importKey("jwk",sM,{name:"AES-GCM"},!0,["encrypt"])}}else{var v={name:"PBKDF2",salt:u,iterations:s,hash:{name:o}},y=yield l.subtle.importKey("raw",t,{name:"PBKDF2"},!1,["deriveKey"]);c=yield l.subtle.deriveKey(v,y,{name:r,length:n},!0,["encrypt"])}var g=yield l.subtle.encrypt(h,c,e);return _t([u,h.iv,new Uint8Array(g)])}))).apply(this,arguments)}function u(){return(u=e._asyncToGenerator((function*(e,t){var c,u=e.subarray(0,a),d=e.subarray(a,a+i),h=e.subarray(a+i),p={name:r,iv:d};if("string"==typeof t&&(t=ot(t)),0===t.length)try{var f={name:"PBKDF2",salt:u,iterations:s,hash:{name:o}},v=yield l.subtle.importKey("raw",t,{name:"PBKDF2"},!1,["deriveKey"]);c=yield l.subtle.deriveKey(f,v,{name:r,length:n},!0,["decrypt"])}catch(e){c=yield l.subtle.importKey("jwk",sM,{name:"AES-GCM"},!0,["decrypt"])}else{var y={name:"PBKDF2",salt:u,iterations:s,hash:{name:o}},g=yield l.subtle.importKey("raw",t,{name:"PBKDF2"},!1,["deriveKey"]);c=yield l.subtle.deriveKey(y,g,{name:r,length:n},!0,["decrypt"])}var m=yield l.subtle.decrypt(p,c,h);return new Uint8Array(m)}))).apply(this,arguments)}n*=8;var d={encrypt:function(e,t){return c.apply(this,arguments)},decrypt:function(e,t){return u.apply(this,arguments)}};return d}var cM=1e4;function uM(e,t){return dM.apply(this,arguments)}function dM(){return(dM=e._asyncToGenerator((function*(e,t){var r=lM(),n=yield r.encrypt(e,t);return z.encode(n)}))).apply(this,arguments)}function hM(e,t,r){return pM.apply(this,arguments)}function pM(){return pM=e._asyncToGenerator((function*(e,t,r){if("RSA"===e.type)return function(e,t){return gM.apply(this,arguments)}(e,t,r);if("Ed25519"===e.type)return function(e,t){return fM.apply(this,arguments)}(e,t,r);if("secp256k1"===e.type)return function(e,t){return vM.apply(this,arguments)}(e,t,r);if("ECDSA"===e.type)return function(e,t){return yM.apply(this,arguments)}(e,t,r);throw new ka})),pM.apply(this,arguments)}function fM(){return fM=e._asyncToGenerator((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"libp2p-key";if("libp2p-key"===r)return uM(Wl(e),t);throw new ea("export format '".concat(r,"' is not supported"))})),fM.apply(this,arguments)}function vM(){return vM=e._asyncToGenerator((function*(e,t){if("libp2p-key"===(arguments.length>2&&void 0!==arguments[2]?arguments[2]:"libp2p-key"))return uM(Wl(e),t);throw new ea("Export format is not supported")})),vM.apply(this,arguments)}function yM(){return yM=e._asyncToGenerator((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"libp2p-key";if("libp2p-key"===r)return uM(Wl(e),t);throw new ea("export format '".concat(r,"' is not supported"))})),yM.apply(this,arguments)}function gM(){return gM=e._asyncToGenerator((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:"pkcs-8";if("pkcs-8"===r)return function(e,t){return mM.apply(this,arguments)}(e,t);if("libp2p-key"===r)return uM(Wl(e),t);throw new ea("Export format is not supported")})),gM.apply(this,arguments)}function mM(){return(mM=e._asyncToGenerator((function*(e,t){var r=_l.get(),n=new Xv({value:[new Hv({value:0}),new Xv({value:[new Yv({value:"1.2.840.113549.1.1.1"}),new Av]}),new Cv({valueHex:e.raw})]}).toBER(),i=new Uint8Array(n,0,n.byteLength),o=gl(16),a=yield xo(Eo,t,o,{c:cM,dkLen:32}),s=gl(16),l=yield r.subtle.importKey("raw",a,"AES-CBC",!1,["encrypt"]),c=yield r.subtle.encrypt({name:"AES-CBC",iv:s},l,i),u=new Xv({value:[new Cv({valueHex:o}),new Hv({value:cM}),new Hv({value:32}),new Xv({value:[new Yv({value:"1.2.840.113549.2.11"}),new Av]})]}),d=new Xv({value:[new Yv({value:"1.2.840.113549.1.5.13"}),new Xv({value:[new Xv({value:[new Yv({value:"1.2.840.113549.1.5.12"}),u]}),new Xv({value:[new Yv({value:"2.16.840.1.101.3.4.1.42"}),new Cv({valueHex:s})]})]})]}),h=new Xv({value:[d,new Cv({valueHex:c})]}).toBER();return["-----BEGIN ENCRYPTED PRIVATE KEY-----",...Ze(new Uint8Array(h,0,h.byteLength),"base64pad").split(/(.{64})/).filter(Boolean),"-----END ENCRYPTED PRIVATE KEY-----"].join("\n")}))).apply(this,arguments)}function wM(e,t){return bM.apply(this,arguments)}function bM(){return bM=e._asyncToGenerator((function*(e,t){try{var r=yield function(e,t){return _M.apply(this,arguments)}(e,t);return Hl(r)}catch(e){}if(!e.includes("BEGIN"))throw new ea("Encrypted key was not a libp2p-key or a PEM file");return function(e,t){return SM.apply(this,arguments)}(e,t)})),bM.apply(this,arguments)}function _M(){return(_M=e._asyncToGenerator((function*(e,t){var r=z.decode(e);return lM().decrypt(r,t)}))).apply(this,arguments)}function SM(){return(SM=e._asyncToGenerator((function*(e,t){var r,n=_l.get();if(e.includes("-----BEGIN ENCRYPTED PRIVATE KEY-----")){var i=ot(e.replace("-----BEGIN ENCRYPTED PRIVATE KEY-----","").replace("-----END ENCRYPTED PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:o}=wv(i),{iv:a,salt:s,iterations:l,keySize:c,cipherText:u}=function(e){var t=e.valueBlock.value[0];if("OBJECT IDENTIFIER : 1.2.840.113549.1.5.13"!==t.valueBlock.value[0].toString())throw new ea("Only pkcs5PBES2 encrypted private keys are supported");var r=t.valueBlock.value[1].valueBlock.value[0];if("OBJECT IDENTIFIER : 1.2.840.113549.1.5.12"!==r.valueBlock.value[0].toString())throw new ea("Only pkcs5PBKDF2 key derivation functions are supported");var n=r.valueBlock.value[1],i=EM(n.valueBlock.value[0].getValue()),o=cM,a=32;if(3===n.valueBlock.value.length)o=Number(n.valueBlock.value[1].toBigInt()),a=Number(n.valueBlock.value[2].toBigInt());else if(2===n.valueBlock.value.length)throw new ea("Could not derive key size and iterations from PEM file - please use @libp2p/rsa to re-import your key");var s=t.valueBlock.value[1].valueBlock.value[1],l=s.valueBlock.value[0].toString();if("OBJECT IDENTIFIER : 1.2.840.113549.3.7"===l);else if("OBJECT IDENTIFIER : 1.3.14.3.2.7"===l);else if("OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.2"===l);else if("OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.22"===l);else if("OBJECT IDENTIFIER : 2.16.840.1.101.3.4.1.42"!==l)throw new ea("Only AES-CBC encryption schemes are supported");var c=EM(s.valueBlock.value[1].getValue());return{cipherText:EM(e.valueBlock.value[1].getValue()),salt:i,iterations:o,keySize:a,iv:c}}(o),d=yield xo(Eo,t,s,{c:l,dkLen:c}),h=yield n.subtle.importKey("raw",d,"AES-CBC",!1,["decrypt"]),p=EM(yield n.subtle.decrypt({name:"AES-CBC",iv:a},h,u)),{result:f}=wv(p);r=PM(f)}else{if(!e.includes("-----BEGIN PRIVATE KEY-----"))throw new ea("Could not parse private key from PEM data");var v=ot(e.replace("-----BEGIN PRIVATE KEY-----","").replace("-----END PRIVATE KEY-----","").replace(/\n/g,"").trim(),"base64pad"),{result:y}=wv(v);r=PM(y)}var g=Kl(r);if("RSA"!==g.type)throw new ea("Could not parse RSA private key from PEM data");return g}))).apply(this,arguments)}function PM(e){return EM(e.valueBlock.value[2].getValue())}function EM(e){return new Uint8Array(e,0,e.byteLength)}var AM,kM="/info/",xM=new WeakMap,TM=14,IM=16,CM=1e3,BM={dek:{keyLength:64,iterationCount:1e4,salt:"you should override this value with a crypto secure random number",hash:"sha2-512"}};function NM(e){return null!=e&&("string"==typeof e&&(e===aM(e.trim())&&e.length>0))}function DM(){return GM.apply(this,arguments)}function GM(){return GM=e._asyncToGenerator((function*(){var e=800*Math.random()+200;yield new Promise((t=>setTimeout(t,e)))})),GM.apply(this,arguments)}function RM(e){return new Bc("/pkcs8/"+e)}function OM(e){return new Bc(kM+e)}function LM(){return(LM=e._asyncToGenerator((function*(e){var t=Wl(e),r=yield De.digest(t);return j.encode(r.bytes).substring(1)}))).apply(this,arguments)}class MM{constructor(t,r){var n,i,o,a,s,l,c,u,d,h;if(e._defineProperty(this,"components",void 0),e._defineProperty(this,"init",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"self",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/keychain"),e._defineProperty(this,Ra,["@libp2p/keychain"]),this.components=t,this.log=t.logger.forComponent("libp2p:keychain"),this.init=rM(BM,r),this.self=null!==(n=r.selfKey)&&void 0!==n?n:"self",null!=this.init.pass&&(null===(i=this.init.pass)||void 0===i?void 0:i.length)<20)throw new Error("pass must be least 20 characters");if(null!=(null===(o=this.init.dek)||void 0===o?void 0:o.keyLength)&&this.init.dek.keyLength<TM)throw new Error("dek.keyLength must be least ".concat(TM," bytes"));if(null!=(null===(a=this.init.dek)||void 0===a||null===(a=a.salt)||void 0===a?void 0:a.length)&&this.init.dek.salt.length<IM)throw new Error("dek.saltLength must be least ".concat(IM," bytes"));if(null!=(null===(s=this.init.dek)||void 0===s?void 0:s.iterationCount)&&this.init.dek.iterationCount<CM)throw new Error("dek.iterationCount must be least ".concat(CM));var p=null!=this.init.pass&&null!=(null===(l=this.init.dek)||void 0===l?void 0:l.salt)?xc(this.init.pass,null===(c=this.init.dek)||void 0===c?void 0:c.salt,null===(u=this.init.dek)||void 0===u?void 0:u.iterationCount,null===(d=this.init.dek)||void 0===d?void 0:d.keyLength,null===(h=this.init.dek)||void 0===h?void 0:h.hash):"";xM.set(this,{dek:p})}static generateOptions(){var e=Object.assign({},BM),t=3*Math.ceil(IM/3);return e.dek.salt=Ze(gl(t),"base64"),e}static get options(){return BM}findKeyByName(t){var r=this;return e._asyncToGenerator((function*(){if(!NM(t))throw yield DM(),new ea("Invalid key name '".concat(t,"'"));var e=OM(t);try{var n=yield r.components.datastore.get(e);return JSON.parse(Ze(n))}catch(e){throw yield DM(),r.log.error(e),new ua("Key '".concat(t,"' does not exist."))}}))()}findKeyById(t){var r=this;return e._asyncToGenerator((function*(){try{var n,i={prefix:kM},o=!1,a=!1;try{for(var s,l=e._asyncIterator(r.components.datastore.query(i));o=!(s=yield l.next()).done;o=!1){var c=s.value,u=JSON.parse(Ze(c.value));if(u.id===t)return u}}catch(e){a=!0,n=e}finally{try{o&&null!=l.return&&(yield l.return())}finally{if(a)throw n}}throw new ea("Key with id '".concat(t,"' does not exist."))}catch(e){throw yield DM(),e}}))()}importKey(t,r){var n=this;return e._asyncToGenerator((function*(){if(!NM(t))throw yield DM(),new ea("Invalid key name '".concat(t,"'"));if(null==r)throw yield DM(),new ea("Key is required");var e,i,o=RM(t);if(yield n.components.datastore.has(o))throw yield DM(),new ea("Key '".concat(t,"' already exists"));try{e=yield function(e){return LM.apply(this,arguments)}(r);var a=xM.get(n);if(null==a)throw new ea("dek missing");var s=a.dek;i=yield hM(r,s,"RSA"===r.type?"pkcs-8":"libp2p-key")}catch(e){throw yield DM(),e}var l={name:t,id:e},c=n.components.datastore.batch();return c.put(o,ot(i)),c.put(OM(t),ot(JSON.stringify(l))),yield c.commit(),l}))()}exportKey(t){var r=this;return e._asyncToGenerator((function*(){if(!NM(t))throw yield DM(),new ea("Invalid key name '".concat(t,"'"));var e=RM(t);try{var n=Ze(yield r.components.datastore.get(e)),i=xM.get(r);if(null==i)throw new ea("dek missing");var o=i.dek;return yield wM(n,o)}catch(e){throw yield DM(),e}}))()}removeKey(t){var r=this;return e._asyncToGenerator((function*(){if(!NM(t)||t===r.self)throw yield DM(),new ea("Invalid key name '".concat(t,"'"));var e=RM(t),n=yield r.findKeyByName(t),i=r.components.datastore.batch();return i.delete(e),i.delete(OM(t)),yield i.commit(),n}))()}listKeys(){var t=this;return e._asyncToGenerator((function*(){var r,n={prefix:kM},i=[],o=!1,a=!1;try{for(var s,l=e._asyncIterator(t.components.datastore.query(n));o=!(s=yield l.next()).done;o=!1){var c=s.value;i.push(JSON.parse(Ze(c.value)))}}catch(e){a=!0,r=e}finally{try{o&&null!=l.return&&(yield l.return())}finally{if(a)throw r}}return i}))()}renameKey(t,r){var n=this;return e._asyncToGenerator((function*(){if(!NM(t)||t===n.self)throw yield DM(),new ea("Invalid old key name '".concat(t,"'"));if(!NM(r)||r===n.self)throw yield DM(),new ea("Invalid new key name '".concat(r,"'"));var e=RM(t),i=RM(r),o=OM(t),a=OM(r);if(yield n.components.datastore.has(i))throw yield DM(),new ea("Key '".concat(r,"' already exists"));try{var s=yield n.components.datastore.get(e),l=yield n.components.datastore.get(o),c=JSON.parse(Ze(l));c.name=r;var u=n.components.datastore.batch();return u.put(i,s),u.put(a,ot(JSON.stringify(c))),u.delete(e),u.delete(o),yield u.commit(),c}catch(e){throw yield DM(),e}}))()}rotateKeychainPass(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i,o,a;if("string"!=typeof t)throw yield DM(),new ea("Invalid old pass type '".concat(typeof t,"'"));if("string"!=typeof r)throw yield DM(),new ea("Invalid new pass type '".concat(typeof r,"'"));if(r.length<20)throw yield DM(),new ea("Invalid pass length ".concat(r.length));n.log("recreating keychain");var s=xM.get(n);if(null==s)throw new ea("dek missing");var l=s.dek;n.init.pass=r;var c=null!=r&&null!=(null===(e=n.init.dek)||void 0===e?void 0:e.salt)?xc(r,n.init.dek.salt,null===(i=n.init.dek)||void 0===i?void 0:i.iterationCount,null===(o=n.init.dek)||void 0===o?void 0:o.keyLength,null===(a=n.init.dek)||void 0===a?void 0:a.hash):"";xM.set(n,{dek:c});var u=yield n.listKeys();for(var d of u){var h=Ze(yield n.components.datastore.get(RM(d.name))),p=yield wM(h,l),f=c.toString(),v=yield hM(p,f,"RSA"===p.type?"pkcs-8":"libp2p-key"),y=n.components.datastore.batch(),g={name:d.name,id:d.id};y.put(RM(d.name),ot(v)),y.put(OM(d.name),ot(JSON.stringify(g))),yield y.commit()}n.log("keychain reconstructed")}))()}}function jM(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new MM(t,e)}class FM{constructor(){var t,r,n,i,o,a,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};e._defineProperty(this,"memoryStorage",void 0),e._defineProperty(this,"points",void 0),e._defineProperty(this,"duration",void 0),e._defineProperty(this,"blockDuration",void 0),e._defineProperty(this,"execEvenly",void 0),e._defineProperty(this,"execEvenlyMinDelayMs",void 0),e._defineProperty(this,"keyPrefix",void 0),this.points=null!==(t=s.points)&&void 0!==t?t:4,this.duration=null!==(r=s.duration)&&void 0!==r?r:1,this.blockDuration=null!==(n=s.blockDuration)&&void 0!==n?n:0,this.execEvenly=null!==(i=s.execEvenly)&&void 0!==i&&i,this.execEvenlyMinDelayMs=null!==(o=s.execEvenlyMinDelayMs)&&void 0!==o?o:1e3*this.duration/this.points,this.keyPrefix=null!==(a=s.keyPrefix)&&void 0!==a?a:"rlflx",this.memoryStorage=new UM}consume(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:1,i=r.length>2&&void 0!==r[2]?r[2]:{},o=n.getKey(t),a=n._getKeySecDuration(i),s=n.memoryStorage.incrby(o,e,a);if(s.remainingPoints=Math.max(n.points-s.consumedPoints,0),s.consumedPoints>n.points)throw n.blockDuration>0&&s.consumedPoints<=n.points+e&&(s=n.memoryStorage.set(o,s.consumedPoints,n.blockDuration)),new Gh("Rate limit exceeded",s);if(n.execEvenly&&s.msBeforeNext>0&&!s.isFirstInDuration){var l=Math.ceil(s.msBeforeNext/(s.remainingPoints+2));l<n.execEvenlyMinDelayMs&&(l=s.consumedPoints*n.execEvenlyMinDelayMs),yield BR(l)}return s}))()}penalty(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=this.getKey(e),i=this._getKeySecDuration(r),o=this.memoryStorage.incrby(n,t,i);return o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o}reward(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=this.getKey(e),i=this._getKeySecDuration(r),o=this.memoryStorage.incrby(n,-t,i);return o.remainingPoints=Math.max(this.points-o.consumedPoints,0),o}block(e,t){var r=1e3*t,n=this.points+1;return this.memoryStorage.set(this.getKey(e),n,t),{remainingPoints:0,msBeforeNext:0===r?-1:r,consumedPoints:n,isFirstInDuration:!1}}set(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0,n=1e3*(r>=0?r:this.duration);return this.memoryStorage.set(this.getKey(e),t,r),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:t,isFirstInDuration:!1}}get(e){var t=this.memoryStorage.get(this.getKey(e));return null!=t&&(t.remainingPoints=Math.max(this.points-t.consumedPoints,0)),t}delete(e){this.memoryStorage.delete(this.getKey(e))}_getKeySecDuration(e){return null!=(null==e?void 0:e.customDuration)&&e.customDuration>=0?e.customDuration:this.duration}getKey(e){return this.keyPrefix.length>0?"".concat(this.keyPrefix,":").concat(e):e}parseKey(e){return e.substring(this.keyPrefix.length)}}class UM{constructor(){e._defineProperty(this,"storage",void 0),this.storage=new Map}incrby(e,t,r){var n=this.storage.get(e);if(null!=n){var i=null!=n.expiresAt?n.expiresAt.getTime()-(new Date).getTime():-1;return null==n.expiresAt||i>0?(n.value+=t,{remainingPoints:0,msBeforeNext:i,consumedPoints:n.value,isFirstInDuration:!1}):this.set(e,t,r)}return this.set(e,t,r)}set(e,t,r){var n=1e3*r,i=this.storage.get(e);null!=i&&clearTimeout(i.timeoutId);var o={value:t,expiresAt:n>0?new Date(Date.now()+n):void 0};return this.storage.set(e,o),n>0&&(o.timeoutId=setTimeout((()=>{this.storage.delete(e)}),n),null!=o.timeoutId.unref&&o.timeoutId.unref()),{remainingPoints:0,msBeforeNext:0===n?-1:n,consumedPoints:o.value,isFirstInDuration:!0}}get(e){var t=this.storage.get(e);if(null!=t)return{remainingPoints:0,msBeforeNext:null!=t.expiresAt?t.expiresAt.getTime()-(new Date).getTime():-1,consumedPoints:t.value,isFirstInDuration:!1}}delete(e){var t=this.storage.get(e);return null!=t&&(null!=t.timeoutId&&clearTimeout(t.timeoutId),this.storage.delete(e),!0)}}!function(e){e[e.NEW_STREAM=0]="NEW_STREAM",e[e.MESSAGE_RECEIVER=1]="MESSAGE_RECEIVER",e[e.MESSAGE_INITIATOR=2]="MESSAGE_INITIATOR",e[e.CLOSE_RECEIVER=3]="CLOSE_RECEIVER",e[e.CLOSE_INITIATOR=4]="CLOSE_INITIATOR",e[e.RESET_RECEIVER=5]="RESET_RECEIVER",e[e.RESET_INITIATOR=6]="RESET_INITIATOR"}(AM||(AM={}));var zM=Object.freeze({0:"NEW_STREAM",1:"MESSAGE_RECEIVER",2:"MESSAGE_INITIATOR",3:"CLOSE_RECEIVER",4:"CLOSE_INITIATOR",5:"RESET_RECEIVER",6:"RESET_INITIATOR"}),VM=Object.freeze({NEW_STREAM:AM.NEW_STREAM,MESSAGE:AM.MESSAGE_INITIATOR,CLOSE:AM.CLOSE_INITIATOR,RESET:AM.RESET_INITIATOR}),qM=Object.freeze({MESSAGE:AM.MESSAGE_RECEIVER,CLOSE:AM.CLOSE_RECEIVER,RESET:AM.RESET_RECEIVER}),HM=1<<20;class KM{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:HM,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:4194304;e._defineProperty(this,"_buffer",void 0),e._defineProperty(this,"_headerInfo",void 0),e._defineProperty(this,"_maxMessageSize",void 0),e._defineProperty(this,"_maxUnprocessedMessageQueueSize",void 0),this._buffer=new Fa,this._headerInfo=null,this._maxMessageSize=t,this._maxUnprocessedMessageQueueSize=r}write(e){if(null==e||0===e.length)return[];if(this._buffer.append(e),this._buffer.byteLength>this._maxUnprocessedMessageQueueSize)throw new ya("Unprocessed message queue size too large!");for(var t=[];0!==this._buffer.length;){if(null==this._headerInfo)try{this._headerInfo=this._decodeHeader(this._buffer)}catch(e){if("InvalidMessageError"===e.name)throw e;break}var{id:r,type:n,length:i,offset:o}=this._headerInfo;if(this._buffer.length-o<i)break;var a={id:r,type:n};n!==AM.NEW_STREAM&&n!==AM.MESSAGE_INITIATOR&&n!==AM.MESSAGE_RECEIVER||(a.data=this._buffer.sublist(o,o+i)),t.push(a),this._buffer.consume(o+i),this._headerInfo=null}return t}_decodeHeader(e){var{value:t,offset:r}=YM(e),{value:n,offset:i}=YM(e,r),o=7&t;if(null==zM[o])throw new Error("Invalid type received: ".concat(o));if(n>this._maxMessageSize)throw new ya("Message size too large");return{id:t>>3,type:o,offset:r+i,length:n}}}var WM=128,QM=127;function YM(e){var t,r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,n=0,i=0,o=r,a=e.length;do{if(o>=a||i>49)throw r=0,new RangeError("Could not decode varint");t=e.get(o++),n+=i<28?(t&QM)<<i:(t&QM)*Math.pow(2,i),i+=7}while(t>=WM);return{value:n,offset:r=o-r}}var JM=10240;var ZM=new class{constructor(){e._defineProperty(this,"_pool",void 0),e._defineProperty(this,"_poolOffset",void 0),this._pool=Ke(JM),this._poolOffset=0}write(e,t){var r=this._pool,n=this._poolOffset;wt(e.id<<3|e.type,r,n),n+=yt(e.id<<3|e.type),e.type!==AM.NEW_STREAM&&e.type!==AM.MESSAGE_INITIATOR&&e.type!==AM.MESSAGE_RECEIVER||null==e.data?(wt(0,r,n),n+=yt(0)):(wt(e.data.length,r,n),n+=yt(e.data.length));var i=r.subarray(this._poolOffset,n);JM-n<100?(this._pool=Ke(JM),this._poolOffset=0):this._poolOffset=n,t.append(i),e.type!==AM.NEW_STREAM&&e.type!==AM.MESSAGE_INITIATOR&&e.type!==AM.MESSAGE_RECEIVER||null==e.data||t.append(e.data)}};function $M(){return $M=e._wrapAsyncGenerator((function*(t){var r,n=!1,i=!1;try{for(var o,a=e._asyncIterator(t);n=!(o=yield e._awaitAsyncGenerator(a.next())).done;n=!1){var s=o.value,l=new Fa;ZM.write(s,l),yield l}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield e._awaitAsyncGenerator(a.return()))}finally{if(i)throw r}}})),$M.apply(this,arguments)}class XM extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Stream input buffer error"),this.name="StreamInputBufferError"}}class ej extends Dp{constructor(t){super(t),e._defineProperty(this,"name",void 0),e._defineProperty(this,"streamId",void 0),e._defineProperty(this,"send",void 0),e._defineProperty(this,"types",void 0),e._defineProperty(this,"maxDataSize",void 0),this.types="outbound"===t.direction?VM:qM,this.send=t.send,this.name=t.name,this.streamId=t.streamId,this.maxDataSize=t.maxDataSize}sendNewStream(){var t=this;return e._asyncToGenerator((function*(){yield t.send({id:t.streamId,type:VM.NEW_STREAM,data:new Fa(ot(t.name))})}))()}sendData(t){var r=this;return e._asyncToGenerator((function*(){for(t=t.sublist();t.byteLength>0;){var e=Math.min(t.byteLength,r.maxDataSize);yield r.send({id:r.streamId,type:r.types.MESSAGE,data:t.sublist(0,e)}),t.consume(e)}}))()}sendReset(){var t=this;return e._asyncToGenerator((function*(){yield t.send({id:t.streamId,type:t.types.RESET})}))()}sendCloseWrite(){var t=this;return e._asyncToGenerator((function*(){yield t.send({id:t.streamId,type:t.types.CLOSE})}))()}sendCloseRead(){return e._asyncToGenerator((function*(){}))()}}function tj(t){var r=e._objectSpread2(e._objectSpread2({},t),{},{type:"".concat(zM[t.type]," (").concat(t.type,")")});return t.type===AM.NEW_STREAM&&(r.data=Ze(t.data instanceof Uint8Array?t.data:t.data.subarray())),t.type!==AM.MESSAGE_INITIATOR&&t.type!==AM.MESSAGE_RECEIVER||(r.data=Ze(t.data instanceof Uint8Array?t.data:t.data.subarray(),"base16")),r}class rj{constructor(t,r){var n,i;e._defineProperty(this,"protocol","/mplex/6.7.0"),e._defineProperty(this,"sink",void 0),e._defineProperty(this,"source",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"_streamId",void 0),e._defineProperty(this,"_streams",void 0),e._defineProperty(this,"_init",void 0),e._defineProperty(this,"_source",void 0),e._defineProperty(this,"closeController",void 0),e._defineProperty(this,"rateLimiter",void 0),e._defineProperty(this,"closeTimeout",void 0),e._defineProperty(this,"logger",void 0),r=null!=r?r:{},this.log=t.logger.forComponent("libp2p:mplex"),this.logger=t.logger,this._streamId=0,this._streams={initiators:new Map,receivers:new Map},this._init=r,this.closeTimeout=null!==(n=r.closeTimeout)&&void 0!==n?n:500,this.sink=this._createSink(),this._source=Xc({objectMode:!0,onEnd:()=>{for(var e of this._streams.initiators.values())e.destroy();for(var t of this._streams.receivers.values())t.destroy()}}),this.source=lu(this._source,(e=>function(e){return $M.apply(this,arguments)}(e))),this.closeController=new AbortController,this.rateLimiter=new FM({points:null!==(i=r.disconnectThreshold)&&void 0!==i?i:5,duration:1})}get streams(){var e=[];for(var t of this._streams.initiators.values())e.push(t);for(var r of this._streams.receivers.values())e.push(r);return e}newStream(e){if(this.closeController.signal.aborted)throw new sa("Muxer already closed");var t=this._streamId++;e=null==e?t.toString():e.toString();var r=this._streams.initiators;return this._newStream({id:t,name:e,type:"initiator",registry:r})}close(t){var r=this;return e._asyncToGenerator((function*(){var n;if(!r.closeController.signal.aborted){var i=null!==(n=null==t?void 0:t.signal)&&void 0!==n?n:AbortSignal.timeout(r.closeTimeout);try{yield Promise.all(r.streams.map(function(){var t=e._asyncToGenerator((function*(e){return e.close({signal:i})}));return function(e){return t.apply(this,arguments)}}())),r._source.end(),yield r._source.onEmpty({signal:i}),r.closeController.abort()}catch(e){r.abort(e)}}}))()}abort(e){this.closeController.signal.aborted||(this.streams.forEach((t=>{t.abort(e)})),this.closeController.abort(e))}_newReceiverStream(e){var{id:t,name:r}=e,n=this._streams.receivers;return this._newStream({id:t,name:r,type:"receiver",registry:n})}_newStream(t){var r,n=this,{id:i,name:o,type:a,registry:s}=t;if(this.log("new %s stream %s",a,i),"initiator"===a&&this._streams.initiators.size===(null!==(r=this._init.maxOutboundStreams)&&void 0!==r?r:1024))throw new Aa("Too many outbound streams open");if(s.has(i))throw new Error("".concat(a," stream ").concat(i," already exists!"));var l=function(){var t=e._asyncToGenerator((function*(e){n.log.enabled&&n.log.trace("%s stream %s send",a,i,tj(e)),n._source.push(e)}));return function(e){return t.apply(this,arguments)}}(),c=function(e){var{id:t,name:r,send:n,onEnd:i,type:o="initiator",maxMsgSize:a=HM}=e;return new ej({id:"initiator"===o?"i".concat(t):"r".concat(t),streamId:t,name:"".concat(null!=r?r:t),direction:"initiator"===o?"outbound":"inbound",maxDataSize:a,onEnd:i,send:n,log:e.logger.forComponent("libp2p:mplex:stream:".concat(o,":").concat(t))})}({id:i,name:o,send:l,type:a,onEnd:()=>{this.log("%s stream with id %s and protocol %s ended",a,i,c.protocol),s.delete(i),null!=this._init.onStreamEnd&&this._init.onStreamEnd(c)},maxMsgSize:this._init.maxMsgSize,logger:this.logger});return s.set(i,c),c}_createSink(){var t=this,r=function(){var r=e._asyncToGenerator((function*(r){var n=()=>{Bp(r,t.log)};t.closeController.signal.addEventListener("abort",n);try{var i,o=new KM(t._init.maxMsgSize,t._init.maxUnprocessedMessageQueueSize),a=!1,s=!1;try{for(var l,c=e._asyncIterator(r);a=!(l=yield c.next()).done;a=!1){var u=l.value;for(var d of o.write(u))yield t._handleIncoming(d)}}catch(e){s=!0,i=e}finally{try{a&&null!=c.return&&(yield c.return())}finally{if(s)throw i}}t._source.end()}catch(e){t.log("error in sink",e),t._source.end(e)}finally{t.closeController.signal.removeEventListener("abort",n)}}));return function(e){return r.apply(this,arguments)}}();return r}_handleIncoming(t){var r=this;return e._asyncToGenerator((function*(){var e,{id:n,type:i}=t;if(r.log.enabled&&r.log.trace("incoming message",tj(t)),t.type!==AM.NEW_STREAM){var o=(1&~i?r._streams.receivers:r._streams.initiators).get(n);if(null!=o){var a=null!==(e=r._init.maxStreamBufferSize)&&void 0!==e?e:4194304;try{switch(i){case AM.MESSAGE_INITIATOR:case AM.MESSAGE_RECEIVER:if(o.sourceReadableLength()>a)throw r._source.push({id:t.id,type:i===AM.MESSAGE_INITIATOR?AM.RESET_RECEIVER:AM.RESET_INITIATOR}),new XM("Input buffer full - increase Mplex maxBufferSize to accommodate slow consumers");o.sourcePush(t.data);break;case AM.CLOSE_INITIATOR:case AM.CLOSE_RECEIVER:o.remoteCloseWrite();break;case AM.RESET_INITIATOR:case AM.RESET_RECEIVER:o.reset();break;default:r.log("unknown message type %s",i)}}catch(e){r.log.error("error while processing message",e),o.abort(e)}}else{r.log("missing stream %s for message type %s",n,zM[i]);try{yield r.rateLimiter.consume("missing-stream",1)}catch(e){return r.log("rate limit hit when receiving messages for streams that do not exist - closing remote connection"),void r.abort(new Error("Too many messages for missing streams"))}}}else{var s;if(r._streams.receivers.size===(null!==(s=r._init.maxInboundStreams)&&void 0!==s?s:1024)){r.log("too many inbound streams open"),r._source.push({id:n,type:AM.RESET_RECEIVER});try{yield r.rateLimiter.consume("new-stream",1)}catch(e){return r.log("rate limit hit when opening too many new streams over the inbound stream limit - closing remote connection"),void r.abort(new Error("Too many open streams"))}return}var l=r._newReceiverStream({id:n,name:Ze(t.data instanceof Uint8Array?t.data:t.data.subarray())});null!=r._init.onIncomingStream&&r._init.onIncomingStream(l)}}))()}}class nj{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"protocol","/mplex/6.7.0"),e._defineProperty(this,"_init",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/mplex"),e._defineProperty(this,Ra,["@libp2p/stream-multiplexing"]),this.components=t,this._init=r}createStreamMuxer(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return new rj(this.components,e._objectSpread2(e._objectSpread2({},t),this._init))}}function ij(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new nj(t,e)}class oj{constructor(t){var r,n,i,o,a,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"protocol",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"started",void 0),e._defineProperty(this,"timeout",void 0),e._defineProperty(this,"maxInboundStreams",void 0),e._defineProperty(this,"maxOutboundStreams",void 0),e._defineProperty(this,"runOnLimitedConnection",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/ping"),e._defineProperty(this,Ra,["@libp2p/ping"]),this.components=t,this.log=t.logger.forComponent("libp2p:ping"),this.started=!1,this.protocol="/".concat(null!==(r=s.protocolPrefix)&&void 0!==r?r:"ipfs","/").concat("ping","/").concat("1.0.0"),this.timeout=null!==(n=s.timeout)&&void 0!==n?n:1e4,this.maxInboundStreams=null!==(i=s.maxInboundStreams)&&void 0!==i?i:2,this.maxOutboundStreams=null!==(o=s.maxOutboundStreams)&&void 0!==o?o:1,this.runOnLimitedConnection=null===(a=s.runOnLimitedConnection)||void 0===a||a,this.handleMessage=this.handleMessage.bind(this)}start(){var t=this;return e._asyncToGenerator((function*(){yield t.components.registrar.handle(t.protocol,t.handleMessage,{maxInboundStreams:t.maxInboundStreams,maxOutboundStreams:t.maxOutboundStreams,runOnLimitedConnection:t.runOnLimitedConnection}),t.started=!0}))()}stop(){var t=this;return e._asyncToGenerator((function*(){yield t.components.registrar.unhandle(t.protocol),t.started=!1}))()}isStarted(){return this.started}handleMessage(t){var r=this;this.log("incoming ping from %p",t.connection.remotePeer);var{stream:n}=t,i=Date.now(),o=zu(n),a=!1;Promise.resolve().then(e._asyncToGenerator((function*(){for(;;){var e=AbortSignal.timeout(r.timeout);e.addEventListener("abort",(()=>{null==n||n.abort(new ma("ping timeout"))}));var t=yield o.read({bytes:32,signal:e});yield o.write(t,{signal:e}),a=!0}}))).catch((e=>{a&&"UnexpectedEOFError"===e.name&&"ready"!==n.readStatus||(this.log.error("incoming ping from %p failed with error - %e",t.connection.remotePeer,e),null==n||n.abort(e))})).finally((()=>{var e=Date.now()-i;this.log("incoming ping from %p complete in %dms",t.connection.remotePeer,e);var r=AbortSignal.timeout(this.timeout);n.close({signal:r}).catch((e=>{this.log.error("error closing ping stream from %p - %e",t.connection.remotePeer,e),null==n||n.abort(e)}))}))}ping(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i=r.length>1&&void 0!==r[1]?r[1]:{};n.log("pinging %p",t);var o,a=Date.now(),s=gl(32),l=yield n.components.connectionManager.openConnection(t,i);if(null==i.signal){var c=AbortSignal.timeout(n.timeout);i=e._objectSpread2(e._objectSpread2({},i),{},{signal:c})}try{var u=zu(o=yield l.newStream(n.protocol,e._objectSpread2(e._objectSpread2({},i),{},{runOnLimitedConnection:n.runOnLimitedConnection}))),[,d]=yield Promise.all([u.write(s,i),u.read(e._objectSpread2(e._objectSpread2({},i),{},{bytes:32}))]),h=Date.now()-a;if(!nt(s,d.subarray()))throw new ga("Received wrong ping ack after ".concat(h,"ms"));return n.log("ping %p complete in %dms",l.remotePeer,h),h}catch(e){var p;throw n.log.error("error while pinging %p",l.remotePeer,e),null===(p=o)||void 0===p||p.abort(e),e}finally{null!=o&&(yield o.close(i))}}))()}}function aj(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new oj(t,e)}var sj,lj,cj=function(){var t=e._asyncToGenerator((function*(e){if(e.readyState>=2)throw new Error("socket closed");1!==e.readyState&&(yield new Promise(((t,r)=>{function n(){e.removeEventListener("open",i),e.removeEventListener("error",o)}function i(){n(),t()}function o(t){var i;n(),r(null!==(i=t.error)&&void 0!==i?i:new Error("connect ECONNREFUSED ".concat(e.url)))}e.addEventListener("open",i),e.addEventListener("error",o)})))}));return function(e){return t.apply(this,arguments)}}(),uj=(t,r)=>{(r=null!=r?r:{}).closeOnEnd=!1!==r.closeOnEnd;var n=function(){var n=e._asyncToGenerator((function*(n){var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(n);o=!(s=yield l.next()).done;o=!1){var c=s.value;try{yield cj(t)}catch(e){if("socket closed"===e.message)break;throw e}if(t.readyState===t.CLOSING||t.readyState===t.CLOSED)break;t.send(c)}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield l.return())}finally{if(a)throw i}}null!=r.closeOnEnd&&t.readyState<=1&&(yield new Promise(((e,r)=>{t.addEventListener("close",(t=>{if(t.wasClean||1006===t.code)e();else{var n=Object.assign(new Error("ws error"),{event:t});r(n)}})),setTimeout((()=>{t.close()}))})))}));return function(e){return n.apply(this,arguments)}}();return n},dj={},hj={};var pj=function(){if(lj)return dj;lj=1,Object.defineProperty(dj,"__esModule",{value:!0});var e=function(){if(sj)return hj;sj=1,Object.defineProperty(hj,"__esModule",{value:!0});class e{constructor(){this.pullQueue=[],this.pushQueue=[],this.eventHandlers={},this.isPaused=!1,this.isStopped=!1}push(e){if(!this.isStopped){var t={value:e,done:!1};if(this.pullQueue.length){var r=this.pullQueue.shift();r&&r.resolve(t)}else this.pushQueue.push(Promise.resolve(t)),void 0!==this.highWaterMark&&this.pushQueue.length>=this.highWaterMark&&!this.isPaused&&(this.isPaused=!0,this.eventHandlers.highWater?this.eventHandlers.highWater():console)}}stop(){if(!this.isStopped){for(var e of(this.isStopped=!0,this.remove(),this.pullQueue))e.resolve({value:void 0,done:!0});this.pullQueue.length=0}}fail(e){if(!this.isStopped)if(this.isStopped=!0,this.remove(),this.pullQueue.length){for(var t of this.pullQueue)t.reject(e);this.pullQueue.length=0}else{var r=Promise.reject(e);r.catch((()=>{})),this.pushQueue.push(r)}}remove(){Promise.resolve().then((()=>{this.removeCallback&&this.removeCallback()}))}[Symbol.asyncIterator](){return{next:e=>{var t=this.pushQueue.shift();return t?(void 0!==this.lowWaterMark&&this.pushQueue.length<=this.lowWaterMark&&this.isPaused&&(this.isPaused=!1,this.eventHandlers.lowWater&&this.eventHandlers.lowWater()),t):this.isStopped?Promise.resolve({value:void 0,done:!0}):new Promise(((e,t)=>{this.pullQueue.push({resolve:e,reject:t})}))},return:()=>(this.isStopped=!0,this.pushQueue.length=0,this.remove(),Promise.resolve({value:void 0,done:!0}))}}}class t{constructor(t){var{highWaterMark:r=100,lowWaterMark:n=1}=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},i=new e;i.highWaterMark=r,i.lowWaterMark=n,i.removeCallback=t({push:e=>i.push(e),stop:()=>i.stop(),fail:e=>i.fail(e),on:(e,t)=>{i.eventHandlers[e]=t}})||(()=>{}),this[Symbol.asyncIterator]=()=>i[Symbol.asyncIterator](),Object.freeze(this)}}return hj.EventIterator=t,hj.default=t,hj}();return dj.EventIterator=e.EventIterator,dj.subscribe=function(t,r,n){return new e.EventIterator((e=>{var{push:n}=e;return this.addEventListener(t,n,r),()=>this.removeEventListener(t,n,r)}),n)},dj.default=e.EventIterator,dj}();function fj(e){var t;return e instanceof ArrayBuffer||"ArrayBuffer"===(null==e||null===(t=e.constructor)||void 0===t?void 0:t.name)&&"number"==typeof(null==e?void 0:e.byteLength)}var vj=t=>{t.binaryType="arraybuffer";var r,n=function(){var n=e._asyncToGenerator((function*(){yield new Promise(((e,n)=>{if(o)e();else if(null==r){var i=e=>{t.removeEventListener("open",a),t.removeEventListener("error",s),e()},a=()=>{i(e)},s=e=>{i((()=>{var r;n(null!==(r=e.error)&&void 0!==r?r:new Error("connect ECONNREFUSED ".concat(t.url)))}))};t.addEventListener("open",a),t.addEventListener("error",s)}else n(r)}))}));return function(){return n.apply(this,arguments)}}(),i=e._wrapAsyncGenerator((function*(){var r=new pj.EventIterator((e=>{var{push:r,stop:n,fail:i}=e,o=e=>{var t=null;"string"==typeof e.data&&(t=ot(e.data)),fj(e.data)&&(t=new Uint8Array(e.data)),e.data instanceof Uint8Array&&(t=e.data),null!=t&&r(t)},a=e=>{var t;i(null!==(t=e.error)&&void 0!==t?t:new Error("Socket error"))};return t.addEventListener("message",o),t.addEventListener("error",a),t.addEventListener("close",n),()=>{t.removeEventListener("message",o),t.removeEventListener("error",a),t.removeEventListener("close",n)}}),{highWaterMark:1/0});yield e._awaitAsyncGenerator(n());var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(r);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;yield fj(c)?new Uint8Array(c):c}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}}))(),o=1===t.readyState;return t.addEventListener("open",(()=>{o=!0,r=null})),t.addEventListener("close",(()=>{o=!1,r=null})),t.addEventListener("error",(e=>{var n;o||(r=null!==(n=e.error)&&void 0!==n?n:new Error("connect ECONNREFUSED ".concat(t.url)))})),Object.assign(i,{connected:n})},yj=(t,r)=>{r=null!=r?r:{};var n=vj(t),i=r.remoteAddress,o=r.remotePort;if(null!=t.url)try{var a=new URL(t.url);i=a.hostname,o=parseInt(a.port,10)}catch(e){}if(null==i||null==o)throw new Error("Remote connection did not have address and/or port");var s,l,c={sink:uj(t,r),source:n,connected:(l=e._asyncToGenerator((function*(){yield n.connected()})),function(){return l.apply(this,arguments)}),close:(s=e._asyncToGenerator((function*(){t.readyState!==t.CONNECTING&&t.readyState!==t.OPEN||(yield new Promise((e=>{t.addEventListener("close",(()=>{e()})),t.close()})))})),function(){return s.apply(this,arguments)}),destroy:()=>{null!=t.terminate?t.terminate():t.close()},remoteAddress:i,remotePort:o,socket:t};return c},gj=WebSocket,mj={"http:":"ws:","https:":"wss:"};function wj(e,t){t=null!=t?t:{};var r=((e,t)=>{var r;if(e.startsWith("//")&&(e="".concat(null!==(r=null==t?void 0:t.protocol)&&void 0!==r?r:"ws:").concat(e)),e.startsWith("/")&&null!=t){var n,i=null!==(n=t.protocol)&&void 0!==n?n:"ws:",o=t.host,a=null!=t.port&&!0!==(null==o?void 0:o.endsWith(":".concat(t.port)))?":".concat(t.port):"";e="".concat(i,"//").concat(o).concat(a).concat(e)}var s=new URL(e);for(var[l,c]of Object.entries(mj))s.protocol===l&&(s.protocol=c);return s})(e,"undefined"==typeof window?void 0:window.location),n=new gj(r.toString(),t.websocket);return yj(n,t)}class bj{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"log",void 0),e._defineProperty(this,"init",void 0),e._defineProperty(this,"logger",void 0),e._defineProperty(this,"metrics",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,Jo,!0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/websockets"),e._defineProperty(this,Ra,["@libp2p/transport"]),this.log=t.logger.forComponent("libp2p:websockets"),this.logger=t.logger,this.components=t,this.init=r,null!=t.metrics&&(this.metrics={dialerEvents:t.metrics.registerCounterGroup("libp2p_websockets_dialer_events_total",{label:"event",help:"Total count of WebSockets dialer events by type"})})}dial(t,r){var n=this;return e._asyncToGenerator((function*(){var i;n.log("dialing %s",t),r=null!=r?r:{};var o=function(t,r,n){var i,o=n.logger.forComponent("libp2p:websockets:maconn"),a=n.metrics,s=null!==(i=n.metricPrefix)&&void 0!==i?i:"",l={log:o,sink:r=>e._asyncToGenerator((function*(){try{yield t.sink(e._wrapAsyncGenerator((function*(){var t,n=!1,i=!1;try{for(var o,a=e._asyncIterator(r);n=!(o=yield e._awaitAsyncGenerator(a.next())).done;n=!1){var s=o.value;s instanceof Uint8Array?yield s:yield s.subarray()}}catch(e){i=!0,t=e}finally{try{n&&null!=a.return&&(yield e._awaitAsyncGenerator(a.return()))}finally{if(i)throw t}}}))())}catch(e){"aborted"!==e.type&&o.error(e)}}))(),source:t.source,remoteAddr:r,timeline:{open:Date.now()},close(){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i,a=r.length>0&&void 0!==r[0]?r[0]:{},s=Date.now();if(null==a.signal){var c=AbortSignal.timeout(500);a=e._objectSpread2(e._objectSpread2({},a),{},{signal:c})}var u=()=>{var{host:e,port:t}=l.remoteAddr.toOptions();o("timeout closing stream to %s:%s after %dms, destroying it manually",e,t,Date.now()-s),n.abort(new Zo("Socket close timeout"))};null===(i=a.signal)||void 0===i||i.addEventListener("abort",u);try{yield t.close()}catch(e){o.error("error closing WebSocket gracefully",e),n.abort(e)}finally{var d;null===(d=a.signal)||void 0===d||d.removeEventListener("abort",u),l.timeline.close=Date.now()}}))()},abort(e){var{host:r,port:n}=l.remoteAddr.toOptions();o("timeout closing stream to %s:%s due to error",r,n,e),t.destroy(),l.timeline.close=Date.now(),null==a||a.increment({["".concat(s,"error")]:!0})}};return t.socket.addEventListener("close",(()=>{null==a||a.increment({["".concat(s,"close")]:!0}),null==l.timeline.close&&(l.timeline.close=Date.now())}),{once:!0}),l}(yield n._connect(t,r),t,{logger:n.logger,metrics:null===(i=n.metrics)||void 0===i?void 0:i.dialerEvents});n.log("new outbound connection %s",o.remoteAddr);var a=yield r.upgrader.upgradeOutbound(o,r);return n.log("outbound connection %s upgraded",o.remoteAddr),a}))()}_connect(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i;null==r||null===(e=r.signal)||void 0===e||e.throwIfAborted();var o=t.toOptions();n.log("dialing %s:%s",o.host,o.port);var a=Yc(),s=wj(MN(t),n.init);s.socket.addEventListener("error",(()=>{var e,r=new aa("Could not connect to ".concat(t.toString()));n.log.error("connection error:",r),null===(e=n.metrics)||void 0===e||e.dialerEvents.increment({error:!0}),a.reject(r)}));try{var l;null===(l=r.onProgress)||void 0===l||l.call(r,new Ih("websockets:open-connection")),yield tu(Promise.race([s.connected(),a.promise]),r.signal)}catch(e){var c,u;if(null!==(c=r.signal)&&void 0!==c&&c.aborted)null===(u=n.metrics)||void 0===u||u.dialerEvents.increment({abort:!0});throw s.close().catch((e=>{n.log.error("error closing raw socket",e)})),e}return n.log("connected %s",t),null===(i=n.metrics)||void 0===i||i.dialerEvents.increment({connect:!0}),s}))()}createListener(t){return function(){throw new Error("WebSocket Servers can not be created in the browser!")}((this.logger,this.components.events,this.components.metrics),e._objectSpread2(e._objectSpread2({},this.init),t))}listenFilter(e){var t,r;return e=Array.isArray(e)?e:[e],null!=(null===(t=this.init)||void 0===t?void 0:t.filter)?null===(r=this.init)||void 0===r?void 0:r.filter(e):function(e){return e.filter((e=>Ud.exactMatch(e)||jd.exactMatch(e)))}(e)}dialFilter(e){return this.listenFilter(e)}}function _j(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return t=>new bj(t,e)}function Sj(e,t){var r=t.map(((e,t)=>({record:bD(e),index:t})));return r.sort(((e,t)=>{var r=e.record.sequence,n=t.record.sequence;if(r>n)return-1;if(r<n)return 1;if(e.record.validityType===aD.ValidityType.EOL&&t.record.validityType===aD.ValidityType.EOL){var i=lD.fromString(e.record.validity).toDate(),o=lD.fromString(t.record.validity).toDate();if(i.getTime()>o.getTime())return-1;if(i.getTime()<o.getTime())return 1}return 0})),r[0].index}var Pj="2.8.8",Ej="js-libp2p";function Aj(e,t){return"".concat(null!=e?e:Ej,"/").concat(null!=t?t:Pj," browser/").concat(globalThis.navigator.userAgent)}var kj={list:["/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN","/dnsaddr/bootstrap.libp2p.io/p2p/QmbLHAnMoJPWSCR5Zhtx6BHJX9KiKNN6tpvbUcqanj75Nb","/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt","/dnsaddr/va1.bootstrap.libp2p.io/p2p/12D3KooWKnDdG3iXw9eTFijk3EWSunZcFi54Zka4wmtqtt6rPxc8","/ip4/104.131.131.82/tcp/4001/p2p/QmaCpDMGvV2BGHeYERUEnRQAwe3N8SzbUtfsmvsqQLuvuJ"]};function xj(){var e,t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},r="".concat("helia","/").concat("5.3.0"," ").concat(Aj());return{privateKey:t.privateKey,dns:t.dns,nodeInfo:{userAgent:r},addresses:{listen:["/p2p-circuit","/webrtc"]},transports:[tp(),dx(),ux(),_j()],connectionEncrypters:[Zk()],streamMuxers:[zG(),ij()],peerDiscovery:[(e=kj,t=>new xR(t,e))],services:{autoNAT:QG(),dcutr:FR(),delegatedRouting:()=>function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return new zD(new URL(e),t)}("https://delegated-ipfs.dev",{filterProtocols:["unknown","transport-bitswap","transport-ipfs-gateway-http"],filterAddrs:["https","webtransport","webrtc","webrtc-direct","wss","tls"]}),dht:LL({clientMode:!0,validators:{ipns:xD},selectors:{ipns:Sj}}),identify:ZR(),identifyPush:$R(),keychain:jM(t.keychain),ping:aj()}}}function Tj(){return Tj=e._asyncToGenerator((function*(e){var t,r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},o=null!==(t=i.selfKey)&&void 0!==t?t:"self",a=jM(i)({datastore:e,logger:Iu()});(yield e.has(new Bc("/pkcs8/".concat(o))))?r=yield a.exportKey(o):(r=yield Fl(null!==(n=i.keyType)&&void 0!==n?n:"Ed25519"),yield a.importKey(o,r));return r})),Tj.apply(this,arguments)}var Ij=-1,Cj={},Bj={};[[4,32,"ip4"],[6,16,"tcp"],[33,16,"dccp"],[41,128,"ip6"],[42,Ij,"ip6zone"],[43,8,"ipcidr"],[53,Ij,"dns",!0],[54,Ij,"dns4",!0],[55,Ij,"dns6",!0],[56,Ij,"dnsaddr",!0],[132,16,"sctp"],[273,16,"udp"],[275,0,"p2p-webrtc-star"],[276,0,"p2p-webrtc-direct"],[277,0,"p2p-stardust"],[280,0,"webrtc-direct"],[281,0,"webrtc"],[290,0,"p2p-circuit"],[301,0,"udt"],[302,0,"utp"],[400,Ij,"unix",!1,!0],[421,Ij,"ipfs"],[421,Ij,"p2p"],[443,0,"https"],[444,96,"onion"],[445,296,"onion3"],[446,Ij,"garlic64"],[448,0,"tls"],[449,Ij,"sni"],[460,0,"quic"],[461,0,"quic-v1"],[465,0,"webtransport"],[466,Ij,"certhash"],[477,0,"ws"],[478,0,"wss"],[479,0,"p2p-websocket-star"],[480,0,"http"],[481,Ij,"http-path"],[777,Ij,"memory"]].forEach((e=>{var t=function(e,t,r,n,i){return{code:e,size:t,name:r,resolvable:Boolean(n),path:Boolean(i)}}(...e);Bj[t.code]=t,Cj[t.name]=t}));var{code:Nj}=function(e){if(null!=Cj[e])return Cj[e];throw new Error("no protocol with name: ".concat(e))}("dnsaddr");class Dj extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Max recursive depth reached"),this.name="RecursionLimitError"}}var Gj=function(){var t=e._asyncToGenerator((function*(t){var r,n,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},a=null!==(r=o.maxRecursiveDepth)&&void 0!==r?r:32;if(0===a)throw new Dj("Max recursive depth reached");var[,s]=null!==(n=t.stringTuples().find((e=>{var[t]=e;return t===Nj})))&&void 0!==n?n:[],l=null!==(i=null==o?void 0:o.dns)&&void 0!==i?i:PT(),c=yield l.query("_dnsaddr.".concat(s),{signal:null==o?void 0:o.signal,types:[ST.TXT]}),u=t.getPeerId(),d=[];for(var h of c.Answer){var p=h.data.replace(/["']/g,"").trim().split("=")[1];if(null!=p&&(null==u||p.includes(u))){var f=sr(p);if(p.startsWith("/dnsaddr")){var v=yield f.resolve(e._objectSpread2(e._objectSpread2({},o),{},{maxRecursiveDepth:a-1}));d.push(...v.map((e=>e.toString())))}else d.push(f.toString())}}return d}));return function(e){return t.apply(this,arguments)}}(),Rj={addresses:{listen:[],announce:[],noAnnounce:[],announceFilter:e=>e},connectionManager:{resolvers:{dnsaddr:Gj}},transportManager:{faultTolerance:Wo.FATAL_ALL}};function Oj(){return Oj=e._asyncToGenerator((function*(e){var t,r=rM(Rj,e);if(null===r.connectionProtector&&null!=(null===(t=globalThis.process)||void 0===t||null===(t=t.env)||void 0===t?void 0:t.LIBP2P_FORCE_PNET))throw new ea("Private network is enforced, but no protector was provided");return r})),Oj.apply(this,arguments)}var Lj,Mj,jj;function Fj(e,t){if(null!=e.publicKey||null==t.publicKey)return e;var r;"RSA"===e.type&&(r=Ae(j.decode("z".concat(e))));return nc(zl(t.publicKey,r))}function Uj(e,t,r){return zj(e,Lj.decode(t),r)}function zj(t,r,n){var i,o=new Map,a=BigInt(Date.now());for(var[s,l]of r.tags.entries())null!=l.expiry&&l.expiry<a||o.set(s,l);return e._objectSpread2(e._objectSpread2({},r),{},{id:Fj(t,r),addresses:r.addresses.filter((e=>{var{observed:t}=e;return null!=t&&t>Date.now()-n})).map((e=>{var{multiaddr:t,isCertified:r}=e;return{multiaddr:sr(t),isCertified:null!=r&&r}})),metadata:r.metadata,peerRecordEnvelope:null!==(i=r.peerRecordEnvelope)&&void 0!==i?i:void 0,tags:o})}function Vj(e,t){return u=e.addresses,d=t.addresses,Hj(u,d,((e,t)=>e.isCertified===t.isCertified&&!!nt(e.multiaddr,t.multiaddr)))&&(l=e.protocols,c=t.protocols,Hj(l,c,((e,t)=>e===t)))&&(a=e.publicKey,s=t.publicKey,qj(a,s))&&(i=e.peerRecordEnvelope,o=t.peerRecordEnvelope,qj(i,o))&&(r=e.metadata,n=t.metadata,Kj(r,n,((e,t)=>nt(e,t))))&&function(e,t){return Kj(e,t,((e,t)=>e.value===t.value&&e.expiry===t.expiry))}(e.tags,t.tags);var r,n,i,o,a,s,l,c,u,d}function qj(e,t){return null==e&&null==t||null!=e&&null!=t&&nt(e,t)}function Hj(e,t,r){if(e.length!==t.length)return!1;for(var n=0;n<e.length;n++)if(!r(e[n],t[n]))return!1;return!0}function Kj(e,t,r){if(e.size!==t.size)return!1;for(var[n,i]of e.entries()){var o=t.get(n);if(null==o)return!1;if(!r(i,o))return!1}return!0}!function(e){var t;!function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&e.value.byteLength>0&&(t.uint32(18),t.bytes(e.value)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={key:"",value:He(0)},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.key=e.string();break;case 2:r.value=e.bytes();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(e.Peer$metadataEntry||(e.Peer$metadataEntry={})),function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.key&&""!==e.key&&(t.uint32(10),t.string(e.key)),null!=e.value&&(t.uint32(18),jj.codec().encode(e.value,t)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n={key:""},i=null==t?e.len:e.pos+t;e.pos<i;){var o=e.uint32();switch(o>>>3){case 1:n.key=e.string();break;case 2:var a;n.value=jj.codec().decode(e,e.uint32(),{limits:null===(a=r.limits)||void 0===a?void 0:a.value});break;default:e.skipType(7&o)}}return n}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(e.Peer$tagsEntry||(e.Peer$tagsEntry={})),e.codec=()=>(null==t&&(t=fl((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==n.lengthDelimited&&r.fork(),null!=t.addresses)for(var i of t.addresses)r.uint32(10),Mj.codec().encode(i,r);if(null!=t.protocols)for(var o of t.protocols)r.uint32(18),r.string(o);if(null!=t.publicKey&&(r.uint32(34),r.bytes(t.publicKey)),null!=t.peerRecordEnvelope&&(r.uint32(42),r.bytes(t.peerRecordEnvelope)),null!=t.metadata&&0!==t.metadata.size)for(var[a,s]of t.metadata.entries())r.uint32(50),e.Peer$metadataEntry.codec().encode({key:a,value:s},r);if(null!=t.tags&&0!==t.tags.size)for(var[l,c]of t.tags.entries())r.uint32(58),e.Peer$tagsEntry.codec().encode({key:l,value:c},r);null!=t.updated&&(r.uint32(64),r.uint64Number(t.updated)),!1!==n.lengthDelimited&&r.ldelim()}),(function(t,r){for(var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},i={addresses:[],protocols:[],metadata:new Map,tags:new Map},o=null==r?t.len:t.pos+r;t.pos<o;){var a=t.uint32();switch(a>>>3){case 1:var s,l;if(null!=(null===(s=n.limits)||void 0===s?void 0:s.addresses)&&i.addresses.length===n.limits.addresses)throw new vl('Decode error - map field "addresses" had too many elements');i.addresses.push(Mj.codec().decode(t,t.uint32(),{limits:null===(l=n.limits)||void 0===l?void 0:l.addresses$}));break;case 2:var c;if(null!=(null===(c=n.limits)||void 0===c?void 0:c.protocols)&&i.protocols.length===n.limits.protocols)throw new vl('Decode error - map field "protocols" had too many elements');i.protocols.push(t.string());break;case 4:i.publicKey=t.bytes();break;case 5:i.peerRecordEnvelope=t.bytes();break;case 6:var u;if(null!=(null===(u=n.limits)||void 0===u?void 0:u.metadata)&&i.metadata.size===n.limits.metadata)throw new yl('Decode error - map field "metadata" had too many elements');var d=e.Peer$metadataEntry.codec().decode(t,t.uint32());i.metadata.set(d.key,d.value);break;case 7:var h,p;if(null!=(null===(h=n.limits)||void 0===h?void 0:h.tags)&&i.tags.size===n.limits.tags)throw new yl('Decode error - map field "tags" had too many elements');var f=e.Peer$tagsEntry.codec().decode(t,t.uint32(),{limits:{value:null===(p=n.limits)||void 0===p?void 0:p.tags$value}});i.tags.set(f.key,f.value);break;case 8:i.updated=t.uint64Number();break;default:t.skipType(7&a)}}return i}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(Lj||(Lj={})),function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.multiaddr&&e.multiaddr.byteLength>0&&(t.uint32(10),t.bytes(e.multiaddr)),null!=e.isCertified&&(t.uint32(16),t.bool(e.isCertified)),null!=e.observed&&(t.uint32(24),t.uint64Number(e.observed)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={multiaddr:He(0)},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.multiaddr=e.bytes();break;case 2:r.isCertified=e.bool();break;case 3:r.observed=e.uint64Number();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(Mj||(Mj={})),function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.value&&0!==e.value&&(t.uint32(8),t.uint32(e.value)),null!=e.expiry&&(t.uint32(16),t.uint64(e.expiry)),!1!==r.lengthDelimited&&t.ldelim()}),(function(e,t){for(var r={value:0},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.value=e.uint32();break;case 2:r.expiry=e.uint64();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>dl(t,e.codec()),e.decode=(t,r)=>Vs(t,e.codec(),r)}(jj||(jj={}));var Wj="/peers/";function Qj(e){if(!Ko(e)||null==e.type)throw new ea("Invalid PeerId");var t=e.toCID().toString();return new Bc("".concat(Wj).concat(t))}function Yj(e,t,r,n){return Jj.apply(this,arguments)}function Jj(){return Jj=e._asyncToGenerator((function*(e,t,r,n){var i=new Map;for(var o of r){var a;if(null!=o){if(o.multiaddr instanceof Uint8Array&&(o.multiaddr=sr(o.multiaddr)),!ar(o.multiaddr))throw new ea("Multiaddr was invalid");if(yield t(e,o.multiaddr)){var s=null!==(a=o.isCertified)&&void 0!==a&&a,l=o.multiaddr.toString(),c=i.get(l);null!=c?o.isCertified=c.isCertified||s:i.set(l,{multiaddr:o.multiaddr,isCertified:s})}}}return[...i.values()].sort(((e,t)=>e.multiaddr.toString().localeCompare(t.multiaddr.toString()))).map((t=>{var{isCertified:r,multiaddr:n}=t,i=n.getPeerId();return e.equals(i)&&(n=n.decapsulate(sr("/p2p/".concat(e)))),{isCertified:r,multiaddr:n.bytes}}))})),Jj.apply(this,arguments)}function Zj(e,t,r,n){return $j.apply(this,arguments)}function $j(){return $j=e._asyncToGenerator((function*(t,r,n,i){var o,a,s,l,c,u,d;if(null==r)throw new ea("Invalid PeerData");if(null!=r.publicKey&&null!=t.publicKey&&!r.publicKey.equals(t.publicKey))throw new ea("publicKey bytes do not match peer id publicKey bytes");var h=null===(o=i.existingPeer)||void 0===o?void 0:o.peer;if(null!=h&&!t.equals(h.id))throw new ea("peer id did not match existing peer id");var p,f=null!==(a=null==h?void 0:h.addresses)&&void 0!==a?a:[],v=new Set(null!==(s=null==h?void 0:h.protocols)&&void 0!==s?s:[]),y=null!==(l=null==h?void 0:h.metadata)&&void 0!==l?l:new Map,g=null!==(c=null==h?void 0:h.tags)&&void 0!==c?c:new Map,m=null==h?void 0:h.peerRecordEnvelope;if("patch"===n){if(null==r.multiaddrs&&null==r.addresses||(f=[],null!=r.multiaddrs&&f.push(...r.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=r.addresses&&f.push(...r.addresses)),null!=r.protocols&&(v=new Set(r.protocols)),null!=r.metadata)y=Xj(r.metadata instanceof Map?[...r.metadata.entries()]:Object.entries(r.metadata),{validate:eF});if(null!=r.tags)g=Xj(r.tags instanceof Map?[...r.tags.entries()]:Object.entries(r.tags),{validate:tF,map:rF});null!=r.peerRecordEnvelope&&(m=r.peerRecordEnvelope)}if("merge"===n){if(null!=r.multiaddrs&&f.push(...r.multiaddrs.map((e=>({isCertified:!1,multiaddr:e})))),null!=r.addresses&&f.push(...r.addresses),null!=r.protocols&&(v=new Set([...v,...r.protocols])),null!=r.metadata){var w=r.metadata instanceof Map?[...r.metadata.entries()]:Object.entries(r.metadata);for(var[b,_]of w)null==_?y.delete(b):y.set(b,_);y=Xj([...y.entries()],{validate:eF})}if(null!=r.tags){var S=r.tags instanceof Map?[...r.tags.entries()]:Object.entries(r.tags),P=new Map(g);for(var[E,A]of S)null==A?P.delete(E):P.set(E,A);g=Xj([...P.entries()],{validate:tF,map:rF})}null!=r.peerRecordEnvelope&&(m=r.peerRecordEnvelope)}null!=(null==h?void 0:h.id.publicKey)?p=ql(h.id.publicKey):null!=r.publicKey?p=ql(r.publicKey):null!=t.publicKey&&(p=ql(t.publicKey));var k={addresses:yield Yj(t,null!==(u=i.addressFilter)&&void 0!==u?u:e._asyncToGenerator((function*(){return!0})),f,null===(d=i.existingPeer)||void 0===d?void 0:d.peerPB.addresses),protocols:[...v.values()].sort(((e,t)=>e.localeCompare(t))),metadata:y,tags:g,publicKey:p,peerRecordEnvelope:m};return k.addresses.forEach((e=>{var t,r;e.observed=null!==(t=null===(r=i.existingPeer)||void 0===r||null===(r=r.peerPB.addresses)||void 0===r||null===(r=r.find((e=>nt(e.multiaddr,e.multiaddr))))||void 0===r?void 0:r.observed)&&void 0!==t?t:Date.now()})),"RSA"!==t.type&&delete k.publicKey,k})),$j.apply(this,arguments)}function Xj(e,t){var r=new Map;for(var[n,i]of e)null!=i&&t.validate(n,i);for(var[o,a]of e.sort(((e,t)=>{var[r]=e,[n]=t;return r.localeCompare(n)}))){var s,l;if(null!=a)r.set(o,null!==(s=null===(l=t.map)||void 0===l?void 0:l.call(t,o,a))&&void 0!==s?s:a)}return r}function eF(e,t){if("string"!=typeof e)throw new ea("Metadata key must be a string");if(!(t instanceof Uint8Array))throw new ea("Metadata value must be a Uint8Array")}function tF(e,t){if("string"!=typeof e)throw new ea("Tag name must be a string");if(null!=t.value){if(parseInt("".concat(t.value),10)!==t.value)throw new ea("Tag value must be an integer");if(t.value<0||t.value>100)throw new ea("Tag value must be between 0-100")}if(null!=t.ttl){if(parseInt("".concat(t.ttl),10)!==t.ttl)throw new ea("Tag ttl must be an integer");if(t.ttl<0)throw new ea("Tag ttl must be between greater than 0")}}function rF(e,t){var r,n;return null!=t.expiry&&(n=t.expiry),null!=t.ttl&&(n=BigInt(Date.now()+Number(t.ttl))),{value:null!==(r=t.value)&&void 0!==r?r:0,expiry:n}}function nF(e){var t=e.toString().split("/")[2];return ac(je.parse(t,k))}function iF(e,t,r){return Uj(nF(e),t,r)}var oF=new WeakSet;class aF{constructor(t){var r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._classPrivateMethodInitSpec(this,oF),e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"datastore",void 0),e._defineProperty(this,"lock",void 0),e._defineProperty(this,"addressFilter",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"maxAddressAge",void 0),e._defineProperty(this,"maxPeerAge",void 0),this.log=t.logger.forComponent("libp2p:peer-store"),this.peerId=t.peerId,this.datastore=t.datastore,this.addressFilter=i.addressFilter,this.lock=iB({name:"peer-store",singleProcess:!0}),this.maxAddressAge=null!==(r=i.maxAddressAge)&&void 0!==r?r:36e5,this.maxPeerAge=null!==(n=i.maxPeerAge)&&void 0!==n?n:216e5}has(t){var r=this;return e._asyncToGenerator((function*(){try{return yield r.load(t),!0}catch(e){if("NotFoundError"!==e.name)throw e}return!1}))()}delete(t){var r=this;return e._asyncToGenerator((function*(){r.peerId.equals(t)||(yield r.datastore.delete(Qj(t)))}))()}load(t){var r=this;return e._asyncToGenerator((function*(){var n=Qj(t),i=yield r.datastore.get(n),o=Lj.decode(i);if(e._assertClassBrand(oF,r,dF).call(r,t,o))throw yield r.datastore.delete(n),new ua;return zj(t,o,r.peerId.equals(t)?1/0:r.maxAddressAge)}))()}save(t,r){var n=this;return e._asyncToGenerator((function*(){var i=yield e._assertClassBrand(oF,n,sF).call(n,t),o=yield Zj(t,r,"patch",{addressFilter:n.addressFilter});return e._assertClassBrand(oF,n,cF).call(n,t,o,i)}))()}patch(t,r){var n=this;return e._asyncToGenerator((function*(){var i=yield e._assertClassBrand(oF,n,sF).call(n,t),o=yield Zj(t,r,"patch",{addressFilter:n.addressFilter,existingPeer:i});return e._assertClassBrand(oF,n,cF).call(n,t,o,i)}))()}merge(t,r){var n=this;return e._asyncToGenerator((function*(){var i=yield e._assertClassBrand(oF,n,sF).call(n,t),o=yield Zj(t,r,"merge",{addressFilter:n.addressFilter,existingPeer:i});return e._assertClassBrand(oF,n,cF).call(n,t,o,i)}))()}all(t){var r=this;return e._wrapAsyncGenerator((function*(){var n,i=!1,o=!1;try{for(var a,s=e._asyncIterator(r.datastore.query(function(e,t){var r,n;return{prefix:Wj,filters:(null!==(r=e.filters)&&void 0!==r?r:[]).map((e=>r=>{var{key:n,value:i}=r;return e(iF(n,i,t))})),orders:(null!==(n=e.orders)&&void 0!==n?n:[]).map((e=>(r,n)=>e(iF(r.key,r.value,t),iF(n.key,n.value,t))))}}(null!=t?t:{},r.maxAddressAge)));i=!(a=yield e._awaitAsyncGenerator(s.next())).done;i=!1){var{key:l,value:c}=a.value,u=nF(l);if(!u.equals(r.peerId)){var d=Lj.decode(c);e._assertClassBrand(oF,r,dF).call(r,u,d)?yield e._awaitAsyncGenerator(r.datastore.delete(l)):yield zj(u,d,r.peerId.equals(u)?1/0:r.maxAddressAge)}}}catch(e){o=!0,n=e}finally{try{i&&null!=s.return&&(yield e._awaitAsyncGenerator(s.return()))}finally{if(o)throw n}}}))()}}function sF(e){return lF.apply(this,arguments)}function lF(){return lF=e._asyncToGenerator((function*(t){try{var r=Qj(t),n=yield this.datastore.get(r),i=Lj.decode(n);if(e._assertClassBrand(oF,this,dF).call(this,t,i))throw yield this.datastore.delete(r),new ua;return{peerPB:i,peer:Uj(t,n,this.maxAddressAge)}}catch(e){"NotFoundError"!==e.name&&this.log.error("invalid peer data found in peer store - %e",e)}})),lF.apply(this,arguments)}function cF(e,t,r){return uF.apply(this,arguments)}function uF(){return uF=e._asyncToGenerator((function*(e,t,r){t.updated=Date.now();var n=Lj.encode(t);return yield this.datastore.put(Qj(e),n),{peer:Uj(e,n,this.maxAddressAge),previous:null==r?void 0:r.peer,updated:null==r||!Vj(t,r.peerPB)}})),uF.apply(this,arguments)}function dF(e,t){if(null==t.updated)return!0;if(this.peerId.equals(e))return!1;var r=t.updated<Date.now()-this.maxPeerAge,n=Date.now()-this.maxAddressAge,i=t.addresses.filter((e=>null!=e.observed&&e.observed>n));return r&&0===i.length}var hF=new WeakSet;class pF{constructor(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._classPrivateMethodInitSpec(this,hF),e._defineProperty(this,"store",void 0),e._defineProperty(this,"events",void 0),e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/peer-store"),this.log=t.logger.forComponent("libp2p:peer-store"),this.events=t.events,this.peerId=t.peerId,this.store=new aF(t,r)}forEach(t,r){var n=this;return e._asyncToGenerator((function*(){n.log.trace("forEach await read lock");var i=yield n.store.lock.readLock();n.log.trace("forEach got read lock");try{var o,a=!1,s=!1;try{for(var l,c=e._asyncIterator(n.store.all(r));a=!(l=yield c.next()).done;a=!1){var u=l.value;t(u)}}catch(e){s=!0,o=e}finally{try{a&&null!=c.return&&(yield c.return())}finally{if(s)throw o}}}finally{n.log.trace("forEach release read lock"),i()}}))()}all(t){var r=this;return e._asyncToGenerator((function*(){r.log.trace("all await read lock");var e=yield r.store.lock.readLock();r.log.trace("all got read lock");try{return yield Rc(r.store.all(t))}finally{r.log.trace("all release read lock"),e()}}))()}delete(t){var r=this;return e._asyncToGenerator((function*(){r.log.trace("delete await write lock");var e=yield r.store.lock.writeLock();r.log.trace("delete got write lock");try{yield r.store.delete(t)}finally{r.log.trace("delete release write lock"),e()}}))()}has(t){var r=this;return e._asyncToGenerator((function*(){r.log.trace("has await read lock");var e=yield r.store.lock.readLock();r.log.trace("has got read lock");try{return yield r.store.has(t)}finally{r.log.trace("has release read lock"),e()}}))()}get(t){var r=this;return e._asyncToGenerator((function*(){r.log.trace("get await read lock");var e=yield r.store.lock.readLock();r.log.trace("get got read lock");try{return yield r.store.load(t)}finally{r.log.trace("get release read lock"),e()}}))()}getInfo(t){var r=this;return e._asyncToGenerator((function*(){var e=yield r.get(t);return{id:e.id,multiaddrs:e.addresses.map((e=>{var{multiaddr:t}=e;return t}))}}))()}save(t,r){var n=this;return e._asyncToGenerator((function*(){n.log.trace("save await write lock");var i=yield n.store.lock.writeLock();n.log.trace("save got write lock");try{var o=yield n.store.save(t,r);return e._assertClassBrand(hF,n,fF).call(n,t,o),o.peer}finally{n.log.trace("save release write lock"),i()}}))()}patch(t,r){var n=this;return e._asyncToGenerator((function*(){n.log.trace("patch await write lock");var i=yield n.store.lock.writeLock();n.log.trace("patch got write lock");try{var o=yield n.store.patch(t,r);return e._assertClassBrand(hF,n,fF).call(n,t,o),o.peer}finally{n.log.trace("patch release write lock"),i()}}))()}merge(t,r){var n=this;return e._asyncToGenerator((function*(){n.log.trace("merge await write lock");var i=yield n.store.lock.writeLock();n.log.trace("merge got write lock");try{var o=yield n.store.merge(t,r);return e._assertClassBrand(hF,n,fF).call(n,t,o),o.peer}finally{n.log.trace("merge release write lock"),i()}}))()}consumePeerRecord(t,r){var n=this;return e._asyncToGenerator((function*(){var e,i=yield Ru.openAndCertify(t,Fu.DOMAIN),o=ac(i.publicKey.toCID());if(!1===(null==r?void 0:r.equals(o)))return n.log("envelope peer id was not the expected peer id - expected: %p received: %p",r,o),!1;var a,s=Fu.createFromProtobuf(i.payload);try{a=yield n.get(o)}catch(e){if("NotFoundError"!==e.name)throw e}if(null!=(null===(e=a)||void 0===e?void 0:e.peerRecordEnvelope)){var l=yield Ru.createFromProtobuf(a.peerRecordEnvelope),c=Fu.createFromProtobuf(l.payload);if(c.seqNumber>=s.seqNumber)return n.log("sequence number was lower or equal to existing sequence number - stored: %d received: %d",c.seqNumber,s.seqNumber),!1}return yield n.patch(s.peerId,{peerRecordEnvelope:t,addresses:s.multiaddrs.map((e=>({isCertified:!0,multiaddr:e})))}),!0}))()}}function fF(e,t){t.updated&&(this.peerId.equals(e)?this.events.safeDispatchEvent("self:peer:update",{detail:t}):this.events.safeDispatchEvent("peer:update",{detail:t}))}var vF=864e13;class yF{constructor(t){e._defineProperty(this,"log",void 0),e._defineProperty(this,"mappings",void 0),this.log=t.logger.forComponent("libp2p:address-manager:dns-mappings"),this.mappings=new Map}has(e){var t=this.findHost(e);for(var r of this.mappings.values())if(r.domain===t)return!0;return!1}add(e,t){t.forEach((t=>{this.log("add DNS mapping %s to %s",t,e);var r=!0===CN(t);this.mappings.set(t,{domain:e,verified:r,expires:r?vF-Date.now():0,lastVerified:r?vF-Date.now():void 0})}))}remove(e){var t=this.findHost(e),r=!1;for(var[n,i]of this.mappings.entries())i.domain===t&&(this.log("removing %s to %s DNS mapping %e",n,i.domain,new Error("where")),this.mappings.delete(n),r=r||i.verified);return r}getAll(e){for(var t=[],r=0;r<e.length;r++){var n=e[r].multiaddr.stringTuples(),i=n[0][1];if(null!=i)for(var[o,a]of this.mappings.entries()){if(i===o)this.maybeAddSNITuple(n,a.domain)&&(e.splice(r,1),r--,t.push({multiaddr:sr("/".concat(n.map((e=>[lr(e[0]).name,e[1]].join("/"))).join("/"))),verified:a.verified,type:"dns-mapping",expires:a.expires,lastVerified:a.lastVerified}))}}return t}maybeAddSNITuple(e,t){for(var r=0;r<e.length;r++){var n;if(448===e[r][0]&&449!==(null===(n=e[r+1])||void 0===n?void 0:n[0]))return e.splice(r+1,0,[449,t]),!0}return!1}confirm(e,t){var r=this.findHost(e),n=!1;for(var[i,o]of this.mappings.entries())o.domain===r&&(this.log("marking %s to %s DNS mapping as verified",i,o.domain),n=o.verified,o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now());return n}unconfirm(e,t){var r=this.findHost(e),n=!1;for(var[i,o]of this.mappings.entries())o.domain===r&&(this.log("removing verification of %s to %s DNS mapping",i,o.domain),n=n||o.verified,o.verified=!1,o.expires=Date.now()+t);return n}findHost(e){for(var t of e.stringTuples()){if(449===t[0])return t[1];if(53===t[0]||54===t[0]||55===t[0]||56===t[0])return t[1]}}}class gF{constructor(t){e._defineProperty(this,"log",void 0),e._defineProperty(this,"mappings",void 0),this.log=t.logger.forComponent("libp2p:address-manager:ip-mappings"),this.mappings=new Map}has(e){var t=e.stringTuples();for(var r of this.mappings.values())for(var n of r)if(n.externalIp===t[0][1])return!0;return!1}add(e,t,r){var n,i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:t,o=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"tcp",a="".concat(e,"-").concat(t,"-").concat(o),s=null!==(n=this.mappings.get(a))&&void 0!==n?n:[],l={internalIp:e,internalPort:t,externalIp:r,externalPort:i,externalFamily:xt(r)?4:6,protocol:o,verified:!1,expires:0};s.push(l),this.mappings.set(a,s)}remove(e){var t,r,n=e.stringTuples(),i=null!==(t=n[0][1])&&void 0!==t?t:"",o=6===n[1][0]?"tcp":"udp",a=parseInt(null!==(r=n[1][1])&&void 0!==r?r:"0"),s=!1;for(var[l,c]of this.mappings.entries()){for(var u=0;u<c.length;u++){var d=c[u];d.externalIp===i&&d.externalPort===a&&d.protocol===o&&(this.log("removing %s:%s to %s:%s %s IP mapping",d.externalIp,d.externalPort,i,a,o),s=s||d.verified,c.splice(u,1),u--)}0===c.length&&this.mappings.delete(l)}return s}getAll(e){var t=[];for(var{multiaddr:r}of e){var n=r.stringTuples(),i=void 0;if(4!==n[0][0]&&41!==n[0][0]||6!==n[1][0]?4!==n[0][0]&&41!==n[0][0]||273!==n[1][0]||(i="".concat(n[0][1],"-").concat(n[1][1],"-udp")):i="".concat(n[0][1],"-").concat(n[1][1],"-tcp"),null!=i){var o=this.mappings.get(i);if(null!=o)for(var a of o)n[0][0]=4===a.externalFamily?4:41,n[0][1]=a.externalIp,n[1][1]="".concat(a.externalPort),t.push({multiaddr:sr("/".concat(n.map((e=>[lr(e[0]).name,e[1]].join("/"))).join("/"))),verified:a.verified,type:"ip-mapping",expires:a.expires,lastVerified:a.lastVerified})}}return t}confirm(e,t){var r=e.stringTuples()[0][1],n=!1;for(var i of this.mappings.values())for(var o of i)o.externalIp===r&&(this.log("marking %s to %s IP mapping as verified",o.internalIp,o.externalIp),n=o.verified,o.verified=!0,o.expires=Date.now()+t,o.lastVerified=Date.now());return n}unconfirm(e,t){var r,n,i=e.stringTuples(),o=null!==(r=i[0][1])&&void 0!==r?r:"",a=6===i[1][0]?"tcp":"udp",s=parseInt(null!==(n=i[1][1])&&void 0!==n?n:"0"),l=!1;for(var c of this.mappings.values())for(var u=0;u<c.length;u++){var d=c[u];d.externalIp===o&&d.externalPort===s&&d.protocol===a&&(this.log("removing verification of %s:%s to %s:%s %s IP mapping",d.externalIp,d.externalPort,o,s,a),l=l||d.verified,d.verified=!1,d.expires=Date.now()+t)}return l}}var mF=10;class wF{constructor(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"log",void 0),e._defineProperty(this,"addresses",void 0),e._defineProperty(this,"maxObservedAddresses",void 0),this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=null!==(r=n.maxObservedAddresses)&&void 0!==r?r:mF}has(e){return this.addresses.has(e.toString())}removePrefixed(e){for(var t of this.addresses.keys())t.toString().startsWith(e)&&this.addresses.delete(t)}add(e){this.addresses.size!==this.maxObservedAddresses&&(HG(e)||function(e){try{var[[t,r]]=e.stringTuples();if(null==r)return!1;if(4===t)return r.startsWith("169.254.");if(41===t)return r.toLowerCase().startsWith("fe80")}catch(e){}return!1}(e)||(this.log("adding observed address %a",e),this.addresses.set(e.toString(),{verified:!1,expires:0})))}getAll(){return Array.from(this.addresses).map((e=>{var[t,r]=e;return{multiaddr:sr(t),verified:r.verified,type:"observed",expires:r.expires,lastVerified:r.lastVerified}}))}remove(e){var t,r,n=null!==(t=null===(r=this.addresses.get(e.toString()))||void 0===r?void 0:r.verified)&&void 0!==t&&t;return this.log("removing observed address %a",e),this.addresses.delete(e.toString()),n}confirm(e,t){var r,n=e.toString(),i=null!==(r=this.addresses.get(n))&&void 0!==r?r:{verified:!1,expires:Date.now()+t,lastVerified:Date.now()},o=i.verified;return i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now(),this.log("marking observed address %a as verified",n),this.addresses.set(n,i),o}}var bF=[4,41,53,54,55,56];function _F(e){try{var[[t]]=e.stringTuples();return bF.includes(t)}catch(e){}return!1}var SF=10;class PF{constructor(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"log",void 0),e._defineProperty(this,"addresses",void 0),e._defineProperty(this,"maxObservedAddresses",void 0),this.log=t.logger.forComponent("libp2p:address-manager:observed-addresses"),this.addresses=new Map,this.maxObservedAddresses=null!==(r=n.maxObservedAddresses)&&void 0!==r?r:SF}get(e,t){if(HG(e))return{multiaddr:e,verified:!0,type:"transport",expires:Date.now()+t,lastVerified:Date.now()};var r=this.toKey(e),n=this.addresses.get(r);return null==n&&(n={verified:!_F(e),expires:0},this.addresses.set(r,n)),{multiaddr:e,verified:n.verified,type:"transport",expires:n.expires,lastVerified:n.lastVerified}}has(e){var t=this.toKey(e);return this.addresses.has(t)}remove(e){var t,r,n=this.toKey(e),i=null!==(t=null===(r=this.addresses.get(n))||void 0===r?void 0:r.verified)&&void 0!==t&&t;return this.log("removing observed address %a",e),this.addresses.delete(n),i}confirm(e,t){var r,n=this.toKey(e),i=null!==(r=this.addresses.get(n))&&void 0!==r?r:{verified:!1,expires:0,lastVerified:0},o=i.verified;return i.verified=!0,i.expires=Date.now()+t,i.lastVerified=Date.now(),this.addresses.set(n,i),o}unconfirm(e,t){var r,n=this.toKey(e),i=null!==(r=this.addresses.get(n))&&void 0!==r?r:{verified:!1,expires:0},o=i.verified;return i.verified=!1,i.expires=Date.now()+t,this.addresses.set(n,i),o}toKey(e){if(_F(e)){var t=e.toOptions();return"".concat(t.host,"-").concat(t.port,"-").concat(t.transport)}return e.toString()}}var EF,AF={addressVerificationTTL:6e5,addressVerificationRetry:3e5},kF=e=>e;function xF(e,t){var r=e.getPeerId();null!=r&&(rc(r).equals(t)&&(e=e.decapsulate(sr("/p2p/".concat(t.toString())))));return e}class TF{constructor(t){var r,n,i,o=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"log",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"listen",void 0),e._defineProperty(this,"announce",void 0),e._defineProperty(this,"appendAnnounce",void 0),e._defineProperty(this,"announceFilter",void 0),e._defineProperty(this,"observed",void 0),e._defineProperty(this,"dnsMappings",void 0),e._defineProperty(this,"ipMappings",void 0),e._defineProperty(this,"transportAddresses",void 0),e._defineProperty(this,"observedAddressFilter",void 0),e._defineProperty(this,"addressVerificationTTL",void 0),e._defineProperty(this,"addressVerificationRetry",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/address-manager");var{listen:a=[],announce:s=[],appendAnnounce:l=[]}=o;this.components=t,this.log=t.logger.forComponent("libp2p:address-manager"),this.listen=a.map((e=>e.toString())),this.announce=new Set(s.map((e=>e.toString()))),this.appendAnnounce=new Set(l.map((e=>e.toString()))),this.observed=new wF(t,o),this.dnsMappings=new yF(t,o),this.ipMappings=new gF(t,o),this.transportAddresses=new PF(t,o),this.announceFilter=null!==(r=o.announceFilter)&&void 0!==r?r:kF,this.observedAddressFilter=_h(1024),this.addressVerificationTTL=null!==(n=o.addressVerificationTTL)&&void 0!==n?n:AF.addressVerificationTTL,this.addressVerificationRetry=null!==(i=o.addressVerificationRetry)&&void 0!==i?i:AF.addressVerificationRetry,this._updatePeerStoreAddresses=Dh(this._updatePeerStoreAddresses.bind(this),1e3),t.events.addEventListener("transport:listening",(()=>{this._updatePeerStoreAddresses()})),t.events.addEventListener("transport:close",(()=>{this._updatePeerStoreAddresses()}))}_updatePeerStoreAddresses(){var e=this.getAddresses().map((e=>e.getPeerId()===this.components.peerId.toString()?e.decapsulate("/p2p/".concat(this.components.peerId.toString())):e));this.components.peerStore.patch(this.components.peerId,{multiaddrs:e}).catch((e=>{this.log.error("error updating addresses",e)}))}getListenAddrs(){return Array.from(this.listen).map((e=>sr(e)))}getAnnounceAddrs(){return Array.from(this.announce).map((e=>sr(e)))}getAppendAnnounceAddrs(){return Array.from(this.appendAnnounce).map((e=>sr(e)))}getObservedAddrs(){return this.observed.getAll().map((e=>e.multiaddr))}addObservedAddr(e){var t=e.stringTuples(),r="".concat(t[0][1],":").concat(t[1][1]);this.observedAddressFilter.has(r)||(this.observedAddressFilter.add(r),e=xF(e,this.components.peerId),this.ipMappings.has(e)||this.dnsMappings.has(e)||this.observed.add(e))}confirmObservedAddr(e,t){e=xF(e,this.components.peerId);var r,n,i,o,a,s=!0;("transport"===(null==t?void 0:t.type)||this.transportAddresses.has(e))&&(!this.transportAddresses.confirm(e,null!==(r=null==t?void 0:t.ttl)&&void 0!==r?r:this.addressVerificationTTL)&&s&&(s=!1));("dns-mapping"===(null==t?void 0:t.type)||this.dnsMappings.has(e))&&(!this.dnsMappings.confirm(e,null!==(n=null==t?void 0:t.ttl)&&void 0!==n?n:this.addressVerificationTTL)&&s&&(s=!1));("ip-mapping"===(null==t?void 0:t.type)||this.ipMappings.has(e))&&(!this.ipMappings.confirm(e,null!==(i=null==t?void 0:t.ttl)&&void 0!==i?i:this.addressVerificationTTL)&&s&&(s=!1));("observed"===(null==t?void 0:t.type)||this.observed.has(e))&&(this.maybeUpgradeToIPMapping(e)?(this.ipMappings.confirm(e,null!==(o=null==t?void 0:t.ttl)&&void 0!==o?o:this.addressVerificationTTL),s=!1):!this.observed.confirm(e,null!==(a=null==t?void 0:t.ttl)&&void 0!==a?a:this.addressVerificationTTL)&&s&&(s=!1));s||this._updatePeerStoreAddresses()}removeObservedAddr(e,t){var r,n,i;(e=xF(e,this.components.peerId),this.observed.has(e)&&this.observed.remove(e),this.transportAddresses.has(e))&&this.transportAddresses.unconfirm(e,null!==(r=null==t?void 0:t.ttl)&&void 0!==r?r:this.addressVerificationRetry);this.dnsMappings.has(e)&&this.dnsMappings.unconfirm(e,null!==(n=null==t?void 0:t.ttl)&&void 0!==n?n:this.addressVerificationRetry);this.ipMappings.has(e)&&this.ipMappings.unconfirm(e,null!==(i=null==t?void 0:t.ttl)&&void 0!==i?i:this.addressVerificationRetry)}getAddresses(){var e=new Set,t=this.getAddressesWithMetadata().filter((t=>{if(!t.verified)return!1;var r=t.multiaddr.toString();return!e.has(r)&&(e.add(r),!0)})).map((e=>e.multiaddr));return this.announceFilter(t.map((e=>{var t,r=sr(e);return!0===(null===(t=r.protos().pop())||void 0===t?void 0:t.path)||r.getPeerId()===this.components.peerId.toString()?r:r.encapsulate("/p2p/".concat(this.components.peerId.toString()))})))}getAddressesWithMetadata(){var e=this.getAnnounceAddrs();if(e.length>0)return this.components.transportManager.getListeners().forEach((t=>{t.updateAnnounceAddrs(e)})),e.map((e=>({multiaddr:e,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()})));var t=[];t=t.concat(this.components.transportManager.getAddrs().map((e=>this.transportAddresses.get(e,this.addressVerificationTTL))));var r=this.getAppendAnnounceAddrs();return r.length>0&&(this.components.transportManager.getListeners().forEach((e=>{e.updateAnnounceAddrs(r)})),t=t.concat(r.map((e=>({multiaddr:e,verified:!0,type:"announce",expires:Date.now()+this.addressVerificationTTL,lastVerified:Date.now()}))))),t=(t=(t=t.concat(this.observed.getAll())).concat(this.ipMappings.getAll(t))).concat(this.dnsMappings.getAll(t))}addDNSMapping(e,t){this.dnsMappings.add(e,t)}removeDNSMapping(e){this.dnsMappings.remove(sr("/dns/".concat(e)))&&this._updatePeerStoreAddresses()}addPublicAddressMapping(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:t,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"tcp";this.ipMappings.add(e,t,r,n,i),this.observed.removePrefixed("/ip".concat(xt(r)?4:6,"/").concat(r,"/").concat(i,"/").concat(n))}removePublicAddressMapping(e,t,r){var n=arguments.length>3&&void 0!==arguments[3]?arguments[3]:t,i=arguments.length>4&&void 0!==arguments[4]?arguments[4]:"tcp";this.ipMappings.remove(sr("/ip".concat(xt(r)?4:6,"/").concat(r,"/").concat(i,"/").concat(n)))&&this._updatePeerStoreAddresses()}maybeUpgradeToIPMapping(e){var t=this;if(this.ipMappings.has(e))return!1;var r=e.toOptions();if(6===r.family||"127.0.0.1"===r.host||!0===CN(r.host))return!1;var n,i=this.components.transportManager.getListeners(),o=[e=>jd.exactMatch(e)||Ud.exactMatch(e),e=>Nd.exactMatch(e),e=>Od.exactMatch(e)],a=function(n){if(!n(e))return 0;var o=i.filter((e=>e.getAddrs().filter((e=>4===e.toOptions().family&&n(e))).length>0));if(1!==o.length)return 0;var a=o[0].getAddrs().filter((e=>"127.0.0.1"!==e.toOptions().host)).pop();if(null==a)return 0;var s=a.toOptions();return t.observed.remove(e),t.ipMappings.add(s.host,s.port,r.host,r.port,r.transport),{v:!0}};for(var s of o)if(0!==(n=a(s))&&n)return n.v;return!1}}!function(e){e.NOT_STARTED_YET="The libp2p node is not started yet",e.NOT_FOUND="Not found"}(EF||(EF={}));class IF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Missing service"),this.name="MissingServiceError"}}class CF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unmet service dependencies"),this.name="UnmetServiceDependenciesError"}}class BF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No content routers available"),this.name="NoContentRoutersError"}}class NF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No peer routers available"),this.name="NoPeerRoutersError"}}class DF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Should not try to find self"),this.name="QueriedForSelfError"}}class GF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Unhandled protocol error"),this.name="UnhandledProtocolError"}}class RF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Duplicate protocol handler error"),this.name="DuplicateProtocolHandlerError"}}class OF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Dial denied error"),this.name="DialDeniedError"}}class LF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No transport was configured to listen on this address"),this.name="UnsupportedListenAddressError"}}class MF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Configured listen addresses could not be listened on"),this.name="UnsupportedListenAddressesError"}}class jF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No valid addresses"),this.name="NoValidAddressesError"}}class FF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Connection intercepted"),this.name="ConnectionInterceptedError"}}class UF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Connection denied"),this.name="ConnectionDeniedError"}}class zF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Stream is not multiplexed"),this.name="MuxerUnavailableError"}}class VF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Encryption failed"),this.name="EncryptionFailedError"}}class qF extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Transport unavailable"),this.name="TransportUnavailableError"}}class HF{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};for(var[r,n]of(e._defineProperty(this,"components",{}),e._defineProperty(this,"_started",!1),this.components={},Object.entries(t)))this.components[r]=n;null==this.components.logger&&(this.components.logger=Iu())}isStarted(){return this._started}_invokeStartableMethod(t){var r=this;return e._asyncToGenerator((function*(){yield Promise.all(Object.values(r.components).filter((e=>Ca(e))).map(function(){var r=e._asyncToGenerator((function*(e){var r;yield null===(r=e[t])||void 0===r?void 0:r.call(e)}));return function(e){return r.apply(this,arguments)}}()))}))()}beforeStart(){var t=this;return e._asyncToGenerator((function*(){yield t._invokeStartableMethod("beforeStart")}))()}start(){var t=this;return e._asyncToGenerator((function*(){yield t._invokeStartableMethod("start"),t._started=!0}))()}afterStart(){var t=this;return e._asyncToGenerator((function*(){yield t._invokeStartableMethod("afterStart")}))()}beforeStop(){var t=this;return e._asyncToGenerator((function*(){yield t._invokeStartableMethod("beforeStop")}))()}stop(){var t=this;return e._asyncToGenerator((function*(){yield t._invokeStartableMethod("stop"),t._started=!1}))()}afterStop(){var t=this;return e._asyncToGenerator((function*(){yield t._invokeStartableMethod("afterStop")}))()}}var KF=["metrics","connectionProtector","dns"],WF=["components","isStarted","beforeStart","start","afterStart","beforeStop","stop","afterStop","then","_invokeStartableMethod"];function QF(e){return Array.isArray(null==e?void 0:e[Ra])?e[Ra]:[]}function YF(e){return Array.isArray(null==e?void 0:e[Oa])?e[Oa]:[]}function JF(e){var t,r;return null!==(t=null!==(r=null==e?void 0:e[Symbol.toStringTag])&&void 0!==r?r:null==e?void 0:e.toString())&&void 0!==t?t:"unknown"}function ZF(){var t,r,n,i,o,a,s,l,c,u=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return e._objectSpread2({denyDialPeer:(c=e._asyncToGenerator((function*(){return!1})),function(){return c.apply(this,arguments)}),denyDialMultiaddr:(l=e._asyncToGenerator((function*(e){if(jd.matches(e))return!1;var t=e.stringTuples();return(4===t[0][0]||41===t[0][0])&&Boolean(CN("".concat(t[0][1])))})),function(e){return l.apply(this,arguments)}),denyInboundConnection:(s=e._asyncToGenerator((function*(){return!1})),function(){return s.apply(this,arguments)}),denyOutboundConnection:(a=e._asyncToGenerator((function*(){return!1})),function(){return a.apply(this,arguments)}),denyInboundEncryptedConnection:(o=e._asyncToGenerator((function*(){return!1})),function(){return o.apply(this,arguments)}),denyOutboundEncryptedConnection:(i=e._asyncToGenerator((function*(){return!1})),function(){return i.apply(this,arguments)}),denyInboundUpgradedConnection:(n=e._asyncToGenerator((function*(){return!1})),function(){return n.apply(this,arguments)}),denyOutboundUpgradedConnection:(r=e._asyncToGenerator((function*(){return!1})),function(){return r.apply(this,arguments)}),filterMultiaddrForPeer:(t=e._asyncToGenerator((function*(){return!0})),function(){return t.apply(this,arguments)})},u)}function $F(e){if(Ko(e))return{peerId:e,multiaddrs:[]};var t,r=Array.isArray(e)?e:[e];if(r.length>0){var n=r[0].getPeerId();t=null==n?void 0:rc(n),r.forEach((e=>{if(!ar(e))throw new ha("Invalid multiaddr");var r=e.getPeerId();if(null==r){if(null!=t)throw new ea("Multiaddrs must all have the same peer id or have no peer id")}else{var n,i=rc(r);if(!0!==(null===(n=t)||void 0===n?void 0:n.equals(i)))throw new ea("Multiaddrs must all have the same peer id or have no peer id")}}))}return r=r.filter((e=>!yd.exactMatch(e))),{peerId:t,multiaddrs:r}}var XF=["/ipfs/id/1.0.0","/ipfs/id/push/1.0.0","/libp2p/autonat/1.0.0","/libp2p/dcutr"];function eU(){return eU=e._asyncToGenerator((function*(e,t){var r,n,i,o=null!==(r=null==e||null===(n=e.streams)||void 0===n?void 0:n.map((e=>e.protocol)))&&void 0!==r?r:[],a=null!==(i=null==t?void 0:t.closableProtocols)&&void 0!==i?i:XF;if(!(o.filter((e=>null!=e&&!a.includes(e))).length>0))try{yield null==e?void 0:e.close(t)}catch(t){null==e||e.abort(t)}})),eU.apply(this,arguments)}var tU="last-dial-failure",rU="last-dial-success";function nU(){return nU=e._asyncToGenerator((function*(e,t){var r=!1;for(var n of or.keys())if(r=e.protoNames().includes(n))break;if(!r)return[e];var i=yield e.resolve(t);return t.log("resolved %s to",e,i.map((e=>e.toString()))),i})),nU.apply(this,arguments)}function iU(e){try{var t;if(!(t="string"==typeof e?sr(e):e).protoNames().includes("ipcidr")){var r=t.protoNames().includes("ip6")?"/ipcidr/128":"/ipcidr/32";t=t.encapsulate(r)}return function(e){var t,r;if(e.getComponents().forEach((e=>{"ip4"!==e.name&&"ip6"!==e.name||(r=e.value),"ipcidr"===e.name&&(t=e.value)})),null==t||null==r)throw new Error("Invalid multiaddr");return new ir(r,t)}(t)}catch(t){throw new Error("Can't convert to IpNet, Invalid multiaddr format: ".concat(e))}}var oU=100;class aU{constructor(t){var r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"maxConnections",void 0),e._defineProperty(this,"connectionManager",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"allow",void 0),e._defineProperty(this,"events",void 0),e._defineProperty(this,"log",void 0),this.maxConnections=null!==(r=i.maxConnections)&&void 0!==r?r:oU,this.allow=(null!==(n=i.allow)&&void 0!==n?n:[]).map((e=>iU(e))),this.connectionManager=t.connectionManager,this.peerStore=t.peerStore,this.events=t.events,this.log=t.logger.forComponent("libp2p:connection-manager:connection-pruner"),this.maybePruneConnections=this.maybePruneConnections.bind(this)}start(){this.events.addEventListener("connection:open",this.maybePruneConnections)}stop(){this.events.removeEventListener("connection:open",this.maybePruneConnections)}maybePruneConnections(){this._maybePruneConnections().catch((e=>{this.log.error("error while pruning connections %e",e)}))}_maybePruneConnections(){var t=this;return e._asyncToGenerator((function*(){var r=t.connectionManager.getConnections(),n=r.length;if(t.log("checking max connections limit %d/%d",n,t.maxConnections),!(n<=t.maxConnections)){var i=new lh;for(var o of r){var a=o.remotePeer;if(!i.has(a)){i.set(a,0);try{var s=yield t.peerStore.get(a);i.set(a,[...s.tags.values()].reduce(((e,t)=>e+t.value),0))}catch(e){"NotFoundError"!==e.name&&t.log.error("error loading peer tags",e)}}}var l=t.sortConnections(r,i),c=Math.max(n-t.maxConnections,0),u=[],d=function*(e){if(t.log("too many connections open - closing a connection to %p",e.remotePeer),t.allow.some((t=>t.contains(e.remoteAddr.nodeAddress().address)))||u.push(e),u.length===c)return 1};for(var h of l)if(yield*d(h))break;yield Promise.all(u.map(function(){var t=e._asyncToGenerator((function*(e){yield function(e,t){return eU.apply(this,arguments)}(e,{signal:AbortSignal.timeout(1e3)})}));return function(e){return t.apply(this,arguments)}}())),t.events.safeDispatchEvent("connection:prune",{detail:u})}}))()}sortConnections(e,t){return e.sort(((e,t)=>{var r=e.timeline.open,n=t.timeline.open;return r<n?1:r>n?-1:0})).sort(((e,t)=>"outbound"===e.direction&&"inbound"===t.direction?1:"inbound"===e.direction&&"outbound"===t.direction?-1:0)).sort(((e,t)=>e.streams.length>t.streams.length?1:e.streams.length<t.streams.length?-1:0)).sort(((e,r)=>{var n,i,o=null!==(n=t.get(e.remotePeer))&&void 0!==n?n:0,a=null!==(i=t.get(r.remotePeer))&&void 0!==i?i:0;return o>a?1:o<a?-1:0}))}}class sU extends Mh{constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};super(e._objectSpread2(e._objectSpread2({},t),{},{sort:(e,t)=>e.options.priority>t.options.priority?-1:e.options.priority<t.options.priority?1:0}))}}function lU(e){if(!qG(e))return!1;var t,{address:r}=e.nodeAddress();return/^127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(t=r)||/^::1$/.test(t)}function cU(e,t){var r=Nd.exactMatch(e.multiaddr),n=Nd.exactMatch(t.multiaddr);if(r&&!n)return-1;if(!r&&n)return 1;var i=Ud.exactMatch(e.multiaddr),o=Ud.exactMatch(t.multiaddr);if(i&&!o)return-1;if(!i&&o)return 1;var a=jd.exactMatch(e.multiaddr),s=jd.exactMatch(t.multiaddr);if(a&&!s)return-1;if(!a&&s)return 1;var l=Yd.exactMatch(e.multiaddr),c=Yd.exactMatch(t.multiaddr);if(l&&!c)return-1;if(!l&&c)return 1;var u=Vd.exactMatch(e.multiaddr),d=Vd.exactMatch(t.multiaddr);if(u&&!d)return-1;if(!u&&d)return 1;var h=Hd.exactMatch(e.multiaddr),p=Hd.exactMatch(t.multiaddr);return h&&!p?-1:!h&&p?1:0}function uU(e,t){var r=lU(e.multiaddr),n=lU(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function dU(e,t){var r=HG(e.multiaddr),n=HG(t.multiaddr);return r&&!n?1:!r&&n?-1:0}function hU(e,t){return e.isCertified&&!t.isCertified?-1:!e.isCertified&&t.isCertified?1:0}function pU(e,t){var r=Qd.exactMatch(e.multiaddr),n=Qd.exactMatch(t.multiaddr);return r&&!n?1:!r&&n?-1:0}var fU=50,vU=500,yU=25,gU=1e4;class mU{constructor(t){var r,n,i,o,a,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};for(var[l,c]of(e._defineProperty(this,"queue",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"addressSorter",void 0),e._defineProperty(this,"maxPeerAddrsToDial",void 0),e._defineProperty(this,"maxDialQueueLength",void 0),e._defineProperty(this,"dialTimeout",void 0),e._defineProperty(this,"shutDownController",void 0),e._defineProperty(this,"connections",void 0),e._defineProperty(this,"log",void 0),this.addressSorter=s.addressSorter,this.maxPeerAddrsToDial=null!==(r=s.maxPeerAddrsToDial)&&void 0!==r?r:yU,this.maxDialQueueLength=null!==(n=s.maxDialQueueLength)&&void 0!==n?n:vU,this.dialTimeout=null!==(i=s.dialTimeout)&&void 0!==i?i:gU,this.connections=null!==(o=s.connections)&&void 0!==o?o:new lh,this.log=t.logger.forComponent("libp2p:connection-manager:dial-queue"),this.components=t,this.shutDownController=new AbortController,this.shutDownController.signal,Object.entries(null!==(u=s.resolvers)&&void 0!==u?u:{}))){var u;or.set(l,c)}this.queue=new sU({concurrency:null!==(a=s.maxParallelDials)&&void 0!==a?a:fU,metricName:"libp2p_dial_queue",metrics:t.metrics}),this.queue.addEventListener("error",(e=>{var t;(null===(t=e.detail)||void 0===t?void 0:t.name)!==Zo.name&&this.log.error("error in dial queue - %e",e.detail)}))}start(){this.shutDownController=new AbortController,this.shutDownController.signal}stop(){this.shutDownController.abort(),this.queue.abort()}dial(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i,o,a,s,l=r.length>1&&void 0!==r[1]?r[1]:{},{peerId:c,multiaddrs:u}=$F(t),d=Array.from(n.connections.values()).flat().find((e=>!0!==l.force&&(!!e.remotePeer.equals(c)||u.find((t=>t.equals(e.remoteAddr))))));if("open"===(null==d?void 0:d.status))return n.log("already connected to %a",d.remoteAddr),null===(s=l.onProgress)||void 0===s||s.call(l,new Ih("dial-queue:already-connected")),d;var h=n.queue.queue.find((e=>{if(!0===(null==c?void 0:c.equals(e.options.peerId)))return!0;var t=e.options.multiaddrs;if(null==t)return!1;for(var r of u)if(t.has(r.toString()))return!0;return!1}));if(null!=h){var p;for(var f of(n.log("joining existing dial target for %p",c),u))h.options.multiaddrs.add(f.toString());return null===(p=l.onProgress)||void 0===p||p.call(l,new Ih("dial-queue:already-in-dial-queue")),h.join(l)}if(n.queue.size>=n.maxDialQueueLength)throw new _a("Dial queue is full");return n.log("creating dial target for %p",c,u.map((e=>e.toString()))),null===(i=l.onProgress)||void 0===i||i.call(l,new Ih("dial-queue:add-to-dial-queue")),n.queue.add(function(){var t=e._asyncToGenerator((function*(e){var t;null===(t=e.onProgress)||void 0===t||t.call(e,new Ih("dial-queue:start-dial"));var r=$d([n.shutDownController.signal,e.signal]);try{return yield n.dialPeer(e,r)}finally{r.clear()}}));return function(e){return t.apply(this,arguments)}}(),{peerId:c,priority:null!==(o=l.priority)&&void 0!==o?o:OU,multiaddrs:new Set(u.map((e=>e.toString()))),signal:null!==(a=l.signal)&&void 0!==a?a:AbortSignal.timeout(n.dialTimeout),onProgress:l.onProgress})}))()}dialPeer(t,r){var n=this;return e._asyncToGenerator((function*(){var i=t.peerId,o=t.multiaddrs,a=new Set,s=0===t.multiaddrs.size,l=0,c=0,u=[];for(n.log("starting dial to %p",i);s||o.size>0;){var d;c++,s=!1;var h=[],p=new Set(t.multiaddrs);o.clear(),n.log("calculating addrs to dial %p from %s",i,[...p]);var f=yield n.calculateMultiaddrs(i,p,e._objectSpread2(e._objectSpread2({},t),{},{signal:r}));for(var v of f)a.has(v.multiaddr.toString())?n.log.trace("skipping previously failed multiaddr %a while dialing %p",v.multiaddr,i):h.push(v);for(var y of(n.log("%s dial to %p with %s",1===c?"starting":"continuing",i,h.map((e=>e.multiaddr.toString()))),null==t||null===(d=t.onProgress)||void 0===d||d.call(t,new Ih("dial-queue:calculated-addresses",h)),h)){if(l===n.maxPeerAddrsToDial)throw n.log("dialed maxPeerAddrsToDial (%d) addresses for %p, not trying any others",l,t.peerId),new _a("Peer had more than maxPeerAddrsToDial");l++;try{var g=yield n.components.transportManager.dial(y.multiaddr,e._objectSpread2(e._objectSpread2({},t),{},{signal:r}));n.log("dial to %a succeeded",y.multiaddr);try{yield n.components.peerStore.merge(g.remotePeer,{multiaddrs:[g.remoteAddr],metadata:{[rU]:ot(Date.now().toString())}})}catch(e){n.log.error("could not update last dial failure key for %p",i,e)}return g}catch(e){if(n.log.error("dial failed to %a",y.multiaddr,e),a.add(y.multiaddr.toString()),null!=i)try{yield n.components.peerStore.merge(i,{metadata:{[tU]:ot(Date.now().toString())}})}catch(e){n.log.error("could not update last dial failure key for %p",i,e)}if(r.aborted)throw new ma(e.message);u.push(e)}}}if(1===u.length)throw u[0];throw new AggregateError(u,"All multiaddr dials failed")}))()}calculateMultiaddrs(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i=r.length>1&&void 0!==r[1]?r[1]:new Set,o=r.length>2&&void 0!==r[2]?r[2]:{},a=[...i].map((e=>({multiaddr:sr(e),isCertified:!1})));if(null!=t){var s,l;if(n.components.peerId.equals(t))throw new _a("Tried to dial self");if(!0===(yield null===(s=(l=n.components.connectionGater).denyDialPeer)||void 0===s?void 0:s.call(l,t)))throw new OF("The dial request is blocked by gater.allowDialPeer");if(0===a.length){n.log("loading multiaddrs for %p",t);try{var c=yield n.components.peerStore.get(t);a.push(...c.addresses),n.log("loaded multiaddrs for %p",t,a.map((e=>{var{multiaddr:t}=e;return t.toString()})))}catch(e){if("NotFoundError"!==e.name)throw e}}if(0===a.length){n.log("looking up multiaddrs for %p in the peer routing",t);try{var u=yield n.components.peerRouting.findPeer(t,o);n.log("found multiaddrs for %p in the peer routing",t,a.map((e=>{var{multiaddr:t}=e;return t.toString()}))),a.push(...u.multiaddrs.map((e=>({multiaddr:e,isCertified:!1}))))}catch(e){"NoPeerRoutersError"===e.name?n.log("no peer routers configured",t):n.log.error("looking up multiaddrs for %p in the peer routing failed - %e",t,e)}}}var d=(yield Promise.all(a.map(function(){var t=e._asyncToGenerator((function*(t){var r=yield function(e,t){return nU.apply(this,arguments)}(t.multiaddr,e._objectSpread2(e._objectSpread2({dns:n.components.dns},o),{},{log:n.log}));return 1===r.length&&r[0].equals(t.multiaddr)?t:r.map((e=>({multiaddr:e,isCertified:!1})))}));return function(e){return t.apply(this,arguments)}}()))).flat();if(null!=t){var h="/p2p/".concat(t.toString());d=d.map((e=>{var t=e.multiaddr.protos().pop();return!0===(null==t?void 0:t.path)?e:null==e.multiaddr.getPeerId()?{multiaddr:e.multiaddr.encapsulate(h),isCertified:e.isCertified}:e}))}var p=d.filter((e=>{if(null==n.components.transportManager.dialTransportForMultiaddr(e.multiaddr))return!1;var r=e.multiaddr.getPeerId();return null==t||null==r||t.equals(r)})),f=new Map;for(var v of p){var y=v.multiaddr.toString(),g=f.get(y);null==g?f.set(y,v):g.isCertified=g.isCertified||v.isCertified||!1}var m=[...f.values()];if(0===m.length)throw new jF("The dial request has no valid addresses");var w=[];for(var b of m)null!=n.components.connectionGater.denyDialMultiaddr&&(yield n.components.connectionGater.denyDialMultiaddr(b.multiaddr))||w.push(b);var _=null==n.addressSorter?w.sort(cU).sort(hU).sort(pU).sort(dU).sort(uU):w.sort(n.addressSorter);if(0===_.length)throw new OF("The connection gater denied all addresses in the dial request");return n.log.trace("addresses for %p before filtering",null!=t?t:"unknown peer",d.map((e=>{var{multiaddr:t}=e;return t.toString()}))),n.log.trace("addresses for %p after filtering",null!=t?t:"unknown peer",_.map((e=>{var{multiaddr:t}=e;return t.toString()}))),_}))()}isDialable(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};Array.isArray(t)||(t=[t]);try{var i=yield n.calculateMultiaddrs(void 0,new Set(t.map((e=>e.toString()))),e);return!1!==e.runOnLimitedConnection||null!=i.find((e=>!Qd.matches(e.multiaddr)))}catch(e){n.log.trace("error calculating if multiaddr(s) were dialable",e)}return!1}))()}}var wU,bU,_U,SU,PU,EU={};function AU(){return _U||(_U=1,function(e){var t=function(){if(bU)return wU;function e(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}return bU=1,wU=e,e.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},e.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},e.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(void 0===r){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1)}var n=this;return this._timer=setTimeout((function(){n._attempts++,n._operationTimeoutCb&&(n._timeout=setTimeout((function(){n._operationTimeoutCb(n._attempts)}),n._operationTimeout),n._options.unref&&n._timeout.unref()),n._fn(n._attempts)}),r),this._options.unref&&this._timer.unref(),!0},e.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout((function(){r._operationTimeoutCb()}),r._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},e.prototype.try=function(e){this.attempt(e)},e.prototype.start=function(e){this.attempt(e)},e.prototype.start=e.prototype.try,e.prototype.errors=function(){return this._errors},e.prototype.attempts=function(){return this._attempts},e.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,r=0,n=0;n<this._errors.length;n++){var i=this._errors[n],o=i.message,a=(e[o]||0)+1;e[o]=a,a>=r&&(t=i,r=a)}return t},wU}();e.operation=function(r){var n=e.timeouts(r);return new t(n,{forever:r&&(r.forever||r.retries===1/0),unref:r&&r.unref,maxRetryTime:r&&r.maxRetryTime})},e.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var r in e)t[r]=e[r];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var n=[],i=0;i<t.retries;i++)n.push(this.createTimeout(i,t));return e&&e.forever&&!n.length&&n.push(this.createTimeout(i,t)),n.sort((function(e,t){return e-t})),n},e.createTimeout=function(e,t){var r=t.randomize?Math.random()+1:1,n=Math.round(r*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return n=Math.min(n,t.maxTimeout)},e.wrap=function(t,r,n){if(r instanceof Array&&(n=r,r=null),!n)for(var i in n=[],t)"function"==typeof t[i]&&n.push(i);for(var o=0;o<n.length;o++){var a=n[o],s=t[a];t[a]=function(n){var i=e.operation(r),o=Array.prototype.slice.call(arguments,1),a=o.pop();o.push((function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),a.apply(this,arguments))})),i.attempt((function(){n.apply(t,o)}))}.bind(t,s),t[a].options=r}}}(EU)),EU}var kU=PU?SU:(PU=1,SU=AU()),xU=e.getDefaultExportFromCjs(kU),TU=Object.prototype.toString,IU=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Load failed","Network request failed","fetch failed","terminated"]);function CU(e){var t;return!(!e||(t=e,"[object Error]"!==TU.call(t))||"TypeError"!==e.name||"string"!=typeof e.message)&&("Load failed"===e.message?void 0===e.stack:IU.has(e.message))}class BU extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}var NU=(e,t,r)=>{var n=r.retries-(t-1);return e.attemptNumber=t,e.retriesLeft=n,e};function DU(){return DU=e._asyncToGenerator((function*(t,r){return new Promise(((n,i)=>{var o,a,s,l,c,u;null!==(a=(o=r=e._objectSpread2({},r)).onFailedAttempt)&&void 0!==a||(o.onFailedAttempt=()=>{}),null!==(l=(s=r).shouldRetry)&&void 0!==l||(s.shouldRetry=()=>!0),null!==(u=(c=r).retries)&&void 0!==u||(c.retries=10);var d=xU.operation(r),h=()=>{var e;d.stop(),i(null===(e=r.signal)||void 0===e?void 0:e.reason)};r.signal&&!r.signal.aborted&&r.signal.addEventListener("abort",h,{once:!0});var p=()=>{var e;null===(e=r.signal)||void 0===e||e.removeEventListener("abort",h),d.stop()};d.attempt(function(){var o=e._asyncToGenerator((function*(e){try{var o=yield t(e);p(),n(o)}catch(t){try{if(!(t instanceof Error))throw new TypeError('Non-error was thrown: "'.concat(t,'". You should only throw errors.'));if(t instanceof BU)throw t.originalError;if(t instanceof TypeError&&!CU(t))throw t;if(NU(t,e,r),(yield r.shouldRetry(t))||(d.stop(),i(t)),yield r.onFailedAttempt(t),!d.retry(t))throw d.mainError()}catch(t){NU(t,e,r),p(),i(t)}}}));return function(e){return o.apply(this,arguments)}}())}))})),DU.apply(this,arguments)}class GU{constructor(t){var r,n,i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"log",void 0),e._defineProperty(this,"queue",void 0),e._defineProperty(this,"started",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"retries",void 0),e._defineProperty(this,"retryInterval",void 0),e._defineProperty(this,"backoffFactor",void 0),e._defineProperty(this,"connectionManager",void 0),e._defineProperty(this,"events",void 0),this.log=t.logger.forComponent("libp2p:reconnect-queue"),this.peerStore=t.peerStore,this.connectionManager=t.connectionManager,this.queue=new jh({concurrency:null!==(r=i.maxParallelReconnects)&&void 0!==r?r:5,metricName:"libp2p_reconnect_queue",metrics:t.metrics}),this.started=!1,this.retries=null!==(n=i.retries)&&void 0!==n?n:5,this.backoffFactor=i.backoffFactor,this.retryInterval=i.retryInterval,this.events=t.events,t.events.addEventListener("peer:disconnect",(e=>{this.maybeReconnect(e.detail).catch((t=>{this.log.error("failed to maybe reconnect to %p - %e",e.detail,t)}))}))}maybeReconnect(t){var r=this;return e._asyncToGenerator((function*(){if(r.started){var n=yield r.peerStore.get(t);RU(n)&&(r.queue.has(t)||r.queue.add(function(){var n=e._asyncToGenerator((function*(n){yield function(e,t){return DU.apply(this,arguments)}(function(){var i=e._asyncToGenerator((function*(e){if(r.started)try{yield r.connectionManager.openConnection(t,{signal:null==n?void 0:n.signal})}catch(n){throw r.log("reconnecting to %p attempt %d of %d failed - %e",t,e,r.retries,n),n}}));return function(e){return i.apply(this,arguments)}}(),{signal:null==n?void 0:n.signal,retries:r.retries,factor:r.backoffFactor,minTimeout:r.retryInterval})}));return function(e){return n.apply(this,arguments)}}(),{peerId:t}).catch(function(){var i=e._asyncToGenerator((function*(e){r.log.error("failed to reconnect to %p - %e",t,e);var i={};[...n.tags.keys()].forEach((e=>{e.startsWith(Yo)&&(i[e]=void 0)})),yield r.peerStore.merge(t,{tags:i}),r.events.safeDispatchEvent("peer:reconnect-failure",{detail:t})}));return function(e){return i.apply(this,arguments)}}()).catch(function(){var n=e._asyncToGenerator((function*(e){r.log.error("failed to remove keep-alive tag from %p - %e",t,e)}));return function(e){return n.apply(this,arguments)}}()))}}))()}start(){this.started=!0}afterStart(){var t=this;return e._asyncToGenerator((function*(){Promise.resolve().then(e._asyncToGenerator((function*(){var r=yield t.peerStore.all({filters:[e=>RU(e)]});yield Promise.all(r.map(function(){var r=e._asyncToGenerator((function*(e){yield t.connectionManager.openConnection(e.id).catch((e=>{t.log.error(e)}))}));return function(e){return r.apply(this,arguments)}}()))}))).catch((e=>{t.log.error(e)}))}))()}stop(){this.started=!1,this.queue.abort()}}function RU(e){for(var t of e.tags.keys())if(t.startsWith(Yo))return!0;return!1}var OU=50,LU=100,MU=5,jU=10;class FU{constructor(t){var r,n,i,o,a,s,l,c,u,d,h,p=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(e._defineProperty(this,"started",void 0),e._defineProperty(this,"connections",void 0),e._defineProperty(this,"allow",void 0),e._defineProperty(this,"deny",void 0),e._defineProperty(this,"maxIncomingPendingConnections",void 0),e._defineProperty(this,"incomingPendingConnections",void 0),e._defineProperty(this,"outboundPendingConnections",void 0),e._defineProperty(this,"maxConnections",void 0),e._defineProperty(this,"dialQueue",void 0),e._defineProperty(this,"reconnectQueue",void 0),e._defineProperty(this,"connectionPruner",void 0),e._defineProperty(this,"inboundConnectionRateLimiter",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"metrics",void 0),e._defineProperty(this,"events",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"peerId",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/connection-manager"),this.maxConnections=null!==(r=p.maxConnections)&&void 0!==r?r:LU,this.maxConnections<1)throw new ea("Connection Manager maxConnections must be greater than 0");this.connections=new lh,this.started=!1,this.peerId=t.peerId,this.peerStore=t.peerStore,this.metrics=t.metrics,this.events=t.events,this.log=t.logger.forComponent("libp2p:connection-manager"),this.onConnect=this.onConnect.bind(this),this.onDisconnect=this.onDisconnect.bind(this),this.allow=(null!==(n=p.allow)&&void 0!==n?n:[]).map((e=>iU(e))),this.deny=(null!==(i=p.deny)&&void 0!==i?i:[]).map((e=>iU(e))),this.incomingPendingConnections=0,this.maxIncomingPendingConnections=null!==(o=p.maxIncomingPendingConnections)&&void 0!==o?o:jU,this.outboundPendingConnections=0,this.inboundConnectionRateLimiter=new FM({points:null!==(a=p.inboundConnectionThreshold)&&void 0!==a?a:MU,duration:1}),this.connectionPruner=new aU({connectionManager:this,peerStore:t.peerStore,events:t.events,logger:t.logger},{maxConnections:this.maxConnections,allow:null===(s=p.allow)||void 0===s?void 0:s.map((e=>sr(e)))}),this.dialQueue=new mU(t,{addressSorter:p.addressSorter,maxParallelDials:null!==(l=p.maxParallelDials)&&void 0!==l?l:50,maxDialQueueLength:null!==(c=p.maxDialQueueLength)&&void 0!==c?c:500,maxPeerAddrsToDial:null!==(u=p.maxPeerAddrsToDial)&&void 0!==u?u:25,dialTimeout:null!==(d=p.dialTimeout)&&void 0!==d?d:1e4,resolvers:null!==(h=p.resolvers)&&void 0!==h?h:{dnsaddr:Gj},connections:this.connections}),this.reconnectQueue=new GU({events:t.events,peerStore:t.peerStore,logger:t.logger,connectionManager:this},{retries:p.reconnectRetries,retryInterval:p.reconnectRetryInterval,backoffFactor:p.reconnectBackoffFactor,maxParallelReconnects:p.maxParallelReconnects})}start(){var t=this;return e._asyncToGenerator((function*(){var e,r,n;null===(e=t.metrics)||void 0===e||e.registerMetricGroup("libp2p_connection_manager_connections",{calculate:()=>{var e={inbound:0,"inbound pending":t.incomingPendingConnections,outbound:0,"outbound pending":t.outboundPendingConnections};for(var r of t.connections.values())for(var n of r)e[n.direction]++;return e}}),null===(r=t.metrics)||void 0===r||r.registerMetricGroup("libp2p_protocol_streams_total",{label:"protocol",calculate:()=>{var e={};for(var r of t.connections.values())for(var n of r)for(var i of n.streams){var o,a,s="".concat(i.direction," ").concat(null!==(o=i.protocol)&&void 0!==o?o:"unnegotiated");e[s]=(null!==(a=e[s])&&void 0!==a?a:0)+1}return e}}),null===(n=t.metrics)||void 0===n||n.registerMetricGroup("libp2p_connection_manager_protocol_streams_per_connection_90th_percentile",{label:"protocol",calculate:()=>{var e={};for(var r of t.connections.values())for(var n of r){var i={};for(var o of n.streams){var a,s,l="".concat(o.direction," ").concat(null!==(a=o.protocol)&&void 0!==a?a:"unnegotiated");i[l]=(null!==(s=i[l])&&void 0!==s?s:0)+1}for(var[c,u]of Object.entries(i)){var d;e[c]=null!==(d=e[c])&&void 0!==d?d:[],e[c].push(u)}}var h={};for(var[p,f]of Object.entries(e)){f=f.sort(((e,t)=>e-t));var v=Math.floor(.9*f.length);h[p]=f[v]}return h}}),t.events.addEventListener("connection:open",t.onConnect),t.events.addEventListener("connection:close",t.onDisconnect),yield Ba(t.dialQueue,t.reconnectQueue,t.connectionPruner),t.started=!0,t.log("started")}))()}stop(){var t=this;return e._asyncToGenerator((function*(){t.events.removeEventListener("connection:open",t.onConnect),t.events.removeEventListener("connection:close",t.onDisconnect),yield Da(t.reconnectQueue,t.dialQueue,t.connectionPruner);var r=[];for(var n of t.connections.values()){var i=function*(n){r.push(e._asyncToGenerator((function*(){try{yield n.close()}catch(e){t.log.error(e)}}))())};for(var o of n)yield*i(o)}t.log("closing %d connections",r.length),yield Promise.all(r),t.connections.clear(),t.log("stopped")}))()}getMaxConnections(){return this.maxConnections}onConnect(e){this._onConnect(e).catch((e=>{this.log.error(e)}))}_onConnect(t){var r=this;return e._asyncToGenerator((function*(){var e,{detail:n}=t;if(r.started){if("open"===n.status){var i=n.remotePeer,o=!r.connections.has(i),a=null!==(e=r.connections.get(i))&&void 0!==e?e:[];a.push(n),r.connections.set(i,a),null!=i.publicKey&&"RSA"===i.type&&(yield r.peerStore.patch(i,{publicKey:i.publicKey})),o&&r.events.safeDispatchEvent("peer:connect",{detail:n.remotePeer})}}else yield n.close()}))()}onDisconnect(e){var t,{detail:r}=e,n=r.remotePeer,i=(null!==(t=this.connections.get(n))&&void 0!==t?t:[]).filter((e=>e.id!==r.id));this.connections.set(n,i),0===i.length&&(this.log("onDisconnect remove all connections for peer %p",n),this.connections.delete(n),this.events.safeDispatchEvent("peer:disconnect",{detail:r.remotePeer}))}getConnections(e){var t;if(null!=e)return null!==(t=this.connections.get(e))&&void 0!==t?t:[];var r=[];for(var n of this.connections.values())r=r.concat(n);return r}getConnectionsMap(){return this.connections}openConnection(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i=r.length>1&&void 0!==r[1]?r[1]:{};if(!n.started)throw new wa("Not started");n.outboundPendingConnections++;try{var o,a;null===(o=i.signal)||void 0===o||o.throwIfAborted();var{peerId:s}=$F(t);if(n.peerId.equals(s))throw new da("Can not dial self");if(null!=s&&!0!==i.force){n.log("dial %p",s);var l,c=n.getConnections(s).find((e=>null==e.limits));if(null!=c)return n.log("had an existing non-limited connection to %p",s),null===(l=i.onProgress)||void 0===l||l.call(i,new Ih("dial-queue:already-connected")),c}var u=yield n.dialQueue.dial(t,e._objectSpread2(e._objectSpread2({},i),{},{priority:null!==(a=i.priority)&&void 0!==a?a:OU}));if("open"!==u.status)throw new oa("Remote closed connection during opening");var d=n.connections.get(u.remotePeer);null==d&&(d=[],n.connections.set(u.remotePeer,d));var h=!1;for(var p of d)if(p.id===u.id&&(h=!0),!0!==i.force&&p.id!==u.id&&p.remoteAddr.equals(u.remoteAddr))return u.abort(new ha("Duplicate multiaddr connection")),p;return h||d.push(u),u}finally{n.outboundPendingConnections--}}))()}closeConnections(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i,o=r.length>1&&void 0!==r[1]?r[1]:{},a=null!==(i=n.connections.get(t))&&void 0!==i?i:[];yield Promise.all(a.map(function(){var t=e._asyncToGenerator((function*(e){try{yield e.close(o)}catch(t){e.abort(t)}}));return function(e){return t.apply(this,arguments)}}()))}))()}acceptIncomingConnection(t){var r=this;return e._asyncToGenerator((function*(){if(r.deny.some((e=>e.contains(t.remoteAddr.nodeAddress().address))))return r.log("connection from %a refused - connection remote address was in deny list",t.remoteAddr),!1;if(r.allow.some((e=>e.contains(t.remoteAddr.nodeAddress().address))))return r.incomingPendingConnections++,!0;if(r.incomingPendingConnections===r.maxIncomingPendingConnections)return r.log("connection from %a refused - incomingPendingConnections exceeded by host",t.remoteAddr),!1;if(t.remoteAddr.isThinWaistAddress()){var e=t.remoteAddr.nodeAddress().address;try{yield r.inboundConnectionRateLimiter.consume(e,1)}catch(n){return r.log("connection from %a refused - inboundConnectionThreshold exceeded by host %s",t.remoteAddr,e),!1}}return r.getConnections().length<r.maxConnections?(r.incomingPendingConnections++,!0):(r.log("connection from %a refused - maxConnections exceeded",t.remoteAddr),!1)}))()}afterUpgradeInbound(){this.incomingPendingConnections--}getDialQueue(){var e={queued:"queued",running:"active",errored:"error",complete:"success"};return this.dialQueue.queue.queue.map((t=>({id:t.id,status:e[t.status],peerId:t.options.peerId,multiaddrs:[...t.options.multiaddrs].map((e=>sr(e)))})))}isDialable(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};return n.dialQueue.isDialable(t,e)}))()}}class UU{constructor(t){var r,n,i,o,a=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"protocol",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"heartbeatInterval",void 0),e._defineProperty(this,"pingIntervalMs",void 0),e._defineProperty(this,"abortController",void 0),e._defineProperty(this,"timeout",void 0),e._defineProperty(this,"abortConnectionOnPingFailure",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/connection-monitor"),e._defineProperty(this,Ra,["@libp2p/connection-monitor"]),this.components=t,this.protocol="/".concat(null!==(r=a.protocolPrefix)&&void 0!==r?r:"ipfs","/").concat("ping","/").concat("1.0.0"),this.log=t.logger.forComponent("libp2p:connection-monitor"),this.pingIntervalMs=null!==(n=a.pingInterval)&&void 0!==n?n:1e4,this.abortConnectionOnPingFailure=null===(i=a.abortConnectionOnPingFailure)||void 0===i||i,this.timeout=new WO(e._objectSpread2(e._objectSpread2({},null!==(o=a.pingTimeout)&&void 0!==o?o:{}),{},{metrics:t.metrics,metricName:"libp2p_connection_monitor_ping_time_milliseconds"}))}start(){var t=this;this.abortController=new AbortController,this.abortController.signal,this.heartbeatInterval=setInterval((()=>{this.components.connectionManager.getConnections().forEach((r=>{Promise.resolve().then(e._asyncToGenerator((function*(){var e=Date.now();try{var n,i=t.timeout.getTimeoutSignal({signal:null===(n=t.abortController)||void 0===n?void 0:n.signal}),o=zu(yield r.newStream(t.protocol,{signal:i,runOnLimitedConnection:!0}));e=Date.now(),yield Promise.all([o.write(gl(32),{signal:i}),o.read({bytes:32,signal:i})]),r.rtt=Date.now()-e,yield o.unwrap().close({signal:i})}catch(t){if("UnsupportedProtocolError"!==t.name)throw t;r.rtt=(Date.now()-e)/2}}))).catch((e=>{this.log.error("error during heartbeat",e),this.abortConnectionOnPingFailure?(this.log.error("aborting connection due to ping failure"),r.abort(e)):this.log("connection ping failed, but not aborting due to abortConnectionOnPingFailure flag")}))}))}),this.pingIntervalMs)}stop(){var e;null===(e=this.abortController)||void 0===e||e.abort(),null!=this.heartbeatInterval&&clearInterval(this.heartbeatInterval)}}class zU{constructor(t,r){var n,i,o,a,s,l,c,u,d,h,p;e._defineProperty(this,"routers",void 0),e._defineProperty(this,"started",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/content-routing"),this.routers=null!==(n=r.routers)&&void 0!==n?n:[],this.started=!1,this.components=t,this.findProviders=null!==(i=null===(o=t.metrics)||void 0===o?void 0:o.traceFunction("libp2p.contentRouting.findProviders",this.findProviders.bind(this),{optionsIndex:1,getAttributesFromArgs:(t,r)=>{var[n]=t;return e._objectSpread2(e._objectSpread2({},r),{},{cid:n.toString()})},getAttributesFromYieldedValue:(t,r)=>e._objectSpread2(e._objectSpread2({},r),{},{providers:[...Array.isArray(r.providers)?r.providers:[],t.id.toString()]})}))&&void 0!==i?i:this.findProviders,this.provide=null!==(a=null===(s=t.metrics)||void 0===s?void 0:s.traceFunction("libp2p.contentRouting.provide",this.provide.bind(this),{optionsIndex:1,getAttributesFromArgs:(t,r)=>{var[n]=t;return e._objectSpread2(e._objectSpread2({},r),{},{cid:n.toString()})}}))&&void 0!==a?a:this.provide,this.cancelReprovide=null!==(l=null===(c=t.metrics)||void 0===c?void 0:c.traceFunction("libp2p.contentRouting.cancelReprovide",this.cancelReprovide.bind(this),{optionsIndex:1,getAttributesFromArgs:(t,r)=>{var[n]=t;return e._objectSpread2(e._objectSpread2({},r),{},{cid:n.toString()})}}))&&void 0!==l?l:this.cancelReprovide,this.put=null!==(u=null===(d=t.metrics)||void 0===d?void 0:d.traceFunction("libp2p.contentRouting.put",this.put.bind(this),{optionsIndex:2,getAttributesFromArgs:e=>{var[t]=e;return{key:Ze(t,"base36")}}}))&&void 0!==u?u:this.put,this.get=null!==(h=null===(p=t.metrics)||void 0===p?void 0:p.traceFunction("libp2p.contentRouting.get",this.get.bind(this),{optionsIndex:1,getAttributesFromArgs:e=>{var[t]=e;return{key:Ze(t,"base36")}}}))&&void 0!==h?h:this.get}isStarted(){return this.started}start(){var t=this;return e._asyncToGenerator((function*(){t.started=!0}))()}stop(){var t=this;return e._asyncToGenerator((function*(){t.started=!1}))()}findProviders(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){if(0===r.routers.length)throw new BF("No content routers available");var i,o=r,a=new ch,s=!1,l=!1;try{for(var c,u=e._asyncIterator(su(...o.routers.filter((e=>e.findProviders instanceof Function)).map((e=>e.findProviders(t,n)))));s=!(c=yield e._awaitAsyncGenerator(u.next())).done;s=!1){var d=c.value;null!=d&&(d.multiaddrs.length>0&&(yield e._awaitAsyncGenerator(r.components.peerStore.merge(d.id,{multiaddrs:d.multiaddrs}))),a.has(d.id)||(a.add(d.id),yield d))}}catch(e){l=!0,i=e}finally{try{s&&null!=u.return&&(yield e._awaitAsyncGenerator(u.return()))}finally{if(l)throw i}}}()})).apply(this,arguments)}provide(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i=r.length>1&&void 0!==r[1]?r[1]:{};if(0===n.routers.length)throw new BF("No content routers available");yield Promise.all(n.routers.filter((e=>e.provide instanceof Function)).map(function(){var r=e._asyncToGenerator((function*(e){yield e.provide(t,i)}));return function(e){return r.apply(this,arguments)}}()))}))()}cancelReprovide(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i=r.length>1&&void 0!==r[1]?r[1]:{};if(0===n.routers.length)throw new BF("No content routers available");yield Promise.all(n.routers.filter((e=>e.cancelReprovide instanceof Function)).map(function(){var r=e._asyncToGenerator((function*(e){yield e.cancelReprovide(t,i)}));return function(e){return r.apply(this,arguments)}}()))}))()}put(t,r,n){var i=this;return e._asyncToGenerator((function*(){if(!i.isStarted())throw new wa;yield Promise.all(i.routers.filter((e=>e.put instanceof Function)).map(function(){var i=e._asyncToGenerator((function*(e){yield e.put(t,r,n)}));return function(e){return i.apply(this,arguments)}}()))}))()}get(t,r){var n=this;return e._asyncToGenerator((function*(){if(!n.isStarted())throw new wa;return Promise.any(n.routers.filter((e=>e.get instanceof Function)).map(function(){var n=e._asyncToGenerator((function*(e){return e.get(t,r)}));return function(e){return n.apply(this,arguments)}}()))}))()}}class VU{constructor(t){var r,n,i,o,a,s=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"log",void 0),e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"routers",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/peer-routing"),this.log=t.logger.forComponent("libp2p:peer-routing"),this.peerId=t.peerId,this.peerStore=t.peerStore,this.routers=null!==(r=s.routers)&&void 0!==r?r:[],this.findPeer=null!==(n=null===(i=t.metrics)||void 0===i?void 0:i.traceFunction("libp2p.peerRouting.findPeer",this.findPeer.bind(this),{optionsIndex:1,getAttributesFromArgs:(t,r)=>{var[n]=t;return e._objectSpread2(e._objectSpread2({},r),{},{peer:n.toString()})}}))&&void 0!==n?n:this.findPeer,this.getClosestPeers=null!==(o=null===(a=t.metrics)||void 0===a?void 0:a.traceFunction("libp2p.peerRouting.getClosestPeers",this.getClosestPeers.bind(this),{optionsIndex:1,getAttributesFromArgs:(t,r)=>{var[n]=t;return e._objectSpread2(e._objectSpread2({},r),{},{key:Ze(n,"base36")})},getAttributesFromYieldedValue:(t,r)=>e._objectSpread2(e._objectSpread2({},r),{},{peers:[...Array.isArray(r.peers)?r.peers:[],t.id.toString()]})}))&&void 0!==o?o:this.getClosestPeers}findPeer(t,r){var n=this;return e._asyncToGenerator((function*(){if(0===n.routers.length)throw new NF("No peer routers available");if(t.toString()===n.peerId.toString())throw new DF("Should not try to find self");var i,o=n,a=su(...n.routers.filter((e=>e.findPeer instanceof Function)).map((n=>e._wrapAsyncGenerator((function*(){try{yield yield e._awaitAsyncGenerator(n.findPeer(t,r))}catch(e){o.log.error(e)}}))()))),s=!1,l=!1;try{for(var c,u=e._asyncIterator(a);s=!(c=yield u.next()).done;s=!1){var d=c.value;if(null!=d)return d.multiaddrs.length>0&&(yield n.peerStore.merge(d.id,{multiaddrs:d.multiaddrs})),d}}catch(e){l=!0,i=e}finally{try{s&&null!=u.return&&(yield u.return())}finally{if(l)throw i}}throw new ua}))()}getClosestPeers(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){if(0===r.routers.length)throw new NF("No peer routers available");var i,o=r,a=_h(1024),s=!1,l=!1;try{for(var c,u=e._asyncIterator(zR(e._wrapAsyncGenerator((function*(){var r,i=su(...o.routers.filter((e=>e.getClosestPeers instanceof Function)).map((e=>e.getClosestPeers(t,n)))),a=!1,s=!1;try{for(var l,c=function*(){var t=l.value;yield e._asyncToGenerator((function*(){if(0===t.multiaddrs.length)try{t=yield o.findPeer(t.id,e._objectSpread2(e._objectSpread2({},n),{},{useCache:!1}))}catch(e){return void o.log.error("could not find peer multiaddrs",e)}return t}))},u=e._asyncIterator(i);a=!(l=yield e._awaitAsyncGenerator(u.next())).done;a=!1)yield*c()}catch(e){s=!0,r=e}finally{try{a&&null!=u.return&&(yield e._awaitAsyncGenerator(u.return()))}finally{if(s)throw r}}}))()));s=!(c=yield e._awaitAsyncGenerator(u.next())).done;s=!1){var d=c.value;null!=d&&(d.multiaddrs.length>0&&(yield e._awaitAsyncGenerator(r.peerStore.merge(d.id,{multiaddrs:d.multiaddrs}))),a.has(d.id.toMultihash().bytes)||(a.add(d.id.toMultihash().bytes),yield d))}}catch(e){l=!0,i=e}finally{try{s&&null!=u.return&&(yield e._awaitAsyncGenerator(u.return()))}finally{if(l)throw i}}}()})).apply(this,arguments)}}class qU extends Ia{constructor(t){super(),e._defineProperty(this,"peerRouting",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"walking",void 0),e._defineProperty(this,"walkers",void 0),e._defineProperty(this,"shutdownController",void 0),e._defineProperty(this,"walkController",void 0),e._defineProperty(this,"needNext",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/random-walk"),this.log=t.logger.forComponent("libp2p:random-walk"),this.peerRouting=t.peerRouting,this.walkers=0,this.walking=!1,this.shutdownController=new AbortController,this.shutdownController.signal}start(){this.shutdownController=new AbortController,this.shutdownController.signal}stop(){this.shutdownController.abort()}walk(t){var r=this;return e._wrapAsyncGenerator((function*(){r.walking||r.startWalk(),r.walkers++;var n=$d([r.shutdownController.signal,null==t?void 0:t.signal]);try{for(;;){var i;null===(i=r.needNext)||void 0===i||i.resolve(),r.needNext=Yc();var o=yield e._awaitAsyncGenerator(Bh(r,"walk:peer",n,{errorEvent:"walk:error"}));yield o.detail}}finally{var a;if(n.clear(),r.walkers--,0===r.walkers)null===(a=r.walkController)||void 0===a||a.abort(),r.walkController=void 0}}))()}startWalk(){var t=this;this.walking=!0,this.walkController=new AbortController,this.walkController.signal;var r=$d([this.walkController.signal,this.shutdownController.signal]),n=Date.now(),i=0;Promise.resolve().then(e._asyncToGenerator((function*(){for(t.log("start walk");t.walkers>0;)try{var n,o=gl(32),a=Date.now(),s=!1,l=!1;try{for(var c,u=e._asyncIterator(t.peerRouting.getClosestPeers(o,{signal:r}));s=!(c=yield u.next()).done;s=!1){var d=c.value;r.aborted&&t.log("aborting walk"),r.throwIfAborted(),t.log("found peer %p after %dms for %d walkers",d.id,Date.now()-a,t.walkers),i++,t.safeDispatchEvent("walk:peer",{detail:d}),1===t.walkers&&null!=t.needNext&&(t.log("wait for need next"),yield tu(t.needNext.promise,r)),a=Date.now()}}catch(e){l=!0,n=e}finally{try{s&&null!=u.return&&(yield u.return())}finally{if(l)throw n}}t.log("walk iteration for %b and %d walkers finished, found %d peers",o,t.walkers,i)}catch(e){t.log.error("random walk errored",e),t.safeDispatchEvent("walk:error",{detail:e})}t.log("no walkers left, ended walk")}))).catch((e=>{this.log.error("random walk errored",e)})).finally((()=>{this.log("finished walk, found %d peers after %dms",i,Date.now()-n),this.walking=!1}))}}class HU{constructor(t){e._defineProperty(this,"log",void 0),e._defineProperty(this,"topologies",void 0),e._defineProperty(this,"handlers",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/registrar"),this.log=t.logger.forComponent("libp2p:registrar"),this.topologies=new Map,this.handlers=new Map,this.components=t,this._onDisconnect=this._onDisconnect.bind(this),this._onPeerUpdate=this._onPeerUpdate.bind(this),this._onPeerIdentify=this._onPeerIdentify.bind(this),this.components.events.addEventListener("peer:disconnect",this._onDisconnect),this.components.events.addEventListener("peer:update",this._onPeerUpdate),this.components.events.addEventListener("peer:identify",this._onPeerIdentify)}getProtocols(){return Array.from(new Set([...this.handlers.keys()])).sort()}getHandler(e){var t=this.handlers.get(e);if(null==t)throw new GF("No handler registered for protocol ".concat(e));return t}getTopologies(e){var t=this.topologies.get(e);return null==t?[]:[...t.values()]}handle(t,r,n){var i=this;return e._asyncToGenerator((function*(){if(i.handlers.has(t)&&!0!==(null==n?void 0:n.force))throw new RF("Handler already registered for protocol ".concat(t));var e=rM.bind({ignoreUndefined:!0})({maxInboundStreams:32,maxOutboundStreams:64},n);i.handlers.set(t,{handler:r,options:e}),yield i.components.peerStore.merge(i.components.peerId,{protocols:[t]})}))()}unhandle(t){var r=this;return e._asyncToGenerator((function*(){(Array.isArray(t)?t:[t]).forEach((e=>{r.handlers.delete(e)})),yield r.components.peerStore.patch(r.components.peerId,{protocols:r.getProtocols()})}))()}register(t,r){var n=this;return e._asyncToGenerator((function*(){if(null==r)throw new ea("invalid topology");var e="".concat((1e9*Math.random()).toString(36)).concat(Date.now()),i=n.topologies.get(t);return null==i&&(i=new Map,n.topologies.set(t,i)),i.set(e,r),e}))()}unregister(e){for(var[t,r]of this.topologies.entries())r.has(e)&&(r.delete(e),0===r.size&&this.topologies.delete(t))}_onDisconnect(e){var t=e.detail;this.components.peerStore.get(t).then((e=>{for(var r of e.protocols){var n=this.topologies.get(r);if(null!=n)for(var i of n.values()){var o,a,s;!1!==(null===(o=i.filter)||void 0===o?void 0:o.has(t))&&(null===(a=i.filter)||void 0===a||a.remove(t),null===(s=i.onDisconnect)||void 0===s||s.call(i,t))}}})).catch((e=>{"NotFoundError"!==e.name&&this.log.error("could not inform topologies of disconnecting peer %p",t,e)}))}_onPeerUpdate(e){var t,{peer:r,previous:n}=e.detail,i=(null!==(t=null==n?void 0:n.protocols)&&void 0!==t?t:[]).filter((e=>!r.protocols.includes(e)));for(var o of i){var a=this.topologies.get(o);if(null!=a)for(var s of a.values()){var l,c,u;!1!==(null===(l=s.filter)||void 0===l?void 0:l.has(r.id))&&(null===(c=s.filter)||void 0===c||c.remove(r.id),null===(u=s.onDisconnect)||void 0===u||u.call(s,r.id))}}}_onPeerIdentify(e){var t=e.detail.protocols,r=e.detail.connection,n=e.detail.peerId;for(var i of t){var o=this.topologies.get(i);if(null!=o)for(var a of o.values()){var s,l,c;null!=r.limits&&!0!==a.notifyOnLimitedConnection||!0!==(null===(s=a.filter)||void 0===s?void 0:s.has(n))&&(null===(l=a.filter)||void 0===l||l.add(n),null===(c=a.onConnect)||void 0===c||c.call(a,n,r))}}}}class KU{constructor(t){var r,n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};e._defineProperty(this,"log",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"transports",void 0),e._defineProperty(this,"listeners",void 0),e._defineProperty(this,"faultTolerance",void 0),e._defineProperty(this,"started",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/transport-manager"),this.log=t.logger.forComponent("libp2p:transports"),this.components=t,this.started=!1,this.transports=new Map,this.listeners=wN({name:"libp2p_transport_manager_listeners",metrics:this.components.metrics}),this.faultTolerance=null!==(r=n.faultTolerance)&&void 0!==r?r:Wo.FATAL_ALL}add(e){var t=e[Symbol.toStringTag];if(null==t)throw new ea("Transport must have a valid tag");if(this.transports.has(t))throw new ea("There is already a transport with the tag ".concat(t));this.log("adding transport %s",t),this.transports.set(t,e),this.listeners.has(t)||this.listeners.set(t,[])}isStarted(){return this.started}start(){this.started=!0}afterStart(){var t=this;return e._asyncToGenerator((function*(){var e=t.components.addressManager.getListenAddrs();yield t.listen(e)}))()}stop(){var t=this;return e._asyncToGenerator((function*(){var e=[];for(var[r,n]of t.listeners)for(t.log("closing listeners for %s",r);n.length>0;){var i=n.pop();null!=i&&e.push(i.close())}for(var o of(yield Promise.all(e),t.log("all listeners closed"),t.listeners.keys()))t.listeners.set(o,[]);t.started=!1}))()}dial(t,r){var n=this;return e._asyncToGenerator((function*(){var i,o=n.dialTransportForMultiaddr(t);if(null==o)throw new qF("No transport available for address ".concat(String(t)));return null==r||null===(i=r.onProgress)||void 0===i||i.call(r,new Ih("transport-manager:selected-transport",o[Symbol.toStringTag])),o.dial(t,e._objectSpread2(e._objectSpread2({},r),{},{upgrader:n.components.upgrader}))}))()}getAddrs(){var e=[];for(var t of this.listeners.values())for(var r of t)e=[...e,...r.getAddrs()];return e}getTransports(){return Array.of(...this.transports.values())}getListeners(){return Array.of(...this.listeners.values()).flat()}dialTransportForMultiaddr(e){for(var t of this.transports.values()){if(t.dialFilter([e]).length>0)return t}}listenTransportForMultiaddr(e){for(var t of this.transports.values()){if(t.listenFilter([e]).length>0)return t}}listen(t){var r=this;return e._asyncToGenerator((function*(){if(!r.isStarted())throw new wa("Not started");if(null!=t&&0!==t.length){var e={errors:new Map,ipv4:{success:0,attempts:0},ipv6:{success:0,attempts:0}};t.forEach((t=>{e.errors.set(t.toString(),new LF)}));var n=[],i=function*(i){var o=a.listenFilter(t),s=function*(t){var o;r.log("creating listener for %s on %a",i,t);var s=a.createListener({upgrader:r.components.upgrader}),l=null!==(o=r.listeners.get(i))&&void 0!==o?o:[];null==l&&(l=[],r.listeners.set(i,l)),l.push(s),s.addEventListener("listening",(()=>{r.components.events.safeDispatchEvent("transport:listening",{detail:s})})),s.addEventListener("close",(()=>{var e=l.findIndex((e=>e===s));l.splice(e,1),r.components.events.safeDispatchEvent("transport:close",{detail:s})})),xd.matches(t)?e.ipv4.attempts++:Td.matches(t)&&e.ipv6.attempts++,n.push(s.listen(t).then((()=>{e.errors.delete(t.toString()),xd.matches(t)&&e.ipv4.success++,Td.matches(t)&&e.ipv6.success++}),(n=>{throw r.log.error("transport %s could not listen on address %a - %e",i,t,n),e.errors.set(t.toString(),n),n})))};for(var l of o)yield*s(l)};for(var[o,a]of r.transports.entries())yield*i(o);var s=yield Promise.allSettled(n);if(!(s.length>0&&s.every((e=>"fulfilled"===e.status))))if(r.ipv6Unsupported(e))r.log("all IPv4 addresses succeed but all IPv6 failed");else{if(r.faultTolerance!==Wo.NO_FATAL)throw new MF("Some configured addresses failed to be listened on, you may need to remove one or more listen addresses from your configuration or set `transportManager.faultTolerance` to NO_FATAL:\n".concat([...e.errors.entries()].map((e=>{var t,[r,n]=e;return"\n ".concat(r,": ").concat("".concat(null!==(t=n.stack)&&void 0!==t?t:n).split("\n").join("\n "),"\n")})).join("")));r.log("failed to listen on any address but fault tolerance allows this")}}else r.log("no addresses were provided for listening, this node is dial only")}))()}ipv6Unsupported(e){if(0===e.ipv4.attempts||0===e.ipv6.attempts)return!1;var t=e.ipv4.attempts===e.ipv4.success,r=0===e.ipv6.success;return t&&r}remove(t){var r=this;return e._asyncToGenerator((function*(){var e,n=null!==(e=r.listeners.get(t))&&void 0!==e?e:[];r.log.trace("removing transport %s",t);var i=[];for(r.log.trace("closing listeners for %s",t);n.length>0;){var o=n.pop();null!=o&&i.push(o.close())}yield Promise.all(i),r.transports.delete(t),r.listeners.delete(t)}))()}removeAll(){var t=this;return e._asyncToGenerator((function*(){var e=[];for(var r of t.transports.keys())e.push(t.remove(r));yield Promise.all(e)}))()}}var WU="/multistream/1.0.0",QU=1024,YU=ot("\n");function JU(e,t,r){return ZU.apply(this,arguments)}function ZU(){return ZU=e._asyncToGenerator((function*(e,t,r){yield e.write(t,r)})),ZU.apply(this,arguments)}function $U(){return $U=e._asyncToGenerator((function*(e,t,r){yield e.writeV(t,r)})),$U.apply(this,arguments)}function XU(){return XU=e._asyncToGenerator((function*(e,t){var r=yield e.read(t);if(0===r.byteLength||r.get(r.byteLength-1)!==YU[0])throw t.log.error("Invalid mss message - missing newline",r),new ya("Missing newline");return r.sublist(0,-1)})),XU.apply(this,arguments)}function ez(e,t){return tz.apply(this,arguments)}function tz(){return tz=e._asyncToGenerator((function*(e,t){var r=yield function(e,t){return XU.apply(this,arguments)}(e,t);return Ze(r.subarray())})),tz.apply(this,arguments)}function rz(e,t,r){return nz.apply(this,arguments)}function nz(){return nz=e._asyncToGenerator((function*(t,r,n){if(1===(r=Array.isArray(r)?[...r]:[r]).length&&!1===n.negotiateFully)return function(t,r,n){var i=t.sink.bind(t),o=t.source,a=!1,s=!1,l=Yc(),c=!1,u=!1,d=Yc(),h=!1,p=!1,f=Yc(),v=Ku({sink:i,source:o},e._objectSpread2(e._objectSpread2({},n),{},{maxDataLength:QU}));function y(){return g.apply(this,arguments)}function g(){return(g=e._asyncToGenerator((function*(){if(s)return n.log.trace("optimistic: already negotiating %s stream",r),void(yield l.promise);s=!0;try{c||(n.log.trace("optimistic: doing send protocol for %s stream",r),yield m()),h||(n.log.trace("optimistic: doing read protocol for %s stream",r),yield b())}finally{s=!1,a=!0,l.resolve()}}))).apply(this,arguments)}function m(){return w.apply(this,arguments)}function w(){return(w=e._asyncToGenerator((function*(){if(u)yield d.promise;else{u=!0;try{n.log.trace('optimistic: write ["%s", "%s", data] in source',WU,r),yield v.writeV([ot("".concat(WU,"\n")),ot("".concat(r,"\n"))]),n.log.trace('optimistic: wrote ["%s", "%s", data] in source',WU,r)}finally{c=!0,u=!1,d.resolve()}}}))).apply(this,arguments)}function b(){return _.apply(this,arguments)}function _(){return _=e._asyncToGenerator((function*(){if(p)yield f.promise;else{p=!0;try{n.log.trace("optimistic: reading multistream select header");var e=yield ez(v,n);if(n.log.trace('optimistic: read multistream select header "%s"',e),e===WU&&(e=yield ez(v,n)),n.log.trace('optimistic: read protocol "%s", expecting "%s"',e,r),e!==r)throw new va("protocol selection failed")}finally{h=!0,p=!1,f.resolve()}}})),_.apply(this,arguments)}if(t.sink=function(){var t=e._asyncToGenerator((function*(t){var{sink:i}=v.unwrap();yield i(e._wrapAsyncGenerator((function*(){var i,o=!1,a=!1,s=!1;try{for(var l,h=e._asyncIterator(t);a=!(l=yield e._awaitAsyncGenerator(h.next())).done;a=!1){var p=l.value;if(u&&(yield e._awaitAsyncGenerator(d.promise)),c)yield p;else{u=!0,n.log.trace('optimistic: write ["%s", "%s", data(%d)] in sink',WU,r,p.byteLength);var f="".concat(r,"\n");yield new Fa(Uint8Array.from([19]),ot("".concat(WU,"\n")),wt(f.length),ot(f),p).subarray(),n.log.trace('optimistic: wrote ["%s", "%s", data(%d)] in sink',WU,r,p.byteLength),c=!0,u=!1,d.resolve(),y().catch((e=>{n.log.error("could not finish optimistic protocol negotiation of %s",r,e)}))}o=!0}}catch(e){s=!0,i=e}finally{try{a&&null!=h.return&&(yield e._awaitAsyncGenerator(h.return()))}finally{if(s)throw i}}o||(yield e._awaitAsyncGenerator(y()))}))())}));return function(e){return t.apply(this,arguments)}}(),t.source=e._wrapAsyncGenerator((function*(){yield e._awaitAsyncGenerator(y()),n.log.trace('optimistic: reading data from "%s" stream',r),yield*e._asyncGeneratorDelegate(e._asyncIterator(v.unwrap().source))}))(),null!=t.closeRead){var S=t.closeRead.bind(t);t.closeRead=function(){var t=e._asyncToGenerator((function*(e){a||(yield y().catch((e=>{n.log.error("could not negotiate protocol before close read",e)}))),yield S(e)}));return function(e){return t.apply(this,arguments)}}()}if(null!=t.closeWrite){var P=t.closeWrite.bind(t);t.closeWrite=function(){var t=e._asyncToGenerator((function*(e){a||(yield y().catch((e=>{n.log.error("could not negotiate protocol before close write",e)}))),yield P(e)}));return function(e){return t.apply(this,arguments)}}()}if(null!=t.close){var E=t.close.bind(t);t.close=function(){var t=e._asyncToGenerator((function*(e){var t=[];u&&t.push(d.promise),p&&t.push(f.promise),t.length>0?yield tu(Promise.all(t),null==e?void 0:e.signal):(a=!0,s=!1,l.resolve()),yield E(e)}));return function(e){return t.apply(this,arguments)}}()}return{stream:t,protocol:r}}(t,r[0],n);var i=Ku(t,e._objectSpread2(e._objectSpread2({},n),{},{maxDataLength:QU})),o=r.shift();if(null==o)throw new Error("At least one protocol must be specified");n.log.trace('select: write ["%s", "%s"]',WU,o);var a=ot("".concat(WU,"\n")),s=ot("".concat(o,"\n"));yield function(e,t,r){return $U.apply(this,arguments)}(i,[a,s],n),n.log.trace("select: reading multistream-select header");var l=yield ez(i,n);if(n.log.trace('select: read "%s"',l),l===WU&&(n.log.trace("select: reading protocol response"),l=yield ez(i,n),n.log.trace('select: read "%s"',l)),l===o)return{stream:i.unwrap(),protocol:o};for(var c of r){n.log.trace('select: write "%s"',c),yield JU(i,ot("".concat(c,"\n")),n),n.log.trace("select: reading protocol response");var u=yield ez(i,n);if(n.log.trace('select: read "%s" for "%s"',u,c),u===c)return{stream:i.unwrap(),protocol:c}}throw new va("protocol selection failed")})),nz.apply(this,arguments)}function iz(e,t,r){return oz.apply(this,arguments)}function oz(){return oz=e._asyncToGenerator((function*(t,r,n){r=Array.isArray(r)?r:[r],n.log.trace("handle: available protocols %s",r);for(var i=Ku(t,e._objectSpread2(e._objectSpread2({},n),{},{maxDataLength:QU,maxLengthLength:2}));;){n.log.trace("handle: reading incoming string");var o=yield ez(i,n);if(n.log.trace('handle: read "%s"',o),o!==WU){if(r.includes(o))return n.log.trace('handle: respond with "%s" for "%s"',o,o),yield JU(i,ot("".concat(o,"\n")),n),n.log.trace('handle: responded with "%s" for "%s"',o,o),{stream:i.unwrap(),protocol:o};if("ls"!==o)n.log.trace('handle: respond with "na" for "%s"',o),yield JU(i,ot("na\n"),n),n.log('handle: responded with "na" for "%s"',o);else{var a=new Fa(...r.map((e=>Vp.single(ot("".concat(e,"\n"))))),ot("\n"));n.log.trace('handle: respond with "%s" for %s',r,o),yield JU(i,a,n),n.log.trace('handle: responded with "%s" for %s',r,o)}}else n.log.trace('handle: respond with "%s" for "%s"',WU,o),yield JU(i,ot("".concat(WU,"\n")),n),n.log.trace('handle: responded with "%s" for "%s"',WU,o)}})),oz.apply(this,arguments)}class az{constructor(t){e._defineProperty(this,"id",void 0),e._defineProperty(this,"remoteAddr",void 0),e._defineProperty(this,"remotePeer",void 0),e._defineProperty(this,"direction",void 0),e._defineProperty(this,"timeline",void 0),e._defineProperty(this,"multiplexer",void 0),e._defineProperty(this,"encryption",void 0),e._defineProperty(this,"status",void 0),e._defineProperty(this,"limits",void 0),e._defineProperty(this,"log",void 0),e._defineProperty(this,"tags",void 0),e._defineProperty(this,"_newStream",void 0),e._defineProperty(this,"_close",void 0),e._defineProperty(this,"_abort",void 0),e._defineProperty(this,"_getStreams",void 0),e._defineProperty(this,Symbol.toStringTag,"Connection"),e._defineProperty(this,zo,!0);var{remoteAddr:r,remotePeer:n,newStream:i,close:o,abort:a,getStreams:s}=t;this.id="".concat(parseInt(String(1e9*Math.random())).toString(36)).concat(Date.now()),this.remoteAddr=r,this.remotePeer=n,this.direction=t.direction,this.status="open",this.timeline=t.timeline,this.multiplexer=t.multiplexer,this.encryption=t.encryption,this.limits=t.limits,this.log=t.logger.forComponent("libp2p:connection:".concat(this.direction,":").concat(this.id)),null==this.remoteAddr.getPeerId()&&(this.remoteAddr=this.remoteAddr.encapsulate("/p2p/".concat(this.remotePeer))),this._newStream=i,this._close=o,this._abort=a,this._getStreams=s,this.tags=[]}get streams(){return this._getStreams()}newStream(t,r){var n=this;return e._asyncToGenerator((function*(){if("closing"===n.status)throw new ia("the connection is being closed");if("closed"===n.status)throw new oa("the connection is closed");if(Array.isArray(t)||(t=[t]),null!=n.limits&&!0!==(null==r?void 0:r.runOnLimitedConnection))throw new Pa("Cannot open protocol stream on limited connection");var e=yield n._newStream(t,r);return e.direction="outbound",e}))()}close(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var n=t.length>0&&void 0!==t[0]?t[0]:{};if("closed"!==r.status&&"closing"!==r.status){if(r.log("closing connection to %a",r.remoteAddr),r.status="closing",null==n.signal){var i=AbortSignal.timeout(500);n=e._objectSpread2(e._objectSpread2({},n),{},{signal:i})}try{r.log.trace("closing underlying transport"),yield r._close(n),r.log.trace("updating timeline with close time"),r.status="closed",r.timeline.close=Date.now()}catch(e){r.log.error("error encountered during graceful close of connection to %a",r.remoteAddr,e),r.abort(e)}}}))()}abort(e){"closed"!==this.status&&(this.log.error("aborting connection to %a due to error",this.remoteAddr,e),this.status="closing",this._abort(e),this.status="closed",this.timeline.close=Date.now())}}function sz(e,t,r){var n=0;return r.streams.forEach((r=>{r.direction===t&&r.protocol===e&&n++})),n}class lz{constructor(t,r){var n,i,o,a,s;e._defineProperty(this,"components",void 0),e._defineProperty(this,"connectionEncrypters",void 0),e._defineProperty(this,"streamMuxers",void 0),e._defineProperty(this,"inboundUpgradeTimeout",void 0),e._defineProperty(this,"inboundStreamProtocolNegotiationTimeout",void 0),e._defineProperty(this,"outboundStreamProtocolNegotiationTimeout",void 0),e._defineProperty(this,"events",void 0),e._defineProperty(this,"metrics",void 0),e._defineProperty(this,Symbol.toStringTag,"@libp2p/upgrader"),this.components=t,this.connectionEncrypters=new Map,r.connectionEncrypters.forEach((e=>{this.connectionEncrypters.set(e.protocol,e)})),this.streamMuxers=new Map,r.streamMuxers.forEach((e=>{this.streamMuxers.set(e.protocol,e)})),this.inboundUpgradeTimeout=null!==(n=r.inboundUpgradeTimeout)&&void 0!==n?n:1e4,this.inboundStreamProtocolNegotiationTimeout=null!==(i=r.inboundStreamProtocolNegotiationTimeout)&&void 0!==i?i:1e4,this.outboundStreamProtocolNegotiationTimeout=null!==(o=r.outboundStreamProtocolNegotiationTimeout)&&void 0!==o?o:1e4,this.events=t.events,this.metrics={dials:null===(a=t.metrics)||void 0===a?void 0:a.registerCounterGroup("libp2p_connection_manager_dials_total"),errors:null===(s=t.metrics)||void 0===s?void 0:s.registerCounterGroup("libp2p_connection_manager_dial_errors_total")}}shouldBlockConnection(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=n.components.connectionGater[t];if(null!=e){for(var i=r.length,o=new Array(i>1?i-1:0),a=1;a<i;a++)o[a-1]=r[a];if(!0===(yield e.apply(n.components.connectionGater,o)))throw new FF("The multiaddr connection is blocked by gater.".concat(t))}}))()}createInboundAbortSignal(e){return $d([AbortSignal.timeout(this.inboundUpgradeTimeout),e])}upgradeInbound(t,r){var n=this;return e._asyncToGenerator((function*(){var i=!1,o=n.createInboundAbortSignal(r.signal);try{var a;if(null===(a=n.metrics.dials)||void 0===a||a.increment({inbound:!0}),!(i=yield n.components.connectionManager.acceptIncomingConnection(t)))throw new UF("Connection denied");yield n.shouldBlockConnection("denyInboundConnection",t),yield n._performUpgrade(t,"inbound",e._objectSpread2(e._objectSpread2({},r),{},{signal:o}))}catch(e){var s;throw null===(s=n.metrics.errors)||void 0===s||s.increment({inbound:!0}),e}finally{o.clear(),i&&n.components.connectionManager.afterUpgradeInbound()}}))()}upgradeOutbound(t,r){var n=this;return e._asyncToGenerator((function*(){try{var e;null===(e=n.metrics.dials)||void 0===e||e.increment({outbound:!0});var i,o=t.remoteAddr.getPeerId();null!=o&&(i=rc(o),yield n.shouldBlockConnection("denyOutboundConnection",i,t));var a="outbound";return!1===r.initiator&&(a="inbound"),yield n._performUpgrade(t,a,r)}catch(e){var s;throw null===(s=n.metrics.errors)||void 0===s||s.increment({outbound:!0}),e}}))()}_performUpgrade(t,r,n){var i=this;return e._asyncToGenerator((function*(){var o,a,s,l,c,u;null===(o=i.components.metrics)||void 0===o||o.trackMultiaddrConnection(t),t.log.trace("starting the %s connection upgrade",r);var d=t;if(!0!==(null==n?void 0:n.skipProtection)){var h=i.components.connectionProtector;null!=h&&(t.log("protecting the %s connection",r),d=yield h.protect(t,n))}try{if(a=d,!0!==(null==n?void 0:n.skipEncryption)){var p;null==n||null===(p=n.onProgress)||void 0===p||p.call(n,new Ih("upgrader:encrypt-".concat(r,"-connection"))),({conn:a,remotePeer:s,protocol:u,streamMuxer:c}=yield"inbound"===r?i._encryptInbound(d,n):i._encryptOutbound(d,n));var f=e._objectSpread2(e._objectSpread2({},d),a);yield i.shouldBlockConnection("inbound"===r?"denyInboundEncryptedConnection":"denyOutboundEncryptedConnection",s,f)}else{var v=t.remoteAddr.getPeerId();if(null==v)throw new ha("".concat(r," connection that skipped encryption must have a peer id"));var y=rc(v);u="native",s=y}if(s.equals(i.components.peerId)){var g=new da("Can not dial self");throw t.abort(g),g}if(l=a,null!=(null==n?void 0:n.muxerFactory))c=n.muxerFactory;else if(null==c&&i.streamMuxers.size>0){var m;null==n||null===(m=n.onProgress)||void 0===m||m.call(n,new Ih("upgrader:multiplex-".concat(r,"-connection")));var w=yield"inbound"===r?i._multiplexInbound(e._objectSpread2(e._objectSpread2({},d),a),i.streamMuxers,n):i._multiplexOutbound(e._objectSpread2(e._objectSpread2({},d),a),i.streamMuxers,n);c=w.muxerFactory,l=w.stream}}catch(g){throw t.log.error("failed to upgrade inbound connection %s %a - %e","inbound"===r?"from":"to",t.remoteAddr,g),g}return yield i.shouldBlockConnection("inbound"===r?"denyInboundUpgradedConnection":"denyOutboundUpgradedConnection",s,t),t.log("successfully upgraded %s connection",r),i._createConnection({cryptoProtocol:u,direction:r,maConn:t,upgradedConn:l,muxerFactory:c,remotePeer:s,limits:null==n?void 0:n.limits})}))()}_createConnection(t){var r,n,i,o,a=this,{cryptoProtocol:s,direction:l,maConn:c,upgradedConn:u,remotePeer:d,muxerFactory:h,limits:p}=t;null!=h&&(n=h.createStreamMuxer({direction:l,onIncomingStream:t=>{null!=o&&Promise.resolve().then(e._asyncToGenerator((function*(){var e,r=a.components.registrar.getProtocols(),n=AbortSignal.timeout(a.inboundStreamProtocolNegotiationTimeout),{stream:i,protocol:s}=yield iz(t,r,{signal:n,log:t.log,yieldBytes:!1});if(null!=o){o.log("incoming stream opened on %s",s);var l=function(e,t){try{var{options:r}=t.getHandler(e);return r.maxInboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return 32}(s,a.components.registrar);if(sz(s,"inbound",o)===l){var c=new Ea('Too many inbound protocol streams for protocol "'.concat(s,'" - limit ').concat(l));throw t.abort(c),c}t.source=i.source,t.sink=i.sink,t.protocol=s,null!=i.closeWrite&&(t.closeWrite=i.closeWrite),null!=i.closeRead&&(t.closeRead=i.closeRead),null!=i.close&&(t.close=i.close),yield a.components.peerStore.merge(d,{protocols:[s]}),null===(e=a.components.metrics)||void 0===e||e.trackProtocolStream(t,o),a._onStream({connection:o,stream:t,protocol:s})}}))).catch(function(){var r=e._asyncToGenerator((function*(e){o.log.error("error handling incoming stream id %s - %e",t.id,e),null==t.timeline.close&&(yield t.close())}));return function(e){return r.apply(this,arguments)}}())}}),i=function(){var r=e._asyncToGenerator((function*(r){var i=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(null==n)throw new zF("Connection is not multiplexed");o.log.trace("starting new stream for protocols %s",r);var s=yield n.newStream();o.log.trace("started new stream %s for protocols %s",s.id,r);try{var c;if(null==i.signal){s.log("no abort signal was passed while trying to negotiate protocols %s falling back to default timeout",r);var u=AbortSignal.timeout(a.outboundStreamProtocolNegotiationTimeout);i=e._objectSpread2(e._objectSpread2({},i),{},{signal:u})}s.log.trace("selecting protocol from protocols %s",r);var{stream:h,protocol:p}=yield rz(s,r,e._objectSpread2(e._objectSpread2({},i),{},{log:s.log,yieldBytes:!0}));s.log.trace("selected protocol %s",p);var f=function(e,t){var r,n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};try{var{options:i}=t.getHandler(e);if(null!=i.maxOutboundStreams)return i.maxOutboundStreams}catch(e){if("UnhandledProtocolError"!==e.name)throw e}return null!==(r=n.maxOutboundStreams)&&void 0!==r?r:64}(p,a.components.registrar,i),v=sz(p,"outbound",o);if(v>=f){var y=new Aa('Too many outbound protocol streams for protocol "'.concat(p,'" - ').concat(v,"/").concat(f));throw s.abort(y),y}return yield a.components.peerStore.merge(d,{protocols:[p]}),s.source=h.source,s.sink=h.sink,s.protocol=p,null!=h.closeWrite&&(s.closeWrite=h.closeWrite),null!=h.closeRead&&(s.closeRead=h.closeRead),null!=h.close&&(s.close=h.close),null===(c=a.components.metrics)||void 0===c||c.trackProtocolStream(s,o),s}catch(y){throw o.log.error("could not create new outbound stream on connection %s %a for protocols %s - %e","inbound"===l?"from":"to",t.maConn.remoteAddr,r,y),null==s.timeline.close&&s.abort(y),y}}));return function(e){return r.apply(this,arguments)}}(),Promise.all([n.sink(u.source),u.sink(n.source)]).catch((e=>{o.log.error("error piping data through muxer - %e",e)})));var f=c.timeline;c.timeline=new Proxy(f,{set:function(){return"close"===(arguments.length<=1?void 0:arguments[1])&&null!=(arguments.length<=2?void 0:arguments[2])&&null==f.close&&e._asyncToGenerator((function*(){try{"open"===o.status&&(yield o.close())}catch(e){o.log.error("error closing connection after timeline close %e",e)}finally{a.events.safeDispatchEvent("connection:close",{detail:o})}}))().catch((e=>{o.log.error("error thrown while dispatching connection:close event %e",e)})),Reflect.set(...arguments)}}),c.timeline.upgraded=Date.now();var v,y;return v={remoteAddr:c.remoteAddr,remotePeer:d,status:"open",direction:l,timeline:c.timeline,multiplexer:null===(r=n)||void 0===r?void 0:r.protocol,encryption:s,limits:p,logger:this.components.logger,newStream:null!=i?i:()=>{throw new zF("Connection is not multiplexed")},getStreams:()=>{var e,t;return null!==(e=null===(t=n)||void 0===t?void 0:t.streams)&&void 0!==e?e:[]},close:(y=e._asyncToGenerator((function*(e){var t;yield null===(t=n)||void 0===t?void 0:t.close(e),yield c.close(e)})),function(e){return y.apply(this,arguments)}),abort:e=>{var t;c.abort(e),null===(t=n)||void 0===t||t.abort(e)}},o=new az(v),this.events.safeDispatchEvent("connection:open",{detail:o}),o.__maConnTimeline=f,o}_onStream(e){var{connection:t,stream:r,protocol:n}=e,{handler:i,options:o}=this.components.registrar.getHandler(n);if(null!=t.limits&&!0!==o.runOnLimitedConnection)throw new Pa("Cannot open protocol stream on limited connection");i({connection:t,stream:r})}_encryptInbound(t,r){var n=this;return e._asyncToGenerator((function*(){var i=Array.from(n.connectionEncrypters.keys());try{var{stream:o,protocol:a}=yield iz(t,i,e._objectSpread2(e._objectSpread2({},r),{},{log:t.log})),s=n.connectionEncrypters.get(a);if(null==s)throw new VF("no crypto module found for ".concat(a));return t.log("encrypting inbound connection to %a using %s",t.remoteAddr,a),e._objectSpread2(e._objectSpread2({},yield s.secureInbound(o,r)),{},{protocol:a})}catch(e){throw t.log.error("encrypting inbound connection from %a failed",t.remoteAddr,e),new VF(e.message)}}))()}_encryptOutbound(t,r){var n=this;return e._asyncToGenerator((function*(){var i=Array.from(n.connectionEncrypters.keys());try{t.log.trace("selecting encrypter from %s",i);var{stream:o,protocol:a}=yield rz(t,i,e._objectSpread2(e._objectSpread2({},r),{},{log:t.log,yieldBytes:!0})),s=n.connectionEncrypters.get(a);if(null==s)throw new VF("no crypto module found for ".concat(a));return t.log("encrypting outbound connection to %a using %s",t.remoteAddr,a),e._objectSpread2(e._objectSpread2({},yield s.secureOutbound(o,r)),{},{protocol:a})}catch(e){throw t.log.error("encrypting outbound connection to %a failed",t.remoteAddr,e),new VF(e.message)}}))()}_multiplexOutbound(t,r,n){return e._asyncToGenerator((function*(){var i=Array.from(r.keys());t.log("outbound selecting muxer %s",i);try{t.log.trace("selecting stream muxer from %s",i);var{stream:o,protocol:a}=yield rz(t,i,e._objectSpread2(e._objectSpread2({},n),{},{log:t.log,yieldBytes:!0}));return t.log("selected %s as muxer protocol",a),{stream:o,muxerFactory:r.get(a)}}catch(e){throw t.log.error("error multiplexing outbound connection",e),new zF(String(e))}}))()}_multiplexInbound(t,r,n){return e._asyncToGenerator((function*(){var i=Array.from(r.keys());t.log("inbound handling muxers %s",i);try{var{stream:o,protocol:a}=yield iz(t,i,e._objectSpread2(e._objectSpread2({},n),{},{log:t.log}));return{stream:o,muxerFactory:r.get(a)}}catch(e){throw t.log.error("error multiplexing inbound connection",e),new zF(String(e))}}))()}getConnectionEncrypters(){return this.connectionEncrypters}getStreamMuxers(){return this.streamMuxers}}var cz=new WeakSet;class uz extends Ia{constructor(t){var r,n,i,o,a,s,l,c,u,d,h,p,f,v,y,g,m,w,b,_,S,P;super(),e._classPrivateMethodInitSpec(this,cz),e._defineProperty(this,"peerId",void 0),e._defineProperty(this,"peerStore",void 0),e._defineProperty(this,"contentRouting",void 0),e._defineProperty(this,"peerRouting",void 0),e._defineProperty(this,"metrics",void 0),e._defineProperty(this,"services",void 0),e._defineProperty(this,"logger",void 0),e._defineProperty(this,"status",void 0),e._defineProperty(this,"components",void 0),e._defineProperty(this,"log",void 0),this.status="stopped";var E=new Ia,A=E.dispatchEvent.bind(E);E.dispatchEvent=e=>{var t=A(e),r=this.dispatchEvent(new CustomEvent(e.type,{detail:e.detail}));return t||r},this.peerId=t.peerId,this.logger=null!==(r=t.logger)&&void 0!==r?r:Iu(),this.log=this.logger.forComponent("libp2p"),this.services={};var k=null!==(n=null===(i=t.nodeInfo)||void 0===i?void 0:i.name)&&void 0!==n?n:Ej,x=null!==(o=null===(a=t.nodeInfo)||void 0===a?void 0:a.version)&&void 0!==o?o:Pj,T=this.components=function(){var e=new HF(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{});return new Proxy(e,{get(t,r,n){if("string"==typeof r&&!WF.includes(r)){var i=e.components[r];if(null==i&&!KF.includes(r))throw new IF("".concat(r," not set"));return i}return Reflect.get(t,r,n)},set:(t,r,n)=>("string"==typeof r?e.components[r]=n:Reflect.set(t,r,n),!0)})}({peerId:t.peerId,privateKey:t.privateKey,nodeInfo:{name:k,version:x,userAgent:null!==(s=null===(l=t.nodeInfo)||void 0===l?void 0:l.userAgent)&&void 0!==s?s:Aj(k,x)},logger:this.logger,events:E,datastore:null!==(c=t.datastore)&&void 0!==c?c:new Wc,connectionGater:ZF(t.connectionGater),dns:t.dns});this.peerStore=this.configureComponent("peerStore",function(e){return new pF(e,arguments.length>1&&void 0!==arguments[1]?arguments[1]:{})}(T,e._objectSpread2({addressFilter:this.components.connectionGater.filterMultiaddrForPeer},t.peerStore))),null!=t.metrics&&(this.metrics=this.configureComponent("metrics",t.metrics(this.components))),T.events.addEventListener("peer:update",(e=>{if(null==e.detail.previous){var t={id:e.detail.peer.id,multiaddrs:e.detail.peer.addresses.map((e=>e.multiaddr))};T.events.safeDispatchEvent("peer:discovery",{detail:t})}})),null!=t.connectionProtector&&this.configureComponent("connectionProtector",t.connectionProtector(T)),this.components.upgrader=new lz(this.components,{connectionEncrypters:(null!==(u=t.connectionEncrypters)&&void 0!==u?u:[]).map(((e,t)=>this.configureComponent("connection-encryption-".concat(t),e(this.components)))),streamMuxers:(null!==(d=t.streamMuxers)&&void 0!==d?d:[]).map(((e,t)=>this.configureComponent("stream-muxers-".concat(t),e(this.components)))),inboundUpgradeTimeout:null===(h=t.connectionManager)||void 0===h?void 0:h.inboundUpgradeTimeout,inboundStreamProtocolNegotiationTimeout:null!==(p=null===(f=t.connectionManager)||void 0===f?void 0:f.inboundStreamProtocolNegotiationTimeout)&&void 0!==p?p:null===(v=t.connectionManager)||void 0===v?void 0:v.protocolNegotiationTimeout,outboundStreamProtocolNegotiationTimeout:null!==(y=null===(g=t.connectionManager)||void 0===g?void 0:g.outboundStreamProtocolNegotiationTimeout)&&void 0!==y?y:null===(m=t.connectionManager)||void 0===m?void 0:m.protocolNegotiationTimeout}),this.configureComponent("transportManager",new KU(this.components,t.transportManager)),this.configureComponent("connectionManager",new FU(this.components,t.connectionManager)),!1!==(null===(w=t.connectionMonitor)||void 0===w?void 0:w.enabled)&&this.configureComponent("connectionMonitor",new UU(this.components,t.connectionMonitor)),this.configureComponent("registrar",new HU(this.components)),this.configureComponent("addressManager",new TF(this.components,t.addresses));var I=(null!==(b=t.peerRouters)&&void 0!==b?b:[]).map(((e,t)=>this.configureComponent("peer-router-".concat(t),e(this.components))));this.peerRouting=this.components.peerRouting=this.configureComponent("peerRouting",new VU(this.components,{routers:I}));var C=(null!==(_=t.contentRouters)&&void 0!==_?_:[]).map(((e,t)=>this.configureComponent("content-router-".concat(t),e(this.components))));if(this.contentRouting=this.components.contentRouting=this.configureComponent("contentRouting",new zU(this.components,{routers:C})),this.configureComponent("randomWalk",new qU(this.components)),(null!==(S=t.peerDiscovery)&&void 0!==S?S:[]).forEach(((t,r)=>{this.configureComponent("peer-discovery-".concat(r),t(this.components)).addEventListener("peer",(t=>{e._assertClassBrand(cz,this,dz).call(this,t)}))})),null===(P=t.transports)||void 0===P||P.forEach(((e,t)=>{this.components.transportManager.add(this.configureComponent("transport-".concat(t),e(this.components)))})),null!=t.services)for(var B of Object.keys(t.services)){var N,D,G=(0,t.services[B])(this.components);if(null!=G){if(this.services[B]=G,this.configureComponent(B,G),null!=G[Vo]&&(this.log("registering service %s for content routing",B),C.push(G[Vo])),null!=G[Qo]&&(this.log("registering service %s for peer routing",B),I.push(G[Qo])),null!=G[qo])this.log("registering service %s for peer discovery",B),null===(N=(D=G[qo]).addEventListener)||void 0===N||N.call(D,"peer",(t=>{e._assertClassBrand(cz,this,dz).call(this,t)}))}else this.log.error("service factory %s returned null or undefined instance",B)}!function(e){var t={};for(var r of Object.values(e.components))for(var n of QF(r))t[n]=!0;for(var i of Object.values(e.components))for(var o of YF(i))if(!0!==t[o])throw new CF('Service "'.concat(JF(i),'" required capability "').concat(o,'" but it was not provided by any component, you may need to add additional configuration when creating your node.'))}(T)}configureComponent(e,t){return null==t&&this.log.error("component %s was null or undefined",e),this.components[e]=t,t}start(){var t=this;return e._asyncToGenerator((function*(){if("stopped"===t.status){t.status="starting",t.log("libp2p is starting");try{var e,r,n,i;yield null===(e=(r=t.components).beforeStart)||void 0===e?void 0:e.call(r),yield t.components.start(),yield null===(n=(i=t.components).afterStart)||void 0===n?void 0:n.call(i),t.status="started",t.safeDispatchEvent("start",{detail:t}),t.log("libp2p has started")}catch(e){throw t.log.error("An error occurred starting libp2p",e),t.status="started",yield t.stop(),e}}}))()}stop(){var t=this;return e._asyncToGenerator((function*(){var e,r,n,i;"started"===t.status&&(t.log("libp2p is stopping"),t.status="stopping",yield null===(e=(r=t.components).beforeStop)||void 0===e?void 0:e.call(r),yield t.components.stop(),yield null===(n=(i=t.components).afterStop)||void 0===n?void 0:n.call(i),t.status="stopped",t.safeDispatchEvent("stop",{detail:t}),t.log("libp2p has stopped"))}))()}getConnections(e){return this.components.connectionManager.getConnections(e)}getDialQueue(){return this.components.connectionManager.getDialQueue()}getPeers(){var e=new ch;for(var t of this.components.connectionManager.getConnections())e.add(t.remotePeer);return Array.from(e)}dial(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var i=r.length>1&&void 0!==r[1]?r[1]:{};return n.components.connectionManager.openConnection(t,e._objectSpread2({priority:75},i))}))()}dialProtocol(t,r){var n=arguments,i=this;return e._asyncToGenerator((function*(){var e=n.length>2&&void 0!==n[2]?n[2]:{};if(null==r)throw new ea("no protocols were provided to open a stream");if(0===(r=Array.isArray(r)?r:[r]).length)throw new ea("no protocols were provided to open a stream");return(yield i.dial(t,e)).newStream(r,e)}))()}getMultiaddrs(){return this.components.addressManager.getAddresses()}getProtocols(){return this.components.registrar.getProtocols()}hangUp(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e,i=r.length>1&&void 0!==r[1]?r[1]:{};ar(t)&&(t=rc(null!==(e=t.getPeerId())&&void 0!==e?e:""));yield n.components.connectionManager.closeConnections(t,i)}))()}getPublicKey(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};if(n.log("getPublicKey %p",t),null!=t.publicKey)return t.publicKey;try{var i=yield n.peerStore.get(t);if(null!=i.id.publicKey)return i.id.publicKey}catch(e){if("NotFoundError"!==e.name)throw e}var o=_t([ot("/pk/"),t.toMultihash().bytes]),a=zl(yield n.contentRouting.get(o,e));return yield n.peerStore.patch(t,{publicKey:a}),a}))()}handle(t,r,n){var i=this;return e._asyncToGenerator((function*(){Array.isArray(t)||(t=[t]),yield Promise.all(t.map(function(){var t=e._asyncToGenerator((function*(e){yield i.components.registrar.handle(e,r,n)}));return function(e){return t.apply(this,arguments)}}()))}))()}unhandle(t){var r=this;return e._asyncToGenerator((function*(){Array.isArray(t)||(t=[t]),yield Promise.all(t.map(function(){var t=e._asyncToGenerator((function*(e){yield r.components.registrar.unhandle(e)}));return function(e){return t.apply(this,arguments)}}()))}))()}register(t,r){var n=this;return e._asyncToGenerator((function*(){return n.components.registrar.register(t,r)}))()}unregister(e){this.components.registrar.unregister(e)}isDialable(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};return n.components.connectionManager.isDialable(t,e)}))()}}function dz(e){var{detail:t}=e;t.id.toString()!==this.peerId.toString()?this.components.peerStore.merge(t.id,{multiaddrs:t.multiaddrs}).catch((e=>{this.log.error(e)})):this.log.error("peer discovery mechanism discovered self")}function hz(){return pz.apply(this,arguments)}function pz(){return pz=e._asyncToGenerator((function*(){var t,r=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};null!==(t=r.privateKey)&&void 0!==t||(r.privateKey=yield Fl("Ed25519"));var n=new uz(e._objectSpread2(e._objectSpread2({},yield function(e){return Oj.apply(this,arguments)}(r)),{},{peerId:ic(r.privateKey)}));return!1!==r.start&&(yield n.start()),n})),pz.apply(this,arguments)}function fz(){return fz=e._asyncToGenerator((function*(t){var r,n,i=null!==(r=t.libp2p)&&void 0!==r?r:{};null==i.privateKey&&null!=t.datastore&&(i.privateKey=yield function(e){return Tj.apply(this,arguments)}(t.datastore,t.keychain));var o=xj(i);return o.datastore=null!==(n=o.datastore)&&void 0!==n?n:t.datastore,yield hz(e._objectSpread2(e._objectSpread2(e._objectSpread2({},o),i),{},{start:!1}))})),fz.apply(this,arguments)}function vz(){return vz=e._asyncToGenerator((function*(){var t,r,n,i,o,a=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{},s=null!==(t=a.datastore)&&void 0!==t?t:new Wc,l=null!==(r=a.blockstore)&&void 0!==r?r:new Du;o=function(e){if(null==e)return!1;return["dial","dialProtocol","hangUp","handle","unhandle","getMultiaddrs","getProtocols"].every((t=>"function"==typeof e[t]))}(a.libp2p)?a.libp2p:yield function(e){return fz.apply(this,arguments)}(e._objectSpread2(e._objectSpread2({},a),{},{libp2p:e._objectSpread2(e._objectSpread2({dns:a.dns},a.libp2p),{},{start:void 0}),datastore:s}));var c=new wG(e._objectSpread2(e._objectSpread2({},a),{},{libp2p:o,datastore:s,blockstore:l,blockBrokers:null!==(n=a.blockBrokers)&&void 0!==n?n:[eD(),EN()],routers:null!==(i=a.routers)&&void 0!==i?i:[mG(o),yG()],metrics:o.metrics}));return!1!==a.start&&(yield c.start()),c})),vz.apply(this,arguments)}function yz(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return r=Number(r),null!=t[Symbol.asyncIterator]?e._wrapAsyncGenerator((function*(){var n=[];if(r<1&&(r=1),r!==Math.round(r))throw new Error("Batch size must be an integer");var i,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t);o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c=s.value;for(n.push(c);n.length>=r;)yield n.slice(0,r),n=n.slice(r)}}catch(e){a=!0,i=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw i}}for(;n.length>0;)yield n.slice(0,r),n=n.slice(r)}))():function*(){var e=[];if(r<1&&(r=1),r!==Math.round(r))throw new Error("Batch size must be an integer");for(var n of t)for(e.push(n);e.length>=r;)yield e.slice(0,r),e=e.slice(r);for(;e.length>0;)yield e.slice(0,r),e=e.slice(r)}()}function gz(e){return mz.apply(this,arguments)}function mz(){return mz=e._wrapAsyncGenerator((function(t){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:1;return function*(){var n,i=!1,o=!1;try{for(var a,s=e._asyncIterator(yz(t,r));i=!(a=yield e._awaitAsyncGenerator(s.next())).done;i=!1)for(var l=a.value.map(function(){var t=e._asyncToGenerator((function*(e){return e().then((e=>({ok:!0,value:e})),(e=>({ok:!1,err:e})))}));return function(e){return t.apply(this,arguments)}}()),c=0;c<l.length;c++){var u=yield e._awaitAsyncGenerator(l[c]);if(!u.ok)throw u.err;yield u.value}}catch(e){o=!0,n=e}finally{try{i&&null!=s.return&&(yield e._awaitAsyncGenerator(s.return()))}finally{if(o)throw n}}}()})),mz.apply(this,arguments)}var wz,bz,_z,Sz=function(){var t,r=null!==(t=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}).chunkSize)&&void 0!==t?t:262144;return function(){var t=e._wrapAsyncGenerator((function*(t){var n,i=new Fa,o=0,a=!1,s=!1,l=!1;try{for(var c,u=e._asyncIterator(t);s=!(c=yield e._awaitAsyncGenerator(u.next())).done;s=!1){var d=c.value;for(i.append(d),o+=d.length;o>=r;)if(yield i.slice(0,r),a=!0,r===i.length)i=new Fa,o=0;else{var h=new Fa;h.append(i.sublist(r)),i=h,o-=r}}}catch(e){l=!0,n=e}finally{try{s&&null!=u.return&&(yield e._awaitAsyncGenerator(u.return()))}finally{if(l)throw n}}(!a||o>0)&&(yield i.subarray(0,o))}));return function(e){return t.apply(this,arguments)}}()};class Pz extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid type"),e._defineProperty(this,"name",Pz.name),e._defineProperty(this,"code",Pz.code)}}e._defineProperty(Pz,"name","InvalidTypeError"),e._defineProperty(Pz,"code","ERR_INVALID_TYPE"),function(e){var t,r,n;(t=e.DataType||(e.DataType={})).Raw="Raw",t.Directory="Directory",t.File="File",t.Metadata="Metadata",t.Symlink="Symlink",t.HAMTShard="HAMTShard",function(e){e[e.Raw=0]="Raw",e[e.Directory=1]="Directory",e[e.File=2]="File",e[e.Metadata=3]="Metadata",e[e.Symlink=4]="Symlink",e[e.HAMTShard=5]="HAMTShard"}(r||(r={})),function(e){e.codec=()=>pl(r)}(e.DataType||(e.DataType={})),e.codec=()=>(null==n&&(n=fl((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};if(!1!==n.lengthDelimited&&r.fork(),null!=t.Type&&(r.uint32(8),e.DataType.codec().encode(t.Type,r)),null!=t.Data&&(r.uint32(18),r.bytes(t.Data)),null!=t.filesize&&(r.uint32(24),r.uint64(t.filesize)),null!=t.blocksizes)for(var i of t.blocksizes)r.uint32(32),r.uint64(i);null!=t.hashType&&(r.uint32(40),r.uint64(t.hashType)),null!=t.fanout&&(r.uint32(48),r.uint64(t.fanout)),null!=t.mode&&(r.uint32(56),r.uint32(t.mode)),null!=t.mtime&&(r.uint32(66),bz.codec().encode(t.mtime,r)),!1!==n.lengthDelimited&&r.ldelim()}),((t,r)=>{for(var n={blocksizes:[]},i=null==r?t.len:t.pos+r;t.pos<i;){var o=t.uint32();switch(o>>>3){case 1:n.Type=e.DataType.codec().decode(t);break;case 2:n.Data=t.bytes();break;case 3:n.filesize=t.uint64();break;case 4:n.blocksizes.push(t.uint64());break;case 5:n.hashType=t.uint64();break;case 6:n.fanout=t.uint64();break;case 7:n.mode=t.uint32();break;case 8:n.mtime=bz.codec().decode(t,t.uint32());break;default:t.skipType(7&o)}}return n}))),n),e.encode=t=>dl(t,e.codec()),e.decode=t=>Vs(t,e.codec())}(wz||(wz={})),function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.Seconds&&(t.uint32(8),t.int64(e.Seconds)),null!=e.FractionalNanoseconds&&(t.uint32(21),t.fixed32(e.FractionalNanoseconds)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{for(var r={},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();switch(i>>>3){case 1:r.Seconds=e.int64();break;case 2:r.FractionalNanoseconds=e.fixed32();break;default:e.skipType(7&i)}}return r}))),t),e.encode=t=>dl(t,e.codec()),e.decode=t=>Vs(t,e.codec())}(bz||(bz={})),function(e){var t;e.codec=()=>(null==t&&(t=fl((function(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};!1!==r.lengthDelimited&&t.fork(),null!=e.MimeType&&(t.uint32(10),t.string(e.MimeType)),!1!==r.lengthDelimited&&t.ldelim()}),((e,t)=>{for(var r={},n=null==t?e.len:e.pos+t;e.pos<n;){var i=e.uint32();if(i>>>3==1)r.MimeType=e.string();else e.skipType(7&i)}return r}))),t),e.encode=t=>dl(t,e.codec()),e.decode=t=>Vs(t,e.codec())}(_z||(_z={}));var Ez={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},Az=["directory","hamt-sharded-directory"],kz=parseInt("0644",8),xz=parseInt("0755",8);let Tz=class t{static unmarshal(e){var r,n,i=wz.decode(e),o=new t({type:Ez[null!=i.Type?i.Type.toString():"File"],data:i.Data,blockSizes:i.blocksizes,mode:i.mode,mtime:null!=i.mtime?{secs:null!==(r=i.mtime.Seconds)&&void 0!==r?r:0n,nsecs:i.mtime.FractionalNanoseconds}:void 0,fanout:i.fanout});return o._originalMode=null!==(n=i.mode)&&void 0!==n?n:0,o}constructor(){var t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{type:"file"};e._defineProperty(this,"type",void 0),e._defineProperty(this,"data",void 0),e._defineProperty(this,"blockSizes",void 0),e._defineProperty(this,"hashType",void 0),e._defineProperty(this,"fanout",void 0),e._defineProperty(this,"mtime",void 0),e._defineProperty(this,"_mode",void 0),e._defineProperty(this,"_originalMode",void 0);var{type:r,data:n,blockSizes:i,hashType:o,fanout:a,mtime:s,mode:l}=t;if(null!=r&&!Object.values(Ez).includes(r))throw new Pz("Type: "+r+" is not valid");this.type=null!=r?r:"file",this.data=n,this.hashType=o,this.fanout=a,this.blockSizes=null!=i?i:[],this._originalMode=0,this.mode=l,this.mtime=s}set mode(e){this._mode=null==e?this.isDirectory()?xz:kz:4095&e}get mode(){return this._mode}isDirectory(){return Az.includes(this.type)}addBlockSize(e){this.blockSizes.push(e)}removeBlockSize(e){this.blockSizes.splice(e,1)}fileSize(){if(this.isDirectory())return 0n;var e=0n;return this.blockSizes.forEach((t=>{e+=t})),null!=this.data&&(e+=BigInt(this.data.length)),e}marshal(){var e;switch(this.type){case"raw":e=wz.DataType.Raw;break;case"directory":e=wz.DataType.Directory;break;case"file":e=wz.DataType.File;break;case"metadata":e=wz.DataType.Metadata;break;case"symlink":e=wz.DataType.Symlink;break;case"hamt-sharded-directory":e=wz.DataType.HAMTShard;break;default:throw new Pz("Type: ".concat(e," is not valid"))}var t,r,n,i=this.data;(null!=this.data&&0!==this.data.length||(i=void 0),null!=this.mode)&&((t=4294963200&this._originalMode|(null!==(r=this.mode)&&void 0!==r?r:0))!==kz||this.isDirectory()||(t=void 0),t===xz&&this.isDirectory()&&(t=void 0));return null!=this.mtime&&(n={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),wz.encode({Type:e,Data:i,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:t,mtime:n})}};var Iz=function(){var t=e._asyncToGenerator((function*(e,t,r){null==r.codec&&(r.codec=iN);var n=yield De.digest(e),i=je.create(r.cidVersion,r.codec.code,n);return yield t.put(i,e,r),i}));return function(e,r,n){return t.apply(this,arguments)}}();function Cz(t){return function(){var r=e._wrapAsyncGenerator((function*(r,n){var i,o=0n,a=!1,s=!1;try{for(var l,c=function*(){var i=l.value;yield e._asyncToGenerator((function*(){var e,a,s={codec:iN,cidVersion:t.cidVersion,onProgress:t.onProgress};t.rawLeaves?(s.codec=ne,s.cidVersion=1):(a=new Tz({type:t.leafType,data:i}),i=rN({Data:a.marshal(),Links:[]}));var l=yield Iz(i,n,s);return o+=BigInt(i.byteLength),null===(e=t.onProgress)||void 0===e||e.call(t,new Ih("unixfs:importer:progress:file:write",{bytesWritten:o,cid:l,path:r.path})),{cid:l,unixfs:a,size:BigInt(i.length),block:i}}))},u=e._asyncIterator(r.content);a=!(l=yield e._awaitAsyncGenerator(u.next())).done;a=!1)yield*c()}catch(e){s=!0,i=e}finally{try{a&&null!=u.return&&(yield e._awaitAsyncGenerator(u.return()))}finally{if(s)throw i}}}));return function(e,t){return r.apply(this,arguments)}}()}let Bz=class t extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid parameters"),e._defineProperty(this,"name",t.name),e._defineProperty(this,"code",t.code)}};e._defineProperty(Bz,"name","InvalidParametersError"),e._defineProperty(Bz,"code","ERR_INVALID_PARAMS");class Nz extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid avg chunk size"),e._defineProperty(this,"name",Nz.name),e._defineProperty(this,"code",Nz.code)}}e._defineProperty(Nz,"name","InvalidAvgChunkSizeError"),e._defineProperty(Nz,"code","ERR_INVALID_AVG_CHUNK_SIZE");class Dz extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid chunk size"),e._defineProperty(this,"name",Dz.name),e._defineProperty(this,"code",Dz.code)}}e._defineProperty(Dz,"name","InvalidChunkSizeError"),e._defineProperty(Dz,"code","ERR_INVALID_CHUNK_SIZE");class Gz extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid min chunk size"),e._defineProperty(this,"name",Gz.name),e._defineProperty(this,"code",Gz.code)}}e._defineProperty(Gz,"name","InvalidMinChunkSizeError"),e._defineProperty(Gz,"code","ERR_INVALID_MIN_CHUNK_SIZE");class Rz extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid content"),e._defineProperty(this,"name",Rz.name),e._defineProperty(this,"code",Rz.code)}}e._defineProperty(Rz,"name","InvalidContentError"),e._defineProperty(Rz,"code","ERR_INVALID_CONTENT");var Oz=function(){var t=e._asyncToGenerator((function*(e,t,r){var n=new Tz({type:"directory",mtime:e.mtime,mode:e.mode}),i=rN(XB({Data:n.marshal()}));return{cid:yield Iz(i,t,r),path:e.path,unixfs:n,size:BigInt(i.length),originalPath:e.originalPath,block:i}}));return function(e,r,n){return t.apply(this,arguments)}}();function Lz(){return Lz=e._wrapAsyncGenerator((function*(t,r,n){var i,o,a=-1,s=!1,l=!1;try{for(var c,u=e._asyncIterator(gz(n.bufferImporter(t,r),n.blockWriteConcurrency));s=!(c=yield e._awaitAsyncGenerator(u.next())).done;s=!1){var d=c.value;0!==++a?(1===a&&null!=i&&(yield e._objectSpread2(e._objectSpread2({},i),{},{block:void 0,single:void 0}),i=void 0),yield e._objectSpread2(e._objectSpread2({},d),{},{block:void 0})):i=e._objectSpread2(e._objectSpread2({},d),{},{single:!0})}}catch(e){l=!0,o=e}finally{try{s&&null!=u.return&&(yield e._awaitAsyncGenerator(u.return()))}finally{if(l)throw o}}null!=i&&(yield i)})),Lz.apply(this,arguments)}function Mz(e){return!0===e.single}var jz=(t,r,n)=>{var i=function(){var i=e._asyncToGenerator((function*(i){var o;if(1===i.length&&Mz(i[0])&&n.reduceSingleLeafToSelf){var a,s=i[0],l=s.block;return!Mz(s)||void 0===t.mtime&&void 0===t.mode||(s.unixfs=new Tz({type:"file",mtime:t.mtime,mode:t.mode,data:s.block}),l={Data:s.unixfs.marshal(),Links:[]},s.block=rN(XB(l)),s.cid=yield Iz(s.block,r,e._objectSpread2(e._objectSpread2({},n),{},{cidVersion:n.cidVersion})),s.size=BigInt(s.block.length)),null===(a=n.onProgress)||void 0===a||a.call(n,new Ih("unixfs:importer:progress:file:layout",{cid:s.cid,path:s.originalPath})),{cid:s.cid,path:t.path,unixfs:s.unixfs,size:s.size,originalPath:s.originalPath}}var c=new Tz({type:"file",mtime:t.mtime,mode:t.mode}),u=i.filter((e=>{var t;return e.cid.code===re&&e.size>0||(null!=e.unixfs&&null==e.unixfs.data&&e.unixfs.fileSize()>0n||Boolean(null===(t=e.unixfs)||void 0===t||null===(t=t.data)||void 0===t?void 0:t.length))})).map((e=>{var t,r,n;if(e.cid.code===re)return c.addBlockSize(e.size),{Name:"",Tsize:Number(e.size),Hash:e.cid};null==(null===(t=e.unixfs)||void 0===t?void 0:t.data)?c.addBlockSize(null!==(r=null===(n=e.unixfs)||void 0===n?void 0:n.fileSize())&&void 0!==r?r:0n):c.addBlockSize(BigInt(e.unixfs.data.length));return{Name:"",Tsize:Number(e.size),Hash:e.cid}})),d={Data:c.marshal(),Links:u},h=rN(XB(d)),p=yield Iz(h,r,n);return null===(o=n.onProgress)||void 0===o||o.call(n,new Ih("unixfs:importer:progress:file:layout",{cid:p,path:t.originalPath})),{cid:p,path:t.path,unixfs:c,size:BigInt(h.length+d.Links.reduce(((e,t)=>{var r;return e+(null!==(r=t.Tsize)&&void 0!==r?r:0)}),0)),originalPath:t.originalPath,block:h}}));return function(e){return i.apply(this,arguments)}}();return i},Fz=function(){var t=e._asyncToGenerator((function*(e,t,r){return r.layout(function(e,t,r){return Lz.apply(this,arguments)}(e,t,r),jz(e,t,r))}));return function(e,r,n){return t.apply(this,arguments)}}();function Uz(t){try{if(t instanceof Uint8Array)return e._wrapAsyncGenerator((function*(){yield t}))();if(r=t,Symbol.iterator in r)return e._wrapAsyncGenerator((function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(t),e._awaitAsyncGenerator)}))();if(function(e){return Symbol.asyncIterator in e}(t))return t}catch(e){throw new Rz("Content was invalid")}var r;throw new Rz("Content was invalid")}var zz=()=>function(){var t=e._wrapAsyncGenerator((function*(t){var r,n=!1,i=!1;try{for(var o,a=e._asyncIterator(t);n=!(o=yield e._awaitAsyncGenerator(a.next())).done;n=!1){var s=o.value;if(void 0===s.length)throw new Rz("Content was invalid");if("string"==typeof s||s instanceof String)yield ot(s.toString());else if(Array.isArray(s))yield Uint8Array.from(s);else{if(!(s instanceof Uint8Array))throw new Rz("Content was invalid");yield s}}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield e._awaitAsyncGenerator(a.return()))}finally{if(i)throw r}}}));return function(e){return t.apply(this,arguments)}}();function Vz(t){var r,n=null!==(r=null==t?void 0:t.maxChildrenPerNode)&&void 0!==r?r:174;return function(){var t=e._asyncToGenerator((function*(t,i){var o,a=[],s=!1,l=!1;try{for(var c,u=e._asyncIterator(yz(t,n));s=!(c=yield u.next()).done;s=!1){var d=c.value;a.push(yield i(d))}}catch(e){l=!0,o=e}finally{try{s&&null!=u.return&&(yield u.return())}finally{if(l)throw o}}return a.length>1?r(a,i):a[0]}));function r(e,r){return t.apply(this,arguments)}return r}()}let qz=class{constructor(t,r){e._defineProperty(this,"options",void 0),e._defineProperty(this,"root",void 0),e._defineProperty(this,"dir",void 0),e._defineProperty(this,"path",void 0),e._defineProperty(this,"dirty",void 0),e._defineProperty(this,"flat",void 0),e._defineProperty(this,"parent",void 0),e._defineProperty(this,"parentKey",void 0),e._defineProperty(this,"unixfs",void 0),e._defineProperty(this,"mode",void 0),e._defineProperty(this,"mtime",void 0),e._defineProperty(this,"cid",void 0),e._defineProperty(this,"size",void 0),e._defineProperty(this,"nodeSize",void 0),this.options=null!=r?r:{},this.root=t.root,this.dir=t.dir,this.path=t.path,this.dirty=t.dirty,this.flat=t.flat,this.parent=t.parent,this.parentKey=t.parentKey,this.unixfs=t.unixfs,this.mode=t.mode,this.mtime=t.mtime}};var Hz=je.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),Kz=je.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi");class Wz extends qz{constructor(t,r){super(t,r),e._defineProperty(this,"_children",void 0),this._children=new Map}put(t,r){var n=this;return e._asyncToGenerator((function*(){n.cid=void 0,n.size=void 0,n.nodeSize=void 0,n._children.set(t,r)}))()}get(t){var r=this;return e._asyncToGenerator((function*(){return Promise.resolve(r._children.get(t))}))()}childCount(){return this._children.size}directChildrenCount(){return this.childCount()}onlyChild(){return this._children.values().next().value}eachChildSeries(){var t=this;return e._wrapAsyncGenerator((function*(){for(var[e,r]of t._children.entries())yield{key:e,child:r}}))()}estimateNodeSize(){if(void 0!==this.nodeSize)return this.nodeSize;for(var[e,t]of(this.nodeSize=0,this._children.entries()))null!=t.size&&null!=t.cid&&(this.nodeSize+=e.length+(1===this.options.cidVersion?Kz.bytes.byteLength:Hz.bytes.byteLength));return this.nodeSize}flush(t){var r=this;return e._wrapAsyncGenerator((function*(){var n=[];for(var[i,o]of r._children.entries()){var a=o;if(o instanceof qz){var s,l=!1,c=!1;try{for(var u,d=e._asyncIterator(o.flush(t));l=!(u=yield e._awaitAsyncGenerator(d.next())).done;l=!1){var h=u.value;a=h,yield h}}catch(e){c=!0,s=e}finally{try{l&&null!=d.return&&(yield e._awaitAsyncGenerator(d.return()))}finally{if(c)throw s}}}null!=a.size&&null!=a.cid&&n.push({Name:i,Tsize:Number(a.size),Hash:a.cid})}var p=new Tz({type:"directory",mtime:r.mtime,mode:r.mode}),f={Data:p.marshal(),Links:n},v=rN(XB(f)),y=yield e._awaitAsyncGenerator(Iz(v,t,r.options)),g=v.length+f.Links.reduce(((e,t)=>{var r;return e+(null!==(r=t.Tsize)&&void 0!==r?r:0)}),0);r.cid=y,r.size=g,yield{cid:y,unixfs:p,path:r.path,size:BigInt(g)}}))()}}var Qz,Yz,Jz,Zz={exports:{}};var $z=Jz?Yz:(Jz=1,Qz||(Qz=1,function(e,t){!function(r,n){var i={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function o(e){if(!Array.isArray(e)&&!ArrayBuffer.isView(e))return!1;for(var t=0;t<e.length;t++)if(!Number.isInteger(e[t])||e[t]<0||e[t]>255)return!1;return!0}function a(e,t){return(65535&e)*t+(((e>>>16)*t&65535)<<16)}function s(e,t){return e<<t|e>>>32-t}function l(e){return e=a(e^=e>>>16,2246822507),(e=a(e^=e>>>13,3266489909))^e>>>16}function c(e,t){e=[e[0]>>>16,65535&e[0],e[1]>>>16,65535&e[1]],t=[t[0]>>>16,65535&t[0],t[1]>>>16,65535&t[1]];var r=[0,0,0,0];return r[3]+=e[3]+t[3],r[2]+=r[3]>>>16,r[3]&=65535,r[2]+=e[2]+t[2],r[1]+=r[2]>>>16,r[2]&=65535,r[1]+=e[1]+t[1],r[0]+=r[1]>>>16,r[1]&=65535,r[0]+=e[0]+t[0],r[0]&=65535,[r[0]<<16|r[1],r[2]<<16|r[3]]}function u(e,t){e=[e[0]>>>16,65535&e[0],e[1]>>>16,65535&e[1]],t=[t[0]>>>16,65535&t[0],t[1]>>>16,65535&t[1]];var r=[0,0,0,0];return r[3]+=e[3]*t[3],r[2]+=r[3]>>>16,r[3]&=65535,r[2]+=e[2]*t[3],r[1]+=r[2]>>>16,r[2]&=65535,r[2]+=e[3]*t[2],r[1]+=r[2]>>>16,r[2]&=65535,r[1]+=e[1]*t[3],r[0]+=r[1]>>>16,r[1]&=65535,r[1]+=e[2]*t[2],r[0]+=r[1]>>>16,r[1]&=65535,r[1]+=e[3]*t[1],r[0]+=r[1]>>>16,r[1]&=65535,r[0]+=e[0]*t[3]+e[1]*t[2]+e[2]*t[1]+e[3]*t[0],r[0]&=65535,[r[0]<<16|r[1],r[2]<<16|r[3]]}function d(e,t){return 32==(t%=64)?[e[1],e[0]]:t<32?[e[0]<<t|e[1]>>>32-t,e[1]<<t|e[0]>>>32-t]:(t-=32,[e[1]<<t|e[0]>>>32-t,e[0]<<t|e[1]>>>32-t])}function h(e,t){return 0==(t%=64)?e:t<32?[e[0]<<t|e[1]>>>32-t,e[1]<<t]:[e[1]<<t-32,0]}function p(e,t){return[e[0]^t[0],e[1]^t[1]]}function f(e){return e=p(e,[0,e[0]>>>1]),e=p(e=u(e,[4283543511,3981806797]),[0,e[0]>>>1]),p(e=u(e,[3301882366,444984403]),[0,e[0]>>>1])}i.x86.hash32=function(e,t){if(i.inputValidation&&!o(e))return n;t=t||0;for(var r=e.length%4,c=e.length-r,u=t,d=0,h=3432918353,p=461845907,f=0;f<c;f+=4)d=a(d=e[f]|e[f+1]<<8|e[f+2]<<16|e[f+3]<<24,h),d=a(d=s(d,15),p),u=a(u=s(u^=d,13),5)+3864292196;switch(d=0,r){case 3:d^=e[f+2]<<16;case 2:d^=e[f+1]<<8;case 1:d=a(d^=e[f],h),u^=d=a(d=s(d,15),p)}return(u=l(u^=e.length))>>>0},i.x86.hash128=function(e,t){if(i.inputValidation&&!o(e))return n;t=t||0;for(var r=e.length%16,c=e.length-r,u=t,d=t,h=t,p=t,f=0,v=0,y=0,g=0,m=597399067,w=2869860233,b=951274213,_=2716044179,S=0;S<c;S+=16)f=e[S]|e[S+1]<<8|e[S+2]<<16|e[S+3]<<24,v=e[S+4]|e[S+5]<<8|e[S+6]<<16|e[S+7]<<24,y=e[S+8]|e[S+9]<<8|e[S+10]<<16|e[S+11]<<24,g=e[S+12]|e[S+13]<<8|e[S+14]<<16|e[S+15]<<24,f=s(f=a(f,m),15),u=s(u^=f=a(f,w),19),u=a(u+=d,5)+1444728091,v=s(v=a(v,w),16),d=s(d^=v=a(v,b),17),d=a(d+=h,5)+197830471,y=s(y=a(y,b),17),h=s(h^=y=a(y,_),15),h=a(h+=p,5)+2530024501,g=s(g=a(g,_),18),p=s(p^=g=a(g,m),13),p=a(p+=u,5)+850148119;switch(f=0,v=0,y=0,g=0,r){case 15:g^=e[S+14]<<16;case 14:g^=e[S+13]<<8;case 13:g=a(g^=e[S+12],_),p^=g=a(g=s(g,18),m);case 12:y^=e[S+11]<<24;case 11:y^=e[S+10]<<16;case 10:y^=e[S+9]<<8;case 9:y=a(y^=e[S+8],b),h^=y=a(y=s(y,17),_);case 8:v^=e[S+7]<<24;case 7:v^=e[S+6]<<16;case 6:v^=e[S+5]<<8;case 5:v=a(v^=e[S+4],w),d^=v=a(v=s(v,16),b);case 4:f^=e[S+3]<<24;case 3:f^=e[S+2]<<16;case 2:f^=e[S+1]<<8;case 1:f=a(f^=e[S],m),u^=f=a(f=s(f,15),w)}return u^=e.length,u+=d^=e.length,u+=h^=e.length,d+=u+=p^=e.length,h+=u,p+=u,u=l(u),u+=d=l(d),u+=h=l(h),d+=u+=p=l(p),h+=u,p+=u,("00000000"+(u>>>0).toString(16)).slice(-8)+("00000000"+(d>>>0).toString(16)).slice(-8)+("00000000"+(h>>>0).toString(16)).slice(-8)+("00000000"+(p>>>0).toString(16)).slice(-8)},i.x64.hash128=function(e,t){if(i.inputValidation&&!o(e))return n;t=t||0;for(var r=e.length%16,a=e.length-r,s=[0,t],l=[0,t],v=[0,0],y=[0,0],g=[2277735313,289559509],m=[1291169091,658871167],w=0;w<a;w+=16)v=[e[w+4]|e[w+5]<<8|e[w+6]<<16|e[w+7]<<24,e[w]|e[w+1]<<8|e[w+2]<<16|e[w+3]<<24],y=[e[w+12]|e[w+13]<<8|e[w+14]<<16|e[w+15]<<24,e[w+8]|e[w+9]<<8|e[w+10]<<16|e[w+11]<<24],v=d(v=u(v,g),31),s=c(s=d(s=p(s,v=u(v,m)),27),l),s=c(u(s,[0,5]),[0,1390208809]),y=d(y=u(y,m),33),l=c(l=d(l=p(l,y=u(y,g)),31),s),l=c(u(l,[0,5]),[0,944331445]);switch(v=[0,0],y=[0,0],r){case 15:y=p(y,h([0,e[w+14]],48));case 14:y=p(y,h([0,e[w+13]],40));case 13:y=p(y,h([0,e[w+12]],32));case 12:y=p(y,h([0,e[w+11]],24));case 11:y=p(y,h([0,e[w+10]],16));case 10:y=p(y,h([0,e[w+9]],8));case 9:y=u(y=p(y,[0,e[w+8]]),m),l=p(l,y=u(y=d(y,33),g));case 8:v=p(v,h([0,e[w+7]],56));case 7:v=p(v,h([0,e[w+6]],48));case 6:v=p(v,h([0,e[w+5]],40));case 5:v=p(v,h([0,e[w+4]],32));case 4:v=p(v,h([0,e[w+3]],24));case 3:v=p(v,h([0,e[w+2]],16));case 2:v=p(v,h([0,e[w+1]],8));case 1:v=u(v=p(v,[0,e[w]]),g),s=p(s,v=u(v=d(v,31),m))}return s=c(s=p(s,[0,e.length]),l=p(l,[0,e.length])),l=c(l,s),s=c(s=f(s),l=f(l)),l=c(l,s),("00000000"+(s[0]>>>0).toString(16)).slice(-8)+("00000000"+(s[1]>>>0).toString(16)).slice(-8)+("00000000"+(l[0]>>>0).toString(16)).slice(-8)+("00000000"+(l[1]>>>0).toString(16)).slice(-8)},e.exports&&(t=e.exports=i),t.murmurHash3=i}()}(Zz,Zz.exports)),Yz=Zz.exports),Xz=e.getDefaultExportFromCjs($z);Ce({name:"murmur3-32",code:35,encode:e=>function(e){for(var t=new Array(4),r=0;r<4;r++)t[r]=255&e,e>>=8;return new Uint8Array(t)}(Xz.x86.hash32(e))});var eV,tV,rV=Ce({name:"murmur3-128",code:34,encode:e=>r(Xz.x64.hash128(e))});Ce({name:"murmur3-x64-64",code:34,encode:e=>r(Xz.x64.hash128(e)).subarray(0,8)});var nV=function(){if(tV)return eV;function e(e,r){return e+t(r)}function t(e){var t=e;return 16843009*((t=(858993459&(t-=t>>1&1431655765))+(t>>2&858993459))+(t>>4)&252645135)>>24}function r(e,t){return e[0]-t[0]}function n(e){return e[1]}return tV=1,eV=class{constructor(){this._bitArrays=[],this._data=[],this._length=0,this._changedLength=!1,this._changedData=!1}set(e,t){var r=this._internalPositionFor(e,!1);if(void 0===t)-1!==r&&(this._unsetInternalPos(r),this._unsetBit(e),this._changedLength=!0,this._changedData=!0);else{var n=!1;-1===r?(r=this._data.length,this._setBit(e),this._changedData=!0):n=!0,this._setInternalPos(r,e,t,n),this._changedLength=!0}}unset(e){this.set(e,void 0)}get(e){this._sortData();var t=this._internalPositionFor(e,!0);if(-1!==t)return this._data[t][1]}push(e){return this.set(this.length,e),this.length}get length(){if(this._sortData(),this._changedLength){var e=this._data[this._data.length-1];this._length=e?e[0]+1:0,this._changedLength=!1}return this._length}forEach(e){for(var t=0;t<this.length;)e(this.get(t),t,this),t++}map(e){for(var t=0,r=new Array(this.length);t<this.length;)r[t]=e(this.get(t),t,this),t++;return r}reduce(e,t){for(var r=0,n=t;r<this.length;){n=e(n,this.get(r),r),r++}return n}find(e){for(var t,r,n=0;n<this.length&&!t;)t=e(r=this.get(n)),n++;return t?r:void 0}_internalPositionFor(r,n){var i=this._bytePosFor(r,n);if(i>=this._bitArrays.length)return-1;var o=this._bitArrays[i],a=r-7*i;return(o&1<<a)>0?this._bitArrays.slice(0,i).reduce(e,0)+t(o&~(4294967295<<a+1))-1:-1}_bytePosFor(e,t){for(var r=Math.floor(e/7),n=r+1;!t&&this._bitArrays.length<n;)this._bitArrays.push(0);return r}_setBit(e){var t=this._bytePosFor(e,!1);this._bitArrays[t]|=1<<e-7*t}_unsetBit(e){var t=this._bytePosFor(e,!1);this._bitArrays[t]&=~(1<<e-7*t)}_setInternalPos(e,t,r,n){var i=this._data,o=[t,r];if(n)this._sortData(),i[e]=o;else{if(i.length)if(i[i.length-1][0]>=t)i.push(o);else if(i[0][0]<=t)i.unshift(o);else{var a=Math.round(i.length/2);this._data=i.slice(0,a).concat(o).concat(i.slice(a))}else this._data.push(o);this._changedData=!0,this._changedLength=!0}}_unsetInternalPos(e){this._data.splice(e,1)}_sortData(){this._changedData&&this._data.sort(r),this._changedData=!1}bitField(){for(var e,t=[],r=8,n=0,i=0,o=this._bitArrays.slice();o.length||n;){0===n&&(e=o.shift(),n=7);var a=Math.min(n,r);i|=(e&~(255<<a))<<8-r,e>>>=a,n-=a,(r-=a)&&(n||o.length)||(t.push(i),i=0,r=8)}for(var s=t.length-1;s>0;s--){if(0!==t[s])break;t.pop()}return t}compactArray(){return this._sortData(),this._data.map(n)}},eV}(),iV=e.getDefaultExportFromCjs(nV);class oV{constructor(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:0;e._defineProperty(this,"_options",void 0),e._defineProperty(this,"_popCount",void 0),e._defineProperty(this,"_parent",void 0),e._defineProperty(this,"_posAtParent",void 0),e._defineProperty(this,"_children",void 0),e._defineProperty(this,"key",void 0),this._options=t,this._popCount=0,this._parent=r,this._posAtParent=n,this._children=new iV,this.key=null}put(t,r){var n=this;return e._asyncToGenerator((function*(){var e=yield n._findNewBucketAndPos(t);e.bucket._putAt(e,t,r)}))()}get(t){var r=this;return e._asyncToGenerator((function*(){var e=yield r._findChild(t);if(null!=e)return e.value}))()}del(t){var r=this;return e._asyncToGenerator((function*(){var e=yield r._findPlace(t),n=e.bucket._at(e.pos);null!=n&&n.key===t&&e.bucket._delAt(e.pos)}))()}leafCount(){return this._children.compactArray().reduce(((e,t)=>t instanceof oV?e+t.leafCount():e+1),0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){var e=this._children.compactArray();for(var t of e)t instanceof oV?yield*t.eachLeafSeries():yield t}serialize(e,t){return t(this._children.reduce(((r,n,i)=>(null!=n&&(n instanceof oV?r.push(n.serialize(e,t)):r.push(e(n,i))),r)),[]))}asyncTransform(t,r){var n=this;return e._asyncToGenerator((function*(){return cV(n,t,r)}))()}toJSON(){return this.serialize(sV,lV)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}_findChild(t){var r=this;return e._asyncToGenerator((function*(){var e=yield r._findPlace(t),n=e.bucket._at(e.pos);if(!(n instanceof oV))return null!=n&&n.key===t?n:void 0}))()}_findPlace(t){var r=this;return e._asyncToGenerator((function*(){var e=r._options.hash("string"==typeof t?ot(t):t),n=yield e.take(r._options.bits),i=r._children.get(n);return i instanceof oV?i._findPlace(e):{bucket:r,pos:n,hash:e,existingChild:i}}))()}_findNewBucketAndPos(t){var r=this;return e._asyncToGenerator((function*(){var e=yield r._findPlace(t);if(null!=e.existingChild&&e.existingChild.key!==t){var n=new oV(r._options,e.bucket,e.pos);e.bucket._putObjectAt(e.pos,n);var i=yield n._findPlace(e.existingChild.hash);return i.bucket._putAt(i,e.existingChild.key,e.existingChild.value),n._findNewBucketAndPos(e.hash)}return e}))()}_putAt(e,t,r){this._putObjectAt(e.pos,{key:t,value:r,hash:e.hash})}_putObjectAt(e,t){null==this._children.get(e)&&this._popCount++,this._children.set(e,t)}_delAt(e){if(-1===e)throw new Error("Invalid position");null!=this._children.get(e)&&this._popCount--,this._children.unset(e),this._level()}_level(){if(null!=this._parent&&this._popCount<=1)if(1===this._popCount){var e=this._children.find(aV);if(null!=e&&!(e instanceof oV)){var t=e.hash;t.untake(this._options.bits);var r={pos:this._posAtParent,hash:t,bucket:this._parent};this._parent._putAt(r,e.key,e.value)}}else this._parent._delAt(this._posAtParent)}_at(e){return this._children.get(e)}}function aV(e){return Boolean(e)}function sV(e,t){return e.key}function lV(e){return e}function cV(e,t,r){return uV.apply(this,arguments)}function uV(){return(uV=e._asyncToGenerator((function*(e,t,r){var n=[];for(var i of e._children.compactArray())if(i instanceof oV)yield cV(i,t,r);else{var o=yield t(i);n.push({bitField:e._children.bitField(),children:o})}return r(n)}))).apply(this,arguments)}var dV=[255,254,252,248,240,224,192,128],hV=[1,3,7,15,31,63,127,255];let pV=class{constructor(t){e._defineProperty(this,"_value",void 0),e._defineProperty(this,"_currentBytePos",void 0),e._defineProperty(this,"_currentBitPos",void 0),this._value=t,this._currentBytePos=t.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+8*this._currentBytePos}totalBits(){return 8*this._value.length}take(e){for(var t=e,r=0;t>0&&this._haveBits();){var n=this._value[this._currentBytePos],i=this._currentBitPos+1,o=Math.min(i,t);r=(r<<o)+fV(n,i-o,o),t-=o,this._currentBitPos-=o,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return r}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}};function fV(e,t,r){var n=function(e,t){return dV[e]&hV[Math.min(t+e-1,7)]}(t,r);return(e&n)>>>t}function vV(e){return function(t){return t instanceof yV?t:new yV(t,e)}}let yV=class{constructor(t,r){if(e._defineProperty(this,"_value",void 0),e._defineProperty(this,"_hashFn",void 0),e._defineProperty(this,"_depth",void 0),e._defineProperty(this,"_availableBits",void 0),e._defineProperty(this,"_currentBufferIndex",void 0),e._defineProperty(this,"_buffers",void 0),!(t instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=t,this._hashFn=r,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}take(t){var r=this;return e._asyncToGenerator((function*(){for(var e=t;r._availableBits<e;)yield r._produceMoreBits();for(var n=0;e>0;){var i=r._buffers[r._currentBufferIndex],o=Math.min(i.availableBits(),e);n=(n<<o)+i.take(o),e-=o,r._availableBits-=o,0===i.availableBits()&&r._currentBufferIndex++}return n}))()}untake(e){for(var t=e;t>0;){var r=this._buffers[this._currentBufferIndex],n=Math.min(r.totalBits()-r.availableBits(),t);r.untake(n),t-=n,this._availableBits+=n,this._currentBufferIndex>0&&r.totalBits()===r.availableBits()&&(this._depth--,this._currentBufferIndex--)}}_produceMoreBits(){var t=this;return e._asyncToGenerator((function*(){t._depth++;var e=t._depth>0?_t([t._value,Uint8Array.from([t._depth])]):t._value,r=yield t._hashFn(e),n=new pV(r);t._buffers.push(n),t._availableBits+=n.availableBits()}))()}};function gV(e){var t;if(null==e||null==e.hashFn)throw new Error("please define an options.hashFn");var r={bits:null!==(t=e.bits)&&void 0!==t?t:8,hash:vV(e.hashFn)};return new oV(r)}function mV(e){return wV.apply(this,arguments)}function wV(){return wV=e._asyncToGenerator((function*(e){return(yield rV.encode(e)).slice(0,8).reverse()})),wV.apply(this,arguments)}var bV=BigInt(34);let _V=class extends qz{constructor(t,r){var n;super(t,r),e._defineProperty(this,"_bucket",void 0),this._bucket=gV({hashFn:mV,bits:null!==(n=r.shardFanoutBits)&&void 0!==n?n:8})}put(t,r){var n=this;return e._asyncToGenerator((function*(){n.cid=void 0,n.size=void 0,n.nodeSize=void 0,yield n._bucket.put(t,r)}))()}get(t){var r=this;return e._asyncToGenerator((function*(){return r._bucket.get(t)}))()}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}eachChildSeries(){var t=this;return e._wrapAsyncGenerator((function*(){var r,n=!1,i=!1;try{for(var o,a=e._asyncIterator(t._bucket.eachLeafSeries());n=!(o=yield e._awaitAsyncGenerator(a.next())).done;n=!1){var{key:s,value:l}=o.value;yield{key:s,child:l}}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield e._awaitAsyncGenerator(a.return()))}finally{if(i)throw r}}}))()}estimateNodeSize(){return void 0!==this.nodeSize||(this.nodeSize=EV(this._bucket,this,this.options)),this.nodeSize}flush(t){var r=this;return e._wrapAsyncGenerator((function*(){var n,i=!1,o=!1;try{for(var a,s=e._asyncIterator(SV(r._bucket,t,r,r.options));i=!(a=yield e._awaitAsyncGenerator(s.next())).done;i=!1){var l=a.value;yield e._objectSpread2(e._objectSpread2({},l),{},{path:r.path})}}catch(e){o=!0,n=e}finally{try{i&&null!=s.return&&(yield e._awaitAsyncGenerator(s.return()))}finally{if(o)throw n}}}))()}};function SV(e,t,r,n){return PV.apply(this,arguments)}function PV(){return PV=e._wrapAsyncGenerator((function*(t,r,n,i){for(var o=t._children,a=(t.tableSize()-1).toString(16).length,s=[],l=0n,c=0;c<o.length;c++){var u=o.get(c);if(null!=u){var d=c.toString(16).toUpperCase().padStart(a,"0");if(u instanceof oV){var h,p=void 0,f=!1,v=!1;try{for(var y,g=e._asyncIterator(SV(u,r,null,i));f=!(y=yield e._awaitAsyncGenerator(g.next())).done;f=!1){p=y.value}}catch(e){v=!0,h=e}finally{try{f&&null!=g.return&&(yield e._awaitAsyncGenerator(g.return()))}finally{if(v)throw h}}if(null==p)throw new Error("Could not flush sharded directory, no subshard found");s.push({Name:d,Tsize:Number(p.size),Hash:p.cid}),l+=p.size}else if("function"==typeof u.value.flush){var m,w=u.value,b=void 0,_=!1,S=!1;try{for(var P,E=e._asyncIterator(w.flush(r));_=!(P=yield e._awaitAsyncGenerator(E.next())).done;_=!1){b=P.value,yield b}}catch(e){S=!0,m=e}finally{try{_&&null!=E.return&&(yield e._awaitAsyncGenerator(E.return()))}finally{if(S)throw m}}if(null==b)throw new Error("Did not flush dir");var A=d+u.key;s.push({Name:A,Tsize:Number(b.size),Hash:b.cid}),l+=b.size}else{var k=u.value;if(null==k.cid)continue;var x=d+u.key,T=k.size;s.push({Name:x,Tsize:Number(T),Hash:k.cid}),l+=BigInt(null!=T?T:0)}}}var I=Uint8Array.from(o.bitField().reverse()),C=new Tz({type:"hamt-sharded-directory",data:I,fanout:BigInt(t.tableSize()),hashType:bV,mtime:null==n?void 0:n.mtime,mode:null==n?void 0:n.mode}),B=rN(XB({Data:C.marshal(),Links:s})),N=yield e._awaitAsyncGenerator(Iz(B,r,i)),D=BigInt(B.byteLength)+l;yield{cid:N,unixfs:C,size:D}})),PV.apply(this,arguments)}function EV(e,t,r){for(var n=e._children,i=(e.tableSize()-1).toString(16).length,o=[],a=0;a<n.length;a++){var s=n.get(a);if(null!=s){var l=a.toString(16).toUpperCase().padStart(i,"0");if(s instanceof oV){var c=EV(s,null,r);o.push({Name:l,Tsize:Number(c),Hash:0===r.cidVersion?Hz:Kz})}else if("function"==typeof s.value.flush){var u=s.value.nodeSize();o.push({Name:l+s.key,Tsize:Number(u),Hash:0===r.cidVersion?Hz:Kz})}else{var d=s.value;if(null==d.cid)continue;var h=l+s.key,p=d.size;o.push({Name:h,Tsize:Number(p),Hash:d.cid})}}}var f=Uint8Array.from(n.bitField().reverse());return rN(XB({Data:new Tz({type:"hamt-sharded-directory",data:f,fanout:BigInt(e.tableSize()),hashType:bV,mtime:null==t?void 0:t.mtime,mode:null==t?void 0:t.mode}).marshal(),Links:o})).length}function AV(e,t,r,n){return kV.apply(this,arguments)}function kV(){return kV=e._asyncToGenerator((function*(e,t,r,n){var i=t;t instanceof Wz&&t.estimateNodeSize()>r&&(i=yield function(e,t){return xV.apply(this,arguments)}(t,n));var o=i.parent;if(null!=o){if(i!==t){if(null!=e&&(e.parent=i),null==i.parentKey)throw new Error("No parent key found");yield o.put(i.parentKey,i)}return AV(i,o,r,n)}return i})),kV.apply(this,arguments)}function xV(){return xV=e._asyncToGenerator((function*(t,r){var n,i=new _V({root:t.root,dir:!0,parent:t.parent,parentKey:t.parentKey,path:t.path,dirty:t.dirty,flat:!1,mtime:t.mtime,mode:t.mode},r),o=!1,a=!1;try{for(var s,l=e._asyncIterator(t.eachChildSeries());o=!(s=yield l.next()).done;o=!1){var{key:c,child:u}=s.value;yield i.put(c,u)}}catch(e){a=!0,n=e}finally{try{o&&null!=l.return&&(yield l.return())}finally{if(a)throw n}}return i})),xV.apply(this,arguments)}function TV(e,t,r){return IV.apply(this,arguments)}function IV(){return IV=e._asyncToGenerator((function*(e,t,r){for(var n,i=function(){return(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").split(/(?<!\\)\//).filter(Boolean)}(null!==(n=e.path)&&void 0!==n?n:""),o=i.length-1,a=t,s="",l=0;l<i.length;l++){var c=i[l];s+="".concat(""!==s?"/":"").concat(c);var u=l===o;if(a.dirty=!0,a.cid=void 0,a.size=void 0,u)yield a.put(c,e),t=yield AV(null,a,r.shardSplitThresholdBytes,r);else{var d,h,p=yield a.get(c);if(null==p||!(p instanceof qz))p=new Wz({root:!1,dir:!0,parent:a,parentKey:c,path:s,dirty:!0,flat:!0,mtime:null===(d=p)||void 0===d||null===(d=d.unixfs)||void 0===d?void 0:d.mtime,mode:null===(h=p)||void 0===h||null===(h=h.unixfs)||void 0===h?void 0:h.mode},r);yield a.put(c,p),a=p}}return t})),IV.apply(this,arguments)}function CV(e,t){return BV.apply(this,arguments)}function BV(){return BV=e._wrapAsyncGenerator((function*(t,r){var n;t instanceof qz?yield*e._asyncGeneratorDelegate(e._asyncIterator(t.flush(r))):!0===(null===(n=t.unixfs)||void 0===n?void 0:n.isDirectory())&&(yield t)})),BV.apply(this,arguments)}function NV(e,t){return DV.apply(this,arguments)}function DV(){return DV=e._wrapAsyncGenerator((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(i,o,a,s,l,c,u,d,h,p,f,v,y,g,m){var w;w=Symbol.asyncIterator in t||Symbol.iterator in t?t:[t];var b,_=null!==(i=n.wrapWithDirectory)&&void 0!==i&&i,S=null!==(o=n.shardSplitThresholdBytes)&&void 0!==o?o:262144,P=null!==(a=n.shardFanoutBits)&&void 0!==a?a:8,E=null!==(s=n.cidVersion)&&void 0!==s?s:1,A=null===(l=n.rawLeaves)||void 0===l||l,k=null!==(c=n.leafType)&&void 0!==c?c:"file",x=null!==(u=n.fileImportConcurrency)&&void 0!==u?u:50,T=null!==(d=n.blockWriteConcurrency)&&void 0!==d?d:10,I=null===(h=n.reduceSingleLeafToSelf)||void 0===h||h,C=null!==(p=n.chunker)&&void 0!==p?p:Sz(),B=null!==(f=n.chunkValidator)&&void 0!==f?f:zz(),N=null!==(v=n.dagBuilder)&&void 0!==v?v:function(t){return function(){var r=e._wrapAsyncGenerator((function*(r,n){var i,o=!1,a=!1;try{for(var s,l=function*(){var r,i=s.value;if(null!=i.path&&(r=i.path,i.path=i.path.split("/").filter((e=>null!=e&&"."!==e)).join("/")),function(e){return null!=e.content}(i)){var o={path:i.path,mtime:i.mtime,mode:i.mode,content:e._wrapAsyncGenerator((function*(){var r,n=0n,o=!1,a=!1;try{for(var s,l=e._asyncIterator(t.chunker(t.chunkValidator(Uz(i.content))));o=!(s=yield e._awaitAsyncGenerator(l.next())).done;o=!1){var c,u=s.value,d=BigInt(u.byteLength);n+=d,null===(c=t.onProgress)||void 0===c||c.call(t,new Ih("unixfs:importer:progress:file:read",{bytesRead:n,chunkSize:d,path:i.path})),yield u}}catch(e){a=!0,r=e}finally{try{o&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(a)throw r}}}))(),originalPath:r};yield e._asyncToGenerator((function*(){return Fz(o,n,t)}))}else{if(null==i.path)throw new Error("Import candidate must have content or path or both");var a={path:i.path,mtime:i.mtime,mode:i.mode,originalPath:r};yield e._asyncToGenerator((function*(){return Oz(a,n,t)}))}},c=e._asyncIterator(r);o=!(s=yield e._awaitAsyncGenerator(c.next())).done;o=!1)yield*l()}catch(e){a=!0,i=e}finally{try{o&&null!=c.return&&(yield e._awaitAsyncGenerator(c.return()))}finally{if(a)throw i}}}));return function(e,t){return r.apply(this,arguments)}}()}({chunker:C,chunkValidator:B,wrapWithDirectory:_,layout:null!==(y=n.layout)&&void 0!==y?y:Vz(),bufferImporter:null!==(g=n.bufferImporter)&&void 0!==g?g:Cz({cidVersion:E,rawLeaves:A,leafType:k,onProgress:n.onProgress}),blockWriteConcurrency:T,reduceSingleLeafToSelf:I,cidVersion:E,onProgress:n.onProgress}),D=null!==(m=n.treeBuilder)&&void 0!==m?m:function(t){return function(){var r=e._wrapAsyncGenerator((function*(r,n){var i,o,a=new Wz({root:!0,dir:!0,path:"",dirty:!0,flat:!0},t),s=!1,l=!1,c=!1;try{for(var u,d=e._asyncIterator(r);l=!(u=yield e._awaitAsyncGenerator(d.next())).done;l=!1){var h,p,f=u.value;if(null!=f){var v="".concat(null!==(h=f.originalPath)&&void 0!==h?h:"").split("/")[0];null!=v&&""!==v&&(null==i?(i=v,s=!0):i!==v&&(s=!1)),a=yield e._awaitAsyncGenerator(TV(f,a,t)),!0!==(null===(p=f.unixfs)||void 0===p?void 0:p.isDirectory())&&(yield f)}}}catch(e){c=!0,o=e}finally{try{l&&null!=d.return&&(yield e._awaitAsyncGenerator(d.return()))}finally{if(c)throw o}}if(t.wrapWithDirectory||s&&a.childCount()>1)yield*e._asyncGeneratorDelegate(e._asyncIterator(CV(a,n)));else{var y,g=!1,m=!1;try{for(var w,b=e._asyncIterator(a.eachChildSeries());g=!(w=yield e._awaitAsyncGenerator(b.next())).done;g=!1){var _=w.value;null!=_&&(yield*e._asyncGeneratorDelegate(e._asyncIterator(CV(_.child,n)),e._awaitAsyncGenerator))}}catch(e){m=!0,y=e}finally{try{g&&null!=b.return&&(yield e._awaitAsyncGenerator(b.return()))}finally{if(m)throw y}}}}));return function(e,t){return r.apply(this,arguments)}}()}({wrapWithDirectory:_,shardSplitThresholdBytes:S,shardFanoutBits:P,cidVersion:E,onProgress:n.onProgress}),G=!1,R=!1;try{for(var O,L=e._asyncIterator(D(gz(N(w,r),x),r));G=!(O=yield e._awaitAsyncGenerator(L.next())).done;G=!1){var M=O.value;yield{cid:M.cid,path:M.path,unixfs:M.unixfs,size:M.size}}}catch(e){R=!0,b=e}finally{try{G&&null!=L.return&&(yield e._awaitAsyncGenerator(L.return()))}finally{if(R)throw b}}}()})),DV.apply(this,arguments)}function GV(e,t){return RV.apply(this,arguments)}function RV(){return RV=e._asyncToGenerator((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=yield GD(NV([e],t,r));if(null==n)throw new Bz("Nothing imported");return n})),RV.apply(this,arguments)}function OV(){return OV=e._asyncToGenerator((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=yield GD(NV([e],t,r));if(null==n)throw new Bz("Nothing imported");return n})),OV.apply(this,arguments)}function LV(){return LV=e._asyncToGenerator((function*(e,t){return GV({content:e},t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})})),LV.apply(this,arguments)}function MV(){return MV=e._asyncToGenerator((function*(e,t){return GV({content:e},t,arguments.length>2&&void 0!==arguments[2]?arguments[2]:{})})),MV.apply(this,arguments)}var jV={cidVersion:1,rawLeaves:!0,layout:Vz({maxChildrenPerNode:1024}),chunker:Sz({chunkSize:1048576})};function FV(){return FV=e._wrapAsyncGenerator((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(NV(t,r,e._objectSpread2(e._objectSpread2({},jV),n))))}()})),FV.apply(this,arguments)}function UV(){return UV=e._asyncToGenerator((function*(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{cid:i}=yield function(e,t){return LV.apply(this,arguments)}(t,r,e._objectSpread2(e._objectSpread2({},jV),n));return i})),UV.apply(this,arguments)}function zV(){return zV=e._asyncToGenerator((function*(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{cid:i}=yield function(e,t){return MV.apply(this,arguments)}(t,r,e._objectSpread2(e._objectSpread2({},jV),n));return i})),zV.apply(this,arguments)}function VV(){return VV=e._asyncToGenerator((function*(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{cid:i}=yield GV(t,r,e._objectSpread2(e._objectSpread2({},jV),n));return i})),VV.apply(this,arguments)}function qV(){return qV=e._asyncToGenerator((function*(t,r){var n,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},{cid:o}=yield function(e,t){return OV.apply(this,arguments)}(e._objectSpread2(e._objectSpread2({},t),{},{path:null!==(n=t.path)&&void 0!==n?n:"-"}),r,e._objectSpread2(e._objectSpread2({},jV),i));return o})),qV.apply(this,arguments)}function HV(t){if(null!=t[Symbol.asyncIterator])return e._asyncToGenerator((function*(){var r,n,i=!1,o=!1;try{for(var a,s=e._asyncIterator(t);i=!(a=yield s.next()).done;i=!1){r=a.value}}catch(e){o=!0,n=e}finally{try{i&&null!=s.return&&(yield s.return())}finally{if(o)throw n}}return r}))();var r;for(var n of t)r=n;return r}class KV extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Bad path"),e._defineProperty(this,"name",KV.name),e._defineProperty(this,"code",KV.code)}}e._defineProperty(KV,"name","BadPathError"),e._defineProperty(KV,"code","ERR_BAD_PATH");class WV extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not found"),e._defineProperty(this,"name",WV.name),e._defineProperty(this,"code",WV.code)}}e._defineProperty(WV,"name","NotFoundError"),e._defineProperty(WV,"code","ERR_NOT_FOUND");class QV extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No resolver"),e._defineProperty(this,"name",QV.name),e._defineProperty(this,"code",QV.code)}}e._defineProperty(QV,"name","NoResolverError"),e._defineProperty(QV,"code","ERR_NO_RESOLVER");let YV=class t extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Not UnixFS"),e._defineProperty(this,"name",t.name),e._defineProperty(this,"code",t.code)}};e._defineProperty(YV,"name","NotUnixFSError"),e._defineProperty(YV,"code","ERR_NOT_UNIXFS");class JV extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Over read"),e._defineProperty(this,"name",JV.name),e._defineProperty(this,"code",JV.code)}}e._defineProperty(JV,"name","OverReadError"),e._defineProperty(JV,"code","ERR_OVER_READ");class ZV extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Under read"),e._defineProperty(this,"name",ZV.name),e._defineProperty(this,"code",ZV.code)}}e._defineProperty(ZV,"name","UnderReadError"),e._defineProperty(ZV,"code","ERR_UNDER_READ");class $V extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"No Property found"),e._defineProperty(this,"name",$V.name),e._defineProperty(this,"code",$V.code)}}e._defineProperty($V,"name","NoPropError"),e._defineProperty($V,"code","ERR_NO_PROP");let XV=class t extends Error{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"Invalid parameters"),e._defineProperty(this,"name",t.name),e._defineProperty(this,"code",t.code)}};function eq(t,r,n,i,o,a,s){for(var l,c=t,u=o;a.length>0;){var d=a[0];if(!(d in c))throw new $V("No property named ".concat(d," found in node ").concat(n));a.shift(),u="".concat(u,"/").concat(d);var h=je.asCID(c[d]);if(null!=h)return{entry:{type:"object",name:i,path:o,cid:n,node:r,depth:s,size:BigInt(r.length),content:function(){var r=e._wrapAsyncGenerator((function*(){yield t}));return function(){return r.apply(this,arguments)}}()},next:{cid:h,name:d,path:u,toResolve:a}};c=c[d]}return{entry:{type:"object",name:i,path:o,cid:n,node:r,depth:s,size:BigInt(r.length),content:(l=e._wrapAsyncGenerator((function*(){yield t})),function(){return l.apply(this,arguments)})}}}e._defineProperty(XV,"name","InvalidParametersError"),e._defineProperty(XV,"code","ERR_INVALID_PARAMS");var tq=function(){var t=e._asyncToGenerator((function*(e,t,r,n,i,o,a,s){var l=yield a.get(e,s);return eq(yB(l),l,e,t,r,n,o)}));return function(e,r,n,i,o,a,s,l){return t.apply(this,arguments)}}(),rq=function(){var t=e._asyncToGenerator((function*(e,t,r,n,i,o,a,s){var l=yield a.get(e,s);return eq(TB(l),l,e,t,r,n,o)}));return function(e,r,n,i,o,a,s,l){return t.apply(this,arguments)}}();function nq(e,t,r,n){var i=BigInt(e.length),o=BigInt(t+i);return r>=o||n<t?new Uint8Array(0):(n>=t&&n<o&&(e=e.subarray(0,Number(n-t))),r>=t&&r<o&&(e=e.subarray(Number(r-t))),e)}var iq=function(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:0,r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:e,n=BigInt(e),i=BigInt(null!=t?t:0),o=BigInt(r);if(o!==n&&(o=i+o),o>n&&(o=n),i<0n)throw new XV("Offset must be greater than or equal to 0");if(i>n)throw new XV("Offset must be less than the file size");if(o<0n)throw new XV("Length must be greater than or equal to 0");if(o>n)throw new XV("Length must be less than the file size");return{start:i,end:o}},oq=t=>{function r(){return r=e._wrapAsyncGenerator((function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(r){var{start:n,end:i}=iq(t.length,e.offset,e.length),o=nq(t,0n,n,i);null===(r=e.onProgress)||void 0===r||r.call(e,new Ih("unixfs:exporter:progress:identity",{bytesRead:BigInt(o.byteLength),totalBytes:i-n,fileSize:BigInt(t.byteLength)})),yield o}()})),r.apply(this,arguments)}return function(){return r.apply(this,arguments)}},aq=function(){var t=e._asyncToGenerator((function*(e,t,r,n,i,o,a,s){if(n.length>0)throw new WV("No link named ".concat(r," found in raw node ").concat(e));var l=Ae(e.multihash.bytes);return{entry:{type:"identity",name:t,path:r,cid:e,content:oq(l.digest),depth:o,size:BigInt(l.digest.length),node:l.digest}}}));return function(e,r,n,i,o,a,s,l){return t.apply(this,arguments)}}(),sq=function(){var t=e._asyncToGenerator((function*(e,t,r,n,i,o,a,s){var l=yield a.get(e,s);return eq(ee(l),l,e,t,r,n,o)}));return function(e,r,n,i,o,a,s,l){return t.apply(this,arguments)}}(),lq=t=>{function r(){return r=e._wrapAsyncGenerator((function(){var e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(r){var{start:n,end:i}=iq(t.length,e.offset,e.length),o=nq(t,0n,n,i);null===(r=e.onProgress)||void 0===r||r.call(e,new Ih("unixfs:exporter:progress:raw",{bytesRead:BigInt(o.byteLength),totalBytes:i-n,fileSize:BigInt(t.byteLength)})),yield o}()})),r.apply(this,arguments)}return function(){return r.apply(this,arguments)}},cq=function(){var t=e._asyncToGenerator((function*(e,t,r,n,i,o,a,s){if(n.length>0)throw new WV("No link named ".concat(r," found in raw node ").concat(e));var l=yield a.get(e,s);return{entry:{type:"raw",name:t,path:r,cid:e,content:lq(l),depth:o,size:BigInt(l.length),node:l}}}));return function(e,r,n,i,o,a,s,l){return t.apply(this,arguments)}}(),uq=function(){var t=e._asyncToGenerator((function*(e){return(yield rV.encode(e)).slice(0,8).reverse()}));return function(e){return t.apply(this,arguments)}}(),dq=function(){var t=e._asyncToGenerator((function*(t,r,n){var i=(r.tableSize()-1).toString(16).length;yield Promise.all(t.map(function(){var t=e._asyncToGenerator((function*(e){if(null==e.Name)throw new Error("Unexpected Link without a Name");if(e.Name.length!==i)yield n.put(e.Name.substring(2),!0);else{var t=parseInt(e.Name,16);r._putObjectAt(t,new oV({hash:n._options.hash,bits:n._options.bits},r,t))}}));return function(e){return t.apply(this,arguments)}}()))}));return function(e,r,n){return t.apply(this,arguments)}}(),hq=(e,t)=>e.toString(16).toUpperCase().padStart(t,"0").substring(0,t),pq=function(){var t=e._asyncToGenerator((function*(e,t,r,n,i){if(null==n){if(null==e.Data)throw new YV("no data in PBNode");var o;try{o=Tz.unmarshal(e.Data)}catch(e){throw new YV(e.message)}if("hamt-sharded-directory"!==o.type)throw new YV("not a HAMT");if(null==o.fanout)throw new YV("missing fanout");var a=gV({hashFn:uq,bits:Math.log2(Number(o.fanout))});n={rootBucket:a,hamtDepth:1,lastBucket:a}}var s=(n.lastBucket.tableSize()-1).toString(16).length;yield dq(e.Links,n.lastBucket,n.rootBucket);var l=yield n.rootBucket._findNewBucketAndPos(t),c=hq(l.pos,s),u=(e=>{for(var t=e.bucket,r=[];null!=t._parent;)r.push(t),t=t._parent;return r.push(t),r.reverse()})(l);u.length>n.hamtDepth&&(n.lastBucket=u[n.hamtDepth],c=hq(n.lastBucket._posAtParent,s));var d=e.Links.find((e=>{if(null==e.Name)return!1;var r=e.Name.substring(0,s),n=e.Name.substring(s);return r===c&&(""===n||n===t)}));if(null!=d)return null!=d.Name&&d.Name.substring(s)===t?d.Hash:(n.hamtDepth++,e=nN(yield r.get(d.Hash,i)),pq(e,t,r,n,i))}));return function(e,r,n,i,o){return t.apply(this,arguments)}}();function fq(e,t,r,n,i,o,a){return vq.apply(this,arguments)}function vq(){return vq=e._asyncToGenerator((function*(t,r,n,i,o,a,s){if(r instanceof Uint8Array){var l=nq(r,i,o,a);n.push(l)}else{if(null==r.Data)throw new YV("no data in PBNode");var c;try{c=Tz.unmarshal(r.Data)}catch(e){throw new YV(e.message)}if(null!=c.data){var u=nq(c.data,i,o,a);n.push(u),i+=BigInt(u.byteLength)}var d=[];if(r.Links.length!==c.blockSizes.length)throw new YV("Inconsistent block sizes and dag links");for(var h=0;h<r.Links.length;h++){var p=r.Links[h],f=i,v=f+c.blockSizes[h];if((o>=f&&o<v||a>=f&&a<=v||o<f&&a>v)&&d.push({link:p,blockStart:i}),(i=v)>a)break}yield lu(d,(r=>Qc(r,(r=>e._asyncToGenerator((function*(){var n=yield t.get(r.link.Hash,s);return e._objectSpread2(e._objectSpread2({},r),{},{block:n})}))))),(e=>zR(e,{ordered:!0,concurrency:s.blockReadConcurrency})),function(){var r=e._asyncToGenerator((function*(r){var i,l=!1,c=!1;try{for(var u,d,h=function*(){var r,{link:i,block:l,blockStart:c}=d.value;switch(i.Hash.code){case tN:r=nN(l);break;case re:r=l;break;default:return n.end(new YV("Unsupported codec: ".concat(i.Hash.code))),{v:void 0}}var u=new Xx({concurrency:1});u.on("error",(e=>{n.end(e)})),u.add(e._asyncToGenerator((function*(){var e;null===(e=s.onProgress)||void 0===e||e.call(s,new Ih("unixfs:exporter:walk:file",{cid:i.Hash})),yield fq(t,r,n,c,o,a,s)}))),yield u.onIdle()},p=e._asyncIterator(r);l=!(d=yield p.next()).done;l=!1)if(u=yield*h())return u.v}catch(e){c=!0,i=e}finally{try{l&&null!=p.return&&(yield p.return())}finally{if(c)throw i}}}));return function(e){return r.apply(this,arguments)}}()),i>=a&&n.end()}})),vq.apply(this,arguments)}var yq=(t,r,n,i,o,a,s)=>{function l(){return l=e._wrapAsyncGenerator((function(){var i=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(o){var a=n.fileSize();if(void 0===a)throw new Error("File was a directory");var{start:l,end:c}=iq(a,i.offset,i.length);if(0n!==c){var u=0n,d=c-l,h=Xc();null===(o=i.onProgress)||void 0===o||o.call(i,new Ih("unixfs:exporter:walk:file",{cid:t})),fq(s,r,h,0n,l,c,i).catch((e=>{h.end(e)}));var p,f=!1,v=!1;try{for(var y,g=e._asyncIterator(h);f=!(y=yield e._awaitAsyncGenerator(g.next())).done;f=!1){var m,w=y.value;if(null!=w){if((u+=BigInt(w.byteLength))>d)throw h.end(),new JV("Read too many bytes - the file size reported by the UnixFS data in the root node may be incorrect");u===d&&h.end(),null===(m=i.onProgress)||void 0===m||m.call(i,new Ih("unixfs:exporter:progress:unixfs:file",{bytesRead:u,totalBytes:d,fileSize:a})),yield w}}}catch(e){v=!0,p=e}finally{try{f&&null!=g.return&&(yield e._awaitAsyncGenerator(g.return()))}finally{if(v)throw p}}if(u<d)throw new ZV("Traversed entire DAG but did not read enough bytes")}}()})),l.apply(this,arguments)}return function(){return l.apply(this,arguments)}};function gq(e,t,r,n,i,o){return mq.apply(this,arguments)}function mq(){return mq=e._wrapAsyncGenerator((function*(t,r,n,i,o,a){var s,l=t.Links;if(null==t.Data)throw new YV("no data in PBNode");try{s=Tz.unmarshal(t.Data)}catch(e){throw new YV(e.message)}if(null==s.fanout)throw new YV("missing fanout");var c,u=(s.fanout-1n).toString(16).length,d=lu(l,(s=>Qc(s,(s=>e._asyncToGenerator((function*(){var e=null!=s.Name?s.Name.substring(u):null;if(null!=e&&""!==e){var l=yield n(s.Hash,e,"".concat(r,"/").concat(e),[],i+1,o,a);return{entries:null==l.entry?[]:[l.entry]}}var c,d=yield o.get(s.Hash,a);return t=nN(d),null===(c=a.onProgress)||void 0===c||c.call(a,new Ih("unixfs:exporter:walk:hamt-sharded-directory",{cid:s.Hash})),{entries:gq(t,r,n,i,o,a)}}))))),(e=>zR(e,{ordered:!0,concurrency:a.blockReadConcurrency}))),h=!1,p=!1;try{for(var f,v=e._asyncIterator(d);h=!(f=yield e._awaitAsyncGenerator(v.next())).done;h=!1){var{entries:y}=f.value;yield*e._asyncGeneratorDelegate(e._asyncIterator(y),e._awaitAsyncGenerator)}}catch(e){p=!0,c=e}finally{try{h&&null!=v.return&&(yield e._awaitAsyncGenerator(v.return()))}finally{if(p)throw c}}})),mq.apply(this,arguments)}var wq,bq,_q,Sq,Pq={raw:yq,file:yq,directory:(t,r,n,i,o,a,s)=>{function l(){return l=e._wrapAsyncGenerator((function(){var n=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return function*(l,c,u){var d=null!==(l=n.offset)&&void 0!==l?l:0,h=null!==(c=n.length)&&void 0!==c?c:r.Links.length,p=r.Links.slice(d,h);null===(u=n.onProgress)||void 0===u||u.call(n,new Ih("unixfs:exporter:walk:directory",{cid:t})),yield*e._asyncGeneratorDelegate(e._asyncIterator(lu(p,(t=>Qc(t,(t=>e._asyncToGenerator((function*(){var e,r=null!==(e=t.Name)&&void 0!==e?e:"",l="".concat(i,"/").concat(r);return(yield o(t.Hash,r,l,[],a+1,s,n)).entry}))))),(e=>zR(e,{ordered:!0,concurrency:n.blockReadConcurrency})),(e=>Gc(e,(e=>null!=e))))))}()})),l.apply(this,arguments)}return function(){return l.apply(this,arguments)}},"hamt-sharded-directory":(e,t,r,n,i,o,a)=>function(){var r,s=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};return null===(r=s.onProgress)||void 0===r||r.call(s,new Ih("unixfs:exporter:walk:hamt-sharded-directory",{cid:e})),gq(t,n,i,o,a,s)},metadata:(e,t,r,n,i,o,a)=>()=>[],symlink:(e,t,r,n,i,o,a)=>()=>[]},Eq=function(){var t=e._asyncToGenerator((function*(e,t,r,n,i,o,a,s){var l,c,u=nN(yield a.get(e,s));if(null==t&&(t=e.toString()),null==u.Data)throw new YV("no data in PBNode");try{l=Tz.unmarshal(u.Data)}catch(e){throw new YV(e.message)}if(null==r&&(r=t),n.length>0){var d,h;if(h="hamt-sharded-directory"===(null===(d=l)||void 0===d?void 0:d.type)?yield pq(u,n[0],a):((e,t)=>{var r=e.Links.find((e=>e.Name===t));return null==r?void 0:r.Hash})(u,n[0]),null==h)throw new WV("file does not exist");var p=n.shift();c={cid:h,toResolve:n,name:null!=p?p:"",path:"".concat(r,"/").concat(p)}}var f=Pq[l.type](e,u,l,r,i,o,a);if(null==f)throw new WV("could not find content exporter");return l.isDirectory()?{entry:{type:"directory",name:t,path:r,cid:e,content:f,unixfs:l,depth:o,node:u,size:l.fileSize()},next:c}:{entry:{type:"file",name:t,path:r,cid:e,content:f,unixfs:l,depth:o,node:u,size:l.fileSize()},next:c}}));return function(e,r,n,i,o,a,s,l){return t.apply(this,arguments)}}(),Aq={[tN]:Eq,[re]:cq,[fB]:tq,[kB]:rq,[Te.code]:aq,[X]:sq},kq=function(){var t=e._asyncToGenerator((function*(e,t,r,n,i,o,a){var s=Aq[e.code];if(null==s)throw new QV("No resolver for code ".concat(e.code));return s(e,t,r,n,kq,i,o,a)}));return function(e,r,n,i,o,a,s){return t.apply(this,arguments)}}(),xq=e=>{if(e instanceof Uint8Array)return{cid:je.decode(e),toResolve:[]};var t=je.asCID(e);if(null!=t)return{cid:t,toResolve:[]};if("string"==typeof e){0===e.indexOf("/ipfs/")&&(e=e.substring(6));var r=function(){var e;return(null!==(e=(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"").trim().match(/([^\\^/]|\\\/)+/g))&&void 0!==e?e:[]).filter(Boolean)}(e);return{cid:je.parse(r[0]),toResolve:r.slice(1)}}throw new KV("Unknown path type ".concat(e))};function Tq(e,t){return Iq.apply(this,arguments)}function Iq(){return Iq=e._wrapAsyncGenerator((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){for(var{cid:i,toResolve:o}=xq(t),a=i.toString(),s=a,l=o.length;;){var c=yield e._awaitAsyncGenerator(kq(i,a,s,o,l,r,n));if(null==c.entry&&null==c.next)throw new WV("Could not resolve ".concat(t));if(null!=c.entry&&(yield c.entry),null==c.next)return;o=c.next.toResolve,i=c.next.cid,a=c.next.name,s=c.next.path}}()})),Iq.apply(this,arguments)}function Cq(e,t){return Bq.apply(this,arguments)}function Bq(){return Bq=e._asyncToGenerator((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=yield HV(Tq(e,t,r));if(null==n)throw new WV("Could not resolve ".concat(e));return n})),Bq.apply(this,arguments)}function Nq(e,t){return Dq.apply(this,arguments)}function Dq(){return Dq=e._wrapAsyncGenerator((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){var i=yield e._awaitAsyncGenerator(Cq(t,r,n));if(null!=i&&(yield i,"directory"===i.type)){var o,a=!1,s=!1;try{for(var l,c=e._asyncIterator(d(i,n));a=!(l=yield e._awaitAsyncGenerator(c.next())).done;a=!1){var u=l.value;yield u}}catch(e){s=!0,o=e}finally{try{a&&null!=c.return&&(yield e._awaitAsyncGenerator(c.return()))}finally{if(s)throw o}}}function d(e,t){return h.apply(this,arguments)}function h(){return h=e._wrapAsyncGenerator((function*(t,r){var n,i=!1,o=!1;try{for(var a,s=e._asyncIterator(t.content(r));i=!(a=yield e._awaitAsyncGenerator(s.next())).done;i=!1){var l=a.value;(yield l,l instanceof Uint8Array)||"directory"===l.type&&(yield*e._asyncGeneratorDelegate(e._asyncIterator(d(l,r)),e._awaitAsyncGenerator))}}catch(e){o=!0,n=e}finally{try{i&&null!=s.return&&(yield e._awaitAsyncGenerator(s.return()))}finally{if(o)throw n}}})),h.apply(this,arguments)}}()})),Dq.apply(this,arguments)}var Gq=function(){if(Sq)return _q;Sq=1;var e=bq?wq:(bq=1,wq=e=>{if("[object Object]"!==Object.prototype.toString.call(e))return!1;var t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}),{hasOwnProperty:t}=Object.prototype,{propertyIsEnumerable:r}=Object,n=(e,t,r)=>Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0}),i=_q,o={concatArrays:!1,ignoreUndefined:!1},a=e=>{var n=[];for(var i in e)t.call(e,i)&&n.push(i);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(var a of o)r.call(e,a)&&n.push(a)}return n};function s(t){return Array.isArray(t)?(i=(r=t).slice(0,0),a(r).forEach((e=>{n(i,e,s(r[e]))})),i):e(t)?function(e){var t=null===Object.getPrototypeOf(e)?Object.create(null):{};return a(e).forEach((r=>{n(t,r,s(e[r]))})),t}(t):t;var r,i}var l=(e,t,r,i)=>(r.forEach((r=>{void 0===t[r]&&i.ignoreUndefined||(r in e&&e[r]!==Object.getPrototypeOf(e)?n(e,r,u(e[r],t[r],i)):n(e,r,s(t[r])))})),e),c=(e,r,i)=>{var o=e.slice(0,0),c=0;return[e,r].forEach((r=>{for(var u=[],d=0;d<r.length;d++)t.call(r,d)&&(u.push(String(d)),n(o,c++,r===e?r[d]:s(r[d])));o=l(o,r,a(r).filter((e=>!u.includes(e))),i)})),o};function u(t,r,n){return n.concatArrays&&Array.isArray(t)&&Array.isArray(r)?c(t,r,n):e(r)&&e(t)?l(t,r,a(r),n):s(r)}return _q=function(){for(var t=u(s(o),this!==i&&this||{},o),r={_:{}},n=arguments.length,a=new Array(n),l=0;l<n;l++)a[l]=arguments[l];for(var c of a)if(void 0!==c){if(!e(c))throw new TypeError("`"+c+"` is not an Option Object");r=u(r,{_:c},t)}return r._},_q}(),Rq=e.getDefaultExportFromCjs(Gq);class Oq extends Error{constructor(t,r,n){super(t),e._defineProperty(this,"name",void 0),e._defineProperty(this,"code",void 0),this.name=r,this.code=n}}class Lq extends Oq{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"not a Unixfs node","NotUnixFSError","ERR_NOT_UNIXFS")}}class Mq extends Oq{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"invalid PBNode","InvalidPBNodeError","ERR_INVALID_PB_NODE")}}class jq extends Oq{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"unknown error","InvalidPBNodeError","ERR_UNKNOWN_ERROR")}}class Fq extends Oq{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"path already exists","AlreadyExistsError","ERR_ALREADY_EXISTS")}}class Uq extends Oq{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"path does not exist","DoesNotExistError","ERR_DOES_NOT_EXIST")}}class zq extends Oq{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"no content","NoContentError","ERR_NO_CONTENT")}}class Vq extends Oq{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"not a file","NotAFileError","ERR_NOT_A_FILE")}}class qq extends Oq{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"not a directory","NotADirectoryError","ERR_NOT_A_DIRECTORY")}}class Hq extends Oq{constructor(){super(arguments.length>0&&void 0!==arguments[0]?arguments[0]:"invalid parameters","InvalidParametersError","ERR_INVALID_PARAMETERS")}}function Kq(e){return function(t){return t instanceof Wq?t:new Wq(t,e)}}class Wq{constructor(t,r){if(e._defineProperty(this,"_value",void 0),e._defineProperty(this,"_hashFn",void 0),e._defineProperty(this,"_depth",void 0),e._defineProperty(this,"_availableBits",void 0),e._defineProperty(this,"_currentBufferIndex",void 0),e._defineProperty(this,"_buffers",void 0),!(t instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=t,this._hashFn=r,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}take(t){var r=this;return e._asyncToGenerator((function*(){for(var e=t;r._availableBits<e;)yield r._produceMoreBits();for(var n=0;e>0;){var i=r._buffers[r._currentBufferIndex],o=Math.min(i.availableBits(),e);n=(n<<o)+i.take(o),e-=o,r._availableBits-=o,0===i.availableBits()&&r._currentBufferIndex++}return n}))()}untake(e){for(var t=e;t>0;){var r=this._buffers[this._currentBufferIndex],n=Math.min(r.totalBits()-r.availableBits(),t);r.untake(n),t-=n,this._availableBits+=n,this._currentBufferIndex>0&&r.totalBits()===r.availableBits()&&(this._depth--,this._currentBufferIndex--)}}_produceMoreBits(){var t=this;return e._asyncToGenerator((function*(){t._depth++;var e=t._depth>0?_t([t._value,Uint8Array.from([t._depth])]):t._value,r=yield t._hashFn(e),n=new Jq(r);t._buffers.push(n),t._availableBits+=n.availableBits()}))()}}var Qq=[255,254,252,248,240,224,192,128],Yq=[1,3,7,15,31,63,127,255];class Jq{constructor(t){e._defineProperty(this,"_value",void 0),e._defineProperty(this,"_currentBytePos",void 0),e._defineProperty(this,"_currentBitPos",void 0),this._value=t,this._currentBytePos=t.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+8*this._currentBytePos}totalBits(){return 8*this._value.length}take(e){for(var t=e,r=0;t>0&&this._haveBits();){var n=this._value[this._currentBytePos],i=this._currentBitPos+1,o=Math.min(i,t);r=(r<<o)+Zq(n,i-o,o),t-=o,this._currentBitPos-=o,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return r}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}}function Zq(e,t,r){var n=function(e,t){return Qq[e]&Yq[Math.min(t+e-1,7)]}(t,r);return(e&n)>>>t}var $q=BigInt(rV.code);function Xq(e){return eH.apply(this,arguments)}function eH(){return eH=e._asyncToGenerator((function*(e){return(yield rV.encode(e)).subarray(0,8).reverse()})),eH.apply(this,arguments)}var tH=function(){var t=e._asyncToGenerator((function*(t,r,n){null==n.codec&&(n.codec=iN);var i=yield De.digest(t),o=je.create(n.cidVersion,n.codec.code,i);return yield r.put(o,t,e._objectSpread2(e._objectSpread2({},n),{},{signal:n.signal})),o}));return function(e,r,n){return t.apply(this,arguments)}}();class rH{constructor(t,r){e._defineProperty(this,"options",void 0),e._defineProperty(this,"root",void 0),e._defineProperty(this,"dir",void 0),e._defineProperty(this,"path",void 0),e._defineProperty(this,"dirty",void 0),e._defineProperty(this,"flat",void 0),e._defineProperty(this,"parent",void 0),e._defineProperty(this,"parentKey",void 0),e._defineProperty(this,"unixfs",void 0),e._defineProperty(this,"mode",void 0),e._defineProperty(this,"mtime",void 0),e._defineProperty(this,"cid",void 0),e._defineProperty(this,"size",void 0),e._defineProperty(this,"nodeSize",void 0),this.options=null!=r?r:{},this.root=t.root,this.dir=t.dir,this.path=t.path,this.dirty=t.dirty,this.flat=t.flat,this.parent=t.parent,this.parentKey=t.parentKey,this.unixfs=t.unixfs,this.mode=t.mode,this.mtime=t.mtime}}class nH extends rH{constructor(t,r){super(t,r),e._defineProperty(this,"_bucket",void 0),this._bucket=gV({hashFn:Xq,bits:8})}put(t,r){var n=this;return e._asyncToGenerator((function*(){n.cid=void 0,n.size=void 0,n.nodeSize=void 0,yield n._bucket.put(t,r)}))()}get(t){var r=this;return e._asyncToGenerator((function*(){return r._bucket.get(t)}))()}childCount(){return this._bucket.leafCount()}directChildrenCount(){return this._bucket.childrenCount()}onlyChild(){return this._bucket.onlyChild()}eachChildSeries(){var t=this;return e._wrapAsyncGenerator((function*(){var r,n=!1,i=!1;try{for(var o,a=e._asyncIterator(t._bucket.eachLeafSeries());n=!(o=yield e._awaitAsyncGenerator(a.next())).done;n=!1){var{key:s,value:l}=o.value;yield{key:s,child:l}}}catch(e){i=!0,r=e}finally{try{n&&null!=a.return&&(yield e._awaitAsyncGenerator(a.return()))}finally{if(i)throw r}}}))()}estimateNodeSize(){return void 0!==this.nodeSize||(this.nodeSize=aH(this._bucket,this,this.options)),this.nodeSize}flush(t){var r=this;return e._wrapAsyncGenerator((function*(){var n,i=!1,o=!1;try{for(var a,s=e._asyncIterator(iH(r._bucket,t,r,r.options));i=!(a=yield e._awaitAsyncGenerator(s.next())).done;i=!1){var l=a.value;yield e._objectSpread2(e._objectSpread2({},l),{},{path:r.path})}}catch(e){o=!0,n=e}finally{try{i&&null!=s.return&&(yield e._awaitAsyncGenerator(s.return()))}finally{if(o)throw n}}}))()}}function iH(e,t,r,n){return oH.apply(this,arguments)}function oH(){return oH=e._wrapAsyncGenerator((function*(t,r,n,i){for(var o=t._children,a=[],s=0n,l=0;l<o.length;l++){var c=o.get(l);if(null!=c){var u=l.toString(16).toUpperCase().padStart(2,"0");if(c instanceof oV){var d,h=void 0,p=!1,f=!1;try{for(var v,y=e._asyncIterator(iH(c,r,null,i));p=!(v=yield e._awaitAsyncGenerator(y.next())).done;p=!1){h=v.value}}catch(e){f=!0,d=e}finally{try{p&&null!=y.return&&(yield e._awaitAsyncGenerator(y.return()))}finally{if(f)throw d}}if(null==h)throw new Error("Could not flush sharded directory, no sub-shard found");a.push({Name:u,Tsize:Number(h.size),Hash:h.cid}),s+=h.size}else if("function"==typeof c.value.flush){var g,m=c.value,w=void 0,b=!1,_=!1;try{for(var S,P=e._asyncIterator(m.flush(r));b=!(S=yield e._awaitAsyncGenerator(P.next())).done;b=!1){w=S.value,yield w}}catch(e){_=!0,g=e}finally{try{b&&null!=P.return&&(yield e._awaitAsyncGenerator(P.return()))}finally{if(_)throw g}}if(null==w)throw new Error("Did not flush dir");var E=u+c.key;a.push({Name:E,Tsize:Number(w.size),Hash:w.cid}),s+=w.size}else{var A=c.value;if(null==A.cid)continue;var k=u+c.key,x=A.size;a.push({Name:k,Tsize:Number(x),Hash:A.cid}),s+=BigInt(null!=x?x:0)}}}var T=Uint8Array.from(o.bitField().reverse()),I=new Tz({type:"hamt-sharded-directory",data:T,fanout:BigInt(t.tableSize()),hashType:$q,mtime:null==n?void 0:n.mtime,mode:null==n?void 0:n.mode}),C=rN(XB({Data:I.marshal(),Links:a})),B=yield e._awaitAsyncGenerator(tH(C,r,i)),N=BigInt(C.byteLength)+s;yield{cid:B,unixfs:I,size:N}})),oH.apply(this,arguments)}function aH(e,t,r){for(var n=e._children,i=[],o=0;o<n.length;o++){var a=n.get(o);if(null!=a){var s=o.toString(16).toUpperCase().padStart(2,"0");if(a instanceof oV){var l=aH(a,null,r);i.push({Name:s,Tsize:Number(l),Hash:0===r.cidVersion?sH:lH})}else if("function"==typeof a.value.flush){var c=a.value.nodeSize();i.push({Name:s+a.key,Tsize:Number(c),Hash:0===r.cidVersion?sH:lH})}else{var u=a.value;if(null==u.cid)continue;var d=s+a.key,h=u.size;i.push({Name:d,Tsize:Number(h),Hash:u.cid})}}}var p=Uint8Array.from(n.bitField().reverse());return rN(XB({Data:new Tz({type:"hamt-sharded-directory",data:p,fanout:BigInt(e.tableSize()),hashType:$q,mtime:null==t?void 0:t.mtime,mode:null==t?void 0:t.mode}).marshal(),Links:i})).length}var sH=je.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),lH=je.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi"),cH=Cu("helia:unixfs:commands:utils:hamt-utils"),uH=e=>e.toString(16).toUpperCase().padStart(2,"0").substring(0,2),dH=function(){var t=e._asyncToGenerator((function*(e,t,r){for(var n=new nH({root:!0,dir:!0,parent:void 0,parentKey:void 0,path:"",dirty:!0,flat:!1,mtime:r.mtime,mode:r.mode},r),i=0;i<t.length;i++)yield n._bucket.put(t[i].name,{size:t[i].size,cid:t[i].cid});var o=yield HV(n.flush(e));if(null==o)throw new Error("Flushing shard yielded no result");return o}));return function(e,r,n){return t.apply(this,arguments)}}(),hH=function(){var t=e._asyncToGenerator((function*(e,t,r){var n,i,o,a=Tz.unmarshal(null!==(n=e[0].node.Data)&&void 0!==n?n:new Uint8Array(0)),s=BigInt(Math.pow(2,8));e.reverse();for(var l=function*(){var n=c===e.length-1,l=e[c],u=Uint8Array.from(l.children.bitField().reverse()),d=new Tz({type:"hamt-sharded-directory",data:u,fanout:s,hashType:$q});n&&(d.mtime=a.mtime,d.mode=a.mode);var h=rN(XB(o={Data:d.marshal(),Links:l.node.Links}));if(i=yield tH(h,t,r),!n){var p=e[c+1];if(null==p)throw new Error("Was not operating on shard root but also had no parent?");cH("updating link in parent sub-shard with prefix %s",p.prefix),p.node.Links=p.node.Links.filter((e=>e.Name!==p.prefix)),p.node.Links.push({Name:p.prefix,Hash:i,Tsize:l.node.Links.reduce(((e,t)=>{var r;return e+(null!==(r=t.Tsize)&&void 0!==r?r:0)}),h.byteLength)})}},c=0;c<e.length;c++)yield*l();if(null==i||null==o)throw new Error("Noting persisted");return{cid:i,node:o}}));return function(e,r,n){return t.apply(this,arguments)}}(),pH=function(){var t=e._asyncToGenerator((function*(e,t,r,n){for(var i=Kq(Xq)(ot(t)),o=[];;){var a,s=nN(yield r.get(e,n)),l=new iV,c=yield i.take(8),u=uH(c);o.push({prefix:u,children:l,node:s});var d=void 0;for(var h of s.Links){var p,f=null!==(p=h.Name)&&void 0!==p?p:"";if(f.length<2)throw new Error("Invalid HAMT - link name was too short");var v=parseInt(f.substring(0,2),16);l.set(v,!0),f.startsWith(u)&&(d=h)}if(null==d){cH("no link found with prefix %s for %s",u,t);break}var y=null!==(a=d.Name)&&void 0!==a?a:"";if(y.length<2)throw new Error("Invalid HAMT - link name was too short");if(2!==y.length)break;e=d.Hash,cH("descend into sub-shard with prefix %s",y)}return{path:o,hash:i}}));return function(e,r,n,i){return t.apply(this,arguments)}}();function fH(e,t,r,n){return vH.apply(this,arguments)}function vH(){return vH=e._asyncToGenerator((function*(e,t,r,n){if(null==e.Data)throw new Error("DagPB node had no data");var i,o=Tz.unmarshal(e.Data);if("directory"===o.type)i=function(e){var t=0;for(var r of e.Links){var n;t+=(null!==(n=r.Name)&&void 0!==n?n:"").length,t+=1===r.Hash.version?lH.bytes.byteLength:sH.bytes.byteLength}return t}(e);else{if("hamt-sharded-directory"!==o.type)throw new Error("Can only estimate the size of directories or shards");i=yield yH(e,0,r,t,n)}return i>r})),vH.apply(this,arguments)}function yH(e,t,r,n,i){return gH.apply(this,arguments)}function gH(){return gH=e._asyncToGenerator((function*(e,t,r,n,i){if(t>r)return r;if(null==e.Data)return t;if(!Tz.unmarshal(e.Data).isDirectory())return t;for(var o of e.Links){var a,s=null!==(a=o.Name)&&void 0!==a?a:"";if(t+=(s=s.substring(2)).length,t+=o.Hash.bytes.byteLength,o.Hash.code===tN){var l=nN(yield n.get(o.Hash,i));t+=(yield yH(l,t,r,n,i))}}return t})),gH.apply(this,arguments)}var mH=Cu("helia:unixfs:components:utils:add-link");function wH(e,t,r,n){return bH.apply(this,arguments)}function bH(){return bH=e._asyncToGenerator((function*(e,t,r,n){if(null==e.node.Data)throw new Hq("Invalid parent passed to addLink");if("hamt-sharded-directory"===Tz.unmarshal(e.node.Data).type)return mH("adding link to sharded directory"),PH(e,t,r,n);mH("adding ".concat(t.Name," (").concat(t.Hash,") to regular directory"));var i=yield SH(e,t,r,n);if(yield fH(i.node,r,n.shardSplitThresholdBytes,n)){mH("converting directory to sharded directory");var o=yield _H(i,r);i.cid=o.cid,i.node=nN(yield r.get(o.cid,n))}return i})),bH.apply(this,arguments)}var _H=function(){var t=e._asyncToGenerator((function*(e,t){if(null==e.node.Data)throw new Hq("Invalid parent passed to convertToShardedDirectory");var r=Tz.unmarshal(e.node.Data),n=yield dH(t,e.node.Links.map((e=>{var t,r;return{name:null!==(t=e.Name)&&void 0!==t?t:"",size:BigInt(null!==(r=e.Tsize)&&void 0!==r?r:0),cid:e.Hash}})),{mode:r.mode,mtime:r.mtime,cidVersion:e.cid.version});return mH("converted directory to sharded directory ".concat(n.cid)),n}));return function(e,r){return t.apply(this,arguments)}}(),SH=function(){var t=e._asyncToGenerator((function*(e,t,r,n){var i=e.node.Links.filter((e=>{var r=e.Name===t.Name;if(r&&!n.allowOverwriting)throw new Fq;return!r}));if(i.push(t),null==e.node.Data)throw new Mq("Parent node with no data passed to addToDirectory");var o,a=Tz.unmarshal(e.node.Data);if(null!=a.mtime){var s=Date.now(),l=Math.floor(s/1e3);a.mtime={secs:BigInt(l),nsecs:1e3*(s-1e3*l)},o=a.marshal()}else o=e.node.Data;e.node=XB({Data:o,Links:i});var c=rN(e.node),u=yield De.digest(c),d=je.create(e.cid.version,tN,u);return yield r.put(d,c),{node:e.node,cid:d}}));return function(e,r,n,i){return t.apply(this,arguments)}}(),PH=function(){var t=e._asyncToGenerator((function*(e,t,r,n){var{path:i,hash:o}=yield pH(e.cid,t.Name,r,n),a=i[i.length-1];if(null==a)throw new Error("Invalid HAMT, could not generate path");var s=a.prefix,l=parseInt(s,16);mH("next prefix for %s is %s",t.Name,s);var c,u="".concat(s).concat(t.Name),d=a.node.Links.find((e=>{var t;return(null!==(t=e.Name)&&void 0!==t?t:"").startsWith(s)}));if(null!=d)if(mH("link %s was present in shard",u),d.Name===u){if(!n.allowOverwriting)throw new Fq;mH("overwriting %s in sub-shard",t.Name),a.node.Links=a.node.Links.filter((e=>e.Name!==u)),a.node.Links.push({Name:u,Hash:t.Hash,Tsize:t.Tsize})}else{if(2===(null===(c=d.Name)||void 0===c?void 0:c.length))throw new Error("Existing link was sub-shard?!");var h;mH("prefix %s already exists, creating new sub-shard",s);for(var p=a.node.Links.findIndex((e=>{var t;return null===(t=e.Name)||void 0===t?void 0:t.startsWith(s)})),f=a.node.Links.splice(p,1)[0],v=(null!==(h=f.Name)&&void 0!==h?h:"").substring(2),y=Kq(Xq)(ot(v)),g=0;g<i.length;g++)yield y.take(8);for(;;){var m=yield y.take(8),w=uH(m);f.Name="".concat(w).concat(v);var b=yield o.take(8),_=uH(b);if(w!==_){var S=new iV;S.set(b,!0),S.set(m,!0),i.push({prefix:s,children:S,node:{Links:[f,{Name:"".concat(_).concat(t.Name),Hash:t.Hash,Tsize:t.Tsize}]}});break}var P=new iV;P.set(b,!0),i.push({prefix:_,children:P,node:{Links:[]}})}}else mH("link %s was not present in sub-shard",u),t.Name=u,a.node.Links.push(t),a.children.set(l,!0),mH("adding %s to existing sub-shard",u);return hH(i,r,n)}));return function(e,r,n,i){return t.apply(this,arguments)}}();function EH(e,t){return AH.apply(this,arguments)}function AH(){return AH=e._asyncToGenerator((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=yield Cq(e,t,r);if("directory"!==n.type)throw new qq("".concat(e.toString()," was not a UnixFS directory"));return{cid:e,node:n.node}})),AH.apply(this,arguments)}function kH(e,t,r,n){return xH.apply(this,arguments)}function xH(){return xH=e._asyncToGenerator((function*(e,t,r,n){var i,o,a=yield Cq(e,r,n);if("directory"!==a.type&&"file"!==a.type&&"raw"!==a.type)throw new Lq("".concat(e.toString()," was not a UnixFS node"));return{Name:t,Tsize:a.node instanceof Uint8Array?a.node.byteLength:(i=a.node,o=i.Links.reduce(((e,t)=>{var r;return e+(null!==(r=t.Tsize)&&void 0!==r?r:0)}),0),rN(i).byteLength+o),Hash:e}})),xH.apply(this,arguments)}var TH=Cu("helia:unixfs:components:utils:resolve");function IH(e,t,r,n){return CH.apply(this,arguments)}function CH(){return CH=e._asyncToGenerator((function*(e,t,r,n){if(null==t||""===t)return{cid:e};var i="/ipfs/".concat(e).concat(null==t?"":"/".concat(t)),o=yield Rc(Tq(i,r,n));if(0===o.length)throw new Uq("Could not find path in directory");return TH("resolved %s to %c",t,e),{cid:o[o.length-1].cid,path:t,segments:o}})),CH.apply(this,arguments)}function BH(e,t,r,n){return NH.apply(this,arguments)}function NH(){return NH=e._asyncToGenerator((function*(t,r,n,i){if(null==r.segments||0===r.segments.length)return t;var o=r.segments.pop();if(null==o)throw new Error("Insufficient segments");for(var a of(o.cid=t,r.segments.reverse(),r.segments)){var[s,l]=yield Promise.all([EH(a.cid,n,i),kH(o.cid,o.name,n,i)]);t=(yield wH(s,l,n,e._objectSpread2(e._objectSpread2({},i),{},{allowOverwriting:!0,cidVersion:t.version}))).cid,a.cid=t,o=a}return t})),NH.apply(this,arguments)}var DH=Rq.bind({ignoreUndefined:!0}),GH={};function RH(){return RH=e._wrapAsyncGenerator((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){var i=DH(GH,n),o=yield e._awaitAsyncGenerator(IH(t,i.path,r,i)),a=yield e._awaitAsyncGenerator(Cq(o.cid,r,i));if("file"!==a.type&&"raw"!==a.type)throw new Vq;if(null==a.content)throw new zq;yield*e._asyncGeneratorDelegate(e._asyncIterator(a.content(i)))}()})),RH.apply(this,arguments)}var OH=262144,LH=Rq.bind({ignoreUndefined:!0}),MH=Cu("helia:unixfs:chmod"),jH={recursive:!1,shardSplitThresholdBytes:OH};function FH(){return FH=e._asyncToGenerator((function*(t,r,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},o=LH(jH,i),a=yield IH(t,o.path,n,i);if(MH("chmod %c %d",a.cid,r),o.recursive){var s=yield lu(e._wrapAsyncGenerator((function*(){var t,o=!1,s=!1;try{for(var l,c=e._asyncIterator(Nq(a.cid,n,i));o=!(l=yield e._awaitAsyncGenerator(c.next())).done;o=!1){var u=l.value,d=void 0,h=[];if("raw"===u.type)d=new Tz({type:"file",data:u.node});else{if("file"!==u.type&&"directory"!==u.type)throw new Lq;d=u.unixfs,h=u.node.Links}d.mode=r;var p={Data:d.marshal(),Links:h};yield{path:u.path,content:p}}}catch(e){s=!0,t=e}finally{try{o&&null!=c.return&&(yield e._awaitAsyncGenerator(c.return()))}finally{if(s)throw t}}})),(r=>{return NV(r,n,e._objectSpread2(e._objectSpread2({},o),{},{dagBuilder:(i=e._wrapAsyncGenerator((function*(r,n){var i,a=!1,s=!1;try{for(var l,c=function*(){var r=l.value;yield e._asyncToGenerator((function*(){var i=r.content,a=rN(i),s=yield tH(a,n,e._objectSpread2(e._objectSpread2({},o),{},{cidVersion:t.version}));if(null==i.Data)throw new Mq("".concat(s," had no data"));var l=Tz.unmarshal(i.Data);return{cid:s,size:BigInt(a.length),path:r.path,unixfs:l}}))},u=e._asyncIterator(r);a=!(l=yield e._awaitAsyncGenerator(u.next())).done;a=!1)yield*c()}catch(e){s=!0,i=e}finally{try{a&&null!=u.return&&(yield e._awaitAsyncGenerator(u.return()))}finally{if(s)throw i}}})),function(e,t){return i.apply(this,arguments)})}));var i}),function(){var t=e._asyncToGenerator((function*(e){return HV(e)}));return function(e){return t.apply(this,arguments)}}());if(null==s)throw new jq("Could not chmod ".concat(a.cid.toString()));return BH(s.cid,a,n,o)}var l,c=yield n.get(a.cid,i),u=[];if(a.cid.code===re)l=new Tz({type:"file",data:c});else{var d=nN(c);if(null==d.Data)throw new Mq("".concat(a.cid.toString()," had no data"));u=d.Links,l=Tz.unmarshal(d.Data)}l.mode=r;var h=rN({Data:l.marshal(),Links:u}),p=yield De.digest(h),f=je.create(a.cid.version,tN,p);return yield n.put(f,h),BH(f,a,n,o)})),FH.apply(this,arguments)}var UH=Rq.bind({ignoreUndefined:!0}),zH=Cu("helia:unixfs:cp"),VH={force:!1,shardSplitThresholdBytes:OH};function qH(){return qH=e._asyncToGenerator((function*(t,r,n,i){var o=UH(VH,arguments.length>4&&void 0!==arguments[4]?arguments[4]:{});if(n.includes("/"))throw new Hq("Name must not have slashes");var[a,s]=yield Promise.all([EH(r,i,o),kH(t,n,i,o)]);return zH('Adding %c as "%s" to %c',t,n,r),(yield wH(a,s,i,e._objectSpread2({allowOverwriting:o.force,cidVersion:r.version},o))).cid})),qH.apply(this,arguments)}var HH=Rq.bind({ignoreUndefined:!0}),KH={};function WH(){return WH=e._wrapAsyncGenerator((function(t,r){var n=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{};return function*(){var i=HH(KH,n),o=yield e._awaitAsyncGenerator(IH(t,i.path,r,i)),a=yield e._awaitAsyncGenerator(Cq(o.cid,r));if("file"!==a.type&&"raw"!==a.type){if(null==a.content)throw new zq;if("directory"!==a.type)throw new qq;yield*e._asyncGeneratorDelegate(e._asyncIterator(a.content({offset:n.offset,length:n.length})))}else yield a}()})),WH.apply(this,arguments)}var QH=Rq.bind({ignoreUndefined:!0}),YH=Cu("helia:unixfs:mkdir"),JH={cidVersion:1,force:!1,shardSplitThresholdBytes:OH};function ZH(){return ZH=e._asyncToGenerator((function*(t,r,n){var i=arguments.length>3&&void 0!==arguments[3]?arguments[3]:{},o=QH(JH,i);if(r.includes("/"))throw new Hq("Path must not have slashes");if("directory"!==(yield Cq(t,n,i)).type)throw new qq("".concat(t.toString()," was not a UnixFS directory"));YH("creating %s",r);var a=rN({Data:new Tz({type:"directory",mode:o.mode,mtime:o.mtime}).marshal(),Links:[]}),s=yield De.digest(a),l=je.create(o.cidVersion,tN,s);yield n.put(l,a);var[c,u]=yield Promise.all([EH(t,n,o),kH(l,r,n,o)]);return YH("adding empty dir called %s to %c",r,t),(yield wH(c,u,n,e._objectSpread2(e._objectSpread2({},o),{},{allowOverwriting:o.force}))).cid})),ZH.apply(this,arguments)}var $H=Cu("helia:unixfs:utils:remove-link");function XH(){return XH=e._asyncToGenerator((function*(e,t,r,n){if(null==e.node.Data)throw new Mq("Parent node had no data");if("hamt-sharded-directory"===Tz.unmarshal(e.node.Data).type){$H("removing ".concat(t," from sharded directory"));var i=yield tK(e,t,r,n);return(yield fH(i.node,r,n.shardSplitThresholdBytes,n))?i:($H("converting shard to flat directory %c",e.cid),rK(i,r,n))}return $H("removing link ".concat(t," regular directory")),eK(e,t,r,n)})),XH.apply(this,arguments)}var eK=function(){var t=e._asyncToGenerator((function*(t,r,n,i){t.node.Links=t.node.Links.filter((e=>e.Name!==r));var o=rN(t.node),a=yield tH(o,n,e._objectSpread2(e._objectSpread2({},i),{},{cidVersion:t.cid.version}));return $H("Updated regular directory ".concat(a)),{node:t.node,cid:a}}));return function(e,r,n,i){return t.apply(this,arguments)}}(),tK=function(){var t=e._asyncToGenerator((function*(e,t,r,n){var{path:i}=yield pH(e.cid,t,r,n),o=i[i.length-1];if(null==o)throw new Error("Invalid HAMT, could not generate path");var a=o.node.Links.filter((e=>{var r;return(null!==(r=e.Name)&&void 0!==r?r:"").substring(2)===t})).map((e=>e.Name)).pop();if(null==a)throw new Error("File not found");var s=a.substring(0,2),l=parseInt(s,16);if(o.node.Links=o.node.Links.filter((e=>e.Name!==a)),o.children.unset(l),1===o.node.Links.length)for(var c=function*(){var e;if(1===i.length)return 0;var t=i[i.length-1];if(null==t||t.node.Links.length>1)return 0;i.pop();var r=i[i.length-1];if(null==r)return 0;var n=t.node.Links[0];r.node.Links=r.node.Links.filter((e=>{var t;return!(null!==(t=e.Name)&&void 0!==t?t:"").startsWith(r.prefix)})),r.node.Links.push({Hash:n.Hash,Name:"".concat(r.prefix).concat((null!==(e=n.Name)&&void 0!==e?e:"").substring(2)),Tsize:n.Tsize})};0!==(yield*c()););return hH(i,r,n)}));return function(e,r,n,i){return t.apply(this,arguments)}}(),rK=function(){var t=e._asyncToGenerator((function*(t,r,n){if(null==t.node.Data)throw new Hq("Invalid parent passed to convertToFlatDirectory");var i={Links:[]},o=yield Cq(t.cid,r);if("directory"!==o.type)throw new Error("Unexpected node type");var a,s=!1,l=!1;try{for(var c,u=e._asyncIterator(o.content());s=!(c=yield u.next()).done;s=!1){var d=c.value,h=0;h=d.node instanceof Uint8Array?d.node.byteLength:rN(d.node).length,i.Links.push({Hash:d.cid,Name:d.name,Tsize:h})}}catch(e){l=!0,a=e}finally{try{s&&null!=u.return&&(yield u.return())}finally{if(l)throw a}}var p=Tz.unmarshal(t.node.Data);i.Data=new Tz({type:"directory",mode:p.mode,mtime:p.mtime}).marshal();var f=rN(XB(i));return{cid:yield tH(f,r,{codec:iN,cidVersion:t.cid.version,signal:n.signal}),node:i}}));return function(e,r,n){return t.apply(this,arguments)}}(),nK=Rq.bind({ignoreUndefined:!0}),iK=Cu("helia:unixfs:rm"),oK={shardSplitThresholdBytes:OH};function aK(){return aK=e._asyncToGenerator((function*(t,r,n){var i=nK(oK,arguments.length>3&&void 0!==arguments[3]?arguments[3]:{});if(r.includes("/"))throw new Hq("Name must not have slashes");var o=yield EH(t,n,i);iK("Removing %s from %c",r,t);var a=yield function(e,t,r,n){return XH.apply(this,arguments)}(o,r,n,e._objectSpread2(e._objectSpread2({},i),{},{cidVersion:t.version}));return a.cid})),aK.apply(this,arguments)}var sK=Rq.bind({ignoreUndefined:!0}),lK=Cu("helia:unixfs:stat"),cK={};function uK(){return uK=e._asyncToGenerator((function*(e,t){var r=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},n=sK(cK,r),i=yield IH(e,r.path,t,n);lK("stat %c",i.cid);var o=yield Cq(i.cid,t,n);if("file"!==o.type&&"directory"!==o.type&&"raw"!==o.type)throw new Lq;var a,s,l,c=0n,u=0n,d=0n,h=0n,p=0,f=o.type;if("raw"===o.type&&(c=BigInt(o.node.byteLength),u=BigInt(o.node.byteLength),d=BigInt(o.node.byteLength),h=BigInt(o.node.byteLength),p=1),"directory"===o.type&&(c=0n,d=0n,h=u=BigInt(o.unixfs.marshal().byteLength),p=1,a=o.unixfs.mode,s=o.unixfs.mtime,l=o.unixfs),"file"===o.type){var v,y,g=yield dK(i.cid,t,n);c=o.unixfs.fileSize(),u=BigInt((null!==(v=null===(y=o.node.Data)||void 0===y?void 0:y.byteLength)&&void 0!==v?v:0)+o.node.Links.reduce(((e,t)=>{var r;return e+(null!==(r=t.Tsize)&&void 0!==r?r:0)}),0)),d=BigInt(g.localFileSize),h=BigInt(g.localDagSize),p=g.blocks,a=o.unixfs.mode,s=o.unixfs.mtime,l=o.unixfs}return{cid:i.cid,mode:a,mtime:s,fileSize:c,dagSize:u,localFileSize:d,localDagSize:h,blocks:p,type:f,unixfs:l}})),uK.apply(this,arguments)}function dK(e,t,r){return hK.apply(this,arguments)}function hK(){return hK=e._asyncToGenerator((function*(e,t,r){var n={localFileSize:0,localDagSize:0,blocks:0};if(yield t.has(e,r)){var i=yield t.get(e,r);if(n.blocks++,n.localDagSize+=i.byteLength,e.code===re)n.localFileSize+=i.byteLength;else{if(e.code!==tN)throw new jq("".concat(e.toString()," was neither DAG_PB nor RAW"));var o=nN(i);if(o.Links.length>0)for(var a of o.Links){var s=yield dK(a.Hash,t,r);n.localFileSize+=s.localFileSize,n.localDagSize+=s.localDagSize,n.blocks+=s.blocks}else{var l;if(null==o.Data)throw new Mq("PBNode ".concat(e.toString()," had no data"));var c=Tz.unmarshal(o.Data);if(null==c.data)throw new Mq("UnixFS node ".concat(e.toString()," had no data"));n.localFileSize+=null!==(l=c.data.byteLength)&&void 0!==l?l:0}}}return n})),hK.apply(this,arguments)}var pK=Rq.bind({ignoreUndefined:!0}),fK=Cu("helia:unixfs:touch"),vK={recursive:!1,shardSplitThresholdBytes:OH};function yK(){return yK=e._asyncToGenerator((function*(t,r){var n,i=arguments.length>2&&void 0!==arguments[2]?arguments[2]:{},o=pK(vK,i),a=yield IH(t,o.path,r,o),s=null!==(n=o.mtime)&&void 0!==n?n:{secs:BigInt(Math.round(Date.now()/1e3)),nsecs:0};if(fK("touch %c %o",a.cid,s),o.recursive){var l=yield lu(e._wrapAsyncGenerator((function*(){var t,n=!1,i=!1;try{for(var o,l=e._asyncIterator(Nq(a.cid,r));n=!(o=yield e._awaitAsyncGenerator(l.next())).done;n=!1){var c=o.value,u=void 0,d=void 0;if("raw"===c.type)u=new Tz({data:c.node}),d=[];else{if("file"!==c.type&&"directory"!==c.type)throw new Lq;u=c.unixfs,d=c.node.Links}u.mtime=s;var h={Data:u.marshal(),Links:d};yield{path:c.path,content:h}}}catch(e){i=!0,t=e}finally{try{n&&null!=l.return&&(yield e._awaitAsyncGenerator(l.return()))}finally{if(i)throw t}}})),(n=>{return NV(n,r,e._objectSpread2(e._objectSpread2({},o),{},{dagBuilder:(i=e._wrapAsyncGenerator((function*(r,n){var i,a=!1,s=!1;try{for(var l,c=function*(){var r=l.value;yield e._asyncToGenerator((function*(){var i=r.content,a=rN(i),s=yield tH(a,n,e._objectSpread2(e._objectSpread2({},o),{},{cidVersion:t.version}));if(null==i.Data)throw new Mq("".concat(s," had no data"));var l=Tz.unmarshal(i.Data);return{cid:s,size:BigInt(a.length),path:r.path,unixfs:l}}))},u=e._asyncIterator(r);a=!(l=yield e._awaitAsyncGenerator(u.next())).done;a=!1)yield*c()}catch(e){s=!0,i=e}finally{try{a&&null!=u.return&&(yield e._awaitAsyncGenerator(u.return()))}finally{if(s)throw i}}})),function(e,t){return i.apply(this,arguments)})}));var i}),function(){var t=e._asyncToGenerator((function*(e){return HV(e)}));return function(e){return t.apply(this,arguments)}}());if(null==l)throw new jq("Could not chmod ".concat(a.cid.toString()));return BH(l.cid,a,r,o)}var c,u=yield r.get(a.cid,i),d=[];if(a.cid.code===re)c=new Tz({data:u});else{var h=nN(u);if(d=h.Links,null==h.Data)throw new Mq("".concat(a.cid.toString()," had no data"));c=Tz.unmarshal(h.Data)}c.mtime=s;var p=rN({Data:c.marshal(),Links:d}),f=yield De.digest(p),v=je.create(a.cid.version,tN,f);return yield r.put(v,p),BH(v,a,r,o)})),yK.apply(this,arguments)}class gK{constructor(t){e._defineProperty(this,"components",void 0),this.components=t}addAll(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(function(e,t){return FV.apply(this,arguments)}(t,r.components.blockstore,n)))}()})).apply(this,arguments)}addBytes(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};return function(e,t){return UV.apply(this,arguments)}(t,n.components.blockstore,e)}))()}addByteStream(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};return function(e,t){return zV.apply(this,arguments)}(t,n.components.blockstore,e)}))()}addFile(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};return function(e,t){return VV.apply(this,arguments)}(t,n.components.blockstore,e)}))()}addDirectory(){var t=arguments,r=this;return e._asyncToGenerator((function*(){var e=t.length>1&&void 0!==t[1]?t[1]:{};return function(e,t){return qV.apply(this,arguments)}(t.length>0&&void 0!==t[0]?t[0]:{},r.components.blockstore,e)}))()}cat(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(function(e,t){return RH.apply(this,arguments)}(t,r.components.blockstore,n)))}()})).apply(this,arguments)}chmod(t,r){var n=arguments,i=this;return e._asyncToGenerator((function*(){var e=n.length>2&&void 0!==n[2]?n[2]:{};return function(e,t,r){return FH.apply(this,arguments)}(t,r,i.components.blockstore,e)}))()}cp(t,r,n){var i=arguments,o=this;return e._asyncToGenerator((function*(){var e=i.length>3&&void 0!==i[3]?i[3]:{};return function(e,t,r,n){return qH.apply(this,arguments)}(t,r,n,o.components.blockstore,e)}))()}ls(t){var r=this;return e._wrapAsyncGenerator((function(t){var n=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};return function*(){yield*e._asyncGeneratorDelegate(e._asyncIterator(function(e,t){return WH.apply(this,arguments)}(t,r.components.blockstore,n)))}()})).apply(this,arguments)}mkdir(t,r){var n=arguments,i=this;return e._asyncToGenerator((function*(){var e=n.length>2&&void 0!==n[2]?n[2]:{};return function(e,t,r){return ZH.apply(this,arguments)}(t,r,i.components.blockstore,e)}))()}rm(t,r){var n=arguments,i=this;return e._asyncToGenerator((function*(){var e=n.length>2&&void 0!==n[2]?n[2]:{};return function(e,t,r){return aK.apply(this,arguments)}(t,r,i.components.blockstore,e)}))()}stat(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};return function(e,t){return uK.apply(this,arguments)}(t,n.components.blockstore,e)}))()}touch(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{};return function(e,t){return yK.apply(this,arguments)}(t,n.components.blockstore,e)}))()}}class mK{constructor(t){e._defineProperty(this,"components",void 0),this.components=t}add(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e,i=r.length>1&&void 0!==r[1]?r[1]:{},o=vB(t),a=yield(null!==(e=i.hasher)&&void 0!==e?e:De).digest(o),s=je.createV1(fB,a);return yield n.components.blockstore.put(s,o,i),s}))()}get(t){var r=arguments,n=this;return e._asyncToGenerator((function*(){var e=r.length>1&&void 0!==r[1]?r[1]:{},i=yield n.components.blockstore.get(t,e);return yB(i)}))()}}exports.BaseBlockstore=Nu,exports.BaseDatastore=Mc,exports.CID=je,exports.DeleteFailedError=Vc,exports.EventEmitter=No,exports.GetFailedError=zc,exports.Hash=Mr,exports.Key=Bc,exports.NotFoundError=Hc,exports.OpenFailedError=jc,exports.PutFailedError=Uc,exports.Uint8ArrayList=Fa,exports.__asyncGenerator=function(e,t,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n,i=r.apply(e,t||[]),o=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),a("next"),a("throw"),a("return",(function(e){return function(t){return Promise.resolve(t).then(e,c)}})),n[Symbol.asyncIterator]=function(){return this},n;function a(e,t){i[e]&&(n[e]=function(t){return new Promise((function(r,n){o.push([e,t,r,n])>1||s(e,t)}))},t&&(n[e]=t(n[e])))}function s(e,t){try{(r=i[e](t)).value instanceof Uo?Promise.resolve(r.value.v).then(l,c):u(o[0][2],r)}catch(e){u(o[0][3],e)}var r}function l(e){s("next",e)}function c(e){s("throw",e)}function u(e,t){e(t),o.shift(),o.length&&s(o[0][0],o[0][1])}},exports.__asyncValues=function(e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=Mo(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise((function(n,i){(function(e,t,r,n){Promise.resolve(n).then((function(t){e({value:t,done:r})}),t)})(n,i,(t=e[r](t)).done,t.value)}))}}},exports.__await=Uo,exports.__awaiter=Oo,exports.__classPrivateFieldGet=function(e,t,r,n){if("a"===r&&!n)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof t?e!==t||!n:!t.has(e))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?n:"a"===r?n.call(e):n?n.value:t.get(e)},exports.__extends=Go,exports.__generator=Lo,exports.__read=jo,exports.__spreadArray=function(e,t,r){if(r||2===arguments.length)for(var n,i=0,o=t.length;i<o;i++)!n&&i in t||(n||(n=Array.prototype.slice.call(t,0,i)),n[i]=t[i]);return e.concat(n||Array.prototype.slice.call(t))},exports.__values=Mo,exports.abytes=dr,exports.add=rn,exports.add3H=on,exports.add3L=nn,exports.aexists=pr,exports.anumber=ur,exports.aoutput=fr,exports.autoNAT=QG,exports.base32=k,exports.base32upper=x,exports.base58btc=j,exports.bases=qe,exports.bitswap=EN,exports.bytesToHex=function(e){if(dr(e),Pr)return e.toHex();for(var t="",r=0;r<e.length;r++)t+=Er[e[r]];return t},exports.bytesToHex$1=Nn,exports.circuitRelayTransport=tp,exports.clean=vr,exports.code=re,exports.code$1=fB,exports.compare=function(e,t){for(var r=0;r<e.byteLength;r++){if(e[r]<t[r])return-1;if(e[r]>t[r])return 1}return e.byteLength>t.byteLength?1:e.byteLength<t.byteLength?-1:0},exports.concat=_t,exports.concat$1=St,exports.concatBytes=Lr,exports.createHasher=jr,exports.createHelia=function(){return vz.apply(this,arguments)},exports.createLibp2p=hz,exports.createOptHasher=function(e){var t=(t,r)=>e(r).update(Rr(t)).digest(),r=e({});return t.outputLen=r.outputLen,t.blockLen=r.blockLen,t.create=t=>e(t),t},exports.createView=yr,exports.dagCbor=function(e){return new mK(e)},exports.dcutr=FR,exports.decode=Ae,exports.decode$1=yB,exports.decode$2=bt,exports.ed25519=_o,exports.encode=vB,exports.encodingLength=yt,exports.equals=it,exports.filter=Gc,exports.fromBig=Qr,exports.fromString=at,exports.generateKeyPair=Fl,exports.hexToBytes=function(e){if("string"!=typeof e)throw new Error("hex string expected, got "+typeof e);if(Pr)return Uint8Array.fromHex(e);var t=e.length,r=t/2;if(t%2)throw new Error("hex string expected, got unpadded hex of length "+t);for(var n=new Uint8Array(r),i=0,o=0;i<r;i++,o+=2){var a=Br(e.charCodeAt(o)),s=Br(e.charCodeAt(o+1));if(void 0===a||void 0===s){var l=e[o]+e[o+1];throw new Error('hex string expected, got non-hex character "'+l+'" at index '+o)}n[i]=16*a+s}return n},exports.hexToBytes$1=Fn,exports.hmac=Sn,exports.identify=ZR,exports.identifyPush=$R,exports.identity=Te,exports.isMultiaddr=ar,exports.isName=function(e){return!!ar(e)&&e.protos().some((e=>e.resolvable))},exports.mod=ci,exports.multiaddr=sr,exports.name=pB,exports.nanoid=Vh,exports.noise=Zk,exports.pbkdf2Async=xo,exports.peerIdFromMultihash=oc,exports.peerIdFromPrivateKey=ic,exports.peerIdFromPublicKey=nc,exports.peerIdFromString=rc,exports.ping=aj,exports.pipe=lu,exports.privateKeyFromProtobuf=Hl,exports.privateKeyFromRaw=Kl,exports.privateKeyToProtobuf=Wl,exports.protocols=lr,exports.publicKeyFromProtobuf=zl,exports.publicKeyFromRaw=function(e){var t,r;if(32===e.byteLength)return As(e);if(33===e.byteLength)return Ml(e);var n=Ha(e),i=null===(t=n[1])||void 0===t?void 0:t[0];if(i===$a||i===Xa||i===es)return vs(n);if("1.2.840.113549.1.1.1"===(null===(r=n[0])||void 0===r?void 0:r[0]))return Tl(n,e);throw new ea("Could not extract public key from raw bytes")},exports.publicKeyToProtobuf=ql,exports.pushable=Xc,exports.raceSignal=tu,exports.randomBytes=Fr,exports.ripemd160=Ac,exports.rotlBH=(e,t,r)=>t<<r-32|e>>>64-r,exports.rotlBL=(e,t,r)=>e<<r-32|t>>>64-r,exports.rotlSH=(e,t,r)=>e<<r|t>>>32-r,exports.rotlSL=(e,t,r)=>t<<r|e>>>32-r,exports.rotr32H=(e,t)=>t,exports.rotr32L=(e,t)=>e,exports.rotrBH=en,exports.rotrBL=tn,exports.rotrSH=$r,exports.rotrSL=Xr,exports.secp256k1=Zi,exports.sha256=wn,exports.sha256$1=De,exports.sha512=bn,exports.sha512$1=Eo,exports.sort=Oc,exports.split=Yr,exports.swap32IfBE=Sr,exports.swap8IfBE=_r,exports.toBytes=Rr,exports.toString=Ze,exports.toString$1=$e,exports.u32=function(e){return new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4))},exports.unixfs=function(e){return new gK(e)},exports.utf8ToBytes=Gr,exports.webRTC=dx,exports.webRTCDirect=ux,exports.yamux=zG;