@hashgraphonline/standards-sdk 0.1.176 → 0.1.177
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.
- package/dist/browser/services/registry-broker/client/base-client.d.ts +7 -4
- package/dist/browser/services/registry-broker/client/base-client.d.ts.map +1 -1
- package/dist/browser/services/registry-broker/client/skills.d.ts +5 -3
- package/dist/browser/services/registry-broker/client/skills.d.ts.map +1 -1
- package/dist/browser/services/registry-broker/schemas.d.ts +6871 -24133
- package/dist/browser/services/registry-broker/schemas.d.ts.map +1 -1
- package/dist/browser/services/registry-broker/types.d.ts +34 -26
- package/dist/browser/services/registry-broker/types.d.ts.map +1 -1
- package/dist/browser/standards-sdk.browser.js +220 -221
- package/dist/browser/standards-sdk.browser.js.map +1 -1
- package/dist/browser-root/services/registry-broker/client/base-client.d.ts +7 -4
- package/dist/browser-root/services/registry-broker/client/base-client.d.ts.map +1 -1
- package/dist/browser-root/services/registry-broker/client/skills.d.ts +5 -3
- package/dist/browser-root/services/registry-broker/client/skills.d.ts.map +1 -1
- package/dist/browser-root/services/registry-broker/schemas.d.ts +6871 -24133
- package/dist/browser-root/services/registry-broker/schemas.d.ts.map +1 -1
- package/dist/browser-root/services/registry-broker/types.d.ts +34 -26
- package/dist/browser-root/services/registry-broker/types.d.ts.map +1 -1
- package/dist/browser-root/standards-sdk.root-browser.js +342 -282
- package/dist/browser-root/standards-sdk.root-browser.js.map +1 -1
- package/dist/cjs/services/registry-broker/client/base-client.d.ts +7 -4
- package/dist/cjs/services/registry-broker/client/base-client.d.ts.map +1 -1
- package/dist/cjs/services/registry-broker/client/skills.d.ts +5 -3
- package/dist/cjs/services/registry-broker/client/skills.d.ts.map +1 -1
- package/dist/cjs/services/registry-broker/schemas.d.ts +6869 -24131
- package/dist/cjs/services/registry-broker/schemas.d.ts.map +1 -1
- package/dist/cjs/services/registry-broker/types.d.ts +34 -26
- package/dist/cjs/services/registry-broker/types.d.ts.map +1 -1
- package/dist/cjs/standards-sdk.cjs +1 -1
- package/dist/cjs/standards-sdk.cjs.map +1 -1
- package/dist/es/services/registry-broker/client/base-client.d.ts +7 -4
- package/dist/es/services/registry-broker/client/base-client.d.ts.map +1 -1
- package/dist/es/services/registry-broker/client/skills.d.ts +5 -3
- package/dist/es/services/registry-broker/client/skills.d.ts.map +1 -1
- package/dist/es/services/registry-broker/schemas.d.ts +6869 -24131
- package/dist/es/services/registry-broker/schemas.d.ts.map +1 -1
- package/dist/es/services/registry-broker/types.d.ts +34 -26
- package/dist/es/services/registry-broker/types.d.ts.map +1 -1
- package/dist/es/standards-sdk.es116.js +1 -1
- package/dist/es/standards-sdk.es121.js +1 -1
- package/dist/es/standards-sdk.es127.js +1 -1
- package/dist/es/standards-sdk.es128.js +5 -5
- package/dist/es/standards-sdk.es138.js +1 -1
- package/dist/es/standards-sdk.es139.js +1 -1
- package/dist/es/standards-sdk.es140.js +5 -5
- package/dist/es/standards-sdk.es142.js +3 -3
- package/dist/es/standards-sdk.es143.js +1 -1
- package/dist/es/standards-sdk.es145.js +28 -11
- package/dist/es/standards-sdk.es145.js.map +1 -1
- package/dist/es/standards-sdk.es147.js +1 -1
- package/dist/es/standards-sdk.es148.js +1 -1
- package/dist/es/standards-sdk.es16.js +1 -1
- package/dist/es/standards-sdk.es160.js +12461 -1778
- package/dist/es/standards-sdk.es160.js.map +1 -1
- package/dist/es/standards-sdk.es161.js +1773 -12461
- package/dist/es/standards-sdk.es161.js.map +1 -1
- package/dist/es/standards-sdk.es163.js +167 -51
- package/dist/es/standards-sdk.es163.js.map +1 -1
- package/dist/es/standards-sdk.es164.js +306 -88
- package/dist/es/standards-sdk.es164.js.map +1 -1
- package/dist/es/standards-sdk.es165.js +336 -71
- package/dist/es/standards-sdk.es165.js.map +1 -1
- package/dist/es/standards-sdk.es166.js +439 -186
- package/dist/es/standards-sdk.es166.js.map +1 -1
- package/dist/es/standards-sdk.es167.js +314 -695
- package/dist/es/standards-sdk.es167.js.map +1 -1
- package/dist/es/standards-sdk.es168.js +66 -63
- package/dist/es/standards-sdk.es168.js.map +1 -1
- package/dist/es/standards-sdk.es169.js +744 -158
- package/dist/es/standards-sdk.es169.js.map +1 -1
- package/dist/es/standards-sdk.es170.js +55 -321
- package/dist/es/standards-sdk.es170.js.map +1 -1
- package/dist/es/standards-sdk.es171.js +88 -330
- package/dist/es/standards-sdk.es171.js.map +1 -1
- package/dist/es/standards-sdk.es172.js +71 -443
- package/dist/es/standards-sdk.es172.js.map +1 -1
- package/dist/es/standards-sdk.es173.js +184 -315
- package/dist/es/standards-sdk.es173.js.map +1 -1
- package/dist/es/standards-sdk.es174.js +63 -66
- package/dist/es/standards-sdk.es174.js.map +1 -1
- package/dist/es/standards-sdk.es175.js +1 -1
- package/dist/es/standards-sdk.es176.js +1 -1
- package/dist/es/standards-sdk.es178.js +2 -2
- package/dist/es/standards-sdk.es179.js +1 -1
- package/dist/es/standards-sdk.es18.js +2 -2
- package/dist/es/standards-sdk.es180.js +1 -1
- package/dist/es/standards-sdk.es181.js +2 -2
- package/dist/es/standards-sdk.es182.js +1 -1
- package/dist/es/standards-sdk.es183.js +1 -1
- package/dist/es/standards-sdk.es19.js +2 -2
- package/dist/es/standards-sdk.es27.js +2 -2
- package/dist/es/standards-sdk.es30.js +1 -1
- package/dist/es/standards-sdk.es31.js +1 -1
- package/dist/es/standards-sdk.es35.js +2 -2
- package/dist/es/standards-sdk.es36.js +1 -1
- package/dist/es/standards-sdk.es37.js +1 -1
- package/dist/es/standards-sdk.es56.js +1 -1
- package/dist/es/standards-sdk.es59.js +1 -1
- package/dist/es/standards-sdk.es60.js +1 -1
- package/dist/es/standards-sdk.es62.js +1 -1
- package/dist/es/standards-sdk.es63.js +2 -2
- package/dist/es/standards-sdk.es64.js +1 -1
- package/dist/es/standards-sdk.es65.js +1 -1
- package/dist/es/standards-sdk.es66.js +1 -1
- package/dist/es/standards-sdk.es67.js +1 -1
- package/dist/es/standards-sdk.es69.js +1 -1
- package/dist/es/standards-sdk.es75.js +1 -1
- package/dist/es/standards-sdk.es84.js +1 -1
- package/package.json +1 -1
|
@@ -7,5 +7,5 @@ read:function(e,t,r,i,n){var o,s,a=8*n-i-1,c=(1<<a)-1,l=c>>1,u=-7,d=r?n-1:0,p=r?
|
|
|
7
7
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
8
8
|
* @license MIT
|
|
9
9
|
*/
|
|
10
|
-
!function(e){const t=H,r=Z,i="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=l,e.SlowBuffer=function(e){+e!=e&&(e=0);return l.alloc(+e)},e.INSPECT_MAX_BYTES=50;const n=2147483647;e.kMaxLength=n;const{Uint8Array:o,ArrayBuffer:s,SharedArrayBuffer:a}=globalThis;function c(e){if(e>n)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new o(e);return Object.setPrototypeOf(t,l.prototype),t}function l(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return p(e)}return u(e,t,r)}function u(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!l.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|f(e,t);let i=c(r);const n=i.write(e,t);n!==r&&(i=i.slice(0,n));return i}(e,t);if(s.isView(e))return function(e){if(X(e,o)){const t=new o(e);return g(t.buffer,t.byteOffset,t.byteLength)}return h(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(X(e,s)||e&&X(e.buffer,s))return g(e,t,r);if(void 0!==a&&(X(e,a)||e&&X(e.buffer,a)))return g(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const i=e.valueOf&&e.valueOf();if(null!=i&&i!==e)return l.from(i,t,r);const n=function(e){if(l.isBuffer(e)){const t=0|m(e.length),r=c(t);return 0===r.length||e.copy(r,0,0,t),r}if(void 0!==e.length)return"number"!=typeof e.length||Q(e.length)?c(0):h(e);if("Buffer"===e.type&&Array.isArray(e.data))return h(e.data)}(e);if(n)return n;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return l.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function d(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function p(e){return d(e),c(e<0?0:0|m(e))}function h(e){const t=e.length<0?0:0|m(e.length),r=c(t);for(let i=0;i<t;i+=1)r[i]=255&e[i];return r}function g(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');let i;return i=void 0===t&&void 0===r?new o(e):void 0===r?new o(e,t):new o(e,t,r),Object.setPrototypeOf(i,l.prototype),i}function m(e){if(e>=n)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n.toString(16)+" bytes");return 0|e}function f(e,t){if(l.isBuffer(e))return e.length;if(s.isView(e)||X(e,s))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===r)return 0;let n=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return G(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return J(e).length;default:if(n)return i?-1:G(e).length;t=(""+t).toLowerCase(),n=!0}}function y(e,t,r){let i=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return z(this,t,r);case"utf8":case"utf-8":return C(this,t,r);case"ascii":return x(this,t,r);case"latin1":case"binary":return N(this,t,r);case"base64":return A(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,t,r);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}function b(e,t,r){const i=e[t];e[t]=e[r],e[r]=i}function w(e,t,r,i,n){if(0===e.length)return-1;if("string"==typeof r?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Q(r=+r)&&(r=n?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(n)return-1;r=e.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof t&&(t=l.from(t,i)),l.isBuffer(t))return 0===t.length?-1:I(e,t,r,i,n);if("number"==typeof t)return t&=255,"function"==typeof o.prototype.indexOf?n?o.prototype.indexOf.call(e,t,r):o.prototype.lastIndexOf.call(e,t,r):I(e,[t],r,i,n);throw new TypeError("val must be string, number or Buffer")}function I(e,t,r,i,n){let o,s=1,a=e.length,c=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,r/=2}function l(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(n){let i=-1;for(o=r;o<a;o++)if(l(e,o)===l(t,-1===i?0:o-i)){if(-1===i&&(i=o),o-i+1===c)return i*s}else-1!==i&&(o-=o-i),i=-1}else for(r+c>a&&(r=a-c),o=r;o>=0;o--){let r=!0;for(let i=0;i<c;i++)if(l(e,o+i)!==l(t,i)){r=!1;break}if(r)return o}return-1}function T(e,t,r,i){r=Number(r)||0;const n=e.length-r;i?(i=Number(i))>n&&(i=n):i=n;const o=t.length;let s;for(i>o/2&&(i=o/2),s=0;s<i;++s){const i=parseInt(t.substr(2*s,2),16);if(Q(i))return s;e[r+s]=i}return s}function S(e,t,r,i){return Y(G(t,e.length-r),e,r,i)}function k(e,t,r,i){return Y(function(e){const t=[];for(let r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,i)}function v(e,t,r,i){return Y(J(t),e,r,i)}function E(e,t,r,i){return Y(function(e,t){let r,i,n;const o=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)r=e.charCodeAt(s),i=r>>8,n=r%256,o.push(n),o.push(i);return o}(t,e.length-r),e,r,i)}function A(e,r,i){return 0===r&&i===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(r,i))}function C(e,t,r){r=Math.min(e.length,r);const i=[];let n=t;for(;n<r;){const t=e[n];let o=null,s=t>239?4:t>223?3:t>191?2:1;if(n+s<=r){let r,i,a,c;switch(s){case 1:t<128&&(o=t);break;case 2:r=e[n+1],128==(192&r)&&(c=(31&t)<<6|63&r,c>127&&(o=c));break;case 3:r=e[n+1],i=e[n+2],128==(192&r)&&128==(192&i)&&(c=(15&t)<<12|(63&r)<<6|63&i,c>2047&&(c<55296||c>57343)&&(o=c));break;case 4:r=e[n+1],i=e[n+2],a=e[n+3],128==(192&r)&&128==(192&i)&&128==(192&a)&&(c=(15&t)<<18|(63&r)<<12|(63&i)<<6|63&a,c>65535&&c<1114112&&(o=c))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,i.push(o>>>10&1023|55296),o=56320|1023&o),i.push(o),n+=s}return function(e){const t=e.length;if(t<=R)return String.fromCharCode.apply(String,e);let r="",i=0;for(;i<t;)r+=String.fromCharCode.apply(String,e.slice(i,i+=R));return r}(i)}l.TYPED_ARRAY_SUPPORT=function(){try{const e=new o(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,o.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),l.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(l.prototype,"parent",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.buffer}}),Object.defineProperty(l.prototype,"offset",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.byteOffset}}),l.poolSize=8192,l.from=function(e,t,r){return u(e,t,r)},Object.setPrototypeOf(l.prototype,o.prototype),Object.setPrototypeOf(l,o),l.alloc=function(e,t,r){return function(e,t,r){return d(e),e<=0?c(e):void 0!==t?"string"==typeof r?c(e).fill(t,r):c(e).fill(t):c(e)}(e,t,r)},l.allocUnsafe=function(e){return p(e)},l.allocUnsafeSlow=function(e){return p(e)},l.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==l.prototype},l.compare=function(e,t){if(X(e,o)&&(e=l.from(e,e.offset,e.byteLength)),X(t,o)&&(t=l.from(t,t.offset,t.byteLength)),!l.isBuffer(e)||!l.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let r=e.length,i=t.length;for(let n=0,o=Math.min(r,i);n<o;++n)if(e[n]!==t[n]){r=e[n],i=t[n];break}return r<i?-1:i<r?1:0},l.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},l.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return l.alloc(0);let r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;const i=l.allocUnsafe(t);let n=0;for(r=0;r<e.length;++r){let t=e[r];if(X(t,o))n+t.length>i.length?(l.isBuffer(t)||(t=l.from(t)),t.copy(i,n)):o.prototype.set.call(i,t,n);else{if(!l.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(i,n)}n+=t.length}return i},l.byteLength=f,l.prototype._isBuffer=!0,l.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)b(this,t,t+1);return this},l.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)b(this,t,t+3),b(this,t+1,t+2);return this},l.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)b(this,t,t+7),b(this,t+1,t+6),b(this,t+2,t+5),b(this,t+3,t+4);return this},l.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?C(this,0,e):y.apply(this,arguments)},l.prototype.toLocaleString=l.prototype.toString,l.prototype.equals=function(e){if(!l.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===l.compare(this,e)},l.prototype.inspect=function(){let t="";const r=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(t+=" ... "),"<Buffer "+t+">"},i&&(l.prototype[i]=l.prototype.inspect),l.prototype.compare=function(e,t,r,i,n){if(X(e,o)&&(e=l.from(e,e.offset,e.byteLength)),!l.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===i&&(i=0),void 0===n&&(n=this.length),t<0||r>e.length||i<0||n>this.length)throw new RangeError("out of range index");if(i>=n&&t>=r)return 0;if(i>=n)return-1;if(t>=r)return 1;if(this===e)return 0;let s=(n>>>=0)-(i>>>=0),a=(r>>>=0)-(t>>>=0);const c=Math.min(s,a),u=this.slice(i,n),d=e.slice(t,r);for(let o=0;o<c;++o)if(u[o]!==d[o]){s=u[o],a=d[o];break}return s<a?-1:a<s?1:0},l.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},l.prototype.indexOf=function(e,t,r){return w(this,e,t,r,!0)},l.prototype.lastIndexOf=function(e,t,r){return w(this,e,t,r,!1)},l.prototype.write=function(e,t,r,i){if(void 0===t)i="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)i=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(r)?(r>>>=0,void 0===i&&(i="utf8")):(i=r,r=void 0)}const n=this.length-t;if((void 0===r||r>n)&&(r=n),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let o=!1;for(;;)switch(i){case"hex":return T(this,e,t,r);case"utf8":case"utf-8":return S(this,e,t,r);case"ascii":case"latin1":case"binary":return k(this,e,t,r);case"base64":return v(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const R=4096;function x(e,t,r){let i="";r=Math.min(e.length,r);for(let n=t;n<r;++n)i+=String.fromCharCode(127&e[n]);return i}function N(e,t,r){let i="";r=Math.min(e.length,r);for(let n=t;n<r;++n)i+=String.fromCharCode(e[n]);return i}function z(e,t,r){const i=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>i)&&(r=i);let n="";for(let o=t;o<r;++o)n+=ee[e[o]];return n}function _(e,t,r){const i=e.slice(t,r);let n="";for(let o=0;o<i.length-1;o+=2)n+=String.fromCharCode(i[o]+256*i[o+1]);return n}function P(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function O(e,t,r,i,n,o){if(!l.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>n||t<o)throw new RangeError('"value" argument is out of bounds');if(r+i>e.length)throw new RangeError("Index out of range")}function D(e,t,r,i,n){q(t,i,n,e,r,7);let o=Number(t&BigInt(4294967295));e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,r}function F(e,t,r,i,n){q(t,i,n,e,r,7);let o=Number(t&BigInt(4294967295));e[r+7]=o,o>>=8,e[r+6]=o,o>>=8,e[r+5]=o,o>>=8,e[r+4]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=s,s>>=8,e[r+2]=s,s>>=8,e[r+1]=s,s>>=8,e[r]=s,r+8}function M(e,t,r,i,n,o){if(r+i>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function U(e,t,i,n,o){return t=+t,i>>>=0,o||M(e,0,i,4),r.write(e,t,i,n,23,4),i+4}function B(e,t,i,n,o){return t=+t,i>>>=0,o||M(e,0,i,8),r.write(e,t,i,n,52,8),i+8}l.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e);const i=this.subarray(e,t);return Object.setPrototypeOf(i,l.prototype),i},l.prototype.readUintLE=l.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let i=this[e],n=1,o=0;for(;++o<t&&(n*=256);)i+=this[e+o]*n;return i},l.prototype.readUintBE=l.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let i=this[e+--t],n=1;for(;t>0&&(n*=256);)i+=this[e+--t]*n;return i},l.prototype.readUint8=l.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},l.prototype.readUint32LE=l.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},l.prototype.readUint32BE=l.prototype.readUInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},l.prototype.readBigUInt64LE=te(function(e){j(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||W(e,this.length-8);const i=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,n=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(i)+(BigInt(n)<<BigInt(32))}),l.prototype.readBigUInt64BE=te(function(e){j(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||W(e,this.length-8);const i=t*2**24+65536*this[++e]+256*this[++e]+this[++e],n=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(i)<<BigInt(32))+BigInt(n)}),l.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let i=this[e],n=1,o=0;for(;++o<t&&(n*=256);)i+=this[e+o]*n;return n*=128,i>=n&&(i-=Math.pow(2,8*t)),i},l.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let i=t,n=1,o=this[e+--i];for(;i>0&&(n*=256);)o+=this[e+--i]*n;return n*=128,o>=n&&(o-=Math.pow(2,8*t)),o},l.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},l.prototype.readInt16LE=function(e,t){e>>>=0,t||P(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},l.prototype.readInt16BE=function(e,t){e>>>=0,t||P(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},l.prototype.readInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},l.prototype.readInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},l.prototype.readBigInt64LE=te(function(e){j(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||W(e,this.length-8);const i=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(i)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),l.prototype.readBigInt64BE=te(function(e){j(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||W(e,this.length-8);const i=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(i)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+r)}),l.prototype.readFloatLE=function(e,t){return e>>>=0,t||P(e,4,this.length),r.read(this,e,!0,23,4)},l.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),r.read(this,e,!1,23,4)},l.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),r.read(this,e,!0,52,8)},l.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(e,8,this.length),r.read(this,e,!1,52,8)},l.prototype.writeUintLE=l.prototype.writeUIntLE=function(e,t,r,i){if(e=+e,t>>>=0,r>>>=0,!i){O(this,e,t,r,Math.pow(2,8*r)-1,0)}let n=1,o=0;for(this[t]=255&e;++o<r&&(n*=256);)this[t+o]=e/n&255;return t+r},l.prototype.writeUintBE=l.prototype.writeUIntBE=function(e,t,r,i){if(e=+e,t>>>=0,r>>>=0,!i){O(this,e,t,r,Math.pow(2,8*r)-1,0)}let n=r-1,o=1;for(this[t+n]=255&e;--n>=0&&(o*=256);)this[t+n]=e/o&255;return t+r},l.prototype.writeUint8=l.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,1,255,0),this[t]=255&e,t+1},l.prototype.writeUint16LE=l.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeUint16BE=l.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeUint32LE=l.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},l.prototype.writeUint32BE=l.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigUInt64LE=te(function(e,t=0){return D(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeBigUInt64BE=te(function(e,t=0){return F(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeIntLE=function(e,t,r,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*r-1);O(this,e,t,r,i-1,-i)}let n=0,o=1,s=0;for(this[t]=255&e;++n<r&&(o*=256);)e<0&&0===s&&0!==this[t+n-1]&&(s=1),this[t+n]=(e/o|0)-s&255;return t+r},l.prototype.writeIntBE=function(e,t,r,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*r-1);O(this,e,t,r,i-1,-i)}let n=r-1,o=1,s=0;for(this[t+n]=255&e;--n>=0&&(o*=256);)e<0&&0===s&&0!==this[t+n+1]&&(s=1),this[t+n]=(e/o|0)-s&255;return t+r},l.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},l.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},l.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigInt64LE=te(function(e,t=0){return D(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeBigInt64BE=te(function(e,t=0){return F(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeFloatLE=function(e,t,r){return U(this,e,t,!0,r)},l.prototype.writeFloatBE=function(e,t,r){return U(this,e,t,!1,r)},l.prototype.writeDoubleLE=function(e,t,r){return B(this,e,t,!0,r)},l.prototype.writeDoubleBE=function(e,t,r){return B(this,e,t,!1,r)},l.prototype.copy=function(e,t,r,i){if(!l.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<r&&(i=r),i===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-r&&(i=e.length-t+r);const n=i-r;return this===e&&"function"==typeof o.prototype.copyWithin?this.copyWithin(t,r,i):o.prototype.set.call(e,this.subarray(r,i),t),n},l.prototype.fill=function(e,t,r,i){if("string"==typeof e){if("string"==typeof t?(i=t,t=0,r=this.length):"string"==typeof r&&(i=r,r=this.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!l.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(1===e.length){const t=e.charCodeAt(0);("utf8"===i&&t<128||"latin1"===i)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;let n;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(n=t;n<r;++n)this[n]=e;else{const o=l.isBuffer(e)?e:l.from(e,i),s=o.length;if(0===s)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(n=0;n<r-t;++n)this[n+t]=o[n%s]}return this};const L={};function K(e,t,r){L[e]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function $(e){let t="",r=e.length;const i="-"===e[0]?1:0;for(;r>=i+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function q(e,t,r,i,n,o){if(e>r||e<t){const r="bigint"==typeof t?"n":"";let i;throw i=0===t||t===BigInt(0)?`>= 0${r} and < 2${r} ** ${8*(o+1)}${r}`:`>= -(2${r} ** ${8*(o+1)-1}${r}) and < 2 ** ${8*(o+1)-1}${r}`,new L.ERR_OUT_OF_RANGE("value",i,e)}!function(e,t,r){j(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||W(t,e.length-(r+1))}(i,n,o)}function j(e,t){if("number"!=typeof e)throw new L.ERR_INVALID_ARG_TYPE(t,"number",e)}function W(e,t,r){if(Math.floor(e)!==e)throw j(e,r),new L.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new L.ERR_BUFFER_OUT_OF_BOUNDS;throw new L.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}K("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),K("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),K("ERR_OUT_OF_RANGE",function(e,t,r){let i=`The value of "${e}" is out of range.`,n=r;return Number.isInteger(r)&&Math.abs(r)>2**32?n=$(String(r)):"bigint"==typeof r&&(n=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(n=$(n)),n+="n"),i+=` It must be ${t}. Received ${n}`,i},RangeError);const V=/[^+/0-9A-Za-z-_]/g;function G(e,t){let r;t=t||1/0;const i=e.length;let n=null;const o=[];for(let s=0;s<i;++s){if(r=e.charCodeAt(s),r>55295&&r<57344){if(!n){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===i){(t-=3)>-1&&o.push(239,191,189);continue}n=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),n=r;continue}r=65536+(n-55296<<10|r-56320)}else n&&(t-=3)>-1&&o.push(239,191,189);if(n=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function J(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(V,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function Y(e,t,r,i){let n;for(n=0;n<i&&!(n+r>=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function X(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Q(e){return e!=e}const ee=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const i=16*r;for(let n=0;n<16;++n)t[i+n]=e[r]+e[n]}return t}();function te(e){return"undefined"==typeof BigInt?re:e}function re(){throw new Error("BigInt not supported")}}($);const Q=$.Buffer,ee=$.Buffer,te=globalThis||self;function re(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ie,ne,oe={exports:{}},se=oe.exports={};function ae(){throw new Error("setTimeout has not been defined")}function ce(){throw new Error("clearTimeout has not been defined")}function le(e){if(ie===setTimeout)return setTimeout(e,0);if((ie===ae||!ie)&&setTimeout)return ie=setTimeout,setTimeout(e,0);try{return ie(e,0)}catch(t){try{return ie.call(null,e,0)}catch(r){return ie.call(this,e,0)}}}!function(){try{ie="function"==typeof setTimeout?setTimeout:ae}catch(e){ie=ae}try{ne="function"==typeof clearTimeout?clearTimeout:ce}catch(e){ne=ce}}();var ue,de=[],pe=!1,he=-1;function ge(){pe&&ue&&(pe=!1,ue.length?de=ue.concat(de):he=-1,de.length&&me())}function me(){if(!pe){var e=le(ge);pe=!0;for(var t=de.length;t;){for(ue=de,de=[];++he<t;)ue&&ue[he].run();he=-1,t=de.length}ue=null,pe=!1,function(e){if(ne===clearTimeout)return clearTimeout(e);if((ne===ce||!ne)&&clearTimeout)return ne=clearTimeout,clearTimeout(e);try{return ne(e)}catch(t){try{return ne.call(null,e)}catch(r){return ne.call(this,e)}}}(e)}}function fe(e,t){this.fun=e,this.array=t}function ye(){}se.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];de.push(new fe(e,t)),1!==de.length||pe||le(me)},fe.prototype.run=function(){this.fun.apply(null,this.array)},se.title="browser",se.browser=!0,se.env={},se.argv=[],se.version="",se.versions={},se.on=ye,se.addListener=ye,se.once=ye,se.off=ye,se.removeListener=ye,se.removeAllListeners=ye,se.emit=ye,se.prependListener=ye,se.prependOnceListener=ye,se.listeners=function(e){return[]},se.binding=function(e){throw new Error("process.binding is not supported")},se.cwd=function(){return"/"},se.chdir=function(e){throw new Error("process.chdir is not supported")},se.umask=function(){return 0};const be=re(oe.exports);function we(e,t){return function(){return e.apply(t,arguments)}}const{toString:Ie}=Object.prototype,{getPrototypeOf:Te}=Object,{iterator:Se,toStringTag:ke}=Symbol,ve=(e=>t=>{const r=Ie.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Ee=e=>(e=e.toLowerCase(),t=>ve(t)===e),Ae=e=>t=>typeof t===e,{isArray:Ce}=Array,Re=Ae("undefined");function xe(e){return null!==e&&!Re(e)&&null!==e.constructor&&!Re(e.constructor)&&_e(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Ne=Ee("ArrayBuffer");const ze=Ae("string"),_e=Ae("function"),Pe=Ae("number"),Oe=e=>null!==e&&"object"==typeof e,De=e=>{if("object"!==ve(e))return!1;const t=Te(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||ke in e||Se in e)},Fe=Ee("Date"),Me=Ee("File"),Ue=Ee("Blob"),Be=Ee("FileList"),Le=Ee("URLSearchParams"),[Ke,$e,He,qe]=["ReadableStream","Request","Response","Headers"].map(Ee);function je(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let i,n;if("object"!=typeof e&&(e=[e]),Ce(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(xe(e))return;const n=r?Object.getOwnPropertyNames(e):Object.keys(e),o=n.length;let s;for(i=0;i<o;i++)s=n[i],t.call(null,e[s],s,e)}}function We(e,t){if(xe(e))return null;t=t.toLowerCase();const r=Object.keys(e);let i,n=r.length;for(;n-- >0;)if(i=r[n],t===i.toLowerCase())return i;return null}const Ve="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:te,Ge=e=>!Re(e)&&e!==Ve;const Je=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&Te(Uint8Array)),Ye=Ee("HTMLFormElement"),Xe=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),Ze=Ee("RegExp"),Qe=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),i={};je(r,(r,n)=>{let o;!1!==(o=t(r,n,e))&&(i[n]=o||r)}),Object.defineProperties(e,i)};const et=Ee("AsyncFunction"),tt=(rt="function"==typeof setImmediate,it=_e(Ve.postMessage),rt?setImmediate:it?(nt=`axios@${Math.random()}`,ot=[],Ve.addEventListener("message",({source:e,data:t})=>{e===Ve&&t===nt&&ot.length&&ot.shift()()},!1),e=>{ot.push(e),Ve.postMessage(nt,"*")}):e=>setTimeout(e));var rt,it,nt,ot;const st="undefined"!=typeof queueMicrotask?queueMicrotask.bind(Ve):void 0!==be&&be.nextTick||tt,at={isArray:Ce,isArrayBuffer:Ne,isBuffer:xe,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||_e(e.append)&&("formdata"===(t=ve(e))||"object"===t&&_e(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Ne(e.buffer),t},isString:ze,isNumber:Pe,isBoolean:e=>!0===e||!1===e,isObject:Oe,isPlainObject:De,isEmptyObject:e=>{if(!Oe(e)||xe(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(t){return!1}},isReadableStream:Ke,isRequest:$e,isResponse:He,isHeaders:qe,isUndefined:Re,isDate:Fe,isFile:Me,isBlob:Ue,isRegExp:Ze,isFunction:_e,isStream:e=>Oe(e)&&_e(e.pipe),isURLSearchParams:Le,isTypedArray:Je,isFileList:Be,forEach:je,merge:function e(){const{caseless:t}=Ge(this)&&this||{},r={},i=(i,n)=>{const o=t&&We(r,n)||n;De(r[o])&&De(i)?r[o]=e(r[o],i):De(i)?r[o]=e({},i):Ce(i)?r[o]=i.slice():r[o]=i};for(let n=0,o=arguments.length;n<o;n++)arguments[n]&&je(arguments[n],i);return r},extend:(e,t,r,{allOwnKeys:i}={})=>(je(t,(t,i)=>{r&&_e(t)?e[i]=we(t,r):e[i]=t},{allOwnKeys:i}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,i)=>{let n,o,s;const a={};if(t=t||{},null==e)return t;do{for(n=Object.getOwnPropertyNames(e),o=n.length;o-- >0;)s=n[o],i&&!i(s,e,t)||a[s]||(t[s]=e[s],a[s]=!0);e=!1!==r&&Te(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:ve,kindOfTest:Ee,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const i=e.indexOf(t,r);return-1!==i&&i===r},toArray:e=>{if(!e)return null;if(Ce(e))return e;let t=e.length;if(!Pe(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Se]).call(e);let i;for(;(i=r.next())&&!i.done;){const r=i.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const i=[];for(;null!==(r=e.exec(t));)i.push(r);return i},isHTMLForm:Ye,hasOwnProperty:Xe,hasOwnProp:Xe,reduceDescriptors:Qe,freezeMethods:e=>{Qe(e,(t,r)=>{if(_e(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const i=e[r];_e(i)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))})},toObjectSet:(e,t)=>{const r={},i=e=>{e.forEach(e=>{r[e]=!0})};return Ce(e)?i(e):i(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,r){return t.toUpperCase()+r}),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:We,global:Ve,isContextDefined:Ge,isSpecCompliantForm:function(e){return!!(e&&_e(e.append)&&"FormData"===e[ke]&&e[Se])},toJSONObject:e=>{const t=new Array(10),r=(e,i)=>{if(Oe(e)){if(t.indexOf(e)>=0)return;if(xe(e))return e;if(!("toJSON"in e)){t[i]=e;const n=Ce(e)?[]:{};return je(e,(e,t)=>{const o=r(e,i+1);!Re(o)&&(n[t]=o)}),t[i]=void 0,n}}return e};return r(e,0)},isAsyncFn:et,isThenable:e=>e&&(Oe(e)||_e(e))&&_e(e.then)&&_e(e.catch),setImmediate:tt,asap:st,isIterable:e=>null!=e&&_e(e[Se])};function ct(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}at.inherits(ct,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:at.toJSONObject(this.config),code:this.code,status:this.status}}});const lt=ct.prototype,ut={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{ut[e]={value:e}}),Object.defineProperties(ct,ut),Object.defineProperty(lt,"isAxiosError",{value:!0}),ct.from=(e,t,r,i,n,o)=>{const s=Object.create(lt);return at.toFlatObject(e,s,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),ct.call(s,e.message,t,r,i,n),s.cause=e,s.name=e.name,o&&Object.assign(s,o),s};function dt(e){return at.isPlainObject(e)||at.isArray(e)}function pt(e){return at.endsWith(e,"[]")?e.slice(0,-2):e}function ht(e,t,r){return e?e.concat(t).map(function(e,t){return e=pt(e),!r&&t?"["+e+"]":e}).join(r?".":""):t}const gt=at.toFlatObject(at,{},null,function(e){return/^is[A-Z]/.test(e)});function mt(e,t,r){if(!at.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const i=(r=at.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!at.isUndefined(t[e])})).metaTokens,n=r.visitor||l,o=r.dots,s=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&at.isSpecCompliantForm(t);if(!at.isFunction(n))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(at.isDate(e))return e.toISOString();if(at.isBoolean(e))return e.toString();if(!a&&at.isBlob(e))throw new ct("Blob is not supported. Use a Buffer instead.");return at.isArrayBuffer(e)||at.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Q.from(e):e}function l(e,r,n){let a=e;if(e&&!n&&"object"==typeof e)if(at.endsWith(r,"{}"))r=i?r:r.slice(0,-2),e=JSON.stringify(e);else if(at.isArray(e)&&function(e){return at.isArray(e)&&!e.some(dt)}(e)||(at.isFileList(e)||at.endsWith(r,"[]"))&&(a=at.toArray(e)))return r=pt(r),a.forEach(function(e,i){!at.isUndefined(e)&&null!==e&&t.append(!0===s?ht([r],i,o):null===s?r:r+"[]",c(e))}),!1;return!!dt(e)||(t.append(ht(n,r,o),c(e)),!1)}const u=[],d=Object.assign(gt,{defaultVisitor:l,convertValue:c,isVisitable:dt});if(!at.isObject(e))throw new TypeError("data must be an object");return function e(r,i){if(!at.isUndefined(r)){if(-1!==u.indexOf(r))throw Error("Circular reference detected in "+i.join("."));u.push(r),at.forEach(r,function(r,o){!0===(!(at.isUndefined(r)||null===r)&&n.call(t,r,at.isString(o)?o.trim():o,i,d))&&e(r,i?i.concat(o):[o])}),u.pop()}}(e),t}function ft(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function yt(e,t){this._pairs=[],e&&mt(e,this,t)}const bt=yt.prototype;function wt(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function It(e,t,r){if(!t)return e;const i=r&&r.encode||wt;at.isFunction(r)&&(r={serialize:r});const n=r&&r.serialize;let o;if(o=n?n(t,r):at.isURLSearchParams(t)?t.toString():new yt(t,r).toString(i),o){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+o}return e}bt.append=function(e,t){this._pairs.push([e,t])},bt.toString=function(e){const t=e?function(t){return e.call(this,t,ft)}:ft;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class Tt{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){at.forEach(this.handlers,function(t){null!==t&&e(t)})}}const St={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},kt={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:yt,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},vt="undefined"!=typeof window&&"undefined"!=typeof document,Et="object"==typeof navigator&&navigator||void 0,At=vt&&(!Et||["ReactNative","NativeScript","NS"].indexOf(Et.product)<0),Ct="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Rt=vt&&window.location.href||"http://localhost",xt={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:vt,hasStandardBrowserEnv:At,hasStandardBrowserWebWorkerEnv:Ct,navigator:Et,origin:Rt},Symbol.toStringTag,{value:"Module"})),...kt};function Nt(e){function t(e,r,i,n){let o=e[n++];if("__proto__"===o)return!0;const s=Number.isFinite(+o),a=n>=e.length;if(o=!o&&at.isArray(i)?i.length:o,a)return at.hasOwnProp(i,o)?i[o]=[i[o],r]:i[o]=r,!s;i[o]&&at.isObject(i[o])||(i[o]=[]);return t(e,r,i[o],n)&&at.isArray(i[o])&&(i[o]=function(e){const t={},r=Object.keys(e);let i;const n=r.length;let o;for(i=0;i<n;i++)o=r[i],t[o]=e[o];return t}(i[o])),!s}if(at.isFormData(e)&&at.isFunction(e.entries)){const r={};return at.forEachEntry(e,(e,i)=>{t(function(e){return at.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),i,r,0)}),r}return null}const zt={transitional:St,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",i=r.indexOf("application/json")>-1,n=at.isObject(e);n&&at.isHTMLForm(e)&&(e=new FormData(e));if(at.isFormData(e))return i?JSON.stringify(Nt(e)):e;if(at.isArrayBuffer(e)||at.isBuffer(e)||at.isStream(e)||at.isFile(e)||at.isBlob(e)||at.isReadableStream(e))return e;if(at.isArrayBufferView(e))return e.buffer;if(at.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let o;if(n){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return mt(e,new xt.classes.URLSearchParams,{visitor:function(e,t,r,i){return xt.isNode&&at.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}(e,this.formSerializer).toString();if((o=at.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return mt(o?{"files[]":e}:e,t&&new t,this.formSerializer)}}return n||i?(t.setContentType("application/json",!1),function(e,t,r){if(at.isString(e))try{return(t||JSON.parse)(e),at.trim(e)}catch(i){if("SyntaxError"!==i.name)throw i}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||zt.transitional,r=t&&t.forcedJSONParsing,i="json"===this.responseType;if(at.isResponse(e)||at.isReadableStream(e))return e;if(e&&at.isString(e)&&(r&&!this.responseType||i)){const r=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(n){if(r){if("SyntaxError"===n.name)throw ct.from(n,ct.ERR_BAD_RESPONSE,this,null,this.response);throw n}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:xt.classes.FormData,Blob:xt.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};at.forEach(["delete","get","head","post","put","patch"],e=>{zt.headers[e]={}});const _t=at.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Pt=Symbol("internals");function Ot(e){return e&&String(e).trim().toLowerCase()}function Dt(e){return!1===e||null==e?e:at.isArray(e)?e.map(Dt):String(e)}function Ft(e,t,r,i,n){return at.isFunction(i)?i.call(this,t,r):(n&&(t=r),at.isString(t)?at.isString(i)?-1!==t.indexOf(i):at.isRegExp(i)?i.test(t):void 0:void 0)}let Mt=class{constructor(e){e&&this.set(e)}set(e,t,r){const i=this;function n(e,t,r){const n=Ot(t);if(!n)throw new Error("header name must be a non-empty string");const o=at.findKey(i,n);(!o||void 0===i[o]||!0===r||void 0===r&&!1!==i[o])&&(i[o||t]=Dt(e))}const o=(e,t)=>at.forEach(e,(e,r)=>n(e,r,t));if(at.isPlainObject(e)||e instanceof this.constructor)o(e,t);else if(at.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))o((e=>{const t={};let r,i,n;return e&&e.split("\n").forEach(function(e){n=e.indexOf(":"),r=e.substring(0,n).trim().toLowerCase(),i=e.substring(n+1).trim(),!r||t[r]&&_t[r]||("set-cookie"===r?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t})(e),t);else if(at.isObject(e)&&at.isIterable(e)){let r,i,n={};for(const t of e){if(!at.isArray(t))throw TypeError("Object iterator must return a key-value pair");n[i=t[0]]=(r=n[i])?at.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}o(n,t)}else null!=e&&n(t,e,r);return this}get(e,t){if(e=Ot(e)){const r=at.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let i;for(;i=r.exec(e);)t[i[1]]=i[2];return t}(e);if(at.isFunction(t))return t.call(this,e,r);if(at.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Ot(e)){const r=at.findKey(this,e);return!(!r||void 0===this[r]||t&&!Ft(0,this[r],r,t))}return!1}delete(e,t){const r=this;let i=!1;function n(e){if(e=Ot(e)){const n=at.findKey(r,e);!n||t&&!Ft(0,r[n],n,t)||(delete r[n],i=!0)}}return at.isArray(e)?e.forEach(n):n(e),i}clear(e){const t=Object.keys(this);let r=t.length,i=!1;for(;r--;){const n=t[r];e&&!Ft(0,this[n],n,e,!0)||(delete this[n],i=!0)}return i}normalize(e){const t=this,r={};return at.forEach(this,(i,n)=>{const o=at.findKey(r,n);if(o)return t[o]=Dt(i),void delete t[n];const s=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,r)=>t.toUpperCase()+r)}(n):String(n).trim();s!==n&&delete t[n],t[s]=Dt(i),r[s]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return at.forEach(this,(r,i)=>{null!=r&&!1!==r&&(t[i]=e&&at.isArray(r)?r.join(", "):r)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach(e=>r.set(e)),r}static accessor(e){const t=(this[Pt]=this[Pt]={accessors:{}}).accessors,r=this.prototype;function i(e){const i=Ot(e);t[i]||(!function(e,t){const r=at.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+r,{value:function(e,r,n){return this[i].call(this,t,e,r,n)},configurable:!0})})}(r,e),t[i]=!0)}return at.isArray(e)?e.forEach(i):i(e),this}};function Ut(e,t){const r=this||zt,i=t||r,n=Mt.from(i.headers);let o=i.data;return at.forEach(e,function(e){o=e.call(r,o,n.normalize(),t?t.status:void 0)}),n.normalize(),o}function Bt(e){return!(!e||!e.__CANCEL__)}function Lt(e,t,r){ct.call(this,null==e?"canceled":e,ct.ERR_CANCELED,t,r),this.name="CanceledError"}function Kt(e,t,r){const i=r.config.validateStatus;r.status&&i&&!i(r.status)?t(new ct("Request failed with status code "+r.status,[ct.ERR_BAD_REQUEST,ct.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}Mt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),at.reduceDescriptors(Mt.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}}),at.freezeMethods(Mt),at.inherits(Lt,ct,{__CANCEL__:!0});const $t=(e,t,r=3)=>{let i=0;const n=function(e,t){e=e||10;const r=new Array(e),i=new Array(e);let n,o=0,s=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),l=i[s];n||(n=c),r[o]=a,i[o]=c;let u=s,d=0;for(;u!==o;)d+=r[u++],u%=e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),c-n<t)return;const p=l&&c-l;return p?Math.round(1e3*d/p):void 0}}(50,250);return function(e,t){let r,i,n=0,o=1e3/t;const s=(t,o=Date.now())=>{n=o,r=null,i&&(clearTimeout(i),i=null),e(...t)};return[(...e)=>{const t=Date.now(),a=t-n;a>=o?s(e,t):(r=e,i||(i=setTimeout(()=>{i=null,s(r)},o-a)))},()=>r&&s(r)]}(r=>{const o=r.loaded,s=r.lengthComputable?r.total:void 0,a=o-i,c=n(a);i=o;e({loaded:o,total:s,progress:s?o/s:void 0,bytes:a,rate:c||void 0,estimated:c&&s&&o<=s?(s-o)/c:void 0,event:r,lengthComputable:null!=s,[t?"download":"upload"]:!0})},r)},Ht=(e,t)=>{const r=null!=e;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},qt=e=>(...t)=>at.asap(()=>e(...t)),jt=xt.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,xt.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(xt.origin),xt.navigator&&/(msie|trident)/i.test(xt.navigator.userAgent)):()=>!0,Wt=xt.hasStandardBrowserEnv?{write(e,t,r,i,n,o){const s=[e+"="+encodeURIComponent(t)];at.isNumber(r)&&s.push("expires="+new Date(r).toGMTString()),at.isString(i)&&s.push("path="+i),at.isString(n)&&s.push("domain="+n),!0===o&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function Vt(e,t,r){let i=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(i||0==r)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const Gt=e=>e instanceof Mt?{...e}:e;function Jt(e,t){t=t||{};const r={};function i(e,t,r,i){return at.isPlainObject(e)&&at.isPlainObject(t)?at.merge.call({caseless:i},e,t):at.isPlainObject(t)?at.merge({},t):at.isArray(t)?t.slice():t}function n(e,t,r,n){return at.isUndefined(t)?at.isUndefined(e)?void 0:i(void 0,e,0,n):i(e,t,0,n)}function o(e,t){if(!at.isUndefined(t))return i(void 0,t)}function s(e,t){return at.isUndefined(t)?at.isUndefined(e)?void 0:i(void 0,e):i(void 0,t)}function a(r,n,o){return o in t?i(r,n):o in e?i(void 0,r):void 0}const c={url:o,method:o,data:o,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:a,headers:(e,t,r)=>n(Gt(e),Gt(t),0,!0)};return at.forEach(Object.keys({...e,...t}),function(i){const o=c[i]||n,s=o(e[i],t[i],i);at.isUndefined(s)&&o!==a||(r[i]=s)}),r}const Yt=e=>{const t=Jt({},e);let r,{data:i,withXSRFToken:n,xsrfHeaderName:o,xsrfCookieName:s,headers:a,auth:c}=t;if(t.headers=a=Mt.from(a),t.url=It(Vt(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),at.isFormData(i))if(xt.hasStandardBrowserEnv||xt.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(r=a.getContentType())){const[e,...t]=r?r.split(";").map(e=>e.trim()).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(xt.hasStandardBrowserEnv&&(n&&at.isFunction(n)&&(n=n(t)),n||!1!==n&&jt(t.url))){const e=o&&s&&Wt.read(s);e&&a.set(o,e)}return t},Xt="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,r){const i=Yt(e);let n=i.data;const o=Mt.from(i.headers).normalize();let s,a,c,l,u,{responseType:d,onUploadProgress:p,onDownloadProgress:h}=i;function g(){l&&l(),u&&u(),i.cancelToken&&i.cancelToken.unsubscribe(s),i.signal&&i.signal.removeEventListener("abort",s)}let m=new XMLHttpRequest;function f(){if(!m)return;const i=Mt.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());Kt(function(e){t(e),g()},function(e){r(e),g()},{data:d&&"text"!==d&&"json"!==d?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:i,config:e,request:m}),m=null}m.open(i.method.toUpperCase(),i.url,!0),m.timeout=i.timeout,"onloadend"in m?m.onloadend=f:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(f)},m.onabort=function(){m&&(r(new ct("Request aborted",ct.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new ct("Network Error",ct.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let t=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const n=i.transitional||St;i.timeoutErrorMessage&&(t=i.timeoutErrorMessage),r(new ct(t,n.clarifyTimeoutError?ct.ETIMEDOUT:ct.ECONNABORTED,e,m)),m=null},void 0===n&&o.setContentType(null),"setRequestHeader"in m&&at.forEach(o.toJSON(),function(e,t){m.setRequestHeader(t,e)}),at.isUndefined(i.withCredentials)||(m.withCredentials=!!i.withCredentials),d&&"json"!==d&&(m.responseType=i.responseType),h&&([c,u]=$t(h,!0),m.addEventListener("progress",c)),p&&m.upload&&([a,l]=$t(p),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",l)),(i.cancelToken||i.signal)&&(s=t=>{m&&(r(!t||t.type?new Lt(null,e,m):t),m.abort(),m=null)},i.cancelToken&&i.cancelToken.subscribe(s),i.signal&&(i.signal.aborted?s():i.signal.addEventListener("abort",s)));const y=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(i.url);y&&-1===xt.protocols.indexOf(y)?r(new ct("Unsupported protocol "+y+":",ct.ERR_BAD_REQUEST,e)):m.send(n||null)})},Zt=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,i=new AbortController;const n=function(e){if(!r){r=!0,s();const t=e instanceof Error?e:this.reason;i.abort(t instanceof ct?t:new Lt(t instanceof Error?t.message:t))}};let o=t&&setTimeout(()=>{o=null,n(new ct(`timeout ${t} of ms exceeded`,ct.ETIMEDOUT))},t);const s=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(n):e.removeEventListener("abort",n)}),e=null)};e.forEach(e=>e.addEventListener("abort",n));const{signal:a}=i;return a.unsubscribe=()=>at.asap(s),a}},Qt=function*(e,t){let r=e.byteLength;if(r<t)return void(yield e);let i,n=0;for(;n<r;)i=n+t,yield e.slice(n,i),n=i},er=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)break;yield r}}finally{await t.cancel()}},tr=(e,t,r,i)=>{const n=async function*(e,t){for await(const r of er(e))yield*Qt(r,t)}(e,t);let o,s=0,a=e=>{o||(o=!0,i&&i(e))};return new ReadableStream({async pull(e){try{const{done:t,value:i}=await n.next();if(t)return a(),void e.close();let o=i.byteLength;if(r){let e=s+=o;r(e)}e.enqueue(new Uint8Array(i))}catch(t){throw a(t),t}},cancel:e=>(a(e),n.return())},{highWaterMark:2})},rr="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,ir=rr&&"function"==typeof ReadableStream,nr=rr&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),or=(e,...t)=>{try{return!!e(...t)}catch(r){return!1}},sr=ir&&or(()=>{let e=!1;const t=new Request(xt.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),ar=ir&&or(()=>at.isReadableStream(new Response("").body)),cr={stream:ar&&(e=>e.body)};var lr;rr&&(lr=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!cr[e]&&(cr[e]=at.isFunction(lr[e])?t=>t[e]():(t,r)=>{throw new ct(`Response type '${e}' is not supported`,ct.ERR_NOT_SUPPORT,r)})}));const ur=async(e,t)=>{const r=at.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(at.isBlob(e))return e.size;if(at.isSpecCompliantForm(e)){const t=new Request(xt.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return at.isArrayBufferView(e)||at.isArrayBuffer(e)?e.byteLength:(at.isURLSearchParams(e)&&(e+=""),at.isString(e)?(await nr(e)).byteLength:void 0)})(t):r},dr={http:null,xhr:Xt,fetch:rr&&(async e=>{let{url:t,method:r,data:i,signal:n,cancelToken:o,timeout:s,onDownloadProgress:a,onUploadProgress:c,responseType:l,headers:u,withCredentials:d="same-origin",fetchOptions:p}=Yt(e);l=l?(l+"").toLowerCase():"text";let h,g=Zt([n,o&&o.toAbortSignal()],s);const m=g&&g.unsubscribe&&(()=>{g.unsubscribe()});let f;try{if(c&&sr&&"get"!==r&&"head"!==r&&0!==(f=await ur(u,i))){let e,r=new Request(t,{method:"POST",body:i,duplex:"half"});if(at.isFormData(i)&&(e=r.headers.get("content-type"))&&u.setContentType(e),r.body){const[e,t]=Ht(f,$t(qt(c)));i=tr(r.body,65536,e,t)}}at.isString(d)||(d=d?"include":"omit");const n="credentials"in Request.prototype;h=new Request(t,{...p,signal:g,method:r.toUpperCase(),headers:u.normalize().toJSON(),body:i,duplex:"half",credentials:n?d:void 0});let o=await fetch(h,p);const s=ar&&("stream"===l||"response"===l);if(ar&&(a||s&&m)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=o[t]});const t=at.toFiniteNumber(o.headers.get("content-length")),[r,i]=a&&Ht(t,$t(qt(a),!0))||[];o=new Response(tr(o.body,65536,r,()=>{i&&i(),m&&m()}),e)}l=l||"text";let y=await cr[at.findKey(cr,l)||"text"](o,e);return!s&&m&&m(),await new Promise((t,r)=>{Kt(t,r,{data:y,headers:Mt.from(o.headers),status:o.status,statusText:o.statusText,config:e,request:h})})}catch(y){if(m&&m(),y&&"TypeError"===y.name&&/Load failed|fetch/i.test(y.message))throw Object.assign(new ct("Network Error",ct.ERR_NETWORK,e,h),{cause:y.cause||y});throw ct.from(y,y&&y.code,e,h)}})};at.forEach(dr,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(r){}Object.defineProperty(e,"adapterName",{value:t})}});const pr=e=>`- ${e}`,hr=e=>at.isFunction(e)||null===e||!1===e,gr=e=>{e=at.isArray(e)?e:[e];const{length:t}=e;let r,i;const n={};for(let o=0;o<t;o++){let t;if(r=e[o],i=r,!hr(r)&&(i=dr[(t=String(r)).toLowerCase()],void 0===i))throw new ct(`Unknown adapter '${t}'`);if(i)break;n[t||"#"+o]=i}if(!i){const e=Object.entries(n).map(([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));throw new ct("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(pr).join("\n"):" "+pr(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return i};function mr(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Lt(null,e)}function fr(e){mr(e),e.headers=Mt.from(e.headers),e.data=Ut.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return gr(e.adapter||zt.adapter)(e).then(function(t){return mr(e),t.data=Ut.call(e,e.transformResponse,t),t.headers=Mt.from(t.headers),t},function(t){return Bt(t)||(mr(e),t&&t.response&&(t.response.data=Ut.call(e,e.transformResponse,t.response),t.response.headers=Mt.from(t.response.headers))),Promise.reject(t)})}const yr="1.11.0",br={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{br[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const wr={};br.transitional=function(e,t,r){function i(e,t){return"[Axios v"+yr+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,n,o)=>{if(!1===e)throw new ct(i(n," has been removed"+(t?" in "+t:"")),ct.ERR_DEPRECATED);return t&&!wr[n]&&(wr[n]=!0,console.warn(i(n," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,n,o)}},br.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};const Ir={assertOptions:function(e,t,r){if("object"!=typeof e)throw new ct("options must be an object",ct.ERR_BAD_OPTION_VALUE);const i=Object.keys(e);let n=i.length;for(;n-- >0;){const o=i[n],s=t[o];if(s){const t=e[o],r=void 0===t||s(t,o,e);if(!0!==r)throw new ct("option "+o+" must be "+r,ct.ERR_BAD_OPTION_VALUE);continue}if(!0!==r)throw new ct("Unknown option "+o,ct.ERR_BAD_OPTION)}},validators:br},Tr=Ir.validators;let Sr=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Tt,response:new Tt}}async request(e,t){try{return await this._request(e,t)}catch(r){if(r instanceof Error){let e={};Error.captureStackTrace?Error.captureStackTrace(e):e=new Error;const t=e.stack?e.stack.replace(/^.+\n/,""):"";try{r.stack?t&&!String(r.stack).endsWith(t.replace(/^.+\n.+\n/,""))&&(r.stack+="\n"+t):r.stack=t}catch(i){}}throw r}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=Jt(this.defaults,t);const{transitional:r,paramsSerializer:i,headers:n}=t;void 0!==r&&Ir.assertOptions(r,{silentJSONParsing:Tr.transitional(Tr.boolean),forcedJSONParsing:Tr.transitional(Tr.boolean),clarifyTimeoutError:Tr.transitional(Tr.boolean)},!1),null!=i&&(at.isFunction(i)?t.paramsSerializer={serialize:i}:Ir.assertOptions(i,{encode:Tr.function,serialize:Tr.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Ir.assertOptions(t,{baseUrl:Tr.spelling("baseURL"),withXsrfToken:Tr.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let o=n&&at.merge(n.common,n[t.method]);n&&at.forEach(["delete","get","head","post","put","patch","common"],e=>{delete n[e]}),t.headers=Mt.concat(o,n);const s=[];let a=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,s.unshift(e.fulfilled,e.rejected))});const c=[];let l;this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let u,d=0;if(!a){const e=[fr.bind(this),void 0];for(e.unshift(...s),e.push(...c),u=e.length,l=Promise.resolve(t);d<u;)l=l.then(e[d++],e[d++]);return l}u=s.length;let p=t;for(d=0;d<u;){const e=s[d++],t=s[d++];try{p=e(p)}catch(h){t.call(this,h);break}}try{l=fr.call(this,p)}catch(h){return Promise.reject(h)}for(d=0,u=c.length;d<u;)l=l.then(c[d++],c[d++]);return l}getUri(e){return It(Vt((e=Jt(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};at.forEach(["delete","get","head","options"],function(e){Sr.prototype[e]=function(t,r){return this.request(Jt(r||{},{method:e,url:t,data:(r||{}).data}))}}),at.forEach(["post","put","patch"],function(e){function t(t){return function(r,i,n){return this.request(Jt(n||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:i}))}}Sr.prototype[e]=t(),Sr.prototype[e+"Form"]=t(!0)});const kr={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(kr).forEach(([e,t])=>{kr[t]=e});const vr=function e(t){const r=new Sr(t),i=we(Sr.prototype.request,r);return at.extend(i,Sr.prototype,r,{allOwnKeys:!0}),at.extend(i,r,null,{allOwnKeys:!0}),i.create=function(r){return e(Jt(t,r))},i}(zt);vr.Axios=Sr,vr.CanceledError=Lt,vr.CancelToken=class e{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(e){t=e});const r=this;this.promise.then(e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null}),this.promise.then=e=>{let t;const i=new Promise(e=>{r.subscribe(e),t=e}).then(e);return i.cancel=function(){r.unsubscribe(t)},i},e(function(e,i,n){r.reason||(r.reason=new Lt(e,i,n),t(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;return{token:new e(function(e){t=e}),cancel:t}}},vr.isCancel=Bt,vr.VERSION=yr,vr.toFormData=mt,vr.AxiosError=ct,vr.Cancel=vr.CanceledError,vr.all=function(e){return Promise.all(e)},vr.spread=function(e){return function(t){return e.apply(null,t)}},vr.isAxiosError=function(e){return at.isObject(e)&&!0===e.isAxiosError},vr.mergeConfig=Jt,vr.AxiosHeaders=Mt,vr.formToJSON=e=>Nt(at.isHTMLForm(e)?new FormData(e):e),vr.getAdapter=gr,vr.HttpStatusCode=kr,vr.default=vr;const{Axios:Er,AxiosError:Ar,CanceledError:Cr,isCancel:Rr,CancelToken:xr,VERSION:Nr,all:zr,Cancel:_r,isAxiosError:Pr,spread:Or,toFormData:Dr,AxiosHeaders:Fr,HttpStatusCode:Mr,formToJSON:Ur,getAdapter:Br,mergeConfig:Lr}=vr,Kr=class e{constructor(){K(this,"isProduction"),this.isProduction="production"===be.env.NODE_ENV}static getInstance(){return e.instance||(e.instance=new e),e.instance}debug(e,...t){this.isProduction||console.debug(e,...t)}info(e,...t){this.isProduction||console.info(e,...t)}warn(e,...t){console.warn(e,...t)}error(e,...t){console.error(e,...t)}};K(Kr,"instance");let $r=Kr;class Hr extends Error{constructor(e){super(e),this.name="ValidationError"}}function qr(e){try{return{detectedType:"ecdsa",privateKey:r.PrivateKey.fromStringECDSA(e)}}catch(t){try{return{detectedType:"ed25519",privateKey:r.PrivateKey.fromStringED25519(e)}}catch{throw new Error(`Failed to parse private key as either ECDSA or ED25519: ${String(t)}`)}}}class jr{constructor(e){if(K(this,"accountId"),K(this,"privateKey"),K(this,"baseUrl"),K(this,"network"),this.accountId=e.accountId,"string"==typeof e.privateKey){const t=qr(e.privateKey);this.privateKey=t.privateKey}else this.privateKey=e.privateKey;this.network=e.network||"mainnet",this.baseUrl=function(e){let t=e.trim();return t=t.replace(/\/+$/,""),t.endsWith("/api")?t.slice(0,-4):t}(e.baseUrl||"https://kiloscribe.com")}async authenticate(){var e,t,r;const i=await vr.get(`${this.baseUrl}/api/auth/request-signature`,{headers:{"x-session":this.accountId}});if(!(null==(e=i.data)?void 0:e.message))throw new Error("Failed to get signature message");const n=i.data.message,o=await this.signMessage(n),s=await vr.post(`${this.baseUrl}/api/auth/authenticate`,{authData:{id:this.accountId,signature:o,data:n,network:this.network},include:"apiKey"});if(!(null==(r=null==(t=s.data)?void 0:t.user)?void 0:r.sessionToken))throw new Error("Authentication failed");return{apiKey:s.data.apiKey}}async signMessage(e){const t=(new TextEncoder).encode(e),r=await this.privateKey.sign(t);return ee.from(r).toString("hex")}}class Wr{constructor(e,t){K(this,"baseUrl"),this.baseUrl=t??function(e){return"mainnet"===e?"https://mainnet-public.mirrornode.hedera.com":"https://testnet.mirrornode.hedera.com"}(e)}async requestAccount(e){return(await vr.get(`${this.baseUrl}/api/v1/accounts/${e}`)).data}}class Vr{constructor(e){K(this,"accountId"),K(this,"signer"),K(this,"baseUrl"),K(this,"network"),K(this,"logger"),this.accountId=e.accountId,this.signer=e.signer,this.network=e.network||"mainnet",this.baseUrl=e.baseUrl||"https://kiloscribe.com",this.logger=e.logger}async authenticate(){var e,t,r;const i=await vr.get(`${this.baseUrl}/api/auth/request-signature`,{headers:{"x-session":this.accountId}});if(!(null==(e=i.data)?void 0:e.message))throw new Error("Failed to get signature message");const n=i.data.message,o=await this.signMessage(JSON.stringify(n)),s=await vr.post(`${this.baseUrl}/api/auth/authenticate`,{authData:{id:this.accountId,signature:o,data:n,network:this.network},include:"apiKey"});if(!(null==(r=null==(t=s.data)?void 0:t.user)?void 0:r.sessionToken))throw new Error("Authentication failed");return{apiKey:s.data.apiKey}}async signMessage(e){try{const t=(new TextEncoder).encode(e);this.logger.debug("signing message");const r=await this.signer.sign([t],{encoding:"utf-8"});return ee.from(null==r?void 0:r[0].signature).toString("hex")}catch(t){throw this.logger.error("Failed to sign message",t),new Error("Failed to sign message")}}}function Gr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Jr(e){return new DataView(e.buffer,e.byteOffset)}const Yr={len:1,get:(e,t)=>Jr(e).getUint8(t),put:(e,t,r)=>(Jr(e).setUint8(t,r),t+1)},Xr={len:2,get:(e,t)=>Jr(e).getUint16(t,!0),put:(e,t,r)=>(Jr(e).setUint16(t,r,!0),t+2)},Zr={len:2,get:(e,t)=>Jr(e).getUint16(t),put:(e,t,r)=>(Jr(e).setUint16(t,r),t+2)},Qr={len:4,get:(e,t)=>Jr(e).getUint32(t,!0),put:(e,t,r)=>(Jr(e).setUint32(t,r,!0),t+4)},ei={len:4,get:(e,t)=>Jr(e).getUint32(t),put:(e,t,r)=>(Jr(e).setUint32(t,r),t+4)},ti={len:4,get:(e,t)=>Jr(e).getInt32(t),put:(e,t,r)=>(Jr(e).setInt32(t,r),t+4)},ri={len:8,get:(e,t)=>Jr(e).getBigUint64(t,!0),put:(e,t,r)=>(Jr(e).setBigUint64(t,r,!0),t+8)};class ii{constructor(e,t){if(this.len=e,t&&"windows-1252"===t.toLowerCase())this.decoder=ii.decodeWindows1252;else{const e=new TextDecoder(t);this.decoder=t=>e.decode(t)}}get(e,t=0){const r=e.subarray(t,t+this.len);return this.decoder(r)}static decodeWindows1252(e){let t="";for(let r=0;r<e.length;r++){const i=e[r];t+=i<128||i>=160?String.fromCharCode(i):ii.win1252Map[i-128]}return t}}ii.win1252Map="€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ";class ni extends Error{constructor(){super("End-Of-Stream"),this.name="EndOfStreamError"}}class oi extends Error{constructor(e="The operation was aborted"){super(e),this.name="AbortError"}}class si{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){const r=await this.read(e,t);return this.peekQueue.push(e.subarray(0,r)),r}async read(e,t=!1){if(0===e.length)return 0;let r=this.readFromPeekBuffer(e);if(this.endOfStream||(r+=await this.readRemainderFromStream(e.subarray(r),t)),0===r&&!t)throw new ni;return r}readFromPeekBuffer(e){let t=e.length,r=0;for(;this.peekQueue.length>0&&t>0;){const i=this.peekQueue.pop();if(!i)throw new Error("peekData should be defined");const n=Math.min(i.length,t);e.set(i.subarray(0,n),r),r+=n,t-=n,n<i.length&&this.peekQueue.push(i.subarray(n))}return r}async readRemainderFromStream(e,t){let r=0;for(;r<e.length&&!this.endOfStream;){if(this.interrupted)throw new oi;const i=await this.readFromStream(e.subarray(r),t);if(0===i)break;r+=i}if(!t&&r<e.length)throw new ni;return r}}class ai extends si{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}}class ci extends ai{async readFromStream(e,t){if(0===e.length)return 0;const r=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return r.done&&(this.endOfStream=r.done),r.value?(e.set(r.value),r.value.length):0}}class li extends si{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){const r=Math.min(t.length,e.length);return e.set(t.subarray(0,r)),r<t.length?this.buffer=t.subarray(r):this.buffer=null,r}async readFromStream(e,t){if(0===e.length)return 0;let r=0;for(this.buffer&&(r+=this.writeChunk(e,this.buffer));r<e.length&&!this.endOfStream;){const t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(r+=this.writeChunk(e.subarray(r),t.value))}if(!t&&0===r&&this.endOfStream)throw new ni;return r}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}}class ui{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=null==e?void 0:e.onClose,(null==e?void 0:e.abortSignal)&&e.abortSignal.addEventListener("abort",()=>{this.abort()})}async readToken(e,t=this.position){const r=new Uint8Array(e.len);if(await this.readBuffer(r,{position:t})<e.len)throw new ni;return e.get(r,0)}async peekToken(e,t=this.position){const r=new Uint8Array(e.len);if(await this.peekBuffer(r,{position:t})<e.len)throw new ni;return e.get(r,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new ni;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new ni;return e.get(this.numBuffer,0)}async ignore(e){if(void 0!==this.fileInfo.size){const t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){var e;await this.abort(),await(null==(e=this.onClose)?void 0:e.call(this))}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&void 0!==t.position&&t.position<this.position)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}}class di extends ui{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=(null==t?void 0:t.fileInfo)??{}}async readBuffer(e,t){const r=this.normalizeOptions(e,t),i=r.position-this.position;if(i>0)return await this.ignore(i),this.readBuffer(e,t);if(i<0)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");if(0===r.length)return 0;const n=await this.streamReader.read(e.subarray(0,r.length),r.mayBeLess);if(this.position+=n,(!t||!t.mayBeLess)&&n<r.length)throw new ni;return n}async peekBuffer(e,t){const r=this.normalizeOptions(e,t);let i=0;if(r.position){const t=r.position-this.position;if(t>0){const n=new Uint8Array(r.length+t);return i=await this.peekBuffer(n,{mayBeLess:r.mayBeLess}),e.set(n.subarray(t)),i-t}if(t<0)throw new Error("Cannot peek from a negative offset in a stream")}if(r.length>0){try{i=await this.streamReader.peek(e.subarray(0,r.length),r.mayBeLess)}catch(n){if((null==t?void 0:t.mayBeLess)&&n instanceof ni)return 0;throw n}if(!r.mayBeLess&&i<r.length)throw new ni}return i}async ignore(e){const t=Math.min(256e3,e),r=new Uint8Array(t);let i=0;for(;i<e;){const n=e-i,o=await this.readBuffer(r,{length:Math.min(t,n)});if(o<0)return o;i+=o}return i}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}}class pi extends ui{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...(null==t?void 0:t.fileInfo)??{},size:e.length}}async readBuffer(e,t){(null==t?void 0:t.position)&&(this.position=t.position);const r=await this.peekBuffer(e,t);return this.position+=r,r}async peekBuffer(e,t){const r=this.normalizeOptions(e,t),i=Math.min(this.uint8Array.length-r.position,r.length);if(!r.mayBeLess&&i<r.length)throw new ni;return e.set(this.uint8Array.subarray(r.position,r.position+i)),i}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}}function hi(e,t){const r=function(e){try{const t=e.getReader({mode:"byob"});return t instanceof ReadableStreamDefaultReader?new li(t):new ci(t)}catch(t){if(t instanceof TypeError)return new li(e.getReader());throw t}}(e),i=t??{},n=i.onClose;return i.onClose=async()=>{if(await r.close(),n)return n()},new di(r,i)}var gi=Uint8Array,mi=Uint16Array,fi=Int32Array,yi=new gi([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),bi=new gi([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),wi=new gi([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ii=function(e,t){for(var r=new mi(31),i=0;i<31;++i)r[i]=t+=1<<e[i-1];var n=new fi(r[30]);for(i=1;i<30;++i)for(var o=r[i];o<r[i+1];++o)n[o]=o-r[i]<<5|i;return{b:r,r:n}},Ti=Ii(yi,2),Si=Ti.b,ki=Ti.r;Si[28]=258,ki[258]=28;for(var vi=Ii(bi,0).b,Ei=new mi(32768),Ai=0;Ai<32768;++Ai){var Ci=(43690&Ai)>>1|(21845&Ai)<<1;Ci=(61680&(Ci=(52428&Ci)>>2|(13107&Ci)<<2))>>4|(3855&Ci)<<4,Ei[Ai]=((65280&Ci)>>8|(255&Ci)<<8)>>1}var Ri=function(e,t,r){for(var i=e.length,n=0,o=new mi(t);n<i;++n)e[n]&&++o[e[n]-1];var s,a=new mi(t);for(n=1;n<t;++n)a[n]=a[n-1]+o[n-1]<<1;s=new mi(1<<t);var c=15-t;for(n=0;n<i;++n)if(e[n])for(var l=n<<4|e[n],u=t-e[n],d=a[e[n]-1]++<<u,p=d|(1<<u)-1;d<=p;++d)s[Ei[d]>>c]=l;return s},xi=new gi(288);for(Ai=0;Ai<144;++Ai)xi[Ai]=8;for(Ai=144;Ai<256;++Ai)xi[Ai]=9;for(Ai=256;Ai<280;++Ai)xi[Ai]=7;for(Ai=280;Ai<288;++Ai)xi[Ai]=8;var Ni=new gi(32);for(Ai=0;Ai<32;++Ai)Ni[Ai]=5;var zi=Ri(xi,9),_i=Ri(Ni,5),Pi=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},Oi=function(e,t,r){var i=t/8|0;return(e[i]|e[i+1]<<8)>>(7&t)&r},Di=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},Fi=function(e){return(e+7)/8|0},Mi=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Ui=function(e,t,r){var i=new Error(t||Mi[e]);if(i.code=e,Error.captureStackTrace&&Error.captureStackTrace(i,Ui),!r)throw i;return i},Bi=function(e,t,r,i){var n=e.length;if(!n||t.f&&!t.l)return r||new gi(0);var o=!r,s=o||2!=t.i,a=t.i;o&&(r=new gi(3*n));var c=function(e){var t=r.length;if(e>t){var i=new gi(Math.max(2*t,e));i.set(r),r=i}},l=t.f||0,u=t.p||0,d=t.b||0,p=t.l,h=t.d,g=t.m,m=t.n,f=8*n;do{if(!p){l=Oi(e,u,1);var y=Oi(e,u+1,3);if(u+=3,!y){var b=e[(x=Fi(u)+4)-4]|e[x-3]<<8,w=x+b;if(w>n){a&&Ui(0);break}s&&c(d+b),r.set(e.subarray(x,w),d),t.b=d+=b,t.p=u=8*w,t.f=l;continue}if(1==y)p=zi,h=_i,g=9,m=5;else if(2==y){var I=Oi(e,u,31)+257,T=Oi(e,u+10,15)+4,S=I+Oi(e,u+5,31)+1;u+=14;for(var k=new gi(S),v=new gi(19),E=0;E<T;++E)v[wi[E]]=Oi(e,u+3*E,7);u+=3*T;var A=Pi(v),C=(1<<A)-1,R=Ri(v,A);for(E=0;E<S;){var x,N=R[Oi(e,u,C)];if(u+=15&N,(x=N>>4)<16)k[E++]=x;else{var z=0,_=0;for(16==x?(_=3+Oi(e,u,3),u+=2,z=k[E-1]):17==x?(_=3+Oi(e,u,7),u+=3):18==x&&(_=11+Oi(e,u,127),u+=7);_--;)k[E++]=z}}var P=k.subarray(0,I),O=k.subarray(I);g=Pi(P),m=Pi(O),p=Ri(P,g),h=Ri(O,m)}else Ui(1);if(u>f){a&&Ui(0);break}}s&&c(d+131072);for(var D=(1<<g)-1,F=(1<<m)-1,M=u;;M=u){var U=(z=p[Di(e,u)&D])>>4;if((u+=15&z)>f){a&&Ui(0);break}if(z||Ui(2),U<256)r[d++]=U;else{if(256==U){M=u,p=null;break}var B=U-254;if(U>264){var L=yi[E=U-257];B=Oi(e,u,(1<<L)-1)+Si[E],u+=L}var K=h[Di(e,u)&F],$=K>>4;K||Ui(3),u+=15&K;O=vi[$];if($>3){L=bi[$];O+=Di(e,u)&(1<<L)-1,u+=L}if(u>f){a&&Ui(0);break}s&&c(d+131072);var H=d+B;if(d<O){var q=0-O,j=Math.min(O,H);for(q+d<0&&Ui(3);d<j;++d)r[d]=i[q+d]}for(;d<H;++d)r[d]=r[d-O]}}t.l=p,t.p=M,t.b=d,t.f=l,p&&(l=1,t.m=g,t.d=h,t.n=m)}while(!l);return d!=r.length&&o?function(e,t,r){return(null==r||r>e.length)&&(r=e.length),new gi(e.subarray(t,r))}(r,0,d):r.subarray(0,d)},Li=new gi(0);function Ki(e,t){var r,i,n=function(e){31==e[0]&&139==e[1]&&8==e[2]||Ui(6,"invalid gzip data");var t=e[3],r=10;4&t&&(r+=2+(e[10]|e[11]<<8));for(var i=(t>>3&1)+(t>>4&1);i>0;i-=!e[r++]);return r+(2&t)}(e);return n+8>e.length&&Ui(6,"invalid gzip data"),Bi(e.subarray(n,-8),{i:2},new gi((i=(r=e).length,(r[i-4]|r[i-3]<<8|r[i-2]<<16|r[i-1]<<24)>>>0)),t)}function $i(e,t){return Bi(e.subarray(((8!=(15&(r=e)[0])||r[0]>>4>7||(r[0]<<8|r[1])%31)&&Ui(6,"invalid zlib data"),1==(r[1]>>5&1)&&Ui(6,"invalid zlib data: "+(32&r[1]?"need":"unexpected")+" dictionary"),2+(r[1]>>3&4)),-4),{i:2},t,t);var r}function Hi(e,t){return 31==e[0]&&139==e[1]&&8==e[2]?Ki(e,t):8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31?function(e,t){return Bi(e,{i:2},t,t)}(e,t):$i(e,t)}var qi="undefined"!=typeof TextDecoder&&new TextDecoder;try{qi.decode(Li,{stream:!0})}catch(Pw){}var ji,Wi,Vi,Gi,Ji,Yi={exports:{}};function Xi(){if(Wi)return ji;Wi=1;var e=1e3,t=60*e,r=60*t,i=24*r,n=7*i,o=365.25*i;function s(e,t,r,i){var n=t>=1.5*r;return Math.round(e/r)+" "+i+(n?"s":"")}return ji=function(a,c){c=c||{};var l=typeof a;if("string"===l&&a.length>0)return function(s){if((s=String(s)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(s);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*o;case"weeks":case"week":case"w":return c*n;case"days":case"day":case"d":return c*i;case"hours":case"hour":case"hrs":case"hr":case"h":return c*r;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(a);if("number"===l&&isFinite(a))return c.long?function(n){var o=Math.abs(n);if(o>=i)return s(n,o,i,"day");if(o>=r)return s(n,o,r,"hour");if(o>=t)return s(n,o,t,"minute");if(o>=e)return s(n,o,e,"second");return n+" ms"}(a):function(n){var o=Math.abs(n);if(o>=i)return Math.round(n/i)+"d";if(o>=r)return Math.round(n/r)+"h";if(o>=t)return Math.round(n/t)+"m";if(o>=e)return Math.round(n/e)+"s";return n+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))}}var Zi=(Ji||(Ji=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let i=0,n=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(i++,"%c"===e&&(n=i))}),t.splice(n,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(r){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(r){}return!e&&void 0!==be&&"env"in be&&(e=be.env.DEBUG),e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.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"],t.log=console.debug||console.log||(()=>{}),e.exports=(Gi||(Gi=1,Vi=function(e){function t(e){let i,n,o,s=null;function a(...e){if(!a.enabled)return;const r=a,n=Number(new Date),o=n-(i||n);r.diff=o,r.prev=i,r.curr=n,i=n,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let s=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(i,n)=>{if("%%"===i)return"%";s++;const o=t.formatters[n];if("function"==typeof o){const t=e[s];i=o.call(r,t),e.splice(s,1),s--}return i}),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==s?s:(n!==t.namespaces&&(n=t.namespaces,o=t.enabled(e)),o),set:e=>{s=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const i=t(this.namespace+(void 0===r?":":r)+e);return i.log=this.log,i}function i(e,t){let r=0,i=0,n=-1,o=0;for(;r<e.length;)if(i<t.length&&(t[i]===e[r]||"*"===t[i]))"*"===t[i]?(n=i,o=r,i++):(r++,i++);else{if(-1===n)return!1;i=n+1,o++,r=o}for(;i<t.length&&"*"===t[i];)i++;return i===t.length}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const i of r)"-"===i[0]?t.skips.push(i.slice(1)):t.names.push(i)},t.enabled=function(e){for(const r of t.skips)if(i(e,r))return!1;for(const r of t.names)if(i(e,r))return!0;return!1},t.humanize=Xi(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(r=>{t[r]=e[r]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t}),Vi)(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}(Yi,Yi.exports)),Yi.exports);const Qi=Gr(Zi),en=67324752,tn=134695760,rn=33639248,nn=101010256,on={get:e=>(Xr.get(e,6),{signature:Qr.get(e,0),compressedSize:Qr.get(e,8),uncompressedSize:Qr.get(e,12)}),len:16},sn={get(e){const t=Xr.get(e,6);return{signature:Qr.get(e,0),minVersion:Xr.get(e,4),dataDescriptor:!!(8&t),compressedMethod:Xr.get(e,8),compressedSize:Qr.get(e,18),uncompressedSize:Qr.get(e,22),filenameLength:Xr.get(e,26),extraFieldLength:Xr.get(e,28),filename:null}},len:30},an={get:e=>({signature:Qr.get(e,0),nrOfThisDisk:Xr.get(e,4),nrOfThisDiskWithTheStart:Xr.get(e,6),nrOfEntriesOnThisDisk:Xr.get(e,8),nrOfEntriesOfSize:Xr.get(e,10),sizeOfCd:Qr.get(e,12),offsetOfStartOfCd:Qr.get(e,16),zipFileCommentLength:Xr.get(e,20)}),len:22},cn={get(e){const t=Xr.get(e,8);return{signature:Qr.get(e,0),minVersion:Xr.get(e,6),dataDescriptor:!!(8&t),compressedMethod:Xr.get(e,10),compressedSize:Qr.get(e,20),uncompressedSize:Qr.get(e,24),filenameLength:Xr.get(e,28),extraFieldLength:Xr.get(e,30),fileCommentLength:Xr.get(e,32),relativeOffsetOfLocalHeader:Qr.get(e,42),filename:null}},len:46};function ln(e){const t=new Uint8Array(Qr.len);return Qr.put(t,0,e),t}const un=Qi("tokenizer:inflate"),dn=262144,pn=ln(tn),hn=ln(nn);class gn{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(dn)}async isZip(){return await this.peekSignature()===en}peekSignature(){return this.tokenizer.peekToken(Qr)}async findEndOfCentralDirectoryLocator(){const e=this.tokenizer,t=Math.min(16384,e.fileInfo.size),r=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(r,{position:e.fileInfo.size-t});for(let i=r.length-4;i>=0;i--)if(r[i]===hn[0]&&r[i+1]===hn[1]&&r[i+2]===hn[2]&&r[i+3]===hn[3])return e.fileInfo.size-t+i;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess())return void un("Cannot reading central-directory without random-read support");un("Reading central-directory...");const e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){un("Central-directory 32-bit signature found");const r=await this.tokenizer.readToken(an,t),i=[];this.tokenizer.setPosition(r.offsetOfStartOfCd);for(let e=0;e<r.nrOfEntriesOfSize;++e){const t=await this.tokenizer.readToken(cn);if(t.signature!==rn)throw new Error("Expected Central-File-Header signature");t.filename=await this.tokenizer.readToken(new ii(t.filenameLength,"utf-8")),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),i.push(t),un(`Add central-directory file-entry: n=${e+1}/${i.length}: filename=${i[e].filename}`)}return this.tokenizer.setPosition(e),i}this.tokenizer.setPosition(e)}async unzip(e){const t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let r=!1;do{const t=await this.readLocalFileHeader();if(!t)break;const i=e(t);let n;if(r=!!i.stop,await this.tokenizer.ignore(t.extraFieldLength),t.dataDescriptor&&0===t.compressedSize){const e=[];let r=dn;un("Compressed-file-size unknown, scanning for next data-descriptor-signature....");let n=-1;for(;n<0&&r===dn;){r=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),n=mn(this.syncBuffer.subarray(0,r),pn);const t=n>=0?n:r;if(i.handler){const r=new Uint8Array(t);await this.tokenizer.readBuffer(r),e.push(r)}else await this.tokenizer.ignore(t)}un(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),i.handler&&await this.inflate(t,fn(e),i.handler)}else i.handler?(un(`Reading compressed-file-data: ${t.compressedSize} bytes`),n=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(n),await this.inflate(t,n,i.handler)):(un(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(un(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor){if(134695760!==(await this.tokenizer.readToken(on)).signature)throw new Error("Expected data-descriptor-signature at position "+(this.tokenizer.position-on.len))}}while(!r)}async iterateOverCentralDirectory(e,t){for(const r of e){const e=t(r);if(e.handler){this.tokenizer.setPosition(r.relativeOffsetOfLocalHeader);const t=await this.readLocalFileHeader();if(t){await this.tokenizer.ignore(t.extraFieldLength);const i=new Uint8Array(r.compressedSize);await this.tokenizer.readBuffer(i),await this.inflate(t,i,e.handler)}}if(e.stop)break}}inflate(e,t,r){if(0===e.compressedMethod)return r(t);un(`Decompress filename=${e.filename}, compressed-size=${t.length}`);return r(Hi(t))}async readLocalFileHeader(){const e=await this.tokenizer.peekToken(Qr);if(e===en){const e=await this.tokenizer.readToken(sn);return e.filename=await this.tokenizer.readToken(new ii(e.filenameLength,"utf-8")),e}if(e===rn)return!1;if(3759263696===e)throw new Error("Encrypted ZIP");throw new Error("Unexpected signature")}}function mn(e,t){const r=e.length,i=t.length;if(i>r)return-1;for(let n=0;n<=r-i;n++){let r=!0;for(let o=0;o<i;o++)if(e[n+o]!==t[o]){r=!1;break}if(r)return n}return-1}function fn(e){const t=e.reduce((e,t)=>e+t.length,0),r=new Uint8Array(t);let i=0;for(const n of e)r.set(n,i),i+=n.length;return r}function yn(e){const{byteLength:t}=e;return 6===t?e.getUint16(0)*2**32+e.getUint32(2):5===t?e.getUint8(0)*2**32+e.getUint32(1):4===t?e.getUint32(0):3===t?65536*e.getUint8(0)+e.getUint16(1):2===t?e.getUint16(0):1===t?e.getUint8(0):void 0}new globalThis.TextDecoder("utf8"),new globalThis.TextEncoder,Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));const bn={get:(e,t)=>127&e[t+3]|e[t+2]<<7|e[t+1]<<14|e[t]<<21,len:4},wn=4100;function In(e){switch(e=e.toLowerCase()){case"application/epub+zip":return{ext:"epub",mime:e};case"application/vnd.oasis.opendocument.text":return{ext:"odt",mime:e};case"application/vnd.oasis.opendocument.text-template":return{ext:"ott",mime:e};case"application/vnd.oasis.opendocument.spreadsheet":return{ext:"ods",mime:e};case"application/vnd.oasis.opendocument.spreadsheet-template":return{ext:"ots",mime:e};case"application/vnd.oasis.opendocument.presentation":return{ext:"odp",mime:e};case"application/vnd.oasis.opendocument.presentation-template":return{ext:"otp",mime:e};case"application/vnd.oasis.opendocument.graphics":return{ext:"odg",mime:e};case"application/vnd.oasis.opendocument.graphics-template":return{ext:"otg",mime:e};case"application/vnd.openxmlformats-officedocument.presentationml.slideshow":return{ext:"ppsx",mime:e};case"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":return{ext:"xlsx",mime:e};case"application/vnd.ms-excel.sheet.macroenabled":return{ext:"xlsm",mime:"application/vnd.ms-excel.sheet.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.spreadsheetml.template":return{ext:"xltx",mime:e};case"application/vnd.ms-excel.template.macroenabled":return{ext:"xltm",mime:"application/vnd.ms-excel.template.macroenabled.12"};case"application/vnd.ms-powerpoint.slideshow.macroenabled":return{ext:"ppsm",mime:"application/vnd.ms-powerpoint.slideshow.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.document":return{ext:"docx",mime:e};case"application/vnd.ms-word.document.macroenabled":return{ext:"docm",mime:"application/vnd.ms-word.document.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.template":return{ext:"dotx",mime:e};case"application/vnd.ms-word.template.macroenabledtemplate":return{ext:"dotm",mime:"application/vnd.ms-word.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.template":return{ext:"potx",mime:e};case"application/vnd.ms-powerpoint.template.macroenabled":return{ext:"potm",mime:"application/vnd.ms-powerpoint.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.presentation":return{ext:"pptx",mime:e};case"application/vnd.ms-powerpoint.presentation.macroenabled":return{ext:"pptm",mime:"application/vnd.ms-powerpoint.presentation.macroenabled.12"};case"application/vnd.ms-visio.drawing":return{ext:"vsdx",mime:"application/vnd.visio"};case"application/vnd.ms-package.3dmanufacturing-3dmodel+xml":return{ext:"3mf",mime:"model/3mf"}}}function Tn(e,t,r){r={offset:0,...r};for(const[i,n]of t.entries())if(r.mask){if(n!==(r.mask[i]&e[i+r.offset]))return!1}else if(n!==e[i+r.offset])return!1;return!0}class Sn{constructor(e){K(this,"detectConfident",async e=>{if(this.buffer=new Uint8Array(wn),void 0===e.fileInfo.size&&(e.fileInfo.size=Number.MAX_SAFE_INTEGER),this.tokenizer=e,await e.peekBuffer(this.buffer,{length:12,mayBeLess:!0}),this.check([66,77]))return{ext:"bmp",mime:"image/bmp"};if(this.check([11,119]))return{ext:"ac3",mime:"audio/vnd.dolby.dd-raw"};if(this.check([120,1]))return{ext:"dmg",mime:"application/x-apple-diskimage"};if(this.check([77,90]))return{ext:"exe",mime:"application/x-msdownload"};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString("PS-Adobe-",{offset:2})&&this.checkString(" EPSF-",{offset:14})?{ext:"eps",mime:"application/eps"}:{ext:"ps",mime:"application/postscript"};if(this.check([31,160])||this.check([31,157]))return{ext:"Z",mime:"application/x-compress"};if(this.check([199,113]))return{ext:"cpio",mime:"application/x-cpio"};if(this.check([96,234]))return{ext:"arj",mime:"application/x-arj"};if(this.check([239,187,191]))return this.tokenizer.ignore(3),this.detectConfident(e);if(this.check([71,73,70]))return{ext:"gif",mime:"image/gif"};if(this.check([73,73,188]))return{ext:"jxr",mime:"image/vnd.ms-photo"};if(this.check([31,139,8]))return{ext:"gz",mime:"application/gzip"};if(this.check([66,90,104]))return{ext:"bz2",mime:"application/x-bzip2"};if(this.checkString("ID3")){await e.ignore(6);const t=await e.readToken(bn);return e.position+t>e.fileInfo.size?{ext:"mp3",mime:"audio/mpeg"}:(await e.ignore(t),this.fromTokenizer(e))}if(this.checkString("MP+"))return{ext:"mpc",mime:"audio/x-musepack"};if((67===this.buffer[0]||70===this.buffer[0])&&this.check([87,83],{offset:1}))return{ext:"swf",mime:"application/x-shockwave-flash"};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:"jls",mime:"image/jls"}:{ext:"jpg",mime:"image/jpeg"};if(this.check([79,98,106,1]))return{ext:"avro",mime:"application/avro"};if(this.checkString("FLIF"))return{ext:"flif",mime:"image/flif"};if(this.checkString("8BPS"))return{ext:"psd",mime:"image/vnd.adobe.photoshop"};if(this.checkString("MPCK"))return{ext:"mpc",mime:"audio/x-musepack"};if(this.checkString("FORM"))return{ext:"aif",mime:"audio/aiff"};if(this.checkString("icns",{offset:0}))return{ext:"icns",mime:"image/icns"};if(this.check([80,75,3,4])){let r;return await new gn(e).unzip(e=>{switch(e.filename){case"META-INF/mozilla.rsa":return r={ext:"xpi",mime:"application/x-xpinstall"},{stop:!0};case"META-INF/MANIFEST.MF":return r={ext:"jar",mime:"application/java-archive"},{stop:!0};case"mimetype":return{async handler(e){const t=new TextDecoder("utf-8").decode(e).trim();r=In(t)},stop:!0};case"[Content_Types].xml":return{async handler(e){let t=new TextDecoder("utf-8").decode(e);const i=t.indexOf('.main+xml"');if(-1===i){const e="application/vnd.ms-package.3dmanufacturing-3dmodel+xml";t.includes(`ContentType="${e}"`)&&(r=In(e))}else{t=t.slice(0,Math.max(0,i));const e=t.lastIndexOf('"'),n=t.slice(Math.max(0,e+1));r=In(n)}},stop:!0};default:return/classes\d*\.dex/.test(e.filename)?(r={ext:"apk",mime:"application/vnd.android.package-archive"},{stop:!0}):{}}}),r??{ext:"zip",mime:"application/zip"}}if(this.checkString("OggS")){await e.ignore(28);const i=new Uint8Array(8);return await e.readBuffer(i),Tn(i,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/ogg; codecs=opus"}:Tn(i,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:Tn(i,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:Tn(i,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:Tn(i,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:Tn(i,[1,118,111,114,98,105,115])?{ext:"ogg",mime:"audio/ogg"}:{ext:"ogx",mime:"application/ogg"}}if(this.check([80,75])&&(3===this.buffer[2]||5===this.buffer[2]||7===this.buffer[2])&&(4===this.buffer[3]||6===this.buffer[3]||8===this.buffer[3]))return{ext:"zip",mime:"application/zip"};if(this.checkString("MThd"))return{ext:"mid",mime:"audio/midi"};if(this.checkString("wOFF")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff",mime:"font/woff"};if(this.checkString("wOF2")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff2",mime:"font/woff2"};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:"pcap",mime:"application/vnd.tcpdump.pcap"};if(this.checkString("DSD "))return{ext:"dsf",mime:"audio/x-dsf"};if(this.checkString("LZIP"))return{ext:"lz",mime:"application/x-lzip"};if(this.checkString("fLaC"))return{ext:"flac",mime:"audio/flac"};if(this.check([66,80,71,251]))return{ext:"bpg",mime:"image/bpg"};if(this.checkString("wvpk"))return{ext:"wv",mime:"audio/wavpack"};if(this.checkString("%PDF"))return{ext:"pdf",mime:"application/pdf"};if(this.check([0,97,115,109]))return{ext:"wasm",mime:"application/wasm"};if(this.check([73,73])){const n=await this.readTiffHeader(!1);if(n)return n}if(this.check([77,77])){const o=await this.readTiffHeader(!0);if(o)return o}if(this.checkString("MAC "))return{ext:"ape",mime:"audio/ape"};if(this.check([26,69,223,163])){async function s(){const t=await e.peekNumber(Yr);let r=128,i=0;for(;0===(t&r)&&0!==r;)++i,r>>=1;const n=new Uint8Array(i+1);return await e.readBuffer(n),n}async function a(){const e=await s(),t=await s();t[0]^=128>>t.length-1;const r=Math.min(6,t.length),i=new DataView(e.buffer),n=new DataView(t.buffer,t.length-r,r);return{id:yn(i),len:yn(n)}}async function c(t){for(;t>0;){const r=await a();if(17026===r.id){return(await e.readToken(new ii(r.len))).replaceAll(/\00.*$/g,"")}await e.ignore(r.len),--t}}const l=await a();switch(await c(l.len)){case"webm":return{ext:"webm",mime:"video/webm"};case"matroska":return{ext:"mkv",mime:"video/matroska"};default:return}}if(this.checkString("SQLi"))return{ext:"sqlite",mime:"application/x-sqlite3"};if(this.check([78,69,83,26]))return{ext:"nes",mime:"application/x-nintendo-nes-rom"};if(this.checkString("Cr24"))return{ext:"crx",mime:"application/x-google-chrome-extension"};if(this.checkString("MSCF")||this.checkString("ISc("))return{ext:"cab",mime:"application/vnd.ms-cab-compressed"};if(this.check([237,171,238,219]))return{ext:"rpm",mime:"application/x-rpm"};if(this.check([197,208,211,198]))return{ext:"eps",mime:"application/eps"};if(this.check([40,181,47,253]))return{ext:"zst",mime:"application/zstd"};if(this.check([127,69,76,70]))return{ext:"elf",mime:"application/x-elf"};if(this.check([33,66,68,78]))return{ext:"pst",mime:"application/vnd.ms-outlook"};if(this.checkString("PAR1")||this.checkString("PARE"))return{ext:"parquet",mime:"application/vnd.apache.parquet"};if(this.checkString("ttcf"))return{ext:"ttc",mime:"font/collection"};if(this.check([207,250,237,254]))return{ext:"macho",mime:"application/x-mach-binary"};if(this.check([4,34,77,24]))return{ext:"lz4",mime:"application/x-lz4"};if(this.check([79,84,84,79,0]))return{ext:"otf",mime:"font/otf"};if(this.checkString("#!AMR"))return{ext:"amr",mime:"audio/amr"};if(this.checkString("{\\rtf"))return{ext:"rtf",mime:"application/rtf"};if(this.check([70,76,86,1]))return{ext:"flv",mime:"video/x-flv"};if(this.checkString("IMPM"))return{ext:"it",mime:"audio/x-it"};if(this.checkString("-lh0-",{offset:2})||this.checkString("-lh1-",{offset:2})||this.checkString("-lh2-",{offset:2})||this.checkString("-lh3-",{offset:2})||this.checkString("-lh4-",{offset:2})||this.checkString("-lh5-",{offset:2})||this.checkString("-lh6-",{offset:2})||this.checkString("-lh7-",{offset:2})||this.checkString("-lzs-",{offset:2})||this.checkString("-lz4-",{offset:2})||this.checkString("-lz5-",{offset:2})||this.checkString("-lhd-",{offset:2}))return{ext:"lzh",mime:"application/x-lzh-compressed"};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:"mpg",mime:"video/MP1S"};if(this.check([68],{offset:4,mask:[196]}))return{ext:"mpg",mime:"video/MP2P"}}if(this.checkString("ITSF"))return{ext:"chm",mime:"application/vnd.ms-htmlhelp"};if(this.check([202,254,186,190]))return{ext:"class",mime:"application/java-vm"};if(this.checkString(".RMF"))return{ext:"rm",mime:"application/vnd.rn-realmedia"};if(this.checkString("DRACO"))return{ext:"drc",mime:"application/vnd.google.draco"};if(this.check([253,55,122,88,90,0]))return{ext:"xz",mime:"application/x-xz"};if(this.checkString("<?xml "))return{ext:"xml",mime:"application/xml"};if(this.check([55,122,188,175,39,28]))return{ext:"7z",mime:"application/x-7z-compressed"};if(this.check([82,97,114,33,26,7])&&(0===this.buffer[6]||1===this.buffer[6]))return{ext:"rar",mime:"application/x-rar-compressed"};if(this.checkString("solid "))return{ext:"stl",mime:"model/stl"};if(this.checkString("AC")){const u=new ii(4,"latin1").get(this.buffer,2);if(u.match("^d*")&&u>=1e3&&u<=1050)return{ext:"dwg",mime:"image/vnd.dwg"}}if(this.checkString("070707"))return{ext:"cpio",mime:"application/x-cpio"};if(this.checkString("BLENDER"))return{ext:"blend",mime:"application/x-blender"};if(this.checkString("!<arch>")){await e.ignore(8);return"debian-binary"===await e.readToken(new ii(13,"ascii"))?{ext:"deb",mime:"application/x-deb"}:{ext:"ar",mime:"application/x-unix-archive"}}if(this.checkString("WEBVTT")&&["\n","\r","\t"," ","\0"].some(e=>this.checkString(e,{offset:6})))return{ext:"vtt",mime:"text/vtt"};if(this.check([137,80,78,71,13,10,26,10])){async function d(){return{length:await e.readToken(ti),type:await e.readToken(new ii(4,"latin1"))}}await e.ignore(8);do{const p=await d();if(p.length<0)return;switch(p.type){case"IDAT":return{ext:"png",mime:"image/png"};case"acTL":return{ext:"apng",mime:"image/apng"};default:await e.ignore(p.length+4)}}while(e.position+8<e.fileInfo.size);return{ext:"png",mime:"image/png"}}if(this.check([65,82,82,79,87,49,0,0]))return{ext:"arrow",mime:"application/vnd.apache.arrow.file"};if(this.check([103,108,84,70,2,0,0,0]))return{ext:"glb",mime:"model/gltf-binary"};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:"mov",mime:"video/quicktime"};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:"orf",mime:"image/x-olympus-orf"};if(this.checkString("gimp xcf "))return{ext:"xcf",mime:"image/x-xcf"};if(this.checkString("ftyp",{offset:4})&&96&this.buffer[8]){const h=new ii(4,"latin1").get(this.buffer,8).replace("\0"," ").trim();switch(h){case"avif":case"avis":return{ext:"avif",mime:"image/avif"};case"mif1":return{ext:"heic",mime:"image/heif"};case"msf1":return{ext:"heic",mime:"image/heif-sequence"};case"heic":case"heix":return{ext:"heic",mime:"image/heic"};case"hevc":case"hevx":return{ext:"heic",mime:"image/heic-sequence"};case"qt":return{ext:"mov",mime:"video/quicktime"};case"M4V":case"M4VH":case"M4VP":return{ext:"m4v",mime:"video/x-m4v"};case"M4P":return{ext:"m4p",mime:"video/mp4"};case"M4B":return{ext:"m4b",mime:"audio/mp4"};case"M4A":return{ext:"m4a",mime:"audio/x-m4a"};case"F4V":return{ext:"f4v",mime:"video/mp4"};case"F4P":return{ext:"f4p",mime:"video/mp4"};case"F4A":return{ext:"f4a",mime:"audio/mp4"};case"F4B":return{ext:"f4b",mime:"audio/mp4"};case"crx":return{ext:"cr3",mime:"image/x-canon-cr3"};default:return h.startsWith("3g")?h.startsWith("3g2")?{ext:"3g2",mime:"video/3gpp2"}:{ext:"3gp",mime:"video/3gpp"}:{ext:"mp4",mime:"video/mp4"}}}if(this.check([82,73,70,70])){if(this.checkString("WEBP",{offset:8}))return{ext:"webp",mime:"image/webp"};if(this.check([65,86,73],{offset:8}))return{ext:"avi",mime:"video/vnd.avi"};if(this.check([87,65,86,69],{offset:8}))return{ext:"wav",mime:"audio/wav"};if(this.check([81,76,67,77],{offset:8}))return{ext:"qcp",mime:"audio/qcelp"}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:"rw2",mime:"image/x-panasonic-rw2"};if(this.check([48,38,178,117,142,102,207,17,166,217])){async function g(){const t=new Uint8Array(16);return await e.readBuffer(t),{id:t,size:Number(await e.readToken(ri))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){const m=await g();let f=m.size-24;if(Tn(m.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){const y=new Uint8Array(16);if(f-=await e.readBuffer(y),Tn(y,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"audio/x-ms-asf"};if(Tn(y,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"video/x-ms-asf"};break}await e.ignore(f)}return{ext:"asf",mime:"application/vnd.ms-asf"}}if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:"ktx",mime:"image/ktx"};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:"mie",mime:"application/x-mie"};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:"shp",mime:"application/x-esri-shape"};if(this.check([255,79,255,81]))return{ext:"j2c",mime:"image/j2c"};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10])){await e.ignore(20);switch(await e.readToken(new ii(4,"ascii"))){case"jp2 ":return{ext:"jp2",mime:"image/jp2"};case"jpx ":return{ext:"jpx",mime:"image/jpx"};case"jpm ":return{ext:"jpm",mime:"image/jpm"};case"mjp2":return{ext:"mj2",mime:"image/mj2"};default:return}}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:"jxl",mime:"image/jxl"};if(this.check([254,255]))return this.check([0,60,0,63,0,120,0,109,0,108],{offset:2})?{ext:"xml",mime:"application/xml"}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:"cfb",mime:"application/x-cfb"};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:"icc",mime:"application/vnd.iccprofile"};if(this.checkString("**ACE",{offset:7})&&this.checkString("**",{offset:12}))return{ext:"ace",mime:"application/x-ace-compressed"};if(this.checkString("BEGIN:")){if(this.checkString("VCARD",{offset:6}))return{ext:"vcf",mime:"text/vcard"};if(this.checkString("VCALENDAR",{offset:6}))return{ext:"ics",mime:"text/calendar"}}if(this.checkString("FUJIFILMCCD-RAW"))return{ext:"raf",mime:"image/x-fujifilm-raf"};if(this.checkString("Extended Module:"))return{ext:"xm",mime:"audio/x-xm"};if(this.checkString("Creative Voice File"))return{ext:"voc",mime:"audio/x-voc"};if(this.check([4,0,0,0])&&this.buffer.length>=16){const b=new DataView(this.buffer.buffer).getUint32(12,!0);if(b>12&&this.buffer.length>=b+16)try{const w=(new TextDecoder).decode(this.buffer.subarray(16,b+16));if(JSON.parse(w).files)return{ext:"asar",mime:"application/x-asar"}}catch{}}return this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2])?{ext:"mxf",mime:"application/mxf"}:this.checkString("SCRM",{offset:44})?{ext:"s3m",mime:"audio/x-s3m"}:this.check([71])&&this.check([71],{offset:188})||this.check([71],{offset:4})&&this.check([71],{offset:196})?{ext:"mts",mime:"video/mp2t"}:this.check([66,79,79,75,77,79,66,73],{offset:60})?{ext:"mobi",mime:"application/x-mobipocket-ebook"}:this.check([68,73,67,77],{offset:128})?{ext:"dcm",mime:"application/dicom"}:this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70])?{ext:"lnk",mime:"application/x.ms.shortcut"}:this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0])?{ext:"alias",mime:"application/x.apple.alias"}:this.checkString("Kaydara FBX Binary \0")?{ext:"fbx",mime:"application/x.autodesk.fbx"}:this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8}))?{ext:"eot",mime:"application/vnd.ms-fontobject"}:this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29])?{ext:"indd",mime:"application/x-indesign"}:(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),this.checkString("ustar",{offset:257})&&(this.checkString("\0",{offset:262})||this.checkString(" ",{offset:262}))||this.check([0,0,0,0,0,0],{offset:257})&&function(e,t=0){const r=Number.parseInt(new ii(6).get(e,148).replace(/\0.*$/,"").trim(),8);if(Number.isNaN(r))return!1;let i=256;for(let n=t;n<t+148;n++)i+=e[n];for(let n=t+156;n<t+512;n++)i+=e[n];return r===i}(this.buffer)?{ext:"tar",mime:"application/x-tar"}:this.check([255,254])?this.check([60,0,63,0,120,0,109,0,108,0],{offset:2})?{ext:"xml",mime:"application/xml"}:this.check([255,14,83,0,107,0,101,0,116,0,99,0,104,0,85,0,112,0,32,0,77,0,111,0,100,0,101,0,108,0],{offset:2})?{ext:"skp",mime:"application/vnd.sketchup.skp"}:void 0:this.checkString("-----BEGIN PGP MESSAGE-----")?{ext:"pgp",mime:"application/pgp-encrypted"}:void 0)}),K(this,"detectImprecise",async e=>{if(this.buffer=new Uint8Array(wn),await e.peekBuffer(this.buffer,{length:Math.min(8,e.fileInfo.size),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:"mpg",mime:"video/mpeg"};if(this.check([0,1,0,0,0]))return{ext:"ttf",mime:"font/ttf"};if(this.check([0,0,1,0]))return{ext:"ico",mime:"image/x-icon"};if(this.check([0,0,2,0]))return{ext:"cur",mime:"image/x-icon"};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,e.fileInfo.size),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let t=0;t<=this.options.mpegOffsetTolerance;++t){const e=this.scanMpeg(t);if(e)return e}}),this.options={mpegOffsetTolerance:0,...e},this.detectors=[...(null==e?void 0:e.customDetectors)??[],{id:"core",detect:this.detectConfident},{id:"core.imprecise",detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:null==e?void 0:e.signal}}async fromTokenizer(e){const t=e.position;for(const r of this.detectors){const i=await r.detect(e);if(i)return i;if(t!==e.position)return}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);const t=e instanceof Uint8Array?e:new Uint8Array(e);var r,i;if((null==t?void 0:t.length)>1)return this.fromTokenizer((r=t,i=this.tokenizerOptions,new pi(r,i)))}async fromBlob(e){return this.fromStream(e.stream())}async fromStream(e){const t=await hi(e,this.tokenizerOptions);try{return await this.fromTokenizer(t)}finally{await t.close()}}async toDetectionStream(e,t){const{sampleSize:r=wn}=t;let i,n;const o=e.getReader({mode:"byob"});try{const{value:e,done:t}=await o.read(new Uint8Array(r));if(n=e,!t&&e)try{i=await this.fromBuffer(e.subarray(0,r))}catch(c){if(!(c instanceof ni))throw c;i=void 0}n=e}finally{o.releaseLock()}const s=new TransformStream({async start(e){e.enqueue(n)},transform(e,t){t.enqueue(e)}}),a=e.pipeThrough(s);return a.fileType=i,a}check(e,t){return Tn(this.buffer,e,t)}checkString(e,t){return this.check((r=e,[...r].map(e=>e.charCodeAt(0))),t);var r}async readTiffTag(e){const t=await this.tokenizer.readToken(e?Zr:Xr);switch(this.tokenizer.ignore(10),t){case 50341:return{ext:"arw",mime:"image/x-sony-arw"};case 50706:return{ext:"dng",mime:"image/x-adobe-dng"}}}async readTiffIFD(e){const t=await this.tokenizer.readToken(e?Zr:Xr);for(let r=0;r<t;++r){const t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){const t=(e?Zr:Xr).get(this.buffer,2),r=(e?ei:Qr).get(this.buffer,4);if(42===t){if(r>=6){if(this.checkString("CR",{offset:8}))return{ext:"cr2",mime:"image/x-canon-cr2"};if(r>=8){const t=(e?Zr:Xr).get(this.buffer,8),r=(e?Zr:Xr).get(this.buffer,10);if(28===t&&254===r||31===t&&11===r)return{ext:"nef",mime:"image/x-nikon-nef"}}}await this.tokenizer.ignore(r);return await this.readTiffIFD(e)??{ext:"tif",mime:"image/tiff"}}if(43===t)return{ext:"tif",mime:"image/tiff"}}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]}),{ext:"aac",mime:"audio/aac"};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:"mp3",mime:"audio/mpeg"};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:"mp2",mime:"audio/mpeg"};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:"mp1",mime:"audio/mpeg"}}}}new Set(["jpg","png","apng","gif","webp","flif","xcf","cr2","cr3","orf","arw","dng","nef","rw2","raf","tif","bmp","icns","jxr","psd","indd","zip","tar","rar","gz","bz2","7z","dmg","mp4","mid","mkv","webm","mov","avi","mpg","mp2","mp3","m4a","oga","ogg","ogv","opus","flac","wav","spx","amr","pdf","epub","elf","macho","exe","swf","rtf","wasm","woff","woff2","eot","ttf","otf","ttc","ico","flv","ps","xz","sqlite","nes","crx","xpi","cab","deb","ar","rpm","Z","lz","cfb","mxf","mts","blend","bpg","docx","pptx","xlsx","3gp","3g2","j2c","jp2","jpm","jpx","mj2","aif","qcp","odt","ods","odp","xml","mobi","heic","cur","ktx","ape","wv","dcm","ics","glb","pcap","dsf","lnk","alias","voc","ac3","m4v","m4p","m4b","f4v","f4p","f4b","f4a","mie","asf","ogm","ogx","mpc","arrow","shp","aac","mp1","it","s3m","xm","skp","avif","eps","lzh","pgp","asar","stl","chm","3mf","zst","jxl","vcf","jls","pst","dwg","parquet","class","arj","cpio","ace","avro","icc","fbx","vsdx","vtt","apk","drc","lz4","potx","xltx","dotx","xltm","ott","ots","otp","odg","otg","xlsm","docm","dotm","potm","pptm","jar","rm","ppsm","ppsx"]),new Set(["image/jpeg","image/png","image/gif","image/webp","image/flif","image/x-xcf","image/x-canon-cr2","image/x-canon-cr3","image/tiff","image/bmp","image/vnd.ms-photo","image/vnd.adobe.photoshop","application/x-indesign","application/epub+zip","application/x-xpinstall","application/vnd.ms-powerpoint.slideshow.macroenabled.12","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet","application/vnd.oasis.opendocument.presentation","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.presentationml.slideshow","application/zip","application/x-tar","application/x-rar-compressed","application/gzip","application/x-bzip2","application/x-7z-compressed","application/x-apple-diskimage","application/vnd.apache.arrow.file","video/mp4","audio/midi","video/matroska","video/webm","video/quicktime","video/vnd.avi","audio/wav","audio/qcelp","audio/x-ms-asf","video/x-ms-asf","application/vnd.ms-asf","video/mpeg","video/3gpp","audio/mpeg","audio/mp4","video/ogg","audio/ogg","audio/ogg; codecs=opus","application/ogg","audio/flac","audio/ape","audio/wavpack","audio/amr","application/pdf","application/x-elf","application/x-mach-binary","application/x-msdownload","application/x-shockwave-flash","application/rtf","application/wasm","font/woff","font/woff2","application/vnd.ms-fontobject","font/ttf","font/otf","font/collection","image/x-icon","video/x-flv","application/postscript","application/eps","application/x-xz","application/x-sqlite3","application/x-nintendo-nes-rom","application/x-google-chrome-extension","application/vnd.ms-cab-compressed","application/x-deb","application/x-unix-archive","application/x-rpm","application/x-compress","application/x-lzip","application/x-cfb","application/x-mie","application/mxf","video/mp2t","application/x-blender","image/bpg","image/j2c","image/jp2","image/jpx","image/jpm","image/mj2","audio/aiff","application/xml","application/x-mobipocket-ebook","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/icns","image/ktx","application/dicom","audio/x-musepack","text/calendar","text/vcard","text/vtt","model/gltf-binary","application/vnd.tcpdump.pcap","audio/x-dsf","application/x.ms.shortcut","application/x.apple.alias","audio/x-voc","audio/vnd.dolby.dd-raw","audio/x-m4a","image/apng","image/x-olympus-orf","image/x-sony-arw","image/x-adobe-dng","image/x-nikon-nef","image/x-panasonic-rw2","image/x-fujifilm-raf","video/x-m4v","video/3gpp2","application/x-esri-shape","audio/aac","audio/x-it","audio/x-s3m","audio/x-xm","video/MP1S","video/MP2P","application/vnd.sketchup.skp","image/avif","application/x-lzh-compressed","application/pgp-encrypted","application/x-asar","model/stl","application/vnd.ms-htmlhelp","model/3mf","image/jxl","application/zstd","image/jls","application/vnd.ms-outlook","image/vnd.dwg","application/vnd.apache.parquet","application/java-vm","application/x-arj","application/x-cpio","application/x-ace-compressed","application/avro","application/vnd.iccprofile","application/x.autodesk.fbx","application/vnd.visio","application/vnd.android.package-archive","application/vnd.google.draco","application/x-lz4","application/vnd.openxmlformats-officedocument.presentationml.template","application/vnd.openxmlformats-officedocument.spreadsheetml.template","application/vnd.openxmlformats-officedocument.wordprocessingml.template","application/vnd.ms-excel.template.macroenabled.12","application/vnd.oasis.opendocument.text-template","application/vnd.oasis.opendocument.spreadsheet-template","application/vnd.oasis.opendocument.presentation-template","application/vnd.oasis.opendocument.graphics","application/vnd.oasis.opendocument.graphics-template","application/vnd.ms-excel.sheet.macroenabled.12","application/vnd.ms-word.document.macroenabled.12","application/vnd.ms-word.template.macroenabled.12","application/vnd.ms-powerpoint.template.macroenabled.12","application/vnd.ms-powerpoint.presentation.macroenabled.12","application/java-archive","application/vnd.rn-realmedia"]);const kn=Object.create(null);kn.open="0",kn.close="1",kn.ping="2",kn.pong="3",kn.message="4",kn.upgrade="5",kn.noop="6";const vn=Object.create(null);Object.keys(kn).forEach(e=>{vn[kn[e]]=e});const En={type:"error",data:"parser error"},An="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Cn="function"==typeof ArrayBuffer,Rn=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,xn=({type:e,data:t},r,i)=>An&&t instanceof Blob?r?i(t):Nn(t,i):Cn&&(t instanceof ArrayBuffer||Rn(t))?r?i(t):Nn(new Blob([t]),i):i(kn[e]+(t||"")),Nn=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+(e||""))},r.readAsDataURL(e)};function zn(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let _n;const Pn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",On="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let Dw=0;Dw<64;Dw++)On[Pn.charCodeAt(Dw)]=Dw;const Dn="function"==typeof ArrayBuffer,Fn=(e,t)=>{if("string"!=typeof e)return{type:"message",data:Un(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:Mn(e.substring(1),t)};return vn[r]?e.length>1?{type:vn[r],data:e.substring(1)}:{type:vn[r]}:En},Mn=(e,t)=>{if(Dn){const r=(e=>{let t,r,i,n,o,s=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(s--,"="===e[e.length-2]&&s--);const l=new ArrayBuffer(s),u=new Uint8Array(l);for(t=0;t<a;t+=4)r=On[e.charCodeAt(t)],i=On[e.charCodeAt(t+1)],n=On[e.charCodeAt(t+2)],o=On[e.charCodeAt(t+3)],u[c++]=r<<2|i>>4,u[c++]=(15&i)<<4|n>>2,u[c++]=(3&n)<<6|63&o;return l})(e);return Un(r,t)}return{base64:!0,data:e}},Un=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,Bn=String.fromCharCode(30);function Ln(){return new TransformStream({transform(e,t){!function(e,t){An&&e.data instanceof Blob?e.data.arrayBuffer().then(zn).then(t):Cn&&(e.data instanceof ArrayBuffer||Rn(e.data))?t(zn(e.data)):xn(e,!1,e=>{_n||(_n=new TextEncoder),t(_n.encode(e))})}(e,r=>{const i=r.length;let n;if(i<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,i);else if(i<65536){n=new Uint8Array(3);const e=new DataView(n.buffer);e.setUint8(0,126),e.setUint16(1,i)}else{n=new Uint8Array(9);const e=new DataView(n.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(i))}e.data&&"string"!=typeof e.data&&(n[0]|=128),t.enqueue(n),t.enqueue(r)})}})}let Kn;function $n(e){return e.reduce((e,t)=>e+t.length,0)}function Hn(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let i=0;for(let n=0;n<t;n++)r[n]=e[0][i++],i===e[0].length&&(e.shift(),i=0);return e.length&&i<e[0].length&&(e[0]=e[0].slice(i)),r}function qn(e){if(e)return function(e){for(var t in qn.prototype)e[t]=qn.prototype[t];return e}(e)}qn.prototype.on=qn.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},qn.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},qn.prototype.off=qn.prototype.removeListener=qn.prototype.removeAllListeners=qn.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,i=this._callbacks["$"+e];if(!i)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var n=0;n<i.length;n++)if((r=i[n])===t||r.fn===t){i.splice(n,1);break}return 0===i.length&&delete this._callbacks["$"+e],this},qn.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],i=1;i<arguments.length;i++)t[i-1]=arguments[i];if(r){i=0;for(var n=(r=r.slice(0)).length;i<n;++i)r[i].apply(this,t)}return this},qn.prototype.emitReserved=qn.prototype.emit,qn.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},qn.prototype.hasListeners=function(e){return!!this.listeners(e).length};const jn="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Wn="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Vn(e,...t){return t.reduce((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t),{})}const Gn=Wn.setTimeout,Jn=Wn.clearTimeout;function Yn(e,t){t.useNativeTimers?(e.setTimeoutFn=Gn.bind(Wn),e.clearTimeoutFn=Jn.bind(Wn)):(e.setTimeoutFn=Wn.setTimeout.bind(Wn),e.clearTimeoutFn=Wn.clearTimeout.bind(Wn))}function Xn(e){return"string"==typeof e?function(e){let t=0,r=0;for(let i=0,n=e.length;i<n;i++)t=e.charCodeAt(i),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(i++,r+=4);return r}(e):Math.ceil(1.33*(e.byteLength||e.size))}function Zn(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class Qn extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class eo extends qn{constructor(e){super(),this.writable=!1,Yn(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,r){return super.emitReserved("error",new Qn(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=Fn(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}(e);return t.length?"?"+t:""}}class to extends eo{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const r=e.split(Bn),i=[];for(let n=0;n<r.length;n++){const e=Fn(r[n],t);if(i.push(e),"error"===e.type)break}return i})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const r=e.length,i=new Array(r);let n=0;e.forEach((e,o)=>{xn(e,!1,e=>{i[o]=e,++n===r&&t(i.join(Bn))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=Zn()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let ro=!1;try{ro="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(Ow){}const io=ro;function no(){}class oo extends to{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let r=location.port;r||(r=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||r!==e.port}}doWrite(e,t){const r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}let so=class e extends qn{constructor(e,t,r){super(),this.createRequest=e,Yn(this,r),this._opts=r,this._method=r.method||"GET",this._uri=t,this._data=void 0!==r.data?r.data:null,this._create()}_create(){var t;const r=Vn(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this._opts.xd;const i=this._xhr=this.createRequest(r);try{i.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&i.setRequestHeader(e,this._opts.extraHeaders[e])}}catch(Pw){}if("POST"===this._method)try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(Pw){}try{i.setRequestHeader("Accept","*/*")}catch(Pw){}null===(t=this._opts.cookieJar)||void 0===t||t.addCookies(i),"withCredentials"in i&&(i.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(i.timeout=this._opts.requestTimeout),i.onreadystatechange=()=>{var e;3===i.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(i.getResponseHeader("set-cookie"))),4===i.readyState&&(200===i.status||1223===i.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof i.status?i.status:0)},0))},i.send(this._data)}catch(Pw){return void this.setTimeoutFn(()=>{this._onError(Pw)},0)}"undefined"!=typeof document&&(this._index=e.requestsCount++,e.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(t){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=no,t)try{this._xhr.abort()}catch(Pw){}"undefined"!=typeof document&&delete e.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};if(so.requestsCount=0,so.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",ao);else if("function"==typeof addEventListener){addEventListener("onpagehide"in Wn?"pagehide":"unload",ao,!1)}function ao(){for(let e in so.requests)so.requests.hasOwnProperty(e)&&so.requests[e].abort()}const co=function(){const e=lo({xdomain:!1});return e&&null!==e.responseType}();function lo(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||io))return new XMLHttpRequest}catch(Pw){}if(!t)try{return new(Wn[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(Pw){}}const uo="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class po extends eo{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,r=uo?{}:Vn(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,r)}catch(Ow){return this.emitReserved("error",Ow)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],i=t===e.length-1;xn(r,this.supportsBinary,e=>{try{this.doWrite(r,e)}catch(Pw){}i&&jn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=Zn()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const ho=Wn.WebSocket||Wn.MozWebSocket;const go={websocket:class extends po{createSocket(e,t,r){return uo?new ho(e,t,r):t?new ho(e,t):new ho(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends eo{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(Ow){return this.emitReserved("error",Ow)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=function(e,t){Kn||(Kn=new TextDecoder);const r=[];let i=0,n=-1,o=!1;return new TransformStream({transform(s,a){for(r.push(s);;){if(0===i){if($n(r)<1)break;const e=Hn(r,1);o=!(128&~e[0]),n=127&e[0],i=n<126?3:126===n?1:2}else if(1===i){if($n(r)<2)break;const e=Hn(r,2);n=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if($n(r)<8)break;const e=Hn(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),o=t.getUint32(0);if(o>Math.pow(2,21)-1){a.enqueue(En);break}n=o*Math.pow(2,32)+t.getUint32(4),i=3}else{if($n(r)<n)break;const e=Hn(r,n);a.enqueue(Fn(o?e:Kn.decode(e),t)),i=0}if(0===n||n>e){a.enqueue(En);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),i=Ln();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const n=()=>{r.read().then(({done:e,value:t})=>{e||(this.onPacket(t),n())}).catch(e=>{})};n();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],i=t===e.length-1;this._writer.write(r).then(()=>{i&&jn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends oo{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=co&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new so(lo,this.uri(),e)}}},mo=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,fo=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function yo(e){if(e.length>8e3)throw"URI too long";const t=e,r=e.indexOf("["),i=e.indexOf("]");-1!=r&&-1!=i&&(e=e.substring(0,r)+e.substring(r,i).replace(/:/g,";")+e.substring(i,e.length));let n=mo.exec(e||""),o={},s=14;for(;s--;)o[fo[s]]=n[s]||"";return-1!=r&&-1!=i&&(o.source=t,o.host=o.host.substring(1,o.host.length-1).replace(/;/g,":"),o.authority=o.authority.replace("[","").replace("]","").replace(/;/g,":"),o.ipv6uri=!0),o.pathNames=function(e,t){const r=/\/{2,9}/g,i=t.replace(r,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||i.splice(0,1);"/"==t.slice(-1)&&i.splice(i.length-1,1);return i}(0,o.path),o.queryKey=function(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,i){t&&(r[t]=i)}),r}(0,o.query),o}const bo="function"==typeof addEventListener&&"function"==typeof removeEventListener,wo=[];bo&&addEventListener("offline",()=>{wo.forEach(e=>e())},!1);class Io extends qn{constructor(e,t){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const r=yo(e);t.hostname=r.host,t.secure="https"===r.protocol||"wss"===r.protocol,t.port=r.port,r.query&&(t.query=r.query)}else t.host&&(t.hostname=yo(t.host).host);Yn(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{const t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},r=e.split("&");for(let i=0,n=r.length;i<n;i++){let e=r[i].split("=");t[decodeURIComponent(e[0])]=decodeURIComponent(e[1])}return t}(this.opts.query)),bo&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},wo.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](r)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&Io.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",Io.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const r=this.writeBuffer[t].data;if(r&&(e+=Xn(r)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,jn(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,r){return this._sendPacket("message",e,t,r),this}send(e,t,r){return this._sendPacket("message",e,t,r),this}_sendPacket(e,t,r,i){if("function"==typeof t&&(i=t,t=void 0),"function"==typeof r&&(i=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const n={type:e,data:t,options:r};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():e()}):this.upgrading?r():e()),this}_onError(e){if(Io.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),bo&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=wo.indexOf(this._offlineEventListener);-1!==e&&wo.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}Io.protocol=4;class To extends Io{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),r=!1;Io.priorWebsocketSuccess=!1;const i=()=>{r||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!r)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Io.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{r||"closed"!==this.readyState&&(l(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function n(){r||(r=!0,l(),t.close(),t=null)}const o=e=>{const r=new Error("probe error: "+e);r.transport=t.name,n(),this.emitReserved("upgradeError",r)};function s(){o("transport closed")}function a(){o("socket closed")}function c(e){t&&e.name!==t.name&&n()}const l=()=>{t.removeListener("open",i),t.removeListener("error",o),t.removeListener("close",s),this.off("close",a),this.off("upgrading",c)};t.once("open",i),t.once("error",o),t.once("close",s),this.once("close",a),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{r||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let r=0;r<e.length;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}}let So=class extends To{constructor(e,t={}){const r="object"==typeof e?e:t;(!r.transports||r.transports&&"string"==typeof r.transports[0])&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(e=>go[e]).filter(e=>!!e)),super(e,r)}};const ko="function"==typeof ArrayBuffer,vo=Object.prototype.toString,Eo="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===vo.call(Blob),Ao="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===vo.call(File);function Co(e){return ko&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Eo&&e instanceof Blob||Ao&&e instanceof File}function Ro(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(Ro(e[t]))return!0;return!1}if(Co(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Ro(e.toJSON(),!0);for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&Ro(e[r]))return!0;return!1}function xo(e){const t=[],r=e.data,i=e;return i.data=No(r,t),i.attachments=t.length,{packet:i,buffers:t}}function No(e,t){if(!e)return e;if(Co(e)){const r={_placeholder:!0,num:t.length};return t.push(e),r}if(Array.isArray(e)){const r=new Array(e.length);for(let i=0;i<e.length;i++)r[i]=No(e[i],t);return r}if("object"==typeof e&&!(e instanceof Date)){const r={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=No(e[i],t));return r}return e}function zo(e,t){return e.data=_o(e.data,t),delete e.attachments,e}function _o(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=_o(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=_o(e[r],t));return e}const Po=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Oo,Do;(Do=Oo||(Oo={}))[Do.CONNECT=0]="CONNECT",Do[Do.DISCONNECT=1]="DISCONNECT",Do[Do.EVENT=2]="EVENT",Do[Do.ACK=3]="ACK",Do[Do.CONNECT_ERROR=4]="CONNECT_ERROR",Do[Do.BINARY_EVENT=5]="BINARY_EVENT",Do[Do.BINARY_ACK=6]="BINARY_ACK";function Fo(e){return"[object Object]"===Object.prototype.toString.call(e)}class Mo extends qn{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const r=t.type===Oo.BINARY_EVENT;r||t.type===Oo.BINARY_ACK?(t.type=r?Oo.EVENT:Oo.ACK,this.reconstructor=new Uo(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Co(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const r={type:Number(e.charAt(0))};if(void 0===Oo[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Oo.BINARY_EVENT||r.type===Oo.BINARY_ACK){const i=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const n=e.substring(i,t);if(n!=Number(n)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(n)}if("/"===e.charAt(t+1)){const i=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}r.nsp=e.substring(i,t)}else r.nsp="/";const i=e.charAt(t+1);if(""!==i&&Number(i)==i){const i=t+1;for(;++t;){const r=e.charAt(t);if(null==r||Number(r)!=r){--t;break}if(t===e.length)break}r.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){const i=this.tryParse(e.substr(t));if(!Mo.isPayloadValid(r.type,i))throw new Error("invalid payload");r.data=i}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(Pw){return!1}}static isPayloadValid(e,t){switch(e){case Oo.CONNECT:return Fo(t);case Oo.DISCONNECT:return void 0===t;case Oo.CONNECT_ERROR:return"string"==typeof t||Fo(t);case Oo.EVENT:case Oo.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Po.indexOf(t[0]));case Oo.ACK:case Oo.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Uo{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=zo(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Bo=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Mo,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Oo.EVENT&&e.type!==Oo.ACK||!Ro(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Oo.EVENT?Oo.BINARY_EVENT:Oo.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Oo.BINARY_EVENT&&e.type!==Oo.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=xo(e),r=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(r),i}},get PacketType(){return Oo},protocol:5},Symbol.toStringTag,{value:"Module"}));function Lo(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const Ko=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class $o extends qn{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[Lo(e,"open",this.onopen.bind(this)),Lo(e,"packet",this.onpacket.bind(this)),Lo(e,"error",this.onerror.bind(this)),Lo(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var r,i,n;if(Ko.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const o={type:Oo.EVENT,data:t,options:{}};if(o.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,r=t.pop();this._registerAckCallback(e,r),o.id=e}const s=null===(i=null===(r=this.io.engine)||void 0===r?void 0:r.transport)||void 0===i?void 0:i.writable,a=this.connected&&!(null===(n=this.io.engine)||void 0===n?void 0:n._hasPingExpired());return this.flags.volatile&&!s||(a?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,t){var r;const i=null!==(r=this.flags.timeout)&&void 0!==r?r:this._opts.ackTimeout;if(void 0===i)return void(this.acks[e]=t);const n=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},i),o=(...e)=>{this.io.clearTimeoutFn(n),t.apply(this,e)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((r,i)=>{const n=(e,t)=>e?i(e):r(t);n.withError=!0,t.push(n),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...i)=>{if(r!==this._queue[0])return;return null!==e?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...i)),r.pending=!1,this._drainQueue()}),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Oo.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){const t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Oo.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Oo.EVENT:case Oo.BINARY_EVENT:this.onevent(e);break;case Oo.ACK:case Oo.BINARY_ACK:this.onack(e);break;case Oo.DISCONNECT:this.ondisconnect();break;case Oo.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let r=!1;return function(...i){r||(r=!0,t.packet({type:Oo.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Oo.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const r of t)r.apply(this,e.data)}}}function Ho(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Ho.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+r:e-r}return 0|Math.min(e,this.max)},Ho.prototype.reset=function(){this.attempts=0},Ho.prototype.setMin=function(e){this.ms=e},Ho.prototype.setMax=function(e){this.max=e},Ho.prototype.setJitter=function(e){this.jitter=e};class qo extends qn{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,Yn(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(r=t.randomizationFactor)&&void 0!==r?r:.5),this.backoff=new Ho({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||Bo;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new So(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const i=Lo(t,"open",function(){r.onopen(),e&&e()}),n=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},o=Lo(t,"error",n);if(!1!==this._timeout){const e=this._timeout,r=this.setTimeoutFn(()=>{i(),n(new Error("timeout")),t.close()},e);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}return this.subs.push(i),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(Lo(e,"ping",this.onping.bind(this)),Lo(e,"data",this.ondata.bind(this)),Lo(e,"error",this.onerror.bind(this)),Lo(e,"close",this.onclose.bind(this)),Lo(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(Pw){this.onclose("parse error",Pw)}}ondecoded(e){jn(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new $o(this,e,t),this.nsps[e]=r),r}_destroy(e){const t=Object.keys(this.nsps);for(const r of t){if(this.nsps[r].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var r;this.cleanup(),null===(r=this.engine)||void 0===r||r.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const jo={};function Wo(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let i=e;r=r||"undefined"!=typeof location&&location,null==e&&(e=r.protocol+"//"+r.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?r.protocol+e:r.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==r?r.protocol+"//"+e:"https://"+e),i=yo(e)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const n=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+n+":"+i.port+t,i.href=i.protocol+"://"+n+(r&&r.port===i.port?"":":"+i.port),i}(e,(t=t||{}).path||"/socket.io"),i=r.source,n=r.id,o=r.path,s=jo[n]&&o in jo[n].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||s?a=new qo(i,t):(jo[n]||(jo[n]=new qo(i,t)),a=jo[n]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}function Vo(e,t,r=0){if(r>5)return;if("string"==typeof e){const r=e.trim();return void(r&&t.push(r))}if(Array.isArray(e)){for(const i of e)Vo(i,t,r+1);return}if(!function(e){return"object"==typeof e&&null!==e}(e))return;const i=["message","error","detail","reason","title","description"];for(const o of i)Vo(e[o],t,r+1);const n=["errors","details","causes","cause"];for(const o of n)Vo(e[o],t,r+1)}function Go(e){if("string"==typeof e)return e.trim();try{return JSON.stringify(e)}catch{return String(e)}}function Jo(e){var t,r;if(vr.isAxiosError(e))return null==(t=e.response)?void 0:t.status;return null==(r=e.response)?void 0:r.status}function Yo(e){if(vr.isAxiosError(e))return e.code;return e.code}function Xo(e){if(e instanceof Error&&"ValidationError"===e.name)return!1;const t=Jo(e);if("number"==typeof t)return[408,425,429,500,502,503,504].includes(t);const r=Yo(e);return!!r&&["ECONNRESET","ETIMEDOUT","EAI_AGAIN","ENOTFOUND","ECONNREFUSED","ERR_NETWORK"].includes(r)}function Zo(e){const t=Jo(e),r=Yo(e),i=function(e){var t,r;return vr.isAxiosError(e)?null==(t=e.response)?void 0:t.data:null==(r=e.response)?void 0:r.data}(e),n=[];Vo(i,n),Vo(e,n);const o=Array.from(new Set(n)).filter(Boolean),s=new Set(["failed to start inscription","failed to start inscribe job","request failed","bad request"]),a=o.filter(e=>{const t=e.toLowerCase().trim();return!!t&&(!s.has(t)&&!t.startsWith("failed to start inscription"))}).sort((e,t)=>t.length-e.length)[0]??o[0]??(e instanceof Error?e.message:""),c=["number"==typeof t?`HTTP ${t}`:null,r?`code=${r}`:null].filter(Boolean),l=c.length?` (${c.join(", ")})`:"";return a?`Failed to start inscription${l}: ${a}`:`Failed to start inscription${l}: ${Go(i)||Go(e)}`}Object.assign(Wo,{Manager:qo,Socket:$o,io:Wo,connect:Wo});const Qo=class e{constructor(e){if(K(this,"client"),K(this,"config"),K(this,"logger",$r.getInstance()),K(this,"socket",null),K(this,"socketConnected",!1),K(this,"connectionMode","auto"),K(this,"wsBaseUrl",null),this.config=e,!e.apiKey)throw new Hr("API key is required");if(!e.network)throw new Hr("Network is required");const t={"x-api-key":e.apiKey,"Content-Type":"application/json"};this.client=vr.create({baseURL:e.baseURL||e.baseUrl||"https://v2-api.tier.bot/api",headers:t}),this.logger=$r.getInstance(),e.wsBaseUrl&&(this.wsBaseUrl=e.wsBaseUrl),this.connectionMode=e.connectionMode||"websocket",this.wsBaseUrl||"http"===this.connectionMode||this.fetchWebSocketServers().catch(e=>this.logger.warn("Failed to fetch WebSocket servers:",e))}async getFileMetadata(e){try{const t=await vr.get(e),r=t.headers["content-type"]||"";return{size:parseInt(t.headers["content-length"]||"0",10),mimeType:r}}catch(t){throw this.logger.error("Error fetching file metadata:",t),new Hr("Unable to fetch file metadata")}}getMimeType(t){const r=t.toLowerCase().split(".").pop();if(!r)throw new Hr("File must have an extension");const i=e.VALID_MIME_TYPES[r];if(!i)throw new Hr(`Unsupported file type: ${r}`);return i}validateRequest(t){if(this.logger.debug("Validating request:",t),!t.holderId||""===t.holderId.trim())throw this.logger.warn("holderId is missing or empty"),new Hr("holderId is required");if(!e.VALID_MODES.includes(t.mode))throw new Hr(`Invalid mode: ${t.mode}. Must be one of: ${e.VALID_MODES.join(", ")}`);if("hashinal"===t.mode&&!t.jsonFileURL&&!t.metadataObject)throw new Hr("Hashinal mode requires either jsonFileURL or metadataObject");if(t.onlyJSONCollection&&"hashinal-collection"!==t.mode)throw new Hr("onlyJSONCollection can only be used with hashinal-collection mode");this.validateFileInput(t.file)}normalizeMimeType(e){return"image/vnd.microsoft.icon"===e?(this.logger.debug("Normalizing MIME type from image/vnd.microsoft.icon to image/x-icon"),"image/x-icon"):e}validateMimeType(t){return!!Object.values(e.VALID_MIME_TYPES).includes(t)||"image/vnd.microsoft.icon"===t&&(this.logger.debug("Accepting alternative MIME type for ICO: image/vnd.microsoft.icon"),!0)}validateFileInput(t){if("base64"===t.type){if(!t.base64)throw new Hr("Base64 data is required");const r=t.base64.replace(/^data:.*?;base64,/,"");if(Math.ceil(.75*r.length)>e.MAX_BASE64_SIZE)throw new Hr(`File size exceeds maximum limit of ${e.MAX_BASE64_SIZE/1024/1024}MB`);const i=t.mimeType||this.getMimeType(t.fileName);if(!this.validateMimeType(i))throw new Hr("File must have one of the supported MIME types");"image/vnd.microsoft.icon"===t.mimeType&&(t.mimeType=this.normalizeMimeType(t.mimeType))}else if("url"===t.type&&!t.url)throw new Hr("URL is required")}async detectMimeTypeFromBase64(e){if(e.startsWith("data:")){const t=e.match(/^data:([^;]+);base64,/);if(t&&t.length>1)return t[1]}try{const t=e.replace(/\s/g,""),r=Q.from(t,"base64"),i=await async function(e,t){return new Sn(t).fromBuffer(e)}(r);return(null==i?void 0:i.mime)||"application/octet-stream"}catch(Ow){return this.logger.warn("Failed to detect MIME type from buffer"),"application/octet-stream"}}async startInscription(t){try{const r=async()=>{this.validateRequest(t);let r=t.file.mimeType;if("url"===t.file.type){const i=await this.getFileMetadata(t.file.url);if(r=i.mimeType||r,i.size>e.MAX_URL_FILE_SIZE)throw new Hr(`File size exceeds maximum URL file limit of ${e.MAX_URL_FILE_SIZE/1024/1024}MB`)}else"base64"===t.file.type&&(r=await this.detectMimeTypeFromBase64(t.file.base64));if("image/vnd.microsoft.icon"===r&&(r=this.normalizeMimeType(r)),t.jsonFileURL){if("application/json"!==(await this.getFileMetadata(t.jsonFileURL)).mimeType)throw new Hr("JSON file must be of type application/json")}const i={holderId:t.holderId,mode:t.mode,network:this.config.network,onlyJSONCollection:t.onlyJSONCollection?1:0,creator:t.creator,description:t.description,fileStandard:t.fileStandard,metadataObject:t.metadataObject,jsonFileURL:t.jsonFileURL};if("url"===t.file.type){return(await this.client.post("/inscriptions/start-inscription",{...i,fileURL:t.file.url})).data}return(await this.client.post("/inscriptions/start-inscription",{...i,fileBase64:t.file.base64,fileName:t.file.fileName,fileMimeType:r||this.getMimeType(t.file.fileName)})).data};return await this.retryWithBackoff(r,{shouldRetry:Xo})}catch(r){if(r instanceof Hr)throw r;if(vr.isAxiosError(r))throw new Error(Zo(r));throw new Error(Zo(r))}}async executeTransaction(e,t){var i,n;try{const o="mainnet"===t.network?r.Client.forMainnet():r.Client.forTestnet(),s=new Wr(t.network),a=await s.requestAccount(t.accountId),c=null==(i=null==a?void 0:a.key)?void 0:i._type,l="string"==typeof t.privateKey;let u;if(c&&l)u=(null==(n=null==c?void 0:c.toLowerCase())?void 0:n.includes("ecdsa"))?r.PrivateKey.fromStringECDSA(t.privateKey):r.PrivateKey.fromStringED25519(t.privateKey);else if(!c&&l){const e=l?qr(t.privateKey):void 0;u="ed25519"===(null==e?void 0:e.detectedType)?r.PrivateKey.fromStringED25519(t.privateKey):r.PrivateKey.fromStringECDSA(t.privateKey)}else u=t.privateKey;o.setOperator(t.accountId,u);const d=r.TransferTransaction.fromBytes(Q.from(e,"base64")),p=await d.sign(u),h=await p.execute(o),g=(await h.getReceipt(o)).status.toString();if("SUCCESS"!==g)throw new Error(`Transaction failed with status: ${g}`);return h.transactionId.toString()}catch(o){throw new Error(`Failed to execute transaction: ${o instanceof Error?o.message:"Unknown error"}`)}}async executeTransactionWithSigner(e,t){try{const i=r.TransferTransaction.fromBytes(Q.from(e,"base64")),n=await i.executeWithSigner(t),o=(await n.getReceiptWithSigner(t)).status.toString();if("SUCCESS"!==o)throw new Error(`Transaction failed with status: ${o}`);return n.transactionId.toString()}catch(i){throw new Error(`Failed to execute transaction: ${i instanceof Error?i.message:"Unknown error"}`)}}async inscribeAndExecute(e,t,r,i){const n=(null==i?void 0:i.waitForCompletion)??!0,o=(null==i?void 0:i.maxWaitTime)??12e4,s=(null==i?void 0:i.checkInterval)??2e3;if(this.logger.debug("inscribeAndExecute called",{hasProgressCallback:!!r,connectionMode:this.connectionMode,wsBaseUrl:this.wsBaseUrl}),"http"!==this.connectionMode){const i="websocket"===this.connectionMode||"auto"===this.connectionMode&&await this.detectBestConnection();if(i)try{return await this.inscribeViaWebSocket(e,t,r)}catch(u){this.logger.warn("WebSocket inscription failed, falling back to HTTP",u)}else this.logger.info(`Not using WebSocket: useWebSocket=${i}, wsBaseUrl=${this.wsBaseUrl}`)}else this.logger.info(`Not using WebSocket: hasCallback=${!!r}, connectionMode=${this.connectionMode}`);const a=await this.startInscription(e);if(!a.transactionBytes)throw this.logger.error("No transaction bytes returned from inscription request",a),new Error("No transaction bytes returned from inscription request");this.logger.info("executing transaction");const c=await this.executeTransaction(a.transactionBytes,t),l={jobId:a.tx_id,transactionId:c};if(n){r&&r({stage:"confirming",message:"Transaction executed, waiting for inscription to complete",progressPercent:5});const e=Math.floor(o/s),t=await this.waitForInscription(c,e,s,!0,r);return{...l,topicId:t.topic_id,status:t.status,completed:t.completed}}return l}async fetchWebSocketServers(){try{const e=await this.client.get("/inscriptions/websocket-servers"),{servers:t,recommended:r}=e.data;if(r)this.wsBaseUrl=r;else if(t&&t.length>0){const e=t.filter(e=>"active"===e.status);if(e.length>0){const t=e[0];this.wsBaseUrl=t.url}}}catch(e){this.logger.debug("Could not fetch WebSocket servers, will use HTTP only")}}async detectBestConnection(){if(!this.wsBaseUrl)return!1;try{const e=Wo(this.wsBaseUrl,{auth:{apiKey:this.config.apiKey},transports:["websocket"],timeout:3e3});return new Promise(t=>{const r=setTimeout(()=>{e.disconnect(),t(!1)},3e3);e.on("connect",()=>{clearTimeout(r),e.disconnect(),t(!0)}),e.on("connect_error",()=>{clearTimeout(r),e.disconnect(),t(!1)})})}catch(Pw){return!1}}async inscribeViaWebSocket(e,t,r){if(!this.wsBaseUrl){const e=(await this.client.get("/inscriptions/websocket-servers")).data.recommended;if(!e)throw new Error("No WebSocket servers available");this.wsBaseUrl=e}return await this.connectWebSocket(),new Promise((i,n)=>{if(!this.socket)return n(new Error("WebSocket not connected"));let o,s,a,c;const l=()=>{var e,t,r;c&&clearTimeout(c),null==(e=this.socket)||e.off("inscription-progress",g),null==(t=this.socket)||t.off("inscription-complete",p),null==(r=this.socket)||r.off("inscription-error",h)},u=this.config.websocketInactivityTimeoutMs,d=()=>{!u||u<=0||(c&&clearTimeout(c),c=setTimeout(()=>{this.logger.error(`WebSocket inscription timeout after ${u/1e3} seconds`,{jobId:o,transactionId:s,lastTopicId:a}),l(),i({jobId:o,transactionId:s,topicId:a,topic_id:a,status:"timeout",completed:!1})},u))};d();const p=e=>{l(),i({jobId:o,transactionId:s,topicId:e.topicId||e.topic_id,topic_id:e.topicId||e.topic_id,status:"completed",completed:!0})},h=e=>{l(),n(new Error(e.error||"Inscription failed"))},g=e=>{d(),this.logger.debug("Progress event received:",{jobId:e.jobId,status:e.status,progress:e.progress,topicId:e.topicId||e.topic_id,topic_id:e.topicId||e.topic_id}),(e.topicId||e.topic_id)&&(a=e.topicId||e.topic_id),r&&r({stage:"completed"===e.status?"completed":"confirming",message:`Processing inscription: ${e.status}`,progressPercent:e.progress||0,details:e}),"completed"!==e.status&&100!==e.progress||(this.logger.info("Inscription completed via progress handler",{status:e.status,progress:e.progress,topicId:e.topicId||e.topic_id||a,topic_id:e.topicId||e.topic_id||a}),l(),i({jobId:o,transactionId:s,topicId:e.topicId||e.topic_id||a,topic_id:e.topicId||e.topic_id||a,status:"completed",completed:!0}))};this.socket.on("inscription-progress",g),this.socket.on("inscription-complete",p),this.socket.on("inscription-error",h),this.socket.emit("start-inscription",{...e,network:this.config.network},async e=>{if(!e.success)return l(),n(new Error(e.error||"Inscription failed"));try{if(!e.transactionBytes)throw new Error("No transaction bytes returned from WebSocket inscription");if(s=await this.executeTransaction(e.transactionBytes,t),o=e.jobId||e.tx_id,!o)throw new Error("No job ID returned from WebSocket inscription");r&&r({stage:"confirming",message:"Transaction executed, inscribing to HCS...",progressPercent:5}),this.logger.info("Transaction executed, waiting for inscription completion...",{jobId:o,transactionId:s})}catch(i){l(),n(i)}})})}async connectWebSocket(){if(!this.socketConnected||!this.socket){if(!this.wsBaseUrl)throw new Error("WebSocket URL not configured");return new Promise((e,t)=>{this.socket=Wo(this.wsBaseUrl,{auth:{apiKey:this.config.apiKey},transports:["websocket","polling"]});const r=setTimeout(()=>{t(new Error("WebSocket connection timeout"))},1e4);this.socket.on("connect",()=>{clearTimeout(r),this.socketConnected=!0,this.logger.info("WebSocket connected"),e()}),this.socket.on("connect_error",e=>{clearTimeout(r),this.socketConnected=!1,t(new Error(`WebSocket connection failed: ${e.message}`))}),this.socket.on("disconnect",()=>{this.socketConnected=!1,this.logger.info("WebSocket disconnected")})})}}disconnect(){this.socket&&(this.socket.disconnect(),this.socket=null,this.socketConnected=!1)}async inscribe(e,t){const r=await this.startInscription(e);if(!r.transactionBytes)throw this.logger.error("No transaction bytes returned from inscription request",r),new Error("No transaction bytes returned from inscription request");this.logger.info("executing transaction");const i=await this.executeTransactionWithSigner(r.transactionBytes,t);return{jobId:r.tx_id,transactionId:i}}async retryWithBackoff(e,t){const r=(null==t?void 0:t.maxRetries)??3,i=(null==t?void 0:t.baseDelayMs)??1e3,n=(null==t?void 0:t.shouldRetry)??(()=>!0);for(let s=0;s<r;s++)try{return await e()}catch(o){if(s===r-1||!n(o))throw o;const e=i*Math.pow(2,s);await new Promise(t=>setTimeout(t,e)),this.logger.debug(`Retry attempt ${s+1}/${r} after ${e}ms delay`)}throw new Error("Retry operation failed")}async retrieveInscription(e){if(!e)throw new Hr("Transaction ID is required");try{const t=e.includes("@")?`${e.split("@")[0]}-${e.split("@")[1].replace(/\./g,"-")}`:e;return await this.retryWithBackoff(async()=>{const e=(await this.client.get(`/inscriptions/retrieve-inscription?id=${t}`)).data,r=e.completed||"completed"===e.status.toLowerCase();return{...e,completed:r,jobId:e.tx_id||t}})}catch(t){throw this.logger.error("Failed to retrieve inscription:",t),t}}async getInscriptionNumbers(e={}){try{return(await this.client.get("/inscriptions/numbers",{params:e})).data}catch(t){throw this.logger.error("Failed to fetch inscription numbers:",t),t}}static async authenticate(e){return new jr(e).authenticate()}static async createWithAuth(t){const r="client"===t.type?new Vr({...t,logger:$r.getInstance()}):new jr(t),{apiKey:i}=await r.authenticate();return new e({apiKey:i,network:t.network||"mainnet",baseURL:t.baseUrl,wsBaseUrl:t.wsBaseUrl,connectionMode:t.connectionMode||"websocket"})}async waitForInscription(e,t=Number.MAX_SAFE_INTEGER,r=4e3,i=!1,n){var o,s;let a=0,c=0;const l=(r,i,o,s)=>{if(n)try{c=Math.max(c,o),n({stage:r,message:i,progressPercent:c,details:{...s,txId:e,currentAttempt:a,maxAttempts:t}})}catch(Ow){this.logger.warn(`Error in progress callback: ${Ow}`)}};for(l("confirming","Starting inscription verification",0);a<t;){l("confirming",`Verifying inscription status (attempt ${a+1}/${t})`,5,{attempt:a+1});const n=await this.retrieveInscription(e);if(n.error)throw l("verifying",`Error: ${n.error}`,100,{error:n.error}),new Error(n.error);let c=5;const u=n.completed||"completed"===n.status.toLowerCase();void 0!==n.messages&&void 0!==n.maxMessages&&n.maxMessages>0?(c=Math.min(95,5+n.messages/n.maxMessages*90),u&&(c=100)):"processing"===n.status?c=10:u&&(c=100),l(u?"completed":"confirming",u?"Inscription completed successfully":`Processing inscription (${n.status})`,c,{status:n.status,messagesProcessed:n.messages,maxMessages:n.maxMessages,messageCount:n.messages,completed:u,confirmedMessages:n.confirmedMessages,result:n});const d="hashinal"===n.mode,p="hashinal-collection"===n.mode,h="bulk-files"===n.mode,g="6"===(null==(o=n.fileStandard)?void 0:o.toString());if(p&&u&&(!i||u))return l("completed","Inscription verification complete",100,{result:n}),n;if(d&&n.topic_id&&n.jsonTopicId&&(!i||u))return l("completed","Inscription verification complete",100,{result:n}),n;if(!d&&!g&&n.topic_id&&(!i||u))return l("completed","Inscription verification complete",100,{result:n}),n;if(g&&n.topic_id&&n.jsonTopicId&&n.registryTopicId&&(!i||u))return l("completed","Inscription verification complete",100,{result:n}),n;if(h&&u){const e=null==(s=n.files)?void 0:s.bulkUploads,t=Array.isArray(e)&&e.length>0;if(!i||t)return l("completed","Inscription verification complete",100,{result:n}),n}await new Promise(e=>setTimeout(e,r)),a++}throw l("verifying",`Inscription ${e} did not complete within ${t} attempts`,100,{timedOut:!0}),new Error(`Inscription ${e} did not complete within ${t} attempts`)}async getHolderInscriptions(e){var t,r;if(!e.holderId)throw new Hr("Holder ID is required");try{const t={holderId:e.holderId};e.includeCollections&&(t.includeCollections="1");return(await this.client.get("/inscriptions/holder-inscriptions",{params:t})).data}catch(i){if(this.logger.error("Failed to fetch holder inscriptions:",i),vr.isAxiosError(i))throw new Error((null==(r=null==(t=i.response)?void 0:t.data)?void 0:r.message)||"Failed to fetch holder inscriptions");throw i}}};K(Qo,"VALID_MODES",["file","upload","hashinal","hashinal-collection","bulk-files"]),K(Qo,"MAX_BASE64_SIZE",33554432),K(Qo,"MAX_URL_FILE_SIZE",104857600),K(Qo,"VALID_MIME_TYPES",{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",ico:"image/x-icon",heic:"image/heic",heif:"image/heif",bmp:"image/bmp",webp:"image/webp",tiff:"image/tiff",tif:"image/tiff",svg:"image/svg+xml",mp4:"video/mp4",webm:"video/webm",mp3:"audio/mpeg",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",html:"text/html",htm:"text/html",css:"text/css",php:"application/x-httpd-php",java:"text/x-java-source",js:"application/javascript",mjs:"application/javascript",csv:"text/csv",json:"application/json",txt:"text/plain",glb:"model/gltf-binary",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",flac:"audio/flac",aac:"audio/aac",m4a:"audio/mp4",avi:"video/x-msvideo",mov:"video/quicktime",mkv:"video/x-matroska",m4v:"video/mp4",mpg:"video/mpeg",mpeg:"video/mpeg",ts:"application/typescript",zip:"application/zip",rar:"application/vnd.rar",tar:"application/x-tar",gz:"application/gzip","7z":"application/x-7z-compressed",xml:"application/xml",yaml:"application/yaml",yml:"application/yaml",md:"text/markdown",markdown:"text/markdown",rtf:"application/rtf",gltf:"model/gltf+json",usdz:"model/vnd.usdz+zip",obj:"model/obj",stl:"model/stl",fbx:"application/octet-stream",ttf:"font/ttf",otf:"font/otf",woff:"font/woff",woff2:"font/woff2",eot:"application/vnd.ms-fontobject",psd:"application/vnd.adobe.photoshop",ai:"application/postscript",eps:"application/postscript",ps:"application/postscript",sqlite:"application/x-sqlite3",db:"application/x-sqlite3",apk:"application/vnd.android.package-archive",ics:"text/calendar",vcf:"text/vcard",py:"text/x-python",rb:"text/x-ruby",go:"text/x-go",rs:"text/x-rust",typescript:"application/typescript",jsx:"text/jsx",tsx:"text/tsx",sql:"application/sql",toml:"application/toml",avif:"image/avif",jxl:"image/jxl",weba:"audio/webm",wasm:"application/wasm"});let es=Qo;class ts{constructor(e={}){this.module=e.module||"Progress",this.callback=e.callback,this.logger=e.logger||new y({level:"info",module:"ProgressReporter"}),this.logProgress=e.logProgress??!0,this.minPercent=e.minPercent??0,this.maxPercent=e.maxPercent??100,this.lastReportedPercent=-1,this.lastReportedTime=0,this.throttleMs=100}static getInstance(e={}){return ts.instance?(e.callback&&ts.instance.setCallback(e.callback),e.module&&ts.instance.setModule(e.module),e.logger&&ts.instance.setLogger(e.logger),void 0!==e.minPercent&&ts.instance.setMinPercent(e.minPercent),void 0!==e.maxPercent&&ts.instance.setMaxPercent(e.maxPercent)):ts.instance=new ts(e),ts.instance}setCallback(e){this.callback=e}setModule(e){this.module=e}setLogger(e){this.logger=e}setMinPercent(e){this.minPercent=e}setMaxPercent(e){this.maxPercent=e}createSubProgress(e){const t=new ts({module:this.module,logger:this.logger,logProgress:this.logProgress,minPercent:e.minPercent,maxPercent:e.maxPercent}),r=e.logPrefix||"";return t.setCallback(t=>{const i=this.scalePercent(t.progressPercent,e.minPercent,e.maxPercent);let n=t.message;r&&!n.startsWith(r)&&(n=`${r}: ${n}`),this.report({stage:t.stage,message:n,progressPercent:i,details:t.details})}),t}report(e){const t=e.progressPercent,r=Math.max(0,Math.min(100,t)),i=this.scalePercent(r,0,100),n=Date.now();if(i===this.lastReportedPercent&&n-this.lastReportedTime<this.throttleMs&&"completed"!==e.stage&&"failed"!==e.stage)return;this.lastReportedPercent=i,this.lastReportedTime=n;const o={...e,progressPercent:i};if(this.logProgress&&this.logger.debug(`[${this.module}] [${e.stage.toUpperCase()}] ${e.message} (${i.toFixed(1)}%)`,e.details),this.callback)try{this.callback(o)}catch(Ow){this.logger.warn(`Error in progress callback: ${Ow}`)}}scalePercent(e,t,r){const i=(this.maxPercent-this.minPercent)/(r-t);return this.minPercent+(e-t)*i}preparing(e,t,r){this.report({stage:"preparing",message:e,progressPercent:t,details:r})}submitting(e,t,r){this.report({stage:"submitting",message:e,progressPercent:t,details:r})}confirming(e,t,r){this.report({stage:"confirming",message:e,progressPercent:t,details:r})}verifying(e,t,r){this.report({stage:"verifying",message:e,progressPercent:t,details:r})}completed(e,t){this.report({stage:"completed",message:e,progressPercent:100,details:t})}failed(e,t){this.report({stage:"failed",message:e,progressPercent:this.lastReportedPercent,details:t})}}class rs extends Error{constructor(e,t="PARSING_FAILED",r,i){super(e),this.name="TransactionParsingError",this.code=t,this.originalError=r,this.transactionBytes=i,Error.captureStackTrace&&Error.captureStackTrace(this,rs)}}const is=(e,t)=>e.replace(/\{([^}]+)\}/g,(e,r)=>{const i=((e,t)=>{const r=t.split(".");let i=e;for(const n of r){if(null==i)return;i=i[n]}return i})(t,String(r).trim());return null==i?"(Unknown)":String(i)}),ns=e=>{const t=[],r=[];if(Array.isArray(e.transfers))for(const i of e.transfers){const e=parseFloat(i.amount);let n=i.amount;n.startsWith("-")&&(n=n.substring(1)),n=n.replace(/\s*ℏ$/,""),e<0?t.push(`${i.accountId} (${n} ℏ)`):e>0&&r.push(`${i.accountId} (${n} ℏ)`)}return t.length>0&&r.length>0?`Transfer of HBAR from ${t.join(", ")} to ${r.join(", ")}`:e.humanReadableType},os=e=>{if(!e.contractCall)return e.humanReadableType;let t=`Contract call to ${e.contractCall.contractId} with ${e.contractCall.gas} gas`;return e.contractCall.amount>0&&(t+=` and ${e.contractCall.amount} HBAR`),e.contractCall.functionName&&(t+=` calling function ${e.contractCall.functionName}`),t},ss=e=>e.tokenMint?`Mint ${e.tokenMint.amount} tokens for token ${e.tokenMint.tokenId}`:e.humanReadableType,as=e=>e.tokenBurn?`Burn ${e.tokenBurn.amount} tokens for token ${e.tokenBurn.tokenId}`:e.humanReadableType,cs=e=>{if(!e.tokenCreation)return e.humanReadableType;let t=`Create token ${e.tokenCreation.tokenName||"(No Name)"} (${e.tokenCreation.tokenSymbol||"(No Symbol)"})`;return e.tokenCreation.initialSupply&&(t+=` with initial supply ${e.tokenCreation.initialSupply}`),e.tokenCreation.customFees&&e.tokenCreation.customFees.length>0&&(t+=` including ${e.tokenCreation.customFees.length} custom fee(s)`),t},ls=e=>{if(!e.consensusCreateTopic)return e.humanReadableType;let t="Create new topic";return e.consensusCreateTopic.memo&&(t+=` with memo "${e.consensusCreateTopic.memo}"`),e.consensusCreateTopic.autoRenewAccountId&&(t+=`, auto-renew by ${e.consensusCreateTopic.autoRenewAccountId}`),t},us=e=>{if(!e.consensusSubmitMessage)return e.humanReadableType;let t="Submit message";if(e.consensusSubmitMessage.topicId&&(t+=` to topic ${e.consensusSubmitMessage.topicId}`),e.consensusSubmitMessage.message)if("utf8"===e.consensusSubmitMessage.messageEncoding){t+=`: "${e.consensusSubmitMessage.message.substring(0,70)}${e.consensusSubmitMessage.message.length>70?"...":""}"`}else{t+=` (binary message data, length: ${globalThis.Buffer.from(e.consensusSubmitMessage.message,"base64").length} bytes)`}return e.consensusSubmitMessage.chunkInfoNumber&&e.consensusSubmitMessage.chunkInfoTotal&&(t+=` (chunk ${e.consensusSubmitMessage.chunkInfoNumber}/${e.consensusSubmitMessage.chunkInfoTotal})`),t},ds=e=>{if(!e.fileCreate)return e.humanReadableType;let t="Create File";return e.fileCreate.memo&&(t+=` with memo "${e.fileCreate.memo}"`),e.fileCreate.contents&&(t+=" (includes content)"),t},ps=e=>e.fileAppend?`Append to File ${e.fileAppend.fileId||"(Unknown ID)"}`:e.humanReadableType,hs=e=>e.fileUpdate?`Update File ${e.fileUpdate.fileId||"(Unknown ID)"}`:e.humanReadableType,gs=e=>e.fileDelete?`Delete File ${e.fileDelete.fileId||"(Unknown ID)"}`:e.humanReadableType,ms=e=>e.consensusUpdateTopic?`Update Topic ${e.consensusUpdateTopic.topicId||"(Unknown ID)"}`:e.humanReadableType,fs=e=>e.consensusDeleteTopic?`Delete Topic ${e.consensusDeleteTopic.topicId||"(Unknown ID)"}`:e.humanReadableType,ys=e=>e.tokenFreeze?`Freeze Token ${e.tokenFreeze.tokenId} for Account ${e.tokenFreeze.accountId}`:e.humanReadableType,bs=e=>e.tokenUnfreeze?`Unfreeze Token ${e.tokenUnfreeze.tokenId} for Account ${e.tokenUnfreeze.accountId}`:e.humanReadableType,ws=e=>e.tokenGrantKyc?`Grant KYC for Token ${e.tokenGrantKyc.tokenId} to Account ${e.tokenGrantKyc.accountId}`:e.humanReadableType,Is=e=>e.tokenRevokeKyc?`Revoke KYC for Token ${e.tokenRevokeKyc.tokenId} from Account ${e.tokenRevokeKyc.accountId}`:e.humanReadableType,Ts=e=>e.tokenPause?`Pause Token ${e.tokenPause.tokenId}`:e.humanReadableType,Ss=e=>e.tokenUnpause?`Unpause Token ${e.tokenUnpause.tokenId}`:e.humanReadableType,ks=e=>{if(e.tokenWipeAccount){let t=`Wipe Token ${e.tokenWipeAccount.tokenId} from Account ${e.tokenWipeAccount.accountId}`;return e.tokenWipeAccount.serialNumbers&&e.tokenWipeAccount.serialNumbers.length>0&&(t+=` (Serials: ${e.tokenWipeAccount.serialNumbers.join(", ")})`),e.tokenWipeAccount.amount&&(t+=` (Amount: ${e.tokenWipeAccount.amount})`),t}return e.humanReadableType},vs=e=>e.tokenDelete?`Delete Token ${e.tokenDelete.tokenId}`:e.humanReadableType,Es=e=>e.tokenAssociate?`Associate Account ${e.tokenAssociate.accountId} with Tokens: ${(e.tokenAssociate.tokenIds||[]).join(", ")}`:e.humanReadableType,As=e=>e.tokenDissociate?`Dissociate Account ${e.tokenDissociate.accountId} from Tokens: ${(e.tokenDissociate.tokenIds||[]).join(", ")}`:e.humanReadableType,Cs=e=>e.cryptoDelete?`Delete Account ${e.cryptoDelete.deleteAccountId}`:e.humanReadableType,Rs=e=>{if(!e.cryptoCreateAccount)return e.humanReadableType;let t="Create Account";return e.cryptoCreateAccount.initialBalance&&"0"!==e.cryptoCreateAccount.initialBalance&&(t+=` with balance ${e.cryptoCreateAccount.initialBalance}`),e.cryptoCreateAccount.alias&&(t+=` (Alias: ${e.cryptoCreateAccount.alias})`),t},xs=e=>e.cryptoUpdateAccount?`Update Account ${e.cryptoUpdateAccount.accountIdToUpdate||"(Unknown ID)"}`:e.humanReadableType,Ns=e=>{if(e.cryptoApproveAllowance){let t=0;return e.cryptoApproveAllowance.hbarAllowances&&(t+=e.cryptoApproveAllowance.hbarAllowances.length),e.cryptoApproveAllowance.tokenAllowances&&(t+=e.cryptoApproveAllowance.tokenAllowances.length),e.cryptoApproveAllowance.nftAllowances&&(t+=e.cryptoApproveAllowance.nftAllowances.length),`Approve ${t} Crypto Allowance(s)`}return e.humanReadableType},zs=e=>{if(e.cryptoDeleteAllowance){return`Delete ${(e.cryptoDeleteAllowance.nftAllowancesToRemove||[]).length} NFT Crypto Allowance(s)`}return e.humanReadableType},_s=e=>{if(e.contractCreate){let t="Create Contract";return e.contractCreate.memo&&(t+=` (Memo: ${e.contractCreate.memo})`),t}return e.humanReadableType},Ps=e=>e.contractUpdate?`Update Contract ${e.contractUpdate.contractIdToUpdate||"(Unknown ID)"}`:e.humanReadableType,Os=e=>{if(e.contractDelete){let t=`Delete Contract ${e.contractDelete.contractIdToDelete||"(Unknown ID)"}`;return e.contractDelete.transferAccountId?t+=` (Transfer to Account: ${e.contractDelete.transferAccountId})`:e.contractDelete.transferContractId&&(t+=` (Transfer to Contract: ${e.contractDelete.transferContractId})`),t}return e.humanReadableType},Ds=e=>e.tokenUpdate?`Update Token ${e.tokenUpdate.tokenId||"(Unknown ID)"}`:e.humanReadableType,Fs=e=>e.tokenFeeScheduleUpdate?`Update Fee Schedule for Token ${e.tokenFeeScheduleUpdate.tokenId||"(Unknown ID)"}`:e.humanReadableType,Ms=e=>{if(!e.tokenAirdrop||!e.tokenAirdrop.tokenTransfers)return e.humanReadableType;let t=0,r=0;for(const i of e.tokenAirdrop.tokenTransfers)t+=1,r+=Array.isArray(i.transfers)?i.transfers.length:0;return`Token Airdrop across ${t} token(s), ${r} transfer(s)`},Us=e=>{if(!e.scheduleCreate)return e.humanReadableType;let t="Create Schedule";return e.scheduleCreate.memo&&(t+=` (Memo: ${e.scheduleCreate.memo})`),t},Bs=e=>e.scheduleSign?"Sign Schedule":e.humanReadableType,Ls=e=>e.scheduleDelete?"Delete Schedule":e.humanReadableType,Ks=e=>e.systemDelete?e.systemDelete.fileId?`System Delete File ${e.systemDelete.fileId}`:e.systemDelete.contractId?`System Delete Contract ${e.systemDelete.contractId}`:"System Delete":e.humanReadableType,$s=e=>e.systemUndelete?e.systemUndelete.fileId?`System Undelete File ${e.systemUndelete.fileId}`:e.systemUndelete.contractId?`System Undelete Contract ${e.systemUndelete.contractId}`:"System Undelete":e.humanReadableType,Hs=e=>"Network Freeze",qs=e=>"Ethereum Transaction",js=e=>e.uncheckedSubmit&&e.uncheckedSubmit.topicId?`Unchecked Submit to topic ${e.uncheckedSubmit.topicId}`:"Unchecked Submit",Ws=e=>"Create Node",Vs=e=>"Update Node",Gs=e=>"Delete Node",Js=e=>`Atomic Batch (${Array.isArray(e.atomicBatch?.transactions)?e.atomicBatch.transactions.length:0} transaction(s))`,Ys={CRYPTOTRANSFER:{fn:ns},cryptoTransfer:{fn:ns},CONTRACTCALL:{fn:os},contractCall:{fn:os},TOKENMINT:{fn:ss},tokenMint:{fn:ss},TOKENBURN:{fn:as},tokenBurn:{fn:as},TOKENCREATE:{fn:cs},tokenCreation:{fn:cs},TOPICCREATE:{fn:ls},consensusCreateTopic:{fn:ls},CONSENSUSSUBMITMESSAGE:{fn:us},consensusSubmitMessage:{fn:us},TOPICUPDATE:{fn:ms},consensusUpdateTopic:{fn:ms},TOPICDELETE:{fn:fs},consensusDeleteTopic:{fn:fs},FILECREATE:{fn:ds},fileCreate:{fn:ds},FILEAPPEND:{fn:ps},fileAppend:{fn:ps},FILEUPDATE:{fn:hs},fileUpdate:{fn:hs},FILEDELETE:{fn:gs},fileDelete:{fn:gs},TOKENUPDATE:{fn:Ds},tokenUpdate:{fn:Ds},TOKENFEESCHEDULEUPDATE:{fn:Fs},tokenFeeScheduleUpdate:{fn:Fs},TOKENFREEZE:{fn:ys},tokenFreeze:{fn:ys},TOKENUNFREEZE:{fn:bs},tokenUnfreeze:{fn:bs},TOKENGRANTKYC:{fn:ws},tokenGrantKyc:{fn:ws},TOKENREVOKEKYC:{fn:Is},tokenRevokeKyc:{fn:Is},TOKENPAUSE:{fn:Ts},tokenPause:{fn:Ts},TOKENUNPAUSE:{fn:Ss},tokenUnpause:{fn:Ss},TOKENWIPE:{fn:ks},TOKENWIPEACCOUNT:{fn:ks},tokenWipe:{fn:ks},tokenWipeAccount:{fn:ks},TOKENDELETE:{fn:vs},tokenDelete:{fn:vs},TOKENASSOCIATE:{fn:Es},tokenAssociate:{fn:Es},TOKENDISSOCIATE:{fn:As},tokenDissociate:{fn:As},ACCOUNTDELETE:{fn:Cs},cryptoDelete:{fn:Cs},ACCOUNTCREATE:{fn:Rs},cryptoCreateAccount:{fn:Rs},ACCOUNTUPDATE:{fn:xs},cryptoUpdateAccount:{fn:xs},APPROVEALLOWANCE:{fn:Ns},cryptoApproveAllowance:{fn:Ns},DELETEALLOWANCE:{fn:zs},cryptoDeleteAllowance:{fn:zs},CONTRACTCREATE:{fn:_s},contractCreate:{fn:_s},CONTRACTUPDATE:{fn:Ps},contractUpdate:{fn:Ps},CONTRACTDELETE:{fn:Os},contractDelete:{fn:Os},TOKENAIRDROP:{fn:Ms},tokenAirdrop:{fn:Ms},SCHEDULECREATE:{fn:Us},scheduleCreate:{fn:Us},SCHEDULESIGN:{fn:Bs},scheduleSign:{fn:Bs},SCHEDULEDELETE:{fn:Ls},scheduleDelete:{fn:Ls},SYSTEMDELETE:{fn:Ks},systemDelete:{fn:Ks},SYSTEMUNDELETE:{fn:$s},systemUndelete:{fn:$s},FREEZE:{fn:Hs},freeze:{fn:Hs},ETHEREUMTRANSACTION:{fn:qs},ethereumTransaction:{fn:qs},UNCHECKEDSUBMIT:{fn:js},uncheckedSubmit:{fn:js},NODECREATE:{fn:Ws},nodeCreate:{fn:Ws},NODEUPDATE:{fn:Vs},nodeUpdate:{fn:Vs},NODEDELETE:{fn:Gs},nodeDelete:{fn:Gs},ATOMICBATCH:{fn:Js},atomicBatch:{fn:Js}},Xs=e=>{const t=Ys[e.type];if(t){if(t.fn)return t.fn(e);if(t.template)return is(t.template,e)}const r=Ys[e.humanReadableType];if(r){if(r.fn)return r.fn(e);if(r.template)return is(r.template,e)}return"cryptoTransfer"===e.type||"CRYPTOTRANSFER"===e.type?ns(e):e.contractCall?os(e):Array.isArray(e.tokenTransfers)&&e.tokenTransfers.length>0?(e=>{const t=[],r=(e=>{const t={};for(const r of e)t[r.tokenId]||(t[r.tokenId]=[]),t[r.tokenId].push(r);return t})(e.tokenTransfers||[]);for(const[i,n]of Object.entries(r)){const e=[],r=[];for(const t of n){const i=parseFloat(String(t.amount));i<0?e.push(`${t.accountId} (${Math.abs(i)})`):i>0&&r.push(`${t.accountId} (${i})`)}e.length>0&&r.length>0&&t.push(`Transfer of token ${i} from ${e.join(", ")} to ${r.join(", ")}`)}return t.length>0?t.join("; "):e.humanReadableType})(e):e.humanReadableType&&"Unknown Transaction"!==e.humanReadableType?e.humanReadableType:"Unknown Transaction"};function Zs(e){if(e){if(e.contractID)return`ContractID: ${new r.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()}`;if(e.ed25519)return`ED25519: ${o.Buffer.from(e.ed25519).toString("hex")}`;if(e.ECDSASecp256k1)return`ECDSA_secp256k1: ${o.Buffer.from(e.ECDSASecp256k1).toString("hex")}`;if(e?.keyList?.keys?.length>0){const t=e.keyList.keys.map(e=>Zs(e)).filter(Boolean);return`KeyList (${t.length} keys): [${t.join(", ")}]`}if(e?.thresholdKey?.keys?.keys?.length>0){const t=e.thresholdKey.keys.keys.map(e=>Zs(e)).filter(Boolean);return`ThresholdKey (${e.thresholdKey.threshold} of ${t.length}): [${t.join(", ")}]`}return e.delegatableContractId?`DelegatableContractID: ${new r.ContractId(e.delegatableContractId.shardNum??0,e.delegatableContractId.realmNum??0,e.delegatableContractId.contractNum??0).toString()}`:0===Object.keys(e).length?"Empty Key Structure":"Unknown or Unset Key Type"}}function Qs(e){try{const t=e.toBytes?e.toBytes():void 0;if(!t)return null;const r=n.proto.TransactionList.decode(t);if(!r.transactionList||0===r.transactionList.length)return null;const i=r.transactionList[0];if(i.bodyBytes&&i.bodyBytes.length>0)return n.proto.TransactionBody.decode(i.bodyBytes);if(i.signedTransactionBytes&&i.signedTransactionBytes.length>0){const e=n.proto.SignedTransaction.decode(i.signedTransactionBytes);if(e.bodyBytes)return n.proto.TransactionBody.decode(e.bodyBytes)}return null}catch(t){return null}}function ea(e,t){const r=Qs(e);return!(!r||!r[t])}class ta{static parseHTSTransaction(e){try{const t=e._transactionBody;if(!t)return{};if(t.tokenCreation){const e=this.parseTokenCreate(t.tokenCreation);if(e)return{type:"TOKENCREATE",humanReadableType:"Token Creation",tokenCreation:e}}if(t.tokenMint){const e=this.parseTokenMint(t.tokenMint);if(e)return{type:"TOKENMINT",humanReadableType:"Token Mint",tokenMint:e}}if(t.tokenBurn){const e=this.parseTokenBurn(t.tokenBurn);if(e)return{type:"TOKENBURN",humanReadableType:"Token Burn",tokenBurn:e}}if(t.tokenUpdate){const e=this.parseTokenUpdate(t.tokenUpdate);if(e)return{type:"TOKENUPDATE",humanReadableType:"Token Update",tokenUpdate:e}}if(t.tokenFreeze){const e=this.parseTokenFreeze(t.tokenFreeze);if(e)return{type:"TOKENFREEZE",humanReadableType:"Token Freeze",tokenFreeze:e}}if(t.tokenUnfreeze){const e=this.parseTokenUnfreeze(t.tokenUnfreeze);if(e)return{type:"TOKENUNFREEZE",humanReadableType:"Token Unfreeze",tokenUnfreeze:e}}if(t.tokenGrantKyc){const e=this.parseTokenGrantKyc(t.tokenGrantKyc);if(e)return{type:"TOKENGRANTKYC",humanReadableType:"Token Grant KYC",tokenGrantKyc:e}}if(t.tokenRevokeKyc){const e=this.parseTokenRevokeKyc(t.tokenRevokeKyc);if(e)return{type:"TOKENREVOKEKYC",humanReadableType:"Token Revoke KYC",tokenRevokeKyc:e}}if(t.tokenPause){const e=this.parseTokenPause(t.tokenPause);if(e)return{type:"TOKENPAUSE",humanReadableType:"Token Pause",tokenPause:e}}if(t.tokenUnpause){const e=this.parseTokenUnpause(t.tokenUnpause);if(e)return{type:"TOKENUNPAUSE",humanReadableType:"Token Unpause",tokenUnpause:e}}if(t.tokenWipe){const e=this.parseTokenWipeAccount(t.tokenWipe);if(e)return{type:"TOKENWIPEACCOUNT",humanReadableType:"Token Wipe Account",tokenWipeAccount:e}}if(t.tokenDeletion){const e=this.parseTokenDelete(t.tokenDeletion);if(e)return{type:"TOKENDELETE",humanReadableType:"Token Delete",tokenDelete:e}}if(t.tokenAssociate){const e=this.parseTokenAssociate(t.tokenAssociate);if(e)return{type:"TOKENASSOCIATE",humanReadableType:"Token Associate",tokenAssociate:e}}if(t.tokenDissociate){const e=this.parseTokenDissociate(t.tokenDissociate);if(e)return{type:"TOKENDISSOCIATE",humanReadableType:"Token Dissociate",tokenDissociate:e}}if(t.tokenFeeScheduleUpdate){const e=this.parseTokenFeeScheduleUpdate(t.tokenFeeScheduleUpdate);if(e)return{type:"TOKENFEESCHEDULEUPDATE",humanReadableType:"Token Fee Schedule Update",tokenFeeScheduleUpdate:e}}const r=this.parseTokenAirdrop(e);return r?{type:"TOKENAIRDROP",humanReadableType:"Token Airdrop",tokenAirdrop:r}:{}}catch(t){return console.warn("[HTSParser] Failed to parse HTS transaction:",t),{}}}static parseTokenCreate(e){if(!e)return;const t={};return e.name&&(t.tokenName=e.name),e.symbol&&(t.tokenSymbol=e.symbol),e.treasury&&(t.treasuryAccountId=new r.AccountId(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),e.initialSupply&&(t.initialSupply=r.Long.fromValue(e.initialSupply).toString()),void 0!==e.decimals&&null!==e.decimals&&(t.decimals=r.Long.fromValue(e.decimals).toNumber()),e.maxSupply&&(t.maxSupply=r.Long.fromValue(e.maxSupply).toString()),e.memo&&(t.memo=e.memo),null!==e.tokenType&&void 0!==e.tokenType&&(t.tokenType=n.proto.TokenType[e.tokenType]),null!==e.supplyType&&void 0!==e.supplyType&&(t.supplyType=n.proto.TokenSupplyType[e.supplyType]),t.adminKey=Zs(e.adminKey),t.kycKey=Zs(e.kycKey),t.freezeKey=Zs(e.freezeKey),t.wipeKey=Zs(e.wipeKey),t.supplyKey=Zs(e.supplyKey),t.feeScheduleKey=Zs(e.feeScheduleKey),t.pauseKey=Zs(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccount=new r.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.customFees&&e.customFees.length>0&&(t.customFees=e.customFees.map(e=>{const t={feeCollectorAccountId:e.feeCollectorAccountId?new r.AccountId(e.feeCollectorAccountId.shardNum??0,e.feeCollectorAccountId.realmNum??0,e.feeCollectorAccountId.accountNum??0).toString():"Not Set",allCollectorsAreExempt:e.allCollectorsAreExempt||!1};if(e.fixedFee)return{...t,feeType:"FIXED_FEE",fixedFee:{amount:r.Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new r.TokenId(e.fixedFee.denominatingTokenId.shardNum??0,e.fixedFee.denominatingTokenId.realmNum??0,e.fixedFee.denominatingTokenId.tokenNum??0).toString():void 0}};if(e.fractionalFee)return{...t,feeType:"FRACTIONAL_FEE",fractionalFee:{numerator:r.Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:r.Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:r.Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:r.Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let i;return e.royaltyFee.fallbackFee&&(i={amount:r.Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new r.TokenId(e.royaltyFee.fallbackFee.denominatingTokenId.shardNum??0,e.royaltyFee.fallbackFee.denominatingTokenId.realmNum??0,e.royaltyFee.fallbackFee.denominatingTokenId.tokenNum??0).toString():void 0}),{...t,feeType:"ROYALTY_FEE",royaltyFee:{numerator:r.Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:r.Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:i}}}return{...t,feeType:"FIXED_FEE",fixedFee:{amount:"0"}}})),t}static parseTokenMint(e){if(!e||!e.token||null===e.amount||void 0===e.amount)return;const t={tokenId:new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:r.Long.fromValue(e.amount).toNumber()};return e.metadata&&e.metadata.length>0&&(t.metadata=e.metadata.map(e=>o.Buffer.from(e).toString("base64"))),t}static parseTokenBurn(e){if(!e||!e.token||null===e.amount||void 0===e.amount)return;const t={tokenId:new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:r.Long.fromValue(e.amount).toNumber()};return e.serialNumbers&&e.serialNumbers.length>0&&(t.serialNumbers=e.serialNumbers.map(e=>r.Long.fromValue(e).toNumber())),t}static parseTokenUpdate(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.name&&(t.name=e.name),e.symbol&&(t.symbol=e.symbol),e.treasury&&(t.treasuryAccountId=new r.AccountId(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),t.adminKey=Zs(e.adminKey),t.kycKey=Zs(e.kycKey),t.freezeKey=Zs(e.freezeKey),t.wipeKey=Zs(e.wipeKey),t.supplyKey=Zs(e.supplyKey),t.feeScheduleKey=Zs(e.feeScheduleKey),t.pauseKey=Zs(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccountId=new r.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),void 0!==e.memo?.value&&(t.memo=e.memo.value),e.expiry?.seconds&&(t.expiry=`${r.Long.fromValue(e.expiry.seconds).toString()}.${e.expiry.nanos}`),t}static parseTokenFeeScheduleUpdate(e){if(!e)return;const t={};return e.tokenId&&(t.tokenId=new r.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString()),e.customFees&&e.customFees.length>0&&(t.customFees=e.customFees.map(e=>{const t={feeCollectorAccountId:e.feeCollectorAccountId?new r.AccountId(e.feeCollectorAccountId.shardNum??0,e.feeCollectorAccountId.realmNum??0,e.feeCollectorAccountId.accountNum??0).toString():"Not Set",allCollectorsAreExempt:e.allCollectorsAreExempt||!1};if(e.fixedFee)return{...t,feeType:"FIXED_FEE",fixedFee:{amount:r.Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new r.TokenId(e.fixedFee.denominatingTokenId.shardNum??0,e.fixedFee.denominatingTokenId.realmNum??0,e.fixedFee.denominatingTokenId.tokenNum??0).toString():void 0}};if(e.fractionalFee)return{...t,feeType:"FRACTIONAL_FEE",fractionalFee:{numerator:r.Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:r.Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:r.Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:r.Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let i;return e.royaltyFee.fallbackFee&&(i={amount:r.Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new r.TokenId(e.royaltyFee.fallbackFee.denominatingTokenId.shardNum??0,e.royaltyFee.fallbackFee.denominatingTokenId.realmNum??0,e.royaltyFee.fallbackFee.denominatingTokenId.tokenNum??0).toString():void 0}),{...t,feeType:"ROYALTY_FEE",royaltyFee:{numerator:r.Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:r.Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:i}}}return{...t,feeType:"FIXED_FEE",fixedFee:{amount:"0"}}})),t}static parseTokenFreeze(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new r.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),t}static parseTokenUnfreeze(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new r.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),t}static parseTokenGrantKyc(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new r.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),t}static parseTokenRevokeKyc(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new r.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),t}static parseTokenPause(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),t}static parseTokenUnpause(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),t}static parseTokenWipeAccount(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new r.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),e.serialNumbers&&e.serialNumbers.length>0&&(t.serialNumbers=e.serialNumbers.map(e=>r.Long.fromValue(e).toString())),e.amount&&(t.amount=r.Long.fromValue(e.amount).toString()),t}static parseTokenDelete(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),t}static parseTokenAssociate(e){if(!e)return;const t={};return e.account&&(t.accountId=new r.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),e.tokens&&e.tokens.length>0&&(t.tokenIds=e.tokens.map(e=>new r.TokenId(e.shardNum??0,e.realmNum??0,e.tokenNum??0).toString())),t}static parseTokenDissociate(e){if(!e)return;const t={};return e.account&&(t.accountId=new r.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),e.tokens&&e.tokens.length>0&&(t.tokenIds=e.tokens.map(e=>new r.TokenId(e.shardNum??0,e.realmNum??0,e.tokenNum??0).toString())),t}static parseTokenAirdrop(e){try{const t=e._transactionBody;if(t?.tokenAirdrop){return{tokenTransfers:(t.tokenAirdrop.tokenTransfers||[]).map(e=>({tokenId:e.token?.toString()||"Unknown",transfers:(e.transfers||[]).map(e=>({accountId:e.accountID?.toString()||"Unknown",amount:e.amount?.toString()||"0",serialNumbers:e.serialNumbers?.map(e=>e.toString())}))}))}}if(ea(e,"tokenAirdrop")){const t=Qs(e);if(t?.tokenAirdrop)return this.parseTokenAirdropFromProto(t.tokenAirdrop)}const r=e._tokenTransfers||[];return r.length>0?{tokenTransfers:r.map(e=>({tokenId:e.tokenId?.toString()||"Unknown",transfers:(e.transfers||[]).map(e=>({accountId:e.accountId?.toString()||"Unknown",amount:e.amount?.toString()||"0",serialNumbers:e.serialNumbers?.map(e=>e.toString())}))}))}:null}catch(t){return console.warn("[HTSParser] Failed to parse token airdrop:",t),null}}static parseTokenAirdropFromProto(e){const t=[];if(e.tokenTransfers)for(const i of e.tokenTransfers){const e=i.token?new r.TokenId(i.token.shardNum??0,i.token.realmNum??0,i.token.tokenNum??0):null,n=[];if(i.transfers)for(const t of i.transfers){const e=t.accountID?new r.AccountId(t.accountID.shardNum??0,t.accountID.realmNum??0,t.accountID.accountNum??0):null;n.push({accountId:e?.toString()||"Unknown",amount:t.amount?r.Long.fromValue(t.amount).toString():"0",serialNumbers:t.serialNumbers?.map(e=>r.Long.fromValue(e).toString())})}t.push({tokenId:e?.toString()||"Unknown",transfers:n})}return{tokenTransfers:t}}static extractTokenCreationFromTransaction(e){try{const t=e;if(t._tokenName||t._tokenSymbol){const e={tokenName:t._tokenName||"Unknown Token",tokenSymbol:t._tokenSymbol||"UNKNOWN",initialSupply:t._initialSupply?.toString()||"0",decimals:Number(t._decimals||0),treasuryAccountId:t._treasuryAccountId?.toString()||"Unknown"};return t._maxSupply&&(e.maxSupply=t._maxSupply.toString()),t._tokenType&&(e.tokenType=t._tokenType.toString?t._tokenType.toString():String(t._tokenType)),t._supplyType&&(e.supplyType=t._supplyType.toString?t._supplyType.toString():String(t._supplyType)),t._tokenMemo&&(e.memo=t._tokenMemo),t._adminKey&&(e.adminKey=t._adminKey.toString()),t._kycKey&&(e.kycKey=t._kycKey.toString()),t._freezeKey&&(e.freezeKey=t._freezeKey.toString()),t._wipeKey&&(e.wipeKey=t._wipeKey.toString()),t._supplyKey&&(e.supplyKey=t._supplyKey.toString()),t._feeScheduleKey&&(e.feeScheduleKey=t._feeScheduleKey.toString()),t._pauseKey&&(e.pauseKey=t._pauseKey.toString()),t._metadataKey&&(e.metadataKey=t._metadataKey.toString()),t._autoRenewAccountId&&(e.autoRenewAccount=t._autoRenewAccountId.toString()),t._autoRenewPeriod&&(e.autoRenewPeriod=t._autoRenewPeriod.seconds?.toString()||t._autoRenewPeriod.toString()),t._expirationTime&&(e.expiry=t._expirationTime.seconds?.toString()||t._expirationTime.toString()),t._customFees&&Array.isArray(t._customFees)&&t._customFees.length>0&&(e.customFees=t._customFees.map(e=>{const t={feeCollectorAccountId:e.feeCollectorAccountId?.toString()||"",feeType:"FIXED_FEE"};return e.fixedFee?(t.feeType="FIXED_FEE",t.fixedFee={amount:e.fixedFee.amount?.toString()||"0",denominatingTokenId:e.fixedFee.denominatingTokenId?.toString()}):e.fractionalFee?(t.feeType="FRACTIONAL_FEE",t.fractionalFee={numerator:e.fractionalFee.numerator?.toString()||"0",denominator:e.fractionalFee.denominator?.toString()||"1",minimumAmount:e.fractionalFee.minimumAmount?.toString()||"0",maximumAmount:e.fractionalFee.maximumAmount?.toString()||"0",netOfTransfers:e.fractionalFee.netOfTransfers||!1}):e.royaltyFee&&(t.feeType="ROYALTY_FEE",t.royaltyFee={numerator:e.royaltyFee.numerator?.toString()||"0",denominator:e.royaltyFee.denominator?.toString()||"1",fallbackFee:e.royaltyFee.fallbackFee?{amount:e.royaltyFee.fallbackFee.amount?.toString()||"0",denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?.toString()}:void 0}),t.allCollectorsAreExempt=e.allCollectorsAreExempt||!1,t})),e}return null}catch(t){return null}}static extractTokenAirdropFromTransaction(e){try{const t=e;if(t._tokenAirdrops&&Array.isArray(t._tokenAirdrops)){return{tokenTransfers:t._tokenAirdrops.map(e=>({tokenId:e.tokenId?.toString()||"Unknown",transfers:(e.transfers||[]).map(e=>({accountId:e.accountId?.toString()||"Unknown",amount:e.amount?.toString()||"0",serialNumbers:e.serialNumbers?.map(e=>e.toString())||[]}))}))}}return null}catch(t){return null}}static parseFromTransactionObject(e){try{try{const t=e.toBytes?e.toBytes():void 0;if(t){const e=n.proto.TransactionList.decode(t);if(e.transactionList&&e.transactionList.length>0){const t=e.transactionList[0];let r=null;if(t.bodyBytes&&t.bodyBytes.length>0)r=n.proto.TransactionBody.decode(t.bodyBytes);else if(t.signedTransactionBytes&&t.signedTransactionBytes.length>0){const e=n.proto.SignedTransaction.decode(t.signedTransactionBytes);e.bodyBytes&&(r=n.proto.TransactionBody.decode(e.bodyBytes))}if(r){if(r.tokenCreation){const e=this.parseTokenCreate(r.tokenCreation);if(e)return{type:"TOKENCREATE",humanReadableType:"Token Creation",tokenCreation:e}}if(r.tokenMint){const e=this.parseTokenMint(r.tokenMint);if(e)return{type:"TOKENMINT",humanReadableType:"Token Mint",tokenMint:e}}if(r.tokenBurn){const e=this.parseTokenBurn(r.tokenBurn);if(e)return{type:"TOKENBURN",humanReadableType:"Token Burn",tokenBurn:e}}if(r.tokenUpdate){const e=this.parseTokenUpdate(r.tokenUpdate);if(e)return{type:"TOKENUPDATE",humanReadableType:"Token Update",tokenUpdate:e}}if(r.tokenFreeze){const e=this.parseTokenFreeze(r.tokenFreeze);if(e)return{type:"TOKENFREEZE",humanReadableType:"Token Freeze",tokenFreeze:e}}if(r.tokenUnfreeze){const e=this.parseTokenUnfreeze(r.tokenUnfreeze);if(e)return{type:"TOKENUNFREEZE",humanReadableType:"Token Unfreeze",tokenUnfreeze:e}}if(r.tokenGrantKyc){const e=this.parseTokenGrantKyc(r.tokenGrantKyc);if(e)return{type:"TOKENGRANTKYC",humanReadableType:"Token Grant KYC",tokenGrantKyc:e}}if(r.tokenRevokeKyc){const e=this.parseTokenRevokeKyc(r.tokenRevokeKyc);if(e)return{type:"TOKENREVOKEKYC",humanReadableType:"Token Revoke KYC",tokenRevokeKyc:e}}if(r.tokenPause){const e=this.parseTokenPause(r.tokenPause);if(e)return{type:"TOKENPAUSE",humanReadableType:"Token Pause",tokenPause:e}}if(r.tokenUnpause){const e=this.parseTokenUnpause(r.tokenUnpause);if(e)return{type:"TOKENUNPAUSE",humanReadableType:"Token Unpause",tokenUnpause:e}}if(r.tokenWipe){const e=this.parseTokenWipeAccount(r.tokenWipe);if(e)return{type:"TOKENWIPEACCOUNT",humanReadableType:"Token Wipe Account",tokenWipeAccount:e}}if(r.tokenDeletion){const e=this.parseTokenDelete(r.tokenDeletion);if(e)return{type:"TOKENDELETE",humanReadableType:"Token Delete",tokenDelete:e}}if(r.tokenAssociate){const e=this.parseTokenAssociate(r.tokenAssociate);if(e)return{type:"TOKENASSOCIATE",humanReadableType:"Token Associate",tokenAssociate:e}}if(r.tokenDissociate){const e=this.parseTokenDissociate(r.tokenDissociate);if(e)return{type:"TOKENDISSOCIATE",humanReadableType:"Token Dissociate",tokenDissociate:e}}if(r.tokenFeeScheduleUpdate){const e=this.parseTokenFeeScheduleUpdate(r.tokenFeeScheduleUpdate);if(e)return{type:"TOKENFEESCHEDULEUPDATE",humanReadableType:"Token Fee Schedule Update",tokenFeeScheduleUpdate:e}}if(r.tokenAirdrop){const e=this.parseTokenAirdropFromProto(r.tokenAirdrop);if(e)return{type:"TOKENAIRDROP",humanReadableType:"Token Airdrop",tokenAirdrop:e}}}}}}catch(Pw){}const t=this.parseHTSTransaction(e);if(t.type)return t;const r=this.extractTokenCreationFromTransaction(e),i=this.extractTokenAirdropFromTransaction(e);return r?{type:"TOKENCREATE",humanReadableType:"Token Creation",tokenCreation:r}:i?{type:"TOKENAIRDROP",humanReadableType:"Token Airdrop",tokenAirdrop:i}:{}}catch(t){return{}}}}class ra{static parseConsensusCreateTopic(e){if(!e)return;const t={};return e.memo&&(t.memo=e.memo),t.adminKey=Zs(e.adminKey),t.submitKey=Zs(e.submitKey),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new r.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),t}static parseConsensusSubmitMessage(e){if(!e)return;const t={};if(e.topicID&&(t.topicId=`${e.topicID.shardNum??0}.${e.topicID.realmNum??0}.${e.topicID.topicNum??0}`),e.message?.length>0){const r=o.Buffer.from(e.message),i=r.toString("utf8");/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(i)||i.includes("�")?(t.message=r.toString("base64"),t.messageEncoding="base64"):(t.message=i,t.messageEncoding="utf8")}if(e.chunkInfo){if(e.chunkInfo.initialTransactionID){const r=e.chunkInfo.initialTransactionID.accountID,i=e.chunkInfo.initialTransactionID.transactionValidStart;r&&i&&(t.chunkInfoInitialTransactionID=`${r.shardNum??0}.${r.realmNum??0}.${r.accountNum??0}@${i.seconds??0}.${i.nanos??0}`)}void 0!==e.chunkInfo.number&&null!==e.chunkInfo.number&&(t.chunkInfoNumber=e.chunkInfo.number),void 0!==e.chunkInfo.total&&null!==e.chunkInfo.total&&(t.chunkInfoTotal=e.chunkInfo.total)}return t}static parseConsensusUpdateTopic(e){if(!e)return;const t={};return e.topicID&&(t.topicId=`${e.topicID.shardNum}.${e.topicID.realmNum}.${e.topicID.topicNum}`),void 0!==e.memo?.value&&(t.memo=e.memo.value),null===e.adminKey?(t.clearAdminKey=!0,t.adminKey=void 0):e.adminKey?t.adminKey=Zs(e.adminKey):t.adminKey=void 0,null===e.submitKey?(t.clearSubmitKey=!0,t.submitKey=void 0):e.submitKey?t.submitKey=Zs(e.submitKey):t.submitKey=void 0,e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new r.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),t}static parseConsensusDeleteTopic(e){if(!e)return;const t={};return e.topicID&&(t.topicId=`${e.topicID.shardNum}.${e.topicID.realmNum??0}.${e.topicID.topicNum??0}`),t}static parseFromTransactionObject(e){try{const t=e._transactionBody;if(!t)return{};if(t.consensusCreateTopic){const e=this.parseConsensusCreateTopic(t.consensusCreateTopic);if(e)return{type:"TOPICCREATE",humanReadableType:"Topic Create",consensusCreateTopic:e}}if(t.consensusSubmitMessage){const e=this.parseConsensusSubmitMessage(t.consensusSubmitMessage);if(e)return{type:"CONSENSUSSUBMITMESSAGE",humanReadableType:"Submit Message",consensusSubmitMessage:e}}if(t.consensusUpdateTopic){const e=this.parseConsensusUpdateTopic(t.consensusUpdateTopic);if(e)return{type:"TOPICUPDATE",humanReadableType:"Topic Update",consensusUpdateTopic:e}}if(t.consensusDeleteTopic){const e=this.parseConsensusDeleteTopic(t.consensusDeleteTopic);if(e)return{type:"TOPICDELETE",humanReadableType:"Topic Delete",consensusDeleteTopic:e}}return{}}catch(t){return{}}}}class ia{static parseFileTransaction(e,t){try{if(t||e.toBytes)try{const r=t||e.toBytes(),i=n.proto.TransactionList.decode(r);if(i.transactionList&&i.transactionList.length>0){const e=i.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=n.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const r=n.proto.SignedTransaction.decode(e.signedTransactionBytes);r.bodyBytes&&(t=n.proto.TransactionBody.decode(r.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(r){}return this.parseFromTransactionInternals(e)}catch(i){return{type:"UNKNOWN",humanReadableType:"Unknown File Transaction"}}}static parseFromProtobufTxBody(e){if(e.fileCreate){const t=this.parseFileCreate(e.fileCreate);if(t)return{type:"FILECREATE",humanReadableType:"File Create",fileCreate:t}}if(e.fileAppend){const t=this.parseFileAppend(e.fileAppend);if(t)return{type:"FILEAPPEND",humanReadableType:"File Append",fileAppend:t}}if(e.fileUpdate){const t=this.parseFileUpdate(e.fileUpdate);if(t)return{type:"FILEUPDATE",humanReadableType:"File Update",fileUpdate:t}}if(e.fileDelete){const t=this.parseFileDelete(e.fileDelete);if(t)return{type:"FILEDELETE",humanReadableType:"File Delete",fileDelete:t}}return{}}static parseFromTransactionInternals(e){try{const t=e;if(ea(e,"fileCreate")){const e={};if(t._contents){const r=this.analyzeContent(t._contents);e.contents=r.encoded,r.contentType&&(e.contentType=r.contentType),r.size&&(e.contentSize=r.size)}if(t._keys&&t._keys.length>0){const r={keys:t._keys};e.keys=Zs({keyList:r})}return t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),t._memo&&(e.memo=t._memo),{type:"FILECREATE",humanReadableType:"File Create",fileCreate:e}}if(ea(e,"fileAppend")){const e={fileId:t._fileId.toString()};if(t._contents){const r=this.analyzeContent(t._contents);e.contents=r.encoded,r.size&&(e.contentSize=r.size)}return{type:"FILEAPPEND",humanReadableType:"File Append",fileAppend:e}}if(ea(e,"fileUpdate")){const e={fileId:t._fileId.toString()};if(t._contents){const r=this.analyzeContent(t._contents);e.contents=r.encoded,r.size&&(e.contentSize=r.size)}if(t._keys&&t._keys.length>0){const r={keys:t._keys};e.keys=Zs({keyList:r})}return t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),t._memo&&(e.memo=t._memo),{type:"FILEUPDATE",humanReadableType:"File Update",fileUpdate:e}}if(ea(e,"fileDelete")){return{type:"FILEDELETE",humanReadableType:"File Delete",fileDelete:{fileId:t._fileId.toString()}}}return{}}catch(t){return{}}}static analyzeContent(e){const t=e.length,r=o.Buffer.from(e);let i,n;if(t>=4){i={"89504e47":"image/png",ffd8ffe0:"image/jpeg",ffd8ffe1:"image/jpeg",47494638:"image/gif",25504446:"application/pdf","504b0304":"application/zip","7f454c46":"application/x-executable",d0cf11e0:"application/msoffice"}[r.subarray(0,4).toString("hex").toLowerCase()]}if(!i)try{const e=r.toString("utf8"),t=/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(e),n=e.includes("�");i=t||n?"application/octet-stream":e.trim().startsWith("{")&&e.trim().endsWith("}")?"application/json":e.includes("<?xml")||e.includes("<html")?"text/xml":e.includes("<!DOCTYPE html")?"text/html":"text/plain"}catch{i="application/octet-stream"}if(i?.startsWith("text/")||"application/json"===i)try{n=r.toString("utf8"),(n.includes("�")||/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(n))&&(n=r.toString("base64"))}catch{n=r.toString("base64")}else n=r.toString("base64");return{encoded:n,contentType:i,size:t}}static parseFileCreate(e){if(!e)return;const t={};return e.expirationTime?.seconds&&(t.expirationTime=`${r.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=Zs({keyList:e.keys})),e.contents&&(t.contents=o.Buffer.from(e.contents).toString("base64")),e.memo&&(t.memo=e.memo),t}static parseFileAppend(e){if(!e)return;const t={};return e.fileID&&(t.fileId=`${e.fileID.shardNum??0}.${e.fileID.realmNum??0}.${e.fileID.fileNum??0}`),e.contents&&(t.contents=o.Buffer.from(e.contents).toString("base64")),t}static parseFileUpdate(e){if(!e)return;const t={};return e.fileID&&(t.fileId=`${e.fileID.shardNum??0}.${e.fileID.realmNum??0}.${e.fileID.fileNum??0}`),e.expirationTime?.seconds&&(t.expirationTime=`${r.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=Zs({keyList:e.keys})),e.contents&&(t.contents=o.Buffer.from(e.contents).toString("base64")),void 0!==e.memo?.value&&(t.memo=e.memo.value),t}static parseFileDelete(e){if(!e)return;const t={};return e.fileID&&(t.fileId=`${e.fileID.shardNum??0}.${e.fileID.realmNum??0}.${e.fileID.fileNum??0}`),t}static parseFromTransactionObject(e){return this.parseFileTransaction(e)}}class na{static parseCryptoTransfers(e,t){if(e.transfers?.accountAmounts&&(t.transfers=e.transfers.accountAmounts.map(e=>{const t=new r.AccountId(e.accountID.shardNum??0,e.accountID.realmNum??0,e.accountID.accountNum??0),i=r.Hbar.fromTinybars(r.Long.fromValue(e.amount));return{accountId:t.toString(),amount:i.toString(r.HbarUnit.Hbar),isDecimal:!0}})),e.tokenTransfers)for(const i of e.tokenTransfers){const e=new r.TokenId(i.token.shardNum??0,i.token.realmNum??0,i.token.tokenNum??0);if(i.transfers)for(const n of i.transfers){const i=new r.AccountId(n.accountID.shardNum??0,n.accountID.realmNum??0,n.accountID.accountNum??0),o=r.Long.fromValue(n.amount).toNumber();t.tokenTransfers.push({tokenId:e.toString(),accountId:i.toString(),amount:o})}}}static parseCryptoDelete(e){if(!e)return;const t={};return e.deleteAccountID&&(t.deleteAccountId=new r.AccountId(e.deleteAccountID.shardNum??0,e.deleteAccountID.realmNum??0,e.deleteAccountID.accountNum??0).toString()),e.transferAccountID&&(t.transferAccountId=new r.AccountId(e.transferAccountID.shardNum??0,e.transferAccountID.realmNum??0,e.transferAccountID.accountNum??0).toString()),t}static parseCryptoCreateAccount(e){if(!e)return;const t={};return e.initialBalance&&(t.initialBalance=r.Hbar.fromTinybars(r.Long.fromValue(e.initialBalance)).toString(r.HbarUnit.Hbar)),e.key&&(t.key=Zs(e.key)),void 0!==e.receiverSigRequired&&(t.receiverSigRequired=e.receiverSigRequired),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.memo&&(t.memo=e.memo),void 0!==e.maxAutomaticTokenAssociations&&(t.maxAutomaticTokenAssociations=e.maxAutomaticTokenAssociations),e.stakedAccountId?t.stakedAccountId=new r.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=r.Long.fromValue(e.stakedNodeId).toString()),void 0!==e.declineReward&&(t.declineReward=e.declineReward),e.alias&&e.alias.length>0&&(t.alias=globalThis.Buffer.from(e.alias).toString("hex")),t}static parseCryptoUpdateAccount(e){if(!e)return;const t={};return e.accountIDToUpdate&&(t.accountIdToUpdate=new r.AccountId(e.accountIDToUpdate.shardNum??0,e.accountIDToUpdate.realmNum??0,e.accountIDToUpdate.accountNum??0).toString()),e.key&&(t.key=Zs(e.key)),e.expirationTime?.seconds&&(t.expirationTime=`${r.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),null!==e.receiverSigRequired&&void 0!==e.receiverSigRequired&&(t.receiverSigRequired=Boolean(e.receiverSigRequired)),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),void 0!==e.memo?.value&&(t.memo=e.memo.value),void 0!==e.maxAutomaticTokenAssociations?.value&&(t.maxAutomaticTokenAssociations=e.maxAutomaticTokenAssociations.value),e.stakedAccountId?(t.stakedAccountId=new r.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString(),t.stakedNodeId=void 0):null!==e.stakedNodeId&&void 0!==e.stakedNodeId?(t.stakedNodeId=r.Long.fromValue(e.stakedNodeId).toString(),t.stakedAccountId=void 0):(t.stakedAccountId=void 0,t.stakedNodeId=void 0),null!==e.declineReward&&void 0!==e.declineReward&&(t.declineReward=Boolean(e.declineReward)),t}static parseCryptoApproveAllowance(e){if(!e)return;const t={};return e.cryptoAllowances&&e.cryptoAllowances.length>0&&(t.hbarAllowances=e.cryptoAllowances.map(e=>({ownerAccountId:new r.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new r.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount:r.Hbar.fromTinybars(r.Long.fromValue(e.amount)).toString(r.HbarUnit.Hbar)}))),e.tokenAllowances&&e.tokenAllowances.length>0&&(t.tokenAllowances=e.tokenAllowances.map(e=>({tokenId:new r.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),ownerAccountId:new r.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new r.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount:r.Long.fromValue(e.amount).toString()}))),e.nftAllowances&&e.nftAllowances.length>0&&(t.nftAllowances=e.nftAllowances.map(e=>{const t={};return e.tokenId&&(t.tokenId=new r.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString()),e.owner&&(t.ownerAccountId=new r.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString()),e.spender&&(t.spenderAccountId=new r.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString()),e.serialNumbers&&e.serialNumbers.length>0&&(t.serialNumbers=e.serialNumbers.map(e=>r.Long.fromValue(e).toString())),void 0!==e.approvedForAll?.value&&(t.approvedForAll=e.approvedForAll.value),e.delegatingSpender&&(t.delegatingSpender=new r.AccountId(e.delegatingSpender.shardNum??0,e.delegatingSpender.realmNum??0,e.delegatingSpender.accountNum??0).toString()),t})),t}static parseCryptoDeleteAllowance(e){if(!e)return;const t={};return e.nftAllowances&&e.nftAllowances.length>0&&(t.nftAllowancesToRemove=e.nftAllowances.map(e=>({ownerAccountId:new r.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),tokenId:new r.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),serialNumbers:e.serialNumbers?e.serialNumbers.map(e=>r.Long.fromValue(e).toString()):[]}))),t}static extractHbarTransfersFromTransaction(e){const t=[];try{const r=e._hbarTransfers;Array.isArray(r)&&r.forEach(e=>{if(e.accountId&&e.amount){const r=e.amount.toTinybars(),i=Number(r)/1e8;t.push({accountId:e.accountId.toString(),amount:i})}})}catch(r){}return t}static extractTokenTransfersFromTransaction(e){const t=[];try{const r=e._tokenTransfers;Array.isArray(r)&&r.forEach(e=>{if(e.tokenId&&Array.isArray(e.transfers)){const r=e.transfers.map(e=>({accountId:e.accountId?.toString()||"Unknown",amount:Number(e.amount||0)}));t.push({tokenId:e.tokenId.toString(),transfers:r})}})}catch(r){}return t}static parseFromTransactionObject(e){try{const t=this.extractHbarTransfersFromTransaction(e),r=this.extractTokenTransfersFromTransaction(e);if(t.length>0||r.length>0){const e=t.map(e=>({accountId:e.accountId,amount:e.amount.toString()+" ℏ",isDecimal:!0})),i=r.flatMap(e=>e.transfers.map(t=>({tokenId:e.tokenId,accountId:t.accountId,amount:t.amount})));if(t.length>0)return{type:"CRYPTOTRANSFER",humanReadableType:"Crypto Transfer",transfers:e,tokenTransfers:i};if(r.length>0)return{type:"TOKENTRANSFER",humanReadableType:"Token Transfer",transfers:e,tokenTransfers:i}}return{}}catch(t){return{}}}}class oa{static parseSCSTransaction(e,t){try{if(t||e.toBytes)try{const r=t||e.toBytes(),i=n.proto.TransactionList.decode(r);if(i.transactionList&&i.transactionList.length>0){const e=i.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=n.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const r=n.proto.SignedTransaction.decode(e.signedTransactionBytes);r.bodyBytes&&(t=n.proto.TransactionBody.decode(r.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(r){}return this.parseFromTransactionInternals(e)}catch(i){return{type:"UNKNOWN",humanReadableType:"Unknown Contract Transaction"}}}static parseFromProtobufTxBody(e){if(e.contractCall){const t=this.parseContractCall(e.contractCall);if(t)return{type:"CONTRACTCALL",humanReadableType:"Contract Call",contractCall:t}}if(e.contractCreateInstance){const t=this.parseContractCreate(e.contractCreateInstance);if(t)return{type:"CONTRACTCREATE",humanReadableType:"Contract Create",contractCreate:t}}if(e.contractUpdateInstance){const t=this.parseContractUpdate(e.contractUpdateInstance);if(t)return{type:"CONTRACTUPDATE",humanReadableType:"Contract Update",contractUpdate:t}}if(e.contractDeleteInstance){const t=this.parseContractDelete(e.contractDeleteInstance);if(t)return{type:"CONTRACTDELETE",humanReadableType:"Contract Delete",contractDelete:t}}if(e.ethereumTransaction){const t=this.parseEthereumTransaction(e.ethereumTransaction);if(t)return{type:"ETHEREUMTRANSACTION",humanReadableType:"Ethereum Transaction",ethereumTransaction:t}}return{}}static parseFromTransactionInternals(e){try{const t=e;if(t._contractId&&t._gas){const e={contractId:t._contractId.toString(),gas:"number"==typeof t._gas?t._gas:r.Long.fromValue(t._gas).toNumber(),amount:t._amount?parseFloat(t._amount.toString()):0};if(t._functionParameters){const r=o.Buffer.from(t._functionParameters).toString("hex");e.functionParameters=r,e.functionName=this.extractFunctionName(r)}return{type:"CONTRACTCALL",humanReadableType:"Contract Call",contractCall:e}}if(ea(e,"contractCreateInstance")){const e={gas:t._gas.toString(),initialBalance:t._initialBalance?.toString()||"0"};return t._fileId?(e.initcodeSource="fileID",e.initcode=t._fileId.toString()):t._bytecode&&(e.initcodeSource="bytes",e.initcode=o.Buffer.from(t._bytecode).toString("hex")),t._constructorParameters&&(e.constructorParameters=o.Buffer.from(t._constructorParameters).toString("hex")),t._memo&&(e.memo=t._memo),t._adminKey&&(e.adminKey=Zs(t._adminKey)),void 0!==t._maxAutomaticTokenAssociations&&(e.maxAutomaticTokenAssociations=t._maxAutomaticTokenAssociations),t._stakedAccountId?e.stakedAccountId=t._stakedAccountId.toString():null!==t._stakedNodeId&&void 0!==t._stakedNodeId&&(e.stakedNodeId=r.Long.fromValue(t._stakedNodeId).toString()),void 0!==t._declineReward&&(e.declineReward=t._declineReward),t._autoRenewPeriod&&(e.autoRenewPeriod=t._autoRenewPeriod.toString()),{type:"CONTRACTCREATE",humanReadableType:"Contract Create",contractCreate:e}}if(ea(e,"contractUpdateInstance")){const e={contractIdToUpdate:t._contractId.toString()};return t._memo&&(e.memo=t._memo),t._adminKey&&(e.adminKey=Zs(t._adminKey)),void 0!==t._maxAutomaticTokenAssociations&&(e.maxAutomaticTokenAssociations=t._maxAutomaticTokenAssociations),t._stakedAccountId?e.stakedAccountId=t._stakedAccountId.toString():null!==t._stakedNodeId&&void 0!==t._stakedNodeId&&(e.stakedNodeId=r.Long.fromValue(t._stakedNodeId).toString()),void 0!==t._declineReward&&(e.declineReward=t._declineReward),t._autoRenewPeriod&&(e.autoRenewPeriod=t._autoRenewPeriod.toString()),{type:"CONTRACTUPDATE",humanReadableType:"Contract Update",contractUpdate:e}}if(ea(e,"contractDeleteInstance")){const e={contractIdToDelete:t._contractId.toString()};return t._transferAccountId?e.transferAccountId=t._transferAccountId.toString():t._transferContractId&&(e.transferContractId=t._transferContractId.toString()),{type:"CONTRACTDELETE",humanReadableType:"Contract Delete",contractDelete:e}}return{}}catch(t){return{}}}static extractFunctionName(e){if(e.length<8)return"unknown";const t=e.substring(0,8);return{a9059cbb:"transfer","095ea7b3":"approve","23b872dd":"transferFrom","70a08231":"balanceOf",dd62ed3e:"allowance","18160ddd":"totalSupply","06fdde03":"name","95d89b41":"symbol","313ce567":"decimals","42842e0e":"safeTransferFrom",b88d4fde:"safeTransferFrom",e985e9c5:"isApprovedForAll",a22cb465:"setApprovalForAll","6352211e":"ownerOf",c87b56dd:"tokenURI","01ffc9a7":"supportsInterface","40c10f19":"mint","42966c68":"burn",f2fde38b:"transferOwnership","715018a6":"renounceOwnership","8da5cb5b":"owner"}[t]||t}static parseEthereumTransaction(e){if(!e)return;const t={contractId:"EVM",gas:e.maxGasAllowance?r.Long.fromValue(e.maxGasAllowance).toNumber():0,amount:0};if(e.ethereumData&&e.ethereumData.length>0){const r=o.Buffer.from(e.ethereumData).toString("hex");t.functionParameters=r,r.length>=8&&(t.functionName=this.extractFunctionName(r))}return t}static parseContractCall(e){if(!e)return;const t=r.Hbar.fromTinybars(r.Long.fromValue(e.amount??0)),i={contractId:new r.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString(),gas:r.Long.fromValue(e.gas??0).toNumber(),amount:parseFloat(t.toString(r.HbarUnit.Hbar))};return e.functionParameters&&(i.functionParameters=o.Buffer.from(e.functionParameters).toString("hex"),i.functionParameters.length>=8&&(i.functionName=this.extractFunctionName(i.functionParameters))),i}static parseContractCreate(e){if(!e)return;const t={};return e.initialBalance&&(t.initialBalance=r.Hbar.fromTinybars(r.Long.fromValue(e.initialBalance)).toString(r.HbarUnit.Hbar)),e.gas&&(t.gas=r.Long.fromValue(e.gas).toString()),e.adminKey&&(t.adminKey=Zs(e.adminKey)),e.constructorParameters&&(t.constructorParameters=o.Buffer.from(e.constructorParameters).toString("hex")),e.memo&&(t.memo=e.memo),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.stakedAccountId?t.stakedAccountId=new r.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=r.Long.fromValue(e.stakedNodeId).toString()),void 0!==e.declineReward&&(t.declineReward=e.declineReward),void 0!==e.maxAutomaticTokenAssociations&&(t.maxAutomaticTokenAssociations=e.maxAutomaticTokenAssociations),e.fileID?(t.initcodeSource="fileID",t.initcode=new r.FileId(e.fileID.shardNum??0,e.fileID.realmNum??0,e.fileID.fileNum??0).toString()):e.initcode&&e.initcode.length>0&&(t.initcodeSource="bytes",t.initcode=o.Buffer.from(e.initcode).toString("hex")),t}static parseContractUpdate(e){if(!e)return;const t={};if(e.contractID&&(t.contractIdToUpdate=new r.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.adminKey&&(t.adminKey=Zs(e.adminKey)),e.expirationTime?.seconds&&(t.expirationTime=`${r.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.memo){const r=e.memo;if(r&&"object"==typeof r&&Object.prototype.hasOwnProperty.call(r,"value")){const e=r.value;t.memo=null==e?void 0:String(e)}else t.memo="string"==typeof r?r:void 0}else t.memo=void 0;return e.stakedAccountId?(t.stakedAccountId=new r.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString(),t.stakedNodeId=void 0):null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&r.Long.fromValue(e.stakedNodeId).notEquals(-1)?(t.stakedNodeId=r.Long.fromValue(e.stakedNodeId).toString(),t.stakedAccountId=void 0):(t.stakedNodeId=void 0,t.stakedAccountId=void 0),void 0!==e.declineReward?.value&&(t.declineReward=e.declineReward.value),void 0!==e.maxAutomaticTokenAssociations?.value&&(t.maxAutomaticTokenAssociations=e.maxAutomaticTokenAssociations.value),e.autoRenewAccountId&&(t.autoRenewAccountId=new r.AccountId(e.autoRenewAccountId.shardNum??0,e.autoRenewAccountId.realmNum??0,e.autoRenewAccountId.accountNum??0).toString()),t}static parseContractDelete(e){if(!e)return;const t={};return e.contractID&&(t.contractIdToDelete=new r.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.transferAccountID?t.transferAccountId=new r.AccountId(e.transferAccountID.shardNum??0,e.transferAccountID.realmNum??0,e.transferAccountID.accountNum??0).toString():e.transferContractID&&(t.transferContractId=new r.ContractId(e.transferContractID.shardNum??0,e.transferContractID.realmNum??0,e.transferContractID.contractNum??0).toString()),t}static parseFromTransactionObject(e){return this.parseSCSTransaction(e)}}class sa{static parseUtilTransaction(e,t){try{if(t||e.toBytes)try{const r=t||e.toBytes(),i=n.proto.TransactionList.decode(r);if(i.transactionList&&i.transactionList.length>0){const e=i.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=n.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const r=n.proto.SignedTransaction.decode(e.signedTransactionBytes);r.bodyBytes&&(t=n.proto.TransactionBody.decode(r.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(r){}return this.parseFromTransactionInternals(e)}catch(i){return{type:"UNKNOWN",humanReadableType:"Unknown Utility Transaction"}}}static parseFromProtobufTxBody(e){if(e.utilPrng){const t=this.parseUtilPrng(e.utilPrng);if(t)return{type:"PRNG",humanReadableType:"Pseudo Random Number",utilPrng:t}}if(e.freeze){const t=this.parseNetworkFreezeFromProto(e.freeze);if(t)return{type:"FREEZE",humanReadableType:"Network Freeze",freeze:t}}if(e.systemDelete){const t=this.parseSystemDeleteFromProto(e.systemDelete);if(t)return{type:"SYSTEMDELETE",humanReadableType:"System Delete",systemDelete:t}}if(e.systemUndelete){const t=this.parseSystemUndeleteFromProto(e.systemUndelete);if(t)return{type:"SYSTEMUNDELETE",humanReadableType:"System Undelete",systemUndelete:t}}if(e.nodeCreate){const t=this.parseNodeCreateFromProto(e.nodeCreate);if(t)return{type:"NODECREATE",humanReadableType:"Node Create",nodeCreate:t}}if(e.nodeUpdate){const t=this.parseNodeUpdateFromProto(e.nodeUpdate);if(t)return{type:"NODEUPDATE",humanReadableType:"Node Update",nodeUpdate:t}}if(e.nodeDelete){const t=this.parseNodeDeleteFromProto(e.nodeDelete);if(t)return{type:"NODEDELETE",humanReadableType:"Node Delete",nodeDelete:t}}return{}}static parseFromTransactionInternals(e){try{const t=e;if(ea(e,"utilPrng")){const e={};return t._range&&0!==t._range&&(e.range=t._range),{type:"PRNG",humanReadableType:"Pseudo Random Number",utilPrng:e}}if(ea(e,"freeze")){const e={};return t._startTime&&(e.startTime=t._startTime.toString()),t._endTime&&(e.endTime=t._endTime.toString()),t._updateFile&&(e.updateFile=t._updateFile.toString()),t._fileHash&&(e.fileHash=globalThis.Buffer.from(t._fileHash).toString("hex")),t._freezeType&&(e.freezeType=t._freezeType),{type:"FREEZE",humanReadableType:"Network Freeze",freeze:e}}if(ea(e,"systemDelete")){const e={};return t._fileId?e.fileId=t._fileId.toString():t._contractId&&(e.contractId=t._contractId.toString()),t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),{type:"SYSTEMDELETE",humanReadableType:"System Delete",systemDelete:e}}if(ea(e,"systemUndelete")){const e={};return t._fileId?e.fileId=t._fileId.toString():t._contractId&&(e.contractId=t._contractId.toString()),{type:"SYSTEMUNDELETE",humanReadableType:"System Undelete",systemUndelete:e}}return{}}catch(t){return{}}}static parseNetworkFreezeFromProto(e){if(!e)return;const t={};if(e.startTime?.seconds&&(t.startTime=`${r.Long.fromValue(e.startTime.seconds).toString()}.${e.startTime.nanos??0}`),e.updateFile&&(t.updateFile=new r.FileId(e.updateFile.shardNum??0,e.updateFile.realmNum??0,e.updateFile.fileNum??0).toString()),e.fileHash&&e.fileHash.length>0&&(t.fileHash=globalThis.Buffer.from(e.fileHash).toString("hex")),void 0!==e.freezeType){const r=["FREEZE_ONLY","PREPARE_UPGRADE","FREEZE_UPGRADE","FREEZE_ABORT"];t.freezeType=r[e.freezeType]||"FREEZE_ONLY"}return t}static parseSystemDeleteFromProto(e){if(!e)return;const t={};return e.fileID?t.fileId=new r.FileId(e.fileID.shardNum??0,e.fileID.realmNum??0,e.fileID.fileNum??0).toString():e.contractID&&(t.contractId=new r.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.expirationTime?.seconds&&(t.expirationTime=r.Long.fromValue(e.expirationTime.seconds).toString()),t}static parseSystemUndeleteFromProto(e){if(!e)return;const t={};return e.fileID?t.fileId=new r.FileId(e.fileID.shardNum??0,e.fileID.realmNum??0,e.fileID.fileNum??0).toString():e.contractID&&(t.contractId=new r.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),t}static parseNodeCreateFromProto(e){if(!e)return;const t={};return void 0!==e.nodeId&&(t.nodeId=r.Long.fromValue(e.nodeId).toNumber()),t}static parseNodeUpdateFromProto(e){if(!e)return;const t={};return void 0!==e.nodeId&&(t.nodeId=r.Long.fromValue(e.nodeId).toNumber()),t}static parseNodeDeleteFromProto(e){if(!e)return;const t={};return void 0!==e.nodeId&&(t.nodeId=r.Long.fromValue(e.nodeId).toNumber()),t}static parseUtilPrng(e){if(!e)return;const t={};return e.range&&0!==e.range&&(t.range=e.range),t}static parseFreeze(e){return this.parseNetworkFreezeFromProto(e)}static parseFromTransactionObject(e){return this.parseUtilTransaction(e)}}class aa{static parseScheduleTransaction(e,t){try{if(t||e.toBytes)try{const r=t||e.toBytes(),i=n.proto.TransactionList.decode(r);if(i.transactionList&&i.transactionList.length>0){const e=i.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=n.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const r=n.proto.SignedTransaction.decode(e.signedTransactionBytes);r.bodyBytes&&(t=n.proto.TransactionBody.decode(r.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(r){}return this.parseFromTransactionInternals(e)}catch(i){return{type:"UNKNOWN",humanReadableType:"Unknown Schedule Transaction"}}}static parseFromProtobufTxBody(e){if(e.scheduleCreate){const t=this.parseScheduleCreateFromProto(e.scheduleCreate);if(t)return{type:"SCHEDULECREATE",humanReadableType:"Schedule Create",scheduleCreate:t}}if(e.scheduleSign){const t=this.parseScheduleSignFromProto(e.scheduleSign);if(t)return{type:"SCHEDULESIGN",humanReadableType:"Schedule Sign",scheduleSign:t}}if(e.scheduleDelete){const t=this.parseScheduleDeleteFromProto(e.scheduleDelete);if(t)return{type:"SCHEDULEDELETE",humanReadableType:"Schedule Delete",scheduleDelete:t}}return{}}static parseFromTransactionInternals(e){try{const t=e;if(ea(e,"scheduleCreate")){return{type:"SCHEDULECREATE",humanReadableType:"Schedule Create",scheduleCreate:{scheduledTransactionBody:globalThis.Buffer.from(t._scheduledTransaction).toString("base64"),memo:t._scheduleMemo,adminKey:t._adminKey?Zs(t._adminKey):void 0,payerAccountId:t._payerAccountId?.toString(),expirationTime:t._expirationTime?.toString(),waitForExpiry:t._waitForExpiry||!1}}}if(ea(e,"scheduleSign")){return{type:"SCHEDULESIGN",humanReadableType:"Schedule Sign",scheduleSign:{scheduleId:t._scheduleId.toString()}}}if(ea(e,"scheduleDelete")){return{type:"SCHEDULEDELETE",humanReadableType:"Schedule Delete",scheduleDelete:{scheduleId:t._scheduleId.toString()}}}return{}}catch(t){return{}}}static parseScheduleCreateFromProto(e){if(!e)return;const t={};if(e.scheduledTransactionBody){const r=n.proto.SchedulableTransactionBody.encode(n.proto.SchedulableTransactionBody.create(e.scheduledTransactionBody)).finish();t.scheduledTransactionBody=globalThis.Buffer.from(r).toString("base64")}return e.memo&&(t.memo=e.memo),e.adminKey&&(t.adminKey=Zs(e.adminKey)),e.payerAccountID&&(t.payerAccountId=new r.AccountId(e.payerAccountID.shardNum??0,e.payerAccountID.realmNum??0,e.payerAccountID.accountNum??0).toString()),e.expirationTime?.seconds&&(t.expirationTime=`${r.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos??0}`),void 0!==e.waitForExpiry&&(t.waitForExpiry=e.waitForExpiry),t}static parseScheduleSignFromProto(e){if(!e)return;const t={};return e.scheduleID&&(t.scheduleId=new r.ScheduleId(e.scheduleID.shardNum??0,e.scheduleID.realmNum??0,e.scheduleID.scheduleNum??0).toString()),t}static parseScheduleDeleteFromProto(e){if(!e)return;const t={};return e.scheduleID&&(t.scheduleId=new r.ScheduleId(e.scheduleID.shardNum??0,e.scheduleID.realmNum??0,e.scheduleID.scheduleNum??0).toString()),t}static parseScheduleCreate(e){try{return this.parseScheduleTransaction(e).scheduleCreate||null}catch(t){return console.warn("[ScheduleParser] Failed to parse schedule create:",t),null}}static parseScheduleSign(e){try{return this.parseScheduleTransaction(e).scheduleSign||null}catch(t){return console.warn("[ScheduleParser] Failed to parse schedule sign:",t),null}}static parseScheduleDelete(e){try{return this.parseScheduleTransaction(e).scheduleDelete||null}catch(t){return console.warn("[ScheduleParser] Failed to parse schedule delete:",t),null}}static extractScheduleInfo(e){try{const t=e._transactionBody;if(t?.scheduleRef)return{isScheduled:!0,scheduleRef:t.scheduleRef.toString()};const r=e;return r._scheduleId||r.scheduleId?{isScheduled:!0,scheduleRef:(r._scheduleId||r.scheduleId)?.toString()}:{isScheduled:!1}}catch(t){return{isScheduled:!1}}}static parseScheduledTransactionBody(e){try{let t;if(e.startsWith("0x")){const r=e.slice(2);t=new Uint8Array(globalThis.Buffer.from(r,"hex"))}else t=new Uint8Array(globalThis.Buffer.from(e,"base64"));const r=n.proto.SchedulableTransactionBody.decode(t),i=Object.keys(r).find(e=>null!==r[e]&&"transactionFee"!==e&&"memo"!==e);return i?{type:i.toUpperCase(),body:r[i],memo:r.memo,transactionFee:r.transactionFee?.toString()}:null}catch(t){return console.warn("[ScheduleParser] Failed to parse scheduled transaction body:",t),null}}static parseFromTransactionObject(e){return this.parseScheduleTransaction(e)}}const ca={TOKENCREATE:{bodyField:"tokenCreation",parser:ta.parseTokenCreate,resultField:"tokenCreation"},TOKENMINT:{bodyField:"tokenMint",parser:ta.parseTokenMint,resultField:"tokenMint"},TOKENBURN:{bodyField:"tokenBurn",parser:ta.parseTokenBurn,resultField:"tokenBurn"},TOKENUPDATE:{bodyField:"tokenUpdate",parser:ta.parseTokenUpdate,resultField:"tokenUpdate"},TOKENDELETE:{bodyField:"tokenDeletion",parser:ta.parseTokenDelete,resultField:"tokenDelete"},TOKENASSOCIATE:{bodyField:"tokenAssociate",parser:ta.parseTokenAssociate,resultField:"tokenAssociate"},TOKENDISSOCIATE:{bodyField:"tokenDissociate",parser:ta.parseTokenDissociate,resultField:"tokenDissociate"},TOKENFREEZE:{bodyField:"tokenFreeze",parser:ta.parseTokenFreeze,resultField:"tokenFreeze"},TOKENUNFREEZE:{bodyField:"tokenUnfreeze",parser:ta.parseTokenUnfreeze,resultField:"tokenUnfreeze"},TOKENGRANTKYC:{bodyField:"tokenGrantKyc",parser:ta.parseTokenGrantKyc,resultField:"tokenGrantKyc"},TOKENREVOKEKYC:{bodyField:"tokenRevokeKyc",parser:ta.parseTokenRevokeKyc,resultField:"tokenRevokeKyc"},TOKENPAUSE:{bodyField:"tokenPause",parser:ta.parseTokenPause,resultField:"tokenPause"},TOKENUNPAUSE:{bodyField:"tokenUnpause",parser:ta.parseTokenUnpause,resultField:"tokenUnpause"},TOKENWIPEACCOUNT:{bodyField:"tokenWipe",parser:ta.parseTokenWipeAccount,resultField:"tokenWipeAccount"},TOKENFEESCHEDULEUPDATE:{bodyField:"tokenFeeScheduleUpdate",parser:ta.parseTokenFeeScheduleUpdate,resultField:"tokenFeeScheduleUpdate"},TOKENAIRDROP:{bodyField:"tokenAirdrop",parser:ta.parseTokenAirdropFromProto,resultField:"tokenAirdrop"},TOPICCREATE:{bodyField:"consensusCreateTopic",parser:ra.parseConsensusCreateTopic,resultField:"consensusCreateTopic"},CONSENSUSSUBMITMESSAGE:{bodyField:"consensusSubmitMessage",parser:ra.parseConsensusSubmitMessage,resultField:"consensusSubmitMessage"},TOPICUPDATE:{bodyField:"consensusUpdateTopic",parser:ra.parseConsensusUpdateTopic,resultField:"consensusUpdateTopic"},TOPICDELETE:{bodyField:"consensusDeleteTopic",parser:ra.parseConsensusDeleteTopic,resultField:"consensusDeleteTopic"},ACCOUNTCREATE:{bodyField:"cryptoCreateAccount",parser:na.parseCryptoCreateAccount,resultField:"cryptoCreateAccount"},ACCOUNTUPDATE:{bodyField:"cryptoUpdateAccount",parser:na.parseCryptoUpdateAccount,resultField:"cryptoUpdateAccount"},ACCOUNTDELETE:{bodyField:"cryptoDelete",parser:na.parseCryptoDelete,resultField:"cryptoDelete"},CRYPTOTRANSFER:{bodyField:"cryptoTransfer",parser:e=>{const t={transfers:[],tokenTransfers:[]};return na.parseCryptoTransfers(e,t),t},resultField:"transfers",spreadResult:!0},APPROVEALLOWANCE:{bodyField:"cryptoApproveAllowance",parser:na.parseCryptoApproveAllowance,resultField:"cryptoApproveAllowance"},DELETEALLOWANCE:{bodyField:"cryptoDeleteAllowance",parser:na.parseCryptoDeleteAllowance,resultField:"cryptoDeleteAllowance"},FILECREATE:{bodyField:"fileCreate",parser:ia.parseFileCreate,resultField:"fileCreate"},FILEUPDATE:{bodyField:"fileUpdate",parser:ia.parseFileUpdate,resultField:"fileUpdate"},FILEDELETE:{bodyField:"fileDelete",parser:ia.parseFileDelete,resultField:"fileDelete"},FILEAPPEND:{bodyField:"fileAppend",parser:ia.parseFileAppend,resultField:"fileAppend"},CONTRACTCREATE:{bodyField:"contractCreateInstance",parser:oa.parseContractCreate,resultField:"contractCreate"},CONTRACTUPDATE:{bodyField:"contractUpdateInstance",parser:oa.parseContractUpdate,resultField:"contractUpdate"},CONTRACTDELETE:{bodyField:"contractDeleteInstance",parser:oa.parseContractDelete,resultField:"contractDelete"},CONTRACTCALL:{bodyField:"contractCall",parser:oa.parseContractCall,resultField:"contractCall"},ETHEREUMTRANSACTION:{bodyField:"ethereumTransaction",parser:oa.parseEthereumTransaction,resultField:"ethereumTransaction"},SCHEDULECREATE:{bodyField:"scheduleCreate",parser:aa.parseScheduleCreateFromProto,resultField:"scheduleCreate"},SCHEDULESIGN:{bodyField:"scheduleSign",parser:aa.parseScheduleSignFromProto,resultField:"scheduleSign"},SCHEDULEDELETE:{bodyField:"scheduleDelete",parser:aa.parseScheduleDeleteFromProto,resultField:"scheduleDelete"},PRNG:{bodyField:"utilPrng",parser:sa.parseUtilPrng,resultField:"utilPrng"},FREEZE:{bodyField:"freeze",parser:sa.parseFreeze,resultField:"freeze"},SYSTEMDELETE:{bodyField:"systemDelete",parser:e=>({fileId:e.fileID?`${e.fileID.shardNum}.${e.fileID.realmNum}.${e.fileID.fileNum}`:void 0,contractId:e.contractID?`${e.contractID.shardNum}.${e.contractID.realmNum}.${e.contractID.contractNum}`:void 0,expirationTime:e.expirationTime?.seconds?e.expirationTime.seconds.toString():void 0}),resultField:"systemDelete"},SYSTEMUNDELETE:{bodyField:"systemUndelete",parser:e=>({fileId:e.fileID?`${e.fileID.shardNum}.${e.fileID.realmNum}.${e.fileID.fileNum}`:void 0,contractId:e.contractID?`${e.contractID.shardNum}.${e.contractID.realmNum}.${e.contractID.contractNum}`:void 0}),resultField:"systemUndelete"},TOKENCANCELAIRDROP:{bodyField:"tokenCancelAirdrop",parser:e=>({pendingAirdrops:e.pendingAirdrops||[]}),resultField:"tokenCancelAirdrop"},TOKENCLAIMAIRDROP:{bodyField:"tokenClaimAirdrop",parser:e=>({pendingAirdrops:e.pendingAirdrops||[]}),resultField:"tokenClaimAirdrop"},TOKENREJECT:{bodyField:"tokenReject",parser:e=>({owner:e.owner?`${e.owner.shardNum}.${e.owner.realmNum}.${e.owner.accountNum}`:void 0,rejections:e.rejections||[]}),resultField:"tokenReject"},TOKENUPDATENFTS:{bodyField:"tokenUpdateNfts",parser:e=>({tokenId:e.token?`${e.token.shardNum}.${e.token.realmNum}.${e.token.tokenNum}`:void 0,serialNumbers:e.serialNumbers||[],metadata:e.metadata}),resultField:"tokenUpdateNfts"},TOKENWIPE:{bodyField:"tokenWipe",parser:ta.parseTokenWipeAccount,resultField:"tokenWipeAccount"},CRYPTOADDLIVEHASH:{bodyField:"cryptoAddLiveHash",parser:e=>({accountId:e.accountID?`${e.accountID.shardNum}.${e.accountID.realmNum}.${e.accountID.accountNum}`:void 0,liveHash:e.liveHash}),resultField:"cryptoAddLiveHash"},CRYPTODELETELIVEHASH:{bodyField:"cryptoDeleteLiveHash",parser:e=>({accountId:e.accountOfLiveHash?`${e.accountOfLiveHash.shardNum}.${e.accountOfLiveHash.realmNum}.${e.accountOfLiveHash.accountNum}`:void 0,liveHashToDelete:e.liveHashToDelete}),resultField:"cryptoDeleteLiveHash"},UNCHECKEDSUBMIT:{bodyField:"uncheckedSubmit",parser:e=>({topicId:e.topicID?`${e.topicID.shardNum}.${e.topicID.realmNum}.${e.topicID.topicNum}`:void 0,message:e.message}),resultField:"uncheckedSubmit"},NODECREATE:{bodyField:"nodeCreate",parser:e=>({accountId:e.accountId?`${e.accountId.shardNum}.${e.accountId.realmNum}.${e.accountId.accountNum}`:void 0,description:e.description,gossipEndpoint:e.gossipEndpoint,serviceEndpoint:e.serviceEndpoint,gossipCaCertificate:e.gossipCaCertificate,grpcCertificateHash:e.grpcCertificateHash,adminKey:e.adminKey}),resultField:"nodeCreate"},NODEUPDATE:{bodyField:"nodeUpdate",parser:e=>({nodeId:e.nodeId?.toString(),accountId:e.accountId?`${e.accountId.shardNum}.${e.accountId.realmNum}.${e.accountId.accountNum}`:void 0,description:e.description,gossipEndpoint:e.gossipEndpoint,serviceEndpoint:e.serviceEndpoint,gossipCaCertificate:e.gossipCaCertificate,grpcCertificateHash:e.grpcCertificateHash,adminKey:e.adminKey}),resultField:"nodeUpdate"},NODEDELETE:{bodyField:"nodeDelete",parser:e=>({nodeId:e.nodeId?.toString()}),resultField:"nodeDelete"},NODESTAKEUPDATE:{bodyField:"nodeStakeUpdate",parser:e=>({nodeId:e.nodeId?.toString(),maxStake:e.maxStake?.toString(),minStake:e.minStake?.toString(),rewardRate:e.rewardRate?.toString()}),resultField:"nodeStakeUpdate"},ATOMICBATCH:{bodyField:"atomicBatch",parser:e=>({transactions:e.transactions||[]}),resultField:"atomicBatch"},STATESIGNATURETRANSACTION:{bodyField:"stateSignatureTransaction",parser:e=>({signature:e.signature,round:e.round?.toString()}),resultField:"stateSignatureTransaction"},HISTORYPROOFSIGNATURE:{bodyField:"historyProofSignature",parser:e=>({signature:e.signature,round:e.round?.toString()}),resultField:"historyProofSignature"},HISTORYPROOFKEYPUBLICATION:{bodyField:"historyProofKeyPublication",parser:e=>({publicKey:e.publicKey,round:e.round?.toString()}),resultField:"historyProofKeyPublication"},HISTORYPROOFVOTE:{bodyField:"historyProofVote",parser:e=>({vote:e.vote,round:e.round?.toString()}),resultField:"historyProofVote"},HINTSPREPROCESSINGVOTE:{bodyField:"hintsPreprocessingVote",parser:e=>({vote:e.vote,round:e.round?.toString()}),resultField:"hintsPreprocessingVote"},HINTSKEYPUBLICATION:{bodyField:"hintsKeyPublication",parser:e=>({publicKey:e.publicKey,round:e.round?.toString()}),resultField:"hintsKeyPublication"},HINTSPARTIALSIGNATURE:{bodyField:"hintsPartialSignature",parser:e=>({signature:e.signature,round:e.round?.toString()}),resultField:"hintsPartialSignature"},CRSPUBLICATION:{bodyField:"crsPublication",parser:e=>({crs:e.crs,round:e.round?.toString()}),resultField:"crsPublication"}};const la={tokenCreation:{type:"TOKENCREATE",humanReadableType:"Token Creation"},tokenAirdrop:{type:"TOKENAIRDROP",humanReadableType:"Token Airdrop"},tokenMint:{type:"TOKENMINT",humanReadableType:"Token Mint"},tokenBurn:{type:"TOKENBURN",humanReadableType:"Token Burn"},tokenUpdate:{type:"TOKENUPDATE",humanReadableType:"Token Update"},tokenDeletion:{type:"TOKENDELETE",humanReadableType:"Token Deletion"},tokenAssociate:{type:"TOKENASSOCIATE",humanReadableType:"Token Association"},tokenDissociate:{type:"TOKENDISSOCIATE",humanReadableType:"Token Dissociation"},tokenFreeze:{type:"TOKENFREEZE",humanReadableType:"Token Freeze"},tokenUnfreeze:{type:"TOKENUNFREEZE",humanReadableType:"Token Unfreeze"},tokenGrantKyc:{type:"TOKENGRANTKYC",humanReadableType:"Token Grant KYC"},tokenRevokeKyc:{type:"TOKENREVOKEKYC",humanReadableType:"Token Revoke KYC"},tokenPause:{type:"TOKENPAUSE",humanReadableType:"Token Pause"},tokenUnpause:{type:"TOKENUNPAUSE",humanReadableType:"Token Unpause"},tokenWipe:{type:"TOKENWIPE",humanReadableType:"Token Wipe"},tokenFeeScheduleUpdate:{type:"TOKENFEESCHEDULEUPDATE",humanReadableType:"Token Fee Schedule Update"},tokenCancelAirdrop:{type:"TOKENCANCELAIRDROP",humanReadableType:"Cancel Token Airdrop"},tokenClaimAirdrop:{type:"TOKENCLAIMAIRDROP",humanReadableType:"Claim Token Airdrop"},tokenReject:{type:"TOKENREJECT",humanReadableType:"Token Reject"},tokenUpdateNfts:{type:"TOKENUPDATENFTS",humanReadableType:"Update NFT Metadata"},cryptoTransfer:{type:"CRYPTOTRANSFER",humanReadableType:"Crypto Transfer"},cryptoCreateAccount:{type:"ACCOUNTCREATE",humanReadableType:"Account Creation"},cryptoUpdateAccount:{type:"ACCOUNTUPDATE",humanReadableType:"Account Update"},cryptoDelete:{type:"ACCOUNTDELETE",humanReadableType:"Account Deletion"},cryptoApproveAllowance:{type:"APPROVEALLOWANCE",humanReadableType:"Approve Allowance"},cryptoDeleteAllowance:{type:"DELETEALLOWANCE",humanReadableType:"Delete Allowance"},cryptoAddLiveHash:{type:"CRYPTOADDLIVEHASH",humanReadableType:"Add Live Hash"},cryptoDeleteLiveHash:{type:"CRYPTODELETELIVEHASH",humanReadableType:"Delete Live Hash"},consensusCreateTopic:{type:"TOPICCREATE",humanReadableType:"Topic Creation"},consensusSubmitMessage:{type:"CONSENSUSSUBMITMESSAGE",humanReadableType:"Submit Message"},consensusUpdateTopic:{type:"TOPICUPDATE",humanReadableType:"Topic Update"},consensusDeleteTopic:{type:"TOPICDELETE",humanReadableType:"Topic Deletion"},uncheckedSubmit:{type:"UNCHECKEDSUBMIT",humanReadableType:"Unchecked Submit"},contractCall:{type:"CONTRACTCALL",humanReadableType:"Contract Call"},contractCreateInstance:{type:"CONTRACTCREATE",humanReadableType:"Contract Creation"},contractUpdateInstance:{type:"CONTRACTUPDATE",humanReadableType:"Contract Update"},contractDeleteInstance:{type:"CONTRACTDELETE",humanReadableType:"Contract Deletion"},ethereumTransaction:{type:"ETHEREUMTRANSACTION",humanReadableType:"Ethereum Transaction"},fileCreate:{type:"FILECREATE",humanReadableType:"File Creation"},fileUpdate:{type:"FILEUPDATE",humanReadableType:"File Update"},fileDelete:{type:"FILEDELETE",humanReadableType:"File Deletion"},fileAppend:{type:"FILEAPPEND",humanReadableType:"File Append"},scheduleCreate:{type:"SCHEDULECREATE",humanReadableType:"Schedule Creation"},scheduleSign:{type:"SCHEDULESIGN",humanReadableType:"Schedule Sign"},scheduleDelete:{type:"SCHEDULEDELETE",humanReadableType:"Schedule Deletion"},freeze:{type:"FREEZE",humanReadableType:"Network Freeze"},systemDelete:{type:"SYSTEMDELETE",humanReadableType:"System Delete"},systemUndelete:{type:"SYSTEMUNDELETE",humanReadableType:"System Undelete"},nodeCreate:{type:"NODECREATE",humanReadableType:"Node Creation"},nodeUpdate:{type:"NODEUPDATE",humanReadableType:"Node Update"},nodeDelete:{type:"NODEDELETE",humanReadableType:"Node Deletion"},nodeStakeUpdate:{type:"NODESTAKEUPDATE",humanReadableType:"Node Stake Update"},utilPrng:{type:"PRNG",humanReadableType:"Pseudo Random Number"},atomicBatch:{type:"ATOMICBATCH",humanReadableType:"Atomic Batch"},stateSignatureTransaction:{type:"STATESIGNATURETRANSACTION",humanReadableType:"State Signature"},historyProofSignature:{type:"HISTORYPROOFSIGNATURE",humanReadableType:"History Proof Signature"},historyProofKeyPublication:{type:"HISTORYPROOFKEYPUBLICATION",humanReadableType:"History Proof Key Publication"},historyProofVote:{type:"HISTORYPROOFVOTE",humanReadableType:"History Proof Vote"},hintsPreprocessingVote:{type:"HINTSPREPROCESSINGVOTE",humanReadableType:"Hints Preprocessing Vote"},hintsKeyPublication:{type:"HINTSKEYPUBLICATION",humanReadableType:"Hints Key Publication"},hintsPartialSignature:{type:"HINTSPARTIALSIGNATURE",humanReadableType:"Hints Partial Signature"},crsPublication:{type:"CRSPUBLICATION",humanReadableType:"CRS Publication"},transactionID:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},nodeAccountID:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},transactionFee:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},transactionValidDuration:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},generateRecord:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},memo:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},batchKey:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},maxCustomFees:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"}},ua={cryptoTransfer:"HBAR Transfer",CRYPTOTRANSFER:"HBAR Transfer",cryptoCreateAccount:"Create Account",ACCOUNTCREATE:"Create Account",cryptoUpdateAccount:"Update Account",ACCOUNTUPDATE:"Update Account",cryptoDeleteAccount:"Delete Account",cryptoDelete:"Delete Account",ACCOUNTDELETE:"Delete Account",cryptoApproveAllowance:"Approve Allowance",APPROVEALLOWANCE:"Approve Allowance",cryptoDeleteAllowance:"Delete Allowance",DELETEALLOWANCE:"Delete Allowance",CRYPTOADDLIVEHASH:"Add Live Hash",CRYPTODELETELIVEHASH:"Delete Live Hash",consensusCreateTopic:"Create Topic",TOPICCREATE:"Create Topic",consensusUpdateTopic:"Update Topic",TOPICUPDATE:"Update Topic",consensusSubmitMessage:"Submit Message",CONSENSUSSUBMITMESSAGE:"Submit Message",consensusDeleteTopic:"Delete Topic",TOPICDELETE:"Delete Topic",UNCHECKEDSUBMIT:"Unchecked Submit",fileCreate:"Create File",FILECREATE:"Create File",fileAppend:"Append File",FILEAPPEND:"Append File",fileUpdate:"Update File",FILEUPDATE:"Update File",fileDelete:"Delete File",FILEDELETE:"Delete File",contractCall:"Contract Call",CONTRACTCALL:"Contract Call",contractCreate:"Create Contract",CONTRACTCREATE:"Create Contract",contractUpdate:"Update Contract",CONTRACTUPDATE:"Update Contract",contractDelete:"Delete Contract",CONTRACTDELETE:"Delete Contract",ethereumTransaction:"Ethereum Transaction",ETHEREUMTRANSACTION:"Ethereum Transaction",tokenCreate:"Create Token",TOKENCREATE:"Create Token",tokenUpdate:"Update Token",TOKENUPDATE:"Update Token",tokenDelete:"Delete Token",TOKENDELETE:"Delete Token",tokenAssociate:"Associate Token",TOKENASSOCIATE:"Associate Token",tokenDissociate:"Dissociate Token",TOKENDISSOCIATE:"Dissociate Token",tokenMint:"Mint Token",TOKENMINT:"Mint Token",tokenBurn:"Burn Token",TOKENBURN:"Burn Token",tokenFeeScheduleUpdate:"Update Token Fee Schedule",TOKENFEESCHEDULEUPDATE:"Update Token Fee Schedule",tokenFreeze:"Freeze Token",TOKENFREEZE:"Freeze Token",tokenUnfreeze:"Unfreeze Token",TOKENUNFREEZE:"Unfreeze Token",tokenGrantKyc:"Grant KYC",TOKENGRANTKYC:"Grant KYC",tokenRevokeKyc:"Revoke KYC",TOKENREVOKEKYC:"Revoke KYC",tokenPause:"Pause Token",TOKENPAUSE:"Pause Token",tokenUnpause:"Unpause Token",TOKENUNPAUSE:"Unpause Token",tokenWipe:"Wipe Token",TOKENWIPE:"Wipe Token",tokenAirdrop:"Token Airdrop",TOKENAIRDROP:"Token Airdrop",TOKENCANCELAIRDROP:"Cancel Token Airdrop",TOKENCLAIMAIRDROP:"Claim Token Airdrop",TOKENREJECT:"Token Reject",TOKENUPDATENFTS:"Update NFT Metadata",scheduleCreate:"Create Schedule",SCHEDULECREATE:"Create Schedule",scheduleSign:"Sign Schedule",SCHEDULESIGN:"Sign Schedule",SCHEDULEDELETE:"Delete Schedule",FREEZE:"Network Freeze",SYSTEMDELETE:"System Delete",SYSTEMUNDELETE:"System Undelete",NODECREATE:"Create Node",NODEUPDATE:"Update Node",NODEDELETE:"Delete Node",NODESTAKEUPDATE:"Update Node Stake",utilPrng:"Generate Random Number",PRNG:"Generate Random Number",ATOMICBATCH:"Atomic Batch",STATESIGNATURETRANSACTION:"State Signature",HISTORYPROOFSIGNATURE:"History Proof Signature",HISTORYPROOFKEYPUBLICATION:"History Proof Key Publication",HISTORYPROOFVOTE:"History Proof Vote",HINTSPREPROCESSINGVOTE:"Hints Preprocessing Vote",HINTSKEYPUBLICATION:"Hints Key Publication",HINTSPARTIALSIGNATURE:"Hints Partial Signature",CRSPUBLICATION:"CRS Publication",unknown:"Unknown Transaction",UNKNOWN:"Unknown Transaction"},da={tokenCreation:"tokenCreate",tokenAirdrop:"tokenAirdrop",cryptoTransfer:"cryptoTransfer",consensusSubmitMessage:"consensusSubmitMessage",contractCall:"contractCall",cryptoCreateAccount:"cryptoCreateAccount",cryptoUpdateAccount:"cryptoUpdateAccount",cryptoApproveAllowance:"cryptoApproveAllowance",cryptoDeleteAllowance:"cryptoDeleteAllowance",cryptoDelete:"cryptoDelete",consensusCreateTopic:"consensusCreateTopic",consensusUpdateTopic:"consensusUpdateTopic",consensusDeleteTopic:"consensusDeleteTopic",fileCreate:"fileCreate",fileAppend:"fileAppend",fileUpdate:"fileUpdate",fileDelete:"fileDelete",contractCreateInstance:"contractCreate",contractUpdateInstance:"contractUpdate",contractDeleteInstance:"contractDelete",tokenUpdate:"tokenUpdate",tokenDeletion:"tokenDelete",tokenAssociate:"tokenAssociate",tokenDissociate:"tokenDissociate",tokenMint:"tokenMint",tokenBurn:"tokenBurn",tokenFeeScheduleUpdate:"tokenFeeScheduleUpdate",tokenFreeze:"tokenFreeze",tokenUnfreeze:"tokenUnfreeze",tokenGrantKyc:"tokenGrantKyc",tokenRevokeKyc:"tokenRevokeKyc",tokenPause:"tokenPause",tokenUnpause:"tokenUnpause",tokenWipe:"tokenWipe",utilPrng:"utilPrng"};function pa(e){for(const[t,r]of Object.entries(la))if(e[t])return r;return{type:"UNKNOWN",humanReadableType:"Unknown Transaction"}}function ha(e){return ua[e]||"Unknown Transaction"}class ga{static async parseTransactionBytes(e,t={}){const{enableFallback:r=!0,strictMode:i=!1,includeRaw:n=!0,maxRetries:o=2}=t,s=this.validateTransactionBytes(e);if(!s.isValid&&i)throw new rs(`Invalid transaction bytes format: ${s.error}`,"INVALID_FORMAT",void 0,e);let a,c=0;for(;c<=o;)try{const r=await this.parseTransaction(e,t);return r.formatDetection={originalFormat:s.format||"base64",wasConverted:"hex"===s.format,length:e.length},r}catch(u){if(a=u instanceof Error?u:new Error(String(u)),c++,!r||c>o){if(i)throw new rs("Failed to parse transaction after all attempts","PARSING_FAILED",a,e);break}try{const r=this.parseScheduledTransaction(e,t);return r.formatDetection={originalFormat:s.format||"base64",wasConverted:!1,length:e.length},r}catch(d){}}const l=this.createFallbackResult(e,a,void 0);return l.details&&(l.details.parseAttempts=Math.max(c,1)),l}static parseTransactionObject(e,t,r={}){let i,s;!t||o.Buffer.isBuffer(t)||t instanceof Uint8Array?(i=t,s=r):(s=t,i=void 0);try{const t=this.extractTransactionMetadata(e),r=ta.parseFromTransactionObject(e),o=na.parseFromTransactionObject(e),c=ra.parseFromTransactionObject(e),l=ia.parseFromTransactionObject(e),u=oa.parseFromTransactionObject(e),d=aa.parseFromTransactionObject(e),p=sa.parseFromTransactionObject(e),h=[r,o,c,l,u,d,p].find(e=>e.type&&"UNKNOWN"!==e.type)||{};let g,m="UNKNOWN",f="Unknown Transaction",y={};if(i||e.toBytes)try{const t=i||e.toBytes(),r=n.proto.TransactionList.decode(t);if(r.transactionList&&r.transactionList.length>0){const e=r.transactionList[0];if(e.bodyBytes&&e.bodyBytes.length>0){const t=n.proto.TransactionBody.decode(e.bodyBytes),r=this.detectTransactionTypeFromBody(t);m=r.type,f=r.humanReadableType,y=this.parseTransactionBodyDetails(t,m),y.tokenCreation&&(g=y.tokenCreation)}else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const t=n.proto.SignedTransaction.decode(e.signedTransactionBytes);if(t.bodyBytes){const e=n.proto.TransactionBody.decode(t.bodyBytes),r=this.detectTransactionTypeFromBody(e);m=r.type,f=r.humanReadableType,y=this.parseTransactionBodyDetails(e,m),y.tokenCreation&&(g=y.tokenCreation)}}}}catch(a){}"UNKNOWN"===m&&h.type&&(m=h.type,f=h.humanReadableType||f);const b={type:m,humanReadableType:f,transfers:[],tokenTransfers:[],...t,...h,raw:s.includeRaw?e._transactionBody||{}:void 0};return this.mergeProtoParsingResults(b,y,r,e,i),b.transfers=o.transfers||b.transfers||[],b.tokenTransfers=o.tokenTransfers||b.tokenTransfers||[],b}catch(c){return{type:"UNKNOWN",humanReadableType:"Unknown Transaction",transfers:[],tokenTransfers:[],raw:s.includeRaw?{}:void 0,details:{error:`Failed to parse Transaction object: ${c instanceof Error?c.message:String(c)}`}}}}static parseTransactionBody(e){try{const t=s.ethers.decodeBase64(e),i=n.proto.SchedulableTransactionBody.decode(t),o=this.getTransactionType(i),a={type:o,humanReadableType:this.getHumanReadableType(o),transfers:[],tokenTransfers:[],raw:i};if(i.memo&&(a.memo=i.memo),i.transactionFee){const e=r.Hbar.fromTinybars(r.Long.fromValue(i.transactionFee));a.transactionFee=e.toString(r.HbarUnit.Hbar)}return this.applySchedulableTransactionParsing(i,a),a}catch(t){return{type:"UNKNOWN",humanReadableType:"Unknown Transaction",transfers:[],tokenTransfers:[],raw:void 0,details:{error:`Failed to parse transaction body: ${t instanceof Error?t.message:String(t)}`}}}}static detectTransactionTypeFromBody(e){return pa(e)}static parseScheduleResponse(e){if(!e.transaction_body)return{type:"UNKNOWN",humanReadableType:"Unknown Transaction",transfers:[],tokenTransfers:[],raw:void 0,details:{error:"Schedule response missing transaction_body"}};const t=this.parseTransactionBody(e.transaction_body);return e.memo&&(t.memo=e.memo),t}static getTransactionType(e){return pa(e).type}static getHumanReadableType(e){return ha(e)}static getTransactionSummary(e){return Xs(e)}static validateTransactionBytes(e){if(!e||"string"!=typeof e)return{isValid:!1,error:"Transaction bytes must be a non-empty string"};const t=this.detectTransactionFormat(e),r=/^[A-Za-z0-9+/]*={0,2}$/;let i,n=!1;return"hex"===t?(n=/^0x[0-9a-fA-F]+$/.test(e)&&e.length>2,n||(i="Invalid hex format")):(n=r.test(e)&&e.length>0,n||(i="Invalid base64 format")),{isValid:n,format:t,error:i,length:e.length}}static detectTransactionFormat(e){return e.startsWith("0x")?"hex":"base64"}static decodeTransactionBytes(e){try{if("hex"===this.detectTransactionFormat(e)){const t=e.slice(2);return new Uint8Array(o.Buffer.from(t,"hex"))}return new Uint8Array(o.Buffer.from(e,"base64"))}catch(t){throw new rs("Failed to decode transaction bytes","DECODE_ERROR",t instanceof Error?t:void 0,e)}}static async isValidHederaTransaction(e){try{if(!this.validateTransactionBytes(e).isValid)return!1;const t=this.decodeTransactionBytes(e);return r.Transaction.fromBytes(t),!0}catch{return!1}}static decodeBytesLegacy(e){return this.decodeTransactionBytes(e)}static async parseTransaction(e,t={}){try{const i=this.decodeTransactionBytes(e),n=r.Transaction.fromBytes(i),o=this.extractTransactionMetadataEnhanced(n),s=this.runAllParsers(n),a=s.find(e=>e.type&&"UNKNOWN"!==e.type)||{},c=this.parseFromProtobuf(i),l=c.type||a.type||"UNKNOWN",u={type:l,humanReadableType:c.humanReadableType||a.humanReadableType||"Unknown Transaction",transfers:[],tokenTransfers:[],details:{...o},memo:"string"==typeof o.memo?o.memo:void 0,transactionId:"string"==typeof o.transactionId?o.transactionId:void 0,nodeAccountIds:Array.isArray(o.nodeAccountIds)?o.nodeAccountIds:[],maxTransactionFee:"string"==typeof o.maxTransactionFee?o.maxTransactionFee:void 0,validStart:"string"==typeof o.validStart?o.validStart:void 0,validDuration:"string"==typeof o.validDuration?o.validDuration:void 0,raw:t.includeRaw?{}:void 0};return this.mergeAllResults(u,c,a,s),u}catch(i){throw new rs("Failed to parse as regular transaction","REGULAR_PARSING_FAILED",i instanceof Error?i:void 0,e)}}static parseScheduledTransaction(e,t={}){try{const t=this.parseTransactionBody(e),r=this.validateTransactionBytes(e);return{...t,details:{...t.details||{},parseMethod:"scheduled",validation:r,parseAttempts:t.details?.parseAttempts||1},formatDetection:{originalFormat:r.format||"base64",wasConverted:!1,length:e.length}}}catch(r){throw new rs("Failed to parse as scheduled transaction","SCHEDULED_PARSING_FAILED",r instanceof Error?r:void 0,e)}}static extractTransactionMetadata(e){return{transactionId:e.transactionId?.toString(),nodeAccountIds:e.nodeAccountIds?.map(e=>e.toString())||[],maxTransactionFee:e.maxTransactionFee?.toTinybars().toString()||"0",memo:e._transactionMemo||void 0,transfers:[],tokenTransfers:[]}}static extractTransactionMetadataEnhanced(e){return{transactionId:e.transactionId?.toString(),nodeAccountIds:e.nodeAccountIds?.map(e=>e.toString())||[],maxTransactionFee:e.maxTransactionFee?.toTinybars().toString()||"0",memo:e._transactionMemo||void 0,validStart:e._transactionValidStart?.toString(),validDuration:e._transactionValidDuration?.toString()}}static runAllParsers(e){return[ta.parseFromTransactionObject(e),na.parseFromTransactionObject(e),ra.parseFromTransactionObject(e),ia.parseFromTransactionObject(e),oa.parseFromTransactionObject(e),aa.parseFromTransactionObject(e),sa.parseFromTransactionObject(e)]}static parseFromProtobuf(e){const t={};try{const r=n.proto.TransactionList.decode(e);if(r.transactionList&&r.transactionList.length>0){const e=r.transactionList[0];let i=null;if(e.bodyBytes&&e.bodyBytes.length>0)i=n.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const t=n.proto.SignedTransaction.decode(e.signedTransactionBytes);t.bodyBytes&&(i=n.proto.TransactionBody.decode(t.bodyBytes))}if(i){const e=this.detectTransactionTypeFromBody(i);t.type=e.type,t.humanReadableType=e.humanReadableType;const r=this.parseTransactionBodyDetails(i,e.type);Object.assign(t,r)}}}catch(r){}return t}static mergeAllResults(e,t,r,i){const n=i.find(e=>e.transfers||e.tokenTransfers)||{};e.transfers=n.transfers||e.transfers||[],e.tokenTransfers=n.tokenTransfers||e.tokenTransfers||[],Object.keys(t).forEach(r=>{void 0!==t[r]&&"type"!==r&&"humanReadableType"!==r&&(e[r]=t[r])}),Object.keys(r).forEach(t=>{void 0===r[t]||t in e||"type"===t||"humanReadableType"===t||(e[t]=r[t])})}static applySchedulableTransactionParsing(e,t){e.cryptoTransfer&&na.parseCryptoTransfers(e.cryptoTransfer,t),e.cryptoDelete&&(t.cryptoDelete=na.parseCryptoDelete(e.cryptoDelete)),e.cryptoCreateAccount&&(t.cryptoCreateAccount=na.parseCryptoCreateAccount(e.cryptoCreateAccount)),e.cryptoUpdateAccount&&(t.cryptoUpdateAccount=na.parseCryptoUpdateAccount(e.cryptoUpdateAccount)),e.cryptoApproveAllowance&&(t.cryptoApproveAllowance=na.parseCryptoApproveAllowance(e.cryptoApproveAllowance)),e.cryptoDeleteAllowance&&(t.cryptoDeleteAllowance=na.parseCryptoDeleteAllowance(e.cryptoDeleteAllowance)),e.contractCall&&(t.contractCall=oa.parseContractCall(e.contractCall)),e.contractCreateInstance&&(t.contractCreate=oa.parseContractCreate(e.contractCreateInstance)),e.contractUpdateInstance&&(t.contractUpdate=oa.parseContractUpdate(e.contractUpdateInstance)),e.contractDeleteInstance&&(t.contractDelete=oa.parseContractDelete(e.contractDeleteInstance)),e.tokenCreation&&(t.tokenCreation=ta.parseTokenCreate(e.tokenCreation)),e.tokenMint&&(t.tokenMint=ta.parseTokenMint(e.tokenMint)),e.tokenBurn&&(t.tokenBurn=ta.parseTokenBurn(e.tokenBurn)),e.tokenUpdate&&(t.tokenUpdate=ta.parseTokenUpdate(e.tokenUpdate)),e.tokenFeeScheduleUpdate&&(t.tokenFeeScheduleUpdate=ta.parseTokenFeeScheduleUpdate(e.tokenFeeScheduleUpdate)),e.tokenFreeze&&(t.tokenFreeze=ta.parseTokenFreeze(e.tokenFreeze)),e.tokenUnfreeze&&(t.tokenUnfreeze=ta.parseTokenUnfreeze(e.tokenUnfreeze)),e.tokenGrantKyc&&(t.tokenGrantKyc=ta.parseTokenGrantKyc(e.tokenGrantKyc)),e.tokenRevokeKyc&&(t.tokenRevokeKyc=ta.parseTokenRevokeKyc(e.tokenRevokeKyc)),e.tokenPause&&(t.tokenPause=ta.parseTokenPause(e.tokenPause)),e.tokenUnpause&&(t.tokenUnpause=ta.parseTokenUnpause(e.tokenUnpause)),e.tokenWipe&&(t.tokenWipeAccount=ta.parseTokenWipeAccount(e.tokenWipe)),e.tokenDeletion&&(t.tokenDelete=ta.parseTokenDelete(e.tokenDeletion)),e.tokenAssociate&&(t.tokenAssociate=ta.parseTokenAssociate(e.tokenAssociate)),e.tokenDissociate&&(t.tokenDissociate=ta.parseTokenDissociate(e.tokenDissociate)),e.tokenAirdrop&&(t.tokenAirdrop=ta.parseTokenAirdropFromProto(e.tokenAirdrop)),e.consensusCreateTopic&&(t.consensusCreateTopic=ra.parseConsensusCreateTopic(e.consensusCreateTopic)),e.consensusSubmitMessage&&(t.consensusSubmitMessage=ra.parseConsensusSubmitMessage(e.consensusSubmitMessage)),e.consensusUpdateTopic&&(t.consensusUpdateTopic=ra.parseConsensusUpdateTopic(e.consensusUpdateTopic)),e.consensusDeleteTopic&&(t.consensusDeleteTopic=ra.parseConsensusDeleteTopic(e.consensusDeleteTopic)),e.fileCreate&&(t.fileCreate=ia.parseFileCreate(e.fileCreate)),e.fileAppend&&(t.fileAppend=ia.parseFileAppend(e.fileAppend)),e.fileUpdate&&(t.fileUpdate=ia.parseFileUpdate(e.fileUpdate)),e.fileDelete&&(t.fileDelete=ia.parseFileDelete(e.fileDelete)),e.utilPrng&&(t.utilPrng=sa.parseUtilPrng(e.utilPrng))}static parseTransactionBodyDetails(e,t){const r={},i=ca[t];if(i){const t=e[i.bodyField];if(t){const e=i.parser(t);i.spreadResult?Object.assign(r,e):r[i.resultField]=e}}return r}static mergeProtoParsingResults(e,t,r,i,n){const o=Object.values(ca).map(e=>e.resultField);for(const s of o){const n=t[s],o=r[s];void 0!==n?e[s]=n:void 0!==o?e[s]=o:this.handleSpecialFieldExtraction(e,s,i)}}static handleSpecialFieldExtraction(e,t,r){if("tokenCreation"===t&&"TOKENCREATE"===e.type){const i=ta.extractTokenCreationFromTransaction(r);i&&(e[t]=i)}else if("tokenAirdrop"===t&&"TOKENAIRDROP"===e.type){const i=ta.extractTokenAirdropFromTransaction(r);i&&(e[t]=i)}}static createFallbackResult(e,t,r){const i=this.validateTransactionBytes(e);return{type:"UNKNOWN",humanReadableType:"Unknown Transaction",transfers:[],tokenTransfers:[],details:{rawBytes:e.length>100?e.substring(0,100)+"...":e,primaryError:t?.message,secondaryError:r?.message,parseAttempts:r?2:1,validation:i},formatDetection:{originalFormat:i.format||"base64",wasConverted:!1,length:e.length},raw:{}}}}const ma="undefined"!=typeof window&&void 0!==window.document;let fa;const ya=()=>"undefined"!=typeof process&&Boolean(process.versions?.node);function ba(){try{const e=process.getBuiltinModule?.("module");if("function"==typeof e?.createRequire){const t=e.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:p&&"SCRIPT"===p.tagName.toUpperCase()&&p.src||new URL("standards-sdk.cjs",document.baseURI).href);if("function"==typeof t.resolve)return t}const t="undefined"!=typeof global?global:globalThis,r=t.process?.mainModule?.require??t.require??Function('return typeof require === "function" ? require : undefined;')();if("function"==typeof r&&"function"==typeof r.resolve)return r}catch{return null}return null}function wa(e,t){if(!t||"object"!=typeof t)return!1;const r=Reflect.get(t,"code"),i=Reflect.get(t,"message"),n="string"==typeof i?i:"";if("string"==typeof r&&r.includes("MODULE_NOT_FOUND"))return n.includes(e);if(n){const t=n.toLowerCase();if(t.includes("cannot find module")||t.includes("module not found")||t.includes("cannot find package"))return t.includes(e.toLowerCase())}return!1}async function Ia(e){try{return await import(e)}catch(t){if(wa(e,t))return null;throw t}}async function Ta(e,t={}){if(ma&&!ya())return Ia(e);if(!t.preferImport){const t=await async function(){if(void 0!==fa)return fa;if(ma&&!ya())return fa=null,fa;try{fa=ba()}catch{fa=null}return fa}();if(t)try{return t(e)}catch(r){if(!wa(e,r))throw r}}return Ia(e)}function Sa(e){if(ma&&!ya())return null;try{const t=ba();if(t)return t(e)}catch(t){if(!wa(e,t))throw t}return null}const ka=new class{constructor(){this.cache=new Map,this.maxSize=100,this.defaultTtlMs=3e5}generateKey(e){return`${e.inputHash}-${e.clientConfigHash}-${e.optionsHash}`}hashObject(e){return globalThis.Buffer.from(JSON.stringify(e)).toString("base64").slice(0,16)}createCacheKey(e,t,r){return{inputHash:this.hashObject(e),clientConfigHash:this.hashObject({accountId:t.accountId,network:t.network}),optionsHash:this.hashObject({mode:r.mode,apiKey:r.apiKey?"present":"absent",network:r.network,metadata:r.metadata})}}get(e){const t=this.generateKey(e),r=this.cache.get(t);if(!r)return null;return Date.now()-r.timestamp>r.ttlMs?(this.cache.delete(t),null):(this.cache.delete(t),this.cache.set(t,r),r.quote)}set(e,t,r=this.defaultTtlMs){const i=this.generateKey(e);if(this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}this.cache.set(i,{quote:t,timestamp:Date.now(),ttlMs:r})}clear(){this.cache.clear()}},va=new class{constructor(){this.cache=new Map,this.maxSize=10,this.defaultTtlMs=18e5}generateConfigKey(e){return globalThis.Buffer.from(JSON.stringify(e)).toString("base64")}get(e){const t=this.generateConfigKey(e),r=this.cache.get(t);if(!r)return null;return Date.now()-r.timestamp>this.defaultTtlMs?(this.cache.delete(t),null):r.sdk}set(e,t){const r=this.generateConfigKey(e);if(this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}this.cache.set(r,{sdk:t,timestamp:Date.now(),config:r})}clear(){this.cache.clear()}};async function Ea(e,t,r){if(r)return r;const i=t.connectionMode??"websocket",n={apiKey:t.apiKey,accountId:e.accountId,network:e.network||"mainnet",authType:t.apiKey?"api":"server",connectionMode:i},o=va.get(n);if(o)return o;let s;return s=t.apiKey?new es({apiKey:t.apiKey,network:e.network||"mainnet",connectionMode:i}):await es.createWithAuth({type:"server",accountId:e.accountId,privateKey:"string"==typeof e.privateKey?e.privateKey:e.privateKey.toString(),network:e.network||"mainnet",connectionMode:i}),va.set(n,s),s}function Aa(e){return new a(e).dividedBy(1e8).toFixed()}function Ca(e){const{txn:t,payerAccountId:r}=e,i=(n=t.transfers,Array.isArray(n)?n.filter(e=>"number"==typeof e.amount&&e.amount>0).map(e=>({account:e.account,amountTinybar:e.amount})):[]);var n;const o=function(e,t){if(!Array.isArray(e))return null;const r=e.find(e=>e.account===t&&"number"==typeof e.amount&&e.amount<0);return r&&"number"==typeof r.amount?Math.abs(r.amount):null}(t.transfers,r),s=o??i.reduce((e,t)=>e+t.amountTinybar,0),a="number"==typeof(c=t.charged_tx_fee)&&Number.isFinite(c)?c<=0?null:c:null;var c;const l=s>0?s:a;if(!l||l<=0)return null;const u=Aa(l);return{totalTinybar:l,summary:{totalCostHbar:u,breakdown:{transfers:i.length>0?i.map(e=>({to:e.account,amount:Aa(e.amountTinybar),description:`HBAR transfer from ${r}`})):[{to:"Hedera network",amount:u,description:`Transaction fee debited from ${r}`}]}}}}let Ra={};const xa=e=>{if(!e.includes("@"))return e;const t=e?.split("@");return`${t[0]}-${t[1].replace(".","-")}`};const Na=1e3;async function za(e){if(ma)throw new Error("File path operations are not supported in browser environment. Use buffer input type instead.");if(await async function(){if(!ma&&!Ra.readFileSync)try{const[e,t]=await Promise.all([Ta("node:fs"),Ta("node:path")]);if(!e||!t)throw new Error("Node.js fs or path module not available");Ra.readFileSync=e.readFileSync,Ra.basename=t.basename,Ra.extname=t.extname}catch(e){y.getInstance({module:"Inscriber",level:"warn"}).warn("Node.js modules not available, file path operations will be disabled",{error:e instanceof Error?e.message:String(e)})}}(),!Ra.readFileSync||!Ra.basename||!Ra.extname)throw new Error("Node.js file system modules are not available. Cannot read file from path.");try{const r=Ra.readFileSync(e),i=r.toString("base64"),n=Ra.basename(e);let o="application/octet-stream";try{const e=await Ta("file-type"),t="function"==typeof e?.fileTypeFromBuffer?await e.fileTypeFromBuffer(r):void 0;t&&(o=t.mime)}catch(t){const r=Ra.extname(e).toLowerCase();o={".txt":"text/plain",".json":"application/json",".html":"text/html",".css":"text/css",".js":"application/javascript",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".pdf":"application/pdf"}[r]||"application/octet-stream"}return{base64:i,fileName:n,mimeType:o}}catch(r){throw new Error(`Failed to read file ${e}: ${r.message}`)}}function _a(e){return{accountId:e.accountId,privateKey:"string"==typeof e.privateKey?e.privateKey:e.privateKey.toString(),network:e.network}}function Pa(e){return e.connectionMode?e.connectionMode:"boolean"==typeof e.websocket?e.websocket?"websocket":"http":"websocket"}async function Oa(e,t,r,i){const n=y.getInstance({module:"Inscriber",...r.logging}),o=Pa(r);n.info("Starting inscription process",{type:e.type,mode:r.mode||"file",quoteOnly:r.quoteOnly||!1,..."url"===e.type?{url:e.url}:{},..."file"===e.type?{path:e.path}:{},..."buffer"===e.type?{fileName:e.fileName,bufferSize:e.buffer.byteLength}:{}});try{if(r.quoteOnly)return n.debug("Quote-only mode requested, generating quote"),await Ba(e,t,r,i);let s;if("hashinal"===r.mode&&r.metadata&&Ua(r.metadata,n),i)n.debug("Using existing InscriptionSDK instance"),s=i;else if(r.apiKey)n.debug("Initializing InscriptionSDK with API key"),s=new es({apiKey:r.apiKey,network:t.network||"mainnet",connectionMode:o,baseURL:r.baseURL});else{n.debug("Initializing InscriptionSDK with server auth");const e=_a(t);s=await es.createWithAuth({type:"server",accountId:e.accountId,privateKey:e.privateKey,network:e.network||"mainnet",connectionMode:o,baseUrl:r.baseURL})}const a={holderId:t.accountId,metadata:r.metadata||{},tags:r.tags||[],mode:r.mode||"file",fileStandard:r.fileStandard,chunkSize:r.chunkSize};let c;switch(e.type){case"url":c={...a,file:{type:"url",url:e.url}};break;case"file":{const t=await za(e.path);c={...a,file:{type:"base64",base64:t.base64,fileName:t.fileName,mimeType:t.mimeType}};break}case"buffer":c={...a,file:{type:"base64",base64:globalThis.Buffer.from(e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer):e.buffer).toString("base64"),fileName:e.fileName,mimeType:e.mimeType}}}"hashinal"===r.mode&&(c.metadataObject=r.metadata,c.creator=r.metadata?.creator||t.accountId,c.description=r.metadata?.description,r.jsonFileURL&&(c.jsonFileURL=r.jsonFileURL)),n.debug("Preparing to inscribe content",{type:e.type,mode:r.mode||"file",holderId:t.accountId});const l=_a(t),u=await s.inscribeAndExecute(c,l,r.progressCallback),d=u.jobId||u.tx_id||u.transactionId||"",p=u.transactionId||d||"",h=xa(d),g=xa(p),m=xa(h||g||d||u.jobId||"");if(n.info("Starting to inscribe.",{type:e.type,mode:r.mode||"file",transactionId:u.jobId}),r.waitForConfirmation){n.debug("Waiting for inscription confirmation",{transactionId:m,maxAttempts:r.waitMaxAttempts,intervalMs:r.waitIntervalMs});const e=await La(s,m,r.waitMaxAttempts,r.waitIntervalMs,r.progressCallback);return n.info("Inscription confirmation received",{transactionId:u.jobId}),{confirmed:!0,result:{...u,jobId:m,transactionId:g},inscription:e,sdk:s,costSummary:await Da(g,t.network||"mainnet",r.logging?.level)}}return{confirmed:!1,result:{...u,jobId:m,transactionId:g},sdk:s,costSummary:await Da(g,t.network||"mainnet",r.logging?.level)}}catch(s){throw n.error("Error during inscription process",s),s}}async function Da(e,t,r){const i=y.getInstance({module:"InscriberCost",level:r??"info"}),n=new x(t,i),o=xa(e),s=o.split("-")[0];for(let c=0;c<3;c++)try{const e=await n.getTransaction(o);if(!e){c<2&&await b(Na);continue}const t=Ca({txn:e,payerAccountId:s});if(!t){c<2&&await b(Na);continue}return t.summary}catch(a){i.warn("Unable to resolve inscription cost",{transactionId:o,attempt:c+1,error:a instanceof Error?a.message:String(a)}),c<2&&await b(Na)}}async function Fa(e,t,r,i){const n=y.getInstance({module:"Inscriber",...r.logging}),o=Pa(r);n.info("Starting inscription process with signer",{type:e.type,mode:r.mode||"file",quoteOnly:r.quoteOnly||!1,..."url"===e.type?{url:e.url}:{},..."file"===e.type?{path:e.path}:{},..."buffer"===e.type?{fileName:e.fileName,bufferSize:e.buffer.byteLength}:{}});try{if(r.quoteOnly){n.debug("Quote-only mode requested with signer, generating quote");const o={accountId:t.getAccountId().toString(),privateKey:"",network:r.network||"mainnet"};return await Ba(e,o,r,i)}"hashinal"===r.mode&&r.metadata&&Ua(r.metadata,n);const s=t.getAccountId().toString();let a;n.debug("Using account ID from signer",{accountId:s}),i?(n.debug("Using existing InscriptionSDK instance"),a=i):r.apiKey?(n.debug("Initializing InscriptionSDK with API key"),a=new es({apiKey:r.apiKey,network:r.network||"mainnet",connectionMode:o,baseURL:r.baseURL})):(n.debug("Initializing InscriptionSDK with client auth (websocket)"),a=await es.createWithAuth({type:"client",accountId:s,signer:t,network:r.network||"mainnet",connectionMode:o,baseUrl:r.baseURL}));const c={holderId:s,metadata:r.metadata||{},tags:r.tags||[],mode:r.mode||"file",fileStandard:r.fileStandard,chunkSize:r.chunkSize};let l;switch(e.type){case"url":l={...c,file:{type:"url",url:e.url}};break;case"file":{const t=await za(e.path);l={...c,file:{type:"base64",base64:t.base64,fileName:t.fileName,mimeType:t.mimeType}};break}case"buffer":l={...c,file:{type:"base64",base64:globalThis.Buffer.from(e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer):e.buffer).toString("base64"),fileName:e.fileName,mimeType:e.mimeType}}}"hashinal"===r.mode&&(l.metadataObject=r.metadata,l.creator=r.metadata?.creator||s,l.description=r.metadata?.description,r.jsonFileURL&&(l.jsonFileURL=r.jsonFileURL)),n.debug("Starting inscription via startInscription (websocket)",{type:e.type,mode:r.mode||"file",holderId:s,usesStartInscription:!0});const u=await a.startInscription({...l,holderId:s,network:r.network||"mainnet"}),d="string"==typeof u?.tx_id&&u.tx_id.trim()||"string"==typeof u?.jobId&&(u.jobId||"").trim()||"string"==typeof u?.id&&(u.id||"").trim()||"",p=xa(d);if(!p)throw new Error("startInscription did not return a transaction id");if(n.info("about to start inscription",{type:e.type,mode:r.mode||"file",jobId:p,...u}),"string"==typeof u?.transactionBytes?(n.debug("Executing inscription transaction with signer from bytes"),await a.executeTransactionWithSigner(u.transactionBytes,t)):"Buffer"===u?.transactionBytes?.type&&(n.debug("Executing inscription transaction with signer from buffer"),await a.executeTransactionWithSigner(globalThis.Buffer.from(u.transactionBytes.data).toString("base64"),t)),r.waitForConfirmation){n.debug("Waiting for inscription confirmation (websocket)",{jobId:p,maxAttempts:r.waitMaxAttempts,intervalMs:r.waitIntervalMs});const e=await La(a,p,r.waitMaxAttempts,r.waitIntervalMs,r.progressCallback);return n.info("Inscription confirmation received",{jobId:p}),{confirmed:!0,result:{jobId:p,transactionId:p,topic_id:u.topic_id,status:u.status,completed:u.completed},inscription:e,sdk:a,costSummary:await Da(p,r.network||"mainnet",r.logging?.level)}}return{confirmed:!1,result:{jobId:p,transactionId:p,topic_id:u.topic_id,status:u.status,completed:u.completed},sdk:a,costSummary:await Da(p,r.network||"mainnet",r.logging?.level)}}catch(s){throw n.error("Error during inscription process",s),s}}async function Ma(e,t){const r=y.getInstance({module:"Inscriber",...t?.logging||{}}),i=e.includes("@")?`${e.split("@")[0]}-${e.split("@")[1].replace(/\./g,"-")}`:e;r.info("Retrieving inscription",{originalTransactionId:e,formattedTransactionId:i});try{let e;if(t?.apiKey)r.debug("Initializing InscriptionSDK with API key"),e=new es({apiKey:t.apiKey,network:t.network||"mainnet",baseURL:t.baseURL});else{if(!t?.accountId||!t?.privateKey){const e=new Error("Either API key or account ID and private key are required for retrieving inscriptions");throw r.error("Missing authentication credentials",{hasApiKey:Boolean(t?.apiKey),hasAccountId:Boolean(t?.accountId),hasPrivateKey:Boolean(t?.privateKey)}),e}r.debug("Initializing InscriptionSDK with server auth"),e=await es.createWithAuth({type:"server",accountId:t.accountId,privateKey:t.privateKey,network:t.network||"mainnet",baseUrl:t.baseURL})}r.debug("Initialized SDK for inscription retrieval",{formattedTransactionId:i,network:t.network||"mainnet"});const n=await e.retrieveInscription(i);return r.info("Successfully retrieved inscription",{formattedTransactionId:i}),n}catch(n){throw r.error("Error retrieving inscription",{formattedTransactionId:i,error:n}),n}}function Ua(e,t){const r=["name","creator","description","type"].filter(t=>!e[t]);if(r.length>0){const e=new Error(`Missing required Hashinal metadata fields: ${r.join(", ")}`);throw t.error("Hashinal metadata validation failed",{missingFields:r}),e}t.debug("Hashinal metadata validation passed",{name:e.name,creator:e.creator,description:e.description,type:e.type,hasAttributes:!!e.attributes,hasProperties:!!e.properties})}async function Ba(e,t,r,i){const n=y.getInstance({module:"Inscriber",...r.logging});n.info("Generating inscription quote",{type:e.type,mode:r.mode||"file",..."url"===e.type?{url:e.url}:{},..."file"===e.type?{path:e.path}:{},..."buffer"===e.type?{fileName:e.fileName,bufferSize:e.buffer.byteLength}:{}});try{!function(e,t,r){if(!e||"object"!=typeof e||!("type"in e))throw new Error("Invalid inscription input: type is required");if(!t||!t.accountId)throw new Error("Invalid client config: accountId is required");if(!r)throw new Error("Options are required");if("hashinal"===r.mode){if(!r.metadata)throw new Error("Hashinal mode requires metadata");const e=["name","creator","description","type"].filter(e=>!r.metadata||!r.metadata[e]);if(e.length>0)throw new Error(`Missing required Hashinal metadata fields: ${e.join(", ")}`)}}(e,t,r);const o=function(e,t,r){const i=ka.createCacheKey(e,t,r);return ka.get(i)}(e,t,r);if(o)return n.debug("Returning cached quote"),{confirmed:!1,quote:!0,result:o};"hashinal"===r.mode&&r.metadata&&Ua(r.metadata,n);const s=await Ea(t,r,i),a={holderId:t.accountId,metadata:r.metadata||{},tags:r.tags||[],mode:r.mode||"file",fileStandard:r.fileStandard,chunkSize:r.chunkSize};let c;switch(e.type){case"url":c={...a,file:{type:"url",url:e.url}};break;case"file":{const t=await za(e.path);c={...a,file:{type:"base64",base64:t.base64,fileName:t.fileName,mimeType:t.mimeType}};break}case"buffer":c={...a,file:{type:"base64",base64:globalThis.Buffer.from(e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer):e.buffer).toString("base64"),fileName:e.fileName,mimeType:e.mimeType}}}"hashinal"===r.mode&&(c.metadataObject=r.metadata,c.creator=r.metadata?.creator||t.accountId,c.description=r.metadata?.description,r.jsonFileURL&&(c.jsonFileURL=r.jsonFileURL)),n.debug("Calling inscription SDK startInscription for quote",{type:e.type,mode:r.mode||"file",holderId:t.accountId});const l=await s.startInscription(c);n.debug("Received inscription response for quote parsing",{hasTransactionBytes:!!l.transactionBytes,bytesLength:l.transactionBytes?.length||0,transactionBytesType:typeof l.transactionBytes,totalCost:l.totalCost});const u=await async function(e,t){try{let i="0.001";if(e.totalCost&&"number"==typeof e.totalCost){i=(e.totalCost/1e8).toString(),t.debug("Using totalCost from inscription response",{totalCostTinybars:e.totalCost,totalCostHbar:i})}else if(e.transactionBytes){t.debug("Parsing transaction bytes for cost information");try{let r;if("string"==typeof e.transactionBytes)r=e.transactionBytes;else{if(!e.transactionBytes||"object"!=typeof e.transactionBytes||!("data"in e.transactionBytes))throw new Error("Invalid transactionBytes format");r=globalThis.Buffer.from(e.transactionBytes.data).toString("base64")}t.debug("About to parse transaction bytes",{bytesLength:r.length,bytesPreview:r.slice(0,100)});const n=await ga.parseTransactionBytes(r,{includeRaw:!1});t.debug("Parsed transaction for quote",{type:n.type,hasTransfers:!!n.transfers,transferCount:n.transfers?.length||0,transfers:n.transfers});let o=0;if(n.transfers&&n.transfers.length>0)for(const e of n.transfers){const r="string"==typeof e.amount?parseFloat(e.amount):e.amount;if(r<0){const i=Math.abs(r);o+=i,t.debug("Found HBAR transfer",{from:e.accountId,to:"service",amount:i})}}o>0&&(i=o.toString(),t.debug("Using parsed transaction transfer amount",{totalTransferAmount:o,totalCostHbar:i}))}catch(r){t.warn("Could not parse transaction bytes, using totalCost fallback",{error:r,errorMessage:r instanceof Error?r.message:String(r)})}}const n=[{to:"Inscription Service",amount:i,description:`Inscription fee (${i} HBAR)`}],o={totalCostHbar:i,validUntil:new Date(Date.now()+9e5).toISOString(),breakdown:{transfers:n}};return t.debug("Successfully parsed transaction for quote",{totalCostHbar:o.totalCostHbar,transferCount:n.length,hasTransactionBytes:!!e.transactionBytes,hasTotalCost:!!e.totalCost}),o}catch(i){throw t.error("Error parsing transaction for quote",i),i}}(l,n);return function(e,t,r,i){const n=ka.createCacheKey(e,t,r);ka.set(n,i,6e5)}(e,t,r,u),n.info("Successfully generated inscription quote",{totalCostHbar:u.totalCostHbar}),{confirmed:!1,quote:!0,result:u}}catch(o){throw n.error("Error generating inscription quote",o),o}}async function La(e,t,r=450,i=4e3,n){const o=y.getInstance({module:"Inscriber"}),s=xa(t),a=new ts({module:"Inscriber",logger:o,callback:n});try{o.debug("Waiting for inscription confirmation",{transactionId:s,maxAttempts:r,intervalMs:i}),a.preparing("Preparing for inscription confirmation",5,{transactionId:s,maxAttempts:r,intervalMs:i});try{const t=e.waitForInscription.bind(e),n=e=>{const t=e.stage||"confirming",r=["preparing","submitting","confirming","verifying","completed","failed"].includes(t)?t:"confirming",i=e.message||"Processing inscription",n=e.progressPercent||50;a.report({stage:r,message:i,progressPercent:n,details:e.details})};return await t(s,r,i,!0,n)}catch(Pw){return o.debug("Falling back to standard waitForInscription method",{error:Pw}),a.verifying("Verifying inscription status",50,{error:Pw}),await e.waitForInscription(s,r,i,!0)}}catch(c){throw o.error("Error waiting for inscription confirmation",{transactionId:t,maxAttempts:r,intervalMs:i,error:c}),a.failed("Inscription confirmation failed",{transactionId:t,error:c}),c}}const Ka="https://hol.org/registry/api/v1";async function $a(e,t){const r=await fetch(e,t),i=await r.json().catch(()=>({}));if(!r.ok){const e="object"==typeof i&&i&&"error"in i?String(i.error):`HTTP ${r.status}`;throw new Error(e)}return i}function Ha(e){if(!e||"object"!=typeof e)return;const t=e,r=t.topicId||t.topic_id;if("string"==typeof r&&r.trim())return r;const i=t,n=i.topicId;if("string"==typeof n&&n.trim())return n;const o=i.topic_id;return"string"==typeof o&&o.trim()?o:void 0}var qa=(e=>(e.REGISTER_CONFIG="register-config",e.REGISTER="register",e))(qa||{}),ja=(e=>(e.EVM="evm",e.WASM="wasm",e))(ja||{});const Wa=t.z.object({name:t.z.string().optional(),type:t.z.string()}),Va=t.z.object({name:t.z.string(),inputs:t.z.array(Wa),outputs:t.z.array(Wa),stateMutability:t.z.enum(["view","pure"]),type:t.z.literal("function")}),Ga=t.z.enum(["number","string","bool"]),Ja=t.z.object({p:t.z.literal("hcs-7"),m:t.z.string().optional()}),Ya=Ja.extend({op:t.z.literal("register-config"),t:t.z.literal("evm"),c:t.z.object({contractAddress:t.z.string().regex(/^0x[a-fA-F0-9]{40}$/,"Invalid contract address"),abi:Va})}),Xa=Ja.extend({op:t.z.literal("register-config"),t:t.z.literal("wasm"),c:t.z.object({wasmTopicId:t.z.string(),inputType:t.z.object({stateData:t.z.record(Ga)}),outputType:t.z.object({type:t.z.literal("string"),format:t.z.literal("topic-id")})})}),Za=Ja.extend({op:t.z.literal("register"),t_id:t.z.string(),d:t.z.object({weight:t.z.number(),tags:t.z.array(t.z.string()).nonempty()}).catchall(t.z.unknown())}),Qa=t.z.union([Ya,Xa,Za]);class ec{constructor(e){this.network=e.network,this.logger=e.logger||y.getInstance({level:e.logLevel||"info",module:"HCS7Client",silent:e.silent}),this.mirrorNode=new x(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0)}generateRegistryMemo(e){return`hcs-7:indexed:${e}`}createConfigMessage(e){return e.config.type===ja.EVM?{p:"hcs-7",op:qa.REGISTER_CONFIG,t:ja.EVM,c:{contractAddress:e.config.contractAddress,abi:e.config.abi},m:e.memo}:{p:"hcs-7",op:qa.REGISTER_CONFIG,t:ja.WASM,c:{wasmTopicId:e.config.wasmTopicId,inputType:e.config.inputType,outputType:e.config.outputType},m:e.memo}}createMetadataMessage(e){return{p:"hcs-7",op:qa.REGISTER,t_id:e.metadataTopicId,m:e.memo,d:{weight:e.weight,tags:e.tags,...e.data||{}}}}validateMessage(e){const t=Qa.safeParse(e);if(t.success)return{valid:!0,errors:[]};const r=t.error.errors.map(e=>{const t=e.path.join(".");return t?`${t}: ${e.message}`:e.message});return this.logger.debug(`HCS-7 message validation failed: ${r.join(", ")}`),{valid:!1,errors:r}}async getRegistry(e,t){const r=[];try{const i=await this.mirrorNode.getTopicMessages(e,{limit:t?.limit,order:t?.order,sequenceNumber:t?.next});for(const e of i){if("hcs-7"!==e.p)continue;const t=Qa.safeParse(e);if(!t.success)continue;const i=t.data;r.push({sequenceNumber:Number(e.sequence_number),timestamp:e.consensus_timestamp||"",payer:e.payer||"",message:i})}}catch(i){this.logger.error("Failed to query HCS-7 registry",i)}return{topicId:e,entries:r}}}function tc(e){const t=e.topicSequenceNumber;return"number"==typeof t?t:"function"==typeof t?.toNumber?t.toNumber():"number"==typeof t?.low?t.low:void 0}function rc(e){return z({memo:`hcs-7:indexed:${e.ttl}`,submitKey:e.submitKey,adminKey:e.adminKey,operatorPublicKey:e.operatorPublicKey})}function ic(e){const t={p:"hcs-7",...e.message};return _({topicId:e.topicId,message:JSON.stringify(t),transactionMemo:e.transactionMemo})}class nc{constructor(){this.cache=new Map}get(e){return this.cache.get(e)}set(e,t){this.cache.set(e,t)}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}}function oc(e,t){return null==e?"0":e._isBigNumber?e.toString():t.startsWith("uint")||t.startsWith("int")?String(e):"bool"===t?e?"true":"false":"string"===t?e:"address"===t?String(e).toLowerCase():t.endsWith("[]")?Array.isArray(e)?e.map(e=>String(e)).join(","):"":String(e)}function sc(e){const t=Object.create(y.prototype);return t.debug=(...t)=>e.debug(...t),t.info=(...t)=>e.info(...t),t.warn=(...t)=>e.warn(...t),t.error=(...t)=>e.error(...t),t.trace=(...t)=>e.trace(...t),t.setLogLevel=t=>e.setLogLevel(t),t.getLevel=()=>e.getLevel(),t.setSilent=t=>e.setSilent(t),t.setModule=t=>e.setModule(t),t.logger={level:e.getLevel()},t.moduleContext="",t.formatArgs=()=>({msg:""}),t}function ac(e){return e instanceof y}async function cc(e,t,r){const i=new x(t,r),n=[];for(const s of e)try{const e=await i.getPublicKey(s);n.push(e)}catch(o){r&&r.warn(`Could not get public key for account ${s}: ${o}`)}return n}const lc="hcs-21",uc=1024,dc=1e3,pc=/^(?:hcs:\/\/1\/0\.0\.\d+|ipfs:\/\/\S+|ar:\/\/\S+|oci:\/\/\S+|https?:\/\/\S+)$/,hc=/^(?:0\.0\.\d+|hcs:\/\/1\/0\.0\.\d+(?:\/\d+)?|ipfs:\/\/\S+|ar:\/\/\S+|oci:\/\/\S+|https?:\/\/\S+)$/;var gc=(e=>(e[e.ADAPTER_REGISTRY=0]="ADAPTER_REGISTRY",e[e.REGISTRY_OF_REGISTRIES=1]="REGISTRY_OF_REGISTRIES",e[e.ADAPTER_CATEGORY=2]="ADAPTER_CATEGORY",e))(gc||{});const mc=t.z.object({registry:t.z.string().min(1),name:t.z.string().min(1),version:t.z.string().min(1),integrity:t.z.string().min(1)}),fc=t.z.object({type:t.z.string().min(1),account:t.z.string().min(1).optional(),threshold:t.z.string().min(1).optional(),ctopic:t.z.string().min(1).optional(),ttopic:t.z.string().min(1).optional(),stopic:t.z.string().min(1).optional()}).catchall(t.z.unknown()),yc=t.z.object({p:t.z.literal(lc),op:t.z.enum(["register","update","delete"]),adapter_id:t.z.string().min(1),entity:t.z.string().min(1),package:mc,manifest:t.z.string().regex(pc,"manifest must be an immutable pointer (hcs://1/<topicId>, ipfs://cid/path, ar://txid, oci://repo@digest, https://...#sha384-..)"),manifest_sequence:t.z.number().int().positive().optional(),config:fc,state_model:t.z.string().min(1).optional(),signature:t.z.string().min(1).optional()}),bc=t.z.object({meta:t.z.object({spec_version:t.z.string().min(1),adapter_version:t.z.string().min(1),minimum_version:t.z.string().min(1).optional(),generated:t.z.string().min(1)}),adapter:t.z.object({name:t.z.string().min(1),id:t.z.string().min(1),maintainers:t.z.array(t.z.object({name:t.z.string().min(1),contact:t.z.string().min(1)})).min(1),license:t.z.string().min(1)}),package:t.z.object({registry:t.z.string().min(1),dist_tag:t.z.string().min(1).optional(),artifacts:t.z.array(t.z.object({url:t.z.string().min(1),digest:t.z.string().min(1),signature:t.z.string().min(1).optional()})).min(1)}),runtime:t.z.object({platforms:t.z.array(t.z.string().min(1)).min(1),primary:t.z.string().min(1),entry:t.z.string().min(1),dependencies:t.z.array(t.z.string().min(1)).optional(),env:t.z.array(t.z.string().min(1)).optional()}),capabilities:t.z.object({discovery:t.z.boolean(),communication:t.z.boolean(),protocols:t.z.array(t.z.string().min(1)),discovery_tags:t.z.array(t.z.string().min(1)).optional(),communication_channels:t.z.array(t.z.string().min(1)).optional(),extras:t.z.record(t.z.string(),t.z.unknown()).optional()}),consensus:t.z.object({state_model:t.z.string().min(1).optional(),profile_uri:t.z.string().min(1).optional(),entity_schema:t.z.string().min(1).optional(),required_fields:t.z.array(t.z.string().min(1)),hashing:t.z.literal("sha384")})}),wc=t.z.object({version:t.z.string().min(1),name:t.z.string().min(1),description:t.z.string().min(1),operator:t.z.object({account:t.z.string().min(1),name:t.z.string().optional(),contact:t.z.string().optional()}),entityTypes:t.z.array(t.z.string().min(1)),categories:t.z.array(t.z.string().min(1)).optional(),tags:t.z.array(t.z.string().min(1)).optional(),links:t.z.record(t.z.string().min(1)).optional()}),Ic=t.z.union([bc,wc]);var Tc=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(Tc||{}),Sc=(e=>(e[e.TEXT_GENERATION=0]="TEXT_GENERATION",e[e.IMAGE_GENERATION=1]="IMAGE_GENERATION",e[e.AUDIO_GENERATION=2]="AUDIO_GENERATION",e[e.VIDEO_GENERATION=3]="VIDEO_GENERATION",e[e.CODE_GENERATION=4]="CODE_GENERATION",e[e.LANGUAGE_TRANSLATION=5]="LANGUAGE_TRANSLATION",e[e.SUMMARIZATION_EXTRACTION=6]="SUMMARIZATION_EXTRACTION",e[e.KNOWLEDGE_RETRIEVAL=7]="KNOWLEDGE_RETRIEVAL",e[e.DATA_INTEGRATION=8]="DATA_INTEGRATION",e[e.MARKET_INTELLIGENCE=9]="MARKET_INTELLIGENCE",e[e.TRANSACTION_ANALYTICS=10]="TRANSACTION_ANALYTICS",e[e.SMART_CONTRACT_AUDIT=11]="SMART_CONTRACT_AUDIT",e[e.GOVERNANCE_FACILITATION=12]="GOVERNANCE_FACILITATION",e[e.SECURITY_MONITORING=13]="SECURITY_MONITORING",e[e.COMPLIANCE_ANALYSIS=14]="COMPLIANCE_ANALYSIS",e[e.FRAUD_DETECTION=15]="FRAUD_DETECTION",e[e.MULTI_AGENT_COORDINATION=16]="MULTI_AGENT_COORDINATION",e[e.API_INTEGRATION=17]="API_INTEGRATION",e[e.WORKFLOW_AUTOMATION=18]="WORKFLOW_AUTOMATION",e))(Sc||{});const kc=t.z.nativeEnum(Sc),vc=t.z.union([t.z.number(),t.z.string()]),Ec=t.z.union([t.z.string(),t.z.number(),t.z.boolean(),t.z.null()]),Ac=t.z.lazy(()=>t.z.union([Ec,t.z.array(Ac),t.z.record(Ac)])),Cc=t.z.object({version:t.z.string(),type:t.z.number(),display_name:t.z.string(),alias:t.z.string().optional(),bio:t.z.string().optional(),socials:t.z.array(Ac).optional(),aiAgent:t.z.object({type:t.z.nativeEnum(Tc),creator:t.z.string().optional(),model:t.z.string().optional(),capabilities:t.z.array(t.z.union([kc,t.z.number()])).optional()}).optional(),uaid:t.z.string().optional()}).catchall(Ac),Rc=t.z.object({uaid:t.z.string().optional(),ledgerAccountId:t.z.string().optional(),userId:t.z.string().optional(),email:t.z.string().optional(),encryptedShare:t.z.string()}),xc=t.z.object({algorithm:t.z.string(),ciphertext:t.z.string(),nonce:t.z.string(),associatedData:t.z.string().optional(),keyLocator:t.z.object({sessionId:t.z.string().optional(),revision:t.z.number().optional()}).optional(),recipients:t.z.array(Rc)}),Nc=t.z.object({keyType:t.z.string(),publicKey:t.z.string(),uaid:t.z.string().optional(),ledgerAccountId:t.z.string().optional(),userId:t.z.string().optional(),email:t.z.string().optional()}),zc=t.z.object({role:t.z.enum(["requester","responder"]),uaid:t.z.string().optional(),userId:t.z.string().optional(),ledgerAccountId:t.z.string().optional(),keyType:t.z.string(),longTermPublicKey:t.z.string().optional(),ephemeralPublicKey:t.z.string(),signature:t.z.string().optional(),metadata:t.z.record(Ac).optional(),submittedAt:t.z.string()}),_c=t.z.object({sessionId:t.z.string(),algorithm:t.z.string(),createdAt:t.z.string(),expiresAt:t.z.number(),status:t.z.enum(["pending","complete"]),requester:zc.optional(),responder:zc.optional()}),Pc=t.z.object({enabled:t.z.boolean(),algorithm:t.z.string(),requireCiphertext:t.z.boolean(),requester:Nc.nullable().optional(),responder:Nc.nullable().optional(),handshake:_c.nullable().optional()}),Oc=t.z.object({messageId:t.z.string(),role:t.z.enum(["user","agent"]),content:t.z.string(),timestamp:t.z.string(),cipherEnvelope:xc.optional(),metadata:t.z.record(Ac).optional()}),Dc=t.z.record(t.z.union([t.z.array(Ac),t.z.record(Ac),Ac])).optional(),Fc=t.z.object({delegationRoles:Ac.optional(),delegationTaskTags:Ac.optional(),delegationProtocols:Ac.optional(),delegationSummary:Ac.optional(),delegationSignals:Ac.optional()}).passthrough(),Mc=t.z.object({id:t.z.string(),uaid:t.z.string(),registry:t.z.string(),name:t.z.string(),description:t.z.string().optional(),capabilities:t.z.array(vc),endpoints:t.z.union([t.z.record(Ac),t.z.array(t.z.string())]).optional(),metadata:Fc.optional(),metadataFacet:Dc,profile:Cc.optional(),protocols:t.z.array(t.z.string()).optional(),adapter:t.z.string().optional(),originalId:t.z.string().optional(),communicationSupported:t.z.boolean().optional(),routingSupported:t.z.boolean().optional(),available:t.z.boolean().optional(),availabilityStatus:t.z.string().optional(),availabilityCheckedAt:t.z.string().optional(),availabilitySource:t.z.string().optional(),availabilityLatencyMs:t.z.number().optional(),availabilityScore:t.z.number().optional(),capabilityLabels:t.z.array(t.z.string()).optional(),capabilityTokens:t.z.array(t.z.string()).optional(),image:t.z.string().optional(),createdAt:t.z.string().optional(),updatedAt:t.z.string().optional(),lastSeen:t.z.string().optional(),lastIndexed:t.z.string().optional()}).passthrough(),Uc=t.z.object({hits:t.z.array(Mc),total:t.z.number(),page:t.z.number(),limit:t.z.number()}),Bc=t.z.object({totalAgents:t.z.number(),registries:t.z.record(t.z.number()),capabilities:t.z.record(t.z.number()),lastUpdate:t.z.string(),status:t.z.string()}),Lc=t.z.object({registries:t.z.array(t.z.string())}),Kc=t.z.object({searches:t.z.array(t.z.string())}),$c=t.z.object({agent:Mc}),Hc=t.z.object({uaid:t.z.string(),label:t.z.string(),registry:t.z.string().optional(),agent:Mc,score:t.z.number(),matchedQueries:t.z.array(t.z.string()).optional(),matchedRoles:t.z.array(t.z.string()).optional(),matchedProtocols:t.z.array(t.z.string()).optional(),matchedSurfaces:t.z.array(t.z.string()).optional(),matchedLanguages:t.z.array(t.z.string()).optional(),matchedArtifacts:t.z.array(t.z.string()).optional(),matchedTaskTags:t.z.array(t.z.string()).optional(),reasons:t.z.array(t.z.string()).optional(),suggestedMessage:t.z.string().optional(),trustScore:t.z.number().optional(),verified:t.z.boolean().optional(),communicationSupported:t.z.boolean().optional(),availability:t.z.boolean().optional(),explanation:t.z.string().optional()}).passthrough(),qc=t.z.object({id:t.z.string(),title:t.z.string(),reason:t.z.string(),role:t.z.string(),type:t.z.enum(["ai-agents","mcp-servers"]),suggestedMode:t.z.enum(["best-match","fallback","parallel"]),searchQueries:t.z.array(t.z.string()),protocols:t.z.array(t.z.string()).optional(),surfaces:t.z.array(t.z.string()).optional(),languages:t.z.array(t.z.string()).optional(),artifacts:t.z.array(t.z.string()).optional(),candidates:t.z.array(Hc)}).passthrough(),jc=t.z.object({action:t.z.enum(["delegate-now","review-shortlist","handle-locally"]),confidence:t.z.number(),reason:t.z.string(),opportunityId:t.z.string().optional(),candidate:Hc.optional()}).passthrough(),Wc=t.z.object({task:t.z.string(),context:t.z.string().optional(),summary:t.z.string().optional(),intents:t.z.array(t.z.string()),protocols:t.z.array(t.z.string()),surfaces:t.z.array(t.z.string()),languages:t.z.array(t.z.string()).optional(),artifacts:t.z.array(t.z.string()).optional(),shouldDelegate:t.z.boolean(),localFirstReason:t.z.string().optional(),recommendation:jc.optional(),opportunities:t.z.array(qc)}).passthrough(),Vc=t.z.object({averageScore:t.z.number(),totalFeedbacks:t.z.number(),registry:t.z.string().optional(),network:t.z.string().optional(),updatedAt:t.z.string().optional()}),Gc=t.z.object({registry:t.z.string(),network:t.z.string().optional(),agentId:t.z.number(),client:t.z.string(),score:t.z.number(),tag1:t.z.string().nullable().optional(),tag2:t.z.string().nullable().optional(),revoked:t.z.boolean(),feedbackIndex:t.z.number().nullable().optional(),fileUri:t.z.string().nullable().optional(),fileHash:t.z.string().nullable().optional(),createdAt:t.z.string().nullable().optional()}),Jc=t.z.object({uaid:t.z.string(),summary:Vc,entries:t.z.array(Gc)}),Yc=t.z.object({uaid:t.z.string(),sessionId:t.z.string(),eligible:t.z.boolean(),messageCount:t.z.number(),minimumMessages:t.z.number(),reason:t.z.string().optional(),onchain:t.z.object({eligible:t.z.boolean(),reason:t.z.string().optional(),estimatedCredits:t.z.number().optional(),usdEstimate:t.z.number().optional(),nativeFeeEstimate:t.z.number().optional()}).optional()}),Xc=t.z.object({uaid:t.z.string(),registry:t.z.string(),network:t.z.string().optional(),agentId:t.z.number(),score:t.z.number(),tag1:t.z.string().nullable().optional(),tag2:t.z.string().nullable().optional(),fileUri:t.z.string().nullable().optional(),fileHash:t.z.string().nullable().optional(),feedbackIndex:t.z.number().nullable().optional(),transactionHash:t.z.string().nullable().optional(),signature:t.z.string().nullable().optional(),submittedAt:t.z.string()}),Zc=t.z.object({page:t.z.number(),limit:t.z.number(),total:t.z.number(),items:t.z.array(t.z.object({uaid:t.z.string(),registry:t.z.string(),network:t.z.string().optional(),agentId:t.z.number().nullable().optional(),summary:Vc.nullable(),trustScore:t.z.number().nullable().optional()}))}),Qc=t.z.object({page:t.z.number(),limit:t.z.number(),total:t.z.number(),items:t.z.array(t.z.object({uaid:t.z.string(),entry:Gc}))}),el=t.z.object({sessionId:t.z.string(),uaid:t.z.string().nullable().optional(),agent:t.z.object({name:t.z.string(),description:t.z.string().optional(),capabilities:t.z.record(Ac).nullable().optional(),skills:t.z.array(t.z.string()).optional()}),history:t.z.array(Oc).optional().default([]),historyTtlSeconds:t.z.number().nullable().optional(),encryption:Pc.nullable().optional()}),tl=t.z.object({sessionId:t.z.string(),uaid:t.z.string().nullable().optional(),message:t.z.string(),timestamp:t.z.string(),rawResponse:Ac.optional(),content:t.z.string().optional(),ops:t.z.array(t.z.record(Ac)).optional(),history:t.z.array(Oc).optional(),historyTtlSeconds:t.z.number().nullable().optional(),encrypted:t.z.boolean().optional()}),rl=t.z.object({sessionId:t.z.string(),history:t.z.array(Oc),historyTtlSeconds:t.z.number()});t.z.object({preserveEntries:t.z.number().int().min(0).optional()}).strict();const il=t.z.object({sessionId:t.z.string(),history:t.z.array(Oc),summaryEntry:Oc,preservedEntries:t.z.array(Oc),historyTtlSeconds:t.z.number(),creditsDebited:t.z.number(),metadata:t.z.record(Ac).optional()}),nl=t.z.object({sessionId:t.z.string(),encryption:Pc.nullable()}),ol=t.z.object({sessionId:t.z.string(),handshake:_c}),sl=t.z.object({id:t.z.string(),keyType:t.z.string(),publicKey:t.z.string(),uaid:t.z.string().nullable(),ledgerAccountId:t.z.string().nullable(),ledgerNetwork:t.z.string().nullable().optional(),userId:t.z.string().nullable().optional(),email:t.z.string().nullable().optional(),createdAt:t.z.string(),updatedAt:t.z.string()}),al=t.z.object({challengeId:t.z.string(),message:t.z.string(),expiresAt:t.z.string()}),cl=t.z.object({id:t.z.string(),label:t.z.string().optional(),prefix:t.z.string(),lastFour:t.z.string(),createdAt:t.z.string(),lastUsedAt:t.z.string().nullable().optional(),ownerType:t.z.literal("ledger"),ledgerAccountId:t.z.string().optional(),ledgerNetwork:t.z.string().optional(),ledgerNetworkCanonical:t.z.string().optional()}),ll=t.z.object({key:t.z.string(),apiKey:cl,accountId:t.z.string(),network:t.z.string(),networkCanonical:t.z.string().optional()}),ul=t.z.object({protocols:t.z.array(t.z.string())}),dl=t.z.object({protocol:t.z.string().nullable()}),pl=t.z.object({hits:t.z.array(Mc),total:t.z.number(),page:t.z.number().optional(),limit:t.z.number().optional()}),hl=t.z.union([t.z.string(),t.z.number()]),gl=t.z.object({capabilities:t.z.array(hl).optional(),type:t.z.enum(["ai-agents","mcp-servers"]).optional(),registry:t.z.string().optional(),protocols:t.z.array(t.z.string()).optional(),adapter:t.z.array(t.z.string()).optional()}).strict();t.z.object({query:t.z.string(),filter:gl.optional(),limit:t.z.number().int().min(1).max(100).optional(),offset:t.z.number().int().min(0).optional()}).strict();const ml=t.z.object({agent:Mc,score:t.z.number().optional(),highlights:t.z.record(t.z.array(t.z.string())).optional()}),fl=t.z.object({hits:t.z.array(ml),total:t.z.number(),took:t.z.number(),totalAvailable:t.z.number().optional(),visible:t.z.number().optional(),limited:t.z.boolean().optional(),credits_used:t.z.number().optional()}),yl=t.z.object({enabled:t.z.boolean(),healthy:t.z.boolean(),mode:t.z.enum(["disabled","initializing","healthy","degraded","error"]),lastUpdated:t.z.string(),details:t.z.record(t.z.any()).optional(),lastError:t.z.object({message:t.z.string(),stack:t.z.string().optional(),timestamp:t.z.string().optional()}).optional()}),bl=t.z.object({storageMode:t.z.string(),vectorStatus:yl}),wl=t.z.object({clients:t.z.number(),stats:t.z.object({totalClients:t.z.number().optional(),clientsByRegistry:t.z.record(t.z.number()).optional(),clientsByEventType:t.z.record(t.z.number()).optional()}).passthrough()}),Il=t.z.object({p50:t.z.number(),p90:t.z.number(),p95:t.z.number(),p99:t.z.number()}),Tl=t.z.object({http:t.z.object({requestsTotal:t.z.number(),activeConnections:t.z.number(),requestDuration:Il}),search:t.z.object({queriesTotal:t.z.number(),queryDuration:Il}),indexing:t.z.object({agentsTotal:t.z.number(),crawlErrors:t.z.number()}),registration:t.z.object({total:t.z.number(),failures:t.z.number(),duration:Il}),cache:t.z.object({hits:t.z.number(),misses:t.z.number(),hitRate:t.z.number()}),websocket:t.z.object({connections:t.z.number()})}),Sl=t.z.object({uaid:t.z.string(),valid:t.z.boolean(),formats:t.z.array(t.z.string())}),kl=t.z.object({id:t.z.string(),agentId:t.z.string(),protocol:t.z.string(),endpoint:t.z.string(),status:t.z.enum(["connected","disconnected","error"]),metadata:t.z.record(Ec).optional(),createdAt:t.z.string()}),vl=t.z.object({connected:t.z.boolean(),connection:kl.optional(),adapter:t.z.string().optional(),agentId:t.z.string().optional()}),El=t.z.object({operatorId:t.z.string().optional(),adapters:t.z.array(t.z.object({name:t.z.string(),version:t.z.string(),status:t.z.string(),agentCount:t.z.number(),lastDiscovery:t.z.string(),registryType:t.z.string(),health:t.z.string()})).optional(),totalAgents:t.z.number().optional(),elasticsearchDocumentCount:t.z.number().optional(),agentsByAdapter:t.z.record(t.z.number()).optional(),agentsByRegistry:t.z.record(t.z.number()).optional(),systemInfo:t.z.object({uptime:t.z.number().optional(),version:t.z.string().optional(),network:t.z.string().optional()}).optional()}),Al=t.z.object({id:t.z.string(),name:t.z.string(),type:t.z.string(),endpoint:t.z.string().optional(),capabilities:t.z.array(vc),registry:t.z.string().optional(),protocol:t.z.string().optional(),profile:Cc.optional(),nativeId:t.z.string().optional(),metadata:t.z.record(Ac).optional()}),Cl=t.z.object({tId:t.z.string().nullable(),sizeBytes:t.z.number().optional()}),Rl=t.z.object({topicId:t.z.string().optional(),sequenceNumber:t.z.number().optional(),profileReference:t.z.string().optional(),profileTopicId:t.z.string().optional()}).passthrough().nullable().optional(),xl=t.z.object({registry:t.z.string(),status:t.z.enum(["created","duplicate","skipped","error","updated","pending"]),agentId:t.z.string().nullable().optional(),agentUri:t.z.string().nullable().optional(),error:t.z.string().optional(),metadata:t.z.record(Ac).optional(),registryKey:t.z.string().optional(),networkId:t.z.string().optional(),networkName:t.z.string().optional(),chainId:t.z.number().optional(),estimatedCredits:t.z.number().nullable().optional(),gasEstimateCredits:t.z.number().nullable().optional(),gasEstimateUsd:t.z.number().nullable().optional(),gasPriceGwei:t.z.number().nullable().optional(),gasLimit:t.z.number().nullable().optional(),creditMode:t.z.enum(["fixed","gas"]).nullable().optional(),minCredits:t.z.number().nullable().optional(),consumedCredits:t.z.number().nullable().optional(),cost:t.z.object({credits:t.z.number(),usd:t.z.number(),eth:t.z.number(),gasUsedWei:t.z.string(),effectiveGasPriceWei:t.z.string().nullable().optional(),transactions:t.z.array(t.z.object({hash:t.z.string(),gasUsedWei:t.z.string(),effectiveGasPriceWei:t.z.string().nullable().optional(),costWei:t.z.string()})).optional()}).optional()}),Nl=t.z.object({base:t.z.number(),additional:t.z.number(),total:t.z.number()}),zl=t.z.object({status:t.z.string(),uaid:t.z.string().optional(),transactionId:t.z.string().optional(),consensusTimestamp:t.z.string().optional(),registryTopicId:t.z.string().optional(),topicSequenceNumber:t.z.number().optional(),payloadHash:t.z.string().optional(),profileReference:t.z.string().optional(),tId:t.z.string().optional(),profileSizeBytes:t.z.number().optional(),error:t.z.string().optional()}).passthrough(),_l=t.z.object({key:t.z.string(),registryId:t.z.string().optional(),networkId:t.z.string().optional(),name:t.z.string().optional(),chainId:t.z.number().optional(),label:t.z.string().optional(),estimatedCredits:t.z.number().nullable().optional(),baseCredits:t.z.number().nullable().optional(),gasPortionCredits:t.z.number().nullable().optional(),gasPortionUsd:t.z.number().nullable().optional(),gasEstimateCredits:t.z.number().nullable().optional(),gasEstimateUsd:t.z.number().nullable().optional(),gasPriceGwei:t.z.number().nullable().optional(),gasLimit:t.z.number().nullable().optional(),minCredits:t.z.number().nullable().optional(),creditMode:t.z.string().nullable().optional()}).passthrough(),Pl=t.z.object({id:t.z.string(),label:t.z.string(),networks:t.z.array(_l)}),Ol=t.z.object({registries:t.z.array(Pl)}),Dl=t.z.object({success:t.z.literal(!0),status:t.z.enum(["created","duplicate","updated"]).optional(),uaid:t.z.string(),agentId:t.z.string(),message:t.z.string().optional(),registry:t.z.string().optional(),attemptId:t.z.string().nullable().optional(),agent:Al,openConvAI:t.z.object({compatible:t.z.boolean(),hcs11Profile:Cc.optional(),bridgeEndpoint:t.z.string().optional()}).optional(),profile:Cl.optional(),profileRegistry:Rl.nullable().optional(),hcs10Registry:zl.nullable().optional(),credits:Nl.optional(),additionalRegistries:t.z.array(xl).optional(),additionalRegistryCredits:t.z.array(xl).optional(),additionalRegistryCostPerRegistry:t.z.number().optional(),additionalRegistrySecrets:t.z.record(t.z.string(),t.z.record(Ac)).optional()}),Fl=t.z.object({success:t.z.literal(!0),status:t.z.literal("pending"),message:t.z.string(),uaid:t.z.string(),agentId:t.z.string(),registry:t.z.string().optional(),attemptId:t.z.string().nullable(),agent:Al,openConvAI:t.z.object({compatible:t.z.boolean(),hcs11Profile:Cc.optional(),bridgeEndpoint:t.z.string().optional()}).optional(),profile:Cl.optional(),profileRegistry:Rl.nullable().optional(),hcs10Registry:zl.nullable().optional(),credits:Nl,additionalRegistries:t.z.array(xl),additionalRegistryCredits:t.z.array(xl).optional(),additionalRegistryCostPerRegistry:t.z.number().optional(),additionalRegistrySecrets:t.z.record(t.z.string(),t.z.record(Ac)).optional()}),Ml=t.z.object({success:t.z.literal(!1),status:t.z.literal("partial"),message:t.z.string(),uaid:t.z.string(),agentId:t.z.string(),registry:t.z.string().optional(),attemptId:t.z.string().nullable().optional(),agent:Al,openConvAI:t.z.object({compatible:t.z.boolean(),hcs11Profile:Cc.optional(),bridgeEndpoint:t.z.string().optional()}).optional(),profile:Cl.optional(),profileRegistry:Rl.nullable().optional(),hcs10Registry:zl.nullable().optional(),credits:Nl.optional(),additionalRegistries:t.z.array(xl).optional(),additionalRegistryCredits:t.z.array(xl).optional(),additionalRegistryCostPerRegistry:t.z.number().optional(),additionalRegistrySecrets:t.z.record(t.z.string(),t.z.record(Ac)).optional(),errors:t.z.array(t.z.object({registry:t.z.string(),registryKey:t.z.string().nullable().optional(),error:t.z.string()})).min(1)}),Ul=t.z.union([Dl,Fl,Ml]),Bl=t.z.object({registryId:t.z.string(),registryKey:t.z.string(),networkId:t.z.string().optional(),networkName:t.z.string().optional(),chainId:t.z.number().optional(),label:t.z.string().optional(),status:t.z.enum(["pending","in_progress","completed","failed"]),error:t.z.string().optional(),credits:t.z.number().nullable().optional(),agentId:t.z.string().nullable().optional(),agentUri:t.z.string().nullable().optional(),metadata:t.z.record(Ac).optional(),lastUpdated:t.z.string()}),Ll=t.z.object({attemptId:t.z.string(),mode:t.z.enum(["register","update"]),status:t.z.enum(["pending","partial","completed","failed"]),uaid:t.z.string().optional(),agentId:t.z.string().optional(),registryNamespace:t.z.string(),accountId:t.z.string().optional(),startedAt:t.z.string(),completedAt:t.z.string().optional(),primary:t.z.object({status:t.z.enum(["pending","completed","failed"]),finishedAt:t.z.string().optional(),error:t.z.string().optional()}),additionalRegistries:t.z.record(t.z.string(),Bl),errors:t.z.array(t.z.string()).optional()}),Kl=t.z.object({progress:Ll}),$l=t.z.object({accountId:t.z.string().nullable().optional(),registry:t.z.string().optional(),protocol:t.z.string().optional(),requiredCredits:t.z.number(),availableCredits:t.z.number().nullable().optional(),shortfallCredits:t.z.number().nullable().optional(),creditsPerHbar:t.z.number().nullable().optional(),estimatedHbar:t.z.number().nullable().optional()}),Hl=t.z.object({success:t.z.boolean().optional(),purchaser:t.z.string(),credits:t.z.number(),hbarAmount:t.z.number(),transactionId:t.z.string(),consensusTimestamp:t.z.string().nullable().optional()}),ql=t.z.object({success:t.z.boolean().optional(),transaction:t.z.string().optional(),network:t.z.string().optional(),payer:t.z.string().optional(),errorReason:t.z.string().optional()}).strict(),jl=t.z.object({success:t.z.boolean(),accountId:t.z.string(),creditedCredits:t.z.number(),usdAmount:t.z.number(),balance:t.z.number(),payment:t.z.object({payer:t.z.string().optional(),requirement:t.z.record(Ac).optional(),settlement:ql.optional()}).optional()}),Wl=t.z.object({minimums:t.z.record(t.z.object({network:t.z.string().optional(),gasLimit:t.z.number().optional(),gasPriceWei:t.z.string().optional(),gasUsd:t.z.number().optional(),minUsd:t.z.number().optional(),ethUsd:t.z.number().optional(),fetchedAt:t.z.string().optional(),source:t.z.string().optional()})).optional(),creditUnitUsd:t.z.number().optional()}),Vl=t.z.object({adapters:t.z.array(t.z.string())}),Gl=t.z.object({id:t.z.number().int(),network:t.z.string(),type:t.z.string(),slug:t.z.string(),name:t.z.string(),description:t.z.string().nullable().optional(),topicId:t.z.string(),versionTopicId:t.z.string(),registryTransactionId:t.z.string().nullable().optional(),versionTransactionId:t.z.string().nullable().optional(),metadataPointer:t.z.string().nullable().optional(),metadataSequence:t.z.number().int().nullable().optional(),createdAt:t.z.string(),updatedAt:t.z.string(),metadata:Ac.optional().nullable()}),Jl=t.z.object({categories:t.z.array(Gl)}),Yl=t.z.object({id:t.z.union([t.z.string(),t.z.number()]).optional(),network:t.z.string().optional(),categoryId:t.z.union([t.z.string(),t.z.number()]).nullable().optional(),operation:t.z.string().optional(),adapterId:t.z.string(),adapterName:t.z.string(),entity:t.z.string(),manifestPointer:t.z.string().nullable().optional(),manifestSequence:t.z.number().int().nullable().optional(),packageRegistry:t.z.string().nullable().optional(),packageName:t.z.string().nullable().optional(),packageVersion:t.z.string().nullable().optional(),packageIntegrity:t.z.string().nullable().optional(),stateModel:t.z.string().nullable().optional(),config:Ac.nullable().optional(),signature:t.z.string().nullable().optional(),manifest:Ac.nullable().optional(),keywords:t.z.array(t.z.string()).optional(),searchText:t.z.string().nullable().optional(),creditAccountId:t.z.string().nullable().optional(),registeredByUserId:t.z.string().nullable().optional(),registeredByEmail:t.z.string().nullable().optional(),totalCostHbar:t.z.number().nullable().optional(),totalCostCredits:t.z.number().nullable().optional(),consensusTimestamp:t.z.string().nullable().optional(),sequenceNumber:t.z.number().int().nullable().optional(),payerAccountId:t.z.string().nullable().optional(),mirrorNodePayload:Ac.nullable().optional(),versionTopicId:t.z.string().nullable().optional(),declarationTopicId:t.z.string().nullable().optional(),categoryEntrySequence:t.z.number().int().nullable().optional(),categoryEntryTransactionId:t.z.string().nullable().optional(),versionPointerSequence:t.z.number().int().nullable().optional(),versionPointerTransactionId:t.z.string().nullable().optional(),transactionId:t.z.string().nullable().optional(),createdAt:t.z.string().optional(),category:Gl.optional()}).passthrough(),Xl=t.z.object({network:t.z.string(),adapters:t.z.array(Yl)}),Zl=t.z.object({category:Gl});t.z.object({adapter:t.z.record(Ac),declaration:yc,transactionId:t.z.string().optional().nullable(),category:Gl});const Ql=t.z.object({submissionId:t.z.string(),status:t.z.string().optional(),network:t.z.string().optional(),message:t.z.string().optional()}).passthrough(),eu=t.z.object({submission:t.z.object({id:t.z.string(),network:t.z.string(),status:t.z.enum(["pending","running","completed","failed"]),adapterId:t.z.string(),categorySlug:t.z.string().nullable().optional(),creditAccountId:t.z.string().nullable().optional(),registeredByUserId:t.z.string().nullable().optional(),registeredByEmail:t.z.string().nullable().optional(),requestPayload:Ac.optional(),resultPayload:Ac.nullable().optional(),error:t.z.string().nullable().optional(),createdAt:t.z.string().optional(),updatedAt:t.z.string().optional(),startedAt:t.z.string().nullable().optional(),completedAt:t.z.string().nullable().optional()}).passthrough()}),tu=t.z.object({supportsChat:t.z.boolean(),delivery:t.z.string().optional(),transport:t.z.string().optional(),streaming:t.z.boolean().optional(),requiresAuth:t.z.array(t.z.string()).optional(),notes:t.z.string().optional()}),ru=t.z.object({discovery:t.z.boolean(),routing:t.z.boolean(),communication:t.z.boolean(),translation:t.z.boolean(),protocols:t.z.array(t.z.string())}),iu=t.z.object({id:t.z.string(),name:t.z.string(),version:t.z.string(),author:t.z.string(),description:t.z.string(),supportedProtocols:t.z.array(t.z.string()),registryType:t.z.enum(["web2","web3","hybrid"]),chatProfile:tu.optional(),capabilities:ru,enabled:t.z.boolean(),priority:t.z.number(),status:t.z.enum(["running","stopped"])}),nu=t.z.object({adapters:t.z.array(iu)}),ou=t.z.object({value:t.z.union([t.z.string(),t.z.number(),t.z.boolean()]),label:t.z.string()}),su=t.z.object({key:t.z.string(),label:t.z.string(),description:t.z.string().optional(),type:t.z.enum(["string","boolean","number"]),adapters:t.z.array(t.z.string()).optional(),options:t.z.array(ou).optional()}),au=t.z.object({facets:t.z.array(su)}),cu=t.z.object({ownerType:t.z.string(),ownerId:t.z.string(),ownerHandle:t.z.string().optional(),verifiedAt:t.z.string().optional(),method:t.z.string().optional()}).passthrough(),lu=t.z.object({challengeId:t.z.string(),code:t.z.string(),expiresAt:t.z.string(),expectedHandle:t.z.string(),instructions:t.z.string(),existingOwnership:cu.optional()}).passthrough(),uu=t.z.object({challengeId:t.z.string(),uaid:t.z.string(),code:t.z.string(),expiresAt:t.z.string(),status:t.z.string(),message:t.z.string().optional()}).passthrough(),du=t.z.object({verified:t.z.boolean(),uaid:t.z.string(),ownerType:t.z.string(),ownerId:t.z.string(),ownerHandle:t.z.string().optional(),method:t.z.string().optional(),verificationPostUrl:t.z.string().optional()}).passthrough(),pu=t.z.object({uaid:t.z.string(),ownerType:t.z.string(),ownerId:t.z.string(),ownerHandle:t.z.string().optional(),chain:t.z.string(),verifiedAt:t.z.string(),method:t.z.string()}).passthrough(),hu=t.z.object({uaid:t.z.string(),verified:t.z.boolean(),chain:t.z.string().nullable()}).passthrough(),gu=t.z.object({verified:t.z.boolean(),uaid:t.z.string(),ownerType:t.z.string(),ownerId:t.z.string()}).passthrough(),mu=t.z.object({code:t.z.string(),message:t.z.string(),details:t.z.record(Ac).optional()}).passthrough(),fu=t.z.object({uaid:t.z.string(),verified:t.z.boolean(),profileId:t.z.string(),checkedAt:t.z.string(),nativeId:t.z.string().optional(),dnsName:t.z.string().optional(),verificationLevel:t.z.string().optional(),resolutionMode:t.z.string().optional(),reconstructedUaid:t.z.string().optional(),selectedFollowupProfile:t.z.string().optional(),error:mu.optional(),source:t.z.string().optional(),persisted:t.z.boolean().optional()}).passthrough(),yu=t.z.object({registered:t.z.boolean(),agent:Ac.optional()}).passthrough(),bu=t.z.object({ok:t.z.boolean(),uaid:t.z.string(),registered:t.z.boolean(),registeredAt:t.z.string().optional(),agent:Ac.optional(),warning:t.z.string().optional()}).passthrough(),wu=t.z.union([t.z.literal("skill-md"),t.z.literal("skill-json"),t.z.literal("skill-icon"),t.z.literal("file")]),Iu=t.z.record(t.z.number()).refine(e=>"number"==typeof e.total&&Number.isFinite(e.total),{message:"trustScores.total is required"}),Tu=t.z.enum(["safe","review","caution","unsafe"]),Su=t.z.object({score:t.z.number(),label:Tu,findingsTotal:t.z.number().int(),highFindings:t.z.number().int(),scriptsTotal:t.z.number().int(),permissionsMissing:t.z.array(t.z.string())}).passthrough(),ku=t.z.enum(["low","medium","high"]),vu=t.z.object({ruleId:t.z.string(),severity:ku,file:t.z.string(),message:t.z.string()}).passthrough(),Eu=t.z.object({name:t.z.string(),mimeType:t.z.string(),role:wu,topicId:t.z.string().optional(),hrl:t.z.string().optional(),packageSequenceNumber:t.z.number().int().optional()}).passthrough(),Au=t.z.object({jobId:t.z.string(),network:t.z.union([t.z.literal("mainnet"),t.z.literal("testnet")]),name:t.z.string(),version:t.z.string(),description:t.z.string().optional(),createdAt:t.z.string(),directoryTopicId:t.z.string(),skillUid:t.z.number().int().optional(),directorySequenceNumber:t.z.number().int().optional(),versionRegistryTopicId:t.z.string().optional(),packageTopicId:t.z.string(),manifestHrl:t.z.string().optional(),skillJsonHrl:t.z.string(),iconHcs1:t.z.string().optional(),tags:t.z.array(t.z.string()).optional(),category:t.z.string().optional(),featured:t.z.boolean().optional(),verified:t.z.boolean().optional(),upvotes:t.z.number().int().optional(),trustScore:t.z.number().optional(),trustScores:Iu.optional(),safety:Su.optional(),safetyFindings:t.z.array(vu).optional(),files:t.z.array(Eu).optional()}).passthrough(),Cu=t.z.object({items:t.z.array(Au),nextCursor:t.z.string().nullable()}).passthrough(),Ru=t.z.object({name:t.z.string(),version:t.z.string(),jobId:t.z.string(),createdAt:t.z.string(),safety:Su.nullable(),findings:t.z.array(vu)}).passthrough();t.z.enum(["stable","prerelease","all"]),t.z.enum(["trending","upvotes","updated","name"]);const xu=t.z.object({version:t.z.string(),publishedAt:t.z.string(),verified:t.z.boolean().optional()}).passthrough(),Nu=t.z.object({name:t.z.string(),description:t.z.string().optional(),iconHcs1:t.z.string().optional(),category:t.z.string().optional(),tags:t.z.array(t.z.string()).optional(),latest:xu,latestStable:xu.optional(),recommended:xu,upvotes:t.z.number().int(),verified:t.z.boolean(),repoStamped:t.z.boolean(),trustScore:t.z.number().optional(),safetyScore:t.z.number().optional()}).passthrough(),zu=t.z.object({items:t.z.array(Nu),nextCursor:t.z.string().nullable()}).passthrough(),_u=t.z.object({name:t.z.string(),version:t.z.string(),updatedAt:t.z.string(),setBy:t.z.string()}).passthrough(),Pu=t.z.object({name:t.z.string(),version:t.z.string().optional(),reason:t.z.string(),replacementRef:t.z.string().optional(),deprecatedAt:t.z.string(),deprecatedBy:t.z.string()}).passthrough(),Ou=t.z.object({name:t.z.string(),items:t.z.array(Pu)}).passthrough(),Du=t.z.object({id:t.z.string(),label:t.z.string(),description:t.z.string(),command:t.z.string(),href:t.z.string().nullable().optional()}).passthrough(),Fu=t.z.object({presetId:t.z.string(),label:t.z.string(),description:t.z.string(),recommendedFor:t.z.string(),command:t.z.string()}).passthrough(),Mu=t.z.object({cliPackageUrl:t.z.string(),cliCommand:t.z.string(),actionMarketplaceUrl:t.z.string(),repositoryUrl:t.z.string(),guideUrl:t.z.string().nullable().optional(),docsUrl:t.z.string().nullable().optional(),submitUrl:t.z.string().nullable().optional(),skillsIndexUrl:t.z.string().nullable().optional(),quickstartCommands:t.z.array(Du),templatePresets:t.z.array(Fu)}).passthrough(),Uu=t.z.enum(["unpublished","unclaimed","validated","published","verified","hardened"]),Bu=t.z.object({repoCommitIntegrity:t.z.boolean(),manifestIntegrity:t.z.boolean(),domainProof:t.z.boolean()}).passthrough(),Lu=t.z.object({kind:t.z.enum(["setup_validate","publish_first_release","verify_domain","harden_workflow","share_status"]).optional(),priority:t.z.number().int().optional(),id:t.z.string(),label:t.z.string(),description:t.z.string(),url:t.z.string().nullable().optional(),href:t.z.string().nullable().optional(),command:t.z.string().nullable().optional()}).passthrough(),Ku=t.z.object({id:t.z.string(),label:t.z.string(),description:t.z.string(),command:t.z.string().optional(),href:t.z.string().optional()}).passthrough(),$u=t.z.object({schema_version:t.z.literal("skill-preview.v1"),tool_version:t.z.string(),preview_id:t.z.string(),repo_url:t.z.string(),repo_owner:t.z.string(),repo_name:t.z.string(),default_branch:t.z.string(),commit_sha:t.z.string(),ref:t.z.string(),event_name:t.z.string(),workflow_run_url:t.z.string(),skill_dir:t.z.string(),name:t.z.string(),version:t.z.string(),validation_status:t.z.literal("passed"),findings:t.z.array(t.z.unknown()),package_summary:t.z.record(t.z.string(),t.z.unknown()),suggested_next_steps:t.z.array(Ku),generated_at:t.z.string()}).passthrough(),Hu=t.z.object({id:t.z.string(),previewId:t.z.string(),source:t.z.literal("github-oidc"),report:$u,generatedAt:t.z.string(),expiresAt:t.z.string(),statusUrl:t.z.string(),authoritative:t.z.boolean()}).passthrough(),qu=t.z.object({found:t.z.boolean(),authoritative:t.z.boolean(),preview:Hu.nullable(),statusUrl:t.z.string().nullable(),expiresAt:t.z.string().nullable()}).passthrough(),ju=t.z.object({previewId:t.z.string(),repoUrl:t.z.string(),repoOwner:t.z.string(),repoName:t.z.string(),commitSha:t.z.string(),ref:t.z.string(),eventName:t.z.string(),skillDir:t.z.string(),generatedAt:t.z.string(),expiresAt:t.z.string(),statusUrl:t.z.string()}).passthrough(),Wu=t.z.object({publisherBound:t.z.boolean(),domainProof:t.z.boolean(),verifiedDomain:t.z.boolean(),previewValidated:t.z.boolean()}).passthrough(),Vu=t.z.object({repoCommitIntegrity:t.z.boolean(),manifestIntegrity:t.z.boolean(),canonicalRelease:t.z.boolean(),previewAvailable:t.z.boolean(),previewAuthoritative:t.z.boolean()}).passthrough(),Gu=t.z.enum(["version","version_verification","status","verification","repo_commit","manifest","domain","trust","tier","safety","upvotes","updated"]),Ju=t.z.object({name:t.z.string(),version:t.z.string().nullable(),published:t.z.boolean(),verifiedDomain:t.z.boolean(),trustTier:Uu,badgeMetric:Gu,checks:Bu,nextSteps:t.z.array(Lu),verificationSignals:Wu.default({publisherBound:!1,domainProof:!1,verifiedDomain:!1,previewValidated:!1}),provenanceSignals:Vu.default({repoCommitIntegrity:!1,manifestIntegrity:!1,canonicalRelease:!1,previewAvailable:!1,previewAuthoritative:!1}),publisher:Mu.nullable().optional(),preview:ju.nullable().optional(),statusUrl:t.z.string().nullable().optional()}).passthrough(),Yu=t.z.object({url:t.z.string(),pointer:t.z.string().nullable(),sha256:t.z.string().nullable()}).passthrough(),Xu=t.z.object({skillRef:t.z.string(),skillMdUrl:t.z.string(),manifestUrl:t.z.string()}).passthrough(),Zu=t.z.object({apiUrl:t.z.string(),imageUrl:t.z.string(),markdown:t.z.string(),html:t.z.string()}).passthrough(),Qu=t.z.object({canonicalUrl:t.z.string().nullable(),latestUrl:t.z.string().nullable(),markdownLink:t.z.string().nullable(),htmlLink:t.z.string().nullable(),badge:Zu.nullable()}).passthrough(),ed=t.z.object({cli:t.z.string(),claude:t.z.string(),cursor:t.z.string(),codex:t.z.string(),openclaw:t.z.string()}).passthrough(),td=t.z.object({name:t.z.string(),version:t.z.string(),skillRef:t.z.string(),network:t.z.union([t.z.literal("mainnet"),t.z.literal("testnet")]),detailUrl:t.z.string().nullable(),artifacts:t.z.object({skillMd:Yu,manifest:Yu}).passthrough(),resolvers:t.z.object({pinned:Xu,latest:Xu}).passthrough(),share:Qu,snippets:ed}).passthrough(),rd=t.z.object({accepted:t.z.boolean()}).passthrough(),id=t.z.enum(["flat","flat-square","for-the-badge","plastic","social"]),nd=t.z.object({schemaVersion:t.z.number().int(),label:t.z.string(),message:t.z.string(),color:t.z.string(),style:id.optional(),isError:t.z.boolean().optional(),cacheSeconds:t.z.number().int().optional()}).passthrough(),od=t.z.object({tags:t.z.array(t.z.string())}).passthrough(),sd=t.z.object({categories:t.z.array(t.z.string())}).passthrough(),ad=t.z.record(Ac),cd=t.z.object({name:t.z.string(),mimeType:t.z.string(),estimatedCostHbar:t.z.number()}).passthrough(),ld=t.z.object({quoteId:t.z.string(),name:t.z.string(),version:t.z.string(),directoryTopicId:t.z.string(),estimatedCostHbar:t.z.number(),credits:t.z.number(),usdCents:t.z.number(),expiresAt:t.z.string(),files:t.z.array(cd)}).passthrough(),ud=t.z.union([t.z.literal("pending"),t.z.literal("in_progress"),t.z.literal("completed"),t.z.literal("failed")]),dd=t.z.object({jobId:t.z.string(),status:ud,credits:t.z.number().nullable().optional(),usdCents:t.z.number().nullable().optional(),quoteId:t.z.string().nullable().optional(),createdAt:t.z.string(),updatedAt:t.z.string(),network:t.z.union([t.z.literal("mainnet"),t.z.literal("testnet")])}).passthrough(),pd=t.z.object({jobId:t.z.string(),status:ud,network:t.z.union([t.z.literal("mainnet"),t.z.literal("testnet")]),name:t.z.string(),version:t.z.string(),directoryTopicId:t.z.string(),skillUid:t.z.number().int().nullable().optional(),directorySequenceNumber:t.z.number().int().nullable().optional(),versionRegistryTopicId:t.z.string().nullable().optional(),packageTopicId:t.z.string().nullable().optional(),manifestHrl:t.z.string().nullable().optional(),skillJsonHrl:t.z.string().nullable().optional(),iconHcs1:t.z.string().nullable().optional(),tags:t.z.array(t.z.string()).nullable().optional(),category:t.z.string().nullable().optional(),files:t.z.array(Eu).nullable().optional(),quoteCredits:t.z.number().nullable().optional(),quoteUsdCents:t.z.number().nullable().optional(),safety:Su.nullable().optional(),reservationId:t.z.string().nullable().optional(),totalCostHbar:t.z.number().nullable().optional(),totalCostCredits:t.z.number().nullable().optional(),failureReason:t.z.string().nullable().optional(),createdAt:t.z.string(),updatedAt:t.z.string()}).passthrough(),hd=t.z.object({jobId:t.z.string(),version:t.z.string(),createdAt:t.z.string(),verified:t.z.boolean().optional()}).passthrough(),gd=t.z.object({name:t.z.string(),items:t.z.array(hd)}).passthrough(),md=t.z.object({name:t.z.string(),latestVersion:t.z.string(),latestCreatedAt:t.z.string(),verified:t.z.boolean().optional(),iconHcs1:t.z.string().optional(),versions:t.z.array(t.z.string())}).passthrough(),fd=t.z.object({items:t.z.array(md)}).passthrough(),yd=t.z.object({owned:fd,upvoted:Cu}).passthrough(),bd=t.z.object({enabled:t.z.boolean(),directoryTopicId:t.z.string().nullable().optional(),maxFiles:t.z.number().int().nullable().optional(),maxTotalSizeBytes:t.z.number().int().nullable().optional(),allowedMimeTypes:t.z.array(t.z.string()).nullable().optional(),network:t.z.union([t.z.literal("mainnet"),t.z.literal("testnet")]).nullable().optional(),publisher:Mu.nullable().optional()}).passthrough(),wd=t.z.object({name:t.z.string(),exists:t.z.boolean(),isOwner:t.z.boolean()}).passthrough(),Id=t.z.object({name:t.z.string(),upvotes:t.z.number().int(),hasUpvoted:t.z.boolean()}).passthrough(),Td=t.z.enum(["basic","express"]),Sd=t.z.enum(["pending","approved","rejected"]),kd=t.z.enum(["not_requested","pending","approved","rejected"]),vd=t.z.enum(["missing_owner","missing_repo_or_commit","unsupported_repo","repo_fetch_failed","manifest_pointer_missing","manifest_fetch_failed","manifest_parse_failed","missing_file_hashes","missing_domain","challenge_invalid","challenge_expired","dns_lookup_failed","dns_record_missing","mismatch"]),Ed=t.z.object({ok:t.z.boolean(),ownerAccountId:t.z.string().nullable(),ownerUserId:t.z.string().nullable(),checkedAt:t.z.string(),reason:vd.optional()}).passthrough(),Ad=t.z.object({path:t.z.string(),expectedSha256:t.z.string(),actualSha256:t.z.string().optional(),error:t.z.string().optional()}).passthrough(),Cd=t.z.object({ok:t.z.boolean(),repo:t.z.string().nullable(),commit:t.z.string().nullable(),checkedAt:t.z.string(),filesChecked:t.z.number().int().min(0),mismatches:t.z.array(Ad),partial:t.z.boolean().optional(),reason:vd.optional()}).passthrough(),Rd=t.z.object({path:t.z.string(),expectedSha256:t.z.string(),actualSha256:t.z.string().optional()}).passthrough(),xd=t.z.object({ok:t.z.boolean(),manifestHrl:t.z.string().nullable(),manifestSha256:t.z.string().nullable(),checkedAt:t.z.string(),missingFiles:t.z.array(t.z.string()),shaMismatches:t.z.array(Rd),extraFiles:t.z.array(t.z.string()).optional(),reason:vd.optional()}).passthrough(),Nd=t.z.object({ok:t.z.boolean(),domain:t.z.string().optional(),method:t.z.literal("dns_txt").optional(),checkedAt:t.z.string().optional(),details:t.z.string().optional(),txtRecordName:t.z.string().optional(),reason:vd.optional()}).passthrough(),zd=t.z.object({publisherBound:Ed,repoCommitIntegrity:Cd,manifestIntegrity:xd,domainProof:Nd.optional()}).passthrough(),_d=t.z.object({id:t.z.string(),network:t.z.union([t.z.literal("mainnet"),t.z.literal("testnet")]),name:t.z.string(),version:t.z.string().optional(),tier:Td,status:Sd,usdCents:t.z.number(),creditsCharged:t.z.number(),creditAccountId:t.z.string().optional(),signals:zd.optional(),reviewNotes:t.z.string().optional(),requestedBy:t.z.object({userId:t.z.string().optional(),accountId:t.z.string().optional(),email:t.z.string().optional()}).optional(),approvedBy:t.z.object({userId:t.z.string().optional(),email:t.z.string().optional()}).optional(),approvedAt:t.z.string().optional(),rejectedBy:t.z.object({userId:t.z.string().optional(),email:t.z.string().optional()}).optional(),rejectedAt:t.z.string().optional(),createdAt:t.z.string(),updatedAt:t.z.string()}).passthrough(),Pd=t.z.object({request:_d}).passthrough(),Od=t.z.object({name:t.z.string(),version:t.z.string(),status:kd,verified:t.z.boolean(),previouslyVerified:t.z.boolean(),signals:zd.nullable().optional(),reviewNotes:t.z.string().nullable().optional(),pendingRequest:_d.nullable().optional()}).passthrough();t.z.object({name:t.z.string().min(1),version:t.z.string().min(1).optional(),domain:t.z.string().min(1).optional()}).passthrough();const Dd=t.z.object({challengeId:t.z.string().min(1),name:t.z.string().min(1),version:t.z.string().min(1),domain:t.z.string().min(1),method:t.z.literal("dns_txt"),txtRecordName:t.z.string().min(1),txtRecordValue:t.z.string().min(1),expiresAt:t.z.string().min(1)}).passthrough();t.z.object({name:t.z.string().min(1),version:t.z.string().min(1).optional(),domain:t.z.string().min(1).optional(),challengeToken:t.z.string().min(1)}).passthrough();const Fd=t.z.object({name:t.z.string().min(1),version:t.z.string().min(1),signal:Nd}).passthrough();function Md(e,t){return!e&&!t||!(!e||!t)&&(!(!e.uaid||!t.uaid||e.uaid.toLowerCase()!==t.uaid.toLowerCase())||(!(!e.ledgerAccountId||!t.ledgerAccountId||e.ledgerAccountId.toLowerCase()!==t.ledgerAccountId.toLowerCase())||(!(!e.userId||!t.userId||e.userId!==t.userId)||!(!e.email||!t.email||e.email.toLowerCase()!==t.email.toLowerCase()))))}function Ud(e,t,r,i,n){if(!(void 0!==n?.decrypt?n.decrypt:!0===t.encryptionOptions?.autoDecryptHistory))return i;if(!i.history.some(e=>Boolean(e.cipherEnvelope)))return{...i,decryptedHistory:i.history.map(e=>({entry:e,plaintext:e.content}))};const o=Bd(e,t,r,n);if(!o)throw new Error("Unable to decrypt chat history: encryption context unavailable");const s=i.history.map(e=>({entry:e,plaintext:Ld(t,e,o)}));return{...i,decryptedHistory:s}}function Bd(e,t,r,i){if(i?.sharedSecret)return{sessionId:r,sharedSecret:t.normalizeSharedSecret(i.sharedSecret),identity:i.identity};const n=e.get(r);if(!n||0===n.length)return null;if(i?.identity){const e=n.find(e=>Md(e.identity,i.identity));if(e)return e}return n[0]}function Ld(e,t,r){const i=t.cipherEnvelope;if(!i)return t.content;const n=o.Buffer.from(r.sharedSecret);try{return e.encryption.decryptCipherEnvelope({envelope:i,sharedSecret:n})}catch(s){return null}}const Kd="https://hol.org/registry/api/v1",$d=/application\/json/i,Hd=e=>{let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t-=1;return t===e.length?e:e.slice(0,t)},qd=()=>"function"==typeof DOMException?new DOMException("Aborted","AbortError"):new Error("The operation was aborted"),jd=e=>e.trim().toLowerCase(),Wd=e=>{if(null===e)return null;if(e instanceof Date)return e.toISOString();if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map(e=>void 0===e?null:Wd(e));if("object"==typeof e){const t={};return Object.entries(e).forEach(([e,r])=>{void 0!==r&&(t[e]=Wd(r))}),t}throw new TypeError("Only JSON-compatible values are supported")},Vd=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Gd=e=>{const t=Wd(e);if(Vd(t))return t;throw new TypeError("Expected JSON object value")},Jd=e=>{const t={};return e.type&&(t.type=e.type),e.token&&(t.token=e.token),e.username&&(t.username=e.username),e.password&&(t.password=e.password),e.headerName&&(t.headerName=e.headerName),e.headerValue&&(t.headerValue=e.headerValue),e.headers&&(t.headers={...e.headers}),t},Yd=e=>{const t={profile:Gd(e.profile)};return void 0!==e.endpoint&&(t.endpoint=e.endpoint),void 0!==e.protocol&&(t.protocol=e.protocol),void 0!==e.communicationProtocol&&(t.communicationProtocol=e.communicationProtocol),void 0!==e.registry&&(t.registry=e.registry),void 0!==e.additionalRegistries&&(t.additionalRegistries=e.additionalRegistries),void 0!==e.metadata&&(t.metadata=Gd(e.metadata)),t};class Xd extends Error{constructor(e,t){super("Encryption is not enabled for this session"),this.sessionId=e,this.summary=t}}class Zd{constructor(e){this.client=e}registerConversationContext(e){this.client.registerConversationContextForEncryption(e)}async startSession(e){await this.client.encryptionReady();const t=await this.client.chat.createSession({uaid:e.uaid,senderUaid:e.senderUaid,encryptionRequested:!0,historyTtlSeconds:e.historyTtlSeconds,auth:e.auth});e.onSessionCreated?.(t.sessionId);const r=t.encryption;if(!r?.enabled)throw new Xd(t.sessionId,t.encryption??null);return await this.establishRequesterContext({sessionId:t.sessionId,summary:r,senderUaid:e.senderUaid,handshakeTimeoutMs:e.handshakeTimeoutMs,pollIntervalMs:e.pollIntervalMs})}async acceptSession(e){await this.client.encryptionReady();const t=await this.waitForEncryptionSummary(e.sessionId,e.handshakeTimeoutMs,e.pollIntervalMs);return await this.establishResponderContext({sessionId:e.sessionId,summary:t,responderUaid:e.responderUaid,handshakeTimeoutMs:e.handshakeTimeoutMs,pollIntervalMs:e.pollIntervalMs})}async establishRequesterContext(e){const t=this.client.encryption.generateEphemeralKeyPair();await this.client.chat.submitEncryptionHandshake(e.sessionId,{role:"requester",keyType:"secp256k1",ephemeralPublicKey:t.publicKey,uaid:e.senderUaid??e.summary.requester?.uaid??void 0});const{summary:r,record:i}=await this.waitForHandshakeCompletion(e.sessionId,e.handshakeTimeoutMs,e.pollIntervalMs),n=i.responder?.ephemeralPublicKey;if(!n)throw new Error("Responder handshake was not completed in time");const o=this.client.encryption.deriveSharedSecret({privateKey:t.privateKey,peerPublicKey:n}).subarray(),s=this.buildRecipients(r);return this.createHandle({sessionId:e.sessionId,sharedSecret:o,summary:r,recipients:s,identity:r.requester??void 0})}async establishResponderContext(e){const t=this.client.encryption.generateEphemeralKeyPair();await this.client.chat.submitEncryptionHandshake(e.sessionId,{role:"responder",keyType:"secp256k1",ephemeralPublicKey:t.publicKey,uaid:e.responderUaid??e.summary.responder?.uaid??void 0});const{summary:r,record:i}=await this.waitForHandshakeCompletion(e.sessionId,e.handshakeTimeoutMs,e.pollIntervalMs),n=i.requester?.ephemeralPublicKey;if(!n)throw new Error("Requester handshake was not detected in time");const o=this.client.encryption.deriveSharedSecret({privateKey:t.privateKey,peerPublicKey:n}).subarray(),s=this.buildRecipients(r);return this.createHandle({sessionId:e.sessionId,sharedSecret:o,summary:r,recipients:s,identity:r.responder??void 0})}async waitForHandshakeCompletion(e,t=3e4,r=1e3){const i=Date.now()+t;for(;;){const t=(await this.client.chat.getEncryptionStatus(e)).encryption,n=t?.handshake;if(t&&n&&"complete"===n.status)return{summary:t,record:n};if(Date.now()>=i)throw new Error("Timed out waiting for encrypted handshake completion");await this.delay(r)}}async waitForEncryptionSummary(e,t=3e4,r=1e3){const i=await this.client.chat.getEncryptionStatus(e);if(!i.encryption?.enabled)throw new Xd(e,i.encryption??null);return i.encryption}buildRecipients(e){const t=[e.requester,e.responder].filter(Boolean).map(e=>{if(!e)return null;const t={};return e.uaid&&(t.uaid=e.uaid),e.ledgerAccountId&&(t.ledgerAccountId=e.ledgerAccountId),e.userId&&(t.userId=e.userId),e.email&&(t.email=e.email),t}).filter(e=>Boolean(e?.uaid||e?.ledgerAccountId||e?.userId||e?.email));return t.length>0?t:e.responder?.uaid?[{uaid:e.responder.uaid}]:[]}createHandle(e){const t=e.sharedSecret,r=e.summary.requester?.uaid??e.summary.responder?.uaid??e.identity?.uaid,i=r=>this.decryptEntry(r,e.identity,t),n={sessionId:e.sessionId,mode:"encrypted",summary:e.summary,send:async i=>{const n=i.recipients??e.recipients;return this.client.chat.sendMessage({sessionId:e.sessionId,message:i.message??"[ciphertext omitted]",streaming:i.streaming,auth:i.auth,uaid:r,encryption:{plaintext:i.plaintext,sharedSecret:globalThis.Buffer.from(t),recipients:n}})},decryptHistoryEntry:i,fetchHistory:async t=>{const r=await this.client.fetchHistorySnapshot(e.sessionId,t);return r.decryptedHistory?r.decryptedHistory:r.history.map(e=>({entry:e,plaintext:i(e)}))}};return this.registerConversationContext({sessionId:e.sessionId,sharedSecret:t,identity:e.identity}),n}decryptEntry(e,t,r){const i=e.cipherEnvelope;if(!i)return null;const n=globalThis.Buffer.from(r);try{return this.client.encryption.decryptCipherEnvelope({envelope:i,sharedSecret:n})}catch(o){return null}}recipientMatches(e,t){return!(!t.uaid||e.uaid?.toLowerCase()!==t.uaid.toLowerCase())||(!(!t.ledgerAccountId||e.ledgerAccountId?.toLowerCase()!==t.ledgerAccountId.toLowerCase())||(!(!t.userId||e.userId!==t.userId)||!(!t.email||e.email?.toLowerCase()!==t.email.toLowerCase())))}async delay(e){e<=0||await new Promise(t=>setTimeout(t,e))}}async function Qd(e,t,r=!0){const i={};"uaid"in t&&t.uaid&&(i.uaid=t.uaid),"agentUrl"in t&&t.agentUrl&&(i.agentUrl=t.agentUrl),t.auth&&(i.auth=Jd(t.auth)),void 0!==t.historyTtlSeconds&&(i.historyTtlSeconds=t.historyTtlSeconds),void 0!==t.encryptionRequested&&(i.encryptionRequested=t.encryptionRequested),t.senderUaid&&(i.senderUaid=t.senderUaid);try{const t=await e.requestJson("/chat/session",{method:"POST",body:i,headers:{"content-type":"application/json"}});return e.parseWithSchema(t,el,"chat session response")}catch(n){const i=n instanceof Error?n:null;if(r&&e.shouldAutoTopUpHistory(t,i))return await e.executeHistoryAutoTopUp("chat.session"),Qd(e,t,!1);throw n}}async function ep(e,t,r){const i=r.encryption?.preference??"preferred";if(!("disabled"!==i)){const t=await Qd(e,{uaid:r.uaid,auth:r.auth,historyTtlSeconds:r.historyTtlSeconds,senderUaid:r.senderUaid,encryptionRequested:!1});return r.onSessionCreated?.(t.sessionId),tp(e,t.sessionId,t.encryption??null,r.auth,{uaid:r.uaid})}try{return await t.startSession({uaid:r.uaid,senderUaid:r.senderUaid,historyTtlSeconds:r.historyTtlSeconds,handshakeTimeoutMs:r.encryption?.handshakeTimeoutMs,pollIntervalMs:r.encryption?.pollIntervalMs,onSessionCreated:e=>{r.onSessionCreated?.(e)},auth:r.auth})}catch(n){if(n instanceof Xd){if("required"===i)throw n;return tp(e,n.sessionId,n.summary??null,r.auth,{uaid:r.uaid})}throw n}}function tp(e,t,r,i,n){const o=n?.uaid?.trim(),s=n?.agentUrl?.trim();return{sessionId:t,mode:"plaintext",summary:r??null,send:async r=>{const n=r.plaintext;if(!n||0===n.trim().length)throw new Error("plaintext is required for chat messages");const a=r.message??n;return rp(e,{sessionId:t,message:a,streaming:r.streaming,auth:r.auth??i,uaid:o,agentUrl:s})},decryptHistoryEntry:e=>e.content,fetchHistory:async r=>{const i=await e.fetchHistorySnapshot(t,r);return i.decryptedHistory?i.decryptedHistory:i.history.map(e=>({entry:e,plaintext:e.content}))}}}async function rp(e,t){const r={message:t.message};void 0!==t.streaming&&(r.streaming=t.streaming),t.auth&&(r.auth=Jd(t.auth)),"uaid"in t&&(r.uaid=t.uaid),"sessionId"in t&&t.sessionId&&(r.sessionId=t.sessionId),"agentUrl"in t&&t.agentUrl&&(r.agentUrl=t.agentUrl);let i=t.cipherEnvelope??null;if(t.encryption){const n=t.encryption.sessionId??("string"==typeof r.sessionId?r.sessionId:void 0);if(!n)throw new Error("sessionId is required when using encrypted chat payloads");if(!t.encryption.recipients?.length)throw new Error("recipients are required for encrypted chat payloads");i=e.encryption.encryptCipherEnvelope({...t.encryption,sessionId:n})}i&&(r.cipherEnvelope=Gd(i));const n=await e.requestJson("/chat/message",{method:"POST",body:r,headers:{"content-type":"application/json"}});return e.parseWithSchema(n,tl,"chat message response")}async function ip(e,t){const r=await e.requestJson("/encryption/keys",{method:"POST",headers:{"content-type":"application/json"},body:t});return e.parseWithSchema(r,sl,"register encryption key response")}async function np(e,t){if(t.publicKey?.trim())return{publicKey:t.publicKey.trim()};let r=t.privateKey?.trim();const i=t.envVar??"RB_ENCRYPTION_PRIVATE_KEY";if(!r&&i&&process?.env?.[i]?.trim()&&(r=process.env[i]?.trim()),!r&&t.generateIfMissing){const r=await e.generateEncryptionKeyPair({keyType:t.keyType??"secp256k1",envVar:i,envPath:t.envPath,overwrite:t.overwriteEnv});return{publicKey:r.publicKey,privateKey:r.privateKey}}if(r){const t=function(e,t){const r=e.hexToBuffer(t),i=c.secp256k1.getPublicKey(r,!0);return o.Buffer.from(i).toString("hex")}(e,r);return{publicKey:t,privateKey:r}}return null}async function op(e,t){const r=function(e){const t={};return e.uaid&&(t.uaid=e.uaid),e.ledgerAccountId&&(t.ledgerAccountId=e.ledgerAccountId,e.ledgerNetwork&&(t.ledgerNetwork=e.ledgerNetwork)),e.email&&(t.email=e.email),t.uaid||t.ledgerAccountId||t.email?t:null}(t);if(!r)throw new Error("Auto-registration requires uaid, ledgerAccountId, or email");const i=await np(e,t);if(!i)throw new Error("Unable to resolve encryption public key for auto-registration");return await ip(e,{keyType:t.keyType??"secp256k1",publicKey:i.publicKey,...r}),i}function sp(e){return{registerKey:t=>ip(e,t),generateEphemeralKeyPair:()=>e.createEphemeralKeyPair(),deriveSharedSecret:t=>e.deriveSharedSecret(t),encryptCipherEnvelope:t=>e.buildCipherEnvelope(t),decryptCipherEnvelope:t=>e.openCipherEnvelope(t),ensureAgentKey:t=>async function(e,t){return op(e,{...t,uaid:t.uaid})}(e,t)}}async function ap(e,t={}){e.assertNodeRuntime("generateEncryptionKeyPair");if("secp256k1"!==(t.keyType??"secp256k1"))throw new Error("Only secp256k1 key generation is supported currently");const r=await(async()=>{const e=await Ta("node:crypto")??await Ta("crypto");return e&&"function"==typeof e.randomBytes?e:null})();if(!r)throw new Error("Node.js crypto module is not available; cannot generate encryption key pair");const i=r.randomBytes(32),n=o.Buffer.from(i).toString("hex"),s=c.secp256k1.getPublicKey(i,!0),a=o.Buffer.from(s).toString("hex"),l=t.envVar??"RB_ENCRYPTION_PRIVATE_KEY",u=t.envPath?await(async()=>{const e=await Ta("node:path")??await Ta("path");return e&&"function"==typeof e.resolve?e:null})():null,d=t.envPath&&u?u.resolve(t.envPath):void 0;if(t.envPath&&!d)throw new Error("Node.js path module is not available; cannot resolve encryption key env path");if(d){const e=await(async()=>{const e=await Ta("node:fs")??await Ta("fs");return e&&"function"==typeof e.existsSync&&"function"==typeof e.readFileSync&&"function"==typeof e.writeFileSync&&"function"==typeof e.appendFileSync?e:null})();if(!e)throw new Error("File system module is not available; cannot write encryption key env file");const r=`${l}=${n}`;if(e.existsSync(d)){const i=e.readFileSync(d,"utf-8"),n=new RegExp(`^${l}=.*$`,"m");if(n.test(i)){if(!t.overwrite)throw new Error(`${l} already exists in ${d}; set overwrite=true to replace it`);const o=i.replace(n,r);e.writeFileSync(d,o)}else{const t=!i.endsWith("\n");e.appendFileSync(d,`${t?"\n":""}${r}\n`)}}else e.writeFileSync(d,`${r}\n`)}return{privateKey:n,publicKey:a,envPath:d,envVar:l}}async function cp(e){const[{default:t},r,i]=await Promise.all([import("axios"),Ta("x402-axios"),Ta("x402/types")]);if(!r||!i)throw new Error("x402-axios and x402/types are required for X402 flows. Install them to enable ledger payments.");const n=r.withPaymentInterceptor;return{createPaymentClient:r=>{const i=t.create({baseURL:e.baseUrl,headers:{...e.getDefaultHeaders(),"content-type":"application/json"}});return n(i,r)},decodePaymentResponse:r.decodeXPaymentResponse,createX402Signer:i.createSigner}}function lp(e){const t=Math.ceil(1e8*e);if(t<=0)throw new Error("Calculated purchase amount must be positive");return t/1e8}async function up(e,t){const r={accountId:t.accountId,payerKey:t.privateKey,hbarAmount:lp(t.hbarAmount)};t.memo&&(r.memo=t.memo),t.metadata&&(r.metadata=t.metadata);const i=await e.requestJson("/credits/purchase",{method:"POST",headers:{"content-type":"application/json"},body:r});return e.parseWithSchema(i,Hl,"credit purchase response")}async function dp(e,t){const{createPaymentClient:r,decodePaymentResponse:i}=await cp(e);if(!Number.isFinite(t.credits)||t.credits<=0)throw new Error("credits must be a positive number");if(void 0!==t.usdAmount&&(!Number.isFinite(t.usdAmount)||t.usdAmount<=0))throw new Error("usdAmount must be a positive number when provided");const n={accountId:t.accountId,credits:t.credits};void 0!==t.usdAmount&&(n.usdAmount=t.usdAmount),t.description&&(n.description=t.description),t.metadata&&(n.metadata=t.metadata);const o=r(t.walletClient),s=await o.post("/credits/purchase/x402",n),a=e.parseWithSchema(s.data,jl,"x402 credit purchase response"),c=s.headers??{},l="string"==typeof c["x-payment-response"]?c["x-payment-response"]:void 0;return{...a,paymentResponseHeader:l,paymentResponse:void 0!==l?i(l):void 0}}async function pp(e,t){const r=t.network??"base",{createX402Signer:i}=await cp(e),n=(e=>{const t=e.trim();if(!t)throw new Error("evmPrivateKey is required");return t.startsWith("0x")?t:`0x${t}`})(t.evmPrivateKey),o=await i(r,n);return dp(e,{accountId:t.accountId,credits:t.credits,usdAmount:t.usdAmount,description:t.description,metadata:t.metadata,walletClient:o})}class hp extends Error{constructor(e,t){super(e),this.status=t.status,this.statusText=t.statusText,this.body=t.body}}class gp extends Error{constructor(e,t,r){super(e),this.cause=t,this.rawValue=r}}async function mp(e,t){const r=await e.requestJson("/register",{method:"POST",body:Yd(t),headers:{"content-type":"application/json"}});return e.parseWithSchema(r,Ul,"register agent response")}function fp(e,t){if(t<=0)throw new Error("creditsPerHbar must be positive");if(e<=0)throw new Error("creditsToPurchase must be positive");const r=e/t;return Math.ceil(1e8*r)/1e8}function yp(e){return!Number.isFinite(e)||e<=0?0:Math.max(Math.ceil(e),1)}async function bp(e,t,r){const i=r??null;if(!i)return;if(!i.accountId||!i.accountId.trim())throw new Error("autoTopUp.accountId is required");if(!i.privateKey||!i.privateKey.trim())throw new Error("autoTopUp.privateKey is required");for(let n=0;n<3;n+=1){const r=await Ip(e,t),n=r.shortfallCredits??0;if(n<=0)return;const o=yp(n);if(o<=0)return;const s=r.creditsPerHbar??null;if(!s||s<=0)throw new Error("Unable to determine credits per HBAR for auto top-up");const a=fp(o,s);await up(e,{accountId:i.accountId.trim(),privateKey:i.privateKey.trim(),hbarAmount:a,memo:i.memo??"Registry Broker auto top-up",metadata:{shortfallCredits:n,requiredCredits:r.requiredCredits,purchasedCredits:o}})}if(((await Ip(e,t)).shortfallCredits??0)>0)throw new Error("Unable to purchase sufficient credits for registration")}async function wp(e,t){const r=await e.requestJson(`/resolve/${encodeURIComponent(t)}`,{method:"GET"});return e.parseWithSchema(r,$c,"resolve UAID response")}async function Ip(e,t){const r=await e.requestJson("/register/quote",{method:"POST",body:Yd(t),headers:{"content-type":"application/json"}});return e.parseWithSchema(r,$l,"registration quote response")}async function Tp(e,t,r){const i=await e.requestJson(`/register/${encodeURIComponent(t)}`,{method:"PUT",body:Yd(r),headers:{"content-type":"application/json"}});return e.parseWithSchema(i,Ul,"update agent response")}async function Sp(e,t){const r=t.trim();if(!r)throw new Error("attemptId is required");try{const t=await e.requestJson(`/register/progress/${encodeURIComponent(r)}`,{method:"GET"});return e.parseWithSchema(t,Kl,"registration progress response").progress}catch(i){if(i instanceof hp&&404===i.status)return null;throw i}}async function kp(e,t,r={}){const i=t.trim();if(!i)throw new Error("attemptId is required");const n=Math.max(250,r.intervalMs??1500),o=r.timeoutMs??3e5,s=r.throwOnFailure??!0,a=r.signal,c=Date.now();for(;;){if(a?.aborted)throw qd();const t=await e.getRegistrationProgress(i);if(t){if(r.onProgress?.(t),"completed"===t.status)return t;if("partial"===t.status||"failed"===t.status){if(s)throw new hp("Registration did not complete successfully",{status:409,statusText:t.status,body:t});return t}}if(Date.now()-c>=o)throw new Error(`Registration progress polling timed out after ${o}ms`);await e.delay(n,a)}}async function vp(e,t){const r=await e.requestJson(`/uaids/validate/${encodeURIComponent(t)}`,{method:"GET"});return e.parseWithSchema(r,Sl,"UAID validation response")}async function Ep(e,t){const r=await e.requestJson(`/uaids/connections/${encodeURIComponent(t)}/status`,{method:"GET"});return e.parseWithSchema(r,vl,"UAID connection status")}async function Ap(e,t){await e.request(`/uaids/connections/${encodeURIComponent(t)}`,{method:"DELETE"})}async function Cp(e){const t=await e.requestJson("/dashboard/stats",{method:"GET"});return e.parseWithSchema(t,El,"dashboard stats response")}const Rp=e=>e.trim().toLowerCase(),xp=new Map([["hedera:mainnet",{canonical:"hedera:mainnet",hederaNetwork:"mainnet"}],["mainnet",{canonical:"hedera:mainnet",hederaNetwork:"mainnet"}],["hedera-mainnet",{canonical:"hedera:mainnet",hederaNetwork:"mainnet"}],["hedera_mainnet",{canonical:"hedera:mainnet",hederaNetwork:"mainnet"}],["hedera:testnet",{canonical:"hedera:testnet",hederaNetwork:"testnet"}],["testnet",{canonical:"hedera:testnet",hederaNetwork:"testnet"}],["hedera-testnet",{canonical:"hedera:testnet",hederaNetwork:"testnet"}],["hedera_testnet",{canonical:"hedera:testnet",hederaNetwork:"testnet"}]]),Np={abstract:2741,"abstract-testnet":11124,base:8453,"base-sepolia":84532,avalanche:43114,"avalanche-fuji":43113,iotex:4689,sei:1329,"sei-testnet":1328,polygon:137,"polygon-amoy":80002,peaq:3338},zp=new Map(Object.entries(Np).map(([e,t])=>[t,e])),_p=e=>{const t=Rp(e);let r,i=(e=>/^eip155:\d+$/i.test(e)?Number.parseInt(e.split(":")[1],10):/^\d+$/.test(e)?Number.parseInt(e,10):void 0)(t);if(void 0===i){const e=Np[t];void 0!==e&&(i=e,r=t)}else zp.has(i)&&(r=zp.get(i));if(void 0===i)throw new Error('Unsupported EVM ledger network. Provide an alias like "base-sepolia" or a canonical eip155:<chainId> string.');return{canonical:`eip155:${i}`,kind:"evm",chainId:i,legacyName:r}},Pp=e=>{if("string"!=typeof e||0===e.trim().length)throw new Error("Ledger network is required.");const t=Rp(e);return t.startsWith("hedera:")||t.includes("hedera-")||t.includes("hedera_")||"mainnet"===t||"testnet"===t?(e=>{const t=Rp(e),r=xp.get(t);if(!r)throw new Error('Unsupported Hedera network. Use hedera:mainnet or hedera:testnet (legacy "mainnet"/"testnet" also accepted).');return{canonical:r.canonical,kind:"hedera",hederaNetwork:r.hederaNetwork}})(t):_p(t)},Op=e=>new Error(`${e} is not supported by the in-memory signer`);let Dp=null;const Fp=(e,t)=>{const{AccountId:r,LedgerId:i,PrivateKey:n,SignerSignature:o}=e;if(!t.privateKey)throw new Error("privateKey is required to create a ledger signer.");if(!t.accountId)throw new Error("accountId is required to create a ledger signer.");const s=r.fromString(t.accountId),a=n.fromString(t.privateKey),c=i.fromString(t.network);return{getLedgerId:()=>c,getAccountId:()=>s,getAccountKey:()=>a.publicKey,getNetwork:()=>({}),getMirrorNetwork:()=>[],sign:async e=>Promise.all(e.map(async e=>{const t=await a.sign(e);return new o({publicKey:a.publicKey,signature:t,accountId:s})})),getAccountBalance:async()=>{throw Op("getAccountBalance")},getAccountInfo:async()=>{throw Op("getAccountInfo")},getAccountRecords:async()=>{throw Op("getAccountRecords")},signTransaction:async e=>{throw Op("signTransaction")},checkTransaction:async e=>{throw Op("checkTransaction")},populateTransaction:async e=>{throw Op("populateTransaction")},call:async e=>{throw Op("call")}}},Mp=async e=>Fp(await(async()=>{if(Dp)return Dp;const e=await Ta("@hashgraph/sdk");if(e)return Dp=e,e;throw new Error("@hashgraph/sdk is required for ledger signing. Install it as a dependency to enable createPrivateKeySigner.")})(),e);async function Up(e,t){const r=await e.createLedgerChallenge({accountId:t.accountId,network:t.network}),i=await async function(e,t){if("function"==typeof t.sign){const r=await t.sign(e);if(!r||"string"!=typeof r.signature||0===r.signature.length)throw new Error("Custom ledger signer failed to produce a signature.");return r}if(!t.signer||"function"!=typeof t.signer.sign)throw new Error("Ledger authentication requires a Hedera Signer or custom sign function.");const r=o.Buffer.from(e,"utf8"),i=await t.signer.sign([r]),n=i?.[0];if(!n)throw new Error("Signer did not return any signatures.");let s;if(n.publicKey)s=n.publicKey.toString();else if("function"==typeof t.signer.getAccountKey){const e=await t.signer.getAccountKey();e&&"function"==typeof e.toString&&(s=e.toString())}return{signature:o.Buffer.from(n.signature).toString("base64"),signatureKind:"raw",publicKey:s}}(r.message,t);return await e.verifyLedgerChallenge({challengeId:r.challengeId,accountId:t.accountId,network:t.network,signature:i.signature,signatureKind:i.signatureKind,publicKey:i.publicKey,expiresInMinutes:t.expiresInMinutes})}async function Bp(e,t){const{accountId:r,network:i,signer:n,sign:o,hederaPrivateKey:s,evmPrivateKey:a,expiresInMinutes:c,setAccountHeader:l=!0,label:u,logger:d}=t,p=Pp(i),h=u?` for ${u}`:"",g={accountId:r,network:p.canonical,expiresInMinutes:c};if(o)g.sign=o;else if(n)g.signer=n;else if(s){if("hedera"!==p.kind||!p.hederaNetwork)throw new Error("hederaPrivateKey can only be used with hedera:mainnet or hedera:testnet networks.");g.signer=await Mp({accountId:r,privateKey:s,network:p.hederaNetwork})}else{if(!a)throw new Error("Provide a signer, sign function, hederaPrivateKey, or evmPrivateKey to authenticate with the ledger.");{if("evm"!==p.kind)throw new Error("evmPrivateKey can only be used with CAIP-2 EVM networks (eip155:<chainId>).");const e=a.startsWith("0x")?a:`0x${a}`,t=await async function(e){try{return(await import("viem/accounts")).privateKeyToAccount(e)}catch(t){const e=new Error('EVM ledger authentication requires the optional dependency "viem". Install it to use evmPrivateKey flows.');throw e.cause=t,e}}(e);g.sign=async e=>({signature:await t.signMessage({message:e}),signatureKind:"evm",publicKey:t.publicKey})}}d?.info?.(`Authenticating ledger account ${r} (${p.canonical})${h}...`);const m=await e.authenticateWithLedger(g);return l&&e.setDefaultHeader("x-account-id",m.accountId),d?.info?.(`Ledger authentication complete${h}. Issued key prefix: ${m.apiKey.prefix}…${m.apiKey.lastFour}`),m}async function Lp(e,t={}){const r=function(e){const t=new URLSearchParams,r=(e,r)=>{r&&r.forEach(r=>{if("string"==typeof r){const i=r.trim();i.length>0&&t.append(e,i)}})};if(e.q){const r=e.q.trim();r.length>0&&t.set("q",r)}if("number"==typeof e.page&&t.set("page",e.page.toString()),"number"==typeof e.limit&&t.set("limit",e.limit.toString()),e.registry){const r=e.registry.trim();r.length>0&&t.set("registry",r)}if(r("registries",e.registries),"number"==typeof e.minTrust&&t.set("minTrust",e.minTrust.toString()),r("capabilities",e.capabilities),r("protocols",e.protocols),r("adapters",e.adapters),e.metadata&&Object.entries(e.metadata).forEach(([e,r])=>{if(!e||!Array.isArray(r)||0===r.length)return;const i=e.trim();0!==i.length&&r.forEach(e=>{null!=e&&t.append(`metadata.${i}`,String(e))})}),e.type){const r=e.type.trim();r.length>0&&"all"!==r.toLowerCase()&&t.set("type",r)}if(!0===e.verified&&t.set("verified","true"),!0===e.online&&t.set("online","true"),e.sortBy){const r=e.sortBy.trim();r.length>0&&t.set("sortBy",r)}if(e.sortOrder){const r=e.sortOrder.toLowerCase();"asc"!==r&&"desc"!==r||t.set("sortOrder",r)}const i=t.toString();return i.length>0?`?${i}`:""}(t),i=await e.requestJson(`/search${r}`,{method:"GET"});return e.parseWithSchema(i,Uc,"search response")}async function Kp(e,t){try{const r=await e.requestJson("/search",{method:"POST",body:t,headers:{"content-type":"application/json"}});return e.parseWithSchema(r,fl,"vector search response")}catch(r){if(r instanceof hp&&501===r.status){const r=await Lp(e,function(e){const t={q:e.query};let r;if("number"==typeof e.limit&&Number.isFinite(e.limit)&&(r=e.limit,t.limit=e.limit),"number"==typeof e.offset&&Number.isFinite(e.offset)&&e.offset>0){const i=r&&r>0?r:20;t.limit=i,t.page=Math.floor(e.offset/i)+1}return e.filter?.registry&&(t.registry=e.filter.registry),e.filter?.protocols?.length&&(t.protocols=[...e.filter.protocols]),e.filter?.adapter?.length&&(t.adapters=[...e.filter.adapter]),e.filter?.capabilities?.length&&(t.capabilities=e.filter.capabilities.map(e=>"number"==typeof e?e.toString(10):e)),e.filter?.type&&(t.type=e.filter.type),t}(t));return function(e){const t=e.hits.map(e=>({agent:e,score:0,highlights:{}})),r=e.total,i=e.limit,n=e.page,o=r>n*i||n>1;return{hits:t,total:r,took:0,totalAvailable:r,visible:t.length,limited:o,credits_used:0}}(r)}throw r}}function $p(e){const t=e.repo.trim(),r=e.skillDir.trim();if(!t)throw new Error("repo is required");if(!r)throw new Error("skillDir is required");const i=new URLSearchParams;return i.set("repo",t),i.set("skillDir",r),e.ref?.trim()&&i.set("ref",e.ref.trim()),i.toString()}async function Hp(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=new URLSearchParams;i.set("name",r),t.version&&i.set("version",t.version);const n=await e.requestJson(`/skills/verification/status?${i.toString()}`,{method:"GET"});return e.parseWithSchema(n,Od,"skill verification status response")}class qp{constructor(e={}){this.encryptionBootstrapPromise=null,this.chatApi=null,this.encryptedChatManager=null,this.encryptionApi=null,this.conversationContexts=new Map;const{baseUrl:t=Kd,fetchImplementation:r,defaultHeaders:i,apiKey:n,accountId:o,ledgerApiKey:s,registrationAutoTopUp:a,historyAutoTopUp:c,encryption:l}=e;this.baseUrl=function(e){const t=e?.trim();let r=t&&t.length>0?t:Kd;try{const e=new URL(Hd(r)),t=e.hostname.toLowerCase(),i=()=>{e.pathname.startsWith("/registry")||(e.pathname="/"===e.pathname?"/registry":`/registry${e.pathname}`)};"hol.org"===t?(i(),r=e.toString()):"registry.hashgraphonline.com"!==t&&"hashgraphonline.com"!==t||(i(),e.hostname="hol.org",r=e.toString())}catch{}const i=Hd(r);return/\/api\/v\d+$/i.test(i)?i:/\/api$/i.test(i)?`${i}/v1`:`${i}/api/v1`}(t);const u=r??("function"==typeof globalThis.fetch?globalThis.fetch:null);if(!u)throw new Error("A fetch implementation is required for RegistryBrokerClient");this.fetchImpl=u,this.defaultHeaders={...i??{}},Object.entries(this.defaultHeaders).forEach(([e,t])=>{const r=jd(e);r!==e&&(delete this.defaultHeaders[e],this.defaultHeaders[r]=t)});const d=this.defaultHeaders["x-ledger-api-key"]?.trim();!this.defaultHeaders["x-api-key"]&&d&&(this.defaultHeaders["x-api-key"]=d),n&&(this.defaultHeaders["x-api-key"]=n),"string"==typeof o&&o.trim().length>0&&(this.defaultHeaders["x-account-id"]=o.trim()),s&&(this.defaultHeaders["x-api-key"]||(this.defaultHeaders["x-api-key"]=s)),this.registrationAutoTopUp=a,this.historyAutoTopUp=c,this.encryptionOptions=l,this.encryptionOptions&&(this.encryptionBootstrapPromise=this.initializeEncryptionBootstrap(this.encryptionOptions))}static async initializeAgent(e){const{uaid:t,ensureEncryptionKey:r=!0,...i}=e,n=new qp(i);let o=null;if(r){const e="object"==typeof r?r:{generateIfMissing:!0};o=await n.encryption.ensureAgentKey({uaid:t,...e})}return{client:n,encryption:o}}get chat(){if(this.chatApi)return this.chatApi;const e=(t=this,r=this.getEncryptedChatManager(),{start:e=>t.startChat(e),createSession:e=>t.createSession(e),sendMessage:e=>t.sendMessage(e),endSession:e=>t.endSession(e),getHistory:(e,r)=>t.fetchHistorySnapshot(e,r),compactHistory:e=>t.compactHistory(e),getEncryptionStatus:e=>t.fetchEncryptionStatus(e),submitEncryptionHandshake:(e,r)=>t.postEncryptionHandshake(e,r),startConversation:e=>t.startConversation(e),acceptConversation:e=>t.acceptConversation(e),createEncryptedSession:e=>r.startSession(e),acceptEncryptedSession:e=>r.acceptSession(e)});var t,r;return this.chatApi=e,e}get encryption(){if(this.encryptionApi)return this.encryptionApi;const e=sp(this);return this.encryptionApi=e,e}setApiKey(e){this.setDefaultHeader("x-api-key",e)}setLedgerApiKey(e){this.setDefaultHeader("x-api-key",e),delete this.defaultHeaders["x-ledger-api-key"]}setDefaultHeader(e,t){if(!e||0===e.trim().length)return;const r=jd(e);t&&0!==t.trim().length?this.defaultHeaders[r]=t.trim():delete this.defaultHeaders[r]}getDefaultHeaders(){return{...this.defaultHeaders}}async encryptionReady(){this.encryptionBootstrapPromise&&await this.encryptionBootstrapPromise}buildUrl(e){const t=e.startsWith("/")?e:`/${e}`;return`${this.baseUrl}${t}`}async request(e,t){const r=new Headers;Object.entries(this.defaultHeaders).forEach(([e,t])=>{r.set(e,t)}),t.headers&&Object.entries(t.headers).forEach(([e,t])=>{r.set(e,t)}),r.has("accept")||r.set("accept","application/json"),r.has("user-agent")||"undefined"!=typeof window&&"function"==typeof window.fetch||r.set("user-agent","@hol-org/rb-client");const i={method:t.method??"GET",headers:r};void 0!==t.body&&(i.body=JSON.stringify(t.body),r.has("content-type")||r.set("content-type","application/json"));const n=await this.fetchImpl(this.buildUrl(e),i);if(n.ok)return n;const o=await this.extractErrorBody(n);throw new hp("Registry broker request failed",{status:n.status,statusText:n.statusText,body:o})}async requestJson(e,t){const r=await this.request(e,t),i=r.headers?.get("content-type")??"";if(!$d.test(i)){const e=await r.text();throw new gp("Expected JSON response from registry broker",e)}return await r.json()}async getAgentFeedback(e,t={}){const r=e.trim();if(!r)throw new Error("uaid is required");const i=!0===t.includeRevoked?"?includeRevoked=true":"",n=await this.requestJson(`/agents/${encodeURIComponent(r)}/feedback${i}`,{method:"GET"});return this.parseWithSchema(n,Jc,"agent feedback response")}async listAgentFeedbackIndex(e={}){const t=new URLSearchParams;"number"==typeof e.page&&Number.isFinite(e.page)&&t.set("page",String(Math.trunc(e.page))),"number"==typeof e.limit&&Number.isFinite(e.limit)&&t.set("limit",String(Math.trunc(e.limit))),e.registries?.length&&t.set("registry",e.registries.join(","));const r=t.size>0?`?${t.toString()}`:"",i=await this.requestJson(`/agents/feedback${r}`,{method:"GET"});return this.parseWithSchema(i,Zc,"agent feedback index response")}async listAgentFeedbackEntriesIndex(e={}){const t=new URLSearchParams;"number"==typeof e.page&&Number.isFinite(e.page)&&t.set("page",String(Math.trunc(e.page))),"number"==typeof e.limit&&Number.isFinite(e.limit)&&t.set("limit",String(Math.trunc(e.limit))),e.registries?.length&&t.set("registry",e.registries.join(","));const r=t.size>0?`?${t.toString()}`:"",i=await this.requestJson(`/agents/feedback/entries${r}`,{method:"GET"});return this.parseWithSchema(i,Qc,"agent feedback entries index response")}async checkAgentFeedbackEligibility(e,t){const r=e.trim();if(!r)throw new Error("uaid is required");const i=await this.requestJson(`/agents/${encodeURIComponent(r)}/feedback/eligibility`,{method:"POST",body:t,headers:{"content-type":"application/json"}});return this.parseWithSchema(i,Yc,"agent feedback eligibility response")}async submitAgentFeedback(e,t){const r=e.trim();if(!r)throw new Error("uaid is required");const i=await this.requestJson(`/agents/${encodeURIComponent(r)}/feedback`,{method:"POST",body:t,headers:{"content-type":"application/json"}});return this.parseWithSchema(i,Xc,"agent feedback submission response")}async search(e={}){return Lp(this,e)}async delegate(e){return async function(e,t){const r=await e.requestJson("/delegate",{method:"POST",body:t,headers:{"content-type":"application/json"}});return e.parseWithSchema(r,Wc,"delegate response")}(this,e)}async searchErc8004ByAgentId(e){const t=Math.floor(e.chainId);if(!Number.isFinite(t)||t<=0)throw new Error("chainId must be a positive integer");const r=("bigint"==typeof e.agentId?e.agentId.toString():String(e.agentId)).trim();if(!r)throw new Error("agentId is required");const i=`${t}:${r}`;return Lp(this,{registries:["erc-8004"],limit:e.limit??1,..."number"==typeof e.page?{page:e.page}:{},..."string"==typeof e.sortBy?{sortBy:e.sortBy}:{},..."string"==typeof e.sortOrder?{sortOrder:e.sortOrder}:{},metadata:{nativeId:[i],networkKey:[`eip155:${t}`]}})}async stats(){return async function(e){const t=await e.requestJson("/stats",{method:"GET"});return e.parseWithSchema(t,Bc,"stats response")}(this)}async registries(){return async function(e){const t=await e.requestJson("/registries",{method:"GET"});return e.parseWithSchema(t,Lc,"registries response")}(this)}async getAdditionalRegistries(){return async function(e){const t=await e.requestJson("/register/additional-registries",{method:"GET"});return e.parseWithSchema(t,Ol,"additional registry catalog response")}(this)}async popularSearches(){return async function(e){const t=await e.requestJson("/popular",{method:"GET"});return e.parseWithSchema(t,Kc,"popular searches response")}(this)}async listProtocols(){return async function(e){const t=await e.requestJson("/protocols",{method:"GET"});return e.parseWithSchema(t,ul,"protocols response")}(this)}async detectProtocol(e){return async function(e,t){const r=await e.requestJson("/detect-protocol",{method:"POST",body:{message:t},headers:{"content-type":"application/json"}});return e.parseWithSchema(r,dl,"detect protocol response")}(this,e)}async registrySearchByNamespace(e,t){return async function(e,t,r){const i=new URLSearchParams;r&&i.set("q",r);const n=i.size>0?`?${i.toString()}`:"",o=await e.requestJson(`/registries/${encodeURIComponent(t)}/search${n}`,{method:"GET"});return e.parseWithSchema(o,pl,"registry search response")}(this,e,t)}async vectorSearch(e){return Kp(this,e)}async searchStatus(){return async function(e){const t=await e.requestJson("/search/status",{method:"GET"});return e.parseWithSchema(t,bl,"search status response")}(this)}async websocketStats(){return async function(e){const t=await e.requestJson("/websocket/stats",{method:"GET"});return e.parseWithSchema(t,wl,"websocket stats response")}(this)}async metricsSummary(){return async function(e){const t=await e.requestJson("/metrics",{method:"GET"});return e.parseWithSchema(t,Tl,"metrics summary response")}(this)}async facets(e){return async function(e,t){const r=new URLSearchParams;t&&r.set("adapter",t);const i=r.size>0?`?${r.toString()}`:"",n=await e.requestJson(`/search/facets${i}`,{method:"GET"});return e.parseWithSchema(n,au,"search facets response")}(this,e)}async adapters(){return async function(e){const t=await e.requestJson("/adapters",{method:"GET"});return e.parseWithSchema(t,Vl,"adapters response")}(this)}async skillsConfig(){return async function(e){const t=await e.requestJson("/skills/config",{method:"GET"});return e.parseWithSchema(t,bd,"skill registry config response")}(this)}async getSkillStatus(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=new URLSearchParams;i.set("name",r),t.version?.trim()&&i.set("version",t.version.trim());const n=await e.requestJson(`/skills/status?${i.toString()}`,{method:"GET"});return e.parseWithSchema(n,Ju,"skill status response")}(this,e)}async listSkills(e){return async function(e,t={}){const r=new URLSearchParams;t.name&&r.set("name",t.name),t.version&&r.set("version",t.version),"number"==typeof t.limit&&Number.isFinite(t.limit)&&r.set("limit",String(Math.trunc(t.limit))),t.cursor&&r.set("cursor",t.cursor),"boolean"==typeof t.includeFiles&&r.set("includeFiles",t.includeFiles?"true":"false"),t.accountId&&r.set("accountId",t.accountId),t.q&&r.set("q",t.q),t.tag&&r.set("tag",t.tag),t.category&&r.set("category",t.category),"boolean"==typeof t.featured&&r.set("featured",t.featured?"true":"false"),"boolean"==typeof t.verified&&r.set("verified",t.verified?"true":"false"),t.view&&r.set("view",t.view);const i=r.size>0?`?${r.toString()}`:"",n=await e.requestJson(`/skills${i}`,{method:"GET"});return e.parseWithSchema(n,Cu,"skill registry list response")}(this,e)}async getSkillSecurityBreakdown(e){return async function(e,t){const r=t.jobId.trim();if(!r)throw new Error("jobId is required");const i=await e.requestJson(`/skills/${encodeURIComponent(r)}/security-breakdown`,{method:"GET"});return e.parseWithSchema(i,Ru,"skill security breakdown response")}(this,e)}async getSkillsCatalog(e){return async function(e,t={}){const r=new URLSearchParams;t.q&&r.set("q",t.q),t.category&&r.set("category",t.category),t.tags?.forEach(e=>{e.trim()&&r.append("tag",e.trim())}),"boolean"==typeof t.featured&&r.set("featured",t.featured?"true":"false"),"boolean"==typeof t.verified&&r.set("verified",t.verified?"true":"false"),t.channel&&r.set("channel",t.channel),t.sortBy&&r.set("sortBy",t.sortBy),"number"==typeof t.limit&&Number.isFinite(t.limit)&&r.set("limit",String(Math.trunc(t.limit))),t.cursor&&r.set("cursor",t.cursor);const i=r.size>0?`?${r.toString()}`:"",n=await e.requestJson(`/skills/catalog${i}`,{method:"GET"});return e.parseWithSchema(n,zu,"skill catalog response")}(this,e)}async listSkillVersions(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=new URLSearchParams;i.set("name",r);const n=await e.requestJson(`/skills/versions?${i.toString()}`,{method:"GET"});return e.parseWithSchema(n,gd,"skill registry versions response")}(this,e)}async listMySkills(e){return async function(e,t={}){const r=new URLSearchParams;"number"==typeof t.limit&&Number.isFinite(t.limit)&&r.set("limit",String(Math.trunc(t.limit)));const i=r.size>0?`?${r.toString()}`:"",n=await e.requestJson(`/skills/mine${i}`,{method:"GET"});return e.parseWithSchema(n,fd,"skill registry mine response")}(this,e)}async getMySkillsList(e){return async function(e,t={}){const r=new URLSearchParams;"number"==typeof t.limit&&Number.isFinite(t.limit)&&r.set("limit",String(Math.trunc(t.limit))),t.cursor&&r.set("cursor",t.cursor),t.accountId&&r.set("accountId",t.accountId);const i=r.size>0?`?${r.toString()}`:"",n=await e.requestJson(`/skills/my-list${i}`,{method:"GET"});return e.parseWithSchema(n,yd,"skill registry my list response")}(this,e)}async quoteSkillPublish(e){return async function(e,t){const r=await e.requestJson("/skills/quote",{method:"POST",body:t,headers:{"content-type":"application/json"}});return e.parseWithSchema(r,ld,"skill registry quote response")}(this,e)}async publishSkill(e){return async function(e,t){const r=await e.requestJson("/skills/publish",{method:"POST",body:t,headers:{"content-type":"application/json"}});return e.parseWithSchema(r,dd,"skill registry publish response")}(this,e)}async getSkillPublishJob(e,t){return async function(e,t,r={}){const i=t.trim();if(!i)throw new Error("jobId is required");const n=new URLSearchParams;r.accountId&&n.set("accountId",r.accountId);const o=n.size>0?`?${n.toString()}`:"",s=await e.requestJson(`/skills/jobs/${encodeURIComponent(i)}${o}`,{method:"GET"});return e.parseWithSchema(s,pd,"skill registry job status response")}(this,e,t)}async getSkillOwnership(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=new URLSearchParams;i.set("name",r),t.accountId&&i.set("accountId",t.accountId);const n=await e.requestJson(`/skills/ownership?${i.toString()}`,{method:"GET"});return e.parseWithSchema(n,wd,"skill registry ownership response")}(this,e)}async getRecommendedSkillVersion(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=new URLSearchParams;i.set("name",r);const n=await e.requestJson(`/skills/recommended?${i.toString()}`,{method:"GET"});return e.parseWithSchema(n,_u,"skill recommended version response")}(this,e)}async setRecommendedSkillVersion(e){return async function(e,t){const r=t.name.trim(),i=t.version.trim();if(!r)throw new Error("name is required");if(!i)throw new Error("version is required");const n=await e.requestJson("/skills/recommended",{method:"POST",body:{name:r,version:i},headers:{"content-type":"application/json"}});return e.parseWithSchema(n,_u,"skill recommended version response")}(this,e)}async getSkillDeprecations(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=new URLSearchParams;i.set("name",r);const n=await e.requestJson(`/skills/deprecations?${i.toString()}`,{method:"GET"});return e.parseWithSchema(n,Ou,"skill deprecations response")}(this,e)}async setSkillDeprecation(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=t.version?.trim(),n=t.reason.trim();if(!n)throw new Error("reason is required");const o=t.replacementRef?.trim(),s=await e.requestJson("/skills/deprecate",{method:"POST",body:{name:r,version:i,reason:n,replacementRef:o},headers:{"content-type":"application/json"}});return e.parseWithSchema(s,Pu,"skill deprecation response")}(this,e)}async getSkillBadge(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=new URLSearchParams;i.set("name",r),t.metric&&i.set("metric",t.metric),t.label?.trim()&&i.set("label",t.label.trim()),t.style&&i.set("style",t.style);const n=await e.requestJson(`/skills/badge?${i.toString()}`,{method:"GET"});return e.parseWithSchema(n,nd,"skill badge response")}(this,e)}async getSkillStatusByRepo(e){return async function(e,t){const r=$p(t),i=await e.requestJson(`/skills/status/by-repo?${r}`,{method:"GET"});return e.parseWithSchema(i,Ju,"skill status response")}(this,e)}async uploadSkillPreviewFromGithubOidc(e){return async function(e,t){const r=t.token.trim();if(!r)throw new Error("token is required");const i=await e.requestJson("/skills/preview/github-oidc",{method:"POST",body:t.report,headers:{"content-type":"application/json",authorization:`Bearer ${r}`}});return e.parseWithSchema(i,Hu,"skill preview record response")}(this,e)}async getSkillPreview(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=new URLSearchParams;i.set("name",r),t.version?.trim()&&i.set("version",t.version.trim());const n=await e.requestJson(`/skills/preview?${i.toString()}`,{method:"GET"});return e.parseWithSchema(n,qu,"skill preview response")}(this,e)}async getSkillPreviewByRepo(e){return async function(e,t){const r=$p(t),i=await e.requestJson(`/skills/preview/by-repo?${r}`,{method:"GET"});return e.parseWithSchema(i,qu,"skill preview by repo response")}(this,e)}async getSkillPreviewById(e){return async function(e,t){const r=t.trim();if(!r)throw new Error("previewId is required");const i=await e.requestJson(`/skills/preview/${encodeURIComponent(r)}`,{method:"GET"});return e.parseWithSchema(i,qu,"skill preview by id response")}(this,e)}async getSkillInstall(e){return async function(e,t){const r=t.trim();if(!r)throw new Error("skillRef is required");const i=await e.requestJson(`/skills/${encodeURIComponent(r)}/install`,{method:"GET"});return e.parseWithSchema(i,td,"skill install response")}(this,e)}async recordSkillInstallCopy(e,t){return async function(e,t,r={}){const i=t.trim();if(!i)throw new Error("skillRef is required");const n=await e.requestJson(`/skills/${encodeURIComponent(i)}/telemetry/install-copy`,{method:"POST",body:r,headers:{"content-type":"application/json"}});return e.parseWithSchema(n,rd,"skill install copy telemetry response")}(this,e,t)}async listSkillTags(){return async function(e){const t=await e.requestJson("/skills/tags",{method:"GET"});return e.parseWithSchema(t,od,"skill tags response")}(this)}async listSkillCategories(){return async function(e){const t=await e.requestJson("/skills/categories",{method:"GET"});return e.parseWithSchema(t,sd,"skill categories response")}(this)}async resolveSkillMarkdown(e){return async function(e,t){const r=t.trim();if(!r)throw new Error("skillRef is required");return(await e.request(`/skills/${encodeURIComponent(r)}/SKILL.md`,{method:"GET",headers:{accept:"text/markdown, text/plain;q=0.9, */*;q=0.8"}})).text()}(this,e)}async resolveSkillManifest(e){return async function(e,t){const r=t.trim();if(!r)throw new Error("skillRef is required");const i=await e.requestJson(`/skills/${encodeURIComponent(r)}/manifest`,{method:"GET"});return e.parseWithSchema(i,ad,"skill resolver manifest response")}(this,e)}async getSkillVoteStatus(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=new URLSearchParams;i.set("name",r);const n=await e.requestJson(`/skills/vote?${i.toString()}`,{method:"GET"});return e.parseWithSchema(n,Id,"skill registry vote status response")}(this,e)}async setSkillVote(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=await e.requestJson("/skills/vote",{method:"POST",body:{name:r,upvoted:t.upvoted},headers:{"content-type":"application/json"}});return e.parseWithSchema(i,Id,"skill registry vote status response")}(this,e)}async requestSkillVerification(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=await e.requestJson("/skills/verification/request",{method:"POST",body:{name:r,version:t.version,tier:t.tier},headers:{"content-type":"application/json"}});return e.parseWithSchema(i,Pd,"skill verification request create response")}(this,e)}async getSkillVerificationStatus(e){return Hp(this,e)}async createSkillDomainProofChallenge(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=await e.requestJson("/skills/verification/domain/challenge",{method:"POST",body:{name:r,version:t.version,domain:t.domain},headers:{"content-type":"application/json"}});return e.parseWithSchema(i,Dd,"skill domain proof challenge response")}(this,e)}async verifySkillDomainProof(e){return async function(e,t){const r=t.name.trim(),i=t.challengeToken.trim();if(!r)throw new Error("name is required");if(!i)throw new Error("challengeToken is required");const n=await e.requestJson("/skills/verification/domain/verify",{method:"POST",body:{name:r,version:t.version,domain:t.domain,challengeToken:i},headers:{"content-type":"application/json"}});return e.parseWithSchema(n,Fd,"skill domain proof verify response")}(this,e)}async adaptersDetailed(){return async function(e){const t=await e.requestJson("/adapters/details",{method:"GET"});return e.parseWithSchema(t,nu,"adapter details response")}(this)}async adapterRegistryCategories(){return async function(e){const t=await e.requestJson("/adapters/registry/categories",{method:"GET"});return e.parseWithSchema(t,Jl,"adapter registry categories response")}(this)}async adapterRegistryAdapters(e){return async function(e,t={}){const r=new URLSearchParams;t.category&&r.set("category",t.category),t.entity&&r.set("entity",t.entity),t.keywords?.length&&r.set("keywords",t.keywords.join(",")),t.query&&r.set("query",t.query),"number"==typeof t.limit&&r.set("limit",String(t.limit)),"number"==typeof t.offset&&r.set("offset",String(t.offset));const i=r.size>0?`?${r.toString()}`:"",n=await e.requestJson(`/adapters/registry/adapters${i}`,{method:"GET"});return e.parseWithSchema(n,Xl,"adapter registry adapters response")}(this,e)}async createAdapterRegistryCategory(e){return async function(e,t){const r=await e.requestJson("/adapters/registry/categories",{method:"POST",headers:{"content-type":"application/json"},body:Gd(t)});return e.parseWithSchema(r,Zl,"adapter registry create category response").category}(this,e)}async submitAdapterRegistryAdapter(e){return async function(e,t){const r=await e.requestJson("/adapters/registry/adapters",{method:"POST",headers:{"content-type":"application/json"},body:Gd(t)});return e.parseWithSchema(r,Ql,"adapter registry submit adapter response")}(this,e)}async adapterRegistrySubmissionStatus(e){return async function(e,t){const r=await e.requestJson(`/adapters/registry/submissions/${encodeURIComponent(t)}`,{method:"GET"});return e.parseWithSchema(r,eu,"adapter registry submission status response")}(this,e)}async resolveUaid(e){return wp(this,e)}async performRegisterAgent(e){const t=await this.requestJson("/register",{method:"POST",body:Yd(e),headers:{"content-type":"application/json"}});return this.parseWithSchema(t,Ul,"register agent response")}calculateHbarAmount(e,t){if(t<=0)throw new Error("creditsPerHbar must be positive");if(e<=0)throw new Error("creditsToPurchase must be positive");const r=e/t;return Math.ceil(1e8*r)/1e8}resolveCreditsToPurchase(e){return!Number.isFinite(e)||e<=0?0:Math.max(Math.ceil(e),1)}async ensureCreditsForRegistration(e,t){const r=t??null;if(!r)return;if(!r.accountId||!r.accountId.trim())throw new Error("autoTopUp.accountId is required");if(!r.privateKey||!r.privateKey.trim())throw new Error("autoTopUp.privateKey is required");for(let i=0;i<3;i+=1){const t=await this.getRegistrationQuote(e),i=t.shortfallCredits??0;if(i<=0)return;const n=this.resolveCreditsToPurchase(i);if(n<=0)return;const o=t.creditsPerHbar??null;if(!o||o<=0)throw new Error("Unable to determine credits per HBAR for auto top-up");const s=this.calculateHbarAmount(n,o);await this.purchaseCreditsWithHbar({accountId:r.accountId.trim(),privateKey:r.privateKey.trim(),hbarAmount:s,memo:r.memo??"Registry Broker auto top-up",metadata:{shortfallCredits:i,requiredCredits:t.requiredCredits,purchasedCredits:n}})}if(((await this.getRegistrationQuote(e)).shortfallCredits??0)>0)throw new Error("Unable to purchase sufficient credits for registration")}async registerAgent(e,t){const r=t?.autoTopUp??this.registrationAutoTopUp;if(!r)return this.performRegisterAgent(e);await this.ensureCreditsForRegistration(e,r);let i=!1;for(;;)try{return await this.performRegisterAgent(e)}catch(n){if(this.extractInsufficientCreditsDetails(n)&&!i){await this.ensureCreditsForRegistration(e,r),i=!0;continue}throw n}}async getRegistrationQuote(e){return Ip(this,e)}async updateAgent(e,t){return Tp(this,e,t)}async getRegisterStatus(e){return async function(e,t){const r=await e.requestJson(`/register/status/${encodeURIComponent(t)}`,{method:"GET"});return e.parseWithSchema(r,yu,"register status response")}(this,e)}async registerOwnedMoltbookAgent(e,t){return async function(e,t,r){const i=await e.requestJson(`/register/${encodeURIComponent(t)}`,{method:"PUT",headers:{"content-type":"application/json"},body:{registered:r.registered??!0,...r.name?{name:r.name}:{},...r.description?{description:r.description}:{},...r.endpoint?{endpoint:r.endpoint}:{},...r.metadata?{metadata:r.metadata}:{}}});return e.parseWithSchema(i,bu,"moltbook owner registration update response")}(this,e,t)}async getRegistrationProgress(e){return Sp(this,e)}async waitForRegistrationCompletion(e,t){return kp(this,e,t)}async validateUaid(e){return vp(this,e)}async getUaidConnectionStatus(e){return Ep(this,e)}async closeUaidConnection(e){return Ap(this,e)}async dashboardStats(){return Cp(this)}async purchaseCreditsWithHbar(e){return up(this,e)}async getX402Minimums(){return async function(e){const t=await e.requestJson("/credits/purchase/x402/minimums",{method:"GET"});return e.parseWithSchema(t,Wl,"x402 minimums response")}(this)}async purchaseCreditsWithX402(e){return dp(this,e)}async buyCreditsWithX402(e){return pp(this,e)}async generateEncryptionKeyPair(e={}){return ap(this,e)}async createLedgerChallenge(e){return async function(e,t){const r=Pp(t.network),i="hedera"===r.kind?r.hederaNetwork??r.canonical:r.canonical,n=await e.requestJson("/auth/ledger/challenge",{method:"POST",headers:{"content-type":"application/json"},body:{accountId:t.accountId,network:i}});return e.parseWithSchema(n,al,"ledger challenge response")}(this,e)}async verifyLedgerChallenge(e){return async function(e,t){const r=Pp(t.network),i="hedera"===r.kind?r.hederaNetwork??r.canonical:r.canonical,n={challengeId:t.challengeId,accountId:t.accountId,network:i,signature:t.signature};t.signatureKind&&(n.signatureKind=t.signatureKind),t.publicKey&&(n.publicKey=t.publicKey),"number"==typeof t.expiresInMinutes&&(n.expiresInMinutes=t.expiresInMinutes);const o=await e.requestJson("/auth/ledger/verify",{method:"POST",headers:{"content-type":"application/json"},body:n}),s=e.parseWithSchema(o,ll,"ledger verification response");return e.setLedgerApiKey(s.key),s}(this,e)}async authenticateWithLedger(e){return Up(this,e)}async authenticateWithLedgerCredentials(e){return Bp(this,e)}async getVerificationStatus(e){return async function(e,t){const r=await e.requestJson(`/verification/status/${encodeURIComponent(t)}`,{method:"GET"});return e.parseWithSchema(r,hu,"verification status response")}(this,e)}async createVerificationChallenge(e){return async function(e,t){const r=await e.requestJson("/verification/challenge",{method:"POST",headers:{"content-type":"application/json"},body:{uaid:t}});return e.parseWithSchema(r,lu,"verification challenge response")}(this,e)}async getVerificationChallenge(e){return async function(e,t){const r=await e.requestJson(`/verification/challenge/${encodeURIComponent(t)}`,{method:"GET"});return e.parseWithSchema(r,uu,"verification challenge details response")}(this,e)}async verifyVerificationChallenge(e){return async function(e,t){const r=await e.requestJson("/verification/verify",{method:"POST",headers:{"content-type":"application/json"},body:{challengeId:t.challengeId,method:t.method??"moltbook-post"}});return e.parseWithSchema(r,du,"verification verify response")}(this,e)}async getVerificationOwnership(e){return async function(e,t){const r=await e.requestJson(`/verification/ownership/${encodeURIComponent(t)}`,{method:"GET"});return e.parseWithSchema(r,pu,"verification ownership response")}(this,e)}async verifySenderOwnership(e){return async function(e,t){const r=await e.requestJson("/verification/verify-sender",{method:"POST",headers:{"content-type":"application/json"},body:{uaid:t}});return e.parseWithSchema(r,gu,"verification sender response")}(this,e)}async verifyUaidDnsTxt(e){return async function(e,t){const r=await e.requestJson("/verification/dns/verify",{method:"POST",headers:{"content-type":"application/json"},body:{uaid:t.uaid,...void 0!==t.persist?{persist:t.persist}:{}}});return e.parseWithSchema(r,fu,"verification dns verify response")}(this,e)}async getVerificationDnsStatus(e,t){return async function(e,t,r){const i=new URLSearchParams;void 0!==r?.refresh&&i.set("refresh",String(r.refresh)),void 0!==r?.persist&&i.set("persist",String(r.persist));const n=i.toString(),o=`/verification/dns/status/${encodeURIComponent(t)}${n?`?${n}`:""}`,s=await e.requestJson(o,{method:"GET"});return e.parseWithSchema(s,fu,"verification dns status response")}(this,e,t)}async fetchHistorySnapshot(e,t){return async function(e,t,r,i){if(!r||0===r.trim().length)throw new Error("sessionId is required to fetch chat history");const n=await t.requestJson(`/chat/session/${encodeURIComponent(r)}/history`,{method:"GET"}),o=t.parseWithSchema(n,rl,"chat history snapshot response");return Ud(e,t,r,o,i)}(this.conversationContexts,this,e,t)}attachDecryptedHistory(e,t,r){return Ud(this.conversationContexts,this,e,t,r)}registerConversationContextForEncryption(e){!function(e,t){const r={sessionId:t.sessionId,sharedSecret:o.Buffer.from(t.sharedSecret),identity:t.identity?{...t.identity}:void 0},i=e.get(t.sessionId)??[],n=i.findIndex(e=>Md(e.identity,r.identity));n>=0?i[n]=r:i.push(r),e.set(t.sessionId,i)}(this.conversationContexts,e)}resolveDecryptionContext(e,t){return Bd(this.conversationContexts,this,e,t)}decryptHistoryEntryFromContext(e,t,r){return Ld(this,t,r)}async createSession(e,t=!0){return Qd(this,e,t)}async startChat(e){return async function(e,t,r){if("uaid"in r&&r.uaid)return ep(e,t,{uaid:r.uaid,senderUaid:r.senderUaid,historyTtlSeconds:r.historyTtlSeconds,auth:r.auth,encryption:r.encryption,onSessionCreated:r.onSessionCreated});if("agentUrl"in r&&r.agentUrl){const t=await Qd(e,{agentUrl:r.agentUrl,auth:r.auth,historyTtlSeconds:r.historyTtlSeconds,senderUaid:r.senderUaid});return r.onSessionCreated?.(t.sessionId),tp(e,t.sessionId,t.encryption??null,r.auth,{agentUrl:r.agentUrl,uaid:r.uaid})}throw new Error("startChat requires either uaid or agentUrl")}(this,this.getEncryptedChatManager(),e)}async startConversation(e){return ep(this,this.getEncryptedChatManager(),e)}async acceptConversation(e){return async function(e,t,r){const i=r.encryption?.preference??"preferred";if("disabled"===i)return tp(e,r.sessionId,null);try{return await t.acceptSession({sessionId:r.sessionId,responderUaid:r.responderUaid,handshakeTimeoutMs:r.encryption?.handshakeTimeoutMs,pollIntervalMs:r.encryption?.pollIntervalMs})}catch(n){if(n instanceof Xd&&"required"!==i)return tp(e,r.sessionId,null,void 0,{uaid:r.responderUaid});throw n}}(this,this.getEncryptedChatManager(),e)}compactHistory(e){return async function(e,t){if(!t.sessionId||0===t.sessionId.trim().length)throw new Error("sessionId is required to compact chat history");const r={};"number"==typeof t.preserveEntries&&Number.isFinite(t.preserveEntries)&&t.preserveEntries>=0&&(r.preserveEntries=Math.floor(t.preserveEntries));const i=await e.requestJson(`/chat/session/${encodeURIComponent(t.sessionId)}/compact`,{method:"POST",headers:{"content-type":"application/json"},body:r});return e.parseWithSchema(i,il,"chat history compaction response")}(this,e)}fetchEncryptionStatus(e){return async function(e,t){if(!t||0===t.trim().length)throw new Error("sessionId is required for encryption status");const r=await e.requestJson(`/chat/session/${encodeURIComponent(t)}/encryption`,{method:"GET"});return e.parseWithSchema(r,nl,"session encryption status response")}(this,e)}postEncryptionHandshake(e,t){return async function(e,t,r){if(!t||0===t.trim().length)throw new Error("sessionId is required for encryption handshake");const i=await e.requestJson(`/chat/session/${encodeURIComponent(t)}/encryption-handshake`,{method:"POST",headers:{"content-type":"application/json"},body:{role:r.role,keyType:r.keyType,ephemeralPublicKey:r.ephemeralPublicKey,longTermPublicKey:r.longTermPublicKey,signature:r.signature,uaid:r.uaid,userId:r.userId,ledgerAccountId:r.ledgerAccountId,metadata:r.metadata}});return e.parseWithSchema(i,ol,"encryption handshake response").handshake}(this,e,t)}sendMessage(e){return rp(this,e)}endSession(e){return async function(e,t){await e.request(`/chat/session/${encodeURIComponent(t)}`,{method:"DELETE"})}(this,e)}createPlaintextConversationHandle(e,t,r,i){return tp(this,e,t,r,i)}getEncryptedChatManager(){if(this.encryptedChatManager)return this.encryptedChatManager;const e=new Zd(this);return this.encryptedChatManager=e,e}async extractErrorBody(e){const t=e.headers?.get("content-type")??"";if($d.test(t))try{return await e.json()}catch(r){return{parseError:String(r)}}try{return await e.text()}catch(r){return{parseError:String(r)}}}parseWithSchema(e,r,i){try{return r.parse(e)}catch(n){throw new gp(`Failed to parse ${i}`,n instanceof t.ZodError||n instanceof Error?n:String(n),e)}}async delay(e,t){if(e<=0){if(t?.aborted)throw qd()}else await new Promise((r,i)=>{const n=setTimeout(()=>{t&&t.removeEventListener("abort",o),r()},e),o=()=>{clearTimeout(n),t?.removeEventListener("abort",o),i(qd())};if(t){if(t.aborted)return clearTimeout(n),void i(qd());t.addEventListener("abort",o,{once:!0})}})}assertNodeRuntime(e){if("undefined"==typeof process||!process.versions?.node)throw new Error(`${e} is only available in Node.js environments`)}getNodeCrypto(e){this.assertNodeRuntime(e);const t=Sa("node:crypto")??Sa("crypto");if(!t)throw new Error(`${e} requires the Node.js crypto module`);return t}createEphemeralKeyPair(){const{randomBytes:e}=this.getNodeCrypto("generateEphemeralKeyPair"),t=e(32),r=c.secp256k1.getPublicKey(t,!0);return{privateKey:o.Buffer.from(t).toString("hex"),publicKey:o.Buffer.from(r).toString("hex")}}deriveSharedSecret(e){const{createHash:t}=this.getNodeCrypto("deriveSharedSecret"),r=this.hexToBuffer(e.privateKey),i=this.hexToBuffer(e.peerPublicKey),n=c.secp256k1.getSharedSecret(r,i,!0);return t("sha256").update(o.Buffer.from(n)).digest()}buildCipherEnvelope(e){const{createCipheriv:t,randomBytes:r}=this.getNodeCrypto("encryptCipherEnvelope"),i=this.normalizeSharedSecret(e.sharedSecret),n=r(12),s=t("aes-256-gcm",i,n),a=e.associatedData??e.sessionId,c=a?o.Buffer.from(a,"utf8").toString("base64"):void 0;a&&s.setAAD(o.Buffer.from(a,"utf8"));const l=o.Buffer.concat([s.update(o.Buffer.from(e.plaintext,"utf8")),s.final()]),u=s.getAuthTag();return{algorithm:"aes-256-gcm",ciphertext:o.Buffer.concat([l,u]).toString("base64"),nonce:n.toString("base64"),associatedData:c,keyLocator:{sessionId:e.sessionId,revision:e.revision??1},recipients:e.recipients.map(e=>({...e,encryptedShare:""}))}}openCipherEnvelope(e){const{createDecipheriv:t}=this.getNodeCrypto("decryptCipherEnvelope"),r=this.normalizeSharedSecret(e.sharedSecret),i=o.Buffer.from(e.envelope.ciphertext,"base64"),n=o.Buffer.from(e.envelope.nonce,"base64"),s=i.slice(0,i.length-16),a=i.slice(i.length-16),c=t("aes-256-gcm",r,n);e.envelope.associatedData&&c.setAAD(o.Buffer.from(e.envelope.associatedData,"base64")),c.setAuthTag(a);return o.Buffer.concat([c.update(s),c.final()]).toString(e.encoding??"utf8")}normalizeSharedSecret(e){if(o.Buffer.isBuffer(e))return o.Buffer.from(e);if(e instanceof Uint8Array)return o.Buffer.from(e);if("string"==typeof e)return this.bufferFromString(e);throw new Error("Unsupported shared secret input")}bufferFromString(e){const t=e.trim();if(!t)throw new Error("sharedSecret string cannot be empty");const r=t.startsWith("0x")?t.slice(2):t;return/^[0-9a-fA-F]+$/.test(r)&&r.length%2==0?o.Buffer.from(r,"hex"):o.Buffer.from(t,"base64")}hexToBuffer(e){const t=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(t)||t.length%2!=0)throw new Error("Expected hex-encoded value");return o.Buffer.from(t,"hex")}extractInsufficientCreditsDetails(e){if(!(e instanceof hp)||402!==e.status)return null;const t=e.body;if(!t||"object"!=typeof t||Array.isArray(t))return null;const r=t.shortfallCredits;return"number"!=typeof r||r<=0?null:{shortfallCredits:r}}extractErrorMessage(e){return"string"==typeof e?e:Vd(e)&&"string"==typeof e.error?e.error:Vd(e)&&"string"==typeof e.message?e.message:void 0}shouldAutoTopUpHistory(e,t){if(!this.historyAutoTopUp||void 0===e.historyTtlSeconds)return!1;if(!(t instanceof hp))return!1;if(402!==t.status)return!1;const r=this.extractErrorMessage(t.body);if(!r)return!0;const i=r.toLowerCase();return i.includes("history")||i.includes("chat history")}async executeHistoryAutoTopUp(e){if(!this.historyAutoTopUp)return;const t=this.historyAutoTopUp.hbarAmount&&this.historyAutoTopUp.hbarAmount>0?this.historyAutoTopUp.hbarAmount:.25;await this.purchaseCreditsWithHbar({accountId:this.historyAutoTopUp.accountId,privateKey:this.historyAutoTopUp.privateKey,hbarAmount:t,memo:this.historyAutoTopUp.memo??"registry-broker-client:chat-history-topup",metadata:{purpose:"chat-history",reason:e}})}initializeEncryptionBootstrap(e){return this.bootstrapEncryptionOptions(e).then(()=>{})}bootstrapEncryptionOptions(e){return async function(e,t){return t?.autoRegister&&!1!==t.autoRegister.enabled?op(e,t.autoRegister):null}(this,e)}}const jp="hol-chat",Wp=e=>Boolean(e)&&"object"==typeof e&&!Array.isArray(e),Vp=e=>{if(!Wp(e))return!1;if(e.p!==jp)return!1;if("string"!=typeof e.request_id||0===e.request_id.trim().length)return!1;const t=e.op;return"payment_request"===t||"payment_approve"===t||"payment_decline"===t||"payment_result"===t||"job_status"===t};class Gp{constructor(e="info"){this.defaultEndpoint="https://kiloscribe.com/api/inscription-cdn",this.logger=y.getInstance({level:e,module:"HRLResolver"})}isBinaryContentType(e){return["image/","audio/","video/","application/octet-stream","application/pdf","application/zip","application/gzip","application/x-binary","application/vnd.ms-","application/x-msdownload","application/x-shockwave-flash","font/","application/wasm"].some(t=>e.startsWith(t))}parseHRL(e){if(!e)return null;const t=e.match(/^hcs:\/\/(\d+)\/([0-9]+\.[0-9]+\.[0-9]+)$/);return t?{standard:t[1],topicId:t[2]}:null}isValidHRL(e){if(!e||"string"!=typeof e)return!1;const t=this.parseHRL(e);if(!t)return!1;return!!/^[0-9]+\.[0-9]+\.[0-9]+$/.test(t.topicId)}isValidTopicId(e){return/^[0-9]+\.[0-9]+\.[0-9]+$/.test(e)}async resolve(e,t){if(this.isValidHRL(e))return this.resolveHRL(e,t);if(!this.isValidTopicId(e))throw new Error(`Invalid HRL or topic ID format: ${e}`);try{const r=new x(t.network,this.logger),i=await r.getTopicInfo(e),n=i?.memo||"";let o="1";if(n){const e=n.match(/^hcs-(\d+)/);e&&e[1]&&(o=e[1])}const s=`hcs://${o}/${e}`;return this.resolveHRL(s,t)}catch(r){this.logger.error(`Failed to get topic info for ${e}: ${r.message}`);const i=`hcs://1/${e}`;return this.resolveHRL(i,t)}}async getContentWithType(e,t){if(!this.isValidHRL(e))return{content:e,contentType:"text/plain",isBinary:!1};try{const r=await this.resolveHRL(e,t);return{content:r.content,contentType:r.contentType,isBinary:r.isBinary}}catch(Pw){const t=`Error resolving HRL for content and type: ${Pw.message}`;throw this.logger.error(t),new Error(t)}}async resolveHRL(e,t){const r=this.parseHRL(e);if(!r)throw new Error(`Invalid HRL format: ${e}`);const{standard:n,topicId:o}=r;this.logger.debug(`Resolving HRL reference: standard=${n}, topicId=${o}`);try{const e=`${t.cdnEndpoint||this.defaultEndpoint}/${o}?network=${t.network}`;this.logger.debug(`Fetching content from CDN: ${e}`);const r=(await i.head(e)).headers["content-type"]||"";if(this.isBinaryContentType(r)||t.returnRaw){return{content:(await i.get(e,{responseType:"arraybuffer"})).data,contentType:r,topicId:o,isBinary:!0}}if("application/json"===r){const t=await i.get(e,{responseType:"json"});if(!t.data)throw new Error(`Failed to fetch content from topic: ${o}`);return{content:t.data,contentType:r,topicId:o,isBinary:!1}}const n=await i.get(e);if(!n.data)throw new Error(`Failed to fetch content from topic: ${o}`);let s;return s="object"==typeof n.data?n.data.content||n.data.text||JSON.stringify(n.data):n.data,{content:s,contentType:r,topicId:o,isBinary:!1}}catch(Pw){const t=`Error resolving HRL reference: ${Pw.message}`;throw this.logger.error(t),new Error(t)}}}class Jp{constructor(e){this.nodeHash=e}update(e){return this.nodeHash.update(e),this}digest(e){return this.nodeHash.digest(e)}}class Yp{constructor(e){this.algorithm=e,this.data=[]}update(e){const t="string"==typeof e?(new TextEncoder).encode(e):new Uint8Array(e);return this.data.push(t),this}async digest(e){const t=this.concatenateArrays(this.data),r=new Uint8Array(t),i=globalThis.crypto;if(!i?.subtle)throw new Error("WebCrypto not available");const n=await i.subtle.digest(this.mapAlgorithm(this.algorithm),r);return"hex"===e?Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join(""):globalThis.Buffer.from(n)}concatenateArrays(e){const t=e.reduce((e,t)=>e+t.length,0),r=new Uint8Array(t);let i=0;for(const n of e)r.set(n,i),i+=n.length;return r}mapAlgorithm(e){return{sha256:"SHA-256",sha384:"SHA-384",sha1:"SHA-1",sha512:"SHA-512"}[e.toLowerCase()]||"SHA-256"}}class Xp{constructor(e){this.algorithm=e,this.data=[]}update(e){const t="string"==typeof e?globalThis.Buffer.from(e):e;return this.data.push(t),this}digest(e){const t=globalThis.Buffer.concat(this.data),r=this.simpleHash(t);return"hex"===e?r.toString(16).padStart(8,"0"):r.toString()}simpleHash(e){let t=0;for(let r=0;r<e.length;r++)t=(t<<5)-t+e[r]&4294967295;return Math.abs(t)}}function Zp(){const e="undefined"==typeof window,t="undefined"!=typeof globalThis?globalThis.crypto:void 0;let r,i=!1,n=!1;try{i="undefined"!=typeof process&&!!process.versions?.node}catch{i=!1}try{n=!e&&void 0!==t&&void 0!==t.subtle}catch{n=!1}return r=n?"web":i?"node":"none",{hasNodeCrypto:i,hasWebCrypto:n,isSSR:e,preferredAPI:r}}function Qp(){return"undefined"==typeof window}class eh{constructor(e){this.nodeHmac=e}update(e){return this.nodeHmac.update(e),this}digest(e){return this.nodeHmac.digest(e)}}class th{constructor(e,t="sha256"){this.key=e,this.algorithm=t,this.data=[]}update(e){return this.data.push(e),this}async digest(e){const t=globalThis.Buffer.concat(this.data),r=new Uint8Array(this.key),i=globalThis.crypto;if(!i?.subtle)throw new Error("WebCrypto not available");const n=await i.subtle.importKey("raw",r,{name:"HMAC",hash:this.mapAlgorithm(this.algorithm)},!1,["sign"]),o=await i.subtle.sign("HMAC",n,new Uint8Array(t));return"hex"===e?Array.from(new Uint8Array(o)).map(e=>e.toString(16).padStart(2,"0")).join(""):globalThis.Buffer.from(o)}mapAlgorithm(e){return{sha256:"SHA-256",sha1:"SHA-1",sha512:"SHA-512"}[e.toLowerCase()]||"SHA-256"}}class rh{constructor(e,t="sha256"){this.key=e,this.algorithm=t,this.data=[]}update(e){return this.data.push(e),this}digest(e){const t=globalThis.Buffer.concat(this.data),r=this.simpleHmac(t,this.key);return"hex"===e?r.toString(16).padStart(8,"0"):r.toString()}simpleHmac(e,t){let r=0;for(let i=0;i<e.length;i++){const n=t[i%t.length];r=(r<<5)-r+e[i]+n&4294967295}return Math.abs(r)}}class ih{constructor(){try{const e="crypto";this.crypto=require(e)}catch(e){throw new Error("Node.js crypto module not available")}}createHash(e){return new Jp(this.crypto.createHash(e))}createHmac(e,t){return new eh(this.crypto.createHmac(e,t))}async pbkdf2(e,t,r,i,n){return new Promise((o,s)=>{this.crypto.pbkdf2(e,t,r,i,n,(e,t)=>{e?s(e):o(t)})})}timingSafeEqual(e,t){return this.crypto.timingSafeEqual(e,t)}}class nh{createHash(e){return new Yp(e)}createHmac(e,t){return new th(t,e)}async pbkdf2(e,t,r,i,n){const o=new TextEncoder,s=globalThis.crypto;if(!s?.subtle)throw new Error("WebCrypto not available");const a=await s.subtle.importKey("raw",o.encode(e),{name:"PBKDF2"},!1,["deriveBits"]),c=await s.subtle.deriveBits({name:"PBKDF2",salt:new Uint8Array(t),iterations:r,hash:this.mapDigest(n)},a,8*i);return globalThis.Buffer.from(c)}timingSafeEqual(e,t){if(e.length!==t.length)return!1;let r=0;for(let i=0;i<e.length;i++)r|=e[i]^t[i];return 0===r}mapDigest(e){return{sha256:"SHA-256",sha1:"SHA-1",sha512:"SHA-512"}[e.toLowerCase()]||"SHA-256"}}class oh{createHash(e){return new Xp(e)}createHmac(e,t){return new rh(t,e)}async pbkdf2(e,t,r,i,n){const o=new TextEncoder,s=globalThis.Buffer.from(o.encode(e));let a=globalThis.Buffer.alloc(i);for(let c=0;c<r;c++){const e=globalThis.Buffer.concat([s,t,globalThis.Buffer.from([c])]);let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e[t]&4294967295;a[c%i]^=255&r}return a}timingSafeEqual(e,t){if(e.length!==t.length)return!1;let r=0;for(let i=0;i<e.length;i++)r|=e[i]^t[i];return 0===r}}function sh(){switch(Zp().preferredAPI){case"node":try{return new ih}catch{const e="undefined"!=typeof globalThis?globalThis.crypto:void 0;return void 0!==e?.subtle?new nh:new oh}case"web":return new nh;default:return new oh}}async function ah(e,t="sha256"){const r=sh().createHash(t),i="string"==typeof e?globalThis.Buffer.from(e):e,n=r.update(i).digest("hex");return n instanceof Promise?await n:n}const ch=["mainnet","testnet","previewnet","devnet"];function lh(e){return ch.includes(e)}const uh=/^hedera:(mainnet|testnet|previewnet|devnet):\d+\.\d+\.\d+(?:-[a-zA-Z0-9]{5})?$/;function dh(e){return uh.test(e)}function ph(e,t){if(!lh(e))throw new Error("Invalid Hedera network");if(t.startsWith("hedera:")){if(dh(t))return t;throw new Error("Invalid Hedera CAIP-10 account")}if(!/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9]{5})?$/.test(t))throw new Error("Invalid Hedera accountId format");return`hedera:${e}:${t}`}function hh(e){if(!dh(e))throw new Error("Invalid Hedera CAIP-10");const[,t,r]=e.match(/^hedera:([^:]+):(.+)$/);return{network:t,accountId:r}}const gh=/^eip155:(\d+):(0x[0-9a-fA-F]{39,40})$/;function mh(e){return gh.test(e)}function fh(e,t){const r=`eip155:${"number"==typeof e?String(e):e}:${t.startsWith("0x")?t:`0x${t}`}`;if(!mh(r))throw new Error("Invalid EIP-155 CAIP-10");return r}var yh=(e=>(e[e.PERSONAL=0]="PERSONAL",e[e.AI_AGENT=1]="AI_AGENT",e[e.MCP_SERVER=2]="MCP_SERVER",e[e.FLORA=3]="FLORA",e))(yh||{}),bh=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(bh||{}),wh=(e=>(e[e.REST=0]="REST",e[e.WEBSOCKET=1]="WEBSOCKET",e[e.GRPC=2]="GRPC",e))(wh||{}),Ih=(e=>(e[e.TEXT_GENERATION=0]="TEXT_GENERATION",e[e.IMAGE_GENERATION=1]="IMAGE_GENERATION",e[e.AUDIO_GENERATION=2]="AUDIO_GENERATION",e[e.VIDEO_GENERATION=3]="VIDEO_GENERATION",e[e.CODE_GENERATION=4]="CODE_GENERATION",e[e.LANGUAGE_TRANSLATION=5]="LANGUAGE_TRANSLATION",e[e.SUMMARIZATION_EXTRACTION=6]="SUMMARIZATION_EXTRACTION",e[e.KNOWLEDGE_RETRIEVAL=7]="KNOWLEDGE_RETRIEVAL",e[e.DATA_INTEGRATION=8]="DATA_INTEGRATION",e[e.MARKET_INTELLIGENCE=9]="MARKET_INTELLIGENCE",e[e.TRANSACTION_ANALYTICS=10]="TRANSACTION_ANALYTICS",e[e.SMART_CONTRACT_AUDIT=11]="SMART_CONTRACT_AUDIT",e[e.GOVERNANCE_FACILITATION=12]="GOVERNANCE_FACILITATION",e[e.SECURITY_MONITORING=13]="SECURITY_MONITORING",e[e.COMPLIANCE_ANALYSIS=14]="COMPLIANCE_ANALYSIS",e[e.FRAUD_DETECTION=15]="FRAUD_DETECTION",e[e.MULTI_AGENT_COORDINATION=16]="MULTI_AGENT_COORDINATION",e[e.API_INTEGRATION=17]="API_INTEGRATION",e[e.WORKFLOW_AUTOMATION=18]="WORKFLOW_AUTOMATION",e))(Ih||{}),Th=(e=>(e[e.RESOURCE_PROVIDER=0]="RESOURCE_PROVIDER",e[e.TOOL_PROVIDER=1]="TOOL_PROVIDER",e[e.PROMPT_TEMPLATE_PROVIDER=2]="PROMPT_TEMPLATE_PROVIDER",e[e.LOCAL_FILE_ACCESS=3]="LOCAL_FILE_ACCESS",e[e.DATABASE_INTEGRATION=4]="DATABASE_INTEGRATION",e[e.API_INTEGRATION=5]="API_INTEGRATION",e[e.WEB_ACCESS=6]="WEB_ACCESS",e[e.KNOWLEDGE_BASE=7]="KNOWLEDGE_BASE",e[e.MEMORY_PERSISTENCE=8]="MEMORY_PERSISTENCE",e[e.CODE_ANALYSIS=9]="CODE_ANALYSIS",e[e.CONTENT_GENERATION=10]="CONTENT_GENERATION",e[e.COMMUNICATION=11]="COMMUNICATION",e[e.DOCUMENT_PROCESSING=12]="DOCUMENT_PROCESSING",e[e.CALENDAR_SCHEDULE=13]="CALENDAR_SCHEDULE",e[e.SEARCH=14]="SEARCH",e[e.ASSISTANT_ORCHESTRATION=15]="ASSISTANT_ORCHESTRATION",e))(Th||{}),Sh=(e=>(e.DNS="dns",e.SIGNATURE="signature",e.CHALLENGE="challenge",e))(Sh||{}),kh=(e=>(e.PUBLIC="PUBLIC",e.CONTROLLED="CONTROLLED",e.FEE_BASED="FEE_BASED",e))(kh||{});const vh=["twitter","github","discord","telegram","linkedin","youtube","website","x"],Eh={text_generation:0,image_generation:1,audio_generation:2,video_generation:3,code_generation:4,language_translation:5,summarization:6,extraction:6,knowledge_retrieval:7,data_integration:8,data_visualization:8,market_intelligence:9,transaction_analytics:10,smart_contract_audit:11,governance:12,security_monitoring:13,compliance_analysis:14,fraud_detection:15,multi_agent:16,api_integration:17,workflow_automation:18},Ah={resource_provider:0,tool_provider:1,prompt_template_provider:2,local_file_access:3,database_integration:4,api_integration:5,web_access:6,knowledge_base:7,memory_persistence:8,code_analysis:9,content_generation:10,communication:11,document_processing:12,calendar_schedule:13,search:14,assistant_orchestration:15},Ch=t.z.object({platform:t.z.string().min(1),handle:t.z.string().min(1)}),Rh=t.z.object({type:t.z.nativeEnum(bh),capabilities:t.z.array(t.z.nativeEnum(Ih)).min(1),model:t.z.string().min(1),creator:t.z.string().optional()}),xh=t.z.object({url:t.z.string().min(1),transport:t.z.enum(["stdio","sse"])}),Nh=t.z.object({type:t.z.nativeEnum(Sh),value:t.z.string(),dns_field:t.z.string().optional(),challenge_path:t.z.string().optional()}),zh=t.z.object({minVersion:t.z.string().optional()}),_h=t.z.object({name:t.z.string().min(1),description:t.z.string().min(1)}),Ph=t.z.object({name:t.z.string().min(1),description:t.z.string().min(1)}),Oh=t.z.object({version:t.z.string().min(1),connectionInfo:xh,services:t.z.array(t.z.nativeEnum(Th)).min(1),description:t.z.string().min(1),verification:Nh.optional(),host:zh.optional(),capabilities:t.z.array(t.z.string()).optional(),resources:t.z.array(_h).optional(),tools:t.z.array(Ph).optional(),maintainer:t.z.string().optional(),repository:t.z.string().optional(),docs:t.z.string().optional()}),Dh=t.z.object({version:t.z.string().min(1),type:t.z.nativeEnum(yh),display_name:t.z.string().min(1),alias:t.z.string().optional(),bio:t.z.string().optional(),socials:t.z.array(Ch).optional(),profileImage:t.z.string().optional(),uaid:t.z.string().optional(),properties:t.z.record(t.z.any()).optional(),inboundTopicId:t.z.string().optional(),outboundTopicId:t.z.string().optional(),base_account:t.z.string().optional()}),Fh=Dh.extend({type:t.z.literal(yh.PERSONAL),language:t.z.string().optional(),timezone:t.z.string().optional()}),Mh=Dh.extend({type:t.z.literal(yh.AI_AGENT),aiAgent:Rh}),Uh=Dh.extend({type:t.z.literal(yh.MCP_SERVER),mcpServer:Oh}),Bh=t.z.object({version:t.z.string(),type:t.z.literal(yh.FLORA),display_name:t.z.string().min(1),members:t.z.array(t.z.object({accountId:t.z.string(),publicKey:t.z.string().optional(),weight:t.z.number().optional()})),threshold:t.z.number().min(1),topics:t.z.object({communication:t.z.string(),transaction:t.z.string(),state:t.z.string()}),inboundTopicId:t.z.string(),outboundTopicId:t.z.string(),bio:t.z.string().optional(),metadata:t.z.record(t.z.any()).optional(),policies:t.z.record(t.z.any()).optional()}),Lh=t.z.union([Fh,Mh,Uh,Bh]),Kh={avif:"image/avif",gif:"image/gif",jpeg:"image/jpeg",jpg:"image/jpeg",json:"application/json",png:"image/png",svg:"image/svg+xml",txt:"text/plain",webp:"image/webp"};class $h{constructor(e){this.client=e.client??("mainnet"===e.network?r.Client.forMainnet():r.Client.forTestnet()),this.auth=e.auth,this.network=e.network,this.operatorId=e.auth.operatorId,this.logger=y.getInstance({level:e.logLevel||"info",module:"HCS-11",silent:e.silent}),this.mirrorNode=new x(this.network,this.logger),this.auth.privateKey?(this.operatorCtx=B({network:this.network,operatorId:this.operatorId,operatorKey:this.auth.privateKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:this.client}),this.client=this.operatorCtx.client,this.keyType=this.operatorCtx.keyType,this.operatorCtx.ensureInitialized(),this.client.setOperator(this.operatorId.toString(),this.operatorCtx.operatorKey)):this.keyType=e.keyType||"ed25519"}getClient(){return this.client}getOperatorId(){return this.auth.operatorId}async initializeOperator(){if(this.operatorCtx)try{await this.operatorCtx.ensureInitialized(),this.keyType=this.operatorCtx.keyType,this.client.setOperator(this.operatorId,this.operatorCtx.operatorKey)}catch(e){this.logger.warn(`Failed to verify operator key with mirror node: ${e.message}`)}}createPersonalProfile(e,t){return{version:"1.0",type:yh.PERSONAL,display_name:e,alias:t?.alias,bio:t?.bio,socials:t?.socials,profileImage:t?.profileImage,properties:t?.properties,inboundTopicId:t?.inboundTopicId,outboundTopicId:t?.outboundTopicId,base_account:t?.baseAccount}}createAIAgentProfile(e,t,r,i,n){const o=this.validateProfile({version:"1.0",type:yh.AI_AGENT,display_name:e,alias:n?.alias,bio:n?.bio,socials:n?.socials,profileImage:n?.profileImage,properties:n?.properties,inboundTopicId:n?.inboundTopicId,outboundTopicId:n?.outboundTopicId,base_account:n?.baseAccount,aiAgent:{type:t,capabilities:r,model:i,creator:n?.creator}});if(!o.valid)throw new Error(`Invalid AI Agent Profile: ${o.errors.join(", ")}`);return{version:"1.0",type:yh.AI_AGENT,display_name:e,alias:n?.alias,bio:n?.bio,socials:n?.socials,profileImage:n?.profileImage,properties:n?.properties,inboundTopicId:n?.inboundTopicId,outboundTopicId:n?.outboundTopicId,base_account:n?.baseAccount,aiAgent:{type:t,capabilities:r,model:i,creator:n?.creator}}}createMCPServerProfile(e,t,r){const i=this.validateProfile({version:"1.0",type:yh.MCP_SERVER,display_name:e,alias:r?.alias,bio:r?.bio,socials:r?.socials,profileImage:r?.profileImage,properties:r?.properties,inboundTopicId:r?.inboundTopicId,outboundTopicId:r?.outboundTopicId,mcpServer:t});if(!i.valid)throw new Error(`Invalid MCP Server Profile: ${i.errors.join(", ")}`);return{version:"1.0",type:yh.MCP_SERVER,display_name:e,alias:r?.alias,bio:r?.bio,socials:r?.socials,profileImage:r?.profileImage,properties:r?.properties,inboundTopicId:r?.inboundTopicId,outboundTopicId:r?.outboundTopicId,mcpServer:t}}validateProfile(e){const t=Lh.safeParse(e);if(t.success)return{valid:!0,errors:[]};return{valid:!1,errors:t.error.errors.map(e=>{const t=e.path.join(".");let r=e.message;if("invalid_type"===e.code)r=`Expected ${e.expected}, got ${e.received}`;else if("invalid_enum_value"===e.code){const t=e.options?.join(", ");r=`Invalid value. Valid options are: ${t}`}else"too_small"===e.code&&"string"===e.type&&(r="Cannot be empty");return`${t}: ${r}`})}}profileToJSONString(e){return JSON.stringify(e)}parseProfileFromString(e){try{const t=JSON.parse(e),r=this.validateProfile(t);return r.valid?t:(this.logger.error("Invalid profile format:",r.errors),null)}catch(t){return this.logger.error("Error parsing profile:"),null}}setProfileForAccountMemo(e,t=1){return`hcs-11:hcs://${t}/${e}`}async executeTransaction(e){try{if(this.auth.privateKey){const t=await e.signWithOperator(this.client),i=await t.execute(this.client),n=await i.getReceipt(this.client);return n.status.toString()!==r.Status.Success.toString()?{success:!1,error:`Transaction failed: ${n.status.toString()}`}:{success:!0,result:n}}if(!this.auth.signer)throw new Error("No valid authentication method provided");const t=this.auth.signer,i=await e.freezeWithSigner(t),n=await i.executeWithSigner(t),o=await n.getReceiptWithSigner(t);return o.status.toString()!==r.Status.Success.toString()?{success:!1,error:`Transaction failed: ${o.status.toString()}: ${r.Status.Success.toString()}`}:{success:!0,result:o}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error during transaction execution"}}}async inscribeImage(e,t,i){try{const n=i?.progressCallback,o=new ts({module:"HCS11-Image",logger:this.logger,callback:n});o.preparing("Preparing to inscribe image",0);const s=(e=>{const t=e.trim(),r=t.lastIndexOf(".");if(r<1||r===t.length-1)return"application/octet-stream";const i=t.substring(r+1).toLowerCase();return Kh[i]??"application/octet-stream"})(t),a=i?.waitForConfirmation??!0;let c;if(this.auth.signer){if(!("accountId"in this.auth.signer))throw o.failed("Signer must be a DAppSigner for inscription"),new Error("Signer must be a DAppSigner for inscription");o.preparing("Using signer for inscription",10),c=await Fa({type:"buffer",buffer:e,fileName:t,mimeType:s},this.auth.signer,{network:this.network,waitForConfirmation:a,waitMaxAttempts:150,waitIntervalMs:4e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);o.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}else{if(!this.auth.privateKey)throw o.failed("Private key is required for inscription"),this.logger.error("Private key is required for inscription"),new Error("Private key is required for inscription");o.preparing("Using private key for inscription",10);const i="ecdsa"===this.keyType?r.PrivateKey.fromStringECDSA(this.auth.privateKey):r.PrivateKey.fromStringED25519(this.auth.privateKey);c=await Oa({type:"buffer",buffer:e,fileName:t,mimeType:s},{accountId:this.auth.operatorId,privateKey:i,network:this.network},{waitForConfirmation:a,waitMaxAttempts:150,waitIntervalMs:2e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);o.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}if(c.confirmed)return o.completed("Image inscription completed",{topicId:Ha(c.inscription)}),{imageTopicId:Ha(c.inscription)||"",transactionId:c.result.jobId,success:!0};{const e=c.quote?"quote-only":c.result.jobId;return o.verifying("Waiting for inscription confirmation",50,{jobId:e}),{imageTopicId:"",transactionId:e,success:!1,error:"Inscription not confirmed"}}}catch(n){return this.logger.error("Error inscribing image:",n),{imageTopicId:"",transactionId:"",success:!1,error:n instanceof Error?n.message:"Error inscribing image"}}}async inscribeProfile(e,t){this.logger.info("Inscribing HCS-11 profile");const i=t?.progressCallback,n=new ts({module:"HCS11-Profile",logger:this.logger,callback:i});await this.attachUaidIfMissing(e),n.preparing("Validating profile data",5);const o=this.validateProfile(e);if(!o.valid)return n.failed(`Invalid profile: ${o.errors.join(", ")}`),{profileTopicId:"",transactionId:"",success:!1,error:`Invalid profile: ${o.errors.join(", ")}`};n.preparing("Formatting profile for inscription",15);const s=this.profileToJSONString(e),a=`profile-${e.display_name.toLowerCase().replace(/\s+/g,"-")}.json`;try{const e=globalThis.Buffer.from(s,"utf-8"),t="application/json";n.preparing("Preparing profile for inscription",20);const i={type:"buffer",buffer:e,fileName:a,mimeType:t},o={waitForConfirmation:!0,mode:"file",network:this.network,waitMaxAttempts:100,waitIntervalMs:2e3,progressCallback:e=>{const t=20+.75*Number(e?.progressPercent||0);n?.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}};let c;if(n.submitting("Submitting profile to Hedera network",30),this.auth.privateKey){const e="ecdsa"===this.keyType?r.PrivateKey.fromStringECDSA(this.auth.privateKey):r.PrivateKey.fromStringED25519(this.auth.privateKey);c=await Oa(i,{accountId:this.auth.operatorId,privateKey:e,network:this.network},o)}else{if(!this.auth.signer)throw new Error("No authentication method available - neither private key nor signer");c=await Fa(i,this.auth.signer,o)}if(!c.confirmed||!Ha(c.inscription))return n.failed("Failed to inscribe profile content"),{profileTopicId:"",transactionId:"",success:!1,error:"Failed to inscribe profile content"};const l=Ha(c.inscription);return n.completed("Profile inscription completed",{topicId:l,transactionId:c.result.transactionId}),{profileTopicId:l,transactionId:c.result.transactionId,success:!0,totalCostHbar:c.costSummary?.totalCostHbar}}catch(c){return n.failed(`Error inscribing profile: ${c.message||"Unknown error"}`),{profileTopicId:"",transactionId:"",success:!1,error:c.message||"Unknown error during inscription"}}}async attachUaidIfMissing(e){if(!e.uaid&&lh(this.network))try{const{HCS14Client:t}=await Promise.resolve().then(()=>pf),r=new t({client:this.client}),i=await r.createDid({method:"hedera",client:this.client}),n=ph(this.network,this.auth.operatorId);let o=this.auth.operatorId;const s=e.inboundTopicId;if(s&&s.trim().length>0)o=`${s}@${this.auth.operatorId}`;else try{const e=await this.fetchProfileByAccountId(this.auth.operatorId,this.network),t=e?.topicInfo?.inboundTopic;t&&t.trim().length>0&&(o=`${t}@${this.auth.operatorId}`)}catch{}const a=r.createUaid(i,{proto:"hcs-10",nativeId:n,uid:o});e.uaid=a}catch(Pw){this.logger.warn("Hiero registrar not available; skipping UAID generation for profile",Pw)}}async updateAccountMemoWithProfile(e,t,i){try{this.logger.info(`Updating account memo for ${e} with profile ${t}`);const n=this.setProfileForAccountMemo(t),o=(new r.AccountUpdateTransaction).setAccountMemo(n).setAccountId(e);if(i&&i.length>0){let e=await o.freezeWith(this.client);for(const r of i)e=await e.sign(r);const t=await e.execute(this.client),n=await t.getReceipt(this.client);return n.status.toString()!==r.Status.Success.toString()?{success:!1,error:`Transaction failed: ${n.status.toString()}`}:{success:!0,result:n}}return this.executeTransaction(o)}catch(n){return this.logger.error(`Error updating account memo: ${n instanceof Error?n.message:"Unknown error"}`),{success:!1,error:n instanceof Error?n.message:"Unknown error updating account memo"}}}async createAndInscribeProfile(e,t=!0,r){const i=r?.progressCallback,n=new ts({module:"HCS11-ProfileCreation",logger:this.logger,callback:i});n.preparing("Starting profile creation process",0);const o=n.createSubProgress({minPercent:0,maxPercent:80,logPrefix:"Inscription"}),s=await this.inscribeProfile(e,{...r,progressCallback:e=>{o.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent,details:e.details})}});if(!s?.success)return n.failed("Profile inscription failed",{error:s?.error}),s;if(n.confirming("Profile inscribed, updating account memo",85),t){const e=await this.updateAccountMemoWithProfile(this.auth.operatorId,s.profileTopicId);if(!e.success)return n.failed("Failed to update account memo",{error:e?.error}),{...s,success:!1,error:e?.error}}return n.completed("Profile creation completed successfully",{profileTopicId:s.profileTopicId,transactionId:s.transactionId,totalCostHbar:s.totalCostHbar}),s}async getCapabilitiesFromTags(e){const t=[];if(0===e.length)return[Ih.TEXT_GENERATION];for(const r of e){const e=Eh[r.toLowerCase()];void 0===e||t.includes(e)||t.push(e)}return 0===t.length&&t.push(Ih.TEXT_GENERATION),t}getAgentTypeFromMetadata(e){return"autonomous"===e.type?bh.AUTONOMOUS:bh.MANUAL}async fetchProfileByAccountId(e,t){try{this.logger.debug(`Fetching profile for account ${e.toString()} on ${this.network}`);const i=await this.mirrorNode.getAccountMemo(e.toString());if(this.logger.debug(`Got account memo: ${i}`),!i?.startsWith("hcs-11:"))return{success:!1,error:`Account ${e.toString()} does not have a valid HCS-11 memo. Current memo: ${i||"empty"}`};this.logger.debug(`Found HCS-11 memo: ${i}`);const n=i.substring(7);if(!n?.startsWith("hcs://")){if(n.startsWith("ipfs://")){this.logger.warn("IPFS protocol references are not fully supported");const e=await fetch(`https://ipfs.io/ipfs/${n.replace("ipfs://","")}`),t=await e.json(),r=Lh.safeParse(t);return r.success?{success:!0,profile:r.data,topicInfo:{inboundTopic:r.data.inboundTopicId||"",outboundTopic:r.data.outboundTopicId||"",profileTopicId:""}}:{success:!1,error:`Invalid HCS-11 profile data from IPFS reference ${n}`}}if(n.startsWith("ar://")){const e=n.replace("ar://",""),t=await fetch(`https://arweave.net/${e}`);if(!t.ok)return{success:!1,error:`Failed to fetch profile from Arweave ${e}: ${t.statusText}`};const r=await t.json(),i=Lh.safeParse(r);return i.success?{success:!0,profile:i.data,topicInfo:{inboundTopic:i.data.inboundTopicId||"",outboundTopic:i.data.outboundTopicId||"",profileTopicId:""}}:{success:!1,error:`Invalid HCS-11 profile data from Arweave reference ${e}`}}return{success:!1,error:`Invalid protocol reference format: ${n}`}}{const e=n.match(/hcs:\/\/(\d+)\/(.+)/);if(!e)return{success:!1,error:`Invalid HCS protocol reference format: ${n}`};const[i,o,s]=e,a=t||this.network||"mainnet";this.logger.debug(`Retrieving profile from Kiloscribe CDN: ${s}`);const c=`https://kiloscribe.com/api/inscription-cdn/${s}?network=${a}`;try{const e=await fetch(c);if(!e.ok)return{success:!1,error:`Failed to fetch profile from Kiloscribe CDN: ${e.statusText}`};const t=await e.json();if(!t)return{success:!1,error:`No profile data found for topic ${s}`};const r=Lh.safeParse(t);return r.success?{success:!0,profile:r.data,topicInfo:{inboundTopic:r.data.inboundTopicId||"",outboundTopic:r.data.outboundTopicId||"",profileTopicId:s}}:{success:!1,error:`Invalid HCS-11 profile data for topic ${s}`}}catch(r){return this.logger.error(`Error retrieving from Kiloscribe CDN: ${r.message}`),{success:!1,error:`Error retrieving from Kiloscribe CDN: ${r.message}`}}}}catch(i){return this.logger.error(`Error fetching profile: ${i.message}`),{success:!1,error:`Error fetching profile: ${i.message}`}}}}class Hh{async checkRegistrationStatus(e,t,r,i){try{const n=await fetch(`${r}/api/request-confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Network":t},body:JSON.stringify({transaction_id:e})});if(!n.ok){const e=`Failed to confirm registration: ${n.statusText}`;throw i&&i.error(e),new Error(e)}return await n.json()}catch(n){throw i&&i.error(`Error checking registration status: ${n.message}`),n}}async waitForRegistrationConfirmation(e,t,r,i=60,n=2e3,o){let s=0;for(;s<i;){o&&o.info(`Checking registration status. Attempt ${s+1}/${i}`);const a=await this.checkRegistrationStatus(e,t,r,o);if("success"===a.status)return o&&o.info("Registration confirmed successfully"),!0;if("failed"===a.status)throw o&&o.error("Registration confirmation failed"),new Error("Registration confirmation failed");o&&o.info(`Registration still pending. Waiting ${n}ms before next attempt`),await new Promise(e=>setTimeout(e,n)),s++}return o&&o.warn(`Registration not confirmed after ${i} attempts`),!1}async executeRegistration(e,t="mainnet",r="https://moonscape.tech",i){try{i&&i.info("Registering agent with guarded registry");try{const r=new $h({network:t,auth:{operatorId:"0.0.0"}});i?.info(`Fetching profile by account ID ${e} on ${t}`),await b(5e3);const n=await r.fetchProfileByAccountId(e,t);if(i?.info("Profile fetched",n),n?.error)return i?.error("Error fetching profile",n.error),{error:n.error,success:!1};if(!n?.success||!n?.profile)return i&&i.error("Profile not found for agent registration"),{error:"Profile not found for the provided account ID",success:!1};if(!n.profile.inboundTopicId)return i&&i.error("Missing inbound topic ID in profile"),{error:"Profile is missing required inbound topic ID",success:!1};if(!n.profile.outboundTopicId)return i&&i.error("Missing outbound topic ID in profile"),{error:"Profile is missing required outbound topic ID",success:!1};i&&i.info(`Profile validation successful. Inbound topic: ${n.profile.inboundTopicId}, Outbound topic: ${n.profile.outboundTopicId}`)}catch(n){return i&&i.error(`Error validating profile: ${n.message}`),{error:`Error validating profile: ${n.message}`,success:!1}}const o=await fetch(`${r}/api/request-register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"*/*","Accept-Language":"en;q=0.5",Origin:r,Referer:`${r}/`,"X-Network":t},body:JSON.stringify({accountId:e})}),s=await o.json();return o.ok?(i&&i.info(`Created new registration request. Transaction ID: ${s.transaction_id}`),{transactionId:s.transaction_id,transaction:s.transaction,success:!0}):s.details?.length>0?{validationErrors:s.details,error:s.error||"Validation failed",success:!1}:{error:s.error||"Failed to register agent",success:!1}}catch(o){return{error:`Error during registration request: ${o.message}`,success:!1}}}async findRegistrations(e={},t="https://moonscape.tech"){try{const r=new URLSearchParams;e.tags?.forEach(e=>r.append("tags",e.toString())),e.accountId&&r.append("accountId",e.accountId),e.network&&r.append("network",e.network);const i=await fetch(`${t}/api/registrations?${r}`,{headers:{Accept:"*/*","Accept-Language":"en;q=0.5",Origin:t,Referer:`${t}/`}});if(!i.ok){return{registrations:[],error:await i.text()||"Failed to fetch registrations",success:!1}}const n=await i.json();return n.error?{registrations:[],error:n.error,success:!1}:{registrations:n.registrations||[],success:!0}}catch(Pw){return{registrations:[],error:`Error fetching registrations: ${Pw.message}`,success:!1}}}}function qh(e,t){return`hcs-10:op:${e}:${t}`}function jh(e){var t,r;return z({memo:e.memoOverride??(t=e.ttl,r=e.accountId,`hcs-10:0:${t}:0:${r}`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Wh(e){return z({memo:e.memoOverride??`hcs-10:0:${e.ttl}:1`,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Vh(e){var t,r,i;return z({memo:e.memoOverride??(t=e.ttl,r=e.inboundTopicId,i=e.connectionId,`hcs-10:1:${t}:2:${r}:${i}`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Gh(e){var t,r;return z({memo:e.memoOverride??(t=e.ttl,(r=e.metadataTopicId)?`hcs-10:0:${t}:3:${r}`:`hcs-10:0:${t}:3`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Jh(e){const t={p:"hcs-10",op:"connection_request",operator_id:e.operatorId,m:e.memo};return _({topicId:e.inboundTopicId,message:JSON.stringify(t),transactionMemo:qh(3,1)})}function Yh(e){const t={p:"hcs-10",op:"connection_created",connection_topic_id:e.connectionTopicId,connected_account_id:e.connectedAccountId,operator_id:e.operatorId,connection_id:e.connectionId,m:e.memo};return _({topicId:e.inboundTopicId,message:JSON.stringify(t),transactionMemo:qh(4,1)})}function Xh(e){const t={p:"hcs-10",op:"connection_request",operator_id:e.operatorId,outbound_topic_id:e.outboundTopicId,connection_request_id:e.connectionRequestId,m:e.memo};return _({topicId:e.outboundTopicId,message:JSON.stringify(t),transactionMemo:qh(3,2)})}function Zh(e){const t={p:"hcs-10",op:"connection_created",connection_topic_id:e.connectionTopicId,outbound_topic_id:e.outboundTopicId,requestor_outbound_topic_id:e.requestorOutboundTopicId,confirmed_request_id:e.confirmedRequestId,connection_request_id:e.connectionRequestId,operator_id:e.operatorId,m:e.memo};return _({topicId:e.outboundTopicId,message:JSON.stringify(t),transactionMemo:qh(4,2)})}function Qh(e){const t={p:"hcs-10",op:"message",operator_id:e.operatorId,data:e.data,m:e.memo};return _({topicId:e.connectionTopicId,message:JSON.stringify(t),transactionMemo:qh(6,3)})}function eg(e){const t={p:"hcs-10",op:"register",account_id:e.accountId,...e.inboundTopicId?{inbound_topic_id:e.inboundTopicId}:{},m:e.memo};return _({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:qh(0,0)})}function tg(e){const t={p:"hcs-10",op:"delete",uid:e.uid,m:e.memo};return _({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:qh(1,0)})}function rg(e){const t={p:"hcs-10",op:"migrate",t_id:e.targetTopicId,m:e.memo};return _({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:qh(2,0)})}var ig=(e=>(e.INBOUND="inbound",e.OUTBOUND="outbound",e.CONNECTION="connection",e.REGISTRY="registry",e))(ig||{});class ng extends Hh{constructor(e){super(),this.network=e.network,this.logger=y.getInstance({level:e.logLevel||"info",module:"HCS10-BaseClient",prettyPrint:e.prettyPrint,silent:e.silent}),this.mirrorNode=new x(e.network,this.logger,e.mirrorNode),this.feeAmount=e.feeAmount||.001}configureMirrorNode(e){this.mirrorNode.configureMirrorNode(e),this.logger.info("Mirror node configuration updated")}extractTopicFromOperatorId(e){if(!e)return"";const t=e.split("@");return t.length>0?t[0]:""}extractAccountFromOperatorId(e){if(!e)return"";const t=e.split("@");return t.length>1?t[1]:""}async getMessageStream(e,t){try{const r=await this.mirrorNode.getTopicMessages(e,t),i=["message","close_connection","transaction"];return{messages:r.filter(e=>{if("hcs-10"!==e.p||!i.includes(e.op))return!1;if("message"===e.op||"close_connection"===e.op){if(!e.operator_id)return!1;if(!this.isValidOperatorId(e.operator_id))return!1;if("message"===e.op&&!e.data)return!1}if("transaction"===e.op){if(!e.operator_id||!e.schedule_id)return!1;if(!this.isValidOperatorId(e.operator_id))return!1}return!0})}}catch(r){return this.logger&&this.logger.error(`Error fetching messages: ${r.message}`),{messages:[]}}}async getPublicTopicInfo(e){try{return await this.mirrorNode.getTopicInfo(e)}catch(t){return this.logger.error(`Error getting public topic info for ${e}:`,t),null}}async canSubmitToTopic(e,t){try{const n=await this.mirrorNode.getTopicInfo(e);if(!n)return{canSubmit:!1,requiresFee:!1,reason:"Topic does not exist"};if(!n.submit_key?.key)return{canSubmit:!0,requiresFee:!1};try{const e=await this.mirrorNode.getPublicKey(t);if("ProtobufEncoded"===n.submit_key._type){const t=globalThis.Buffer.from(n.submit_key.key,"hex");if(await this.mirrorNode.checkKeyListAccess(t,e))return{canSubmit:!0,requiresFee:!1}}else{const t=r.PublicKey.fromString(n.submit_key.key);if(e.toString()===t.toString())return{canSubmit:!0,requiresFee:!1}}}catch(i){this.logger.error(`Key validation error: ${i instanceof Error?i.message:String(i)}`)}return n.fee_schedule_key?.key&&n.custom_fees?.fixed_fees?.length>0?{canSubmit:!0,requiresFee:!0,reason:"Requires fee payment via HIP-991"}:{canSubmit:!1,requiresFee:!1,reason:"User does not have submit permission for this topic"}}catch(i){const e=i instanceof Error?i.message:String(i);return this.logger.error(`Topic submission validation error: ${e}`),{canSubmit:!1,requiresFee:!1,reason:`Error: ${e}`}}}async getMessages(e,t){try{const r=await this.mirrorNode.getTopicMessages(e,t);return{messages:r.filter(e=>{if("hcs-10"!==e.p)return!1;if("message"===e.op){if(!e.data)return!1;if(e.operator_id&&!this.isValidOperatorId(e.operator_id))return!1}return!0})}}catch(r){return this.logger&&this.logger.error(`Error fetching messages: ${r.message}`),{messages:[]}}}async requestAccount(e){try{if(!e)throw new Error("Account ID is required");return await this.mirrorNode.requestAccount(e)}catch(Pw){throw this.logger.error("Failed to fetch account",Pw),Pw}}async getAccountMemo(e){return await this.mirrorNode.getAccountMemo(e)}async retrieveProfile(e,t,r){const i=r?.maxRetries??0,n=r?.retryDelay??3e3;let o=0;for(;o<=i;){this.logger.debug(`Retrieving profile for account: ${e}${o>0?` (attempt ${o+1}/${i+1})`:""}`);const r=`${e}-${this.network}`;if(!t&&0===o){const t=og.getInstance().get(r);if(t)return this.logger.debug(`Cache hit for profile: ${e}`),t}try{const t=new $h({network:this.network,auth:{operatorId:"0.0.0"},logLevel:this.logger.getLevel()}),s=await t.fetchProfileByAccountId(e,this.network);if(!s?.success){if(o<i){this.logger.info(`Profile not found for account ${e}, retrying in ${n}ms... (${s?.error})`),o++,await new Promise(e=>setTimeout(e,n));continue}return this.logger.error(`Failed to retrieve profile for account ID: ${e}`,s?.error),{profile:null,success:!1,error:s?.error||`Failed to retrieve profile for account ID: ${e}`}}const a=s?.profile;let c=null;const l=s?.topicInfo?.inboundTopic||a?.inboundTopicId||"",u=s?.topicInfo?.outboundTopic||a?.outboundTopicId||"";l&&u&&(c={inboundTopic:l,outboundTopic:u,profileTopicId:s?.topicInfo?.profileTopicId||""});const d={profile:a,topicInfo:c,success:!0};return og.getInstance().set(r,d),d}catch(Pw){if(o<i){this.logger.info(`Error retrieving profile for account ${e}, retrying in ${n}ms... (${Pw.message})`),o++,await new Promise(e=>setTimeout(e,n));continue}const r=`Failed to retrieve profile: ${Pw.message}`;return this.logger.error(r),{profile:null,success:!1,error:r}}}return{profile:null,success:!1,error:"Unexpected error in profile retrieval"}}async retrieveOutboundConnectTopic(e){return await this.retrieveCommunicationTopics(e,!0)}async retrieveCommunicationTopics(e,t,r){try{const i=await this.retrieveProfile(e,t,r);if(!i?.success)throw new Error(i.error||"Failed to retrieve profile");const n=i.profile;if(!n)throw new Error(`Profile is null or undefined for account ${e}`);if(!n.inboundTopicId||!n.outboundTopicId)throw new Error("Invalid HCS-11 profile for HCS-10 agent: missing inboundTopicId or outboundTopicId");if(!i.topicInfo)throw new Error(`TopicInfo is missing in the profile for account ${e}`);return i.topicInfo}catch(Pw){const t=Pw,r=`Failed to retrieve topic info: ${t.message}`;throw this.logger.error(r),t}}async retrieveOutboundMessages(e,t){try{const r=await this.retrieveCommunicationTopics(e);if(!r)return this.logger.warn(`No outbound connect topic found for agentAccountId: ${e}`),[];return(await this.getMessages(r.outboundTopic,t)).messages.filter(e=>"hcs-10"===e.p&&("connection_request"===e.op||"connection_created"===e.op||"message"===e.op))}catch(Pw){const t=`Failed to retrieve outbound messages: ${Pw.message}`;return this.logger.error(t),[]}}async hasConnectionCreated(e,t){try{const r=await this.retrieveCommunicationTopics(e);return(await this.retrieveOutboundMessages(r.outboundTopic)).some(e=>"connection_created"===e.op&&e.connection_id===t)}catch(Pw){const t=`Failed to check connection created: ${Pw.message}`;return this.logger.error(t),!1}}async getMessageContent(e,t=!1){if(!e.match(/^hcs:\/\/(\d+)\/([0-9]+\.[0-9]+\.[0-9]+)$/))return e;try{const r=new Gp(this.logger.getLevel());if(!r.isValidHRL(e))return e;return(await r.resolveHRL(e,{network:this.network,returnRaw:t})).content}catch(Pw){const t=`Error resolving HRL reference: ${Pw.message}`;throw this.logger.error(t),new Error(t)}}async getMessageContentWithType(e,t=!1){if(!e.match(/^hcs:\/\/(\d+)\/([0-9]+\.[0-9]+\.[0-9]+)$/))return{content:e,contentType:"text/plain",isBinary:!1};try{const r=new Gp(this.logger.getLevel());return await r.getContentWithType(e,{network:this.network,returnRaw:t})}catch(Pw){const t=`Error resolving HRL reference with type: ${Pw.message}`;throw this.logger.error(t),new Error(t)}}async submitConnectionRequest(e,t){const r=this.getAccountAndSigner();if(!r?.accountId)throw new Error("Operator account ID is not set");const i=await this.getOperatorId(),n=r.accountId,o=await this.canSubmitToTopic(e,n);if(!o?.canSubmit)throw new Error(`Cannot submit to topic: ${o.reason}`);const s=await this.retrieveInboundAccountId(e);if(!s)throw new Error("Failed to retrieve topic info account ID");const a=o.requiresFee,c=Jh({inboundTopicId:e,operatorId:i,memo:t}),l=await this.submitPayload(c,void 0,void 0,a);this.logger.info(`Submitted connection request to topic ID: ${e}`);const u=await this.retrieveCommunicationTopics(n);if(!u)throw new Error("Failed to retrieve outbound topic");const d=l.topicSequenceNumber?.toNumber();if(!d)throw new Error("Failed to get response sequence number");const p=`${e}@${s}`,h=Xh({outboundTopicId:u.outboundTopic,operatorId:p,connectionRequestId:d,memo:t});return await this.submitPayload(h),l}async recordOutboundConnectionConfirmation({outboundTopicId:e,requestorOutboundTopicId:t,connectionRequestId:r,confirmedRequestId:i,connectionTopicId:n,operatorId:o,memo:s}){const a=Zh({outboundTopicId:e,requestorOutboundTopicId:t,connectionTopicId:n,confirmedRequestId:i,connectionRequestId:r,operatorId:o,memo:s});return await this.submitPayload(a)}async waitForConnectionConfirmation(e,t,r=60,i=2e3,n=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let o=0;o<r;o++){this.logger.info(`Attempt ${o+1}/${r} to find connection confirmation`);const s=(await this.mirrorNode.getTopicMessages(e,{order:"desc",limit:100})).filter(e=>"connection_created"===e.op);if(this.logger.info(`Found ${s.length} connection_created messages`),s.length>0)for(const e of s)if(Number(e.connection_id)===Number(t)){const r={connectionTopicId:e.connection_topic_id,sequence_number:Number(e.sequence_number),confirmedBy:e.operator_id,memo:e.m},i=this.extractAccountFromOperatorId(r.confirmedBy),o=this.getAccountAndSigner(),s=await this.retrieveCommunicationTopics(i),a=await this.retrieveCommunicationTopics(o.accountId);return this.logger.info("Connection confirmation found",r),n&&await this.recordOutboundConnectionConfirmation({requestorOutboundTopicId:s.outboundTopic,outboundTopicId:a.outboundTopic,connectionRequestId:t,confirmedRequestId:r.sequence_number,connectionTopicId:r.connectionTopicId,operatorId:r.confirmedBy,memo:r.memo||"Connection confirmed"}),r}o<r-1&&(this.logger.info(`No matching confirmation found, waiting ${i}ms before retrying...`),await new Promise(e=>setTimeout(e,i)))}throw new Error(`Connection confirmation not found after ${r} attempts for request ID ${t}`)}async getOperatorId(e){if(this.operatorId&&!e)return this.operatorId;const t=this.getAccountAndSigner();if(!t?.accountId)throw new Error("Operator ID not found");const r=await this.retrieveProfile(t.accountId);if(!r?.success)throw new Error("Failed to retrieve profile");if(!r?.topicInfo?.inboundTopic)throw new Error("Failed to retrieve inbound topic");const i=`${r.topicInfo?.inboundTopic}@${t.accountId}`;return this.operatorId=i,i}async retrieveInboundAccountId(e){const t=await this.mirrorNode.getTopicInfo(e);if(!t?.memo)throw new Error("Failed to retrieve topic info");const r=t.memo.toString().split(":"),i=r?.[4];if(!i)throw new Error("Failed to retrieve topic info account ID");return i}clearCache(){og.getInstance().clear()}_generateHcs10Memo(e,t){const r=t.ttl??60;switch(e){case"inbound":if(!t.accountId)throw new Error("accountId is required for inbound memo");return`hcs-10:0:${r}:0:${t.accountId}`;case"outbound":return`hcs-10:0:${r}:1`;case"connection":if(!t.inboundTopicId||void 0===t.connectionId)throw new Error("inboundTopicId and connectionId are required for connection memo");return`hcs-10:1:${r}:2:${t.inboundTopicId}:${t.connectionId}`;default:throw new Error(`Invalid HCS-10 memo type: ${e}`)}}async getTopicMemoType(e){try{const t=await this.mirrorNode.getTopicInfo(e);if(!t?.memo)return this.logger.debug(`No memo found for topic ${e}`),null;const r=t.memo.toString();if(!r.startsWith("hcs-10:"))return this.logger.debug(`Topic ${e} is not an HCS-10 topic`),null;const i=r.split(":");if(i.length<4)return this.logger.warn(`Invalid HCS-10 memo format for topic ${e}: ${r}`),null;const n=i[3];switch(n){case"0":return"inbound";case"1":return"outbound";case"2":return"connection";case"3":return"registry";default:return this.logger.warn(`Unknown HCS-10 type enum: ${n} for topic ${e}`),null}}catch(t){return this.logger.error(`Error getting topic memo type for ${e}:`,t),null}}async checkRegistrationStatus(e,t,r){try{const i=await fetch(`${r}/api/request-confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Network":t},body:JSON.stringify({transaction_id:e})});if(!i.ok)throw new Error(`Failed to confirm registration: ${i.statusText}`);return await i.json()}catch(Pw){const t=Pw,r=`Error checking registration status: ${t.message}`;throw this.logger.error(r),t}}isValidOperatorId(e){if(!e)return!1;const t=e.split("@");if(2!==t.length)return!1;const r=t[0],i=t[1];if(!r)return!1;if(!i)return!1;const n=/^[0-9]+\.[0-9]+\.[0-9]+$/;return!!n.test(i)&&!!n.test(r)}async getTransactionRequests(e,t){this.logger.debug(`Retrieving transaction requests from topic ${e}`);const{messages:r}=await this.getMessageStream(e,{limit:t?.limit,sequenceNumber:t?.sequenceNumber,order:t?.order||"desc"}),i=r.filter(e=>"transaction"===e.op&&e.schedule_id).map(e=>({operator_id:e.operator_id||"",schedule_id:e.schedule_id||"",data:e.data||"",memo:e.m,sequence_number:Number(e.sequence_number)})).sort((e,t)=>e.sequence_number&&t.sequence_number?t.sequence_number-e.sequence_number:0);return t?.limit?i.slice(0,t.limit):i}getHcs10TransactionMemo(e){if("object"!=typeof e||!("op"in e))return null;const t=e;let r,i;switch(t.op){case"register":r="0",i="0";break;case"delete":r="1",i="0";break;case"migrate":r="2",i="0";break;case"connection_request":r="3",i=t.outbound_topic_id?"2":"1";break;case"connection_created":r="4",i=t.outbound_topic_id?"2":"1";break;case"connection_closed":r="5",i=t.outbound_topic_id?"2":"3";break;case"message":case"transaction":default:r="6",i="3";break;case"close_connection":r="5",i="3"}return`hcs-10:op:${r}:${i}`}}class og{constructor(){this.CACHE_TTL=36e5,this.cache=new Map,this.cacheExpiry=new Map}static getInstance(){return og.instance||(og.instance=new og),og.instance}set(e,t){this.cache.set(e,t),this.cacheExpiry.set(e,Date.now()+this.CACHE_TTL)}get(e){const t=this.cacheExpiry.get(e);if(t&&t>Date.now())return this.cache.get(e);t&&(this.cache.delete(e),this.cacheExpiry.delete(e))}clear(){this.cache.clear(),this.cacheExpiry.clear()}}class sg extends Error{constructor(e,t){super(e),this.payloadSize=t,this.name="PayloadSizeError"}}class ag extends Error{constructor(e){super(e),this.name="AccountCreationError"}}class cg extends Error{constructor(e){super(e),this.name="TopicCreationError"}}class lg extends Error{constructor(e){super(e),this.name="ConnectionConfirmationError"}}class ug{constructor(){this.config={},this.logger=y.getInstance({module:"AgentBuilder"})}setName(e){return this.config.name=e,this}setAlias(e){return this.config.alias=e,this}setBio(e){return this.config.bio=e,this}setDescription(e){return this.config.bio=e,this}setCapabilities(e){return this.config.capabilities=e,this}setAgentType(e){return this.config.metadata?this.config.metadata.type=e:this.config.metadata={type:e},this}setType(e){return this.config.metadata?this.config.metadata.type=e:this.config.metadata={type:e},this}setModel(e){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.model=e,this}setCreator(e){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.creator=e,this}addSocial(e,t){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.socials||(this.config.metadata.socials={}),this.config.metadata.socials[e]=t,this}addProperty(e,t){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.properties||(this.config.metadata.properties={}),this.config.metadata.properties[e]=t,this}setMetadata(e){return this.config.metadata=e,this}setProfilePicture(e,t){return this.config.pfpBuffer=e,this.config.pfpFileName=t,this}setExistingProfilePicture(e){return this.config.existingPfpTopicId=e,this}setNetwork(e){return this.config.network=e,this}setInboundTopicType(e){return this.config.inboundTopicType=e,this}setFeeConfig(e){return this.config.feeConfig=e,this}setConnectionFeeConfig(e){return this.config.connectionFeeConfig=e,this}setExistingAccount(e,t){return this.config.existingAccount={accountId:e,privateKey:t},this}setInboundTopicId(e){return this.config.inboundTopicId=e,this}setOutboundTopicId(e){return this.config.outboundTopicId=e,this}setBaseAccount(e){return this.baseAccount=e,this}build(){if(!this.config.name)throw new Error("Agent display name is required");if(this.config.bio||this.logger?.warn("Agent description is not set"),this.config.pfpBuffer||this.config.existingPfpTopicId||this.logger.warn("No profile picture provided or referenced."),!this.config.network)throw new Error("Network is required");if(this.config.inboundTopicType||(this.config.inboundTopicType=kh.PUBLIC),this.config.capabilities||(this.config.capabilities=[]),this.config.metadata?this.config.metadata.type||(this.config.metadata.type="manual"):this.config.metadata={type:"manual"},this.config.inboundTopicType===kh.FEE_BASED&&!this.config.feeConfig)throw new Error("Fee configuration is required for fee-based topics");const e=this.config;return this.baseAccount&&(e.baseAccount=this.baseAccount),e}}class dg{constructor(){this.config={version:"1.0",type:0},this.logger=y.getInstance({module:"PersonBuilder"})}setName(e){return this.config.display_name=e,this}setAlias(e){return this.config.alias=e,this}setBio(e){return this.config.bio=e,this}setDescription(e){return this.setBio(e)}addSocial(e,t){this.config.socials||(this.config.socials=[]);const r=this.config.socials.find(t=>t.platform===e);return r?r.handle=t:this.config.socials.push({platform:e,handle:t}),this}setProfileImage(e){return this.config.profileImage=e,this}setProfilePicture(e,t){return this.config.pfpBuffer=e,this.config.pfpFileName=t,this}setBaseAccount(e){return this.config.base_account=e,this}setExistingProfilePicture(e){return this.config.profileImage=`hcs://1/${e}`,this}addProperty(e,t){return this.config.properties||(this.config.properties={}),this.config.properties[e]=t,this}setInboundTopicId(e){return this.config.inboundTopicId=e,this}setOutboundTopicId(e){return this.config.outboundTopicId=e,this}getProfilePicture(){return{pfpBuffer:this.config.pfpBuffer,pfpFileName:this.config.pfpFileName}}build(){if(!this.config.display_name)throw new Error("Display name is required for the profile");return this.config.bio||this.logger.warn("No bio provided for person profile"),this.config.pfpBuffer||this.config.profileImage||this.logger.warn("No profile picture provided or referenced"),{version:this.config.version,type:0,display_name:this.config.display_name,alias:this.config.alias,bio:this.config.bio,socials:this.config.socials,profileImage:this.config.profileImage,base_account:this.config.base_account,properties:this.config.properties,inboundTopicId:this.config.inboundTopicId,outboundTopicId:this.config.outboundTopicId,pfpBuffer:this.config.pfpBuffer,pfpFileName:this.config.pfpFileName}}}class pg{constructor(){this.config={mcpServer:{}},this.socials=[],this.logger=y.getInstance({module:"MCPServerBuilder"})}setName(e){return this.config.name=e,this}setAlias(e){return this.config.alias=e,this}setBio(e){return this.config.bio=e,this}setDescription(e){return this.setBio(e)}setVersion(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.version=e,this}setConnectionInfo(e,t){this.config.mcpServer||(this.config.mcpServer={});const r={url:e,transport:t};return this.config.mcpServer.connectionInfo=r,this}setServerDescription(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.description=e,this}setServices(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.services=e,this}setHostRequirements(e){this.config.mcpServer||(this.config.mcpServer={});const t={minVersion:e};return this.config.mcpServer.host=t,this}setCapabilities(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.capabilities=e,this}addResource(e,t){this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.resources||(this.config.mcpServer.resources=[]);const r={name:e,description:t};return this.config.mcpServer.resources.push(r),this}setResources(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.resources=e,this}addTool(e,t){this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.tools||(this.config.mcpServer.tools=[]);const r={name:e,description:t};return this.config.mcpServer.tools.push(r),this}setTools(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.tools=e,this}setMaintainer(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.maintainer=e,this}setRepository(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.repository=e,this}setDocs(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.docs=e,this}setVerification(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.verification=e,this}addVerificationDNS(e,t){this.config.mcpServer||(this.config.mcpServer={});const r={type:Sh.DNS,value:e,dns_field:t};return this.config.mcpServer.verification=r,this}addVerificationSignature(e){this.config.mcpServer||(this.config.mcpServer={});const t={type:Sh.SIGNATURE,value:e};return this.config.mcpServer.verification=t,this}addVerificationChallenge(e){this.config.mcpServer||(this.config.mcpServer={});const t={type:Sh.CHALLENGE,value:"",challenge_path:e};return this.config.mcpServer.verification=t,this}addSocial(e,t){const r=this.socials.find(t=>t.platform===e);if(r)r.handle=t;else{const r={platform:e,handle:t};this.socials.push(r)}return this}setSocials(e){return this.socials=e,this}setProfilePicture(e,t){return this.config.pfpBuffer=e,this.config.pfpFileName=t,this}setExistingProfilePicture(e){return this.config.existingPfpTopicId=e,this}setNetworkType(e){return this.config.network=e,this}setExistingAccount(e,t){return this.config.existingAccount={accountId:e,privateKey:t},this}build(){if(!this.config.name)throw new Error("MCP server name is required");if(!this.config.network)throw new Error("Network type is required");if(!this.config.mcpServer)throw new Error("MCP server details are required");if(!this.config.mcpServer.version)throw new Error("MCP server version is required");if(!this.config.mcpServer.connectionInfo)throw new Error("MCP server connection info is required");if(!this.config.mcpServer.services||0===this.config.mcpServer.services.length)throw new Error("At least one MCP service type is required");if(!this.config.mcpServer.description)throw new Error("MCP server description is required");return this.config.bio||this.logger.warn("No bio provided for MCP server profile"),this.config.pfpBuffer||this.config.existingPfpTopicId||this.logger.warn("No profile picture provided or referenced"),this.socials.length>0?{...this.config,socials:this.socials}:this.config}}class hg{constructor(){this.config={version:"1.0",type:3},this.logger=y.getInstance({module:"FloraBuilder"})}setDisplayName(e){return this.config.display_name=e,this}setBio(e){return this.config.bio=e,this}setMembers(e){return this.config.members=e,this}setThreshold(e){return this.config.threshold=e,this}setTopics(e){return this.config.topics=e,this.config.inboundTopicId=e.communication,this.config.outboundTopicId=e.transaction,this}setPolicies(e){return this.config.policies=e,this}setMetadata(e){return this.config.metadata=e,this}addMetadata(e,t){return this.config.metadata||(this.config.metadata={}),this.config.metadata[e]=t,this}build(){if(!this.config.display_name)throw new Error("Flora display name is required");if(!this.config.members||0===this.config.members.length)throw new Error("Flora must have at least one member");if(!this.config.threshold||this.config.threshold<1)throw new Error("Flora threshold must be at least 1");if(this.config.threshold>this.config.members.length)throw new Error("Flora threshold cannot exceed number of members");if(!this.config.topics)throw new Error("Flora topics are required");if(!this.config.inboundTopicId||!this.config.outboundTopicId)throw new Error("Flora inbound and outbound topic IDs are required");return this.config}}const gg=Object.freeze(Object.defineProperty({__proto__:null,AIAgentCapability:Ih,AIAgentDetailsSchema:Rh,AIAgentProfileSchema:Mh,AIAgentType:bh,AgentBuilder:ug,BaseProfileSchema:Dh,EndpointType:wh,FloraBuilder:hg,HCS11Client:$h,HCS11ProfileSchema:Lh,InboundTopicType:kh,MCPServerBuilder:pg,MCPServerCapability:Th,MCPServerConnectionInfoSchema:xh,MCPServerDetailsSchema:Oh,MCPServerHostSchema:zh,MCPServerProfileSchema:Uh,MCPServerResourceSchema:_h,MCPServerToolSchema:Ph,MCPServerVerificationSchema:Nh,PersonBuilder:dg,PersonalProfileSchema:Fh,ProfileType:yh,SUPPORTED_SOCIAL_PLATFORMS:vh,SocialLinkSchema:Ch,VerificationType:Sh,capabilityNameToCapabilityMap:Eh,mcpServiceNameToCapabilityMap:Ah},Symbol.toStringTag,{value:"Module"}));class mg{constructor(e){this.connections=new Map,this.pendingRequests=new Map,this.profileCache=new Map,this.filterPendingAccountIds=new Set;const t={module:"ConnectionsManager",level:e?.logLevel||"info",prettyPrint:!0,silent:e?.silent};if(this.logger=y.getInstance(t),e?.filterPendingAccountIds&&(this.filterPendingAccountIds=new Set(e.filterPendingAccountIds)),!e.baseClient)throw new Error("ConnectionsManager requires a baseClient to operate");this.baseClient=e.baseClient}async fetchConnectionData(e){try{const t=await this.baseClient.retrieveCommunicationTopics(e),r=e=>Boolean(e)&&!e.includes(":");if(!r(t?.inboundTopic)||!r(t?.outboundTopic))return this.logger.warn("Invalid topic IDs detected in retrieved communication topics"),this.getAllConnections();const[i,n]=await Promise.all([this.baseClient.getMessages(t?.outboundTopic),this.baseClient.getMessages(t?.inboundTopic)]);this.processOutboundMessages(i.messages||[],e),this.processInboundMessages(n.messages||[]);const o=Array.from(this.connections.values()).filter(e=>"pending"===e.status||e.isPending).length;return this.logger.debug(`Processed ${i.messages?.length||0} outbound and ${n.messages?.length||0} inbound messages. Found ${o} pending connections.`),await this.checkTargetInboundTopicsForConfirmations(),await this.checkOutboundRequestsForConfirmations(),await this.fetchProfilesForConnections(),await this.fetchConnectionActivity(),this.getAllConnections()}catch(t){return this.logger.error("Error fetching connection data:",t),this.getAllConnections()}}async checkTargetInboundTopicsForConfirmations(){const e=Array.from(this.connections.values()).filter(e=>(e.isPending||"pending"===e.status)&&e.targetInboundTopicId);if(0===e.length)return;const t=new Map;e.forEach(e=>{if(e.targetInboundTopicId){const r=t.get(e.targetInboundTopicId)||[];r.push(e),t.set(e.targetInboundTopicId,r)}});for(const[i,n]of t.entries())for(let e=1;e<=2;e++)try{const t=(await this.baseClient.getMessages(i)).messages||[];let r=!1;for(const e of n){const i=e.connectionRequestId;if(!i)continue;const n=t.find(t=>{if("connection_created"!==t.op||!t.connection_topic_id)return!1;if(t.connection_id!==i)return!1;if(e.uniqueRequestKey){const r=e.uniqueRequestKey.split(":");if(r.length>1){const i=r[1];if(t.operator_id&&t.operator_id===i)return!0;if(t.connected_account_id===e.targetAccountId)return!0}}return!0});if(n?.connection_topic_id){r=!0;const t=n.connection_topic_id;let o=e.uniqueRequestKey;const s={connectionTopicId:t,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName,targetInboundTopicId:e.targetInboundTopicId,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(n.created||e.created),profileInfo:e.profileInfo,connectionRequestId:i,uniqueRequestKey:e.uniqueRequestKey,originTopicId:e.originTopicId,processed:e.processed,memo:e.memo};this.connections.set(t,s),o&&this.connections.delete(o),this.logger.debug(`Confirmed connection in target inbound topic: ${t}`)}}if(r||2===e)break;await new Promise(e=>setTimeout(e,500))}catch(r){if(this.logger.debug(`Error fetching target inbound topic ${i}:`,r),2===e)break;await new Promise(e=>setTimeout(e,500))}}async checkOutboundRequestsForConfirmations(){const e=Array.from(this.connections.values());this.logger.info(`Total connections in map: ${e.length}`);const t=e.filter(e=>"pending"===e.status);this.logger.info(`Connections with status='pending': ${t.length}`);const r=e.filter(e=>"pending"===e.status);if(Boolean(r?.length))for(const n of r){if(this.logger.debug(`Processing pending connection: ${n.connectionTopicId}`),!n.targetAccountId){this.logger.debug(`Skipping connection ${n.connectionTopicId} - no targetAccountId`);continue}let e=n.targetInboundTopicId;if(!e)try{const t=await this.baseClient.retrieveProfile(n.targetAccountId);if(!t?.profile?.inboundTopicId){this.logger.debug(`Couldn't get inbound topic ID for account ${n.targetAccountId}`);continue}e=t.profile.inboundTopicId,this.connections.set(n.connectionTopicId,{...n,targetInboundTopicId:e}),this.logger.debug(`Updated connection ${n.connectionTopicId} with inbound topic ID: ${e}`)}catch(i){this.logger.debug(`Error fetching profile for ${n.targetAccountId}: ${i}`);continue}if(!e||e.includes(":")){this.logger.debug(`Skipping invalid inbound topic format: ${e}`);continue}const t=n.connectionRequestId||n.inboundRequestId;if(t)try{this.logger.debug(`Checking for confirmations on topic ${e} for request ID ${t}`);const r=await this.baseClient.getMessages(e),i=(r.messages||[]).find(e=>"connection_created"===e.op&&e.connection_id===t&&e.connection_topic_id);if(i?.connection_topic_id){const e=i.connection_topic_id;this.logger.info(`Found confirmation for request #${t} to ${n.targetAccountId} on their inbound topic`);const r={connectionTopicId:e,targetAccountId:n.targetAccountId,targetAgentName:n.targetAgentName,targetInboundTopicId:n.targetInboundTopicId,targetOutboundTopicId:n.targetOutboundTopicId,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(i.created||n.created),lastActivity:new Date(i.created||n.created),profileInfo:n.profileInfo,connectionRequestId:n.connectionRequestId,confirmedRequestId:n.confirmedRequestId,requesterOutboundTopicId:n.requesterOutboundTopicId,inboundRequestId:n.inboundRequestId,closedReason:n.closedReason,closeMethod:n.closeMethod,uniqueRequestKey:n.uniqueRequestKey,originTopicId:n.originTopicId,processed:n.processed,memo:n.memo};this.connections.set(e,r),n.connectionTopicId&&this.connections.delete(n.connectionTopicId)}else this.logger.debug(`No confirmation found for request ID ${t} on topic ${e}`)}catch(i){this.logger.warn(`Error checking for confirmations on target inbound topic for ${n.targetAccountId}: ${i}`)}else this.logger.debug(`Skipping connection ${n.connectionTopicId} - no request ID`)}else this.logger.info("No pending connections found")}async fetchProfilesForConnections(){const e=new Set;for(const r of this.connections.values())r.targetAccountId&&!this.profileCache.has(r.targetAccountId)&&e.add(r.targetAccountId);const t=Array.from(e).map(async e=>{try{const t=await this.baseClient.retrieveProfile(e);t.success&&t.profile&&(this.addProfileInfo(e,t.profile),this.updatePendingConnectionsWithProfileInfo(e,t.profile))}catch(t){this.logger.debug(`Failed to fetch profile for ${e}:`,t)}});await Promise.allSettled(t)}updatePendingConnectionsWithProfileInfo(e,t){const r=Array.from(this.connections.values()).filter(t=>t.targetAccountId===e&&(t.isPending||t.needsConfirmation)&&!t.targetInboundTopicId);if(r.length>0&&t.inboundTopicId)for(const i of r){const e={...i,targetInboundTopicId:t.inboundTopicId};this.connections.set(i.connectionTopicId,e)}}async fetchConnectionActivity(){const e=this.getActiveConnections().filter(e=>{const t=e.connectionTopicId;return!(!t||t.includes(":")||!t.match(/^0\.0\.\d+$/))||(this.logger.debug(`Skipping activity fetch for invalid topic ID format: ${t}`),!1)}).map(async e=>{try{const t=e.connectionTopicId,r=await this.baseClient.getMessages(t);r?.messages?.length>0&&this.processConnectionMessages(t,r.messages)}catch(t){this.logger.debug(`Failed to fetch activity for ${e.connectionTopicId}:`,t)}});await Promise.allSettled(e)}shouldFilterAccount(e){return!!this.filterPendingAccountIds.has(e)&&!this.hasEstablishedConnectionWithAccount(e)}processOutboundMessages(e,t){if(!Boolean(e?.length))return Array.from(this.connections.values());const r=e.filter(e=>"connection_request"===e.op&&e.connection_request_id);for(const o of r){const e=o.connection_request_id,r=o.operator_id||"",i=this.baseClient.extractAccountFromOperatorId(r),n=this.baseClient.extractTopicFromOperatorId(r);if(this.shouldFilterAccount(i)){this.logger.debug(`Filtering out outbound request to account: ${i}`);continue}const s=Array.from(this.connections.values()).some(t=>t.connectionRequestId===e&&!t.isPending&&t.targetAccountId===i),a=`req-${e}:${r}`;if(!s&&!this.pendingRequests.has(a)){const s={id:e,requesterId:t,requesterTopicId:o.outbound_topic_id||"",targetAccountId:i,targetTopicId:n,operatorId:r,sequenceNumber:o.sequence_number,created:o.created||new Date,memo:o.m,status:"pending"};if(this.pendingRequests.set(a,s),!this.connections.has(a)){const t={connectionTopicId:a,targetAccountId:i,targetInboundTopicId:n,status:"pending",isPending:!0,needsConfirmation:!1,created:o.created||new Date,connectionRequestId:e,uniqueRequestKey:a,originTopicId:o.outbound_topic_id||"",processed:!1,memo:o.m};this.connections.set(a,t)}}}const i=e.filter(e=>"connection_created"===e.op&&e.connection_topic_id&&e.connection_request_id);for(const o of i){const e=o.connection_request_id,t=o.connection_topic_id,r=this.baseClient.extractAccountFromOperatorId(o.operator_id||"");if(this.shouldFilterAccount(r)){this.logger.debug(`Filtering out outbound confirmation to account: ${r}`);continue}const i=`req-${e}:${o.operator_id}`,n=this.pendingRequests.get(i);if(n&&(n.status="confirmed"),this.connections.has(i)&&this.connections.delete(i),this.connections.has(t)){const r=this.connections.get(t);this.connections.set(t,{...r,status:"established",isPending:!1,needsConfirmation:!1,connectionRequestId:e,confirmedRequestId:o.confirmed_request_id,requesterOutboundTopicId:o.outbound_topic_id,uniqueRequestKey:i,originTopicId:o.outbound_topic_id||"",processed:!1,memo:o.m})}else this.connections.set(t,{connectionTopicId:t,targetAccountId:r,status:"established",isPending:!1,needsConfirmation:!1,created:o.created||new Date,connectionRequestId:e,confirmedRequestId:o.confirmed_request_id,requesterOutboundTopicId:o.outbound_topic_id,uniqueRequestKey:i,originTopicId:o.outbound_topic_id||"",processed:!1,memo:o.m})}const n=e.filter(e=>"connection_closed"===e.op||"close_connection"===e.op&&e.connection_topic_id);for(const o of n){const e=o.connection_topic_id;if(this.connections.has(e)){const t=this.connections.get(e);if(this.shouldFilterAccount(t.targetAccountId)&&"established"!==t.status)continue;const r=o.connection_request_id&&o.operator_id?`req-${o.connection_request_id}:${o.operator_id}`:void 0;this.connections.set(e,{...t,status:"closed",isPending:!1,needsConfirmation:!1,lastActivity:o.created||new Date,closedReason:o.reason,closeMethod:o.close_method,uniqueRequestKey:r,originTopicId:t.originTopicId,processed:!1,memo:o.m})}}return Array.from(this.connections.values()).filter(e=>"established"===e.status||"closed"===e.status||!this.filterPendingAccountIds.has(e.targetAccountId))}processInboundMessages(e){if(!Boolean(e?.length))return Array.from(this.connections.values());const t=e.filter(e=>"connection_request"===e.op&&e.sequence_number),r=e.filter(e=>"connection_created"===e.op&&e.connection_topic_id&&e.connection_id);for(const i of t){const e=i.sequence_number,t=i.operator_id||"",n=this.baseClient.extractAccountFromOperatorId(t),o=this.baseClient.extractTopicFromOperatorId(t);if(this.shouldFilterAccount(n)){this.logger.debug(`Filtering out request from account: ${n}`);continue}const s=`inb-${e}:${t}`;r.some(t=>t.connection_id===e)?this.logger.debug(`Skipping request from ${n} as it has already been confirmed`):this.connections.has(s)||this.connections.set(s,{connectionTopicId:s,targetAccountId:n,targetInboundTopicId:o,status:"needs_confirmation",isPending:!1,needsConfirmation:!0,created:i.created||new Date,inboundRequestId:e,uniqueRequestKey:s,originTopicId:o,processed:!1,memo:i.m})}for(const i of r){const e=i.connection_id,t=i.connection_topic_id,r=i.connected_account_id||"",n=i.operator_id||"";if(this.shouldFilterAccount(r)){this.logger.debug(`Filtering out confirmation for account: ${r}`);continue}const o=`inb-${e}:${n}`;if(this.connections.has(o)&&this.connections.delete(o),this.connections.has(t)){const r=this.connections.get(t);this.connections.set(t,{...r,status:"established",isPending:!1,needsConfirmation:!1,inboundRequestId:e,uniqueRequestKey:o,originTopicId:i.connection_topic_id,processed:!1,memo:i.m})}else this.connections.set(t,{connectionTopicId:t,targetAccountId:r,status:"established",isPending:!1,needsConfirmation:!1,created:i.created||new Date,inboundRequestId:e,uniqueRequestKey:o,originTopicId:i.connection_topic_id,processed:!1,memo:i.m})}return Array.from(this.connections.values()).filter(e=>"established"===e.status||"closed"===e.status||!this.filterPendingAccountIds.has(e.targetAccountId))}processConnectionMessages(e,t){if(!t||0===t.length||!this.connections.has(e))return this.connections.get(e);const r=t.filter(e=>e.created).sort((e,t)=>{const r=e.created?new Date(e.created).getTime():0;return(t.created?new Date(t.created).getTime():0)-r})[0];if(r?.created){const t=this.connections.get(e);this.connections.set(e,{...t,lastActivity:r.created})}const i=t.find(e=>"close_connection"===e.op);if(i){const t=this.connections.get(e);this.connections.set(e,{...t,status:"closed",lastActivity:i.created||new Date,closedReason:i.reason,closeMethod:"explicit"})}return this.connections.get(e)}addProfileInfo(e,t){this.profileCache.set(e,t);const r=Array.from(this.connections.values()).filter(t=>t.targetAccountId===e);for(const i of r)this.connections.set(i.connectionTopicId,{...i,profileInfo:t,targetAgentName:t.display_name,targetInboundTopicId:t.inboundTopicId,targetOutboundTopicId:t.outboundTopicId})}getAllConnections(){return Array.from(this.connections.values()).filter(e=>"established"===e.status||"closed"===e.status||!this.filterPendingAccountIds.has(e.targetAccountId))}getPendingRequests(){return Array.from(this.connections.values()).filter(e=>e.isPending&&!this.filterPendingAccountIds.has(e.targetAccountId))}hasEstablishedConnectionWithAccount(e){return Array.from(this.connections.values()).some(t=>t.targetAccountId===e&&"established"===t.status)}getActiveConnections(){return Array.from(this.connections.values()).filter(e=>"established"===e.status)}getConnectionsNeedingConfirmation(){return Array.from(this.connections.values()).filter(e=>e.needsConfirmation&&!this.filterPendingAccountIds.has(e.targetAccountId))}getConnectionByTopicId(e){return this.connections.get(e)}getConnectionByAccountId(e){return Array.from(this.connections.values()).find(t=>t.targetAccountId===e&&"established"===t.status)}getConnectionsByAccountId(e){return Array.from(this.connections.values()).filter(t=>t.targetAccountId===e)}updateOrAddConnection(e){this.connections.set(e.connectionTopicId,e)}clearAll(){this.connections.clear(),this.pendingRequests.clear()}isConnectionRequestProcessed(e,t){for(const r of this.connections.values()){if(r.originTopicId===e&&r.inboundRequestId===t&&r.processed)return!0;if(r.originTopicId===e&&r.connectionRequestId===t&&r.processed)return!0}return!1}markConnectionRequestProcessed(e,t){let r=!1;for(const[i,n]of this.connections.entries())n.originTopicId===e&&n.inboundRequestId===t&&(this.connections.set(i,{...n,processed:!0}),r=!0,this.logger.debug(`Marked inbound connection request #${t} on topic ${e} as processed`)),n.originTopicId===e&&n.connectionRequestId===t&&(this.connections.set(i,{...n,processed:!0}),r=!0,this.logger.debug(`Marked outbound connection request #${t} on topic ${e} as processed`));return r}async getPendingTransactions(e,t){try{const i=await this.baseClient.getTransactionRequests(e,t?{...t}:void 0),n=[];for(const e of i)try{const t=await this.baseClient.mirrorNode.getScheduledTransactionStatus(e.schedule_id);t.executed||t.deleted||n.push(e)}catch(r){this.logger.error(`Error checking transaction status: ${r}`),n.push(e)}return n}catch(r){return this.logger.error(`Error getting pending transactions: ${r}`),[]}}getScheduledTransactionStatus(e){return this.baseClient.mirrorNode.getScheduledTransactionStatus(e)}async getLastOperatorActivity(e,t){try{const r=(await this.baseClient.getMessageStream(e)).messages.filter(e=>e.operator_id&&e.operator_id.includes(t)&&e.created);if(0===r.length)return;return r.sort((e,t)=>t.created.getTime()-e.created.getTime()),r[0].created}catch(r){return void this.logger.error(`Error getting last operator activity: ${r}`)}}}class fg extends ng{constructor(e){super({network:e.network,logLevel:e.logLevel,prettyPrint:e.prettyPrint,feeAmount:e.feeAmount,mirrorNode:e.mirrorNode,silent:e.silent,keyType:e.keyType}),this.logger=y.getInstance({level:e.logLevel||"info",module:"HCS-SDK",silent:e.silent}),this.operatorAccountId=e.operatorId,this.operatorCtx=B({network:this.network,operatorId:this.operatorAccountId,operatorKey:e.operatorPrivateKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:e.client??("mainnet"===e.network?r.Client.forMainnet():r.Client.forTestnet())}),this.client=this.operatorCtx.client,this.network=e.network,this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl||"https://moonscape.tech",this.hcs11Client=new $h({network:e.network,auth:{operatorId:e.operatorId,privateKey:this.operatorCtx.operatorKey.toString()},logLevel:e.logLevel,silent:e.silent,keyType:e.keyType,client:this.client})}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}getClient(){return this.client}async createAccount(e=50){await this.ensureInitialized(),this.logger.info(`Creating new account with ${e} HBAR initial balance`);const t=r.PrivateKey.generateED25519(),i=(new r.AccountCreateTransaction).setKeyWithoutAlias(t.publicKey).setInitialBalance(new r.Hbar(e)),n=await i.execute(this.client),o=(await n.getReceipt(this.client)).accountId;if(!o)throw this.logger.error("Account creation failed: accountId is null"),new ag("Failed to create account: accountId is null");return this.logger.info(`Account created successfully: ${o.toString()}`),{accountId:o.toString(),privateKey:t.toString()}}async createInboundTopic(e,t,r=60,i){let n,o;switch(await this.ensureInitialized(),this._generateHcs10Memo(ig.INBOUND,{accountId:e,ttl:r}),t){case kh.PUBLIC:n=!1;break;case kh.CONTROLLED:n=!0;break;case kh.FEE_BASED:if(n=!1,!i)throw new Error("Fee configuration builder is required for fee-based topics");i.customFees.forEach(t=>{t.feeCollectorAccountId||(t.feeCollectorAccountId=e)}),o=i.build(),o.customFees=o.customFees.map(t=>({...t,feeCollectorAccountId:t.feeCollectorAccountId||e}));break;default:throw new Error(`Unsupported inbound topic type: ${t}`)}const s=this.client.operatorPublicKey||this.operatorCtx.operatorKey.publicKey,a=jh({accountId:e,ttl:r,adminKey:!0,submitKey:n,operatorPublicKey:s});this.logger.info("Creating inbound topic");const{topicId:c}=await this.executeTopicCreateTransaction({transaction:a,feeConfig:o});return c}async createConnectionTopic(e){await this.ensureInitialized();const t=Vh({ttl:e.ttl??60,inboundTopicId:e.inboundTopicId,connectionId:e.connectionId,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:this.client.operatorPublicKey||this.operatorCtx.operatorKey.publicKey}),r=e.feeConfigBuilder?.build(),{topicId:i}=await this.executeTopicCreateTransaction({transaction:t,feeConfig:r});return i}async createAgent(e,t=60,r,i){await this.ensureInitialized();const n=e.build(),o=this.client.operatorAccountId?.toString();if(!o)throw new Error("Failed to retrieve operator account ID");const s=await this._createEntityTopics(t,{outboundTopicId:r?.outboundTopicId||"",inboundTopicId:r?.inboundTopicId||"",pfpTopicId:r?.pfpTopicId||n.existingPfpTopicId||"",profileTopicId:r?.profileTopicId||""},o,n.inboundTopicType,n.feeConfig,n.pfpBuffer,n.pfpFileName,i);if(s.profileTopicId)this.logger.info(`Using existing profile topic ID: ${s.profileTopicId}`);else{i&&i({stage:"preparing",message:"Creating agent profile",progressPercent:60,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,state:{currentStage:"profile",completedPercentage:60}}});const e=await this.storeHCS11Profile(n.name,n.bio,s.inboundTopicId,s.outboundTopicId,n.capabilities,n.metadata,n.pfpBuffer&&n.pfpBuffer.length>0&&!s.pfpTopicId?n.pfpBuffer:void 0,n.pfpFileName,s.pfpTopicId);s.profileTopicId=e.profileTopicId,this.logger.info(`Profile stored with topic ID: ${s.profileTopicId}`),i&&i({stage:"preparing",message:"Agent profile created",progressPercent:70,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,state:{currentStage:"profile",completedPercentage:70}}})}return s}async create(e,t){const r=t?.progressCallback,i=new ts({module:"ProfileCreate",logger:this.logger,callback:r?e=>r({stage:e.stage,message:e.message,progressPercent:e.progressPercent,details:e.details}):void 0});try{const r=e instanceof ug;let n;if(n=t?.existingState?t.existingState:{currentStage:"init",completedPercentage:0,createdResources:[]},r){this.logger.info("Creating Agent Profile and HCS-10 Topics");const t=e.build();n.agentMetadata=t.metadata}else this.logger.info("Creating Person HCS-11 Profile");i.preparing(`Starting ${r?"agent":"person"} resource creation`,0,{state:n});const o=this.client.operatorAccountId?.toString();if(!o)throw new Error("Failed to retrieve operator account ID");const{inboundTopicId:s,outboundTopicId:a,state:c}=await this.createCommunicationTopics(o,t,i);let l,u,d;if(n=c,e.setInboundTopicId(s),e.setOutboundTopicId(a),r){const t=e.build();l=t.existingPfpTopicId||n.pfpTopicId,u=t.pfpBuffer,d=t.pfpFileName||"pfp.png"}else{const t=e.build();l=n.pfpTopicId,u=t.pfpBuffer,d=t.pfpFileName}!l&&u&&d?l=await this.handleProfilePictureCreation(u,d,n,i):l&&(i.preparing(`Using existing profile picture: ${l}`,50,{state:n}),n.pfpTopicId=l),await this.createAndInscribeProfile(r,e,l,n,s,a,t,i),n.currentStage="complete",n.completedPercentage=100,i.completed((r?"Agent":"Person")+" profile created successfully",{profileTopicId:n.profileTopicId,inboundTopicId:s,outboundTopicId:a,pfpTopicId:l,state:n});let p="";n.outboundTopicId&&(p=n.outboundTopicId);let h="";n.inboundTopicId&&(h=n.inboundTopicId);let g="";n.pfpTopicId&&(g=n.pfpTopicId);let m="";return n.profileTopicId&&(m=n.profileTopicId),{outboundTopicId:p,inboundTopicId:h,pfpTopicId:g,profileTopicId:m,success:!0,state:n}}catch(n){return i.failed("Error during profile creation",{error:n.message}),{outboundTopicId:"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:n.message,state:{currentStage:"init",completedPercentage:0,error:n.message}}}}async inscribePfp(e,t){try{this.logger.info("Inscribing profile picture using HCS-11 client");const r=await this.hcs11Client.inscribeImage(e,t);if(!r.success)throw this.logger.error(`Failed to inscribe profile picture: ${r.error}`),new Error(r?.error||"Failed to inscribe profile picture");return this.logger.info(`Successfully inscribed profile picture with topic ID: ${r.imageTopicId}`),{pfpTopicId:r.imageTopicId,transactionId:r.transactionId,success:!0}}catch(Pw){const t=Pw,r=`Error inscribing profile picture: ${t.message}`;return this.logger.error(r),{pfpTopicId:"",transactionId:"",success:!1,error:t.message}}}async storeHCS11Profile(e,t,r,i,n=[],o,s,a,c){try{let l=c||"";if(!l&&s&&a){this.logger.info("Inscribing profile picture for HCS-11 profile");const e=await this.inscribePfp(s,a);e.success?l=e.pfpTopicId:this.logger.warn(`Failed to inscribe profile picture: ${e.error}, proceeding without pfp`)}else c&&(this.logger.info(`Using existing profile picture with topic ID: ${c} for HCS-11 profile`),l=c);const u=this.hcs11Client.getAgentTypeFromMetadata({type:o.type||"autonomous"}),d=o.socials?Object.entries(o.socials).filter(([e,t])=>t).map(([e,t])=>({platform:e,handle:t})):void 0,p=this.hcs11Client.createAIAgentProfile(e,u,n,o.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:l?`hcs://1/${l}`:void 0,socials:d,properties:o.properties,inboundTopicId:r,outboundTopicId:i,creator:o.creator}),h=await this.hcs11Client.createAndInscribeProfile(p,!0);if(!h.success)throw this.logger.error(`Failed to inscribe profile: ${h.error}`),new Error(h.error||"Failed to inscribe profile");return this.logger.info(`Profile inscribed with topic ID: ${h.profileTopicId}, transaction ID: ${h.transactionId}`),{profileTopicId:h.profileTopicId,pfpTopicId:l,transactionId:h.transactionId,success:!0}}catch(Pw){const t=Pw,r=`Error storing HCS-11 profile: ${t.message}`;return this.logger.error(r),{profileTopicId:"",pfpTopicId:"",transactionId:"",success:!1,error:t.message}}}async setupFees(e,t,i=[]){let n=e;if(!this.client.operatorPublicKey)return n;if(!t.customFees||0===t.customFees.length)return this.logger.warn("No custom fees provided in fee config for setupFees"),n;t.customFees.length>10&&(this.logger.warn("More than 10 custom fees provided, only the first 10 will be used"),t.customFees=t.customFees.slice(0,10));const o=t.customFees.map(e=>{if(!e.feeCollectorAccountId)return this.logger.error("Internal Error: Fee collector ID missing in setupFees"),null;if("FIXED_FEE"===e.type){const t=(new r.CustomFixedFee).setAmount(Number(e.feeAmount.amount)).setFeeCollectorAccountId(r.AccountId.fromString(e.feeCollectorAccountId));return e.feeTokenId&&t.setDenominatingTokenId(r.TokenId.fromString(e.feeTokenId)),t}return null}).filter(Boolean);if(0===o.length)return this.logger.warn("No valid custom fees to apply in setupFees"),n;const s=[...t.exemptAccounts||[],...i];return s.length>0&&(n=await this.setupExemptKeys(e,s)),n.setFeeScheduleKey(this.client.operatorPublicKey).setCustomFees(o)}async setupExemptKeys(e,t){let r=e;const i=Array.from(new Set(t)).filter(e=>e!==this.client.operatorAccountId?.toString());let n=[];if(i.length>0)try{n=await cc(i,this.network,this.logger)}catch(Pw){const t=`Error getting exempt keys: ${Pw.message}, continuing without exempt keys`;this.logger.warn(t)}return n.length>0&&(r=r.setFeeExemptKeys(n)),r}async handleConnectionRequest(e,t,i,n,o=60){this.logger.info(`Handling connection request ${i} from ${t}`);const s=this.getClient().operatorAccountId?.toString();if(!s)throw new Error("Failed to retrieve operator account ID");let a=await this.mirrorNode.getPublicKey(t);const c=await this.mirrorNode.getPublicKey(s);if(!c)throw new Error("Failed to retrieve public key");const l=new r.KeyList([c,a],1);let u;try{const t=Vh({ttl:o,inboundTopicId:e,connectionId:i,adminKey:l,submitKey:l});if(n){const e=n.build(),r={...e,exemptAccounts:[...e.exemptAccounts||[]]},{topicId:i}=await this.executeTopicCreateTransaction({transaction:t,feeConfig:r});u=i}else{const{topicId:e}=await this.executeTopicCreateTransaction({transaction:t});u=e}this.logger.info(`Created new connection topic ID: ${u}`)}catch(f){const e=`Failed to create connection topic: ${f}`;throw this.logger.error(e),new cg(e)}const d=`${e}@${s}`,p=await this.confirmConnection(e,u,t,i,"Connection accepted. Looking forward to collaborating!"),h=await this.retrieveCommunicationTopics(s),g=await this.retrieveCommunicationTopics(t),m=`${g.inboundTopic}@${t}`;return await this.recordOutboundConnectionConfirmation({outboundTopicId:h.outboundTopic,requestorOutboundTopicId:g.outboundTopic,connectionRequestId:i,confirmedRequestId:p,connectionTopicId:u,operatorId:m,memo:`Connection established with ${t}`}),{connectionTopicId:u,confirmedConnectionSequenceNumber:p,operatorId:d}}async confirmConnection(e,t,r,i,n,o){const s=await this.getOperatorId();this.logger.info(`Confirming connection with ID ${i}`);const a=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),c=Yh({inboundTopicId:e,connectionTopicId:t,connectedAccountId:r,operatorId:s,connectionId:i,memo:n}),l=await this.submitPayload(c,void 0,o,a.requiresFee),u=l.topicSequenceNumber?.toNumber();if(!u)throw new lg("Failed to confirm connection: sequence number is null");return u}async sendMessage(e,t,r,i,n){const o=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),s=await this.getOperatorId(),a={p:"hcs-10",op:"message",operator_id:s,data:t,m:r},c=JSON.stringify(a);if(globalThis.Buffer.from(c).length>1e3){this.logger.info("Message payload exceeds 1000 bytes, storing via inscription");try{const e=globalThis.Buffer.from(t),r=`message-${Date.now()}.json`,i=await this.inscribeFile(e,r,{progressCallback:n?.progressCallback,waitMaxAttempts:n?.waitMaxAttempts,waitIntervalMs:n?.waitIntervalMs});if(!Ha(i))throw new Error("Failed to inscribe large message content");a.data=`hcs://1/${Ha(i)}`,this.logger.info(`Large message inscribed with topic ID: ${Ha(i)}`)}catch(u){const e=`Error inscribing large message: ${u.message}`;throw this.logger.error(e),new Error(e)}}this.logger.info("Submitting message to connection topic",a);const l=Qh({connectionTopicId:e,operatorId:s,data:a.data,memo:r});return await this.submitPayload(l,void 0,i,o.requiresFee)}async executeTopicCreateTransaction(e){let t=e.transaction;e.feeConfig&&(t=await this.setupFees(t,e.feeConfig,e.additionalExemptAccounts||[]));try{const e=await t.execute(this.client),r=await e.getReceipt(this.client);if(!r.topicId)throw this.logger.error("Failed to create topic: topicId is null"),new Error("Failed to create topic: topicId is null");return{topicId:r.topicId.toString(),receipt:r,response:e}}catch(r){throw this.logger.error("Topic creation failed",{error:r.message,transactionId:r.transactionId?.toString(),operatorId:this.client.operatorAccountId?.toString()}),r}}async createTopic(e,t,r,i){this.logger.info("Creating topic");const n=z({memo:e,adminKey:t,submitKey:r,operatorPublicKey:this.client.operatorPublicKey||this.operatorCtx.operatorKey?.publicKey}),{topicId:o}=await this.executeTopicCreateTransaction({transaction:n,feeConfig:i});return o}async submitPayload(e,t,i,n=!1){if(e instanceof r.TopicMessageSubmitTransaction||"string"!=typeof e&&"function"==typeof e.getMessage){const t=(r.TopicMessageSubmitTransaction,e),o=t.getMessage();if(!o)throw new Error("Message payload is missing");const s=globalThis.Buffer.from(o).length;if(s>1e3)throw new sg("Payload size exceeds 1000 bytes limit",s);let a;if(n&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),t.setMaxTransactionFee(new r.Hbar(this.feeAmount))),i){const e=t.freezeWith(this.client),r=await e.sign(i);a=await r.execute(this.client)}else a=await t.execute(this.client);const c=await a.getReceipt(this.client);if(!c)throw this.logger.error("Failed to submit message: receipt is null"),new Error("Failed to submit message: receipt is null");return this.logger.info("Message submitted successfully"),c}const o="string"==typeof t?t:JSON.stringify(t),s=globalThis.Buffer.byteLength(o,"utf8");if(s>1e3)throw new sg("Payload size exceeds 1000 bytes limit",s);const a=_({topicId:e,message:o,transactionMemo:this.getHcs10TransactionMemo(t)||void 0});let c;if(n&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),a.setMaxTransactionFee(new r.Hbar(this.feeAmount))),i){const e=a.freezeWith(this.client),t=await e.sign(i);c=await t.execute(this.client)}else c=await a.execute(this.client);const l=await c.getReceipt(this.client);if(!l)throw this.logger.error("Failed to submit message: receipt is null"),new Error("Failed to submit message: receipt is null");return this.logger.info("Message submitted successfully"),l}async inscribeFile(e,t,r){if(this.logger.info("Inscribing file"),!this.client.operatorAccountId)throw this.logger.error("Operator account ID is not set"),new Error("Operator account ID is not set");if(!this.operatorCtx.operatorKey)throw this.logger.error("Operator private key is not set"),new Error("Operator private key is not set");const i=g.lookup(t)||"application/octet-stream",n=this.operatorCtx.operatorKey,o=await es.createWithAuth({type:"server",accountId:this.client.operatorAccountId.toString(),privateKey:n,network:this.network}),s={mode:"file",waitForConfirmation:!0,waitMaxAttempts:r?.waitMaxAttempts||30,waitIntervalMs:r?.waitIntervalMs||4e3,progressCallback:r?.progressCallback,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},a=await Oa({type:"buffer",buffer:e,fileName:t,mimeType:i},{accountId:this.client.operatorAccountId.toString(),privateKey:n,network:this.network},s,o);if(!a.confirmed||!a.inscription)throw new Error("Inscription was not confirmed");return a.inscription}async waitForConnectionConfirmation(e,t,r=60,i=2e3,n=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let o=0;o<r;o++){this.logger.info(`Attempt ${o+1}/${r} to find connection confirmation`);const s=(await this.mirrorNode.getTopicMessages(e)).filter(e=>"connection_created"===e.op);if(this.logger.info(`Found ${s.length} connection_created messages`),s.length>0)for(const e of s)if(Number(e.connection_id)===Number(t)){const r={connectionTopicId:e.connection_topic_id,sequence_number:Number(e.sequence_number),confirmedBy:e.operator_id,memo:e.m},i=this.extractAccountFromOperatorId(r.confirmedBy),o=this.getAccountAndSigner(),s=await this.retrieveCommunicationTopics(i),a=await this.retrieveCommunicationTopics(o.accountId);return this.logger.info("Connection confirmation found",r),n&&await this.recordOutboundConnectionConfirmation({requestorOutboundTopicId:s.outboundTopic,outboundTopicId:a.outboundTopic,connectionRequestId:t,confirmedRequestId:r.sequence_number,connectionTopicId:r.connectionTopicId,operatorId:r.confirmedBy,memo:r.memo||"Connection confirmed"}),r}o<r-1&&(this.logger.info(`No matching confirmation found, waiting ${i}ms before retrying...`),await new Promise(e=>setTimeout(e,i)))}throw new Error(`Connection confirmation not found after ${r} attempts for request ID ${t}`)}getAccountAndSigner(){const e=this.operatorCtx.operatorKey;return{accountId:this.client.operatorAccountId.toString(),signer:e}}async createAndRegisterAgent(e,t){try{const i=e.build(),n=t?.progressCallback,o=t?.baseUrl||this.guardedRegistryBaseUrl;let s=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};s.agentMetadata=i.metadata,n&&n({stage:"preparing",message:"Starting agent creation process",progressPercent:0,details:{state:s}});let a,c=i.existingAccount;if(s.inboundTopicId&&s.outboundTopicId&&s.profileTopicId){if(c=c||i.existingAccount,!c)throw new Error("Cannot resume registration without account information");const e="ecdsa"===this.operatorCtx.keyType?r.PrivateKey.fromStringECDSA(c.privateKey).publicKey.toString():r.PrivateKey.fromStringED25519(c.privateKey).publicKey.toString();a=new fg({network:i.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:e,logLevel:"info",guardedRegistryBaseUrl:o}),this.logger.info("Resuming registration with existing state",{inboundTopicId:s.inboundTopicId,outboundTopicId:s.outboundTopicId,profileTopicId:s.profileTopicId,pfpTopicId:s.pfpTopicId})}else{if(!c)if(s.createdResources&&s.createdResources.some(e=>e.startsWith("account:"))){const e=s.createdResources.find(e=>e.startsWith("account:")),r=e?.split(":")[1];r&&i.existingAccount?(c=i.existingAccount,this.logger.info(`Resuming with existing account: ${r}`)):(c=await this.createAccount(t?.initialBalance),s.createdResources=s.createdResources||[],s.createdResources.push(`account:${c.accountId}`))}else c=await this.createAccount(t?.initialBalance),s.createdResources=s.createdResources||[],s.createdResources.push(`account:${c.accountId}`);n&&n({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:s,account:c}});const r=new U({mirrorNode:this.mirrorNode,logger:this.logger}),l=await r.resolveOperatorKey(c.accountId,c.privateKey),u=l.privateKey.publicKey.toString();a=new fg({network:i.network,operatorId:c.accountId,operatorPrivateKey:l.privateKey.toString(),operatorPublicKey:u,keyType:l.keyType,logLevel:"info",guardedRegistryBaseUrl:o}),n&&n({stage:"preparing",message:"Initialized agent client",progressPercent:25,details:{state:s}});let d=s.outboundTopicId,p=s.inboundTopicId,h=s.pfpTopicId,g=s.profileTopicId;if(!d||!p||!g){h&&e.setExistingProfilePicture(h);const t=await a.createAgent(e,60,s,e=>{n&&n({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:{...e.details,state:{...s,...e.details?.state}}})});d=t.outboundTopicId,p=t.inboundTopicId,h=t.pfpTopicId,g=t.profileTopicId,s.outboundTopicId=d,s.inboundTopicId=p,s.pfpTopicId=h,s.profileTopicId=g,s.createdResources||(s.createdResources=[]),h&&!s.createdResources.includes(`pfp:${h}`)&&s.createdResources.push(`pfp:${h}`),s.createdResources.includes(`inbound:${p}`)||s.createdResources.push(`inbound:${p}`),s.createdResources.includes(`outbound:${d}`)||s.createdResources.push(`outbound:${d}`),s.createdResources.includes(`profile:${g}`)||s.createdResources.push(`profile:${g}`)}s.currentStage="profile",s.completedPercentage=60,n&&n({stage:"submitting",message:"Created agent with topics and profile",progressPercent:60,details:{state:s,outboundTopicId:d,inboundTopicId:p,pfpTopicId:h,profileTopicId:g}})}const l=`${s.inboundTopicId}@${c.accountId}`;if("complete"!==s.currentStage||!s.createdResources?.includes(`registration:${s.inboundTopicId}`)){const e=await a.registerAgentWithGuardedRegistry(c.accountId,i.network,{progressCallback:e=>{const t=60+.4*(e.progressPercent||0);n&&n({stage:e.stage,message:e.message,progressPercent:t,details:{...e.details,outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,operatorId:l,state:e.details?.state||s}})},existingState:s});if(!e.success)return{...e,state:s};s=e.state||s}return n&&n({stage:"completed",message:"Agent creation and registration complete",progressPercent:100,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,operatorId:l,state:s}}),{success:!0,state:s,metadata:{accountId:c.accountId,privateKey:c.privateKey,operatorId:l,inboundTopicId:s.inboundTopicId,outboundTopicId:s.outboundTopicId,profileTopicId:s.profileTopicId,pfpTopicId:s.pfpTopicId}}}catch(Pw){const r=Pw,i=`Failed to create and register agent: ${r.message}`;return this.logger.error(i),{error:r.message,success:!1,state:t?.existingState||{currentStage:"init",completedPercentage:0,error:r.message}}}}async registerAgentWithGuardedRegistry(e,t=this.network,i){try{this.logger.info("Registering agent with guarded registry");const n=i?.maxAttempts??60,o=i?.delayMs??2e3,s=i?.progressCallback;let a=i?.existingState||{currentStage:"registration",completedPercentage:0,createdResources:[]};s&&s({stage:"preparing",message:"Preparing agent registration",progressPercent:10,details:{state:a}});const c=await this.executeRegistration(e,t,this.guardedRegistryBaseUrl,this.logger);if(!c.success)return{...c,state:a};if(s&&s({stage:"submitting",message:"Submitting registration to registry",progressPercent:30,details:{transactionId:c.transactionId,state:a}}),c.transaction){const e=r.Transaction.fromBytes(globalThis.Buffer.from(c.transaction,"base64"));this.logger.info("Processing registration transaction"),await e.execute(this.client),this.logger.info("Successfully processed registration transaction")}s&&s({stage:"confirming",message:"Confirming registration transaction",progressPercent:60,details:{accountId:e,transactionId:c.transactionId,state:a}});const l=await this.waitForRegistrationConfirmation(c.transactionId,t,this.guardedRegistryBaseUrl,n,o,this.logger);return a.currentStage="complete",a.completedPercentage=100,a.createdResources||(a.createdResources=[]),c.transactionId&&a.createdResources.push(`registration:${c.transactionId}`),s&&s({stage:"completed",message:"Agent registration complete",progressPercent:100,details:{confirmed:l,transactionId:c.transactionId,state:a}}),{...c,confirmed:l,state:a}}catch(Pw){const t=Pw,r=`Failed to register agent: ${t.message}`;return this.logger.error(r),{error:t.message,success:!1}}}async registerAgent(e,t,r,i,n){this.logger.info("Registering agent");const o=eg({registryTopicId:e,accountId:t,inboundTopicId:r,memo:i});await this.submitPayload(o,void 0,n)}async getInboundTopicType(e){try{const t=await this.mirrorNode.getTopicInfo(e);if(!t)throw new Error("Topic does not exist");if(!(t.submit_key&&t.submit_key.key))return kh.PUBLIC;if(t.fee_schedule_key&&t.fee_schedule_key.key&&t.custom_fees){const r=t.custom_fees;if(r&&r.fixed_fees&&r.fixed_fees.length>0)return this.logger.info(`Topic ${e} is fee-based with ${r.fixed_fees.length} custom fees`),kh.FEE_BASED}return kh.CONTROLLED}catch(Pw){const t=`Error determining topic type: ${Pw.message}`;throw this.logger.error(t),new Error(t)}}getNetwork(){return this.network}getLogger(){return this.logger}getOperatorAccountId(){return this.client.operatorAccountId?.toString()??null}async createScheduledTransaction(e,t,i,n){this.logger.info("Creating scheduled transaction");const o=(new r.ScheduleCreateTransaction).setScheduledTransaction(e).setPayerAccountId(n?r.AccountId.fromString(n):this.client.operatorAccountId);if(t&&o.setScheduleMemo(t),i){const e=u.addSeconds(new Date,i),t=r.Timestamp.fromDate(e);o.setExpirationTime(t)}const s=await o.execute(this.client),a=await s.getReceipt(this.client);if(!a.scheduleId)throw this.logger.error("Failed to create scheduled transaction: scheduleId is null"),new Error("Failed to create scheduled transaction: scheduleId is null");const c=a.scheduleId.toString(),l=s.transactionId.toString();return this.logger.info(`Scheduled transaction created successfully: ${c}`),{scheduleId:c,transactionId:l}}async sendTransactionOperation(e,t,r,i,n){const o=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),s={p:"hcs-10",op:"transaction",operator_id:await this.getOperatorId(),schedule_id:t,data:r,m:n?.memo};return this.logger.info("Submitting transaction operation to connection topic",s),await this.submitPayload(e,s,i,o.requiresFee)}async sendTransaction(e,t,r,i){this.logger.info("Creating scheduled transaction and sending transaction operation");const{scheduleId:n,transactionId:o}=await this.createScheduledTransaction(t,i?.scheduleMemo,i?.expirationTime,i?.schedulePayerAccountId);return{scheduleId:n,transactionId:o,receipt:await this.sendTransactionOperation(e,n,r,i?.submitKey,{memo:i?.operationMemo})}}async createCommunicationTopics(e,t,r){let i=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};if(r&&r.preparing("Starting communication topic creation",0,{state:i}),!i.outboundTopicId){i.currentStage="topics",r&&r.preparing("Creating outbound topic",5,{state:i});const e=this.client.operatorPublicKey||this.operatorCtx.operatorKey.publicKey,n=Wh({ttl:t?.ttl??60,adminKey:!0,submitKey:!0,operatorPublicKey:e}),{topicId:o}=await this.executeTopicCreateTransaction({transaction:n});i.outboundTopicId=o,i.createdResources&&i.createdResources.push(`outbound:${i.outboundTopicId}`)}if(!i.inboundTopicId){i.currentStage="topics",r&&r.preparing("Creating inbound topic",10,{state:i});const n=this.client.operatorPublicKey||this.operatorCtx.operatorKey.publicKey,o=jh({accountId:e,ttl:t?.ttl??60,adminKey:!0,submitKey:!1,operatorPublicKey:n}),{topicId:s}=await this.executeTopicCreateTransaction({transaction:o});i.inboundTopicId=s,i.createdResources&&i.createdResources.push(`inbound:${i.inboundTopicId}`)}return{inboundTopicId:i.inboundTopicId,outboundTopicId:i.outboundTopicId,state:i}}async handleProfilePictureCreation(e,t,r,i){r.currentStage="pfp",i.preparing("Creating profile picture",30,{state:r}),i.createSubProgress({minPercent:30,maxPercent:50,logPrefix:"PFP"});const n=await this.inscribePfp(e,t);if(!n.success){let e="Failed to inscribe profile picture";throw n.error&&(e=n.error),new Error(e)}const o=n.pfpTopicId;return r.pfpTopicId=o,r.createdResources&&r.createdResources.push(`pfp:${r.pfpTopicId}`),i.preparing("Profile picture created",50,{state:r}),o}async createAndInscribeProfile(e,t,r,i,n,o,s,a){if(this.logger.info("Creating and inscribing profile"),i.profileTopicId)a&&a.preparing(`Using existing ${e?"agent":"person"} profile`,95,{state:i});else{let c;if(a&&a.preparing(`Storing HCS-11 ${e?"agent":"person"} profile`,80),a?.createSubProgress({minPercent:80,maxPercent:95,logPrefix:"StoreProfile"}),e){const e=t.build(),i=e.metadata?.socials?Object.entries(e.metadata.socials).map(([e,t])=>({platform:e,handle:t})):[];c=this.hcs11Client.createAIAgentProfile(e.name,"manual"===e.metadata?.type?0:1,e.capabilities||[],e.metadata?.model||"unknown",{alias:e.name.toLowerCase().replace(/\s+/g,"_"),bio:e.bio,profileImage:r?`hcs://1/${r}`:void 0,socials:i,properties:e.metadata?.properties||{},inboundTopicId:n,outboundTopicId:o,creator:e.metadata?.creator,baseAccount:e.baseAccount})}else{const e=t.build(),{pfpBuffer:i,pfpFileName:s,...a}=e;c=this.hcs11Client.createPersonalProfile(e.display_name,{alias:e.alias,bio:e.bio,socials:e.socials,profileImage:r?`hcs://1/${r}`:e.profileImage,properties:e.properties,inboundTopicId:n,outboundTopicId:o,baseAccount:e.base_account})}const l=await this.hcs11Client.createAndInscribeProfile(c,s?.updateAccountMemo??!0);if(!l.success){a&&a.failed(`Failed to inscribe ${e?"agent":"person"} profile`,{error:l.error});let t=`Failed to inscribe ${e?"agent":"person"} profile`;throw l.error&&(t=l.error),new Error(t)}i.profileTopicId=l.profileTopicId,i.createdResources&&i.createdResources.push(`profile:${l.profileTopicId}`),a&&a.preparing("HCS-11 Profile stored",95,{state:i})}}async createMCPServer(e,t=60,r,i){await this.ensureInitialized();const n=e.build(),o=this.client.operatorAccountId?.toString();if(!o)throw new Error("Failed to retrieve operator account ID");const s=await this._createEntityTopics(t,{outboundTopicId:r?.outboundTopicId||"",inboundTopicId:r?.inboundTopicId||"",pfpTopicId:r?.pfpTopicId||n.existingPfpTopicId||"",profileTopicId:r?.profileTopicId||""},o,kh.PUBLIC,void 0,n.pfpBuffer,n.pfpFileName,i);if(s.profileTopicId)this.logger.info(`Using existing profile topic ID: ${s.profileTopicId}`);else{this.logger.info("Creating and storing HCS-11 MCP server profile"),i&&i({stage:"preparing",message:"Creating MCP server profile",progressPercent:60,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,state:{currentStage:"profile",completedPercentage:60}}}),await this.hcs11Client.initializeOperator();const e=this.hcs11Client.createMCPServerProfile(n.name,n.mcpServer,{alias:n.alias,bio:n.bio,socials:n.socials||[],inboundTopicId:s.inboundTopicId,outboundTopicId:s.outboundTopicId,profileImage:s.pfpTopicId?`hcs://1/${s.pfpTopicId}`:void 0}),t=await this.hcs11Client.inscribeProfile(e);if(!t.success)throw this.logger.error(`Failed to inscribe MCP server profile: ${t.error}`),new Error(t.error||"Failed to inscribe MCP server profile");s.profileTopicId=t.profileTopicId,this.logger.info(`MCP server profile stored with topic ID: ${s.profileTopicId}`);const r=await this.hcs11Client.updateAccountMemoWithProfile(o,s.profileTopicId);r.success?this.logger.info("Updated account memo with profile reference"):this.logger.warn(`Failed to update account memo: ${r.error}, but continuing with MCP server creation`),i&&i({stage:"preparing",message:"MCP server profile created",progressPercent:70,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,state:{currentStage:"profile",completedPercentage:70}}})}return s}async _createEntityTopics(e,t,r,i,n,o,s,a){let{outboundTopicId:c,inboundTopicId:l,pfpTopicId:u,profileTopicId:d}=t;if(c)this.logger.info(`Using existing outbound topic ID: ${c}`);else{const t=Wh({ttl:e,adminKey:!0,submitKey:!0,operatorPublicKey:this.client.operatorPublicKey||this.operatorCtx.operatorKey.publicKey}),{topicId:r}=await this.executeTopicCreateTransaction({transaction:t});c=r,this.logger.info(`Created new outbound topic ID: ${c}`),a&&a({stage:"preparing",message:"Created outbound topic",progressPercent:30,details:{outboundTopicId:c,state:{currentStage:"topics",completedPercentage:30}}})}if(l?this.logger.info(`Using existing inbound topic ID: ${l}`):(l=await this.createInboundTopic(r,i,e,i===kh.FEE_BASED?n:void 0),this.logger.info(`Created new inbound topic ID: ${l}`),a&&a({stage:"preparing",message:"Created inbound topic",progressPercent:40,details:{outboundTopicId:c,inboundTopicId:l,state:{currentStage:"topics",completedPercentage:40}}})),!u&&o&&o.length>0&&s){this.logger.info("Inscribing new profile picture"),a&&a({stage:"preparing",message:"Inscribing profile picture",progressPercent:50,details:{outboundTopicId:c,inboundTopicId:l,state:{currentStage:"pfp",completedPercentage:50}}});u=(await this.inscribePfp(o,s)).pfpTopicId,this.logger.info(`Profile picture inscribed with topic ID: ${u}`),a&&a({stage:"preparing",message:"Profile picture inscribed",progressPercent:55,details:{outboundTopicId:c,inboundTopicId:l,pfpTopicId:u,state:{currentStage:"pfp",completedPercentage:55}}})}else u&&this.logger.info(`Using existing profile picture with topic ID: ${u}`);return{inboundTopicId:l,outboundTopicId:c,pfpTopicId:u,profileTopicId:d}}async createAndRegisterMCPServer(e,t){try{const i=e.build(),n=t?.progressCallback,o=t?.baseUrl||this.guardedRegistryBaseUrl;let s=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};s.serverMetadata={name:i.name,description:i.mcpServer.description,services:i.mcpServer.services},n&&n({stage:"preparing",message:"Starting MCP server creation process",progressPercent:0,details:{state:s}});let a,c=i.existingAccount;if(s.inboundTopicId&&s.outboundTopicId&&s.profileTopicId){if(c=c||i.existingAccount,!c)throw new Error("Cannot resume registration without account information");const e=M(c.privateKey),t=("ed25519"===e.detectedType?r.PrivateKey.fromStringED25519(c.privateKey):r.PrivateKey.fromStringECDSA(c.privateKey)).publicKey.toString();a=new fg({network:i.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:t,keyType:e.detectedType,logLevel:"info",guardedRegistryBaseUrl:o}),this.logger.info("Resuming registration with existing state",{inboundTopicId:s.inboundTopicId,outboundTopicId:s.outboundTopicId,profileTopicId:s.profileTopicId,pfpTopicId:s.pfpTopicId})}else{if(!c)if(s.createdResources&&s.createdResources.some(e=>e.startsWith("account:"))){const e=s.createdResources.find(e=>e.startsWith("account:")),r=e?.split(":")[1];r&&i.existingAccount?(c=i.existingAccount,this.logger.info(`Resuming with existing account: ${r}`)):(c=await this.createAccount(t?.initialBalance),s.createdResources=s.createdResources||[],s.createdResources.push(`account:${c.accountId}`))}else c=await this.createAccount(t?.initialBalance),s.createdResources=s.createdResources||[],s.createdResources.push(`account:${c.accountId}`);n&&n({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:s,account:c}});const l=new U({mirrorNode:this.mirrorNode,logger:this.logger}),u=await l.resolveOperatorKey(c.accountId,c.privateKey);e.setExistingAccount(c.accountId,c.privateKey);const d=("ed25519"===u.keyType?r.PrivateKey.fromStringED25519(c.privateKey):r.PrivateKey.fromStringECDSA(c.privateKey)).publicKey.toString();a=new fg({network:i.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:d,logLevel:"info",guardedRegistryBaseUrl:o}),n&&n({stage:"preparing",message:"Initialized MCP server client",progressPercent:25,details:{state:s}});let p=s.outboundTopicId,h=s.inboundTopicId,g=s.pfpTopicId,m=s.profileTopicId;if(!p||!h||!m){g&&e.setExistingProfilePicture(g);const t=await a.createMCPServer(e,60,s,e=>{n&&n({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:{...e.details,state:{...s,...e.details?.state}}})});p=t.outboundTopicId,h=t.inboundTopicId,g=t.pfpTopicId,m=t.profileTopicId,s.outboundTopicId=p,s.inboundTopicId=h,s.pfpTopicId=g,s.profileTopicId=m,s.createdResources||(s.createdResources=[]),g&&!s.createdResources.includes(`pfp:${g}`)&&s.createdResources.push(`pfp:${g}`),s.createdResources.includes(`inbound:${h}`)||s.createdResources.push(`inbound:${h}`),s.createdResources.includes(`outbound:${p}`)||s.createdResources.push(`outbound:${p}`),s.createdResources.includes(`profile:${m}`)||s.createdResources.push(`profile:${m}`)}s.currentStage="profile",s.completedPercentage=60,n&&n({stage:"submitting",message:"Created MCP server with topics and profile",progressPercent:60,details:{state:s,outboundTopicId:p,inboundTopicId:h,pfpTopicId:g,profileTopicId:m}})}const l=`${s.inboundTopicId}@${c.accountId}`;if("complete"!==s.currentStage||!s.createdResources?.includes(`registration:${s.inboundTopicId}`)){const e=await a.registerAgentWithGuardedRegistry(c.accountId,i.network,{progressCallback:e=>{const t=60+.4*(e.progressPercent||0);n&&n({stage:e.stage,message:e.message,progressPercent:t,details:{...e.details,outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,operatorId:l,state:e.details?.state||s}})},existingState:s});if(!e.success)return{...e,state:s};s=e.state||s}return n&&n({stage:"completed",message:"MCP server creation and registration complete",progressPercent:100,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,operatorId:l,state:s}}),{success:!0,state:s,metadata:{accountId:c.accountId,privateKey:c.privateKey,operatorId:l,inboundTopicId:s.inboundTopicId,outboundTopicId:s.outboundTopicId,profileTopicId:s.profileTopicId,pfpTopicId:s.pfpTopicId}}}catch(Pw){const r=Pw,i=`Failed to create and register MCP server: ${r.message}`;return this.logger.error(i),{error:r.message,success:!1,state:t?.existingState||{currentStage:"init",completedPercentage:0,error:r.message}}}}async createRegistryTopic(e={}){const{ttl:t=86400,metadata:r,adminKey:i=!1,submitKey:n=!1,waitForConfirmation:o=!0,waitMaxAttempts:s=30,waitIntervalMs:a=4e3,progressCallback:c}=e;try{let e;if(await this.ensureInitialized(),c&&c({stage:"preparing",message:"Preparing registry topic creation",progressPercent:10,details:{metadata:!!r}}),r){this.logger.info("Creating metadata inscription for registry"),c&&c({stage:"submitting",message:"Creating registry metadata inscription",progressPercent:30,details:{metadataName:r.name}});const t=globalThis.Buffer.from(JSON.stringify(r,null,2)),i={mode:"file",waitForConfirmation:o,waitMaxAttempts:s,waitIntervalMs:a,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},n=await Oa({type:"buffer",buffer:t,fileName:`registry-metadata-${Date.now()}.json`,mimeType:"application/json"},{accountId:this.client.operatorAccountId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},i);if(!n.confirmed||!n.inscription)throw new Error("Metadata inscription was not confirmed");e=Ha(n.inscription),this.logger.info(`Metadata inscribed to topic: ${e}`)}c&&c({stage:"submitting",message:"Creating registry topic",progressPercent:60,details:{metadataTopicId:e}});const l=this.operatorCtx.operatorKey,u=Gh({ttl:t,metadataTopicId:e,adminKey:i,submitKey:n,operatorPublicKey:this.client.operatorPublicKey||l.publicKey}),{topicId:d,response:p}=await this.executeTopicCreateTransaction({transaction:u});return c&&c({stage:"completed",message:"Registry topic created successfully",progressPercent:100,details:{topicId:d,metadataTopicId:e,transactionId:p.transactionId.toString()}}),this.logger.info(`Registry topic created successfully: ${d}`),{success:!0,topicId:d,transactionId:p.transactionId.toString(),metadataTopicId:e}}catch(l){const e=l instanceof Error?l.message:"Unknown error";return c&&c({stage:"failed",message:`Registry creation failed: ${e}`,progressPercent:0,details:{error:e}}),this.logger.error("Failed to create registry topic",{error:e}),{success:!1,error:e}}}}const yg="undefined"!=typeof window;class bg extends ng{constructor(e){let t;if(super({network:e.network,logLevel:e.logLevel,prettyPrint:e.prettyPrint,feeAmount:e.feeAmount,mirrorNode:e.mirrorNode,silent:e.silent}),this.hcs11Client=null,this.hwc=e.hwc,e.guardedRegistryBaseUrl?this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl:this.guardedRegistryBaseUrl="https://moonscape.tech",t=e.logLevel?e.logLevel:"info",this.logger=y.getInstance({level:t,module:"HCS-Browser",prettyPrint:e.prettyPrint,silent:e.silent}),yg)try{const{accountId:t,signer:r}=this.getAccountAndSigner();this.hcs11Client=new $h({network:e.network,auth:{operatorId:t,signer:r},logLevel:e.logLevel,silent:e.silent})}catch(Ow){this.logger.warn(`Failed to initialize HCS11Client: ${Ow}`)}else this.logger.error("BrowserHCSClient initialized in server environment - browser-specific features will not be available. Use HCS10Client instead.")}async sendMessage(e,t,r,i,n){this.logger.info("Sending message");const o={p:"hcs-10",op:"message",operator_id:await this.getOperatorId(),data:t,m:r},s=await this.canSubmitToTopic(e,this.hwc.getAccountInfo().accountId),a=JSON.stringify(o);if(globalThis.Buffer.from(a).length>1e3){this.logger.info("Message payload exceeds 1000 bytes, storing via inscription");try{const e=globalThis.Buffer.from(t),r=`message-${Date.now()}.json`,i=await this.inscribeFile(e,r,{progressCallback:n?.progressCallback,waitMaxAttempts:n?.waitMaxAttempts,waitIntervalMs:n?.waitIntervalMs});if(!Ha(i))throw new Error("Failed to inscribe large message content");o.data=`hcs://1/${Ha(i)}`,this.logger.info(`Large message inscribed with topic ID: ${Ha(i)}`)}catch(c){throw this.logger.error("Error inscribing large message:",c),new Error(`Failed to handle large message: ${c instanceof Error?c.message:"Unknown error"}`)}}return await this.submitPayload(e,o,i,s.requiresFee)}async getPublicKey(e){return await this.mirrorNode.getPublicKey(e)}async handleConnectionRequest(e,t,i,n="Connection accepted. Looking forward to collaborating!",o=60){this.logger.info("Handling connection request");const s=this.hwc.getAccountInfo().accountId;if(!s)throw new Error("Failed to retrieve user account ID");const a=await this.mirrorNode.getPublicKey(t),c=await this.mirrorNode.getPublicKey(s);if(!c)throw new Error("Failed to retrieve public key");const l=new r.KeyList([c,a],1),u=this._generateHcs10Memo(ig.CONNECTION,{ttl:o,inboundTopicId:e,connectionId:i}),d=(new r.TopicCreateTransaction).setTopicMemo(u).setAutoRenewAccountId(r.AccountId.fromString(s)).setAdminKey(l).setSubmitKey(l);this.logger.debug("Executing topic creation transaction");const p=await this.hwc.executeTransactionWithErrorHandling(d,!1);if(p?.error)throw this.logger.error(p.error),new Error(p.error);const h=p?.result;if(!h?.topicId)throw this.logger.error("Failed to create topic: topicId is null"),new Error("Failed to create topic: topicId is null");const g=h.topicId.toString(),m=`${e}@${s}`,f=await this.confirmConnection(e,g,t,i,m,n),y=await this.retrieveCommunicationTopics(s),b=await this.retrieveCommunicationTopics(t),w=`${b.inboundTopic}@${t}`;return await this.recordOutboundConnectionConfirmation({outboundTopicId:y.outboundTopic,requestorOutboundTopicId:b.outboundTopic,connectionRequestId:i,confirmedRequestId:f,connectionTopicId:g,operatorId:w,memo:`Connection established with ${t}`}),{connectionTopicId:g,confirmedConnectionSequenceNumber:f,operatorId:m}}async confirmConnection(e,t,r,i,n,o){this.logger.info("Confirming connection");const s={p:"hcs-10",op:"connection_created",connection_topic_id:t,connected_account_id:r,operator_id:n,connection_id:i,m:o},a=await this.submitPayload(e,s);if(!a?.topicSequenceNumber)throw this.logger.error("Failed to confirm connection: sequence number is null"),new Error("Failed to confirm connection: sequence number is null");return a.topicSequenceNumber.toNumber()}async create(e,t){const r=t?.progressCallback,i=new ts({module:"ProfileCreate",logger:this.logger,callback:r});try{const r=e instanceof ug;let n;if(n=t?.existingState?t.existingState:{currentStage:"init",completedPercentage:0,createdResources:[]},r){this.logger.info("Creating Agent Profile and HCS-10 Topics");const t=e.build();n.agentMetadata=t.metadata}else this.logger.info("Creating Person HCS-11 Profile");i.preparing(`Starting ${r?"agent":"person"} resource creation`,0,{state:n});const{inboundTopicId:o,outboundTopicId:s,state:a}=await this.createCommunicationTopics(t,i);let c,l,u;if(n=a,e.setInboundTopicId(o),e.setOutboundTopicId(s),r){const t=e.build();c=t.existingPfpTopicId||n.pfpTopicId,l=t.pfpBuffer,u=t.pfpFileName||"pfp.png"}else{const t=e.build();c=n.pfpTopicId,l=t.pfpBuffer,u=t.pfpFileName}!c&&l&&u?c=await this.handleProfilePictureCreation(l,u,n,i):c&&(i.preparing(`Using existing profile picture: ${c}`,50,{state:n}),n.pfpTopicId=c),await this.createAndInscribeProfile(r,e,c,n,o,s,t,i),n.currentStage="complete",n.completedPercentage=100,i.completed((r?"Agent":"Person")+" profile created successfully",{profileTopicId:n.profileTopicId,inboundTopicId:o,outboundTopicId:s,pfpTopicId:c,state:n});let d="";n.outboundTopicId&&(d=n.outboundTopicId);let p="";n.inboundTopicId&&(p=n.inboundTopicId);let h="";n.pfpTopicId&&(h=n.pfpTopicId);let g="";return n.profileTopicId&&(g=n.profileTopicId),{outboundTopicId:d,inboundTopicId:p,pfpTopicId:h,profileTopicId:g,success:!0,state:n}}catch(n){return i.failed("Error during profile creation",{error:n.message}),{outboundTopicId:"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:n.message,state:{currentStage:"init",completedPercentage:0,error:n.message}}}}async handleProfilePictureCreation(e,t,r,i){r.currentStage="pfp",i.preparing("Creating profile picture",30,{state:r});const n=i.createSubProgress({minPercent:30,maxPercent:50,logPrefix:"PFP"}),o=await this.inscribePfp(e,t,{progressCallback:e=>n.report({...e,progressPercent:e.progressPercent??0,details:{...e.details,state:r}})});if(!o.success){let e="Failed to inscribe profile picture";throw o.error&&(e=o.error),new Error(e)}const s=o.pfpTopicId;return r.pfpTopicId=s,r.createdResources&&r.createdResources.push(`pfp:${r.pfpTopicId}`),i.preparing("Profile picture created",50,{state:r}),s}async createAndInscribeProfile(e,t,r,i,n,o,s,a){if(!this.hcs11Client)throw a&&a.failed("HCS11Client is not available"),new Error("HCS11Client is not available");if(this.logger.info("Creating and inscribing profile"),i.profileTopicId)a&&a.preparing(`Using existing ${e?"agent":"person"} profile`,95,{state:i});else{a&&a.preparing(`Storing HCS-11 ${e?"agent":"person"} profile`,80);const c=a?.createSubProgress({minPercent:80,maxPercent:95,logPrefix:"StoreProfile"});let l;if(e){const e=t.build(),i=e.metadata?.socials?Object.entries(e.metadata.socials).map(([e,t])=>({platform:e,handle:t})):[];l=this.hcs11Client.createAIAgentProfile(e.name,"manual"===e.metadata?.type?0:1,e.capabilities||[],e.metadata?.model||"unknown",{alias:e.name.toLowerCase().replace(/\s+/g,"_"),bio:e.bio,profileImage:r?`hcs://1/${r}`:void 0,socials:i,properties:e.metadata?.properties||{},inboundTopicId:n,outboundTopicId:o,creator:e.metadata?.creator})}else{const e=t.build(),{pfpBuffer:i,pfpFileName:s,...a}=e;l=this.hcs11Client.createPersonalProfile(e.display_name,{alias:e.alias,bio:e.bio,socials:e.socials,profileImage:r?`hcs://1/${r}`:e.profileImage,properties:e.properties,inboundTopicId:n,outboundTopicId:o})}const u=await this.hcs11Client.createAndInscribeProfile(l,s?.updateAccountMemo??!0,{progressCallback:e=>c?.report({...e,progressPercent:e.progressPercent??0})});if(!u.success){a&&a.failed(`Failed to inscribe ${e?"agent":"person"} profile`,{error:u.error});let t=`Failed to inscribe ${e?"agent":"person"} profile`;throw u.error&&(t=u.error),new Error(t)}i.profileTopicId=u.profileTopicId,i.createdResources&&i.createdResources.push(`profile:${u.profileTopicId}`),a&&a.preparing("HCS-11 Profile stored",95,{state:i})}}initializeRegistrationState(e,t){const r=t||{inboundTopicId:e,currentStage:"registration",completedPercentage:0,createdResources:[]};return"registration"!==r.currentStage&&"complete"!==r.currentStage&&(r.currentStage="registration"),r}updateStateForCompletedRegistration(e,t){e.currentStage="complete",e.completedPercentage=100,e.createdResources&&e.createdResources.push(`registration:${t}`)}async registerAgentWithGuardedRegistry(e,t=this.network,i){try{let n;if(this.logger.info("Registering agent with guarded registry"),i?.existingState?.inboundTopicId)this.logger.info("Using inboundTopicId from existing state"),n=i.existingState.inboundTopicId;else{const t=await this.retrieveProfile(e,!1,{maxRetries:5,retryDelay:3e3});if(!t.success||!t.profile||!t.topicInfo){const r=t.error||`Failed to retrieve profile for account ${e}. Make sure the agent profile is created and memo is updated before registration.`;return this.logger.error(r),{error:r,success:!1,state:{currentStage:"registration",completedPercentage:0,error:r}}}n=t.topicInfo.inboundTopic}const o=this.initializeRegistrationState(n,i?.existingState),s=new ts({module:"AgentRegistration",logger:this.logger,callback:i?.progressCallback});s.preparing("Preparing agent registration",10,{inboundTopicId:n,accountId:e});const a=await this.executeRegistration(e,t,this.guardedRegistryBaseUrl,this.logger);if(!a.success)return{...a,state:o};if(s.submitting("Submitting registration to registry",30,{transactionId:a.transactionId}),a.transaction){const e=r.Transaction.fromBytes(globalThis.Buffer.from(a.transaction,"base64"));this.logger.info("Processing registration transaction");const t=await this.hwc.executeTransactionWithErrorHandling(e,!0);if(t.error)return{...a,error:t.error,success:!1,state:o};this.logger.info("Successfully processed registration transaction")}s.confirming("Confirming registration transaction",60,{accountId:e,inboundTopicId:n,transactionId:a.transactionId});const c=i?.maxAttempts??60,l=i?.delayMs??2e3,u=await this.waitForRegistrationConfirmation(a.transactionId,t,this.guardedRegistryBaseUrl,c,l,this.logger);return this.updateStateForCompletedRegistration(o,n),s.completed("Agent registration complete",{transactionId:a.transactionId,inboundTopicId:n,state:o,confirmed:u}),{...a,confirmed:u,state:o}}catch(n){return this.logger.error(`Registration error: ${n.message}`),{error:`Error during registration: ${n.message}`,success:!1,state:{currentStage:"registration",completedPercentage:0,error:n.message}}}}async createAndRegisterAgent(e,t){try{const r=e.build(),i=t?.progressCallback,n=new ts({module:"AgentCreateRegister",logger:this.logger,callback:i});let o=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};if(o.agentMetadata=r.metadata,n.preparing("Starting agent creation process",0,{state:o}),"complete"!==o.currentStage||!o.inboundTopicId||!o.outboundTopicId||!o.profileTopicId){const t=await this.create(e,{progressCallback:e=>{const t=.3*(e.progressPercent||0);n.report({...e,progressPercent:t,details:{...e.details,state:e.details?.state||o}})},existingState:o,updateAccountMemo:!0});if(!("state"in t))throw new Error("Create method did not return expected agent state.");if(!t.success)throw new Error(t.error||"Failed to create agent resources");o=t.state,o.agentMetadata=r.metadata,this.logger.info("Waiting for account memo update to propagate..."),await new Promise(e=>setTimeout(e,5e3))}n.preparing(`Agent creation status: ${o.currentStage}, ${o.completedPercentage}%`,30,{state:o});const{accountId:s}=this.getAccountAndSigner();if("complete"!==o.currentStage||!o.createdResources?.includes(`registration:${o.inboundTopicId}`)){t?.baseUrl&&(this.guardedRegistryBaseUrl=t.baseUrl);const e=await this.registerAgentWithGuardedRegistry(s,r.network,{progressCallback:e=>{const t=30+.7*(e.progressPercent||0);n.report({...e,progressPercent:t,details:{...e.details,state:e.details?.state||o}})},maxAttempts:t?.maxAttempts,delayMs:t?.delayMs,existingState:o});if(!e.success)throw new Error(e.error||"Failed to register agent with registry");o=e.state}return n.completed("Agent creation and registration complete",{state:o}),{success:!0,state:o,metadata:{accountId:s,operatorId:`${o.inboundTopicId}@${s}`,inboundTopicId:o.inboundTopicId,outboundTopicId:o.outboundTopicId,profileTopicId:o.profileTopicId,pfpTopicId:o.pfpTopicId,privateKey:null,...o.agentMetadata}}}catch(r){return this.logger.error(`Failed to create and register agent: ${r.message}`),{success:!1,error:`Failed to create and register agent: ${r.message}`,state:t?.existingState||{currentStage:"init",completedPercentage:0,error:r.message}}}}async storeHCS11Profile(e,t,r,i,n=[],o={},s,a,c,l){try{const u=l?.progressCallback,d=new ts({module:"StoreHCS11Profile",logger:this.logger,callback:u});d.preparing("Preparing agent profile data",0);let p=c;if(!p&&s&&a){const e=d.createSubProgress({minPercent:0,maxPercent:60,logPrefix:"PFP"}),t=await this.inscribePfp(s,a,{progressCallback:t=>{e.report({stage:t.stage,message:t.message,progressPercent:t.progressPercent||0,details:t.details})}});t.success?p=t.pfpTopicId:d.failed("Failed to inscribe profile picture, continuing without PFP")}else c?d.preparing(`Using existing profile picture: ${c}`,30):d.preparing("No profile picture provided",30);if(!this.hcs11Client)return d.failed("HCS11Client is not available in this environment"),{profileTopicId:"",success:!1,error:"HCS11Client is not available in this environment",transactionId:""};const h=this.hcs11Client.getAgentTypeFromMetadata({type:o.type||"autonomous"});d.preparing("Building agent profile",65);const g=o.socials?Object.entries(o.socials).filter(([e,t])=>t).map(([e,t])=>({platform:e,handle:t})):void 0,m=this.hcs11Client.createAIAgentProfile(e,h,n,o.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:p?`hcs://1/${p}`:void 0,socials:g,properties:{version:o.version||"1.0.0",creator:o.creator||"Unknown",supported_languages:o.supported_languages||["en"],permissions:o.permissions||[],model_details:o.model_details,training:o.training,capabilities_description:o.capabilities_description,...o},inboundTopicId:r,outboundTopicId:i,creator:o.creator}),f=d.createSubProgress({minPercent:65,maxPercent:100,logPrefix:"Profile"}),y=await this.hcs11Client.createAndInscribeProfile(m,l?.updateAccountMemo??!0,{progressCallback:e=>{f.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:e.details})}});return y.success?(d.completed("Profile stored successfully",{profileTopicId:y.profileTopicId}),{profileTopicId:y.profileTopicId,pfpTopicId:p,success:!0,transactionId:y.transactionId||""}):(d.failed("Failed to inscribe profile"),{profileTopicId:"",success:!1,error:y.error||"Failed to inscribe profile",transactionId:y.transactionId||""})}catch(u){return this.logger.error(`Error storing HCS11 profile: ${u.message}`),{profileTopicId:"",success:!1,error:u.message,transactionId:""}}}async createTopic(e,t,i){this.logger.info("Creating topic");const{accountId:n,signer:o}=this.getAccountAndSigner(),s=(new r.TopicCreateTransaction).setTopicMemo(e),a=await this.mirrorNode.getPublicKey(n);t&&a&&(s.setAdminKey(a),s.setAutoRenewAccountId(n)),i&&a&&s.setSubmitKey(a);const c=await this.hwc.executeTransactionWithErrorHandling(s,!1),l=c.error;if(l)return this.logger.error(l),{success:!1,error:l};const u=c.result;return u?.topicId?{success:!0,topicId:u.topicId.toString()}:(this.logger.error("Failed to create topic: topicId is null"),{success:!1,error:"Failed to create topic: topicId is null"})}async submitPayload(e,t,i,n){let o;this.logger.debug(`Submitting payload to topic ${e}`),o="string"==typeof t?t:JSON.stringify(t);const s=(new r.TopicMessageSubmitTransaction).setTopicId(e).setMessage(o),a=this.getHcs10TransactionMemo(t);let c;if(a&&s.setTransactionMemo(a),n&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),s.setMaxTransactionFee(new r.Hbar(this.feeAmount))),i){const{signer:e}=this.getAccountAndSigner();s.freezeWithSigner(e);const t=await s.sign(i);c=await this.hwc.executeTransactionWithErrorHandling(t,!0)}else c=await this.hwc.executeTransactionWithErrorHandling(s,!1);if(c?.error)throw this.logger.error(`Failed to submit payload: ${c.error}`),new Error(`Failed to submit payload: ${c.error}`);if(!c?.result)throw this.logger.error("Failed to submit message: receipt is null or undefined"),new Error("Failed to submit message: receipt is null or undefined");return this.logger.debug("Payload submitted successfully via HWC"),c.result}async inscribeFile(e,t,r){const{accountId:i,signer:n}=this.getAccountAndSigner(),o=g.lookup(t)||"application/octet-stream",s=await es.createWithAuth({type:"client",accountId:i,signer:n,network:this.network}),a={mode:"file",waitForConfirmation:!0,waitMaxAttempts:r?.waitMaxAttempts||30,waitIntervalMs:r?.waitIntervalMs||4e3,progressCallback:r?.progressCallback,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},c=await Fa({type:"buffer",buffer:e,fileName:t,mimeType:o},n,{...a,network:this.network},s);if(!c.confirmed||!c.inscription)throw new Error("Inscription was not confirmed");return c.inscription}getAccountAndSigner(){const e=this?.hwc?.getAccountInfo(),t=e?.accountId?.toString(),r=this?.hwc?.dAppConnector?.signers?.find(e=>e.getAccountId().toString()===t);if(!r)throw this.logger.error("Failed to find signer",{accountId:t,signers:this?.hwc?.dAppConnector?.signers,accountInfo:e}),new Error("Failed to find signer");return{accountId:t,signer:r}}async inscribePfp(e,t,r){try{const i=r?.progressCallback,n=new ts({module:"PFP-Inscription",logger:this.logger,callback:i});if(!this.hcs11Client)return n.failed("HCS11Client is not available in this environment"),{pfpTopicId:"",success:!1,error:"HCS11Client is not available in this environment",transactionId:""};n.preparing("Preparing to inscribe profile picture",10),this.logger.info("Inscribing profile picture using HCS-11 client");const o=e=>{n.report({stage:e.stage||"confirming",message:e.message||"Processing PFP inscription",progressPercent:e.progressPercent||50,details:e.details})},s=await this.hcs11Client.inscribeImage(e,t,{progressCallback:o});if(!s.success){let e="Failed to inscribe profile picture";s.error&&(e=s.error);let t="";return s.transactionId&&(t=s.transactionId),{pfpTopicId:"",success:!1,error:e,transactionId:t}}return n.completed("Successfully inscribed profile picture",{pfpTopicId:s.imageTopicId}),this.logger.info(`Successfully inscribed profile picture with topic ID: ${s.imageTopicId}`),{pfpTopicId:s.imageTopicId,success:!0,transactionId:s.transactionId||""}}catch(i){return this.logger.error(`Error inscribing profile picture: ${i.message}`),{pfpTopicId:"",success:!1,error:i.message,transactionId:""}}}async createCommunicationTopics(e,t){let r=e?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};t&&t.preparing("Starting communication topic creation",0,{state:r});const{accountId:i}=this.getAccountAndSigner();if(!r.outboundTopicId){r.currentStage="topics",t&&t.preparing("Creating outbound topic",5,{state:r});const n=this._generateHcs10Memo(ig.OUTBOUND,{ttl:e?.ttl,accountId:i}),o=await this.createTopic(n,!0,!0);if(!o.success||!o.topicId)throw new Error(o.error||"Failed to create outbound topic");r.outboundTopicId=o.topicId,r.createdResources&&r.createdResources.push(`outbound:${r.outboundTopicId}`)}if(!r.inboundTopicId){r.currentStage="topics",t&&t.preparing("Creating inbound topic",10,{state:r});const n=this._generateHcs10Memo(ig.INBOUND,{ttl:e?.ttl,accountId:i}),o=await this.createTopic(n,!0,!1);if(!o.success||!o.topicId)throw new Error(o.error||"Failed to create inbound topic");r.inboundTopicId=o.topicId,r.createdResources&&r.createdResources.push(`inbound:${r.inboundTopicId}`)}return{inboundTopicId:r.inboundTopicId,outboundTopicId:r.outboundTopicId,state:r}}}const wg=Object.freeze(Object.defineProperty({__proto__:null,AccountCreationError:ag,BrowserHCSClient:bg,ConnectionConfirmationError:lg,ConnectionsManager:mg,HCS10BaseClient:ng,HCS10Cache:og,HCS10Client:fg,Hcs10MemoType:ig,PayloadSizeError:sg,Registration:Hh,TopicCreationError:cg,buildHcs10ConfirmConnectionTx:Yh,buildHcs10CreateConnectionTopicTx:Vh,buildHcs10CreateInboundTopicTx:jh,buildHcs10CreateOutboundTopicTx:Wh,buildHcs10CreateRegistryTopicTx:Gh,buildHcs10OutboundConnectionCreatedRecordTx:Zh,buildHcs10OutboundConnectionRequestRecordTx:Xh,buildHcs10RegistryDeleteTx:tg,buildHcs10RegistryMigrateTx:rg,buildHcs10RegistryRegisterTx:eg,buildHcs10SendMessageTx:Qh,buildHcs10SubmitConnectionRequestTx:Jh},Symbol.toStringTag,{value:"Module"}));var Ig=(e=>(e[e.ACTION=0]="ACTION",e[e.ASSEMBLY=2]="ASSEMBLY",e[e.HASHLINKS=3]="HASHLINKS",e))(Ig||{});class Tg{constructor(e,t,r,i,n){this.entries=new Map,this.networkType=e,this.logger=t,this.registryType=r,this.topicId=i,this.client=n}async getEntry(e){const t=this.entries.get(e);return t||(this.topicId&&this.client?(await this.sync(),this.entries.get(e)||null):null)}async getLatestEntry(e){if(!this.client)return null;try{const t=await this.client.mirrorNode.getTopicMessagesByFilter(e,{order:"desc",limit:1});if(!t||0===t.length)return null;const r=t[0];let i;if(r.raw_content)i=JSON.parse(r.raw_content);else{const e=r;if("hcs-12"!==e.p||!e.op)return null;i={p:e.p,op:e.op,name:e.name,version:e.version,description:e.description,permissions:e.permissions,metadata:e.metadata,data:e.data,category:e.category,source:e.source,inputs:e.inputs,outputs:e.outputs,tags:e.tags,fields:e.fields,styles:e.styles,actions:e.actions,blocks:e.blocks,refs:e.refs},Object.keys(i).forEach(e=>{void 0===i[e]&&delete i[e]})}return{id:r.sequence_number.toString(),sequenceNumber:r.sequence_number,timestamp:r.consensus_timestamp||(new Date).toISOString(),submitter:r.payer||"unknown",data:i}}catch(t){return this.logger.error("Failed to get latest entry",{topicId:e,error:t}),null}}async listEntries(e){this.topicId&&this.client&&await this.sync();const t=Array.from(this.entries.values());return e?t.filter(t=>(!e.submitter||t.submitter===e.submitter)&&(!(e.afterTimestamp&&t.timestamp<e.afterTimestamp)&&!(e.beforeTimestamp&&t.timestamp>e.beforeTimestamp))):t}async sync(){if(this.topicId&&this.client){this.logger.info("Syncing registry entries",{topicId:this.topicId,registryType:Ig[this.registryType],lastSync:this.lastSyncTimestamp});try{const t=await this.client.mirrorNode.getTopicMessagesByFilter(this.topicId,{startTime:this.lastSyncTimestamp,order:"asc",limit:100});for(const r of t)try{let e;if(r.raw_content)e=JSON.parse(r.raw_content);else{const t=r;if("hcs-12"!==t.p||!t.op)continue;e={p:t.p,op:t.op,name:t.name,version:t.version,description:t.description,permissions:t.permissions,metadata:t.metadata,data:t.data,category:t.category,source:t.source,inputs:t.inputs,outputs:t.outputs,tags:t.tags,fields:t.fields,styles:t.styles,actions:t.actions,blocks:t.blocks,refs:t.refs,t_id:t.t_id,hash:t.hash,wasm_hash:t.wasm_hash,info_t_id:t.info_t_id,validation_rules:t.validation_rules,js_t_id:t.js_t_id,js_hash:t.js_hash,interface_version:t.interface_version,title:t.title,template:t.template,author:t.author,m:t.m},Object.keys(e).forEach(t=>{void 0===e[t]&&delete e[t]})}if("hcs-12"!==e.p)continue;const t={id:r.sequence_number.toString(),sequenceNumber:r.sequence_number,timestamp:r.consensus_timestamp||(new Date).toISOString(),submitter:r.payer||"unknown",data:e};this.entries.set(t.id,t)}catch(e){this.logger.warn("Failed to parse registry message",{sequenceNumber:r.sequence_number,error:e})}t.length>0?this.lastSyncTimestamp=t[t.length-1].consensus_timestamp||(new Date).toISOString():this.lastSyncTimestamp=(new Date).toISOString(),this.logger.info("Registry sync completed",{topicId:this.topicId,messageCount:t.length,lastSync:this.lastSyncTimestamp})}catch(e){throw this.logger.error("Failed to sync registry",{error:e}),e}}else this.logger.warn("Cannot sync without topic ID and client")}getTopicMemo(){return`hcs-12:1:60:${this.registryType}`}async createRegistryTopic(){if(!this.client)throw new Error("Client required to create topic");const e=await this.client.createRegistryTopic(this.registryType);return this.topicId=e,e}getConfig(){return{type:this.registryType,indexed:!1,ttl:60,topicId:this.topicId,memo:this.getTopicMemo()}}async inscribeContent(e,t,r){if(!this.client)throw new Error("Client required for inscription");const i="string"==typeof e?globalThis.Buffer.from(e):e;let n;if(this.logger.info("Inscribing content via HCS-1",{size:i.length,mimeType:t,registryType:Ig[this.registryType]}),"getOperatorAccountId"in this.client)n=await Oa({type:"buffer",buffer:i,fileName:"application/octet-stream"===t&&"wasm"===r?.fileType?`${r?.name||"content"}.wasm`:r?.name||"content",mimeType:t},{accountId:this.client.getOperatorAccountId(),privateKey:this.client.getOperatorPrivateKey(),network:this.networkType},{mode:"file",metadata:r,waitForConfirmation:!0});else{const{accountId:e,signer:o}=await this.client.getAccountAndSigner();n=await Fa({type:"buffer",buffer:i,fileName:"application/octet-stream"===t&&"wasm"===r?.fileType?`${r?.name||"content"}.wasm`:r?.name||"content",mimeType:t},o,{mode:"file",metadata:r,waitForConfirmation:!0})}if(!n.confirmed)throw new Error("Failed to inscribe content");const o=n.inscription.topic_id;if(!o)throw new Error("No topic ID in inscription response");return this.logger.info("Content inscribed successfully",{topicId:o}),o}validateBaseRegistration(e){if(!e.p||"hcs-12"!==e.p)throw new Error("Invalid protocol identifier");if(!e.op||"register"!==e.op)throw new Error("Invalid operation")}clearCache(){this.entries.clear(),this.lastSyncTimestamp=void 0,this.logger.info("Registry cache cleared",{registryType:Ig[this.registryType]})}getStats(){return{entryCount:this.entries.size,lastSync:this.lastSyncTimestamp,topicId:this.topicId,registryType:Ig[this.registryType]}}}const Sg=t.z.object({p:t.z.literal("hcs-12")}),kg=t.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid Hedera address format"),vg=t.z.string().regex(/^[a-f0-9]{64}$/,"Invalid SHA-256 hash format"),Eg=t.z.object({format:t.z.enum(["tar.gz","zip","car"]),root_manifest:t.z.string(),includes_lockfile:t.z.boolean(),workspace_members:t.z.array(t.z.string()).optional()}),Ag=t.z.object({source_t_id:kg,source_hash:vg,compiler_version:t.z.string(),cargo_version:t.z.string(),target:t.z.literal("wasm32-unknown-unknown"),profile:t.z.string(),build_flags:t.z.array(t.z.string()),lockfile_hash:vg,source_structure:Eg}),Cg=t.z.lazy(()=>t.z.object({type:t.z.string().optional(),required:t.z.array(t.z.string()).optional(),properties:t.z.record(Cg).optional(),pattern:t.z.string().optional(),minimum:t.z.number().optional(),maximum:t.z.number().optional(),regex:t.z.string().optional(),min:t.z.number().optional(),max:t.z.number().optional(),length:t.z.number().optional(),email:t.z.boolean().optional(),url:t.z.boolean().optional(),uuid:t.z.boolean().optional(),cuid:t.z.boolean().optional(),cuid2:t.z.boolean().optional(),ulid:t.z.boolean().optional(),datetime:t.z.boolean().optional(),ip:t.z.boolean().optional(),startsWith:t.z.string().optional(),endsWith:t.z.string().optional(),includes:t.z.string().optional(),gt:t.z.number().optional(),gte:t.z.number().optional(),lt:t.z.number().optional(),lte:t.z.number().optional(),int:t.z.boolean().optional(),positive:t.z.boolean().optional(),nonnegative:t.z.boolean().optional(),negative:t.z.boolean().optional(),nonpositive:t.z.boolean().optional(),multipleOf:t.z.number().optional(),finite:t.z.boolean().optional(),safe:t.z.boolean().optional(),nonempty:t.z.boolean().optional(),literal:t.z.union([t.z.string(),t.z.number(),t.z.boolean()]).optional(),enum:t.z.array(t.z.string()).optional(),nullable:t.z.boolean().optional(),nullish:t.z.boolean().optional(),optional:t.z.boolean().optional(),element:t.z.any().optional(),shape:t.z.record(t.z.any()).optional(),strict:t.z.boolean().optional(),passthrough:t.z.boolean().optional(),catchall:t.z.any().optional()})),Rg=t.z.object({p:t.z.literal("hcs-12"),op:t.z.literal("register"),t_id:kg,hash:vg,wasm_hash:vg,js_t_id:kg.optional(),js_hash:vg.optional(),interface_version:t.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid version format").optional(),info_t_id:kg.optional(),source_verification:Ag.optional(),previous_version:t.z.string().optional(),migration_notes:t.z.string().optional(),validation_rules:t.z.record(Cg).optional(),m:t.z.string().optional()}),xg=t.z.object({p:t.z.literal("hcs-12"),op:t.z.enum(["register","template"]),name:t.z.string(),version:t.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid semver format"),data:t.z.union([t.z.any(),t.z.string()]).optional(),t_id:kg.optional()});t.z.enum(["register","add-action","add-block","update"]);const Ng=Sg.extend({op:t.z.literal("register"),name:t.z.string(),version:t.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid semver format"),description:t.z.string().optional(),tags:t.z.array(t.z.string()).optional(),author:t.z.string().optional()}),zg=Sg.extend({op:t.z.literal("add-action"),t_id:kg,alias:t.z.string(),config:t.z.any().optional(),data:kg.optional()}),_g=Sg.extend({op:t.z.literal("add-block"),block_t_id:kg,actions:t.z.record(t.z.string(),kg).optional(),attributes:t.z.record(t.z.any()).optional(),children:t.z.array(t.z.string()).optional(),data:kg.optional()}),Pg=Sg.extend({op:t.z.literal("update"),description:t.z.string().optional(),tags:t.z.array(t.z.string()).optional()});t.z.object({type:t.z.enum(["vertical","horizontal","grid"]),responsive:t.z.boolean().optional(),containerClass:t.z.string().optional()}),t.z.object({source_t_id:kg,source_hash:vg,description:t.z.string().optional()});const Og=t.z.discriminatedUnion("op",[Ng,zg,_g,Pg]),Dg=Ng,Fg=Sg.extend({op:t.z.literal("register"),t_id:kg,name:t.z.string().max(100,"Name must be 100 characters or less"),description:t.z.string().max(500,"Description must be 500 characters or less").optional(),tags:t.z.array(t.z.string()).max(10,"Maximum 10 tags allowed").optional(),category:t.z.string().optional(),featured:t.z.boolean().optional(),icon:t.z.string().optional(),author:t.z.string().optional(),website:t.z.string().url().optional()});function Mg(e){return Rg.parse(e)}function Ug(e){return Og.parse(e)}function Bg(e,t){const r=t.safeParse(e);return r.success?{isValid:!0,errors:[],data:r.data}:{isValid:!1,errors:r.error.errors.map(e=>`${e.path.join(".")}: ${e.message}`)}}class Lg extends Tg{constructor(e,t,r,i){super(e,t,Ig.ACTION,r,i),this.actionsByHash=new Map,this.cryptoAdapter=sh()}async registerWithWasm(e,t,r){let i,n;if(Qp()){i=this.createSSRSafeHash(e,"wasm");const r=JSON.stringify(t);n=this.createSSRSafeHash(globalThis.Buffer.from(r),"info")}else{const r=this.cryptoAdapter.createHash("sha256").update(e).digest("hex"),o=r instanceof Promise?await r:r;i="string"==typeof o?o:o.toString("hex");const s=JSON.stringify(t),a=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(s)).digest("hex"),c=a instanceof Promise?await a:a;n="string"==typeof c?c:c.toString("hex")}const o=await this.inscribeContent(e,"application/octet-stream",{name:t.name,version:t.version,hash:i,fileType:"wasm"});let s;const a=JSON.stringify(t);globalThis.Buffer.byteLength(a,"utf8")>1024&&(s=await this.inscribeContent(a,"application/json",{name:`${t.name}-info`,version:t.version}));const c={p:"hcs-12",op:"register",t_id:o,hash:n,wasm_hash:i,info_t_id:s,source_verification:r,m:`${t.name} v${t.version}`};return await this.register(c),c}async register(e){if(this.validateRegistration(e),this.topicId&&this.client){this.logger.info("Submitting action registration to HCS",{topicId:this.topicId,hash:e.hash,wasmHash:e.wasm_hash});const t=(await this.client.submitMessage(this.topicId,JSON.stringify(e))).sequenceNumber;if(!t)throw new Error("No sequence number returned from submission");const r={id:t.toString(),sequenceNumber:t,timestamp:(new Date).toISOString(),submitter:"getHashConnect"in this.client?(await this.client.getAccountAndSigner()).accountId:this.client.getOperatorAccountId(),data:e};return this.entries.set(r.id,r),this.actionsByHash.set(e.hash,e),this.logger.info("Action registered",{hash:e.hash,sequenceNumber:t,hasSourceVerification:!!e.source_verification}),t.toString()}{const t=this.entries.size+1,r={id:t.toString(),sequenceNumber:t,timestamp:(new Date).toISOString(),submitter:"local",data:e};return this.entries.set(r.id,r),this.actionsByHash.set(e.hash,e),t.toString()}}async getAction(e){const t=this.actionsByHash.get(e);return t||(this.topicId&&this.client?(await this.sync(),this.actionsByHash.get(e)||null):null)}async getActionByTopicId(e){this.logger.debug("getActionByTopicId called",{topicId:e}),console.log("DEBUG: getActionByTopicId called",{topicId:e,cacheSize:this.actionsByHash.size,cachedTopicIds:Array.from(this.actionsByHash.values()).map(e=>e.t_id)});for(const t of this.actionsByHash.values())if(t.t_id===e)return this.logger.debug("Action found in cache",{topicId:e,action:t}),console.log("DEBUG: Action found in cache",{topicId:e,action:t}),t;if(this.topicId&&this.client){this.logger.debug("Action not in cache, syncing...",{topicId:e}),console.log("DEBUG: Action not in cache, syncing..."),await this.sync(),console.log("DEBUG: After sync",{cacheSize:this.actionsByHash.size,cachedTopicIds:Array.from(this.actionsByHash.values()).map(e=>e.t_id)});for(const t of this.actionsByHash.values())if(t.t_id===e)return this.logger.debug("Action found after sync",{topicId:e,action:t}),console.log("DEBUG: Action found after sync",{topicId:e,action:t}),t}return this.logger.warn("Action not found",{topicId:e}),console.log("DEBUG: Action not found",{topicId:e}),null}async getActionInfo(e){const t=await this.getAction(e);if(!t)return null;try{let e;if(!t.info_t_id)return this.logger.warn("Inline INFO storage not yet implemented"),null;{if(!this.client)return this.logger.error("Client not initialized - cannot fetch INFO"),null;let r;if("getOperatorAccountId"in this.client)r=await Ma(t.info_t_id,{accountId:this.client.getOperatorAccountId(),privateKey:this.client.getOperatorPrivateKey(),network:this.networkType});else{const{accountId:e}=await this.client.getAccountAndSigner();r=await Ma(t.info_t_id,{accountId:e,network:this.networkType})}if(!r.content)return this.logger.error("No content in inscription response"),null;e="string"==typeof r.content?r.content:globalThis.Buffer.from(r.content).toString("utf8")}const r=JSON.parse(e);let i;if(Qp())i=this.createSSRSafeHash(globalThis.Buffer.from(e),"info");else{const t=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(e)).digest("hex"),r=t instanceof Promise?await t:t;i="string"==typeof r?r:r.toString("hex")}if(i!==t.hash)throw this.logger.error("INFO hash mismatch",{expected:t.hash,computed:i}),new Error("Module info verification failed");return r}catch(r){return this.logger.error("Failed to fetch action INFO",{hash:e,error:r}),null}}async getActionWasm(e){const t=await this.getAction(e);if(!t)return null;if(!this.client)return this.logger.error("Client not initialized - cannot fetch WASM"),null;try{let e;if("getOperatorAccountId"in this.client)e=await Ma(t.t_id,{accountId:this.client.getOperatorAccountId(),privateKey:this.client.getOperatorPrivateKey(),network:this.networkType});else{const{accountId:r}=await this.client.getAccountAndSigner();e=await Ma(t.t_id,{accountId:r,network:this.networkType})}if(!e.content)return this.logger.error("No content in inscription response"),null;const r="string"==typeof e.content?globalThis.Buffer.from(e.content,"base64"):globalThis.Buffer.from(e.content);let i;if(Qp())i=this.createSSRSafeHash(r,"wasm");else{const e=this.cryptoAdapter.createHash("sha256").update(r).digest("hex"),t=e instanceof Promise?await e:e;i="string"==typeof t?t:t.toString("hex")}if(i!==t.wasm_hash)throw this.logger.error("WASM hash mismatch",{expected:t.wasm_hash,computed:i}),new Error("WASM binary verification failed");return new Uint8Array(r)}catch(r){return this.logger.error("Failed to fetch WASM from HCS-1",{topicId:t.t_id,error:r}),null}}async searchActions(e){return(await this.listEntries({submitter:e.creator,afterTimestamp:e.afterTimestamp,beforeTimestamp:e.beforeTimestamp})).map(e=>e.data).filter(t=>{if(void 0!==e.hasSourceVerification){if(!!t.source_verification!==e.hasSourceVerification)return!1}return!0})}async getVersionChain(e){const t=[];let r=e;for(;r;){const e=await this.getAction(r);if(!e)break;t.push(e),r=void 0}return t}validateRegistration(e){try{Mg(e)}catch(r){if(r instanceof t.ZodError){const e=r.errors[0];throw new Error(`Validation failed: ${e.path.join(".")} - ${e.message}`)}throw r}}async sync(){await super.sync(),this.actionsByHash.clear();for(const e of this.entries.values()){const t=e.data;this.actionsByHash.set(t.hash,t)}}clearCache(){super.clearCache(),this.actionsByHash.clear()}createSSRSafeHash(e,t){let r=0;for(let i=0;i<Math.min(e.length,256);i++)r=(r<<5)-r+e[i]&4294967295;return`ssr-${t}-${e.length}-${Math.abs(r).toString(16).padStart(8,"0")}`}}class Kg{constructor(e,t,r){this.blockCache=new Map,this.templateCache=new Map,this.networkType=e,this.logger=t,this.client=r}async loadBlockDefinition(e){const t=this.blockCache.get(e);if(t)return t;try{const t=new Gp,r=await t.resolve(e,{network:this.networkType});if(!r.content)throw new Error(`Block definition not found: ${e}`);let i;return i="object"!=typeof r.content||null===r.content||r.content instanceof ArrayBuffer?JSON.parse("string"==typeof r.content?r.content:r.content.toString()):r.content,this.blockCache.set(e,i),i}catch(r){throw this.logger.error("Failed to load block definition",{blockTopicId:e,error:r.message}),new Error(`Failed to load block definition: ${r.message}`)}}async loadBlockTemplate(e){const t=this.templateCache.get(e);if(t)return t;try{const t=new Gp,r=await t.resolve(e,{network:this.networkType});if(!r.content)throw new Error(`Block template not found: ${e}`);let i;return i="string"==typeof r.content?r.content:"object"==typeof r.content&&null!==r.content?r.content.text||JSON.stringify(r.content):r.content.toString(),this.templateCache.set(e,i),i}catch(r){throw this.logger.error("Failed to load block template",{templateTopicId:e,error:r.message}),new Error(`Failed to load block template: ${r.message}`)}}async loadBlock(e){const t=await this.loadBlockDefinition(e);return{definition:t,template:await this.loadBlockTemplate(t.template_t_id)}}async storeBlock(e,t){if(!this.client||!("inscribeFile"in this.client))throw new Error("Client does not support inscription");try{const r=globalThis.Buffer.from(e),i=await this.client.inscribeFile(r,`block-${t.name}-template.html`);if(!i?.topic_id)throw new Error("Failed to inscribe block template");const n={...t,template_t_id:i.topic_id},o=globalThis.Buffer.from(JSON.stringify(n)),s=await this.client.inscribeFile(o,`block-${t.name}-definition.json`);if(!s?.topic_id)throw new Error("Failed to inscribe block definition");return this.blockCache.set(s.topic_id,n),this.templateCache.set(i.topic_id,e),{definitionTopicId:s.topic_id,templateTopicId:i.topic_id}}catch(r){throw this.logger.error("Failed to store block",{error:r.message}),new Error(`Failed to store block: ${r.message}`)}}clearCache(){this.blockCache.clear(),this.templateCache.clear()}}class $g extends Tg{constructor(e,t,r,i){super(e,t,Ig.ASSEMBLY,r,i),this.assemblyStates=new Map}getTopicMemo(){return`hcs-12:0:60:${this.registryType}`}async register(e){return this.submitMessage(e)}async createAssemblyTopic(){const e=await this.createRegistryTopic();return this.topicId=e,e}async addAction(e){return this.submitMessage(e)}async addBlock(e){return this.submitMessage(e)}async update(e){return this.submitMessage(e)}async submitMessage(e){if(this.validateMessage(e),!this.topicId)throw new Error("Assembly topic ID not found");if(!this.client)throw new Error("Client not found");this.logger.info("Submitting assembly message to HCS",{topicId:this.topicId,op:e.op});const t=(await this.client.submitMessage(this.topicId,JSON.stringify(e))).sequenceNumber;if(!t)throw new Error("No sequence number returned from submission");const r={id:t.toString(),sequenceNumber:t,timestamp:(new Date).toISOString(),submitter:"getHashConnect"in this.client?(await this.client.getAccountAndSigner()).accountId:this.client.getOperatorAccountId(),data:e};return this.entries.set(r.id,r),await this.processMessage(r),this.logger.info("Assembly message processed",{op:e.op,sequenceNumber:t}),t.toString()}async processMessage(e){const t=e.data;if(!this.topicId)return;let r=this.assemblyStates.get(this.topicId);switch(t.op){case"register":const i=t;r={topicId:this.topicId,name:i.name,version:i.version,description:i.description,tags:i.tags,author:i.author,actions:[],blocks:[],created:e.timestamp,updated:e.timestamp},this.assemblyStates.set(this.topicId,r);break;case"add-action":if(!r)return void this.logger.warn("Cannot add action without assembly registration");const n=t,o={t_id:n.t_id,alias:n.alias,config:n.config,data:n.data};r.actions.push(o),r.updated=e.timestamp;break;case"add-block":if(!r)return void this.logger.warn("Cannot add block without assembly registration");const s=t,a={block_t_id:s.block_t_id,actions:s.actions,attributes:s.attributes,children:s.children,data:s.data};r.blocks.push(a),r.updated=e.timestamp;break;case"update":if(!r)return void this.logger.warn("Cannot update without assembly registration");const c=t;void 0!==c.description&&(r.description=c.description),void 0!==c.tags&&(r.tags=c.tags),r.updated=e.timestamp}}async getAssemblyState(e){const t=e||this.topicId;if(!t||!this.client)return null;let r=this.assemblyStates.get(t);if(r)return r;if(t===this.topicId&&this.entries.size>0){this.logger.debug("Building state from existing entries",{topicId:t,entriesCount:this.entries.size}),this.assemblyStates.clear();for(const r of this.entries.values())this.processAssemblyMessage(t,r);const e=this.assemblyStates.get(t)||null;return this.logger.debug("Built state from entries",{topicId:t,hasState:!!e,name:e?.name}),e}this.logger.info("Syncing assembly state from topic",{topicId:t});try{const e=await this.client.mirrorNode.getTopicMessagesByFilter(t,{order:"asc",limit:1e3}),r=Array.isArray(e)?e:[];this.logger.info("Processing assembly messages",{topicId:t,messageCount:r.length});for(const o of r)try{let e;if(!o.message)continue;try{let t;t="undefined"==typeof window?globalThis.Buffer.from(o.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(o.message),e=>e.charCodeAt(0))),e=JSON.parse(t),this.logger.debug("Successfully parsed message",{sequenceNumber:o.sequence_number,op:e.op,p:e.p})}catch(i){this.logger.debug("Failed to decode/parse message",{sequenceNumber:o.sequence_number,error:i});continue}if("hcs-12"!==e.p){this.logger.debug("Skipping non-HCS-12 message",{sequenceNumber:o.sequence_number,protocol:e.p});continue}const r={id:o.sequence_number.toString(),sequenceNumber:o.sequence_number,timestamp:o.consensus_timestamp||(new Date).toISOString(),submitter:o.payer_account_id||"unknown",data:e};this.processAssemblyMessage(t,r),this.logger.debug("Processed message for assembly",{topicId:t,sequenceNumber:r.sequenceNumber,op:r.data.op})}catch(i){this.logger.warn("Failed to parse assembly message",{sequenceNumber:o.sequence_number,error:i})}const n=this.assemblyStates.get(t)||null;return this.logger.info("Assembly state after sync",{topicId:t,hasState:!!n,name:n?.name,version:n?.version,actionsCount:n?.actions?.length||0,blocksCount:n?.blocks?.length||0}),n}catch(i){return this.logger.error("Failed to sync assembly state",{topicId:t,error:i}),null}}processAssemblyMessage(e,t){const r=t.data;let i=this.assemblyStates.get(e);switch(this.logger.debug("Processing assembly message",{topicId:e,op:r.op,hasState:!!i}),r.op){case"register":const n=r;i={topicId:e,name:n.name,version:n.version,description:n.description,tags:n.tags,author:n.author,actions:[],blocks:[],created:t.timestamp,updated:t.timestamp},this.assemblyStates.set(e,i),this.logger.debug("Assembly registered",{topicId:e,name:n.name,version:n.version});break;case"add-action":if(!i)return void this.logger.warn("Cannot add action without assembly registration");const o=r,s={t_id:o.t_id,alias:o.alias,config:o.config,data:o.data};i.actions.push(s),i.updated=t.timestamp;break;case"add-block":if(!i)return void this.logger.warn("Cannot add block without assembly registration");const a=r,c={block_t_id:a.block_t_id,actions:a.actions,attributes:a.attributes,children:a.children,data:a.data};i.blocks.push(c),i.updated=t.timestamp;break;case"update":if(!i)return void this.logger.warn("Cannot update without assembly registration");const l=r;void 0!==l.description&&(i.description=l.description),void 0!==l.tags&&(i.tags=l.tags),i.updated=t.timestamp}}async sync(){if(this.topicId&&this.client){this.entries.clear(),this.assemblyStates.delete(this.topicId),this.logger.info("Syncing assembly messages",{topicId:this.topicId});try{const t=await this.client.mirrorNode.getTopicMessagesByFilter(this.topicId,{order:"asc",limit:1e3}),r=Array.isArray(t)?t:[];this.logger.info("Processing assembly messages",{topicId:this.topicId,messageCount:r.length});for(const i of r)try{let t;if(i.message)try{let e;e="undefined"==typeof window?globalThis.Buffer.from(i.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(i.message),e=>e.charCodeAt(0))),t=JSON.parse(e)}catch(e){this.logger.debug("Failed to decode/parse message in sync",{sequenceNumber:i.sequence_number,error:e});continue}else if(i.raw_content)try{t=JSON.parse(i.raw_content)}catch{continue}else{const e=i;if(!e.p||!e.op)continue;t={...e},delete t.consensus_timestamp,delete t.sequence_number,delete t.payer_account_id,delete t.topic_id,delete t.running_hash,delete t.running_hash_version,delete t.chunk_info,delete t.created,delete t.payer}if("hcs-12"!==t.p)continue;const r={id:i.sequence_number.toString(),sequenceNumber:i.sequence_number,timestamp:i.consensus_timestamp||(new Date).toISOString(),submitter:i.payer_account_id||"unknown",data:t};this.entries.set(r.id,r),await this.processMessage(r),this.logger.debug("Processed sync message",{sequenceNumber:r.sequenceNumber,op:r.data.op})}catch(e){this.logger.warn("Failed to parse assembly message",{sequenceNumber:i.sequence_number,error:e})}this.logger.info("Assembly sync completed",{topicId:this.topicId,messageCount:r.length})}catch(e){throw this.logger.error("Failed to sync assembly",{error:e}),e}}else this.logger.warn("Cannot sync without topic ID and client")}validateMessage(e){try{Ug(e)}catch(r){if(r instanceof t.ZodError){const e=r.errors.map(e=>`${e.path.join(".")}: ${e.message}`);throw new Error(`Assembly validation failed: ${e.join("; ")}`)}throw r}}}class Hg extends Tg{constructor(e,t,r,i){super(e,t,Ig.HASHLINKS,r,i)}async register(e){this.validateRegistration(e);const t=`${this.topicId||"local"}_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,r={id:t,sequenceNumber:0,timestamp:(new Date).toISOString(),submitter:this.client&&"getHashConnect"in this.client?"browser":this.client?.getOperatorAccountId()||"local",data:e};if(this.entries.set(t,r),this.client&&this.topicId)try{const i=JSON.stringify(e),n=await this.client.submitMessage(this.topicId,i);return n.sequenceNumber&&(r.sequenceNumber=n.sequenceNumber,r.id=n.sequenceNumber.toString(),this.entries.delete(t),this.entries.set(r.id,r)),this.logger.info("HashLink submitted to HCS",{transactionId:n.transactionId,sequenceNumber:n.sequenceNumber,topicId:this.topicId}),r.id}catch(i){throw this.logger.error("Failed to submit HashLink to HCS",{error:i}),this.entries.delete(t),i}return this.logger.info("HashLink registered in directory",{id:t,name:e.name,assemblyTopicId:e.t_id,tags:e.tags}),t}async searchByTags(e){return(await this.listEntries()).map(e=>e.data).filter(t=>!(!t.tags||0===t.tags.length)&&e.some(e=>t.tags?.includes(e)))}async searchByName(e){const t=await this.listEntries(),r=e.toLowerCase();return t.map(e=>e.data).filter(e=>e.name.toLowerCase().includes(r)||(e.description?.toLowerCase().includes(r)??!1))}async getFeatured(){return(await this.listEntries()).map(e=>e.data).filter(e=>!0===e.featured)}async getByCategory(e){return(await this.listEntries()).map(e=>e.data).filter(t=>t.category===e)}async getCategories(){const e=await this.listEntries(),t=new Set;return e.forEach(e=>{const r=e.data;r.category&&t.add(r.category)}),Array.from(t).sort()}async getAllTags(){const e=await this.listEntries(),t=new Set;return e.forEach(e=>{const r=e.data;r.tags&&r.tags.forEach(e=>t.add(e))}),Array.from(t).sort()}validateRegistration(e){this.validateBaseRegistration(e);const t=Bg(e,Fg);if(!t.isValid)throw new Error(`HashLinks validation failed: ${t.errors.join(", ")}`);if(!e.t_id||!e.t_id.match(/^\d+\.\d+\.\d+$/))throw new Error("Valid assembly topic ID (t_id) is required");if(e.tags&&e.tags.length>10)throw new Error("Maximum 10 tags allowed");if(e.name.length>100)throw new Error("Name must be 100 characters or less");if(e.description&&e.description.length>500)throw new Error("Description must be 500 characters or less")}getStats(){const e=super.getStats(),t=Array.from(this.entries.values()),r=new Set,i=new Set;let n=0;return t.forEach(e=>{const t=e.data;t.category&&r.add(t.category),t.tags&&t.tags.forEach(e=>i.add(e)),t.featured&&n++}),{...e,categories:r.size,totalTags:i.size,featuredCount:n}}}class qg{constructor(e,t,r,i){this.cache=new Map,this.logger=e,this.assemblyRegistry=t,this.actionRegistry=r,this.blockLoader=i}async loadAssembly(e){this.logger.debug("Loading assembly",{topicId:e});const t=this.cache.get(e);if(t)return this.logger.debug("Assembly loaded from cache",{topicId:e}),t;try{const t=await this.assemblyRegistry.getAssemblyState(e);if(!t)throw new Error(`Assembly not found: ${e}`);const r={topicId:e,state:t,actions:[],blocks:[]};return this.cache.set(e,r),this.logger.debug("Assembly loaded successfully",{topicId:e,name:t.name,version:t.version,actionsCount:t.actions?.length||0,blocksCount:t.blocks?.length||0}),r}catch(r){throw this.logger.error("Failed to load assembly",{topicId:e,error:r}),new Error(`Failed to load assembly: ${r instanceof Error?r.message:"Unknown error"}`)}}async resolveReferences(e){this.logger.debug("Resolving assembly references",{name:e.name});const t={topicId:e.topicId,state:e,actions:[],blocks:[]};if(e.actions)for(const i of e.actions)try{const e=await this.resolveActionReference(i);t.actions.push({alias:i.alias,t_id:i.t_id,definition:e,config:i.config})}catch(r){this.logger.warn("Failed to resolve action reference",{t_id:i.t_id,alias:i.alias,error:r}),t.actions.push({alias:i.alias,t_id:i.t_id,definition:null,config:i.config,error:r instanceof Error?r.message:"Unknown error"})}if(e.blocks)for(const i of e.blocks)try{const{definition:e,template:r}=await this.resolveBlockReference(i);t.blocks.push({block_t_id:i.block_t_id,definition:e,template:r,attributes:i.attributes,actions:i.actions,children:i.children})}catch(r){this.logger.warn("Failed to resolve block reference",{block_t_id:i.block_t_id,error:r}),t.blocks.push({block_t_id:i.block_t_id,definition:null,attributes:i.attributes,actions:i.actions,children:i.children,error:r instanceof Error?r.message:"Unknown error"})}return t}validateComposition(e){const t=[];if(this.logger.debug("Validating assembly composition",{topicId:e.topicId}),e.state.name||t.push("Assembly must have a name"),e.state.version||t.push("Assembly must have a version"),e.state.blocks)for(const r of e.state.blocks){if(r.actions)for(const[i,n]of Object.entries(r.actions)){const o=e.state.actions?.some(e=>e.t_id===n);o||t.push(`Block ${r.block_t_id} references non-existent action: ${n} for key ${i}`)}if(r.children)for(const i of r.children){const n=e.state.blocks?.some(e=>e.block_t_id===i);n||t.push(`Block ${r.block_t_id} references non-existent child block: ${i}`)}}for(const r of e.actions)r.error&&t.push(`Action ${r.alias} has resolution error: ${r.error}`);for(const r of e.blocks)r.error&&t.push(`Block ${r.block_t_id} has resolution error: ${r.error}`);return{valid:0===t.length,errors:t}}async loadAndResolveAssembly(e){this.logger.debug("Loading and resolving assembly",{topicId:e});try{const t=await this.loadAssembly(e),r=await this.resolveReferences(t.state),i=this.validateComposition(r);return i.valid||this.logger.warn("Assembly validation failed",{topicId:e,errors:i.errors}),r}catch(t){throw this.logger.error("Failed to load and resolve assembly",{topicId:e,error:t}),new Error(`Failed to load and resolve assembly: ${t instanceof Error?t.message:"Unknown error"}`)}}async resolveActionReference(e){const t=await this.actionRegistry.getActionByTopicId(e.t_id);if(!t)throw new Error(`Action not found at topic: ${e.t_id}`);return t}async resolveBlockReference(e){return await this.blockLoader.loadBlock(e.block_t_id)}clearCache(){this.cache.clear(),this.logger.debug("Assembly cache cleared")}getCachedAssembly(e){return this.cache.get(e)}isAssemblyCached(e){return this.cache.has(e)}}class jg{constructor(e){this.network=e.network,this.logger=e.logger||y.getInstance({level:e.logLevel||"info",module:"HCS12-BaseClient",prettyPrint:e.prettyPrint,silent:e.silent}),this.mirrorNode=new x(e.network,this.logger,e.mirrorNode)}initializeRegistries(e){this.actionRegistryTopicId=e?.action,this._assemblyRegistryTopicId=e?.assembly,this._hashLinksRegistryTopicId=e?.hashlinks}async registerAssembly(e){if(!this._assemblyRegistry)throw new Error("Assembly registry not initialized");return{id:await this._assemblyRegistry.register(e)}}async getAction(e){if(!this._actionRegistry)throw new Error("Action registry not initialized");return this._actionRegistry.getAction(e)}async loadBlock(e){return this._blockLoader||(this._blockLoader=new Kg(this.network,this.logger,this)),this._blockLoader.loadBlock(e)}async getAssembly(e,t){if(!this._assemblyRegistry)throw new Error("Assembly registry not initialized");const r=await this._assemblyRegistry.listEntries();for(const i of r){const r=await this._assemblyRegistry.getAssemblyState(i.id);if(r&&r.name===e&&r.version===t)return r}return null}async loadAssembly(e){this._actionRegistry&&(this.logger.info("Syncing action registry before loading assembly"),await this._actionRegistry.sync());const t=new $g(this.network,this.logger,e,this);await t.sync();return new qg(this.logger,t,this._actionRegistry,this._blockLoader).loadAndResolveAssembly(e)}async getAssemblyState(e){if(!this._assemblyRegistry)throw new Error("Assembly registry not initialized");return this._assemblyRegistry.getAssemblyState(e)}ensureAssemblyEngine(){if(!this._assemblyEngine){if(!this._actionRegistry||!this._blockLoader||!this._assemblyRegistry)throw new Error("Registries must be initialized before assembly engine");this._assemblyEngine=new qg(this.logger,this._assemblyRegistry,this._actionRegistry,this._blockLoader)}}async registerHashLink(e){if(!this._hashLinksRegistry)throw new Error("HashLinks registry not initialized");return{id:await this._hashLinksRegistry.register(e)}}async searchHashLinksByTags(e){if(!this._hashLinksRegistry)throw new Error("HashLinks registry not initialized");return this._hashLinksRegistry.searchByTags(e)}async searchHashLinksByName(e){if(!this._hashLinksRegistry)throw new Error("HashLinks registry not initialized");return this._hashLinksRegistry.searchByName(e)}async getFeaturedHashLinks(){if(!this._hashLinksRegistry)throw new Error("HashLinks registry not initialized");return this._hashLinksRegistry.getFeatured()}async getHashLinksByCategory(e){if(!this._hashLinksRegistry)throw new Error("HashLinks registry not initialized");return this._hashLinksRegistry.getByCategory(e)}async syncRegistries(){const e=[];this._actionRegistry&&e.push(this._actionRegistry.sync()),this._assemblyRegistry&&e.push(this._assemblyRegistry.sync()),this._hashLinksRegistry&&e.push(this._hashLinksRegistry.sync()),await Promise.all(e)}getRegistryTopicIds(){return{action:this.actionRegistryTopicId,assembly:this._assemblyRegistryTopicId,hashlinks:this._hashLinksRegistryTopicId}}clearCaches(){this._actionRegistry?.clearCache(),this._blockLoader?.clearCache(),this._assemblyRegistry?.clearCache(),this._hashLinksRegistry?.clearCache()}get actionRegistry(){return this._actionRegistry}get blockLoader(){return this._blockLoader}get assemblyRegistry(){return this._assemblyRegistry}get hashLinksRegistry(){return this._hashLinksRegistry}}class Wg{constructor(){this.block={apiVersion:3},this.attributes={},this.supports={},this.actions={},this.logger=new y({module:"BlockBuilder"})}setName(e){return this.block.name=e,this}setTitle(e){return this.block.title=e,this}setDescription(e){return this.block.description=e,this}setCategory(e){return this.block.category=e,this}setIcon(e){return this.block.icon=e,this}setKeywords(e){return this.block.keywords=e,this}setApiVersion(e){return this.block.apiVersion=e,this}addAttribute(e,t,r,i){const n={type:t,default:r};return i?.enum&&(n.enum=i.enum),i?.source&&(n.source=i.source),i?.selector&&(n.selector=i.selector),i?.attribute&&(n.attribute=i.attribute),this.attributes[e]=n,this}setTemplateTopicId(e){return this.block.template_t_id=e,this}setTemplate(e){return this.templateBuffer=e,this}setActions(e){return this.actions=e,this}addAction(e,t){return this.actions[e]=t,this}addSupport(e,t=!0){return this.supports[e]=t,this}enableCommonSupports(){return this.supports={...this.supports,align:!0,anchor:!0,className:!0,spacing:{margin:!0,padding:!0}},this}build(){if(!this.block.name)throw new Error("Block name is required");if(!this.block.title)throw new Error("Block title is required");if(!this.block.category)throw new Error("Block category is required");if(!this.block.template_t_id)throw new Error("Block template_t_id is required");return{apiVersion:this.block.apiVersion||3,name:this.block.name,title:this.block.title,category:this.block.category,template_t_id:this.block.template_t_id,icon:this.block.icon,description:this.block.description,keywords:this.block.keywords,attributes:this.attributes,supports:this.supports}}static createDisplayBlock(e,t){return(new Wg).setName(e).setTitle(t).setCategory("formatting").enableCommonSupports()}static createInteractiveBlock(e,t){return(new Wg).setName(e).setTitle(t).setCategory("widgets").enableCommonSupports()}static createWidgetBlock(e,t){return this.createInteractiveBlock(e,t)}static createContainerBlock(e,t){return(new Wg).setName(e).setTitle(t).setCategory("design").enableCommonSupports().addSupport("html",!1)}getTemplate(){return this.templateBuffer}getActions(){return this.actions}setTopicId(e){return this.blockTopicId=e,this}getTopicId(){if(!this.blockTopicId)throw new Error("Block topic ID not set");return this.blockTopicId}getName(){return this.block.name}}class Vg{constructor(e,t){this.wasmCache=new Map,this.logger=e,this.network=t,this.hrlResolver=new Gp}async execute(e,t){try{if(this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Executing WASM action",{actionId:e.t_id,method:t.method,hasJavaScript:!!e.js_t_id}),e.js_t_id)return await this.executeJavaScript(e,t);throw new Error("Raw WASM execution is not supported for wasm-bindgen modules. JavaScript wrapper is required.")}catch(r){return this.logger&&"function"==typeof this.logger.error?this.logger.error("WASM execution failed",{actionId:e.t_id,error:r.message}):console.error("WASM execution failed",{actionId:e.t_id,error:r.message}),{success:!1,error:r.message}}}readWasmString(e,t){const r=new Uint8Array(e.buffer);let i=0;for(;0!==r[t+i];)i++;return(new TextDecoder).decode(r.slice(t,t+i))}async executeJavaScript(e,t){try{if(this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Loading JavaScript wrapper",{jsTopicId:e.js_t_id}),"undefined"==typeof window){this.logger&&"function"==typeof this.logger.info&&this.logger.info("Executing JavaScript wrapper in Node.js environment");const t=await this.hrlResolver.resolve(e.js_t_id,{network:this.network,returnRaw:!1});if(!t.content||"string"!=typeof t.content)throw new Error("Failed to load JavaScript module: invalid content");await this.hrlResolver.resolve(e.t_id,{network:this.network,returnRaw:!0}),global,globalThis,WebAssembly,console,queueMicrotask,TextDecoder,TextEncoder,void 0!==globalThis.FinalizationRegistry&&globalThis.FinalizationRegistry,URL;throw new Error("WASM execution in Node.js/SSR environment is not supported. This functionality is browser-only.")}{const r=await this.hrlResolver.resolve(e.js_t_id,{network:this.network,returnRaw:!1});if(!r.content||"string"!=typeof r.content)throw new Error("Failed to load JavaScript module: invalid content");const i=new Blob([r.content],{type:"application/javascript"}),n=URL.createObjectURL(i);try{this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Importing JavaScript module from blob URL");const r=new Function("url","return import(url)"),i=await r(n);if(this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Module imported, exports:",Object.keys(i)),!i.default&&!i.init)throw new Error("No init function found in JavaScript module");{const t=i.default||i.init;this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Loading WASM bytes from topic:",e.t_id);const r=await this.hrlResolver.resolve(e.t_id,{network:this.network,returnRaw:!0});if(this.logger&&"function"==typeof this.logger.debug){const e=r.content instanceof ArrayBuffer?r.content.byteLength:r.content.length;this.logger.debug("WASM bytes loaded, size:",e)}await t({module_or_path:r.content}),this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("WASM module initialized successfully")}const o=i.WasmInterface;if(!o)throw new Error("WasmInterface not found in module exports. Available exports: "+Object.keys(i).join(", "));this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Creating WasmInterface instance");const s=new o;let a,c;if("POST"===t.method&&s.POST){const e=t.params.operation||"default",r={...t.params,...t.state},i=JSON.stringify(r);this.logger&&"function"==typeof this.logger.debug?this.logger.debug("Calling POST method",{actionName:e,paramsJson:i,allParams:r}):console.log("WASM POST params:",{actionName:e,paramsJson:i,allParams:r}),a=await s.POST(e,i,this.network.toString(),"")}else if("GET"===t.method&&s.GET){const e=t.params.operation||"default",r=JSON.stringify(t.params);this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Calling GET method",{actionName:e,paramsJson:r}),a=await s.GET(e,r,this.network.toString())}else{if("INFO"!==t.method||!s.INFO)throw new Error(`Method ${t.method} not supported by WASM module`);this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Calling INFO method"),a=s.INFO()}try{c=JSON.parse(a)}catch{c={value:a}}return s.free&&s.free(),URL.revokeObjectURL(n),{success:!0,data:c}}catch(Pw){throw URL.revokeObjectURL(n),Pw}}}catch(r){const t=r instanceof Error?r.message:String(r),i=r instanceof Error?r.stack:void 0;return this.logger&&"function"==typeof this.logger.error?this.logger.error("JavaScript execution failed",{jsTopicId:e.js_t_id,error:t,stack:i,fullError:r}):console.error("JavaScript execution failed",{jsTopicId:e.js_t_id,error:t,stack:i,fullError:r}),{success:!1,error:t||"Unknown error"}}}clearCache(){this.wasmCache.clear()}}class Gg{constructor(e){this.logger=e}async scanTemplate(e){const t=[],r=/<([^>]+)\s+data-hashlink=["']([^"']+)["']([^>]*)>/gs;let i;for(;null!==(i=r.exec(e));){const e=i[0],r=i[1].split(/\s+/)[0],o=i[2],s=i[3];try{const i=this.parseHashLinkURI(o),n=s.match(/data-attributes=(['"])((?:(?!\1).)*)\1/s);let a;if(n)try{const e=n[2];a=JSON.parse(e)}catch(Pw){this.logger.warn("Failed to parse data-attributes",{uri:o,attributes:n[2],error:Pw.message})}const c=s.match(/data-actions=(['"])((?:(?!\1).)*)\1/s);let l;if(c)try{const e=c[2];l=JSON.parse(e)}catch(Pw){this.logger.warn("Failed to parse data-actions",{uri:o,actions:c[2],error:Pw.message})}const u=s.match(/data-loading=['"]([^'"]+)['"]/),d=u?.[1]||"eager";t.push({element:r,uri:o,...i,attributes:a,actions:l,loading:d,placeholder:e}),this.logger.debug("Found HashLink reference",{uri:o,parsed:i})}catch(n){this.logger.error("Failed to parse HashLink URI",{uri:o,error:n.message})}}return t}parseHashLinkURI(e){const t=e.match(/^hcs:\/\/(\d+)\/(.+)$/);if(!t)throw new Error(`Invalid HashLink URI format: ${e}`);const r=t[1],i=t[2];if("2"===r){const e=i.split("/");if(2!==e.length)throw new Error(`Invalid HCS-2 reference format: ${i}`);return{protocol:r,reference:i,registryId:e[0],entryName:e[1]}}return{protocol:r,reference:i}}createPlaceholder(e,t){return`\x3c!-- HASHLINK_PLACEHOLDER_${t}_${e.uri.replace(/[^a-zA-Z0-9]/g,"_")} --\x3e`}}class Jg{constructor(e,t,r,i){this.logger=e,this.blockLoader=t,this.hrlResolver=r,this.network=i,this.cache=new Map,this.renderStack=new Set}async resolveReference(e,t){this.logger.debug("Resolving HashLink reference",{uri:e.uri,protocol:e.protocol});try{switch(e.protocol){case"12":return await this.resolveHCS12Block(e,t);case"1":return await this.resolveHCS1Block(e,t);case"2":return await this.resolveHCS2Block(e,t);default:throw new Error(`Unsupported HashLink protocol: ${e.protocol}`)}}catch(r){return this.logger.error("Failed to resolve HashLink",{uri:e.uri,error:r.message}),{blockId:e.reference,definition:null,template:null,attributes:{},actions:{},error:r.message}}}async resolveHCS12Block(e,t){const r=e.reference;if(this.renderStack.has(r))return{blockId:r,definition:null,template:null,attributes:{},actions:{},error:"Circular reference detected"};const i=this.getCacheKey(r,e.attributes,e.actions);if(this.cache.has(i))return this.cache.get(i);try{const n=await this.blockLoader.loadBlock(r);if(!n||!n.definition)throw new Error(`Block not found: ${r}`);const o={...this.extractDefaults(n.definition),...t.attributes,...e.attributes},s={...t.actions,...e.actions},a={blockId:r,definition:n.definition,template:n.template,attributes:o,actions:s};return this.cache.set(i,a),a}catch(n){throw this.renderStack.delete(r),new Error(`Failed to load HCS-12 block ${r}: ${n.message}`)}}async resolveHCS1Block(e,t){const r=e.reference;try{const t=await this.blockLoader.loadBlock(r);if(t&&t.definition)return{blockId:r,definition:t.definition,template:t.template,attributes:{...this.extractDefaults(t.definition),...e.attributes},actions:e.actions||{}};return{blockId:r,definition:null,template:(await this.hrlResolver.resolve(r,{network:this.network})).content,attributes:e.attributes||{},actions:e.actions||{}}}catch(i){throw new Error(`Failed to load HCS-1 content ${r}: ${i.message}`)}}async resolveHCS2Block(e,t){if(!e.registryId||!e.entryName)throw new Error("Invalid HCS-2 reference: missing registry ID or entry name");try{const t=`hcs://2/${e.registryId}`;await this.hrlResolver.resolve(t,{network:this.network});return this.logger.warn("HCS-2 registry lookup not fully implemented",{registryId:e.registryId,entryName:e.entryName}),{blockId:`${e.registryId}/${e.entryName}`,definition:null,template:`\x3c!-- HCS-2 lookup not implemented: ${e.uri} --\x3e`,attributes:e.attributes||{},actions:e.actions||{}}}catch(r){throw new Error(`Failed to resolve HCS-2 entry: ${r.message}`)}}extractDefaults(e){const t={};return e.attributes&&Object.entries(e.attributes).forEach(([e,r])=>{r&&"object"==typeof r&&"default"in r&&(t[e]=r.default)}),t}getCacheKey(e,t,r){return`${e}:${t?JSON.stringify(t):""}:${r?JSON.stringify(r):""}`}pushRenderStack(e){this.renderStack.add(e)}popRenderStack(e){this.renderStack.delete(e)}clearCache(){this.cache.clear()}}const Yg={ACTIONS:{CALCULATOR:"0.0.TBD1",NFT_MINT:"0.0.TBD2",TOKEN_TRANSFER:"0.0.TBD3"},BLOCKS:{BUTTON:"0.0.TBD4",NFT_GALLERY:"0.0.TBD5",FORM:"0.0.TBD6"},ASSEMBLIES:{NFT_MARKETPLACE:"0.0.TBD7",TOKEN_DASHBOARD:"0.0.TBD8"}},Xg={ACTIONS:{},BLOCKS:{},ASSEMBLIES:{}};const Zg=/^[a-z0-9][a-z0-9-]*$/,Qg=t.z.object({registry:t.z.string().min(1),name:t.z.string().min(1),version:t.z.string().min(1),protocol:t.z.string().min(1),nativeId:t.z.string().min(1),skills:t.z.array(t.z.number().int().nonnegative())});function em(e){return e.trim()}function tm(e){return e.trim().toLowerCase()}function rm(e){const t=Qg.parse(e);if("hcs-10"===t.protocol.trim().toLowerCase()&&!dh(t.nativeId.trim()))throw new Error("HCS-14: For protocol hcs-10, nativeId must be CAIP-10 (hedera:<network>:<account>)");if("acp-virtuals"===t.protocol.trim().toLowerCase()&&!mh(t.nativeId.trim()))throw new Error("HCS-14: For protocol acp-virtuals, nativeId must be EIP-155 CAIP-10 (eip155:<chainId>:<address>)");const r={registry:tm(t.registry),name:em(t.name),version:em(t.version),protocol:tm(t.protocol),nativeId:em(t.nativeId),skills:[...t.skills].sort((e,t)=>e-t)},i=["skills","name","nativeId","protocol","registry","version"],n={};for(const o of i)n[o]=r[o];return{normalized:r,canonicalJson:JSON.stringify(n)}}const im="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function nm(e){if(0===e.length)return"";let t=0;for(;t<e.length&&0===e[t];)t++;if(t===e.length)return"1".repeat(t);const r=[0];for(let n=t;n<e.length;n++){let t=e[n];for(let e=0;e<r.length;e++){const i=(r[e]<<8)+t;r[e]=i%58,t=i/58|0}for(;t>0;)r.push(t%58),t=t/58|0}let i="";for(let n=0;n<t;n++)i+="1";for(let n=r.length-1;n>=0;n--)i+=im[r[n]];return i}function om(e){if(!e.startsWith("z"))throw new Error("Invalid multibase base58btc");return function(e){if(0===e.length)return new Uint8Array(0);let t=0;for(;t<e.length&&"1"===e[t];)t++;const r=[];for(let i=t;i<e.length;i++){const t=e[i],n=im.indexOf(t);if(-1===n)throw new Error("Invalid Base58 character");let o=n;for(let e=0;e<r.length;e++){const t=58*r[e]+o;r[e]=255&t,o=t>>8}for(;o>0;)r.push(255&o),o>>=8}for(let i=0;i<t;i++)r.push(0);return r.reverse(),Uint8Array.from(r)}(e.slice(1))}function sm(e){const t=[];return e.uid&&t.push(["uid",e.uid]),e.registry&&t.push(["registry",e.registry]),e.proto&&t.push(["proto",e.proto]),e.nativeId&&t.push(["nativeId",e.nativeId]),e.domain&&t.push(["domain",e.domain]),e.src&&t.push(["src",e.src]),0===t.length?"":t.map(([e,t])=>`${e}=${t}`).join(";")}function am(e,t){let r,i;if(e.startsWith("uaid:aid:"))r="aid",i=e.slice(9);else{if(!e.startsWith("did:"))throw new Error("Invalid DID format");{const t=e.indexOf(":"),n=e.indexOf(":",t+1);if(n<0)throw new Error("Invalid DID format");r=e.slice(t+1,n),i=e.slice(n+1)}}const{sanitized:n,hadSuffix:o}=function(e){const t=e.search(/[;?#]/);return-1===t?{sanitized:e,hadSuffix:!1}:{sanitized:e.slice(0,t),hadSuffix:!0}}(i);let s=n;if("hedera"===r){const e=n.match(/^(mainnet|testnet|previewnet|devnet):(.+)$/);e&&(s=e[2])}const a={...t||{}};var c;o&&!a.src&&(a.src=(c=e,"z"+nm(globalThis.Buffer.from(c,"utf8"))));const l=sm(a);return l?`uaid:did:${s};${l}`:`uaid:did:${s}`}function cm(e,t,r){return"string"==typeof e?am(e,t):async function(e,t,r){const{normalized:i,canonicalJson:n}=rm(e),o=sh().createHash("sha384").update(globalThis.Buffer.from(n,"utf8")).digest(),s=await Promise.resolve(o),a=nm(globalThis.Buffer.isBuffer(s)?s:globalThis.Buffer.from(s)),c=!1!==r?.includeParams,l=c?function(e,t){const r={...t};return r.registry||(r.registry=e.registry),r.nativeId||(r.nativeId=e.nativeId),r.uid||(r.uid="0"),r}(i,t||{}):{},u=c?sm(l):"";return u?`uaid:aid:${a};${u}`:`uaid:aid:${a}`}(e,t,r)}function lm(e){if(e.startsWith("uaid:")){const t=e.slice(5);let r,i;if(t.startsWith("did:"))r="did",i=t.slice(4);else{if(!t.startsWith("aid:"))throw new Error("Invalid UAID");r="aid",i=t.slice(4)}const n=i.indexOf(";"),o=n>=0?i.slice(0,n):i,s=(e=>{const t={};if(!e)return t;const r=e.split(";");for(const i of r){const e=i.indexOf("=");if(e>0){const r=i.slice(0,e),n=i.slice(e+1);t[r]=n}}return t})(n>=0?i.slice(n+1):"");return{method:"did"===r?"uaid":"aid",id:o,params:s}}throw new Error("Invalid DID")}function um(e){return"object"==typeof e&&null!==e}function dm(e){if(!um(e))return;const t=e.adapterKind;return"did-resolver"===t||"did-profile-resolver"===t||"uaid-profile-resolver"===t?t:void 0}function pm(e){return um(e)&&"profile"in e&&"string"==typeof e.profile}function hm(e){const t=dm(e);return void 0!==t?"uaid-profile-resolver"===t:pm(e)&&um(e)&&"resolveProfile"in e&&"function"==typeof e.resolveProfile&&function(e){return!!um(e)&&"supports"in e&&"function"==typeof e.supports}(e)}function gm(e){const t=dm(e);return void 0!==t?"did-profile-resolver"===t:um(e)&&"resolveProfile"in e&&"function"==typeof e.resolveProfile&&!pm(e)}function mm(e){const t=dm(e);return void 0!==t?"did-resolver"===t:um(e)&&"resolve"in e&&"function"==typeof e.resolve}const fm=["@hiero-did-sdk","resolver"].join("/");let ym=null;class bm{constructor(){this.adapterKind="did-resolver",this.meta={id:"hedera/hiero-resolver",didMethods:["hedera"],caip2Networks:["hedera:mainnet","hedera:testnet","hedera:previewnet","hedera:devnet"],caip10Namespaces:["hedera"],displayName:"Hedera (Hiero Resolver)",description:"Resolves did:hedera identifiers via Hiero DID resolver.",homepage:"https://github.com/hiero-ledger/hiero-did-sdk-js"}}supports(e){return e.startsWith("did:hedera:")}async resolve(e){const t=await async function(){return ym||(ym=Ta(fm).then(e=>e?.resolveDID??null)),ym}();if(!t)throw new Error("Hiero resolver unavailable. Ensure @hiero-did-sdk/resolver is installed.");const r=await t(e);return r&&"string"==typeof r.id?{id:r.id}:null}}class wm{constructor(){this.resolvers=[],this.profileResolvers=[],this.uaidProfileResolvers=[],this.adapters=[]}supportsDidMethod(e,t){return!!e&&(e.includes(t)||e.includes("*"))}addDidResolver(e){this.resolvers.push(e),this.adapters.push({capability:"did-resolver",adapter:e})}addDidProfileResolver(e){this.profileResolvers.push(e),this.adapters.push({capability:"did-profile-resolver",adapter:e})}addUaidProfileResolver(e){this.uaidProfileResolvers.push(e),this.adapters.push({capability:"uaid-profile-resolver",adapter:e})}registerAdapter(e){const t=hm(e),r=gm(e),i=mm(e);if([t,r,i].filter(Boolean).length>1)throw new Error("Adapter matches multiple resolver capabilities. Split it into single-capability adapters, or use register/registerProfileResolver/registerUaidProfileResolver to explicitly select one capability.");if(t)this.addUaidProfileResolver(e);else if(r)this.addDidProfileResolver(e);else{if(!i)throw new Error("Adapter does not match a supported resolver capability.");this.addDidResolver(e)}}listAdapters(){return[...this.adapters]}filterAdapters(e={}){if(void 0!==e.profileId&&void 0!==e.capability&&"uaid-profile-resolver"!==e.capability)throw new Error('profileId filter requires capability "uaid-profile-resolver".');const t=e.capability??(void 0!==e.profileId?"uaid-profile-resolver":void 0);return this.adapters.filter(r=>{if(void 0!==t&&r.capability!==t)return!1;if(void 0!==e.didMethod&&!this.supportsDidMethod(r.adapter.meta?.didMethods,e.didMethod))return!1;if(void 0!==e.profileId){if("uaid-profile-resolver"!==r.capability)return!1;if(r.adapter.profile!==e.profileId)return!1}return!0})}register(e){this.addDidResolver(e)}registerProfileResolver(e){this.addDidProfileResolver(e)}registerUaidProfileResolver(e){this.addUaidProfileResolver(e)}list(){return[...this.resolvers]}listProfileResolvers(){return[...this.profileResolvers]}listUaidProfileResolvers(){return[...this.uaidProfileResolvers]}filterByDidMethod(e){return this.resolvers.filter(t=>this.supportsDidMethod(t.meta?.didMethods,e))}filterProfileResolversByDidMethod(e){return this.profileResolvers.filter(t=>this.supportsDidMethod(t.meta?.didMethods,e))}filterUaidProfileResolversByDidMethod(e){return this.uaidProfileResolvers.filter(t=>this.supportsDidMethod(t.meta?.didMethods,e))}filterUaidProfileResolversByProfileId(e){return this.uaidProfileResolvers.filter(t=>t.profile===e)}async resolveDid(e){for(const t of this.resolvers)if(t.supports(e))return t.resolve(e);return null}deriveDidFromParsedUaid(e){if("aid"===e.method){const t=e.params.proto,r=e.params.nativeId;if("hcs-10"===t&&r){const e=r.match(/^hedera:(mainnet|testnet|previewnet|devnet):(.+)$/);if(e){return`did:hedera:${e[1]}:${e[2]}`}}return null}const t=e.params.src;if(t)try{return globalThis.Buffer.from(om(t)).toString("utf8")}catch{return null}const r=e.id;if(r.startsWith("testnet:")||r.startsWith("mainnet:")||r.startsWith("previewnet:")||r.startsWith("devnet:"))return`did:hedera:${r}`;const i=e.params.proto,n=e.params.nativeId;if("hcs-10"===i&&n){const e=n.match(/^hedera:(mainnet|testnet|previewnet|devnet):/);if(e){return`did:hedera:${e[1]}:${r}`}}return null}buildFallbackProfile(e,t={}){const r=t.uaid??e,i=t.didDocument??null,n=new Set;r!==e&&n.add(e);for(const o of i?.alsoKnownAs??[])n.add(o);return{id:r,did:e,verificationMethod:i?.verificationMethod,authentication:i?.authentication,assertionMethod:i?.assertionMethod,service:i?.service,alsoKnownAs:n.size>0?[...n]:void 0}}mergeResolvedProfile(e,t){const r=new Set([...e.alsoKnownAs??[],...t.alsoKnownAs??[]]);return{...e,...t,id:t.id||e.id,did:t.did??e.did,verificationMethod:t.verificationMethod??e.verificationMethod,authentication:t.authentication??e.authentication,assertionMethod:t.assertionMethod??e.assertionMethod,service:t.service??e.service,profiles:t.profiles??e.profiles,metadata:t.metadata??e.metadata,error:t.error??e.error,alsoKnownAs:r.size>0?[...r]:void 0}}async resolveDidProfile(e,t={}){const r=t.didDocument??await this.resolveDid(e),i={...t,didDocument:r},n=this.buildFallbackProfile(e,i);for(const o of this.profileResolvers){if(!o.supports(e))continue;const t=await o.resolveProfile(e,i);if(t)return this.mergeResolvedProfile(n,t)}return n}async resolveUaidProfileByIdInternal(e,t,r){const i=lm(t);return this.resolveUaidProfileInternal(t,i,{profileId:e,excludeProfileId:r.excludeProfileId})}async resolveUaidProfileInternal(e,t,r={}){const i=this.deriveDidFromParsedUaid(t),n=i?await this.resolveDid(i):null,o=i?this.buildFallbackProfile(i,{uaid:e,parsedUaid:t,didDocument:n}):{id:e},s=void 0!==r.profileId?this.uaidProfileResolvers.filter(e=>e.profile===r.profileId):this.uaidProfileResolvers;for(const a of s){if(void 0!==r.excludeProfileId&&a.profile===r.excludeProfileId)continue;const s=a.supports(e,t);if(void 0===r.profileId&&!s)continue;const c={parsedUaid:t,did:i,didDocument:n,resolveDid:async e=>this.resolveDid(e),resolveDidProfile:async(e,t)=>this.resolveDidProfile(e,t),resolveUaidProfileById:async(e,t)=>this.resolveUaidProfileByIdInternal(e,t,{excludeProfileId:a.profile})},l=await a.resolveProfile(e,c);if(!l)continue;if(void 0!==l.error||!1===l.metadata?.resolved){if(void 0===r.profileId)continue;return l}return this.mergeResolvedProfile(o,l)}return null}async resolveUaid(e){const t=lm(e),r=this.deriveDidFromParsedUaid(t);return r?this.resolveDid(r):null}async resolveUaidProfile(e,t={}){const r=lm(e),i=await this.resolveUaidProfileInternal(e,r,{profileId:t.profileId});if(i)return i;if(void 0!==t.profileId)return null;const n=this.deriveDidFromParsedUaid(r);if(!n)return"aid"===r.method?{id:e}:null;const o=await this.resolveDid(n);return this.resolveDidProfile(n,{uaid:e,parsedUaid:r,didDocument:o})}}const Im=new wm;function Tm(){Im.registerAdapter(new bm)}function Sm(e){return"mainnet"===e||"testnet"===e?e:null}function km(e,t){const r=t?.parsedUaid?.params.nativeId;if(r){const e=function(e){try{const t=hh(e),r=Sm(t.network);return r?{network:r,accountId:t.accountId}:null}catch(t){return null}}(r);if(e)return e}const i=e.match(/^did:hedera:(mainnet|testnet):(.+)$/);if(!i)return null;const n=Sm(i[1]);return n?{network:n,accountId:i[2]}:null}class vm{constructor(){this.adapterKind="did-profile-resolver",this.meta={id:"hedera/hcs11-profile-resolver",didMethods:["hedera"],caip2Networks:["hedera:mainnet","hedera:testnet"],caip10Namespaces:["hedera"],displayName:"Hedera (HCS-11 Profile Resolver)",description:"Resolves HCS-11 protocol profiles and HCS-10 service metadata for did:hedera identifiers."}}supports(e){return/^did:hedera:(mainnet|testnet):/.test(e)}async resolveProfile(e,t){const r=km(e,t);if(!r)return null;const{network:i,accountId:n}=r,o=new $h({network:i,auth:{operatorId:n},silent:!0}),s=await o.fetchProfileByAccountId(n,i);if(!s.success||!s.profile)return null;const a=t?.uaid??e,c=t?.didDocument?.service??[],l=function(e,t,r,i){return i?{id:`${e}#hcs10`,type:"HCS10Service",serviceEndpoint:{network:t,accountId:r,inboundTopicId:i.inboundTopic||void 0,outboundTopicId:i.outboundTopic||void 0,profileTopicId:i.profileTopicId||void 0}}:null}(a,i,n,s.topicInfo),u=l?[...c,l]:c;return{id:a,did:e,service:u.length>0?u:void 0,profiles:{hcs11:{protocol:"hcs-11",network:i,accountId:n,profile:s.profile,topicInfo:s.topicInfo}}}}}let Em=null;const Am=async e=>{const t=await async function(){return Em||(Em=(async()=>{const e=await Ta("node:dns/promises",{preferImport:!0});if(e?.resolveTxt)return e.resolveTxt;const t=await Ta("dns/promises",{preferImport:!0});return t?.resolveTxt??null})()),Em}();if(!t)return[];try{return(await t(e)).map(e=>e.join(""))}catch(r){if(function(e){if(!e||"object"!=typeof e)return!1;const t=Reflect.get(e,"code");return"string"==typeof t&&("ENOTFOUND"===t||"ENODATA"===t||"ENOENT"===t||"ENONAME"===t||"NXDOMAIN"===t)}(r))return[];throw r}},Cm=["uid","registry","proto","nativeId","domain","src"],Rm=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;function xm(e){return"aid"===e.method?"aid":"did"}function Nm(e){return e.trim().replace(/\.$/,"").toLowerCase()}function zm(e){const t=Nm(e);if(!t||t.length>253||!t.includes("."))return!1;const r=t.split(".");for(const i of r)if(!i||i.length>63||!Rm.test(i))return!1;return!0}function _m(e){const t=e.trim();if(t.length>=2&&t.startsWith('"')&&t.endsWith('"'))return t.slice(1,-1);const r=t.match(/^\[(.+)\]\((.+)\)$/);return r?r[2].trim():t}function Pm(e){const t={};for(const r of e.split(";")){const e=r.trim();if(!e)continue;const i=e.indexOf("=");if(i<=0)continue;const n=e.slice(0,i).trim(),o=_m(e.slice(i+1));n&&o&&(t[n]=o)}return t}function Om(e,t,r){const i=[],n=new Set;for(const s of Cm){const e=r[s];e&&(i.push(`${s}=${e}`),n.add(s))}const o=Object.keys(r).filter(e=>!n.has(e)&&r[e]).sort((e,t)=>e.localeCompare(t));for(const s of o)i.push(`${s}=${r[s]}`);return i.length>0?`uaid:${e}:${t};${i.join(";")}`:`uaid:${e}:${t}`}const Dm="hcs-14.profile.aid-dns-web";function Fm(e,t,r,i){return{id:e,error:{code:t,message:r,details:i},metadata:{profile:Dm,resolved:!1}}}function Mm(e){return`${e.protocol}|${e.endpoint}|${e.publicKey??""}|${e.keyId??""}`}function Um(e){return"cryptographic"===e?"aid-pka":"metadata"===e?"metadata-match":void 0}class Bm{constructor(e={}){this.adapterKind="uaid-profile-resolver",this.profile=Dm,this.meta={id:"hcs-14/aid-dns-web",didMethods:["*"],displayName:"HCS-14 AID DNS/Web Profile",description:"Resolves uaid:aid identifiers via _agent.<nativeId> DNS TXT records and protocol endpoint hints."},this.dnsLookup=e.dnsLookup??Am,this.supportedSchemes=new Set((e.supportedUriSchemes??["https","http","wss","ws"]).map(e=>e.toLowerCase())),this.metadataVerifier=e.metadataVerifier,this.cryptographicVerifier=e.cryptographicVerifier}supports(e,t){if("aid"!==t.method)return!1;const r=t.params.nativeId;return!!r&&zm(r)}async resolveProfile(e,t){const r=t.parsedUaid;if("aid"!==r.method)return Fm(e,"ERR_NOT_APPLICABLE","AID DNS/Web profile only applies to uaid:aid identifiers.");const i=r.params.nativeId;if(!i||!zm(i))return Fm(e,"ERR_NOT_APPLICABLE","AID DNS/Web profile requires an FQDN nativeId.");const n=`_agent.${Nm(i)}`,o=await this.dnsLookup(n);if(0===o.length)return Fm(e,"ERR_NO_DNS_RECORD","No AID DNS TXT record was found for the requested nativeId.",{dnsName:n});const s=o.map(e=>function(e,t){const r=Pm(e),i=r.v,n=r.p??r.proto,o=r.u;if(!i||!n||!o)return{code:"ERR_INVALID_AID_RECORD"};if(!i.toLowerCase().startsWith("aid"))return{code:"ERR_INVALID_AID_RECORD"};let s;try{s=new URL(o)}catch{return{code:"ERR_ENDPOINT_INVALID"}}const a=s.protocol.replace(/:$/,"").toLowerCase();return t.has(a)?{record:{version:i,protocol:n,endpoint:s.toString(),publicKey:r.k,keyId:r.i}}:{code:"ERR_ENDPOINT_INVALID"}}(e,this.supportedSchemes)),a=s.filter(e=>"record"in e).map(e=>e.record);if(0===a.length){const t=s.some(e=>!("record"in e)&&"ERR_ENDPOINT_INVALID"===e.code);return Fm(e,t?"ERR_ENDPOINT_INVALID":"ERR_INVALID_AID_RECORD",t?"AID DNS record endpoint URI is invalid or unsupported.":"AID DNS TXT payload is malformed or unsupported.",{dnsName:n})}const c=[...a].sort((e,t)=>Mm(e).localeCompare(Mm(t)))[0],l={uaid:e,protocol:c.protocol,endpoint:c.endpoint,record:c};let u="none";if(this.metadataVerifier){if(!(await this.metadataVerifier(l)))return Fm(e,"ERR_VERIFICATION_FAILED","AID metadata verification failed.",{dnsName:n});u="metadata"}if(c.publicKey&&this.cryptographicVerifier){if(!(await this.cryptographicVerifier(l)))return Fm(e,"ERR_VERIFICATION_FAILED","AID cryptographic verification failed.",{dnsName:n});u="cryptographic"}const d=t.did??void 0;return{id:e,did:d,alsoKnownAs:d?[d]:void 0,service:[{id:`${e}#aid-endpoint`,type:"AIDService",serviceEndpoint:c.endpoint}],metadata:{profile:Dm,resolved:!0,endpoint:c.endpoint,protocol:c.protocol,verification:{level:u,method:Um(u)},verificationLevel:u,precedenceSource:"dns"}}}}function Lm(e){return"object"==typeof e&&null!==e}function Km(e){if("string"!=typeof e)return null;const t=e.trim();return t||null}function $m(e){const t=e.trim();if(!t)return null;const r=t.startsWith("v")||t.startsWith("V")?t.slice(1):t;return function(e){return/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.test(e)}(r)?r:null}function Hm(e){if(!Lm(e))return;const t=function(e){if(!Lm(e))return;const t=Km(e.checkpoint_topic_id),r=Km(e.registry),i=Km(e.log_id);if(!t||!r||!i||"ans"!==r)return;return{checkpointTopicId:t,registry:r,logId:i,checkpointUri:Km(e.checkpoint_uri)??void 0,viewerUri:Km(e.viewer_uri)??void 0}}(e.hcs27),r=function(e){if(!Lm(e))return;const t=Km(e.directory_topic_id),r=Km(e.t_id),i=Km(e.agent_id);if(!t||!r||!i)return;return{directoryTopicId:t,tId:r,agentId:i,proofProfile:Km(e.proof_profile)??void 0}}(e.hcs28);return t||r?{hcs27:t,hcs28:r}:void 0}function qm(e){return e instanceof Error&&e.message?e.message:null}const jm="hcs-14.profile.ans-dns-web";function Wm(e,t,r,i){return{id:e,error:{code:t,message:r,details:i},metadata:{profile:jm,resolved:!1}}}async function Vm(e){if("function"!=typeof globalThis.fetch)throw new Error("Fetch API is unavailable in this runtime.");const t=await globalThis.fetch(e,{method:"GET",headers:{accept:"application/json"}});if(!t.ok)throw new Error(`Agent Card request failed with status ${t.status}.`);return t.json()}function Gm(e){return!e||"0"===e}class Jm{constructor(e={}){this.adapterKind="uaid-profile-resolver",this.profile=jm,this.meta={id:"hcs-14/ans-dns-web",didMethods:["*"],displayName:"HCS-14 ANS DNS/Web Profile",description:"Resolves ANS uaid:aid identifiers via _ans.<nativeId> TXT records and Agent Card endpoint selection."},this.dnsLookup=e.dnsLookup??Am,this.fetchJson=e.fetchJson??Vm,this.supportedSchemes=new Set((e.supportedUriSchemes??["https","wss"]).map(e=>e.toLowerCase())),this.transparencyVerifier=e.transparencyVerifier}supports(e,t){if("aid"!==t.method)return!1;if("ans"!==t.params.registry)return!1;const r=t.params.nativeId;return!!r&&zm(r)}async resolveProfile(e,t){const r=t.parsedUaid;if("aid"!==r.method)return Wm(e,"ERR_NOT_APPLICABLE","ANS profile only applies to uaid:aid identifiers.");if("ans"!==r.params.registry)return Wm(e,"ERR_NOT_APPLICABLE","ANS profile requires registry=ans.");const i=r.params.nativeId;if(!i||!zm(i))return Wm(e,"ERR_NOT_APPLICABLE","ANS profile requires an FQDN nativeId.");const n=r.params.uid;if(Gm(n))return Wm(e,"ERR_NOT_APPLICABLE","ANS profile requires a non-zero uid parameter.");const o=r.params.proto;if(Gm(o))return Wm(e,"ERR_PROTOCOL_UNSPECIFIED","ANS profile requires a usable proto parameter.");const s=r.params.version,a=void 0===s?void 0:$m(s);if(void 0!==s&&(!(c=s)||null===$m(c)))return Wm(e,"ERR_NOT_APPLICABLE","ANS profile requires a valid semver version parameter when provided.");var c;const l=Nm(i),u=`_ans.${l}`,d=await this.dnsLookup(u);if(0===d.length)return Wm(e,"ERR_NO_DNS_RECORD","No ANS DNS TXT record was found for the requested nativeId.",{dnsName:u});const p=d.map(e=>function(e){const t=Pm(e),r=t.v,i=t.url;if(!r||!i||"ans1"!==r.toLowerCase())return null;let n;try{n=new URL(i)}catch{return null}if("https:"!==n.protocol.toLowerCase())return null;const o=t.version;let s;if(void 0!==o){const e=$m(o);if(!e)return null;s=e}return{version:s,url:n.toString()}}(e)).filter(e=>null!==e);if(0===p.length)return Wm(e,"ERR_INVALID_ANS_RECORD","ANS DNS TXT payload is malformed or unsupported.",{dnsName:u});let h=p;if(a){const t=p.filter(e=>void 0!==e.version);if(0===t.length)return Wm(e,"ERR_VERSION_MISMATCH","UAID specifies a version but no ANS DNS TXT record carries a version field.",{dnsName:u,uaidVersion:a});if(h=t.filter(e=>e.version===a),0===h.length)return Wm(e,"ERR_VERSION_MISMATCH","UAID version does not match ANS DNS TXT record version.",{dnsName:u,uaidVersion:a})}const g=(m=h,[...m].sort((e,t)=>e.url.localeCompare(t.url))[0]);var m;let f;try{f=await this.fetchJson(g.url)}catch(A){return Wm(e,"ERR_AGENT_CARD_INVALID","Agent Card retrieval failed.",{stage:"fetch",agentCardUrl:g.url,reason:qm(A)})}const y=function(e){if(!Lm(e))return null;const t=Km(e.ansName),r=e.endpoints;return t&&Lm(r)?{ansName:t,endpoints:r,transparencyHints:Hm(e.transparency)}:null}(f);if(!y)return Wm(e,"ERR_AGENT_CARD_INVALID","Agent Card is missing required fields.",{stage:"validate",agentCardUrl:g.url});if(y.ansName!==n)return Wm(e,"ERR_AGENT_CARD_INVALID","Agent Card ansName does not match UAID uid.",{stage:"validate",expectedUid:n,actualAnsName:y.ansName});const b=function(e,t){const r=[];for(const[i,n]of Object.entries(e)){if(!Lm(n))continue;const e=Km(n.url);if(!e)continue;let o;try{o=new URL(e)}catch{continue}const s=o.protocol.replace(/:$/,"").toLowerCase();t.has(s)&&r.push({key:i,endpointUrl:o.toString(),parsedUrl:o})}return r}(y.endpoints,this.supportedSchemes),w=b.filter(e=>Nm(e.parsedUrl.hostname)===l);if(0===w.length)return Wm(e,"ERR_ENDPOINT_NOT_ANCHORED","No endpoint URL is anchored to the UAID nativeId host.",{nativeId:l});const I=function(e,t){if(0===e.length)return null;const r=[...e].sort((e,t)=>e.key.localeCompare(t.key)),i=r.filter(e=>function(e,t){const r=t.trim().toLowerCase();if(!r)return!1;const i=e.split("/").map(e=>e.trim()).filter(e=>e.length>0);for(const n of i)if(n.toLowerCase()===r)return!0;return!1}(e.parsedUrl.pathname,t));return i.length>0?i[0]:r[0]}(w,o)??w[0];let T=!1,S=!1;if(this.transparencyVerifier&&(T=!0,S=await this.transparencyVerifier({uaid:e,protocol:o,endpoint:I.endpointUrl,agentCardUrl:g.url,transparencyHints:y.transparencyHints}),!S))return Wm(e,"ERR_TRANSPARENCY_VERIFICATION_FAILED","Transparency verification failed.",{agentCardUrl:g.url});const k=t.did??void 0,v=S?"cryptographic":"metadata",E=S?"ans-transparency":"metadata-match";return{id:e,did:k,alsoKnownAs:k?[k]:void 0,service:[{id:`${e}#ans-endpoint`,type:"ANSService",serviceEndpoint:I.endpointUrl}],metadata:{profile:jm,resolved:!0,endpoint:I.endpointUrl,protocol:o,precedenceSource:"dns",verification:{level:v,method:E},verificationLevel:v,agentCardUrl:g.url,dnsRecordSelection:"lexicographically-smallest-url",transparencyHints:y.transparencyHints,transparencyVerification:{attempted:T,succeeded:S}}}}}const Ym="hcs-14.profile.uaid-did-resolution";function Xm(e,t,r,i){return{id:e,error:{code:t,message:r,details:i},metadata:{profile:Ym,resolved:!1}}}function Zm(e,t=[]){return[...new Set([e,...t])]}class Qm{constructor(){this.adapterKind="uaid-profile-resolver",this.profile=Ym,this.meta={id:"hcs-14/uaid-did-resolution",didMethods:["*"],displayName:"HCS-14 UAID DID Resolution Profile",description:"Resolves uaid:did identifiers to DID Document-compatible output with profile metadata."}}supports(e,t){return"uaid"===t.method}async resolveProfile(e,t){const r=t.parsedUaid;if("uaid"!==r.method)return Xm(e,"ERR_INVALID_UAID","Identifier is not uaid:did and cannot be resolved by this profile.",{uaid:e});const i=r.params.src,n=i?function(e){try{const t=om(e);return globalThis.Buffer.from(t).toString("utf8").trim()||null}catch{return null}}(i):null,o=n??t.did??null;if(!o)return Xm(e,"ERR_BASE_DID_UNDETERMINED","Unable to determine base DID; provide src parameter or configure method inference.",{uaid:e});const s=t.didDocument&&t.didDocument.id===o?t.didDocument:await t.resolveDid(o);if(!s)return Xm(e,"ERR_DID_RESOLUTION_FAILED","Base DID resolution failed.",{uaid:e,baseDid:o});if(!s.id||"string"!=typeof s.id)return Xm(e,"ERR_DID_DOCUMENT_INVALID","Resolved DID document is malformed.",{uaid:e,baseDid:o});const a=s.service??[],c=function(e,t){const r=t.proto,i=t.nativeId,n=t.domain;return r||i||n?{id:`${e}#hcs14-hinted-service-1`,type:"HintedService",serviceEndpoint:{source:"uaid-parameters",proto:r,nativeId:i,domain:n}}:null}(e,r.params),l=0===a.length&&null!==c,u=l?[...a,c]:a;return{id:e,did:o,alsoKnownAs:Zm(o,s.alsoKnownAs),verificationMethod:s.verificationMethod,authentication:s.authentication,assertionMethod:s.assertionMethod,service:u.length>0?u:void 0,metadata:{profile:Ym,resolved:!0,baseDid:o,baseDidResolved:!0,verification:{method:"did-resolution",assurance:"base-method",details:"Validated according to base DID method rules"},services:{copiedFromBaseDidDocument:a.length>0,derivedFromUaidParameters:l}}}}}const ef="hcs-14.profile.uaid-dns-web";function tf(e,t,r,i){return{id:e,error:{code:t,message:r,details:i},metadata:{profile:ef,resolved:!1}}}function rf(e){const t={...e},r=t.nativeId;r&&zm(r)&&(t.nativeId=Nm(r));const i=t.domain;return i&&zm(i)&&(t.domain=Nm(i)),t}class nf{constructor(e={}){this.adapterKind="uaid-profile-resolver",this.profile=ef,this.meta={id:"hcs-14/uaid-dns-web",didMethods:["*"],displayName:"HCS-14 UAID DNS TXT Profile",description:"Binds UAIDs to DNS TXT records at _uaid.<nativeId> and can continue to follow-up profile resolution."},this.dnsLookup=e.dnsLookup??Am,this.dnssecValidation=e.dnssecValidation,this.requireFullResolution=e.requireFullResolution??!1,this.enableFollowupResolution=e.enableFollowupResolution??!0}supports(e,t){const r=xm(t);if("aid"!==r&&"did"!==r)return!1;const i=t.params.nativeId;return!!i&&zm(i)}async resolveProfile(e,t){const r=t.parsedUaid,i=xm(r);if("aid"!==i&&"did"!==i)return tf(e,"ERR_NOT_APPLICABLE","UAID DNS/Web profile only applies to uaid:aid or uaid:did identifiers.");const n=r.params.nativeId;if(!n||!zm(n))return tf(e,"ERR_NOT_APPLICABLE","UAID DNS/Web profile requires an FQDN nativeId.");const o=Nm(n),s=`_uaid.${o}`,a=Om(xm(r),r.id,rf(r.params)),c=await this.dnsLookup(s);if(0===c.length)return tf(e,"ERR_NO_DNS_RECORD","No UAID DNS TXT record was found for the requested nativeId.",{dnsName:s});const l=c.map(e=>Pm(e)).map(e=>function(e,t){const r=e.target,i=e.id,n=e.uid,o=e.proto,s=e.nativeId;if("aid"!==r&&"did"!==r)return null;if(!(i&&n&&o&&s))return null;if(Nm(s)!==t)return null;if("registry"in e&&!e.registry)return null;const a=e.did;if(a&&("did"!==r||!a.startsWith("did:")))return null;const c={uid:n,proto:o,nativeId:s};return e.registry&&(c.registry=e.registry),e.domain&&(c.domain=e.domain),e.src&&(c.src=e.src),{target:r,id:i,uid:n,proto:o,nativeId:s,registry:e.registry,domain:e.domain,src:e.src,did:a,memo:e.m,reconstructedUaid:Om(r,i,rf(c))}}(e,o)),u=l.filter(e=>null!==e);if(0===u.length)return tf(e,"ERR_INVALID_UAID_DNS_RECORD","DNS TXT payload at _uaid record is invalid.",{dnsName:s});const d=u.filter(e=>e.target===i&&e.id===r.id&&e.reconstructedUaid===a);if(0===d.length)return tf(e,"ERR_UAID_MISMATCH","DNS TXT payload does not match the input UAID after canonical reconstruction.",{dnsName:s,inputCanonical:a});const p=[...d].sort((e,t)=>e.reconstructedUaid.localeCompare(t.reconstructedUaid))[0],h=!!this.dnssecValidation&&await this.dnssecValidation(s)?"dns-binding-dnssec":"dns-binding";if(this.enableFollowupResolution){const i=function(e){return"aid"===xm(e)?"ans"===e.params.registry?[jm,Dm]:[Dm]:[Ym]}(r),n=[];for(const r of i){const i=await t.resolveUaidProfileById(r,e);if(i){if(!i.error&&!1!==i.metadata?.resolved)return{...i,metadata:{...i.metadata,profile:ef,resolved:!0,verificationLevel:h,reconstructedUaid:p.reconstructedUaid,selectedFollowupProfile:r,resolutionMode:"full-resolution"}};n.push(r)}}if(n.length>0)return tf(e,"ERR_FOLLOWUP_RESOLUTION_FAILED","Follow-up profile resolution failed after successful DNS binding.",{followupProfileId:n[n.length-1],attemptedFailedProfiles:n,dnsName:s})}if(this.requireFullResolution)return tf(e,"ERR_NO_FOLLOWUP_PROFILE","Resolver policy requires full resolution, but no supported follow-up profile was available.",{dnsName:s});const g=p.did??t.did??void 0;return{id:e,did:g,alsoKnownAs:g?[g]:void 0,metadata:{profile:ef,resolved:!0,reconstructedUaid:p.reconstructedUaid,verificationLevel:h,resolutionMode:"dns-binding-only"}}}}class of{constructor(){this.issuers=[]}register(e){this.issuers.push(e)}list(){return[...this.issuers]}filterByDidMethod(e){return this.issuers.filter(t=>t.meta.didMethods.includes(e))}filterByCaip2(e){return this.issuers.filter(t=>t.meta.caip2Networks?.includes(e))}filter(e){return this.issuers.filter(e)}async issue(e){for(const t of this.issuers)if(t.supports(e.method))return t.issue(e);throw new Error(`No issuer registered for method: ${e.method}`)}}const sf=new of,af=["@hiero-did-sdk","registrar"].join("/");let cf=null;function lf(e){return{network:()=>{const t=e.ledgerId;if(!t)throw new Error("Hedera SDK Client must be configured with a network");if(t.isMainnet())return"mainnet";if(t.isTestnet())return"testnet";if(t.isPreviewnet())return"previewnet";if(t.isLocalNode())return"local-node";throw new Error(`Unknown network, ledger ID: ${t.toString()}`)},publicKey:()=>{if(!e.operatorPublicKey)throw new Error("Hedera SDK Client must be configured with an operator account");return e.operatorPublicKey},publish:async t=>{const r="function"==typeof t.getAutoRenewAccountId?t.getAutoRenewAccountId():null,i=function(e){if("string"==typeof e&&e.trim())return e;if(e&&"function"==typeof e.toString){const t=e.toString();return"string"==typeof t&&t.trim()?t:null}return null}(e.operatorAccountId);!r&&i&&"function"==typeof t.setAutoRenewAccountId&&t.setAutoRenewAccountId(i);return(await t.freezeWith(e).execute(e)).getReceipt(e)}}}class uf{constructor(){this.meta={id:"hedera/hiero",didMethods:["hedera"],caip2Networks:["hedera:mainnet","hedera:testnet","hedera:previewnet","hedera:devnet"],caip10Namespaces:["hedera"],displayName:"Hedera (Hiero Registrar)",description:"Issues did:hedera identifiers using the Hiero DID registrar.",homepage:"https://github.com/hiero-ledger/hiero-did-sdk-js"}}supports(e){return"hedera"===e}async issue(e){if("hedera"!==e.method)throw new Error('HederaHieroIssuer only handles method "hedera"');if(!("client"in e))throw new Error("Hedera client is required to issue did:hedera");const t=await async function(){return cf||(cf=Ta(af,{preferImport:!0}).then(e=>e?.createDID??null)),cf}();if(!t)throw new Error("Hiero registrar unavailable. Ensure @hiero-did-sdk/registrar is installed.");const r=e.client;return(await t({},{publisher:lf(r)})).did}}class df{constructor(e){this.registry=e?.registry??new wm,this.issuers=new of,this.registerHederaIssuer(),this.registerHederaResolver(),this.registerUaidDnsWebProfileResolver(),this.registerAnsDnsWebProfileResolver(),this.registerAidDnsWebProfileResolver(),this.registerUaidDidResolutionProfileResolver(),this.registerHcs11ProfileResolver(),this.logger=y.getInstance({module:"HCS-14"}),this.client=e?.client,this.network=e?.network,this.operatorId=e?.operatorId,!this.client&&e?.network&&e?.operatorId&&e?.privateKey&&this.configureHederaClient(e.network,e.operatorId,e.privateKey),e?.privateKey&&(this.operatorPrivateKey=e.privateKey),e?.hcs10Client&&(this.hcs10Client=e.hcs10Client)}configureHederaClient(e,t,i){const n=B({network:e,operatorId:t,operatorKey:i,mirrorNode:new x(e),logger:this.logger,client:r.Client.forName(e)});this.operatorCtx=n,this.client=n.client,this.network=e,this.operatorId=t,this.operatorPrivateKey=i}async ensureInitializedHedera(){this.operatorCtx&&(await this.operatorCtx.ensureInitialized(),this.operatorId||(this.operatorId=this.operatorCtx.operatorId.toString()),this.operatorPrivateKey||(this.operatorPrivateKey=this.operatorCtx.operatorKey.toString()),this.client||(this.client=this.operatorCtx.client))}getIssuerRegistry(){return this.issuers}listIssuers(){return this.issuers.list()}registerAdapter(e){this.registry.registerAdapter(e)}listAdapters(){return this.registry.listAdapters()}filterAdapters(e={}){return this.registry.filterAdapters(e)}listResolvers(){return this.registry.list()}listProfileResolvers(){return this.registry.listProfileResolvers()}listUaidProfileResolvers(){return this.registry.listUaidProfileResolvers()}filterIssuersByMethod(e){return this.issuers.filterByDidMethod(e)}filterResolversByMethod(e){return this.registry.filterByDidMethod(e)}filterProfileResolversByMethod(e){return this.registry.filterProfileResolversByDidMethod(e)}filterUaidProfileResolversByMethod(e){return this.registry.filterUaidProfileResolversByDidMethod(e)}filterUaidProfileResolversByProfileId(e){return this.registry.filterUaidProfileResolversByProfileId(e)}registerHederaIssuer(){this.issuers.register(new uf)}async createDid(e){return this.issuers.issue(e)}canonicalizeAgentData(e){return rm(e)}createUaid(e,t,r){return"string"==typeof e?cm(e,t):cm(e,t,r)}parseHcs14Did(e){return lm(e)}isHederaNetwork(e){return lh(e)}isHederaCaip10(e){return dh(e)}toHederaCaip10(e,t){return ph(e,t)}parseHederaCaip10(e){return hh(e)}isEip155Caip10(e){return mh(e)}toEip155Caip10(e,t){return fh(e,t)}getResolverRegistry(){return this.registry}registerProfileResolver(e){this.registry.registerProfileResolver(e)}registerUaidProfileResolver(e){this.registry.registerUaidProfileResolver(e)}registerHederaResolver(){this.registry.registerAdapter(new bm)}registerHcs11ProfileResolver(){this.registry.registerAdapter(new vm)}registerUaidDidResolutionProfileResolver(){this.registry.registerAdapter(new Qm)}registerAidDnsWebProfileResolver(e){this.registry.registerAdapter(new Bm(e))}registerAnsDnsWebProfileResolver(e){this.registry.registerAdapter(new Jm(e))}registerUaidDnsWebProfileResolver(e){this.registry.registerAdapter(new nf(e))}async resolveDidProfile(e){return this.registry.resolveDidProfile(e)}async resolveUaidProfile(e,t){return this.registry.resolveUaidProfile(e,t)}async createDidWithUaid(e){const t=await this.createDid(e.issue);let r=e.uid;const i=e.proto;let n=e.nativeId;if("hedera"===e.issue.method){if(await this.ensureInitializedHedera(),!n){if(!this.network||!this.operatorId)throw new Error("nativeId not provided and network/operatorId are not configured");n=ph(this.network,this.operatorId)}if(!r&&"hcs-10"===i&&this.network&&this.operatorId)try{if(!this.hcs10Client&&this.operatorPrivateKey&&(this.hcs10Client=new fg({network:this.network,operatorId:this.operatorId,operatorPrivateKey:this.operatorPrivateKey,silent:!0})),this.hcs10Client)r=await this.hcs10Client.getOperatorId();else{const e=new $h({network:this.network,auth:{operatorId:this.operatorId},silent:!0}),t=await e.fetchProfileByAccountId(this.operatorId,this.network),i=t?.topicInfo?.inboundTopic;r=i?`${i}@${this.operatorId}`:this.operatorId}}catch{r=this.operatorId}}r=r??"0";const o=this.createUaid(t,{uid:r,proto:i,nativeId:n});return{did:t,uaid:o,parsed:lm(o)}}}const pf=Object.freeze(Object.defineProperty({__proto__:null,AID_DNS_WEB_PROFILE_ID:Dm,ANS_DNS_WEB_PROFILE_ID:jm,AidDnsWebProfileResolver:Bm,AnsDnsWebProfileResolver:Jm,CanonicalAgentDataSchema:Qg,HCS11ProfileResolver:vm,HCS14Client:df,HCS14_PROTOCOL_REGEX:Zg,HederaHieroIssuer:uf,HieroDidResolver:bm,IssuerRegistry:of,ResolverRegistry:wm,UAID_DID_RESOLUTION_PROFILE_ID:Ym,UAID_DNS_WEB_PROFILE_ID:ef,UaidDidResolutionProfileResolver:Qm,UaidDnsWebProfileResolver:nf,canonicalizeAgentData:rm,createUaid:cm,defaultIssuerRegistry:sf,defaultResolverRegistry:Im,isDidProfileResolverAdapter:gm,isDidResolverAdapter:mm,isEip155Caip10:mh,isHederaCaip10:dh,isHederaNetwork:lh,isUaidProfileResolverAdapter:hm,nodeDnsTxtLookup:Am,parseHcs14Did:lm,parseHederaCaip10:hh,registerDefaultResolvers:Tm,toEip155Caip10:fh,toHederaCaip10:ph},Symbol.toStringTag,{value:"Module"}));function hf(e){return`hcs://1/${e}`}class gf{constructor(e){this.network=e.network,this.logger=e.logger||y.getInstance({level:e.logLevel||"info",module:"HCS5Client",silent:e.silent}),this.mirrorNode=new x(this.network,this.logger)}}function mf(e){const t=(new r.TokenMintTransaction).setTokenId(r.TokenId.fromString(e.tokenId)).setMetadata([globalThis.Buffer.from(e.metadata)]);return e.transactionMemo&&t.setTransactionMemo(e.transactionMemo),t}var ff=(e=>(e.REGISTER="register",e.UPDATE="update",e.DELETE="delete",e.MIGRATE="migrate",e))(ff||{}),yf=(e=>(e[e.INDEXED=0]="INDEXED",e[e.NON_INDEXED=1]="NON_INDEXED",e))(yf||{});const bf=t.z.string().regex(/^\d+\.\d+\.\d+$/,{message:"Topic ID must be in Hedera format (e.g., '0.0.123456')"}),wf=t.z.object({p:t.z.string().regex(/^hcs-\d+$/,{message:"Protocol must be in format 'hcs-N' where N is a number"}),op:t.z.enum(["register","update","delete","migrate"]),m:t.z.string().max(500,"Memo must not exceed 500 characters").optional(),ttl:t.z.number().int().positive().optional()}),If=wf.extend({op:t.z.literal("register"),t_id:bf,metadata:t.z.string().optional()}),Tf=wf.extend({op:t.z.literal("update"),uid:t.z.string(),t_id:bf,metadata:t.z.string().optional()}),Sf=wf.extend({op:t.z.literal("delete"),uid:t.z.string()}),kf=wf.extend({op:t.z.literal("migrate"),t_id:bf,metadata:t.z.string().optional()}),vf=t.z.discriminatedUnion("op",[If,Tf,Sf,kf]);class Ef{constructor(e){this.network=e.network,this.logger=e.logger||y.getInstance({level:e.logLevel||"info",module:"HCS2Client",silent:e.silent}),this.mirrorNode=new x(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0)}parseRegistryTypeFromMemo(e){try{const t=/hcs-2:(\d):(\d+)/,r=e.match(t);if(r&&3===r.length){const e=parseInt(r[1]),t=parseInt(r[2]);if(void 0!==e&&!isNaN(t))return{registryType:e,ttl:t}}return}catch(t){return void this.logger.error(`Error parsing registry type from memo: ${t}`)}}generateRegistryMemo(e,t){return`hcs-2:${e}:${t}`}validateMessage(e){try{return vf.parse(e),{valid:!0,errors:[]}}catch(r){const e=[];return r instanceof t.ZodError?r.errors.forEach(t=>{const r=t.path.join(".");e.push(`${r?r+": ":""}${t.message}`)}):e.push(`Unexpected error: ${r}`),this.logger.debug(`Message validation failed: ${e.join(", ")}`),{valid:!1,errors:e}}}createRegisterMessage(e,t,r,i="hcs-2"){return{p:i,op:ff.REGISTER,t_id:e,metadata:t,m:r}}createUpdateMessage(e,t,r,i,n="hcs-2"){return{p:n,op:ff.UPDATE,t_id:e,uid:t,metadata:r,m:i}}createDeleteMessage(e,t,r="hcs-2"){return{p:r,op:ff.DELETE,uid:e,m:t}}createMigrateMessage(e,t,r,i="hcs-2"){return{p:i,op:ff.MIGRATE,t_id:e,metadata:t,m:r}}parseRegistryEntries(e,t,r,i){const n=[];let o;this.logger.debug(`Parsing ${t.length} messages for topic ${e}`);for(const a of t)try{if(!a.message){this.logger.debug(`Message is missing 'message' property: ${JSON.stringify(a)}`);continue}const t=globalThis.Buffer.from(a.message,"base64").toString("utf-8"),i=JSON.parse(t);this.logger.debug(`Successfully parsed message: ${JSON.stringify(i)}`);const{valid:s,errors:c}=this.validateMessage(i);if(!s){this.logger.warn(`Invalid HCS-2 message: ${c.join(", ")}`);continue}const l={topicId:e,sequence:a.sequence_number,timestamp:a.consensus_timestamp,payer:a.payer_account_id,message:i,consensus_timestamp:a.consensus_timestamp,registry_type:r};n.push(l),(r===yf.NON_INDEXED||!o||l.timestamp>o.timestamp)&&(o=l)}catch(s){this.logger.warn(`Error parsing message: ${s}`)}return this.logger.debug(`Parsed ${n.length} valid entries for topic ${e}`),{topicId:e,registryType:r,ttl:i,entries:r===yf.INDEXED?n:o?[o]:[],latestEntry:o}}}function Af(e){var t,r;return z({memo:e.memoOverride??(t=e.registryType,r=e.ttl,`hcs-2:${t}:${r}`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Cf(e){const t={p:"hcs-2",op:ff.REGISTER,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return _({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})}const Rf=/^hcs:\/\/1\/(\d+\.\d+\.\d+)$/,xf=class e extends Ef{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,mirrorNodeUrl:e.mirrorNodeUrl,logger:e.logger}),this.registryTypeCache=new Map,this.operatorId="string"==typeof e.operatorId?r.AccountId.fromString(e.operatorId):e.operatorId,this.operatorCtx=B({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:e.client??this.createClient(e.network)}),this.client=this.operatorCtx.client}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}createClient(e){return"mainnet"===e?r.Client.forMainnet():r.Client.forTestnet()}async createRegistry(e={}){try{await this.ensureInitialized();const t=e.registryType??yf.INDEXED,i=e.ttl??86400;this.generateRegistryMemo(t,i);let n,o,s,a;if(e.adminKey)if("string"==typeof e.adminKey)try{o=r.PublicKey.fromString(e.adminKey)}catch{const t=globalThis.Buffer.from(e.adminKey.replace(/^0x/i,""),"hex");o="ed25519"===this.operatorCtx.keyType?r.PublicKey.fromBytesED25519(t):r.PublicKey.fromBytesECDSA(t)}else"boolean"==typeof e.adminKey?o=this.operatorCtx.operatorKey.publicKey:(o=e.adminKey.publicKey,n=e.adminKey);if(e.submitKey)if("string"==typeof e.submitKey)try{a=r.PublicKey.fromString(e.submitKey)}catch{const t=globalThis.Buffer.from(e.submitKey.replace(/^0x/i,""),"hex");a="ed25519"===this.operatorCtx.keyType?r.PublicKey.fromBytesED25519(t):r.PublicKey.fromBytesECDSA(t)}else"boolean"==typeof e.submitKey?a=this.operatorCtx.operatorKey.publicKey:(a=e.submitKey.publicKey,s=e.submitKey);const c=Af({registryType:t,ttl:i,adminKey:o,submitKey:a,operatorPublicKey:this.operatorCtx.operatorKey.publicKey}),l=await c.freezeWith(this.client);n&&await l.sign(n),s&&await l.sign(s);const u=await l.execute(this.client),d=(await u.getReceipt(this.client)).topicId;if(!d)throw new Error("Failed to create registry: No topic ID in receipt");const p=d.toString();return this.registryTypeCache.set(p,t),this.logger.info(`Created registry topic: ${p} (${t===yf.INDEXED?"Indexed":"Non-indexed"}, TTL: ${i}s)`),{success:!0,topicId:p,transactionId:u.transactionId.toString()}}catch(t){return this.logger.error(`Failed to create registry: ${t}`),{success:!1,error:`Failed to create registry: ${t}`}}}async registerEntry(e,t,r="hcs-2"){try{await this.ensureInitialized();const i=this.createRegisterMessage(t.targetTopicId,t.metadata,t.memo,r),n=t.registryType??await this.resolveRegistryType(e);this.registryTypeCache.set(e,n);const o=t.analyticsMemo??this.buildAnalyticsMemo(ff.REGISTER,n),s=await this.submitMessage(e,i,o);return this.logger.info(`Registered entry in registry ${e} pointing to topic ${t.targetTopicId} using protocol ${r}`),{success:!0,receipt:s,sequenceNumber:s.topicSequenceNumber?.low??void 0}}catch(i){return this.logger.error(`Failed to register entry: ${i}`),{success:!1,error:`Failed to register entry: ${i}`}}}async updateEntry(e,t){try{await this.ensureInitialized();const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i||i.registryType!==yf.INDEXED)throw new Error("Update operation is only valid for indexed registries");const n=this.createUpdateMessage(t.targetTopicId,t.uid,t.metadata,t.memo),o=t.registryType??await this.resolveRegistryType(e);this.registryTypeCache.set(e,o);const s=t.analyticsMemo??this.buildAnalyticsMemo(ff.UPDATE,o),a=await this.submitMessage(e,n,s);return this.logger.info(`Updated entry with UID ${t.uid} in registry ${e}`),{success:!0,receipt:a,sequenceNumber:a.topicSequenceNumber?.low??void 0}}catch(r){throw this.logger.error(`Failed to update entry: ${r}`),r}}async deleteEntry(e,t){try{await this.ensureInitialized();const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i||i.registryType!==yf.INDEXED)throw new Error("Delete operation is only valid for indexed registries");const n=this.createDeleteMessage(t.uid,t.memo),o=t.registryType??await this.resolveRegistryType(e);this.registryTypeCache.set(e,o);const s=t.analyticsMemo??this.buildAnalyticsMemo(ff.DELETE,o),a=await this.submitMessage(e,n,s);return this.logger.info(`Deleted entry with UID ${t.uid} from registry ${e}`),{success:!0,receipt:a,sequenceNumber:a.topicSequenceNumber?.low??void 0}}catch(r){throw this.logger.error(`Failed to delete entry: ${r}`),r}}async migrateRegistry(e,t){try{await this.ensureInitialized();const r=this.createMigrateMessage(t.targetTopicId,t.metadata,t.memo),i=t.registryType??await this.resolveRegistryType(e);this.registryTypeCache.set(e,i);const n=t.analyticsMemo??this.buildAnalyticsMemo(ff.MIGRATE,i),o=await this.submitMessage(e,r,n);return this.logger.info(`Migrated registry ${e} to ${t.targetTopicId}`),{success:!0,receipt:o,sequenceNumber:o.topicSequenceNumber?.low??void 0}}catch(r){throw this.logger.error(`Failed to migrate registry: ${r}`),r}}async getRegistry(e,t={}){try{await this.ensureInitialized();const n=await this.mirrorNode.getTopicInfo(e);this.logger.debug(`Retrieved topic info for ${e}: ${JSON.stringify(n)}`);const o=this.parseRegistryTypeFromMemo(n.memo);if(!o)throw new Error(`Topic ${e} is not an HCS-2 registry (invalid memo format)`);this.logger.debug(`Retrieving messages for topic ${e} with limit ${t.limit??100}`);const s=await this.mirrorNode.getTopicMessages(e,{sequenceNumber:t.skip&&t.skip>0?`gt:${t.skip}`:void 0,limit:t.limit??100,order:t.order??"asc"}),a=t.limit?s.slice(0,t.limit):s;this.logger.debug(`Retrieved ${s.length} messages, using ${a.length} after applying limit.`);const c=[];let l;for(const u of a)try{let i;if(i={p:u.p||"hcs-2",op:u.op,t_id:u.t_id,uid:u.uid,metadata:u.metadata,m:u.m},t.resolveOverflow&&"string"==typeof u.metadata&&Rf.test(u.metadata)){const e=u.metadata.match(Rf);if(e){const t=e[1];try{const e=await this.mirrorNode.getTopicMessages(t);if(e.length>0){const t=e[0];i={p:t.p||"hcs-2",op:t.op,t_id:t.t_id,uid:t.uid,metadata:t.metadata,m:t.m}}}catch(r){this.logger.warn(`Failed to resolve overflow ${u.metadata}: ${r}`)}}}const{valid:n,errors:s}=this.validateMessage(i);if(!n){this.logger.warn(`Invalid HCS-2 message: ${s.join(", ")}`);continue}const a={topicId:e,sequence:u.sequence_number,timestamp:u.consensus_timestamp,payer:u.payer_account_id||u.payer||"",message:i,consensus_timestamp:u.consensus_timestamp,registry_type:o.registryType};c.push(a),(o.registryType===yf.NON_INDEXED||!l||a.timestamp>l.timestamp)&&(l=a)}catch(i){this.logger.warn(`Error processing message: ${i}`)}this.logger.debug(`Processed ${c.length} valid entries for registry ${e}`);return{topicId:e,registryType:o.registryType,ttl:o.ttl,entries:o.registryType===yf.INDEXED?c:l?[l]:[],latestEntry:l}}catch(i){throw this.logger.error(`Failed to get registry: ${i}`),i}}buildAnalyticsMemo(t,r){return`hcs-2:op:${e.operationAnalyticsCode[t]}:${r}`}async resolveRegistryType(e){const t=this.registryTypeCache.get(e);if(void 0!==t)return t;const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i)throw new Error(`Topic ${e} is not an HCS-2 registry (invalid memo format)`);return this.registryTypeCache.set(e,i.registryType),i.registryType}async submitMessage(e,t,r){try{await this.ensureInitialized();const{valid:i,errors:n}=this.validateMessage(t);if(!i)throw new Error(`Invalid HCS-2 message: ${n.join(", ")}`);let o=JSON.stringify(t);if(globalThis.Buffer.byteLength(o,"utf8")>1024){this.logger.info("HCS-2 payload exceeds 1024 bytes, inscribing via HCS-1");const e=globalThis.Buffer.from(o,"utf8"),r=`hcs2-overflow-${d.randomUUID()}.json`;if("testnet"!==this.network&&"mainnet"!==this.network)throw new Error(`Overflow inscription is only supported on testnet and mainnet, but network is ${this.network}`);const i={accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network};this.inscriptionSDK||(this.inscriptionSDK=await es.createWithAuth({type:"server",...i}));const n=await Oa({type:"buffer",buffer:e,fileName:r,mimeType:"application/json"},i,{mode:"file",waitForConfirmation:!0,waitMaxAttempts:30,waitIntervalMs:4e3},this.inscriptionSDK),s=Ha(n?.inscription);if(!s)throw new Error("Failed to inscribe overflow HCS-2 payload: no topic ID returned");const a=`hcs://1/${s}`,c={...t,metadata:a};this.logger.info(`HCS-2 payload inscribed to ${a}, submitting overflow wrapper`),o=JSON.stringify(c)}const s=_({topicId:e,message:o,transactionMemo:r}),a=await s.execute(this.client);return await a.getReceipt(this.client)}catch(i){throw this.logger.error(`Failed to submit message: ${i}`),i}}async getTopicInfo(e){return this.mirrorNode.getTopicInfo(e)}close(){this.logger.info("HCS-2 client closed.")}getKeyType(){return this.operatorCtx.keyType}getOperatorKey(){return this.operatorCtx.operatorKey}};xf.operationAnalyticsCode={[ff.REGISTER]:0,[ff.UPDATE]:1,[ff.DELETE]:2,[ff.MIGRATE]:3};let Nf=xf;class zf extends Ef{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,mirrorNodeUrl:e.mirrorNodeUrl,logger:e.logger}),this.hwc=e.hwc,ma?this.logger.info("HCS-2 browser client initialized successfully"):this.logger.error("BrowserHCS2Client initialized in server environment - browser-specific features will not be available. Use HCS2Client instead.")}getOperatorId(){const e=this.hwc.getAccountInfo();if(!e||!e.accountId)throw new Error("No connected account found");return e.accountId}async createRegistry(e={}){try{const t=e.registryType??yf.INDEXED,i=e.ttl??86400,n=this.generateRegistryMemo(t,i);let o=(new r.TopicCreateTransaction).setTopicMemo(n);if(e.adminKey){let t;if("string"==typeof e.adminKey)try{t=r.PublicKey.fromString(e.adminKey)}catch{const i=F.detect(e.adminKey);if(!i.rawBytes)throw new Error("Failed to parse admin public key");t="ed25519"===i.type?r.PublicKey.fromBytesED25519(i.rawBytes):r.PublicKey.fromBytesECDSA(i.rawBytes)}else t="boolean"==typeof e.adminKey?await this.mirrorNode.getPublicKey(this.getOperatorId()):e.adminKey.publicKey;o=o.setAdminKey(t)}if(e.submitKey){let t;if("string"==typeof e.submitKey)try{t=r.PublicKey.fromString(e.submitKey)}catch{const i=F.detect(e.submitKey);if(!i.rawBytes)throw new Error("Failed to parse submit public key");t="ed25519"===i.type?r.PublicKey.fromBytesED25519(i.rawBytes):r.PublicKey.fromBytesECDSA(i.rawBytes)}else t="boolean"==typeof e.submitKey?await this.mirrorNode.getPublicKey(this.getOperatorId()):e.submitKey.publicKey;o=o.setSubmitKey(t)}const s=await this.executeWithWallet(o);if(s?.error)throw new Error(s.error);const a=s?.result;if(!a?.topicId)throw new Error("Failed to create registry: No topic ID in receipt");const c=a.topicId.toString();return this.logger.info(`Created registry topic: ${c} (${t===yf.INDEXED?"Indexed":"Non-indexed"}, TTL: ${i}s)`),{success:!0,topicId:c,transactionId:s.transactionId||"unknown"}}catch(t){return this.logger.error(`Failed to create registry: ${t}`),{success:!1,error:`Failed to create registry: ${t}`}}}async registerEntry(e,t){try{const r=this.createRegisterMessage(t.targetTopicId,t.metadata,t.memo);if(r.op!==ff.REGISTER)throw new Error(`Invalid operation type: ${r.op}, expected ${ff.REGISTER}`);const i=await this.submitMessage(e,r);return this.logger.info(`Registered entry in registry ${e} pointing to topic ${t.targetTopicId}`),{success:!0,receipt:i,sequenceNumber:i.topicSequenceNumber?.low??void 0}}catch(r){return this.logger.error(`Failed to register entry: ${r}`),{success:!1,error:`Failed to register entry: ${r}`}}}async updateEntry(e,t){try{const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i||i.registryType!==yf.INDEXED)throw new Error("Update operation is only valid for indexed registries");const n=this.createUpdateMessage(t.targetTopicId,t.uid,t.metadata,t.memo),o=await this.submitMessage(e,n);return this.logger.info(`Updated entry with UID ${t.uid} in registry ${e}`),{success:!0,receipt:o,sequenceNumber:o.topicSequenceNumber?.low??void 0}}catch(r){return this.logger.error(`Failed to update entry: ${r}`),{success:!1,error:`Failed to update entry: ${r}`}}}async deleteEntry(e,t){try{const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i||i.registryType!==yf.INDEXED)throw new Error("Delete operation is only valid for indexed registries");const n=this.createDeleteMessage(t.uid,t.memo),o=await this.submitMessage(e,n);return this.logger.info(`Deleted entry with UID ${t.uid} from registry ${e}`),{success:!0,receipt:o,sequenceNumber:o.topicSequenceNumber?.low??void 0}}catch(r){return this.logger.error(`Failed to delete entry: ${r}`),{success:!1,error:`Failed to delete entry: ${r}`}}}async migrateRegistry(e,t){try{const r=this.createMigrateMessage(t.targetTopicId,t.metadata,t.memo),i=await this.submitMessage(e,r);return this.logger.info(`Migrated registry ${e} to ${t.targetTopicId}`),{success:!0,receipt:i,sequenceNumber:i.topicSequenceNumber?.low??void 0}}catch(r){return this.logger.error(`Failed to migrate registry: ${r}`),{success:!1,error:`Failed to migrate registry: ${r}`}}}async getRegistry(e,t={}){try{const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i)throw new Error(`Topic ${e} is not an HCS-2 registry (invalid memo format)`);const n=await this.mirrorNode.getTopicMessages(e,{sequenceNumber:t.skip&&t.skip>0?`gt:${t.skip}`:void 0,limit:t.limit??100,order:t.order??"asc"}),o=t.limit?n.slice(0,t.limit):n;return this.parseRegistryEntries(e,o,i.registryType,i.ttl)}catch(r){throw this.logger.error(`Failed to get registry: ${r}`),r}}async submitMessage(e,t){try{const{valid:r,errors:i}=this.validateMessage(t);if(!r)throw new Error(`Invalid HCS-2 message: ${i.join(", ")}`);const n=_({topicId:e,message:JSON.stringify(t)}),o=await this.executeWithWallet(n);if(o?.error)throw new Error(o.error);return o.result}catch(r){throw this.logger.error(`Failed to submit message: ${r}`),r}}async executeWithWallet(e){const t=this.hwc.executeTransactionWithErrorHandling;if(!t)throw new Error("Wallet SDK does not support executeTransactionWithErrorHandling");return await t.call(this.hwc,e,!1)}}const _f={PROTOCOL:"hcs-20",PUBLIC_TOPIC_ID:"0.0.4350190",REGISTRY_TOPIC_ID:"0.0.4362300",MAX_NUMBER_LENGTH:18,MAX_NAME_LENGTH:100,MAX_METADATA_LENGTH:100,HEDERA_ACCOUNT_REGEX:/^(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))$/},Pf=t.z.string().regex(_f.HEDERA_ACCOUNT_REGEX,"Invalid Hedera account ID format"),Of=t.z.string().regex(/^\d+$/,"Must be a valid number").max(_f.MAX_NUMBER_LENGTH,`Max ${_f.MAX_NUMBER_LENGTH} digits`),Df=t.z.string().min(1,"Tick cannot be empty").transform(e=>e.toLowerCase().trim()),Ff=t.z.object({p:t.z.literal("hcs-20"),m:t.z.string().optional()}),Mf=Ff.extend({op:t.z.literal("deploy"),name:t.z.string().min(1).max(_f.MAX_NAME_LENGTH),tick:Df,max:Of,lim:Of.optional(),metadata:t.z.string().max(_f.MAX_METADATA_LENGTH).optional()}),Uf=Ff.extend({op:t.z.literal("mint"),tick:Df,amt:Of,to:Pf}),Bf=Ff.extend({op:t.z.literal("burn"),tick:Df,amt:Of,from:Pf}),Lf=Ff.extend({op:t.z.literal("transfer"),tick:Df,amt:Of,from:Pf,to:Pf}),Kf=Ff.extend({op:t.z.literal("register"),name:t.z.string().min(1).max(_f.MAX_NAME_LENGTH),metadata:t.z.string().max(_f.MAX_METADATA_LENGTH).optional(),private:t.z.boolean(),t_id:Pf}),$f=t.z.discriminatedUnion("op",[Mf,Uf,Bf,Lf,Kf]);class Hf extends Error{constructor(e){super(e),this.name="HCS20Error"}}class qf extends Hf{constructor(e,t){super(e),this.tick=t,this.name="PointsDeploymentError"}}class jf extends Hf{constructor(e,t,r,i,n,o){super(e),this.tick=t,this.from=r,this.to=i,this.amount=n,this.availableBalance=o,this.name="PointsTransferError"}}class Wf extends Hf{constructor(e,t,r,i,n){super(e),this.tick=t,this.from=r,this.amount=i,this.availableBalance=n,this.name="PointsBurnError"}}class Vf extends Hf{constructor(e,t){super(e),this.validationErrors=t,this.name="PointsValidationError"}}class Gf extends Hf{constructor(e,t){super(e),this.topicId=t,this.name="TopicRegistrationError"}}class Jf extends Hf{constructor(e){super(`Invalid Hedera account format: ${e}`),this.account=e,this.name="InvalidAccountFormatError"}}class Yf{constructor(e){this.logger=e.logger||new y({module:"HCS20Client"}),this.network="mainnet"===e.network?"mainnet":"testnet",this.mirrorNode=new x(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0),this.registryTopicId=e.registryTopicId||_f.REGISTRY_TOPIC_ID,this.publicTopicId=e.publicTopicId||_f.PUBLIC_TOPIC_ID}validateMessage(e){try{return $f.parse(e),{valid:!0}}catch(t){if(t.errors){return{valid:!1,errors:t.errors.map(e=>`${e.path.join(".")}: ${e.message}`)}}return{valid:!1,errors:[t.message]}}}normalizeTick(e){return e.toLowerCase().trim()}accountToString(e){if("string"==typeof e){if(!_f.HEDERA_ACCOUNT_REGEX.test(e))throw new Jf(e);return e}return e.toString()}topicToString(e){if("string"==typeof e){if(!_f.HEDERA_ACCOUNT_REGEX.test(e))throw new Jf(e);return e}return e.toString()}}function Xf(e){const t={p:"hcs-20",op:"deploy",name:e.name,tick:e.tick.toLowerCase().trim(),max:e.max,lim:e.lim,metadata:e.metadata,m:e.memo};return _({topicId:e.topicId,message:JSON.stringify(t)})}function Zf(e){const t={p:"hcs-20",op:"mint",tick:e.tick.toLowerCase().trim(),amt:e.amt,to:e.to,m:e.memo};return _({topicId:e.topicId,message:JSON.stringify(t)})}function Qf(e){const t={p:"hcs-20",op:"transfer",tick:e.tick.toLowerCase().trim(),amt:e.amt,from:e.from,to:e.to,m:e.memo};return _({topicId:e.topicId,message:JSON.stringify(t)})}function ey(e){const t={p:"hcs-20",op:"burn",tick:e.tick.toLowerCase().trim(),amt:e.amt,from:e.from,m:e.memo};return _({topicId:e.topicId,message:JSON.stringify(t)})}function ty(e){const t={p:"hcs-20",op:"register",name:e.name,metadata:e.metadata,private:e.isPrivate,t_id:e.topicId,m:e.memo};return _({topicId:e.registryTopicId,message:JSON.stringify(t)})}class ry extends Error{constructor(e,t){super(e),this.code=t,this.name="HCS21ValidationError"}}function iy(e){const t=e.indexed??0,r=e.type??gc.ADAPTER_REGISTRY;if(e.metaTopicId&&!hc.test(e.metaTopicId))throw new ry("Meta value must be a short pointer (topic ID, HRL, IPFS, Arweave, OCI, or HTTPS)","invalid_payload");const i=e.metaTopicId?`:${e.metaTopicId}`:"";return`hcs-21:${t}:${e.ttl}:${r}${i}`}function ny(e){return z({memo:iy({ttl:e.ttl,indexed:e.indexed,type:e.type,metaTopicId:e.metaTopicId}),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function oy(e){const t=JSON.stringify(e.declaration),r=globalThis.Buffer.byteLength(t,"utf8");if(r>dc)throw new ry(`HCS-21 payload exceeds safe limit of 1000 bytes (${r}); Hedera cap is 1024`,"size_exceeded");return _({topicId:e.topicId,message:JSON.stringify(e.declaration),transactionMemo:e.transactionMemo})}class sy{constructor(e){this.network=e.network,this.logger=e.logger||new y({level:"info",module:"HCS-21"}),this.mirrorNode=new x(this.network,this.logger,{customUrl:e.mirrorNodeUrl})}buildDeclaration(e){const t={p:lc,op:e.op,adapter_id:e.adapterId,entity:e.entity,package:e.adapterPackage,manifest:e.manifest,...e.manifestSequence?{manifest_sequence:e.manifestSequence}:{},config:e.config,state_model:e.stateModel,signature:e.signature};return this.validateDeclaration(t)}validateDeclaration(e){try{const t="string"==typeof e?JSON.parse(e):e,r=yc.parse(t);return this.assertSizeLimit(r),r}catch(t){const e=t instanceof Error?t.message:"Invalid adapter declaration";throw new ry(e,"invalid_payload")}}async fetchDeclarations(e,t){const r=await this.mirrorNode.getTopicMessages(e,{limit:t?.limit,order:t?.order}),i=[];for(const o of r)if(o.p===lc)try{const e=this.validateDeclaration(o);i.push({declaration:e,consensusTimestamp:o.consensus_timestamp,sequenceNumber:o.sequence_number,payer:o.payer})}catch(n){const e=n instanceof Error?n.message:"unknown error";this.logger.warn(`Skipping invalid HCS-21 message: ${e}`)}return i}async fetchCategoryEntries(e){const t=await this.mirrorNode.getTopicMessages(e),r=[];for(const i of t){if("hcs-2"!==i.p||"register"!==i.op)continue;if(!i.t_id||"string"!=typeof i.t_id)continue;const e="string"==typeof i.m?i.m:void 0,t=e?.startsWith("adapter:")?e.slice(8):e;r.push({adapterId:t??i.t_id,adapterTopicId:i.t_id,metadata:i.metadata,memo:e,payer:i.payer,sequenceNumber:Number(i.sequence_number??0),consensusTimestamp:i.consensus_timestamp})}return r}assertSizeLimit(e){const t=JSON.stringify(e),r=globalThis.Buffer.byteLength(t,"utf8");if(r>dc)throw new ry(`HCS-21 payload exceeds safe limit of 1000 bytes (${r}); Hedera cap is 1024`,"size_exceeded")}}function ay(e){if(Array.isArray(e))return e.map(ay);if(e&&"object"==typeof e){const t=Object.entries(e).sort(([e],[t])=>e<t?-1:e>t?1:0),r={};for(const[e,i]of t)r[e]=ay(i);return r}return e}function cy(e){const t=ay(e);return JSON.stringify(t)}const ly="hcs-15:op:base_create",uy="hcs-15:op:petal_create";function dy(e,t){if("string"!=typeof e)return t;const r=e.trim();return r||t}function py(e){const t=(new r.AccountCreateTransaction).setECDSAKeyWithAlias(e.publicKey).setInitialBalance(e.initialBalance instanceof r.Hbar?e.initialBalance:new r.Hbar(e.initialBalance??1));return"number"==typeof e.maxAutomaticTokenAssociations&&t.setMaxAutomaticTokenAssociations(e.maxAutomaticTokenAssociations),e.accountMemo&&t.setAccountMemo(e.accountMemo),t.setTransactionMemo(dy(e.transactionMemo,ly)),t}function hy(e){const t=(new r.AccountCreateTransaction).setKeyWithoutAlias(e.publicKey).setInitialBalance(e.initialBalance instanceof r.Hbar?e.initialBalance:new r.Hbar(e.initialBalance??1));return"number"==typeof e.maxAutomaticTokenAssociations&&t.setMaxAutomaticTokenAssociations(e.maxAutomaticTokenAssociations),e.accountMemo&&t.setAccountMemo(e.accountMemo),t.setTransactionMemo(dy(e.transactionMemo,uy)),t}class gy{constructor(e){this.network=e.network,this.logger=e.logger||new y({module:"HCS-15",level:e.logLevel||"info"}),this.mirrorNode=new x(this.network,this.logger,{customUrl:e.mirrorNodeUrl})}async verifyPetalAccount(e,t){try{const r=await this.mirrorNode.requestAccount(e),i=await this.mirrorNode.requestAccount(t),n=r?.key?.key||"";return""!==n&&n===(i?.key?.key||"")}catch(Pw){return this.logger.warn("verifyPetalAccount failed",{error:String(Pw)}),!1}}}var my=(e=>(e[e.COMMUNICATION=0]="COMMUNICATION",e[e.TRANSACTION=1]="TRANSACTION",e[e.STATE=2]="STATE",e))(my||{}),fy=(e=>(e.FLORA_CREATED="flora_created",e.TRANSACTION="transaction",e.STATE_UPDATE="state_update",e.FLORA_JOIN_REQUEST="flora_join_request",e.FLORA_JOIN_VOTE="flora_join_vote",e.FLORA_JOIN_ACCEPTED="flora_join_accepted",e))(fy||{});class yy extends Error{constructor(e,t){super(e),this.code=t,this.name="FloraError"}}const by="hcs-16:op:0:0",wy="hcs-17:op:6:2",Iy="hcs-16:op:1:1",Ty="hcs-16:op:1:1";function Sy(e,t){if("string"!=typeof e)return t;const r=e.trim();return r||t}const ky={[fy.FLORA_CREATED]:0,[fy.TRANSACTION]:1,[fy.STATE_UPDATE]:2,[fy.FLORA_JOIN_REQUEST]:3,[fy.FLORA_JOIN_VOTE]:4,[fy.FLORA_JOIN_ACCEPTED]:5},vy={[fy.FLORA_CREATED]:my.COMMUNICATION,[fy.TRANSACTION]:my.TRANSACTION,[fy.STATE_UPDATE]:my.STATE,[fy.FLORA_JOIN_REQUEST]:my.COMMUNICATION,[fy.FLORA_JOIN_VOTE]:my.COMMUNICATION,[fy.FLORA_JOIN_ACCEPTED]:my.STATE};function Ey(e){const t=function(e){return`hcs-16:${e.floraAccountId}:${e.topicType}`}({floraAccountId:e.floraAccountId,topicType:e.topicType}),i=z({memo:t,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey});var n;return i.setTransactionMemo(Sy(e.transactionMemo,(n=e.topicType,`hcs-16:op:${ky[fy.FLORA_CREATED]}:${n}`))),e.autoRenewAccountId&&i.setAutoRenewAccountId(r.AccountId.fromString(e.autoRenewAccountId)),i}function Ay(e){const t=(new r.AccountCreateTransaction).setKey(e.keyList),i="number"==typeof e.initialBalanceHbar?e.initialBalanceHbar:1;t.setInitialBalance(new r.Hbar(i));const n="number"==typeof e.maxAutomaticTokenAssociations?e.maxAutomaticTokenAssociations:-1;return t.setMaxAutomaticTokenAssociations(n),t.setTransactionMemo(Sy(e.transactionMemo,by)),t}function Cy(e){const t={p:"hcs-16",op:e.op,operator_id:e.operatorId,...e.body||{}};return _({topicId:e.topicId,message:JSON.stringify(t),transactionMemo:Sy(e.transactionMemo,(r=e.op,`hcs-16:op:${ky[r]}:${vy[r]}`))});var r}function Ry(e){return Cy({topicId:e.topicId,operatorId:e.operatorId,op:fy.FLORA_CREATED,body:{flora_account_id:e.floraAccountId,topics:e.topics}})}function xy(e){return Cy({topicId:e.topicId,operatorId:e.operatorId,op:fy.TRANSACTION,body:{schedule_id:e.scheduleId,data:e.data,m:e.data}})}function Ny(e){const t={p:"hcs-17",op:"state_hash",state_hash:e.hash,topics:e.topics??[],account_id:e.accountId??e.operatorId,epoch:e.epoch,timestamp:(new Date).toISOString(),m:e.memo};return _({topicId:e.topicId,message:JSON.stringify(t),transactionMemo:Sy(e.transactionMemo,wy)})}function zy(e){return Cy({topicId:e.topicId,operatorId:e.operatorId,op:fy.FLORA_JOIN_REQUEST,body:{account_id:e.accountId,connection_request_id:e.connectionRequestId,connection_topic_id:e.connectionTopicId,connection_seq:e.connectionSeq}})}function _y(e){return Cy({topicId:e.topicId,operatorId:e.operatorId,op:fy.FLORA_JOIN_VOTE,body:{account_id:e.accountId,approve:e.approve,connection_request_id:e.connectionRequestId,connection_seq:e.connectionSeq}})}function Py(e){return Cy({topicId:e.topicId,operatorId:e.operatorId,op:fy.FLORA_JOIN_ACCEPTED,body:{members:e.members,epoch:e.epoch}})}class Oy{constructor(e){this.network=e.network,this.logger=e.logger||new y({level:"info",module:"HCS-16"}),this.mirrorNode=new x(this.network,this.logger,{customUrl:e.mirrorNodeUrl})}async assembleKeyList(e){const t=[];for(const r of e.members){const e=await this.mirrorNode.getPublicKey(r);t.push(e)}return new r.KeyList(t,e.threshold)}async assembleSubmitKeyList(e){const t=[];for(const r of e){const e=await this.mirrorNode.getPublicKey(r);t.push(e)}return new r.KeyList(t,1)}buildFloraTopicCreateTxs(e){return{communication:Ey({floraAccountId:e.floraAccountId,topicType:my.COMMUNICATION,adminKey:e.keyList,submitKey:e.submitList,autoRenewAccountId:e.autoRenewAccountId}),transaction:Ey({floraAccountId:e.floraAccountId,topicType:my.TRANSACTION,adminKey:e.keyList,submitKey:e.submitList,autoRenewAccountId:e.autoRenewAccountId}),state:Ey({floraAccountId:e.floraAccountId,topicType:my.STATE,adminKey:e.keyList,submitKey:e.submitList,autoRenewAccountId:e.autoRenewAccountId})}}parseTopicMemo(e){const t=e.match(/^hcs-16:([0-9.]+):(\d)$/);if(!t)return null;const r=t[1],i=Number(t[2]);return i!==my.COMMUNICATION&&i!==my.TRANSACTION&&i!==my.STATE?null:{protocol:"hcs-16",floraAccountId:r,topicType:i}}createFloraMessage(e,t,r){return{p:"hcs-16",op:e,operator_id:t,...r||{}}}async getRecentMessages(e,t){const r=t?.limit??25,i=t?.order??"desc",n=await this.mirrorNode.getTopicMessages(e,{limit:r,order:i}),o=[];for(const s of n){if("hcs-16"!==s.p)continue;const{consensus_timestamp:e,sequence_number:r,running_hash:i,running_hash_version:n,topic_id:a,payer:c,created:l,chunk_info:u,...d}=s,p=d.op,h=d.operator_id;if(t?.opFilter&&p!==t.opFilter)continue;if("string"!=typeof h)continue;const g=d;o.push({message:g,consensus_timestamp:e,sequence_number:Number(r),payer:c})}return o}async getLatestMessage(e,t){const r=await this.getRecentMessages(e,{limit:1,order:"desc",opFilter:t});if(0===r.length)return null;const i=r[0];return Object.assign({},i.message,{consensus_timestamp:i.consensus_timestamp,sequence_number:i.sequence_number})}}const Dy=t.z.object({p:t.z.literal("hcs-17"),op:t.z.literal("state_hash"),state_hash:t.z.string().min(1),topics:t.z.array(t.z.string()),account_id:t.z.string().min(1),epoch:t.z.number().int().nonnegative().optional(),timestamp:t.z.string().optional(),m:t.z.string().optional()});class Fy extends Error{constructor(e,t){super(e),this.code=t,this.name="StateHashError"}}var My=(e=>(e[e.STATE=0]="STATE",e))(My||{});function Uy(e){return`hcs-17:0:${e}`}function By(e){try{const t=e.match(/^hcs-17:(\d+):(\d+)$/);if(!t)return;const r=Number(t[1]),i=Number(t[2]);if(Number.isNaN(r)||Number.isNaN(i)||i<=0)return;if(0!==r)return;return{type:r,ttl:i}}catch{return}}class Ly{constructor(e){this.network=e.network,this.logger=e.logger||new y({level:e.logLevel||"info",module:"HCS-17"}),this.mirrorNode=new x(this.network,this.logger,{customUrl:e.mirrorNodeUrl})}createMessage(e){return{p:"hcs-17",op:"state_hash",state_hash:e.stateHash,topics:e.topics,account_id:e.accountId,epoch:e.epoch,timestamp:(new Date).toISOString(),m:e.memo}}validateMessage(e){const t=Dy.safeParse(e);if(t.success)return{valid:!0,errors:[]};const r=t.error.errors.map(e=>`${e.path.join(".")}: ${e.message}`);return this.logger.debug(`HCS-17 message validation failed: ${r.join(", ")}`),{valid:!1,errors:r}}generateTopicMemo(e){return Uy(e)}async validateHCS17Topic(e){try{const t=By((await this.mirrorNode.getTopicInfo(e)).memo);return t?t.type!==My.STATE?{valid:!1,error:"Unsupported HCS-17 topic type"}:{valid:!0,type:t.type,ttl:t.ttl}:{valid:!1,error:"Invalid HCS-17 memo format"}}catch(Pw){return{valid:!1,error:String(Pw)}}}async getRecentMessages(e,t){const r=t?.limit??25,i=t?.order??"desc",n=await this.mirrorNode.getTopicMessages(e,{limit:r,order:i}),o=[];for(const s of n)try{if("hcs-17"!==s.p||"state_hash"!==s.op)continue;const e=s,{valid:t}=this.validateMessage(e);if(!t)continue;o.push({message:{p:"hcs-17",op:"state_hash",state_hash:e.state_hash,topics:e.topics,account_id:e.account_id,epoch:e.epoch,timestamp:e.timestamp,m:e.m},consensus_timestamp:e.consensus_timestamp,sequence_number:Number(e.sequence_number),payer:e.payer})}catch(Ow){this.logger.debug(`Failed to parse HCS-17 message: ${Ow}`)}return o}async getLatestMessage(e){const t=await this.getRecentMessages(e,{limit:1,order:"desc"});if(!t.length)return null;const{message:r,consensus_timestamp:i,sequence_number:n}=t[0];return Object.assign({},r,{consensus_timestamp:i,sequence_number:n})}calculateAccountStateHash(e){try{this.logger.debug("Calculating account state hash",{accountId:e.accountId,topicCount:e.topics.length});const t=[...e.topics].sort((e,t)=>e.topicId.localeCompare(t.topicId));let r="";for(const e of t)r+=e.topicId+e.latestRunningHash;let i="";i="string"==typeof e.publicKey?e.publicKey:e.publicKey.toString(),r+=i;const n=d.createHash("sha384");n.update(r);const o=n.digest("hex");return this.logger.debug("Account state hash calculated",{accountId:e.accountId,stateHash:o}),{stateHash:o,accountId:e.accountId,timestamp:new Date,topicCount:e.topics.length}}catch(t){throw this.logger.error("Failed to calculate account state hash",t),new Error("HCS-17 CALCULATION_FAILED")}}calculateCompositeStateHash(e){try{this.logger.debug("Calculating composite state hash",{compositeAccountId:e.compositeAccountId,memberCount:e.memberStates.length,topicCount:e.compositeTopics.length});const t=[...e.memberStates].sort((e,t)=>e.accountId.localeCompare(t.accountId)),r=[...e.compositeTopics].sort((e,t)=>e.topicId.localeCompare(t.topicId));let i="";for(const e of t)i+=e.accountId+e.stateHash;for(const e of r)i+=e.topicId+e.latestRunningHash;i+=e.compositePublicKeyFingerprint;const n=d.createHash("sha384");n.update(i);const o=n.digest("hex");return this.logger.debug("Composite state hash calculated",{compositeAccountId:e.compositeAccountId,stateHash:o}),{stateHash:o,accountId:e.compositeAccountId,timestamp:new Date,topicCount:e.compositeTopics.length,memberCount:e.memberStates.length,compositeTopicCount:e.compositeTopics.length}}catch(t){throw this.logger.error("Failed to calculate composite state hash",t),new Error("HCS-17 COMPOSITE_CALCULATION_FAILED")}}calculateKeyFingerprint(e,t){try{const r={threshold:t,keys:[...e].sort((e,t)=>e.toString().localeCompare(t.toString())).map(e=>e.toString())},i=d.createHash("sha384");return i.update(JSON.stringify(r)),i.digest("hex")}catch(r){throw this.logger.error("Failed to calculate key fingerprint",r),new Error("HCS-17 FINGERPRINT_FAILED")}}createStateHashMessage(e,t,r,i){return{p:"hcs-17",op:"state_hash",state_hash:e,topics:r,account_id:t,timestamp:(new Date).toISOString(),m:i}}async verifyStateHash(e,t){try{let r;r="publicKey"in e?this.calculateAccountStateHash(e).stateHash:this.calculateCompositeStateHash(e).stateHash;const i=r===t,n="accountId"in e?e.accountId:e.compositeAccountId;return this.logger.debug("State hash verification",{accountId:n,isValid:i,expected:t,calculated:r}),i}catch(r){return this.logger.error("Failed to verify state hash",r),!1}}}function Ky(e){return z({memo:Uy(e.ttl),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function $y(e){const t={p:"hcs-17",op:"state_hash",state_hash:e.stateHash,topics:e.topics,account_id:e.accountId,epoch:e.epoch,timestamp:e.timestamp??(new Date).toISOString(),m:e.memo};return _({topicId:e.topicId,message:JSON.stringify(t),transactionMemo:e.transactionMemo})}var Hy=(e=>(e.ANNOUNCE="announce",e.PROPOSE="propose",e.RESPOND="respond",e.COMPLETE="complete",e.WITHDRAW="withdraw",e))(Hy||{});function qy(e){return"object"==typeof e&&null!==e}function jy(e){return"string"==typeof e}function Wy(e){return"number"==typeof e&&Number.isFinite(e)}function Vy(e){if(!qy(e))return!1;if("hcs-18"!==e.p)return!1;if(!jy(e.op))return!1;const t=e.op;return!!["announce","propose","respond","complete","withdraw"].includes(t)&&"data"in e}var Gy=(e=>(e.IDLE="idle",e.ANNOUNCED="announced",e.PROPOSING="proposing",e.FORMING="forming",e.ACTIVE="active",e.WITHDRAWN="withdrawn",e))(Gy||{});class Jy extends Error{constructor(e,t){super(e),this.code=t,this.name="DiscoveryError"}}function Yy(e,t){return t&&t.trim().length>0?t:e&&e>0?`hcs-18:0:${e}`:"hcs-18:0"}function Xy(e){return z({memo:Yy(e.ttlSeconds,e.memoOverride),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Zy(e){const t="string"==typeof e.transactionMemo&&e.transactionMemo.length>0?e.transactionMemo:`hcs-18:op:${function(e){switch(e){case Hy.ANNOUNCE:return 0;case Hy.PROPOSE:return 1;case Hy.RESPOND:return 2;case Hy.COMPLETE:return 3;case Hy.WITHDRAW:return 4;default:return 0}}(e.message.op)}`;return(new r.TopicMessageSubmitTransaction).setTopicId(e.topicId).setMessage(JSON.stringify(e.message)).setTransactionMemo(t)}function Qy(e){return{p:"hcs-18",op:Hy.ANNOUNCE,data:e}}function eb(e){return{p:"hcs-18",op:Hy.PROPOSE,data:e}}function tb(e){return{p:"hcs-18",op:Hy.RESPOND,data:e}}function rb(e){return{p:"hcs-18",op:Hy.COMPLETE,data:e}}function ib(e){return{p:"hcs-18",op:Hy.WITHDRAW,data:e}}class nb{constructor(e){this.network=e.network,this.logger=e.logger||y.getInstance({module:"HCS-18"}),this.mirrorNode=new x(this.network,this.logger)}async getDiscoveryMessages(e,t){const r=["announce","propose","respond","complete","withdraw"],i=await this.mirrorNode.getTopicMessages(e,t);return i?i.filter(e=>"hcs-18"===e.p&&r.includes(e.op)):[]}isProposalReady(e){const t=Array.from(e.responses.values()).filter(e=>"accept"===e.decision),r=e.data.members.length-1;return t.length>=r}}const ob=t.z.string().regex(/^(0|[1-9]\d*)$/);const sb=t.z.string().min(1).refine(function(e){if(!/^[A-Za-z0-9_-]+$/.test(e))return!1;try{const t=e+"=".repeat((4-e.length%4)%4),r=globalThis.Buffer.from(t,"base64url");return r.length>0&&r.toString("base64url")===e}catch{return!1}},"must be base64url"),ab=t.z.string().min(1).refine(function(e){if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))return!1;try{return globalThis.Buffer.from(e,"base64").toString("base64")===e}catch{return!1}},"must be base64"),cb=t.z.object({treeSize:ob,rootHashB64u:sb}).passthrough(),lb=t.z.object({treeSize:ob,rootHashB64u:sb}).passthrough(),ub=t.z.object({alg:t.z.string().min(1),kid:t.z.string().min(1),b64u:sb}).passthrough(),db=t.z.object({type:t.z.literal("ans-checkpoint-v1"),stream:t.z.object({registry:t.z.string().min(1),log_id:t.z.string().min(1)}).passthrough(),log:t.z.object({alg:t.z.literal("sha-256"),leaf:t.z.string().min(1),merkle:t.z.literal("rfc9162")}).passthrough(),root:cb,prev:lb.optional(),sig:ub.optional()}).passthrough(),pb=db.superRefine((e,r)=>{const i=BigInt(e.root.treeSize),n=e.prev?BigInt(e.prev.treeSize):void 0;void 0!==n&&n>i&&r.addIssue({code:t.z.ZodIssueCode.custom,message:"metadata.prev.treeSize must be <= metadata.root.treeSize",path:["prev","treeSize"]})}),hb=t.z.object({alg:t.z.literal("sha-256"),b64u:sb}).passthrough(),gb=t.z.object({p:t.z.literal("hcs-27"),op:t.z.literal("register"),metadata:t.z.union([db,t.z.string().regex(/^hcs:\/\/1\/\d+\.\d+\.\d+$/)]),metadata_digest:hb.optional(),m:t.z.string().max(299).optional()}).passthrough().superRefine((e,r)=>{"string"!=typeof e.metadata||e.metadata_digest||r.addIssue({code:t.z.ZodIssueCode.custom,message:"metadata_digest is required when metadata is an HCS-1 reference",path:["metadata_digest"]})}),mb=t.z.object({leafHash:t.z.string().regex(/^(?:[0-9a-f]{2})+$/i),leafIndex:ob,treeSize:ob,path:t.z.array(ab),rootHash:ab,rootSignature:t.z.string().optional(),treeVersion:t.z.literal(1)}).passthrough(),fb=t.z.object({oldTreeSize:ob,newTreeSize:ob,oldRootHash:t.z.string(),newRootHash:t.z.string(),consistencyPath:t.z.array(ab),treeVersion:t.z.literal(1)}).passthrough();function yb(e){const{type:t,stream:r,log:i,root:n,prev:o,sig:s}=e;if(!(t&&r&&i&&n))throw new Error("Invalid HCS-27 checkpoint metadata");return{type:t,stream:{registry:r.registry,log_id:r.log_id},log:{alg:i.alg,leaf:i.leaf,merkle:i.merkle},root:{treeSize:n.treeSize,rootHashB64u:n.rootHashB64u},...o?{prev:{treeSize:o.treeSize,rootHashB64u:o.rootHashB64u}}:{},...s?{sig:{alg:s.alg,kid:s.kid,b64u:s.b64u}}:{}}}function bb(e){const{p:t,op:r,metadata:i,metadata_digest:n,m:o}=e;if(!t||!r||!i)throw new Error("Invalid HCS-27 checkpoint message");return{p:t,op:r,metadata:"string"==typeof i?i:yb(i),...n?{metadata_digest:{alg:n.alg,b64u:n.b64u}}:{},...o?{m:o}:{}}}function wb(e=86400){return`hcs-27:0:${e>0?e:86400}:0`}function Ib(e){const t=e.trim().split(":");if(4!==t.length||"hcs-27"!==t[0])return;const r=Number.parseInt(t[1],10),i=Number.parseInt(t[2],10),n=Number.parseInt(t[3],10);return Number.isNaN(r)||Number.isNaN(i)||Number.isNaN(n)?void 0:{indexedFlag:r,ttlSeconds:i,topicType:n}}function Tb(){return"hcs-27:op:0:0"}function Sb(e){if(null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e){if("number"==typeof e&&!Number.isFinite(e))throw new Error("JSON numbers must be finite");return e}if(Array.isArray(e))return Array.from(e,e=>void 0===e?null:Sb(e));if("object"==typeof e){const t=e.toJSON;if("function"==typeof t)return Sb(t.call(e));const r={};for(const[i,n]of Object.entries(e))void 0!==n&&(r[i]=Sb(n));return r}throw new Error("Unsupported JSON value type: "+typeof e)}function kb(e,t){try{if(!e)throw new Error("empty base64");const t=globalThis.Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("non-canonical base64");return t}catch{throw new Error(`${t} must be valid base64`)}}function vb(e){if(null===e)return"null";if("boolean"==typeof e)return e?"true":"false";if("string"==typeof e)return JSON.stringify(e);if("number"==typeof e)return function(e){return Object.is(e,-0)?"0":e.toString()}(e);if(Array.isArray(e))return`[${e.map(e=>vb(e)).join(",")}]`;if("object"==typeof e){return`{${Object.entries(e).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>`${JSON.stringify(e)}:${vb(t)}`).join(",")}}`}throw new Error("Unsupported JSON value type: "+typeof e)}function Eb(e){return BigInt(e)}function Ab(e){return 1n&e}function Cb(e){const t=Sb(e);return globalThis.Buffer.from(vb(t),"utf8")}function Rb(){return d.createHash("sha256").update(globalThis.Buffer.alloc(0)).digest()}function xb(e){return d.createHash("sha256").update(globalThis.Buffer.from([0])).update(globalThis.Buffer.from(e)).digest()}function Nb(e,t){return d.createHash("sha256").update(globalThis.Buffer.from([1])).update(globalThis.Buffer.from(e)).update(globalThis.Buffer.from(t)).digest()}function zb(e){if(0===e.length)return Rb();if(1===e.length)return xb(e[0]);const t=function(e){if(e<=1)return 0;let t=1;for(;t<<1<e;)t<<=1;return t}(e.length);return Nb(zb(e.slice(0,t)),zb(e.slice(t)))}function _b(e){return zb(e.map(e=>Cb(e)))}function Pb(e){return xb(Cb(e)).toString("hex")}function Ob(e){let t,r,i,n,o,s;if("leafHash"in e){const s=mb.parse(e);t=BigInt(s.leafIndex),r=BigInt(s.treeSize),i=s.leafHash,n=s.path,o=s.rootHash}else t=Eb(e.leafIndex),r=Eb(e.treeSize),i=e.leafHashHex,n=e.path,o=e.expectedRootB64;if(r<=0n)throw new Error("treeSize must be greater than zero for inclusion proofs");if(t<0n||t>=r)throw new Error("leafIndex must be less than treeSize");if(!/^(?:[0-9a-f]{2})+$/i.test(i.trim()))throw new Error("leafHash must be valid hex");try{s=globalThis.Buffer.from(i.trim(),"hex")}catch{throw new Error("leafHash must be valid hex")}let a=t,c=r-1n;for(const[l,u]of n.entries()){if(0n===c)return!1;const e=kb(u,`path[${l}]`);if(1n===Ab(a)||a===c){if(s=Nb(e,s),0n===Ab(a))for(;0n===Ab(a)&&0n!==a;)a/=2n,c/=2n}else s=Nb(s,e);a/=2n,c/=2n}return 0n===c&&s.toString("base64")===o}function Db(e){let t,r,i,n,o;if("oldRootHash"in e){const s=fb.parse(e);t=BigInt(s.oldTreeSize),r=BigInt(s.newTreeSize),i=s.oldRootHash,n=s.newRootHash,o=s.consistencyPath}else t=Eb(e.oldTreeSize),r=Eb(e.newTreeSize),i=e.oldRootB64,n=e.newRootB64,o=e.consistencyPath;if(t<0n||r<0n)throw new Error("tree sizes must be non-negative");if(0n===t)return!0;if(t===r)return kb(i,"oldRootHash"),kb(n,"newRootHash"),i===n&&0===o.length;if(t>r||0===o.length)return!1;const s=o.map((e,t)=>kb(e,`consistencyPath[${t}]`));var a;0n!==(a=t)&&0n==(a&a-1n)&&s.unshift(kb(i,"oldRootHash"));let c=t-1n,l=r-1n;for(;1n===Ab(c);)c/=2n,l/=2n;const u=globalThis.Buffer.from(s[0]);let d=globalThis.Buffer.from(u),p=globalThis.Buffer.from(u);for(const h of s.slice(1)){if(0n===l)return!1;if(1n===Ab(c)||c===l){if(d=Nb(h,d),p=Nb(h,p),0n===Ab(c))for(;0n===Ab(c)&&0n!==c;)c/=2n,l/=2n}else p=Nb(p,h);c/=2n,l/=2n}return 0n===l&&globalThis.Buffer.from(d).toString("base64")===i&&globalThis.Buffer.from(p).toString("base64")===n}class Fb{constructor(e){this.network=e.network,this.logger=e.logger??y.getInstance({module:"HCS27Client",level:"info"}),this.mirrorNode=new x(this.network,this.logger,e.mirrorNode),this.cdnEndpoint=e.cdnEndpoint?.trim()||void 0,this.hrlResolver=new Gp}buildTopicMemo(e){return wb(e)}parseTopicMemo(e){return Ib(e)}buildTransactionMemo(){return"hcs-27:op:0:0"}emptyRoot(){return Rb()}hashLeaf(e){return xb("string"==typeof e?globalThis.Buffer.from(e,"utf8"):globalThis.Buffer.from(e))}hashNode(e,t){return Nb("string"==typeof e?globalThis.Buffer.from(e,"hex"):globalThis.Buffer.from(e),"string"==typeof t?globalThis.Buffer.from(t,"hex"):globalThis.Buffer.from(t))}merkleRootFromCanonicalEntries(e){return zb(e.map(e=>"string"==typeof e?globalThis.Buffer.from(e,"utf8"):globalThis.Buffer.from(e)))}merkleRootFromEntries(e){return _b(e)}leafHashHexFromEntry(e){return Pb(e)}verifyInclusionProof(e){return Ob(e)}verifyConsistencyProof(e){return Db(e)}async validateCheckpointMessage(e,t,r){const i=r??("string"==typeof e.metadata?void 0:globalThis.Buffer.from(JSON.stringify(e.metadata),"utf8")),n=gb.parse(e),o=t??(e=>this.resolveHCS1Reference(e));let s,a;if("string"==typeof n.metadata?(s=await o(n.metadata),a=yb(pb.parse(JSON.parse(s.toString("utf8"))))):a=yb(pb.parse(n.metadata)),n.metadata_digest){const e=s??i??globalThis.Buffer.from(JSON.stringify(n.metadata),"utf8");if(d.createHash("sha256").update(e).digest("base64url")!==n.metadata_digest.b64u)throw new Error("metadata digest does not match resolved payload")}return a}validateCheckpointChain(e){const t=new Map;for(const r of e){const e=r.effectiveMetadata.stream.registry,i=r.effectiveMetadata.stream.log_id;let n=t.get(e);n||(n=new Map,t.set(e,n));const o=JSON.stringify({registry:e,log_id:i}),s=BigInt(r.effectiveMetadata.root.treeSize),a=n.get(i);if(a){if(s<a.treeSize)throw new Error(`tree size decreased for stream ${o}`);if(s===a.treeSize&&r.effectiveMetadata.root.rootHashB64u!==a.rootHashB64u)throw new Error(`root changed without growing tree size for stream ${o}`);if(!r.effectiveMetadata.prev)throw new Error(`missing prev linkage for stream ${o}`);if(BigInt(r.effectiveMetadata.prev.treeSize)!==a.treeSize)throw new Error(`prev.treeSize mismatch for stream ${o}`);if(r.effectiveMetadata.prev.rootHashB64u!==a.rootHashB64u)throw new Error(`prev.rootHashB64u mismatch for stream ${o}`)}n.set(i,{treeSize:s,rootHashB64u:r.effectiveMetadata.root.rootHashB64u})}}async getCheckpoints(e){const t=await this.mirrorNode.getTopicMessages(e,{order:"asc"}),r=[];for(const n of t)try{const t=gb.parse({p:n.p,op:n.op,metadata:n.metadata,metadata_digest:n.metadata_digest,m:n.m}),i="string"==typeof n.metadata?void 0:globalThis.Buffer.from(JSON.stringify(n.metadata),"utf8"),o=await this.validateCheckpointMessage(t,void 0,i),s=bb(t);r.push({topicId:e,sequence:n.sequence_number,consensusTimestamp:n.consensus_timestamp??"",payer:"string"==typeof n.payer_account_id?n.payer_account_id:n.payer,message:s,effectiveMetadata:o})}catch(i){const e=i instanceof Error?i.message:String(i);this.logger.warn(`Skipping invalid HCS-27 checkpoint message: ${e}`)}return r}async resolveHCS1Reference(e){const t=e.trim();if(!/^hcs:\/\/1\/\d+\.\d+\.\d+$/.test(t))throw new Error(`Invalid HCS-1 reference: ${e}`);const r=await this.hrlResolver.resolveHRL(t,{network:this.network,cdnEndpoint:this.cdnEndpoint,returnRaw:!0});return"string"==typeof r.content?globalThis.Buffer.from(r.content,"utf8"):globalThis.Buffer.from(r.content)}}const Mb=1024;const Ub="hcs-26",Bb=t.z.union([t.z.literal(0),t.z.literal(1),t.z.literal(2)]),Lb=t.z.union([t.z.literal(0),t.z.literal(1),t.z.literal(2),t.z.literal(3)]),Kb=t.z.string().regex(/^[0-9]+\.[0-9]+\.[0-9]+$/),$b=t.z.string().regex(/^hcs:\/\/1\/[0-9]+\.[0-9]+\.[0-9]+$/),Hb=t.z.string().regex(/^(hcs:\/\/1\/[0-9]+\.[0-9]+\.[0-9]+|ipfs:\/\/\S+|ar:\/\/\S+|ord:\/\/\S+)$/),qb=t.z.string().regex(/^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/);const jb=t.z.string().regex(/^hcs:\/\/1\/[0-9]+\.[0-9]+\.[0-9]+$/).optional(),Wb=t.z.union([t.z.string().min(1),t.z.object({name:t.z.string().min(1),contact:t.z.string().min(1).optional(),url:t.z.string().url().optional()}).passthrough()]),Vb=t.z.object({name:t.z.string().min(1),description:t.z.string().min(1),author:Wb,license:t.z.string().min(1),tags:t.z.array(t.z.union([t.z.number().int().positive(),t.z.string().regex(/^(0|[1-9]\d*)$/).transform(e=>Number.parseInt(e,10))])).optional(),homepage:t.z.string().url().optional(),icon:t.z.union([t.z.string().url(),Hb]).optional(),icon_hcs1:jb,languages:t.z.array(t.z.string().min(1)).optional(),capabilities:t.z.array(t.z.string().min(1)).optional(),repo:t.z.string().url().optional(),commit:t.z.string().regex(/^[0-9a-f]{7,64}$/i,"commit must be a git commit SHA").optional()}).passthrough(),Gb=Vb.partial().passthrough(),Jb=t.z.object({p:t.z.literal(Ub),op:t.z.literal("register"),t_id:Kb,account_id:t.z.string().min(1),metadata:t.z.union([Vb,$b]),m:t.z.string().max(500).optional(),sequence_number:t.z.number().int().optional()}).passthrough(),Yb=t.z.object({p:t.z.literal(Ub),op:t.z.literal("register"),version_registry:Kb,publisher:t.z.string().min(1),metadata:t.z.union([Vb,$b]),m:t.z.string().max(500).optional(),sequence_number:t.z.number().int().optional()}).passthrough(),Xb=t.z.object({p:t.z.literal(Ub),op:t.z.literal("update"),uid:t.z.string().min(1),account_id:t.z.string().min(1).optional(),metadata:t.z.union([Gb,$b]).optional(),m:t.z.string().max(500).optional(),sequence_number:t.z.number().int().optional()}).passthrough(),Zb=t.z.object({p:t.z.literal(Ub),op:t.z.literal("update"),uid:t.z.string().min(1),publisher:t.z.string().min(1).optional(),metadata:t.z.union([Gb,$b]).optional(),m:t.z.string().max(500).optional(),sequence_number:t.z.number().int().optional()}).passthrough(),Qb=t.z.object({p:t.z.literal(Ub),op:t.z.literal("delete"),uid:t.z.string().min(1),m:t.z.string().max(500).optional(),sequence_number:t.z.number().int().optional()}).passthrough(),ew=t.z.object({p:t.z.literal(Ub),op:t.z.literal("migrate"),m:t.z.string().max(500).optional(),sequence_number:t.z.number().int().optional()}).passthrough(),tw=t.z.string().regex(/^sha256:[0-9a-f]{64}$/),rw=t.z.object({p:t.z.literal(Ub),op:t.z.literal("register"),skill_uid:t.z.number().int().positive(),version:qb,t_id:Kb,checksum:tw.optional(),status:t.z.enum(["active","deprecated","yanked"]).optional(),m:t.z.string().max(500).optional(),sequence_number:t.z.number().int().optional()}).passthrough(),iw=t.z.object({p:t.z.literal(Ub),op:t.z.literal("register"),skill_uid:t.z.number().int().positive(),version:qb,manifest_hcs1:$b,checksum:tw.optional(),status:t.z.enum(["active","deprecated","yanked"]).optional(),m:t.z.string().max(500).optional(),sequence_number:t.z.number().int().optional()}).passthrough(),nw=t.z.object({p:t.z.literal(Ub),op:t.z.literal("update"),uid:t.z.string().min(1),status:t.z.enum(["active","deprecated","yanked"]).optional(),m:t.z.string().max(500).optional(),sequence_number:t.z.number().int().optional()}).passthrough(),ow=t.z.object({p:t.z.literal(Ub),op:t.z.literal("delete"),uid:t.z.string().min(1),m:t.z.string().max(500).optional(),sequence_number:t.z.number().int().optional()}).passthrough(),sw=t.z.object({p:t.z.literal(Ub),op:t.z.literal("migrate"),m:t.z.string().max(500).optional(),sequence_number:t.z.number().int().optional()}).passthrough(),aw=t.z.object({path:t.z.string().min(1).superRefine((e,r)=>{try{!function(e){const t=e.trim();if(!t)throw new Error("Path must be non-empty");if(t.startsWith("/"))throw new Error("Path must be relative");if(t.includes("\\"))throw new Error('Path must use "/" separators');const r=t.split("/");for(const i of r)if(!i||"."===i||".."===i)throw new Error('Path must be normalized (no ".", "..", or empty segments)')}(e)}catch(i){const e=i instanceof Error?i.message:String(i);r.addIssue({code:t.z.ZodIssueCode.custom,message:e})}}),hrl:$b,sha256:t.z.string().regex(/^[0-9a-f]{64}$/),mime:t.z.string().min(1)}).passthrough(),cw=t.z.object({name:t.z.string().min(1),description:t.z.string().min(1),version:qb,license:t.z.string().min(1),author:Wb,tags:t.z.array(t.z.union([t.z.number().int().positive(),t.z.string().regex(/^(0|[1-9]\d*)$/).transform(e=>Number.parseInt(e,10))])).optional(),homepage:t.z.string().url().optional(),languages:t.z.array(t.z.string().min(1)).optional(),repo:t.z.string().url().optional(),commit:t.z.string().regex(/^[0-9a-f]{7,64}$/i,"commit must be a git commit SHA").optional(),entrypoints:t.z.array(t.z.object({path:t.z.string().min(1),language:t.z.string().min(1),args:t.z.array(t.z.string()).optional()}).passthrough()).optional(),files:t.z.array(aw).min(1)}).passthrough().superRefine((e,r)=>{e.files.some(e=>"SKILL.md"===e.path)||r.addIssue({code:t.z.ZodIssueCode.custom,message:'SKILL.md must be present in the manifest files list with path "SKILL.md".',path:["files"]})}),lw=t.z.union([Jb,Yb,Xb,Zb,Qb,ew]),uw=t.z.union([rw,iw,nw,ow,sw]);function dw(e){const t=e.trim().replace(/^v/i,"").match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/);if(!t)return null;const r=Number(t[1]),i=Number(t[2]),n=Number(t[3]);if(![r,i,n].every(Number.isFinite))return null;const o=t[4];return{major:r,minor:i,patch:n,prerelease:o?o.split(".").map(e=>/^(0|[1-9]\d*)$/.test(e)?Number(e):e):[]}}function pw(e,t){if(e.major!==t.major)return e.major-t.major;if(e.minor!==t.minor)return e.minor-t.minor;if(e.patch!==t.patch)return e.patch-t.patch;const r=e.prerelease.length>0,i=t.prerelease.length>0;if(!r&&i)return 1;if(r&&!i)return-1;if(!r&&!i)return 0;const n=Math.max(e.prerelease.length,t.prerelease.length);for(let o=0;o<n;o+=1){const r=e.prerelease[o],i=t.prerelease[o];if(void 0===r&&void 0!==i)return-1;if(void 0!==r&&void 0===i)return 1;if(r!==i){if("number"==typeof r&&"number"==typeof i)return r-i;if("number"==typeof r&&"string"==typeof i)return-1;if("string"==typeof r&&"number"==typeof i)return 1;if("string"==typeof r&&"string"==typeof i)return r<i?-1:1}}return 0}function hw(e){if("string"!=typeof e)return null;const t=e.trim();return t.length>0?t:null}function gw(e,t){return"number"==typeof e?e:"number"==typeof t?t:null}function mw(e){if(!/^\d+$/.test(e))return null;const t=Number(e);return Number.isSafeInteger(t)?t:null}function fw(e,t){if("string"!=typeof e)throw new Error(`Expected ${t} to be a string`);const r=e.trim();if(!r)throw new Error(`Expected ${t} to be a non-empty string`);return r}function yw(e,t){return t?{...e,...t}:e}function bw(e,t){const r="number"==typeof e.sequence_number?e.sequence_number:"number"==typeof t?t:void 0;return"t_id"in e?{p:"hcs-26",op:"register",t_id:fw(e.t_id,"t_id"),account_id:fw(e.account_id,"account_id"),metadata:e.metadata,...e.m?{m:e.m}:{},..."number"==typeof r?{sequence_number:r}:{}}:{p:"hcs-26",op:"register",t_id:fw(e.version_registry,"version_registry"),account_id:fw(e.publisher,"publisher"),metadata:e.metadata,...e.m?{m:e.m}:{},..."number"==typeof r?{sequence_number:r}:{}}}class ww{constructor(e){this.network=e.network,this.logger=e.logger??y.getInstance({module:"HCS26Resolver",level:"info"}),this.mirrorNode=new x(e.network,this.logger,e.mirrorNode),this.hrlResolver=new Gp("warn")}async resolveDiscoveryMetadataHrl(e,t){const r=await this.hrlResolver.resolve(e,{network:this.network,returnRaw:!0}),i=r.content instanceof ArrayBuffer?globalThis.Buffer.from(r.content):globalThis.Buffer.from(String(r.content),"utf8");let n;try{n=JSON.parse(i.toString("utf8"))}catch{throw new Error("Discovery metadata HRL content is not valid JSON")}const o=("full"===t?Vb:Gb).safeParse(n);if(!o.success)throw new Error(`Invalid discovery metadata: ${o.error.message}`);return this.normalizeDiscoveryMetadataObject(o.data)}normalizeDiscoveryMetadataObject(e){if("string"!=typeof e.icon||0===e.icon.trim().length){const t=e.icon_hcs1;if("string"==typeof t&&t.trim().length>0)return{...e,icon:t}}return e}async resolveDiscoveryMetadataUri(e,t){const r=e.trim();if(r.startsWith("hcs://1/"))return this.resolveDiscoveryMetadataHrl(r,t);throw new Error(`Unsupported discovery metadata URI: ${r}`)}resolveDiscoveryMetadataObject(e){if("string"==typeof e.metadata)return this.resolveDiscoveryMetadataUri(e.metadata,e.mode);const t=("full"===e.mode?Vb:Gb).safeParse(e.metadata);if(!t.success)throw new Error(`Invalid discovery metadata: ${t.error.message}`);return Promise.resolve(this.normalizeDiscoveryMetadataObject(t.data))}async getDiscoveryRegister(e){const t=await this.mirrorNode.getTopicMessages(e.directoryTopicId,{sequenceNumber:`eq:${e.skillUid}`,limit:5,order:"asc"});for(const r of t){const t=Jb.safeParse(r),i=t.success?null:Yb.safeParse(r),n=t.success?t:i&&i.success?i:null;if(!n)continue;const o=bw(n.data,r.sequence_number),s=o.sequence_number;if("number"==typeof s&&s===e.skillUid){const e=await this.resolveDiscoveryMetadataObject({metadata:o.metadata,mode:"full"});return{...o,metadata:e}}}return null}async resolveDiscoveryRecord(e){const t=await this.getDiscoveryRegister({directoryTopicId:e.directoryTopicId,skillUid:e.skillUid});if(!t)return null;const r="number"==typeof e.scanLimit&&e.scanLimit>0?Math.min(5e3,Math.floor(e.scanLimit)):1e3,i=await this.mirrorNode.getTopicMessages(e.directoryTopicId,{limit:r,order:"asc"}),n=String(e.skillUid),o=gw(t.sequence_number,e.skillUid);let s=t;for(const a of i){const e=gw(void 0,a.sequence_number),t=Qb.safeParse(a);if(t.success&&t.data.uid===n){const r=gw(t.data.sequence_number,e);if(null!==o&&null!==r&&r<=o)continue;return null}const r=Xb.safeParse(a),i=r.success?null:Zb.safeParse(a),c=r.success?r:i&&i.success?i:null;if(!c||c.data.uid!==n)continue;const l=gw(c.data.sequence_number,e);if(null!==o&&null!==l&&l<=o)continue;const u="account_id"in c.data?hw(c.data.account_id):hw(c.data.publisher),d=c.data.metadata,p=void 0!==d?await this.resolveDiscoveryMetadataObject({metadata:d,mode:"patch"}):void 0;s={...s,...u?{account_id:u}:{},metadata:yw(s.metadata,p)}}return s}async listVersionRegisters(e){const t="number"==typeof e.limit&&e.limit>0?Math.min(1e3,e.limit):500,r=await this.mirrorNode.getTopicMessages(e.versionRegistryTopicId,{limit:t,order:"desc"}),i=new Map,n=new Map,o=new Map;for(const a of r){const t=rw.safeParse(a),r=t.success?null:iw.safeParse(a),s=t.success?t:r&&r.success?r:null;if(s){if(s.data.skill_uid!==e.skillUid)continue;const t="number"==typeof s.data.sequence_number?String(s.data.sequence_number):"number"==typeof a.sequence_number?String(a.sequence_number):null;if(t){const e=gw(s.data.sequence_number,a.sequence_number);i.set(t,{register:s.data,sequenceNumber:e})}continue}const c=nw.safeParse(a);if(c.success){const e=c.data.uid.trim(),t=n.get(e)??[];t.push({update:c.data,sequenceNumber:gw(c.data.sequence_number,a.sequence_number)}),n.set(e,t);continue}const l=ow.safeParse(a);if(l.success){const e=l.data.uid.trim(),t=o.get(e)??[],r=gw(l.data.sequence_number,a.sequence_number);null!==r&&(t.push(r),o.set(e,t))}}const s=[];for(const[a,c]of i.entries()){const e=c.sequenceNumber??mw(a);if((o.get(a)??[]).some(t=>null===e||t>e))continue;const t=n.get(a);if(!t||0===t.length){s.push(c.register);continue}const r=[...t].filter(t=>null===e||null!==t.sequenceNumber&&t.sequenceNumber>e).sort((e,t)=>(e.sequenceNumber??0)-(t.sequenceNumber??0));if(0===r.length){s.push(c.register);continue}const i=r.reduce((e,t)=>t.update.status?{...e,status:t.update.status}:e,c.register);s.push(i)}return s}async getLatestVersionRegister(e){const t=(await this.listVersionRegisters({versionRegistryTopicId:e.versionRegistryTopicId,skillUid:e.skillUid,limit:100})).filter(e=>{return!(t=e.status)||"active"===t;var t});if(0===t.length)return null;let r=t[0],i=dw(r.version);for(let n=1;n<t.length;n+=1){const e=t[n],o=dw(e.version);if(i||!o){if(i&&o){const t=pw(o,i);if(t>0){r=e,i=o;continue}if(0===t){const t="number"==typeof r.sequence_number?r.sequence_number:0;("number"==typeof e.sequence_number?e.sequence_number:0)>t&&(r=e,i=o)}}}else r=e,i=o}return r}async resolveManifest(e){const t="string"==typeof e.manifestHrl&&e.manifestHrl.trim().length>0?e.manifestHrl.trim():"string"==typeof e.manifestTopicId&&e.manifestTopicId.trim().length>0?`hcs://1/${e.manifestTopicId.trim()}`:null;if(!t)throw new Error("Manifest HRL or topic id is required");const r=await this.hrlResolver.resolve(t,{network:this.network,returnRaw:!0});if(!(r.contentType??"").toLowerCase().startsWith("application/json"))throw new Error(`Expected application/json for manifest, got ${r.contentType??"unknown"}`);const i=r.content instanceof ArrayBuffer?globalThis.Buffer.from(r.content):globalThis.Buffer.from(String(r.content),"utf8"),n=await ah(i,"sha256");let o;try{o=JSON.parse(i.toString("utf8"))}catch{throw new Error("Manifest content is not valid JSON")}const s=cw.safeParse(o);if(!s.success)throw new Error(`Invalid HCS-26 manifest: ${s.error.message}`);if(!s.data.files.some(e=>"SKILL.md"===e.path))throw new Error('HCS-26 manifest must include SKILL.md at path "SKILL.md"');return{manifest:s.data,raw:o,sha256Hex:n}}async verifyVersionRegisterMatchesManifest(e){const t=e.versionRegister.checksum;if(!t)return void this.logger.warn("HCS-26 version register is missing checksum; skipping manifest verification.");const r=t.trim();if(!r.startsWith("sha256:"))throw new Error(`Unsupported checksum: ${r}`);const i=r.slice(7);if(e.manifestSha256Hex!==i)throw new Error(`Manifest checksum mismatch (expected ${i}, got ${e.manifestSha256Hex})`)}}function Iw(e){const t=e.trim();if(!t)return null;const r=t.match(/^hcs-26:(\d+):(\d+):(\d+)$/);if(!r)return null;const i=Number(r[1]),n=Number(r[2]),o=Number(r[3]);if(![i,n,o].every(Number.isFinite))return null;const s=Bb.safeParse(o);return s.success?0!==i&&1!==i?null:{protocol:Ub,indexed:0===i,ttlSeconds:n,topicType:s.data}:null}function Tw(e){const t=e.trim();if(!t)return null;const r=t.match(/^hcs-26:op:(\d+):(\d+)$/);if(!r)return null;const i=Number(r[1]),n=Number(r[2]);if(![i,n].every(Number.isFinite))return null;const o=Lb.safeParse(i);if(!o.success)return null;const s=Bb.safeParse(n);return s.success?{protocol:Ub,operation:o.data,topicType:s.data}:null}const Sw=t.z.string().transform(e=>{const t=Iw(e);if(!t)throw new Error("Invalid HCS-26 topic memo");return t}),kw=t.z.string().transform(e=>{const t=Tw(e);if(!t)throw new Error("Invalid HCS-26 transaction memo");return t});function vw(e){const t=e.t_id;if("string"==typeof t&&t.trim())return t.trim();const r=e.manifest_hcs1;if("string"!=typeof r||!r.trim())throw new Error("Missing manifest reference in version register entry");const i=r.trim(),n="hcs://1/";if(!i.startsWith(n))throw new Error(`Invalid manifest HRL: ${i}`);return i.slice(8)}class Ew{constructor(e){this.network=e.network,this.logger=e.logger??y.getInstance({module:"HCS26Client",level:"info"}),this.verificationProvider=e.verificationProvider,this.resolver=new ww({network:this.network,logger:this.logger,mirrorNode:e.mirrorNode})}async resolveSkill(e){const t=await this.resolver.resolveDiscoveryRecord({directoryTopicId:e.directoryTopicId,skillUid:e.skillUid,scanLimit:e.discoveryScanLimit});if(!t)return null;const r=t.t_id,i=await this.resolver.getLatestVersionRegister({versionRegistryTopicId:r,skillUid:e.skillUid});if(!i)throw new Error(`No active version entries found for skill ${e.skillUid} in version registry ${r}`);const n=vw(i),{manifest:o,sha256Hex:s}=await this.resolver.resolveManifest({manifestTopicId:n});let a;await this.resolver.verifyVersionRegisterMatchesManifest({versionRegister:i,manifestSha256Hex:s});const c=this.verificationProvider,l=!0===e.includeVerification,u="string"==typeof t.metadata?.name?t.metadata.name.trim():"";if(l&&c&&u)try{a=await c.getSkillVerificationStatus({name:u})}catch(d){const e=d instanceof Error?d.message:String(d);this.logger.warn(`Failed to resolve verification status for skill "${u}": ${e}`),a=null}return{directoryTopicId:e.directoryTopicId,skillUid:e.skillUid,discovery:t,versionRegistryTopicId:r,latestVersion:i,manifest:o,manifestSha256Hex:s,...l?{verification:a}:{}}}async listSkillVersions(e){const t=await this.resolver.resolveDiscoveryRecord({directoryTopicId:e.directoryTopicId,skillUid:e.skillUid,scanLimit:e.discoveryScanLimit});if(!t)return[];const r=t.t_id;return this.resolver.listVersionRegisters({versionRegistryTopicId:r,skillUid:e.skillUid,limit:e.limit})}async resolveSkillVersion(e){const t=e.version.trim();if(!t)throw new Error("version is required");const r=await this.resolver.resolveDiscoveryRecord({directoryTopicId:e.directoryTopicId,skillUid:e.skillUid,scanLimit:e.discoveryScanLimit});if(!r)return null;const i=r.t_id,n=(await this.resolver.listVersionRegisters({versionRegistryTopicId:i,skillUid:e.skillUid,limit:250})).find(e=>e.version.trim()===t);if(!n)return null;const o=vw(n),{manifest:s,sha256Hex:a}=await this.resolver.resolveManifest({manifestTopicId:o});let c;await this.resolver.verifyVersionRegisterMatchesManifest({versionRegister:n,manifestSha256Hex:a});const l=this.verificationProvider,u=!0===e.includeVerification,d="string"==typeof r.metadata?.name?r.metadata.name.trim():"";if(u&&l&&d)try{c=await l.getSkillVerificationStatus({name:d})}catch(p){const e=p instanceof Error?p.message:String(p);this.logger.warn(`Failed to resolve verification status for skill "${d}": ${e}`),c=null}return{directoryTopicId:e.directoryTopicId,skillUid:e.skillUid,discovery:r,versionRegistryTopicId:i,versionEntry:n,manifest:s,manifestSha256Hex:a,...u?{verification:c}:{}}}}function Aw(e){return{getSkillVerificationStatus:async t=>function(e){const t=e.pendingRequest??void 0;return{name:e.name,verified:e.verified,previouslyVerified:e.previouslyVerified,...t?{pendingRequest:t}:{}}}(await Hp(e,{name:t.name}))}}var Cw=(e=>(e.FIXED_FEE="FIXED_FEE",e.FRACTIONAL_FEE="FRACTIONAL_FEE",e.ROYALTY_FEE="ROYALTY_FEE",e))(Cw||{});class Rw{constructor(e){this.customFees=[],this.logger=e.logger,this.mirrorNode=new x(e.network,e.logger),this.defaultCollectorAccountId=e.defaultCollectorAccountId||""}static forHbar(e,t,r,i,n=[]){return new Rw({network:r,logger:i,defaultCollectorAccountId:t}).addHbarFee(e,t,n)}static async forToken(e,t,r,i,n,o=[],s){const a=new Rw({network:i,logger:n,defaultCollectorAccountId:r});return await a.addTokenFee(e,t,r,s,o),a}addHbarFee(e,t,r=[]){if(e<=0)throw new Error("HBAR amount must be greater than zero");return this.customFees.push({feeAmount:{amount:1e8*e,decimals:0},feeCollectorAccountId:t||this.defaultCollectorAccountId,feeTokenId:void 0,exemptAccounts:[...r],type:Cw.FIXED_FEE}),this}async addTokenFee(e,t,r,i,n=[]){if(e<=0)throw new Error("Token amount must be greater than zero");if(!t)throw new Error("Fee token ID is required when adding a token fee");let o=i;if(void 0===o)try{const e=await this.mirrorNode.getTokenInfo(t);e?.decimals?(o=parseInt(e.decimals,10),this.logger.info(`Fetched decimals for ${t}: ${o}`)):(this.logger.warn(`Could not fetch decimals for ${t}, defaulting to 0.`),o=0)}catch(s){this.logger.error(`Error fetching decimals for ${t}, defaulting to 0: ${s}`),o=0}return this.customFees.push({feeAmount:{amount:e*10**o,decimals:o},feeCollectorAccountId:r||this.defaultCollectorAccountId,feeTokenId:t,exemptAccounts:[...n],type:Cw.FIXED_FEE}),this}build(){if(0===this.customFees.length)throw new Error("At least one fee must be added using addHbarFee/addTokenFee or created using forHbar/forToken");if(this.customFees.length>10)throw new Error("Maximum of 10 custom fees per topic allowed");const e=new Set;this.customFees.forEach(t=>{t.exemptAccounts.forEach(t=>e.add(t))});return{customFees:this.customFees.map(e=>({...e,feeCollectorAccountId:e.feeCollectorAccountId||this.defaultCollectorAccountId})),exemptAccounts:Array.from(e)}}}class xw{constructor(){this.resolver=null,this.onUnavailableCallbacks=[],this.logger=y.getInstance({module:"ContentResolverRegistry"})}static getInstance(){return xw._instance||(xw._instance=new xw),xw._instance}register(e){this.resolver&&this.logger.warn("Resolver already registered, replacing existing"),this.resolver=e,this.logger.info("Content resolver registered")}getResolver(){return this.resolver}isAvailable(){return null!==this.resolver}unregister(){this.resolver&&(this.resolver=null,this.logger.info("Content resolver unregistered"),this.onUnavailableCallbacks.forEach(e=>{try{e()}catch(t){this.logger.error("Error in unavailable callback:",t)}}))}onUnavailable(e){this.onUnavailableCallbacks.push(e)}offUnavailable(e){const t=this.onUnavailableCallbacks.indexOf(e);-1!==t&&this.onUnavailableCallbacks.splice(t,1)}async withResolver(e,t){if(!this.resolver)return this.logger.warn("No resolver available, using fallback"),await t();try{return await e(this.resolver)}catch(r){return this.logger.warn("Resolver operation failed, using fallback:",r),await t()}}}const Nw=xw.getInstance();class zw{constructor(){this.contentStore=null,this.logger=y.getInstance({module:"ContentStoreService"})}static getInstance(){return zw._instance||(zw._instance=new zw),zw._instance}async setInstance(e){this.contentStore&&this.logger.warn("Content store already set, replacing"),this.contentStore=e,this.logger.info("Content store instance set")}getInstance(){return this.contentStore}dispose(){this.contentStore=null,this.logger.info("Content store disposed")}isAvailable(){return null!==this.contentStore}}const _w=zw.getInstance();exports.AIAgentCapability=Ih,exports.AIAgentDetailsSchema=Rh,exports.AIAgentProfileSchema=Mh,exports.AIAgentType=bh,exports.AID_DNS_WEB_PROFILE_ID=Dm,exports.ANS_DNS_WEB_PROFILE_ID=jm,exports.AccountCreationError=ag,exports.ActionBuilder=class{constructor(e){this.cryptoAdapter=sh(),this.logger=e,this.registration={p:"hcs-12",op:"register"}}setTopicId(e){if(!this.isValidTopicId(e))throw new Error("Invalid topic ID format");return this.registration.t_id=e,this}setAlias(e){return this.alias=e,this}setHash(e){if(!this.isValidHash(e))throw new Error("Invalid hash format");return this.registration.hash=e,this}setWasmHash(e){if(!this.isValidHash(e))throw new Error("Invalid hash format");return this.registration.wasm_hash=e,this}setInfoTopicId(e){if(!this.isValidTopicId(e))throw new Error("Invalid topic ID format");return this.registration.info_t_id=e,this}setJsTopicId(e){if(!this.isValidTopicId(e))throw new Error("Invalid topic ID format");return this.registration.js_t_id=e,this}setJsHash(e){if(!this.isValidHash(e))throw new Error("Invalid hash format");return this.registration.js_hash=e,this}setInterfaceVersion(e){if(!this.isValidVersion(e))throw new Error("Invalid version format");return this.registration.interface_version=e,this}addValidationRule(e,t){return this.registration.validation_rules||(this.registration.validation_rules={}),this.registration.validation_rules[e]=t,this}setSourceVerification(e){if(!this.isValidTopicId(e.source_t_id))throw new Error("Invalid source topic ID");if(!this.isValidHash(e.source_hash))throw new Error("Invalid source hash");if("wasm32-unknown-unknown"!==e.target)throw new Error("Invalid compilation target");return this.registration.source_verification=e,this}build(e={validate:!0}){return!1!==e.validate&&this.validate(),{...this.registration}}reset(){return this.registration={p:"hcs-12",op:"register"},this.alias=void 0,this}getAlias(){if(!this.alias)throw new Error("Action alias not set");return this.alias}getTopicId(){if(!this.registration.t_id)throw new Error("Action topic ID not set");return this.registration.t_id}async generateWasmHash(e){if(Qp())return this.createSSRSafeHash(e,"wasm");const t=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(e)).digest("hex"),r=t instanceof Promise?await t:t;return"string"==typeof r?r:r.toString("hex")}async generateInfoHash(e){const t=JSON.stringify(e,Object.keys(e).sort());if(Qp())return this.createSSRSafeHash(globalThis.Buffer.from(t),"info");const r=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(t)).digest("hex"),i=r instanceof Promise?await r:r;return"string"==typeof i?i:i.toString("hex")}async calculateHash(e){const t="string"==typeof e||e instanceof Uint8Array?globalThis.Buffer.from(e):e;if(Qp())return this.createSSRSafeHash(t,"data");const r=this.cryptoAdapter.createHash("sha256").update(t).digest("hex"),i=r instanceof Promise?await r:r;return"string"==typeof i?i:i.toString("hex")}createSSRSafeHash(e,t){const r=e instanceof Uint8Array?globalThis.Buffer.from(e):e;let i=0;for(let n=0;n<Math.min(r.length,256);n++)i=(i<<5)-i+r[n]&4294967295;return`ssr-${t}-${r.length}-${Math.abs(i).toString(16).padStart(8,"0")}`}async createFromWasmAndInfo(e,t,r){const i=await this.generateWasmHash(t),n=await this.generateInfoHash(r),o=this.registration.js_t_id,s=this.registration.js_hash,a=this.registration.interface_version;return this.reset().setTopicId(e).setHash(n).setWasmHash(i),o&&this.setJsTopicId(o),s&&this.setJsHash(s),a&&this.setInterfaceVersion(a),this.build()}isComplete(e){return!!("hcs-12"===e.p&&"register"===e.op&&e.t_id&&e.hash&&e.wasm_hash)}validate(){if(!this.registration.t_id)throw new Error("Topic ID is required");if(!this.registration.hash)throw new Error("INFO hash is required");if(!this.registration.wasm_hash)throw new Error("WASM hash is required")}isValidTopicId(e){return/^\d+\.\d+\.\d+$/.test(e)}isValidHash(e){return/^[a-f0-9]{64}$/.test(e)}isValidVersion(e){return/^\d+\.\d+\.\d+$/.test(e)}},exports.ActionRegistry=Lg,exports.AgentBuilder=ug,exports.AidDnsWebProfileResolver=Bm,exports.AnsDnsWebProfileResolver=Jm,exports.AssemblyBuilder=class{constructor(e){this.registration={p:"hcs-12",op:"register"},this.operations=[],this.updateFields={p:"hcs-12",op:"update"},this.logger=e||new y({module:"AssemblyBuilder"})}setName(e){if(!this.isValidName(e))throw new Error("Invalid assembly name format");return this.registration.name=e,this}setVersion(e){if(!this.isValidSemver(e))throw new Error("Invalid semantic version");return this.registration.version=e,this}setDescription(e){return this.registration.description=e,this.updateFields&&(this.updateFields.description=e),this}setTags(e){return this.registration.tags=e,this.updateFields&&(this.updateFields.tags=e),this}addTag(e){return this.registration.tags||(this.registration.tags=[]),this.updateFields.tags||(this.updateFields.tags=[]),this.registration.tags.push(e),this.updateFields.tags.push(e),this}setAuthor(e){return this.registration.author=e,this}addAction(e){const t=e.getTopicId(),r=e.getAlias();if(!this.isValidAlias(r))throw new Error("Invalid alias format");const i={p:"hcs-12",op:"add-action",t_id:t,alias:r};return this.operations.push(i),this}addBlock(e){const t=e.getTopicId();if(!this.isValidTopicId(t))throw new Error(`Invalid block topic ID: ${t}`);const r=e.build(),i=e.getActions(),n=this.extractDefaultAttributes(r.attributes);if(i&&Object.keys(i).length>0)for(const[s,a]of Object.entries(i))if(!this.isValidTopicId(a))throw new Error(`Invalid action topic ID for "${s}": ${a}`);const o={p:"hcs-12",op:"add-block",block_t_id:t,...Object.keys(i).length>0&&{actions:i},attributes:n};return this.operations.push(o),this}updateMetadata(e,t){const r={p:"hcs-12",op:"update",description:e,tags:t};return this.operations.push(r),this}build(){if(!this.registration.name)throw new Error("Assembly name is required");if(!this.registration.version)throw new Error("Assembly version is required");return{...this.registration}}buildUpdate(){const e={p:"hcs-12",op:"update"};return void 0!==this.updateFields.description&&(e.description=this.updateFields.description),void 0!==this.updateFields.tags&&(e.tags=this.updateFields.tags),e}buildOperations(){return[...this.operations]}reset(){return this.registration={p:"hcs-12",op:"register"},this.operations=[],this.updateFields={p:"hcs-12",op:"update"},this}getRegistration(){return this.build()}getOperations(){return this.buildOperations()}buildPreview(){const e=[],t=[];for(const r of this.operations)switch(r.op){case"add-action":e.push({t_id:r.t_id,alias:r.alias,config:r.config,data:r.data});break;case"add-block":t.push({block_t_id:r.block_t_id,actions:r.actions,attributes:r.attributes,children:r.children,data:r.data});break;case"update":r.description&&(this.registration.description=r.description),r.tags&&(this.registration.tags=r.tags)}return{topicId:"",name:this.registration.name,version:this.registration.version,description:this.registration.description,tags:this.registration.tags,author:this.registration.author,actions:e,blocks:t,created:(new Date).toISOString(),updated:(new Date).toISOString()}}validate(){const e=[];this.registration.name||e.push("Assembly name is required"),this.registration.version||e.push("Assembly version is required"),this.registration.version&&!this.isValidSemver(this.registration.version)&&e.push("Invalid semantic version format");const t=new Set;for(const i of this.operations)"add-action"===i.op?(t.has(i.alias)?e.push(`Duplicate alias: ${i.alias}`):t.add(i.alias),this.isValidTopicId(i.t_id)||e.push(`Invalid topic ID for ${i.alias}: ${i.t_id}`),this.isValidAlias(i.alias)||e.push(`Invalid alias format: ${i.alias}`)):"add-block"===i.op&&(this.isValidTopicId(i.block_t_id)||e.push(`Invalid block topic ID: ${i.block_t_id}`));const r=new Set;this.operations.filter(e=>"add-action"===e.op).forEach(e=>r.add(e.alias));for(const i of this.operations)if("add-block"===i.op&&i.actions)for(const[t,r]of Object.entries(i.actions))this.isValidTopicId(r)||e.push(`Block ${i.block_t_id} has invalid action topic ID for key ${t}: ${r}`);return{valid:0===e.length,errors:e}}isValidSemver(e){return/^\d+\.\d+\.\d+(-[\w\.\+]+)?$/.test(e)}isValidTopicId(e){return/^\d+\.\d+\.\d+$/.test(e)}isValidAlias(e){return/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(e)&&e.length>=2&&e.length<=50}isValidName(e){return/^[a-z0-9-]+$/.test(e)&&e.length>=2&&e.length<=100}extractDefaultAttributes(e){if(!e)return{};const t={};for(const[r,i]of Object.entries(e))i&&"object"==typeof i&&"default"in i&&(t[r]=i.default);return t}},exports.AssemblyEngine=qg,exports.AssemblyRegistry=$g,exports.BaseProfileSchema=Dh,exports.BaseRegistry=Tg,exports.BlockBuilder=Wg,exports.BlockLoader=Kg,exports.BlockRenderer=class{constructor(e,t,r,i){this.MAX_DEPTH=10,this.logger=e,this.gutenbergBridge=t,this.templateEngine=r,this.stateManager=i,this.hashLinkScanner=new Gg(e)}async render(e,t={}){try{this.currentBlock=e,this.currentOptions=t,t.assembly&&(this.assembly=t.assembly),t.actionRegistry&&(this.actionRegistry=t.actionRegistry),t.network&&!this.wasmExecutor&&(this.wasmExecutor=new Vg(this.logger,t.network)),t.initialState&&this.stateManager.setBlockState(e.id,t.initialState);let r=this.stateManager.getBlockState(e.id)||{attributes:{},actionResults:{}};r.attributes&&"object"==typeof r.attributes||(this.logger.warn("Invalid state structure, fixing...",{state:r}),r={attributes:r||{},actionResults:{}});let i={},n=e.attributes||{};if(this.assembly){const t=this.assembly.state?.blocks?.find(t=>t.block_t_id===e.id||t.block_t_id===e.t_id);t&&(i=t.actions||{},n={...t.attributes,...n})}const o={};e.attributes&&Object.entries(e.attributes).forEach(([e,t])=>{t&&"object"==typeof t&&"default"in t&&(o[e]=t.default)});const s={...o};n&&"object"==typeof n&&Object.entries(n).forEach(([e,t])=>{"object"==typeof t&&null!==t||(s[e]=t)}),r.attributes&&"object"==typeof r.attributes&&Object.entries(r.attributes).forEach(([e,t])=>{"object"==typeof t&&null!==t||(s[e]=t)}),r.attributes={...s},this.stateManager.setBlockState(e.id,r);const a={attributes:s,actions:i,blockId:e.id,actionResults:r.actionResults||{}};this.logger.debug("Template context",{blockId:e.id,attributes:a.attributes,hasActions:!!i,actionKeys:Object.keys(i),rawState:r,mergedAttributes:s});let c=await this.templateEngine.render(e.template||"",a);if(this.shouldProcessHashLinks(t)&&(c=await this.processHashLinks(c,e,t)),t.container&&"undefined"!=typeof window){const r="string"==typeof t.container?document.querySelector(t.container):t.container;if(r instanceof HTMLElement)return r.innerHTML=c,e.styles&&this.applyStyles(e.id,e.styles),this.setupEventHandlers(r,e.id),{element:r,html:c,cleanup:()=>this.cleanup(e.id)}}return{html:c}}catch(r){throw this.logger.error("Block render failed",{blockId:e.id,error:r}),r}}applyStyles(e,t){if("undefined"==typeof document)return;const r=`hashlink-styles-${e}`;let i=document.getElementById(r);i||(i=document.createElement("style"),i.id=r,document.head.appendChild(i)),i.textContent=t}setupEventHandlers(e,t){this.stateManager.onStateChange(t,t=>{this.updateBlockUI(e,t)}),e.querySelectorAll("[data-action]").forEach(e=>{e.addEventListener("click",async r=>{r.preventDefault();const i=e.dataset.action,n=e.dataset.params;this.logger.debug("Action button clicked",{actionTopicId:i,paramsStr:n,hasAction:!!i}),i&&await this.executeAction(t,i,n)})})}async updateBlockDisplay(e,t){try{this.logger.debug("updateBlockDisplay called",{blockId:e,newState:t});const r=document.querySelector(`[data-block-id="${e}"]`);if(!r||!r.parentElement)return void this.logger.warn("Block element not found for re-render",{blockId:e});const i=r.parentElement;if(this.currentBlock&&this.currentBlock.id===e&&this.currentOptions){const r={...this.currentOptions,container:i,initialState:t};await this.render(this.currentBlock,r);this.logger.debug("Block re-rendered with updated state",{blockId:e,newState:t})}}catch(r){this.logger.error("Failed to re-render block",{blockId:e,error:r.message})}}async executeAction(e,t,r){try{this.logger.debug("Executing action",{blockId:e,actionTopicId:t});let i={};if(r)try{i=JSON.parse(r)}catch(Pw){this.logger.warn("Failed to parse action params",{paramsStr:r})}const n=this.stateManager.getBlockState(e)||{attributes:{},actionResults:{}};if(this.wasmExecutor&&this.actionRegistry){this.logger.debug("Looking up action in registry",{actionTopicId:t});const r=await this.actionRegistry.getActionByTopicId(t);if(this.logger.debug("Action lookup result",{found:!!r,actionTopicId:t,actionData:r}),!r)throw new Error(`Action not found: ${t}`);this.logger.debug("Executing WASM",{actionData:r,params:i,state:n.attributes});const o=await this.wasmExecutor.execute(r,{method:"POST",params:i,state:n.attributes});if(this.logger.debug("WASM execution result",{result:o}),o.success&&o.data){const t=i.operation||"default";let r=o.data;r.success&&r.data&&(r=r.data);const s={...n,attributes:{...n.attributes,...r},actionResults:{...n.actionResults,[t]:r}};this.stateManager.updateBlockState(e,s),await this.updateBlockDisplay(e,s)}else this.logger.error("Action execution failed",{result:o})}else this.stateManager.sendMessage(e,"action",{action:t,params:i})}catch(i){this.logger.error("Failed to execute action",{blockId:e,actionTopicId:t,error:i.message}),this.stateManager.sendMessage(e,"action-error",{action:t,error:i.message})}}updateBlockUI(e,t){Object.entries(t).forEach(([t,r])=>{e.querySelectorAll(`[data-bind="${t}"]`).forEach(e=>{e instanceof HTMLElement&&(e.textContent=String(r))})})}cleanup(e){const t=document.getElementById(`hashlink-styles-${e}`);t&&t.remove(),this.stateManager.removeBlockState(e)}shouldProcessHashLinks(e){const t=e.depth||0,r=e.maxDepth||this.MAX_DEPTH;return t>=r?(this.logger.warn("Max render depth reached, skipping HashLink processing",{depth:t,maxDepth:r}),!1):!(!e.network||!e.blockLoader&&!this.blockLoader)}ensureHashLinkResolver(e){!this.hashLinkResolver&&e.network&&(this.blockLoader=e.blockLoader||this.blockLoader,this.hrlResolver=e.hrlResolver||this.hrlResolver,this.blockLoader&&this.hrlResolver&&(this.hashLinkResolver=new Jg(this.logger,this.blockLoader,this.hrlResolver,e.network)))}async processHashLinks(e,t,r){if(this.ensureHashLinkResolver(r),!this.hashLinkResolver)return this.logger.warn("HashLink resolver not available, skipping processing"),e;this.hashLinkResolver.pushRenderStack(t.id);try{const n=await this.hashLinkScanner.scanTemplate(e);if(0===n.length)return e;this.logger.debug("Processing HashLinks",{parentBlockId:t.id,referenceCount:n.length});const o={blockId:t.id,depth:(r.depth||0)+1,parentContext:r.parentContext,attributes:r.initialState?.attributes||{},actions:{},assembly:this.assembly,maxDepth:r.maxDepth||this.MAX_DEPTH};if(this.assembly){const e=this.assembly.state?.blocks?.find(e=>e.block_t_id===t.id||e.block_t_id===t.t_id);e?.actions&&(o.actions=e.actions)}let s=e;for(let e=0;e<n.length;e++){const t=n[e];try{const e=await this.hashLinkResolver.resolveReference(t,o);if(e.error){this.logger.error("Failed to resolve HashLink",{uri:t.uri,error:e.error});const r=`\x3c!-- HashLink Error: ${e.error} --\x3e`;s=s.replace(t.placeholder,r);continue}let i;if(e.definition){const t={id:e.blockId,template:e.template||"",attributes:e.definition.attributes,p:"hcs-12",op:"register",name:e.definition.name,version:"1.0.0",title:e.definition.title,description:e.definition.description},n={attributes:e.attributes,actionResults:{}},s={attributes:e.attributes,actions:e.actions,blockId:e.blockId,actionResults:{}};if(e.template){i=await this.templateEngine.render(e.template,s);const a={...r,depth:o.depth,parentContext:o,initialState:n};this.shouldProcessHashLinks(a)&&(i=await this.processHashLinks(i,t,a))}else i="\x3c!-- Block has no template --\x3e"}else i=e.template?e.template:"\x3c!-- Empty block --\x3e";"lazy"===t.loading&&(i=this.wrapLazyLoad(i,t)),s=s.replace(t.placeholder,i)}catch(i){this.logger.error("Error processing HashLink",{uri:t.uri,error:i.message});const e=`\x3c!-- HashLink Error: ${i.message} --\x3e`;s=s.replace(t.placeholder,e)}}return s}finally{this.hashLinkResolver.popRenderStack(t.id)}}wrapLazyLoad(e,t){return`\n <div id="${`lazy-${t.uri.replace(/[^a-zA-Z0-9]/g,"-")}`}" class="hashlink-lazy-container" data-hashlink-lazy="${t.uri}">\n <div class="hashlink-lazy-placeholder">Loading...</div>\n <template class="hashlink-lazy-content">${e}</template>\n </div>\n `}},exports.BlockStateManager=class{constructor(e){this.blockStates=new Map,this.stateListeners=new Map,this.messageHandlers=new Map,this.schemas=new Map,this.persistentBlocks=new Set,this.unusedBlocks=new Set,this.maxBlockStates=1e3,this.logger=e}createBlockState(e,t){for(this.logger.debug("Creating block state",{blockId:e}),this.schemas.has(e)&&this.validateState(e,t);this.blockStates.size>=this.maxBlockStates;)this.unusedBlocks.size>0?this.cleanupUnusedStates():this.evictOldestBlock();this.blockStates.set(e,{...t}),this.logger.debug("Block state created",{blockId:e,stateKeys:Object.keys(t)})}getBlockState(e){return this.blockStates.has(e)?{...this.blockStates.get(e)}:null}hasBlockState(e){return this.blockStates.has(e)}updateBlockState(e,t){if(!this.blockStates.has(e))throw new Error(`Block state not found: ${e}`);const r={...this.blockStates.get(e)},i={...r,...t};this.schemas.has(e)&&this.validateState(e,i),this.blockStates.set(e,i);const n=this.stateListeners.get(e)||[];for(const s of n)try{s(i,r,e)}catch(o){this.logger.error("State change listener error",{blockId:e,error:o})}this.logger.debug("Block state updated",{blockId:e,updates:t})}destroyBlockState(e){this.logger.debug("Destroying block state",{blockId:e}),this.blockStates.delete(e),this.stateListeners.delete(e),this.messageHandlers.delete(e),this.schemas.delete(e),this.persistentBlocks.delete(e),this.unusedBlocks.delete(e),this.logger.debug("Block state destroyed",{blockId:e})}onStateChange(e,t){this.stateListeners.has(e)||this.stateListeners.set(e,[]),this.stateListeners.get(e).push(t)}removeStateChangeListener(e,t){const r=this.stateListeners.get(e);if(r){const e=r.indexOf(t);e>-1&&r.splice(e,1)}}onBlockMessage(e,t){this.messageHandlers.has(e)||this.messageHandlers.set(e,[]),this.messageHandlers.get(e).push(t)}sendBlockMessage(e,t,r,i){const n={type:r,payload:i,fromBlock:e,toBlock:t},o=this.messageHandlers.get(t)||[];for(const a of o)try{a(n)}catch(s){this.logger.error("Block message handler error",{fromBlock:e,toBlock:t,type:r,error:s})}this.logger.debug("Block message sent",{fromBlock:e,toBlock:t,type:r})}broadcastMessage(e,t){for(const i of this.blockStates.keys()){const n=this.messageHandlers.get(i)||[],o={type:e,payload:t,fromBlock:"system",toBlock:i};for(const t of n)try{t(o)}catch(r){this.logger.error("Broadcast message handler error",{blockId:i,type:e,error:r})}}this.logger.debug("Message broadcasted",{type:e,blockCount:this.blockStates.size})}async bindActionResult(e,t,r,i){if(!this.blockStates.has(e))throw new Error(`Block state not found: ${e}`);const n=this.getBlockState(e);let o;try{if(r.success&&i.onSuccess)o=i.onSuccess(n,r);else{if(r.success||!i.onError)return;o=i.onError(n,r)}o&&this.updateBlockState(e,o),this.logger.debug("Action result bound to state",{blockId:e,actionName:t,success:r.success})}catch(s){throw this.logger.error("Action result binding failed",{blockId:e,actionName:t,error:s}),s}}async persistBlockState(e){if(!this.storageBackend)return this.logger.warn("No storage backend configured"),void this.persistentBlocks.add(e);if(!this.blockStates.has(e))throw new Error(`Block state not found: ${e}`);try{const t=this.blockStates.get(e);await this.storageBackend.setItem(e,JSON.stringify(t)),this.persistentBlocks.add(e),this.logger.debug("Block state persisted",{blockId:e})}catch(t){this.logger.error("Failed to persist block state",{blockId:e,error:t})}}async restoreBlockState(e){if(this.storageBackend)try{const t=await this.storageBackend.getItem(e);if(t){const r=JSON.parse(t);this.blockStates.set(e,r),this.persistentBlocks.add(e),this.logger.debug("Block state restored",{blockId:e})}}catch(t){this.logger.error("Failed to restore block state",{blockId:e,error:t})}else this.logger.warn("No storage backend configured")}isPersistent(e){return this.persistentBlocks.has(e)}setStorageBackend(e){this.storageBackend=e}setBlockStateSchema(e,t){this.schemas.set(e,t),this.logger.debug("Block state schema set",{blockId:e})}setMaxBlockStates(e){this.maxBlockStates=e}getActiveBlockCount(){return this.blockStates.size}markBlockUnused(e){this.unusedBlocks.add(e)}cleanupUnusedStates(){for(const e of this.unusedBlocks)this.destroyBlockState(e);this.unusedBlocks.clear(),this.logger.debug("Unused states cleaned up")}evictOldestBlock(){for(const e of this.blockStates.keys())if(!this.persistentBlocks.has(e))return this.destroyBlockState(e),void this.logger.debug("Evicted block to make room",{blockId:e});this.logger.warn("Cannot evict blocks - all are persistent")}getListenerCount(e){return(this.stateListeners.get(e)?.length||0)+(this.messageHandlers.get(e)?.length||0)}validateState(e,t){const r=this.schemas.get(e);if(r&&"object"===r.type){if("object"!=typeof t||null===t)throw new Error("State validation failed: expected object");if(r.required)for(const e of r.required)if(!(e in t))throw new Error(`State validation failed: missing required property '${e}'`);if(r.properties)for(const[e,i]of Object.entries(r.properties))if(e in t){const r=t[e],n=i.type;if("string"===n&&"string"!=typeof r)throw new Error(`State validation failed: property '${e}' must be string`);if("number"===n&&"number"!=typeof r)throw new Error(`State validation failed: property '${e}' must be number`);if("number"===n&&void 0!==i.minimum&&r<i.minimum)throw new Error(`State validation failed: property '${e}' below minimum`)}}}setBlockState(e,t){this.blockStates.has(e)?this.updateBlockState(e,t):this.createBlockState(e,t)}removeBlockState(e){this.blockStates.delete(e),this.stateListeners.delete(e),this.messageHandlers.delete(e),this.persistentBlocks.delete(e),this.schemas.delete(e),this.storageBackend&&this.storageBackend.removeItem(e).catch(t=>{this.logger.error("Failed to remove persisted state",{blockId:e,error:t})}),this.logger.debug("Block state removed",{blockId:e})}sendMessage(e,t,r,i="system"){const n=this.messageHandlers.get(e)||[],o={type:t,payload:r,fromBlock:i,toBlock:e};for(const a of n)try{a(o)}catch(s){this.logger.error("Message handler error",{blockId:e,type:t,error:s})}}},exports.BrowserHCS20Client=class extends Yf{constructor(e){super({network:e.network,logger:e.logger,mirrorNodeUrl:e.mirrorNodeUrl,registryTopicId:e.registryTopicId,publicTopicId:e.publicTopicId}),this.hwc=e.hwc,this.feeAmount=e.feeAmount||20}getOperatorId(){const e=this.hwc.getAccountInfo();if(!e?.accountId)throw new Error("Wallet not connected");return e.accountId}async createRegistryTopic(){const e=new zf({hwc:this.hwc,network:this.network}),t=await e.createRegistry();if(!t.success)throw new Error("Failed to create topic");return t.topicId}async deployPoints(e){const t=this.getOperatorId(),{progressCallback:r}=e;try{let i;if(r?.({stage:"creating-topic",percentage:20}),e.usePrivateTopic){const e=await this.mirrorNode.getPublicKey(t),r=new zf({hwc:this.hwc,network:this.network}),n=await r.createRegistry({submitKey:e.toString(),adminKey:e.toString()});if(!n.success)throw new Error("Failed to create topic");i=n.topicId,this.logger.info(`Created private topic: ${i}`)}else i=this.publicTopicId;r?.({stage:"submitting-deploy",percentage:50,topicId:i});const n={p:"hcs-20",op:"deploy",name:e.name,tick:this.normalizeTick(e.tick),max:e.maxSupply,lim:e.limitPerMint,metadata:e.metadata,m:e.topicMemo},o=this.validateMessage(n);if(!o.valid)throw new Vf("Invalid deploy message",o.errors);const s=await this.submitPayload(i,n,e.usePrivateTopic),a=s.transactionHash?.toString()||"";return r?.({stage:"confirming",percentage:80,topicId:i,deployTxId:a}),await new Promise(e=>setTimeout(e,2e3)),r?.({stage:"complete",percentage:100,topicId:i,deployTxId:a}),{name:e.name,tick:this.normalizeTick(e.tick),maxSupply:e.maxSupply,limitPerMint:e.limitPerMint,metadata:e.metadata,topicId:i,deployerAccountId:t,currentSupply:"0",deploymentTimestamp:(new Date).toISOString(),isPrivate:e.usePrivateTopic||!1}}catch(i){throw r?.({stage:"complete",percentage:100,error:i instanceof Error?i.message:"Unknown error"}),i}}async mintPoints(e){const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20}),t?.({stage:"submitting",percentage:50});const r={p:"hcs-20",op:"mint",tick:this.normalizeTick(e.tick),amt:e.amount,to:this.accountToString(e.to),m:e.memo},i=e.topicId||this.publicTopicId,n=await this.submitPayload(i,r,!1),o=n.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,mintTxId:o}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,mintTxId:o}),{id:o,operation:"mint",tick:this.normalizeTick(e.tick),amount:e.amount,to:this.accountToString(e.to),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:o,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async transferPoints(e){const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20}),t?.({stage:"submitting",percentage:50});const r={p:"hcs-20",op:"transfer",tick:this.normalizeTick(e.tick),amt:e.amount,from:this.accountToString(e.from),to:this.accountToString(e.to),m:e.memo},i=e.topicId||this.publicTopicId,n=await this.submitPayload(i,r,!1),o=n.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,transferTxId:o}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,transferTxId:o}),{id:o,operation:"transfer",tick:this.normalizeTick(e.tick),amount:e.amount,from:this.accountToString(e.from),to:this.accountToString(e.to),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:o,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async burnPoints(e){const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20}),t?.({stage:"submitting",percentage:50});const r={p:"hcs-20",op:"burn",tick:this.normalizeTick(e.tick),amt:e.amount,from:this.accountToString(e.from),m:e.memo},i=e.topicId||this.publicTopicId,n=await this.submitPayload(i,r,!1),o=n.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,burnTxId:o}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,burnTxId:o}),{id:o,operation:"burn",tick:this.normalizeTick(e.tick),amount:e.amount,from:this.accountToString(e.from),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:o,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async registerTopic(e){const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20});const r={p:"hcs-20",op:"register",name:e.name,metadata:e.metadata,private:e.isPrivate,t_id:this.topicToString(e.topicId),m:e.memo},i=this.validateMessage(r);if(!i.valid)throw new Vf("Invalid register message",i.errors);t?.({stage:"submitting",percentage:50});const n=await this.submitPayload(this.registryTopicId,r,!1),o=n.transactionHash?.toString()||"";t?.({stage:"confirming",percentage:80,registerTxId:o}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,registerTxId:o})}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),new Gf(r instanceof Error?r.message:"Unknown error",this.topicToString(e.topicId))}}async submitPayload(e,t,i){let n;this.logger.debug(`Submitting payload to topic ${e}`),n="string"==typeof t?t:JSON.stringify(t);const o=(new r.TopicMessageSubmitTransaction).setTopicId(r.TopicId.fromString(e)).setMessage(n);i&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),o.setMaxTransactionFee(new r.Hbar(this.feeAmount)));const s=await this.hwc.executeTransactionWithErrorHandling(o,!1);if(s?.error)throw this.logger.error(`Failed to submit payload: ${s.error}`),new Error(`Failed to submit payload: ${s.error}`);if(!s?.result)throw this.logger.error("Failed to submit message: receipt is null or undefined"),new Error("Failed to submit message: receipt is null or undefined");return this.logger.debug("Payload submitted successfully via HWC"),s.result}},exports.BrowserHCS2Client=zf,exports.BrowserHCSClient=bg,exports.CanonicalAgentDataSchema=Qg,exports.ConnectionConfirmationError=lg,exports.ConnectionsManager=mg,exports.ContentResolverRegistry=Nw,exports.ContentResolverRegistryImpl=xw,exports.ContentStoreService=_w,exports.CustomFeeType=Cw,exports.DiscoveryError=Jy,exports.DiscoveryErrorCodes={INVALID_MESSAGE:"INVALID_MESSAGE",TIMEOUT:"TIMEOUT",INSUFFICIENT_PETALS:"INSUFFICIENT_PETALS",FLORA_CREATION_FAILED:"FLORA_CREATION_FAILED",ALREADY_IN_DISCOVERY:"ALREADY_IN_DISCOVERY",INVALID_STATE:"INVALID_STATE"},exports.DiscoveryOperation=Hy,exports.DiscoveryState=Gy,exports.EVMBridge=class{constructor(e="mainnet-public",t="mirrornode.hedera.com/api/v1/contracts/call",r){this.network=e,this.mirrorNodeUrl=t,this.cache=r||new nc,this.logger=y.getInstance({module:"EVMBridge"})}async executeCommands(e,t={}){let i={...t};const n={};for(const a of e){const e=`${a.c.contractAddress}-${a.c.abi.name}`,t=await this.cache.get(e);if(t)n[a.c.abi.name]=JSON.parse(t),Object.assign(i,n[a.c.abi.name]);else try{const t=new s.ethers.Interface([{...a.c.abi}]),o=t.encodeFunctionData(a.c.abi.name),c=r.ContractId.fromSolidityAddress(a.c.contractAddress),l=await this.readFromMirrorNode(o,r.AccountId.fromString("0.0.800"),c);if(this.logger.info(`Result for ${a.c.contractAddress}:`,l?.result),!l?.result){this.logger.warn(`Failed to get result from mirror node for ${a.c.contractAddress}`),n[a.c.abi.name]="0",Object.assign(i,n[a.c.abi.name]);continue}const u=t?.decodeFunctionResult(a.c.abi.name,l.result);let d={values:[]};u&&a.c.abi.outputs?.forEach((e,t)=>{const r=oc(u[t],e.type);d.values.push(r),e.name&&(d[e.name]=r)}),await this.cache.set(e,JSON.stringify(d)),n[a.c.abi.name]=d,i[a.c.abi.name]=d}catch(o){this.logger.error(`Error executing command for ${a.c.contractAddress}:`,o),n[a.c.abi.name]="0",Object.assign(i,n[a.c.abi.name])}}return{results:n,stateData:i}}async executeCommand(e,t={}){const{results:r,stateData:i}=await this.executeCommands([e],t);return{result:r[e.c.abi.name],stateData:i}}async readFromMirrorNode(e,t,r){try{const i=r.toSolidityAddress(),n=t.toSolidityAddress(),o=await fetch(`https://${this.network}.${this.mirrorNodeUrl}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({block:"latest",data:e,estimate:!1,gas:3e5,gasPrice:1e8,from:n.startsWith("0x")?n:`0x${n}`,to:i?.startsWith("0x")?i:`0x${i}`,value:0})});if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);return await o.json()}catch(i){return this.logger.error("Error reading from mirror node:",i),null}}async clearCache(){await this.cache.clear()}async clearCacheForContract(e,t){await this.cache.delete(`${e}-${t}`)}setLogLevel(e){this.logger.setLogLevel(e)}},exports.EndpointType=wh,exports.FallbackCryptoAdapter=oh,exports.FallbackHashAdapter=Xp,exports.FallbackHmacAdapter=rh,exports.FeeConfigBuilder=Rw,exports.FloraBuilder=hg,exports.FloraError=yy,exports.FloraOperation=fy,exports.FloraTopicType=my,exports.GutenbergBridge=class{constructor(e){this.logger=e}convertToGutenberg(e){if(this.logger.debug("Converting BlockDefinition to Gutenberg format",{name:e.name}),!e||!e.name)throw new Error("Invalid block definition: missing name");const t={apiVersion:e.apiVersion,name:e.name,title:e.title,category:e.category,icon:e.icon,description:e.description,keywords:e.keywords,attributes:e.attributes,supports:e.supports};return t.attributes||(t.attributes={}),t.supports||(t.supports={}),this.logger.debug("Converted to Gutenberg format",{name:t.name,attributeCount:Object.keys(t.attributes).length}),t}parseFromGutenberg(e){if(this.logger.debug("Parsing Gutenberg block to BlockDefinition",{name:e.name}),!e||!e.name)throw new Error("Invalid Gutenberg block: missing name");if(!e.title)throw new Error("Invalid Gutenberg block: missing title");const t={apiVersion:e.apiVersion||3,name:e.name,title:e.title,category:e.category||"common",template_t_id:"",icon:e.icon,description:e.description,keywords:e.keywords,attributes:e.attributes||{},supports:e.supports||{}};return this.logger.debug("Parsed from Gutenberg format",{name:t.name}),t}validateBlockStructure(e){this.logger.debug("Validating block structure",{name:e.name});const t={isValid:!0,errors:[],warnings:[]};return this.validateBasicStructure(e,t),this.validateBlockName(e,t),this.validateAttributes(e,t),this.validateSupports(e,t),this.validateParentChild(e,t),t.isValid=0===t.errors.filter(e=>"critical"===e.severity||"high"===e.severity).length,this.logger.debug("Block structure validation completed",{name:e.name,isValid:t.isValid,errorCount:t.errors.length,warningCount:t.warnings.length}),t}validateBasicStructure(e,t){e.name&&""!==e.name.trim()||t.errors.push({code:"MISSING_NAME",message:"Block name cannot be empty",field:"name",severity:"critical"}),e&&(e.title||t.errors.push({code:"MISSING_TITLE",message:"Block title is required",field:"data.title",severity:"high"}),e.description||t.warnings.push({code:"MISSING_DESCRIPTION",message:"Block description improves usability",field:"data.description",impact:"usability"})),e||t.errors.push({code:"MISSING_BLOCK_JSON",message:"data is required for Gutenberg compatibility",field:"data",severity:"critical"})}validateBlockName(e,t){if(!e.name)return;/^[a-z0-9-]+\/[a-z0-9-]+$/.test(e.name)||t.errors.push({code:"INVALID_BLOCK_NAME",message:"Block name must follow namespace/block-name format (lowercase, hyphens only)",field:"name",severity:"high"}),e&&e.name&&t.warnings.push({code:"NAME_MISMATCH",message:"Block name should match data.name",field:"name",impact:"functionality"})}validateAttributes(e,t){if(!e||!e.attributes)return;const r=e.attributes,i=["string","number","boolean","array","object"];for(const[n,o]of Object.entries(r))o.type?(i.includes(o.type)||t.errors.push({code:"INVALID_ATTRIBUTE_TYPE",message:`Attribute '${n}' has invalid type '${o.type}'`,field:`attributes.${n}.type`,severity:"high"}),o.enum&&o.default&&!o.enum.includes(o.default)&&t.warnings.push({code:"DEFAULT_NOT_IN_ENUM",message:`Attribute '${n}' default value not in enum`,field:`attributes.${n}.default`,impact:"functionality"})):t.errors.push({code:"MISSING_ATTRIBUTE_TYPE",message:`Attribute '${n}' must specify a type`,field:`attributes.${n}.type`,severity:"medium"})}validateSupports(e,t){if(!e||!e.supports)return;const r=e.supports;if(void 0!==r.align)if("boolean"==typeof r.align);else if(Array.isArray(r.align)){const e=["left","center","right","wide","full"],i=r.align.filter(t=>!e.includes(t));i.length>0&&t.warnings.push({code:"INVALID_ALIGNMENT",message:`Invalid alignment values: ${i.join(", ")}`,field:"supports.align",impact:"functionality"})}}validateParentChild(e,t){e&&(e.parent&&t.warnings.push({code:"REQUIRES_PARENT",message:"Block requires a specific parent block",field:"parent",impact:"usability"}),e.provides&&Object.keys(e.provides).length>0&&t.warnings.push({code:"PROVIDES_CONTEXT",message:"Block provides context to child blocks",field:"provides",impact:"functionality"}),e.usesContext&&e.usesContext.length>0&&t.warnings.push({code:"USES_CONTEXT",message:"Block depends on context from parent blocks",field:"usesContext",impact:"functionality"}))}},exports.HCS=w,exports.HCS10BaseClient=ng,exports.HCS10Cache=og,exports.HCS10Client=fg,exports.HCS11Client=$h,exports.HCS11ProfileResolver=vm,exports.HCS11ProfileSchema=Lh,exports.HCS12BaseClient=jg,exports.HCS12BrowserClient=class extends jg{constructor(e){super(e),this.hwc=e.hwc,this.updateAccountFromWallet(),this.logger.info("HCS-12 Browser Client initialized",{network:e.network,accountId:this.accountId})}async updateAccountFromWallet(){try{const{accountId:e}=await this.getAccountAndSigner();this.accountId=e}catch(e){this.logger.warn("No active wallet connection")}}async getAccountAndSigner(){const e=this?.hwc?.getAccountInfo(),t=e?.accountId?.toString(),r=this?.hwc?.dAppConnector?.signers?.find(e=>e.getAccountId().toString()===t);if(!r||!t)throw this.logger.error("Failed to find signer",{accountId:t,signers:this?.hwc?.dAppConnector?.signers,accountInfo:e}),new Error("Failed to find signer or account");return{accountId:t,signer:r}}getOperatorAccountId(){throw new Error("Browser client does not have operator account")}getOperatorPrivateKey(){throw new Error("Browser client does not have operator private key")}initializeRegistries(e){super.initializeRegistries(e),this._actionRegistry=new Lg(this.network,this.logger,this.actionRegistryTopicId,this),this._blockLoader=new Kg(this.network,this.logger,this),this._assemblyRegistry=new $g(this.network,this.logger,this._assemblyRegistryTopicId,this),this._hashLinksRegistry=new Hg(this.network,this.logger,this._hashLinksRegistryTopicId,this),this.logger.info("Registries initialized with signer",{actionTopicId:this.actionRegistryTopicId,assemblyTopicId:this._assemblyRegistryTopicId,hashLinksTopicId:this._hashLinksRegistryTopicId})}async createRegistryTopic(e,t,i){const{accountId:n,signer:o}=await this.getAccountAndSigner(),s={[Ig.ACTION]:"hcs-12:1:60:0",[Ig.ASSEMBLY]:"hcs-12:1:60:2",[Ig.HASHLINKS]:"hcs-12:1:60:3"}[e];this.logger.info("Creating registry topic via wallet",{registryType:Ig[e],memo:s,accountId:n});const a=(new r.TopicCreateTransaction).setTopicMemo(s).setTransactionId(r.TransactionId.generate(n));if(t)if("boolean"==typeof t&&t){const e=await o.getAccountKey();a.setAdminKey(e),a.setAutoRenewAccountId(r.AccountId.fromString(n))}else(t instanceof r.PublicKey||t instanceof r.KeyList)&&(a.setAdminKey(t),a.setAutoRenewAccountId(r.AccountId.fromString(n)));if(i)if("boolean"==typeof i&&i){const e=await o.getAccountKey();a.setSubmitKey(e)}else(i instanceof r.PublicKey||i instanceof r.KeyList)&&a.setSubmitKey(i);const c=await a.freezeWithSigner(o),l=await c.executeWithSigner(o),u=await l.getReceiptWithSigner(o);if(!u.topicId)throw new Error("Failed to create topic: topicId is null");const d=u.topicId.toString();switch(this.logger.info("Registry topic created via wallet",{topicId:d,registryType:Ig[e]}),e){case Ig.ACTION:this.actionRegistryTopicId=d;break;case Ig.ASSEMBLY:this._assemblyRegistryTopicId=d;case Ig.HASHLINKS:}return d}async createAssemblyTopic(){this.logger.info("Creating new assembly topic");return await this.createRegistryTopic(Ig.ASSEMBLY)}async registerAssemblyDirect(e,t){return this.logger.info("Registering assembly",{topicId:e,name:t.name,version:t.version}),this._submitMessage(e,JSON.stringify(t))}async addBlockToAssembly(e,t){return this.logger.info("Adding block to assembly",{assemblyTopicId:e,blockTopicId:t.block_t_id}),this._submitMessage(e,JSON.stringify(t))}async addActionToAssembly(e,t){return this.logger.info("Adding action to assembly",{assemblyTopicId:e,actionTopicId:t.t_id,alias:t.alias}),this._submitMessage(e,JSON.stringify(t))}async updateAssembly(e,t){return this.logger.info("Updating assembly",{assemblyTopicId:e,update:t}),this._submitMessage(e,JSON.stringify(t))}async storeBlock(e,t){if(!this.blockLoader)throw new Error("Block loader not initialized");return this.blockLoader.storeBlock(e,t)}async submitMessage(e,t,r){return this.logger.warn("submitMessage is deprecated. Use operation-specific methods instead."),this._submitMessage(e,t,r)}async _submitMessage(e,t,i){const{accountId:n,signer:o}=await this.getAccountAndSigner();this.logger.debug("Submitting message to topic via wallet",{topicId:e,messageLength:t.length,accountId:n});const s=(new r.TopicMessageSubmitTransaction).setTopicId(r.TopicId.fromString(e)).setMessage(t).setTransactionId(r.TransactionId.generate(n));i&&this.logger.warn("Submit key parameter ignored in browser client - using wallet signer");const a=await s.freezeWithSigner(o),c=await a.executeWithSigner(o),l=await c.getReceiptWithSigner(o);return this.logger.info("Message submitted successfully via wallet",{topicId:e,transactionId:c.transactionId.toString(),sequenceNumber:l.topicSequenceNumber?.toString()}),{transactionId:c.transactionId.toString(),sequenceNumber:l.topicSequenceNumber?Number(l.topicSequenceNumber):void 0}}getHashConnect(){return this.hwc}getAccountId(){return this.accountId}async isConnected(){try{return await this.getAccountAndSigner(),!0}catch{return!1}}async inscribeFile(e,t,r){const{accountId:i,signer:n}=await this.getAccountAndSigner();this.logger.info("Inscribing file via HCS-1 (browser)",{fileName:t});const o=g.lookup(t)||"application/octet-stream",s=await es.createWithAuth({type:"client",accountId:i,signer:n,network:this.network}),a={mode:"file",waitForConfirmation:!0,waitMaxAttempts:r?.waitMaxAttempts||30,waitIntervalMs:r?.waitIntervalMs||4e3,progressCallback:r?.progressCallback,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"},network:this.network},c=await Fa({type:"buffer",buffer:e,fileName:t,mimeType:o},n,a,s);if(!c.confirmed||!c.inscription)throw new Error("Inscription failed to confirm");return c.inscription}async registerAction(e){const t=e.build();if(!this._actionRegistry)throw new Error("Action registry not initialized");const r=await this._submitMessage(this.actionRegistryTopicId,JSON.stringify(t));return this.logger.info("Action registered (browser)",{topicId:t.t_id,transactionId:r.transactionId}),e}async registerBlock(e){const t=e.getTemplate();if(t){const r=await this.inscribeFile(t,`${e.getName()||"block"}-template.html`);e.setTemplateTopicId(r.topic_id)}const r=e.build();if(!r.template_t_id)throw new Error("Block must have either a template buffer (via setTemplate) or template_t_id");const i=await this.inscribeFile(globalThis.Buffer.from(JSON.stringify(r,null,2)),`${r.name}-definition.json`);return this.logger.info("Block registered (browser)",{name:r.name,definitionTopicId:i.topic_id,templateTopicId:r.template_t_id}),e.setTopicId(i.topic_id),e}async createAssembly(e){if(!e)return this.createAssemblyTopic();const t=e.build(),r=await this.createAssemblyTopic();await this.registerAssemblyDirect(r,t);const i=e.getOperations();for(const n of i)switch(n.op){case"add-block":await this.addBlockToAssembly(r,n);break;case"add-action":await this.addActionToAssembly(r,n);break;case"update":await this.updateAssembly(r,n)}return this.logger.info("Assembly created (browser)",{topicId:r,name:t.name,version:t.version,operations:i.length}),r}},exports.HCS12Client=class extends jg{constructor(e){super(e),this.operatorAccountId=e.operatorId,this.operatorCtx=B({network:this.network,operatorId:this.operatorAccountId,operatorKey:e.operatorPrivateKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:e.client??("mainnet"===e.network?r.Client.forMainnet():r.Client.forTestnet())}),this.client=this.operatorCtx.client,this.logger.info("HCS-12 SDK Client initialized",{network:e.network,operatorId:this.operatorAccountId,keyType:this.operatorCtx.keyType})}initializeRegistries(e){super.initializeRegistries(e),this._actionRegistry=new Lg(this.network,this.logger,this.actionRegistryTopicId,this),this._blockLoader=new Kg(this.network,this.logger,this),this._assemblyRegistry=new $g(this.network,this.logger,this._assemblyRegistryTopicId,this),this._hashLinksRegistry=new Hg(this.network,this.logger,this._hashLinksRegistryTopicId,this),this.logger.info("Registries initialized",{actionTopicId:this.actionRegistryTopicId,assemblyTopicId:this._assemblyRegistryTopicId,hashLinksTopicId:this._hashLinksRegistryTopicId})}async createRegistryTopic(e,t,r){const i={[Ig.ACTION]:"hcs-12:1:60:0",[Ig.ASSEMBLY]:"hcs-12:1:60:2",[Ig.HASHLINKS]:"hcs-12:1:60:3"}[e];this.logger.info("Creating registry topic",{registryType:Ig[e],memo:i});const n=z({memo:i,adminKey:t,submitKey:r,operatorPublicKey:this.client.operatorPublicKey||void 0}),o=await n.execute(this.client),s=await o.getReceipt(this.client);if(!s.topicId)throw new Error("Failed to create topic: topicId is null");const a=s.topicId.toString();switch(this.logger.info("Registry topic created",{topicId:a,registryType:Ig[e]}),e){case Ig.ACTION:this.actionRegistryTopicId=a;break;case Ig.ASSEMBLY:this._assemblyRegistryTopicId=a;case Ig.HASHLINKS:}return a}async registerAssemblyDirect(e,t){return this.logger.info("Registering assembly",{topicId:e,name:t.name,version:t.version}),this._submitMessage(e,JSON.stringify(t))}async addBlockToAssembly(e,t){return this.logger.info("Adding block to assembly",{assemblyTopicId:e,blockTopicId:t.block_t_id}),this._submitMessage(e,JSON.stringify(t))}async addActionToAssembly(e,t){return this.logger.info("Adding action to assembly",{assemblyTopicId:e,actionTopicId:t.t_id,alias:t.alias}),this._submitMessage(e,JSON.stringify(t))}async updateAssembly(e,t){return this.logger.info("Updating assembly",{assemblyTopicId:e,update:t}),this._submitMessage(e,JSON.stringify(t))}async submitMessage(e,t,r){return this.logger.warn("submitMessage is deprecated. Use operation-specific methods instead."),this._submitMessage(e,t,r)}async _submitMessage(e,t,r){this.logger.debug("Submitting message to topic",{topicId:e,messageLength:t.length});const i=_({topicId:e,message:t});let n;if(r){const e=i.freezeWith(this.client),t=await e.sign(r);n=await t.execute(this.client)}else n=await i.execute(this.client);const o=await n.getReceipt(this.client);return this.logger.info("Message submitted successfully",{topicId:e,transactionId:n.transactionId.toString(),sequenceNumber:o.topicSequenceNumber?.toString()}),{transactionId:n.transactionId.toString(),sequenceNumber:o.topicSequenceNumber?Number(o.topicSequenceNumber):void 0}}getClient(){return this.client}getOperatorAccountId(){return this.operatorAccountId}getOperatorPrivateKey(){return this.operatorCtx.operatorKey.toString()}async inscribeFile(e,t,r){this.logger.info("Inscribing file via HCS-1",{fileName:t});const i=g.lookup(t)||"application/octet-stream",n=await es.createWithAuth({type:"server",accountId:this.operatorAccountId,privateKey:this.operatorCtx.operatorKey.toString(),network:this.network}),o={mode:"file",waitForConfirmation:!0,waitMaxAttempts:r?.waitMaxAttempts||30,waitIntervalMs:r?.waitIntervalMs||4e3,progressCallback:r?.progressCallback,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},s=await Oa({type:"buffer",buffer:e,fileName:t,mimeType:i},{accountId:this.operatorAccountId,privateKey:this.operatorCtx.operatorKey,network:this.network},o,n);if(!s.confirmed||!s.inscription)throw new Error("Inscription failed to confirm");return s.inscription}async createAssemblyTopic(){if(!this._assemblyRegistry)throw new Error("Assembly registry not initialized");return this._assemblyRegistry.createAssemblyTopic()}async registerAction(e){const t=e.build();if(!this._actionRegistry)throw new Error("Action registry not initialized");const r=await this._submitMessage(this.actionRegistryTopicId,JSON.stringify(t));return this.logger.info("Action registered",{topicId:t.t_id,transactionId:r.transactionId}),e}async registerBlock(e){const t=e.getTemplate();if(t){const r=await this.inscribeFile(t,`${e.getName()||"block"}-template.html`);e.setTemplateTopicId(r.topic_id)}const r=e.build();if(!r.template_t_id)throw new Error("Block must have either a template buffer (via setTemplate) or template_t_id");const i=await this.inscribeFile(globalThis.Buffer.from(JSON.stringify(r,null,2)),`${r.name}-definition.json`);return this.logger.info("Block registered",{name:r.name,definitionTopicId:i.topic_id,templateTopicId:r.template_t_id}),e.setTopicId(i.topic_id),e}async createAssembly(e){const t=e.build(),r=await this.createAssemblyTopic();await this.registerAssemblyDirect(r,t);const i=e.getOperations();for(const n of i)switch(n.op){case"add-block":await this.addBlockToAssembly(r,n);break;case"add-action":await this.addActionToAssembly(r,n);break;case"update":await this.updateAssembly(r,n)}return this.logger.info("Assembly created",{topicId:r,name:t.name,version:t.version,operations:i.length}),r}},exports.HCS14Client=df,exports.HCS14_PROTOCOL_REGEX=Zg,exports.HCS15BaseClient=gy,exports.HCS15BrowserClient=class extends gy{constructor(e){super(e),this.signer=e.signer||e.hwc?.dAppConnector?.signers?.[0]}requireSigner(){if(!this.signer)throw new Error("HCS-15 Browser client requires an active signer");return this.signer}async createBaseAccount(e){const t=this.requireSigner(),i=r.PrivateKey.generateECDSA(),n=i.publicKey,o=py({publicKey:n,initialBalance:new r.Hbar(e?.initialBalance??10),maxAutomaticTokenAssociations:e?.maxAutomaticTokenAssociations,accountMemo:e?.accountMemo,transactionMemo:e?.transactionMemo}),s=await o.freezeWithSigner(t),a=await s.executeWithSigner(t),c=await a.getReceiptWithSigner(t),l=c?.accountId?.toString?.(),u=`0x${n.toEvmAddress()}`;return this.logger.info("Created HCS-15 base account (browser)",{accountId:l,evmAddress:u}),{accountId:l,privateKey:i,privateKeyHex:i.toStringRaw(),publicKey:n,evmAddress:u}}async createPetalAccount(e){const t=this.requireSigner(),i=hy({publicKey:("string"==typeof e.basePrivateKey?r.PrivateKey.fromStringECDSA(e.basePrivateKey):e.basePrivateKey).publicKey,initialBalance:new r.Hbar(e.initialBalance??1),maxAutomaticTokenAssociations:e.maxAutomaticTokenAssociations,accountMemo:e.accountMemo,transactionMemo:e.transactionMemo}),n=await i.freezeWithSigner(t),o=await n.executeWithSigner(t),s=await o.getReceiptWithSigner(t),a=s?.accountId?.toString?.();return this.logger.info("Created HCS-15 petal account (browser)",{accountId:a}),{accountId:a}}},exports.HCS15Client=class extends gy{constructor(e){super(e),this.operatorId=r.AccountId.fromString(e.operatorId),this.operatorCtx=B({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:e.client??("mainnet"===this.network?r.Client.forMainnet():r.Client.forTestnet())}),this.client=this.operatorCtx.client}getKeyType(){return this.operatorCtx.keyType}async close(){try{this.client.close()}catch{}}async ensureOperatorReady(){await this.operatorCtx.ensureInitialized()}async createBaseAccount(e){await this.ensureOperatorReady();const t=r.PrivateKey.generateECDSA(),i=t.publicKey,n=py({publicKey:i,initialBalance:new r.Hbar(e?.initialBalance??10),maxAutomaticTokenAssociations:e?.maxAutomaticTokenAssociations,accountMemo:e?.accountMemo,transactionMemo:e?.transactionMemo}),o=await n.execute(this.client),s=await o.getReceipt(this.client);if(!s.accountId)throw new Error("HCS-15 BASE_ACCOUNT_CREATE_FAILED");const a=s.accountId.toString(),c=`0x${i.toEvmAddress()}`;return this.logger.info("Created HCS-15 base account",{accountId:a,evmAddress:c}),{accountId:a,privateKey:t,privateKeyHex:t.toStringRaw(),publicKey:i,evmAddress:c,receipt:s}}async createPetalAccount(e){await this.ensureOperatorReady();const t="string"==typeof e.basePrivateKey?r.PrivateKey.fromStringECDSA(e.basePrivateKey):e.basePrivateKey,i=hy({publicKey:t.publicKey,initialBalance:new r.Hbar(e.initialBalance??1),maxAutomaticTokenAssociations:e.maxAutomaticTokenAssociations,accountMemo:e.accountMemo,transactionMemo:e.transactionMemo}),n=await i.execute(this.client),o=await n.getReceipt(this.client);if(!o.accountId)throw new Error("HCS-15 PETAL_ACCOUNT_CREATE_FAILED");const s=o.accountId.toString();let a;return this.logger.info("Created HCS-15 petal account",{accountId:s}),e.profile&&(a=await this.createPetalProfile({accountId:s,basePrivateKey:t,profile:e.profile})),{accountId:s,receipt:o,profile:a}}async createPetalProfile(e){const{HCS10Client:t}=await Promise.resolve().then(()=>wg),{PersonBuilder:r}=await Promise.resolve().then(()=>gg),i=new t({network:this.network,operatorId:e.accountId,operatorPrivateKey:e.basePrivateKey.toString(),logLevel:this.logger.getLevel()});try{const t=(new r).setName(e.profile.displayName).setBaseAccount(e.profile.baseAccountId);if(e.profile.alias&&t.setAlias(e.profile.alias),e.profile.bio&&t.setBio(e.profile.bio),e.profile.profileImage&&t.setProfileImage(e.profile.profileImage),e.profile.socials)for(const r of e.profile.socials)t.addSocial(r.platform,r.handle);if(e.profile.properties)for(const[r,i]of Object.entries(e.profile.properties))t.addProperty(r,i);const n=await i.create(t,{ttl:e.profile.ttl??300,updateAccountMemo:!0});if("success"in n&&!1===n.success)throw new Error(n.error??"Failed to create petal profile");const o="inboundTopicId"in n?n.inboundTopicId:"",s="outboundTopicId"in n?n.outboundTopicId:"",a="profileTopicId"in n?n.profileTopicId:"";if(!a)throw new Error("Failed to resolve petal profile topic ID");return{profileTopicId:a,inboundTopicId:o,outboundTopicId:s}}finally{try{i.getClient().close()}catch{}}}},exports.HCS15_BASE_ACCOUNT_CREATE_TRANSACTION_MEMO=ly,exports.HCS15_PETAL_ACCOUNT_CREATE_TRANSACTION_MEMO=uy,exports.HCS16BaseClient=Oy,exports.HCS16BrowserClient=class extends Oy{constructor(e){super({network:e.network}),this.hwc=e.hwc,this.signer=e.signer}ensureConnected(){if(this.signer&&"function"==typeof this.signer.getAccountId)return this.signer.getAccountId().toString();const e=this.hwc?.getAccountInfo?.(),t=e?.accountId;if(!t)throw new Error("No active wallet connection");return t}getSigner(){if(this.signer)return this.signer;this.ensureConnected();const e=this.hwc?.dAppConnector?.signers?.[0];if(!e)throw new Error("No active wallet signer");return e}async createFloraTopic(e){this.ensureConnected();const t=this.getSigner(),r=Ey({floraAccountId:e.floraAccountId,topicType:e.topicType,adminKey:e.adminKey,submitKey:e.submitKey,autoRenewAccountId:e.autoRenewAccountId}),i=await r.freezeWithSigner(t),n=await i.executeWithSigner(t),o=await n.getReceiptWithSigner(t);return o?.topicId?.toString?.()||""}async sendFloraCreated(e){const t=this.getSigner(),r=Ry(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendTransaction(e){const t=this.getSigner(),r=xy(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async signSchedule(e){const t=this.getSigner(),i=await(new r.ScheduleSignTransaction).setScheduleId(e.scheduleId).freezeWithSigner(t);await i.executeWithSigner(t)}async sendStateUpdate(e){const t=this.getSigner(),r=Ny(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async createFloraAccountWithTopics(e){const t=this.getSigner(),r=await this.assembleKeyList({members:e.members,threshold:e.threshold}),i=await this.assembleSubmitKeyList(e.members),n=Ay({keyList:r,initialBalanceHbar:"number"==typeof e.initialBalanceHbar?e.initialBalanceHbar:5,maxAutomaticTokenAssociations:-1}),o=await n.freezeWithSigner(t),s=await o.executeWithSigner(t),a=await s.getReceiptWithSigner(t),c=a?.accountId?.toString?.();if(!c)throw new Error("Failed to create Flora account");const{communication:l,transaction:u,state:d}=this.buildFloraTopicCreateTxs({floraAccountId:c,keyList:r,submitList:i,autoRenewAccountId:e.autoRenewAccountId}),p=await(await(await l.freezeWithSigner(t)).executeWithSigner(t)).getReceiptWithSigner(t),h=await(await(await u.freezeWithSigner(t)).executeWithSigner(t)).getReceiptWithSigner(t),g=await(await(await d.freezeWithSigner(t)).executeWithSigner(t)).getReceiptWithSigner(t);return{floraAccountId:c,topics:{communication:p?.topicId?.toString?.()||"",transaction:h?.topicId?.toString?.()||"",state:g?.topicId?.toString?.()||""}}}async publishFloraCreated(e){const t=this.getSigner(),r=Ry({topicId:e.communicationTopicId,operatorId:e.operatorId,floraAccountId:e.floraAccountId,topics:e.topics}),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendFloraJoinRequest(e){const t=this.getSigner(),r=zy(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendFloraJoinVote(e){const t=this.getSigner(),r=_y(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendFloraJoinAccepted(e){const t=this.getSigner(),r=Py(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}},exports.HCS16Client=class extends Oy{constructor(e){super({network:e.network,logger:e.logger}),this.operatorId=r.AccountId.fromString(e.operatorId);const t=new x(e.network,this.logger);this.operatorCtx=B({network:e.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:t,logger:this.logger,client:e.client??("mainnet"===e.network?r.Client.forMainnet():r.Client.forTestnet())}),this.client=this.operatorCtx.client}async ensureOperatorReady(){await this.operatorCtx.ensureInitialized()}async createFloraTopic(e){await this.ensureOperatorReady();const t=Ey({floraAccountId:e.floraAccountId,topicType:e.topicType,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:this.client.operatorPublicKey||void 0,autoRenewAccountId:e.autoRenewAccountId}),r=e.signerKeys??[];if(r.length>0){let e=await t.freezeWith(this.client);for(const t of r)e=await e.sign(t);const i=await e.execute(this.client),n=await i.getReceipt(this.client);if(!n.topicId)throw new Error("Failed to create Flora topic");return n.topicId.toString()}const i=await t.execute(this.client),n=await i.getReceipt(this.client);if(!n.topicId)throw new Error("Failed to create Flora topic");return n.topicId.toString()}async createFloraAccount(e){await this.ensureOperatorReady();const t=Ay({keyList:e.keyList,initialBalanceHbar:e.initialBalanceHbar,maxAutomaticTokenAssociations:e.maxAutomaticTokenAssociations}),r=await t.execute(this.client),i=await r.getReceipt(this.client);if(!i.accountId)throw new Error("Failed to create Flora account");return{accountId:i.accountId.toString(),receipt:i}}async sendFloraCreated(e){await this.ensureOperatorReady();const t=Ry(e);return(await t.execute(this.client)).getReceipt(this.client)}async sendTransaction(e){await this.ensureOperatorReady();const t=xy(e);return(await t.execute(this.client)).getReceipt(this.client)}async signSchedule(e){await this.ensureOperatorReady();const t=await(new r.ScheduleSignTransaction).setScheduleId(e.scheduleId).freezeWith(this.client),i=await t.sign(e.signerKey);return(await i.execute(this.client)).getReceipt(this.client)}async sendStateUpdate(e){await this.ensureOperatorReady();const t=Ny({topicId:e.topicId,operatorId:e.operatorId,hash:e.hash,epoch:e.epoch,accountId:e.accountId,topics:e.topics,memo:e.memo,transactionMemo:e.transactionMemo});if(e.signerKeys&&e.signerKeys.length>0){let r=await t.freezeWith(this.client);for(const t of e.signerKeys)r=await r.sign(t);return(await r.execute(this.client)).getReceipt(this.client)}return(await t.execute(this.client)).getReceipt(this.client)}async sendFloraJoinRequest(e){await this.ensureOperatorReady();const t=zy(e);if(e.signerKey){const r=await t.freezeWith(this.client),i=await r.sign(e.signerKey);return(await i.execute(this.client)).getReceipt(this.client)}return(await t.execute(this.client)).getReceipt(this.client)}async sendFloraJoinVote(e){await this.ensureOperatorReady();const t=_y(e);if(e.signerKey){const r=await t.freezeWith(this.client),i=await r.sign(e.signerKey);return(await i.execute(this.client)).getReceipt(this.client)}return(await t.execute(this.client)).getReceipt(this.client)}async sendFloraJoinAccepted(e){await this.ensureOperatorReady();const t=Py(e);if(e.signerKeys&&e.signerKeys.length>0){let r=await t.freezeWith(this.client);for(const t of e.signerKeys)r=await r.sign(t);return(await r.execute(this.client)).getReceipt(this.client)}return(await t.execute(this.client)).getReceipt(this.client)}async assembleKeyList(e){return super.assembleKeyList(e)}async createFloraAccountWithTopics(e){await this.ensureOperatorReady();const t=await this.assembleKeyList({members:e.members,threshold:e.threshold}),r=await this.assembleSubmitKeyList(e.members),i=Ay({keyList:t,initialBalanceHbar:"number"==typeof e.initialBalanceHbar?e.initialBalanceHbar:5,maxAutomaticTokenAssociations:-1}),n=await i.execute(this.client),o=await n.getReceipt(this.client);if(!o.accountId)throw new Error("Failed to create Flora account");const s=o.accountId.toString(),{communication:a,transaction:c,state:l}=this.buildFloraTopicCreateTxs({floraAccountId:s,keyList:t,submitList:r,autoRenewAccountId:e.autoRenewAccountId}),u=await a.execute(this.client).then(e=>e.getReceipt(this.client)),d=await c.execute(this.client).then(e=>e.getReceipt(this.client)),p=await l.execute(this.client).then(e=>e.getReceipt(this.client));return{floraAccountId:s,topics:{communication:u.topicId.toString(),transaction:d.topicId.toString(),state:p.topicId.toString()}}}async createFloraProfile(e){if(await this.ensureOperatorReady(),0===e.signerKeys.length)throw new Error("Flora profile creation requires signer keys");const t={version:"1.0",type:3,display_name:e.displayName,members:e.members,threshold:e.threshold,topics:e.topics,inboundTopicId:e.inboundTopicId??e.topics.communication,outboundTopicId:e.outboundTopicId??e.topics.transaction,bio:e.bio,metadata:e.metadata,policies:e.policies},r=new $h({network:this.network,auth:{operatorId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey.toString()},logLevel:this.logger.getLevel()});try{await r.initializeOperator();const i=await r.inscribeProfile(t);if(!i.success)throw new Error(i.error??"Failed to inscribe Flora profile");const n=await r.updateAccountMemoWithProfile(e.floraAccountId,i.profileTopicId,e.signerKeys);if(!n.success)throw new Error(n.error??"Failed to update Flora account memo");return{profileTopicId:i.profileTopicId,transactionId:i.transactionId}}finally{try{r.getClient().close()}catch{}}}async publishFloraCreated(e){await this.ensureOperatorReady();const t=Ry({topicId:e.communicationTopicId,operatorId:e.operatorId,floraAccountId:e.floraAccountId,topics:e.topics});return(await t.execute(this.client)).getReceipt(this.client)}},exports.HCS16_ACCOUNT_KEY_UPDATE_TRANSACTION_MEMO=Iy,exports.HCS16_FLORA_ACCOUNT_CREATE_TRANSACTION_MEMO=by,exports.HCS16_TOPIC_KEY_UPDATE_TRANSACTION_MEMO=Ty,exports.HCS17BaseClient=Ly,exports.HCS17BrowserClient=class extends Ly{constructor(e){super(e),this.hwc=e.hwc,this.signer=e.signer}ensureConnected(){if(this.signer&&"function"==typeof this.signer.getAccountId)return this.signer.getAccountId().toString();const e=this.hwc?.getAccountInfo?.(),t=e?.accountId;if(!t)throw new Error("No active wallet connection");return t}getSigner(){if(this.signer)return this.signer;this.ensureConnected();const e=this.hwc?.dAppConnector?.signers?.[0];if(!e)throw new Error("No active wallet signer");return e}async createStateTopic(e){this.ensureConnected();const t=this.getSigner(),r=Ky({ttl:e?.ttl??86400}),i=await r.freezeWithSigner(t),n=await i.executeWithSigner(t),o=await n.getReceiptWithSigner(t),s=o?.topicId?.toString?.()||"";return this.logger.info(`Created HCS-17 state topic via wallet: ${s}`),s}async submitMessage(e,t){const{valid:r,errors:i}=this.validateMessage(t);if(!r)throw new Error(`Invalid HCS-17 message: ${i.join(", ")}`);const n=this.getSigner(),o=$y({topicId:e,stateHash:t.state_hash,accountId:t.account_id,topics:t.topics,memo:t.m}),s=await o.freezeWithSigner(n),a=await s.executeWithSigner(n);return await a.getReceiptWithSigner(n),{}}async computeAndPublish(e){this.ensureConnected();const t=this.getSigner(),r=[];for(const a of e.topics){const e=(await this.mirrorNode.getTopicMessages(a,{limit:1,order:"desc"}))[0],t=e&&e.running_hash||"";r.push({topicId:a,latestRunningHash:t})}const i={accountId:e.accountId,publicKey:e.accountPublicKey,topics:r},n=this.calculateAccountStateHash(i),o=$y({topicId:e.publishTopicId,stateHash:n.stateHash,accountId:e.accountId,topics:e.topics,memo:e.memo}),s=await o.freezeWithSigner(t);return await s.executeWithSigner(t),{stateHash:n.stateHash}}},exports.HCS17Client=class extends Ly{constructor(e){super(e),this.operatorId=r.AccountId.fromString(e.operatorId),this.operatorCtx=B({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:e.client??("mainnet"===e.network?r.Client.forMainnet():r.Client.forTestnet())}),this.client=this.operatorCtx.client}getKeyType(){return this.operatorCtx.keyType}async createStateTopic(e){const t=Ky({ttl:e?.ttl??86400,adminKey:e?.adminKey,submitKey:e?.submitKey,operatorPublicKey:this.client.operatorPublicKey||void 0}),r=await t.execute(this.client),i=await r.getReceipt(this.client);if(!i.topicId)throw new Error("Failed to create topic: topicId empty");const n=i.topicId.toString();return this.logger.info(`Created HCS-17 state topic ${n}`),n}async submitMessage(e,t){const{valid:r,errors:i}=this.validateMessage(t);if(!r)throw new Error(`Invalid HCS-17 message: ${i.join(", ")}`);const n=$y({topicId:e,stateHash:t.state_hash,accountId:t.account_id,topics:t.topics,memo:t.m,epoch:t.epoch,timestamp:t.timestamp}),o=await n.execute(this.client);return await o.getReceipt(this.client)}async computeAndPublish(e){const t=[];for(const a of e.topics){const e=(await this.mirrorNode.getTopicMessages(a,{limit:1,order:"desc"}))[0],r=e?.running_hash||"";t.push({topicId:a,latestRunningHash:r})}const r={accountId:e.accountId,publicKey:e.accountPublicKey,topics:t},i=this.calculateAccountStateHash(r);this.createStateHashMessage(i.stateHash,e.accountId,e.topics,e.memo);const n=$y({topicId:e.publishTopicId,stateHash:i.stateHash,accountId:e.accountId,topics:e.topics,memo:e.memo}),o=await n.execute(this.client),s=await o.getReceipt(this.client);return{stateHash:i.stateHash,receipt:s}}},exports.HCS17TopicType=My,exports.HCS17_STATE_HASH_TRANSACTION_MEMO=wy,exports.HCS18BaseClient=nb,exports.HCS18BrowserClient=class{constructor(e){this.hwc=e.hwc}async submit(e,t){return await this.hwc.submitMessageToTopic(e,JSON.stringify(t))}async announce(e){const t=Qy(e.data);return this.submit(e.discoveryTopicId,t)}async propose(e){const t=eb(e.data);return this.submit(e.discoveryTopicId,t)}async respond(e){const t=tb(e.data);return this.submit(e.discoveryTopicId,t)}async complete(e){const t=rb(e.data);return this.submit(e.discoveryTopicId,t)}async withdraw(e){const t=ib(e.data);return this.submit(e.discoveryTopicId,t)}},exports.HCS18Client=class extends nb{constructor(e){super({network:e.network,logger:y.getInstance({level:e.logLevel||"info",module:"HCS-18",silent:e.silent})}),this.operatorCtx=B({network:this.network,operatorId:e.operatorId,operatorKey:e.operatorKey,mirrorNode:this.mirrorNode,logger:this.logger,client:e.client??r.Client.forName(this.network)}),this.client=this.operatorCtx.client}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}async createDiscoveryTopic(e){await this.ensureInitialized();const t=e?.ttlSeconds;let r;try{r=this.operatorCtx.operatorKey.publicKey}catch{r=void 0}const i=Xy({ttlSeconds:t,adminKey:e?.adminKey,submitKey:e?.submitKey,operatorPublicKey:r,memoOverride:e?.memoOverride}),n=await i.execute(this.client),o=await n.getReceipt(this.client),s=o.topicId?.toString();if(!s)throw new Error("Failed to create discovery topic");return{topicId:s,receipt:o}}async announce(e){await this.ensureInitialized();const t=Qy(e.data),r=Zy({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client),n=await i.getReceipt(this.client),o=n.topicSequenceNumber.toNumber();return{receipt:n,sequenceNumber:o}}async propose(e){await this.ensureInitialized();const t=eb(e.data),r=Zy({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client),n=await i.getReceipt(this.client),o=n.topicSequenceNumber.toNumber();return{receipt:n,sequenceNumber:o}}async respond(e){await this.ensureInitialized();const t=tb(e.data),r=Zy({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client);return await i.getReceipt(this.client)}async complete(e){await this.ensureInitialized();const t=rb(e.data),r=Zy({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client);return await i.getReceipt(this.client)}async withdraw(e){await this.ensureInitialized();const t=ib(e.data),r=Zy({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client);return await i.getReceipt(this.client)}},exports.HCS20BaseClient=Yf,exports.HCS20BurnMessageSchema=Bf,exports.HCS20Client=class extends Yf{constructor(e){super(e),this.operatorAccountId="string"==typeof e.operatorId?r.AccountId.fromString(e.operatorId):e.operatorId,this.operatorId=this.operatorAccountId.toString();const t=e.client??("mainnet"===this.network?r.Client.forMainnet():r.Client.forTestnet());this.operatorCtx=B({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:t}),this.client=this.operatorCtx.client,this.operatorCtx.ensureInitialized()}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}async submitPayload(e,t){let i;if(t){const r=e.freezeWith(this.client),n=await r.sign(t);i=await n.execute(this.client)}else i=await e.execute(this.client);const n=await i.getReceipt(this.client);if(!n||n.status!==r.Status.Success)throw new Error("Failed to submit message to topic");return{receipt:n,transactionId:i.transactionId.toString()}}async createPublicTopic(e){await this.ensureInitialized(),this.logger.info("Creating public HCS-20 topic...");const t=await(new r.TopicCreateTransaction).setTopicMemo(e||"HCS-20 Public Topic").execute(this.client),i=await t.getReceipt(this.client);if(i.status!==r.Status.Success||!i.topicId)throw new Error("Failed to create public topic");const n=i.topicId.toString();return this.logger.info(`Created public topic: ${n}`),this.publicTopicId=n,n}async createRegistryTopic(){await this.ensureInitialized(),this.logger.info("Creating HCS-20 registry topic...");const e=new Nf({operatorId:this.operatorId,operatorKey:this.operatorCtx.operatorKey,network:this.network,client:this.client}),t=await e.createRegistry({submitKey:this.operatorCtx.operatorKey,adminKey:this.operatorCtx.operatorKey});if(!t.success)throw new Error("Failed to create registry topic");const r=t.topicId;return this.logger.info(`Created registry topic: ${r}`),this.registryTopicId=r,r}async deployPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{let r;t?.({stage:"creating-topic",percentage:20});const i=new Nf({operatorId:this.operatorId,operatorKey:this.operatorCtx.operatorKey,network:this.network,client:this.client});if(e.usePrivateTopic){const t=await i.createRegistry({submitKey:this.operatorCtx.operatorKey,adminKey:this.operatorCtx.operatorKey});if(!t.success)throw new qf("Failed to create topic",e.tick);r=t.topicId,this.logger.info(`Created private topic: ${r}`)}else r=this.publicTopicId;t?.({stage:"submitting-deploy",percentage:50,topicId:r});const n={p:"hcs-20",op:"deploy",name:e.name,tick:this.normalizeTick(e.tick),max:e.maxSupply,lim:e.limitPerMint,metadata:e.metadata,m:e.topicMemo},o=this.validateMessage(n);if(!o.valid)throw new Vf("Invalid deploy message",o.errors);const s=Xf({topicId:r,name:e.name,tick:e.tick,max:e.maxSupply,lim:e.limitPerMint,metadata:e.metadata,memo:e.topicMemo}),{transactionId:a}=await this.submitPayload(s);t?.({stage:"confirming",percentage:80,topicId:r,deployTxId:a}),await this.waitForMirrorNodeConfirmation(r,a),t?.({stage:"complete",percentage:100,topicId:r,deployTxId:a});return{name:e.name,tick:this.normalizeTick(e.tick),maxSupply:e.maxSupply,limitPerMint:e.limitPerMint,metadata:e.metadata,topicId:r,deployerAccountId:this.operatorId,currentSupply:"0",deploymentTimestamp:(new Date).toISOString(),isPrivate:e.usePrivateTopic||!1}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async mintPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20});const r=this.normalizeTick(e.tick);t?.({stage:"submitting",percentage:50});const i=e.topicId?this.topicToString(e.topicId):this.publicTopicId,n=Zf({topicId:i,tick:e.tick,amt:e.amount,to:this.accountToString(e.to),memo:e.memo}),{transactionId:o}=await this.submitPayload(n);t?.({stage:"confirming",percentage:80,mintTxId:o}),e.disableMirrorCheck||await this.waitForMirrorNodeConfirmation(i,o),t?.({stage:"complete",percentage:100,mintTxId:o});return{id:o,operation:"mint",tick:r,amount:e.amount,to:this.accountToString(e.to),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:o,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async transferPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20});const r=this.normalizeTick(e.tick),i=this.accountToString(e.from),n=this.accountToString(e.to);if(i!==this.operatorId)throw new jf("For public topics, transaction payer must match sender",e.tick,i,n,e.amount);t?.({stage:"submitting",percentage:50});const o=e.topicId?this.topicToString(e.topicId):this.publicTopicId,s=Qf({topicId:o,tick:e.tick,amt:e.amount,from:i,to:n,memo:e.memo}),{transactionId:a}=await this.submitPayload(s);t?.({stage:"confirming",percentage:80,transferTxId:a}),await this.waitForMirrorNodeConfirmation(o,a),t?.({stage:"complete",percentage:100,transferTxId:a});return{id:a,operation:"transfer",tick:r,amount:e.amount,from:i,to:n,timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:o,transactionId:a,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async burnPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20});const r=this.normalizeTick(e.tick),i=this.accountToString(e.from);if(i!==this.operatorId)throw new Wf("For public topics, transaction payer must match burner",e.tick,i,e.amount);t?.({stage:"submitting",percentage:50});const n=e.topicId?this.topicToString(e.topicId):this.publicTopicId,o=ey({topicId:n,tick:e.tick,amt:e.amount,from:i,memo:e.memo}),{transactionId:s}=await this.submitPayload(o);t?.({stage:"confirming",percentage:80,burnTxId:s}),await this.waitForMirrorNodeConfirmation(n,s),t?.({stage:"complete",percentage:100,burnTxId:s});return{id:s,operation:"burn",tick:r,amount:e.amount,from:i,timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:n,transactionId:s,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async registerTopic(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20});const r={p:"hcs-20",op:"register",name:e.name,metadata:e.metadata,private:e.isPrivate,t_id:this.topicToString(e.topicId),m:e.memo},i=this.validateMessage(r);if(!i.valid)throw new Vf("Invalid register message",i.errors);if(!this.registryTopicId)throw new qf("Registry topic not available",e.name);t?.({stage:"submitting",percentage:50});const n=ty({registryTopicId:this.registryTopicId,name:e.name,topicId:this.topicToString(e.topicId),isPrivate:e.isPrivate,metadata:e.metadata,memo:e.memo}),{transactionId:o}=await this.submitPayload(n,this.operatorCtx.operatorKey);t?.({stage:"confirming",percentage:80,registerTxId:o}),await this.waitForMirrorNodeConfirmation(this.registryTopicId,o),t?.({stage:"complete",percentage:100,registerTxId:o}),this.logger.info(`Registered topic ${e.topicId} in registry`)}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async waitForMirrorNodeConfirmation(e,t,r=10){for(let n=0;n<r;n++){try{const r=await this.mirrorNode.getTopicMessages(e,{limit:10,order:"desc"});if(r.some(e=>{if("object"!=typeof e||null===e)return!1;return"string"==typeof e.consensus_timestamp}))return void this.logger.debug(`Transaction ${t} confirmed on mirror node`)}catch(i){this.logger.debug(`Mirror node check attempt ${n+1} failed:`,i)}await b(2e3)}this.logger.warn(`Transaction ${t} not found on mirror node after ${r} attempts`)}},exports.HCS20DeployMessageSchema=Mf,exports.HCS20Error=Hf,exports.HCS20MessageSchema=$f,exports.HCS20MintMessageSchema=Uf,exports.HCS20PointsIndexer=class{constructor(e,t,r){this.isProcessing=!1,this.lastIndexedSequence=new Map,this.logger=t||new y({level:"info",module:"HCS20PointsIndexer"}),this.mirrorNode=new x(e,this.logger,{customUrl:r}),this.state=this.initializeState()}initializeState(){return{deployedPoints:new Map,balances:new Map,transactions:[],lastProcessedSequence:0,lastProcessedTimestamp:(new Date).toISOString()}}getState(){return{...this.state,deployedPoints:new Map(this.state.deployedPoints),balances:new Map(this.state.balances),transactions:[...this.state.transactions]}}getPointsInfo(e){return this.state.deployedPoints.get(this.normalizeTick(e))}getBalance(e,t){const r=this.normalizeTick(e),i=this.state.balances.get(r);if(!i)return"0";const n=i.get(t);return n?.balance||"0"}async startIndexing(e){if(this.isProcessing)return void this.logger.warn("Indexing already in progress");this.isProcessing=!0;const t=!1!==e?.includePublicTopic,r=!1!==e?.includeRegistryTopic,i=t?e?.publicTopicId||_f.PUBLIC_TOPIC_ID:null,n=r?e?.registryTopicId||_f.REGISTRY_TOPIC_ID:null,o=e?.pollInterval||3e4;await this.indexTopics(i,n,e?.privateTopics);const s=async()=>{if(this.isProcessing){try{await this.indexTopics(i,n,e?.privateTopics)}catch(t){this.logger.error("Polling error:",t)}this.isProcessing&&setTimeout(s,o)}};setTimeout(s,o)}async indexOnce(e){const t=!1!==e?.includePublicTopic,r=!1!==e?.includeRegistryTopic,i=t?e?.publicTopicId||_f.PUBLIC_TOPIC_ID:null,n=r?e?.registryTopicId||_f.REGISTRY_TOPIC_ID:null;await this.indexTopics(i,n,e?.privateTopics)}stopIndexing(){this.isProcessing=!1,this.logger.info("Indexing stopped")}async indexTopics(e,t,r){this.logger.debug("Starting indexing cycle"),e&&await this.indexTopic(e,!1);const i=[...t?await this.getRegisteredTopics(t):[],...r||[]];for(const n of i)await this.indexTopic(n,!0);this.logger.debug("Indexing cycle complete")}async getRegisteredTopics(e){const t=[];try{(await this.mirrorNode.getTopicMessages(e,{limit:100,order:"asc"})).filter(e=>"hcs-20"===e.p&&"register"===e.op&&"string"==typeof e.t_id).forEach(e=>{t.push(e.t_id)})}catch(r){this.logger.error("Failed to fetch registry messages:",r)}return t}async indexTopic(e,t){try{const r=this.lastIndexedSequence.get(e);this.logger.debug(`Indexing topic ${e}, starting from sequence ${r||0}`);const i=await this.mirrorNode.getTopicMessages(e,{sequenceNumber:r?r+1:void 0,limit:1e3,order:"asc"});this.logger.debug(`Fetched ${i.length} messages from topic ${e}`);let n=r||0;for(const o of i){if("hcs-20"!==o.p)continue;const r=$f.safeParse(o);if(!r.success){this.logger.debug("Skipping message due to schema mismatch");continue}const i=r.data,s=o.sequence_number??0;this.logger.debug(`Found HCS-20 message: op=${i.op}, sequence=${s}`),s>n&&(n=s);const a={consensus_timestamp:o.consensus_timestamp??"",sequence_number:s,payer_account_id:o.payer_account_id??o.payer??"",transaction_id:o.transaction_id??""};this.processMessage(i,a,e,t),this.state.lastProcessedSequence++,this.state.lastProcessedTimestamp=o.consensus_timestamp||""}n>(r||0)&&this.lastIndexedSequence.set(e,n)}catch(r){this.logger.error(`Failed to index topic ${e}:`,r)}}processMessage(e,t,r,i){switch(e.op){case"deploy":this.processDeployMessage(e,t,r,i);break;case"mint":this.processMintMessage(e,t,r,i);break;case"transfer":this.processTransferMessage(e,t,r,i);break;case"burn":this.processBurnMessage(e,t,r,i)}}processDeployMessage(e,t,r,i){const n=this.normalizeTick(e.tick);if(this.state.deployedPoints.has(n))return;const o={name:e.name,tick:n,maxSupply:e.max,limitPerMint:e.lim,metadata:e.metadata,topicId:r,deployerAccountId:t.payer_account_id,currentSupply:"0",deploymentTimestamp:t.consensus_timestamp,isPrivate:i};this.state.deployedPoints.set(n,o),this.logger.info(`Deployed points: ${n}`)}processMintMessage(e,t,r,i){const n=this.normalizeTick(e.tick),o=this.state.deployedPoints.get(n);if(!o)return;const s=BigInt(e.amt),a=BigInt(o.currentSupply);if(a+s>BigInt(o.maxSupply))return;if(o.limitPerMint&&s>BigInt(o.limitPerMint))return;o.currentSupply=(a+s).toString();let c=this.state.balances.get(n);c||(c=new Map,this.state.balances.set(n,c));const l=c.get(e.to),u=l?(BigInt(l.balance)+s).toString():e.amt;c.set(e.to,{tick:n,accountId:e.to,balance:u,lastUpdated:t.consensus_timestamp}),this.state.transactions.push({id:t.transaction_id||`${r}-${t.sequence_number}`,operation:"mint",tick:n,amount:e.amt,to:e.to,timestamp:t.consensus_timestamp,sequenceNumber:t.sequence_number,topicId:r,transactionId:t.transaction_id||"",memo:e.m})}processTransferMessage(e,t,r,i){const n=this.normalizeTick(e.tick),o=this.state.balances.get(n);if(!o)return;if(!i&&t.payer_account_id!==e.from)return;const s=o.get(e.from);if(!s||BigInt(s.balance)<BigInt(e.amt))return;const a=BigInt(e.amt);s.balance=(BigInt(s.balance)-a).toString(),s.lastUpdated=t.consensus_timestamp;const c=o.get(e.to);c?(c.balance=(BigInt(c.balance)+a).toString(),c.lastUpdated=t.consensus_timestamp):o.set(e.to,{tick:n,accountId:e.to,balance:e.amt,lastUpdated:t.consensus_timestamp}),this.state.transactions.push({id:t.transaction_id||`${r}-${t.sequence_number}`,operation:"transfer",tick:n,amount:e.amt,from:e.from,to:e.to,timestamp:t.consensus_timestamp,sequenceNumber:t.sequence_number,topicId:r,transactionId:t.transaction_id||"",memo:e.m})}processBurnMessage(e,t,r,i){const n=this.normalizeTick(e.tick),o=this.state.deployedPoints.get(n),s=this.state.balances.get(n);if(!o||!s)return;if(!i&&t.payer_account_id!==e.from)return;const a=s.get(e.from);if(!a||BigInt(a.balance)<BigInt(e.amt))return;const c=BigInt(e.amt);a.balance=(BigInt(a.balance)-c).toString(),a.lastUpdated=t.consensus_timestamp,o.currentSupply=(BigInt(o.currentSupply)-c).toString(),this.state.transactions.push({id:t.transaction_id||`${r}-${t.sequence_number}`,operation:"burn",tick:n,amount:e.amt,from:e.from,timestamp:t.consensus_timestamp,sequenceNumber:t.sequence_number,topicId:r,transactionId:t.transaction_id||"",memo:e.m})}normalizeTick(e){return e.toLowerCase().trim()}},exports.HCS20RegisterMessageSchema=Kf,exports.HCS20TransferMessageSchema=Lf,exports.HCS20_CONSTANTS=_f,exports.HCS21BaseClient=sy,exports.HCS21BrowserClient=class extends sy{constructor(e){super({network:e.network,logger:e.logger}),this.hwc=e.hwc}async createRegistryTopic(e){const{publicKey:t}=await this.getSignerContext(),i=ny({ttl:e.ttl,indexed:e.indexed,type:e.type,metaTopicId:e.metaTopicId,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:t});e.transactionMemo&&i.setTransactionMemo(e.transactionMemo);const{receipt:n}=await this.executeWithWallet(i);if(n.status!==r.Status.Success||!n.topicId)throw new ry("Failed to create HCS-21 registry topic","invalid_payload");return n.topicId.toString()}async createAdapterVersionPointerTopic(e){const{publicKey:t}=await this.getSignerContext(),i=Af({registryType:yf.NON_INDEXED,ttl:e.ttl,adminKey:e.adminKey,submitKey:e.submitKey,memoOverride:e.memoOverride,operatorPublicKey:t});e.transactionMemo&&i.setTransactionMemo(e.transactionMemo);const{receipt:n}=await this.executeWithWallet(i);if(n.status!==r.Status.Success||!n.topicId)throw new ry("Failed to create HCS-2 registry version topic","invalid_payload");return n.topicId.toString()}async createRegistryDiscoveryTopic(e){const{publicKey:t}=await this.getSignerContext(),i=Af({registryType:yf.INDEXED,ttl:e.ttl,adminKey:e.adminKey,submitKey:e.submitKey,memoOverride:e.memoOverride,operatorPublicKey:t});e.transactionMemo&&i.setTransactionMemo(e.transactionMemo);const{receipt:n}=await this.executeWithWallet(i);if(n.status!==r.Status.Success||!n.topicId)throw new ry("Failed to create registry-of-registries topic","invalid_payload");return n.topicId.toString()}async createAdapterCategoryTopic(e){const{publicKey:t}=await this.getSignerContext(),i=ny({ttl:e.ttl,indexed:e.indexed??0,type:gc.ADAPTER_CATEGORY,metaTopicId:e.metaTopicId,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:t});e.transactionMemo&&i.setTransactionMemo(e.transactionMemo);const{receipt:n}=await this.executeWithWallet(i);if(n.status!==r.Status.Success||!n.topicId)throw new ry("Failed to create adapter category topic","invalid_payload");return n.topicId.toString()}async publishVersionPointer(e){const t=Cf({registryTopicId:e.versionTopicId,targetTopicId:e.declarationTopicId,memo:e.memo,analyticsMemo:e.transactionMemo}),{receipt:i,transactionId:n}=await this.executeWithWallet(t);if(i.status!==r.Status.Success)throw new ry("Failed to publish registry version pointer","invalid_payload");return{sequenceNumber:this.toNumber(i.topicSequenceNumber),transactionId:n}}async resolveVersionPointer(e){const[t]=await this.mirrorNode.getTopicMessages(e,{limit:1,order:"desc"});if(!t)throw new ry("Version pointer topic has no messages","invalid_payload");const r=t.t_id;if("string"!=typeof r||0===r.length)throw new ry("Version pointer topic does not include a declaration topic ID (`t_id`)","invalid_payload");const i="number"==typeof t.sequence_number?t.sequence_number:Number(t.sequence_number);return{versionTopicId:e,declarationTopicId:r,sequenceNumber:Number.isFinite(i)?i:0,payer:t.payer,memo:t.m,op:t.op}}async registerCategoryTopic(e){const t=Cf({registryTopicId:e.discoveryTopicId,targetTopicId:e.categoryTopicId,metadata:e.metadata,memo:e.memo,analyticsMemo:e.transactionMemo}),{receipt:i,transactionId:n}=await this.executeWithWallet(t);if(i.status!==r.Status.Success)throw new ry("Failed to register adapter category topic","invalid_payload");return{sequenceNumber:this.toNumber(i.topicSequenceNumber),transactionId:n}}async publishCategoryEntry(e){const t=e.memo??`adapter:${e.adapterId}`,i=Cf({registryTopicId:e.categoryTopicId,targetTopicId:e.versionTopicId,metadata:e.metadata,memo:t,analyticsMemo:e.transactionMemo}),{receipt:n,transactionId:o}=await this.executeWithWallet(i);if(n.status!==r.Status.Success)throw new ry("Failed to publish adapter category entry","invalid_payload");return{sequenceNumber:this.toNumber(n.topicSequenceNumber),transactionId:o}}async publishDeclaration(e){const t="p"in e.declaration?this.validateDeclaration(e.declaration):this.buildDeclaration(e.declaration),i=oy({topicId:e.topicId,declaration:t,transactionMemo:e.transactionMemo}),{receipt:n,transactionId:o}=await this.executeWithWallet(i);if(n.status!==r.Status.Success)throw new ry("Failed to submit HCS-21 declaration","invalid_payload");return{sequenceNumber:this.toNumber(n.topicSequenceNumber),transactionId:o}}async fetchDeclarations(e,t){const{messages:r=[]}=await this.hwc.getMessages(e),i=[];for(const s of r)if(s&&"hcs-21"===s.p)try{const e=this.validateDeclaration(s);i.push({declaration:e,consensusTimestamp:s.consensus_timestamp,sequenceNumber:Number(s.sequence_number??0),payer:s.payer})}catch(o){const e=o instanceof Error?o.message:"unknown error";this.logger.warn(`Skipping invalid HCS-21 browser message: ${e}`)}const n="desc"===t?.order?[...i].sort((e,t)=>t.sequenceNumber-e.sequenceNumber):i;return t?.limit&&t.limit>0?n.slice(0,t.limit):n}async getSignerContext(){if(this.signerCache)return this.signerCache;const e=this.hwc.getAccountInfo?.(),t="string"==typeof e?e:e?.accountId;if(!t)throw new ry("Wallet is not connected","invalid_payload");const i=await this.hwc.requestAccount(t),n=i?.key?.key;if(!n)throw new ry("Unable to resolve wallet public key","invalid_payload");const o=r.PublicKey.fromString(n);return this.signerCache={accountId:t,publicKey:o},this.signerCache}async executeWithWallet(e){const{accountId:t}=await this.getSignerContext(),i=r.TransactionId.generate(r.AccountId.fromString(t));e.setTransactionId(i);return{receipt:await this.hwc.executeTransaction(e,!1),transactionId:i.toString()}}toNumber(e){return"number"==typeof e?e:e&&"function"==typeof e.toNumber?e.toNumber():void 0}},exports.HCS21Client=class extends sy{constructor(e){const t=e.logger||new y({level:e.logLevel||"info",module:"HCS-21"});super({network:e.network,logger:t,mirrorNodeUrl:e.mirrorNodeUrl});const i=e.client??("mainnet"===e.network?r.Client.forMainnet():r.Client.forTestnet());this.operatorCtx=B({network:e.network,operatorId:e.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:i}),this.operatorCtx.ensureInitialized(),this.client=this.operatorCtx.client}async inscribeMetadata(e){await this.operatorCtx.ensureInitialized();const t=Ic.parse(e.document),r=JSON.stringify(t,null,2),i=globalThis.Buffer.from(r,"utf8"),n={waitForConfirmation:!0,connectionMode:e.inscriptionOptions?.connectionMode??(!1===e.inscriptionOptions?.websocket?"http":"auto"),websocket:e.inscriptionOptions?.websocket??!1,...e.inscriptionOptions||{},metadata:{...e.inscriptionOptions?.metadata||{},...t}},o=await Oa({type:"buffer",buffer:i,fileName:e.fileName||`hcs21-adapter-manifest-${Date.now()}.json`,mimeType:"application/json"},{accountId:this.operatorCtx.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},n);if(!o.confirmed||!o.inscription)throw new ry("Failed to inscribe HCS-21 metadata","invalid_payload");const s=o.inscription.jsonTopicId||o.inscription.topic_id||Ha(o.inscription);if(!s)throw new ry("Metadata inscription did not return a topic ID","invalid_payload");const a=o.inscription.sequence_number??o.inscription.sequenceNumber,c=await this.resolveManifestPointer(s,a),l=o.result?.manifest_sequence,u=o.result&&"jobId"in o.result?{jobId:o.result.jobId,transactionId:o.result.transactionId,totalCostHbar:o.costSummary?.totalCostHbar,costBreakdown:o.costSummary?.breakdown}:{};return{pointer:c.pointer,topicId:s,sequenceNumber:c.sequenceNumber,manifestSequence:l||c.sequenceNumber,...u}}async createRegistryTopic(e){await this.operatorCtx.ensureInitialized();const t=ny({ttl:e.ttl,indexed:e.indexed,type:e.type,metaTopicId:e.metaTopicId,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:this.operatorCtx.operatorKey.publicKey});e.transactionMemo&&t.setTransactionMemo(e.transactionMemo);const i=await t.execute(this.client),n=await i.getReceipt(this.client);if(n.status!==r.Status.Success||!n.topicId)throw new ry("Failed to create HCS-21 registry topic","invalid_payload");return n.topicId.toString()}async createAdapterVersionPointerTopic(e){await this.operatorCtx.ensureInitialized();const t=Af({registryType:yf.NON_INDEXED,ttl:e.ttl,adminKey:e.adminKey,submitKey:e.submitKey,memoOverride:e.memoOverride,operatorPublicKey:this.operatorCtx.operatorKey.publicKey});e.transactionMemo&&t.setTransactionMemo(e.transactionMemo);const i=await t.execute(this.client),n=await i.getReceipt(this.client);if(n.status!==r.Status.Success||!n.topicId)throw new ry("Failed to create HCS-2 registry version topic","invalid_payload");return n.topicId.toString()}async createRegistryDiscoveryTopic(e){await this.operatorCtx.ensureInitialized();const t=Af({registryType:yf.INDEXED,ttl:e.ttl,adminKey:e.adminKey,submitKey:e.submitKey,memoOverride:e.memoOverride,operatorPublicKey:this.operatorCtx.operatorKey.publicKey});e.transactionMemo&&t.setTransactionMemo(e.transactionMemo);const i=await t.execute(this.client),n=await i.getReceipt(this.client);if(n.status!==r.Status.Success||!n.topicId)throw new ry("Failed to create registry-of-registries topic","invalid_payload");return n.topicId.toString()}async createAdapterCategoryTopic(e){await this.operatorCtx.ensureInitialized();const t=ny({ttl:e.ttl,indexed:e.indexed??0,type:gc.ADAPTER_CATEGORY,metaTopicId:e.metaTopicId,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:this.operatorCtx.operatorKey.publicKey});e.transactionMemo&&t.setTransactionMemo(e.transactionMemo);const i=await t.execute(this.client),n=await i.getReceipt(this.client);if(n.status!==r.Status.Success||!n.topicId)throw new ry("Failed to create adapter category topic","invalid_payload");return n.topicId.toString()}async publishVersionPointer(e){await this.operatorCtx.ensureInitialized();const t=Cf({registryTopicId:e.versionTopicId,targetTopicId:e.declarationTopicId,memo:e.memo,analyticsMemo:e.transactionMemo}),i=await t.execute(this.client),n=await i.getReceipt(this.client);if(n.status!==r.Status.Success)throw new ry("Failed to publish registry version pointer","invalid_payload");return{sequenceNumber:n.topicSequenceNumber?.toNumber(),transactionId:i.transactionId.toString()}}async resolveVersionPointer(e){const[t]=await this.mirrorNode.getTopicMessages(e,{limit:1,order:"desc"});if(!t)throw new ry("Version pointer topic has no messages","invalid_payload");const r=t.t_id;if("string"!=typeof r||0===r.length)throw new ry("Version pointer topic does not include a declaration topic ID (`t_id`)","invalid_payload");const i="number"==typeof t.sequence_number?t.sequence_number:Number(t.sequence_number);return{versionTopicId:e,declarationTopicId:r,sequenceNumber:Number.isFinite(i)?i:0,payer:t.payer,memo:t.m,op:t.op}}async registerCategoryTopic(e){await this.operatorCtx.ensureInitialized();const t=Cf({registryTopicId:e.discoveryTopicId,targetTopicId:e.categoryTopicId,metadata:e.metadata,memo:e.memo,analyticsMemo:e.transactionMemo}),i=await t.execute(this.client),n=await i.getReceipt(this.client);if(n.status!==r.Status.Success)throw new ry("Failed to register adapter category topic","invalid_payload");return{sequenceNumber:n.topicSequenceNumber?.toNumber(),transactionId:i.transactionId.toString()}}async publishCategoryEntry(e){await this.operatorCtx.ensureInitialized();const t=e.memo??`adapter:${e.adapterId}`,i=Cf({registryTopicId:e.categoryTopicId,targetTopicId:e.versionTopicId,metadata:e.metadata,memo:t,analyticsMemo:e.transactionMemo}),n=await i.execute(this.client),o=await n.getReceipt(this.client);if(o.status!==r.Status.Success)throw new ry("Failed to publish adapter category entry","invalid_payload");return{sequenceNumber:o.topicSequenceNumber?.toNumber(),transactionId:n.transactionId.toString()}}async publishDeclaration(e){await this.operatorCtx.ensureInitialized();const t=this.normalizeDeclarationInput(e.declaration),i=oy({topicId:e.topicId,declaration:t,transactionMemo:e.transactionMemo}),n=await i.execute(this.client),o=await n.getReceipt(this.client);if(o.status!==r.Status.Success)throw new ry("Failed to submit HCS-21 declaration","invalid_payload");return{sequenceNumber:o.topicSequenceNumber?.toNumber(),transactionId:n.transactionId.toString()}}normalizeDeclarationInput(e){return"p"in e?this.validateDeclaration(e):this.buildDeclaration(e)}async resolveManifestPointer(e,t){const r="string"==typeof t?Number(t):t;let i="number"==typeof r&&Number.isFinite(r)?r:void 0;if(!i){const[t]=await this.mirrorNode.getTopicMessages(e,{limit:1,order:"desc"});if(!t||!t.sequence_number)throw new ry("Unable to resolve manifest sequence number","invalid_payload");i=Number(t.sequence_number)}if(!Number.isFinite(i))throw new ry("Invalid manifest sequence number","invalid_payload");const n=`hcs://1/${e}`;if(!pc.test(n))throw new ry("Manifest pointer format is invalid","invalid_payload");return{pointer:n,sequenceNumber:i}}},exports.HCS21ManifestPointerPattern=pc,exports.HCS21MetadataPointerPattern=hc,exports.HCS21TopicIdPattern=/^0\.0\.\d+$/,exports.HCS21TopicType=gc,exports.HCS21ValidationError=ry,exports.HCS21_MAX_MESSAGE_BYTES=uc,exports.HCS21_PROTOCOL=lc,exports.HCS21_SAFE_MESSAGE_BYTES=dc,exports.HCS26BaseClient=Ew,exports.HCS26BrowserClient=class extends Ew{constructor(e){super({network:e.network,logger:e.logger,mirrorNode:e.mirrorNode,verificationProvider:e.verificationProvider})}},exports.HCS26Client=class extends Ew{constructor(e){const t=e.verificationProvider??(e.registryBrokerClient?Aw(e.registryBrokerClient):void 0);super({network:e.network,logger:e.logger,mirrorNode:e.mirrorNode,verificationProvider:t})}},exports.HCS26_DEFAULT_TTL_SECONDS=86400,exports.HCS26_PROTOCOL=Ub,exports.HCS27BaseClient=Fb,exports.HCS27Client=class extends Fb{constructor(e){super(e),this.topicSubmitKeySigners=new Map,this.operatorId="string"==typeof e.operatorId?r.AccountId.fromString(e.operatorId):e.operatorId;let t=e.client;t||(t="mainnet"===e.network?r.Client.forMainnet():r.Client.forTestnet()),this.operatorCtx=B({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:t}),this.client=this.operatorCtx.client}getKeyType(){return this.operatorCtx.keyType}async createCheckpointTopic(e={}){await this.operatorCtx.ensureInitialized();const t=(new r.TopicCreateTransaction).setTopicMemo(this.buildTopicMemo(e.ttl)),i=this.resolveTopicKeyMaterial(e.adminKey);this.assertSignableTopicKey(e.adminKey,i,"adminKey"),i.publicKey&&t.setAdminKey(i.publicKey);const n=this.resolveTopicKeyMaterial(e.submitKey);let o;if(this.assertSignableTopicKey(e.submitKey,n,"submitKey"),n.publicKey&&t.setSubmitKey(n.publicKey),e.transactionMemo?.trim()&&t.setTransactionMemo(e.transactionMemo.trim()),i.signer||n.signer){let e=await t.freezeWith(this.client);i.signer&&(e=await e.sign(i.signer)),n.signer&&(e=await e.sign(n.signer)),o=await e.execute(this.client)}else o=await t.execute(this.client);const s=await o.getReceipt(this.client);if(!s.topicId)throw new Error("Failed to create checkpoint topic: topicId empty");return n.signer&&this.topicSubmitKeySigners.set(s.topicId.toString(),n.signer),{topicId:s.topicId.toString(),transactionId:o.transactionId.toString()}}async publishCheckpoint(e,t,i,n){await this.operatorCtx.ensureInitialized();const o=r.TopicId.fromString(e).toString(),s=yb(pb.parse(t)),{message:a,inlineResolvedMetadata:c}=await this.prepareCheckpointPayload(s,i);"string"==typeof a.metadata&&c?await this.validateCheckpointMessage(a,async e=>e===a.metadata?c:this.resolveHCS1Reference(e)):await this.validateCheckpointMessage(a);const l=(new r.TopicMessageSubmitTransaction).setTopicId(r.TopicId.fromString(o)).setMessage(JSON.stringify(a)).setTransactionMemo(n?.trim()||this.buildTransactionMemo()),u=this.topicSubmitKeySigners.get(o),d=u?await(await l.freezeWith(this.client)).sign(u).then(e=>e.execute(this.client)):await l.execute(this.client),p=await d.getReceipt(this.client);return{transactionId:d.transactionId.toString(),sequenceNumber:this.parseSequenceNumber(p.topicSequenceNumber),receipt:p}}registerTopicSubmitKey(e,t){const i=this.resolveTopicKeyMaterial(t);if(!i.signer)throw new Error("submitKey must include a private key so the client can sign private-topic submissions");this.topicSubmitKeySigners.set(r.TopicId.fromString(e).toString(),i.signer)}resolveTopicKeyMaterial(e){if(void 0===e||!1===e)return{};if(e instanceof r.PublicKey||e instanceof r.KeyList)return{publicKey:e};if(e instanceof r.PrivateKey)return{publicKey:e.publicKey,signer:e};if("boolean"==typeof e)return e?{publicKey:this.operatorCtx.operatorKey.publicKey}:{};if("string"==typeof e){if(0===e.trim().length)throw new Error("topic key string cannot be empty");try{return{publicKey:r.PublicKey.fromString(e)}}catch(t){try{const t=r.PrivateKey.fromString(e);return{publicKey:t.publicKey,signer:t}}catch(i){throw new Error(`Failed to parse topic key as PublicKey or PrivateKey: ${String(t)}; ${String(i)}`)}}}return{}}assertSignableTopicKey(e,t,r){if(e&&"boolean"!=typeof e&&!t.signer&&t.publicKey&&!this.operatorCanSignTopicKey(t.publicKey))throw new Error(`${r} must include a private key or use true to reuse the operator key`)}operatorCanSignTopicKey(e){return e instanceof r.PublicKey?this.operatorCtx.operatorKey.publicKey.equals(e):this.operatorCanSignKeyList(e)}operatorCanSignKeyList(e){const t=e.toArray();return!((e.threshold??t.length)>1||0===t.length)&&t.some(e=>e instanceof r.PublicKey?this.operatorCtx.operatorKey.publicKey.equals(e):e instanceof r.KeyList&&this.operatorCanSignKeyList(e))}parseSequenceNumber(e){const t=BigInt(e.toString());if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("topicSequenceNumber exceeds Number.MAX_SAFE_INTEGER and cannot be represented safely");return Number(t)}async prepareCheckpointPayload(e,t){const r=t?.trim();if(r&&r.length>299)throw new Error("messageMemo must be 299 characters or fewer for HCS-27 checkpoints");const i={p:"hcs-27",op:"register",metadata:e,...r?{m:r}:{}},n=JSON.stringify(i);if(globalThis.Buffer.byteLength(n,"utf8")<=Mb)return{message:i};const o=globalThis.Buffer.from(JSON.stringify(e),"utf8"),s=this.sha256Base64Url(o);gb.parse({p:"hcs-27",op:"register",metadata:"hcs://1/18446744073709551615.18446744073709551615.18446744073709551615",metadata_digest:{alg:"sha-256",b64u:s},...r?{m:r}:{}});const a=JSON.stringify({p:"hcs-27",op:"register",metadata:"hcs://1/18446744073709551615.18446744073709551615.18446744073709551615",metadata_digest:{alg:"sha-256",b64u:s},...r?{m:r}:{}});if(globalThis.Buffer.byteLength(a,"utf8")>Mb)throw new Error("checkpoint overflow pointer message exceeds 1024 bytes");const c={p:"hcs-27",op:"register",metadata:await this.publishMetadataHCS1(o),metadata_digest:{alg:"sha-256",b64u:s},...r?{m:r}:{}},l=JSON.stringify(c);if(globalThis.Buffer.byteLength(l,"utf8")>Mb)throw new Error("checkpoint overflow pointer message still exceeds 1024 bytes");return{message:c,inlineResolvedMetadata:o}}async publishMetadataHCS1(e){if("testnet"!==this.network&&"mainnet"!==this.network)throw new Error(`HCS-1 metadata publication is only supported on testnet and mainnet, got ${this.network}`);const t={accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network};this.inscriptionSDK||(this.inscriptionSDK=await es.createWithAuth({type:"server",...t}));const r=Ha((await Oa({type:"buffer",buffer:e,fileName:`hcs27-checkpoint-${d.randomUUID()}.json`,mimeType:"application/json"},t,{mode:"file",fileStandard:"hcs-1",waitForConfirmation:!0,waitMaxAttempts:120,waitIntervalMs:2e3},this.inscriptionSDK)).inscription);if(!r)throw new Error("Failed to inscribe overflow HCS-27 metadata: no topic ID returned");return`hcs://1/${r}`}sha256Base64Url(e){return d.createHash("sha256").update(e).digest("base64url")}},exports.HCS2BaseClient=Ef,exports.HCS2Client=Nf,exports.HCS2Operation=ff,exports.HCS2RegistryType=yf,exports.HCS5BrowserClient=class extends gf{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,logger:void 0,operatorId:"0.0.0",operatorKey:""}),this.hwc=e.hwc,this.signer=e.signer}getSigner(){if(this.signer)return this.signer;const e=this.hwc.getAccountInfo()?.accountId,t=this.hwc.dAppConnector?.signers?.find(t=>t.getAccountId().toString()===e);if(!t)throw new Error("No active wallet signer");return t}async mint(e){try{if(!e.metadataTopicId)return{success:!1,error:"metadataTopicId is required for mint()"};const t=hf(e.metadataTopicId),i=mf({tokenId:e.tokenId,metadata:t});let n;if(e.supplyKey&&e.supplyKey instanceof r.PrivateKey){const t=this.getSigner();await i.freezeWithSigner(t);const r=await i.sign(e.supplyKey);n=await this.hwc.executeTransactionWithErrorHandling(r,!0)}else n=await this.hwc.executeTransactionWithErrorHandling(i,!1);if(n.error)return{success:!1,error:n.error};const o=n.result;return{success:!0,serialNumber:o.serials?.[0]?Number(o.serials[0].toString()):void 0,transactionId:o?.transactionId?.toString?.(),metadata:t}}catch(Pw){return{success:!1,error:String(Pw)}}}async createHashinal(e){try{const t=this.getSigner(),r={...e.inscriptionOptions,mode:"hashinal",waitForConfirmation:!0,network:this.network},i=await Fa(e.inscriptionInput,t,r),n=i.inscription?.jsonTopicId||i.inscription?.topic_id;return i.confirmed&&n?await this.mint({tokenId:e.tokenId,metadataTopicId:n,supplyKey:e.supplyKey,memo:e.memo}):{success:!1,error:"Failed to inscribe content"}}catch(Pw){return{success:!1,error:String(Pw)}}}},exports.HCS5Client=class extends gf{constructor(e){super(e),this.operatorId=r.AccountId.fromString(e.operatorId),this.operatorCtx=B({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,mirrorNode:this.mirrorNode,logger:this.logger,client:e.client}),this.client=this.operatorCtx.client}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}async mint(e){try{if(await this.ensureInitialized(),!e.metadataTopicId)return{success:!1,error:"metadataTopicId is required for mint()"};const t=hf(e.metadataTopicId),r=mf({tokenId:e.tokenId,metadata:t}),i=await r.freezeWith(this.client);if(e.supplyKey){const t=new U({mirrorNode:this.mirrorNode,logger:this.logger}),r="string"==typeof e.supplyKey?await t.resolveSupplyKey(e.tokenId,e.supplyKey,this.operatorCtx.keyType):e.supplyKey;await i.sign(r)}const n=await i.execute(this.client),o=await n.getReceipt(this.client);return{success:!0,serialNumber:o.serials&&o.serials[0]?Number(o.serials[0].toString()):void 0,transactionId:n.transactionId?.toString?.(),metadata:t}}catch(Pw){const t=Pw;return this.logger.error(`Failed to mint HCS-5 Hashinal: ${t.message}`),{success:!1,error:t.message}}}async createHashinal(e){try{await this.ensureInitialized();const t=await Oa(e.inscriptionInput,{accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},{...e.inscriptionOptions||{},mode:"hashinal",waitForConfirmation:!0});if(!t.confirmed||!t.inscription)return{success:!1,error:"Failed to inscribe content"};const r=t.inscription.jsonTopicId||t.inscription.topic_id;return r?await this.mint({tokenId:e.tokenId,metadataTopicId:r,supplyKey:e.supplyKey,memo:e.memo}):{success:!1,error:"No topic ID from inscription"}}catch(Pw){const t=Pw;return this.logger.error(`Failed to inscribe and mint HCS-5 Hashinal: ${t.message}`),{success:!1,error:t.message}}}},exports.HCS6BaseClient=N,exports.HCS6BrowserClient=class extends N{constructor(e){super(e),this.hwc=e.hwc,this.signer=e.signer}ensureConnected(){const e=this.hwc.getAccountInfo(),t=e?.accountId;if(!t)throw new Error("No active wallet connection: wallet integration required to perform write operations");return t}getSigner(){const e=this.signer;if(e)return e;this.ensureConnected();const t=this.hwc.dAppConnector,r=t?.signers?.[0];if(!r)throw new Error("No active wallet signer");return r}async createRegistry(e){try{this.ensureConnected();const t=e?.ttl??86400,r=this.generateRegistryMemo(t),i=await this.hwc.createTopic(r);return this.logger.info(`Created HCS-6 registry topic via wallet: ${i} (TTL ${t})`),{success:!0,topicId:i}}catch(t){return this.logger.error(`Failed to create HCS-6 registry: ${t}`),{success:!1,error:String(t)}}}async registerEntry(e,t){try{if(!(await this.validateHCS6Topic(e)))throw new Error(`Topic ${e} is not a valid HCS-6 registry`);const r=this.createRegisterMessage(t.targetTopicId,t.memo),i=await this.submitMessage(e,r),n=i.topicSequenceNumber;return{success:!0,receipt:i,sequenceNumber:"number"==typeof n?n:n?.low}}catch(r){return this.logger.error(`Failed to register HCS-6 entry: ${r}`),{success:!1,error:String(r)}}}async getRegistry(e,t={}){try{const r=await this.mirrorNode.getTopicInfo(e);this.logger.debug(`Retrieved topic info for HCS-6 ${e}: ${JSON.stringify(r)}`);const i=this.parseRegistryTypeFromMemo(r.memo);if(!i)throw new Error(`Topic ${e} is not an HCS-6 registry (invalid memo format)`);this.logger.debug(`Retrieving messages for HCS-6 topic ${e} with limit ${t.limit??100}`);const n=await this.mirrorNode.getTopicMessages(e,{sequenceNumber:t.skip&&t.skip>0?`gt:${t.skip}`:void 0,limit:t.limit??100,order:t.order??"asc"}),o=t.limit?n.slice(0,t.limit):n;return this.logger.debug(`Retrieved ${n.length} messages, using ${o.length} after applying limit.`),this.parseRegistryEntries(e,o,i.registryType,i.ttl)}catch(r){throw this.logger.error(`Failed to get HCS-6 registry: ${r}`),r}}async submitMessage(e,t){this.ensureConnected();const{valid:r,errors:i}=this.validateMessage(t);if(!r)throw new Error(`Invalid HCS-6 message: ${i.join(", ")}`);return await this.hwc.submitMessageToTopic(e,JSON.stringify(t))}async createHashinal(e){try{if(!this.signer)return{success:!1,error:"No signer configured for browser createHashinal"};const t={...e.inscriptionOptions,mode:"hashinal",metadata:e.metadata,waitForConfirmation:!0,network:this.network},r={type:"buffer",buffer:globalThis.Buffer.from(JSON.stringify(e.metadata)),fileName:"metadata.json",mimeType:"application/json"},i=await Fa(r,this.signer,t),n=i.inscription?.jsonTopicId||Ha(i.inscription);if(!n)return{success:!1,error:"Failed to inscribe metadata"};let o=e.registryTopicId;if(!o){const t=await this.createRegistry({ttl:e.ttl});if(!t.success||!t.topicId)return{success:!1,error:t.error};o=t.topicId}const s=await this.registerEntry(o,{targetTopicId:n,memo:e.memo||"Initial dynamic hashinal registration"});return s.success?{success:!0,registryTopicId:o,inscriptionTopicId:n}:{success:!1,error:s.error}}catch(t){return this.logger.error(`Failed to create dynamic hashinal: ${t}`),{success:!1,error:String(t)}}}async register(e){try{if(!this.signer)return{success:!1,error:"No signer configured for browser register"};let t;t=e.data?.base64?{type:"buffer",buffer:globalThis.Buffer.from(e.data.base64,"base64"),fileName:"data."+(e.data.mimeType?.split("/")[1]||"bin"),mimeType:e.data.mimeType||"application/octet-stream"}:e.data?.url?{type:"url",url:e.data.url}:{type:"buffer",buffer:globalThis.Buffer.from(JSON.stringify(e.metadata)),fileName:"metadata.json",mimeType:"application/json"};const r={...e.inscriptionOptions,mode:"hashinal",metadata:e.metadata,waitForConfirmation:!0,network:this.network},i=await Fa(t,this.signer,r),n=i.inscription?.jsonTopicId||Ha(i.inscription);if(!n)return{success:!1,error:"Failed to inscribe data"};let o=e.registryTopicId;if(!o){const t=await this.createRegistry({ttl:e.ttl});if(!t.success||!t.topicId)return{success:!1,error:t.error};o=t.topicId}const s=await this.registerEntry(o,{targetTopicId:n,memo:e.memo||"Dynamic hashinal registration"});return s.success?{success:!0,registryTopicId:o,inscriptionTopicId:n}:{success:!1,error:s.error}}catch(t){return this.logger.error(`Failed to register dynamic hashinal: ${t}`),{success:!1,error:String(t)}}}async validateHCS6Topic(e){try{const t=await this.mirrorNode.getTopicInfo(e),r=this.parseRegistryTypeFromMemo(t.memo);return r?r.registryType===T.NON_INDEXED||(this.logger.warn(`Topic ${e} is not a valid HCS-6 registry (must be non-indexed)`),!1):(this.logger.warn(`Topic ${e} is not a valid HCS-6 registry (invalid memo format)`),!1)}catch(t){return this.logger.error(`Error validating HCS-6 topic ${e}: ${t}`),!1}}},exports.HCS6Client=class extends N{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,mirrorNodeUrl:e.mirrorNodeUrl,logger:e.logger}),this.operatorId="string"==typeof e.operatorId?r.AccountId.fromString(e.operatorId):e.operatorId,this.operatorCtx=B({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:e.client??this.createClient(e.network)}),this.client=this.operatorCtx.client}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}createClient(e){return"mainnet"===e?r.Client.forMainnet():r.Client.forTestnet()}close(){this.logger.info("HCS-6 client closed.")}getKeyType(){return this.operatorCtx.keyType}getOperatorKey(){return this.operatorCtx.operatorKey}async submitMessage(e,t){return this.submitMessageWithKey(e,t,void 0)}async submitMessageWithKey(e,t,i){const{valid:n,errors:o}=this.validateMessage(t);if(!n)throw new Error(`Invalid HCS-6 message: ${o.join(", ")}`);let s=(new r.TopicMessageSubmitTransaction).setTopicId(r.TopicId.fromString(e)).setMessage(JSON.stringify(t));if(!i){const e=await s.execute(this.client);return await e.getReceipt(this.client)}const a="string"==typeof i?r.PrivateKey.fromString(i):i,c=await s.freezeWith(this.client);await c.sign(a);const l=await c.execute(this.client);return await l.getReceipt(this.client)}async registerEntryWithKey(e,t,r){try{const i=this.createRegisterMessage(t.targetTopicId,t.memo),n=await this.submitMessageWithKey(e,i,r),o=n.topicSequenceNumber?.toNumber();return{success:!0,receipt:n,sequenceNumber:o}}catch(i){return this.logger.error(`Failed to register HCS-6 entry: ${i}`),{success:!1,error:String(i)}}}async createRegistry(e={}){try{await this.ensureInitialized();const t=e.ttl??86400;if(!(t>=3600))throw new Error("TTL must be at least 3600 seconds (1 hour)");let i,n;if(e.submitKey)if("string"==typeof e.submitKey)try{i=r.PublicKey.fromString(e.submitKey)}catch{const t=globalThis.Buffer.from(e.submitKey.replace(/^0x/i,""),"hex");i="ed25519"===this.operatorCtx.keyType?r.PublicKey.fromBytesED25519(t):r.PublicKey.fromBytesECDSA(t)}else"boolean"==typeof e.submitKey?i=this.operatorCtx.operatorKey.publicKey:(i=e.submitKey.publicKey,n=e.submitKey);let o=P({ttl:t,submitKey:i,adminKey:this.operatorCtx.operatorKey.publicKey,operatorPublicKey:this.operatorCtx.operatorKey.publicKey});const s=await o.freezeWith(this.client);n&&await s.sign(n);const a=await s.execute(this.client),c=(await a.getReceipt(this.client)).topicId;if(!c)throw new Error("Failed to create HCS-6 registry: No topic ID in receipt");return{success:!0,topicId:c.toString(),transactionId:a.transactionId.toString()}}catch(t){return this.logger.error(`Failed to create HCS-6 registry: ${t}`),{success:!1,error:`Failed to create HCS-6 registry: ${t}`}}}async registerEntry(e,t){return await this.ensureInitialized(),this.registerEntryWithKey(e,t,void 0)}async getRegistry(e,t={}){await this.ensureInitialized();const r=((await this.mirrorNode.getTopicInfo(e)).memo||"").match(/^hcs-6:(\d):(\d+)$/);if(!r)throw new Error(`Topic ${e} is not an HCS-6 registry (invalid memo format)`);const i=parseInt(r[2]),n=parseInt(r[1]),o=(await this.mirrorNode.getTopicMessages(e,{sequenceNumber:t.skip&&t.skip>0?`gt:${t.skip}`:void 0,limit:t.limit??100,order:t.order??"asc"})).map(t=>{try{const r=t,{valid:i}=this.validateMessage(r);return i?{topicId:e,sequence:r.sequence_number,timestamp:r.consensus_timestamp||"",payer:r.payer||"",message:r,consensus_timestamp:r.consensus_timestamp||"",registry_type:n}:null}catch{return null}}).filter(e=>Boolean(e)),s=o.length>0?o[o.length-1]:void 0;return{topicId:e,registryType:n,ttl:i,entries:o,latestEntry:s}}async mint(e){try{if(await this.ensureInitialized(),!e.metadataTopicId)return{success:!1,error:"metadataTopicId is required for mint()"};const t=S(e.metadataTopicId);let i=(new r.TokenMintTransaction).setTokenId(r.TokenId.fromString(e.tokenId)).setMetadata([globalThis.Buffer.from(t)]);const n=await i.freezeWith(this.client);if(e.supplyKey){const t=new U({mirrorNode:this.mirrorNode,logger:this.logger}),r="string"==typeof e.supplyKey?await t.resolveSupplyKey(e.tokenId,e.supplyKey,this.operatorCtx.keyType):e.supplyKey;await n.sign(r)}const o=await n.execute(this.client),s=await o.getReceipt(this.client);return{success:!0,serialNumber:s.serials&&s.serials[0]?Number(s.serials[0].toString()):void 0,transactionId:o.transactionId?.toString?.(),metadata:t}}catch(Pw){return{success:!1,error:String(Pw)}}}async inscribeAndMint(e){try{await this.ensureInitialized();const t={...e.inscriptionOptions,mode:"hashinal",waitForConfirmation:!0},r=await Oa(e.inscriptionInput,{accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},t);if(!r.confirmed||!r.inscription)return{success:!1,error:"Failed to inscribe content"};const i=r.inscription.jsonTopicId||r.inscription.topic_id;return i?await this.mint({tokenId:e.tokenId,metadataTopicId:i,supplyKey:e.supplyKey,memo:e.memo}):{success:!1,error:"No topic ID from inscription"}}catch(Pw){return{success:!1,error:String(Pw)}}}async createHashinal(e){try{let t,r;if(await this.ensureInitialized(),e.registryTopicId){t=e.registryTopicId;const r=(await this.mirrorNode.getTopicInfo(t)).memo||"";if(!/^hcs-6:\d:\d+$/.test(r))throw new Error(`Topic ${t} is not a valid HCS-6 registry`)}else{const i=await this.createRegistry({ttl:e.ttl,submitKey:!0});if(!i.success||!i.topicId)throw new Error(i.error||"Failed to create HCS-6 registry");t=i.topicId,r=i.transactionId}const i=globalThis.Buffer.from(JSON.stringify(e.metadata)),n={...e.inscriptionOptions,mode:"hashinal",metadata:e.metadata,waitForConfirmation:!0},o=await Oa({type:"buffer",buffer:i,fileName:"metadata.json",mimeType:"application/json"},{accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},n);if(!o.confirmed||!o.inscription)throw new Error("Failed to inscribe metadata");const s=o.inscription.jsonTopicId||o.inscription.topic_id;if(!s)throw new Error("No inscription topic ID available");const a=await this.registerEntryWithKey(t,{targetTopicId:s,memo:e.memo||"Dynamic hashinal registration"},e.submitKey);if(!a.success)throw new Error(a.error||"Failed to register entry");return{success:!0,registryTopicId:t,inscriptionTopicId:s,transactionId:r}}catch(Pw){return{success:!1,error:String(Pw)}}}async register(e){try{let t,r,i;if(await this.ensureInitialized(),e.registryTopicId){t=e.registryTopicId;const r=(await this.mirrorNode.getTopicInfo(t)).memo||"";if(!/^hcs-6:\d:\d+$/.test(r))throw new Error(`Topic ${t} is not a valid HCS-6 registry`)}else{const i=await this.createRegistry({ttl:e.ttl,submitKey:!0});if(!i.success||!i.topicId)throw new Error(i.error||"Failed to create HCS-6 registry");t=i.topicId,r=i.transactionId}if(e.data?.base64){i={type:"buffer",buffer:globalThis.Buffer.from(e.data.base64,"base64"),fileName:`data.${e.data.mimeType?.split("/")[1]||"bin"}`,mimeType:e.data.mimeType||"application/octet-stream"}}else i=e.data?.url?{type:"url",url:e.data.url}:{type:"buffer",buffer:globalThis.Buffer.from(JSON.stringify(e.metadata)),fileName:"metadata.json",mimeType:"application/json"};const n={...e.inscriptionOptions,mode:"hashinal",metadata:e.metadata,waitForConfirmation:!0},o=await Oa(i,{accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},n);if(!o.confirmed||!o.inscription)throw new Error("Failed to inscribe data");const s=o.inscription.jsonTopicId||o.inscription.topic_id;if(!s)throw new Error("No inscription topic ID available");const a=await this.registerEntryWithKey(t,{targetTopicId:s,memo:e.memo||"Dynamic hashinal registration"},e.submitKey);if(!a.success)throw new Error(a.error||"Failed to register entry");return{success:!0,registryTopicId:t,inscriptionTopicId:s,transactionId:r}}catch(Pw){return{success:!1,error:String(Pw)}}}},exports.HCS6Operation=I,exports.HCS6RegistryType=T,exports.HCS7BaseClient=ec,exports.HCS7BrowserClient=class extends ec{constructor(e){super(e),this.hwc=e.hwc}ensureConnected(){const e=this.hwc.getAccountInfo();if(!e?.accountId)throw new Error("No active wallet connection")}async createRegistry(e={}){try{this.ensureConnected();const t=e.ttl??86400;if(t<3600)throw new Error("TTL must be at least 3600 seconds");const r=this.generateRegistryMemo(t),i=await this.hwc.createTopic(r);return this.logger.info(`Created HCS-7 registry topic ${i}`),{success:!0,topicId:i}}catch(t){return this.logger.error("Failed to create HCS-7 registry in browser",t),{success:!1,error:String(t)}}}async registerConfig(e){const t=this.createConfigMessage({config:e.config,memo:e.memo});return this.submitWithWallet({topicId:e.registryTopicId,message:t})}async registerMetadata(e){const t=this.createMetadataMessage(e);return this.submitWithWallet({topicId:e.registryTopicId,message:t})}async submitWithWallet(e){try{this.ensureConnected();const{valid:t,errors:r}=this.validateMessage(e.message);if(!t)return{success:!1,error:`Invalid HCS-7 payload: ${r.join(", ")}`};const i=await this.hwc.submitMessageToTopic(e.topicId,JSON.stringify(e.message));return{success:!0,receipt:i,sequenceNumber:tc(i)}}catch(t){return this.logger.error("Failed to submit HCS-7 browser message",t),{success:!1,error:String(t)}}}},exports.HCS7Client=class extends ec{constructor(e){super(e),this.closed=!1,this.operatorCtx=B({network:this.network,operatorId:e.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:e.client}),this.client=this.operatorCtx.client}close(){this.closed||(this.closed=!0,this.logger.info("HCS-7 client closed"))}getKeyType(){return this.operatorCtx.keyType}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}resolvePublicKey(e){if(e){if("boolean"==typeof e)return e?this.operatorCtx.operatorKey.publicKey:void 0;if("string"==typeof e)try{return r.PublicKey.fromString(e)}catch{return}return e.publicKey}}coercePrivateKey(e){if(e instanceof r.PrivateKey)return e;try{return r.PrivateKey.fromStringED25519(e)}catch{return r.PrivateKey.fromStringECDSA(e)}}async createRegistry(e={}){const t=e.ttl??86400;if(t<3600)return{success:!1,error:"TTL must be at least 3600 seconds"};try{await this.ensureInitialized();const r=this.resolvePublicKey(e.submitKey);let i=rc({ttl:t,submitKey:r,adminKey:this.resolvePublicKey(e.adminKey),operatorPublicKey:this.operatorCtx.operatorKey.publicKey});i=await i.freezeWith(this.client);const n=await i.execute(this.client),o=await n.getReceipt(this.client),s=o.topicId?.toString();return s?{success:!0,topicId:s,transactionId:n.transactionId?.toString()}:{success:!1,error:"Topic creation receipt did not include a topic ID"}}catch(r){return this.logger.error("Failed to create HCS-7 registry topic",r),{success:!1,error:String(r)}}}async registerConfig(e){await this.ensureInitialized();const t=this.createConfigMessage({config:e.config,memo:e.memo});return this.submitMessage({topicId:e.registryTopicId,message:t,submitKey:e.submitKey,transactionMemo:e.transactionMemo})}async registerMetadata(e){await this.ensureInitialized();const t=this.createMetadataMessage(e);return this.submitMessage({topicId:e.registryTopicId,message:t,submitKey:e.submitKey,transactionMemo:e.transactionMemo})}async submitMessage(e){const{valid:t,errors:r}=this.validateMessage(e.message);if(!t)return{success:!1,error:`Invalid HCS-7 payload: ${r.join(", ")}`};try{let t=ic({topicId:e.topicId,message:e.message,transactionMemo:e.transactionMemo});if(e.submitKey){const r=this.coercePrivateKey(e.submitKey);t=await t.freezeWith(this.client),await t.sign(r);const i=await t.execute(this.client),n=await i.getReceipt(this.client);return{success:!0,receipt:n,sequenceNumber:n.topicSequenceNumber?.toNumber(),transactionId:i.transactionId?.toString()}}const r=await t.execute(this.client),i=await r.getReceipt(this.client);return{success:!0,receipt:i,sequenceNumber:i.topicSequenceNumber?.toNumber(),transactionId:r.transactionId?.toString()}}catch(i){return this.logger.error("Failed to submit HCS-7 message",i),{success:!1,error:String(i)}}}},exports.HCS7ConfigType=ja,exports.HCS7Operation=qa,exports.HOL_CHAT_PROTOCOL_ID=jp,exports.HRLResolver=Gp,exports.HTSParser=ta,exports.HashLinkResolver=Jg,exports.HashLinkScanner=Gg,exports.HashLinksRegistry=Hg,exports.Hcs10MemoType=ig,exports.Hcs26SkillRegistryResolver=ww,exports.HederaHieroIssuer=uf,exports.HederaMirrorNode=x,exports.HieroDidResolver=bm,exports.InboundTopicType=kh,exports.InsufficientBalanceError=class extends Hf{constructor(e,t,r,i){super(`Insufficient balance for ${t}: required ${r}, available ${i}`),this.accountId=e,this.tick=t,this.required=r,this.available=i,this.name="InsufficientBalanceError"}},exports.InvalidAccountFormatError=Jf,exports.InvalidMessageFormatError=class extends Hf{constructor(e,t){super(e),this.messageData=t,this.name="InvalidMessageFormatError"}},exports.InvalidNumberFormatError=class extends Hf{constructor(e,t){super(`Invalid number format for ${t}: ${e}`),this.value=e,this.field=t,this.name="InvalidNumberFormatError"}},exports.InvalidTickFormatError=class extends Hf{constructor(e){super(`Invalid tick format: ${e}`),this.tick=e,this.name="InvalidTickFormatError"}},exports.IssuerRegistry=of,exports.KeyType=O,exports.KeyTypeDetector=F,exports.Logger=y,exports.MAINNET_EXAMPLES=Xg,exports.MCPServerBuilder=pg,exports.MCPServerCapability=Th,exports.MCPServerConnectionInfoSchema=xh,exports.MCPServerDetailsSchema=Oh,exports.MCPServerHostSchema=zh,exports.MCPServerProfileSchema=Uh,exports.MCPServerResourceSchema=_h,exports.MCPServerToolSchema=Ph,exports.MCPServerVerificationSchema=Nh,exports.MapCache=nc,exports.MintLimitExceededError=class extends Hf{constructor(e,t,r){super(`Mint limit exceeded for ${e}: requested ${t}, limit ${r}`),this.tick=e,this.requested=t,this.limit=r,this.name="MintLimitExceededError"}},exports.NodeCryptoAdapter=ih,exports.NodeHashAdapter=Jp,exports.NodeHmacAdapter=eh,exports.PayloadSizeError=sg,exports.PersonBuilder=dg,exports.PersonalProfileSchema=Fh,exports.PointsBurnError=Wf,exports.PointsDeploymentError=qf,exports.PointsMintError=class extends Hf{constructor(e,t,r,i){super(e),this.tick=t,this.requestedAmount=r,this.availableSupply=i,this.name="PointsMintError"}},exports.PointsNotFoundError=class extends Hf{constructor(e){super(`Points with tick "${e}" not found`),this.tick=e,this.name="PointsNotFoundError"}},exports.PointsTransferError=jf,exports.PointsValidationError=Vf,exports.ProfileType=yh,exports.ProgressReporter=ts,exports.REFERENCE_THRESHOLD=51200,exports.RedisCache=class{constructor(e={}){const{host:t="localhost",port:r=6379,password:i,db:n=0,keyPrefix:o="",tls:s=!1,connectTimeout:a=5e3,retryStrategy:c,logLevel:l="info"}=e;this.prefix=o,this.logger=y.getInstance({level:l,module:"RedisCache"}),this.client=function(e,t){const r=function(){if("function"!=typeof require)return null;try{const e=require("ioredis");if("function"==typeof e)return e;if("function"==typeof e.default)return e.default}catch{return null}return null}();if(!r)return e.warn("ioredis is not installed; RedisCache will use an in-memory cache instead"),function(){const e=new Map;return{get:async t=>e.get(t)??null,set:async(t,r)=>(e.set(t,r),"OK"),setex:async(t,r,i)=>(e.set(t,i),"OK"),async del(...t){let r=0;for(const i of t)e.delete(i)&&(r+=1);return r},async keys(t){if(t.endsWith("*")){const r=t.slice(0,-1);return Array.from(e.keys()).filter(e=>e.startsWith(r))}return e.has(t)?[t]:[]},async quit(){e.clear()},on(){}}}();const i=new r({host:t.host,port:t.port,password:t.password,db:t.db,tls:t.tls,keyPrefix:t.keyPrefix,connectTimeout:t.connectTimeout,retryStrategy:t.retryStrategy,maxRetriesPerRequest:t.maxRetriesPerRequest});return i.on("error",t=>{e.error("Redis connection error:",t)}),i.on("connect",()=>{e.debug("Redis connected")}),i}(this.logger,{host:t,port:r,password:i,db:n,tls:s?{}:void 0,keyPrefix:o,connectTimeout:a,retryStrategy:c||(e=>Math.min(50*e,2e3)),maxRetriesPerRequest:3})}getKey(e){return`${this.prefix}${e}`}async get(e){try{return await this.client.get(this.getKey(e))||void 0}catch(t){throw this.logger.error("Redis get error:",t),t}}async set(e,t,r){try{const i=this.getKey(e);r?await this.client.setex(i,r,t):await this.client.set(i,t)}catch(i){throw this.logger.error("Redis set error:",i),i}}async delete(e){try{await this.client.del(this.getKey(e))}catch(t){throw this.logger.error("Redis delete error:",t),t}}async clear(){try{const e=await this.client.keys(`${this.prefix}*`);e.length>0&&await this.client.del(...e)}catch(e){throw this.logger.error("Redis clear error:",e),e}}async disconnect(){await this.client.quit()}setLogLevel(e){this.logger.setLogLevel(e)}},exports.Registration=Hh,exports.RegistryBrokerClient=qp,exports.RegistryBrokerError=hp,exports.RegistryBrokerParseError=gp,exports.RegistryType=Ig,exports.ResolverRegistry=wm,exports.ResourceManager=class{constructor(e,t,r,i={}){this.cache=new Map,this.currentCacheSize=0,this.supportedImageTypes=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/svg+xml","image/webp"]),this.dangerousJSPatterns=[/eval\s*\(/g,/Function\s*\(/g,/setTimeout\s*\(\s*["'].*["']/g,/setInterval\s*\(\s*["'].*["']/g,/document\.write/g,/innerHTML\s*=/g,/outerHTML\s*=/g],this.dangerousCSSPatterns=[/javascript\s*:/gi,/@import.*url\s*\(\s*["']?javascript:/gi,/expression\s*\(/gi,/behavior\s*:/gi],this.logger=t,this.hcs=r||new w,this.options={cacheTTL:i.cacheTTL||3e5,maxCacheSize:i.maxCacheSize||52428800,maxResourceSize:i.maxResourceSize||5242880}}async loadCSS(e){this.logger.debug("Loading CSS resource",{topicId:e});try{const t=await this.loadResource(e);if("text/css"!==t.contentType)throw new Error(`Expected CSS resource, got ${t.contentType}`);const r=t.content,i=this.sanitizeCSS(r);return this.logger.debug("CSS resource loaded successfully",{topicId:e,size:r.length,sanitized:i.length!==r.length}),i}catch(t){throw this.logger.error("Failed to load CSS resource",{topicId:e,error:t}),new Error(`Failed to load CSS resource: ${t instanceof Error?t.message:"Unknown error"}`)}}async loadJS(e){this.logger.debug("Loading JavaScript resource",{topicId:e});try{const t=await this.loadResource(e);if(!t.contentType.includes("javascript")&&!t.contentType.includes("ecmascript"))throw new Error(`Expected JavaScript resource, got ${t.contentType}`);const r=t.content;if(r.length>this.options.maxResourceSize)throw new Error("JavaScript resource too large");const i=this.sanitizeJavaScript(r);return this.logger.debug("JavaScript resource loaded successfully",{topicId:e,size:r.length,sanitized:i.length!==r.length}),i}catch(t){throw this.logger.error("Failed to load JavaScript resource",{topicId:e,error:t}),new Error(`Failed to load JavaScript resource: ${t instanceof Error?t.message:"Unknown error"}`)}}async loadImage(e){this.logger.debug("Loading image resource",{topicId:e});try{const t=await this.loadResource(e);if(!this.supportedImageTypes.has(t.contentType))throw new Error(`Unsupported image format: ${t.contentType}`);const r=t.content,i=new Uint8Array(r),n=new Blob([i.buffer],{type:t.contentType});return this.logger.debug("Image resource loaded successfully",{topicId:e,size:r.length,type:t.contentType}),n}catch(t){throw this.logger.error("Failed to load image resource",{topicId:e,error:t}),new Error(`Failed to load image resource: ${t instanceof Error?t.message:"Unknown error"}`)}}async loadTemplate(e){this.logger.debug("Loading template resource",{topicId:e});try{const t=(await this.loadResource(e)).content;this.validateTemplateSyntax(t);const r=this.sanitizeTemplate(t);return this.logger.debug("Template resource loaded successfully",{topicId:e,size:t.length}),r}catch(t){throw this.logger.error("Failed to load template resource",{topicId:e,error:t}),new Error(`Failed to load template resource: ${t instanceof Error?t.message:"Unknown error"}`)}}async loadWithIntegrityCheck(e,t){this.logger.debug("Loading resource with integrity check",{topicId:e,expectedHash:t});try{const r=await this.loadResource(e),i=await this.verifyIntegrity(r.content,t);if(!i)throw new Error("Resource integrity verification failed");return this.logger.debug("Resource integrity verified",{topicId:e}),{content:r.content,verified:i,contentType:r.contentType}}catch(r){throw this.logger.error("Resource integrity check failed",{topicId:e,error:r}),r}}async verifyIntegrity(e,t){try{if(Qp())return this.logger.warn("Integrity verification skipped in SSR environment"),!0;const r=globalThis.crypto;if(void 0===r||!r.subtle)return this.logger.warn("WebCrypto not available, skipping integrity verification"),!0;const i="string"==typeof e?(new TextEncoder).encode(e):e,n=i instanceof Uint8Array?i:new Uint8Array(i),o=new Uint8Array(n),s=await r.subtle.digest("SHA-256",o.buffer),a=Array.from(new Uint8Array(s));return a.map(e=>e.toString(16).padStart(2,"0")).join("")===t.toLowerCase()}catch(r){return this.logger.error("Error verifying integrity",{error:r}),!1}}async loadDependencies(e){this.logger.debug("Loading dependencies",{count:e.length});try{this.detectCircularDependencies(e);const t=this.topologicalSort(e),r=[];for(const e of t){let t;switch(e.type){case"css":t=await this.loadCSS(e.topicId);break;case"js":t=await this.loadJS(e.topicId);break;case"template":t=await this.loadTemplate(e.topicId);break;case"image":const r=await this.loadImage(e.topicId);t=new Uint8Array(await r.arrayBuffer());break;default:throw new Error(`Unsupported dependency type: ${e.type}`)}r.push({topicId:e.topicId,content:t,contentType:this.getContentTypeForType(e.type),type:e.type})}return this.logger.debug("Dependencies loaded successfully",{count:r.length}),r}catch(t){throw this.logger.error("Failed to load dependencies",{error:t}),t}}clearCache(){this.cache.clear(),this.currentCacheSize=0,this.logger.debug("Resource cache cleared")}getCacheSize(){return this.currentCacheSize}async loadResource(e){const t=this.getFromCache(e);if(t)return this.logger.debug("Resource loaded from cache",{topicId:e}),t;const r=await this.hcs.retrieveHCS1Data(e),i=r.type||"application/octet-stream";let n;n=i.startsWith("text/")||i.includes("javascript")||i.includes("json")?await r.text():new Uint8Array(await r.arrayBuffer());const o={content:n,contentType:i,size:r.size};return this.addToCache(e,o),o}getFromCache(e){const t=this.cache.get(e);return t?Date.now()-t.timestamp>this.options.cacheTTL?(this.removeFromCache(e),null):t.data:null}addToCache(e,t){const r="string"==typeof t.content?t.content.length:t.content.byteLength;if(r>this.options.maxCacheSize/2)return void this.logger.warn("Resource too large for cache",{topicId:e,size:r});for(;this.currentCacheSize+r>this.options.maxCacheSize&&this.cache.size>0;)this.evictOldestEntry();const i={data:t,timestamp:Date.now(),size:r};this.cache.set(e,i),this.currentCacheSize+=r,this.logger.debug("Resource added to cache",{topicId:e,size:r,totalCacheSize:this.currentCacheSize})}removeFromCache(e){const t=this.cache.get(e);t&&(this.cache.delete(e),this.currentCacheSize-=t.size)}evictOldestEntry(){let e=null,t=Date.now();for(const[r,i]of this.cache)i.timestamp<t&&(t=i.timestamp,e=r);e&&(this.removeFromCache(e),this.logger.debug("Evicted oldest cache entry",{topicId:e}))}sanitizeCSS(e){let t=e;for(const r of this.dangerousCSSPatterns)t=t.replace(r,"");return t}sanitizeJavaScript(e){let t=e;for(const r of this.dangerousJSPatterns)t=t.replace(r,"");return t}sanitizeTemplate(e){return e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/on\w+\s*=\s*["'][^"']*["']/gi,"").replace(/javascript\s*:/gi,"")}validateTemplateSyntax(e){if((e.match(/\{\{/g)||[]).length!==(e.match(/\}\}/g)||[]).length)throw new Error("Invalid template syntax: unmatched braces");if((e.match(/\{\{#\w+/g)||[]).length!==(e.match(/\{\{\/\w+/g)||[]).length)throw new Error("Invalid template syntax: unclosed block helpers")}detectCircularDependencies(e){const t=new Map;for(const o of e)t.set(o.topicId,o.depends||[]);const r=new Set,i=new Set,n=e=>{if(i.has(e))throw new Error("Circular dependency detected");if(r.has(e))return;i.add(e);const o=t.get(e)||[];for(const t of o)n(t);i.delete(e),r.add(e)};for(const o of e)n(o.topicId)}topologicalSort(e){const t=new Map,r=new Map;for(const s of e)t.set(s.topicId,s),r.set(s.topicId,s.depends||[]);const i=[],n=new Set,o=e=>{if(n.has(e))return;const s=r.get(e)||[];for(const t of s)o(t);n.add(e);const a=t.get(e);a&&i.push(a)};for(const s of e)o(s.topicId);return i}getContentTypeForType(e){switch(e){case"css":return"text/css";case"js":return"application/javascript";case"template":return"text/html";case"image":return"image/*";default:return"application/octet-stream"}}},exports.SUPPORTED_SOCIAL_PLATFORMS=vh,exports.ScheduleParser=aa,exports.SocialLinkSchema=Ch,exports.StateHashError=Fy,exports.SupplyLimitExceededError=class extends Hf{constructor(e,t,r,i){super(`Supply limit exceeded for ${e}: max ${r}, current ${i}, requested ${t}`),this.tick=e,this.requested=t,this.maxSupply=r,this.currentSupply=i,this.name="SupplyLimitExceededError"}},exports.TESTNET_EXAMPLES=Yg,exports.TemplateEngine=class{constructor(e){this.templateCache=new Map,this.helpers=new Map,this.compiledTemplates=new Map,this.logger=e,this.setupBuiltinHelpers()}async render(e,t={}){this.logger.debug("Rendering template",{templateLength:e.length,context:JSON.stringify(t,null,2),attributesType:t.attributes?typeof t.attributes:"undefined",contextKeys:Object.keys(t)});try{const r=this.getCacheKey(e);let i=this.templateCache.get(r);i||(i=await this.compileTemplate(e),this.templateCache.set(r,i));const n=i.render(this.sanitizeContext(t));return this.logger.debug("Template rendered successfully",{resultLength:n.length}),n}catch(r){throw this.logger.error("Template rendering failed",{error:r,template:e}),new Error(`Template rendering failed: ${r instanceof Error?r.message:"Unknown error"}`)}}async precompile(e,t){this.logger.debug("Precompiling template",{name:e,templateLength:t.length});try{const r=await this.compileTemplate(t);this.compiledTemplates.set(e,r),this.logger.debug("Template precompiled successfully",{name:e})}catch(r){throw this.logger.error("Template precompilation failed",{error:r,name:e}),new Error(`Template precompilation failed: ${r instanceof Error?r.message:"Unknown error"}`)}}async renderCompiled(e,t={}){const r=this.compiledTemplates.get(e);if(!r)throw new Error(`Precompiled template '${e}' not found`);this.logger.debug("Rendering precompiled template",{name:e});try{const i=r.render(this.sanitizeContext(t));return this.logger.debug("Precompiled template rendered successfully",{name:e}),i}catch(i){throw this.logger.error("Precompiled template rendering failed",{error:i,name:e}),new Error(`Template rendering failed: ${i instanceof Error?i.message:"Unknown error"}`)}}registerHelper(e,t){this.helpers.set(e,t),this.logger.debug("Helper registered",{name:e})}clearCache(){this.templateCache.clear(),this.logger.debug("Template cache cleared")}getCacheSize(){return this.templateCache.size}async compileTemplate(e){this.validateTemplate(e);return{source:e,compiled:!0,render:t=>this.executeTemplate(e,t)}}executeTemplate(e,t){let r=e;return r=this.processHelpers(r,t),r=this.processLoops(r,t),r=this.processConditionals(r,t),r=this.processVariables(r,t),r}processConditionals(e,t){let r=e;r=r.replace(/\{\{#if\s+([^}]+)\}\}((?:[^{]|\{(?!\{)|\{\{(?!#if|\{#else|\{\/if))*?)\{\{#if\s+([^}]+)\}\}((?:[^{]|\{(?!\{)|\{\{(?!#if|#else|\/if))*?)\{\{else\}\}((?:[^{]|\{(?!\{)|\{\{(?!#if|#else|\/if))*?)\{\{\/if\}\}((?:[^{]|\{(?!\{)|\{\{(?!\/if))*?)\{\{\/if\}\}/gs,(e,r,i,n,o,s,a)=>{if(!this.evaluateCondition(r,t))return"";return i+(this.evaluateCondition(n,t)?o:s)+a});r=r.replace(/\{\{#if\s+([^}]+)\}\}((?:[^{]|\{(?!\{)|\{\{(?!else|\/if))*?)\{\{else\}\}((?:[^{]|\{(?!\{)|\{\{(?!\/if))*?)\{\{\/if\}\}/gs,(e,r,i,n)=>this.evaluateCondition(r,t)?i:n);r=r.replace(/\{\{#if\s+([^}]+)\}\}((?:[^{]|\{(?!\{)|\{\{(?!\/if))*?)\{\{\/if\}\}/gs,(e,r,i)=>this.evaluateCondition(r,t)?i:"");return r=r.replace(/\{\{#unless\s+([^}]+)\}\}((?:[^{]|\{(?!\{)|\{\{(?!\/unless))*?)\{\{\/unless\}\}/gs,(e,r,i)=>this.evaluateCondition(r,t)?"":i),r}processLoops(e,t){let r=e;return r=r.replace(/\{\{#each\s+([^}]+)\}\}(.*?)\{\{\/each\}\}/gs,(e,r,i)=>{const n=this.getNestedValue(r,t);if(!n)return"";let o="";if(Array.isArray(n))n.forEach((e,r)=>{let n=i;if(n=n.replace(/\{\{this\}\}/g,this.escapeHtml(String(e))),n=n.replace(/\{\{@index\}\}/g,String(r)),"object"==typeof e&&null!==e)for(const[t,i]of Object.entries(e)){const e=new RegExp(`\\{\\{${t}\\}\\}`,"g");n=n.replace(e,this.escapeHtml(String(i)))}n=n.replace(/\{\{\.\.\/([^}]+)\}\}/g,(e,r)=>{const i=this.getNestedValue(r,t);return this.escapeHtml(String(i||""))}),o+=n});else if("object"==typeof n)for(const[t,s]of Object.entries(n)){let e=i;e=e.replace(/\{\{@key\}\}/g,this.escapeHtml(t)),e=e.replace(/\{\{this\}\}/g,this.escapeHtml(String(s))),o+=e}return o}),r}processVariables(e,t){let r=e;r=r.replace(/\{\{\{([^}]+)\}\}\}/g,(e,r)=>{const i=this.getNestedValue(r.trim(),t);return this.sanitizeHtml(String(i||""))});return r=r.replace(/\{\{([^}#/]+)\}\}/g,(e,r)=>{const i=r.trim();if(i.startsWith("#")||i.startsWith("/")||i.startsWith("else"))return e;const n=this.getNestedValue(i,t);return 0===n||!1===n?this.escapeHtml(String(n)):this.escapeHtml(String(n||""))}),r}processHelpers(e,t){let r=e;r=r.replace(/\{\{#with\s+([^}]+)\}\}(.*?)\{\{\/with\}\}/gs,(e,r,i)=>{const n=this.getNestedValue(r.trim(),t);return n?this.executeTemplate(i,n):""});for(const[i,n]of this.helpers){const e=new RegExp(`\\{\\{${i}\\s+([^}]+)\\}\\}`,"g");r=r.replace(e,(e,r)=>{try{const e=this.getNestedValue(r.trim(),t);return this.escapeHtml(n.call(t,e))}catch(o){return this.logger.warn("Helper execution failed",{helperName:i,error:o}),""}})}return r}evaluateCondition(e,t){const r=this.getNestedValue(e.trim(),t);return Boolean(r)}getNestedValue(e,t){if(!e||!t)return;const r=e.split(".");let i=t;for(const n of r){if(null==i||"object"!=typeof i)return;i=i[n]}return i}sanitizeContext(e){if(null==e)return e;const t=new WeakSet,r=e=>{if(null===e||"object"!=typeof e)return e;if(t.has(e))return"[Circular]";if(t.add(e),Array.isArray(e))return e.map(r);const i={};for(const[t,n]of Object.entries(e))i[t]=r(n);return i};return r(e)}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}sanitizeHtml(e){return e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"")}validateTemplate(e){if((e.match(/\{\{#\w+/g)||[]).length!==(e.match(/\{\{\/\w+/g)||[]).length)throw new Error("Invalid template syntax: unclosed block helpers");if(/\{\{[^}]*$|\{\{[^}]*\{\{/.test(e))throw new Error("Invalid template syntax: malformed handlebars")}getCacheKey(e){let t=0;for(let r=0;r<e.length;r++){t=(t<<5)-t+e.charCodeAt(r),t&=t}return t.toString()}setupBuiltinHelpers(){}},exports.TopicCreationError=cg,exports.TopicRegistrationError=Gf,exports.TransactionParser=ga,exports.TransactionParsingError=rs,exports.UAID_DID_RESOLUTION_PROFILE_ID=Ym,exports.UAID_DNS_WEB_PROFILE_ID=ef,exports.UaidDidResolutionProfileResolver=Qm,exports.UaidDnsWebProfileResolver=nf,exports.VerificationType=Sh,exports.WasmBridge=class{constructor(){this.wasm=null,this.WASM_VECTOR_LEN=0,this.cachedUint8Memory=null,this.cachedDataViewMemory=null,this.textEncoder=new TextEncoder,this.textDecoder=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),this.textDecoder.decode(),this.logger=y.getInstance({module:"WasmBridge"})}setLogLevel(e){this.logger.setLogLevel(e)}get wasmInstance(){if(!this.wasm)throw new Error("WASM not initialized");return this.wasm}getUint8Memory(){if(!this.wasm)throw new Error("WASM not initialized");return null!==this.cachedUint8Memory&&0!==this.cachedUint8Memory.byteLength||(this.cachedUint8Memory=new Uint8Array(this.wasm.memory.buffer)),this.cachedUint8Memory}getDataViewMemory(){if(!this.wasm)throw new Error("WASM not initialized");return null!==this.cachedDataViewMemory&&this.cachedDataViewMemory.buffer===this.wasm.memory.buffer||(this.cachedDataViewMemory=new DataView(this.wasm.memory.buffer)),this.cachedDataViewMemory}encodeString(e,t){if(0===e.length)return{read:0,written:0};const r=this.textEncoder.encode(e);return t.set(r),{read:e.length,written:r.length}}passStringToWasm(e,t,r){if(void 0===r){const r=this.textEncoder.encode(e),i=t(r.length,1);return this.getUint8Memory().set(r,i),this.WASM_VECTOR_LEN=r.length,i}let i=this.textEncoder.encode(e).length,n=t(i,1);const o=this.getUint8Memory();let s=0;for(;s<i;s++){const t=e.charCodeAt(s);if(t>127)break;o[n+s]=t}if(s!==i){0!==s&&(e=e.slice(s)),n=r(n,i,i=s+3*this.textEncoder.encode(e).length,1);const t=this.getUint8Memory().subarray(n+s,n+i);s+=this.encodeString(e,t).written}return this.WASM_VECTOR_LEN=s,n}getStringFromWasm(e,t){return e>>>=0,this.textDecoder.decode(this.getUint8Memory().subarray(e,e+t))}createWasmFunction(e){if(!this.wasm)throw new Error("WASM not initialized");return(...t)=>{const r=this.wasm.__wbindgen_add_to_stack_pointer(-16);let i=[0,0];try{const n=[r,...t.map(e=>[this.passStringToWasm(e,this.wasm.__wbindgen_malloc,this.wasm.__wbindgen_realloc),this.WASM_VECTOR_LEN]).flat()];e.apply(this.wasm,n);const o=this.getDataViewMemory().getInt32(r+0,!0),s=this.getDataViewMemory().getInt32(r+4,!0);return i=[o,s],this.getStringFromWasm(o,s)}finally{this.wasm.__wbindgen_add_to_stack_pointer(16),this.wasm.__wbindgen_free(i[0],i[1],1)}}}async initWasm(e){const t=this,r={__wbindgen_placeholder__:{__wbindgen_throw:function(e,r){const i=t.getStringFromWasm(e,r);throw t.logger.error(`WASM error: ${i}`),new Error(i)}}};try{this.logger.debug("Compiling WASM module");const t=await WebAssembly.compile(e);this.logger.debug("Instantiating WASM module");const i=await WebAssembly.instantiate(t,r);return this.wasm=i.exports,this.logger.info("WASM module initialized successfully"),this.wasm}catch(i){throw this.logger.error("Failed to initialize WASM module",i),i}}createStateData(e,t={}){let r={};return e?.c?.inputType?.stateData&&(t.latestRoundData&&Object.keys(e.c.inputType.stateData).every(e=>e in t.latestRoundData)?(r.latestRoundData={},Object.entries(e.c.inputType.stateData).forEach(([e,i])=>{r.latestRoundData[e]=String(t.latestRoundData[e])})):Object.entries(e.c.inputType.stateData).forEach(([e,i])=>{const n=t[e];n&&"object"==typeof n&&"values"in n&&n.values.length>0?r[e]=String(n.values[0]):r[e]=this.getDefaultValueForType(i)})),r}getDefaultValueForType(e){return e.startsWith("uint")||e.startsWith("int")||"number"===e?"0":"bool"===e?"false":""}executeWasm(e,t){if(!this.wasm)throw this.logger.error("WASM not initialized"),new Error("WASM not initialized");try{this.logger.debug("Executing WASM with stateData",e);return this.createWasmFunction(this.wasmInstance.process_state)(JSON.stringify(e),JSON.stringify(t))}catch(r){throw this.logger.error("Error executing WASM",r),r}}getParams(){return this.createWasmFunction(this.wasmInstance.get_params)()}},exports.WasmExecutor=Vg,exports.WasmValidator=class{constructor(e){this.cryptoAdapter=sh(),this.REQUIRED_EXPORTS=["INFO","POST","GET"],this.ALLOWED_IMPORTS=new Set(["env.console_log","env.get_network","env.submit_hcs_message","env.memory"]),this.MAX_INITIAL_MEMORY=256,this.WARN_MODULE_SIZE=1048576,this.MAX_MODULE_SIZE=5242880,this.logger=e}async validate(e){const t=[],r=[],i={isValid:!0,errors:t,warnings:r};try{if(e.length>this.WARN_MODULE_SIZE&&r.push(`Large module size: ${(e.length/1024/1024).toFixed(2)} MB`),e.length>this.MAX_MODULE_SIZE&&(t.push("Module size exceeds maximum allowed"),i.isValid=!1),!this.validateMagicNumber(e))return t.push("Invalid WASM magic number"),i.isValid=!1,i;const n=this.getWasmVersion(e);if(i.version=n,1!==n)return t.push(`Unsupported WASM version: ${n}`),i.isValid=!1,i;const o=await this.parseModule(e);i.exports=o.exports;for(const e of this.REQUIRED_EXPORTS)o.exports.includes(e)||(t.push(`Missing required export: ${e}`),i.isValid=!1);i.imports=o.imports;for(const e of o.imports){const r=`${e.module}.${e.name}`;this.ALLOWED_IMPORTS.has(r)||(t.push(`Disallowed import: ${r}`),i.isValid=!1)}o.memory&&(i.memoryRequirements=o.memory,o.memory.initial>this.MAX_INITIAL_MEMORY&&(t.push(`Excessive initial memory: ${o.memory.initial} pages`),i.isValid=!1)),o.hasStartFunction&&r.push("Module has start function - may execute code on load"),o.functionCount>100&&r.push(`High function count: ${o.functionCount}`),this.hasSuspiciousPatterns(e)&&r.push("Potentially unsafe operation detected"),i.exportSignatures=o.exportSignatures}catch(n){this.logger.error("WASM validation failed",{error:n}),t.push(`Validation error: ${n instanceof Error?n.message:"Unknown error"}`),i.isValid=!1}return i}async validateInfoFunction(e){const t=[],r=[];try{const i=await e(),n=JSON.parse(i);return n.name&&n.version&&n.hashlinks_version?{isValid:!0,errors:t,warnings:r,moduleInfo:n}:(t.push("INFO missing required fields"),{isValid:!1,errors:t,warnings:r})}catch(i){return t.push("INFO function returned invalid JSON"),{isValid:!1,errors:t,warnings:r}}}async validateActionSchemas(e){const t=[];if(e.validation_rules)for(const[r,i]of Object.entries(e.validation_rules))"object"!=typeof i&&t.push(`Invalid validation rule for action: ${r}`);return{isValid:0===t.length,errors:t,warnings:[]}}async extractMetadata(e){return{size:e.length,hash:await this.calculateHash(e),producers:{language:["Unknown"]}}}async calculateHash(e){if(Qp())return this.createSSRSafeHash(e);const t=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(e)).digest("hex"),r=t instanceof Promise?await t:t;return"string"==typeof r?r:r.toString("hex")}createSSRSafeHash(e){let t=0;for(let r=0;r<Math.min(e.length,1024);r++)t=(t<<5)-t+e[r]&4294967295;return`ssr-wasm-${e.length}-${Math.abs(t).toString(16).padStart(8,"0")}`}validateMagicNumber(e){return e.length>=4&&0===e[0]&&97===e[1]&&115===e[2]&&109===e[3]}getWasmVersion(e){return e.length<8?0:e[4]|e[5]<<8|e[6]<<16|e[7]<<24}async parseModule(e){const t=e.slice(8),r=new TextDecoder("utf-8",{fatal:!1}).decode(t),i=[];r.includes("INFO")&&i.push("INFO"),r.includes("POST")&&i.push("POST"),r.includes("GET")&&i.push("GET"),0===i.length&&e.length>8&&i.push("INFO","POST","GET");const n=[],o=r.split("import:");for(let d=1;d<o.length;d++){const e=o[d].match(/^([a-zA-Z_]+[a-zA-Z0-9_]*)\.([a-zA-Z_]+[a-zA-Z0-9_]*)/);e&&n.push({module:e[1],name:e[2],type:"function"})}let s=1,a=16;const c=r.match(/memory:(\d+)(?:-(\d+))?/);c&&(s=parseInt(c[1]),c[2]&&(a=parseInt(c[2])));let l=10;const u=r.match(/functions:(\d+)/);u&&(l=parseInt(u[1]));return{exports:i,imports:n,memory:{initial:s,maximum:a},functionCount:l,hasStartFunction:r.includes("start:true"),exportSignatures:{INFO:{type:"function",params:[],results:["i32"]},POST:{type:"function",params:["i32","i32","i32","i32"],results:["i32"]},GET:{type:"function",params:["i32","i32","i32"],results:["i32"]}}}}hasSuspiciousPatterns(e){const t=new TextDecoder("utf-8",{fatal:!1}).decode(e);return["eval","__proto__","constructor"].some(e=>t.includes(e))}},exports.WebCryptoAdapter=nh,exports.WebHashAdapter=Yp,exports.WebHmacAdapter=th,exports.accountIdsToExemptKeys=cc,exports.actionRegistrationSchema=Rg,exports.adapterConfigContextSchema=fc,exports.adapterDeclarationSchema=yc,exports.adapterManifestSchema=bc,exports.adapterPackageSchema=mc,exports.assemblyMessageSchema=Og,exports.assemblyRegistrationSchema=Dg,exports.baseMessageSchema=wf,exports.blockRegistrationSchema=xg,exports.buildHCS27TopicMemo=wb,exports.buildHCS27TransactionMemo=Tb,exports.buildHcs10ConfirmConnectionTx=Yh,exports.buildHcs10CreateConnectionTopicTx=Vh,exports.buildHcs10CreateInboundTopicTx=jh,exports.buildHcs10CreateOutboundTopicTx=Wh,exports.buildHcs10CreateRegistryTopicTx=Gh,exports.buildHcs10OutboundConnectionCreatedRecordTx=Zh,exports.buildHcs10OutboundConnectionRequestRecordTx=Xh,exports.buildHcs10RegistryDeleteTx=tg,exports.buildHcs10RegistryMigrateTx=rg,exports.buildHcs10RegistryRegisterTx=eg,exports.buildHcs10SendMessageTx=Qh,exports.buildHcs10SubmitConnectionRequestTx=Jh,exports.buildHcs12AddActionToAssemblyTx=function(e){return _({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs12AddBlockToAssemblyTx=function(e){return _({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs12CreateRegistryTopicTx=function(e){var t;return z({memo:e.memoOverride??(t=e.registry,`hcs-12:1:${e.ttl}:${{action:0,assembly:2,hashlinks:3}[t]}`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})},exports.buildHcs12RegisterAssemblyTx=function(e){return _({topicId:e.assemblyTopicId,message:JSON.stringify(e.registration)})},exports.buildHcs12SubmitMessageTx=function(e){const t="string"==typeof e.payload?e.payload:JSON.stringify(e.payload);return _({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs12UpdateAssemblyTx=function(e){return _({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs15BaseAccountCreateTx=py,exports.buildHcs15PetalAccountCreateTx=hy,exports.buildHcs16CreateAccountTx=Ay,exports.buildHcs16CreateFloraTopicTx=Ey,exports.buildHcs16CreateTransactionTopicTx=function(e){const t=(new r.TopicCreateTransaction).setTopicMemo(e.memo);if(e.adminKey&&t.setAdminKey(e.adminKey),e.submitKey&&t.setSubmitKey(e.submitKey),e.feeScheduleKey&&t.setFeeScheduleKey(e.feeScheduleKey),e.customFees&&e.customFees.length>0){const i=e.customFees.map(e=>{const t=(new r.CustomFixedFee).setAmount(e.amount).setFeeCollectorAccountId(r.AccountId.fromString(e.feeCollectorAccountId));return e.denominatingTokenId&&t.setDenominatingTokenId(r.TokenId.fromString(e.denominatingTokenId)),t});t.setCustomFees(i)}if(e.feeExemptKeys&&e.feeExemptKeys.length>0)throw new Error("feeExemptKeys not supported by installed @hashgraph/sdk");return t},exports.buildHcs16FloraCreatedTx=Ry,exports.buildHcs16FloraJoinAcceptedTx=Py,exports.buildHcs16FloraJoinRequestTx=zy,exports.buildHcs16FloraJoinVoteTx=_y,exports.buildHcs16MessageTx=Cy,exports.buildHcs16ScheduleAccountKeyUpdateTx=function(e){const t=(new r.AccountUpdateTransaction).setAccountId(r.AccountId.fromString(e.floraAccountId)).setKey(e.newKeyList);return t.setTransactionMemo(Sy(e.transactionMemo??e.memo,Iy)),(new r.ScheduleCreateTransaction).setScheduledTransaction(t)},exports.buildHcs16ScheduleTopicKeyUpdateTx=function(e){const t=(new r.TopicUpdateTransaction).setTopicId(e.topicId);return e.adminKey&&t.setAdminKey(e.adminKey),e.submitKey&&t.setSubmitKey(e.submitKey),t.setTransactionMemo(Sy(e.transactionMemo??e.memo,Ty)),(new r.ScheduleCreateTransaction).setScheduledTransaction(t)},exports.buildHcs16StateUpdateTx=Ny,exports.buildHcs16TransactionTx=xy,exports.buildHcs17CreateTopicTx=Ky,exports.buildHcs17MessageTx=$y,exports.buildHcs18AnnounceMessage=Qy,exports.buildHcs18CompleteMessage=rb,exports.buildHcs18CreateDiscoveryTopicTx=Xy,exports.buildHcs18DiscoveryMemo=Yy,exports.buildHcs18ProposeMessage=eb,exports.buildHcs18RespondMessage=tb,exports.buildHcs18SubmitDiscoveryMessageTx=Zy,exports.buildHcs18WithdrawMessage=ib,exports.buildHcs1Hrl=hf,exports.buildHcs20BurnTx=ey,exports.buildHcs20DeployTx=Xf,exports.buildHcs20MintTx=Zf,exports.buildHcs20RegisterTx=ty,exports.buildHcs20SubmitMessageTx=function(e){const t="string"==typeof e.payload?e.payload:JSON.stringify(e.payload);return _({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs20TransferTx=Qf,exports.buildHcs21CreateRegistryTx=ny,exports.buildHcs21MessageTx=oy,exports.buildHcs21RegistryMemo=iy,exports.buildHcs26TopicMemo=function(e){const t=e.indexed??!0,r=function(e){if(!Number.isFinite(e))throw new Error("Expected a finite number");const t=Math.floor(e);if(t<=0)throw new Error("Expected a positive integer");return t}(e.ttlSeconds??86400),i=Bb.parse(e.topicType);return`${Ub}:${t?"0":"1"}:${r}:${i}`},exports.buildHcs26TransactionMemo=function(e){const t=Lb.parse(e.operation),r=Bb.parse(e.topicType);return`${Ub}:op:${t}:${r}`},exports.buildHcs2CreateRegistryTx=Af,exports.buildHcs2DeleteTx=function(e){const t={p:"hcs-2",op:ff.DELETE,uid:e.uid,m:e.memo};return _({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs2MigrateTx=function(e){const t={p:"hcs-2",op:ff.MIGRATE,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return _({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs2RegisterTx=Cf,exports.buildHcs2UpdateTx=function(e){const t={p:"hcs-2",op:ff.UPDATE,uid:e.uid,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return _({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs5MintTx=mf,exports.buildHcs5MintWithHrlTx=function(e){const t=hf(e.metadataTopicId);return mf({tokenId:e.tokenId,metadata:t,transactionMemo:e.transactionMemo})},exports.buildHcs6CreateRegistryTx=P,exports.buildHcs6Hrl=S,exports.buildHcs6RegisterEntryTx=function(e){const t={p:"hcs-6",op:I.REGISTER,t_id:e.targetTopicId,m:e.memo};return _({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs7CreateRegistryTx=rc,exports.buildHcs7EvmMessageTx=function(e){const t={p:"hcs-7",op:qa.REGISTER_CONFIG,t:ja.EVM,c:{contractAddress:e.config.contractAddress,abi:e.config.abi},m:e.config.memo??""};return ic({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs7SubmitMessageTx=ic,exports.buildHcs7WasmMessageTx=function(e){const t={p:"hcs-7",op:qa.REGISTER_CONFIG,t:ja.WASM,c:{wasmTopicId:e.config.wasmTopicId,inputType:e.config.inputType,outputType:e.config.outputType},m:e.config.memo??""};return ic({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildJobStatusMessage=e=>JSON.stringify({p:jp,op:"job_status",request_id:e.requestId,data:{job_id:e.jobId}}),exports.buildPaymentApproveMessage=e=>JSON.stringify({p:jp,op:"payment_approve",request_id:e.requestId,data:{job_id:e.jobId}}),exports.buildPaymentDeclineMessage=e=>JSON.stringify({p:jp,op:"payment_decline",request_id:e.requestId}),exports.canonicalize=cy,exports.canonicalizeAgentData=rm,exports.canonicalizeHCS27Json=Cb,exports.canonicalizeLedgerNetwork=Pp,exports.capabilityNameToCapabilityMap=Eh,exports.closeUaidConnection=Ap,exports.createLoggerAdapter=sc,exports.createPrivateKeySigner=e=>Fp((()=>{if(Dp)return Dp;const e=Sa("@hashgraph/sdk");if(e)return Dp=e,e;throw new Error("@hashgraph/sdk is required for ledger signing. Install it as a dependency to enable createPrivateKeySigner.")})(),e),exports.createPrivateKeySignerAsync=Mp,exports.createRegistryBrokerVerificationProvider=Aw,exports.createUaid=cm,exports.dashboardStats=Cp,exports.defaultIssuerRegistry=sf,exports.defaultResolverRegistry=Im,exports.deleteMessageSchema=Sf,exports.detectCryptoEnvironment=Zp,exports.detectKeyTypeFromString=M,exports.emptyHCS27Root=Rb,exports.ensureLoggerType=function(e){return ac(e)?e:sc(e)},exports.extractReferenceId=function(e){const t=e.trim(),r=t.match(/^content-ref:([a-f0-9]+)$/);if(r)return r[1];const i=t.match(/content-ref:([a-f0-9]+)/);return i?i[1]:null},exports.generateHCS17Memo=Uy,exports.generateHCS6RegistryMemo=R,exports.generateQuote=Ba,exports.getCryptoAdapter=sh,exports.getExampleTopics=function(e){return"mainnet"===e?Xg:Yg},exports.getHumanReadableTransactionType=ha,exports.getOrCreateSDK=Ea,exports.getParserConfig=function(e){return ca[e]},exports.getRegistrationProgress=Sp,exports.getRegistrationQuote=Ip,exports.getRegistryBrokerQuote=async function(e,t={}){const r=y.getInstance({module:"InscribeViaBroker",...t.logging}),i=t.baseUrl??Ka,n={"Content-Type":"application/json",Accept:"application/json"};if(t.ledgerApiKey)n["x-api-key"]=t.ledgerApiKey;else{if(!t.apiKey)throw new Error("Either ledgerApiKey or apiKey is required for Registry Broker quotes");n["x-api-key"]=t.apiKey}let o,s,a;switch(e.type){case"url":break;case"file":{const t=await za(e.path);o=t.base64,s=t.fileName,a=t.mimeType;break}case"buffer":o=globalThis.Buffer.from(e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer):e.buffer).toString("base64"),s=e.fileName,a=e.mimeType}const c={inputType:"url"===e.type?"url":"base64",mode:t.mode??"file"};return"url"===e.type?c.url=e.url:(c.base64=o,c.fileName=s,a&&(c.mimeType=a)),t.metadata&&(c.metadata=t.metadata),t.tags&&(c.tags=t.tags),t.fileStandard&&(c.fileStandard=t.fileStandard),t.chunkSize&&(c.chunkSize=t.chunkSize),r.debug("Getting inscription quote from Registry Broker"),$a(`${i}/inscribe/content/quote`,{method:"POST",headers:n,body:JSON.stringify(c)})},exports.getSchedulableTransactionType=function(e){for(const[t,r]of Object.entries(da))if(e[t])return r;return"unknown"},exports.getSupportedTransactionTypes=function(){return Object.keys(ca)},exports.getTopicId=Ha,exports.getTransactionTypeFromBody=pa,exports.getUaidConnectionStatus=Ep,exports.hash=ah,exports.hashHCS27Leaf=xb,exports.hashHCS27Node=Nb,exports.hashLinksRegistrationSchema=Fg,exports.hcs17MessageSchema=Dy,exports.hcs26DiscoveryDeleteSchema=Qb,exports.hcs26DiscoveryMessageSchema=lw,exports.hcs26DiscoveryMetadataPatchSchema=Gb,exports.hcs26DiscoveryMetadataSchema=Vb,exports.hcs26DiscoveryMigrateSchema=ew,exports.hcs26DiscoveryRegisterLegacySchema=Yb,exports.hcs26DiscoveryRegisterSchema=Jb,exports.hcs26DiscoveryUpdateLegacySchema=Zb,exports.hcs26DiscoveryUpdateSchema=Xb,exports.hcs26ManifestFileSchema=aw,exports.hcs26OperationEnumSchema=Lb,exports.hcs26SkillManifestSchema=cw,exports.hcs26TopicMemoSchema=Sw,exports.hcs26TopicTypeEnumSchema=Bb,exports.hcs26TransactionMemoSchema=kw,exports.hcs26VersionDeleteSchema=ow,exports.hcs26VersionMessageSchema=uw,exports.hcs26VersionMigrateSchema=sw,exports.hcs26VersionRegisterLegacySchema=iw,exports.hcs26VersionRegisterSchema=rw,exports.hcs26VersionUpdateSchema=nw,exports.hcs27CheckpointMessageSchema=gb,exports.hcs27CheckpointMetadataSchema=pb,exports.hcs27ConsistencyProofSchema=fb,exports.hcs27InclusionProofSchema=mb,exports.hcs27MetadataDigestSchema=hb,exports.hcs27PreviousCommitmentSchema=lb,exports.hcs27RootCommitmentSchema=cb,exports.hcs27SignatureSchema=ub,exports.hcs2MessageSchema=vf,exports.hcs6BaseMessageSchema=v,exports.hcs6MessageSchema=A,exports.hcs6RegisterMessageSchema=E,exports.hcs6TopicIdSchema=k,exports.hcs7MessageSchema=Qa,exports.humanReadableTypeRegistry=ua,exports.inscribe=Oa,exports.inscribeViaRegistryBroker=async function(e,t={}){const r=y.getInstance({module:"InscribeViaBroker",...t.logging}),i=t.baseUrl??Ka,n=t.waitForConfirmation??!0,o=t.waitTimeoutMs??12e4,s=t.pollIntervalMs??2e3,a={"Content-Type":"application/json",Accept:"application/json"};if(t.ledgerApiKey)a["x-api-key"]=t.ledgerApiKey;else{if(!t.apiKey)throw new Error("Either ledgerApiKey or apiKey is required for Registry Broker inscription");a["x-api-key"]=t.apiKey}let c,l,u;switch(r.info("Starting inscription via Registry Broker",{baseUrl:i,inputType:e.type,mode:t.mode??"file"}),e.type){case"url":r.debug("Creating job with URL input");break;case"file":{const t=await za(e.path);c=t.base64,l=t.fileName,u=t.mimeType;break}case"buffer":c=globalThis.Buffer.from(e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer):e.buffer).toString("base64"),l=e.fileName,u=e.mimeType}const d={inputType:"url"===e.type?"url":"base64",mode:t.mode??"file"};"url"===e.type?d.url=e.url:(d.base64=c,d.fileName=l,u&&(d.mimeType=u)),t.metadata&&(d.metadata=t.metadata),t.tags&&(d.tags=t.tags),t.fileStandard&&(d.fileStandard=t.fileStandard),t.chunkSize&&(d.chunkSize=t.chunkSize),r.debug("Creating inscription job");const p=await $a(`${i}/inscribe/content`,{method:"POST",headers:a,body:JSON.stringify(d)}),h=p.jobId??p.id??"";if(r.info("Inscription job created",{jobId:h,status:p.status}),!n)return{confirmed:!1,jobId:h,status:p.status,credits:p.credits??p.quoteCredits,usdCents:p.usdCents??p.quoteUsdCents,sizeBytes:p.sizeBytes,createdAt:p.createdAt,updatedAt:p.updatedAt,network:p.network};r.debug("Polling for job completion",{jobId:h,waitTimeoutMs:o});const g=Date.now();let m="";for(;Date.now()-g<o;){const e=await $a(`${i}/inscribe/content/${h}`,{method:"GET",headers:a});if(e.status!==m&&(r.debug("Job status update",{jobId:h,status:e.status}),m=e.status),"completed"===e.status)return r.info("Inscription completed",{jobId:h,hrl:e.hrl,topicId:e.topicId}),{confirmed:!0,jobId:h,status:e.status,hrl:e.hrl,topicId:e.topicId,network:e.network,credits:e.credits??e.quoteCredits,usdCents:e.usdCents??e.quoteUsdCents,sizeBytes:e.sizeBytes,createdAt:e.createdAt,updatedAt:e.updatedAt};if("failed"===e.status)return r.error("Inscription failed",{jobId:h,error:e.error}),{confirmed:!1,jobId:h,status:e.status,error:e.error??"Inscription failed",credits:e.credits??e.quoteCredits,createdAt:e.createdAt,updatedAt:e.updatedAt};await b(s)}throw new Error(`Inscription job ${h} did not complete within ${o}ms`)},exports.inscribeWithSigner=Fa,exports.isAnnounceMessage=function(e){if(!Vy(e))return!1;const t=e;if("announce"!==t.op)return!1;if(!qy(t.data))return!1;const r=t.data;if(!jy(r.account))return!1;if(!qy(r.petal))return!1;const i=r.petal;return!(!jy(i.name)||!Wy(i.priority))&&(!!qy(r.capabilities)&&(!!function(e){return Array.isArray(e)&&e.every(jy)}(r.capabilities.protocols)&&!("valid_for"in r&&void 0!==r.valid_for&&null!==r.valid_for&&!Wy(r.valid_for))))},exports.isBrowser=ma,exports.isCompleteMessage=function(e){if(!Vy(e))return!1;const t=e;if("complete"!==t.op)return!1;if(!qy(t.data))return!1;const r=t.data;if(!jy(r.proposer))return!1;if(!Wy(r.proposal_seq))return!1;if(!jy(r.flora_account))return!1;if(!qy(r.topics))return!1;const i=r.topics;return!!(jy(i.communication)&&jy(i.transaction)&&jy(i.state))},exports.isConcreteLogger=ac,exports.isCryptoAvailable=function(){return"none"!==Zp().preferredAPI},exports.isDidProfileResolverAdapter=gm,exports.isDidResolverAdapter=mm,exports.isDiscoveryMessage=Vy,exports.isEip155Caip10=mh,exports.isHederaCaip10=dh,exports.isHederaNetwork=lh,exports.isHolChatOp=Vp,exports.isPartialRegisterAgentResponse=e=>"partial"===e.status&&!1===e.success,exports.isPendingRegisterAgentResponse=e=>"pending"===e.status,exports.isProposeMessage=function(e){if(!Vy(e))return!1;const t=e;if("propose"!==t.op)return!1;if(!qy(t.data))return!1;const r=t.data;if(!jy(r.proposer))return!1;if(!function(e){return Array.isArray(e)}(r.members))return!1;if(!r.members.every(e=>{if(!qy(e))return!1;const t=e;return!!jy(t.account)&&(!(!("priority"in t)||!Wy(t.priority))&&!("announce_seq"in t&&void 0!==t.announce_seq&&null!==t.announce_seq&&!Wy(t.announce_seq)))}))return!1;if(!qy(r.config))return!1;const i=r.config;return!(!jy(i.name)||!Wy(i.threshold))},exports.isRespondMessage=function(e){if(!Vy(e))return!1;const t=e;if("respond"!==t.op)return!1;if(!qy(t.data))return!1;const r=t.data;return!!jy(r.responder)&&(!!Wy(r.proposal_seq)&&(!!jy(r.decision)&&!!["accept","reject"].includes(r.decision)))},exports.isSSREnvironment=Qp,exports.isSuccessRegisterAgentResponse=e=>!0===e.success&&"pending"!==e.status,exports.isTransactionTypeSupported=function(e){return e in ca},exports.isUaidProfileResolverAdapter=hm,exports.isWithdrawMessage=function(e){if(!Vy(e))return!1;const t=e;if("withdraw"!==t.op)return!1;if(!qy(t.data))return!1;const r=t.data;return!!jy(r.account)&&(!!Wy(r.announce_seq)&&!("reason"in r&&void 0!==r.reason&&null!==r.reason&&!jy(r.reason)))},exports.leafHashHexFromEntry=Pb,exports.mcpServiceNameToCapabilityMap=Ah,exports.merkleRootFromCanonicalEntries=zb,exports.merkleRootFromEntries=_b,exports.metadataDocumentSchema=Ic,exports.migrateMessageSchema=kf,exports.nodeDnsTxtLookup=Am,exports.normalizeTransactionId=xa,exports.parseHCS17Memo=By,exports.parseHCS27TopicMemo=Ib,exports.parseHcs14Did=lm,exports.parseHcs26TopicMemo=Iw,exports.parseHcs26TransactionMemo=Tw,exports.parseHederaCaip10=hh,exports.parseHolChatOps=e=>Array.isArray(e)?e.filter(Vp).map(e=>{const t={p:jp,op:e.op,request_id:e.request_id.trim()};return"string"==typeof e.m&&e.m.trim().length>0&&(t.m=e.m.trim()),Wp(e.data)&&(t.data={...e.data}),t}):[],exports.protoFieldToTypeRegistry=la,exports.registerAgent=async function(e,t,r){const i=r?.autoTopUp??e.registrationAutoTopUp;if(!i)return mp(e,t);await bp(e,t,i);let n=!1;for(;;)try{return await mp(e,t)}catch(o){if(e.extractInsufficientCreditsDetails(o)&&!n){await bp(e,t,i),n=!0;continue}throw o}},exports.registerDefaultResolvers=Tm,exports.registerMessageSchema=If,exports.registryMetadataSchema=wc,exports.resolveTransactionSummary=Xs,exports.resolveUaid=wp,exports.retrieveInscription=Ma,exports.safeValidate=function(e,t){const r=e.safeParse(t);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error}},exports.schedulableTransactionTypeRegistry=da,exports.setLoggerFactory=function(e){m=e,y.clearInstances()},exports.shouldUseReference=function(e){return("string"==typeof e?globalThis.Buffer.byteLength(e,"utf8"):e.length)>51200},exports.sleep=b,exports.toEip155Caip10=fh,exports.toHCS27CheckpointMessage=bb,exports.toHCS27CheckpointMetadata=yb,exports.toHederaCaip10=ph,exports.topicIdSchema=bf,exports.transactionParserRegistry=ca,exports.transactionSummaryRegistry=Ys,exports.updateAgent=Tp,exports.updateMessageSchema=Tf,exports.validateActionRegistration=Mg,exports.validateAssemblyMessage=Ug,exports.validateAssemblyRegistration=function(e){return Dg.parse(e)},exports.validateBlockRegistration=function(e){return xg.parse(e)},exports.validateHCS6RegistryMemo=function(e){const t=e.match(/^hcs-6:(\d):(\d+)$/);if(!t)return!1;const r=parseInt(t[1]),i=parseInt(t[2]);return 1===r&&C(i)},exports.validateHCS6TTL=C,exports.validateHashLinksRegistration=function(e){return Fg.parse(e)},exports.validateUaid=vp,exports.validateWithSchema=Bg,exports.verifyArtifactDigest=function(e,t){const r=d.createHash("sha384");r.update(e);const i=r.digest("hex").toLowerCase(),n=globalThis.Buffer.from(i,"hex").toString("base64").toLowerCase(),o=t.replace(/^sha384[-:]?/i,"").trim().toLowerCase();return o===i||o===n},exports.verifyConsistencyProof=Db,exports.verifyDeclarationSignature=function(e,t){if(!e.signature)return!1;try{const{signature:i,...n}=e,o=cy(n),s=globalThis.Buffer.from(i,"base64");return r.PublicKey.fromString(t).verify(globalThis.Buffer.from(o,"utf8"),s)}catch{return!1}},exports.verifyInclusionProof=Ob,exports.verifyManifestSignature=function(e,t,i){try{const n=cy(e),o=globalThis.Buffer.from(t,"base64");return r.PublicKey.fromString(i).verify(globalThis.Buffer.from(n,"utf8"),o)}catch{return!1}},exports.waitForInscriptionConfirmation=La,exports.waitForRegistrationCompletion=kp;
|
|
10
|
+
!function(e){const t=H,r=Z,i="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=l,e.SlowBuffer=function(e){+e!=e&&(e=0);return l.alloc(+e)},e.INSPECT_MAX_BYTES=50;const n=2147483647;e.kMaxLength=n;const{Uint8Array:o,ArrayBuffer:s,SharedArrayBuffer:a}=globalThis;function c(e){if(e>n)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new o(e);return Object.setPrototypeOf(t,l.prototype),t}function l(e,t,r){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return p(e)}return u(e,t,r)}function u(e,t,r){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!l.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const r=0|f(e,t);let i=c(r);const n=i.write(e,t);n!==r&&(i=i.slice(0,n));return i}(e,t);if(s.isView(e))return function(e){if(X(e,o)){const t=new o(e);return g(t.buffer,t.byteOffset,t.byteLength)}return h(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(X(e,s)||e&&X(e.buffer,s))return g(e,t,r);if(void 0!==a&&(X(e,a)||e&&X(e.buffer,a)))return g(e,t,r);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const i=e.valueOf&&e.valueOf();if(null!=i&&i!==e)return l.from(i,t,r);const n=function(e){if(l.isBuffer(e)){const t=0|m(e.length),r=c(t);return 0===r.length||e.copy(r,0,0,t),r}if(void 0!==e.length)return"number"!=typeof e.length||Q(e.length)?c(0):h(e);if("Buffer"===e.type&&Array.isArray(e.data))return h(e.data)}(e);if(n)return n;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return l.from(e[Symbol.toPrimitive]("string"),t,r);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function d(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function p(e){return d(e),c(e<0?0:0|m(e))}function h(e){const t=e.length<0?0:0|m(e.length),r=c(t);for(let i=0;i<t;i+=1)r[i]=255&e[i];return r}function g(e,t,r){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(r||0))throw new RangeError('"length" is outside of buffer bounds');let i;return i=void 0===t&&void 0===r?new o(e):void 0===r?new o(e,t):new o(e,t,r),Object.setPrototypeOf(i,l.prototype),i}function m(e){if(e>=n)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+n.toString(16)+" bytes");return 0|e}function f(e,t){if(l.isBuffer(e))return e.length;if(s.isView(e)||X(e,s))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const r=e.length,i=arguments.length>2&&!0===arguments[2];if(!i&&0===r)return 0;let n=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return G(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return J(e).length;default:if(n)return i?-1:G(e).length;t=(""+t).toLowerCase(),n=!0}}function y(e,t,r){let i=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===r||r>this.length)&&(r=this.length),r<=0)return"";if((r>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return z(this,t,r);case"utf8":case"utf-8":return C(this,t,r);case"ascii":return x(this,t,r);case"latin1":case"binary":return N(this,t,r);case"base64":return A(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return _(this,t,r);default:if(i)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),i=!0}}function b(e,t,r){const i=e[t];e[t]=e[r],e[r]=i}function w(e,t,r,i,n){if(0===e.length)return-1;if("string"==typeof r?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),Q(r=+r)&&(r=n?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(n)return-1;r=e.length-1}else if(r<0){if(!n)return-1;r=0}if("string"==typeof t&&(t=l.from(t,i)),l.isBuffer(t))return 0===t.length?-1:I(e,t,r,i,n);if("number"==typeof t)return t&=255,"function"==typeof o.prototype.indexOf?n?o.prototype.indexOf.call(e,t,r):o.prototype.lastIndexOf.call(e,t,r):I(e,[t],r,i,n);throw new TypeError("val must be string, number or Buffer")}function I(e,t,r,i,n){let o,s=1,a=e.length,c=t.length;if(void 0!==i&&("ucs2"===(i=String(i).toLowerCase())||"ucs-2"===i||"utf16le"===i||"utf-16le"===i)){if(e.length<2||t.length<2)return-1;s=2,a/=2,c/=2,r/=2}function l(e,t){return 1===s?e[t]:e.readUInt16BE(t*s)}if(n){let i=-1;for(o=r;o<a;o++)if(l(e,o)===l(t,-1===i?0:o-i)){if(-1===i&&(i=o),o-i+1===c)return i*s}else-1!==i&&(o-=o-i),i=-1}else for(r+c>a&&(r=a-c),o=r;o>=0;o--){let r=!0;for(let i=0;i<c;i++)if(l(e,o+i)!==l(t,i)){r=!1;break}if(r)return o}return-1}function T(e,t,r,i){r=Number(r)||0;const n=e.length-r;i?(i=Number(i))>n&&(i=n):i=n;const o=t.length;let s;for(i>o/2&&(i=o/2),s=0;s<i;++s){const i=parseInt(t.substr(2*s,2),16);if(Q(i))return s;e[r+s]=i}return s}function S(e,t,r,i){return Y(G(t,e.length-r),e,r,i)}function k(e,t,r,i){return Y(function(e){const t=[];for(let r=0;r<e.length;++r)t.push(255&e.charCodeAt(r));return t}(t),e,r,i)}function v(e,t,r,i){return Y(J(t),e,r,i)}function E(e,t,r,i){return Y(function(e,t){let r,i,n;const o=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)r=e.charCodeAt(s),i=r>>8,n=r%256,o.push(n),o.push(i);return o}(t,e.length-r),e,r,i)}function A(e,r,i){return 0===r&&i===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(r,i))}function C(e,t,r){r=Math.min(e.length,r);const i=[];let n=t;for(;n<r;){const t=e[n];let o=null,s=t>239?4:t>223?3:t>191?2:1;if(n+s<=r){let r,i,a,c;switch(s){case 1:t<128&&(o=t);break;case 2:r=e[n+1],128==(192&r)&&(c=(31&t)<<6|63&r,c>127&&(o=c));break;case 3:r=e[n+1],i=e[n+2],128==(192&r)&&128==(192&i)&&(c=(15&t)<<12|(63&r)<<6|63&i,c>2047&&(c<55296||c>57343)&&(o=c));break;case 4:r=e[n+1],i=e[n+2],a=e[n+3],128==(192&r)&&128==(192&i)&&128==(192&a)&&(c=(15&t)<<18|(63&r)<<12|(63&i)<<6|63&a,c>65535&&c<1114112&&(o=c))}}null===o?(o=65533,s=1):o>65535&&(o-=65536,i.push(o>>>10&1023|55296),o=56320|1023&o),i.push(o),n+=s}return function(e){const t=e.length;if(t<=R)return String.fromCharCode.apply(String,e);let r="",i=0;for(;i<t;)r+=String.fromCharCode.apply(String,e.slice(i,i+=R));return r}(i)}l.TYPED_ARRAY_SUPPORT=function(){try{const e=new o(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,o.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),l.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(l.prototype,"parent",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.buffer}}),Object.defineProperty(l.prototype,"offset",{enumerable:!0,get:function(){if(l.isBuffer(this))return this.byteOffset}}),l.poolSize=8192,l.from=function(e,t,r){return u(e,t,r)},Object.setPrototypeOf(l.prototype,o.prototype),Object.setPrototypeOf(l,o),l.alloc=function(e,t,r){return function(e,t,r){return d(e),e<=0?c(e):void 0!==t?"string"==typeof r?c(e).fill(t,r):c(e).fill(t):c(e)}(e,t,r)},l.allocUnsafe=function(e){return p(e)},l.allocUnsafeSlow=function(e){return p(e)},l.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==l.prototype},l.compare=function(e,t){if(X(e,o)&&(e=l.from(e,e.offset,e.byteLength)),X(t,o)&&(t=l.from(t,t.offset,t.byteLength)),!l.isBuffer(e)||!l.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let r=e.length,i=t.length;for(let n=0,o=Math.min(r,i);n<o;++n)if(e[n]!==t[n]){r=e[n],i=t[n];break}return r<i?-1:i<r?1:0},l.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},l.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return l.alloc(0);let r;if(void 0===t)for(t=0,r=0;r<e.length;++r)t+=e[r].length;const i=l.allocUnsafe(t);let n=0;for(r=0;r<e.length;++r){let t=e[r];if(X(t,o))n+t.length>i.length?(l.isBuffer(t)||(t=l.from(t)),t.copy(i,n)):o.prototype.set.call(i,t,n);else{if(!l.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(i,n)}n+=t.length}return i},l.byteLength=f,l.prototype._isBuffer=!0,l.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)b(this,t,t+1);return this},l.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)b(this,t,t+3),b(this,t+1,t+2);return this},l.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)b(this,t,t+7),b(this,t+1,t+6),b(this,t+2,t+5),b(this,t+3,t+4);return this},l.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?C(this,0,e):y.apply(this,arguments)},l.prototype.toLocaleString=l.prototype.toString,l.prototype.equals=function(e){if(!l.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===l.compare(this,e)},l.prototype.inspect=function(){let t="";const r=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,r).replace(/(.{2})/g,"$1 ").trim(),this.length>r&&(t+=" ... "),"<Buffer "+t+">"},i&&(l.prototype[i]=l.prototype.inspect),l.prototype.compare=function(e,t,r,i,n){if(X(e,o)&&(e=l.from(e,e.offset,e.byteLength)),!l.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===r&&(r=e?e.length:0),void 0===i&&(i=0),void 0===n&&(n=this.length),t<0||r>e.length||i<0||n>this.length)throw new RangeError("out of range index");if(i>=n&&t>=r)return 0;if(i>=n)return-1;if(t>=r)return 1;if(this===e)return 0;let s=(n>>>=0)-(i>>>=0),a=(r>>>=0)-(t>>>=0);const c=Math.min(s,a),u=this.slice(i,n),d=e.slice(t,r);for(let o=0;o<c;++o)if(u[o]!==d[o]){s=u[o],a=d[o];break}return s<a?-1:a<s?1:0},l.prototype.includes=function(e,t,r){return-1!==this.indexOf(e,t,r)},l.prototype.indexOf=function(e,t,r){return w(this,e,t,r,!0)},l.prototype.lastIndexOf=function(e,t,r){return w(this,e,t,r,!1)},l.prototype.write=function(e,t,r,i){if(void 0===t)i="utf8",r=this.length,t=0;else if(void 0===r&&"string"==typeof t)i=t,r=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(r)?(r>>>=0,void 0===i&&(i="utf8")):(i=r,r=void 0)}const n=this.length-t;if((void 0===r||r>n)&&(r=n),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let o=!1;for(;;)switch(i){case"hex":return T(this,e,t,r);case"utf8":case"utf-8":return S(this,e,t,r);case"ascii":case"latin1":case"binary":return k(this,e,t,r);case"base64":return v(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return E(this,e,t,r);default:if(o)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),o=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const R=4096;function x(e,t,r){let i="";r=Math.min(e.length,r);for(let n=t;n<r;++n)i+=String.fromCharCode(127&e[n]);return i}function N(e,t,r){let i="";r=Math.min(e.length,r);for(let n=t;n<r;++n)i+=String.fromCharCode(e[n]);return i}function z(e,t,r){const i=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>i)&&(r=i);let n="";for(let o=t;o<r;++o)n+=ee[e[o]];return n}function _(e,t,r){const i=e.slice(t,r);let n="";for(let o=0;o<i.length-1;o+=2)n+=String.fromCharCode(i[o]+256*i[o+1]);return n}function P(e,t,r){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>r)throw new RangeError("Trying to access beyond buffer length")}function O(e,t,r,i,n,o){if(!l.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>n||t<o)throw new RangeError('"value" argument is out of bounds');if(r+i>e.length)throw new RangeError("Index out of range")}function D(e,t,r,i,n){q(t,i,n,e,r,7);let o=Number(t&BigInt(4294967295));e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o,o>>=8,e[r++]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,s>>=8,e[r++]=s,r}function F(e,t,r,i,n){q(t,i,n,e,r,7);let o=Number(t&BigInt(4294967295));e[r+7]=o,o>>=8,e[r+6]=o,o>>=8,e[r+5]=o,o>>=8,e[r+4]=o;let s=Number(t>>BigInt(32)&BigInt(4294967295));return e[r+3]=s,s>>=8,e[r+2]=s,s>>=8,e[r+1]=s,s>>=8,e[r]=s,r+8}function M(e,t,r,i,n,o){if(r+i>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function U(e,t,i,n,o){return t=+t,i>>>=0,o||M(e,0,i,4),r.write(e,t,i,n,23,4),i+4}function B(e,t,i,n,o){return t=+t,i>>>=0,o||M(e,0,i,8),r.write(e,t,i,n,52,8),i+8}l.prototype.slice=function(e,t){const r=this.length;(e=~~e)<0?(e+=r)<0&&(e=0):e>r&&(e=r),(t=void 0===t?r:~~t)<0?(t+=r)<0&&(t=0):t>r&&(t=r),t<e&&(t=e);const i=this.subarray(e,t);return Object.setPrototypeOf(i,l.prototype),i},l.prototype.readUintLE=l.prototype.readUIntLE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let i=this[e],n=1,o=0;for(;++o<t&&(n*=256);)i+=this[e+o]*n;return i},l.prototype.readUintBE=l.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let i=this[e+--t],n=1;for(;t>0&&(n*=256);)i+=this[e+--t]*n;return i},l.prototype.readUint8=l.prototype.readUInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),this[e]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]|this[e+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(e,t){return e>>>=0,t||P(e,2,this.length),this[e]<<8|this[e+1]},l.prototype.readUint32LE=l.prototype.readUInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},l.prototype.readUint32BE=l.prototype.readUInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},l.prototype.readBigUInt64LE=te(function(e){j(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||W(e,this.length-8);const i=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,n=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(i)+(BigInt(n)<<BigInt(32))}),l.prototype.readBigUInt64BE=te(function(e){j(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||W(e,this.length-8);const i=t*2**24+65536*this[++e]+256*this[++e]+this[++e],n=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(i)<<BigInt(32))+BigInt(n)}),l.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let i=this[e],n=1,o=0;for(;++o<t&&(n*=256);)i+=this[e+o]*n;return n*=128,i>=n&&(i-=Math.pow(2,8*t)),i},l.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||P(e,t,this.length);let i=t,n=1,o=this[e+--i];for(;i>0&&(n*=256);)o+=this[e+--i]*n;return n*=128,o>=n&&(o-=Math.pow(2,8*t)),o},l.prototype.readInt8=function(e,t){return e>>>=0,t||P(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},l.prototype.readInt16LE=function(e,t){e>>>=0,t||P(e,2,this.length);const r=this[e]|this[e+1]<<8;return 32768&r?4294901760|r:r},l.prototype.readInt16BE=function(e,t){e>>>=0,t||P(e,2,this.length);const r=this[e+1]|this[e]<<8;return 32768&r?4294901760|r:r},l.prototype.readInt32LE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},l.prototype.readInt32BE=function(e,t){return e>>>=0,t||P(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},l.prototype.readBigInt64LE=te(function(e){j(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||W(e,this.length-8);const i=this[e+4]+256*this[e+5]+65536*this[e+6]+(r<<24);return(BigInt(i)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),l.prototype.readBigInt64BE=te(function(e){j(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||W(e,this.length-8);const i=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(i)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+r)}),l.prototype.readFloatLE=function(e,t){return e>>>=0,t||P(e,4,this.length),r.read(this,e,!0,23,4)},l.prototype.readFloatBE=function(e,t){return e>>>=0,t||P(e,4,this.length),r.read(this,e,!1,23,4)},l.prototype.readDoubleLE=function(e,t){return e>>>=0,t||P(e,8,this.length),r.read(this,e,!0,52,8)},l.prototype.readDoubleBE=function(e,t){return e>>>=0,t||P(e,8,this.length),r.read(this,e,!1,52,8)},l.prototype.writeUintLE=l.prototype.writeUIntLE=function(e,t,r,i){if(e=+e,t>>>=0,r>>>=0,!i){O(this,e,t,r,Math.pow(2,8*r)-1,0)}let n=1,o=0;for(this[t]=255&e;++o<r&&(n*=256);)this[t+o]=e/n&255;return t+r},l.prototype.writeUintBE=l.prototype.writeUIntBE=function(e,t,r,i){if(e=+e,t>>>=0,r>>>=0,!i){O(this,e,t,r,Math.pow(2,8*r)-1,0)}let n=r-1,o=1;for(this[t+n]=255&e;--n>=0&&(o*=256);)this[t+n]=e/o&255;return t+r},l.prototype.writeUint8=l.prototype.writeUInt8=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,1,255,0),this[t]=255&e,t+1},l.prototype.writeUint16LE=l.prototype.writeUInt16LE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeUint16BE=l.prototype.writeUInt16BE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeUint32LE=l.prototype.writeUInt32LE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},l.prototype.writeUint32BE=l.prototype.writeUInt32BE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigUInt64LE=te(function(e,t=0){return D(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeBigUInt64BE=te(function(e,t=0){return F(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeIntLE=function(e,t,r,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*r-1);O(this,e,t,r,i-1,-i)}let n=0,o=1,s=0;for(this[t]=255&e;++n<r&&(o*=256);)e<0&&0===s&&0!==this[t+n-1]&&(s=1),this[t+n]=(e/o|0)-s&255;return t+r},l.prototype.writeIntBE=function(e,t,r,i){if(e=+e,t>>>=0,!i){const i=Math.pow(2,8*r-1);O(this,e,t,r,i-1,-i)}let n=r-1,o=1,s=0;for(this[t+n]=255&e;--n>=0&&(o*=256);)e<0&&0===s&&0!==this[t+n+1]&&(s=1),this[t+n]=(e/o|0)-s&255;return t+r},l.prototype.writeInt8=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},l.prototype.writeInt16LE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},l.prototype.writeInt16BE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},l.prototype.writeInt32LE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},l.prototype.writeInt32BE=function(e,t,r){return e=+e,t>>>=0,r||O(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},l.prototype.writeBigInt64LE=te(function(e,t=0){return D(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeBigInt64BE=te(function(e,t=0){return F(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeFloatLE=function(e,t,r){return U(this,e,t,!0,r)},l.prototype.writeFloatBE=function(e,t,r){return U(this,e,t,!1,r)},l.prototype.writeDoubleLE=function(e,t,r){return B(this,e,t,!0,r)},l.prototype.writeDoubleBE=function(e,t,r){return B(this,e,t,!1,r)},l.prototype.copy=function(e,t,r,i){if(!l.isBuffer(e))throw new TypeError("argument should be a Buffer");if(r||(r=0),i||0===i||(i=this.length),t>=e.length&&(t=e.length),t||(t=0),i>0&&i<r&&(i=r),i===r)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(r<0||r>=this.length)throw new RangeError("Index out of range");if(i<0)throw new RangeError("sourceEnd out of bounds");i>this.length&&(i=this.length),e.length-t<i-r&&(i=e.length-t+r);const n=i-r;return this===e&&"function"==typeof o.prototype.copyWithin?this.copyWithin(t,r,i):o.prototype.set.call(e,this.subarray(r,i),t),n},l.prototype.fill=function(e,t,r,i){if("string"==typeof e){if("string"==typeof t?(i=t,t=0,r=this.length):"string"==typeof r&&(i=r,r=this.length),void 0!==i&&"string"!=typeof i)throw new TypeError("encoding must be a string");if("string"==typeof i&&!l.isEncoding(i))throw new TypeError("Unknown encoding: "+i);if(1===e.length){const t=e.charCodeAt(0);("utf8"===i&&t<128||"latin1"===i)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<r)throw new RangeError("Out of range index");if(r<=t)return this;let n;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(n=t;n<r;++n)this[n]=e;else{const o=l.isBuffer(e)?e:l.from(e,i),s=o.length;if(0===s)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(n=0;n<r-t;++n)this[n+t]=o[n%s]}return this};const L={};function K(e,t,r){L[e]=class extends r{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function $(e){let t="",r=e.length;const i="-"===e[0]?1:0;for(;r>=i+4;r-=3)t=`_${e.slice(r-3,r)}${t}`;return`${e.slice(0,r)}${t}`}function q(e,t,r,i,n,o){if(e>r||e<t){const r="bigint"==typeof t?"n":"";let i;throw i=0===t||t===BigInt(0)?`>= 0${r} and < 2${r} ** ${8*(o+1)}${r}`:`>= -(2${r} ** ${8*(o+1)-1}${r}) and < 2 ** ${8*(o+1)-1}${r}`,new L.ERR_OUT_OF_RANGE("value",i,e)}!function(e,t,r){j(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||W(t,e.length-(r+1))}(i,n,o)}function j(e,t){if("number"!=typeof e)throw new L.ERR_INVALID_ARG_TYPE(t,"number",e)}function W(e,t,r){if(Math.floor(e)!==e)throw j(e,r),new L.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new L.ERR_BUFFER_OUT_OF_BOUNDS;throw new L.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}K("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),K("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),K("ERR_OUT_OF_RANGE",function(e,t,r){let i=`The value of "${e}" is out of range.`,n=r;return Number.isInteger(r)&&Math.abs(r)>2**32?n=$(String(r)):"bigint"==typeof r&&(n=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(n=$(n)),n+="n"),i+=` It must be ${t}. Received ${n}`,i},RangeError);const V=/[^+/0-9A-Za-z-_]/g;function G(e,t){let r;t=t||1/0;const i=e.length;let n=null;const o=[];for(let s=0;s<i;++s){if(r=e.charCodeAt(s),r>55295&&r<57344){if(!n){if(r>56319){(t-=3)>-1&&o.push(239,191,189);continue}if(s+1===i){(t-=3)>-1&&o.push(239,191,189);continue}n=r;continue}if(r<56320){(t-=3)>-1&&o.push(239,191,189),n=r;continue}r=65536+(n-55296<<10|r-56320)}else n&&(t-=3)>-1&&o.push(239,191,189);if(n=null,r<128){if((t-=1)<0)break;o.push(r)}else if(r<2048){if((t-=2)<0)break;o.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;o.push(r>>12|224,r>>6&63|128,63&r|128)}else{if(!(r<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;o.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return o}function J(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(V,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function Y(e,t,r,i){let n;for(n=0;n<i&&!(n+r>=t.length||n>=e.length);++n)t[n+r]=e[n];return n}function X(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Q(e){return e!=e}const ee=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const i=16*r;for(let n=0;n<16;++n)t[i+n]=e[r]+e[n]}return t}();function te(e){return"undefined"==typeof BigInt?re:e}function re(){throw new Error("BigInt not supported")}}($);const Q=$.Buffer,ee=$.Buffer,te=globalThis||self;function re(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ie,ne,oe={exports:{}},se=oe.exports={};function ae(){throw new Error("setTimeout has not been defined")}function ce(){throw new Error("clearTimeout has not been defined")}function le(e){if(ie===setTimeout)return setTimeout(e,0);if((ie===ae||!ie)&&setTimeout)return ie=setTimeout,setTimeout(e,0);try{return ie(e,0)}catch(t){try{return ie.call(null,e,0)}catch(r){return ie.call(this,e,0)}}}!function(){try{ie="function"==typeof setTimeout?setTimeout:ae}catch(e){ie=ae}try{ne="function"==typeof clearTimeout?clearTimeout:ce}catch(e){ne=ce}}();var ue,de=[],pe=!1,he=-1;function ge(){pe&&ue&&(pe=!1,ue.length?de=ue.concat(de):he=-1,de.length&&me())}function me(){if(!pe){var e=le(ge);pe=!0;for(var t=de.length;t;){for(ue=de,de=[];++he<t;)ue&&ue[he].run();he=-1,t=de.length}ue=null,pe=!1,function(e){if(ne===clearTimeout)return clearTimeout(e);if((ne===ce||!ne)&&clearTimeout)return ne=clearTimeout,clearTimeout(e);try{return ne(e)}catch(t){try{return ne.call(null,e)}catch(r){return ne.call(this,e)}}}(e)}}function fe(e,t){this.fun=e,this.array=t}function ye(){}se.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];de.push(new fe(e,t)),1!==de.length||pe||le(me)},fe.prototype.run=function(){this.fun.apply(null,this.array)},se.title="browser",se.browser=!0,se.env={},se.argv=[],se.version="",se.versions={},se.on=ye,se.addListener=ye,se.once=ye,se.off=ye,se.removeListener=ye,se.removeAllListeners=ye,se.emit=ye,se.prependListener=ye,se.prependOnceListener=ye,se.listeners=function(e){return[]},se.binding=function(e){throw new Error("process.binding is not supported")},se.cwd=function(){return"/"},se.chdir=function(e){throw new Error("process.chdir is not supported")},se.umask=function(){return 0};const be=re(oe.exports);function we(e,t){return function(){return e.apply(t,arguments)}}const{toString:Ie}=Object.prototype,{getPrototypeOf:Te}=Object,{iterator:Se,toStringTag:ke}=Symbol,ve=(e=>t=>{const r=Ie.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Ee=e=>(e=e.toLowerCase(),t=>ve(t)===e),Ae=e=>t=>typeof t===e,{isArray:Ce}=Array,Re=Ae("undefined");function xe(e){return null!==e&&!Re(e)&&null!==e.constructor&&!Re(e.constructor)&&_e(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Ne=Ee("ArrayBuffer");const ze=Ae("string"),_e=Ae("function"),Pe=Ae("number"),Oe=e=>null!==e&&"object"==typeof e,De=e=>{if("object"!==ve(e))return!1;const t=Te(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||ke in e||Se in e)},Fe=Ee("Date"),Me=Ee("File"),Ue=Ee("Blob"),Be=Ee("FileList"),Le=Ee("URLSearchParams"),[Ke,$e,He,qe]=["ReadableStream","Request","Response","Headers"].map(Ee);function je(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let i,n;if("object"!=typeof e&&(e=[e]),Ce(e))for(i=0,n=e.length;i<n;i++)t.call(null,e[i],i,e);else{if(xe(e))return;const n=r?Object.getOwnPropertyNames(e):Object.keys(e),o=n.length;let s;for(i=0;i<o;i++)s=n[i],t.call(null,e[s],s,e)}}function We(e,t){if(xe(e))return null;t=t.toLowerCase();const r=Object.keys(e);let i,n=r.length;for(;n-- >0;)if(i=r[n],t===i.toLowerCase())return i;return null}const Ve="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:te,Ge=e=>!Re(e)&&e!==Ve;const Je=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&Te(Uint8Array)),Ye=Ee("HTMLFormElement"),Xe=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),Ze=Ee("RegExp"),Qe=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),i={};je(r,(r,n)=>{let o;!1!==(o=t(r,n,e))&&(i[n]=o||r)}),Object.defineProperties(e,i)};const et=Ee("AsyncFunction"),tt=(rt="function"==typeof setImmediate,it=_e(Ve.postMessage),rt?setImmediate:it?(nt=`axios@${Math.random()}`,ot=[],Ve.addEventListener("message",({source:e,data:t})=>{e===Ve&&t===nt&&ot.length&&ot.shift()()},!1),e=>{ot.push(e),Ve.postMessage(nt,"*")}):e=>setTimeout(e));var rt,it,nt,ot;const st="undefined"!=typeof queueMicrotask?queueMicrotask.bind(Ve):void 0!==be&&be.nextTick||tt,at={isArray:Ce,isArrayBuffer:Ne,isBuffer:xe,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||_e(e.append)&&("formdata"===(t=ve(e))||"object"===t&&_e(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Ne(e.buffer),t},isString:ze,isNumber:Pe,isBoolean:e=>!0===e||!1===e,isObject:Oe,isPlainObject:De,isEmptyObject:e=>{if(!Oe(e)||xe(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(t){return!1}},isReadableStream:Ke,isRequest:$e,isResponse:He,isHeaders:qe,isUndefined:Re,isDate:Fe,isFile:Me,isBlob:Ue,isRegExp:Ze,isFunction:_e,isStream:e=>Oe(e)&&_e(e.pipe),isURLSearchParams:Le,isTypedArray:Je,isFileList:Be,forEach:je,merge:function e(){const{caseless:t}=Ge(this)&&this||{},r={},i=(i,n)=>{const o=t&&We(r,n)||n;De(r[o])&&De(i)?r[o]=e(r[o],i):De(i)?r[o]=e({},i):Ce(i)?r[o]=i.slice():r[o]=i};for(let n=0,o=arguments.length;n<o;n++)arguments[n]&&je(arguments[n],i);return r},extend:(e,t,r,{allOwnKeys:i}={})=>(je(t,(t,i)=>{r&&_e(t)?e[i]=we(t,r):e[i]=t},{allOwnKeys:i}),e),trim:e=>e.trim?e.trim():e.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,""),stripBOM:e=>(65279===e.charCodeAt(0)&&(e=e.slice(1)),e),inherits:(e,t,r,i)=>{e.prototype=Object.create(t.prototype,i),e.prototype.constructor=e,Object.defineProperty(e,"super",{value:t.prototype}),r&&Object.assign(e.prototype,r)},toFlatObject:(e,t,r,i)=>{let n,o,s;const a={};if(t=t||{},null==e)return t;do{for(n=Object.getOwnPropertyNames(e),o=n.length;o-- >0;)s=n[o],i&&!i(s,e,t)||a[s]||(t[s]=e[s],a[s]=!0);e=!1!==r&&Te(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:ve,kindOfTest:Ee,endsWith:(e,t,r)=>{e=String(e),(void 0===r||r>e.length)&&(r=e.length),r-=t.length;const i=e.indexOf(t,r);return-1!==i&&i===r},toArray:e=>{if(!e)return null;if(Ce(e))return e;let t=e.length;if(!Pe(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Se]).call(e);let i;for(;(i=r.next())&&!i.done;){const r=i.value;t.call(e,r[0],r[1])}},matchAll:(e,t)=>{let r;const i=[];for(;null!==(r=e.exec(t));)i.push(r);return i},isHTMLForm:Ye,hasOwnProperty:Xe,hasOwnProp:Xe,reduceDescriptors:Qe,freezeMethods:e=>{Qe(e,(t,r)=>{if(_e(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const i=e[r];_e(i)&&(t.enumerable=!1,"writable"in t?t.writable=!1:t.set||(t.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")}))})},toObjectSet:(e,t)=>{const r={},i=e=>{e.forEach(e=>{r[e]=!0})};return Ce(e)?i(e):i(String(e).split(t)),r},toCamelCase:e=>e.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(e,t,r){return t.toUpperCase()+r}),noop:()=>{},toFiniteNumber:(e,t)=>null!=e&&Number.isFinite(e=+e)?e:t,findKey:We,global:Ve,isContextDefined:Ge,isSpecCompliantForm:function(e){return!!(e&&_e(e.append)&&"FormData"===e[ke]&&e[Se])},toJSONObject:e=>{const t=new Array(10),r=(e,i)=>{if(Oe(e)){if(t.indexOf(e)>=0)return;if(xe(e))return e;if(!("toJSON"in e)){t[i]=e;const n=Ce(e)?[]:{};return je(e,(e,t)=>{const o=r(e,i+1);!Re(o)&&(n[t]=o)}),t[i]=void 0,n}}return e};return r(e,0)},isAsyncFn:et,isThenable:e=>e&&(Oe(e)||_e(e))&&_e(e.then)&&_e(e.catch),setImmediate:tt,asap:st,isIterable:e=>null!=e&&_e(e[Se])};function ct(e,t,r,i,n){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=(new Error).stack,this.message=e,this.name="AxiosError",t&&(this.code=t),r&&(this.config=r),i&&(this.request=i),n&&(this.response=n,this.status=n.status?n.status:null)}at.inherits(ct,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:at.toJSONObject(this.config),code:this.code,status:this.status}}});const lt=ct.prototype,ut={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(e=>{ut[e]={value:e}}),Object.defineProperties(ct,ut),Object.defineProperty(lt,"isAxiosError",{value:!0}),ct.from=(e,t,r,i,n,o)=>{const s=Object.create(lt);return at.toFlatObject(e,s,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),ct.call(s,e.message,t,r,i,n),s.cause=e,s.name=e.name,o&&Object.assign(s,o),s};function dt(e){return at.isPlainObject(e)||at.isArray(e)}function pt(e){return at.endsWith(e,"[]")?e.slice(0,-2):e}function ht(e,t,r){return e?e.concat(t).map(function(e,t){return e=pt(e),!r&&t?"["+e+"]":e}).join(r?".":""):t}const gt=at.toFlatObject(at,{},null,function(e){return/^is[A-Z]/.test(e)});function mt(e,t,r){if(!at.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const i=(r=at.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!at.isUndefined(t[e])})).metaTokens,n=r.visitor||l,o=r.dots,s=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&at.isSpecCompliantForm(t);if(!at.isFunction(n))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(at.isDate(e))return e.toISOString();if(at.isBoolean(e))return e.toString();if(!a&&at.isBlob(e))throw new ct("Blob is not supported. Use a Buffer instead.");return at.isArrayBuffer(e)||at.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):Q.from(e):e}function l(e,r,n){let a=e;if(e&&!n&&"object"==typeof e)if(at.endsWith(r,"{}"))r=i?r:r.slice(0,-2),e=JSON.stringify(e);else if(at.isArray(e)&&function(e){return at.isArray(e)&&!e.some(dt)}(e)||(at.isFileList(e)||at.endsWith(r,"[]"))&&(a=at.toArray(e)))return r=pt(r),a.forEach(function(e,i){!at.isUndefined(e)&&null!==e&&t.append(!0===s?ht([r],i,o):null===s?r:r+"[]",c(e))}),!1;return!!dt(e)||(t.append(ht(n,r,o),c(e)),!1)}const u=[],d=Object.assign(gt,{defaultVisitor:l,convertValue:c,isVisitable:dt});if(!at.isObject(e))throw new TypeError("data must be an object");return function e(r,i){if(!at.isUndefined(r)){if(-1!==u.indexOf(r))throw Error("Circular reference detected in "+i.join("."));u.push(r),at.forEach(r,function(r,o){!0===(!(at.isUndefined(r)||null===r)&&n.call(t,r,at.isString(o)?o.trim():o,i,d))&&e(r,i?i.concat(o):[o])}),u.pop()}}(e),t}function ft(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function yt(e,t){this._pairs=[],e&&mt(e,this,t)}const bt=yt.prototype;function wt(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function It(e,t,r){if(!t)return e;const i=r&&r.encode||wt;at.isFunction(r)&&(r={serialize:r});const n=r&&r.serialize;let o;if(o=n?n(t,r):at.isURLSearchParams(t)?t.toString():new yt(t,r).toString(i),o){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+o}return e}bt.append=function(e,t){this._pairs.push([e,t])},bt.toString=function(e){const t=e?function(t){return e.call(this,t,ft)}:ft;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class Tt{constructor(){this.handlers=[]}use(e,t,r){return this.handlers.push({fulfilled:e,rejected:t,synchronous:!!r&&r.synchronous,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){at.forEach(this.handlers,function(t){null!==t&&e(t)})}}const St={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},kt={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:yt,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},vt="undefined"!=typeof window&&"undefined"!=typeof document,Et="object"==typeof navigator&&navigator||void 0,At=vt&&(!Et||["ReactNative","NativeScript","NS"].indexOf(Et.product)<0),Ct="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Rt=vt&&window.location.href||"http://localhost",xt={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:vt,hasStandardBrowserEnv:At,hasStandardBrowserWebWorkerEnv:Ct,navigator:Et,origin:Rt},Symbol.toStringTag,{value:"Module"})),...kt};function Nt(e){function t(e,r,i,n){let o=e[n++];if("__proto__"===o)return!0;const s=Number.isFinite(+o),a=n>=e.length;if(o=!o&&at.isArray(i)?i.length:o,a)return at.hasOwnProp(i,o)?i[o]=[i[o],r]:i[o]=r,!s;i[o]&&at.isObject(i[o])||(i[o]=[]);return t(e,r,i[o],n)&&at.isArray(i[o])&&(i[o]=function(e){const t={},r=Object.keys(e);let i;const n=r.length;let o;for(i=0;i<n;i++)o=r[i],t[o]=e[o];return t}(i[o])),!s}if(at.isFormData(e)&&at.isFunction(e.entries)){const r={};return at.forEachEntry(e,(e,i)=>{t(function(e){return at.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),i,r,0)}),r}return null}const zt={transitional:St,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",i=r.indexOf("application/json")>-1,n=at.isObject(e);n&&at.isHTMLForm(e)&&(e=new FormData(e));if(at.isFormData(e))return i?JSON.stringify(Nt(e)):e;if(at.isArrayBuffer(e)||at.isBuffer(e)||at.isStream(e)||at.isFile(e)||at.isBlob(e)||at.isReadableStream(e))return e;if(at.isArrayBufferView(e))return e.buffer;if(at.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let o;if(n){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return mt(e,new xt.classes.URLSearchParams,{visitor:function(e,t,r,i){return xt.isNode&&at.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}(e,this.formSerializer).toString();if((o=at.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return mt(o?{"files[]":e}:e,t&&new t,this.formSerializer)}}return n||i?(t.setContentType("application/json",!1),function(e,t,r){if(at.isString(e))try{return(t||JSON.parse)(e),at.trim(e)}catch(i){if("SyntaxError"!==i.name)throw i}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||zt.transitional,r=t&&t.forcedJSONParsing,i="json"===this.responseType;if(at.isResponse(e)||at.isReadableStream(e))return e;if(e&&at.isString(e)&&(r&&!this.responseType||i)){const r=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(n){if(r){if("SyntaxError"===n.name)throw ct.from(n,ct.ERR_BAD_RESPONSE,this,null,this.response);throw n}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:xt.classes.FormData,Blob:xt.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};at.forEach(["delete","get","head","post","put","patch"],e=>{zt.headers[e]={}});const _t=at.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Pt=Symbol("internals");function Ot(e){return e&&String(e).trim().toLowerCase()}function Dt(e){return!1===e||null==e?e:at.isArray(e)?e.map(Dt):String(e)}function Ft(e,t,r,i,n){return at.isFunction(i)?i.call(this,t,r):(n&&(t=r),at.isString(t)?at.isString(i)?-1!==t.indexOf(i):at.isRegExp(i)?i.test(t):void 0:void 0)}let Mt=class{constructor(e){e&&this.set(e)}set(e,t,r){const i=this;function n(e,t,r){const n=Ot(t);if(!n)throw new Error("header name must be a non-empty string");const o=at.findKey(i,n);(!o||void 0===i[o]||!0===r||void 0===r&&!1!==i[o])&&(i[o||t]=Dt(e))}const o=(e,t)=>at.forEach(e,(e,r)=>n(e,r,t));if(at.isPlainObject(e)||e instanceof this.constructor)o(e,t);else if(at.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))o((e=>{const t={};let r,i,n;return e&&e.split("\n").forEach(function(e){n=e.indexOf(":"),r=e.substring(0,n).trim().toLowerCase(),i=e.substring(n+1).trim(),!r||t[r]&&_t[r]||("set-cookie"===r?t[r]?t[r].push(i):t[r]=[i]:t[r]=t[r]?t[r]+", "+i:i)}),t})(e),t);else if(at.isObject(e)&&at.isIterable(e)){let r,i,n={};for(const t of e){if(!at.isArray(t))throw TypeError("Object iterator must return a key-value pair");n[i=t[0]]=(r=n[i])?at.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}o(n,t)}else null!=e&&n(t,e,r);return this}get(e,t){if(e=Ot(e)){const r=at.findKey(this,e);if(r){const e=this[r];if(!t)return e;if(!0===t)return function(e){const t=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let i;for(;i=r.exec(e);)t[i[1]]=i[2];return t}(e);if(at.isFunction(t))return t.call(this,e,r);if(at.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Ot(e)){const r=at.findKey(this,e);return!(!r||void 0===this[r]||t&&!Ft(0,this[r],r,t))}return!1}delete(e,t){const r=this;let i=!1;function n(e){if(e=Ot(e)){const n=at.findKey(r,e);!n||t&&!Ft(0,r[n],n,t)||(delete r[n],i=!0)}}return at.isArray(e)?e.forEach(n):n(e),i}clear(e){const t=Object.keys(this);let r=t.length,i=!1;for(;r--;){const n=t[r];e&&!Ft(0,this[n],n,e,!0)||(delete this[n],i=!0)}return i}normalize(e){const t=this,r={};return at.forEach(this,(i,n)=>{const o=at.findKey(r,n);if(o)return t[o]=Dt(i),void delete t[n];const s=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,r)=>t.toUpperCase()+r)}(n):String(n).trim();s!==n&&delete t[n],t[s]=Dt(i),r[s]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return at.forEach(this,(r,i)=>{null!=r&&!1!==r&&(t[i]=e&&at.isArray(r)?r.join(", "):r)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join("\n")}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const r=new this(e);return t.forEach(e=>r.set(e)),r}static accessor(e){const t=(this[Pt]=this[Pt]={accessors:{}}).accessors,r=this.prototype;function i(e){const i=Ot(e);t[i]||(!function(e,t){const r=at.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+r,{value:function(e,r,n){return this[i].call(this,t,e,r,n)},configurable:!0})})}(r,e),t[i]=!0)}return at.isArray(e)?e.forEach(i):i(e),this}};function Ut(e,t){const r=this||zt,i=t||r,n=Mt.from(i.headers);let o=i.data;return at.forEach(e,function(e){o=e.call(r,o,n.normalize(),t?t.status:void 0)}),n.normalize(),o}function Bt(e){return!(!e||!e.__CANCEL__)}function Lt(e,t,r){ct.call(this,null==e?"canceled":e,ct.ERR_CANCELED,t,r),this.name="CanceledError"}function Kt(e,t,r){const i=r.config.validateStatus;r.status&&i&&!i(r.status)?t(new ct("Request failed with status code "+r.status,[ct.ERR_BAD_REQUEST,ct.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}Mt.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),at.reduceDescriptors(Mt.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}}),at.freezeMethods(Mt),at.inherits(Lt,ct,{__CANCEL__:!0});const $t=(e,t,r=3)=>{let i=0;const n=function(e,t){e=e||10;const r=new Array(e),i=new Array(e);let n,o=0,s=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),l=i[s];n||(n=c),r[o]=a,i[o]=c;let u=s,d=0;for(;u!==o;)d+=r[u++],u%=e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),c-n<t)return;const p=l&&c-l;return p?Math.round(1e3*d/p):void 0}}(50,250);return function(e,t){let r,i,n=0,o=1e3/t;const s=(t,o=Date.now())=>{n=o,r=null,i&&(clearTimeout(i),i=null),e(...t)};return[(...e)=>{const t=Date.now(),a=t-n;a>=o?s(e,t):(r=e,i||(i=setTimeout(()=>{i=null,s(r)},o-a)))},()=>r&&s(r)]}(r=>{const o=r.loaded,s=r.lengthComputable?r.total:void 0,a=o-i,c=n(a);i=o;e({loaded:o,total:s,progress:s?o/s:void 0,bytes:a,rate:c||void 0,estimated:c&&s&&o<=s?(s-o)/c:void 0,event:r,lengthComputable:null!=s,[t?"download":"upload"]:!0})},r)},Ht=(e,t)=>{const r=null!=e;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},qt=e=>(...t)=>at.asap(()=>e(...t)),jt=xt.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,xt.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(xt.origin),xt.navigator&&/(msie|trident)/i.test(xt.navigator.userAgent)):()=>!0,Wt=xt.hasStandardBrowserEnv?{write(e,t,r,i,n,o){const s=[e+"="+encodeURIComponent(t)];at.isNumber(r)&&s.push("expires="+new Date(r).toGMTString()),at.isString(i)&&s.push("path="+i),at.isString(n)&&s.push("domain="+n),!0===o&&s.push("secure"),document.cookie=s.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read:()=>null,remove(){}};function Vt(e,t,r){let i=!/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t);return e&&(i||0==r)?function(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}(e,t):t}const Gt=e=>e instanceof Mt?{...e}:e;function Jt(e,t){t=t||{};const r={};function i(e,t,r,i){return at.isPlainObject(e)&&at.isPlainObject(t)?at.merge.call({caseless:i},e,t):at.isPlainObject(t)?at.merge({},t):at.isArray(t)?t.slice():t}function n(e,t,r,n){return at.isUndefined(t)?at.isUndefined(e)?void 0:i(void 0,e,0,n):i(e,t,0,n)}function o(e,t){if(!at.isUndefined(t))return i(void 0,t)}function s(e,t){return at.isUndefined(t)?at.isUndefined(e)?void 0:i(void 0,e):i(void 0,t)}function a(r,n,o){return o in t?i(r,n):o in e?i(void 0,r):void 0}const c={url:o,method:o,data:o,baseURL:s,transformRequest:s,transformResponse:s,paramsSerializer:s,timeout:s,timeoutMessage:s,withCredentials:s,withXSRFToken:s,adapter:s,responseType:s,xsrfCookieName:s,xsrfHeaderName:s,onUploadProgress:s,onDownloadProgress:s,decompress:s,maxContentLength:s,maxBodyLength:s,beforeRedirect:s,transport:s,httpAgent:s,httpsAgent:s,cancelToken:s,socketPath:s,responseEncoding:s,validateStatus:a,headers:(e,t,r)=>n(Gt(e),Gt(t),0,!0)};return at.forEach(Object.keys({...e,...t}),function(i){const o=c[i]||n,s=o(e[i],t[i],i);at.isUndefined(s)&&o!==a||(r[i]=s)}),r}const Yt=e=>{const t=Jt({},e);let r,{data:i,withXSRFToken:n,xsrfHeaderName:o,xsrfCookieName:s,headers:a,auth:c}=t;if(t.headers=a=Mt.from(a),t.url=It(Vt(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),at.isFormData(i))if(xt.hasStandardBrowserEnv||xt.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(!1!==(r=a.getContentType())){const[e,...t]=r?r.split(";").map(e=>e.trim()).filter(Boolean):[];a.setContentType([e||"multipart/form-data",...t].join("; "))}if(xt.hasStandardBrowserEnv&&(n&&at.isFunction(n)&&(n=n(t)),n||!1!==n&&jt(t.url))){const e=o&&s&&Wt.read(s);e&&a.set(o,e)}return t},Xt="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,r){const i=Yt(e);let n=i.data;const o=Mt.from(i.headers).normalize();let s,a,c,l,u,{responseType:d,onUploadProgress:p,onDownloadProgress:h}=i;function g(){l&&l(),u&&u(),i.cancelToken&&i.cancelToken.unsubscribe(s),i.signal&&i.signal.removeEventListener("abort",s)}let m=new XMLHttpRequest;function f(){if(!m)return;const i=Mt.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());Kt(function(e){t(e),g()},function(e){r(e),g()},{data:d&&"text"!==d&&"json"!==d?m.response:m.responseText,status:m.status,statusText:m.statusText,headers:i,config:e,request:m}),m=null}m.open(i.method.toUpperCase(),i.url,!0),m.timeout=i.timeout,"onloadend"in m?m.onloadend=f:m.onreadystatechange=function(){m&&4===m.readyState&&(0!==m.status||m.responseURL&&0===m.responseURL.indexOf("file:"))&&setTimeout(f)},m.onabort=function(){m&&(r(new ct("Request aborted",ct.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new ct("Network Error",ct.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let t=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const n=i.transitional||St;i.timeoutErrorMessage&&(t=i.timeoutErrorMessage),r(new ct(t,n.clarifyTimeoutError?ct.ETIMEDOUT:ct.ECONNABORTED,e,m)),m=null},void 0===n&&o.setContentType(null),"setRequestHeader"in m&&at.forEach(o.toJSON(),function(e,t){m.setRequestHeader(t,e)}),at.isUndefined(i.withCredentials)||(m.withCredentials=!!i.withCredentials),d&&"json"!==d&&(m.responseType=i.responseType),h&&([c,u]=$t(h,!0),m.addEventListener("progress",c)),p&&m.upload&&([a,l]=$t(p),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",l)),(i.cancelToken||i.signal)&&(s=t=>{m&&(r(!t||t.type?new Lt(null,e,m):t),m.abort(),m=null)},i.cancelToken&&i.cancelToken.subscribe(s),i.signal&&(i.signal.aborted?s():i.signal.addEventListener("abort",s)));const y=function(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}(i.url);y&&-1===xt.protocols.indexOf(y)?r(new ct("Unsupported protocol "+y+":",ct.ERR_BAD_REQUEST,e)):m.send(n||null)})},Zt=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,i=new AbortController;const n=function(e){if(!r){r=!0,s();const t=e instanceof Error?e:this.reason;i.abort(t instanceof ct?t:new Lt(t instanceof Error?t.message:t))}};let o=t&&setTimeout(()=>{o=null,n(new ct(`timeout ${t} of ms exceeded`,ct.ETIMEDOUT))},t);const s=()=>{e&&(o&&clearTimeout(o),o=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(n):e.removeEventListener("abort",n)}),e=null)};e.forEach(e=>e.addEventListener("abort",n));const{signal:a}=i;return a.unsubscribe=()=>at.asap(s),a}},Qt=function*(e,t){let r=e.byteLength;if(r<t)return void(yield e);let i,n=0;for(;n<r;)i=n+t,yield e.slice(n,i),n=i},er=async function*(e){if(e[Symbol.asyncIterator])return void(yield*e);const t=e.getReader();try{for(;;){const{done:e,value:r}=await t.read();if(e)break;yield r}}finally{await t.cancel()}},tr=(e,t,r,i)=>{const n=async function*(e,t){for await(const r of er(e))yield*Qt(r,t)}(e,t);let o,s=0,a=e=>{o||(o=!0,i&&i(e))};return new ReadableStream({async pull(e){try{const{done:t,value:i}=await n.next();if(t)return a(),void e.close();let o=i.byteLength;if(r){let e=s+=o;r(e)}e.enqueue(new Uint8Array(i))}catch(t){throw a(t),t}},cancel:e=>(a(e),n.return())},{highWaterMark:2})},rr="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,ir=rr&&"function"==typeof ReadableStream,nr=rr&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),or=(e,...t)=>{try{return!!e(...t)}catch(r){return!1}},sr=ir&&or(()=>{let e=!1;const t=new Request(xt.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),ar=ir&&or(()=>at.isReadableStream(new Response("").body)),cr={stream:ar&&(e=>e.body)};var lr;rr&&(lr=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!cr[e]&&(cr[e]=at.isFunction(lr[e])?t=>t[e]():(t,r)=>{throw new ct(`Response type '${e}' is not supported`,ct.ERR_NOT_SUPPORT,r)})}));const ur=async(e,t)=>{const r=at.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(at.isBlob(e))return e.size;if(at.isSpecCompliantForm(e)){const t=new Request(xt.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return at.isArrayBufferView(e)||at.isArrayBuffer(e)?e.byteLength:(at.isURLSearchParams(e)&&(e+=""),at.isString(e)?(await nr(e)).byteLength:void 0)})(t):r},dr={http:null,xhr:Xt,fetch:rr&&(async e=>{let{url:t,method:r,data:i,signal:n,cancelToken:o,timeout:s,onDownloadProgress:a,onUploadProgress:c,responseType:l,headers:u,withCredentials:d="same-origin",fetchOptions:p}=Yt(e);l=l?(l+"").toLowerCase():"text";let h,g=Zt([n,o&&o.toAbortSignal()],s);const m=g&&g.unsubscribe&&(()=>{g.unsubscribe()});let f;try{if(c&&sr&&"get"!==r&&"head"!==r&&0!==(f=await ur(u,i))){let e,r=new Request(t,{method:"POST",body:i,duplex:"half"});if(at.isFormData(i)&&(e=r.headers.get("content-type"))&&u.setContentType(e),r.body){const[e,t]=Ht(f,$t(qt(c)));i=tr(r.body,65536,e,t)}}at.isString(d)||(d=d?"include":"omit");const n="credentials"in Request.prototype;h=new Request(t,{...p,signal:g,method:r.toUpperCase(),headers:u.normalize().toJSON(),body:i,duplex:"half",credentials:n?d:void 0});let o=await fetch(h,p);const s=ar&&("stream"===l||"response"===l);if(ar&&(a||s&&m)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=o[t]});const t=at.toFiniteNumber(o.headers.get("content-length")),[r,i]=a&&Ht(t,$t(qt(a),!0))||[];o=new Response(tr(o.body,65536,r,()=>{i&&i(),m&&m()}),e)}l=l||"text";let y=await cr[at.findKey(cr,l)||"text"](o,e);return!s&&m&&m(),await new Promise((t,r)=>{Kt(t,r,{data:y,headers:Mt.from(o.headers),status:o.status,statusText:o.statusText,config:e,request:h})})}catch(y){if(m&&m(),y&&"TypeError"===y.name&&/Load failed|fetch/i.test(y.message))throw Object.assign(new ct("Network Error",ct.ERR_NETWORK,e,h),{cause:y.cause||y});throw ct.from(y,y&&y.code,e,h)}})};at.forEach(dr,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(r){}Object.defineProperty(e,"adapterName",{value:t})}});const pr=e=>`- ${e}`,hr=e=>at.isFunction(e)||null===e||!1===e,gr=e=>{e=at.isArray(e)?e:[e];const{length:t}=e;let r,i;const n={};for(let o=0;o<t;o++){let t;if(r=e[o],i=r,!hr(r)&&(i=dr[(t=String(r)).toLowerCase()],void 0===i))throw new ct(`Unknown adapter '${t}'`);if(i)break;n[t||"#"+o]=i}if(!i){const e=Object.entries(n).map(([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));throw new ct("There is no suitable adapter to dispatch the request "+(t?e.length>1?"since :\n"+e.map(pr).join("\n"):" "+pr(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return i};function mr(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new Lt(null,e)}function fr(e){mr(e),e.headers=Mt.from(e.headers),e.data=Ut.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return gr(e.adapter||zt.adapter)(e).then(function(t){return mr(e),t.data=Ut.call(e,e.transformResponse,t),t.headers=Mt.from(t.headers),t},function(t){return Bt(t)||(mr(e),t&&t.response&&(t.response.data=Ut.call(e,e.transformResponse,t.response),t.response.headers=Mt.from(t.response.headers))),Promise.reject(t)})}const yr="1.11.0",br={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{br[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const wr={};br.transitional=function(e,t,r){function i(e,t){return"[Axios v"+yr+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,n,o)=>{if(!1===e)throw new ct(i(n," has been removed"+(t?" in "+t:"")),ct.ERR_DEPRECATED);return t&&!wr[n]&&(wr[n]=!0,console.warn(i(n," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,n,o)}},br.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};const Ir={assertOptions:function(e,t,r){if("object"!=typeof e)throw new ct("options must be an object",ct.ERR_BAD_OPTION_VALUE);const i=Object.keys(e);let n=i.length;for(;n-- >0;){const o=i[n],s=t[o];if(s){const t=e[o],r=void 0===t||s(t,o,e);if(!0!==r)throw new ct("option "+o+" must be "+r,ct.ERR_BAD_OPTION_VALUE);continue}if(!0!==r)throw new ct("Unknown option "+o,ct.ERR_BAD_OPTION)}},validators:br},Tr=Ir.validators;let Sr=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Tt,response:new Tt}}async request(e,t){try{return await this._request(e,t)}catch(r){if(r instanceof Error){let e={};Error.captureStackTrace?Error.captureStackTrace(e):e=new Error;const t=e.stack?e.stack.replace(/^.+\n/,""):"";try{r.stack?t&&!String(r.stack).endsWith(t.replace(/^.+\n.+\n/,""))&&(r.stack+="\n"+t):r.stack=t}catch(i){}}throw r}}_request(e,t){"string"==typeof e?(t=t||{}).url=e:t=e||{},t=Jt(this.defaults,t);const{transitional:r,paramsSerializer:i,headers:n}=t;void 0!==r&&Ir.assertOptions(r,{silentJSONParsing:Tr.transitional(Tr.boolean),forcedJSONParsing:Tr.transitional(Tr.boolean),clarifyTimeoutError:Tr.transitional(Tr.boolean)},!1),null!=i&&(at.isFunction(i)?t.paramsSerializer={serialize:i}:Ir.assertOptions(i,{encode:Tr.function,serialize:Tr.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Ir.assertOptions(t,{baseUrl:Tr.spelling("baseURL"),withXsrfToken:Tr.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let o=n&&at.merge(n.common,n[t.method]);n&&at.forEach(["delete","get","head","post","put","patch","common"],e=>{delete n[e]}),t.headers=Mt.concat(o,n);const s=[];let a=!0;this.interceptors.request.forEach(function(e){"function"==typeof e.runWhen&&!1===e.runWhen(t)||(a=a&&e.synchronous,s.unshift(e.fulfilled,e.rejected))});const c=[];let l;this.interceptors.response.forEach(function(e){c.push(e.fulfilled,e.rejected)});let u,d=0;if(!a){const e=[fr.bind(this),void 0];for(e.unshift(...s),e.push(...c),u=e.length,l=Promise.resolve(t);d<u;)l=l.then(e[d++],e[d++]);return l}u=s.length;let p=t;for(d=0;d<u;){const e=s[d++],t=s[d++];try{p=e(p)}catch(h){t.call(this,h);break}}try{l=fr.call(this,p)}catch(h){return Promise.reject(h)}for(d=0,u=c.length;d<u;)l=l.then(c[d++],c[d++]);return l}getUri(e){return It(Vt((e=Jt(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};at.forEach(["delete","get","head","options"],function(e){Sr.prototype[e]=function(t,r){return this.request(Jt(r||{},{method:e,url:t,data:(r||{}).data}))}}),at.forEach(["post","put","patch"],function(e){function t(t){return function(r,i,n){return this.request(Jt(n||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:i}))}}Sr.prototype[e]=t(),Sr.prototype[e+"Form"]=t(!0)});const kr={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(kr).forEach(([e,t])=>{kr[t]=e});const vr=function e(t){const r=new Sr(t),i=we(Sr.prototype.request,r);return at.extend(i,Sr.prototype,r,{allOwnKeys:!0}),at.extend(i,r,null,{allOwnKeys:!0}),i.create=function(r){return e(Jt(t,r))},i}(zt);vr.Axios=Sr,vr.CanceledError=Lt,vr.CancelToken=class e{constructor(e){if("function"!=typeof e)throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(e){t=e});const r=this;this.promise.then(e=>{if(!r._listeners)return;let t=r._listeners.length;for(;t-- >0;)r._listeners[t](e);r._listeners=null}),this.promise.then=e=>{let t;const i=new Promise(e=>{r.subscribe(e),t=e}).then(e);return i.cancel=function(){r.unsubscribe(t)},i},e(function(e,i,n){r.reason||(r.reason=new Lt(e,i,n),t(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){this.reason?e(this.reason):this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);-1!==t&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=t=>{e.abort(t)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let t;return{token:new e(function(e){t=e}),cancel:t}}},vr.isCancel=Bt,vr.VERSION=yr,vr.toFormData=mt,vr.AxiosError=ct,vr.Cancel=vr.CanceledError,vr.all=function(e){return Promise.all(e)},vr.spread=function(e){return function(t){return e.apply(null,t)}},vr.isAxiosError=function(e){return at.isObject(e)&&!0===e.isAxiosError},vr.mergeConfig=Jt,vr.AxiosHeaders=Mt,vr.formToJSON=e=>Nt(at.isHTMLForm(e)?new FormData(e):e),vr.getAdapter=gr,vr.HttpStatusCode=kr,vr.default=vr;const{Axios:Er,AxiosError:Ar,CanceledError:Cr,isCancel:Rr,CancelToken:xr,VERSION:Nr,all:zr,Cancel:_r,isAxiosError:Pr,spread:Or,toFormData:Dr,AxiosHeaders:Fr,HttpStatusCode:Mr,formToJSON:Ur,getAdapter:Br,mergeConfig:Lr}=vr,Kr=class e{constructor(){K(this,"isProduction"),this.isProduction="production"===be.env.NODE_ENV}static getInstance(){return e.instance||(e.instance=new e),e.instance}debug(e,...t){this.isProduction||console.debug(e,...t)}info(e,...t){this.isProduction||console.info(e,...t)}warn(e,...t){console.warn(e,...t)}error(e,...t){console.error(e,...t)}};K(Kr,"instance");let $r=Kr;class Hr extends Error{constructor(e){super(e),this.name="ValidationError"}}function qr(e){try{return{detectedType:"ecdsa",privateKey:r.PrivateKey.fromStringECDSA(e)}}catch(t){try{return{detectedType:"ed25519",privateKey:r.PrivateKey.fromStringED25519(e)}}catch{throw new Error(`Failed to parse private key as either ECDSA or ED25519: ${String(t)}`)}}}class jr{constructor(e){if(K(this,"accountId"),K(this,"privateKey"),K(this,"baseUrl"),K(this,"network"),this.accountId=e.accountId,"string"==typeof e.privateKey){const t=qr(e.privateKey);this.privateKey=t.privateKey}else this.privateKey=e.privateKey;this.network=e.network||"mainnet",this.baseUrl=function(e){let t=e.trim();return t=t.replace(/\/+$/,""),t.endsWith("/api")?t.slice(0,-4):t}(e.baseUrl||"https://kiloscribe.com")}async authenticate(){var e,t,r;const i=await vr.get(`${this.baseUrl}/api/auth/request-signature`,{headers:{"x-session":this.accountId}});if(!(null==(e=i.data)?void 0:e.message))throw new Error("Failed to get signature message");const n=i.data.message,o=await this.signMessage(n),s=await vr.post(`${this.baseUrl}/api/auth/authenticate`,{authData:{id:this.accountId,signature:o,data:n,network:this.network},include:"apiKey"});if(!(null==(r=null==(t=s.data)?void 0:t.user)?void 0:r.sessionToken))throw new Error("Authentication failed");return{apiKey:s.data.apiKey}}async signMessage(e){const t=(new TextEncoder).encode(e),r=await this.privateKey.sign(t);return ee.from(r).toString("hex")}}class Wr{constructor(e,t){K(this,"baseUrl"),this.baseUrl=t??function(e){return"mainnet"===e?"https://mainnet-public.mirrornode.hedera.com":"https://testnet.mirrornode.hedera.com"}(e)}async requestAccount(e){return(await vr.get(`${this.baseUrl}/api/v1/accounts/${e}`)).data}}class Vr{constructor(e){K(this,"accountId"),K(this,"signer"),K(this,"baseUrl"),K(this,"network"),K(this,"logger"),this.accountId=e.accountId,this.signer=e.signer,this.network=e.network||"mainnet",this.baseUrl=e.baseUrl||"https://kiloscribe.com",this.logger=e.logger}async authenticate(){var e,t,r;const i=await vr.get(`${this.baseUrl}/api/auth/request-signature`,{headers:{"x-session":this.accountId}});if(!(null==(e=i.data)?void 0:e.message))throw new Error("Failed to get signature message");const n=i.data.message,o=await this.signMessage(JSON.stringify(n)),s=await vr.post(`${this.baseUrl}/api/auth/authenticate`,{authData:{id:this.accountId,signature:o,data:n,network:this.network},include:"apiKey"});if(!(null==(r=null==(t=s.data)?void 0:t.user)?void 0:r.sessionToken))throw new Error("Authentication failed");return{apiKey:s.data.apiKey}}async signMessage(e){try{const t=(new TextEncoder).encode(e);this.logger.debug("signing message");const r=await this.signer.sign([t],{encoding:"utf-8"});return ee.from(null==r?void 0:r[0].signature).toString("hex")}catch(t){throw this.logger.error("Failed to sign message",t),new Error("Failed to sign message")}}}function Gr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Jr(e){return new DataView(e.buffer,e.byteOffset)}const Yr={len:1,get:(e,t)=>Jr(e).getUint8(t),put:(e,t,r)=>(Jr(e).setUint8(t,r),t+1)},Xr={len:2,get:(e,t)=>Jr(e).getUint16(t,!0),put:(e,t,r)=>(Jr(e).setUint16(t,r,!0),t+2)},Zr={len:2,get:(e,t)=>Jr(e).getUint16(t),put:(e,t,r)=>(Jr(e).setUint16(t,r),t+2)},Qr={len:4,get:(e,t)=>Jr(e).getUint32(t,!0),put:(e,t,r)=>(Jr(e).setUint32(t,r,!0),t+4)},ei={len:4,get:(e,t)=>Jr(e).getUint32(t),put:(e,t,r)=>(Jr(e).setUint32(t,r),t+4)},ti={len:4,get:(e,t)=>Jr(e).getInt32(t),put:(e,t,r)=>(Jr(e).setInt32(t,r),t+4)},ri={len:8,get:(e,t)=>Jr(e).getBigUint64(t,!0),put:(e,t,r)=>(Jr(e).setBigUint64(t,r,!0),t+8)};class ii{constructor(e,t){if(this.len=e,t&&"windows-1252"===t.toLowerCase())this.decoder=ii.decodeWindows1252;else{const e=new TextDecoder(t);this.decoder=t=>e.decode(t)}}get(e,t=0){const r=e.subarray(t,t+this.len);return this.decoder(r)}static decodeWindows1252(e){let t="";for(let r=0;r<e.length;r++){const i=e[r];t+=i<128||i>=160?String.fromCharCode(i):ii.win1252Map[i-128]}return t}}ii.win1252Map="€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ";class ni extends Error{constructor(){super("End-Of-Stream"),this.name="EndOfStreamError"}}class oi extends Error{constructor(e="The operation was aborted"){super(e),this.name="AbortError"}}class si{constructor(){this.endOfStream=!1,this.interrupted=!1,this.peekQueue=[]}async peek(e,t=!1){const r=await this.read(e,t);return this.peekQueue.push(e.subarray(0,r)),r}async read(e,t=!1){if(0===e.length)return 0;let r=this.readFromPeekBuffer(e);if(this.endOfStream||(r+=await this.readRemainderFromStream(e.subarray(r),t)),0===r&&!t)throw new ni;return r}readFromPeekBuffer(e){let t=e.length,r=0;for(;this.peekQueue.length>0&&t>0;){const i=this.peekQueue.pop();if(!i)throw new Error("peekData should be defined");const n=Math.min(i.length,t);e.set(i.subarray(0,n),r),r+=n,t-=n,n<i.length&&this.peekQueue.push(i.subarray(n))}return r}async readRemainderFromStream(e,t){let r=0;for(;r<e.length&&!this.endOfStream;){if(this.interrupted)throw new oi;const i=await this.readFromStream(e.subarray(r),t);if(0===i)break;r+=i}if(!t&&r<e.length)throw new ni;return r}}class ai extends si{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}}class ci extends ai{async readFromStream(e,t){if(0===e.length)return 0;const r=await this.reader.read(new Uint8Array(e.length),{min:t?void 0:e.length});return r.done&&(this.endOfStream=r.done),r.value?(e.set(r.value),r.value.length):0}}class li extends si{constructor(e){super(),this.reader=e,this.buffer=null}writeChunk(e,t){const r=Math.min(t.length,e.length);return e.set(t.subarray(0,r)),r<t.length?this.buffer=t.subarray(r):this.buffer=null,r}async readFromStream(e,t){if(0===e.length)return 0;let r=0;for(this.buffer&&(r+=this.writeChunk(e,this.buffer));r<e.length&&!this.endOfStream;){const t=await this.reader.read();if(t.done){this.endOfStream=!0;break}t.value&&(r+=this.writeChunk(e.subarray(r),t.value))}if(!t&&0===r&&this.endOfStream)throw new ni;return r}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}}class ui{constructor(e){this.numBuffer=new Uint8Array(8),this.position=0,this.onClose=null==e?void 0:e.onClose,(null==e?void 0:e.abortSignal)&&e.abortSignal.addEventListener("abort",()=>{this.abort()})}async readToken(e,t=this.position){const r=new Uint8Array(e.len);if(await this.readBuffer(r,{position:t})<e.len)throw new ni;return e.get(r,0)}async peekToken(e,t=this.position){const r=new Uint8Array(e.len);if(await this.peekBuffer(r,{position:t})<e.len)throw new ni;return e.get(r,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new ni;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new ni;return e.get(this.numBuffer,0)}async ignore(e){if(void 0!==this.fileInfo.size){const t=this.fileInfo.size-this.position;if(e>t)return this.position+=t,t}return this.position+=e,e}async close(){var e;await this.abort(),await(null==(e=this.onClose)?void 0:e.call(this))}normalizeOptions(e,t){if(!this.supportsRandomAccess()&&t&&void 0!==t.position&&t.position<this.position)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");return{mayBeLess:!1,offset:0,length:e.length,position:this.position,...t}}abort(){return Promise.resolve()}}class di extends ui{constructor(e,t){super(t),this.streamReader=e,this.fileInfo=(null==t?void 0:t.fileInfo)??{}}async readBuffer(e,t){const r=this.normalizeOptions(e,t),i=r.position-this.position;if(i>0)return await this.ignore(i),this.readBuffer(e,t);if(i<0)throw new Error("`options.position` must be equal or greater than `tokenizer.position`");if(0===r.length)return 0;const n=await this.streamReader.read(e.subarray(0,r.length),r.mayBeLess);if(this.position+=n,(!t||!t.mayBeLess)&&n<r.length)throw new ni;return n}async peekBuffer(e,t){const r=this.normalizeOptions(e,t);let i=0;if(r.position){const t=r.position-this.position;if(t>0){const n=new Uint8Array(r.length+t);return i=await this.peekBuffer(n,{mayBeLess:r.mayBeLess}),e.set(n.subarray(t)),i-t}if(t<0)throw new Error("Cannot peek from a negative offset in a stream")}if(r.length>0){try{i=await this.streamReader.peek(e.subarray(0,r.length),r.mayBeLess)}catch(n){if((null==t?void 0:t.mayBeLess)&&n instanceof ni)return 0;throw n}if(!r.mayBeLess&&i<r.length)throw new ni}return i}async ignore(e){const t=Math.min(256e3,e),r=new Uint8Array(t);let i=0;for(;i<e;){const n=e-i,o=await this.readBuffer(r,{length:Math.min(t,n)});if(o<0)return o;i+=o}return i}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}}class pi extends ui{constructor(e,t){super(t),this.uint8Array=e,this.fileInfo={...(null==t?void 0:t.fileInfo)??{},size:e.length}}async readBuffer(e,t){(null==t?void 0:t.position)&&(this.position=t.position);const r=await this.peekBuffer(e,t);return this.position+=r,r}async peekBuffer(e,t){const r=this.normalizeOptions(e,t),i=Math.min(this.uint8Array.length-r.position,r.length);if(!r.mayBeLess&&i<r.length)throw new ni;return e.set(this.uint8Array.subarray(r.position,r.position+i)),i}close(){return super.close()}supportsRandomAccess(){return!0}setPosition(e){this.position=e}}function hi(e,t){const r=function(e){try{const t=e.getReader({mode:"byob"});return t instanceof ReadableStreamDefaultReader?new li(t):new ci(t)}catch(t){if(t instanceof TypeError)return new li(e.getReader());throw t}}(e),i=t??{},n=i.onClose;return i.onClose=async()=>{if(await r.close(),n)return n()},new di(r,i)}var gi=Uint8Array,mi=Uint16Array,fi=Int32Array,yi=new gi([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),bi=new gi([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),wi=new gi([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ii=function(e,t){for(var r=new mi(31),i=0;i<31;++i)r[i]=t+=1<<e[i-1];var n=new fi(r[30]);for(i=1;i<30;++i)for(var o=r[i];o<r[i+1];++o)n[o]=o-r[i]<<5|i;return{b:r,r:n}},Ti=Ii(yi,2),Si=Ti.b,ki=Ti.r;Si[28]=258,ki[258]=28;for(var vi=Ii(bi,0).b,Ei=new mi(32768),Ai=0;Ai<32768;++Ai){var Ci=(43690&Ai)>>1|(21845&Ai)<<1;Ci=(61680&(Ci=(52428&Ci)>>2|(13107&Ci)<<2))>>4|(3855&Ci)<<4,Ei[Ai]=((65280&Ci)>>8|(255&Ci)<<8)>>1}var Ri=function(e,t,r){for(var i=e.length,n=0,o=new mi(t);n<i;++n)e[n]&&++o[e[n]-1];var s,a=new mi(t);for(n=1;n<t;++n)a[n]=a[n-1]+o[n-1]<<1;s=new mi(1<<t);var c=15-t;for(n=0;n<i;++n)if(e[n])for(var l=n<<4|e[n],u=t-e[n],d=a[e[n]-1]++<<u,p=d|(1<<u)-1;d<=p;++d)s[Ei[d]>>c]=l;return s},xi=new gi(288);for(Ai=0;Ai<144;++Ai)xi[Ai]=8;for(Ai=144;Ai<256;++Ai)xi[Ai]=9;for(Ai=256;Ai<280;++Ai)xi[Ai]=7;for(Ai=280;Ai<288;++Ai)xi[Ai]=8;var Ni=new gi(32);for(Ai=0;Ai<32;++Ai)Ni[Ai]=5;var zi=Ri(xi,9),_i=Ri(Ni,5),Pi=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},Oi=function(e,t,r){var i=t/8|0;return(e[i]|e[i+1]<<8)>>(7&t)&r},Di=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},Fi=function(e){return(e+7)/8|0},Mi=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Ui=function(e,t,r){var i=new Error(t||Mi[e]);if(i.code=e,Error.captureStackTrace&&Error.captureStackTrace(i,Ui),!r)throw i;return i},Bi=function(e,t,r,i){var n=e.length;if(!n||t.f&&!t.l)return r||new gi(0);var o=!r,s=o||2!=t.i,a=t.i;o&&(r=new gi(3*n));var c=function(e){var t=r.length;if(e>t){var i=new gi(Math.max(2*t,e));i.set(r),r=i}},l=t.f||0,u=t.p||0,d=t.b||0,p=t.l,h=t.d,g=t.m,m=t.n,f=8*n;do{if(!p){l=Oi(e,u,1);var y=Oi(e,u+1,3);if(u+=3,!y){var b=e[(x=Fi(u)+4)-4]|e[x-3]<<8,w=x+b;if(w>n){a&&Ui(0);break}s&&c(d+b),r.set(e.subarray(x,w),d),t.b=d+=b,t.p=u=8*w,t.f=l;continue}if(1==y)p=zi,h=_i,g=9,m=5;else if(2==y){var I=Oi(e,u,31)+257,T=Oi(e,u+10,15)+4,S=I+Oi(e,u+5,31)+1;u+=14;for(var k=new gi(S),v=new gi(19),E=0;E<T;++E)v[wi[E]]=Oi(e,u+3*E,7);u+=3*T;var A=Pi(v),C=(1<<A)-1,R=Ri(v,A);for(E=0;E<S;){var x,N=R[Oi(e,u,C)];if(u+=15&N,(x=N>>4)<16)k[E++]=x;else{var z=0,_=0;for(16==x?(_=3+Oi(e,u,3),u+=2,z=k[E-1]):17==x?(_=3+Oi(e,u,7),u+=3):18==x&&(_=11+Oi(e,u,127),u+=7);_--;)k[E++]=z}}var P=k.subarray(0,I),O=k.subarray(I);g=Pi(P),m=Pi(O),p=Ri(P,g),h=Ri(O,m)}else Ui(1);if(u>f){a&&Ui(0);break}}s&&c(d+131072);for(var D=(1<<g)-1,F=(1<<m)-1,M=u;;M=u){var U=(z=p[Di(e,u)&D])>>4;if((u+=15&z)>f){a&&Ui(0);break}if(z||Ui(2),U<256)r[d++]=U;else{if(256==U){M=u,p=null;break}var B=U-254;if(U>264){var L=yi[E=U-257];B=Oi(e,u,(1<<L)-1)+Si[E],u+=L}var K=h[Di(e,u)&F],$=K>>4;K||Ui(3),u+=15&K;O=vi[$];if($>3){L=bi[$];O+=Di(e,u)&(1<<L)-1,u+=L}if(u>f){a&&Ui(0);break}s&&c(d+131072);var H=d+B;if(d<O){var q=0-O,j=Math.min(O,H);for(q+d<0&&Ui(3);d<j;++d)r[d]=i[q+d]}for(;d<H;++d)r[d]=r[d-O]}}t.l=p,t.p=M,t.b=d,t.f=l,p&&(l=1,t.m=g,t.d=h,t.n=m)}while(!l);return d!=r.length&&o?function(e,t,r){return(null==r||r>e.length)&&(r=e.length),new gi(e.subarray(t,r))}(r,0,d):r.subarray(0,d)},Li=new gi(0);function Ki(e,t){var r,i,n=function(e){31==e[0]&&139==e[1]&&8==e[2]||Ui(6,"invalid gzip data");var t=e[3],r=10;4&t&&(r+=2+(e[10]|e[11]<<8));for(var i=(t>>3&1)+(t>>4&1);i>0;i-=!e[r++]);return r+(2&t)}(e);return n+8>e.length&&Ui(6,"invalid gzip data"),Bi(e.subarray(n,-8),{i:2},new gi((i=(r=e).length,(r[i-4]|r[i-3]<<8|r[i-2]<<16|r[i-1]<<24)>>>0)),t)}function $i(e,t){return Bi(e.subarray(((8!=(15&(r=e)[0])||r[0]>>4>7||(r[0]<<8|r[1])%31)&&Ui(6,"invalid zlib data"),1==(r[1]>>5&1)&&Ui(6,"invalid zlib data: "+(32&r[1]?"need":"unexpected")+" dictionary"),2+(r[1]>>3&4)),-4),{i:2},t,t);var r}function Hi(e,t){return 31==e[0]&&139==e[1]&&8==e[2]?Ki(e,t):8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31?function(e,t){return Bi(e,{i:2},t,t)}(e,t):$i(e,t)}var qi="undefined"!=typeof TextDecoder&&new TextDecoder;try{qi.decode(Li,{stream:!0})}catch(zw){}var ji,Wi,Vi,Gi,Ji,Yi={exports:{}};function Xi(){if(Wi)return ji;Wi=1;var e=1e3,t=60*e,r=60*t,i=24*r,n=7*i,o=365.25*i;function s(e,t,r,i){var n=t>=1.5*r;return Math.round(e/r)+" "+i+(n?"s":"")}return ji=function(a,c){c=c||{};var l=typeof a;if("string"===l&&a.length>0)return function(s){if((s=String(s)).length>100)return;var a=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(s);if(!a)return;var c=parseFloat(a[1]);switch((a[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return c*o;case"weeks":case"week":case"w":return c*n;case"days":case"day":case"d":return c*i;case"hours":case"hour":case"hrs":case"hr":case"h":return c*r;case"minutes":case"minute":case"mins":case"min":case"m":return c*t;case"seconds":case"second":case"secs":case"sec":case"s":return c*e;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return c;default:return}}(a);if("number"===l&&isFinite(a))return c.long?function(n){var o=Math.abs(n);if(o>=i)return s(n,o,i,"day");if(o>=r)return s(n,o,r,"hour");if(o>=t)return s(n,o,t,"minute");if(o>=e)return s(n,o,e,"second");return n+" ms"}(a):function(n){var o=Math.abs(n);if(o>=i)return Math.round(n/i)+"d";if(o>=r)return Math.round(n/r)+"h";if(o>=t)return Math.round(n/t)+"m";if(o>=e)return Math.round(n/e)+"s";return n+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))}}var Zi=(Ji||(Ji=1,function(e,t){t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const r="color: "+this.color;t.splice(1,0,r,"color: inherit");let i=0,n=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(i++,"%c"===e&&(n=i))}),t.splice(n,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(r){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(r){}return!e&&void 0!==be&&"env"in be&&(e=be.env.DEBUG),e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.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"],t.log=console.debug||console.log||(()=>{}),e.exports=(Gi||(Gi=1,Vi=function(e){function t(e){let i,n,o,s=null;function a(...e){if(!a.enabled)return;const r=a,n=Number(new Date),o=n-(i||n);r.diff=o,r.prev=i,r.curr=n,i=n,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let s=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(i,n)=>{if("%%"===i)return"%";s++;const o=t.formatters[n];if("function"==typeof o){const t=e[s];i=o.call(r,t),e.splice(s,1),s--}return i}),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==s?s:(n!==t.namespaces&&(n=t.namespaces,o=t.enabled(e)),o),set:e=>{s=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,r){const i=t(this.namespace+(void 0===r?":":r)+e);return i.log=this.log,i}function i(e,t){let r=0,i=0,n=-1,o=0;for(;r<e.length;)if(i<t.length&&(t[i]===e[r]||"*"===t[i]))"*"===t[i]?(n=i,o=r,i++):(r++,i++);else{if(-1===n)return!1;i=n+1,o++,r=o}for(;i<t.length&&"*"===t[i];)i++;return i===t.length}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names,...t.skips.map(e=>"-"+e)].join(",");return t.enable(""),e},t.enable=function(e){t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const i of r)"-"===i[0]?t.skips.push(i.slice(1)):t.names.push(i)},t.enabled=function(e){for(const r of t.skips)if(i(e,r))return!1;for(const r of t.names)if(i(e,r))return!0;return!1},t.humanize=Xi(),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(r=>{t[r]=e[r]}),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e.charCodeAt(t),r|=0;return t.colors[Math.abs(r)%t.colors.length]},t.enable(t.load()),t}),Vi)(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}(Yi,Yi.exports)),Yi.exports);const Qi=Gr(Zi),en=67324752,tn=134695760,rn=33639248,nn=101010256,on={get:e=>(Xr.get(e,6),{signature:Qr.get(e,0),compressedSize:Qr.get(e,8),uncompressedSize:Qr.get(e,12)}),len:16},sn={get(e){const t=Xr.get(e,6);return{signature:Qr.get(e,0),minVersion:Xr.get(e,4),dataDescriptor:!!(8&t),compressedMethod:Xr.get(e,8),compressedSize:Qr.get(e,18),uncompressedSize:Qr.get(e,22),filenameLength:Xr.get(e,26),extraFieldLength:Xr.get(e,28),filename:null}},len:30},an={get:e=>({signature:Qr.get(e,0),nrOfThisDisk:Xr.get(e,4),nrOfThisDiskWithTheStart:Xr.get(e,6),nrOfEntriesOnThisDisk:Xr.get(e,8),nrOfEntriesOfSize:Xr.get(e,10),sizeOfCd:Qr.get(e,12),offsetOfStartOfCd:Qr.get(e,16),zipFileCommentLength:Xr.get(e,20)}),len:22},cn={get(e){const t=Xr.get(e,8);return{signature:Qr.get(e,0),minVersion:Xr.get(e,6),dataDescriptor:!!(8&t),compressedMethod:Xr.get(e,10),compressedSize:Qr.get(e,20),uncompressedSize:Qr.get(e,24),filenameLength:Xr.get(e,28),extraFieldLength:Xr.get(e,30),fileCommentLength:Xr.get(e,32),relativeOffsetOfLocalHeader:Qr.get(e,42),filename:null}},len:46};function ln(e){const t=new Uint8Array(Qr.len);return Qr.put(t,0,e),t}const un=Qi("tokenizer:inflate"),dn=262144,pn=ln(tn),hn=ln(nn);class gn{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(dn)}async isZip(){return await this.peekSignature()===en}peekSignature(){return this.tokenizer.peekToken(Qr)}async findEndOfCentralDirectoryLocator(){const e=this.tokenizer,t=Math.min(16384,e.fileInfo.size),r=this.syncBuffer.subarray(0,t);await this.tokenizer.readBuffer(r,{position:e.fileInfo.size-t});for(let i=r.length-4;i>=0;i--)if(r[i]===hn[0]&&r[i+1]===hn[1]&&r[i+2]===hn[2]&&r[i+3]===hn[3])return e.fileInfo.size-t+i;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess())return void un("Cannot reading central-directory without random-read support");un("Reading central-directory...");const e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){un("Central-directory 32-bit signature found");const r=await this.tokenizer.readToken(an,t),i=[];this.tokenizer.setPosition(r.offsetOfStartOfCd);for(let e=0;e<r.nrOfEntriesOfSize;++e){const t=await this.tokenizer.readToken(cn);if(t.signature!==rn)throw new Error("Expected Central-File-Header signature");t.filename=await this.tokenizer.readToken(new ii(t.filenameLength,"utf-8")),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),i.push(t),un(`Add central-directory file-entry: n=${e+1}/${i.length}: filename=${i[e].filename}`)}return this.tokenizer.setPosition(e),i}this.tokenizer.setPosition(e)}async unzip(e){const t=await this.readCentralDirectory();if(t)return this.iterateOverCentralDirectory(t,e);let r=!1;do{const t=await this.readLocalFileHeader();if(!t)break;const i=e(t);let n;if(r=!!i.stop,await this.tokenizer.ignore(t.extraFieldLength),t.dataDescriptor&&0===t.compressedSize){const e=[];let r=dn;un("Compressed-file-size unknown, scanning for next data-descriptor-signature....");let n=-1;for(;n<0&&r===dn;){r=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),n=mn(this.syncBuffer.subarray(0,r),pn);const t=n>=0?n:r;if(i.handler){const r=new Uint8Array(t);await this.tokenizer.readBuffer(r),e.push(r)}else await this.tokenizer.ignore(t)}un(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),i.handler&&await this.inflate(t,fn(e),i.handler)}else i.handler?(un(`Reading compressed-file-data: ${t.compressedSize} bytes`),n=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(n),await this.inflate(t,n,i.handler)):(un(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(un(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor){if(134695760!==(await this.tokenizer.readToken(on)).signature)throw new Error("Expected data-descriptor-signature at position "+(this.tokenizer.position-on.len))}}while(!r)}async iterateOverCentralDirectory(e,t){for(const r of e){const e=t(r);if(e.handler){this.tokenizer.setPosition(r.relativeOffsetOfLocalHeader);const t=await this.readLocalFileHeader();if(t){await this.tokenizer.ignore(t.extraFieldLength);const i=new Uint8Array(r.compressedSize);await this.tokenizer.readBuffer(i),await this.inflate(t,i,e.handler)}}if(e.stop)break}}inflate(e,t,r){if(0===e.compressedMethod)return r(t);un(`Decompress filename=${e.filename}, compressed-size=${t.length}`);return r(Hi(t))}async readLocalFileHeader(){const e=await this.tokenizer.peekToken(Qr);if(e===en){const e=await this.tokenizer.readToken(sn);return e.filename=await this.tokenizer.readToken(new ii(e.filenameLength,"utf-8")),e}if(e===rn)return!1;if(3759263696===e)throw new Error("Encrypted ZIP");throw new Error("Unexpected signature")}}function mn(e,t){const r=e.length,i=t.length;if(i>r)return-1;for(let n=0;n<=r-i;n++){let r=!0;for(let o=0;o<i;o++)if(e[n+o]!==t[o]){r=!1;break}if(r)return n}return-1}function fn(e){const t=e.reduce((e,t)=>e+t.length,0),r=new Uint8Array(t);let i=0;for(const n of e)r.set(n,i),i+=n.length;return r}function yn(e){const{byteLength:t}=e;return 6===t?e.getUint16(0)*2**32+e.getUint32(2):5===t?e.getUint8(0)*2**32+e.getUint32(1):4===t?e.getUint32(0):3===t?65536*e.getUint8(0)+e.getUint16(1):2===t?e.getUint16(0):1===t?e.getUint8(0):void 0}new globalThis.TextDecoder("utf8"),new globalThis.TextEncoder,Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));const bn={get:(e,t)=>127&e[t+3]|e[t+2]<<7|e[t+1]<<14|e[t]<<21,len:4},wn=4100;function In(e){switch(e=e.toLowerCase()){case"application/epub+zip":return{ext:"epub",mime:e};case"application/vnd.oasis.opendocument.text":return{ext:"odt",mime:e};case"application/vnd.oasis.opendocument.text-template":return{ext:"ott",mime:e};case"application/vnd.oasis.opendocument.spreadsheet":return{ext:"ods",mime:e};case"application/vnd.oasis.opendocument.spreadsheet-template":return{ext:"ots",mime:e};case"application/vnd.oasis.opendocument.presentation":return{ext:"odp",mime:e};case"application/vnd.oasis.opendocument.presentation-template":return{ext:"otp",mime:e};case"application/vnd.oasis.opendocument.graphics":return{ext:"odg",mime:e};case"application/vnd.oasis.opendocument.graphics-template":return{ext:"otg",mime:e};case"application/vnd.openxmlformats-officedocument.presentationml.slideshow":return{ext:"ppsx",mime:e};case"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":return{ext:"xlsx",mime:e};case"application/vnd.ms-excel.sheet.macroenabled":return{ext:"xlsm",mime:"application/vnd.ms-excel.sheet.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.spreadsheetml.template":return{ext:"xltx",mime:e};case"application/vnd.ms-excel.template.macroenabled":return{ext:"xltm",mime:"application/vnd.ms-excel.template.macroenabled.12"};case"application/vnd.ms-powerpoint.slideshow.macroenabled":return{ext:"ppsm",mime:"application/vnd.ms-powerpoint.slideshow.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.document":return{ext:"docx",mime:e};case"application/vnd.ms-word.document.macroenabled":return{ext:"docm",mime:"application/vnd.ms-word.document.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.wordprocessingml.template":return{ext:"dotx",mime:e};case"application/vnd.ms-word.template.macroenabledtemplate":return{ext:"dotm",mime:"application/vnd.ms-word.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.template":return{ext:"potx",mime:e};case"application/vnd.ms-powerpoint.template.macroenabled":return{ext:"potm",mime:"application/vnd.ms-powerpoint.template.macroenabled.12"};case"application/vnd.openxmlformats-officedocument.presentationml.presentation":return{ext:"pptx",mime:e};case"application/vnd.ms-powerpoint.presentation.macroenabled":return{ext:"pptm",mime:"application/vnd.ms-powerpoint.presentation.macroenabled.12"};case"application/vnd.ms-visio.drawing":return{ext:"vsdx",mime:"application/vnd.visio"};case"application/vnd.ms-package.3dmanufacturing-3dmodel+xml":return{ext:"3mf",mime:"model/3mf"}}}function Tn(e,t,r){r={offset:0,...r};for(const[i,n]of t.entries())if(r.mask){if(n!==(r.mask[i]&e[i+r.offset]))return!1}else if(n!==e[i+r.offset])return!1;return!0}class Sn{constructor(e){K(this,"detectConfident",async e=>{if(this.buffer=new Uint8Array(wn),void 0===e.fileInfo.size&&(e.fileInfo.size=Number.MAX_SAFE_INTEGER),this.tokenizer=e,await e.peekBuffer(this.buffer,{length:12,mayBeLess:!0}),this.check([66,77]))return{ext:"bmp",mime:"image/bmp"};if(this.check([11,119]))return{ext:"ac3",mime:"audio/vnd.dolby.dd-raw"};if(this.check([120,1]))return{ext:"dmg",mime:"application/x-apple-diskimage"};if(this.check([77,90]))return{ext:"exe",mime:"application/x-msdownload"};if(this.check([37,33]))return await e.peekBuffer(this.buffer,{length:24,mayBeLess:!0}),this.checkString("PS-Adobe-",{offset:2})&&this.checkString(" EPSF-",{offset:14})?{ext:"eps",mime:"application/eps"}:{ext:"ps",mime:"application/postscript"};if(this.check([31,160])||this.check([31,157]))return{ext:"Z",mime:"application/x-compress"};if(this.check([199,113]))return{ext:"cpio",mime:"application/x-cpio"};if(this.check([96,234]))return{ext:"arj",mime:"application/x-arj"};if(this.check([239,187,191]))return this.tokenizer.ignore(3),this.detectConfident(e);if(this.check([71,73,70]))return{ext:"gif",mime:"image/gif"};if(this.check([73,73,188]))return{ext:"jxr",mime:"image/vnd.ms-photo"};if(this.check([31,139,8]))return{ext:"gz",mime:"application/gzip"};if(this.check([66,90,104]))return{ext:"bz2",mime:"application/x-bzip2"};if(this.checkString("ID3")){await e.ignore(6);const t=await e.readToken(bn);return e.position+t>e.fileInfo.size?{ext:"mp3",mime:"audio/mpeg"}:(await e.ignore(t),this.fromTokenizer(e))}if(this.checkString("MP+"))return{ext:"mpc",mime:"audio/x-musepack"};if((67===this.buffer[0]||70===this.buffer[0])&&this.check([87,83],{offset:1}))return{ext:"swf",mime:"application/x-shockwave-flash"};if(this.check([255,216,255]))return this.check([247],{offset:3})?{ext:"jls",mime:"image/jls"}:{ext:"jpg",mime:"image/jpeg"};if(this.check([79,98,106,1]))return{ext:"avro",mime:"application/avro"};if(this.checkString("FLIF"))return{ext:"flif",mime:"image/flif"};if(this.checkString("8BPS"))return{ext:"psd",mime:"image/vnd.adobe.photoshop"};if(this.checkString("MPCK"))return{ext:"mpc",mime:"audio/x-musepack"};if(this.checkString("FORM"))return{ext:"aif",mime:"audio/aiff"};if(this.checkString("icns",{offset:0}))return{ext:"icns",mime:"image/icns"};if(this.check([80,75,3,4])){let r;return await new gn(e).unzip(e=>{switch(e.filename){case"META-INF/mozilla.rsa":return r={ext:"xpi",mime:"application/x-xpinstall"},{stop:!0};case"META-INF/MANIFEST.MF":return r={ext:"jar",mime:"application/java-archive"},{stop:!0};case"mimetype":return{async handler(e){const t=new TextDecoder("utf-8").decode(e).trim();r=In(t)},stop:!0};case"[Content_Types].xml":return{async handler(e){let t=new TextDecoder("utf-8").decode(e);const i=t.indexOf('.main+xml"');if(-1===i){const e="application/vnd.ms-package.3dmanufacturing-3dmodel+xml";t.includes(`ContentType="${e}"`)&&(r=In(e))}else{t=t.slice(0,Math.max(0,i));const e=t.lastIndexOf('"'),n=t.slice(Math.max(0,e+1));r=In(n)}},stop:!0};default:return/classes\d*\.dex/.test(e.filename)?(r={ext:"apk",mime:"application/vnd.android.package-archive"},{stop:!0}):{}}}),r??{ext:"zip",mime:"application/zip"}}if(this.checkString("OggS")){await e.ignore(28);const i=new Uint8Array(8);return await e.readBuffer(i),Tn(i,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/ogg; codecs=opus"}:Tn(i,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:Tn(i,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:Tn(i,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:Tn(i,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:Tn(i,[1,118,111,114,98,105,115])?{ext:"ogg",mime:"audio/ogg"}:{ext:"ogx",mime:"application/ogg"}}if(this.check([80,75])&&(3===this.buffer[2]||5===this.buffer[2]||7===this.buffer[2])&&(4===this.buffer[3]||6===this.buffer[3]||8===this.buffer[3]))return{ext:"zip",mime:"application/zip"};if(this.checkString("MThd"))return{ext:"mid",mime:"audio/midi"};if(this.checkString("wOFF")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff",mime:"font/woff"};if(this.checkString("wOF2")&&(this.check([0,1,0,0],{offset:4})||this.checkString("OTTO",{offset:4})))return{ext:"woff2",mime:"font/woff2"};if(this.check([212,195,178,161])||this.check([161,178,195,212]))return{ext:"pcap",mime:"application/vnd.tcpdump.pcap"};if(this.checkString("DSD "))return{ext:"dsf",mime:"audio/x-dsf"};if(this.checkString("LZIP"))return{ext:"lz",mime:"application/x-lzip"};if(this.checkString("fLaC"))return{ext:"flac",mime:"audio/flac"};if(this.check([66,80,71,251]))return{ext:"bpg",mime:"image/bpg"};if(this.checkString("wvpk"))return{ext:"wv",mime:"audio/wavpack"};if(this.checkString("%PDF"))return{ext:"pdf",mime:"application/pdf"};if(this.check([0,97,115,109]))return{ext:"wasm",mime:"application/wasm"};if(this.check([73,73])){const n=await this.readTiffHeader(!1);if(n)return n}if(this.check([77,77])){const o=await this.readTiffHeader(!0);if(o)return o}if(this.checkString("MAC "))return{ext:"ape",mime:"audio/ape"};if(this.check([26,69,223,163])){async function s(){const t=await e.peekNumber(Yr);let r=128,i=0;for(;0===(t&r)&&0!==r;)++i,r>>=1;const n=new Uint8Array(i+1);return await e.readBuffer(n),n}async function a(){const e=await s(),t=await s();t[0]^=128>>t.length-1;const r=Math.min(6,t.length),i=new DataView(e.buffer),n=new DataView(t.buffer,t.length-r,r);return{id:yn(i),len:yn(n)}}async function c(t){for(;t>0;){const r=await a();if(17026===r.id){return(await e.readToken(new ii(r.len))).replaceAll(/\00.*$/g,"")}await e.ignore(r.len),--t}}const l=await a();switch(await c(l.len)){case"webm":return{ext:"webm",mime:"video/webm"};case"matroska":return{ext:"mkv",mime:"video/matroska"};default:return}}if(this.checkString("SQLi"))return{ext:"sqlite",mime:"application/x-sqlite3"};if(this.check([78,69,83,26]))return{ext:"nes",mime:"application/x-nintendo-nes-rom"};if(this.checkString("Cr24"))return{ext:"crx",mime:"application/x-google-chrome-extension"};if(this.checkString("MSCF")||this.checkString("ISc("))return{ext:"cab",mime:"application/vnd.ms-cab-compressed"};if(this.check([237,171,238,219]))return{ext:"rpm",mime:"application/x-rpm"};if(this.check([197,208,211,198]))return{ext:"eps",mime:"application/eps"};if(this.check([40,181,47,253]))return{ext:"zst",mime:"application/zstd"};if(this.check([127,69,76,70]))return{ext:"elf",mime:"application/x-elf"};if(this.check([33,66,68,78]))return{ext:"pst",mime:"application/vnd.ms-outlook"};if(this.checkString("PAR1")||this.checkString("PARE"))return{ext:"parquet",mime:"application/vnd.apache.parquet"};if(this.checkString("ttcf"))return{ext:"ttc",mime:"font/collection"};if(this.check([207,250,237,254]))return{ext:"macho",mime:"application/x-mach-binary"};if(this.check([4,34,77,24]))return{ext:"lz4",mime:"application/x-lz4"};if(this.check([79,84,84,79,0]))return{ext:"otf",mime:"font/otf"};if(this.checkString("#!AMR"))return{ext:"amr",mime:"audio/amr"};if(this.checkString("{\\rtf"))return{ext:"rtf",mime:"application/rtf"};if(this.check([70,76,86,1]))return{ext:"flv",mime:"video/x-flv"};if(this.checkString("IMPM"))return{ext:"it",mime:"audio/x-it"};if(this.checkString("-lh0-",{offset:2})||this.checkString("-lh1-",{offset:2})||this.checkString("-lh2-",{offset:2})||this.checkString("-lh3-",{offset:2})||this.checkString("-lh4-",{offset:2})||this.checkString("-lh5-",{offset:2})||this.checkString("-lh6-",{offset:2})||this.checkString("-lh7-",{offset:2})||this.checkString("-lzs-",{offset:2})||this.checkString("-lz4-",{offset:2})||this.checkString("-lz5-",{offset:2})||this.checkString("-lhd-",{offset:2}))return{ext:"lzh",mime:"application/x-lzh-compressed"};if(this.check([0,0,1,186])){if(this.check([33],{offset:4,mask:[241]}))return{ext:"mpg",mime:"video/MP1S"};if(this.check([68],{offset:4,mask:[196]}))return{ext:"mpg",mime:"video/MP2P"}}if(this.checkString("ITSF"))return{ext:"chm",mime:"application/vnd.ms-htmlhelp"};if(this.check([202,254,186,190]))return{ext:"class",mime:"application/java-vm"};if(this.checkString(".RMF"))return{ext:"rm",mime:"application/vnd.rn-realmedia"};if(this.checkString("DRACO"))return{ext:"drc",mime:"application/vnd.google.draco"};if(this.check([253,55,122,88,90,0]))return{ext:"xz",mime:"application/x-xz"};if(this.checkString("<?xml "))return{ext:"xml",mime:"application/xml"};if(this.check([55,122,188,175,39,28]))return{ext:"7z",mime:"application/x-7z-compressed"};if(this.check([82,97,114,33,26,7])&&(0===this.buffer[6]||1===this.buffer[6]))return{ext:"rar",mime:"application/x-rar-compressed"};if(this.checkString("solid "))return{ext:"stl",mime:"model/stl"};if(this.checkString("AC")){const u=new ii(4,"latin1").get(this.buffer,2);if(u.match("^d*")&&u>=1e3&&u<=1050)return{ext:"dwg",mime:"image/vnd.dwg"}}if(this.checkString("070707"))return{ext:"cpio",mime:"application/x-cpio"};if(this.checkString("BLENDER"))return{ext:"blend",mime:"application/x-blender"};if(this.checkString("!<arch>")){await e.ignore(8);return"debian-binary"===await e.readToken(new ii(13,"ascii"))?{ext:"deb",mime:"application/x-deb"}:{ext:"ar",mime:"application/x-unix-archive"}}if(this.checkString("WEBVTT")&&["\n","\r","\t"," ","\0"].some(e=>this.checkString(e,{offset:6})))return{ext:"vtt",mime:"text/vtt"};if(this.check([137,80,78,71,13,10,26,10])){async function d(){return{length:await e.readToken(ti),type:await e.readToken(new ii(4,"latin1"))}}await e.ignore(8);do{const p=await d();if(p.length<0)return;switch(p.type){case"IDAT":return{ext:"png",mime:"image/png"};case"acTL":return{ext:"apng",mime:"image/apng"};default:await e.ignore(p.length+4)}}while(e.position+8<e.fileInfo.size);return{ext:"png",mime:"image/png"}}if(this.check([65,82,82,79,87,49,0,0]))return{ext:"arrow",mime:"application/vnd.apache.arrow.file"};if(this.check([103,108,84,70,2,0,0,0]))return{ext:"glb",mime:"model/gltf-binary"};if(this.check([102,114,101,101],{offset:4})||this.check([109,100,97,116],{offset:4})||this.check([109,111,111,118],{offset:4})||this.check([119,105,100,101],{offset:4}))return{ext:"mov",mime:"video/quicktime"};if(this.check([73,73,82,79,8,0,0,0,24]))return{ext:"orf",mime:"image/x-olympus-orf"};if(this.checkString("gimp xcf "))return{ext:"xcf",mime:"image/x-xcf"};if(this.checkString("ftyp",{offset:4})&&96&this.buffer[8]){const h=new ii(4,"latin1").get(this.buffer,8).replace("\0"," ").trim();switch(h){case"avif":case"avis":return{ext:"avif",mime:"image/avif"};case"mif1":return{ext:"heic",mime:"image/heif"};case"msf1":return{ext:"heic",mime:"image/heif-sequence"};case"heic":case"heix":return{ext:"heic",mime:"image/heic"};case"hevc":case"hevx":return{ext:"heic",mime:"image/heic-sequence"};case"qt":return{ext:"mov",mime:"video/quicktime"};case"M4V":case"M4VH":case"M4VP":return{ext:"m4v",mime:"video/x-m4v"};case"M4P":return{ext:"m4p",mime:"video/mp4"};case"M4B":return{ext:"m4b",mime:"audio/mp4"};case"M4A":return{ext:"m4a",mime:"audio/x-m4a"};case"F4V":return{ext:"f4v",mime:"video/mp4"};case"F4P":return{ext:"f4p",mime:"video/mp4"};case"F4A":return{ext:"f4a",mime:"audio/mp4"};case"F4B":return{ext:"f4b",mime:"audio/mp4"};case"crx":return{ext:"cr3",mime:"image/x-canon-cr3"};default:return h.startsWith("3g")?h.startsWith("3g2")?{ext:"3g2",mime:"video/3gpp2"}:{ext:"3gp",mime:"video/3gpp"}:{ext:"mp4",mime:"video/mp4"}}}if(this.check([82,73,70,70])){if(this.checkString("WEBP",{offset:8}))return{ext:"webp",mime:"image/webp"};if(this.check([65,86,73],{offset:8}))return{ext:"avi",mime:"video/vnd.avi"};if(this.check([87,65,86,69],{offset:8}))return{ext:"wav",mime:"audio/wav"};if(this.check([81,76,67,77],{offset:8}))return{ext:"qcp",mime:"audio/qcelp"}}if(this.check([73,73,85,0,24,0,0,0,136,231,116,216]))return{ext:"rw2",mime:"image/x-panasonic-rw2"};if(this.check([48,38,178,117,142,102,207,17,166,217])){async function g(){const t=new Uint8Array(16);return await e.readBuffer(t),{id:t,size:Number(await e.readToken(ri))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){const m=await g();let f=m.size-24;if(Tn(m.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){const y=new Uint8Array(16);if(f-=await e.readBuffer(y),Tn(y,[64,158,105,248,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"audio/x-ms-asf"};if(Tn(y,[192,239,25,188,77,91,207,17,168,253,0,128,95,92,68,43]))return{ext:"asf",mime:"video/x-ms-asf"};break}await e.ignore(f)}return{ext:"asf",mime:"application/vnd.ms-asf"}}if(this.check([171,75,84,88,32,49,49,187,13,10,26,10]))return{ext:"ktx",mime:"image/ktx"};if((this.check([126,16,4])||this.check([126,24,4]))&&this.check([48,77,73,69],{offset:4}))return{ext:"mie",mime:"application/x-mie"};if(this.check([39,10,0,0,0,0,0,0,0,0,0,0],{offset:2}))return{ext:"shp",mime:"application/x-esri-shape"};if(this.check([255,79,255,81]))return{ext:"j2c",mime:"image/j2c"};if(this.check([0,0,0,12,106,80,32,32,13,10,135,10])){await e.ignore(20);switch(await e.readToken(new ii(4,"ascii"))){case"jp2 ":return{ext:"jp2",mime:"image/jp2"};case"jpx ":return{ext:"jpx",mime:"image/jpx"};case"jpm ":return{ext:"jpm",mime:"image/jpm"};case"mjp2":return{ext:"mj2",mime:"image/mj2"};default:return}}if(this.check([255,10])||this.check([0,0,0,12,74,88,76,32,13,10,135,10]))return{ext:"jxl",mime:"image/jxl"};if(this.check([254,255]))return this.check([0,60,0,63,0,120,0,109,0,108],{offset:2})?{ext:"xml",mime:"application/xml"}:void 0;if(this.check([208,207,17,224,161,177,26,225]))return{ext:"cfb",mime:"application/x-cfb"};if(await e.peekBuffer(this.buffer,{length:Math.min(256,e.fileInfo.size),mayBeLess:!0}),this.check([97,99,115,112],{offset:36}))return{ext:"icc",mime:"application/vnd.iccprofile"};if(this.checkString("**ACE",{offset:7})&&this.checkString("**",{offset:12}))return{ext:"ace",mime:"application/x-ace-compressed"};if(this.checkString("BEGIN:")){if(this.checkString("VCARD",{offset:6}))return{ext:"vcf",mime:"text/vcard"};if(this.checkString("VCALENDAR",{offset:6}))return{ext:"ics",mime:"text/calendar"}}if(this.checkString("FUJIFILMCCD-RAW"))return{ext:"raf",mime:"image/x-fujifilm-raf"};if(this.checkString("Extended Module:"))return{ext:"xm",mime:"audio/x-xm"};if(this.checkString("Creative Voice File"))return{ext:"voc",mime:"audio/x-voc"};if(this.check([4,0,0,0])&&this.buffer.length>=16){const b=new DataView(this.buffer.buffer).getUint32(12,!0);if(b>12&&this.buffer.length>=b+16)try{const w=(new TextDecoder).decode(this.buffer.subarray(16,b+16));if(JSON.parse(w).files)return{ext:"asar",mime:"application/x-asar"}}catch{}}return this.check([6,14,43,52,2,5,1,1,13,1,2,1,1,2])?{ext:"mxf",mime:"application/mxf"}:this.checkString("SCRM",{offset:44})?{ext:"s3m",mime:"audio/x-s3m"}:this.check([71])&&this.check([71],{offset:188})||this.check([71],{offset:4})&&this.check([71],{offset:196})?{ext:"mts",mime:"video/mp2t"}:this.check([66,79,79,75,77,79,66,73],{offset:60})?{ext:"mobi",mime:"application/x-mobipocket-ebook"}:this.check([68,73,67,77],{offset:128})?{ext:"dcm",mime:"application/dicom"}:this.check([76,0,0,0,1,20,2,0,0,0,0,0,192,0,0,0,0,0,0,70])?{ext:"lnk",mime:"application/x.ms.shortcut"}:this.check([98,111,111,107,0,0,0,0,109,97,114,107,0,0,0,0])?{ext:"alias",mime:"application/x.apple.alias"}:this.checkString("Kaydara FBX Binary \0")?{ext:"fbx",mime:"application/x.autodesk.fbx"}:this.check([76,80],{offset:34})&&(this.check([0,0,1],{offset:8})||this.check([1,0,2],{offset:8})||this.check([2,0,2],{offset:8}))?{ext:"eot",mime:"application/vnd.ms-fontobject"}:this.check([6,6,237,245,216,29,70,229,189,49,239,231,254,116,183,29])?{ext:"indd",mime:"application/x-indesign"}:(await e.peekBuffer(this.buffer,{length:Math.min(512,e.fileInfo.size),mayBeLess:!0}),this.checkString("ustar",{offset:257})&&(this.checkString("\0",{offset:262})||this.checkString(" ",{offset:262}))||this.check([0,0,0,0,0,0],{offset:257})&&function(e,t=0){const r=Number.parseInt(new ii(6).get(e,148).replace(/\0.*$/,"").trim(),8);if(Number.isNaN(r))return!1;let i=256;for(let n=t;n<t+148;n++)i+=e[n];for(let n=t+156;n<t+512;n++)i+=e[n];return r===i}(this.buffer)?{ext:"tar",mime:"application/x-tar"}:this.check([255,254])?this.check([60,0,63,0,120,0,109,0,108,0],{offset:2})?{ext:"xml",mime:"application/xml"}:this.check([255,14,83,0,107,0,101,0,116,0,99,0,104,0,85,0,112,0,32,0,77,0,111,0,100,0,101,0,108,0],{offset:2})?{ext:"skp",mime:"application/vnd.sketchup.skp"}:void 0:this.checkString("-----BEGIN PGP MESSAGE-----")?{ext:"pgp",mime:"application/pgp-encrypted"}:void 0)}),K(this,"detectImprecise",async e=>{if(this.buffer=new Uint8Array(wn),await e.peekBuffer(this.buffer,{length:Math.min(8,e.fileInfo.size),mayBeLess:!0}),this.check([0,0,1,186])||this.check([0,0,1,179]))return{ext:"mpg",mime:"video/mpeg"};if(this.check([0,1,0,0,0]))return{ext:"ttf",mime:"font/ttf"};if(this.check([0,0,1,0]))return{ext:"ico",mime:"image/x-icon"};if(this.check([0,0,2,0]))return{ext:"cur",mime:"image/x-icon"};if(await e.peekBuffer(this.buffer,{length:Math.min(2+this.options.mpegOffsetTolerance,e.fileInfo.size),mayBeLess:!0}),this.buffer.length>=2+this.options.mpegOffsetTolerance)for(let t=0;t<=this.options.mpegOffsetTolerance;++t){const e=this.scanMpeg(t);if(e)return e}}),this.options={mpegOffsetTolerance:0,...e},this.detectors=[...(null==e?void 0:e.customDetectors)??[],{id:"core",detect:this.detectConfident},{id:"core.imprecise",detect:this.detectImprecise}],this.tokenizerOptions={abortSignal:null==e?void 0:e.signal}}async fromTokenizer(e){const t=e.position;for(const r of this.detectors){const i=await r.detect(e);if(i)return i;if(t!==e.position)return}}async fromBuffer(e){if(!(e instanceof Uint8Array||e instanceof ArrayBuffer))throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof e}\``);const t=e instanceof Uint8Array?e:new Uint8Array(e);var r,i;if((null==t?void 0:t.length)>1)return this.fromTokenizer((r=t,i=this.tokenizerOptions,new pi(r,i)))}async fromBlob(e){return this.fromStream(e.stream())}async fromStream(e){const t=await hi(e,this.tokenizerOptions);try{return await this.fromTokenizer(t)}finally{await t.close()}}async toDetectionStream(e,t){const{sampleSize:r=wn}=t;let i,n;const o=e.getReader({mode:"byob"});try{const{value:e,done:t}=await o.read(new Uint8Array(r));if(n=e,!t&&e)try{i=await this.fromBuffer(e.subarray(0,r))}catch(c){if(!(c instanceof ni))throw c;i=void 0}n=e}finally{o.releaseLock()}const s=new TransformStream({async start(e){e.enqueue(n)},transform(e,t){t.enqueue(e)}}),a=e.pipeThrough(s);return a.fileType=i,a}check(e,t){return Tn(this.buffer,e,t)}checkString(e,t){return this.check((r=e,[...r].map(e=>e.charCodeAt(0))),t);var r}async readTiffTag(e){const t=await this.tokenizer.readToken(e?Zr:Xr);switch(this.tokenizer.ignore(10),t){case 50341:return{ext:"arw",mime:"image/x-sony-arw"};case 50706:return{ext:"dng",mime:"image/x-adobe-dng"}}}async readTiffIFD(e){const t=await this.tokenizer.readToken(e?Zr:Xr);for(let r=0;r<t;++r){const t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){const t=(e?Zr:Xr).get(this.buffer,2),r=(e?ei:Qr).get(this.buffer,4);if(42===t){if(r>=6){if(this.checkString("CR",{offset:8}))return{ext:"cr2",mime:"image/x-canon-cr2"};if(r>=8){const t=(e?Zr:Xr).get(this.buffer,8),r=(e?Zr:Xr).get(this.buffer,10);if(28===t&&254===r||31===t&&11===r)return{ext:"nef",mime:"image/x-nikon-nef"}}}await this.tokenizer.ignore(r);return await this.readTiffIFD(e)??{ext:"tif",mime:"image/tiff"}}if(43===t)return{ext:"tif",mime:"image/tiff"}}scanMpeg(e){if(this.check([255,224],{offset:e,mask:[255,224]})){if(this.check([16],{offset:e+1,mask:[22]}))return this.check([8],{offset:e+1,mask:[8]}),{ext:"aac",mime:"audio/aac"};if(this.check([2],{offset:e+1,mask:[6]}))return{ext:"mp3",mime:"audio/mpeg"};if(this.check([4],{offset:e+1,mask:[6]}))return{ext:"mp2",mime:"audio/mpeg"};if(this.check([6],{offset:e+1,mask:[6]}))return{ext:"mp1",mime:"audio/mpeg"}}}}new Set(["jpg","png","apng","gif","webp","flif","xcf","cr2","cr3","orf","arw","dng","nef","rw2","raf","tif","bmp","icns","jxr","psd","indd","zip","tar","rar","gz","bz2","7z","dmg","mp4","mid","mkv","webm","mov","avi","mpg","mp2","mp3","m4a","oga","ogg","ogv","opus","flac","wav","spx","amr","pdf","epub","elf","macho","exe","swf","rtf","wasm","woff","woff2","eot","ttf","otf","ttc","ico","flv","ps","xz","sqlite","nes","crx","xpi","cab","deb","ar","rpm","Z","lz","cfb","mxf","mts","blend","bpg","docx","pptx","xlsx","3gp","3g2","j2c","jp2","jpm","jpx","mj2","aif","qcp","odt","ods","odp","xml","mobi","heic","cur","ktx","ape","wv","dcm","ics","glb","pcap","dsf","lnk","alias","voc","ac3","m4v","m4p","m4b","f4v","f4p","f4b","f4a","mie","asf","ogm","ogx","mpc","arrow","shp","aac","mp1","it","s3m","xm","skp","avif","eps","lzh","pgp","asar","stl","chm","3mf","zst","jxl","vcf","jls","pst","dwg","parquet","class","arj","cpio","ace","avro","icc","fbx","vsdx","vtt","apk","drc","lz4","potx","xltx","dotx","xltm","ott","ots","otp","odg","otg","xlsm","docm","dotm","potm","pptm","jar","rm","ppsm","ppsx"]),new Set(["image/jpeg","image/png","image/gif","image/webp","image/flif","image/x-xcf","image/x-canon-cr2","image/x-canon-cr3","image/tiff","image/bmp","image/vnd.ms-photo","image/vnd.adobe.photoshop","application/x-indesign","application/epub+zip","application/x-xpinstall","application/vnd.ms-powerpoint.slideshow.macroenabled.12","application/vnd.oasis.opendocument.text","application/vnd.oasis.opendocument.spreadsheet","application/vnd.oasis.opendocument.presentation","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/vnd.openxmlformats-officedocument.presentationml.slideshow","application/zip","application/x-tar","application/x-rar-compressed","application/gzip","application/x-bzip2","application/x-7z-compressed","application/x-apple-diskimage","application/vnd.apache.arrow.file","video/mp4","audio/midi","video/matroska","video/webm","video/quicktime","video/vnd.avi","audio/wav","audio/qcelp","audio/x-ms-asf","video/x-ms-asf","application/vnd.ms-asf","video/mpeg","video/3gpp","audio/mpeg","audio/mp4","video/ogg","audio/ogg","audio/ogg; codecs=opus","application/ogg","audio/flac","audio/ape","audio/wavpack","audio/amr","application/pdf","application/x-elf","application/x-mach-binary","application/x-msdownload","application/x-shockwave-flash","application/rtf","application/wasm","font/woff","font/woff2","application/vnd.ms-fontobject","font/ttf","font/otf","font/collection","image/x-icon","video/x-flv","application/postscript","application/eps","application/x-xz","application/x-sqlite3","application/x-nintendo-nes-rom","application/x-google-chrome-extension","application/vnd.ms-cab-compressed","application/x-deb","application/x-unix-archive","application/x-rpm","application/x-compress","application/x-lzip","application/x-cfb","application/x-mie","application/mxf","video/mp2t","application/x-blender","image/bpg","image/j2c","image/jp2","image/jpx","image/jpm","image/mj2","audio/aiff","application/xml","application/x-mobipocket-ebook","image/heif","image/heif-sequence","image/heic","image/heic-sequence","image/icns","image/ktx","application/dicom","audio/x-musepack","text/calendar","text/vcard","text/vtt","model/gltf-binary","application/vnd.tcpdump.pcap","audio/x-dsf","application/x.ms.shortcut","application/x.apple.alias","audio/x-voc","audio/vnd.dolby.dd-raw","audio/x-m4a","image/apng","image/x-olympus-orf","image/x-sony-arw","image/x-adobe-dng","image/x-nikon-nef","image/x-panasonic-rw2","image/x-fujifilm-raf","video/x-m4v","video/3gpp2","application/x-esri-shape","audio/aac","audio/x-it","audio/x-s3m","audio/x-xm","video/MP1S","video/MP2P","application/vnd.sketchup.skp","image/avif","application/x-lzh-compressed","application/pgp-encrypted","application/x-asar","model/stl","application/vnd.ms-htmlhelp","model/3mf","image/jxl","application/zstd","image/jls","application/vnd.ms-outlook","image/vnd.dwg","application/vnd.apache.parquet","application/java-vm","application/x-arj","application/x-cpio","application/x-ace-compressed","application/avro","application/vnd.iccprofile","application/x.autodesk.fbx","application/vnd.visio","application/vnd.android.package-archive","application/vnd.google.draco","application/x-lz4","application/vnd.openxmlformats-officedocument.presentationml.template","application/vnd.openxmlformats-officedocument.spreadsheetml.template","application/vnd.openxmlformats-officedocument.wordprocessingml.template","application/vnd.ms-excel.template.macroenabled.12","application/vnd.oasis.opendocument.text-template","application/vnd.oasis.opendocument.spreadsheet-template","application/vnd.oasis.opendocument.presentation-template","application/vnd.oasis.opendocument.graphics","application/vnd.oasis.opendocument.graphics-template","application/vnd.ms-excel.sheet.macroenabled.12","application/vnd.ms-word.document.macroenabled.12","application/vnd.ms-word.template.macroenabled.12","application/vnd.ms-powerpoint.template.macroenabled.12","application/vnd.ms-powerpoint.presentation.macroenabled.12","application/java-archive","application/vnd.rn-realmedia"]);const kn=Object.create(null);kn.open="0",kn.close="1",kn.ping="2",kn.pong="3",kn.message="4",kn.upgrade="5",kn.noop="6";const vn=Object.create(null);Object.keys(kn).forEach(e=>{vn[kn[e]]=e});const En={type:"error",data:"parser error"},An="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),Cn="function"==typeof ArrayBuffer,Rn=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,xn=({type:e,data:t},r,i)=>An&&t instanceof Blob?r?i(t):Nn(t,i):Cn&&(t instanceof ArrayBuffer||Rn(t))?r?i(t):Nn(new Blob([t]),i):i(kn[e]+(t||"")),Nn=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+(e||""))},r.readAsDataURL(e)};function zn(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let _n;const Pn="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",On="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let Pw=0;Pw<64;Pw++)On[Pn.charCodeAt(Pw)]=Pw;const Dn="function"==typeof ArrayBuffer,Fn=(e,t)=>{if("string"!=typeof e)return{type:"message",data:Un(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:Mn(e.substring(1),t)};return vn[r]?e.length>1?{type:vn[r],data:e.substring(1)}:{type:vn[r]}:En},Mn=(e,t)=>{if(Dn){const r=(e=>{let t,r,i,n,o,s=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(s--,"="===e[e.length-2]&&s--);const l=new ArrayBuffer(s),u=new Uint8Array(l);for(t=0;t<a;t+=4)r=On[e.charCodeAt(t)],i=On[e.charCodeAt(t+1)],n=On[e.charCodeAt(t+2)],o=On[e.charCodeAt(t+3)],u[c++]=r<<2|i>>4,u[c++]=(15&i)<<4|n>>2,u[c++]=(3&n)<<6|63&o;return l})(e);return Un(r,t)}return{base64:!0,data:e}},Un=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,Bn=String.fromCharCode(30);function Ln(){return new TransformStream({transform(e,t){!function(e,t){An&&e.data instanceof Blob?e.data.arrayBuffer().then(zn).then(t):Cn&&(e.data instanceof ArrayBuffer||Rn(e.data))?t(zn(e.data)):xn(e,!1,e=>{_n||(_n=new TextEncoder),t(_n.encode(e))})}(e,r=>{const i=r.length;let n;if(i<126)n=new Uint8Array(1),new DataView(n.buffer).setUint8(0,i);else if(i<65536){n=new Uint8Array(3);const e=new DataView(n.buffer);e.setUint8(0,126),e.setUint16(1,i)}else{n=new Uint8Array(9);const e=new DataView(n.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(i))}e.data&&"string"!=typeof e.data&&(n[0]|=128),t.enqueue(n),t.enqueue(r)})}})}let Kn;function $n(e){return e.reduce((e,t)=>e+t.length,0)}function Hn(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let i=0;for(let n=0;n<t;n++)r[n]=e[0][i++],i===e[0].length&&(e.shift(),i=0);return e.length&&i<e[0].length&&(e[0]=e[0].slice(i)),r}function qn(e){if(e)return function(e){for(var t in qn.prototype)e[t]=qn.prototype[t];return e}(e)}qn.prototype.on=qn.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},qn.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},qn.prototype.off=qn.prototype.removeListener=qn.prototype.removeAllListeners=qn.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var r,i=this._callbacks["$"+e];if(!i)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var n=0;n<i.length;n++)if((r=i[n])===t||r.fn===t){i.splice(n,1);break}return 0===i.length&&delete this._callbacks["$"+e],this},qn.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),r=this._callbacks["$"+e],i=1;i<arguments.length;i++)t[i-1]=arguments[i];if(r){i=0;for(var n=(r=r.slice(0)).length;i<n;++i)r[i].apply(this,t)}return this},qn.prototype.emitReserved=qn.prototype.emit,qn.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},qn.prototype.hasListeners=function(e){return!!this.listeners(e).length};const jn="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),Wn="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function Vn(e,...t){return t.reduce((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t),{})}const Gn=Wn.setTimeout,Jn=Wn.clearTimeout;function Yn(e,t){t.useNativeTimers?(e.setTimeoutFn=Gn.bind(Wn),e.clearTimeoutFn=Jn.bind(Wn)):(e.setTimeoutFn=Wn.setTimeout.bind(Wn),e.clearTimeoutFn=Wn.clearTimeout.bind(Wn))}function Xn(e){return"string"==typeof e?function(e){let t=0,r=0;for(let i=0,n=e.length;i<n;i++)t=e.charCodeAt(i),t<128?r+=1:t<2048?r+=2:t<55296||t>=57344?r+=3:(i++,r+=4);return r}(e):Math.ceil(1.33*(e.byteLength||e.size))}function Zn(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class Qn extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class eo extends qn{constructor(e){super(),this.writable=!1,Yn(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,r){return super.emitReserved("error",new Qn(e,t,r)),this}open(){return this.readyState="opening",this.doOpen(),this}close(){return"opening"!==this.readyState&&"open"!==this.readyState||(this.doClose(),this.onClose()),this}send(e){"open"===this.readyState&&this.write(e)}onOpen(){this.readyState="open",this.writable=!0,super.emitReserved("open")}onData(e){const t=Fn(e,this.socket.binaryType);this.onPacket(t)}onPacket(e){super.emitReserved("packet",e)}onClose(e){this.readyState="closed",super.emitReserved("close",e)}pause(e){}createUri(e,t={}){return e+"://"+this._hostname()+this._port()+this.opts.path+this._query(t)}_hostname(){const e=this.opts.hostname;return-1===e.indexOf(":")?e:"["+e+"]"}_port(){return this.opts.port&&(this.opts.secure&&Number(443!==this.opts.port)||!this.opts.secure&&80!==Number(this.opts.port))?":"+this.opts.port:""}_query(e){const t=function(e){let t="";for(let r in e)e.hasOwnProperty(r)&&(t.length&&(t+="&"),t+=encodeURIComponent(r)+"="+encodeURIComponent(e[r]));return t}(e);return t.length?"?"+t:""}}class to extends eo{constructor(){super(...arguments),this._polling=!1}get name(){return"polling"}doOpen(){this._poll()}pause(e){this.readyState="pausing";const t=()=>{this.readyState="paused",e()};if(this._polling||!this.writable){let e=0;this._polling&&(e++,this.once("pollComplete",function(){--e||t()})),this.writable||(e++,this.once("drain",function(){--e||t()}))}else t()}_poll(){this._polling=!0,this.doPoll(),this.emitReserved("poll")}onData(e){((e,t)=>{const r=e.split(Bn),i=[];for(let n=0;n<r.length;n++){const e=Fn(r[n],t);if(i.push(e),"error"===e.type)break}return i})(e,this.socket.binaryType).forEach(e=>{if("opening"===this.readyState&&"open"===e.type&&this.onOpen(),"close"===e.type)return this.onClose({description:"transport closed by the server"}),!1;this.onPacket(e)}),"closed"!==this.readyState&&(this._polling=!1,this.emitReserved("pollComplete"),"open"===this.readyState&&this._poll())}doClose(){const e=()=>{this.write([{type:"close"}])};"open"===this.readyState?e():this.once("open",e)}write(e){this.writable=!1,((e,t)=>{const r=e.length,i=new Array(r);let n=0;e.forEach((e,o)=>{xn(e,!1,e=>{i[o]=e,++n===r&&t(i.join(Bn))})})})(e,e=>{this.doWrite(e,()=>{this.writable=!0,this.emitReserved("drain")})})}uri(){const e=this.opts.secure?"https":"http",t=this.query||{};return!1!==this.opts.timestampRequests&&(t[this.opts.timestampParam]=Zn()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let ro=!1;try{ro="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(_w){}const io=ro;function no(){}class oo extends to{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let r=location.port;r||(r=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||r!==e.port}}doWrite(e,t){const r=this.request({method:"POST",data:e});r.on("success",t),r.on("error",(e,t)=>{this.onError("xhr post error",e,t)})}doPoll(){const e=this.request();e.on("data",this.onData.bind(this)),e.on("error",(e,t)=>{this.onError("xhr poll error",e,t)}),this.pollXhr=e}}let so=class e extends qn{constructor(e,t,r){super(),this.createRequest=e,Yn(this,r),this._opts=r,this._method=r.method||"GET",this._uri=t,this._data=void 0!==r.data?r.data:null,this._create()}_create(){var t;const r=Vn(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");r.xdomain=!!this._opts.xd;const i=this._xhr=this.createRequest(r);try{i.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){i.setDisableHeaderCheck&&i.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&i.setRequestHeader(e,this._opts.extraHeaders[e])}}catch(zw){}if("POST"===this._method)try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(zw){}try{i.setRequestHeader("Accept","*/*")}catch(zw){}null===(t=this._opts.cookieJar)||void 0===t||t.addCookies(i),"withCredentials"in i&&(i.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(i.timeout=this._opts.requestTimeout),i.onreadystatechange=()=>{var e;3===i.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(i.getResponseHeader("set-cookie"))),4===i.readyState&&(200===i.status||1223===i.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof i.status?i.status:0)},0))},i.send(this._data)}catch(zw){return void this.setTimeoutFn(()=>{this._onError(zw)},0)}"undefined"!=typeof document&&(this._index=e.requestsCount++,e.requests[this._index]=this)}_onError(e){this.emitReserved("error",e,this._xhr),this._cleanup(!0)}_cleanup(t){if(void 0!==this._xhr&&null!==this._xhr){if(this._xhr.onreadystatechange=no,t)try{this._xhr.abort()}catch(zw){}"undefined"!=typeof document&&delete e.requests[this._index],this._xhr=null}}_onLoad(){const e=this._xhr.responseText;null!==e&&(this.emitReserved("data",e),this.emitReserved("success"),this._cleanup())}abort(){this._cleanup()}};if(so.requestsCount=0,so.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",ao);else if("function"==typeof addEventListener){addEventListener("onpagehide"in Wn?"pagehide":"unload",ao,!1)}function ao(){for(let e in so.requests)so.requests.hasOwnProperty(e)&&so.requests[e].abort()}const co=function(){const e=lo({xdomain:!1});return e&&null!==e.responseType}();function lo(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||io))return new XMLHttpRequest}catch(zw){}if(!t)try{return new(Wn[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(zw){}}const uo="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class po extends eo{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,r=uo?{}:Vn(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(r.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,r)}catch(_w){return this.emitReserved("error",_w)}this.ws.binaryType=this.socket.binaryType,this.addEventListeners()}addEventListeners(){this.ws.onopen=()=>{this.opts.autoUnref&&this.ws._socket.unref(),this.onOpen()},this.ws.onclose=e=>this.onClose({description:"websocket connection closed",context:e}),this.ws.onmessage=e=>this.onData(e.data),this.ws.onerror=e=>this.onError("websocket error",e)}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],i=t===e.length-1;xn(r,this.supportsBinary,e=>{try{this.doWrite(r,e)}catch(zw){}i&&jn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){void 0!==this.ws&&(this.ws.onerror=()=>{},this.ws.close(),this.ws=null)}uri(){const e=this.opts.secure?"wss":"ws",t=this.query||{};return this.opts.timestampRequests&&(t[this.opts.timestampParam]=Zn()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const ho=Wn.WebSocket||Wn.MozWebSocket;const go={websocket:class extends po{createSocket(e,t,r){return uo?new ho(e,t,r):t?new ho(e,t):new ho(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends eo{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(_w){return this.emitReserved("error",_w)}this._transport.closed.then(()=>{this.onClose()}).catch(e=>{this.onError("webtransport error",e)}),this._transport.ready.then(()=>{this._transport.createBidirectionalStream().then(e=>{const t=function(e,t){Kn||(Kn=new TextDecoder);const r=[];let i=0,n=-1,o=!1;return new TransformStream({transform(s,a){for(r.push(s);;){if(0===i){if($n(r)<1)break;const e=Hn(r,1);o=!(128&~e[0]),n=127&e[0],i=n<126?3:126===n?1:2}else if(1===i){if($n(r)<2)break;const e=Hn(r,2);n=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if($n(r)<8)break;const e=Hn(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),o=t.getUint32(0);if(o>Math.pow(2,21)-1){a.enqueue(En);break}n=o*Math.pow(2,32)+t.getUint32(4),i=3}else{if($n(r)<n)break;const e=Hn(r,n);a.enqueue(Fn(o?e:Kn.decode(e),t)),i=0}if(0===n||n>e){a.enqueue(En);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),i=Ln();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const n=()=>{r.read().then(({done:e,value:t})=>{e||(this.onPacket(t),n())}).catch(e=>{})};n();const o={type:"open"};this.query.sid&&(o.data=`{"sid":"${this.query.sid}"}`),this._writer.write(o).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const r=e[t],i=t===e.length-1;this._writer.write(r).then(()=>{i&&jn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends oo{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=co&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new so(lo,this.uri(),e)}}},mo=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,fo=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function yo(e){if(e.length>8e3)throw"URI too long";const t=e,r=e.indexOf("["),i=e.indexOf("]");-1!=r&&-1!=i&&(e=e.substring(0,r)+e.substring(r,i).replace(/:/g,";")+e.substring(i,e.length));let n=mo.exec(e||""),o={},s=14;for(;s--;)o[fo[s]]=n[s]||"";return-1!=r&&-1!=i&&(o.source=t,o.host=o.host.substring(1,o.host.length-1).replace(/;/g,":"),o.authority=o.authority.replace("[","").replace("]","").replace(/;/g,":"),o.ipv6uri=!0),o.pathNames=function(e,t){const r=/\/{2,9}/g,i=t.replace(r,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||i.splice(0,1);"/"==t.slice(-1)&&i.splice(i.length-1,1);return i}(0,o.path),o.queryKey=function(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,i){t&&(r[t]=i)}),r}(0,o.query),o}const bo="function"==typeof addEventListener&&"function"==typeof removeEventListener,wo=[];bo&&addEventListener("offline",()=>{wo.forEach(e=>e())},!1);class Io extends qn{constructor(e,t){if(super(),this.binaryType="arraybuffer",this.writeBuffer=[],this._prevBufferLen=0,this._pingInterval=-1,this._pingTimeout=-1,this._maxPayload=-1,this._pingTimeoutTime=1/0,e&&"object"==typeof e&&(t=e,e=null),e){const r=yo(e);t.hostname=r.host,t.secure="https"===r.protocol||"wss"===r.protocol,t.port=r.port,r.query&&(t.query=r.query)}else t.host&&(t.hostname=yo(t.host).host);Yn(this,t),this.secure=null!=t.secure?t.secure:"undefined"!=typeof location&&"https:"===location.protocol,t.hostname&&!t.port&&(t.port=this.secure?"443":"80"),this.hostname=t.hostname||("undefined"!=typeof location?location.hostname:"localhost"),this.port=t.port||("undefined"!=typeof location&&location.port?location.port:this.secure?"443":"80"),this.transports=[],this._transportsByName={},t.transports.forEach(e=>{const t=e.prototype.name;this.transports.push(t),this._transportsByName[t]=e}),this.opts=Object.assign({path:"/engine.io",agent:!1,withCredentials:!1,upgrade:!0,timestampParam:"t",rememberUpgrade:!1,addTrailingSlash:!0,rejectUnauthorized:!0,perMessageDeflate:{threshold:1024},transportOptions:{},closeOnBeforeunload:!1},t),this.opts.path=this.opts.path.replace(/\/$/,"")+(this.opts.addTrailingSlash?"/":""),"string"==typeof this.opts.query&&(this.opts.query=function(e){let t={},r=e.split("&");for(let i=0,n=r.length;i<n;i++){let e=r[i].split("=");t[decodeURIComponent(e[0])]=decodeURIComponent(e[1])}return t}(this.opts.query)),bo&&(this.opts.closeOnBeforeunload&&(this._beforeunloadEventListener=()=>{this.transport&&(this.transport.removeAllListeners(),this.transport.close())},addEventListener("beforeunload",this._beforeunloadEventListener,!1)),"localhost"!==this.hostname&&(this._offlineEventListener=()=>{this._onClose("transport close",{description:"network connection lost"})},wo.push(this._offlineEventListener))),this.opts.withCredentials&&(this._cookieJar=void 0),this._open()}createTransport(e){const t=Object.assign({},this.opts.query);t.EIO=4,t.transport=e,this.id&&(t.sid=this.id);const r=Object.assign({},this.opts,{query:t,socket:this,hostname:this.hostname,secure:this.secure,port:this.port},this.opts.transportOptions[e]);return new this._transportsByName[e](r)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&Io.priorWebsocketSuccess&&-1!==this.transports.indexOf("websocket")?"websocket":this.transports[0];this.readyState="opening";const t=this.createTransport(e);t.open(),this.setTransport(t)}setTransport(e){this.transport&&this.transport.removeAllListeners(),this.transport=e,e.on("drain",this._onDrain.bind(this)).on("packet",this._onPacket.bind(this)).on("error",this._onError.bind(this)).on("close",e=>this._onClose("transport close",e))}onOpen(){this.readyState="open",Io.priorWebsocketSuccess="websocket"===this.transport.name,this.emitReserved("open"),this.flush()}_onPacket(e){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState)switch(this.emitReserved("packet",e),this.emitReserved("heartbeat"),e.type){case"open":this.onHandshake(JSON.parse(e.data));break;case"ping":this._sendPacket("pong"),this.emitReserved("ping"),this.emitReserved("pong"),this._resetPingTimeout();break;case"error":const t=new Error("server error");t.code=e.data,this._onError(t);break;case"message":this.emitReserved("data",e.data),this.emitReserved("message",e.data)}}onHandshake(e){this.emitReserved("handshake",e),this.id=e.sid,this.transport.query.sid=e.sid,this._pingInterval=e.pingInterval,this._pingTimeout=e.pingTimeout,this._maxPayload=e.maxPayload,this.onOpen(),"closed"!==this.readyState&&this._resetPingTimeout()}_resetPingTimeout(){this.clearTimeoutFn(this._pingTimeoutTimer);const e=this._pingInterval+this._pingTimeout;this._pingTimeoutTime=Date.now()+e,this._pingTimeoutTimer=this.setTimeoutFn(()=>{this._onClose("ping timeout")},e),this.opts.autoUnref&&this._pingTimeoutTimer.unref()}_onDrain(){this.writeBuffer.splice(0,this._prevBufferLen),this._prevBufferLen=0,0===this.writeBuffer.length?this.emitReserved("drain"):this.flush()}flush(){if("closed"!==this.readyState&&this.transport.writable&&!this.upgrading&&this.writeBuffer.length){const e=this._getWritablePackets();this.transport.send(e),this._prevBufferLen=e.length,this.emitReserved("flush")}}_getWritablePackets(){if(!(this._maxPayload&&"polling"===this.transport.name&&this.writeBuffer.length>1))return this.writeBuffer;let e=1;for(let t=0;t<this.writeBuffer.length;t++){const r=this.writeBuffer[t].data;if(r&&(e+=Xn(r)),t>0&&e>this._maxPayload)return this.writeBuffer.slice(0,t);e+=2}return this.writeBuffer}_hasPingExpired(){if(!this._pingTimeoutTime)return!0;const e=Date.now()>this._pingTimeoutTime;return e&&(this._pingTimeoutTime=0,jn(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,r){return this._sendPacket("message",e,t,r),this}send(e,t,r){return this._sendPacket("message",e,t,r),this}_sendPacket(e,t,r,i){if("function"==typeof t&&(i=t,t=void 0),"function"==typeof r&&(i=r,r=null),"closing"===this.readyState||"closed"===this.readyState)return;(r=r||{}).compress=!1!==r.compress;const n={type:e,data:t,options:r};this.emitReserved("packetCreate",n),this.writeBuffer.push(n),i&&this.once("flush",i),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},r=()=>{this.once("upgrade",t),this.once("upgradeError",t)};return"opening"!==this.readyState&&"open"!==this.readyState||(this.readyState="closing",this.writeBuffer.length?this.once("drain",()=>{this.upgrading?r():e()}):this.upgrading?r():e()),this}_onError(e){if(Io.priorWebsocketSuccess=!1,this.opts.tryAllTransports&&this.transports.length>1&&"opening"===this.readyState)return this.transports.shift(),this._open();this.emitReserved("error",e),this._onClose("transport error",e)}_onClose(e,t){if("opening"===this.readyState||"open"===this.readyState||"closing"===this.readyState){if(this.clearTimeoutFn(this._pingTimeoutTimer),this.transport.removeAllListeners("close"),this.transport.close(),this.transport.removeAllListeners(),bo&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=wo.indexOf(this._offlineEventListener);-1!==e&&wo.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}Io.protocol=4;class To extends Io{constructor(){super(...arguments),this._upgrades=[]}onOpen(){if(super.onOpen(),"open"===this.readyState&&this.opts.upgrade)for(let e=0;e<this._upgrades.length;e++)this._probe(this._upgrades[e])}_probe(e){let t=this.createTransport(e),r=!1;Io.priorWebsocketSuccess=!1;const i=()=>{r||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!r)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;Io.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{r||"closed"!==this.readyState&&(l(),this.setTransport(t),t.send([{type:"upgrade"}]),this.emitReserved("upgrade",t),t=null,this.upgrading=!1,this.flush())})}else{const e=new Error("probe error");e.transport=t.name,this.emitReserved("upgradeError",e)}}))};function n(){r||(r=!0,l(),t.close(),t=null)}const o=e=>{const r=new Error("probe error: "+e);r.transport=t.name,n(),this.emitReserved("upgradeError",r)};function s(){o("transport closed")}function a(){o("socket closed")}function c(e){t&&e.name!==t.name&&n()}const l=()=>{t.removeListener("open",i),t.removeListener("error",o),t.removeListener("close",s),this.off("close",a),this.off("upgrading",c)};t.once("open",i),t.once("error",o),t.once("close",s),this.once("close",a),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{r||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let r=0;r<e.length;r++)~this.transports.indexOf(e[r])&&t.push(e[r]);return t}}let So=class extends To{constructor(e,t={}){const r="object"==typeof e?e:t;(!r.transports||r.transports&&"string"==typeof r.transports[0])&&(r.transports=(r.transports||["polling","websocket","webtransport"]).map(e=>go[e]).filter(e=>!!e)),super(e,r)}};const ko="function"==typeof ArrayBuffer,vo=Object.prototype.toString,Eo="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===vo.call(Blob),Ao="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===vo.call(File);function Co(e){return ko&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Eo&&e instanceof Blob||Ao&&e instanceof File}function Ro(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(Ro(e[t]))return!0;return!1}if(Co(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Ro(e.toJSON(),!0);for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&Ro(e[r]))return!0;return!1}function xo(e){const t=[],r=e.data,i=e;return i.data=No(r,t),i.attachments=t.length,{packet:i,buffers:t}}function No(e,t){if(!e)return e;if(Co(e)){const r={_placeholder:!0,num:t.length};return t.push(e),r}if(Array.isArray(e)){const r=new Array(e.length);for(let i=0;i<e.length;i++)r[i]=No(e[i],t);return r}if("object"==typeof e&&!(e instanceof Date)){const r={};for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(r[i]=No(e[i],t));return r}return e}function zo(e,t){return e.data=_o(e.data,t),delete e.attachments,e}function _o(e,t){if(!e)return e;if(e&&!0===e._placeholder){if("number"==typeof e.num&&e.num>=0&&e.num<t.length)return t[e.num];throw new Error("illegal attachments")}if(Array.isArray(e))for(let r=0;r<e.length;r++)e[r]=_o(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=_o(e[r],t));return e}const Po=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Oo,Do;(Do=Oo||(Oo={}))[Do.CONNECT=0]="CONNECT",Do[Do.DISCONNECT=1]="DISCONNECT",Do[Do.EVENT=2]="EVENT",Do[Do.ACK=3]="ACK",Do[Do.CONNECT_ERROR=4]="CONNECT_ERROR",Do[Do.BINARY_EVENT=5]="BINARY_EVENT",Do[Do.BINARY_ACK=6]="BINARY_ACK";function Fo(e){return"[object Object]"===Object.prototype.toString.call(e)}class Mo extends qn{constructor(e){super(),this.reviver=e}add(e){let t;if("string"==typeof e){if(this.reconstructor)throw new Error("got plaintext data when reconstructing a packet");t=this.decodeString(e);const r=t.type===Oo.BINARY_EVENT;r||t.type===Oo.BINARY_ACK?(t.type=r?Oo.EVENT:Oo.ACK,this.reconstructor=new Uo(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!Co(e)&&!e.base64)throw new Error("Unknown type: "+e);if(!this.reconstructor)throw new Error("got binary data when not reconstructing a packet");t=this.reconstructor.takeBinaryData(e),t&&(this.reconstructor=null,super.emitReserved("decoded",t))}}decodeString(e){let t=0;const r={type:Number(e.charAt(0))};if(void 0===Oo[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Oo.BINARY_EVENT||r.type===Oo.BINARY_ACK){const i=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const n=e.substring(i,t);if(n!=Number(n)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(n)}if("/"===e.charAt(t+1)){const i=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}r.nsp=e.substring(i,t)}else r.nsp="/";const i=e.charAt(t+1);if(""!==i&&Number(i)==i){const i=t+1;for(;++t;){const r=e.charAt(t);if(null==r||Number(r)!=r){--t;break}if(t===e.length)break}r.id=Number(e.substring(i,t+1))}if(e.charAt(++t)){const i=this.tryParse(e.substr(t));if(!Mo.isPayloadValid(r.type,i))throw new Error("invalid payload");r.data=i}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(zw){return!1}}static isPayloadValid(e,t){switch(e){case Oo.CONNECT:return Fo(t);case Oo.DISCONNECT:return void 0===t;case Oo.CONNECT_ERROR:return"string"==typeof t||Fo(t);case Oo.EVENT:case Oo.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Po.indexOf(t[0]));case Oo.ACK:case Oo.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class Uo{constructor(e){this.packet=e,this.buffers=[],this.reconPack=e}takeBinaryData(e){if(this.buffers.push(e),this.buffers.length===this.reconPack.attachments){const e=zo(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const Bo=Object.freeze(Object.defineProperty({__proto__:null,Decoder:Mo,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Oo.EVENT&&e.type!==Oo.ACK||!Ro(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Oo.EVENT?Oo.BINARY_EVENT:Oo.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Oo.BINARY_EVENT&&e.type!==Oo.BINARY_ACK||(t+=e.attachments+"-"),e.nsp&&"/"!==e.nsp&&(t+=e.nsp+","),null!=e.id&&(t+=e.id),null!=e.data&&(t+=JSON.stringify(e.data,this.replacer)),t}encodeAsBinary(e){const t=xo(e),r=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(r),i}},get PacketType(){return Oo},protocol:5},Symbol.toStringTag,{value:"Module"}));function Lo(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const Ko=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class $o extends qn{constructor(e,t,r){super(),this.connected=!1,this.recovered=!1,this.receiveBuffer=[],this.sendBuffer=[],this._queue=[],this._queueSeq=0,this.ids=0,this.acks={},this.flags={},this.io=e,this.nsp=t,r&&r.auth&&(this.auth=r.auth),this._opts=Object.assign({},r),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[Lo(e,"open",this.onopen.bind(this)),Lo(e,"packet",this.onpacket.bind(this)),Lo(e,"error",this.onerror.bind(this)),Lo(e,"close",this.onclose.bind(this))]}get active(){return!!this.subs}connect(){return this.connected||(this.subEvents(),this.io._reconnecting||this.io.open(),"open"===this.io._readyState&&this.onopen()),this}open(){return this.connect()}send(...e){return e.unshift("message"),this.emit.apply(this,e),this}emit(e,...t){var r,i,n;if(Ko.hasOwnProperty(e))throw new Error('"'+e.toString()+'" is a reserved event name');if(t.unshift(e),this._opts.retries&&!this.flags.fromQueue&&!this.flags.volatile)return this._addToQueue(t),this;const o={type:Oo.EVENT,data:t,options:{}};if(o.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,r=t.pop();this._registerAckCallback(e,r),o.id=e}const s=null===(i=null===(r=this.io.engine)||void 0===r?void 0:r.transport)||void 0===i?void 0:i.writable,a=this.connected&&!(null===(n=this.io.engine)||void 0===n?void 0:n._hasPingExpired());return this.flags.volatile&&!s||(a?(this.notifyOutgoingListeners(o),this.packet(o)):this.sendBuffer.push(o)),this.flags={},this}_registerAckCallback(e,t){var r;const i=null!==(r=this.flags.timeout)&&void 0!==r?r:this._opts.ackTimeout;if(void 0===i)return void(this.acks[e]=t);const n=this.io.setTimeoutFn(()=>{delete this.acks[e];for(let t=0;t<this.sendBuffer.length;t++)this.sendBuffer[t].id===e&&this.sendBuffer.splice(t,1);t.call(this,new Error("operation has timed out"))},i),o=(...e)=>{this.io.clearTimeoutFn(n),t.apply(this,e)};o.withError=!0,this.acks[e]=o}emitWithAck(e,...t){return new Promise((r,i)=>{const n=(e,t)=>e?i(e):r(t);n.withError=!0,t.push(n),this.emit(e,...t)})}_addToQueue(e){let t;"function"==typeof e[e.length-1]&&(t=e.pop());const r={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...i)=>{if(r!==this._queue[0])return;return null!==e?r.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...i)),r.pending=!1,this._drainQueue()}),this._queue.push(r),this._drainQueue()}_drainQueue(e=!1){if(!this.connected||0===this._queue.length)return;const t=this._queue[0];t.pending&&!e||(t.pending=!0,t.tryCount++,this.flags=t.flags,this.emit.apply(this,t.args))}packet(e){e.nsp=this.nsp,this.io._packet(e)}onopen(){"function"==typeof this.auth?this.auth(e=>{this._sendConnectPacket(e)}):this._sendConnectPacket(this.auth)}_sendConnectPacket(e){this.packet({type:Oo.CONNECT,data:this._pid?Object.assign({pid:this._pid,offset:this._lastOffset},e):e})}onerror(e){this.connected||this.emitReserved("connect_error",e)}onclose(e,t){this.connected=!1,delete this.id,this.emitReserved("disconnect",e,t),this._clearAcks()}_clearAcks(){Object.keys(this.acks).forEach(e=>{if(!this.sendBuffer.some(t=>String(t.id)===e)){const t=this.acks[e];delete this.acks[e],t.withError&&t.call(this,new Error("socket has been disconnected"))}})}onpacket(e){if(e.nsp===this.nsp)switch(e.type){case Oo.CONNECT:e.data&&e.data.sid?this.onconnect(e.data.sid,e.data.pid):this.emitReserved("connect_error",new Error("It seems you are trying to reach a Socket.IO server in v2.x with a v3.x client, but they are not compatible (more information here: https://socket.io/docs/v3/migrating-from-2-x-to-3-0/)"));break;case Oo.EVENT:case Oo.BINARY_EVENT:this.onevent(e);break;case Oo.ACK:case Oo.BINARY_ACK:this.onack(e);break;case Oo.DISCONNECT:this.ondisconnect();break;case Oo.CONNECT_ERROR:this.destroy();const t=new Error(e.data.message);t.data=e.data.data,this.emitReserved("connect_error",t)}}onevent(e){const t=e.data||[];null!=e.id&&t.push(this.ack(e.id)),this.connected?this.emitEvent(t):this.receiveBuffer.push(Object.freeze(t))}emitEvent(e){if(this._anyListeners&&this._anyListeners.length){const t=this._anyListeners.slice();for(const r of t)r.apply(this,e)}super.emit.apply(this,e),this._pid&&e.length&&"string"==typeof e[e.length-1]&&(this._lastOffset=e[e.length-1])}ack(e){const t=this;let r=!1;return function(...i){r||(r=!0,t.packet({type:Oo.ACK,id:e,data:i}))}}onack(e){const t=this.acks[e.id];"function"==typeof t&&(delete this.acks[e.id],t.withError&&e.data.unshift(null),t.apply(this,e.data))}onconnect(e,t){this.id=e,this.recovered=t&&this._pid===t,this._pid=t,this.connected=!0,this.emitBuffered(),this.emitReserved("connect"),this._drainQueue(!0)}emitBuffered(){this.receiveBuffer.forEach(e=>this.emitEvent(e)),this.receiveBuffer=[],this.sendBuffer.forEach(e=>{this.notifyOutgoingListeners(e),this.packet(e)}),this.sendBuffer=[]}ondisconnect(){this.destroy(),this.onclose("io server disconnect")}destroy(){this.subs&&(this.subs.forEach(e=>e()),this.subs=void 0),this.io._destroy(this)}disconnect(){return this.connected&&this.packet({type:Oo.DISCONNECT}),this.destroy(),this.connected&&this.onclose("io client disconnect"),this}close(){return this.disconnect()}compress(e){return this.flags.compress=e,this}get volatile(){return this.flags.volatile=!0,this}timeout(e){return this.flags.timeout=e,this}onAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.push(e),this}prependAny(e){return this._anyListeners=this._anyListeners||[],this._anyListeners.unshift(e),this}offAny(e){if(!this._anyListeners)return this;if(e){const t=this._anyListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyListeners=[];return this}listenersAny(){return this._anyListeners||[]}onAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.push(e),this}prependAnyOutgoing(e){return this._anyOutgoingListeners=this._anyOutgoingListeners||[],this._anyOutgoingListeners.unshift(e),this}offAnyOutgoing(e){if(!this._anyOutgoingListeners)return this;if(e){const t=this._anyOutgoingListeners;for(let r=0;r<t.length;r++)if(e===t[r])return t.splice(r,1),this}else this._anyOutgoingListeners=[];return this}listenersAnyOutgoing(){return this._anyOutgoingListeners||[]}notifyOutgoingListeners(e){if(this._anyOutgoingListeners&&this._anyOutgoingListeners.length){const t=this._anyOutgoingListeners.slice();for(const r of t)r.apply(this,e.data)}}}function Ho(e){e=e||{},this.ms=e.min||100,this.max=e.max||1e4,this.factor=e.factor||2,this.jitter=e.jitter>0&&e.jitter<=1?e.jitter:0,this.attempts=0}Ho.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),r=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+r:e-r}return 0|Math.min(e,this.max)},Ho.prototype.reset=function(){this.attempts=0},Ho.prototype.setMin=function(e){this.ms=e},Ho.prototype.setMax=function(e){this.max=e},Ho.prototype.setJitter=function(e){this.jitter=e};class qo extends qn{constructor(e,t){var r;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,Yn(this,t),this.reconnection(!1!==t.reconnection),this.reconnectionAttempts(t.reconnectionAttempts||1/0),this.reconnectionDelay(t.reconnectionDelay||1e3),this.reconnectionDelayMax(t.reconnectionDelayMax||5e3),this.randomizationFactor(null!==(r=t.randomizationFactor)&&void 0!==r?r:.5),this.backoff=new Ho({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const i=t.parser||Bo;this.encoder=new i.Encoder,this.decoder=new i.Decoder,this._autoConnect=!1!==t.autoConnect,this._autoConnect&&this.open()}reconnection(e){return arguments.length?(this._reconnection=!!e,e||(this.skipReconnect=!0),this):this._reconnection}reconnectionAttempts(e){return void 0===e?this._reconnectionAttempts:(this._reconnectionAttempts=e,this)}reconnectionDelay(e){var t;return void 0===e?this._reconnectionDelay:(this._reconnectionDelay=e,null===(t=this.backoff)||void 0===t||t.setMin(e),this)}randomizationFactor(e){var t;return void 0===e?this._randomizationFactor:(this._randomizationFactor=e,null===(t=this.backoff)||void 0===t||t.setJitter(e),this)}reconnectionDelayMax(e){var t;return void 0===e?this._reconnectionDelayMax:(this._reconnectionDelayMax=e,null===(t=this.backoff)||void 0===t||t.setMax(e),this)}timeout(e){return arguments.length?(this._timeout=e,this):this._timeout}maybeReconnectOnOpen(){!this._reconnecting&&this._reconnection&&0===this.backoff.attempts&&this.reconnect()}open(e){if(~this._readyState.indexOf("open"))return this;this.engine=new So(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const i=Lo(t,"open",function(){r.onopen(),e&&e()}),n=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},o=Lo(t,"error",n);if(!1!==this._timeout){const e=this._timeout,r=this.setTimeoutFn(()=>{i(),n(new Error("timeout")),t.close()},e);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}return this.subs.push(i),this.subs.push(o),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(Lo(e,"ping",this.onping.bind(this)),Lo(e,"data",this.ondata.bind(this)),Lo(e,"error",this.onerror.bind(this)),Lo(e,"close",this.onclose.bind(this)),Lo(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(zw){this.onclose("parse error",zw)}}ondecoded(e){jn(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let r=this.nsps[e];return r?this._autoConnect&&!r.active&&r.connect():(r=new $o(this,e,t),this.nsps[e]=r),r}_destroy(e){const t=Object.keys(this.nsps);for(const r of t){if(this.nsps[r].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let r=0;r<t.length;r++)this.engine.write(t[r],e.options)}cleanup(){this.subs.forEach(e=>e()),this.subs.length=0,this.decoder.destroy()}_close(){this.skipReconnect=!0,this._reconnecting=!1,this.onclose("forced close")}disconnect(){return this._close()}onclose(e,t){var r;this.cleanup(),null===(r=this.engine)||void 0===r||r.close(),this.backoff.reset(),this._readyState="closed",this.emitReserved("close",e,t),this._reconnection&&!this.skipReconnect&&this.reconnect()}reconnect(){if(this._reconnecting||this.skipReconnect)return this;const e=this;if(this.backoff.attempts>=this._reconnectionAttempts)this.backoff.reset(),this.emitReserved("reconnect_failed"),this._reconnecting=!1;else{const t=this.backoff.duration();this._reconnecting=!0;const r=this.setTimeoutFn(()=>{e.skipReconnect||(this.emitReserved("reconnect_attempt",e.backoff.attempts),e.skipReconnect||e.open(t=>{t?(e._reconnecting=!1,e.reconnect(),this.emitReserved("reconnect_error",t)):e.onreconnect()}))},t);this.opts.autoUnref&&r.unref(),this.subs.push(()=>{this.clearTimeoutFn(r)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const jo={};function Wo(e,t){"object"==typeof e&&(t=e,e=void 0);const r=function(e,t="",r){let i=e;r=r||"undefined"!=typeof location&&location,null==e&&(e=r.protocol+"//"+r.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?r.protocol+e:r.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==r?r.protocol+"//"+e:"https://"+e),i=yo(e)),i.port||(/^(http|ws)$/.test(i.protocol)?i.port="80":/^(http|ws)s$/.test(i.protocol)&&(i.port="443")),i.path=i.path||"/";const n=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+n+":"+i.port+t,i.href=i.protocol+"://"+n+(r&&r.port===i.port?"":":"+i.port),i}(e,(t=t||{}).path||"/socket.io"),i=r.source,n=r.id,o=r.path,s=jo[n]&&o in jo[n].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||s?a=new qo(i,t):(jo[n]||(jo[n]=new qo(i,t)),a=jo[n]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}function Vo(e,t,r=0){if(r>5)return;if("string"==typeof e){const r=e.trim();return void(r&&t.push(r))}if(Array.isArray(e)){for(const i of e)Vo(i,t,r+1);return}if(!function(e){return"object"==typeof e&&null!==e}(e))return;const i=["message","error","detail","reason","title","description"];for(const o of i)Vo(e[o],t,r+1);const n=["errors","details","causes","cause"];for(const o of n)Vo(e[o],t,r+1)}function Go(e){if("string"==typeof e)return e.trim();try{return JSON.stringify(e)}catch{return String(e)}}function Jo(e){var t,r;if(vr.isAxiosError(e))return null==(t=e.response)?void 0:t.status;return null==(r=e.response)?void 0:r.status}function Yo(e){if(vr.isAxiosError(e))return e.code;return e.code}function Xo(e){if(e instanceof Error&&"ValidationError"===e.name)return!1;const t=Jo(e);if("number"==typeof t)return[408,425,429,500,502,503,504].includes(t);const r=Yo(e);return!!r&&["ECONNRESET","ETIMEDOUT","EAI_AGAIN","ENOTFOUND","ECONNREFUSED","ERR_NETWORK"].includes(r)}function Zo(e){const t=Jo(e),r=Yo(e),i=function(e){var t,r;return vr.isAxiosError(e)?null==(t=e.response)?void 0:t.data:null==(r=e.response)?void 0:r.data}(e),n=[];Vo(i,n),Vo(e,n);const o=Array.from(new Set(n)).filter(Boolean),s=new Set(["failed to start inscription","failed to start inscribe job","request failed","bad request"]),a=o.filter(e=>{const t=e.toLowerCase().trim();return!!t&&(!s.has(t)&&!t.startsWith("failed to start inscription"))}).sort((e,t)=>t.length-e.length)[0]??o[0]??(e instanceof Error?e.message:""),c=["number"==typeof t?`HTTP ${t}`:null,r?`code=${r}`:null].filter(Boolean),l=c.length?` (${c.join(", ")})`:"";return a?`Failed to start inscription${l}: ${a}`:`Failed to start inscription${l}: ${Go(i)||Go(e)}`}Object.assign(Wo,{Manager:qo,Socket:$o,io:Wo,connect:Wo});const Qo=class e{constructor(e){if(K(this,"client"),K(this,"config"),K(this,"logger",$r.getInstance()),K(this,"socket",null),K(this,"socketConnected",!1),K(this,"connectionMode","auto"),K(this,"wsBaseUrl",null),this.config=e,!e.apiKey)throw new Hr("API key is required");if(!e.network)throw new Hr("Network is required");const t={"x-api-key":e.apiKey,"Content-Type":"application/json"};this.client=vr.create({baseURL:e.baseURL||e.baseUrl||"https://v2-api.tier.bot/api",headers:t}),this.logger=$r.getInstance(),e.wsBaseUrl&&(this.wsBaseUrl=e.wsBaseUrl),this.connectionMode=e.connectionMode||"websocket",this.wsBaseUrl||"http"===this.connectionMode||this.fetchWebSocketServers().catch(e=>this.logger.warn("Failed to fetch WebSocket servers:",e))}async getFileMetadata(e){try{const t=await vr.get(e),r=t.headers["content-type"]||"";return{size:parseInt(t.headers["content-length"]||"0",10),mimeType:r}}catch(t){throw this.logger.error("Error fetching file metadata:",t),new Hr("Unable to fetch file metadata")}}getMimeType(t){const r=t.toLowerCase().split(".").pop();if(!r)throw new Hr("File must have an extension");const i=e.VALID_MIME_TYPES[r];if(!i)throw new Hr(`Unsupported file type: ${r}`);return i}validateRequest(t){if(this.logger.debug("Validating request:",t),!t.holderId||""===t.holderId.trim())throw this.logger.warn("holderId is missing or empty"),new Hr("holderId is required");if(!e.VALID_MODES.includes(t.mode))throw new Hr(`Invalid mode: ${t.mode}. Must be one of: ${e.VALID_MODES.join(", ")}`);if("hashinal"===t.mode&&!t.jsonFileURL&&!t.metadataObject)throw new Hr("Hashinal mode requires either jsonFileURL or metadataObject");if(t.onlyJSONCollection&&"hashinal-collection"!==t.mode)throw new Hr("onlyJSONCollection can only be used with hashinal-collection mode");this.validateFileInput(t.file)}normalizeMimeType(e){return"image/vnd.microsoft.icon"===e?(this.logger.debug("Normalizing MIME type from image/vnd.microsoft.icon to image/x-icon"),"image/x-icon"):e}validateMimeType(t){return!!Object.values(e.VALID_MIME_TYPES).includes(t)||"image/vnd.microsoft.icon"===t&&(this.logger.debug("Accepting alternative MIME type for ICO: image/vnd.microsoft.icon"),!0)}validateFileInput(t){if("base64"===t.type){if(!t.base64)throw new Hr("Base64 data is required");const r=t.base64.replace(/^data:.*?;base64,/,"");if(Math.ceil(.75*r.length)>e.MAX_BASE64_SIZE)throw new Hr(`File size exceeds maximum limit of ${e.MAX_BASE64_SIZE/1024/1024}MB`);const i=t.mimeType||this.getMimeType(t.fileName);if(!this.validateMimeType(i))throw new Hr("File must have one of the supported MIME types");"image/vnd.microsoft.icon"===t.mimeType&&(t.mimeType=this.normalizeMimeType(t.mimeType))}else if("url"===t.type&&!t.url)throw new Hr("URL is required")}async detectMimeTypeFromBase64(e){if(e.startsWith("data:")){const t=e.match(/^data:([^;]+);base64,/);if(t&&t.length>1)return t[1]}try{const t=e.replace(/\s/g,""),r=Q.from(t,"base64"),i=await async function(e,t){return new Sn(t).fromBuffer(e)}(r);return(null==i?void 0:i.mime)||"application/octet-stream"}catch(_w){return this.logger.warn("Failed to detect MIME type from buffer"),"application/octet-stream"}}async startInscription(t){try{const r=async()=>{this.validateRequest(t);let r=t.file.mimeType;if("url"===t.file.type){const i=await this.getFileMetadata(t.file.url);if(r=i.mimeType||r,i.size>e.MAX_URL_FILE_SIZE)throw new Hr(`File size exceeds maximum URL file limit of ${e.MAX_URL_FILE_SIZE/1024/1024}MB`)}else"base64"===t.file.type&&(r=await this.detectMimeTypeFromBase64(t.file.base64));if("image/vnd.microsoft.icon"===r&&(r=this.normalizeMimeType(r)),t.jsonFileURL){if("application/json"!==(await this.getFileMetadata(t.jsonFileURL)).mimeType)throw new Hr("JSON file must be of type application/json")}const i={holderId:t.holderId,mode:t.mode,network:this.config.network,onlyJSONCollection:t.onlyJSONCollection?1:0,creator:t.creator,description:t.description,fileStandard:t.fileStandard,metadataObject:t.metadataObject,jsonFileURL:t.jsonFileURL};if("url"===t.file.type){return(await this.client.post("/inscriptions/start-inscription",{...i,fileURL:t.file.url})).data}return(await this.client.post("/inscriptions/start-inscription",{...i,fileBase64:t.file.base64,fileName:t.file.fileName,fileMimeType:r||this.getMimeType(t.file.fileName)})).data};return await this.retryWithBackoff(r,{shouldRetry:Xo})}catch(r){if(r instanceof Hr)throw r;if(vr.isAxiosError(r))throw new Error(Zo(r));throw new Error(Zo(r))}}async executeTransaction(e,t){var i,n;try{const o="mainnet"===t.network?r.Client.forMainnet():r.Client.forTestnet(),s=new Wr(t.network),a=await s.requestAccount(t.accountId),c=null==(i=null==a?void 0:a.key)?void 0:i._type,l="string"==typeof t.privateKey;let u;if(c&&l)u=(null==(n=null==c?void 0:c.toLowerCase())?void 0:n.includes("ecdsa"))?r.PrivateKey.fromStringECDSA(t.privateKey):r.PrivateKey.fromStringED25519(t.privateKey);else if(!c&&l){const e=l?qr(t.privateKey):void 0;u="ed25519"===(null==e?void 0:e.detectedType)?r.PrivateKey.fromStringED25519(t.privateKey):r.PrivateKey.fromStringECDSA(t.privateKey)}else u=t.privateKey;o.setOperator(t.accountId,u);const d=r.TransferTransaction.fromBytes(Q.from(e,"base64")),p=await d.sign(u),h=await p.execute(o),g=(await h.getReceipt(o)).status.toString();if("SUCCESS"!==g)throw new Error(`Transaction failed with status: ${g}`);return h.transactionId.toString()}catch(o){throw new Error(`Failed to execute transaction: ${o instanceof Error?o.message:"Unknown error"}`)}}async executeTransactionWithSigner(e,t){try{const i=r.TransferTransaction.fromBytes(Q.from(e,"base64")),n=await i.executeWithSigner(t),o=(await n.getReceiptWithSigner(t)).status.toString();if("SUCCESS"!==o)throw new Error(`Transaction failed with status: ${o}`);return n.transactionId.toString()}catch(i){throw new Error(`Failed to execute transaction: ${i instanceof Error?i.message:"Unknown error"}`)}}async inscribeAndExecute(e,t,r,i){const n=(null==i?void 0:i.waitForCompletion)??!0,o=(null==i?void 0:i.maxWaitTime)??12e4,s=(null==i?void 0:i.checkInterval)??2e3;if(this.logger.debug("inscribeAndExecute called",{hasProgressCallback:!!r,connectionMode:this.connectionMode,wsBaseUrl:this.wsBaseUrl}),"http"!==this.connectionMode){const i="websocket"===this.connectionMode||"auto"===this.connectionMode&&await this.detectBestConnection();if(i)try{return await this.inscribeViaWebSocket(e,t,r)}catch(u){this.logger.warn("WebSocket inscription failed, falling back to HTTP",u)}else this.logger.info(`Not using WebSocket: useWebSocket=${i}, wsBaseUrl=${this.wsBaseUrl}`)}else this.logger.info(`Not using WebSocket: hasCallback=${!!r}, connectionMode=${this.connectionMode}`);const a=await this.startInscription(e);if(!a.transactionBytes)throw this.logger.error("No transaction bytes returned from inscription request",a),new Error("No transaction bytes returned from inscription request");this.logger.info("executing transaction");const c=await this.executeTransaction(a.transactionBytes,t),l={jobId:a.tx_id,transactionId:c};if(n){r&&r({stage:"confirming",message:"Transaction executed, waiting for inscription to complete",progressPercent:5});const e=Math.floor(o/s),t=await this.waitForInscription(c,e,s,!0,r);return{...l,topicId:t.topic_id,status:t.status,completed:t.completed}}return l}async fetchWebSocketServers(){try{const e=await this.client.get("/inscriptions/websocket-servers"),{servers:t,recommended:r}=e.data;if(r)this.wsBaseUrl=r;else if(t&&t.length>0){const e=t.filter(e=>"active"===e.status);if(e.length>0){const t=e[0];this.wsBaseUrl=t.url}}}catch(e){this.logger.debug("Could not fetch WebSocket servers, will use HTTP only")}}async detectBestConnection(){if(!this.wsBaseUrl)return!1;try{const e=Wo(this.wsBaseUrl,{auth:{apiKey:this.config.apiKey},transports:["websocket"],timeout:3e3});return new Promise(t=>{const r=setTimeout(()=>{e.disconnect(),t(!1)},3e3);e.on("connect",()=>{clearTimeout(r),e.disconnect(),t(!0)}),e.on("connect_error",()=>{clearTimeout(r),e.disconnect(),t(!1)})})}catch(zw){return!1}}async inscribeViaWebSocket(e,t,r){if(!this.wsBaseUrl){const e=(await this.client.get("/inscriptions/websocket-servers")).data.recommended;if(!e)throw new Error("No WebSocket servers available");this.wsBaseUrl=e}return await this.connectWebSocket(),new Promise((i,n)=>{if(!this.socket)return n(new Error("WebSocket not connected"));let o,s,a,c;const l=()=>{var e,t,r;c&&clearTimeout(c),null==(e=this.socket)||e.off("inscription-progress",g),null==(t=this.socket)||t.off("inscription-complete",p),null==(r=this.socket)||r.off("inscription-error",h)},u=this.config.websocketInactivityTimeoutMs,d=()=>{!u||u<=0||(c&&clearTimeout(c),c=setTimeout(()=>{this.logger.error(`WebSocket inscription timeout after ${u/1e3} seconds`,{jobId:o,transactionId:s,lastTopicId:a}),l(),i({jobId:o,transactionId:s,topicId:a,topic_id:a,status:"timeout",completed:!1})},u))};d();const p=e=>{l(),i({jobId:o,transactionId:s,topicId:e.topicId||e.topic_id,topic_id:e.topicId||e.topic_id,status:"completed",completed:!0})},h=e=>{l(),n(new Error(e.error||"Inscription failed"))},g=e=>{d(),this.logger.debug("Progress event received:",{jobId:e.jobId,status:e.status,progress:e.progress,topicId:e.topicId||e.topic_id,topic_id:e.topicId||e.topic_id}),(e.topicId||e.topic_id)&&(a=e.topicId||e.topic_id),r&&r({stage:"completed"===e.status?"completed":"confirming",message:`Processing inscription: ${e.status}`,progressPercent:e.progress||0,details:e}),"completed"!==e.status&&100!==e.progress||(this.logger.info("Inscription completed via progress handler",{status:e.status,progress:e.progress,topicId:e.topicId||e.topic_id||a,topic_id:e.topicId||e.topic_id||a}),l(),i({jobId:o,transactionId:s,topicId:e.topicId||e.topic_id||a,topic_id:e.topicId||e.topic_id||a,status:"completed",completed:!0}))};this.socket.on("inscription-progress",g),this.socket.on("inscription-complete",p),this.socket.on("inscription-error",h),this.socket.emit("start-inscription",{...e,network:this.config.network},async e=>{if(!e.success)return l(),n(new Error(e.error||"Inscription failed"));try{if(!e.transactionBytes)throw new Error("No transaction bytes returned from WebSocket inscription");if(s=await this.executeTransaction(e.transactionBytes,t),o=e.jobId||e.tx_id,!o)throw new Error("No job ID returned from WebSocket inscription");r&&r({stage:"confirming",message:"Transaction executed, inscribing to HCS...",progressPercent:5}),this.logger.info("Transaction executed, waiting for inscription completion...",{jobId:o,transactionId:s})}catch(i){l(),n(i)}})})}async connectWebSocket(){if(!this.socketConnected||!this.socket){if(!this.wsBaseUrl)throw new Error("WebSocket URL not configured");return new Promise((e,t)=>{this.socket=Wo(this.wsBaseUrl,{auth:{apiKey:this.config.apiKey},transports:["websocket","polling"]});const r=setTimeout(()=>{t(new Error("WebSocket connection timeout"))},1e4);this.socket.on("connect",()=>{clearTimeout(r),this.socketConnected=!0,this.logger.info("WebSocket connected"),e()}),this.socket.on("connect_error",e=>{clearTimeout(r),this.socketConnected=!1,t(new Error(`WebSocket connection failed: ${e.message}`))}),this.socket.on("disconnect",()=>{this.socketConnected=!1,this.logger.info("WebSocket disconnected")})})}}disconnect(){this.socket&&(this.socket.disconnect(),this.socket=null,this.socketConnected=!1)}async inscribe(e,t){const r=await this.startInscription(e);if(!r.transactionBytes)throw this.logger.error("No transaction bytes returned from inscription request",r),new Error("No transaction bytes returned from inscription request");this.logger.info("executing transaction");const i=await this.executeTransactionWithSigner(r.transactionBytes,t);return{jobId:r.tx_id,transactionId:i}}async retryWithBackoff(e,t){const r=(null==t?void 0:t.maxRetries)??3,i=(null==t?void 0:t.baseDelayMs)??1e3,n=(null==t?void 0:t.shouldRetry)??(()=>!0);for(let s=0;s<r;s++)try{return await e()}catch(o){if(s===r-1||!n(o))throw o;const e=i*Math.pow(2,s);await new Promise(t=>setTimeout(t,e)),this.logger.debug(`Retry attempt ${s+1}/${r} after ${e}ms delay`)}throw new Error("Retry operation failed")}async retrieveInscription(e){if(!e)throw new Hr("Transaction ID is required");try{const t=e.includes("@")?`${e.split("@")[0]}-${e.split("@")[1].replace(/\./g,"-")}`:e;return await this.retryWithBackoff(async()=>{const e=(await this.client.get(`/inscriptions/retrieve-inscription?id=${t}`)).data,r=e.completed||"completed"===e.status.toLowerCase();return{...e,completed:r,jobId:e.tx_id||t}})}catch(t){throw this.logger.error("Failed to retrieve inscription:",t),t}}async getInscriptionNumbers(e={}){try{return(await this.client.get("/inscriptions/numbers",{params:e})).data}catch(t){throw this.logger.error("Failed to fetch inscription numbers:",t),t}}static async authenticate(e){return new jr(e).authenticate()}static async createWithAuth(t){const r="client"===t.type?new Vr({...t,logger:$r.getInstance()}):new jr(t),{apiKey:i}=await r.authenticate();return new e({apiKey:i,network:t.network||"mainnet",baseURL:t.baseUrl,wsBaseUrl:t.wsBaseUrl,connectionMode:t.connectionMode||"websocket"})}async waitForInscription(e,t=Number.MAX_SAFE_INTEGER,r=4e3,i=!1,n){var o,s;let a=0,c=0;const l=(r,i,o,s)=>{if(n)try{c=Math.max(c,o),n({stage:r,message:i,progressPercent:c,details:{...s,txId:e,currentAttempt:a,maxAttempts:t}})}catch(_w){this.logger.warn(`Error in progress callback: ${_w}`)}};for(l("confirming","Starting inscription verification",0);a<t;){l("confirming",`Verifying inscription status (attempt ${a+1}/${t})`,5,{attempt:a+1});const n=await this.retrieveInscription(e);if(n.error)throw l("verifying",`Error: ${n.error}`,100,{error:n.error}),new Error(n.error);let c=5;const u=n.completed||"completed"===n.status.toLowerCase();void 0!==n.messages&&void 0!==n.maxMessages&&n.maxMessages>0?(c=Math.min(95,5+n.messages/n.maxMessages*90),u&&(c=100)):"processing"===n.status?c=10:u&&(c=100),l(u?"completed":"confirming",u?"Inscription completed successfully":`Processing inscription (${n.status})`,c,{status:n.status,messagesProcessed:n.messages,maxMessages:n.maxMessages,messageCount:n.messages,completed:u,confirmedMessages:n.confirmedMessages,result:n});const d="hashinal"===n.mode,p="hashinal-collection"===n.mode,h="bulk-files"===n.mode,g="6"===(null==(o=n.fileStandard)?void 0:o.toString());if(p&&u&&(!i||u))return l("completed","Inscription verification complete",100,{result:n}),n;if(d&&n.topic_id&&n.jsonTopicId&&(!i||u))return l("completed","Inscription verification complete",100,{result:n}),n;if(!d&&!g&&n.topic_id&&(!i||u))return l("completed","Inscription verification complete",100,{result:n}),n;if(g&&n.topic_id&&n.jsonTopicId&&n.registryTopicId&&(!i||u))return l("completed","Inscription verification complete",100,{result:n}),n;if(h&&u){const e=null==(s=n.files)?void 0:s.bulkUploads,t=Array.isArray(e)&&e.length>0;if(!i||t)return l("completed","Inscription verification complete",100,{result:n}),n}await new Promise(e=>setTimeout(e,r)),a++}throw l("verifying",`Inscription ${e} did not complete within ${t} attempts`,100,{timedOut:!0}),new Error(`Inscription ${e} did not complete within ${t} attempts`)}async getHolderInscriptions(e){var t,r;if(!e.holderId)throw new Hr("Holder ID is required");try{const t={holderId:e.holderId};e.includeCollections&&(t.includeCollections="1");return(await this.client.get("/inscriptions/holder-inscriptions",{params:t})).data}catch(i){if(this.logger.error("Failed to fetch holder inscriptions:",i),vr.isAxiosError(i))throw new Error((null==(r=null==(t=i.response)?void 0:t.data)?void 0:r.message)||"Failed to fetch holder inscriptions");throw i}}};K(Qo,"VALID_MODES",["file","upload","hashinal","hashinal-collection","bulk-files"]),K(Qo,"MAX_BASE64_SIZE",33554432),K(Qo,"MAX_URL_FILE_SIZE",104857600),K(Qo,"VALID_MIME_TYPES",{jpg:"image/jpeg",jpeg:"image/jpeg",png:"image/png",gif:"image/gif",ico:"image/x-icon",heic:"image/heic",heif:"image/heif",bmp:"image/bmp",webp:"image/webp",tiff:"image/tiff",tif:"image/tiff",svg:"image/svg+xml",mp4:"video/mp4",webm:"video/webm",mp3:"audio/mpeg",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",html:"text/html",htm:"text/html",css:"text/css",php:"application/x-httpd-php",java:"text/x-java-source",js:"application/javascript",mjs:"application/javascript",csv:"text/csv",json:"application/json",txt:"text/plain",glb:"model/gltf-binary",wav:"audio/wav",ogg:"audio/ogg",oga:"audio/ogg",flac:"audio/flac",aac:"audio/aac",m4a:"audio/mp4",avi:"video/x-msvideo",mov:"video/quicktime",mkv:"video/x-matroska",m4v:"video/mp4",mpg:"video/mpeg",mpeg:"video/mpeg",ts:"application/typescript",zip:"application/zip",rar:"application/vnd.rar",tar:"application/x-tar",gz:"application/gzip","7z":"application/x-7z-compressed",xml:"application/xml",yaml:"application/yaml",yml:"application/yaml",md:"text/markdown",markdown:"text/markdown",rtf:"application/rtf",gltf:"model/gltf+json",usdz:"model/vnd.usdz+zip",obj:"model/obj",stl:"model/stl",fbx:"application/octet-stream",ttf:"font/ttf",otf:"font/otf",woff:"font/woff",woff2:"font/woff2",eot:"application/vnd.ms-fontobject",psd:"application/vnd.adobe.photoshop",ai:"application/postscript",eps:"application/postscript",ps:"application/postscript",sqlite:"application/x-sqlite3",db:"application/x-sqlite3",apk:"application/vnd.android.package-archive",ics:"text/calendar",vcf:"text/vcard",py:"text/x-python",rb:"text/x-ruby",go:"text/x-go",rs:"text/x-rust",typescript:"application/typescript",jsx:"text/jsx",tsx:"text/tsx",sql:"application/sql",toml:"application/toml",avif:"image/avif",jxl:"image/jxl",weba:"audio/webm",wasm:"application/wasm"});let es=Qo;class ts{constructor(e={}){this.module=e.module||"Progress",this.callback=e.callback,this.logger=e.logger||new y({level:"info",module:"ProgressReporter"}),this.logProgress=e.logProgress??!0,this.minPercent=e.minPercent??0,this.maxPercent=e.maxPercent??100,this.lastReportedPercent=-1,this.lastReportedTime=0,this.throttleMs=100}static getInstance(e={}){return ts.instance?(e.callback&&ts.instance.setCallback(e.callback),e.module&&ts.instance.setModule(e.module),e.logger&&ts.instance.setLogger(e.logger),void 0!==e.minPercent&&ts.instance.setMinPercent(e.minPercent),void 0!==e.maxPercent&&ts.instance.setMaxPercent(e.maxPercent)):ts.instance=new ts(e),ts.instance}setCallback(e){this.callback=e}setModule(e){this.module=e}setLogger(e){this.logger=e}setMinPercent(e){this.minPercent=e}setMaxPercent(e){this.maxPercent=e}createSubProgress(e){const t=new ts({module:this.module,logger:this.logger,logProgress:this.logProgress,minPercent:e.minPercent,maxPercent:e.maxPercent}),r=e.logPrefix||"";return t.setCallback(t=>{const i=this.scalePercent(t.progressPercent,e.minPercent,e.maxPercent);let n=t.message;r&&!n.startsWith(r)&&(n=`${r}: ${n}`),this.report({stage:t.stage,message:n,progressPercent:i,details:t.details})}),t}report(e){const t=e.progressPercent,r=Math.max(0,Math.min(100,t)),i=this.scalePercent(r,0,100),n=Date.now();if(i===this.lastReportedPercent&&n-this.lastReportedTime<this.throttleMs&&"completed"!==e.stage&&"failed"!==e.stage)return;this.lastReportedPercent=i,this.lastReportedTime=n;const o={...e,progressPercent:i};if(this.logProgress&&this.logger.debug(`[${this.module}] [${e.stage.toUpperCase()}] ${e.message} (${i.toFixed(1)}%)`,e.details),this.callback)try{this.callback(o)}catch(_w){this.logger.warn(`Error in progress callback: ${_w}`)}}scalePercent(e,t,r){const i=(this.maxPercent-this.minPercent)/(r-t);return this.minPercent+(e-t)*i}preparing(e,t,r){this.report({stage:"preparing",message:e,progressPercent:t,details:r})}submitting(e,t,r){this.report({stage:"submitting",message:e,progressPercent:t,details:r})}confirming(e,t,r){this.report({stage:"confirming",message:e,progressPercent:t,details:r})}verifying(e,t,r){this.report({stage:"verifying",message:e,progressPercent:t,details:r})}completed(e,t){this.report({stage:"completed",message:e,progressPercent:100,details:t})}failed(e,t){this.report({stage:"failed",message:e,progressPercent:this.lastReportedPercent,details:t})}}class rs extends Error{constructor(e,t="PARSING_FAILED",r,i){super(e),this.name="TransactionParsingError",this.code=t,this.originalError=r,this.transactionBytes=i,Error.captureStackTrace&&Error.captureStackTrace(this,rs)}}const is=(e,t)=>e.replace(/\{([^}]+)\}/g,(e,r)=>{const i=((e,t)=>{const r=t.split(".");let i=e;for(const n of r){if(null==i)return;i=i[n]}return i})(t,String(r).trim());return null==i?"(Unknown)":String(i)}),ns=e=>{const t=[],r=[];if(Array.isArray(e.transfers))for(const i of e.transfers){const e=parseFloat(i.amount);let n=i.amount;n.startsWith("-")&&(n=n.substring(1)),n=n.replace(/\s*ℏ$/,""),e<0?t.push(`${i.accountId} (${n} ℏ)`):e>0&&r.push(`${i.accountId} (${n} ℏ)`)}return t.length>0&&r.length>0?`Transfer of HBAR from ${t.join(", ")} to ${r.join(", ")}`:e.humanReadableType},os=e=>{if(!e.contractCall)return e.humanReadableType;let t=`Contract call to ${e.contractCall.contractId} with ${e.contractCall.gas} gas`;return e.contractCall.amount>0&&(t+=` and ${e.contractCall.amount} HBAR`),e.contractCall.functionName&&(t+=` calling function ${e.contractCall.functionName}`),t},ss=e=>e.tokenMint?`Mint ${e.tokenMint.amount} tokens for token ${e.tokenMint.tokenId}`:e.humanReadableType,as=e=>e.tokenBurn?`Burn ${e.tokenBurn.amount} tokens for token ${e.tokenBurn.tokenId}`:e.humanReadableType,cs=e=>{if(!e.tokenCreation)return e.humanReadableType;let t=`Create token ${e.tokenCreation.tokenName||"(No Name)"} (${e.tokenCreation.tokenSymbol||"(No Symbol)"})`;return e.tokenCreation.initialSupply&&(t+=` with initial supply ${e.tokenCreation.initialSupply}`),e.tokenCreation.customFees&&e.tokenCreation.customFees.length>0&&(t+=` including ${e.tokenCreation.customFees.length} custom fee(s)`),t},ls=e=>{if(!e.consensusCreateTopic)return e.humanReadableType;let t="Create new topic";return e.consensusCreateTopic.memo&&(t+=` with memo "${e.consensusCreateTopic.memo}"`),e.consensusCreateTopic.autoRenewAccountId&&(t+=`, auto-renew by ${e.consensusCreateTopic.autoRenewAccountId}`),t},us=e=>{if(!e.consensusSubmitMessage)return e.humanReadableType;let t="Submit message";if(e.consensusSubmitMessage.topicId&&(t+=` to topic ${e.consensusSubmitMessage.topicId}`),e.consensusSubmitMessage.message)if("utf8"===e.consensusSubmitMessage.messageEncoding){t+=`: "${e.consensusSubmitMessage.message.substring(0,70)}${e.consensusSubmitMessage.message.length>70?"...":""}"`}else{t+=` (binary message data, length: ${globalThis.Buffer.from(e.consensusSubmitMessage.message,"base64").length} bytes)`}return e.consensusSubmitMessage.chunkInfoNumber&&e.consensusSubmitMessage.chunkInfoTotal&&(t+=` (chunk ${e.consensusSubmitMessage.chunkInfoNumber}/${e.consensusSubmitMessage.chunkInfoTotal})`),t},ds=e=>{if(!e.fileCreate)return e.humanReadableType;let t="Create File";return e.fileCreate.memo&&(t+=` with memo "${e.fileCreate.memo}"`),e.fileCreate.contents&&(t+=" (includes content)"),t},ps=e=>e.fileAppend?`Append to File ${e.fileAppend.fileId||"(Unknown ID)"}`:e.humanReadableType,hs=e=>e.fileUpdate?`Update File ${e.fileUpdate.fileId||"(Unknown ID)"}`:e.humanReadableType,gs=e=>e.fileDelete?`Delete File ${e.fileDelete.fileId||"(Unknown ID)"}`:e.humanReadableType,ms=e=>e.consensusUpdateTopic?`Update Topic ${e.consensusUpdateTopic.topicId||"(Unknown ID)"}`:e.humanReadableType,fs=e=>e.consensusDeleteTopic?`Delete Topic ${e.consensusDeleteTopic.topicId||"(Unknown ID)"}`:e.humanReadableType,ys=e=>e.tokenFreeze?`Freeze Token ${e.tokenFreeze.tokenId} for Account ${e.tokenFreeze.accountId}`:e.humanReadableType,bs=e=>e.tokenUnfreeze?`Unfreeze Token ${e.tokenUnfreeze.tokenId} for Account ${e.tokenUnfreeze.accountId}`:e.humanReadableType,ws=e=>e.tokenGrantKyc?`Grant KYC for Token ${e.tokenGrantKyc.tokenId} to Account ${e.tokenGrantKyc.accountId}`:e.humanReadableType,Is=e=>e.tokenRevokeKyc?`Revoke KYC for Token ${e.tokenRevokeKyc.tokenId} from Account ${e.tokenRevokeKyc.accountId}`:e.humanReadableType,Ts=e=>e.tokenPause?`Pause Token ${e.tokenPause.tokenId}`:e.humanReadableType,Ss=e=>e.tokenUnpause?`Unpause Token ${e.tokenUnpause.tokenId}`:e.humanReadableType,ks=e=>{if(e.tokenWipeAccount){let t=`Wipe Token ${e.tokenWipeAccount.tokenId} from Account ${e.tokenWipeAccount.accountId}`;return e.tokenWipeAccount.serialNumbers&&e.tokenWipeAccount.serialNumbers.length>0&&(t+=` (Serials: ${e.tokenWipeAccount.serialNumbers.join(", ")})`),e.tokenWipeAccount.amount&&(t+=` (Amount: ${e.tokenWipeAccount.amount})`),t}return e.humanReadableType},vs=e=>e.tokenDelete?`Delete Token ${e.tokenDelete.tokenId}`:e.humanReadableType,Es=e=>e.tokenAssociate?`Associate Account ${e.tokenAssociate.accountId} with Tokens: ${(e.tokenAssociate.tokenIds||[]).join(", ")}`:e.humanReadableType,As=e=>e.tokenDissociate?`Dissociate Account ${e.tokenDissociate.accountId} from Tokens: ${(e.tokenDissociate.tokenIds||[]).join(", ")}`:e.humanReadableType,Cs=e=>e.cryptoDelete?`Delete Account ${e.cryptoDelete.deleteAccountId}`:e.humanReadableType,Rs=e=>{if(!e.cryptoCreateAccount)return e.humanReadableType;let t="Create Account";return e.cryptoCreateAccount.initialBalance&&"0"!==e.cryptoCreateAccount.initialBalance&&(t+=` with balance ${e.cryptoCreateAccount.initialBalance}`),e.cryptoCreateAccount.alias&&(t+=` (Alias: ${e.cryptoCreateAccount.alias})`),t},xs=e=>e.cryptoUpdateAccount?`Update Account ${e.cryptoUpdateAccount.accountIdToUpdate||"(Unknown ID)"}`:e.humanReadableType,Ns=e=>{if(e.cryptoApproveAllowance){let t=0;return e.cryptoApproveAllowance.hbarAllowances&&(t+=e.cryptoApproveAllowance.hbarAllowances.length),e.cryptoApproveAllowance.tokenAllowances&&(t+=e.cryptoApproveAllowance.tokenAllowances.length),e.cryptoApproveAllowance.nftAllowances&&(t+=e.cryptoApproveAllowance.nftAllowances.length),`Approve ${t} Crypto Allowance(s)`}return e.humanReadableType},zs=e=>{if(e.cryptoDeleteAllowance){return`Delete ${(e.cryptoDeleteAllowance.nftAllowancesToRemove||[]).length} NFT Crypto Allowance(s)`}return e.humanReadableType},_s=e=>{if(e.contractCreate){let t="Create Contract";return e.contractCreate.memo&&(t+=` (Memo: ${e.contractCreate.memo})`),t}return e.humanReadableType},Ps=e=>e.contractUpdate?`Update Contract ${e.contractUpdate.contractIdToUpdate||"(Unknown ID)"}`:e.humanReadableType,Os=e=>{if(e.contractDelete){let t=`Delete Contract ${e.contractDelete.contractIdToDelete||"(Unknown ID)"}`;return e.contractDelete.transferAccountId?t+=` (Transfer to Account: ${e.contractDelete.transferAccountId})`:e.contractDelete.transferContractId&&(t+=` (Transfer to Contract: ${e.contractDelete.transferContractId})`),t}return e.humanReadableType},Ds=e=>e.tokenUpdate?`Update Token ${e.tokenUpdate.tokenId||"(Unknown ID)"}`:e.humanReadableType,Fs=e=>e.tokenFeeScheduleUpdate?`Update Fee Schedule for Token ${e.tokenFeeScheduleUpdate.tokenId||"(Unknown ID)"}`:e.humanReadableType,Ms=e=>{if(!e.tokenAirdrop||!e.tokenAirdrop.tokenTransfers)return e.humanReadableType;let t=0,r=0;for(const i of e.tokenAirdrop.tokenTransfers)t+=1,r+=Array.isArray(i.transfers)?i.transfers.length:0;return`Token Airdrop across ${t} token(s), ${r} transfer(s)`},Us=e=>{if(!e.scheduleCreate)return e.humanReadableType;let t="Create Schedule";return e.scheduleCreate.memo&&(t+=` (Memo: ${e.scheduleCreate.memo})`),t},Bs=e=>e.scheduleSign?"Sign Schedule":e.humanReadableType,Ls=e=>e.scheduleDelete?"Delete Schedule":e.humanReadableType,Ks=e=>e.systemDelete?e.systemDelete.fileId?`System Delete File ${e.systemDelete.fileId}`:e.systemDelete.contractId?`System Delete Contract ${e.systemDelete.contractId}`:"System Delete":e.humanReadableType,$s=e=>e.systemUndelete?e.systemUndelete.fileId?`System Undelete File ${e.systemUndelete.fileId}`:e.systemUndelete.contractId?`System Undelete Contract ${e.systemUndelete.contractId}`:"System Undelete":e.humanReadableType,Hs=e=>"Network Freeze",qs=e=>"Ethereum Transaction",js=e=>e.uncheckedSubmit&&e.uncheckedSubmit.topicId?`Unchecked Submit to topic ${e.uncheckedSubmit.topicId}`:"Unchecked Submit",Ws=e=>"Create Node",Vs=e=>"Update Node",Gs=e=>"Delete Node",Js=e=>`Atomic Batch (${Array.isArray(e.atomicBatch?.transactions)?e.atomicBatch.transactions.length:0} transaction(s))`,Ys={CRYPTOTRANSFER:{fn:ns},cryptoTransfer:{fn:ns},CONTRACTCALL:{fn:os},contractCall:{fn:os},TOKENMINT:{fn:ss},tokenMint:{fn:ss},TOKENBURN:{fn:as},tokenBurn:{fn:as},TOKENCREATE:{fn:cs},tokenCreation:{fn:cs},TOPICCREATE:{fn:ls},consensusCreateTopic:{fn:ls},CONSENSUSSUBMITMESSAGE:{fn:us},consensusSubmitMessage:{fn:us},TOPICUPDATE:{fn:ms},consensusUpdateTopic:{fn:ms},TOPICDELETE:{fn:fs},consensusDeleteTopic:{fn:fs},FILECREATE:{fn:ds},fileCreate:{fn:ds},FILEAPPEND:{fn:ps},fileAppend:{fn:ps},FILEUPDATE:{fn:hs},fileUpdate:{fn:hs},FILEDELETE:{fn:gs},fileDelete:{fn:gs},TOKENUPDATE:{fn:Ds},tokenUpdate:{fn:Ds},TOKENFEESCHEDULEUPDATE:{fn:Fs},tokenFeeScheduleUpdate:{fn:Fs},TOKENFREEZE:{fn:ys},tokenFreeze:{fn:ys},TOKENUNFREEZE:{fn:bs},tokenUnfreeze:{fn:bs},TOKENGRANTKYC:{fn:ws},tokenGrantKyc:{fn:ws},TOKENREVOKEKYC:{fn:Is},tokenRevokeKyc:{fn:Is},TOKENPAUSE:{fn:Ts},tokenPause:{fn:Ts},TOKENUNPAUSE:{fn:Ss},tokenUnpause:{fn:Ss},TOKENWIPE:{fn:ks},TOKENWIPEACCOUNT:{fn:ks},tokenWipe:{fn:ks},tokenWipeAccount:{fn:ks},TOKENDELETE:{fn:vs},tokenDelete:{fn:vs},TOKENASSOCIATE:{fn:Es},tokenAssociate:{fn:Es},TOKENDISSOCIATE:{fn:As},tokenDissociate:{fn:As},ACCOUNTDELETE:{fn:Cs},cryptoDelete:{fn:Cs},ACCOUNTCREATE:{fn:Rs},cryptoCreateAccount:{fn:Rs},ACCOUNTUPDATE:{fn:xs},cryptoUpdateAccount:{fn:xs},APPROVEALLOWANCE:{fn:Ns},cryptoApproveAllowance:{fn:Ns},DELETEALLOWANCE:{fn:zs},cryptoDeleteAllowance:{fn:zs},CONTRACTCREATE:{fn:_s},contractCreate:{fn:_s},CONTRACTUPDATE:{fn:Ps},contractUpdate:{fn:Ps},CONTRACTDELETE:{fn:Os},contractDelete:{fn:Os},TOKENAIRDROP:{fn:Ms},tokenAirdrop:{fn:Ms},SCHEDULECREATE:{fn:Us},scheduleCreate:{fn:Us},SCHEDULESIGN:{fn:Bs},scheduleSign:{fn:Bs},SCHEDULEDELETE:{fn:Ls},scheduleDelete:{fn:Ls},SYSTEMDELETE:{fn:Ks},systemDelete:{fn:Ks},SYSTEMUNDELETE:{fn:$s},systemUndelete:{fn:$s},FREEZE:{fn:Hs},freeze:{fn:Hs},ETHEREUMTRANSACTION:{fn:qs},ethereumTransaction:{fn:qs},UNCHECKEDSUBMIT:{fn:js},uncheckedSubmit:{fn:js},NODECREATE:{fn:Ws},nodeCreate:{fn:Ws},NODEUPDATE:{fn:Vs},nodeUpdate:{fn:Vs},NODEDELETE:{fn:Gs},nodeDelete:{fn:Gs},ATOMICBATCH:{fn:Js},atomicBatch:{fn:Js}},Xs=e=>{const t=Ys[e.type];if(t){if(t.fn)return t.fn(e);if(t.template)return is(t.template,e)}const r=Ys[e.humanReadableType];if(r){if(r.fn)return r.fn(e);if(r.template)return is(r.template,e)}return"cryptoTransfer"===e.type||"CRYPTOTRANSFER"===e.type?ns(e):e.contractCall?os(e):Array.isArray(e.tokenTransfers)&&e.tokenTransfers.length>0?(e=>{const t=[],r=(e=>{const t={};for(const r of e)t[r.tokenId]||(t[r.tokenId]=[]),t[r.tokenId].push(r);return t})(e.tokenTransfers||[]);for(const[i,n]of Object.entries(r)){const e=[],r=[];for(const t of n){const i=parseFloat(String(t.amount));i<0?e.push(`${t.accountId} (${Math.abs(i)})`):i>0&&r.push(`${t.accountId} (${i})`)}e.length>0&&r.length>0&&t.push(`Transfer of token ${i} from ${e.join(", ")} to ${r.join(", ")}`)}return t.length>0?t.join("; "):e.humanReadableType})(e):e.humanReadableType&&"Unknown Transaction"!==e.humanReadableType?e.humanReadableType:"Unknown Transaction"};function Zs(e){if(e){if(e.contractID)return`ContractID: ${new r.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()}`;if(e.ed25519)return`ED25519: ${o.Buffer.from(e.ed25519).toString("hex")}`;if(e.ECDSASecp256k1)return`ECDSA_secp256k1: ${o.Buffer.from(e.ECDSASecp256k1).toString("hex")}`;if(e?.keyList?.keys?.length>0){const t=e.keyList.keys.map(e=>Zs(e)).filter(Boolean);return`KeyList (${t.length} keys): [${t.join(", ")}]`}if(e?.thresholdKey?.keys?.keys?.length>0){const t=e.thresholdKey.keys.keys.map(e=>Zs(e)).filter(Boolean);return`ThresholdKey (${e.thresholdKey.threshold} of ${t.length}): [${t.join(", ")}]`}return e.delegatableContractId?`DelegatableContractID: ${new r.ContractId(e.delegatableContractId.shardNum??0,e.delegatableContractId.realmNum??0,e.delegatableContractId.contractNum??0).toString()}`:0===Object.keys(e).length?"Empty Key Structure":"Unknown or Unset Key Type"}}function Qs(e){try{const t=e.toBytes?e.toBytes():void 0;if(!t)return null;const r=n.proto.TransactionList.decode(t);if(!r.transactionList||0===r.transactionList.length)return null;const i=r.transactionList[0];if(i.bodyBytes&&i.bodyBytes.length>0)return n.proto.TransactionBody.decode(i.bodyBytes);if(i.signedTransactionBytes&&i.signedTransactionBytes.length>0){const e=n.proto.SignedTransaction.decode(i.signedTransactionBytes);if(e.bodyBytes)return n.proto.TransactionBody.decode(e.bodyBytes)}return null}catch(t){return null}}function ea(e,t){const r=Qs(e);return!(!r||!r[t])}class ta{static parseHTSTransaction(e){try{const t=e._transactionBody;if(!t)return{};if(t.tokenCreation){const e=this.parseTokenCreate(t.tokenCreation);if(e)return{type:"TOKENCREATE",humanReadableType:"Token Creation",tokenCreation:e}}if(t.tokenMint){const e=this.parseTokenMint(t.tokenMint);if(e)return{type:"TOKENMINT",humanReadableType:"Token Mint",tokenMint:e}}if(t.tokenBurn){const e=this.parseTokenBurn(t.tokenBurn);if(e)return{type:"TOKENBURN",humanReadableType:"Token Burn",tokenBurn:e}}if(t.tokenUpdate){const e=this.parseTokenUpdate(t.tokenUpdate);if(e)return{type:"TOKENUPDATE",humanReadableType:"Token Update",tokenUpdate:e}}if(t.tokenFreeze){const e=this.parseTokenFreeze(t.tokenFreeze);if(e)return{type:"TOKENFREEZE",humanReadableType:"Token Freeze",tokenFreeze:e}}if(t.tokenUnfreeze){const e=this.parseTokenUnfreeze(t.tokenUnfreeze);if(e)return{type:"TOKENUNFREEZE",humanReadableType:"Token Unfreeze",tokenUnfreeze:e}}if(t.tokenGrantKyc){const e=this.parseTokenGrantKyc(t.tokenGrantKyc);if(e)return{type:"TOKENGRANTKYC",humanReadableType:"Token Grant KYC",tokenGrantKyc:e}}if(t.tokenRevokeKyc){const e=this.parseTokenRevokeKyc(t.tokenRevokeKyc);if(e)return{type:"TOKENREVOKEKYC",humanReadableType:"Token Revoke KYC",tokenRevokeKyc:e}}if(t.tokenPause){const e=this.parseTokenPause(t.tokenPause);if(e)return{type:"TOKENPAUSE",humanReadableType:"Token Pause",tokenPause:e}}if(t.tokenUnpause){const e=this.parseTokenUnpause(t.tokenUnpause);if(e)return{type:"TOKENUNPAUSE",humanReadableType:"Token Unpause",tokenUnpause:e}}if(t.tokenWipe){const e=this.parseTokenWipeAccount(t.tokenWipe);if(e)return{type:"TOKENWIPEACCOUNT",humanReadableType:"Token Wipe Account",tokenWipeAccount:e}}if(t.tokenDeletion){const e=this.parseTokenDelete(t.tokenDeletion);if(e)return{type:"TOKENDELETE",humanReadableType:"Token Delete",tokenDelete:e}}if(t.tokenAssociate){const e=this.parseTokenAssociate(t.tokenAssociate);if(e)return{type:"TOKENASSOCIATE",humanReadableType:"Token Associate",tokenAssociate:e}}if(t.tokenDissociate){const e=this.parseTokenDissociate(t.tokenDissociate);if(e)return{type:"TOKENDISSOCIATE",humanReadableType:"Token Dissociate",tokenDissociate:e}}if(t.tokenFeeScheduleUpdate){const e=this.parseTokenFeeScheduleUpdate(t.tokenFeeScheduleUpdate);if(e)return{type:"TOKENFEESCHEDULEUPDATE",humanReadableType:"Token Fee Schedule Update",tokenFeeScheduleUpdate:e}}const r=this.parseTokenAirdrop(e);return r?{type:"TOKENAIRDROP",humanReadableType:"Token Airdrop",tokenAirdrop:r}:{}}catch(t){return console.warn("[HTSParser] Failed to parse HTS transaction:",t),{}}}static parseTokenCreate(e){if(!e)return;const t={};return e.name&&(t.tokenName=e.name),e.symbol&&(t.tokenSymbol=e.symbol),e.treasury&&(t.treasuryAccountId=new r.AccountId(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),e.initialSupply&&(t.initialSupply=r.Long.fromValue(e.initialSupply).toString()),void 0!==e.decimals&&null!==e.decimals&&(t.decimals=r.Long.fromValue(e.decimals).toNumber()),e.maxSupply&&(t.maxSupply=r.Long.fromValue(e.maxSupply).toString()),e.memo&&(t.memo=e.memo),null!==e.tokenType&&void 0!==e.tokenType&&(t.tokenType=n.proto.TokenType[e.tokenType]),null!==e.supplyType&&void 0!==e.supplyType&&(t.supplyType=n.proto.TokenSupplyType[e.supplyType]),t.adminKey=Zs(e.adminKey),t.kycKey=Zs(e.kycKey),t.freezeKey=Zs(e.freezeKey),t.wipeKey=Zs(e.wipeKey),t.supplyKey=Zs(e.supplyKey),t.feeScheduleKey=Zs(e.feeScheduleKey),t.pauseKey=Zs(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccount=new r.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.customFees&&e.customFees.length>0&&(t.customFees=e.customFees.map(e=>{const t={feeCollectorAccountId:e.feeCollectorAccountId?new r.AccountId(e.feeCollectorAccountId.shardNum??0,e.feeCollectorAccountId.realmNum??0,e.feeCollectorAccountId.accountNum??0).toString():"Not Set",allCollectorsAreExempt:e.allCollectorsAreExempt||!1};if(e.fixedFee)return{...t,feeType:"FIXED_FEE",fixedFee:{amount:r.Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new r.TokenId(e.fixedFee.denominatingTokenId.shardNum??0,e.fixedFee.denominatingTokenId.realmNum??0,e.fixedFee.denominatingTokenId.tokenNum??0).toString():void 0}};if(e.fractionalFee)return{...t,feeType:"FRACTIONAL_FEE",fractionalFee:{numerator:r.Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:r.Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:r.Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:r.Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let i;return e.royaltyFee.fallbackFee&&(i={amount:r.Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new r.TokenId(e.royaltyFee.fallbackFee.denominatingTokenId.shardNum??0,e.royaltyFee.fallbackFee.denominatingTokenId.realmNum??0,e.royaltyFee.fallbackFee.denominatingTokenId.tokenNum??0).toString():void 0}),{...t,feeType:"ROYALTY_FEE",royaltyFee:{numerator:r.Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:r.Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:i}}}return{...t,feeType:"FIXED_FEE",fixedFee:{amount:"0"}}})),t}static parseTokenMint(e){if(!e||!e.token||null===e.amount||void 0===e.amount)return;const t={tokenId:new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:r.Long.fromValue(e.amount).toNumber()};return e.metadata&&e.metadata.length>0&&(t.metadata=e.metadata.map(e=>o.Buffer.from(e).toString("base64"))),t}static parseTokenBurn(e){if(!e||!e.token||null===e.amount||void 0===e.amount)return;const t={tokenId:new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:r.Long.fromValue(e.amount).toNumber()};return e.serialNumbers&&e.serialNumbers.length>0&&(t.serialNumbers=e.serialNumbers.map(e=>r.Long.fromValue(e).toNumber())),t}static parseTokenUpdate(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.name&&(t.name=e.name),e.symbol&&(t.symbol=e.symbol),e.treasury&&(t.treasuryAccountId=new r.AccountId(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),t.adminKey=Zs(e.adminKey),t.kycKey=Zs(e.kycKey),t.freezeKey=Zs(e.freezeKey),t.wipeKey=Zs(e.wipeKey),t.supplyKey=Zs(e.supplyKey),t.feeScheduleKey=Zs(e.feeScheduleKey),t.pauseKey=Zs(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccountId=new r.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),void 0!==e.memo?.value&&(t.memo=e.memo.value),e.expiry?.seconds&&(t.expiry=`${r.Long.fromValue(e.expiry.seconds).toString()}.${e.expiry.nanos}`),t}static parseTokenFeeScheduleUpdate(e){if(!e)return;const t={};return e.tokenId&&(t.tokenId=new r.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString()),e.customFees&&e.customFees.length>0&&(t.customFees=e.customFees.map(e=>{const t={feeCollectorAccountId:e.feeCollectorAccountId?new r.AccountId(e.feeCollectorAccountId.shardNum??0,e.feeCollectorAccountId.realmNum??0,e.feeCollectorAccountId.accountNum??0).toString():"Not Set",allCollectorsAreExempt:e.allCollectorsAreExempt||!1};if(e.fixedFee)return{...t,feeType:"FIXED_FEE",fixedFee:{amount:r.Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new r.TokenId(e.fixedFee.denominatingTokenId.shardNum??0,e.fixedFee.denominatingTokenId.realmNum??0,e.fixedFee.denominatingTokenId.tokenNum??0).toString():void 0}};if(e.fractionalFee)return{...t,feeType:"FRACTIONAL_FEE",fractionalFee:{numerator:r.Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:r.Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:r.Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:r.Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let i;return e.royaltyFee.fallbackFee&&(i={amount:r.Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new r.TokenId(e.royaltyFee.fallbackFee.denominatingTokenId.shardNum??0,e.royaltyFee.fallbackFee.denominatingTokenId.realmNum??0,e.royaltyFee.fallbackFee.denominatingTokenId.tokenNum??0).toString():void 0}),{...t,feeType:"ROYALTY_FEE",royaltyFee:{numerator:r.Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:r.Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:i}}}return{...t,feeType:"FIXED_FEE",fixedFee:{amount:"0"}}})),t}static parseTokenFreeze(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new r.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),t}static parseTokenUnfreeze(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new r.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),t}static parseTokenGrantKyc(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new r.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),t}static parseTokenRevokeKyc(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new r.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),t}static parseTokenPause(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),t}static parseTokenUnpause(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),t}static parseTokenWipeAccount(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new r.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),e.serialNumbers&&e.serialNumbers.length>0&&(t.serialNumbers=e.serialNumbers.map(e=>r.Long.fromValue(e).toString())),e.amount&&(t.amount=r.Long.fromValue(e.amount).toString()),t}static parseTokenDelete(e){if(!e)return;const t={};return e.token&&(t.tokenId=new r.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),t}static parseTokenAssociate(e){if(!e)return;const t={};return e.account&&(t.accountId=new r.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),e.tokens&&e.tokens.length>0&&(t.tokenIds=e.tokens.map(e=>new r.TokenId(e.shardNum??0,e.realmNum??0,e.tokenNum??0).toString())),t}static parseTokenDissociate(e){if(!e)return;const t={};return e.account&&(t.accountId=new r.AccountId(e.account.shardNum??0,e.account.realmNum??0,e.account.accountNum??0).toString()),e.tokens&&e.tokens.length>0&&(t.tokenIds=e.tokens.map(e=>new r.TokenId(e.shardNum??0,e.realmNum??0,e.tokenNum??0).toString())),t}static parseTokenAirdrop(e){try{const t=e._transactionBody;if(t?.tokenAirdrop){return{tokenTransfers:(t.tokenAirdrop.tokenTransfers||[]).map(e=>({tokenId:e.token?.toString()||"Unknown",transfers:(e.transfers||[]).map(e=>({accountId:e.accountID?.toString()||"Unknown",amount:e.amount?.toString()||"0",serialNumbers:e.serialNumbers?.map(e=>e.toString())}))}))}}if(ea(e,"tokenAirdrop")){const t=Qs(e);if(t?.tokenAirdrop)return this.parseTokenAirdropFromProto(t.tokenAirdrop)}const r=e._tokenTransfers||[];return r.length>0?{tokenTransfers:r.map(e=>({tokenId:e.tokenId?.toString()||"Unknown",transfers:(e.transfers||[]).map(e=>({accountId:e.accountId?.toString()||"Unknown",amount:e.amount?.toString()||"0",serialNumbers:e.serialNumbers?.map(e=>e.toString())}))}))}:null}catch(t){return console.warn("[HTSParser] Failed to parse token airdrop:",t),null}}static parseTokenAirdropFromProto(e){const t=[];if(e.tokenTransfers)for(const i of e.tokenTransfers){const e=i.token?new r.TokenId(i.token.shardNum??0,i.token.realmNum??0,i.token.tokenNum??0):null,n=[];if(i.transfers)for(const t of i.transfers){const e=t.accountID?new r.AccountId(t.accountID.shardNum??0,t.accountID.realmNum??0,t.accountID.accountNum??0):null;n.push({accountId:e?.toString()||"Unknown",amount:t.amount?r.Long.fromValue(t.amount).toString():"0",serialNumbers:t.serialNumbers?.map(e=>r.Long.fromValue(e).toString())})}t.push({tokenId:e?.toString()||"Unknown",transfers:n})}return{tokenTransfers:t}}static extractTokenCreationFromTransaction(e){try{const t=e;if(t._tokenName||t._tokenSymbol){const e={tokenName:t._tokenName||"Unknown Token",tokenSymbol:t._tokenSymbol||"UNKNOWN",initialSupply:t._initialSupply?.toString()||"0",decimals:Number(t._decimals||0),treasuryAccountId:t._treasuryAccountId?.toString()||"Unknown"};return t._maxSupply&&(e.maxSupply=t._maxSupply.toString()),t._tokenType&&(e.tokenType=t._tokenType.toString?t._tokenType.toString():String(t._tokenType)),t._supplyType&&(e.supplyType=t._supplyType.toString?t._supplyType.toString():String(t._supplyType)),t._tokenMemo&&(e.memo=t._tokenMemo),t._adminKey&&(e.adminKey=t._adminKey.toString()),t._kycKey&&(e.kycKey=t._kycKey.toString()),t._freezeKey&&(e.freezeKey=t._freezeKey.toString()),t._wipeKey&&(e.wipeKey=t._wipeKey.toString()),t._supplyKey&&(e.supplyKey=t._supplyKey.toString()),t._feeScheduleKey&&(e.feeScheduleKey=t._feeScheduleKey.toString()),t._pauseKey&&(e.pauseKey=t._pauseKey.toString()),t._metadataKey&&(e.metadataKey=t._metadataKey.toString()),t._autoRenewAccountId&&(e.autoRenewAccount=t._autoRenewAccountId.toString()),t._autoRenewPeriod&&(e.autoRenewPeriod=t._autoRenewPeriod.seconds?.toString()||t._autoRenewPeriod.toString()),t._expirationTime&&(e.expiry=t._expirationTime.seconds?.toString()||t._expirationTime.toString()),t._customFees&&Array.isArray(t._customFees)&&t._customFees.length>0&&(e.customFees=t._customFees.map(e=>{const t={feeCollectorAccountId:e.feeCollectorAccountId?.toString()||"",feeType:"FIXED_FEE"};return e.fixedFee?(t.feeType="FIXED_FEE",t.fixedFee={amount:e.fixedFee.amount?.toString()||"0",denominatingTokenId:e.fixedFee.denominatingTokenId?.toString()}):e.fractionalFee?(t.feeType="FRACTIONAL_FEE",t.fractionalFee={numerator:e.fractionalFee.numerator?.toString()||"0",denominator:e.fractionalFee.denominator?.toString()||"1",minimumAmount:e.fractionalFee.minimumAmount?.toString()||"0",maximumAmount:e.fractionalFee.maximumAmount?.toString()||"0",netOfTransfers:e.fractionalFee.netOfTransfers||!1}):e.royaltyFee&&(t.feeType="ROYALTY_FEE",t.royaltyFee={numerator:e.royaltyFee.numerator?.toString()||"0",denominator:e.royaltyFee.denominator?.toString()||"1",fallbackFee:e.royaltyFee.fallbackFee?{amount:e.royaltyFee.fallbackFee.amount?.toString()||"0",denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?.toString()}:void 0}),t.allCollectorsAreExempt=e.allCollectorsAreExempt||!1,t})),e}return null}catch(t){return null}}static extractTokenAirdropFromTransaction(e){try{const t=e;if(t._tokenAirdrops&&Array.isArray(t._tokenAirdrops)){return{tokenTransfers:t._tokenAirdrops.map(e=>({tokenId:e.tokenId?.toString()||"Unknown",transfers:(e.transfers||[]).map(e=>({accountId:e.accountId?.toString()||"Unknown",amount:e.amount?.toString()||"0",serialNumbers:e.serialNumbers?.map(e=>e.toString())||[]}))}))}}return null}catch(t){return null}}static parseFromTransactionObject(e){try{try{const t=e.toBytes?e.toBytes():void 0;if(t){const e=n.proto.TransactionList.decode(t);if(e.transactionList&&e.transactionList.length>0){const t=e.transactionList[0];let r=null;if(t.bodyBytes&&t.bodyBytes.length>0)r=n.proto.TransactionBody.decode(t.bodyBytes);else if(t.signedTransactionBytes&&t.signedTransactionBytes.length>0){const e=n.proto.SignedTransaction.decode(t.signedTransactionBytes);e.bodyBytes&&(r=n.proto.TransactionBody.decode(e.bodyBytes))}if(r){if(r.tokenCreation){const e=this.parseTokenCreate(r.tokenCreation);if(e)return{type:"TOKENCREATE",humanReadableType:"Token Creation",tokenCreation:e}}if(r.tokenMint){const e=this.parseTokenMint(r.tokenMint);if(e)return{type:"TOKENMINT",humanReadableType:"Token Mint",tokenMint:e}}if(r.tokenBurn){const e=this.parseTokenBurn(r.tokenBurn);if(e)return{type:"TOKENBURN",humanReadableType:"Token Burn",tokenBurn:e}}if(r.tokenUpdate){const e=this.parseTokenUpdate(r.tokenUpdate);if(e)return{type:"TOKENUPDATE",humanReadableType:"Token Update",tokenUpdate:e}}if(r.tokenFreeze){const e=this.parseTokenFreeze(r.tokenFreeze);if(e)return{type:"TOKENFREEZE",humanReadableType:"Token Freeze",tokenFreeze:e}}if(r.tokenUnfreeze){const e=this.parseTokenUnfreeze(r.tokenUnfreeze);if(e)return{type:"TOKENUNFREEZE",humanReadableType:"Token Unfreeze",tokenUnfreeze:e}}if(r.tokenGrantKyc){const e=this.parseTokenGrantKyc(r.tokenGrantKyc);if(e)return{type:"TOKENGRANTKYC",humanReadableType:"Token Grant KYC",tokenGrantKyc:e}}if(r.tokenRevokeKyc){const e=this.parseTokenRevokeKyc(r.tokenRevokeKyc);if(e)return{type:"TOKENREVOKEKYC",humanReadableType:"Token Revoke KYC",tokenRevokeKyc:e}}if(r.tokenPause){const e=this.parseTokenPause(r.tokenPause);if(e)return{type:"TOKENPAUSE",humanReadableType:"Token Pause",tokenPause:e}}if(r.tokenUnpause){const e=this.parseTokenUnpause(r.tokenUnpause);if(e)return{type:"TOKENUNPAUSE",humanReadableType:"Token Unpause",tokenUnpause:e}}if(r.tokenWipe){const e=this.parseTokenWipeAccount(r.tokenWipe);if(e)return{type:"TOKENWIPEACCOUNT",humanReadableType:"Token Wipe Account",tokenWipeAccount:e}}if(r.tokenDeletion){const e=this.parseTokenDelete(r.tokenDeletion);if(e)return{type:"TOKENDELETE",humanReadableType:"Token Delete",tokenDelete:e}}if(r.tokenAssociate){const e=this.parseTokenAssociate(r.tokenAssociate);if(e)return{type:"TOKENASSOCIATE",humanReadableType:"Token Associate",tokenAssociate:e}}if(r.tokenDissociate){const e=this.parseTokenDissociate(r.tokenDissociate);if(e)return{type:"TOKENDISSOCIATE",humanReadableType:"Token Dissociate",tokenDissociate:e}}if(r.tokenFeeScheduleUpdate){const e=this.parseTokenFeeScheduleUpdate(r.tokenFeeScheduleUpdate);if(e)return{type:"TOKENFEESCHEDULEUPDATE",humanReadableType:"Token Fee Schedule Update",tokenFeeScheduleUpdate:e}}if(r.tokenAirdrop){const e=this.parseTokenAirdropFromProto(r.tokenAirdrop);if(e)return{type:"TOKENAIRDROP",humanReadableType:"Token Airdrop",tokenAirdrop:e}}}}}}catch(zw){}const t=this.parseHTSTransaction(e);if(t.type)return t;const r=this.extractTokenCreationFromTransaction(e),i=this.extractTokenAirdropFromTransaction(e);return r?{type:"TOKENCREATE",humanReadableType:"Token Creation",tokenCreation:r}:i?{type:"TOKENAIRDROP",humanReadableType:"Token Airdrop",tokenAirdrop:i}:{}}catch(t){return{}}}}class ra{static parseConsensusCreateTopic(e){if(!e)return;const t={};return e.memo&&(t.memo=e.memo),t.adminKey=Zs(e.adminKey),t.submitKey=Zs(e.submitKey),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new r.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),t}static parseConsensusSubmitMessage(e){if(!e)return;const t={};if(e.topicID&&(t.topicId=`${e.topicID.shardNum??0}.${e.topicID.realmNum??0}.${e.topicID.topicNum??0}`),e.message?.length>0){const r=o.Buffer.from(e.message),i=r.toString("utf8");/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(i)||i.includes("�")?(t.message=r.toString("base64"),t.messageEncoding="base64"):(t.message=i,t.messageEncoding="utf8")}if(e.chunkInfo){if(e.chunkInfo.initialTransactionID){const r=e.chunkInfo.initialTransactionID.accountID,i=e.chunkInfo.initialTransactionID.transactionValidStart;r&&i&&(t.chunkInfoInitialTransactionID=`${r.shardNum??0}.${r.realmNum??0}.${r.accountNum??0}@${i.seconds??0}.${i.nanos??0}`)}void 0!==e.chunkInfo.number&&null!==e.chunkInfo.number&&(t.chunkInfoNumber=e.chunkInfo.number),void 0!==e.chunkInfo.total&&null!==e.chunkInfo.total&&(t.chunkInfoTotal=e.chunkInfo.total)}return t}static parseConsensusUpdateTopic(e){if(!e)return;const t={};return e.topicID&&(t.topicId=`${e.topicID.shardNum}.${e.topicID.realmNum}.${e.topicID.topicNum}`),void 0!==e.memo?.value&&(t.memo=e.memo.value),null===e.adminKey?(t.clearAdminKey=!0,t.adminKey=void 0):e.adminKey?t.adminKey=Zs(e.adminKey):t.adminKey=void 0,null===e.submitKey?(t.clearSubmitKey=!0,t.submitKey=void 0):e.submitKey?t.submitKey=Zs(e.submitKey):t.submitKey=void 0,e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new r.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),t}static parseConsensusDeleteTopic(e){if(!e)return;const t={};return e.topicID&&(t.topicId=`${e.topicID.shardNum}.${e.topicID.realmNum??0}.${e.topicID.topicNum??0}`),t}static parseFromTransactionObject(e){try{const t=e._transactionBody;if(!t)return{};if(t.consensusCreateTopic){const e=this.parseConsensusCreateTopic(t.consensusCreateTopic);if(e)return{type:"TOPICCREATE",humanReadableType:"Topic Create",consensusCreateTopic:e}}if(t.consensusSubmitMessage){const e=this.parseConsensusSubmitMessage(t.consensusSubmitMessage);if(e)return{type:"CONSENSUSSUBMITMESSAGE",humanReadableType:"Submit Message",consensusSubmitMessage:e}}if(t.consensusUpdateTopic){const e=this.parseConsensusUpdateTopic(t.consensusUpdateTopic);if(e)return{type:"TOPICUPDATE",humanReadableType:"Topic Update",consensusUpdateTopic:e}}if(t.consensusDeleteTopic){const e=this.parseConsensusDeleteTopic(t.consensusDeleteTopic);if(e)return{type:"TOPICDELETE",humanReadableType:"Topic Delete",consensusDeleteTopic:e}}return{}}catch(t){return{}}}}class ia{static parseFileTransaction(e,t){try{if(t||e.toBytes)try{const r=t||e.toBytes(),i=n.proto.TransactionList.decode(r);if(i.transactionList&&i.transactionList.length>0){const e=i.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=n.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const r=n.proto.SignedTransaction.decode(e.signedTransactionBytes);r.bodyBytes&&(t=n.proto.TransactionBody.decode(r.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(r){}return this.parseFromTransactionInternals(e)}catch(i){return{type:"UNKNOWN",humanReadableType:"Unknown File Transaction"}}}static parseFromProtobufTxBody(e){if(e.fileCreate){const t=this.parseFileCreate(e.fileCreate);if(t)return{type:"FILECREATE",humanReadableType:"File Create",fileCreate:t}}if(e.fileAppend){const t=this.parseFileAppend(e.fileAppend);if(t)return{type:"FILEAPPEND",humanReadableType:"File Append",fileAppend:t}}if(e.fileUpdate){const t=this.parseFileUpdate(e.fileUpdate);if(t)return{type:"FILEUPDATE",humanReadableType:"File Update",fileUpdate:t}}if(e.fileDelete){const t=this.parseFileDelete(e.fileDelete);if(t)return{type:"FILEDELETE",humanReadableType:"File Delete",fileDelete:t}}return{}}static parseFromTransactionInternals(e){try{const t=e;if(ea(e,"fileCreate")){const e={};if(t._contents){const r=this.analyzeContent(t._contents);e.contents=r.encoded,r.contentType&&(e.contentType=r.contentType),r.size&&(e.contentSize=r.size)}if(t._keys&&t._keys.length>0){const r={keys:t._keys};e.keys=Zs({keyList:r})}return t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),t._memo&&(e.memo=t._memo),{type:"FILECREATE",humanReadableType:"File Create",fileCreate:e}}if(ea(e,"fileAppend")){const e={fileId:t._fileId.toString()};if(t._contents){const r=this.analyzeContent(t._contents);e.contents=r.encoded,r.size&&(e.contentSize=r.size)}return{type:"FILEAPPEND",humanReadableType:"File Append",fileAppend:e}}if(ea(e,"fileUpdate")){const e={fileId:t._fileId.toString()};if(t._contents){const r=this.analyzeContent(t._contents);e.contents=r.encoded,r.size&&(e.contentSize=r.size)}if(t._keys&&t._keys.length>0){const r={keys:t._keys};e.keys=Zs({keyList:r})}return t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),t._memo&&(e.memo=t._memo),{type:"FILEUPDATE",humanReadableType:"File Update",fileUpdate:e}}if(ea(e,"fileDelete")){return{type:"FILEDELETE",humanReadableType:"File Delete",fileDelete:{fileId:t._fileId.toString()}}}return{}}catch(t){return{}}}static analyzeContent(e){const t=e.length,r=o.Buffer.from(e);let i,n;if(t>=4){i={"89504e47":"image/png",ffd8ffe0:"image/jpeg",ffd8ffe1:"image/jpeg",47494638:"image/gif",25504446:"application/pdf","504b0304":"application/zip","7f454c46":"application/x-executable",d0cf11e0:"application/msoffice"}[r.subarray(0,4).toString("hex").toLowerCase()]}if(!i)try{const e=r.toString("utf8"),t=/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(e),n=e.includes("�");i=t||n?"application/octet-stream":e.trim().startsWith("{")&&e.trim().endsWith("}")?"application/json":e.includes("<?xml")||e.includes("<html")?"text/xml":e.includes("<!DOCTYPE html")?"text/html":"text/plain"}catch{i="application/octet-stream"}if(i?.startsWith("text/")||"application/json"===i)try{n=r.toString("utf8"),(n.includes("�")||/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(n))&&(n=r.toString("base64"))}catch{n=r.toString("base64")}else n=r.toString("base64");return{encoded:n,contentType:i,size:t}}static parseFileCreate(e){if(!e)return;const t={};return e.expirationTime?.seconds&&(t.expirationTime=`${r.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=Zs({keyList:e.keys})),e.contents&&(t.contents=o.Buffer.from(e.contents).toString("base64")),e.memo&&(t.memo=e.memo),t}static parseFileAppend(e){if(!e)return;const t={};return e.fileID&&(t.fileId=`${e.fileID.shardNum??0}.${e.fileID.realmNum??0}.${e.fileID.fileNum??0}`),e.contents&&(t.contents=o.Buffer.from(e.contents).toString("base64")),t}static parseFileUpdate(e){if(!e)return;const t={};return e.fileID&&(t.fileId=`${e.fileID.shardNum??0}.${e.fileID.realmNum??0}.${e.fileID.fileNum??0}`),e.expirationTime?.seconds&&(t.expirationTime=`${r.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=Zs({keyList:e.keys})),e.contents&&(t.contents=o.Buffer.from(e.contents).toString("base64")),void 0!==e.memo?.value&&(t.memo=e.memo.value),t}static parseFileDelete(e){if(!e)return;const t={};return e.fileID&&(t.fileId=`${e.fileID.shardNum??0}.${e.fileID.realmNum??0}.${e.fileID.fileNum??0}`),t}static parseFromTransactionObject(e){return this.parseFileTransaction(e)}}class na{static parseCryptoTransfers(e,t){if(e.transfers?.accountAmounts&&(t.transfers=e.transfers.accountAmounts.map(e=>{const t=new r.AccountId(e.accountID.shardNum??0,e.accountID.realmNum??0,e.accountID.accountNum??0),i=r.Hbar.fromTinybars(r.Long.fromValue(e.amount));return{accountId:t.toString(),amount:i.toString(r.HbarUnit.Hbar),isDecimal:!0}})),e.tokenTransfers)for(const i of e.tokenTransfers){const e=new r.TokenId(i.token.shardNum??0,i.token.realmNum??0,i.token.tokenNum??0);if(i.transfers)for(const n of i.transfers){const i=new r.AccountId(n.accountID.shardNum??0,n.accountID.realmNum??0,n.accountID.accountNum??0),o=r.Long.fromValue(n.amount).toNumber();t.tokenTransfers.push({tokenId:e.toString(),accountId:i.toString(),amount:o})}}}static parseCryptoDelete(e){if(!e)return;const t={};return e.deleteAccountID&&(t.deleteAccountId=new r.AccountId(e.deleteAccountID.shardNum??0,e.deleteAccountID.realmNum??0,e.deleteAccountID.accountNum??0).toString()),e.transferAccountID&&(t.transferAccountId=new r.AccountId(e.transferAccountID.shardNum??0,e.transferAccountID.realmNum??0,e.transferAccountID.accountNum??0).toString()),t}static parseCryptoCreateAccount(e){if(!e)return;const t={};return e.initialBalance&&(t.initialBalance=r.Hbar.fromTinybars(r.Long.fromValue(e.initialBalance)).toString(r.HbarUnit.Hbar)),e.key&&(t.key=Zs(e.key)),void 0!==e.receiverSigRequired&&(t.receiverSigRequired=e.receiverSigRequired),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.memo&&(t.memo=e.memo),void 0!==e.maxAutomaticTokenAssociations&&(t.maxAutomaticTokenAssociations=e.maxAutomaticTokenAssociations),e.stakedAccountId?t.stakedAccountId=new r.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=r.Long.fromValue(e.stakedNodeId).toString()),void 0!==e.declineReward&&(t.declineReward=e.declineReward),e.alias&&e.alias.length>0&&(t.alias=globalThis.Buffer.from(e.alias).toString("hex")),t}static parseCryptoUpdateAccount(e){if(!e)return;const t={};return e.accountIDToUpdate&&(t.accountIdToUpdate=new r.AccountId(e.accountIDToUpdate.shardNum??0,e.accountIDToUpdate.realmNum??0,e.accountIDToUpdate.accountNum??0).toString()),e.key&&(t.key=Zs(e.key)),e.expirationTime?.seconds&&(t.expirationTime=`${r.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),null!==e.receiverSigRequired&&void 0!==e.receiverSigRequired&&(t.receiverSigRequired=Boolean(e.receiverSigRequired)),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),void 0!==e.memo?.value&&(t.memo=e.memo.value),void 0!==e.maxAutomaticTokenAssociations?.value&&(t.maxAutomaticTokenAssociations=e.maxAutomaticTokenAssociations.value),e.stakedAccountId?(t.stakedAccountId=new r.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString(),t.stakedNodeId=void 0):null!==e.stakedNodeId&&void 0!==e.stakedNodeId?(t.stakedNodeId=r.Long.fromValue(e.stakedNodeId).toString(),t.stakedAccountId=void 0):(t.stakedAccountId=void 0,t.stakedNodeId=void 0),null!==e.declineReward&&void 0!==e.declineReward&&(t.declineReward=Boolean(e.declineReward)),t}static parseCryptoApproveAllowance(e){if(!e)return;const t={};return e.cryptoAllowances&&e.cryptoAllowances.length>0&&(t.hbarAllowances=e.cryptoAllowances.map(e=>({ownerAccountId:new r.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new r.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount:r.Hbar.fromTinybars(r.Long.fromValue(e.amount)).toString(r.HbarUnit.Hbar)}))),e.tokenAllowances&&e.tokenAllowances.length>0&&(t.tokenAllowances=e.tokenAllowances.map(e=>({tokenId:new r.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),ownerAccountId:new r.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new r.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount:r.Long.fromValue(e.amount).toString()}))),e.nftAllowances&&e.nftAllowances.length>0&&(t.nftAllowances=e.nftAllowances.map(e=>{const t={};return e.tokenId&&(t.tokenId=new r.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString()),e.owner&&(t.ownerAccountId=new r.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString()),e.spender&&(t.spenderAccountId=new r.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString()),e.serialNumbers&&e.serialNumbers.length>0&&(t.serialNumbers=e.serialNumbers.map(e=>r.Long.fromValue(e).toString())),void 0!==e.approvedForAll?.value&&(t.approvedForAll=e.approvedForAll.value),e.delegatingSpender&&(t.delegatingSpender=new r.AccountId(e.delegatingSpender.shardNum??0,e.delegatingSpender.realmNum??0,e.delegatingSpender.accountNum??0).toString()),t})),t}static parseCryptoDeleteAllowance(e){if(!e)return;const t={};return e.nftAllowances&&e.nftAllowances.length>0&&(t.nftAllowancesToRemove=e.nftAllowances.map(e=>({ownerAccountId:new r.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),tokenId:new r.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),serialNumbers:e.serialNumbers?e.serialNumbers.map(e=>r.Long.fromValue(e).toString()):[]}))),t}static extractHbarTransfersFromTransaction(e){const t=[];try{const r=e._hbarTransfers;Array.isArray(r)&&r.forEach(e=>{if(e.accountId&&e.amount){const r=e.amount.toTinybars(),i=Number(r)/1e8;t.push({accountId:e.accountId.toString(),amount:i})}})}catch(r){}return t}static extractTokenTransfersFromTransaction(e){const t=[];try{const r=e._tokenTransfers;Array.isArray(r)&&r.forEach(e=>{if(e.tokenId&&Array.isArray(e.transfers)){const r=e.transfers.map(e=>({accountId:e.accountId?.toString()||"Unknown",amount:Number(e.amount||0)}));t.push({tokenId:e.tokenId.toString(),transfers:r})}})}catch(r){}return t}static parseFromTransactionObject(e){try{const t=this.extractHbarTransfersFromTransaction(e),r=this.extractTokenTransfersFromTransaction(e);if(t.length>0||r.length>0){const e=t.map(e=>({accountId:e.accountId,amount:e.amount.toString()+" ℏ",isDecimal:!0})),i=r.flatMap(e=>e.transfers.map(t=>({tokenId:e.tokenId,accountId:t.accountId,amount:t.amount})));if(t.length>0)return{type:"CRYPTOTRANSFER",humanReadableType:"Crypto Transfer",transfers:e,tokenTransfers:i};if(r.length>0)return{type:"TOKENTRANSFER",humanReadableType:"Token Transfer",transfers:e,tokenTransfers:i}}return{}}catch(t){return{}}}}class oa{static parseSCSTransaction(e,t){try{if(t||e.toBytes)try{const r=t||e.toBytes(),i=n.proto.TransactionList.decode(r);if(i.transactionList&&i.transactionList.length>0){const e=i.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=n.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const r=n.proto.SignedTransaction.decode(e.signedTransactionBytes);r.bodyBytes&&(t=n.proto.TransactionBody.decode(r.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(r){}return this.parseFromTransactionInternals(e)}catch(i){return{type:"UNKNOWN",humanReadableType:"Unknown Contract Transaction"}}}static parseFromProtobufTxBody(e){if(e.contractCall){const t=this.parseContractCall(e.contractCall);if(t)return{type:"CONTRACTCALL",humanReadableType:"Contract Call",contractCall:t}}if(e.contractCreateInstance){const t=this.parseContractCreate(e.contractCreateInstance);if(t)return{type:"CONTRACTCREATE",humanReadableType:"Contract Create",contractCreate:t}}if(e.contractUpdateInstance){const t=this.parseContractUpdate(e.contractUpdateInstance);if(t)return{type:"CONTRACTUPDATE",humanReadableType:"Contract Update",contractUpdate:t}}if(e.contractDeleteInstance){const t=this.parseContractDelete(e.contractDeleteInstance);if(t)return{type:"CONTRACTDELETE",humanReadableType:"Contract Delete",contractDelete:t}}if(e.ethereumTransaction){const t=this.parseEthereumTransaction(e.ethereumTransaction);if(t)return{type:"ETHEREUMTRANSACTION",humanReadableType:"Ethereum Transaction",ethereumTransaction:t}}return{}}static parseFromTransactionInternals(e){try{const t=e;if(t._contractId&&t._gas){const e={contractId:t._contractId.toString(),gas:"number"==typeof t._gas?t._gas:r.Long.fromValue(t._gas).toNumber(),amount:t._amount?parseFloat(t._amount.toString()):0};if(t._functionParameters){const r=o.Buffer.from(t._functionParameters).toString("hex");e.functionParameters=r,e.functionName=this.extractFunctionName(r)}return{type:"CONTRACTCALL",humanReadableType:"Contract Call",contractCall:e}}if(ea(e,"contractCreateInstance")){const e={gas:t._gas.toString(),initialBalance:t._initialBalance?.toString()||"0"};return t._fileId?(e.initcodeSource="fileID",e.initcode=t._fileId.toString()):t._bytecode&&(e.initcodeSource="bytes",e.initcode=o.Buffer.from(t._bytecode).toString("hex")),t._constructorParameters&&(e.constructorParameters=o.Buffer.from(t._constructorParameters).toString("hex")),t._memo&&(e.memo=t._memo),t._adminKey&&(e.adminKey=Zs(t._adminKey)),void 0!==t._maxAutomaticTokenAssociations&&(e.maxAutomaticTokenAssociations=t._maxAutomaticTokenAssociations),t._stakedAccountId?e.stakedAccountId=t._stakedAccountId.toString():null!==t._stakedNodeId&&void 0!==t._stakedNodeId&&(e.stakedNodeId=r.Long.fromValue(t._stakedNodeId).toString()),void 0!==t._declineReward&&(e.declineReward=t._declineReward),t._autoRenewPeriod&&(e.autoRenewPeriod=t._autoRenewPeriod.toString()),{type:"CONTRACTCREATE",humanReadableType:"Contract Create",contractCreate:e}}if(ea(e,"contractUpdateInstance")){const e={contractIdToUpdate:t._contractId.toString()};return t._memo&&(e.memo=t._memo),t._adminKey&&(e.adminKey=Zs(t._adminKey)),void 0!==t._maxAutomaticTokenAssociations&&(e.maxAutomaticTokenAssociations=t._maxAutomaticTokenAssociations),t._stakedAccountId?e.stakedAccountId=t._stakedAccountId.toString():null!==t._stakedNodeId&&void 0!==t._stakedNodeId&&(e.stakedNodeId=r.Long.fromValue(t._stakedNodeId).toString()),void 0!==t._declineReward&&(e.declineReward=t._declineReward),t._autoRenewPeriod&&(e.autoRenewPeriod=t._autoRenewPeriod.toString()),{type:"CONTRACTUPDATE",humanReadableType:"Contract Update",contractUpdate:e}}if(ea(e,"contractDeleteInstance")){const e={contractIdToDelete:t._contractId.toString()};return t._transferAccountId?e.transferAccountId=t._transferAccountId.toString():t._transferContractId&&(e.transferContractId=t._transferContractId.toString()),{type:"CONTRACTDELETE",humanReadableType:"Contract Delete",contractDelete:e}}return{}}catch(t){return{}}}static extractFunctionName(e){if(e.length<8)return"unknown";const t=e.substring(0,8);return{a9059cbb:"transfer","095ea7b3":"approve","23b872dd":"transferFrom","70a08231":"balanceOf",dd62ed3e:"allowance","18160ddd":"totalSupply","06fdde03":"name","95d89b41":"symbol","313ce567":"decimals","42842e0e":"safeTransferFrom",b88d4fde:"safeTransferFrom",e985e9c5:"isApprovedForAll",a22cb465:"setApprovalForAll","6352211e":"ownerOf",c87b56dd:"tokenURI","01ffc9a7":"supportsInterface","40c10f19":"mint","42966c68":"burn",f2fde38b:"transferOwnership","715018a6":"renounceOwnership","8da5cb5b":"owner"}[t]||t}static parseEthereumTransaction(e){if(!e)return;const t={contractId:"EVM",gas:e.maxGasAllowance?r.Long.fromValue(e.maxGasAllowance).toNumber():0,amount:0};if(e.ethereumData&&e.ethereumData.length>0){const r=o.Buffer.from(e.ethereumData).toString("hex");t.functionParameters=r,r.length>=8&&(t.functionName=this.extractFunctionName(r))}return t}static parseContractCall(e){if(!e)return;const t=r.Hbar.fromTinybars(r.Long.fromValue(e.amount??0)),i={contractId:new r.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString(),gas:r.Long.fromValue(e.gas??0).toNumber(),amount:parseFloat(t.toString(r.HbarUnit.Hbar))};return e.functionParameters&&(i.functionParameters=o.Buffer.from(e.functionParameters).toString("hex"),i.functionParameters.length>=8&&(i.functionName=this.extractFunctionName(i.functionParameters))),i}static parseContractCreate(e){if(!e)return;const t={};return e.initialBalance&&(t.initialBalance=r.Hbar.fromTinybars(r.Long.fromValue(e.initialBalance)).toString(r.HbarUnit.Hbar)),e.gas&&(t.gas=r.Long.fromValue(e.gas).toString()),e.adminKey&&(t.adminKey=Zs(e.adminKey)),e.constructorParameters&&(t.constructorParameters=o.Buffer.from(e.constructorParameters).toString("hex")),e.memo&&(t.memo=e.memo),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.stakedAccountId?t.stakedAccountId=new r.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=r.Long.fromValue(e.stakedNodeId).toString()),void 0!==e.declineReward&&(t.declineReward=e.declineReward),void 0!==e.maxAutomaticTokenAssociations&&(t.maxAutomaticTokenAssociations=e.maxAutomaticTokenAssociations),e.fileID?(t.initcodeSource="fileID",t.initcode=new r.FileId(e.fileID.shardNum??0,e.fileID.realmNum??0,e.fileID.fileNum??0).toString()):e.initcode&&e.initcode.length>0&&(t.initcodeSource="bytes",t.initcode=o.Buffer.from(e.initcode).toString("hex")),t}static parseContractUpdate(e){if(!e)return;const t={};if(e.contractID&&(t.contractIdToUpdate=new r.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.adminKey&&(t.adminKey=Zs(e.adminKey)),e.expirationTime?.seconds&&(t.expirationTime=`${r.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=r.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.memo){const r=e.memo;if(r&&"object"==typeof r&&Object.prototype.hasOwnProperty.call(r,"value")){const e=r.value;t.memo=null==e?void 0:String(e)}else t.memo="string"==typeof r?r:void 0}else t.memo=void 0;return e.stakedAccountId?(t.stakedAccountId=new r.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString(),t.stakedNodeId=void 0):null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&r.Long.fromValue(e.stakedNodeId).notEquals(-1)?(t.stakedNodeId=r.Long.fromValue(e.stakedNodeId).toString(),t.stakedAccountId=void 0):(t.stakedNodeId=void 0,t.stakedAccountId=void 0),void 0!==e.declineReward?.value&&(t.declineReward=e.declineReward.value),void 0!==e.maxAutomaticTokenAssociations?.value&&(t.maxAutomaticTokenAssociations=e.maxAutomaticTokenAssociations.value),e.autoRenewAccountId&&(t.autoRenewAccountId=new r.AccountId(e.autoRenewAccountId.shardNum??0,e.autoRenewAccountId.realmNum??0,e.autoRenewAccountId.accountNum??0).toString()),t}static parseContractDelete(e){if(!e)return;const t={};return e.contractID&&(t.contractIdToDelete=new r.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.transferAccountID?t.transferAccountId=new r.AccountId(e.transferAccountID.shardNum??0,e.transferAccountID.realmNum??0,e.transferAccountID.accountNum??0).toString():e.transferContractID&&(t.transferContractId=new r.ContractId(e.transferContractID.shardNum??0,e.transferContractID.realmNum??0,e.transferContractID.contractNum??0).toString()),t}static parseFromTransactionObject(e){return this.parseSCSTransaction(e)}}class sa{static parseUtilTransaction(e,t){try{if(t||e.toBytes)try{const r=t||e.toBytes(),i=n.proto.TransactionList.decode(r);if(i.transactionList&&i.transactionList.length>0){const e=i.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=n.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const r=n.proto.SignedTransaction.decode(e.signedTransactionBytes);r.bodyBytes&&(t=n.proto.TransactionBody.decode(r.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(r){}return this.parseFromTransactionInternals(e)}catch(i){return{type:"UNKNOWN",humanReadableType:"Unknown Utility Transaction"}}}static parseFromProtobufTxBody(e){if(e.utilPrng){const t=this.parseUtilPrng(e.utilPrng);if(t)return{type:"PRNG",humanReadableType:"Pseudo Random Number",utilPrng:t}}if(e.freeze){const t=this.parseNetworkFreezeFromProto(e.freeze);if(t)return{type:"FREEZE",humanReadableType:"Network Freeze",freeze:t}}if(e.systemDelete){const t=this.parseSystemDeleteFromProto(e.systemDelete);if(t)return{type:"SYSTEMDELETE",humanReadableType:"System Delete",systemDelete:t}}if(e.systemUndelete){const t=this.parseSystemUndeleteFromProto(e.systemUndelete);if(t)return{type:"SYSTEMUNDELETE",humanReadableType:"System Undelete",systemUndelete:t}}if(e.nodeCreate){const t=this.parseNodeCreateFromProto(e.nodeCreate);if(t)return{type:"NODECREATE",humanReadableType:"Node Create",nodeCreate:t}}if(e.nodeUpdate){const t=this.parseNodeUpdateFromProto(e.nodeUpdate);if(t)return{type:"NODEUPDATE",humanReadableType:"Node Update",nodeUpdate:t}}if(e.nodeDelete){const t=this.parseNodeDeleteFromProto(e.nodeDelete);if(t)return{type:"NODEDELETE",humanReadableType:"Node Delete",nodeDelete:t}}return{}}static parseFromTransactionInternals(e){try{const t=e;if(ea(e,"utilPrng")){const e={};return t._range&&0!==t._range&&(e.range=t._range),{type:"PRNG",humanReadableType:"Pseudo Random Number",utilPrng:e}}if(ea(e,"freeze")){const e={};return t._startTime&&(e.startTime=t._startTime.toString()),t._endTime&&(e.endTime=t._endTime.toString()),t._updateFile&&(e.updateFile=t._updateFile.toString()),t._fileHash&&(e.fileHash=globalThis.Buffer.from(t._fileHash).toString("hex")),t._freezeType&&(e.freezeType=t._freezeType),{type:"FREEZE",humanReadableType:"Network Freeze",freeze:e}}if(ea(e,"systemDelete")){const e={};return t._fileId?e.fileId=t._fileId.toString():t._contractId&&(e.contractId=t._contractId.toString()),t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),{type:"SYSTEMDELETE",humanReadableType:"System Delete",systemDelete:e}}if(ea(e,"systemUndelete")){const e={};return t._fileId?e.fileId=t._fileId.toString():t._contractId&&(e.contractId=t._contractId.toString()),{type:"SYSTEMUNDELETE",humanReadableType:"System Undelete",systemUndelete:e}}return{}}catch(t){return{}}}static parseNetworkFreezeFromProto(e){if(!e)return;const t={};if(e.startTime?.seconds&&(t.startTime=`${r.Long.fromValue(e.startTime.seconds).toString()}.${e.startTime.nanos??0}`),e.updateFile&&(t.updateFile=new r.FileId(e.updateFile.shardNum??0,e.updateFile.realmNum??0,e.updateFile.fileNum??0).toString()),e.fileHash&&e.fileHash.length>0&&(t.fileHash=globalThis.Buffer.from(e.fileHash).toString("hex")),void 0!==e.freezeType){const r=["FREEZE_ONLY","PREPARE_UPGRADE","FREEZE_UPGRADE","FREEZE_ABORT"];t.freezeType=r[e.freezeType]||"FREEZE_ONLY"}return t}static parseSystemDeleteFromProto(e){if(!e)return;const t={};return e.fileID?t.fileId=new r.FileId(e.fileID.shardNum??0,e.fileID.realmNum??0,e.fileID.fileNum??0).toString():e.contractID&&(t.contractId=new r.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.expirationTime?.seconds&&(t.expirationTime=r.Long.fromValue(e.expirationTime.seconds).toString()),t}static parseSystemUndeleteFromProto(e){if(!e)return;const t={};return e.fileID?t.fileId=new r.FileId(e.fileID.shardNum??0,e.fileID.realmNum??0,e.fileID.fileNum??0).toString():e.contractID&&(t.contractId=new r.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),t}static parseNodeCreateFromProto(e){if(!e)return;const t={};return void 0!==e.nodeId&&(t.nodeId=r.Long.fromValue(e.nodeId).toNumber()),t}static parseNodeUpdateFromProto(e){if(!e)return;const t={};return void 0!==e.nodeId&&(t.nodeId=r.Long.fromValue(e.nodeId).toNumber()),t}static parseNodeDeleteFromProto(e){if(!e)return;const t={};return void 0!==e.nodeId&&(t.nodeId=r.Long.fromValue(e.nodeId).toNumber()),t}static parseUtilPrng(e){if(!e)return;const t={};return e.range&&0!==e.range&&(t.range=e.range),t}static parseFreeze(e){return this.parseNetworkFreezeFromProto(e)}static parseFromTransactionObject(e){return this.parseUtilTransaction(e)}}class aa{static parseScheduleTransaction(e,t){try{if(t||e.toBytes)try{const r=t||e.toBytes(),i=n.proto.TransactionList.decode(r);if(i.transactionList&&i.transactionList.length>0){const e=i.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=n.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const r=n.proto.SignedTransaction.decode(e.signedTransactionBytes);r.bodyBytes&&(t=n.proto.TransactionBody.decode(r.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(r){}return this.parseFromTransactionInternals(e)}catch(i){return{type:"UNKNOWN",humanReadableType:"Unknown Schedule Transaction"}}}static parseFromProtobufTxBody(e){if(e.scheduleCreate){const t=this.parseScheduleCreateFromProto(e.scheduleCreate);if(t)return{type:"SCHEDULECREATE",humanReadableType:"Schedule Create",scheduleCreate:t}}if(e.scheduleSign){const t=this.parseScheduleSignFromProto(e.scheduleSign);if(t)return{type:"SCHEDULESIGN",humanReadableType:"Schedule Sign",scheduleSign:t}}if(e.scheduleDelete){const t=this.parseScheduleDeleteFromProto(e.scheduleDelete);if(t)return{type:"SCHEDULEDELETE",humanReadableType:"Schedule Delete",scheduleDelete:t}}return{}}static parseFromTransactionInternals(e){try{const t=e;if(ea(e,"scheduleCreate")){return{type:"SCHEDULECREATE",humanReadableType:"Schedule Create",scheduleCreate:{scheduledTransactionBody:globalThis.Buffer.from(t._scheduledTransaction).toString("base64"),memo:t._scheduleMemo,adminKey:t._adminKey?Zs(t._adminKey):void 0,payerAccountId:t._payerAccountId?.toString(),expirationTime:t._expirationTime?.toString(),waitForExpiry:t._waitForExpiry||!1}}}if(ea(e,"scheduleSign")){return{type:"SCHEDULESIGN",humanReadableType:"Schedule Sign",scheduleSign:{scheduleId:t._scheduleId.toString()}}}if(ea(e,"scheduleDelete")){return{type:"SCHEDULEDELETE",humanReadableType:"Schedule Delete",scheduleDelete:{scheduleId:t._scheduleId.toString()}}}return{}}catch(t){return{}}}static parseScheduleCreateFromProto(e){if(!e)return;const t={};if(e.scheduledTransactionBody){const r=n.proto.SchedulableTransactionBody.encode(n.proto.SchedulableTransactionBody.create(e.scheduledTransactionBody)).finish();t.scheduledTransactionBody=globalThis.Buffer.from(r).toString("base64")}return e.memo&&(t.memo=e.memo),e.adminKey&&(t.adminKey=Zs(e.adminKey)),e.payerAccountID&&(t.payerAccountId=new r.AccountId(e.payerAccountID.shardNum??0,e.payerAccountID.realmNum??0,e.payerAccountID.accountNum??0).toString()),e.expirationTime?.seconds&&(t.expirationTime=`${r.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos??0}`),void 0!==e.waitForExpiry&&(t.waitForExpiry=e.waitForExpiry),t}static parseScheduleSignFromProto(e){if(!e)return;const t={};return e.scheduleID&&(t.scheduleId=new r.ScheduleId(e.scheduleID.shardNum??0,e.scheduleID.realmNum??0,e.scheduleID.scheduleNum??0).toString()),t}static parseScheduleDeleteFromProto(e){if(!e)return;const t={};return e.scheduleID&&(t.scheduleId=new r.ScheduleId(e.scheduleID.shardNum??0,e.scheduleID.realmNum??0,e.scheduleID.scheduleNum??0).toString()),t}static parseScheduleCreate(e){try{return this.parseScheduleTransaction(e).scheduleCreate||null}catch(t){return console.warn("[ScheduleParser] Failed to parse schedule create:",t),null}}static parseScheduleSign(e){try{return this.parseScheduleTransaction(e).scheduleSign||null}catch(t){return console.warn("[ScheduleParser] Failed to parse schedule sign:",t),null}}static parseScheduleDelete(e){try{return this.parseScheduleTransaction(e).scheduleDelete||null}catch(t){return console.warn("[ScheduleParser] Failed to parse schedule delete:",t),null}}static extractScheduleInfo(e){try{const t=e._transactionBody;if(t?.scheduleRef)return{isScheduled:!0,scheduleRef:t.scheduleRef.toString()};const r=e;return r._scheduleId||r.scheduleId?{isScheduled:!0,scheduleRef:(r._scheduleId||r.scheduleId)?.toString()}:{isScheduled:!1}}catch(t){return{isScheduled:!1}}}static parseScheduledTransactionBody(e){try{let t;if(e.startsWith("0x")){const r=e.slice(2);t=new Uint8Array(globalThis.Buffer.from(r,"hex"))}else t=new Uint8Array(globalThis.Buffer.from(e,"base64"));const r=n.proto.SchedulableTransactionBody.decode(t),i=Object.keys(r).find(e=>null!==r[e]&&"transactionFee"!==e&&"memo"!==e);return i?{type:i.toUpperCase(),body:r[i],memo:r.memo,transactionFee:r.transactionFee?.toString()}:null}catch(t){return console.warn("[ScheduleParser] Failed to parse scheduled transaction body:",t),null}}static parseFromTransactionObject(e){return this.parseScheduleTransaction(e)}}const ca={TOKENCREATE:{bodyField:"tokenCreation",parser:ta.parseTokenCreate,resultField:"tokenCreation"},TOKENMINT:{bodyField:"tokenMint",parser:ta.parseTokenMint,resultField:"tokenMint"},TOKENBURN:{bodyField:"tokenBurn",parser:ta.parseTokenBurn,resultField:"tokenBurn"},TOKENUPDATE:{bodyField:"tokenUpdate",parser:ta.parseTokenUpdate,resultField:"tokenUpdate"},TOKENDELETE:{bodyField:"tokenDeletion",parser:ta.parseTokenDelete,resultField:"tokenDelete"},TOKENASSOCIATE:{bodyField:"tokenAssociate",parser:ta.parseTokenAssociate,resultField:"tokenAssociate"},TOKENDISSOCIATE:{bodyField:"tokenDissociate",parser:ta.parseTokenDissociate,resultField:"tokenDissociate"},TOKENFREEZE:{bodyField:"tokenFreeze",parser:ta.parseTokenFreeze,resultField:"tokenFreeze"},TOKENUNFREEZE:{bodyField:"tokenUnfreeze",parser:ta.parseTokenUnfreeze,resultField:"tokenUnfreeze"},TOKENGRANTKYC:{bodyField:"tokenGrantKyc",parser:ta.parseTokenGrantKyc,resultField:"tokenGrantKyc"},TOKENREVOKEKYC:{bodyField:"tokenRevokeKyc",parser:ta.parseTokenRevokeKyc,resultField:"tokenRevokeKyc"},TOKENPAUSE:{bodyField:"tokenPause",parser:ta.parseTokenPause,resultField:"tokenPause"},TOKENUNPAUSE:{bodyField:"tokenUnpause",parser:ta.parseTokenUnpause,resultField:"tokenUnpause"},TOKENWIPEACCOUNT:{bodyField:"tokenWipe",parser:ta.parseTokenWipeAccount,resultField:"tokenWipeAccount"},TOKENFEESCHEDULEUPDATE:{bodyField:"tokenFeeScheduleUpdate",parser:ta.parseTokenFeeScheduleUpdate,resultField:"tokenFeeScheduleUpdate"},TOKENAIRDROP:{bodyField:"tokenAirdrop",parser:ta.parseTokenAirdropFromProto,resultField:"tokenAirdrop"},TOPICCREATE:{bodyField:"consensusCreateTopic",parser:ra.parseConsensusCreateTopic,resultField:"consensusCreateTopic"},CONSENSUSSUBMITMESSAGE:{bodyField:"consensusSubmitMessage",parser:ra.parseConsensusSubmitMessage,resultField:"consensusSubmitMessage"},TOPICUPDATE:{bodyField:"consensusUpdateTopic",parser:ra.parseConsensusUpdateTopic,resultField:"consensusUpdateTopic"},TOPICDELETE:{bodyField:"consensusDeleteTopic",parser:ra.parseConsensusDeleteTopic,resultField:"consensusDeleteTopic"},ACCOUNTCREATE:{bodyField:"cryptoCreateAccount",parser:na.parseCryptoCreateAccount,resultField:"cryptoCreateAccount"},ACCOUNTUPDATE:{bodyField:"cryptoUpdateAccount",parser:na.parseCryptoUpdateAccount,resultField:"cryptoUpdateAccount"},ACCOUNTDELETE:{bodyField:"cryptoDelete",parser:na.parseCryptoDelete,resultField:"cryptoDelete"},CRYPTOTRANSFER:{bodyField:"cryptoTransfer",parser:e=>{const t={transfers:[],tokenTransfers:[]};return na.parseCryptoTransfers(e,t),t},resultField:"transfers",spreadResult:!0},APPROVEALLOWANCE:{bodyField:"cryptoApproveAllowance",parser:na.parseCryptoApproveAllowance,resultField:"cryptoApproveAllowance"},DELETEALLOWANCE:{bodyField:"cryptoDeleteAllowance",parser:na.parseCryptoDeleteAllowance,resultField:"cryptoDeleteAllowance"},FILECREATE:{bodyField:"fileCreate",parser:ia.parseFileCreate,resultField:"fileCreate"},FILEUPDATE:{bodyField:"fileUpdate",parser:ia.parseFileUpdate,resultField:"fileUpdate"},FILEDELETE:{bodyField:"fileDelete",parser:ia.parseFileDelete,resultField:"fileDelete"},FILEAPPEND:{bodyField:"fileAppend",parser:ia.parseFileAppend,resultField:"fileAppend"},CONTRACTCREATE:{bodyField:"contractCreateInstance",parser:oa.parseContractCreate,resultField:"contractCreate"},CONTRACTUPDATE:{bodyField:"contractUpdateInstance",parser:oa.parseContractUpdate,resultField:"contractUpdate"},CONTRACTDELETE:{bodyField:"contractDeleteInstance",parser:oa.parseContractDelete,resultField:"contractDelete"},CONTRACTCALL:{bodyField:"contractCall",parser:oa.parseContractCall,resultField:"contractCall"},ETHEREUMTRANSACTION:{bodyField:"ethereumTransaction",parser:oa.parseEthereumTransaction,resultField:"ethereumTransaction"},SCHEDULECREATE:{bodyField:"scheduleCreate",parser:aa.parseScheduleCreateFromProto,resultField:"scheduleCreate"},SCHEDULESIGN:{bodyField:"scheduleSign",parser:aa.parseScheduleSignFromProto,resultField:"scheduleSign"},SCHEDULEDELETE:{bodyField:"scheduleDelete",parser:aa.parseScheduleDeleteFromProto,resultField:"scheduleDelete"},PRNG:{bodyField:"utilPrng",parser:sa.parseUtilPrng,resultField:"utilPrng"},FREEZE:{bodyField:"freeze",parser:sa.parseFreeze,resultField:"freeze"},SYSTEMDELETE:{bodyField:"systemDelete",parser:e=>({fileId:e.fileID?`${e.fileID.shardNum}.${e.fileID.realmNum}.${e.fileID.fileNum}`:void 0,contractId:e.contractID?`${e.contractID.shardNum}.${e.contractID.realmNum}.${e.contractID.contractNum}`:void 0,expirationTime:e.expirationTime?.seconds?e.expirationTime.seconds.toString():void 0}),resultField:"systemDelete"},SYSTEMUNDELETE:{bodyField:"systemUndelete",parser:e=>({fileId:e.fileID?`${e.fileID.shardNum}.${e.fileID.realmNum}.${e.fileID.fileNum}`:void 0,contractId:e.contractID?`${e.contractID.shardNum}.${e.contractID.realmNum}.${e.contractID.contractNum}`:void 0}),resultField:"systemUndelete"},TOKENCANCELAIRDROP:{bodyField:"tokenCancelAirdrop",parser:e=>({pendingAirdrops:e.pendingAirdrops||[]}),resultField:"tokenCancelAirdrop"},TOKENCLAIMAIRDROP:{bodyField:"tokenClaimAirdrop",parser:e=>({pendingAirdrops:e.pendingAirdrops||[]}),resultField:"tokenClaimAirdrop"},TOKENREJECT:{bodyField:"tokenReject",parser:e=>({owner:e.owner?`${e.owner.shardNum}.${e.owner.realmNum}.${e.owner.accountNum}`:void 0,rejections:e.rejections||[]}),resultField:"tokenReject"},TOKENUPDATENFTS:{bodyField:"tokenUpdateNfts",parser:e=>({tokenId:e.token?`${e.token.shardNum}.${e.token.realmNum}.${e.token.tokenNum}`:void 0,serialNumbers:e.serialNumbers||[],metadata:e.metadata}),resultField:"tokenUpdateNfts"},TOKENWIPE:{bodyField:"tokenWipe",parser:ta.parseTokenWipeAccount,resultField:"tokenWipeAccount"},CRYPTOADDLIVEHASH:{bodyField:"cryptoAddLiveHash",parser:e=>({accountId:e.accountID?`${e.accountID.shardNum}.${e.accountID.realmNum}.${e.accountID.accountNum}`:void 0,liveHash:e.liveHash}),resultField:"cryptoAddLiveHash"},CRYPTODELETELIVEHASH:{bodyField:"cryptoDeleteLiveHash",parser:e=>({accountId:e.accountOfLiveHash?`${e.accountOfLiveHash.shardNum}.${e.accountOfLiveHash.realmNum}.${e.accountOfLiveHash.accountNum}`:void 0,liveHashToDelete:e.liveHashToDelete}),resultField:"cryptoDeleteLiveHash"},UNCHECKEDSUBMIT:{bodyField:"uncheckedSubmit",parser:e=>({topicId:e.topicID?`${e.topicID.shardNum}.${e.topicID.realmNum}.${e.topicID.topicNum}`:void 0,message:e.message}),resultField:"uncheckedSubmit"},NODECREATE:{bodyField:"nodeCreate",parser:e=>({accountId:e.accountId?`${e.accountId.shardNum}.${e.accountId.realmNum}.${e.accountId.accountNum}`:void 0,description:e.description,gossipEndpoint:e.gossipEndpoint,serviceEndpoint:e.serviceEndpoint,gossipCaCertificate:e.gossipCaCertificate,grpcCertificateHash:e.grpcCertificateHash,adminKey:e.adminKey}),resultField:"nodeCreate"},NODEUPDATE:{bodyField:"nodeUpdate",parser:e=>({nodeId:e.nodeId?.toString(),accountId:e.accountId?`${e.accountId.shardNum}.${e.accountId.realmNum}.${e.accountId.accountNum}`:void 0,description:e.description,gossipEndpoint:e.gossipEndpoint,serviceEndpoint:e.serviceEndpoint,gossipCaCertificate:e.gossipCaCertificate,grpcCertificateHash:e.grpcCertificateHash,adminKey:e.adminKey}),resultField:"nodeUpdate"},NODEDELETE:{bodyField:"nodeDelete",parser:e=>({nodeId:e.nodeId?.toString()}),resultField:"nodeDelete"},NODESTAKEUPDATE:{bodyField:"nodeStakeUpdate",parser:e=>({nodeId:e.nodeId?.toString(),maxStake:e.maxStake?.toString(),minStake:e.minStake?.toString(),rewardRate:e.rewardRate?.toString()}),resultField:"nodeStakeUpdate"},ATOMICBATCH:{bodyField:"atomicBatch",parser:e=>({transactions:e.transactions||[]}),resultField:"atomicBatch"},STATESIGNATURETRANSACTION:{bodyField:"stateSignatureTransaction",parser:e=>({signature:e.signature,round:e.round?.toString()}),resultField:"stateSignatureTransaction"},HISTORYPROOFSIGNATURE:{bodyField:"historyProofSignature",parser:e=>({signature:e.signature,round:e.round?.toString()}),resultField:"historyProofSignature"},HISTORYPROOFKEYPUBLICATION:{bodyField:"historyProofKeyPublication",parser:e=>({publicKey:e.publicKey,round:e.round?.toString()}),resultField:"historyProofKeyPublication"},HISTORYPROOFVOTE:{bodyField:"historyProofVote",parser:e=>({vote:e.vote,round:e.round?.toString()}),resultField:"historyProofVote"},HINTSPREPROCESSINGVOTE:{bodyField:"hintsPreprocessingVote",parser:e=>({vote:e.vote,round:e.round?.toString()}),resultField:"hintsPreprocessingVote"},HINTSKEYPUBLICATION:{bodyField:"hintsKeyPublication",parser:e=>({publicKey:e.publicKey,round:e.round?.toString()}),resultField:"hintsKeyPublication"},HINTSPARTIALSIGNATURE:{bodyField:"hintsPartialSignature",parser:e=>({signature:e.signature,round:e.round?.toString()}),resultField:"hintsPartialSignature"},CRSPUBLICATION:{bodyField:"crsPublication",parser:e=>({crs:e.crs,round:e.round?.toString()}),resultField:"crsPublication"}};const la={tokenCreation:{type:"TOKENCREATE",humanReadableType:"Token Creation"},tokenAirdrop:{type:"TOKENAIRDROP",humanReadableType:"Token Airdrop"},tokenMint:{type:"TOKENMINT",humanReadableType:"Token Mint"},tokenBurn:{type:"TOKENBURN",humanReadableType:"Token Burn"},tokenUpdate:{type:"TOKENUPDATE",humanReadableType:"Token Update"},tokenDeletion:{type:"TOKENDELETE",humanReadableType:"Token Deletion"},tokenAssociate:{type:"TOKENASSOCIATE",humanReadableType:"Token Association"},tokenDissociate:{type:"TOKENDISSOCIATE",humanReadableType:"Token Dissociation"},tokenFreeze:{type:"TOKENFREEZE",humanReadableType:"Token Freeze"},tokenUnfreeze:{type:"TOKENUNFREEZE",humanReadableType:"Token Unfreeze"},tokenGrantKyc:{type:"TOKENGRANTKYC",humanReadableType:"Token Grant KYC"},tokenRevokeKyc:{type:"TOKENREVOKEKYC",humanReadableType:"Token Revoke KYC"},tokenPause:{type:"TOKENPAUSE",humanReadableType:"Token Pause"},tokenUnpause:{type:"TOKENUNPAUSE",humanReadableType:"Token Unpause"},tokenWipe:{type:"TOKENWIPE",humanReadableType:"Token Wipe"},tokenFeeScheduleUpdate:{type:"TOKENFEESCHEDULEUPDATE",humanReadableType:"Token Fee Schedule Update"},tokenCancelAirdrop:{type:"TOKENCANCELAIRDROP",humanReadableType:"Cancel Token Airdrop"},tokenClaimAirdrop:{type:"TOKENCLAIMAIRDROP",humanReadableType:"Claim Token Airdrop"},tokenReject:{type:"TOKENREJECT",humanReadableType:"Token Reject"},tokenUpdateNfts:{type:"TOKENUPDATENFTS",humanReadableType:"Update NFT Metadata"},cryptoTransfer:{type:"CRYPTOTRANSFER",humanReadableType:"Crypto Transfer"},cryptoCreateAccount:{type:"ACCOUNTCREATE",humanReadableType:"Account Creation"},cryptoUpdateAccount:{type:"ACCOUNTUPDATE",humanReadableType:"Account Update"},cryptoDelete:{type:"ACCOUNTDELETE",humanReadableType:"Account Deletion"},cryptoApproveAllowance:{type:"APPROVEALLOWANCE",humanReadableType:"Approve Allowance"},cryptoDeleteAllowance:{type:"DELETEALLOWANCE",humanReadableType:"Delete Allowance"},cryptoAddLiveHash:{type:"CRYPTOADDLIVEHASH",humanReadableType:"Add Live Hash"},cryptoDeleteLiveHash:{type:"CRYPTODELETELIVEHASH",humanReadableType:"Delete Live Hash"},consensusCreateTopic:{type:"TOPICCREATE",humanReadableType:"Topic Creation"},consensusSubmitMessage:{type:"CONSENSUSSUBMITMESSAGE",humanReadableType:"Submit Message"},consensusUpdateTopic:{type:"TOPICUPDATE",humanReadableType:"Topic Update"},consensusDeleteTopic:{type:"TOPICDELETE",humanReadableType:"Topic Deletion"},uncheckedSubmit:{type:"UNCHECKEDSUBMIT",humanReadableType:"Unchecked Submit"},contractCall:{type:"CONTRACTCALL",humanReadableType:"Contract Call"},contractCreateInstance:{type:"CONTRACTCREATE",humanReadableType:"Contract Creation"},contractUpdateInstance:{type:"CONTRACTUPDATE",humanReadableType:"Contract Update"},contractDeleteInstance:{type:"CONTRACTDELETE",humanReadableType:"Contract Deletion"},ethereumTransaction:{type:"ETHEREUMTRANSACTION",humanReadableType:"Ethereum Transaction"},fileCreate:{type:"FILECREATE",humanReadableType:"File Creation"},fileUpdate:{type:"FILEUPDATE",humanReadableType:"File Update"},fileDelete:{type:"FILEDELETE",humanReadableType:"File Deletion"},fileAppend:{type:"FILEAPPEND",humanReadableType:"File Append"},scheduleCreate:{type:"SCHEDULECREATE",humanReadableType:"Schedule Creation"},scheduleSign:{type:"SCHEDULESIGN",humanReadableType:"Schedule Sign"},scheduleDelete:{type:"SCHEDULEDELETE",humanReadableType:"Schedule Deletion"},freeze:{type:"FREEZE",humanReadableType:"Network Freeze"},systemDelete:{type:"SYSTEMDELETE",humanReadableType:"System Delete"},systemUndelete:{type:"SYSTEMUNDELETE",humanReadableType:"System Undelete"},nodeCreate:{type:"NODECREATE",humanReadableType:"Node Creation"},nodeUpdate:{type:"NODEUPDATE",humanReadableType:"Node Update"},nodeDelete:{type:"NODEDELETE",humanReadableType:"Node Deletion"},nodeStakeUpdate:{type:"NODESTAKEUPDATE",humanReadableType:"Node Stake Update"},utilPrng:{type:"PRNG",humanReadableType:"Pseudo Random Number"},atomicBatch:{type:"ATOMICBATCH",humanReadableType:"Atomic Batch"},stateSignatureTransaction:{type:"STATESIGNATURETRANSACTION",humanReadableType:"State Signature"},historyProofSignature:{type:"HISTORYPROOFSIGNATURE",humanReadableType:"History Proof Signature"},historyProofKeyPublication:{type:"HISTORYPROOFKEYPUBLICATION",humanReadableType:"History Proof Key Publication"},historyProofVote:{type:"HISTORYPROOFVOTE",humanReadableType:"History Proof Vote"},hintsPreprocessingVote:{type:"HINTSPREPROCESSINGVOTE",humanReadableType:"Hints Preprocessing Vote"},hintsKeyPublication:{type:"HINTSKEYPUBLICATION",humanReadableType:"Hints Key Publication"},hintsPartialSignature:{type:"HINTSPARTIALSIGNATURE",humanReadableType:"Hints Partial Signature"},crsPublication:{type:"CRSPUBLICATION",humanReadableType:"CRS Publication"},transactionID:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},nodeAccountID:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},transactionFee:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},transactionValidDuration:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},generateRecord:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},memo:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},batchKey:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"},maxCustomFees:{type:"UNKNOWN",humanReadableType:"Unknown Transaction"}},ua={cryptoTransfer:"HBAR Transfer",CRYPTOTRANSFER:"HBAR Transfer",cryptoCreateAccount:"Create Account",ACCOUNTCREATE:"Create Account",cryptoUpdateAccount:"Update Account",ACCOUNTUPDATE:"Update Account",cryptoDeleteAccount:"Delete Account",cryptoDelete:"Delete Account",ACCOUNTDELETE:"Delete Account",cryptoApproveAllowance:"Approve Allowance",APPROVEALLOWANCE:"Approve Allowance",cryptoDeleteAllowance:"Delete Allowance",DELETEALLOWANCE:"Delete Allowance",CRYPTOADDLIVEHASH:"Add Live Hash",CRYPTODELETELIVEHASH:"Delete Live Hash",consensusCreateTopic:"Create Topic",TOPICCREATE:"Create Topic",consensusUpdateTopic:"Update Topic",TOPICUPDATE:"Update Topic",consensusSubmitMessage:"Submit Message",CONSENSUSSUBMITMESSAGE:"Submit Message",consensusDeleteTopic:"Delete Topic",TOPICDELETE:"Delete Topic",UNCHECKEDSUBMIT:"Unchecked Submit",fileCreate:"Create File",FILECREATE:"Create File",fileAppend:"Append File",FILEAPPEND:"Append File",fileUpdate:"Update File",FILEUPDATE:"Update File",fileDelete:"Delete File",FILEDELETE:"Delete File",contractCall:"Contract Call",CONTRACTCALL:"Contract Call",contractCreate:"Create Contract",CONTRACTCREATE:"Create Contract",contractUpdate:"Update Contract",CONTRACTUPDATE:"Update Contract",contractDelete:"Delete Contract",CONTRACTDELETE:"Delete Contract",ethereumTransaction:"Ethereum Transaction",ETHEREUMTRANSACTION:"Ethereum Transaction",tokenCreate:"Create Token",TOKENCREATE:"Create Token",tokenUpdate:"Update Token",TOKENUPDATE:"Update Token",tokenDelete:"Delete Token",TOKENDELETE:"Delete Token",tokenAssociate:"Associate Token",TOKENASSOCIATE:"Associate Token",tokenDissociate:"Dissociate Token",TOKENDISSOCIATE:"Dissociate Token",tokenMint:"Mint Token",TOKENMINT:"Mint Token",tokenBurn:"Burn Token",TOKENBURN:"Burn Token",tokenFeeScheduleUpdate:"Update Token Fee Schedule",TOKENFEESCHEDULEUPDATE:"Update Token Fee Schedule",tokenFreeze:"Freeze Token",TOKENFREEZE:"Freeze Token",tokenUnfreeze:"Unfreeze Token",TOKENUNFREEZE:"Unfreeze Token",tokenGrantKyc:"Grant KYC",TOKENGRANTKYC:"Grant KYC",tokenRevokeKyc:"Revoke KYC",TOKENREVOKEKYC:"Revoke KYC",tokenPause:"Pause Token",TOKENPAUSE:"Pause Token",tokenUnpause:"Unpause Token",TOKENUNPAUSE:"Unpause Token",tokenWipe:"Wipe Token",TOKENWIPE:"Wipe Token",tokenAirdrop:"Token Airdrop",TOKENAIRDROP:"Token Airdrop",TOKENCANCELAIRDROP:"Cancel Token Airdrop",TOKENCLAIMAIRDROP:"Claim Token Airdrop",TOKENREJECT:"Token Reject",TOKENUPDATENFTS:"Update NFT Metadata",scheduleCreate:"Create Schedule",SCHEDULECREATE:"Create Schedule",scheduleSign:"Sign Schedule",SCHEDULESIGN:"Sign Schedule",SCHEDULEDELETE:"Delete Schedule",FREEZE:"Network Freeze",SYSTEMDELETE:"System Delete",SYSTEMUNDELETE:"System Undelete",NODECREATE:"Create Node",NODEUPDATE:"Update Node",NODEDELETE:"Delete Node",NODESTAKEUPDATE:"Update Node Stake",utilPrng:"Generate Random Number",PRNG:"Generate Random Number",ATOMICBATCH:"Atomic Batch",STATESIGNATURETRANSACTION:"State Signature",HISTORYPROOFSIGNATURE:"History Proof Signature",HISTORYPROOFKEYPUBLICATION:"History Proof Key Publication",HISTORYPROOFVOTE:"History Proof Vote",HINTSPREPROCESSINGVOTE:"Hints Preprocessing Vote",HINTSKEYPUBLICATION:"Hints Key Publication",HINTSPARTIALSIGNATURE:"Hints Partial Signature",CRSPUBLICATION:"CRS Publication",unknown:"Unknown Transaction",UNKNOWN:"Unknown Transaction"},da={tokenCreation:"tokenCreate",tokenAirdrop:"tokenAirdrop",cryptoTransfer:"cryptoTransfer",consensusSubmitMessage:"consensusSubmitMessage",contractCall:"contractCall",cryptoCreateAccount:"cryptoCreateAccount",cryptoUpdateAccount:"cryptoUpdateAccount",cryptoApproveAllowance:"cryptoApproveAllowance",cryptoDeleteAllowance:"cryptoDeleteAllowance",cryptoDelete:"cryptoDelete",consensusCreateTopic:"consensusCreateTopic",consensusUpdateTopic:"consensusUpdateTopic",consensusDeleteTopic:"consensusDeleteTopic",fileCreate:"fileCreate",fileAppend:"fileAppend",fileUpdate:"fileUpdate",fileDelete:"fileDelete",contractCreateInstance:"contractCreate",contractUpdateInstance:"contractUpdate",contractDeleteInstance:"contractDelete",tokenUpdate:"tokenUpdate",tokenDeletion:"tokenDelete",tokenAssociate:"tokenAssociate",tokenDissociate:"tokenDissociate",tokenMint:"tokenMint",tokenBurn:"tokenBurn",tokenFeeScheduleUpdate:"tokenFeeScheduleUpdate",tokenFreeze:"tokenFreeze",tokenUnfreeze:"tokenUnfreeze",tokenGrantKyc:"tokenGrantKyc",tokenRevokeKyc:"tokenRevokeKyc",tokenPause:"tokenPause",tokenUnpause:"tokenUnpause",tokenWipe:"tokenWipe",utilPrng:"utilPrng"};function pa(e){for(const[t,r]of Object.entries(la))if(e[t])return r;return{type:"UNKNOWN",humanReadableType:"Unknown Transaction"}}function ha(e){return ua[e]||"Unknown Transaction"}class ga{static async parseTransactionBytes(e,t={}){const{enableFallback:r=!0,strictMode:i=!1,includeRaw:n=!0,maxRetries:o=2}=t,s=this.validateTransactionBytes(e);if(!s.isValid&&i)throw new rs(`Invalid transaction bytes format: ${s.error}`,"INVALID_FORMAT",void 0,e);let a,c=0;for(;c<=o;)try{const r=await this.parseTransaction(e,t);return r.formatDetection={originalFormat:s.format||"base64",wasConverted:"hex"===s.format,length:e.length},r}catch(u){if(a=u instanceof Error?u:new Error(String(u)),c++,!r||c>o){if(i)throw new rs("Failed to parse transaction after all attempts","PARSING_FAILED",a,e);break}try{const r=this.parseScheduledTransaction(e,t);return r.formatDetection={originalFormat:s.format||"base64",wasConverted:!1,length:e.length},r}catch(d){}}const l=this.createFallbackResult(e,a,void 0);return l.details&&(l.details.parseAttempts=Math.max(c,1)),l}static parseTransactionObject(e,t,r={}){let i,s;!t||o.Buffer.isBuffer(t)||t instanceof Uint8Array?(i=t,s=r):(s=t,i=void 0);try{const t=this.extractTransactionMetadata(e),r=ta.parseFromTransactionObject(e),o=na.parseFromTransactionObject(e),c=ra.parseFromTransactionObject(e),l=ia.parseFromTransactionObject(e),u=oa.parseFromTransactionObject(e),d=aa.parseFromTransactionObject(e),p=sa.parseFromTransactionObject(e),h=[r,o,c,l,u,d,p].find(e=>e.type&&"UNKNOWN"!==e.type)||{};let g,m="UNKNOWN",f="Unknown Transaction",y={};if(i||e.toBytes)try{const t=i||e.toBytes(),r=n.proto.TransactionList.decode(t);if(r.transactionList&&r.transactionList.length>0){const e=r.transactionList[0];if(e.bodyBytes&&e.bodyBytes.length>0){const t=n.proto.TransactionBody.decode(e.bodyBytes),r=this.detectTransactionTypeFromBody(t);m=r.type,f=r.humanReadableType,y=this.parseTransactionBodyDetails(t,m),y.tokenCreation&&(g=y.tokenCreation)}else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const t=n.proto.SignedTransaction.decode(e.signedTransactionBytes);if(t.bodyBytes){const e=n.proto.TransactionBody.decode(t.bodyBytes),r=this.detectTransactionTypeFromBody(e);m=r.type,f=r.humanReadableType,y=this.parseTransactionBodyDetails(e,m),y.tokenCreation&&(g=y.tokenCreation)}}}}catch(a){}"UNKNOWN"===m&&h.type&&(m=h.type,f=h.humanReadableType||f);const b={type:m,humanReadableType:f,transfers:[],tokenTransfers:[],...t,...h,raw:s.includeRaw?e._transactionBody||{}:void 0};return this.mergeProtoParsingResults(b,y,r,e,i),b.transfers=o.transfers||b.transfers||[],b.tokenTransfers=o.tokenTransfers||b.tokenTransfers||[],b}catch(c){return{type:"UNKNOWN",humanReadableType:"Unknown Transaction",transfers:[],tokenTransfers:[],raw:s.includeRaw?{}:void 0,details:{error:`Failed to parse Transaction object: ${c instanceof Error?c.message:String(c)}`}}}}static parseTransactionBody(e){try{const t=s.ethers.decodeBase64(e),i=n.proto.SchedulableTransactionBody.decode(t),o=this.getTransactionType(i),a={type:o,humanReadableType:this.getHumanReadableType(o),transfers:[],tokenTransfers:[],raw:i};if(i.memo&&(a.memo=i.memo),i.transactionFee){const e=r.Hbar.fromTinybars(r.Long.fromValue(i.transactionFee));a.transactionFee=e.toString(r.HbarUnit.Hbar)}return this.applySchedulableTransactionParsing(i,a),a}catch(t){return{type:"UNKNOWN",humanReadableType:"Unknown Transaction",transfers:[],tokenTransfers:[],raw:void 0,details:{error:`Failed to parse transaction body: ${t instanceof Error?t.message:String(t)}`}}}}static detectTransactionTypeFromBody(e){return pa(e)}static parseScheduleResponse(e){if(!e.transaction_body)return{type:"UNKNOWN",humanReadableType:"Unknown Transaction",transfers:[],tokenTransfers:[],raw:void 0,details:{error:"Schedule response missing transaction_body"}};const t=this.parseTransactionBody(e.transaction_body);return e.memo&&(t.memo=e.memo),t}static getTransactionType(e){return pa(e).type}static getHumanReadableType(e){return ha(e)}static getTransactionSummary(e){return Xs(e)}static validateTransactionBytes(e){if(!e||"string"!=typeof e)return{isValid:!1,error:"Transaction bytes must be a non-empty string"};const t=this.detectTransactionFormat(e),r=/^[A-Za-z0-9+/]*={0,2}$/;let i,n=!1;return"hex"===t?(n=/^0x[0-9a-fA-F]+$/.test(e)&&e.length>2,n||(i="Invalid hex format")):(n=r.test(e)&&e.length>0,n||(i="Invalid base64 format")),{isValid:n,format:t,error:i,length:e.length}}static detectTransactionFormat(e){return e.startsWith("0x")?"hex":"base64"}static decodeTransactionBytes(e){try{if("hex"===this.detectTransactionFormat(e)){const t=e.slice(2);return new Uint8Array(o.Buffer.from(t,"hex"))}return new Uint8Array(o.Buffer.from(e,"base64"))}catch(t){throw new rs("Failed to decode transaction bytes","DECODE_ERROR",t instanceof Error?t:void 0,e)}}static async isValidHederaTransaction(e){try{if(!this.validateTransactionBytes(e).isValid)return!1;const t=this.decodeTransactionBytes(e);return r.Transaction.fromBytes(t),!0}catch{return!1}}static decodeBytesLegacy(e){return this.decodeTransactionBytes(e)}static async parseTransaction(e,t={}){try{const i=this.decodeTransactionBytes(e),n=r.Transaction.fromBytes(i),o=this.extractTransactionMetadataEnhanced(n),s=this.runAllParsers(n),a=s.find(e=>e.type&&"UNKNOWN"!==e.type)||{},c=this.parseFromProtobuf(i),l=c.type||a.type||"UNKNOWN",u={type:l,humanReadableType:c.humanReadableType||a.humanReadableType||"Unknown Transaction",transfers:[],tokenTransfers:[],details:{...o},memo:"string"==typeof o.memo?o.memo:void 0,transactionId:"string"==typeof o.transactionId?o.transactionId:void 0,nodeAccountIds:Array.isArray(o.nodeAccountIds)?o.nodeAccountIds:[],maxTransactionFee:"string"==typeof o.maxTransactionFee?o.maxTransactionFee:void 0,validStart:"string"==typeof o.validStart?o.validStart:void 0,validDuration:"string"==typeof o.validDuration?o.validDuration:void 0,raw:t.includeRaw?{}:void 0};return this.mergeAllResults(u,c,a,s),u}catch(i){throw new rs("Failed to parse as regular transaction","REGULAR_PARSING_FAILED",i instanceof Error?i:void 0,e)}}static parseScheduledTransaction(e,t={}){try{const t=this.parseTransactionBody(e),r=this.validateTransactionBytes(e);return{...t,details:{...t.details||{},parseMethod:"scheduled",validation:r,parseAttempts:t.details?.parseAttempts||1},formatDetection:{originalFormat:r.format||"base64",wasConverted:!1,length:e.length}}}catch(r){throw new rs("Failed to parse as scheduled transaction","SCHEDULED_PARSING_FAILED",r instanceof Error?r:void 0,e)}}static extractTransactionMetadata(e){return{transactionId:e.transactionId?.toString(),nodeAccountIds:e.nodeAccountIds?.map(e=>e.toString())||[],maxTransactionFee:e.maxTransactionFee?.toTinybars().toString()||"0",memo:e._transactionMemo||void 0,transfers:[],tokenTransfers:[]}}static extractTransactionMetadataEnhanced(e){return{transactionId:e.transactionId?.toString(),nodeAccountIds:e.nodeAccountIds?.map(e=>e.toString())||[],maxTransactionFee:e.maxTransactionFee?.toTinybars().toString()||"0",memo:e._transactionMemo||void 0,validStart:e._transactionValidStart?.toString(),validDuration:e._transactionValidDuration?.toString()}}static runAllParsers(e){return[ta.parseFromTransactionObject(e),na.parseFromTransactionObject(e),ra.parseFromTransactionObject(e),ia.parseFromTransactionObject(e),oa.parseFromTransactionObject(e),aa.parseFromTransactionObject(e),sa.parseFromTransactionObject(e)]}static parseFromProtobuf(e){const t={};try{const r=n.proto.TransactionList.decode(e);if(r.transactionList&&r.transactionList.length>0){const e=r.transactionList[0];let i=null;if(e.bodyBytes&&e.bodyBytes.length>0)i=n.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const t=n.proto.SignedTransaction.decode(e.signedTransactionBytes);t.bodyBytes&&(i=n.proto.TransactionBody.decode(t.bodyBytes))}if(i){const e=this.detectTransactionTypeFromBody(i);t.type=e.type,t.humanReadableType=e.humanReadableType;const r=this.parseTransactionBodyDetails(i,e.type);Object.assign(t,r)}}}catch(r){}return t}static mergeAllResults(e,t,r,i){const n=i.find(e=>e.transfers||e.tokenTransfers)||{};e.transfers=n.transfers||e.transfers||[],e.tokenTransfers=n.tokenTransfers||e.tokenTransfers||[],Object.keys(t).forEach(r=>{void 0!==t[r]&&"type"!==r&&"humanReadableType"!==r&&(e[r]=t[r])}),Object.keys(r).forEach(t=>{void 0===r[t]||t in e||"type"===t||"humanReadableType"===t||(e[t]=r[t])})}static applySchedulableTransactionParsing(e,t){e.cryptoTransfer&&na.parseCryptoTransfers(e.cryptoTransfer,t),e.cryptoDelete&&(t.cryptoDelete=na.parseCryptoDelete(e.cryptoDelete)),e.cryptoCreateAccount&&(t.cryptoCreateAccount=na.parseCryptoCreateAccount(e.cryptoCreateAccount)),e.cryptoUpdateAccount&&(t.cryptoUpdateAccount=na.parseCryptoUpdateAccount(e.cryptoUpdateAccount)),e.cryptoApproveAllowance&&(t.cryptoApproveAllowance=na.parseCryptoApproveAllowance(e.cryptoApproveAllowance)),e.cryptoDeleteAllowance&&(t.cryptoDeleteAllowance=na.parseCryptoDeleteAllowance(e.cryptoDeleteAllowance)),e.contractCall&&(t.contractCall=oa.parseContractCall(e.contractCall)),e.contractCreateInstance&&(t.contractCreate=oa.parseContractCreate(e.contractCreateInstance)),e.contractUpdateInstance&&(t.contractUpdate=oa.parseContractUpdate(e.contractUpdateInstance)),e.contractDeleteInstance&&(t.contractDelete=oa.parseContractDelete(e.contractDeleteInstance)),e.tokenCreation&&(t.tokenCreation=ta.parseTokenCreate(e.tokenCreation)),e.tokenMint&&(t.tokenMint=ta.parseTokenMint(e.tokenMint)),e.tokenBurn&&(t.tokenBurn=ta.parseTokenBurn(e.tokenBurn)),e.tokenUpdate&&(t.tokenUpdate=ta.parseTokenUpdate(e.tokenUpdate)),e.tokenFeeScheduleUpdate&&(t.tokenFeeScheduleUpdate=ta.parseTokenFeeScheduleUpdate(e.tokenFeeScheduleUpdate)),e.tokenFreeze&&(t.tokenFreeze=ta.parseTokenFreeze(e.tokenFreeze)),e.tokenUnfreeze&&(t.tokenUnfreeze=ta.parseTokenUnfreeze(e.tokenUnfreeze)),e.tokenGrantKyc&&(t.tokenGrantKyc=ta.parseTokenGrantKyc(e.tokenGrantKyc)),e.tokenRevokeKyc&&(t.tokenRevokeKyc=ta.parseTokenRevokeKyc(e.tokenRevokeKyc)),e.tokenPause&&(t.tokenPause=ta.parseTokenPause(e.tokenPause)),e.tokenUnpause&&(t.tokenUnpause=ta.parseTokenUnpause(e.tokenUnpause)),e.tokenWipe&&(t.tokenWipeAccount=ta.parseTokenWipeAccount(e.tokenWipe)),e.tokenDeletion&&(t.tokenDelete=ta.parseTokenDelete(e.tokenDeletion)),e.tokenAssociate&&(t.tokenAssociate=ta.parseTokenAssociate(e.tokenAssociate)),e.tokenDissociate&&(t.tokenDissociate=ta.parseTokenDissociate(e.tokenDissociate)),e.tokenAirdrop&&(t.tokenAirdrop=ta.parseTokenAirdropFromProto(e.tokenAirdrop)),e.consensusCreateTopic&&(t.consensusCreateTopic=ra.parseConsensusCreateTopic(e.consensusCreateTopic)),e.consensusSubmitMessage&&(t.consensusSubmitMessage=ra.parseConsensusSubmitMessage(e.consensusSubmitMessage)),e.consensusUpdateTopic&&(t.consensusUpdateTopic=ra.parseConsensusUpdateTopic(e.consensusUpdateTopic)),e.consensusDeleteTopic&&(t.consensusDeleteTopic=ra.parseConsensusDeleteTopic(e.consensusDeleteTopic)),e.fileCreate&&(t.fileCreate=ia.parseFileCreate(e.fileCreate)),e.fileAppend&&(t.fileAppend=ia.parseFileAppend(e.fileAppend)),e.fileUpdate&&(t.fileUpdate=ia.parseFileUpdate(e.fileUpdate)),e.fileDelete&&(t.fileDelete=ia.parseFileDelete(e.fileDelete)),e.utilPrng&&(t.utilPrng=sa.parseUtilPrng(e.utilPrng))}static parseTransactionBodyDetails(e,t){const r={},i=ca[t];if(i){const t=e[i.bodyField];if(t){const e=i.parser(t);i.spreadResult?Object.assign(r,e):r[i.resultField]=e}}return r}static mergeProtoParsingResults(e,t,r,i,n){const o=Object.values(ca).map(e=>e.resultField);for(const s of o){const n=t[s],o=r[s];void 0!==n?e[s]=n:void 0!==o?e[s]=o:this.handleSpecialFieldExtraction(e,s,i)}}static handleSpecialFieldExtraction(e,t,r){if("tokenCreation"===t&&"TOKENCREATE"===e.type){const i=ta.extractTokenCreationFromTransaction(r);i&&(e[t]=i)}else if("tokenAirdrop"===t&&"TOKENAIRDROP"===e.type){const i=ta.extractTokenAirdropFromTransaction(r);i&&(e[t]=i)}}static createFallbackResult(e,t,r){const i=this.validateTransactionBytes(e);return{type:"UNKNOWN",humanReadableType:"Unknown Transaction",transfers:[],tokenTransfers:[],details:{rawBytes:e.length>100?e.substring(0,100)+"...":e,primaryError:t?.message,secondaryError:r?.message,parseAttempts:r?2:1,validation:i},formatDetection:{originalFormat:i.format||"base64",wasConverted:!1,length:e.length},raw:{}}}}const ma="undefined"!=typeof window&&void 0!==window.document;let fa;const ya=()=>"undefined"!=typeof process&&Boolean(process.versions?.node);function ba(){try{const e=process.getBuiltinModule?.("module");if("function"==typeof e?.createRequire){const t=e.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:p&&"SCRIPT"===p.tagName.toUpperCase()&&p.src||new URL("standards-sdk.cjs",document.baseURI).href);if("function"==typeof t.resolve)return t}const t="undefined"!=typeof global?global:globalThis,r=t.process?.mainModule?.require??t.require??Function('return typeof require === "function" ? require : undefined;')();if("function"==typeof r&&"function"==typeof r.resolve)return r}catch{return null}return null}function wa(e,t){if(!t||"object"!=typeof t)return!1;const r=Reflect.get(t,"code"),i=Reflect.get(t,"message"),n="string"==typeof i?i:"";if("string"==typeof r&&r.includes("MODULE_NOT_FOUND"))return n.includes(e);if(n){const t=n.toLowerCase();if(t.includes("cannot find module")||t.includes("module not found")||t.includes("cannot find package"))return t.includes(e.toLowerCase())}return!1}async function Ia(e){try{return await import(e)}catch(t){if(wa(e,t))return null;throw t}}async function Ta(e,t={}){if(ma&&!ya())return Ia(e);if(!t.preferImport){const t=await async function(){if(void 0!==fa)return fa;if(ma&&!ya())return fa=null,fa;try{fa=ba()}catch{fa=null}return fa}();if(t)try{return t(e)}catch(r){if(!wa(e,r))throw r}}return Ia(e)}function Sa(e){if(ma&&!ya())return null;try{const t=ba();if(t)return t(e)}catch(t){if(!wa(e,t))throw t}return null}const ka=new class{constructor(){this.cache=new Map,this.maxSize=100,this.defaultTtlMs=3e5}generateKey(e){return`${e.inputHash}-${e.clientConfigHash}-${e.optionsHash}`}hashObject(e){return globalThis.Buffer.from(JSON.stringify(e)).toString("base64").slice(0,16)}createCacheKey(e,t,r){return{inputHash:this.hashObject(e),clientConfigHash:this.hashObject({accountId:t.accountId,network:t.network}),optionsHash:this.hashObject({mode:r.mode,apiKey:r.apiKey?"present":"absent",network:r.network,metadata:r.metadata})}}get(e){const t=this.generateKey(e),r=this.cache.get(t);if(!r)return null;return Date.now()-r.timestamp>r.ttlMs?(this.cache.delete(t),null):(this.cache.delete(t),this.cache.set(t,r),r.quote)}set(e,t,r=this.defaultTtlMs){const i=this.generateKey(e);if(this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}this.cache.set(i,{quote:t,timestamp:Date.now(),ttlMs:r})}clear(){this.cache.clear()}},va=new class{constructor(){this.cache=new Map,this.maxSize=10,this.defaultTtlMs=18e5}generateConfigKey(e){return globalThis.Buffer.from(JSON.stringify(e)).toString("base64")}get(e){const t=this.generateConfigKey(e),r=this.cache.get(t);if(!r)return null;return Date.now()-r.timestamp>this.defaultTtlMs?(this.cache.delete(t),null):r.sdk}set(e,t){const r=this.generateConfigKey(e);if(this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}this.cache.set(r,{sdk:t,timestamp:Date.now(),config:r})}clear(){this.cache.clear()}};async function Ea(e,t,r){if(r)return r;const i=t.connectionMode??"websocket",n={apiKey:t.apiKey,accountId:e.accountId,network:e.network||"mainnet",authType:t.apiKey?"api":"server",connectionMode:i},o=va.get(n);if(o)return o;let s;return s=t.apiKey?new es({apiKey:t.apiKey,network:e.network||"mainnet",connectionMode:i}):await es.createWithAuth({type:"server",accountId:e.accountId,privateKey:"string"==typeof e.privateKey?e.privateKey:e.privateKey.toString(),network:e.network||"mainnet",connectionMode:i}),va.set(n,s),s}function Aa(e){return new a(e).dividedBy(1e8).toFixed()}function Ca(e){const{txn:t,payerAccountId:r}=e,i=(n=t.transfers,Array.isArray(n)?n.filter(e=>"number"==typeof e.amount&&e.amount>0).map(e=>({account:e.account,amountTinybar:e.amount})):[]);var n;const o=function(e,t){if(!Array.isArray(e))return null;const r=e.find(e=>e.account===t&&"number"==typeof e.amount&&e.amount<0);return r&&"number"==typeof r.amount?Math.abs(r.amount):null}(t.transfers,r),s=o??i.reduce((e,t)=>e+t.amountTinybar,0),a="number"==typeof(c=t.charged_tx_fee)&&Number.isFinite(c)?c<=0?null:c:null;var c;const l=s>0?s:a;if(!l||l<=0)return null;const u=Aa(l);return{totalTinybar:l,summary:{totalCostHbar:u,breakdown:{transfers:i.length>0?i.map(e=>({to:e.account,amount:Aa(e.amountTinybar),description:`HBAR transfer from ${r}`})):[{to:"Hedera network",amount:u,description:`Transaction fee debited from ${r}`}]}}}}let Ra={};const xa=e=>{if(!e.includes("@"))return e;const t=e?.split("@");return`${t[0]}-${t[1].replace(".","-")}`};const Na=1e3;async function za(e){if(ma)throw new Error("File path operations are not supported in browser environment. Use buffer input type instead.");if(await async function(){if(!ma&&!Ra.readFileSync)try{const[e,t]=await Promise.all([Ta("node:fs"),Ta("node:path")]);if(!e||!t)throw new Error("Node.js fs or path module not available");Ra.readFileSync=e.readFileSync,Ra.basename=t.basename,Ra.extname=t.extname}catch(e){y.getInstance({module:"Inscriber",level:"warn"}).warn("Node.js modules not available, file path operations will be disabled",{error:e instanceof Error?e.message:String(e)})}}(),!Ra.readFileSync||!Ra.basename||!Ra.extname)throw new Error("Node.js file system modules are not available. Cannot read file from path.");try{const r=Ra.readFileSync(e),i=r.toString("base64"),n=Ra.basename(e);let o="application/octet-stream";try{const e=await Ta("file-type"),t="function"==typeof e?.fileTypeFromBuffer?await e.fileTypeFromBuffer(r):void 0;t&&(o=t.mime)}catch(t){const r=Ra.extname(e).toLowerCase();o={".txt":"text/plain",".json":"application/json",".html":"text/html",".css":"text/css",".js":"application/javascript",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".pdf":"application/pdf"}[r]||"application/octet-stream"}return{base64:i,fileName:n,mimeType:o}}catch(r){throw new Error(`Failed to read file ${e}: ${r.message}`)}}function _a(e){return{accountId:e.accountId,privateKey:"string"==typeof e.privateKey?e.privateKey:e.privateKey.toString(),network:e.network}}function Pa(e){return e.connectionMode?e.connectionMode:"boolean"==typeof e.websocket?e.websocket?"websocket":"http":"websocket"}async function Oa(e,t,r,i){const n=y.getInstance({module:"Inscriber",...r.logging}),o=Pa(r);n.info("Starting inscription process",{type:e.type,mode:r.mode||"file",quoteOnly:r.quoteOnly||!1,..."url"===e.type?{url:e.url}:{},..."file"===e.type?{path:e.path}:{},..."buffer"===e.type?{fileName:e.fileName,bufferSize:e.buffer.byteLength}:{}});try{if(r.quoteOnly)return n.debug("Quote-only mode requested, generating quote"),await Ba(e,t,r,i);let s;if("hashinal"===r.mode&&r.metadata&&Ua(r.metadata,n),i)n.debug("Using existing InscriptionSDK instance"),s=i;else if(r.apiKey)n.debug("Initializing InscriptionSDK with API key"),s=new es({apiKey:r.apiKey,network:t.network||"mainnet",connectionMode:o,baseURL:r.baseURL});else{n.debug("Initializing InscriptionSDK with server auth");const e=_a(t);s=await es.createWithAuth({type:"server",accountId:e.accountId,privateKey:e.privateKey,network:e.network||"mainnet",connectionMode:o,baseUrl:r.baseURL})}const a={holderId:t.accountId,metadata:r.metadata||{},tags:r.tags||[],mode:r.mode||"file",fileStandard:r.fileStandard,chunkSize:r.chunkSize};let c;switch(e.type){case"url":c={...a,file:{type:"url",url:e.url}};break;case"file":{const t=await za(e.path);c={...a,file:{type:"base64",base64:t.base64,fileName:t.fileName,mimeType:t.mimeType}};break}case"buffer":c={...a,file:{type:"base64",base64:globalThis.Buffer.from(e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer):e.buffer).toString("base64"),fileName:e.fileName,mimeType:e.mimeType}}}"hashinal"===r.mode&&(c.metadataObject=r.metadata,c.creator=r.metadata?.creator||t.accountId,c.description=r.metadata?.description,r.jsonFileURL&&(c.jsonFileURL=r.jsonFileURL)),n.debug("Preparing to inscribe content",{type:e.type,mode:r.mode||"file",holderId:t.accountId});const l=_a(t),u=await s.inscribeAndExecute(c,l,r.progressCallback),d=u.jobId||u.tx_id||u.transactionId||"",p=u.transactionId||d||"",h=xa(d),g=xa(p),m=xa(h||g||d||u.jobId||"");if(n.info("Starting to inscribe.",{type:e.type,mode:r.mode||"file",transactionId:u.jobId}),r.waitForConfirmation){n.debug("Waiting for inscription confirmation",{transactionId:m,maxAttempts:r.waitMaxAttempts,intervalMs:r.waitIntervalMs});const e=await La(s,m,r.waitMaxAttempts,r.waitIntervalMs,r.progressCallback);return n.info("Inscription confirmation received",{transactionId:u.jobId}),{confirmed:!0,result:{...u,jobId:m,transactionId:g},inscription:e,sdk:s,costSummary:await Da(g,t.network||"mainnet",r.logging?.level)}}return{confirmed:!1,result:{...u,jobId:m,transactionId:g},sdk:s,costSummary:await Da(g,t.network||"mainnet",r.logging?.level)}}catch(s){throw n.error("Error during inscription process",s),s}}async function Da(e,t,r){const i=y.getInstance({module:"InscriberCost",level:r??"info"}),n=new x(t,i),o=xa(e),s=o.split("-")[0];for(let c=0;c<3;c++)try{const e=await n.getTransaction(o);if(!e){c<2&&await b(Na);continue}const t=Ca({txn:e,payerAccountId:s});if(!t){c<2&&await b(Na);continue}return t.summary}catch(a){i.warn("Unable to resolve inscription cost",{transactionId:o,attempt:c+1,error:a instanceof Error?a.message:String(a)}),c<2&&await b(Na)}}async function Fa(e,t,r,i){const n=y.getInstance({module:"Inscriber",...r.logging}),o=Pa(r);n.info("Starting inscription process with signer",{type:e.type,mode:r.mode||"file",quoteOnly:r.quoteOnly||!1,..."url"===e.type?{url:e.url}:{},..."file"===e.type?{path:e.path}:{},..."buffer"===e.type?{fileName:e.fileName,bufferSize:e.buffer.byteLength}:{}});try{if(r.quoteOnly){n.debug("Quote-only mode requested with signer, generating quote");const o={accountId:t.getAccountId().toString(),privateKey:"",network:r.network||"mainnet"};return await Ba(e,o,r,i)}"hashinal"===r.mode&&r.metadata&&Ua(r.metadata,n);const s=t.getAccountId().toString();let a;n.debug("Using account ID from signer",{accountId:s}),i?(n.debug("Using existing InscriptionSDK instance"),a=i):r.apiKey?(n.debug("Initializing InscriptionSDK with API key"),a=new es({apiKey:r.apiKey,network:r.network||"mainnet",connectionMode:o,baseURL:r.baseURL})):(n.debug("Initializing InscriptionSDK with client auth (websocket)"),a=await es.createWithAuth({type:"client",accountId:s,signer:t,network:r.network||"mainnet",connectionMode:o,baseUrl:r.baseURL}));const c={holderId:s,metadata:r.metadata||{},tags:r.tags||[],mode:r.mode||"file",fileStandard:r.fileStandard,chunkSize:r.chunkSize};let l;switch(e.type){case"url":l={...c,file:{type:"url",url:e.url}};break;case"file":{const t=await za(e.path);l={...c,file:{type:"base64",base64:t.base64,fileName:t.fileName,mimeType:t.mimeType}};break}case"buffer":l={...c,file:{type:"base64",base64:globalThis.Buffer.from(e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer):e.buffer).toString("base64"),fileName:e.fileName,mimeType:e.mimeType}}}"hashinal"===r.mode&&(l.metadataObject=r.metadata,l.creator=r.metadata?.creator||s,l.description=r.metadata?.description,r.jsonFileURL&&(l.jsonFileURL=r.jsonFileURL)),n.debug("Starting inscription via startInscription (websocket)",{type:e.type,mode:r.mode||"file",holderId:s,usesStartInscription:!0});const u=await a.startInscription({...l,holderId:s,network:r.network||"mainnet"}),d="string"==typeof u?.tx_id&&u.tx_id.trim()||"string"==typeof u?.jobId&&(u.jobId||"").trim()||"string"==typeof u?.id&&(u.id||"").trim()||"",p=xa(d);if(!p)throw new Error("startInscription did not return a transaction id");if(n.info("about to start inscription",{type:e.type,mode:r.mode||"file",jobId:p,...u}),"string"==typeof u?.transactionBytes?(n.debug("Executing inscription transaction with signer from bytes"),await a.executeTransactionWithSigner(u.transactionBytes,t)):"Buffer"===u?.transactionBytes?.type&&(n.debug("Executing inscription transaction with signer from buffer"),await a.executeTransactionWithSigner(globalThis.Buffer.from(u.transactionBytes.data).toString("base64"),t)),r.waitForConfirmation){n.debug("Waiting for inscription confirmation (websocket)",{jobId:p,maxAttempts:r.waitMaxAttempts,intervalMs:r.waitIntervalMs});const e=await La(a,p,r.waitMaxAttempts,r.waitIntervalMs,r.progressCallback);return n.info("Inscription confirmation received",{jobId:p}),{confirmed:!0,result:{jobId:p,transactionId:p,topic_id:u.topic_id,status:u.status,completed:u.completed},inscription:e,sdk:a,costSummary:await Da(p,r.network||"mainnet",r.logging?.level)}}return{confirmed:!1,result:{jobId:p,transactionId:p,topic_id:u.topic_id,status:u.status,completed:u.completed},sdk:a,costSummary:await Da(p,r.network||"mainnet",r.logging?.level)}}catch(s){throw n.error("Error during inscription process",s),s}}async function Ma(e,t){const r=y.getInstance({module:"Inscriber",...t?.logging||{}}),i=e.includes("@")?`${e.split("@")[0]}-${e.split("@")[1].replace(/\./g,"-")}`:e;r.info("Retrieving inscription",{originalTransactionId:e,formattedTransactionId:i});try{let e;if(t?.apiKey)r.debug("Initializing InscriptionSDK with API key"),e=new es({apiKey:t.apiKey,network:t.network||"mainnet",baseURL:t.baseURL});else{if(!t?.accountId||!t?.privateKey){const e=new Error("Either API key or account ID and private key are required for retrieving inscriptions");throw r.error("Missing authentication credentials",{hasApiKey:Boolean(t?.apiKey),hasAccountId:Boolean(t?.accountId),hasPrivateKey:Boolean(t?.privateKey)}),e}r.debug("Initializing InscriptionSDK with server auth"),e=await es.createWithAuth({type:"server",accountId:t.accountId,privateKey:t.privateKey,network:t.network||"mainnet",baseUrl:t.baseURL})}r.debug("Initialized SDK for inscription retrieval",{formattedTransactionId:i,network:t.network||"mainnet"});const n=await e.retrieveInscription(i);return r.info("Successfully retrieved inscription",{formattedTransactionId:i}),n}catch(n){throw r.error("Error retrieving inscription",{formattedTransactionId:i,error:n}),n}}function Ua(e,t){const r=["name","creator","description","type"].filter(t=>!e[t]);if(r.length>0){const e=new Error(`Missing required Hashinal metadata fields: ${r.join(", ")}`);throw t.error("Hashinal metadata validation failed",{missingFields:r}),e}t.debug("Hashinal metadata validation passed",{name:e.name,creator:e.creator,description:e.description,type:e.type,hasAttributes:!!e.attributes,hasProperties:!!e.properties})}async function Ba(e,t,r,i){const n=y.getInstance({module:"Inscriber",...r.logging});n.info("Generating inscription quote",{type:e.type,mode:r.mode||"file",..."url"===e.type?{url:e.url}:{},..."file"===e.type?{path:e.path}:{},..."buffer"===e.type?{fileName:e.fileName,bufferSize:e.buffer.byteLength}:{}});try{!function(e,t,r){if(!e||"object"!=typeof e||!("type"in e))throw new Error("Invalid inscription input: type is required");if(!t||!t.accountId)throw new Error("Invalid client config: accountId is required");if(!r)throw new Error("Options are required");if("hashinal"===r.mode){if(!r.metadata)throw new Error("Hashinal mode requires metadata");const e=["name","creator","description","type"].filter(e=>!r.metadata||!r.metadata[e]);if(e.length>0)throw new Error(`Missing required Hashinal metadata fields: ${e.join(", ")}`)}}(e,t,r);const o=function(e,t,r){const i=ka.createCacheKey(e,t,r);return ka.get(i)}(e,t,r);if(o)return n.debug("Returning cached quote"),{confirmed:!1,quote:!0,result:o};"hashinal"===r.mode&&r.metadata&&Ua(r.metadata,n);const s=await Ea(t,r,i),a={holderId:t.accountId,metadata:r.metadata||{},tags:r.tags||[],mode:r.mode||"file",fileStandard:r.fileStandard,chunkSize:r.chunkSize};let c;switch(e.type){case"url":c={...a,file:{type:"url",url:e.url}};break;case"file":{const t=await za(e.path);c={...a,file:{type:"base64",base64:t.base64,fileName:t.fileName,mimeType:t.mimeType}};break}case"buffer":c={...a,file:{type:"base64",base64:globalThis.Buffer.from(e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer):e.buffer).toString("base64"),fileName:e.fileName,mimeType:e.mimeType}}}"hashinal"===r.mode&&(c.metadataObject=r.metadata,c.creator=r.metadata?.creator||t.accountId,c.description=r.metadata?.description,r.jsonFileURL&&(c.jsonFileURL=r.jsonFileURL)),n.debug("Calling inscription SDK startInscription for quote",{type:e.type,mode:r.mode||"file",holderId:t.accountId});const l=await s.startInscription(c);n.debug("Received inscription response for quote parsing",{hasTransactionBytes:!!l.transactionBytes,bytesLength:l.transactionBytes?.length||0,transactionBytesType:typeof l.transactionBytes,totalCost:l.totalCost});const u=await async function(e,t){try{let i="0.001";if(e.totalCost&&"number"==typeof e.totalCost){i=(e.totalCost/1e8).toString(),t.debug("Using totalCost from inscription response",{totalCostTinybars:e.totalCost,totalCostHbar:i})}else if(e.transactionBytes){t.debug("Parsing transaction bytes for cost information");try{let r;if("string"==typeof e.transactionBytes)r=e.transactionBytes;else{if(!e.transactionBytes||"object"!=typeof e.transactionBytes||!("data"in e.transactionBytes))throw new Error("Invalid transactionBytes format");r=globalThis.Buffer.from(e.transactionBytes.data).toString("base64")}t.debug("About to parse transaction bytes",{bytesLength:r.length,bytesPreview:r.slice(0,100)});const n=await ga.parseTransactionBytes(r,{includeRaw:!1});t.debug("Parsed transaction for quote",{type:n.type,hasTransfers:!!n.transfers,transferCount:n.transfers?.length||0,transfers:n.transfers});let o=0;if(n.transfers&&n.transfers.length>0)for(const e of n.transfers){const r="string"==typeof e.amount?parseFloat(e.amount):e.amount;if(r<0){const i=Math.abs(r);o+=i,t.debug("Found HBAR transfer",{from:e.accountId,to:"service",amount:i})}}o>0&&(i=o.toString(),t.debug("Using parsed transaction transfer amount",{totalTransferAmount:o,totalCostHbar:i}))}catch(r){t.warn("Could not parse transaction bytes, using totalCost fallback",{error:r,errorMessage:r instanceof Error?r.message:String(r)})}}const n=[{to:"Inscription Service",amount:i,description:`Inscription fee (${i} HBAR)`}],o={totalCostHbar:i,validUntil:new Date(Date.now()+9e5).toISOString(),breakdown:{transfers:n}};return t.debug("Successfully parsed transaction for quote",{totalCostHbar:o.totalCostHbar,transferCount:n.length,hasTransactionBytes:!!e.transactionBytes,hasTotalCost:!!e.totalCost}),o}catch(i){throw t.error("Error parsing transaction for quote",i),i}}(l,n);return function(e,t,r,i){const n=ka.createCacheKey(e,t,r);ka.set(n,i,6e5)}(e,t,r,u),n.info("Successfully generated inscription quote",{totalCostHbar:u.totalCostHbar}),{confirmed:!1,quote:!0,result:u}}catch(o){throw n.error("Error generating inscription quote",o),o}}async function La(e,t,r=450,i=4e3,n){const o=y.getInstance({module:"Inscriber"}),s=xa(t),a=new ts({module:"Inscriber",logger:o,callback:n});try{o.debug("Waiting for inscription confirmation",{transactionId:s,maxAttempts:r,intervalMs:i}),a.preparing("Preparing for inscription confirmation",5,{transactionId:s,maxAttempts:r,intervalMs:i});try{const t=e.waitForInscription.bind(e),n=e=>{const t=e.stage||"confirming",r=["preparing","submitting","confirming","verifying","completed","failed"].includes(t)?t:"confirming",i=e.message||"Processing inscription",n=e.progressPercent||50;a.report({stage:r,message:i,progressPercent:n,details:e.details})};return await t(s,r,i,!0,n)}catch(zw){return o.debug("Falling back to standard waitForInscription method",{error:zw}),a.verifying("Verifying inscription status",50,{error:zw}),await e.waitForInscription(s,r,i,!0)}}catch(c){throw o.error("Error waiting for inscription confirmation",{transactionId:t,maxAttempts:r,intervalMs:i,error:c}),a.failed("Inscription confirmation failed",{transactionId:t,error:c}),c}}const Ka="https://hol.org/registry/api/v1";async function $a(e,t){const r=await fetch(e,t),i=await r.json().catch(()=>({}));if(!r.ok){const e="object"==typeof i&&i&&"error"in i?String(i.error):`HTTP ${r.status}`;throw new Error(e)}return i}function Ha(e){if(!e||"object"!=typeof e)return;const t=e,r=t.topicId||t.topic_id;if("string"==typeof r&&r.trim())return r;const i=t,n=i.topicId;if("string"==typeof n&&n.trim())return n;const o=i.topic_id;return"string"==typeof o&&o.trim()?o:void 0}var qa=(e=>(e.REGISTER_CONFIG="register-config",e.REGISTER="register",e))(qa||{}),ja=(e=>(e.EVM="evm",e.WASM="wasm",e))(ja||{});const Wa=t.z.object({name:t.z.string().optional(),type:t.z.string()}),Va=t.z.object({name:t.z.string(),inputs:t.z.array(Wa),outputs:t.z.array(Wa),stateMutability:t.z.enum(["view","pure"]),type:t.z.literal("function")}),Ga=t.z.enum(["number","string","bool"]),Ja=t.z.object({p:t.z.literal("hcs-7"),m:t.z.string().optional()}),Ya=Ja.extend({op:t.z.literal("register-config"),t:t.z.literal("evm"),c:t.z.object({contractAddress:t.z.string().regex(/^0x[a-fA-F0-9]{40}$/,"Invalid contract address"),abi:Va})}),Xa=Ja.extend({op:t.z.literal("register-config"),t:t.z.literal("wasm"),c:t.z.object({wasmTopicId:t.z.string(),inputType:t.z.object({stateData:t.z.record(Ga)}),outputType:t.z.object({type:t.z.literal("string"),format:t.z.literal("topic-id")})})}),Za=Ja.extend({op:t.z.literal("register"),t_id:t.z.string(),d:t.z.object({weight:t.z.number(),tags:t.z.array(t.z.string()).nonempty()}).catchall(t.z.unknown())}),Qa=t.z.union([Ya,Xa,Za]);class ec{constructor(e){this.network=e.network,this.logger=e.logger||y.getInstance({level:e.logLevel||"info",module:"HCS7Client",silent:e.silent}),this.mirrorNode=new x(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0)}generateRegistryMemo(e){return`hcs-7:indexed:${e}`}createConfigMessage(e){return e.config.type===ja.EVM?{p:"hcs-7",op:qa.REGISTER_CONFIG,t:ja.EVM,c:{contractAddress:e.config.contractAddress,abi:e.config.abi},m:e.memo}:{p:"hcs-7",op:qa.REGISTER_CONFIG,t:ja.WASM,c:{wasmTopicId:e.config.wasmTopicId,inputType:e.config.inputType,outputType:e.config.outputType},m:e.memo}}createMetadataMessage(e){return{p:"hcs-7",op:qa.REGISTER,t_id:e.metadataTopicId,m:e.memo,d:{weight:e.weight,tags:e.tags,...e.data||{}}}}validateMessage(e){const t=Qa.safeParse(e);if(t.success)return{valid:!0,errors:[]};const r=t.error.errors.map(e=>{const t=e.path.join(".");return t?`${t}: ${e.message}`:e.message});return this.logger.debug(`HCS-7 message validation failed: ${r.join(", ")}`),{valid:!1,errors:r}}async getRegistry(e,t){const r=[];try{const i=await this.mirrorNode.getTopicMessages(e,{limit:t?.limit,order:t?.order,sequenceNumber:t?.next});for(const e of i){if("hcs-7"!==e.p)continue;const t=Qa.safeParse(e);if(!t.success)continue;const i=t.data;r.push({sequenceNumber:Number(e.sequence_number),timestamp:e.consensus_timestamp||"",payer:e.payer||"",message:i})}}catch(i){this.logger.error("Failed to query HCS-7 registry",i)}return{topicId:e,entries:r}}}function tc(e){const t=e.topicSequenceNumber;return"number"==typeof t?t:"function"==typeof t?.toNumber?t.toNumber():"number"==typeof t?.low?t.low:void 0}function rc(e){return z({memo:`hcs-7:indexed:${e.ttl}`,submitKey:e.submitKey,adminKey:e.adminKey,operatorPublicKey:e.operatorPublicKey})}function ic(e){const t={p:"hcs-7",...e.message};return _({topicId:e.topicId,message:JSON.stringify(t),transactionMemo:e.transactionMemo})}class nc{constructor(){this.cache=new Map}get(e){return this.cache.get(e)}set(e,t){this.cache.set(e,t)}delete(e){this.cache.delete(e)}clear(){this.cache.clear()}}function oc(e,t){return null==e?"0":e._isBigNumber?e.toString():t.startsWith("uint")||t.startsWith("int")?String(e):"bool"===t?e?"true":"false":"string"===t?e:"address"===t?String(e).toLowerCase():t.endsWith("[]")?Array.isArray(e)?e.map(e=>String(e)).join(","):"":String(e)}function sc(e){const t=Object.create(y.prototype);return t.debug=(...t)=>e.debug(...t),t.info=(...t)=>e.info(...t),t.warn=(...t)=>e.warn(...t),t.error=(...t)=>e.error(...t),t.trace=(...t)=>e.trace(...t),t.setLogLevel=t=>e.setLogLevel(t),t.getLevel=()=>e.getLevel(),t.setSilent=t=>e.setSilent(t),t.setModule=t=>e.setModule(t),t.logger={level:e.getLevel()},t.moduleContext="",t.formatArgs=()=>({msg:""}),t}function ac(e){return e instanceof y}async function cc(e,t,r){const i=new x(t,r),n=[];for(const s of e)try{const e=await i.getPublicKey(s);n.push(e)}catch(o){r&&r.warn(`Could not get public key for account ${s}: ${o}`)}return n}const lc="hcs-21",uc=1024,dc=1e3,pc=/^(?:hcs:\/\/1\/0\.0\.\d+|ipfs:\/\/\S+|ar:\/\/\S+|oci:\/\/\S+|https?:\/\/\S+)$/,hc=/^(?:0\.0\.\d+|hcs:\/\/1\/0\.0\.\d+(?:\/\d+)?|ipfs:\/\/\S+|ar:\/\/\S+|oci:\/\/\S+|https?:\/\/\S+)$/;var gc=(e=>(e[e.ADAPTER_REGISTRY=0]="ADAPTER_REGISTRY",e[e.REGISTRY_OF_REGISTRIES=1]="REGISTRY_OF_REGISTRIES",e[e.ADAPTER_CATEGORY=2]="ADAPTER_CATEGORY",e))(gc||{});const mc=t.z.object({registry:t.z.string().min(1),name:t.z.string().min(1),version:t.z.string().min(1),integrity:t.z.string().min(1)}),fc=t.z.object({type:t.z.string().min(1),account:t.z.string().min(1).optional(),threshold:t.z.string().min(1).optional(),ctopic:t.z.string().min(1).optional(),ttopic:t.z.string().min(1).optional(),stopic:t.z.string().min(1).optional()}).catchall(t.z.unknown()),yc=t.z.object({p:t.z.literal(lc),op:t.z.enum(["register","update","delete"]),adapter_id:t.z.string().min(1),entity:t.z.string().min(1),package:mc,manifest:t.z.string().regex(pc,"manifest must be an immutable pointer (hcs://1/<topicId>, ipfs://cid/path, ar://txid, oci://repo@digest, https://...#sha384-..)"),manifest_sequence:t.z.number().int().positive().optional(),config:fc,state_model:t.z.string().min(1).optional(),signature:t.z.string().min(1).optional()}),bc=t.z.object({meta:t.z.object({spec_version:t.z.string().min(1),adapter_version:t.z.string().min(1),minimum_version:t.z.string().min(1).optional(),generated:t.z.string().min(1)}),adapter:t.z.object({name:t.z.string().min(1),id:t.z.string().min(1),maintainers:t.z.array(t.z.object({name:t.z.string().min(1),contact:t.z.string().min(1)})).min(1),license:t.z.string().min(1)}),package:t.z.object({registry:t.z.string().min(1),dist_tag:t.z.string().min(1).optional(),artifacts:t.z.array(t.z.object({url:t.z.string().min(1),digest:t.z.string().min(1),signature:t.z.string().min(1).optional()})).min(1)}),runtime:t.z.object({platforms:t.z.array(t.z.string().min(1)).min(1),primary:t.z.string().min(1),entry:t.z.string().min(1),dependencies:t.z.array(t.z.string().min(1)).optional(),env:t.z.array(t.z.string().min(1)).optional()}),capabilities:t.z.object({discovery:t.z.boolean(),communication:t.z.boolean(),protocols:t.z.array(t.z.string().min(1)),discovery_tags:t.z.array(t.z.string().min(1)).optional(),communication_channels:t.z.array(t.z.string().min(1)).optional(),extras:t.z.record(t.z.string(),t.z.unknown()).optional()}),consensus:t.z.object({state_model:t.z.string().min(1).optional(),profile_uri:t.z.string().min(1).optional(),entity_schema:t.z.string().min(1).optional(),required_fields:t.z.array(t.z.string().min(1)),hashing:t.z.literal("sha384")})}),wc=t.z.object({version:t.z.string().min(1),name:t.z.string().min(1),description:t.z.string().min(1),operator:t.z.object({account:t.z.string().min(1),name:t.z.string().optional(),contact:t.z.string().optional()}),entityTypes:t.z.array(t.z.string().min(1)),categories:t.z.array(t.z.string().min(1)).optional(),tags:t.z.array(t.z.string().min(1)).optional(),links:t.z.record(t.z.string().min(1)).optional()}),Ic=t.z.union([bc,wc]);var Tc=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(Tc||{}),Sc=(e=>(e[e.TEXT_GENERATION=0]="TEXT_GENERATION",e[e.IMAGE_GENERATION=1]="IMAGE_GENERATION",e[e.AUDIO_GENERATION=2]="AUDIO_GENERATION",e[e.VIDEO_GENERATION=3]="VIDEO_GENERATION",e[e.CODE_GENERATION=4]="CODE_GENERATION",e[e.LANGUAGE_TRANSLATION=5]="LANGUAGE_TRANSLATION",e[e.SUMMARIZATION_EXTRACTION=6]="SUMMARIZATION_EXTRACTION",e[e.KNOWLEDGE_RETRIEVAL=7]="KNOWLEDGE_RETRIEVAL",e[e.DATA_INTEGRATION=8]="DATA_INTEGRATION",e[e.MARKET_INTELLIGENCE=9]="MARKET_INTELLIGENCE",e[e.TRANSACTION_ANALYTICS=10]="TRANSACTION_ANALYTICS",e[e.SMART_CONTRACT_AUDIT=11]="SMART_CONTRACT_AUDIT",e[e.GOVERNANCE_FACILITATION=12]="GOVERNANCE_FACILITATION",e[e.SECURITY_MONITORING=13]="SECURITY_MONITORING",e[e.COMPLIANCE_ANALYSIS=14]="COMPLIANCE_ANALYSIS",e[e.FRAUD_DETECTION=15]="FRAUD_DETECTION",e[e.MULTI_AGENT_COORDINATION=16]="MULTI_AGENT_COORDINATION",e[e.API_INTEGRATION=17]="API_INTEGRATION",e[e.WORKFLOW_AUTOMATION=18]="WORKFLOW_AUTOMATION",e))(Sc||{});const kc=t.z.nativeEnum(Sc),vc=t.z.union([t.z.number(),t.z.string()]),Ec=t.z.union([t.z.string(),t.z.number(),t.z.boolean(),t.z.null()]),Ac=t.z.lazy(()=>t.z.union([Ec,t.z.array(Ac),t.z.record(Ac)])),Cc=t.z.object({version:t.z.string(),type:t.z.number(),display_name:t.z.string(),alias:t.z.string().optional(),bio:t.z.string().optional(),socials:t.z.array(Ac).optional(),aiAgent:t.z.object({type:t.z.nativeEnum(Tc),creator:t.z.string().optional(),model:t.z.string().optional(),capabilities:t.z.array(t.z.union([kc,t.z.number()])).optional()}).optional(),uaid:t.z.string().optional()}).catchall(Ac),Rc=t.z.object({uaid:t.z.string().optional(),ledgerAccountId:t.z.string().optional(),userId:t.z.string().optional(),email:t.z.string().optional(),encryptedShare:t.z.string()}),xc=t.z.object({algorithm:t.z.string(),ciphertext:t.z.string(),nonce:t.z.string(),associatedData:t.z.string().optional(),keyLocator:t.z.object({sessionId:t.z.string().optional(),revision:t.z.number().optional()}).optional(),recipients:t.z.array(Rc)}),Nc=t.z.object({keyType:t.z.string(),publicKey:t.z.string(),uaid:t.z.string().optional(),ledgerAccountId:t.z.string().optional(),userId:t.z.string().optional(),email:t.z.string().optional()}),zc=t.z.object({role:t.z.enum(["requester","responder"]),uaid:t.z.string().optional(),userId:t.z.string().optional(),ledgerAccountId:t.z.string().optional(),keyType:t.z.string(),longTermPublicKey:t.z.string().optional(),ephemeralPublicKey:t.z.string(),signature:t.z.string().optional(),metadata:t.z.record(Ac).optional(),submittedAt:t.z.string()}),_c=t.z.object({sessionId:t.z.string(),algorithm:t.z.string(),createdAt:t.z.string(),expiresAt:t.z.number(),status:t.z.enum(["pending","complete"]),requester:zc.optional(),responder:zc.optional()}),Pc=t.z.object({enabled:t.z.boolean(),algorithm:t.z.string(),requireCiphertext:t.z.boolean(),requester:Nc.nullable().optional(),responder:Nc.nullable().optional(),handshake:_c.nullable().optional()}),Oc=t.z.object({messageId:t.z.string(),role:t.z.enum(["user","agent"]),content:t.z.string(),timestamp:t.z.string(),cipherEnvelope:xc.optional(),metadata:t.z.record(Ac).optional()}),Dc=t.z.record(t.z.union([t.z.array(Ac),t.z.record(Ac),Ac])).optional(),Fc=t.z.object({id:t.z.string(),uaid:t.z.string(),registry:t.z.string(),name:t.z.string(),description:t.z.string().optional(),capabilities:t.z.array(vc),endpoints:t.z.union([t.z.record(Ac),t.z.array(t.z.string())]).optional(),metadata:t.z.record(Ac).optional(),metadataFacet:Dc,profile:Cc.optional(),protocols:t.z.array(t.z.string()).optional(),adapter:t.z.string().optional(),originalId:t.z.string().optional(),communicationSupported:t.z.boolean().optional(),routingSupported:t.z.boolean().optional(),available:t.z.boolean().optional(),availabilityStatus:t.z.string().optional(),availabilityCheckedAt:t.z.string().optional(),availabilitySource:t.z.string().optional(),availabilityLatencyMs:t.z.number().optional(),availabilityScore:t.z.number().optional(),capabilityLabels:t.z.array(t.z.string()).optional(),capabilityTokens:t.z.array(t.z.string()).optional(),image:t.z.string().optional(),createdAt:t.z.string().optional(),updatedAt:t.z.string().optional(),lastSeen:t.z.string().optional(),lastIndexed:t.z.string().optional()}).passthrough(),Mc=t.z.object({hits:t.z.array(Fc),total:t.z.number(),page:t.z.number(),limit:t.z.number()}),Uc=t.z.object({totalAgents:t.z.number(),registries:t.z.record(t.z.number()),capabilities:t.z.record(t.z.number()),lastUpdate:t.z.string(),status:t.z.string()}),Bc=t.z.object({registries:t.z.array(t.z.string())}),Lc=t.z.object({searches:t.z.array(t.z.string())}),Kc=t.z.object({agent:Fc}),$c=t.z.object({uaid:t.z.string(),score:t.z.number(),displayName:t.z.string().optional(),summary:t.z.string().optional(),protocols:t.z.array(t.z.string()).optional(),surfaces:t.z.array(t.z.string()).optional(),languages:t.z.array(t.z.string()).optional(),artifacts:t.z.array(t.z.string()).optional(),availability:t.z.boolean().optional(),explanation:t.z.string().optional()}).passthrough(),Hc=t.z.object({id:t.z.string(),title:t.z.string(),reason:t.z.string(),role:t.z.string(),type:t.z.enum(["ai-agents","mcp-servers"]),suggestedMode:t.z.enum(["best-match","fallback","parallel"]),searchQueries:t.z.array(t.z.string()),protocols:t.z.array(t.z.string()).optional(),surfaces:t.z.array(t.z.string()).optional(),languages:t.z.array(t.z.string()).optional(),artifacts:t.z.array(t.z.string()).optional(),candidates:t.z.array($c)}).passthrough(),qc=t.z.object({action:t.z.enum(["delegate-now","review-shortlist","handle-locally"]),confidence:t.z.number(),reason:t.z.string(),opportunityId:t.z.string().optional(),candidate:$c.optional()}).passthrough(),jc=t.z.object({task:t.z.string(),context:t.z.string().optional(),summary:t.z.string().optional(),intents:t.z.array(t.z.string()),protocols:t.z.array(t.z.string()),surfaces:t.z.array(t.z.string()),languages:t.z.array(t.z.string()).optional(),artifacts:t.z.array(t.z.string()).optional(),shouldDelegate:t.z.boolean(),localFirstReason:t.z.string().optional(),recommendation:qc.optional(),opportunities:t.z.array(Hc)}).passthrough(),Wc=t.z.object({averageScore:t.z.number(),totalFeedbacks:t.z.number(),registry:t.z.string().optional(),network:t.z.string().optional(),updatedAt:t.z.string().optional()}),Vc=t.z.object({registry:t.z.string(),network:t.z.string().optional(),agentId:t.z.number(),client:t.z.string(),score:t.z.number(),tag1:t.z.string().nullable().optional(),tag2:t.z.string().nullable().optional(),revoked:t.z.boolean(),feedbackIndex:t.z.number().nullable().optional(),fileUri:t.z.string().nullable().optional(),fileHash:t.z.string().nullable().optional(),createdAt:t.z.string().nullable().optional()}),Gc=t.z.object({uaid:t.z.string(),summary:Wc,entries:t.z.array(Vc)}),Jc=t.z.object({uaid:t.z.string(),sessionId:t.z.string(),eligible:t.z.boolean(),messageCount:t.z.number(),minimumMessages:t.z.number(),reason:t.z.string().optional(),onchain:t.z.object({eligible:t.z.boolean(),reason:t.z.string().optional(),estimatedCredits:t.z.number().optional(),usdEstimate:t.z.number().optional(),nativeFeeEstimate:t.z.number().optional()}).optional()}),Yc=t.z.object({uaid:t.z.string(),registry:t.z.string(),network:t.z.string().optional(),agentId:t.z.number(),score:t.z.number(),tag1:t.z.string().nullable().optional(),tag2:t.z.string().nullable().optional(),fileUri:t.z.string().nullable().optional(),fileHash:t.z.string().nullable().optional(),feedbackIndex:t.z.number().nullable().optional(),transactionHash:t.z.string().nullable().optional(),signature:t.z.string().nullable().optional(),submittedAt:t.z.string()}),Xc=t.z.object({page:t.z.number(),limit:t.z.number(),total:t.z.number(),items:t.z.array(t.z.object({uaid:t.z.string(),registry:t.z.string(),network:t.z.string().optional(),agentId:t.z.number().nullable().optional(),summary:Wc.nullable(),trustScore:t.z.number().nullable().optional()}))}),Zc=t.z.object({page:t.z.number(),limit:t.z.number(),total:t.z.number(),items:t.z.array(t.z.object({uaid:t.z.string(),entry:Vc}))}),Qc=t.z.object({sessionId:t.z.string(),uaid:t.z.string().nullable().optional(),agent:t.z.object({name:t.z.string(),description:t.z.string().optional(),capabilities:t.z.record(Ac).nullable().optional(),skills:t.z.array(t.z.string()).optional()}),history:t.z.array(Oc).optional().default([]),historyTtlSeconds:t.z.number().nullable().optional(),encryption:Pc.nullable().optional()}),el=t.z.object({sessionId:t.z.string(),uaid:t.z.string().nullable().optional(),message:t.z.string(),timestamp:t.z.string(),rawResponse:Ac.optional(),content:t.z.string().optional(),ops:t.z.array(t.z.record(Ac)).optional(),history:t.z.array(Oc).optional(),historyTtlSeconds:t.z.number().nullable().optional(),encrypted:t.z.boolean().optional()}),tl=t.z.object({sessionId:t.z.string(),history:t.z.array(Oc),historyTtlSeconds:t.z.number()});t.z.object({preserveEntries:t.z.number().int().min(0).optional()}).strict();const rl=t.z.object({sessionId:t.z.string(),history:t.z.array(Oc),summaryEntry:Oc,preservedEntries:t.z.array(Oc),historyTtlSeconds:t.z.number(),creditsDebited:t.z.number(),metadata:t.z.record(Ac).optional()}),il=t.z.object({sessionId:t.z.string(),encryption:Pc.nullable()}),nl=t.z.object({sessionId:t.z.string(),handshake:_c}),ol=t.z.object({id:t.z.string(),keyType:t.z.string(),publicKey:t.z.string(),uaid:t.z.string().nullable(),ledgerAccountId:t.z.string().nullable(),ledgerNetwork:t.z.string().nullable().optional(),userId:t.z.string().nullable().optional(),email:t.z.string().nullable().optional(),createdAt:t.z.string(),updatedAt:t.z.string()}),sl=t.z.object({challengeId:t.z.string(),message:t.z.string(),expiresAt:t.z.string()}),al=t.z.object({id:t.z.string(),label:t.z.string().optional(),prefix:t.z.string(),lastFour:t.z.string(),createdAt:t.z.string(),lastUsedAt:t.z.string().nullable().optional(),ownerType:t.z.literal("ledger"),ledgerAccountId:t.z.string().optional(),ledgerNetwork:t.z.string().optional(),ledgerNetworkCanonical:t.z.string().optional()}),cl=t.z.object({key:t.z.string(),apiKey:al,accountId:t.z.string(),network:t.z.string(),networkCanonical:t.z.string().optional()}),ll=t.z.object({protocols:t.z.array(t.z.string())}),ul=t.z.object({protocol:t.z.string().nullable()}),dl=t.z.object({hits:t.z.array(Fc),total:t.z.number(),page:t.z.number().optional(),limit:t.z.number().optional()}),pl=t.z.union([t.z.string(),t.z.number()]),hl=t.z.object({capabilities:t.z.array(pl).optional(),type:t.z.enum(["ai-agents","mcp-servers"]).optional(),registry:t.z.string().optional(),protocols:t.z.array(t.z.string()).optional(),adapter:t.z.array(t.z.string()).optional()}).strict();t.z.object({query:t.z.string(),filter:hl.optional(),limit:t.z.number().int().min(1).max(100).optional(),offset:t.z.number().int().min(0).optional()}).strict();const gl=t.z.object({agent:Fc,score:t.z.number().optional(),highlights:t.z.record(t.z.array(t.z.string())).optional()}),ml=t.z.object({hits:t.z.array(gl),total:t.z.number(),took:t.z.number(),totalAvailable:t.z.number().optional(),visible:t.z.number().optional(),limited:t.z.boolean().optional(),credits_used:t.z.number().optional()}),fl=t.z.object({enabled:t.z.boolean(),healthy:t.z.boolean(),mode:t.z.enum(["disabled","initializing","healthy","degraded","error"]),lastUpdated:t.z.string(),details:t.z.record(t.z.any()).optional(),lastError:t.z.object({message:t.z.string(),stack:t.z.string().optional(),timestamp:t.z.string().optional()}).optional()}),yl=t.z.object({storageMode:t.z.string(),vectorStatus:fl}),bl=t.z.object({clients:t.z.number(),stats:t.z.object({totalClients:t.z.number().optional(),clientsByRegistry:t.z.record(t.z.number()).optional(),clientsByEventType:t.z.record(t.z.number()).optional()}).passthrough()}),wl=t.z.object({p50:t.z.number(),p90:t.z.number(),p95:t.z.number(),p99:t.z.number()}),Il=t.z.object({http:t.z.object({requestsTotal:t.z.number(),activeConnections:t.z.number(),requestDuration:wl}),search:t.z.object({queriesTotal:t.z.number(),queryDuration:wl}),indexing:t.z.object({agentsTotal:t.z.number(),crawlErrors:t.z.number()}),registration:t.z.object({total:t.z.number(),failures:t.z.number(),duration:wl}),cache:t.z.object({hits:t.z.number(),misses:t.z.number(),hitRate:t.z.number()}),websocket:t.z.object({connections:t.z.number()})}),Tl=t.z.object({uaid:t.z.string(),valid:t.z.boolean(),formats:t.z.array(t.z.string())}),Sl=t.z.object({id:t.z.string(),agentId:t.z.string(),protocol:t.z.string(),endpoint:t.z.string(),status:t.z.enum(["connected","disconnected","error"]),metadata:t.z.record(Ec).optional(),createdAt:t.z.string()}),kl=t.z.object({connected:t.z.boolean(),connection:Sl.optional(),adapter:t.z.string().optional(),agentId:t.z.string().optional()}),vl=t.z.object({operatorId:t.z.string().optional(),adapters:t.z.array(t.z.object({name:t.z.string(),version:t.z.string(),status:t.z.string(),agentCount:t.z.number(),lastDiscovery:t.z.string(),registryType:t.z.string(),health:t.z.string()})).optional(),totalAgents:t.z.number().optional(),elasticsearchDocumentCount:t.z.number().optional(),agentsByAdapter:t.z.record(t.z.number()).optional(),agentsByRegistry:t.z.record(t.z.number()).optional(),systemInfo:t.z.object({uptime:t.z.number().optional(),version:t.z.string().optional(),network:t.z.string().optional()}).optional()}),El=t.z.object({id:t.z.string(),name:t.z.string(),type:t.z.string(),endpoint:t.z.string().optional(),capabilities:t.z.array(vc),registry:t.z.string().optional(),protocol:t.z.string().optional(),profile:Cc.optional(),nativeId:t.z.string().optional(),metadata:t.z.record(Ac).optional()}),Al=t.z.object({tId:t.z.string().nullable(),sizeBytes:t.z.number().optional()}),Cl=t.z.object({topicId:t.z.string().optional(),sequenceNumber:t.z.number().optional(),profileReference:t.z.string().optional(),profileTopicId:t.z.string().optional()}).passthrough().nullable().optional(),Rl=t.z.object({registry:t.z.string(),status:t.z.enum(["created","duplicate","skipped","error","updated","pending"]),agentId:t.z.string().nullable().optional(),agentUri:t.z.string().nullable().optional(),error:t.z.string().optional(),metadata:t.z.record(Ac).optional(),registryKey:t.z.string().optional(),networkId:t.z.string().optional(),networkName:t.z.string().optional(),chainId:t.z.number().optional(),estimatedCredits:t.z.number().nullable().optional(),gasEstimateCredits:t.z.number().nullable().optional(),gasEstimateUsd:t.z.number().nullable().optional(),gasPriceGwei:t.z.number().nullable().optional(),gasLimit:t.z.number().nullable().optional(),creditMode:t.z.enum(["fixed","gas"]).nullable().optional(),minCredits:t.z.number().nullable().optional(),consumedCredits:t.z.number().nullable().optional(),cost:t.z.object({credits:t.z.number(),usd:t.z.number(),eth:t.z.number(),gasUsedWei:t.z.string(),effectiveGasPriceWei:t.z.string().nullable().optional(),transactions:t.z.array(t.z.object({hash:t.z.string(),gasUsedWei:t.z.string(),effectiveGasPriceWei:t.z.string().nullable().optional(),costWei:t.z.string()})).optional()}).optional()}),xl=t.z.object({base:t.z.number(),additional:t.z.number(),total:t.z.number()}),Nl=t.z.object({status:t.z.string(),uaid:t.z.string().optional(),transactionId:t.z.string().optional(),consensusTimestamp:t.z.string().optional(),registryTopicId:t.z.string().optional(),topicSequenceNumber:t.z.number().optional(),payloadHash:t.z.string().optional(),profileReference:t.z.string().optional(),tId:t.z.string().optional(),profileSizeBytes:t.z.number().optional(),error:t.z.string().optional()}).passthrough(),zl=t.z.object({key:t.z.string(),registryId:t.z.string().optional(),networkId:t.z.string().optional(),name:t.z.string().optional(),chainId:t.z.number().optional(),label:t.z.string().optional(),estimatedCredits:t.z.number().nullable().optional(),baseCredits:t.z.number().nullable().optional(),gasPortionCredits:t.z.number().nullable().optional(),gasPortionUsd:t.z.number().nullable().optional(),gasEstimateCredits:t.z.number().nullable().optional(),gasEstimateUsd:t.z.number().nullable().optional(),gasPriceGwei:t.z.number().nullable().optional(),gasLimit:t.z.number().nullable().optional(),minCredits:t.z.number().nullable().optional(),creditMode:t.z.string().nullable().optional()}).passthrough(),_l=t.z.object({id:t.z.string(),label:t.z.string(),networks:t.z.array(zl)}),Pl=t.z.object({registries:t.z.array(_l)}),Ol=t.z.object({success:t.z.literal(!0),status:t.z.enum(["created","duplicate","updated"]).optional(),uaid:t.z.string(),agentId:t.z.string(),message:t.z.string().optional(),registry:t.z.string().optional(),attemptId:t.z.string().nullable().optional(),agent:El,openConvAI:t.z.object({compatible:t.z.boolean(),hcs11Profile:Cc.optional(),bridgeEndpoint:t.z.string().optional()}).optional(),profile:Al.optional(),profileRegistry:Cl.nullable().optional(),hcs10Registry:Nl.nullable().optional(),credits:xl.optional(),additionalRegistries:t.z.array(Rl).optional(),additionalRegistryCredits:t.z.array(Rl).optional(),additionalRegistryCostPerRegistry:t.z.number().optional(),additionalRegistrySecrets:t.z.record(t.z.string(),t.z.record(Ac)).optional()}),Dl=t.z.object({success:t.z.literal(!0),status:t.z.literal("pending"),message:t.z.string(),uaid:t.z.string(),agentId:t.z.string(),registry:t.z.string().optional(),attemptId:t.z.string().nullable(),agent:El,openConvAI:t.z.object({compatible:t.z.boolean(),hcs11Profile:Cc.optional(),bridgeEndpoint:t.z.string().optional()}).optional(),profile:Al.optional(),profileRegistry:Cl.nullable().optional(),hcs10Registry:Nl.nullable().optional(),credits:xl,additionalRegistries:t.z.array(Rl),additionalRegistryCredits:t.z.array(Rl).optional(),additionalRegistryCostPerRegistry:t.z.number().optional(),additionalRegistrySecrets:t.z.record(t.z.string(),t.z.record(Ac)).optional()}),Fl=t.z.object({success:t.z.literal(!1),status:t.z.literal("partial"),message:t.z.string(),uaid:t.z.string(),agentId:t.z.string(),registry:t.z.string().optional(),attemptId:t.z.string().nullable().optional(),agent:El,openConvAI:t.z.object({compatible:t.z.boolean(),hcs11Profile:Cc.optional(),bridgeEndpoint:t.z.string().optional()}).optional(),profile:Al.optional(),profileRegistry:Cl.nullable().optional(),hcs10Registry:Nl.nullable().optional(),credits:xl.optional(),additionalRegistries:t.z.array(Rl).optional(),additionalRegistryCredits:t.z.array(Rl).optional(),additionalRegistryCostPerRegistry:t.z.number().optional(),additionalRegistrySecrets:t.z.record(t.z.string(),t.z.record(Ac)).optional(),errors:t.z.array(t.z.object({registry:t.z.string(),registryKey:t.z.string().nullable().optional(),error:t.z.string()})).min(1)}),Ml=t.z.union([Ol,Dl,Fl]),Ul=t.z.object({registryId:t.z.string(),registryKey:t.z.string(),networkId:t.z.string().optional(),networkName:t.z.string().optional(),chainId:t.z.number().optional(),label:t.z.string().optional(),status:t.z.enum(["pending","in_progress","completed","failed"]),error:t.z.string().optional(),credits:t.z.number().nullable().optional(),agentId:t.z.string().nullable().optional(),agentUri:t.z.string().nullable().optional(),metadata:t.z.record(Ac).optional(),lastUpdated:t.z.string()}),Bl=t.z.object({attemptId:t.z.string(),mode:t.z.enum(["register","update"]),status:t.z.enum(["pending","partial","completed","failed"]),uaid:t.z.string().optional(),agentId:t.z.string().optional(),registryNamespace:t.z.string(),accountId:t.z.string().optional(),startedAt:t.z.string(),completedAt:t.z.string().optional(),primary:t.z.object({status:t.z.enum(["pending","completed","failed"]),finishedAt:t.z.string().optional(),error:t.z.string().optional()}),additionalRegistries:t.z.record(t.z.string(),Ul),errors:t.z.array(t.z.string()).optional()}),Ll=t.z.object({progress:Bl}),Kl=t.z.object({accountId:t.z.string().nullable().optional(),registry:t.z.string().optional(),protocol:t.z.string().optional(),requiredCredits:t.z.number(),availableCredits:t.z.number().nullable().optional(),shortfallCredits:t.z.number().nullable().optional(),creditsPerHbar:t.z.number().nullable().optional(),estimatedHbar:t.z.number().nullable().optional()}),$l=t.z.object({success:t.z.boolean().optional(),purchaser:t.z.string(),credits:t.z.number(),hbarAmount:t.z.number(),transactionId:t.z.string(),consensusTimestamp:t.z.string().nullable().optional()}),Hl=t.z.object({success:t.z.boolean().optional(),transaction:t.z.string().optional(),network:t.z.string().optional(),payer:t.z.string().optional(),errorReason:t.z.string().optional()}).strict(),ql=t.z.object({success:t.z.boolean(),accountId:t.z.string(),creditedCredits:t.z.number(),usdAmount:t.z.number(),balance:t.z.number(),payment:t.z.object({payer:t.z.string().optional(),requirement:t.z.record(Ac).optional(),settlement:Hl.optional()}).optional()}),jl=t.z.object({minimums:t.z.record(t.z.object({network:t.z.string().optional(),gasLimit:t.z.number().optional(),gasPriceWei:t.z.string().optional(),gasUsd:t.z.number().optional(),minUsd:t.z.number().optional(),ethUsd:t.z.number().optional(),fetchedAt:t.z.string().optional(),source:t.z.string().optional()})).optional(),creditUnitUsd:t.z.number().optional()}),Wl=t.z.object({adapters:t.z.array(t.z.string())}),Vl=t.z.object({id:t.z.number().int(),network:t.z.string(),type:t.z.string(),slug:t.z.string(),name:t.z.string(),description:t.z.string().nullable().optional(),topicId:t.z.string(),versionTopicId:t.z.string(),registryTransactionId:t.z.string().nullable().optional(),versionTransactionId:t.z.string().nullable().optional(),metadataPointer:t.z.string().nullable().optional(),metadataSequence:t.z.number().int().nullable().optional(),createdAt:t.z.string(),updatedAt:t.z.string(),metadata:Ac.optional().nullable()}),Gl=t.z.object({categories:t.z.array(Vl)}),Jl=t.z.object({id:t.z.union([t.z.string(),t.z.number()]).optional(),network:t.z.string().optional(),categoryId:t.z.union([t.z.string(),t.z.number()]).nullable().optional(),operation:t.z.string().optional(),adapterId:t.z.string(),adapterName:t.z.string(),entity:t.z.string(),manifestPointer:t.z.string().nullable().optional(),manifestSequence:t.z.number().int().nullable().optional(),packageRegistry:t.z.string().nullable().optional(),packageName:t.z.string().nullable().optional(),packageVersion:t.z.string().nullable().optional(),packageIntegrity:t.z.string().nullable().optional(),stateModel:t.z.string().nullable().optional(),config:Ac.nullable().optional(),signature:t.z.string().nullable().optional(),manifest:Ac.nullable().optional(),keywords:t.z.array(t.z.string()).optional(),searchText:t.z.string().nullable().optional(),creditAccountId:t.z.string().nullable().optional(),registeredByUserId:t.z.string().nullable().optional(),registeredByEmail:t.z.string().nullable().optional(),totalCostHbar:t.z.number().nullable().optional(),totalCostCredits:t.z.number().nullable().optional(),consensusTimestamp:t.z.string().nullable().optional(),sequenceNumber:t.z.number().int().nullable().optional(),payerAccountId:t.z.string().nullable().optional(),mirrorNodePayload:Ac.nullable().optional(),versionTopicId:t.z.string().nullable().optional(),declarationTopicId:t.z.string().nullable().optional(),categoryEntrySequence:t.z.number().int().nullable().optional(),categoryEntryTransactionId:t.z.string().nullable().optional(),versionPointerSequence:t.z.number().int().nullable().optional(),versionPointerTransactionId:t.z.string().nullable().optional(),transactionId:t.z.string().nullable().optional(),createdAt:t.z.string().optional(),category:Vl.optional()}).passthrough(),Yl=t.z.object({network:t.z.string(),adapters:t.z.array(Jl)}),Xl=t.z.object({category:Vl});t.z.object({adapter:t.z.record(Ac),declaration:yc,transactionId:t.z.string().optional().nullable(),category:Vl});const Zl=t.z.object({submissionId:t.z.string(),status:t.z.string().optional(),network:t.z.string().optional(),message:t.z.string().optional()}).passthrough(),Ql=t.z.object({submission:t.z.object({id:t.z.string(),network:t.z.string(),status:t.z.enum(["pending","running","completed","failed"]),adapterId:t.z.string(),categorySlug:t.z.string().nullable().optional(),creditAccountId:t.z.string().nullable().optional(),registeredByUserId:t.z.string().nullable().optional(),registeredByEmail:t.z.string().nullable().optional(),requestPayload:Ac.optional(),resultPayload:Ac.nullable().optional(),error:t.z.string().nullable().optional(),createdAt:t.z.string().optional(),updatedAt:t.z.string().optional(),startedAt:t.z.string().nullable().optional(),completedAt:t.z.string().nullable().optional()}).passthrough()}),eu=t.z.object({supportsChat:t.z.boolean(),delivery:t.z.string().optional(),transport:t.z.string().optional(),streaming:t.z.boolean().optional(),requiresAuth:t.z.array(t.z.string()).optional(),notes:t.z.string().optional()}),tu=t.z.object({discovery:t.z.boolean(),routing:t.z.boolean(),communication:t.z.boolean(),translation:t.z.boolean(),protocols:t.z.array(t.z.string())}),ru=t.z.object({id:t.z.string(),name:t.z.string(),version:t.z.string(),author:t.z.string(),description:t.z.string(),supportedProtocols:t.z.array(t.z.string()),registryType:t.z.enum(["web2","web3","hybrid"]),chatProfile:eu.optional(),capabilities:tu,enabled:t.z.boolean(),priority:t.z.number(),status:t.z.enum(["running","stopped"])}),iu=t.z.object({adapters:t.z.array(ru)}),nu=t.z.object({value:t.z.union([t.z.string(),t.z.number(),t.z.boolean()]),label:t.z.string()}),ou=t.z.object({key:t.z.string(),label:t.z.string(),description:t.z.string().optional(),type:t.z.enum(["string","boolean","number"]),adapters:t.z.array(t.z.string()).optional(),options:t.z.array(nu).optional()}),su=t.z.object({facets:t.z.array(ou)}),au=t.z.object({ownerType:t.z.string(),ownerId:t.z.string(),ownerHandle:t.z.string().optional(),verifiedAt:t.z.string().optional(),method:t.z.string().optional()}).passthrough(),cu=t.z.object({challengeId:t.z.string(),code:t.z.string(),expiresAt:t.z.string(),expectedHandle:t.z.string(),instructions:t.z.string(),existingOwnership:au.optional()}).passthrough(),lu=t.z.object({challengeId:t.z.string(),uaid:t.z.string(),code:t.z.string(),expiresAt:t.z.string(),status:t.z.string(),message:t.z.string().optional()}).passthrough(),uu=t.z.object({verified:t.z.boolean(),uaid:t.z.string(),ownerType:t.z.string(),ownerId:t.z.string(),ownerHandle:t.z.string().optional(),method:t.z.string().optional(),verificationPostUrl:t.z.string().optional()}).passthrough(),du=t.z.object({uaid:t.z.string(),ownerType:t.z.string(),ownerId:t.z.string(),ownerHandle:t.z.string().optional(),chain:t.z.string(),verifiedAt:t.z.string(),method:t.z.string()}).passthrough(),pu=t.z.object({uaid:t.z.string(),verified:t.z.boolean(),chain:t.z.string().nullable()}).passthrough(),hu=t.z.object({verified:t.z.boolean(),uaid:t.z.string(),ownerType:t.z.string(),ownerId:t.z.string()}).passthrough(),gu=t.z.object({code:t.z.string(),message:t.z.string(),details:t.z.record(Ac).optional()}).passthrough(),mu=t.z.object({uaid:t.z.string(),verified:t.z.boolean(),profileId:t.z.string(),checkedAt:t.z.string(),nativeId:t.z.string().optional(),dnsName:t.z.string().optional(),verificationLevel:t.z.string().optional(),resolutionMode:t.z.string().optional(),reconstructedUaid:t.z.string().optional(),selectedFollowupProfile:t.z.string().optional(),error:gu.optional(),source:t.z.string().optional(),persisted:t.z.boolean().optional()}).passthrough(),fu=t.z.object({registered:t.z.boolean(),agent:Ac.optional()}).passthrough(),yu=t.z.object({ok:t.z.boolean(),uaid:t.z.string(),registered:t.z.boolean(),registeredAt:t.z.string().optional(),agent:Ac.optional(),warning:t.z.string().optional()}).passthrough(),bu=t.z.union([t.z.literal("skill-md"),t.z.literal("skill-json"),t.z.literal("skill-icon"),t.z.literal("file")]),wu=t.z.record(t.z.number()).refine(e=>"number"==typeof e.total&&Number.isFinite(e.total),{message:"trustScores.total is required"}),Iu=t.z.enum(["safe","review","caution","unsafe"]),Tu=t.z.object({score:t.z.number(),label:Iu,findingsTotal:t.z.number().int(),highFindings:t.z.number().int(),scriptsTotal:t.z.number().int(),permissionsMissing:t.z.array(t.z.string())}).passthrough(),Su=t.z.enum(["low","medium","high"]),ku=t.z.object({ruleId:t.z.string(),severity:Su,file:t.z.string(),message:t.z.string()}).passthrough(),vu=t.z.object({name:t.z.string(),mimeType:t.z.string(),role:bu,topicId:t.z.string().optional(),hrl:t.z.string().optional(),packageSequenceNumber:t.z.number().int().optional()}).passthrough(),Eu=t.z.object({jobId:t.z.string(),network:t.z.union([t.z.literal("mainnet"),t.z.literal("testnet")]),name:t.z.string(),version:t.z.string(),description:t.z.string().optional(),createdAt:t.z.string(),directoryTopicId:t.z.string(),skillUid:t.z.number().int().optional(),directorySequenceNumber:t.z.number().int().optional(),versionRegistryTopicId:t.z.string().optional(),packageTopicId:t.z.string(),manifestHrl:t.z.string().optional(),skillJsonHrl:t.z.string(),iconHcs1:t.z.string().optional(),tags:t.z.array(t.z.string()).optional(),category:t.z.string().optional(),featured:t.z.boolean().optional(),verified:t.z.boolean().optional(),upvotes:t.z.number().int().optional(),trustScore:t.z.number().optional(),trustScores:wu.optional(),safety:Tu.optional(),safetyFindings:t.z.array(ku).optional(),files:t.z.array(vu).optional()}).passthrough(),Au=t.z.object({items:t.z.array(Eu),nextCursor:t.z.string().nullable()}).passthrough();t.z.enum(["stable","prerelease","all"]),t.z.enum(["trending","upvotes","updated","name"]);const Cu=t.z.object({version:t.z.string(),publishedAt:t.z.string(),verified:t.z.boolean().optional()}).passthrough(),Ru=t.z.object({name:t.z.string(),description:t.z.string().optional(),iconHcs1:t.z.string().optional(),category:t.z.string().optional(),tags:t.z.array(t.z.string()).optional(),latest:Cu,latestStable:Cu.optional(),recommended:Cu,upvotes:t.z.number().int(),verified:t.z.boolean(),repoStamped:t.z.boolean(),trustScore:t.z.number().optional(),safetyScore:t.z.number().optional()}).passthrough(),xu=t.z.object({items:t.z.array(Ru),nextCursor:t.z.string().nullable()}).passthrough(),Nu=t.z.object({name:t.z.string(),version:t.z.string(),updatedAt:t.z.string(),setBy:t.z.string()}).passthrough(),zu=t.z.object({name:t.z.string(),version:t.z.string().optional(),reason:t.z.string(),replacementRef:t.z.string().optional(),deprecatedAt:t.z.string(),deprecatedBy:t.z.string()}).passthrough(),_u=t.z.object({name:t.z.string(),items:t.z.array(zu)}).passthrough(),Pu=t.z.object({jobId:t.z.string(),score:t.z.number().nullable().optional(),findings:t.z.array(t.z.unknown()).optional(),summary:t.z.unknown().optional(),generatedAt:t.z.string().nullable().optional(),scannerVersion:t.z.string().nullable().optional()}).passthrough(),Ou=t.z.enum(["version","version_verification","status","verification","repo_commit","manifest","domain","trust","tier","safety","upvotes","updated"]),Du=t.z.enum(["flat","flat-square","for-the-badge","plastic","social"]),Fu=t.z.object({schemaVersion:t.z.number().int(),label:t.z.string(),message:t.z.string(),color:t.z.string(),style:Du.optional(),isError:t.z.boolean().optional(),cacheSeconds:t.z.number().int().optional()}).passthrough(),Mu=t.z.object({tags:t.z.array(t.z.string())}).passthrough(),Uu=t.z.object({categories:t.z.array(t.z.string())}).passthrough(),Bu=t.z.record(Ac),Lu=t.z.object({name:t.z.string(),mimeType:t.z.string(),estimatedCostHbar:t.z.number()}).passthrough(),Ku=t.z.object({quoteId:t.z.string(),name:t.z.string(),version:t.z.string(),directoryTopicId:t.z.string(),estimatedCostHbar:t.z.number(),credits:t.z.number(),usdCents:t.z.number(),expiresAt:t.z.string(),files:t.z.array(Lu)}).passthrough(),$u=t.z.union([t.z.literal("pending"),t.z.literal("in_progress"),t.z.literal("completed"),t.z.literal("failed")]),Hu=t.z.object({jobId:t.z.string(),status:$u,credits:t.z.number().nullable().optional(),usdCents:t.z.number().nullable().optional(),quoteId:t.z.string().nullable().optional(),createdAt:t.z.string(),updatedAt:t.z.string(),network:t.z.union([t.z.literal("mainnet"),t.z.literal("testnet")])}).passthrough(),qu=t.z.object({jobId:t.z.string(),status:$u,network:t.z.union([t.z.literal("mainnet"),t.z.literal("testnet")]),name:t.z.string(),version:t.z.string(),directoryTopicId:t.z.string(),skillUid:t.z.number().int().nullable().optional(),directorySequenceNumber:t.z.number().int().nullable().optional(),versionRegistryTopicId:t.z.string().nullable().optional(),packageTopicId:t.z.string().nullable().optional(),manifestHrl:t.z.string().nullable().optional(),skillJsonHrl:t.z.string().nullable().optional(),iconHcs1:t.z.string().nullable().optional(),tags:t.z.array(t.z.string()).nullable().optional(),category:t.z.string().nullable().optional(),files:t.z.array(vu).nullable().optional(),quoteCredits:t.z.number().nullable().optional(),quoteUsdCents:t.z.number().nullable().optional(),safety:Tu.nullable().optional(),reservationId:t.z.string().nullable().optional(),totalCostHbar:t.z.number().nullable().optional(),totalCostCredits:t.z.number().nullable().optional(),failureReason:t.z.string().nullable().optional(),createdAt:t.z.string(),updatedAt:t.z.string()}).passthrough(),ju=t.z.object({jobId:t.z.string(),version:t.z.string(),createdAt:t.z.string(),verified:t.z.boolean().optional()}).passthrough(),Wu=t.z.object({name:t.z.string(),items:t.z.array(ju)}).passthrough(),Vu=t.z.object({name:t.z.string(),latestVersion:t.z.string(),latestCreatedAt:t.z.string(),verified:t.z.boolean().optional(),iconHcs1:t.z.string().optional(),versions:t.z.array(t.z.string())}).passthrough(),Gu=t.z.object({items:t.z.array(Vu)}).passthrough(),Ju=t.z.object({owned:Gu,upvoted:Au}).passthrough(),Yu=t.z.object({enabled:t.z.boolean(),directoryTopicId:t.z.string().nullable().optional(),maxFiles:t.z.number().int().nullable().optional(),maxTotalSizeBytes:t.z.number().int().nullable().optional(),allowedMimeTypes:t.z.array(t.z.string()).nullable().optional(),network:t.z.union([t.z.literal("mainnet"),t.z.literal("testnet")]).nullable().optional(),publisher:t.z.object({cliPackageUrl:t.z.string(),cliCommand:t.z.string(),actionMarketplaceUrl:t.z.string(),repositoryUrl:t.z.string(),guideUrl:t.z.string().nullable().optional(),docsUrl:t.z.string().nullable().optional(),submitUrl:t.z.string().nullable().optional(),skillsIndexUrl:t.z.string().nullable().optional(),quickstartCommands:t.z.array(t.z.object({id:t.z.string(),label:t.z.string(),description:t.z.string(),command:t.z.string(),href:t.z.string().nullable().optional()}).passthrough()).optional().default([]),templatePresets:t.z.array(t.z.object({presetId:t.z.string(),label:t.z.string(),description:t.z.string(),recommendedFor:t.z.string(),command:t.z.string()}).passthrough()).optional().default([])}).nullable().optional()}).passthrough(),Xu=t.z.object({name:t.z.string(),exists:t.z.boolean(),isOwner:t.z.boolean()}).passthrough(),Zu=t.z.object({name:t.z.string(),upvotes:t.z.number().int(),hasUpvoted:t.z.boolean()}).passthrough(),Qu=t.z.enum(["unclaimed","validated","published","verified","hardened"]),ed=t.z.object({kind:t.z.enum(["setup_validate","publish_first_release","verify_domain","harden_workflow","share_status"]),priority:t.z.number().int(),id:t.z.string(),label:t.z.string(),description:t.z.string(),url:t.z.string().nullable().optional(),href:t.z.string().nullable().optional(),command:t.z.string().nullable().optional()}).passthrough(),td=t.z.object({id:t.z.string(),label:t.z.string(),description:t.z.string(),command:t.z.string().optional(),href:t.z.string().optional()}).passthrough(),rd=t.z.object({schema_version:t.z.literal("skill-preview.v1"),tool_version:t.z.string(),preview_id:t.z.string(),repo_url:t.z.string(),repo_owner:t.z.string(),repo_name:t.z.string(),default_branch:t.z.string(),commit_sha:t.z.string(),ref:t.z.string(),event_name:t.z.string(),workflow_run_url:t.z.string(),skill_dir:t.z.string(),name:t.z.string(),version:t.z.string(),validation_status:t.z.literal("passed"),findings:t.z.array(t.z.unknown()),package_summary:t.z.record(t.z.string(),t.z.unknown()),suggested_next_steps:t.z.array(td),generated_at:t.z.string()}).passthrough(),id=t.z.object({id:t.z.string(),previewId:t.z.string(),source:t.z.literal("github-oidc"),report:rd,generatedAt:t.z.string(),expiresAt:t.z.string(),statusUrl:t.z.string(),authoritative:t.z.boolean()}).passthrough(),nd=t.z.object({found:t.z.boolean(),authoritative:t.z.boolean(),preview:id.nullable(),statusUrl:t.z.string().nullable(),expiresAt:t.z.string().nullable()}).passthrough(),od=t.z.object({previewId:t.z.string(),repoUrl:t.z.string(),repoOwner:t.z.string(),repoName:t.z.string(),commitSha:t.z.string(),ref:t.z.string(),eventName:t.z.string(),skillDir:t.z.string(),generatedAt:t.z.string(),expiresAt:t.z.string(),statusUrl:t.z.string()}).passthrough(),sd=t.z.object({repoCommitIntegrity:t.z.boolean(),manifestIntegrity:t.z.boolean(),domainProof:t.z.boolean()}).passthrough(),ad=t.z.object({publisherBound:t.z.boolean(),domainProof:t.z.boolean(),verifiedDomain:t.z.boolean(),previewValidated:t.z.boolean()}).passthrough(),cd=t.z.object({repoCommitIntegrity:t.z.boolean(),manifestIntegrity:t.z.boolean(),canonicalRelease:t.z.boolean(),previewAvailable:t.z.boolean(),previewAuthoritative:t.z.boolean()}).passthrough(),ld=t.z.object({name:t.z.string(),version:t.z.string().nullable(),published:t.z.boolean(),verifiedDomain:t.z.boolean(),trustTier:Qu,badgeMetric:Ou,checks:sd,nextSteps:t.z.array(ed),verificationSignals:ad,provenanceSignals:cd,publisher:Yu.shape.publisher,preview:od.nullable().optional(),statusUrl:t.z.string().nullable().optional()}).passthrough(),ud=t.z.object({min:t.z.number(),max:t.z.number()}).passthrough(),dd=t.z.object({estimatedCredits:ud,estimatedHbar:ud,pricingVersion:t.z.string(),assumptions:t.z.array(t.z.string()),purchaseUrl:t.z.string().nullable(),publishUrl:t.z.string().nullable(),verificationUrl:t.z.string().nullable()}).passthrough(),pd=t.z.object({repoUrl:t.z.string(),skillDir:t.z.string(),trustTier:Qu,actionInstalled:t.z.boolean(),previewUploaded:t.z.boolean(),previewId:t.z.string().nullable(),lastValidateSuccessAt:t.z.string().nullable(),stalePreviewAgeDays:t.z.number().nullable(),published:t.z.boolean(),verified:t.z.boolean(),publishReady:t.z.boolean(),publishBlockedByMissingAuth:t.z.boolean(),statusUrl:t.z.string().nullable(),purchaseUrl:t.z.string().nullable(),publishUrl:t.z.string().nullable(),verificationUrl:t.z.string().nullable(),nextSteps:t.z.array(ed)}).passthrough(),hd=t.z.object({url:t.z.string(),pointer:t.z.string().nullable(),sha256:t.z.string().nullable()}).passthrough(),gd=t.z.object({skillRef:t.z.string(),skillMdUrl:t.z.string(),manifestUrl:t.z.string()}).passthrough(),md=t.z.object({apiUrl:t.z.string(),imageUrl:t.z.string(),markdown:t.z.string(),html:t.z.string()}).passthrough(),fd=t.z.object({canonicalUrl:t.z.string().nullable(),latestUrl:t.z.string().nullable(),markdownLink:t.z.string().nullable(),htmlLink:t.z.string().nullable(),badge:md.nullable()}).passthrough(),yd=t.z.object({cli:t.z.string(),claude:t.z.string(),cursor:t.z.string(),codex:t.z.string(),openclaw:t.z.string()}).passthrough(),bd=t.z.object({name:t.z.string(),version:t.z.string(),skillRef:t.z.string(),network:t.z.union([t.z.literal("mainnet"),t.z.literal("testnet")]),detailUrl:t.z.string().nullable(),artifacts:t.z.object({skillMd:hd,manifest:hd}).passthrough(),resolvers:t.z.object({pinned:gd,latest:gd}).passthrough(),share:fd,snippets:yd}).passthrough(),wd=t.z.object({accepted:t.z.boolean()}).passthrough(),Id=t.z.enum(["basic","express"]),Td=t.z.enum(["pending","approved","rejected"]),Sd=t.z.enum(["not_requested","pending","approved","rejected"]),kd=t.z.enum(["missing_owner","missing_repo_or_commit","unsupported_repo","repo_fetch_failed","manifest_pointer_missing","manifest_fetch_failed","manifest_parse_failed","missing_file_hashes","missing_domain","challenge_invalid","challenge_expired","dns_lookup_failed","dns_record_missing","mismatch"]),vd=t.z.object({ok:t.z.boolean(),ownerAccountId:t.z.string().nullable(),ownerUserId:t.z.string().nullable(),checkedAt:t.z.string(),reason:kd.optional()}).passthrough(),Ed=t.z.object({path:t.z.string(),expectedSha256:t.z.string(),actualSha256:t.z.string().optional(),error:t.z.string().optional()}).passthrough(),Ad=t.z.object({ok:t.z.boolean(),repo:t.z.string().nullable(),commit:t.z.string().nullable(),checkedAt:t.z.string(),filesChecked:t.z.number().int().min(0),mismatches:t.z.array(Ed),partial:t.z.boolean().optional(),reason:kd.optional()}).passthrough(),Cd=t.z.object({path:t.z.string(),expectedSha256:t.z.string(),actualSha256:t.z.string().optional()}).passthrough(),Rd=t.z.object({ok:t.z.boolean(),manifestHrl:t.z.string().nullable(),manifestSha256:t.z.string().nullable(),checkedAt:t.z.string(),missingFiles:t.z.array(t.z.string()),shaMismatches:t.z.array(Cd),extraFiles:t.z.array(t.z.string()).optional(),reason:kd.optional()}).passthrough(),xd=t.z.object({ok:t.z.boolean(),domain:t.z.string().optional(),method:t.z.literal("dns_txt").optional(),checkedAt:t.z.string().optional(),details:t.z.string().optional(),txtRecordName:t.z.string().optional(),reason:kd.optional()}).passthrough(),Nd=t.z.object({publisherBound:vd,repoCommitIntegrity:Ad,manifestIntegrity:Rd,domainProof:xd.optional()}).passthrough(),zd=t.z.object({id:t.z.string(),network:t.z.union([t.z.literal("mainnet"),t.z.literal("testnet")]),name:t.z.string(),version:t.z.string().optional(),tier:Id,status:Td,usdCents:t.z.number(),creditsCharged:t.z.number(),creditAccountId:t.z.string().optional(),signals:Nd.optional(),reviewNotes:t.z.string().optional(),requestedBy:t.z.object({userId:t.z.string().optional(),accountId:t.z.string().optional(),email:t.z.string().optional()}).optional(),approvedBy:t.z.object({userId:t.z.string().optional(),email:t.z.string().optional()}).optional(),approvedAt:t.z.string().optional(),rejectedBy:t.z.object({userId:t.z.string().optional(),email:t.z.string().optional()}).optional(),rejectedAt:t.z.string().optional(),createdAt:t.z.string(),updatedAt:t.z.string()}).passthrough(),_d=t.z.object({request:zd}).passthrough(),Pd=t.z.object({name:t.z.string(),version:t.z.string(),status:Sd,verified:t.z.boolean(),previouslyVerified:t.z.boolean(),signals:Nd.nullable().optional(),reviewNotes:t.z.string().nullable().optional(),pendingRequest:zd.nullable().optional()}).passthrough();t.z.object({name:t.z.string().min(1),version:t.z.string().min(1).optional(),domain:t.z.string().min(1).optional()}).passthrough();const Od=t.z.object({challengeId:t.z.string().min(1),name:t.z.string().min(1),version:t.z.string().min(1),domain:t.z.string().min(1),method:t.z.literal("dns_txt"),txtRecordName:t.z.string().min(1),txtRecordValue:t.z.string().min(1),expiresAt:t.z.string().min(1)}).passthrough();t.z.object({name:t.z.string().min(1),version:t.z.string().min(1).optional(),domain:t.z.string().min(1).optional(),challengeToken:t.z.string().min(1)}).passthrough();const Dd=t.z.object({name:t.z.string().min(1),version:t.z.string().min(1),signal:xd}).passthrough();function Fd(e,t){return!e&&!t||!(!e||!t)&&(!(!e.uaid||!t.uaid||e.uaid.toLowerCase()!==t.uaid.toLowerCase())||(!(!e.ledgerAccountId||!t.ledgerAccountId||e.ledgerAccountId.toLowerCase()!==t.ledgerAccountId.toLowerCase())||(!(!e.userId||!t.userId||e.userId!==t.userId)||!(!e.email||!t.email||e.email.toLowerCase()!==t.email.toLowerCase()))))}function Md(e,t,r,i,n){if(!(void 0!==n?.decrypt?n.decrypt:!0===t.encryptionOptions?.autoDecryptHistory))return i;if(!i.history.some(e=>Boolean(e.cipherEnvelope)))return{...i,decryptedHistory:i.history.map(e=>({entry:e,plaintext:e.content}))};const o=Ud(e,t,r,n);if(!o)throw new Error("Unable to decrypt chat history: encryption context unavailable");const s=i.history.map(e=>({entry:e,plaintext:Bd(t,e,o)}));return{...i,decryptedHistory:s}}function Ud(e,t,r,i){if(i?.sharedSecret)return{sessionId:r,sharedSecret:t.normalizeSharedSecret(i.sharedSecret),identity:i.identity};const n=e.get(r);if(!n||0===n.length)return null;if(i?.identity){const e=n.find(e=>Fd(e.identity,i.identity));if(e)return e}return n[0]}function Bd(e,t,r){const i=t.cipherEnvelope;if(!i)return t.content;const n=o.Buffer.from(r.sharedSecret);try{return e.encryption.decryptCipherEnvelope({envelope:i,sharedSecret:n})}catch(s){return null}}const Ld="https://hol.org/registry/api/v1",Kd=/application\/json/i,$d=e=>{let t=e.length;for(;t>0&&47===e.charCodeAt(t-1);)t-=1;return t===e.length?e:e.slice(0,t)},Hd=()=>"function"==typeof DOMException?new DOMException("Aborted","AbortError"):new Error("The operation was aborted"),qd=e=>e.trim().toLowerCase(),jd=e=>{if(null===e)return null;if(e instanceof Date)return e.toISOString();if("string"==typeof e||"number"==typeof e||"boolean"==typeof e)return e;if(Array.isArray(e))return e.map(e=>void 0===e?null:jd(e));if("object"==typeof e){const t={};return Object.entries(e).forEach(([e,r])=>{void 0!==r&&(t[e]=jd(r))}),t}throw new TypeError("Only JSON-compatible values are supported")},Wd=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Vd=e=>{const t=jd(e);if(Wd(t))return t;throw new TypeError("Expected JSON object value")},Gd=e=>{const t={};return e.type&&(t.type=e.type),e.token&&(t.token=e.token),e.username&&(t.username=e.username),e.password&&(t.password=e.password),e.headerName&&(t.headerName=e.headerName),e.headerValue&&(t.headerValue=e.headerValue),e.headers&&(t.headers={...e.headers}),t},Jd=e=>{const t={profile:Vd(e.profile)};return void 0!==e.endpoint&&(t.endpoint=e.endpoint),void 0!==e.protocol&&(t.protocol=e.protocol),void 0!==e.communicationProtocol&&(t.communicationProtocol=e.communicationProtocol),void 0!==e.registry&&(t.registry=e.registry),void 0!==e.additionalRegistries&&(t.additionalRegistries=e.additionalRegistries),void 0!==e.metadata&&(t.metadata=Vd(e.metadata)),t};class Yd extends Error{constructor(e,t){super("Encryption is not enabled for this session"),this.sessionId=e,this.summary=t}}class Xd{constructor(e){this.client=e}registerConversationContext(e){this.client.registerConversationContextForEncryption(e)}async startSession(e){await this.client.encryptionReady();const t=await this.client.chat.createSession({uaid:e.uaid,senderUaid:e.senderUaid,encryptionRequested:!0,historyTtlSeconds:e.historyTtlSeconds,auth:e.auth});e.onSessionCreated?.(t.sessionId);const r=t.encryption;if(!r?.enabled)throw new Yd(t.sessionId,t.encryption??null);return await this.establishRequesterContext({sessionId:t.sessionId,summary:r,senderUaid:e.senderUaid,handshakeTimeoutMs:e.handshakeTimeoutMs,pollIntervalMs:e.pollIntervalMs})}async acceptSession(e){await this.client.encryptionReady();const t=await this.waitForEncryptionSummary(e.sessionId,e.handshakeTimeoutMs,e.pollIntervalMs);return await this.establishResponderContext({sessionId:e.sessionId,summary:t,responderUaid:e.responderUaid,handshakeTimeoutMs:e.handshakeTimeoutMs,pollIntervalMs:e.pollIntervalMs})}async establishRequesterContext(e){const t=this.client.encryption.generateEphemeralKeyPair();await this.client.chat.submitEncryptionHandshake(e.sessionId,{role:"requester",keyType:"secp256k1",ephemeralPublicKey:t.publicKey,uaid:e.senderUaid??e.summary.requester?.uaid??void 0});const{summary:r,record:i}=await this.waitForHandshakeCompletion(e.sessionId,e.handshakeTimeoutMs,e.pollIntervalMs),n=i.responder?.ephemeralPublicKey;if(!n)throw new Error("Responder handshake was not completed in time");const o=this.client.encryption.deriveSharedSecret({privateKey:t.privateKey,peerPublicKey:n}).subarray(),s=this.buildRecipients(r);return this.createHandle({sessionId:e.sessionId,sharedSecret:o,summary:r,recipients:s,identity:r.requester??void 0})}async establishResponderContext(e){const t=this.client.encryption.generateEphemeralKeyPair();await this.client.chat.submitEncryptionHandshake(e.sessionId,{role:"responder",keyType:"secp256k1",ephemeralPublicKey:t.publicKey,uaid:e.responderUaid??e.summary.responder?.uaid??void 0});const{summary:r,record:i}=await this.waitForHandshakeCompletion(e.sessionId,e.handshakeTimeoutMs,e.pollIntervalMs),n=i.requester?.ephemeralPublicKey;if(!n)throw new Error("Requester handshake was not detected in time");const o=this.client.encryption.deriveSharedSecret({privateKey:t.privateKey,peerPublicKey:n}).subarray(),s=this.buildRecipients(r);return this.createHandle({sessionId:e.sessionId,sharedSecret:o,summary:r,recipients:s,identity:r.responder??void 0})}async waitForHandshakeCompletion(e,t=3e4,r=1e3){const i=Date.now()+t;for(;;){const t=(await this.client.chat.getEncryptionStatus(e)).encryption,n=t?.handshake;if(t&&n&&"complete"===n.status)return{summary:t,record:n};if(Date.now()>=i)throw new Error("Timed out waiting for encrypted handshake completion");await this.delay(r)}}async waitForEncryptionSummary(e,t=3e4,r=1e3){const i=await this.client.chat.getEncryptionStatus(e);if(!i.encryption?.enabled)throw new Yd(e,i.encryption??null);return i.encryption}buildRecipients(e){const t=[e.requester,e.responder].filter(Boolean).map(e=>{if(!e)return null;const t={};return e.uaid&&(t.uaid=e.uaid),e.ledgerAccountId&&(t.ledgerAccountId=e.ledgerAccountId),e.userId&&(t.userId=e.userId),e.email&&(t.email=e.email),t}).filter(e=>Boolean(e?.uaid||e?.ledgerAccountId||e?.userId||e?.email));return t.length>0?t:e.responder?.uaid?[{uaid:e.responder.uaid}]:[]}createHandle(e){const t=e.sharedSecret,r=e.summary.requester?.uaid??e.summary.responder?.uaid??e.identity?.uaid,i=r=>this.decryptEntry(r,e.identity,t),n={sessionId:e.sessionId,mode:"encrypted",summary:e.summary,send:async i=>{const n=i.recipients??e.recipients;return this.client.chat.sendMessage({sessionId:e.sessionId,message:i.message??"[ciphertext omitted]",streaming:i.streaming,auth:i.auth,uaid:r,encryption:{plaintext:i.plaintext,sharedSecret:globalThis.Buffer.from(t),recipients:n}})},decryptHistoryEntry:i,fetchHistory:async t=>{const r=await this.client.fetchHistorySnapshot(e.sessionId,t);return r.decryptedHistory?r.decryptedHistory:r.history.map(e=>({entry:e,plaintext:i(e)}))}};return this.registerConversationContext({sessionId:e.sessionId,sharedSecret:t,identity:e.identity}),n}decryptEntry(e,t,r){const i=e.cipherEnvelope;if(!i)return null;const n=globalThis.Buffer.from(r);try{return this.client.encryption.decryptCipherEnvelope({envelope:i,sharedSecret:n})}catch(o){return null}}recipientMatches(e,t){return!(!t.uaid||e.uaid?.toLowerCase()!==t.uaid.toLowerCase())||(!(!t.ledgerAccountId||e.ledgerAccountId?.toLowerCase()!==t.ledgerAccountId.toLowerCase())||(!(!t.userId||e.userId!==t.userId)||!(!t.email||e.email?.toLowerCase()!==t.email.toLowerCase())))}async delay(e){e<=0||await new Promise(t=>setTimeout(t,e))}}async function Zd(e,t,r=!0){const i={};"uaid"in t&&t.uaid&&(i.uaid=t.uaid),"agentUrl"in t&&t.agentUrl&&(i.agentUrl=t.agentUrl),t.auth&&(i.auth=Gd(t.auth)),void 0!==t.historyTtlSeconds&&(i.historyTtlSeconds=t.historyTtlSeconds),void 0!==t.encryptionRequested&&(i.encryptionRequested=t.encryptionRequested),t.senderUaid&&(i.senderUaid=t.senderUaid);try{const t=await e.requestJson("/chat/session",{method:"POST",body:i,headers:{"content-type":"application/json"}});return e.parseWithSchema(t,Qc,"chat session response")}catch(n){const i=n instanceof Error?n:null;if(r&&e.shouldAutoTopUpHistory(t,i))return await e.executeHistoryAutoTopUp("chat.session"),Zd(e,t,!1);throw n}}async function Qd(e,t,r){const i=r.encryption?.preference??"preferred";if(!("disabled"!==i)){const t=await Zd(e,{uaid:r.uaid,auth:r.auth,historyTtlSeconds:r.historyTtlSeconds,senderUaid:r.senderUaid,encryptionRequested:!1});return r.onSessionCreated?.(t.sessionId),ep(e,t.sessionId,t.encryption??null,r.auth,{uaid:r.uaid})}try{return await t.startSession({uaid:r.uaid,senderUaid:r.senderUaid,historyTtlSeconds:r.historyTtlSeconds,handshakeTimeoutMs:r.encryption?.handshakeTimeoutMs,pollIntervalMs:r.encryption?.pollIntervalMs,onSessionCreated:e=>{r.onSessionCreated?.(e)},auth:r.auth})}catch(n){if(n instanceof Yd){if("required"===i)throw n;return ep(e,n.sessionId,n.summary??null,r.auth,{uaid:r.uaid})}throw n}}function ep(e,t,r,i,n){const o=n?.uaid?.trim(),s=n?.agentUrl?.trim();return{sessionId:t,mode:"plaintext",summary:r??null,send:async r=>{const n=r.plaintext;if(!n||0===n.trim().length)throw new Error("plaintext is required for chat messages");const a=r.message??n;return tp(e,{sessionId:t,message:a,streaming:r.streaming,auth:r.auth??i,uaid:o,agentUrl:s})},decryptHistoryEntry:e=>e.content,fetchHistory:async r=>{const i=await e.fetchHistorySnapshot(t,r);return i.decryptedHistory?i.decryptedHistory:i.history.map(e=>({entry:e,plaintext:e.content}))}}}async function tp(e,t){const r={message:t.message};void 0!==t.streaming&&(r.streaming=t.streaming),t.auth&&(r.auth=Gd(t.auth)),"uaid"in t&&(r.uaid=t.uaid),"sessionId"in t&&t.sessionId&&(r.sessionId=t.sessionId),"agentUrl"in t&&t.agentUrl&&(r.agentUrl=t.agentUrl);let i=t.cipherEnvelope??null;if(t.encryption){const n=t.encryption.sessionId??("string"==typeof r.sessionId?r.sessionId:void 0);if(!n)throw new Error("sessionId is required when using encrypted chat payloads");if(!t.encryption.recipients?.length)throw new Error("recipients are required for encrypted chat payloads");i=e.encryption.encryptCipherEnvelope({...t.encryption,sessionId:n})}i&&(r.cipherEnvelope=Vd(i));const n=await e.requestJson("/chat/message",{method:"POST",body:r,headers:{"content-type":"application/json"}});return e.parseWithSchema(n,el,"chat message response")}async function rp(e,t){const r=await e.requestJson("/encryption/keys",{method:"POST",headers:{"content-type":"application/json"},body:t});return e.parseWithSchema(r,ol,"register encryption key response")}async function ip(e,t){if(t.publicKey?.trim())return{publicKey:t.publicKey.trim()};let r=t.privateKey?.trim();const i=t.envVar??"RB_ENCRYPTION_PRIVATE_KEY";if(!r&&i&&process?.env?.[i]?.trim()&&(r=process.env[i]?.trim()),!r&&t.generateIfMissing){const r=await e.generateEncryptionKeyPair({keyType:t.keyType??"secp256k1",envVar:i,envPath:t.envPath,overwrite:t.overwriteEnv});return{publicKey:r.publicKey,privateKey:r.privateKey}}if(r){const t=function(e,t){const r=e.hexToBuffer(t),i=c.secp256k1.getPublicKey(r,!0);return o.Buffer.from(i).toString("hex")}(e,r);return{publicKey:t,privateKey:r}}return null}async function np(e,t){const r=function(e){const t={};return e.uaid&&(t.uaid=e.uaid),e.ledgerAccountId&&(t.ledgerAccountId=e.ledgerAccountId,e.ledgerNetwork&&(t.ledgerNetwork=e.ledgerNetwork)),e.email&&(t.email=e.email),t.uaid||t.ledgerAccountId||t.email?t:null}(t);if(!r)throw new Error("Auto-registration requires uaid, ledgerAccountId, or email");const i=await ip(e,t);if(!i)throw new Error("Unable to resolve encryption public key for auto-registration");return await rp(e,{keyType:t.keyType??"secp256k1",publicKey:i.publicKey,...r}),i}function op(e){return{registerKey:t=>rp(e,t),generateEphemeralKeyPair:()=>e.createEphemeralKeyPair(),deriveSharedSecret:t=>e.deriveSharedSecret(t),encryptCipherEnvelope:t=>e.buildCipherEnvelope(t),decryptCipherEnvelope:t=>e.openCipherEnvelope(t),ensureAgentKey:t=>async function(e,t){return np(e,{...t,uaid:t.uaid})}(e,t)}}async function sp(e,t={}){e.assertNodeRuntime("generateEncryptionKeyPair");if("secp256k1"!==(t.keyType??"secp256k1"))throw new Error("Only secp256k1 key generation is supported currently");const r=await(async()=>{const e=await Ta("node:crypto")??await Ta("crypto");return e&&"function"==typeof e.randomBytes?e:null})();if(!r)throw new Error("Node.js crypto module is not available; cannot generate encryption key pair");const i=r.randomBytes(32),n=o.Buffer.from(i).toString("hex"),s=c.secp256k1.getPublicKey(i,!0),a=o.Buffer.from(s).toString("hex"),l=t.envVar??"RB_ENCRYPTION_PRIVATE_KEY",u=t.envPath?await(async()=>{const e=await Ta("node:path")??await Ta("path");return e&&"function"==typeof e.resolve?e:null})():null,d=t.envPath&&u?u.resolve(t.envPath):void 0;if(t.envPath&&!d)throw new Error("Node.js path module is not available; cannot resolve encryption key env path");if(d){const e=await(async()=>{const e=await Ta("node:fs")??await Ta("fs");return e&&"function"==typeof e.existsSync&&"function"==typeof e.readFileSync&&"function"==typeof e.writeFileSync&&"function"==typeof e.appendFileSync?e:null})();if(!e)throw new Error("File system module is not available; cannot write encryption key env file");const r=`${l}=${n}`;if(e.existsSync(d)){const i=e.readFileSync(d,"utf-8"),n=new RegExp(`^${l}=.*$`,"m");if(n.test(i)){if(!t.overwrite)throw new Error(`${l} already exists in ${d}; set overwrite=true to replace it`);const o=i.replace(n,r);e.writeFileSync(d,o)}else{const t=!i.endsWith("\n");e.appendFileSync(d,`${t?"\n":""}${r}\n`)}}else e.writeFileSync(d,`${r}\n`)}return{privateKey:n,publicKey:a,envPath:d,envVar:l}}async function ap(e){const[{default:t},r,i]=await Promise.all([import("axios"),Ta("x402-axios"),Ta("x402/types")]);if(!r||!i)throw new Error("x402-axios and x402/types are required for X402 flows. Install them to enable ledger payments.");const n=r.withPaymentInterceptor;return{createPaymentClient:r=>{const i=t.create({baseURL:e.baseUrl,headers:{...e.getDefaultHeaders(),"content-type":"application/json"}});return n(i,r)},decodePaymentResponse:r.decodeXPaymentResponse,createX402Signer:i.createSigner}}function cp(e){const t=Math.ceil(1e8*e);if(t<=0)throw new Error("Calculated purchase amount must be positive");return t/1e8}async function lp(e,t){const r={accountId:t.accountId,payerKey:t.privateKey,hbarAmount:cp(t.hbarAmount)};t.memo&&(r.memo=t.memo),t.metadata&&(r.metadata=t.metadata);const i=await e.requestJson("/credits/purchase",{method:"POST",headers:{"content-type":"application/json"},body:r});return e.parseWithSchema(i,$l,"credit purchase response")}async function up(e,t){const{createPaymentClient:r,decodePaymentResponse:i}=await ap(e);if(!Number.isFinite(t.credits)||t.credits<=0)throw new Error("credits must be a positive number");if(void 0!==t.usdAmount&&(!Number.isFinite(t.usdAmount)||t.usdAmount<=0))throw new Error("usdAmount must be a positive number when provided");const n={accountId:t.accountId,credits:t.credits};void 0!==t.usdAmount&&(n.usdAmount=t.usdAmount),t.description&&(n.description=t.description),t.metadata&&(n.metadata=t.metadata);const o=r(t.walletClient),s=await o.post("/credits/purchase/x402",n),a=e.parseWithSchema(s.data,ql,"x402 credit purchase response"),c=s.headers??{},l="string"==typeof c["x-payment-response"]?c["x-payment-response"]:void 0;return{...a,paymentResponseHeader:l,paymentResponse:void 0!==l?i(l):void 0}}async function dp(e,t){const r=t.network??"base",{createX402Signer:i}=await ap(e),n=(e=>{const t=e.trim();if(!t)throw new Error("evmPrivateKey is required");return t.startsWith("0x")?t:`0x${t}`})(t.evmPrivateKey),o=await i(r,n);return up(e,{accountId:t.accountId,credits:t.credits,usdAmount:t.usdAmount,description:t.description,metadata:t.metadata,walletClient:o})}class pp extends Error{constructor(e,t){super(e),this.status=t.status,this.statusText=t.statusText,this.body=t.body}}class hp extends Error{constructor(e,t,r){super(e),this.cause=t,this.rawValue=r}}async function gp(e,t){const r=await e.requestJson("/register",{method:"POST",body:Jd(t),headers:{"content-type":"application/json"}});return e.parseWithSchema(r,Ml,"register agent response")}function mp(e,t){if(t<=0)throw new Error("creditsPerHbar must be positive");if(e<=0)throw new Error("creditsToPurchase must be positive");const r=e/t;return Math.ceil(1e8*r)/1e8}function fp(e){return!Number.isFinite(e)||e<=0?0:Math.max(Math.ceil(e),1)}async function yp(e,t,r){const i=r??null;if(!i)return;if(!i.accountId||!i.accountId.trim())throw new Error("autoTopUp.accountId is required");if(!i.privateKey||!i.privateKey.trim())throw new Error("autoTopUp.privateKey is required");for(let n=0;n<3;n+=1){const r=await wp(e,t),n=r.shortfallCredits??0;if(n<=0)return;const o=fp(n);if(o<=0)return;const s=r.creditsPerHbar??null;if(!s||s<=0)throw new Error("Unable to determine credits per HBAR for auto top-up");const a=mp(o,s);await lp(e,{accountId:i.accountId.trim(),privateKey:i.privateKey.trim(),hbarAmount:a,memo:i.memo??"Registry Broker auto top-up",metadata:{shortfallCredits:n,requiredCredits:r.requiredCredits,purchasedCredits:o}})}if(((await wp(e,t)).shortfallCredits??0)>0)throw new Error("Unable to purchase sufficient credits for registration")}async function bp(e,t){const r=await e.requestJson(`/resolve/${encodeURIComponent(t)}`,{method:"GET"});return e.parseWithSchema(r,Kc,"resolve UAID response")}async function wp(e,t){const r=await e.requestJson("/register/quote",{method:"POST",body:Jd(t),headers:{"content-type":"application/json"}});return e.parseWithSchema(r,Kl,"registration quote response")}async function Ip(e,t,r){const i=await e.requestJson(`/register/${encodeURIComponent(t)}`,{method:"PUT",body:Jd(r),headers:{"content-type":"application/json"}});return e.parseWithSchema(i,Ml,"update agent response")}async function Tp(e,t){const r=t.trim();if(!r)throw new Error("attemptId is required");try{const t=await e.requestJson(`/register/progress/${encodeURIComponent(r)}`,{method:"GET"});return e.parseWithSchema(t,Ll,"registration progress response").progress}catch(i){if(i instanceof pp&&404===i.status)return null;throw i}}async function Sp(e,t,r={}){const i=t.trim();if(!i)throw new Error("attemptId is required");const n=Math.max(250,r.intervalMs??1500),o=r.timeoutMs??3e5,s=r.throwOnFailure??!0,a=r.signal,c=Date.now();for(;;){if(a?.aborted)throw Hd();const t=await e.getRegistrationProgress(i);if(t){if(r.onProgress?.(t),"completed"===t.status)return t;if("partial"===t.status||"failed"===t.status){if(s)throw new pp("Registration did not complete successfully",{status:409,statusText:t.status,body:t});return t}}if(Date.now()-c>=o)throw new Error(`Registration progress polling timed out after ${o}ms`);await e.delay(n,a)}}async function kp(e,t){const r=await e.requestJson(`/uaids/validate/${encodeURIComponent(t)}`,{method:"GET"});return e.parseWithSchema(r,Tl,"UAID validation response")}async function vp(e,t){const r=await e.requestJson(`/uaids/connections/${encodeURIComponent(t)}/status`,{method:"GET"});return e.parseWithSchema(r,kl,"UAID connection status")}async function Ep(e,t){await e.request(`/uaids/connections/${encodeURIComponent(t)}`,{method:"DELETE"})}async function Ap(e){const t=await e.requestJson("/dashboard/stats",{method:"GET"});return e.parseWithSchema(t,vl,"dashboard stats response")}const Cp=e=>e.trim().toLowerCase(),Rp=new Map([["hedera:mainnet",{canonical:"hedera:mainnet",hederaNetwork:"mainnet"}],["mainnet",{canonical:"hedera:mainnet",hederaNetwork:"mainnet"}],["hedera-mainnet",{canonical:"hedera:mainnet",hederaNetwork:"mainnet"}],["hedera_mainnet",{canonical:"hedera:mainnet",hederaNetwork:"mainnet"}],["hedera:testnet",{canonical:"hedera:testnet",hederaNetwork:"testnet"}],["testnet",{canonical:"hedera:testnet",hederaNetwork:"testnet"}],["hedera-testnet",{canonical:"hedera:testnet",hederaNetwork:"testnet"}],["hedera_testnet",{canonical:"hedera:testnet",hederaNetwork:"testnet"}]]),xp={abstract:2741,"abstract-testnet":11124,base:8453,"base-sepolia":84532,avalanche:43114,"avalanche-fuji":43113,iotex:4689,sei:1329,"sei-testnet":1328,polygon:137,"polygon-amoy":80002,peaq:3338},Np=new Map(Object.entries(xp).map(([e,t])=>[t,e])),zp=e=>{const t=Cp(e);let r,i=(e=>/^eip155:\d+$/i.test(e)?Number.parseInt(e.split(":")[1],10):/^\d+$/.test(e)?Number.parseInt(e,10):void 0)(t);if(void 0===i){const e=xp[t];void 0!==e&&(i=e,r=t)}else Np.has(i)&&(r=Np.get(i));if(void 0===i)throw new Error('Unsupported EVM ledger network. Provide an alias like "base-sepolia" or a canonical eip155:<chainId> string.');return{canonical:`eip155:${i}`,kind:"evm",chainId:i,legacyName:r}},_p=e=>{if("string"!=typeof e||0===e.trim().length)throw new Error("Ledger network is required.");const t=Cp(e);return t.startsWith("hedera:")||t.includes("hedera-")||t.includes("hedera_")||"mainnet"===t||"testnet"===t?(e=>{const t=Cp(e),r=Rp.get(t);if(!r)throw new Error('Unsupported Hedera network. Use hedera:mainnet or hedera:testnet (legacy "mainnet"/"testnet" also accepted).');return{canonical:r.canonical,kind:"hedera",hederaNetwork:r.hederaNetwork}})(t):zp(t)},Pp=e=>new Error(`${e} is not supported by the in-memory signer`);let Op=null;const Dp=(e,t)=>{const{AccountId:r,LedgerId:i,PrivateKey:n,SignerSignature:o}=e;if(!t.privateKey)throw new Error("privateKey is required to create a ledger signer.");if(!t.accountId)throw new Error("accountId is required to create a ledger signer.");const s=r.fromString(t.accountId),a=n.fromString(t.privateKey),c=i.fromString(t.network);return{getLedgerId:()=>c,getAccountId:()=>s,getAccountKey:()=>a.publicKey,getNetwork:()=>({}),getMirrorNetwork:()=>[],sign:async e=>Promise.all(e.map(async e=>{const t=await a.sign(e);return new o({publicKey:a.publicKey,signature:t,accountId:s})})),getAccountBalance:async()=>{throw Pp("getAccountBalance")},getAccountInfo:async()=>{throw Pp("getAccountInfo")},getAccountRecords:async()=>{throw Pp("getAccountRecords")},signTransaction:async e=>{throw Pp("signTransaction")},checkTransaction:async e=>{throw Pp("checkTransaction")},populateTransaction:async e=>{throw Pp("populateTransaction")},call:async e=>{throw Pp("call")}}},Fp=async e=>Dp(await(async()=>{if(Op)return Op;const e=await Ta("@hashgraph/sdk");if(e)return Op=e,e;throw new Error("@hashgraph/sdk is required for ledger signing. Install it as a dependency to enable createPrivateKeySigner.")})(),e);async function Mp(e,t){const r=await e.createLedgerChallenge({accountId:t.accountId,network:t.network}),i=await async function(e,t){if("function"==typeof t.sign){const r=await t.sign(e);if(!r||"string"!=typeof r.signature||0===r.signature.length)throw new Error("Custom ledger signer failed to produce a signature.");return r}if(!t.signer||"function"!=typeof t.signer.sign)throw new Error("Ledger authentication requires a Hedera Signer or custom sign function.");const r=o.Buffer.from(e,"utf8"),i=await t.signer.sign([r]),n=i?.[0];if(!n)throw new Error("Signer did not return any signatures.");let s;if(n.publicKey)s=n.publicKey.toString();else if("function"==typeof t.signer.getAccountKey){const e=await t.signer.getAccountKey();e&&"function"==typeof e.toString&&(s=e.toString())}return{signature:o.Buffer.from(n.signature).toString("base64"),signatureKind:"raw",publicKey:s}}(r.message,t);return await e.verifyLedgerChallenge({challengeId:r.challengeId,accountId:t.accountId,network:t.network,signature:i.signature,signatureKind:i.signatureKind,publicKey:i.publicKey,expiresInMinutes:t.expiresInMinutes})}async function Up(e,t){const{accountId:r,network:i,signer:n,sign:o,hederaPrivateKey:s,evmPrivateKey:a,expiresInMinutes:c,setAccountHeader:l=!0,label:u,logger:d}=t,p=_p(i),h=u?` for ${u}`:"",g={accountId:r,network:p.canonical,expiresInMinutes:c};if(o)g.sign=o;else if(n)g.signer=n;else if(s){if("hedera"!==p.kind||!p.hederaNetwork)throw new Error("hederaPrivateKey can only be used with hedera:mainnet or hedera:testnet networks.");g.signer=await Fp({accountId:r,privateKey:s,network:p.hederaNetwork})}else{if(!a)throw new Error("Provide a signer, sign function, hederaPrivateKey, or evmPrivateKey to authenticate with the ledger.");{if("evm"!==p.kind)throw new Error("evmPrivateKey can only be used with CAIP-2 EVM networks (eip155:<chainId>).");const e=a.startsWith("0x")?a:`0x${a}`,t=await async function(e){try{return(await import("viem/accounts")).privateKeyToAccount(e)}catch(t){const e=new Error('EVM ledger authentication requires the optional dependency "viem". Install it to use evmPrivateKey flows.');throw e.cause=t,e}}(e);g.sign=async e=>({signature:await t.signMessage({message:e}),signatureKind:"evm",publicKey:t.publicKey})}}d?.info?.(`Authenticating ledger account ${r} (${p.canonical})${h}...`);const m=await e.authenticateWithLedger(g);return l&&e.setDefaultHeader("x-account-id",m.accountId),d?.info?.(`Ledger authentication complete${h}. Issued key prefix: ${m.apiKey.prefix}…${m.apiKey.lastFour}`),m}async function Bp(e,t={}){const r=function(e){const t=new URLSearchParams,r=(e,r)=>{r&&r.forEach(r=>{if("string"==typeof r){const i=r.trim();i.length>0&&t.append(e,i)}})};if(e.q){const r=e.q.trim();r.length>0&&t.set("q",r)}if("number"==typeof e.page&&t.set("page",e.page.toString()),"number"==typeof e.limit&&t.set("limit",e.limit.toString()),e.registry){const r=e.registry.trim();r.length>0&&t.set("registry",r)}if(r("registries",e.registries),"number"==typeof e.minTrust&&t.set("minTrust",e.minTrust.toString()),r("capabilities",e.capabilities),r("protocols",e.protocols),r("adapters",e.adapters),e.metadata&&Object.entries(e.metadata).forEach(([e,r])=>{if(!e||!Array.isArray(r)||0===r.length)return;const i=e.trim();0!==i.length&&r.forEach(e=>{null!=e&&t.append(`metadata.${i}`,String(e))})}),e.type){const r=e.type.trim();r.length>0&&"all"!==r.toLowerCase()&&t.set("type",r)}if(!0===e.verified&&t.set("verified","true"),!0===e.online&&t.set("online","true"),e.sortBy){const r=e.sortBy.trim();r.length>0&&t.set("sortBy",r)}if(e.sortOrder){const r=e.sortOrder.toLowerCase();"asc"!==r&&"desc"!==r||t.set("sortOrder",r)}const i=t.toString();return i.length>0?`?${i}`:""}(t),i=await e.requestJson(`/search${r}`,{method:"GET"});return e.parseWithSchema(i,Mc,"search response")}async function Lp(e,t){try{const r=await e.requestJson("/search",{method:"POST",body:t,headers:{"content-type":"application/json"}});return e.parseWithSchema(r,ml,"vector search response")}catch(r){if(r instanceof pp&&501===r.status){const r=await Bp(e,function(e){const t={q:e.query};let r;if("number"==typeof e.limit&&Number.isFinite(e.limit)&&(r=e.limit,t.limit=e.limit),"number"==typeof e.offset&&Number.isFinite(e.offset)&&e.offset>0){const i=r&&r>0?r:20;t.limit=i,t.page=Math.floor(e.offset/i)+1}return e.filter?.registry&&(t.registry=e.filter.registry),e.filter?.protocols?.length&&(t.protocols=[...e.filter.protocols]),e.filter?.adapter?.length&&(t.adapters=[...e.filter.adapter]),e.filter?.capabilities?.length&&(t.capabilities=e.filter.capabilities.map(e=>"number"==typeof e?e.toString(10):e)),e.filter?.type&&(t.type=e.filter.type),t}(t));return function(e){const t=e.hits.map(e=>({agent:e,score:0,highlights:{}})),r=e.total,i=e.limit,n=e.page,o=r>n*i||n>1;return{hits:t,total:r,took:0,totalAvailable:r,visible:t.length,limited:o,credits_used:0}}(r)}throw r}}async function Kp(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=new URLSearchParams;i.set("name",r),t.version&&i.set("version",t.version);const n=await e.requestJson(`/skills/verification/status?${i.toString()}`,{method:"GET"});return e.parseWithSchema(n,Pd,"skill verification status response")}class $p{constructor(e={}){this.encryptionBootstrapPromise=null,this.chatApi=null,this.encryptedChatManager=null,this.encryptionApi=null,this.conversationContexts=new Map;const{baseUrl:t=Ld,fetchImplementation:r,defaultHeaders:i,apiKey:n,accountId:o,ledgerApiKey:s,registrationAutoTopUp:a,historyAutoTopUp:c,encryption:l}=e;this.baseUrl=function(e){const t=e?.trim();let r=t&&t.length>0?t:Ld;try{const e=new URL($d(r)),t=e.hostname.toLowerCase(),i=()=>{e.pathname.startsWith("/registry")||(e.pathname="/"===e.pathname?"/registry":`/registry${e.pathname}`)};"hol.org"===t?(i(),r=e.toString()):"registry.hashgraphonline.com"!==t&&"hashgraphonline.com"!==t||(i(),e.hostname="hol.org",r=e.toString())}catch{}const i=$d(r);return/\/api\/v\d+$/i.test(i)?i:/\/api$/i.test(i)?`${i}/v1`:`${i}/api/v1`}(t);const u=r??("function"==typeof globalThis.fetch?globalThis.fetch:null);if(!u)throw new Error("A fetch implementation is required for RegistryBrokerClient");this.fetchImpl=u,this.defaultHeaders={...i??{}},Object.entries(this.defaultHeaders).forEach(([e,t])=>{const r=qd(e);r!==e&&(delete this.defaultHeaders[e],this.defaultHeaders[r]=t)});const d=this.defaultHeaders["x-ledger-api-key"]?.trim();!this.defaultHeaders["x-api-key"]&&d&&(this.defaultHeaders["x-api-key"]=d),n&&(this.defaultHeaders["x-api-key"]=n),"string"==typeof o&&o.trim().length>0&&(this.defaultHeaders["x-account-id"]=o.trim()),s&&(this.defaultHeaders["x-api-key"]||(this.defaultHeaders["x-api-key"]=s)),this.registrationAutoTopUp=a,this.historyAutoTopUp=c,this.encryptionOptions=l,this.encryptionOptions&&(this.encryptionBootstrapPromise=this.initializeEncryptionBootstrap(this.encryptionOptions))}static async initializeAgent(e){const{uaid:t,ensureEncryptionKey:r=!0,...i}=e,n=new $p(i);let o=null;if(r){const e="object"==typeof r?r:{generateIfMissing:!0};o=await n.encryption.ensureAgentKey({uaid:t,...e})}return{client:n,encryption:o}}get chat(){if(this.chatApi)return this.chatApi;const e=(t=this,r=this.getEncryptedChatManager(),{start:e=>t.startChat(e),createSession:e=>t.createSession(e),sendMessage:e=>t.sendMessage(e),endSession:e=>t.endSession(e),getHistory:(e,r)=>t.fetchHistorySnapshot(e,r),compactHistory:e=>t.compactHistory(e),getEncryptionStatus:e=>t.fetchEncryptionStatus(e),submitEncryptionHandshake:(e,r)=>t.postEncryptionHandshake(e,r),startConversation:e=>t.startConversation(e),acceptConversation:e=>t.acceptConversation(e),createEncryptedSession:e=>r.startSession(e),acceptEncryptedSession:e=>r.acceptSession(e)});var t,r;return this.chatApi=e,e}get encryption(){if(this.encryptionApi)return this.encryptionApi;const e=op(this);return this.encryptionApi=e,e}setApiKey(e){this.setDefaultHeader("x-api-key",e)}setLedgerApiKey(e){this.setDefaultHeader("x-api-key",e),delete this.defaultHeaders["x-ledger-api-key"]}setDefaultHeader(e,t){if(!e||0===e.trim().length)return;const r=qd(e);t&&0!==t.trim().length?this.defaultHeaders[r]=t.trim():delete this.defaultHeaders[r]}getDefaultHeaders(){return{...this.defaultHeaders}}async encryptionReady(){this.encryptionBootstrapPromise&&await this.encryptionBootstrapPromise}buildUrl(e){const t=e.startsWith("/")?e:`/${e}`;return`${this.baseUrl}${t}`}async request(e,t){const r=new Headers;Object.entries(this.defaultHeaders).forEach(([e,t])=>{r.set(e,t)}),t.headers&&Object.entries(t.headers).forEach(([e,t])=>{r.set(e,t)}),r.has("accept")||r.set("accept","application/json"),r.has("user-agent")||"undefined"!=typeof window&&"function"==typeof window.fetch||r.set("user-agent","@hol-org/rb-client");const i={method:t.method??"GET",headers:r};void 0!==t.body&&(i.body=JSON.stringify(t.body),r.has("content-type")||r.set("content-type","application/json"));const n=await this.fetchImpl(this.buildUrl(e),i);if(n.ok)return n;const o=await this.extractErrorBody(n);throw new pp("Registry broker request failed",{status:n.status,statusText:n.statusText,body:o})}async requestJson(e,t){const r=await this.request(e,t),i=r.headers?.get("content-type")??"";if(!Kd.test(i)){const e=await r.text();throw new hp("Expected JSON response from registry broker",e)}return await r.json()}async getAgentFeedback(e,t={}){const r=e.trim();if(!r)throw new Error("uaid is required");const i=!0===t.includeRevoked?"?includeRevoked=true":"",n=await this.requestJson(`/agents/${encodeURIComponent(r)}/feedback${i}`,{method:"GET"});return this.parseWithSchema(n,Gc,"agent feedback response")}async listAgentFeedbackIndex(e={}){const t=new URLSearchParams;"number"==typeof e.page&&Number.isFinite(e.page)&&t.set("page",String(Math.trunc(e.page))),"number"==typeof e.limit&&Number.isFinite(e.limit)&&t.set("limit",String(Math.trunc(e.limit))),e.registries?.length&&t.set("registry",e.registries.join(","));const r=t.size>0?`?${t.toString()}`:"",i=await this.requestJson(`/agents/feedback${r}`,{method:"GET"});return this.parseWithSchema(i,Xc,"agent feedback index response")}async listAgentFeedbackEntriesIndex(e={}){const t=new URLSearchParams;"number"==typeof e.page&&Number.isFinite(e.page)&&t.set("page",String(Math.trunc(e.page))),"number"==typeof e.limit&&Number.isFinite(e.limit)&&t.set("limit",String(Math.trunc(e.limit))),e.registries?.length&&t.set("registry",e.registries.join(","));const r=t.size>0?`?${t.toString()}`:"",i=await this.requestJson(`/agents/feedback/entries${r}`,{method:"GET"});return this.parseWithSchema(i,Zc,"agent feedback entries index response")}async checkAgentFeedbackEligibility(e,t){const r=e.trim();if(!r)throw new Error("uaid is required");const i=await this.requestJson(`/agents/${encodeURIComponent(r)}/feedback/eligibility`,{method:"POST",body:t,headers:{"content-type":"application/json"}});return this.parseWithSchema(i,Jc,"agent feedback eligibility response")}async submitAgentFeedback(e,t){const r=e.trim();if(!r)throw new Error("uaid is required");const i=await this.requestJson(`/agents/${encodeURIComponent(r)}/feedback`,{method:"POST",body:t,headers:{"content-type":"application/json"}});return this.parseWithSchema(i,Yc,"agent feedback submission response")}async search(e={}){return Bp(this,e)}async delegate(e){return async function(e,t){const r=await e.requestJson("/delegate",{method:"POST",body:t,headers:{"content-type":"application/json"}});return e.parseWithSchema(r,jc,"delegate response")}(this,e)}async searchErc8004ByAgentId(e){const t=Math.floor(e.chainId);if(!Number.isFinite(t)||t<=0)throw new Error("chainId must be a positive integer");const r=("bigint"==typeof e.agentId?e.agentId.toString():String(e.agentId)).trim();if(!r)throw new Error("agentId is required");const i=`${t}:${r}`;return Bp(this,{registries:["erc-8004"],limit:e.limit??1,..."number"==typeof e.page?{page:e.page}:{},..."string"==typeof e.sortBy?{sortBy:e.sortBy}:{},..."string"==typeof e.sortOrder?{sortOrder:e.sortOrder}:{},metadata:{nativeId:[i],networkKey:[`eip155:${t}`]}})}async stats(){return async function(e){const t=await e.requestJson("/stats",{method:"GET"});return e.parseWithSchema(t,Uc,"stats response")}(this)}async registries(){return async function(e){const t=await e.requestJson("/registries",{method:"GET"});return e.parseWithSchema(t,Bc,"registries response")}(this)}async getAdditionalRegistries(){return async function(e){const t=await e.requestJson("/register/additional-registries",{method:"GET"});return e.parseWithSchema(t,Pl,"additional registry catalog response")}(this)}async popularSearches(){return async function(e){const t=await e.requestJson("/popular",{method:"GET"});return e.parseWithSchema(t,Lc,"popular searches response")}(this)}async listProtocols(){return async function(e){const t=await e.requestJson("/protocols",{method:"GET"});return e.parseWithSchema(t,ll,"protocols response")}(this)}async detectProtocol(e){return async function(e,t){const r=await e.requestJson("/detect-protocol",{method:"POST",body:{message:t},headers:{"content-type":"application/json"}});return e.parseWithSchema(r,ul,"detect protocol response")}(this,e)}async registrySearchByNamespace(e,t){return async function(e,t,r){const i=new URLSearchParams;r&&i.set("q",r);const n=i.size>0?`?${i.toString()}`:"",o=await e.requestJson(`/registries/${encodeURIComponent(t)}/search${n}`,{method:"GET"});return e.parseWithSchema(o,dl,"registry search response")}(this,e,t)}async vectorSearch(e){return Lp(this,e)}async searchStatus(){return async function(e){const t=await e.requestJson("/search/status",{method:"GET"});return e.parseWithSchema(t,yl,"search status response")}(this)}async websocketStats(){return async function(e){const t=await e.requestJson("/websocket/stats",{method:"GET"});return e.parseWithSchema(t,bl,"websocket stats response")}(this)}async metricsSummary(){return async function(e){const t=await e.requestJson("/metrics",{method:"GET"});return e.parseWithSchema(t,Il,"metrics summary response")}(this)}async facets(e){return async function(e,t){const r=new URLSearchParams;t&&r.set("adapter",t);const i=r.size>0?`?${r.toString()}`:"",n=await e.requestJson(`/search/facets${i}`,{method:"GET"});return e.parseWithSchema(n,su,"search facets response")}(this,e)}async adapters(){return async function(e){const t=await e.requestJson("/adapters",{method:"GET"});return e.parseWithSchema(t,Wl,"adapters response")}(this)}async skillsConfig(){return async function(e){const t=await e.requestJson("/skills/config",{method:"GET"});return e.parseWithSchema(t,Yu,"skill registry config response")}(this)}async listSkills(e){return async function(e,t={}){const r=new URLSearchParams;t.name&&r.set("name",t.name),t.version&&r.set("version",t.version),"number"==typeof t.limit&&Number.isFinite(t.limit)&&r.set("limit",String(Math.trunc(t.limit))),t.cursor&&r.set("cursor",t.cursor),"boolean"==typeof t.includeFiles&&r.set("includeFiles",t.includeFiles?"true":"false"),t.accountId&&r.set("accountId",t.accountId),t.q&&r.set("q",t.q),t.tag&&r.set("tag",t.tag),t.category&&r.set("category",t.category),"boolean"==typeof t.featured&&r.set("featured",t.featured?"true":"false"),"boolean"==typeof t.verified&&r.set("verified",t.verified?"true":"false"),t.view&&r.set("view",t.view);const i=r.size>0?`?${r.toString()}`:"",n=await e.requestJson(`/skills${i}`,{method:"GET"});return e.parseWithSchema(n,Au,"skill registry list response")}(this,e)}async getSkillsCatalog(e){return async function(e,t={}){const r=new URLSearchParams;t.q&&r.set("q",t.q),t.category&&r.set("category",t.category),t.tags?.forEach(e=>{e.trim()&&r.append("tag",e.trim())}),"boolean"==typeof t.featured&&r.set("featured",t.featured?"true":"false"),"boolean"==typeof t.verified&&r.set("verified",t.verified?"true":"false"),t.channel&&r.set("channel",t.channel),t.sortBy&&r.set("sortBy",t.sortBy),"number"==typeof t.limit&&Number.isFinite(t.limit)&&r.set("limit",String(Math.trunc(t.limit))),t.cursor&&r.set("cursor",t.cursor);const i=r.size>0?`?${r.toString()}`:"",n=await e.requestJson(`/skills/catalog${i}`,{method:"GET"});return e.parseWithSchema(n,xu,"skill catalog response")}(this,e)}async listSkillVersions(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=new URLSearchParams;i.set("name",r);const n=await e.requestJson(`/skills/versions?${i.toString()}`,{method:"GET"});return e.parseWithSchema(n,Wu,"skill registry versions response")}(this,e)}async listMySkills(e){return async function(e,t={}){const r=new URLSearchParams;"number"==typeof t.limit&&Number.isFinite(t.limit)&&r.set("limit",String(Math.trunc(t.limit)));const i=r.size>0?`?${r.toString()}`:"",n=await e.requestJson(`/skills/mine${i}`,{method:"GET"});return e.parseWithSchema(n,Gu,"skill registry mine response")}(this,e)}async getMySkillsList(e){return async function(e,t={}){const r=new URLSearchParams;"number"==typeof t.limit&&Number.isFinite(t.limit)&&r.set("limit",String(Math.trunc(t.limit))),t.cursor&&r.set("cursor",t.cursor),t.accountId&&r.set("accountId",t.accountId);const i=r.size>0?`?${r.toString()}`:"",n=await e.requestJson(`/skills/my-list${i}`,{method:"GET"});return e.parseWithSchema(n,Ju,"skill registry my list response")}(this,e)}async quoteSkillPublish(e){return async function(e,t){const r=await e.requestJson("/skills/quote",{method:"POST",body:t,headers:{"content-type":"application/json"}});return e.parseWithSchema(r,Ku,"skill registry quote response")}(this,e)}async quoteSkillPublishPreview(e){return async function(e,t){const r=await e.requestJson("/skills/quote-preview",{method:"POST",body:t,headers:{"content-type":"application/json"}});return e.parseWithSchema(r,dd,"skill quote preview response")}(this,e)}async publishSkill(e){return async function(e,t){const r=await e.requestJson("/skills/publish",{method:"POST",body:t,headers:{"content-type":"application/json"}});return e.parseWithSchema(r,Hu,"skill registry publish response")}(this,e)}async getSkillPublishJob(e,t){return async function(e,t,r={}){const i=t.trim();if(!i)throw new Error("jobId is required");const n=new URLSearchParams;r.accountId&&n.set("accountId",r.accountId);const o=n.size>0?`?${n.toString()}`:"",s=await e.requestJson(`/skills/jobs/${encodeURIComponent(i)}${o}`,{method:"GET"});return e.parseWithSchema(s,qu,"skill registry job status response")}(this,e,t)}async getSkillOwnership(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=new URLSearchParams;i.set("name",r),t.accountId&&i.set("accountId",t.accountId);const n=await e.requestJson(`/skills/ownership?${i.toString()}`,{method:"GET"});return e.parseWithSchema(n,Xu,"skill registry ownership response")}(this,e)}async getRecommendedSkillVersion(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=new URLSearchParams;i.set("name",r);const n=await e.requestJson(`/skills/recommended?${i.toString()}`,{method:"GET"});return e.parseWithSchema(n,Nu,"skill recommended version response")}(this,e)}async setRecommendedSkillVersion(e){return async function(e,t){const r=t.name.trim(),i=t.version.trim();if(!r)throw new Error("name is required");if(!i)throw new Error("version is required");const n=await e.requestJson("/skills/recommended",{method:"POST",body:{name:r,version:i},headers:{"content-type":"application/json"}});return e.parseWithSchema(n,Nu,"skill recommended version response")}(this,e)}async getSkillDeprecations(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=new URLSearchParams;i.set("name",r);const n=await e.requestJson(`/skills/deprecations?${i.toString()}`,{method:"GET"});return e.parseWithSchema(n,_u,"skill deprecations response")}(this,e)}async setSkillDeprecation(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=t.version?.trim(),n=t.reason.trim();if(!n)throw new Error("reason is required");const o=t.replacementRef?.trim(),s=await e.requestJson("/skills/deprecate",{method:"POST",body:{name:r,version:i,reason:n,replacementRef:o},headers:{"content-type":"application/json"}});return e.parseWithSchema(s,zu,"skill deprecation response")}(this,e)}async getSkillBadge(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=new URLSearchParams;i.set("name",r),t.metric&&i.set("metric",t.metric),t.label?.trim()&&i.set("label",t.label.trim()),t.style&&i.set("style",t.style);const n=await e.requestJson(`/skills/badge?${i.toString()}`,{method:"GET"});return e.parseWithSchema(n,Fu,"skill badge response")}(this,e)}async getSkillStatus(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=new URLSearchParams;i.set("name",r),t.version?.trim()&&i.set("version",t.version.trim());const n=await e.requestJson(`/skills/status?${i.toString()}`,{method:"GET"});return e.parseWithSchema(n,ld,"skill status response")}(this,e)}async getSkillSecurityBreakdown(e){return async function(e,t){const r=t.jobId.trim();if(!r)throw new Error("jobId is required");const i=await e.requestJson(`/skills/${encodeURIComponent(r)}/security-breakdown`,{method:"GET"});return e.parseWithSchema(i,Pu,"skill security breakdown response")}(this,e)}async getSkillStatusByRepo(e){return async function(e,t){const r=t.repo.trim(),i=t.skillDir.trim();if(!r)throw new Error("repo is required");if(!i)throw new Error("skillDir is required");const n=new URLSearchParams;n.set("repo",r),n.set("skillDir",i),t.ref?.trim()&&n.set("ref",t.ref.trim());const o=await e.requestJson(`/skills/status/by-repo?${n.toString()}`,{method:"GET"});return e.parseWithSchema(o,ld,"skill status response")}(this,e)}async getSkillConversionSignalsByRepo(e){return async function(e,t){const r=t.repo.trim(),i=t.skillDir.trim();if(!r)throw new Error("repo is required");if(!i)throw new Error("skillDir is required");const n=new URLSearchParams;n.set("repo",r),n.set("skillDir",i),t.ref?.trim()&&n.set("ref",t.ref.trim());const o=await e.requestJson(`/skills/conversion-signals/by-repo?${n.toString()}`,{method:"GET"});return e.parseWithSchema(o,pd,"skill conversion signals response")}(this,e)}async uploadSkillPreviewFromGithubOidc(e){return async function(e,t){const r=t.token.trim();if(!r)throw new Error("token is required");const i=await e.requestJson("/skills/preview/github-oidc",{method:"POST",body:t.report,headers:{"content-type":"application/json",authorization:`Bearer ${r}`}});return e.parseWithSchema(i,id,"skill preview record response")}(this,e)}async getSkillPreview(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=new URLSearchParams;i.set("name",r),t.version?.trim()&&i.set("version",t.version.trim());const n=await e.requestJson(`/skills/preview?${i.toString()}`,{method:"GET"});return e.parseWithSchema(n,nd,"skill preview response")}(this,e)}async getSkillPreviewByRepo(e){return async function(e,t){const r=t.repo.trim(),i=t.skillDir.trim();if(!r)throw new Error("repo is required");if(!i)throw new Error("skillDir is required");const n=new URLSearchParams;n.set("repo",r),n.set("skillDir",i),t.ref?.trim()&&n.set("ref",t.ref.trim());const o=await e.requestJson(`/skills/preview/by-repo?${n.toString()}`,{method:"GET"});return e.parseWithSchema(o,nd,"skill preview by repo response")}(this,e)}async getSkillPreviewById(e){return async function(e,t){const r=t.trim();if(!r)throw new Error("previewId is required");const i=await e.requestJson(`/skills/preview/${encodeURIComponent(r)}`,{method:"GET"});return e.parseWithSchema(i,nd,"skill preview by id response")}(this,e)}async getSkillInstall(e){return async function(e,t){const r=t.trim();if(!r)throw new Error("skillRef is required");const i=await e.requestJson(`/skills/${encodeURIComponent(r)}/install`,{method:"GET"});return e.parseWithSchema(i,bd,"skill install response")}(this,e)}async recordSkillInstallCopy(e,t){return async function(e,t,r={}){const i=t.trim();if(!i)throw new Error("skillRef is required");const n=await e.requestJson(`/skills/${encodeURIComponent(i)}/telemetry/install-copy`,{method:"POST",body:r,headers:{"content-type":"application/json"}});return e.parseWithSchema(n,wd,"skill install copy telemetry response")}(this,e,t)}async listSkillTags(){return async function(e){const t=await e.requestJson("/skills/tags",{method:"GET"});return e.parseWithSchema(t,Mu,"skill tags response")}(this)}async listSkillCategories(){return async function(e){const t=await e.requestJson("/skills/categories",{method:"GET"});return e.parseWithSchema(t,Uu,"skill categories response")}(this)}async resolveSkillMarkdown(e){return async function(e,t){const r=t.trim();if(!r)throw new Error("skillRef is required");return(await e.request(`/skills/${encodeURIComponent(r)}/SKILL.md`,{method:"GET",headers:{accept:"text/markdown, text/plain;q=0.9, */*;q=0.8"}})).text()}(this,e)}async resolveSkillManifest(e){return async function(e,t){const r=t.trim();if(!r)throw new Error("skillRef is required");const i=await e.requestJson(`/skills/${encodeURIComponent(r)}/manifest`,{method:"GET"});return e.parseWithSchema(i,Bu,"skill resolver manifest response")}(this,e)}async getSkillVoteStatus(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=new URLSearchParams;i.set("name",r);const n=await e.requestJson(`/skills/vote?${i.toString()}`,{method:"GET"});return e.parseWithSchema(n,Zu,"skill registry vote status response")}(this,e)}async setSkillVote(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=await e.requestJson("/skills/vote",{method:"POST",body:{name:r,upvoted:t.upvoted},headers:{"content-type":"application/json"}});return e.parseWithSchema(i,Zu,"skill registry vote status response")}(this,e)}async requestSkillVerification(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=await e.requestJson("/skills/verification/request",{method:"POST",body:{name:r,version:t.version,tier:t.tier},headers:{"content-type":"application/json"}});return e.parseWithSchema(i,_d,"skill verification request create response")}(this,e)}async getSkillVerificationStatus(e){return Kp(this,e)}async createSkillDomainProofChallenge(e){return async function(e,t){const r=t.name.trim();if(!r)throw new Error("name is required");const i=await e.requestJson("/skills/verification/domain/challenge",{method:"POST",body:{name:r,version:t.version,domain:t.domain},headers:{"content-type":"application/json"}});return e.parseWithSchema(i,Od,"skill domain proof challenge response")}(this,e)}async verifySkillDomainProof(e){return async function(e,t){const r=t.name.trim(),i=t.challengeToken.trim();if(!r)throw new Error("name is required");if(!i)throw new Error("challengeToken is required");const n=await e.requestJson("/skills/verification/domain/verify",{method:"POST",body:{name:r,version:t.version,domain:t.domain,challengeToken:i},headers:{"content-type":"application/json"}});return e.parseWithSchema(n,Dd,"skill domain proof verify response")}(this,e)}async adaptersDetailed(){return async function(e){const t=await e.requestJson("/adapters/details",{method:"GET"});return e.parseWithSchema(t,iu,"adapter details response")}(this)}async adapterRegistryCategories(){return async function(e){const t=await e.requestJson("/adapters/registry/categories",{method:"GET"});return e.parseWithSchema(t,Gl,"adapter registry categories response")}(this)}async adapterRegistryAdapters(e){return async function(e,t={}){const r=new URLSearchParams;t.category&&r.set("category",t.category),t.entity&&r.set("entity",t.entity),t.keywords?.length&&r.set("keywords",t.keywords.join(",")),t.query&&r.set("query",t.query),"number"==typeof t.limit&&r.set("limit",String(t.limit)),"number"==typeof t.offset&&r.set("offset",String(t.offset));const i=r.size>0?`?${r.toString()}`:"",n=await e.requestJson(`/adapters/registry/adapters${i}`,{method:"GET"});return e.parseWithSchema(n,Yl,"adapter registry adapters response")}(this,e)}async createAdapterRegistryCategory(e){return async function(e,t){const r=await e.requestJson("/adapters/registry/categories",{method:"POST",headers:{"content-type":"application/json"},body:Vd(t)});return e.parseWithSchema(r,Xl,"adapter registry create category response").category}(this,e)}async submitAdapterRegistryAdapter(e){return async function(e,t){const r=await e.requestJson("/adapters/registry/adapters",{method:"POST",headers:{"content-type":"application/json"},body:Vd(t)});return e.parseWithSchema(r,Zl,"adapter registry submit adapter response")}(this,e)}async adapterRegistrySubmissionStatus(e){return async function(e,t){const r=await e.requestJson(`/adapters/registry/submissions/${encodeURIComponent(t)}`,{method:"GET"});return e.parseWithSchema(r,Ql,"adapter registry submission status response")}(this,e)}async resolveUaid(e){return bp(this,e)}async performRegisterAgent(e){const t=await this.requestJson("/register",{method:"POST",body:Jd(e),headers:{"content-type":"application/json"}});return this.parseWithSchema(t,Ml,"register agent response")}calculateHbarAmount(e,t){if(t<=0)throw new Error("creditsPerHbar must be positive");if(e<=0)throw new Error("creditsToPurchase must be positive");const r=e/t;return Math.ceil(1e8*r)/1e8}resolveCreditsToPurchase(e){return!Number.isFinite(e)||e<=0?0:Math.max(Math.ceil(e),1)}async ensureCreditsForRegistration(e,t){const r=t??null;if(!r)return;if(!r.accountId||!r.accountId.trim())throw new Error("autoTopUp.accountId is required");if(!r.privateKey||!r.privateKey.trim())throw new Error("autoTopUp.privateKey is required");for(let i=0;i<3;i+=1){const t=await this.getRegistrationQuote(e),i=t.shortfallCredits??0;if(i<=0)return;const n=this.resolveCreditsToPurchase(i);if(n<=0)return;const o=t.creditsPerHbar??null;if(!o||o<=0)throw new Error("Unable to determine credits per HBAR for auto top-up");const s=this.calculateHbarAmount(n,o);await this.purchaseCreditsWithHbar({accountId:r.accountId.trim(),privateKey:r.privateKey.trim(),hbarAmount:s,memo:r.memo??"Registry Broker auto top-up",metadata:{shortfallCredits:i,requiredCredits:t.requiredCredits,purchasedCredits:n}})}if(((await this.getRegistrationQuote(e)).shortfallCredits??0)>0)throw new Error("Unable to purchase sufficient credits for registration")}async registerAgent(e,t){const r=t?.autoTopUp??this.registrationAutoTopUp;if(!r)return this.performRegisterAgent(e);await this.ensureCreditsForRegistration(e,r);let i=!1;for(;;)try{return await this.performRegisterAgent(e)}catch(n){if(this.extractInsufficientCreditsDetails(n)&&!i){await this.ensureCreditsForRegistration(e,r),i=!0;continue}throw n}}async getRegistrationQuote(e){return wp(this,e)}async updateAgent(e,t){return Ip(this,e,t)}async getRegisterStatus(e){return async function(e,t){const r=await e.requestJson(`/register/status/${encodeURIComponent(t)}`,{method:"GET"});return e.parseWithSchema(r,fu,"register status response")}(this,e)}async registerOwnedMoltbookAgent(e,t){return async function(e,t,r){const i=await e.requestJson(`/register/${encodeURIComponent(t)}`,{method:"PUT",headers:{"content-type":"application/json"},body:{registered:r.registered??!0,...r.name?{name:r.name}:{},...r.description?{description:r.description}:{},...r.endpoint?{endpoint:r.endpoint}:{},...r.metadata?{metadata:r.metadata}:{}}});return e.parseWithSchema(i,yu,"moltbook owner registration update response")}(this,e,t)}async getRegistrationProgress(e){return Tp(this,e)}async waitForRegistrationCompletion(e,t){return Sp(this,e,t)}async validateUaid(e){return kp(this,e)}async getUaidConnectionStatus(e){return vp(this,e)}async closeUaidConnection(e){return Ep(this,e)}async dashboardStats(){return Ap(this)}async purchaseCreditsWithHbar(e){return lp(this,e)}async getX402Minimums(){return async function(e){const t=await e.requestJson("/credits/purchase/x402/minimums",{method:"GET"});return e.parseWithSchema(t,jl,"x402 minimums response")}(this)}async purchaseCreditsWithX402(e){return up(this,e)}async buyCreditsWithX402(e){return dp(this,e)}async generateEncryptionKeyPair(e={}){return sp(this,e)}async createLedgerChallenge(e){return async function(e,t){const r=_p(t.network),i="hedera"===r.kind?r.hederaNetwork??r.canonical:r.canonical,n=await e.requestJson("/auth/ledger/challenge",{method:"POST",headers:{"content-type":"application/json"},body:{accountId:t.accountId,network:i}});return e.parseWithSchema(n,sl,"ledger challenge response")}(this,e)}async verifyLedgerChallenge(e){return async function(e,t){const r=_p(t.network),i="hedera"===r.kind?r.hederaNetwork??r.canonical:r.canonical,n={challengeId:t.challengeId,accountId:t.accountId,network:i,signature:t.signature};t.signatureKind&&(n.signatureKind=t.signatureKind),t.publicKey&&(n.publicKey=t.publicKey),"number"==typeof t.expiresInMinutes&&(n.expiresInMinutes=t.expiresInMinutes);const o=await e.requestJson("/auth/ledger/verify",{method:"POST",headers:{"content-type":"application/json"},body:n}),s=e.parseWithSchema(o,cl,"ledger verification response");return e.setLedgerApiKey(s.key),s}(this,e)}async authenticateWithLedger(e){return Mp(this,e)}async authenticateWithLedgerCredentials(e){return Up(this,e)}async getVerificationStatus(e){return async function(e,t){const r=await e.requestJson(`/verification/status/${encodeURIComponent(t)}`,{method:"GET"});return e.parseWithSchema(r,pu,"verification status response")}(this,e)}async createVerificationChallenge(e){return async function(e,t){const r=await e.requestJson("/verification/challenge",{method:"POST",headers:{"content-type":"application/json"},body:{uaid:t}});return e.parseWithSchema(r,cu,"verification challenge response")}(this,e)}async getVerificationChallenge(e){return async function(e,t){const r=await e.requestJson(`/verification/challenge/${encodeURIComponent(t)}`,{method:"GET"});return e.parseWithSchema(r,lu,"verification challenge details response")}(this,e)}async verifyVerificationChallenge(e){return async function(e,t){const r=await e.requestJson("/verification/verify",{method:"POST",headers:{"content-type":"application/json"},body:{challengeId:t.challengeId,method:t.method??"moltbook-post"}});return e.parseWithSchema(r,uu,"verification verify response")}(this,e)}async getVerificationOwnership(e){return async function(e,t){const r=await e.requestJson(`/verification/ownership/${encodeURIComponent(t)}`,{method:"GET"});return e.parseWithSchema(r,du,"verification ownership response")}(this,e)}async verifySenderOwnership(e){return async function(e,t){const r=await e.requestJson("/verification/verify-sender",{method:"POST",headers:{"content-type":"application/json"},body:{uaid:t}});return e.parseWithSchema(r,hu,"verification sender response")}(this,e)}async verifyUaidDnsTxt(e){return async function(e,t){const r=await e.requestJson("/verification/dns/verify",{method:"POST",headers:{"content-type":"application/json"},body:{uaid:t.uaid,...void 0!==t.persist?{persist:t.persist}:{}}});return e.parseWithSchema(r,mu,"verification dns verify response")}(this,e)}async getVerificationDnsStatus(e,t){return async function(e,t,r){const i=new URLSearchParams;void 0!==r?.refresh&&i.set("refresh",String(r.refresh)),void 0!==r?.persist&&i.set("persist",String(r.persist));const n=i.toString(),o=`/verification/dns/status/${encodeURIComponent(t)}${n?`?${n}`:""}`,s=await e.requestJson(o,{method:"GET"});return e.parseWithSchema(s,mu,"verification dns status response")}(this,e,t)}async fetchHistorySnapshot(e,t){return async function(e,t,r,i){if(!r||0===r.trim().length)throw new Error("sessionId is required to fetch chat history");const n=await t.requestJson(`/chat/session/${encodeURIComponent(r)}/history`,{method:"GET"}),o=t.parseWithSchema(n,tl,"chat history snapshot response");return Md(e,t,r,o,i)}(this.conversationContexts,this,e,t)}attachDecryptedHistory(e,t,r){return Md(this.conversationContexts,this,e,t,r)}registerConversationContextForEncryption(e){!function(e,t){const r={sessionId:t.sessionId,sharedSecret:o.Buffer.from(t.sharedSecret),identity:t.identity?{...t.identity}:void 0},i=e.get(t.sessionId)??[],n=i.findIndex(e=>Fd(e.identity,r.identity));n>=0?i[n]=r:i.push(r),e.set(t.sessionId,i)}(this.conversationContexts,e)}resolveDecryptionContext(e,t){return Ud(this.conversationContexts,this,e,t)}decryptHistoryEntryFromContext(e,t,r){return Bd(this,t,r)}async createSession(e,t=!0){return Zd(this,e,t)}async startChat(e){return async function(e,t,r){if("uaid"in r&&r.uaid)return Qd(e,t,{uaid:r.uaid,senderUaid:r.senderUaid,historyTtlSeconds:r.historyTtlSeconds,auth:r.auth,encryption:r.encryption,onSessionCreated:r.onSessionCreated});if("agentUrl"in r&&r.agentUrl){const t=await Zd(e,{agentUrl:r.agentUrl,auth:r.auth,historyTtlSeconds:r.historyTtlSeconds,senderUaid:r.senderUaid});return r.onSessionCreated?.(t.sessionId),ep(e,t.sessionId,t.encryption??null,r.auth,{agentUrl:r.agentUrl,uaid:r.uaid})}throw new Error("startChat requires either uaid or agentUrl")}(this,this.getEncryptedChatManager(),e)}async startConversation(e){return Qd(this,this.getEncryptedChatManager(),e)}async acceptConversation(e){return async function(e,t,r){const i=r.encryption?.preference??"preferred";if("disabled"===i)return ep(e,r.sessionId,null);try{return await t.acceptSession({sessionId:r.sessionId,responderUaid:r.responderUaid,handshakeTimeoutMs:r.encryption?.handshakeTimeoutMs,pollIntervalMs:r.encryption?.pollIntervalMs})}catch(n){if(n instanceof Yd&&"required"!==i)return ep(e,r.sessionId,null,void 0,{uaid:r.responderUaid});throw n}}(this,this.getEncryptedChatManager(),e)}compactHistory(e){return async function(e,t){if(!t.sessionId||0===t.sessionId.trim().length)throw new Error("sessionId is required to compact chat history");const r={};"number"==typeof t.preserveEntries&&Number.isFinite(t.preserveEntries)&&t.preserveEntries>=0&&(r.preserveEntries=Math.floor(t.preserveEntries));const i=await e.requestJson(`/chat/session/${encodeURIComponent(t.sessionId)}/compact`,{method:"POST",headers:{"content-type":"application/json"},body:r});return e.parseWithSchema(i,rl,"chat history compaction response")}(this,e)}fetchEncryptionStatus(e){return async function(e,t){if(!t||0===t.trim().length)throw new Error("sessionId is required for encryption status");const r=await e.requestJson(`/chat/session/${encodeURIComponent(t)}/encryption`,{method:"GET"});return e.parseWithSchema(r,il,"session encryption status response")}(this,e)}postEncryptionHandshake(e,t){return async function(e,t,r){if(!t||0===t.trim().length)throw new Error("sessionId is required for encryption handshake");const i=await e.requestJson(`/chat/session/${encodeURIComponent(t)}/encryption-handshake`,{method:"POST",headers:{"content-type":"application/json"},body:{role:r.role,keyType:r.keyType,ephemeralPublicKey:r.ephemeralPublicKey,longTermPublicKey:r.longTermPublicKey,signature:r.signature,uaid:r.uaid,userId:r.userId,ledgerAccountId:r.ledgerAccountId,metadata:r.metadata}});return e.parseWithSchema(i,nl,"encryption handshake response").handshake}(this,e,t)}sendMessage(e){return tp(this,e)}endSession(e){return async function(e,t){await e.request(`/chat/session/${encodeURIComponent(t)}`,{method:"DELETE"})}(this,e)}createPlaintextConversationHandle(e,t,r,i){return ep(this,e,t,r,i)}getEncryptedChatManager(){if(this.encryptedChatManager)return this.encryptedChatManager;const e=new Xd(this);return this.encryptedChatManager=e,e}async extractErrorBody(e){const t=e.headers?.get("content-type")??"";if(Kd.test(t))try{return await e.json()}catch(r){return{parseError:String(r)}}try{return await e.text()}catch(r){return{parseError:String(r)}}}parseWithSchema(e,r,i){try{return r.parse(e)}catch(n){throw new hp(`Failed to parse ${i}`,n instanceof t.ZodError||n instanceof Error?n:String(n),e)}}async delay(e,t){if(e<=0){if(t?.aborted)throw Hd()}else await new Promise((r,i)=>{const n=setTimeout(()=>{t&&t.removeEventListener("abort",o),r()},e),o=()=>{clearTimeout(n),t?.removeEventListener("abort",o),i(Hd())};if(t){if(t.aborted)return clearTimeout(n),void i(Hd());t.addEventListener("abort",o,{once:!0})}})}assertNodeRuntime(e){if("undefined"==typeof process||!process.versions?.node)throw new Error(`${e} is only available in Node.js environments`)}getNodeCrypto(e){this.assertNodeRuntime(e);const t=Sa("node:crypto")??Sa("crypto");if(!t)throw new Error(`${e} requires the Node.js crypto module`);return t}getSecureRandomBytes(e,t){const r=globalThis.crypto;if(r&&"function"==typeof r.getRandomValues){const t=new Uint8Array(e);return r.getRandomValues(t),t}return this.getNodeCrypto(t).randomBytes(e)}createEphemeralKeyPair(){const e=this.getSecureRandomBytes(32,"generateEphemeralKeyPair"),t=c.secp256k1.getPublicKey(e,!0);return{privateKey:o.Buffer.from(e).toString("hex"),publicKey:o.Buffer.from(t).toString("hex")}}deriveSharedSecret(e){const{createHash:t}=this.getNodeCrypto("deriveSharedSecret"),r=this.hexToBuffer(e.privateKey),i=this.hexToBuffer(e.peerPublicKey),n=c.secp256k1.getSharedSecret(r,i,!0);return t("sha256").update(o.Buffer.from(n)).digest()}buildCipherEnvelope(e){const{createCipheriv:t,randomBytes:r}=this.getNodeCrypto("encryptCipherEnvelope"),i=this.normalizeSharedSecret(e.sharedSecret),n=r(12),s=t("aes-256-gcm",i,n),a=e.associatedData??e.sessionId,c=a?o.Buffer.from(a,"utf8").toString("base64"):void 0;a&&s.setAAD(o.Buffer.from(a,"utf8"));const l=o.Buffer.concat([s.update(o.Buffer.from(e.plaintext,"utf8")),s.final()]),u=s.getAuthTag();return{algorithm:"aes-256-gcm",ciphertext:o.Buffer.concat([l,u]).toString("base64"),nonce:n.toString("base64"),associatedData:c,keyLocator:{sessionId:e.sessionId,revision:e.revision??1},recipients:e.recipients.map(e=>({...e,encryptedShare:""}))}}openCipherEnvelope(e){const{createDecipheriv:t}=this.getNodeCrypto("decryptCipherEnvelope"),r=this.normalizeSharedSecret(e.sharedSecret),i=o.Buffer.from(e.envelope.ciphertext,"base64"),n=o.Buffer.from(e.envelope.nonce,"base64"),s=i.slice(0,i.length-16),a=i.slice(i.length-16),c=t("aes-256-gcm",r,n);e.envelope.associatedData&&c.setAAD(o.Buffer.from(e.envelope.associatedData,"base64")),c.setAuthTag(a);return o.Buffer.concat([c.update(s),c.final()]).toString(e.encoding??"utf8")}normalizeSharedSecret(e){if(o.Buffer.isBuffer(e))return o.Buffer.from(e);if(e instanceof Uint8Array)return o.Buffer.from(e);if("string"==typeof e)return this.bufferFromString(e);throw new Error("Unsupported shared secret input")}bufferFromString(e){const t=e.trim();if(!t)throw new Error("sharedSecret string cannot be empty");const r=t.startsWith("0x")?t.slice(2):t;return/^[0-9a-fA-F]+$/.test(r)&&r.length%2==0?o.Buffer.from(r,"hex"):o.Buffer.from(t,"base64")}hexToBuffer(e){const t=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(t)||t.length%2!=0)throw new Error("Expected hex-encoded value");return o.Buffer.from(t,"hex")}extractInsufficientCreditsDetails(e){if(!(e instanceof pp)||402!==e.status)return null;const t=e.body;if(!t||"object"!=typeof t||Array.isArray(t))return null;const r=t.shortfallCredits;return"number"!=typeof r||r<=0?null:{shortfallCredits:r}}extractErrorMessage(e){return"string"==typeof e?e:Wd(e)&&"string"==typeof e.error?e.error:Wd(e)&&"string"==typeof e.message?e.message:void 0}shouldAutoTopUpHistory(e,t){if(!this.historyAutoTopUp||void 0===e.historyTtlSeconds)return!1;if(!(t instanceof pp))return!1;if(402!==t.status)return!1;const r=this.extractErrorMessage(t.body);if(!r)return!0;const i=r.toLowerCase();return i.includes("history")||i.includes("chat history")}async executeHistoryAutoTopUp(e){if(!this.historyAutoTopUp)return;const t=this.historyAutoTopUp.hbarAmount&&this.historyAutoTopUp.hbarAmount>0?this.historyAutoTopUp.hbarAmount:.25;await this.purchaseCreditsWithHbar({accountId:this.historyAutoTopUp.accountId,privateKey:this.historyAutoTopUp.privateKey,hbarAmount:t,memo:this.historyAutoTopUp.memo??"registry-broker-client:chat-history-topup",metadata:{purpose:"chat-history",reason:e}})}initializeEncryptionBootstrap(e){return this.bootstrapEncryptionOptions(e).then(()=>{})}bootstrapEncryptionOptions(e){return async function(e,t){return t?.autoRegister&&!1!==t.autoRegister.enabled?np(e,t.autoRegister):null}(this,e)}}const Hp="hol-chat",qp=e=>Boolean(e)&&"object"==typeof e&&!Array.isArray(e),jp=e=>{if(!qp(e))return!1;if(e.p!==Hp)return!1;if("string"!=typeof e.request_id||0===e.request_id.trim().length)return!1;const t=e.op;return"payment_request"===t||"payment_approve"===t||"payment_decline"===t||"payment_result"===t||"job_status"===t};class Wp{constructor(e="info"){this.defaultEndpoint="https://kiloscribe.com/api/inscription-cdn",this.logger=y.getInstance({level:e,module:"HRLResolver"})}isBinaryContentType(e){return["image/","audio/","video/","application/octet-stream","application/pdf","application/zip","application/gzip","application/x-binary","application/vnd.ms-","application/x-msdownload","application/x-shockwave-flash","font/","application/wasm"].some(t=>e.startsWith(t))}parseHRL(e){if(!e)return null;const t=e.match(/^hcs:\/\/(\d+)\/([0-9]+\.[0-9]+\.[0-9]+)$/);return t?{standard:t[1],topicId:t[2]}:null}isValidHRL(e){if(!e||"string"!=typeof e)return!1;const t=this.parseHRL(e);if(!t)return!1;return!!/^[0-9]+\.[0-9]+\.[0-9]+$/.test(t.topicId)}isValidTopicId(e){return/^[0-9]+\.[0-9]+\.[0-9]+$/.test(e)}async resolve(e,t){if(this.isValidHRL(e))return this.resolveHRL(e,t);if(!this.isValidTopicId(e))throw new Error(`Invalid HRL or topic ID format: ${e}`);try{const r=new x(t.network,this.logger),i=await r.getTopicInfo(e),n=i?.memo||"";let o="1";if(n){const e=n.match(/^hcs-(\d+)/);e&&e[1]&&(o=e[1])}const s=`hcs://${o}/${e}`;return this.resolveHRL(s,t)}catch(r){this.logger.error(`Failed to get topic info for ${e}: ${r.message}`);const i=`hcs://1/${e}`;return this.resolveHRL(i,t)}}async getContentWithType(e,t){if(!this.isValidHRL(e))return{content:e,contentType:"text/plain",isBinary:!1};try{const r=await this.resolveHRL(e,t);return{content:r.content,contentType:r.contentType,isBinary:r.isBinary}}catch(zw){const t=`Error resolving HRL for content and type: ${zw.message}`;throw this.logger.error(t),new Error(t)}}async resolveHRL(e,t){const r=this.parseHRL(e);if(!r)throw new Error(`Invalid HRL format: ${e}`);const{standard:n,topicId:o}=r;this.logger.debug(`Resolving HRL reference: standard=${n}, topicId=${o}`);try{const e=`${t.cdnEndpoint||this.defaultEndpoint}/${o}?network=${t.network}`;this.logger.debug(`Fetching content from CDN: ${e}`);const r=(await i.head(e)).headers["content-type"]||"";if(this.isBinaryContentType(r)||t.returnRaw){return{content:(await i.get(e,{responseType:"arraybuffer"})).data,contentType:r,topicId:o,isBinary:!0}}if("application/json"===r){const t=await i.get(e,{responseType:"json"});if(!t.data)throw new Error(`Failed to fetch content from topic: ${o}`);return{content:t.data,contentType:r,topicId:o,isBinary:!1}}const n=await i.get(e);if(!n.data)throw new Error(`Failed to fetch content from topic: ${o}`);let s;return s="object"==typeof n.data?n.data.content||n.data.text||JSON.stringify(n.data):n.data,{content:s,contentType:r,topicId:o,isBinary:!1}}catch(zw){const t=`Error resolving HRL reference: ${zw.message}`;throw this.logger.error(t),new Error(t)}}}class Vp{constructor(e){this.nodeHash=e}update(e){return this.nodeHash.update(e),this}digest(e){return this.nodeHash.digest(e)}}class Gp{constructor(e){this.algorithm=e,this.data=[]}update(e){const t="string"==typeof e?(new TextEncoder).encode(e):new Uint8Array(e);return this.data.push(t),this}async digest(e){const t=this.concatenateArrays(this.data),r=new Uint8Array(t),i=globalThis.crypto;if(!i?.subtle)throw new Error("WebCrypto not available");const n=await i.subtle.digest(this.mapAlgorithm(this.algorithm),r);return"hex"===e?Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join(""):globalThis.Buffer.from(n)}concatenateArrays(e){const t=e.reduce((e,t)=>e+t.length,0),r=new Uint8Array(t);let i=0;for(const n of e)r.set(n,i),i+=n.length;return r}mapAlgorithm(e){return{sha256:"SHA-256",sha384:"SHA-384",sha1:"SHA-1",sha512:"SHA-512"}[e.toLowerCase()]||"SHA-256"}}class Jp{constructor(e){this.algorithm=e,this.data=[]}update(e){const t="string"==typeof e?globalThis.Buffer.from(e):e;return this.data.push(t),this}digest(e){const t=globalThis.Buffer.concat(this.data),r=this.simpleHash(t);return"hex"===e?r.toString(16).padStart(8,"0"):r.toString()}simpleHash(e){let t=0;for(let r=0;r<e.length;r++)t=(t<<5)-t+e[r]&4294967295;return Math.abs(t)}}function Yp(){const e="undefined"==typeof window,t="undefined"!=typeof globalThis?globalThis.crypto:void 0;let r,i=!1,n=!1;try{i="undefined"!=typeof process&&!!process.versions?.node}catch{i=!1}try{n=!e&&void 0!==t&&void 0!==t.subtle}catch{n=!1}return r=n?"web":i?"node":"none",{hasNodeCrypto:i,hasWebCrypto:n,isSSR:e,preferredAPI:r}}function Xp(){return"undefined"==typeof window}class Zp{constructor(e){this.nodeHmac=e}update(e){return this.nodeHmac.update(e),this}digest(e){return this.nodeHmac.digest(e)}}class Qp{constructor(e,t="sha256"){this.key=e,this.algorithm=t,this.data=[]}update(e){return this.data.push(e),this}async digest(e){const t=globalThis.Buffer.concat(this.data),r=new Uint8Array(this.key),i=globalThis.crypto;if(!i?.subtle)throw new Error("WebCrypto not available");const n=await i.subtle.importKey("raw",r,{name:"HMAC",hash:this.mapAlgorithm(this.algorithm)},!1,["sign"]),o=await i.subtle.sign("HMAC",n,new Uint8Array(t));return"hex"===e?Array.from(new Uint8Array(o)).map(e=>e.toString(16).padStart(2,"0")).join(""):globalThis.Buffer.from(o)}mapAlgorithm(e){return{sha256:"SHA-256",sha1:"SHA-1",sha512:"SHA-512"}[e.toLowerCase()]||"SHA-256"}}class eh{constructor(e,t="sha256"){this.key=e,this.algorithm=t,this.data=[]}update(e){return this.data.push(e),this}digest(e){const t=globalThis.Buffer.concat(this.data),r=this.simpleHmac(t,this.key);return"hex"===e?r.toString(16).padStart(8,"0"):r.toString()}simpleHmac(e,t){let r=0;for(let i=0;i<e.length;i++){const n=t[i%t.length];r=(r<<5)-r+e[i]+n&4294967295}return Math.abs(r)}}class th{constructor(){try{const e="crypto";this.crypto=require(e)}catch(e){throw new Error("Node.js crypto module not available")}}createHash(e){return new Vp(this.crypto.createHash(e))}createHmac(e,t){return new Zp(this.crypto.createHmac(e,t))}async pbkdf2(e,t,r,i,n){return new Promise((o,s)=>{this.crypto.pbkdf2(e,t,r,i,n,(e,t)=>{e?s(e):o(t)})})}timingSafeEqual(e,t){return this.crypto.timingSafeEqual(e,t)}}class rh{createHash(e){return new Gp(e)}createHmac(e,t){return new Qp(t,e)}async pbkdf2(e,t,r,i,n){const o=new TextEncoder,s=globalThis.crypto;if(!s?.subtle)throw new Error("WebCrypto not available");const a=await s.subtle.importKey("raw",o.encode(e),{name:"PBKDF2"},!1,["deriveBits"]),c=await s.subtle.deriveBits({name:"PBKDF2",salt:new Uint8Array(t),iterations:r,hash:this.mapDigest(n)},a,8*i);return globalThis.Buffer.from(c)}timingSafeEqual(e,t){if(e.length!==t.length)return!1;let r=0;for(let i=0;i<e.length;i++)r|=e[i]^t[i];return 0===r}mapDigest(e){return{sha256:"SHA-256",sha1:"SHA-1",sha512:"SHA-512"}[e.toLowerCase()]||"SHA-256"}}class ih{createHash(e){return new Jp(e)}createHmac(e,t){return new eh(t,e)}async pbkdf2(e,t,r,i,n){const o=new TextEncoder,s=globalThis.Buffer.from(o.encode(e));let a=globalThis.Buffer.alloc(i);for(let c=0;c<r;c++){const e=globalThis.Buffer.concat([s,t,globalThis.Buffer.from([c])]);let r=0;for(let t=0;t<e.length;t++)r=(r<<5)-r+e[t]&4294967295;a[c%i]^=255&r}return a}timingSafeEqual(e,t){if(e.length!==t.length)return!1;let r=0;for(let i=0;i<e.length;i++)r|=e[i]^t[i];return 0===r}}function nh(){switch(Yp().preferredAPI){case"node":try{return new th}catch{const e="undefined"!=typeof globalThis?globalThis.crypto:void 0;return void 0!==e?.subtle?new rh:new ih}case"web":return new rh;default:return new ih}}async function oh(e,t="sha256"){const r=nh().createHash(t),i="string"==typeof e?globalThis.Buffer.from(e):e,n=r.update(i).digest("hex");return n instanceof Promise?await n:n}const sh=["mainnet","testnet","previewnet","devnet"];function ah(e){return sh.includes(e)}const ch=/^hedera:(mainnet|testnet|previewnet|devnet):\d+\.\d+\.\d+(?:-[a-zA-Z0-9]{5})?$/;function lh(e){return ch.test(e)}function uh(e,t){if(!ah(e))throw new Error("Invalid Hedera network");if(t.startsWith("hedera:")){if(lh(t))return t;throw new Error("Invalid Hedera CAIP-10 account")}if(!/^\d+\.\d+\.\d+(?:-[a-zA-Z0-9]{5})?$/.test(t))throw new Error("Invalid Hedera accountId format");return`hedera:${e}:${t}`}function dh(e){if(!lh(e))throw new Error("Invalid Hedera CAIP-10");const[,t,r]=e.match(/^hedera:([^:]+):(.+)$/);return{network:t,accountId:r}}const ph=/^eip155:(\d+):(0x[0-9a-fA-F]{39,40})$/;function hh(e){return ph.test(e)}function gh(e,t){const r=`eip155:${"number"==typeof e?String(e):e}:${t.startsWith("0x")?t:`0x${t}`}`;if(!hh(r))throw new Error("Invalid EIP-155 CAIP-10");return r}var mh=(e=>(e[e.PERSONAL=0]="PERSONAL",e[e.AI_AGENT=1]="AI_AGENT",e[e.MCP_SERVER=2]="MCP_SERVER",e[e.FLORA=3]="FLORA",e))(mh||{}),fh=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(fh||{}),yh=(e=>(e[e.REST=0]="REST",e[e.WEBSOCKET=1]="WEBSOCKET",e[e.GRPC=2]="GRPC",e))(yh||{}),bh=(e=>(e[e.TEXT_GENERATION=0]="TEXT_GENERATION",e[e.IMAGE_GENERATION=1]="IMAGE_GENERATION",e[e.AUDIO_GENERATION=2]="AUDIO_GENERATION",e[e.VIDEO_GENERATION=3]="VIDEO_GENERATION",e[e.CODE_GENERATION=4]="CODE_GENERATION",e[e.LANGUAGE_TRANSLATION=5]="LANGUAGE_TRANSLATION",e[e.SUMMARIZATION_EXTRACTION=6]="SUMMARIZATION_EXTRACTION",e[e.KNOWLEDGE_RETRIEVAL=7]="KNOWLEDGE_RETRIEVAL",e[e.DATA_INTEGRATION=8]="DATA_INTEGRATION",e[e.MARKET_INTELLIGENCE=9]="MARKET_INTELLIGENCE",e[e.TRANSACTION_ANALYTICS=10]="TRANSACTION_ANALYTICS",e[e.SMART_CONTRACT_AUDIT=11]="SMART_CONTRACT_AUDIT",e[e.GOVERNANCE_FACILITATION=12]="GOVERNANCE_FACILITATION",e[e.SECURITY_MONITORING=13]="SECURITY_MONITORING",e[e.COMPLIANCE_ANALYSIS=14]="COMPLIANCE_ANALYSIS",e[e.FRAUD_DETECTION=15]="FRAUD_DETECTION",e[e.MULTI_AGENT_COORDINATION=16]="MULTI_AGENT_COORDINATION",e[e.API_INTEGRATION=17]="API_INTEGRATION",e[e.WORKFLOW_AUTOMATION=18]="WORKFLOW_AUTOMATION",e))(bh||{}),wh=(e=>(e[e.RESOURCE_PROVIDER=0]="RESOURCE_PROVIDER",e[e.TOOL_PROVIDER=1]="TOOL_PROVIDER",e[e.PROMPT_TEMPLATE_PROVIDER=2]="PROMPT_TEMPLATE_PROVIDER",e[e.LOCAL_FILE_ACCESS=3]="LOCAL_FILE_ACCESS",e[e.DATABASE_INTEGRATION=4]="DATABASE_INTEGRATION",e[e.API_INTEGRATION=5]="API_INTEGRATION",e[e.WEB_ACCESS=6]="WEB_ACCESS",e[e.KNOWLEDGE_BASE=7]="KNOWLEDGE_BASE",e[e.MEMORY_PERSISTENCE=8]="MEMORY_PERSISTENCE",e[e.CODE_ANALYSIS=9]="CODE_ANALYSIS",e[e.CONTENT_GENERATION=10]="CONTENT_GENERATION",e[e.COMMUNICATION=11]="COMMUNICATION",e[e.DOCUMENT_PROCESSING=12]="DOCUMENT_PROCESSING",e[e.CALENDAR_SCHEDULE=13]="CALENDAR_SCHEDULE",e[e.SEARCH=14]="SEARCH",e[e.ASSISTANT_ORCHESTRATION=15]="ASSISTANT_ORCHESTRATION",e))(wh||{}),Ih=(e=>(e.DNS="dns",e.SIGNATURE="signature",e.CHALLENGE="challenge",e))(Ih||{}),Th=(e=>(e.PUBLIC="PUBLIC",e.CONTROLLED="CONTROLLED",e.FEE_BASED="FEE_BASED",e))(Th||{});const Sh=["twitter","github","discord","telegram","linkedin","youtube","website","x"],kh={text_generation:0,image_generation:1,audio_generation:2,video_generation:3,code_generation:4,language_translation:5,summarization:6,extraction:6,knowledge_retrieval:7,data_integration:8,data_visualization:8,market_intelligence:9,transaction_analytics:10,smart_contract_audit:11,governance:12,security_monitoring:13,compliance_analysis:14,fraud_detection:15,multi_agent:16,api_integration:17,workflow_automation:18},vh={resource_provider:0,tool_provider:1,prompt_template_provider:2,local_file_access:3,database_integration:4,api_integration:5,web_access:6,knowledge_base:7,memory_persistence:8,code_analysis:9,content_generation:10,communication:11,document_processing:12,calendar_schedule:13,search:14,assistant_orchestration:15},Eh=t.z.object({platform:t.z.string().min(1),handle:t.z.string().min(1)}),Ah=t.z.object({type:t.z.nativeEnum(fh),capabilities:t.z.array(t.z.nativeEnum(bh)).min(1),model:t.z.string().min(1),creator:t.z.string().optional()}),Ch=t.z.object({url:t.z.string().min(1),transport:t.z.enum(["stdio","sse"])}),Rh=t.z.object({type:t.z.nativeEnum(Ih),value:t.z.string(),dns_field:t.z.string().optional(),challenge_path:t.z.string().optional()}),xh=t.z.object({minVersion:t.z.string().optional()}),Nh=t.z.object({name:t.z.string().min(1),description:t.z.string().min(1)}),zh=t.z.object({name:t.z.string().min(1),description:t.z.string().min(1)}),_h=t.z.object({version:t.z.string().min(1),connectionInfo:Ch,services:t.z.array(t.z.nativeEnum(wh)).min(1),description:t.z.string().min(1),verification:Rh.optional(),host:xh.optional(),capabilities:t.z.array(t.z.string()).optional(),resources:t.z.array(Nh).optional(),tools:t.z.array(zh).optional(),maintainer:t.z.string().optional(),repository:t.z.string().optional(),docs:t.z.string().optional()}),Ph=t.z.object({version:t.z.string().min(1),type:t.z.nativeEnum(mh),display_name:t.z.string().min(1),alias:t.z.string().optional(),bio:t.z.string().optional(),socials:t.z.array(Eh).optional(),profileImage:t.z.string().optional(),uaid:t.z.string().optional(),properties:t.z.record(t.z.any()).optional(),inboundTopicId:t.z.string().optional(),outboundTopicId:t.z.string().optional(),base_account:t.z.string().optional()}),Oh=Ph.extend({type:t.z.literal(mh.PERSONAL),language:t.z.string().optional(),timezone:t.z.string().optional()}),Dh=Ph.extend({type:t.z.literal(mh.AI_AGENT),aiAgent:Ah}),Fh=Ph.extend({type:t.z.literal(mh.MCP_SERVER),mcpServer:_h}),Mh=t.z.object({version:t.z.string(),type:t.z.literal(mh.FLORA),display_name:t.z.string().min(1),members:t.z.array(t.z.object({accountId:t.z.string(),publicKey:t.z.string().optional(),weight:t.z.number().optional()})),threshold:t.z.number().min(1),topics:t.z.object({communication:t.z.string(),transaction:t.z.string(),state:t.z.string()}),inboundTopicId:t.z.string(),outboundTopicId:t.z.string(),bio:t.z.string().optional(),metadata:t.z.record(t.z.any()).optional(),policies:t.z.record(t.z.any()).optional()}),Uh=t.z.union([Oh,Dh,Fh,Mh]),Bh={avif:"image/avif",gif:"image/gif",jpeg:"image/jpeg",jpg:"image/jpeg",json:"application/json",png:"image/png",svg:"image/svg+xml",txt:"text/plain",webp:"image/webp"};class Lh{constructor(e){this.client=e.client??("mainnet"===e.network?r.Client.forMainnet():r.Client.forTestnet()),this.auth=e.auth,this.network=e.network,this.operatorId=e.auth.operatorId,this.logger=y.getInstance({level:e.logLevel||"info",module:"HCS-11",silent:e.silent}),this.mirrorNode=new x(this.network,this.logger),this.auth.privateKey?(this.operatorCtx=B({network:this.network,operatorId:this.operatorId,operatorKey:this.auth.privateKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:this.client}),this.client=this.operatorCtx.client,this.keyType=this.operatorCtx.keyType,this.operatorCtx.ensureInitialized(),this.client.setOperator(this.operatorId.toString(),this.operatorCtx.operatorKey)):this.keyType=e.keyType||"ed25519"}getClient(){return this.client}getOperatorId(){return this.auth.operatorId}async initializeOperator(){if(this.operatorCtx)try{await this.operatorCtx.ensureInitialized(),this.keyType=this.operatorCtx.keyType,this.client.setOperator(this.operatorId,this.operatorCtx.operatorKey)}catch(e){this.logger.warn(`Failed to verify operator key with mirror node: ${e.message}`)}}createPersonalProfile(e,t){return{version:"1.0",type:mh.PERSONAL,display_name:e,alias:t?.alias,bio:t?.bio,socials:t?.socials,profileImage:t?.profileImage,properties:t?.properties,inboundTopicId:t?.inboundTopicId,outboundTopicId:t?.outboundTopicId,base_account:t?.baseAccount}}createAIAgentProfile(e,t,r,i,n){const o=this.validateProfile({version:"1.0",type:mh.AI_AGENT,display_name:e,alias:n?.alias,bio:n?.bio,socials:n?.socials,profileImage:n?.profileImage,properties:n?.properties,inboundTopicId:n?.inboundTopicId,outboundTopicId:n?.outboundTopicId,base_account:n?.baseAccount,aiAgent:{type:t,capabilities:r,model:i,creator:n?.creator}});if(!o.valid)throw new Error(`Invalid AI Agent Profile: ${o.errors.join(", ")}`);return{version:"1.0",type:mh.AI_AGENT,display_name:e,alias:n?.alias,bio:n?.bio,socials:n?.socials,profileImage:n?.profileImage,properties:n?.properties,inboundTopicId:n?.inboundTopicId,outboundTopicId:n?.outboundTopicId,base_account:n?.baseAccount,aiAgent:{type:t,capabilities:r,model:i,creator:n?.creator}}}createMCPServerProfile(e,t,r){const i=this.validateProfile({version:"1.0",type:mh.MCP_SERVER,display_name:e,alias:r?.alias,bio:r?.bio,socials:r?.socials,profileImage:r?.profileImage,properties:r?.properties,inboundTopicId:r?.inboundTopicId,outboundTopicId:r?.outboundTopicId,mcpServer:t});if(!i.valid)throw new Error(`Invalid MCP Server Profile: ${i.errors.join(", ")}`);return{version:"1.0",type:mh.MCP_SERVER,display_name:e,alias:r?.alias,bio:r?.bio,socials:r?.socials,profileImage:r?.profileImage,properties:r?.properties,inboundTopicId:r?.inboundTopicId,outboundTopicId:r?.outboundTopicId,mcpServer:t}}validateProfile(e){const t=Uh.safeParse(e);if(t.success)return{valid:!0,errors:[]};return{valid:!1,errors:t.error.errors.map(e=>{const t=e.path.join(".");let r=e.message;if("invalid_type"===e.code)r=`Expected ${e.expected}, got ${e.received}`;else if("invalid_enum_value"===e.code){const t=e.options?.join(", ");r=`Invalid value. Valid options are: ${t}`}else"too_small"===e.code&&"string"===e.type&&(r="Cannot be empty");return`${t}: ${r}`})}}profileToJSONString(e){return JSON.stringify(e)}parseProfileFromString(e){try{const t=JSON.parse(e),r=this.validateProfile(t);return r.valid?t:(this.logger.error("Invalid profile format:",r.errors),null)}catch(t){return this.logger.error("Error parsing profile:"),null}}setProfileForAccountMemo(e,t=1){return`hcs-11:hcs://${t}/${e}`}async executeTransaction(e){try{if(this.auth.privateKey){const t=await e.signWithOperator(this.client),i=await t.execute(this.client),n=await i.getReceipt(this.client);return n.status.toString()!==r.Status.Success.toString()?{success:!1,error:`Transaction failed: ${n.status.toString()}`}:{success:!0,result:n}}if(!this.auth.signer)throw new Error("No valid authentication method provided");const t=this.auth.signer,i=await e.freezeWithSigner(t),n=await i.executeWithSigner(t),o=await n.getReceiptWithSigner(t);return o.status.toString()!==r.Status.Success.toString()?{success:!1,error:`Transaction failed: ${o.status.toString()}: ${r.Status.Success.toString()}`}:{success:!0,result:o}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error during transaction execution"}}}async inscribeImage(e,t,i){try{const n=i?.progressCallback,o=new ts({module:"HCS11-Image",logger:this.logger,callback:n});o.preparing("Preparing to inscribe image",0);const s=(e=>{const t=e.trim(),r=t.lastIndexOf(".");if(r<1||r===t.length-1)return"application/octet-stream";const i=t.substring(r+1).toLowerCase();return Bh[i]??"application/octet-stream"})(t),a=i?.waitForConfirmation??!0;let c;if(this.auth.signer){if(!("accountId"in this.auth.signer))throw o.failed("Signer must be a DAppSigner for inscription"),new Error("Signer must be a DAppSigner for inscription");o.preparing("Using signer for inscription",10),c=await Fa({type:"buffer",buffer:e,fileName:t,mimeType:s},this.auth.signer,{network:this.network,waitForConfirmation:a,waitMaxAttempts:150,waitIntervalMs:4e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);o.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}else{if(!this.auth.privateKey)throw o.failed("Private key is required for inscription"),this.logger.error("Private key is required for inscription"),new Error("Private key is required for inscription");o.preparing("Using private key for inscription",10);const i="ecdsa"===this.keyType?r.PrivateKey.fromStringECDSA(this.auth.privateKey):r.PrivateKey.fromStringED25519(this.auth.privateKey);c=await Oa({type:"buffer",buffer:e,fileName:t,mimeType:s},{accountId:this.auth.operatorId,privateKey:i,network:this.network},{waitForConfirmation:a,waitMaxAttempts:150,waitIntervalMs:2e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);o.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}if(c.confirmed)return o.completed("Image inscription completed",{topicId:Ha(c.inscription)}),{imageTopicId:Ha(c.inscription)||"",transactionId:c.result.jobId,success:!0};{const e=c.quote?"quote-only":c.result.jobId;return o.verifying("Waiting for inscription confirmation",50,{jobId:e}),{imageTopicId:"",transactionId:e,success:!1,error:"Inscription not confirmed"}}}catch(n){return this.logger.error("Error inscribing image:",n),{imageTopicId:"",transactionId:"",success:!1,error:n instanceof Error?n.message:"Error inscribing image"}}}async inscribeProfile(e,t){this.logger.info("Inscribing HCS-11 profile");const i=t?.progressCallback,n=new ts({module:"HCS11-Profile",logger:this.logger,callback:i});await this.attachUaidIfMissing(e),n.preparing("Validating profile data",5);const o=this.validateProfile(e);if(!o.valid)return n.failed(`Invalid profile: ${o.errors.join(", ")}`),{profileTopicId:"",transactionId:"",success:!1,error:`Invalid profile: ${o.errors.join(", ")}`};n.preparing("Formatting profile for inscription",15);const s=this.profileToJSONString(e),a=`profile-${e.display_name.toLowerCase().replace(/\s+/g,"-")}.json`;try{const e=globalThis.Buffer.from(s,"utf-8"),t="application/json";n.preparing("Preparing profile for inscription",20);const i={type:"buffer",buffer:e,fileName:a,mimeType:t},o={waitForConfirmation:!0,mode:"file",network:this.network,waitMaxAttempts:100,waitIntervalMs:2e3,progressCallback:e=>{const t=20+.75*Number(e?.progressPercent||0);n?.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}};let c;if(n.submitting("Submitting profile to Hedera network",30),this.auth.privateKey){const e="ecdsa"===this.keyType?r.PrivateKey.fromStringECDSA(this.auth.privateKey):r.PrivateKey.fromStringED25519(this.auth.privateKey);c=await Oa(i,{accountId:this.auth.operatorId,privateKey:e,network:this.network},o)}else{if(!this.auth.signer)throw new Error("No authentication method available - neither private key nor signer");c=await Fa(i,this.auth.signer,o)}if(!c.confirmed||!Ha(c.inscription))return n.failed("Failed to inscribe profile content"),{profileTopicId:"",transactionId:"",success:!1,error:"Failed to inscribe profile content"};const l=Ha(c.inscription);return n.completed("Profile inscription completed",{topicId:l,transactionId:c.result.transactionId}),{profileTopicId:l,transactionId:c.result.transactionId,success:!0,totalCostHbar:c.costSummary?.totalCostHbar}}catch(c){return n.failed(`Error inscribing profile: ${c.message||"Unknown error"}`),{profileTopicId:"",transactionId:"",success:!1,error:c.message||"Unknown error during inscription"}}}async attachUaidIfMissing(e){if(!e.uaid&&ah(this.network))try{const{HCS14Client:t}=await Promise.resolve().then(()=>uf),r=new t({client:this.client}),i=await r.createDid({method:"hedera",client:this.client}),n=uh(this.network,this.auth.operatorId);let o=this.auth.operatorId;const s=e.inboundTopicId;if(s&&s.trim().length>0)o=`${s}@${this.auth.operatorId}`;else try{const e=await this.fetchProfileByAccountId(this.auth.operatorId,this.network),t=e?.topicInfo?.inboundTopic;t&&t.trim().length>0&&(o=`${t}@${this.auth.operatorId}`)}catch{}const a=r.createUaid(i,{proto:"hcs-10",nativeId:n,uid:o});e.uaid=a}catch(zw){this.logger.warn("Hiero registrar not available; skipping UAID generation for profile",zw)}}async updateAccountMemoWithProfile(e,t,i){try{this.logger.info(`Updating account memo for ${e} with profile ${t}`);const n=this.setProfileForAccountMemo(t),o=(new r.AccountUpdateTransaction).setAccountMemo(n).setAccountId(e);if(i&&i.length>0){let e=await o.freezeWith(this.client);for(const r of i)e=await e.sign(r);const t=await e.execute(this.client),n=await t.getReceipt(this.client);return n.status.toString()!==r.Status.Success.toString()?{success:!1,error:`Transaction failed: ${n.status.toString()}`}:{success:!0,result:n}}return this.executeTransaction(o)}catch(n){return this.logger.error(`Error updating account memo: ${n instanceof Error?n.message:"Unknown error"}`),{success:!1,error:n instanceof Error?n.message:"Unknown error updating account memo"}}}async createAndInscribeProfile(e,t=!0,r){const i=r?.progressCallback,n=new ts({module:"HCS11-ProfileCreation",logger:this.logger,callback:i});n.preparing("Starting profile creation process",0);const o=n.createSubProgress({minPercent:0,maxPercent:80,logPrefix:"Inscription"}),s=await this.inscribeProfile(e,{...r,progressCallback:e=>{o.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent,details:e.details})}});if(!s?.success)return n.failed("Profile inscription failed",{error:s?.error}),s;if(n.confirming("Profile inscribed, updating account memo",85),t){const e=await this.updateAccountMemoWithProfile(this.auth.operatorId,s.profileTopicId);if(!e.success)return n.failed("Failed to update account memo",{error:e?.error}),{...s,success:!1,error:e?.error}}return n.completed("Profile creation completed successfully",{profileTopicId:s.profileTopicId,transactionId:s.transactionId,totalCostHbar:s.totalCostHbar}),s}async getCapabilitiesFromTags(e){const t=[];if(0===e.length)return[bh.TEXT_GENERATION];for(const r of e){const e=kh[r.toLowerCase()];void 0===e||t.includes(e)||t.push(e)}return 0===t.length&&t.push(bh.TEXT_GENERATION),t}getAgentTypeFromMetadata(e){return"autonomous"===e.type?fh.AUTONOMOUS:fh.MANUAL}async fetchProfileByAccountId(e,t){try{this.logger.debug(`Fetching profile for account ${e.toString()} on ${this.network}`);const i=await this.mirrorNode.getAccountMemo(e.toString());if(this.logger.debug(`Got account memo: ${i}`),!i?.startsWith("hcs-11:"))return{success:!1,error:`Account ${e.toString()} does not have a valid HCS-11 memo. Current memo: ${i||"empty"}`};this.logger.debug(`Found HCS-11 memo: ${i}`);const n=i.substring(7);if(!n?.startsWith("hcs://")){if(n.startsWith("ipfs://")){this.logger.warn("IPFS protocol references are not fully supported");const e=await fetch(`https://ipfs.io/ipfs/${n.replace("ipfs://","")}`),t=await e.json(),r=Uh.safeParse(t);return r.success?{success:!0,profile:r.data,topicInfo:{inboundTopic:r.data.inboundTopicId||"",outboundTopic:r.data.outboundTopicId||"",profileTopicId:""}}:{success:!1,error:`Invalid HCS-11 profile data from IPFS reference ${n}`}}if(n.startsWith("ar://")){const e=n.replace("ar://",""),t=await fetch(`https://arweave.net/${e}`);if(!t.ok)return{success:!1,error:`Failed to fetch profile from Arweave ${e}: ${t.statusText}`};const r=await t.json(),i=Uh.safeParse(r);return i.success?{success:!0,profile:i.data,topicInfo:{inboundTopic:i.data.inboundTopicId||"",outboundTopic:i.data.outboundTopicId||"",profileTopicId:""}}:{success:!1,error:`Invalid HCS-11 profile data from Arweave reference ${e}`}}return{success:!1,error:`Invalid protocol reference format: ${n}`}}{const e=n.match(/hcs:\/\/(\d+)\/(.+)/);if(!e)return{success:!1,error:`Invalid HCS protocol reference format: ${n}`};const[i,o,s]=e,a=t||this.network||"mainnet";this.logger.debug(`Retrieving profile from Kiloscribe CDN: ${s}`);const c=`https://kiloscribe.com/api/inscription-cdn/${s}?network=${a}`;try{const e=await fetch(c);if(!e.ok)return{success:!1,error:`Failed to fetch profile from Kiloscribe CDN: ${e.statusText}`};const t=await e.json();if(!t)return{success:!1,error:`No profile data found for topic ${s}`};const r=Uh.safeParse(t);return r.success?{success:!0,profile:r.data,topicInfo:{inboundTopic:r.data.inboundTopicId||"",outboundTopic:r.data.outboundTopicId||"",profileTopicId:s}}:{success:!1,error:`Invalid HCS-11 profile data for topic ${s}`}}catch(r){return this.logger.error(`Error retrieving from Kiloscribe CDN: ${r.message}`),{success:!1,error:`Error retrieving from Kiloscribe CDN: ${r.message}`}}}}catch(i){return this.logger.error(`Error fetching profile: ${i.message}`),{success:!1,error:`Error fetching profile: ${i.message}`}}}}class Kh{async checkRegistrationStatus(e,t,r,i){try{const n=await fetch(`${r}/api/request-confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Network":t},body:JSON.stringify({transaction_id:e})});if(!n.ok){const e=`Failed to confirm registration: ${n.statusText}`;throw i&&i.error(e),new Error(e)}return await n.json()}catch(n){throw i&&i.error(`Error checking registration status: ${n.message}`),n}}async waitForRegistrationConfirmation(e,t,r,i=60,n=2e3,o){let s=0;for(;s<i;){o&&o.info(`Checking registration status. Attempt ${s+1}/${i}`);const a=await this.checkRegistrationStatus(e,t,r,o);if("success"===a.status)return o&&o.info("Registration confirmed successfully"),!0;if("failed"===a.status)throw o&&o.error("Registration confirmation failed"),new Error("Registration confirmation failed");o&&o.info(`Registration still pending. Waiting ${n}ms before next attempt`),await new Promise(e=>setTimeout(e,n)),s++}return o&&o.warn(`Registration not confirmed after ${i} attempts`),!1}async executeRegistration(e,t="mainnet",r="https://moonscape.tech",i){try{i&&i.info("Registering agent with guarded registry");try{const r=new Lh({network:t,auth:{operatorId:"0.0.0"}});i?.info(`Fetching profile by account ID ${e} on ${t}`),await b(5e3);const n=await r.fetchProfileByAccountId(e,t);if(i?.info("Profile fetched",n),n?.error)return i?.error("Error fetching profile",n.error),{error:n.error,success:!1};if(!n?.success||!n?.profile)return i&&i.error("Profile not found for agent registration"),{error:"Profile not found for the provided account ID",success:!1};if(!n.profile.inboundTopicId)return i&&i.error("Missing inbound topic ID in profile"),{error:"Profile is missing required inbound topic ID",success:!1};if(!n.profile.outboundTopicId)return i&&i.error("Missing outbound topic ID in profile"),{error:"Profile is missing required outbound topic ID",success:!1};i&&i.info(`Profile validation successful. Inbound topic: ${n.profile.inboundTopicId}, Outbound topic: ${n.profile.outboundTopicId}`)}catch(n){return i&&i.error(`Error validating profile: ${n.message}`),{error:`Error validating profile: ${n.message}`,success:!1}}const o=await fetch(`${r}/api/request-register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"*/*","Accept-Language":"en;q=0.5",Origin:r,Referer:`${r}/`,"X-Network":t},body:JSON.stringify({accountId:e})}),s=await o.json();return o.ok?(i&&i.info(`Created new registration request. Transaction ID: ${s.transaction_id}`),{transactionId:s.transaction_id,transaction:s.transaction,success:!0}):s.details?.length>0?{validationErrors:s.details,error:s.error||"Validation failed",success:!1}:{error:s.error||"Failed to register agent",success:!1}}catch(o){return{error:`Error during registration request: ${o.message}`,success:!1}}}async findRegistrations(e={},t="https://moonscape.tech"){try{const r=new URLSearchParams;e.tags?.forEach(e=>r.append("tags",e.toString())),e.accountId&&r.append("accountId",e.accountId),e.network&&r.append("network",e.network);const i=await fetch(`${t}/api/registrations?${r}`,{headers:{Accept:"*/*","Accept-Language":"en;q=0.5",Origin:t,Referer:`${t}/`}});if(!i.ok){return{registrations:[],error:await i.text()||"Failed to fetch registrations",success:!1}}const n=await i.json();return n.error?{registrations:[],error:n.error,success:!1}:{registrations:n.registrations||[],success:!0}}catch(zw){return{registrations:[],error:`Error fetching registrations: ${zw.message}`,success:!1}}}}function $h(e,t){return`hcs-10:op:${e}:${t}`}function Hh(e){var t,r;return z({memo:e.memoOverride??(t=e.ttl,r=e.accountId,`hcs-10:0:${t}:0:${r}`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function qh(e){return z({memo:e.memoOverride??`hcs-10:0:${e.ttl}:1`,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function jh(e){var t,r,i;return z({memo:e.memoOverride??(t=e.ttl,r=e.inboundTopicId,i=e.connectionId,`hcs-10:1:${t}:2:${r}:${i}`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Wh(e){var t,r;return z({memo:e.memoOverride??(t=e.ttl,(r=e.metadataTopicId)?`hcs-10:0:${t}:3:${r}`:`hcs-10:0:${t}:3`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Vh(e){const t={p:"hcs-10",op:"connection_request",operator_id:e.operatorId,m:e.memo};return _({topicId:e.inboundTopicId,message:JSON.stringify(t),transactionMemo:$h(3,1)})}function Gh(e){const t={p:"hcs-10",op:"connection_created",connection_topic_id:e.connectionTopicId,connected_account_id:e.connectedAccountId,operator_id:e.operatorId,connection_id:e.connectionId,m:e.memo};return _({topicId:e.inboundTopicId,message:JSON.stringify(t),transactionMemo:$h(4,1)})}function Jh(e){const t={p:"hcs-10",op:"connection_request",operator_id:e.operatorId,outbound_topic_id:e.outboundTopicId,connection_request_id:e.connectionRequestId,m:e.memo};return _({topicId:e.outboundTopicId,message:JSON.stringify(t),transactionMemo:$h(3,2)})}function Yh(e){const t={p:"hcs-10",op:"connection_created",connection_topic_id:e.connectionTopicId,outbound_topic_id:e.outboundTopicId,requestor_outbound_topic_id:e.requestorOutboundTopicId,confirmed_request_id:e.confirmedRequestId,connection_request_id:e.connectionRequestId,operator_id:e.operatorId,m:e.memo};return _({topicId:e.outboundTopicId,message:JSON.stringify(t),transactionMemo:$h(4,2)})}function Xh(e){const t={p:"hcs-10",op:"message",operator_id:e.operatorId,data:e.data,m:e.memo};return _({topicId:e.connectionTopicId,message:JSON.stringify(t),transactionMemo:$h(6,3)})}function Zh(e){const t={p:"hcs-10",op:"register",account_id:e.accountId,...e.inboundTopicId?{inbound_topic_id:e.inboundTopicId}:{},m:e.memo};return _({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:$h(0,0)})}function Qh(e){const t={p:"hcs-10",op:"delete",uid:e.uid,m:e.memo};return _({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:$h(1,0)})}function eg(e){const t={p:"hcs-10",op:"migrate",t_id:e.targetTopicId,m:e.memo};return _({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:$h(2,0)})}var tg=(e=>(e.INBOUND="inbound",e.OUTBOUND="outbound",e.CONNECTION="connection",e.REGISTRY="registry",e))(tg||{});class rg extends Kh{constructor(e){super(),this.network=e.network,this.logger=y.getInstance({level:e.logLevel||"info",module:"HCS10-BaseClient",prettyPrint:e.prettyPrint,silent:e.silent}),this.mirrorNode=new x(e.network,this.logger,e.mirrorNode),this.feeAmount=e.feeAmount||.001}configureMirrorNode(e){this.mirrorNode.configureMirrorNode(e),this.logger.info("Mirror node configuration updated")}extractTopicFromOperatorId(e){if(!e)return"";const t=e.split("@");return t.length>0?t[0]:""}extractAccountFromOperatorId(e){if(!e)return"";const t=e.split("@");return t.length>1?t[1]:""}async getMessageStream(e,t){try{const r=await this.mirrorNode.getTopicMessages(e,t),i=["message","close_connection","transaction"];return{messages:r.filter(e=>{if("hcs-10"!==e.p||!i.includes(e.op))return!1;if("message"===e.op||"close_connection"===e.op){if(!e.operator_id)return!1;if(!this.isValidOperatorId(e.operator_id))return!1;if("message"===e.op&&!e.data)return!1}if("transaction"===e.op){if(!e.operator_id||!e.schedule_id)return!1;if(!this.isValidOperatorId(e.operator_id))return!1}return!0})}}catch(r){return this.logger&&this.logger.error(`Error fetching messages: ${r.message}`),{messages:[]}}}async getPublicTopicInfo(e){try{return await this.mirrorNode.getTopicInfo(e)}catch(t){return this.logger.error(`Error getting public topic info for ${e}:`,t),null}}async canSubmitToTopic(e,t){try{const n=await this.mirrorNode.getTopicInfo(e);if(!n)return{canSubmit:!1,requiresFee:!1,reason:"Topic does not exist"};if(!n.submit_key?.key)return{canSubmit:!0,requiresFee:!1};try{const e=await this.mirrorNode.getPublicKey(t);if("ProtobufEncoded"===n.submit_key._type){const t=globalThis.Buffer.from(n.submit_key.key,"hex");if(await this.mirrorNode.checkKeyListAccess(t,e))return{canSubmit:!0,requiresFee:!1}}else{const t=r.PublicKey.fromString(n.submit_key.key);if(e.toString()===t.toString())return{canSubmit:!0,requiresFee:!1}}}catch(i){this.logger.error(`Key validation error: ${i instanceof Error?i.message:String(i)}`)}return n.fee_schedule_key?.key&&n.custom_fees?.fixed_fees?.length>0?{canSubmit:!0,requiresFee:!0,reason:"Requires fee payment via HIP-991"}:{canSubmit:!1,requiresFee:!1,reason:"User does not have submit permission for this topic"}}catch(i){const e=i instanceof Error?i.message:String(i);return this.logger.error(`Topic submission validation error: ${e}`),{canSubmit:!1,requiresFee:!1,reason:`Error: ${e}`}}}async getMessages(e,t){try{const r=await this.mirrorNode.getTopicMessages(e,t);return{messages:r.filter(e=>{if("hcs-10"!==e.p)return!1;if("message"===e.op){if(!e.data)return!1;if(e.operator_id&&!this.isValidOperatorId(e.operator_id))return!1}return!0})}}catch(r){return this.logger&&this.logger.error(`Error fetching messages: ${r.message}`),{messages:[]}}}async requestAccount(e){try{if(!e)throw new Error("Account ID is required");return await this.mirrorNode.requestAccount(e)}catch(zw){throw this.logger.error("Failed to fetch account",zw),zw}}async getAccountMemo(e){return await this.mirrorNode.getAccountMemo(e)}async retrieveProfile(e,t,r){const i=r?.maxRetries??0,n=r?.retryDelay??3e3;let o=0;for(;o<=i;){this.logger.debug(`Retrieving profile for account: ${e}${o>0?` (attempt ${o+1}/${i+1})`:""}`);const r=`${e}-${this.network}`;if(!t&&0===o){const t=ig.getInstance().get(r);if(t)return this.logger.debug(`Cache hit for profile: ${e}`),t}try{const t=new Lh({network:this.network,auth:{operatorId:"0.0.0"},logLevel:this.logger.getLevel()}),s=await t.fetchProfileByAccountId(e,this.network);if(!s?.success){if(o<i){this.logger.info(`Profile not found for account ${e}, retrying in ${n}ms... (${s?.error})`),o++,await new Promise(e=>setTimeout(e,n));continue}return this.logger.error(`Failed to retrieve profile for account ID: ${e}`,s?.error),{profile:null,success:!1,error:s?.error||`Failed to retrieve profile for account ID: ${e}`}}const a=s?.profile;let c=null;const l=s?.topicInfo?.inboundTopic||a?.inboundTopicId||"",u=s?.topicInfo?.outboundTopic||a?.outboundTopicId||"";l&&u&&(c={inboundTopic:l,outboundTopic:u,profileTopicId:s?.topicInfo?.profileTopicId||""});const d={profile:a,topicInfo:c,success:!0};return ig.getInstance().set(r,d),d}catch(zw){if(o<i){this.logger.info(`Error retrieving profile for account ${e}, retrying in ${n}ms... (${zw.message})`),o++,await new Promise(e=>setTimeout(e,n));continue}const r=`Failed to retrieve profile: ${zw.message}`;return this.logger.error(r),{profile:null,success:!1,error:r}}}return{profile:null,success:!1,error:"Unexpected error in profile retrieval"}}async retrieveOutboundConnectTopic(e){return await this.retrieveCommunicationTopics(e,!0)}async retrieveCommunicationTopics(e,t,r){try{const i=await this.retrieveProfile(e,t,r);if(!i?.success)throw new Error(i.error||"Failed to retrieve profile");const n=i.profile;if(!n)throw new Error(`Profile is null or undefined for account ${e}`);if(!n.inboundTopicId||!n.outboundTopicId)throw new Error("Invalid HCS-11 profile for HCS-10 agent: missing inboundTopicId or outboundTopicId");if(!i.topicInfo)throw new Error(`TopicInfo is missing in the profile for account ${e}`);return i.topicInfo}catch(zw){const t=zw,r=`Failed to retrieve topic info: ${t.message}`;throw this.logger.error(r),t}}async retrieveOutboundMessages(e,t){try{const r=await this.retrieveCommunicationTopics(e);if(!r)return this.logger.warn(`No outbound connect topic found for agentAccountId: ${e}`),[];return(await this.getMessages(r.outboundTopic,t)).messages.filter(e=>"hcs-10"===e.p&&("connection_request"===e.op||"connection_created"===e.op||"message"===e.op))}catch(zw){const t=`Failed to retrieve outbound messages: ${zw.message}`;return this.logger.error(t),[]}}async hasConnectionCreated(e,t){try{const r=await this.retrieveCommunicationTopics(e);return(await this.retrieveOutboundMessages(r.outboundTopic)).some(e=>"connection_created"===e.op&&e.connection_id===t)}catch(zw){const t=`Failed to check connection created: ${zw.message}`;return this.logger.error(t),!1}}async getMessageContent(e,t=!1){if(!e.match(/^hcs:\/\/(\d+)\/([0-9]+\.[0-9]+\.[0-9]+)$/))return e;try{const r=new Wp(this.logger.getLevel());if(!r.isValidHRL(e))return e;return(await r.resolveHRL(e,{network:this.network,returnRaw:t})).content}catch(zw){const t=`Error resolving HRL reference: ${zw.message}`;throw this.logger.error(t),new Error(t)}}async getMessageContentWithType(e,t=!1){if(!e.match(/^hcs:\/\/(\d+)\/([0-9]+\.[0-9]+\.[0-9]+)$/))return{content:e,contentType:"text/plain",isBinary:!1};try{const r=new Wp(this.logger.getLevel());return await r.getContentWithType(e,{network:this.network,returnRaw:t})}catch(zw){const t=`Error resolving HRL reference with type: ${zw.message}`;throw this.logger.error(t),new Error(t)}}async submitConnectionRequest(e,t){const r=this.getAccountAndSigner();if(!r?.accountId)throw new Error("Operator account ID is not set");const i=await this.getOperatorId(),n=r.accountId,o=await this.canSubmitToTopic(e,n);if(!o?.canSubmit)throw new Error(`Cannot submit to topic: ${o.reason}`);const s=await this.retrieveInboundAccountId(e);if(!s)throw new Error("Failed to retrieve topic info account ID");const a=o.requiresFee,c=Vh({inboundTopicId:e,operatorId:i,memo:t}),l=await this.submitPayload(c,void 0,void 0,a);this.logger.info(`Submitted connection request to topic ID: ${e}`);const u=await this.retrieveCommunicationTopics(n);if(!u)throw new Error("Failed to retrieve outbound topic");const d=l.topicSequenceNumber?.toNumber();if(!d)throw new Error("Failed to get response sequence number");const p=`${e}@${s}`,h=Jh({outboundTopicId:u.outboundTopic,operatorId:p,connectionRequestId:d,memo:t});return await this.submitPayload(h),l}async recordOutboundConnectionConfirmation({outboundTopicId:e,requestorOutboundTopicId:t,connectionRequestId:r,confirmedRequestId:i,connectionTopicId:n,operatorId:o,memo:s}){const a=Yh({outboundTopicId:e,requestorOutboundTopicId:t,connectionTopicId:n,confirmedRequestId:i,connectionRequestId:r,operatorId:o,memo:s});return await this.submitPayload(a)}async waitForConnectionConfirmation(e,t,r=60,i=2e3,n=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let o=0;o<r;o++){this.logger.info(`Attempt ${o+1}/${r} to find connection confirmation`);const s=(await this.mirrorNode.getTopicMessages(e,{order:"desc",limit:100})).filter(e=>"connection_created"===e.op);if(this.logger.info(`Found ${s.length} connection_created messages`),s.length>0)for(const e of s)if(Number(e.connection_id)===Number(t)){const r={connectionTopicId:e.connection_topic_id,sequence_number:Number(e.sequence_number),confirmedBy:e.operator_id,memo:e.m},i=this.extractAccountFromOperatorId(r.confirmedBy),o=this.getAccountAndSigner(),s=await this.retrieveCommunicationTopics(i),a=await this.retrieveCommunicationTopics(o.accountId);return this.logger.info("Connection confirmation found",r),n&&await this.recordOutboundConnectionConfirmation({requestorOutboundTopicId:s.outboundTopic,outboundTopicId:a.outboundTopic,connectionRequestId:t,confirmedRequestId:r.sequence_number,connectionTopicId:r.connectionTopicId,operatorId:r.confirmedBy,memo:r.memo||"Connection confirmed"}),r}o<r-1&&(this.logger.info(`No matching confirmation found, waiting ${i}ms before retrying...`),await new Promise(e=>setTimeout(e,i)))}throw new Error(`Connection confirmation not found after ${r} attempts for request ID ${t}`)}async getOperatorId(e){if(this.operatorId&&!e)return this.operatorId;const t=this.getAccountAndSigner();if(!t?.accountId)throw new Error("Operator ID not found");const r=await this.retrieveProfile(t.accountId);if(!r?.success)throw new Error("Failed to retrieve profile");if(!r?.topicInfo?.inboundTopic)throw new Error("Failed to retrieve inbound topic");const i=`${r.topicInfo?.inboundTopic}@${t.accountId}`;return this.operatorId=i,i}async retrieveInboundAccountId(e){const t=await this.mirrorNode.getTopicInfo(e);if(!t?.memo)throw new Error("Failed to retrieve topic info");const r=t.memo.toString().split(":"),i=r?.[4];if(!i)throw new Error("Failed to retrieve topic info account ID");return i}clearCache(){ig.getInstance().clear()}_generateHcs10Memo(e,t){const r=t.ttl??60;switch(e){case"inbound":if(!t.accountId)throw new Error("accountId is required for inbound memo");return`hcs-10:0:${r}:0:${t.accountId}`;case"outbound":return`hcs-10:0:${r}:1`;case"connection":if(!t.inboundTopicId||void 0===t.connectionId)throw new Error("inboundTopicId and connectionId are required for connection memo");return`hcs-10:1:${r}:2:${t.inboundTopicId}:${t.connectionId}`;default:throw new Error(`Invalid HCS-10 memo type: ${e}`)}}async getTopicMemoType(e){try{const t=await this.mirrorNode.getTopicInfo(e);if(!t?.memo)return this.logger.debug(`No memo found for topic ${e}`),null;const r=t.memo.toString();if(!r.startsWith("hcs-10:"))return this.logger.debug(`Topic ${e} is not an HCS-10 topic`),null;const i=r.split(":");if(i.length<4)return this.logger.warn(`Invalid HCS-10 memo format for topic ${e}: ${r}`),null;const n=i[3];switch(n){case"0":return"inbound";case"1":return"outbound";case"2":return"connection";case"3":return"registry";default:return this.logger.warn(`Unknown HCS-10 type enum: ${n} for topic ${e}`),null}}catch(t){return this.logger.error(`Error getting topic memo type for ${e}:`,t),null}}async checkRegistrationStatus(e,t,r){try{const i=await fetch(`${r}/api/request-confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Network":t},body:JSON.stringify({transaction_id:e})});if(!i.ok)throw new Error(`Failed to confirm registration: ${i.statusText}`);return await i.json()}catch(zw){const t=zw,r=`Error checking registration status: ${t.message}`;throw this.logger.error(r),t}}isValidOperatorId(e){if(!e)return!1;const t=e.split("@");if(2!==t.length)return!1;const r=t[0],i=t[1];if(!r)return!1;if(!i)return!1;const n=/^[0-9]+\.[0-9]+\.[0-9]+$/;return!!n.test(i)&&!!n.test(r)}async getTransactionRequests(e,t){this.logger.debug(`Retrieving transaction requests from topic ${e}`);const{messages:r}=await this.getMessageStream(e,{limit:t?.limit,sequenceNumber:t?.sequenceNumber,order:t?.order||"desc"}),i=r.filter(e=>"transaction"===e.op&&e.schedule_id).map(e=>({operator_id:e.operator_id||"",schedule_id:e.schedule_id||"",data:e.data||"",memo:e.m,sequence_number:Number(e.sequence_number)})).sort((e,t)=>e.sequence_number&&t.sequence_number?t.sequence_number-e.sequence_number:0);return t?.limit?i.slice(0,t.limit):i}getHcs10TransactionMemo(e){if("object"!=typeof e||!("op"in e))return null;const t=e;let r,i;switch(t.op){case"register":r="0",i="0";break;case"delete":r="1",i="0";break;case"migrate":r="2",i="0";break;case"connection_request":r="3",i=t.outbound_topic_id?"2":"1";break;case"connection_created":r="4",i=t.outbound_topic_id?"2":"1";break;case"connection_closed":r="5",i=t.outbound_topic_id?"2":"3";break;case"message":case"transaction":default:r="6",i="3";break;case"close_connection":r="5",i="3"}return`hcs-10:op:${r}:${i}`}}class ig{constructor(){this.CACHE_TTL=36e5,this.cache=new Map,this.cacheExpiry=new Map}static getInstance(){return ig.instance||(ig.instance=new ig),ig.instance}set(e,t){this.cache.set(e,t),this.cacheExpiry.set(e,Date.now()+this.CACHE_TTL)}get(e){const t=this.cacheExpiry.get(e);if(t&&t>Date.now())return this.cache.get(e);t&&(this.cache.delete(e),this.cacheExpiry.delete(e))}clear(){this.cache.clear(),this.cacheExpiry.clear()}}class ng extends Error{constructor(e,t){super(e),this.payloadSize=t,this.name="PayloadSizeError"}}class og extends Error{constructor(e){super(e),this.name="AccountCreationError"}}class sg extends Error{constructor(e){super(e),this.name="TopicCreationError"}}class ag extends Error{constructor(e){super(e),this.name="ConnectionConfirmationError"}}class cg{constructor(){this.config={},this.logger=y.getInstance({module:"AgentBuilder"})}setName(e){return this.config.name=e,this}setAlias(e){return this.config.alias=e,this}setBio(e){return this.config.bio=e,this}setDescription(e){return this.config.bio=e,this}setCapabilities(e){return this.config.capabilities=e,this}setAgentType(e){return this.config.metadata?this.config.metadata.type=e:this.config.metadata={type:e},this}setType(e){return this.config.metadata?this.config.metadata.type=e:this.config.metadata={type:e},this}setModel(e){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.model=e,this}setCreator(e){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.creator=e,this}addSocial(e,t){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.socials||(this.config.metadata.socials={}),this.config.metadata.socials[e]=t,this}addProperty(e,t){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.properties||(this.config.metadata.properties={}),this.config.metadata.properties[e]=t,this}setMetadata(e){return this.config.metadata=e,this}setProfilePicture(e,t){return this.config.pfpBuffer=e,this.config.pfpFileName=t,this}setExistingProfilePicture(e){return this.config.existingPfpTopicId=e,this}setNetwork(e){return this.config.network=e,this}setInboundTopicType(e){return this.config.inboundTopicType=e,this}setFeeConfig(e){return this.config.feeConfig=e,this}setConnectionFeeConfig(e){return this.config.connectionFeeConfig=e,this}setExistingAccount(e,t){return this.config.existingAccount={accountId:e,privateKey:t},this}setInboundTopicId(e){return this.config.inboundTopicId=e,this}setOutboundTopicId(e){return this.config.outboundTopicId=e,this}setBaseAccount(e){return this.baseAccount=e,this}build(){if(!this.config.name)throw new Error("Agent display name is required");if(this.config.bio||this.logger?.warn("Agent description is not set"),this.config.pfpBuffer||this.config.existingPfpTopicId||this.logger.warn("No profile picture provided or referenced."),!this.config.network)throw new Error("Network is required");if(this.config.inboundTopicType||(this.config.inboundTopicType=Th.PUBLIC),this.config.capabilities||(this.config.capabilities=[]),this.config.metadata?this.config.metadata.type||(this.config.metadata.type="manual"):this.config.metadata={type:"manual"},this.config.inboundTopicType===Th.FEE_BASED&&!this.config.feeConfig)throw new Error("Fee configuration is required for fee-based topics");const e=this.config;return this.baseAccount&&(e.baseAccount=this.baseAccount),e}}class lg{constructor(){this.config={version:"1.0",type:0},this.logger=y.getInstance({module:"PersonBuilder"})}setName(e){return this.config.display_name=e,this}setAlias(e){return this.config.alias=e,this}setBio(e){return this.config.bio=e,this}setDescription(e){return this.setBio(e)}addSocial(e,t){this.config.socials||(this.config.socials=[]);const r=this.config.socials.find(t=>t.platform===e);return r?r.handle=t:this.config.socials.push({platform:e,handle:t}),this}setProfileImage(e){return this.config.profileImage=e,this}setProfilePicture(e,t){return this.config.pfpBuffer=e,this.config.pfpFileName=t,this}setBaseAccount(e){return this.config.base_account=e,this}setExistingProfilePicture(e){return this.config.profileImage=`hcs://1/${e}`,this}addProperty(e,t){return this.config.properties||(this.config.properties={}),this.config.properties[e]=t,this}setInboundTopicId(e){return this.config.inboundTopicId=e,this}setOutboundTopicId(e){return this.config.outboundTopicId=e,this}getProfilePicture(){return{pfpBuffer:this.config.pfpBuffer,pfpFileName:this.config.pfpFileName}}build(){if(!this.config.display_name)throw new Error("Display name is required for the profile");return this.config.bio||this.logger.warn("No bio provided for person profile"),this.config.pfpBuffer||this.config.profileImage||this.logger.warn("No profile picture provided or referenced"),{version:this.config.version,type:0,display_name:this.config.display_name,alias:this.config.alias,bio:this.config.bio,socials:this.config.socials,profileImage:this.config.profileImage,base_account:this.config.base_account,properties:this.config.properties,inboundTopicId:this.config.inboundTopicId,outboundTopicId:this.config.outboundTopicId,pfpBuffer:this.config.pfpBuffer,pfpFileName:this.config.pfpFileName}}}class ug{constructor(){this.config={mcpServer:{}},this.socials=[],this.logger=y.getInstance({module:"MCPServerBuilder"})}setName(e){return this.config.name=e,this}setAlias(e){return this.config.alias=e,this}setBio(e){return this.config.bio=e,this}setDescription(e){return this.setBio(e)}setVersion(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.version=e,this}setConnectionInfo(e,t){this.config.mcpServer||(this.config.mcpServer={});const r={url:e,transport:t};return this.config.mcpServer.connectionInfo=r,this}setServerDescription(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.description=e,this}setServices(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.services=e,this}setHostRequirements(e){this.config.mcpServer||(this.config.mcpServer={});const t={minVersion:e};return this.config.mcpServer.host=t,this}setCapabilities(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.capabilities=e,this}addResource(e,t){this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.resources||(this.config.mcpServer.resources=[]);const r={name:e,description:t};return this.config.mcpServer.resources.push(r),this}setResources(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.resources=e,this}addTool(e,t){this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.tools||(this.config.mcpServer.tools=[]);const r={name:e,description:t};return this.config.mcpServer.tools.push(r),this}setTools(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.tools=e,this}setMaintainer(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.maintainer=e,this}setRepository(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.repository=e,this}setDocs(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.docs=e,this}setVerification(e){return this.config.mcpServer||(this.config.mcpServer={}),this.config.mcpServer.verification=e,this}addVerificationDNS(e,t){this.config.mcpServer||(this.config.mcpServer={});const r={type:Ih.DNS,value:e,dns_field:t};return this.config.mcpServer.verification=r,this}addVerificationSignature(e){this.config.mcpServer||(this.config.mcpServer={});const t={type:Ih.SIGNATURE,value:e};return this.config.mcpServer.verification=t,this}addVerificationChallenge(e){this.config.mcpServer||(this.config.mcpServer={});const t={type:Ih.CHALLENGE,value:"",challenge_path:e};return this.config.mcpServer.verification=t,this}addSocial(e,t){const r=this.socials.find(t=>t.platform===e);if(r)r.handle=t;else{const r={platform:e,handle:t};this.socials.push(r)}return this}setSocials(e){return this.socials=e,this}setProfilePicture(e,t){return this.config.pfpBuffer=e,this.config.pfpFileName=t,this}setExistingProfilePicture(e){return this.config.existingPfpTopicId=e,this}setNetworkType(e){return this.config.network=e,this}setExistingAccount(e,t){return this.config.existingAccount={accountId:e,privateKey:t},this}build(){if(!this.config.name)throw new Error("MCP server name is required");if(!this.config.network)throw new Error("Network type is required");if(!this.config.mcpServer)throw new Error("MCP server details are required");if(!this.config.mcpServer.version)throw new Error("MCP server version is required");if(!this.config.mcpServer.connectionInfo)throw new Error("MCP server connection info is required");if(!this.config.mcpServer.services||0===this.config.mcpServer.services.length)throw new Error("At least one MCP service type is required");if(!this.config.mcpServer.description)throw new Error("MCP server description is required");return this.config.bio||this.logger.warn("No bio provided for MCP server profile"),this.config.pfpBuffer||this.config.existingPfpTopicId||this.logger.warn("No profile picture provided or referenced"),this.socials.length>0?{...this.config,socials:this.socials}:this.config}}class dg{constructor(){this.config={version:"1.0",type:3},this.logger=y.getInstance({module:"FloraBuilder"})}setDisplayName(e){return this.config.display_name=e,this}setBio(e){return this.config.bio=e,this}setMembers(e){return this.config.members=e,this}setThreshold(e){return this.config.threshold=e,this}setTopics(e){return this.config.topics=e,this.config.inboundTopicId=e.communication,this.config.outboundTopicId=e.transaction,this}setPolicies(e){return this.config.policies=e,this}setMetadata(e){return this.config.metadata=e,this}addMetadata(e,t){return this.config.metadata||(this.config.metadata={}),this.config.metadata[e]=t,this}build(){if(!this.config.display_name)throw new Error("Flora display name is required");if(!this.config.members||0===this.config.members.length)throw new Error("Flora must have at least one member");if(!this.config.threshold||this.config.threshold<1)throw new Error("Flora threshold must be at least 1");if(this.config.threshold>this.config.members.length)throw new Error("Flora threshold cannot exceed number of members");if(!this.config.topics)throw new Error("Flora topics are required");if(!this.config.inboundTopicId||!this.config.outboundTopicId)throw new Error("Flora inbound and outbound topic IDs are required");return this.config}}const pg=Object.freeze(Object.defineProperty({__proto__:null,AIAgentCapability:bh,AIAgentDetailsSchema:Ah,AIAgentProfileSchema:Dh,AIAgentType:fh,AgentBuilder:cg,BaseProfileSchema:Ph,EndpointType:yh,FloraBuilder:dg,HCS11Client:Lh,HCS11ProfileSchema:Uh,InboundTopicType:Th,MCPServerBuilder:ug,MCPServerCapability:wh,MCPServerConnectionInfoSchema:Ch,MCPServerDetailsSchema:_h,MCPServerHostSchema:xh,MCPServerProfileSchema:Fh,MCPServerResourceSchema:Nh,MCPServerToolSchema:zh,MCPServerVerificationSchema:Rh,PersonBuilder:lg,PersonalProfileSchema:Oh,ProfileType:mh,SUPPORTED_SOCIAL_PLATFORMS:Sh,SocialLinkSchema:Eh,VerificationType:Ih,capabilityNameToCapabilityMap:kh,mcpServiceNameToCapabilityMap:vh},Symbol.toStringTag,{value:"Module"}));class hg{constructor(e){this.connections=new Map,this.pendingRequests=new Map,this.profileCache=new Map,this.filterPendingAccountIds=new Set;const t={module:"ConnectionsManager",level:e?.logLevel||"info",prettyPrint:!0,silent:e?.silent};if(this.logger=y.getInstance(t),e?.filterPendingAccountIds&&(this.filterPendingAccountIds=new Set(e.filterPendingAccountIds)),!e.baseClient)throw new Error("ConnectionsManager requires a baseClient to operate");this.baseClient=e.baseClient}async fetchConnectionData(e){try{const t=await this.baseClient.retrieveCommunicationTopics(e),r=e=>Boolean(e)&&!e.includes(":");if(!r(t?.inboundTopic)||!r(t?.outboundTopic))return this.logger.warn("Invalid topic IDs detected in retrieved communication topics"),this.getAllConnections();const[i,n]=await Promise.all([this.baseClient.getMessages(t?.outboundTopic),this.baseClient.getMessages(t?.inboundTopic)]);this.processOutboundMessages(i.messages||[],e),this.processInboundMessages(n.messages||[]);const o=Array.from(this.connections.values()).filter(e=>"pending"===e.status||e.isPending).length;return this.logger.debug(`Processed ${i.messages?.length||0} outbound and ${n.messages?.length||0} inbound messages. Found ${o} pending connections.`),await this.checkTargetInboundTopicsForConfirmations(),await this.checkOutboundRequestsForConfirmations(),await this.fetchProfilesForConnections(),await this.fetchConnectionActivity(),this.getAllConnections()}catch(t){return this.logger.error("Error fetching connection data:",t),this.getAllConnections()}}async checkTargetInboundTopicsForConfirmations(){const e=Array.from(this.connections.values()).filter(e=>(e.isPending||"pending"===e.status)&&e.targetInboundTopicId);if(0===e.length)return;const t=new Map;e.forEach(e=>{if(e.targetInboundTopicId){const r=t.get(e.targetInboundTopicId)||[];r.push(e),t.set(e.targetInboundTopicId,r)}});for(const[i,n]of t.entries())for(let e=1;e<=2;e++)try{const t=(await this.baseClient.getMessages(i)).messages||[];let r=!1;for(const e of n){const i=e.connectionRequestId;if(!i)continue;const n=t.find(t=>{if("connection_created"!==t.op||!t.connection_topic_id)return!1;if(t.connection_id!==i)return!1;if(e.uniqueRequestKey){const r=e.uniqueRequestKey.split(":");if(r.length>1){const i=r[1];if(t.operator_id&&t.operator_id===i)return!0;if(t.connected_account_id===e.targetAccountId)return!0}}return!0});if(n?.connection_topic_id){r=!0;const t=n.connection_topic_id;let o=e.uniqueRequestKey;const s={connectionTopicId:t,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName,targetInboundTopicId:e.targetInboundTopicId,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(n.created||e.created),profileInfo:e.profileInfo,connectionRequestId:i,uniqueRequestKey:e.uniqueRequestKey,originTopicId:e.originTopicId,processed:e.processed,memo:e.memo};this.connections.set(t,s),o&&this.connections.delete(o),this.logger.debug(`Confirmed connection in target inbound topic: ${t}`)}}if(r||2===e)break;await new Promise(e=>setTimeout(e,500))}catch(r){if(this.logger.debug(`Error fetching target inbound topic ${i}:`,r),2===e)break;await new Promise(e=>setTimeout(e,500))}}async checkOutboundRequestsForConfirmations(){const e=Array.from(this.connections.values());this.logger.info(`Total connections in map: ${e.length}`);const t=e.filter(e=>"pending"===e.status);this.logger.info(`Connections with status='pending': ${t.length}`);const r=e.filter(e=>"pending"===e.status);if(Boolean(r?.length))for(const n of r){if(this.logger.debug(`Processing pending connection: ${n.connectionTopicId}`),!n.targetAccountId){this.logger.debug(`Skipping connection ${n.connectionTopicId} - no targetAccountId`);continue}let e=n.targetInboundTopicId;if(!e)try{const t=await this.baseClient.retrieveProfile(n.targetAccountId);if(!t?.profile?.inboundTopicId){this.logger.debug(`Couldn't get inbound topic ID for account ${n.targetAccountId}`);continue}e=t.profile.inboundTopicId,this.connections.set(n.connectionTopicId,{...n,targetInboundTopicId:e}),this.logger.debug(`Updated connection ${n.connectionTopicId} with inbound topic ID: ${e}`)}catch(i){this.logger.debug(`Error fetching profile for ${n.targetAccountId}: ${i}`);continue}if(!e||e.includes(":")){this.logger.debug(`Skipping invalid inbound topic format: ${e}`);continue}const t=n.connectionRequestId||n.inboundRequestId;if(t)try{this.logger.debug(`Checking for confirmations on topic ${e} for request ID ${t}`);const r=await this.baseClient.getMessages(e),i=(r.messages||[]).find(e=>"connection_created"===e.op&&e.connection_id===t&&e.connection_topic_id);if(i?.connection_topic_id){const e=i.connection_topic_id;this.logger.info(`Found confirmation for request #${t} to ${n.targetAccountId} on their inbound topic`);const r={connectionTopicId:e,targetAccountId:n.targetAccountId,targetAgentName:n.targetAgentName,targetInboundTopicId:n.targetInboundTopicId,targetOutboundTopicId:n.targetOutboundTopicId,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(i.created||n.created),lastActivity:new Date(i.created||n.created),profileInfo:n.profileInfo,connectionRequestId:n.connectionRequestId,confirmedRequestId:n.confirmedRequestId,requesterOutboundTopicId:n.requesterOutboundTopicId,inboundRequestId:n.inboundRequestId,closedReason:n.closedReason,closeMethod:n.closeMethod,uniqueRequestKey:n.uniqueRequestKey,originTopicId:n.originTopicId,processed:n.processed,memo:n.memo};this.connections.set(e,r),n.connectionTopicId&&this.connections.delete(n.connectionTopicId)}else this.logger.debug(`No confirmation found for request ID ${t} on topic ${e}`)}catch(i){this.logger.warn(`Error checking for confirmations on target inbound topic for ${n.targetAccountId}: ${i}`)}else this.logger.debug(`Skipping connection ${n.connectionTopicId} - no request ID`)}else this.logger.info("No pending connections found")}async fetchProfilesForConnections(){const e=new Set;for(const r of this.connections.values())r.targetAccountId&&!this.profileCache.has(r.targetAccountId)&&e.add(r.targetAccountId);const t=Array.from(e).map(async e=>{try{const t=await this.baseClient.retrieveProfile(e);t.success&&t.profile&&(this.addProfileInfo(e,t.profile),this.updatePendingConnectionsWithProfileInfo(e,t.profile))}catch(t){this.logger.debug(`Failed to fetch profile for ${e}:`,t)}});await Promise.allSettled(t)}updatePendingConnectionsWithProfileInfo(e,t){const r=Array.from(this.connections.values()).filter(t=>t.targetAccountId===e&&(t.isPending||t.needsConfirmation)&&!t.targetInboundTopicId);if(r.length>0&&t.inboundTopicId)for(const i of r){const e={...i,targetInboundTopicId:t.inboundTopicId};this.connections.set(i.connectionTopicId,e)}}async fetchConnectionActivity(){const e=this.getActiveConnections().filter(e=>{const t=e.connectionTopicId;return!(!t||t.includes(":")||!t.match(/^0\.0\.\d+$/))||(this.logger.debug(`Skipping activity fetch for invalid topic ID format: ${t}`),!1)}).map(async e=>{try{const t=e.connectionTopicId,r=await this.baseClient.getMessages(t);r?.messages?.length>0&&this.processConnectionMessages(t,r.messages)}catch(t){this.logger.debug(`Failed to fetch activity for ${e.connectionTopicId}:`,t)}});await Promise.allSettled(e)}shouldFilterAccount(e){return!!this.filterPendingAccountIds.has(e)&&!this.hasEstablishedConnectionWithAccount(e)}processOutboundMessages(e,t){if(!Boolean(e?.length))return Array.from(this.connections.values());const r=e.filter(e=>"connection_request"===e.op&&e.connection_request_id);for(const o of r){const e=o.connection_request_id,r=o.operator_id||"",i=this.baseClient.extractAccountFromOperatorId(r),n=this.baseClient.extractTopicFromOperatorId(r);if(this.shouldFilterAccount(i)){this.logger.debug(`Filtering out outbound request to account: ${i}`);continue}const s=Array.from(this.connections.values()).some(t=>t.connectionRequestId===e&&!t.isPending&&t.targetAccountId===i),a=`req-${e}:${r}`;if(!s&&!this.pendingRequests.has(a)){const s={id:e,requesterId:t,requesterTopicId:o.outbound_topic_id||"",targetAccountId:i,targetTopicId:n,operatorId:r,sequenceNumber:o.sequence_number,created:o.created||new Date,memo:o.m,status:"pending"};if(this.pendingRequests.set(a,s),!this.connections.has(a)){const t={connectionTopicId:a,targetAccountId:i,targetInboundTopicId:n,status:"pending",isPending:!0,needsConfirmation:!1,created:o.created||new Date,connectionRequestId:e,uniqueRequestKey:a,originTopicId:o.outbound_topic_id||"",processed:!1,memo:o.m};this.connections.set(a,t)}}}const i=e.filter(e=>"connection_created"===e.op&&e.connection_topic_id&&e.connection_request_id);for(const o of i){const e=o.connection_request_id,t=o.connection_topic_id,r=this.baseClient.extractAccountFromOperatorId(o.operator_id||"");if(this.shouldFilterAccount(r)){this.logger.debug(`Filtering out outbound confirmation to account: ${r}`);continue}const i=`req-${e}:${o.operator_id}`,n=this.pendingRequests.get(i);if(n&&(n.status="confirmed"),this.connections.has(i)&&this.connections.delete(i),this.connections.has(t)){const r=this.connections.get(t);this.connections.set(t,{...r,status:"established",isPending:!1,needsConfirmation:!1,connectionRequestId:e,confirmedRequestId:o.confirmed_request_id,requesterOutboundTopicId:o.outbound_topic_id,uniqueRequestKey:i,originTopicId:o.outbound_topic_id||"",processed:!1,memo:o.m})}else this.connections.set(t,{connectionTopicId:t,targetAccountId:r,status:"established",isPending:!1,needsConfirmation:!1,created:o.created||new Date,connectionRequestId:e,confirmedRequestId:o.confirmed_request_id,requesterOutboundTopicId:o.outbound_topic_id,uniqueRequestKey:i,originTopicId:o.outbound_topic_id||"",processed:!1,memo:o.m})}const n=e.filter(e=>"connection_closed"===e.op||"close_connection"===e.op&&e.connection_topic_id);for(const o of n){const e=o.connection_topic_id;if(this.connections.has(e)){const t=this.connections.get(e);if(this.shouldFilterAccount(t.targetAccountId)&&"established"!==t.status)continue;const r=o.connection_request_id&&o.operator_id?`req-${o.connection_request_id}:${o.operator_id}`:void 0;this.connections.set(e,{...t,status:"closed",isPending:!1,needsConfirmation:!1,lastActivity:o.created||new Date,closedReason:o.reason,closeMethod:o.close_method,uniqueRequestKey:r,originTopicId:t.originTopicId,processed:!1,memo:o.m})}}return Array.from(this.connections.values()).filter(e=>"established"===e.status||"closed"===e.status||!this.filterPendingAccountIds.has(e.targetAccountId))}processInboundMessages(e){if(!Boolean(e?.length))return Array.from(this.connections.values());const t=e.filter(e=>"connection_request"===e.op&&e.sequence_number),r=e.filter(e=>"connection_created"===e.op&&e.connection_topic_id&&e.connection_id);for(const i of t){const e=i.sequence_number,t=i.operator_id||"",n=this.baseClient.extractAccountFromOperatorId(t),o=this.baseClient.extractTopicFromOperatorId(t);if(this.shouldFilterAccount(n)){this.logger.debug(`Filtering out request from account: ${n}`);continue}const s=`inb-${e}:${t}`;r.some(t=>t.connection_id===e)?this.logger.debug(`Skipping request from ${n} as it has already been confirmed`):this.connections.has(s)||this.connections.set(s,{connectionTopicId:s,targetAccountId:n,targetInboundTopicId:o,status:"needs_confirmation",isPending:!1,needsConfirmation:!0,created:i.created||new Date,inboundRequestId:e,uniqueRequestKey:s,originTopicId:o,processed:!1,memo:i.m})}for(const i of r){const e=i.connection_id,t=i.connection_topic_id,r=i.connected_account_id||"",n=i.operator_id||"";if(this.shouldFilterAccount(r)){this.logger.debug(`Filtering out confirmation for account: ${r}`);continue}const o=`inb-${e}:${n}`;if(this.connections.has(o)&&this.connections.delete(o),this.connections.has(t)){const r=this.connections.get(t);this.connections.set(t,{...r,status:"established",isPending:!1,needsConfirmation:!1,inboundRequestId:e,uniqueRequestKey:o,originTopicId:i.connection_topic_id,processed:!1,memo:i.m})}else this.connections.set(t,{connectionTopicId:t,targetAccountId:r,status:"established",isPending:!1,needsConfirmation:!1,created:i.created||new Date,inboundRequestId:e,uniqueRequestKey:o,originTopicId:i.connection_topic_id,processed:!1,memo:i.m})}return Array.from(this.connections.values()).filter(e=>"established"===e.status||"closed"===e.status||!this.filterPendingAccountIds.has(e.targetAccountId))}processConnectionMessages(e,t){if(!t||0===t.length||!this.connections.has(e))return this.connections.get(e);const r=t.filter(e=>e.created).sort((e,t)=>{const r=e.created?new Date(e.created).getTime():0;return(t.created?new Date(t.created).getTime():0)-r})[0];if(r?.created){const t=this.connections.get(e);this.connections.set(e,{...t,lastActivity:r.created})}const i=t.find(e=>"close_connection"===e.op);if(i){const t=this.connections.get(e);this.connections.set(e,{...t,status:"closed",lastActivity:i.created||new Date,closedReason:i.reason,closeMethod:"explicit"})}return this.connections.get(e)}addProfileInfo(e,t){this.profileCache.set(e,t);const r=Array.from(this.connections.values()).filter(t=>t.targetAccountId===e);for(const i of r)this.connections.set(i.connectionTopicId,{...i,profileInfo:t,targetAgentName:t.display_name,targetInboundTopicId:t.inboundTopicId,targetOutboundTopicId:t.outboundTopicId})}getAllConnections(){return Array.from(this.connections.values()).filter(e=>"established"===e.status||"closed"===e.status||!this.filterPendingAccountIds.has(e.targetAccountId))}getPendingRequests(){return Array.from(this.connections.values()).filter(e=>e.isPending&&!this.filterPendingAccountIds.has(e.targetAccountId))}hasEstablishedConnectionWithAccount(e){return Array.from(this.connections.values()).some(t=>t.targetAccountId===e&&"established"===t.status)}getActiveConnections(){return Array.from(this.connections.values()).filter(e=>"established"===e.status)}getConnectionsNeedingConfirmation(){return Array.from(this.connections.values()).filter(e=>e.needsConfirmation&&!this.filterPendingAccountIds.has(e.targetAccountId))}getConnectionByTopicId(e){return this.connections.get(e)}getConnectionByAccountId(e){return Array.from(this.connections.values()).find(t=>t.targetAccountId===e&&"established"===t.status)}getConnectionsByAccountId(e){return Array.from(this.connections.values()).filter(t=>t.targetAccountId===e)}updateOrAddConnection(e){this.connections.set(e.connectionTopicId,e)}clearAll(){this.connections.clear(),this.pendingRequests.clear()}isConnectionRequestProcessed(e,t){for(const r of this.connections.values()){if(r.originTopicId===e&&r.inboundRequestId===t&&r.processed)return!0;if(r.originTopicId===e&&r.connectionRequestId===t&&r.processed)return!0}return!1}markConnectionRequestProcessed(e,t){let r=!1;for(const[i,n]of this.connections.entries())n.originTopicId===e&&n.inboundRequestId===t&&(this.connections.set(i,{...n,processed:!0}),r=!0,this.logger.debug(`Marked inbound connection request #${t} on topic ${e} as processed`)),n.originTopicId===e&&n.connectionRequestId===t&&(this.connections.set(i,{...n,processed:!0}),r=!0,this.logger.debug(`Marked outbound connection request #${t} on topic ${e} as processed`));return r}async getPendingTransactions(e,t){try{const i=await this.baseClient.getTransactionRequests(e,t?{...t}:void 0),n=[];for(const e of i)try{const t=await this.baseClient.mirrorNode.getScheduledTransactionStatus(e.schedule_id);t.executed||t.deleted||n.push(e)}catch(r){this.logger.error(`Error checking transaction status: ${r}`),n.push(e)}return n}catch(r){return this.logger.error(`Error getting pending transactions: ${r}`),[]}}getScheduledTransactionStatus(e){return this.baseClient.mirrorNode.getScheduledTransactionStatus(e)}async getLastOperatorActivity(e,t){try{const r=(await this.baseClient.getMessageStream(e)).messages.filter(e=>e.operator_id&&e.operator_id.includes(t)&&e.created);if(0===r.length)return;return r.sort((e,t)=>t.created.getTime()-e.created.getTime()),r[0].created}catch(r){return void this.logger.error(`Error getting last operator activity: ${r}`)}}}class gg extends rg{constructor(e){super({network:e.network,logLevel:e.logLevel,prettyPrint:e.prettyPrint,feeAmount:e.feeAmount,mirrorNode:e.mirrorNode,silent:e.silent,keyType:e.keyType}),this.logger=y.getInstance({level:e.logLevel||"info",module:"HCS-SDK",silent:e.silent}),this.operatorAccountId=e.operatorId,this.operatorCtx=B({network:this.network,operatorId:this.operatorAccountId,operatorKey:e.operatorPrivateKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:e.client??("mainnet"===e.network?r.Client.forMainnet():r.Client.forTestnet())}),this.client=this.operatorCtx.client,this.network=e.network,this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl||"https://moonscape.tech",this.hcs11Client=new Lh({network:e.network,auth:{operatorId:e.operatorId,privateKey:this.operatorCtx.operatorKey.toString()},logLevel:e.logLevel,silent:e.silent,keyType:e.keyType,client:this.client})}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}getClient(){return this.client}async createAccount(e=50){await this.ensureInitialized(),this.logger.info(`Creating new account with ${e} HBAR initial balance`);const t=r.PrivateKey.generateED25519(),i=(new r.AccountCreateTransaction).setKeyWithoutAlias(t.publicKey).setInitialBalance(new r.Hbar(e)),n=await i.execute(this.client),o=(await n.getReceipt(this.client)).accountId;if(!o)throw this.logger.error("Account creation failed: accountId is null"),new og("Failed to create account: accountId is null");return this.logger.info(`Account created successfully: ${o.toString()}`),{accountId:o.toString(),privateKey:t.toString()}}async createInboundTopic(e,t,r=60,i){let n,o;switch(await this.ensureInitialized(),this._generateHcs10Memo(tg.INBOUND,{accountId:e,ttl:r}),t){case Th.PUBLIC:n=!1;break;case Th.CONTROLLED:n=!0;break;case Th.FEE_BASED:if(n=!1,!i)throw new Error("Fee configuration builder is required for fee-based topics");i.customFees.forEach(t=>{t.feeCollectorAccountId||(t.feeCollectorAccountId=e)}),o=i.build(),o.customFees=o.customFees.map(t=>({...t,feeCollectorAccountId:t.feeCollectorAccountId||e}));break;default:throw new Error(`Unsupported inbound topic type: ${t}`)}const s=this.client.operatorPublicKey||this.operatorCtx.operatorKey.publicKey,a=Hh({accountId:e,ttl:r,adminKey:!0,submitKey:n,operatorPublicKey:s});this.logger.info("Creating inbound topic");const{topicId:c}=await this.executeTopicCreateTransaction({transaction:a,feeConfig:o});return c}async createConnectionTopic(e){await this.ensureInitialized();const t=jh({ttl:e.ttl??60,inboundTopicId:e.inboundTopicId,connectionId:e.connectionId,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:this.client.operatorPublicKey||this.operatorCtx.operatorKey.publicKey}),r=e.feeConfigBuilder?.build(),{topicId:i}=await this.executeTopicCreateTransaction({transaction:t,feeConfig:r});return i}async createAgent(e,t=60,r,i){await this.ensureInitialized();const n=e.build(),o=this.client.operatorAccountId?.toString();if(!o)throw new Error("Failed to retrieve operator account ID");const s=await this._createEntityTopics(t,{outboundTopicId:r?.outboundTopicId||"",inboundTopicId:r?.inboundTopicId||"",pfpTopicId:r?.pfpTopicId||n.existingPfpTopicId||"",profileTopicId:r?.profileTopicId||""},o,n.inboundTopicType,n.feeConfig,n.pfpBuffer,n.pfpFileName,i);if(s.profileTopicId)this.logger.info(`Using existing profile topic ID: ${s.profileTopicId}`);else{i&&i({stage:"preparing",message:"Creating agent profile",progressPercent:60,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,state:{currentStage:"profile",completedPercentage:60}}});const e=await this.storeHCS11Profile(n.name,n.bio,s.inboundTopicId,s.outboundTopicId,n.capabilities,n.metadata,n.pfpBuffer&&n.pfpBuffer.length>0&&!s.pfpTopicId?n.pfpBuffer:void 0,n.pfpFileName,s.pfpTopicId);s.profileTopicId=e.profileTopicId,this.logger.info(`Profile stored with topic ID: ${s.profileTopicId}`),i&&i({stage:"preparing",message:"Agent profile created",progressPercent:70,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,state:{currentStage:"profile",completedPercentage:70}}})}return s}async create(e,t){const r=t?.progressCallback,i=new ts({module:"ProfileCreate",logger:this.logger,callback:r?e=>r({stage:e.stage,message:e.message,progressPercent:e.progressPercent,details:e.details}):void 0});try{const r=e instanceof cg;let n;if(n=t?.existingState?t.existingState:{currentStage:"init",completedPercentage:0,createdResources:[]},r){this.logger.info("Creating Agent Profile and HCS-10 Topics");const t=e.build();n.agentMetadata=t.metadata}else this.logger.info("Creating Person HCS-11 Profile");i.preparing(`Starting ${r?"agent":"person"} resource creation`,0,{state:n});const o=this.client.operatorAccountId?.toString();if(!o)throw new Error("Failed to retrieve operator account ID");const{inboundTopicId:s,outboundTopicId:a,state:c}=await this.createCommunicationTopics(o,t,i);let l,u,d;if(n=c,e.setInboundTopicId(s),e.setOutboundTopicId(a),r){const t=e.build();l=t.existingPfpTopicId||n.pfpTopicId,u=t.pfpBuffer,d=t.pfpFileName||"pfp.png"}else{const t=e.build();l=n.pfpTopicId,u=t.pfpBuffer,d=t.pfpFileName}!l&&u&&d?l=await this.handleProfilePictureCreation(u,d,n,i):l&&(i.preparing(`Using existing profile picture: ${l}`,50,{state:n}),n.pfpTopicId=l),await this.createAndInscribeProfile(r,e,l,n,s,a,t,i),n.currentStage="complete",n.completedPercentage=100,i.completed((r?"Agent":"Person")+" profile created successfully",{profileTopicId:n.profileTopicId,inboundTopicId:s,outboundTopicId:a,pfpTopicId:l,state:n});let p="";n.outboundTopicId&&(p=n.outboundTopicId);let h="";n.inboundTopicId&&(h=n.inboundTopicId);let g="";n.pfpTopicId&&(g=n.pfpTopicId);let m="";return n.profileTopicId&&(m=n.profileTopicId),{outboundTopicId:p,inboundTopicId:h,pfpTopicId:g,profileTopicId:m,success:!0,state:n}}catch(n){return i.failed("Error during profile creation",{error:n.message}),{outboundTopicId:"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:n.message,state:{currentStage:"init",completedPercentage:0,error:n.message}}}}async inscribePfp(e,t){try{this.logger.info("Inscribing profile picture using HCS-11 client");const r=await this.hcs11Client.inscribeImage(e,t);if(!r.success)throw this.logger.error(`Failed to inscribe profile picture: ${r.error}`),new Error(r?.error||"Failed to inscribe profile picture");return this.logger.info(`Successfully inscribed profile picture with topic ID: ${r.imageTopicId}`),{pfpTopicId:r.imageTopicId,transactionId:r.transactionId,success:!0}}catch(zw){const t=zw,r=`Error inscribing profile picture: ${t.message}`;return this.logger.error(r),{pfpTopicId:"",transactionId:"",success:!1,error:t.message}}}async storeHCS11Profile(e,t,r,i,n=[],o,s,a,c){try{let l=c||"";if(!l&&s&&a){this.logger.info("Inscribing profile picture for HCS-11 profile");const e=await this.inscribePfp(s,a);e.success?l=e.pfpTopicId:this.logger.warn(`Failed to inscribe profile picture: ${e.error}, proceeding without pfp`)}else c&&(this.logger.info(`Using existing profile picture with topic ID: ${c} for HCS-11 profile`),l=c);const u=this.hcs11Client.getAgentTypeFromMetadata({type:o.type||"autonomous"}),d=o.socials?Object.entries(o.socials).filter(([e,t])=>t).map(([e,t])=>({platform:e,handle:t})):void 0,p=this.hcs11Client.createAIAgentProfile(e,u,n,o.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:l?`hcs://1/${l}`:void 0,socials:d,properties:o.properties,inboundTopicId:r,outboundTopicId:i,creator:o.creator}),h=await this.hcs11Client.createAndInscribeProfile(p,!0);if(!h.success)throw this.logger.error(`Failed to inscribe profile: ${h.error}`),new Error(h.error||"Failed to inscribe profile");return this.logger.info(`Profile inscribed with topic ID: ${h.profileTopicId}, transaction ID: ${h.transactionId}`),{profileTopicId:h.profileTopicId,pfpTopicId:l,transactionId:h.transactionId,success:!0}}catch(zw){const t=zw,r=`Error storing HCS-11 profile: ${t.message}`;return this.logger.error(r),{profileTopicId:"",pfpTopicId:"",transactionId:"",success:!1,error:t.message}}}async setupFees(e,t,i=[]){let n=e;if(!this.client.operatorPublicKey)return n;if(!t.customFees||0===t.customFees.length)return this.logger.warn("No custom fees provided in fee config for setupFees"),n;t.customFees.length>10&&(this.logger.warn("More than 10 custom fees provided, only the first 10 will be used"),t.customFees=t.customFees.slice(0,10));const o=t.customFees.map(e=>{if(!e.feeCollectorAccountId)return this.logger.error("Internal Error: Fee collector ID missing in setupFees"),null;if("FIXED_FEE"===e.type){const t=(new r.CustomFixedFee).setAmount(Number(e.feeAmount.amount)).setFeeCollectorAccountId(r.AccountId.fromString(e.feeCollectorAccountId));return e.feeTokenId&&t.setDenominatingTokenId(r.TokenId.fromString(e.feeTokenId)),t}return null}).filter(Boolean);if(0===o.length)return this.logger.warn("No valid custom fees to apply in setupFees"),n;const s=[...t.exemptAccounts||[],...i];return s.length>0&&(n=await this.setupExemptKeys(e,s)),n.setFeeScheduleKey(this.client.operatorPublicKey).setCustomFees(o)}async setupExemptKeys(e,t){let r=e;const i=Array.from(new Set(t)).filter(e=>e!==this.client.operatorAccountId?.toString());let n=[];if(i.length>0)try{n=await cc(i,this.network,this.logger)}catch(zw){const t=`Error getting exempt keys: ${zw.message}, continuing without exempt keys`;this.logger.warn(t)}return n.length>0&&(r=r.setFeeExemptKeys(n)),r}async handleConnectionRequest(e,t,i,n,o=60){this.logger.info(`Handling connection request ${i} from ${t}`);const s=this.getClient().operatorAccountId?.toString();if(!s)throw new Error("Failed to retrieve operator account ID");let a=await this.mirrorNode.getPublicKey(t);const c=await this.mirrorNode.getPublicKey(s);if(!c)throw new Error("Failed to retrieve public key");const l=new r.KeyList([c,a],1);let u;try{const t=jh({ttl:o,inboundTopicId:e,connectionId:i,adminKey:l,submitKey:l});if(n){const e=n.build(),r={...e,exemptAccounts:[...e.exemptAccounts||[]]},{topicId:i}=await this.executeTopicCreateTransaction({transaction:t,feeConfig:r});u=i}else{const{topicId:e}=await this.executeTopicCreateTransaction({transaction:t});u=e}this.logger.info(`Created new connection topic ID: ${u}`)}catch(f){const e=`Failed to create connection topic: ${f}`;throw this.logger.error(e),new sg(e)}const d=`${e}@${s}`,p=await this.confirmConnection(e,u,t,i,"Connection accepted. Looking forward to collaborating!"),h=await this.retrieveCommunicationTopics(s),g=await this.retrieveCommunicationTopics(t),m=`${g.inboundTopic}@${t}`;return await this.recordOutboundConnectionConfirmation({outboundTopicId:h.outboundTopic,requestorOutboundTopicId:g.outboundTopic,connectionRequestId:i,confirmedRequestId:p,connectionTopicId:u,operatorId:m,memo:`Connection established with ${t}`}),{connectionTopicId:u,confirmedConnectionSequenceNumber:p,operatorId:d}}async confirmConnection(e,t,r,i,n,o){const s=await this.getOperatorId();this.logger.info(`Confirming connection with ID ${i}`);const a=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),c=Gh({inboundTopicId:e,connectionTopicId:t,connectedAccountId:r,operatorId:s,connectionId:i,memo:n}),l=await this.submitPayload(c,void 0,o,a.requiresFee),u=l.topicSequenceNumber?.toNumber();if(!u)throw new ag("Failed to confirm connection: sequence number is null");return u}async sendMessage(e,t,r,i,n){const o=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),s=await this.getOperatorId(),a={p:"hcs-10",op:"message",operator_id:s,data:t,m:r},c=JSON.stringify(a);if(globalThis.Buffer.from(c).length>1e3){this.logger.info("Message payload exceeds 1000 bytes, storing via inscription");try{const e=globalThis.Buffer.from(t),r=`message-${Date.now()}.json`,i=await this.inscribeFile(e,r,{progressCallback:n?.progressCallback,waitMaxAttempts:n?.waitMaxAttempts,waitIntervalMs:n?.waitIntervalMs});if(!Ha(i))throw new Error("Failed to inscribe large message content");a.data=`hcs://1/${Ha(i)}`,this.logger.info(`Large message inscribed with topic ID: ${Ha(i)}`)}catch(u){const e=`Error inscribing large message: ${u.message}`;throw this.logger.error(e),new Error(e)}}this.logger.info("Submitting message to connection topic",a);const l=Xh({connectionTopicId:e,operatorId:s,data:a.data,memo:r});return await this.submitPayload(l,void 0,i,o.requiresFee)}async executeTopicCreateTransaction(e){let t=e.transaction;e.feeConfig&&(t=await this.setupFees(t,e.feeConfig,e.additionalExemptAccounts||[]));try{const e=await t.execute(this.client),r=await e.getReceipt(this.client);if(!r.topicId)throw this.logger.error("Failed to create topic: topicId is null"),new Error("Failed to create topic: topicId is null");return{topicId:r.topicId.toString(),receipt:r,response:e}}catch(r){throw this.logger.error("Topic creation failed",{error:r.message,transactionId:r.transactionId?.toString(),operatorId:this.client.operatorAccountId?.toString()}),r}}async createTopic(e,t,r,i){this.logger.info("Creating topic");const n=z({memo:e,adminKey:t,submitKey:r,operatorPublicKey:this.client.operatorPublicKey||this.operatorCtx.operatorKey?.publicKey}),{topicId:o}=await this.executeTopicCreateTransaction({transaction:n,feeConfig:i});return o}async submitPayload(e,t,i,n=!1){if(e instanceof r.TopicMessageSubmitTransaction||"string"!=typeof e&&"function"==typeof e.getMessage){const t=(r.TopicMessageSubmitTransaction,e),o=t.getMessage();if(!o)throw new Error("Message payload is missing");const s=globalThis.Buffer.from(o).length;if(s>1e3)throw new ng("Payload size exceeds 1000 bytes limit",s);let a;if(n&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),t.setMaxTransactionFee(new r.Hbar(this.feeAmount))),i){const e=t.freezeWith(this.client),r=await e.sign(i);a=await r.execute(this.client)}else a=await t.execute(this.client);const c=await a.getReceipt(this.client);if(!c)throw this.logger.error("Failed to submit message: receipt is null"),new Error("Failed to submit message: receipt is null");return this.logger.info("Message submitted successfully"),c}const o="string"==typeof t?t:JSON.stringify(t),s=globalThis.Buffer.byteLength(o,"utf8");if(s>1e3)throw new ng("Payload size exceeds 1000 bytes limit",s);const a=_({topicId:e,message:o,transactionMemo:this.getHcs10TransactionMemo(t)||void 0});let c;if(n&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),a.setMaxTransactionFee(new r.Hbar(this.feeAmount))),i){const e=a.freezeWith(this.client),t=await e.sign(i);c=await t.execute(this.client)}else c=await a.execute(this.client);const l=await c.getReceipt(this.client);if(!l)throw this.logger.error("Failed to submit message: receipt is null"),new Error("Failed to submit message: receipt is null");return this.logger.info("Message submitted successfully"),l}async inscribeFile(e,t,r){if(this.logger.info("Inscribing file"),!this.client.operatorAccountId)throw this.logger.error("Operator account ID is not set"),new Error("Operator account ID is not set");if(!this.operatorCtx.operatorKey)throw this.logger.error("Operator private key is not set"),new Error("Operator private key is not set");const i=g.lookup(t)||"application/octet-stream",n=this.operatorCtx.operatorKey,o=await es.createWithAuth({type:"server",accountId:this.client.operatorAccountId.toString(),privateKey:n,network:this.network}),s={mode:"file",waitForConfirmation:!0,waitMaxAttempts:r?.waitMaxAttempts||30,waitIntervalMs:r?.waitIntervalMs||4e3,progressCallback:r?.progressCallback,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},a=await Oa({type:"buffer",buffer:e,fileName:t,mimeType:i},{accountId:this.client.operatorAccountId.toString(),privateKey:n,network:this.network},s,o);if(!a.confirmed||!a.inscription)throw new Error("Inscription was not confirmed");return a.inscription}async waitForConnectionConfirmation(e,t,r=60,i=2e3,n=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let o=0;o<r;o++){this.logger.info(`Attempt ${o+1}/${r} to find connection confirmation`);const s=(await this.mirrorNode.getTopicMessages(e)).filter(e=>"connection_created"===e.op);if(this.logger.info(`Found ${s.length} connection_created messages`),s.length>0)for(const e of s)if(Number(e.connection_id)===Number(t)){const r={connectionTopicId:e.connection_topic_id,sequence_number:Number(e.sequence_number),confirmedBy:e.operator_id,memo:e.m},i=this.extractAccountFromOperatorId(r.confirmedBy),o=this.getAccountAndSigner(),s=await this.retrieveCommunicationTopics(i),a=await this.retrieveCommunicationTopics(o.accountId);return this.logger.info("Connection confirmation found",r),n&&await this.recordOutboundConnectionConfirmation({requestorOutboundTopicId:s.outboundTopic,outboundTopicId:a.outboundTopic,connectionRequestId:t,confirmedRequestId:r.sequence_number,connectionTopicId:r.connectionTopicId,operatorId:r.confirmedBy,memo:r.memo||"Connection confirmed"}),r}o<r-1&&(this.logger.info(`No matching confirmation found, waiting ${i}ms before retrying...`),await new Promise(e=>setTimeout(e,i)))}throw new Error(`Connection confirmation not found after ${r} attempts for request ID ${t}`)}getAccountAndSigner(){const e=this.operatorCtx.operatorKey;return{accountId:this.client.operatorAccountId.toString(),signer:e}}async createAndRegisterAgent(e,t){try{const i=e.build(),n=t?.progressCallback,o=t?.baseUrl||this.guardedRegistryBaseUrl;let s=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};s.agentMetadata=i.metadata,n&&n({stage:"preparing",message:"Starting agent creation process",progressPercent:0,details:{state:s}});let a,c=i.existingAccount;if(s.inboundTopicId&&s.outboundTopicId&&s.profileTopicId){if(c=c||i.existingAccount,!c)throw new Error("Cannot resume registration without account information");const e="ecdsa"===this.operatorCtx.keyType?r.PrivateKey.fromStringECDSA(c.privateKey).publicKey.toString():r.PrivateKey.fromStringED25519(c.privateKey).publicKey.toString();a=new gg({network:i.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:e,logLevel:"info",guardedRegistryBaseUrl:o}),this.logger.info("Resuming registration with existing state",{inboundTopicId:s.inboundTopicId,outboundTopicId:s.outboundTopicId,profileTopicId:s.profileTopicId,pfpTopicId:s.pfpTopicId})}else{if(!c)if(s.createdResources&&s.createdResources.some(e=>e.startsWith("account:"))){const e=s.createdResources.find(e=>e.startsWith("account:")),r=e?.split(":")[1];r&&i.existingAccount?(c=i.existingAccount,this.logger.info(`Resuming with existing account: ${r}`)):(c=await this.createAccount(t?.initialBalance),s.createdResources=s.createdResources||[],s.createdResources.push(`account:${c.accountId}`))}else c=await this.createAccount(t?.initialBalance),s.createdResources=s.createdResources||[],s.createdResources.push(`account:${c.accountId}`);n&&n({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:s,account:c}});const r=new U({mirrorNode:this.mirrorNode,logger:this.logger}),l=await r.resolveOperatorKey(c.accountId,c.privateKey),u=l.privateKey.publicKey.toString();a=new gg({network:i.network,operatorId:c.accountId,operatorPrivateKey:l.privateKey.toString(),operatorPublicKey:u,keyType:l.keyType,logLevel:"info",guardedRegistryBaseUrl:o}),n&&n({stage:"preparing",message:"Initialized agent client",progressPercent:25,details:{state:s}});let d=s.outboundTopicId,p=s.inboundTopicId,h=s.pfpTopicId,g=s.profileTopicId;if(!d||!p||!g){h&&e.setExistingProfilePicture(h);const t=await a.createAgent(e,60,s,e=>{n&&n({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:{...e.details,state:{...s,...e.details?.state}}})});d=t.outboundTopicId,p=t.inboundTopicId,h=t.pfpTopicId,g=t.profileTopicId,s.outboundTopicId=d,s.inboundTopicId=p,s.pfpTopicId=h,s.profileTopicId=g,s.createdResources||(s.createdResources=[]),h&&!s.createdResources.includes(`pfp:${h}`)&&s.createdResources.push(`pfp:${h}`),s.createdResources.includes(`inbound:${p}`)||s.createdResources.push(`inbound:${p}`),s.createdResources.includes(`outbound:${d}`)||s.createdResources.push(`outbound:${d}`),s.createdResources.includes(`profile:${g}`)||s.createdResources.push(`profile:${g}`)}s.currentStage="profile",s.completedPercentage=60,n&&n({stage:"submitting",message:"Created agent with topics and profile",progressPercent:60,details:{state:s,outboundTopicId:d,inboundTopicId:p,pfpTopicId:h,profileTopicId:g}})}const l=`${s.inboundTopicId}@${c.accountId}`;if("complete"!==s.currentStage||!s.createdResources?.includes(`registration:${s.inboundTopicId}`)){const e=await a.registerAgentWithGuardedRegistry(c.accountId,i.network,{progressCallback:e=>{const t=60+.4*(e.progressPercent||0);n&&n({stage:e.stage,message:e.message,progressPercent:t,details:{...e.details,outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,operatorId:l,state:e.details?.state||s}})},existingState:s});if(!e.success)return{...e,state:s};s=e.state||s}return n&&n({stage:"completed",message:"Agent creation and registration complete",progressPercent:100,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,operatorId:l,state:s}}),{success:!0,state:s,metadata:{accountId:c.accountId,privateKey:c.privateKey,operatorId:l,inboundTopicId:s.inboundTopicId,outboundTopicId:s.outboundTopicId,profileTopicId:s.profileTopicId,pfpTopicId:s.pfpTopicId}}}catch(zw){const r=zw,i=`Failed to create and register agent: ${r.message}`;return this.logger.error(i),{error:r.message,success:!1,state:t?.existingState||{currentStage:"init",completedPercentage:0,error:r.message}}}}async registerAgentWithGuardedRegistry(e,t=this.network,i){try{this.logger.info("Registering agent with guarded registry");const n=i?.maxAttempts??60,o=i?.delayMs??2e3,s=i?.progressCallback;let a=i?.existingState||{currentStage:"registration",completedPercentage:0,createdResources:[]};s&&s({stage:"preparing",message:"Preparing agent registration",progressPercent:10,details:{state:a}});const c=await this.executeRegistration(e,t,this.guardedRegistryBaseUrl,this.logger);if(!c.success)return{...c,state:a};if(s&&s({stage:"submitting",message:"Submitting registration to registry",progressPercent:30,details:{transactionId:c.transactionId,state:a}}),c.transaction){const e=r.Transaction.fromBytes(globalThis.Buffer.from(c.transaction,"base64"));this.logger.info("Processing registration transaction"),await e.execute(this.client),this.logger.info("Successfully processed registration transaction")}s&&s({stage:"confirming",message:"Confirming registration transaction",progressPercent:60,details:{accountId:e,transactionId:c.transactionId,state:a}});const l=await this.waitForRegistrationConfirmation(c.transactionId,t,this.guardedRegistryBaseUrl,n,o,this.logger);return a.currentStage="complete",a.completedPercentage=100,a.createdResources||(a.createdResources=[]),c.transactionId&&a.createdResources.push(`registration:${c.transactionId}`),s&&s({stage:"completed",message:"Agent registration complete",progressPercent:100,details:{confirmed:l,transactionId:c.transactionId,state:a}}),{...c,confirmed:l,state:a}}catch(zw){const t=zw,r=`Failed to register agent: ${t.message}`;return this.logger.error(r),{error:t.message,success:!1}}}async registerAgent(e,t,r,i,n){this.logger.info("Registering agent");const o=Zh({registryTopicId:e,accountId:t,inboundTopicId:r,memo:i});await this.submitPayload(o,void 0,n)}async getInboundTopicType(e){try{const t=await this.mirrorNode.getTopicInfo(e);if(!t)throw new Error("Topic does not exist");if(!(t.submit_key&&t.submit_key.key))return Th.PUBLIC;if(t.fee_schedule_key&&t.fee_schedule_key.key&&t.custom_fees){const r=t.custom_fees;if(r&&r.fixed_fees&&r.fixed_fees.length>0)return this.logger.info(`Topic ${e} is fee-based with ${r.fixed_fees.length} custom fees`),Th.FEE_BASED}return Th.CONTROLLED}catch(zw){const t=`Error determining topic type: ${zw.message}`;throw this.logger.error(t),new Error(t)}}getNetwork(){return this.network}getLogger(){return this.logger}getOperatorAccountId(){return this.client.operatorAccountId?.toString()??null}async createScheduledTransaction(e,t,i,n){this.logger.info("Creating scheduled transaction");const o=(new r.ScheduleCreateTransaction).setScheduledTransaction(e).setPayerAccountId(n?r.AccountId.fromString(n):this.client.operatorAccountId);if(t&&o.setScheduleMemo(t),i){const e=u.addSeconds(new Date,i),t=r.Timestamp.fromDate(e);o.setExpirationTime(t)}const s=await o.execute(this.client),a=await s.getReceipt(this.client);if(!a.scheduleId)throw this.logger.error("Failed to create scheduled transaction: scheduleId is null"),new Error("Failed to create scheduled transaction: scheduleId is null");const c=a.scheduleId.toString(),l=s.transactionId.toString();return this.logger.info(`Scheduled transaction created successfully: ${c}`),{scheduleId:c,transactionId:l}}async sendTransactionOperation(e,t,r,i,n){const o=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),s={p:"hcs-10",op:"transaction",operator_id:await this.getOperatorId(),schedule_id:t,data:r,m:n?.memo};return this.logger.info("Submitting transaction operation to connection topic",s),await this.submitPayload(e,s,i,o.requiresFee)}async sendTransaction(e,t,r,i){this.logger.info("Creating scheduled transaction and sending transaction operation");const{scheduleId:n,transactionId:o}=await this.createScheduledTransaction(t,i?.scheduleMemo,i?.expirationTime,i?.schedulePayerAccountId);return{scheduleId:n,transactionId:o,receipt:await this.sendTransactionOperation(e,n,r,i?.submitKey,{memo:i?.operationMemo})}}async createCommunicationTopics(e,t,r){let i=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};if(r&&r.preparing("Starting communication topic creation",0,{state:i}),!i.outboundTopicId){i.currentStage="topics",r&&r.preparing("Creating outbound topic",5,{state:i});const e=this.client.operatorPublicKey||this.operatorCtx.operatorKey.publicKey,n=qh({ttl:t?.ttl??60,adminKey:!0,submitKey:!0,operatorPublicKey:e}),{topicId:o}=await this.executeTopicCreateTransaction({transaction:n});i.outboundTopicId=o,i.createdResources&&i.createdResources.push(`outbound:${i.outboundTopicId}`)}if(!i.inboundTopicId){i.currentStage="topics",r&&r.preparing("Creating inbound topic",10,{state:i});const n=this.client.operatorPublicKey||this.operatorCtx.operatorKey.publicKey,o=Hh({accountId:e,ttl:t?.ttl??60,adminKey:!0,submitKey:!1,operatorPublicKey:n}),{topicId:s}=await this.executeTopicCreateTransaction({transaction:o});i.inboundTopicId=s,i.createdResources&&i.createdResources.push(`inbound:${i.inboundTopicId}`)}return{inboundTopicId:i.inboundTopicId,outboundTopicId:i.outboundTopicId,state:i}}async handleProfilePictureCreation(e,t,r,i){r.currentStage="pfp",i.preparing("Creating profile picture",30,{state:r}),i.createSubProgress({minPercent:30,maxPercent:50,logPrefix:"PFP"});const n=await this.inscribePfp(e,t);if(!n.success){let e="Failed to inscribe profile picture";throw n.error&&(e=n.error),new Error(e)}const o=n.pfpTopicId;return r.pfpTopicId=o,r.createdResources&&r.createdResources.push(`pfp:${r.pfpTopicId}`),i.preparing("Profile picture created",50,{state:r}),o}async createAndInscribeProfile(e,t,r,i,n,o,s,a){if(this.logger.info("Creating and inscribing profile"),i.profileTopicId)a&&a.preparing(`Using existing ${e?"agent":"person"} profile`,95,{state:i});else{let c;if(a&&a.preparing(`Storing HCS-11 ${e?"agent":"person"} profile`,80),a?.createSubProgress({minPercent:80,maxPercent:95,logPrefix:"StoreProfile"}),e){const e=t.build(),i=e.metadata?.socials?Object.entries(e.metadata.socials).map(([e,t])=>({platform:e,handle:t})):[];c=this.hcs11Client.createAIAgentProfile(e.name,"manual"===e.metadata?.type?0:1,e.capabilities||[],e.metadata?.model||"unknown",{alias:e.name.toLowerCase().replace(/\s+/g,"_"),bio:e.bio,profileImage:r?`hcs://1/${r}`:void 0,socials:i,properties:e.metadata?.properties||{},inboundTopicId:n,outboundTopicId:o,creator:e.metadata?.creator,baseAccount:e.baseAccount})}else{const e=t.build(),{pfpBuffer:i,pfpFileName:s,...a}=e;c=this.hcs11Client.createPersonalProfile(e.display_name,{alias:e.alias,bio:e.bio,socials:e.socials,profileImage:r?`hcs://1/${r}`:e.profileImage,properties:e.properties,inboundTopicId:n,outboundTopicId:o,baseAccount:e.base_account})}const l=await this.hcs11Client.createAndInscribeProfile(c,s?.updateAccountMemo??!0);if(!l.success){a&&a.failed(`Failed to inscribe ${e?"agent":"person"} profile`,{error:l.error});let t=`Failed to inscribe ${e?"agent":"person"} profile`;throw l.error&&(t=l.error),new Error(t)}i.profileTopicId=l.profileTopicId,i.createdResources&&i.createdResources.push(`profile:${l.profileTopicId}`),a&&a.preparing("HCS-11 Profile stored",95,{state:i})}}async createMCPServer(e,t=60,r,i){await this.ensureInitialized();const n=e.build(),o=this.client.operatorAccountId?.toString();if(!o)throw new Error("Failed to retrieve operator account ID");const s=await this._createEntityTopics(t,{outboundTopicId:r?.outboundTopicId||"",inboundTopicId:r?.inboundTopicId||"",pfpTopicId:r?.pfpTopicId||n.existingPfpTopicId||"",profileTopicId:r?.profileTopicId||""},o,Th.PUBLIC,void 0,n.pfpBuffer,n.pfpFileName,i);if(s.profileTopicId)this.logger.info(`Using existing profile topic ID: ${s.profileTopicId}`);else{this.logger.info("Creating and storing HCS-11 MCP server profile"),i&&i({stage:"preparing",message:"Creating MCP server profile",progressPercent:60,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,state:{currentStage:"profile",completedPercentage:60}}}),await this.hcs11Client.initializeOperator();const e=this.hcs11Client.createMCPServerProfile(n.name,n.mcpServer,{alias:n.alias,bio:n.bio,socials:n.socials||[],inboundTopicId:s.inboundTopicId,outboundTopicId:s.outboundTopicId,profileImage:s.pfpTopicId?`hcs://1/${s.pfpTopicId}`:void 0}),t=await this.hcs11Client.inscribeProfile(e);if(!t.success)throw this.logger.error(`Failed to inscribe MCP server profile: ${t.error}`),new Error(t.error||"Failed to inscribe MCP server profile");s.profileTopicId=t.profileTopicId,this.logger.info(`MCP server profile stored with topic ID: ${s.profileTopicId}`);const r=await this.hcs11Client.updateAccountMemoWithProfile(o,s.profileTopicId);r.success?this.logger.info("Updated account memo with profile reference"):this.logger.warn(`Failed to update account memo: ${r.error}, but continuing with MCP server creation`),i&&i({stage:"preparing",message:"MCP server profile created",progressPercent:70,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,state:{currentStage:"profile",completedPercentage:70}}})}return s}async _createEntityTopics(e,t,r,i,n,o,s,a){let{outboundTopicId:c,inboundTopicId:l,pfpTopicId:u,profileTopicId:d}=t;if(c)this.logger.info(`Using existing outbound topic ID: ${c}`);else{const t=qh({ttl:e,adminKey:!0,submitKey:!0,operatorPublicKey:this.client.operatorPublicKey||this.operatorCtx.operatorKey.publicKey}),{topicId:r}=await this.executeTopicCreateTransaction({transaction:t});c=r,this.logger.info(`Created new outbound topic ID: ${c}`),a&&a({stage:"preparing",message:"Created outbound topic",progressPercent:30,details:{outboundTopicId:c,state:{currentStage:"topics",completedPercentage:30}}})}if(l?this.logger.info(`Using existing inbound topic ID: ${l}`):(l=await this.createInboundTopic(r,i,e,i===Th.FEE_BASED?n:void 0),this.logger.info(`Created new inbound topic ID: ${l}`),a&&a({stage:"preparing",message:"Created inbound topic",progressPercent:40,details:{outboundTopicId:c,inboundTopicId:l,state:{currentStage:"topics",completedPercentage:40}}})),!u&&o&&o.length>0&&s){this.logger.info("Inscribing new profile picture"),a&&a({stage:"preparing",message:"Inscribing profile picture",progressPercent:50,details:{outboundTopicId:c,inboundTopicId:l,state:{currentStage:"pfp",completedPercentage:50}}});u=(await this.inscribePfp(o,s)).pfpTopicId,this.logger.info(`Profile picture inscribed with topic ID: ${u}`),a&&a({stage:"preparing",message:"Profile picture inscribed",progressPercent:55,details:{outboundTopicId:c,inboundTopicId:l,pfpTopicId:u,state:{currentStage:"pfp",completedPercentage:55}}})}else u&&this.logger.info(`Using existing profile picture with topic ID: ${u}`);return{inboundTopicId:l,outboundTopicId:c,pfpTopicId:u,profileTopicId:d}}async createAndRegisterMCPServer(e,t){try{const i=e.build(),n=t?.progressCallback,o=t?.baseUrl||this.guardedRegistryBaseUrl;let s=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};s.serverMetadata={name:i.name,description:i.mcpServer.description,services:i.mcpServer.services},n&&n({stage:"preparing",message:"Starting MCP server creation process",progressPercent:0,details:{state:s}});let a,c=i.existingAccount;if(s.inboundTopicId&&s.outboundTopicId&&s.profileTopicId){if(c=c||i.existingAccount,!c)throw new Error("Cannot resume registration without account information");const e=M(c.privateKey),t=("ed25519"===e.detectedType?r.PrivateKey.fromStringED25519(c.privateKey):r.PrivateKey.fromStringECDSA(c.privateKey)).publicKey.toString();a=new gg({network:i.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:t,keyType:e.detectedType,logLevel:"info",guardedRegistryBaseUrl:o}),this.logger.info("Resuming registration with existing state",{inboundTopicId:s.inboundTopicId,outboundTopicId:s.outboundTopicId,profileTopicId:s.profileTopicId,pfpTopicId:s.pfpTopicId})}else{if(!c)if(s.createdResources&&s.createdResources.some(e=>e.startsWith("account:"))){const e=s.createdResources.find(e=>e.startsWith("account:")),r=e?.split(":")[1];r&&i.existingAccount?(c=i.existingAccount,this.logger.info(`Resuming with existing account: ${r}`)):(c=await this.createAccount(t?.initialBalance),s.createdResources=s.createdResources||[],s.createdResources.push(`account:${c.accountId}`))}else c=await this.createAccount(t?.initialBalance),s.createdResources=s.createdResources||[],s.createdResources.push(`account:${c.accountId}`);n&&n({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:s,account:c}});const l=new U({mirrorNode:this.mirrorNode,logger:this.logger}),u=await l.resolveOperatorKey(c.accountId,c.privateKey);e.setExistingAccount(c.accountId,c.privateKey);const d=("ed25519"===u.keyType?r.PrivateKey.fromStringED25519(c.privateKey):r.PrivateKey.fromStringECDSA(c.privateKey)).publicKey.toString();a=new gg({network:i.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:d,logLevel:"info",guardedRegistryBaseUrl:o}),n&&n({stage:"preparing",message:"Initialized MCP server client",progressPercent:25,details:{state:s}});let p=s.outboundTopicId,h=s.inboundTopicId,g=s.pfpTopicId,m=s.profileTopicId;if(!p||!h||!m){g&&e.setExistingProfilePicture(g);const t=await a.createMCPServer(e,60,s,e=>{n&&n({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:{...e.details,state:{...s,...e.details?.state}}})});p=t.outboundTopicId,h=t.inboundTopicId,g=t.pfpTopicId,m=t.profileTopicId,s.outboundTopicId=p,s.inboundTopicId=h,s.pfpTopicId=g,s.profileTopicId=m,s.createdResources||(s.createdResources=[]),g&&!s.createdResources.includes(`pfp:${g}`)&&s.createdResources.push(`pfp:${g}`),s.createdResources.includes(`inbound:${h}`)||s.createdResources.push(`inbound:${h}`),s.createdResources.includes(`outbound:${p}`)||s.createdResources.push(`outbound:${p}`),s.createdResources.includes(`profile:${m}`)||s.createdResources.push(`profile:${m}`)}s.currentStage="profile",s.completedPercentage=60,n&&n({stage:"submitting",message:"Created MCP server with topics and profile",progressPercent:60,details:{state:s,outboundTopicId:p,inboundTopicId:h,pfpTopicId:g,profileTopicId:m}})}const l=`${s.inboundTopicId}@${c.accountId}`;if("complete"!==s.currentStage||!s.createdResources?.includes(`registration:${s.inboundTopicId}`)){const e=await a.registerAgentWithGuardedRegistry(c.accountId,i.network,{progressCallback:e=>{const t=60+.4*(e.progressPercent||0);n&&n({stage:e.stage,message:e.message,progressPercent:t,details:{...e.details,outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,operatorId:l,state:e.details?.state||s}})},existingState:s});if(!e.success)return{...e,state:s};s=e.state||s}return n&&n({stage:"completed",message:"MCP server creation and registration complete",progressPercent:100,details:{outboundTopicId:s.outboundTopicId,inboundTopicId:s.inboundTopicId,pfpTopicId:s.pfpTopicId,profileTopicId:s.profileTopicId,operatorId:l,state:s}}),{success:!0,state:s,metadata:{accountId:c.accountId,privateKey:c.privateKey,operatorId:l,inboundTopicId:s.inboundTopicId,outboundTopicId:s.outboundTopicId,profileTopicId:s.profileTopicId,pfpTopicId:s.pfpTopicId}}}catch(zw){const r=zw,i=`Failed to create and register MCP server: ${r.message}`;return this.logger.error(i),{error:r.message,success:!1,state:t?.existingState||{currentStage:"init",completedPercentage:0,error:r.message}}}}async createRegistryTopic(e={}){const{ttl:t=86400,metadata:r,adminKey:i=!1,submitKey:n=!1,waitForConfirmation:o=!0,waitMaxAttempts:s=30,waitIntervalMs:a=4e3,progressCallback:c}=e;try{let e;if(await this.ensureInitialized(),c&&c({stage:"preparing",message:"Preparing registry topic creation",progressPercent:10,details:{metadata:!!r}}),r){this.logger.info("Creating metadata inscription for registry"),c&&c({stage:"submitting",message:"Creating registry metadata inscription",progressPercent:30,details:{metadataName:r.name}});const t=globalThis.Buffer.from(JSON.stringify(r,null,2)),i={mode:"file",waitForConfirmation:o,waitMaxAttempts:s,waitIntervalMs:a,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},n=await Oa({type:"buffer",buffer:t,fileName:`registry-metadata-${Date.now()}.json`,mimeType:"application/json"},{accountId:this.client.operatorAccountId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},i);if(!n.confirmed||!n.inscription)throw new Error("Metadata inscription was not confirmed");e=Ha(n.inscription),this.logger.info(`Metadata inscribed to topic: ${e}`)}c&&c({stage:"submitting",message:"Creating registry topic",progressPercent:60,details:{metadataTopicId:e}});const l=this.operatorCtx.operatorKey,u=Wh({ttl:t,metadataTopicId:e,adminKey:i,submitKey:n,operatorPublicKey:this.client.operatorPublicKey||l.publicKey}),{topicId:d,response:p}=await this.executeTopicCreateTransaction({transaction:u});return c&&c({stage:"completed",message:"Registry topic created successfully",progressPercent:100,details:{topicId:d,metadataTopicId:e,transactionId:p.transactionId.toString()}}),this.logger.info(`Registry topic created successfully: ${d}`),{success:!0,topicId:d,transactionId:p.transactionId.toString(),metadataTopicId:e}}catch(l){const e=l instanceof Error?l.message:"Unknown error";return c&&c({stage:"failed",message:`Registry creation failed: ${e}`,progressPercent:0,details:{error:e}}),this.logger.error("Failed to create registry topic",{error:e}),{success:!1,error:e}}}}const mg="undefined"!=typeof window;class fg extends rg{constructor(e){let t;if(super({network:e.network,logLevel:e.logLevel,prettyPrint:e.prettyPrint,feeAmount:e.feeAmount,mirrorNode:e.mirrorNode,silent:e.silent}),this.hcs11Client=null,this.hwc=e.hwc,e.guardedRegistryBaseUrl?this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl:this.guardedRegistryBaseUrl="https://moonscape.tech",t=e.logLevel?e.logLevel:"info",this.logger=y.getInstance({level:t,module:"HCS-Browser",prettyPrint:e.prettyPrint,silent:e.silent}),mg)try{const{accountId:t,signer:r}=this.getAccountAndSigner();this.hcs11Client=new Lh({network:e.network,auth:{operatorId:t,signer:r},logLevel:e.logLevel,silent:e.silent})}catch(_w){this.logger.warn(`Failed to initialize HCS11Client: ${_w}`)}else this.logger.error("BrowserHCSClient initialized in server environment - browser-specific features will not be available. Use HCS10Client instead.")}async sendMessage(e,t,r,i,n){this.logger.info("Sending message");const o={p:"hcs-10",op:"message",operator_id:await this.getOperatorId(),data:t,m:r},s=await this.canSubmitToTopic(e,this.hwc.getAccountInfo().accountId),a=JSON.stringify(o);if(globalThis.Buffer.from(a).length>1e3){this.logger.info("Message payload exceeds 1000 bytes, storing via inscription");try{const e=globalThis.Buffer.from(t),r=`message-${Date.now()}.json`,i=await this.inscribeFile(e,r,{progressCallback:n?.progressCallback,waitMaxAttempts:n?.waitMaxAttempts,waitIntervalMs:n?.waitIntervalMs});if(!Ha(i))throw new Error("Failed to inscribe large message content");o.data=`hcs://1/${Ha(i)}`,this.logger.info(`Large message inscribed with topic ID: ${Ha(i)}`)}catch(c){throw this.logger.error("Error inscribing large message:",c),new Error(`Failed to handle large message: ${c instanceof Error?c.message:"Unknown error"}`)}}return await this.submitPayload(e,o,i,s.requiresFee)}async getPublicKey(e){return await this.mirrorNode.getPublicKey(e)}async handleConnectionRequest(e,t,i,n="Connection accepted. Looking forward to collaborating!",o=60){this.logger.info("Handling connection request");const s=this.hwc.getAccountInfo().accountId;if(!s)throw new Error("Failed to retrieve user account ID");const a=await this.mirrorNode.getPublicKey(t),c=await this.mirrorNode.getPublicKey(s);if(!c)throw new Error("Failed to retrieve public key");const l=new r.KeyList([c,a],1),u=this._generateHcs10Memo(tg.CONNECTION,{ttl:o,inboundTopicId:e,connectionId:i}),d=(new r.TopicCreateTransaction).setTopicMemo(u).setAutoRenewAccountId(r.AccountId.fromString(s)).setAdminKey(l).setSubmitKey(l);this.logger.debug("Executing topic creation transaction");const p=await this.hwc.executeTransactionWithErrorHandling(d,!1);if(p?.error)throw this.logger.error(p.error),new Error(p.error);const h=p?.result;if(!h?.topicId)throw this.logger.error("Failed to create topic: topicId is null"),new Error("Failed to create topic: topicId is null");const g=h.topicId.toString(),m=`${e}@${s}`,f=await this.confirmConnection(e,g,t,i,m,n),y=await this.retrieveCommunicationTopics(s),b=await this.retrieveCommunicationTopics(t),w=`${b.inboundTopic}@${t}`;return await this.recordOutboundConnectionConfirmation({outboundTopicId:y.outboundTopic,requestorOutboundTopicId:b.outboundTopic,connectionRequestId:i,confirmedRequestId:f,connectionTopicId:g,operatorId:w,memo:`Connection established with ${t}`}),{connectionTopicId:g,confirmedConnectionSequenceNumber:f,operatorId:m}}async confirmConnection(e,t,r,i,n,o){this.logger.info("Confirming connection");const s={p:"hcs-10",op:"connection_created",connection_topic_id:t,connected_account_id:r,operator_id:n,connection_id:i,m:o},a=await this.submitPayload(e,s);if(!a?.topicSequenceNumber)throw this.logger.error("Failed to confirm connection: sequence number is null"),new Error("Failed to confirm connection: sequence number is null");return a.topicSequenceNumber.toNumber()}async create(e,t){const r=t?.progressCallback,i=new ts({module:"ProfileCreate",logger:this.logger,callback:r});try{const r=e instanceof cg;let n;if(n=t?.existingState?t.existingState:{currentStage:"init",completedPercentage:0,createdResources:[]},r){this.logger.info("Creating Agent Profile and HCS-10 Topics");const t=e.build();n.agentMetadata=t.metadata}else this.logger.info("Creating Person HCS-11 Profile");i.preparing(`Starting ${r?"agent":"person"} resource creation`,0,{state:n});const{inboundTopicId:o,outboundTopicId:s,state:a}=await this.createCommunicationTopics(t,i);let c,l,u;if(n=a,e.setInboundTopicId(o),e.setOutboundTopicId(s),r){const t=e.build();c=t.existingPfpTopicId||n.pfpTopicId,l=t.pfpBuffer,u=t.pfpFileName||"pfp.png"}else{const t=e.build();c=n.pfpTopicId,l=t.pfpBuffer,u=t.pfpFileName}!c&&l&&u?c=await this.handleProfilePictureCreation(l,u,n,i):c&&(i.preparing(`Using existing profile picture: ${c}`,50,{state:n}),n.pfpTopicId=c),await this.createAndInscribeProfile(r,e,c,n,o,s,t,i),n.currentStage="complete",n.completedPercentage=100,i.completed((r?"Agent":"Person")+" profile created successfully",{profileTopicId:n.profileTopicId,inboundTopicId:o,outboundTopicId:s,pfpTopicId:c,state:n});let d="";n.outboundTopicId&&(d=n.outboundTopicId);let p="";n.inboundTopicId&&(p=n.inboundTopicId);let h="";n.pfpTopicId&&(h=n.pfpTopicId);let g="";return n.profileTopicId&&(g=n.profileTopicId),{outboundTopicId:d,inboundTopicId:p,pfpTopicId:h,profileTopicId:g,success:!0,state:n}}catch(n){return i.failed("Error during profile creation",{error:n.message}),{outboundTopicId:"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:n.message,state:{currentStage:"init",completedPercentage:0,error:n.message}}}}async handleProfilePictureCreation(e,t,r,i){r.currentStage="pfp",i.preparing("Creating profile picture",30,{state:r});const n=i.createSubProgress({minPercent:30,maxPercent:50,logPrefix:"PFP"}),o=await this.inscribePfp(e,t,{progressCallback:e=>n.report({...e,progressPercent:e.progressPercent??0,details:{...e.details,state:r}})});if(!o.success){let e="Failed to inscribe profile picture";throw o.error&&(e=o.error),new Error(e)}const s=o.pfpTopicId;return r.pfpTopicId=s,r.createdResources&&r.createdResources.push(`pfp:${r.pfpTopicId}`),i.preparing("Profile picture created",50,{state:r}),s}async createAndInscribeProfile(e,t,r,i,n,o,s,a){if(!this.hcs11Client)throw a&&a.failed("HCS11Client is not available"),new Error("HCS11Client is not available");if(this.logger.info("Creating and inscribing profile"),i.profileTopicId)a&&a.preparing(`Using existing ${e?"agent":"person"} profile`,95,{state:i});else{a&&a.preparing(`Storing HCS-11 ${e?"agent":"person"} profile`,80);const c=a?.createSubProgress({minPercent:80,maxPercent:95,logPrefix:"StoreProfile"});let l;if(e){const e=t.build(),i=e.metadata?.socials?Object.entries(e.metadata.socials).map(([e,t])=>({platform:e,handle:t})):[];l=this.hcs11Client.createAIAgentProfile(e.name,"manual"===e.metadata?.type?0:1,e.capabilities||[],e.metadata?.model||"unknown",{alias:e.name.toLowerCase().replace(/\s+/g,"_"),bio:e.bio,profileImage:r?`hcs://1/${r}`:void 0,socials:i,properties:e.metadata?.properties||{},inboundTopicId:n,outboundTopicId:o,creator:e.metadata?.creator})}else{const e=t.build(),{pfpBuffer:i,pfpFileName:s,...a}=e;l=this.hcs11Client.createPersonalProfile(e.display_name,{alias:e.alias,bio:e.bio,socials:e.socials,profileImage:r?`hcs://1/${r}`:e.profileImage,properties:e.properties,inboundTopicId:n,outboundTopicId:o})}const u=await this.hcs11Client.createAndInscribeProfile(l,s?.updateAccountMemo??!0,{progressCallback:e=>c?.report({...e,progressPercent:e.progressPercent??0})});if(!u.success){a&&a.failed(`Failed to inscribe ${e?"agent":"person"} profile`,{error:u.error});let t=`Failed to inscribe ${e?"agent":"person"} profile`;throw u.error&&(t=u.error),new Error(t)}i.profileTopicId=u.profileTopicId,i.createdResources&&i.createdResources.push(`profile:${u.profileTopicId}`),a&&a.preparing("HCS-11 Profile stored",95,{state:i})}}initializeRegistrationState(e,t){const r=t||{inboundTopicId:e,currentStage:"registration",completedPercentage:0,createdResources:[]};return"registration"!==r.currentStage&&"complete"!==r.currentStage&&(r.currentStage="registration"),r}updateStateForCompletedRegistration(e,t){e.currentStage="complete",e.completedPercentage=100,e.createdResources&&e.createdResources.push(`registration:${t}`)}async registerAgentWithGuardedRegistry(e,t=this.network,i){try{let n;if(this.logger.info("Registering agent with guarded registry"),i?.existingState?.inboundTopicId)this.logger.info("Using inboundTopicId from existing state"),n=i.existingState.inboundTopicId;else{const t=await this.retrieveProfile(e,!1,{maxRetries:5,retryDelay:3e3});if(!t.success||!t.profile||!t.topicInfo){const r=t.error||`Failed to retrieve profile for account ${e}. Make sure the agent profile is created and memo is updated before registration.`;return this.logger.error(r),{error:r,success:!1,state:{currentStage:"registration",completedPercentage:0,error:r}}}n=t.topicInfo.inboundTopic}const o=this.initializeRegistrationState(n,i?.existingState),s=new ts({module:"AgentRegistration",logger:this.logger,callback:i?.progressCallback});s.preparing("Preparing agent registration",10,{inboundTopicId:n,accountId:e});const a=await this.executeRegistration(e,t,this.guardedRegistryBaseUrl,this.logger);if(!a.success)return{...a,state:o};if(s.submitting("Submitting registration to registry",30,{transactionId:a.transactionId}),a.transaction){const e=r.Transaction.fromBytes(globalThis.Buffer.from(a.transaction,"base64"));this.logger.info("Processing registration transaction");const t=await this.hwc.executeTransactionWithErrorHandling(e,!0);if(t.error)return{...a,error:t.error,success:!1,state:o};this.logger.info("Successfully processed registration transaction")}s.confirming("Confirming registration transaction",60,{accountId:e,inboundTopicId:n,transactionId:a.transactionId});const c=i?.maxAttempts??60,l=i?.delayMs??2e3,u=await this.waitForRegistrationConfirmation(a.transactionId,t,this.guardedRegistryBaseUrl,c,l,this.logger);return this.updateStateForCompletedRegistration(o,n),s.completed("Agent registration complete",{transactionId:a.transactionId,inboundTopicId:n,state:o,confirmed:u}),{...a,confirmed:u,state:o}}catch(n){return this.logger.error(`Registration error: ${n.message}`),{error:`Error during registration: ${n.message}`,success:!1,state:{currentStage:"registration",completedPercentage:0,error:n.message}}}}async createAndRegisterAgent(e,t){try{const r=e.build(),i=t?.progressCallback,n=new ts({module:"AgentCreateRegister",logger:this.logger,callback:i});let o=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};if(o.agentMetadata=r.metadata,n.preparing("Starting agent creation process",0,{state:o}),"complete"!==o.currentStage||!o.inboundTopicId||!o.outboundTopicId||!o.profileTopicId){const t=await this.create(e,{progressCallback:e=>{const t=.3*(e.progressPercent||0);n.report({...e,progressPercent:t,details:{...e.details,state:e.details?.state||o}})},existingState:o,updateAccountMemo:!0});if(!("state"in t))throw new Error("Create method did not return expected agent state.");if(!t.success)throw new Error(t.error||"Failed to create agent resources");o=t.state,o.agentMetadata=r.metadata,this.logger.info("Waiting for account memo update to propagate..."),await new Promise(e=>setTimeout(e,5e3))}n.preparing(`Agent creation status: ${o.currentStage}, ${o.completedPercentage}%`,30,{state:o});const{accountId:s}=this.getAccountAndSigner();if("complete"!==o.currentStage||!o.createdResources?.includes(`registration:${o.inboundTopicId}`)){t?.baseUrl&&(this.guardedRegistryBaseUrl=t.baseUrl);const e=await this.registerAgentWithGuardedRegistry(s,r.network,{progressCallback:e=>{const t=30+.7*(e.progressPercent||0);n.report({...e,progressPercent:t,details:{...e.details,state:e.details?.state||o}})},maxAttempts:t?.maxAttempts,delayMs:t?.delayMs,existingState:o});if(!e.success)throw new Error(e.error||"Failed to register agent with registry");o=e.state}return n.completed("Agent creation and registration complete",{state:o}),{success:!0,state:o,metadata:{accountId:s,operatorId:`${o.inboundTopicId}@${s}`,inboundTopicId:o.inboundTopicId,outboundTopicId:o.outboundTopicId,profileTopicId:o.profileTopicId,pfpTopicId:o.pfpTopicId,privateKey:null,...o.agentMetadata}}}catch(r){return this.logger.error(`Failed to create and register agent: ${r.message}`),{success:!1,error:`Failed to create and register agent: ${r.message}`,state:t?.existingState||{currentStage:"init",completedPercentage:0,error:r.message}}}}async storeHCS11Profile(e,t,r,i,n=[],o={},s,a,c,l){try{const u=l?.progressCallback,d=new ts({module:"StoreHCS11Profile",logger:this.logger,callback:u});d.preparing("Preparing agent profile data",0);let p=c;if(!p&&s&&a){const e=d.createSubProgress({minPercent:0,maxPercent:60,logPrefix:"PFP"}),t=await this.inscribePfp(s,a,{progressCallback:t=>{e.report({stage:t.stage,message:t.message,progressPercent:t.progressPercent||0,details:t.details})}});t.success?p=t.pfpTopicId:d.failed("Failed to inscribe profile picture, continuing without PFP")}else c?d.preparing(`Using existing profile picture: ${c}`,30):d.preparing("No profile picture provided",30);if(!this.hcs11Client)return d.failed("HCS11Client is not available in this environment"),{profileTopicId:"",success:!1,error:"HCS11Client is not available in this environment",transactionId:""};const h=this.hcs11Client.getAgentTypeFromMetadata({type:o.type||"autonomous"});d.preparing("Building agent profile",65);const g=o.socials?Object.entries(o.socials).filter(([e,t])=>t).map(([e,t])=>({platform:e,handle:t})):void 0,m=this.hcs11Client.createAIAgentProfile(e,h,n,o.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:p?`hcs://1/${p}`:void 0,socials:g,properties:{version:o.version||"1.0.0",creator:o.creator||"Unknown",supported_languages:o.supported_languages||["en"],permissions:o.permissions||[],model_details:o.model_details,training:o.training,capabilities_description:o.capabilities_description,...o},inboundTopicId:r,outboundTopicId:i,creator:o.creator}),f=d.createSubProgress({minPercent:65,maxPercent:100,logPrefix:"Profile"}),y=await this.hcs11Client.createAndInscribeProfile(m,l?.updateAccountMemo??!0,{progressCallback:e=>{f.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:e.details})}});return y.success?(d.completed("Profile stored successfully",{profileTopicId:y.profileTopicId}),{profileTopicId:y.profileTopicId,pfpTopicId:p,success:!0,transactionId:y.transactionId||""}):(d.failed("Failed to inscribe profile"),{profileTopicId:"",success:!1,error:y.error||"Failed to inscribe profile",transactionId:y.transactionId||""})}catch(u){return this.logger.error(`Error storing HCS11 profile: ${u.message}`),{profileTopicId:"",success:!1,error:u.message,transactionId:""}}}async createTopic(e,t,i){this.logger.info("Creating topic");const{accountId:n,signer:o}=this.getAccountAndSigner(),s=(new r.TopicCreateTransaction).setTopicMemo(e),a=await this.mirrorNode.getPublicKey(n);t&&a&&(s.setAdminKey(a),s.setAutoRenewAccountId(n)),i&&a&&s.setSubmitKey(a);const c=await this.hwc.executeTransactionWithErrorHandling(s,!1),l=c.error;if(l)return this.logger.error(l),{success:!1,error:l};const u=c.result;return u?.topicId?{success:!0,topicId:u.topicId.toString()}:(this.logger.error("Failed to create topic: topicId is null"),{success:!1,error:"Failed to create topic: topicId is null"})}async submitPayload(e,t,i,n){let o;this.logger.debug(`Submitting payload to topic ${e}`),o="string"==typeof t?t:JSON.stringify(t);const s=(new r.TopicMessageSubmitTransaction).setTopicId(e).setMessage(o),a=this.getHcs10TransactionMemo(t);let c;if(a&&s.setTransactionMemo(a),n&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),s.setMaxTransactionFee(new r.Hbar(this.feeAmount))),i){const{signer:e}=this.getAccountAndSigner();s.freezeWithSigner(e);const t=await s.sign(i);c=await this.hwc.executeTransactionWithErrorHandling(t,!0)}else c=await this.hwc.executeTransactionWithErrorHandling(s,!1);if(c?.error)throw this.logger.error(`Failed to submit payload: ${c.error}`),new Error(`Failed to submit payload: ${c.error}`);if(!c?.result)throw this.logger.error("Failed to submit message: receipt is null or undefined"),new Error("Failed to submit message: receipt is null or undefined");return this.logger.debug("Payload submitted successfully via HWC"),c.result}async inscribeFile(e,t,r){const{accountId:i,signer:n}=this.getAccountAndSigner(),o=g.lookup(t)||"application/octet-stream",s=await es.createWithAuth({type:"client",accountId:i,signer:n,network:this.network}),a={mode:"file",waitForConfirmation:!0,waitMaxAttempts:r?.waitMaxAttempts||30,waitIntervalMs:r?.waitIntervalMs||4e3,progressCallback:r?.progressCallback,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},c=await Fa({type:"buffer",buffer:e,fileName:t,mimeType:o},n,{...a,network:this.network},s);if(!c.confirmed||!c.inscription)throw new Error("Inscription was not confirmed");return c.inscription}getAccountAndSigner(){const e=this?.hwc?.getAccountInfo(),t=e?.accountId?.toString(),r=this?.hwc?.dAppConnector?.signers?.find(e=>e.getAccountId().toString()===t);if(!r)throw this.logger.error("Failed to find signer",{accountId:t,signers:this?.hwc?.dAppConnector?.signers,accountInfo:e}),new Error("Failed to find signer");return{accountId:t,signer:r}}async inscribePfp(e,t,r){try{const i=r?.progressCallback,n=new ts({module:"PFP-Inscription",logger:this.logger,callback:i});if(!this.hcs11Client)return n.failed("HCS11Client is not available in this environment"),{pfpTopicId:"",success:!1,error:"HCS11Client is not available in this environment",transactionId:""};n.preparing("Preparing to inscribe profile picture",10),this.logger.info("Inscribing profile picture using HCS-11 client");const o=e=>{n.report({stage:e.stage||"confirming",message:e.message||"Processing PFP inscription",progressPercent:e.progressPercent||50,details:e.details})},s=await this.hcs11Client.inscribeImage(e,t,{progressCallback:o});if(!s.success){let e="Failed to inscribe profile picture";s.error&&(e=s.error);let t="";return s.transactionId&&(t=s.transactionId),{pfpTopicId:"",success:!1,error:e,transactionId:t}}return n.completed("Successfully inscribed profile picture",{pfpTopicId:s.imageTopicId}),this.logger.info(`Successfully inscribed profile picture with topic ID: ${s.imageTopicId}`),{pfpTopicId:s.imageTopicId,success:!0,transactionId:s.transactionId||""}}catch(i){return this.logger.error(`Error inscribing profile picture: ${i.message}`),{pfpTopicId:"",success:!1,error:i.message,transactionId:""}}}async createCommunicationTopics(e,t){let r=e?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};t&&t.preparing("Starting communication topic creation",0,{state:r});const{accountId:i}=this.getAccountAndSigner();if(!r.outboundTopicId){r.currentStage="topics",t&&t.preparing("Creating outbound topic",5,{state:r});const n=this._generateHcs10Memo(tg.OUTBOUND,{ttl:e?.ttl,accountId:i}),o=await this.createTopic(n,!0,!0);if(!o.success||!o.topicId)throw new Error(o.error||"Failed to create outbound topic");r.outboundTopicId=o.topicId,r.createdResources&&r.createdResources.push(`outbound:${r.outboundTopicId}`)}if(!r.inboundTopicId){r.currentStage="topics",t&&t.preparing("Creating inbound topic",10,{state:r});const n=this._generateHcs10Memo(tg.INBOUND,{ttl:e?.ttl,accountId:i}),o=await this.createTopic(n,!0,!1);if(!o.success||!o.topicId)throw new Error(o.error||"Failed to create inbound topic");r.inboundTopicId=o.topicId,r.createdResources&&r.createdResources.push(`inbound:${r.inboundTopicId}`)}return{inboundTopicId:r.inboundTopicId,outboundTopicId:r.outboundTopicId,state:r}}}const yg=Object.freeze(Object.defineProperty({__proto__:null,AccountCreationError:og,BrowserHCSClient:fg,ConnectionConfirmationError:ag,ConnectionsManager:hg,HCS10BaseClient:rg,HCS10Cache:ig,HCS10Client:gg,Hcs10MemoType:tg,PayloadSizeError:ng,Registration:Kh,TopicCreationError:sg,buildHcs10ConfirmConnectionTx:Gh,buildHcs10CreateConnectionTopicTx:jh,buildHcs10CreateInboundTopicTx:Hh,buildHcs10CreateOutboundTopicTx:qh,buildHcs10CreateRegistryTopicTx:Wh,buildHcs10OutboundConnectionCreatedRecordTx:Yh,buildHcs10OutboundConnectionRequestRecordTx:Jh,buildHcs10RegistryDeleteTx:Qh,buildHcs10RegistryMigrateTx:eg,buildHcs10RegistryRegisterTx:Zh,buildHcs10SendMessageTx:Xh,buildHcs10SubmitConnectionRequestTx:Vh},Symbol.toStringTag,{value:"Module"}));var bg=(e=>(e[e.ACTION=0]="ACTION",e[e.ASSEMBLY=2]="ASSEMBLY",e[e.HASHLINKS=3]="HASHLINKS",e))(bg||{});class wg{constructor(e,t,r,i,n){this.entries=new Map,this.networkType=e,this.logger=t,this.registryType=r,this.topicId=i,this.client=n}async getEntry(e){const t=this.entries.get(e);return t||(this.topicId&&this.client?(await this.sync(),this.entries.get(e)||null):null)}async getLatestEntry(e){if(!this.client)return null;try{const t=await this.client.mirrorNode.getTopicMessagesByFilter(e,{order:"desc",limit:1});if(!t||0===t.length)return null;const r=t[0];let i;if(r.raw_content)i=JSON.parse(r.raw_content);else{const e=r;if("hcs-12"!==e.p||!e.op)return null;i={p:e.p,op:e.op,name:e.name,version:e.version,description:e.description,permissions:e.permissions,metadata:e.metadata,data:e.data,category:e.category,source:e.source,inputs:e.inputs,outputs:e.outputs,tags:e.tags,fields:e.fields,styles:e.styles,actions:e.actions,blocks:e.blocks,refs:e.refs},Object.keys(i).forEach(e=>{void 0===i[e]&&delete i[e]})}return{id:r.sequence_number.toString(),sequenceNumber:r.sequence_number,timestamp:r.consensus_timestamp||(new Date).toISOString(),submitter:r.payer||"unknown",data:i}}catch(t){return this.logger.error("Failed to get latest entry",{topicId:e,error:t}),null}}async listEntries(e){this.topicId&&this.client&&await this.sync();const t=Array.from(this.entries.values());return e?t.filter(t=>(!e.submitter||t.submitter===e.submitter)&&(!(e.afterTimestamp&&t.timestamp<e.afterTimestamp)&&!(e.beforeTimestamp&&t.timestamp>e.beforeTimestamp))):t}async sync(){if(this.topicId&&this.client){this.logger.info("Syncing registry entries",{topicId:this.topicId,registryType:bg[this.registryType],lastSync:this.lastSyncTimestamp});try{const t=await this.client.mirrorNode.getTopicMessagesByFilter(this.topicId,{startTime:this.lastSyncTimestamp,order:"asc",limit:100});for(const r of t)try{let e;if(r.raw_content)e=JSON.parse(r.raw_content);else{const t=r;if("hcs-12"!==t.p||!t.op)continue;e={p:t.p,op:t.op,name:t.name,version:t.version,description:t.description,permissions:t.permissions,metadata:t.metadata,data:t.data,category:t.category,source:t.source,inputs:t.inputs,outputs:t.outputs,tags:t.tags,fields:t.fields,styles:t.styles,actions:t.actions,blocks:t.blocks,refs:t.refs,t_id:t.t_id,hash:t.hash,wasm_hash:t.wasm_hash,info_t_id:t.info_t_id,validation_rules:t.validation_rules,js_t_id:t.js_t_id,js_hash:t.js_hash,interface_version:t.interface_version,title:t.title,template:t.template,author:t.author,m:t.m},Object.keys(e).forEach(t=>{void 0===e[t]&&delete e[t]})}if("hcs-12"!==e.p)continue;const t={id:r.sequence_number.toString(),sequenceNumber:r.sequence_number,timestamp:r.consensus_timestamp||(new Date).toISOString(),submitter:r.payer||"unknown",data:e};this.entries.set(t.id,t)}catch(e){this.logger.warn("Failed to parse registry message",{sequenceNumber:r.sequence_number,error:e})}t.length>0?this.lastSyncTimestamp=t[t.length-1].consensus_timestamp||(new Date).toISOString():this.lastSyncTimestamp=(new Date).toISOString(),this.logger.info("Registry sync completed",{topicId:this.topicId,messageCount:t.length,lastSync:this.lastSyncTimestamp})}catch(e){throw this.logger.error("Failed to sync registry",{error:e}),e}}else this.logger.warn("Cannot sync without topic ID and client")}getTopicMemo(){return`hcs-12:1:60:${this.registryType}`}async createRegistryTopic(){if(!this.client)throw new Error("Client required to create topic");const e=await this.client.createRegistryTopic(this.registryType);return this.topicId=e,e}getConfig(){return{type:this.registryType,indexed:!1,ttl:60,topicId:this.topicId,memo:this.getTopicMemo()}}async inscribeContent(e,t,r){if(!this.client)throw new Error("Client required for inscription");const i="string"==typeof e?globalThis.Buffer.from(e):e;let n;if(this.logger.info("Inscribing content via HCS-1",{size:i.length,mimeType:t,registryType:bg[this.registryType]}),"getOperatorAccountId"in this.client)n=await Oa({type:"buffer",buffer:i,fileName:"application/octet-stream"===t&&"wasm"===r?.fileType?`${r?.name||"content"}.wasm`:r?.name||"content",mimeType:t},{accountId:this.client.getOperatorAccountId(),privateKey:this.client.getOperatorPrivateKey(),network:this.networkType},{mode:"file",metadata:r,waitForConfirmation:!0});else{const{accountId:e,signer:o}=await this.client.getAccountAndSigner();n=await Fa({type:"buffer",buffer:i,fileName:"application/octet-stream"===t&&"wasm"===r?.fileType?`${r?.name||"content"}.wasm`:r?.name||"content",mimeType:t},o,{mode:"file",metadata:r,waitForConfirmation:!0})}if(!n.confirmed)throw new Error("Failed to inscribe content");const o=n.inscription.topic_id;if(!o)throw new Error("No topic ID in inscription response");return this.logger.info("Content inscribed successfully",{topicId:o}),o}validateBaseRegistration(e){if(!e.p||"hcs-12"!==e.p)throw new Error("Invalid protocol identifier");if(!e.op||"register"!==e.op)throw new Error("Invalid operation")}clearCache(){this.entries.clear(),this.lastSyncTimestamp=void 0,this.logger.info("Registry cache cleared",{registryType:bg[this.registryType]})}getStats(){return{entryCount:this.entries.size,lastSync:this.lastSyncTimestamp,topicId:this.topicId,registryType:bg[this.registryType]}}}const Ig=t.z.object({p:t.z.literal("hcs-12")}),Tg=t.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid Hedera address format"),Sg=t.z.string().regex(/^[a-f0-9]{64}$/,"Invalid SHA-256 hash format"),kg=t.z.object({format:t.z.enum(["tar.gz","zip","car"]),root_manifest:t.z.string(),includes_lockfile:t.z.boolean(),workspace_members:t.z.array(t.z.string()).optional()}),vg=t.z.object({source_t_id:Tg,source_hash:Sg,compiler_version:t.z.string(),cargo_version:t.z.string(),target:t.z.literal("wasm32-unknown-unknown"),profile:t.z.string(),build_flags:t.z.array(t.z.string()),lockfile_hash:Sg,source_structure:kg}),Eg=t.z.lazy(()=>t.z.object({type:t.z.string().optional(),required:t.z.array(t.z.string()).optional(),properties:t.z.record(Eg).optional(),pattern:t.z.string().optional(),minimum:t.z.number().optional(),maximum:t.z.number().optional(),regex:t.z.string().optional(),min:t.z.number().optional(),max:t.z.number().optional(),length:t.z.number().optional(),email:t.z.boolean().optional(),url:t.z.boolean().optional(),uuid:t.z.boolean().optional(),cuid:t.z.boolean().optional(),cuid2:t.z.boolean().optional(),ulid:t.z.boolean().optional(),datetime:t.z.boolean().optional(),ip:t.z.boolean().optional(),startsWith:t.z.string().optional(),endsWith:t.z.string().optional(),includes:t.z.string().optional(),gt:t.z.number().optional(),gte:t.z.number().optional(),lt:t.z.number().optional(),lte:t.z.number().optional(),int:t.z.boolean().optional(),positive:t.z.boolean().optional(),nonnegative:t.z.boolean().optional(),negative:t.z.boolean().optional(),nonpositive:t.z.boolean().optional(),multipleOf:t.z.number().optional(),finite:t.z.boolean().optional(),safe:t.z.boolean().optional(),nonempty:t.z.boolean().optional(),literal:t.z.union([t.z.string(),t.z.number(),t.z.boolean()]).optional(),enum:t.z.array(t.z.string()).optional(),nullable:t.z.boolean().optional(),nullish:t.z.boolean().optional(),optional:t.z.boolean().optional(),element:t.z.any().optional(),shape:t.z.record(t.z.any()).optional(),strict:t.z.boolean().optional(),passthrough:t.z.boolean().optional(),catchall:t.z.any().optional()})),Ag=t.z.object({p:t.z.literal("hcs-12"),op:t.z.literal("register"),t_id:Tg,hash:Sg,wasm_hash:Sg,js_t_id:Tg.optional(),js_hash:Sg.optional(),interface_version:t.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid version format").optional(),info_t_id:Tg.optional(),source_verification:vg.optional(),previous_version:t.z.string().optional(),migration_notes:t.z.string().optional(),validation_rules:t.z.record(Eg).optional(),m:t.z.string().optional()}),Cg=t.z.object({p:t.z.literal("hcs-12"),op:t.z.enum(["register","template"]),name:t.z.string(),version:t.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid semver format"),data:t.z.union([t.z.any(),t.z.string()]).optional(),t_id:Tg.optional()});t.z.enum(["register","add-action","add-block","update"]);const Rg=Ig.extend({op:t.z.literal("register"),name:t.z.string(),version:t.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid semver format"),description:t.z.string().optional(),tags:t.z.array(t.z.string()).optional(),author:t.z.string().optional()}),xg=Ig.extend({op:t.z.literal("add-action"),t_id:Tg,alias:t.z.string(),config:t.z.any().optional(),data:Tg.optional()}),Ng=Ig.extend({op:t.z.literal("add-block"),block_t_id:Tg,actions:t.z.record(t.z.string(),Tg).optional(),attributes:t.z.record(t.z.any()).optional(),children:t.z.array(t.z.string()).optional(),data:Tg.optional()}),zg=Ig.extend({op:t.z.literal("update"),description:t.z.string().optional(),tags:t.z.array(t.z.string()).optional()});t.z.object({type:t.z.enum(["vertical","horizontal","grid"]),responsive:t.z.boolean().optional(),containerClass:t.z.string().optional()}),t.z.object({source_t_id:Tg,source_hash:Sg,description:t.z.string().optional()});const _g=t.z.discriminatedUnion("op",[Rg,xg,Ng,zg]),Pg=Rg,Og=Ig.extend({op:t.z.literal("register"),t_id:Tg,name:t.z.string().max(100,"Name must be 100 characters or less"),description:t.z.string().max(500,"Description must be 500 characters or less").optional(),tags:t.z.array(t.z.string()).max(10,"Maximum 10 tags allowed").optional(),category:t.z.string().optional(),featured:t.z.boolean().optional(),icon:t.z.string().optional(),author:t.z.string().optional(),website:t.z.string().url().optional()});function Dg(e){return Ag.parse(e)}function Fg(e){return _g.parse(e)}function Mg(e,t){const r=t.safeParse(e);return r.success?{isValid:!0,errors:[],data:r.data}:{isValid:!1,errors:r.error.errors.map(e=>`${e.path.join(".")}: ${e.message}`)}}class Ug extends wg{constructor(e,t,r,i){super(e,t,bg.ACTION,r,i),this.actionsByHash=new Map,this.cryptoAdapter=nh()}async registerWithWasm(e,t,r){let i,n;if(Xp()){i=this.createSSRSafeHash(e,"wasm");const r=JSON.stringify(t);n=this.createSSRSafeHash(globalThis.Buffer.from(r),"info")}else{const r=this.cryptoAdapter.createHash("sha256").update(e).digest("hex"),o=r instanceof Promise?await r:r;i="string"==typeof o?o:o.toString("hex");const s=JSON.stringify(t),a=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(s)).digest("hex"),c=a instanceof Promise?await a:a;n="string"==typeof c?c:c.toString("hex")}const o=await this.inscribeContent(e,"application/octet-stream",{name:t.name,version:t.version,hash:i,fileType:"wasm"});let s;const a=JSON.stringify(t);globalThis.Buffer.byteLength(a,"utf8")>1024&&(s=await this.inscribeContent(a,"application/json",{name:`${t.name}-info`,version:t.version}));const c={p:"hcs-12",op:"register",t_id:o,hash:n,wasm_hash:i,info_t_id:s,source_verification:r,m:`${t.name} v${t.version}`};return await this.register(c),c}async register(e){if(this.validateRegistration(e),this.topicId&&this.client){this.logger.info("Submitting action registration to HCS",{topicId:this.topicId,hash:e.hash,wasmHash:e.wasm_hash});const t=(await this.client.submitMessage(this.topicId,JSON.stringify(e))).sequenceNumber;if(!t)throw new Error("No sequence number returned from submission");const r={id:t.toString(),sequenceNumber:t,timestamp:(new Date).toISOString(),submitter:"getHashConnect"in this.client?(await this.client.getAccountAndSigner()).accountId:this.client.getOperatorAccountId(),data:e};return this.entries.set(r.id,r),this.actionsByHash.set(e.hash,e),this.logger.info("Action registered",{hash:e.hash,sequenceNumber:t,hasSourceVerification:!!e.source_verification}),t.toString()}{const t=this.entries.size+1,r={id:t.toString(),sequenceNumber:t,timestamp:(new Date).toISOString(),submitter:"local",data:e};return this.entries.set(r.id,r),this.actionsByHash.set(e.hash,e),t.toString()}}async getAction(e){const t=this.actionsByHash.get(e);return t||(this.topicId&&this.client?(await this.sync(),this.actionsByHash.get(e)||null):null)}async getActionByTopicId(e){this.logger.debug("getActionByTopicId called",{topicId:e}),console.log("DEBUG: getActionByTopicId called",{topicId:e,cacheSize:this.actionsByHash.size,cachedTopicIds:Array.from(this.actionsByHash.values()).map(e=>e.t_id)});for(const t of this.actionsByHash.values())if(t.t_id===e)return this.logger.debug("Action found in cache",{topicId:e,action:t}),console.log("DEBUG: Action found in cache",{topicId:e,action:t}),t;if(this.topicId&&this.client){this.logger.debug("Action not in cache, syncing...",{topicId:e}),console.log("DEBUG: Action not in cache, syncing..."),await this.sync(),console.log("DEBUG: After sync",{cacheSize:this.actionsByHash.size,cachedTopicIds:Array.from(this.actionsByHash.values()).map(e=>e.t_id)});for(const t of this.actionsByHash.values())if(t.t_id===e)return this.logger.debug("Action found after sync",{topicId:e,action:t}),console.log("DEBUG: Action found after sync",{topicId:e,action:t}),t}return this.logger.warn("Action not found",{topicId:e}),console.log("DEBUG: Action not found",{topicId:e}),null}async getActionInfo(e){const t=await this.getAction(e);if(!t)return null;try{let e;if(!t.info_t_id)return this.logger.warn("Inline INFO storage not yet implemented"),null;{if(!this.client)return this.logger.error("Client not initialized - cannot fetch INFO"),null;let r;if("getOperatorAccountId"in this.client)r=await Ma(t.info_t_id,{accountId:this.client.getOperatorAccountId(),privateKey:this.client.getOperatorPrivateKey(),network:this.networkType});else{const{accountId:e}=await this.client.getAccountAndSigner();r=await Ma(t.info_t_id,{accountId:e,network:this.networkType})}if(!r.content)return this.logger.error("No content in inscription response"),null;e="string"==typeof r.content?r.content:globalThis.Buffer.from(r.content).toString("utf8")}const r=JSON.parse(e);let i;if(Xp())i=this.createSSRSafeHash(globalThis.Buffer.from(e),"info");else{const t=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(e)).digest("hex"),r=t instanceof Promise?await t:t;i="string"==typeof r?r:r.toString("hex")}if(i!==t.hash)throw this.logger.error("INFO hash mismatch",{expected:t.hash,computed:i}),new Error("Module info verification failed");return r}catch(r){return this.logger.error("Failed to fetch action INFO",{hash:e,error:r}),null}}async getActionWasm(e){const t=await this.getAction(e);if(!t)return null;if(!this.client)return this.logger.error("Client not initialized - cannot fetch WASM"),null;try{let e;if("getOperatorAccountId"in this.client)e=await Ma(t.t_id,{accountId:this.client.getOperatorAccountId(),privateKey:this.client.getOperatorPrivateKey(),network:this.networkType});else{const{accountId:r}=await this.client.getAccountAndSigner();e=await Ma(t.t_id,{accountId:r,network:this.networkType})}if(!e.content)return this.logger.error("No content in inscription response"),null;const r="string"==typeof e.content?globalThis.Buffer.from(e.content,"base64"):globalThis.Buffer.from(e.content);let i;if(Xp())i=this.createSSRSafeHash(r,"wasm");else{const e=this.cryptoAdapter.createHash("sha256").update(r).digest("hex"),t=e instanceof Promise?await e:e;i="string"==typeof t?t:t.toString("hex")}if(i!==t.wasm_hash)throw this.logger.error("WASM hash mismatch",{expected:t.wasm_hash,computed:i}),new Error("WASM binary verification failed");return new Uint8Array(r)}catch(r){return this.logger.error("Failed to fetch WASM from HCS-1",{topicId:t.t_id,error:r}),null}}async searchActions(e){return(await this.listEntries({submitter:e.creator,afterTimestamp:e.afterTimestamp,beforeTimestamp:e.beforeTimestamp})).map(e=>e.data).filter(t=>{if(void 0!==e.hasSourceVerification){if(!!t.source_verification!==e.hasSourceVerification)return!1}return!0})}async getVersionChain(e){const t=[];let r=e;for(;r;){const e=await this.getAction(r);if(!e)break;t.push(e),r=void 0}return t}validateRegistration(e){try{Dg(e)}catch(r){if(r instanceof t.ZodError){const e=r.errors[0];throw new Error(`Validation failed: ${e.path.join(".")} - ${e.message}`)}throw r}}async sync(){await super.sync(),this.actionsByHash.clear();for(const e of this.entries.values()){const t=e.data;this.actionsByHash.set(t.hash,t)}}clearCache(){super.clearCache(),this.actionsByHash.clear()}createSSRSafeHash(e,t){let r=0;for(let i=0;i<Math.min(e.length,256);i++)r=(r<<5)-r+e[i]&4294967295;return`ssr-${t}-${e.length}-${Math.abs(r).toString(16).padStart(8,"0")}`}}class Bg{constructor(e,t,r){this.blockCache=new Map,this.templateCache=new Map,this.networkType=e,this.logger=t,this.client=r}async loadBlockDefinition(e){const t=this.blockCache.get(e);if(t)return t;try{const t=new Wp,r=await t.resolve(e,{network:this.networkType});if(!r.content)throw new Error(`Block definition not found: ${e}`);let i;return i="object"!=typeof r.content||null===r.content||r.content instanceof ArrayBuffer?JSON.parse("string"==typeof r.content?r.content:r.content.toString()):r.content,this.blockCache.set(e,i),i}catch(r){throw this.logger.error("Failed to load block definition",{blockTopicId:e,error:r.message}),new Error(`Failed to load block definition: ${r.message}`)}}async loadBlockTemplate(e){const t=this.templateCache.get(e);if(t)return t;try{const t=new Wp,r=await t.resolve(e,{network:this.networkType});if(!r.content)throw new Error(`Block template not found: ${e}`);let i;return i="string"==typeof r.content?r.content:"object"==typeof r.content&&null!==r.content?r.content.text||JSON.stringify(r.content):r.content.toString(),this.templateCache.set(e,i),i}catch(r){throw this.logger.error("Failed to load block template",{templateTopicId:e,error:r.message}),new Error(`Failed to load block template: ${r.message}`)}}async loadBlock(e){const t=await this.loadBlockDefinition(e);return{definition:t,template:await this.loadBlockTemplate(t.template_t_id)}}async storeBlock(e,t){if(!this.client||!("inscribeFile"in this.client))throw new Error("Client does not support inscription");try{const r=globalThis.Buffer.from(e),i=await this.client.inscribeFile(r,`block-${t.name}-template.html`);if(!i?.topic_id)throw new Error("Failed to inscribe block template");const n={...t,template_t_id:i.topic_id},o=globalThis.Buffer.from(JSON.stringify(n)),s=await this.client.inscribeFile(o,`block-${t.name}-definition.json`);if(!s?.topic_id)throw new Error("Failed to inscribe block definition");return this.blockCache.set(s.topic_id,n),this.templateCache.set(i.topic_id,e),{definitionTopicId:s.topic_id,templateTopicId:i.topic_id}}catch(r){throw this.logger.error("Failed to store block",{error:r.message}),new Error(`Failed to store block: ${r.message}`)}}clearCache(){this.blockCache.clear(),this.templateCache.clear()}}class Lg extends wg{constructor(e,t,r,i){super(e,t,bg.ASSEMBLY,r,i),this.assemblyStates=new Map}getTopicMemo(){return`hcs-12:0:60:${this.registryType}`}async register(e){return this.submitMessage(e)}async createAssemblyTopic(){const e=await this.createRegistryTopic();return this.topicId=e,e}async addAction(e){return this.submitMessage(e)}async addBlock(e){return this.submitMessage(e)}async update(e){return this.submitMessage(e)}async submitMessage(e){if(this.validateMessage(e),!this.topicId)throw new Error("Assembly topic ID not found");if(!this.client)throw new Error("Client not found");this.logger.info("Submitting assembly message to HCS",{topicId:this.topicId,op:e.op});const t=(await this.client.submitMessage(this.topicId,JSON.stringify(e))).sequenceNumber;if(!t)throw new Error("No sequence number returned from submission");const r={id:t.toString(),sequenceNumber:t,timestamp:(new Date).toISOString(),submitter:"getHashConnect"in this.client?(await this.client.getAccountAndSigner()).accountId:this.client.getOperatorAccountId(),data:e};return this.entries.set(r.id,r),await this.processMessage(r),this.logger.info("Assembly message processed",{op:e.op,sequenceNumber:t}),t.toString()}async processMessage(e){const t=e.data;if(!this.topicId)return;let r=this.assemblyStates.get(this.topicId);switch(t.op){case"register":const i=t;r={topicId:this.topicId,name:i.name,version:i.version,description:i.description,tags:i.tags,author:i.author,actions:[],blocks:[],created:e.timestamp,updated:e.timestamp},this.assemblyStates.set(this.topicId,r);break;case"add-action":if(!r)return void this.logger.warn("Cannot add action without assembly registration");const n=t,o={t_id:n.t_id,alias:n.alias,config:n.config,data:n.data};r.actions.push(o),r.updated=e.timestamp;break;case"add-block":if(!r)return void this.logger.warn("Cannot add block without assembly registration");const s=t,a={block_t_id:s.block_t_id,actions:s.actions,attributes:s.attributes,children:s.children,data:s.data};r.blocks.push(a),r.updated=e.timestamp;break;case"update":if(!r)return void this.logger.warn("Cannot update without assembly registration");const c=t;void 0!==c.description&&(r.description=c.description),void 0!==c.tags&&(r.tags=c.tags),r.updated=e.timestamp}}async getAssemblyState(e){const t=e||this.topicId;if(!t||!this.client)return null;let r=this.assemblyStates.get(t);if(r)return r;if(t===this.topicId&&this.entries.size>0){this.logger.debug("Building state from existing entries",{topicId:t,entriesCount:this.entries.size}),this.assemblyStates.clear();for(const r of this.entries.values())this.processAssemblyMessage(t,r);const e=this.assemblyStates.get(t)||null;return this.logger.debug("Built state from entries",{topicId:t,hasState:!!e,name:e?.name}),e}this.logger.info("Syncing assembly state from topic",{topicId:t});try{const e=await this.client.mirrorNode.getTopicMessagesByFilter(t,{order:"asc",limit:1e3}),r=Array.isArray(e)?e:[];this.logger.info("Processing assembly messages",{topicId:t,messageCount:r.length});for(const o of r)try{let e;if(!o.message)continue;try{let t;t="undefined"==typeof window?globalThis.Buffer.from(o.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(o.message),e=>e.charCodeAt(0))),e=JSON.parse(t),this.logger.debug("Successfully parsed message",{sequenceNumber:o.sequence_number,op:e.op,p:e.p})}catch(i){this.logger.debug("Failed to decode/parse message",{sequenceNumber:o.sequence_number,error:i});continue}if("hcs-12"!==e.p){this.logger.debug("Skipping non-HCS-12 message",{sequenceNumber:o.sequence_number,protocol:e.p});continue}const r={id:o.sequence_number.toString(),sequenceNumber:o.sequence_number,timestamp:o.consensus_timestamp||(new Date).toISOString(),submitter:o.payer_account_id||"unknown",data:e};this.processAssemblyMessage(t,r),this.logger.debug("Processed message for assembly",{topicId:t,sequenceNumber:r.sequenceNumber,op:r.data.op})}catch(i){this.logger.warn("Failed to parse assembly message",{sequenceNumber:o.sequence_number,error:i})}const n=this.assemblyStates.get(t)||null;return this.logger.info("Assembly state after sync",{topicId:t,hasState:!!n,name:n?.name,version:n?.version,actionsCount:n?.actions?.length||0,blocksCount:n?.blocks?.length||0}),n}catch(i){return this.logger.error("Failed to sync assembly state",{topicId:t,error:i}),null}}processAssemblyMessage(e,t){const r=t.data;let i=this.assemblyStates.get(e);switch(this.logger.debug("Processing assembly message",{topicId:e,op:r.op,hasState:!!i}),r.op){case"register":const n=r;i={topicId:e,name:n.name,version:n.version,description:n.description,tags:n.tags,author:n.author,actions:[],blocks:[],created:t.timestamp,updated:t.timestamp},this.assemblyStates.set(e,i),this.logger.debug("Assembly registered",{topicId:e,name:n.name,version:n.version});break;case"add-action":if(!i)return void this.logger.warn("Cannot add action without assembly registration");const o=r,s={t_id:o.t_id,alias:o.alias,config:o.config,data:o.data};i.actions.push(s),i.updated=t.timestamp;break;case"add-block":if(!i)return void this.logger.warn("Cannot add block without assembly registration");const a=r,c={block_t_id:a.block_t_id,actions:a.actions,attributes:a.attributes,children:a.children,data:a.data};i.blocks.push(c),i.updated=t.timestamp;break;case"update":if(!i)return void this.logger.warn("Cannot update without assembly registration");const l=r;void 0!==l.description&&(i.description=l.description),void 0!==l.tags&&(i.tags=l.tags),i.updated=t.timestamp}}async sync(){if(this.topicId&&this.client){this.entries.clear(),this.assemblyStates.delete(this.topicId),this.logger.info("Syncing assembly messages",{topicId:this.topicId});try{const t=await this.client.mirrorNode.getTopicMessagesByFilter(this.topicId,{order:"asc",limit:1e3}),r=Array.isArray(t)?t:[];this.logger.info("Processing assembly messages",{topicId:this.topicId,messageCount:r.length});for(const i of r)try{let t;if(i.message)try{let e;e="undefined"==typeof window?globalThis.Buffer.from(i.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(i.message),e=>e.charCodeAt(0))),t=JSON.parse(e)}catch(e){this.logger.debug("Failed to decode/parse message in sync",{sequenceNumber:i.sequence_number,error:e});continue}else if(i.raw_content)try{t=JSON.parse(i.raw_content)}catch{continue}else{const e=i;if(!e.p||!e.op)continue;t={...e},delete t.consensus_timestamp,delete t.sequence_number,delete t.payer_account_id,delete t.topic_id,delete t.running_hash,delete t.running_hash_version,delete t.chunk_info,delete t.created,delete t.payer}if("hcs-12"!==t.p)continue;const r={id:i.sequence_number.toString(),sequenceNumber:i.sequence_number,timestamp:i.consensus_timestamp||(new Date).toISOString(),submitter:i.payer_account_id||"unknown",data:t};this.entries.set(r.id,r),await this.processMessage(r),this.logger.debug("Processed sync message",{sequenceNumber:r.sequenceNumber,op:r.data.op})}catch(e){this.logger.warn("Failed to parse assembly message",{sequenceNumber:i.sequence_number,error:e})}this.logger.info("Assembly sync completed",{topicId:this.topicId,messageCount:r.length})}catch(e){throw this.logger.error("Failed to sync assembly",{error:e}),e}}else this.logger.warn("Cannot sync without topic ID and client")}validateMessage(e){try{Fg(e)}catch(r){if(r instanceof t.ZodError){const e=r.errors.map(e=>`${e.path.join(".")}: ${e.message}`);throw new Error(`Assembly validation failed: ${e.join("; ")}`)}throw r}}}class Kg extends wg{constructor(e,t,r,i){super(e,t,bg.HASHLINKS,r,i)}async register(e){this.validateRegistration(e);const t=`${this.topicId||"local"}_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,r={id:t,sequenceNumber:0,timestamp:(new Date).toISOString(),submitter:this.client&&"getHashConnect"in this.client?"browser":this.client?.getOperatorAccountId()||"local",data:e};if(this.entries.set(t,r),this.client&&this.topicId)try{const i=JSON.stringify(e),n=await this.client.submitMessage(this.topicId,i);return n.sequenceNumber&&(r.sequenceNumber=n.sequenceNumber,r.id=n.sequenceNumber.toString(),this.entries.delete(t),this.entries.set(r.id,r)),this.logger.info("HashLink submitted to HCS",{transactionId:n.transactionId,sequenceNumber:n.sequenceNumber,topicId:this.topicId}),r.id}catch(i){throw this.logger.error("Failed to submit HashLink to HCS",{error:i}),this.entries.delete(t),i}return this.logger.info("HashLink registered in directory",{id:t,name:e.name,assemblyTopicId:e.t_id,tags:e.tags}),t}async searchByTags(e){return(await this.listEntries()).map(e=>e.data).filter(t=>!(!t.tags||0===t.tags.length)&&e.some(e=>t.tags?.includes(e)))}async searchByName(e){const t=await this.listEntries(),r=e.toLowerCase();return t.map(e=>e.data).filter(e=>e.name.toLowerCase().includes(r)||(e.description?.toLowerCase().includes(r)??!1))}async getFeatured(){return(await this.listEntries()).map(e=>e.data).filter(e=>!0===e.featured)}async getByCategory(e){return(await this.listEntries()).map(e=>e.data).filter(t=>t.category===e)}async getCategories(){const e=await this.listEntries(),t=new Set;return e.forEach(e=>{const r=e.data;r.category&&t.add(r.category)}),Array.from(t).sort()}async getAllTags(){const e=await this.listEntries(),t=new Set;return e.forEach(e=>{const r=e.data;r.tags&&r.tags.forEach(e=>t.add(e))}),Array.from(t).sort()}validateRegistration(e){this.validateBaseRegistration(e);const t=Mg(e,Og);if(!t.isValid)throw new Error(`HashLinks validation failed: ${t.errors.join(", ")}`);if(!e.t_id||!e.t_id.match(/^\d+\.\d+\.\d+$/))throw new Error("Valid assembly topic ID (t_id) is required");if(e.tags&&e.tags.length>10)throw new Error("Maximum 10 tags allowed");if(e.name.length>100)throw new Error("Name must be 100 characters or less");if(e.description&&e.description.length>500)throw new Error("Description must be 500 characters or less")}getStats(){const e=super.getStats(),t=Array.from(this.entries.values()),r=new Set,i=new Set;let n=0;return t.forEach(e=>{const t=e.data;t.category&&r.add(t.category),t.tags&&t.tags.forEach(e=>i.add(e)),t.featured&&n++}),{...e,categories:r.size,totalTags:i.size,featuredCount:n}}}class $g{constructor(e,t,r,i){this.cache=new Map,this.logger=e,this.assemblyRegistry=t,this.actionRegistry=r,this.blockLoader=i}async loadAssembly(e){this.logger.debug("Loading assembly",{topicId:e});const t=this.cache.get(e);if(t)return this.logger.debug("Assembly loaded from cache",{topicId:e}),t;try{const t=await this.assemblyRegistry.getAssemblyState(e);if(!t)throw new Error(`Assembly not found: ${e}`);const r={topicId:e,state:t,actions:[],blocks:[]};return this.cache.set(e,r),this.logger.debug("Assembly loaded successfully",{topicId:e,name:t.name,version:t.version,actionsCount:t.actions?.length||0,blocksCount:t.blocks?.length||0}),r}catch(r){throw this.logger.error("Failed to load assembly",{topicId:e,error:r}),new Error(`Failed to load assembly: ${r instanceof Error?r.message:"Unknown error"}`)}}async resolveReferences(e){this.logger.debug("Resolving assembly references",{name:e.name});const t={topicId:e.topicId,state:e,actions:[],blocks:[]};if(e.actions)for(const i of e.actions)try{const e=await this.resolveActionReference(i);t.actions.push({alias:i.alias,t_id:i.t_id,definition:e,config:i.config})}catch(r){this.logger.warn("Failed to resolve action reference",{t_id:i.t_id,alias:i.alias,error:r}),t.actions.push({alias:i.alias,t_id:i.t_id,definition:null,config:i.config,error:r instanceof Error?r.message:"Unknown error"})}if(e.blocks)for(const i of e.blocks)try{const{definition:e,template:r}=await this.resolveBlockReference(i);t.blocks.push({block_t_id:i.block_t_id,definition:e,template:r,attributes:i.attributes,actions:i.actions,children:i.children})}catch(r){this.logger.warn("Failed to resolve block reference",{block_t_id:i.block_t_id,error:r}),t.blocks.push({block_t_id:i.block_t_id,definition:null,attributes:i.attributes,actions:i.actions,children:i.children,error:r instanceof Error?r.message:"Unknown error"})}return t}validateComposition(e){const t=[];if(this.logger.debug("Validating assembly composition",{topicId:e.topicId}),e.state.name||t.push("Assembly must have a name"),e.state.version||t.push("Assembly must have a version"),e.state.blocks)for(const r of e.state.blocks){if(r.actions)for(const[i,n]of Object.entries(r.actions)){const o=e.state.actions?.some(e=>e.t_id===n);o||t.push(`Block ${r.block_t_id} references non-existent action: ${n} for key ${i}`)}if(r.children)for(const i of r.children){const n=e.state.blocks?.some(e=>e.block_t_id===i);n||t.push(`Block ${r.block_t_id} references non-existent child block: ${i}`)}}for(const r of e.actions)r.error&&t.push(`Action ${r.alias} has resolution error: ${r.error}`);for(const r of e.blocks)r.error&&t.push(`Block ${r.block_t_id} has resolution error: ${r.error}`);return{valid:0===t.length,errors:t}}async loadAndResolveAssembly(e){this.logger.debug("Loading and resolving assembly",{topicId:e});try{const t=await this.loadAssembly(e),r=await this.resolveReferences(t.state),i=this.validateComposition(r);return i.valid||this.logger.warn("Assembly validation failed",{topicId:e,errors:i.errors}),r}catch(t){throw this.logger.error("Failed to load and resolve assembly",{topicId:e,error:t}),new Error(`Failed to load and resolve assembly: ${t instanceof Error?t.message:"Unknown error"}`)}}async resolveActionReference(e){const t=await this.actionRegistry.getActionByTopicId(e.t_id);if(!t)throw new Error(`Action not found at topic: ${e.t_id}`);return t}async resolveBlockReference(e){return await this.blockLoader.loadBlock(e.block_t_id)}clearCache(){this.cache.clear(),this.logger.debug("Assembly cache cleared")}getCachedAssembly(e){return this.cache.get(e)}isAssemblyCached(e){return this.cache.has(e)}}class Hg{constructor(e){this.network=e.network,this.logger=e.logger||y.getInstance({level:e.logLevel||"info",module:"HCS12-BaseClient",prettyPrint:e.prettyPrint,silent:e.silent}),this.mirrorNode=new x(e.network,this.logger,e.mirrorNode)}initializeRegistries(e){this.actionRegistryTopicId=e?.action,this._assemblyRegistryTopicId=e?.assembly,this._hashLinksRegistryTopicId=e?.hashlinks}async registerAssembly(e){if(!this._assemblyRegistry)throw new Error("Assembly registry not initialized");return{id:await this._assemblyRegistry.register(e)}}async getAction(e){if(!this._actionRegistry)throw new Error("Action registry not initialized");return this._actionRegistry.getAction(e)}async loadBlock(e){return this._blockLoader||(this._blockLoader=new Bg(this.network,this.logger,this)),this._blockLoader.loadBlock(e)}async getAssembly(e,t){if(!this._assemblyRegistry)throw new Error("Assembly registry not initialized");const r=await this._assemblyRegistry.listEntries();for(const i of r){const r=await this._assemblyRegistry.getAssemblyState(i.id);if(r&&r.name===e&&r.version===t)return r}return null}async loadAssembly(e){this._actionRegistry&&(this.logger.info("Syncing action registry before loading assembly"),await this._actionRegistry.sync());const t=new Lg(this.network,this.logger,e,this);await t.sync();return new $g(this.logger,t,this._actionRegistry,this._blockLoader).loadAndResolveAssembly(e)}async getAssemblyState(e){if(!this._assemblyRegistry)throw new Error("Assembly registry not initialized");return this._assemblyRegistry.getAssemblyState(e)}ensureAssemblyEngine(){if(!this._assemblyEngine){if(!this._actionRegistry||!this._blockLoader||!this._assemblyRegistry)throw new Error("Registries must be initialized before assembly engine");this._assemblyEngine=new $g(this.logger,this._assemblyRegistry,this._actionRegistry,this._blockLoader)}}async registerHashLink(e){if(!this._hashLinksRegistry)throw new Error("HashLinks registry not initialized");return{id:await this._hashLinksRegistry.register(e)}}async searchHashLinksByTags(e){if(!this._hashLinksRegistry)throw new Error("HashLinks registry not initialized");return this._hashLinksRegistry.searchByTags(e)}async searchHashLinksByName(e){if(!this._hashLinksRegistry)throw new Error("HashLinks registry not initialized");return this._hashLinksRegistry.searchByName(e)}async getFeaturedHashLinks(){if(!this._hashLinksRegistry)throw new Error("HashLinks registry not initialized");return this._hashLinksRegistry.getFeatured()}async getHashLinksByCategory(e){if(!this._hashLinksRegistry)throw new Error("HashLinks registry not initialized");return this._hashLinksRegistry.getByCategory(e)}async syncRegistries(){const e=[];this._actionRegistry&&e.push(this._actionRegistry.sync()),this._assemblyRegistry&&e.push(this._assemblyRegistry.sync()),this._hashLinksRegistry&&e.push(this._hashLinksRegistry.sync()),await Promise.all(e)}getRegistryTopicIds(){return{action:this.actionRegistryTopicId,assembly:this._assemblyRegistryTopicId,hashlinks:this._hashLinksRegistryTopicId}}clearCaches(){this._actionRegistry?.clearCache(),this._blockLoader?.clearCache(),this._assemblyRegistry?.clearCache(),this._hashLinksRegistry?.clearCache()}get actionRegistry(){return this._actionRegistry}get blockLoader(){return this._blockLoader}get assemblyRegistry(){return this._assemblyRegistry}get hashLinksRegistry(){return this._hashLinksRegistry}}class qg{constructor(){this.block={apiVersion:3},this.attributes={},this.supports={},this.actions={},this.logger=new y({module:"BlockBuilder"})}setName(e){return this.block.name=e,this}setTitle(e){return this.block.title=e,this}setDescription(e){return this.block.description=e,this}setCategory(e){return this.block.category=e,this}setIcon(e){return this.block.icon=e,this}setKeywords(e){return this.block.keywords=e,this}setApiVersion(e){return this.block.apiVersion=e,this}addAttribute(e,t,r,i){const n={type:t,default:r};return i?.enum&&(n.enum=i.enum),i?.source&&(n.source=i.source),i?.selector&&(n.selector=i.selector),i?.attribute&&(n.attribute=i.attribute),this.attributes[e]=n,this}setTemplateTopicId(e){return this.block.template_t_id=e,this}setTemplate(e){return this.templateBuffer=e,this}setActions(e){return this.actions=e,this}addAction(e,t){return this.actions[e]=t,this}addSupport(e,t=!0){return this.supports[e]=t,this}enableCommonSupports(){return this.supports={...this.supports,align:!0,anchor:!0,className:!0,spacing:{margin:!0,padding:!0}},this}build(){if(!this.block.name)throw new Error("Block name is required");if(!this.block.title)throw new Error("Block title is required");if(!this.block.category)throw new Error("Block category is required");if(!this.block.template_t_id)throw new Error("Block template_t_id is required");return{apiVersion:this.block.apiVersion||3,name:this.block.name,title:this.block.title,category:this.block.category,template_t_id:this.block.template_t_id,icon:this.block.icon,description:this.block.description,keywords:this.block.keywords,attributes:this.attributes,supports:this.supports}}static createDisplayBlock(e,t){return(new qg).setName(e).setTitle(t).setCategory("formatting").enableCommonSupports()}static createInteractiveBlock(e,t){return(new qg).setName(e).setTitle(t).setCategory("widgets").enableCommonSupports()}static createWidgetBlock(e,t){return this.createInteractiveBlock(e,t)}static createContainerBlock(e,t){return(new qg).setName(e).setTitle(t).setCategory("design").enableCommonSupports().addSupport("html",!1)}getTemplate(){return this.templateBuffer}getActions(){return this.actions}setTopicId(e){return this.blockTopicId=e,this}getTopicId(){if(!this.blockTopicId)throw new Error("Block topic ID not set");return this.blockTopicId}getName(){return this.block.name}}class jg{constructor(e,t){this.wasmCache=new Map,this.logger=e,this.network=t,this.hrlResolver=new Wp}async execute(e,t){try{if(this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Executing WASM action",{actionId:e.t_id,method:t.method,hasJavaScript:!!e.js_t_id}),e.js_t_id)return await this.executeJavaScript(e,t);throw new Error("Raw WASM execution is not supported for wasm-bindgen modules. JavaScript wrapper is required.")}catch(r){return this.logger&&"function"==typeof this.logger.error?this.logger.error("WASM execution failed",{actionId:e.t_id,error:r.message}):console.error("WASM execution failed",{actionId:e.t_id,error:r.message}),{success:!1,error:r.message}}}readWasmString(e,t){const r=new Uint8Array(e.buffer);let i=0;for(;0!==r[t+i];)i++;return(new TextDecoder).decode(r.slice(t,t+i))}async executeJavaScript(e,t){try{if(this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Loading JavaScript wrapper",{jsTopicId:e.js_t_id}),"undefined"==typeof window){this.logger&&"function"==typeof this.logger.info&&this.logger.info("Executing JavaScript wrapper in Node.js environment");const t=await this.hrlResolver.resolve(e.js_t_id,{network:this.network,returnRaw:!1});if(!t.content||"string"!=typeof t.content)throw new Error("Failed to load JavaScript module: invalid content");await this.hrlResolver.resolve(e.t_id,{network:this.network,returnRaw:!0}),global,globalThis,WebAssembly,console,queueMicrotask,TextDecoder,TextEncoder,void 0!==globalThis.FinalizationRegistry&&globalThis.FinalizationRegistry,URL;throw new Error("WASM execution in Node.js/SSR environment is not supported. This functionality is browser-only.")}{const r=await this.hrlResolver.resolve(e.js_t_id,{network:this.network,returnRaw:!1});if(!r.content||"string"!=typeof r.content)throw new Error("Failed to load JavaScript module: invalid content");const i=new Blob([r.content],{type:"application/javascript"}),n=URL.createObjectURL(i);try{this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Importing JavaScript module from blob URL");const r=new Function("url","return import(url)"),i=await r(n);if(this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Module imported, exports:",Object.keys(i)),!i.default&&!i.init)throw new Error("No init function found in JavaScript module");{const t=i.default||i.init;this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Loading WASM bytes from topic:",e.t_id);const r=await this.hrlResolver.resolve(e.t_id,{network:this.network,returnRaw:!0});if(this.logger&&"function"==typeof this.logger.debug){const e=r.content instanceof ArrayBuffer?r.content.byteLength:r.content.length;this.logger.debug("WASM bytes loaded, size:",e)}await t({module_or_path:r.content}),this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("WASM module initialized successfully")}const o=i.WasmInterface;if(!o)throw new Error("WasmInterface not found in module exports. Available exports: "+Object.keys(i).join(", "));this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Creating WasmInterface instance");const s=new o;let a,c;if("POST"===t.method&&s.POST){const e=t.params.operation||"default",r={...t.params,...t.state},i=JSON.stringify(r);this.logger&&"function"==typeof this.logger.debug?this.logger.debug("Calling POST method",{actionName:e,paramsJson:i,allParams:r}):console.log("WASM POST params:",{actionName:e,paramsJson:i,allParams:r}),a=await s.POST(e,i,this.network.toString(),"")}else if("GET"===t.method&&s.GET){const e=t.params.operation||"default",r=JSON.stringify(t.params);this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Calling GET method",{actionName:e,paramsJson:r}),a=await s.GET(e,r,this.network.toString())}else{if("INFO"!==t.method||!s.INFO)throw new Error(`Method ${t.method} not supported by WASM module`);this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Calling INFO method"),a=s.INFO()}try{c=JSON.parse(a)}catch{c={value:a}}return s.free&&s.free(),URL.revokeObjectURL(n),{success:!0,data:c}}catch(zw){throw URL.revokeObjectURL(n),zw}}}catch(r){const t=r instanceof Error?r.message:String(r),i=r instanceof Error?r.stack:void 0;return this.logger&&"function"==typeof this.logger.error?this.logger.error("JavaScript execution failed",{jsTopicId:e.js_t_id,error:t,stack:i,fullError:r}):console.error("JavaScript execution failed",{jsTopicId:e.js_t_id,error:t,stack:i,fullError:r}),{success:!1,error:t||"Unknown error"}}}clearCache(){this.wasmCache.clear()}}class Wg{constructor(e){this.logger=e}async scanTemplate(e){const t=[],r=/<([^>]+)\s+data-hashlink=["']([^"']+)["']([^>]*)>/gs;let i;for(;null!==(i=r.exec(e));){const e=i[0],r=i[1].split(/\s+/)[0],o=i[2],s=i[3];try{const i=this.parseHashLinkURI(o),n=s.match(/data-attributes=(['"])((?:(?!\1).)*)\1/s);let a;if(n)try{const e=n[2];a=JSON.parse(e)}catch(zw){this.logger.warn("Failed to parse data-attributes",{uri:o,attributes:n[2],error:zw.message})}const c=s.match(/data-actions=(['"])((?:(?!\1).)*)\1/s);let l;if(c)try{const e=c[2];l=JSON.parse(e)}catch(zw){this.logger.warn("Failed to parse data-actions",{uri:o,actions:c[2],error:zw.message})}const u=s.match(/data-loading=['"]([^'"]+)['"]/),d=u?.[1]||"eager";t.push({element:r,uri:o,...i,attributes:a,actions:l,loading:d,placeholder:e}),this.logger.debug("Found HashLink reference",{uri:o,parsed:i})}catch(n){this.logger.error("Failed to parse HashLink URI",{uri:o,error:n.message})}}return t}parseHashLinkURI(e){const t=e.match(/^hcs:\/\/(\d+)\/(.+)$/);if(!t)throw new Error(`Invalid HashLink URI format: ${e}`);const r=t[1],i=t[2];if("2"===r){const e=i.split("/");if(2!==e.length)throw new Error(`Invalid HCS-2 reference format: ${i}`);return{protocol:r,reference:i,registryId:e[0],entryName:e[1]}}return{protocol:r,reference:i}}createPlaceholder(e,t){return`\x3c!-- HASHLINK_PLACEHOLDER_${t}_${e.uri.replace(/[^a-zA-Z0-9]/g,"_")} --\x3e`}}class Vg{constructor(e,t,r,i){this.logger=e,this.blockLoader=t,this.hrlResolver=r,this.network=i,this.cache=new Map,this.renderStack=new Set}async resolveReference(e,t){this.logger.debug("Resolving HashLink reference",{uri:e.uri,protocol:e.protocol});try{switch(e.protocol){case"12":return await this.resolveHCS12Block(e,t);case"1":return await this.resolveHCS1Block(e,t);case"2":return await this.resolveHCS2Block(e,t);default:throw new Error(`Unsupported HashLink protocol: ${e.protocol}`)}}catch(r){return this.logger.error("Failed to resolve HashLink",{uri:e.uri,error:r.message}),{blockId:e.reference,definition:null,template:null,attributes:{},actions:{},error:r.message}}}async resolveHCS12Block(e,t){const r=e.reference;if(this.renderStack.has(r))return{blockId:r,definition:null,template:null,attributes:{},actions:{},error:"Circular reference detected"};const i=this.getCacheKey(r,e.attributes,e.actions);if(this.cache.has(i))return this.cache.get(i);try{const n=await this.blockLoader.loadBlock(r);if(!n||!n.definition)throw new Error(`Block not found: ${r}`);const o={...this.extractDefaults(n.definition),...t.attributes,...e.attributes},s={...t.actions,...e.actions},a={blockId:r,definition:n.definition,template:n.template,attributes:o,actions:s};return this.cache.set(i,a),a}catch(n){throw this.renderStack.delete(r),new Error(`Failed to load HCS-12 block ${r}: ${n.message}`)}}async resolveHCS1Block(e,t){const r=e.reference;try{const t=await this.blockLoader.loadBlock(r);if(t&&t.definition)return{blockId:r,definition:t.definition,template:t.template,attributes:{...this.extractDefaults(t.definition),...e.attributes},actions:e.actions||{}};return{blockId:r,definition:null,template:(await this.hrlResolver.resolve(r,{network:this.network})).content,attributes:e.attributes||{},actions:e.actions||{}}}catch(i){throw new Error(`Failed to load HCS-1 content ${r}: ${i.message}`)}}async resolveHCS2Block(e,t){if(!e.registryId||!e.entryName)throw new Error("Invalid HCS-2 reference: missing registry ID or entry name");try{const t=`hcs://2/${e.registryId}`;await this.hrlResolver.resolve(t,{network:this.network});return this.logger.warn("HCS-2 registry lookup not fully implemented",{registryId:e.registryId,entryName:e.entryName}),{blockId:`${e.registryId}/${e.entryName}`,definition:null,template:`\x3c!-- HCS-2 lookup not implemented: ${e.uri} --\x3e`,attributes:e.attributes||{},actions:e.actions||{}}}catch(r){throw new Error(`Failed to resolve HCS-2 entry: ${r.message}`)}}extractDefaults(e){const t={};return e.attributes&&Object.entries(e.attributes).forEach(([e,r])=>{r&&"object"==typeof r&&"default"in r&&(t[e]=r.default)}),t}getCacheKey(e,t,r){return`${e}:${t?JSON.stringify(t):""}:${r?JSON.stringify(r):""}`}pushRenderStack(e){this.renderStack.add(e)}popRenderStack(e){this.renderStack.delete(e)}clearCache(){this.cache.clear()}}const Gg={ACTIONS:{CALCULATOR:"0.0.TBD1",NFT_MINT:"0.0.TBD2",TOKEN_TRANSFER:"0.0.TBD3"},BLOCKS:{BUTTON:"0.0.TBD4",NFT_GALLERY:"0.0.TBD5",FORM:"0.0.TBD6"},ASSEMBLIES:{NFT_MARKETPLACE:"0.0.TBD7",TOKEN_DASHBOARD:"0.0.TBD8"}},Jg={ACTIONS:{},BLOCKS:{},ASSEMBLIES:{}};const Yg=/^[a-z0-9][a-z0-9-]*$/,Xg=t.z.object({registry:t.z.string().min(1),name:t.z.string().min(1),version:t.z.string().min(1),protocol:t.z.string().min(1),nativeId:t.z.string().min(1),skills:t.z.array(t.z.number().int().nonnegative())});function Zg(e){return e.trim()}function Qg(e){return e.trim().toLowerCase()}function em(e){const t=Xg.parse(e);if("hcs-10"===t.protocol.trim().toLowerCase()&&!lh(t.nativeId.trim()))throw new Error("HCS-14: For protocol hcs-10, nativeId must be CAIP-10 (hedera:<network>:<account>)");if("acp-virtuals"===t.protocol.trim().toLowerCase()&&!hh(t.nativeId.trim()))throw new Error("HCS-14: For protocol acp-virtuals, nativeId must be EIP-155 CAIP-10 (eip155:<chainId>:<address>)");const r={registry:Qg(t.registry),name:Zg(t.name),version:Zg(t.version),protocol:Qg(t.protocol),nativeId:Zg(t.nativeId),skills:[...t.skills].sort((e,t)=>e-t)},i=["skills","name","nativeId","protocol","registry","version"],n={};for(const o of i)n[o]=r[o];return{normalized:r,canonicalJson:JSON.stringify(n)}}const tm="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function rm(e){if(0===e.length)return"";let t=0;for(;t<e.length&&0===e[t];)t++;if(t===e.length)return"1".repeat(t);const r=[0];for(let n=t;n<e.length;n++){let t=e[n];for(let e=0;e<r.length;e++){const i=(r[e]<<8)+t;r[e]=i%58,t=i/58|0}for(;t>0;)r.push(t%58),t=t/58|0}let i="";for(let n=0;n<t;n++)i+="1";for(let n=r.length-1;n>=0;n--)i+=tm[r[n]];return i}function im(e){if(!e.startsWith("z"))throw new Error("Invalid multibase base58btc");return function(e){if(0===e.length)return new Uint8Array(0);let t=0;for(;t<e.length&&"1"===e[t];)t++;const r=[];for(let i=t;i<e.length;i++){const t=e[i],n=tm.indexOf(t);if(-1===n)throw new Error("Invalid Base58 character");let o=n;for(let e=0;e<r.length;e++){const t=58*r[e]+o;r[e]=255&t,o=t>>8}for(;o>0;)r.push(255&o),o>>=8}for(let i=0;i<t;i++)r.push(0);return r.reverse(),Uint8Array.from(r)}(e.slice(1))}function nm(e){const t=[];return e.uid&&t.push(["uid",e.uid]),e.registry&&t.push(["registry",e.registry]),e.proto&&t.push(["proto",e.proto]),e.nativeId&&t.push(["nativeId",e.nativeId]),e.domain&&t.push(["domain",e.domain]),e.src&&t.push(["src",e.src]),0===t.length?"":t.map(([e,t])=>`${e}=${t}`).join(";")}function om(e,t){let r,i;if(e.startsWith("uaid:aid:"))r="aid",i=e.slice(9);else{if(!e.startsWith("did:"))throw new Error("Invalid DID format");{const t=e.indexOf(":"),n=e.indexOf(":",t+1);if(n<0)throw new Error("Invalid DID format");r=e.slice(t+1,n),i=e.slice(n+1)}}const{sanitized:n,hadSuffix:o}=function(e){const t=e.search(/[;?#]/);return-1===t?{sanitized:e,hadSuffix:!1}:{sanitized:e.slice(0,t),hadSuffix:!0}}(i);let s=n;if("hedera"===r){const e=n.match(/^(mainnet|testnet|previewnet|devnet):(.+)$/);e&&(s=e[2])}const a={...t||{}};var c;o&&!a.src&&(a.src=(c=e,"z"+rm(globalThis.Buffer.from(c,"utf8"))));const l=nm(a);return l?`uaid:did:${s};${l}`:`uaid:did:${s}`}function sm(e,t,r){return"string"==typeof e?om(e,t):async function(e,t,r){const{normalized:i,canonicalJson:n}=em(e),o=nh().createHash("sha384").update(globalThis.Buffer.from(n,"utf8")).digest(),s=await Promise.resolve(o),a=rm(globalThis.Buffer.isBuffer(s)?s:globalThis.Buffer.from(s)),c=!1!==r?.includeParams,l=c?function(e,t){const r={...t};return r.registry||(r.registry=e.registry),r.nativeId||(r.nativeId=e.nativeId),r.uid||(r.uid="0"),r}(i,t||{}):{},u=c?nm(l):"";return u?`uaid:aid:${a};${u}`:`uaid:aid:${a}`}(e,t,r)}function am(e){if(e.startsWith("uaid:")){const t=e.slice(5);let r,i;if(t.startsWith("did:"))r="did",i=t.slice(4);else{if(!t.startsWith("aid:"))throw new Error("Invalid UAID");r="aid",i=t.slice(4)}const n=i.indexOf(";"),o=n>=0?i.slice(0,n):i,s=(e=>{const t={};if(!e)return t;const r=e.split(";");for(const i of r){const e=i.indexOf("=");if(e>0){const r=i.slice(0,e),n=i.slice(e+1);t[r]=n}}return t})(n>=0?i.slice(n+1):"");return{method:"did"===r?"uaid":"aid",id:o,params:s}}throw new Error("Invalid DID")}function cm(e){return"object"==typeof e&&null!==e}function lm(e){if(!cm(e))return;const t=e.adapterKind;return"did-resolver"===t||"did-profile-resolver"===t||"uaid-profile-resolver"===t?t:void 0}function um(e){return cm(e)&&"profile"in e&&"string"==typeof e.profile}function dm(e){const t=lm(e);return void 0!==t?"uaid-profile-resolver"===t:um(e)&&cm(e)&&"resolveProfile"in e&&"function"==typeof e.resolveProfile&&function(e){return!!cm(e)&&"supports"in e&&"function"==typeof e.supports}(e)}function pm(e){const t=lm(e);return void 0!==t?"did-profile-resolver"===t:cm(e)&&"resolveProfile"in e&&"function"==typeof e.resolveProfile&&!um(e)}function hm(e){const t=lm(e);return void 0!==t?"did-resolver"===t:cm(e)&&"resolve"in e&&"function"==typeof e.resolve}const gm=["@hiero-did-sdk","resolver"].join("/");let mm=null;class fm{constructor(){this.adapterKind="did-resolver",this.meta={id:"hedera/hiero-resolver",didMethods:["hedera"],caip2Networks:["hedera:mainnet","hedera:testnet","hedera:previewnet","hedera:devnet"],caip10Namespaces:["hedera"],displayName:"Hedera (Hiero Resolver)",description:"Resolves did:hedera identifiers via Hiero DID resolver.",homepage:"https://github.com/hiero-ledger/hiero-did-sdk-js"}}supports(e){return e.startsWith("did:hedera:")}async resolve(e){const t=await async function(){return mm||(mm=Ta(gm).then(e=>e?.resolveDID??null)),mm}();if(!t)throw new Error("Hiero resolver unavailable. Ensure @hiero-did-sdk/resolver is installed.");const r=await t(e);return r&&"string"==typeof r.id?{id:r.id}:null}}class ym{constructor(){this.resolvers=[],this.profileResolvers=[],this.uaidProfileResolvers=[],this.adapters=[]}supportsDidMethod(e,t){return!!e&&(e.includes(t)||e.includes("*"))}addDidResolver(e){this.resolvers.push(e),this.adapters.push({capability:"did-resolver",adapter:e})}addDidProfileResolver(e){this.profileResolvers.push(e),this.adapters.push({capability:"did-profile-resolver",adapter:e})}addUaidProfileResolver(e){this.uaidProfileResolvers.push(e),this.adapters.push({capability:"uaid-profile-resolver",adapter:e})}registerAdapter(e){const t=dm(e),r=pm(e),i=hm(e);if([t,r,i].filter(Boolean).length>1)throw new Error("Adapter matches multiple resolver capabilities. Split it into single-capability adapters, or use register/registerProfileResolver/registerUaidProfileResolver to explicitly select one capability.");if(t)this.addUaidProfileResolver(e);else if(r)this.addDidProfileResolver(e);else{if(!i)throw new Error("Adapter does not match a supported resolver capability.");this.addDidResolver(e)}}listAdapters(){return[...this.adapters]}filterAdapters(e={}){if(void 0!==e.profileId&&void 0!==e.capability&&"uaid-profile-resolver"!==e.capability)throw new Error('profileId filter requires capability "uaid-profile-resolver".');const t=e.capability??(void 0!==e.profileId?"uaid-profile-resolver":void 0);return this.adapters.filter(r=>{if(void 0!==t&&r.capability!==t)return!1;if(void 0!==e.didMethod&&!this.supportsDidMethod(r.adapter.meta?.didMethods,e.didMethod))return!1;if(void 0!==e.profileId){if("uaid-profile-resolver"!==r.capability)return!1;if(r.adapter.profile!==e.profileId)return!1}return!0})}register(e){this.addDidResolver(e)}registerProfileResolver(e){this.addDidProfileResolver(e)}registerUaidProfileResolver(e){this.addUaidProfileResolver(e)}list(){return[...this.resolvers]}listProfileResolvers(){return[...this.profileResolvers]}listUaidProfileResolvers(){return[...this.uaidProfileResolvers]}filterByDidMethod(e){return this.resolvers.filter(t=>this.supportsDidMethod(t.meta?.didMethods,e))}filterProfileResolversByDidMethod(e){return this.profileResolvers.filter(t=>this.supportsDidMethod(t.meta?.didMethods,e))}filterUaidProfileResolversByDidMethod(e){return this.uaidProfileResolvers.filter(t=>this.supportsDidMethod(t.meta?.didMethods,e))}filterUaidProfileResolversByProfileId(e){return this.uaidProfileResolvers.filter(t=>t.profile===e)}async resolveDid(e){for(const t of this.resolvers)if(t.supports(e))return t.resolve(e);return null}deriveDidFromParsedUaid(e){if("aid"===e.method){const t=e.params.proto,r=e.params.nativeId;if("hcs-10"===t&&r){const e=r.match(/^hedera:(mainnet|testnet|previewnet|devnet):(.+)$/);if(e){return`did:hedera:${e[1]}:${e[2]}`}}return null}const t=e.params.src;if(t)try{return globalThis.Buffer.from(im(t)).toString("utf8")}catch{return null}const r=e.id;if(r.startsWith("testnet:")||r.startsWith("mainnet:")||r.startsWith("previewnet:")||r.startsWith("devnet:"))return`did:hedera:${r}`;const i=e.params.proto,n=e.params.nativeId;if("hcs-10"===i&&n){const e=n.match(/^hedera:(mainnet|testnet|previewnet|devnet):/);if(e){return`did:hedera:${e[1]}:${r}`}}return null}buildFallbackProfile(e,t={}){const r=t.uaid??e,i=t.didDocument??null,n=new Set;r!==e&&n.add(e);for(const o of i?.alsoKnownAs??[])n.add(o);return{id:r,did:e,verificationMethod:i?.verificationMethod,authentication:i?.authentication,assertionMethod:i?.assertionMethod,service:i?.service,alsoKnownAs:n.size>0?[...n]:void 0}}mergeResolvedProfile(e,t){const r=new Set([...e.alsoKnownAs??[],...t.alsoKnownAs??[]]);return{...e,...t,id:t.id||e.id,did:t.did??e.did,verificationMethod:t.verificationMethod??e.verificationMethod,authentication:t.authentication??e.authentication,assertionMethod:t.assertionMethod??e.assertionMethod,service:t.service??e.service,profiles:t.profiles??e.profiles,metadata:t.metadata??e.metadata,error:t.error??e.error,alsoKnownAs:r.size>0?[...r]:void 0}}async resolveDidProfile(e,t={}){const r=t.didDocument??await this.resolveDid(e),i={...t,didDocument:r},n=this.buildFallbackProfile(e,i);for(const o of this.profileResolvers){if(!o.supports(e))continue;const t=await o.resolveProfile(e,i);if(t)return this.mergeResolvedProfile(n,t)}return n}async resolveUaidProfileByIdInternal(e,t,r){const i=am(t);return this.resolveUaidProfileInternal(t,i,{profileId:e,excludeProfileId:r.excludeProfileId})}async resolveUaidProfileInternal(e,t,r={}){const i=this.deriveDidFromParsedUaid(t),n=i?await this.resolveDid(i):null,o=i?this.buildFallbackProfile(i,{uaid:e,parsedUaid:t,didDocument:n}):{id:e},s=void 0!==r.profileId?this.uaidProfileResolvers.filter(e=>e.profile===r.profileId):this.uaidProfileResolvers;for(const a of s){if(void 0!==r.excludeProfileId&&a.profile===r.excludeProfileId)continue;const s=a.supports(e,t);if(void 0===r.profileId&&!s)continue;const c={parsedUaid:t,did:i,didDocument:n,resolveDid:async e=>this.resolveDid(e),resolveDidProfile:async(e,t)=>this.resolveDidProfile(e,t),resolveUaidProfileById:async(e,t)=>this.resolveUaidProfileByIdInternal(e,t,{excludeProfileId:a.profile})},l=await a.resolveProfile(e,c);if(!l)continue;if(void 0!==l.error||!1===l.metadata?.resolved){if(void 0===r.profileId)continue;return l}return this.mergeResolvedProfile(o,l)}return null}async resolveUaid(e){const t=am(e),r=this.deriveDidFromParsedUaid(t);return r?this.resolveDid(r):null}async resolveUaidProfile(e,t={}){const r=am(e),i=await this.resolveUaidProfileInternal(e,r,{profileId:t.profileId});if(i)return i;if(void 0!==t.profileId)return null;const n=this.deriveDidFromParsedUaid(r);if(!n)return"aid"===r.method?{id:e}:null;const o=await this.resolveDid(n);return this.resolveDidProfile(n,{uaid:e,parsedUaid:r,didDocument:o})}}const bm=new ym;function wm(){bm.registerAdapter(new fm)}function Im(e){return"mainnet"===e||"testnet"===e?e:null}function Tm(e,t){const r=t?.parsedUaid?.params.nativeId;if(r){const e=function(e){try{const t=dh(e),r=Im(t.network);return r?{network:r,accountId:t.accountId}:null}catch(t){return null}}(r);if(e)return e}const i=e.match(/^did:hedera:(mainnet|testnet):(.+)$/);if(!i)return null;const n=Im(i[1]);return n?{network:n,accountId:i[2]}:null}class Sm{constructor(){this.adapterKind="did-profile-resolver",this.meta={id:"hedera/hcs11-profile-resolver",didMethods:["hedera"],caip2Networks:["hedera:mainnet","hedera:testnet"],caip10Namespaces:["hedera"],displayName:"Hedera (HCS-11 Profile Resolver)",description:"Resolves HCS-11 protocol profiles and HCS-10 service metadata for did:hedera identifiers."}}supports(e){return/^did:hedera:(mainnet|testnet):/.test(e)}async resolveProfile(e,t){const r=Tm(e,t);if(!r)return null;const{network:i,accountId:n}=r,o=new Lh({network:i,auth:{operatorId:n},silent:!0}),s=await o.fetchProfileByAccountId(n,i);if(!s.success||!s.profile)return null;const a=t?.uaid??e,c=t?.didDocument?.service??[],l=function(e,t,r,i){return i?{id:`${e}#hcs10`,type:"HCS10Service",serviceEndpoint:{network:t,accountId:r,inboundTopicId:i.inboundTopic||void 0,outboundTopicId:i.outboundTopic||void 0,profileTopicId:i.profileTopicId||void 0}}:null}(a,i,n,s.topicInfo),u=l?[...c,l]:c;return{id:a,did:e,service:u.length>0?u:void 0,profiles:{hcs11:{protocol:"hcs-11",network:i,accountId:n,profile:s.profile,topicInfo:s.topicInfo}}}}}let km=null;const vm=async e=>{const t=await async function(){return km||(km=(async()=>{const e=await Ta("node:dns/promises",{preferImport:!0});if(e?.resolveTxt)return e.resolveTxt;const t=await Ta("dns/promises",{preferImport:!0});return t?.resolveTxt??null})()),km}();if(!t)return[];try{return(await t(e)).map(e=>e.join(""))}catch(r){if(function(e){if(!e||"object"!=typeof e)return!1;const t=Reflect.get(e,"code");return"string"==typeof t&&("ENOTFOUND"===t||"ENODATA"===t||"ENOENT"===t||"ENONAME"===t||"NXDOMAIN"===t)}(r))return[];throw r}},Em=["uid","registry","proto","nativeId","domain","src"],Am=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i;function Cm(e){return"aid"===e.method?"aid":"did"}function Rm(e){return e.trim().replace(/\.$/,"").toLowerCase()}function xm(e){const t=Rm(e);if(!t||t.length>253||!t.includes("."))return!1;const r=t.split(".");for(const i of r)if(!i||i.length>63||!Am.test(i))return!1;return!0}function Nm(e){const t=e.trim();if(t.length>=2&&t.startsWith('"')&&t.endsWith('"'))return t.slice(1,-1);const r=t.match(/^\[(.+)\]\((.+)\)$/);return r?r[2].trim():t}function zm(e){const t={};for(const r of e.split(";")){const e=r.trim();if(!e)continue;const i=e.indexOf("=");if(i<=0)continue;const n=e.slice(0,i).trim(),o=Nm(e.slice(i+1));n&&o&&(t[n]=o)}return t}function _m(e,t,r){const i=[],n=new Set;for(const s of Em){const e=r[s];e&&(i.push(`${s}=${e}`),n.add(s))}const o=Object.keys(r).filter(e=>!n.has(e)&&r[e]).sort((e,t)=>e.localeCompare(t));for(const s of o)i.push(`${s}=${r[s]}`);return i.length>0?`uaid:${e}:${t};${i.join(";")}`:`uaid:${e}:${t}`}const Pm="hcs-14.profile.aid-dns-web";function Om(e,t,r,i){return{id:e,error:{code:t,message:r,details:i},metadata:{profile:Pm,resolved:!1}}}function Dm(e){return`${e.protocol}|${e.endpoint}|${e.publicKey??""}|${e.keyId??""}`}function Fm(e){return"cryptographic"===e?"aid-pka":"metadata"===e?"metadata-match":void 0}class Mm{constructor(e={}){this.adapterKind="uaid-profile-resolver",this.profile=Pm,this.meta={id:"hcs-14/aid-dns-web",didMethods:["*"],displayName:"HCS-14 AID DNS/Web Profile",description:"Resolves uaid:aid identifiers via _agent.<nativeId> DNS TXT records and protocol endpoint hints."},this.dnsLookup=e.dnsLookup??vm,this.supportedSchemes=new Set((e.supportedUriSchemes??["https","http","wss","ws"]).map(e=>e.toLowerCase())),this.metadataVerifier=e.metadataVerifier,this.cryptographicVerifier=e.cryptographicVerifier}supports(e,t){if("aid"!==t.method)return!1;const r=t.params.nativeId;return!!r&&xm(r)}async resolveProfile(e,t){const r=t.parsedUaid;if("aid"!==r.method)return Om(e,"ERR_NOT_APPLICABLE","AID DNS/Web profile only applies to uaid:aid identifiers.");const i=r.params.nativeId;if(!i||!xm(i))return Om(e,"ERR_NOT_APPLICABLE","AID DNS/Web profile requires an FQDN nativeId.");const n=`_agent.${Rm(i)}`,o=await this.dnsLookup(n);if(0===o.length)return Om(e,"ERR_NO_DNS_RECORD","No AID DNS TXT record was found for the requested nativeId.",{dnsName:n});const s=o.map(e=>function(e,t){const r=zm(e),i=r.v,n=r.p??r.proto,o=r.u;if(!i||!n||!o)return{code:"ERR_INVALID_AID_RECORD"};if(!i.toLowerCase().startsWith("aid"))return{code:"ERR_INVALID_AID_RECORD"};let s;try{s=new URL(o)}catch{return{code:"ERR_ENDPOINT_INVALID"}}const a=s.protocol.replace(/:$/,"").toLowerCase();return t.has(a)?{record:{version:i,protocol:n,endpoint:s.toString(),publicKey:r.k,keyId:r.i}}:{code:"ERR_ENDPOINT_INVALID"}}(e,this.supportedSchemes)),a=s.filter(e=>"record"in e).map(e=>e.record);if(0===a.length){const t=s.some(e=>!("record"in e)&&"ERR_ENDPOINT_INVALID"===e.code);return Om(e,t?"ERR_ENDPOINT_INVALID":"ERR_INVALID_AID_RECORD",t?"AID DNS record endpoint URI is invalid or unsupported.":"AID DNS TXT payload is malformed or unsupported.",{dnsName:n})}const c=[...a].sort((e,t)=>Dm(e).localeCompare(Dm(t)))[0],l={uaid:e,protocol:c.protocol,endpoint:c.endpoint,record:c};let u="none";if(this.metadataVerifier){if(!(await this.metadataVerifier(l)))return Om(e,"ERR_VERIFICATION_FAILED","AID metadata verification failed.",{dnsName:n});u="metadata"}if(c.publicKey&&this.cryptographicVerifier){if(!(await this.cryptographicVerifier(l)))return Om(e,"ERR_VERIFICATION_FAILED","AID cryptographic verification failed.",{dnsName:n});u="cryptographic"}const d=t.did??void 0;return{id:e,did:d,alsoKnownAs:d?[d]:void 0,service:[{id:`${e}#aid-endpoint`,type:"AIDService",serviceEndpoint:c.endpoint}],metadata:{profile:Pm,resolved:!0,endpoint:c.endpoint,protocol:c.protocol,verification:{level:u,method:Fm(u)},verificationLevel:u,precedenceSource:"dns"}}}}function Um(e){return"object"==typeof e&&null!==e}function Bm(e){if("string"!=typeof e)return null;const t=e.trim();return t||null}function Lm(e){const t=e.trim();if(!t)return null;const r=t.startsWith("v")||t.startsWith("V")?t.slice(1):t;return function(e){return/^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.test(e)}(r)?r:null}function Km(e){if(!Um(e))return;const t=function(e){if(!Um(e))return;const t=Bm(e.checkpoint_topic_id),r=Bm(e.registry),i=Bm(e.log_id);if(!t||!r||!i||"ans"!==r)return;return{checkpointTopicId:t,registry:r,logId:i,checkpointUri:Bm(e.checkpoint_uri)??void 0,viewerUri:Bm(e.viewer_uri)??void 0}}(e.hcs27),r=function(e){if(!Um(e))return;const t=Bm(e.directory_topic_id),r=Bm(e.t_id),i=Bm(e.agent_id);if(!t||!r||!i)return;return{directoryTopicId:t,tId:r,agentId:i,proofProfile:Bm(e.proof_profile)??void 0}}(e.hcs28);return t||r?{hcs27:t,hcs28:r}:void 0}function $m(e){return e instanceof Error&&e.message?e.message:null}const Hm="hcs-14.profile.ans-dns-web";function qm(e,t,r,i){return{id:e,error:{code:t,message:r,details:i},metadata:{profile:Hm,resolved:!1}}}async function jm(e){if("function"!=typeof globalThis.fetch)throw new Error("Fetch API is unavailable in this runtime.");const t=await globalThis.fetch(e,{method:"GET",headers:{accept:"application/json"}});if(!t.ok)throw new Error(`Agent Card request failed with status ${t.status}.`);return t.json()}function Wm(e){return!e||"0"===e}class Vm{constructor(e={}){this.adapterKind="uaid-profile-resolver",this.profile=Hm,this.meta={id:"hcs-14/ans-dns-web",didMethods:["*"],displayName:"HCS-14 ANS DNS/Web Profile",description:"Resolves ANS uaid:aid identifiers via _ans.<nativeId> TXT records and Agent Card endpoint selection."},this.dnsLookup=e.dnsLookup??vm,this.fetchJson=e.fetchJson??jm,this.supportedSchemes=new Set((e.supportedUriSchemes??["https","wss"]).map(e=>e.toLowerCase())),this.transparencyVerifier=e.transparencyVerifier}supports(e,t){if("aid"!==t.method)return!1;if("ans"!==t.params.registry)return!1;const r=t.params.nativeId;return!!r&&xm(r)}async resolveProfile(e,t){const r=t.parsedUaid;if("aid"!==r.method)return qm(e,"ERR_NOT_APPLICABLE","ANS profile only applies to uaid:aid identifiers.");if("ans"!==r.params.registry)return qm(e,"ERR_NOT_APPLICABLE","ANS profile requires registry=ans.");const i=r.params.nativeId;if(!i||!xm(i))return qm(e,"ERR_NOT_APPLICABLE","ANS profile requires an FQDN nativeId.");const n=r.params.uid;if(Wm(n))return qm(e,"ERR_NOT_APPLICABLE","ANS profile requires a non-zero uid parameter.");const o=r.params.proto;if(Wm(o))return qm(e,"ERR_PROTOCOL_UNSPECIFIED","ANS profile requires a usable proto parameter.");const s=r.params.version,a=void 0===s?void 0:Lm(s);if(void 0!==s&&(!(c=s)||null===Lm(c)))return qm(e,"ERR_NOT_APPLICABLE","ANS profile requires a valid semver version parameter when provided.");var c;const l=Rm(i),u=`_ans.${l}`,d=await this.dnsLookup(u);if(0===d.length)return qm(e,"ERR_NO_DNS_RECORD","No ANS DNS TXT record was found for the requested nativeId.",{dnsName:u});const p=d.map(e=>function(e){const t=zm(e),r=t.v,i=t.url;if(!r||!i||"ans1"!==r.toLowerCase())return null;let n;try{n=new URL(i)}catch{return null}if("https:"!==n.protocol.toLowerCase())return null;const o=t.version;let s;if(void 0!==o){const e=Lm(o);if(!e)return null;s=e}return{version:s,url:n.toString()}}(e)).filter(e=>null!==e);if(0===p.length)return qm(e,"ERR_INVALID_ANS_RECORD","ANS DNS TXT payload is malformed or unsupported.",{dnsName:u});let h=p;if(a){const t=p.filter(e=>void 0!==e.version);if(0===t.length)return qm(e,"ERR_VERSION_MISMATCH","UAID specifies a version but no ANS DNS TXT record carries a version field.",{dnsName:u,uaidVersion:a});if(h=t.filter(e=>e.version===a),0===h.length)return qm(e,"ERR_VERSION_MISMATCH","UAID version does not match ANS DNS TXT record version.",{dnsName:u,uaidVersion:a})}const g=(m=h,[...m].sort((e,t)=>e.url.localeCompare(t.url))[0]);var m;let f;try{f=await this.fetchJson(g.url)}catch(A){return qm(e,"ERR_AGENT_CARD_INVALID","Agent Card retrieval failed.",{stage:"fetch",agentCardUrl:g.url,reason:$m(A)})}const y=function(e){if(!Um(e))return null;const t=Bm(e.ansName),r=e.endpoints;return t&&Um(r)?{ansName:t,endpoints:r,transparencyHints:Km(e.transparency)}:null}(f);if(!y)return qm(e,"ERR_AGENT_CARD_INVALID","Agent Card is missing required fields.",{stage:"validate",agentCardUrl:g.url});if(y.ansName!==n)return qm(e,"ERR_AGENT_CARD_INVALID","Agent Card ansName does not match UAID uid.",{stage:"validate",expectedUid:n,actualAnsName:y.ansName});const b=function(e,t){const r=[];for(const[i,n]of Object.entries(e)){if(!Um(n))continue;const e=Bm(n.url);if(!e)continue;let o;try{o=new URL(e)}catch{continue}const s=o.protocol.replace(/:$/,"").toLowerCase();t.has(s)&&r.push({key:i,endpointUrl:o.toString(),parsedUrl:o})}return r}(y.endpoints,this.supportedSchemes),w=b.filter(e=>Rm(e.parsedUrl.hostname)===l);if(0===w.length)return qm(e,"ERR_ENDPOINT_NOT_ANCHORED","No endpoint URL is anchored to the UAID nativeId host.",{nativeId:l});const I=function(e,t){if(0===e.length)return null;const r=[...e].sort((e,t)=>e.key.localeCompare(t.key)),i=r.filter(e=>function(e,t){const r=t.trim().toLowerCase();if(!r)return!1;const i=e.split("/").map(e=>e.trim()).filter(e=>e.length>0);for(const n of i)if(n.toLowerCase()===r)return!0;return!1}(e.parsedUrl.pathname,t));return i.length>0?i[0]:r[0]}(w,o)??w[0];let T=!1,S=!1;if(this.transparencyVerifier&&(T=!0,S=await this.transparencyVerifier({uaid:e,protocol:o,endpoint:I.endpointUrl,agentCardUrl:g.url,transparencyHints:y.transparencyHints}),!S))return qm(e,"ERR_TRANSPARENCY_VERIFICATION_FAILED","Transparency verification failed.",{agentCardUrl:g.url});const k=t.did??void 0,v=S?"cryptographic":"metadata",E=S?"ans-transparency":"metadata-match";return{id:e,did:k,alsoKnownAs:k?[k]:void 0,service:[{id:`${e}#ans-endpoint`,type:"ANSService",serviceEndpoint:I.endpointUrl}],metadata:{profile:Hm,resolved:!0,endpoint:I.endpointUrl,protocol:o,precedenceSource:"dns",verification:{level:v,method:E},verificationLevel:v,agentCardUrl:g.url,dnsRecordSelection:"lexicographically-smallest-url",transparencyHints:y.transparencyHints,transparencyVerification:{attempted:T,succeeded:S}}}}}const Gm="hcs-14.profile.uaid-did-resolution";function Jm(e,t,r,i){return{id:e,error:{code:t,message:r,details:i},metadata:{profile:Gm,resolved:!1}}}function Ym(e,t=[]){return[...new Set([e,...t])]}class Xm{constructor(){this.adapterKind="uaid-profile-resolver",this.profile=Gm,this.meta={id:"hcs-14/uaid-did-resolution",didMethods:["*"],displayName:"HCS-14 UAID DID Resolution Profile",description:"Resolves uaid:did identifiers to DID Document-compatible output with profile metadata."}}supports(e,t){return"uaid"===t.method}async resolveProfile(e,t){const r=t.parsedUaid;if("uaid"!==r.method)return Jm(e,"ERR_INVALID_UAID","Identifier is not uaid:did and cannot be resolved by this profile.",{uaid:e});const i=r.params.src,n=i?function(e){try{const t=im(e);return globalThis.Buffer.from(t).toString("utf8").trim()||null}catch{return null}}(i):null,o=n??t.did??null;if(!o)return Jm(e,"ERR_BASE_DID_UNDETERMINED","Unable to determine base DID; provide src parameter or configure method inference.",{uaid:e});const s=t.didDocument&&t.didDocument.id===o?t.didDocument:await t.resolveDid(o);if(!s)return Jm(e,"ERR_DID_RESOLUTION_FAILED","Base DID resolution failed.",{uaid:e,baseDid:o});if(!s.id||"string"!=typeof s.id)return Jm(e,"ERR_DID_DOCUMENT_INVALID","Resolved DID document is malformed.",{uaid:e,baseDid:o});const a=s.service??[],c=function(e,t){const r=t.proto,i=t.nativeId,n=t.domain;return r||i||n?{id:`${e}#hcs14-hinted-service-1`,type:"HintedService",serviceEndpoint:{source:"uaid-parameters",proto:r,nativeId:i,domain:n}}:null}(e,r.params),l=0===a.length&&null!==c,u=l?[...a,c]:a;return{id:e,did:o,alsoKnownAs:Ym(o,s.alsoKnownAs),verificationMethod:s.verificationMethod,authentication:s.authentication,assertionMethod:s.assertionMethod,service:u.length>0?u:void 0,metadata:{profile:Gm,resolved:!0,baseDid:o,baseDidResolved:!0,verification:{method:"did-resolution",assurance:"base-method",details:"Validated according to base DID method rules"},services:{copiedFromBaseDidDocument:a.length>0,derivedFromUaidParameters:l}}}}}const Zm="hcs-14.profile.uaid-dns-web";function Qm(e,t,r,i){return{id:e,error:{code:t,message:r,details:i},metadata:{profile:Zm,resolved:!1}}}function ef(e){const t={...e},r=t.nativeId;r&&xm(r)&&(t.nativeId=Rm(r));const i=t.domain;return i&&xm(i)&&(t.domain=Rm(i)),t}class tf{constructor(e={}){this.adapterKind="uaid-profile-resolver",this.profile=Zm,this.meta={id:"hcs-14/uaid-dns-web",didMethods:["*"],displayName:"HCS-14 UAID DNS TXT Profile",description:"Binds UAIDs to DNS TXT records at _uaid.<nativeId> and can continue to follow-up profile resolution."},this.dnsLookup=e.dnsLookup??vm,this.dnssecValidation=e.dnssecValidation,this.requireFullResolution=e.requireFullResolution??!1,this.enableFollowupResolution=e.enableFollowupResolution??!0}supports(e,t){const r=Cm(t);if("aid"!==r&&"did"!==r)return!1;const i=t.params.nativeId;return!!i&&xm(i)}async resolveProfile(e,t){const r=t.parsedUaid,i=Cm(r);if("aid"!==i&&"did"!==i)return Qm(e,"ERR_NOT_APPLICABLE","UAID DNS/Web profile only applies to uaid:aid or uaid:did identifiers.");const n=r.params.nativeId;if(!n||!xm(n))return Qm(e,"ERR_NOT_APPLICABLE","UAID DNS/Web profile requires an FQDN nativeId.");const o=Rm(n),s=`_uaid.${o}`,a=_m(Cm(r),r.id,ef(r.params)),c=await this.dnsLookup(s);if(0===c.length)return Qm(e,"ERR_NO_DNS_RECORD","No UAID DNS TXT record was found for the requested nativeId.",{dnsName:s});const l=c.map(e=>zm(e)).map(e=>function(e,t){const r=e.target,i=e.id,n=e.uid,o=e.proto,s=e.nativeId;if("aid"!==r&&"did"!==r)return null;if(!(i&&n&&o&&s))return null;if(Rm(s)!==t)return null;if("registry"in e&&!e.registry)return null;const a=e.did;if(a&&("did"!==r||!a.startsWith("did:")))return null;const c={uid:n,proto:o,nativeId:s};return e.registry&&(c.registry=e.registry),e.domain&&(c.domain=e.domain),e.src&&(c.src=e.src),{target:r,id:i,uid:n,proto:o,nativeId:s,registry:e.registry,domain:e.domain,src:e.src,did:a,memo:e.m,reconstructedUaid:_m(r,i,ef(c))}}(e,o)),u=l.filter(e=>null!==e);if(0===u.length)return Qm(e,"ERR_INVALID_UAID_DNS_RECORD","DNS TXT payload at _uaid record is invalid.",{dnsName:s});const d=u.filter(e=>e.target===i&&e.id===r.id&&e.reconstructedUaid===a);if(0===d.length)return Qm(e,"ERR_UAID_MISMATCH","DNS TXT payload does not match the input UAID after canonical reconstruction.",{dnsName:s,inputCanonical:a});const p=[...d].sort((e,t)=>e.reconstructedUaid.localeCompare(t.reconstructedUaid))[0],h=!!this.dnssecValidation&&await this.dnssecValidation(s)?"dns-binding-dnssec":"dns-binding";if(this.enableFollowupResolution){const i=function(e){return"aid"===Cm(e)?"ans"===e.params.registry?[Hm,Pm]:[Pm]:[Gm]}(r),n=[];for(const r of i){const i=await t.resolveUaidProfileById(r,e);if(i){if(!i.error&&!1!==i.metadata?.resolved)return{...i,metadata:{...i.metadata,profile:Zm,resolved:!0,verificationLevel:h,reconstructedUaid:p.reconstructedUaid,selectedFollowupProfile:r,resolutionMode:"full-resolution"}};n.push(r)}}if(n.length>0)return Qm(e,"ERR_FOLLOWUP_RESOLUTION_FAILED","Follow-up profile resolution failed after successful DNS binding.",{followupProfileId:n[n.length-1],attemptedFailedProfiles:n,dnsName:s})}if(this.requireFullResolution)return Qm(e,"ERR_NO_FOLLOWUP_PROFILE","Resolver policy requires full resolution, but no supported follow-up profile was available.",{dnsName:s});const g=p.did??t.did??void 0;return{id:e,did:g,alsoKnownAs:g?[g]:void 0,metadata:{profile:Zm,resolved:!0,reconstructedUaid:p.reconstructedUaid,verificationLevel:h,resolutionMode:"dns-binding-only"}}}}class rf{constructor(){this.issuers=[]}register(e){this.issuers.push(e)}list(){return[...this.issuers]}filterByDidMethod(e){return this.issuers.filter(t=>t.meta.didMethods.includes(e))}filterByCaip2(e){return this.issuers.filter(t=>t.meta.caip2Networks?.includes(e))}filter(e){return this.issuers.filter(e)}async issue(e){for(const t of this.issuers)if(t.supports(e.method))return t.issue(e);throw new Error(`No issuer registered for method: ${e.method}`)}}const nf=new rf,of=["@hiero-did-sdk","registrar"].join("/");let sf=null;function af(e){return{network:()=>{const t=e.ledgerId;if(!t)throw new Error("Hedera SDK Client must be configured with a network");if(t.isMainnet())return"mainnet";if(t.isTestnet())return"testnet";if(t.isPreviewnet())return"previewnet";if(t.isLocalNode())return"local-node";throw new Error(`Unknown network, ledger ID: ${t.toString()}`)},publicKey:()=>{if(!e.operatorPublicKey)throw new Error("Hedera SDK Client must be configured with an operator account");return e.operatorPublicKey},publish:async t=>{const r="function"==typeof t.getAutoRenewAccountId?t.getAutoRenewAccountId():null,i=function(e){if("string"==typeof e&&e.trim())return e;if(e&&"function"==typeof e.toString){const t=e.toString();return"string"==typeof t&&t.trim()?t:null}return null}(e.operatorAccountId);!r&&i&&"function"==typeof t.setAutoRenewAccountId&&t.setAutoRenewAccountId(i);return(await t.freezeWith(e).execute(e)).getReceipt(e)}}}class cf{constructor(){this.meta={id:"hedera/hiero",didMethods:["hedera"],caip2Networks:["hedera:mainnet","hedera:testnet","hedera:previewnet","hedera:devnet"],caip10Namespaces:["hedera"],displayName:"Hedera (Hiero Registrar)",description:"Issues did:hedera identifiers using the Hiero DID registrar.",homepage:"https://github.com/hiero-ledger/hiero-did-sdk-js"}}supports(e){return"hedera"===e}async issue(e){if("hedera"!==e.method)throw new Error('HederaHieroIssuer only handles method "hedera"');if(!("client"in e))throw new Error("Hedera client is required to issue did:hedera");const t=await async function(){return sf||(sf=Ta(of,{preferImport:!0}).then(e=>e?.createDID??null)),sf}();if(!t)throw new Error("Hiero registrar unavailable. Ensure @hiero-did-sdk/registrar is installed.");const r=e.client;return(await t({},{publisher:af(r)})).did}}class lf{constructor(e){this.registry=e?.registry??new ym,this.issuers=new rf,this.registerHederaIssuer(),this.registerHederaResolver(),this.registerUaidDnsWebProfileResolver(),this.registerAnsDnsWebProfileResolver(),this.registerAidDnsWebProfileResolver(),this.registerUaidDidResolutionProfileResolver(),this.registerHcs11ProfileResolver(),this.logger=y.getInstance({module:"HCS-14"}),this.client=e?.client,this.network=e?.network,this.operatorId=e?.operatorId,!this.client&&e?.network&&e?.operatorId&&e?.privateKey&&this.configureHederaClient(e.network,e.operatorId,e.privateKey),e?.privateKey&&(this.operatorPrivateKey=e.privateKey),e?.hcs10Client&&(this.hcs10Client=e.hcs10Client)}configureHederaClient(e,t,i){const n=B({network:e,operatorId:t,operatorKey:i,mirrorNode:new x(e),logger:this.logger,client:r.Client.forName(e)});this.operatorCtx=n,this.client=n.client,this.network=e,this.operatorId=t,this.operatorPrivateKey=i}async ensureInitializedHedera(){this.operatorCtx&&(await this.operatorCtx.ensureInitialized(),this.operatorId||(this.operatorId=this.operatorCtx.operatorId.toString()),this.operatorPrivateKey||(this.operatorPrivateKey=this.operatorCtx.operatorKey.toString()),this.client||(this.client=this.operatorCtx.client))}getIssuerRegistry(){return this.issuers}listIssuers(){return this.issuers.list()}registerAdapter(e){this.registry.registerAdapter(e)}listAdapters(){return this.registry.listAdapters()}filterAdapters(e={}){return this.registry.filterAdapters(e)}listResolvers(){return this.registry.list()}listProfileResolvers(){return this.registry.listProfileResolvers()}listUaidProfileResolvers(){return this.registry.listUaidProfileResolvers()}filterIssuersByMethod(e){return this.issuers.filterByDidMethod(e)}filterResolversByMethod(e){return this.registry.filterByDidMethod(e)}filterProfileResolversByMethod(e){return this.registry.filterProfileResolversByDidMethod(e)}filterUaidProfileResolversByMethod(e){return this.registry.filterUaidProfileResolversByDidMethod(e)}filterUaidProfileResolversByProfileId(e){return this.registry.filterUaidProfileResolversByProfileId(e)}registerHederaIssuer(){this.issuers.register(new cf)}async createDid(e){return this.issuers.issue(e)}canonicalizeAgentData(e){return em(e)}createUaid(e,t,r){return"string"==typeof e?sm(e,t):sm(e,t,r)}parseHcs14Did(e){return am(e)}isHederaNetwork(e){return ah(e)}isHederaCaip10(e){return lh(e)}toHederaCaip10(e,t){return uh(e,t)}parseHederaCaip10(e){return dh(e)}isEip155Caip10(e){return hh(e)}toEip155Caip10(e,t){return gh(e,t)}getResolverRegistry(){return this.registry}registerProfileResolver(e){this.registry.registerProfileResolver(e)}registerUaidProfileResolver(e){this.registry.registerUaidProfileResolver(e)}registerHederaResolver(){this.registry.registerAdapter(new fm)}registerHcs11ProfileResolver(){this.registry.registerAdapter(new Sm)}registerUaidDidResolutionProfileResolver(){this.registry.registerAdapter(new Xm)}registerAidDnsWebProfileResolver(e){this.registry.registerAdapter(new Mm(e))}registerAnsDnsWebProfileResolver(e){this.registry.registerAdapter(new Vm(e))}registerUaidDnsWebProfileResolver(e){this.registry.registerAdapter(new tf(e))}async resolveDidProfile(e){return this.registry.resolveDidProfile(e)}async resolveUaidProfile(e,t){return this.registry.resolveUaidProfile(e,t)}async createDidWithUaid(e){const t=await this.createDid(e.issue);let r=e.uid;const i=e.proto;let n=e.nativeId;if("hedera"===e.issue.method){if(await this.ensureInitializedHedera(),!n){if(!this.network||!this.operatorId)throw new Error("nativeId not provided and network/operatorId are not configured");n=uh(this.network,this.operatorId)}if(!r&&"hcs-10"===i&&this.network&&this.operatorId)try{if(!this.hcs10Client&&this.operatorPrivateKey&&(this.hcs10Client=new gg({network:this.network,operatorId:this.operatorId,operatorPrivateKey:this.operatorPrivateKey,silent:!0})),this.hcs10Client)r=await this.hcs10Client.getOperatorId();else{const e=new Lh({network:this.network,auth:{operatorId:this.operatorId},silent:!0}),t=await e.fetchProfileByAccountId(this.operatorId,this.network),i=t?.topicInfo?.inboundTopic;r=i?`${i}@${this.operatorId}`:this.operatorId}}catch{r=this.operatorId}}r=r??"0";const o=this.createUaid(t,{uid:r,proto:i,nativeId:n});return{did:t,uaid:o,parsed:am(o)}}}const uf=Object.freeze(Object.defineProperty({__proto__:null,AID_DNS_WEB_PROFILE_ID:Pm,ANS_DNS_WEB_PROFILE_ID:Hm,AidDnsWebProfileResolver:Mm,AnsDnsWebProfileResolver:Vm,CanonicalAgentDataSchema:Xg,HCS11ProfileResolver:Sm,HCS14Client:lf,HCS14_PROTOCOL_REGEX:Yg,HederaHieroIssuer:cf,HieroDidResolver:fm,IssuerRegistry:rf,ResolverRegistry:ym,UAID_DID_RESOLUTION_PROFILE_ID:Gm,UAID_DNS_WEB_PROFILE_ID:Zm,UaidDidResolutionProfileResolver:Xm,UaidDnsWebProfileResolver:tf,canonicalizeAgentData:em,createUaid:sm,defaultIssuerRegistry:nf,defaultResolverRegistry:bm,isDidProfileResolverAdapter:pm,isDidResolverAdapter:hm,isEip155Caip10:hh,isHederaCaip10:lh,isHederaNetwork:ah,isUaidProfileResolverAdapter:dm,nodeDnsTxtLookup:vm,parseHcs14Did:am,parseHederaCaip10:dh,registerDefaultResolvers:wm,toEip155Caip10:gh,toHederaCaip10:uh},Symbol.toStringTag,{value:"Module"}));function df(e){return`hcs://1/${e}`}class pf{constructor(e){this.network=e.network,this.logger=e.logger||y.getInstance({level:e.logLevel||"info",module:"HCS5Client",silent:e.silent}),this.mirrorNode=new x(this.network,this.logger)}}function hf(e){const t=(new r.TokenMintTransaction).setTokenId(r.TokenId.fromString(e.tokenId)).setMetadata([globalThis.Buffer.from(e.metadata)]);return e.transactionMemo&&t.setTransactionMemo(e.transactionMemo),t}var gf=(e=>(e.REGISTER="register",e.UPDATE="update",e.DELETE="delete",e.MIGRATE="migrate",e))(gf||{}),mf=(e=>(e[e.INDEXED=0]="INDEXED",e[e.NON_INDEXED=1]="NON_INDEXED",e))(mf||{});const ff=t.z.string().regex(/^\d+\.\d+\.\d+$/,{message:"Topic ID must be in Hedera format (e.g., '0.0.123456')"}),yf=t.z.object({p:t.z.string().regex(/^hcs-\d+$/,{message:"Protocol must be in format 'hcs-N' where N is a number"}),op:t.z.enum(["register","update","delete","migrate"]),m:t.z.string().max(500,"Memo must not exceed 500 characters").optional(),ttl:t.z.number().int().positive().optional()}),bf=yf.extend({op:t.z.literal("register"),t_id:ff,metadata:t.z.string().optional()}),wf=yf.extend({op:t.z.literal("update"),uid:t.z.string(),t_id:ff,metadata:t.z.string().optional()}),If=yf.extend({op:t.z.literal("delete"),uid:t.z.string()}),Tf=yf.extend({op:t.z.literal("migrate"),t_id:ff,metadata:t.z.string().optional()}),Sf=t.z.discriminatedUnion("op",[bf,wf,If,Tf]);class kf{constructor(e){this.network=e.network,this.logger=e.logger||y.getInstance({level:e.logLevel||"info",module:"HCS2Client",silent:e.silent}),this.mirrorNode=new x(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0)}parseRegistryTypeFromMemo(e){try{const t=/hcs-2:(\d):(\d+)/,r=e.match(t);if(r&&3===r.length){const e=parseInt(r[1]),t=parseInt(r[2]);if(void 0!==e&&!isNaN(t))return{registryType:e,ttl:t}}return}catch(t){return void this.logger.error(`Error parsing registry type from memo: ${t}`)}}generateRegistryMemo(e,t){return`hcs-2:${e}:${t}`}validateMessage(e){try{return Sf.parse(e),{valid:!0,errors:[]}}catch(r){const e=[];return r instanceof t.ZodError?r.errors.forEach(t=>{const r=t.path.join(".");e.push(`${r?r+": ":""}${t.message}`)}):e.push(`Unexpected error: ${r}`),this.logger.debug(`Message validation failed: ${e.join(", ")}`),{valid:!1,errors:e}}}createRegisterMessage(e,t,r,i="hcs-2"){return{p:i,op:gf.REGISTER,t_id:e,metadata:t,m:r}}createUpdateMessage(e,t,r,i,n="hcs-2"){return{p:n,op:gf.UPDATE,t_id:e,uid:t,metadata:r,m:i}}createDeleteMessage(e,t,r="hcs-2"){return{p:r,op:gf.DELETE,uid:e,m:t}}createMigrateMessage(e,t,r,i="hcs-2"){return{p:i,op:gf.MIGRATE,t_id:e,metadata:t,m:r}}parseRegistryEntries(e,t,r,i){const n=[];let o;this.logger.debug(`Parsing ${t.length} messages for topic ${e}`);for(const a of t)try{if(!a.message){this.logger.debug(`Message is missing 'message' property: ${JSON.stringify(a)}`);continue}const t=globalThis.Buffer.from(a.message,"base64").toString("utf-8"),i=JSON.parse(t);this.logger.debug(`Successfully parsed message: ${JSON.stringify(i)}`);const{valid:s,errors:c}=this.validateMessage(i);if(!s){this.logger.warn(`Invalid HCS-2 message: ${c.join(", ")}`);continue}const l={topicId:e,sequence:a.sequence_number,timestamp:a.consensus_timestamp,payer:a.payer_account_id,message:i,consensus_timestamp:a.consensus_timestamp,registry_type:r};n.push(l),(r===mf.NON_INDEXED||!o||l.timestamp>o.timestamp)&&(o=l)}catch(s){this.logger.warn(`Error parsing message: ${s}`)}return this.logger.debug(`Parsed ${n.length} valid entries for topic ${e}`),{topicId:e,registryType:r,ttl:i,entries:r===mf.INDEXED?n:o?[o]:[],latestEntry:o}}}function vf(e){var t,r;return z({memo:e.memoOverride??(t=e.registryType,r=e.ttl,`hcs-2:${t}:${r}`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Ef(e){const t={p:"hcs-2",op:gf.REGISTER,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return _({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})}const Af=/^hcs:\/\/1\/(\d+\.\d+\.\d+)$/,Cf=class e extends kf{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,mirrorNodeUrl:e.mirrorNodeUrl,logger:e.logger}),this.registryTypeCache=new Map,this.operatorId="string"==typeof e.operatorId?r.AccountId.fromString(e.operatorId):e.operatorId,this.operatorCtx=B({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:e.client??this.createClient(e.network)}),this.client=this.operatorCtx.client}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}createClient(e){return"mainnet"===e?r.Client.forMainnet():r.Client.forTestnet()}async createRegistry(e={}){try{await this.ensureInitialized();const t=e.registryType??mf.INDEXED,i=e.ttl??86400;this.generateRegistryMemo(t,i);let n,o,s,a;if(e.adminKey)if("string"==typeof e.adminKey)try{o=r.PublicKey.fromString(e.adminKey)}catch{const t=globalThis.Buffer.from(e.adminKey.replace(/^0x/i,""),"hex");o="ed25519"===this.operatorCtx.keyType?r.PublicKey.fromBytesED25519(t):r.PublicKey.fromBytesECDSA(t)}else"boolean"==typeof e.adminKey?o=this.operatorCtx.operatorKey.publicKey:(o=e.adminKey.publicKey,n=e.adminKey);if(e.submitKey)if("string"==typeof e.submitKey)try{a=r.PublicKey.fromString(e.submitKey)}catch{const t=globalThis.Buffer.from(e.submitKey.replace(/^0x/i,""),"hex");a="ed25519"===this.operatorCtx.keyType?r.PublicKey.fromBytesED25519(t):r.PublicKey.fromBytesECDSA(t)}else"boolean"==typeof e.submitKey?a=this.operatorCtx.operatorKey.publicKey:(a=e.submitKey.publicKey,s=e.submitKey);const c=vf({registryType:t,ttl:i,adminKey:o,submitKey:a,operatorPublicKey:this.operatorCtx.operatorKey.publicKey}),l=await c.freezeWith(this.client);n&&await l.sign(n),s&&await l.sign(s);const u=await l.execute(this.client),d=(await u.getReceipt(this.client)).topicId;if(!d)throw new Error("Failed to create registry: No topic ID in receipt");const p=d.toString();return this.registryTypeCache.set(p,t),this.logger.info(`Created registry topic: ${p} (${t===mf.INDEXED?"Indexed":"Non-indexed"}, TTL: ${i}s)`),{success:!0,topicId:p,transactionId:u.transactionId.toString()}}catch(t){return this.logger.error(`Failed to create registry: ${t}`),{success:!1,error:`Failed to create registry: ${t}`}}}async registerEntry(e,t,r="hcs-2"){try{await this.ensureInitialized();const i=this.createRegisterMessage(t.targetTopicId,t.metadata,t.memo,r),n=t.registryType??await this.resolveRegistryType(e);this.registryTypeCache.set(e,n);const o=t.analyticsMemo??this.buildAnalyticsMemo(gf.REGISTER,n),s=await this.submitMessage(e,i,o);return this.logger.info(`Registered entry in registry ${e} pointing to topic ${t.targetTopicId} using protocol ${r}`),{success:!0,receipt:s,sequenceNumber:s.topicSequenceNumber?.low??void 0}}catch(i){return this.logger.error(`Failed to register entry: ${i}`),{success:!1,error:`Failed to register entry: ${i}`}}}async updateEntry(e,t){try{await this.ensureInitialized();const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i||i.registryType!==mf.INDEXED)throw new Error("Update operation is only valid for indexed registries");const n=this.createUpdateMessage(t.targetTopicId,t.uid,t.metadata,t.memo),o=t.registryType??await this.resolveRegistryType(e);this.registryTypeCache.set(e,o);const s=t.analyticsMemo??this.buildAnalyticsMemo(gf.UPDATE,o),a=await this.submitMessage(e,n,s);return this.logger.info(`Updated entry with UID ${t.uid} in registry ${e}`),{success:!0,receipt:a,sequenceNumber:a.topicSequenceNumber?.low??void 0}}catch(r){throw this.logger.error(`Failed to update entry: ${r}`),r}}async deleteEntry(e,t){try{await this.ensureInitialized();const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i||i.registryType!==mf.INDEXED)throw new Error("Delete operation is only valid for indexed registries");const n=this.createDeleteMessage(t.uid,t.memo),o=t.registryType??await this.resolveRegistryType(e);this.registryTypeCache.set(e,o);const s=t.analyticsMemo??this.buildAnalyticsMemo(gf.DELETE,o),a=await this.submitMessage(e,n,s);return this.logger.info(`Deleted entry with UID ${t.uid} from registry ${e}`),{success:!0,receipt:a,sequenceNumber:a.topicSequenceNumber?.low??void 0}}catch(r){throw this.logger.error(`Failed to delete entry: ${r}`),r}}async migrateRegistry(e,t){try{await this.ensureInitialized();const r=this.createMigrateMessage(t.targetTopicId,t.metadata,t.memo),i=t.registryType??await this.resolveRegistryType(e);this.registryTypeCache.set(e,i);const n=t.analyticsMemo??this.buildAnalyticsMemo(gf.MIGRATE,i),o=await this.submitMessage(e,r,n);return this.logger.info(`Migrated registry ${e} to ${t.targetTopicId}`),{success:!0,receipt:o,sequenceNumber:o.topicSequenceNumber?.low??void 0}}catch(r){throw this.logger.error(`Failed to migrate registry: ${r}`),r}}async getRegistry(e,t={}){try{await this.ensureInitialized();const n=await this.mirrorNode.getTopicInfo(e);this.logger.debug(`Retrieved topic info for ${e}: ${JSON.stringify(n)}`);const o=this.parseRegistryTypeFromMemo(n.memo);if(!o)throw new Error(`Topic ${e} is not an HCS-2 registry (invalid memo format)`);this.logger.debug(`Retrieving messages for topic ${e} with limit ${t.limit??100}`);const s=await this.mirrorNode.getTopicMessages(e,{sequenceNumber:t.skip&&t.skip>0?`gt:${t.skip}`:void 0,limit:t.limit??100,order:t.order??"asc"}),a=t.limit?s.slice(0,t.limit):s;this.logger.debug(`Retrieved ${s.length} messages, using ${a.length} after applying limit.`);const c=[];let l;for(const u of a)try{let i;if(i={p:u.p||"hcs-2",op:u.op,t_id:u.t_id,uid:u.uid,metadata:u.metadata,m:u.m},t.resolveOverflow&&"string"==typeof u.metadata&&Af.test(u.metadata)){const e=u.metadata.match(Af);if(e){const t=e[1];try{const e=await this.mirrorNode.getTopicMessages(t);if(e.length>0){const t=e[0];i={p:t.p||"hcs-2",op:t.op,t_id:t.t_id,uid:t.uid,metadata:t.metadata,m:t.m}}}catch(r){this.logger.warn(`Failed to resolve overflow ${u.metadata}: ${r}`)}}}const{valid:n,errors:s}=this.validateMessage(i);if(!n){this.logger.warn(`Invalid HCS-2 message: ${s.join(", ")}`);continue}const a={topicId:e,sequence:u.sequence_number,timestamp:u.consensus_timestamp,payer:u.payer_account_id||u.payer||"",message:i,consensus_timestamp:u.consensus_timestamp,registry_type:o.registryType};c.push(a),(o.registryType===mf.NON_INDEXED||!l||a.timestamp>l.timestamp)&&(l=a)}catch(i){this.logger.warn(`Error processing message: ${i}`)}this.logger.debug(`Processed ${c.length} valid entries for registry ${e}`);return{topicId:e,registryType:o.registryType,ttl:o.ttl,entries:o.registryType===mf.INDEXED?c:l?[l]:[],latestEntry:l}}catch(i){throw this.logger.error(`Failed to get registry: ${i}`),i}}buildAnalyticsMemo(t,r){return`hcs-2:op:${e.operationAnalyticsCode[t]}:${r}`}async resolveRegistryType(e){const t=this.registryTypeCache.get(e);if(void 0!==t)return t;const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i)throw new Error(`Topic ${e} is not an HCS-2 registry (invalid memo format)`);return this.registryTypeCache.set(e,i.registryType),i.registryType}async submitMessage(e,t,r){try{await this.ensureInitialized();const{valid:i,errors:n}=this.validateMessage(t);if(!i)throw new Error(`Invalid HCS-2 message: ${n.join(", ")}`);let o=JSON.stringify(t);if(globalThis.Buffer.byteLength(o,"utf8")>1024){this.logger.info("HCS-2 payload exceeds 1024 bytes, inscribing via HCS-1");const e=globalThis.Buffer.from(o,"utf8"),r=`hcs2-overflow-${d.randomUUID()}.json`;if("testnet"!==this.network&&"mainnet"!==this.network)throw new Error(`Overflow inscription is only supported on testnet and mainnet, but network is ${this.network}`);const i={accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network};this.inscriptionSDK||(this.inscriptionSDK=await es.createWithAuth({type:"server",...i}));const n=await Oa({type:"buffer",buffer:e,fileName:r,mimeType:"application/json"},i,{mode:"file",waitForConfirmation:!0,waitMaxAttempts:30,waitIntervalMs:4e3},this.inscriptionSDK),s=Ha(n?.inscription);if(!s)throw new Error("Failed to inscribe overflow HCS-2 payload: no topic ID returned");const a=`hcs://1/${s}`,c={...t,metadata:a};this.logger.info(`HCS-2 payload inscribed to ${a}, submitting overflow wrapper`),o=JSON.stringify(c)}const s=_({topicId:e,message:o,transactionMemo:r}),a=await s.execute(this.client);return await a.getReceipt(this.client)}catch(i){throw this.logger.error(`Failed to submit message: ${i}`),i}}async getTopicInfo(e){return this.mirrorNode.getTopicInfo(e)}close(){this.logger.info("HCS-2 client closed.")}getKeyType(){return this.operatorCtx.keyType}getOperatorKey(){return this.operatorCtx.operatorKey}};Cf.operationAnalyticsCode={[gf.REGISTER]:0,[gf.UPDATE]:1,[gf.DELETE]:2,[gf.MIGRATE]:3};let Rf=Cf;class xf extends kf{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,mirrorNodeUrl:e.mirrorNodeUrl,logger:e.logger}),this.hwc=e.hwc,ma?this.logger.info("HCS-2 browser client initialized successfully"):this.logger.error("BrowserHCS2Client initialized in server environment - browser-specific features will not be available. Use HCS2Client instead.")}getOperatorId(){const e=this.hwc.getAccountInfo();if(!e||!e.accountId)throw new Error("No connected account found");return e.accountId}async createRegistry(e={}){try{const t=e.registryType??mf.INDEXED,i=e.ttl??86400,n=this.generateRegistryMemo(t,i);let o=(new r.TopicCreateTransaction).setTopicMemo(n);if(e.adminKey){let t;if("string"==typeof e.adminKey)try{t=r.PublicKey.fromString(e.adminKey)}catch{const i=F.detect(e.adminKey);if(!i.rawBytes)throw new Error("Failed to parse admin public key");t="ed25519"===i.type?r.PublicKey.fromBytesED25519(i.rawBytes):r.PublicKey.fromBytesECDSA(i.rawBytes)}else t="boolean"==typeof e.adminKey?await this.mirrorNode.getPublicKey(this.getOperatorId()):e.adminKey.publicKey;o=o.setAdminKey(t)}if(e.submitKey){let t;if("string"==typeof e.submitKey)try{t=r.PublicKey.fromString(e.submitKey)}catch{const i=F.detect(e.submitKey);if(!i.rawBytes)throw new Error("Failed to parse submit public key");t="ed25519"===i.type?r.PublicKey.fromBytesED25519(i.rawBytes):r.PublicKey.fromBytesECDSA(i.rawBytes)}else t="boolean"==typeof e.submitKey?await this.mirrorNode.getPublicKey(this.getOperatorId()):e.submitKey.publicKey;o=o.setSubmitKey(t)}const s=await this.executeWithWallet(o);if(s?.error)throw new Error(s.error);const a=s?.result;if(!a?.topicId)throw new Error("Failed to create registry: No topic ID in receipt");const c=a.topicId.toString();return this.logger.info(`Created registry topic: ${c} (${t===mf.INDEXED?"Indexed":"Non-indexed"}, TTL: ${i}s)`),{success:!0,topicId:c,transactionId:s.transactionId||"unknown"}}catch(t){return this.logger.error(`Failed to create registry: ${t}`),{success:!1,error:`Failed to create registry: ${t}`}}}async registerEntry(e,t){try{const r=this.createRegisterMessage(t.targetTopicId,t.metadata,t.memo);if(r.op!==gf.REGISTER)throw new Error(`Invalid operation type: ${r.op}, expected ${gf.REGISTER}`);const i=await this.submitMessage(e,r);return this.logger.info(`Registered entry in registry ${e} pointing to topic ${t.targetTopicId}`),{success:!0,receipt:i,sequenceNumber:i.topicSequenceNumber?.low??void 0}}catch(r){return this.logger.error(`Failed to register entry: ${r}`),{success:!1,error:`Failed to register entry: ${r}`}}}async updateEntry(e,t){try{const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i||i.registryType!==mf.INDEXED)throw new Error("Update operation is only valid for indexed registries");const n=this.createUpdateMessage(t.targetTopicId,t.uid,t.metadata,t.memo),o=await this.submitMessage(e,n);return this.logger.info(`Updated entry with UID ${t.uid} in registry ${e}`),{success:!0,receipt:o,sequenceNumber:o.topicSequenceNumber?.low??void 0}}catch(r){return this.logger.error(`Failed to update entry: ${r}`),{success:!1,error:`Failed to update entry: ${r}`}}}async deleteEntry(e,t){try{const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i||i.registryType!==mf.INDEXED)throw new Error("Delete operation is only valid for indexed registries");const n=this.createDeleteMessage(t.uid,t.memo),o=await this.submitMessage(e,n);return this.logger.info(`Deleted entry with UID ${t.uid} from registry ${e}`),{success:!0,receipt:o,sequenceNumber:o.topicSequenceNumber?.low??void 0}}catch(r){return this.logger.error(`Failed to delete entry: ${r}`),{success:!1,error:`Failed to delete entry: ${r}`}}}async migrateRegistry(e,t){try{const r=this.createMigrateMessage(t.targetTopicId,t.metadata,t.memo),i=await this.submitMessage(e,r);return this.logger.info(`Migrated registry ${e} to ${t.targetTopicId}`),{success:!0,receipt:i,sequenceNumber:i.topicSequenceNumber?.low??void 0}}catch(r){return this.logger.error(`Failed to migrate registry: ${r}`),{success:!1,error:`Failed to migrate registry: ${r}`}}}async getRegistry(e,t={}){try{const r=await this.mirrorNode.getTopicInfo(e),i=this.parseRegistryTypeFromMemo(r.memo);if(!i)throw new Error(`Topic ${e} is not an HCS-2 registry (invalid memo format)`);const n=await this.mirrorNode.getTopicMessages(e,{sequenceNumber:t.skip&&t.skip>0?`gt:${t.skip}`:void 0,limit:t.limit??100,order:t.order??"asc"}),o=t.limit?n.slice(0,t.limit):n;return this.parseRegistryEntries(e,o,i.registryType,i.ttl)}catch(r){throw this.logger.error(`Failed to get registry: ${r}`),r}}async submitMessage(e,t){try{const{valid:r,errors:i}=this.validateMessage(t);if(!r)throw new Error(`Invalid HCS-2 message: ${i.join(", ")}`);const n=_({topicId:e,message:JSON.stringify(t)}),o=await this.executeWithWallet(n);if(o?.error)throw new Error(o.error);return o.result}catch(r){throw this.logger.error(`Failed to submit message: ${r}`),r}}async executeWithWallet(e){const t=this.hwc.executeTransactionWithErrorHandling;if(!t)throw new Error("Wallet SDK does not support executeTransactionWithErrorHandling");return await t.call(this.hwc,e,!1)}}const Nf={PROTOCOL:"hcs-20",PUBLIC_TOPIC_ID:"0.0.4350190",REGISTRY_TOPIC_ID:"0.0.4362300",MAX_NUMBER_LENGTH:18,MAX_NAME_LENGTH:100,MAX_METADATA_LENGTH:100,HEDERA_ACCOUNT_REGEX:/^(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))$/},zf=t.z.string().regex(Nf.HEDERA_ACCOUNT_REGEX,"Invalid Hedera account ID format"),_f=t.z.string().regex(/^\d+$/,"Must be a valid number").max(Nf.MAX_NUMBER_LENGTH,`Max ${Nf.MAX_NUMBER_LENGTH} digits`),Pf=t.z.string().min(1,"Tick cannot be empty").transform(e=>e.toLowerCase().trim()),Of=t.z.object({p:t.z.literal("hcs-20"),m:t.z.string().optional()}),Df=Of.extend({op:t.z.literal("deploy"),name:t.z.string().min(1).max(Nf.MAX_NAME_LENGTH),tick:Pf,max:_f,lim:_f.optional(),metadata:t.z.string().max(Nf.MAX_METADATA_LENGTH).optional()}),Ff=Of.extend({op:t.z.literal("mint"),tick:Pf,amt:_f,to:zf}),Mf=Of.extend({op:t.z.literal("burn"),tick:Pf,amt:_f,from:zf}),Uf=Of.extend({op:t.z.literal("transfer"),tick:Pf,amt:_f,from:zf,to:zf}),Bf=Of.extend({op:t.z.literal("register"),name:t.z.string().min(1).max(Nf.MAX_NAME_LENGTH),metadata:t.z.string().max(Nf.MAX_METADATA_LENGTH).optional(),private:t.z.boolean(),t_id:zf}),Lf=t.z.discriminatedUnion("op",[Df,Ff,Mf,Uf,Bf]);class Kf extends Error{constructor(e){super(e),this.name="HCS20Error"}}class $f extends Kf{constructor(e,t){super(e),this.tick=t,this.name="PointsDeploymentError"}}class Hf extends Kf{constructor(e,t,r,i,n,o){super(e),this.tick=t,this.from=r,this.to=i,this.amount=n,this.availableBalance=o,this.name="PointsTransferError"}}class qf extends Kf{constructor(e,t,r,i,n){super(e),this.tick=t,this.from=r,this.amount=i,this.availableBalance=n,this.name="PointsBurnError"}}class jf extends Kf{constructor(e,t){super(e),this.validationErrors=t,this.name="PointsValidationError"}}class Wf extends Kf{constructor(e,t){super(e),this.topicId=t,this.name="TopicRegistrationError"}}class Vf extends Kf{constructor(e){super(`Invalid Hedera account format: ${e}`),this.account=e,this.name="InvalidAccountFormatError"}}class Gf{constructor(e){this.logger=e.logger||new y({module:"HCS20Client"}),this.network="mainnet"===e.network?"mainnet":"testnet",this.mirrorNode=new x(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0),this.registryTopicId=e.registryTopicId||Nf.REGISTRY_TOPIC_ID,this.publicTopicId=e.publicTopicId||Nf.PUBLIC_TOPIC_ID}validateMessage(e){try{return Lf.parse(e),{valid:!0}}catch(t){if(t.errors){return{valid:!1,errors:t.errors.map(e=>`${e.path.join(".")}: ${e.message}`)}}return{valid:!1,errors:[t.message]}}}normalizeTick(e){return e.toLowerCase().trim()}accountToString(e){if("string"==typeof e){if(!Nf.HEDERA_ACCOUNT_REGEX.test(e))throw new Vf(e);return e}return e.toString()}topicToString(e){if("string"==typeof e){if(!Nf.HEDERA_ACCOUNT_REGEX.test(e))throw new Vf(e);return e}return e.toString()}}function Jf(e){const t={p:"hcs-20",op:"deploy",name:e.name,tick:e.tick.toLowerCase().trim(),max:e.max,lim:e.lim,metadata:e.metadata,m:e.memo};return _({topicId:e.topicId,message:JSON.stringify(t)})}function Yf(e){const t={p:"hcs-20",op:"mint",tick:e.tick.toLowerCase().trim(),amt:e.amt,to:e.to,m:e.memo};return _({topicId:e.topicId,message:JSON.stringify(t)})}function Xf(e){const t={p:"hcs-20",op:"transfer",tick:e.tick.toLowerCase().trim(),amt:e.amt,from:e.from,to:e.to,m:e.memo};return _({topicId:e.topicId,message:JSON.stringify(t)})}function Zf(e){const t={p:"hcs-20",op:"burn",tick:e.tick.toLowerCase().trim(),amt:e.amt,from:e.from,m:e.memo};return _({topicId:e.topicId,message:JSON.stringify(t)})}function Qf(e){const t={p:"hcs-20",op:"register",name:e.name,metadata:e.metadata,private:e.isPrivate,t_id:e.topicId,m:e.memo};return _({topicId:e.registryTopicId,message:JSON.stringify(t)})}class ey extends Error{constructor(e,t){super(e),this.code=t,this.name="HCS21ValidationError"}}function ty(e){const t=e.indexed??0,r=e.type??gc.ADAPTER_REGISTRY;if(e.metaTopicId&&!hc.test(e.metaTopicId))throw new ey("Meta value must be a short pointer (topic ID, HRL, IPFS, Arweave, OCI, or HTTPS)","invalid_payload");const i=e.metaTopicId?`:${e.metaTopicId}`:"";return`hcs-21:${t}:${e.ttl}:${r}${i}`}function ry(e){return z({memo:ty({ttl:e.ttl,indexed:e.indexed,type:e.type,metaTopicId:e.metaTopicId}),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function iy(e){const t=JSON.stringify(e.declaration),r=globalThis.Buffer.byteLength(t,"utf8");if(r>dc)throw new ey(`HCS-21 payload exceeds safe limit of 1000 bytes (${r}); Hedera cap is 1024`,"size_exceeded");return _({topicId:e.topicId,message:JSON.stringify(e.declaration),transactionMemo:e.transactionMemo})}class ny{constructor(e){this.network=e.network,this.logger=e.logger||new y({level:"info",module:"HCS-21"}),this.mirrorNode=new x(this.network,this.logger,{customUrl:e.mirrorNodeUrl})}buildDeclaration(e){const t={p:lc,op:e.op,adapter_id:e.adapterId,entity:e.entity,package:e.adapterPackage,manifest:e.manifest,...e.manifestSequence?{manifest_sequence:e.manifestSequence}:{},config:e.config,state_model:e.stateModel,signature:e.signature};return this.validateDeclaration(t)}validateDeclaration(e){try{const t="string"==typeof e?JSON.parse(e):e,r=yc.parse(t);return this.assertSizeLimit(r),r}catch(t){const e=t instanceof Error?t.message:"Invalid adapter declaration";throw new ey(e,"invalid_payload")}}async fetchDeclarations(e,t){const r=await this.mirrorNode.getTopicMessages(e,{limit:t?.limit,order:t?.order}),i=[];for(const o of r)if(o.p===lc)try{const e=this.validateDeclaration(o);i.push({declaration:e,consensusTimestamp:o.consensus_timestamp,sequenceNumber:o.sequence_number,payer:o.payer})}catch(n){const e=n instanceof Error?n.message:"unknown error";this.logger.warn(`Skipping invalid HCS-21 message: ${e}`)}return i}async fetchCategoryEntries(e){const t=await this.mirrorNode.getTopicMessages(e),r=[];for(const i of t){if("hcs-2"!==i.p||"register"!==i.op)continue;if(!i.t_id||"string"!=typeof i.t_id)continue;const e="string"==typeof i.m?i.m:void 0,t=e?.startsWith("adapter:")?e.slice(8):e;r.push({adapterId:t??i.t_id,adapterTopicId:i.t_id,metadata:i.metadata,memo:e,payer:i.payer,sequenceNumber:Number(i.sequence_number??0),consensusTimestamp:i.consensus_timestamp})}return r}assertSizeLimit(e){const t=JSON.stringify(e),r=globalThis.Buffer.byteLength(t,"utf8");if(r>dc)throw new ey(`HCS-21 payload exceeds safe limit of 1000 bytes (${r}); Hedera cap is 1024`,"size_exceeded")}}function oy(e){if(Array.isArray(e))return e.map(oy);if(e&&"object"==typeof e){const t=Object.entries(e).sort(([e],[t])=>e<t?-1:e>t?1:0),r={};for(const[e,i]of t)r[e]=oy(i);return r}return e}function sy(e){const t=oy(e);return JSON.stringify(t)}const ay="hcs-15:op:base_create",cy="hcs-15:op:petal_create";function ly(e,t){if("string"!=typeof e)return t;const r=e.trim();return r||t}function uy(e){const t=(new r.AccountCreateTransaction).setECDSAKeyWithAlias(e.publicKey).setInitialBalance(e.initialBalance instanceof r.Hbar?e.initialBalance:new r.Hbar(e.initialBalance??1));return"number"==typeof e.maxAutomaticTokenAssociations&&t.setMaxAutomaticTokenAssociations(e.maxAutomaticTokenAssociations),e.accountMemo&&t.setAccountMemo(e.accountMemo),t.setTransactionMemo(ly(e.transactionMemo,ay)),t}function dy(e){const t=(new r.AccountCreateTransaction).setKeyWithoutAlias(e.publicKey).setInitialBalance(e.initialBalance instanceof r.Hbar?e.initialBalance:new r.Hbar(e.initialBalance??1));return"number"==typeof e.maxAutomaticTokenAssociations&&t.setMaxAutomaticTokenAssociations(e.maxAutomaticTokenAssociations),e.accountMemo&&t.setAccountMemo(e.accountMemo),t.setTransactionMemo(ly(e.transactionMemo,cy)),t}class py{constructor(e){this.network=e.network,this.logger=e.logger||new y({module:"HCS-15",level:e.logLevel||"info"}),this.mirrorNode=new x(this.network,this.logger,{customUrl:e.mirrorNodeUrl})}async verifyPetalAccount(e,t){try{const r=await this.mirrorNode.requestAccount(e),i=await this.mirrorNode.requestAccount(t),n=r?.key?.key||"";return""!==n&&n===(i?.key?.key||"")}catch(zw){return this.logger.warn("verifyPetalAccount failed",{error:String(zw)}),!1}}}var hy=(e=>(e[e.COMMUNICATION=0]="COMMUNICATION",e[e.TRANSACTION=1]="TRANSACTION",e[e.STATE=2]="STATE",e))(hy||{}),gy=(e=>(e.FLORA_CREATED="flora_created",e.TRANSACTION="transaction",e.STATE_UPDATE="state_update",e.FLORA_JOIN_REQUEST="flora_join_request",e.FLORA_JOIN_VOTE="flora_join_vote",e.FLORA_JOIN_ACCEPTED="flora_join_accepted",e))(gy||{});class my extends Error{constructor(e,t){super(e),this.code=t,this.name="FloraError"}}const fy="hcs-16:op:0:0",yy="hcs-17:op:6:2",by="hcs-16:op:1:1",wy="hcs-16:op:1:1";function Iy(e,t){if("string"!=typeof e)return t;const r=e.trim();return r||t}const Ty={[gy.FLORA_CREATED]:0,[gy.TRANSACTION]:1,[gy.STATE_UPDATE]:2,[gy.FLORA_JOIN_REQUEST]:3,[gy.FLORA_JOIN_VOTE]:4,[gy.FLORA_JOIN_ACCEPTED]:5},Sy={[gy.FLORA_CREATED]:hy.COMMUNICATION,[gy.TRANSACTION]:hy.TRANSACTION,[gy.STATE_UPDATE]:hy.STATE,[gy.FLORA_JOIN_REQUEST]:hy.COMMUNICATION,[gy.FLORA_JOIN_VOTE]:hy.COMMUNICATION,[gy.FLORA_JOIN_ACCEPTED]:hy.STATE};function ky(e){const t=function(e){return`hcs-16:${e.floraAccountId}:${e.topicType}`}({floraAccountId:e.floraAccountId,topicType:e.topicType}),i=z({memo:t,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey});var n;return i.setTransactionMemo(Iy(e.transactionMemo,(n=e.topicType,`hcs-16:op:${Ty[gy.FLORA_CREATED]}:${n}`))),e.autoRenewAccountId&&i.setAutoRenewAccountId(r.AccountId.fromString(e.autoRenewAccountId)),i}function vy(e){const t=(new r.AccountCreateTransaction).setKey(e.keyList),i="number"==typeof e.initialBalanceHbar?e.initialBalanceHbar:1;t.setInitialBalance(new r.Hbar(i));const n="number"==typeof e.maxAutomaticTokenAssociations?e.maxAutomaticTokenAssociations:-1;return t.setMaxAutomaticTokenAssociations(n),t.setTransactionMemo(Iy(e.transactionMemo,fy)),t}function Ey(e){const t={p:"hcs-16",op:e.op,operator_id:e.operatorId,...e.body||{}};return _({topicId:e.topicId,message:JSON.stringify(t),transactionMemo:Iy(e.transactionMemo,(r=e.op,`hcs-16:op:${Ty[r]}:${Sy[r]}`))});var r}function Ay(e){return Ey({topicId:e.topicId,operatorId:e.operatorId,op:gy.FLORA_CREATED,body:{flora_account_id:e.floraAccountId,topics:e.topics}})}function Cy(e){return Ey({topicId:e.topicId,operatorId:e.operatorId,op:gy.TRANSACTION,body:{schedule_id:e.scheduleId,data:e.data,m:e.data}})}function Ry(e){const t={p:"hcs-17",op:"state_hash",state_hash:e.hash,topics:e.topics??[],account_id:e.accountId??e.operatorId,epoch:e.epoch,timestamp:(new Date).toISOString(),m:e.memo};return _({topicId:e.topicId,message:JSON.stringify(t),transactionMemo:Iy(e.transactionMemo,yy)})}function xy(e){return Ey({topicId:e.topicId,operatorId:e.operatorId,op:gy.FLORA_JOIN_REQUEST,body:{account_id:e.accountId,connection_request_id:e.connectionRequestId,connection_topic_id:e.connectionTopicId,connection_seq:e.connectionSeq}})}function Ny(e){return Ey({topicId:e.topicId,operatorId:e.operatorId,op:gy.FLORA_JOIN_VOTE,body:{account_id:e.accountId,approve:e.approve,connection_request_id:e.connectionRequestId,connection_seq:e.connectionSeq}})}function zy(e){return Ey({topicId:e.topicId,operatorId:e.operatorId,op:gy.FLORA_JOIN_ACCEPTED,body:{members:e.members,epoch:e.epoch}})}class _y{constructor(e){this.network=e.network,this.logger=e.logger||new y({level:"info",module:"HCS-16"}),this.mirrorNode=new x(this.network,this.logger,{customUrl:e.mirrorNodeUrl})}async assembleKeyList(e){const t=[];for(const r of e.members){const e=await this.mirrorNode.getPublicKey(r);t.push(e)}return new r.KeyList(t,e.threshold)}async assembleSubmitKeyList(e){const t=[];for(const r of e){const e=await this.mirrorNode.getPublicKey(r);t.push(e)}return new r.KeyList(t,1)}buildFloraTopicCreateTxs(e){return{communication:ky({floraAccountId:e.floraAccountId,topicType:hy.COMMUNICATION,adminKey:e.keyList,submitKey:e.submitList,autoRenewAccountId:e.autoRenewAccountId}),transaction:ky({floraAccountId:e.floraAccountId,topicType:hy.TRANSACTION,adminKey:e.keyList,submitKey:e.submitList,autoRenewAccountId:e.autoRenewAccountId}),state:ky({floraAccountId:e.floraAccountId,topicType:hy.STATE,adminKey:e.keyList,submitKey:e.submitList,autoRenewAccountId:e.autoRenewAccountId})}}parseTopicMemo(e){const t=e.match(/^hcs-16:([0-9.]+):(\d)$/);if(!t)return null;const r=t[1],i=Number(t[2]);return i!==hy.COMMUNICATION&&i!==hy.TRANSACTION&&i!==hy.STATE?null:{protocol:"hcs-16",floraAccountId:r,topicType:i}}createFloraMessage(e,t,r){return{p:"hcs-16",op:e,operator_id:t,...r||{}}}async getRecentMessages(e,t){const r=t?.limit??25,i=t?.order??"desc",n=await this.mirrorNode.getTopicMessages(e,{limit:r,order:i}),o=[];for(const s of n){if("hcs-16"!==s.p)continue;const{consensus_timestamp:e,sequence_number:r,running_hash:i,running_hash_version:n,topic_id:a,payer:c,created:l,chunk_info:u,...d}=s,p=d.op,h=d.operator_id;if(t?.opFilter&&p!==t.opFilter)continue;if("string"!=typeof h)continue;const g=d;o.push({message:g,consensus_timestamp:e,sequence_number:Number(r),payer:c})}return o}async getLatestMessage(e,t){const r=await this.getRecentMessages(e,{limit:1,order:"desc",opFilter:t});if(0===r.length)return null;const i=r[0];return Object.assign({},i.message,{consensus_timestamp:i.consensus_timestamp,sequence_number:i.sequence_number})}}const Py=t.z.object({p:t.z.literal("hcs-17"),op:t.z.literal("state_hash"),state_hash:t.z.string().min(1),topics:t.z.array(t.z.string()),account_id:t.z.string().min(1),epoch:t.z.number().int().nonnegative().optional(),timestamp:t.z.string().optional(),m:t.z.string().optional()});class Oy extends Error{constructor(e,t){super(e),this.code=t,this.name="StateHashError"}}var Dy=(e=>(e[e.STATE=0]="STATE",e))(Dy||{});function Fy(e){return`hcs-17:0:${e}`}function My(e){try{const t=e.match(/^hcs-17:(\d+):(\d+)$/);if(!t)return;const r=Number(t[1]),i=Number(t[2]);if(Number.isNaN(r)||Number.isNaN(i)||i<=0)return;if(0!==r)return;return{type:r,ttl:i}}catch{return}}class Uy{constructor(e){this.network=e.network,this.logger=e.logger||new y({level:e.logLevel||"info",module:"HCS-17"}),this.mirrorNode=new x(this.network,this.logger,{customUrl:e.mirrorNodeUrl})}createMessage(e){return{p:"hcs-17",op:"state_hash",state_hash:e.stateHash,topics:e.topics,account_id:e.accountId,epoch:e.epoch,timestamp:(new Date).toISOString(),m:e.memo}}validateMessage(e){const t=Py.safeParse(e);if(t.success)return{valid:!0,errors:[]};const r=t.error.errors.map(e=>`${e.path.join(".")}: ${e.message}`);return this.logger.debug(`HCS-17 message validation failed: ${r.join(", ")}`),{valid:!1,errors:r}}generateTopicMemo(e){return Fy(e)}async validateHCS17Topic(e){try{const t=My((await this.mirrorNode.getTopicInfo(e)).memo);return t?t.type!==Dy.STATE?{valid:!1,error:"Unsupported HCS-17 topic type"}:{valid:!0,type:t.type,ttl:t.ttl}:{valid:!1,error:"Invalid HCS-17 memo format"}}catch(zw){return{valid:!1,error:String(zw)}}}async getRecentMessages(e,t){const r=t?.limit??25,i=t?.order??"desc",n=await this.mirrorNode.getTopicMessages(e,{limit:r,order:i}),o=[];for(const s of n)try{if("hcs-17"!==s.p||"state_hash"!==s.op)continue;const e=s,{valid:t}=this.validateMessage(e);if(!t)continue;o.push({message:{p:"hcs-17",op:"state_hash",state_hash:e.state_hash,topics:e.topics,account_id:e.account_id,epoch:e.epoch,timestamp:e.timestamp,m:e.m},consensus_timestamp:e.consensus_timestamp,sequence_number:Number(e.sequence_number),payer:e.payer})}catch(_w){this.logger.debug(`Failed to parse HCS-17 message: ${_w}`)}return o}async getLatestMessage(e){const t=await this.getRecentMessages(e,{limit:1,order:"desc"});if(!t.length)return null;const{message:r,consensus_timestamp:i,sequence_number:n}=t[0];return Object.assign({},r,{consensus_timestamp:i,sequence_number:n})}calculateAccountStateHash(e){try{this.logger.debug("Calculating account state hash",{accountId:e.accountId,topicCount:e.topics.length});const t=[...e.topics].sort((e,t)=>e.topicId.localeCompare(t.topicId));let r="";for(const e of t)r+=e.topicId+e.latestRunningHash;let i="";i="string"==typeof e.publicKey?e.publicKey:e.publicKey.toString(),r+=i;const n=d.createHash("sha384");n.update(r);const o=n.digest("hex");return this.logger.debug("Account state hash calculated",{accountId:e.accountId,stateHash:o}),{stateHash:o,accountId:e.accountId,timestamp:new Date,topicCount:e.topics.length}}catch(t){throw this.logger.error("Failed to calculate account state hash",t),new Error("HCS-17 CALCULATION_FAILED")}}calculateCompositeStateHash(e){try{this.logger.debug("Calculating composite state hash",{compositeAccountId:e.compositeAccountId,memberCount:e.memberStates.length,topicCount:e.compositeTopics.length});const t=[...e.memberStates].sort((e,t)=>e.accountId.localeCompare(t.accountId)),r=[...e.compositeTopics].sort((e,t)=>e.topicId.localeCompare(t.topicId));let i="";for(const e of t)i+=e.accountId+e.stateHash;for(const e of r)i+=e.topicId+e.latestRunningHash;i+=e.compositePublicKeyFingerprint;const n=d.createHash("sha384");n.update(i);const o=n.digest("hex");return this.logger.debug("Composite state hash calculated",{compositeAccountId:e.compositeAccountId,stateHash:o}),{stateHash:o,accountId:e.compositeAccountId,timestamp:new Date,topicCount:e.compositeTopics.length,memberCount:e.memberStates.length,compositeTopicCount:e.compositeTopics.length}}catch(t){throw this.logger.error("Failed to calculate composite state hash",t),new Error("HCS-17 COMPOSITE_CALCULATION_FAILED")}}calculateKeyFingerprint(e,t){try{const r={threshold:t,keys:[...e].sort((e,t)=>e.toString().localeCompare(t.toString())).map(e=>e.toString())},i=d.createHash("sha384");return i.update(JSON.stringify(r)),i.digest("hex")}catch(r){throw this.logger.error("Failed to calculate key fingerprint",r),new Error("HCS-17 FINGERPRINT_FAILED")}}createStateHashMessage(e,t,r,i){return{p:"hcs-17",op:"state_hash",state_hash:e,topics:r,account_id:t,timestamp:(new Date).toISOString(),m:i}}async verifyStateHash(e,t){try{let r;r="publicKey"in e?this.calculateAccountStateHash(e).stateHash:this.calculateCompositeStateHash(e).stateHash;const i=r===t,n="accountId"in e?e.accountId:e.compositeAccountId;return this.logger.debug("State hash verification",{accountId:n,isValid:i,expected:t,calculated:r}),i}catch(r){return this.logger.error("Failed to verify state hash",r),!1}}}function By(e){return z({memo:Fy(e.ttl),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Ly(e){const t={p:"hcs-17",op:"state_hash",state_hash:e.stateHash,topics:e.topics,account_id:e.accountId,epoch:e.epoch,timestamp:e.timestamp??(new Date).toISOString(),m:e.memo};return _({topicId:e.topicId,message:JSON.stringify(t),transactionMemo:e.transactionMemo})}var Ky=(e=>(e.ANNOUNCE="announce",e.PROPOSE="propose",e.RESPOND="respond",e.COMPLETE="complete",e.WITHDRAW="withdraw",e))(Ky||{});function $y(e){return"object"==typeof e&&null!==e}function Hy(e){return"string"==typeof e}function qy(e){return"number"==typeof e&&Number.isFinite(e)}function jy(e){if(!$y(e))return!1;if("hcs-18"!==e.p)return!1;if(!Hy(e.op))return!1;const t=e.op;return!!["announce","propose","respond","complete","withdraw"].includes(t)&&"data"in e}var Wy=(e=>(e.IDLE="idle",e.ANNOUNCED="announced",e.PROPOSING="proposing",e.FORMING="forming",e.ACTIVE="active",e.WITHDRAWN="withdrawn",e))(Wy||{});class Vy extends Error{constructor(e,t){super(e),this.code=t,this.name="DiscoveryError"}}function Gy(e,t){return t&&t.trim().length>0?t:e&&e>0?`hcs-18:0:${e}`:"hcs-18:0"}function Jy(e){return z({memo:Gy(e.ttlSeconds,e.memoOverride),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Yy(e){const t="string"==typeof e.transactionMemo&&e.transactionMemo.length>0?e.transactionMemo:`hcs-18:op:${function(e){switch(e){case Ky.ANNOUNCE:return 0;case Ky.PROPOSE:return 1;case Ky.RESPOND:return 2;case Ky.COMPLETE:return 3;case Ky.WITHDRAW:return 4;default:return 0}}(e.message.op)}`;return(new r.TopicMessageSubmitTransaction).setTopicId(e.topicId).setMessage(JSON.stringify(e.message)).setTransactionMemo(t)}function Xy(e){return{p:"hcs-18",op:Ky.ANNOUNCE,data:e}}function Zy(e){return{p:"hcs-18",op:Ky.PROPOSE,data:e}}function Qy(e){return{p:"hcs-18",op:Ky.RESPOND,data:e}}function eb(e){return{p:"hcs-18",op:Ky.COMPLETE,data:e}}function tb(e){return{p:"hcs-18",op:Ky.WITHDRAW,data:e}}class rb{constructor(e){this.network=e.network,this.logger=e.logger||y.getInstance({module:"HCS-18"}),this.mirrorNode=new x(this.network,this.logger)}async getDiscoveryMessages(e,t){const r=["announce","propose","respond","complete","withdraw"],i=await this.mirrorNode.getTopicMessages(e,t);return i?i.filter(e=>"hcs-18"===e.p&&r.includes(e.op)):[]}isProposalReady(e){const t=Array.from(e.responses.values()).filter(e=>"accept"===e.decision),r=e.data.members.length-1;return t.length>=r}}const ib=t.z.string().regex(/^(0|[1-9]\d*)$/);const nb=t.z.string().min(1).refine(function(e){if(!/^[A-Za-z0-9_-]+$/.test(e))return!1;try{const t=e+"=".repeat((4-e.length%4)%4),r=globalThis.Buffer.from(t,"base64url");return r.length>0&&r.toString("base64url")===e}catch{return!1}},"must be base64url"),ob=t.z.string().min(1).refine(function(e){if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(e))return!1;try{return globalThis.Buffer.from(e,"base64").toString("base64")===e}catch{return!1}},"must be base64"),sb=t.z.object({treeSize:ib,rootHashB64u:nb}).passthrough(),ab=t.z.object({treeSize:ib,rootHashB64u:nb}).passthrough(),cb=t.z.object({alg:t.z.string().min(1),kid:t.z.string().min(1),b64u:nb}).passthrough(),lb=t.z.object({type:t.z.literal("ans-checkpoint-v1"),stream:t.z.object({registry:t.z.string().min(1),log_id:t.z.string().min(1)}).passthrough(),log:t.z.object({alg:t.z.literal("sha-256"),leaf:t.z.string().min(1),merkle:t.z.literal("rfc9162")}).passthrough(),root:sb,prev:ab.optional(),sig:cb.optional()}).passthrough(),ub=lb.superRefine((e,r)=>{const i=BigInt(e.root.treeSize),n=e.prev?BigInt(e.prev.treeSize):void 0;void 0!==n&&n>i&&r.addIssue({code:t.z.ZodIssueCode.custom,message:"metadata.prev.treeSize must be <= metadata.root.treeSize",path:["prev","treeSize"]})}),db=t.z.object({alg:t.z.literal("sha-256"),b64u:nb}).passthrough(),pb=t.z.object({p:t.z.literal("hcs-27"),op:t.z.literal("register"),metadata:t.z.union([lb,t.z.string().regex(/^hcs:\/\/1\/\d+\.\d+\.\d+$/)]),metadata_digest:db.optional(),m:t.z.string().max(299).optional()}).passthrough().superRefine((e,r)=>{"string"!=typeof e.metadata||e.metadata_digest||r.addIssue({code:t.z.ZodIssueCode.custom,message:"metadata_digest is required when metadata is an HCS-1 reference",path:["metadata_digest"]})}),hb=t.z.object({leafHash:t.z.string().regex(/^(?:[0-9a-f]{2})+$/i),leafIndex:ib,treeSize:ib,path:t.z.array(ob),rootHash:ob,rootSignature:t.z.string().optional(),treeVersion:t.z.literal(1)}).passthrough(),gb=t.z.object({oldTreeSize:ib,newTreeSize:ib,oldRootHash:t.z.string(),newRootHash:t.z.string(),consistencyPath:t.z.array(ob),treeVersion:t.z.literal(1)}).passthrough();function mb(e){const{type:t,stream:r,log:i,root:n,prev:o,sig:s}=e;if(!(t&&r&&i&&n))throw new Error("Invalid HCS-27 checkpoint metadata");return{type:t,stream:{registry:r.registry,log_id:r.log_id},log:{alg:i.alg,leaf:i.leaf,merkle:i.merkle},root:{treeSize:n.treeSize,rootHashB64u:n.rootHashB64u},...o?{prev:{treeSize:o.treeSize,rootHashB64u:o.rootHashB64u}}:{},...s?{sig:{alg:s.alg,kid:s.kid,b64u:s.b64u}}:{}}}function fb(e){const{p:t,op:r,metadata:i,metadata_digest:n,m:o}=e;if(!t||!r||!i)throw new Error("Invalid HCS-27 checkpoint message");return{p:t,op:r,metadata:"string"==typeof i?i:mb(i),...n?{metadata_digest:{alg:n.alg,b64u:n.b64u}}:{},...o?{m:o}:{}}}function yb(e=86400){return`hcs-27:0:${e>0?e:86400}:0`}function bb(e){const t=e.trim().split(":");if(4!==t.length||"hcs-27"!==t[0])return;const r=Number.parseInt(t[1],10),i=Number.parseInt(t[2],10),n=Number.parseInt(t[3],10);return Number.isNaN(r)||Number.isNaN(i)||Number.isNaN(n)?void 0:{indexedFlag:r,ttlSeconds:i,topicType:n}}function wb(){return"hcs-27:op:0:0"}function Ib(e){if(null===e||"boolean"==typeof e||"number"==typeof e||"string"==typeof e){if("number"==typeof e&&!Number.isFinite(e))throw new Error("JSON numbers must be finite");return e}if(Array.isArray(e))return Array.from(e,e=>void 0===e?null:Ib(e));if("object"==typeof e){const t=e.toJSON;if("function"==typeof t)return Ib(t.call(e));const r={};for(const[i,n]of Object.entries(e))void 0!==n&&(r[i]=Ib(n));return r}throw new Error("Unsupported JSON value type: "+typeof e)}function Tb(e,t){try{if(!e)throw new Error("empty base64");const t=globalThis.Buffer.from(e,"base64");if(t.toString("base64")!==e)throw new Error("non-canonical base64");return t}catch{throw new Error(`${t} must be valid base64`)}}function Sb(e){if(null===e)return"null";if("boolean"==typeof e)return e?"true":"false";if("string"==typeof e)return JSON.stringify(e);if("number"==typeof e)return function(e){return Object.is(e,-0)?"0":e.toString()}(e);if(Array.isArray(e))return`[${e.map(e=>Sb(e)).join(",")}]`;if("object"==typeof e){return`{${Object.entries(e).sort(([e],[t])=>e<t?-1:e>t?1:0).map(([e,t])=>`${JSON.stringify(e)}:${Sb(t)}`).join(",")}}`}throw new Error("Unsupported JSON value type: "+typeof e)}function kb(e){return BigInt(e)}function vb(e){return 1n&e}function Eb(e){const t=Ib(e);return globalThis.Buffer.from(Sb(t),"utf8")}function Ab(){return d.createHash("sha256").update(globalThis.Buffer.alloc(0)).digest()}function Cb(e){return d.createHash("sha256").update(globalThis.Buffer.from([0])).update(globalThis.Buffer.from(e)).digest()}function Rb(e,t){return d.createHash("sha256").update(globalThis.Buffer.from([1])).update(globalThis.Buffer.from(e)).update(globalThis.Buffer.from(t)).digest()}function xb(e){if(0===e.length)return Ab();if(1===e.length)return Cb(e[0]);const t=function(e){if(e<=1)return 0;let t=1;for(;t<<1<e;)t<<=1;return t}(e.length);return Rb(xb(e.slice(0,t)),xb(e.slice(t)))}function Nb(e){return xb(e.map(e=>Eb(e)))}function zb(e){return Cb(Eb(e)).toString("hex")}function _b(e){let t,r,i,n,o,s;if("leafHash"in e){const s=hb.parse(e);t=BigInt(s.leafIndex),r=BigInt(s.treeSize),i=s.leafHash,n=s.path,o=s.rootHash}else t=kb(e.leafIndex),r=kb(e.treeSize),i=e.leafHashHex,n=e.path,o=e.expectedRootB64;if(r<=0n)throw new Error("treeSize must be greater than zero for inclusion proofs");if(t<0n||t>=r)throw new Error("leafIndex must be less than treeSize");if(!/^(?:[0-9a-f]{2})+$/i.test(i.trim()))throw new Error("leafHash must be valid hex");try{s=globalThis.Buffer.from(i.trim(),"hex")}catch{throw new Error("leafHash must be valid hex")}let a=t,c=r-1n;for(const[l,u]of n.entries()){if(0n===c)return!1;const e=Tb(u,`path[${l}]`);if(1n===vb(a)||a===c){if(s=Rb(e,s),0n===vb(a))for(;0n===vb(a)&&0n!==a;)a/=2n,c/=2n}else s=Rb(s,e);a/=2n,c/=2n}return 0n===c&&s.toString("base64")===o}function Pb(e){let t,r,i,n,o;if("oldRootHash"in e){const s=gb.parse(e);t=BigInt(s.oldTreeSize),r=BigInt(s.newTreeSize),i=s.oldRootHash,n=s.newRootHash,o=s.consistencyPath}else t=kb(e.oldTreeSize),r=kb(e.newTreeSize),i=e.oldRootB64,n=e.newRootB64,o=e.consistencyPath;if(t<0n||r<0n)throw new Error("tree sizes must be non-negative");if(0n===t)return!0;if(t===r)return Tb(i,"oldRootHash"),Tb(n,"newRootHash"),i===n&&0===o.length;if(t>r||0===o.length)return!1;const s=o.map((e,t)=>Tb(e,`consistencyPath[${t}]`));var a;0n!==(a=t)&&0n==(a&a-1n)&&s.unshift(Tb(i,"oldRootHash"));let c=t-1n,l=r-1n;for(;1n===vb(c);)c/=2n,l/=2n;const u=globalThis.Buffer.from(s[0]);let d=globalThis.Buffer.from(u),p=globalThis.Buffer.from(u);for(const h of s.slice(1)){if(0n===l)return!1;if(1n===vb(c)||c===l){if(d=Rb(h,d),p=Rb(h,p),0n===vb(c))for(;0n===vb(c)&&0n!==c;)c/=2n,l/=2n}else p=Rb(p,h);c/=2n,l/=2n}return 0n===l&&globalThis.Buffer.from(d).toString("base64")===i&&globalThis.Buffer.from(p).toString("base64")===n}class Ob{constructor(e){this.network=e.network,this.logger=e.logger??y.getInstance({module:"HCS27Client",level:"info"}),this.mirrorNode=new x(this.network,this.logger,e.mirrorNode),this.cdnEndpoint=e.cdnEndpoint?.trim()||void 0,this.hrlResolver=new Wp}buildTopicMemo(e){return yb(e)}parseTopicMemo(e){return bb(e)}buildTransactionMemo(){return"hcs-27:op:0:0"}emptyRoot(){return Ab()}hashLeaf(e){return Cb("string"==typeof e?globalThis.Buffer.from(e,"utf8"):globalThis.Buffer.from(e))}hashNode(e,t){return Rb("string"==typeof e?globalThis.Buffer.from(e,"hex"):globalThis.Buffer.from(e),"string"==typeof t?globalThis.Buffer.from(t,"hex"):globalThis.Buffer.from(t))}merkleRootFromCanonicalEntries(e){return xb(e.map(e=>"string"==typeof e?globalThis.Buffer.from(e,"utf8"):globalThis.Buffer.from(e)))}merkleRootFromEntries(e){return Nb(e)}leafHashHexFromEntry(e){return zb(e)}verifyInclusionProof(e){return _b(e)}verifyConsistencyProof(e){return Pb(e)}async validateCheckpointMessage(e,t,r){const i=r??("string"==typeof e.metadata?void 0:globalThis.Buffer.from(JSON.stringify(e.metadata),"utf8")),n=pb.parse(e),o=t??(e=>this.resolveHCS1Reference(e));let s,a;if("string"==typeof n.metadata?(s=await o(n.metadata),a=mb(ub.parse(JSON.parse(s.toString("utf8"))))):a=mb(ub.parse(n.metadata)),n.metadata_digest){const e=s??i??globalThis.Buffer.from(JSON.stringify(n.metadata),"utf8");if(d.createHash("sha256").update(e).digest("base64url")!==n.metadata_digest.b64u)throw new Error("metadata digest does not match resolved payload")}return a}validateCheckpointChain(e){const t=new Map;for(const r of e){const e=r.effectiveMetadata.stream.registry,i=r.effectiveMetadata.stream.log_id;let n=t.get(e);n||(n=new Map,t.set(e,n));const o=JSON.stringify({registry:e,log_id:i}),s=BigInt(r.effectiveMetadata.root.treeSize),a=n.get(i);if(a){if(s<a.treeSize)throw new Error(`tree size decreased for stream ${o}`);if(s===a.treeSize&&r.effectiveMetadata.root.rootHashB64u!==a.rootHashB64u)throw new Error(`root changed without growing tree size for stream ${o}`);if(!r.effectiveMetadata.prev)throw new Error(`missing prev linkage for stream ${o}`);if(BigInt(r.effectiveMetadata.prev.treeSize)!==a.treeSize)throw new Error(`prev.treeSize mismatch for stream ${o}`);if(r.effectiveMetadata.prev.rootHashB64u!==a.rootHashB64u)throw new Error(`prev.rootHashB64u mismatch for stream ${o}`)}n.set(i,{treeSize:s,rootHashB64u:r.effectiveMetadata.root.rootHashB64u})}}async getCheckpoints(e){const t=await this.mirrorNode.getTopicMessages(e,{order:"asc"}),r=[];for(const n of t)try{const t=pb.parse({p:n.p,op:n.op,metadata:n.metadata,metadata_digest:n.metadata_digest,m:n.m}),i="string"==typeof n.metadata?void 0:globalThis.Buffer.from(JSON.stringify(n.metadata),"utf8"),o=await this.validateCheckpointMessage(t,void 0,i),s=fb(t);r.push({topicId:e,sequence:n.sequence_number,consensusTimestamp:n.consensus_timestamp??"",payer:"string"==typeof n.payer_account_id?n.payer_account_id:n.payer,message:s,effectiveMetadata:o})}catch(i){const e=i instanceof Error?i.message:String(i);this.logger.warn(`Skipping invalid HCS-27 checkpoint message: ${e}`)}return r}async resolveHCS1Reference(e){const t=e.trim();if(!/^hcs:\/\/1\/\d+\.\d+\.\d+$/.test(t))throw new Error(`Invalid HCS-1 reference: ${e}`);const r=await this.hrlResolver.resolveHRL(t,{network:this.network,cdnEndpoint:this.cdnEndpoint,returnRaw:!0});return"string"==typeof r.content?globalThis.Buffer.from(r.content,"utf8"):globalThis.Buffer.from(r.content)}}const Db=1024;const Fb="hcs-26",Mb=t.z.union([t.z.literal(0),t.z.literal(1),t.z.literal(2)]),Ub=t.z.union([t.z.literal(0),t.z.literal(1),t.z.literal(2),t.z.literal(3)]),Bb=t.z.string().regex(/^[0-9]+\.[0-9]+\.[0-9]+$/),Lb=t.z.string().regex(/^hcs:\/\/1\/[0-9]+\.[0-9]+\.[0-9]+$/),Kb=t.z.string().regex(/^(hcs:\/\/1\/[0-9]+\.[0-9]+\.[0-9]+|ipfs:\/\/\S+|ar:\/\/\S+|ord:\/\/\S+)$/),$b=t.z.string().regex(/^v?(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/);const Hb=t.z.string().regex(/^hcs:\/\/1\/[0-9]+\.[0-9]+\.[0-9]+$/).optional(),qb=t.z.union([t.z.string().min(1),t.z.object({name:t.z.string().min(1),contact:t.z.string().min(1).optional(),url:t.z.string().url().optional()}).passthrough()]),jb=t.z.object({name:t.z.string().min(1),description:t.z.string().min(1),author:qb,license:t.z.string().min(1),tags:t.z.array(t.z.union([t.z.number().int().positive(),t.z.string().regex(/^(0|[1-9]\d*)$/).transform(e=>Number.parseInt(e,10))])).optional(),homepage:t.z.string().url().optional(),icon:t.z.union([t.z.string().url(),Kb]).optional(),icon_hcs1:Hb,languages:t.z.array(t.z.string().min(1)).optional(),capabilities:t.z.array(t.z.string().min(1)).optional(),repo:t.z.string().url().optional(),commit:t.z.string().regex(/^[0-9a-f]{7,64}$/i,"commit must be a git commit SHA").optional()}).passthrough(),Wb=jb.partial().passthrough(),Vb=t.z.object({p:t.z.literal(Fb),op:t.z.literal("register"),t_id:Bb,account_id:t.z.string().min(1),metadata:t.z.union([jb,Lb]),m:t.z.string().max(500).optional(),sequence_number:t.z.number().int().optional()}).passthrough(),Gb=t.z.object({p:t.z.literal(Fb),op:t.z.literal("register"),version_registry:Bb,publisher:t.z.string().min(1),metadata:t.z.union([jb,Lb]),m:t.z.string().max(500).optional(),sequence_number:t.z.number().int().optional()}).passthrough(),Jb=t.z.object({p:t.z.literal(Fb),op:t.z.literal("update"),uid:t.z.string().min(1),account_id:t.z.string().min(1).optional(),metadata:t.z.union([Wb,Lb]).optional(),m:t.z.string().max(500).optional(),sequence_number:t.z.number().int().optional()}).passthrough(),Yb=t.z.object({p:t.z.literal(Fb),op:t.z.literal("update"),uid:t.z.string().min(1),publisher:t.z.string().min(1).optional(),metadata:t.z.union([Wb,Lb]).optional(),m:t.z.string().max(500).optional(),sequence_number:t.z.number().int().optional()}).passthrough(),Xb=t.z.object({p:t.z.literal(Fb),op:t.z.literal("delete"),uid:t.z.string().min(1),m:t.z.string().max(500).optional(),sequence_number:t.z.number().int().optional()}).passthrough(),Zb=t.z.object({p:t.z.literal(Fb),op:t.z.literal("migrate"),m:t.z.string().max(500).optional(),sequence_number:t.z.number().int().optional()}).passthrough(),Qb=t.z.string().regex(/^sha256:[0-9a-f]{64}$/),ew=t.z.object({p:t.z.literal(Fb),op:t.z.literal("register"),skill_uid:t.z.number().int().positive(),version:$b,t_id:Bb,checksum:Qb.optional(),status:t.z.enum(["active","deprecated","yanked"]).optional(),m:t.z.string().max(500).optional(),sequence_number:t.z.number().int().optional()}).passthrough(),tw=t.z.object({p:t.z.literal(Fb),op:t.z.literal("register"),skill_uid:t.z.number().int().positive(),version:$b,manifest_hcs1:Lb,checksum:Qb.optional(),status:t.z.enum(["active","deprecated","yanked"]).optional(),m:t.z.string().max(500).optional(),sequence_number:t.z.number().int().optional()}).passthrough(),rw=t.z.object({p:t.z.literal(Fb),op:t.z.literal("update"),uid:t.z.string().min(1),status:t.z.enum(["active","deprecated","yanked"]).optional(),m:t.z.string().max(500).optional(),sequence_number:t.z.number().int().optional()}).passthrough(),iw=t.z.object({p:t.z.literal(Fb),op:t.z.literal("delete"),uid:t.z.string().min(1),m:t.z.string().max(500).optional(),sequence_number:t.z.number().int().optional()}).passthrough(),nw=t.z.object({p:t.z.literal(Fb),op:t.z.literal("migrate"),m:t.z.string().max(500).optional(),sequence_number:t.z.number().int().optional()}).passthrough(),ow=t.z.object({path:t.z.string().min(1).superRefine((e,r)=>{try{!function(e){const t=e.trim();if(!t)throw new Error("Path must be non-empty");if(t.startsWith("/"))throw new Error("Path must be relative");if(t.includes("\\"))throw new Error('Path must use "/" separators');const r=t.split("/");for(const i of r)if(!i||"."===i||".."===i)throw new Error('Path must be normalized (no ".", "..", or empty segments)')}(e)}catch(i){const e=i instanceof Error?i.message:String(i);r.addIssue({code:t.z.ZodIssueCode.custom,message:e})}}),hrl:Lb,sha256:t.z.string().regex(/^[0-9a-f]{64}$/),mime:t.z.string().min(1)}).passthrough(),sw=t.z.object({name:t.z.string().min(1),description:t.z.string().min(1),version:$b,license:t.z.string().min(1),author:qb,tags:t.z.array(t.z.union([t.z.number().int().positive(),t.z.string().regex(/^(0|[1-9]\d*)$/).transform(e=>Number.parseInt(e,10))])).optional(),homepage:t.z.string().url().optional(),languages:t.z.array(t.z.string().min(1)).optional(),repo:t.z.string().url().optional(),commit:t.z.string().regex(/^[0-9a-f]{7,64}$/i,"commit must be a git commit SHA").optional(),entrypoints:t.z.array(t.z.object({path:t.z.string().min(1),language:t.z.string().min(1),args:t.z.array(t.z.string()).optional()}).passthrough()).optional(),files:t.z.array(ow).min(1)}).passthrough().superRefine((e,r)=>{e.files.some(e=>"SKILL.md"===e.path)||r.addIssue({code:t.z.ZodIssueCode.custom,message:'SKILL.md must be present in the manifest files list with path "SKILL.md".',path:["files"]})}),aw=t.z.union([Vb,Gb,Jb,Yb,Xb,Zb]),cw=t.z.union([ew,tw,rw,iw,nw]);function lw(e){const t=e.trim().replace(/^v/i,"").match(/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/);if(!t)return null;const r=Number(t[1]),i=Number(t[2]),n=Number(t[3]);if(![r,i,n].every(Number.isFinite))return null;const o=t[4];return{major:r,minor:i,patch:n,prerelease:o?o.split(".").map(e=>/^(0|[1-9]\d*)$/.test(e)?Number(e):e):[]}}function uw(e,t){if(e.major!==t.major)return e.major-t.major;if(e.minor!==t.minor)return e.minor-t.minor;if(e.patch!==t.patch)return e.patch-t.patch;const r=e.prerelease.length>0,i=t.prerelease.length>0;if(!r&&i)return 1;if(r&&!i)return-1;if(!r&&!i)return 0;const n=Math.max(e.prerelease.length,t.prerelease.length);for(let o=0;o<n;o+=1){const r=e.prerelease[o],i=t.prerelease[o];if(void 0===r&&void 0!==i)return-1;if(void 0!==r&&void 0===i)return 1;if(r!==i){if("number"==typeof r&&"number"==typeof i)return r-i;if("number"==typeof r&&"string"==typeof i)return-1;if("string"==typeof r&&"number"==typeof i)return 1;if("string"==typeof r&&"string"==typeof i)return r<i?-1:1}}return 0}function dw(e){if("string"!=typeof e)return null;const t=e.trim();return t.length>0?t:null}function pw(e,t){return"number"==typeof e?e:"number"==typeof t?t:null}function hw(e){if(!/^\d+$/.test(e))return null;const t=Number(e);return Number.isSafeInteger(t)?t:null}function gw(e,t){if("string"!=typeof e)throw new Error(`Expected ${t} to be a string`);const r=e.trim();if(!r)throw new Error(`Expected ${t} to be a non-empty string`);return r}function mw(e,t){return t?{...e,...t}:e}function fw(e,t){const r="number"==typeof e.sequence_number?e.sequence_number:"number"==typeof t?t:void 0;return"t_id"in e?{p:"hcs-26",op:"register",t_id:gw(e.t_id,"t_id"),account_id:gw(e.account_id,"account_id"),metadata:e.metadata,...e.m?{m:e.m}:{},..."number"==typeof r?{sequence_number:r}:{}}:{p:"hcs-26",op:"register",t_id:gw(e.version_registry,"version_registry"),account_id:gw(e.publisher,"publisher"),metadata:e.metadata,...e.m?{m:e.m}:{},..."number"==typeof r?{sequence_number:r}:{}}}class yw{constructor(e){this.network=e.network,this.logger=e.logger??y.getInstance({module:"HCS26Resolver",level:"info"}),this.mirrorNode=new x(e.network,this.logger,e.mirrorNode),this.hrlResolver=new Wp("warn")}async resolveDiscoveryMetadataHrl(e,t){const r=await this.hrlResolver.resolve(e,{network:this.network,returnRaw:!0}),i=r.content instanceof ArrayBuffer?globalThis.Buffer.from(r.content):globalThis.Buffer.from(String(r.content),"utf8");let n;try{n=JSON.parse(i.toString("utf8"))}catch{throw new Error("Discovery metadata HRL content is not valid JSON")}const o=("full"===t?jb:Wb).safeParse(n);if(!o.success)throw new Error(`Invalid discovery metadata: ${o.error.message}`);return this.normalizeDiscoveryMetadataObject(o.data)}normalizeDiscoveryMetadataObject(e){if("string"!=typeof e.icon||0===e.icon.trim().length){const t=e.icon_hcs1;if("string"==typeof t&&t.trim().length>0)return{...e,icon:t}}return e}async resolveDiscoveryMetadataUri(e,t){const r=e.trim();if(r.startsWith("hcs://1/"))return this.resolveDiscoveryMetadataHrl(r,t);throw new Error(`Unsupported discovery metadata URI: ${r}`)}resolveDiscoveryMetadataObject(e){if("string"==typeof e.metadata)return this.resolveDiscoveryMetadataUri(e.metadata,e.mode);const t=("full"===e.mode?jb:Wb).safeParse(e.metadata);if(!t.success)throw new Error(`Invalid discovery metadata: ${t.error.message}`);return Promise.resolve(this.normalizeDiscoveryMetadataObject(t.data))}async getDiscoveryRegister(e){const t=await this.mirrorNode.getTopicMessages(e.directoryTopicId,{sequenceNumber:`eq:${e.skillUid}`,limit:5,order:"asc"});for(const r of t){const t=Vb.safeParse(r),i=t.success?null:Gb.safeParse(r),n=t.success?t:i&&i.success?i:null;if(!n)continue;const o=fw(n.data,r.sequence_number),s=o.sequence_number;if("number"==typeof s&&s===e.skillUid){const e=await this.resolveDiscoveryMetadataObject({metadata:o.metadata,mode:"full"});return{...o,metadata:e}}}return null}async resolveDiscoveryRecord(e){const t=await this.getDiscoveryRegister({directoryTopicId:e.directoryTopicId,skillUid:e.skillUid});if(!t)return null;const r="number"==typeof e.scanLimit&&e.scanLimit>0?Math.min(5e3,Math.floor(e.scanLimit)):1e3,i=await this.mirrorNode.getTopicMessages(e.directoryTopicId,{limit:r,order:"asc"}),n=String(e.skillUid),o=pw(t.sequence_number,e.skillUid);let s=t;for(const a of i){const e=pw(void 0,a.sequence_number),t=Xb.safeParse(a);if(t.success&&t.data.uid===n){const r=pw(t.data.sequence_number,e);if(null!==o&&null!==r&&r<=o)continue;return null}const r=Jb.safeParse(a),i=r.success?null:Yb.safeParse(a),c=r.success?r:i&&i.success?i:null;if(!c||c.data.uid!==n)continue;const l=pw(c.data.sequence_number,e);if(null!==o&&null!==l&&l<=o)continue;const u="account_id"in c.data?dw(c.data.account_id):dw(c.data.publisher),d=c.data.metadata,p=void 0!==d?await this.resolveDiscoveryMetadataObject({metadata:d,mode:"patch"}):void 0;s={...s,...u?{account_id:u}:{},metadata:mw(s.metadata,p)}}return s}async listVersionRegisters(e){const t="number"==typeof e.limit&&e.limit>0?Math.min(1e3,e.limit):500,r=await this.mirrorNode.getTopicMessages(e.versionRegistryTopicId,{limit:t,order:"desc"}),i=new Map,n=new Map,o=new Map;for(const a of r){const t=ew.safeParse(a),r=t.success?null:tw.safeParse(a),s=t.success?t:r&&r.success?r:null;if(s){if(s.data.skill_uid!==e.skillUid)continue;const t="number"==typeof s.data.sequence_number?String(s.data.sequence_number):"number"==typeof a.sequence_number?String(a.sequence_number):null;if(t){const e=pw(s.data.sequence_number,a.sequence_number);i.set(t,{register:s.data,sequenceNumber:e})}continue}const c=rw.safeParse(a);if(c.success){const e=c.data.uid.trim(),t=n.get(e)??[];t.push({update:c.data,sequenceNumber:pw(c.data.sequence_number,a.sequence_number)}),n.set(e,t);continue}const l=iw.safeParse(a);if(l.success){const e=l.data.uid.trim(),t=o.get(e)??[],r=pw(l.data.sequence_number,a.sequence_number);null!==r&&(t.push(r),o.set(e,t))}}const s=[];for(const[a,c]of i.entries()){const e=c.sequenceNumber??hw(a);if((o.get(a)??[]).some(t=>null===e||t>e))continue;const t=n.get(a);if(!t||0===t.length){s.push(c.register);continue}const r=[...t].filter(t=>null===e||null!==t.sequenceNumber&&t.sequenceNumber>e).sort((e,t)=>(e.sequenceNumber??0)-(t.sequenceNumber??0));if(0===r.length){s.push(c.register);continue}const i=r.reduce((e,t)=>t.update.status?{...e,status:t.update.status}:e,c.register);s.push(i)}return s}async getLatestVersionRegister(e){const t=(await this.listVersionRegisters({versionRegistryTopicId:e.versionRegistryTopicId,skillUid:e.skillUid,limit:100})).filter(e=>{return!(t=e.status)||"active"===t;var t});if(0===t.length)return null;let r=t[0],i=lw(r.version);for(let n=1;n<t.length;n+=1){const e=t[n],o=lw(e.version);if(i||!o){if(i&&o){const t=uw(o,i);if(t>0){r=e,i=o;continue}if(0===t){const t="number"==typeof r.sequence_number?r.sequence_number:0;("number"==typeof e.sequence_number?e.sequence_number:0)>t&&(r=e,i=o)}}}else r=e,i=o}return r}async resolveManifest(e){const t="string"==typeof e.manifestHrl&&e.manifestHrl.trim().length>0?e.manifestHrl.trim():"string"==typeof e.manifestTopicId&&e.manifestTopicId.trim().length>0?`hcs://1/${e.manifestTopicId.trim()}`:null;if(!t)throw new Error("Manifest HRL or topic id is required");const r=await this.hrlResolver.resolve(t,{network:this.network,returnRaw:!0});if(!(r.contentType??"").toLowerCase().startsWith("application/json"))throw new Error(`Expected application/json for manifest, got ${r.contentType??"unknown"}`);const i=r.content instanceof ArrayBuffer?globalThis.Buffer.from(r.content):globalThis.Buffer.from(String(r.content),"utf8"),n=await oh(i,"sha256");let o;try{o=JSON.parse(i.toString("utf8"))}catch{throw new Error("Manifest content is not valid JSON")}const s=sw.safeParse(o);if(!s.success)throw new Error(`Invalid HCS-26 manifest: ${s.error.message}`);if(!s.data.files.some(e=>"SKILL.md"===e.path))throw new Error('HCS-26 manifest must include SKILL.md at path "SKILL.md"');return{manifest:s.data,raw:o,sha256Hex:n}}async verifyVersionRegisterMatchesManifest(e){const t=e.versionRegister.checksum;if(!t)return void this.logger.warn("HCS-26 version register is missing checksum; skipping manifest verification.");const r=t.trim();if(!r.startsWith("sha256:"))throw new Error(`Unsupported checksum: ${r}`);const i=r.slice(7);if(e.manifestSha256Hex!==i)throw new Error(`Manifest checksum mismatch (expected ${i}, got ${e.manifestSha256Hex})`)}}function bw(e){const t=e.trim();if(!t)return null;const r=t.match(/^hcs-26:(\d+):(\d+):(\d+)$/);if(!r)return null;const i=Number(r[1]),n=Number(r[2]),o=Number(r[3]);if(![i,n,o].every(Number.isFinite))return null;const s=Mb.safeParse(o);return s.success?0!==i&&1!==i?null:{protocol:Fb,indexed:0===i,ttlSeconds:n,topicType:s.data}:null}function ww(e){const t=e.trim();if(!t)return null;const r=t.match(/^hcs-26:op:(\d+):(\d+)$/);if(!r)return null;const i=Number(r[1]),n=Number(r[2]);if(![i,n].every(Number.isFinite))return null;const o=Ub.safeParse(i);if(!o.success)return null;const s=Mb.safeParse(n);return s.success?{protocol:Fb,operation:o.data,topicType:s.data}:null}const Iw=t.z.string().transform(e=>{const t=bw(e);if(!t)throw new Error("Invalid HCS-26 topic memo");return t}),Tw=t.z.string().transform(e=>{const t=ww(e);if(!t)throw new Error("Invalid HCS-26 transaction memo");return t});function Sw(e){const t=e.t_id;if("string"==typeof t&&t.trim())return t.trim();const r=e.manifest_hcs1;if("string"!=typeof r||!r.trim())throw new Error("Missing manifest reference in version register entry");const i=r.trim(),n="hcs://1/";if(!i.startsWith(n))throw new Error(`Invalid manifest HRL: ${i}`);return i.slice(8)}class kw{constructor(e){this.network=e.network,this.logger=e.logger??y.getInstance({module:"HCS26Client",level:"info"}),this.verificationProvider=e.verificationProvider,this.resolver=new yw({network:this.network,logger:this.logger,mirrorNode:e.mirrorNode})}async resolveSkill(e){const t=await this.resolver.resolveDiscoveryRecord({directoryTopicId:e.directoryTopicId,skillUid:e.skillUid,scanLimit:e.discoveryScanLimit});if(!t)return null;const r=t.t_id,i=await this.resolver.getLatestVersionRegister({versionRegistryTopicId:r,skillUid:e.skillUid});if(!i)throw new Error(`No active version entries found for skill ${e.skillUid} in version registry ${r}`);const n=Sw(i),{manifest:o,sha256Hex:s}=await this.resolver.resolveManifest({manifestTopicId:n});let a;await this.resolver.verifyVersionRegisterMatchesManifest({versionRegister:i,manifestSha256Hex:s});const c=this.verificationProvider,l=!0===e.includeVerification,u="string"==typeof t.metadata?.name?t.metadata.name.trim():"";if(l&&c&&u)try{a=await c.getSkillVerificationStatus({name:u})}catch(d){const e=d instanceof Error?d.message:String(d);this.logger.warn(`Failed to resolve verification status for skill "${u}": ${e}`),a=null}return{directoryTopicId:e.directoryTopicId,skillUid:e.skillUid,discovery:t,versionRegistryTopicId:r,latestVersion:i,manifest:o,manifestSha256Hex:s,...l?{verification:a}:{}}}async listSkillVersions(e){const t=await this.resolver.resolveDiscoveryRecord({directoryTopicId:e.directoryTopicId,skillUid:e.skillUid,scanLimit:e.discoveryScanLimit});if(!t)return[];const r=t.t_id;return this.resolver.listVersionRegisters({versionRegistryTopicId:r,skillUid:e.skillUid,limit:e.limit})}async resolveSkillVersion(e){const t=e.version.trim();if(!t)throw new Error("version is required");const r=await this.resolver.resolveDiscoveryRecord({directoryTopicId:e.directoryTopicId,skillUid:e.skillUid,scanLimit:e.discoveryScanLimit});if(!r)return null;const i=r.t_id,n=(await this.resolver.listVersionRegisters({versionRegistryTopicId:i,skillUid:e.skillUid,limit:250})).find(e=>e.version.trim()===t);if(!n)return null;const o=Sw(n),{manifest:s,sha256Hex:a}=await this.resolver.resolveManifest({manifestTopicId:o});let c;await this.resolver.verifyVersionRegisterMatchesManifest({versionRegister:n,manifestSha256Hex:a});const l=this.verificationProvider,u=!0===e.includeVerification,d="string"==typeof r.metadata?.name?r.metadata.name.trim():"";if(u&&l&&d)try{c=await l.getSkillVerificationStatus({name:d})}catch(p){const e=p instanceof Error?p.message:String(p);this.logger.warn(`Failed to resolve verification status for skill "${d}": ${e}`),c=null}return{directoryTopicId:e.directoryTopicId,skillUid:e.skillUid,discovery:r,versionRegistryTopicId:i,versionEntry:n,manifest:s,manifestSha256Hex:a,...u?{verification:c}:{}}}}function vw(e){return{getSkillVerificationStatus:async t=>function(e){const t=e.pendingRequest??void 0;return{name:e.name,verified:e.verified,previouslyVerified:e.previouslyVerified,...t?{pendingRequest:t}:{}}}(await Kp(e,{name:t.name}))}}var Ew=(e=>(e.FIXED_FEE="FIXED_FEE",e.FRACTIONAL_FEE="FRACTIONAL_FEE",e.ROYALTY_FEE="ROYALTY_FEE",e))(Ew||{});class Aw{constructor(e){this.customFees=[],this.logger=e.logger,this.mirrorNode=new x(e.network,e.logger),this.defaultCollectorAccountId=e.defaultCollectorAccountId||""}static forHbar(e,t,r,i,n=[]){return new Aw({network:r,logger:i,defaultCollectorAccountId:t}).addHbarFee(e,t,n)}static async forToken(e,t,r,i,n,o=[],s){const a=new Aw({network:i,logger:n,defaultCollectorAccountId:r});return await a.addTokenFee(e,t,r,s,o),a}addHbarFee(e,t,r=[]){if(e<=0)throw new Error("HBAR amount must be greater than zero");return this.customFees.push({feeAmount:{amount:1e8*e,decimals:0},feeCollectorAccountId:t||this.defaultCollectorAccountId,feeTokenId:void 0,exemptAccounts:[...r],type:Ew.FIXED_FEE}),this}async addTokenFee(e,t,r,i,n=[]){if(e<=0)throw new Error("Token amount must be greater than zero");if(!t)throw new Error("Fee token ID is required when adding a token fee");let o=i;if(void 0===o)try{const e=await this.mirrorNode.getTokenInfo(t);e?.decimals?(o=parseInt(e.decimals,10),this.logger.info(`Fetched decimals for ${t}: ${o}`)):(this.logger.warn(`Could not fetch decimals for ${t}, defaulting to 0.`),o=0)}catch(s){this.logger.error(`Error fetching decimals for ${t}, defaulting to 0: ${s}`),o=0}return this.customFees.push({feeAmount:{amount:e*10**o,decimals:o},feeCollectorAccountId:r||this.defaultCollectorAccountId,feeTokenId:t,exemptAccounts:[...n],type:Ew.FIXED_FEE}),this}build(){if(0===this.customFees.length)throw new Error("At least one fee must be added using addHbarFee/addTokenFee or created using forHbar/forToken");if(this.customFees.length>10)throw new Error("Maximum of 10 custom fees per topic allowed");const e=new Set;this.customFees.forEach(t=>{t.exemptAccounts.forEach(t=>e.add(t))});return{customFees:this.customFees.map(e=>({...e,feeCollectorAccountId:e.feeCollectorAccountId||this.defaultCollectorAccountId})),exemptAccounts:Array.from(e)}}}class Cw{constructor(){this.resolver=null,this.onUnavailableCallbacks=[],this.logger=y.getInstance({module:"ContentResolverRegistry"})}static getInstance(){return Cw._instance||(Cw._instance=new Cw),Cw._instance}register(e){this.resolver&&this.logger.warn("Resolver already registered, replacing existing"),this.resolver=e,this.logger.info("Content resolver registered")}getResolver(){return this.resolver}isAvailable(){return null!==this.resolver}unregister(){this.resolver&&(this.resolver=null,this.logger.info("Content resolver unregistered"),this.onUnavailableCallbacks.forEach(e=>{try{e()}catch(t){this.logger.error("Error in unavailable callback:",t)}}))}onUnavailable(e){this.onUnavailableCallbacks.push(e)}offUnavailable(e){const t=this.onUnavailableCallbacks.indexOf(e);-1!==t&&this.onUnavailableCallbacks.splice(t,1)}async withResolver(e,t){if(!this.resolver)return this.logger.warn("No resolver available, using fallback"),await t();try{return await e(this.resolver)}catch(r){return this.logger.warn("Resolver operation failed, using fallback:",r),await t()}}}const Rw=Cw.getInstance();class xw{constructor(){this.contentStore=null,this.logger=y.getInstance({module:"ContentStoreService"})}static getInstance(){return xw._instance||(xw._instance=new xw),xw._instance}async setInstance(e){this.contentStore&&this.logger.warn("Content store already set, replacing"),this.contentStore=e,this.logger.info("Content store instance set")}getInstance(){return this.contentStore}dispose(){this.contentStore=null,this.logger.info("Content store disposed")}isAvailable(){return null!==this.contentStore}}const Nw=xw.getInstance();exports.AIAgentCapability=bh,exports.AIAgentDetailsSchema=Ah,exports.AIAgentProfileSchema=Dh,exports.AIAgentType=fh,exports.AID_DNS_WEB_PROFILE_ID=Pm,exports.ANS_DNS_WEB_PROFILE_ID=Hm,exports.AccountCreationError=og,exports.ActionBuilder=class{constructor(e){this.cryptoAdapter=nh(),this.logger=e,this.registration={p:"hcs-12",op:"register"}}setTopicId(e){if(!this.isValidTopicId(e))throw new Error("Invalid topic ID format");return this.registration.t_id=e,this}setAlias(e){return this.alias=e,this}setHash(e){if(!this.isValidHash(e))throw new Error("Invalid hash format");return this.registration.hash=e,this}setWasmHash(e){if(!this.isValidHash(e))throw new Error("Invalid hash format");return this.registration.wasm_hash=e,this}setInfoTopicId(e){if(!this.isValidTopicId(e))throw new Error("Invalid topic ID format");return this.registration.info_t_id=e,this}setJsTopicId(e){if(!this.isValidTopicId(e))throw new Error("Invalid topic ID format");return this.registration.js_t_id=e,this}setJsHash(e){if(!this.isValidHash(e))throw new Error("Invalid hash format");return this.registration.js_hash=e,this}setInterfaceVersion(e){if(!this.isValidVersion(e))throw new Error("Invalid version format");return this.registration.interface_version=e,this}addValidationRule(e,t){return this.registration.validation_rules||(this.registration.validation_rules={}),this.registration.validation_rules[e]=t,this}setSourceVerification(e){if(!this.isValidTopicId(e.source_t_id))throw new Error("Invalid source topic ID");if(!this.isValidHash(e.source_hash))throw new Error("Invalid source hash");if("wasm32-unknown-unknown"!==e.target)throw new Error("Invalid compilation target");return this.registration.source_verification=e,this}build(e={validate:!0}){return!1!==e.validate&&this.validate(),{...this.registration}}reset(){return this.registration={p:"hcs-12",op:"register"},this.alias=void 0,this}getAlias(){if(!this.alias)throw new Error("Action alias not set");return this.alias}getTopicId(){if(!this.registration.t_id)throw new Error("Action topic ID not set");return this.registration.t_id}async generateWasmHash(e){if(Xp())return this.createSSRSafeHash(e,"wasm");const t=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(e)).digest("hex"),r=t instanceof Promise?await t:t;return"string"==typeof r?r:r.toString("hex")}async generateInfoHash(e){const t=JSON.stringify(e,Object.keys(e).sort());if(Xp())return this.createSSRSafeHash(globalThis.Buffer.from(t),"info");const r=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(t)).digest("hex"),i=r instanceof Promise?await r:r;return"string"==typeof i?i:i.toString("hex")}async calculateHash(e){const t="string"==typeof e||e instanceof Uint8Array?globalThis.Buffer.from(e):e;if(Xp())return this.createSSRSafeHash(t,"data");const r=this.cryptoAdapter.createHash("sha256").update(t).digest("hex"),i=r instanceof Promise?await r:r;return"string"==typeof i?i:i.toString("hex")}createSSRSafeHash(e,t){const r=e instanceof Uint8Array?globalThis.Buffer.from(e):e;let i=0;for(let n=0;n<Math.min(r.length,256);n++)i=(i<<5)-i+r[n]&4294967295;return`ssr-${t}-${r.length}-${Math.abs(i).toString(16).padStart(8,"0")}`}async createFromWasmAndInfo(e,t,r){const i=await this.generateWasmHash(t),n=await this.generateInfoHash(r),o=this.registration.js_t_id,s=this.registration.js_hash,a=this.registration.interface_version;return this.reset().setTopicId(e).setHash(n).setWasmHash(i),o&&this.setJsTopicId(o),s&&this.setJsHash(s),a&&this.setInterfaceVersion(a),this.build()}isComplete(e){return!!("hcs-12"===e.p&&"register"===e.op&&e.t_id&&e.hash&&e.wasm_hash)}validate(){if(!this.registration.t_id)throw new Error("Topic ID is required");if(!this.registration.hash)throw new Error("INFO hash is required");if(!this.registration.wasm_hash)throw new Error("WASM hash is required")}isValidTopicId(e){return/^\d+\.\d+\.\d+$/.test(e)}isValidHash(e){return/^[a-f0-9]{64}$/.test(e)}isValidVersion(e){return/^\d+\.\d+\.\d+$/.test(e)}},exports.ActionRegistry=Ug,exports.AgentBuilder=cg,exports.AidDnsWebProfileResolver=Mm,exports.AnsDnsWebProfileResolver=Vm,exports.AssemblyBuilder=class{constructor(e){this.registration={p:"hcs-12",op:"register"},this.operations=[],this.updateFields={p:"hcs-12",op:"update"},this.logger=e||new y({module:"AssemblyBuilder"})}setName(e){if(!this.isValidName(e))throw new Error("Invalid assembly name format");return this.registration.name=e,this}setVersion(e){if(!this.isValidSemver(e))throw new Error("Invalid semantic version");return this.registration.version=e,this}setDescription(e){return this.registration.description=e,this.updateFields&&(this.updateFields.description=e),this}setTags(e){return this.registration.tags=e,this.updateFields&&(this.updateFields.tags=e),this}addTag(e){return this.registration.tags||(this.registration.tags=[]),this.updateFields.tags||(this.updateFields.tags=[]),this.registration.tags.push(e),this.updateFields.tags.push(e),this}setAuthor(e){return this.registration.author=e,this}addAction(e){const t=e.getTopicId(),r=e.getAlias();if(!this.isValidAlias(r))throw new Error("Invalid alias format");const i={p:"hcs-12",op:"add-action",t_id:t,alias:r};return this.operations.push(i),this}addBlock(e){const t=e.getTopicId();if(!this.isValidTopicId(t))throw new Error(`Invalid block topic ID: ${t}`);const r=e.build(),i=e.getActions(),n=this.extractDefaultAttributes(r.attributes);if(i&&Object.keys(i).length>0)for(const[s,a]of Object.entries(i))if(!this.isValidTopicId(a))throw new Error(`Invalid action topic ID for "${s}": ${a}`);const o={p:"hcs-12",op:"add-block",block_t_id:t,...Object.keys(i).length>0&&{actions:i},attributes:n};return this.operations.push(o),this}updateMetadata(e,t){const r={p:"hcs-12",op:"update",description:e,tags:t};return this.operations.push(r),this}build(){if(!this.registration.name)throw new Error("Assembly name is required");if(!this.registration.version)throw new Error("Assembly version is required");return{...this.registration}}buildUpdate(){const e={p:"hcs-12",op:"update"};return void 0!==this.updateFields.description&&(e.description=this.updateFields.description),void 0!==this.updateFields.tags&&(e.tags=this.updateFields.tags),e}buildOperations(){return[...this.operations]}reset(){return this.registration={p:"hcs-12",op:"register"},this.operations=[],this.updateFields={p:"hcs-12",op:"update"},this}getRegistration(){return this.build()}getOperations(){return this.buildOperations()}buildPreview(){const e=[],t=[];for(const r of this.operations)switch(r.op){case"add-action":e.push({t_id:r.t_id,alias:r.alias,config:r.config,data:r.data});break;case"add-block":t.push({block_t_id:r.block_t_id,actions:r.actions,attributes:r.attributes,children:r.children,data:r.data});break;case"update":r.description&&(this.registration.description=r.description),r.tags&&(this.registration.tags=r.tags)}return{topicId:"",name:this.registration.name,version:this.registration.version,description:this.registration.description,tags:this.registration.tags,author:this.registration.author,actions:e,blocks:t,created:(new Date).toISOString(),updated:(new Date).toISOString()}}validate(){const e=[];this.registration.name||e.push("Assembly name is required"),this.registration.version||e.push("Assembly version is required"),this.registration.version&&!this.isValidSemver(this.registration.version)&&e.push("Invalid semantic version format");const t=new Set;for(const i of this.operations)"add-action"===i.op?(t.has(i.alias)?e.push(`Duplicate alias: ${i.alias}`):t.add(i.alias),this.isValidTopicId(i.t_id)||e.push(`Invalid topic ID for ${i.alias}: ${i.t_id}`),this.isValidAlias(i.alias)||e.push(`Invalid alias format: ${i.alias}`)):"add-block"===i.op&&(this.isValidTopicId(i.block_t_id)||e.push(`Invalid block topic ID: ${i.block_t_id}`));const r=new Set;this.operations.filter(e=>"add-action"===e.op).forEach(e=>r.add(e.alias));for(const i of this.operations)if("add-block"===i.op&&i.actions)for(const[t,r]of Object.entries(i.actions))this.isValidTopicId(r)||e.push(`Block ${i.block_t_id} has invalid action topic ID for key ${t}: ${r}`);return{valid:0===e.length,errors:e}}isValidSemver(e){return/^\d+\.\d+\.\d+(-[\w\.\+]+)?$/.test(e)}isValidTopicId(e){return/^\d+\.\d+\.\d+$/.test(e)}isValidAlias(e){return/^[a-zA-Z][a-zA-Z0-9_-]*$/.test(e)&&e.length>=2&&e.length<=50}isValidName(e){return/^[a-z0-9-]+$/.test(e)&&e.length>=2&&e.length<=100}extractDefaultAttributes(e){if(!e)return{};const t={};for(const[r,i]of Object.entries(e))i&&"object"==typeof i&&"default"in i&&(t[r]=i.default);return t}},exports.AssemblyEngine=$g,exports.AssemblyRegistry=Lg,exports.BaseProfileSchema=Ph,exports.BaseRegistry=wg,exports.BlockBuilder=qg,exports.BlockLoader=Bg,exports.BlockRenderer=class{constructor(e,t,r,i){this.MAX_DEPTH=10,this.logger=e,this.gutenbergBridge=t,this.templateEngine=r,this.stateManager=i,this.hashLinkScanner=new Wg(e)}async render(e,t={}){try{this.currentBlock=e,this.currentOptions=t,t.assembly&&(this.assembly=t.assembly),t.actionRegistry&&(this.actionRegistry=t.actionRegistry),t.network&&!this.wasmExecutor&&(this.wasmExecutor=new jg(this.logger,t.network)),t.initialState&&this.stateManager.setBlockState(e.id,t.initialState);let r=this.stateManager.getBlockState(e.id)||{attributes:{},actionResults:{}};r.attributes&&"object"==typeof r.attributes||(this.logger.warn("Invalid state structure, fixing...",{state:r}),r={attributes:r||{},actionResults:{}});let i={},n=e.attributes||{};if(this.assembly){const t=this.assembly.state?.blocks?.find(t=>t.block_t_id===e.id||t.block_t_id===e.t_id);t&&(i=t.actions||{},n={...t.attributes,...n})}const o={};e.attributes&&Object.entries(e.attributes).forEach(([e,t])=>{t&&"object"==typeof t&&"default"in t&&(o[e]=t.default)});const s={...o};n&&"object"==typeof n&&Object.entries(n).forEach(([e,t])=>{"object"==typeof t&&null!==t||(s[e]=t)}),r.attributes&&"object"==typeof r.attributes&&Object.entries(r.attributes).forEach(([e,t])=>{"object"==typeof t&&null!==t||(s[e]=t)}),r.attributes={...s},this.stateManager.setBlockState(e.id,r);const a={attributes:s,actions:i,blockId:e.id,actionResults:r.actionResults||{}};this.logger.debug("Template context",{blockId:e.id,attributes:a.attributes,hasActions:!!i,actionKeys:Object.keys(i),rawState:r,mergedAttributes:s});let c=await this.templateEngine.render(e.template||"",a);if(this.shouldProcessHashLinks(t)&&(c=await this.processHashLinks(c,e,t)),t.container&&"undefined"!=typeof window){const r="string"==typeof t.container?document.querySelector(t.container):t.container;if(r instanceof HTMLElement)return r.innerHTML=c,e.styles&&this.applyStyles(e.id,e.styles),this.setupEventHandlers(r,e.id),{element:r,html:c,cleanup:()=>this.cleanup(e.id)}}return{html:c}}catch(r){throw this.logger.error("Block render failed",{blockId:e.id,error:r}),r}}applyStyles(e,t){if("undefined"==typeof document)return;const r=`hashlink-styles-${e}`;let i=document.getElementById(r);i||(i=document.createElement("style"),i.id=r,document.head.appendChild(i)),i.textContent=t}setupEventHandlers(e,t){this.stateManager.onStateChange(t,t=>{this.updateBlockUI(e,t)}),e.querySelectorAll("[data-action]").forEach(e=>{e.addEventListener("click",async r=>{r.preventDefault();const i=e.dataset.action,n=e.dataset.params;this.logger.debug("Action button clicked",{actionTopicId:i,paramsStr:n,hasAction:!!i}),i&&await this.executeAction(t,i,n)})})}async updateBlockDisplay(e,t){try{this.logger.debug("updateBlockDisplay called",{blockId:e,newState:t});const r=document.querySelector(`[data-block-id="${e}"]`);if(!r||!r.parentElement)return void this.logger.warn("Block element not found for re-render",{blockId:e});const i=r.parentElement;if(this.currentBlock&&this.currentBlock.id===e&&this.currentOptions){const r={...this.currentOptions,container:i,initialState:t};await this.render(this.currentBlock,r);this.logger.debug("Block re-rendered with updated state",{blockId:e,newState:t})}}catch(r){this.logger.error("Failed to re-render block",{blockId:e,error:r.message})}}async executeAction(e,t,r){try{this.logger.debug("Executing action",{blockId:e,actionTopicId:t});let i={};if(r)try{i=JSON.parse(r)}catch(zw){this.logger.warn("Failed to parse action params",{paramsStr:r})}const n=this.stateManager.getBlockState(e)||{attributes:{},actionResults:{}};if(this.wasmExecutor&&this.actionRegistry){this.logger.debug("Looking up action in registry",{actionTopicId:t});const r=await this.actionRegistry.getActionByTopicId(t);if(this.logger.debug("Action lookup result",{found:!!r,actionTopicId:t,actionData:r}),!r)throw new Error(`Action not found: ${t}`);this.logger.debug("Executing WASM",{actionData:r,params:i,state:n.attributes});const o=await this.wasmExecutor.execute(r,{method:"POST",params:i,state:n.attributes});if(this.logger.debug("WASM execution result",{result:o}),o.success&&o.data){const t=i.operation||"default";let r=o.data;r.success&&r.data&&(r=r.data);const s={...n,attributes:{...n.attributes,...r},actionResults:{...n.actionResults,[t]:r}};this.stateManager.updateBlockState(e,s),await this.updateBlockDisplay(e,s)}else this.logger.error("Action execution failed",{result:o})}else this.stateManager.sendMessage(e,"action",{action:t,params:i})}catch(i){this.logger.error("Failed to execute action",{blockId:e,actionTopicId:t,error:i.message}),this.stateManager.sendMessage(e,"action-error",{action:t,error:i.message})}}updateBlockUI(e,t){Object.entries(t).forEach(([t,r])=>{e.querySelectorAll(`[data-bind="${t}"]`).forEach(e=>{e instanceof HTMLElement&&(e.textContent=String(r))})})}cleanup(e){const t=document.getElementById(`hashlink-styles-${e}`);t&&t.remove(),this.stateManager.removeBlockState(e)}shouldProcessHashLinks(e){const t=e.depth||0,r=e.maxDepth||this.MAX_DEPTH;return t>=r?(this.logger.warn("Max render depth reached, skipping HashLink processing",{depth:t,maxDepth:r}),!1):!(!e.network||!e.blockLoader&&!this.blockLoader)}ensureHashLinkResolver(e){!this.hashLinkResolver&&e.network&&(this.blockLoader=e.blockLoader||this.blockLoader,this.hrlResolver=e.hrlResolver||this.hrlResolver,this.blockLoader&&this.hrlResolver&&(this.hashLinkResolver=new Vg(this.logger,this.blockLoader,this.hrlResolver,e.network)))}async processHashLinks(e,t,r){if(this.ensureHashLinkResolver(r),!this.hashLinkResolver)return this.logger.warn("HashLink resolver not available, skipping processing"),e;this.hashLinkResolver.pushRenderStack(t.id);try{const n=await this.hashLinkScanner.scanTemplate(e);if(0===n.length)return e;this.logger.debug("Processing HashLinks",{parentBlockId:t.id,referenceCount:n.length});const o={blockId:t.id,depth:(r.depth||0)+1,parentContext:r.parentContext,attributes:r.initialState?.attributes||{},actions:{},assembly:this.assembly,maxDepth:r.maxDepth||this.MAX_DEPTH};if(this.assembly){const e=this.assembly.state?.blocks?.find(e=>e.block_t_id===t.id||e.block_t_id===t.t_id);e?.actions&&(o.actions=e.actions)}let s=e;for(let e=0;e<n.length;e++){const t=n[e];try{const e=await this.hashLinkResolver.resolveReference(t,o);if(e.error){this.logger.error("Failed to resolve HashLink",{uri:t.uri,error:e.error});const r=`\x3c!-- HashLink Error: ${e.error} --\x3e`;s=s.replace(t.placeholder,r);continue}let i;if(e.definition){const t={id:e.blockId,template:e.template||"",attributes:e.definition.attributes,p:"hcs-12",op:"register",name:e.definition.name,version:"1.0.0",title:e.definition.title,description:e.definition.description},n={attributes:e.attributes,actionResults:{}},s={attributes:e.attributes,actions:e.actions,blockId:e.blockId,actionResults:{}};if(e.template){i=await this.templateEngine.render(e.template,s);const a={...r,depth:o.depth,parentContext:o,initialState:n};this.shouldProcessHashLinks(a)&&(i=await this.processHashLinks(i,t,a))}else i="\x3c!-- Block has no template --\x3e"}else i=e.template?e.template:"\x3c!-- Empty block --\x3e";"lazy"===t.loading&&(i=this.wrapLazyLoad(i,t)),s=s.replace(t.placeholder,i)}catch(i){this.logger.error("Error processing HashLink",{uri:t.uri,error:i.message});const e=`\x3c!-- HashLink Error: ${i.message} --\x3e`;s=s.replace(t.placeholder,e)}}return s}finally{this.hashLinkResolver.popRenderStack(t.id)}}wrapLazyLoad(e,t){return`\n <div id="${`lazy-${t.uri.replace(/[^a-zA-Z0-9]/g,"-")}`}" class="hashlink-lazy-container" data-hashlink-lazy="${t.uri}">\n <div class="hashlink-lazy-placeholder">Loading...</div>\n <template class="hashlink-lazy-content">${e}</template>\n </div>\n `}},exports.BlockStateManager=class{constructor(e){this.blockStates=new Map,this.stateListeners=new Map,this.messageHandlers=new Map,this.schemas=new Map,this.persistentBlocks=new Set,this.unusedBlocks=new Set,this.maxBlockStates=1e3,this.logger=e}createBlockState(e,t){for(this.logger.debug("Creating block state",{blockId:e}),this.schemas.has(e)&&this.validateState(e,t);this.blockStates.size>=this.maxBlockStates;)this.unusedBlocks.size>0?this.cleanupUnusedStates():this.evictOldestBlock();this.blockStates.set(e,{...t}),this.logger.debug("Block state created",{blockId:e,stateKeys:Object.keys(t)})}getBlockState(e){return this.blockStates.has(e)?{...this.blockStates.get(e)}:null}hasBlockState(e){return this.blockStates.has(e)}updateBlockState(e,t){if(!this.blockStates.has(e))throw new Error(`Block state not found: ${e}`);const r={...this.blockStates.get(e)},i={...r,...t};this.schemas.has(e)&&this.validateState(e,i),this.blockStates.set(e,i);const n=this.stateListeners.get(e)||[];for(const s of n)try{s(i,r,e)}catch(o){this.logger.error("State change listener error",{blockId:e,error:o})}this.logger.debug("Block state updated",{blockId:e,updates:t})}destroyBlockState(e){this.logger.debug("Destroying block state",{blockId:e}),this.blockStates.delete(e),this.stateListeners.delete(e),this.messageHandlers.delete(e),this.schemas.delete(e),this.persistentBlocks.delete(e),this.unusedBlocks.delete(e),this.logger.debug("Block state destroyed",{blockId:e})}onStateChange(e,t){this.stateListeners.has(e)||this.stateListeners.set(e,[]),this.stateListeners.get(e).push(t)}removeStateChangeListener(e,t){const r=this.stateListeners.get(e);if(r){const e=r.indexOf(t);e>-1&&r.splice(e,1)}}onBlockMessage(e,t){this.messageHandlers.has(e)||this.messageHandlers.set(e,[]),this.messageHandlers.get(e).push(t)}sendBlockMessage(e,t,r,i){const n={type:r,payload:i,fromBlock:e,toBlock:t},o=this.messageHandlers.get(t)||[];for(const a of o)try{a(n)}catch(s){this.logger.error("Block message handler error",{fromBlock:e,toBlock:t,type:r,error:s})}this.logger.debug("Block message sent",{fromBlock:e,toBlock:t,type:r})}broadcastMessage(e,t){for(const i of this.blockStates.keys()){const n=this.messageHandlers.get(i)||[],o={type:e,payload:t,fromBlock:"system",toBlock:i};for(const t of n)try{t(o)}catch(r){this.logger.error("Broadcast message handler error",{blockId:i,type:e,error:r})}}this.logger.debug("Message broadcasted",{type:e,blockCount:this.blockStates.size})}async bindActionResult(e,t,r,i){if(!this.blockStates.has(e))throw new Error(`Block state not found: ${e}`);const n=this.getBlockState(e);let o;try{if(r.success&&i.onSuccess)o=i.onSuccess(n,r);else{if(r.success||!i.onError)return;o=i.onError(n,r)}o&&this.updateBlockState(e,o),this.logger.debug("Action result bound to state",{blockId:e,actionName:t,success:r.success})}catch(s){throw this.logger.error("Action result binding failed",{blockId:e,actionName:t,error:s}),s}}async persistBlockState(e){if(!this.storageBackend)return this.logger.warn("No storage backend configured"),void this.persistentBlocks.add(e);if(!this.blockStates.has(e))throw new Error(`Block state not found: ${e}`);try{const t=this.blockStates.get(e);await this.storageBackend.setItem(e,JSON.stringify(t)),this.persistentBlocks.add(e),this.logger.debug("Block state persisted",{blockId:e})}catch(t){this.logger.error("Failed to persist block state",{blockId:e,error:t})}}async restoreBlockState(e){if(this.storageBackend)try{const t=await this.storageBackend.getItem(e);if(t){const r=JSON.parse(t);this.blockStates.set(e,r),this.persistentBlocks.add(e),this.logger.debug("Block state restored",{blockId:e})}}catch(t){this.logger.error("Failed to restore block state",{blockId:e,error:t})}else this.logger.warn("No storage backend configured")}isPersistent(e){return this.persistentBlocks.has(e)}setStorageBackend(e){this.storageBackend=e}setBlockStateSchema(e,t){this.schemas.set(e,t),this.logger.debug("Block state schema set",{blockId:e})}setMaxBlockStates(e){this.maxBlockStates=e}getActiveBlockCount(){return this.blockStates.size}markBlockUnused(e){this.unusedBlocks.add(e)}cleanupUnusedStates(){for(const e of this.unusedBlocks)this.destroyBlockState(e);this.unusedBlocks.clear(),this.logger.debug("Unused states cleaned up")}evictOldestBlock(){for(const e of this.blockStates.keys())if(!this.persistentBlocks.has(e))return this.destroyBlockState(e),void this.logger.debug("Evicted block to make room",{blockId:e});this.logger.warn("Cannot evict blocks - all are persistent")}getListenerCount(e){return(this.stateListeners.get(e)?.length||0)+(this.messageHandlers.get(e)?.length||0)}validateState(e,t){const r=this.schemas.get(e);if(r&&"object"===r.type){if("object"!=typeof t||null===t)throw new Error("State validation failed: expected object");if(r.required)for(const e of r.required)if(!(e in t))throw new Error(`State validation failed: missing required property '${e}'`);if(r.properties)for(const[e,i]of Object.entries(r.properties))if(e in t){const r=t[e],n=i.type;if("string"===n&&"string"!=typeof r)throw new Error(`State validation failed: property '${e}' must be string`);if("number"===n&&"number"!=typeof r)throw new Error(`State validation failed: property '${e}' must be number`);if("number"===n&&void 0!==i.minimum&&r<i.minimum)throw new Error(`State validation failed: property '${e}' below minimum`)}}}setBlockState(e,t){this.blockStates.has(e)?this.updateBlockState(e,t):this.createBlockState(e,t)}removeBlockState(e){this.blockStates.delete(e),this.stateListeners.delete(e),this.messageHandlers.delete(e),this.persistentBlocks.delete(e),this.schemas.delete(e),this.storageBackend&&this.storageBackend.removeItem(e).catch(t=>{this.logger.error("Failed to remove persisted state",{blockId:e,error:t})}),this.logger.debug("Block state removed",{blockId:e})}sendMessage(e,t,r,i="system"){const n=this.messageHandlers.get(e)||[],o={type:t,payload:r,fromBlock:i,toBlock:e};for(const a of n)try{a(o)}catch(s){this.logger.error("Message handler error",{blockId:e,type:t,error:s})}}},exports.BrowserHCS20Client=class extends Gf{constructor(e){super({network:e.network,logger:e.logger,mirrorNodeUrl:e.mirrorNodeUrl,registryTopicId:e.registryTopicId,publicTopicId:e.publicTopicId}),this.hwc=e.hwc,this.feeAmount=e.feeAmount||20}getOperatorId(){const e=this.hwc.getAccountInfo();if(!e?.accountId)throw new Error("Wallet not connected");return e.accountId}async createRegistryTopic(){const e=new xf({hwc:this.hwc,network:this.network}),t=await e.createRegistry();if(!t.success)throw new Error("Failed to create topic");return t.topicId}async deployPoints(e){const t=this.getOperatorId(),{progressCallback:r}=e;try{let i;if(r?.({stage:"creating-topic",percentage:20}),e.usePrivateTopic){const e=await this.mirrorNode.getPublicKey(t),r=new xf({hwc:this.hwc,network:this.network}),n=await r.createRegistry({submitKey:e.toString(),adminKey:e.toString()});if(!n.success)throw new Error("Failed to create topic");i=n.topicId,this.logger.info(`Created private topic: ${i}`)}else i=this.publicTopicId;r?.({stage:"submitting-deploy",percentage:50,topicId:i});const n={p:"hcs-20",op:"deploy",name:e.name,tick:this.normalizeTick(e.tick),max:e.maxSupply,lim:e.limitPerMint,metadata:e.metadata,m:e.topicMemo},o=this.validateMessage(n);if(!o.valid)throw new jf("Invalid deploy message",o.errors);const s=await this.submitPayload(i,n,e.usePrivateTopic),a=s.transactionHash?.toString()||"";return r?.({stage:"confirming",percentage:80,topicId:i,deployTxId:a}),await new Promise(e=>setTimeout(e,2e3)),r?.({stage:"complete",percentage:100,topicId:i,deployTxId:a}),{name:e.name,tick:this.normalizeTick(e.tick),maxSupply:e.maxSupply,limitPerMint:e.limitPerMint,metadata:e.metadata,topicId:i,deployerAccountId:t,currentSupply:"0",deploymentTimestamp:(new Date).toISOString(),isPrivate:e.usePrivateTopic||!1}}catch(i){throw r?.({stage:"complete",percentage:100,error:i instanceof Error?i.message:"Unknown error"}),i}}async mintPoints(e){const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20}),t?.({stage:"submitting",percentage:50});const r={p:"hcs-20",op:"mint",tick:this.normalizeTick(e.tick),amt:e.amount,to:this.accountToString(e.to),m:e.memo},i=e.topicId||this.publicTopicId,n=await this.submitPayload(i,r,!1),o=n.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,mintTxId:o}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,mintTxId:o}),{id:o,operation:"mint",tick:this.normalizeTick(e.tick),amount:e.amount,to:this.accountToString(e.to),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:o,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async transferPoints(e){const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20}),t?.({stage:"submitting",percentage:50});const r={p:"hcs-20",op:"transfer",tick:this.normalizeTick(e.tick),amt:e.amount,from:this.accountToString(e.from),to:this.accountToString(e.to),m:e.memo},i=e.topicId||this.publicTopicId,n=await this.submitPayload(i,r,!1),o=n.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,transferTxId:o}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,transferTxId:o}),{id:o,operation:"transfer",tick:this.normalizeTick(e.tick),amount:e.amount,from:this.accountToString(e.from),to:this.accountToString(e.to),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:o,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async burnPoints(e){const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20}),t?.({stage:"submitting",percentage:50});const r={p:"hcs-20",op:"burn",tick:this.normalizeTick(e.tick),amt:e.amount,from:this.accountToString(e.from),m:e.memo},i=e.topicId||this.publicTopicId,n=await this.submitPayload(i,r,!1),o=n.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,burnTxId:o}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,burnTxId:o}),{id:o,operation:"burn",tick:this.normalizeTick(e.tick),amount:e.amount,from:this.accountToString(e.from),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:o,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async registerTopic(e){const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20});const r={p:"hcs-20",op:"register",name:e.name,metadata:e.metadata,private:e.isPrivate,t_id:this.topicToString(e.topicId),m:e.memo},i=this.validateMessage(r);if(!i.valid)throw new jf("Invalid register message",i.errors);t?.({stage:"submitting",percentage:50});const n=await this.submitPayload(this.registryTopicId,r,!1),o=n.transactionHash?.toString()||"";t?.({stage:"confirming",percentage:80,registerTxId:o}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,registerTxId:o})}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),new Wf(r instanceof Error?r.message:"Unknown error",this.topicToString(e.topicId))}}async submitPayload(e,t,i){let n;this.logger.debug(`Submitting payload to topic ${e}`),n="string"==typeof t?t:JSON.stringify(t);const o=(new r.TopicMessageSubmitTransaction).setTopicId(r.TopicId.fromString(e)).setMessage(n);i&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),o.setMaxTransactionFee(new r.Hbar(this.feeAmount)));const s=await this.hwc.executeTransactionWithErrorHandling(o,!1);if(s?.error)throw this.logger.error(`Failed to submit payload: ${s.error}`),new Error(`Failed to submit payload: ${s.error}`);if(!s?.result)throw this.logger.error("Failed to submit message: receipt is null or undefined"),new Error("Failed to submit message: receipt is null or undefined");return this.logger.debug("Payload submitted successfully via HWC"),s.result}},exports.BrowserHCS2Client=xf,exports.BrowserHCSClient=fg,exports.CanonicalAgentDataSchema=Xg,exports.ConnectionConfirmationError=ag,exports.ConnectionsManager=hg,exports.ContentResolverRegistry=Rw,exports.ContentResolverRegistryImpl=Cw,exports.ContentStoreService=Nw,exports.CustomFeeType=Ew,exports.DiscoveryError=Vy,exports.DiscoveryErrorCodes={INVALID_MESSAGE:"INVALID_MESSAGE",TIMEOUT:"TIMEOUT",INSUFFICIENT_PETALS:"INSUFFICIENT_PETALS",FLORA_CREATION_FAILED:"FLORA_CREATION_FAILED",ALREADY_IN_DISCOVERY:"ALREADY_IN_DISCOVERY",INVALID_STATE:"INVALID_STATE"},exports.DiscoveryOperation=Ky,exports.DiscoveryState=Wy,exports.EVMBridge=class{constructor(e="mainnet-public",t="mirrornode.hedera.com/api/v1/contracts/call",r){this.network=e,this.mirrorNodeUrl=t,this.cache=r||new nc,this.logger=y.getInstance({module:"EVMBridge"})}async executeCommands(e,t={}){let i={...t};const n={};for(const a of e){const e=`${a.c.contractAddress}-${a.c.abi.name}`,t=await this.cache.get(e);if(t)n[a.c.abi.name]=JSON.parse(t),Object.assign(i,n[a.c.abi.name]);else try{const t=new s.ethers.Interface([{...a.c.abi}]),o=t.encodeFunctionData(a.c.abi.name),c=r.ContractId.fromSolidityAddress(a.c.contractAddress),l=await this.readFromMirrorNode(o,r.AccountId.fromString("0.0.800"),c);if(this.logger.info(`Result for ${a.c.contractAddress}:`,l?.result),!l?.result){this.logger.warn(`Failed to get result from mirror node for ${a.c.contractAddress}`),n[a.c.abi.name]="0",Object.assign(i,n[a.c.abi.name]);continue}const u=t?.decodeFunctionResult(a.c.abi.name,l.result);let d={values:[]};u&&a.c.abi.outputs?.forEach((e,t)=>{const r=oc(u[t],e.type);d.values.push(r),e.name&&(d[e.name]=r)}),await this.cache.set(e,JSON.stringify(d)),n[a.c.abi.name]=d,i[a.c.abi.name]=d}catch(o){this.logger.error(`Error executing command for ${a.c.contractAddress}:`,o),n[a.c.abi.name]="0",Object.assign(i,n[a.c.abi.name])}}return{results:n,stateData:i}}async executeCommand(e,t={}){const{results:r,stateData:i}=await this.executeCommands([e],t);return{result:r[e.c.abi.name],stateData:i}}async readFromMirrorNode(e,t,r){try{const i=r.toSolidityAddress(),n=t.toSolidityAddress(),o=await fetch(`https://${this.network}.${this.mirrorNodeUrl}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({block:"latest",data:e,estimate:!1,gas:3e5,gasPrice:1e8,from:n.startsWith("0x")?n:`0x${n}`,to:i?.startsWith("0x")?i:`0x${i}`,value:0})});if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);return await o.json()}catch(i){return this.logger.error("Error reading from mirror node:",i),null}}async clearCache(){await this.cache.clear()}async clearCacheForContract(e,t){await this.cache.delete(`${e}-${t}`)}setLogLevel(e){this.logger.setLogLevel(e)}},exports.EndpointType=yh,exports.FallbackCryptoAdapter=ih,exports.FallbackHashAdapter=Jp,exports.FallbackHmacAdapter=eh,exports.FeeConfigBuilder=Aw,exports.FloraBuilder=dg,exports.FloraError=my,exports.FloraOperation=gy,exports.FloraTopicType=hy,exports.GutenbergBridge=class{constructor(e){this.logger=e}convertToGutenberg(e){if(this.logger.debug("Converting BlockDefinition to Gutenberg format",{name:e.name}),!e||!e.name)throw new Error("Invalid block definition: missing name");const t={apiVersion:e.apiVersion,name:e.name,title:e.title,category:e.category,icon:e.icon,description:e.description,keywords:e.keywords,attributes:e.attributes,supports:e.supports};return t.attributes||(t.attributes={}),t.supports||(t.supports={}),this.logger.debug("Converted to Gutenberg format",{name:t.name,attributeCount:Object.keys(t.attributes).length}),t}parseFromGutenberg(e){if(this.logger.debug("Parsing Gutenberg block to BlockDefinition",{name:e.name}),!e||!e.name)throw new Error("Invalid Gutenberg block: missing name");if(!e.title)throw new Error("Invalid Gutenberg block: missing title");const t={apiVersion:e.apiVersion||3,name:e.name,title:e.title,category:e.category||"common",template_t_id:"",icon:e.icon,description:e.description,keywords:e.keywords,attributes:e.attributes||{},supports:e.supports||{}};return this.logger.debug("Parsed from Gutenberg format",{name:t.name}),t}validateBlockStructure(e){this.logger.debug("Validating block structure",{name:e.name});const t={isValid:!0,errors:[],warnings:[]};return this.validateBasicStructure(e,t),this.validateBlockName(e,t),this.validateAttributes(e,t),this.validateSupports(e,t),this.validateParentChild(e,t),t.isValid=0===t.errors.filter(e=>"critical"===e.severity||"high"===e.severity).length,this.logger.debug("Block structure validation completed",{name:e.name,isValid:t.isValid,errorCount:t.errors.length,warningCount:t.warnings.length}),t}validateBasicStructure(e,t){e.name&&""!==e.name.trim()||t.errors.push({code:"MISSING_NAME",message:"Block name cannot be empty",field:"name",severity:"critical"}),e&&(e.title||t.errors.push({code:"MISSING_TITLE",message:"Block title is required",field:"data.title",severity:"high"}),e.description||t.warnings.push({code:"MISSING_DESCRIPTION",message:"Block description improves usability",field:"data.description",impact:"usability"})),e||t.errors.push({code:"MISSING_BLOCK_JSON",message:"data is required for Gutenberg compatibility",field:"data",severity:"critical"})}validateBlockName(e,t){if(!e.name)return;/^[a-z0-9-]+\/[a-z0-9-]+$/.test(e.name)||t.errors.push({code:"INVALID_BLOCK_NAME",message:"Block name must follow namespace/block-name format (lowercase, hyphens only)",field:"name",severity:"high"}),e&&e.name&&t.warnings.push({code:"NAME_MISMATCH",message:"Block name should match data.name",field:"name",impact:"functionality"})}validateAttributes(e,t){if(!e||!e.attributes)return;const r=e.attributes,i=["string","number","boolean","array","object"];for(const[n,o]of Object.entries(r))o.type?(i.includes(o.type)||t.errors.push({code:"INVALID_ATTRIBUTE_TYPE",message:`Attribute '${n}' has invalid type '${o.type}'`,field:`attributes.${n}.type`,severity:"high"}),o.enum&&o.default&&!o.enum.includes(o.default)&&t.warnings.push({code:"DEFAULT_NOT_IN_ENUM",message:`Attribute '${n}' default value not in enum`,field:`attributes.${n}.default`,impact:"functionality"})):t.errors.push({code:"MISSING_ATTRIBUTE_TYPE",message:`Attribute '${n}' must specify a type`,field:`attributes.${n}.type`,severity:"medium"})}validateSupports(e,t){if(!e||!e.supports)return;const r=e.supports;if(void 0!==r.align)if("boolean"==typeof r.align);else if(Array.isArray(r.align)){const e=["left","center","right","wide","full"],i=r.align.filter(t=>!e.includes(t));i.length>0&&t.warnings.push({code:"INVALID_ALIGNMENT",message:`Invalid alignment values: ${i.join(", ")}`,field:"supports.align",impact:"functionality"})}}validateParentChild(e,t){e&&(e.parent&&t.warnings.push({code:"REQUIRES_PARENT",message:"Block requires a specific parent block",field:"parent",impact:"usability"}),e.provides&&Object.keys(e.provides).length>0&&t.warnings.push({code:"PROVIDES_CONTEXT",message:"Block provides context to child blocks",field:"provides",impact:"functionality"}),e.usesContext&&e.usesContext.length>0&&t.warnings.push({code:"USES_CONTEXT",message:"Block depends on context from parent blocks",field:"usesContext",impact:"functionality"}))}},exports.HCS=w,exports.HCS10BaseClient=rg,exports.HCS10Cache=ig,exports.HCS10Client=gg,exports.HCS11Client=Lh,exports.HCS11ProfileResolver=Sm,exports.HCS11ProfileSchema=Uh,exports.HCS12BaseClient=Hg,exports.HCS12BrowserClient=class extends Hg{constructor(e){super(e),this.hwc=e.hwc,this.updateAccountFromWallet(),this.logger.info("HCS-12 Browser Client initialized",{network:e.network,accountId:this.accountId})}async updateAccountFromWallet(){try{const{accountId:e}=await this.getAccountAndSigner();this.accountId=e}catch(e){this.logger.warn("No active wallet connection")}}async getAccountAndSigner(){const e=this?.hwc?.getAccountInfo(),t=e?.accountId?.toString(),r=this?.hwc?.dAppConnector?.signers?.find(e=>e.getAccountId().toString()===t);if(!r||!t)throw this.logger.error("Failed to find signer",{accountId:t,signers:this?.hwc?.dAppConnector?.signers,accountInfo:e}),new Error("Failed to find signer or account");return{accountId:t,signer:r}}getOperatorAccountId(){throw new Error("Browser client does not have operator account")}getOperatorPrivateKey(){throw new Error("Browser client does not have operator private key")}initializeRegistries(e){super.initializeRegistries(e),this._actionRegistry=new Ug(this.network,this.logger,this.actionRegistryTopicId,this),this._blockLoader=new Bg(this.network,this.logger,this),this._assemblyRegistry=new Lg(this.network,this.logger,this._assemblyRegistryTopicId,this),this._hashLinksRegistry=new Kg(this.network,this.logger,this._hashLinksRegistryTopicId,this),this.logger.info("Registries initialized with signer",{actionTopicId:this.actionRegistryTopicId,assemblyTopicId:this._assemblyRegistryTopicId,hashLinksTopicId:this._hashLinksRegistryTopicId})}async createRegistryTopic(e,t,i){const{accountId:n,signer:o}=await this.getAccountAndSigner(),s={[bg.ACTION]:"hcs-12:1:60:0",[bg.ASSEMBLY]:"hcs-12:1:60:2",[bg.HASHLINKS]:"hcs-12:1:60:3"}[e];this.logger.info("Creating registry topic via wallet",{registryType:bg[e],memo:s,accountId:n});const a=(new r.TopicCreateTransaction).setTopicMemo(s).setTransactionId(r.TransactionId.generate(n));if(t)if("boolean"==typeof t&&t){const e=await o.getAccountKey();a.setAdminKey(e),a.setAutoRenewAccountId(r.AccountId.fromString(n))}else(t instanceof r.PublicKey||t instanceof r.KeyList)&&(a.setAdminKey(t),a.setAutoRenewAccountId(r.AccountId.fromString(n)));if(i)if("boolean"==typeof i&&i){const e=await o.getAccountKey();a.setSubmitKey(e)}else(i instanceof r.PublicKey||i instanceof r.KeyList)&&a.setSubmitKey(i);const c=await a.freezeWithSigner(o),l=await c.executeWithSigner(o),u=await l.getReceiptWithSigner(o);if(!u.topicId)throw new Error("Failed to create topic: topicId is null");const d=u.topicId.toString();switch(this.logger.info("Registry topic created via wallet",{topicId:d,registryType:bg[e]}),e){case bg.ACTION:this.actionRegistryTopicId=d;break;case bg.ASSEMBLY:this._assemblyRegistryTopicId=d;case bg.HASHLINKS:}return d}async createAssemblyTopic(){this.logger.info("Creating new assembly topic");return await this.createRegistryTopic(bg.ASSEMBLY)}async registerAssemblyDirect(e,t){return this.logger.info("Registering assembly",{topicId:e,name:t.name,version:t.version}),this._submitMessage(e,JSON.stringify(t))}async addBlockToAssembly(e,t){return this.logger.info("Adding block to assembly",{assemblyTopicId:e,blockTopicId:t.block_t_id}),this._submitMessage(e,JSON.stringify(t))}async addActionToAssembly(e,t){return this.logger.info("Adding action to assembly",{assemblyTopicId:e,actionTopicId:t.t_id,alias:t.alias}),this._submitMessage(e,JSON.stringify(t))}async updateAssembly(e,t){return this.logger.info("Updating assembly",{assemblyTopicId:e,update:t}),this._submitMessage(e,JSON.stringify(t))}async storeBlock(e,t){if(!this.blockLoader)throw new Error("Block loader not initialized");return this.blockLoader.storeBlock(e,t)}async submitMessage(e,t,r){return this.logger.warn("submitMessage is deprecated. Use operation-specific methods instead."),this._submitMessage(e,t,r)}async _submitMessage(e,t,i){const{accountId:n,signer:o}=await this.getAccountAndSigner();this.logger.debug("Submitting message to topic via wallet",{topicId:e,messageLength:t.length,accountId:n});const s=(new r.TopicMessageSubmitTransaction).setTopicId(r.TopicId.fromString(e)).setMessage(t).setTransactionId(r.TransactionId.generate(n));i&&this.logger.warn("Submit key parameter ignored in browser client - using wallet signer");const a=await s.freezeWithSigner(o),c=await a.executeWithSigner(o),l=await c.getReceiptWithSigner(o);return this.logger.info("Message submitted successfully via wallet",{topicId:e,transactionId:c.transactionId.toString(),sequenceNumber:l.topicSequenceNumber?.toString()}),{transactionId:c.transactionId.toString(),sequenceNumber:l.topicSequenceNumber?Number(l.topicSequenceNumber):void 0}}getHashConnect(){return this.hwc}getAccountId(){return this.accountId}async isConnected(){try{return await this.getAccountAndSigner(),!0}catch{return!1}}async inscribeFile(e,t,r){const{accountId:i,signer:n}=await this.getAccountAndSigner();this.logger.info("Inscribing file via HCS-1 (browser)",{fileName:t});const o=g.lookup(t)||"application/octet-stream",s=await es.createWithAuth({type:"client",accountId:i,signer:n,network:this.network}),a={mode:"file",waitForConfirmation:!0,waitMaxAttempts:r?.waitMaxAttempts||30,waitIntervalMs:r?.waitIntervalMs||4e3,progressCallback:r?.progressCallback,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"},network:this.network},c=await Fa({type:"buffer",buffer:e,fileName:t,mimeType:o},n,a,s);if(!c.confirmed||!c.inscription)throw new Error("Inscription failed to confirm");return c.inscription}async registerAction(e){const t=e.build();if(!this._actionRegistry)throw new Error("Action registry not initialized");const r=await this._submitMessage(this.actionRegistryTopicId,JSON.stringify(t));return this.logger.info("Action registered (browser)",{topicId:t.t_id,transactionId:r.transactionId}),e}async registerBlock(e){const t=e.getTemplate();if(t){const r=await this.inscribeFile(t,`${e.getName()||"block"}-template.html`);e.setTemplateTopicId(r.topic_id)}const r=e.build();if(!r.template_t_id)throw new Error("Block must have either a template buffer (via setTemplate) or template_t_id");const i=await this.inscribeFile(globalThis.Buffer.from(JSON.stringify(r,null,2)),`${r.name}-definition.json`);return this.logger.info("Block registered (browser)",{name:r.name,definitionTopicId:i.topic_id,templateTopicId:r.template_t_id}),e.setTopicId(i.topic_id),e}async createAssembly(e){if(!e)return this.createAssemblyTopic();const t=e.build(),r=await this.createAssemblyTopic();await this.registerAssemblyDirect(r,t);const i=e.getOperations();for(const n of i)switch(n.op){case"add-block":await this.addBlockToAssembly(r,n);break;case"add-action":await this.addActionToAssembly(r,n);break;case"update":await this.updateAssembly(r,n)}return this.logger.info("Assembly created (browser)",{topicId:r,name:t.name,version:t.version,operations:i.length}),r}},exports.HCS12Client=class extends Hg{constructor(e){super(e),this.operatorAccountId=e.operatorId,this.operatorCtx=B({network:this.network,operatorId:this.operatorAccountId,operatorKey:e.operatorPrivateKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:e.client??("mainnet"===e.network?r.Client.forMainnet():r.Client.forTestnet())}),this.client=this.operatorCtx.client,this.logger.info("HCS-12 SDK Client initialized",{network:e.network,operatorId:this.operatorAccountId,keyType:this.operatorCtx.keyType})}initializeRegistries(e){super.initializeRegistries(e),this._actionRegistry=new Ug(this.network,this.logger,this.actionRegistryTopicId,this),this._blockLoader=new Bg(this.network,this.logger,this),this._assemblyRegistry=new Lg(this.network,this.logger,this._assemblyRegistryTopicId,this),this._hashLinksRegistry=new Kg(this.network,this.logger,this._hashLinksRegistryTopicId,this),this.logger.info("Registries initialized",{actionTopicId:this.actionRegistryTopicId,assemblyTopicId:this._assemblyRegistryTopicId,hashLinksTopicId:this._hashLinksRegistryTopicId})}async createRegistryTopic(e,t,r){const i={[bg.ACTION]:"hcs-12:1:60:0",[bg.ASSEMBLY]:"hcs-12:1:60:2",[bg.HASHLINKS]:"hcs-12:1:60:3"}[e];this.logger.info("Creating registry topic",{registryType:bg[e],memo:i});const n=z({memo:i,adminKey:t,submitKey:r,operatorPublicKey:this.client.operatorPublicKey||void 0}),o=await n.execute(this.client),s=await o.getReceipt(this.client);if(!s.topicId)throw new Error("Failed to create topic: topicId is null");const a=s.topicId.toString();switch(this.logger.info("Registry topic created",{topicId:a,registryType:bg[e]}),e){case bg.ACTION:this.actionRegistryTopicId=a;break;case bg.ASSEMBLY:this._assemblyRegistryTopicId=a;case bg.HASHLINKS:}return a}async registerAssemblyDirect(e,t){return this.logger.info("Registering assembly",{topicId:e,name:t.name,version:t.version}),this._submitMessage(e,JSON.stringify(t))}async addBlockToAssembly(e,t){return this.logger.info("Adding block to assembly",{assemblyTopicId:e,blockTopicId:t.block_t_id}),this._submitMessage(e,JSON.stringify(t))}async addActionToAssembly(e,t){return this.logger.info("Adding action to assembly",{assemblyTopicId:e,actionTopicId:t.t_id,alias:t.alias}),this._submitMessage(e,JSON.stringify(t))}async updateAssembly(e,t){return this.logger.info("Updating assembly",{assemblyTopicId:e,update:t}),this._submitMessage(e,JSON.stringify(t))}async submitMessage(e,t,r){return this.logger.warn("submitMessage is deprecated. Use operation-specific methods instead."),this._submitMessage(e,t,r)}async _submitMessage(e,t,r){this.logger.debug("Submitting message to topic",{topicId:e,messageLength:t.length});const i=_({topicId:e,message:t});let n;if(r){const e=i.freezeWith(this.client),t=await e.sign(r);n=await t.execute(this.client)}else n=await i.execute(this.client);const o=await n.getReceipt(this.client);return this.logger.info("Message submitted successfully",{topicId:e,transactionId:n.transactionId.toString(),sequenceNumber:o.topicSequenceNumber?.toString()}),{transactionId:n.transactionId.toString(),sequenceNumber:o.topicSequenceNumber?Number(o.topicSequenceNumber):void 0}}getClient(){return this.client}getOperatorAccountId(){return this.operatorAccountId}getOperatorPrivateKey(){return this.operatorCtx.operatorKey.toString()}async inscribeFile(e,t,r){this.logger.info("Inscribing file via HCS-1",{fileName:t});const i=g.lookup(t)||"application/octet-stream",n=await es.createWithAuth({type:"server",accountId:this.operatorAccountId,privateKey:this.operatorCtx.operatorKey.toString(),network:this.network}),o={mode:"file",waitForConfirmation:!0,waitMaxAttempts:r?.waitMaxAttempts||30,waitIntervalMs:r?.waitIntervalMs||4e3,progressCallback:r?.progressCallback,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},s=await Oa({type:"buffer",buffer:e,fileName:t,mimeType:i},{accountId:this.operatorAccountId,privateKey:this.operatorCtx.operatorKey,network:this.network},o,n);if(!s.confirmed||!s.inscription)throw new Error("Inscription failed to confirm");return s.inscription}async createAssemblyTopic(){if(!this._assemblyRegistry)throw new Error("Assembly registry not initialized");return this._assemblyRegistry.createAssemblyTopic()}async registerAction(e){const t=e.build();if(!this._actionRegistry)throw new Error("Action registry not initialized");const r=await this._submitMessage(this.actionRegistryTopicId,JSON.stringify(t));return this.logger.info("Action registered",{topicId:t.t_id,transactionId:r.transactionId}),e}async registerBlock(e){const t=e.getTemplate();if(t){const r=await this.inscribeFile(t,`${e.getName()||"block"}-template.html`);e.setTemplateTopicId(r.topic_id)}const r=e.build();if(!r.template_t_id)throw new Error("Block must have either a template buffer (via setTemplate) or template_t_id");const i=await this.inscribeFile(globalThis.Buffer.from(JSON.stringify(r,null,2)),`${r.name}-definition.json`);return this.logger.info("Block registered",{name:r.name,definitionTopicId:i.topic_id,templateTopicId:r.template_t_id}),e.setTopicId(i.topic_id),e}async createAssembly(e){const t=e.build(),r=await this.createAssemblyTopic();await this.registerAssemblyDirect(r,t);const i=e.getOperations();for(const n of i)switch(n.op){case"add-block":await this.addBlockToAssembly(r,n);break;case"add-action":await this.addActionToAssembly(r,n);break;case"update":await this.updateAssembly(r,n)}return this.logger.info("Assembly created",{topicId:r,name:t.name,version:t.version,operations:i.length}),r}},exports.HCS14Client=lf,exports.HCS14_PROTOCOL_REGEX=Yg,exports.HCS15BaseClient=py,exports.HCS15BrowserClient=class extends py{constructor(e){super(e),this.signer=e.signer||e.hwc?.dAppConnector?.signers?.[0]}requireSigner(){if(!this.signer)throw new Error("HCS-15 Browser client requires an active signer");return this.signer}async createBaseAccount(e){const t=this.requireSigner(),i=r.PrivateKey.generateECDSA(),n=i.publicKey,o=uy({publicKey:n,initialBalance:new r.Hbar(e?.initialBalance??10),maxAutomaticTokenAssociations:e?.maxAutomaticTokenAssociations,accountMemo:e?.accountMemo,transactionMemo:e?.transactionMemo}),s=await o.freezeWithSigner(t),a=await s.executeWithSigner(t),c=await a.getReceiptWithSigner(t),l=c?.accountId?.toString?.(),u=`0x${n.toEvmAddress()}`;return this.logger.info("Created HCS-15 base account (browser)",{accountId:l,evmAddress:u}),{accountId:l,privateKey:i,privateKeyHex:i.toStringRaw(),publicKey:n,evmAddress:u}}async createPetalAccount(e){const t=this.requireSigner(),i=dy({publicKey:("string"==typeof e.basePrivateKey?r.PrivateKey.fromStringECDSA(e.basePrivateKey):e.basePrivateKey).publicKey,initialBalance:new r.Hbar(e.initialBalance??1),maxAutomaticTokenAssociations:e.maxAutomaticTokenAssociations,accountMemo:e.accountMemo,transactionMemo:e.transactionMemo}),n=await i.freezeWithSigner(t),o=await n.executeWithSigner(t),s=await o.getReceiptWithSigner(t),a=s?.accountId?.toString?.();return this.logger.info("Created HCS-15 petal account (browser)",{accountId:a}),{accountId:a}}},exports.HCS15Client=class extends py{constructor(e){super(e),this.operatorId=r.AccountId.fromString(e.operatorId),this.operatorCtx=B({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:e.client??("mainnet"===this.network?r.Client.forMainnet():r.Client.forTestnet())}),this.client=this.operatorCtx.client}getKeyType(){return this.operatorCtx.keyType}async close(){try{this.client.close()}catch{}}async ensureOperatorReady(){await this.operatorCtx.ensureInitialized()}async createBaseAccount(e){await this.ensureOperatorReady();const t=r.PrivateKey.generateECDSA(),i=t.publicKey,n=uy({publicKey:i,initialBalance:new r.Hbar(e?.initialBalance??10),maxAutomaticTokenAssociations:e?.maxAutomaticTokenAssociations,accountMemo:e?.accountMemo,transactionMemo:e?.transactionMemo}),o=await n.execute(this.client),s=await o.getReceipt(this.client);if(!s.accountId)throw new Error("HCS-15 BASE_ACCOUNT_CREATE_FAILED");const a=s.accountId.toString(),c=`0x${i.toEvmAddress()}`;return this.logger.info("Created HCS-15 base account",{accountId:a,evmAddress:c}),{accountId:a,privateKey:t,privateKeyHex:t.toStringRaw(),publicKey:i,evmAddress:c,receipt:s}}async createPetalAccount(e){await this.ensureOperatorReady();const t="string"==typeof e.basePrivateKey?r.PrivateKey.fromStringECDSA(e.basePrivateKey):e.basePrivateKey,i=dy({publicKey:t.publicKey,initialBalance:new r.Hbar(e.initialBalance??1),maxAutomaticTokenAssociations:e.maxAutomaticTokenAssociations,accountMemo:e.accountMemo,transactionMemo:e.transactionMemo}),n=await i.execute(this.client),o=await n.getReceipt(this.client);if(!o.accountId)throw new Error("HCS-15 PETAL_ACCOUNT_CREATE_FAILED");const s=o.accountId.toString();let a;return this.logger.info("Created HCS-15 petal account",{accountId:s}),e.profile&&(a=await this.createPetalProfile({accountId:s,basePrivateKey:t,profile:e.profile})),{accountId:s,receipt:o,profile:a}}async createPetalProfile(e){const{HCS10Client:t}=await Promise.resolve().then(()=>yg),{PersonBuilder:r}=await Promise.resolve().then(()=>pg),i=new t({network:this.network,operatorId:e.accountId,operatorPrivateKey:e.basePrivateKey.toString(),logLevel:this.logger.getLevel()});try{const t=(new r).setName(e.profile.displayName).setBaseAccount(e.profile.baseAccountId);if(e.profile.alias&&t.setAlias(e.profile.alias),e.profile.bio&&t.setBio(e.profile.bio),e.profile.profileImage&&t.setProfileImage(e.profile.profileImage),e.profile.socials)for(const r of e.profile.socials)t.addSocial(r.platform,r.handle);if(e.profile.properties)for(const[r,i]of Object.entries(e.profile.properties))t.addProperty(r,i);const n=await i.create(t,{ttl:e.profile.ttl??300,updateAccountMemo:!0});if("success"in n&&!1===n.success)throw new Error(n.error??"Failed to create petal profile");const o="inboundTopicId"in n?n.inboundTopicId:"",s="outboundTopicId"in n?n.outboundTopicId:"",a="profileTopicId"in n?n.profileTopicId:"";if(!a)throw new Error("Failed to resolve petal profile topic ID");return{profileTopicId:a,inboundTopicId:o,outboundTopicId:s}}finally{try{i.getClient().close()}catch{}}}},exports.HCS15_BASE_ACCOUNT_CREATE_TRANSACTION_MEMO=ay,exports.HCS15_PETAL_ACCOUNT_CREATE_TRANSACTION_MEMO=cy,exports.HCS16BaseClient=_y,exports.HCS16BrowserClient=class extends _y{constructor(e){super({network:e.network}),this.hwc=e.hwc,this.signer=e.signer}ensureConnected(){if(this.signer&&"function"==typeof this.signer.getAccountId)return this.signer.getAccountId().toString();const e=this.hwc?.getAccountInfo?.(),t=e?.accountId;if(!t)throw new Error("No active wallet connection");return t}getSigner(){if(this.signer)return this.signer;this.ensureConnected();const e=this.hwc?.dAppConnector?.signers?.[0];if(!e)throw new Error("No active wallet signer");return e}async createFloraTopic(e){this.ensureConnected();const t=this.getSigner(),r=ky({floraAccountId:e.floraAccountId,topicType:e.topicType,adminKey:e.adminKey,submitKey:e.submitKey,autoRenewAccountId:e.autoRenewAccountId}),i=await r.freezeWithSigner(t),n=await i.executeWithSigner(t),o=await n.getReceiptWithSigner(t);return o?.topicId?.toString?.()||""}async sendFloraCreated(e){const t=this.getSigner(),r=Ay(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendTransaction(e){const t=this.getSigner(),r=Cy(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async signSchedule(e){const t=this.getSigner(),i=await(new r.ScheduleSignTransaction).setScheduleId(e.scheduleId).freezeWithSigner(t);await i.executeWithSigner(t)}async sendStateUpdate(e){const t=this.getSigner(),r=Ry(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async createFloraAccountWithTopics(e){const t=this.getSigner(),r=await this.assembleKeyList({members:e.members,threshold:e.threshold}),i=await this.assembleSubmitKeyList(e.members),n=vy({keyList:r,initialBalanceHbar:"number"==typeof e.initialBalanceHbar?e.initialBalanceHbar:5,maxAutomaticTokenAssociations:-1}),o=await n.freezeWithSigner(t),s=await o.executeWithSigner(t),a=await s.getReceiptWithSigner(t),c=a?.accountId?.toString?.();if(!c)throw new Error("Failed to create Flora account");const{communication:l,transaction:u,state:d}=this.buildFloraTopicCreateTxs({floraAccountId:c,keyList:r,submitList:i,autoRenewAccountId:e.autoRenewAccountId}),p=await(await(await l.freezeWithSigner(t)).executeWithSigner(t)).getReceiptWithSigner(t),h=await(await(await u.freezeWithSigner(t)).executeWithSigner(t)).getReceiptWithSigner(t),g=await(await(await d.freezeWithSigner(t)).executeWithSigner(t)).getReceiptWithSigner(t);return{floraAccountId:c,topics:{communication:p?.topicId?.toString?.()||"",transaction:h?.topicId?.toString?.()||"",state:g?.topicId?.toString?.()||""}}}async publishFloraCreated(e){const t=this.getSigner(),r=Ay({topicId:e.communicationTopicId,operatorId:e.operatorId,floraAccountId:e.floraAccountId,topics:e.topics}),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendFloraJoinRequest(e){const t=this.getSigner(),r=xy(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendFloraJoinVote(e){const t=this.getSigner(),r=Ny(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendFloraJoinAccepted(e){const t=this.getSigner(),r=zy(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}},exports.HCS16Client=class extends _y{constructor(e){super({network:e.network,logger:e.logger}),this.operatorId=r.AccountId.fromString(e.operatorId);const t=new x(e.network,this.logger);this.operatorCtx=B({network:e.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:t,logger:this.logger,client:e.client??("mainnet"===e.network?r.Client.forMainnet():r.Client.forTestnet())}),this.client=this.operatorCtx.client}async ensureOperatorReady(){await this.operatorCtx.ensureInitialized()}async createFloraTopic(e){await this.ensureOperatorReady();const t=ky({floraAccountId:e.floraAccountId,topicType:e.topicType,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:this.client.operatorPublicKey||void 0,autoRenewAccountId:e.autoRenewAccountId}),r=e.signerKeys??[];if(r.length>0){let e=await t.freezeWith(this.client);for(const t of r)e=await e.sign(t);const i=await e.execute(this.client),n=await i.getReceipt(this.client);if(!n.topicId)throw new Error("Failed to create Flora topic");return n.topicId.toString()}const i=await t.execute(this.client),n=await i.getReceipt(this.client);if(!n.topicId)throw new Error("Failed to create Flora topic");return n.topicId.toString()}async createFloraAccount(e){await this.ensureOperatorReady();const t=vy({keyList:e.keyList,initialBalanceHbar:e.initialBalanceHbar,maxAutomaticTokenAssociations:e.maxAutomaticTokenAssociations}),r=await t.execute(this.client),i=await r.getReceipt(this.client);if(!i.accountId)throw new Error("Failed to create Flora account");return{accountId:i.accountId.toString(),receipt:i}}async sendFloraCreated(e){await this.ensureOperatorReady();const t=Ay(e);return(await t.execute(this.client)).getReceipt(this.client)}async sendTransaction(e){await this.ensureOperatorReady();const t=Cy(e);return(await t.execute(this.client)).getReceipt(this.client)}async signSchedule(e){await this.ensureOperatorReady();const t=await(new r.ScheduleSignTransaction).setScheduleId(e.scheduleId).freezeWith(this.client),i=await t.sign(e.signerKey);return(await i.execute(this.client)).getReceipt(this.client)}async sendStateUpdate(e){await this.ensureOperatorReady();const t=Ry({topicId:e.topicId,operatorId:e.operatorId,hash:e.hash,epoch:e.epoch,accountId:e.accountId,topics:e.topics,memo:e.memo,transactionMemo:e.transactionMemo});if(e.signerKeys&&e.signerKeys.length>0){let r=await t.freezeWith(this.client);for(const t of e.signerKeys)r=await r.sign(t);return(await r.execute(this.client)).getReceipt(this.client)}return(await t.execute(this.client)).getReceipt(this.client)}async sendFloraJoinRequest(e){await this.ensureOperatorReady();const t=xy(e);if(e.signerKey){const r=await t.freezeWith(this.client),i=await r.sign(e.signerKey);return(await i.execute(this.client)).getReceipt(this.client)}return(await t.execute(this.client)).getReceipt(this.client)}async sendFloraJoinVote(e){await this.ensureOperatorReady();const t=Ny(e);if(e.signerKey){const r=await t.freezeWith(this.client),i=await r.sign(e.signerKey);return(await i.execute(this.client)).getReceipt(this.client)}return(await t.execute(this.client)).getReceipt(this.client)}async sendFloraJoinAccepted(e){await this.ensureOperatorReady();const t=zy(e);if(e.signerKeys&&e.signerKeys.length>0){let r=await t.freezeWith(this.client);for(const t of e.signerKeys)r=await r.sign(t);return(await r.execute(this.client)).getReceipt(this.client)}return(await t.execute(this.client)).getReceipt(this.client)}async assembleKeyList(e){return super.assembleKeyList(e)}async createFloraAccountWithTopics(e){await this.ensureOperatorReady();const t=await this.assembleKeyList({members:e.members,threshold:e.threshold}),r=await this.assembleSubmitKeyList(e.members),i=vy({keyList:t,initialBalanceHbar:"number"==typeof e.initialBalanceHbar?e.initialBalanceHbar:5,maxAutomaticTokenAssociations:-1}),n=await i.execute(this.client),o=await n.getReceipt(this.client);if(!o.accountId)throw new Error("Failed to create Flora account");const s=o.accountId.toString(),{communication:a,transaction:c,state:l}=this.buildFloraTopicCreateTxs({floraAccountId:s,keyList:t,submitList:r,autoRenewAccountId:e.autoRenewAccountId}),u=await a.execute(this.client).then(e=>e.getReceipt(this.client)),d=await c.execute(this.client).then(e=>e.getReceipt(this.client)),p=await l.execute(this.client).then(e=>e.getReceipt(this.client));return{floraAccountId:s,topics:{communication:u.topicId.toString(),transaction:d.topicId.toString(),state:p.topicId.toString()}}}async createFloraProfile(e){if(await this.ensureOperatorReady(),0===e.signerKeys.length)throw new Error("Flora profile creation requires signer keys");const t={version:"1.0",type:3,display_name:e.displayName,members:e.members,threshold:e.threshold,topics:e.topics,inboundTopicId:e.inboundTopicId??e.topics.communication,outboundTopicId:e.outboundTopicId??e.topics.transaction,bio:e.bio,metadata:e.metadata,policies:e.policies},r=new Lh({network:this.network,auth:{operatorId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey.toString()},logLevel:this.logger.getLevel()});try{await r.initializeOperator();const i=await r.inscribeProfile(t);if(!i.success)throw new Error(i.error??"Failed to inscribe Flora profile");const n=await r.updateAccountMemoWithProfile(e.floraAccountId,i.profileTopicId,e.signerKeys);if(!n.success)throw new Error(n.error??"Failed to update Flora account memo");return{profileTopicId:i.profileTopicId,transactionId:i.transactionId}}finally{try{r.getClient().close()}catch{}}}async publishFloraCreated(e){await this.ensureOperatorReady();const t=Ay({topicId:e.communicationTopicId,operatorId:e.operatorId,floraAccountId:e.floraAccountId,topics:e.topics});return(await t.execute(this.client)).getReceipt(this.client)}},exports.HCS16_ACCOUNT_KEY_UPDATE_TRANSACTION_MEMO=by,exports.HCS16_FLORA_ACCOUNT_CREATE_TRANSACTION_MEMO=fy,exports.HCS16_TOPIC_KEY_UPDATE_TRANSACTION_MEMO=wy,exports.HCS17BaseClient=Uy,exports.HCS17BrowserClient=class extends Uy{constructor(e){super(e),this.hwc=e.hwc,this.signer=e.signer}ensureConnected(){if(this.signer&&"function"==typeof this.signer.getAccountId)return this.signer.getAccountId().toString();const e=this.hwc?.getAccountInfo?.(),t=e?.accountId;if(!t)throw new Error("No active wallet connection");return t}getSigner(){if(this.signer)return this.signer;this.ensureConnected();const e=this.hwc?.dAppConnector?.signers?.[0];if(!e)throw new Error("No active wallet signer");return e}async createStateTopic(e){this.ensureConnected();const t=this.getSigner(),r=By({ttl:e?.ttl??86400}),i=await r.freezeWithSigner(t),n=await i.executeWithSigner(t),o=await n.getReceiptWithSigner(t),s=o?.topicId?.toString?.()||"";return this.logger.info(`Created HCS-17 state topic via wallet: ${s}`),s}async submitMessage(e,t){const{valid:r,errors:i}=this.validateMessage(t);if(!r)throw new Error(`Invalid HCS-17 message: ${i.join(", ")}`);const n=this.getSigner(),o=Ly({topicId:e,stateHash:t.state_hash,accountId:t.account_id,topics:t.topics,memo:t.m}),s=await o.freezeWithSigner(n),a=await s.executeWithSigner(n);return await a.getReceiptWithSigner(n),{}}async computeAndPublish(e){this.ensureConnected();const t=this.getSigner(),r=[];for(const a of e.topics){const e=(await this.mirrorNode.getTopicMessages(a,{limit:1,order:"desc"}))[0],t=e&&e.running_hash||"";r.push({topicId:a,latestRunningHash:t})}const i={accountId:e.accountId,publicKey:e.accountPublicKey,topics:r},n=this.calculateAccountStateHash(i),o=Ly({topicId:e.publishTopicId,stateHash:n.stateHash,accountId:e.accountId,topics:e.topics,memo:e.memo}),s=await o.freezeWithSigner(t);return await s.executeWithSigner(t),{stateHash:n.stateHash}}},exports.HCS17Client=class extends Uy{constructor(e){super(e),this.operatorId=r.AccountId.fromString(e.operatorId),this.operatorCtx=B({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:e.client??("mainnet"===e.network?r.Client.forMainnet():r.Client.forTestnet())}),this.client=this.operatorCtx.client}getKeyType(){return this.operatorCtx.keyType}async createStateTopic(e){const t=By({ttl:e?.ttl??86400,adminKey:e?.adminKey,submitKey:e?.submitKey,operatorPublicKey:this.client.operatorPublicKey||void 0}),r=await t.execute(this.client),i=await r.getReceipt(this.client);if(!i.topicId)throw new Error("Failed to create topic: topicId empty");const n=i.topicId.toString();return this.logger.info(`Created HCS-17 state topic ${n}`),n}async submitMessage(e,t){const{valid:r,errors:i}=this.validateMessage(t);if(!r)throw new Error(`Invalid HCS-17 message: ${i.join(", ")}`);const n=Ly({topicId:e,stateHash:t.state_hash,accountId:t.account_id,topics:t.topics,memo:t.m,epoch:t.epoch,timestamp:t.timestamp}),o=await n.execute(this.client);return await o.getReceipt(this.client)}async computeAndPublish(e){const t=[];for(const a of e.topics){const e=(await this.mirrorNode.getTopicMessages(a,{limit:1,order:"desc"}))[0],r=e?.running_hash||"";t.push({topicId:a,latestRunningHash:r})}const r={accountId:e.accountId,publicKey:e.accountPublicKey,topics:t},i=this.calculateAccountStateHash(r);this.createStateHashMessage(i.stateHash,e.accountId,e.topics,e.memo);const n=Ly({topicId:e.publishTopicId,stateHash:i.stateHash,accountId:e.accountId,topics:e.topics,memo:e.memo}),o=await n.execute(this.client),s=await o.getReceipt(this.client);return{stateHash:i.stateHash,receipt:s}}},exports.HCS17TopicType=Dy,exports.HCS17_STATE_HASH_TRANSACTION_MEMO=yy,exports.HCS18BaseClient=rb,exports.HCS18BrowserClient=class{constructor(e){this.hwc=e.hwc}async submit(e,t){return await this.hwc.submitMessageToTopic(e,JSON.stringify(t))}async announce(e){const t=Xy(e.data);return this.submit(e.discoveryTopicId,t)}async propose(e){const t=Zy(e.data);return this.submit(e.discoveryTopicId,t)}async respond(e){const t=Qy(e.data);return this.submit(e.discoveryTopicId,t)}async complete(e){const t=eb(e.data);return this.submit(e.discoveryTopicId,t)}async withdraw(e){const t=tb(e.data);return this.submit(e.discoveryTopicId,t)}},exports.HCS18Client=class extends rb{constructor(e){super({network:e.network,logger:y.getInstance({level:e.logLevel||"info",module:"HCS-18",silent:e.silent})}),this.operatorCtx=B({network:this.network,operatorId:e.operatorId,operatorKey:e.operatorKey,mirrorNode:this.mirrorNode,logger:this.logger,client:e.client??r.Client.forName(this.network)}),this.client=this.operatorCtx.client}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}async createDiscoveryTopic(e){await this.ensureInitialized();const t=e?.ttlSeconds;let r;try{r=this.operatorCtx.operatorKey.publicKey}catch{r=void 0}const i=Jy({ttlSeconds:t,adminKey:e?.adminKey,submitKey:e?.submitKey,operatorPublicKey:r,memoOverride:e?.memoOverride}),n=await i.execute(this.client),o=await n.getReceipt(this.client),s=o.topicId?.toString();if(!s)throw new Error("Failed to create discovery topic");return{topicId:s,receipt:o}}async announce(e){await this.ensureInitialized();const t=Xy(e.data),r=Yy({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client),n=await i.getReceipt(this.client),o=n.topicSequenceNumber.toNumber();return{receipt:n,sequenceNumber:o}}async propose(e){await this.ensureInitialized();const t=Zy(e.data),r=Yy({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client),n=await i.getReceipt(this.client),o=n.topicSequenceNumber.toNumber();return{receipt:n,sequenceNumber:o}}async respond(e){await this.ensureInitialized();const t=Qy(e.data),r=Yy({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client);return await i.getReceipt(this.client)}async complete(e){await this.ensureInitialized();const t=eb(e.data),r=Yy({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client);return await i.getReceipt(this.client)}async withdraw(e){await this.ensureInitialized();const t=tb(e.data),r=Yy({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client);return await i.getReceipt(this.client)}},exports.HCS20BaseClient=Gf,exports.HCS20BurnMessageSchema=Mf,exports.HCS20Client=class extends Gf{constructor(e){super(e),this.operatorAccountId="string"==typeof e.operatorId?r.AccountId.fromString(e.operatorId):e.operatorId,this.operatorId=this.operatorAccountId.toString();const t=e.client??("mainnet"===this.network?r.Client.forMainnet():r.Client.forTestnet());this.operatorCtx=B({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:t}),this.client=this.operatorCtx.client,this.operatorCtx.ensureInitialized()}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}async submitPayload(e,t){let i;if(t){const r=e.freezeWith(this.client),n=await r.sign(t);i=await n.execute(this.client)}else i=await e.execute(this.client);const n=await i.getReceipt(this.client);if(!n||n.status!==r.Status.Success)throw new Error("Failed to submit message to topic");return{receipt:n,transactionId:i.transactionId.toString()}}async createPublicTopic(e){await this.ensureInitialized(),this.logger.info("Creating public HCS-20 topic...");const t=await(new r.TopicCreateTransaction).setTopicMemo(e||"HCS-20 Public Topic").execute(this.client),i=await t.getReceipt(this.client);if(i.status!==r.Status.Success||!i.topicId)throw new Error("Failed to create public topic");const n=i.topicId.toString();return this.logger.info(`Created public topic: ${n}`),this.publicTopicId=n,n}async createRegistryTopic(){await this.ensureInitialized(),this.logger.info("Creating HCS-20 registry topic...");const e=new Rf({operatorId:this.operatorId,operatorKey:this.operatorCtx.operatorKey,network:this.network,client:this.client}),t=await e.createRegistry({submitKey:this.operatorCtx.operatorKey,adminKey:this.operatorCtx.operatorKey});if(!t.success)throw new Error("Failed to create registry topic");const r=t.topicId;return this.logger.info(`Created registry topic: ${r}`),this.registryTopicId=r,r}async deployPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{let r;t?.({stage:"creating-topic",percentage:20});const i=new Rf({operatorId:this.operatorId,operatorKey:this.operatorCtx.operatorKey,network:this.network,client:this.client});if(e.usePrivateTopic){const t=await i.createRegistry({submitKey:this.operatorCtx.operatorKey,adminKey:this.operatorCtx.operatorKey});if(!t.success)throw new $f("Failed to create topic",e.tick);r=t.topicId,this.logger.info(`Created private topic: ${r}`)}else r=this.publicTopicId;t?.({stage:"submitting-deploy",percentage:50,topicId:r});const n={p:"hcs-20",op:"deploy",name:e.name,tick:this.normalizeTick(e.tick),max:e.maxSupply,lim:e.limitPerMint,metadata:e.metadata,m:e.topicMemo},o=this.validateMessage(n);if(!o.valid)throw new jf("Invalid deploy message",o.errors);const s=Jf({topicId:r,name:e.name,tick:e.tick,max:e.maxSupply,lim:e.limitPerMint,metadata:e.metadata,memo:e.topicMemo}),{transactionId:a}=await this.submitPayload(s);t?.({stage:"confirming",percentage:80,topicId:r,deployTxId:a}),await this.waitForMirrorNodeConfirmation(r,a),t?.({stage:"complete",percentage:100,topicId:r,deployTxId:a});return{name:e.name,tick:this.normalizeTick(e.tick),maxSupply:e.maxSupply,limitPerMint:e.limitPerMint,metadata:e.metadata,topicId:r,deployerAccountId:this.operatorId,currentSupply:"0",deploymentTimestamp:(new Date).toISOString(),isPrivate:e.usePrivateTopic||!1}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async mintPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20});const r=this.normalizeTick(e.tick);t?.({stage:"submitting",percentage:50});const i=e.topicId?this.topicToString(e.topicId):this.publicTopicId,n=Yf({topicId:i,tick:e.tick,amt:e.amount,to:this.accountToString(e.to),memo:e.memo}),{transactionId:o}=await this.submitPayload(n);t?.({stage:"confirming",percentage:80,mintTxId:o}),e.disableMirrorCheck||await this.waitForMirrorNodeConfirmation(i,o),t?.({stage:"complete",percentage:100,mintTxId:o});return{id:o,operation:"mint",tick:r,amount:e.amount,to:this.accountToString(e.to),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:o,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async transferPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20});const r=this.normalizeTick(e.tick),i=this.accountToString(e.from),n=this.accountToString(e.to);if(i!==this.operatorId)throw new Hf("For public topics, transaction payer must match sender",e.tick,i,n,e.amount);t?.({stage:"submitting",percentage:50});const o=e.topicId?this.topicToString(e.topicId):this.publicTopicId,s=Xf({topicId:o,tick:e.tick,amt:e.amount,from:i,to:n,memo:e.memo}),{transactionId:a}=await this.submitPayload(s);t?.({stage:"confirming",percentage:80,transferTxId:a}),await this.waitForMirrorNodeConfirmation(o,a),t?.({stage:"complete",percentage:100,transferTxId:a});return{id:a,operation:"transfer",tick:r,amount:e.amount,from:i,to:n,timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:o,transactionId:a,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async burnPoints(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating-balance",percentage:20});const r=this.normalizeTick(e.tick),i=this.accountToString(e.from);if(i!==this.operatorId)throw new qf("For public topics, transaction payer must match burner",e.tick,i,e.amount);t?.({stage:"submitting",percentage:50});const n=e.topicId?this.topicToString(e.topicId):this.publicTopicId,o=Zf({topicId:n,tick:e.tick,amt:e.amount,from:i,memo:e.memo}),{transactionId:s}=await this.submitPayload(o);t?.({stage:"confirming",percentage:80,burnTxId:s}),await this.waitForMirrorNodeConfirmation(n,s),t?.({stage:"complete",percentage:100,burnTxId:s});return{id:s,operation:"burn",tick:r,amount:e.amount,from:i,timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:n,transactionId:s,memo:e.memo}}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async registerTopic(e){await this.ensureInitialized();const{progressCallback:t}=e;try{t?.({stage:"validating",percentage:20});const r={p:"hcs-20",op:"register",name:e.name,metadata:e.metadata,private:e.isPrivate,t_id:this.topicToString(e.topicId),m:e.memo},i=this.validateMessage(r);if(!i.valid)throw new jf("Invalid register message",i.errors);if(!this.registryTopicId)throw new $f("Registry topic not available",e.name);t?.({stage:"submitting",percentage:50});const n=Qf({registryTopicId:this.registryTopicId,name:e.name,topicId:this.topicToString(e.topicId),isPrivate:e.isPrivate,metadata:e.metadata,memo:e.memo}),{transactionId:o}=await this.submitPayload(n,this.operatorCtx.operatorKey);t?.({stage:"confirming",percentage:80,registerTxId:o}),await this.waitForMirrorNodeConfirmation(this.registryTopicId,o),t?.({stage:"complete",percentage:100,registerTxId:o}),this.logger.info(`Registered topic ${e.topicId} in registry`)}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),r}}async waitForMirrorNodeConfirmation(e,t,r=10){for(let n=0;n<r;n++){try{const r=await this.mirrorNode.getTopicMessages(e,{limit:10,order:"desc"});if(r.some(e=>{if("object"!=typeof e||null===e)return!1;return"string"==typeof e.consensus_timestamp}))return void this.logger.debug(`Transaction ${t} confirmed on mirror node`)}catch(i){this.logger.debug(`Mirror node check attempt ${n+1} failed:`,i)}await b(2e3)}this.logger.warn(`Transaction ${t} not found on mirror node after ${r} attempts`)}},exports.HCS20DeployMessageSchema=Df,exports.HCS20Error=Kf,exports.HCS20MessageSchema=Lf,exports.HCS20MintMessageSchema=Ff,exports.HCS20PointsIndexer=class{constructor(e,t,r){this.isProcessing=!1,this.lastIndexedSequence=new Map,this.logger=t||new y({level:"info",module:"HCS20PointsIndexer"}),this.mirrorNode=new x(e,this.logger,{customUrl:r}),this.state=this.initializeState()}initializeState(){return{deployedPoints:new Map,balances:new Map,transactions:[],lastProcessedSequence:0,lastProcessedTimestamp:(new Date).toISOString()}}getState(){return{...this.state,deployedPoints:new Map(this.state.deployedPoints),balances:new Map(this.state.balances),transactions:[...this.state.transactions]}}getPointsInfo(e){return this.state.deployedPoints.get(this.normalizeTick(e))}getBalance(e,t){const r=this.normalizeTick(e),i=this.state.balances.get(r);if(!i)return"0";const n=i.get(t);return n?.balance||"0"}async startIndexing(e){if(this.isProcessing)return void this.logger.warn("Indexing already in progress");this.isProcessing=!0;const t=!1!==e?.includePublicTopic,r=!1!==e?.includeRegistryTopic,i=t?e?.publicTopicId||Nf.PUBLIC_TOPIC_ID:null,n=r?e?.registryTopicId||Nf.REGISTRY_TOPIC_ID:null,o=e?.pollInterval||3e4;await this.indexTopics(i,n,e?.privateTopics);const s=async()=>{if(this.isProcessing){try{await this.indexTopics(i,n,e?.privateTopics)}catch(t){this.logger.error("Polling error:",t)}this.isProcessing&&setTimeout(s,o)}};setTimeout(s,o)}async indexOnce(e){const t=!1!==e?.includePublicTopic,r=!1!==e?.includeRegistryTopic,i=t?e?.publicTopicId||Nf.PUBLIC_TOPIC_ID:null,n=r?e?.registryTopicId||Nf.REGISTRY_TOPIC_ID:null;await this.indexTopics(i,n,e?.privateTopics)}stopIndexing(){this.isProcessing=!1,this.logger.info("Indexing stopped")}async indexTopics(e,t,r){this.logger.debug("Starting indexing cycle"),e&&await this.indexTopic(e,!1);const i=[...t?await this.getRegisteredTopics(t):[],...r||[]];for(const n of i)await this.indexTopic(n,!0);this.logger.debug("Indexing cycle complete")}async getRegisteredTopics(e){const t=[];try{(await this.mirrorNode.getTopicMessages(e,{limit:100,order:"asc"})).filter(e=>"hcs-20"===e.p&&"register"===e.op&&"string"==typeof e.t_id).forEach(e=>{t.push(e.t_id)})}catch(r){this.logger.error("Failed to fetch registry messages:",r)}return t}async indexTopic(e,t){try{const r=this.lastIndexedSequence.get(e);this.logger.debug(`Indexing topic ${e}, starting from sequence ${r||0}`);const i=await this.mirrorNode.getTopicMessages(e,{sequenceNumber:r?r+1:void 0,limit:1e3,order:"asc"});this.logger.debug(`Fetched ${i.length} messages from topic ${e}`);let n=r||0;for(const o of i){if("hcs-20"!==o.p)continue;const r=Lf.safeParse(o);if(!r.success){this.logger.debug("Skipping message due to schema mismatch");continue}const i=r.data,s=o.sequence_number??0;this.logger.debug(`Found HCS-20 message: op=${i.op}, sequence=${s}`),s>n&&(n=s);const a={consensus_timestamp:o.consensus_timestamp??"",sequence_number:s,payer_account_id:o.payer_account_id??o.payer??"",transaction_id:o.transaction_id??""};this.processMessage(i,a,e,t),this.state.lastProcessedSequence++,this.state.lastProcessedTimestamp=o.consensus_timestamp||""}n>(r||0)&&this.lastIndexedSequence.set(e,n)}catch(r){this.logger.error(`Failed to index topic ${e}:`,r)}}processMessage(e,t,r,i){switch(e.op){case"deploy":this.processDeployMessage(e,t,r,i);break;case"mint":this.processMintMessage(e,t,r,i);break;case"transfer":this.processTransferMessage(e,t,r,i);break;case"burn":this.processBurnMessage(e,t,r,i)}}processDeployMessage(e,t,r,i){const n=this.normalizeTick(e.tick);if(this.state.deployedPoints.has(n))return;const o={name:e.name,tick:n,maxSupply:e.max,limitPerMint:e.lim,metadata:e.metadata,topicId:r,deployerAccountId:t.payer_account_id,currentSupply:"0",deploymentTimestamp:t.consensus_timestamp,isPrivate:i};this.state.deployedPoints.set(n,o),this.logger.info(`Deployed points: ${n}`)}processMintMessage(e,t,r,i){const n=this.normalizeTick(e.tick),o=this.state.deployedPoints.get(n);if(!o)return;const s=BigInt(e.amt),a=BigInt(o.currentSupply);if(a+s>BigInt(o.maxSupply))return;if(o.limitPerMint&&s>BigInt(o.limitPerMint))return;o.currentSupply=(a+s).toString();let c=this.state.balances.get(n);c||(c=new Map,this.state.balances.set(n,c));const l=c.get(e.to),u=l?(BigInt(l.balance)+s).toString():e.amt;c.set(e.to,{tick:n,accountId:e.to,balance:u,lastUpdated:t.consensus_timestamp}),this.state.transactions.push({id:t.transaction_id||`${r}-${t.sequence_number}`,operation:"mint",tick:n,amount:e.amt,to:e.to,timestamp:t.consensus_timestamp,sequenceNumber:t.sequence_number,topicId:r,transactionId:t.transaction_id||"",memo:e.m})}processTransferMessage(e,t,r,i){const n=this.normalizeTick(e.tick),o=this.state.balances.get(n);if(!o)return;if(!i&&t.payer_account_id!==e.from)return;const s=o.get(e.from);if(!s||BigInt(s.balance)<BigInt(e.amt))return;const a=BigInt(e.amt);s.balance=(BigInt(s.balance)-a).toString(),s.lastUpdated=t.consensus_timestamp;const c=o.get(e.to);c?(c.balance=(BigInt(c.balance)+a).toString(),c.lastUpdated=t.consensus_timestamp):o.set(e.to,{tick:n,accountId:e.to,balance:e.amt,lastUpdated:t.consensus_timestamp}),this.state.transactions.push({id:t.transaction_id||`${r}-${t.sequence_number}`,operation:"transfer",tick:n,amount:e.amt,from:e.from,to:e.to,timestamp:t.consensus_timestamp,sequenceNumber:t.sequence_number,topicId:r,transactionId:t.transaction_id||"",memo:e.m})}processBurnMessage(e,t,r,i){const n=this.normalizeTick(e.tick),o=this.state.deployedPoints.get(n),s=this.state.balances.get(n);if(!o||!s)return;if(!i&&t.payer_account_id!==e.from)return;const a=s.get(e.from);if(!a||BigInt(a.balance)<BigInt(e.amt))return;const c=BigInt(e.amt);a.balance=(BigInt(a.balance)-c).toString(),a.lastUpdated=t.consensus_timestamp,o.currentSupply=(BigInt(o.currentSupply)-c).toString(),this.state.transactions.push({id:t.transaction_id||`${r}-${t.sequence_number}`,operation:"burn",tick:n,amount:e.amt,from:e.from,timestamp:t.consensus_timestamp,sequenceNumber:t.sequence_number,topicId:r,transactionId:t.transaction_id||"",memo:e.m})}normalizeTick(e){return e.toLowerCase().trim()}},exports.HCS20RegisterMessageSchema=Bf,exports.HCS20TransferMessageSchema=Uf,exports.HCS20_CONSTANTS=Nf,exports.HCS21BaseClient=ny,exports.HCS21BrowserClient=class extends ny{constructor(e){super({network:e.network,logger:e.logger}),this.hwc=e.hwc}async createRegistryTopic(e){const{publicKey:t}=await this.getSignerContext(),i=ry({ttl:e.ttl,indexed:e.indexed,type:e.type,metaTopicId:e.metaTopicId,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:t});e.transactionMemo&&i.setTransactionMemo(e.transactionMemo);const{receipt:n}=await this.executeWithWallet(i);if(n.status!==r.Status.Success||!n.topicId)throw new ey("Failed to create HCS-21 registry topic","invalid_payload");return n.topicId.toString()}async createAdapterVersionPointerTopic(e){const{publicKey:t}=await this.getSignerContext(),i=vf({registryType:mf.NON_INDEXED,ttl:e.ttl,adminKey:e.adminKey,submitKey:e.submitKey,memoOverride:e.memoOverride,operatorPublicKey:t});e.transactionMemo&&i.setTransactionMemo(e.transactionMemo);const{receipt:n}=await this.executeWithWallet(i);if(n.status!==r.Status.Success||!n.topicId)throw new ey("Failed to create HCS-2 registry version topic","invalid_payload");return n.topicId.toString()}async createRegistryDiscoveryTopic(e){const{publicKey:t}=await this.getSignerContext(),i=vf({registryType:mf.INDEXED,ttl:e.ttl,adminKey:e.adminKey,submitKey:e.submitKey,memoOverride:e.memoOverride,operatorPublicKey:t});e.transactionMemo&&i.setTransactionMemo(e.transactionMemo);const{receipt:n}=await this.executeWithWallet(i);if(n.status!==r.Status.Success||!n.topicId)throw new ey("Failed to create registry-of-registries topic","invalid_payload");return n.topicId.toString()}async createAdapterCategoryTopic(e){const{publicKey:t}=await this.getSignerContext(),i=ry({ttl:e.ttl,indexed:e.indexed??0,type:gc.ADAPTER_CATEGORY,metaTopicId:e.metaTopicId,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:t});e.transactionMemo&&i.setTransactionMemo(e.transactionMemo);const{receipt:n}=await this.executeWithWallet(i);if(n.status!==r.Status.Success||!n.topicId)throw new ey("Failed to create adapter category topic","invalid_payload");return n.topicId.toString()}async publishVersionPointer(e){const t=Ef({registryTopicId:e.versionTopicId,targetTopicId:e.declarationTopicId,memo:e.memo,analyticsMemo:e.transactionMemo}),{receipt:i,transactionId:n}=await this.executeWithWallet(t);if(i.status!==r.Status.Success)throw new ey("Failed to publish registry version pointer","invalid_payload");return{sequenceNumber:this.toNumber(i.topicSequenceNumber),transactionId:n}}async resolveVersionPointer(e){const[t]=await this.mirrorNode.getTopicMessages(e,{limit:1,order:"desc"});if(!t)throw new ey("Version pointer topic has no messages","invalid_payload");const r=t.t_id;if("string"!=typeof r||0===r.length)throw new ey("Version pointer topic does not include a declaration topic ID (`t_id`)","invalid_payload");const i="number"==typeof t.sequence_number?t.sequence_number:Number(t.sequence_number);return{versionTopicId:e,declarationTopicId:r,sequenceNumber:Number.isFinite(i)?i:0,payer:t.payer,memo:t.m,op:t.op}}async registerCategoryTopic(e){const t=Ef({registryTopicId:e.discoveryTopicId,targetTopicId:e.categoryTopicId,metadata:e.metadata,memo:e.memo,analyticsMemo:e.transactionMemo}),{receipt:i,transactionId:n}=await this.executeWithWallet(t);if(i.status!==r.Status.Success)throw new ey("Failed to register adapter category topic","invalid_payload");return{sequenceNumber:this.toNumber(i.topicSequenceNumber),transactionId:n}}async publishCategoryEntry(e){const t=e.memo??`adapter:${e.adapterId}`,i=Ef({registryTopicId:e.categoryTopicId,targetTopicId:e.versionTopicId,metadata:e.metadata,memo:t,analyticsMemo:e.transactionMemo}),{receipt:n,transactionId:o}=await this.executeWithWallet(i);if(n.status!==r.Status.Success)throw new ey("Failed to publish adapter category entry","invalid_payload");return{sequenceNumber:this.toNumber(n.topicSequenceNumber),transactionId:o}}async publishDeclaration(e){const t="p"in e.declaration?this.validateDeclaration(e.declaration):this.buildDeclaration(e.declaration),i=iy({topicId:e.topicId,declaration:t,transactionMemo:e.transactionMemo}),{receipt:n,transactionId:o}=await this.executeWithWallet(i);if(n.status!==r.Status.Success)throw new ey("Failed to submit HCS-21 declaration","invalid_payload");return{sequenceNumber:this.toNumber(n.topicSequenceNumber),transactionId:o}}async fetchDeclarations(e,t){const{messages:r=[]}=await this.hwc.getMessages(e),i=[];for(const s of r)if(s&&"hcs-21"===s.p)try{const e=this.validateDeclaration(s);i.push({declaration:e,consensusTimestamp:s.consensus_timestamp,sequenceNumber:Number(s.sequence_number??0),payer:s.payer})}catch(o){const e=o instanceof Error?o.message:"unknown error";this.logger.warn(`Skipping invalid HCS-21 browser message: ${e}`)}const n="desc"===t?.order?[...i].sort((e,t)=>t.sequenceNumber-e.sequenceNumber):i;return t?.limit&&t.limit>0?n.slice(0,t.limit):n}async getSignerContext(){if(this.signerCache)return this.signerCache;const e=this.hwc.getAccountInfo?.(),t="string"==typeof e?e:e?.accountId;if(!t)throw new ey("Wallet is not connected","invalid_payload");const i=await this.hwc.requestAccount(t),n=i?.key?.key;if(!n)throw new ey("Unable to resolve wallet public key","invalid_payload");const o=r.PublicKey.fromString(n);return this.signerCache={accountId:t,publicKey:o},this.signerCache}async executeWithWallet(e){const{accountId:t}=await this.getSignerContext(),i=r.TransactionId.generate(r.AccountId.fromString(t));e.setTransactionId(i);return{receipt:await this.hwc.executeTransaction(e,!1),transactionId:i.toString()}}toNumber(e){return"number"==typeof e?e:e&&"function"==typeof e.toNumber?e.toNumber():void 0}},exports.HCS21Client=class extends ny{constructor(e){const t=e.logger||new y({level:e.logLevel||"info",module:"HCS-21"});super({network:e.network,logger:t,mirrorNodeUrl:e.mirrorNodeUrl});const i=e.client??("mainnet"===e.network?r.Client.forMainnet():r.Client.forTestnet());this.operatorCtx=B({network:e.network,operatorId:e.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:i}),this.operatorCtx.ensureInitialized(),this.client=this.operatorCtx.client}async inscribeMetadata(e){await this.operatorCtx.ensureInitialized();const t=Ic.parse(e.document),r=JSON.stringify(t,null,2),i=globalThis.Buffer.from(r,"utf8"),n={waitForConfirmation:!0,connectionMode:e.inscriptionOptions?.connectionMode??(!1===e.inscriptionOptions?.websocket?"http":"auto"),websocket:e.inscriptionOptions?.websocket??!1,...e.inscriptionOptions||{},metadata:{...e.inscriptionOptions?.metadata||{},...t}},o=await Oa({type:"buffer",buffer:i,fileName:e.fileName||`hcs21-adapter-manifest-${Date.now()}.json`,mimeType:"application/json"},{accountId:this.operatorCtx.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},n);if(!o.confirmed||!o.inscription)throw new ey("Failed to inscribe HCS-21 metadata","invalid_payload");const s=o.inscription.jsonTopicId||o.inscription.topic_id||Ha(o.inscription);if(!s)throw new ey("Metadata inscription did not return a topic ID","invalid_payload");const a=o.inscription.sequence_number??o.inscription.sequenceNumber,c=await this.resolveManifestPointer(s,a),l=o.result?.manifest_sequence,u=o.result&&"jobId"in o.result?{jobId:o.result.jobId,transactionId:o.result.transactionId,totalCostHbar:o.costSummary?.totalCostHbar,costBreakdown:o.costSummary?.breakdown}:{};return{pointer:c.pointer,topicId:s,sequenceNumber:c.sequenceNumber,manifestSequence:l||c.sequenceNumber,...u}}async createRegistryTopic(e){await this.operatorCtx.ensureInitialized();const t=ry({ttl:e.ttl,indexed:e.indexed,type:e.type,metaTopicId:e.metaTopicId,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:this.operatorCtx.operatorKey.publicKey});e.transactionMemo&&t.setTransactionMemo(e.transactionMemo);const i=await t.execute(this.client),n=await i.getReceipt(this.client);if(n.status!==r.Status.Success||!n.topicId)throw new ey("Failed to create HCS-21 registry topic","invalid_payload");return n.topicId.toString()}async createAdapterVersionPointerTopic(e){await this.operatorCtx.ensureInitialized();const t=vf({registryType:mf.NON_INDEXED,ttl:e.ttl,adminKey:e.adminKey,submitKey:e.submitKey,memoOverride:e.memoOverride,operatorPublicKey:this.operatorCtx.operatorKey.publicKey});e.transactionMemo&&t.setTransactionMemo(e.transactionMemo);const i=await t.execute(this.client),n=await i.getReceipt(this.client);if(n.status!==r.Status.Success||!n.topicId)throw new ey("Failed to create HCS-2 registry version topic","invalid_payload");return n.topicId.toString()}async createRegistryDiscoveryTopic(e){await this.operatorCtx.ensureInitialized();const t=vf({registryType:mf.INDEXED,ttl:e.ttl,adminKey:e.adminKey,submitKey:e.submitKey,memoOverride:e.memoOverride,operatorPublicKey:this.operatorCtx.operatorKey.publicKey});e.transactionMemo&&t.setTransactionMemo(e.transactionMemo);const i=await t.execute(this.client),n=await i.getReceipt(this.client);if(n.status!==r.Status.Success||!n.topicId)throw new ey("Failed to create registry-of-registries topic","invalid_payload");return n.topicId.toString()}async createAdapterCategoryTopic(e){await this.operatorCtx.ensureInitialized();const t=ry({ttl:e.ttl,indexed:e.indexed??0,type:gc.ADAPTER_CATEGORY,metaTopicId:e.metaTopicId,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:this.operatorCtx.operatorKey.publicKey});e.transactionMemo&&t.setTransactionMemo(e.transactionMemo);const i=await t.execute(this.client),n=await i.getReceipt(this.client);if(n.status!==r.Status.Success||!n.topicId)throw new ey("Failed to create adapter category topic","invalid_payload");return n.topicId.toString()}async publishVersionPointer(e){await this.operatorCtx.ensureInitialized();const t=Ef({registryTopicId:e.versionTopicId,targetTopicId:e.declarationTopicId,memo:e.memo,analyticsMemo:e.transactionMemo}),i=await t.execute(this.client),n=await i.getReceipt(this.client);if(n.status!==r.Status.Success)throw new ey("Failed to publish registry version pointer","invalid_payload");return{sequenceNumber:n.topicSequenceNumber?.toNumber(),transactionId:i.transactionId.toString()}}async resolveVersionPointer(e){const[t]=await this.mirrorNode.getTopicMessages(e,{limit:1,order:"desc"});if(!t)throw new ey("Version pointer topic has no messages","invalid_payload");const r=t.t_id;if("string"!=typeof r||0===r.length)throw new ey("Version pointer topic does not include a declaration topic ID (`t_id`)","invalid_payload");const i="number"==typeof t.sequence_number?t.sequence_number:Number(t.sequence_number);return{versionTopicId:e,declarationTopicId:r,sequenceNumber:Number.isFinite(i)?i:0,payer:t.payer,memo:t.m,op:t.op}}async registerCategoryTopic(e){await this.operatorCtx.ensureInitialized();const t=Ef({registryTopicId:e.discoveryTopicId,targetTopicId:e.categoryTopicId,metadata:e.metadata,memo:e.memo,analyticsMemo:e.transactionMemo}),i=await t.execute(this.client),n=await i.getReceipt(this.client);if(n.status!==r.Status.Success)throw new ey("Failed to register adapter category topic","invalid_payload");return{sequenceNumber:n.topicSequenceNumber?.toNumber(),transactionId:i.transactionId.toString()}}async publishCategoryEntry(e){await this.operatorCtx.ensureInitialized();const t=e.memo??`adapter:${e.adapterId}`,i=Ef({registryTopicId:e.categoryTopicId,targetTopicId:e.versionTopicId,metadata:e.metadata,memo:t,analyticsMemo:e.transactionMemo}),n=await i.execute(this.client),o=await n.getReceipt(this.client);if(o.status!==r.Status.Success)throw new ey("Failed to publish adapter category entry","invalid_payload");return{sequenceNumber:o.topicSequenceNumber?.toNumber(),transactionId:n.transactionId.toString()}}async publishDeclaration(e){await this.operatorCtx.ensureInitialized();const t=this.normalizeDeclarationInput(e.declaration),i=iy({topicId:e.topicId,declaration:t,transactionMemo:e.transactionMemo}),n=await i.execute(this.client),o=await n.getReceipt(this.client);if(o.status!==r.Status.Success)throw new ey("Failed to submit HCS-21 declaration","invalid_payload");return{sequenceNumber:o.topicSequenceNumber?.toNumber(),transactionId:n.transactionId.toString()}}normalizeDeclarationInput(e){return"p"in e?this.validateDeclaration(e):this.buildDeclaration(e)}async resolveManifestPointer(e,t){const r="string"==typeof t?Number(t):t;let i="number"==typeof r&&Number.isFinite(r)?r:void 0;if(!i){const[t]=await this.mirrorNode.getTopicMessages(e,{limit:1,order:"desc"});if(!t||!t.sequence_number)throw new ey("Unable to resolve manifest sequence number","invalid_payload");i=Number(t.sequence_number)}if(!Number.isFinite(i))throw new ey("Invalid manifest sequence number","invalid_payload");const n=`hcs://1/${e}`;if(!pc.test(n))throw new ey("Manifest pointer format is invalid","invalid_payload");return{pointer:n,sequenceNumber:i}}},exports.HCS21ManifestPointerPattern=pc,exports.HCS21MetadataPointerPattern=hc,exports.HCS21TopicIdPattern=/^0\.0\.\d+$/,exports.HCS21TopicType=gc,exports.HCS21ValidationError=ey,exports.HCS21_MAX_MESSAGE_BYTES=uc,exports.HCS21_PROTOCOL=lc,exports.HCS21_SAFE_MESSAGE_BYTES=dc,exports.HCS26BaseClient=kw,exports.HCS26BrowserClient=class extends kw{constructor(e){super({network:e.network,logger:e.logger,mirrorNode:e.mirrorNode,verificationProvider:e.verificationProvider})}},exports.HCS26Client=class extends kw{constructor(e){const t=e.verificationProvider??(e.registryBrokerClient?vw(e.registryBrokerClient):void 0);super({network:e.network,logger:e.logger,mirrorNode:e.mirrorNode,verificationProvider:t})}},exports.HCS26_DEFAULT_TTL_SECONDS=86400,exports.HCS26_PROTOCOL=Fb,exports.HCS27BaseClient=Ob,exports.HCS27Client=class extends Ob{constructor(e){super(e),this.topicSubmitKeySigners=new Map,this.operatorId="string"==typeof e.operatorId?r.AccountId.fromString(e.operatorId):e.operatorId;let t=e.client;t||(t="mainnet"===e.network?r.Client.forMainnet():r.Client.forTestnet()),this.operatorCtx=B({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:t}),this.client=this.operatorCtx.client}getKeyType(){return this.operatorCtx.keyType}async createCheckpointTopic(e={}){await this.operatorCtx.ensureInitialized();const t=(new r.TopicCreateTransaction).setTopicMemo(this.buildTopicMemo(e.ttl)),i=this.resolveTopicKeyMaterial(e.adminKey);this.assertSignableTopicKey(e.adminKey,i,"adminKey"),i.publicKey&&t.setAdminKey(i.publicKey);const n=this.resolveTopicKeyMaterial(e.submitKey);let o;if(this.assertSignableTopicKey(e.submitKey,n,"submitKey"),n.publicKey&&t.setSubmitKey(n.publicKey),e.transactionMemo?.trim()&&t.setTransactionMemo(e.transactionMemo.trim()),i.signer||n.signer){let e=await t.freezeWith(this.client);i.signer&&(e=await e.sign(i.signer)),n.signer&&(e=await e.sign(n.signer)),o=await e.execute(this.client)}else o=await t.execute(this.client);const s=await o.getReceipt(this.client);if(!s.topicId)throw new Error("Failed to create checkpoint topic: topicId empty");return n.signer&&this.topicSubmitKeySigners.set(s.topicId.toString(),n.signer),{topicId:s.topicId.toString(),transactionId:o.transactionId.toString()}}async publishCheckpoint(e,t,i,n){await this.operatorCtx.ensureInitialized();const o=r.TopicId.fromString(e).toString(),s=mb(ub.parse(t)),{message:a,inlineResolvedMetadata:c}=await this.prepareCheckpointPayload(s,i);"string"==typeof a.metadata&&c?await this.validateCheckpointMessage(a,async e=>e===a.metadata?c:this.resolveHCS1Reference(e)):await this.validateCheckpointMessage(a);const l=(new r.TopicMessageSubmitTransaction).setTopicId(r.TopicId.fromString(o)).setMessage(JSON.stringify(a)).setTransactionMemo(n?.trim()||this.buildTransactionMemo()),u=this.topicSubmitKeySigners.get(o),d=u?await(await l.freezeWith(this.client)).sign(u).then(e=>e.execute(this.client)):await l.execute(this.client),p=await d.getReceipt(this.client);return{transactionId:d.transactionId.toString(),sequenceNumber:this.parseSequenceNumber(p.topicSequenceNumber),receipt:p}}registerTopicSubmitKey(e,t){const i=this.resolveTopicKeyMaterial(t);if(!i.signer)throw new Error("submitKey must include a private key so the client can sign private-topic submissions");this.topicSubmitKeySigners.set(r.TopicId.fromString(e).toString(),i.signer)}resolveTopicKeyMaterial(e){if(void 0===e||!1===e)return{};if(e instanceof r.PublicKey||e instanceof r.KeyList)return{publicKey:e};if(e instanceof r.PrivateKey)return{publicKey:e.publicKey,signer:e};if("boolean"==typeof e)return e?{publicKey:this.operatorCtx.operatorKey.publicKey}:{};if("string"==typeof e){if(0===e.trim().length)throw new Error("topic key string cannot be empty");try{return{publicKey:r.PublicKey.fromString(e)}}catch(t){try{const t=r.PrivateKey.fromString(e);return{publicKey:t.publicKey,signer:t}}catch(i){throw new Error(`Failed to parse topic key as PublicKey or PrivateKey: ${String(t)}; ${String(i)}`)}}}return{}}assertSignableTopicKey(e,t,r){if(e&&"boolean"!=typeof e&&!t.signer&&t.publicKey&&!this.operatorCanSignTopicKey(t.publicKey))throw new Error(`${r} must include a private key or use true to reuse the operator key`)}operatorCanSignTopicKey(e){return e instanceof r.PublicKey?this.operatorCtx.operatorKey.publicKey.equals(e):this.operatorCanSignKeyList(e)}operatorCanSignKeyList(e){const t=e.toArray();return!((e.threshold??t.length)>1||0===t.length)&&t.some(e=>e instanceof r.PublicKey?this.operatorCtx.operatorKey.publicKey.equals(e):e instanceof r.KeyList&&this.operatorCanSignKeyList(e))}parseSequenceNumber(e){const t=BigInt(e.toString());if(t>BigInt(Number.MAX_SAFE_INTEGER))throw new Error("topicSequenceNumber exceeds Number.MAX_SAFE_INTEGER and cannot be represented safely");return Number(t)}async prepareCheckpointPayload(e,t){const r=t?.trim();if(r&&r.length>299)throw new Error("messageMemo must be 299 characters or fewer for HCS-27 checkpoints");const i={p:"hcs-27",op:"register",metadata:e,...r?{m:r}:{}},n=JSON.stringify(i);if(globalThis.Buffer.byteLength(n,"utf8")<=Db)return{message:i};const o=globalThis.Buffer.from(JSON.stringify(e),"utf8"),s=this.sha256Base64Url(o);pb.parse({p:"hcs-27",op:"register",metadata:"hcs://1/18446744073709551615.18446744073709551615.18446744073709551615",metadata_digest:{alg:"sha-256",b64u:s},...r?{m:r}:{}});const a=JSON.stringify({p:"hcs-27",op:"register",metadata:"hcs://1/18446744073709551615.18446744073709551615.18446744073709551615",metadata_digest:{alg:"sha-256",b64u:s},...r?{m:r}:{}});if(globalThis.Buffer.byteLength(a,"utf8")>Db)throw new Error("checkpoint overflow pointer message exceeds 1024 bytes");const c={p:"hcs-27",op:"register",metadata:await this.publishMetadataHCS1(o),metadata_digest:{alg:"sha-256",b64u:s},...r?{m:r}:{}},l=JSON.stringify(c);if(globalThis.Buffer.byteLength(l,"utf8")>Db)throw new Error("checkpoint overflow pointer message still exceeds 1024 bytes");return{message:c,inlineResolvedMetadata:o}}async publishMetadataHCS1(e){if("testnet"!==this.network&&"mainnet"!==this.network)throw new Error(`HCS-1 metadata publication is only supported on testnet and mainnet, got ${this.network}`);const t={accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network};this.inscriptionSDK||(this.inscriptionSDK=await es.createWithAuth({type:"server",...t}));const r=Ha((await Oa({type:"buffer",buffer:e,fileName:`hcs27-checkpoint-${d.randomUUID()}.json`,mimeType:"application/json"},t,{mode:"file",fileStandard:"hcs-1",waitForConfirmation:!0,waitMaxAttempts:120,waitIntervalMs:2e3},this.inscriptionSDK)).inscription);if(!r)throw new Error("Failed to inscribe overflow HCS-27 metadata: no topic ID returned");return`hcs://1/${r}`}sha256Base64Url(e){return d.createHash("sha256").update(e).digest("base64url")}},exports.HCS2BaseClient=kf,exports.HCS2Client=Rf,exports.HCS2Operation=gf,exports.HCS2RegistryType=mf,exports.HCS5BrowserClient=class extends pf{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,logger:void 0,operatorId:"0.0.0",operatorKey:""}),this.hwc=e.hwc,this.signer=e.signer}getSigner(){if(this.signer)return this.signer;const e=this.hwc.getAccountInfo()?.accountId,t=this.hwc.dAppConnector?.signers?.find(t=>t.getAccountId().toString()===e);if(!t)throw new Error("No active wallet signer");return t}async mint(e){try{if(!e.metadataTopicId)return{success:!1,error:"metadataTopicId is required for mint()"};const t=df(e.metadataTopicId),i=hf({tokenId:e.tokenId,metadata:t});let n;if(e.supplyKey&&e.supplyKey instanceof r.PrivateKey){const t=this.getSigner();await i.freezeWithSigner(t);const r=await i.sign(e.supplyKey);n=await this.hwc.executeTransactionWithErrorHandling(r,!0)}else n=await this.hwc.executeTransactionWithErrorHandling(i,!1);if(n.error)return{success:!1,error:n.error};const o=n.result;return{success:!0,serialNumber:o.serials?.[0]?Number(o.serials[0].toString()):void 0,transactionId:o?.transactionId?.toString?.(),metadata:t}}catch(zw){return{success:!1,error:String(zw)}}}async createHashinal(e){try{const t=this.getSigner(),r={...e.inscriptionOptions,mode:"hashinal",waitForConfirmation:!0,network:this.network},i=await Fa(e.inscriptionInput,t,r),n=i.inscription?.jsonTopicId||i.inscription?.topic_id;return i.confirmed&&n?await this.mint({tokenId:e.tokenId,metadataTopicId:n,supplyKey:e.supplyKey,memo:e.memo}):{success:!1,error:"Failed to inscribe content"}}catch(zw){return{success:!1,error:String(zw)}}}},exports.HCS5Client=class extends pf{constructor(e){super(e),this.operatorId=r.AccountId.fromString(e.operatorId),this.operatorCtx=B({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,mirrorNode:this.mirrorNode,logger:this.logger,client:e.client}),this.client=this.operatorCtx.client}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}async mint(e){try{if(await this.ensureInitialized(),!e.metadataTopicId)return{success:!1,error:"metadataTopicId is required for mint()"};const t=df(e.metadataTopicId),r=hf({tokenId:e.tokenId,metadata:t}),i=await r.freezeWith(this.client);if(e.supplyKey){const t=new U({mirrorNode:this.mirrorNode,logger:this.logger}),r="string"==typeof e.supplyKey?await t.resolveSupplyKey(e.tokenId,e.supplyKey,this.operatorCtx.keyType):e.supplyKey;await i.sign(r)}const n=await i.execute(this.client),o=await n.getReceipt(this.client);return{success:!0,serialNumber:o.serials&&o.serials[0]?Number(o.serials[0].toString()):void 0,transactionId:n.transactionId?.toString?.(),metadata:t}}catch(zw){const t=zw;return this.logger.error(`Failed to mint HCS-5 Hashinal: ${t.message}`),{success:!1,error:t.message}}}async createHashinal(e){try{await this.ensureInitialized();const t=await Oa(e.inscriptionInput,{accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},{...e.inscriptionOptions||{},mode:"hashinal",waitForConfirmation:!0});if(!t.confirmed||!t.inscription)return{success:!1,error:"Failed to inscribe content"};const r=t.inscription.jsonTopicId||t.inscription.topic_id;return r?await this.mint({tokenId:e.tokenId,metadataTopicId:r,supplyKey:e.supplyKey,memo:e.memo}):{success:!1,error:"No topic ID from inscription"}}catch(zw){const t=zw;return this.logger.error(`Failed to inscribe and mint HCS-5 Hashinal: ${t.message}`),{success:!1,error:t.message}}}},exports.HCS6BaseClient=N,exports.HCS6BrowserClient=class extends N{constructor(e){super(e),this.hwc=e.hwc,this.signer=e.signer}ensureConnected(){const e=this.hwc.getAccountInfo(),t=e?.accountId;if(!t)throw new Error("No active wallet connection: wallet integration required to perform write operations");return t}getSigner(){const e=this.signer;if(e)return e;this.ensureConnected();const t=this.hwc.dAppConnector,r=t?.signers?.[0];if(!r)throw new Error("No active wallet signer");return r}async createRegistry(e){try{this.ensureConnected();const t=e?.ttl??86400,r=this.generateRegistryMemo(t),i=await this.hwc.createTopic(r);return this.logger.info(`Created HCS-6 registry topic via wallet: ${i} (TTL ${t})`),{success:!0,topicId:i}}catch(t){return this.logger.error(`Failed to create HCS-6 registry: ${t}`),{success:!1,error:String(t)}}}async registerEntry(e,t){try{if(!(await this.validateHCS6Topic(e)))throw new Error(`Topic ${e} is not a valid HCS-6 registry`);const r=this.createRegisterMessage(t.targetTopicId,t.memo),i=await this.submitMessage(e,r),n=i.topicSequenceNumber;return{success:!0,receipt:i,sequenceNumber:"number"==typeof n?n:n?.low}}catch(r){return this.logger.error(`Failed to register HCS-6 entry: ${r}`),{success:!1,error:String(r)}}}async getRegistry(e,t={}){try{const r=await this.mirrorNode.getTopicInfo(e);this.logger.debug(`Retrieved topic info for HCS-6 ${e}: ${JSON.stringify(r)}`);const i=this.parseRegistryTypeFromMemo(r.memo);if(!i)throw new Error(`Topic ${e} is not an HCS-6 registry (invalid memo format)`);this.logger.debug(`Retrieving messages for HCS-6 topic ${e} with limit ${t.limit??100}`);const n=await this.mirrorNode.getTopicMessages(e,{sequenceNumber:t.skip&&t.skip>0?`gt:${t.skip}`:void 0,limit:t.limit??100,order:t.order??"asc"}),o=t.limit?n.slice(0,t.limit):n;return this.logger.debug(`Retrieved ${n.length} messages, using ${o.length} after applying limit.`),this.parseRegistryEntries(e,o,i.registryType,i.ttl)}catch(r){throw this.logger.error(`Failed to get HCS-6 registry: ${r}`),r}}async submitMessage(e,t){this.ensureConnected();const{valid:r,errors:i}=this.validateMessage(t);if(!r)throw new Error(`Invalid HCS-6 message: ${i.join(", ")}`);return await this.hwc.submitMessageToTopic(e,JSON.stringify(t))}async createHashinal(e){try{if(!this.signer)return{success:!1,error:"No signer configured for browser createHashinal"};const t={...e.inscriptionOptions,mode:"hashinal",metadata:e.metadata,waitForConfirmation:!0,network:this.network},r={type:"buffer",buffer:globalThis.Buffer.from(JSON.stringify(e.metadata)),fileName:"metadata.json",mimeType:"application/json"},i=await Fa(r,this.signer,t),n=i.inscription?.jsonTopicId||Ha(i.inscription);if(!n)return{success:!1,error:"Failed to inscribe metadata"};let o=e.registryTopicId;if(!o){const t=await this.createRegistry({ttl:e.ttl});if(!t.success||!t.topicId)return{success:!1,error:t.error};o=t.topicId}const s=await this.registerEntry(o,{targetTopicId:n,memo:e.memo||"Initial dynamic hashinal registration"});return s.success?{success:!0,registryTopicId:o,inscriptionTopicId:n}:{success:!1,error:s.error}}catch(t){return this.logger.error(`Failed to create dynamic hashinal: ${t}`),{success:!1,error:String(t)}}}async register(e){try{if(!this.signer)return{success:!1,error:"No signer configured for browser register"};let t;t=e.data?.base64?{type:"buffer",buffer:globalThis.Buffer.from(e.data.base64,"base64"),fileName:"data."+(e.data.mimeType?.split("/")[1]||"bin"),mimeType:e.data.mimeType||"application/octet-stream"}:e.data?.url?{type:"url",url:e.data.url}:{type:"buffer",buffer:globalThis.Buffer.from(JSON.stringify(e.metadata)),fileName:"metadata.json",mimeType:"application/json"};const r={...e.inscriptionOptions,mode:"hashinal",metadata:e.metadata,waitForConfirmation:!0,network:this.network},i=await Fa(t,this.signer,r),n=i.inscription?.jsonTopicId||Ha(i.inscription);if(!n)return{success:!1,error:"Failed to inscribe data"};let o=e.registryTopicId;if(!o){const t=await this.createRegistry({ttl:e.ttl});if(!t.success||!t.topicId)return{success:!1,error:t.error};o=t.topicId}const s=await this.registerEntry(o,{targetTopicId:n,memo:e.memo||"Dynamic hashinal registration"});return s.success?{success:!0,registryTopicId:o,inscriptionTopicId:n}:{success:!1,error:s.error}}catch(t){return this.logger.error(`Failed to register dynamic hashinal: ${t}`),{success:!1,error:String(t)}}}async validateHCS6Topic(e){try{const t=await this.mirrorNode.getTopicInfo(e),r=this.parseRegistryTypeFromMemo(t.memo);return r?r.registryType===T.NON_INDEXED||(this.logger.warn(`Topic ${e} is not a valid HCS-6 registry (must be non-indexed)`),!1):(this.logger.warn(`Topic ${e} is not a valid HCS-6 registry (invalid memo format)`),!1)}catch(t){return this.logger.error(`Error validating HCS-6 topic ${e}: ${t}`),!1}}},exports.HCS6Client=class extends N{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,mirrorNodeUrl:e.mirrorNodeUrl,logger:e.logger}),this.operatorId="string"==typeof e.operatorId?r.AccountId.fromString(e.operatorId):e.operatorId,this.operatorCtx=B({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:e.client??this.createClient(e.network)}),this.client=this.operatorCtx.client}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}createClient(e){return"mainnet"===e?r.Client.forMainnet():r.Client.forTestnet()}close(){this.logger.info("HCS-6 client closed.")}getKeyType(){return this.operatorCtx.keyType}getOperatorKey(){return this.operatorCtx.operatorKey}async submitMessage(e,t){return this.submitMessageWithKey(e,t,void 0)}async submitMessageWithKey(e,t,i){const{valid:n,errors:o}=this.validateMessage(t);if(!n)throw new Error(`Invalid HCS-6 message: ${o.join(", ")}`);let s=(new r.TopicMessageSubmitTransaction).setTopicId(r.TopicId.fromString(e)).setMessage(JSON.stringify(t));if(!i){const e=await s.execute(this.client);return await e.getReceipt(this.client)}const a="string"==typeof i?r.PrivateKey.fromString(i):i,c=await s.freezeWith(this.client);await c.sign(a);const l=await c.execute(this.client);return await l.getReceipt(this.client)}async registerEntryWithKey(e,t,r){try{const i=this.createRegisterMessage(t.targetTopicId,t.memo),n=await this.submitMessageWithKey(e,i,r),o=n.topicSequenceNumber?.toNumber();return{success:!0,receipt:n,sequenceNumber:o}}catch(i){return this.logger.error(`Failed to register HCS-6 entry: ${i}`),{success:!1,error:String(i)}}}async createRegistry(e={}){try{await this.ensureInitialized();const t=e.ttl??86400;if(!(t>=3600))throw new Error("TTL must be at least 3600 seconds (1 hour)");let i,n;if(e.submitKey)if("string"==typeof e.submitKey)try{i=r.PublicKey.fromString(e.submitKey)}catch{const t=globalThis.Buffer.from(e.submitKey.replace(/^0x/i,""),"hex");i="ed25519"===this.operatorCtx.keyType?r.PublicKey.fromBytesED25519(t):r.PublicKey.fromBytesECDSA(t)}else"boolean"==typeof e.submitKey?i=this.operatorCtx.operatorKey.publicKey:(i=e.submitKey.publicKey,n=e.submitKey);let o=P({ttl:t,submitKey:i,adminKey:this.operatorCtx.operatorKey.publicKey,operatorPublicKey:this.operatorCtx.operatorKey.publicKey});const s=await o.freezeWith(this.client);n&&await s.sign(n);const a=await s.execute(this.client),c=(await a.getReceipt(this.client)).topicId;if(!c)throw new Error("Failed to create HCS-6 registry: No topic ID in receipt");return{success:!0,topicId:c.toString(),transactionId:a.transactionId.toString()}}catch(t){return this.logger.error(`Failed to create HCS-6 registry: ${t}`),{success:!1,error:`Failed to create HCS-6 registry: ${t}`}}}async registerEntry(e,t){return await this.ensureInitialized(),this.registerEntryWithKey(e,t,void 0)}async getRegistry(e,t={}){await this.ensureInitialized();const r=((await this.mirrorNode.getTopicInfo(e)).memo||"").match(/^hcs-6:(\d):(\d+)$/);if(!r)throw new Error(`Topic ${e} is not an HCS-6 registry (invalid memo format)`);const i=parseInt(r[2]),n=parseInt(r[1]),o=(await this.mirrorNode.getTopicMessages(e,{sequenceNumber:t.skip&&t.skip>0?`gt:${t.skip}`:void 0,limit:t.limit??100,order:t.order??"asc"})).map(t=>{try{const r=t,{valid:i}=this.validateMessage(r);return i?{topicId:e,sequence:r.sequence_number,timestamp:r.consensus_timestamp||"",payer:r.payer||"",message:r,consensus_timestamp:r.consensus_timestamp||"",registry_type:n}:null}catch{return null}}).filter(e=>Boolean(e)),s=o.length>0?o[o.length-1]:void 0;return{topicId:e,registryType:n,ttl:i,entries:o,latestEntry:s}}async mint(e){try{if(await this.ensureInitialized(),!e.metadataTopicId)return{success:!1,error:"metadataTopicId is required for mint()"};const t=S(e.metadataTopicId);let i=(new r.TokenMintTransaction).setTokenId(r.TokenId.fromString(e.tokenId)).setMetadata([globalThis.Buffer.from(t)]);const n=await i.freezeWith(this.client);if(e.supplyKey){const t=new U({mirrorNode:this.mirrorNode,logger:this.logger}),r="string"==typeof e.supplyKey?await t.resolveSupplyKey(e.tokenId,e.supplyKey,this.operatorCtx.keyType):e.supplyKey;await n.sign(r)}const o=await n.execute(this.client),s=await o.getReceipt(this.client);return{success:!0,serialNumber:s.serials&&s.serials[0]?Number(s.serials[0].toString()):void 0,transactionId:o.transactionId?.toString?.(),metadata:t}}catch(zw){return{success:!1,error:String(zw)}}}async inscribeAndMint(e){try{await this.ensureInitialized();const t={...e.inscriptionOptions,mode:"hashinal",waitForConfirmation:!0},r=await Oa(e.inscriptionInput,{accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},t);if(!r.confirmed||!r.inscription)return{success:!1,error:"Failed to inscribe content"};const i=r.inscription.jsonTopicId||r.inscription.topic_id;return i?await this.mint({tokenId:e.tokenId,metadataTopicId:i,supplyKey:e.supplyKey,memo:e.memo}):{success:!1,error:"No topic ID from inscription"}}catch(zw){return{success:!1,error:String(zw)}}}async createHashinal(e){try{let t,r;if(await this.ensureInitialized(),e.registryTopicId){t=e.registryTopicId;const r=(await this.mirrorNode.getTopicInfo(t)).memo||"";if(!/^hcs-6:\d:\d+$/.test(r))throw new Error(`Topic ${t} is not a valid HCS-6 registry`)}else{const i=await this.createRegistry({ttl:e.ttl,submitKey:!0});if(!i.success||!i.topicId)throw new Error(i.error||"Failed to create HCS-6 registry");t=i.topicId,r=i.transactionId}const i=globalThis.Buffer.from(JSON.stringify(e.metadata)),n={...e.inscriptionOptions,mode:"hashinal",metadata:e.metadata,waitForConfirmation:!0},o=await Oa({type:"buffer",buffer:i,fileName:"metadata.json",mimeType:"application/json"},{accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},n);if(!o.confirmed||!o.inscription)throw new Error("Failed to inscribe metadata");const s=o.inscription.jsonTopicId||o.inscription.topic_id;if(!s)throw new Error("No inscription topic ID available");const a=await this.registerEntryWithKey(t,{targetTopicId:s,memo:e.memo||"Dynamic hashinal registration"},e.submitKey);if(!a.success)throw new Error(a.error||"Failed to register entry");return{success:!0,registryTopicId:t,inscriptionTopicId:s,transactionId:r}}catch(zw){return{success:!1,error:String(zw)}}}async register(e){try{let t,r,i;if(await this.ensureInitialized(),e.registryTopicId){t=e.registryTopicId;const r=(await this.mirrorNode.getTopicInfo(t)).memo||"";if(!/^hcs-6:\d:\d+$/.test(r))throw new Error(`Topic ${t} is not a valid HCS-6 registry`)}else{const i=await this.createRegistry({ttl:e.ttl,submitKey:!0});if(!i.success||!i.topicId)throw new Error(i.error||"Failed to create HCS-6 registry");t=i.topicId,r=i.transactionId}if(e.data?.base64){i={type:"buffer",buffer:globalThis.Buffer.from(e.data.base64,"base64"),fileName:`data.${e.data.mimeType?.split("/")[1]||"bin"}`,mimeType:e.data.mimeType||"application/octet-stream"}}else i=e.data?.url?{type:"url",url:e.data.url}:{type:"buffer",buffer:globalThis.Buffer.from(JSON.stringify(e.metadata)),fileName:"metadata.json",mimeType:"application/json"};const n={...e.inscriptionOptions,mode:"hashinal",metadata:e.metadata,waitForConfirmation:!0},o=await Oa(i,{accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},n);if(!o.confirmed||!o.inscription)throw new Error("Failed to inscribe data");const s=o.inscription.jsonTopicId||o.inscription.topic_id;if(!s)throw new Error("No inscription topic ID available");const a=await this.registerEntryWithKey(t,{targetTopicId:s,memo:e.memo||"Dynamic hashinal registration"},e.submitKey);if(!a.success)throw new Error(a.error||"Failed to register entry");return{success:!0,registryTopicId:t,inscriptionTopicId:s,transactionId:r}}catch(zw){return{success:!1,error:String(zw)}}}},exports.HCS6Operation=I,exports.HCS6RegistryType=T,exports.HCS7BaseClient=ec,exports.HCS7BrowserClient=class extends ec{constructor(e){super(e),this.hwc=e.hwc}ensureConnected(){const e=this.hwc.getAccountInfo();if(!e?.accountId)throw new Error("No active wallet connection")}async createRegistry(e={}){try{this.ensureConnected();const t=e.ttl??86400;if(t<3600)throw new Error("TTL must be at least 3600 seconds");const r=this.generateRegistryMemo(t),i=await this.hwc.createTopic(r);return this.logger.info(`Created HCS-7 registry topic ${i}`),{success:!0,topicId:i}}catch(t){return this.logger.error("Failed to create HCS-7 registry in browser",t),{success:!1,error:String(t)}}}async registerConfig(e){const t=this.createConfigMessage({config:e.config,memo:e.memo});return this.submitWithWallet({topicId:e.registryTopicId,message:t})}async registerMetadata(e){const t=this.createMetadataMessage(e);return this.submitWithWallet({topicId:e.registryTopicId,message:t})}async submitWithWallet(e){try{this.ensureConnected();const{valid:t,errors:r}=this.validateMessage(e.message);if(!t)return{success:!1,error:`Invalid HCS-7 payload: ${r.join(", ")}`};const i=await this.hwc.submitMessageToTopic(e.topicId,JSON.stringify(e.message));return{success:!0,receipt:i,sequenceNumber:tc(i)}}catch(t){return this.logger.error("Failed to submit HCS-7 browser message",t),{success:!1,error:String(t)}}}},exports.HCS7Client=class extends ec{constructor(e){super(e),this.closed=!1,this.operatorCtx=B({network:this.network,operatorId:e.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:e.client}),this.client=this.operatorCtx.client}close(){this.closed||(this.closed=!0,this.logger.info("HCS-7 client closed"))}getKeyType(){return this.operatorCtx.keyType}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}resolvePublicKey(e){if(e){if("boolean"==typeof e)return e?this.operatorCtx.operatorKey.publicKey:void 0;if("string"==typeof e)try{return r.PublicKey.fromString(e)}catch{return}return e.publicKey}}coercePrivateKey(e){if(e instanceof r.PrivateKey)return e;try{return r.PrivateKey.fromStringED25519(e)}catch{return r.PrivateKey.fromStringECDSA(e)}}async createRegistry(e={}){const t=e.ttl??86400;if(t<3600)return{success:!1,error:"TTL must be at least 3600 seconds"};try{await this.ensureInitialized();const r=this.resolvePublicKey(e.submitKey);let i=rc({ttl:t,submitKey:r,adminKey:this.resolvePublicKey(e.adminKey),operatorPublicKey:this.operatorCtx.operatorKey.publicKey});i=await i.freezeWith(this.client);const n=await i.execute(this.client),o=await n.getReceipt(this.client),s=o.topicId?.toString();return s?{success:!0,topicId:s,transactionId:n.transactionId?.toString()}:{success:!1,error:"Topic creation receipt did not include a topic ID"}}catch(r){return this.logger.error("Failed to create HCS-7 registry topic",r),{success:!1,error:String(r)}}}async registerConfig(e){await this.ensureInitialized();const t=this.createConfigMessage({config:e.config,memo:e.memo});return this.submitMessage({topicId:e.registryTopicId,message:t,submitKey:e.submitKey,transactionMemo:e.transactionMemo})}async registerMetadata(e){await this.ensureInitialized();const t=this.createMetadataMessage(e);return this.submitMessage({topicId:e.registryTopicId,message:t,submitKey:e.submitKey,transactionMemo:e.transactionMemo})}async submitMessage(e){const{valid:t,errors:r}=this.validateMessage(e.message);if(!t)return{success:!1,error:`Invalid HCS-7 payload: ${r.join(", ")}`};try{let t=ic({topicId:e.topicId,message:e.message,transactionMemo:e.transactionMemo});if(e.submitKey){const r=this.coercePrivateKey(e.submitKey);t=await t.freezeWith(this.client),await t.sign(r);const i=await t.execute(this.client),n=await i.getReceipt(this.client);return{success:!0,receipt:n,sequenceNumber:n.topicSequenceNumber?.toNumber(),transactionId:i.transactionId?.toString()}}const r=await t.execute(this.client),i=await r.getReceipt(this.client);return{success:!0,receipt:i,sequenceNumber:i.topicSequenceNumber?.toNumber(),transactionId:r.transactionId?.toString()}}catch(i){return this.logger.error("Failed to submit HCS-7 message",i),{success:!1,error:String(i)}}}},exports.HCS7ConfigType=ja,exports.HCS7Operation=qa,exports.HOL_CHAT_PROTOCOL_ID=Hp,exports.HRLResolver=Wp,exports.HTSParser=ta,exports.HashLinkResolver=Vg,exports.HashLinkScanner=Wg,exports.HashLinksRegistry=Kg,exports.Hcs10MemoType=tg,exports.Hcs26SkillRegistryResolver=yw,exports.HederaHieroIssuer=cf,exports.HederaMirrorNode=x,exports.HieroDidResolver=fm,exports.InboundTopicType=Th,exports.InsufficientBalanceError=class extends Kf{constructor(e,t,r,i){super(`Insufficient balance for ${t}: required ${r}, available ${i}`),this.accountId=e,this.tick=t,this.required=r,this.available=i,this.name="InsufficientBalanceError"}},exports.InvalidAccountFormatError=Vf,exports.InvalidMessageFormatError=class extends Kf{constructor(e,t){super(e),this.messageData=t,this.name="InvalidMessageFormatError"}},exports.InvalidNumberFormatError=class extends Kf{constructor(e,t){super(`Invalid number format for ${t}: ${e}`),this.value=e,this.field=t,this.name="InvalidNumberFormatError"}},exports.InvalidTickFormatError=class extends Kf{constructor(e){super(`Invalid tick format: ${e}`),this.tick=e,this.name="InvalidTickFormatError"}},exports.IssuerRegistry=rf,exports.KeyType=O,exports.KeyTypeDetector=F,exports.Logger=y,exports.MAINNET_EXAMPLES=Jg,exports.MCPServerBuilder=ug,exports.MCPServerCapability=wh,exports.MCPServerConnectionInfoSchema=Ch,exports.MCPServerDetailsSchema=_h,exports.MCPServerHostSchema=xh,exports.MCPServerProfileSchema=Fh,exports.MCPServerResourceSchema=Nh,exports.MCPServerToolSchema=zh,exports.MCPServerVerificationSchema=Rh,exports.MapCache=nc,exports.MintLimitExceededError=class extends Kf{constructor(e,t,r){super(`Mint limit exceeded for ${e}: requested ${t}, limit ${r}`),this.tick=e,this.requested=t,this.limit=r,this.name="MintLimitExceededError"}},exports.NodeCryptoAdapter=th,exports.NodeHashAdapter=Vp,exports.NodeHmacAdapter=Zp,exports.PayloadSizeError=ng,exports.PersonBuilder=lg,exports.PersonalProfileSchema=Oh,exports.PointsBurnError=qf,exports.PointsDeploymentError=$f,exports.PointsMintError=class extends Kf{constructor(e,t,r,i){super(e),this.tick=t,this.requestedAmount=r,this.availableSupply=i,this.name="PointsMintError"}},exports.PointsNotFoundError=class extends Kf{constructor(e){super(`Points with tick "${e}" not found`),this.tick=e,this.name="PointsNotFoundError"}},exports.PointsTransferError=Hf,exports.PointsValidationError=jf,exports.ProfileType=mh,exports.ProgressReporter=ts,exports.REFERENCE_THRESHOLD=51200,exports.RedisCache=class{constructor(e={}){const{host:t="localhost",port:r=6379,password:i,db:n=0,keyPrefix:o="",tls:s=!1,connectTimeout:a=5e3,retryStrategy:c,logLevel:l="info"}=e;this.prefix=o,this.logger=y.getInstance({level:l,module:"RedisCache"}),this.client=function(e,t){const r=function(){if("function"!=typeof require)return null;try{const e=require("ioredis");if("function"==typeof e)return e;if("function"==typeof e.default)return e.default}catch{return null}return null}();if(!r)return e.warn("ioredis is not installed; RedisCache will use an in-memory cache instead"),function(){const e=new Map;return{get:async t=>e.get(t)??null,set:async(t,r)=>(e.set(t,r),"OK"),setex:async(t,r,i)=>(e.set(t,i),"OK"),async del(...t){let r=0;for(const i of t)e.delete(i)&&(r+=1);return r},async keys(t){if(t.endsWith("*")){const r=t.slice(0,-1);return Array.from(e.keys()).filter(e=>e.startsWith(r))}return e.has(t)?[t]:[]},async quit(){e.clear()},on(){}}}();const i=new r({host:t.host,port:t.port,password:t.password,db:t.db,tls:t.tls,keyPrefix:t.keyPrefix,connectTimeout:t.connectTimeout,retryStrategy:t.retryStrategy,maxRetriesPerRequest:t.maxRetriesPerRequest});return i.on("error",t=>{e.error("Redis connection error:",t)}),i.on("connect",()=>{e.debug("Redis connected")}),i}(this.logger,{host:t,port:r,password:i,db:n,tls:s?{}:void 0,keyPrefix:o,connectTimeout:a,retryStrategy:c||(e=>Math.min(50*e,2e3)),maxRetriesPerRequest:3})}getKey(e){return`${this.prefix}${e}`}async get(e){try{return await this.client.get(this.getKey(e))||void 0}catch(t){throw this.logger.error("Redis get error:",t),t}}async set(e,t,r){try{const i=this.getKey(e);r?await this.client.setex(i,r,t):await this.client.set(i,t)}catch(i){throw this.logger.error("Redis set error:",i),i}}async delete(e){try{await this.client.del(this.getKey(e))}catch(t){throw this.logger.error("Redis delete error:",t),t}}async clear(){try{const e=await this.client.keys(`${this.prefix}*`);e.length>0&&await this.client.del(...e)}catch(e){throw this.logger.error("Redis clear error:",e),e}}async disconnect(){await this.client.quit()}setLogLevel(e){this.logger.setLogLevel(e)}},exports.Registration=Kh,exports.RegistryBrokerClient=$p,exports.RegistryBrokerError=pp,exports.RegistryBrokerParseError=hp,exports.RegistryType=bg,exports.ResolverRegistry=ym,exports.ResourceManager=class{constructor(e,t,r,i={}){this.cache=new Map,this.currentCacheSize=0,this.supportedImageTypes=new Set(["image/png","image/jpeg","image/jpg","image/gif","image/svg+xml","image/webp"]),this.dangerousJSPatterns=[/eval\s*\(/g,/Function\s*\(/g,/setTimeout\s*\(\s*["'].*["']/g,/setInterval\s*\(\s*["'].*["']/g,/document\.write/g,/innerHTML\s*=/g,/outerHTML\s*=/g],this.dangerousCSSPatterns=[/javascript\s*:/gi,/@import.*url\s*\(\s*["']?javascript:/gi,/expression\s*\(/gi,/behavior\s*:/gi],this.logger=t,this.hcs=r||new w,this.options={cacheTTL:i.cacheTTL||3e5,maxCacheSize:i.maxCacheSize||52428800,maxResourceSize:i.maxResourceSize||5242880}}async loadCSS(e){this.logger.debug("Loading CSS resource",{topicId:e});try{const t=await this.loadResource(e);if("text/css"!==t.contentType)throw new Error(`Expected CSS resource, got ${t.contentType}`);const r=t.content,i=this.sanitizeCSS(r);return this.logger.debug("CSS resource loaded successfully",{topicId:e,size:r.length,sanitized:i.length!==r.length}),i}catch(t){throw this.logger.error("Failed to load CSS resource",{topicId:e,error:t}),new Error(`Failed to load CSS resource: ${t instanceof Error?t.message:"Unknown error"}`)}}async loadJS(e){this.logger.debug("Loading JavaScript resource",{topicId:e});try{const t=await this.loadResource(e);if(!t.contentType.includes("javascript")&&!t.contentType.includes("ecmascript"))throw new Error(`Expected JavaScript resource, got ${t.contentType}`);const r=t.content;if(r.length>this.options.maxResourceSize)throw new Error("JavaScript resource too large");const i=this.sanitizeJavaScript(r);return this.logger.debug("JavaScript resource loaded successfully",{topicId:e,size:r.length,sanitized:i.length!==r.length}),i}catch(t){throw this.logger.error("Failed to load JavaScript resource",{topicId:e,error:t}),new Error(`Failed to load JavaScript resource: ${t instanceof Error?t.message:"Unknown error"}`)}}async loadImage(e){this.logger.debug("Loading image resource",{topicId:e});try{const t=await this.loadResource(e);if(!this.supportedImageTypes.has(t.contentType))throw new Error(`Unsupported image format: ${t.contentType}`);const r=t.content,i=new Uint8Array(r),n=new Blob([i.buffer],{type:t.contentType});return this.logger.debug("Image resource loaded successfully",{topicId:e,size:r.length,type:t.contentType}),n}catch(t){throw this.logger.error("Failed to load image resource",{topicId:e,error:t}),new Error(`Failed to load image resource: ${t instanceof Error?t.message:"Unknown error"}`)}}async loadTemplate(e){this.logger.debug("Loading template resource",{topicId:e});try{const t=(await this.loadResource(e)).content;this.validateTemplateSyntax(t);const r=this.sanitizeTemplate(t);return this.logger.debug("Template resource loaded successfully",{topicId:e,size:t.length}),r}catch(t){throw this.logger.error("Failed to load template resource",{topicId:e,error:t}),new Error(`Failed to load template resource: ${t instanceof Error?t.message:"Unknown error"}`)}}async loadWithIntegrityCheck(e,t){this.logger.debug("Loading resource with integrity check",{topicId:e,expectedHash:t});try{const r=await this.loadResource(e),i=await this.verifyIntegrity(r.content,t);if(!i)throw new Error("Resource integrity verification failed");return this.logger.debug("Resource integrity verified",{topicId:e}),{content:r.content,verified:i,contentType:r.contentType}}catch(r){throw this.logger.error("Resource integrity check failed",{topicId:e,error:r}),r}}async verifyIntegrity(e,t){try{if(Xp())return this.logger.warn("Integrity verification skipped in SSR environment"),!0;const r=globalThis.crypto;if(void 0===r||!r.subtle)return this.logger.warn("WebCrypto not available, skipping integrity verification"),!0;const i="string"==typeof e?(new TextEncoder).encode(e):e,n=i instanceof Uint8Array?i:new Uint8Array(i),o=new Uint8Array(n),s=await r.subtle.digest("SHA-256",o.buffer),a=Array.from(new Uint8Array(s));return a.map(e=>e.toString(16).padStart(2,"0")).join("")===t.toLowerCase()}catch(r){return this.logger.error("Error verifying integrity",{error:r}),!1}}async loadDependencies(e){this.logger.debug("Loading dependencies",{count:e.length});try{this.detectCircularDependencies(e);const t=this.topologicalSort(e),r=[];for(const e of t){let t;switch(e.type){case"css":t=await this.loadCSS(e.topicId);break;case"js":t=await this.loadJS(e.topicId);break;case"template":t=await this.loadTemplate(e.topicId);break;case"image":const r=await this.loadImage(e.topicId);t=new Uint8Array(await r.arrayBuffer());break;default:throw new Error(`Unsupported dependency type: ${e.type}`)}r.push({topicId:e.topicId,content:t,contentType:this.getContentTypeForType(e.type),type:e.type})}return this.logger.debug("Dependencies loaded successfully",{count:r.length}),r}catch(t){throw this.logger.error("Failed to load dependencies",{error:t}),t}}clearCache(){this.cache.clear(),this.currentCacheSize=0,this.logger.debug("Resource cache cleared")}getCacheSize(){return this.currentCacheSize}async loadResource(e){const t=this.getFromCache(e);if(t)return this.logger.debug("Resource loaded from cache",{topicId:e}),t;const r=await this.hcs.retrieveHCS1Data(e),i=r.type||"application/octet-stream";let n;n=i.startsWith("text/")||i.includes("javascript")||i.includes("json")?await r.text():new Uint8Array(await r.arrayBuffer());const o={content:n,contentType:i,size:r.size};return this.addToCache(e,o),o}getFromCache(e){const t=this.cache.get(e);return t?Date.now()-t.timestamp>this.options.cacheTTL?(this.removeFromCache(e),null):t.data:null}addToCache(e,t){const r="string"==typeof t.content?t.content.length:t.content.byteLength;if(r>this.options.maxCacheSize/2)return void this.logger.warn("Resource too large for cache",{topicId:e,size:r});for(;this.currentCacheSize+r>this.options.maxCacheSize&&this.cache.size>0;)this.evictOldestEntry();const i={data:t,timestamp:Date.now(),size:r};this.cache.set(e,i),this.currentCacheSize+=r,this.logger.debug("Resource added to cache",{topicId:e,size:r,totalCacheSize:this.currentCacheSize})}removeFromCache(e){const t=this.cache.get(e);t&&(this.cache.delete(e),this.currentCacheSize-=t.size)}evictOldestEntry(){let e=null,t=Date.now();for(const[r,i]of this.cache)i.timestamp<t&&(t=i.timestamp,e=r);e&&(this.removeFromCache(e),this.logger.debug("Evicted oldest cache entry",{topicId:e}))}sanitizeCSS(e){let t=e;for(const r of this.dangerousCSSPatterns)t=t.replace(r,"");return t}sanitizeJavaScript(e){let t=e;for(const r of this.dangerousJSPatterns)t=t.replace(r,"");return t}sanitizeTemplate(e){return e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/on\w+\s*=\s*["'][^"']*["']/gi,"").replace(/javascript\s*:/gi,"")}validateTemplateSyntax(e){if((e.match(/\{\{/g)||[]).length!==(e.match(/\}\}/g)||[]).length)throw new Error("Invalid template syntax: unmatched braces");if((e.match(/\{\{#\w+/g)||[]).length!==(e.match(/\{\{\/\w+/g)||[]).length)throw new Error("Invalid template syntax: unclosed block helpers")}detectCircularDependencies(e){const t=new Map;for(const o of e)t.set(o.topicId,o.depends||[]);const r=new Set,i=new Set,n=e=>{if(i.has(e))throw new Error("Circular dependency detected");if(r.has(e))return;i.add(e);const o=t.get(e)||[];for(const t of o)n(t);i.delete(e),r.add(e)};for(const o of e)n(o.topicId)}topologicalSort(e){const t=new Map,r=new Map;for(const s of e)t.set(s.topicId,s),r.set(s.topicId,s.depends||[]);const i=[],n=new Set,o=e=>{if(n.has(e))return;const s=r.get(e)||[];for(const t of s)o(t);n.add(e);const a=t.get(e);a&&i.push(a)};for(const s of e)o(s.topicId);return i}getContentTypeForType(e){switch(e){case"css":return"text/css";case"js":return"application/javascript";case"template":return"text/html";case"image":return"image/*";default:return"application/octet-stream"}}},exports.SUPPORTED_SOCIAL_PLATFORMS=Sh,exports.ScheduleParser=aa,exports.SocialLinkSchema=Eh,exports.StateHashError=Oy,exports.SupplyLimitExceededError=class extends Kf{constructor(e,t,r,i){super(`Supply limit exceeded for ${e}: max ${r}, current ${i}, requested ${t}`),this.tick=e,this.requested=t,this.maxSupply=r,this.currentSupply=i,this.name="SupplyLimitExceededError"}},exports.TESTNET_EXAMPLES=Gg,exports.TemplateEngine=class{constructor(e){this.templateCache=new Map,this.helpers=new Map,this.compiledTemplates=new Map,this.logger=e,this.setupBuiltinHelpers()}async render(e,t={}){this.logger.debug("Rendering template",{templateLength:e.length,context:JSON.stringify(t,null,2),attributesType:t.attributes?typeof t.attributes:"undefined",contextKeys:Object.keys(t)});try{const r=this.getCacheKey(e);let i=this.templateCache.get(r);i||(i=await this.compileTemplate(e),this.templateCache.set(r,i));const n=i.render(this.sanitizeContext(t));return this.logger.debug("Template rendered successfully",{resultLength:n.length}),n}catch(r){throw this.logger.error("Template rendering failed",{error:r,template:e}),new Error(`Template rendering failed: ${r instanceof Error?r.message:"Unknown error"}`)}}async precompile(e,t){this.logger.debug("Precompiling template",{name:e,templateLength:t.length});try{const r=await this.compileTemplate(t);this.compiledTemplates.set(e,r),this.logger.debug("Template precompiled successfully",{name:e})}catch(r){throw this.logger.error("Template precompilation failed",{error:r,name:e}),new Error(`Template precompilation failed: ${r instanceof Error?r.message:"Unknown error"}`)}}async renderCompiled(e,t={}){const r=this.compiledTemplates.get(e);if(!r)throw new Error(`Precompiled template '${e}' not found`);this.logger.debug("Rendering precompiled template",{name:e});try{const i=r.render(this.sanitizeContext(t));return this.logger.debug("Precompiled template rendered successfully",{name:e}),i}catch(i){throw this.logger.error("Precompiled template rendering failed",{error:i,name:e}),new Error(`Template rendering failed: ${i instanceof Error?i.message:"Unknown error"}`)}}registerHelper(e,t){this.helpers.set(e,t),this.logger.debug("Helper registered",{name:e})}clearCache(){this.templateCache.clear(),this.logger.debug("Template cache cleared")}getCacheSize(){return this.templateCache.size}async compileTemplate(e){this.validateTemplate(e);return{source:e,compiled:!0,render:t=>this.executeTemplate(e,t)}}executeTemplate(e,t){let r=e;return r=this.processHelpers(r,t),r=this.processLoops(r,t),r=this.processConditionals(r,t),r=this.processVariables(r,t),r}processConditionals(e,t){let r=e;r=r.replace(/\{\{#if\s+([^}]+)\}\}((?:[^{]|\{(?!\{)|\{\{(?!#if|\{#else|\{\/if))*?)\{\{#if\s+([^}]+)\}\}((?:[^{]|\{(?!\{)|\{\{(?!#if|#else|\/if))*?)\{\{else\}\}((?:[^{]|\{(?!\{)|\{\{(?!#if|#else|\/if))*?)\{\{\/if\}\}((?:[^{]|\{(?!\{)|\{\{(?!\/if))*?)\{\{\/if\}\}/gs,(e,r,i,n,o,s,a)=>{if(!this.evaluateCondition(r,t))return"";return i+(this.evaluateCondition(n,t)?o:s)+a});r=r.replace(/\{\{#if\s+([^}]+)\}\}((?:[^{]|\{(?!\{)|\{\{(?!else|\/if))*?)\{\{else\}\}((?:[^{]|\{(?!\{)|\{\{(?!\/if))*?)\{\{\/if\}\}/gs,(e,r,i,n)=>this.evaluateCondition(r,t)?i:n);r=r.replace(/\{\{#if\s+([^}]+)\}\}((?:[^{]|\{(?!\{)|\{\{(?!\/if))*?)\{\{\/if\}\}/gs,(e,r,i)=>this.evaluateCondition(r,t)?i:"");return r=r.replace(/\{\{#unless\s+([^}]+)\}\}((?:[^{]|\{(?!\{)|\{\{(?!\/unless))*?)\{\{\/unless\}\}/gs,(e,r,i)=>this.evaluateCondition(r,t)?"":i),r}processLoops(e,t){let r=e;return r=r.replace(/\{\{#each\s+([^}]+)\}\}(.*?)\{\{\/each\}\}/gs,(e,r,i)=>{const n=this.getNestedValue(r,t);if(!n)return"";let o="";if(Array.isArray(n))n.forEach((e,r)=>{let n=i;if(n=n.replace(/\{\{this\}\}/g,this.escapeHtml(String(e))),n=n.replace(/\{\{@index\}\}/g,String(r)),"object"==typeof e&&null!==e)for(const[t,i]of Object.entries(e)){const e=new RegExp(`\\{\\{${t}\\}\\}`,"g");n=n.replace(e,this.escapeHtml(String(i)))}n=n.replace(/\{\{\.\.\/([^}]+)\}\}/g,(e,r)=>{const i=this.getNestedValue(r,t);return this.escapeHtml(String(i||""))}),o+=n});else if("object"==typeof n)for(const[t,s]of Object.entries(n)){let e=i;e=e.replace(/\{\{@key\}\}/g,this.escapeHtml(t)),e=e.replace(/\{\{this\}\}/g,this.escapeHtml(String(s))),o+=e}return o}),r}processVariables(e,t){let r=e;r=r.replace(/\{\{\{([^}]+)\}\}\}/g,(e,r)=>{const i=this.getNestedValue(r.trim(),t);return this.sanitizeHtml(String(i||""))});return r=r.replace(/\{\{([^}#/]+)\}\}/g,(e,r)=>{const i=r.trim();if(i.startsWith("#")||i.startsWith("/")||i.startsWith("else"))return e;const n=this.getNestedValue(i,t);return 0===n||!1===n?this.escapeHtml(String(n)):this.escapeHtml(String(n||""))}),r}processHelpers(e,t){let r=e;r=r.replace(/\{\{#with\s+([^}]+)\}\}(.*?)\{\{\/with\}\}/gs,(e,r,i)=>{const n=this.getNestedValue(r.trim(),t);return n?this.executeTemplate(i,n):""});for(const[i,n]of this.helpers){const e=new RegExp(`\\{\\{${i}\\s+([^}]+)\\}\\}`,"g");r=r.replace(e,(e,r)=>{try{const e=this.getNestedValue(r.trim(),t);return this.escapeHtml(n.call(t,e))}catch(o){return this.logger.warn("Helper execution failed",{helperName:i,error:o}),""}})}return r}evaluateCondition(e,t){const r=this.getNestedValue(e.trim(),t);return Boolean(r)}getNestedValue(e,t){if(!e||!t)return;const r=e.split(".");let i=t;for(const n of r){if(null==i||"object"!=typeof i)return;i=i[n]}return i}sanitizeContext(e){if(null==e)return e;const t=new WeakSet,r=e=>{if(null===e||"object"!=typeof e)return e;if(t.has(e))return"[Circular]";if(t.add(e),Array.isArray(e))return e.map(r);const i={};for(const[t,n]of Object.entries(e))i[t]=r(n);return i};return r(e)}escapeHtml(e){return e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}sanitizeHtml(e){return e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"")}validateTemplate(e){if((e.match(/\{\{#\w+/g)||[]).length!==(e.match(/\{\{\/\w+/g)||[]).length)throw new Error("Invalid template syntax: unclosed block helpers");if(/\{\{[^}]*$|\{\{[^}]*\{\{/.test(e))throw new Error("Invalid template syntax: malformed handlebars")}getCacheKey(e){let t=0;for(let r=0;r<e.length;r++){t=(t<<5)-t+e.charCodeAt(r),t&=t}return t.toString()}setupBuiltinHelpers(){}},exports.TopicCreationError=sg,exports.TopicRegistrationError=Wf,exports.TransactionParser=ga,exports.TransactionParsingError=rs,exports.UAID_DID_RESOLUTION_PROFILE_ID=Gm,exports.UAID_DNS_WEB_PROFILE_ID=Zm,exports.UaidDidResolutionProfileResolver=Xm,exports.UaidDnsWebProfileResolver=tf,exports.VerificationType=Ih,exports.WasmBridge=class{constructor(){this.wasm=null,this.WASM_VECTOR_LEN=0,this.cachedUint8Memory=null,this.cachedDataViewMemory=null,this.textEncoder=new TextEncoder,this.textDecoder=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),this.textDecoder.decode(),this.logger=y.getInstance({module:"WasmBridge"})}setLogLevel(e){this.logger.setLogLevel(e)}get wasmInstance(){if(!this.wasm)throw new Error("WASM not initialized");return this.wasm}getUint8Memory(){if(!this.wasm)throw new Error("WASM not initialized");return null!==this.cachedUint8Memory&&0!==this.cachedUint8Memory.byteLength||(this.cachedUint8Memory=new Uint8Array(this.wasm.memory.buffer)),this.cachedUint8Memory}getDataViewMemory(){if(!this.wasm)throw new Error("WASM not initialized");return null!==this.cachedDataViewMemory&&this.cachedDataViewMemory.buffer===this.wasm.memory.buffer||(this.cachedDataViewMemory=new DataView(this.wasm.memory.buffer)),this.cachedDataViewMemory}encodeString(e,t){if(0===e.length)return{read:0,written:0};const r=this.textEncoder.encode(e);return t.set(r),{read:e.length,written:r.length}}passStringToWasm(e,t,r){if(void 0===r){const r=this.textEncoder.encode(e),i=t(r.length,1);return this.getUint8Memory().set(r,i),this.WASM_VECTOR_LEN=r.length,i}let i=this.textEncoder.encode(e).length,n=t(i,1);const o=this.getUint8Memory();let s=0;for(;s<i;s++){const t=e.charCodeAt(s);if(t>127)break;o[n+s]=t}if(s!==i){0!==s&&(e=e.slice(s)),n=r(n,i,i=s+3*this.textEncoder.encode(e).length,1);const t=this.getUint8Memory().subarray(n+s,n+i);s+=this.encodeString(e,t).written}return this.WASM_VECTOR_LEN=s,n}getStringFromWasm(e,t){return e>>>=0,this.textDecoder.decode(this.getUint8Memory().subarray(e,e+t))}createWasmFunction(e){if(!this.wasm)throw new Error("WASM not initialized");return(...t)=>{const r=this.wasm.__wbindgen_add_to_stack_pointer(-16);let i=[0,0];try{const n=[r,...t.map(e=>[this.passStringToWasm(e,this.wasm.__wbindgen_malloc,this.wasm.__wbindgen_realloc),this.WASM_VECTOR_LEN]).flat()];e.apply(this.wasm,n);const o=this.getDataViewMemory().getInt32(r+0,!0),s=this.getDataViewMemory().getInt32(r+4,!0);return i=[o,s],this.getStringFromWasm(o,s)}finally{this.wasm.__wbindgen_add_to_stack_pointer(16),this.wasm.__wbindgen_free(i[0],i[1],1)}}}async initWasm(e){const t=this,r={__wbindgen_placeholder__:{__wbindgen_throw:function(e,r){const i=t.getStringFromWasm(e,r);throw t.logger.error(`WASM error: ${i}`),new Error(i)}}};try{this.logger.debug("Compiling WASM module");const t=await WebAssembly.compile(e);this.logger.debug("Instantiating WASM module");const i=await WebAssembly.instantiate(t,r);return this.wasm=i.exports,this.logger.info("WASM module initialized successfully"),this.wasm}catch(i){throw this.logger.error("Failed to initialize WASM module",i),i}}createStateData(e,t={}){let r={};return e?.c?.inputType?.stateData&&(t.latestRoundData&&Object.keys(e.c.inputType.stateData).every(e=>e in t.latestRoundData)?(r.latestRoundData={},Object.entries(e.c.inputType.stateData).forEach(([e,i])=>{r.latestRoundData[e]=String(t.latestRoundData[e])})):Object.entries(e.c.inputType.stateData).forEach(([e,i])=>{const n=t[e];n&&"object"==typeof n&&"values"in n&&n.values.length>0?r[e]=String(n.values[0]):r[e]=this.getDefaultValueForType(i)})),r}getDefaultValueForType(e){return e.startsWith("uint")||e.startsWith("int")||"number"===e?"0":"bool"===e?"false":""}executeWasm(e,t){if(!this.wasm)throw this.logger.error("WASM not initialized"),new Error("WASM not initialized");try{this.logger.debug("Executing WASM with stateData",e);return this.createWasmFunction(this.wasmInstance.process_state)(JSON.stringify(e),JSON.stringify(t))}catch(r){throw this.logger.error("Error executing WASM",r),r}}getParams(){return this.createWasmFunction(this.wasmInstance.get_params)()}},exports.WasmExecutor=jg,exports.WasmValidator=class{constructor(e){this.cryptoAdapter=nh(),this.REQUIRED_EXPORTS=["INFO","POST","GET"],this.ALLOWED_IMPORTS=new Set(["env.console_log","env.get_network","env.submit_hcs_message","env.memory"]),this.MAX_INITIAL_MEMORY=256,this.WARN_MODULE_SIZE=1048576,this.MAX_MODULE_SIZE=5242880,this.logger=e}async validate(e){const t=[],r=[],i={isValid:!0,errors:t,warnings:r};try{if(e.length>this.WARN_MODULE_SIZE&&r.push(`Large module size: ${(e.length/1024/1024).toFixed(2)} MB`),e.length>this.MAX_MODULE_SIZE&&(t.push("Module size exceeds maximum allowed"),i.isValid=!1),!this.validateMagicNumber(e))return t.push("Invalid WASM magic number"),i.isValid=!1,i;const n=this.getWasmVersion(e);if(i.version=n,1!==n)return t.push(`Unsupported WASM version: ${n}`),i.isValid=!1,i;const o=await this.parseModule(e);i.exports=o.exports;for(const e of this.REQUIRED_EXPORTS)o.exports.includes(e)||(t.push(`Missing required export: ${e}`),i.isValid=!1);i.imports=o.imports;for(const e of o.imports){const r=`${e.module}.${e.name}`;this.ALLOWED_IMPORTS.has(r)||(t.push(`Disallowed import: ${r}`),i.isValid=!1)}o.memory&&(i.memoryRequirements=o.memory,o.memory.initial>this.MAX_INITIAL_MEMORY&&(t.push(`Excessive initial memory: ${o.memory.initial} pages`),i.isValid=!1)),o.hasStartFunction&&r.push("Module has start function - may execute code on load"),o.functionCount>100&&r.push(`High function count: ${o.functionCount}`),this.hasSuspiciousPatterns(e)&&r.push("Potentially unsafe operation detected"),i.exportSignatures=o.exportSignatures}catch(n){this.logger.error("WASM validation failed",{error:n}),t.push(`Validation error: ${n instanceof Error?n.message:"Unknown error"}`),i.isValid=!1}return i}async validateInfoFunction(e){const t=[],r=[];try{const i=await e(),n=JSON.parse(i);return n.name&&n.version&&n.hashlinks_version?{isValid:!0,errors:t,warnings:r,moduleInfo:n}:(t.push("INFO missing required fields"),{isValid:!1,errors:t,warnings:r})}catch(i){return t.push("INFO function returned invalid JSON"),{isValid:!1,errors:t,warnings:r}}}async validateActionSchemas(e){const t=[];if(e.validation_rules)for(const[r,i]of Object.entries(e.validation_rules))"object"!=typeof i&&t.push(`Invalid validation rule for action: ${r}`);return{isValid:0===t.length,errors:t,warnings:[]}}async extractMetadata(e){return{size:e.length,hash:await this.calculateHash(e),producers:{language:["Unknown"]}}}async calculateHash(e){if(Xp())return this.createSSRSafeHash(e);const t=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(e)).digest("hex"),r=t instanceof Promise?await t:t;return"string"==typeof r?r:r.toString("hex")}createSSRSafeHash(e){let t=0;for(let r=0;r<Math.min(e.length,1024);r++)t=(t<<5)-t+e[r]&4294967295;return`ssr-wasm-${e.length}-${Math.abs(t).toString(16).padStart(8,"0")}`}validateMagicNumber(e){return e.length>=4&&0===e[0]&&97===e[1]&&115===e[2]&&109===e[3]}getWasmVersion(e){return e.length<8?0:e[4]|e[5]<<8|e[6]<<16|e[7]<<24}async parseModule(e){const t=e.slice(8),r=new TextDecoder("utf-8",{fatal:!1}).decode(t),i=[];r.includes("INFO")&&i.push("INFO"),r.includes("POST")&&i.push("POST"),r.includes("GET")&&i.push("GET"),0===i.length&&e.length>8&&i.push("INFO","POST","GET");const n=[],o=r.split("import:");for(let d=1;d<o.length;d++){const e=o[d].match(/^([a-zA-Z_]+[a-zA-Z0-9_]*)\.([a-zA-Z_]+[a-zA-Z0-9_]*)/);e&&n.push({module:e[1],name:e[2],type:"function"})}let s=1,a=16;const c=r.match(/memory:(\d+)(?:-(\d+))?/);c&&(s=parseInt(c[1]),c[2]&&(a=parseInt(c[2])));let l=10;const u=r.match(/functions:(\d+)/);u&&(l=parseInt(u[1]));return{exports:i,imports:n,memory:{initial:s,maximum:a},functionCount:l,hasStartFunction:r.includes("start:true"),exportSignatures:{INFO:{type:"function",params:[],results:["i32"]},POST:{type:"function",params:["i32","i32","i32","i32"],results:["i32"]},GET:{type:"function",params:["i32","i32","i32"],results:["i32"]}}}}hasSuspiciousPatterns(e){const t=new TextDecoder("utf-8",{fatal:!1}).decode(e);return["eval","__proto__","constructor"].some(e=>t.includes(e))}},exports.WebCryptoAdapter=rh,exports.WebHashAdapter=Gp,exports.WebHmacAdapter=Qp,exports.accountIdsToExemptKeys=cc,exports.actionRegistrationSchema=Ag,exports.adapterConfigContextSchema=fc,exports.adapterDeclarationSchema=yc,exports.adapterManifestSchema=bc,exports.adapterPackageSchema=mc,exports.assemblyMessageSchema=_g,exports.assemblyRegistrationSchema=Pg,exports.baseMessageSchema=yf,exports.blockRegistrationSchema=Cg,exports.buildHCS27TopicMemo=yb,exports.buildHCS27TransactionMemo=wb,exports.buildHcs10ConfirmConnectionTx=Gh,exports.buildHcs10CreateConnectionTopicTx=jh,exports.buildHcs10CreateInboundTopicTx=Hh,exports.buildHcs10CreateOutboundTopicTx=qh,exports.buildHcs10CreateRegistryTopicTx=Wh,exports.buildHcs10OutboundConnectionCreatedRecordTx=Yh,exports.buildHcs10OutboundConnectionRequestRecordTx=Jh,exports.buildHcs10RegistryDeleteTx=Qh,exports.buildHcs10RegistryMigrateTx=eg,exports.buildHcs10RegistryRegisterTx=Zh,exports.buildHcs10SendMessageTx=Xh,exports.buildHcs10SubmitConnectionRequestTx=Vh,exports.buildHcs12AddActionToAssemblyTx=function(e){return _({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs12AddBlockToAssemblyTx=function(e){return _({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs12CreateRegistryTopicTx=function(e){var t;return z({memo:e.memoOverride??(t=e.registry,`hcs-12:1:${e.ttl}:${{action:0,assembly:2,hashlinks:3}[t]}`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})},exports.buildHcs12RegisterAssemblyTx=function(e){return _({topicId:e.assemblyTopicId,message:JSON.stringify(e.registration)})},exports.buildHcs12SubmitMessageTx=function(e){const t="string"==typeof e.payload?e.payload:JSON.stringify(e.payload);return _({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs12UpdateAssemblyTx=function(e){return _({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs15BaseAccountCreateTx=uy,exports.buildHcs15PetalAccountCreateTx=dy,exports.buildHcs16CreateAccountTx=vy,exports.buildHcs16CreateFloraTopicTx=ky,exports.buildHcs16CreateTransactionTopicTx=function(e){const t=(new r.TopicCreateTransaction).setTopicMemo(e.memo);if(e.adminKey&&t.setAdminKey(e.adminKey),e.submitKey&&t.setSubmitKey(e.submitKey),e.feeScheduleKey&&t.setFeeScheduleKey(e.feeScheduleKey),e.customFees&&e.customFees.length>0){const i=e.customFees.map(e=>{const t=(new r.CustomFixedFee).setAmount(e.amount).setFeeCollectorAccountId(r.AccountId.fromString(e.feeCollectorAccountId));return e.denominatingTokenId&&t.setDenominatingTokenId(r.TokenId.fromString(e.denominatingTokenId)),t});t.setCustomFees(i)}if(e.feeExemptKeys&&e.feeExemptKeys.length>0)throw new Error("feeExemptKeys not supported by installed @hashgraph/sdk");return t},exports.buildHcs16FloraCreatedTx=Ay,exports.buildHcs16FloraJoinAcceptedTx=zy,exports.buildHcs16FloraJoinRequestTx=xy,exports.buildHcs16FloraJoinVoteTx=Ny,exports.buildHcs16MessageTx=Ey,exports.buildHcs16ScheduleAccountKeyUpdateTx=function(e){const t=(new r.AccountUpdateTransaction).setAccountId(r.AccountId.fromString(e.floraAccountId)).setKey(e.newKeyList);return t.setTransactionMemo(Iy(e.transactionMemo??e.memo,by)),(new r.ScheduleCreateTransaction).setScheduledTransaction(t)},exports.buildHcs16ScheduleTopicKeyUpdateTx=function(e){const t=(new r.TopicUpdateTransaction).setTopicId(e.topicId);return e.adminKey&&t.setAdminKey(e.adminKey),e.submitKey&&t.setSubmitKey(e.submitKey),t.setTransactionMemo(Iy(e.transactionMemo??e.memo,wy)),(new r.ScheduleCreateTransaction).setScheduledTransaction(t)},exports.buildHcs16StateUpdateTx=Ry,exports.buildHcs16TransactionTx=Cy,exports.buildHcs17CreateTopicTx=By,exports.buildHcs17MessageTx=Ly,exports.buildHcs18AnnounceMessage=Xy,exports.buildHcs18CompleteMessage=eb,exports.buildHcs18CreateDiscoveryTopicTx=Jy,exports.buildHcs18DiscoveryMemo=Gy,exports.buildHcs18ProposeMessage=Zy,exports.buildHcs18RespondMessage=Qy,exports.buildHcs18SubmitDiscoveryMessageTx=Yy,exports.buildHcs18WithdrawMessage=tb,exports.buildHcs1Hrl=df,exports.buildHcs20BurnTx=Zf,exports.buildHcs20DeployTx=Jf,exports.buildHcs20MintTx=Yf,exports.buildHcs20RegisterTx=Qf,exports.buildHcs20SubmitMessageTx=function(e){const t="string"==typeof e.payload?e.payload:JSON.stringify(e.payload);return _({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs20TransferTx=Xf,exports.buildHcs21CreateRegistryTx=ry,exports.buildHcs21MessageTx=iy,exports.buildHcs21RegistryMemo=ty,exports.buildHcs26TopicMemo=function(e){const t=e.indexed??!0,r=function(e){if(!Number.isFinite(e))throw new Error("Expected a finite number");const t=Math.floor(e);if(t<=0)throw new Error("Expected a positive integer");return t}(e.ttlSeconds??86400),i=Mb.parse(e.topicType);return`${Fb}:${t?"0":"1"}:${r}:${i}`},exports.buildHcs26TransactionMemo=function(e){const t=Ub.parse(e.operation),r=Mb.parse(e.topicType);return`${Fb}:op:${t}:${r}`},exports.buildHcs2CreateRegistryTx=vf,exports.buildHcs2DeleteTx=function(e){const t={p:"hcs-2",op:gf.DELETE,uid:e.uid,m:e.memo};return _({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs2MigrateTx=function(e){const t={p:"hcs-2",op:gf.MIGRATE,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return _({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs2RegisterTx=Ef,exports.buildHcs2UpdateTx=function(e){const t={p:"hcs-2",op:gf.UPDATE,uid:e.uid,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return _({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs5MintTx=hf,exports.buildHcs5MintWithHrlTx=function(e){const t=df(e.metadataTopicId);return hf({tokenId:e.tokenId,metadata:t,transactionMemo:e.transactionMemo})},exports.buildHcs6CreateRegistryTx=P,exports.buildHcs6Hrl=S,exports.buildHcs6RegisterEntryTx=function(e){const t={p:"hcs-6",op:I.REGISTER,t_id:e.targetTopicId,m:e.memo};return _({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs7CreateRegistryTx=rc,exports.buildHcs7EvmMessageTx=function(e){const t={p:"hcs-7",op:qa.REGISTER_CONFIG,t:ja.EVM,c:{contractAddress:e.config.contractAddress,abi:e.config.abi},m:e.config.memo??""};return ic({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs7SubmitMessageTx=ic,exports.buildHcs7WasmMessageTx=function(e){const t={p:"hcs-7",op:qa.REGISTER_CONFIG,t:ja.WASM,c:{wasmTopicId:e.config.wasmTopicId,inputType:e.config.inputType,outputType:e.config.outputType},m:e.config.memo??""};return ic({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildJobStatusMessage=e=>JSON.stringify({p:Hp,op:"job_status",request_id:e.requestId,data:{job_id:e.jobId}}),exports.buildPaymentApproveMessage=e=>JSON.stringify({p:Hp,op:"payment_approve",request_id:e.requestId,data:{job_id:e.jobId}}),exports.buildPaymentDeclineMessage=e=>JSON.stringify({p:Hp,op:"payment_decline",request_id:e.requestId}),exports.canonicalize=sy,exports.canonicalizeAgentData=em,exports.canonicalizeHCS27Json=Eb,exports.canonicalizeLedgerNetwork=_p,exports.capabilityNameToCapabilityMap=kh,exports.closeUaidConnection=Ep,exports.createLoggerAdapter=sc,exports.createPrivateKeySigner=e=>Dp((()=>{if(Op)return Op;const e=Sa("@hashgraph/sdk");if(e)return Op=e,e;throw new Error("@hashgraph/sdk is required for ledger signing. Install it as a dependency to enable createPrivateKeySigner.")})(),e),exports.createPrivateKeySignerAsync=Fp,exports.createRegistryBrokerVerificationProvider=vw,exports.createUaid=sm,exports.dashboardStats=Ap,exports.defaultIssuerRegistry=nf,exports.defaultResolverRegistry=bm,exports.deleteMessageSchema=If,exports.detectCryptoEnvironment=Yp,exports.detectKeyTypeFromString=M,exports.emptyHCS27Root=Ab,exports.ensureLoggerType=function(e){return ac(e)?e:sc(e)},exports.extractReferenceId=function(e){const t=e.trim(),r=t.match(/^content-ref:([a-f0-9]+)$/);if(r)return r[1];const i=t.match(/content-ref:([a-f0-9]+)/);return i?i[1]:null},exports.generateHCS17Memo=Fy,exports.generateHCS6RegistryMemo=R,exports.generateQuote=Ba,exports.getCryptoAdapter=nh,exports.getExampleTopics=function(e){return"mainnet"===e?Jg:Gg},exports.getHumanReadableTransactionType=ha,exports.getOrCreateSDK=Ea,exports.getParserConfig=function(e){return ca[e]},exports.getRegistrationProgress=Tp,exports.getRegistrationQuote=wp,exports.getRegistryBrokerQuote=async function(e,t={}){const r=y.getInstance({module:"InscribeViaBroker",...t.logging}),i=t.baseUrl??Ka,n={"Content-Type":"application/json",Accept:"application/json"};if(t.ledgerApiKey)n["x-api-key"]=t.ledgerApiKey;else{if(!t.apiKey)throw new Error("Either ledgerApiKey or apiKey is required for Registry Broker quotes");n["x-api-key"]=t.apiKey}let o,s,a;switch(e.type){case"url":break;case"file":{const t=await za(e.path);o=t.base64,s=t.fileName,a=t.mimeType;break}case"buffer":o=globalThis.Buffer.from(e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer):e.buffer).toString("base64"),s=e.fileName,a=e.mimeType}const c={inputType:"url"===e.type?"url":"base64",mode:t.mode??"file"};return"url"===e.type?c.url=e.url:(c.base64=o,c.fileName=s,a&&(c.mimeType=a)),t.metadata&&(c.metadata=t.metadata),t.tags&&(c.tags=t.tags),t.fileStandard&&(c.fileStandard=t.fileStandard),t.chunkSize&&(c.chunkSize=t.chunkSize),r.debug("Getting inscription quote from Registry Broker"),$a(`${i}/inscribe/content/quote`,{method:"POST",headers:n,body:JSON.stringify(c)})},exports.getSchedulableTransactionType=function(e){for(const[t,r]of Object.entries(da))if(e[t])return r;return"unknown"},exports.getSupportedTransactionTypes=function(){return Object.keys(ca)},exports.getTopicId=Ha,exports.getTransactionTypeFromBody=pa,exports.getUaidConnectionStatus=vp,exports.hash=oh,exports.hashHCS27Leaf=Cb,exports.hashHCS27Node=Rb,exports.hashLinksRegistrationSchema=Og,exports.hcs17MessageSchema=Py,exports.hcs26DiscoveryDeleteSchema=Xb,exports.hcs26DiscoveryMessageSchema=aw,exports.hcs26DiscoveryMetadataPatchSchema=Wb,exports.hcs26DiscoveryMetadataSchema=jb,exports.hcs26DiscoveryMigrateSchema=Zb,exports.hcs26DiscoveryRegisterLegacySchema=Gb,exports.hcs26DiscoveryRegisterSchema=Vb,exports.hcs26DiscoveryUpdateLegacySchema=Yb,exports.hcs26DiscoveryUpdateSchema=Jb,exports.hcs26ManifestFileSchema=ow,exports.hcs26OperationEnumSchema=Ub,exports.hcs26SkillManifestSchema=sw,exports.hcs26TopicMemoSchema=Iw,exports.hcs26TopicTypeEnumSchema=Mb,exports.hcs26TransactionMemoSchema=Tw,exports.hcs26VersionDeleteSchema=iw,exports.hcs26VersionMessageSchema=cw,exports.hcs26VersionMigrateSchema=nw,exports.hcs26VersionRegisterLegacySchema=tw,exports.hcs26VersionRegisterSchema=ew,exports.hcs26VersionUpdateSchema=rw,exports.hcs27CheckpointMessageSchema=pb,exports.hcs27CheckpointMetadataSchema=ub,exports.hcs27ConsistencyProofSchema=gb,exports.hcs27InclusionProofSchema=hb,exports.hcs27MetadataDigestSchema=db,exports.hcs27PreviousCommitmentSchema=ab,exports.hcs27RootCommitmentSchema=sb,exports.hcs27SignatureSchema=cb,exports.hcs2MessageSchema=Sf,exports.hcs6BaseMessageSchema=v,exports.hcs6MessageSchema=A,exports.hcs6RegisterMessageSchema=E,exports.hcs6TopicIdSchema=k,exports.hcs7MessageSchema=Qa,exports.humanReadableTypeRegistry=ua,exports.inscribe=Oa,exports.inscribeViaRegistryBroker=async function(e,t={}){const r=y.getInstance({module:"InscribeViaBroker",...t.logging}),i=t.baseUrl??Ka,n=t.waitForConfirmation??!0,o=t.waitTimeoutMs??12e4,s=t.pollIntervalMs??2e3,a={"Content-Type":"application/json",Accept:"application/json"};if(t.ledgerApiKey)a["x-api-key"]=t.ledgerApiKey;else{if(!t.apiKey)throw new Error("Either ledgerApiKey or apiKey is required for Registry Broker inscription");a["x-api-key"]=t.apiKey}let c,l,u;switch(r.info("Starting inscription via Registry Broker",{baseUrl:i,inputType:e.type,mode:t.mode??"file"}),e.type){case"url":r.debug("Creating job with URL input");break;case"file":{const t=await za(e.path);c=t.base64,l=t.fileName,u=t.mimeType;break}case"buffer":c=globalThis.Buffer.from(e.buffer instanceof ArrayBuffer?new Uint8Array(e.buffer):e.buffer).toString("base64"),l=e.fileName,u=e.mimeType}const d={inputType:"url"===e.type?"url":"base64",mode:t.mode??"file"};"url"===e.type?d.url=e.url:(d.base64=c,d.fileName=l,u&&(d.mimeType=u)),t.metadata&&(d.metadata=t.metadata),t.tags&&(d.tags=t.tags),t.fileStandard&&(d.fileStandard=t.fileStandard),t.chunkSize&&(d.chunkSize=t.chunkSize),r.debug("Creating inscription job");const p=await $a(`${i}/inscribe/content`,{method:"POST",headers:a,body:JSON.stringify(d)}),h=p.jobId??p.id??"";if(r.info("Inscription job created",{jobId:h,status:p.status}),!n)return{confirmed:!1,jobId:h,status:p.status,credits:p.credits??p.quoteCredits,usdCents:p.usdCents??p.quoteUsdCents,sizeBytes:p.sizeBytes,createdAt:p.createdAt,updatedAt:p.updatedAt,network:p.network};r.debug("Polling for job completion",{jobId:h,waitTimeoutMs:o});const g=Date.now();let m="";for(;Date.now()-g<o;){const e=await $a(`${i}/inscribe/content/${h}`,{method:"GET",headers:a});if(e.status!==m&&(r.debug("Job status update",{jobId:h,status:e.status}),m=e.status),"completed"===e.status)return r.info("Inscription completed",{jobId:h,hrl:e.hrl,topicId:e.topicId}),{confirmed:!0,jobId:h,status:e.status,hrl:e.hrl,topicId:e.topicId,network:e.network,credits:e.credits??e.quoteCredits,usdCents:e.usdCents??e.quoteUsdCents,sizeBytes:e.sizeBytes,createdAt:e.createdAt,updatedAt:e.updatedAt};if("failed"===e.status)return r.error("Inscription failed",{jobId:h,error:e.error}),{confirmed:!1,jobId:h,status:e.status,error:e.error??"Inscription failed",credits:e.credits??e.quoteCredits,createdAt:e.createdAt,updatedAt:e.updatedAt};await b(s)}throw new Error(`Inscription job ${h} did not complete within ${o}ms`)},exports.inscribeWithSigner=Fa,exports.isAnnounceMessage=function(e){if(!jy(e))return!1;const t=e;if("announce"!==t.op)return!1;if(!$y(t.data))return!1;const r=t.data;if(!Hy(r.account))return!1;if(!$y(r.petal))return!1;const i=r.petal;return!(!Hy(i.name)||!qy(i.priority))&&(!!$y(r.capabilities)&&(!!function(e){return Array.isArray(e)&&e.every(Hy)}(r.capabilities.protocols)&&!("valid_for"in r&&void 0!==r.valid_for&&null!==r.valid_for&&!qy(r.valid_for))))},exports.isBrowser=ma,exports.isCompleteMessage=function(e){if(!jy(e))return!1;const t=e;if("complete"!==t.op)return!1;if(!$y(t.data))return!1;const r=t.data;if(!Hy(r.proposer))return!1;if(!qy(r.proposal_seq))return!1;if(!Hy(r.flora_account))return!1;if(!$y(r.topics))return!1;const i=r.topics;return!!(Hy(i.communication)&&Hy(i.transaction)&&Hy(i.state))},exports.isConcreteLogger=ac,exports.isCryptoAvailable=function(){return"none"!==Yp().preferredAPI},exports.isDidProfileResolverAdapter=pm,exports.isDidResolverAdapter=hm,exports.isDiscoveryMessage=jy,exports.isEip155Caip10=hh,exports.isHederaCaip10=lh,exports.isHederaNetwork=ah,exports.isHolChatOp=jp,exports.isPartialRegisterAgentResponse=e=>"partial"===e.status&&!1===e.success,exports.isPendingRegisterAgentResponse=e=>"pending"===e.status,exports.isProposeMessage=function(e){if(!jy(e))return!1;const t=e;if("propose"!==t.op)return!1;if(!$y(t.data))return!1;const r=t.data;if(!Hy(r.proposer))return!1;if(!function(e){return Array.isArray(e)}(r.members))return!1;if(!r.members.every(e=>{if(!$y(e))return!1;const t=e;return!!Hy(t.account)&&(!(!("priority"in t)||!qy(t.priority))&&!("announce_seq"in t&&void 0!==t.announce_seq&&null!==t.announce_seq&&!qy(t.announce_seq)))}))return!1;if(!$y(r.config))return!1;const i=r.config;return!(!Hy(i.name)||!qy(i.threshold))},exports.isRespondMessage=function(e){if(!jy(e))return!1;const t=e;if("respond"!==t.op)return!1;if(!$y(t.data))return!1;const r=t.data;return!!Hy(r.responder)&&(!!qy(r.proposal_seq)&&(!!Hy(r.decision)&&!!["accept","reject"].includes(r.decision)))},exports.isSSREnvironment=Xp,exports.isSuccessRegisterAgentResponse=e=>!0===e.success&&"pending"!==e.status,exports.isTransactionTypeSupported=function(e){return e in ca},exports.isUaidProfileResolverAdapter=dm,exports.isWithdrawMessage=function(e){if(!jy(e))return!1;const t=e;if("withdraw"!==t.op)return!1;if(!$y(t.data))return!1;const r=t.data;return!!Hy(r.account)&&(!!qy(r.announce_seq)&&!("reason"in r&&void 0!==r.reason&&null!==r.reason&&!Hy(r.reason)))},exports.leafHashHexFromEntry=zb,exports.mcpServiceNameToCapabilityMap=vh,exports.merkleRootFromCanonicalEntries=xb,exports.merkleRootFromEntries=Nb,exports.metadataDocumentSchema=Ic,exports.migrateMessageSchema=Tf,exports.nodeDnsTxtLookup=vm,exports.normalizeTransactionId=xa,exports.parseHCS17Memo=My,exports.parseHCS27TopicMemo=bb,exports.parseHcs14Did=am,exports.parseHcs26TopicMemo=bw,exports.parseHcs26TransactionMemo=ww,exports.parseHederaCaip10=dh,exports.parseHolChatOps=e=>Array.isArray(e)?e.filter(jp).map(e=>{const t={p:Hp,op:e.op,request_id:e.request_id.trim()};return"string"==typeof e.m&&e.m.trim().length>0&&(t.m=e.m.trim()),qp(e.data)&&(t.data={...e.data}),t}):[],exports.protoFieldToTypeRegistry=la,exports.registerAgent=async function(e,t,r){const i=r?.autoTopUp??e.registrationAutoTopUp;if(!i)return gp(e,t);await yp(e,t,i);let n=!1;for(;;)try{return await gp(e,t)}catch(o){if(e.extractInsufficientCreditsDetails(o)&&!n){await yp(e,t,i),n=!0;continue}throw o}},exports.registerDefaultResolvers=wm,exports.registerMessageSchema=bf,exports.registryMetadataSchema=wc,exports.resolveTransactionSummary=Xs,exports.resolveUaid=bp,exports.retrieveInscription=Ma,exports.safeValidate=function(e,t){const r=e.safeParse(t);return r.success?{success:!0,data:r.data}:{success:!1,errors:r.error}},exports.schedulableTransactionTypeRegistry=da,exports.setLoggerFactory=function(e){m=e,y.clearInstances()},exports.shouldUseReference=function(e){return("string"==typeof e?globalThis.Buffer.byteLength(e,"utf8"):e.length)>51200},exports.sleep=b,exports.toEip155Caip10=gh,exports.toHCS27CheckpointMessage=fb,exports.toHCS27CheckpointMetadata=mb,exports.toHederaCaip10=uh,exports.topicIdSchema=ff,exports.transactionParserRegistry=ca,exports.transactionSummaryRegistry=Ys,exports.updateAgent=Ip,exports.updateMessageSchema=wf,exports.validateActionRegistration=Dg,exports.validateAssemblyMessage=Fg,exports.validateAssemblyRegistration=function(e){return Pg.parse(e)},exports.validateBlockRegistration=function(e){return Cg.parse(e)},exports.validateHCS6RegistryMemo=function(e){const t=e.match(/^hcs-6:(\d):(\d+)$/);if(!t)return!1;const r=parseInt(t[1]),i=parseInt(t[2]);return 1===r&&C(i)},exports.validateHCS6TTL=C,exports.validateHashLinksRegistration=function(e){return Og.parse(e)},exports.validateUaid=kp,exports.validateWithSchema=Mg,exports.verifyArtifactDigest=function(e,t){const r=d.createHash("sha384");r.update(e);const i=r.digest("hex").toLowerCase(),n=globalThis.Buffer.from(i,"hex").toString("base64").toLowerCase(),o=t.replace(/^sha384[-:]?/i,"").trim().toLowerCase();return o===i||o===n},exports.verifyConsistencyProof=Pb,exports.verifyDeclarationSignature=function(e,t){if(!e.signature)return!1;try{const{signature:i,...n}=e,o=sy(n),s=globalThis.Buffer.from(i,"base64");return r.PublicKey.fromString(t).verify(globalThis.Buffer.from(o,"utf8"),s)}catch{return!1}},exports.verifyInclusionProof=_b,exports.verifyManifestSignature=function(e,t,i){try{const n=sy(e),o=globalThis.Buffer.from(t,"base64");return r.PublicKey.fromString(i).verify(globalThis.Buffer.from(n,"utf8"),o)}catch{return!1}},exports.waitForInscriptionConfirmation=La,exports.waitForRegistrationCompletion=Sp;
|
|
11
11
|
//# sourceMappingURL=standards-sdk.cjs.map
|