@hashgraphonline/standards-sdk 0.1.141-canary.3 → 0.1.141-canary.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/services/registry-broker/private-key-signer.d.ts.map +1 -1
- package/dist/cjs/standards-sdk.cjs +2 -2
- package/dist/cjs/standards-sdk.cjs.map +1 -1
- package/dist/es/services/registry-broker/private-key-signer.d.ts.map +1 -1
- package/dist/es/standards-sdk.es101.js +1 -1
- package/dist/es/standards-sdk.es103.js +1 -1
- package/dist/es/standards-sdk.es109.js +2 -2
- package/dist/es/standards-sdk.es110.js +5 -5
- package/dist/es/standards-sdk.es12.js +1 -1
- package/dist/es/standards-sdk.es120.js +1 -1
- package/dist/es/standards-sdk.es121.js +1 -1
- package/dist/es/standards-sdk.es122.js +5 -5
- package/dist/es/standards-sdk.es124.js +1 -1
- package/dist/es/standards-sdk.es125.js +1 -1
- package/dist/es/standards-sdk.es127.js +1 -1
- package/dist/es/standards-sdk.es128.js +22 -1
- package/dist/es/standards-sdk.es128.js.map +1 -1
- package/dist/es/standards-sdk.es13.js +1 -1
- package/dist/es/standards-sdk.es135.js +12241 -105
- package/dist/es/standards-sdk.es135.js.map +1 -1
- package/dist/es/standards-sdk.es136.js +760 -42
- package/dist/es/standards-sdk.es136.js.map +1 -1
- package/dist/es/standards-sdk.es137.js +138 -760
- package/dist/es/standards-sdk.es137.js.map +1 -1
- package/dist/es/standards-sdk.es138.js +36 -50
- package/dist/es/standards-sdk.es138.js.map +1 -1
- package/dist/es/standards-sdk.es139.js +15 -62
- package/dist/es/standards-sdk.es139.js.map +1 -1
- package/dist/es/standards-sdk.es140.js +54 -12272
- package/dist/es/standards-sdk.es140.js.map +1 -1
- package/dist/es/standards-sdk.es141.js +53 -161
- package/dist/es/standards-sdk.es141.js.map +1 -1
- package/dist/es/standards-sdk.es142.js +139 -289
- package/dist/es/standards-sdk.es142.js.map +1 -1
- package/dist/es/standards-sdk.es143.js +274 -298
- package/dist/es/standards-sdk.es143.js.map +1 -1
- package/dist/es/standards-sdk.es144.js +262 -369
- package/dist/es/standards-sdk.es144.js.map +1 -1
- package/dist/es/standards-sdk.es145.js +316 -194
- package/dist/es/standards-sdk.es145.js.map +1 -1
- package/dist/es/standards-sdk.es146.js +319 -64
- package/dist/es/standards-sdk.es146.js.map +1 -1
- package/dist/es/standards-sdk.es147.js +74 -15
- package/dist/es/standards-sdk.es147.js.map +1 -1
- package/dist/es/standards-sdk.es17.js +2 -1
- package/dist/es/standards-sdk.es17.js.map +1 -1
- package/dist/es/standards-sdk.es19.js +5 -4
- package/dist/es/standards-sdk.es19.js.map +1 -1
- package/dist/es/standards-sdk.es20.js +3 -2
- package/dist/es/standards-sdk.es20.js.map +1 -1
- package/dist/es/standards-sdk.es23.js +1 -1
- package/dist/es/standards-sdk.es28.js +4 -3
- package/dist/es/standards-sdk.es28.js.map +1 -1
- package/dist/es/standards-sdk.es31.js +1 -1
- package/dist/es/standards-sdk.es32.js +1 -1
- package/dist/es/standards-sdk.es36.js +4 -3
- package/dist/es/standards-sdk.es36.js.map +1 -1
- package/dist/es/standards-sdk.es37.js +3 -3
- package/dist/es/standards-sdk.es38.js +1 -1
- package/dist/es/standards-sdk.es5.js +1 -1
- package/dist/es/standards-sdk.es54.js +1 -1
- package/dist/es/standards-sdk.es57.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.es61.js +3 -2
- package/dist/es/standards-sdk.es61.js.map +1 -1
- package/dist/es/standards-sdk.es63.js +1 -1
- package/dist/es/standards-sdk.es65.js +1 -1
- package/dist/es/standards-sdk.es66.js +2 -2
- package/dist/es/standards-sdk.es69.js +2 -2
- package/dist/es/standards-sdk.es70.js +1 -1
- package/dist/es/standards-sdk.es72.js +1 -1
- package/dist/es/standards-sdk.es77.js +1 -1
- package/dist/es/standards-sdk.es78.js +2 -2
- package/dist/es/standards-sdk.es79.js +1 -1
- package/dist/es/standards-sdk.es8.js +1 -1
- package/dist/es/standards-sdk.es82.js +1 -1
- package/dist/es/standards-sdk.es84.js +1 -1
- package/dist/es/standards-sdk.es87.js +1 -1
- package/dist/es/standards-sdk.es91.js +1 -1
- package/dist/es/standards-sdk.es92.js +1 -1
- package/dist/es/standards-sdk.es97.js +1 -1
- package/dist/es/standards-sdk.es99.js +1 -1
- package/package.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var e;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("util"),r=require("zod"),i=require("@hashgraph/sdk"),o=require("axios"),n=require("@hashgraph/proto"),s=require("@hashgraphonline/standards-sdk"),a=require("buffer"),c=require("ethers"),l=require("file-type"),d=require("node:path"),u=require("node:buffer"),p=require("node:crypto"),h=require("@noble/curves/secp256k1.js"),g=require("viem/accounts");require("viem/chains");const m=require("x402-axios"),f=require("x402/types"),y=require("mime-types"),b=require("date-fns"),w=require("crypto");var I="undefined"!=typeof document?document.currentScript:null;function T(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const r in e)if("default"!==r){const i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:()=>e[r]})}return t.default=e,Object.freeze(t)}const S=T(d),k=T(y),E=/^\d+\.\d+\.\d+$/u,A=Symbol.for("standards-sdk.topic-auto-renew.patch"),v=Symbol.for("standards-sdk.account-id.patch"),C=function(){const e=function(){try{if("undefined"!=typeof module&&module?.createRequire)return module}catch{}try{if("function"==typeof require){const e=require("module");if(e?.createRequire)return e}}catch{}return null}();if(e?.createRequire)try{return e.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:I&&"SCRIPT"===I.tagName.toUpperCase()&&I.src||new URL("standards-sdk.cjs",document.baseURI).href)}catch{return null}if("function"==typeof require)return require;return null}();function x(e,t){try{return e(t)}catch{return null}}function R(e,t){if(!e||!t)return;!function(e){if(Reflect.get(e,v))return;const t=e.fromString.bind(e);e.fromString=function(e){if("string"==typeof e)return t(e);const r=_(e);if(r)return t(r);if(P(e)){const r=O(e.shard),i=O(e.realm),o=O(e.num);if(r&&i&&o)return t(`${r}.${i}.${o}`)}return t(e)},Reflect.set(e,v,!0)}(t);const r=e.prototype;if(Reflect.get(r,A))return;const i=r.setAutoRenewAccountId,o=r.freezeWith;r.setAutoRenewAccountId=function(e){const r=N(e,t);return r?(function(e){const t=e;t._requireNotFrozen?.()}(this),this._autoRenewAccountId=r,this):i.call(this,e)},r.freezeWith=function(e){if(!this.getAutoRenewAccountId||"function"!=typeof this.getAutoRenewAccountId)return o.call(this,e);if(!this.getAutoRenewAccountId()){const r=this.transactionId?.accountId,i=e?.operatorAccountId,o=N(r,t)??N(i,t);o&&(this._autoRenewAccountId=o)}return o.call(this,e)},Reflect.set(r,A,!0)}function N(e,t){if(e instanceof t)return e;if("string"==typeof e&&E.test(e))return t.fromString(e);const r=function(e){if("string"==typeof e&&E.test(e))return e;const t=_(e);if(t)return t;if(P(e)){const t=O(e.shard),r=O(e.realm),i=O(e.num);if(t&&r&&i){const e=`${t}.${r}.${i}`;if(E.test(e))return e}}return null}(e);return r?t.fromString(r):null}function _(e){if("object"!=typeof e||null===e)return null;const t=e.toString;if("function"!=typeof t)return null;const r=t.call(e);return"string"!=typeof r?null:E.test(r)?r:null}function P(e){if("object"!=typeof e||null===e)return!1;const t=e;return F(t.shard)&&F(t.realm)&&F(t.num)}function F(e){return"object"==typeof e&&null!==e&&"function"==typeof e.toString}function O(e){if("number"==typeof e&&Number.isFinite(e))return String(Math.trunc(e));if("bigint"==typeof e)return e.toString();if(F(e)){const t=e.toString();if(/^\d+$/u.test(t))return t}return null}C?function(e){const t=x(e,"@hashgraph/sdk/lib/account/AccountId.cjs"),r=x(e,"@hashgraph/sdk/lib/topic/TopicCreateTransaction.cjs"),i=x(e,"@hashgraph/sdk"),o=[];t?.default&&r?.default&&o.push({accountId:t.default,topic:r.default});i&&o.push({accountId:i.AccountId??i.default?.AccountId,topic:i.TopicCreateTransaction??i.default?.TopicCreateTransaction});for(const n of o)R(n.topic,n.accountId);Reflect.set(globalThis,"__standardsSdkTopicAutoRenewPatched",!0)}(C):Reflect.set(globalThis,"__standardsSdkTopicAutoRenewPatched",!1);let z=null;let D=((e=class{constructor(e={}){if(z)return z(e);const t="undefined"!=typeof process&&"true"===process.env?.DISABLE_LOGS;this.silent=e.silent||t,this.level=this.silent?"silent":e.level||"info",this.moduleContext=e.module||"app",this.prettyPrint=!this.silent&&!1!==e.prettyPrint}static getInstance(t={}){const r=t.module||"default";if("undefined"!=typeof process&&"true"===process.env?.DISABLE_LOGS&&e.instances.has(r)){"silent"!==e.instances.get(r).getLevel()&&e.instances.delete(r)}if(!e.instances.has(r)){const i=z?z(t):new e(t);e.instances.set(r,i)}return e.instances.get(r)}setLogLevel(e){this.level=e}getLevel(){return this.level}setSilent(e){this.silent=e,e&&(this.level="silent")}setModule(e){this.moduleContext=e}formatArgs(e){if(0===e.length)return{msg:""};if(1===e.length)return"string"==typeof e[0]?{msg:e[0]}:{msg:"",data:e[0]};const t=[],r=[];e.forEach(e=>{"string"==typeof e||"number"==typeof e||"boolean"==typeof e?t.push(String(e)):r.push(e)});const i=t.join(" ");return r.length>0?{msg:i,data:r}:{msg:i}}shouldLog(e){if(this.silent||"silent"===this.level)return!1;const t=["trace","debug","info","warn","error","silent"],r=t.indexOf(this.level);return t.indexOf(e)>=r}getConsoleMethod(e){return"error"===e?console.error:"warn"===e?console.warn:"debug"===e?console.debug:console.log}writeLog(e,...r){if(!this.shouldLog(e))return;const{msg:i,data:o}=this.formatArgs(r),n=(new Date).toISOString(),s=this.getConsoleMethod(e);if(this.prettyPrint){let r=`${n} ${e.toUpperCase().padEnd(5)} [${this.moduleContext}] ${i}`;o&&(r+="\n"+t.inspect(o,{colors:!0,depth:3})),s(r)}else{const t={timestamp:n,level:e,module:this.moduleContext,message:i,...o&&{data:o}};s(JSON.stringify(t))}}debug(...e){this.writeLog("debug",...e)}info(...e){this.writeLog("info",...e)}warn(...e){this.writeLog("warn",...e)}error(...e){this.writeLog("error",...e)}trace(...e){this.writeLog("trace",...e)}static clearInstances(){e.instances.clear()}}).instances=new Map,e);const B=e=>new Promise(t=>setTimeout(t,e));class M{constructor(){this.modelViewerLoaded=!1,this.modelViewerLoading=null,this.config={cdnUrl:"https://kiloscribe.com/api/inscription-cdn/",network:"mainnet",retryAttempts:3,retryBackoff:300,debug:!1,showLoadingIndicator:!1,loadingCallbackName:null},this.configMapping={hcsCdnUrl:"cdnUrl",hcsNetwork:"network",hcsRetryAttempts:"retryAttempts",hcsRetryBackoff:"retryBackoff",hcsDebug:"debug",hcsShowLoadingIndicator:"showLoadingIndicator",hcsLoadingCallbackName:"loadingCallbackName"},this.LoadedScripts={},this.LoadedWasm={},this.LoadedImages={},this.LoadedVideos={},this.LoadedAudios={},this.LoadedAudioUrls={},this.LoadedGLBs={},this.scriptLoadedEvent=new Event("HCSScriptLoaded"),this.loadQueue=[],this.isProcessingQueue=!1;try{this.logger=D.getInstance({module:"HCS-3",level:this.config.debug?"debug":"error"})}catch(e){this.logger=this.createFallbackLogger()}}createFallbackLogger(){return{debug:(...e)=>this.config.debug&&console.debug("[HCS-3]",...e),info:(...e)=>this.config.debug&&console.info("[HCS-3]",...e),warn:(...e)=>console.warn("[HCS-3]",...e),error:(...e)=>console.error("[HCS-3]",...e),setLogLevel:e=>{this.config.debug="debug"===e}}}log(...e){if(0===e.length)this.logger.debug("");else if(1===e.length)this.logger.debug(String(e[0]));else{const t=String(e[0]),r=e.slice(1);this.logger.debug(t,r)}}error(...e){if(0===e.length)this.logger.error("");else if(1===e.length)this.logger.error(String(e[0]));else{const t=String(e[0]),r=e.slice(1);this.logger.error(t,r)}}loadConfigFromHTML(){const e=document.querySelector("script[data-hcs-config]");e&&(Object.keys(this.configMapping).forEach(t=>{if(e.dataset[t]){const r=this.configMapping[t];let i=e.dataset[t];"true"===i&&(i=!0),"false"===i&&(i=!1),isNaN(Number(i))||""===i||(i=Number(i)),this.config[r]=i}}),this.logger.setLogLevel(this.config.debug?"debug":"error")),this.log("Loaded config:",this.config)}updateLoadingStatus(e,t){if("loaded"!==this.LoadedScripts[e]&&(this.config.showLoadingIndicator&&console.log("[HCS Loading] "+e+" : "+t),this.LoadedScripts[e]=t,this.config.loadingCallbackName&&"function"==typeof window[this.config.loadingCallbackName])){const r=window[this.config.loadingCallbackName];"function"==typeof r&&r(e,t)}}async fetchWithRetry(e,t=this.config.retryAttempts,r=this.config.retryBackoff){try{const t=await fetch(e);if(!t.ok)throw new Error("HTTP error! status: "+t.status);return t}catch(i){if(t>0)return this.log("Retrying fetch for "+e+" Attempts left: "+(t-1)),await this.sleep(r),this.fetchWithRetry(e,t-1,2*r);throw i}}sleep(e){return B(e)}isDuplicate(e){return!!this.LoadedScripts[e]}async retrieveHCS1Data(e,t=this.config.cdnUrl,r=this.config.network){const i=r.replace(/['"]+/g,""),o=await this.fetchWithRetry(t+e+"?network="+i);return await o.blob()}async loadScript(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),i=t?.split("/").pop(),o=e.getAttribute("type"),n=e.hasAttribute("data-required"),s="module"===e.getAttribute("type");if(!this.isDuplicate(i||"")){this.updateLoadingStatus(r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,a=e.getAttribute("data-network")||this.config.network,c=await this.retrieveHCS1Data(i,t,a);if("wasm"===o){const t=await c.arrayBuffer(),i=await WebAssembly.compile(t);this.LoadedWasm[r]=await WebAssembly.instantiate(i,{env:{},...e.dataset}),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded wasm: "+r)}else{const e=await c.text(),t=document.createElement("script");if(t.textContent=e,t.className="hcs-inline-script",r&&t.setAttribute("data-loaded-script-id",r),s){t.type="module";const r=new Blob([e],{type:"application/javascript"});t.src=URL.createObjectURL(r)}document.body.appendChild(t),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded script: "+r),t.onerror=e=>{if(this.error("Failed to load "+o+": "+r,e),this.updateLoadingStatus(r,"failed"),n)throw e}}}catch(a){if(this.error("Failed to load "+o+": "+r,a),this.updateLoadingStatus(r,"failed"),n)throw a}}}async loadModuleExports(e){const t=document.querySelector('script[data-loaded-script-id="'+e+'"]');if(!t)throw new Error("Module script with id "+e+" not found");const r=t.getAttribute("src");if(!r)throw new Error("Module script "+e+" has no src attribute");try{const e=new Function("url","return import(url)");return await e(r)}catch(i){throw this.error("Failed to import module",i),i}}async loadStylesheet(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),i=t?.split("/").pop(),o=e.hasAttribute("data-required");if(!this.isDuplicate(i||"")){this.updateLoadingStatus(r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,o=e.getAttribute("data-network")||this.config.network,n=await this.retrieveHCS1Data(i,t,o),s=await n.text(),a=document.createElement("style");a.textContent=s,document.head.appendChild(a),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded and inlined stylesheet: "+r)}catch(n){if(this.error("Failed to load stylesheet: "+r,n),this.updateLoadingStatus(r,"failed"),o)throw n}}}async loadImage(e){const t=e.getAttribute("data-src"),r=t?.split("/").pop();this.log("Loading image: "+r),this.updateLoadingStatus("Image: "+r,"loaded");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,i=e.getAttribute("data-network")||this.config.network,o=await this.retrieveHCS1Data(r,t,i),n=URL.createObjectURL(o);e.src=n,this.LoadedImages[r]=n,this.updateLoadingStatus("Image: "+r,"loaded"),this.log("Loaded image: "+r)}catch(i){this.error("Failed to load image: "+r,i),this.updateLoadingStatus("Image: "+r,"failed")}}async loadMedia(e,t){const r=e.getAttribute("data-src"),i=r?.split("/").pop();this.log("Loading "+t+": "+i),this.updateLoadingStatus(t+": "+i,"loading");try{const r=e.getAttribute("data-cdn-url")||this.config.cdnUrl,o=e.getAttribute("data-network")||this.config.network,n=await this.retrieveHCS1Data(i,r,o),s=URL.createObjectURL(n);e.src=s,"video"===t?this.LoadedVideos[i]=s:this.LoadedAudioUrls[i]=s,this.updateLoadingStatus(t+": "+i,"loaded"),this.log("Loaded "+t+": "+i)}catch(o){this.error("Failed to load "+t+": "+i,o),this.updateLoadingStatus(t+": "+i,"failed")}}async loadModelViewer(){return this.modelViewerLoading?this.modelViewerLoading:this.modelViewerLoaded?Promise.resolve():(this.modelViewerLoading=new Promise(e=>{const t=document.createElement("script");t.setAttribute("data-src","hcs://1/0.0.7293044"),t.setAttribute("data-script-id","model-viewer"),t.setAttribute("type","module"),window.addEventListener("HCSScriptLoaded",()=>{this.modelViewerLoaded=!0,e()},{once:!0}),this.loadScript(t)}),this.modelViewerLoading)}async loadGLB(e){await this.loadModelViewer();const t=e.getAttribute("data-src"),r=t?.split("/").pop();this.log("Loading GLB: "+r),this.updateLoadingStatus("GLB: "+r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,i=e.getAttribute("data-network")||this.config.network;let o;"model-viewer"!==e.tagName.toLowerCase()?(o=document.createElement("model-viewer"),Array.from(e.attributes).forEach(e=>{o.setAttribute(e.name,e.value)}),o.setAttribute("camera-controls",""),o.setAttribute("auto-rotate",""),o.setAttribute("ar",""),e.parentNode?.replaceChild(o,e)):o=e;const n=await this.retrieveHCS1Data(r,t,i),s=URL.createObjectURL(n);o.setAttribute("src",s),this.LoadedGLBs[r]=s,this.updateLoadingStatus("GLB: "+r,"loaded"),this.log("Loaded GLB: "+r)}catch(i){this.error("Failed to load GLB: "+r,i),this.updateLoadingStatus("GLB: "+r,"failed")}}async loadResource(e,t,r){return new Promise(i=>{this.loadQueue.push({element:e,type:t,order:r,resolve:i}),this.processQueue()})}async processQueue(){if(!this.isProcessingQueue){for(this.isProcessingQueue=!0;this.loadQueue.length>0;){const t=this.loadQueue.shift();try{"script"===t.type?await this.loadScript(t.element):"image"===t.type?await this.loadImage(t.element):"video"===t.type||"audio"===t.type?await this.loadMedia(t.element,t.type):"glb"===t.type?await this.loadGLB(t.element):"css"===t.type&&await this.loadStylesheet(t.element),t.resolve()}catch(e){if(this.error("Error processing queue item:",e),"script"===t.type&&t.element.hasAttribute("data-required"))break}}this.isProcessingQueue=!1}}async replaceHCSInStyle(e){let t=e,r=t.indexOf("hcs://");for(;-1!==r;){let e=r;for(;e<t.length&&!["'",'"'," ",")"].includes(t[e]);)e++;const o=t.substring(r,e),n=o.split("/").pop();try{const i=this.config.cdnUrl,s=this.config.network,a=await this.retrieveHCS1Data(n,i,s),c=URL.createObjectURL(a);t=t.substring(0,r)+c+t.substring(e),this.LoadedImages[n]=c,this.log("Replaced CSS HCS URL: "+o+" with "+c)}catch(i){this.error("Failed to load CSS image: "+n,i)}r=t.indexOf("hcs://",r+1)}return t}async processInlineStyles(){const e=document.querySelectorAll('[style*="hcs://"]');this.log("Found "+e.length+" elements with HCS style references");for(const r of Array.from(e)){const e=r.getAttribute("style");if(e){this.log("Processing style: "+e);const t=await this.replaceHCSInStyle(e);e!==t&&(r.setAttribute("style",t),this.log("Updated style to: "+t))}}const t=document.querySelectorAll("style");for(const r of Array.from(t))if(r.textContent?.includes("hcs://")){const e=await this.replaceHCSInStyle(r.textContent);r.textContent!==e&&(r.textContent=e)}}async init(){return this.loadConfigFromHTML(),new Promise(e=>{const t=async()=>{const t=document.querySelectorAll('script[data-src^="hcs://"]'),r=document.querySelectorAll('img[data-src^="hcs://"], img[src^="hcs://"]'),i=document.querySelectorAll('video[data-src^="hcs://"], video[src^="hcs://"]'),o=document.querySelectorAll('audio[data-src^="hcs://"], audio[src^="hcs://"]'),n=document.querySelectorAll('model-viewer[data-src^="hcs://"]'),s=document.querySelectorAll('link[data-src^="hcs://"]');document.querySelectorAll('[src^="hcs://"]').forEach(e=>{const t=e.getAttribute("src");t&&(e.setAttribute("data-src",t),e.removeAttribute("src"))}),await this.processInlineStyles();const a=[];[{elements:t,type:"script"},{elements:r,type:"image"},{elements:i,type:"video"},{elements:o,type:"audio"},{elements:n,type:"glb"},{elements:s,type:"css"}].forEach(({elements:e,type:t})=>{e.forEach(e=>{const r=parseInt(e.getAttribute("data-load-order")||"")||1/0;a.push(this.loadResource(e,t,r))})}),await Promise.all(a);const c=new MutationObserver(e=>{e.forEach(e=>{if(e.addedNodes.forEach(e=>{if(e.nodeType===Node.ELEMENT_NODE){const t=e;if(t.getAttribute("style")?.includes("hcs://")&&this.processInlineStyles(),"style"===t.tagName.toLowerCase()&&t.textContent?.includes("hcs://")&&this.processInlineStyles(),t.getAttribute("src")?.startsWith("hcs://")){const e=t.getAttribute("src");t.setAttribute("data-src",e),t.removeAttribute("src");switch(t.tagName.toLowerCase()){case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"script":this.loadResource(t,"script",1/0)}}t.matches('script[data-src^="hcs://"]')?this.loadResource(t,"script",1/0):t.matches('img[data-src^="hcs://"]')?this.loadResource(t,"image",1/0):t.matches('video[data-src^="hcs://"]')?this.loadResource(t,"video",1/0):t.matches('audio[data-src^="hcs://"]')?this.loadResource(t,"audio",1/0):t.matches('model-viewer[data-src^="hcs://"]')?this.loadResource(t,"glb",1/0):t.matches('link[data-src^="hcs://"]')&&this.loadResource(t,"css",1/0);t.querySelectorAll('[data-src^="hcs://"], [src^="hcs://"]').forEach(e=>{const t=e,r=t.tagName.toLowerCase(),i=t.getAttribute("src");switch(i?.startsWith("hcs://")&&(t.setAttribute("data-src",i),t.removeAttribute("src")),r){case"script":this.loadResource(t,"script",1/0);break;case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"model-viewer":this.loadResource(t,"glb",1/0);break;case"link":this.loadResource(t,"css",1/0)}})}}),"attributes"===e.type){const t=e.target;if("style"===e.attributeName&&t.getAttribute("style")?.includes("hcs://"))this.processInlineStyles();else if("src"===e.attributeName){const e=t.getAttribute("src");if(e?.startsWith("hcs://")){t.setAttribute("data-src",e),t.removeAttribute("src");const r=t.tagName.toLowerCase();["img","video","audio"].includes(r)&&this.loadResource(t,r,1/0)}}}})});document.body?c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]}):document.addEventListener("DOMContentLoaded",()=>{c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]})}),e()};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()})}async preloadImage(e){this.log("Loading image:"+e),this.updateLoadingStatus("image: "+e,"loading");const t=await this.retrieveHCS1Data(e),r=URL.createObjectURL(t);return this.LoadedImages[e]=r,this.updateLoadingStatus("image: "+e,"loaded"),r}async preloadAudio(e){const t=document.createElement("audio");t.setAttribute("data-topic-id",e),t.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(t),await this.loadMedia(t,"audio");const r=document.querySelector('audio[data-topic-id="'+e+'"]');return r?this.LoadedAudioUrls[e]=r.src:console.error("Failed to preload audio: "+e),this.LoadedAudioUrls[e]}async playAudio(e,t=1){const r=this.LoadedAudioUrls[e];if(r){const i=new Audio(r);i.volume=t,this.LoadedAudios[e]=i,i.play().catch(e=>{console.error("Failed to play audio:",e)}),i.addEventListener("ended",()=>{i.remove(),delete this.LoadedAudios[e]})}else console.error("Audio not preloaded: "+e)}async pauseAudio(e){const t=document.querySelector('audio[data-topic-id="'+e+'"]');t?(console.log("found element",t),t.pause(),this.LoadedAudios[e]?.pause()):this.LoadedAudios[e]?.pause()}async loadAndPlayAudio(e,t=!1,r=1){let i=document.querySelector('audio[data-topic-id="'+e+'"]');if(i)i.volume=r,await i.play();else{const o=document.createElement("audio");o.volume=r,t&&o.setAttribute("autoplay","autoplay"),o.setAttribute("data-topic-id",e),o.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(o),await this.loadMedia(o,"audio"),i=document.querySelector('audio[data-topic-id="'+e+'"]'),t||await i.play()}}}var U=(e=>(e.REGISTER="register",e))(U||{}),K=(e=>(e[e.NON_INDEXED=1]="NON_INDEXED",e))(K||{});function L(e){return`hcs://6/${e}`}const $=r.z.string().regex(/^\d+\.\d+\.\d+$/,{message:"Topic ID must be in Hedera format (e.g., '0.0.123456')"}),H=r.z.object({p:r.z.literal("hcs-6"),op:r.z.enum(["register"]),m:r.z.string().max(500,"Memo must not exceed 500 characters").optional()}),q=H.extend({op:r.z.literal("register"),t_id:$}),j=r.z.discriminatedUnion("op",[q]);function W(e){return e>=3600}function V(e){if(!W(e))throw new Error("TTL must be at least 3600 seconds (1 hour)");return`hcs-6:1:${e}`}class G{constructor(e,t,r){this.maxRetries=5,this.initialDelayMs=2e3,this.maxDelayMs=3e4,this.backoffFactor=2,this.network=e,this.apiKey=r?.apiKey,this.customHeaders=r?.headers||{},this.baseUrl=r?.customUrl||this.getMirrorNodeUrl(),this.logger=t||new D({level:"debug",module:"MirrorNode"}),this.isServerEnvironment="undefined"==typeof window,r?.customUrl&&this.logger.info(`Using custom mirror node URL: ${r.customUrl}`),r?.apiKey&&this.logger.info("Using API key for mirror node requests")}configureRetry(e){this.maxRetries=e.maxRetries??this.maxRetries,this.initialDelayMs=e.initialDelayMs??this.initialDelayMs,this.maxDelayMs=e.maxDelayMs??this.maxDelayMs,this.backoffFactor=e.backoffFactor??this.backoffFactor,this.logger.info(`Retry configuration updated: maxRetries=${this.maxRetries}, initialDelayMs=${this.initialDelayMs}, maxDelayMs=${this.maxDelayMs}, backoffFactor=${this.backoffFactor}`)}configureMirrorNode(e){e.customUrl&&(this.baseUrl=e.customUrl,this.logger.info(`Updated mirror node URL: ${e.customUrl}`)),e.apiKey&&(this.apiKey=e.apiKey,this.logger.info("Updated API key for mirror node requests")),e.headers&&(this.customHeaders={...this.customHeaders,...e.headers},this.logger.info("Updated custom headers for mirror node requests"))}constructUrl(e){if(this.baseUrl.includes("<API-KEY>")&&this.apiKey){const t=this.baseUrl.replace("<API-KEY>",this.apiKey);return e.startsWith("/")?`${t}${e}`:`${t}/${e}`}return e.startsWith("/")?`${this.baseUrl}${e}`:`${this.baseUrl}/${e}`}getMirrorNodeUrl(){return"mainnet"===this.network?"https://mainnet-public.mirrornode.hedera.com":"https://testnet.mirrornode.hedera.com"}getBaseUrl(){return this.baseUrl}async getPublicKey(e){this.logger.debug(`Getting public key for account ${e}`);const t=await this.requestAccount(e);try{if(!t||!t.key)throw new Error(`Failed to retrieve public key for account ID: ${e}`);return i.PublicKey.fromString(t.key.key)}catch(r){const e=`Error fetching public key from Mirror Node: ${r.message}`;throw this.logger.error(e),new Error(e)}}async getAccountMemo(e){this.logger.debug(`Getting account memo for account ID: ${e}`);try{const t=await this._requestWithRetry(`/api/v1/accounts/${e}`);return t?.memo?t.memo:(this.logger.warn(`No memo found for account ${e}`),null)}catch(t){const r=t;return this.logger.error(`Failed to get account memo for ${e} after retries: ${r.message}`),null}}async getTopicInfo(e){try{this.logger.debug(`Fetching topic info for ${e}`);return await this._requestWithRetry(`/api/v1/topics/${e}`)}catch(t){const r=`Error retrieving topic information for ${e} after retries: ${t.message}`;throw this.logger.error(r),new Error(r)}}async getTopicFees(e){try{return(await this.getTopicInfo(e)).custom_fees}catch(t){const e=`Error retrieving topic fees: ${t.message}`;return this.logger.error(e),null}}async getHBARPrice(e){try{const t=i.Timestamp.fromDate(e).toString();this.logger.debug(`Fetching HBAR price for timestamp ${t}`);const r=await this._requestWithRetry(`/api/v1/network/exchangerate?timestamp=${t}`);return Number(r?.current_rate?.cent_equivalent)/Number(r?.current_rate?.hbar_equivalent)/100}catch(t){const e=`Error retrieving HBAR price: ${t.message}`;return this.logger.error(e),null}}async getTokenInfo(e){this.logger.debug(`Fetching token info for ${e}`);try{const t=await this._requestWithRetry(`/api/v1/tokens/${e}`);return t?(this.logger.trace(`Token info found for ${e}:`,t),t):(this.logger.warn(`No token info found for ${e}`),null)}catch(t){const r=`Error fetching token info for ${e}: ${t.message}`;return this.logger.error(r),null}}async getTopicMessages(e,t){this.logger.trace(`Querying messages for topic ${e}${t?" with filters":""}`);let r=`/api/v1/topics/${e}/messages`;const i=new URLSearchParams;if(t){if(void 0!==t.sequenceNumber){const e="number"==typeof t.sequenceNumber?t.sequenceNumber.toString():t.sequenceNumber;e.match(/^(gt|gte|lt|lte|eq|ne):/)?i.append("sequencenumber",e):i.append("sequencenumber",`gt:${e}`)}t.limit&&i.append("limit",t.limit.toString()),t.order&&i.append("order",t.order)}const o=i.toString();o&&(r+=`?${o}`);const n=[];let s=r;for(;s;)try{const e=await this._requestWithRetry(s);if(e.messages&&e.messages.length>0)for(const t of e.messages)try{if(!t.message)continue;let e,r;try{e=this.isServerEnvironment?globalThis.Buffer.from(t.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(t.message),e=>e.charCodeAt(0)))}catch(a){const e=`Error decoding message: ${a}`;this.logger.error(e);continue}try{r=JSON.parse(e)}catch(a){const t=`Invalid JSON message content: ${e}`;this.logger.error(t);continue}r.sequence_number=t.sequence_number,n.push({...r,consensus_timestamp:t.consensus_timestamp,sequence_number:t.sequence_number,running_hash:t.running_hash,running_hash_version:t.running_hash_version,topic_id:t.topic_id,payer:t.payer_account_id,created:new Date(1e3*Number(t.consensus_timestamp))})}catch(a){const e=`Error processing message: ${a.message}`;this.logger.error(e)}s=e.links?.next||""}catch(c){const t=`Error querying topic messages for topic ${e} (endpoint: ${s}) after retries: ${c.message}`;throw this.logger.error(t),new Error(t)}return n}async requestAccount(e){try{this.logger.debug(`Requesting account info for ${e}`);const t=await this._requestWithRetry(`/api/v1/accounts/${e}`);if(!t)throw new Error(`No data received from mirror node for account: ${e}`);return t}catch(t){const r=`Failed to fetch account ${e} after retries: ${t.message}`;throw this.logger.error(r),new Error(r)}}async checkKeyListAccess(e,t){try{const r=n.proto.Key.decode(e);return this.evaluateKeyAccess(r,t)}catch(r){const e=`Error decoding protobuf key: ${r.message}`;throw this.logger.error(e),new Error(e)}}async evaluateKeyAccess(e,t){return e.ed25519?this.compareEd25519Key(e.ed25519,t):e.keyList?this.evaluateKeyList(e.keyList,t):!(!e.thresholdKey||!e.thresholdKey.keys)&&this.evaluateKeyList(e.thresholdKey.keys,t)}async evaluateKeyList(e,t){const r=e.keys||[];for(const o of r)if(o)if(o.ed25519){if(this.compareEd25519Key(o.ed25519,t))return!0}else if(o.keyList||o.thresholdKey)try{const e=n.proto.Key.encode({...o.keyList?{keyList:o.keyList}:{},...o.thresholdKey?{thresholdKey:o.thresholdKey}:{}}).finish();if(await this.checkKeyListAccess(globalThis.Buffer.from(e),t))return!0}catch(i){const e=`Error in nested key: ${i.message}`;this.logger.debug(e)}return!1}compareEd25519Key(e,t){try{return i.PublicKey.fromBytes(globalThis.Buffer.from(e)).toString()===t.toString()}catch(r){const e=`Error comparing Ed25519 key: ${r.message}`;return this.logger.debug(e),!1}}async getScheduleInfo(e){try{this.logger.info(`Getting information for scheduled transaction ${e}`);const t=await this._requestWithRetry(`/api/v1/schedules/${e}`);return t||(this.logger.warn(`No schedule info found for ${e} after retries.`),null)}catch(t){return this.logger.error(`Error fetching schedule info for ${e} after retries: ${t.message}`),null}}async getScheduledTransactionStatus(e){try{this.logger.info(`Checking status of scheduled transaction ${e}`);const t=await this.getScheduleInfo(e);if(!t)throw new Error(`Schedule ${e} not found`);return{executed:Boolean(t.executed_timestamp),executedDate:t.executed_timestamp?new Date(1e3*Number(t.executed_timestamp)):void 0,deleted:t.deleted||!1}}catch(t){throw this.logger.error(`Error checking scheduled transaction status: ${t}`),t}}async getTransaction(e){this.logger.info(`Getting transaction details for ID/hash: ${e}`);try{const t=await this._requestWithRetry(`/api/v1/transactions/${e}`);return t?.transactions?.length>0?(this.logger.trace(`Transaction details found for ${e}:`,t.transactions[0]),t.transactions[0]):(this.logger.warn(`No transaction details found for ${e} or unexpected response structure.`),null)}catch(t){const r=t;return this.logger.error(`Failed to get transaction details for ${e} after retries: ${r.message}`),null}}async _requestWithRetry(e,t){let r=0,i=this.initialDelayMs;const n=this.constructUrl(e),s={...t,headers:{...this.customHeaders,...t?.headers}};for(this.apiKey&&(s.headers={...s.headers,Authorization:`Bearer ${this.apiKey}`,"X-API-Key":this.apiKey});r<this.maxRetries;)try{return(await o.get(n,s)).data}catch(a){r++;const e=r>=this.maxRetries,t=a.response?.status;if(t&&t>404&&t<500&&429!==t)throw this.logger.error(`Client error for ${n} (status ${t}): ${a.message}. Not retrying.`),a;if(e)throw this.logger.error(`Max retries (${this.maxRetries}) reached for ${n}. Last error: ${a.message}`),a;this.logger.warn(`Attempt ${r}/${this.maxRetries} failed for ${n}: ${a.message}. Retrying in ${i}ms...`),await new Promise(e=>setTimeout(e,i)),i=Math.min(i*this.backoffFactor,this.maxDelayMs)}throw new Error(`Failed to fetch data from ${n} after ${this.maxRetries} attempts.`)}async _fetchWithRetry(e,t){let r=0,i=this.initialDelayMs;const o={...this.customHeaders};t?.headers&&(t.headers instanceof Headers?t.headers.forEach((e,t)=>{o[t]=e}):Array.isArray(t.headers)?t.headers.forEach(([e,t])=>{o[e]=t}):Object.assign(o,t.headers)),this.apiKey&&(o.Authorization=`Bearer ${this.apiKey}`,o["X-API-Key"]=this.apiKey);const n={...t,headers:o};for(;r<this.maxRetries;)try{const t=await fetch(e,n);if(!t.ok){if(t.status>=400&&t.status<500&&429!==t.status)throw this.logger.error(`Client error for ${e} (status ${t.status}): ${t.statusText}. Not retrying.`),new Error(`Fetch failed with status ${t.status}: ${t.statusText} for URL: ${e}`);throw new Error(`Fetch failed with status ${t.status}: ${t.statusText} for URL: ${e}`)}return await t.json()}catch(s){if(r++,r>=this.maxRetries)throw this.logger.error(`Max retries (${this.maxRetries}) reached for ${e}. Last error: ${s.message}`),s;this.logger.warn(`Attempt ${r}/${this.maxRetries} failed for ${e}: ${s.message}. Retrying in ${i}ms...`),await new Promise(e=>setTimeout(e,i)),i=Math.min(i*this.backoffFactor,this.maxDelayMs)}throw new Error(`Failed to fetch data from ${e} after ${this.maxRetries} attempts.`)}async getAccountBalance(e){this.logger.info(`Getting balance for account ${e}`);try{const t=await this.requestAccount(e);if(t&&t.balance){return t.balance.balance/1e8}return this.logger.warn(`Could not retrieve balance for account ${e} from account info.`),null}catch(t){return this.logger.error(`Error fetching numerical balance for account ${e}: ${t.message}`),null}}async getTopicMessagesByFilter(e,t){this.logger.trace(`Querying messages for topic ${e} with filters: ${JSON.stringify(t)}`);let r=`/api/v1/topics/${e}/messages`;const i=new URLSearchParams;t?.limit&&i.append("limit",t.limit.toString()),t?.sequenceNumber&&i.append("sequencenumber",t.sequenceNumber),t?.startTime&&i.append("timestamp",`gte:${t.startTime}`),t?.endTime&&i.append("timestamp",`lt:${t.endTime}`),t?.order&&i.append("order",t.order);const o=i.toString();o&&(r+=`?${o}`);const n=[];let s=0;try{for(;r&&s<10;){s++;const e=await this._requestWithRetry(r);if(e.messages&&e.messages.length>0)for(const t of e.messages)try{if(!t.message)continue;let e;e=this.isServerEnvironment?globalThis.Buffer.from(t.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(t.message),e=>e.charCodeAt(0)));let r={};try{r=JSON.parse(e)}catch(a){this.logger.debug(`Message content is not valid JSON, using raw: ${e}`),r={raw_content:e}}const i={...r,consensus_timestamp:t.consensus_timestamp,sequence_number:t.sequence_number,payer_account_id:t.payer_account_id,topic_id:t.topic_id,running_hash:t.running_hash,running_hash_version:t.running_hash_version,chunk_info:t.chunk_info,created:new Date(1e3*Number(t.consensus_timestamp.split(".")[0])+Number(t.consensus_timestamp.split(".")[1]||0)/1e6),payer:t.payer_account_id};n.push(i)}catch(c){this.logger.error(`Error processing individual message: ${c.message}`)}if(t?.limit&&n.length>=t.limit)break;r=e.links?.next?`${e.links.next}`:""}return n}catch(l){const t=l;return this.logger.error(`Error querying filtered topic messages for ${e}: ${t.message}`),null}}async getAccountTokens(e,t=100){this.logger.info(`Getting tokens for account ${e}`);let r=[],i=`/api/v1/accounts/${e}/tokens?limit=${t}`;try{for(let e=0;e<10&&i;e++){const e=await this._requestWithRetry(i);if(e&&e.tokens&&(r=r.concat(e.tokens)),i=e.links?.next||"",!i||t&&r.length>=t){t&&r.length>t&&(r=r.slice(0,t));break}}return r}catch(o){return this.logger.error(`Error fetching tokens for account ${e}: ${o.message}`),null}}async getTransactionByTimestamp(e){this.logger.info(`Getting transaction by timestamp: ${e}`);try{return(await this._requestWithRetry(`/api/v1/transactions?timestamp=${e}&limit=1`)).transactions}catch(t){return this.logger.error(`Error fetching transaction by timestamp ${e}: ${t}`),[]}}async getAccountNfts(e,t,r=100){this.logger.info(`Getting NFTs for account ${e}${t?` for token ${t}`:""}`);let i=[],o=`/api/v1/accounts/${e}/nfts?limit=${r}`;t&&(o+=`&token.id=${t}`);try{for(let e=0;e<10&&o;e++){const e=await this._requestWithRetry(o);if(e&&e.nfts){const t=e.nfts.map(e=>{let t;if(e.metadata)try{t=this.isServerEnvironment?globalThis.Buffer.from(e.metadata,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(e.metadata),e=>e.charCodeAt(0)))}catch(r){this.logger.warn(`Failed to decode metadata for NFT ${e.token_id} SN ${e.serial_number}: ${r.message}`)}return{...e,token_uri:t}});i=i.concat(t)}if(o=e.links?.next||"",!o)break}return i}catch(n){return this.logger.error(`Error fetching NFTs for account ${e}: ${n.message}`),null}}async validateNFTOwnership(e,t,r){this.logger.info(`Validating ownership of NFT ${t} SN ${r} for account ${e}`);try{const i=await this.getAccountNfts(e,t);if(i){return i.find(e=>e.token_id===t&&e.serial_number===r)||null}return null}catch(i){return this.logger.error(`Error validating NFT ownership: ${i.message}`),null}}async readSmartContractQuery(e,t,r,o){this.logger.info(`Reading smart contract ${e} with selector ${t}`);const n=e.startsWith("0x")?e:`0x${i.AccountId.fromString(e).toSolidityAddress()}`,s=r.startsWith("0x")?r:`0x${i.AccountId.fromString(r).toSolidityAddress()}`,a={block:o?.block||"latest",data:t,estimate:o?.estimate||!1,from:s,to:n,gas:o?.gas,gasPrice:o?.gasPrice,value:o?.value||0};Object.keys(a).forEach(e=>{const t=e;void 0===a[t]&&delete a[t]});try{const e=this.constructUrl("/api/v1/contracts/call");return await this._fetchWithRetry(e,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json"}})}catch(c){return this.logger.error(`Error reading smart contract ${e}: ${c.message}`),null}}async getOutstandingTokenAirdrops(e,t){this.logger.info(`Getting outstanding token airdrops sent by account ${e}`);let r=`/api/v1/accounts/${e}/airdrops/outstanding`;const i=new URLSearchParams;t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.receiverId&&i.append("receiver.id",t.receiverId),t?.serialNumber&&i.append("serialnumber",t.serialNumber),t?.tokenId&&i.append("token.id",t.tokenId);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).airdrops||[]}catch(n){return this.logger.error(`Error fetching outstanding token airdrops for account ${e}: ${n.message}`),null}}async getPendingTokenAirdrops(e,t){this.logger.info(`Getting pending token airdrops received by account ${e}`);let r=`/api/v1/accounts/${e}/airdrops/pending`;const i=new URLSearchParams;t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.senderId&&i.append("sender.id",t.senderId),t?.serialNumber&&i.append("serialnumber",t.serialNumber),t?.tokenId&&i.append("token.id",t.tokenId);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).airdrops||[]}catch(n){return this.logger.error(`Error fetching pending token airdrops for account ${e}: ${n.message}`),null}}async getBlocks(e){this.logger.info("Getting blocks from the network");let t="/api/v1/blocks";const r=new URLSearchParams;e?.limit&&r.append("limit",e.limit.toString()),e?.order&&r.append("order",e.order),e?.timestamp&&r.append("timestamp",e.timestamp),e?.blockNumber&&r.append("block.number",e.blockNumber);const i=r.toString();i&&(t+=`?${i}`);try{return(await this._requestWithRetry(t)).blocks||[]}catch(o){return this.logger.error(`Error fetching blocks: ${o.message}`),null}}async getBlock(e){this.logger.info(`Getting block ${e}`);try{return await this._requestWithRetry(`/api/v1/blocks/${e}`)}catch(t){return this.logger.error(`Error fetching block ${e}: ${t.message}`),null}}async getContracts(e){this.logger.info("Getting contracts from the network");let t="/api/v1/contracts";const r=new URLSearchParams;e?.contractId&&r.append("contract.id",e.contractId),e?.limit&&r.append("limit",e.limit.toString()),e?.order&&r.append("order",e.order);const i=r.toString();i&&(t+=`?${i}`);try{return(await this._requestWithRetry(t)).contracts||[]}catch(o){return this.logger.error(`Error fetching contracts: ${o.message}`),null}}async getContract(e,t){this.logger.info(`Getting contract ${e}`);let r=`/api/v1/contracts/${e}`;t&&(r+=`?timestamp=${t}`);try{return await this._requestWithRetry(r)}catch(i){return this.logger.error(`Error fetching contract ${e}: ${i.message}`),null}}async getContractResults(e){this.logger.info("Getting contract results from the network");let t="/api/v1/contracts/results";const r=new URLSearchParams;e?.from&&r.append("from",e.from),e?.blockHash&&r.append("block.hash",e.blockHash),e?.blockNumber&&r.append("block.number",e.blockNumber),void 0!==e?.internal&&r.append("internal",e.internal.toString()),e?.limit&&r.append("limit",e.limit.toString()),e?.order&&r.append("order",e.order),e?.timestamp&&r.append("timestamp",e.timestamp),e?.transactionIndex&&r.append("transaction.index",e.transactionIndex.toString());const i=r.toString();i&&(t+=`?${i}`);try{return(await this._requestWithRetry(t)).results||[]}catch(o){return this.logger.error(`Error fetching contract results: ${o.message}`),null}}async getContractResult(e,t){this.logger.info(`Getting contract result for ${e}`);let r=`/api/v1/contracts/results/${e}`;void 0!==t&&(r+=`?nonce=${t}`);try{return await this._requestWithRetry(r)}catch(i){return this.logger.error(`Error fetching contract result for ${e}: ${i.message}`),null}}async getContractResultsByContract(e,t){this.logger.info(`Getting contract results for contract ${e}`);let r=`/api/v1/contracts/${e}/results`;const i=new URLSearchParams;t?.blockHash&&i.append("block.hash",t.blockHash),t?.blockNumber&&i.append("block.number",t.blockNumber),t?.from&&i.append("from",t.from),void 0!==t?.internal&&i.append("internal",t.internal.toString()),t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.timestamp&&i.append("timestamp",t.timestamp),t?.transactionIndex&&i.append("transaction.index",t.transactionIndex.toString());const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).results||[]}catch(n){return this.logger.error(`Error fetching contract results for ${e}: ${n.message}`),null}}async getContractState(e,t){this.logger.info(`Getting contract state for ${e}`);let r=`/api/v1/contracts/${e}/state`;const i=new URLSearchParams;t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.slot&&i.append("slot",t.slot),t?.timestamp&&i.append("timestamp",t.timestamp);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).state||[]}catch(n){return this.logger.error(`Error fetching contract state for ${e}: ${n.message}`),null}}async getContractActions(e,t){this.logger.info(`Getting contract actions for ${e}`);let r=`/api/v1/contracts/results/${e}/actions`;const i=new URLSearchParams;t?.index&&i.append("index",t.index),t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).actions||[]}catch(n){return this.logger.error(`Error fetching contract actions for ${e}: ${n.message}`),null}}async getContractLogs(e){this.logger.info("Getting contract logs from the network");let t="/api/v1/contracts/results/logs";const r=new URLSearchParams;e?.index&&r.append("index",e.index),e?.limit&&r.append("limit",e.limit.toString()),e?.order&&r.append("order",e.order),e?.timestamp&&r.append("timestamp",e.timestamp),e?.topic0&&r.append("topic0",e.topic0),e?.topic1&&r.append("topic1",e.topic1),e?.topic2&&r.append("topic2",e.topic2),e?.topic3&&r.append("topic3",e.topic3),e?.transactionHash&&r.append("transaction.hash",e.transactionHash);const i=r.toString();i&&(t+=`?${i}`);try{return(await this._requestWithRetry(t)).logs||[]}catch(o){return this.logger.error(`Error fetching contract logs: ${o.message}`),null}}async getContractLogsByContract(e,t){this.logger.info(`Getting contract logs for contract ${e}`);let r=`/api/v1/contracts/${e}/results/logs`;const i=new URLSearchParams;t?.index&&i.append("index",t.index),t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.timestamp&&i.append("timestamp",t.timestamp),t?.topic0&&i.append("topic0",t.topic0),t?.topic1&&i.append("topic1",t.topic1),t?.topic2&&i.append("topic2",t.topic2),t?.topic3&&i.append("topic3",t.topic3);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).logs||[]}catch(n){return this.logger.error(`Error fetching contract logs for ${e}: ${n.message}`),null}}async getNftInfo(e,t){this.logger.info(`Getting NFT info for ${e}/${t}`);const r=`/api/v1/tokens/${e}/nfts/${t}`;try{return await this._requestWithRetry(r)}catch(i){return this.logger.error(`Error fetching NFT info for ${e}/${t}: ${i.message}`),null}}async getNftsByToken(e,t){this.logger.info(`Getting NFTs for token ${e}`);let r=`/api/v1/tokens/${e}/nfts`;const i=new URLSearchParams;t?.accountId&&i.append("account.id",t.accountId),t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.serialNumber&&i.append("serialnumber",t.serialNumber);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).nfts||[]}catch(n){return this.logger.error(`Error fetching NFTs for token ${e}: ${n.message}`),null}}async getNetworkInfo(){this.logger.info("Getting network information");try{return await this._requestWithRetry("/api/v1/network/nodes")}catch(e){return this.logger.error(`Error fetching network info: ${e.message}`),null}}async getNetworkFees(e){this.logger.info("Getting network fees");let t="/api/v1/network/fees";e&&(t+=`?timestamp=${e}`);try{return await this._requestWithRetry(t)}catch(r){return this.logger.error(`Error fetching network fees: ${r.message}`),null}}async getNetworkSupply(e){this.logger.info("Getting network supply");let t="/api/v1/network/supply";e&&(t+=`?timestamp=${e}`);try{return await this._requestWithRetry(t)}catch(r){return this.logger.error(`Error fetching network supply: ${r.message}`),null}}async getNetworkStake(e){this.logger.info("Getting network stake");let t="/api/v1/network/stake";e&&(t+=`?timestamp=${e}`);try{return await this._requestWithRetry(t)}catch(r){return this.logger.error(`Error fetching network stake: ${r.message}`),null}}async getOpcodeTraces(e,t){this.logger.info(`Getting opcode traces for ${e}`);let r=`/api/v1/contracts/results/${e}/opcodes`;const i=new URLSearchParams;void 0!==t?.stack&&i.append("stack",t.stack.toString()),void 0!==t?.memory&&i.append("memory",t.memory.toString()),void 0!==t?.storage&&i.append("storage",t.storage.toString());const o=i.toString();o&&(r+=`?${o}`);try{return await this._requestWithRetry(r)}catch(n){return this.logger.error(`Error fetching opcode traces for ${e}: ${n.message}`),null}}}class J{constructor(e){this.network=e.network,this.logger=e.logger||D.getInstance({level:e.logLevel||"info",module:"HCS6Client",silent:e.silent}),this.mirrorNode=new G(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0)}parseRegistryTypeFromMemo(e){try{const t=/hcs-6:(\d):(\d+)/,r=e.match(t);if(r&&3===r.length){const e=parseInt(r[1]),t=parseInt(r[2]);if(e===K.NON_INDEXED&&W(t))return{registryType:e,ttl:t}}return}catch(t){return void this.logger.error(`Error parsing HCS-6 registry type from memo: ${t}`)}}generateRegistryMemo(e){return V(e)}validateMessage(e){try{return j.parse(e),{valid:!0,errors:[]}}catch(t){const e=[];return t instanceof r.ZodError?t.errors.forEach(t=>{const r=t.path.join(".");e.push(`${r?r+": ":""}${t.message}`)}):e.push(`Unexpected error: ${t}`),this.logger.debug(`HCS-6 message validation failed: ${e.join(", ")}`),{valid:!1,errors:e}}}createRegisterMessage(e,t){return{p:"hcs-6",op:U.REGISTER,t_id:e,m:t}}parseRegistryEntries(e,t,r,i){const o=[];let n;this.logger.debug(`Parsing ${t.length} messages for HCS-6 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 HCS-6 message: ${JSON.stringify(i)}`);const{valid:s,errors:c}=this.validateMessage(i);if(!s){this.logger.warn(`Invalid HCS-6 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};o.push(l),(!n||l.timestamp>n.timestamp)&&(n=l)}catch(s){this.logger.warn(`Error parsing HCS-6 message: ${s}`)}return this.logger.debug(`Parsed ${o.length} valid entries for HCS-6 topic ${e}`),{topicId:e,registryType:r,ttl:i,entries:n?[n]:[],latestEntry:n}}async validateHCS6Topic(e){try{const t=await this.mirrorNode.getTopicInfo(e),r=this.parseRegistryTypeFromMemo(t.memo);return r?r.registryType===K.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}}}function Y(e){const{memo:t,adminKey:r,submitKey:o,operatorPublicKey:n}=e,s=(new i.TopicCreateTransaction).setTopicMemo(t),a=e=>{if(e){if(e instanceof i.PublicKey||e instanceof i.KeyList)return e;if("boolean"==typeof e)return e?n:void 0;if("string"==typeof e)try{return i.PublicKey.fromString(e)}catch{return}}},c=a(r);c&&s.setAdminKey(c);const l=a(o);return l&&s.setSubmitKey(l),s}function X(e){const t=(new i.TopicMessageSubmitTransaction).setTopicId(i.TopicId.fromString(e.topicId)).setMessage(e.message);return e.transactionMemo&&t.setTransactionMemo(e.transactionMemo),t}function Z(e){return Y({memo:e.memoOverride??`hcs-6:1:${e.ttl}`,submitKey:e.submitKey,adminKey:e.adminKey,operatorPublicKey:e.operatorPublicKey})}var Q=(e=>(e.ED25519="ed25519",e.ECDSA="ecdsa",e.UNKNOWN="unknown",e))(Q||{});const ee=class{static detect(e){try{let t,r="raw";if("string"==typeof e){let i=e.trim();if(i.includes("-----BEGIN"))return this.detectFromPem(i);if(i.toLowerCase().startsWith("0x")&&(i=i.substring(2)),this.isValidHex(i))t=this.hexToBytes(i),r="hex";else{if(!this.isBase64(i))return{type:"unknown",format:"raw",isPrivateKey:!1,confidence:"certain"};t=globalThis.Buffer.from(i,"base64"),r="der"}}else t=e instanceof globalThis.Buffer?new Uint8Array(e):e;return this.detectFromBytes(t,r)}catch(t){return{type:"unknown",format:"raw",isPrivateKey:!1,confidence:"certain"}}}static detectFromBytes(e,t){if(this.hasPrefix(e,this.ED25519_PUBLIC_KEY_PREFIX)){const t=this.ED25519_PUBLIC_KEY_PREFIX.length;return{type:"ed25519",format:"der",isPrivateKey:!1,rawBytes:e.slice(t),confidence:"certain"}}if(this.hasPrefix(e,this.ED25519_PRIVATE_KEY_PREFIX)){const t=this.ED25519_PRIVATE_KEY_PREFIX.length;if(e.length>=t+32)return{type:"ed25519",format:"der",isPrivateKey:!0,rawBytes:e.slice(t,t+32),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PUBLIC_KEY_PREFIX)){const t=this.ECDSA_SECP256K1_PUBLIC_KEY_PREFIX.length;return{type:"ecdsa",format:"der",isPrivateKey:!1,rawBytes:e.slice(t),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_SHORT)){const t=this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_SHORT.length;return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:e.slice(t),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX)){const t=this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX.length;return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:e.slice(t,t+32),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_LONG)){const t=this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_LONG.length;return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:e.slice(t,t+32),confidence:"certain"}}if(e.length>36&&this.containsECDSAPrivateKeyPattern(e))return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:this.extractECDSAPrivateKey(e),confidence:"certain"};switch(e.length){case this.ED25519_PUBLIC_KEY_LENGTH:if("hex"===t){const t=Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join(""),r=this.tryCreateKey(t);if("unknown"!==r.type)return r}return{type:"unknown",format:t,isPrivateKey:!1,rawBytes:e,confidence:"certain"};case this.ED25519_EXPANDED_PRIVATE_KEY_LENGTH:return{type:"ed25519",format:t,isPrivateKey:!0,rawBytes:e,confidence:"certain"}}return{type:"unknown",format:t,isPrivateKey:!1,rawBytes:e,confidence:"certain"}}static detectFromPem(e){const t=e.trim(),r=t.includes("PRIVATE KEY"),i={EC_PRIVATE:/-----BEGIN EC PRIVATE KEY-----/,EC_PUBLIC:/-----BEGIN EC PUBLIC KEY-----/,PRIVATE:/-----BEGIN PRIVATE KEY-----/,PUBLIC:/-----BEGIN PUBLIC KEY-----/};let o=!1;for(const[a,c]of Object.entries(i))if(c.test(t)&&a.includes("EC")){o=!0;break}const n=t.match(/-----BEGIN[\s\S]+?-----[\r\n]+([\s\S]+?)[\r\n]+-----END/);if(!n)return{type:"unknown",format:"pem",isPrivateKey:r,confidence:"certain"};const s=n[1].replace(/\s/g,"");try{const e=globalThis.Buffer.from(s,"base64"),t=this.detectFromBytes(new Uint8Array(e),"der");return"unknown"===t.type&&o?{type:"ecdsa",format:"pem",isPrivateKey:r,rawBytes:e,confidence:"certain"}:{...t,format:"pem"}}catch{return{type:"unknown",format:"pem",isPrivateKey:r,confidence:"certain"}}}static tryCreateKey(e){try{if("string"==typeof e){let t=e.trim();if(t.toLowerCase().startsWith("0x")&&(t=t.substring(2)),this.isValidHex(t)&&64===t.length){const e=this.hexToBytes(t),r=this.detectBySignature(t);return"unknown"!==r.type?{type:r.type,format:"hex",isPrivateKey:!0,rawBytes:e,confidence:r.confidence,warning:r.warning}:{type:"unknown",format:"hex",isPrivateKey:!1,rawBytes:e,confidence:"certain"}}}}catch{}return{type:"unknown",format:"hex",isPrivateKey:!1,rawBytes:new Uint8Array,confidence:"certain"}}static detectBySignature(e){const t=BigInt("0x"+e),r=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");if(0n===t)return{type:"ed25519",confidence:"certain"};if(t>=r)return{type:"ed25519",confidence:"certain"};let o=!1,n=!1;try{const t=i.PrivateKey.fromStringED25519(e),r=new Uint8Array([1,2,3,4,5]),n=t.sign(r);t.publicKey.verify(r,n)&&(o=!0)}catch{}try{const t=i.PrivateKey.fromStringECDSA(e),r=new Uint8Array([1,2,3,4,5]),o=t.sign(r);t.publicKey.verify(r,o)&&(n=!0)}catch{}if(o&&n){const t=this.hexToBytes(e);if(168===t[0]&&1===t[1])return{type:"ed25519",confidence:"uncertain",warning:"Detection based on byte pattern heuristic. Both ED25519 and ECDSA accept this key."};let r=0;for(const e of t)e>=128&&r++;const i=r/t.length;return i>=.4&&i<=.6?{type:"ecdsa",confidence:"uncertain",warning:"Detection based on entropy heuristic. Both ED25519 and ECDSA accept this key."}:{type:"ecdsa",confidence:"uncertain",warning:"Detection based on entropy heuristic. Both ED25519 and ECDSA accept this key. Defaulting to ECDSA."}}return o&&!n?{type:"ed25519",confidence:"certain"}:n&&!o?{type:"ecdsa",confidence:"certain"}:{type:"unknown",confidence:"certain"}}static isValidHex(e){return/^[0-9a-fA-F]+$/.test(e)&&e.length%2==0}static isBase64(e){try{return globalThis.Buffer.from(e,"base64").toString("base64")===e}catch{return!1}}static hexToBytes(e){const t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=parseInt(e.substr(r,2),16);return t}static hasPrefix(e,t){if(e.length<t.length)return!1;for(let r=0;r<t.length;r++)if(e[r]!==t[r])return!1;return!0}static containsECDSAPrivateKeyPattern(e){for(let t=0;t<e.length-7;t++)if(48===e[t]&&116===e[t+1]&&2===e[t+2]&&1===e[t+3]&&1===e[t+4]&&4===e[t+5]&&32===e[t+6])return!0;return!1}static extractECDSAPrivateKey(e){for(let t=0;t<e.length-32;t++)if(4===e[t]&&32===e[t+1])return e.slice(t+2,t+34);return e}};ee.ED25519_PUBLIC_KEY_LENGTH=32,ee.ED25519_EXPANDED_PRIVATE_KEY_LENGTH=64,ee.ED25519_PUBLIC_KEY_PREFIX=globalThis.Buffer.from([48,42,48,5,6,3,43,101,112,3,33,0]),ee.ED25519_PRIVATE_KEY_PREFIX=globalThis.Buffer.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),ee.ECDSA_SECP256K1_PUBLIC_KEY_PREFIX=globalThis.Buffer.from([48,86,48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,10,3,66,0]),ee.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX=globalThis.Buffer.from([48,116,2,1,1,4,32]),ee.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_SHORT=globalThis.Buffer.from([48,48,2,1,0,48,7,6,5,43,129,4,0,10,4,34,4,32]),ee.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_LONG=globalThis.Buffer.from([48,119,2,1,1,4,32]);let te=ee;function re(e){const t=te.detect(e);if("unknown"!==t.type)try{const r="ecdsa"===t.type?i.PrivateKey.fromStringECDSA(e):i.PrivateKey.fromStringED25519(e),o={detectedType:t.type,privateKey:r};return"uncertain"===t.confidence&&(o.warning="Key type detection is uncertain. If you have the associated account ID, consider using the Hedera mirror node to confirm the key type."),o}catch(r){}try{return{detectedType:"ecdsa",privateKey:i.PrivateKey.fromStringECDSA(e),warning:"Using ECDSA as default. If you have the associated account ID, consider using the Hedera mirror node to confirm the key type."}}catch(o){try{return{detectedType:"ed25519",privateKey:i.PrivateKey.fromStringED25519(e),warning:"Using ED25519 as fallback. If you have the associated account ID, consider using the Hedera mirror node to confirm the key type."}}catch(n){throw new Error(`Failed to parse private key as either ECDSA or ED25519: ${o}`)}}}class ie{constructor(e){this.mirror=e.mirrorNode,this.logger=e.logger}bestGuessOperatorKey(e,t){if("string"!=typeof e)return{keyType:t||"ecdsa",privateKey:e};if(t){return{keyType:t,privateKey:"ed25519"===t?i.PrivateKey.fromStringED25519(e):i.PrivateKey.fromStringECDSA(e)}}try{const t=re(e);return{keyType:t.detectedType,privateKey:t.privateKey}}catch{return{keyType:"ecdsa",privateKey:i.PrivateKey.fromStringECDSA(e)}}}async resolveOperatorKey(e,t,r){if("string"!=typeof t)return{keyType:r||"ecdsa",privateKey:t};if(r){return{keyType:r,privateKey:"ed25519"===r?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t)}}const o="string"==typeof e?e:e.toString();try{const e=await this.mirror.requestAccount(o),r=(e?.key?._type||"").includes("ED25519")?"ed25519":"ecdsa";return{keyType:r,privateKey:"ed25519"===r?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t)}}catch{return this.logger.warn("Mirror node key detection failed; using local detection or default ECDSA"),this.bestGuessOperatorKey(t)}}async resolveSupplyKey(e,t,r,o){try{const n=await this.mirror.getTokenInfo(e),s=n?.supply_key?._type||"";return"string"!=typeof t?t:o?"ed25519"===o?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t):s.includes("ED25519")?i.PrivateKey.fromStringED25519(t):s.includes("ECDSA")?i.PrivateKey.fromStringECDSA(t):"ed25519"===r?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t)}catch{return"string"!=typeof t?t:o?"ed25519"===o?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t):"ed25519"===r?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t)}}}function oe(e){const t="string"==typeof e.operatorId?i.AccountId.fromString(e.operatorId):e.operatorId,r=e.client?e.client:"mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet(),o=new ie({mirrorNode:e.mirrorNode,logger:e.logger});let n,s;const a=o.bestGuessOperatorKey(e.operatorKey,e.keyType);n=a.keyType,s=a.privateKey,r.setOperator(t.toString(),s);const c=(async()=>{try{const i=await o.resolveOperatorKey(t,e.operatorKey,e.keyType);n=i.keyType,s=i.privateKey,r.setOperator(t.toString(),s)}catch{}})();return{client:r,operatorId:t,get operatorKey(){return s},get keyType(){return n},ensureInitialized:async()=>{await c}}}for(var ne=Object.defineProperty,se=((e,t,r)=>((e,t,r)=>t in e?ne(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r)),ae={},ce={byteLength:function(e){var t=ge(e),r=t[0],i=t[1];return 3*(r+i)/4-i},toByteArray:function(e){var t,r,i=ge(e),o=i[0],n=i[1],s=new ue(function(e,t,r){return 3*(t+r)/4-r}(0,o,n)),a=0,c=n>0?o-4:o;for(r=0;r<c;r+=4)t=de[e.charCodeAt(r)]<<18|de[e.charCodeAt(r+1)]<<12|de[e.charCodeAt(r+2)]<<6|de[e.charCodeAt(r+3)],s[a++]=t>>16&255,s[a++]=t>>8&255,s[a++]=255&t;2===n&&(t=de[e.charCodeAt(r)]<<2|de[e.charCodeAt(r+1)]>>4,s[a++]=255&t);1===n&&(t=de[e.charCodeAt(r)]<<10|de[e.charCodeAt(r+1)]<<4|de[e.charCodeAt(r+2)]>>2,s[a++]=t>>8&255,s[a++]=255&t);return s},fromByteArray:function(e){for(var t,r=e.length,i=r%3,o=[],n=16383,s=0,a=r-i;s<a;s+=n)o.push(fe(e,s,s+n>a?a:s+n));1===i?(t=e[r-1],o.push(le[t>>2]+le[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],o.push(le[t>>10]+le[t>>4&63]+le[t<<2&63]+"="));return o.join("")}},le=[],de=[],ue="undefined"!=typeof Uint8Array?Uint8Array:Array,pe="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",he=0;he<64;++he)le[he]=pe[he],de[pe.charCodeAt(he)]=he;function ge(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function me(e){return le[e>>18&63]+le[e>>12&63]+le[e>>6&63]+le[63&e]}function fe(e,t,r){for(var i,o=[],n=t;n<r;n+=3)i=(e[n]<<16&16711680)+(e[n+1]<<8&65280)+(255&e[n+2]),o.push(me(i));return o.join("")}de["-".charCodeAt(0)]=62,de["_".charCodeAt(0)]=63;var ye={
|
|
1
|
+
"use strict";var e;Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const t=require("util"),r=require("zod"),i=require("@hashgraph/sdk"),o=require("axios"),n=require("@hashgraph/proto"),s=require("@hashgraphonline/standards-sdk"),a=require("buffer"),c=require("ethers"),l=require("file-type"),d=require("node:path"),u=require("node:buffer"),p=require("node:crypto"),h=require("@noble/curves/secp256k1.js"),g=require("viem/accounts");require("viem/chains");const m=require("x402-axios"),f=require("x402/types"),y=require("node:module"),b=require("mime-types"),w=require("date-fns"),I=require("crypto");var T="undefined"!=typeof document?document.currentScript:null;function S(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const r in e)if("default"!==r){const i=Object.getOwnPropertyDescriptor(e,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:()=>e[r]})}return t.default=e,Object.freeze(t)}const k=S(d),E=S(b),A=/^\d+\.\d+\.\d+$/u,v=Symbol.for("standards-sdk.topic-auto-renew.patch"),C=Symbol.for("standards-sdk.account-id.patch"),x=function(){const e=function(){try{if("undefined"!=typeof module&&module?.createRequire)return module}catch{}try{if("function"==typeof require){const e=require("module");if(e?.createRequire)return e}}catch{}return null}();if(e?.createRequire)try{return e.createRequire("undefined"==typeof document?require("url").pathToFileURL(__filename).href:T&&"SCRIPT"===T.tagName.toUpperCase()&&T.src||new URL("standards-sdk.cjs",document.baseURI).href)}catch{return null}if("function"==typeof require)return require;return null}();function R(e,t){try{return e(t)}catch{return null}}function N(e,t){if(!e||!t)return;!function(e){if(Reflect.get(e,C))return;const t=e.fromString.bind(e);e.fromString=function(e){if("string"==typeof e)return t(e);const r=P(e);if(r)return t(r);if(F(e)){const r=z(e.shard),i=z(e.realm),o=z(e.num);if(r&&i&&o)return t(`${r}.${i}.${o}`)}return t(e)},Reflect.set(e,C,!0)}(t);const r=e.prototype;if(Reflect.get(r,v))return;const i=r.setAutoRenewAccountId,o=r.freezeWith;r.setAutoRenewAccountId=function(e){const r=_(e,t);return r?(function(e){const t=e;t._requireNotFrozen?.()}(this),this._autoRenewAccountId=r,this):i.call(this,e)},r.freezeWith=function(e){if(!this.getAutoRenewAccountId||"function"!=typeof this.getAutoRenewAccountId)return o.call(this,e);if(!this.getAutoRenewAccountId()){const r=this.transactionId?.accountId,i=e?.operatorAccountId,o=_(r,t)??_(i,t);o&&(this._autoRenewAccountId=o)}return o.call(this,e)},Reflect.set(r,v,!0)}function _(e,t){if(e instanceof t)return e;if("string"==typeof e&&A.test(e))return t.fromString(e);const r=function(e){if("string"==typeof e&&A.test(e))return e;const t=P(e);if(t)return t;if(F(e)){const t=z(e.shard),r=z(e.realm),i=z(e.num);if(t&&r&&i){const e=`${t}.${r}.${i}`;if(A.test(e))return e}}return null}(e);return r?t.fromString(r):null}function P(e){if("object"!=typeof e||null===e)return null;const t=e.toString;if("function"!=typeof t)return null;const r=t.call(e);return"string"!=typeof r?null:A.test(r)?r:null}function F(e){if("object"!=typeof e||null===e)return!1;const t=e;return O(t.shard)&&O(t.realm)&&O(t.num)}function O(e){return"object"==typeof e&&null!==e&&"function"==typeof e.toString}function z(e){if("number"==typeof e&&Number.isFinite(e))return String(Math.trunc(e));if("bigint"==typeof e)return e.toString();if(O(e)){const t=e.toString();if(/^\d+$/u.test(t))return t}return null}x?function(e){const t=R(e,"@hashgraph/sdk/lib/account/AccountId.cjs"),r=R(e,"@hashgraph/sdk/lib/topic/TopicCreateTransaction.cjs"),i=R(e,"@hashgraph/sdk"),o=[];t?.default&&r?.default&&o.push({accountId:t.default,topic:r.default});i&&o.push({accountId:i.AccountId??i.default?.AccountId,topic:i.TopicCreateTransaction??i.default?.TopicCreateTransaction});for(const n of o)N(n.topic,n.accountId);Reflect.set(globalThis,"__standardsSdkTopicAutoRenewPatched",!0)}(x):Reflect.set(globalThis,"__standardsSdkTopicAutoRenewPatched",!1);let D=null;let B=((e=class{constructor(e={}){if(D)return D(e);const t="undefined"!=typeof process&&"true"===process.env?.DISABLE_LOGS;this.silent=e.silent||t,this.level=this.silent?"silent":e.level||"info",this.moduleContext=e.module||"app",this.prettyPrint=!this.silent&&!1!==e.prettyPrint}static getInstance(t={}){const r=t.module||"default";if("undefined"!=typeof process&&"true"===process.env?.DISABLE_LOGS&&e.instances.has(r)){"silent"!==e.instances.get(r).getLevel()&&e.instances.delete(r)}if(!e.instances.has(r)){const i=D?D(t):new e(t);e.instances.set(r,i)}return e.instances.get(r)}setLogLevel(e){this.level=e}getLevel(){return this.level}setSilent(e){this.silent=e,e&&(this.level="silent")}setModule(e){this.moduleContext=e}formatArgs(e){if(0===e.length)return{msg:""};if(1===e.length)return"string"==typeof e[0]?{msg:e[0]}:{msg:"",data:e[0]};const t=[],r=[];e.forEach(e=>{"string"==typeof e||"number"==typeof e||"boolean"==typeof e?t.push(String(e)):r.push(e)});const i=t.join(" ");return r.length>0?{msg:i,data:r}:{msg:i}}shouldLog(e){if(this.silent||"silent"===this.level)return!1;const t=["trace","debug","info","warn","error","silent"],r=t.indexOf(this.level);return t.indexOf(e)>=r}getConsoleMethod(e){return"error"===e?console.error:"warn"===e?console.warn:"debug"===e?console.debug:console.log}writeLog(e,...r){if(!this.shouldLog(e))return;const{msg:i,data:o}=this.formatArgs(r),n=(new Date).toISOString(),s=this.getConsoleMethod(e);if(this.prettyPrint){let r=`${n} ${e.toUpperCase().padEnd(5)} [${this.moduleContext}] ${i}`;o&&(r+="\n"+t.inspect(o,{colors:!0,depth:3})),s(r)}else{const t={timestamp:n,level:e,module:this.moduleContext,message:i,...o&&{data:o}};s(JSON.stringify(t))}}debug(...e){this.writeLog("debug",...e)}info(...e){this.writeLog("info",...e)}warn(...e){this.writeLog("warn",...e)}error(...e){this.writeLog("error",...e)}trace(...e){this.writeLog("trace",...e)}static clearInstances(){e.instances.clear()}}).instances=new Map,e);const M=e=>new Promise(t=>setTimeout(t,e));class U{constructor(){this.modelViewerLoaded=!1,this.modelViewerLoading=null,this.config={cdnUrl:"https://kiloscribe.com/api/inscription-cdn/",network:"mainnet",retryAttempts:3,retryBackoff:300,debug:!1,showLoadingIndicator:!1,loadingCallbackName:null},this.configMapping={hcsCdnUrl:"cdnUrl",hcsNetwork:"network",hcsRetryAttempts:"retryAttempts",hcsRetryBackoff:"retryBackoff",hcsDebug:"debug",hcsShowLoadingIndicator:"showLoadingIndicator",hcsLoadingCallbackName:"loadingCallbackName"},this.LoadedScripts={},this.LoadedWasm={},this.LoadedImages={},this.LoadedVideos={},this.LoadedAudios={},this.LoadedAudioUrls={},this.LoadedGLBs={},this.scriptLoadedEvent=new Event("HCSScriptLoaded"),this.loadQueue=[],this.isProcessingQueue=!1;try{this.logger=B.getInstance({module:"HCS-3",level:this.config.debug?"debug":"error"})}catch(e){this.logger=this.createFallbackLogger()}}createFallbackLogger(){return{debug:(...e)=>this.config.debug&&console.debug("[HCS-3]",...e),info:(...e)=>this.config.debug&&console.info("[HCS-3]",...e),warn:(...e)=>console.warn("[HCS-3]",...e),error:(...e)=>console.error("[HCS-3]",...e),setLogLevel:e=>{this.config.debug="debug"===e}}}log(...e){if(0===e.length)this.logger.debug("");else if(1===e.length)this.logger.debug(String(e[0]));else{const t=String(e[0]),r=e.slice(1);this.logger.debug(t,r)}}error(...e){if(0===e.length)this.logger.error("");else if(1===e.length)this.logger.error(String(e[0]));else{const t=String(e[0]),r=e.slice(1);this.logger.error(t,r)}}loadConfigFromHTML(){const e=document.querySelector("script[data-hcs-config]");e&&(Object.keys(this.configMapping).forEach(t=>{if(e.dataset[t]){const r=this.configMapping[t];let i=e.dataset[t];"true"===i&&(i=!0),"false"===i&&(i=!1),isNaN(Number(i))||""===i||(i=Number(i)),this.config[r]=i}}),this.logger.setLogLevel(this.config.debug?"debug":"error")),this.log("Loaded config:",this.config)}updateLoadingStatus(e,t){if("loaded"!==this.LoadedScripts[e]&&(this.config.showLoadingIndicator&&console.log("[HCS Loading] "+e+" : "+t),this.LoadedScripts[e]=t,this.config.loadingCallbackName&&"function"==typeof window[this.config.loadingCallbackName])){const r=window[this.config.loadingCallbackName];"function"==typeof r&&r(e,t)}}async fetchWithRetry(e,t=this.config.retryAttempts,r=this.config.retryBackoff){try{const t=await fetch(e);if(!t.ok)throw new Error("HTTP error! status: "+t.status);return t}catch(i){if(t>0)return this.log("Retrying fetch for "+e+" Attempts left: "+(t-1)),await this.sleep(r),this.fetchWithRetry(e,t-1,2*r);throw i}}sleep(e){return M(e)}isDuplicate(e){return!!this.LoadedScripts[e]}async retrieveHCS1Data(e,t=this.config.cdnUrl,r=this.config.network){const i=r.replace(/['"]+/g,""),o=await this.fetchWithRetry(t+e+"?network="+i);return await o.blob()}async loadScript(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),i=t?.split("/").pop(),o=e.getAttribute("type"),n=e.hasAttribute("data-required"),s="module"===e.getAttribute("type");if(!this.isDuplicate(i||"")){this.updateLoadingStatus(r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,a=e.getAttribute("data-network")||this.config.network,c=await this.retrieveHCS1Data(i,t,a);if("wasm"===o){const t=await c.arrayBuffer(),i=await WebAssembly.compile(t);this.LoadedWasm[r]=await WebAssembly.instantiate(i,{env:{},...e.dataset}),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded wasm: "+r)}else{const e=await c.text(),t=document.createElement("script");if(t.textContent=e,t.className="hcs-inline-script",r&&t.setAttribute("data-loaded-script-id",r),s){t.type="module";const r=new Blob([e],{type:"application/javascript"});t.src=URL.createObjectURL(r)}document.body.appendChild(t),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded script: "+r),t.onerror=e=>{if(this.error("Failed to load "+o+": "+r,e),this.updateLoadingStatus(r,"failed"),n)throw e}}}catch(a){if(this.error("Failed to load "+o+": "+r,a),this.updateLoadingStatus(r,"failed"),n)throw a}}}async loadModuleExports(e){const t=document.querySelector('script[data-loaded-script-id="'+e+'"]');if(!t)throw new Error("Module script with id "+e+" not found");const r=t.getAttribute("src");if(!r)throw new Error("Module script "+e+" has no src attribute");try{const e=new Function("url","return import(url)");return await e(r)}catch(i){throw this.error("Failed to import module",i),i}}async loadStylesheet(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),i=t?.split("/").pop(),o=e.hasAttribute("data-required");if(!this.isDuplicate(i||"")){this.updateLoadingStatus(r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,o=e.getAttribute("data-network")||this.config.network,n=await this.retrieveHCS1Data(i,t,o),s=await n.text(),a=document.createElement("style");a.textContent=s,document.head.appendChild(a),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded and inlined stylesheet: "+r)}catch(n){if(this.error("Failed to load stylesheet: "+r,n),this.updateLoadingStatus(r,"failed"),o)throw n}}}async loadImage(e){const t=e.getAttribute("data-src"),r=t?.split("/").pop();this.log("Loading image: "+r),this.updateLoadingStatus("Image: "+r,"loaded");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,i=e.getAttribute("data-network")||this.config.network,o=await this.retrieveHCS1Data(r,t,i),n=URL.createObjectURL(o);e.src=n,this.LoadedImages[r]=n,this.updateLoadingStatus("Image: "+r,"loaded"),this.log("Loaded image: "+r)}catch(i){this.error("Failed to load image: "+r,i),this.updateLoadingStatus("Image: "+r,"failed")}}async loadMedia(e,t){const r=e.getAttribute("data-src"),i=r?.split("/").pop();this.log("Loading "+t+": "+i),this.updateLoadingStatus(t+": "+i,"loading");try{const r=e.getAttribute("data-cdn-url")||this.config.cdnUrl,o=e.getAttribute("data-network")||this.config.network,n=await this.retrieveHCS1Data(i,r,o),s=URL.createObjectURL(n);e.src=s,"video"===t?this.LoadedVideos[i]=s:this.LoadedAudioUrls[i]=s,this.updateLoadingStatus(t+": "+i,"loaded"),this.log("Loaded "+t+": "+i)}catch(o){this.error("Failed to load "+t+": "+i,o),this.updateLoadingStatus(t+": "+i,"failed")}}async loadModelViewer(){return this.modelViewerLoading?this.modelViewerLoading:this.modelViewerLoaded?Promise.resolve():(this.modelViewerLoading=new Promise(e=>{const t=document.createElement("script");t.setAttribute("data-src","hcs://1/0.0.7293044"),t.setAttribute("data-script-id","model-viewer"),t.setAttribute("type","module"),window.addEventListener("HCSScriptLoaded",()=>{this.modelViewerLoaded=!0,e()},{once:!0}),this.loadScript(t)}),this.modelViewerLoading)}async loadGLB(e){await this.loadModelViewer();const t=e.getAttribute("data-src"),r=t?.split("/").pop();this.log("Loading GLB: "+r),this.updateLoadingStatus("GLB: "+r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,i=e.getAttribute("data-network")||this.config.network;let o;"model-viewer"!==e.tagName.toLowerCase()?(o=document.createElement("model-viewer"),Array.from(e.attributes).forEach(e=>{o.setAttribute(e.name,e.value)}),o.setAttribute("camera-controls",""),o.setAttribute("auto-rotate",""),o.setAttribute("ar",""),e.parentNode?.replaceChild(o,e)):o=e;const n=await this.retrieveHCS1Data(r,t,i),s=URL.createObjectURL(n);o.setAttribute("src",s),this.LoadedGLBs[r]=s,this.updateLoadingStatus("GLB: "+r,"loaded"),this.log("Loaded GLB: "+r)}catch(i){this.error("Failed to load GLB: "+r,i),this.updateLoadingStatus("GLB: "+r,"failed")}}async loadResource(e,t,r){return new Promise(i=>{this.loadQueue.push({element:e,type:t,order:r,resolve:i}),this.processQueue()})}async processQueue(){if(!this.isProcessingQueue){for(this.isProcessingQueue=!0;this.loadQueue.length>0;){const t=this.loadQueue.shift();try{"script"===t.type?await this.loadScript(t.element):"image"===t.type?await this.loadImage(t.element):"video"===t.type||"audio"===t.type?await this.loadMedia(t.element,t.type):"glb"===t.type?await this.loadGLB(t.element):"css"===t.type&&await this.loadStylesheet(t.element),t.resolve()}catch(e){if(this.error("Error processing queue item:",e),"script"===t.type&&t.element.hasAttribute("data-required"))break}}this.isProcessingQueue=!1}}async replaceHCSInStyle(e){let t=e,r=t.indexOf("hcs://");for(;-1!==r;){let e=r;for(;e<t.length&&!["'",'"'," ",")"].includes(t[e]);)e++;const o=t.substring(r,e),n=o.split("/").pop();try{const i=this.config.cdnUrl,s=this.config.network,a=await this.retrieveHCS1Data(n,i,s),c=URL.createObjectURL(a);t=t.substring(0,r)+c+t.substring(e),this.LoadedImages[n]=c,this.log("Replaced CSS HCS URL: "+o+" with "+c)}catch(i){this.error("Failed to load CSS image: "+n,i)}r=t.indexOf("hcs://",r+1)}return t}async processInlineStyles(){const e=document.querySelectorAll('[style*="hcs://"]');this.log("Found "+e.length+" elements with HCS style references");for(const r of Array.from(e)){const e=r.getAttribute("style");if(e){this.log("Processing style: "+e);const t=await this.replaceHCSInStyle(e);e!==t&&(r.setAttribute("style",t),this.log("Updated style to: "+t))}}const t=document.querySelectorAll("style");for(const r of Array.from(t))if(r.textContent?.includes("hcs://")){const e=await this.replaceHCSInStyle(r.textContent);r.textContent!==e&&(r.textContent=e)}}async init(){return this.loadConfigFromHTML(),new Promise(e=>{const t=async()=>{const t=document.querySelectorAll('script[data-src^="hcs://"]'),r=document.querySelectorAll('img[data-src^="hcs://"], img[src^="hcs://"]'),i=document.querySelectorAll('video[data-src^="hcs://"], video[src^="hcs://"]'),o=document.querySelectorAll('audio[data-src^="hcs://"], audio[src^="hcs://"]'),n=document.querySelectorAll('model-viewer[data-src^="hcs://"]'),s=document.querySelectorAll('link[data-src^="hcs://"]');document.querySelectorAll('[src^="hcs://"]').forEach(e=>{const t=e.getAttribute("src");t&&(e.setAttribute("data-src",t),e.removeAttribute("src"))}),await this.processInlineStyles();const a=[];[{elements:t,type:"script"},{elements:r,type:"image"},{elements:i,type:"video"},{elements:o,type:"audio"},{elements:n,type:"glb"},{elements:s,type:"css"}].forEach(({elements:e,type:t})=>{e.forEach(e=>{const r=parseInt(e.getAttribute("data-load-order")||"")||1/0;a.push(this.loadResource(e,t,r))})}),await Promise.all(a);const c=new MutationObserver(e=>{e.forEach(e=>{if(e.addedNodes.forEach(e=>{if(e.nodeType===Node.ELEMENT_NODE){const t=e;if(t.getAttribute("style")?.includes("hcs://")&&this.processInlineStyles(),"style"===t.tagName.toLowerCase()&&t.textContent?.includes("hcs://")&&this.processInlineStyles(),t.getAttribute("src")?.startsWith("hcs://")){const e=t.getAttribute("src");t.setAttribute("data-src",e),t.removeAttribute("src");switch(t.tagName.toLowerCase()){case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"script":this.loadResource(t,"script",1/0)}}t.matches('script[data-src^="hcs://"]')?this.loadResource(t,"script",1/0):t.matches('img[data-src^="hcs://"]')?this.loadResource(t,"image",1/0):t.matches('video[data-src^="hcs://"]')?this.loadResource(t,"video",1/0):t.matches('audio[data-src^="hcs://"]')?this.loadResource(t,"audio",1/0):t.matches('model-viewer[data-src^="hcs://"]')?this.loadResource(t,"glb",1/0):t.matches('link[data-src^="hcs://"]')&&this.loadResource(t,"css",1/0);t.querySelectorAll('[data-src^="hcs://"], [src^="hcs://"]').forEach(e=>{const t=e,r=t.tagName.toLowerCase(),i=t.getAttribute("src");switch(i?.startsWith("hcs://")&&(t.setAttribute("data-src",i),t.removeAttribute("src")),r){case"script":this.loadResource(t,"script",1/0);break;case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"model-viewer":this.loadResource(t,"glb",1/0);break;case"link":this.loadResource(t,"css",1/0)}})}}),"attributes"===e.type){const t=e.target;if("style"===e.attributeName&&t.getAttribute("style")?.includes("hcs://"))this.processInlineStyles();else if("src"===e.attributeName){const e=t.getAttribute("src");if(e?.startsWith("hcs://")){t.setAttribute("data-src",e),t.removeAttribute("src");const r=t.tagName.toLowerCase();["img","video","audio"].includes(r)&&this.loadResource(t,r,1/0)}}}})});document.body?c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]}):document.addEventListener("DOMContentLoaded",()=>{c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]})}),e()};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()})}async preloadImage(e){this.log("Loading image:"+e),this.updateLoadingStatus("image: "+e,"loading");const t=await this.retrieveHCS1Data(e),r=URL.createObjectURL(t);return this.LoadedImages[e]=r,this.updateLoadingStatus("image: "+e,"loaded"),r}async preloadAudio(e){const t=document.createElement("audio");t.setAttribute("data-topic-id",e),t.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(t),await this.loadMedia(t,"audio");const r=document.querySelector('audio[data-topic-id="'+e+'"]');return r?this.LoadedAudioUrls[e]=r.src:console.error("Failed to preload audio: "+e),this.LoadedAudioUrls[e]}async playAudio(e,t=1){const r=this.LoadedAudioUrls[e];if(r){const i=new Audio(r);i.volume=t,this.LoadedAudios[e]=i,i.play().catch(e=>{console.error("Failed to play audio:",e)}),i.addEventListener("ended",()=>{i.remove(),delete this.LoadedAudios[e]})}else console.error("Audio not preloaded: "+e)}async pauseAudio(e){const t=document.querySelector('audio[data-topic-id="'+e+'"]');t?(console.log("found element",t),t.pause(),this.LoadedAudios[e]?.pause()):this.LoadedAudios[e]?.pause()}async loadAndPlayAudio(e,t=!1,r=1){let i=document.querySelector('audio[data-topic-id="'+e+'"]');if(i)i.volume=r,await i.play();else{const o=document.createElement("audio");o.volume=r,t&&o.setAttribute("autoplay","autoplay"),o.setAttribute("data-topic-id",e),o.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(o),await this.loadMedia(o,"audio"),i=document.querySelector('audio[data-topic-id="'+e+'"]'),t||await i.play()}}}var L=(e=>(e.REGISTER="register",e))(L||{}),K=(e=>(e[e.NON_INDEXED=1]="NON_INDEXED",e))(K||{});function $(e){return`hcs://6/${e}`}const H=r.z.string().regex(/^\d+\.\d+\.\d+$/,{message:"Topic ID must be in Hedera format (e.g., '0.0.123456')"}),q=r.z.object({p:r.z.literal("hcs-6"),op:r.z.enum(["register"]),m:r.z.string().max(500,"Memo must not exceed 500 characters").optional()}),j=q.extend({op:r.z.literal("register"),t_id:H}),W=r.z.discriminatedUnion("op",[j]);function V(e){return e>=3600}function G(e){if(!V(e))throw new Error("TTL must be at least 3600 seconds (1 hour)");return`hcs-6:1:${e}`}class J{constructor(e,t,r){this.maxRetries=5,this.initialDelayMs=2e3,this.maxDelayMs=3e4,this.backoffFactor=2,this.network=e,this.apiKey=r?.apiKey,this.customHeaders=r?.headers||{},this.baseUrl=r?.customUrl||this.getMirrorNodeUrl(),this.logger=t||new B({level:"debug",module:"MirrorNode"}),this.isServerEnvironment="undefined"==typeof window,r?.customUrl&&this.logger.info(`Using custom mirror node URL: ${r.customUrl}`),r?.apiKey&&this.logger.info("Using API key for mirror node requests")}configureRetry(e){this.maxRetries=e.maxRetries??this.maxRetries,this.initialDelayMs=e.initialDelayMs??this.initialDelayMs,this.maxDelayMs=e.maxDelayMs??this.maxDelayMs,this.backoffFactor=e.backoffFactor??this.backoffFactor,this.logger.info(`Retry configuration updated: maxRetries=${this.maxRetries}, initialDelayMs=${this.initialDelayMs}, maxDelayMs=${this.maxDelayMs}, backoffFactor=${this.backoffFactor}`)}configureMirrorNode(e){e.customUrl&&(this.baseUrl=e.customUrl,this.logger.info(`Updated mirror node URL: ${e.customUrl}`)),e.apiKey&&(this.apiKey=e.apiKey,this.logger.info("Updated API key for mirror node requests")),e.headers&&(this.customHeaders={...this.customHeaders,...e.headers},this.logger.info("Updated custom headers for mirror node requests"))}constructUrl(e){if(this.baseUrl.includes("<API-KEY>")&&this.apiKey){const t=this.baseUrl.replace("<API-KEY>",this.apiKey);return e.startsWith("/")?`${t}${e}`:`${t}/${e}`}return e.startsWith("/")?`${this.baseUrl}${e}`:`${this.baseUrl}/${e}`}getMirrorNodeUrl(){return"mainnet"===this.network?"https://mainnet-public.mirrornode.hedera.com":"https://testnet.mirrornode.hedera.com"}getBaseUrl(){return this.baseUrl}async getPublicKey(e){this.logger.debug(`Getting public key for account ${e}`);const t=await this.requestAccount(e);try{if(!t||!t.key)throw new Error(`Failed to retrieve public key for account ID: ${e}`);return i.PublicKey.fromString(t.key.key)}catch(r){const e=`Error fetching public key from Mirror Node: ${r.message}`;throw this.logger.error(e),new Error(e)}}async getAccountMemo(e){this.logger.debug(`Getting account memo for account ID: ${e}`);try{const t=await this._requestWithRetry(`/api/v1/accounts/${e}`);return t?.memo?t.memo:(this.logger.warn(`No memo found for account ${e}`),null)}catch(t){const r=t;return this.logger.error(`Failed to get account memo for ${e} after retries: ${r.message}`),null}}async getTopicInfo(e){try{this.logger.debug(`Fetching topic info for ${e}`);return await this._requestWithRetry(`/api/v1/topics/${e}`)}catch(t){const r=`Error retrieving topic information for ${e} after retries: ${t.message}`;throw this.logger.error(r),new Error(r)}}async getTopicFees(e){try{return(await this.getTopicInfo(e)).custom_fees}catch(t){const e=`Error retrieving topic fees: ${t.message}`;return this.logger.error(e),null}}async getHBARPrice(e){try{const t=i.Timestamp.fromDate(e).toString();this.logger.debug(`Fetching HBAR price for timestamp ${t}`);const r=await this._requestWithRetry(`/api/v1/network/exchangerate?timestamp=${t}`);return Number(r?.current_rate?.cent_equivalent)/Number(r?.current_rate?.hbar_equivalent)/100}catch(t){const e=`Error retrieving HBAR price: ${t.message}`;return this.logger.error(e),null}}async getTokenInfo(e){this.logger.debug(`Fetching token info for ${e}`);try{const t=await this._requestWithRetry(`/api/v1/tokens/${e}`);return t?(this.logger.trace(`Token info found for ${e}:`,t),t):(this.logger.warn(`No token info found for ${e}`),null)}catch(t){const r=`Error fetching token info for ${e}: ${t.message}`;return this.logger.error(r),null}}async getTopicMessages(e,t){this.logger.trace(`Querying messages for topic ${e}${t?" with filters":""}`);let r=`/api/v1/topics/${e}/messages`;const i=new URLSearchParams;if(t){if(void 0!==t.sequenceNumber){const e="number"==typeof t.sequenceNumber?t.sequenceNumber.toString():t.sequenceNumber;e.match(/^(gt|gte|lt|lte|eq|ne):/)?i.append("sequencenumber",e):i.append("sequencenumber",`gt:${e}`)}t.limit&&i.append("limit",t.limit.toString()),t.order&&i.append("order",t.order)}const o=i.toString();o&&(r+=`?${o}`);const n=[];let s=r;for(;s;)try{const e=await this._requestWithRetry(s);if(e.messages&&e.messages.length>0)for(const t of e.messages)try{if(!t.message)continue;let e,r;try{e=this.isServerEnvironment?globalThis.Buffer.from(t.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(t.message),e=>e.charCodeAt(0)))}catch(a){const e=`Error decoding message: ${a}`;this.logger.error(e);continue}try{r=JSON.parse(e)}catch(a){const t=`Invalid JSON message content: ${e}`;this.logger.error(t);continue}r.sequence_number=t.sequence_number,n.push({...r,consensus_timestamp:t.consensus_timestamp,sequence_number:t.sequence_number,running_hash:t.running_hash,running_hash_version:t.running_hash_version,topic_id:t.topic_id,payer:t.payer_account_id,created:new Date(1e3*Number(t.consensus_timestamp))})}catch(a){const e=`Error processing message: ${a.message}`;this.logger.error(e)}s=e.links?.next||""}catch(c){const t=`Error querying topic messages for topic ${e} (endpoint: ${s}) after retries: ${c.message}`;throw this.logger.error(t),new Error(t)}return n}async requestAccount(e){try{this.logger.debug(`Requesting account info for ${e}`);const t=await this._requestWithRetry(`/api/v1/accounts/${e}`);if(!t)throw new Error(`No data received from mirror node for account: ${e}`);return t}catch(t){const r=`Failed to fetch account ${e} after retries: ${t.message}`;throw this.logger.error(r),new Error(r)}}async checkKeyListAccess(e,t){try{const r=n.proto.Key.decode(e);return this.evaluateKeyAccess(r,t)}catch(r){const e=`Error decoding protobuf key: ${r.message}`;throw this.logger.error(e),new Error(e)}}async evaluateKeyAccess(e,t){return e.ed25519?this.compareEd25519Key(e.ed25519,t):e.keyList?this.evaluateKeyList(e.keyList,t):!(!e.thresholdKey||!e.thresholdKey.keys)&&this.evaluateKeyList(e.thresholdKey.keys,t)}async evaluateKeyList(e,t){const r=e.keys||[];for(const o of r)if(o)if(o.ed25519){if(this.compareEd25519Key(o.ed25519,t))return!0}else if(o.keyList||o.thresholdKey)try{const e=n.proto.Key.encode({...o.keyList?{keyList:o.keyList}:{},...o.thresholdKey?{thresholdKey:o.thresholdKey}:{}}).finish();if(await this.checkKeyListAccess(globalThis.Buffer.from(e),t))return!0}catch(i){const e=`Error in nested key: ${i.message}`;this.logger.debug(e)}return!1}compareEd25519Key(e,t){try{return i.PublicKey.fromBytes(globalThis.Buffer.from(e)).toString()===t.toString()}catch(r){const e=`Error comparing Ed25519 key: ${r.message}`;return this.logger.debug(e),!1}}async getScheduleInfo(e){try{this.logger.info(`Getting information for scheduled transaction ${e}`);const t=await this._requestWithRetry(`/api/v1/schedules/${e}`);return t||(this.logger.warn(`No schedule info found for ${e} after retries.`),null)}catch(t){return this.logger.error(`Error fetching schedule info for ${e} after retries: ${t.message}`),null}}async getScheduledTransactionStatus(e){try{this.logger.info(`Checking status of scheduled transaction ${e}`);const t=await this.getScheduleInfo(e);if(!t)throw new Error(`Schedule ${e} not found`);return{executed:Boolean(t.executed_timestamp),executedDate:t.executed_timestamp?new Date(1e3*Number(t.executed_timestamp)):void 0,deleted:t.deleted||!1}}catch(t){throw this.logger.error(`Error checking scheduled transaction status: ${t}`),t}}async getTransaction(e){this.logger.info(`Getting transaction details for ID/hash: ${e}`);try{const t=await this._requestWithRetry(`/api/v1/transactions/${e}`);return t?.transactions?.length>0?(this.logger.trace(`Transaction details found for ${e}:`,t.transactions[0]),t.transactions[0]):(this.logger.warn(`No transaction details found for ${e} or unexpected response structure.`),null)}catch(t){const r=t;return this.logger.error(`Failed to get transaction details for ${e} after retries: ${r.message}`),null}}async _requestWithRetry(e,t){let r=0,i=this.initialDelayMs;const n=this.constructUrl(e),s={...t,headers:{...this.customHeaders,...t?.headers}};for(this.apiKey&&(s.headers={...s.headers,Authorization:`Bearer ${this.apiKey}`,"X-API-Key":this.apiKey});r<this.maxRetries;)try{return(await o.get(n,s)).data}catch(a){r++;const e=r>=this.maxRetries,t=a.response?.status;if(t&&t>404&&t<500&&429!==t)throw this.logger.error(`Client error for ${n} (status ${t}): ${a.message}. Not retrying.`),a;if(e)throw this.logger.error(`Max retries (${this.maxRetries}) reached for ${n}. Last error: ${a.message}`),a;this.logger.warn(`Attempt ${r}/${this.maxRetries} failed for ${n}: ${a.message}. Retrying in ${i}ms...`),await new Promise(e=>setTimeout(e,i)),i=Math.min(i*this.backoffFactor,this.maxDelayMs)}throw new Error(`Failed to fetch data from ${n} after ${this.maxRetries} attempts.`)}async _fetchWithRetry(e,t){let r=0,i=this.initialDelayMs;const o={...this.customHeaders};t?.headers&&(t.headers instanceof Headers?t.headers.forEach((e,t)=>{o[t]=e}):Array.isArray(t.headers)?t.headers.forEach(([e,t])=>{o[e]=t}):Object.assign(o,t.headers)),this.apiKey&&(o.Authorization=`Bearer ${this.apiKey}`,o["X-API-Key"]=this.apiKey);const n={...t,headers:o};for(;r<this.maxRetries;)try{const t=await fetch(e,n);if(!t.ok){if(t.status>=400&&t.status<500&&429!==t.status)throw this.logger.error(`Client error for ${e} (status ${t.status}): ${t.statusText}. Not retrying.`),new Error(`Fetch failed with status ${t.status}: ${t.statusText} for URL: ${e}`);throw new Error(`Fetch failed with status ${t.status}: ${t.statusText} for URL: ${e}`)}return await t.json()}catch(s){if(r++,r>=this.maxRetries)throw this.logger.error(`Max retries (${this.maxRetries}) reached for ${e}. Last error: ${s.message}`),s;this.logger.warn(`Attempt ${r}/${this.maxRetries} failed for ${e}: ${s.message}. Retrying in ${i}ms...`),await new Promise(e=>setTimeout(e,i)),i=Math.min(i*this.backoffFactor,this.maxDelayMs)}throw new Error(`Failed to fetch data from ${e} after ${this.maxRetries} attempts.`)}async getAccountBalance(e){this.logger.info(`Getting balance for account ${e}`);try{const t=await this.requestAccount(e);if(t&&t.balance){return t.balance.balance/1e8}return this.logger.warn(`Could not retrieve balance for account ${e} from account info.`),null}catch(t){return this.logger.error(`Error fetching numerical balance for account ${e}: ${t.message}`),null}}async getTopicMessagesByFilter(e,t){this.logger.trace(`Querying messages for topic ${e} with filters: ${JSON.stringify(t)}`);let r=`/api/v1/topics/${e}/messages`;const i=new URLSearchParams;t?.limit&&i.append("limit",t.limit.toString()),t?.sequenceNumber&&i.append("sequencenumber",t.sequenceNumber),t?.startTime&&i.append("timestamp",`gte:${t.startTime}`),t?.endTime&&i.append("timestamp",`lt:${t.endTime}`),t?.order&&i.append("order",t.order);const o=i.toString();o&&(r+=`?${o}`);const n=[];let s=0;try{for(;r&&s<10;){s++;const e=await this._requestWithRetry(r);if(e.messages&&e.messages.length>0)for(const t of e.messages)try{if(!t.message)continue;let e;e=this.isServerEnvironment?globalThis.Buffer.from(t.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(t.message),e=>e.charCodeAt(0)));let r={};try{r=JSON.parse(e)}catch(a){this.logger.debug(`Message content is not valid JSON, using raw: ${e}`),r={raw_content:e}}const i={...r,consensus_timestamp:t.consensus_timestamp,sequence_number:t.sequence_number,payer_account_id:t.payer_account_id,topic_id:t.topic_id,running_hash:t.running_hash,running_hash_version:t.running_hash_version,chunk_info:t.chunk_info,created:new Date(1e3*Number(t.consensus_timestamp.split(".")[0])+Number(t.consensus_timestamp.split(".")[1]||0)/1e6),payer:t.payer_account_id};n.push(i)}catch(c){this.logger.error(`Error processing individual message: ${c.message}`)}if(t?.limit&&n.length>=t.limit)break;r=e.links?.next?`${e.links.next}`:""}return n}catch(l){const t=l;return this.logger.error(`Error querying filtered topic messages for ${e}: ${t.message}`),null}}async getAccountTokens(e,t=100){this.logger.info(`Getting tokens for account ${e}`);let r=[],i=`/api/v1/accounts/${e}/tokens?limit=${t}`;try{for(let e=0;e<10&&i;e++){const e=await this._requestWithRetry(i);if(e&&e.tokens&&(r=r.concat(e.tokens)),i=e.links?.next||"",!i||t&&r.length>=t){t&&r.length>t&&(r=r.slice(0,t));break}}return r}catch(o){return this.logger.error(`Error fetching tokens for account ${e}: ${o.message}`),null}}async getTransactionByTimestamp(e){this.logger.info(`Getting transaction by timestamp: ${e}`);try{return(await this._requestWithRetry(`/api/v1/transactions?timestamp=${e}&limit=1`)).transactions}catch(t){return this.logger.error(`Error fetching transaction by timestamp ${e}: ${t}`),[]}}async getAccountNfts(e,t,r=100){this.logger.info(`Getting NFTs for account ${e}${t?` for token ${t}`:""}`);let i=[],o=`/api/v1/accounts/${e}/nfts?limit=${r}`;t&&(o+=`&token.id=${t}`);try{for(let e=0;e<10&&o;e++){const e=await this._requestWithRetry(o);if(e&&e.nfts){const t=e.nfts.map(e=>{let t;if(e.metadata)try{t=this.isServerEnvironment?globalThis.Buffer.from(e.metadata,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(e.metadata),e=>e.charCodeAt(0)))}catch(r){this.logger.warn(`Failed to decode metadata for NFT ${e.token_id} SN ${e.serial_number}: ${r.message}`)}return{...e,token_uri:t}});i=i.concat(t)}if(o=e.links?.next||"",!o)break}return i}catch(n){return this.logger.error(`Error fetching NFTs for account ${e}: ${n.message}`),null}}async validateNFTOwnership(e,t,r){this.logger.info(`Validating ownership of NFT ${t} SN ${r} for account ${e}`);try{const i=await this.getAccountNfts(e,t);if(i){return i.find(e=>e.token_id===t&&e.serial_number===r)||null}return null}catch(i){return this.logger.error(`Error validating NFT ownership: ${i.message}`),null}}async readSmartContractQuery(e,t,r,o){this.logger.info(`Reading smart contract ${e} with selector ${t}`);const n=e.startsWith("0x")?e:`0x${i.AccountId.fromString(e).toSolidityAddress()}`,s=r.startsWith("0x")?r:`0x${i.AccountId.fromString(r).toSolidityAddress()}`,a={block:o?.block||"latest",data:t,estimate:o?.estimate||!1,from:s,to:n,gas:o?.gas,gasPrice:o?.gasPrice,value:o?.value||0};Object.keys(a).forEach(e=>{const t=e;void 0===a[t]&&delete a[t]});try{const e=this.constructUrl("/api/v1/contracts/call");return await this._fetchWithRetry(e,{method:"POST",body:JSON.stringify(a),headers:{"Content-Type":"application/json"}})}catch(c){return this.logger.error(`Error reading smart contract ${e}: ${c.message}`),null}}async getOutstandingTokenAirdrops(e,t){this.logger.info(`Getting outstanding token airdrops sent by account ${e}`);let r=`/api/v1/accounts/${e}/airdrops/outstanding`;const i=new URLSearchParams;t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.receiverId&&i.append("receiver.id",t.receiverId),t?.serialNumber&&i.append("serialnumber",t.serialNumber),t?.tokenId&&i.append("token.id",t.tokenId);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).airdrops||[]}catch(n){return this.logger.error(`Error fetching outstanding token airdrops for account ${e}: ${n.message}`),null}}async getPendingTokenAirdrops(e,t){this.logger.info(`Getting pending token airdrops received by account ${e}`);let r=`/api/v1/accounts/${e}/airdrops/pending`;const i=new URLSearchParams;t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.senderId&&i.append("sender.id",t.senderId),t?.serialNumber&&i.append("serialnumber",t.serialNumber),t?.tokenId&&i.append("token.id",t.tokenId);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).airdrops||[]}catch(n){return this.logger.error(`Error fetching pending token airdrops for account ${e}: ${n.message}`),null}}async getBlocks(e){this.logger.info("Getting blocks from the network");let t="/api/v1/blocks";const r=new URLSearchParams;e?.limit&&r.append("limit",e.limit.toString()),e?.order&&r.append("order",e.order),e?.timestamp&&r.append("timestamp",e.timestamp),e?.blockNumber&&r.append("block.number",e.blockNumber);const i=r.toString();i&&(t+=`?${i}`);try{return(await this._requestWithRetry(t)).blocks||[]}catch(o){return this.logger.error(`Error fetching blocks: ${o.message}`),null}}async getBlock(e){this.logger.info(`Getting block ${e}`);try{return await this._requestWithRetry(`/api/v1/blocks/${e}`)}catch(t){return this.logger.error(`Error fetching block ${e}: ${t.message}`),null}}async getContracts(e){this.logger.info("Getting contracts from the network");let t="/api/v1/contracts";const r=new URLSearchParams;e?.contractId&&r.append("contract.id",e.contractId),e?.limit&&r.append("limit",e.limit.toString()),e?.order&&r.append("order",e.order);const i=r.toString();i&&(t+=`?${i}`);try{return(await this._requestWithRetry(t)).contracts||[]}catch(o){return this.logger.error(`Error fetching contracts: ${o.message}`),null}}async getContract(e,t){this.logger.info(`Getting contract ${e}`);let r=`/api/v1/contracts/${e}`;t&&(r+=`?timestamp=${t}`);try{return await this._requestWithRetry(r)}catch(i){return this.logger.error(`Error fetching contract ${e}: ${i.message}`),null}}async getContractResults(e){this.logger.info("Getting contract results from the network");let t="/api/v1/contracts/results";const r=new URLSearchParams;e?.from&&r.append("from",e.from),e?.blockHash&&r.append("block.hash",e.blockHash),e?.blockNumber&&r.append("block.number",e.blockNumber),void 0!==e?.internal&&r.append("internal",e.internal.toString()),e?.limit&&r.append("limit",e.limit.toString()),e?.order&&r.append("order",e.order),e?.timestamp&&r.append("timestamp",e.timestamp),e?.transactionIndex&&r.append("transaction.index",e.transactionIndex.toString());const i=r.toString();i&&(t+=`?${i}`);try{return(await this._requestWithRetry(t)).results||[]}catch(o){return this.logger.error(`Error fetching contract results: ${o.message}`),null}}async getContractResult(e,t){this.logger.info(`Getting contract result for ${e}`);let r=`/api/v1/contracts/results/${e}`;void 0!==t&&(r+=`?nonce=${t}`);try{return await this._requestWithRetry(r)}catch(i){return this.logger.error(`Error fetching contract result for ${e}: ${i.message}`),null}}async getContractResultsByContract(e,t){this.logger.info(`Getting contract results for contract ${e}`);let r=`/api/v1/contracts/${e}/results`;const i=new URLSearchParams;t?.blockHash&&i.append("block.hash",t.blockHash),t?.blockNumber&&i.append("block.number",t.blockNumber),t?.from&&i.append("from",t.from),void 0!==t?.internal&&i.append("internal",t.internal.toString()),t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.timestamp&&i.append("timestamp",t.timestamp),t?.transactionIndex&&i.append("transaction.index",t.transactionIndex.toString());const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).results||[]}catch(n){return this.logger.error(`Error fetching contract results for ${e}: ${n.message}`),null}}async getContractState(e,t){this.logger.info(`Getting contract state for ${e}`);let r=`/api/v1/contracts/${e}/state`;const i=new URLSearchParams;t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.slot&&i.append("slot",t.slot),t?.timestamp&&i.append("timestamp",t.timestamp);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).state||[]}catch(n){return this.logger.error(`Error fetching contract state for ${e}: ${n.message}`),null}}async getContractActions(e,t){this.logger.info(`Getting contract actions for ${e}`);let r=`/api/v1/contracts/results/${e}/actions`;const i=new URLSearchParams;t?.index&&i.append("index",t.index),t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).actions||[]}catch(n){return this.logger.error(`Error fetching contract actions for ${e}: ${n.message}`),null}}async getContractLogs(e){this.logger.info("Getting contract logs from the network");let t="/api/v1/contracts/results/logs";const r=new URLSearchParams;e?.index&&r.append("index",e.index),e?.limit&&r.append("limit",e.limit.toString()),e?.order&&r.append("order",e.order),e?.timestamp&&r.append("timestamp",e.timestamp),e?.topic0&&r.append("topic0",e.topic0),e?.topic1&&r.append("topic1",e.topic1),e?.topic2&&r.append("topic2",e.topic2),e?.topic3&&r.append("topic3",e.topic3),e?.transactionHash&&r.append("transaction.hash",e.transactionHash);const i=r.toString();i&&(t+=`?${i}`);try{return(await this._requestWithRetry(t)).logs||[]}catch(o){return this.logger.error(`Error fetching contract logs: ${o.message}`),null}}async getContractLogsByContract(e,t){this.logger.info(`Getting contract logs for contract ${e}`);let r=`/api/v1/contracts/${e}/results/logs`;const i=new URLSearchParams;t?.index&&i.append("index",t.index),t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.timestamp&&i.append("timestamp",t.timestamp),t?.topic0&&i.append("topic0",t.topic0),t?.topic1&&i.append("topic1",t.topic1),t?.topic2&&i.append("topic2",t.topic2),t?.topic3&&i.append("topic3",t.topic3);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).logs||[]}catch(n){return this.logger.error(`Error fetching contract logs for ${e}: ${n.message}`),null}}async getNftInfo(e,t){this.logger.info(`Getting NFT info for ${e}/${t}`);const r=`/api/v1/tokens/${e}/nfts/${t}`;try{return await this._requestWithRetry(r)}catch(i){return this.logger.error(`Error fetching NFT info for ${e}/${t}: ${i.message}`),null}}async getNftsByToken(e,t){this.logger.info(`Getting NFTs for token ${e}`);let r=`/api/v1/tokens/${e}/nfts`;const i=new URLSearchParams;t?.accountId&&i.append("account.id",t.accountId),t?.limit&&i.append("limit",t.limit.toString()),t?.order&&i.append("order",t.order),t?.serialNumber&&i.append("serialnumber",t.serialNumber);const o=i.toString();o&&(r+=`?${o}`);try{return(await this._requestWithRetry(r)).nfts||[]}catch(n){return this.logger.error(`Error fetching NFTs for token ${e}: ${n.message}`),null}}async getNetworkInfo(){this.logger.info("Getting network information");try{return await this._requestWithRetry("/api/v1/network/nodes")}catch(e){return this.logger.error(`Error fetching network info: ${e.message}`),null}}async getNetworkFees(e){this.logger.info("Getting network fees");let t="/api/v1/network/fees";e&&(t+=`?timestamp=${e}`);try{return await this._requestWithRetry(t)}catch(r){return this.logger.error(`Error fetching network fees: ${r.message}`),null}}async getNetworkSupply(e){this.logger.info("Getting network supply");let t="/api/v1/network/supply";e&&(t+=`?timestamp=${e}`);try{return await this._requestWithRetry(t)}catch(r){return this.logger.error(`Error fetching network supply: ${r.message}`),null}}async getNetworkStake(e){this.logger.info("Getting network stake");let t="/api/v1/network/stake";e&&(t+=`?timestamp=${e}`);try{return await this._requestWithRetry(t)}catch(r){return this.logger.error(`Error fetching network stake: ${r.message}`),null}}async getOpcodeTraces(e,t){this.logger.info(`Getting opcode traces for ${e}`);let r=`/api/v1/contracts/results/${e}/opcodes`;const i=new URLSearchParams;void 0!==t?.stack&&i.append("stack",t.stack.toString()),void 0!==t?.memory&&i.append("memory",t.memory.toString()),void 0!==t?.storage&&i.append("storage",t.storage.toString());const o=i.toString();o&&(r+=`?${o}`);try{return await this._requestWithRetry(r)}catch(n){return this.logger.error(`Error fetching opcode traces for ${e}: ${n.message}`),null}}}class Y{constructor(e){this.network=e.network,this.logger=e.logger||B.getInstance({level:e.logLevel||"info",module:"HCS6Client",silent:e.silent}),this.mirrorNode=new J(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0)}parseRegistryTypeFromMemo(e){try{const t=/hcs-6:(\d):(\d+)/,r=e.match(t);if(r&&3===r.length){const e=parseInt(r[1]),t=parseInt(r[2]);if(e===K.NON_INDEXED&&V(t))return{registryType:e,ttl:t}}return}catch(t){return void this.logger.error(`Error parsing HCS-6 registry type from memo: ${t}`)}}generateRegistryMemo(e){return G(e)}validateMessage(e){try{return W.parse(e),{valid:!0,errors:[]}}catch(t){const e=[];return t instanceof r.ZodError?t.errors.forEach(t=>{const r=t.path.join(".");e.push(`${r?r+": ":""}${t.message}`)}):e.push(`Unexpected error: ${t}`),this.logger.debug(`HCS-6 message validation failed: ${e.join(", ")}`),{valid:!1,errors:e}}}createRegisterMessage(e,t){return{p:"hcs-6",op:L.REGISTER,t_id:e,m:t}}parseRegistryEntries(e,t,r,i){const o=[];let n;this.logger.debug(`Parsing ${t.length} messages for HCS-6 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 HCS-6 message: ${JSON.stringify(i)}`);const{valid:s,errors:c}=this.validateMessage(i);if(!s){this.logger.warn(`Invalid HCS-6 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};o.push(l),(!n||l.timestamp>n.timestamp)&&(n=l)}catch(s){this.logger.warn(`Error parsing HCS-6 message: ${s}`)}return this.logger.debug(`Parsed ${o.length} valid entries for HCS-6 topic ${e}`),{topicId:e,registryType:r,ttl:i,entries:n?[n]:[],latestEntry:n}}async validateHCS6Topic(e){try{const t=await this.mirrorNode.getTopicInfo(e),r=this.parseRegistryTypeFromMemo(t.memo);return r?r.registryType===K.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}}}function X(e){const{memo:t,adminKey:r,submitKey:o,operatorPublicKey:n}=e,s=(new i.TopicCreateTransaction).setTopicMemo(t),a=e=>{if(e){if(e instanceof i.PublicKey||e instanceof i.KeyList)return e;if("boolean"==typeof e)return e?n:void 0;if("string"==typeof e)try{return i.PublicKey.fromString(e)}catch{return}}},c=a(r);c&&s.setAdminKey(c);const l=a(o);return l&&s.setSubmitKey(l),s}function Z(e){const t=(new i.TopicMessageSubmitTransaction).setTopicId(i.TopicId.fromString(e.topicId)).setMessage(e.message);return e.transactionMemo&&t.setTransactionMemo(e.transactionMemo),t}function Q(e){return X({memo:e.memoOverride??`hcs-6:1:${e.ttl}`,submitKey:e.submitKey,adminKey:e.adminKey,operatorPublicKey:e.operatorPublicKey})}var ee=(e=>(e.ED25519="ed25519",e.ECDSA="ecdsa",e.UNKNOWN="unknown",e))(ee||{});const te=class{static detect(e){try{let t,r="raw";if("string"==typeof e){let i=e.trim();if(i.includes("-----BEGIN"))return this.detectFromPem(i);if(i.toLowerCase().startsWith("0x")&&(i=i.substring(2)),this.isValidHex(i))t=this.hexToBytes(i),r="hex";else{if(!this.isBase64(i))return{type:"unknown",format:"raw",isPrivateKey:!1,confidence:"certain"};t=globalThis.Buffer.from(i,"base64"),r="der"}}else t=e instanceof globalThis.Buffer?new Uint8Array(e):e;return this.detectFromBytes(t,r)}catch(t){return{type:"unknown",format:"raw",isPrivateKey:!1,confidence:"certain"}}}static detectFromBytes(e,t){if(this.hasPrefix(e,this.ED25519_PUBLIC_KEY_PREFIX)){const t=this.ED25519_PUBLIC_KEY_PREFIX.length;return{type:"ed25519",format:"der",isPrivateKey:!1,rawBytes:e.slice(t),confidence:"certain"}}if(this.hasPrefix(e,this.ED25519_PRIVATE_KEY_PREFIX)){const t=this.ED25519_PRIVATE_KEY_PREFIX.length;if(e.length>=t+32)return{type:"ed25519",format:"der",isPrivateKey:!0,rawBytes:e.slice(t,t+32),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PUBLIC_KEY_PREFIX)){const t=this.ECDSA_SECP256K1_PUBLIC_KEY_PREFIX.length;return{type:"ecdsa",format:"der",isPrivateKey:!1,rawBytes:e.slice(t),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_SHORT)){const t=this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_SHORT.length;return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:e.slice(t),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX)){const t=this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX.length;return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:e.slice(t,t+32),confidence:"certain"}}if(this.hasPrefix(e,this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_LONG)){const t=this.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_LONG.length;return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:e.slice(t,t+32),confidence:"certain"}}if(e.length>36&&this.containsECDSAPrivateKeyPattern(e))return{type:"ecdsa",format:"der",isPrivateKey:!0,rawBytes:this.extractECDSAPrivateKey(e),confidence:"certain"};switch(e.length){case this.ED25519_PUBLIC_KEY_LENGTH:if("hex"===t){const t=Array.from(e).map(e=>e.toString(16).padStart(2,"0")).join(""),r=this.tryCreateKey(t);if("unknown"!==r.type)return r}return{type:"unknown",format:t,isPrivateKey:!1,rawBytes:e,confidence:"certain"};case this.ED25519_EXPANDED_PRIVATE_KEY_LENGTH:return{type:"ed25519",format:t,isPrivateKey:!0,rawBytes:e,confidence:"certain"}}return{type:"unknown",format:t,isPrivateKey:!1,rawBytes:e,confidence:"certain"}}static detectFromPem(e){const t=e.trim(),r=t.includes("PRIVATE KEY"),i={EC_PRIVATE:/-----BEGIN EC PRIVATE KEY-----/,EC_PUBLIC:/-----BEGIN EC PUBLIC KEY-----/,PRIVATE:/-----BEGIN PRIVATE KEY-----/,PUBLIC:/-----BEGIN PUBLIC KEY-----/};let o=!1;for(const[a,c]of Object.entries(i))if(c.test(t)&&a.includes("EC")){o=!0;break}const n=t.match(/-----BEGIN[\s\S]+?-----[\r\n]+([\s\S]+?)[\r\n]+-----END/);if(!n)return{type:"unknown",format:"pem",isPrivateKey:r,confidence:"certain"};const s=n[1].replace(/\s/g,"");try{const e=globalThis.Buffer.from(s,"base64"),t=this.detectFromBytes(new Uint8Array(e),"der");return"unknown"===t.type&&o?{type:"ecdsa",format:"pem",isPrivateKey:r,rawBytes:e,confidence:"certain"}:{...t,format:"pem"}}catch{return{type:"unknown",format:"pem",isPrivateKey:r,confidence:"certain"}}}static tryCreateKey(e){try{if("string"==typeof e){let t=e.trim();if(t.toLowerCase().startsWith("0x")&&(t=t.substring(2)),this.isValidHex(t)&&64===t.length){const e=this.hexToBytes(t),r=this.detectBySignature(t);return"unknown"!==r.type?{type:r.type,format:"hex",isPrivateKey:!0,rawBytes:e,confidence:r.confidence,warning:r.warning}:{type:"unknown",format:"hex",isPrivateKey:!1,rawBytes:e,confidence:"certain"}}}}catch{}return{type:"unknown",format:"hex",isPrivateKey:!1,rawBytes:new Uint8Array,confidence:"certain"}}static detectBySignature(e){const t=BigInt("0x"+e),r=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141");if(0n===t)return{type:"ed25519",confidence:"certain"};if(t>=r)return{type:"ed25519",confidence:"certain"};let o=!1,n=!1;try{const t=i.PrivateKey.fromStringED25519(e),r=new Uint8Array([1,2,3,4,5]),n=t.sign(r);t.publicKey.verify(r,n)&&(o=!0)}catch{}try{const t=i.PrivateKey.fromStringECDSA(e),r=new Uint8Array([1,2,3,4,5]),o=t.sign(r);t.publicKey.verify(r,o)&&(n=!0)}catch{}if(o&&n){const t=this.hexToBytes(e);if(168===t[0]&&1===t[1])return{type:"ed25519",confidence:"uncertain",warning:"Detection based on byte pattern heuristic. Both ED25519 and ECDSA accept this key."};let r=0;for(const e of t)e>=128&&r++;const i=r/t.length;return i>=.4&&i<=.6?{type:"ecdsa",confidence:"uncertain",warning:"Detection based on entropy heuristic. Both ED25519 and ECDSA accept this key."}:{type:"ecdsa",confidence:"uncertain",warning:"Detection based on entropy heuristic. Both ED25519 and ECDSA accept this key. Defaulting to ECDSA."}}return o&&!n?{type:"ed25519",confidence:"certain"}:n&&!o?{type:"ecdsa",confidence:"certain"}:{type:"unknown",confidence:"certain"}}static isValidHex(e){return/^[0-9a-fA-F]+$/.test(e)&&e.length%2==0}static isBase64(e){try{return globalThis.Buffer.from(e,"base64").toString("base64")===e}catch{return!1}}static hexToBytes(e){const t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=parseInt(e.substr(r,2),16);return t}static hasPrefix(e,t){if(e.length<t.length)return!1;for(let r=0;r<t.length;r++)if(e[r]!==t[r])return!1;return!0}static containsECDSAPrivateKeyPattern(e){for(let t=0;t<e.length-7;t++)if(48===e[t]&&116===e[t+1]&&2===e[t+2]&&1===e[t+3]&&1===e[t+4]&&4===e[t+5]&&32===e[t+6])return!0;return!1}static extractECDSAPrivateKey(e){for(let t=0;t<e.length-32;t++)if(4===e[t]&&32===e[t+1])return e.slice(t+2,t+34);return e}};te.ED25519_PUBLIC_KEY_LENGTH=32,te.ED25519_EXPANDED_PRIVATE_KEY_LENGTH=64,te.ED25519_PUBLIC_KEY_PREFIX=globalThis.Buffer.from([48,42,48,5,6,3,43,101,112,3,33,0]),te.ED25519_PRIVATE_KEY_PREFIX=globalThis.Buffer.from([48,46,2,1,0,48,5,6,3,43,101,112,4,34,4,32]),te.ECDSA_SECP256K1_PUBLIC_KEY_PREFIX=globalThis.Buffer.from([48,86,48,16,6,7,42,134,72,206,61,2,1,6,5,43,129,4,0,10,3,66,0]),te.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX=globalThis.Buffer.from([48,116,2,1,1,4,32]),te.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_SHORT=globalThis.Buffer.from([48,48,2,1,0,48,7,6,5,43,129,4,0,10,4,34,4,32]),te.ECDSA_SECP256K1_PRIVATE_KEY_PREFIX_LONG=globalThis.Buffer.from([48,119,2,1,1,4,32]);let re=te;function ie(e){const t=re.detect(e);if("unknown"!==t.type)try{const r="ecdsa"===t.type?i.PrivateKey.fromStringECDSA(e):i.PrivateKey.fromStringED25519(e),o={detectedType:t.type,privateKey:r};return"uncertain"===t.confidence&&(o.warning="Key type detection is uncertain. If you have the associated account ID, consider using the Hedera mirror node to confirm the key type."),o}catch(r){}try{return{detectedType:"ecdsa",privateKey:i.PrivateKey.fromStringECDSA(e),warning:"Using ECDSA as default. If you have the associated account ID, consider using the Hedera mirror node to confirm the key type."}}catch(o){try{return{detectedType:"ed25519",privateKey:i.PrivateKey.fromStringED25519(e),warning:"Using ED25519 as fallback. If you have the associated account ID, consider using the Hedera mirror node to confirm the key type."}}catch(n){throw new Error(`Failed to parse private key as either ECDSA or ED25519: ${o}`)}}}class oe{constructor(e){this.mirror=e.mirrorNode,this.logger=e.logger}bestGuessOperatorKey(e,t){if("string"!=typeof e)return{keyType:t||"ecdsa",privateKey:e};if(t){return{keyType:t,privateKey:"ed25519"===t?i.PrivateKey.fromStringED25519(e):i.PrivateKey.fromStringECDSA(e)}}try{const t=ie(e);return{keyType:t.detectedType,privateKey:t.privateKey}}catch{return{keyType:"ecdsa",privateKey:i.PrivateKey.fromStringECDSA(e)}}}async resolveOperatorKey(e,t,r){if("string"!=typeof t)return{keyType:r||"ecdsa",privateKey:t};if(r){return{keyType:r,privateKey:"ed25519"===r?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t)}}const o="string"==typeof e?e:e.toString();try{const e=await this.mirror.requestAccount(o),r=(e?.key?._type||"").includes("ED25519")?"ed25519":"ecdsa";return{keyType:r,privateKey:"ed25519"===r?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t)}}catch{return this.logger.warn("Mirror node key detection failed; using local detection or default ECDSA"),this.bestGuessOperatorKey(t)}}async resolveSupplyKey(e,t,r,o){try{const n=await this.mirror.getTokenInfo(e),s=n?.supply_key?._type||"";return"string"!=typeof t?t:o?"ed25519"===o?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t):s.includes("ED25519")?i.PrivateKey.fromStringED25519(t):s.includes("ECDSA")?i.PrivateKey.fromStringECDSA(t):"ed25519"===r?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t)}catch{return"string"!=typeof t?t:o?"ed25519"===o?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t):"ed25519"===r?i.PrivateKey.fromStringED25519(t):i.PrivateKey.fromStringECDSA(t)}}}function ne(e){const t="string"==typeof e.operatorId?i.AccountId.fromString(e.operatorId):e.operatorId,r=e.client?e.client:"mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet(),o=new oe({mirrorNode:e.mirrorNode,logger:e.logger});let n,s;const a=o.bestGuessOperatorKey(e.operatorKey,e.keyType);n=a.keyType,s=a.privateKey,r.setOperator(t.toString(),s);const c=(async()=>{try{const i=await o.resolveOperatorKey(t,e.operatorKey,e.keyType);n=i.keyType,s=i.privateKey,r.setOperator(t.toString(),s)}catch{}})();return{client:r,operatorId:t,get operatorKey(){return s},get keyType(){return n},ensureInitialized:async()=>{await c}}}for(var se=Object.defineProperty,ae=((e,t,r)=>((e,t,r)=>t in e?se(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r)(e,"symbol"!=typeof t?t+"":t,r)),ce={},le={byteLength:function(e){var t=me(e),r=t[0],i=t[1];return 3*(r+i)/4-i},toByteArray:function(e){var t,r,i=me(e),o=i[0],n=i[1],s=new pe(function(e,t,r){return 3*(t+r)/4-r}(0,o,n)),a=0,c=n>0?o-4:o;for(r=0;r<c;r+=4)t=ue[e.charCodeAt(r)]<<18|ue[e.charCodeAt(r+1)]<<12|ue[e.charCodeAt(r+2)]<<6|ue[e.charCodeAt(r+3)],s[a++]=t>>16&255,s[a++]=t>>8&255,s[a++]=255&t;2===n&&(t=ue[e.charCodeAt(r)]<<2|ue[e.charCodeAt(r+1)]>>4,s[a++]=255&t);1===n&&(t=ue[e.charCodeAt(r)]<<10|ue[e.charCodeAt(r+1)]<<4|ue[e.charCodeAt(r+2)]>>2,s[a++]=t>>8&255,s[a++]=255&t);return s},fromByteArray:function(e){for(var t,r=e.length,i=r%3,o=[],n=16383,s=0,a=r-i;s<a;s+=n)o.push(ye(e,s,s+n>a?a:s+n));1===i?(t=e[r-1],o.push(de[t>>2]+de[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],o.push(de[t>>10]+de[t>>4&63]+de[t<<2&63]+"="));return o.join("")}},de=[],ue=[],pe="undefined"!=typeof Uint8Array?Uint8Array:Array,he="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ge=0;ge<64;++ge)de[ge]=he[ge],ue[he.charCodeAt(ge)]=ge;function me(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=e.indexOf("=");return-1===r&&(r=t),[r,r===t?0:4-r%4]}function fe(e){return de[e>>18&63]+de[e>>12&63]+de[e>>6&63]+de[63&e]}function ye(e,t,r){for(var i,o=[],n=t;n<r;n+=3)i=(e[n]<<16&16711680)+(e[n+1]<<8&65280)+(255&e[n+2]),o.push(fe(i));return o.join("")}ue["-".charCodeAt(0)]=62,ue["_".charCodeAt(0)]=63;var be={
|
|
2
2
|
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
|
|
3
3
|
read:function(e,t,r,i,o){var n,s,a=8*o-i-1,c=(1<<a)-1,l=c>>1,d=-7,u=r?o-1:0,p=r?-1:1,h=e[t+u];for(u+=p,n=h&(1<<-d)-1,h>>=-d,d+=a;d>0;n=256*n+e[t+u],u+=p,d-=8);for(s=n&(1<<-d)-1,n>>=-d,d+=i;d>0;s=256*s+e[t+u],u+=p,d-=8);if(0===n)n=1-l;else{if(n===c)return s?NaN:1/0*(h?-1:1);s+=Math.pow(2,i),n-=l}return(h?-1:1)*s*Math.pow(2,n-i)},write:function(e,t,r,i,o,n){var s,a,c,l=8*n-o-1,d=(1<<l)-1,u=d>>1,p=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,h=i?0:n-1,g=i?1:-1,m=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,s=d):(s=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-s))<1&&(s--,c*=2),(t+=s+u>=1?p/c:p*Math.pow(2,1-u))*c>=2&&(s++,c/=2),s+u>=d?(a=0,s=d):s+u>=1?(a=(t*c-1)*Math.pow(2,o),s+=u):(a=t*Math.pow(2,u-1)*Math.pow(2,o),s=0));o>=8;e[r+h]=255&a,h+=g,a/=256,o-=8);for(s=s<<o|a,l+=o;l>0;e[r+h]=255&s,h+=g,s/=256,l-=8);e[r+h-g]|=128*m}};
|
|
4
4
|
/*!
|
|
@@ -7,5 +7,5 @@ read:function(e,t,r,i,o){var n,s,a=8*o-i-1,c=(1<<a)-1,l=c>>1,d=-7,u=r?o-1:0,p=r?
|
|
|
7
7
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
8
8
|
* @license MIT
|
|
9
9
|
*/
|
|
10
|
-
!function(e){const t=ce,r=ye,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 o=2147483647;e.kMaxLength=o;const{Uint8Array:n,ArrayBuffer:s,SharedArrayBuffer:a}=globalThis;function c(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new n(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 d(e,t,r)}function d(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 o=i.write(e,t);o!==r&&(i=i.slice(0,o));return i}(e,t);if(s.isView(e))return function(e){if(Y(e,n)){const t=new n(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(Y(e,s)||e&&Y(e.buffer,s))return g(e,t,r);if(void 0!==a&&(Y(e,a)||e&&Y(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 o=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||X(e.length)?c(0):h(e);if("Buffer"===e.type&&Array.isArray(e.data))return h(e.data)}(e);if(o)return o;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 u(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 u(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 n(e):void 0===r?new n(e,t):new n(e,t,r),Object.setPrototypeOf(i,l.prototype),i}function m(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function f(e,t){if(l.isBuffer(e))return e.length;if(s.isView(e)||Y(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 o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return V(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(e).length;default:if(o)return i?-1:V(e).length;t=(""+t).toLowerCase(),o=!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 _(this,t,r);case"utf8":case"utf-8":return C(this,t,r);case"ascii":return R(this,t,r);case"latin1":case"binary":return N(this,t,r);case"base64":return v(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(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,o){if(0===e.length)return-1;if("string"==typeof r?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),X(r=+r)&&(r=o?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)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,o);if("number"==typeof t)return t&=255,"function"==typeof n.prototype.indexOf?o?n.prototype.indexOf.call(e,t,r):n.prototype.lastIndexOf.call(e,t,r):I(e,[t],r,i,o);throw new TypeError("val must be string, number or Buffer")}function I(e,t,r,i,o){let n,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(o){let i=-1;for(n=r;n<a;n++)if(l(e,n)===l(t,-1===i?0:n-i)){if(-1===i&&(i=n),n-i+1===c)return i*s}else-1!==i&&(n-=n-i),i=-1}else for(r+c>a&&(r=a-c),n=r;n>=0;n--){let r=!0;for(let i=0;i<c;i++)if(l(e,n+i)!==l(t,i)){r=!1;break}if(r)return n}return-1}function T(e,t,r,i){r=Number(r)||0;const o=e.length-r;i?(i=Number(i))>o&&(i=o):i=o;const n=t.length;let s;for(i>n/2&&(i=n/2),s=0;s<i;++s){const i=parseInt(t.substr(2*s,2),16);if(X(i))return s;e[r+s]=i}return s}function S(e,t,r,i){return J(V(t,e.length-r),e,r,i)}function k(e,t,r,i){return J(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 E(e,t,r,i){return J(G(t),e,r,i)}function A(e,t,r,i){return J(function(e,t){let r,i,o;const n=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)r=e.charCodeAt(s),i=r>>8,o=r%256,n.push(o),n.push(i);return n}(t,e.length-r),e,r,i)}function v(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 o=t;for(;o<r;){const t=e[o];let n=null,s=t>239?4:t>223?3:t>191?2:1;if(o+s<=r){let r,i,a,c;switch(s){case 1:t<128&&(n=t);break;case 2:r=e[o+1],128==(192&r)&&(c=(31&t)<<6|63&r,c>127&&(n=c));break;case 3:r=e[o+1],i=e[o+2],128==(192&r)&&128==(192&i)&&(c=(15&t)<<12|(63&r)<<6|63&i,c>2047&&(c<55296||c>57343)&&(n=c));break;case 4:r=e[o+1],i=e[o+2],a=e[o+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&&(n=c))}}null===n?(n=65533,s=1):n>65535&&(n-=65536,i.push(n>>>10&1023|55296),n=56320|1023&n),i.push(n),o+=s}return function(e){const t=e.length;if(t<=x)return String.fromCharCode.apply(String,e);let r="",i=0;for(;i<t;)r+=String.fromCharCode.apply(String,e.slice(i,i+=x));return r}(i)}l.TYPED_ARRAY_SUPPORT=function(){try{const e=new n(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,n.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 d(e,t,r)},Object.setPrototypeOf(l.prototype,n.prototype),Object.setPrototypeOf(l,n),l.alloc=function(e,t,r){return function(e,t,r){return u(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(Y(e,n)&&(e=l.from(e,e.offset,e.byteLength)),Y(t,n)&&(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 o=0,n=Math.min(r,i);o<n;++o)if(e[o]!==t[o]){r=e[o],i=t[o];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 o=0;for(r=0;r<e.length;++r){let t=e[r];if(Y(t,n))o+t.length>i.length?(l.isBuffer(t)||(t=l.from(t)),t.copy(i,o)):n.prototype.set.call(i,t,o);else{if(!l.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(i,o)}o+=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,o){if(Y(e,n)&&(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===o&&(o=this.length),t<0||r>e.length||i<0||o>this.length)throw new RangeError("out of range index");if(i>=o&&t>=r)return 0;if(i>=o)return-1;if(t>=r)return 1;if(this===e)return 0;let s=(o>>>=0)-(i>>>=0),a=(r>>>=0)-(t>>>=0);const c=Math.min(s,a),d=this.slice(i,o),u=e.slice(t,r);for(let n=0;n<c;++n)if(d[n]!==u[n]){s=d[n],a=u[n];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 o=this.length-t;if((void 0===r||r>o)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let n=!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 E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,e,t,r);default:if(n)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),n=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const x=4096;function R(e,t,r){let i="";r=Math.min(e.length,r);for(let o=t;o<r;++o)i+=String.fromCharCode(127&e[o]);return i}function N(e,t,r){let i="";r=Math.min(e.length,r);for(let o=t;o<r;++o)i+=String.fromCharCode(e[o]);return i}function _(e,t,r){const i=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>i)&&(r=i);let o="";for(let n=t;n<r;++n)o+=Z[e[n]];return o}function P(e,t,r){const i=e.slice(t,r);let o="";for(let n=0;n<i.length-1;n+=2)o+=String.fromCharCode(i[n]+256*i[n+1]);return o}function F(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,o,n){if(!l.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<n)throw new RangeError('"value" argument is out of bounds');if(r+i>e.length)throw new RangeError("Index out of range")}function z(e,t,r,i,o){H(t,i,o,e,r,7);let n=Number(t&BigInt(4294967295));e[r++]=n,n>>=8,e[r++]=n,n>>=8,e[r++]=n,n>>=8,e[r++]=n;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 D(e,t,r,i,o){H(t,i,o,e,r,7);let n=Number(t&BigInt(4294967295));e[r+7]=n,n>>=8,e[r+6]=n,n>>=8,e[r+5]=n,n>>=8,e[r+4]=n;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 B(e,t,r,i,o,n){if(r+i>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function M(e,t,i,o,n){return t=+t,i>>>=0,n||B(e,0,i,4),r.write(e,t,i,o,23,4),i+4}function U(e,t,i,o,n){return t=+t,i>>>=0,n||B(e,0,i,8),r.write(e,t,i,o,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||F(e,t,this.length);let i=this[e],o=1,n=0;for(;++n<t&&(o*=256);)i+=this[e+n]*o;return i},l.prototype.readUintBE=l.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||F(e,t,this.length);let i=this[e+--t],o=1;for(;t>0&&(o*=256);)i+=this[e+--t]*o;return i},l.prototype.readUint8=l.prototype.readUInt8=function(e,t){return e>>>=0,t||F(e,1,this.length),this[e]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(e,t){return e>>>=0,t||F(e,2,this.length),this[e]|this[e+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(e,t){return e>>>=0,t||F(e,2,this.length),this[e]<<8|this[e+1]},l.prototype.readUint32LE=l.prototype.readUInt32LE=function(e,t){return e>>>=0,t||F(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||F(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},l.prototype.readBigUInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||j(e,this.length-8);const i=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(i)+(BigInt(o)<<BigInt(32))}),l.prototype.readBigUInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||j(e,this.length-8);const i=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(i)<<BigInt(32))+BigInt(o)}),l.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||F(e,t,this.length);let i=this[e],o=1,n=0;for(;++n<t&&(o*=256);)i+=this[e+n]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},l.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||F(e,t,this.length);let i=t,o=1,n=this[e+--i];for(;i>0&&(o*=256);)n+=this[e+--i]*o;return o*=128,n>=o&&(n-=Math.pow(2,8*t)),n},l.prototype.readInt8=function(e,t){return e>>>=0,t||F(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},l.prototype.readInt16LE=function(e,t){e>>>=0,t||F(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||F(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||F(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||F(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},l.prototype.readBigInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||j(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=Q(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||j(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||F(e,4,this.length),r.read(this,e,!0,23,4)},l.prototype.readFloatBE=function(e,t){return e>>>=0,t||F(e,4,this.length),r.read(this,e,!1,23,4)},l.prototype.readDoubleLE=function(e,t){return e>>>=0,t||F(e,8,this.length),r.read(this,e,!0,52,8)},l.prototype.readDoubleBE=function(e,t){return e>>>=0,t||F(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 o=1,n=0;for(this[t]=255&e;++n<r&&(o*=256);)this[t+n]=e/o&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 o=r-1,n=1;for(this[t+o]=255&e;--o>=0&&(n*=256);)this[t+o]=e/n&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=Q(function(e,t=0){return z(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeBigUInt64BE=Q(function(e,t=0){return D(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 o=0,n=1,s=0;for(this[t]=255&e;++o<r&&(n*=256);)e<0&&0===s&&0!==this[t+o-1]&&(s=1),this[t+o]=(e/n|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 o=r-1,n=1,s=0;for(this[t+o]=255&e;--o>=0&&(n*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/n|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=Q(function(e,t=0){return z(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeBigInt64BE=Q(function(e,t=0){return D(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeFloatLE=function(e,t,r){return M(this,e,t,!0,r)},l.prototype.writeFloatBE=function(e,t,r){return M(this,e,t,!1,r)},l.prototype.writeDoubleLE=function(e,t,r){return U(this,e,t,!0,r)},l.prototype.writeDoubleBE=function(e,t,r){return U(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 o=i-r;return this===e&&"function"==typeof n.prototype.copyWithin?this.copyWithin(t,r,i):n.prototype.set.call(e,this.subarray(r,i),t),o},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 o;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o<r;++o)this[o]=e;else{const n=l.isBuffer(e)?e:l.from(e,i),s=n.length;if(0===s)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<r-t;++o)this[o+t]=n[o%s]}return this};const K={};function L(e,t,r){K[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 H(e,t,r,i,o,n){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*(n+1)}${r}`:`>= -(2${r} ** ${8*(n+1)-1}${r}) and < 2 ** ${8*(n+1)-1}${r}`,new K.ERR_OUT_OF_RANGE("value",i,e)}!function(e,t,r){q(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||j(t,e.length-(r+1))}(i,o,n)}function q(e,t){if("number"!=typeof e)throw new K.ERR_INVALID_ARG_TYPE(t,"number",e)}function j(e,t,r){if(Math.floor(e)!==e)throw q(e,r),new K.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new K.ERR_BUFFER_OUT_OF_BOUNDS;throw new K.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}L("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),L("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),L("ERR_OUT_OF_RANGE",function(e,t,r){let i=`The value of "${e}" is out of range.`,o=r;return Number.isInteger(r)&&Math.abs(r)>2**32?o=$(String(r)):"bigint"==typeof r&&(o=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(o=$(o)),o+="n"),i+=` It must be ${t}. Received ${o}`,i},RangeError);const W=/[^+/0-9A-Za-z-_]/g;function V(e,t){let r;t=t||1/0;const i=e.length;let o=null;const n=[];for(let s=0;s<i;++s){if(r=e.charCodeAt(s),r>55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&n.push(239,191,189);continue}if(s+1===i){(t-=3)>-1&&n.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&n.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&n.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;n.push(r)}else if(r<2048){if((t-=2)<0)break;n.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;n.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;n.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return n}function G(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(W,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function J(e,t,r,i){let o;for(o=0;o<i&&!(o+r>=t.length||o>=e.length);++o)t[o+r]=e[o];return o}function Y(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function X(e){return e!=e}const Z=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const i=16*r;for(let o=0;o<16;++o)t[i+o]=e[r]+e[o]}return t}();function Q(e){return"undefined"==typeof BigInt?ee:e}function ee(){throw new Error("BigInt not supported")}}(ae);const be=ae.Buffer,we=ae.Buffer,Ie=globalThis||self;function Te(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Se,ke,Ee={exports:{}},Ae=Ee.exports={};function ve(){throw new Error("setTimeout has not been defined")}function Ce(){throw new Error("clearTimeout has not been defined")}function xe(e){if(Se===setTimeout)return setTimeout(e,0);if((Se===ve||!Se)&&setTimeout)return Se=setTimeout,setTimeout(e,0);try{return Se(e,0)}catch(t){try{return Se.call(null,e,0)}catch(r){return Se.call(this,e,0)}}}!function(){try{Se="function"==typeof setTimeout?setTimeout:ve}catch(e){Se=ve}try{ke="function"==typeof clearTimeout?clearTimeout:Ce}catch(e){ke=Ce}}();var Re,Ne=[],_e=!1,Pe=-1;function Fe(){_e&&Re&&(_e=!1,Re.length?Ne=Re.concat(Ne):Pe=-1,Ne.length&&Oe())}function Oe(){if(!_e){var e=xe(Fe);_e=!0;for(var t=Ne.length;t;){for(Re=Ne,Ne=[];++Pe<t;)Re&&Re[Pe].run();Pe=-1,t=Ne.length}Re=null,_e=!1,function(e){if(ke===clearTimeout)return clearTimeout(e);if((ke===Ce||!ke)&&clearTimeout)return ke=clearTimeout,clearTimeout(e);try{return ke(e)}catch(t){try{return ke.call(null,e)}catch(r){return ke.call(this,e)}}}(e)}}function ze(e,t){this.fun=e,this.array=t}function De(){}Ae.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];Ne.push(new ze(e,t)),1!==Ne.length||_e||xe(Oe)},ze.prototype.run=function(){this.fun.apply(null,this.array)},Ae.title="browser",Ae.browser=!0,Ae.env={},Ae.argv=[],Ae.version="",Ae.versions={},Ae.on=De,Ae.addListener=De,Ae.once=De,Ae.off=De,Ae.removeListener=De,Ae.removeAllListeners=De,Ae.emit=De,Ae.prependListener=De,Ae.prependOnceListener=De,Ae.listeners=function(e){return[]},Ae.binding=function(e){throw new Error("process.binding is not supported")},Ae.cwd=function(){return"/"},Ae.chdir=function(e){throw new Error("process.chdir is not supported")},Ae.umask=function(){return 0};const Be=Te(Ee.exports);function Me(e,t){return function(){return e.apply(t,arguments)}}const{toString:Ue}=Object.prototype,{getPrototypeOf:Ke}=Object,{iterator:Le,toStringTag:$e}=Symbol,He=(e=>t=>{const r=Ue.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),qe=e=>(e=e.toLowerCase(),t=>He(t)===e),je=e=>t=>typeof t===e,{isArray:We}=Array,Ve=je("undefined");function Ge(e){return null!==e&&!Ve(e)&&null!==e.constructor&&!Ve(e.constructor)&&Xe(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Je=qe("ArrayBuffer");const Ye=je("string"),Xe=je("function"),Ze=je("number"),Qe=e=>null!==e&&"object"==typeof e,et=e=>{if("object"!==He(e))return!1;const t=Ke(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||$e in e||Le in e)},tt=qe("Date"),rt=qe("File"),it=qe("Blob"),ot=qe("FileList"),nt=qe("URLSearchParams"),[st,at,ct,lt]=["ReadableStream","Request","Response","Headers"].map(qe);function dt(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let i,o;if("object"!=typeof e&&(e=[e]),We(e))for(i=0,o=e.length;i<o;i++)t.call(null,e[i],i,e);else{if(Ge(e))return;const o=r?Object.getOwnPropertyNames(e):Object.keys(e),n=o.length;let s;for(i=0;i<n;i++)s=o[i],t.call(null,e[s],s,e)}}function ut(e,t){if(Ge(e))return null;t=t.toLowerCase();const r=Object.keys(e);let i,o=r.length;for(;o-- >0;)if(i=r[o],t===i.toLowerCase())return i;return null}const pt="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:Ie,ht=e=>!Ve(e)&&e!==pt;const gt=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&Ke(Uint8Array)),mt=qe("HTMLFormElement"),ft=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),yt=qe("RegExp"),bt=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),i={};dt(r,(r,o)=>{let n;!1!==(n=t(r,o,e))&&(i[o]=n||r)}),Object.defineProperties(e,i)};const wt=qe("AsyncFunction"),It=(Tt="function"==typeof setImmediate,St=Xe(pt.postMessage),Tt?setImmediate:St?(kt=`axios@${Math.random()}`,Et=[],pt.addEventListener("message",({source:e,data:t})=>{e===pt&&t===kt&&Et.length&&Et.shift()()},!1),e=>{Et.push(e),pt.postMessage(kt,"*")}):e=>setTimeout(e));var Tt,St,kt,Et;const At="undefined"!=typeof queueMicrotask?queueMicrotask.bind(pt):void 0!==Be&&Be.nextTick||It,vt={isArray:We,isArrayBuffer:Je,isBuffer:Ge,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Xe(e.append)&&("formdata"===(t=He(e))||"object"===t&&Xe(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Je(e.buffer),t},isString:Ye,isNumber:Ze,isBoolean:e=>!0===e||!1===e,isObject:Qe,isPlainObject:et,isEmptyObject:e=>{if(!Qe(e)||Ge(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(t){return!1}},isReadableStream:st,isRequest:at,isResponse:ct,isHeaders:lt,isUndefined:Ve,isDate:tt,isFile:rt,isBlob:it,isRegExp:yt,isFunction:Xe,isStream:e=>Qe(e)&&Xe(e.pipe),isURLSearchParams:nt,isTypedArray:gt,isFileList:ot,forEach:dt,merge:function e(){const{caseless:t}=ht(this)&&this||{},r={},i=(i,o)=>{const n=t&&ut(r,o)||o;et(r[n])&&et(i)?r[n]=e(r[n],i):et(i)?r[n]=e({},i):We(i)?r[n]=i.slice():r[n]=i};for(let o=0,n=arguments.length;o<n;o++)arguments[o]&&dt(arguments[o],i);return r},extend:(e,t,r,{allOwnKeys:i}={})=>(dt(t,(t,i)=>{r&&Xe(t)?e[i]=Me(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 o,n,s;const a={};if(t=t||{},null==e)return t;do{for(o=Object.getOwnPropertyNames(e),n=o.length;n-- >0;)s=o[n],i&&!i(s,e,t)||a[s]||(t[s]=e[s],a[s]=!0);e=!1!==r&&Ke(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:He,kindOfTest:qe,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(We(e))return e;let t=e.length;if(!Ze(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[Le]).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:mt,hasOwnProperty:ft,hasOwnProp:ft,reduceDescriptors:bt,freezeMethods:e=>{bt(e,(t,r)=>{if(Xe(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const i=e[r];Xe(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 We(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:ut,global:pt,isContextDefined:ht,isSpecCompliantForm:function(e){return!!(e&&Xe(e.append)&&"FormData"===e[$e]&&e[Le])},toJSONObject:e=>{const t=new Array(10),r=(e,i)=>{if(Qe(e)){if(t.indexOf(e)>=0)return;if(Ge(e))return e;if(!("toJSON"in e)){t[i]=e;const o=We(e)?[]:{};return dt(e,(e,t)=>{const n=r(e,i+1);!Ve(n)&&(o[t]=n)}),t[i]=void 0,o}}return e};return r(e,0)},isAsyncFn:wt,isThenable:e=>e&&(Qe(e)||Xe(e))&&Xe(e.then)&&Xe(e.catch),setImmediate:It,asap:At,isIterable:e=>null!=e&&Xe(e[Le])};function Ct(e,t,r,i,o){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),o&&(this.response=o,this.status=o.status?o.status:null)}vt.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:vt.toJSONObject(this.config),code:this.code,status:this.status}}});const xt=Ct.prototype,Rt={};["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=>{Rt[e]={value:e}}),Object.defineProperties(Ct,Rt),Object.defineProperty(xt,"isAxiosError",{value:!0}),Ct.from=(e,t,r,i,o,n)=>{const s=Object.create(xt);return vt.toFlatObject(e,s,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),Ct.call(s,e.message,t,r,i,o),s.cause=e,s.name=e.name,n&&Object.assign(s,n),s};function Nt(e){return vt.isPlainObject(e)||vt.isArray(e)}function _t(e){return vt.endsWith(e,"[]")?e.slice(0,-2):e}function Pt(e,t,r){return e?e.concat(t).map(function(e,t){return e=_t(e),!r&&t?"["+e+"]":e}).join(r?".":""):t}const Ft=vt.toFlatObject(vt,{},null,function(e){return/^is[A-Z]/.test(e)});function Ot(e,t,r){if(!vt.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const i=(r=vt.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!vt.isUndefined(t[e])})).metaTokens,o=r.visitor||l,n=r.dots,s=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&vt.isSpecCompliantForm(t);if(!vt.isFunction(o))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(vt.isDate(e))return e.toISOString();if(vt.isBoolean(e))return e.toString();if(!a&&vt.isBlob(e))throw new Ct("Blob is not supported. Use a Buffer instead.");return vt.isArrayBuffer(e)||vt.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):be.from(e):e}function l(e,r,o){let a=e;if(e&&!o&&"object"==typeof e)if(vt.endsWith(r,"{}"))r=i?r:r.slice(0,-2),e=JSON.stringify(e);else if(vt.isArray(e)&&function(e){return vt.isArray(e)&&!e.some(Nt)}(e)||(vt.isFileList(e)||vt.endsWith(r,"[]"))&&(a=vt.toArray(e)))return r=_t(r),a.forEach(function(e,i){!vt.isUndefined(e)&&null!==e&&t.append(!0===s?Pt([r],i,n):null===s?r:r+"[]",c(e))}),!1;return!!Nt(e)||(t.append(Pt(o,r,n),c(e)),!1)}const d=[],u=Object.assign(Ft,{defaultVisitor:l,convertValue:c,isVisitable:Nt});if(!vt.isObject(e))throw new TypeError("data must be an object");return function e(r,i){if(!vt.isUndefined(r)){if(-1!==d.indexOf(r))throw Error("Circular reference detected in "+i.join("."));d.push(r),vt.forEach(r,function(r,n){!0===(!(vt.isUndefined(r)||null===r)&&o.call(t,r,vt.isString(n)?n.trim():n,i,u))&&e(r,i?i.concat(n):[n])}),d.pop()}}(e),t}function zt(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function Dt(e,t){this._pairs=[],e&&Ot(e,this,t)}const Bt=Dt.prototype;function Mt(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Ut(e,t,r){if(!t)return e;const i=r&&r.encode||Mt;vt.isFunction(r)&&(r={serialize:r});const o=r&&r.serialize;let n;if(n=o?o(t,r):vt.isURLSearchParams(t)?t.toString():new Dt(t,r).toString(i),n){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+n}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,zt)}:zt;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class Kt{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){vt.forEach(this.handlers,function(t){null!==t&&e(t)})}}const Lt={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},$t={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Dt,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},Ht="undefined"!=typeof window&&"undefined"!=typeof document,qt="object"==typeof navigator&&navigator||void 0,jt=Ht&&(!qt||["ReactNative","NativeScript","NS"].indexOf(qt.product)<0),Wt="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Vt=Ht&&window.location.href||"http://localhost",Gt={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Ht,hasStandardBrowserEnv:jt,hasStandardBrowserWebWorkerEnv:Wt,navigator:qt,origin:Vt},Symbol.toStringTag,{value:"Module"})),...$t};function Jt(e){function t(e,r,i,o){let n=e[o++];if("__proto__"===n)return!0;const s=Number.isFinite(+n),a=o>=e.length;if(n=!n&&vt.isArray(i)?i.length:n,a)return vt.hasOwnProp(i,n)?i[n]=[i[n],r]:i[n]=r,!s;i[n]&&vt.isObject(i[n])||(i[n]=[]);return t(e,r,i[n],o)&&vt.isArray(i[n])&&(i[n]=function(e){const t={},r=Object.keys(e);let i;const o=r.length;let n;for(i=0;i<o;i++)n=r[i],t[n]=e[n];return t}(i[n])),!s}if(vt.isFormData(e)&&vt.isFunction(e.entries)){const r={};return vt.forEachEntry(e,(e,i)=>{t(function(e){return vt.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),i,r,0)}),r}return null}const Yt={transitional:Lt,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",i=r.indexOf("application/json")>-1,o=vt.isObject(e);o&&vt.isHTMLForm(e)&&(e=new FormData(e));if(vt.isFormData(e))return i?JSON.stringify(Jt(e)):e;if(vt.isArrayBuffer(e)||vt.isBuffer(e)||vt.isStream(e)||vt.isFile(e)||vt.isBlob(e)||vt.isReadableStream(e))return e;if(vt.isArrayBufferView(e))return e.buffer;if(vt.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let n;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return Ot(e,new Gt.classes.URLSearchParams,{visitor:function(e,t,r,i){return Gt.isNode&&vt.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}(e,this.formSerializer).toString();if((n=vt.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return Ot(n?{"files[]":e}:e,t&&new t,this.formSerializer)}}return o||i?(t.setContentType("application/json",!1),function(e,t,r){if(vt.isString(e))try{return(t||JSON.parse)(e),vt.trim(e)}catch(i){if("SyntaxError"!==i.name)throw i}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Yt.transitional,r=t&&t.forcedJSONParsing,i="json"===this.responseType;if(vt.isResponse(e)||vt.isReadableStream(e))return e;if(e&&vt.isString(e)&&(r&&!this.responseType||i)){const r=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(o){if(r){if("SyntaxError"===o.name)throw Ct.from(o,Ct.ERR_BAD_RESPONSE,this,null,this.response);throw o}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Gt.classes.FormData,Blob:Gt.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};vt.forEach(["delete","get","head","post","put","patch"],e=>{Yt.headers[e]={}});const Xt=vt.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"]),Zt=Symbol("internals");function Qt(e){return e&&String(e).trim().toLowerCase()}function er(e){return!1===e||null==e?e:vt.isArray(e)?e.map(er):String(e)}function tr(e,t,r,i,o){return vt.isFunction(i)?i.call(this,t,r):(o&&(t=r),vt.isString(t)?vt.isString(i)?-1!==t.indexOf(i):vt.isRegExp(i)?i.test(t):void 0:void 0)}let rr=class{constructor(e){e&&this.set(e)}set(e,t,r){const i=this;function o(e,t,r){const o=Qt(t);if(!o)throw new Error("header name must be a non-empty string");const n=vt.findKey(i,o);(!n||void 0===i[n]||!0===r||void 0===r&&!1!==i[n])&&(i[n||t]=er(e))}const n=(e,t)=>vt.forEach(e,(e,r)=>o(e,r,t));if(vt.isPlainObject(e)||e instanceof this.constructor)n(e,t);else if(vt.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))n((e=>{const t={};let r,i,o;return e&&e.split("\n").forEach(function(e){o=e.indexOf(":"),r=e.substring(0,o).trim().toLowerCase(),i=e.substring(o+1).trim(),!r||t[r]&&Xt[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(vt.isObject(e)&&vt.isIterable(e)){let r,i,o={};for(const t of e){if(!vt.isArray(t))throw TypeError("Object iterator must return a key-value pair");o[i=t[0]]=(r=o[i])?vt.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}n(o,t)}else null!=e&&o(t,e,r);return this}get(e,t){if(e=Qt(e)){const r=vt.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(vt.isFunction(t))return t.call(this,e,r);if(vt.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Qt(e)){const r=vt.findKey(this,e);return!(!r||void 0===this[r]||t&&!tr(0,this[r],r,t))}return!1}delete(e,t){const r=this;let i=!1;function o(e){if(e=Qt(e)){const o=vt.findKey(r,e);!o||t&&!tr(0,r[o],o,t)||(delete r[o],i=!0)}}return vt.isArray(e)?e.forEach(o):o(e),i}clear(e){const t=Object.keys(this);let r=t.length,i=!1;for(;r--;){const o=t[r];e&&!tr(0,this[o],o,e,!0)||(delete this[o],i=!0)}return i}normalize(e){const t=this,r={};return vt.forEach(this,(i,o)=>{const n=vt.findKey(r,o);if(n)return t[n]=er(i),void delete t[o];const s=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,r)=>t.toUpperCase()+r)}(o):String(o).trim();s!==o&&delete t[o],t[s]=er(i),r[s]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return vt.forEach(this,(r,i)=>{null!=r&&!1!==r&&(t[i]=e&&vt.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[Zt]=this[Zt]={accessors:{}}).accessors,r=this.prototype;function i(e){const i=Qt(e);t[i]||(!function(e,t){const r=vt.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+r,{value:function(e,r,o){return this[i].call(this,t,e,r,o)},configurable:!0})})}(r,e),t[i]=!0)}return vt.isArray(e)?e.forEach(i):i(e),this}};function ir(e,t){const r=this||Yt,i=t||r,o=rr.from(i.headers);let n=i.data;return vt.forEach(e,function(e){n=e.call(r,n,o.normalize(),t?t.status:void 0)}),o.normalize(),n}function or(e){return!(!e||!e.__CANCEL__)}function nr(e,t,r){Ct.call(this,null==e?"canceled":e,Ct.ERR_CANCELED,t,r),this.name="CanceledError"}function sr(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)}rr.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),vt.reduceDescriptors(rr.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}}),vt.freezeMethods(rr),vt.inherits(nr,Ct,{__CANCEL__:!0});const ar=(e,t,r=3)=>{let i=0;const o=function(e,t){e=e||10;const r=new Array(e),i=new Array(e);let o,n=0,s=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),l=i[s];o||(o=c),r[n]=a,i[n]=c;let d=s,u=0;for(;d!==n;)u+=r[d++],d%=e;if(n=(n+1)%e,n===s&&(s=(s+1)%e),c-o<t)return;const p=l&&c-l;return p?Math.round(1e3*u/p):void 0}}(50,250);return function(e,t){let r,i,o=0,n=1e3/t;const s=(t,n=Date.now())=>{o=n,r=null,i&&(clearTimeout(i),i=null),e(...t)};return[(...e)=>{const t=Date.now(),a=t-o;a>=n?s(e,t):(r=e,i||(i=setTimeout(()=>{i=null,s(r)},n-a)))},()=>r&&s(r)]}(r=>{const n=r.loaded,s=r.lengthComputable?r.total:void 0,a=n-i,c=o(a);i=n;e({loaded:n,total:s,progress:s?n/s:void 0,bytes:a,rate:c||void 0,estimated:c&&s&&n<=s?(s-n)/c:void 0,event:r,lengthComputable:null!=s,[t?"download":"upload"]:!0})},r)},cr=(e,t)=>{const r=null!=e;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},lr=e=>(...t)=>vt.asap(()=>e(...t)),dr=Gt.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,Gt.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(Gt.origin),Gt.navigator&&/(msie|trident)/i.test(Gt.navigator.userAgent)):()=>!0,ur=Gt.hasStandardBrowserEnv?{write(e,t,r,i,o,n){const s=[e+"="+encodeURIComponent(t)];vt.isNumber(r)&&s.push("expires="+new Date(r).toGMTString()),vt.isString(i)&&s.push("path="+i),vt.isString(o)&&s.push("domain="+o),!0===n&&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 pr(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 hr=e=>e instanceof rr?{...e}:e;function gr(e,t){t=t||{};const r={};function i(e,t,r,i){return vt.isPlainObject(e)&&vt.isPlainObject(t)?vt.merge.call({caseless:i},e,t):vt.isPlainObject(t)?vt.merge({},t):vt.isArray(t)?t.slice():t}function o(e,t,r,o){return vt.isUndefined(t)?vt.isUndefined(e)?void 0:i(void 0,e,0,o):i(e,t,0,o)}function n(e,t){if(!vt.isUndefined(t))return i(void 0,t)}function s(e,t){return vt.isUndefined(t)?vt.isUndefined(e)?void 0:i(void 0,e):i(void 0,t)}function a(r,o,n){return n in t?i(r,o):n in e?i(void 0,r):void 0}const c={url:n,method:n,data:n,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)=>o(hr(e),hr(t),0,!0)};return vt.forEach(Object.keys({...e,...t}),function(i){const n=c[i]||o,s=n(e[i],t[i],i);vt.isUndefined(s)&&n!==a||(r[i]=s)}),r}const mr=e=>{const t=gr({},e);let r,{data:i,withXSRFToken:o,xsrfHeaderName:n,xsrfCookieName:s,headers:a,auth:c}=t;if(t.headers=a=rr.from(a),t.url=Ut(pr(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),vt.isFormData(i))if(Gt.hasStandardBrowserEnv||Gt.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(Gt.hasStandardBrowserEnv&&(o&&vt.isFunction(o)&&(o=o(t)),o||!1!==o&&dr(t.url))){const e=n&&s&&ur.read(s);e&&a.set(n,e)}return t},fr="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,r){const i=mr(e);let o=i.data;const n=rr.from(i.headers).normalize();let s,a,c,l,d,{responseType:u,onUploadProgress:p,onDownloadProgress:h}=i;function g(){l&&l(),d&&d(),i.cancelToken&&i.cancelToken.unsubscribe(s),i.signal&&i.signal.removeEventListener("abort",s)}let m=new XMLHttpRequest;function f(){if(!m)return;const i=rr.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());sr(function(e){t(e),g()},function(e){r(e),g()},{data:u&&"text"!==u&&"json"!==u?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 o=i.transitional||Lt;i.timeoutErrorMessage&&(t=i.timeoutErrorMessage),r(new Ct(t,o.clarifyTimeoutError?Ct.ETIMEDOUT:Ct.ECONNABORTED,e,m)),m=null},void 0===o&&n.setContentType(null),"setRequestHeader"in m&&vt.forEach(n.toJSON(),function(e,t){m.setRequestHeader(t,e)}),vt.isUndefined(i.withCredentials)||(m.withCredentials=!!i.withCredentials),u&&"json"!==u&&(m.responseType=i.responseType),h&&([c,d]=ar(h,!0),m.addEventListener("progress",c)),p&&m.upload&&([a,l]=ar(p),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",l)),(i.cancelToken||i.signal)&&(s=t=>{m&&(r(!t||t.type?new nr(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===Gt.protocols.indexOf(y)?r(new Ct("Unsupported protocol "+y+":",Ct.ERR_BAD_REQUEST,e)):m.send(o||null)})},yr=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,i=new AbortController;const o=function(e){if(!r){r=!0,s();const t=e instanceof Error?e:this.reason;i.abort(t instanceof Ct?t:new nr(t instanceof Error?t.message:t))}};let n=t&&setTimeout(()=>{n=null,o(new Ct(`timeout ${t} of ms exceeded`,Ct.ETIMEDOUT))},t);const s=()=>{e&&(n&&clearTimeout(n),n=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(o):e.removeEventListener("abort",o)}),e=null)};e.forEach(e=>e.addEventListener("abort",o));const{signal:a}=i;return a.unsubscribe=()=>vt.asap(s),a}},br=function*(e,t){let r=e.byteLength;if(r<t)return void(yield e);let i,o=0;for(;o<r;)i=o+t,yield e.slice(o,i),o=i},wr=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()}},Ir=(e,t,r,i)=>{const o=async function*(e,t){for await(const r of wr(e))yield*br(r,t)}(e,t);let n,s=0,a=e=>{n||(n=!0,i&&i(e))};return new ReadableStream({async pull(e){try{const{done:t,value:i}=await o.next();if(t)return a(),void e.close();let n=i.byteLength;if(r){let e=s+=n;r(e)}e.enqueue(new Uint8Array(i))}catch(t){throw a(t),t}},cancel:e=>(a(e),o.return())},{highWaterMark:2})},Tr="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,Sr=Tr&&"function"==typeof ReadableStream,kr=Tr&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),Er=(e,...t)=>{try{return!!e(...t)}catch(r){return!1}},Ar=Sr&&Er(()=>{let e=!1;const t=new Request(Gt.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),vr=Sr&&Er(()=>vt.isReadableStream(new Response("").body)),Cr={stream:vr&&(e=>e.body)};var xr;Tr&&(xr=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!Cr[e]&&(Cr[e]=vt.isFunction(xr[e])?t=>t[e]():(t,r)=>{throw new Ct(`Response type '${e}' is not supported`,Ct.ERR_NOT_SUPPORT,r)})}));const Rr=async(e,t)=>{const r=vt.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(vt.isBlob(e))return e.size;if(vt.isSpecCompliantForm(e)){const t=new Request(Gt.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return vt.isArrayBufferView(e)||vt.isArrayBuffer(e)?e.byteLength:(vt.isURLSearchParams(e)&&(e+=""),vt.isString(e)?(await kr(e)).byteLength:void 0)})(t):r},Nr={http:null,xhr:fr,fetch:Tr&&(async e=>{let{url:t,method:r,data:i,signal:o,cancelToken:n,timeout:s,onDownloadProgress:a,onUploadProgress:c,responseType:l,headers:d,withCredentials:u="same-origin",fetchOptions:p}=mr(e);l=l?(l+"").toLowerCase():"text";let h,g=yr([o,n&&n.toAbortSignal()],s);const m=g&&g.unsubscribe&&(()=>{g.unsubscribe()});let f;try{if(c&&Ar&&"get"!==r&&"head"!==r&&0!==(f=await Rr(d,i))){let e,r=new Request(t,{method:"POST",body:i,duplex:"half"});if(vt.isFormData(i)&&(e=r.headers.get("content-type"))&&d.setContentType(e),r.body){const[e,t]=cr(f,ar(lr(c)));i=Ir(r.body,65536,e,t)}}vt.isString(u)||(u=u?"include":"omit");const o="credentials"in Request.prototype;h=new Request(t,{...p,signal:g,method:r.toUpperCase(),headers:d.normalize().toJSON(),body:i,duplex:"half",credentials:o?u:void 0});let n=await fetch(h,p);const s=vr&&("stream"===l||"response"===l);if(vr&&(a||s&&m)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=n[t]});const t=vt.toFiniteNumber(n.headers.get("content-length")),[r,i]=a&&cr(t,ar(lr(a),!0))||[];n=new Response(Ir(n.body,65536,r,()=>{i&&i(),m&&m()}),e)}l=l||"text";let y=await Cr[vt.findKey(Cr,l)||"text"](n,e);return!s&&m&&m(),await new Promise((t,r)=>{sr(t,r,{data:y,headers:rr.from(n.headers),status:n.status,statusText:n.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)}})};vt.forEach(Nr,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(r){}Object.defineProperty(e,"adapterName",{value:t})}});const _r=e=>`- ${e}`,Pr=e=>vt.isFunction(e)||null===e||!1===e,Fr=e=>{e=vt.isArray(e)?e:[e];const{length:t}=e;let r,i;const o={};for(let n=0;n<t;n++){let t;if(r=e[n],i=r,!Pr(r)&&(i=Nr[(t=String(r)).toLowerCase()],void 0===i))throw new Ct(`Unknown adapter '${t}'`);if(i)break;o[t||"#"+n]=i}if(!i){const e=Object.entries(o).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(_r).join("\n"):" "+_r(e[0]):"as no adapter specified"),"ERR_NOT_SUPPORT")}return i};function Or(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new nr(null,e)}function zr(e){Or(e),e.headers=rr.from(e.headers),e.data=ir.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Fr(e.adapter||Yt.adapter)(e).then(function(t){return Or(e),t.data=ir.call(e,e.transformResponse,t),t.headers=rr.from(t.headers),t},function(t){return or(t)||(Or(e),t&&t.response&&(t.response.data=ir.call(e,e.transformResponse,t.response),t.response.headers=rr.from(t.response.headers))),Promise.reject(t)})}const Dr="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 Mr={};Br.transitional=function(e,t,r){function i(e,t){return"[Axios v"+Dr+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,o,n)=>{if(!1===e)throw new Ct(i(o," has been removed"+(t?" in "+t:"")),Ct.ERR_DEPRECATED);return t&&!Mr[o]&&(Mr[o]=!0,console.warn(i(o," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,o,n)}},Br.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};const Ur={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 o=i.length;for(;o-- >0;){const n=i[o],s=t[n];if(s){const t=e[n],r=void 0===t||s(t,n,e);if(!0!==r)throw new Ct("option "+n+" must be "+r,Ct.ERR_BAD_OPTION_VALUE);continue}if(!0!==r)throw new Ct("Unknown option "+n,Ct.ERR_BAD_OPTION)}},validators:Br},Kr=Ur.validators;let Lr=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Kt,response:new Kt}}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=gr(this.defaults,t);const{transitional:r,paramsSerializer:i,headers:o}=t;void 0!==r&&Ur.assertOptions(r,{silentJSONParsing:Kr.transitional(Kr.boolean),forcedJSONParsing:Kr.transitional(Kr.boolean),clarifyTimeoutError:Kr.transitional(Kr.boolean)},!1),null!=i&&(vt.isFunction(i)?t.paramsSerializer={serialize:i}:Ur.assertOptions(i,{encode:Kr.function,serialize:Kr.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Ur.assertOptions(t,{baseUrl:Kr.spelling("baseURL"),withXsrfToken:Kr.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let n=o&&vt.merge(o.common,o[t.method]);o&&vt.forEach(["delete","get","head","post","put","patch","common"],e=>{delete o[e]}),t.headers=rr.concat(n,o);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 d,u=0;if(!a){const e=[zr.bind(this),void 0];for(e.unshift(...s),e.push(...c),d=e.length,l=Promise.resolve(t);u<d;)l=l.then(e[u++],e[u++]);return l}d=s.length;let p=t;for(u=0;u<d;){const e=s[u++],t=s[u++];try{p=e(p)}catch(h){t.call(this,h);break}}try{l=zr.call(this,p)}catch(h){return Promise.reject(h)}for(u=0,d=c.length;u<d;)l=l.then(c[u++],c[u++]);return l}getUri(e){return Ut(pr((e=gr(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};vt.forEach(["delete","get","head","options"],function(e){Lr.prototype[e]=function(t,r){return this.request(gr(r||{},{method:e,url:t,data:(r||{}).data}))}}),vt.forEach(["post","put","patch"],function(e){function t(t){return function(r,i,o){return this.request(gr(o||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:i}))}}Lr.prototype[e]=t(),Lr.prototype[e+"Form"]=t(!0)});const $r={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($r).forEach(([e,t])=>{$r[t]=e});const Hr=function e(t){const r=new Lr(t),i=Me(Lr.prototype.request,r);return vt.extend(i,Lr.prototype,r,{allOwnKeys:!0}),vt.extend(i,r,null,{allOwnKeys:!0}),i.create=function(r){return e(gr(t,r))},i}(Yt);Hr.Axios=Lr,Hr.CanceledError=nr,Hr.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,o){r.reason||(r.reason=new nr(e,i,o),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}}},Hr.isCancel=or,Hr.VERSION=Dr,Hr.toFormData=Ot,Hr.AxiosError=Ct,Hr.Cancel=Hr.CanceledError,Hr.all=function(e){return Promise.all(e)},Hr.spread=function(e){return function(t){return e.apply(null,t)}},Hr.isAxiosError=function(e){return vt.isObject(e)&&!0===e.isAxiosError},Hr.mergeConfig=gr,Hr.AxiosHeaders=rr,Hr.formToJSON=e=>Jt(vt.isHTMLForm(e)?new FormData(e):e),Hr.getAdapter=Fr,Hr.HttpStatusCode=$r,Hr.default=Hr;const{Axios:qr,AxiosError:jr,CanceledError:Wr,isCancel:Vr,CancelToken:Gr,VERSION:Jr,all:Yr,Cancel:Xr,isAxiosError:Zr,spread:Qr,toFormData:ei,AxiosHeaders:ti,HttpStatusCode:ri,formToJSON:ii,getAdapter:oi,mergeConfig:ni}=Hr,si=class e{constructor(){se(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)}};se(si,"instance");let ai=si;class ci extends Error{constructor(e){super(e),this.name="ValidationError"}}class li{constructor(e){if(se(this,"accountId"),se(this,"privateKey"),se(this,"baseUrl"),se(this,"network"),this.accountId=e.accountId,"string"==typeof e.privateKey){const t=s.detectKeyTypeFromString(e.privateKey);this.privateKey=t.privateKey}else this.privateKey=e.privateKey;this.network=e.network||"mainnet",this.baseUrl=e.baseUrl||"https://kiloscribe.com"}async authenticate(){var e,t,r;const i=await Hr.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 o=i.data.message,n=await this.signMessage(o),s=await Hr.post(`${this.baseUrl}/api/auth/authenticate`,{authData:{id:this.accountId,signature:n,data:o,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 we.from(r).toString("hex")}}class di{constructor(e){se(this,"accountId"),se(this,"signer"),se(this,"baseUrl"),se(this,"network"),se(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 Hr.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 o=i.data.message,n=await this.signMessage(JSON.stringify(o)),s=await Hr.post(`${this.baseUrl}/api/auth/authenticate`,{authData:{id:this.accountId,signature:n,data:o,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 we.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 ui(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function pi(e){return new DataView(e.buffer,e.byteOffset)}const hi={len:1,get:(e,t)=>pi(e).getUint8(t),put:(e,t,r)=>(pi(e).setUint8(t,r),t+1)},gi={len:2,get:(e,t)=>pi(e).getUint16(t,!0),put:(e,t,r)=>(pi(e).setUint16(t,r,!0),t+2)},mi={len:2,get:(e,t)=>pi(e).getUint16(t),put:(e,t,r)=>(pi(e).setUint16(t,r),t+2)},fi={len:4,get:(e,t)=>pi(e).getUint32(t,!0),put:(e,t,r)=>(pi(e).setUint32(t,r,!0),t+4)},yi={len:4,get:(e,t)=>pi(e).getUint32(t),put:(e,t,r)=>(pi(e).setUint32(t,r),t+4)},bi={len:4,get:(e,t)=>pi(e).getInt32(t),put:(e,t,r)=>(pi(e).setInt32(t,r),t+4)},wi={len:8,get:(e,t)=>pi(e).getBigUint64(t,!0),put:(e,t,r)=>(pi(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 Ti extends Error{constructor(){super("End-Of-Stream"),this.name="EndOfStreamError"}}class Si extends Error{constructor(e="The operation was aborted"){super(e),this.name="AbortError"}}class ki{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 Ti;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 o=Math.min(i.length,t);e.set(i.subarray(0,o),r),r+=o,t-=o,o<i.length&&this.peekQueue.push(i.subarray(o))}return r}async readRemainderFromStream(e,t){let r=0;for(;r<e.length&&!this.endOfStream;){if(this.interrupted)throw new Si;const i=await this.readFromStream(e.subarray(r),t);if(0===i)break;r+=i}if(!t&&r<e.length)throw new Ti;return r}}class Ei extends ki{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}}class Ai extends Ei{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 vi extends ki{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 Ti;return r}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}}class Ci{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 Ti;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 Ti;return e.get(r,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new Ti;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new Ti;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 xi extends Ci{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 o=await this.streamReader.read(e.subarray(0,r.length),r.mayBeLess);if(this.position+=o,(!t||!t.mayBeLess)&&o<r.length)throw new Ti;return o}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 o=new Uint8Array(r.length+t);return i=await this.peekBuffer(o,{mayBeLess:r.mayBeLess}),e.set(o.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(o){if((null==t?void 0:t.mayBeLess)&&o instanceof Ti)return 0;throw o}if(!r.mayBeLess&&i<r.length)throw new Ti}return i}async ignore(e){const t=Math.min(256e3,e),r=new Uint8Array(t);let i=0;for(;i<e;){const o=e-i,n=await this.readBuffer(r,{length:Math.min(t,o)});if(n<0)return n;i+=n}return i}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}}class Ri extends Ci{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 Ti;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 Ni(e,t){const r=function(e){try{const t=e.getReader({mode:"byob"});return t instanceof ReadableStreamDefaultReader?new vi(t):new Ai(t)}catch(t){if(t instanceof TypeError)return new vi(e.getReader());throw t}}(e),i=t??{},o=i.onClose;return i.onClose=async()=>{if(await r.close(),o)return o()},new xi(r,i)}var _i=Uint8Array,Pi=Uint16Array,Fi=Int32Array,Oi=new _i([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]),zi=new _i([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]),Di=new _i([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Bi=function(e,t){for(var r=new Pi(31),i=0;i<31;++i)r[i]=t+=1<<e[i-1];var o=new Fi(r[30]);for(i=1;i<30;++i)for(var n=r[i];n<r[i+1];++n)o[n]=n-r[i]<<5|i;return{b:r,r:o}},Mi=Bi(Oi,2),Ui=Mi.b,Ki=Mi.r;Ui[28]=258,Ki[258]=28;for(var Li=Bi(zi,0).b,$i=new Pi(32768),Hi=0;Hi<32768;++Hi){var qi=(43690&Hi)>>1|(21845&Hi)<<1;qi=(61680&(qi=(52428&qi)>>2|(13107&qi)<<2))>>4|(3855&qi)<<4,$i[Hi]=((65280&qi)>>8|(255&qi)<<8)>>1}var ji=function(e,t,r){for(var i=e.length,o=0,n=new Pi(t);o<i;++o)e[o]&&++n[e[o]-1];var s,a=new Pi(t);for(o=1;o<t;++o)a[o]=a[o-1]+n[o-1]<<1;s=new Pi(1<<t);var c=15-t;for(o=0;o<i;++o)if(e[o])for(var l=o<<4|e[o],d=t-e[o],u=a[e[o]-1]++<<d,p=u|(1<<d)-1;u<=p;++u)s[$i[u]>>c]=l;return s},Wi=new _i(288);for(Hi=0;Hi<144;++Hi)Wi[Hi]=8;for(Hi=144;Hi<256;++Hi)Wi[Hi]=9;for(Hi=256;Hi<280;++Hi)Wi[Hi]=7;for(Hi=280;Hi<288;++Hi)Wi[Hi]=8;var Vi=new _i(32);for(Hi=0;Hi<32;++Hi)Vi[Hi]=5;var Gi=ji(Wi,9),Ji=ji(Vi,5),Yi=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},Xi=function(e,t,r){var i=t/8|0;return(e[i]|e[i+1]<<8)>>(7&t)&r},Zi=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},Qi=function(e){return(e+7)/8|0},eo=["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"],to=function(e,t,r){var i=new Error(t||eo[e]);if(i.code=e,Error.captureStackTrace&&Error.captureStackTrace(i,to),!r)throw i;return i},ro=function(e,t,r,i){var o=e.length;if(!o||t.f&&!t.l)return r||new _i(0);var n=!r,s=n||2!=t.i,a=t.i;n&&(r=new _i(3*o));var c=function(e){var t=r.length;if(e>t){var i=new _i(Math.max(2*t,e));i.set(r),r=i}},l=t.f||0,d=t.p||0,u=t.b||0,p=t.l,h=t.d,g=t.m,m=t.n,f=8*o;do{if(!p){l=Xi(e,d,1);var y=Xi(e,d+1,3);if(d+=3,!y){var b=e[(R=Qi(d)+4)-4]|e[R-3]<<8,w=R+b;if(w>o){a&&to(0);break}s&&c(u+b),r.set(e.subarray(R,w),u),t.b=u+=b,t.p=d=8*w,t.f=l;continue}if(1==y)p=Gi,h=Ji,g=9,m=5;else if(2==y){var I=Xi(e,d,31)+257,T=Xi(e,d+10,15)+4,S=I+Xi(e,d+5,31)+1;d+=14;for(var k=new _i(S),E=new _i(19),A=0;A<T;++A)E[Di[A]]=Xi(e,d+3*A,7);d+=3*T;var v=Yi(E),C=(1<<v)-1,x=ji(E,v);for(A=0;A<S;){var R,N=x[Xi(e,d,C)];if(d+=15&N,(R=N>>4)<16)k[A++]=R;else{var _=0,P=0;for(16==R?(P=3+Xi(e,d,3),d+=2,_=k[A-1]):17==R?(P=3+Xi(e,d,7),d+=3):18==R&&(P=11+Xi(e,d,127),d+=7);P--;)k[A++]=_}}var F=k.subarray(0,I),O=k.subarray(I);g=Yi(F),m=Yi(O),p=ji(F,g),h=ji(O,m)}else to(1);if(d>f){a&&to(0);break}}s&&c(u+131072);for(var z=(1<<g)-1,D=(1<<m)-1,B=d;;B=d){var M=(_=p[Zi(e,d)&z])>>4;if((d+=15&_)>f){a&&to(0);break}if(_||to(2),M<256)r[u++]=M;else{if(256==M){B=d,p=null;break}var U=M-254;if(M>264){var K=Oi[A=M-257];U=Xi(e,d,(1<<K)-1)+Ui[A],d+=K}var L=h[Zi(e,d)&D],$=L>>4;L||to(3),d+=15&L;O=Li[$];if($>3){K=zi[$];O+=Zi(e,d)&(1<<K)-1,d+=K}if(d>f){a&&to(0);break}s&&c(u+131072);var H=u+U;if(u<O){var q=0-O,j=Math.min(O,H);for(q+u<0&&to(3);u<j;++u)r[u]=i[q+u]}for(;u<H;++u)r[u]=r[u-O]}}t.l=p,t.p=B,t.b=u,t.f=l,p&&(l=1,t.m=g,t.d=h,t.n=m)}while(!l);return u!=r.length&&n?function(e,t,r){return(null==r||r>e.length)&&(r=e.length),new _i(e.subarray(t,r))}(r,0,u):r.subarray(0,u)},io=new _i(0);function oo(e,t){var r,i,o=function(e){31==e[0]&&139==e[1]&&8==e[2]||to(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 o+8>e.length&&to(6,"invalid gzip data"),ro(e.subarray(o,-8),{i:2},new _i((i=(r=e).length,(r[i-4]|r[i-3]<<8|r[i-2]<<16|r[i-1]<<24)>>>0)),t)}function no(e,t){return ro(e.subarray(((8!=(15&(r=e)[0])||r[0]>>4>7||(r[0]<<8|r[1])%31)&&to(6,"invalid zlib data"),1==(r[1]>>5&1)&&to(6,"invalid zlib data: "+(32&r[1]?"need":"unexpected")+" dictionary"),2+(r[1]>>3&4)),-4),{i:2},t,t);var r}function so(e,t){return 31==e[0]&&139==e[1]&&8==e[2]?oo(e,t):8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31?function(e,t){return ro(e,{i:2},t,t)}(e,t):no(e,t)}var ao="undefined"!=typeof TextDecoder&&new TextDecoder;try{ao.decode(io,{stream:!0})}catch(ag){}var co,lo,uo,po,ho,go={exports:{}};function mo(){if(lo)return co;lo=1;var e=1e3,t=60*e,r=60*t,i=24*r,o=7*i,n=365.25*i;function s(e,t,r,i){var o=t>=1.5*r;return Math.round(e/r)+" "+i+(o?"s":"")}return co=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*n;case"weeks":case"week":case"w":return c*o;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(o){var n=Math.abs(o);if(n>=i)return s(o,n,i,"day");if(n>=r)return s(o,n,r,"hour");if(n>=t)return s(o,n,t,"minute");if(n>=e)return s(o,n,e,"second");return o+" ms"}(a):function(o){var n=Math.abs(o);if(n>=i)return Math.round(o/i)+"d";if(n>=r)return Math.round(o/r)+"h";if(n>=t)return Math.round(o/t)+"m";if(n>=e)return Math.round(o/e)+"s";return o+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))}}var fo=(ho||(ho=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,o=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(i++,"%c"===e&&(o=i))}),t.splice(o,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=(po||(po=1,uo=function(e){function t(e){let i,o,n,s=null;function a(...e){if(!a.enabled)return;const r=a,o=Number(new Date),n=o-(i||o);r.diff=n,r.prev=i,r.curr=o,i=o,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,o)=>{if("%%"===i)return"%";s++;const n=t.formatters[o];if("function"==typeof n){const t=e[s];i=n.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:(o!==t.namespaces&&(o=t.namespaces,n=t.enabled(e)),n),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,o=-1,n=0;for(;r<e.length;)if(i<t.length&&(t[i]===e[r]||"*"===t[i]))"*"===t[i]?(o=i,n=r,i++):(r++,i++);else{if(-1===o)return!1;i=o+1,n++,r=n}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=mo(),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}),uo)(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}(go,go.exports)),go.exports);const yo=ui(fo),bo=67324752,wo=134695760,Io=33639248,To=101010256,So={get:e=>(gi.get(e,6),{signature:fi.get(e,0),compressedSize:fi.get(e,8),uncompressedSize:fi.get(e,12)}),len:16},ko={get(e){const t=gi.get(e,6);return{signature:fi.get(e,0),minVersion:gi.get(e,4),dataDescriptor:!!(8&t),compressedMethod:gi.get(e,8),compressedSize:fi.get(e,18),uncompressedSize:fi.get(e,22),filenameLength:gi.get(e,26),extraFieldLength:gi.get(e,28),filename:null}},len:30},Eo={get:e=>({signature:fi.get(e,0),nrOfThisDisk:gi.get(e,4),nrOfThisDiskWithTheStart:gi.get(e,6),nrOfEntriesOnThisDisk:gi.get(e,8),nrOfEntriesOfSize:gi.get(e,10),sizeOfCd:fi.get(e,12),offsetOfStartOfCd:fi.get(e,16),zipFileCommentLength:gi.get(e,20)}),len:22},Ao={get(e){const t=gi.get(e,8);return{signature:fi.get(e,0),minVersion:gi.get(e,6),dataDescriptor:!!(8&t),compressedMethod:gi.get(e,10),compressedSize:fi.get(e,20),uncompressedSize:fi.get(e,24),filenameLength:gi.get(e,28),extraFieldLength:gi.get(e,30),fileCommentLength:gi.get(e,32),relativeOffsetOfLocalHeader:fi.get(e,42),filename:null}},len:46};function vo(e){const t=new Uint8Array(fi.len);return fi.put(t,0,e),t}const Co=yo("tokenizer:inflate"),xo=262144,Ro=vo(wo),No=vo(To);class _o{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(xo)}async isZip(){return await this.peekSignature()===bo}peekSignature(){return this.tokenizer.peekToken(fi)}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]===No[0]&&r[i+1]===No[1]&&r[i+2]===No[2]&&r[i+3]===No[3])return e.fileInfo.size-t+i;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess())return void Co("Cannot reading central-directory without random-read support");Co("Reading central-directory...");const e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){Co("Central-directory 32-bit signature found");const r=await this.tokenizer.readToken(Eo,t),i=[];this.tokenizer.setPosition(r.offsetOfStartOfCd);for(let e=0;e<r.nrOfEntriesOfSize;++e){const t=await this.tokenizer.readToken(Ao);if(t.signature!==Io)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),Co(`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 o;if(r=!!i.stop,await this.tokenizer.ignore(t.extraFieldLength),t.dataDescriptor&&0===t.compressedSize){const e=[];let r=xo;Co("Compressed-file-size unknown, scanning for next data-descriptor-signature....");let o=-1;for(;o<0&&r===xo;){r=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),o=Po(this.syncBuffer.subarray(0,r),Ro);const t=o>=0?o:r;if(i.handler){const r=new Uint8Array(t);await this.tokenizer.readBuffer(r),e.push(r)}else await this.tokenizer.ignore(t)}Co(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),i.handler&&await this.inflate(t,Fo(e),i.handler)}else i.handler?(Co(`Reading compressed-file-data: ${t.compressedSize} bytes`),o=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(o),await this.inflate(t,o,i.handler)):(Co(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(Co(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor){if(134695760!==(await this.tokenizer.readToken(So)).signature)throw new Error("Expected data-descriptor-signature at position "+(this.tokenizer.position-So.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);Co(`Decompress filename=${e.filename}, compressed-size=${t.length}`);return r(so(t))}async readLocalFileHeader(){const e=await this.tokenizer.peekToken(fi);if(e===bo){const e=await this.tokenizer.readToken(ko);return e.filename=await this.tokenizer.readToken(new Ii(e.filenameLength,"utf-8")),e}if(e===Io)return!1;if(3759263696===e)throw new Error("Encrypted ZIP");throw new Error("Unexpected signature")}}function Po(e,t){const r=e.length,i=t.length;if(i>r)return-1;for(let o=0;o<=r-i;o++){let r=!0;for(let n=0;n<i;n++)if(e[o+n]!==t[n]){r=!1;break}if(r)return o}return-1}function Fo(e){const t=e.reduce((e,t)=>e+t.length,0),r=new Uint8Array(t);let i=0;for(const o of e)r.set(o,i),i+=o.length;return r}function Oo(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 zo={get:(e,t)=>127&e[t+3]|e[t+2]<<7|e[t+1]<<14|e[t]<<21,len:4},Do=4100;function Bo(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 Mo(e,t,r){r={offset:0,...r};for(const[i,o]of t.entries())if(r.mask){if(o!==(r.mask[i]&e[i+r.offset]))return!1}else if(o!==e[i+r.offset])return!1;return!0}class Uo{constructor(e){se(this,"detectConfident",async e=>{if(this.buffer=new Uint8Array(Do),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(zo);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 _o(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=Bo(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=Bo(e))}else{t=t.slice(0,Math.max(0,i));const e=t.lastIndexOf('"'),o=t.slice(Math.max(0,e+1));r=Bo(o)}},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),Mo(i,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/ogg; codecs=opus"}:Mo(i,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:Mo(i,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:Mo(i,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:Mo(i,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:Mo(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 o=await this.readTiffHeader(!1);if(o)return o}if(this.check([77,77])){const n=await this.readTiffHeader(!0);if(n)return n}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(hi);let r=128,i=0;for(;0===(t&r)&&0!==r;)++i,r>>=1;const o=new Uint8Array(i+1);return await e.readBuffer(o),o}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),o=new DataView(t.buffer,t.length-r,r);return{id:Oo(i),len:Oo(o)}}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 d=new Ii(4,"latin1").get(this.buffer,2);if(d.match("^d*")&&d>=1e3&&d<=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 u(){return{length:await e.readToken(bi),type:await e.readToken(new Ii(4,"latin1"))}}await e.ignore(8);do{const p=await u();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(wi))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){const m=await g();let f=m.size-24;if(Mo(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),Mo(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(Mo(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 o=t;o<t+148;o++)i+=e[o];for(let o=t+156;o<t+512;o++)i+=e[o];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)}),se(this,"detectImprecise",async e=>{if(this.buffer=new Uint8Array(Do),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 Ri(r,i)))}async fromBlob(e){return this.fromStream(e.stream())}async fromStream(e){const t=await Ni(e,this.tokenizerOptions);try{return await this.fromTokenizer(t)}finally{await t.close()}}async toDetectionStream(e,t){const{sampleSize:r=Do}=t;let i,o;const n=e.getReader({mode:"byob"});try{const{value:e,done:t}=await n.read(new Uint8Array(r));if(o=e,!t&&e)try{i=await this.fromBuffer(e.subarray(0,r))}catch(c){if(!(c instanceof Ti))throw c;i=void 0}o=e}finally{n.releaseLock()}const s=new TransformStream({async start(e){e.enqueue(o)},transform(e,t){t.enqueue(e)}}),a=e.pipeThrough(s);return a.fileType=i,a}check(e,t){return Mo(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?mi:gi);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?mi:gi);for(let r=0;r<t;++r){const t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){const t=(e?mi:gi).get(this.buffer,2),r=(e?yi:fi).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?mi:gi).get(this.buffer,8),r=(e?mi:gi).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 Ko=Object.create(null);Ko.open="0",Ko.close="1",Ko.ping="2",Ko.pong="3",Ko.message="4",Ko.upgrade="5",Ko.noop="6";const Lo=Object.create(null);Object.keys(Ko).forEach(e=>{Lo[Ko[e]]=e});const $o={type:"error",data:"parser error"},Ho="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),qo="function"==typeof ArrayBuffer,jo=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Wo=({type:e,data:t},r,i)=>Ho&&t instanceof Blob?r?i(t):Vo(t,i):qo&&(t instanceof ArrayBuffer||jo(t))?r?i(t):Vo(new Blob([t]),i):i(Ko[e]+(t||"")),Vo=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+(e||""))},r.readAsDataURL(e)};function Go(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Jo;const Yo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Xo="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let lg=0;lg<64;lg++)Xo[Yo.charCodeAt(lg)]=lg;const Zo="function"==typeof ArrayBuffer,Qo=(e,t)=>{if("string"!=typeof e)return{type:"message",data:tn(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:en(e.substring(1),t)};return Lo[r]?e.length>1?{type:Lo[r],data:e.substring(1)}:{type:Lo[r]}:$o},en=(e,t)=>{if(Zo){const r=(e=>{let t,r,i,o,n,s=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(s--,"="===e[e.length-2]&&s--);const l=new ArrayBuffer(s),d=new Uint8Array(l);for(t=0;t<a;t+=4)r=Xo[e.charCodeAt(t)],i=Xo[e.charCodeAt(t+1)],o=Xo[e.charCodeAt(t+2)],n=Xo[e.charCodeAt(t+3)],d[c++]=r<<2|i>>4,d[c++]=(15&i)<<4|o>>2,d[c++]=(3&o)<<6|63&n;return l})(e);return tn(r,t)}return{base64:!0,data:e}},tn=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,rn=String.fromCharCode(30);function on(){return new TransformStream({transform(e,t){!function(e,t){Ho&&e.data instanceof Blob?e.data.arrayBuffer().then(Go).then(t):qo&&(e.data instanceof ArrayBuffer||jo(e.data))?t(Go(e.data)):Wo(e,!1,e=>{Jo||(Jo=new TextEncoder),t(Jo.encode(e))})}(e,r=>{const i=r.length;let o;if(i<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,i);else if(i<65536){o=new Uint8Array(3);const e=new DataView(o.buffer);e.setUint8(0,126),e.setUint16(1,i)}else{o=new Uint8Array(9);const e=new DataView(o.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(i))}e.data&&"string"!=typeof e.data&&(o[0]|=128),t.enqueue(o),t.enqueue(r)})}})}let nn;function sn(e){return e.reduce((e,t)=>e+t.length,0)}function an(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let i=0;for(let o=0;o<t;o++)r[o]=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 cn(e){if(e)return function(e){for(var t in cn.prototype)e[t]=cn.prototype[t];return e}(e)}cn.prototype.on=cn.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},cn.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},cn.prototype.off=cn.prototype.removeListener=cn.prototype.removeAllListeners=cn.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 o=0;o<i.length;o++)if((r=i[o])===t||r.fn===t){i.splice(o,1);break}return 0===i.length&&delete this._callbacks["$"+e],this},cn.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 o=(r=r.slice(0)).length;i<o;++i)r[i].apply(this,t)}return this},cn.prototype.emitReserved=cn.prototype.emit,cn.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},cn.prototype.hasListeners=function(e){return!!this.listeners(e).length};const ln="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),dn="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function un(e,...t){return t.reduce((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t),{})}const pn=dn.setTimeout,hn=dn.clearTimeout;function gn(e,t){t.useNativeTimers?(e.setTimeoutFn=pn.bind(dn),e.clearTimeoutFn=hn.bind(dn)):(e.setTimeoutFn=dn.setTimeout.bind(dn),e.clearTimeoutFn=dn.clearTimeout.bind(dn))}function mn(e){return"string"==typeof e?function(e){let t=0,r=0;for(let i=0,o=e.length;i<o;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 fn(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class yn extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class bn extends cn{constructor(e){super(),this.writable=!1,gn(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 yn(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=Qo(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 wn extends bn{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(rn),i=[];for(let o=0;o<r.length;o++){const e=Qo(r[o],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 o=0;e.forEach((e,n)=>{Wo(e,!1,e=>{i[n]=e,++o===r&&t(i.join(rn))})})})(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]=fn()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let In=!1;try{In="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(cg){}const Tn=In;function Sn(){}class kn extends wn{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 En=class e extends cn{constructor(e,t,r){super(),this.createRequest=e,gn(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=un(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(ag){}if("POST"===this._method)try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(ag){}try{i.setRequestHeader("Accept","*/*")}catch(ag){}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(ag){return void this.setTimeoutFn(()=>{this._onError(ag)},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=Sn,t)try{this._xhr.abort()}catch(ag){}"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(En.requestsCount=0,En.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",An);else if("function"==typeof addEventListener){addEventListener("onpagehide"in dn?"pagehide":"unload",An,!1)}function An(){for(let e in En.requests)En.requests.hasOwnProperty(e)&&En.requests[e].abort()}const vn=function(){const e=Cn({xdomain:!1});return e&&null!==e.responseType}();function Cn(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||Tn))return new XMLHttpRequest}catch(ag){}if(!t)try{return new(dn[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(ag){}}const xn="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Rn extends bn{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,r=xn?{}:un(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(cg){return this.emitReserved("error",cg)}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;Wo(r,this.supportsBinary,e=>{try{this.doWrite(r,e)}catch(ag){}i&&ln(()=>{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]=fn()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const Nn=dn.WebSocket||dn.MozWebSocket;const _n={websocket:class extends Rn{createSocket(e,t,r){return xn?new Nn(e,t,r):t?new Nn(e,t):new Nn(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends bn{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(cg){return this.emitReserved("error",cg)}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){nn||(nn=new TextDecoder);const r=[];let i=0,o=-1,n=!1;return new TransformStream({transform(s,a){for(r.push(s);;){if(0===i){if(sn(r)<1)break;const e=an(r,1);n=!(128&~e[0]),o=127&e[0],i=o<126?3:126===o?1:2}else if(1===i){if(sn(r)<2)break;const e=an(r,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if(sn(r)<8)break;const e=an(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),n=t.getUint32(0);if(n>Math.pow(2,21)-1){a.enqueue($o);break}o=n*Math.pow(2,32)+t.getUint32(4),i=3}else{if(sn(r)<o)break;const e=an(r,o);a.enqueue(Qo(n?e:nn.decode(e),t)),i=0}if(0===o||o>e){a.enqueue($o);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),i=on();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const o=()=>{r.read().then(({done:e,value:t})=>{e||(this.onPacket(t),o())}).catch(e=>{})};o();const n={type:"open"};this.query.sid&&(n.data=`{"sid":"${this.query.sid}"}`),this._writer.write(n).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&&ln(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends kn{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=vn&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new En(Cn,this.uri(),e)}}},Pn=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,Fn=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function On(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 o=Pn.exec(e||""),n={},s=14;for(;s--;)n[Fn[s]]=o[s]||"";return-1!=r&&-1!=i&&(n.source=t,n.host=n.host.substring(1,n.host.length-1).replace(/;/g,":"),n.authority=n.authority.replace("[","").replace("]","").replace(/;/g,":"),n.ipv6uri=!0),n.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,n.path),n.queryKey=function(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,i){t&&(r[t]=i)}),r}(0,n.query),n}const zn="function"==typeof addEventListener&&"function"==typeof removeEventListener,Dn=[];zn&&addEventListener("offline",()=>{Dn.forEach(e=>e())},!1);class Bn extends cn{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=On(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=On(t.host).host);gn(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,o=r.length;i<o;i++){let e=r[i].split("=");t[decodeURIComponent(e[0])]=decodeURIComponent(e[1])}return t}(this.opts.query)),zn&&(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"})},Dn.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&&Bn.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",Bn.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+=mn(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,ln(()=>{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 o={type:e,data:t,options:r};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),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(Bn.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(),zn&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=Dn.indexOf(this._offlineEventListener);-1!==e&&Dn.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}Bn.protocol=4;class Mn extends Bn{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;Bn.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;Bn.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 o(){r||(r=!0,l(),t.close(),t=null)}const n=e=>{const r=new Error("probe error: "+e);r.transport=t.name,o(),this.emitReserved("upgradeError",r)};function s(){n("transport closed")}function a(){n("socket closed")}function c(e){t&&e.name!==t.name&&o()}const l=()=>{t.removeListener("open",i),t.removeListener("error",n),t.removeListener("close",s),this.off("close",a),this.off("upgrading",c)};t.once("open",i),t.once("error",n),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 Un=class extends Mn{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=>_n[e]).filter(e=>!!e)),super(e,r)}};const Kn="function"==typeof ArrayBuffer,Ln=Object.prototype.toString,$n="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Ln.call(Blob),Hn="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===Ln.call(File);function qn(e){return Kn&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||$n&&e instanceof Blob||Hn&&e instanceof File}function jn(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(jn(e[t]))return!0;return!1}if(qn(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return jn(e.toJSON(),!0);for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&jn(e[r]))return!0;return!1}function Wn(e){const t=[],r=e.data,i=e;return i.data=Vn(r,t),i.attachments=t.length,{packet:i,buffers:t}}function Vn(e,t){if(!e)return e;if(qn(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]=Vn(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]=Vn(e[i],t));return r}return e}function Gn(e,t){return e.data=Jn(e.data,t),delete e.attachments,e}function Jn(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]=Jn(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=Jn(e[r],t));return e}const Yn=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Xn,Zn;(Zn=Xn||(Xn={}))[Zn.CONNECT=0]="CONNECT",Zn[Zn.DISCONNECT=1]="DISCONNECT",Zn[Zn.EVENT=2]="EVENT",Zn[Zn.ACK=3]="ACK",Zn[Zn.CONNECT_ERROR=4]="CONNECT_ERROR",Zn[Zn.BINARY_EVENT=5]="BINARY_EVENT",Zn[Zn.BINARY_ACK=6]="BINARY_ACK";function Qn(e){return"[object Object]"===Object.prototype.toString.call(e)}class es extends cn{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===Xn.BINARY_EVENT;r||t.type===Xn.BINARY_ACK?(t.type=r?Xn.EVENT:Xn.ACK,this.reconstructor=new ts(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!qn(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===Xn[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Xn.BINARY_EVENT||r.type===Xn.BINARY_ACK){const i=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const o=e.substring(i,t);if(o!=Number(o)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(o)}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(!es.isPayloadValid(r.type,i))throw new Error("invalid payload");r.data=i}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(ag){return!1}}static isPayloadValid(e,t){switch(e){case Xn.CONNECT:return Qn(t);case Xn.DISCONNECT:return void 0===t;case Xn.CONNECT_ERROR:return"string"==typeof t||Qn(t);case Xn.EVENT:case Xn.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Yn.indexOf(t[0]));case Xn.ACK:case Xn.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class ts{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=Gn(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const rs=Object.freeze(Object.defineProperty({__proto__:null,Decoder:es,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Xn.EVENT&&e.type!==Xn.ACK||!jn(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Xn.EVENT?Xn.BINARY_EVENT:Xn.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Xn.BINARY_EVENT&&e.type!==Xn.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=Wn(e),r=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(r),i}},get PacketType(){return Xn},protocol:5},Symbol.toStringTag,{value:"Module"}));function is(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const os=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ns extends cn{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=[is(e,"open",this.onopen.bind(this)),is(e,"packet",this.onpacket.bind(this)),is(e,"error",this.onerror.bind(this)),is(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,o;if(os.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 n={type:Xn.EVENT,data:t,options:{}};if(n.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,r=t.pop();this._registerAckCallback(e,r),n.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===(o=this.io.engine)||void 0===o?void 0:o._hasPingExpired());return this.flags.volatile&&!s||(a?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),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 o=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),n=(...e)=>{this.io.clearTimeoutFn(o),t.apply(this,e)};n.withError=!0,this.acks[e]=n}emitWithAck(e,...t){return new Promise((r,i)=>{const o=(e,t)=>e?i(e):r(t);o.withError=!0,t.push(o),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:Xn.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 Xn.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 Xn.EVENT:case Xn.BINARY_EVENT:this.onevent(e);break;case Xn.ACK:case Xn.BINARY_ACK:this.onack(e);break;case Xn.DISCONNECT:this.ondisconnect();break;case Xn.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:Xn.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:Xn.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 ss(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}ss.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)},ss.prototype.reset=function(){this.attempts=0},ss.prototype.setMin=function(e){this.ms=e},ss.prototype.setMax=function(e){this.max=e},ss.prototype.setJitter=function(e){this.jitter=e};class as extends cn{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,gn(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 ss({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||rs;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 Un(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const i=is(t,"open",function(){r.onopen(),e&&e()}),o=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},n=is(t,"error",o);if(!1!==this._timeout){const e=this._timeout,r=this.setTimeoutFn(()=>{i(),o(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(n),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(is(e,"ping",this.onping.bind(this)),is(e,"data",this.ondata.bind(this)),is(e,"error",this.onerror.bind(this)),is(e,"close",this.onclose.bind(this)),is(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(ag){this.onclose("parse error",ag)}}ondecoded(e){ln(()=>{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 ns(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 cs={};function ls(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=On(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 o=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+o+":"+i.port+t,i.href=i.protocol+"://"+o+(r&&r.port===i.port?"":":"+i.port),i}(e,(t=t||{}).path||"/socket.io"),i=r.source,o=r.id,n=r.path,s=cs[o]&&n in cs[o].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||s?a=new as(i,t):(cs[o]||(cs[o]=new as(i,t)),a=cs[o]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}Object.assign(ls,{Manager:as,Socket:ns,io:ls,connect:ls});const ds=class e{constructor(e){if(se(this,"client"),se(this,"config"),se(this,"logger",ai.getInstance()),se(this,"socket",null),se(this,"socketConnected",!1),se(this,"connectionMode","auto"),se(this,"wsBaseUrl",null),this.config=e,!e.apiKey)throw new ci("API key is required");if(!e.network)throw new ci("Network is required");const t={"x-api-key":e.apiKey,"Content-Type":"application/json"};this.client=Hr.create({baseURL:"https://v2-api.tier.bot/api",headers:t}),this.logger=ai.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 Hr.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 ci("Unable to fetch file metadata")}}getMimeType(t){const r=t.toLowerCase().split(".").pop();if(!r)throw new ci("File must have an extension");const i=e.VALID_MIME_TYPES[r];if(!i)throw new ci(`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 ci("holderId is required");if(!e.VALID_MODES.includes(t.mode))throw new ci(`Invalid mode: ${t.mode}. Must be one of: ${e.VALID_MODES.join(", ")}`);if("hashinal"===t.mode&&!t.jsonFileURL&&!t.metadataObject)throw new ci("Hashinal mode requires either jsonFileURL or metadataObject");if(t.onlyJSONCollection&&"hashinal-collection"!==t.mode)throw new ci("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 ci("Base64 data is required");const r=t.base64.replace(/^data:.*?;base64,/,"");if(Math.ceil(.75*r.length)>e.MAX_BASE64_SIZE)throw new ci(`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 ci("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 ci("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=be.from(t,"base64"),i=await async function(e,t){return new Uo(t).fromBuffer(e)}(r);return(null==i?void 0:i.mime)||"application/octet-stream"}catch(cg){return this.logger.warn("Failed to detect MIME type from buffer"),"application/octet-stream"}}async startInscription(t){var r,i;try{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 ci(`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 ci("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};let o;return o="url"===t.file.type?await this.client.post("/inscriptions/start-inscription",{...i,fileURL:t.file.url}):await this.client.post("/inscriptions/start-inscription",{...i,fileBase64:t.file.base64,fileName:t.file.fileName,fileMimeType:r||this.getMimeType(t.file.fileName)}),o.data}catch(o){if(o instanceof ci)throw o;if(Hr.isAxiosError(o))throw new Error((null==(i=null==(r=o.response)?void 0:r.data)?void 0:i.message)||"Failed to start inscription");throw o}}async executeTransaction(e,t){var r,o;try{const n="mainnet"===t.network?i.Client.forMainnet():i.Client.forTestnet(),a=new s.HederaMirrorNode(t.network),c=await a.requestAccount(t.accountId),l=null==(r=null==c?void 0:c.key)?void 0:r._type,d="string"==typeof t.privateKey;let u;if(l&&d)u=(null==(o=null==l?void 0:l.toLowerCase())?void 0:o.includes("ecdsa"))?i.PrivateKey.fromStringECDSA(t.privateKey):i.PrivateKey.fromStringED25519(t.privateKey);else if(!l&&d){const e=d?s.detectKeyTypeFromString(t.privateKey):void 0;u="ed25519"===(null==e?void 0:e.detectedType)?i.PrivateKey.fromStringED25519(t.privateKey):i.PrivateKey.fromStringECDSA(t.privateKey)}else u=t.privateKey;n.setOperator(t.accountId,u);const p=i.TransferTransaction.fromBytes(be.from(e,"base64")),h=await p.sign(u),g=await h.execute(n),m=(await g.getReceipt(n)).status.toString();if("SUCCESS"!==m)throw new Error(`Transaction failed with status: ${m}`);return g.transactionId.toString()}catch(n){throw new Error(`Failed to execute transaction: ${n instanceof Error?n.message:"Unknown error"}`)}}async executeTransactionWithSigner(e,t){try{const r=i.TransferTransaction.fromBytes(be.from(e,"base64")),o=await r.executeWithSigner(t),n=(await o.getReceiptWithSigner(t)).status.toString();if("SUCCESS"!==n)throw new Error(`Transaction failed with status: ${n}`);return o.transactionId.toString()}catch(r){throw new Error(`Failed to execute transaction: ${r instanceof Error?r.message:"Unknown error"}`)}}async inscribeAndExecute(e,t,r,i){const o=(null==i?void 0:i.waitForCompletion)??!0,n=(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(d){throw this.logger.error("WebSocket inscription failed, falling back to HTTP:",d),d}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(o){r&&r({stage:"confirming",message:"Transaction executed, waiting for inscription to complete",progressPercent:5});const e=Math.floor(n/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=ls(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(ag){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,o)=>{if(!this.socket)return o(new Error("WebSocket not connected"));let n,s,a,c;const l=()=>{var e,t,r;c&&clearTimeout(c),null==(e=this.socket)||e.off("inscription-progress",p),null==(t=this.socket)||t.off("inscription-complete",d),null==(r=this.socket)||r.off("inscription-error",u)};c=setTimeout(()=>{this.logger.error("WebSocket inscription timeout after 60 seconds",{jobId:n,transactionId:s,lastTopicId:a}),l(),i({jobId:n,transactionId:s,topicId:a,topic_id:a,status:"timeout",completed:!1})},6e4);const d=e=>{l(),i({jobId:n,transactionId:s,topicId:e.topicId||e.topic_id,topic_id:e.topicId||e.topic_id,status:"completed",completed:!0})},u=e=>{l(),o(new Error(e.error||"Inscription failed"))},p=e=>{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:n,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",p),this.socket.on("inscription-complete",d),this.socket.on("inscription-error",u),this.socket.emit("start-inscription",{...e,network:this.config.network},async e=>{if(!e.success)return l(),o(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),n=e.jobId||e.tx_id,!n)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:n,transactionId:s})}catch(i){l(),o(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=ls(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=3,r=1e3){for(let o=0;o<t;o++)try{return await e()}catch(i){if(o===t-1)throw i;const e=r*Math.pow(2,o);await new Promise(t=>setTimeout(t,e)),this.logger.debug(`Retry attempt ${o+1}/${t} after ${e}ms delay`)}throw new Error("Retry operation failed")}async retrieveInscription(e){if(!e)throw new ci("Transaction ID is required");try{return await this.retryWithBackoff(async()=>{const t=(await this.client.get(`/inscriptions/retrieve-inscription?id=${e}`)).data;return{...t,jobId:t.id}})}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 li(e).authenticate()}static async createWithAuth(t){const r="client"===t.type?new di({...t,logger:ai.getInstance()}):new li(t),{apiKey:i}=await r.authenticate();return new e({apiKey:i,network:t.network||"mainnet",wsBaseUrl:t.wsBaseUrl,connectionMode:t.connectionMode||"websocket"})}async waitForInscription(e,t=30,r=4e3,i=!1,o){var n;let s=0,a=0;const c=(r,i,n,c)=>{if(o)try{a=Math.max(a,n),o({stage:r,message:i,progressPercent:a,details:{...c,txId:e,currentAttempt:s,maxAttempts:t}})}catch(cg){this.logger.warn(`Error in progress callback: ${cg}`)}};for(c("confirming","Starting inscription verification",0);s<t;){c("confirming",`Verifying inscription status (attempt ${s+1}/${t})`,5,{attempt:s+1});const o=await this.retrieveInscription(e);if(o.error)throw c("verifying",`Error: ${o.error}`,100,{error:o.error}),new Error(o.error);let a=5;void 0!==o.messages&&void 0!==o.maxMessages&&o.maxMessages>0?(a=Math.min(95,5+o.messages/o.maxMessages*90),o.completed&&(a=100)):"processing"===o.status?a=10:o.completed&&(a=100),c(o.completed?"completed":"confirming",o.completed?"Inscription completed successfully":`Processing inscription (${o.status})`,a,{status:o.status,messagesProcessed:o.messages,maxMessages:o.maxMessages,messageCount:o.messages,completed:o.completed,confirmedMessages:o.confirmedMessages,result:o});const l="hashinal"===o.mode,d="6"===(null==(n=o.fileStandard)?void 0:n.toString());if(l&&o.topic_id&&o.jsonTopicId&&(!i||o.completed))return c("completed","Inscription verification complete",100,{result:o}),o;if(!l&&!d&&o.topic_id&&(!i||o.completed))return c("completed","Inscription verification complete",100,{result:o}),o;if(d&&o.topic_id&&o.jsonTopicId&&o.registryTopicId&&(!i||o.completed))return c("completed","Inscription verification complete",100,{result:o}),o;await new Promise(e=>setTimeout(e,r)),s++}throw c("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 ci("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),Hr.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}}};se(ds,"VALID_MODES",["file","upload","hashinal","hashinal-collection"]),se(ds,"MAX_BASE64_SIZE",2097152),se(ds,"MAX_URL_FILE_SIZE",104857600),se(ds,"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 us=ds;class ps{constructor(e={}){this.module=e.module||"Progress",this.callback=e.callback,this.logger=e.logger||new D({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 ps.instance?(e.callback&&ps.instance.setCallback(e.callback),e.module&&ps.instance.setModule(e.module),e.logger&&ps.instance.setLogger(e.logger),void 0!==e.minPercent&&ps.instance.setMinPercent(e.minPercent),void 0!==e.maxPercent&&ps.instance.setMaxPercent(e.maxPercent)):ps.instance=new ps(e),ps.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 ps({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 o=t.message;r&&!o.startsWith(r)&&(o=`${r}: ${o}`),this.report({stage:t.stage,message:o,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),o=Date.now();if(i===this.lastReportedPercent&&o-this.lastReportedTime<this.throttleMs&&"completed"!==e.stage&&"failed"!==e.stage)return;this.lastReportedPercent=i,this.lastReportedTime=o;const n={...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(n)}catch(cg){this.logger.warn(`Error in progress callback: ${cg}`)}}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 hs 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,hs)}}const gs=(e,t)=>e.replace(/\{([^}]+)\}/g,(e,r)=>{const i=((e,t)=>{const r=t.split(".");let i=e;for(const o of r){if(null==i)return;i=i[o]}return i})(t,String(r).trim());return null==i?"(Unknown)":String(i)}),ms=e=>{const t=[],r=[];if(Array.isArray(e.transfers))for(const i of e.transfers){const e=parseFloat(i.amount);let o=i.amount;o.startsWith("-")&&(o=o.substring(1)),o=o.replace(/\s*ℏ$/,""),e<0?t.push(`${i.accountId} (${o} ℏ)`):e>0&&r.push(`${i.accountId} (${o} ℏ)`)}return t.length>0&&r.length>0?`Transfer of HBAR from ${t.join(", ")} to ${r.join(", ")}`:e.humanReadableType},fs=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},ys=e=>e.tokenMint?`Mint ${e.tokenMint.amount} tokens for token ${e.tokenMint.tokenId}`:e.humanReadableType,bs=e=>e.tokenBurn?`Burn ${e.tokenBurn.amount} tokens for token ${e.tokenBurn.tokenId}`:e.humanReadableType,ws=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},Is=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},Ts=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},Ss=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},ks=e=>e.fileAppend?`Append to File ${e.fileAppend.fileId||"(Unknown ID)"}`:e.humanReadableType,Es=e=>e.fileUpdate?`Update File ${e.fileUpdate.fileId||"(Unknown ID)"}`:e.humanReadableType,As=e=>e.fileDelete?`Delete File ${e.fileDelete.fileId||"(Unknown ID)"}`:e.humanReadableType,vs=e=>e.consensusUpdateTopic?`Update Topic ${e.consensusUpdateTopic.topicId||"(Unknown ID)"}`:e.humanReadableType,Cs=e=>e.consensusDeleteTopic?`Delete Topic ${e.consensusDeleteTopic.topicId||"(Unknown ID)"}`:e.humanReadableType,xs=e=>e.tokenFreeze?`Freeze Token ${e.tokenFreeze.tokenId} for Account ${e.tokenFreeze.accountId}`:e.humanReadableType,Rs=e=>e.tokenUnfreeze?`Unfreeze Token ${e.tokenUnfreeze.tokenId} for Account ${e.tokenUnfreeze.accountId}`:e.humanReadableType,Ns=e=>e.tokenGrantKyc?`Grant KYC for Token ${e.tokenGrantKyc.tokenId} to Account ${e.tokenGrantKyc.accountId}`:e.humanReadableType,_s=e=>e.tokenRevokeKyc?`Revoke KYC for Token ${e.tokenRevokeKyc.tokenId} from Account ${e.tokenRevokeKyc.accountId}`:e.humanReadableType,Ps=e=>e.tokenPause?`Pause Token ${e.tokenPause.tokenId}`:e.humanReadableType,Fs=e=>e.tokenUnpause?`Unpause Token ${e.tokenUnpause.tokenId}`:e.humanReadableType,Os=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},zs=e=>e.tokenDelete?`Delete Token ${e.tokenDelete.tokenId}`:e.humanReadableType,Ds=e=>e.tokenAssociate?`Associate Account ${e.tokenAssociate.accountId} with Tokens: ${(e.tokenAssociate.tokenIds||[]).join(", ")}`:e.humanReadableType,Bs=e=>e.tokenDissociate?`Dissociate Account ${e.tokenDissociate.accountId} from Tokens: ${(e.tokenDissociate.tokenIds||[]).join(", ")}`:e.humanReadableType,Ms=e=>e.cryptoDelete?`Delete Account ${e.cryptoDelete.deleteAccountId}`:e.humanReadableType,Us=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},Ks=e=>e.cryptoUpdateAccount?`Update Account ${e.cryptoUpdateAccount.accountIdToUpdate||"(Unknown ID)"}`:e.humanReadableType,Ls=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},$s=e=>{if(e.cryptoDeleteAllowance){return`Delete ${(e.cryptoDeleteAllowance.nftAllowancesToRemove||[]).length} NFT Crypto Allowance(s)`}return e.humanReadableType},Hs=e=>{if(e.contractCreate){let t="Create Contract";return e.contractCreate.memo&&(t+=` (Memo: ${e.contractCreate.memo})`),t}return e.humanReadableType},qs=e=>e.contractUpdate?`Update Contract ${e.contractUpdate.contractIdToUpdate||"(Unknown ID)"}`:e.humanReadableType,js=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},Ws=e=>e.tokenUpdate?`Update Token ${e.tokenUpdate.tokenId||"(Unknown ID)"}`:e.humanReadableType,Vs=e=>e.tokenFeeScheduleUpdate?`Update Fee Schedule for Token ${e.tokenFeeScheduleUpdate.tokenId||"(Unknown ID)"}`:e.humanReadableType,Gs=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)`},Js=e=>{if(!e.scheduleCreate)return e.humanReadableType;let t="Create Schedule";return e.scheduleCreate.memo&&(t+=` (Memo: ${e.scheduleCreate.memo})`),t},Ys=e=>e.scheduleSign?"Sign Schedule":e.humanReadableType,Xs=e=>e.scheduleDelete?"Delete Schedule":e.humanReadableType,Zs=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,Qs=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,ea=e=>"Network Freeze",ta=e=>"Ethereum Transaction",ra=e=>e.uncheckedSubmit&&e.uncheckedSubmit.topicId?`Unchecked Submit to topic ${e.uncheckedSubmit.topicId}`:"Unchecked Submit",ia=e=>"Create Node",oa=e=>"Update Node",na=e=>"Delete Node",sa=e=>`Atomic Batch (${Array.isArray(e.atomicBatch?.transactions)?e.atomicBatch.transactions.length:0} transaction(s))`,aa={CRYPTOTRANSFER:{fn:ms},cryptoTransfer:{fn:ms},CONTRACTCALL:{fn:fs},contractCall:{fn:fs},TOKENMINT:{fn:ys},tokenMint:{fn:ys},TOKENBURN:{fn:bs},tokenBurn:{fn:bs},TOKENCREATE:{fn:ws},tokenCreation:{fn:ws},TOPICCREATE:{fn:Is},consensusCreateTopic:{fn:Is},CONSENSUSSUBMITMESSAGE:{fn:Ts},consensusSubmitMessage:{fn:Ts},TOPICUPDATE:{fn:vs},consensusUpdateTopic:{fn:vs},TOPICDELETE:{fn:Cs},consensusDeleteTopic:{fn:Cs},FILECREATE:{fn:Ss},fileCreate:{fn:Ss},FILEAPPEND:{fn:ks},fileAppend:{fn:ks},FILEUPDATE:{fn:Es},fileUpdate:{fn:Es},FILEDELETE:{fn:As},fileDelete:{fn:As},TOKENUPDATE:{fn:Ws},tokenUpdate:{fn:Ws},TOKENFEESCHEDULEUPDATE:{fn:Vs},tokenFeeScheduleUpdate:{fn:Vs},TOKENFREEZE:{fn:xs},tokenFreeze:{fn:xs},TOKENUNFREEZE:{fn:Rs},tokenUnfreeze:{fn:Rs},TOKENGRANTKYC:{fn:Ns},tokenGrantKyc:{fn:Ns},TOKENREVOKEKYC:{fn:_s},tokenRevokeKyc:{fn:_s},TOKENPAUSE:{fn:Ps},tokenPause:{fn:Ps},TOKENUNPAUSE:{fn:Fs},tokenUnpause:{fn:Fs},TOKENWIPE:{fn:Os},TOKENWIPEACCOUNT:{fn:Os},tokenWipe:{fn:Os},tokenWipeAccount:{fn:Os},TOKENDELETE:{fn:zs},tokenDelete:{fn:zs},TOKENASSOCIATE:{fn:Ds},tokenAssociate:{fn:Ds},TOKENDISSOCIATE:{fn:Bs},tokenDissociate:{fn:Bs},ACCOUNTDELETE:{fn:Ms},cryptoDelete:{fn:Ms},ACCOUNTCREATE:{fn:Us},cryptoCreateAccount:{fn:Us},ACCOUNTUPDATE:{fn:Ks},cryptoUpdateAccount:{fn:Ks},APPROVEALLOWANCE:{fn:Ls},cryptoApproveAllowance:{fn:Ls},DELETEALLOWANCE:{fn:$s},cryptoDeleteAllowance:{fn:$s},CONTRACTCREATE:{fn:Hs},contractCreate:{fn:Hs},CONTRACTUPDATE:{fn:qs},contractUpdate:{fn:qs},CONTRACTDELETE:{fn:js},contractDelete:{fn:js},TOKENAIRDROP:{fn:Gs},tokenAirdrop:{fn:Gs},SCHEDULECREATE:{fn:Js},scheduleCreate:{fn:Js},SCHEDULESIGN:{fn:Ys},scheduleSign:{fn:Ys},SCHEDULEDELETE:{fn:Xs},scheduleDelete:{fn:Xs},SYSTEMDELETE:{fn:Zs},systemDelete:{fn:Zs},SYSTEMUNDELETE:{fn:Qs},systemUndelete:{fn:Qs},FREEZE:{fn:ea},freeze:{fn:ea},ETHEREUMTRANSACTION:{fn:ta},ethereumTransaction:{fn:ta},UNCHECKEDSUBMIT:{fn:ra},uncheckedSubmit:{fn:ra},NODECREATE:{fn:ia},nodeCreate:{fn:ia},NODEUPDATE:{fn:oa},nodeUpdate:{fn:oa},NODEDELETE:{fn:na},nodeDelete:{fn:na},ATOMICBATCH:{fn:sa},atomicBatch:{fn:sa}},ca=e=>{const t=aa[e.type];if(t){if(t.fn)return t.fn(e);if(t.template)return gs(t.template,e)}const r=aa[e.humanReadableType];if(r){if(r.fn)return r.fn(e);if(r.template)return gs(r.template,e)}return"cryptoTransfer"===e.type||"CRYPTOTRANSFER"===e.type?ms(e):e.contractCall?fs(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,o]of Object.entries(r)){const e=[],r=[];for(const t of o){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 la(e){if(e){if(e.contractID)return`ContractID: ${new i.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()}`;if(e.ed25519)return`ED25519: ${a.Buffer.from(e.ed25519).toString("hex")}`;if(e.ECDSASecp256k1)return`ECDSA_secp256k1: ${a.Buffer.from(e.ECDSASecp256k1).toString("hex")}`;if(e?.keyList?.keys?.length>0){const t=e.keyList.keys.map(e=>la(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=>la(e)).filter(Boolean);return`ThresholdKey (${e.thresholdKey.threshold} of ${t.length}): [${t.join(", ")}]`}return e.delegatableContractId?`DelegatableContractID: ${new i.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 da(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 ua(e,t){const r=da(e);return!(!r||!r[t])}class pa{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 i.AccountId(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),e.initialSupply&&(t.initialSupply=i.Long.fromValue(e.initialSupply).toString()),void 0!==e.decimals&&null!==e.decimals&&(t.decimals=i.Long.fromValue(e.decimals).toNumber()),e.maxSupply&&(t.maxSupply=i.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=la(e.adminKey),t.kycKey=la(e.kycKey),t.freezeKey=la(e.freezeKey),t.wipeKey=la(e.wipeKey),t.supplyKey=la(e.supplyKey),t.feeScheduleKey=la(e.feeScheduleKey),t.pauseKey=la(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccount=new i.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.customFees&&e.customFees.length>0&&(t.customFees=e.customFees.map(e=>{const t={feeCollectorAccountId:e.feeCollectorAccountId?new i.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:i.Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new i.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:i.Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:i.Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:i.Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:i.Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let r;return e.royaltyFee.fallbackFee&&(r={amount:i.Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new i.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:i.Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:i.Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:r}}}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 i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:i.Long.fromValue(e.amount).toNumber()};return e.metadata&&e.metadata.length>0&&(t.metadata=e.metadata.map(e=>a.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 i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:i.Long.fromValue(e.amount).toNumber()};return e.serialNumbers&&e.serialNumbers.length>0&&(t.serialNumbers=e.serialNumbers.map(e=>i.Long.fromValue(e).toNumber())),t}static parseTokenUpdate(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.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 i.AccountId(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),t.adminKey=la(e.adminKey),t.kycKey=la(e.kycKey),t.freezeKey=la(e.freezeKey),t.wipeKey=la(e.wipeKey),t.supplyKey=la(e.supplyKey),t.feeScheduleKey=la(e.feeScheduleKey),t.pauseKey=la(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccountId=new i.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),void 0!==e.memo?.value&&(t.memo=e.memo.value),e.expiry?.seconds&&(t.expiry=`${i.Long.fromValue(e.expiry.seconds).toString()}.${e.expiry.nanos}`),t}static parseTokenFeeScheduleUpdate(e){if(!e)return;const t={};return e.tokenId&&(t.tokenId=new i.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 i.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:i.Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new i.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:i.Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:i.Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:i.Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:i.Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let r;return e.royaltyFee.fallbackFee&&(r={amount:i.Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new i.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:i.Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:i.Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:r}}}return{...t,feeType:"FIXED_FEE",fixedFee:{amount:"0"}}})),t}static parseTokenFreeze(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new i.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 i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new i.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 i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new i.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 i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new i.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 i.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 i.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 i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new i.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=>i.Long.fromValue(e).toString())),e.amount&&(t.amount=i.Long.fromValue(e.amount).toString()),t}static parseTokenDelete(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.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 i.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 i.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 i.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 i.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(ua(e,"tokenAirdrop")){const t=da(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 r of e.tokenTransfers){const e=r.token?new i.TokenId(r.token.shardNum??0,r.token.realmNum??0,r.token.tokenNum??0):null,o=[];if(r.transfers)for(const t of r.transfers){const e=t.accountID?new i.AccountId(t.accountID.shardNum??0,t.accountID.realmNum??0,t.accountID.accountNum??0):null;o.push({accountId:e?.toString()||"Unknown",amount:t.amount?i.Long.fromValue(t.amount).toString():"0",serialNumbers:t.serialNumbers?.map(e=>i.Long.fromValue(e).toString())})}t.push({tokenId:e?.toString()||"Unknown",transfers:o})}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(ag){}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 ha{static parseConsensusCreateTopic(e){if(!e)return;const t={};return e.memo&&(t.memo=e.memo),t.adminKey=la(e.adminKey),t.submitKey=la(e.submitKey),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new i.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=a.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=la(e.adminKey):t.adminKey=void 0,null===e.submitKey?(t.clearSubmitKey=!0,t.submitKey=void 0):e.submitKey?t.submitKey=la(e.submitKey):t.submitKey=void 0,e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new i.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 ga{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(ua(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=la({keyList:r})}return t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),t._memo&&(e.memo=t._memo),{type:"FILECREATE",humanReadableType:"File Create",fileCreate:e}}if(ua(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(ua(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=la({keyList:r})}return t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),t._memo&&(e.memo=t._memo),{type:"FILEUPDATE",humanReadableType:"File Update",fileUpdate:e}}if(ua(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=a.Buffer.from(e);let i,o;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),o=e.includes("�");i=t||o?"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{o=r.toString("utf8"),(o.includes("�")||/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(o))&&(o=r.toString("base64"))}catch{o=r.toString("base64")}else o=r.toString("base64");return{encoded:o,contentType:i,size:t}}static parseFileCreate(e){if(!e)return;const t={};return e.expirationTime?.seconds&&(t.expirationTime=`${i.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=la({keyList:e.keys})),e.contents&&(t.contents=a.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=a.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=`${i.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=la({keyList:e.keys})),e.contents&&(t.contents=a.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 ma{static parseCryptoTransfers(e,t){if(e.transfers?.accountAmounts&&(t.transfers=e.transfers.accountAmounts.map(e=>{const t=new i.AccountId(e.accountID.shardNum??0,e.accountID.realmNum??0,e.accountID.accountNum??0),r=i.Hbar.fromTinybars(i.Long.fromValue(e.amount));return{accountId:t.toString(),amount:r.toString(i.HbarUnit.Hbar),isDecimal:!0}})),e.tokenTransfers)for(const r of e.tokenTransfers){const e=new i.TokenId(r.token.shardNum??0,r.token.realmNum??0,r.token.tokenNum??0);if(r.transfers)for(const o of r.transfers){const r=new i.AccountId(o.accountID.shardNum??0,o.accountID.realmNum??0,o.accountID.accountNum??0),n=i.Long.fromValue(o.amount).toNumber();t.tokenTransfers.push({tokenId:e.toString(),accountId:r.toString(),amount:n})}}}static parseCryptoDelete(e){if(!e)return;const t={};return e.deleteAccountID&&(t.deleteAccountId=new i.AccountId(e.deleteAccountID.shardNum??0,e.deleteAccountID.realmNum??0,e.deleteAccountID.accountNum??0).toString()),e.transferAccountID&&(t.transferAccountId=new i.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=i.Hbar.fromTinybars(i.Long.fromValue(e.initialBalance)).toString(i.HbarUnit.Hbar)),e.key&&(t.key=la(e.key)),void 0!==e.receiverSigRequired&&(t.receiverSigRequired=e.receiverSigRequired),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.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 i.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=i.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 i.AccountId(e.accountIDToUpdate.shardNum??0,e.accountIDToUpdate.realmNum??0,e.accountIDToUpdate.accountNum??0).toString()),e.key&&(t.key=la(e.key)),e.expirationTime?.seconds&&(t.expirationTime=`${i.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=i.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 i.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=i.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 i.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new i.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount:i.Hbar.fromTinybars(i.Long.fromValue(e.amount)).toString(i.HbarUnit.Hbar)}))),e.tokenAllowances&&e.tokenAllowances.length>0&&(t.tokenAllowances=e.tokenAllowances.map(e=>({tokenId:new i.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),ownerAccountId:new i.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new i.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount:i.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 i.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString()),e.owner&&(t.ownerAccountId=new i.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString()),e.spender&&(t.spenderAccountId=new i.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=>i.Long.fromValue(e).toString())),void 0!==e.approvedForAll?.value&&(t.approvedForAll=e.approvedForAll.value),e.delegatingSpender&&(t.delegatingSpender=new i.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 i.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),tokenId:new i.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),serialNumbers:e.serialNumbers?e.serialNumbers.map(e=>i.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 fa{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:i.Long.fromValue(t._gas).toNumber(),amount:t._amount?parseFloat(t._amount.toString()):0};if(t._functionParameters){const r=a.Buffer.from(t._functionParameters).toString("hex");e.functionParameters=r,e.functionName=this.extractFunctionName(r)}return{type:"CONTRACTCALL",humanReadableType:"Contract Call",contractCall:e}}if(ua(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=a.Buffer.from(t._bytecode).toString("hex")),t._constructorParameters&&(e.constructorParameters=a.Buffer.from(t._constructorParameters).toString("hex")),t._memo&&(e.memo=t._memo),t._adminKey&&(e.adminKey=la(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=i.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(ua(e,"contractUpdateInstance")){const e={contractIdToUpdate:t._contractId.toString()};return t._memo&&(e.memo=t._memo),t._adminKey&&(e.adminKey=la(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=i.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(ua(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?i.Long.fromValue(e.maxGasAllowance).toNumber():0,amount:0};if(e.ethereumData&&e.ethereumData.length>0){const r=a.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=i.Hbar.fromTinybars(i.Long.fromValue(e.amount??0)),r={contractId:new i.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString(),gas:i.Long.fromValue(e.gas??0).toNumber(),amount:parseFloat(t.toString(i.HbarUnit.Hbar))};return e.functionParameters&&(r.functionParameters=a.Buffer.from(e.functionParameters).toString("hex"),r.functionParameters.length>=8&&(r.functionName=this.extractFunctionName(r.functionParameters))),r}static parseContractCreate(e){if(!e)return;const t={};return e.initialBalance&&(t.initialBalance=i.Hbar.fromTinybars(i.Long.fromValue(e.initialBalance)).toString(i.HbarUnit.Hbar)),e.gas&&(t.gas=i.Long.fromValue(e.gas).toString()),e.adminKey&&(t.adminKey=la(e.adminKey)),e.constructorParameters&&(t.constructorParameters=a.Buffer.from(e.constructorParameters).toString("hex")),e.memo&&(t.memo=e.memo),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.stakedAccountId?t.stakedAccountId=new i.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=i.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 i.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=a.Buffer.from(e.initcode).toString("hex")),t}static parseContractUpdate(e){if(!e)return;const t={};if(e.contractID&&(t.contractIdToUpdate=new i.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.adminKey&&(t.adminKey=la(e.adminKey)),e.expirationTime?.seconds&&(t.expirationTime=`${i.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.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 i.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&&i.Long.fromValue(e.stakedNodeId).notEquals(-1)?(t.stakedNodeId=i.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 i.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 i.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.transferAccountID?t.transferAccountId=new i.AccountId(e.transferAccountID.shardNum??0,e.transferAccountID.realmNum??0,e.transferAccountID.accountNum??0).toString():e.transferContractID&&(t.transferContractId=new i.ContractId(e.transferContractID.shardNum??0,e.transferContractID.realmNum??0,e.transferContractID.contractNum??0).toString()),t}static parseFromTransactionObject(e){return this.parseSCSTransaction(e)}}class ya{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(ua(e,"utilPrng")){const e={};return t._range&&0!==t._range&&(e.range=t._range),{type:"PRNG",humanReadableType:"Pseudo Random Number",utilPrng:e}}if(ua(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(ua(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(ua(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=`${i.Long.fromValue(e.startTime.seconds).toString()}.${e.startTime.nanos??0}`),e.updateFile&&(t.updateFile=new i.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 i.FileId(e.fileID.shardNum??0,e.fileID.realmNum??0,e.fileID.fileNum??0).toString():e.contractID&&(t.contractId=new i.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.expirationTime?.seconds&&(t.expirationTime=i.Long.fromValue(e.expirationTime.seconds).toString()),t}static parseSystemUndeleteFromProto(e){if(!e)return;const t={};return e.fileID?t.fileId=new i.FileId(e.fileID.shardNum??0,e.fileID.realmNum??0,e.fileID.fileNum??0).toString():e.contractID&&(t.contractId=new i.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=i.Long.fromValue(e.nodeId).toNumber()),t}static parseNodeUpdateFromProto(e){if(!e)return;const t={};return void 0!==e.nodeId&&(t.nodeId=i.Long.fromValue(e.nodeId).toNumber()),t}static parseNodeDeleteFromProto(e){if(!e)return;const t={};return void 0!==e.nodeId&&(t.nodeId=i.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 ba{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(ua(e,"scheduleCreate")){return{type:"SCHEDULECREATE",humanReadableType:"Schedule Create",scheduleCreate:{scheduledTransactionBody:globalThis.Buffer.from(t._scheduledTransaction).toString("base64"),memo:t._scheduleMemo,adminKey:t._adminKey?la(t._adminKey):void 0,payerAccountId:t._payerAccountId?.toString(),expirationTime:t._expirationTime?.toString(),waitForExpiry:t._waitForExpiry||!1}}}if(ua(e,"scheduleSign")){return{type:"SCHEDULESIGN",humanReadableType:"Schedule Sign",scheduleSign:{scheduleId:t._scheduleId.toString()}}}if(ua(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=la(e.adminKey)),e.payerAccountID&&(t.payerAccountId=new i.AccountId(e.payerAccountID.shardNum??0,e.payerAccountID.realmNum??0,e.payerAccountID.accountNum??0).toString()),e.expirationTime?.seconds&&(t.expirationTime=`${i.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 i.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 i.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 wa={TOKENCREATE:{bodyField:"tokenCreation",parser:pa.parseTokenCreate,resultField:"tokenCreation"},TOKENMINT:{bodyField:"tokenMint",parser:pa.parseTokenMint,resultField:"tokenMint"},TOKENBURN:{bodyField:"tokenBurn",parser:pa.parseTokenBurn,resultField:"tokenBurn"},TOKENUPDATE:{bodyField:"tokenUpdate",parser:pa.parseTokenUpdate,resultField:"tokenUpdate"},TOKENDELETE:{bodyField:"tokenDeletion",parser:pa.parseTokenDelete,resultField:"tokenDelete"},TOKENASSOCIATE:{bodyField:"tokenAssociate",parser:pa.parseTokenAssociate,resultField:"tokenAssociate"},TOKENDISSOCIATE:{bodyField:"tokenDissociate",parser:pa.parseTokenDissociate,resultField:"tokenDissociate"},TOKENFREEZE:{bodyField:"tokenFreeze",parser:pa.parseTokenFreeze,resultField:"tokenFreeze"},TOKENUNFREEZE:{bodyField:"tokenUnfreeze",parser:pa.parseTokenUnfreeze,resultField:"tokenUnfreeze"},TOKENGRANTKYC:{bodyField:"tokenGrantKyc",parser:pa.parseTokenGrantKyc,resultField:"tokenGrantKyc"},TOKENREVOKEKYC:{bodyField:"tokenRevokeKyc",parser:pa.parseTokenRevokeKyc,resultField:"tokenRevokeKyc"},TOKENPAUSE:{bodyField:"tokenPause",parser:pa.parseTokenPause,resultField:"tokenPause"},TOKENUNPAUSE:{bodyField:"tokenUnpause",parser:pa.parseTokenUnpause,resultField:"tokenUnpause"},TOKENWIPEACCOUNT:{bodyField:"tokenWipe",parser:pa.parseTokenWipeAccount,resultField:"tokenWipeAccount"},TOKENFEESCHEDULEUPDATE:{bodyField:"tokenFeeScheduleUpdate",parser:pa.parseTokenFeeScheduleUpdate,resultField:"tokenFeeScheduleUpdate"},TOKENAIRDROP:{bodyField:"tokenAirdrop",parser:pa.parseTokenAirdropFromProto,resultField:"tokenAirdrop"},TOPICCREATE:{bodyField:"consensusCreateTopic",parser:ha.parseConsensusCreateTopic,resultField:"consensusCreateTopic"},CONSENSUSSUBMITMESSAGE:{bodyField:"consensusSubmitMessage",parser:ha.parseConsensusSubmitMessage,resultField:"consensusSubmitMessage"},TOPICUPDATE:{bodyField:"consensusUpdateTopic",parser:ha.parseConsensusUpdateTopic,resultField:"consensusUpdateTopic"},TOPICDELETE:{bodyField:"consensusDeleteTopic",parser:ha.parseConsensusDeleteTopic,resultField:"consensusDeleteTopic"},ACCOUNTCREATE:{bodyField:"cryptoCreateAccount",parser:ma.parseCryptoCreateAccount,resultField:"cryptoCreateAccount"},ACCOUNTUPDATE:{bodyField:"cryptoUpdateAccount",parser:ma.parseCryptoUpdateAccount,resultField:"cryptoUpdateAccount"},ACCOUNTDELETE:{bodyField:"cryptoDelete",parser:ma.parseCryptoDelete,resultField:"cryptoDelete"},CRYPTOTRANSFER:{bodyField:"cryptoTransfer",parser:e=>{const t={transfers:[],tokenTransfers:[]};return ma.parseCryptoTransfers(e,t),t},resultField:"transfers",spreadResult:!0},APPROVEALLOWANCE:{bodyField:"cryptoApproveAllowance",parser:ma.parseCryptoApproveAllowance,resultField:"cryptoApproveAllowance"},DELETEALLOWANCE:{bodyField:"cryptoDeleteAllowance",parser:ma.parseCryptoDeleteAllowance,resultField:"cryptoDeleteAllowance"},FILECREATE:{bodyField:"fileCreate",parser:ga.parseFileCreate,resultField:"fileCreate"},FILEUPDATE:{bodyField:"fileUpdate",parser:ga.parseFileUpdate,resultField:"fileUpdate"},FILEDELETE:{bodyField:"fileDelete",parser:ga.parseFileDelete,resultField:"fileDelete"},FILEAPPEND:{bodyField:"fileAppend",parser:ga.parseFileAppend,resultField:"fileAppend"},CONTRACTCREATE:{bodyField:"contractCreateInstance",parser:fa.parseContractCreate,resultField:"contractCreate"},CONTRACTUPDATE:{bodyField:"contractUpdateInstance",parser:fa.parseContractUpdate,resultField:"contractUpdate"},CONTRACTDELETE:{bodyField:"contractDeleteInstance",parser:fa.parseContractDelete,resultField:"contractDelete"},CONTRACTCALL:{bodyField:"contractCall",parser:fa.parseContractCall,resultField:"contractCall"},ETHEREUMTRANSACTION:{bodyField:"ethereumTransaction",parser:fa.parseEthereumTransaction,resultField:"ethereumTransaction"},SCHEDULECREATE:{bodyField:"scheduleCreate",parser:ba.parseScheduleCreateFromProto,resultField:"scheduleCreate"},SCHEDULESIGN:{bodyField:"scheduleSign",parser:ba.parseScheduleSignFromProto,resultField:"scheduleSign"},SCHEDULEDELETE:{bodyField:"scheduleDelete",parser:ba.parseScheduleDeleteFromProto,resultField:"scheduleDelete"},PRNG:{bodyField:"utilPrng",parser:ya.parseUtilPrng,resultField:"utilPrng"},FREEZE:{bodyField:"freeze",parser:ya.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:pa.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 Ia={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"}},Ta={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"},Sa={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 ka(e){for(const[t,r]of Object.entries(Ia))if(e[t])return r;return{type:"UNKNOWN",humanReadableType:"Unknown Transaction"}}function Ea(e){return Ta[e]||"Unknown Transaction"}class Aa{static async parseTransactionBytes(e,t={}){const{enableFallback:r=!0,strictMode:i=!1,includeRaw:o=!0,maxRetries:n=2}=t,s=this.validateTransactionBytes(e);if(!s.isValid&&i)throw new hs(`Invalid transaction bytes format: ${s.error}`,"INVALID_FORMAT",void 0,e);let a,c=0;for(;c<=n;)try{const r=await this.parseTransaction(e,t);return r.formatDetection={originalFormat:s.format||"base64",wasConverted:"hex"===s.format,length:e.length},r}catch(d){if(a=d instanceof Error?d:new Error(String(d)),c++,!r||c>n){if(i)throw new hs("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(u){}}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,o;!t||a.Buffer.isBuffer(t)||t instanceof Uint8Array?(i=t,o=r):(o=t,i=void 0);try{const t=this.extractTransactionMetadata(e),r=pa.parseFromTransactionObject(e),a=ma.parseFromTransactionObject(e),c=ha.parseFromTransactionObject(e),l=ga.parseFromTransactionObject(e),d=fa.parseFromTransactionObject(e),u=ba.parseFromTransactionObject(e),p=ya.parseFromTransactionObject(e),h=[r,a,c,l,d,u,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(s){}"UNKNOWN"===m&&h.type&&(m=h.type,f=h.humanReadableType||f);const b={type:m,humanReadableType:f,transfers:[],tokenTransfers:[],...t,...h,raw:o.includeRaw?e._transactionBody||{}:void 0};return this.mergeProtoParsingResults(b,y,r,e,i),b.transfers=a.transfers||b.transfers||[],b.tokenTransfers=a.tokenTransfers||b.tokenTransfers||[],b}catch(c){return{type:"UNKNOWN",humanReadableType:"Unknown Transaction",transfers:[],tokenTransfers:[],raw:o.includeRaw?{}:void 0,details:{error:`Failed to parse Transaction object: ${c instanceof Error?c.message:String(c)}`}}}}static parseTransactionBody(e){try{const t=c.ethers.decodeBase64(e),r=n.proto.SchedulableTransactionBody.decode(t),o=this.getTransactionType(r),s={type:o,humanReadableType:this.getHumanReadableType(o),transfers:[],tokenTransfers:[],raw:r};if(r.memo&&(s.memo=r.memo),r.transactionFee){const e=i.Hbar.fromTinybars(i.Long.fromValue(r.transactionFee));s.transactionFee=e.toString(i.HbarUnit.Hbar)}return this.applySchedulableTransactionParsing(r,s),s}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 ka(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 ka(e).type}static getHumanReadableType(e){return Ea(e)}static getTransactionSummary(e){return ca(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,o=!1;return"hex"===t?(o=/^0x[0-9a-fA-F]+$/.test(e)&&e.length>2,o||(i="Invalid hex format")):(o=r.test(e)&&e.length>0,o||(i="Invalid base64 format")),{isValid:o,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(a.Buffer.from(t,"hex"))}return new Uint8Array(a.Buffer.from(e,"base64"))}catch(t){throw new hs("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 i.Transaction.fromBytes(t),!0}catch{return!1}}static decodeBytesLegacy(e){return this.decodeTransactionBytes(e)}static async parseTransaction(e,t={}){try{const r=this.decodeTransactionBytes(e),o=i.Transaction.fromBytes(r),n=this.extractTransactionMetadataEnhanced(o),s=this.runAllParsers(o),a=s.find(e=>e.type&&"UNKNOWN"!==e.type)||{},c=this.parseFromProtobuf(r),l=c.type||a.type||"UNKNOWN",d={type:l,humanReadableType:c.humanReadableType||a.humanReadableType||"Unknown Transaction",transfers:[],tokenTransfers:[],details:{...n},memo:"string"==typeof n.memo?n.memo:void 0,transactionId:"string"==typeof n.transactionId?n.transactionId:void 0,nodeAccountIds:Array.isArray(n.nodeAccountIds)?n.nodeAccountIds:[],maxTransactionFee:"string"==typeof n.maxTransactionFee?n.maxTransactionFee:void 0,validStart:"string"==typeof n.validStart?n.validStart:void 0,validDuration:"string"==typeof n.validDuration?n.validDuration:void 0,raw:t.includeRaw?{}:void 0};return this.mergeAllResults(d,c,a,s),d}catch(r){throw new hs("Failed to parse as regular transaction","REGULAR_PARSING_FAILED",r instanceof Error?r: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 hs("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[pa.parseFromTransactionObject(e),ma.parseFromTransactionObject(e),ha.parseFromTransactionObject(e),ga.parseFromTransactionObject(e),fa.parseFromTransactionObject(e),ba.parseFromTransactionObject(e),ya.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 o=i.find(e=>e.transfers||e.tokenTransfers)||{};e.transfers=o.transfers||e.transfers||[],e.tokenTransfers=o.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&&ma.parseCryptoTransfers(e.cryptoTransfer,t),e.cryptoDelete&&(t.cryptoDelete=ma.parseCryptoDelete(e.cryptoDelete)),e.cryptoCreateAccount&&(t.cryptoCreateAccount=ma.parseCryptoCreateAccount(e.cryptoCreateAccount)),e.cryptoUpdateAccount&&(t.cryptoUpdateAccount=ma.parseCryptoUpdateAccount(e.cryptoUpdateAccount)),e.cryptoApproveAllowance&&(t.cryptoApproveAllowance=ma.parseCryptoApproveAllowance(e.cryptoApproveAllowance)),e.cryptoDeleteAllowance&&(t.cryptoDeleteAllowance=ma.parseCryptoDeleteAllowance(e.cryptoDeleteAllowance)),e.contractCall&&(t.contractCall=fa.parseContractCall(e.contractCall)),e.contractCreateInstance&&(t.contractCreate=fa.parseContractCreate(e.contractCreateInstance)),e.contractUpdateInstance&&(t.contractUpdate=fa.parseContractUpdate(e.contractUpdateInstance)),e.contractDeleteInstance&&(t.contractDelete=fa.parseContractDelete(e.contractDeleteInstance)),e.tokenCreation&&(t.tokenCreation=pa.parseTokenCreate(e.tokenCreation)),e.tokenMint&&(t.tokenMint=pa.parseTokenMint(e.tokenMint)),e.tokenBurn&&(t.tokenBurn=pa.parseTokenBurn(e.tokenBurn)),e.tokenUpdate&&(t.tokenUpdate=pa.parseTokenUpdate(e.tokenUpdate)),e.tokenFeeScheduleUpdate&&(t.tokenFeeScheduleUpdate=pa.parseTokenFeeScheduleUpdate(e.tokenFeeScheduleUpdate)),e.tokenFreeze&&(t.tokenFreeze=pa.parseTokenFreeze(e.tokenFreeze)),e.tokenUnfreeze&&(t.tokenUnfreeze=pa.parseTokenUnfreeze(e.tokenUnfreeze)),e.tokenGrantKyc&&(t.tokenGrantKyc=pa.parseTokenGrantKyc(e.tokenGrantKyc)),e.tokenRevokeKyc&&(t.tokenRevokeKyc=pa.parseTokenRevokeKyc(e.tokenRevokeKyc)),e.tokenPause&&(t.tokenPause=pa.parseTokenPause(e.tokenPause)),e.tokenUnpause&&(t.tokenUnpause=pa.parseTokenUnpause(e.tokenUnpause)),e.tokenWipe&&(t.tokenWipeAccount=pa.parseTokenWipeAccount(e.tokenWipe)),e.tokenDeletion&&(t.tokenDelete=pa.parseTokenDelete(e.tokenDeletion)),e.tokenAssociate&&(t.tokenAssociate=pa.parseTokenAssociate(e.tokenAssociate)),e.tokenDissociate&&(t.tokenDissociate=pa.parseTokenDissociate(e.tokenDissociate)),e.tokenAirdrop&&(t.tokenAirdrop=pa.parseTokenAirdropFromProto(e.tokenAirdrop)),e.consensusCreateTopic&&(t.consensusCreateTopic=ha.parseConsensusCreateTopic(e.consensusCreateTopic)),e.consensusSubmitMessage&&(t.consensusSubmitMessage=ha.parseConsensusSubmitMessage(e.consensusSubmitMessage)),e.consensusUpdateTopic&&(t.consensusUpdateTopic=ha.parseConsensusUpdateTopic(e.consensusUpdateTopic)),e.consensusDeleteTopic&&(t.consensusDeleteTopic=ha.parseConsensusDeleteTopic(e.consensusDeleteTopic)),e.fileCreate&&(t.fileCreate=ga.parseFileCreate(e.fileCreate)),e.fileAppend&&(t.fileAppend=ga.parseFileAppend(e.fileAppend)),e.fileUpdate&&(t.fileUpdate=ga.parseFileUpdate(e.fileUpdate)),e.fileDelete&&(t.fileDelete=ga.parseFileDelete(e.fileDelete)),e.utilPrng&&(t.utilPrng=ya.parseUtilPrng(e.utilPrng))}static parseTransactionBodyDetails(e,t){const r={},i=wa[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,o){const n=Object.values(wa).map(e=>e.resultField);for(const s of n){const o=t[s],n=r[s];void 0!==o?e[s]=o:void 0!==n?e[s]=n:this.handleSpecialFieldExtraction(e,s,i)}}static handleSpecialFieldExtraction(e,t,r){if("tokenCreation"===t&&"TOKENCREATE"===e.type){const i=pa.extractTokenCreationFromTransaction(r);i&&(e[t]=i)}else if("tokenAirdrop"===t&&"TOKENAIRDROP"===e.type){const i=pa.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 va="undefined"!=typeof window&&void 0!==window.document;const Ca=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()}},xa=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 Ra(e,t,r){if(r)return r;const i=t.connectionMode||(!1===t.websocket?"http":"auto"),o={apiKey:t.apiKey,accountId:e.accountId,network:e.network||"mainnet",authType:t.apiKey?"api":"server",connectionMode:i},n=xa.get(o);if(n)return n;let s;return s=t.apiKey?new us({apiKey:t.apiKey,network:e.network||"mainnet",connectionMode:i}):await us.createWithAuth({type:"server",accountId:e.accountId,privateKey:"string"==typeof e.privateKey?e.privateKey:e.privateKey.toString(),network:e.network||"mainnet",connectionMode:i}),xa.set(o,s),s}let Na={};async function _a(e){if(va)throw new Error("File path operations are not supported in browser environment. Use buffer input type instead.");if(await async function(){if(!va&&!Na.readFileSync)try{const e="undefined"!=typeof global?global:globalThis,t=e.process?.mainModule?.require||e.require;if("function"!=typeof t)throw new Error("require function not available");{const e=t("fs"),r=t("path");Na.readFileSync=e.readFileSync,Na.basename=r.basename,Na.extname=r.extname}}catch(e){console.warn("Node.js modules not available, file path operations will be disabled")}}(),!Na.readFileSync||!Na.basename||!Na.extname)throw new Error("Node.js file system modules are not available. Cannot read file from path.");try{const r=Na.readFileSync(e),i=r.toString("base64"),o=Na.basename(e);let n="application/octet-stream";try{const e=await l.fileTypeFromBuffer(r);e&&(n=e.mime)}catch(t){const r=Na.extname(e).toLowerCase();n={".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:o,mimeType:n}}catch(t){throw new Error(`Failed to read file ${e}: ${t.message}`)}}function Pa(e){return{accountId:e.accountId,privateKey:"string"==typeof e.privateKey?e.privateKey:e.privateKey.toString(),network:e.network}}async function Fa(e,t,r,i){const o=D.getInstance({module:"Inscriber",...r.logging});o.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 o.debug("Quote-only mode requested, generating quote"),await Ba(e,t,r,i);"hashinal"===r.mode&&r.metadata&&Da(r.metadata,o);const n=r.connectionMode??(!1===r.websocket?"http":"auto"),s=r.waitIntervalMs??4e3,a=!r.waitForConfirmation;let c;if(i)o.debug("Using existing InscriptionSDK instance"),c=i;else if(r.apiKey)o.debug("Initializing InscriptionSDK with API key"),c=new us({apiKey:r.apiKey,network:t.network||"mainnet",connectionMode:n});else{o.debug("Initializing InscriptionSDK with server auth");const e=Pa(t);c=await us.createWithAuth({type:"server",accountId:e.accountId,privateKey:e.privateKey,network:e.network||"mainnet",connectionMode:n})}const l={holderId:t.accountId,metadata:r.metadata||{},tags:r.tags||[],mode:r.mode||"file",fileStandard:r.fileStandard,chunkSize:r.chunkSize};let d;switch(e.type){case"url":d={...l,file:{type:"url",url:e.url}};break;case"file":{const t=await _a(e.path);d={...l,file:{type:"base64",base64:t.base64,fileName:t.fileName,mimeType:t.mimeType}};break}case"buffer":d={...l,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&&(d.metadataObject=r.metadata,d.creator=r.metadata?.creator||t.accountId,d.description=r.metadata?.description,r.jsonFileURL&&(d.jsonFileURL=r.jsonFileURL)),o.debug("Preparing to inscribe content",{type:e.type,mode:r.mode||"file",holderId:t.accountId});const u=Pa(t),p=await c.inscribeAndExecute(d,u,void 0,{waitForCompletion:a,maxWaitTime:18e4,checkInterval:s}),h=p.transactionId||p.jobId;if(o.info("Starting to inscribe.",{type:e.type,mode:r.mode||"file",transactionId:h}),r.waitForConfirmation){if(o.debug("Waiting for inscription confirmation",{transactionId:h,maxAttempts:r.waitMaxAttempts,intervalMs:s}),!h)throw new ci("Transaction ID is required for confirmation");const e=await Ma(c,h,r.waitMaxAttempts,s,r.progressCallback);return o.info("Inscription confirmation received",{transactionId:h}),{confirmed:!0,result:p,inscription:e,sdk:c}}return{confirmed:!1,result:p,sdk:c}}catch(n){throw o.error("Error during inscription process",n),n}}async function Oa(e,t,r,i){const o=D.getInstance({module:"Inscriber",...r.logging});o.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){o.debug("Quote-only mode requested with signer, generating quote");const n={accountId:t.getAccountId().toString(),privateKey:"",network:r.network||"mainnet"};return await Ba(e,n,r,i)}"hashinal"===r.mode&&r.metadata&&Da(r.metadata,o);const n=t.getAccountId().toString();o.debug("Using account ID from signer",{accountId:n});const s=r.connectionMode??(!1===r.websocket?"http":"auto");let a;i?(o.debug("Using existing InscriptionSDK instance"),a=i):r.apiKey?(o.debug("Initializing InscriptionSDK with API key"),a=new us({apiKey:r.apiKey,network:r.network||"mainnet",connectionMode:s})):(o.debug("Initializing InscriptionSDK with client auth (wallet signer)"),a=await us.createWithAuth({type:"client",accountId:n,signer:t,network:r.network||"mainnet",connectionMode:s}));const c={holderId:n,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 _a(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||n,l.description=r.metadata?.description,r.jsonFileURL&&(l.jsonFileURL=r.jsonFileURL)),o.debug("Starting inscription via startInscription (websocket)",{type:e.type,mode:r.mode||"file",holderId:n,usesStartInscription:!0});const d=await a.startInscription({...l,holderId:n,network:r.network||"mainnet"});if(o.info("about to start inscription",{type:e.type,mode:r.mode||"file",jobId:d.id||d.tx_id,...d}),"string"==typeof d?.transactionBytes?(o.debug("Executing inscription transaction with signer from bytes"),await a.executeTransactionWithSigner(d.transactionBytes,t)):"Buffer"===d?.transactionBytes?.type&&(o.debug("Executing inscription transaction with signer from buffer"),await a.executeTransactionWithSigner(globalThis.Buffer.from(d.transactionBytes.data).toString("base64"),t)),r.waitForConfirmation){o.debug("Waiting for inscription confirmation (websocket)",{jobId:d.id||d.tx_id,maxAttempts:r.waitMaxAttempts,intervalMs:r.waitIntervalMs});const e=d.tx_id||d.id,t=await Ma(a,e,r.waitMaxAttempts,r.waitIntervalMs,r.progressCallback);return o.info("Inscription confirmation received",{jobId:e}),{confirmed:!0,result:{jobId:d.id||d.tx_id,transactionId:d.tx_id||"",topic_id:d.topic_id,status:d.status,completed:d.completed},inscription:t,sdk:a}}return{confirmed:!1,result:{jobId:d.id||d.tx_id,transactionId:d.tx_id||"",topic_id:d.topic_id,status:d.status,completed:d.completed},sdk:a}}catch(n){throw o.error("Error during inscription process",n),n}}async function za(e,t){const r=D.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 us({apiKey:t.apiKey,network:t.network||"mainnet"});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 us.createWithAuth({type:"server",accountId:t.accountId,privateKey:t.privateKey,network:t.network||"mainnet"})}r.debug("Initialized SDK for inscription retrieval",{formattedTransactionId:i,network:t.network||"mainnet"});const o=await e.retrieveInscription(i);return r.info("Successfully retrieved inscription",{formattedTransactionId:i}),o}catch(o){throw r.error("Error retrieving inscription",{formattedTransactionId:i,error:o}),o}}function Da(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 o=D.getInstance({module:"Inscriber",...r.logging});o.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 n=function(e,t,r){const i=Ca.createCacheKey(e,t,r);return Ca.get(i)}(e,t,r);if(n)return o.debug("Returning cached quote"),{confirmed:!1,quote:!0,result:n};"hashinal"===r.mode&&r.metadata&&Da(r.metadata,o);const s=await Ra(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 _a(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)),o.debug("Calling inscription SDK startInscription for quote",{type:e.type,mode:r.mode||"file",holderId:t.accountId});const l=await s.startInscription(c);o.debug("Received inscription response for quote parsing",{hasTransactionBytes:!!l.transactionBytes,bytesLength:l.transactionBytes?.length||0,transactionBytesType:typeof l.transactionBytes,totalCost:l.totalCost});const d=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 o=await Aa.parseTransactionBytes(r,{includeRaw:!1});t.debug("Parsed transaction for quote",{type:o.type,hasTransfers:!!o.transfers,transferCount:o.transfers?.length||0,transfers:o.transfers});let n=0;if(o.transfers&&o.transfers.length>0)for(const e of o.transfers){const r="string"==typeof e.amount?parseFloat(e.amount):e.amount;if(r<0){const i=Math.abs(r);n+=i,t.debug("Found HBAR transfer",{from:e.accountId,to:"service",amount:i})}}n>0&&(i=n.toString(),t.debug("Using parsed transaction transfer amount",{totalTransferAmount:n,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 o=[{to:"Inscription Service",amount:i,description:`Inscription fee (${i} HBAR)`}],n={totalCostHbar:i,validUntil:new Date(Date.now()+9e5).toISOString(),breakdown:{transfers:o}};return t.debug("Successfully parsed transaction for quote",{totalCostHbar:n.totalCostHbar,transferCount:o.length,hasTransactionBytes:!!e.transactionBytes,hasTotalCost:!!e.totalCost}),n}catch(i){throw t.error("Error parsing transaction for quote",i),i}}(l,o);return function(e,t,r,i){const o=Ca.createCacheKey(e,t,r);Ca.set(o,i,6e5)}(e,t,r,d),o.info("Successfully generated inscription quote",{totalCostHbar:d.totalCostHbar}),{confirmed:!1,quote:!0,result:d}}catch(n){throw o.error("Error generating inscription quote",n),n}}async function Ma(e,t,r=30,i=4e3,o){const n=D.getInstance({module:"Inscriber"}),s=new ps({module:"Inscriber",logger:n,callback:o});try{n.debug("Waiting for inscription confirmation",{transactionId:t,maxAttempts:r,intervalMs:i}),s.preparing("Preparing for inscription confirmation",5,{transactionId:t,maxAttempts:r,intervalMs:i});for(let c=1;c<=r;c++){s.verifying("Checking inscription status",void 0,{attempt:c,maxAttempts:r});try{const r=await e.retrieveInscription(t);if("completed"===r.status||r.completed)return s.completed("Inscription confirmed",{transactionId:t}),r;s.verifying("Inscription still processing",void 0,{transactionId:t,status:r.status})}catch(a){if(!("number"==typeof a.response?.status&&404===a.response?.status))throw n.error("Error waiting for inscription confirmation",{transactionId:t,attempt:c,error:a}),s.failed("Inscription confirmation failed",{transactionId:t,error:a}),a;n.debug("Inscription not found yet, retrying",{transactionId:t,attempt:c})}c<r&&await B(i)}const o=new Error(`Inscription confirmation timed out after ${r} attempts`);throw n.error("Error waiting for inscription confirmation",{transactionId:t,maxAttempts:r,intervalMs:i,error:o}),s.failed("Inscription confirmation failed",{transactionId:t,error:o}),o}catch(a){throw n.error("Error waiting for inscription confirmation",{transactionId:t,maxAttempts:r,intervalMs:i,error:a}),s.failed("Inscription confirmation failed",{transactionId:t,error:a}),a}}function Ua(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,o=i.topicId;if("string"==typeof o&&o.trim())return o;const n=i.topic_id;return"string"==typeof n&&n.trim()?n:void 0}var Ka=(e=>(e.REGISTER_CONFIG="register-config",e.REGISTER="register",e))(Ka||{}),La=(e=>(e.EVM="evm",e.WASM="wasm",e))(La||{});const $a=r.z.object({name:r.z.string().optional(),type:r.z.string()}),Ha=r.z.object({name:r.z.string(),inputs:r.z.array($a),outputs:r.z.array($a),stateMutability:r.z.enum(["view","pure"]),type:r.z.literal("function")}),qa=r.z.enum(["number","string","bool"]),ja=r.z.object({p:r.z.literal("hcs-7"),m:r.z.string().optional()}),Wa=ja.extend({op:r.z.literal("register-config"),t:r.z.literal("evm"),c:r.z.object({contractAddress:r.z.string().regex(/^0x[a-fA-F0-9]{40}$/,"Invalid contract address"),abi:Ha})}),Va=ja.extend({op:r.z.literal("register-config"),t:r.z.literal("wasm"),c:r.z.object({wasmTopicId:r.z.string(),inputType:r.z.object({stateData:r.z.record(qa)}),outputType:r.z.object({type:r.z.literal("string"),format:r.z.literal("topic-id")})})}),Ga=ja.extend({op:r.z.literal("register"),t_id:r.z.string(),d:r.z.object({weight:r.z.number(),tags:r.z.array(r.z.string()).nonempty()}).catchall(r.z.unknown())}),Ja=r.z.union([Wa,Va,Ga]);class Ya{constructor(e){this.network=e.network,this.logger=e.logger||D.getInstance({level:e.logLevel||"info",module:"HCS7Client",silent:e.silent}),this.mirrorNode=new G(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0)}generateRegistryMemo(e){return`hcs-7:indexed:${e}`}createConfigMessage(e){return e.config.type===La.EVM?{p:"hcs-7",op:Ka.REGISTER_CONFIG,t:La.EVM,c:{contractAddress:e.config.contractAddress,abi:e.config.abi},m:e.memo}:{p:"hcs-7",op:Ka.REGISTER_CONFIG,t:La.WASM,c:{wasmTopicId:e.config.wasmTopicId,inputType:e.config.inputType,outputType:e.config.outputType},m:e.memo}}createMetadataMessage(e){return{p:"hcs-7",op:Ka.REGISTER,t_id:e.metadataTopicId,m:e.memo,d:{weight:e.weight,tags:e.tags,...e.data||{}}}}validateMessage(e){const t=Ja.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=Ja.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 Xa(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 Za(e){return Y({memo:`hcs-7:indexed:${e.ttl}`,submitKey:e.submitKey,adminKey:e.adminKey,operatorPublicKey:e.operatorPublicKey})}function Qa(e){const t={p:"hcs-7",...e.message};return X({topicId:e.topicId,message:JSON.stringify(t),transactionMemo:e.transactionMemo})}class ec{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 tc(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 rc(e){const t=Object.create(D.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 ic(e){return e instanceof D}async function oc(e,t,r){const i=new G(t,r),o=[];for(const s of e)try{const e=await i.getPublicKey(s);o.push(e)}catch(n){r&&r.warn(`Could not get public key for account ${s}: ${n}`)}return o}const nc=e=>e.trim().toLowerCase(),sc=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"}]]),ac={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},cc=new Map(Object.entries(ac).map(([e,t])=>[t,e])),lc=e=>{const t=nc(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=ac[t];void 0!==e&&(i=e,r=t)}else cc.has(i)&&(r=cc.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}},dc=e=>{if("string"!=typeof e||0===e.trim().length)throw new Error("Ledger network is required.");const t=nc(e);return t.startsWith("hedera:")||t.includes("hedera-")||t.includes("hedera_")||"mainnet"===t||"testnet"===t?(e=>{const t=nc(e),r=sc.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):lc(t)};var uc=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(uc||{}),pc=(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))(pc||{});const hc=r.z.nativeEnum(pc),gc=r.z.union([hc,r.z.string()]),mc=r.z.union([r.z.string(),r.z.number(),r.z.boolean(),r.z.null()]),fc=r.z.lazy(()=>r.z.union([mc,r.z.array(fc),r.z.record(fc)])),yc=r.z.object({version:r.z.string(),type:r.z.number(),display_name:r.z.string(),alias:r.z.string().optional(),bio:r.z.string().optional(),socials:r.z.array(fc).optional(),aiAgent:r.z.object({type:r.z.nativeEnum(uc),creator:r.z.string().optional(),model:r.z.string().optional(),capabilities:r.z.array(hc).optional()}).optional(),uaid:r.z.string().optional()}).catchall(fc),bc=r.z.object({uaid:r.z.string().optional(),ledgerAccountId:r.z.string().optional(),userId:r.z.string().optional(),email:r.z.string().optional(),encryptedShare:r.z.string()}),wc=r.z.object({algorithm:r.z.string(),ciphertext:r.z.string(),nonce:r.z.string(),associatedData:r.z.string().optional(),keyLocator:r.z.object({sessionId:r.z.string().optional(),revision:r.z.number().optional()}).optional(),recipients:r.z.array(bc)}),Ic=r.z.object({keyType:r.z.string(),publicKey:r.z.string(),uaid:r.z.string().optional(),ledgerAccountId:r.z.string().optional(),userId:r.z.string().optional(),email:r.z.string().optional()}),Tc=r.z.object({role:r.z.enum(["requester","responder"]),uaid:r.z.string().optional(),userId:r.z.string().optional(),ledgerAccountId:r.z.string().optional(),keyType:r.z.string(),longTermPublicKey:r.z.string().optional(),ephemeralPublicKey:r.z.string(),signature:r.z.string().optional(),metadata:r.z.record(fc).optional(),submittedAt:r.z.string()}),Sc=r.z.object({sessionId:r.z.string(),algorithm:r.z.string(),createdAt:r.z.string(),expiresAt:r.z.number(),status:r.z.enum(["pending","complete"]),requester:Tc.optional(),responder:Tc.optional()}),kc=r.z.object({enabled:r.z.boolean(),algorithm:r.z.string(),requireCiphertext:r.z.boolean(),requester:Ic.nullable().optional(),responder:Ic.nullable().optional(),handshake:Sc.nullable().optional()}),Ec=r.z.object({messageId:r.z.string(),role:r.z.enum(["user","agent"]),content:r.z.string(),timestamp:r.z.string(),cipherEnvelope:wc.optional(),metadata:r.z.record(fc).optional()}),Ac=r.z.record(r.z.array(fc)).optional(),vc=r.z.object({id:r.z.string(),uaid:r.z.string(),registry:r.z.string(),name:r.z.string(),description:r.z.string().optional(),capabilities:r.z.array(gc),endpoints:r.z.union([r.z.record(fc),r.z.array(r.z.string())]).optional(),metadata:r.z.record(fc).optional(),metadataFacet:Ac,profile:yc.optional(),protocols:r.z.array(r.z.string()).optional(),adapter:r.z.string().optional(),originalId:r.z.string().optional(),communicationSupported:r.z.boolean().optional(),routingSupported:r.z.boolean().optional(),available:r.z.boolean().optional(),availabilityStatus:r.z.string().optional(),availabilityCheckedAt:r.z.string().optional(),availabilitySource:r.z.string().optional(),availabilityLatencyMs:r.z.number().optional(),availabilityScore:r.z.number().optional(),capabilityLabels:r.z.array(r.z.string()).optional(),capabilityTokens:r.z.array(r.z.string()).optional(),image:r.z.string().optional(),createdAt:r.z.string().optional(),updatedAt:r.z.string().optional(),lastSeen:r.z.string().optional(),lastIndexed:r.z.string().optional()}).passthrough(),Cc=r.z.object({hits:r.z.array(vc),total:r.z.number(),page:r.z.number(),limit:r.z.number()}),xc=r.z.object({totalAgents:r.z.number(),registries:r.z.record(r.z.number()),capabilities:r.z.record(r.z.number()),lastUpdate:r.z.string(),status:r.z.string()}),Rc=r.z.object({registries:r.z.array(r.z.string())}),Nc=r.z.object({searches:r.z.array(r.z.string())}),_c=r.z.object({agent:vc}),Pc=r.z.object({sessionId:r.z.string(),uaid:r.z.string().nullable().optional(),agent:r.z.object({name:r.z.string(),description:r.z.string().optional(),capabilities:r.z.record(fc).nullable().optional(),skills:r.z.array(r.z.string()).optional()}),history:r.z.array(Ec),historyTtlSeconds:r.z.number().nullable().optional(),encryption:kc.nullable().optional()}),Fc=r.z.object({sessionId:r.z.string(),uaid:r.z.string().nullable().optional(),message:r.z.string(),timestamp:r.z.string(),rawResponse:fc.optional(),content:r.z.string().optional(),history:r.z.array(Ec).optional(),historyTtlSeconds:r.z.number().nullable().optional(),encrypted:r.z.boolean().optional()}),Oc=r.z.object({sessionId:r.z.string(),history:r.z.array(Ec),historyTtlSeconds:r.z.number()});r.z.object({preserveEntries:r.z.number().int().min(0).optional()}).strict();const zc=r.z.object({sessionId:r.z.string(),history:r.z.array(Ec),summaryEntry:Ec,preservedEntries:r.z.array(Ec),historyTtlSeconds:r.z.number(),creditsDebited:r.z.number(),metadata:r.z.record(fc).optional()}),Dc=r.z.object({sessionId:r.z.string(),encryption:kc.nullable()}),Bc=r.z.object({sessionId:r.z.string(),handshake:Sc}),Mc=r.z.object({id:r.z.string(),keyType:r.z.string(),publicKey:r.z.string(),uaid:r.z.string().nullable(),ledgerAccountId:r.z.string().nullable(),ledgerNetwork:r.z.string().nullable().optional(),userId:r.z.string().nullable().optional(),email:r.z.string().nullable().optional(),createdAt:r.z.string(),updatedAt:r.z.string()}),Uc=r.z.object({challengeId:r.z.string(),message:r.z.string(),expiresAt:r.z.string()}),Kc=r.z.object({id:r.z.string(),label:r.z.string().optional(),prefix:r.z.string(),lastFour:r.z.string(),createdAt:r.z.string(),lastUsedAt:r.z.string().nullable().optional(),ownerType:r.z.literal("ledger"),ledgerAccountId:r.z.string().optional(),ledgerNetwork:r.z.string().optional(),ledgerNetworkCanonical:r.z.string().optional()}),Lc=r.z.object({key:r.z.string(),apiKey:Kc,accountId:r.z.string(),network:r.z.string(),networkCanonical:r.z.string().optional()}),$c=r.z.object({protocols:r.z.array(r.z.string())}),Hc=r.z.object({protocol:r.z.string().nullable()}),qc=r.z.object({hits:r.z.array(vc),total:r.z.number(),page:r.z.number().optional(),limit:r.z.number().optional()}),jc=r.z.union([r.z.string(),r.z.number()]),Wc=r.z.object({capabilities:r.z.array(jc).optional(),type:r.z.enum(["ai-agents","mcp-servers"]).optional(),registry:r.z.string().optional(),protocols:r.z.array(r.z.string()).optional(),adapter:r.z.array(r.z.string()).optional()}).strict();r.z.object({query:r.z.string(),filter:Wc.optional(),limit:r.z.number().int().min(1).max(100).optional(),offset:r.z.number().int().min(0).optional()}).strict();const Vc=r.z.object({agent:vc,score:r.z.number().optional(),highlights:r.z.record(r.z.array(r.z.string())).optional()}),Gc=r.z.object({hits:r.z.array(Vc),total:r.z.number(),took:r.z.number(),totalAvailable:r.z.number().optional(),visible:r.z.number().optional(),limited:r.z.boolean().optional(),credits_used:r.z.number().optional()}),Jc=r.z.object({enabled:r.z.boolean(),healthy:r.z.boolean(),mode:r.z.enum(["disabled","initializing","healthy","degraded","error"]),lastUpdated:r.z.string(),details:r.z.record(r.z.any()).optional(),lastError:r.z.object({message:r.z.string(),stack:r.z.string().optional(),timestamp:r.z.string().optional()}).optional()}),Yc=r.z.object({storageMode:r.z.string(),vectorStatus:Jc}),Xc=r.z.object({clients:r.z.number(),stats:r.z.object({totalClients:r.z.number().optional(),clientsByRegistry:r.z.record(r.z.number()).optional(),clientsByEventType:r.z.record(r.z.number()).optional()}).passthrough()}),Zc=r.z.object({p50:r.z.number(),p90:r.z.number(),p95:r.z.number(),p99:r.z.number()}),Qc=r.z.object({http:r.z.object({requestsTotal:r.z.number(),activeConnections:r.z.number(),requestDuration:Zc}),search:r.z.object({queriesTotal:r.z.number(),queryDuration:Zc}),indexing:r.z.object({agentsTotal:r.z.number(),crawlErrors:r.z.number()}),registration:r.z.object({total:r.z.number(),failures:r.z.number(),duration:Zc}),cache:r.z.object({hits:r.z.number(),misses:r.z.number(),hitRate:r.z.number()}),websocket:r.z.object({connections:r.z.number()})}),el=r.z.object({uaid:r.z.string(),valid:r.z.boolean(),formats:r.z.array(r.z.string())}),tl=r.z.object({id:r.z.string(),agentId:r.z.string(),protocol:r.z.string(),endpoint:r.z.string(),status:r.z.enum(["connected","disconnected","error"]),metadata:r.z.record(mc).optional(),createdAt:r.z.string()}),rl=r.z.object({connected:r.z.boolean(),connection:tl.optional(),adapter:r.z.string().optional(),agentId:r.z.string().optional()}),il=r.z.object({operatorId:r.z.string().optional(),adapters:r.z.array(r.z.object({name:r.z.string(),version:r.z.string(),status:r.z.string(),agentCount:r.z.number(),lastDiscovery:r.z.string(),registryType:r.z.string(),health:r.z.string()})).optional(),totalAgents:r.z.number().optional(),elasticsearchDocumentCount:r.z.number().optional(),agentsByAdapter:r.z.record(r.z.number()).optional(),agentsByRegistry:r.z.record(r.z.number()).optional(),systemInfo:r.z.object({uptime:r.z.number().optional(),version:r.z.string().optional(),network:r.z.string().optional()}).optional()}),ol=r.z.object({id:r.z.string(),name:r.z.string(),type:r.z.string(),endpoint:r.z.string().optional(),capabilities:r.z.array(gc),registry:r.z.string().optional(),protocol:r.z.string().optional(),profile:yc.optional(),nativeId:r.z.string().optional(),metadata:r.z.record(fc).optional()}),nl=r.z.object({tId:r.z.string().nullable(),sizeBytes:r.z.number().optional()}),sl=r.z.object({topicId:r.z.string().optional(),sequenceNumber:r.z.number().optional(),profileReference:r.z.string().optional(),profileTopicId:r.z.string().optional()}).passthrough().nullable().optional(),al=r.z.object({registry:r.z.string(),status:r.z.enum(["created","duplicate","skipped","error","updated","pending"]),agentId:r.z.string().nullable().optional(),agentUri:r.z.string().nullable().optional(),error:r.z.string().optional(),metadata:r.z.record(fc).optional(),registryKey:r.z.string().optional(),networkId:r.z.string().optional(),networkName:r.z.string().optional(),chainId:r.z.number().optional(),estimatedCredits:r.z.number().nullable().optional(),gasEstimateCredits:r.z.number().nullable().optional(),gasEstimateUsd:r.z.number().nullable().optional(),gasPriceGwei:r.z.number().nullable().optional(),gasLimit:r.z.number().nullable().optional(),creditMode:r.z.enum(["fixed","gas"]).nullable().optional(),minCredits:r.z.number().nullable().optional(),consumedCredits:r.z.number().nullable().optional(),cost:r.z.object({credits:r.z.number(),usd:r.z.number(),eth:r.z.number(),gasUsedWei:r.z.string(),effectiveGasPriceWei:r.z.string().nullable().optional(),transactions:r.z.array(r.z.object({hash:r.z.string(),gasUsedWei:r.z.string(),effectiveGasPriceWei:r.z.string().nullable().optional(),costWei:r.z.string()})).optional()}).optional()}),cl=r.z.object({base:r.z.number(),additional:r.z.number(),total:r.z.number()}),ll=r.z.object({status:r.z.string(),uaid:r.z.string().optional(),transactionId:r.z.string().optional(),consensusTimestamp:r.z.string().optional(),registryTopicId:r.z.string().optional(),topicSequenceNumber:r.z.number().optional(),payloadHash:r.z.string().optional(),profileReference:r.z.string().optional(),tId:r.z.string().optional(),profileSizeBytes:r.z.number().optional(),error:r.z.string().optional()}).passthrough(),dl=r.z.object({key:r.z.string(),registryId:r.z.string().optional(),networkId:r.z.string().optional(),name:r.z.string().optional(),chainId:r.z.number().optional(),label:r.z.string().optional(),estimatedCredits:r.z.number().nullable().optional(),baseCredits:r.z.number().nullable().optional(),gasPortionCredits:r.z.number().nullable().optional(),gasPortionUsd:r.z.number().nullable().optional(),gasEstimateCredits:r.z.number().nullable().optional(),gasEstimateUsd:r.z.number().nullable().optional(),gasPriceGwei:r.z.number().nullable().optional(),gasLimit:r.z.number().nullable().optional(),minCredits:r.z.number().nullable().optional(),creditMode:r.z.string().nullable().optional()}).passthrough(),ul=r.z.object({id:r.z.string(),label:r.z.string(),networks:r.z.array(dl)}),pl=r.z.object({registries:r.z.array(ul)}),hl=r.z.object({success:r.z.literal(!0),status:r.z.enum(["created","duplicate","updated"]).optional(),uaid:r.z.string(),agentId:r.z.string(),message:r.z.string().optional(),registry:r.z.string().optional(),attemptId:r.z.string().nullable().optional(),agent:ol,openConvAI:r.z.object({compatible:r.z.boolean(),hcs11Profile:yc.optional(),bridgeEndpoint:r.z.string().optional()}).optional(),profile:nl.optional(),profileRegistry:sl.nullable().optional(),hcs10Registry:ll.nullable().optional(),credits:cl.optional(),additionalRegistries:r.z.array(al).optional(),additionalRegistryCredits:r.z.array(al).optional(),additionalRegistryCostPerRegistry:r.z.number().optional()}),gl=r.z.object({success:r.z.literal(!0),status:r.z.literal("pending"),message:r.z.string(),uaid:r.z.string(),agentId:r.z.string(),registry:r.z.string().optional(),attemptId:r.z.string().nullable(),agent:ol,openConvAI:r.z.object({compatible:r.z.boolean(),hcs11Profile:yc.optional(),bridgeEndpoint:r.z.string().optional()}).optional(),profile:nl.optional(),profileRegistry:sl.nullable().optional(),hcs10Registry:ll.nullable().optional(),credits:cl,additionalRegistries:r.z.array(al),additionalRegistryCredits:r.z.array(al).optional(),additionalRegistryCostPerRegistry:r.z.number().optional()}),ml=r.z.object({success:r.z.literal(!1),status:r.z.literal("partial"),message:r.z.string(),uaid:r.z.string(),agentId:r.z.string(),registry:r.z.string().optional(),attemptId:r.z.string().nullable().optional(),agent:ol,openConvAI:r.z.object({compatible:r.z.boolean(),hcs11Profile:yc.optional(),bridgeEndpoint:r.z.string().optional()}).optional(),profile:nl.optional(),profileRegistry:sl.nullable().optional(),hcs10Registry:ll.nullable().optional(),credits:cl.optional(),additionalRegistries:r.z.array(al).optional(),additionalRegistryCredits:r.z.array(al).optional(),additionalRegistryCostPerRegistry:r.z.number().optional(),errors:r.z.array(r.z.object({registry:r.z.string(),registryKey:r.z.string().nullable().optional(),error:r.z.string()})).min(1)}),fl=r.z.union([hl,gl,ml]),yl=r.z.object({registryId:r.z.string(),registryKey:r.z.string(),networkId:r.z.string().optional(),networkName:r.z.string().optional(),chainId:r.z.number().optional(),label:r.z.string().optional(),status:r.z.enum(["pending","in_progress","completed","failed"]),error:r.z.string().optional(),credits:r.z.number().nullable().optional(),agentId:r.z.string().nullable().optional(),agentUri:r.z.string().nullable().optional(),metadata:r.z.record(fc).optional(),lastUpdated:r.z.string()}),bl=r.z.object({attemptId:r.z.string(),mode:r.z.enum(["register","update"]),status:r.z.enum(["pending","partial","completed","failed"]),uaid:r.z.string().optional(),agentId:r.z.string().optional(),registryNamespace:r.z.string(),accountId:r.z.string().optional(),startedAt:r.z.string(),completedAt:r.z.string().optional(),primary:r.z.object({status:r.z.enum(["pending","completed","failed"]),finishedAt:r.z.string().optional(),error:r.z.string().optional()}),additionalRegistries:r.z.record(r.z.string(),yl),errors:r.z.array(r.z.string()).optional()}),wl=r.z.object({progress:bl}),Il=r.z.object({accountId:r.z.string().nullable().optional(),registry:r.z.string().optional(),protocol:r.z.string().optional(),requiredCredits:r.z.number(),availableCredits:r.z.number().nullable().optional(),shortfallCredits:r.z.number().nullable().optional(),creditsPerHbar:r.z.number().nullable().optional(),estimatedHbar:r.z.number().nullable().optional()}),Tl=r.z.object({success:r.z.boolean().optional(),purchaser:r.z.string(),credits:r.z.number(),hbarAmount:r.z.number(),transactionId:r.z.string(),consensusTimestamp:r.z.string().nullable().optional()}),Sl=r.z.object({success:r.z.boolean().optional(),transaction:r.z.string().optional(),network:r.z.string().optional(),payer:r.z.string().optional(),errorReason:r.z.string().optional()}).strict(),kl=r.z.object({success:r.z.boolean(),accountId:r.z.string(),creditedCredits:r.z.number(),usdAmount:r.z.number(),balance:r.z.number(),payment:r.z.object({payer:r.z.string().optional(),requirement:r.z.record(fc).optional(),settlement:Sl.optional()}).optional()}),El=r.z.object({minimums:r.z.record(r.z.object({network:r.z.string().optional(),gasLimit:r.z.number().optional(),gasPriceWei:r.z.string().optional(),gasUsd:r.z.number().optional(),minUsd:r.z.number().optional(),ethUsd:r.z.number().optional(),fetchedAt:r.z.string().optional(),source:r.z.string().optional()})).optional(),creditUnitUsd:r.z.number().optional()}),Al=r.z.object({adapters:r.z.array(r.z.string())}),vl=r.z.object({supportsChat:r.z.boolean(),delivery:r.z.string().optional(),transport:r.z.string().optional(),streaming:r.z.boolean().optional(),requiresAuth:r.z.array(r.z.string()).optional(),notes:r.z.string().optional()}),Cl=r.z.object({discovery:r.z.boolean(),routing:r.z.boolean(),communication:r.z.boolean(),translation:r.z.boolean(),protocols:r.z.array(r.z.string())}),xl=r.z.object({id:r.z.string(),name:r.z.string(),version:r.z.string(),author:r.z.string(),description:r.z.string(),supportedProtocols:r.z.array(r.z.string()),registryType:r.z.enum(["web2","web3","hybrid"]),chatProfile:vl.optional(),capabilities:Cl,enabled:r.z.boolean(),priority:r.z.number(),status:r.z.enum(["running","stopped"])}),Rl=r.z.object({adapters:r.z.array(xl)}),Nl=r.z.object({value:r.z.union([r.z.string(),r.z.number(),r.z.boolean()]),label:r.z.string()}),_l=r.z.object({key:r.z.string(),label:r.z.string(),description:r.z.string().optional(),type:r.z.enum(["string","boolean","number"]),adapters:r.z.array(r.z.string()).optional(),options:r.z.array(Nl).optional()}),Pl=r.z.object({facets:r.z.array(_l)}),Fl=e=>new Error(`${e} is not supported by the in-memory signer`),Ol=e=>{if(!e.privateKey)throw new Error("privateKey is required to create a ledger signer.");if(!e.accountId)throw new Error("accountId is required to create a ledger signer.");const t=i.AccountId.fromString(e.accountId),r=i.PrivateKey.fromString(e.privateKey),o=i.LedgerId.fromString(e.network);return{getLedgerId:()=>o,getAccountId:()=>t,getAccountKey:()=>r.publicKey,getNetwork:()=>({}),getMirrorNetwork:()=>[],sign:async e=>Promise.all(e.map(async e=>{const o=await r.sign(e);return new i.SignerSignature({publicKey:r.publicKey,signature:o,accountId:t})})),getAccountBalance:async()=>{throw Fl("getAccountBalance")},getAccountInfo:async()=>{throw Fl("getAccountInfo")},getAccountRecords:async()=>{throw Fl("getAccountRecords")},signTransaction:async e=>{throw Fl("signTransaction")},checkTransaction:async e=>{throw Fl("checkTransaction")},populateTransaction:async e=>{throw Fl("populateTransaction")},call:async e=>{throw Fl("call")}}},zl=()=>"function"==typeof DOMException?new DOMException("Aborted","AbortError"):new Error("The operation was aborted"),Dl=/application\/json/i,Bl=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:Bl(e));if("object"==typeof e){const t={};return Object.entries(e).forEach(([e,r])=>{void 0!==r&&(t[e]=Bl(r))}),t}throw new TypeError("Only JSON-compatible values are supported")},Ml=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),Ul=e=>{const t=Bl(e);if(Ml(t))return t;throw new TypeError("Expected JSON object value")},Kl=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},Ll=e=>{const t={profile:Ul(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=Ul(e.metadata)),t};class $l extends Error{constructor(e,t){super(e),this.status=t.status,this.statusText=t.statusText,this.body=t.body}}class Hl extends Error{constructor(e,t,r){super(e),this.cause=t,this.rawValue=r}}class ql{constructor(e={}){this.conversationContexts=new Map,this.request=async(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 o=await this.fetchImpl(this.buildUrl(e),i);if(o.ok)return o;const n=await this.extractErrorBody(o);throw new $l("Registry broker request failed",{status:o.status,statusText:o.statusText,body:n})},this.baseUrl=function(e){const t=e?.trim();let r=t&&t.length>0?t:"https://hol.org/registry/api/v1";try{const e=new URL(r.replace(/\/+$/,"")),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=r.replace(/\/+$/,"");return/\/api\/v\d+$/i.test(i)?i:/\/api$/i.test(i)?`${i}/v1`:`${i}/api/v1`}(e.baseUrl);const t=e.fetchImplementation??globalThis.fetch;if(!t)throw new Error("A fetch implementation is required for RegistryBrokerClient");this.fetchImpl=t,this.defaultHeaders={},e.defaultHeaders&&Object.entries(e.defaultHeaders).forEach(([e,t])=>{"string"==typeof t&&this.setDefaultHeader(e,t)}),e.apiKey&&e.apiKey.trim().length>0&&this.setApiKey(e.apiKey),e.ledgerApiKey&&e.ledgerApiKey.trim().length>0&&this.setLedgerApiKey(e.ledgerApiKey),this.registrationAutoTopUp=e.registrationAutoTopUp,this.historyAutoTopUp=e.historyAutoTopUp,this.encryptedChatManager=new jl(this),this.encryptionOptions=e.encryption,this.encryptionBootstrapPromise=this.bootstrapEncryptionOptions(e.encryption),this.chat={start:e=>this.startChat(e),createSession:e=>this.createSession(e),sendMessage:e=>this.sendMessage(e),endSession:e=>this.endSession(e),getHistory:(e,t)=>this.fetchHistorySnapshot(e,t),compactHistory:e=>this.compactHistory(e),getEncryptionStatus:e=>this.fetchEncryptionStatus(e),submitEncryptionHandshake:(e,t)=>this.postEncryptionHandshake(e,t),startConversation:e=>this.startConversation(e),acceptConversation:e=>this.acceptConversation(e)},this.encryption={registerKey:e=>this.registerEncryptionKey(e),generateEphemeralKeyPair:()=>this.createEphemeralKeyPair(),deriveSharedSecret:e=>this.deriveSharedSecret(e),encryptCipherEnvelope:e=>this.buildCipherEnvelope(e),decryptCipherEnvelope:e=>this.openCipherEnvelope(e),ensureAgentKey:e=>this.ensureAgentEncryptionKey(e)},this.chat.createEncryptedSession=e=>this.encryptedChatManager.startSession(e),this.chat.acceptEncryptedSession=e=>this.encryptedChatManager.acceptSession(e)}static async initializeAgent(e){const{uaid:t,ensureEncryptionKey:r=!0,...i}=e,o=new ql(i);let n=null;if(r){const e="object"==typeof r?r:{generateIfMissing:!0};n=await o.encryption.ensureAgentKey({uaid:t,...e})}return{client:o,encryption:n}}setApiKey(e){this.setDefaultHeader("x-api-key",e)}setLedgerApiKey(e){this.setDefaultHeader("x-ledger-api-key",e)}setDefaultHeader(e,t){if(!e||0===e.trim().length)return;const r=(e=>e.trim().toLowerCase())(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}async search(e={}){const t=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}`:""}(e),r=await this.requestJson(`/search${t}`,{method:"GET"});return this.parseWithSchema(r,Cc,"search response")}async stats(){const e=await this.requestJson("/stats",{method:"GET"});return this.parseWithSchema(e,xc,"stats response")}async registries(){const e=await this.requestJson("/registries",{method:"GET"});return this.parseWithSchema(e,Rc,"registries response")}async getAdditionalRegistries(){const e=await this.requestJson("/register/additional-registries",{method:"GET"});return this.parseWithSchema(e,pl,"additional registry catalog response")}bootstrapEncryptionOptions(e){return e?.autoRegister&&!1!==e.autoRegister.enabled?this.autoRegisterEncryptionKey(e.autoRegister).then(()=>{}):null}async autoRegisterEncryptionKey(e){const t=this.normalizeAutoRegisterIdentity(e);if(!t)throw new Error("Auto-registration requires uaid, ledgerAccountId, or email");const r=await this.resolveAutoRegisterKeyMaterial(e);if(!r)throw new Error("Unable to resolve encryption public key for auto-registration");return await this.registerEncryptionKey({keyType:e.keyType??"secp256k1",publicKey:r.publicKey,...t}),r}normalizeAutoRegisterIdentity(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}async resolveAutoRegisterKeyMaterial(e){if(e.publicKey?.trim())return{publicKey:e.publicKey.trim()};let t=e.privateKey?.trim();const r=e.envVar??"RB_ENCRYPTION_PRIVATE_KEY";if(!t&&r&&process?.env?.[r]?.trim()&&(t=process.env[r]?.trim()),!t&&e.generateIfMissing){const t=await this.generateEncryptionKeyPair({keyType:e.keyType??"secp256k1",envVar:r,envPath:e.envPath,overwrite:e.overwriteEnv});return r&&(process.env[r]=t.privateKey),{publicKey:t.publicKey,privateKey:t.privateKey}}if(t){return{publicKey:this.derivePublicKeyFromPrivateKey(t),privateKey:t}}return null}derivePublicKeyFromPrivateKey(e){const t=this.hexToBuffer(e),r=h.secp256k1.getPublicKey(t,!0);return u.Buffer.from(r).toString("hex")}ensureAgentEncryptionKey(e){return this.autoRegisterEncryptionKey({...e,uaid:e.uaid,enabled:!0})}async popularSearches(){const e=await this.requestJson("/popular",{method:"GET"});return this.parseWithSchema(e,Nc,"popular searches response")}async resolveUaid(e){const t=await this.requestJson(`/resolve/${encodeURIComponent(e)}`,{method:"GET"});return this.parseWithSchema(t,_c,"resolve UAID response")}async performRegisterAgent(e){const t=await this.requestJson("/register",{method:"POST",body:Ll(e),headers:{"content-type":"application/json"}});return this.parseWithSchema(t,fl,"register agent response")}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(o){if(this.extractInsufficientCreditsDetails(o)&&!i){await this.ensureCreditsForRegistration(e,r),i=!0;continue}throw o}}async getRegistrationQuote(e){const t=await this.requestJson("/register/quote",{method:"POST",body:Ll(e),headers:{"content-type":"application/json"}});return this.parseWithSchema(t,Il,"registration quote response")}async updateAgent(e,t){const r=await this.requestJson(`/register/${encodeURIComponent(e)}`,{method:"PUT",body:Ll(t),headers:{"content-type":"application/json"}});return this.parseWithSchema(r,fl,"update agent response")}async getRegistrationProgress(e){const t=e.trim();if(!t)throw new Error("attemptId is required");try{const e=await this.requestJson(`/register/progress/${encodeURIComponent(t)}`,{method:"GET"});return this.parseWithSchema(e,wl,"registration progress response").progress}catch(r){if(r instanceof $l&&404===r.status)return null;throw r}}async waitForRegistrationCompletion(e,t={}){const r=e.trim();if(!r)throw new Error("attemptId is required");const i=Math.max(250,t.intervalMs??1500),o=t.timeoutMs??3e5,n=t.throwOnFailure??!0,s=t.signal,a=Date.now();for(;;){if(s?.aborted)throw zl();const e=await this.getRegistrationProgress(r);if(e){if(t.onProgress?.(e),"completed"===e.status)return e;if("partial"===e.status||"failed"===e.status){if(n)throw new $l("Registration did not complete successfully",{status:409,statusText:e.status,body:e});return e}}if(Date.now()-a>=o)throw new Error(`Registration progress polling timed out after ${o}ms`);await this.delay(i,s)}}async purchaseCreditsWithHbar(e){const t={accountId:e.accountId,payerKey:e.privateKey,hbarAmount:this.calculateHbarAmountParam(e.hbarAmount)};e.memo&&(t.memo=e.memo),e.metadata&&(t.metadata=e.metadata);const r=await this.requestJson("/credits/purchase",{method:"POST",headers:{"content-type":"application/json"},body:t});return this.parseWithSchema(r,Tl,"credit purchase response")}async getX402Minimums(){const e=await this.requestJson("/credits/purchase/x402/minimums",{method:"GET"});return this.parseWithSchema(e,El,"x402 minimums response")}async purchaseCreditsWithX402(e){if(!Number.isFinite(e.credits)||e.credits<=0)throw new Error("credits must be a positive number");if(void 0!==e.usdAmount&&(!Number.isFinite(e.usdAmount)||e.usdAmount<=0))throw new Error("usdAmount must be a positive number when provided");const t={accountId:e.accountId,credits:e.credits};void 0!==e.usdAmount&&(t.usdAmount=e.usdAmount),e.description&&(t.description=e.description),e.metadata&&(t.metadata=e.metadata);const r=o.create({baseURL:this.baseUrl,headers:{...this.getDefaultHeaders(),"content-type":"application/json"}}),i=m.withPaymentInterceptor(r,e.walletClient),n=await i.post("/credits/purchase/x402",t),s=this.parseWithSchema(n.data,kl,"x402 credit purchase response"),a="string"==typeof n.headers["x-payment-response"]?n.headers["x-payment-response"]:void 0;return{...s,paymentResponseHeader:a,paymentResponse:void 0!==a?m.decodeXPaymentResponse(a):void 0}}async buyCreditsWithX402(e){const t=e.network??"base",r=(e=>{const t=e.trim();if(!t)throw new Error("evmPrivateKey is required");return t.startsWith("0x")?t:`0x${t}`})(e.evmPrivateKey),i=await f.createSigner(t,r);return this.purchaseCreditsWithX402({accountId:e.accountId,credits:e.credits,usdAmount:e.usdAmount,description:e.description,metadata:e.metadata,walletClient:i})}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)}calculateHbarAmountParam(e){const t=Math.ceil(1e8*e);if(t<=0)throw new Error("Calculated purchase amount must be positive");return t/1e8}shouldAutoTopUpHistory(e,t){if(!this.historyAutoTopUp||void 0===e.historyTtlSeconds)return!1;if(!(t instanceof $l))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")}extractErrorMessage(e){return"string"==typeof e?e:Ml(e)&&"string"==typeof e.error?e.error:Ml(e)&&"string"==typeof e.message?e.message:void 0}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}})}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 o=this.resolveCreditsToPurchase(i);if(o<=0)return;const n=t.creditsPerHbar??null;if(!n||n<=0)throw new Error("Unable to determine credits per HBAR for auto top-up");const s=this.calculateHbarAmount(o,n);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:o}})}if(((await this.getRegistrationQuote(e)).shortfallCredits??0)>0)throw new Error("Unable to purchase sufficient credits for registration")}extractInsufficientCreditsDetails(e){if(!(e instanceof $l)||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}}async createLedgerChallenge(e){const t=dc(e.network),r="hedera"===t.kind?t.hederaNetwork??t.canonical:t.canonical,i=await this.requestJson("/auth/ledger/challenge",{method:"POST",headers:{"content-type":"application/json"},body:{accountId:e.accountId,network:r}});return this.parseWithSchema(i,Uc,"ledger challenge response")}async verifyLedgerChallenge(e){const t=dc(e.network),r="hedera"===t.kind?t.hederaNetwork??t.canonical:t.canonical,i={challengeId:e.challengeId,accountId:e.accountId,network:r,signature:e.signature};e.signatureKind&&(i.signatureKind=e.signatureKind),e.publicKey&&(i.publicKey=e.publicKey),"number"==typeof e.expiresInMinutes&&(i.expiresInMinutes=e.expiresInMinutes);const o=await this.requestJson("/auth/ledger/verify",{method:"POST",headers:{"content-type":"application/json"},body:i}),n=this.parseWithSchema(o,Lc,"ledger verification response");return this.setLedgerApiKey(n.key),n}async authenticateWithLedger(e){const t=await this.createLedgerChallenge({accountId:e.accountId,network:e.network}),r=await this.resolveLedgerAuthSignature(t.message,e);return await this.verifyLedgerChallenge({challengeId:t.challengeId,accountId:e.accountId,network:e.network,signature:r.signature,signatureKind:r.signatureKind,publicKey:r.publicKey,expiresInMinutes:e.expiresInMinutes})}async resolveLedgerAuthSignature(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=u.Buffer.from(e,"utf8"),i=await t.signer.sign([r]),o=i?.[0];if(!o)throw new Error("Signer did not return any signatures.");let n;if(o.publicKey)n=o.publicKey.toString();else if("function"==typeof t.signer.getAccountKey){const e=await t.signer.getAccountKey();e&&"function"==typeof e.toString&&(n=e.toString())}return{signature:u.Buffer.from(o.signature).toString("base64"),signatureKind:"raw",publicKey:n}}async authenticateWithLedgerCredentials(e){const{accountId:t,network:r,signer:i,sign:o,hederaPrivateKey:n,evmPrivateKey:s,expiresInMinutes:a,setAccountHeader:c=!0,label:l,logger:d}=e,u=dc(r),p=l?` for ${l}`:"",h={accountId:t,network:u.canonical,expiresInMinutes:a};if(o)h.sign=o;else if(i)h.signer=i;else if(n){if("hedera"!==u.kind||!u.hederaNetwork)throw new Error("hederaPrivateKey can only be used with hedera:mainnet or hedera:testnet networks.");h.signer=Ol({accountId:t,privateKey:n,network:u.hederaNetwork})}else{if(!s)throw new Error("Provide a signer, sign function, hederaPrivateKey, or evmPrivateKey to authenticate with the ledger.");{if("evm"!==u.kind)throw new Error("evmPrivateKey can only be used with CAIP-2 EVM networks (eip155:<chainId>).");const e=s.startsWith("0x")?s:`0x${s}`,t=g.privateKeyToAccount(e);h.sign=async e=>({signature:await t.signMessage({message:e}),signatureKind:"evm",publicKey:t.publicKey})}}d?.info?.(`Authenticating ledger account ${t} (${u.canonical})${p}...`);const m=await this.authenticateWithLedger(h);return c&&this.setDefaultHeader("x-account-id",m.accountId),d?.info?.(`Ledger authentication complete${p}. Issued key prefix: ${m.apiKey.prefix}…${m.apiKey.lastFour}`),m}async listProtocols(){const e=await this.requestJson("/protocols",{method:"GET"});return this.parseWithSchema(e,$c,"protocols response")}async detectProtocol(e){const t=await this.requestJson("/detect-protocol",{method:"POST",body:{message:e},headers:{"content-type":"application/json"}});return this.parseWithSchema(t,Hc,"detect protocol response")}async registrySearchByNamespace(e,t){const r=new URLSearchParams;t&&r.set("q",t);const i=r.size>0?`?${r.toString()}`:"",o=await this.requestJson(`/registries/${encodeURIComponent(e)}/search${i}`,{method:"GET"});return this.parseWithSchema(o,qc,"registry search response")}async vectorSearch(e){try{const t=await this.requestJson("/search",{method:"POST",body:e,headers:{"content-type":"application/json"}});return this.parseWithSchema(t,Gc,"vector search response")}catch(t){if(t instanceof $l&&501===t.status){const t=await this.search(this.buildVectorFallbackSearchParams(e));return this.convertSearchResultToVectorResponse(t)}throw t}}async searchStatus(){const e=await this.requestJson("/search/status",{method:"GET"});return this.parseWithSchema(e,Yc,"search status response")}async adaptersDetailed(){const e=await this.requestJson("/adapters/details",{method:"GET"});return this.parseWithSchema(e,Rl,"adapter details response")}async websocketStats(){const e=await this.requestJson("/websocket/stats",{method:"GET"});return this.parseWithSchema(e,Xc,"websocket stats response")}async metricsSummary(){const e=await this.requestJson("/metrics",{method:"GET"});return this.parseWithSchema(e,Qc,"metrics summary response")}async validateUaid(e){const t=await this.requestJson(`/uaids/validate/${encodeURIComponent(e)}`,{method:"GET"});return this.parseWithSchema(t,el,"UAID validation response")}async getUaidConnectionStatus(e){const t=await this.requestJson(`/uaids/connections/${encodeURIComponent(e)}/status`,{method:"GET"});return this.parseWithSchema(t,rl,"UAID connection status")}async closeUaidConnection(e){await this.request(`/uaids/connections/${encodeURIComponent(e)}`,{method:"DELETE"})}async dashboardStats(){const e=await this.requestJson("/dashboard/stats",{method:"GET"});return this.parseWithSchema(e,il,"dashboard stats response")}async adapters(){const e=await this.requestJson("/adapters",{method:"GET"});return this.parseWithSchema(e,Al,"adapters response")}async facets(e){const t=new URLSearchParams;e&&t.set("adapter",e);const r=t.size>0?`?${t.toString()}`:"",i=await this.requestJson(`/search/facets${r}`,{method:"GET"});return this.parseWithSchema(i,Pl,"search facets response")}async createSession(e,t=!0){const r={};"uaid"in e&&e.uaid&&(r.uaid=e.uaid),"agentUrl"in e&&e.agentUrl&&(r.agentUrl=e.agentUrl),e.auth&&(r.auth=Kl(e.auth)),void 0!==e.historyTtlSeconds&&(r.historyTtlSeconds=e.historyTtlSeconds),void 0!==e.encryptionRequested&&(r.encryptionRequested=e.encryptionRequested),e.senderUaid&&(r.senderUaid=e.senderUaid);try{const e=await this.requestJson("/chat/session",{method:"POST",body:r,headers:{"content-type":"application/json"}});return this.parseWithSchema(e,Pc,"chat session response")}catch(i){if(t&&this.shouldAutoTopUpHistory(e,i))return await this.executeHistoryAutoTopUp("chat.session"),this.createSession(e,!1);throw i}}async startChat(e){if("uaid"in e&&e.uaid)return this.startConversation({uaid:e.uaid,senderUaid:e.senderUaid,historyTtlSeconds:e.historyTtlSeconds,auth:e.auth,encryption:e.encryption,onSessionCreated:e.onSessionCreated});if("agentUrl"in e&&e.agentUrl){const t=await this.createSession({agentUrl:e.agentUrl,auth:e.auth,historyTtlSeconds:e.historyTtlSeconds,senderUaid:e.senderUaid});return e.onSessionCreated?.(t.sessionId),this.createPlaintextConversationHandle(t.sessionId,t.encryption??null,e.auth,{agentUrl:e.agentUrl,uaid:e.uaid})}throw new Error("startChat requires either uaid or agentUrl")}async startConversation(e){const t=e.encryption?.preference??"preferred";if(!("disabled"!==t)){const t=await this.createSession({uaid:e.uaid,auth:e.auth,historyTtlSeconds:e.historyTtlSeconds,senderUaid:e.senderUaid,encryptionRequested:!1});return e.onSessionCreated?.(t.sessionId),this.createPlaintextConversationHandle(t.sessionId,t.encryption??null,e.auth,{uaid:e.uaid})}try{return await this.encryptedChatManager.startSession({uaid:e.uaid,senderUaid:e.senderUaid,historyTtlSeconds:e.historyTtlSeconds,handshakeTimeoutMs:e.encryption?.handshakeTimeoutMs,pollIntervalMs:e.encryption?.pollIntervalMs,onSessionCreated:t=>{e.onSessionCreated?.(t)},auth:e.auth})}catch(r){if(r instanceof Wl){if("required"===t)throw r;return this.createPlaintextConversationHandle(r.sessionId,r.summary??null,e.auth,{uaid:e.uaid})}throw r}}async acceptConversation(e){const t=e.encryption?.preference??"preferred";if("disabled"===t)return this.createPlaintextConversationHandle(e.sessionId,null);try{return await this.encryptedChatManager.acceptSession({sessionId:e.sessionId,responderUaid:e.responderUaid,handshakeTimeoutMs:e.encryption?.handshakeTimeoutMs,pollIntervalMs:e.encryption?.pollIntervalMs})}catch(r){if(r instanceof Wl&&"required"!==t)return this.createPlaintextConversationHandle(e.sessionId,null,void 0,{uaid:e.responderUaid});throw r}}async fetchHistorySnapshot(e,t){if(!e||0===e.trim().length)throw new Error("sessionId is required to fetch chat history");const r=await this.requestJson(`/chat/session/${encodeURIComponent(e)}/history`,{method:"GET"}),i=this.parseWithSchema(r,Oc,"chat history snapshot response");return this.attachDecryptedHistory(e,i,t)}attachDecryptedHistory(e,t,r){if(!(void 0!==r?.decrypt?r.decrypt:!0===this.encryptionOptions?.autoDecryptHistory))return t;const i=this.resolveDecryptionContext(e,r);if(!i)throw new Error("Unable to decrypt chat history: encryption context unavailable");const o=t.history.map(t=>({entry:t,plaintext:this.decryptHistoryEntryFromContext(e,t,i)}));return{...t,decryptedHistory:o}}registerConversationContext(e){const t={sessionId:e.sessionId,sharedSecret:u.Buffer.from(e.sharedSecret),identity:e.identity?{...e.identity}:void 0},r=this.conversationContexts.get(e.sessionId)??[],i=r.findIndex(e=>this.identitiesMatch(e.identity,t.identity));i>=0?r[i]=t:r.push(t),this.conversationContexts.set(e.sessionId,r)}registerConversationContextForEncryption(e){this.registerConversationContext(e)}resolveDecryptionContext(e,t){if(t?.sharedSecret)return{sessionId:e,sharedSecret:this.normalizeSharedSecret(t.sharedSecret),identity:t.identity};const r=this.conversationContexts.get(e);if(!r||0===r.length)return null;if(t?.identity){const e=r.find(e=>this.identitiesMatch(e.identity,t.identity));if(e)return e}return r[0]}decryptHistoryEntryFromContext(e,t,r){const i=t.cipherEnvelope;if(!i)return t.content;const o=u.Buffer.from(r.sharedSecret);try{return this.encryption.decryptCipherEnvelope({envelope:i,sharedSecret:o})}catch(n){return null}}identitiesMatch(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()))))}identityMatchesRecipient(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())))}createPlaintextConversationHandle(e,t,r,i){const o=i?.uaid?.trim(),n=i?.agentUrl?.trim();return{sessionId:e,mode:"plaintext",summary:t??null,send:async t=>{const i=t.plaintext;if(!i||0===i.trim().length)throw new Error("plaintext is required for chat messages");const s=t.message??i;return this.sendMessage({sessionId:e,message:s,streaming:t.streaming,auth:t.auth??r,uaid:o,agentUrl:n})},decryptHistoryEntry:e=>e.content}}async compactHistory(e){if(!e.sessionId||0===e.sessionId.trim().length)throw new Error("sessionId is required to compact chat history");const t={};"number"==typeof e.preserveEntries&&Number.isFinite(e.preserveEntries)&&e.preserveEntries>=0&&(t.preserveEntries=Math.floor(e.preserveEntries));const r=await this.requestJson(`/chat/session/${encodeURIComponent(e.sessionId)}/compact`,{method:"POST",headers:{"content-type":"application/json"},body:t});return this.parseWithSchema(r,zc,"chat history compaction response")}async fetchEncryptionStatus(e){if(!e||0===e.trim().length)throw new Error("sessionId is required for encryption status");const t=await this.requestJson(`/chat/session/${encodeURIComponent(e)}/encryption`,{method:"GET"});return this.parseWithSchema(t,Dc,"session encryption status response")}async postEncryptionHandshake(e,t){if(!e||0===e.trim().length)throw new Error("sessionId is required for encryption handshake");const r=await this.requestJson(`/chat/session/${encodeURIComponent(e)}/encryption-handshake`,{method:"POST",headers:{"content-type":"application/json"},body:{role:t.role,keyType:t.keyType,ephemeralPublicKey:t.ephemeralPublicKey,longTermPublicKey:t.longTermPublicKey,signature:t.signature,uaid:t.uaid,userId:t.userId,ledgerAccountId:t.ledgerAccountId,metadata:t.metadata}});return this.parseWithSchema(r,Bc,"encryption handshake response").handshake}async registerEncryptionKey(e){const t=await this.requestJson("/encryption/keys",{method:"POST",headers:{"content-type":"application/json"},body:e});return this.parseWithSchema(t,Mc,"register encryption key response")}async sendMessage(e){const t={message:e.message};void 0!==e.streaming&&(t.streaming=e.streaming),e.auth&&(t.auth=Kl(e.auth)),"uaid"in e&&(t.uaid=e.uaid),"sessionId"in e&&e.sessionId&&(t.sessionId=e.sessionId),"agentUrl"in e&&e.agentUrl&&(t.agentUrl=e.agentUrl);let r=e.cipherEnvelope??null;if(e.encryption){const i=e.encryption.sessionId??("string"==typeof t.sessionId?t.sessionId:void 0);if(!i)throw new Error("sessionId is required when using encrypted chat payloads");if(!e.encryption.recipients?.length)throw new Error("recipients are required for encrypted chat payloads");r=this.encryption.encryptCipherEnvelope({...e.encryption,sessionId:i})}r&&(t.cipherEnvelope=r),delete t.encryption;const i=await this.requestJson("/chat/message",{method:"POST",body:t,headers:{"content-type":"application/json"}});return this.parseWithSchema(i,Fc,"chat message response")}async endSession(e){await this.request(`/chat/session/${encodeURIComponent(e)}`,{method:"DELETE"})}async generateEncryptionKeyPair(e={}){this.assertNodeRuntime("generateEncryptionKeyPair");if("secp256k1"!==(e.keyType??"secp256k1"))throw new Error("Only secp256k1 key generation is supported currently");const t=p.randomBytes(32),r=u.Buffer.from(t).toString("hex"),i=h.secp256k1.getPublicKey(t,!0),o=u.Buffer.from(i).toString("hex"),n=e.envVar??"RB_ENCRYPTION_PRIVATE_KEY",s=e.envPath?S.resolve(e.envPath):void 0;if(s){const t=(()=>{if("function"!=typeof require)return null;try{const e=require("node:fs");if(e&&"function"==typeof e.existsSync&&"function"==typeof e.readFileSync&&"function"==typeof e.writeFileSync&&"function"==typeof e.appendFileSync)return e}catch{}return null})();if(!t)throw new Error("File system module is not available; cannot write encryption key env file");const i=`${n}=${r}`;if(t.existsSync(s)){const r=t.readFileSync(s,"utf-8"),o=new RegExp(`^${n}=.*$`,"m");if(o.test(r)){if(!e.overwrite)throw new Error(`${n} already exists in ${s}; set overwrite=true to replace it`);const a=r.replace(o,i);t.writeFileSync(s,a)}else{const e=!r.endsWith("\n");t.appendFileSync(s,`${e?"\n":""}${i}\n`)}}else t.writeFileSync(s,`${i}\n`)}return{privateKey:r,publicKey:o,envPath:s,envVar:n}}buildUrl(e){const t=e.startsWith("/")?e:`/${e}`;return`${this.baseUrl}${t}`}buildVectorFallbackSearchParams(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}convertSearchResultToVectorResponse(e){const t=e.hits.map(e=>({agent:e,score:0,highlights:{}})),r=e.total,i=e.limit,o=e.page,n=r>o*i||o>1;return{hits:t,total:r,took:0,totalAvailable:r,visible:t.length,limited:n,credits_used:0}}async delay(e,t){if(e<=0){if(t?.aborted)throw zl()}else await new Promise((r,i)=>{const o=setTimeout(()=>{t&&t.removeEventListener("abort",n),r()},e),n=()=>{clearTimeout(o),t?.removeEventListener("abort",n),i(zl())};if(t){if(t.aborted)return clearTimeout(o),void i(zl());t.addEventListener("abort",n,{once:!0})}})}async requestJson(e,t){const r=await this.request(e,t),i=r.headers?.get("content-type")??"";if(!Dl.test(i)){const e=await r.text();throw new Hl("Expected JSON response from registry broker",e)}return await r.json()}async extractErrorBody(e){const t=e.headers?.get("content-type")??"";if(Dl.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,t,i){try{return t.parse(e)}catch(o){throw new Hl(`Failed to parse ${i}`,o instanceof r.ZodError||o instanceof Error?o:String(o),e)}}assertNodeRuntime(e){if("undefined"==typeof process||!process.versions?.node)throw new Error(`${e} is only available in Node.js environments`)}createEphemeralKeyPair(){this.assertNodeRuntime("generateEphemeralKeyPair");const e=p.randomBytes(32),t=h.secp256k1.getPublicKey(e,!0);return{privateKey:u.Buffer.from(e).toString("hex"),publicKey:u.Buffer.from(t).toString("hex")}}deriveSharedSecret(e){this.assertNodeRuntime("deriveSharedSecret");const t=this.hexToBuffer(e.privateKey),r=this.hexToBuffer(e.peerPublicKey),i=h.secp256k1.getSharedSecret(t,r,!0);return p.createHash("sha256").update(u.Buffer.from(i)).digest()}buildCipherEnvelope(e){this.assertNodeRuntime("encryptCipherEnvelope");const t=this.normalizeSharedSecret(e.sharedSecret),r=p.randomBytes(12),i=p.createCipheriv("aes-256-gcm",t,r),o=e.associatedData??e.sessionId,n=o?u.Buffer.from(o,"utf8").toString("base64"):void 0;o&&i.setAAD(u.Buffer.from(o,"utf8"));const s=u.Buffer.concat([i.update(u.Buffer.from(e.plaintext,"utf8")),i.final()]),a=i.getAuthTag();return{algorithm:"aes-256-gcm",ciphertext:u.Buffer.concat([s,a]).toString("base64"),nonce:r.toString("base64"),associatedData:n,keyLocator:{sessionId:e.sessionId,revision:e.revision??1},recipients:e.recipients.map(e=>({...e,encryptedShare:""}))}}openCipherEnvelope(e){this.assertNodeRuntime("decryptCipherEnvelope");const t=this.normalizeSharedSecret(e.sharedSecret),r=u.Buffer.from(e.envelope.ciphertext,"base64"),i=u.Buffer.from(e.envelope.nonce,"base64"),o=r.slice(0,r.length-16),n=r.slice(r.length-16),s=p.createDecipheriv("aes-256-gcm",t,i);e.envelope.associatedData&&s.setAAD(u.Buffer.from(e.envelope.associatedData,"base64")),s.setAuthTag(n);return u.Buffer.concat([s.update(o),s.final()]).toString(e.encoding??"utf8")}normalizeSharedSecret(e){if(u.Buffer.isBuffer(e))return u.Buffer.from(e);if(e instanceof Uint8Array)return u.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?u.Buffer.from(r,"hex"):u.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 u.Buffer.from(t,"hex")}}class jl{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 Wl(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),o=i.responder?.ephemeralPublicKey;if(!o)throw new Error("Responder handshake was not completed in time");const n=this.client.encryption.deriveSharedSecret({privateKey:t.privateKey,peerPublicKey:o}).subarray(),s=this.buildRecipients(r);return this.createHandle({sessionId:e.sessionId,sharedSecret:n,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),o=i.requester?.ephemeralPublicKey;if(!o)throw new Error("Requester handshake was not detected in time");const n=this.client.encryption.deriveSharedSecret({privateKey:t.privateKey,peerPublicKey:o}).subarray(),s=this.buildRecipients(r);return this.createHandle({sessionId:e.sessionId,sharedSecret:n,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,o=t?.handshake;if(t&&o&&"complete"===o.status)return{summary:t,record:o};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 Wl(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={sessionId:e.sessionId,mode:"encrypted",summary:e.summary,send:async i=>{const o=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:u.Buffer.from(t),recipients:o}})},decryptHistoryEntry:r=>this.decryptEntry(r,e.identity,t)};return this.registerConversationContext({sessionId:e.sessionId,sharedSecret:t,identity:e.identity}),i}decryptEntry(e,t,r){const i=e.cipherEnvelope;if(!i)return null;const o=u.Buffer.from(r);try{return this.client.encryption.decryptCipherEnvelope({envelope:i,sharedSecret:o})}catch(n){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))}}class Wl extends Error{constructor(e,t){super("Encryption is not enabled for this session"),this.sessionId=e,this.summary=t}}class Vl{constructor(e="info"){this.defaultEndpoint="https://kiloscribe.com/api/inscription-cdn",this.logger=D.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 G(t.network,this.logger),i=await r.getTopicInfo(e),o=i?.memo||"";let n="1";if(o){const e=o.match(/^hcs-(\d+)/);e&&e[1]&&(n=e[1])}const s=`hcs://${n}/${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(ag){const t=`Error resolving HRL for content and type: ${ag.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:i,topicId:n}=r;this.logger.debug(`Resolving HRL reference: standard=${i}, topicId=${n}`);try{const e=`${t.cdnEndpoint||this.defaultEndpoint}/${n}?network=${t.network}`;this.logger.debug(`Fetching content from CDN: ${e}`);const r=(await o.head(e)).headers["content-type"]||"";if(this.isBinaryContentType(r)||t.returnRaw){return{content:(await o.get(e,{responseType:"arraybuffer"})).data,contentType:r,topicId:n,isBinary:!0}}if("application/json"===r){const t=await o.get(e,{responseType:"json"});if(!t.data)throw new Error(`Failed to fetch content from topic: ${n}`);return{content:t.data,contentType:r,topicId:n,isBinary:!1}}const i=await o.get(e);if(!i.data)throw new Error(`Failed to fetch content from topic: ${n}`);let s;return s="object"==typeof i.data?i.data.content||i.data.text||JSON.stringify(i.data):i.data,{content:s,contentType:r,topicId:n,isBinary:!1}}catch(ag){const t=`Error resolving HRL reference: ${ag.message}`;throw this.logger.error(t),new Error(t)}}}class Gl{constructor(e){this.nodeHash=e}update(e){return this.nodeHash.update(e),this}digest(e){return this.nodeHash.digest(e)}}class Jl{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).buffer,i=await crypto.subtle.digest(this.mapAlgorithm(this.algorithm),r);return"hex"===e?Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,"0")).join(""):globalThis.Buffer.from(i)}concatenateArrays(e){const t=e.reduce((e,t)=>e+t.length,0),r=new Uint8Array(t);let i=0;for(const o of e)r.set(o,i),i+=o.length;return r}mapAlgorithm(e){return{sha256:"SHA-256",sha384:"SHA-384",sha1:"SHA-1",sha512:"SHA-512"}[e.toLowerCase()]||"SHA-256"}}class Yl{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 Xl(){const e="undefined"==typeof window;let t,r=!1,i=!1;try{r="undefined"!=typeof require&&"undefined"!=typeof process&&!!process.versions?.node}catch{r=!1}try{i="undefined"!=typeof crypto&&void 0!==crypto.subtle&&!e}catch{i=!1}return t=r&&e?"node":i&&!e?"web":"none",{hasNodeCrypto:r,hasWebCrypto:i,isSSR:e,preferredAPI:t}}function Zl(){return"undefined"==typeof window}class Ql{constructor(e){this.nodeHmac=e}update(e){return this.nodeHmac.update(e),this}digest(e){return this.nodeHmac.digest(e)}}class ed{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=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:this.mapAlgorithm(this.algorithm)},!1,["sign"]),o=await crypto.subtle.sign("HMAC",i,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 td{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 o=t[i%t.length];r=(r<<5)-r+e[i]+o&4294967295}return Math.abs(r)}}class rd{constructor(){try{const e="crypto";this.crypto=require(e)}catch(e){throw new Error("Node.js crypto module not available")}}createHash(e){return new Gl(this.crypto.createHash(e))}createHmac(e,t){return new Ql(this.crypto.createHmac(e,t))}async pbkdf2(e,t,r,i,o){return new Promise((n,s)=>{this.crypto.pbkdf2(e,t,r,i,o,(e,t)=>{e?s(e):n(t)})})}timingSafeEqual(e,t){return this.crypto.timingSafeEqual(e,t)}}class id{createHash(e){return new Jl(e)}createHmac(e,t){return new ed(t,e)}async pbkdf2(e,t,r,i,o){const n=new TextEncoder,s=await crypto.subtle.importKey("raw",n.encode(e),{name:"PBKDF2"},!1,["deriveBits"]),a=await crypto.subtle.deriveBits({name:"PBKDF2",salt:new Uint8Array(t),iterations:r,hash:this.mapDigest(o)},s,8*i);return globalThis.Buffer.from(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}mapDigest(e){return{sha256:"SHA-256",sha1:"SHA-1",sha512:"SHA-512"}[e.toLowerCase()]||"SHA-256"}}class od{createHash(e){return new Yl(e)}createHmac(e,t){return new td(t,e)}async pbkdf2(e,t,r,i,o){const n=new TextEncoder,s=globalThis.Buffer.from(n.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 nd(){switch(Xl().preferredAPI){case"node":try{return new rd}catch{return new od}case"web":return new id;default:return new od}}const sd=["mainnet","testnet","previewnet","devnet"];function ad(e){return sd.includes(e)}const cd=/^hedera:(mainnet|testnet|previewnet|devnet):\d+\.\d+\.\d+(?:-[a-zA-Z0-9]{5})?$/;function ld(e){return cd.test(e)}function dd(e,t){if(!ad(e))throw new Error("Invalid Hedera network");if(t.startsWith("hedera:")){if(ld(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 ud(e){if(!ld(e))throw new Error("Invalid Hedera CAIP-10");const[,t,r]=e.match(/^hedera:([^:]+):(.+)$/);return{network:t,accountId:r}}const pd=/^eip155:(\d+):(0x[0-9a-fA-F]{39,40})$/;function hd(e){return pd.test(e)}function gd(e,t){const r=`eip155:${"number"==typeof e?String(e):e}:${t.startsWith("0x")?t:`0x${t}`}`;if(!hd(r))throw new Error("Invalid EIP-155 CAIP-10");return r}var md=(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))(md||{}),fd=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(fd||{}),yd=(e=>(e[e.REST=0]="REST",e[e.WEBSOCKET=1]="WEBSOCKET",e[e.GRPC=2]="GRPC",e))(yd||{}),bd=(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))(bd||{}),wd=(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))(wd||{}),Id=(e=>(e.DNS="dns",e.SIGNATURE="signature",e.CHALLENGE="challenge",e))(Id||{}),Td=(e=>(e.PUBLIC="PUBLIC",e.CONTROLLED="CONTROLLED",e.FEE_BASED="FEE_BASED",e))(Td||{});const Sd={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},kd=r.z.object({platform:r.z.string().min(1),handle:r.z.string().min(1)}),Ed=r.z.object({type:r.z.nativeEnum(fd),capabilities:r.z.array(r.z.nativeEnum(bd)).min(1),model:r.z.string().min(1),creator:r.z.string().optional()}),Ad=r.z.object({url:r.z.string().min(1),transport:r.z.enum(["stdio","sse"])}),vd=r.z.object({type:r.z.nativeEnum(Id),value:r.z.string(),dns_field:r.z.string().optional(),challenge_path:r.z.string().optional()}),Cd=r.z.object({minVersion:r.z.string().optional()}),xd=r.z.object({name:r.z.string().min(1),description:r.z.string().min(1)}),Rd=r.z.object({name:r.z.string().min(1),description:r.z.string().min(1)}),Nd=r.z.object({version:r.z.string().min(1),connectionInfo:Ad,services:r.z.array(r.z.nativeEnum(wd)).min(1),description:r.z.string().min(1),verification:vd.optional(),host:Cd.optional(),capabilities:r.z.array(r.z.string()).optional(),resources:r.z.array(xd).optional(),tools:r.z.array(Rd).optional(),maintainer:r.z.string().optional(),repository:r.z.string().optional(),docs:r.z.string().optional()}),_d=r.z.object({version:r.z.string().min(1),type:r.z.nativeEnum(md),display_name:r.z.string().min(1),alias:r.z.string().optional(),bio:r.z.string().optional(),socials:r.z.array(kd).optional(),profileImage:r.z.string().optional(),uaid:r.z.string().optional(),properties:r.z.record(r.z.any()).optional(),inboundTopicId:r.z.string().optional(),outboundTopicId:r.z.string().optional(),base_account:r.z.string().optional()}),Pd=_d.extend({type:r.z.literal(md.PERSONAL),language:r.z.string().optional(),timezone:r.z.string().optional()}),Fd=_d.extend({type:r.z.literal(md.AI_AGENT),aiAgent:Ed}),Od=_d.extend({type:r.z.literal(md.MCP_SERVER),mcpServer:Nd}),zd=r.z.object({version:r.z.string(),type:r.z.literal(md.FLORA),display_name:r.z.string().min(1),members:r.z.array(r.z.object({accountId:r.z.string(),publicKey:r.z.string().optional(),weight:r.z.number().optional()})),threshold:r.z.number().min(1),topics:r.z.object({communication:r.z.string(),transaction:r.z.string(),state:r.z.string()}),inboundTopicId:r.z.string(),outboundTopicId:r.z.string(),bio:r.z.string().optional(),metadata:r.z.record(r.z.any()).optional(),policies:r.z.record(r.z.any()).optional()}),Dd=r.z.union([Pd,Fd,Od,zd]);class Bd{constructor(e){this.client="mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet(),this.auth=e.auth,this.network=e.network,this.operatorId=e.auth.operatorId,this.logger=D.getInstance({level:e.logLevel||"info",module:"HCS-11",silent:e.silent}),this.mirrorNode=new G(this.network,this.logger),this.auth.privateKey?(this.operatorCtx=oe({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:md.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,o){const n=this.validateProfile({version:"1.0",type:md.AI_AGENT,display_name:e,alias:o?.alias,bio:o?.bio,socials:o?.socials,profileImage:o?.profileImage,properties:o?.properties,inboundTopicId:o?.inboundTopicId,outboundTopicId:o?.outboundTopicId,base_account:o?.baseAccount,aiAgent:{type:t,capabilities:r,model:i,creator:o?.creator}});if(!n.valid)throw new Error(`Invalid AI Agent Profile: ${n.errors.join(", ")}`);return{version:"1.0",type:md.AI_AGENT,display_name:e,alias:o?.alias,bio:o?.bio,socials:o?.socials,profileImage:o?.profileImage,properties:o?.properties,inboundTopicId:o?.inboundTopicId,outboundTopicId:o?.outboundTopicId,base_account:o?.baseAccount,aiAgent:{type:t,capabilities:r,model:i,creator:o?.creator}}}createMCPServerProfile(e,t,r){const i=this.validateProfile({version:"1.0",type:md.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:md.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=Dd.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),r=await t.execute(this.client),o=await r.getReceipt(this.client);return o.status.toString()!==i.Status.Success.toString()?{success:!1,error:`Transaction failed: ${o.status.toString()}`}:{success:!0,result:o}}if(!this.auth.signer)throw new Error("No valid authentication method provided");const t=this.auth.signer,r=await e.freezeWithSigner(t),o=await r.executeWithSigner(t),n=await o.getReceiptWithSigner(t);return n.status.toString()!==i.Status.Success.toString()?{success:!1,error:`Transaction failed: ${n.status.toString()}: ${i.Status.Success.toString()}`}:{success:!0,result:n}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error during transaction execution"}}}async inscribeImage(e,t,r){try{const o=r?.progressCallback,n=new ps({module:"HCS11-Image",logger:this.logger,callback:o});n.preparing("Preparing to inscribe image",0);const s=k.lookup(t)||"application/octet-stream",a=r?.waitForConfirmation??!0;let c;if(this.auth.signer){if(!("accountId"in this.auth.signer))throw n.failed("Signer must be a DAppSigner for inscription"),new Error("Signer must be a DAppSigner for inscription");n.preparing("Using signer for inscription",10),c=await Oa({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);n.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}else{if(!this.auth.privateKey)throw n.failed("Private key is required for inscription"),this.logger.error("Private key is required for inscription"),new Error("Private key is required for inscription");n.preparing("Using private key for inscription",10);const r="ecdsa"===this.keyType?i.PrivateKey.fromStringECDSA(this.auth.privateKey):i.PrivateKey.fromStringED25519(this.auth.privateKey);c=await Fa({type:"buffer",buffer:e,fileName:t,mimeType:s},{accountId:this.auth.operatorId,privateKey:r,network:this.network},{waitForConfirmation:a,waitMaxAttempts:150,waitIntervalMs:2e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);n.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}if(c.confirmed)return n.completed("Image inscription completed",{topicId:Ua(c.inscription)}),{imageTopicId:Ua(c.inscription)||"",transactionId:c.result.jobId,success:!0};{const e=c.quote?"quote-only":c.result.jobId;return n.verifying("Waiting for inscription confirmation",50,{jobId:e}),{imageTopicId:"",transactionId:e,success:!1,error:"Inscription not confirmed"}}}catch(o){return this.logger.error("Error inscribing image:",o),{imageTopicId:"",transactionId:"",success:!1,error:o instanceof Error?o.message:"Error inscribing image"}}}async inscribeProfile(e,t){this.logger.info("Inscribing HCS-11 profile");const r=t?.progressCallback,o=new ps({module:"HCS11-Profile",logger:this.logger,callback:r});await this.attachUaidIfMissing(e),o.preparing("Validating profile data",5);const n=this.validateProfile(e);if(!n.valid)return o.failed(`Invalid profile: ${n.errors.join(", ")}`),{profileTopicId:"",transactionId:"",success:!1,error:`Invalid profile: ${n.errors.join(", ")}`};o.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";o.preparing("Preparing profile for inscription",20);const r={type:"buffer",buffer:e,fileName:a,mimeType:t},n={waitForConfirmation:!0,mode:"file",network:this.network,waitMaxAttempts:100,waitIntervalMs:2e3,progressCallback:e=>{const t=20+.75*Number(e?.progressPercent||0);o?.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}};let c;if(o.submitting("Submitting profile to Hedera network",30),this.auth.privateKey){const e="ecdsa"===this.keyType?i.PrivateKey.fromStringECDSA(this.auth.privateKey):i.PrivateKey.fromStringED25519(this.auth.privateKey);c=await Fa(r,{accountId:this.auth.operatorId,privateKey:e,network:this.network},n)}else{if(!this.auth.signer)throw new Error("No authentication method available - neither private key nor signer");c=await Oa(r,this.auth.signer,n)}if(!c.confirmed||!Ua(c.inscription))return o.failed("Failed to inscribe profile content"),{profileTopicId:"",transactionId:"",success:!1,error:"Failed to inscribe profile content"};const l=Ua(c.inscription);return o.completed("Profile inscription completed",{topicId:l,transactionId:c.result.transactionId}),{profileTopicId:l,transactionId:c.result.transactionId,success:!0}}catch(c){return o.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&&ad(this.network))try{const{HCS14Client:t}=await Promise.resolve().then(()=>pp),r=new t({client:this.client}),i=await r.createDid({method:"hedera",client:this.client}),o=dd(this.network,this.auth.operatorId);let n=this.auth.operatorId;const s=e.inboundTopicId;if(s&&s.trim().length>0)n=`${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&&(n=`${t}@${this.auth.operatorId}`)}catch{}const a=r.createUaid(i,{proto:"hcs-10",nativeId:o,uid:n});e.uaid=a}catch(ag){this.logger.warn("Hiero registrar not available; skipping UAID generation for profile",ag)}}async updateAccountMemoWithProfile(e,t){try{this.logger.info(`Updating account memo for ${e} with profile ${t}`);const r=this.setProfileForAccountMemo(t),o=(new i.AccountUpdateTransaction).setAccountMemo(r).setAccountId(e);return this.executeTransaction(o)}catch(r){return this.logger.error(`Error updating account memo: ${r instanceof Error?r.message:"Unknown error"}`),{success:!1,error:r instanceof Error?r.message:"Unknown error updating account memo"}}}async createAndInscribeProfile(e,t=!0,r){const i=r?.progressCallback,o=new ps({module:"HCS11-ProfileCreation",logger:this.logger,callback:i});o.preparing("Starting profile creation process",0);const n=o.createSubProgress({minPercent:0,maxPercent:80,logPrefix:"Inscription"}),s=await this.inscribeProfile(e,{...r,progressCallback:e=>{n.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent,details:e.details})}});if(!s?.success)return o.failed("Profile inscription failed",{error:s?.error}),s;if(o.confirming("Profile inscribed, updating account memo",85),t){const e=await this.updateAccountMemoWithProfile(this.auth.operatorId,s.profileTopicId);if(!e.success)return o.failed("Failed to update account memo",{error:e?.error}),{...s,success:!1,error:e?.error}}return o.completed("Profile creation completed successfully",{profileTopicId:s.profileTopicId,transactionId:s.transactionId}),s}async getCapabilitiesFromTags(e){const t=[];if(0===e.length)return[bd.TEXT_GENERATION];for(const r of e){const e=Sd[r.toLowerCase()];void 0===e||t.includes(e)||t.push(e)}return 0===t.length&&t.push(bd.TEXT_GENERATION),t}getAgentTypeFromMetadata(e){return"autonomous"===e.type?fd.AUTONOMOUS:fd.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 o=i.substring(7);if(!o?.startsWith("hcs://")){if(o.startsWith("ipfs://")){this.logger.warn("IPFS protocol references are not fully supported");const e=await fetch(`https://ipfs.io/ipfs/${o.replace("ipfs://","")}`),t=await e.json(),r=Dd.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 ${o}`}}if(o.startsWith("ar://")){const e=o.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=Dd.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: ${o}`}}{const e=o.match(/hcs:\/\/(\d+)\/(.+)/);if(!e)return{success:!1,error:`Invalid HCS protocol reference format: ${o}`};const[i,n,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=Dd.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 Md{async checkRegistrationStatus(e,t,r,i){try{const o=await fetch(`${r}/api/request-confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Network":t},body:JSON.stringify({transaction_id:e})});if(!o.ok){const e=`Failed to confirm registration: ${o.statusText}`;throw i&&i.error(e),new Error(e)}return await o.json()}catch(o){throw i&&i.error(`Error checking registration status: ${o.message}`),o}}async waitForRegistrationConfirmation(e,t,r,i=60,o=2e3,n){let s=0;for(;s<i;){n&&n.info(`Checking registration status. Attempt ${s+1}/${i}`);const a=await this.checkRegistrationStatus(e,t,r,n);if("success"===a.status)return n&&n.info("Registration confirmed successfully"),!0;if("failed"===a.status)throw n&&n.error("Registration confirmation failed"),new Error("Registration confirmation failed");n&&n.info(`Registration still pending. Waiting ${o}ms before next attempt`),await new Promise(e=>setTimeout(e,o)),s++}return n&&n.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 Bd({network:t,auth:{operatorId:"0.0.0"}});i?.info(`Fetching profile by account ID ${e} on ${t}`),await B(5e3);const o=await r.fetchProfileByAccountId(e,t);if(i?.info("Profile fetched",o),o?.error)return i?.error("Error fetching profile",o.error),{error:o.error,success:!1};if(!o?.success||!o?.profile)return i&&i.error("Profile not found for agent registration"),{error:"Profile not found for the provided account ID",success:!1};if(!o.profile.inboundTopicId)return i&&i.error("Missing inbound topic ID in profile"),{error:"Profile is missing required inbound topic ID",success:!1};if(!o.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: ${o.profile.inboundTopicId}, Outbound topic: ${o.profile.outboundTopicId}`)}catch(o){return i&&i.error(`Error validating profile: ${o.message}`),{error:`Error validating profile: ${o.message}`,success:!1}}const n=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 n.json();return n.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(n){return{error:`Error during registration request: ${n.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 o=await i.json();return o.error?{registrations:[],error:o.error,success:!1}:{registrations:o.registrations||[],success:!0}}catch(ag){return{registrations:[],error:`Error fetching registrations: ${ag.message}`,success:!1}}}}function Ud(e,t){return`hcs-10:op:${e}:${t}`}function Kd(e){var t,r;return Y({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 Ld(e){return Y({memo:e.memoOverride??`hcs-10:0:${e.ttl}:1`,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function $d(e){var t,r,i;return Y({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 Hd(e){var t,r;return Y({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 qd(e){const t={p:"hcs-10",op:"connection_request",operator_id:e.operatorId,m:e.memo};return X({topicId:e.inboundTopicId,message:JSON.stringify(t),transactionMemo:Ud(3,1)})}function jd(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 X({topicId:e.inboundTopicId,message:JSON.stringify(t),transactionMemo:Ud(4,1)})}function Wd(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 X({topicId:e.outboundTopicId,message:JSON.stringify(t),transactionMemo:Ud(3,2)})}function Vd(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 X({topicId:e.outboundTopicId,message:JSON.stringify(t),transactionMemo:Ud(4,2)})}function Gd(e){const t={p:"hcs-10",op:"message",operator_id:e.operatorId,data:e.data,m:e.memo};return X({topicId:e.connectionTopicId,message:JSON.stringify(t),transactionMemo:Ud(6,3)})}function Jd(e){const t={p:"hcs-10",op:"register",account_id:e.accountId,...e.inboundTopicId?{inbound_topic_id:e.inboundTopicId}:{},m:e.memo};return X({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:Ud(0,0)})}var Yd=(e=>(e.INBOUND="inbound",e.OUTBOUND="outbound",e.CONNECTION="connection",e.REGISTRY="registry",e))(Yd||{});class Xd extends Md{constructor(e){super(),this.network=e.network,this.logger=D.getInstance({level:e.logLevel||"info",module:"HCS10-BaseClient",prettyPrint:e.prettyPrint,silent:e.silent}),this.mirrorNode=new G(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 o=await this.mirrorNode.getTopicInfo(e);if(!o)return{canSubmit:!1,requiresFee:!1,reason:"Topic does not exist"};if(!o.submit_key?.key)return{canSubmit:!0,requiresFee:!1};try{const e=await this.mirrorNode.getPublicKey(t);if("ProtobufEncoded"===o.submit_key._type){const t=globalThis.Buffer.from(o.submit_key.key,"hex");if(await this.mirrorNode.checkKeyListAccess(t,e))return{canSubmit:!0,requiresFee:!1}}else{const t=i.PublicKey.fromString(o.submit_key.key);if(e.toString()===t.toString())return{canSubmit:!0,requiresFee:!1}}}catch(r){this.logger.error(`Key validation error: ${r instanceof Error?r.message:String(r)}`)}return o.fee_schedule_key?.key&&o.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(r){const e=r instanceof Error?r.message:String(r);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(ag){throw this.logger.error("Failed to fetch account",ag),ag}}async getAccountMemo(e){return await this.mirrorNode.getAccountMemo(e)}async retrieveProfile(e,t,r){const i=r?.maxRetries??0,o=r?.retryDelay??3e3;let n=0;for(;n<=i;){this.logger.debug(`Retrieving profile for account: ${e}${n>0?` (attempt ${n+1}/${i+1})`:""}`);const r=`${e}-${this.network}`;if(!t&&0===n){const t=Zd.getInstance().get(r);if(t)return this.logger.debug(`Cache hit for profile: ${e}`),t}try{const t=new Bd({network:this.network,auth:{operatorId:"0.0.0"},logLevel:this.logger.getLevel()}),s=await t.fetchProfileByAccountId(e,this.network);if(!s?.success){if(n<i){this.logger.info(`Profile not found for account ${e}, retrying in ${o}ms... (${s?.error})`),n++,await new Promise(e=>setTimeout(e,o));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;s?.topicInfo?.inboundTopic&&s?.topicInfo?.outboundTopic&&s?.topicInfo?.profileTopicId&&(c={inboundTopic:s.topicInfo.inboundTopic,outboundTopic:s.topicInfo.outboundTopic,profileTopicId:s.topicInfo.profileTopicId});const l={profile:a,topicInfo:c,success:!0};return Zd.getInstance().set(r,l),l}catch(ag){if(n<i){this.logger.info(`Error retrieving profile for account ${e}, retrying in ${o}ms... (${ag.message})`),n++,await new Promise(e=>setTimeout(e,o));continue}const r=`Failed to retrieve profile: ${ag.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 o=i.profile;if(!o)throw new Error(`Profile is null or undefined for account ${e}`);if(!o.inboundTopicId||!o.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(ag){const t=ag,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(ag){const t=`Failed to retrieve outbound messages: ${ag.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(ag){const t=`Failed to check connection created: ${ag.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 Vl(this.logger.getLevel());if(!r.isValidHRL(e))return e;return(await r.resolveHRL(e,{network:this.network,returnRaw:t})).content}catch(ag){const t=`Error resolving HRL reference: ${ag.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 Vl(this.logger.getLevel());return await r.getContentWithType(e,{network:this.network,returnRaw:t})}catch(ag){const t=`Error resolving HRL reference with type: ${ag.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(),o=r.accountId,n=await this.canSubmitToTopic(e,o);if(!n?.canSubmit)throw new Error(`Cannot submit to topic: ${n.reason}`);const s=await this.retrieveInboundAccountId(e);if(!s)throw new Error("Failed to retrieve topic info account ID");const a=n.requiresFee,c=qd({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 d=await this.retrieveCommunicationTopics(o);if(!d)throw new Error("Failed to retrieve outbound topic");const u=l.topicSequenceNumber?.toNumber();if(!u)throw new Error("Failed to get response sequence number");const p=`${e}@${s}`,h=Wd({outboundTopicId:d.outboundTopic,operatorId:p,connectionRequestId:u,memo:t});return await this.submitPayload(h),l}async recordOutboundConnectionConfirmation({outboundTopicId:e,requestorOutboundTopicId:t,connectionRequestId:r,confirmedRequestId:i,connectionTopicId:o,operatorId:n,memo:s}){const a=Vd({outboundTopicId:e,requestorOutboundTopicId:t,connectionTopicId:o,confirmedRequestId:i,connectionRequestId:r,operatorId:n,memo:s});return await this.submitPayload(a)}async waitForConnectionConfirmation(e,t,r=60,i=2e3,o=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let n=0;n<r;n++){this.logger.info(`Attempt ${n+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),n=this.getAccountAndSigner(),s=await this.retrieveCommunicationTopics(i),a=await this.retrieveCommunicationTopics(n.accountId);return this.logger.info("Connection confirmation found",r),o&&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}n<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(){Zd.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 o=i[3];switch(o){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: ${o} 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(ag){const t=ag,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 o=/^[0-9]+\.[0-9]+\.[0-9]+$/;return!!o.test(i)&&!!o.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 Zd{constructor(){this.CACHE_TTL=36e5,this.cache=new Map,this.cacheExpiry=new Map}static getInstance(){return Zd.instance||(Zd.instance=new Zd),Zd.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 Qd extends Error{constructor(e,t){super(e),this.payloadSize=t,this.name="PayloadSizeError"}}class eu extends Error{constructor(e){super(e),this.name="AccountCreationError"}}class tu extends Error{constructor(e){super(e),this.name="TopicCreationError"}}class ru extends Error{constructor(e){super(e),this.name="ConnectionConfirmationError"}}class iu{constructor(){this.config={},this.logger=D.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=Td.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===Td.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 ou extends Xd{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=D.getInstance({level:e.logLevel||"info",module:"HCS-SDK",silent:e.silent}),this.operatorAccountId=e.operatorId,this.operatorCtx=oe({network:this.network,operatorId:this.operatorAccountId,operatorKey:e.operatorPrivateKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:"mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet()}),this.client=this.operatorCtx.client,this.network=e.network,this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl||"https://moonscape.tech",this.hcs11Client=new Bd({network:e.network,auth:{operatorId:e.operatorId,privateKey:this.operatorCtx.operatorKey.toString()},logLevel:e.logLevel,silent:e.silent,keyType:e.keyType})}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=i.PrivateKey.generateED25519(),r=(new i.AccountCreateTransaction).setKeyWithoutAlias(t.publicKey).setInitialBalance(new i.Hbar(e)),o=await r.execute(this.client),n=(await o.getReceipt(this.client)).accountId;if(!n)throw this.logger.error("Account creation failed: accountId is null"),new eu("Failed to create account: accountId is null");return this.logger.info(`Account created successfully: ${n.toString()}`),{accountId:n.toString(),privateKey:t.toString()}}async createInboundTopic(e,t,r=60,i){let o,n;switch(await this.ensureInitialized(),this._generateHcs10Memo(Yd.INBOUND,{accountId:e,ttl:r}),t){case Td.PUBLIC:o=!1;break;case Td.CONTROLLED:o=!0;break;case Td.FEE_BASED:if(o=!1,!i)throw new Error("Fee configuration builder is required for fee-based topics");i.customFees.forEach(t=>{t.feeCollectorAccountId||(t.feeCollectorAccountId=e)}),n=i.build(),n.customFees=n.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=Kd({accountId:e,ttl:r,adminKey:!0,submitKey:o,operatorPublicKey:s});this.logger.info("Creating inbound topic");const{topicId:c}=await this.executeTopicCreateTransaction({transaction:a,feeConfig:n});return c}async createAgent(e,t=60,r,i){await this.ensureInitialized();const o=e.build(),n=this.client.operatorAccountId?.toString();if(!n)throw new Error("Failed to retrieve operator account ID");const s=await this._createEntityTopics(t,{outboundTopicId:r?.outboundTopicId||"",inboundTopicId:r?.inboundTopicId||"",pfpTopicId:r?.pfpTopicId||o.existingPfpTopicId||"",profileTopicId:r?.profileTopicId||""},n,o.inboundTopicType,o.feeConfig,o.pfpBuffer,o.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(o.name,o.bio,s.inboundTopicId,s.outboundTopicId,o.capabilities,o.metadata,o.pfpBuffer&&o.pfpBuffer.length>0&&!s.pfpTopicId?o.pfpBuffer:void 0,o.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 ps({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 iu;let o;if(o=t?.existingState?t.existingState:{currentStage:"init",completedPercentage:0,createdResources:[]},r){this.logger.info("Creating Agent Profile and HCS-10 Topics");const t=e.build();o.agentMetadata=t.metadata}else this.logger.info("Creating Person HCS-11 Profile");i.preparing(`Starting ${r?"agent":"person"} resource creation`,0,{state:o});const n=this.client.operatorAccountId?.toString();if(!n)throw new Error("Failed to retrieve operator account ID");const{inboundTopicId:s,outboundTopicId:a,state:c}=await this.createCommunicationTopics(n,t,i);let l,d,u;if(o=c,e.setInboundTopicId(s),e.setOutboundTopicId(a),r){const t=e.build();l=t.existingPfpTopicId||o.pfpTopicId,d=t.pfpBuffer,u=t.pfpFileName||"pfp.png"}else{const t=e.build();l=o.pfpTopicId,d=t.pfpBuffer,u=t.pfpFileName}!l&&d&&u?l=await this.handleProfilePictureCreation(d,u,o,i):l&&(i.preparing(`Using existing profile picture: ${l}`,50,{state:o}),o.pfpTopicId=l),await this.createAndInscribeProfile(r,e,l,o,s,a,t,i),o.currentStage="complete",o.completedPercentage=100,i.completed((r?"Agent":"Person")+" profile created successfully",{profileTopicId:o.profileTopicId,inboundTopicId:s,outboundTopicId:a,pfpTopicId:l,state:o});let p="";o.outboundTopicId&&(p=o.outboundTopicId);let h="";o.inboundTopicId&&(h=o.inboundTopicId);let g="";o.pfpTopicId&&(g=o.pfpTopicId);let m="";return o.profileTopicId&&(m=o.profileTopicId),{outboundTopicId:p,inboundTopicId:h,pfpTopicId:g,profileTopicId:m,success:!0,state:o}}catch(o){return i.failed("Error during profile creation",{error:o.message}),{outboundTopicId:"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:o.message,state:{currentStage:"init",completedPercentage:0,error:o.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(ag){const t=ag,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,o=[],n,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 d=this.hcs11Client.getAgentTypeFromMetadata({type:n.type||"autonomous"}),u=n.socials?Object.entries(n.socials).filter(([e,t])=>t).map(([e,t])=>({platform:e,handle:t})):void 0,p=this.hcs11Client.createAIAgentProfile(e,d,o,n.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:l?`hcs://1/${l}`:void 0,socials:u,properties:n.properties,inboundTopicId:r,outboundTopicId:i,creator:n.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(ag){const t=ag,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,r=[]){let o=e;if(!this.client.operatorPublicKey)return o;if(!t.customFees||0===t.customFees.length)return this.logger.warn("No custom fees provided in fee config for setupFees"),o;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 n=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 i.CustomFixedFee).setAmount(Number(e.feeAmount.amount)).setFeeCollectorAccountId(i.AccountId.fromString(e.feeCollectorAccountId));return e.feeTokenId&&t.setDenominatingTokenId(i.TokenId.fromString(e.feeTokenId)),t}return null}).filter(Boolean);if(0===n.length)return this.logger.warn("No valid custom fees to apply in setupFees"),o;const s=[...t.exemptAccounts||[],...r];return s.length>0&&(o=await this.setupExemptKeys(e,s)),o.setFeeScheduleKey(this.client.operatorPublicKey).setCustomFees(n)}async setupExemptKeys(e,t){let r=e;const i=Array.from(new Set(t)).filter(e=>e!==this.client.operatorAccountId?.toString());let o=[];if(i.length>0)try{o=await oc(i,this.network,this.logger)}catch(ag){const t=`Error getting exempt keys: ${ag.message}, continuing without exempt keys`;this.logger.warn(t)}return o.length>0&&(r=r.setFeeExemptKeys(o)),r}async handleConnectionRequest(e,t,r,o,n=60){this.logger.info(`Handling connection request ${r} 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 i.KeyList([c,a],1);let d;try{const t=$d({ttl:n,inboundTopicId:e,connectionId:r,adminKey:l,submitKey:l});if(o){const e=o.build(),r={...e,exemptAccounts:[...e.exemptAccounts||[]]},{topicId:i}=await this.executeTopicCreateTransaction({transaction:t,feeConfig:r});d=i}else{const{topicId:e}=await this.executeTopicCreateTransaction({transaction:t});d=e}this.logger.info(`Created new connection topic ID: ${d}`)}catch(f){const e=`Failed to create connection topic: ${f}`;throw this.logger.error(e),new tu(e)}const u=`${e}@${s}`,p=await this.confirmConnection(e,d,t,r,"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:r,confirmedRequestId:p,connectionTopicId:d,operatorId:m,memo:`Connection established with ${t}`}),{connectionTopicId:d,confirmedConnectionSequenceNumber:p,operatorId:u}}async confirmConnection(e,t,r,i,o,n){const s=await this.getOperatorId();this.logger.info(`Confirming connection with ID ${i}`);const a=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),c=jd({inboundTopicId:e,connectionTopicId:t,connectedAccountId:r,operatorId:s,connectionId:i,memo:o}),l=await this.submitPayload(c,void 0,n,a.requiresFee),d=l.topicSequenceNumber?.toNumber();if(!d)throw new ru("Failed to confirm connection: sequence number is null");return d}async sendMessage(e,t,r,i,o){const n=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:o?.progressCallback,waitMaxAttempts:o?.waitMaxAttempts,waitIntervalMs:o?.waitIntervalMs});if(!Ua(i))throw new Error("Failed to inscribe large message content");a.data=`hcs://1/${Ua(i)}`,this.logger.info(`Large message inscribed with topic ID: ${Ua(i)}`)}catch(d){const e=`Error inscribing large message: ${d.message}`;throw this.logger.error(e),new Error(e)}}this.logger.info("Submitting message to connection topic",a);const l=Gd({connectionTopicId:e,operatorId:s,data:a.data,memo:r});return await this.submitPayload(l,void 0,i,n.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 o=Y({memo:e,adminKey:t,submitKey:r,operatorPublicKey:this.client.operatorPublicKey||this.operatorCtx.operatorKey?.publicKey}),{topicId:n}=await this.executeTopicCreateTransaction({transaction:o,feeConfig:i});return n}async submitPayload(e,t,r,o=!1){if(e instanceof i.TopicMessageSubmitTransaction||"string"!=typeof e&&"function"==typeof e.getMessage){const t=(i.TopicMessageSubmitTransaction,e),n=t.getMessage();if(!n)throw new Error("Message payload is missing");const s=globalThis.Buffer.from(n).length;if(s>1e3)throw new Qd("Payload size exceeds 1000 bytes limit",s);let a;if(o&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),t.setMaxTransactionFee(new i.Hbar(this.feeAmount))),r){const e=t.freezeWith(this.client),i=await e.sign(r);a=await i.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 n="string"==typeof t?t:JSON.stringify(t),s=globalThis.Buffer.byteLength(n,"utf8");if(s>1e3)throw new Qd("Payload size exceeds 1000 bytes limit",s);const a=X({topicId:e,message:n,transactionMemo:this.getHcs10TransactionMemo(t)||void 0});let c;if(o&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),a.setMaxTransactionFee(new i.Hbar(this.feeAmount))),r){const e=a.freezeWith(this.client),t=await e.sign(r);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=k.lookup(t)||"application/octet-stream",o=this.operatorCtx.operatorKey,n=await us.createWithAuth({type:"server",accountId:this.client.operatorAccountId.toString(),privateKey:o,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 Fa({type:"buffer",buffer:e,fileName:t,mimeType:i},{accountId:this.client.operatorAccountId.toString(),privateKey:o,network:this.network},s,n);if(!a.confirmed||!a.inscription)throw new Error("Inscription was not confirmed");return a.inscription}async waitForConnectionConfirmation(e,t,r=60,i=2e3,o=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let n=0;n<r;n++){this.logger.info(`Attempt ${n+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),n=this.getAccountAndSigner(),s=await this.retrieveCommunicationTopics(i),a=await this.retrieveCommunicationTopics(n.accountId);return this.logger.info("Connection confirmation found",r),o&&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}n<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 r=e.build(),o=t?.progressCallback,n=t?.baseUrl||this.guardedRegistryBaseUrl;let s=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};s.agentMetadata=r.metadata,o&&o({stage:"preparing",message:"Starting agent creation process",progressPercent:0,details:{state:s}});let a,c=r.existingAccount;if(s.inboundTopicId&&s.outboundTopicId&&s.profileTopicId){if(c=c||r.existingAccount,!c)throw new Error("Cannot resume registration without account information");const e="ecdsa"===this.operatorCtx.keyType?i.PrivateKey.fromStringECDSA(c.privateKey).publicKey.toString():i.PrivateKey.fromStringED25519(c.privateKey).publicKey.toString();a=new ou({network:r.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:e,logLevel:"info",guardedRegistryBaseUrl:n}),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:")),i=e?.split(":")[1];i&&r.existingAccount?(c=r.existingAccount,this.logger.info(`Resuming with existing account: ${i}`)):(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}`);o&&o({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:s,account:c}});const i=new ie({mirrorNode:this.mirrorNode,logger:this.logger}),l=await i.resolveOperatorKey(c.accountId,c.privateKey),d=l.privateKey.publicKey.toString();a=new ou({network:r.network,operatorId:c.accountId,operatorPrivateKey:l.privateKey.toString(),operatorPublicKey:d,keyType:l.keyType,logLevel:"info",guardedRegistryBaseUrl:n}),o&&o({stage:"preparing",message:"Initialized agent client",progressPercent:25,details:{state:s}});let u=s.outboundTopicId,p=s.inboundTopicId,h=s.pfpTopicId,g=s.profileTopicId;if(!u||!p||!g){h&&e.setExistingProfilePicture(h);const t=await a.createAgent(e,60,s,e=>{o&&o({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:{...e.details,state:{...s,...e.details?.state}}})});u=t.outboundTopicId,p=t.inboundTopicId,h=t.pfpTopicId,g=t.profileTopicId,s.outboundTopicId=u,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:${u}`)||s.createdResources.push(`outbound:${u}`),s.createdResources.includes(`profile:${g}`)||s.createdResources.push(`profile:${g}`)}s.currentStage="profile",s.completedPercentage=60,o&&o({stage:"submitting",message:"Created agent with topics and profile",progressPercent:60,details:{state:s,outboundTopicId:u,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,r.network,{progressCallback:e=>{const t=60+.4*(e.progressPercent||0);o&&o({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 o&&o({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(ag){const r=ag,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,r){try{this.logger.info("Registering agent with guarded registry");const o=r?.maxAttempts??60,n=r?.delayMs??2e3,s=r?.progressCallback;let a=r?.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=i.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,o,n,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(ag){const t=ag,r=`Failed to register agent: ${t.message}`;return this.logger.error(r),{error:t.message,success:!1}}}async registerAgent(e,t,r,i,o){this.logger.info("Registering agent");const n=Jd({registryTopicId:e,accountId:t,inboundTopicId:r,memo:i});await this.submitPayload(n,void 0,o)}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 Td.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`),Td.FEE_BASED}return Td.CONTROLLED}catch(ag){const t=`Error determining topic type: ${ag.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,r,o){this.logger.info("Creating scheduled transaction");const n=(new i.ScheduleCreateTransaction).setScheduledTransaction(e).setPayerAccountId(o?i.AccountId.fromString(o):this.client.operatorAccountId);if(t&&n.setScheduleMemo(t),r){const e=b.addSeconds(new Date,r),t=i.Timestamp.fromDate(e);n.setExpirationTime(t)}const s=await n.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,o){const n=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:o?.memo};return this.logger.info("Submitting transaction operation to connection topic",s),await this.submitPayload(e,s,i,n.requiresFee)}async sendTransaction(e,t,r,i){this.logger.info("Creating scheduled transaction and sending transaction operation");const{scheduleId:o,transactionId:n}=await this.createScheduledTransaction(t,i?.scheduleMemo,i?.expirationTime,i?.schedulePayerAccountId);return{scheduleId:o,transactionId:n,receipt:await this.sendTransactionOperation(e,o,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,o=Ld({ttl:t?.ttl??60,adminKey:!0,submitKey:!0,operatorPublicKey:e}),{topicId:n}=await this.executeTopicCreateTransaction({transaction:o});i.outboundTopicId=n,i.createdResources&&i.createdResources.push(`outbound:${i.outboundTopicId}`)}if(!i.inboundTopicId){i.currentStage="topics",r&&r.preparing("Creating inbound topic",10,{state:i});const o=this.client.operatorPublicKey||this.operatorCtx.operatorKey.publicKey,n=Kd({accountId:e,ttl:t?.ttl??60,adminKey:!0,submitKey:!1,operatorPublicKey:o}),{topicId:s}=await this.executeTopicCreateTransaction({transaction:n});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 o=await this.inscribePfp(e,t);if(!o.success){let e="Failed to inscribe profile picture";throw o.error&&(e=o.error),new Error(e)}const n=o.pfpTopicId;return r.pfpTopicId=n,r.createdResources&&r.createdResources.push(`pfp:${r.pfpTopicId}`),i.preparing("Profile picture created",50,{state:r}),n}async createAndInscribeProfile(e,t,r,i,o,n,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:o,outboundTopicId:n,creator:e.metadata?.creator})}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:o,outboundTopicId:n})}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 o=e.build(),n=this.client.operatorAccountId?.toString();if(!n)throw new Error("Failed to retrieve operator account ID");const s=await this._createEntityTopics(t,{outboundTopicId:r?.outboundTopicId||"",inboundTopicId:r?.inboundTopicId||"",pfpTopicId:r?.pfpTopicId||o.existingPfpTopicId||"",profileTopicId:r?.profileTopicId||""},n,Td.PUBLIC,void 0,o.pfpBuffer,o.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(o.name,o.mcpServer,{alias:o.alias,bio:o.bio,socials:o.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(n,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,o,n,s,a){let{outboundTopicId:c,inboundTopicId:l,pfpTopicId:d,profileTopicId:u}=t;if(c)this.logger.info(`Using existing outbound topic ID: ${c}`);else{const t=Ld({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===Td.FEE_BASED?o: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}}})),!d&&n&&n.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}}});d=(await this.inscribePfp(n,s)).pfpTopicId,this.logger.info(`Profile picture inscribed with topic ID: ${d}`),a&&a({stage:"preparing",message:"Profile picture inscribed",progressPercent:55,details:{outboundTopicId:c,inboundTopicId:l,pfpTopicId:d,state:{currentStage:"pfp",completedPercentage:55}}})}else d&&this.logger.info(`Using existing profile picture with topic ID: ${d}`);return{inboundTopicId:l,outboundTopicId:c,pfpTopicId:d,profileTopicId:u}}async createAndRegisterMCPServer(e,t){try{const r=e.build(),o=t?.progressCallback,n=t?.baseUrl||this.guardedRegistryBaseUrl;let s=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};s.serverMetadata={name:r.name,description:r.mcpServer.description,services:r.mcpServer.services},o&&o({stage:"preparing",message:"Starting MCP server creation process",progressPercent:0,details:{state:s}});let a,c=r.existingAccount;if(s.inboundTopicId&&s.outboundTopicId&&s.profileTopicId){if(c=c||r.existingAccount,!c)throw new Error("Cannot resume registration without account information");const e=re(c.privateKey),t=("ed25519"===e.detectedType?i.PrivateKey.fromStringED25519(c.privateKey):i.PrivateKey.fromStringECDSA(c.privateKey)).publicKey.toString();a=new ou({network:r.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:t,keyType:e.detectedType,logLevel:"info",guardedRegistryBaseUrl:n}),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:")),i=e?.split(":")[1];i&&r.existingAccount?(c=r.existingAccount,this.logger.info(`Resuming with existing account: ${i}`)):(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}`);o&&o({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:s,account:c}});const l=new ie({mirrorNode:this.mirrorNode,logger:this.logger}),d=await l.resolveOperatorKey(c.accountId,c.privateKey);e.setExistingAccount(c.accountId,c.privateKey);const u=("ed25519"===d.keyType?i.PrivateKey.fromStringED25519(c.privateKey):i.PrivateKey.fromStringECDSA(c.privateKey)).publicKey.toString();a=new ou({network:r.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:u,logLevel:"info",guardedRegistryBaseUrl:n}),o&&o({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=>{o&&o({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,o&&o({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,r.network,{progressCallback:e=>{const t=60+.4*(e.progressPercent||0);o&&o({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 o&&o({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(ag){const r=ag,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:o=!1,waitForConfirmation:n=!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:n,waitMaxAttempts:s,waitIntervalMs:a,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},o=await Fa({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(!o.confirmed||!o.inscription)throw new Error("Metadata inscription was not confirmed");e=Ua(o.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,d=Hd({ttl:t,metadataTopicId:e,adminKey:i,submitKey:o,operatorPublicKey:this.client.operatorPublicKey||l.publicKey}),{topicId:u,response:p}=await this.executeTopicCreateTransaction({transaction:d});return c&&c({stage:"completed",message:"Registry topic created successfully",progressPercent:100,details:{topicId:u,metadataTopicId:e,transactionId:p.transactionId.toString()}}),this.logger.info(`Registry topic created successfully: ${u}`),{success:!0,topicId:u,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 nu="undefined"!=typeof window;var su=(e=>(e[e.ACTION=0]="ACTION",e[e.ASSEMBLY=2]="ASSEMBLY",e[e.HASHLINKS=3]="HASHLINKS",e))(su||{});class au{constructor(e,t,r,i,o){this.entries=new Map,this.networkType=e,this.logger=t,this.registryType=r,this.topicId=i,this.client=o}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:su[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 o;if(this.logger.info("Inscribing content via HCS-1",{size:i.length,mimeType:t,registryType:su[this.registryType]}),"getOperatorAccountId"in this.client)o=await Fa({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:n}=await this.client.getAccountAndSigner();o=await Oa({type:"buffer",buffer:i,fileName:"application/octet-stream"===t&&"wasm"===r?.fileType?`${r?.name||"content"}.wasm`:r?.name||"content",mimeType:t},n,{mode:"file",metadata:r,waitForConfirmation:!0})}if(!o.confirmed)throw new Error("Failed to inscribe content");const n=o.inscription.topic_id;if(!n)throw new Error("No topic ID in inscription response");return this.logger.info("Content inscribed successfully",{topicId:n}),n}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:su[this.registryType]})}getStats(){return{entryCount:this.entries.size,lastSync:this.lastSyncTimestamp,topicId:this.topicId,registryType:su[this.registryType]}}}const cu=r.z.object({p:r.z.literal("hcs-12")}),lu=r.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid Hedera address format"),du=r.z.string().regex(/^[a-f0-9]{64}$/,"Invalid SHA-256 hash format"),uu=r.z.object({format:r.z.enum(["tar.gz","zip","car"]),root_manifest:r.z.string(),includes_lockfile:r.z.boolean(),workspace_members:r.z.array(r.z.string()).optional()}),pu=r.z.object({source_t_id:lu,source_hash:du,compiler_version:r.z.string(),cargo_version:r.z.string(),target:r.z.literal("wasm32-unknown-unknown"),profile:r.z.string(),build_flags:r.z.array(r.z.string()),lockfile_hash:du,source_structure:uu}),hu=r.z.lazy(()=>r.z.object({type:r.z.string().optional(),required:r.z.array(r.z.string()).optional(),properties:r.z.record(hu).optional(),pattern:r.z.string().optional(),minimum:r.z.number().optional(),maximum:r.z.number().optional(),regex:r.z.string().optional(),min:r.z.number().optional(),max:r.z.number().optional(),length:r.z.number().optional(),email:r.z.boolean().optional(),url:r.z.boolean().optional(),uuid:r.z.boolean().optional(),cuid:r.z.boolean().optional(),cuid2:r.z.boolean().optional(),ulid:r.z.boolean().optional(),datetime:r.z.boolean().optional(),ip:r.z.boolean().optional(),startsWith:r.z.string().optional(),endsWith:r.z.string().optional(),includes:r.z.string().optional(),gt:r.z.number().optional(),gte:r.z.number().optional(),lt:r.z.number().optional(),lte:r.z.number().optional(),int:r.z.boolean().optional(),positive:r.z.boolean().optional(),nonnegative:r.z.boolean().optional(),negative:r.z.boolean().optional(),nonpositive:r.z.boolean().optional(),multipleOf:r.z.number().optional(),finite:r.z.boolean().optional(),safe:r.z.boolean().optional(),nonempty:r.z.boolean().optional(),literal:r.z.union([r.z.string(),r.z.number(),r.z.boolean()]).optional(),enum:r.z.array(r.z.string()).optional(),nullable:r.z.boolean().optional(),nullish:r.z.boolean().optional(),optional:r.z.boolean().optional(),element:r.z.any().optional(),shape:r.z.record(r.z.any()).optional(),strict:r.z.boolean().optional(),passthrough:r.z.boolean().optional(),catchall:r.z.any().optional()})),gu=r.z.object({p:r.z.literal("hcs-12"),op:r.z.literal("register"),t_id:lu,hash:du,wasm_hash:du,js_t_id:lu.optional(),js_hash:du.optional(),interface_version:r.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid version format").optional(),info_t_id:lu.optional(),source_verification:pu.optional(),previous_version:r.z.string().optional(),migration_notes:r.z.string().optional(),validation_rules:r.z.record(hu).optional(),m:r.z.string().optional()}),mu=r.z.object({p:r.z.literal("hcs-12"),op:r.z.enum(["register","template"]),name:r.z.string(),version:r.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid semver format"),data:r.z.union([r.z.any(),r.z.string()]).optional(),t_id:lu.optional()});r.z.enum(["register","add-action","add-block","update"]);const fu=cu.extend({op:r.z.literal("register"),name:r.z.string(),version:r.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid semver format"),description:r.z.string().optional(),tags:r.z.array(r.z.string()).optional(),author:r.z.string().optional()}),yu=cu.extend({op:r.z.literal("add-action"),t_id:lu,alias:r.z.string(),config:r.z.any().optional(),data:lu.optional()}),bu=cu.extend({op:r.z.literal("add-block"),block_t_id:lu,actions:r.z.record(r.z.string(),lu).optional(),attributes:r.z.record(r.z.any()).optional(),children:r.z.array(r.z.string()).optional(),data:lu.optional()}),wu=cu.extend({op:r.z.literal("update"),description:r.z.string().optional(),tags:r.z.array(r.z.string()).optional()});r.z.object({type:r.z.enum(["vertical","horizontal","grid"]),responsive:r.z.boolean().optional(),containerClass:r.z.string().optional()}),r.z.object({source_t_id:lu,source_hash:du,description:r.z.string().optional()});const Iu=r.z.discriminatedUnion("op",[fu,yu,bu,wu]),Tu=fu,Su=cu.extend({op:r.z.literal("register"),t_id:lu,name:r.z.string().max(100,"Name must be 100 characters or less"),description:r.z.string().max(500,"Description must be 500 characters or less").optional(),tags:r.z.array(r.z.string()).max(10,"Maximum 10 tags allowed").optional(),category:r.z.string().optional(),featured:r.z.boolean().optional(),icon:r.z.string().optional(),author:r.z.string().optional(),website:r.z.string().url().optional()});function ku(e){return gu.parse(e)}function Eu(e){return Iu.parse(e)}function Au(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 vu extends au{constructor(e,t,r,i){super(e,t,su.ACTION,r,i),this.actionsByHash=new Map,this.cryptoAdapter=nd()}async registerWithWasm(e,t,r){let i,o;if(Zl()){i=this.createSSRSafeHash(e,"wasm");const r=JSON.stringify(t);o=this.createSSRSafeHash(globalThis.Buffer.from(r),"info")}else{const r=this.cryptoAdapter.createHash("sha256").update(e).digest("hex"),n=r instanceof Promise?await r:r;i="string"==typeof n?n:n.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;o="string"==typeof c?c:c.toString("hex")}const n=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:n,hash:o,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 za(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 za(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(Zl())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 za(t.t_id,{accountId:this.client.getOperatorAccountId(),privateKey:this.client.getOperatorPrivateKey(),network:this.networkType});else{const{accountId:r}=await this.client.getAccountAndSigner();e=await za(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(Zl())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{ku(e)}catch(t){if(t instanceof r.ZodError){const e=t.errors[0];throw new Error(`Validation failed: ${e.path.join(".")} - ${e.message}`)}throw t}}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 Cu{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 Vl,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 Vl,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 o={...t,template_t_id:i.topic_id},n=globalThis.Buffer.from(JSON.stringify(o)),s=await this.client.inscribeFile(n,`block-${t.name}-definition.json`);if(!s?.topic_id)throw new Error("Failed to inscribe block definition");return this.blockCache.set(s.topic_id,o),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 xu extends au{constructor(e,t,r,i){super(e,t,su.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 o=t,n={t_id:o.t_id,alias:o.alias,config:o.config,data:o.data};r.actions.push(n),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 n of r)try{let e;if(!n.message)continue;try{let t;t="undefined"==typeof window?globalThis.Buffer.from(n.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(n.message),e=>e.charCodeAt(0))),e=JSON.parse(t),this.logger.debug("Successfully parsed message",{sequenceNumber:n.sequence_number,op:e.op,p:e.p})}catch(i){this.logger.debug("Failed to decode/parse message",{sequenceNumber:n.sequence_number,error:i});continue}if("hcs-12"!==e.p){this.logger.debug("Skipping non-HCS-12 message",{sequenceNumber:n.sequence_number,protocol:e.p});continue}const r={id:n.sequence_number.toString(),sequenceNumber:n.sequence_number,timestamp:n.consensus_timestamp||(new Date).toISOString(),submitter:n.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:n.sequence_number,error:i})}const o=this.assemblyStates.get(t)||null;return this.logger.info("Assembly state after sync",{topicId:t,hasState:!!o,name:o?.name,version:o?.version,actionsCount:o?.actions?.length||0,blocksCount:o?.blocks?.length||0}),o}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 o=r;i={topicId:e,name:o.name,version:o.version,description:o.description,tags:o.tags,author:o.author,actions:[],blocks:[],created:t.timestamp,updated:t.timestamp},this.assemblyStates.set(e,i),this.logger.debug("Assembly registered",{topicId:e,name:o.name,version:o.version});break;case"add-action":if(!i)return void this.logger.warn("Cannot add action without assembly registration");const n=r,s={t_id:n.t_id,alias:n.alias,config:n.config,data:n.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{Eu(e)}catch(t){if(t instanceof r.ZodError){const e=t.errors.map(e=>`${e.path.join(".")}: ${e.message}`);throw new Error(`Assembly validation failed: ${e.join("; ")}`)}throw t}}}class Ru extends au{constructor(e,t,r,i){super(e,t,su.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),o=await this.client.submitMessage(this.topicId,i);return o.sequenceNumber&&(r.sequenceNumber=o.sequenceNumber,r.id=o.sequenceNumber.toString(),this.entries.delete(t),this.entries.set(r.id,r)),this.logger.info("HashLink submitted to HCS",{transactionId:o.transactionId,sequenceNumber:o.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=Au(e,Su);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 o=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&&o++}),{...e,categories:r.size,totalTags:i.size,featuredCount:o}}}class Nu{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,o]of Object.entries(r.actions)){const n=e.state.actions?.some(e=>e.t_id===o);n||t.push(`Block ${r.block_t_id} references non-existent action: ${o} for key ${i}`)}if(r.children)for(const i of r.children){const o=e.state.blocks?.some(e=>e.block_t_id===i);o||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 _u{constructor(e){this.network=e.network,this.logger=e.logger||D.getInstance({level:e.logLevel||"info",module:"HCS12-BaseClient",prettyPrint:e.prettyPrint,silent:e.silent}),this.mirrorNode=new G(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 Cu(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 xu(this.network,this.logger,e,this);await t.sync();return new Nu(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 Nu(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 Pu{constructor(){this.block={apiVersion:3},this.attributes={},this.supports={},this.actions={},this.logger=new D({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 o={type:t,default:r};return i?.enum&&(o.enum=i.enum),i?.source&&(o.source=i.source),i?.selector&&(o.selector=i.selector),i?.attribute&&(o.attribute=i.attribute),this.attributes[e]=o,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 Pu).setName(e).setTitle(t).setCategory("formatting").enableCommonSupports()}static createInteractiveBlock(e,t){return(new Pu).setName(e).setTitle(t).setCategory("widgets").enableCommonSupports()}static createWidgetBlock(e,t){return this.createInteractiveBlock(e,t)}static createContainerBlock(e,t){return(new Pu).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 Fu{constructor(e,t){this.wasmCache=new Map,this.logger=e,this.network=t,this.hrlResolver=new Vl}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"}),o=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(o);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 n=i.WasmInterface;if(!n)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 n;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(o),{success:!0,data:c}}catch(ag){throw URL.revokeObjectURL(o),ag}}}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 Ou{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],n=i[2],s=i[3];try{const i=this.parseHashLinkURI(n),o=s.match(/data-attributes=(['"])((?:(?!\1).)*)\1/s);let a;if(o)try{const e=o[2];a=JSON.parse(e)}catch(ag){this.logger.warn("Failed to parse data-attributes",{uri:n,attributes:o[2],error:ag.message})}const c=s.match(/data-actions=(['"])((?:(?!\1).)*)\1/s);let l;if(c)try{const e=c[2];l=JSON.parse(e)}catch(ag){this.logger.warn("Failed to parse data-actions",{uri:n,actions:c[2],error:ag.message})}const d=s.match(/data-loading=['"]([^'"]+)['"]/),u=d?.[1]||"eager";t.push({element:r,uri:n,...i,attributes:a,actions:l,loading:u,placeholder:e}),this.logger.debug("Found HashLink reference",{uri:n,parsed:i})}catch(o){this.logger.error("Failed to parse HashLink URI",{uri:n,error:o.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 zu{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 o=await this.blockLoader.loadBlock(r);if(!o||!o.definition)throw new Error(`Block not found: ${r}`);const n={...this.extractDefaults(o.definition),...t.attributes,...e.attributes},s={...t.actions,...e.actions},a={blockId:r,definition:o.definition,template:o.template,attributes:n,actions:s};return this.cache.set(i,a),a}catch(o){throw this.renderStack.delete(r),new Error(`Failed to load HCS-12 block ${r}: ${o.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 Du={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"}},Bu={ACTIONS:{},BLOCKS:{},ASSEMBLIES:{}};const Mu=/^[a-z0-9][a-z0-9-]*$/,Uu=r.z.object({registry:r.z.string().min(1),name:r.z.string().min(1),version:r.z.string().min(1),protocol:r.z.string().min(1),nativeId:r.z.string().min(1),skills:r.z.array(r.z.number().int().nonnegative())});function Ku(e){return e.trim()}function Lu(e){return e.trim().toLowerCase()}function $u(e){const t=Uu.parse(e);if("hcs-10"===t.protocol.trim().toLowerCase()&&!ld(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()&&!hd(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:Lu(t.registry),name:Ku(t.name),version:Ku(t.version),protocol:Lu(t.protocol),nativeId:Ku(t.nativeId),skills:[...t.skills].sort((e,t)=>e-t)},i=["skills","name","nativeId","protocol","registry","version"],o={};for(const n of i)o[n]=r[n];return{normalized:r,canonicalJson:JSON.stringify(o)}}const Hu="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function qu(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 o=t;o<e.length;o++){let t=e[o];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 o=0;o<t;o++)i+="1";for(let o=r.length-1;o>=0;o--)i+=Hu[r[o]];return i}function ju(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],o=Hu.indexOf(t);if(-1===o)throw new Error("Invalid Base58 character");let n=o;for(let e=0;e<r.length;e++){const t=58*r[e]+n;r[e]=255&t,n=t>>8}for(;n>0;)r.push(255&n),n>>=8}for(let i=0;i<t;i++)r.push(0);return r.reverse(),Uint8Array.from(r)}(e.slice(1))}function Wu(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 Vu(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(":"),o=e.indexOf(":",t+1);if(o<0)throw new Error("Invalid DID format");r=e.slice(t+1,o),i=e.slice(o+1)}}const{sanitized:o,hadSuffix:n}=function(e){const t=e.search(/[;?#]/);return-1===t?{sanitized:e,hadSuffix:!1}:{sanitized:e.slice(0,t),hadSuffix:!0}}(i);let s=o;if("hedera"===r){const e=o.match(/^(mainnet|testnet|previewnet|devnet):(.+)$/);e&&(s=e[2])}const a={...t||{}};var c;n&&!a.src&&(a.src=(c=e,"z"+qu(globalThis.Buffer.from(c,"utf8"))));const l=Wu(a);return l?`uaid:did:${s};${l}`:`uaid:did:${s}`}function Gu(e,t,r){return"string"==typeof e?Vu(e,t):async function(e,t,r){const{normalized:i,canonicalJson:o}=$u(e),n=nd().createHash("sha384").update(globalThis.Buffer.from(o,"utf8")).digest(),s=await Promise.resolve(n),a=qu(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||{}):{},d=c?Wu(l):"";return d?`uaid:aid:${a};${d}`:`uaid:aid:${a}`}(e,t,r)}function Ju(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 o=i.indexOf(";"),n=o>=0?i.slice(0,o):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),o=i.slice(e+1);t[r]=o}}return t})(o>=0?i.slice(o+1):"");return{method:"did"===r?"uaid":"aid",id:n,params:s}}throw new Error("Invalid DID")}let Yu;function Xu(e,t){if(!t||"object"!=typeof t)return!1;const r=Reflect.get(t,"code"),i=Reflect.get(t,"message"),o="string"==typeof i?i:"";if("string"==typeof r&&r.includes("MODULE_NOT_FOUND"))return o.includes(e);if(o){const t=o.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 Zu(e){try{return await import(e)}catch(t){if(Xu(e,t))return null;throw t}}async function Qu(e){if(va)return Zu(e);const t=await async function(){if(void 0!==Yu)return Yu;if(va)return Yu=null,Yu;try{const e="undefined"!=typeof global?global:globalThis,t=e.process?.mainModule?.require??e.require;Yu="function"==typeof t&&"function"==typeof t.resolve?t:null}catch{Yu=null}return Yu}();if(t)try{return t(e)}catch(r){if(!Xu(e,r))throw r}return Zu(e)}const ep=["@hiero-did-sdk","resolver"].join("/");let tp=null;class rp{constructor(){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 tp||(tp=Qu(ep).then(e=>e?.resolveDID??null)),tp}();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 ip{constructor(){this.resolvers=[]}register(e){this.resolvers.push(e)}list(){return[...this.resolvers]}filterByDidMethod(e){return this.resolvers.filter(t=>t.meta?.didMethods?.includes(e))}async resolveDid(e){for(const t of this.resolvers)if(t.supports(e))return t.resolve(e);return null}async resolveUaid(e){const t=Ju(e);if("uaid"!==t.method)return null;const r=t.params.src;if(r){const e=globalThis.Buffer.from(ju(r)).toString("utf8");return this.resolveDid(e)}const i=t.id;if(i.startsWith("testnet:")||i.startsWith("mainnet:")||i.startsWith("previewnet:")||i.startsWith("devnet:")){const e=`did:hedera:${i}`;return this.resolveDid(e)}const o=t.params.proto,n=t.params.nativeId;if("hcs-10"===o&&n){const e=n.match(/^hedera:(mainnet|testnet|previewnet|devnet):/);if(e){const t=`did:hedera:${e[1]}:${i}`;return this.resolveDid(t)}}return null}}const op=new ip;function np(){op.register(new rp)}class sp{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 ap=new sp,cp=["@hiero-did-sdk","registrar"].join("/");let lp=null;class dp{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 lp||(lp=Qu(cp).then(e=>e?.createDID??null)),lp}();if(!t)throw new Error("Hiero registrar unavailable. Ensure @hiero-did-sdk/registrar is installed.");return(await t({},{client:e.client})).did}}class up{constructor(e){this.registry=e?.registry??op,this.issuers=new sp,this.registerHederaIssuer(),this.registerHederaResolver(),this.logger=D.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,r){const o=oe({network:e,operatorId:t,operatorKey:r,mirrorNode:new G(e),logger:this.logger,client:i.Client.forName(e)});this.operatorCtx=o,this.client=o.client,this.network=e,this.operatorId=t,this.operatorPrivateKey=r}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()}listResolvers(){return this.registry.list()}filterIssuersByMethod(e){return this.issuers.filterByDidMethod(e)}filterResolversByMethod(e){return this.registry.filterByDidMethod(e)}registerHederaIssuer(){this.issuers.register(new dp)}async createDid(e){return this.issuers.issue(e)}canonicalizeAgentData(e){return $u(e)}createUaid(e,t,r){return"string"==typeof e?Gu(e,t):Gu(e,t,r)}parseHcs14Did(e){return Ju(e)}isHederaNetwork(e){return ad(e)}isHederaCaip10(e){return ld(e)}toHederaCaip10(e,t){return dd(e,t)}parseHederaCaip10(e){return ud(e)}isEip155Caip10(e){return hd(e)}toEip155Caip10(e,t){return gd(e,t)}getResolverRegistry(){return this.registry}registerHederaResolver(){this.registry.register(new rp)}async createDidWithUaid(e){const t=await this.createDid(e.issue);let r=e.uid;const i=e.proto;let o=e.nativeId;if("hedera"===e.issue.method){if(await this.ensureInitializedHedera(),!o){if(!this.network||!this.operatorId)throw new Error("nativeId not provided and network/operatorId are not configured");o=dd(this.network,this.operatorId)}if(!r&&"hcs-10"===i&&this.network&&this.operatorId)try{if(!this.hcs10Client&&this.operatorPrivateKey&&(this.hcs10Client=new ou({network:this.network,operatorId:this.operatorId,operatorPrivateKey:this.operatorPrivateKey,silent:!0})),this.hcs10Client)r=await this.hcs10Client.getOperatorId();else{const e=new Bd({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 n=this.createUaid(t,{uid:r,proto:i,nativeId:o});return{did:t,uaid:n,parsed:Ju(n)}}}const pp=Object.freeze(Object.defineProperty({__proto__:null,CanonicalAgentDataSchema:Uu,HCS14Client:up,HCS14_PROTOCOL_REGEX:Mu,HederaHieroIssuer:dp,HieroDidResolver:rp,IssuerRegistry:sp,ResolverRegistry:ip,canonicalizeAgentData:$u,createUaid:Gu,defaultIssuerRegistry:ap,defaultResolverRegistry:op,isEip155Caip10:hd,isHederaCaip10:ld,isHederaNetwork:ad,parseHcs14Did:Ju,parseHederaCaip10:ud,registerDefaultResolvers:np,toEip155Caip10:gd,toHederaCaip10:dd},Symbol.toStringTag,{value:"Module"}));function hp(e){return`hcs://1/${e}`}class gp{constructor(e){this.network=e.network,this.logger=e.logger||D.getInstance({level:e.logLevel||"info",module:"HCS5Client",silent:e.silent}),this.mirrorNode=new G(this.network,this.logger)}}function mp(e){const t=(new i.TokenMintTransaction).setTokenId(i.TokenId.fromString(e.tokenId)).setMetadata([globalThis.Buffer.from(e.metadata)]);return e.transactionMemo&&t.setTransactionMemo(e.transactionMemo),t}var fp=(e=>(e.REGISTER="register",e.UPDATE="update",e.DELETE="delete",e.MIGRATE="migrate",e))(fp||{}),yp=(e=>(e[e.INDEXED=0]="INDEXED",e[e.NON_INDEXED=1]="NON_INDEXED",e))(yp||{});const bp=r.z.string().regex(/^\d+\.\d+\.\d+$/,{message:"Topic ID must be in Hedera format (e.g., '0.0.123456')"}),wp=r.z.object({p:r.z.string().regex(/^hcs-\d+$/,{message:"Protocol must be in format 'hcs-N' where N is a number"}),op:r.z.enum(["register","update","delete","migrate"]),m:r.z.string().max(500,"Memo must not exceed 500 characters").optional(),ttl:r.z.number().int().positive().optional()}),Ip=wp.extend({op:r.z.literal("register"),t_id:bp,metadata:r.z.string().optional()}),Tp=wp.extend({op:r.z.literal("update"),uid:r.z.string(),t_id:bp,metadata:r.z.string().optional()}),Sp=wp.extend({op:r.z.literal("delete"),uid:r.z.string()}),kp=wp.extend({op:r.z.literal("migrate"),t_id:bp,metadata:r.z.string().optional()}),Ep=r.z.discriminatedUnion("op",[Ip,Tp,Sp,kp]);class Ap{constructor(e){this.network=e.network,this.logger=e.logger||D.getInstance({level:e.logLevel||"info",module:"HCS2Client",silent:e.silent}),this.mirrorNode=new G(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 Ep.parse(e),{valid:!0,errors:[]}}catch(t){const e=[];return t instanceof r.ZodError?t.errors.forEach(t=>{const r=t.path.join(".");e.push(`${r?r+": ":""}${t.message}`)}):e.push(`Unexpected error: ${t}`),this.logger.debug(`Message validation failed: ${e.join(", ")}`),{valid:!1,errors:e}}}createRegisterMessage(e,t,r,i="hcs-2"){return{p:i,op:fp.REGISTER,t_id:e,metadata:t,m:r}}createUpdateMessage(e,t,r,i,o="hcs-2"){return{p:o,op:fp.UPDATE,t_id:e,uid:t,metadata:r,m:i}}createDeleteMessage(e,t,r="hcs-2"){return{p:r,op:fp.DELETE,uid:e,m:t}}createMigrateMessage(e,t,r,i="hcs-2"){return{p:i,op:fp.MIGRATE,t_id:e,metadata:t,m:r}}parseRegistryEntries(e,t,r,i){const o=[];let n;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};o.push(l),(r===yp.NON_INDEXED||!n||l.timestamp>n.timestamp)&&(n=l)}catch(s){this.logger.warn(`Error parsing message: ${s}`)}return this.logger.debug(`Parsed ${o.length} valid entries for topic ${e}`),{topicId:e,registryType:r,ttl:i,entries:r===yp.INDEXED?o:n?[n]:[],latestEntry:n}}}function vp(e){var t,r;return Y({memo:e.memoOverride??(t=e.registryType,r=e.ttl,`hcs-2:${t}:${r}`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}const Cp=class e extends Ap{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?i.AccountId.fromString(e.operatorId):e.operatorId,this.operatorCtx=oe({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:this.createClient(e.network)}),this.client=this.operatorCtx.client}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}createClient(e){return"mainnet"===e?i.Client.forMainnet():i.Client.forTestnet()}async createRegistry(e={}){try{await this.ensureInitialized();const t=e.registryType??yp.INDEXED,r=e.ttl??86400;this.generateRegistryMemo(t,r);let o,n,s,a;if(e.adminKey)if("string"==typeof e.adminKey)try{n=i.PublicKey.fromString(e.adminKey)}catch{const t=globalThis.Buffer.from(e.adminKey.replace(/^0x/i,""),"hex");n="ed25519"===this.operatorCtx.keyType?i.PublicKey.fromBytesED25519(t):i.PublicKey.fromBytesECDSA(t)}else"boolean"==typeof e.adminKey?n=this.operatorCtx.operatorKey.publicKey:(n=e.adminKey.publicKey,o=e.adminKey);if(e.submitKey)if("string"==typeof e.submitKey)try{a=i.PublicKey.fromString(e.submitKey)}catch{const t=globalThis.Buffer.from(e.submitKey.replace(/^0x/i,""),"hex");a="ed25519"===this.operatorCtx.keyType?i.PublicKey.fromBytesED25519(t):i.PublicKey.fromBytesECDSA(t)}else"boolean"==typeof e.submitKey?a=this.operatorCtx.operatorKey.publicKey:(a=e.submitKey.publicKey,s=e.submitKey);const c=vp({registryType:t,ttl:r,adminKey:n,submitKey:a,operatorPublicKey:this.operatorCtx.operatorKey.publicKey}),l=await c.freezeWith(this.client);o&&await l.sign(o),s&&await l.sign(s);const d=await l.execute(this.client),u=(await d.getReceipt(this.client)).topicId;if(!u)throw new Error("Failed to create registry: No topic ID in receipt");const p=u.toString();return this.registryTypeCache.set(p,t),this.logger.info(`Created registry topic: ${p} (${t===yp.INDEXED?"Indexed":"Non-indexed"}, TTL: ${r}s)`),{success:!0,topicId:p,transactionId:d.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),o=t.registryType??await this.resolveRegistryType(e);this.registryTypeCache.set(e,o);const n=t.analyticsMemo??this.buildAnalyticsMemo(fp.REGISTER,o),s=await this.submitMessage(e,i,n);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!==yp.INDEXED)throw new Error("Update operation is only valid for indexed registries");const o=this.createUpdateMessage(t.targetTopicId,t.uid,t.metadata,t.memo),n=t.registryType??await this.resolveRegistryType(e);this.registryTypeCache.set(e,n);const s=t.analyticsMemo??this.buildAnalyticsMemo(fp.UPDATE,n),a=await this.submitMessage(e,o,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!==yp.INDEXED)throw new Error("Delete operation is only valid for indexed registries");const o=this.createDeleteMessage(t.uid,t.memo),n=t.registryType??await this.resolveRegistryType(e);this.registryTypeCache.set(e,n);const s=t.analyticsMemo??this.buildAnalyticsMemo(fp.DELETE,n),a=await this.submitMessage(e,o,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 o=t.analyticsMemo??this.buildAnalyticsMemo(fp.MIGRATE,i),n=await this.submitMessage(e,r,o);return this.logger.info(`Migrated registry ${e} to ${t.targetTopicId}`),{success:!0,receipt:n,sequenceNumber:n.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 i=await this.mirrorNode.getTopicInfo(e);this.logger.debug(`Retrieved topic info for ${e}: ${JSON.stringify(i)}`);const o=this.parseRegistryTypeFromMemo(i.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 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"}),s=t.limit?n.slice(0,t.limit):n;this.logger.debug(`Retrieved ${n.length} messages, using ${s.length} after applying limit.`);const a=[];let c;for(const t of s)try{const r={p:"hcs-2",op:t.op,t_id:t.t_id,uid:t.uid,metadata:t.metadata,m:t.m},{valid:i,errors:n}=this.validateMessage(r);if(!i){this.logger.warn(`Invalid HCS-2 message: ${n.join(", ")}`);continue}const s={topicId:e,sequence:t.sequence_number,timestamp:t.consensus_timestamp,payer:t.payer_account_id||t.payer||"",message:r,consensus_timestamp:t.consensus_timestamp,registry_type:o.registryType};a.push(s),(o.registryType===yp.NON_INDEXED||!c||s.timestamp>c.timestamp)&&(c=s)}catch(r){this.logger.warn(`Error processing message: ${r}`)}this.logger.debug(`Processed ${a.length} valid entries for registry ${e}`);return{topicId:e,registryType:o.registryType,ttl:o.ttl,entries:o.registryType===yp.INDEXED?a:c?[c]:[],latestEntry:c}}catch(r){throw this.logger.error(`Failed to get registry: ${r}`),r}}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:o}=this.validateMessage(t);if(!i)throw new Error(`Invalid HCS-2 message: ${o.join(", ")}`);const n=X({topicId:e,message:JSON.stringify(t),transactionMemo:r}),s=await n.execute(this.client);return await s.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}};Cp.operationAnalyticsCode={[fp.REGISTER]:0,[fp.UPDATE]:1,[fp.DELETE]:2,[fp.MIGRATE]:3};let xp=Cp;class Rp extends Ap{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,mirrorNodeUrl:e.mirrorNodeUrl,logger:e.logger}),this.hwc=e.hwc,va?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??yp.INDEXED,r=e.ttl??86400,o=this.generateRegistryMemo(t,r);let n=(new i.TopicCreateTransaction).setTopicMemo(o);if(e.adminKey){let t;if("string"==typeof e.adminKey)try{t=i.PublicKey.fromString(e.adminKey)}catch{const r=te.detect(e.adminKey);if(!r.rawBytes)throw new Error("Failed to parse admin public key");t="ed25519"===r.type?i.PublicKey.fromBytesED25519(r.rawBytes):i.PublicKey.fromBytesECDSA(r.rawBytes)}else t="boolean"==typeof e.adminKey?await this.mirrorNode.getPublicKey(this.getOperatorId()):e.adminKey.publicKey;n=n.setAdminKey(t)}if(e.submitKey){let t;if("string"==typeof e.submitKey)try{t=i.PublicKey.fromString(e.submitKey)}catch{const r=te.detect(e.submitKey);if(!r.rawBytes)throw new Error("Failed to parse submit public key");t="ed25519"===r.type?i.PublicKey.fromBytesED25519(r.rawBytes):i.PublicKey.fromBytesECDSA(r.rawBytes)}else t="boolean"==typeof e.submitKey?await this.mirrorNode.getPublicKey(this.getOperatorId()):e.submitKey.publicKey;n=n.setSubmitKey(t)}const s=await this.executeWithWallet(n);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===yp.INDEXED?"Indexed":"Non-indexed"}, TTL: ${r}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!==fp.REGISTER)throw new Error(`Invalid operation type: ${r.op}, expected ${fp.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!==yp.INDEXED)throw new Error("Update operation is only valid for indexed registries");const o=this.createUpdateMessage(t.targetTopicId,t.uid,t.metadata,t.memo),n=await this.submitMessage(e,o);return this.logger.info(`Updated entry with UID ${t.uid} in registry ${e}`),{success:!0,receipt:n,sequenceNumber:n.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!==yp.INDEXED)throw new Error("Delete operation is only valid for indexed registries");const o=this.createDeleteMessage(t.uid,t.memo),n=await this.submitMessage(e,o);return this.logger.info(`Deleted entry with UID ${t.uid} from registry ${e}`),{success:!0,receipt:n,sequenceNumber:n.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 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"}),n=t.limit?o.slice(0,t.limit):o;return this.parseRegistryEntries(e,n,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 o=X({topicId:e,message:JSON.stringify(t)}),n=await this.executeWithWallet(o);if(n?.error)throw new Error(n.error);return n.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 Np={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*))$/},_p=r.z.string().regex(Np.HEDERA_ACCOUNT_REGEX,"Invalid Hedera account ID format"),Pp=r.z.string().regex(/^\d+$/,"Must be a valid number").max(Np.MAX_NUMBER_LENGTH,`Max ${Np.MAX_NUMBER_LENGTH} digits`),Fp=r.z.string().min(1,"Tick cannot be empty").transform(e=>e.toLowerCase().trim()),Op=r.z.object({p:r.z.literal("hcs-20"),m:r.z.string().optional()}),zp=Op.extend({op:r.z.literal("deploy"),name:r.z.string().min(1).max(Np.MAX_NAME_LENGTH),tick:Fp,max:Pp,lim:Pp.optional(),metadata:r.z.string().max(Np.MAX_METADATA_LENGTH).optional()}),Dp=Op.extend({op:r.z.literal("mint"),tick:Fp,amt:Pp,to:_p}),Bp=Op.extend({op:r.z.literal("burn"),tick:Fp,amt:Pp,from:_p}),Mp=Op.extend({op:r.z.literal("transfer"),tick:Fp,amt:Pp,from:_p,to:_p}),Up=Op.extend({op:r.z.literal("register"),name:r.z.string().min(1).max(Np.MAX_NAME_LENGTH),metadata:r.z.string().max(Np.MAX_METADATA_LENGTH).optional(),private:r.z.boolean(),t_id:_p}),Kp=r.z.discriminatedUnion("op",[zp,Dp,Bp,Mp,Up]);class Lp extends Error{constructor(e){super(e),this.name="HCS20Error"}}class $p extends Lp{constructor(e,t){super(e),this.tick=t,this.name="PointsDeploymentError"}}class Hp extends Lp{constructor(e,t,r,i,o,n){super(e),this.tick=t,this.from=r,this.to=i,this.amount=o,this.availableBalance=n,this.name="PointsTransferError"}}class qp extends Lp{constructor(e,t,r,i,o){super(e),this.tick=t,this.from=r,this.amount=i,this.availableBalance=o,this.name="PointsBurnError"}}class jp extends Lp{constructor(e,t){super(e),this.validationErrors=t,this.name="PointsValidationError"}}class Wp extends Lp{constructor(e,t){super(e),this.topicId=t,this.name="TopicRegistrationError"}}class Vp extends Lp{constructor(e){super(`Invalid Hedera account format: ${e}`),this.account=e,this.name="InvalidAccountFormatError"}}class Gp{constructor(e){this.logger=e.logger||new D({module:"HCS20Client"}),this.network="mainnet"===e.network?"mainnet":"testnet",this.mirrorNode=new G(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0),this.registryTopicId=e.registryTopicId||Np.REGISTRY_TOPIC_ID,this.publicTopicId=e.publicTopicId||Np.PUBLIC_TOPIC_ID}validateMessage(e){try{return Kp.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(!Np.HEDERA_ACCOUNT_REGEX.test(e))throw new Vp(e);return e}return e.toString()}topicToString(e){if("string"==typeof e){if(!Np.HEDERA_ACCOUNT_REGEX.test(e))throw new Vp(e);return e}return e.toString()}}function Jp(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 X({topicId:e.topicId,message:JSON.stringify(t)})}function Yp(e){const t={p:"hcs-20",op:"mint",tick:e.tick.toLowerCase().trim(),amt:e.amt,to:e.to,m:e.memo};return X({topicId:e.topicId,message:JSON.stringify(t)})}function Xp(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 X({topicId:e.topicId,message:JSON.stringify(t)})}function Zp(e){const t={p:"hcs-20",op:"burn",tick:e.tick.toLowerCase().trim(),amt:e.amt,from:e.from,m:e.memo};return X({topicId:e.topicId,message:JSON.stringify(t)})}function Qp(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 X({topicId:e.registryTopicId,message:JSON.stringify(t)})}const eh="hcs-21",th=/^hcs:\/\/1\/0\.0\.\d+\/\d+$/,rh=/^0\.0\.\d+$/;var ih=(e=>(e[e.ADAPTER_REGISTRY=0]="ADAPTER_REGISTRY",e[e.REGISTRY_OF_REGISTRIES=1]="REGISTRY_OF_REGISTRIES",e))(ih||{});const oh=r.z.object({registry:r.z.string().min(1),name:r.z.string().min(1),version:r.z.string().min(1),integrity:r.z.string().min(1)}),nh=r.z.object({account:r.z.string().min(1),threshold:r.z.string().min(1),ctopic:r.z.string().min(1),ttopic:r.z.string().min(1),stopic:r.z.string().min(1)}),sh=r.z.object({p:r.z.literal(eh),op:r.z.enum(["register","update","delete"]),adapter_id:r.z.string().min(1),entity:r.z.string().min(1),package:oh,manifest:r.z.string().regex(th,"manifest must be an HCS-1 HRL (hcs://1/<topicId>/<sequence>)"),flora:nh,state_model:r.z.string().min(1),signature:r.z.string().min(1).optional()}),ah=r.z.object({meta:r.z.object({spec_version:r.z.string().min(1),adapter_version:r.z.string().min(1),minimum_flora_version:r.z.string().min(1),generated:r.z.string().min(1)}),adapter:r.z.object({name:r.z.string().min(1),id:r.z.string().min(1),maintainers:r.z.array(r.z.object({name:r.z.string().min(1),contact:r.z.string().min(1)})).min(1),license:r.z.string().min(1)}),package:r.z.object({registry:r.z.string().min(1),dist_tag:r.z.string().min(1).optional(),artifacts:r.z.array(r.z.object({url:r.z.string().min(1),digest:r.z.string().min(1),signature:r.z.string().min(1).optional()})).min(1)}),runtime:r.z.object({platforms:r.z.array(r.z.string().min(1)).min(1),primary:r.z.string().min(1),entry:r.z.string().min(1),dependencies:r.z.array(r.z.string().min(1)).optional(),env:r.z.array(r.z.string().min(1)).optional()}),capabilities:r.z.object({discovery:r.z.boolean(),communication:r.z.boolean(),protocols:r.z.array(r.z.string().min(1))}),consensus:r.z.object({entity_schema:r.z.string().min(1),required_fields:r.z.array(r.z.string().min(1)),hashing:r.z.literal("sha384")})}),ch=r.z.object({version:r.z.string().min(1),name:r.z.string().min(1),description:r.z.string().min(1),operator:r.z.object({account:r.z.string().min(1),name:r.z.string().optional(),contact:r.z.string().optional()}),entityTypes:r.z.array(r.z.string().min(1)),categories:r.z.array(r.z.string().min(1)).optional(),tags:r.z.array(r.z.string().min(1)).optional(),links:r.z.record(r.z.string().min(1)).optional()}),lh=r.z.union([ah,ch]);class dh extends Error{constructor(e,t){super(e),this.code=t,this.name="HCS21ValidationError"}}function uh(e){const t=e.indexed??0,r=e.type??ih.ADAPTER_REGISTRY;if(e.metaTopicId&&!rh.test(e.metaTopicId))throw new dh("Meta topic must be a Hedera topic ID (0.0.x)","invalid_payload");const i=e.metaTopicId?`:${e.metaTopicId}`:"";return`hcs-21:${t}:${e.ttl}:${r}${i}`}function ph(e){return Y({memo:uh({ttl:e.ttl,indexed:e.indexed,type:e.type,metaTopicId:e.metaTopicId}),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function hh(e){return X({topicId:e.topicId,message:JSON.stringify(e.declaration),transactionMemo:e.transactionMemo})}class gh{constructor(e){this.network=e.network,this.logger=e.logger||new D({level:"info",module:"HCS-21"}),this.mirrorNode=new G(this.network,this.logger,{customUrl:e.mirrorNodeUrl})}buildDeclaration(e){const t={p:eh,op:e.op,adapter_id:e.adapterId,entity:e.entity,package:e.adapterPackage,manifest:e.manifest,flora:e.flora,state_model:e.stateModel,signature:e.signature};return this.validateDeclaration(t)}validateDeclaration(e){try{const t="string"==typeof e?JSON.parse(e):e,r=sh.parse(t);return this.assertSizeLimit(r),r}catch(t){const e=t instanceof Error?t.message:"Invalid adapter declaration";throw new dh(e,"invalid_payload")}}async fetchDeclarations(e,t){const r=await this.mirrorNode.getTopicMessages(e,{limit:t?.limit,order:t?.order}),i=[];for(const n of r)if(n.p===eh)try{const e=this.validateDeclaration(n);i.push({declaration:e,consensusTimestamp:n.consensus_timestamp,sequenceNumber:n.sequence_number,payer:n.payer})}catch(o){const e=o instanceof Error?o.message:"unknown error";this.logger.warn(`Skipping invalid HCS-21 message: ${e}`)}return i}assertSizeLimit(e){const t=JSON.stringify(e),r=globalThis.Buffer.byteLength(t,"utf8");if(r>1024)throw new dh(`HCS-21 payload exceeds 1024 bytes (${r})`,"size_exceeded")}}function mh(e){const t=(new i.AccountCreateTransaction).setECDSAKeyWithAlias(e.publicKey).setInitialBalance(e.initialBalance instanceof i.Hbar?e.initialBalance:new i.Hbar(e.initialBalance??1));return"number"==typeof e.maxAutomaticTokenAssociations&&t.setMaxAutomaticTokenAssociations(e.maxAutomaticTokenAssociations),e.accountMemo&&t.setAccountMemo(e.accountMemo),t}function fh(e){const t=(new i.AccountCreateTransaction).setKeyWithoutAlias(e.publicKey).setInitialBalance(e.initialBalance instanceof i.Hbar?e.initialBalance:new i.Hbar(e.initialBalance??1));return"number"==typeof e.maxAutomaticTokenAssociations&&t.setMaxAutomaticTokenAssociations(e.maxAutomaticTokenAssociations),e.accountMemo&&t.setAccountMemo(e.accountMemo),t}class yh{constructor(e){this.network=e.network,this.logger=e.logger||new D({module:"HCS-15",level:e.logLevel||"info"}),this.mirrorNode=new G(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),o=r?.key?.key||"";return""!==o&&o===(i?.key?.key||"")}catch(ag){return this.logger.warn("verifyPetalAccount failed",{error:String(ag)}),!1}}}var bh=(e=>(e[e.COMMUNICATION=0]="COMMUNICATION",e[e.TRANSACTION=1]="TRANSACTION",e[e.STATE=2]="STATE",e))(bh||{}),wh=(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))(wh||{});class Ih extends Error{constructor(e,t){super(e),this.code=t,this.name="FloraError"}}function Th(e){const t=function(e){return`hcs-16:${e.floraAccountId}:${e.topicType}`}({floraAccountId:e.floraAccountId,topicType:e.topicType}),r=Y({memo:t,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey});return e.autoRenewAccountId&&r.setAutoRenewAccountId(i.AccountId.fromString(e.autoRenewAccountId)),r}function Sh(e){const t=(new i.AccountCreateTransaction).setKey(e.keyList),r="number"==typeof e.initialBalanceHbar?e.initialBalanceHbar:1;t.setInitialBalance(new i.Hbar(r));const o="number"==typeof e.maxAutomaticTokenAssociations?e.maxAutomaticTokenAssociations:-1;return t.setMaxAutomaticTokenAssociations(o),t}function kh(e){const t={p:"hcs-16",op:e.op,operator_id:e.operatorId,...e.body||{}};return X({topicId:e.topicId,message:JSON.stringify(t)})}function Eh(e){return kh({topicId:e.topicId,operatorId:e.operatorId,op:wh.FLORA_CREATED,body:{flora_account_id:e.floraAccountId,topics:e.topics}})}function Ah(e){return kh({topicId:e.topicId,operatorId:e.operatorId,op:wh.TRANSACTION,body:{schedule_id:e.scheduleId,data:e.data,m:e.data}})}function vh(e){return kh({topicId:e.topicId,operatorId:e.operatorId,op:wh.STATE_UPDATE,body:{hash:e.hash,epoch:e.epoch,timestamp:(new Date).toISOString()}})}function Ch(e){return kh({topicId:e.topicId,operatorId:e.operatorId,op:wh.FLORA_JOIN_REQUEST,body:{candidate_account_id:e.candidateAccountId}})}function xh(e){return kh({topicId:e.topicId,operatorId:e.operatorId,op:wh.FLORA_JOIN_VOTE,body:{candidate_account_id:e.candidateAccountId,approve:e.approve}})}function Rh(e){return kh({topicId:e.topicId,operatorId:e.operatorId,op:wh.FLORA_JOIN_ACCEPTED,body:{members:e.members,epoch:e.epoch}})}class Nh{constructor(e){this.network=e.network,this.logger=e.logger||new D({level:"info",module:"HCS-16"}),this.mirrorNode=new G(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 i.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 i.KeyList(t,1)}buildFloraTopicCreateTxs(e){return{communication:Th({floraAccountId:e.floraAccountId,topicType:bh.COMMUNICATION,adminKey:e.keyList,submitKey:e.submitList,autoRenewAccountId:e.autoRenewAccountId}),transaction:Th({floraAccountId:e.floraAccountId,topicType:bh.TRANSACTION,adminKey:e.keyList,submitKey:e.submitList,autoRenewAccountId:e.autoRenewAccountId}),state:Th({floraAccountId:e.floraAccountId,topicType:bh.STATE,adminKey:e.keyList,submitKey:e.submitList,autoRenewAccountId:e.autoRenewAccountId})}}parseTopicMemo(e){const t=e.match(/^hcs-16:([0-9.]+):(\d)$/);return t?{protocol:"hcs-16",floraAccountId:t[1],topicType:Number(t[2])}:null}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",o=await this.mirrorNode.getTopicMessages(e,{limit:r,order:i}),n=[];for(const s of o){if("hcs-16"!==s.p)continue;const{consensus_timestamp:e,sequence_number:r,running_hash:i,running_hash_version:o,topic_id:a,payer:c,created:l,chunk_info:d,...u}=s,p=u.op,h=u.operator_id;if(t?.opFilter&&p!==t.opFilter)continue;if("string"!=typeof h)continue;const g=u;n.push({message:g,consensus_timestamp:e,sequence_number:Number(r),payer:c})}return n}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 _h=r.z.object({p:r.z.literal("hcs-17"),op:r.z.literal("state_hash"),state_hash:r.z.string().min(1),topics:r.z.array(r.z.string()),account_id:r.z.string().min(1),timestamp:r.z.string().optional(),m:r.z.string().optional()});class Ph extends Error{constructor(e,t){super(e),this.code=t,this.name="StateHashError"}}var Fh=(e=>(e[e.STATE=0]="STATE",e))(Fh||{});function Oh(e){return`hcs-17:0:${e}`}function zh(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;return{type:r,ttl:i}}catch{return}}class Dh{constructor(e){this.network=e.network,this.logger=e.logger||new D({level:e.logLevel||"info",module:"HCS-17"}),this.mirrorNode=new G(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,timestamp:(new Date).toISOString(),m:e.memo}}validateMessage(e){const t=_h.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 Oh(e)}async validateHCS17Topic(e){try{const t=zh((await this.mirrorNode.getTopicInfo(e)).memo);return t?t.type!==Fh.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(ag){return{valid:!1,error:String(ag)}}}async getRecentMessages(e,t){const r=t?.limit??25,i=t?.order??"desc",o=await this.mirrorNode.getTopicMessages(e,{limit:r,order:i}),n=[];for(const s of o)try{if("hcs-17"!==s.p||"state_hash"!==s.op)continue;const e=s,{valid:t}=this.validateMessage(e);if(!t)continue;n.push({message:{p:"hcs-17",op:"state_hash",state_hash:e.state_hash,topics:e.topics,account_id:e.account_id,timestamp:e.timestamp,m:e.m},consensus_timestamp:e.consensus_timestamp,sequence_number:Number(e.sequence_number),payer:e.payer})}catch(cg){this.logger.debug(`Failed to parse HCS-17 message: ${cg}`)}return n}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:o}=t[0];return Object.assign({},r,{consensus_timestamp:i,sequence_number:o})}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 o=w.createHash("sha384");o.update(r);const n=o.digest("hex");return this.logger.debug("Account state hash calculated",{accountId:e.accountId,stateHash:n}),{stateHash:n,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 o=w.createHash("sha384");o.update(i);const n=o.digest("hex");return this.logger.debug("Composite state hash calculated",{compositeAccountId:e.compositeAccountId,stateHash:n}),{stateHash:n,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=w.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,o="accountId"in e?e.accountId:e.compositeAccountId;return this.logger.debug("State hash verification",{accountId:o,isValid:i,expected:t,calculated:r}),i}catch(r){return this.logger.error("Failed to verify state hash",r),!1}}}function Bh(e){return Y({memo:Oh(e.ttl),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Mh(e){const t={p:"hcs-17",op:"state_hash",state_hash:e.stateHash,topics:e.topics,account_id:e.accountId,timestamp:(new Date).toISOString(),m:e.memo};return X({topicId:e.topicId,message:JSON.stringify(t),transactionMemo:e.transactionMemo})}var Uh=(e=>(e.ANNOUNCE="announce",e.PROPOSE="propose",e.RESPOND="respond",e.COMPLETE="complete",e.WITHDRAW="withdraw",e))(Uh||{});function Kh(e){return"object"==typeof e&&null!==e}function Lh(e){return"string"==typeof e}function $h(e){return"number"==typeof e&&Number.isFinite(e)}function Hh(e){if(!Kh(e))return!1;if("hcs-18"!==e.p)return!1;if(!Lh(e.op))return!1;const t=e.op;return!!["announce","propose","respond","complete","withdraw"].includes(t)&&"data"in e}var qh=(e=>(e.IDLE="idle",e.ANNOUNCED="announced",e.PROPOSING="proposing",e.FORMING="forming",e.ACTIVE="active",e.WITHDRAWN="withdrawn",e))(qh||{});class jh extends Error{constructor(e,t){super(e),this.code=t,this.name="DiscoveryError"}}function Wh(e,t){return t&&t.trim().length>0?t:e&&e>0?`hcs-18:0:${e}`:"hcs-18:0"}function Vh(e){return Y({memo:Wh(e.ttlSeconds,e.memoOverride),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Gh(e){const t="string"==typeof e.transactionMemo&&e.transactionMemo.length>0?e.transactionMemo:`hcs-18:op:${function(e){switch(e){case Uh.ANNOUNCE:return 0;case Uh.PROPOSE:return 1;case Uh.RESPOND:return 2;case Uh.COMPLETE:return 3;case Uh.WITHDRAW:return 4;default:return 0}}(e.message.op)}`;return(new i.TopicMessageSubmitTransaction).setTopicId(e.topicId).setMessage(JSON.stringify(e.message)).setTransactionMemo(t)}function Jh(e){return{p:"hcs-18",op:Uh.ANNOUNCE,data:e}}function Yh(e){return{p:"hcs-18",op:Uh.PROPOSE,data:e}}function Xh(e){return{p:"hcs-18",op:Uh.RESPOND,data:e}}function Zh(e){return{p:"hcs-18",op:Uh.COMPLETE,data:e}}function Qh(e){return{p:"hcs-18",op:Uh.WITHDRAW,data:e}}class eg{constructor(e){this.network=e.network,this.logger=e.logger||D.getInstance({module:"HCS-18"}),this.mirrorNode=new G(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}}var tg=(e=>(e.FIXED_FEE="FIXED_FEE",e.FRACTIONAL_FEE="FRACTIONAL_FEE",e.ROYALTY_FEE="ROYALTY_FEE",e))(tg||{});class rg{constructor(e){this.customFees=[],this.logger=e.logger,this.mirrorNode=new G(e.network,e.logger),this.defaultCollectorAccountId=e.defaultCollectorAccountId||""}static forHbar(e,t,r,i,o=[]){return new rg({network:r,logger:i,defaultCollectorAccountId:t}).addHbarFee(e,t,o)}static async forToken(e,t,r,i,o,n=[],s){const a=new rg({network:i,logger:o,defaultCollectorAccountId:r});return await a.addTokenFee(e,t,r,s,n),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:tg.FIXED_FEE}),this}async addTokenFee(e,t,r,i,o=[]){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 n=i;if(void 0===n)try{const e=await this.mirrorNode.getTokenInfo(t);e?.decimals?(n=parseInt(e.decimals,10),this.logger.info(`Fetched decimals for ${t}: ${n}`)):(this.logger.warn(`Could not fetch decimals for ${t}, defaulting to 0.`),n=0)}catch(s){this.logger.error(`Error fetching decimals for ${t}, defaulting to 0: ${s}`),n=0}return this.customFees.push({feeAmount:{amount:e*10**n,decimals:n},feeCollectorAccountId:r||this.defaultCollectorAccountId,feeTokenId:t,exemptAccounts:[...o],type:tg.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 ig{constructor(){this.resolver=null,this.onUnavailableCallbacks=[],this.logger=D.getInstance({module:"ContentResolverRegistry"})}static getInstance(){return ig._instance||(ig._instance=new ig),ig._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 og=ig.getInstance();class ng{constructor(){this.contentStore=null,this.logger=D.getInstance({module:"ContentStoreService"})}static getInstance(){return ng._instance||(ng._instance=new ng),ng._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 sg=ng.getInstance();exports.AIAgentCapability=bd,exports.AIAgentDetailsSchema=Ed,exports.AIAgentProfileSchema=Fd,exports.AIAgentType=fd,exports.AccountCreationError=eu,exports.ActionBuilder=class{constructor(e){this.cryptoAdapter=nd(),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(Zl())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(Zl())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(Zl())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 o=0;o<Math.min(r.length,256);o++)i=(i<<5)-i+r[o]&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),o=await this.generateInfoHash(r),n=this.registration.js_t_id,s=this.registration.js_hash,a=this.registration.interface_version;return this.reset().setTopicId(e).setHash(o).setWasmHash(i),n&&this.setJsTopicId(n),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=vu,exports.AgentBuilder=iu,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 D({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(),o=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 n={p:"hcs-12",op:"add-block",block_t_id:t,...Object.keys(i).length>0&&{actions:i},attributes:o};return this.operations.push(n),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=Nu,exports.AssemblyRegistry=xu,exports.BaseProfileSchema=_d,exports.BaseRegistry=au,exports.BlockBuilder=Pu,exports.BlockLoader=Cu,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 Ou(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 Fu(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={},o=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||{},o={...t.attributes,...o})}const n={};e.attributes&&Object.entries(e.attributes).forEach(([e,t])=>{t&&"object"==typeof t&&"default"in t&&(n[e]=t.default)});const s={...n};o&&"object"==typeof o&&Object.entries(o).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,o=e.dataset.params;this.logger.debug("Action button clicked",{actionTopicId:i,paramsStr:o,hasAction:!!i}),i&&await this.executeAction(t,i,o)})})}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(ag){this.logger.warn("Failed to parse action params",{paramsStr:r})}const o=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:o.attributes});const n=await this.wasmExecutor.execute(r,{method:"POST",params:i,state:o.attributes});if(this.logger.debug("WASM execution result",{result:n}),n.success&&n.data){const t=i.operation||"default";let r=n.data;r.success&&r.data&&(r=r.data);const s={...o,attributes:{...o.attributes,...r},actionResults:{...o.actionResults,[t]:r}};this.stateManager.updateBlockState(e,s),await this.updateBlockDisplay(e,s)}else this.logger.error("Action execution failed",{result:n})}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 zu(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 o=await this.hashLinkScanner.scanTemplate(e);if(0===o.length)return e;this.logger.debug("Processing HashLinks",{parentBlockId:t.id,referenceCount:o.length});const n={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&&(n.actions=e.actions)}let s=e;for(let e=0;e<o.length;e++){const t=o[e];try{const e=await this.hashLinkResolver.resolveReference(t,n);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},o={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:n.depth,parentContext:n,initialState:o};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 o=this.stateListeners.get(e)||[];for(const s of o)try{s(i,r,e)}catch(n){this.logger.error("State change listener error",{blockId:e,error:n})}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 o={type:r,payload:i,fromBlock:e,toBlock:t},n=this.messageHandlers.get(t)||[];for(const a of n)try{a(o)}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 o=this.messageHandlers.get(i)||[],n={type:e,payload:t,fromBlock:"system",toBlock:i};for(const t of o)try{t(n)}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 o=this.getBlockState(e);let n;try{if(r.success&&i.onSuccess)n=i.onSuccess(o,r);else{if(r.success||!i.onError)return;n=i.onError(o,r)}n&&this.updateBlockState(e,n),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],o=i.type;if("string"===o&&"string"!=typeof r)throw new Error(`State validation failed: property '${e}' must be string`);if("number"===o&&"number"!=typeof r)throw new Error(`State validation failed: property '${e}' must be number`);if("number"===o&&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 o=this.messageHandlers.get(e)||[],n={type:t,payload:r,fromBlock:i,toBlock:e};for(const a of o)try{a(n)}catch(s){this.logger.error("Message handler error",{blockId:e,type:t,error:s})}}},exports.BrowserHCS20Client=class extends Gp{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 Rp({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 Rp({hwc:this.hwc,network:this.network}),o=await r.createRegistry({submitKey:e.toString(),adminKey:e.toString()});if(!o.success)throw new Error("Failed to create topic");i=o.topicId,this.logger.info(`Created private topic: ${i}`)}else i=this.publicTopicId;r?.({stage:"submitting-deploy",percentage:50,topicId:i});const o={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},n=this.validateMessage(o);if(!n.valid)throw new jp("Invalid deploy message",n.errors);const s=await this.submitPayload(i,o,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,o=await this.submitPayload(i,r,!1),n=o.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,mintTxId:n}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,mintTxId:n}),{id:n,operation:"mint",tick:this.normalizeTick(e.tick),amount:e.amount,to:this.accountToString(e.to),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:n,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,o=await this.submitPayload(i,r,!1),n=o.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,transferTxId:n}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,transferTxId:n}),{id:n,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:n,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,o=await this.submitPayload(i,r,!1),n=o.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,burnTxId:n}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,burnTxId:n}),{id:n,operation:"burn",tick:this.normalizeTick(e.tick),amount:e.amount,from:this.accountToString(e.from),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:n,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 jp("Invalid register message",i.errors);t?.({stage:"submitting",percentage:50});const o=await this.submitPayload(this.registryTopicId,r,!1),n=o.transactionHash?.toString()||"";t?.({stage:"confirming",percentage:80,registerTxId:n}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,registerTxId:n})}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),new Wp(r instanceof Error?r.message:"Unknown error",this.topicToString(e.topicId))}}async submitPayload(e,t,r){let o;this.logger.debug(`Submitting payload to topic ${e}`),o="string"==typeof t?t:JSON.stringify(t);const n=(new i.TopicMessageSubmitTransaction).setTopicId(i.TopicId.fromString(e)).setMessage(o);r&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),n.setMaxTransactionFee(new i.Hbar(this.feeAmount)));const s=await this.hwc.executeTransactionWithErrorHandling(n,!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=Rp,exports.BrowserHCSClient=class extends Xd{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=D.getInstance({level:t,module:"HCS-Browser",prettyPrint:e.prettyPrint,silent:e.silent}),nu)try{const{accountId:t,signer:r}=this.getAccountAndSigner();this.hcs11Client=new Bd({network:e.network,auth:{operatorId:t,signer:r},logLevel:e.logLevel,silent:e.silent})}catch(cg){this.logger.warn(`Failed to initialize HCS11Client: ${cg}`)}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,o){this.logger.info("Sending message");const n={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(n);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:o?.progressCallback,waitMaxAttempts:o?.waitMaxAttempts,waitIntervalMs:o?.waitIntervalMs});if(!Ua(i))throw new Error("Failed to inscribe large message content");n.data=`hcs://1/${Ua(i)}`,this.logger.info(`Large message inscribed with topic ID: ${Ua(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,n,i,s.requiresFee)}async getPublicKey(e){return await this.mirrorNode.getPublicKey(e)}async handleConnectionRequest(e,t,r,o="Connection accepted. Looking forward to collaborating!",n=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 i.KeyList([c,a],1),d=this._generateHcs10Memo(Yd.CONNECTION,{ttl:n,inboundTopicId:e,connectionId:r}),u=(new i.TopicCreateTransaction).setTopicMemo(d).setAutoRenewAccountId(i.AccountId.fromString(s)).setAdminKey(l).setSubmitKey(l);this.logger.debug("Executing topic creation transaction");const p=await this.hwc.executeTransactionWithErrorHandling(u,!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,r,m,o),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:r,confirmedRequestId:f,connectionTopicId:g,operatorId:w,memo:`Connection established with ${t}`}),{connectionTopicId:g,confirmedConnectionSequenceNumber:f,operatorId:m}}async confirmConnection(e,t,r,i,o,n){this.logger.info("Confirming connection");const s={p:"hcs-10",op:"connection_created",connection_topic_id:t,connected_account_id:r,operator_id:o,connection_id:i,m:n},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 ps({module:"ProfileCreate",logger:this.logger,callback:r});try{const r=e instanceof iu;let o;if(o=t?.existingState?t.existingState:{currentStage:"init",completedPercentage:0,createdResources:[]},r){this.logger.info("Creating Agent Profile and HCS-10 Topics");const t=e.build();o.agentMetadata=t.metadata}else this.logger.info("Creating Person HCS-11 Profile");i.preparing(`Starting ${r?"agent":"person"} resource creation`,0,{state:o});const{inboundTopicId:n,outboundTopicId:s,state:a}=await this.createCommunicationTopics(t,i);let c,l,d;if(o=a,e.setInboundTopicId(n),e.setOutboundTopicId(s),r){const t=e.build();c=t.existingPfpTopicId||o.pfpTopicId,l=t.pfpBuffer,d=t.pfpFileName||"pfp.png"}else{const t=e.build();c=o.pfpTopicId,l=t.pfpBuffer,d=t.pfpFileName}!c&&l&&d?c=await this.handleProfilePictureCreation(l,d,o,i):c&&(i.preparing(`Using existing profile picture: ${c}`,50,{state:o}),o.pfpTopicId=c),await this.createAndInscribeProfile(r,e,c,o,n,s,t,i),o.currentStage="complete",o.completedPercentage=100,i.completed((r?"Agent":"Person")+" profile created successfully",{profileTopicId:o.profileTopicId,inboundTopicId:n,outboundTopicId:s,pfpTopicId:c,state:o});let u="";o.outboundTopicId&&(u=o.outboundTopicId);let p="";o.inboundTopicId&&(p=o.inboundTopicId);let h="";o.pfpTopicId&&(h=o.pfpTopicId);let g="";return o.profileTopicId&&(g=o.profileTopicId),{outboundTopicId:u,inboundTopicId:p,pfpTopicId:h,profileTopicId:g,success:!0,state:o}}catch(o){return i.failed("Error during profile creation",{error:o.message}),{outboundTopicId:"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:o.message,state:{currentStage:"init",completedPercentage:0,error:o.message}}}}async handleProfilePictureCreation(e,t,r,i){r.currentStage="pfp",i.preparing("Creating profile picture",30,{state:r});const o=i.createSubProgress({minPercent:30,maxPercent:50,logPrefix:"PFP"}),n=await this.inscribePfp(e,t,{progressCallback:e=>o.report({...e,progressPercent:e.progressPercent??0,details:{...e.details,state:r}})});if(!n.success){let e="Failed to inscribe profile picture";throw n.error&&(e=n.error),new Error(e)}const s=n.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,o,n,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:o,outboundTopicId:n,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:o,outboundTopicId:n})}const d=await this.hcs11Client.createAndInscribeProfile(l,s?.updateAccountMemo??!0,{progressCallback:e=>c?.report({...e,progressPercent:e.progressPercent??0})});if(!d.success){a&&a.failed(`Failed to inscribe ${e?"agent":"person"} profile`,{error:d.error});let t=`Failed to inscribe ${e?"agent":"person"} profile`;throw d.error&&(t=d.error),new Error(t)}i.profileTopicId=d.profileTopicId,i.createdResources&&i.createdResources.push(`profile:${d.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,r){try{let o;if(this.logger.info("Registering agent with guarded registry"),r?.existingState?.inboundTopicId)this.logger.info("Using inboundTopicId from existing state"),o=r.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}}}o=t.topicInfo.inboundTopic}const n=this.initializeRegistrationState(o,r?.existingState),s=new ps({module:"AgentRegistration",logger:this.logger,callback:r?.progressCallback});s.preparing("Preparing agent registration",10,{inboundTopicId:o,accountId:e});const a=await this.executeRegistration(e,t,this.guardedRegistryBaseUrl,this.logger);if(!a.success)return{...a,state:n};if(s.submitting("Submitting registration to registry",30,{transactionId:a.transactionId}),a.transaction){const e=i.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:n};this.logger.info("Successfully processed registration transaction")}s.confirming("Confirming registration transaction",60,{accountId:e,inboundTopicId:o,transactionId:a.transactionId});const c=r?.maxAttempts??60,l=r?.delayMs??2e3,d=await this.waitForRegistrationConfirmation(a.transactionId,t,this.guardedRegistryBaseUrl,c,l,this.logger);return this.updateStateForCompletedRegistration(n,o),s.completed("Agent registration complete",{transactionId:a.transactionId,inboundTopicId:o,state:n,confirmed:d}),{...a,confirmed:d,state:n}}catch(o){return this.logger.error(`Registration error: ${o.message}`),{error:`Error during registration: ${o.message}`,success:!1,state:{currentStage:"registration",completedPercentage:0,error:o.message}}}}async createAndRegisterAgent(e,t){try{const r=e.build(),i=t?.progressCallback,o=new ps({module:"AgentCreateRegister",logger:this.logger,callback:i});let n=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};if(n.agentMetadata=r.metadata,o.preparing("Starting agent creation process",0,{state:n}),"complete"!==n.currentStage||!n.inboundTopicId||!n.outboundTopicId||!n.profileTopicId){const t=await this.create(e,{progressCallback:e=>{const t=.3*(e.progressPercent||0);o.report({...e,progressPercent:t,details:{...e.details,state:e.details?.state||n}})},existingState:n,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");n=t.state,n.agentMetadata=r.metadata,this.logger.info("Waiting for account memo update to propagate..."),await new Promise(e=>setTimeout(e,5e3))}o.preparing(`Agent creation status: ${n.currentStage}, ${n.completedPercentage}%`,30,{state:n});const{accountId:s}=this.getAccountAndSigner();if("complete"!==n.currentStage||!n.createdResources?.includes(`registration:${n.inboundTopicId}`)){t?.baseUrl&&(this.guardedRegistryBaseUrl=t.baseUrl);const e=await this.registerAgentWithGuardedRegistry(s,r.network,{progressCallback:e=>{const t=30+.7*(e.progressPercent||0);o.report({...e,progressPercent:t,details:{...e.details,state:e.details?.state||n}})},maxAttempts:t?.maxAttempts,delayMs:t?.delayMs,existingState:n});if(!e.success)throw new Error(e.error||"Failed to register agent with registry");n=e.state}return o.completed("Agent creation and registration complete",{state:n}),{success:!0,state:n,metadata:{accountId:s,operatorId:`${n.inboundTopicId}@${s}`,inboundTopicId:n.inboundTopicId,outboundTopicId:n.outboundTopicId,profileTopicId:n.profileTopicId,pfpTopicId:n.pfpTopicId,privateKey:null,...n.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,o=[],n={},s,a,c,l){try{const d=l?.progressCallback,u=new ps({module:"StoreHCS11Profile",logger:this.logger,callback:d});u.preparing("Preparing agent profile data",0);let p=c;if(!p&&s&&a){const e=u.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:u.failed("Failed to inscribe profile picture, continuing without PFP")}else c?u.preparing(`Using existing profile picture: ${c}`,30):u.preparing("No profile picture provided",30);if(!this.hcs11Client)return u.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:n.type||"autonomous"});u.preparing("Building agent profile",65);const g=n.socials?Object.entries(n.socials).filter(([e,t])=>t).map(([e,t])=>({platform:e,handle:t})):void 0,m=this.hcs11Client.createAIAgentProfile(e,h,o,n.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:p?`hcs://1/${p}`:void 0,socials:g,properties:{version:n.version||"1.0.0",creator:n.creator||"Unknown",supported_languages:n.supported_languages||["en"],permissions:n.permissions||[],model_details:n.model_details,training:n.training,capabilities_description:n.capabilities_description,...n},inboundTopicId:r,outboundTopicId:i,creator:n.creator}),f=u.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?(u.completed("Profile stored successfully",{profileTopicId:y.profileTopicId}),{profileTopicId:y.profileTopicId,pfpTopicId:p,success:!0,transactionId:y.transactionId||""}):(u.failed("Failed to inscribe profile"),{profileTopicId:"",success:!1,error:y.error||"Failed to inscribe profile",transactionId:y.transactionId||""})}catch(d){return this.logger.error(`Error storing HCS11 profile: ${d.message}`),{profileTopicId:"",success:!1,error:d.message,transactionId:""}}}async createTopic(e,t,r){this.logger.info("Creating topic");const{accountId:o,signer:n}=this.getAccountAndSigner(),s=(new i.TopicCreateTransaction).setTopicMemo(e),a=await this.mirrorNode.getPublicKey(o);t&&a&&(s.setAdminKey(a),s.setAutoRenewAccountId(o)),r&&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 d=c.result;return d?.topicId?{success:!0,topicId:d.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,r,o){let n;this.logger.debug(`Submitting payload to topic ${e}`),n="string"==typeof t?t:JSON.stringify(t);const s=(new i.TopicMessageSubmitTransaction).setTopicId(e).setMessage(n),a=this.getHcs10TransactionMemo(t);let c;if(a&&s.setTransactionMemo(a),o&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),s.setMaxTransactionFee(new i.Hbar(this.feeAmount))),r){const{signer:e}=this.getAccountAndSigner();s.freezeWithSigner(e);const t=await s.sign(r);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:o}=this.getAccountAndSigner(),n=k.lookup(t)||"application/octet-stream",s=await us.createWithAuth({type:"client",accountId:i,signer:o,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 Oa({type:"buffer",buffer:e,fileName:t,mimeType:n},o,{...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,o=new ps({module:"PFP-Inscription",logger:this.logger,callback:i});if(!this.hcs11Client)return o.failed("HCS11Client is not available in this environment"),{pfpTopicId:"",success:!1,error:"HCS11Client is not available in this environment",transactionId:""};o.preparing("Preparing to inscribe profile picture",10),this.logger.info("Inscribing profile picture using HCS-11 client");const n=e=>{o.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:n});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 o.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 o=this._generateHcs10Memo(Yd.OUTBOUND,{ttl:e?.ttl,accountId:i}),n=await this.createTopic(o,!0,!0);if(!n.success||!n.topicId)throw new Error(n.error||"Failed to create outbound topic");r.outboundTopicId=n.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 o=this._generateHcs10Memo(Yd.INBOUND,{ttl:e?.ttl,accountId:i}),n=await this.createTopic(o,!0,!1);if(!n.success||!n.topicId)throw new Error(n.error||"Failed to create inbound topic");r.inboundTopicId=n.topicId,r.createdResources&&r.createdResources.push(`inbound:${r.inboundTopicId}`)}return{inboundTopicId:r.inboundTopicId,outboundTopicId:r.outboundTopicId,state:r}}},exports.CanonicalAgentDataSchema=Uu,exports.ConnectionConfirmationError=ru,exports.ConnectionsManager=class{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=D.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,o]=await Promise.all([this.baseClient.getMessages(t?.outboundTopic),this.baseClient.getMessages(t?.inboundTopic)]);this.processOutboundMessages(i.messages||[],e),this.processInboundMessages(o.messages||[]);const n=Array.from(this.connections.values()).filter(e=>"pending"===e.status||e.isPending).length;return this.logger.debug(`Processed ${i.messages?.length||0} outbound and ${o.messages?.length||0} inbound messages. Found ${n} 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,o]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 o){const i=e.connectionRequestId;if(!i)continue;const o=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(o?.connection_topic_id){r=!0;const t=o.connection_topic_id;let n=e.uniqueRequestKey;const s={connectionTopicId:t,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName,targetInboundTopicId:e.targetInboundTopicId,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(o.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),n&&this.connections.delete(n),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 o of r){if(this.logger.debug(`Processing pending connection: ${o.connectionTopicId}`),!o.targetAccountId){this.logger.debug(`Skipping connection ${o.connectionTopicId} - no targetAccountId`);continue}let e=o.targetInboundTopicId;if(!e)try{const t=await this.baseClient.retrieveProfile(o.targetAccountId);if(!t?.profile?.inboundTopicId){this.logger.debug(`Couldn't get inbound topic ID for account ${o.targetAccountId}`);continue}e=t.profile.inboundTopicId,this.connections.set(o.connectionTopicId,{...o,targetInboundTopicId:e}),this.logger.debug(`Updated connection ${o.connectionTopicId} with inbound topic ID: ${e}`)}catch(i){this.logger.debug(`Error fetching profile for ${o.targetAccountId}: ${i}`);continue}if(!e||e.includes(":")){this.logger.debug(`Skipping invalid inbound topic format: ${e}`);continue}const t=o.connectionRequestId||o.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 ${o.targetAccountId} on their inbound topic`);const r={connectionTopicId:e,targetAccountId:o.targetAccountId,targetAgentName:o.targetAgentName,targetInboundTopicId:o.targetInboundTopicId,targetOutboundTopicId:o.targetOutboundTopicId,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(i.created||o.created),lastActivity:new Date(i.created||o.created),profileInfo:o.profileInfo,connectionRequestId:o.connectionRequestId,confirmedRequestId:o.confirmedRequestId,requesterOutboundTopicId:o.requesterOutboundTopicId,inboundRequestId:o.inboundRequestId,closedReason:o.closedReason,closeMethod:o.closeMethod,uniqueRequestKey:o.uniqueRequestKey,originTopicId:o.originTopicId,processed:o.processed,memo:o.memo};this.connections.set(e,r),o.connectionTopicId&&this.connections.delete(o.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 ${o.targetAccountId}: ${i}`)}else this.logger.debug(`Skipping connection ${o.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 n of r){const e=n.connection_request_id,r=n.operator_id||"",i=this.baseClient.extractAccountFromOperatorId(r),o=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:n.outbound_topic_id||"",targetAccountId:i,targetTopicId:o,operatorId:r,sequenceNumber:n.sequence_number,created:n.created||new Date,memo:n.m,status:"pending"};if(this.pendingRequests.set(a,s),!this.connections.has(a)){const t={connectionTopicId:a,targetAccountId:i,targetInboundTopicId:o,status:"pending",isPending:!0,needsConfirmation:!1,created:n.created||new Date,connectionRequestId:e,uniqueRequestKey:a,originTopicId:n.outbound_topic_id||"",processed:!1,memo:n.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 n of i){const e=n.connection_request_id,t=n.connection_topic_id,r=this.baseClient.extractAccountFromOperatorId(n.operator_id||"");if(this.shouldFilterAccount(r)){this.logger.debug(`Filtering out outbound confirmation to account: ${r}`);continue}const i=`req-${e}:${n.operator_id}`,o=this.pendingRequests.get(i);if(o&&(o.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:n.confirmed_request_id,requesterOutboundTopicId:n.outbound_topic_id,uniqueRequestKey:i,originTopicId:n.outbound_topic_id||"",processed:!1,memo:n.m})}else this.connections.set(t,{connectionTopicId:t,targetAccountId:r,status:"established",isPending:!1,needsConfirmation:!1,created:n.created||new Date,connectionRequestId:e,confirmedRequestId:n.confirmed_request_id,requesterOutboundTopicId:n.outbound_topic_id,uniqueRequestKey:i,originTopicId:n.outbound_topic_id||"",processed:!1,memo:n.m})}const o=e.filter(e=>"connection_closed"===e.op||"close_connection"===e.op&&e.connection_topic_id);for(const n of o){const e=n.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=n.connection_request_id&&n.operator_id?`req-${n.connection_request_id}:${n.operator_id}`:void 0;this.connections.set(e,{...t,status:"closed",isPending:!1,needsConfirmation:!1,lastActivity:n.created||new Date,closedReason:n.reason,closeMethod:n.close_method,uniqueRequestKey:r,originTopicId:t.originTopicId,processed:!1,memo:n.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||"",o=this.baseClient.extractAccountFromOperatorId(t),n=this.baseClient.extractTopicFromOperatorId(t);if(this.shouldFilterAccount(o)){this.logger.debug(`Filtering out request from account: ${o}`);continue}const s=`inb-${e}:${t}`;r.some(t=>t.connection_id===e)?this.logger.debug(`Skipping request from ${o} as it has already been confirmed`):this.connections.has(s)||this.connections.set(s,{connectionTopicId:s,targetAccountId:o,targetInboundTopicId:n,status:"needs_confirmation",isPending:!1,needsConfirmation:!0,created:i.created||new Date,inboundRequestId:e,uniqueRequestKey:s,originTopicId:n,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||"",o=i.operator_id||"";if(this.shouldFilterAccount(r)){this.logger.debug(`Filtering out confirmation for account: ${r}`);continue}const n=`inb-${e}:${o}`;if(this.connections.has(n)&&this.connections.delete(n),this.connections.has(t)){const r=this.connections.get(t);this.connections.set(t,{...r,status:"established",isPending:!1,needsConfirmation:!1,inboundRequestId:e,uniqueRequestKey:n,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:n,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,o]of this.connections.entries())o.originTopicId===e&&o.inboundRequestId===t&&(this.connections.set(i,{...o,processed:!0}),r=!0,this.logger.debug(`Marked inbound connection request #${t} on topic ${e} as processed`)),o.originTopicId===e&&o.connectionRequestId===t&&(this.connections.set(i,{...o,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),o=[];for(const e of i)try{const t=await this.baseClient.mirrorNode.getScheduledTransactionStatus(e.schedule_id);t.executed||t.deleted||o.push(e)}catch(r){this.logger.error(`Error checking transaction status: ${r}`),o.push(e)}return o}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}`)}}},exports.ContentResolverRegistry=og,exports.ContentResolverRegistryImpl=ig,exports.ContentStoreService=sg,exports.CustomFeeType=tg,exports.DiscoveryError=jh,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=Uh,exports.DiscoveryState=qh,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 ec,this.logger=D.getInstance({module:"EVMBridge"})}async executeCommands(e,t={}){let r={...t};const o={};for(const s of e){const e=`${s.c.contractAddress}-${s.c.abi.name}`,t=await this.cache.get(e);if(t)o[s.c.abi.name]=JSON.parse(t),Object.assign(r,o[s.c.abi.name]);else try{const t=new c.ethers.Interface([{...s.c.abi}]),n=t.encodeFunctionData(s.c.abi.name),a=i.ContractId.fromSolidityAddress(s.c.contractAddress),l=await this.readFromMirrorNode(n,i.AccountId.fromString("0.0.800"),a);if(this.logger.info(`Result for ${s.c.contractAddress}:`,l?.result),!l?.result){this.logger.warn(`Failed to get result from mirror node for ${s.c.contractAddress}`),o[s.c.abi.name]="0",Object.assign(r,o[s.c.abi.name]);continue}const d=t?.decodeFunctionResult(s.c.abi.name,l.result);let u={values:[]};d&&s.c.abi.outputs?.forEach((e,t)=>{const r=tc(d[t],e.type);u.values.push(r),e.name&&(u[e.name]=r)}),await this.cache.set(e,JSON.stringify(u)),o[s.c.abi.name]=u,r[s.c.abi.name]=u}catch(n){this.logger.error(`Error executing command for ${s.c.contractAddress}:`,n),o[s.c.abi.name]="0",Object.assign(r,o[s.c.abi.name])}}return{results:o,stateData:r}}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(),o=t.toSolidityAddress(),n=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:o.startsWith("0x")?o:`0x${o}`,to:i?.startsWith("0x")?i:`0x${i}`,value:0})});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);return await n.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=yd,exports.FallbackCryptoAdapter=od,exports.FallbackHashAdapter=Yl,exports.FallbackHmacAdapter=td,exports.FeeConfigBuilder=rg,exports.FloraBuilder=class{constructor(){this.config={version:"1.0",type:3},this.logger=D.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}},exports.FloraError=Ih,exports.FloraOperation=wh,exports.FloraTopicType=bh,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[o,n]of Object.entries(r))n.type?(i.includes(n.type)||t.errors.push({code:"INVALID_ATTRIBUTE_TYPE",message:`Attribute '${o}' has invalid type '${n.type}'`,field:`attributes.${o}.type`,severity:"high"}),n.enum&&n.default&&!n.enum.includes(n.default)&&t.warnings.push({code:"DEFAULT_NOT_IN_ENUM",message:`Attribute '${o}' default value not in enum`,field:`attributes.${o}.default`,impact:"functionality"})):t.errors.push({code:"MISSING_ATTRIBUTE_TYPE",message:`Attribute '${o}' must specify a type`,field:`attributes.${o}.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=M,exports.HCS10BaseClient=Xd,exports.HCS10Cache=Zd,exports.HCS10Client=ou,exports.HCS11Client=Bd,exports.HCS11ProfileSchema=Dd,exports.HCS12BaseClient=_u,exports.HCS12BrowserClient=class extends _u{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 vu(this.network,this.logger,this.actionRegistryTopicId,this),this._blockLoader=new Cu(this.network,this.logger,this),this._assemblyRegistry=new xu(this.network,this.logger,this._assemblyRegistryTopicId,this),this._hashLinksRegistry=new Ru(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,r){const{accountId:o,signer:n}=await this.getAccountAndSigner(),s={[su.ACTION]:"hcs-12:1:60:0",[su.ASSEMBLY]:"hcs-12:1:60:2",[su.HASHLINKS]:"hcs-12:1:60:3"}[e];this.logger.info("Creating registry topic via wallet",{registryType:su[e],memo:s,accountId:o});const a=(new i.TopicCreateTransaction).setTopicMemo(s).setTransactionId(i.TransactionId.generate(o));if(t)if("boolean"==typeof t&&t){const e=await n.getAccountKey();a.setAdminKey(e),a.setAutoRenewAccountId(i.AccountId.fromString(o))}else(t instanceof i.PublicKey||t instanceof i.KeyList)&&(a.setAdminKey(t),a.setAutoRenewAccountId(i.AccountId.fromString(o)));if(r)if("boolean"==typeof r&&r){const e=await n.getAccountKey();a.setSubmitKey(e)}else(r instanceof i.PublicKey||r instanceof i.KeyList)&&a.setSubmitKey(r);const c=await a.freezeWithSigner(n),l=await c.executeWithSigner(n),d=await l.getReceiptWithSigner(n);if(!d.topicId)throw new Error("Failed to create topic: topicId is null");const u=d.topicId.toString();switch(this.logger.info("Registry topic created via wallet",{topicId:u,registryType:su[e]}),e){case su.ACTION:this.actionRegistryTopicId=u;break;case su.ASSEMBLY:this._assemblyRegistryTopicId=u;case su.HASHLINKS:}return u}async createAssemblyTopic(){this.logger.info("Creating new assembly topic");return await this.createRegistryTopic(su.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,r){const{accountId:o,signer:n}=await this.getAccountAndSigner();this.logger.debug("Submitting message to topic via wallet",{topicId:e,messageLength:t.length,accountId:o});const s=(new i.TopicMessageSubmitTransaction).setTopicId(i.TopicId.fromString(e)).setMessage(t).setTransactionId(i.TransactionId.generate(o));r&&this.logger.warn("Submit key parameter ignored in browser client - using wallet signer");const a=await s.freezeWithSigner(n),c=await a.executeWithSigner(n),l=await c.getReceiptWithSigner(n);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:o}=await this.getAccountAndSigner();this.logger.info("Inscribing file via HCS-1 (browser)",{fileName:t});const n=k.lookup(t)||"application/octet-stream",s=await us.createWithAuth({type:"client",accountId:i,signer:o,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 Oa({type:"buffer",buffer:e,fileName:t,mimeType:n},o,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 o of i)switch(o.op){case"add-block":await this.addBlockToAssembly(r,o);break;case"add-action":await this.addActionToAssembly(r,o);break;case"update":await this.updateAssembly(r,o)}return this.logger.info("Assembly created (browser)",{topicId:r,name:t.name,version:t.version,operations:i.length}),r}},exports.HCS12Client=class extends _u{constructor(e){super(e),this.operatorAccountId=e.operatorId,this.operatorCtx=oe({network:this.network,operatorId:this.operatorAccountId,operatorKey:e.operatorPrivateKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:"mainnet"===e.network?i.Client.forMainnet():i.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 vu(this.network,this.logger,this.actionRegistryTopicId,this),this._blockLoader=new Cu(this.network,this.logger,this),this._assemblyRegistry=new xu(this.network,this.logger,this._assemblyRegistryTopicId,this),this._hashLinksRegistry=new Ru(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={[su.ACTION]:"hcs-12:1:60:0",[su.ASSEMBLY]:"hcs-12:1:60:2",[su.HASHLINKS]:"hcs-12:1:60:3"}[e];this.logger.info("Creating registry topic",{registryType:su[e],memo:i});const o=Y({memo:i,adminKey:t,submitKey:r,operatorPublicKey:this.client.operatorPublicKey||void 0}),n=await o.execute(this.client),s=await n.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:su[e]}),e){case su.ACTION:this.actionRegistryTopicId=a;break;case su.ASSEMBLY:this._assemblyRegistryTopicId=a;case su.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=X({topicId:e,message:t});let o;if(r){const e=i.freezeWith(this.client),t=await e.sign(r);o=await t.execute(this.client)}else o=await i.execute(this.client);const n=await o.getReceipt(this.client);return this.logger.info("Message submitted successfully",{topicId:e,transactionId:o.transactionId.toString(),sequenceNumber:n.topicSequenceNumber?.toString()}),{transactionId:o.transactionId.toString(),sequenceNumber:n.topicSequenceNumber?Number(n.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=k.lookup(t)||"application/octet-stream",o=await us.createWithAuth({type:"server",accountId:this.operatorAccountId,privateKey:this.operatorCtx.operatorKey.toString(),network:this.network}),n={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 Fa({type:"buffer",buffer:e,fileName:t,mimeType:i},{accountId:this.operatorAccountId,privateKey:this.operatorCtx.operatorKey,network:this.network},n,o);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 o of i)switch(o.op){case"add-block":await this.addBlockToAssembly(r,o);break;case"add-action":await this.addActionToAssembly(r,o);break;case"update":await this.updateAssembly(r,o)}return this.logger.info("Assembly created",{topicId:r,name:t.name,version:t.version,operations:i.length}),r}},exports.HCS14Client=up,exports.HCS14_PROTOCOL_REGEX=Mu,exports.HCS15BaseClient=yh,exports.HCS15BrowserClient=class extends yh{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 DAppSigner");return this.signer}async createBaseAccount(e){const t=this.requireSigner(),r=i.PrivateKey.generateECDSA(),o=r.publicKey,n=mh({publicKey:o,initialBalance:new i.Hbar(e?.initialBalance??10),maxAutomaticTokenAssociations:e?.maxAutomaticTokenAssociations,accountMemo:e?.accountMemo}),s=await n.freezeWithSigner(t),a=await s.executeWithSigner(t),c=await a.getReceiptWithSigner(t),l=c?.accountId?.toString?.(),d=`0x${o.toEvmAddress()}`;return this.logger.info("Created HCS-15 base account (browser)",{accountId:l,evmAddress:d}),{accountId:l,privateKey:r,privateKeyHex:r.toStringRaw(),publicKey:o,evmAddress:d}}async createPetalAccount(e){const t=this.requireSigner(),r=fh({publicKey:("string"==typeof e.basePrivateKey?i.PrivateKey.fromStringECDSA(e.basePrivateKey):e.basePrivateKey).publicKey,initialBalance:new i.Hbar(e.initialBalance??1),maxAutomaticTokenAssociations:e.maxAutomaticTokenAssociations,accountMemo:e.accountMemo}),o=await r.freezeWithSigner(t),n=await o.executeWithSigner(t),s=await n.getReceiptWithSigner(t),a=s?.accountId?.toString?.();return this.logger.info("Created HCS-15 petal account (browser)",{accountId:a}),{accountId:a}}},exports.HCS15Client=class extends yh{constructor(e){super(e),this.operatorId=i.AccountId.fromString(e.operatorId),this.operatorCtx=oe({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:"mainnet"===this.network?i.Client.forMainnet():i.Client.forTestnet()}),this.client=this.operatorCtx.client}getKeyType(){return this.operatorCtx.keyType}async close(){try{this.client.close()}catch{}}async createBaseAccount(e){const t=i.PrivateKey.generateECDSA(),r=t.publicKey,o=mh({publicKey:r,initialBalance:new i.Hbar(e?.initialBalance??10),maxAutomaticTokenAssociations:e?.maxAutomaticTokenAssociations,accountMemo:e?.accountMemo}),n=await o.execute(this.client),s=await n.getReceipt(this.client);if(!s.accountId)throw new Error("HCS-15 BASE_ACCOUNT_CREATE_FAILED");const a=s.accountId.toString(),c=`0x${r.toEvmAddress()}`;return this.logger.info("Created HCS-15 base account",{accountId:a,evmAddress:c}),{accountId:a,privateKey:t,privateKeyHex:t.toStringRaw(),publicKey:r,evmAddress:c,receipt:s}}async createPetalAccount(e){const t=fh({publicKey:("string"==typeof e.basePrivateKey?i.PrivateKey.fromStringECDSA(e.basePrivateKey):e.basePrivateKey).publicKey,initialBalance:new i.Hbar(e.initialBalance??1),maxAutomaticTokenAssociations:e.maxAutomaticTokenAssociations,accountMemo:e.accountMemo}),r=await t.execute(this.client),o=await r.getReceipt(this.client);if(!o.accountId)throw new Error("HCS-15 PETAL_ACCOUNT_CREATE_FAILED");const n=o.accountId.toString();return this.logger.info("Created HCS-15 petal account",{accountId:n}),{accountId:n,receipt:o}}},exports.HCS16BaseClient=Nh,exports.HCS16BrowserClient=class extends Nh{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=Th({floraAccountId:e.floraAccountId,topicType:e.topicType,adminKey:e.adminKey,submitKey:e.submitKey,autoRenewAccountId:e.autoRenewAccountId}),i=await r.freezeWithSigner(t),o=await i.executeWithSigner(t),n=await o.getReceiptWithSigner(t);return n?.topicId?.toString?.()||""}async sendFloraCreated(e){const t=this.getSigner(),r=Eh(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendTransaction(e){const t=this.getSigner(),r=Ah(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async signSchedule(e){const t=this.getSigner(),r=await(new i.ScheduleSignTransaction).setScheduleId(e.scheduleId).freezeWithSigner(t);await r.executeWithSigner(t)}async sendStateUpdate(e){const t=this.getSigner(),r=vh(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),o=Sh({keyList:r,initialBalanceHbar:"number"==typeof e.initialBalanceHbar?e.initialBalanceHbar:5,maxAutomaticTokenAssociations:-1}),n=await o.freezeWithSigner(t),s=await n.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:d,state:u}=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 d.freezeWithSigner(t)).executeWithSigner(t)).getReceiptWithSigner(t),g=await(await(await u.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=Eh({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=Ch(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendFloraJoinVote(e){const t=this.getSigner(),r=xh(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendFloraJoinAccepted(e){const t=this.getSigner(),r=Rh(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}},exports.HCS16Client=class extends Nh{constructor(e){super({network:e.network,logger:e.logger}),this.operatorId=i.AccountId.fromString(e.operatorId);const t=new G(e.network,this.logger);this.operatorCtx=oe({network:e.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:t,logger:this.logger,client:"mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet()}),this.client=this.operatorCtx.client}async createFloraTopic(e){const t=Th({floraAccountId:e.floraAccountId,topicType:e.topicType,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:this.client.operatorPublicKey||void 0,autoRenewAccountId:e.autoRenewAccountId}),r=await t.execute(this.client),i=await r.getReceipt(this.client);if(!i.topicId)throw new Error("Failed to create Flora topic");return i.topicId.toString()}async sendFloraCreated(e){const t=Eh(e);return(await t.execute(this.client)).getReceipt(this.client)}async sendTransaction(e){const t=Ah(e);return(await t.execute(this.client)).getReceipt(this.client)}async signSchedule(e){const t=await(new i.ScheduleSignTransaction).setScheduleId(e.scheduleId).freezeWith(this.client),r=await t.sign(e.signerKey);return(await r.execute(this.client)).getReceipt(this.client)}async sendStateUpdate(e){const t=vh(e);return(await t.execute(this.client)).getReceipt(this.client)}async assembleKeyList(e){return super.assembleKeyList(e)}async createFloraAccountWithTopics(e){const t=await this.assembleKeyList({members:e.members,threshold:e.threshold}),r=await this.assembleSubmitKeyList(e.members),i=Sh({keyList:t,initialBalanceHbar:"number"==typeof e.initialBalanceHbar?e.initialBalanceHbar:5,maxAutomaticTokenAssociations:-1}),o=await i.execute(this.client),n=await o.getReceipt(this.client);if(!n.accountId)throw new Error("Failed to create Flora account");const s=n.accountId.toString(),{communication:a,transaction:c,state:l}=this.buildFloraTopicCreateTxs({floraAccountId:s,keyList:t,submitList:r,autoRenewAccountId:e.autoRenewAccountId}),d=await a.execute(this.client).then(e=>e.getReceipt(this.client)),u=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:d.topicId.toString(),transaction:u.topicId.toString(),state:p.topicId.toString()}}}async publishFloraCreated(e){const t=Eh({topicId:e.communicationTopicId,operatorId:e.operatorId,floraAccountId:e.floraAccountId,topics:e.topics});return(await t.execute(this.client)).getReceipt(this.client)}},exports.HCS17BaseClient=Dh,exports.HCS17BrowserClient=class extends Dh{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=Bh({ttl:e?.ttl??86400}),i=await r.freezeWithSigner(t),o=await i.executeWithSigner(t),n=await o.getReceiptWithSigner(t),s=n?.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 o=this.getSigner(),n=Mh({topicId:e,stateHash:t.state_hash,accountId:t.account_id,topics:t.topics,memo:t.m}),s=await n.freezeWithSigner(o),a=await s.executeWithSigner(o);return await a.getReceiptWithSigner(o),{}}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},o=this.calculateAccountStateHash(i),n=Mh({topicId:e.publishTopicId,stateHash:o.stateHash,accountId:e.accountId,topics:e.topics,memo:e.memo}),s=await n.freezeWithSigner(t);return await s.executeWithSigner(t),{stateHash:o.stateHash}}},exports.HCS17Client=class extends Dh{constructor(e){super(e),this.operatorId=i.AccountId.fromString(e.operatorId),this.operatorCtx=oe({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:"mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet()}),this.client=this.operatorCtx.client}getKeyType(){return this.operatorCtx.keyType}async createStateTopic(e){const t=Bh({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 o=i.topicId.toString();return this.logger.info(`Created HCS-17 state topic ${o}`),o}async submitMessage(e,t){const{valid:r,errors:i}=this.validateMessage(t);if(!r)throw new Error(`Invalid HCS-17 message: ${i.join(", ")}`);const o=Mh({topicId:e,stateHash:t.state_hash,accountId:t.account_id,topics:t.topics,memo:t.m}),n=await o.execute(this.client);return await n.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 o=Mh({topicId:e.publishTopicId,stateHash:i.stateHash,accountId:e.accountId,topics:e.topics,memo:e.memo}),n=await o.execute(this.client),s=await n.getReceipt(this.client);return{stateHash:i.stateHash,receipt:s}}},exports.HCS17TopicType=Fh,exports.HCS18BaseClient=eg,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=Jh(e.data);return this.submit(e.discoveryTopicId,t)}async propose(e){const t=Yh(e.data);return this.submit(e.discoveryTopicId,t)}async respond(e){const t=Xh(e.data);return this.submit(e.discoveryTopicId,t)}async complete(e){const t=Zh(e.data);return this.submit(e.discoveryTopicId,t)}async withdraw(e){const t=Qh(e.data);return this.submit(e.discoveryTopicId,t)}},exports.HCS18Client=class extends eg{constructor(e){super({network:e.network,logger:D.getInstance({level:e.logLevel||"info",module:"HCS-18",silent:e.silent})}),this.operatorCtx=oe({network:this.network,operatorId:e.operatorId,operatorKey:e.operatorKey,mirrorNode:this.mirrorNode,logger:this.logger,client:i.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=Vh({ttlSeconds:t,adminKey:e?.adminKey,submitKey:e?.submitKey,operatorPublicKey:r,memoOverride:e?.memoOverride}),o=await i.execute(this.client),n=await o.getReceipt(this.client),s=n.topicId?.toString();if(!s)throw new Error("Failed to create discovery topic");return{topicId:s,receipt:n}}async announce(e){await this.ensureInitialized();const t=Jh(e.data),r=Gh({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client),o=await i.getReceipt(this.client),n=o.topicSequenceNumber.toNumber();return{receipt:o,sequenceNumber:n}}async propose(e){await this.ensureInitialized();const t=Yh(e.data),r=Gh({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client),o=await i.getReceipt(this.client),n=o.topicSequenceNumber.toNumber();return{receipt:o,sequenceNumber:n}}async respond(e){await this.ensureInitialized();const t=Xh(e.data),r=Gh({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=Zh(e.data),r=Gh({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=Qh(e.data),r=Gh({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client);return await i.getReceipt(this.client)}},exports.HCS20BaseClient=Gp,exports.HCS20BurnMessageSchema=Bp,exports.HCS20Client=class extends Gp{constructor(e){super(e),this.operatorAccountId="string"==typeof e.operatorId?i.AccountId.fromString(e.operatorId):e.operatorId,this.operatorId=this.operatorAccountId.toString();const t="mainnet"===this.network?i.Client.forMainnet():i.Client.forTestnet();this.operatorCtx=oe({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 r;if(t){const i=e.freezeWith(this.client),o=await i.sign(t);r=await o.execute(this.client)}else r=await e.execute(this.client);const o=await r.getReceipt(this.client);if(!o||o.status!==i.Status.Success)throw new Error("Failed to submit message to topic");return{receipt:o,transactionId:r.transactionId.toString()}}async createPublicTopic(e){await this.ensureInitialized(),this.logger.info("Creating public HCS-20 topic...");const t=await(new i.TopicCreateTransaction).setTopicMemo(e||"HCS-20 Public Topic").execute(this.client),r=await t.getReceipt(this.client);if(r.status!==i.Status.Success||!r.topicId)throw new Error("Failed to create public topic");const o=r.topicId.toString();return this.logger.info(`Created public topic: ${o}`),this.publicTopicId=o,o}async createRegistryTopic(){await this.ensureInitialized(),this.logger.info("Creating HCS-20 registry topic...");const e=new xp({operatorId:this.operatorId,operatorKey:this.operatorCtx.operatorKey,network:this.network}),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 xp({operatorId:this.operatorId,operatorKey:this.operatorCtx.operatorKey,network:this.network});if(e.usePrivateTopic){const t=await i.createRegistry({submitKey:this.operatorCtx.operatorKey,adminKey:this.operatorCtx.operatorKey});if(!t.success)throw new $p("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 o={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},n=this.validateMessage(o);if(!n.valid)throw new jp("Invalid deploy message",n.errors);const s=Jp({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,o=Yp({topicId:i,tick:e.tick,amt:e.amount,to:this.accountToString(e.to),memo:e.memo}),{transactionId:n}=await this.submitPayload(o);t?.({stage:"confirming",percentage:80,mintTxId:n}),await this.waitForMirrorNodeConfirmation(i,n),t?.({stage:"complete",percentage:100,mintTxId:n});return{id:n,operation:"mint",tick:r,amount:e.amount,to:this.accountToString(e.to),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:n,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),o=this.accountToString(e.to);if(i!==this.operatorId)throw new Hp("For public topics, transaction payer must match sender",e.tick,i,o,e.amount);t?.({stage:"submitting",percentage:50});const n=e.topicId?this.topicToString(e.topicId):this.publicTopicId,s=Xp({topicId:n,tick:e.tick,amt:e.amount,from:i,to:o,memo:e.memo}),{transactionId:a}=await this.submitPayload(s);t?.({stage:"confirming",percentage:80,transferTxId:a}),await this.waitForMirrorNodeConfirmation(n,a),t?.({stage:"complete",percentage:100,transferTxId:a});return{id:a,operation:"transfer",tick:r,amount:e.amount,from:i,to:o,timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:n,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 qp("For public topics, transaction payer must match burner",e.tick,i,e.amount);t?.({stage:"submitting",percentage:50});const o=e.topicId?this.topicToString(e.topicId):this.publicTopicId,n=Zp({topicId:o,tick:e.tick,amt:e.amount,from:i,memo:e.memo}),{transactionId:s}=await this.submitPayload(n);t?.({stage:"confirming",percentage:80,burnTxId:s}),await this.waitForMirrorNodeConfirmation(o,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:o,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 jp("Invalid register message",i.errors);if(!this.registryTopicId)throw new $p("Registry topic not available",e.name);t?.({stage:"submitting",percentage:50});const o=Qp({registryTopicId:this.registryTopicId,name:e.name,topicId:this.topicToString(e.topicId),isPrivate:e.isPrivate,metadata:e.metadata,memo:e.memo}),{transactionId:n}=await this.submitPayload(o,this.operatorCtx.operatorKey);t?.({stage:"confirming",percentage:80,registerTxId:n}),await this.waitForMirrorNodeConfirmation(this.registryTopicId,n),t?.({stage:"complete",percentage:100,registerTxId:n}),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 o=0;o<r;o++){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 ${o+1} failed:`,i)}await B(2e3)}this.logger.warn(`Transaction ${t} not found on mirror node after ${r} attempts`)}},exports.HCS20DeployMessageSchema=zp,exports.HCS20Error=Lp,exports.HCS20MessageSchema=Kp,exports.HCS20MintMessageSchema=Dp,exports.HCS20PointsIndexer=class{constructor(e,t,r){this.isProcessing=!1,this.lastIndexedSequence=new Map,this.logger=t||new D({level:"info",module:"HCS20PointsIndexer"}),this.mirrorNode=new G(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 o=i.get(t);return o?.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||Np.PUBLIC_TOPIC_ID:null,o=r?e?.registryTopicId||Np.REGISTRY_TOPIC_ID:null,n=e?.pollInterval||3e4;await this.indexTopics(i,o,e?.privateTopics);const s=async()=>{if(this.isProcessing){try{await this.indexTopics(i,o,e?.privateTopics)}catch(t){this.logger.error("Polling error:",t)}this.isProcessing&&setTimeout(s,n)}};setTimeout(s,n)}async indexOnce(e){const t=!1!==e?.includePublicTopic,r=!1!==e?.includeRegistryTopic,i=t?e?.publicTopicId||Np.PUBLIC_TOPIC_ID:null,o=r?e?.registryTopicId||Np.REGISTRY_TOPIC_ID:null;await this.indexTopics(i,o,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 o of i)await this.indexTopic(o,!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 o=r||0;for(const n of i){if("hcs-20"!==n.p)continue;const r=Kp.safeParse(n);if(!r.success){this.logger.debug("Skipping message due to schema mismatch");continue}const i=r.data,s=n.sequence_number??0;this.logger.debug(`Found HCS-20 message: op=${i.op}, sequence=${s}`),s>o&&(o=s);const a={consensus_timestamp:n.consensus_timestamp??"",sequence_number:s,payer_account_id:n.payer_account_id??n.payer??"",transaction_id:n.transaction_id??""};this.processMessage(i,a,e,t),this.state.lastProcessedSequence++,this.state.lastProcessedTimestamp=n.consensus_timestamp||""}o>(r||0)&&this.lastIndexedSequence.set(e,o)}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 o=this.normalizeTick(e.tick);if(this.state.deployedPoints.has(o))return;const n={name:e.name,tick:o,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(o,n),this.logger.info(`Deployed points: ${o}`)}processMintMessage(e,t,r,i){const o=this.normalizeTick(e.tick),n=this.state.deployedPoints.get(o);if(!n)return;const s=BigInt(e.amt),a=BigInt(n.currentSupply);if(a+s>BigInt(n.maxSupply))return;if(n.limitPerMint&&s>BigInt(n.limitPerMint))return;n.currentSupply=(a+s).toString();let c=this.state.balances.get(o);c||(c=new Map,this.state.balances.set(o,c));const l=c.get(e.to),d=l?(BigInt(l.balance)+s).toString():e.amt;c.set(e.to,{tick:o,accountId:e.to,balance:d,lastUpdated:t.consensus_timestamp}),this.state.transactions.push({id:t.transaction_id||`${r}-${t.sequence_number}`,operation:"mint",tick:o,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 o=this.normalizeTick(e.tick),n=this.state.balances.get(o);if(!n)return;if(!i&&t.payer_account_id!==e.from)return;const s=n.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=n.get(e.to);c?(c.balance=(BigInt(c.balance)+a).toString(),c.lastUpdated=t.consensus_timestamp):n.set(e.to,{tick:o,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:o,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 o=this.normalizeTick(e.tick),n=this.state.deployedPoints.get(o),s=this.state.balances.get(o);if(!n||!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,n.currentSupply=(BigInt(n.currentSupply)-c).toString(),this.state.transactions.push({id:t.transaction_id||`${r}-${t.sequence_number}`,operation:"burn",tick:o,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=Up,exports.HCS20TransferMessageSchema=Mp,exports.HCS20_CONSTANTS=Np,exports.HCS21BaseClient=gh,exports.HCS21BrowserClient=class extends gh{constructor(e){super({network:e.network,logger:e.logger}),this.hwc=e.hwc}async publishDeclaration(e){const t="p"in e.declaration?this.validateDeclaration(e.declaration):this.buildDeclaration(e.declaration);await this.hwc.submitMessageToTopic(e.topicId,JSON.stringify(t))}async fetchDeclarations(e){const{messages:t=[]}=await this.hwc.getMessages(e),r=[];for(const o of t)try{const e=this.validateDeclaration(o.message);r.push({declaration:e,consensusTimestamp:o.consensus_timestamp,sequenceNumber:Number(o.sequence_number||0),payer:o.payer_account_id})}catch(i){const e=i instanceof Error?i.message:"unknown error";this.logger.warn(`Skipping invalid HCS-21 browser message: ${e}`)}return r}},exports.HCS21Client=class extends gh{constructor(e){const t=e.logger||new D({level:e.logLevel||"info",module:"HCS-21"});super({network:e.network,logger:t,mirrorNodeUrl:e.mirrorNodeUrl});const r="mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet();this.operatorCtx=oe({network:e.network,operatorId:e.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:r}),this.operatorCtx.ensureInitialized(),this.client=this.operatorCtx.client}async inscribeMetadata(e){await this.operatorCtx.ensureInitialized();const t=lh.parse(e.document),r=JSON.stringify(t,null,2),i=globalThis.Buffer.from(r,"utf8"),o={waitForConfirmation:!0,connectionMode:e.inscriptionOptions?.connectionMode??(!1===e.inscriptionOptions?.websocket?"http":"auto"),websocket:e.inscriptionOptions?.websocket??!1,...e.inscriptionOptions||{},metadata:{...e.inscriptionOptions?.metadata||{},...t}},n=await Fa({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},o);if(!n.confirmed||!n.inscription)throw new dh("Failed to inscribe HCS-21 metadata","invalid_payload");const s=n.inscription.jsonTopicId||n.inscription.topic_id||Ua(n.inscription);if(!s)throw new dh("Metadata inscription did not return a topic ID","invalid_payload");const a=n.inscription.sequence_number??n.inscription.sequenceNumber,c=await this.resolveManifestPointer(s,a),l=n.result&&"jobId"in n.result?{jobId:n.result.jobId,transactionId:n.result.transactionId}:{};return{pointer:c.pointer,topicId:s,sequenceNumber:c.sequenceNumber,...l}}async createRegistryTopic(e){await this.operatorCtx.ensureInitialized();const t=ph({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 r=await t.execute(this.client),o=await r.getReceipt(this.client);if(o.status!==i.Status.Success||!o.topicId)throw new dh("Failed to create HCS-21 registry topic","invalid_payload");return o.topicId.toString()}async publishDeclaration(e){await this.operatorCtx.ensureInitialized();const t=this.normalizeDeclarationInput(e.declaration),r=hh({topicId:e.topicId,declaration:t,transactionMemo:e.transactionMemo}),o=await r.execute(this.client),n=await o.getReceipt(this.client);if(n.status!==i.Status.Success)throw new dh("Failed to submit HCS-21 declaration","invalid_payload");return{sequenceNumber:n.topicSequenceNumber?.toNumber(),transactionId:o.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 dh("Unable to resolve manifest sequence number","invalid_payload");i=Number(t.sequence_number)}if(!Number.isFinite(i))throw new dh("Invalid manifest sequence number","invalid_payload");const o=`hcs://1/${e}/${i}`;if(!th.test(o))throw new dh("Manifest pointer format is invalid","invalid_payload");return{pointer:o,sequenceNumber:i}}},exports.HCS21ManifestPointerPattern=th,exports.HCS21TopicIdPattern=rh,exports.HCS21TopicType=ih,exports.HCS21ValidationError=dh,exports.HCS21_MAX_MESSAGE_BYTES=1024,exports.HCS21_PROTOCOL=eh,exports.HCS2BaseClient=Ap,exports.HCS2Client=xp,exports.HCS2Operation=fp,exports.HCS2RegistryType=yp,exports.HCS5BrowserClient=class extends gp{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=hp(e.metadataTopicId),r=mp({tokenId:e.tokenId,metadata:t});let o;if(e.supplyKey&&e.supplyKey instanceof i.PrivateKey){const t=this.getSigner();r.freezeWithSigner(t);const i=await r.sign(e.supplyKey);o=await this.hwc.executeTransactionWithErrorHandling(i,!0)}else o=await this.hwc.executeTransactionWithErrorHandling(r,!1);if(o.error)return{success:!1,error:o.error};const n=o.result;return{success:!0,serialNumber:n.serials?.[0]?Number(n.serials[0].toString()):void 0,transactionId:n?.transactionId?.toString?.(),metadata:t}}catch(ag){return{success:!1,error:String(ag)}}}async createHashinal(e){try{const t=this.getSigner(),r={...e.inscriptionOptions,mode:"hashinal",waitForConfirmation:!0,network:this.network},i=await Oa(e.inscriptionInput,t,r),o=i.inscription?.jsonTopicId||i.inscription?.topic_id;return i.confirmed&&o?await this.mint({tokenId:e.tokenId,metadataTopicId:o,supplyKey:e.supplyKey,memo:e.memo}):{success:!1,error:"Failed to inscribe content"}}catch(ag){return{success:!1,error:String(ag)}}}},exports.HCS5Client=class extends gp{constructor(e){super(e),this.operatorId=i.AccountId.fromString(e.operatorId),this.operatorCtx=oe({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,mirrorNode:this.mirrorNode,logger:this.logger}),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=hp(e.metadataTopicId),r=mp({tokenId:e.tokenId,metadata:t}),i=await r.freezeWith(this.client);if(e.supplyKey){const t=new ie({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 o=await i.execute(this.client),n=await o.getReceipt(this.client);return{success:!0,serialNumber:n.serials&&n.serials[0]?Number(n.serials[0].toString()):void 0,transactionId:o.transactionId?.toString?.(),metadata:t}}catch(ag){const t=ag;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 Fa(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(ag){const t=ag;return this.logger.error(`Failed to inscribe and mint HCS-5 Hashinal: ${t.message}`),{success:!1,error:t.message}}}},exports.HCS6BaseClient=J,exports.HCS6BrowserClient=class extends J{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),o=i.topicSequenceNumber;return{success:!0,receipt:i,sequenceNumber:"number"==typeof o?o:o?.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 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"}),n=t.limit?o.slice(0,t.limit):o;return this.logger.debug(`Retrieved ${o.length} messages, using ${n.length} after applying limit.`),this.parseRegistryEntries(e,n,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 Oa(r,this.signer,t),o=i.inscription?.jsonTopicId||Ua(i.inscription);if(!o)return{success:!1,error:"Failed to inscribe metadata"};let n=e.registryTopicId;if(!n){const t=await this.createRegistry({ttl:e.ttl});if(!t.success||!t.topicId)return{success:!1,error:t.error};n=t.topicId}const s=await this.registerEntry(n,{targetTopicId:o,memo:e.memo||"Initial dynamic hashinal registration"});return s.success?{success:!0,registryTopicId:n,inscriptionTopicId:o}:{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 Oa(t,this.signer,r),o=i.inscription?.jsonTopicId||Ua(i.inscription);if(!o)return{success:!1,error:"Failed to inscribe data"};let n=e.registryTopicId;if(!n){const t=await this.createRegistry({ttl:e.ttl});if(!t.success||!t.topicId)return{success:!1,error:t.error};n=t.topicId}const s=await this.registerEntry(n,{targetTopicId:o,memo:e.memo||"Dynamic hashinal registration"});return s.success?{success:!0,registryTopicId:n,inscriptionTopicId:o}:{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===K.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 J{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,mirrorNodeUrl:e.mirrorNodeUrl,logger:e.logger}),this.operatorId="string"==typeof e.operatorId?i.AccountId.fromString(e.operatorId):e.operatorId,this.operatorCtx=oe({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:this.createClient(e.network)}),this.client=this.operatorCtx.client}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}createClient(e){return"mainnet"===e?i.Client.forMainnet():i.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,r){const{valid:o,errors:n}=this.validateMessage(t);if(!o)throw new Error(`Invalid HCS-6 message: ${n.join(", ")}`);let s=(new i.TopicMessageSubmitTransaction).setTopicId(i.TopicId.fromString(e)).setMessage(JSON.stringify(t));if(!r){const e=await s.execute(this.client);return await e.getReceipt(this.client)}const a="string"==typeof r?i.PrivateKey.fromString(r):r,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),o=await this.submitMessageWithKey(e,i,r),n=o.topicSequenceNumber?.toNumber();return{success:!0,receipt:o,sequenceNumber:n}}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 r,o;if(e.submitKey)if("string"==typeof e.submitKey)try{r=i.PublicKey.fromString(e.submitKey)}catch{const t=globalThis.Buffer.from(e.submitKey.replace(/^0x/i,""),"hex");r="ed25519"===this.operatorCtx.keyType?i.PublicKey.fromBytesED25519(t):i.PublicKey.fromBytesECDSA(t)}else"boolean"==typeof e.submitKey?r=this.operatorCtx.operatorKey.publicKey:(r=e.submitKey.publicKey,o=e.submitKey);let n=Z({ttl:t,submitKey:r,adminKey:this.operatorCtx.operatorKey.publicKey,operatorPublicKey:this.operatorCtx.operatorKey.publicKey});const s=await n.freezeWith(this.client);o&&await s.sign(o);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]),o=parseInt(r[1]),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"})).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:o}:null}catch{return null}}).filter(e=>Boolean(e)),s=n.length>0?n[n.length-1]:void 0;return{topicId:e,registryType:o,ttl:i,entries:n,latestEntry:s}}async mint(e){try{if(await this.ensureInitialized(),!e.metadataTopicId)return{success:!1,error:"metadataTopicId is required for mint()"};const t=L(e.metadataTopicId);let r=(new i.TokenMintTransaction).setTokenId(i.TokenId.fromString(e.tokenId)).setMetadata([globalThis.Buffer.from(t)]);const o=await r.freezeWith(this.client);if(e.supplyKey){const t=new ie({mirrorNode:this.mirrorNode,logger:this.logger}),r="string"==typeof e.supplyKey?await t.resolveSupplyKey(e.tokenId,e.supplyKey,this.operatorCtx.keyType):e.supplyKey;await o.sign(r)}const n=await o.execute(this.client),s=await n.getReceipt(this.client);return{success:!0,serialNumber:s.serials&&s.serials[0]?Number(s.serials[0].toString()):void 0,transactionId:n.transactionId?.toString?.(),metadata:t}}catch(ag){return{success:!1,error:String(ag)}}}async inscribeAndMint(e){try{await this.ensureInitialized();const t={...e.inscriptionOptions,mode:"hashinal",waitForConfirmation:!0},r=await Fa(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(ag){return{success:!1,error:String(ag)}}}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)),o={...e.inscriptionOptions,mode:"hashinal",metadata:e.metadata,waitForConfirmation:!0},n=await Fa({type:"buffer",buffer:i,fileName:"metadata.json",mimeType:"application/json"},{accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},o);if(!n.confirmed||!n.inscription)throw new Error("Failed to inscribe metadata");const s=n.inscription.jsonTopicId||n.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(ag){return{success:!1,error:String(ag)}}}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 o={...e.inscriptionOptions,mode:"hashinal",metadata:e.metadata,waitForConfirmation:!0},n=await Fa(i,{accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},o);if(!n.confirmed||!n.inscription)throw new Error("Failed to inscribe data");const s=n.inscription.jsonTopicId||n.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(ag){return{success:!1,error:String(ag)}}}},exports.HCS6Operation=U,exports.HCS6RegistryType=K,exports.HCS7BaseClient=Ya,exports.HCS7BrowserClient=class extends Ya{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:Xa(i)}}catch(t){return this.logger.error("Failed to submit HCS-7 browser message",t),{success:!1,error:String(t)}}}},exports.HCS7Client=class extends Ya{constructor(e){super(e),this.closed=!1,this.operatorCtx=oe({network:this.network,operatorId:e.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger}),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 i.PublicKey.fromString(e)}catch{return}return e.publicKey}}coercePrivateKey(e){if(e instanceof i.PrivateKey)return e;try{return i.PrivateKey.fromStringED25519(e)}catch{return i.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=Za({ttl:t,submitKey:r,adminKey:this.resolvePublicKey(e.adminKey),operatorPublicKey:this.operatorCtx.operatorKey.publicKey});i=await i.freezeWith(this.client);const o=await i.execute(this.client),n=await o.getReceipt(this.client),s=n.topicId?.toString();return s?{success:!0,topicId:s,transactionId:o.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=Qa({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),o=await i.getReceipt(this.client);return{success:!0,receipt:o,sequenceNumber:o.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=La,exports.HCS7Operation=Ka,exports.HRLResolver=Vl,exports.HTSParser=pa,exports.HashLinkResolver=zu,exports.HashLinkScanner=Ou,exports.HashLinksRegistry=Ru,exports.Hcs10MemoType=Yd,exports.HederaHieroIssuer=dp,exports.HederaMirrorNode=G,exports.HieroDidResolver=rp,exports.InboundTopicType=Td,exports.InsufficientBalanceError=class extends Lp{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=Vp,exports.InvalidMessageFormatError=class extends Lp{constructor(e,t){super(e),this.messageData=t,this.name="InvalidMessageFormatError"}},exports.InvalidNumberFormatError=class extends Lp{constructor(e,t){super(`Invalid number format for ${t}: ${e}`),this.value=e,this.field=t,this.name="InvalidNumberFormatError"}},exports.InvalidTickFormatError=class extends Lp{constructor(e){super(`Invalid tick format: ${e}`),this.tick=e,this.name="InvalidTickFormatError"}},exports.IssuerRegistry=sp,exports.KeyType=Q,exports.KeyTypeDetector=te,exports.Logger=D,exports.MAINNET_EXAMPLES=Bu,exports.MCPServerBuilder=class{constructor(){this.config={mcpServer:{}},this.socials=[],this.logger=D.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:Id.DNS,value:e,dns_field:t};return this.config.mcpServer.verification=r,this}addVerificationSignature(e){this.config.mcpServer||(this.config.mcpServer={});const t={type:Id.SIGNATURE,value:e};return this.config.mcpServer.verification=t,this}addVerificationChallenge(e){this.config.mcpServer||(this.config.mcpServer={});const t={type:Id.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}},exports.MCPServerCapability=wd,exports.MCPServerConnectionInfoSchema=Ad,exports.MCPServerDetailsSchema=Nd,exports.MCPServerHostSchema=Cd,exports.MCPServerProfileSchema=Od,exports.MCPServerResourceSchema=xd,exports.MCPServerToolSchema=Rd,exports.MCPServerVerificationSchema=vd,exports.MapCache=ec,exports.MintLimitExceededError=class extends Lp{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=rd,exports.NodeHashAdapter=Gl,exports.NodeHmacAdapter=Ql,exports.PayloadSizeError=Qd,exports.PersonBuilder=class{constructor(){this.config={version:"1.0",type:0},this.logger=D.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}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,properties:this.config.properties,inboundTopicId:this.config.inboundTopicId,outboundTopicId:this.config.outboundTopicId,pfpBuffer:this.config.pfpBuffer,pfpFileName:this.config.pfpFileName}}},exports.PersonalProfileSchema=Pd,exports.PointsBurnError=qp,exports.PointsDeploymentError=$p,exports.PointsMintError=class extends Lp{constructor(e,t,r,i){super(e),this.tick=t,this.requestedAmount=r,this.availableSupply=i,this.name="PointsMintError"}},exports.PointsNotFoundError=class extends Lp{constructor(e){super(`Points with tick "${e}" not found`),this.tick=e,this.name="PointsNotFoundError"}},exports.PointsTransferError=Hp,exports.PointsValidationError=jp,exports.ProfileType=md,exports.ProgressReporter=ps,exports.REFERENCE_THRESHOLD=51200,exports.RedisCache=class{constructor(e={}){const{host:t="localhost",port:r=6379,password:i,db:o=0,keyPrefix:n="",tls:s=!1,connectTimeout:a=5e3,retryStrategy:c,logLevel:l="info"}=e;this.prefix=n,this.logger=D.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:o,tls:s?{}:void 0,keyPrefix:n,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=Md,exports.RegistryBrokerClient=ql,exports.RegistryBrokerError=$l,exports.RegistryBrokerParseError=Hl,exports.RegistryType=su,exports.ResolverRegistry=ip,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 M,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),o=new Blob([i.buffer],{type:t.contentType});return this.logger.debug("Image resource loaded successfully",{topicId:e,size:r.length,type:t.contentType}),o}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(Zl())return this.logger.warn("Integrity verification skipped in SSR environment"),!0;if("undefined"==typeof crypto||!crypto.subtle)return this.logger.warn("WebCrypto not available, skipping integrity verification"),!0;const r="string"==typeof e?(new TextEncoder).encode(e):e,i=r instanceof Uint8Array?r:new Uint8Array(r),o=new Uint8Array(i),n=await crypto.subtle.digest("SHA-256",o.buffer),s=Array.from(new Uint8Array(n));return s.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 o;o=i.startsWith("text/")||i.includes("javascript")||i.includes("json")?await r.text():new Uint8Array(await r.arrayBuffer());const n={content:o,contentType:i,size:r.size};return this.addToCache(e,n),n}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 n of e)t.set(n.topicId,n.depends||[]);const r=new Set,i=new Set,o=e=>{if(i.has(e))throw new Error("Circular dependency detected");if(r.has(e))return;i.add(e);const n=t.get(e)||[];for(const t of n)o(t);i.delete(e),r.add(e)};for(const n of e)o(n.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=[],o=new Set,n=e=>{if(o.has(e))return;const s=r.get(e)||[];for(const t of s)n(t);o.add(e);const a=t.get(e);a&&i.push(a)};for(const s of e)n(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=["twitter","github","discord","telegram","linkedin","youtube","website","x"],exports.ScheduleParser=ba,exports.SocialLinkSchema=kd,exports.StateHashError=Ph,exports.SupplyLimitExceededError=class extends Lp{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=Du,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 o=i.render(this.sanitizeContext(t));return this.logger.debug("Template rendered successfully",{resultLength:o.length}),o}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,o,n,s,a)=>{if(!this.evaluateCondition(r,t))return"";return i+(this.evaluateCondition(o,t)?n:s)+a});r=r.replace(/\{\{#if\s+([^}]+)\}\}((?:[^{]|\{(?!\{)|\{\{(?!else|\/if))*?)\{\{else\}\}((?:[^{]|\{(?!\{)|\{\{(?!\/if))*?)\{\{\/if\}\}/gs,(e,r,i,o)=>this.evaluateCondition(r,t)?i:o);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 o=this.getNestedValue(r,t);if(!o)return"";let n="";if(Array.isArray(o))o.forEach((e,r)=>{let o=i;if(o=o.replace(/\{\{this\}\}/g,this.escapeHtml(String(e))),o=o.replace(/\{\{@index\}\}/g,String(r)),"object"==typeof e&&null!==e)for(const[t,i]of Object.entries(e)){const e=new RegExp(`\\{\\{${t}\\}\\}`,"g");o=o.replace(e,this.escapeHtml(String(i)))}o=o.replace(/\{\{\.\.\/([^}]+)\}\}/g,(e,r)=>{const i=this.getNestedValue(r,t);return this.escapeHtml(String(i||""))}),n+=o});else if("object"==typeof o)for(const[t,s]of Object.entries(o)){let e=i;e=e.replace(/\{\{@key\}\}/g,this.escapeHtml(t)),e=e.replace(/\{\{this\}\}/g,this.escapeHtml(String(s))),n+=e}return n}),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 o=this.getNestedValue(i,t);return 0===o||!1===o?this.escapeHtml(String(o)):this.escapeHtml(String(o||""))}),r}processHelpers(e,t){let r=e;r=r.replace(/\{\{#with\s+([^}]+)\}\}(.*?)\{\{\/with\}\}/gs,(e,r,i)=>{const o=this.getNestedValue(r.trim(),t);return o?this.executeTemplate(i,o):""});for(const[i,o]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(o.call(t,e))}catch(n){return this.logger.warn("Helper execution failed",{helperName:i,error:n}),""}})}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 o of r){if(null==i||"object"!=typeof i)return;i=i[o]}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,o]of Object.entries(e))i[t]=r(o);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=tu,exports.TopicRegistrationError=Wp,exports.TransactionParser=Aa,exports.TransactionParsingError=hs,exports.VerificationType=Id,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=D.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,o=t(i,1);const n=this.getUint8Memory();let s=0;for(;s<i;s++){const t=e.charCodeAt(s);if(t>127)break;n[o+s]=t}if(s!==i){0!==s&&(e=e.slice(s)),o=r(o,i,i=s+3*this.textEncoder.encode(e).length,1);const t=this.getUint8Memory().subarray(o+s,o+i);s+=this.encodeString(e,t).written}return this.WASM_VECTOR_LEN=s,o}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 o=[r,...t.map(e=>[this.passStringToWasm(e,this.wasm.__wbindgen_malloc,this.wasm.__wbindgen_realloc),this.WASM_VECTOR_LEN]).flat()];e.apply(this.wasm,o);const n=this.getDataViewMemory().getInt32(r+0,!0),s=this.getDataViewMemory().getInt32(r+4,!0);return i=[n,s],this.getStringFromWasm(n,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 o=t[e];o&&"object"==typeof o&&"values"in o&&o.values.length>0?r[e]=String(o.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=Fu,exports.WasmValidator=class{constructor(e){this.cryptoAdapter=nd(),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 o=this.getWasmVersion(e);if(i.version=o,1!==o)return t.push(`Unsupported WASM version: ${o}`),i.isValid=!1,i;const n=await this.parseModule(e);i.exports=n.exports;for(const e of this.REQUIRED_EXPORTS)n.exports.includes(e)||(t.push(`Missing required export: ${e}`),i.isValid=!1);i.imports=n.imports;for(const e of n.imports){const r=`${e.module}.${e.name}`;this.ALLOWED_IMPORTS.has(r)||(t.push(`Disallowed import: ${r}`),i.isValid=!1)}n.memory&&(i.memoryRequirements=n.memory,n.memory.initial>this.MAX_INITIAL_MEMORY&&(t.push(`Excessive initial memory: ${n.memory.initial} pages`),i.isValid=!1)),n.hasStartFunction&&r.push("Module has start function - may execute code on load"),n.functionCount>100&&r.push(`High function count: ${n.functionCount}`),this.hasSuspiciousPatterns(e)&&r.push("Potentially unsafe operation detected"),i.exportSignatures=n.exportSignatures}catch(o){this.logger.error("WASM validation failed",{error:o}),t.push(`Validation error: ${o instanceof Error?o.message:"Unknown error"}`),i.isValid=!1}return i}async validateInfoFunction(e){const t=[],r=[];try{const i=await e(),o=JSON.parse(i);return o.name&&o.version&&o.hashlinks_version?{isValid:!0,errors:t,warnings:r,moduleInfo:o}:(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(Zl())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 o=[],n=r.split("import:");for(let u=1;u<n.length;u++){const e=n[u].match(/^([a-zA-Z_]+[a-zA-Z0-9_]*)\.([a-zA-Z_]+[a-zA-Z0-9_]*)/);e&&o.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 d=r.match(/functions:(\d+)/);d&&(l=parseInt(d[1]));return{exports:i,imports:o,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=id,exports.WebHashAdapter=Jl,exports.WebHmacAdapter=ed,exports.accountIdsToExemptKeys=oc,exports.actionRegistrationSchema=gu,exports.adapterDeclarationSchema=sh,exports.adapterManifestSchema=ah,exports.adapterPackageSchema=oh,exports.assemblyMessageSchema=Iu,exports.assemblyRegistrationSchema=Tu,exports.baseMessageSchema=wp,exports.blockRegistrationSchema=mu,exports.buildHcs10ConfirmConnectionTx=jd,exports.buildHcs10CreateConnectionTopicTx=$d,exports.buildHcs10CreateInboundTopicTx=Kd,exports.buildHcs10CreateOutboundTopicTx=Ld,exports.buildHcs10CreateRegistryTopicTx=Hd,exports.buildHcs10OutboundConnectionCreatedRecordTx=Vd,exports.buildHcs10OutboundConnectionRequestRecordTx=Wd,exports.buildHcs10RegistryDeleteTx=function(e){const t={p:"hcs-10",op:"delete",uid:e.uid,m:e.memo};return X({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:Ud(1,0)})},exports.buildHcs10RegistryMigrateTx=function(e){const t={p:"hcs-10",op:"migrate",t_id:e.targetTopicId,m:e.memo};return X({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:Ud(2,0)})},exports.buildHcs10RegistryRegisterTx=Jd,exports.buildHcs10SendMessageTx=Gd,exports.buildHcs10SubmitConnectionRequestTx=qd,exports.buildHcs12AddActionToAssemblyTx=function(e){return X({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs12AddBlockToAssemblyTx=function(e){return X({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs12CreateRegistryTopicTx=function(e){var t;return Y({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 X({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 X({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs12UpdateAssemblyTx=function(e){return X({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs15BaseAccountCreateTx=mh,exports.buildHcs15PetalAccountCreateTx=fh,exports.buildHcs16CreateAccountTx=Sh,exports.buildHcs16CreateFloraTopicTx=Th,exports.buildHcs16CreateTransactionTopicTx=function(e){const t=(new i.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 r=e.customFees.map(e=>{const t=(new i.CustomFixedFee).setAmount(e.amount).setFeeCollectorAccountId(i.AccountId.fromString(e.feeCollectorAccountId));return e.denominatingTokenId&&t.setDenominatingTokenId(i.TokenId.fromString(e.denominatingTokenId)),t});t.setCustomFees(r)}if(e.feeExemptKeys&&e.feeExemptKeys.length>0)throw new Error("feeExemptKeys not supported by installed @hashgraph/sdk");return t},exports.buildHcs16FloraCreatedTx=Eh,exports.buildHcs16FloraJoinAcceptedTx=Rh,exports.buildHcs16FloraJoinRequestTx=Ch,exports.buildHcs16FloraJoinVoteTx=xh,exports.buildHcs16MessageTx=kh,exports.buildHcs16ScheduleAccountKeyUpdateTx=function(e){const t=(new i.AccountUpdateTransaction).setAccountId(i.AccountId.fromString(e.floraAccountId)).setKey(e.newKeyList);return e.memo&&t.setTransactionMemo(e.memo),(new i.ScheduleCreateTransaction).setScheduledTransaction(t)},exports.buildHcs16ScheduleTopicKeyUpdateTx=function(e){const t=(new i.TopicUpdateTransaction).setTopicId(e.topicId);return e.adminKey&&t.setAdminKey(e.adminKey),e.submitKey&&t.setSubmitKey(e.submitKey),e.memo&&t.setTransactionMemo(e.memo),(new i.ScheduleCreateTransaction).setScheduledTransaction(t)},exports.buildHcs16StateUpdateTx=vh,exports.buildHcs16TransactionTx=Ah,exports.buildHcs17CreateTopicTx=Bh,exports.buildHcs17MessageTx=Mh,exports.buildHcs18AnnounceMessage=Jh,exports.buildHcs18CompleteMessage=Zh,exports.buildHcs18CreateDiscoveryTopicTx=Vh,exports.buildHcs18DiscoveryMemo=Wh,exports.buildHcs18ProposeMessage=Yh,exports.buildHcs18RespondMessage=Xh,exports.buildHcs18SubmitDiscoveryMessageTx=Gh,exports.buildHcs18WithdrawMessage=Qh,exports.buildHcs1Hrl=hp,exports.buildHcs20BurnTx=Zp,exports.buildHcs20DeployTx=Jp,exports.buildHcs20MintTx=Yp,exports.buildHcs20RegisterTx=Qp,exports.buildHcs20SubmitMessageTx=function(e){const t="string"==typeof e.payload?e.payload:JSON.stringify(e.payload);return X({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs20TransferTx=Xp,exports.buildHcs21CreateRegistryTx=ph,exports.buildHcs21MessageTx=hh,exports.buildHcs21RegistryMemo=uh,exports.buildHcs2CreateRegistryTx=vp,exports.buildHcs2DeleteTx=function(e){const t={p:"hcs-2",op:fp.DELETE,uid:e.uid,m:e.memo};return X({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs2MigrateTx=function(e){const t={p:"hcs-2",op:fp.MIGRATE,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return X({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs2RegisterTx=function(e){const t={p:"hcs-2",op:fp.REGISTER,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return X({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs2UpdateTx=function(e){const t={p:"hcs-2",op:fp.UPDATE,uid:e.uid,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return X({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs5MintTx=mp,exports.buildHcs5MintWithHrlTx=function(e){const t=hp(e.metadataTopicId);return mp({tokenId:e.tokenId,metadata:t,transactionMemo:e.transactionMemo})},exports.buildHcs6CreateRegistryTx=Z,exports.buildHcs6Hrl=L,exports.buildHcs6RegisterEntryTx=function(e){const t={p:"hcs-6",op:U.REGISTER,t_id:e.targetTopicId,m:e.memo};return X({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs7CreateRegistryTx=Za,exports.buildHcs7EvmMessageTx=function(e){const t={p:"hcs-7",op:Ka.REGISTER_CONFIG,t:La.EVM,c:{contractAddress:e.config.contractAddress,abi:e.config.abi},m:e.config.memo??""};return Qa({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs7SubmitMessageTx=Qa,exports.buildHcs7WasmMessageTx=function(e){const t={p:"hcs-7",op:Ka.REGISTER_CONFIG,t:La.WASM,c:{wasmTopicId:e.config.wasmTopicId,inputType:e.config.inputType,outputType:e.config.outputType},m:e.config.memo??""};return Qa({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.canonicalizeAgentData=$u,exports.canonicalizeLedgerNetwork=dc,exports.capabilityNameToCapabilityMap=Sd,exports.createLoggerAdapter=rc,exports.createPrivateKeySigner=Ol,exports.createUaid=Gu,exports.defaultIssuerRegistry=ap,exports.defaultResolverRegistry=op,exports.deleteMessageSchema=Sp,exports.detectCryptoEnvironment=Xl,exports.detectKeyTypeFromString=re,exports.ensureLoggerType=function(e){return ic(e)?e:rc(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.floraContextSchema=nh,exports.generateHCS17Memo=Oh,exports.generateHCS6RegistryMemo=V,exports.generateQuote=Ba,exports.getCryptoAdapter=nd,exports.getExampleTopics=function(e){return"mainnet"===e?Bu:Du},exports.getHumanReadableTransactionType=Ea,exports.getOrCreateSDK=Ra,exports.getParserConfig=function(e){return wa[e]},exports.getSchedulableTransactionType=function(e){for(const[t,r]of Object.entries(Sa))if(e[t])return r;return"unknown"},exports.getSupportedTransactionTypes=function(){return Object.keys(wa)},exports.getTopicId=Ua,exports.getTransactionTypeFromBody=ka,exports.hash=async function(e,t="sha256"){const r=nd().createHash(t),i="string"==typeof e?globalThis.Buffer.from(e):e,o=r.update(i).digest("hex");return o instanceof Promise?await o:o},exports.hashLinksRegistrationSchema=Su,exports.hcs17MessageSchema=_h,exports.hcs2MessageSchema=Ep,exports.hcs6BaseMessageSchema=H,exports.hcs6MessageSchema=j,exports.hcs6RegisterMessageSchema=q,exports.hcs6TopicIdSchema=$,exports.hcs7MessageSchema=Ja,exports.humanReadableTypeRegistry=Ta,exports.inscribe=Fa,exports.inscribeWithSigner=Oa,exports.isAnnounceMessage=function(e){if(!Hh(e))return!1;const t=e;if("announce"!==t.op)return!1;if(!Kh(t.data))return!1;const r=t.data;if(!Lh(r.account))return!1;if(!Kh(r.petal))return!1;const i=r.petal;return!(!Lh(i.name)||!$h(i.priority))&&(!!Kh(r.capabilities)&&(!!function(e){return Array.isArray(e)&&e.every(Lh)}(r.capabilities.protocols)&&!("valid_for"in r&&void 0!==r.valid_for&&null!==r.valid_for&&!$h(r.valid_for))))},exports.isBrowser=va,exports.isCompleteMessage=function(e){if(!Hh(e))return!1;const t=e;if("complete"!==t.op)return!1;if(!Kh(t.data))return!1;const r=t.data;if(!Lh(r.proposer))return!1;if(!$h(r.proposal_seq))return!1;if(!Lh(r.flora_account))return!1;if(!Kh(r.topics))return!1;const i=r.topics;return!!(Lh(i.communication)&&Lh(i.transaction)&&Lh(i.state))},exports.isConcreteLogger=ic,exports.isCryptoAvailable=function(){return"none"!==Xl().preferredAPI},exports.isDiscoveryMessage=Hh,exports.isEip155Caip10=hd,exports.isHederaCaip10=ld,exports.isHederaNetwork=ad,exports.isPartialRegisterAgentResponse=e=>"partial"===e.status&&!1===e.success,exports.isPendingRegisterAgentResponse=e=>"pending"===e.status,exports.isProposeMessage=function(e){if(!Hh(e))return!1;const t=e;if("propose"!==t.op)return!1;if(!Kh(t.data))return!1;const r=t.data;if(!Lh(r.proposer))return!1;if(!function(e){return Array.isArray(e)}(r.members))return!1;if(!r.members.every(e=>{if(!Kh(e))return!1;const t=e;return!!Lh(t.account)&&(!(!("priority"in t)||!$h(t.priority))&&!("announce_seq"in t&&void 0!==t.announce_seq&&null!==t.announce_seq&&!$h(t.announce_seq)))}))return!1;if(!Kh(r.config))return!1;const i=r.config;return!(!Lh(i.name)||!$h(i.threshold))},exports.isRespondMessage=function(e){if(!Hh(e))return!1;const t=e;if("respond"!==t.op)return!1;if(!Kh(t.data))return!1;const r=t.data;return!!Lh(r.responder)&&(!!$h(r.proposal_seq)&&(!!Lh(r.decision)&&!!["accept","reject"].includes(r.decision)))},exports.isSSREnvironment=Zl,exports.isSuccessRegisterAgentResponse=e=>!0===e.success&&"pending"!==e.status,exports.isTransactionTypeSupported=function(e){return e in wa},exports.isWithdrawMessage=function(e){if(!Hh(e))return!1;const t=e;if("withdraw"!==t.op)return!1;if(!Kh(t.data))return!1;const r=t.data;return!!Lh(r.account)&&(!!$h(r.announce_seq)&&!("reason"in r&&void 0!==r.reason&&null!==r.reason&&!Lh(r.reason)))},exports.mcpServiceNameToCapabilityMap={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},exports.metadataDocumentSchema=lh,exports.migrateMessageSchema=kp,exports.parseHCS17Memo=zh,exports.parseHcs14Did=Ju,exports.parseHederaCaip10=ud,exports.protoFieldToTypeRegistry=Ia,exports.registerDefaultResolvers=np,exports.registerMessageSchema=Ip,exports.registryMetadataSchema=ch,exports.resolveTransactionSummary=ca,exports.retrieveInscription=za,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=Sa,exports.setLoggerFactory=function(e){z=e,D.clearInstances()},exports.shouldUseReference=function(e){return("string"==typeof e?globalThis.Buffer.byteLength(e,"utf8"):e.length)>51200},exports.sleep=B,exports.toEip155Caip10=gd,exports.toHederaCaip10=dd,exports.topicIdSchema=bp,exports.transactionParserRegistry=wa,exports.transactionSummaryRegistry=aa,exports.updateMessageSchema=Tp,exports.validateActionRegistration=ku,exports.validateAssemblyMessage=Eu,exports.validateAssemblyRegistration=function(e){return Tu.parse(e)},exports.validateBlockRegistration=function(e){return mu.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&&W(i)},exports.validateHCS6TTL=W,exports.validateHashLinksRegistration=function(e){return Su.parse(e)},exports.validateWithSchema=Au,exports.waitForInscriptionConfirmation=Ma;
|
|
10
|
+
!function(e){const t=le,r=be,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 o=2147483647;e.kMaxLength=o;const{Uint8Array:n,ArrayBuffer:s,SharedArrayBuffer:a}=globalThis;function c(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new n(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 d(e,t,r)}function d(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 o=i.write(e,t);o!==r&&(i=i.slice(0,o));return i}(e,t);if(s.isView(e))return function(e){if(Y(e,n)){const t=new n(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(Y(e,s)||e&&Y(e.buffer,s))return g(e,t,r);if(void 0!==a&&(Y(e,a)||e&&Y(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 o=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||X(e.length)?c(0):h(e);if("Buffer"===e.type&&Array.isArray(e.data))return h(e.data)}(e);if(o)return o;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 u(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 u(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 n(e):void 0===r?new n(e,t):new n(e,t,r),Object.setPrototypeOf(i,l.prototype),i}function m(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function f(e,t){if(l.isBuffer(e))return e.length;if(s.isView(e)||Y(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 o=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return r;case"utf8":case"utf-8":return V(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*r;case"hex":return r>>>1;case"base64":return G(e).length;default:if(o)return i?-1:V(e).length;t=(""+t).toLowerCase(),o=!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 _(this,t,r);case"utf8":case"utf-8":return C(this,t,r);case"ascii":return R(this,t,r);case"latin1":case"binary":return N(this,t,r);case"base64":return v(this,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return P(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,o){if(0===e.length)return-1;if("string"==typeof r?(i=r,r=0):r>2147483647?r=2147483647:r<-2147483648&&(r=-2147483648),X(r=+r)&&(r=o?0:e.length-1),r<0&&(r=e.length+r),r>=e.length){if(o)return-1;r=e.length-1}else if(r<0){if(!o)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,o);if("number"==typeof t)return t&=255,"function"==typeof n.prototype.indexOf?o?n.prototype.indexOf.call(e,t,r):n.prototype.lastIndexOf.call(e,t,r):I(e,[t],r,i,o);throw new TypeError("val must be string, number or Buffer")}function I(e,t,r,i,o){let n,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(o){let i=-1;for(n=r;n<a;n++)if(l(e,n)===l(t,-1===i?0:n-i)){if(-1===i&&(i=n),n-i+1===c)return i*s}else-1!==i&&(n-=n-i),i=-1}else for(r+c>a&&(r=a-c),n=r;n>=0;n--){let r=!0;for(let i=0;i<c;i++)if(l(e,n+i)!==l(t,i)){r=!1;break}if(r)return n}return-1}function T(e,t,r,i){r=Number(r)||0;const o=e.length-r;i?(i=Number(i))>o&&(i=o):i=o;const n=t.length;let s;for(i>n/2&&(i=n/2),s=0;s<i;++s){const i=parseInt(t.substr(2*s,2),16);if(X(i))return s;e[r+s]=i}return s}function S(e,t,r,i){return J(V(t,e.length-r),e,r,i)}function k(e,t,r,i){return J(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 E(e,t,r,i){return J(G(t),e,r,i)}function A(e,t,r,i){return J(function(e,t){let r,i,o;const n=[];for(let s=0;s<e.length&&!((t-=2)<0);++s)r=e.charCodeAt(s),i=r>>8,o=r%256,n.push(o),n.push(i);return n}(t,e.length-r),e,r,i)}function v(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 o=t;for(;o<r;){const t=e[o];let n=null,s=t>239?4:t>223?3:t>191?2:1;if(o+s<=r){let r,i,a,c;switch(s){case 1:t<128&&(n=t);break;case 2:r=e[o+1],128==(192&r)&&(c=(31&t)<<6|63&r,c>127&&(n=c));break;case 3:r=e[o+1],i=e[o+2],128==(192&r)&&128==(192&i)&&(c=(15&t)<<12|(63&r)<<6|63&i,c>2047&&(c<55296||c>57343)&&(n=c));break;case 4:r=e[o+1],i=e[o+2],a=e[o+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&&(n=c))}}null===n?(n=65533,s=1):n>65535&&(n-=65536,i.push(n>>>10&1023|55296),n=56320|1023&n),i.push(n),o+=s}return function(e){const t=e.length;if(t<=x)return String.fromCharCode.apply(String,e);let r="",i=0;for(;i<t;)r+=String.fromCharCode.apply(String,e.slice(i,i+=x));return r}(i)}l.TYPED_ARRAY_SUPPORT=function(){try{const e=new n(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,n.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 d(e,t,r)},Object.setPrototypeOf(l.prototype,n.prototype),Object.setPrototypeOf(l,n),l.alloc=function(e,t,r){return function(e,t,r){return u(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(Y(e,n)&&(e=l.from(e,e.offset,e.byteLength)),Y(t,n)&&(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 o=0,n=Math.min(r,i);o<n;++o)if(e[o]!==t[o]){r=e[o],i=t[o];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 o=0;for(r=0;r<e.length;++r){let t=e[r];if(Y(t,n))o+t.length>i.length?(l.isBuffer(t)||(t=l.from(t)),t.copy(i,o)):n.prototype.set.call(i,t,o);else{if(!l.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(i,o)}o+=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,o){if(Y(e,n)&&(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===o&&(o=this.length),t<0||r>e.length||i<0||o>this.length)throw new RangeError("out of range index");if(i>=o&&t>=r)return 0;if(i>=o)return-1;if(t>=r)return 1;if(this===e)return 0;let s=(o>>>=0)-(i>>>=0),a=(r>>>=0)-(t>>>=0);const c=Math.min(s,a),d=this.slice(i,o),u=e.slice(t,r);for(let n=0;n<c;++n)if(d[n]!==u[n]){s=d[n],a=u[n];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 o=this.length-t;if((void 0===r||r>o)&&(r=o),e.length>0&&(r<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");i||(i="utf8");let n=!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 E(this,e,t,r);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return A(this,e,t,r);default:if(n)throw new TypeError("Unknown encoding: "+i);i=(""+i).toLowerCase(),n=!0}},l.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const x=4096;function R(e,t,r){let i="";r=Math.min(e.length,r);for(let o=t;o<r;++o)i+=String.fromCharCode(127&e[o]);return i}function N(e,t,r){let i="";r=Math.min(e.length,r);for(let o=t;o<r;++o)i+=String.fromCharCode(e[o]);return i}function _(e,t,r){const i=e.length;(!t||t<0)&&(t=0),(!r||r<0||r>i)&&(r=i);let o="";for(let n=t;n<r;++n)o+=Z[e[n]];return o}function P(e,t,r){const i=e.slice(t,r);let o="";for(let n=0;n<i.length-1;n+=2)o+=String.fromCharCode(i[n]+256*i[n+1]);return o}function F(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,o,n){if(!l.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>o||t<n)throw new RangeError('"value" argument is out of bounds');if(r+i>e.length)throw new RangeError("Index out of range")}function z(e,t,r,i,o){H(t,i,o,e,r,7);let n=Number(t&BigInt(4294967295));e[r++]=n,n>>=8,e[r++]=n,n>>=8,e[r++]=n,n>>=8,e[r++]=n;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 D(e,t,r,i,o){H(t,i,o,e,r,7);let n=Number(t&BigInt(4294967295));e[r+7]=n,n>>=8,e[r+6]=n,n>>=8,e[r+5]=n,n>>=8,e[r+4]=n;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 B(e,t,r,i,o,n){if(r+i>e.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("Index out of range")}function M(e,t,i,o,n){return t=+t,i>>>=0,n||B(e,0,i,4),r.write(e,t,i,o,23,4),i+4}function U(e,t,i,o,n){return t=+t,i>>>=0,n||B(e,0,i,8),r.write(e,t,i,o,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||F(e,t,this.length);let i=this[e],o=1,n=0;for(;++n<t&&(o*=256);)i+=this[e+n]*o;return i},l.prototype.readUintBE=l.prototype.readUIntBE=function(e,t,r){e>>>=0,t>>>=0,r||F(e,t,this.length);let i=this[e+--t],o=1;for(;t>0&&(o*=256);)i+=this[e+--t]*o;return i},l.prototype.readUint8=l.prototype.readUInt8=function(e,t){return e>>>=0,t||F(e,1,this.length),this[e]},l.prototype.readUint16LE=l.prototype.readUInt16LE=function(e,t){return e>>>=0,t||F(e,2,this.length),this[e]|this[e+1]<<8},l.prototype.readUint16BE=l.prototype.readUInt16BE=function(e,t){return e>>>=0,t||F(e,2,this.length),this[e]<<8|this[e+1]},l.prototype.readUint32LE=l.prototype.readUInt32LE=function(e,t){return e>>>=0,t||F(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||F(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},l.prototype.readBigUInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||j(e,this.length-8);const i=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,o=this[++e]+256*this[++e]+65536*this[++e]+r*2**24;return BigInt(i)+(BigInt(o)<<BigInt(32))}),l.prototype.readBigUInt64BE=Q(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||j(e,this.length-8);const i=t*2**24+65536*this[++e]+256*this[++e]+this[++e],o=this[++e]*2**24+65536*this[++e]+256*this[++e]+r;return(BigInt(i)<<BigInt(32))+BigInt(o)}),l.prototype.readIntLE=function(e,t,r){e>>>=0,t>>>=0,r||F(e,t,this.length);let i=this[e],o=1,n=0;for(;++n<t&&(o*=256);)i+=this[e+n]*o;return o*=128,i>=o&&(i-=Math.pow(2,8*t)),i},l.prototype.readIntBE=function(e,t,r){e>>>=0,t>>>=0,r||F(e,t,this.length);let i=t,o=1,n=this[e+--i];for(;i>0&&(o*=256);)n+=this[e+--i]*o;return o*=128,n>=o&&(n-=Math.pow(2,8*t)),n},l.prototype.readInt8=function(e,t){return e>>>=0,t||F(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},l.prototype.readInt16LE=function(e,t){e>>>=0,t||F(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||F(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||F(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||F(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},l.prototype.readBigInt64LE=Q(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||j(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=Q(function(e){q(e>>>=0,"offset");const t=this[e],r=this[e+7];void 0!==t&&void 0!==r||j(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||F(e,4,this.length),r.read(this,e,!0,23,4)},l.prototype.readFloatBE=function(e,t){return e>>>=0,t||F(e,4,this.length),r.read(this,e,!1,23,4)},l.prototype.readDoubleLE=function(e,t){return e>>>=0,t||F(e,8,this.length),r.read(this,e,!0,52,8)},l.prototype.readDoubleBE=function(e,t){return e>>>=0,t||F(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 o=1,n=0;for(this[t]=255&e;++n<r&&(o*=256);)this[t+n]=e/o&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 o=r-1,n=1;for(this[t+o]=255&e;--o>=0&&(n*=256);)this[t+o]=e/n&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=Q(function(e,t=0){return z(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),l.prototype.writeBigUInt64BE=Q(function(e,t=0){return D(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 o=0,n=1,s=0;for(this[t]=255&e;++o<r&&(n*=256);)e<0&&0===s&&0!==this[t+o-1]&&(s=1),this[t+o]=(e/n|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 o=r-1,n=1,s=0;for(this[t+o]=255&e;--o>=0&&(n*=256);)e<0&&0===s&&0!==this[t+o+1]&&(s=1),this[t+o]=(e/n|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=Q(function(e,t=0){return z(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeBigInt64BE=Q(function(e,t=0){return D(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),l.prototype.writeFloatLE=function(e,t,r){return M(this,e,t,!0,r)},l.prototype.writeFloatBE=function(e,t,r){return M(this,e,t,!1,r)},l.prototype.writeDoubleLE=function(e,t,r){return U(this,e,t,!0,r)},l.prototype.writeDoubleBE=function(e,t,r){return U(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 o=i-r;return this===e&&"function"==typeof n.prototype.copyWithin?this.copyWithin(t,r,i):n.prototype.set.call(e,this.subarray(r,i),t),o},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 o;if(t>>>=0,r=void 0===r?this.length:r>>>0,e||(e=0),"number"==typeof e)for(o=t;o<r;++o)this[o]=e;else{const n=l.isBuffer(e)?e:l.from(e,i),s=n.length;if(0===s)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(o=0;o<r-t;++o)this[o+t]=n[o%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 H(e,t,r,i,o,n){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*(n+1)}${r}`:`>= -(2${r} ** ${8*(n+1)-1}${r}) and < 2 ** ${8*(n+1)-1}${r}`,new L.ERR_OUT_OF_RANGE("value",i,e)}!function(e,t,r){q(t,"offset"),void 0!==e[t]&&void 0!==e[t+r]||j(t,e.length-(r+1))}(i,o,n)}function q(e,t){if("number"!=typeof e)throw new L.ERR_INVALID_ARG_TYPE(t,"number",e)}function j(e,t,r){if(Math.floor(e)!==e)throw q(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.`,o=r;return Number.isInteger(r)&&Math.abs(r)>2**32?o=$(String(r)):"bigint"==typeof r&&(o=String(r),(r>BigInt(2)**BigInt(32)||r<-(BigInt(2)**BigInt(32)))&&(o=$(o)),o+="n"),i+=` It must be ${t}. Received ${o}`,i},RangeError);const W=/[^+/0-9A-Za-z-_]/g;function V(e,t){let r;t=t||1/0;const i=e.length;let o=null;const n=[];for(let s=0;s<i;++s){if(r=e.charCodeAt(s),r>55295&&r<57344){if(!o){if(r>56319){(t-=3)>-1&&n.push(239,191,189);continue}if(s+1===i){(t-=3)>-1&&n.push(239,191,189);continue}o=r;continue}if(r<56320){(t-=3)>-1&&n.push(239,191,189),o=r;continue}r=65536+(o-55296<<10|r-56320)}else o&&(t-=3)>-1&&n.push(239,191,189);if(o=null,r<128){if((t-=1)<0)break;n.push(r)}else if(r<2048){if((t-=2)<0)break;n.push(r>>6|192,63&r|128)}else if(r<65536){if((t-=3)<0)break;n.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;n.push(r>>18|240,r>>12&63|128,r>>6&63|128,63&r|128)}}return n}function G(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(W,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function J(e,t,r,i){let o;for(o=0;o<i&&!(o+r>=t.length||o>=e.length);++o)t[o+r]=e[o];return o}function Y(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function X(e){return e!=e}const Z=function(){const e="0123456789abcdef",t=new Array(256);for(let r=0;r<16;++r){const i=16*r;for(let o=0;o<16;++o)t[i+o]=e[r]+e[o]}return t}();function Q(e){return"undefined"==typeof BigInt?ee:e}function ee(){throw new Error("BigInt not supported")}}(ce);const we=ce.Buffer,Ie=ce.Buffer,Te=globalThis||self;function Se(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var ke,Ee,Ae={exports:{}},ve=Ae.exports={};function Ce(){throw new Error("setTimeout has not been defined")}function xe(){throw new Error("clearTimeout has not been defined")}function Re(e){if(ke===setTimeout)return setTimeout(e,0);if((ke===Ce||!ke)&&setTimeout)return ke=setTimeout,setTimeout(e,0);try{return ke(e,0)}catch(t){try{return ke.call(null,e,0)}catch(r){return ke.call(this,e,0)}}}!function(){try{ke="function"==typeof setTimeout?setTimeout:Ce}catch(e){ke=Ce}try{Ee="function"==typeof clearTimeout?clearTimeout:xe}catch(e){Ee=xe}}();var Ne,_e=[],Pe=!1,Fe=-1;function Oe(){Pe&&Ne&&(Pe=!1,Ne.length?_e=Ne.concat(_e):Fe=-1,_e.length&&ze())}function ze(){if(!Pe){var e=Re(Oe);Pe=!0;for(var t=_e.length;t;){for(Ne=_e,_e=[];++Fe<t;)Ne&&Ne[Fe].run();Fe=-1,t=_e.length}Ne=null,Pe=!1,function(e){if(Ee===clearTimeout)return clearTimeout(e);if((Ee===xe||!Ee)&&clearTimeout)return Ee=clearTimeout,clearTimeout(e);try{return Ee(e)}catch(t){try{return Ee.call(null,e)}catch(r){return Ee.call(this,e)}}}(e)}}function De(e,t){this.fun=e,this.array=t}function Be(){}ve.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];_e.push(new De(e,t)),1!==_e.length||Pe||Re(ze)},De.prototype.run=function(){this.fun.apply(null,this.array)},ve.title="browser",ve.browser=!0,ve.env={},ve.argv=[],ve.version="",ve.versions={},ve.on=Be,ve.addListener=Be,ve.once=Be,ve.off=Be,ve.removeListener=Be,ve.removeAllListeners=Be,ve.emit=Be,ve.prependListener=Be,ve.prependOnceListener=Be,ve.listeners=function(e){return[]},ve.binding=function(e){throw new Error("process.binding is not supported")},ve.cwd=function(){return"/"},ve.chdir=function(e){throw new Error("process.chdir is not supported")},ve.umask=function(){return 0};const Me=Se(Ae.exports);function Ue(e,t){return function(){return e.apply(t,arguments)}}const{toString:Le}=Object.prototype,{getPrototypeOf:Ke}=Object,{iterator:$e,toStringTag:He}=Symbol,qe=(e=>t=>{const r=Le.call(t);return e[r]||(e[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),je=e=>(e=e.toLowerCase(),t=>qe(t)===e),We=e=>t=>typeof t===e,{isArray:Ve}=Array,Ge=We("undefined");function Je(e){return null!==e&&!Ge(e)&&null!==e.constructor&&!Ge(e.constructor)&&Ze(e.constructor.isBuffer)&&e.constructor.isBuffer(e)}const Ye=je("ArrayBuffer");const Xe=We("string"),Ze=We("function"),Qe=We("number"),et=e=>null!==e&&"object"==typeof e,tt=e=>{if("object"!==qe(e))return!1;const t=Ke(e);return!(null!==t&&t!==Object.prototype&&null!==Object.getPrototypeOf(t)||He in e||$e in e)},rt=je("Date"),it=je("File"),ot=je("Blob"),nt=je("FileList"),st=je("URLSearchParams"),[at,ct,lt,dt]=["ReadableStream","Request","Response","Headers"].map(je);function ut(e,t,{allOwnKeys:r=!1}={}){if(null==e)return;let i,o;if("object"!=typeof e&&(e=[e]),Ve(e))for(i=0,o=e.length;i<o;i++)t.call(null,e[i],i,e);else{if(Je(e))return;const o=r?Object.getOwnPropertyNames(e):Object.keys(e),n=o.length;let s;for(i=0;i<n;i++)s=o[i],t.call(null,e[s],s,e)}}function pt(e,t){if(Je(e))return null;t=t.toLowerCase();const r=Object.keys(e);let i,o=r.length;for(;o-- >0;)if(i=r[o],t===i.toLowerCase())return i;return null}const ht="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:"undefined"!=typeof window?window:Te,gt=e=>!Ge(e)&&e!==ht;const mt=(e=>t=>e&&t instanceof e)("undefined"!=typeof Uint8Array&&Ke(Uint8Array)),ft=je("HTMLFormElement"),yt=(({hasOwnProperty:e})=>(t,r)=>e.call(t,r))(Object.prototype),bt=je("RegExp"),wt=(e,t)=>{const r=Object.getOwnPropertyDescriptors(e),i={};ut(r,(r,o)=>{let n;!1!==(n=t(r,o,e))&&(i[o]=n||r)}),Object.defineProperties(e,i)};const It=je("AsyncFunction"),Tt=(St="function"==typeof setImmediate,kt=Ze(ht.postMessage),St?setImmediate:kt?(Et=`axios@${Math.random()}`,At=[],ht.addEventListener("message",({source:e,data:t})=>{e===ht&&t===Et&&At.length&&At.shift()()},!1),e=>{At.push(e),ht.postMessage(Et,"*")}):e=>setTimeout(e));var St,kt,Et,At;const vt="undefined"!=typeof queueMicrotask?queueMicrotask.bind(ht):void 0!==Me&&Me.nextTick||Tt,Ct={isArray:Ve,isArrayBuffer:Ye,isBuffer:Je,isFormData:e=>{let t;return e&&("function"==typeof FormData&&e instanceof FormData||Ze(e.append)&&("formdata"===(t=qe(e))||"object"===t&&Ze(e.toString)&&"[object FormData]"===e.toString()))},isArrayBufferView:function(e){let t;return t="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer&&Ye(e.buffer),t},isString:Xe,isNumber:Qe,isBoolean:e=>!0===e||!1===e,isObject:et,isPlainObject:tt,isEmptyObject:e=>{if(!et(e)||Je(e))return!1;try{return 0===Object.keys(e).length&&Object.getPrototypeOf(e)===Object.prototype}catch(t){return!1}},isReadableStream:at,isRequest:ct,isResponse:lt,isHeaders:dt,isUndefined:Ge,isDate:rt,isFile:it,isBlob:ot,isRegExp:bt,isFunction:Ze,isStream:e=>et(e)&&Ze(e.pipe),isURLSearchParams:st,isTypedArray:mt,isFileList:nt,forEach:ut,merge:function e(){const{caseless:t}=gt(this)&&this||{},r={},i=(i,o)=>{const n=t&&pt(r,o)||o;tt(r[n])&&tt(i)?r[n]=e(r[n],i):tt(i)?r[n]=e({},i):Ve(i)?r[n]=i.slice():r[n]=i};for(let o=0,n=arguments.length;o<n;o++)arguments[o]&&ut(arguments[o],i);return r},extend:(e,t,r,{allOwnKeys:i}={})=>(ut(t,(t,i)=>{r&&Ze(t)?e[i]=Ue(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 o,n,s;const a={};if(t=t||{},null==e)return t;do{for(o=Object.getOwnPropertyNames(e),n=o.length;n-- >0;)s=o[n],i&&!i(s,e,t)||a[s]||(t[s]=e[s],a[s]=!0);e=!1!==r&&Ke(e)}while(e&&(!r||r(e,t))&&e!==Object.prototype);return t},kindOf:qe,kindOfTest:je,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(Ve(e))return e;let t=e.length;if(!Qe(t))return null;const r=new Array(t);for(;t-- >0;)r[t]=e[t];return r},forEachEntry:(e,t)=>{const r=(e&&e[$e]).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:ft,hasOwnProperty:yt,hasOwnProp:yt,reduceDescriptors:wt,freezeMethods:e=>{wt(e,(t,r)=>{if(Ze(e)&&-1!==["arguments","caller","callee"].indexOf(r))return!1;const i=e[r];Ze(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 Ve(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:pt,global:ht,isContextDefined:gt,isSpecCompliantForm:function(e){return!!(e&&Ze(e.append)&&"FormData"===e[He]&&e[$e])},toJSONObject:e=>{const t=new Array(10),r=(e,i)=>{if(et(e)){if(t.indexOf(e)>=0)return;if(Je(e))return e;if(!("toJSON"in e)){t[i]=e;const o=Ve(e)?[]:{};return ut(e,(e,t)=>{const n=r(e,i+1);!Ge(n)&&(o[t]=n)}),t[i]=void 0,o}}return e};return r(e,0)},isAsyncFn:It,isThenable:e=>e&&(et(e)||Ze(e))&&Ze(e.then)&&Ze(e.catch),setImmediate:Tt,asap:vt,isIterable:e=>null!=e&&Ze(e[$e])};function xt(e,t,r,i,o){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),o&&(this.response=o,this.status=o.status?o.status:null)}Ct.inherits(xt,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:Ct.toJSONObject(this.config),code:this.code,status:this.status}}});const Rt=xt.prototype,Nt={};["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=>{Nt[e]={value:e}}),Object.defineProperties(xt,Nt),Object.defineProperty(Rt,"isAxiosError",{value:!0}),xt.from=(e,t,r,i,o,n)=>{const s=Object.create(Rt);return Ct.toFlatObject(e,s,function(e){return e!==Error.prototype},e=>"isAxiosError"!==e),xt.call(s,e.message,t,r,i,o),s.cause=e,s.name=e.name,n&&Object.assign(s,n),s};function _t(e){return Ct.isPlainObject(e)||Ct.isArray(e)}function Pt(e){return Ct.endsWith(e,"[]")?e.slice(0,-2):e}function Ft(e,t,r){return e?e.concat(t).map(function(e,t){return e=Pt(e),!r&&t?"["+e+"]":e}).join(r?".":""):t}const Ot=Ct.toFlatObject(Ct,{},null,function(e){return/^is[A-Z]/.test(e)});function zt(e,t,r){if(!Ct.isObject(e))throw new TypeError("target must be an object");t=t||new FormData;const i=(r=Ct.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(e,t){return!Ct.isUndefined(t[e])})).metaTokens,o=r.visitor||l,n=r.dots,s=r.indexes,a=(r.Blob||"undefined"!=typeof Blob&&Blob)&&Ct.isSpecCompliantForm(t);if(!Ct.isFunction(o))throw new TypeError("visitor must be a function");function c(e){if(null===e)return"";if(Ct.isDate(e))return e.toISOString();if(Ct.isBoolean(e))return e.toString();if(!a&&Ct.isBlob(e))throw new xt("Blob is not supported. Use a Buffer instead.");return Ct.isArrayBuffer(e)||Ct.isTypedArray(e)?a&&"function"==typeof Blob?new Blob([e]):we.from(e):e}function l(e,r,o){let a=e;if(e&&!o&&"object"==typeof e)if(Ct.endsWith(r,"{}"))r=i?r:r.slice(0,-2),e=JSON.stringify(e);else if(Ct.isArray(e)&&function(e){return Ct.isArray(e)&&!e.some(_t)}(e)||(Ct.isFileList(e)||Ct.endsWith(r,"[]"))&&(a=Ct.toArray(e)))return r=Pt(r),a.forEach(function(e,i){!Ct.isUndefined(e)&&null!==e&&t.append(!0===s?Ft([r],i,n):null===s?r:r+"[]",c(e))}),!1;return!!_t(e)||(t.append(Ft(o,r,n),c(e)),!1)}const d=[],u=Object.assign(Ot,{defaultVisitor:l,convertValue:c,isVisitable:_t});if(!Ct.isObject(e))throw new TypeError("data must be an object");return function e(r,i){if(!Ct.isUndefined(r)){if(-1!==d.indexOf(r))throw Error("Circular reference detected in "+i.join("."));d.push(r),Ct.forEach(r,function(r,n){!0===(!(Ct.isUndefined(r)||null===r)&&o.call(t,r,Ct.isString(n)?n.trim():n,i,u))&&e(r,i?i.concat(n):[n])}),d.pop()}}(e),t}function Dt(e){const t={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(e).replace(/[!'()~]|%20|%00/g,function(e){return t[e]})}function Bt(e,t){this._pairs=[],e&&zt(e,this,t)}const Mt=Bt.prototype;function Ut(e){return encodeURIComponent(e).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Lt(e,t,r){if(!t)return e;const i=r&&r.encode||Ut;Ct.isFunction(r)&&(r={serialize:r});const o=r&&r.serialize;let n;if(n=o?o(t,r):Ct.isURLSearchParams(t)?t.toString():new Bt(t,r).toString(i),n){const t=e.indexOf("#");-1!==t&&(e=e.slice(0,t)),e+=(-1===e.indexOf("?")?"?":"&")+n}return e}Mt.append=function(e,t){this._pairs.push([e,t])},Mt.toString=function(e){const t=e?function(t){return e.call(this,t,Dt)}:Dt;return this._pairs.map(function(e){return t(e[0])+"="+t(e[1])},"").join("&")};class Kt{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){Ct.forEach(this.handlers,function(t){null!==t&&e(t)})}}const $t={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Ht={isBrowser:!0,classes:{URLSearchParams:"undefined"!=typeof URLSearchParams?URLSearchParams:Bt,FormData:"undefined"!=typeof FormData?FormData:null,Blob:"undefined"!=typeof Blob?Blob:null},protocols:["http","https","file","blob","url","data"]},qt="undefined"!=typeof window&&"undefined"!=typeof document,jt="object"==typeof navigator&&navigator||void 0,Wt=qt&&(!jt||["ReactNative","NativeScript","NS"].indexOf(jt.product)<0),Vt="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope&&"function"==typeof self.importScripts,Gt=qt&&window.location.href||"http://localhost",Jt={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:qt,hasStandardBrowserEnv:Wt,hasStandardBrowserWebWorkerEnv:Vt,navigator:jt,origin:Gt},Symbol.toStringTag,{value:"Module"})),...Ht};function Yt(e){function t(e,r,i,o){let n=e[o++];if("__proto__"===n)return!0;const s=Number.isFinite(+n),a=o>=e.length;if(n=!n&&Ct.isArray(i)?i.length:n,a)return Ct.hasOwnProp(i,n)?i[n]=[i[n],r]:i[n]=r,!s;i[n]&&Ct.isObject(i[n])||(i[n]=[]);return t(e,r,i[n],o)&&Ct.isArray(i[n])&&(i[n]=function(e){const t={},r=Object.keys(e);let i;const o=r.length;let n;for(i=0;i<o;i++)n=r[i],t[n]=e[n];return t}(i[n])),!s}if(Ct.isFormData(e)&&Ct.isFunction(e.entries)){const r={};return Ct.forEachEntry(e,(e,i)=>{t(function(e){return Ct.matchAll(/\w+|\[(\w*)]/g,e).map(e=>"[]"===e[0]?"":e[1]||e[0])}(e),i,r,0)}),r}return null}const Xt={transitional:$t,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const r=t.getContentType()||"",i=r.indexOf("application/json")>-1,o=Ct.isObject(e);o&&Ct.isHTMLForm(e)&&(e=new FormData(e));if(Ct.isFormData(e))return i?JSON.stringify(Yt(e)):e;if(Ct.isArrayBuffer(e)||Ct.isBuffer(e)||Ct.isStream(e)||Ct.isFile(e)||Ct.isBlob(e)||Ct.isReadableStream(e))return e;if(Ct.isArrayBufferView(e))return e.buffer;if(Ct.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let n;if(o){if(r.indexOf("application/x-www-form-urlencoded")>-1)return function(e,t){return zt(e,new Jt.classes.URLSearchParams,{visitor:function(e,t,r,i){return Jt.isNode&&Ct.isBuffer(e)?(this.append(t,e.toString("base64")),!1):i.defaultVisitor.apply(this,arguments)},...t})}(e,this.formSerializer).toString();if((n=Ct.isFileList(e))||r.indexOf("multipart/form-data")>-1){const t=this.env&&this.env.FormData;return zt(n?{"files[]":e}:e,t&&new t,this.formSerializer)}}return o||i?(t.setContentType("application/json",!1),function(e,t,r){if(Ct.isString(e))try{return(t||JSON.parse)(e),Ct.trim(e)}catch(i){if("SyntaxError"!==i.name)throw i}return(r||JSON.stringify)(e)}(e)):e}],transformResponse:[function(e){const t=this.transitional||Xt.transitional,r=t&&t.forcedJSONParsing,i="json"===this.responseType;if(Ct.isResponse(e)||Ct.isReadableStream(e))return e;if(e&&Ct.isString(e)&&(r&&!this.responseType||i)){const r=!(t&&t.silentJSONParsing)&&i;try{return JSON.parse(e)}catch(o){if(r){if("SyntaxError"===o.name)throw xt.from(o,xt.ERR_BAD_RESPONSE,this,null,this.response);throw o}}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Jt.classes.FormData,Blob:Jt.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};Ct.forEach(["delete","get","head","post","put","patch"],e=>{Xt.headers[e]={}});const Zt=Ct.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"]),Qt=Symbol("internals");function er(e){return e&&String(e).trim().toLowerCase()}function tr(e){return!1===e||null==e?e:Ct.isArray(e)?e.map(tr):String(e)}function rr(e,t,r,i,o){return Ct.isFunction(i)?i.call(this,t,r):(o&&(t=r),Ct.isString(t)?Ct.isString(i)?-1!==t.indexOf(i):Ct.isRegExp(i)?i.test(t):void 0:void 0)}let ir=class{constructor(e){e&&this.set(e)}set(e,t,r){const i=this;function o(e,t,r){const o=er(t);if(!o)throw new Error("header name must be a non-empty string");const n=Ct.findKey(i,o);(!n||void 0===i[n]||!0===r||void 0===r&&!1!==i[n])&&(i[n||t]=tr(e))}const n=(e,t)=>Ct.forEach(e,(e,r)=>o(e,r,t));if(Ct.isPlainObject(e)||e instanceof this.constructor)n(e,t);else if(Ct.isString(e)&&(e=e.trim())&&!/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(e.trim()))n((e=>{const t={};let r,i,o;return e&&e.split("\n").forEach(function(e){o=e.indexOf(":"),r=e.substring(0,o).trim().toLowerCase(),i=e.substring(o+1).trim(),!r||t[r]&&Zt[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(Ct.isObject(e)&&Ct.isIterable(e)){let r,i,o={};for(const t of e){if(!Ct.isArray(t))throw TypeError("Object iterator must return a key-value pair");o[i=t[0]]=(r=o[i])?Ct.isArray(r)?[...r,t[1]]:[r,t[1]]:t[1]}n(o,t)}else null!=e&&o(t,e,r);return this}get(e,t){if(e=er(e)){const r=Ct.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(Ct.isFunction(t))return t.call(this,e,r);if(Ct.isRegExp(t))return t.exec(e);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=er(e)){const r=Ct.findKey(this,e);return!(!r||void 0===this[r]||t&&!rr(0,this[r],r,t))}return!1}delete(e,t){const r=this;let i=!1;function o(e){if(e=er(e)){const o=Ct.findKey(r,e);!o||t&&!rr(0,r[o],o,t)||(delete r[o],i=!0)}}return Ct.isArray(e)?e.forEach(o):o(e),i}clear(e){const t=Object.keys(this);let r=t.length,i=!1;for(;r--;){const o=t[r];e&&!rr(0,this[o],o,e,!0)||(delete this[o],i=!0)}return i}normalize(e){const t=this,r={};return Ct.forEach(this,(i,o)=>{const n=Ct.findKey(r,o);if(n)return t[n]=tr(i),void delete t[o];const s=e?function(e){return e.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,r)=>t.toUpperCase()+r)}(o):String(o).trim();s!==o&&delete t[o],t[s]=tr(i),r[s]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return Ct.forEach(this,(r,i)=>{null!=r&&!1!==r&&(t[i]=e&&Ct.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[Qt]=this[Qt]={accessors:{}}).accessors,r=this.prototype;function i(e){const i=er(e);t[i]||(!function(e,t){const r=Ct.toCamelCase(" "+t);["get","set","has"].forEach(i=>{Object.defineProperty(e,i+r,{value:function(e,r,o){return this[i].call(this,t,e,r,o)},configurable:!0})})}(r,e),t[i]=!0)}return Ct.isArray(e)?e.forEach(i):i(e),this}};function or(e,t){const r=this||Xt,i=t||r,o=ir.from(i.headers);let n=i.data;return Ct.forEach(e,function(e){n=e.call(r,n,o.normalize(),t?t.status:void 0)}),o.normalize(),n}function nr(e){return!(!e||!e.__CANCEL__)}function sr(e,t,r){xt.call(this,null==e?"canceled":e,xt.ERR_CANCELED,t,r),this.name="CanceledError"}function ar(e,t,r){const i=r.config.validateStatus;r.status&&i&&!i(r.status)?t(new xt("Request failed with status code "+r.status,[xt.ERR_BAD_REQUEST,xt.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r)):e(r)}ir.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),Ct.reduceDescriptors(ir.prototype,({value:e},t)=>{let r=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(e){this[r]=e}}}),Ct.freezeMethods(ir),Ct.inherits(sr,xt,{__CANCEL__:!0});const cr=(e,t,r=3)=>{let i=0;const o=function(e,t){e=e||10;const r=new Array(e),i=new Array(e);let o,n=0,s=0;return t=void 0!==t?t:1e3,function(a){const c=Date.now(),l=i[s];o||(o=c),r[n]=a,i[n]=c;let d=s,u=0;for(;d!==n;)u+=r[d++],d%=e;if(n=(n+1)%e,n===s&&(s=(s+1)%e),c-o<t)return;const p=l&&c-l;return p?Math.round(1e3*u/p):void 0}}(50,250);return function(e,t){let r,i,o=0,n=1e3/t;const s=(t,n=Date.now())=>{o=n,r=null,i&&(clearTimeout(i),i=null),e(...t)};return[(...e)=>{const t=Date.now(),a=t-o;a>=n?s(e,t):(r=e,i||(i=setTimeout(()=>{i=null,s(r)},n-a)))},()=>r&&s(r)]}(r=>{const n=r.loaded,s=r.lengthComputable?r.total:void 0,a=n-i,c=o(a);i=n;e({loaded:n,total:s,progress:s?n/s:void 0,bytes:a,rate:c||void 0,estimated:c&&s&&n<=s?(s-n)/c:void 0,event:r,lengthComputable:null!=s,[t?"download":"upload"]:!0})},r)},lr=(e,t)=>{const r=null!=e;return[i=>t[0]({lengthComputable:r,total:e,loaded:i}),t[1]]},dr=e=>(...t)=>Ct.asap(()=>e(...t)),ur=Jt.hasStandardBrowserEnv?((e,t)=>r=>(r=new URL(r,Jt.origin),e.protocol===r.protocol&&e.host===r.host&&(t||e.port===r.port)))(new URL(Jt.origin),Jt.navigator&&/(msie|trident)/i.test(Jt.navigator.userAgent)):()=>!0,pr=Jt.hasStandardBrowserEnv?{write(e,t,r,i,o,n){const s=[e+"="+encodeURIComponent(t)];Ct.isNumber(r)&&s.push("expires="+new Date(r).toGMTString()),Ct.isString(i)&&s.push("path="+i),Ct.isString(o)&&s.push("domain="+o),!0===n&&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 hr(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 gr=e=>e instanceof ir?{...e}:e;function mr(e,t){t=t||{};const r={};function i(e,t,r,i){return Ct.isPlainObject(e)&&Ct.isPlainObject(t)?Ct.merge.call({caseless:i},e,t):Ct.isPlainObject(t)?Ct.merge({},t):Ct.isArray(t)?t.slice():t}function o(e,t,r,o){return Ct.isUndefined(t)?Ct.isUndefined(e)?void 0:i(void 0,e,0,o):i(e,t,0,o)}function n(e,t){if(!Ct.isUndefined(t))return i(void 0,t)}function s(e,t){return Ct.isUndefined(t)?Ct.isUndefined(e)?void 0:i(void 0,e):i(void 0,t)}function a(r,o,n){return n in t?i(r,o):n in e?i(void 0,r):void 0}const c={url:n,method:n,data:n,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)=>o(gr(e),gr(t),0,!0)};return Ct.forEach(Object.keys({...e,...t}),function(i){const n=c[i]||o,s=n(e[i],t[i],i);Ct.isUndefined(s)&&n!==a||(r[i]=s)}),r}const fr=e=>{const t=mr({},e);let r,{data:i,withXSRFToken:o,xsrfHeaderName:n,xsrfCookieName:s,headers:a,auth:c}=t;if(t.headers=a=ir.from(a),t.url=Lt(hr(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),c&&a.set("Authorization","Basic "+btoa((c.username||"")+":"+(c.password?unescape(encodeURIComponent(c.password)):""))),Ct.isFormData(i))if(Jt.hasStandardBrowserEnv||Jt.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(Jt.hasStandardBrowserEnv&&(o&&Ct.isFunction(o)&&(o=o(t)),o||!1!==o&&ur(t.url))){const e=n&&s&&pr.read(s);e&&a.set(n,e)}return t},yr="undefined"!=typeof XMLHttpRequest&&function(e){return new Promise(function(t,r){const i=fr(e);let o=i.data;const n=ir.from(i.headers).normalize();let s,a,c,l,d,{responseType:u,onUploadProgress:p,onDownloadProgress:h}=i;function g(){l&&l(),d&&d(),i.cancelToken&&i.cancelToken.unsubscribe(s),i.signal&&i.signal.removeEventListener("abort",s)}let m=new XMLHttpRequest;function f(){if(!m)return;const i=ir.from("getAllResponseHeaders"in m&&m.getAllResponseHeaders());ar(function(e){t(e),g()},function(e){r(e),g()},{data:u&&"text"!==u&&"json"!==u?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 xt("Request aborted",xt.ECONNABORTED,e,m)),m=null)},m.onerror=function(){r(new xt("Network Error",xt.ERR_NETWORK,e,m)),m=null},m.ontimeout=function(){let t=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const o=i.transitional||$t;i.timeoutErrorMessage&&(t=i.timeoutErrorMessage),r(new xt(t,o.clarifyTimeoutError?xt.ETIMEDOUT:xt.ECONNABORTED,e,m)),m=null},void 0===o&&n.setContentType(null),"setRequestHeader"in m&&Ct.forEach(n.toJSON(),function(e,t){m.setRequestHeader(t,e)}),Ct.isUndefined(i.withCredentials)||(m.withCredentials=!!i.withCredentials),u&&"json"!==u&&(m.responseType=i.responseType),h&&([c,d]=cr(h,!0),m.addEventListener("progress",c)),p&&m.upload&&([a,l]=cr(p),m.upload.addEventListener("progress",a),m.upload.addEventListener("loadend",l)),(i.cancelToken||i.signal)&&(s=t=>{m&&(r(!t||t.type?new sr(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===Jt.protocols.indexOf(y)?r(new xt("Unsupported protocol "+y+":",xt.ERR_BAD_REQUEST,e)):m.send(o||null)})},br=(e,t)=>{const{length:r}=e=e?e.filter(Boolean):[];if(t||r){let r,i=new AbortController;const o=function(e){if(!r){r=!0,s();const t=e instanceof Error?e:this.reason;i.abort(t instanceof xt?t:new sr(t instanceof Error?t.message:t))}};let n=t&&setTimeout(()=>{n=null,o(new xt(`timeout ${t} of ms exceeded`,xt.ETIMEDOUT))},t);const s=()=>{e&&(n&&clearTimeout(n),n=null,e.forEach(e=>{e.unsubscribe?e.unsubscribe(o):e.removeEventListener("abort",o)}),e=null)};e.forEach(e=>e.addEventListener("abort",o));const{signal:a}=i;return a.unsubscribe=()=>Ct.asap(s),a}},wr=function*(e,t){let r=e.byteLength;if(r<t)return void(yield e);let i,o=0;for(;o<r;)i=o+t,yield e.slice(o,i),o=i},Ir=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 o=async function*(e,t){for await(const r of Ir(e))yield*wr(r,t)}(e,t);let n,s=0,a=e=>{n||(n=!0,i&&i(e))};return new ReadableStream({async pull(e){try{const{done:t,value:i}=await o.next();if(t)return a(),void e.close();let n=i.byteLength;if(r){let e=s+=n;r(e)}e.enqueue(new Uint8Array(i))}catch(t){throw a(t),t}},cancel:e=>(a(e),o.return())},{highWaterMark:2})},Sr="function"==typeof fetch&&"function"==typeof Request&&"function"==typeof Response,kr=Sr&&"function"==typeof ReadableStream,Er=Sr&&("function"==typeof TextEncoder?(e=>t=>e.encode(t))(new TextEncoder):async e=>new Uint8Array(await new Response(e).arrayBuffer())),Ar=(e,...t)=>{try{return!!e(...t)}catch(r){return!1}},vr=kr&&Ar(()=>{let e=!1;const t=new Request(Jt.origin,{body:new ReadableStream,method:"POST",get duplex(){return e=!0,"half"}}).headers.has("Content-Type");return e&&!t}),Cr=kr&&Ar(()=>Ct.isReadableStream(new Response("").body)),xr={stream:Cr&&(e=>e.body)};var Rr;Sr&&(Rr=new Response,["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!xr[e]&&(xr[e]=Ct.isFunction(Rr[e])?t=>t[e]():(t,r)=>{throw new xt(`Response type '${e}' is not supported`,xt.ERR_NOT_SUPPORT,r)})}));const Nr=async(e,t)=>{const r=Ct.toFiniteNumber(e.getContentLength());return null==r?(async e=>{if(null==e)return 0;if(Ct.isBlob(e))return e.size;if(Ct.isSpecCompliantForm(e)){const t=new Request(Jt.origin,{method:"POST",body:e});return(await t.arrayBuffer()).byteLength}return Ct.isArrayBufferView(e)||Ct.isArrayBuffer(e)?e.byteLength:(Ct.isURLSearchParams(e)&&(e+=""),Ct.isString(e)?(await Er(e)).byteLength:void 0)})(t):r},_r={http:null,xhr:yr,fetch:Sr&&(async e=>{let{url:t,method:r,data:i,signal:o,cancelToken:n,timeout:s,onDownloadProgress:a,onUploadProgress:c,responseType:l,headers:d,withCredentials:u="same-origin",fetchOptions:p}=fr(e);l=l?(l+"").toLowerCase():"text";let h,g=br([o,n&&n.toAbortSignal()],s);const m=g&&g.unsubscribe&&(()=>{g.unsubscribe()});let f;try{if(c&&vr&&"get"!==r&&"head"!==r&&0!==(f=await Nr(d,i))){let e,r=new Request(t,{method:"POST",body:i,duplex:"half"});if(Ct.isFormData(i)&&(e=r.headers.get("content-type"))&&d.setContentType(e),r.body){const[e,t]=lr(f,cr(dr(c)));i=Tr(r.body,65536,e,t)}}Ct.isString(u)||(u=u?"include":"omit");const o="credentials"in Request.prototype;h=new Request(t,{...p,signal:g,method:r.toUpperCase(),headers:d.normalize().toJSON(),body:i,duplex:"half",credentials:o?u:void 0});let n=await fetch(h,p);const s=Cr&&("stream"===l||"response"===l);if(Cr&&(a||s&&m)){const e={};["status","statusText","headers"].forEach(t=>{e[t]=n[t]});const t=Ct.toFiniteNumber(n.headers.get("content-length")),[r,i]=a&&lr(t,cr(dr(a),!0))||[];n=new Response(Tr(n.body,65536,r,()=>{i&&i(),m&&m()}),e)}l=l||"text";let y=await xr[Ct.findKey(xr,l)||"text"](n,e);return!s&&m&&m(),await new Promise((t,r)=>{ar(t,r,{data:y,headers:ir.from(n.headers),status:n.status,statusText:n.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 xt("Network Error",xt.ERR_NETWORK,e,h),{cause:y.cause||y});throw xt.from(y,y&&y.code,e,h)}})};Ct.forEach(_r,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch(r){}Object.defineProperty(e,"adapterName",{value:t})}});const Pr=e=>`- ${e}`,Fr=e=>Ct.isFunction(e)||null===e||!1===e,Or=e=>{e=Ct.isArray(e)?e:[e];const{length:t}=e;let r,i;const o={};for(let n=0;n<t;n++){let t;if(r=e[n],i=r,!Fr(r)&&(i=_r[(t=String(r)).toLowerCase()],void 0===i))throw new xt(`Unknown adapter '${t}'`);if(i)break;o[t||"#"+n]=i}if(!i){const e=Object.entries(o).map(([e,t])=>`adapter ${e} `+(!1===t?"is not supported by the environment":"is not available in the build"));throw new xt("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 zr(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new sr(null,e)}function Dr(e){zr(e),e.headers=ir.from(e.headers),e.data=or.call(e,e.transformRequest),-1!==["post","put","patch"].indexOf(e.method)&&e.headers.setContentType("application/x-www-form-urlencoded",!1);return Or(e.adapter||Xt.adapter)(e).then(function(t){return zr(e),t.data=or.call(e,e.transformResponse,t),t.headers=ir.from(t.headers),t},function(t){return nr(t)||(zr(e),t&&t.response&&(t.response.data=or.call(e,e.transformResponse,t.response),t.response.headers=ir.from(t.response.headers))),Promise.reject(t)})}const Br="1.11.0",Mr={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Mr[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Ur={};Mr.transitional=function(e,t,r){function i(e,t){return"[Axios v"+Br+"] Transitional option '"+e+"'"+t+(r?". "+r:"")}return(r,o,n)=>{if(!1===e)throw new xt(i(o," has been removed"+(t?" in "+t:"")),xt.ERR_DEPRECATED);return t&&!Ur[o]&&(Ur[o]=!0,console.warn(i(o," has been deprecated since v"+t+" and will be removed in the near future"))),!e||e(r,o,n)}},Mr.spelling=function(e){return(t,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};const Lr={assertOptions:function(e,t,r){if("object"!=typeof e)throw new xt("options must be an object",xt.ERR_BAD_OPTION_VALUE);const i=Object.keys(e);let o=i.length;for(;o-- >0;){const n=i[o],s=t[n];if(s){const t=e[n],r=void 0===t||s(t,n,e);if(!0!==r)throw new xt("option "+n+" must be "+r,xt.ERR_BAD_OPTION_VALUE);continue}if(!0!==r)throw new xt("Unknown option "+n,xt.ERR_BAD_OPTION)}},validators:Mr},Kr=Lr.validators;let $r=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Kt,response:new Kt}}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=mr(this.defaults,t);const{transitional:r,paramsSerializer:i,headers:o}=t;void 0!==r&&Lr.assertOptions(r,{silentJSONParsing:Kr.transitional(Kr.boolean),forcedJSONParsing:Kr.transitional(Kr.boolean),clarifyTimeoutError:Kr.transitional(Kr.boolean)},!1),null!=i&&(Ct.isFunction(i)?t.paramsSerializer={serialize:i}:Lr.assertOptions(i,{encode:Kr.function,serialize:Kr.function},!0)),void 0!==t.allowAbsoluteUrls||(void 0!==this.defaults.allowAbsoluteUrls?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Lr.assertOptions(t,{baseUrl:Kr.spelling("baseURL"),withXsrfToken:Kr.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let n=o&&Ct.merge(o.common,o[t.method]);o&&Ct.forEach(["delete","get","head","post","put","patch","common"],e=>{delete o[e]}),t.headers=ir.concat(n,o);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 d,u=0;if(!a){const e=[Dr.bind(this),void 0];for(e.unshift(...s),e.push(...c),d=e.length,l=Promise.resolve(t);u<d;)l=l.then(e[u++],e[u++]);return l}d=s.length;let p=t;for(u=0;u<d;){const e=s[u++],t=s[u++];try{p=e(p)}catch(h){t.call(this,h);break}}try{l=Dr.call(this,p)}catch(h){return Promise.reject(h)}for(u=0,d=c.length;u<d;)l=l.then(c[u++],c[u++]);return l}getUri(e){return Lt(hr((e=mr(this.defaults,e)).baseURL,e.url,e.allowAbsoluteUrls),e.params,e.paramsSerializer)}};Ct.forEach(["delete","get","head","options"],function(e){$r.prototype[e]=function(t,r){return this.request(mr(r||{},{method:e,url:t,data:(r||{}).data}))}}),Ct.forEach(["post","put","patch"],function(e){function t(t){return function(r,i,o){return this.request(mr(o||{},{method:e,headers:t?{"Content-Type":"multipart/form-data"}:{},url:r,data:i}))}}$r.prototype[e]=t(),$r.prototype[e+"Form"]=t(!0)});const Hr={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(Hr).forEach(([e,t])=>{Hr[t]=e});const qr=function e(t){const r=new $r(t),i=Ue($r.prototype.request,r);return Ct.extend(i,$r.prototype,r,{allOwnKeys:!0}),Ct.extend(i,r,null,{allOwnKeys:!0}),i.create=function(r){return e(mr(t,r))},i}(Xt);qr.Axios=$r,qr.CanceledError=sr,qr.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,o){r.reason||(r.reason=new sr(e,i,o),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}}},qr.isCancel=nr,qr.VERSION=Br,qr.toFormData=zt,qr.AxiosError=xt,qr.Cancel=qr.CanceledError,qr.all=function(e){return Promise.all(e)},qr.spread=function(e){return function(t){return e.apply(null,t)}},qr.isAxiosError=function(e){return Ct.isObject(e)&&!0===e.isAxiosError},qr.mergeConfig=mr,qr.AxiosHeaders=ir,qr.formToJSON=e=>Yt(Ct.isHTMLForm(e)?new FormData(e):e),qr.getAdapter=Or,qr.HttpStatusCode=Hr,qr.default=qr;const{Axios:jr,AxiosError:Wr,CanceledError:Vr,isCancel:Gr,CancelToken:Jr,VERSION:Yr,all:Xr,Cancel:Zr,isAxiosError:Qr,spread:ei,toFormData:ti,AxiosHeaders:ri,HttpStatusCode:ii,formToJSON:oi,getAdapter:ni,mergeConfig:si}=qr,ai=class e{constructor(){ae(this,"isProduction"),this.isProduction="production"===Me.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)}};ae(ai,"instance");let ci=ai;class li extends Error{constructor(e){super(e),this.name="ValidationError"}}class di{constructor(e){if(ae(this,"accountId"),ae(this,"privateKey"),ae(this,"baseUrl"),ae(this,"network"),this.accountId=e.accountId,"string"==typeof e.privateKey){const t=s.detectKeyTypeFromString(e.privateKey);this.privateKey=t.privateKey}else this.privateKey=e.privateKey;this.network=e.network||"mainnet",this.baseUrl=e.baseUrl||"https://kiloscribe.com"}async authenticate(){var e,t,r;const i=await qr.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 o=i.data.message,n=await this.signMessage(o),s=await qr.post(`${this.baseUrl}/api/auth/authenticate`,{authData:{id:this.accountId,signature:n,data:o,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 Ie.from(r).toString("hex")}}class ui{constructor(e){ae(this,"accountId"),ae(this,"signer"),ae(this,"baseUrl"),ae(this,"network"),ae(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 qr.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 o=i.data.message,n=await this.signMessage(JSON.stringify(o)),s=await qr.post(`${this.baseUrl}/api/auth/authenticate`,{authData:{id:this.accountId,signature:n,data:o,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 Ie.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 pi(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function hi(e){return new DataView(e.buffer,e.byteOffset)}const gi={len:1,get:(e,t)=>hi(e).getUint8(t),put:(e,t,r)=>(hi(e).setUint8(t,r),t+1)},mi={len:2,get:(e,t)=>hi(e).getUint16(t,!0),put:(e,t,r)=>(hi(e).setUint16(t,r,!0),t+2)},fi={len:2,get:(e,t)=>hi(e).getUint16(t),put:(e,t,r)=>(hi(e).setUint16(t,r),t+2)},yi={len:4,get:(e,t)=>hi(e).getUint32(t,!0),put:(e,t,r)=>(hi(e).setUint32(t,r,!0),t+4)},bi={len:4,get:(e,t)=>hi(e).getUint32(t),put:(e,t,r)=>(hi(e).setUint32(t,r),t+4)},wi={len:4,get:(e,t)=>hi(e).getInt32(t),put:(e,t,r)=>(hi(e).setInt32(t,r),t+4)},Ii={len:8,get:(e,t)=>hi(e).getBigUint64(t,!0),put:(e,t,r)=>(hi(e).setBigUint64(t,r,!0),t+8)};class Ti{constructor(e,t){if(this.len=e,t&&"windows-1252"===t.toLowerCase())this.decoder=Ti.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):Ti.win1252Map[i-128]}return t}}Ti.win1252Map="€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ";class Si extends Error{constructor(){super("End-Of-Stream"),this.name="EndOfStreamError"}}class ki extends Error{constructor(e="The operation was aborted"){super(e),this.name="AbortError"}}class Ei{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 Si;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 o=Math.min(i.length,t);e.set(i.subarray(0,o),r),r+=o,t-=o,o<i.length&&this.peekQueue.push(i.subarray(o))}return r}async readRemainderFromStream(e,t){let r=0;for(;r<e.length&&!this.endOfStream;){if(this.interrupted)throw new ki;const i=await this.readFromStream(e.subarray(r),t);if(0===i)break;r+=i}if(!t&&r<e.length)throw new Si;return r}}class Ai extends Ei{constructor(e){super(),this.reader=e}async abort(){return this.close()}async close(){this.reader.releaseLock()}}class vi 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 Ci extends Ei{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 Si;return r}abort(){return this.interrupted=!0,this.reader.cancel()}async close(){await this.abort(),this.reader.releaseLock()}}class xi{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 Si;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 Si;return e.get(r,0)}async readNumber(e){if(await this.readBuffer(this.numBuffer,{length:e.len})<e.len)throw new Si;return e.get(this.numBuffer,0)}async peekNumber(e){if(await this.peekBuffer(this.numBuffer,{length:e.len})<e.len)throw new Si;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 Ri extends xi{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 o=await this.streamReader.read(e.subarray(0,r.length),r.mayBeLess);if(this.position+=o,(!t||!t.mayBeLess)&&o<r.length)throw new Si;return o}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 o=new Uint8Array(r.length+t);return i=await this.peekBuffer(o,{mayBeLess:r.mayBeLess}),e.set(o.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(o){if((null==t?void 0:t.mayBeLess)&&o instanceof Si)return 0;throw o}if(!r.mayBeLess&&i<r.length)throw new Si}return i}async ignore(e){const t=Math.min(256e3,e),r=new Uint8Array(t);let i=0;for(;i<e;){const o=e-i,n=await this.readBuffer(r,{length:Math.min(t,o)});if(n<0)return n;i+=n}return i}abort(){return this.streamReader.abort()}async close(){return this.streamReader.close()}supportsRandomAccess(){return!1}}class Ni extends xi{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 Si;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 _i(e,t){const r=function(e){try{const t=e.getReader({mode:"byob"});return t instanceof ReadableStreamDefaultReader?new Ci(t):new vi(t)}catch(t){if(t instanceof TypeError)return new Ci(e.getReader());throw t}}(e),i=t??{},o=i.onClose;return i.onClose=async()=>{if(await r.close(),o)return o()},new Ri(r,i)}var Pi=Uint8Array,Fi=Uint16Array,Oi=Int32Array,zi=new Pi([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]),Di=new Pi([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]),Bi=new Pi([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Mi=function(e,t){for(var r=new Fi(31),i=0;i<31;++i)r[i]=t+=1<<e[i-1];var o=new Oi(r[30]);for(i=1;i<30;++i)for(var n=r[i];n<r[i+1];++n)o[n]=n-r[i]<<5|i;return{b:r,r:o}},Ui=Mi(zi,2),Li=Ui.b,Ki=Ui.r;Li[28]=258,Ki[258]=28;for(var $i=Mi(Di,0).b,Hi=new Fi(32768),qi=0;qi<32768;++qi){var ji=(43690&qi)>>1|(21845&qi)<<1;ji=(61680&(ji=(52428&ji)>>2|(13107&ji)<<2))>>4|(3855&ji)<<4,Hi[qi]=((65280&ji)>>8|(255&ji)<<8)>>1}var Wi=function(e,t,r){for(var i=e.length,o=0,n=new Fi(t);o<i;++o)e[o]&&++n[e[o]-1];var s,a=new Fi(t);for(o=1;o<t;++o)a[o]=a[o-1]+n[o-1]<<1;s=new Fi(1<<t);var c=15-t;for(o=0;o<i;++o)if(e[o])for(var l=o<<4|e[o],d=t-e[o],u=a[e[o]-1]++<<d,p=u|(1<<d)-1;u<=p;++u)s[Hi[u]>>c]=l;return s},Vi=new Pi(288);for(qi=0;qi<144;++qi)Vi[qi]=8;for(qi=144;qi<256;++qi)Vi[qi]=9;for(qi=256;qi<280;++qi)Vi[qi]=7;for(qi=280;qi<288;++qi)Vi[qi]=8;var Gi=new Pi(32);for(qi=0;qi<32;++qi)Gi[qi]=5;var Ji=Wi(Vi,9),Yi=Wi(Gi,5),Xi=function(e){for(var t=e[0],r=1;r<e.length;++r)e[r]>t&&(t=e[r]);return t},Zi=function(e,t,r){var i=t/8|0;return(e[i]|e[i+1]<<8)>>(7&t)&r},Qi=function(e,t){var r=t/8|0;return(e[r]|e[r+1]<<8|e[r+2]<<16)>>(7&t)},eo=function(e){return(e+7)/8|0},to=["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"],ro=function(e,t,r){var i=new Error(t||to[e]);if(i.code=e,Error.captureStackTrace&&Error.captureStackTrace(i,ro),!r)throw i;return i},io=function(e,t,r,i){var o=e.length;if(!o||t.f&&!t.l)return r||new Pi(0);var n=!r,s=n||2!=t.i,a=t.i;n&&(r=new Pi(3*o));var c=function(e){var t=r.length;if(e>t){var i=new Pi(Math.max(2*t,e));i.set(r),r=i}},l=t.f||0,d=t.p||0,u=t.b||0,p=t.l,h=t.d,g=t.m,m=t.n,f=8*o;do{if(!p){l=Zi(e,d,1);var y=Zi(e,d+1,3);if(d+=3,!y){var b=e[(R=eo(d)+4)-4]|e[R-3]<<8,w=R+b;if(w>o){a&&ro(0);break}s&&c(u+b),r.set(e.subarray(R,w),u),t.b=u+=b,t.p=d=8*w,t.f=l;continue}if(1==y)p=Ji,h=Yi,g=9,m=5;else if(2==y){var I=Zi(e,d,31)+257,T=Zi(e,d+10,15)+4,S=I+Zi(e,d+5,31)+1;d+=14;for(var k=new Pi(S),E=new Pi(19),A=0;A<T;++A)E[Bi[A]]=Zi(e,d+3*A,7);d+=3*T;var v=Xi(E),C=(1<<v)-1,x=Wi(E,v);for(A=0;A<S;){var R,N=x[Zi(e,d,C)];if(d+=15&N,(R=N>>4)<16)k[A++]=R;else{var _=0,P=0;for(16==R?(P=3+Zi(e,d,3),d+=2,_=k[A-1]):17==R?(P=3+Zi(e,d,7),d+=3):18==R&&(P=11+Zi(e,d,127),d+=7);P--;)k[A++]=_}}var F=k.subarray(0,I),O=k.subarray(I);g=Xi(F),m=Xi(O),p=Wi(F,g),h=Wi(O,m)}else ro(1);if(d>f){a&&ro(0);break}}s&&c(u+131072);for(var z=(1<<g)-1,D=(1<<m)-1,B=d;;B=d){var M=(_=p[Qi(e,d)&z])>>4;if((d+=15&_)>f){a&&ro(0);break}if(_||ro(2),M<256)r[u++]=M;else{if(256==M){B=d,p=null;break}var U=M-254;if(M>264){var L=zi[A=M-257];U=Zi(e,d,(1<<L)-1)+Li[A],d+=L}var K=h[Qi(e,d)&D],$=K>>4;K||ro(3),d+=15&K;O=$i[$];if($>3){L=Di[$];O+=Qi(e,d)&(1<<L)-1,d+=L}if(d>f){a&&ro(0);break}s&&c(u+131072);var H=u+U;if(u<O){var q=0-O,j=Math.min(O,H);for(q+u<0&&ro(3);u<j;++u)r[u]=i[q+u]}for(;u<H;++u)r[u]=r[u-O]}}t.l=p,t.p=B,t.b=u,t.f=l,p&&(l=1,t.m=g,t.d=h,t.n=m)}while(!l);return u!=r.length&&n?function(e,t,r){return(null==r||r>e.length)&&(r=e.length),new Pi(e.subarray(t,r))}(r,0,u):r.subarray(0,u)},oo=new Pi(0);function no(e,t){var r,i,o=function(e){31==e[0]&&139==e[1]&&8==e[2]||ro(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 o+8>e.length&&ro(6,"invalid gzip data"),io(e.subarray(o,-8),{i:2},new Pi((i=(r=e).length,(r[i-4]|r[i-3]<<8|r[i-2]<<16|r[i-1]<<24)>>>0)),t)}function so(e,t){return io(e.subarray(((8!=(15&(r=e)[0])||r[0]>>4>7||(r[0]<<8|r[1])%31)&&ro(6,"invalid zlib data"),1==(r[1]>>5&1)&&ro(6,"invalid zlib data: "+(32&r[1]?"need":"unexpected")+" dictionary"),2+(r[1]>>3&4)),-4),{i:2},t,t);var r}function ao(e,t){return 31==e[0]&&139==e[1]&&8==e[2]?no(e,t):8!=(15&e[0])||e[0]>>4>7||(e[0]<<8|e[1])%31?function(e,t){return io(e,{i:2},t,t)}(e,t):so(e,t)}var co="undefined"!=typeof TextDecoder&&new TextDecoder;try{co.decode(oo,{stream:!0})}catch(dg){}var lo,uo,po,ho,go,mo={exports:{}};function fo(){if(uo)return lo;uo=1;var e=1e3,t=60*e,r=60*t,i=24*r,o=7*i,n=365.25*i;function s(e,t,r,i){var o=t>=1.5*r;return Math.round(e/r)+" "+i+(o?"s":"")}return lo=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*n;case"weeks":case"week":case"w":return c*o;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(o){var n=Math.abs(o);if(n>=i)return s(o,n,i,"day");if(n>=r)return s(o,n,r,"hour");if(n>=t)return s(o,n,t,"minute");if(n>=e)return s(o,n,e,"second");return o+" ms"}(a):function(o){var n=Math.abs(o);if(n>=i)return Math.round(o/i)+"d";if(n>=r)return Math.round(o/r)+"h";if(n>=t)return Math.round(o/t)+"m";if(n>=e)return Math.round(o/e)+"s";return o+"ms"}(a);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(a))}}var yo=(go||(go=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,o=0;t[0].replace(/%[a-zA-Z%]/g,e=>{"%%"!==e&&(i++,"%c"===e&&(o=i))}),t.splice(o,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!==Me&&"env"in Me&&(e=Me.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=(ho||(ho=1,po=function(e){function t(e){let i,o,n,s=null;function a(...e){if(!a.enabled)return;const r=a,o=Number(new Date),n=o-(i||o);r.diff=n,r.prev=i,r.curr=o,i=o,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,o)=>{if("%%"===i)return"%";s++;const n=t.formatters[o];if("function"==typeof n){const t=e[s];i=n.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:(o!==t.namespaces&&(o=t.namespaces,n=t.enabled(e)),n),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,o=-1,n=0;for(;r<e.length;)if(i<t.length&&(t[i]===e[r]||"*"===t[i]))"*"===t[i]?(o=i,n=r,i++):(r++,i++);else{if(-1===o)return!1;i=o+1,n++,r=n}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=fo(),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}),po)(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}(mo,mo.exports)),mo.exports);const bo=pi(yo),wo=67324752,Io=134695760,To=33639248,So=101010256,ko={get:e=>(mi.get(e,6),{signature:yi.get(e,0),compressedSize:yi.get(e,8),uncompressedSize:yi.get(e,12)}),len:16},Eo={get(e){const t=mi.get(e,6);return{signature:yi.get(e,0),minVersion:mi.get(e,4),dataDescriptor:!!(8&t),compressedMethod:mi.get(e,8),compressedSize:yi.get(e,18),uncompressedSize:yi.get(e,22),filenameLength:mi.get(e,26),extraFieldLength:mi.get(e,28),filename:null}},len:30},Ao={get:e=>({signature:yi.get(e,0),nrOfThisDisk:mi.get(e,4),nrOfThisDiskWithTheStart:mi.get(e,6),nrOfEntriesOnThisDisk:mi.get(e,8),nrOfEntriesOfSize:mi.get(e,10),sizeOfCd:yi.get(e,12),offsetOfStartOfCd:yi.get(e,16),zipFileCommentLength:mi.get(e,20)}),len:22},vo={get(e){const t=mi.get(e,8);return{signature:yi.get(e,0),minVersion:mi.get(e,6),dataDescriptor:!!(8&t),compressedMethod:mi.get(e,10),compressedSize:yi.get(e,20),uncompressedSize:yi.get(e,24),filenameLength:mi.get(e,28),extraFieldLength:mi.get(e,30),fileCommentLength:mi.get(e,32),relativeOffsetOfLocalHeader:yi.get(e,42),filename:null}},len:46};function Co(e){const t=new Uint8Array(yi.len);return yi.put(t,0,e),t}const xo=bo("tokenizer:inflate"),Ro=262144,No=Co(Io),_o=Co(So);class Po{constructor(e){this.tokenizer=e,this.syncBuffer=new Uint8Array(Ro)}async isZip(){return await this.peekSignature()===wo}peekSignature(){return this.tokenizer.peekToken(yi)}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]===_o[0]&&r[i+1]===_o[1]&&r[i+2]===_o[2]&&r[i+3]===_o[3])return e.fileInfo.size-t+i;return-1}async readCentralDirectory(){if(!this.tokenizer.supportsRandomAccess())return void xo("Cannot reading central-directory without random-read support");xo("Reading central-directory...");const e=this.tokenizer.position,t=await this.findEndOfCentralDirectoryLocator();if(t>0){xo("Central-directory 32-bit signature found");const r=await this.tokenizer.readToken(Ao,t),i=[];this.tokenizer.setPosition(r.offsetOfStartOfCd);for(let e=0;e<r.nrOfEntriesOfSize;++e){const t=await this.tokenizer.readToken(vo);if(t.signature!==To)throw new Error("Expected Central-File-Header signature");t.filename=await this.tokenizer.readToken(new Ti(t.filenameLength,"utf-8")),await this.tokenizer.ignore(t.extraFieldLength),await this.tokenizer.ignore(t.fileCommentLength),i.push(t),xo(`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 o;if(r=!!i.stop,await this.tokenizer.ignore(t.extraFieldLength),t.dataDescriptor&&0===t.compressedSize){const e=[];let r=Ro;xo("Compressed-file-size unknown, scanning for next data-descriptor-signature....");let o=-1;for(;o<0&&r===Ro;){r=await this.tokenizer.peekBuffer(this.syncBuffer,{mayBeLess:!0}),o=Fo(this.syncBuffer.subarray(0,r),No);const t=o>=0?o:r;if(i.handler){const r=new Uint8Array(t);await this.tokenizer.readBuffer(r),e.push(r)}else await this.tokenizer.ignore(t)}xo(`Found data-descriptor-signature at pos=${this.tokenizer.position}`),i.handler&&await this.inflate(t,Oo(e),i.handler)}else i.handler?(xo(`Reading compressed-file-data: ${t.compressedSize} bytes`),o=new Uint8Array(t.compressedSize),await this.tokenizer.readBuffer(o),await this.inflate(t,o,i.handler)):(xo(`Ignoring compressed-file-data: ${t.compressedSize} bytes`),await this.tokenizer.ignore(t.compressedSize));if(xo(`Reading data-descriptor at pos=${this.tokenizer.position}`),t.dataDescriptor){if(134695760!==(await this.tokenizer.readToken(ko)).signature)throw new Error("Expected data-descriptor-signature at position "+(this.tokenizer.position-ko.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);xo(`Decompress filename=${e.filename}, compressed-size=${t.length}`);return r(ao(t))}async readLocalFileHeader(){const e=await this.tokenizer.peekToken(yi);if(e===wo){const e=await this.tokenizer.readToken(Eo);return e.filename=await this.tokenizer.readToken(new Ti(e.filenameLength,"utf-8")),e}if(e===To)return!1;if(3759263696===e)throw new Error("Encrypted ZIP");throw new Error("Unexpected signature")}}function Fo(e,t){const r=e.length,i=t.length;if(i>r)return-1;for(let o=0;o<=r-i;o++){let r=!0;for(let n=0;n<i;n++)if(e[o+n]!==t[n]){r=!1;break}if(r)return o}return-1}function Oo(e){const t=e.reduce((e,t)=>e+t.length,0),r=new Uint8Array(t);let i=0;for(const o of e)r.set(o,i),i+=o.length;return r}function zo(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 Do={get:(e,t)=>127&e[t+3]|e[t+2]<<7|e[t+1]<<14|e[t]<<21,len:4},Bo=4100;function Mo(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 Uo(e,t,r){r={offset:0,...r};for(const[i,o]of t.entries())if(r.mask){if(o!==(r.mask[i]&e[i+r.offset]))return!1}else if(o!==e[i+r.offset])return!1;return!0}class Lo{constructor(e){ae(this,"detectConfident",async e=>{if(this.buffer=new Uint8Array(Bo),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(Do);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 Po(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=Mo(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=Mo(e))}else{t=t.slice(0,Math.max(0,i));const e=t.lastIndexOf('"'),o=t.slice(Math.max(0,e+1));r=Mo(o)}},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),Uo(i,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/ogg; codecs=opus"}:Uo(i,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:Uo(i,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:Uo(i,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:Uo(i,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:Uo(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 o=await this.readTiffHeader(!1);if(o)return o}if(this.check([77,77])){const n=await this.readTiffHeader(!0);if(n)return n}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(gi);let r=128,i=0;for(;0===(t&r)&&0!==r;)++i,r>>=1;const o=new Uint8Array(i+1);return await e.readBuffer(o),o}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),o=new DataView(t.buffer,t.length-r,r);return{id:zo(i),len:zo(o)}}async function c(t){for(;t>0;){const r=await a();if(17026===r.id){return(await e.readToken(new Ti(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 d=new Ti(4,"latin1").get(this.buffer,2);if(d.match("^d*")&&d>=1e3&&d<=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 Ti(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 u(){return{length:await e.readToken(wi),type:await e.readToken(new Ti(4,"latin1"))}}await e.ignore(8);do{const p=await u();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 Ti(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(Ii))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){const m=await g();let f=m.size-24;if(Uo(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),Uo(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(Uo(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 Ti(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 Ti(6).get(e,148).replace(/\0.*$/,"").trim(),8);if(Number.isNaN(r))return!1;let i=256;for(let o=t;o<t+148;o++)i+=e[o];for(let o=t+156;o<t+512;o++)i+=e[o];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)}),ae(this,"detectImprecise",async e=>{if(this.buffer=new Uint8Array(Bo),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 Ni(r,i)))}async fromBlob(e){return this.fromStream(e.stream())}async fromStream(e){const t=await _i(e,this.tokenizerOptions);try{return await this.fromTokenizer(t)}finally{await t.close()}}async toDetectionStream(e,t){const{sampleSize:r=Bo}=t;let i,o;const n=e.getReader({mode:"byob"});try{const{value:e,done:t}=await n.read(new Uint8Array(r));if(o=e,!t&&e)try{i=await this.fromBuffer(e.subarray(0,r))}catch(c){if(!(c instanceof Si))throw c;i=void 0}o=e}finally{n.releaseLock()}const s=new TransformStream({async start(e){e.enqueue(o)},transform(e,t){t.enqueue(e)}}),a=e.pipeThrough(s);return a.fileType=i,a}check(e,t){return Uo(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?fi:mi);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?fi:mi);for(let r=0;r<t;++r){const t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){const t=(e?fi:mi).get(this.buffer,2),r=(e?bi:yi).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?fi:mi).get(this.buffer,8),r=(e?fi:mi).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 Ko=Object.create(null);Ko.open="0",Ko.close="1",Ko.ping="2",Ko.pong="3",Ko.message="4",Ko.upgrade="5",Ko.noop="6";const $o=Object.create(null);Object.keys(Ko).forEach(e=>{$o[Ko[e]]=e});const Ho={type:"error",data:"parser error"},qo="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),jo="function"==typeof ArrayBuffer,Wo=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,Vo=({type:e,data:t},r,i)=>qo&&t instanceof Blob?r?i(t):Go(t,i):jo&&(t instanceof ArrayBuffer||Wo(t))?r?i(t):Go(new Blob([t]),i):i(Ko[e]+(t||"")),Go=(e,t)=>{const r=new FileReader;return r.onload=function(){const e=r.result.split(",")[1];t("b"+(e||""))},r.readAsDataURL(e)};function Jo(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let Yo;const Xo="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Zo="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let pg=0;pg<64;pg++)Zo[Xo.charCodeAt(pg)]=pg;const Qo="function"==typeof ArrayBuffer,en=(e,t)=>{if("string"!=typeof e)return{type:"message",data:rn(e,t)};const r=e.charAt(0);if("b"===r)return{type:"message",data:tn(e.substring(1),t)};return $o[r]?e.length>1?{type:$o[r],data:e.substring(1)}:{type:$o[r]}:Ho},tn=(e,t)=>{if(Qo){const r=(e=>{let t,r,i,o,n,s=.75*e.length,a=e.length,c=0;"="===e[e.length-1]&&(s--,"="===e[e.length-2]&&s--);const l=new ArrayBuffer(s),d=new Uint8Array(l);for(t=0;t<a;t+=4)r=Zo[e.charCodeAt(t)],i=Zo[e.charCodeAt(t+1)],o=Zo[e.charCodeAt(t+2)],n=Zo[e.charCodeAt(t+3)],d[c++]=r<<2|i>>4,d[c++]=(15&i)<<4|o>>2,d[c++]=(3&o)<<6|63&n;return l})(e);return rn(r,t)}return{base64:!0,data:e}},rn=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,on=String.fromCharCode(30);function nn(){return new TransformStream({transform(e,t){!function(e,t){qo&&e.data instanceof Blob?e.data.arrayBuffer().then(Jo).then(t):jo&&(e.data instanceof ArrayBuffer||Wo(e.data))?t(Jo(e.data)):Vo(e,!1,e=>{Yo||(Yo=new TextEncoder),t(Yo.encode(e))})}(e,r=>{const i=r.length;let o;if(i<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,i);else if(i<65536){o=new Uint8Array(3);const e=new DataView(o.buffer);e.setUint8(0,126),e.setUint16(1,i)}else{o=new Uint8Array(9);const e=new DataView(o.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(i))}e.data&&"string"!=typeof e.data&&(o[0]|=128),t.enqueue(o),t.enqueue(r)})}})}let sn;function an(e){return e.reduce((e,t)=>e+t.length,0)}function cn(e,t){if(e[0].length===t)return e.shift();const r=new Uint8Array(t);let i=0;for(let o=0;o<t;o++)r[o]=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 ln(e){if(e)return function(e){for(var t in ln.prototype)e[t]=ln.prototype[t];return e}(e)}ln.prototype.on=ln.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},ln.prototype.once=function(e,t){function r(){this.off(e,r),t.apply(this,arguments)}return r.fn=t,this.on(e,r),this},ln.prototype.off=ln.prototype.removeListener=ln.prototype.removeAllListeners=ln.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 o=0;o<i.length;o++)if((r=i[o])===t||r.fn===t){i.splice(o,1);break}return 0===i.length&&delete this._callbacks["$"+e],this},ln.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 o=(r=r.slice(0)).length;i<o;++i)r[i].apply(this,t)}return this},ln.prototype.emitReserved=ln.prototype.emit,ln.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},ln.prototype.hasListeners=function(e){return!!this.listeners(e).length};const dn="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),un="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function pn(e,...t){return t.reduce((t,r)=>(e.hasOwnProperty(r)&&(t[r]=e[r]),t),{})}const hn=un.setTimeout,gn=un.clearTimeout;function mn(e,t){t.useNativeTimers?(e.setTimeoutFn=hn.bind(un),e.clearTimeoutFn=gn.bind(un)):(e.setTimeoutFn=un.setTimeout.bind(un),e.clearTimeoutFn=un.clearTimeout.bind(un))}function fn(e){return"string"==typeof e?function(e){let t=0,r=0;for(let i=0,o=e.length;i<o;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 yn(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class bn extends Error{constructor(e,t,r){super(e),this.description=t,this.context=r,this.type="TransportError"}}class wn extends ln{constructor(e){super(),this.writable=!1,mn(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 bn(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=en(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 In extends wn{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(on),i=[];for(let o=0;o<r.length;o++){const e=en(r[o],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 o=0;e.forEach((e,n)=>{Vo(e,!1,e=>{i[n]=e,++o===r&&t(i.join(on))})})})(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]=yn()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let Tn=!1;try{Tn="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(ug){}const Sn=Tn;function kn(){}class En extends In{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 An=class e extends ln{constructor(e,t,r){super(),this.createRequest=e,mn(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=pn(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(dg){}if("POST"===this._method)try{i.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(dg){}try{i.setRequestHeader("Accept","*/*")}catch(dg){}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(dg){return void this.setTimeoutFn(()=>{this._onError(dg)},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=kn,t)try{this._xhr.abort()}catch(dg){}"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(An.requestsCount=0,An.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",vn);else if("function"==typeof addEventListener){addEventListener("onpagehide"in un?"pagehide":"unload",vn,!1)}function vn(){for(let e in An.requests)An.requests.hasOwnProperty(e)&&An.requests[e].abort()}const Cn=function(){const e=xn({xdomain:!1});return e&&null!==e.responseType}();function xn(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||Sn))return new XMLHttpRequest}catch(dg){}if(!t)try{return new(un[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(dg){}}const Rn="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class Nn extends wn{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,r=Rn?{}:pn(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(ug){return this.emitReserved("error",ug)}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;Vo(r,this.supportsBinary,e=>{try{this.doWrite(r,e)}catch(dg){}i&&dn(()=>{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]=yn()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const _n=un.WebSocket||un.MozWebSocket;const Pn={websocket:class extends Nn{createSocket(e,t,r){return Rn?new _n(e,t,r):t?new _n(e,t):new _n(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends wn{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(ug){return this.emitReserved("error",ug)}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){sn||(sn=new TextDecoder);const r=[];let i=0,o=-1,n=!1;return new TransformStream({transform(s,a){for(r.push(s);;){if(0===i){if(an(r)<1)break;const e=cn(r,1);n=!(128&~e[0]),o=127&e[0],i=o<126?3:126===o?1:2}else if(1===i){if(an(r)<2)break;const e=cn(r,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),i=3}else if(2===i){if(an(r)<8)break;const e=cn(r,8),t=new DataView(e.buffer,e.byteOffset,e.length),n=t.getUint32(0);if(n>Math.pow(2,21)-1){a.enqueue(Ho);break}o=n*Math.pow(2,32)+t.getUint32(4),i=3}else{if(an(r)<o)break;const e=cn(r,o);a.enqueue(en(n?e:sn.decode(e),t)),i=0}if(0===o||o>e){a.enqueue(Ho);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),r=e.readable.pipeThrough(t).getReader(),i=nn();i.readable.pipeTo(e.writable),this._writer=i.writable.getWriter();const o=()=>{r.read().then(({done:e,value:t})=>{e||(this.onPacket(t),o())}).catch(e=>{})};o();const n={type:"open"};this.query.sid&&(n.data=`{"sid":"${this.query.sid}"}`),this._writer.write(n).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&&dn(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends En{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=Cn&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new An(xn,this.uri(),e)}}},Fn=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,On=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function zn(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 o=Fn.exec(e||""),n={},s=14;for(;s--;)n[On[s]]=o[s]||"";return-1!=r&&-1!=i&&(n.source=t,n.host=n.host.substring(1,n.host.length-1).replace(/;/g,":"),n.authority=n.authority.replace("[","").replace("]","").replace(/;/g,":"),n.ipv6uri=!0),n.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,n.path),n.queryKey=function(e,t){const r={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,i){t&&(r[t]=i)}),r}(0,n.query),n}const Dn="function"==typeof addEventListener&&"function"==typeof removeEventListener,Bn=[];Dn&&addEventListener("offline",()=>{Bn.forEach(e=>e())},!1);class Mn extends ln{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=zn(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=zn(t.host).host);mn(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,o=r.length;i<o;i++){let e=r[i].split("=");t[decodeURIComponent(e[0])]=decodeURIComponent(e[1])}return t}(this.opts.query)),Dn&&(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"})},Bn.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&&Mn.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",Mn.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+=fn(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,dn(()=>{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 o={type:e,data:t,options:r};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),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(Mn.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(),Dn&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=Bn.indexOf(this._offlineEventListener);-1!==e&&Bn.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}Mn.protocol=4;class Un extends Mn{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;Mn.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;Mn.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 o(){r||(r=!0,l(),t.close(),t=null)}const n=e=>{const r=new Error("probe error: "+e);r.transport=t.name,o(),this.emitReserved("upgradeError",r)};function s(){n("transport closed")}function a(){n("socket closed")}function c(e){t&&e.name!==t.name&&o()}const l=()=>{t.removeListener("open",i),t.removeListener("error",n),t.removeListener("close",s),this.off("close",a),this.off("upgrading",c)};t.once("open",i),t.once("error",n),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 Ln=class extends Un{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=>Pn[e]).filter(e=>!!e)),super(e,r)}};const Kn="function"==typeof ArrayBuffer,$n=Object.prototype.toString,Hn="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===$n.call(Blob),qn="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===$n.call(File);function jn(e){return Kn&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||Hn&&e instanceof Blob||qn&&e instanceof File}function Wn(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,r=e.length;t<r;t++)if(Wn(e[t]))return!0;return!1}if(jn(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return Wn(e.toJSON(),!0);for(const r in e)if(Object.prototype.hasOwnProperty.call(e,r)&&Wn(e[r]))return!0;return!1}function Vn(e){const t=[],r=e.data,i=e;return i.data=Gn(r,t),i.attachments=t.length,{packet:i,buffers:t}}function Gn(e,t){if(!e)return e;if(jn(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]=Gn(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]=Gn(e[i],t));return r}return e}function Jn(e,t){return e.data=Yn(e.data,t),delete e.attachments,e}function Yn(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]=Yn(e[r],t);else if("object"==typeof e)for(const r in e)Object.prototype.hasOwnProperty.call(e,r)&&(e[r]=Yn(e[r],t));return e}const Xn=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var Zn,Qn;(Qn=Zn||(Zn={}))[Qn.CONNECT=0]="CONNECT",Qn[Qn.DISCONNECT=1]="DISCONNECT",Qn[Qn.EVENT=2]="EVENT",Qn[Qn.ACK=3]="ACK",Qn[Qn.CONNECT_ERROR=4]="CONNECT_ERROR",Qn[Qn.BINARY_EVENT=5]="BINARY_EVENT",Qn[Qn.BINARY_ACK=6]="BINARY_ACK";function es(e){return"[object Object]"===Object.prototype.toString.call(e)}class ts extends ln{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===Zn.BINARY_EVENT;r||t.type===Zn.BINARY_ACK?(t.type=r?Zn.EVENT:Zn.ACK,this.reconstructor=new rs(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!jn(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===Zn[r.type])throw new Error("unknown packet type "+r.type);if(r.type===Zn.BINARY_EVENT||r.type===Zn.BINARY_ACK){const i=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const o=e.substring(i,t);if(o!=Number(o)||"-"!==e.charAt(t))throw new Error("Illegal attachments");r.attachments=Number(o)}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(!ts.isPayloadValid(r.type,i))throw new Error("invalid payload");r.data=i}return r}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(dg){return!1}}static isPayloadValid(e,t){switch(e){case Zn.CONNECT:return es(t);case Zn.DISCONNECT:return void 0===t;case Zn.CONNECT_ERROR:return"string"==typeof t||es(t);case Zn.EVENT:case Zn.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===Xn.indexOf(t[0]));case Zn.ACK:case Zn.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class rs{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=Jn(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const is=Object.freeze(Object.defineProperty({__proto__:null,Decoder:ts,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==Zn.EVENT&&e.type!==Zn.ACK||!Wn(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===Zn.EVENT?Zn.BINARY_EVENT:Zn.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==Zn.BINARY_EVENT&&e.type!==Zn.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=Vn(e),r=this.encodeAsString(t.packet),i=t.buffers;return i.unshift(r),i}},get PacketType(){return Zn},protocol:5},Symbol.toStringTag,{value:"Module"}));function os(e,t,r){return e.on(t,r),function(){e.off(t,r)}}const ns=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class ss extends ln{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=[os(e,"open",this.onopen.bind(this)),os(e,"packet",this.onpacket.bind(this)),os(e,"error",this.onerror.bind(this)),os(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,o;if(ns.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 n={type:Zn.EVENT,data:t,options:{}};if(n.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,r=t.pop();this._registerAckCallback(e,r),n.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===(o=this.io.engine)||void 0===o?void 0:o._hasPingExpired());return this.flags.volatile&&!s||(a?(this.notifyOutgoingListeners(n),this.packet(n)):this.sendBuffer.push(n)),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 o=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),n=(...e)=>{this.io.clearTimeoutFn(o),t.apply(this,e)};n.withError=!0,this.acks[e]=n}emitWithAck(e,...t){return new Promise((r,i)=>{const o=(e,t)=>e?i(e):r(t);o.withError=!0,t.push(o),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:Zn.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 Zn.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 Zn.EVENT:case Zn.BINARY_EVENT:this.onevent(e);break;case Zn.ACK:case Zn.BINARY_ACK:this.onack(e);break;case Zn.DISCONNECT:this.ondisconnect();break;case Zn.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:Zn.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:Zn.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 as(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}as.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)},as.prototype.reset=function(){this.attempts=0},as.prototype.setMin=function(e){this.ms=e},as.prototype.setMax=function(e){this.max=e},as.prototype.setJitter=function(e){this.jitter=e};class cs extends ln{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,mn(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 as({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||is;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 Ln(this.uri,this.opts);const t=this.engine,r=this;this._readyState="opening",this.skipReconnect=!1;const i=os(t,"open",function(){r.onopen(),e&&e()}),o=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},n=os(t,"error",o);if(!1!==this._timeout){const e=this._timeout,r=this.setTimeoutFn(()=>{i(),o(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(n),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(os(e,"ping",this.onping.bind(this)),os(e,"data",this.ondata.bind(this)),os(e,"error",this.onerror.bind(this)),os(e,"close",this.onclose.bind(this)),os(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(dg){this.onclose("parse error",dg)}}ondecoded(e){dn(()=>{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 ss(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 ls={};function ds(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=zn(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 o=-1!==i.host.indexOf(":")?"["+i.host+"]":i.host;return i.id=i.protocol+"://"+o+":"+i.port+t,i.href=i.protocol+"://"+o+(r&&r.port===i.port?"":":"+i.port),i}(e,(t=t||{}).path||"/socket.io"),i=r.source,o=r.id,n=r.path,s=ls[o]&&n in ls[o].nsps;let a;return t.forceNew||t["force new connection"]||!1===t.multiplex||s?a=new cs(i,t):(ls[o]||(ls[o]=new cs(i,t)),a=ls[o]),r.query&&!t.query&&(t.query=r.queryKey),a.socket(r.path,t)}Object.assign(ds,{Manager:cs,Socket:ss,io:ds,connect:ds});const us=class e{constructor(e){if(ae(this,"client"),ae(this,"config"),ae(this,"logger",ci.getInstance()),ae(this,"socket",null),ae(this,"socketConnected",!1),ae(this,"connectionMode","auto"),ae(this,"wsBaseUrl",null),this.config=e,!e.apiKey)throw new li("API key is required");if(!e.network)throw new li("Network is required");const t={"x-api-key":e.apiKey,"Content-Type":"application/json"};this.client=qr.create({baseURL:"https://v2-api.tier.bot/api",headers:t}),this.logger=ci.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 qr.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 li("Unable to fetch file metadata")}}getMimeType(t){const r=t.toLowerCase().split(".").pop();if(!r)throw new li("File must have an extension");const i=e.VALID_MIME_TYPES[r];if(!i)throw new li(`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 li("holderId is required");if(!e.VALID_MODES.includes(t.mode))throw new li(`Invalid mode: ${t.mode}. Must be one of: ${e.VALID_MODES.join(", ")}`);if("hashinal"===t.mode&&!t.jsonFileURL&&!t.metadataObject)throw new li("Hashinal mode requires either jsonFileURL or metadataObject");if(t.onlyJSONCollection&&"hashinal-collection"!==t.mode)throw new li("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 li("Base64 data is required");const r=t.base64.replace(/^data:.*?;base64,/,"");if(Math.ceil(.75*r.length)>e.MAX_BASE64_SIZE)throw new li(`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 li("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 li("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=we.from(t,"base64"),i=await async function(e,t){return new Lo(t).fromBuffer(e)}(r);return(null==i?void 0:i.mime)||"application/octet-stream"}catch(ug){return this.logger.warn("Failed to detect MIME type from buffer"),"application/octet-stream"}}async startInscription(t){var r,i;try{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 li(`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 li("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};let o;return o="url"===t.file.type?await this.client.post("/inscriptions/start-inscription",{...i,fileURL:t.file.url}):await this.client.post("/inscriptions/start-inscription",{...i,fileBase64:t.file.base64,fileName:t.file.fileName,fileMimeType:r||this.getMimeType(t.file.fileName)}),o.data}catch(o){if(o instanceof li)throw o;if(qr.isAxiosError(o))throw new Error((null==(i=null==(r=o.response)?void 0:r.data)?void 0:i.message)||"Failed to start inscription");throw o}}async executeTransaction(e,t){var r,o;try{const n="mainnet"===t.network?i.Client.forMainnet():i.Client.forTestnet(),a=new s.HederaMirrorNode(t.network),c=await a.requestAccount(t.accountId),l=null==(r=null==c?void 0:c.key)?void 0:r._type,d="string"==typeof t.privateKey;let u;if(l&&d)u=(null==(o=null==l?void 0:l.toLowerCase())?void 0:o.includes("ecdsa"))?i.PrivateKey.fromStringECDSA(t.privateKey):i.PrivateKey.fromStringED25519(t.privateKey);else if(!l&&d){const e=d?s.detectKeyTypeFromString(t.privateKey):void 0;u="ed25519"===(null==e?void 0:e.detectedType)?i.PrivateKey.fromStringED25519(t.privateKey):i.PrivateKey.fromStringECDSA(t.privateKey)}else u=t.privateKey;n.setOperator(t.accountId,u);const p=i.TransferTransaction.fromBytes(we.from(e,"base64")),h=await p.sign(u),g=await h.execute(n),m=(await g.getReceipt(n)).status.toString();if("SUCCESS"!==m)throw new Error(`Transaction failed with status: ${m}`);return g.transactionId.toString()}catch(n){throw new Error(`Failed to execute transaction: ${n instanceof Error?n.message:"Unknown error"}`)}}async executeTransactionWithSigner(e,t){try{const r=i.TransferTransaction.fromBytes(we.from(e,"base64")),o=await r.executeWithSigner(t),n=(await o.getReceiptWithSigner(t)).status.toString();if("SUCCESS"!==n)throw new Error(`Transaction failed with status: ${n}`);return o.transactionId.toString()}catch(r){throw new Error(`Failed to execute transaction: ${r instanceof Error?r.message:"Unknown error"}`)}}async inscribeAndExecute(e,t,r,i){const o=(null==i?void 0:i.waitForCompletion)??!0,n=(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(d){throw this.logger.error("WebSocket inscription failed, falling back to HTTP:",d),d}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(o){r&&r({stage:"confirming",message:"Transaction executed, waiting for inscription to complete",progressPercent:5});const e=Math.floor(n/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=ds(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(dg){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,o)=>{if(!this.socket)return o(new Error("WebSocket not connected"));let n,s,a,c;const l=()=>{var e,t,r;c&&clearTimeout(c),null==(e=this.socket)||e.off("inscription-progress",p),null==(t=this.socket)||t.off("inscription-complete",d),null==(r=this.socket)||r.off("inscription-error",u)};c=setTimeout(()=>{this.logger.error("WebSocket inscription timeout after 60 seconds",{jobId:n,transactionId:s,lastTopicId:a}),l(),i({jobId:n,transactionId:s,topicId:a,topic_id:a,status:"timeout",completed:!1})},6e4);const d=e=>{l(),i({jobId:n,transactionId:s,topicId:e.topicId||e.topic_id,topic_id:e.topicId||e.topic_id,status:"completed",completed:!0})},u=e=>{l(),o(new Error(e.error||"Inscription failed"))},p=e=>{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:n,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",p),this.socket.on("inscription-complete",d),this.socket.on("inscription-error",u),this.socket.emit("start-inscription",{...e,network:this.config.network},async e=>{if(!e.success)return l(),o(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),n=e.jobId||e.tx_id,!n)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:n,transactionId:s})}catch(i){l(),o(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=ds(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=3,r=1e3){for(let o=0;o<t;o++)try{return await e()}catch(i){if(o===t-1)throw i;const e=r*Math.pow(2,o);await new Promise(t=>setTimeout(t,e)),this.logger.debug(`Retry attempt ${o+1}/${t} after ${e}ms delay`)}throw new Error("Retry operation failed")}async retrieveInscription(e){if(!e)throw new li("Transaction ID is required");try{return await this.retryWithBackoff(async()=>{const t=(await this.client.get(`/inscriptions/retrieve-inscription?id=${e}`)).data;return{...t,jobId:t.id}})}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 di(e).authenticate()}static async createWithAuth(t){const r="client"===t.type?new ui({...t,logger:ci.getInstance()}):new di(t),{apiKey:i}=await r.authenticate();return new e({apiKey:i,network:t.network||"mainnet",wsBaseUrl:t.wsBaseUrl,connectionMode:t.connectionMode||"websocket"})}async waitForInscription(e,t=30,r=4e3,i=!1,o){var n;let s=0,a=0;const c=(r,i,n,c)=>{if(o)try{a=Math.max(a,n),o({stage:r,message:i,progressPercent:a,details:{...c,txId:e,currentAttempt:s,maxAttempts:t}})}catch(ug){this.logger.warn(`Error in progress callback: ${ug}`)}};for(c("confirming","Starting inscription verification",0);s<t;){c("confirming",`Verifying inscription status (attempt ${s+1}/${t})`,5,{attempt:s+1});const o=await this.retrieveInscription(e);if(o.error)throw c("verifying",`Error: ${o.error}`,100,{error:o.error}),new Error(o.error);let a=5;void 0!==o.messages&&void 0!==o.maxMessages&&o.maxMessages>0?(a=Math.min(95,5+o.messages/o.maxMessages*90),o.completed&&(a=100)):"processing"===o.status?a=10:o.completed&&(a=100),c(o.completed?"completed":"confirming",o.completed?"Inscription completed successfully":`Processing inscription (${o.status})`,a,{status:o.status,messagesProcessed:o.messages,maxMessages:o.maxMessages,messageCount:o.messages,completed:o.completed,confirmedMessages:o.confirmedMessages,result:o});const l="hashinal"===o.mode,d="6"===(null==(n=o.fileStandard)?void 0:n.toString());if(l&&o.topic_id&&o.jsonTopicId&&(!i||o.completed))return c("completed","Inscription verification complete",100,{result:o}),o;if(!l&&!d&&o.topic_id&&(!i||o.completed))return c("completed","Inscription verification complete",100,{result:o}),o;if(d&&o.topic_id&&o.jsonTopicId&&o.registryTopicId&&(!i||o.completed))return c("completed","Inscription verification complete",100,{result:o}),o;await new Promise(e=>setTimeout(e,r)),s++}throw c("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 li("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),qr.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}}};ae(us,"VALID_MODES",["file","upload","hashinal","hashinal-collection"]),ae(us,"MAX_BASE64_SIZE",2097152),ae(us,"MAX_URL_FILE_SIZE",104857600),ae(us,"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 ps=us;class hs{constructor(e={}){this.module=e.module||"Progress",this.callback=e.callback,this.logger=e.logger||new B({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 hs.instance?(e.callback&&hs.instance.setCallback(e.callback),e.module&&hs.instance.setModule(e.module),e.logger&&hs.instance.setLogger(e.logger),void 0!==e.minPercent&&hs.instance.setMinPercent(e.minPercent),void 0!==e.maxPercent&&hs.instance.setMaxPercent(e.maxPercent)):hs.instance=new hs(e),hs.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 hs({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 o=t.message;r&&!o.startsWith(r)&&(o=`${r}: ${o}`),this.report({stage:t.stage,message:o,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),o=Date.now();if(i===this.lastReportedPercent&&o-this.lastReportedTime<this.throttleMs&&"completed"!==e.stage&&"failed"!==e.stage)return;this.lastReportedPercent=i,this.lastReportedTime=o;const n={...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(n)}catch(ug){this.logger.warn(`Error in progress callback: ${ug}`)}}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 gs 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,gs)}}const ms=(e,t)=>e.replace(/\{([^}]+)\}/g,(e,r)=>{const i=((e,t)=>{const r=t.split(".");let i=e;for(const o of r){if(null==i)return;i=i[o]}return i})(t,String(r).trim());return null==i?"(Unknown)":String(i)}),fs=e=>{const t=[],r=[];if(Array.isArray(e.transfers))for(const i of e.transfers){const e=parseFloat(i.amount);let o=i.amount;o.startsWith("-")&&(o=o.substring(1)),o=o.replace(/\s*ℏ$/,""),e<0?t.push(`${i.accountId} (${o} ℏ)`):e>0&&r.push(`${i.accountId} (${o} ℏ)`)}return t.length>0&&r.length>0?`Transfer of HBAR from ${t.join(", ")} to ${r.join(", ")}`:e.humanReadableType},ys=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},bs=e=>e.tokenMint?`Mint ${e.tokenMint.amount} tokens for token ${e.tokenMint.tokenId}`:e.humanReadableType,ws=e=>e.tokenBurn?`Burn ${e.tokenBurn.amount} tokens for token ${e.tokenBurn.tokenId}`:e.humanReadableType,Is=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},Ts=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},Ss=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},ks=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},Es=e=>e.fileAppend?`Append to File ${e.fileAppend.fileId||"(Unknown ID)"}`:e.humanReadableType,As=e=>e.fileUpdate?`Update File ${e.fileUpdate.fileId||"(Unknown ID)"}`:e.humanReadableType,vs=e=>e.fileDelete?`Delete File ${e.fileDelete.fileId||"(Unknown ID)"}`:e.humanReadableType,Cs=e=>e.consensusUpdateTopic?`Update Topic ${e.consensusUpdateTopic.topicId||"(Unknown ID)"}`:e.humanReadableType,xs=e=>e.consensusDeleteTopic?`Delete Topic ${e.consensusDeleteTopic.topicId||"(Unknown ID)"}`:e.humanReadableType,Rs=e=>e.tokenFreeze?`Freeze Token ${e.tokenFreeze.tokenId} for Account ${e.tokenFreeze.accountId}`:e.humanReadableType,Ns=e=>e.tokenUnfreeze?`Unfreeze Token ${e.tokenUnfreeze.tokenId} for Account ${e.tokenUnfreeze.accountId}`:e.humanReadableType,_s=e=>e.tokenGrantKyc?`Grant KYC for Token ${e.tokenGrantKyc.tokenId} to Account ${e.tokenGrantKyc.accountId}`:e.humanReadableType,Ps=e=>e.tokenRevokeKyc?`Revoke KYC for Token ${e.tokenRevokeKyc.tokenId} from Account ${e.tokenRevokeKyc.accountId}`:e.humanReadableType,Fs=e=>e.tokenPause?`Pause Token ${e.tokenPause.tokenId}`:e.humanReadableType,Os=e=>e.tokenUnpause?`Unpause Token ${e.tokenUnpause.tokenId}`:e.humanReadableType,zs=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},Ds=e=>e.tokenDelete?`Delete Token ${e.tokenDelete.tokenId}`:e.humanReadableType,Bs=e=>e.tokenAssociate?`Associate Account ${e.tokenAssociate.accountId} with Tokens: ${(e.tokenAssociate.tokenIds||[]).join(", ")}`:e.humanReadableType,Ms=e=>e.tokenDissociate?`Dissociate Account ${e.tokenDissociate.accountId} from Tokens: ${(e.tokenDissociate.tokenIds||[]).join(", ")}`:e.humanReadableType,Us=e=>e.cryptoDelete?`Delete Account ${e.cryptoDelete.deleteAccountId}`:e.humanReadableType,Ls=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},Ks=e=>e.cryptoUpdateAccount?`Update Account ${e.cryptoUpdateAccount.accountIdToUpdate||"(Unknown ID)"}`:e.humanReadableType,$s=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},Hs=e=>{if(e.cryptoDeleteAllowance){return`Delete ${(e.cryptoDeleteAllowance.nftAllowancesToRemove||[]).length} NFT Crypto Allowance(s)`}return e.humanReadableType},qs=e=>{if(e.contractCreate){let t="Create Contract";return e.contractCreate.memo&&(t+=` (Memo: ${e.contractCreate.memo})`),t}return e.humanReadableType},js=e=>e.contractUpdate?`Update Contract ${e.contractUpdate.contractIdToUpdate||"(Unknown ID)"}`:e.humanReadableType,Ws=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},Vs=e=>e.tokenUpdate?`Update Token ${e.tokenUpdate.tokenId||"(Unknown ID)"}`:e.humanReadableType,Gs=e=>e.tokenFeeScheduleUpdate?`Update Fee Schedule for Token ${e.tokenFeeScheduleUpdate.tokenId||"(Unknown ID)"}`:e.humanReadableType,Js=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)`},Ys=e=>{if(!e.scheduleCreate)return e.humanReadableType;let t="Create Schedule";return e.scheduleCreate.memo&&(t+=` (Memo: ${e.scheduleCreate.memo})`),t},Xs=e=>e.scheduleSign?"Sign Schedule":e.humanReadableType,Zs=e=>e.scheduleDelete?"Delete Schedule":e.humanReadableType,Qs=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,ea=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,ta=e=>"Network Freeze",ra=e=>"Ethereum Transaction",ia=e=>e.uncheckedSubmit&&e.uncheckedSubmit.topicId?`Unchecked Submit to topic ${e.uncheckedSubmit.topicId}`:"Unchecked Submit",oa=e=>"Create Node",na=e=>"Update Node",sa=e=>"Delete Node",aa=e=>`Atomic Batch (${Array.isArray(e.atomicBatch?.transactions)?e.atomicBatch.transactions.length:0} transaction(s))`,ca={CRYPTOTRANSFER:{fn:fs},cryptoTransfer:{fn:fs},CONTRACTCALL:{fn:ys},contractCall:{fn:ys},TOKENMINT:{fn:bs},tokenMint:{fn:bs},TOKENBURN:{fn:ws},tokenBurn:{fn:ws},TOKENCREATE:{fn:Is},tokenCreation:{fn:Is},TOPICCREATE:{fn:Ts},consensusCreateTopic:{fn:Ts},CONSENSUSSUBMITMESSAGE:{fn:Ss},consensusSubmitMessage:{fn:Ss},TOPICUPDATE:{fn:Cs},consensusUpdateTopic:{fn:Cs},TOPICDELETE:{fn:xs},consensusDeleteTopic:{fn:xs},FILECREATE:{fn:ks},fileCreate:{fn:ks},FILEAPPEND:{fn:Es},fileAppend:{fn:Es},FILEUPDATE:{fn:As},fileUpdate:{fn:As},FILEDELETE:{fn:vs},fileDelete:{fn:vs},TOKENUPDATE:{fn:Vs},tokenUpdate:{fn:Vs},TOKENFEESCHEDULEUPDATE:{fn:Gs},tokenFeeScheduleUpdate:{fn:Gs},TOKENFREEZE:{fn:Rs},tokenFreeze:{fn:Rs},TOKENUNFREEZE:{fn:Ns},tokenUnfreeze:{fn:Ns},TOKENGRANTKYC:{fn:_s},tokenGrantKyc:{fn:_s},TOKENREVOKEKYC:{fn:Ps},tokenRevokeKyc:{fn:Ps},TOKENPAUSE:{fn:Fs},tokenPause:{fn:Fs},TOKENUNPAUSE:{fn:Os},tokenUnpause:{fn:Os},TOKENWIPE:{fn:zs},TOKENWIPEACCOUNT:{fn:zs},tokenWipe:{fn:zs},tokenWipeAccount:{fn:zs},TOKENDELETE:{fn:Ds},tokenDelete:{fn:Ds},TOKENASSOCIATE:{fn:Bs},tokenAssociate:{fn:Bs},TOKENDISSOCIATE:{fn:Ms},tokenDissociate:{fn:Ms},ACCOUNTDELETE:{fn:Us},cryptoDelete:{fn:Us},ACCOUNTCREATE:{fn:Ls},cryptoCreateAccount:{fn:Ls},ACCOUNTUPDATE:{fn:Ks},cryptoUpdateAccount:{fn:Ks},APPROVEALLOWANCE:{fn:$s},cryptoApproveAllowance:{fn:$s},DELETEALLOWANCE:{fn:Hs},cryptoDeleteAllowance:{fn:Hs},CONTRACTCREATE:{fn:qs},contractCreate:{fn:qs},CONTRACTUPDATE:{fn:js},contractUpdate:{fn:js},CONTRACTDELETE:{fn:Ws},contractDelete:{fn:Ws},TOKENAIRDROP:{fn:Js},tokenAirdrop:{fn:Js},SCHEDULECREATE:{fn:Ys},scheduleCreate:{fn:Ys},SCHEDULESIGN:{fn:Xs},scheduleSign:{fn:Xs},SCHEDULEDELETE:{fn:Zs},scheduleDelete:{fn:Zs},SYSTEMDELETE:{fn:Qs},systemDelete:{fn:Qs},SYSTEMUNDELETE:{fn:ea},systemUndelete:{fn:ea},FREEZE:{fn:ta},freeze:{fn:ta},ETHEREUMTRANSACTION:{fn:ra},ethereumTransaction:{fn:ra},UNCHECKEDSUBMIT:{fn:ia},uncheckedSubmit:{fn:ia},NODECREATE:{fn:oa},nodeCreate:{fn:oa},NODEUPDATE:{fn:na},nodeUpdate:{fn:na},NODEDELETE:{fn:sa},nodeDelete:{fn:sa},ATOMICBATCH:{fn:aa},atomicBatch:{fn:aa}},la=e=>{const t=ca[e.type];if(t){if(t.fn)return t.fn(e);if(t.template)return ms(t.template,e)}const r=ca[e.humanReadableType];if(r){if(r.fn)return r.fn(e);if(r.template)return ms(r.template,e)}return"cryptoTransfer"===e.type||"CRYPTOTRANSFER"===e.type?fs(e):e.contractCall?ys(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,o]of Object.entries(r)){const e=[],r=[];for(const t of o){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 da(e){if(e){if(e.contractID)return`ContractID: ${new i.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()}`;if(e.ed25519)return`ED25519: ${a.Buffer.from(e.ed25519).toString("hex")}`;if(e.ECDSASecp256k1)return`ECDSA_secp256k1: ${a.Buffer.from(e.ECDSASecp256k1).toString("hex")}`;if(e?.keyList?.keys?.length>0){const t=e.keyList.keys.map(e=>da(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=>da(e)).filter(Boolean);return`ThresholdKey (${e.thresholdKey.threshold} of ${t.length}): [${t.join(", ")}]`}return e.delegatableContractId?`DelegatableContractID: ${new i.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 ua(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 pa(e,t){const r=ua(e);return!(!r||!r[t])}class ha{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 i.AccountId(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),e.initialSupply&&(t.initialSupply=i.Long.fromValue(e.initialSupply).toString()),void 0!==e.decimals&&null!==e.decimals&&(t.decimals=i.Long.fromValue(e.decimals).toNumber()),e.maxSupply&&(t.maxSupply=i.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=da(e.adminKey),t.kycKey=da(e.kycKey),t.freezeKey=da(e.freezeKey),t.wipeKey=da(e.wipeKey),t.supplyKey=da(e.supplyKey),t.feeScheduleKey=da(e.feeScheduleKey),t.pauseKey=da(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccount=new i.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.customFees&&e.customFees.length>0&&(t.customFees=e.customFees.map(e=>{const t={feeCollectorAccountId:e.feeCollectorAccountId?new i.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:i.Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new i.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:i.Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:i.Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:i.Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:i.Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let r;return e.royaltyFee.fallbackFee&&(r={amount:i.Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new i.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:i.Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:i.Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:r}}}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 i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:i.Long.fromValue(e.amount).toNumber()};return e.metadata&&e.metadata.length>0&&(t.metadata=e.metadata.map(e=>a.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 i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:i.Long.fromValue(e.amount).toNumber()};return e.serialNumbers&&e.serialNumbers.length>0&&(t.serialNumbers=e.serialNumbers.map(e=>i.Long.fromValue(e).toNumber())),t}static parseTokenUpdate(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.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 i.AccountId(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),t.adminKey=da(e.adminKey),t.kycKey=da(e.kycKey),t.freezeKey=da(e.freezeKey),t.wipeKey=da(e.wipeKey),t.supplyKey=da(e.supplyKey),t.feeScheduleKey=da(e.feeScheduleKey),t.pauseKey=da(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccountId=new i.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),void 0!==e.memo?.value&&(t.memo=e.memo.value),e.expiry?.seconds&&(t.expiry=`${i.Long.fromValue(e.expiry.seconds).toString()}.${e.expiry.nanos}`),t}static parseTokenFeeScheduleUpdate(e){if(!e)return;const t={};return e.tokenId&&(t.tokenId=new i.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 i.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:i.Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new i.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:i.Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:i.Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:i.Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:i.Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let r;return e.royaltyFee.fallbackFee&&(r={amount:i.Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new i.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:i.Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:i.Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:r}}}return{...t,feeType:"FIXED_FEE",fixedFee:{amount:"0"}}})),t}static parseTokenFreeze(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new i.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 i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new i.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 i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new i.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 i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new i.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 i.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 i.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 i.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new i.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=>i.Long.fromValue(e).toString())),e.amount&&(t.amount=i.Long.fromValue(e.amount).toString()),t}static parseTokenDelete(e){if(!e)return;const t={};return e.token&&(t.tokenId=new i.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 i.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 i.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 i.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 i.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(pa(e,"tokenAirdrop")){const t=ua(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 r of e.tokenTransfers){const e=r.token?new i.TokenId(r.token.shardNum??0,r.token.realmNum??0,r.token.tokenNum??0):null,o=[];if(r.transfers)for(const t of r.transfers){const e=t.accountID?new i.AccountId(t.accountID.shardNum??0,t.accountID.realmNum??0,t.accountID.accountNum??0):null;o.push({accountId:e?.toString()||"Unknown",amount:t.amount?i.Long.fromValue(t.amount).toString():"0",serialNumbers:t.serialNumbers?.map(e=>i.Long.fromValue(e).toString())})}t.push({tokenId:e?.toString()||"Unknown",transfers:o})}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(dg){}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 ga{static parseConsensusCreateTopic(e){if(!e)return;const t={};return e.memo&&(t.memo=e.memo),t.adminKey=da(e.adminKey),t.submitKey=da(e.submitKey),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new i.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=a.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=da(e.adminKey):t.adminKey=void 0,null===e.submitKey?(t.clearSubmitKey=!0,t.submitKey=void 0):e.submitKey?t.submitKey=da(e.submitKey):t.submitKey=void 0,e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new i.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 ma{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(pa(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=da({keyList:r})}return t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),t._memo&&(e.memo=t._memo),{type:"FILECREATE",humanReadableType:"File Create",fileCreate:e}}if(pa(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(pa(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=da({keyList:r})}return t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),t._memo&&(e.memo=t._memo),{type:"FILEUPDATE",humanReadableType:"File Update",fileUpdate:e}}if(pa(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=a.Buffer.from(e);let i,o;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),o=e.includes("�");i=t||o?"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{o=r.toString("utf8"),(o.includes("�")||/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(o))&&(o=r.toString("base64"))}catch{o=r.toString("base64")}else o=r.toString("base64");return{encoded:o,contentType:i,size:t}}static parseFileCreate(e){if(!e)return;const t={};return e.expirationTime?.seconds&&(t.expirationTime=`${i.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=da({keyList:e.keys})),e.contents&&(t.contents=a.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=a.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=`${i.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=da({keyList:e.keys})),e.contents&&(t.contents=a.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 fa{static parseCryptoTransfers(e,t){if(e.transfers?.accountAmounts&&(t.transfers=e.transfers.accountAmounts.map(e=>{const t=new i.AccountId(e.accountID.shardNum??0,e.accountID.realmNum??0,e.accountID.accountNum??0),r=i.Hbar.fromTinybars(i.Long.fromValue(e.amount));return{accountId:t.toString(),amount:r.toString(i.HbarUnit.Hbar),isDecimal:!0}})),e.tokenTransfers)for(const r of e.tokenTransfers){const e=new i.TokenId(r.token.shardNum??0,r.token.realmNum??0,r.token.tokenNum??0);if(r.transfers)for(const o of r.transfers){const r=new i.AccountId(o.accountID.shardNum??0,o.accountID.realmNum??0,o.accountID.accountNum??0),n=i.Long.fromValue(o.amount).toNumber();t.tokenTransfers.push({tokenId:e.toString(),accountId:r.toString(),amount:n})}}}static parseCryptoDelete(e){if(!e)return;const t={};return e.deleteAccountID&&(t.deleteAccountId=new i.AccountId(e.deleteAccountID.shardNum??0,e.deleteAccountID.realmNum??0,e.deleteAccountID.accountNum??0).toString()),e.transferAccountID&&(t.transferAccountId=new i.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=i.Hbar.fromTinybars(i.Long.fromValue(e.initialBalance)).toString(i.HbarUnit.Hbar)),e.key&&(t.key=da(e.key)),void 0!==e.receiverSigRequired&&(t.receiverSigRequired=e.receiverSigRequired),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.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 i.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=i.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 i.AccountId(e.accountIDToUpdate.shardNum??0,e.accountIDToUpdate.realmNum??0,e.accountIDToUpdate.accountNum??0).toString()),e.key&&(t.key=da(e.key)),e.expirationTime?.seconds&&(t.expirationTime=`${i.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=i.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 i.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=i.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 i.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new i.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount:i.Hbar.fromTinybars(i.Long.fromValue(e.amount)).toString(i.HbarUnit.Hbar)}))),e.tokenAllowances&&e.tokenAllowances.length>0&&(t.tokenAllowances=e.tokenAllowances.map(e=>({tokenId:new i.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),ownerAccountId:new i.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new i.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount:i.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 i.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString()),e.owner&&(t.ownerAccountId=new i.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString()),e.spender&&(t.spenderAccountId=new i.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=>i.Long.fromValue(e).toString())),void 0!==e.approvedForAll?.value&&(t.approvedForAll=e.approvedForAll.value),e.delegatingSpender&&(t.delegatingSpender=new i.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 i.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),tokenId:new i.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),serialNumbers:e.serialNumbers?e.serialNumbers.map(e=>i.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 ya{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:i.Long.fromValue(t._gas).toNumber(),amount:t._amount?parseFloat(t._amount.toString()):0};if(t._functionParameters){const r=a.Buffer.from(t._functionParameters).toString("hex");e.functionParameters=r,e.functionName=this.extractFunctionName(r)}return{type:"CONTRACTCALL",humanReadableType:"Contract Call",contractCall:e}}if(pa(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=a.Buffer.from(t._bytecode).toString("hex")),t._constructorParameters&&(e.constructorParameters=a.Buffer.from(t._constructorParameters).toString("hex")),t._memo&&(e.memo=t._memo),t._adminKey&&(e.adminKey=da(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=i.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(pa(e,"contractUpdateInstance")){const e={contractIdToUpdate:t._contractId.toString()};return t._memo&&(e.memo=t._memo),t._adminKey&&(e.adminKey=da(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=i.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(pa(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?i.Long.fromValue(e.maxGasAllowance).toNumber():0,amount:0};if(e.ethereumData&&e.ethereumData.length>0){const r=a.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=i.Hbar.fromTinybars(i.Long.fromValue(e.amount??0)),r={contractId:new i.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString(),gas:i.Long.fromValue(e.gas??0).toNumber(),amount:parseFloat(t.toString(i.HbarUnit.Hbar))};return e.functionParameters&&(r.functionParameters=a.Buffer.from(e.functionParameters).toString("hex"),r.functionParameters.length>=8&&(r.functionName=this.extractFunctionName(r.functionParameters))),r}static parseContractCreate(e){if(!e)return;const t={};return e.initialBalance&&(t.initialBalance=i.Hbar.fromTinybars(i.Long.fromValue(e.initialBalance)).toString(i.HbarUnit.Hbar)),e.gas&&(t.gas=i.Long.fromValue(e.gas).toString()),e.adminKey&&(t.adminKey=da(e.adminKey)),e.constructorParameters&&(t.constructorParameters=a.Buffer.from(e.constructorParameters).toString("hex")),e.memo&&(t.memo=e.memo),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.stakedAccountId?t.stakedAccountId=new i.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=i.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 i.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=a.Buffer.from(e.initcode).toString("hex")),t}static parseContractUpdate(e){if(!e)return;const t={};if(e.contractID&&(t.contractIdToUpdate=new i.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.adminKey&&(t.adminKey=da(e.adminKey)),e.expirationTime?.seconds&&(t.expirationTime=`${i.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=i.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 i.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&&i.Long.fromValue(e.stakedNodeId).notEquals(-1)?(t.stakedNodeId=i.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 i.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 i.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.transferAccountID?t.transferAccountId=new i.AccountId(e.transferAccountID.shardNum??0,e.transferAccountID.realmNum??0,e.transferAccountID.accountNum??0).toString():e.transferContractID&&(t.transferContractId=new i.ContractId(e.transferContractID.shardNum??0,e.transferContractID.realmNum??0,e.transferContractID.contractNum??0).toString()),t}static parseFromTransactionObject(e){return this.parseSCSTransaction(e)}}class ba{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(pa(e,"utilPrng")){const e={};return t._range&&0!==t._range&&(e.range=t._range),{type:"PRNG",humanReadableType:"Pseudo Random Number",utilPrng:e}}if(pa(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(pa(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(pa(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=`${i.Long.fromValue(e.startTime.seconds).toString()}.${e.startTime.nanos??0}`),e.updateFile&&(t.updateFile=new i.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 i.FileId(e.fileID.shardNum??0,e.fileID.realmNum??0,e.fileID.fileNum??0).toString():e.contractID&&(t.contractId=new i.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.expirationTime?.seconds&&(t.expirationTime=i.Long.fromValue(e.expirationTime.seconds).toString()),t}static parseSystemUndeleteFromProto(e){if(!e)return;const t={};return e.fileID?t.fileId=new i.FileId(e.fileID.shardNum??0,e.fileID.realmNum??0,e.fileID.fileNum??0).toString():e.contractID&&(t.contractId=new i.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=i.Long.fromValue(e.nodeId).toNumber()),t}static parseNodeUpdateFromProto(e){if(!e)return;const t={};return void 0!==e.nodeId&&(t.nodeId=i.Long.fromValue(e.nodeId).toNumber()),t}static parseNodeDeleteFromProto(e){if(!e)return;const t={};return void 0!==e.nodeId&&(t.nodeId=i.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 wa{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(pa(e,"scheduleCreate")){return{type:"SCHEDULECREATE",humanReadableType:"Schedule Create",scheduleCreate:{scheduledTransactionBody:globalThis.Buffer.from(t._scheduledTransaction).toString("base64"),memo:t._scheduleMemo,adminKey:t._adminKey?da(t._adminKey):void 0,payerAccountId:t._payerAccountId?.toString(),expirationTime:t._expirationTime?.toString(),waitForExpiry:t._waitForExpiry||!1}}}if(pa(e,"scheduleSign")){return{type:"SCHEDULESIGN",humanReadableType:"Schedule Sign",scheduleSign:{scheduleId:t._scheduleId.toString()}}}if(pa(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=da(e.adminKey)),e.payerAccountID&&(t.payerAccountId=new i.AccountId(e.payerAccountID.shardNum??0,e.payerAccountID.realmNum??0,e.payerAccountID.accountNum??0).toString()),e.expirationTime?.seconds&&(t.expirationTime=`${i.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 i.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 i.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 Ia={TOKENCREATE:{bodyField:"tokenCreation",parser:ha.parseTokenCreate,resultField:"tokenCreation"},TOKENMINT:{bodyField:"tokenMint",parser:ha.parseTokenMint,resultField:"tokenMint"},TOKENBURN:{bodyField:"tokenBurn",parser:ha.parseTokenBurn,resultField:"tokenBurn"},TOKENUPDATE:{bodyField:"tokenUpdate",parser:ha.parseTokenUpdate,resultField:"tokenUpdate"},TOKENDELETE:{bodyField:"tokenDeletion",parser:ha.parseTokenDelete,resultField:"tokenDelete"},TOKENASSOCIATE:{bodyField:"tokenAssociate",parser:ha.parseTokenAssociate,resultField:"tokenAssociate"},TOKENDISSOCIATE:{bodyField:"tokenDissociate",parser:ha.parseTokenDissociate,resultField:"tokenDissociate"},TOKENFREEZE:{bodyField:"tokenFreeze",parser:ha.parseTokenFreeze,resultField:"tokenFreeze"},TOKENUNFREEZE:{bodyField:"tokenUnfreeze",parser:ha.parseTokenUnfreeze,resultField:"tokenUnfreeze"},TOKENGRANTKYC:{bodyField:"tokenGrantKyc",parser:ha.parseTokenGrantKyc,resultField:"tokenGrantKyc"},TOKENREVOKEKYC:{bodyField:"tokenRevokeKyc",parser:ha.parseTokenRevokeKyc,resultField:"tokenRevokeKyc"},TOKENPAUSE:{bodyField:"tokenPause",parser:ha.parseTokenPause,resultField:"tokenPause"},TOKENUNPAUSE:{bodyField:"tokenUnpause",parser:ha.parseTokenUnpause,resultField:"tokenUnpause"},TOKENWIPEACCOUNT:{bodyField:"tokenWipe",parser:ha.parseTokenWipeAccount,resultField:"tokenWipeAccount"},TOKENFEESCHEDULEUPDATE:{bodyField:"tokenFeeScheduleUpdate",parser:ha.parseTokenFeeScheduleUpdate,resultField:"tokenFeeScheduleUpdate"},TOKENAIRDROP:{bodyField:"tokenAirdrop",parser:ha.parseTokenAirdropFromProto,resultField:"tokenAirdrop"},TOPICCREATE:{bodyField:"consensusCreateTopic",parser:ga.parseConsensusCreateTopic,resultField:"consensusCreateTopic"},CONSENSUSSUBMITMESSAGE:{bodyField:"consensusSubmitMessage",parser:ga.parseConsensusSubmitMessage,resultField:"consensusSubmitMessage"},TOPICUPDATE:{bodyField:"consensusUpdateTopic",parser:ga.parseConsensusUpdateTopic,resultField:"consensusUpdateTopic"},TOPICDELETE:{bodyField:"consensusDeleteTopic",parser:ga.parseConsensusDeleteTopic,resultField:"consensusDeleteTopic"},ACCOUNTCREATE:{bodyField:"cryptoCreateAccount",parser:fa.parseCryptoCreateAccount,resultField:"cryptoCreateAccount"},ACCOUNTUPDATE:{bodyField:"cryptoUpdateAccount",parser:fa.parseCryptoUpdateAccount,resultField:"cryptoUpdateAccount"},ACCOUNTDELETE:{bodyField:"cryptoDelete",parser:fa.parseCryptoDelete,resultField:"cryptoDelete"},CRYPTOTRANSFER:{bodyField:"cryptoTransfer",parser:e=>{const t={transfers:[],tokenTransfers:[]};return fa.parseCryptoTransfers(e,t),t},resultField:"transfers",spreadResult:!0},APPROVEALLOWANCE:{bodyField:"cryptoApproveAllowance",parser:fa.parseCryptoApproveAllowance,resultField:"cryptoApproveAllowance"},DELETEALLOWANCE:{bodyField:"cryptoDeleteAllowance",parser:fa.parseCryptoDeleteAllowance,resultField:"cryptoDeleteAllowance"},FILECREATE:{bodyField:"fileCreate",parser:ma.parseFileCreate,resultField:"fileCreate"},FILEUPDATE:{bodyField:"fileUpdate",parser:ma.parseFileUpdate,resultField:"fileUpdate"},FILEDELETE:{bodyField:"fileDelete",parser:ma.parseFileDelete,resultField:"fileDelete"},FILEAPPEND:{bodyField:"fileAppend",parser:ma.parseFileAppend,resultField:"fileAppend"},CONTRACTCREATE:{bodyField:"contractCreateInstance",parser:ya.parseContractCreate,resultField:"contractCreate"},CONTRACTUPDATE:{bodyField:"contractUpdateInstance",parser:ya.parseContractUpdate,resultField:"contractUpdate"},CONTRACTDELETE:{bodyField:"contractDeleteInstance",parser:ya.parseContractDelete,resultField:"contractDelete"},CONTRACTCALL:{bodyField:"contractCall",parser:ya.parseContractCall,resultField:"contractCall"},ETHEREUMTRANSACTION:{bodyField:"ethereumTransaction",parser:ya.parseEthereumTransaction,resultField:"ethereumTransaction"},SCHEDULECREATE:{bodyField:"scheduleCreate",parser:wa.parseScheduleCreateFromProto,resultField:"scheduleCreate"},SCHEDULESIGN:{bodyField:"scheduleSign",parser:wa.parseScheduleSignFromProto,resultField:"scheduleSign"},SCHEDULEDELETE:{bodyField:"scheduleDelete",parser:wa.parseScheduleDeleteFromProto,resultField:"scheduleDelete"},PRNG:{bodyField:"utilPrng",parser:ba.parseUtilPrng,resultField:"utilPrng"},FREEZE:{bodyField:"freeze",parser:ba.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:ha.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 Ta={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"}},Sa={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"},ka={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 Ea(e){for(const[t,r]of Object.entries(Ta))if(e[t])return r;return{type:"UNKNOWN",humanReadableType:"Unknown Transaction"}}function Aa(e){return Sa[e]||"Unknown Transaction"}class va{static async parseTransactionBytes(e,t={}){const{enableFallback:r=!0,strictMode:i=!1,includeRaw:o=!0,maxRetries:n=2}=t,s=this.validateTransactionBytes(e);if(!s.isValid&&i)throw new gs(`Invalid transaction bytes format: ${s.error}`,"INVALID_FORMAT",void 0,e);let a,c=0;for(;c<=n;)try{const r=await this.parseTransaction(e,t);return r.formatDetection={originalFormat:s.format||"base64",wasConverted:"hex"===s.format,length:e.length},r}catch(d){if(a=d instanceof Error?d:new Error(String(d)),c++,!r||c>n){if(i)throw new gs("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(u){}}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,o;!t||a.Buffer.isBuffer(t)||t instanceof Uint8Array?(i=t,o=r):(o=t,i=void 0);try{const t=this.extractTransactionMetadata(e),r=ha.parseFromTransactionObject(e),a=fa.parseFromTransactionObject(e),c=ga.parseFromTransactionObject(e),l=ma.parseFromTransactionObject(e),d=ya.parseFromTransactionObject(e),u=wa.parseFromTransactionObject(e),p=ba.parseFromTransactionObject(e),h=[r,a,c,l,d,u,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(s){}"UNKNOWN"===m&&h.type&&(m=h.type,f=h.humanReadableType||f);const b={type:m,humanReadableType:f,transfers:[],tokenTransfers:[],...t,...h,raw:o.includeRaw?e._transactionBody||{}:void 0};return this.mergeProtoParsingResults(b,y,r,e,i),b.transfers=a.transfers||b.transfers||[],b.tokenTransfers=a.tokenTransfers||b.tokenTransfers||[],b}catch(c){return{type:"UNKNOWN",humanReadableType:"Unknown Transaction",transfers:[],tokenTransfers:[],raw:o.includeRaw?{}:void 0,details:{error:`Failed to parse Transaction object: ${c instanceof Error?c.message:String(c)}`}}}}static parseTransactionBody(e){try{const t=c.ethers.decodeBase64(e),r=n.proto.SchedulableTransactionBody.decode(t),o=this.getTransactionType(r),s={type:o,humanReadableType:this.getHumanReadableType(o),transfers:[],tokenTransfers:[],raw:r};if(r.memo&&(s.memo=r.memo),r.transactionFee){const e=i.Hbar.fromTinybars(i.Long.fromValue(r.transactionFee));s.transactionFee=e.toString(i.HbarUnit.Hbar)}return this.applySchedulableTransactionParsing(r,s),s}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 Ea(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 Ea(e).type}static getHumanReadableType(e){return Aa(e)}static getTransactionSummary(e){return la(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,o=!1;return"hex"===t?(o=/^0x[0-9a-fA-F]+$/.test(e)&&e.length>2,o||(i="Invalid hex format")):(o=r.test(e)&&e.length>0,o||(i="Invalid base64 format")),{isValid:o,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(a.Buffer.from(t,"hex"))}return new Uint8Array(a.Buffer.from(e,"base64"))}catch(t){throw new gs("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 i.Transaction.fromBytes(t),!0}catch{return!1}}static decodeBytesLegacy(e){return this.decodeTransactionBytes(e)}static async parseTransaction(e,t={}){try{const r=this.decodeTransactionBytes(e),o=i.Transaction.fromBytes(r),n=this.extractTransactionMetadataEnhanced(o),s=this.runAllParsers(o),a=s.find(e=>e.type&&"UNKNOWN"!==e.type)||{},c=this.parseFromProtobuf(r),l=c.type||a.type||"UNKNOWN",d={type:l,humanReadableType:c.humanReadableType||a.humanReadableType||"Unknown Transaction",transfers:[],tokenTransfers:[],details:{...n},memo:"string"==typeof n.memo?n.memo:void 0,transactionId:"string"==typeof n.transactionId?n.transactionId:void 0,nodeAccountIds:Array.isArray(n.nodeAccountIds)?n.nodeAccountIds:[],maxTransactionFee:"string"==typeof n.maxTransactionFee?n.maxTransactionFee:void 0,validStart:"string"==typeof n.validStart?n.validStart:void 0,validDuration:"string"==typeof n.validDuration?n.validDuration:void 0,raw:t.includeRaw?{}:void 0};return this.mergeAllResults(d,c,a,s),d}catch(r){throw new gs("Failed to parse as regular transaction","REGULAR_PARSING_FAILED",r instanceof Error?r: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 gs("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[ha.parseFromTransactionObject(e),fa.parseFromTransactionObject(e),ga.parseFromTransactionObject(e),ma.parseFromTransactionObject(e),ya.parseFromTransactionObject(e),wa.parseFromTransactionObject(e),ba.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 o=i.find(e=>e.transfers||e.tokenTransfers)||{};e.transfers=o.transfers||e.transfers||[],e.tokenTransfers=o.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&&fa.parseCryptoTransfers(e.cryptoTransfer,t),e.cryptoDelete&&(t.cryptoDelete=fa.parseCryptoDelete(e.cryptoDelete)),e.cryptoCreateAccount&&(t.cryptoCreateAccount=fa.parseCryptoCreateAccount(e.cryptoCreateAccount)),e.cryptoUpdateAccount&&(t.cryptoUpdateAccount=fa.parseCryptoUpdateAccount(e.cryptoUpdateAccount)),e.cryptoApproveAllowance&&(t.cryptoApproveAllowance=fa.parseCryptoApproveAllowance(e.cryptoApproveAllowance)),e.cryptoDeleteAllowance&&(t.cryptoDeleteAllowance=fa.parseCryptoDeleteAllowance(e.cryptoDeleteAllowance)),e.contractCall&&(t.contractCall=ya.parseContractCall(e.contractCall)),e.contractCreateInstance&&(t.contractCreate=ya.parseContractCreate(e.contractCreateInstance)),e.contractUpdateInstance&&(t.contractUpdate=ya.parseContractUpdate(e.contractUpdateInstance)),e.contractDeleteInstance&&(t.contractDelete=ya.parseContractDelete(e.contractDeleteInstance)),e.tokenCreation&&(t.tokenCreation=ha.parseTokenCreate(e.tokenCreation)),e.tokenMint&&(t.tokenMint=ha.parseTokenMint(e.tokenMint)),e.tokenBurn&&(t.tokenBurn=ha.parseTokenBurn(e.tokenBurn)),e.tokenUpdate&&(t.tokenUpdate=ha.parseTokenUpdate(e.tokenUpdate)),e.tokenFeeScheduleUpdate&&(t.tokenFeeScheduleUpdate=ha.parseTokenFeeScheduleUpdate(e.tokenFeeScheduleUpdate)),e.tokenFreeze&&(t.tokenFreeze=ha.parseTokenFreeze(e.tokenFreeze)),e.tokenUnfreeze&&(t.tokenUnfreeze=ha.parseTokenUnfreeze(e.tokenUnfreeze)),e.tokenGrantKyc&&(t.tokenGrantKyc=ha.parseTokenGrantKyc(e.tokenGrantKyc)),e.tokenRevokeKyc&&(t.tokenRevokeKyc=ha.parseTokenRevokeKyc(e.tokenRevokeKyc)),e.tokenPause&&(t.tokenPause=ha.parseTokenPause(e.tokenPause)),e.tokenUnpause&&(t.tokenUnpause=ha.parseTokenUnpause(e.tokenUnpause)),e.tokenWipe&&(t.tokenWipeAccount=ha.parseTokenWipeAccount(e.tokenWipe)),e.tokenDeletion&&(t.tokenDelete=ha.parseTokenDelete(e.tokenDeletion)),e.tokenAssociate&&(t.tokenAssociate=ha.parseTokenAssociate(e.tokenAssociate)),e.tokenDissociate&&(t.tokenDissociate=ha.parseTokenDissociate(e.tokenDissociate)),e.tokenAirdrop&&(t.tokenAirdrop=ha.parseTokenAirdropFromProto(e.tokenAirdrop)),e.consensusCreateTopic&&(t.consensusCreateTopic=ga.parseConsensusCreateTopic(e.consensusCreateTopic)),e.consensusSubmitMessage&&(t.consensusSubmitMessage=ga.parseConsensusSubmitMessage(e.consensusSubmitMessage)),e.consensusUpdateTopic&&(t.consensusUpdateTopic=ga.parseConsensusUpdateTopic(e.consensusUpdateTopic)),e.consensusDeleteTopic&&(t.consensusDeleteTopic=ga.parseConsensusDeleteTopic(e.consensusDeleteTopic)),e.fileCreate&&(t.fileCreate=ma.parseFileCreate(e.fileCreate)),e.fileAppend&&(t.fileAppend=ma.parseFileAppend(e.fileAppend)),e.fileUpdate&&(t.fileUpdate=ma.parseFileUpdate(e.fileUpdate)),e.fileDelete&&(t.fileDelete=ma.parseFileDelete(e.fileDelete)),e.utilPrng&&(t.utilPrng=ba.parseUtilPrng(e.utilPrng))}static parseTransactionBodyDetails(e,t){const r={},i=Ia[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,o){const n=Object.values(Ia).map(e=>e.resultField);for(const s of n){const o=t[s],n=r[s];void 0!==o?e[s]=o:void 0!==n?e[s]=n:this.handleSpecialFieldExtraction(e,s,i)}}static handleSpecialFieldExtraction(e,t,r){if("tokenCreation"===t&&"TOKENCREATE"===e.type){const i=ha.extractTokenCreationFromTransaction(r);i&&(e[t]=i)}else if("tokenAirdrop"===t&&"TOKENAIRDROP"===e.type){const i=ha.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 Ca="undefined"!=typeof window&&void 0!==window.document;const xa=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()}},Ra=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 Na(e,t,r){if(r)return r;const i=t.connectionMode||(!1===t.websocket?"http":"auto"),o={apiKey:t.apiKey,accountId:e.accountId,network:e.network||"mainnet",authType:t.apiKey?"api":"server",connectionMode:i},n=Ra.get(o);if(n)return n;let s;return s=t.apiKey?new ps({apiKey:t.apiKey,network:e.network||"mainnet",connectionMode:i}):await ps.createWithAuth({type:"server",accountId:e.accountId,privateKey:"string"==typeof e.privateKey?e.privateKey:e.privateKey.toString(),network:e.network||"mainnet",connectionMode:i}),Ra.set(o,s),s}let _a={};async function Pa(e){if(Ca)throw new Error("File path operations are not supported in browser environment. Use buffer input type instead.");if(await async function(){if(!Ca&&!_a.readFileSync)try{const e="undefined"!=typeof global?global:globalThis,t=e.process?.mainModule?.require||e.require;if("function"!=typeof t)throw new Error("require function not available");{const e=t("fs"),r=t("path");_a.readFileSync=e.readFileSync,_a.basename=r.basename,_a.extname=r.extname}}catch(e){console.warn("Node.js modules not available, file path operations will be disabled")}}(),!_a.readFileSync||!_a.basename||!_a.extname)throw new Error("Node.js file system modules are not available. Cannot read file from path.");try{const r=_a.readFileSync(e),i=r.toString("base64"),o=_a.basename(e);let n="application/octet-stream";try{const e=await l.fileTypeFromBuffer(r);e&&(n=e.mime)}catch(t){const r=_a.extname(e).toLowerCase();n={".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:o,mimeType:n}}catch(t){throw new Error(`Failed to read file ${e}: ${t.message}`)}}function Fa(e){return{accountId:e.accountId,privateKey:"string"==typeof e.privateKey?e.privateKey:e.privateKey.toString(),network:e.network}}async function Oa(e,t,r,i){const o=B.getInstance({module:"Inscriber",...r.logging});o.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 o.debug("Quote-only mode requested, generating quote"),await Ma(e,t,r,i);"hashinal"===r.mode&&r.metadata&&Ba(r.metadata,o);const n=r.connectionMode??(!1===r.websocket?"http":"auto"),s=r.waitIntervalMs??4e3,a=!r.waitForConfirmation;let c;if(i)o.debug("Using existing InscriptionSDK instance"),c=i;else if(r.apiKey)o.debug("Initializing InscriptionSDK with API key"),c=new ps({apiKey:r.apiKey,network:t.network||"mainnet",connectionMode:n});else{o.debug("Initializing InscriptionSDK with server auth");const e=Fa(t);c=await ps.createWithAuth({type:"server",accountId:e.accountId,privateKey:e.privateKey,network:e.network||"mainnet",connectionMode:n})}const l={holderId:t.accountId,metadata:r.metadata||{},tags:r.tags||[],mode:r.mode||"file",fileStandard:r.fileStandard,chunkSize:r.chunkSize};let d;switch(e.type){case"url":d={...l,file:{type:"url",url:e.url}};break;case"file":{const t=await Pa(e.path);d={...l,file:{type:"base64",base64:t.base64,fileName:t.fileName,mimeType:t.mimeType}};break}case"buffer":d={...l,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&&(d.metadataObject=r.metadata,d.creator=r.metadata?.creator||t.accountId,d.description=r.metadata?.description,r.jsonFileURL&&(d.jsonFileURL=r.jsonFileURL)),o.debug("Preparing to inscribe content",{type:e.type,mode:r.mode||"file",holderId:t.accountId});const u=Fa(t),p=await c.inscribeAndExecute(d,u,void 0,{waitForCompletion:a,maxWaitTime:18e4,checkInterval:s}),h=p.transactionId||p.jobId;if(o.info("Starting to inscribe.",{type:e.type,mode:r.mode||"file",transactionId:h}),r.waitForConfirmation){if(o.debug("Waiting for inscription confirmation",{transactionId:h,maxAttempts:r.waitMaxAttempts,intervalMs:s}),!h)throw new li("Transaction ID is required for confirmation");const e=await Ua(c,h,r.waitMaxAttempts,s,r.progressCallback);return o.info("Inscription confirmation received",{transactionId:h}),{confirmed:!0,result:p,inscription:e,sdk:c}}return{confirmed:!1,result:p,sdk:c}}catch(n){throw o.error("Error during inscription process",n),n}}async function za(e,t,r,i){const o=B.getInstance({module:"Inscriber",...r.logging});o.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){o.debug("Quote-only mode requested with signer, generating quote");const n={accountId:t.getAccountId().toString(),privateKey:"",network:r.network||"mainnet"};return await Ma(e,n,r,i)}"hashinal"===r.mode&&r.metadata&&Ba(r.metadata,o);const n=t.getAccountId().toString();o.debug("Using account ID from signer",{accountId:n});const s=r.connectionMode??(!1===r.websocket?"http":"auto");let a;i?(o.debug("Using existing InscriptionSDK instance"),a=i):r.apiKey?(o.debug("Initializing InscriptionSDK with API key"),a=new ps({apiKey:r.apiKey,network:r.network||"mainnet",connectionMode:s})):(o.debug("Initializing InscriptionSDK with client auth (wallet signer)"),a=await ps.createWithAuth({type:"client",accountId:n,signer:t,network:r.network||"mainnet",connectionMode:s}));const c={holderId:n,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 Pa(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||n,l.description=r.metadata?.description,r.jsonFileURL&&(l.jsonFileURL=r.jsonFileURL)),o.debug("Starting inscription via startInscription (websocket)",{type:e.type,mode:r.mode||"file",holderId:n,usesStartInscription:!0});const d=await a.startInscription({...l,holderId:n,network:r.network||"mainnet"});if(o.info("about to start inscription",{type:e.type,mode:r.mode||"file",jobId:d.id||d.tx_id,...d}),"string"==typeof d?.transactionBytes?(o.debug("Executing inscription transaction with signer from bytes"),await a.executeTransactionWithSigner(d.transactionBytes,t)):"Buffer"===d?.transactionBytes?.type&&(o.debug("Executing inscription transaction with signer from buffer"),await a.executeTransactionWithSigner(globalThis.Buffer.from(d.transactionBytes.data).toString("base64"),t)),r.waitForConfirmation){o.debug("Waiting for inscription confirmation (websocket)",{jobId:d.id||d.tx_id,maxAttempts:r.waitMaxAttempts,intervalMs:r.waitIntervalMs});const e=d.tx_id||d.id,t=await Ua(a,e,r.waitMaxAttempts,r.waitIntervalMs,r.progressCallback);return o.info("Inscription confirmation received",{jobId:e}),{confirmed:!0,result:{jobId:d.id||d.tx_id,transactionId:d.tx_id||"",topic_id:d.topic_id,status:d.status,completed:d.completed},inscription:t,sdk:a}}return{confirmed:!1,result:{jobId:d.id||d.tx_id,transactionId:d.tx_id||"",topic_id:d.topic_id,status:d.status,completed:d.completed},sdk:a}}catch(n){throw o.error("Error during inscription process",n),n}}async function Da(e,t){const r=B.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 ps({apiKey:t.apiKey,network:t.network||"mainnet"});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 ps.createWithAuth({type:"server",accountId:t.accountId,privateKey:t.privateKey,network:t.network||"mainnet"})}r.debug("Initialized SDK for inscription retrieval",{formattedTransactionId:i,network:t.network||"mainnet"});const o=await e.retrieveInscription(i);return r.info("Successfully retrieved inscription",{formattedTransactionId:i}),o}catch(o){throw r.error("Error retrieving inscription",{formattedTransactionId:i,error:o}),o}}function Ba(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 Ma(e,t,r,i){const o=B.getInstance({module:"Inscriber",...r.logging});o.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 n=function(e,t,r){const i=xa.createCacheKey(e,t,r);return xa.get(i)}(e,t,r);if(n)return o.debug("Returning cached quote"),{confirmed:!1,quote:!0,result:n};"hashinal"===r.mode&&r.metadata&&Ba(r.metadata,o);const s=await Na(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 Pa(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)),o.debug("Calling inscription SDK startInscription for quote",{type:e.type,mode:r.mode||"file",holderId:t.accountId});const l=await s.startInscription(c);o.debug("Received inscription response for quote parsing",{hasTransactionBytes:!!l.transactionBytes,bytesLength:l.transactionBytes?.length||0,transactionBytesType:typeof l.transactionBytes,totalCost:l.totalCost});const d=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 o=await va.parseTransactionBytes(r,{includeRaw:!1});t.debug("Parsed transaction for quote",{type:o.type,hasTransfers:!!o.transfers,transferCount:o.transfers?.length||0,transfers:o.transfers});let n=0;if(o.transfers&&o.transfers.length>0)for(const e of o.transfers){const r="string"==typeof e.amount?parseFloat(e.amount):e.amount;if(r<0){const i=Math.abs(r);n+=i,t.debug("Found HBAR transfer",{from:e.accountId,to:"service",amount:i})}}n>0&&(i=n.toString(),t.debug("Using parsed transaction transfer amount",{totalTransferAmount:n,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 o=[{to:"Inscription Service",amount:i,description:`Inscription fee (${i} HBAR)`}],n={totalCostHbar:i,validUntil:new Date(Date.now()+9e5).toISOString(),breakdown:{transfers:o}};return t.debug("Successfully parsed transaction for quote",{totalCostHbar:n.totalCostHbar,transferCount:o.length,hasTransactionBytes:!!e.transactionBytes,hasTotalCost:!!e.totalCost}),n}catch(i){throw t.error("Error parsing transaction for quote",i),i}}(l,o);return function(e,t,r,i){const o=xa.createCacheKey(e,t,r);xa.set(o,i,6e5)}(e,t,r,d),o.info("Successfully generated inscription quote",{totalCostHbar:d.totalCostHbar}),{confirmed:!1,quote:!0,result:d}}catch(n){throw o.error("Error generating inscription quote",n),n}}async function Ua(e,t,r=30,i=4e3,o){const n=B.getInstance({module:"Inscriber"}),s=new hs({module:"Inscriber",logger:n,callback:o});try{n.debug("Waiting for inscription confirmation",{transactionId:t,maxAttempts:r,intervalMs:i}),s.preparing("Preparing for inscription confirmation",5,{transactionId:t,maxAttempts:r,intervalMs:i});for(let c=1;c<=r;c++){s.verifying("Checking inscription status",void 0,{attempt:c,maxAttempts:r});try{const r=await e.retrieveInscription(t);if("completed"===r.status||r.completed)return s.completed("Inscription confirmed",{transactionId:t}),r;s.verifying("Inscription still processing",void 0,{transactionId:t,status:r.status})}catch(a){if(!("number"==typeof a.response?.status&&404===a.response?.status))throw n.error("Error waiting for inscription confirmation",{transactionId:t,attempt:c,error:a}),s.failed("Inscription confirmation failed",{transactionId:t,error:a}),a;n.debug("Inscription not found yet, retrying",{transactionId:t,attempt:c})}c<r&&await M(i)}const o=new Error(`Inscription confirmation timed out after ${r} attempts`);throw n.error("Error waiting for inscription confirmation",{transactionId:t,maxAttempts:r,intervalMs:i,error:o}),s.failed("Inscription confirmation failed",{transactionId:t,error:o}),o}catch(a){throw n.error("Error waiting for inscription confirmation",{transactionId:t,maxAttempts:r,intervalMs:i,error:a}),s.failed("Inscription confirmation failed",{transactionId:t,error:a}),a}}function La(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,o=i.topicId;if("string"==typeof o&&o.trim())return o;const n=i.topic_id;return"string"==typeof n&&n.trim()?n:void 0}var Ka=(e=>(e.REGISTER_CONFIG="register-config",e.REGISTER="register",e))(Ka||{}),$a=(e=>(e.EVM="evm",e.WASM="wasm",e))($a||{});const Ha=r.z.object({name:r.z.string().optional(),type:r.z.string()}),qa=r.z.object({name:r.z.string(),inputs:r.z.array(Ha),outputs:r.z.array(Ha),stateMutability:r.z.enum(["view","pure"]),type:r.z.literal("function")}),ja=r.z.enum(["number","string","bool"]),Wa=r.z.object({p:r.z.literal("hcs-7"),m:r.z.string().optional()}),Va=Wa.extend({op:r.z.literal("register-config"),t:r.z.literal("evm"),c:r.z.object({contractAddress:r.z.string().regex(/^0x[a-fA-F0-9]{40}$/,"Invalid contract address"),abi:qa})}),Ga=Wa.extend({op:r.z.literal("register-config"),t:r.z.literal("wasm"),c:r.z.object({wasmTopicId:r.z.string(),inputType:r.z.object({stateData:r.z.record(ja)}),outputType:r.z.object({type:r.z.literal("string"),format:r.z.literal("topic-id")})})}),Ja=Wa.extend({op:r.z.literal("register"),t_id:r.z.string(),d:r.z.object({weight:r.z.number(),tags:r.z.array(r.z.string()).nonempty()}).catchall(r.z.unknown())}),Ya=r.z.union([Va,Ga,Ja]);class Xa{constructor(e){this.network=e.network,this.logger=e.logger||B.getInstance({level:e.logLevel||"info",module:"HCS7Client",silent:e.silent}),this.mirrorNode=new J(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0)}generateRegistryMemo(e){return`hcs-7:indexed:${e}`}createConfigMessage(e){return e.config.type===$a.EVM?{p:"hcs-7",op:Ka.REGISTER_CONFIG,t:$a.EVM,c:{contractAddress:e.config.contractAddress,abi:e.config.abi},m:e.memo}:{p:"hcs-7",op:Ka.REGISTER_CONFIG,t:$a.WASM,c:{wasmTopicId:e.config.wasmTopicId,inputType:e.config.inputType,outputType:e.config.outputType},m:e.memo}}createMetadataMessage(e){return{p:"hcs-7",op:Ka.REGISTER,t_id:e.metadataTopicId,m:e.memo,d:{weight:e.weight,tags:e.tags,...e.data||{}}}}validateMessage(e){const t=Ya.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=Ya.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 Za(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 Qa(e){return X({memo:`hcs-7:indexed:${e.ttl}`,submitKey:e.submitKey,adminKey:e.adminKey,operatorPublicKey:e.operatorPublicKey})}function ec(e){const t={p:"hcs-7",...e.message};return Z({topicId:e.topicId,message:JSON.stringify(t),transactionMemo:e.transactionMemo})}class tc{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 rc(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 ic(e){const t=Object.create(B.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 oc(e){return e instanceof B}async function nc(e,t,r){const i=new J(t,r),o=[];for(const s of e)try{const e=await i.getPublicKey(s);o.push(e)}catch(n){r&&r.warn(`Could not get public key for account ${s}: ${n}`)}return o}const sc=e=>e.trim().toLowerCase(),ac=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"}]]),cc={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},lc=new Map(Object.entries(cc).map(([e,t])=>[t,e])),dc=e=>{const t=sc(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=cc[t];void 0!==e&&(i=e,r=t)}else lc.has(i)&&(r=lc.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}},uc=e=>{if("string"!=typeof e||0===e.trim().length)throw new Error("Ledger network is required.");const t=sc(e);return t.startsWith("hedera:")||t.includes("hedera-")||t.includes("hedera_")||"mainnet"===t||"testnet"===t?(e=>{const t=sc(e),r=ac.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):dc(t)};var pc=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(pc||{}),hc=(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))(hc||{});const gc=r.z.nativeEnum(hc),mc=r.z.union([gc,r.z.string()]),fc=r.z.union([r.z.string(),r.z.number(),r.z.boolean(),r.z.null()]),yc=r.z.lazy(()=>r.z.union([fc,r.z.array(yc),r.z.record(yc)])),bc=r.z.object({version:r.z.string(),type:r.z.number(),display_name:r.z.string(),alias:r.z.string().optional(),bio:r.z.string().optional(),socials:r.z.array(yc).optional(),aiAgent:r.z.object({type:r.z.nativeEnum(pc),creator:r.z.string().optional(),model:r.z.string().optional(),capabilities:r.z.array(gc).optional()}).optional(),uaid:r.z.string().optional()}).catchall(yc),wc=r.z.object({uaid:r.z.string().optional(),ledgerAccountId:r.z.string().optional(),userId:r.z.string().optional(),email:r.z.string().optional(),encryptedShare:r.z.string()}),Ic=r.z.object({algorithm:r.z.string(),ciphertext:r.z.string(),nonce:r.z.string(),associatedData:r.z.string().optional(),keyLocator:r.z.object({sessionId:r.z.string().optional(),revision:r.z.number().optional()}).optional(),recipients:r.z.array(wc)}),Tc=r.z.object({keyType:r.z.string(),publicKey:r.z.string(),uaid:r.z.string().optional(),ledgerAccountId:r.z.string().optional(),userId:r.z.string().optional(),email:r.z.string().optional()}),Sc=r.z.object({role:r.z.enum(["requester","responder"]),uaid:r.z.string().optional(),userId:r.z.string().optional(),ledgerAccountId:r.z.string().optional(),keyType:r.z.string(),longTermPublicKey:r.z.string().optional(),ephemeralPublicKey:r.z.string(),signature:r.z.string().optional(),metadata:r.z.record(yc).optional(),submittedAt:r.z.string()}),kc=r.z.object({sessionId:r.z.string(),algorithm:r.z.string(),createdAt:r.z.string(),expiresAt:r.z.number(),status:r.z.enum(["pending","complete"]),requester:Sc.optional(),responder:Sc.optional()}),Ec=r.z.object({enabled:r.z.boolean(),algorithm:r.z.string(),requireCiphertext:r.z.boolean(),requester:Tc.nullable().optional(),responder:Tc.nullable().optional(),handshake:kc.nullable().optional()}),Ac=r.z.object({messageId:r.z.string(),role:r.z.enum(["user","agent"]),content:r.z.string(),timestamp:r.z.string(),cipherEnvelope:Ic.optional(),metadata:r.z.record(yc).optional()}),vc=r.z.record(r.z.array(yc)).optional(),Cc=r.z.object({id:r.z.string(),uaid:r.z.string(),registry:r.z.string(),name:r.z.string(),description:r.z.string().optional(),capabilities:r.z.array(mc),endpoints:r.z.union([r.z.record(yc),r.z.array(r.z.string())]).optional(),metadata:r.z.record(yc).optional(),metadataFacet:vc,profile:bc.optional(),protocols:r.z.array(r.z.string()).optional(),adapter:r.z.string().optional(),originalId:r.z.string().optional(),communicationSupported:r.z.boolean().optional(),routingSupported:r.z.boolean().optional(),available:r.z.boolean().optional(),availabilityStatus:r.z.string().optional(),availabilityCheckedAt:r.z.string().optional(),availabilitySource:r.z.string().optional(),availabilityLatencyMs:r.z.number().optional(),availabilityScore:r.z.number().optional(),capabilityLabels:r.z.array(r.z.string()).optional(),capabilityTokens:r.z.array(r.z.string()).optional(),image:r.z.string().optional(),createdAt:r.z.string().optional(),updatedAt:r.z.string().optional(),lastSeen:r.z.string().optional(),lastIndexed:r.z.string().optional()}).passthrough(),xc=r.z.object({hits:r.z.array(Cc),total:r.z.number(),page:r.z.number(),limit:r.z.number()}),Rc=r.z.object({totalAgents:r.z.number(),registries:r.z.record(r.z.number()),capabilities:r.z.record(r.z.number()),lastUpdate:r.z.string(),status:r.z.string()}),Nc=r.z.object({registries:r.z.array(r.z.string())}),_c=r.z.object({searches:r.z.array(r.z.string())}),Pc=r.z.object({agent:Cc}),Fc=r.z.object({sessionId:r.z.string(),uaid:r.z.string().nullable().optional(),agent:r.z.object({name:r.z.string(),description:r.z.string().optional(),capabilities:r.z.record(yc).nullable().optional(),skills:r.z.array(r.z.string()).optional()}),history:r.z.array(Ac),historyTtlSeconds:r.z.number().nullable().optional(),encryption:Ec.nullable().optional()}),Oc=r.z.object({sessionId:r.z.string(),uaid:r.z.string().nullable().optional(),message:r.z.string(),timestamp:r.z.string(),rawResponse:yc.optional(),content:r.z.string().optional(),history:r.z.array(Ac).optional(),historyTtlSeconds:r.z.number().nullable().optional(),encrypted:r.z.boolean().optional()}),zc=r.z.object({sessionId:r.z.string(),history:r.z.array(Ac),historyTtlSeconds:r.z.number()});r.z.object({preserveEntries:r.z.number().int().min(0).optional()}).strict();const Dc=r.z.object({sessionId:r.z.string(),history:r.z.array(Ac),summaryEntry:Ac,preservedEntries:r.z.array(Ac),historyTtlSeconds:r.z.number(),creditsDebited:r.z.number(),metadata:r.z.record(yc).optional()}),Bc=r.z.object({sessionId:r.z.string(),encryption:Ec.nullable()}),Mc=r.z.object({sessionId:r.z.string(),handshake:kc}),Uc=r.z.object({id:r.z.string(),keyType:r.z.string(),publicKey:r.z.string(),uaid:r.z.string().nullable(),ledgerAccountId:r.z.string().nullable(),ledgerNetwork:r.z.string().nullable().optional(),userId:r.z.string().nullable().optional(),email:r.z.string().nullable().optional(),createdAt:r.z.string(),updatedAt:r.z.string()}),Lc=r.z.object({challengeId:r.z.string(),message:r.z.string(),expiresAt:r.z.string()}),Kc=r.z.object({id:r.z.string(),label:r.z.string().optional(),prefix:r.z.string(),lastFour:r.z.string(),createdAt:r.z.string(),lastUsedAt:r.z.string().nullable().optional(),ownerType:r.z.literal("ledger"),ledgerAccountId:r.z.string().optional(),ledgerNetwork:r.z.string().optional(),ledgerNetworkCanonical:r.z.string().optional()}),$c=r.z.object({key:r.z.string(),apiKey:Kc,accountId:r.z.string(),network:r.z.string(),networkCanonical:r.z.string().optional()}),Hc=r.z.object({protocols:r.z.array(r.z.string())}),qc=r.z.object({protocol:r.z.string().nullable()}),jc=r.z.object({hits:r.z.array(Cc),total:r.z.number(),page:r.z.number().optional(),limit:r.z.number().optional()}),Wc=r.z.union([r.z.string(),r.z.number()]),Vc=r.z.object({capabilities:r.z.array(Wc).optional(),type:r.z.enum(["ai-agents","mcp-servers"]).optional(),registry:r.z.string().optional(),protocols:r.z.array(r.z.string()).optional(),adapter:r.z.array(r.z.string()).optional()}).strict();r.z.object({query:r.z.string(),filter:Vc.optional(),limit:r.z.number().int().min(1).max(100).optional(),offset:r.z.number().int().min(0).optional()}).strict();const Gc=r.z.object({agent:Cc,score:r.z.number().optional(),highlights:r.z.record(r.z.array(r.z.string())).optional()}),Jc=r.z.object({hits:r.z.array(Gc),total:r.z.number(),took:r.z.number(),totalAvailable:r.z.number().optional(),visible:r.z.number().optional(),limited:r.z.boolean().optional(),credits_used:r.z.number().optional()}),Yc=r.z.object({enabled:r.z.boolean(),healthy:r.z.boolean(),mode:r.z.enum(["disabled","initializing","healthy","degraded","error"]),lastUpdated:r.z.string(),details:r.z.record(r.z.any()).optional(),lastError:r.z.object({message:r.z.string(),stack:r.z.string().optional(),timestamp:r.z.string().optional()}).optional()}),Xc=r.z.object({storageMode:r.z.string(),vectorStatus:Yc}),Zc=r.z.object({clients:r.z.number(),stats:r.z.object({totalClients:r.z.number().optional(),clientsByRegistry:r.z.record(r.z.number()).optional(),clientsByEventType:r.z.record(r.z.number()).optional()}).passthrough()}),Qc=r.z.object({p50:r.z.number(),p90:r.z.number(),p95:r.z.number(),p99:r.z.number()}),el=r.z.object({http:r.z.object({requestsTotal:r.z.number(),activeConnections:r.z.number(),requestDuration:Qc}),search:r.z.object({queriesTotal:r.z.number(),queryDuration:Qc}),indexing:r.z.object({agentsTotal:r.z.number(),crawlErrors:r.z.number()}),registration:r.z.object({total:r.z.number(),failures:r.z.number(),duration:Qc}),cache:r.z.object({hits:r.z.number(),misses:r.z.number(),hitRate:r.z.number()}),websocket:r.z.object({connections:r.z.number()})}),tl=r.z.object({uaid:r.z.string(),valid:r.z.boolean(),formats:r.z.array(r.z.string())}),rl=r.z.object({id:r.z.string(),agentId:r.z.string(),protocol:r.z.string(),endpoint:r.z.string(),status:r.z.enum(["connected","disconnected","error"]),metadata:r.z.record(fc).optional(),createdAt:r.z.string()}),il=r.z.object({connected:r.z.boolean(),connection:rl.optional(),adapter:r.z.string().optional(),agentId:r.z.string().optional()}),ol=r.z.object({operatorId:r.z.string().optional(),adapters:r.z.array(r.z.object({name:r.z.string(),version:r.z.string(),status:r.z.string(),agentCount:r.z.number(),lastDiscovery:r.z.string(),registryType:r.z.string(),health:r.z.string()})).optional(),totalAgents:r.z.number().optional(),elasticsearchDocumentCount:r.z.number().optional(),agentsByAdapter:r.z.record(r.z.number()).optional(),agentsByRegistry:r.z.record(r.z.number()).optional(),systemInfo:r.z.object({uptime:r.z.number().optional(),version:r.z.string().optional(),network:r.z.string().optional()}).optional()}),nl=r.z.object({id:r.z.string(),name:r.z.string(),type:r.z.string(),endpoint:r.z.string().optional(),capabilities:r.z.array(mc),registry:r.z.string().optional(),protocol:r.z.string().optional(),profile:bc.optional(),nativeId:r.z.string().optional(),metadata:r.z.record(yc).optional()}),sl=r.z.object({tId:r.z.string().nullable(),sizeBytes:r.z.number().optional()}),al=r.z.object({topicId:r.z.string().optional(),sequenceNumber:r.z.number().optional(),profileReference:r.z.string().optional(),profileTopicId:r.z.string().optional()}).passthrough().nullable().optional(),cl=r.z.object({registry:r.z.string(),status:r.z.enum(["created","duplicate","skipped","error","updated","pending"]),agentId:r.z.string().nullable().optional(),agentUri:r.z.string().nullable().optional(),error:r.z.string().optional(),metadata:r.z.record(yc).optional(),registryKey:r.z.string().optional(),networkId:r.z.string().optional(),networkName:r.z.string().optional(),chainId:r.z.number().optional(),estimatedCredits:r.z.number().nullable().optional(),gasEstimateCredits:r.z.number().nullable().optional(),gasEstimateUsd:r.z.number().nullable().optional(),gasPriceGwei:r.z.number().nullable().optional(),gasLimit:r.z.number().nullable().optional(),creditMode:r.z.enum(["fixed","gas"]).nullable().optional(),minCredits:r.z.number().nullable().optional(),consumedCredits:r.z.number().nullable().optional(),cost:r.z.object({credits:r.z.number(),usd:r.z.number(),eth:r.z.number(),gasUsedWei:r.z.string(),effectiveGasPriceWei:r.z.string().nullable().optional(),transactions:r.z.array(r.z.object({hash:r.z.string(),gasUsedWei:r.z.string(),effectiveGasPriceWei:r.z.string().nullable().optional(),costWei:r.z.string()})).optional()}).optional()}),ll=r.z.object({base:r.z.number(),additional:r.z.number(),total:r.z.number()}),dl=r.z.object({status:r.z.string(),uaid:r.z.string().optional(),transactionId:r.z.string().optional(),consensusTimestamp:r.z.string().optional(),registryTopicId:r.z.string().optional(),topicSequenceNumber:r.z.number().optional(),payloadHash:r.z.string().optional(),profileReference:r.z.string().optional(),tId:r.z.string().optional(),profileSizeBytes:r.z.number().optional(),error:r.z.string().optional()}).passthrough(),ul=r.z.object({key:r.z.string(),registryId:r.z.string().optional(),networkId:r.z.string().optional(),name:r.z.string().optional(),chainId:r.z.number().optional(),label:r.z.string().optional(),estimatedCredits:r.z.number().nullable().optional(),baseCredits:r.z.number().nullable().optional(),gasPortionCredits:r.z.number().nullable().optional(),gasPortionUsd:r.z.number().nullable().optional(),gasEstimateCredits:r.z.number().nullable().optional(),gasEstimateUsd:r.z.number().nullable().optional(),gasPriceGwei:r.z.number().nullable().optional(),gasLimit:r.z.number().nullable().optional(),minCredits:r.z.number().nullable().optional(),creditMode:r.z.string().nullable().optional()}).passthrough(),pl=r.z.object({id:r.z.string(),label:r.z.string(),networks:r.z.array(ul)}),hl=r.z.object({registries:r.z.array(pl)}),gl=r.z.object({success:r.z.literal(!0),status:r.z.enum(["created","duplicate","updated"]).optional(),uaid:r.z.string(),agentId:r.z.string(),message:r.z.string().optional(),registry:r.z.string().optional(),attemptId:r.z.string().nullable().optional(),agent:nl,openConvAI:r.z.object({compatible:r.z.boolean(),hcs11Profile:bc.optional(),bridgeEndpoint:r.z.string().optional()}).optional(),profile:sl.optional(),profileRegistry:al.nullable().optional(),hcs10Registry:dl.nullable().optional(),credits:ll.optional(),additionalRegistries:r.z.array(cl).optional(),additionalRegistryCredits:r.z.array(cl).optional(),additionalRegistryCostPerRegistry:r.z.number().optional()}),ml=r.z.object({success:r.z.literal(!0),status:r.z.literal("pending"),message:r.z.string(),uaid:r.z.string(),agentId:r.z.string(),registry:r.z.string().optional(),attemptId:r.z.string().nullable(),agent:nl,openConvAI:r.z.object({compatible:r.z.boolean(),hcs11Profile:bc.optional(),bridgeEndpoint:r.z.string().optional()}).optional(),profile:sl.optional(),profileRegistry:al.nullable().optional(),hcs10Registry:dl.nullable().optional(),credits:ll,additionalRegistries:r.z.array(cl),additionalRegistryCredits:r.z.array(cl).optional(),additionalRegistryCostPerRegistry:r.z.number().optional()}),fl=r.z.object({success:r.z.literal(!1),status:r.z.literal("partial"),message:r.z.string(),uaid:r.z.string(),agentId:r.z.string(),registry:r.z.string().optional(),attemptId:r.z.string().nullable().optional(),agent:nl,openConvAI:r.z.object({compatible:r.z.boolean(),hcs11Profile:bc.optional(),bridgeEndpoint:r.z.string().optional()}).optional(),profile:sl.optional(),profileRegistry:al.nullable().optional(),hcs10Registry:dl.nullable().optional(),credits:ll.optional(),additionalRegistries:r.z.array(cl).optional(),additionalRegistryCredits:r.z.array(cl).optional(),additionalRegistryCostPerRegistry:r.z.number().optional(),errors:r.z.array(r.z.object({registry:r.z.string(),registryKey:r.z.string().nullable().optional(),error:r.z.string()})).min(1)}),yl=r.z.union([gl,ml,fl]),bl=r.z.object({registryId:r.z.string(),registryKey:r.z.string(),networkId:r.z.string().optional(),networkName:r.z.string().optional(),chainId:r.z.number().optional(),label:r.z.string().optional(),status:r.z.enum(["pending","in_progress","completed","failed"]),error:r.z.string().optional(),credits:r.z.number().nullable().optional(),agentId:r.z.string().nullable().optional(),agentUri:r.z.string().nullable().optional(),metadata:r.z.record(yc).optional(),lastUpdated:r.z.string()}),wl=r.z.object({attemptId:r.z.string(),mode:r.z.enum(["register","update"]),status:r.z.enum(["pending","partial","completed","failed"]),uaid:r.z.string().optional(),agentId:r.z.string().optional(),registryNamespace:r.z.string(),accountId:r.z.string().optional(),startedAt:r.z.string(),completedAt:r.z.string().optional(),primary:r.z.object({status:r.z.enum(["pending","completed","failed"]),finishedAt:r.z.string().optional(),error:r.z.string().optional()}),additionalRegistries:r.z.record(r.z.string(),bl),errors:r.z.array(r.z.string()).optional()}),Il=r.z.object({progress:wl}),Tl=r.z.object({accountId:r.z.string().nullable().optional(),registry:r.z.string().optional(),protocol:r.z.string().optional(),requiredCredits:r.z.number(),availableCredits:r.z.number().nullable().optional(),shortfallCredits:r.z.number().nullable().optional(),creditsPerHbar:r.z.number().nullable().optional(),estimatedHbar:r.z.number().nullable().optional()}),Sl=r.z.object({success:r.z.boolean().optional(),purchaser:r.z.string(),credits:r.z.number(),hbarAmount:r.z.number(),transactionId:r.z.string(),consensusTimestamp:r.z.string().nullable().optional()}),kl=r.z.object({success:r.z.boolean().optional(),transaction:r.z.string().optional(),network:r.z.string().optional(),payer:r.z.string().optional(),errorReason:r.z.string().optional()}).strict(),El=r.z.object({success:r.z.boolean(),accountId:r.z.string(),creditedCredits:r.z.number(),usdAmount:r.z.number(),balance:r.z.number(),payment:r.z.object({payer:r.z.string().optional(),requirement:r.z.record(yc).optional(),settlement:kl.optional()}).optional()}),Al=r.z.object({minimums:r.z.record(r.z.object({network:r.z.string().optional(),gasLimit:r.z.number().optional(),gasPriceWei:r.z.string().optional(),gasUsd:r.z.number().optional(),minUsd:r.z.number().optional(),ethUsd:r.z.number().optional(),fetchedAt:r.z.string().optional(),source:r.z.string().optional()})).optional(),creditUnitUsd:r.z.number().optional()}),vl=r.z.object({adapters:r.z.array(r.z.string())}),Cl=r.z.object({supportsChat:r.z.boolean(),delivery:r.z.string().optional(),transport:r.z.string().optional(),streaming:r.z.boolean().optional(),requiresAuth:r.z.array(r.z.string()).optional(),notes:r.z.string().optional()}),xl=r.z.object({discovery:r.z.boolean(),routing:r.z.boolean(),communication:r.z.boolean(),translation:r.z.boolean(),protocols:r.z.array(r.z.string())}),Rl=r.z.object({id:r.z.string(),name:r.z.string(),version:r.z.string(),author:r.z.string(),description:r.z.string(),supportedProtocols:r.z.array(r.z.string()),registryType:r.z.enum(["web2","web3","hybrid"]),chatProfile:Cl.optional(),capabilities:xl,enabled:r.z.boolean(),priority:r.z.number(),status:r.z.enum(["running","stopped"])}),Nl=r.z.object({adapters:r.z.array(Rl)}),_l=r.z.object({value:r.z.union([r.z.string(),r.z.number(),r.z.boolean()]),label:r.z.string()}),Pl=r.z.object({key:r.z.string(),label:r.z.string(),description:r.z.string().optional(),type:r.z.enum(["string","boolean","number"]),adapters:r.z.array(r.z.string()).optional(),options:r.z.array(_l).optional()}),Fl=r.z.object({facets:r.z.array(Pl)}),Ol=e=>new Error(`${e} is not supported by the in-memory signer`),zl=e=>{const t=Bl(),{AccountId:r,LedgerId:i,PrivateKey:o,SignerSignature:n}=t;if(!e.privateKey)throw new Error("privateKey is required to create a ledger signer.");if(!e.accountId)throw new Error("accountId is required to create a ledger signer.");const s=r.fromString(e.accountId),a=o.fromString(e.privateKey),c=i.fromString(e.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 n({publicKey:a.publicKey,signature:t,accountId:s})})),getAccountBalance:async()=>{throw Ol("getAccountBalance")},getAccountInfo:async()=>{throw Ol("getAccountInfo")},getAccountRecords:async()=>{throw Ol("getAccountRecords")},signTransaction:async e=>{throw Ol("signTransaction")},checkTransaction:async e=>{throw Ol("checkTransaction")},populateTransaction:async e=>{throw Ol("populateTransaction")},call:async e=>{throw Ol("call")}}};let Dl=null;const Bl=()=>{if(Dl)return Dl;const e=void 0!=={url:"undefined"==typeof document?require("url").pathToFileURL(__filename).href:T&&"SCRIPT"===T.tagName.toUpperCase()&&T.src||new URL("standards-sdk.cjs",document.baseURI).href}&&"string"==typeof("undefined"==typeof document?require("url").pathToFileURL(__filename).href:T&&"SCRIPT"===T.tagName.toUpperCase()&&T.src||new URL("standards-sdk.cjs",document.baseURI).href)?"undefined"==typeof document?require("url").pathToFileURL(__filename).href:T&&"SCRIPT"===T.tagName.toUpperCase()&&T.src||new URL("standards-sdk.cjs",document.baseURI).href:void 0,t=("function"==typeof require?require:null)??y.createRequire(e??`${process.cwd()}/.hol-rb-client.cjs`);try{const e=t("@hashgraph/sdk");return Dl=e,e}catch(r){const e=new Error("@hashgraph/sdk is required for ledger signing. Install it as a dependency to enable createPrivateKeySigner.");throw e.cause=r,e}},Ml=()=>"function"==typeof DOMException?new DOMException("Aborted","AbortError"):new Error("The operation was aborted"),Ul=/application\/json/i,Ll=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:Ll(e));if("object"==typeof e){const t={};return Object.entries(e).forEach(([e,r])=>{void 0!==r&&(t[e]=Ll(r))}),t}throw new TypeError("Only JSON-compatible values are supported")},Kl=e=>"object"==typeof e&&null!==e&&!Array.isArray(e),$l=e=>{const t=Ll(e);if(Kl(t))return t;throw new TypeError("Expected JSON object value")},Hl=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},ql=e=>{const t={profile:$l(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=$l(e.metadata)),t};class jl extends Error{constructor(e,t){super(e),this.status=t.status,this.statusText=t.statusText,this.body=t.body}}class Wl extends Error{constructor(e,t,r){super(e),this.cause=t,this.rawValue=r}}class Vl{constructor(e={}){this.conversationContexts=new Map,this.request=async(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 o=await this.fetchImpl(this.buildUrl(e),i);if(o.ok)return o;const n=await this.extractErrorBody(o);throw new jl("Registry broker request failed",{status:o.status,statusText:o.statusText,body:n})},this.baseUrl=function(e){const t=e?.trim();let r=t&&t.length>0?t:"https://hol.org/registry/api/v1";try{const e=new URL(r.replace(/\/+$/,"")),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=r.replace(/\/+$/,"");return/\/api\/v\d+$/i.test(i)?i:/\/api$/i.test(i)?`${i}/v1`:`${i}/api/v1`}(e.baseUrl);const t=e.fetchImplementation??globalThis.fetch;if(!t)throw new Error("A fetch implementation is required for RegistryBrokerClient");this.fetchImpl=t,this.defaultHeaders={},e.defaultHeaders&&Object.entries(e.defaultHeaders).forEach(([e,t])=>{"string"==typeof t&&this.setDefaultHeader(e,t)}),e.apiKey&&e.apiKey.trim().length>0&&this.setApiKey(e.apiKey),e.ledgerApiKey&&e.ledgerApiKey.trim().length>0&&this.setLedgerApiKey(e.ledgerApiKey),this.registrationAutoTopUp=e.registrationAutoTopUp,this.historyAutoTopUp=e.historyAutoTopUp,this.encryptedChatManager=new Gl(this),this.encryptionOptions=e.encryption,this.encryptionBootstrapPromise=this.bootstrapEncryptionOptions(e.encryption),this.chat={start:e=>this.startChat(e),createSession:e=>this.createSession(e),sendMessage:e=>this.sendMessage(e),endSession:e=>this.endSession(e),getHistory:(e,t)=>this.fetchHistorySnapshot(e,t),compactHistory:e=>this.compactHistory(e),getEncryptionStatus:e=>this.fetchEncryptionStatus(e),submitEncryptionHandshake:(e,t)=>this.postEncryptionHandshake(e,t),startConversation:e=>this.startConversation(e),acceptConversation:e=>this.acceptConversation(e)},this.encryption={registerKey:e=>this.registerEncryptionKey(e),generateEphemeralKeyPair:()=>this.createEphemeralKeyPair(),deriveSharedSecret:e=>this.deriveSharedSecret(e),encryptCipherEnvelope:e=>this.buildCipherEnvelope(e),decryptCipherEnvelope:e=>this.openCipherEnvelope(e),ensureAgentKey:e=>this.ensureAgentEncryptionKey(e)},this.chat.createEncryptedSession=e=>this.encryptedChatManager.startSession(e),this.chat.acceptEncryptedSession=e=>this.encryptedChatManager.acceptSession(e)}static async initializeAgent(e){const{uaid:t,ensureEncryptionKey:r=!0,...i}=e,o=new Vl(i);let n=null;if(r){const e="object"==typeof r?r:{generateIfMissing:!0};n=await o.encryption.ensureAgentKey({uaid:t,...e})}return{client:o,encryption:n}}setApiKey(e){this.setDefaultHeader("x-api-key",e)}setLedgerApiKey(e){this.setDefaultHeader("x-ledger-api-key",e)}setDefaultHeader(e,t){if(!e||0===e.trim().length)return;const r=(e=>e.trim().toLowerCase())(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}async search(e={}){const t=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}`:""}(e),r=await this.requestJson(`/search${t}`,{method:"GET"});return this.parseWithSchema(r,xc,"search response")}async stats(){const e=await this.requestJson("/stats",{method:"GET"});return this.parseWithSchema(e,Rc,"stats response")}async registries(){const e=await this.requestJson("/registries",{method:"GET"});return this.parseWithSchema(e,Nc,"registries response")}async getAdditionalRegistries(){const e=await this.requestJson("/register/additional-registries",{method:"GET"});return this.parseWithSchema(e,hl,"additional registry catalog response")}bootstrapEncryptionOptions(e){return e?.autoRegister&&!1!==e.autoRegister.enabled?this.autoRegisterEncryptionKey(e.autoRegister).then(()=>{}):null}async autoRegisterEncryptionKey(e){const t=this.normalizeAutoRegisterIdentity(e);if(!t)throw new Error("Auto-registration requires uaid, ledgerAccountId, or email");const r=await this.resolveAutoRegisterKeyMaterial(e);if(!r)throw new Error("Unable to resolve encryption public key for auto-registration");return await this.registerEncryptionKey({keyType:e.keyType??"secp256k1",publicKey:r.publicKey,...t}),r}normalizeAutoRegisterIdentity(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}async resolveAutoRegisterKeyMaterial(e){if(e.publicKey?.trim())return{publicKey:e.publicKey.trim()};let t=e.privateKey?.trim();const r=e.envVar??"RB_ENCRYPTION_PRIVATE_KEY";if(!t&&r&&process?.env?.[r]?.trim()&&(t=process.env[r]?.trim()),!t&&e.generateIfMissing){const t=await this.generateEncryptionKeyPair({keyType:e.keyType??"secp256k1",envVar:r,envPath:e.envPath,overwrite:e.overwriteEnv});return r&&(process.env[r]=t.privateKey),{publicKey:t.publicKey,privateKey:t.privateKey}}if(t){return{publicKey:this.derivePublicKeyFromPrivateKey(t),privateKey:t}}return null}derivePublicKeyFromPrivateKey(e){const t=this.hexToBuffer(e),r=h.secp256k1.getPublicKey(t,!0);return u.Buffer.from(r).toString("hex")}ensureAgentEncryptionKey(e){return this.autoRegisterEncryptionKey({...e,uaid:e.uaid,enabled:!0})}async popularSearches(){const e=await this.requestJson("/popular",{method:"GET"});return this.parseWithSchema(e,_c,"popular searches response")}async resolveUaid(e){const t=await this.requestJson(`/resolve/${encodeURIComponent(e)}`,{method:"GET"});return this.parseWithSchema(t,Pc,"resolve UAID response")}async performRegisterAgent(e){const t=await this.requestJson("/register",{method:"POST",body:ql(e),headers:{"content-type":"application/json"}});return this.parseWithSchema(t,yl,"register agent response")}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(o){if(this.extractInsufficientCreditsDetails(o)&&!i){await this.ensureCreditsForRegistration(e,r),i=!0;continue}throw o}}async getRegistrationQuote(e){const t=await this.requestJson("/register/quote",{method:"POST",body:ql(e),headers:{"content-type":"application/json"}});return this.parseWithSchema(t,Tl,"registration quote response")}async updateAgent(e,t){const r=await this.requestJson(`/register/${encodeURIComponent(e)}`,{method:"PUT",body:ql(t),headers:{"content-type":"application/json"}});return this.parseWithSchema(r,yl,"update agent response")}async getRegistrationProgress(e){const t=e.trim();if(!t)throw new Error("attemptId is required");try{const e=await this.requestJson(`/register/progress/${encodeURIComponent(t)}`,{method:"GET"});return this.parseWithSchema(e,Il,"registration progress response").progress}catch(r){if(r instanceof jl&&404===r.status)return null;throw r}}async waitForRegistrationCompletion(e,t={}){const r=e.trim();if(!r)throw new Error("attemptId is required");const i=Math.max(250,t.intervalMs??1500),o=t.timeoutMs??3e5,n=t.throwOnFailure??!0,s=t.signal,a=Date.now();for(;;){if(s?.aborted)throw Ml();const e=await this.getRegistrationProgress(r);if(e){if(t.onProgress?.(e),"completed"===e.status)return e;if("partial"===e.status||"failed"===e.status){if(n)throw new jl("Registration did not complete successfully",{status:409,statusText:e.status,body:e});return e}}if(Date.now()-a>=o)throw new Error(`Registration progress polling timed out after ${o}ms`);await this.delay(i,s)}}async purchaseCreditsWithHbar(e){const t={accountId:e.accountId,payerKey:e.privateKey,hbarAmount:this.calculateHbarAmountParam(e.hbarAmount)};e.memo&&(t.memo=e.memo),e.metadata&&(t.metadata=e.metadata);const r=await this.requestJson("/credits/purchase",{method:"POST",headers:{"content-type":"application/json"},body:t});return this.parseWithSchema(r,Sl,"credit purchase response")}async getX402Minimums(){const e=await this.requestJson("/credits/purchase/x402/minimums",{method:"GET"});return this.parseWithSchema(e,Al,"x402 minimums response")}async purchaseCreditsWithX402(e){if(!Number.isFinite(e.credits)||e.credits<=0)throw new Error("credits must be a positive number");if(void 0!==e.usdAmount&&(!Number.isFinite(e.usdAmount)||e.usdAmount<=0))throw new Error("usdAmount must be a positive number when provided");const t={accountId:e.accountId,credits:e.credits};void 0!==e.usdAmount&&(t.usdAmount=e.usdAmount),e.description&&(t.description=e.description),e.metadata&&(t.metadata=e.metadata);const r=o.create({baseURL:this.baseUrl,headers:{...this.getDefaultHeaders(),"content-type":"application/json"}}),i=m.withPaymentInterceptor(r,e.walletClient),n=await i.post("/credits/purchase/x402",t),s=this.parseWithSchema(n.data,El,"x402 credit purchase response"),a="string"==typeof n.headers["x-payment-response"]?n.headers["x-payment-response"]:void 0;return{...s,paymentResponseHeader:a,paymentResponse:void 0!==a?m.decodeXPaymentResponse(a):void 0}}async buyCreditsWithX402(e){const t=e.network??"base",r=(e=>{const t=e.trim();if(!t)throw new Error("evmPrivateKey is required");return t.startsWith("0x")?t:`0x${t}`})(e.evmPrivateKey),i=await f.createSigner(t,r);return this.purchaseCreditsWithX402({accountId:e.accountId,credits:e.credits,usdAmount:e.usdAmount,description:e.description,metadata:e.metadata,walletClient:i})}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)}calculateHbarAmountParam(e){const t=Math.ceil(1e8*e);if(t<=0)throw new Error("Calculated purchase amount must be positive");return t/1e8}shouldAutoTopUpHistory(e,t){if(!this.historyAutoTopUp||void 0===e.historyTtlSeconds)return!1;if(!(t instanceof jl))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")}extractErrorMessage(e){return"string"==typeof e?e:Kl(e)&&"string"==typeof e.error?e.error:Kl(e)&&"string"==typeof e.message?e.message:void 0}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}})}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 o=this.resolveCreditsToPurchase(i);if(o<=0)return;const n=t.creditsPerHbar??null;if(!n||n<=0)throw new Error("Unable to determine credits per HBAR for auto top-up");const s=this.calculateHbarAmount(o,n);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:o}})}if(((await this.getRegistrationQuote(e)).shortfallCredits??0)>0)throw new Error("Unable to purchase sufficient credits for registration")}extractInsufficientCreditsDetails(e){if(!(e instanceof jl)||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}}async createLedgerChallenge(e){const t=uc(e.network),r="hedera"===t.kind?t.hederaNetwork??t.canonical:t.canonical,i=await this.requestJson("/auth/ledger/challenge",{method:"POST",headers:{"content-type":"application/json"},body:{accountId:e.accountId,network:r}});return this.parseWithSchema(i,Lc,"ledger challenge response")}async verifyLedgerChallenge(e){const t=uc(e.network),r="hedera"===t.kind?t.hederaNetwork??t.canonical:t.canonical,i={challengeId:e.challengeId,accountId:e.accountId,network:r,signature:e.signature};e.signatureKind&&(i.signatureKind=e.signatureKind),e.publicKey&&(i.publicKey=e.publicKey),"number"==typeof e.expiresInMinutes&&(i.expiresInMinutes=e.expiresInMinutes);const o=await this.requestJson("/auth/ledger/verify",{method:"POST",headers:{"content-type":"application/json"},body:i}),n=this.parseWithSchema(o,$c,"ledger verification response");return this.setLedgerApiKey(n.key),n}async authenticateWithLedger(e){const t=await this.createLedgerChallenge({accountId:e.accountId,network:e.network}),r=await this.resolveLedgerAuthSignature(t.message,e);return await this.verifyLedgerChallenge({challengeId:t.challengeId,accountId:e.accountId,network:e.network,signature:r.signature,signatureKind:r.signatureKind,publicKey:r.publicKey,expiresInMinutes:e.expiresInMinutes})}async resolveLedgerAuthSignature(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=u.Buffer.from(e,"utf8"),i=await t.signer.sign([r]),o=i?.[0];if(!o)throw new Error("Signer did not return any signatures.");let n;if(o.publicKey)n=o.publicKey.toString();else if("function"==typeof t.signer.getAccountKey){const e=await t.signer.getAccountKey();e&&"function"==typeof e.toString&&(n=e.toString())}return{signature:u.Buffer.from(o.signature).toString("base64"),signatureKind:"raw",publicKey:n}}async authenticateWithLedgerCredentials(e){const{accountId:t,network:r,signer:i,sign:o,hederaPrivateKey:n,evmPrivateKey:s,expiresInMinutes:a,setAccountHeader:c=!0,label:l,logger:d}=e,u=uc(r),p=l?` for ${l}`:"",h={accountId:t,network:u.canonical,expiresInMinutes:a};if(o)h.sign=o;else if(i)h.signer=i;else if(n){if("hedera"!==u.kind||!u.hederaNetwork)throw new Error("hederaPrivateKey can only be used with hedera:mainnet or hedera:testnet networks.");h.signer=zl({accountId:t,privateKey:n,network:u.hederaNetwork})}else{if(!s)throw new Error("Provide a signer, sign function, hederaPrivateKey, or evmPrivateKey to authenticate with the ledger.");{if("evm"!==u.kind)throw new Error("evmPrivateKey can only be used with CAIP-2 EVM networks (eip155:<chainId>).");const e=s.startsWith("0x")?s:`0x${s}`,t=g.privateKeyToAccount(e);h.sign=async e=>({signature:await t.signMessage({message:e}),signatureKind:"evm",publicKey:t.publicKey})}}d?.info?.(`Authenticating ledger account ${t} (${u.canonical})${p}...`);const m=await this.authenticateWithLedger(h);return c&&this.setDefaultHeader("x-account-id",m.accountId),d?.info?.(`Ledger authentication complete${p}. Issued key prefix: ${m.apiKey.prefix}…${m.apiKey.lastFour}`),m}async listProtocols(){const e=await this.requestJson("/protocols",{method:"GET"});return this.parseWithSchema(e,Hc,"protocols response")}async detectProtocol(e){const t=await this.requestJson("/detect-protocol",{method:"POST",body:{message:e},headers:{"content-type":"application/json"}});return this.parseWithSchema(t,qc,"detect protocol response")}async registrySearchByNamespace(e,t){const r=new URLSearchParams;t&&r.set("q",t);const i=r.size>0?`?${r.toString()}`:"",o=await this.requestJson(`/registries/${encodeURIComponent(e)}/search${i}`,{method:"GET"});return this.parseWithSchema(o,jc,"registry search response")}async vectorSearch(e){try{const t=await this.requestJson("/search",{method:"POST",body:e,headers:{"content-type":"application/json"}});return this.parseWithSchema(t,Jc,"vector search response")}catch(t){if(t instanceof jl&&501===t.status){const t=await this.search(this.buildVectorFallbackSearchParams(e));return this.convertSearchResultToVectorResponse(t)}throw t}}async searchStatus(){const e=await this.requestJson("/search/status",{method:"GET"});return this.parseWithSchema(e,Xc,"search status response")}async adaptersDetailed(){const e=await this.requestJson("/adapters/details",{method:"GET"});return this.parseWithSchema(e,Nl,"adapter details response")}async websocketStats(){const e=await this.requestJson("/websocket/stats",{method:"GET"});return this.parseWithSchema(e,Zc,"websocket stats response")}async metricsSummary(){const e=await this.requestJson("/metrics",{method:"GET"});return this.parseWithSchema(e,el,"metrics summary response")}async validateUaid(e){const t=await this.requestJson(`/uaids/validate/${encodeURIComponent(e)}`,{method:"GET"});return this.parseWithSchema(t,tl,"UAID validation response")}async getUaidConnectionStatus(e){const t=await this.requestJson(`/uaids/connections/${encodeURIComponent(e)}/status`,{method:"GET"});return this.parseWithSchema(t,il,"UAID connection status")}async closeUaidConnection(e){await this.request(`/uaids/connections/${encodeURIComponent(e)}`,{method:"DELETE"})}async dashboardStats(){const e=await this.requestJson("/dashboard/stats",{method:"GET"});return this.parseWithSchema(e,ol,"dashboard stats response")}async adapters(){const e=await this.requestJson("/adapters",{method:"GET"});return this.parseWithSchema(e,vl,"adapters response")}async facets(e){const t=new URLSearchParams;e&&t.set("adapter",e);const r=t.size>0?`?${t.toString()}`:"",i=await this.requestJson(`/search/facets${r}`,{method:"GET"});return this.parseWithSchema(i,Fl,"search facets response")}async createSession(e,t=!0){const r={};"uaid"in e&&e.uaid&&(r.uaid=e.uaid),"agentUrl"in e&&e.agentUrl&&(r.agentUrl=e.agentUrl),e.auth&&(r.auth=Hl(e.auth)),void 0!==e.historyTtlSeconds&&(r.historyTtlSeconds=e.historyTtlSeconds),void 0!==e.encryptionRequested&&(r.encryptionRequested=e.encryptionRequested),e.senderUaid&&(r.senderUaid=e.senderUaid);try{const e=await this.requestJson("/chat/session",{method:"POST",body:r,headers:{"content-type":"application/json"}});return this.parseWithSchema(e,Fc,"chat session response")}catch(i){if(t&&this.shouldAutoTopUpHistory(e,i))return await this.executeHistoryAutoTopUp("chat.session"),this.createSession(e,!1);throw i}}async startChat(e){if("uaid"in e&&e.uaid)return this.startConversation({uaid:e.uaid,senderUaid:e.senderUaid,historyTtlSeconds:e.historyTtlSeconds,auth:e.auth,encryption:e.encryption,onSessionCreated:e.onSessionCreated});if("agentUrl"in e&&e.agentUrl){const t=await this.createSession({agentUrl:e.agentUrl,auth:e.auth,historyTtlSeconds:e.historyTtlSeconds,senderUaid:e.senderUaid});return e.onSessionCreated?.(t.sessionId),this.createPlaintextConversationHandle(t.sessionId,t.encryption??null,e.auth,{agentUrl:e.agentUrl,uaid:e.uaid})}throw new Error("startChat requires either uaid or agentUrl")}async startConversation(e){const t=e.encryption?.preference??"preferred";if(!("disabled"!==t)){const t=await this.createSession({uaid:e.uaid,auth:e.auth,historyTtlSeconds:e.historyTtlSeconds,senderUaid:e.senderUaid,encryptionRequested:!1});return e.onSessionCreated?.(t.sessionId),this.createPlaintextConversationHandle(t.sessionId,t.encryption??null,e.auth,{uaid:e.uaid})}try{return await this.encryptedChatManager.startSession({uaid:e.uaid,senderUaid:e.senderUaid,historyTtlSeconds:e.historyTtlSeconds,handshakeTimeoutMs:e.encryption?.handshakeTimeoutMs,pollIntervalMs:e.encryption?.pollIntervalMs,onSessionCreated:t=>{e.onSessionCreated?.(t)},auth:e.auth})}catch(r){if(r instanceof Jl){if("required"===t)throw r;return this.createPlaintextConversationHandle(r.sessionId,r.summary??null,e.auth,{uaid:e.uaid})}throw r}}async acceptConversation(e){const t=e.encryption?.preference??"preferred";if("disabled"===t)return this.createPlaintextConversationHandle(e.sessionId,null);try{return await this.encryptedChatManager.acceptSession({sessionId:e.sessionId,responderUaid:e.responderUaid,handshakeTimeoutMs:e.encryption?.handshakeTimeoutMs,pollIntervalMs:e.encryption?.pollIntervalMs})}catch(r){if(r instanceof Jl&&"required"!==t)return this.createPlaintextConversationHandle(e.sessionId,null,void 0,{uaid:e.responderUaid});throw r}}async fetchHistorySnapshot(e,t){if(!e||0===e.trim().length)throw new Error("sessionId is required to fetch chat history");const r=await this.requestJson(`/chat/session/${encodeURIComponent(e)}/history`,{method:"GET"}),i=this.parseWithSchema(r,zc,"chat history snapshot response");return this.attachDecryptedHistory(e,i,t)}attachDecryptedHistory(e,t,r){if(!(void 0!==r?.decrypt?r.decrypt:!0===this.encryptionOptions?.autoDecryptHistory))return t;const i=this.resolveDecryptionContext(e,r);if(!i)throw new Error("Unable to decrypt chat history: encryption context unavailable");const o=t.history.map(t=>({entry:t,plaintext:this.decryptHistoryEntryFromContext(e,t,i)}));return{...t,decryptedHistory:o}}registerConversationContext(e){const t={sessionId:e.sessionId,sharedSecret:u.Buffer.from(e.sharedSecret),identity:e.identity?{...e.identity}:void 0},r=this.conversationContexts.get(e.sessionId)??[],i=r.findIndex(e=>this.identitiesMatch(e.identity,t.identity));i>=0?r[i]=t:r.push(t),this.conversationContexts.set(e.sessionId,r)}registerConversationContextForEncryption(e){this.registerConversationContext(e)}resolveDecryptionContext(e,t){if(t?.sharedSecret)return{sessionId:e,sharedSecret:this.normalizeSharedSecret(t.sharedSecret),identity:t.identity};const r=this.conversationContexts.get(e);if(!r||0===r.length)return null;if(t?.identity){const e=r.find(e=>this.identitiesMatch(e.identity,t.identity));if(e)return e}return r[0]}decryptHistoryEntryFromContext(e,t,r){const i=t.cipherEnvelope;if(!i)return t.content;const o=u.Buffer.from(r.sharedSecret);try{return this.encryption.decryptCipherEnvelope({envelope:i,sharedSecret:o})}catch(n){return null}}identitiesMatch(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()))))}identityMatchesRecipient(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())))}createPlaintextConversationHandle(e,t,r,i){const o=i?.uaid?.trim(),n=i?.agentUrl?.trim();return{sessionId:e,mode:"plaintext",summary:t??null,send:async t=>{const i=t.plaintext;if(!i||0===i.trim().length)throw new Error("plaintext is required for chat messages");const s=t.message??i;return this.sendMessage({sessionId:e,message:s,streaming:t.streaming,auth:t.auth??r,uaid:o,agentUrl:n})},decryptHistoryEntry:e=>e.content}}async compactHistory(e){if(!e.sessionId||0===e.sessionId.trim().length)throw new Error("sessionId is required to compact chat history");const t={};"number"==typeof e.preserveEntries&&Number.isFinite(e.preserveEntries)&&e.preserveEntries>=0&&(t.preserveEntries=Math.floor(e.preserveEntries));const r=await this.requestJson(`/chat/session/${encodeURIComponent(e.sessionId)}/compact`,{method:"POST",headers:{"content-type":"application/json"},body:t});return this.parseWithSchema(r,Dc,"chat history compaction response")}async fetchEncryptionStatus(e){if(!e||0===e.trim().length)throw new Error("sessionId is required for encryption status");const t=await this.requestJson(`/chat/session/${encodeURIComponent(e)}/encryption`,{method:"GET"});return this.parseWithSchema(t,Bc,"session encryption status response")}async postEncryptionHandshake(e,t){if(!e||0===e.trim().length)throw new Error("sessionId is required for encryption handshake");const r=await this.requestJson(`/chat/session/${encodeURIComponent(e)}/encryption-handshake`,{method:"POST",headers:{"content-type":"application/json"},body:{role:t.role,keyType:t.keyType,ephemeralPublicKey:t.ephemeralPublicKey,longTermPublicKey:t.longTermPublicKey,signature:t.signature,uaid:t.uaid,userId:t.userId,ledgerAccountId:t.ledgerAccountId,metadata:t.metadata}});return this.parseWithSchema(r,Mc,"encryption handshake response").handshake}async registerEncryptionKey(e){const t=await this.requestJson("/encryption/keys",{method:"POST",headers:{"content-type":"application/json"},body:e});return this.parseWithSchema(t,Uc,"register encryption key response")}async sendMessage(e){const t={message:e.message};void 0!==e.streaming&&(t.streaming=e.streaming),e.auth&&(t.auth=Hl(e.auth)),"uaid"in e&&(t.uaid=e.uaid),"sessionId"in e&&e.sessionId&&(t.sessionId=e.sessionId),"agentUrl"in e&&e.agentUrl&&(t.agentUrl=e.agentUrl);let r=e.cipherEnvelope??null;if(e.encryption){const i=e.encryption.sessionId??("string"==typeof t.sessionId?t.sessionId:void 0);if(!i)throw new Error("sessionId is required when using encrypted chat payloads");if(!e.encryption.recipients?.length)throw new Error("recipients are required for encrypted chat payloads");r=this.encryption.encryptCipherEnvelope({...e.encryption,sessionId:i})}r&&(t.cipherEnvelope=r),delete t.encryption;const i=await this.requestJson("/chat/message",{method:"POST",body:t,headers:{"content-type":"application/json"}});return this.parseWithSchema(i,Oc,"chat message response")}async endSession(e){await this.request(`/chat/session/${encodeURIComponent(e)}`,{method:"DELETE"})}async generateEncryptionKeyPair(e={}){this.assertNodeRuntime("generateEncryptionKeyPair");if("secp256k1"!==(e.keyType??"secp256k1"))throw new Error("Only secp256k1 key generation is supported currently");const t=p.randomBytes(32),r=u.Buffer.from(t).toString("hex"),i=h.secp256k1.getPublicKey(t,!0),o=u.Buffer.from(i).toString("hex"),n=e.envVar??"RB_ENCRYPTION_PRIVATE_KEY",s=e.envPath?k.resolve(e.envPath):void 0;if(s){const t=(()=>{if("function"!=typeof require)return null;try{const e=require("node:fs");if(e&&"function"==typeof e.existsSync&&"function"==typeof e.readFileSync&&"function"==typeof e.writeFileSync&&"function"==typeof e.appendFileSync)return e}catch{}return null})();if(!t)throw new Error("File system module is not available; cannot write encryption key env file");const i=`${n}=${r}`;if(t.existsSync(s)){const r=t.readFileSync(s,"utf-8"),o=new RegExp(`^${n}=.*$`,"m");if(o.test(r)){if(!e.overwrite)throw new Error(`${n} already exists in ${s}; set overwrite=true to replace it`);const a=r.replace(o,i);t.writeFileSync(s,a)}else{const e=!r.endsWith("\n");t.appendFileSync(s,`${e?"\n":""}${i}\n`)}}else t.writeFileSync(s,`${i}\n`)}return{privateKey:r,publicKey:o,envPath:s,envVar:n}}buildUrl(e){const t=e.startsWith("/")?e:`/${e}`;return`${this.baseUrl}${t}`}buildVectorFallbackSearchParams(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}convertSearchResultToVectorResponse(e){const t=e.hits.map(e=>({agent:e,score:0,highlights:{}})),r=e.total,i=e.limit,o=e.page,n=r>o*i||o>1;return{hits:t,total:r,took:0,totalAvailable:r,visible:t.length,limited:n,credits_used:0}}async delay(e,t){if(e<=0){if(t?.aborted)throw Ml()}else await new Promise((r,i)=>{const o=setTimeout(()=>{t&&t.removeEventListener("abort",n),r()},e),n=()=>{clearTimeout(o),t?.removeEventListener("abort",n),i(Ml())};if(t){if(t.aborted)return clearTimeout(o),void i(Ml());t.addEventListener("abort",n,{once:!0})}})}async requestJson(e,t){const r=await this.request(e,t),i=r.headers?.get("content-type")??"";if(!Ul.test(i)){const e=await r.text();throw new Wl("Expected JSON response from registry broker",e)}return await r.json()}async extractErrorBody(e){const t=e.headers?.get("content-type")??"";if(Ul.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,t,i){try{return t.parse(e)}catch(o){throw new Wl(`Failed to parse ${i}`,o instanceof r.ZodError||o instanceof Error?o:String(o),e)}}assertNodeRuntime(e){if("undefined"==typeof process||!process.versions?.node)throw new Error(`${e} is only available in Node.js environments`)}createEphemeralKeyPair(){this.assertNodeRuntime("generateEphemeralKeyPair");const e=p.randomBytes(32),t=h.secp256k1.getPublicKey(e,!0);return{privateKey:u.Buffer.from(e).toString("hex"),publicKey:u.Buffer.from(t).toString("hex")}}deriveSharedSecret(e){this.assertNodeRuntime("deriveSharedSecret");const t=this.hexToBuffer(e.privateKey),r=this.hexToBuffer(e.peerPublicKey),i=h.secp256k1.getSharedSecret(t,r,!0);return p.createHash("sha256").update(u.Buffer.from(i)).digest()}buildCipherEnvelope(e){this.assertNodeRuntime("encryptCipherEnvelope");const t=this.normalizeSharedSecret(e.sharedSecret),r=p.randomBytes(12),i=p.createCipheriv("aes-256-gcm",t,r),o=e.associatedData??e.sessionId,n=o?u.Buffer.from(o,"utf8").toString("base64"):void 0;o&&i.setAAD(u.Buffer.from(o,"utf8"));const s=u.Buffer.concat([i.update(u.Buffer.from(e.plaintext,"utf8")),i.final()]),a=i.getAuthTag();return{algorithm:"aes-256-gcm",ciphertext:u.Buffer.concat([s,a]).toString("base64"),nonce:r.toString("base64"),associatedData:n,keyLocator:{sessionId:e.sessionId,revision:e.revision??1},recipients:e.recipients.map(e=>({...e,encryptedShare:""}))}}openCipherEnvelope(e){this.assertNodeRuntime("decryptCipherEnvelope");const t=this.normalizeSharedSecret(e.sharedSecret),r=u.Buffer.from(e.envelope.ciphertext,"base64"),i=u.Buffer.from(e.envelope.nonce,"base64"),o=r.slice(0,r.length-16),n=r.slice(r.length-16),s=p.createDecipheriv("aes-256-gcm",t,i);e.envelope.associatedData&&s.setAAD(u.Buffer.from(e.envelope.associatedData,"base64")),s.setAuthTag(n);return u.Buffer.concat([s.update(o),s.final()]).toString(e.encoding??"utf8")}normalizeSharedSecret(e){if(u.Buffer.isBuffer(e))return u.Buffer.from(e);if(e instanceof Uint8Array)return u.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?u.Buffer.from(r,"hex"):u.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 u.Buffer.from(t,"hex")}}class Gl{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 Jl(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),o=i.responder?.ephemeralPublicKey;if(!o)throw new Error("Responder handshake was not completed in time");const n=this.client.encryption.deriveSharedSecret({privateKey:t.privateKey,peerPublicKey:o}).subarray(),s=this.buildRecipients(r);return this.createHandle({sessionId:e.sessionId,sharedSecret:n,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),o=i.requester?.ephemeralPublicKey;if(!o)throw new Error("Requester handshake was not detected in time");const n=this.client.encryption.deriveSharedSecret({privateKey:t.privateKey,peerPublicKey:o}).subarray(),s=this.buildRecipients(r);return this.createHandle({sessionId:e.sessionId,sharedSecret:n,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,o=t?.handshake;if(t&&o&&"complete"===o.status)return{summary:t,record:o};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 Jl(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={sessionId:e.sessionId,mode:"encrypted",summary:e.summary,send:async i=>{const o=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:u.Buffer.from(t),recipients:o}})},decryptHistoryEntry:r=>this.decryptEntry(r,e.identity,t)};return this.registerConversationContext({sessionId:e.sessionId,sharedSecret:t,identity:e.identity}),i}decryptEntry(e,t,r){const i=e.cipherEnvelope;if(!i)return null;const o=u.Buffer.from(r);try{return this.client.encryption.decryptCipherEnvelope({envelope:i,sharedSecret:o})}catch(n){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))}}class Jl extends Error{constructor(e,t){super("Encryption is not enabled for this session"),this.sessionId=e,this.summary=t}}class Yl{constructor(e="info"){this.defaultEndpoint="https://kiloscribe.com/api/inscription-cdn",this.logger=B.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 J(t.network,this.logger),i=await r.getTopicInfo(e),o=i?.memo||"";let n="1";if(o){const e=o.match(/^hcs-(\d+)/);e&&e[1]&&(n=e[1])}const s=`hcs://${n}/${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(dg){const t=`Error resolving HRL for content and type: ${dg.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:i,topicId:n}=r;this.logger.debug(`Resolving HRL reference: standard=${i}, topicId=${n}`);try{const e=`${t.cdnEndpoint||this.defaultEndpoint}/${n}?network=${t.network}`;this.logger.debug(`Fetching content from CDN: ${e}`);const r=(await o.head(e)).headers["content-type"]||"";if(this.isBinaryContentType(r)||t.returnRaw){return{content:(await o.get(e,{responseType:"arraybuffer"})).data,contentType:r,topicId:n,isBinary:!0}}if("application/json"===r){const t=await o.get(e,{responseType:"json"});if(!t.data)throw new Error(`Failed to fetch content from topic: ${n}`);return{content:t.data,contentType:r,topicId:n,isBinary:!1}}const i=await o.get(e);if(!i.data)throw new Error(`Failed to fetch content from topic: ${n}`);let s;return s="object"==typeof i.data?i.data.content||i.data.text||JSON.stringify(i.data):i.data,{content:s,contentType:r,topicId:n,isBinary:!1}}catch(dg){const t=`Error resolving HRL reference: ${dg.message}`;throw this.logger.error(t),new Error(t)}}}class Xl{constructor(e){this.nodeHash=e}update(e){return this.nodeHash.update(e),this}digest(e){return this.nodeHash.digest(e)}}class Zl{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).buffer,i=await crypto.subtle.digest(this.mapAlgorithm(this.algorithm),r);return"hex"===e?Array.from(new Uint8Array(i)).map(e=>e.toString(16).padStart(2,"0")).join(""):globalThis.Buffer.from(i)}concatenateArrays(e){const t=e.reduce((e,t)=>e+t.length,0),r=new Uint8Array(t);let i=0;for(const o of e)r.set(o,i),i+=o.length;return r}mapAlgorithm(e){return{sha256:"SHA-256",sha384:"SHA-384",sha1:"SHA-1",sha512:"SHA-512"}[e.toLowerCase()]||"SHA-256"}}class Ql{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 ed(){const e="undefined"==typeof window;let t,r=!1,i=!1;try{r="undefined"!=typeof require&&"undefined"!=typeof process&&!!process.versions?.node}catch{r=!1}try{i="undefined"!=typeof crypto&&void 0!==crypto.subtle&&!e}catch{i=!1}return t=r&&e?"node":i&&!e?"web":"none",{hasNodeCrypto:r,hasWebCrypto:i,isSSR:e,preferredAPI:t}}function td(){return"undefined"==typeof window}class rd{constructor(e){this.nodeHmac=e}update(e){return this.nodeHmac.update(e),this}digest(e){return this.nodeHmac.digest(e)}}class id{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=await crypto.subtle.importKey("raw",r,{name:"HMAC",hash:this.mapAlgorithm(this.algorithm)},!1,["sign"]),o=await crypto.subtle.sign("HMAC",i,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 od{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 o=t[i%t.length];r=(r<<5)-r+e[i]+o&4294967295}return Math.abs(r)}}class nd{constructor(){try{const e="crypto";this.crypto=require(e)}catch(e){throw new Error("Node.js crypto module not available")}}createHash(e){return new Xl(this.crypto.createHash(e))}createHmac(e,t){return new rd(this.crypto.createHmac(e,t))}async pbkdf2(e,t,r,i,o){return new Promise((n,s)=>{this.crypto.pbkdf2(e,t,r,i,o,(e,t)=>{e?s(e):n(t)})})}timingSafeEqual(e,t){return this.crypto.timingSafeEqual(e,t)}}class sd{createHash(e){return new Zl(e)}createHmac(e,t){return new id(t,e)}async pbkdf2(e,t,r,i,o){const n=new TextEncoder,s=await crypto.subtle.importKey("raw",n.encode(e),{name:"PBKDF2"},!1,["deriveBits"]),a=await crypto.subtle.deriveBits({name:"PBKDF2",salt:new Uint8Array(t),iterations:r,hash:this.mapDigest(o)},s,8*i);return globalThis.Buffer.from(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}mapDigest(e){return{sha256:"SHA-256",sha1:"SHA-1",sha512:"SHA-512"}[e.toLowerCase()]||"SHA-256"}}class ad{createHash(e){return new Ql(e)}createHmac(e,t){return new od(t,e)}async pbkdf2(e,t,r,i,o){const n=new TextEncoder,s=globalThis.Buffer.from(n.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 cd(){switch(ed().preferredAPI){case"node":try{return new nd}catch{return new ad}case"web":return new sd;default:return new ad}}const ld=["mainnet","testnet","previewnet","devnet"];function dd(e){return ld.includes(e)}const ud=/^hedera:(mainnet|testnet|previewnet|devnet):\d+\.\d+\.\d+(?:-[a-zA-Z0-9]{5})?$/;function pd(e){return ud.test(e)}function hd(e,t){if(!dd(e))throw new Error("Invalid Hedera network");if(t.startsWith("hedera:")){if(pd(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 gd(e){if(!pd(e))throw new Error("Invalid Hedera CAIP-10");const[,t,r]=e.match(/^hedera:([^:]+):(.+)$/);return{network:t,accountId:r}}const md=/^eip155:(\d+):(0x[0-9a-fA-F]{39,40})$/;function fd(e){return md.test(e)}function yd(e,t){const r=`eip155:${"number"==typeof e?String(e):e}:${t.startsWith("0x")?t:`0x${t}`}`;if(!fd(r))throw new Error("Invalid EIP-155 CAIP-10");return r}var bd=(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))(bd||{}),wd=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(wd||{}),Id=(e=>(e[e.REST=0]="REST",e[e.WEBSOCKET=1]="WEBSOCKET",e[e.GRPC=2]="GRPC",e))(Id||{}),Td=(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))(Td||{}),Sd=(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))(Sd||{}),kd=(e=>(e.DNS="dns",e.SIGNATURE="signature",e.CHALLENGE="challenge",e))(kd||{}),Ed=(e=>(e.PUBLIC="PUBLIC",e.CONTROLLED="CONTROLLED",e.FEE_BASED="FEE_BASED",e))(Ed||{});const Ad={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},vd=r.z.object({platform:r.z.string().min(1),handle:r.z.string().min(1)}),Cd=r.z.object({type:r.z.nativeEnum(wd),capabilities:r.z.array(r.z.nativeEnum(Td)).min(1),model:r.z.string().min(1),creator:r.z.string().optional()}),xd=r.z.object({url:r.z.string().min(1),transport:r.z.enum(["stdio","sse"])}),Rd=r.z.object({type:r.z.nativeEnum(kd),value:r.z.string(),dns_field:r.z.string().optional(),challenge_path:r.z.string().optional()}),Nd=r.z.object({minVersion:r.z.string().optional()}),_d=r.z.object({name:r.z.string().min(1),description:r.z.string().min(1)}),Pd=r.z.object({name:r.z.string().min(1),description:r.z.string().min(1)}),Fd=r.z.object({version:r.z.string().min(1),connectionInfo:xd,services:r.z.array(r.z.nativeEnum(Sd)).min(1),description:r.z.string().min(1),verification:Rd.optional(),host:Nd.optional(),capabilities:r.z.array(r.z.string()).optional(),resources:r.z.array(_d).optional(),tools:r.z.array(Pd).optional(),maintainer:r.z.string().optional(),repository:r.z.string().optional(),docs:r.z.string().optional()}),Od=r.z.object({version:r.z.string().min(1),type:r.z.nativeEnum(bd),display_name:r.z.string().min(1),alias:r.z.string().optional(),bio:r.z.string().optional(),socials:r.z.array(vd).optional(),profileImage:r.z.string().optional(),uaid:r.z.string().optional(),properties:r.z.record(r.z.any()).optional(),inboundTopicId:r.z.string().optional(),outboundTopicId:r.z.string().optional(),base_account:r.z.string().optional()}),zd=Od.extend({type:r.z.literal(bd.PERSONAL),language:r.z.string().optional(),timezone:r.z.string().optional()}),Dd=Od.extend({type:r.z.literal(bd.AI_AGENT),aiAgent:Cd}),Bd=Od.extend({type:r.z.literal(bd.MCP_SERVER),mcpServer:Fd}),Md=r.z.object({version:r.z.string(),type:r.z.literal(bd.FLORA),display_name:r.z.string().min(1),members:r.z.array(r.z.object({accountId:r.z.string(),publicKey:r.z.string().optional(),weight:r.z.number().optional()})),threshold:r.z.number().min(1),topics:r.z.object({communication:r.z.string(),transaction:r.z.string(),state:r.z.string()}),inboundTopicId:r.z.string(),outboundTopicId:r.z.string(),bio:r.z.string().optional(),metadata:r.z.record(r.z.any()).optional(),policies:r.z.record(r.z.any()).optional()}),Ud=r.z.union([zd,Dd,Bd,Md]);class Ld{constructor(e){this.client="mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet(),this.auth=e.auth,this.network=e.network,this.operatorId=e.auth.operatorId,this.logger=B.getInstance({level:e.logLevel||"info",module:"HCS-11",silent:e.silent}),this.mirrorNode=new J(this.network,this.logger),this.auth.privateKey?(this.operatorCtx=ne({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:bd.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,o){const n=this.validateProfile({version:"1.0",type:bd.AI_AGENT,display_name:e,alias:o?.alias,bio:o?.bio,socials:o?.socials,profileImage:o?.profileImage,properties:o?.properties,inboundTopicId:o?.inboundTopicId,outboundTopicId:o?.outboundTopicId,base_account:o?.baseAccount,aiAgent:{type:t,capabilities:r,model:i,creator:o?.creator}});if(!n.valid)throw new Error(`Invalid AI Agent Profile: ${n.errors.join(", ")}`);return{version:"1.0",type:bd.AI_AGENT,display_name:e,alias:o?.alias,bio:o?.bio,socials:o?.socials,profileImage:o?.profileImage,properties:o?.properties,inboundTopicId:o?.inboundTopicId,outboundTopicId:o?.outboundTopicId,base_account:o?.baseAccount,aiAgent:{type:t,capabilities:r,model:i,creator:o?.creator}}}createMCPServerProfile(e,t,r){const i=this.validateProfile({version:"1.0",type:bd.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:bd.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=Ud.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),r=await t.execute(this.client),o=await r.getReceipt(this.client);return o.status.toString()!==i.Status.Success.toString()?{success:!1,error:`Transaction failed: ${o.status.toString()}`}:{success:!0,result:o}}if(!this.auth.signer)throw new Error("No valid authentication method provided");const t=this.auth.signer,r=await e.freezeWithSigner(t),o=await r.executeWithSigner(t),n=await o.getReceiptWithSigner(t);return n.status.toString()!==i.Status.Success.toString()?{success:!1,error:`Transaction failed: ${n.status.toString()}: ${i.Status.Success.toString()}`}:{success:!0,result:n}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error during transaction execution"}}}async inscribeImage(e,t,r){try{const o=r?.progressCallback,n=new hs({module:"HCS11-Image",logger:this.logger,callback:o});n.preparing("Preparing to inscribe image",0);const s=E.lookup(t)||"application/octet-stream",a=r?.waitForConfirmation??!0;let c;if(this.auth.signer){if(!("accountId"in this.auth.signer))throw n.failed("Signer must be a DAppSigner for inscription"),new Error("Signer must be a DAppSigner for inscription");n.preparing("Using signer for inscription",10),c=await za({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);n.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}else{if(!this.auth.privateKey)throw n.failed("Private key is required for inscription"),this.logger.error("Private key is required for inscription"),new Error("Private key is required for inscription");n.preparing("Using private key for inscription",10);const r="ecdsa"===this.keyType?i.PrivateKey.fromStringECDSA(this.auth.privateKey):i.PrivateKey.fromStringED25519(this.auth.privateKey);c=await Oa({type:"buffer",buffer:e,fileName:t,mimeType:s},{accountId:this.auth.operatorId,privateKey:r,network:this.network},{waitForConfirmation:a,waitMaxAttempts:150,waitIntervalMs:2e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);n.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}if(c.confirmed)return n.completed("Image inscription completed",{topicId:La(c.inscription)}),{imageTopicId:La(c.inscription)||"",transactionId:c.result.jobId,success:!0};{const e=c.quote?"quote-only":c.result.jobId;return n.verifying("Waiting for inscription confirmation",50,{jobId:e}),{imageTopicId:"",transactionId:e,success:!1,error:"Inscription not confirmed"}}}catch(o){return this.logger.error("Error inscribing image:",o),{imageTopicId:"",transactionId:"",success:!1,error:o instanceof Error?o.message:"Error inscribing image"}}}async inscribeProfile(e,t){this.logger.info("Inscribing HCS-11 profile");const r=t?.progressCallback,o=new hs({module:"HCS11-Profile",logger:this.logger,callback:r});await this.attachUaidIfMissing(e),o.preparing("Validating profile data",5);const n=this.validateProfile(e);if(!n.valid)return o.failed(`Invalid profile: ${n.errors.join(", ")}`),{profileTopicId:"",transactionId:"",success:!1,error:`Invalid profile: ${n.errors.join(", ")}`};o.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";o.preparing("Preparing profile for inscription",20);const r={type:"buffer",buffer:e,fileName:a,mimeType:t},n={waitForConfirmation:!0,mode:"file",network:this.network,waitMaxAttempts:100,waitIntervalMs:2e3,progressCallback:e=>{const t=20+.75*Number(e?.progressPercent||0);o?.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}};let c;if(o.submitting("Submitting profile to Hedera network",30),this.auth.privateKey){const e="ecdsa"===this.keyType?i.PrivateKey.fromStringECDSA(this.auth.privateKey):i.PrivateKey.fromStringED25519(this.auth.privateKey);c=await Oa(r,{accountId:this.auth.operatorId,privateKey:e,network:this.network},n)}else{if(!this.auth.signer)throw new Error("No authentication method available - neither private key nor signer");c=await za(r,this.auth.signer,n)}if(!c.confirmed||!La(c.inscription))return o.failed("Failed to inscribe profile content"),{profileTopicId:"",transactionId:"",success:!1,error:"Failed to inscribe profile content"};const l=La(c.inscription);return o.completed("Profile inscription completed",{topicId:l,transactionId:c.result.transactionId}),{profileTopicId:l,transactionId:c.result.transactionId,success:!0}}catch(c){return o.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&&dd(this.network))try{const{HCS14Client:t}=await Promise.resolve().then(()=>mp),r=new t({client:this.client}),i=await r.createDid({method:"hedera",client:this.client}),o=hd(this.network,this.auth.operatorId);let n=this.auth.operatorId;const s=e.inboundTopicId;if(s&&s.trim().length>0)n=`${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&&(n=`${t}@${this.auth.operatorId}`)}catch{}const a=r.createUaid(i,{proto:"hcs-10",nativeId:o,uid:n});e.uaid=a}catch(dg){this.logger.warn("Hiero registrar not available; skipping UAID generation for profile",dg)}}async updateAccountMemoWithProfile(e,t){try{this.logger.info(`Updating account memo for ${e} with profile ${t}`);const r=this.setProfileForAccountMemo(t),o=(new i.AccountUpdateTransaction).setAccountMemo(r).setAccountId(e);return this.executeTransaction(o)}catch(r){return this.logger.error(`Error updating account memo: ${r instanceof Error?r.message:"Unknown error"}`),{success:!1,error:r instanceof Error?r.message:"Unknown error updating account memo"}}}async createAndInscribeProfile(e,t=!0,r){const i=r?.progressCallback,o=new hs({module:"HCS11-ProfileCreation",logger:this.logger,callback:i});o.preparing("Starting profile creation process",0);const n=o.createSubProgress({minPercent:0,maxPercent:80,logPrefix:"Inscription"}),s=await this.inscribeProfile(e,{...r,progressCallback:e=>{n.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent,details:e.details})}});if(!s?.success)return o.failed("Profile inscription failed",{error:s?.error}),s;if(o.confirming("Profile inscribed, updating account memo",85),t){const e=await this.updateAccountMemoWithProfile(this.auth.operatorId,s.profileTopicId);if(!e.success)return o.failed("Failed to update account memo",{error:e?.error}),{...s,success:!1,error:e?.error}}return o.completed("Profile creation completed successfully",{profileTopicId:s.profileTopicId,transactionId:s.transactionId}),s}async getCapabilitiesFromTags(e){const t=[];if(0===e.length)return[Td.TEXT_GENERATION];for(const r of e){const e=Ad[r.toLowerCase()];void 0===e||t.includes(e)||t.push(e)}return 0===t.length&&t.push(Td.TEXT_GENERATION),t}getAgentTypeFromMetadata(e){return"autonomous"===e.type?wd.AUTONOMOUS:wd.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 o=i.substring(7);if(!o?.startsWith("hcs://")){if(o.startsWith("ipfs://")){this.logger.warn("IPFS protocol references are not fully supported");const e=await fetch(`https://ipfs.io/ipfs/${o.replace("ipfs://","")}`),t=await e.json(),r=Ud.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 ${o}`}}if(o.startsWith("ar://")){const e=o.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=Ud.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: ${o}`}}{const e=o.match(/hcs:\/\/(\d+)\/(.+)/);if(!e)return{success:!1,error:`Invalid HCS protocol reference format: ${o}`};const[i,n,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=Ud.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 Kd{async checkRegistrationStatus(e,t,r,i){try{const o=await fetch(`${r}/api/request-confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Network":t},body:JSON.stringify({transaction_id:e})});if(!o.ok){const e=`Failed to confirm registration: ${o.statusText}`;throw i&&i.error(e),new Error(e)}return await o.json()}catch(o){throw i&&i.error(`Error checking registration status: ${o.message}`),o}}async waitForRegistrationConfirmation(e,t,r,i=60,o=2e3,n){let s=0;for(;s<i;){n&&n.info(`Checking registration status. Attempt ${s+1}/${i}`);const a=await this.checkRegistrationStatus(e,t,r,n);if("success"===a.status)return n&&n.info("Registration confirmed successfully"),!0;if("failed"===a.status)throw n&&n.error("Registration confirmation failed"),new Error("Registration confirmation failed");n&&n.info(`Registration still pending. Waiting ${o}ms before next attempt`),await new Promise(e=>setTimeout(e,o)),s++}return n&&n.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 Ld({network:t,auth:{operatorId:"0.0.0"}});i?.info(`Fetching profile by account ID ${e} on ${t}`),await M(5e3);const o=await r.fetchProfileByAccountId(e,t);if(i?.info("Profile fetched",o),o?.error)return i?.error("Error fetching profile",o.error),{error:o.error,success:!1};if(!o?.success||!o?.profile)return i&&i.error("Profile not found for agent registration"),{error:"Profile not found for the provided account ID",success:!1};if(!o.profile.inboundTopicId)return i&&i.error("Missing inbound topic ID in profile"),{error:"Profile is missing required inbound topic ID",success:!1};if(!o.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: ${o.profile.inboundTopicId}, Outbound topic: ${o.profile.outboundTopicId}`)}catch(o){return i&&i.error(`Error validating profile: ${o.message}`),{error:`Error validating profile: ${o.message}`,success:!1}}const n=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 n.json();return n.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(n){return{error:`Error during registration request: ${n.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 o=await i.json();return o.error?{registrations:[],error:o.error,success:!1}:{registrations:o.registrations||[],success:!0}}catch(dg){return{registrations:[],error:`Error fetching registrations: ${dg.message}`,success:!1}}}}function $d(e,t){return`hcs-10:op:${e}:${t}`}function Hd(e){var t,r;return X({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 qd(e){return X({memo:e.memoOverride??`hcs-10:0:${e.ttl}:1`,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function jd(e){var t,r,i;return X({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 Wd(e){var t,r;return X({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 Vd(e){const t={p:"hcs-10",op:"connection_request",operator_id:e.operatorId,m:e.memo};return Z({topicId:e.inboundTopicId,message:JSON.stringify(t),transactionMemo:$d(3,1)})}function Gd(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 Z({topicId:e.inboundTopicId,message:JSON.stringify(t),transactionMemo:$d(4,1)})}function Jd(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 Z({topicId:e.outboundTopicId,message:JSON.stringify(t),transactionMemo:$d(3,2)})}function Yd(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 Z({topicId:e.outboundTopicId,message:JSON.stringify(t),transactionMemo:$d(4,2)})}function Xd(e){const t={p:"hcs-10",op:"message",operator_id:e.operatorId,data:e.data,m:e.memo};return Z({topicId:e.connectionTopicId,message:JSON.stringify(t),transactionMemo:$d(6,3)})}function Zd(e){const t={p:"hcs-10",op:"register",account_id:e.accountId,...e.inboundTopicId?{inbound_topic_id:e.inboundTopicId}:{},m:e.memo};return Z({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:$d(0,0)})}var Qd=(e=>(e.INBOUND="inbound",e.OUTBOUND="outbound",e.CONNECTION="connection",e.REGISTRY="registry",e))(Qd||{});class eu extends Kd{constructor(e){super(),this.network=e.network,this.logger=B.getInstance({level:e.logLevel||"info",module:"HCS10-BaseClient",prettyPrint:e.prettyPrint,silent:e.silent}),this.mirrorNode=new J(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 o=await this.mirrorNode.getTopicInfo(e);if(!o)return{canSubmit:!1,requiresFee:!1,reason:"Topic does not exist"};if(!o.submit_key?.key)return{canSubmit:!0,requiresFee:!1};try{const e=await this.mirrorNode.getPublicKey(t);if("ProtobufEncoded"===o.submit_key._type){const t=globalThis.Buffer.from(o.submit_key.key,"hex");if(await this.mirrorNode.checkKeyListAccess(t,e))return{canSubmit:!0,requiresFee:!1}}else{const t=i.PublicKey.fromString(o.submit_key.key);if(e.toString()===t.toString())return{canSubmit:!0,requiresFee:!1}}}catch(r){this.logger.error(`Key validation error: ${r instanceof Error?r.message:String(r)}`)}return o.fee_schedule_key?.key&&o.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(r){const e=r instanceof Error?r.message:String(r);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(dg){throw this.logger.error("Failed to fetch account",dg),dg}}async getAccountMemo(e){return await this.mirrorNode.getAccountMemo(e)}async retrieveProfile(e,t,r){const i=r?.maxRetries??0,o=r?.retryDelay??3e3;let n=0;for(;n<=i;){this.logger.debug(`Retrieving profile for account: ${e}${n>0?` (attempt ${n+1}/${i+1})`:""}`);const r=`${e}-${this.network}`;if(!t&&0===n){const t=tu.getInstance().get(r);if(t)return this.logger.debug(`Cache hit for profile: ${e}`),t}try{const t=new Ld({network:this.network,auth:{operatorId:"0.0.0"},logLevel:this.logger.getLevel()}),s=await t.fetchProfileByAccountId(e,this.network);if(!s?.success){if(n<i){this.logger.info(`Profile not found for account ${e}, retrying in ${o}ms... (${s?.error})`),n++,await new Promise(e=>setTimeout(e,o));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;s?.topicInfo?.inboundTopic&&s?.topicInfo?.outboundTopic&&s?.topicInfo?.profileTopicId&&(c={inboundTopic:s.topicInfo.inboundTopic,outboundTopic:s.topicInfo.outboundTopic,profileTopicId:s.topicInfo.profileTopicId});const l={profile:a,topicInfo:c,success:!0};return tu.getInstance().set(r,l),l}catch(dg){if(n<i){this.logger.info(`Error retrieving profile for account ${e}, retrying in ${o}ms... (${dg.message})`),n++,await new Promise(e=>setTimeout(e,o));continue}const r=`Failed to retrieve profile: ${dg.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 o=i.profile;if(!o)throw new Error(`Profile is null or undefined for account ${e}`);if(!o.inboundTopicId||!o.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(dg){const t=dg,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(dg){const t=`Failed to retrieve outbound messages: ${dg.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(dg){const t=`Failed to check connection created: ${dg.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 Yl(this.logger.getLevel());if(!r.isValidHRL(e))return e;return(await r.resolveHRL(e,{network:this.network,returnRaw:t})).content}catch(dg){const t=`Error resolving HRL reference: ${dg.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 Yl(this.logger.getLevel());return await r.getContentWithType(e,{network:this.network,returnRaw:t})}catch(dg){const t=`Error resolving HRL reference with type: ${dg.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(),o=r.accountId,n=await this.canSubmitToTopic(e,o);if(!n?.canSubmit)throw new Error(`Cannot submit to topic: ${n.reason}`);const s=await this.retrieveInboundAccountId(e);if(!s)throw new Error("Failed to retrieve topic info account ID");const a=n.requiresFee,c=Vd({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 d=await this.retrieveCommunicationTopics(o);if(!d)throw new Error("Failed to retrieve outbound topic");const u=l.topicSequenceNumber?.toNumber();if(!u)throw new Error("Failed to get response sequence number");const p=`${e}@${s}`,h=Jd({outboundTopicId:d.outboundTopic,operatorId:p,connectionRequestId:u,memo:t});return await this.submitPayload(h),l}async recordOutboundConnectionConfirmation({outboundTopicId:e,requestorOutboundTopicId:t,connectionRequestId:r,confirmedRequestId:i,connectionTopicId:o,operatorId:n,memo:s}){const a=Yd({outboundTopicId:e,requestorOutboundTopicId:t,connectionTopicId:o,confirmedRequestId:i,connectionRequestId:r,operatorId:n,memo:s});return await this.submitPayload(a)}async waitForConnectionConfirmation(e,t,r=60,i=2e3,o=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let n=0;n<r;n++){this.logger.info(`Attempt ${n+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),n=this.getAccountAndSigner(),s=await this.retrieveCommunicationTopics(i),a=await this.retrieveCommunicationTopics(n.accountId);return this.logger.info("Connection confirmation found",r),o&&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}n<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(){tu.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 o=i[3];switch(o){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: ${o} 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(dg){const t=dg,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 o=/^[0-9]+\.[0-9]+\.[0-9]+$/;return!!o.test(i)&&!!o.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 tu{constructor(){this.CACHE_TTL=36e5,this.cache=new Map,this.cacheExpiry=new Map}static getInstance(){return tu.instance||(tu.instance=new tu),tu.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 ru extends Error{constructor(e,t){super(e),this.payloadSize=t,this.name="PayloadSizeError"}}class iu extends Error{constructor(e){super(e),this.name="AccountCreationError"}}class ou extends Error{constructor(e){super(e),this.name="TopicCreationError"}}class nu extends Error{constructor(e){super(e),this.name="ConnectionConfirmationError"}}class su{constructor(){this.config={},this.logger=B.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=Ed.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===Ed.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 au extends eu{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=B.getInstance({level:e.logLevel||"info",module:"HCS-SDK",silent:e.silent}),this.operatorAccountId=e.operatorId,this.operatorCtx=ne({network:this.network,operatorId:this.operatorAccountId,operatorKey:e.operatorPrivateKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:"mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet()}),this.client=this.operatorCtx.client,this.network=e.network,this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl||"https://moonscape.tech",this.hcs11Client=new Ld({network:e.network,auth:{operatorId:e.operatorId,privateKey:this.operatorCtx.operatorKey.toString()},logLevel:e.logLevel,silent:e.silent,keyType:e.keyType})}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=i.PrivateKey.generateED25519(),r=(new i.AccountCreateTransaction).setKeyWithoutAlias(t.publicKey).setInitialBalance(new i.Hbar(e)),o=await r.execute(this.client),n=(await o.getReceipt(this.client)).accountId;if(!n)throw this.logger.error("Account creation failed: accountId is null"),new iu("Failed to create account: accountId is null");return this.logger.info(`Account created successfully: ${n.toString()}`),{accountId:n.toString(),privateKey:t.toString()}}async createInboundTopic(e,t,r=60,i){let o,n;switch(await this.ensureInitialized(),this._generateHcs10Memo(Qd.INBOUND,{accountId:e,ttl:r}),t){case Ed.PUBLIC:o=!1;break;case Ed.CONTROLLED:o=!0;break;case Ed.FEE_BASED:if(o=!1,!i)throw new Error("Fee configuration builder is required for fee-based topics");i.customFees.forEach(t=>{t.feeCollectorAccountId||(t.feeCollectorAccountId=e)}),n=i.build(),n.customFees=n.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=Hd({accountId:e,ttl:r,adminKey:!0,submitKey:o,operatorPublicKey:s});this.logger.info("Creating inbound topic");const{topicId:c}=await this.executeTopicCreateTransaction({transaction:a,feeConfig:n});return c}async createAgent(e,t=60,r,i){await this.ensureInitialized();const o=e.build(),n=this.client.operatorAccountId?.toString();if(!n)throw new Error("Failed to retrieve operator account ID");const s=await this._createEntityTopics(t,{outboundTopicId:r?.outboundTopicId||"",inboundTopicId:r?.inboundTopicId||"",pfpTopicId:r?.pfpTopicId||o.existingPfpTopicId||"",profileTopicId:r?.profileTopicId||""},n,o.inboundTopicType,o.feeConfig,o.pfpBuffer,o.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(o.name,o.bio,s.inboundTopicId,s.outboundTopicId,o.capabilities,o.metadata,o.pfpBuffer&&o.pfpBuffer.length>0&&!s.pfpTopicId?o.pfpBuffer:void 0,o.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 hs({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 su;let o;if(o=t?.existingState?t.existingState:{currentStage:"init",completedPercentage:0,createdResources:[]},r){this.logger.info("Creating Agent Profile and HCS-10 Topics");const t=e.build();o.agentMetadata=t.metadata}else this.logger.info("Creating Person HCS-11 Profile");i.preparing(`Starting ${r?"agent":"person"} resource creation`,0,{state:o});const n=this.client.operatorAccountId?.toString();if(!n)throw new Error("Failed to retrieve operator account ID");const{inboundTopicId:s,outboundTopicId:a,state:c}=await this.createCommunicationTopics(n,t,i);let l,d,u;if(o=c,e.setInboundTopicId(s),e.setOutboundTopicId(a),r){const t=e.build();l=t.existingPfpTopicId||o.pfpTopicId,d=t.pfpBuffer,u=t.pfpFileName||"pfp.png"}else{const t=e.build();l=o.pfpTopicId,d=t.pfpBuffer,u=t.pfpFileName}!l&&d&&u?l=await this.handleProfilePictureCreation(d,u,o,i):l&&(i.preparing(`Using existing profile picture: ${l}`,50,{state:o}),o.pfpTopicId=l),await this.createAndInscribeProfile(r,e,l,o,s,a,t,i),o.currentStage="complete",o.completedPercentage=100,i.completed((r?"Agent":"Person")+" profile created successfully",{profileTopicId:o.profileTopicId,inboundTopicId:s,outboundTopicId:a,pfpTopicId:l,state:o});let p="";o.outboundTopicId&&(p=o.outboundTopicId);let h="";o.inboundTopicId&&(h=o.inboundTopicId);let g="";o.pfpTopicId&&(g=o.pfpTopicId);let m="";return o.profileTopicId&&(m=o.profileTopicId),{outboundTopicId:p,inboundTopicId:h,pfpTopicId:g,profileTopicId:m,success:!0,state:o}}catch(o){return i.failed("Error during profile creation",{error:o.message}),{outboundTopicId:"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:o.message,state:{currentStage:"init",completedPercentage:0,error:o.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(dg){const t=dg,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,o=[],n,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 d=this.hcs11Client.getAgentTypeFromMetadata({type:n.type||"autonomous"}),u=n.socials?Object.entries(n.socials).filter(([e,t])=>t).map(([e,t])=>({platform:e,handle:t})):void 0,p=this.hcs11Client.createAIAgentProfile(e,d,o,n.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:l?`hcs://1/${l}`:void 0,socials:u,properties:n.properties,inboundTopicId:r,outboundTopicId:i,creator:n.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(dg){const t=dg,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,r=[]){let o=e;if(!this.client.operatorPublicKey)return o;if(!t.customFees||0===t.customFees.length)return this.logger.warn("No custom fees provided in fee config for setupFees"),o;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 n=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 i.CustomFixedFee).setAmount(Number(e.feeAmount.amount)).setFeeCollectorAccountId(i.AccountId.fromString(e.feeCollectorAccountId));return e.feeTokenId&&t.setDenominatingTokenId(i.TokenId.fromString(e.feeTokenId)),t}return null}).filter(Boolean);if(0===n.length)return this.logger.warn("No valid custom fees to apply in setupFees"),o;const s=[...t.exemptAccounts||[],...r];return s.length>0&&(o=await this.setupExemptKeys(e,s)),o.setFeeScheduleKey(this.client.operatorPublicKey).setCustomFees(n)}async setupExemptKeys(e,t){let r=e;const i=Array.from(new Set(t)).filter(e=>e!==this.client.operatorAccountId?.toString());let o=[];if(i.length>0)try{o=await nc(i,this.network,this.logger)}catch(dg){const t=`Error getting exempt keys: ${dg.message}, continuing without exempt keys`;this.logger.warn(t)}return o.length>0&&(r=r.setFeeExemptKeys(o)),r}async handleConnectionRequest(e,t,r,o,n=60){this.logger.info(`Handling connection request ${r} 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 i.KeyList([c,a],1);let d;try{const t=jd({ttl:n,inboundTopicId:e,connectionId:r,adminKey:l,submitKey:l});if(o){const e=o.build(),r={...e,exemptAccounts:[...e.exemptAccounts||[]]},{topicId:i}=await this.executeTopicCreateTransaction({transaction:t,feeConfig:r});d=i}else{const{topicId:e}=await this.executeTopicCreateTransaction({transaction:t});d=e}this.logger.info(`Created new connection topic ID: ${d}`)}catch(f){const e=`Failed to create connection topic: ${f}`;throw this.logger.error(e),new ou(e)}const u=`${e}@${s}`,p=await this.confirmConnection(e,d,t,r,"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:r,confirmedRequestId:p,connectionTopicId:d,operatorId:m,memo:`Connection established with ${t}`}),{connectionTopicId:d,confirmedConnectionSequenceNumber:p,operatorId:u}}async confirmConnection(e,t,r,i,o,n){const s=await this.getOperatorId();this.logger.info(`Confirming connection with ID ${i}`);const a=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),c=Gd({inboundTopicId:e,connectionTopicId:t,connectedAccountId:r,operatorId:s,connectionId:i,memo:o}),l=await this.submitPayload(c,void 0,n,a.requiresFee),d=l.topicSequenceNumber?.toNumber();if(!d)throw new nu("Failed to confirm connection: sequence number is null");return d}async sendMessage(e,t,r,i,o){const n=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:o?.progressCallback,waitMaxAttempts:o?.waitMaxAttempts,waitIntervalMs:o?.waitIntervalMs});if(!La(i))throw new Error("Failed to inscribe large message content");a.data=`hcs://1/${La(i)}`,this.logger.info(`Large message inscribed with topic ID: ${La(i)}`)}catch(d){const e=`Error inscribing large message: ${d.message}`;throw this.logger.error(e),new Error(e)}}this.logger.info("Submitting message to connection topic",a);const l=Xd({connectionTopicId:e,operatorId:s,data:a.data,memo:r});return await this.submitPayload(l,void 0,i,n.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 o=X({memo:e,adminKey:t,submitKey:r,operatorPublicKey:this.client.operatorPublicKey||this.operatorCtx.operatorKey?.publicKey}),{topicId:n}=await this.executeTopicCreateTransaction({transaction:o,feeConfig:i});return n}async submitPayload(e,t,r,o=!1){if(e instanceof i.TopicMessageSubmitTransaction||"string"!=typeof e&&"function"==typeof e.getMessage){const t=(i.TopicMessageSubmitTransaction,e),n=t.getMessage();if(!n)throw new Error("Message payload is missing");const s=globalThis.Buffer.from(n).length;if(s>1e3)throw new ru("Payload size exceeds 1000 bytes limit",s);let a;if(o&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),t.setMaxTransactionFee(new i.Hbar(this.feeAmount))),r){const e=t.freezeWith(this.client),i=await e.sign(r);a=await i.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 n="string"==typeof t?t:JSON.stringify(t),s=globalThis.Buffer.byteLength(n,"utf8");if(s>1e3)throw new ru("Payload size exceeds 1000 bytes limit",s);const a=Z({topicId:e,message:n,transactionMemo:this.getHcs10TransactionMemo(t)||void 0});let c;if(o&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),a.setMaxTransactionFee(new i.Hbar(this.feeAmount))),r){const e=a.freezeWith(this.client),t=await e.sign(r);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=E.lookup(t)||"application/octet-stream",o=this.operatorCtx.operatorKey,n=await ps.createWithAuth({type:"server",accountId:this.client.operatorAccountId.toString(),privateKey:o,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:o,network:this.network},s,n);if(!a.confirmed||!a.inscription)throw new Error("Inscription was not confirmed");return a.inscription}async waitForConnectionConfirmation(e,t,r=60,i=2e3,o=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let n=0;n<r;n++){this.logger.info(`Attempt ${n+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),n=this.getAccountAndSigner(),s=await this.retrieveCommunicationTopics(i),a=await this.retrieveCommunicationTopics(n.accountId);return this.logger.info("Connection confirmation found",r),o&&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}n<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 r=e.build(),o=t?.progressCallback,n=t?.baseUrl||this.guardedRegistryBaseUrl;let s=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};s.agentMetadata=r.metadata,o&&o({stage:"preparing",message:"Starting agent creation process",progressPercent:0,details:{state:s}});let a,c=r.existingAccount;if(s.inboundTopicId&&s.outboundTopicId&&s.profileTopicId){if(c=c||r.existingAccount,!c)throw new Error("Cannot resume registration without account information");const e="ecdsa"===this.operatorCtx.keyType?i.PrivateKey.fromStringECDSA(c.privateKey).publicKey.toString():i.PrivateKey.fromStringED25519(c.privateKey).publicKey.toString();a=new au({network:r.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:e,logLevel:"info",guardedRegistryBaseUrl:n}),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:")),i=e?.split(":")[1];i&&r.existingAccount?(c=r.existingAccount,this.logger.info(`Resuming with existing account: ${i}`)):(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}`);o&&o({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:s,account:c}});const i=new oe({mirrorNode:this.mirrorNode,logger:this.logger}),l=await i.resolveOperatorKey(c.accountId,c.privateKey),d=l.privateKey.publicKey.toString();a=new au({network:r.network,operatorId:c.accountId,operatorPrivateKey:l.privateKey.toString(),operatorPublicKey:d,keyType:l.keyType,logLevel:"info",guardedRegistryBaseUrl:n}),o&&o({stage:"preparing",message:"Initialized agent client",progressPercent:25,details:{state:s}});let u=s.outboundTopicId,p=s.inboundTopicId,h=s.pfpTopicId,g=s.profileTopicId;if(!u||!p||!g){h&&e.setExistingProfilePicture(h);const t=await a.createAgent(e,60,s,e=>{o&&o({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:{...e.details,state:{...s,...e.details?.state}}})});u=t.outboundTopicId,p=t.inboundTopicId,h=t.pfpTopicId,g=t.profileTopicId,s.outboundTopicId=u,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:${u}`)||s.createdResources.push(`outbound:${u}`),s.createdResources.includes(`profile:${g}`)||s.createdResources.push(`profile:${g}`)}s.currentStage="profile",s.completedPercentage=60,o&&o({stage:"submitting",message:"Created agent with topics and profile",progressPercent:60,details:{state:s,outboundTopicId:u,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,r.network,{progressCallback:e=>{const t=60+.4*(e.progressPercent||0);o&&o({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 o&&o({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(dg){const r=dg,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,r){try{this.logger.info("Registering agent with guarded registry");const o=r?.maxAttempts??60,n=r?.delayMs??2e3,s=r?.progressCallback;let a=r?.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=i.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,o,n,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(dg){const t=dg,r=`Failed to register agent: ${t.message}`;return this.logger.error(r),{error:t.message,success:!1}}}async registerAgent(e,t,r,i,o){this.logger.info("Registering agent");const n=Zd({registryTopicId:e,accountId:t,inboundTopicId:r,memo:i});await this.submitPayload(n,void 0,o)}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 Ed.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`),Ed.FEE_BASED}return Ed.CONTROLLED}catch(dg){const t=`Error determining topic type: ${dg.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,r,o){this.logger.info("Creating scheduled transaction");const n=(new i.ScheduleCreateTransaction).setScheduledTransaction(e).setPayerAccountId(o?i.AccountId.fromString(o):this.client.operatorAccountId);if(t&&n.setScheduleMemo(t),r){const e=w.addSeconds(new Date,r),t=i.Timestamp.fromDate(e);n.setExpirationTime(t)}const s=await n.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,o){const n=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:o?.memo};return this.logger.info("Submitting transaction operation to connection topic",s),await this.submitPayload(e,s,i,n.requiresFee)}async sendTransaction(e,t,r,i){this.logger.info("Creating scheduled transaction and sending transaction operation");const{scheduleId:o,transactionId:n}=await this.createScheduledTransaction(t,i?.scheduleMemo,i?.expirationTime,i?.schedulePayerAccountId);return{scheduleId:o,transactionId:n,receipt:await this.sendTransactionOperation(e,o,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,o=qd({ttl:t?.ttl??60,adminKey:!0,submitKey:!0,operatorPublicKey:e}),{topicId:n}=await this.executeTopicCreateTransaction({transaction:o});i.outboundTopicId=n,i.createdResources&&i.createdResources.push(`outbound:${i.outboundTopicId}`)}if(!i.inboundTopicId){i.currentStage="topics",r&&r.preparing("Creating inbound topic",10,{state:i});const o=this.client.operatorPublicKey||this.operatorCtx.operatorKey.publicKey,n=Hd({accountId:e,ttl:t?.ttl??60,adminKey:!0,submitKey:!1,operatorPublicKey:o}),{topicId:s}=await this.executeTopicCreateTransaction({transaction:n});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 o=await this.inscribePfp(e,t);if(!o.success){let e="Failed to inscribe profile picture";throw o.error&&(e=o.error),new Error(e)}const n=o.pfpTopicId;return r.pfpTopicId=n,r.createdResources&&r.createdResources.push(`pfp:${r.pfpTopicId}`),i.preparing("Profile picture created",50,{state:r}),n}async createAndInscribeProfile(e,t,r,i,o,n,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:o,outboundTopicId:n,creator:e.metadata?.creator})}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:o,outboundTopicId:n})}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 o=e.build(),n=this.client.operatorAccountId?.toString();if(!n)throw new Error("Failed to retrieve operator account ID");const s=await this._createEntityTopics(t,{outboundTopicId:r?.outboundTopicId||"",inboundTopicId:r?.inboundTopicId||"",pfpTopicId:r?.pfpTopicId||o.existingPfpTopicId||"",profileTopicId:r?.profileTopicId||""},n,Ed.PUBLIC,void 0,o.pfpBuffer,o.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(o.name,o.mcpServer,{alias:o.alias,bio:o.bio,socials:o.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(n,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,o,n,s,a){let{outboundTopicId:c,inboundTopicId:l,pfpTopicId:d,profileTopicId:u}=t;if(c)this.logger.info(`Using existing outbound topic ID: ${c}`);else{const t=qd({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===Ed.FEE_BASED?o: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}}})),!d&&n&&n.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}}});d=(await this.inscribePfp(n,s)).pfpTopicId,this.logger.info(`Profile picture inscribed with topic ID: ${d}`),a&&a({stage:"preparing",message:"Profile picture inscribed",progressPercent:55,details:{outboundTopicId:c,inboundTopicId:l,pfpTopicId:d,state:{currentStage:"pfp",completedPercentage:55}}})}else d&&this.logger.info(`Using existing profile picture with topic ID: ${d}`);return{inboundTopicId:l,outboundTopicId:c,pfpTopicId:d,profileTopicId:u}}async createAndRegisterMCPServer(e,t){try{const r=e.build(),o=t?.progressCallback,n=t?.baseUrl||this.guardedRegistryBaseUrl;let s=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};s.serverMetadata={name:r.name,description:r.mcpServer.description,services:r.mcpServer.services},o&&o({stage:"preparing",message:"Starting MCP server creation process",progressPercent:0,details:{state:s}});let a,c=r.existingAccount;if(s.inboundTopicId&&s.outboundTopicId&&s.profileTopicId){if(c=c||r.existingAccount,!c)throw new Error("Cannot resume registration without account information");const e=ie(c.privateKey),t=("ed25519"===e.detectedType?i.PrivateKey.fromStringED25519(c.privateKey):i.PrivateKey.fromStringECDSA(c.privateKey)).publicKey.toString();a=new au({network:r.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:t,keyType:e.detectedType,logLevel:"info",guardedRegistryBaseUrl:n}),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:")),i=e?.split(":")[1];i&&r.existingAccount?(c=r.existingAccount,this.logger.info(`Resuming with existing account: ${i}`)):(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}`);o&&o({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:s,account:c}});const l=new oe({mirrorNode:this.mirrorNode,logger:this.logger}),d=await l.resolveOperatorKey(c.accountId,c.privateKey);e.setExistingAccount(c.accountId,c.privateKey);const u=("ed25519"===d.keyType?i.PrivateKey.fromStringED25519(c.privateKey):i.PrivateKey.fromStringECDSA(c.privateKey)).publicKey.toString();a=new au({network:r.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:u,logLevel:"info",guardedRegistryBaseUrl:n}),o&&o({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=>{o&&o({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,o&&o({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,r.network,{progressCallback:e=>{const t=60+.4*(e.progressPercent||0);o&&o({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 o&&o({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(dg){const r=dg,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:o=!1,waitForConfirmation:n=!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:n,waitMaxAttempts:s,waitIntervalMs:a,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},o=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(!o.confirmed||!o.inscription)throw new Error("Metadata inscription was not confirmed");e=La(o.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,d=Wd({ttl:t,metadataTopicId:e,adminKey:i,submitKey:o,operatorPublicKey:this.client.operatorPublicKey||l.publicKey}),{topicId:u,response:p}=await this.executeTopicCreateTransaction({transaction:d});return c&&c({stage:"completed",message:"Registry topic created successfully",progressPercent:100,details:{topicId:u,metadataTopicId:e,transactionId:p.transactionId.toString()}}),this.logger.info(`Registry topic created successfully: ${u}`),{success:!0,topicId:u,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 cu="undefined"!=typeof window;var lu=(e=>(e[e.ACTION=0]="ACTION",e[e.ASSEMBLY=2]="ASSEMBLY",e[e.HASHLINKS=3]="HASHLINKS",e))(lu||{});class du{constructor(e,t,r,i,o){this.entries=new Map,this.networkType=e,this.logger=t,this.registryType=r,this.topicId=i,this.client=o}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:lu[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 o;if(this.logger.info("Inscribing content via HCS-1",{size:i.length,mimeType:t,registryType:lu[this.registryType]}),"getOperatorAccountId"in this.client)o=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:n}=await this.client.getAccountAndSigner();o=await za({type:"buffer",buffer:i,fileName:"application/octet-stream"===t&&"wasm"===r?.fileType?`${r?.name||"content"}.wasm`:r?.name||"content",mimeType:t},n,{mode:"file",metadata:r,waitForConfirmation:!0})}if(!o.confirmed)throw new Error("Failed to inscribe content");const n=o.inscription.topic_id;if(!n)throw new Error("No topic ID in inscription response");return this.logger.info("Content inscribed successfully",{topicId:n}),n}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:lu[this.registryType]})}getStats(){return{entryCount:this.entries.size,lastSync:this.lastSyncTimestamp,topicId:this.topicId,registryType:lu[this.registryType]}}}const uu=r.z.object({p:r.z.literal("hcs-12")}),pu=r.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid Hedera address format"),hu=r.z.string().regex(/^[a-f0-9]{64}$/,"Invalid SHA-256 hash format"),gu=r.z.object({format:r.z.enum(["tar.gz","zip","car"]),root_manifest:r.z.string(),includes_lockfile:r.z.boolean(),workspace_members:r.z.array(r.z.string()).optional()}),mu=r.z.object({source_t_id:pu,source_hash:hu,compiler_version:r.z.string(),cargo_version:r.z.string(),target:r.z.literal("wasm32-unknown-unknown"),profile:r.z.string(),build_flags:r.z.array(r.z.string()),lockfile_hash:hu,source_structure:gu}),fu=r.z.lazy(()=>r.z.object({type:r.z.string().optional(),required:r.z.array(r.z.string()).optional(),properties:r.z.record(fu).optional(),pattern:r.z.string().optional(),minimum:r.z.number().optional(),maximum:r.z.number().optional(),regex:r.z.string().optional(),min:r.z.number().optional(),max:r.z.number().optional(),length:r.z.number().optional(),email:r.z.boolean().optional(),url:r.z.boolean().optional(),uuid:r.z.boolean().optional(),cuid:r.z.boolean().optional(),cuid2:r.z.boolean().optional(),ulid:r.z.boolean().optional(),datetime:r.z.boolean().optional(),ip:r.z.boolean().optional(),startsWith:r.z.string().optional(),endsWith:r.z.string().optional(),includes:r.z.string().optional(),gt:r.z.number().optional(),gte:r.z.number().optional(),lt:r.z.number().optional(),lte:r.z.number().optional(),int:r.z.boolean().optional(),positive:r.z.boolean().optional(),nonnegative:r.z.boolean().optional(),negative:r.z.boolean().optional(),nonpositive:r.z.boolean().optional(),multipleOf:r.z.number().optional(),finite:r.z.boolean().optional(),safe:r.z.boolean().optional(),nonempty:r.z.boolean().optional(),literal:r.z.union([r.z.string(),r.z.number(),r.z.boolean()]).optional(),enum:r.z.array(r.z.string()).optional(),nullable:r.z.boolean().optional(),nullish:r.z.boolean().optional(),optional:r.z.boolean().optional(),element:r.z.any().optional(),shape:r.z.record(r.z.any()).optional(),strict:r.z.boolean().optional(),passthrough:r.z.boolean().optional(),catchall:r.z.any().optional()})),yu=r.z.object({p:r.z.literal("hcs-12"),op:r.z.literal("register"),t_id:pu,hash:hu,wasm_hash:hu,js_t_id:pu.optional(),js_hash:hu.optional(),interface_version:r.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid version format").optional(),info_t_id:pu.optional(),source_verification:mu.optional(),previous_version:r.z.string().optional(),migration_notes:r.z.string().optional(),validation_rules:r.z.record(fu).optional(),m:r.z.string().optional()}),bu=r.z.object({p:r.z.literal("hcs-12"),op:r.z.enum(["register","template"]),name:r.z.string(),version:r.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid semver format"),data:r.z.union([r.z.any(),r.z.string()]).optional(),t_id:pu.optional()});r.z.enum(["register","add-action","add-block","update"]);const wu=uu.extend({op:r.z.literal("register"),name:r.z.string(),version:r.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid semver format"),description:r.z.string().optional(),tags:r.z.array(r.z.string()).optional(),author:r.z.string().optional()}),Iu=uu.extend({op:r.z.literal("add-action"),t_id:pu,alias:r.z.string(),config:r.z.any().optional(),data:pu.optional()}),Tu=uu.extend({op:r.z.literal("add-block"),block_t_id:pu,actions:r.z.record(r.z.string(),pu).optional(),attributes:r.z.record(r.z.any()).optional(),children:r.z.array(r.z.string()).optional(),data:pu.optional()}),Su=uu.extend({op:r.z.literal("update"),description:r.z.string().optional(),tags:r.z.array(r.z.string()).optional()});r.z.object({type:r.z.enum(["vertical","horizontal","grid"]),responsive:r.z.boolean().optional(),containerClass:r.z.string().optional()}),r.z.object({source_t_id:pu,source_hash:hu,description:r.z.string().optional()});const ku=r.z.discriminatedUnion("op",[wu,Iu,Tu,Su]),Eu=wu,Au=uu.extend({op:r.z.literal("register"),t_id:pu,name:r.z.string().max(100,"Name must be 100 characters or less"),description:r.z.string().max(500,"Description must be 500 characters or less").optional(),tags:r.z.array(r.z.string()).max(10,"Maximum 10 tags allowed").optional(),category:r.z.string().optional(),featured:r.z.boolean().optional(),icon:r.z.string().optional(),author:r.z.string().optional(),website:r.z.string().url().optional()});function vu(e){return yu.parse(e)}function Cu(e){return ku.parse(e)}function xu(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 Ru extends du{constructor(e,t,r,i){super(e,t,lu.ACTION,r,i),this.actionsByHash=new Map,this.cryptoAdapter=cd()}async registerWithWasm(e,t,r){let i,o;if(td()){i=this.createSSRSafeHash(e,"wasm");const r=JSON.stringify(t);o=this.createSSRSafeHash(globalThis.Buffer.from(r),"info")}else{const r=this.cryptoAdapter.createHash("sha256").update(e).digest("hex"),n=r instanceof Promise?await r:r;i="string"==typeof n?n:n.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;o="string"==typeof c?c:c.toString("hex")}const n=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:n,hash:o,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 Da(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 Da(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(td())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 Da(t.t_id,{accountId:this.client.getOperatorAccountId(),privateKey:this.client.getOperatorPrivateKey(),network:this.networkType});else{const{accountId:r}=await this.client.getAccountAndSigner();e=await Da(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(td())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{vu(e)}catch(t){if(t instanceof r.ZodError){const e=t.errors[0];throw new Error(`Validation failed: ${e.path.join(".")} - ${e.message}`)}throw t}}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 Nu{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 Yl,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 Yl,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 o={...t,template_t_id:i.topic_id},n=globalThis.Buffer.from(JSON.stringify(o)),s=await this.client.inscribeFile(n,`block-${t.name}-definition.json`);if(!s?.topic_id)throw new Error("Failed to inscribe block definition");return this.blockCache.set(s.topic_id,o),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 _u extends du{constructor(e,t,r,i){super(e,t,lu.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 o=t,n={t_id:o.t_id,alias:o.alias,config:o.config,data:o.data};r.actions.push(n),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 n of r)try{let e;if(!n.message)continue;try{let t;t="undefined"==typeof window?globalThis.Buffer.from(n.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(n.message),e=>e.charCodeAt(0))),e=JSON.parse(t),this.logger.debug("Successfully parsed message",{sequenceNumber:n.sequence_number,op:e.op,p:e.p})}catch(i){this.logger.debug("Failed to decode/parse message",{sequenceNumber:n.sequence_number,error:i});continue}if("hcs-12"!==e.p){this.logger.debug("Skipping non-HCS-12 message",{sequenceNumber:n.sequence_number,protocol:e.p});continue}const r={id:n.sequence_number.toString(),sequenceNumber:n.sequence_number,timestamp:n.consensus_timestamp||(new Date).toISOString(),submitter:n.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:n.sequence_number,error:i})}const o=this.assemblyStates.get(t)||null;return this.logger.info("Assembly state after sync",{topicId:t,hasState:!!o,name:o?.name,version:o?.version,actionsCount:o?.actions?.length||0,blocksCount:o?.blocks?.length||0}),o}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 o=r;i={topicId:e,name:o.name,version:o.version,description:o.description,tags:o.tags,author:o.author,actions:[],blocks:[],created:t.timestamp,updated:t.timestamp},this.assemblyStates.set(e,i),this.logger.debug("Assembly registered",{topicId:e,name:o.name,version:o.version});break;case"add-action":if(!i)return void this.logger.warn("Cannot add action without assembly registration");const n=r,s={t_id:n.t_id,alias:n.alias,config:n.config,data:n.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{Cu(e)}catch(t){if(t instanceof r.ZodError){const e=t.errors.map(e=>`${e.path.join(".")}: ${e.message}`);throw new Error(`Assembly validation failed: ${e.join("; ")}`)}throw t}}}class Pu extends du{constructor(e,t,r,i){super(e,t,lu.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),o=await this.client.submitMessage(this.topicId,i);return o.sequenceNumber&&(r.sequenceNumber=o.sequenceNumber,r.id=o.sequenceNumber.toString(),this.entries.delete(t),this.entries.set(r.id,r)),this.logger.info("HashLink submitted to HCS",{transactionId:o.transactionId,sequenceNumber:o.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=xu(e,Au);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 o=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&&o++}),{...e,categories:r.size,totalTags:i.size,featuredCount:o}}}class Fu{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,o]of Object.entries(r.actions)){const n=e.state.actions?.some(e=>e.t_id===o);n||t.push(`Block ${r.block_t_id} references non-existent action: ${o} for key ${i}`)}if(r.children)for(const i of r.children){const o=e.state.blocks?.some(e=>e.block_t_id===i);o||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 Ou{constructor(e){this.network=e.network,this.logger=e.logger||B.getInstance({level:e.logLevel||"info",module:"HCS12-BaseClient",prettyPrint:e.prettyPrint,silent:e.silent}),this.mirrorNode=new J(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 Nu(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 _u(this.network,this.logger,e,this);await t.sync();return new Fu(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 Fu(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 zu{constructor(){this.block={apiVersion:3},this.attributes={},this.supports={},this.actions={},this.logger=new B({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 o={type:t,default:r};return i?.enum&&(o.enum=i.enum),i?.source&&(o.source=i.source),i?.selector&&(o.selector=i.selector),i?.attribute&&(o.attribute=i.attribute),this.attributes[e]=o,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 zu).setName(e).setTitle(t).setCategory("formatting").enableCommonSupports()}static createInteractiveBlock(e,t){return(new zu).setName(e).setTitle(t).setCategory("widgets").enableCommonSupports()}static createWidgetBlock(e,t){return this.createInteractiveBlock(e,t)}static createContainerBlock(e,t){return(new zu).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 Du{constructor(e,t){this.wasmCache=new Map,this.logger=e,this.network=t,this.hrlResolver=new Yl}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"}),o=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(o);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 n=i.WasmInterface;if(!n)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 n;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(o),{success:!0,data:c}}catch(dg){throw URL.revokeObjectURL(o),dg}}}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 Bu{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],n=i[2],s=i[3];try{const i=this.parseHashLinkURI(n),o=s.match(/data-attributes=(['"])((?:(?!\1).)*)\1/s);let a;if(o)try{const e=o[2];a=JSON.parse(e)}catch(dg){this.logger.warn("Failed to parse data-attributes",{uri:n,attributes:o[2],error:dg.message})}const c=s.match(/data-actions=(['"])((?:(?!\1).)*)\1/s);let l;if(c)try{const e=c[2];l=JSON.parse(e)}catch(dg){this.logger.warn("Failed to parse data-actions",{uri:n,actions:c[2],error:dg.message})}const d=s.match(/data-loading=['"]([^'"]+)['"]/),u=d?.[1]||"eager";t.push({element:r,uri:n,...i,attributes:a,actions:l,loading:u,placeholder:e}),this.logger.debug("Found HashLink reference",{uri:n,parsed:i})}catch(o){this.logger.error("Failed to parse HashLink URI",{uri:n,error:o.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 Mu{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 o=await this.blockLoader.loadBlock(r);if(!o||!o.definition)throw new Error(`Block not found: ${r}`);const n={...this.extractDefaults(o.definition),...t.attributes,...e.attributes},s={...t.actions,...e.actions},a={blockId:r,definition:o.definition,template:o.template,attributes:n,actions:s};return this.cache.set(i,a),a}catch(o){throw this.renderStack.delete(r),new Error(`Failed to load HCS-12 block ${r}: ${o.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 Uu={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"}},Lu={ACTIONS:{},BLOCKS:{},ASSEMBLIES:{}};const Ku=/^[a-z0-9][a-z0-9-]*$/,$u=r.z.object({registry:r.z.string().min(1),name:r.z.string().min(1),version:r.z.string().min(1),protocol:r.z.string().min(1),nativeId:r.z.string().min(1),skills:r.z.array(r.z.number().int().nonnegative())});function Hu(e){return e.trim()}function qu(e){return e.trim().toLowerCase()}function ju(e){const t=$u.parse(e);if("hcs-10"===t.protocol.trim().toLowerCase()&&!pd(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()&&!fd(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:qu(t.registry),name:Hu(t.name),version:Hu(t.version),protocol:qu(t.protocol),nativeId:Hu(t.nativeId),skills:[...t.skills].sort((e,t)=>e-t)},i=["skills","name","nativeId","protocol","registry","version"],o={};for(const n of i)o[n]=r[n];return{normalized:r,canonicalJson:JSON.stringify(o)}}const Wu="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function Vu(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 o=t;o<e.length;o++){let t=e[o];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 o=0;o<t;o++)i+="1";for(let o=r.length-1;o>=0;o--)i+=Wu[r[o]];return i}function Gu(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],o=Wu.indexOf(t);if(-1===o)throw new Error("Invalid Base58 character");let n=o;for(let e=0;e<r.length;e++){const t=58*r[e]+n;r[e]=255&t,n=t>>8}for(;n>0;)r.push(255&n),n>>=8}for(let i=0;i<t;i++)r.push(0);return r.reverse(),Uint8Array.from(r)}(e.slice(1))}function Ju(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 Yu(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(":"),o=e.indexOf(":",t+1);if(o<0)throw new Error("Invalid DID format");r=e.slice(t+1,o),i=e.slice(o+1)}}const{sanitized:o,hadSuffix:n}=function(e){const t=e.search(/[;?#]/);return-1===t?{sanitized:e,hadSuffix:!1}:{sanitized:e.slice(0,t),hadSuffix:!0}}(i);let s=o;if("hedera"===r){const e=o.match(/^(mainnet|testnet|previewnet|devnet):(.+)$/);e&&(s=e[2])}const a={...t||{}};var c;n&&!a.src&&(a.src=(c=e,"z"+Vu(globalThis.Buffer.from(c,"utf8"))));const l=Ju(a);return l?`uaid:did:${s};${l}`:`uaid:did:${s}`}function Xu(e,t,r){return"string"==typeof e?Yu(e,t):async function(e,t,r){const{normalized:i,canonicalJson:o}=ju(e),n=cd().createHash("sha384").update(globalThis.Buffer.from(o,"utf8")).digest(),s=await Promise.resolve(n),a=Vu(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||{}):{},d=c?Ju(l):"";return d?`uaid:aid:${a};${d}`:`uaid:aid:${a}`}(e,t,r)}function Zu(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 o=i.indexOf(";"),n=o>=0?i.slice(0,o):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),o=i.slice(e+1);t[r]=o}}return t})(o>=0?i.slice(o+1):"");return{method:"did"===r?"uaid":"aid",id:n,params:s}}throw new Error("Invalid DID")}let Qu;function ep(e,t){if(!t||"object"!=typeof t)return!1;const r=Reflect.get(t,"code"),i=Reflect.get(t,"message"),o="string"==typeof i?i:"";if("string"==typeof r&&r.includes("MODULE_NOT_FOUND"))return o.includes(e);if(o){const t=o.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 tp(e){try{return await import(e)}catch(t){if(ep(e,t))return null;throw t}}async function rp(e){if(Ca)return tp(e);const t=await async function(){if(void 0!==Qu)return Qu;if(Ca)return Qu=null,Qu;try{const e="undefined"!=typeof global?global:globalThis,t=e.process?.mainModule?.require??e.require;Qu="function"==typeof t&&"function"==typeof t.resolve?t:null}catch{Qu=null}return Qu}();if(t)try{return t(e)}catch(r){if(!ep(e,r))throw r}return tp(e)}const ip=["@hiero-did-sdk","resolver"].join("/");let op=null;class np{constructor(){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 op||(op=rp(ip).then(e=>e?.resolveDID??null)),op}();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 sp{constructor(){this.resolvers=[]}register(e){this.resolvers.push(e)}list(){return[...this.resolvers]}filterByDidMethod(e){return this.resolvers.filter(t=>t.meta?.didMethods?.includes(e))}async resolveDid(e){for(const t of this.resolvers)if(t.supports(e))return t.resolve(e);return null}async resolveUaid(e){const t=Zu(e);if("uaid"!==t.method)return null;const r=t.params.src;if(r){const e=globalThis.Buffer.from(Gu(r)).toString("utf8");return this.resolveDid(e)}const i=t.id;if(i.startsWith("testnet:")||i.startsWith("mainnet:")||i.startsWith("previewnet:")||i.startsWith("devnet:")){const e=`did:hedera:${i}`;return this.resolveDid(e)}const o=t.params.proto,n=t.params.nativeId;if("hcs-10"===o&&n){const e=n.match(/^hedera:(mainnet|testnet|previewnet|devnet):/);if(e){const t=`did:hedera:${e[1]}:${i}`;return this.resolveDid(t)}}return null}}const ap=new sp;function cp(){ap.register(new np)}class lp{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 dp=new lp,up=["@hiero-did-sdk","registrar"].join("/");let pp=null;class hp{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 pp||(pp=rp(up).then(e=>e?.createDID??null)),pp}();if(!t)throw new Error("Hiero registrar unavailable. Ensure @hiero-did-sdk/registrar is installed.");return(await t({},{client:e.client})).did}}class gp{constructor(e){this.registry=e?.registry??ap,this.issuers=new lp,this.registerHederaIssuer(),this.registerHederaResolver(),this.logger=B.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,r){const o=ne({network:e,operatorId:t,operatorKey:r,mirrorNode:new J(e),logger:this.logger,client:i.Client.forName(e)});this.operatorCtx=o,this.client=o.client,this.network=e,this.operatorId=t,this.operatorPrivateKey=r}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()}listResolvers(){return this.registry.list()}filterIssuersByMethod(e){return this.issuers.filterByDidMethod(e)}filterResolversByMethod(e){return this.registry.filterByDidMethod(e)}registerHederaIssuer(){this.issuers.register(new hp)}async createDid(e){return this.issuers.issue(e)}canonicalizeAgentData(e){return ju(e)}createUaid(e,t,r){return"string"==typeof e?Xu(e,t):Xu(e,t,r)}parseHcs14Did(e){return Zu(e)}isHederaNetwork(e){return dd(e)}isHederaCaip10(e){return pd(e)}toHederaCaip10(e,t){return hd(e,t)}parseHederaCaip10(e){return gd(e)}isEip155Caip10(e){return fd(e)}toEip155Caip10(e,t){return yd(e,t)}getResolverRegistry(){return this.registry}registerHederaResolver(){this.registry.register(new np)}async createDidWithUaid(e){const t=await this.createDid(e.issue);let r=e.uid;const i=e.proto;let o=e.nativeId;if("hedera"===e.issue.method){if(await this.ensureInitializedHedera(),!o){if(!this.network||!this.operatorId)throw new Error("nativeId not provided and network/operatorId are not configured");o=hd(this.network,this.operatorId)}if(!r&&"hcs-10"===i&&this.network&&this.operatorId)try{if(!this.hcs10Client&&this.operatorPrivateKey&&(this.hcs10Client=new au({network:this.network,operatorId:this.operatorId,operatorPrivateKey:this.operatorPrivateKey,silent:!0})),this.hcs10Client)r=await this.hcs10Client.getOperatorId();else{const e=new Ld({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 n=this.createUaid(t,{uid:r,proto:i,nativeId:o});return{did:t,uaid:n,parsed:Zu(n)}}}const mp=Object.freeze(Object.defineProperty({__proto__:null,CanonicalAgentDataSchema:$u,HCS14Client:gp,HCS14_PROTOCOL_REGEX:Ku,HederaHieroIssuer:hp,HieroDidResolver:np,IssuerRegistry:lp,ResolverRegistry:sp,canonicalizeAgentData:ju,createUaid:Xu,defaultIssuerRegistry:dp,defaultResolverRegistry:ap,isEip155Caip10:fd,isHederaCaip10:pd,isHederaNetwork:dd,parseHcs14Did:Zu,parseHederaCaip10:gd,registerDefaultResolvers:cp,toEip155Caip10:yd,toHederaCaip10:hd},Symbol.toStringTag,{value:"Module"}));function fp(e){return`hcs://1/${e}`}class yp{constructor(e){this.network=e.network,this.logger=e.logger||B.getInstance({level:e.logLevel||"info",module:"HCS5Client",silent:e.silent}),this.mirrorNode=new J(this.network,this.logger)}}function bp(e){const t=(new i.TokenMintTransaction).setTokenId(i.TokenId.fromString(e.tokenId)).setMetadata([globalThis.Buffer.from(e.metadata)]);return e.transactionMemo&&t.setTransactionMemo(e.transactionMemo),t}var wp=(e=>(e.REGISTER="register",e.UPDATE="update",e.DELETE="delete",e.MIGRATE="migrate",e))(wp||{}),Ip=(e=>(e[e.INDEXED=0]="INDEXED",e[e.NON_INDEXED=1]="NON_INDEXED",e))(Ip||{});const Tp=r.z.string().regex(/^\d+\.\d+\.\d+$/,{message:"Topic ID must be in Hedera format (e.g., '0.0.123456')"}),Sp=r.z.object({p:r.z.string().regex(/^hcs-\d+$/,{message:"Protocol must be in format 'hcs-N' where N is a number"}),op:r.z.enum(["register","update","delete","migrate"]),m:r.z.string().max(500,"Memo must not exceed 500 characters").optional(),ttl:r.z.number().int().positive().optional()}),kp=Sp.extend({op:r.z.literal("register"),t_id:Tp,metadata:r.z.string().optional()}),Ep=Sp.extend({op:r.z.literal("update"),uid:r.z.string(),t_id:Tp,metadata:r.z.string().optional()}),Ap=Sp.extend({op:r.z.literal("delete"),uid:r.z.string()}),vp=Sp.extend({op:r.z.literal("migrate"),t_id:Tp,metadata:r.z.string().optional()}),Cp=r.z.discriminatedUnion("op",[kp,Ep,Ap,vp]);class xp{constructor(e){this.network=e.network,this.logger=e.logger||B.getInstance({level:e.logLevel||"info",module:"HCS2Client",silent:e.silent}),this.mirrorNode=new J(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 Cp.parse(e),{valid:!0,errors:[]}}catch(t){const e=[];return t instanceof r.ZodError?t.errors.forEach(t=>{const r=t.path.join(".");e.push(`${r?r+": ":""}${t.message}`)}):e.push(`Unexpected error: ${t}`),this.logger.debug(`Message validation failed: ${e.join(", ")}`),{valid:!1,errors:e}}}createRegisterMessage(e,t,r,i="hcs-2"){return{p:i,op:wp.REGISTER,t_id:e,metadata:t,m:r}}createUpdateMessage(e,t,r,i,o="hcs-2"){return{p:o,op:wp.UPDATE,t_id:e,uid:t,metadata:r,m:i}}createDeleteMessage(e,t,r="hcs-2"){return{p:r,op:wp.DELETE,uid:e,m:t}}createMigrateMessage(e,t,r,i="hcs-2"){return{p:i,op:wp.MIGRATE,t_id:e,metadata:t,m:r}}parseRegistryEntries(e,t,r,i){const o=[];let n;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};o.push(l),(r===Ip.NON_INDEXED||!n||l.timestamp>n.timestamp)&&(n=l)}catch(s){this.logger.warn(`Error parsing message: ${s}`)}return this.logger.debug(`Parsed ${o.length} valid entries for topic ${e}`),{topicId:e,registryType:r,ttl:i,entries:r===Ip.INDEXED?o:n?[n]:[],latestEntry:n}}}function Rp(e){var t,r;return X({memo:e.memoOverride??(t=e.registryType,r=e.ttl,`hcs-2:${t}:${r}`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}const Np=class e extends xp{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?i.AccountId.fromString(e.operatorId):e.operatorId,this.operatorCtx=ne({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:this.createClient(e.network)}),this.client=this.operatorCtx.client}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}createClient(e){return"mainnet"===e?i.Client.forMainnet():i.Client.forTestnet()}async createRegistry(e={}){try{await this.ensureInitialized();const t=e.registryType??Ip.INDEXED,r=e.ttl??86400;this.generateRegistryMemo(t,r);let o,n,s,a;if(e.adminKey)if("string"==typeof e.adminKey)try{n=i.PublicKey.fromString(e.adminKey)}catch{const t=globalThis.Buffer.from(e.adminKey.replace(/^0x/i,""),"hex");n="ed25519"===this.operatorCtx.keyType?i.PublicKey.fromBytesED25519(t):i.PublicKey.fromBytesECDSA(t)}else"boolean"==typeof e.adminKey?n=this.operatorCtx.operatorKey.publicKey:(n=e.adminKey.publicKey,o=e.adminKey);if(e.submitKey)if("string"==typeof e.submitKey)try{a=i.PublicKey.fromString(e.submitKey)}catch{const t=globalThis.Buffer.from(e.submitKey.replace(/^0x/i,""),"hex");a="ed25519"===this.operatorCtx.keyType?i.PublicKey.fromBytesED25519(t):i.PublicKey.fromBytesECDSA(t)}else"boolean"==typeof e.submitKey?a=this.operatorCtx.operatorKey.publicKey:(a=e.submitKey.publicKey,s=e.submitKey);const c=Rp({registryType:t,ttl:r,adminKey:n,submitKey:a,operatorPublicKey:this.operatorCtx.operatorKey.publicKey}),l=await c.freezeWith(this.client);o&&await l.sign(o),s&&await l.sign(s);const d=await l.execute(this.client),u=(await d.getReceipt(this.client)).topicId;if(!u)throw new Error("Failed to create registry: No topic ID in receipt");const p=u.toString();return this.registryTypeCache.set(p,t),this.logger.info(`Created registry topic: ${p} (${t===Ip.INDEXED?"Indexed":"Non-indexed"}, TTL: ${r}s)`),{success:!0,topicId:p,transactionId:d.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),o=t.registryType??await this.resolveRegistryType(e);this.registryTypeCache.set(e,o);const n=t.analyticsMemo??this.buildAnalyticsMemo(wp.REGISTER,o),s=await this.submitMessage(e,i,n);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!==Ip.INDEXED)throw new Error("Update operation is only valid for indexed registries");const o=this.createUpdateMessage(t.targetTopicId,t.uid,t.metadata,t.memo),n=t.registryType??await this.resolveRegistryType(e);this.registryTypeCache.set(e,n);const s=t.analyticsMemo??this.buildAnalyticsMemo(wp.UPDATE,n),a=await this.submitMessage(e,o,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!==Ip.INDEXED)throw new Error("Delete operation is only valid for indexed registries");const o=this.createDeleteMessage(t.uid,t.memo),n=t.registryType??await this.resolveRegistryType(e);this.registryTypeCache.set(e,n);const s=t.analyticsMemo??this.buildAnalyticsMemo(wp.DELETE,n),a=await this.submitMessage(e,o,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 o=t.analyticsMemo??this.buildAnalyticsMemo(wp.MIGRATE,i),n=await this.submitMessage(e,r,o);return this.logger.info(`Migrated registry ${e} to ${t.targetTopicId}`),{success:!0,receipt:n,sequenceNumber:n.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 i=await this.mirrorNode.getTopicInfo(e);this.logger.debug(`Retrieved topic info for ${e}: ${JSON.stringify(i)}`);const o=this.parseRegistryTypeFromMemo(i.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 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"}),s=t.limit?n.slice(0,t.limit):n;this.logger.debug(`Retrieved ${n.length} messages, using ${s.length} after applying limit.`);const a=[];let c;for(const t of s)try{const r={p:"hcs-2",op:t.op,t_id:t.t_id,uid:t.uid,metadata:t.metadata,m:t.m},{valid:i,errors:n}=this.validateMessage(r);if(!i){this.logger.warn(`Invalid HCS-2 message: ${n.join(", ")}`);continue}const s={topicId:e,sequence:t.sequence_number,timestamp:t.consensus_timestamp,payer:t.payer_account_id||t.payer||"",message:r,consensus_timestamp:t.consensus_timestamp,registry_type:o.registryType};a.push(s),(o.registryType===Ip.NON_INDEXED||!c||s.timestamp>c.timestamp)&&(c=s)}catch(r){this.logger.warn(`Error processing message: ${r}`)}this.logger.debug(`Processed ${a.length} valid entries for registry ${e}`);return{topicId:e,registryType:o.registryType,ttl:o.ttl,entries:o.registryType===Ip.INDEXED?a:c?[c]:[],latestEntry:c}}catch(r){throw this.logger.error(`Failed to get registry: ${r}`),r}}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:o}=this.validateMessage(t);if(!i)throw new Error(`Invalid HCS-2 message: ${o.join(", ")}`);const n=Z({topicId:e,message:JSON.stringify(t),transactionMemo:r}),s=await n.execute(this.client);return await s.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}};Np.operationAnalyticsCode={[wp.REGISTER]:0,[wp.UPDATE]:1,[wp.DELETE]:2,[wp.MIGRATE]:3};let _p=Np;class Pp extends xp{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,mirrorNodeUrl:e.mirrorNodeUrl,logger:e.logger}),this.hwc=e.hwc,Ca?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??Ip.INDEXED,r=e.ttl??86400,o=this.generateRegistryMemo(t,r);let n=(new i.TopicCreateTransaction).setTopicMemo(o);if(e.adminKey){let t;if("string"==typeof e.adminKey)try{t=i.PublicKey.fromString(e.adminKey)}catch{const r=re.detect(e.adminKey);if(!r.rawBytes)throw new Error("Failed to parse admin public key");t="ed25519"===r.type?i.PublicKey.fromBytesED25519(r.rawBytes):i.PublicKey.fromBytesECDSA(r.rawBytes)}else t="boolean"==typeof e.adminKey?await this.mirrorNode.getPublicKey(this.getOperatorId()):e.adminKey.publicKey;n=n.setAdminKey(t)}if(e.submitKey){let t;if("string"==typeof e.submitKey)try{t=i.PublicKey.fromString(e.submitKey)}catch{const r=re.detect(e.submitKey);if(!r.rawBytes)throw new Error("Failed to parse submit public key");t="ed25519"===r.type?i.PublicKey.fromBytesED25519(r.rawBytes):i.PublicKey.fromBytesECDSA(r.rawBytes)}else t="boolean"==typeof e.submitKey?await this.mirrorNode.getPublicKey(this.getOperatorId()):e.submitKey.publicKey;n=n.setSubmitKey(t)}const s=await this.executeWithWallet(n);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===Ip.INDEXED?"Indexed":"Non-indexed"}, TTL: ${r}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!==wp.REGISTER)throw new Error(`Invalid operation type: ${r.op}, expected ${wp.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!==Ip.INDEXED)throw new Error("Update operation is only valid for indexed registries");const o=this.createUpdateMessage(t.targetTopicId,t.uid,t.metadata,t.memo),n=await this.submitMessage(e,o);return this.logger.info(`Updated entry with UID ${t.uid} in registry ${e}`),{success:!0,receipt:n,sequenceNumber:n.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!==Ip.INDEXED)throw new Error("Delete operation is only valid for indexed registries");const o=this.createDeleteMessage(t.uid,t.memo),n=await this.submitMessage(e,o);return this.logger.info(`Deleted entry with UID ${t.uid} from registry ${e}`),{success:!0,receipt:n,sequenceNumber:n.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 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"}),n=t.limit?o.slice(0,t.limit):o;return this.parseRegistryEntries(e,n,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 o=Z({topicId:e,message:JSON.stringify(t)}),n=await this.executeWithWallet(o);if(n?.error)throw new Error(n.error);return n.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 Fp={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*))$/},Op=r.z.string().regex(Fp.HEDERA_ACCOUNT_REGEX,"Invalid Hedera account ID format"),zp=r.z.string().regex(/^\d+$/,"Must be a valid number").max(Fp.MAX_NUMBER_LENGTH,`Max ${Fp.MAX_NUMBER_LENGTH} digits`),Dp=r.z.string().min(1,"Tick cannot be empty").transform(e=>e.toLowerCase().trim()),Bp=r.z.object({p:r.z.literal("hcs-20"),m:r.z.string().optional()}),Mp=Bp.extend({op:r.z.literal("deploy"),name:r.z.string().min(1).max(Fp.MAX_NAME_LENGTH),tick:Dp,max:zp,lim:zp.optional(),metadata:r.z.string().max(Fp.MAX_METADATA_LENGTH).optional()}),Up=Bp.extend({op:r.z.literal("mint"),tick:Dp,amt:zp,to:Op}),Lp=Bp.extend({op:r.z.literal("burn"),tick:Dp,amt:zp,from:Op}),Kp=Bp.extend({op:r.z.literal("transfer"),tick:Dp,amt:zp,from:Op,to:Op}),$p=Bp.extend({op:r.z.literal("register"),name:r.z.string().min(1).max(Fp.MAX_NAME_LENGTH),metadata:r.z.string().max(Fp.MAX_METADATA_LENGTH).optional(),private:r.z.boolean(),t_id:Op}),Hp=r.z.discriminatedUnion("op",[Mp,Up,Lp,Kp,$p]);class qp extends Error{constructor(e){super(e),this.name="HCS20Error"}}class jp extends qp{constructor(e,t){super(e),this.tick=t,this.name="PointsDeploymentError"}}class Wp extends qp{constructor(e,t,r,i,o,n){super(e),this.tick=t,this.from=r,this.to=i,this.amount=o,this.availableBalance=n,this.name="PointsTransferError"}}class Vp extends qp{constructor(e,t,r,i,o){super(e),this.tick=t,this.from=r,this.amount=i,this.availableBalance=o,this.name="PointsBurnError"}}class Gp extends qp{constructor(e,t){super(e),this.validationErrors=t,this.name="PointsValidationError"}}class Jp extends qp{constructor(e,t){super(e),this.topicId=t,this.name="TopicRegistrationError"}}class Yp extends qp{constructor(e){super(`Invalid Hedera account format: ${e}`),this.account=e,this.name="InvalidAccountFormatError"}}class Xp{constructor(e){this.logger=e.logger||new B({module:"HCS20Client"}),this.network="mainnet"===e.network?"mainnet":"testnet",this.mirrorNode=new J(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0),this.registryTopicId=e.registryTopicId||Fp.REGISTRY_TOPIC_ID,this.publicTopicId=e.publicTopicId||Fp.PUBLIC_TOPIC_ID}validateMessage(e){try{return Hp.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(!Fp.HEDERA_ACCOUNT_REGEX.test(e))throw new Yp(e);return e}return e.toString()}topicToString(e){if("string"==typeof e){if(!Fp.HEDERA_ACCOUNT_REGEX.test(e))throw new Yp(e);return e}return e.toString()}}function Zp(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 Z({topicId:e.topicId,message:JSON.stringify(t)})}function Qp(e){const t={p:"hcs-20",op:"mint",tick:e.tick.toLowerCase().trim(),amt:e.amt,to:e.to,m:e.memo};return Z({topicId:e.topicId,message:JSON.stringify(t)})}function eh(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 Z({topicId:e.topicId,message:JSON.stringify(t)})}function th(e){const t={p:"hcs-20",op:"burn",tick:e.tick.toLowerCase().trim(),amt:e.amt,from:e.from,m:e.memo};return Z({topicId:e.topicId,message:JSON.stringify(t)})}function rh(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 Z({topicId:e.registryTopicId,message:JSON.stringify(t)})}const ih="hcs-21",oh=/^hcs:\/\/1\/0\.0\.\d+\/\d+$/,nh=/^0\.0\.\d+$/;var sh=(e=>(e[e.ADAPTER_REGISTRY=0]="ADAPTER_REGISTRY",e[e.REGISTRY_OF_REGISTRIES=1]="REGISTRY_OF_REGISTRIES",e))(sh||{});const ah=r.z.object({registry:r.z.string().min(1),name:r.z.string().min(1),version:r.z.string().min(1),integrity:r.z.string().min(1)}),ch=r.z.object({account:r.z.string().min(1),threshold:r.z.string().min(1),ctopic:r.z.string().min(1),ttopic:r.z.string().min(1),stopic:r.z.string().min(1)}),lh=r.z.object({p:r.z.literal(ih),op:r.z.enum(["register","update","delete"]),adapter_id:r.z.string().min(1),entity:r.z.string().min(1),package:ah,manifest:r.z.string().regex(oh,"manifest must be an HCS-1 HRL (hcs://1/<topicId>/<sequence>)"),flora:ch,state_model:r.z.string().min(1),signature:r.z.string().min(1).optional()}),dh=r.z.object({meta:r.z.object({spec_version:r.z.string().min(1),adapter_version:r.z.string().min(1),minimum_flora_version:r.z.string().min(1),generated:r.z.string().min(1)}),adapter:r.z.object({name:r.z.string().min(1),id:r.z.string().min(1),maintainers:r.z.array(r.z.object({name:r.z.string().min(1),contact:r.z.string().min(1)})).min(1),license:r.z.string().min(1)}),package:r.z.object({registry:r.z.string().min(1),dist_tag:r.z.string().min(1).optional(),artifacts:r.z.array(r.z.object({url:r.z.string().min(1),digest:r.z.string().min(1),signature:r.z.string().min(1).optional()})).min(1)}),runtime:r.z.object({platforms:r.z.array(r.z.string().min(1)).min(1),primary:r.z.string().min(1),entry:r.z.string().min(1),dependencies:r.z.array(r.z.string().min(1)).optional(),env:r.z.array(r.z.string().min(1)).optional()}),capabilities:r.z.object({discovery:r.z.boolean(),communication:r.z.boolean(),protocols:r.z.array(r.z.string().min(1))}),consensus:r.z.object({entity_schema:r.z.string().min(1),required_fields:r.z.array(r.z.string().min(1)),hashing:r.z.literal("sha384")})}),uh=r.z.object({version:r.z.string().min(1),name:r.z.string().min(1),description:r.z.string().min(1),operator:r.z.object({account:r.z.string().min(1),name:r.z.string().optional(),contact:r.z.string().optional()}),entityTypes:r.z.array(r.z.string().min(1)),categories:r.z.array(r.z.string().min(1)).optional(),tags:r.z.array(r.z.string().min(1)).optional(),links:r.z.record(r.z.string().min(1)).optional()}),ph=r.z.union([dh,uh]);class hh extends Error{constructor(e,t){super(e),this.code=t,this.name="HCS21ValidationError"}}function gh(e){const t=e.indexed??0,r=e.type??sh.ADAPTER_REGISTRY;if(e.metaTopicId&&!nh.test(e.metaTopicId))throw new hh("Meta topic must be a Hedera topic ID (0.0.x)","invalid_payload");const i=e.metaTopicId?`:${e.metaTopicId}`:"";return`hcs-21:${t}:${e.ttl}:${r}${i}`}function mh(e){return X({memo:gh({ttl:e.ttl,indexed:e.indexed,type:e.type,metaTopicId:e.metaTopicId}),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function fh(e){return Z({topicId:e.topicId,message:JSON.stringify(e.declaration),transactionMemo:e.transactionMemo})}class yh{constructor(e){this.network=e.network,this.logger=e.logger||new B({level:"info",module:"HCS-21"}),this.mirrorNode=new J(this.network,this.logger,{customUrl:e.mirrorNodeUrl})}buildDeclaration(e){const t={p:ih,op:e.op,adapter_id:e.adapterId,entity:e.entity,package:e.adapterPackage,manifest:e.manifest,flora:e.flora,state_model:e.stateModel,signature:e.signature};return this.validateDeclaration(t)}validateDeclaration(e){try{const t="string"==typeof e?JSON.parse(e):e,r=lh.parse(t);return this.assertSizeLimit(r),r}catch(t){const e=t instanceof Error?t.message:"Invalid adapter declaration";throw new hh(e,"invalid_payload")}}async fetchDeclarations(e,t){const r=await this.mirrorNode.getTopicMessages(e,{limit:t?.limit,order:t?.order}),i=[];for(const n of r)if(n.p===ih)try{const e=this.validateDeclaration(n);i.push({declaration:e,consensusTimestamp:n.consensus_timestamp,sequenceNumber:n.sequence_number,payer:n.payer})}catch(o){const e=o instanceof Error?o.message:"unknown error";this.logger.warn(`Skipping invalid HCS-21 message: ${e}`)}return i}assertSizeLimit(e){const t=JSON.stringify(e),r=globalThis.Buffer.byteLength(t,"utf8");if(r>1024)throw new hh(`HCS-21 payload exceeds 1024 bytes (${r})`,"size_exceeded")}}function bh(e){const t=(new i.AccountCreateTransaction).setECDSAKeyWithAlias(e.publicKey).setInitialBalance(e.initialBalance instanceof i.Hbar?e.initialBalance:new i.Hbar(e.initialBalance??1));return"number"==typeof e.maxAutomaticTokenAssociations&&t.setMaxAutomaticTokenAssociations(e.maxAutomaticTokenAssociations),e.accountMemo&&t.setAccountMemo(e.accountMemo),t}function wh(e){const t=(new i.AccountCreateTransaction).setKeyWithoutAlias(e.publicKey).setInitialBalance(e.initialBalance instanceof i.Hbar?e.initialBalance:new i.Hbar(e.initialBalance??1));return"number"==typeof e.maxAutomaticTokenAssociations&&t.setMaxAutomaticTokenAssociations(e.maxAutomaticTokenAssociations),e.accountMemo&&t.setAccountMemo(e.accountMemo),t}class Ih{constructor(e){this.network=e.network,this.logger=e.logger||new B({module:"HCS-15",level:e.logLevel||"info"}),this.mirrorNode=new J(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),o=r?.key?.key||"";return""!==o&&o===(i?.key?.key||"")}catch(dg){return this.logger.warn("verifyPetalAccount failed",{error:String(dg)}),!1}}}var Th=(e=>(e[e.COMMUNICATION=0]="COMMUNICATION",e[e.TRANSACTION=1]="TRANSACTION",e[e.STATE=2]="STATE",e))(Th||{}),Sh=(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))(Sh||{});class kh extends Error{constructor(e,t){super(e),this.code=t,this.name="FloraError"}}function Eh(e){const t=function(e){return`hcs-16:${e.floraAccountId}:${e.topicType}`}({floraAccountId:e.floraAccountId,topicType:e.topicType}),r=X({memo:t,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey});return e.autoRenewAccountId&&r.setAutoRenewAccountId(i.AccountId.fromString(e.autoRenewAccountId)),r}function Ah(e){const t=(new i.AccountCreateTransaction).setKey(e.keyList),r="number"==typeof e.initialBalanceHbar?e.initialBalanceHbar:1;t.setInitialBalance(new i.Hbar(r));const o="number"==typeof e.maxAutomaticTokenAssociations?e.maxAutomaticTokenAssociations:-1;return t.setMaxAutomaticTokenAssociations(o),t}function vh(e){const t={p:"hcs-16",op:e.op,operator_id:e.operatorId,...e.body||{}};return Z({topicId:e.topicId,message:JSON.stringify(t)})}function Ch(e){return vh({topicId:e.topicId,operatorId:e.operatorId,op:Sh.FLORA_CREATED,body:{flora_account_id:e.floraAccountId,topics:e.topics}})}function xh(e){return vh({topicId:e.topicId,operatorId:e.operatorId,op:Sh.TRANSACTION,body:{schedule_id:e.scheduleId,data:e.data,m:e.data}})}function Rh(e){return vh({topicId:e.topicId,operatorId:e.operatorId,op:Sh.STATE_UPDATE,body:{hash:e.hash,epoch:e.epoch,timestamp:(new Date).toISOString()}})}function Nh(e){return vh({topicId:e.topicId,operatorId:e.operatorId,op:Sh.FLORA_JOIN_REQUEST,body:{candidate_account_id:e.candidateAccountId}})}function _h(e){return vh({topicId:e.topicId,operatorId:e.operatorId,op:Sh.FLORA_JOIN_VOTE,body:{candidate_account_id:e.candidateAccountId,approve:e.approve}})}function Ph(e){return vh({topicId:e.topicId,operatorId:e.operatorId,op:Sh.FLORA_JOIN_ACCEPTED,body:{members:e.members,epoch:e.epoch}})}class Fh{constructor(e){this.network=e.network,this.logger=e.logger||new B({level:"info",module:"HCS-16"}),this.mirrorNode=new J(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 i.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 i.KeyList(t,1)}buildFloraTopicCreateTxs(e){return{communication:Eh({floraAccountId:e.floraAccountId,topicType:Th.COMMUNICATION,adminKey:e.keyList,submitKey:e.submitList,autoRenewAccountId:e.autoRenewAccountId}),transaction:Eh({floraAccountId:e.floraAccountId,topicType:Th.TRANSACTION,adminKey:e.keyList,submitKey:e.submitList,autoRenewAccountId:e.autoRenewAccountId}),state:Eh({floraAccountId:e.floraAccountId,topicType:Th.STATE,adminKey:e.keyList,submitKey:e.submitList,autoRenewAccountId:e.autoRenewAccountId})}}parseTopicMemo(e){const t=e.match(/^hcs-16:([0-9.]+):(\d)$/);return t?{protocol:"hcs-16",floraAccountId:t[1],topicType:Number(t[2])}:null}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",o=await this.mirrorNode.getTopicMessages(e,{limit:r,order:i}),n=[];for(const s of o){if("hcs-16"!==s.p)continue;const{consensus_timestamp:e,sequence_number:r,running_hash:i,running_hash_version:o,topic_id:a,payer:c,created:l,chunk_info:d,...u}=s,p=u.op,h=u.operator_id;if(t?.opFilter&&p!==t.opFilter)continue;if("string"!=typeof h)continue;const g=u;n.push({message:g,consensus_timestamp:e,sequence_number:Number(r),payer:c})}return n}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 Oh=r.z.object({p:r.z.literal("hcs-17"),op:r.z.literal("state_hash"),state_hash:r.z.string().min(1),topics:r.z.array(r.z.string()),account_id:r.z.string().min(1),timestamp:r.z.string().optional(),m:r.z.string().optional()});class zh extends Error{constructor(e,t){super(e),this.code=t,this.name="StateHashError"}}var Dh=(e=>(e[e.STATE=0]="STATE",e))(Dh||{});function Bh(e){return`hcs-17:0:${e}`}function Mh(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;return{type:r,ttl:i}}catch{return}}class Uh{constructor(e){this.network=e.network,this.logger=e.logger||new B({level:e.logLevel||"info",module:"HCS-17"}),this.mirrorNode=new J(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,timestamp:(new Date).toISOString(),m:e.memo}}validateMessage(e){const t=Oh.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 Bh(e)}async validateHCS17Topic(e){try{const t=Mh((await this.mirrorNode.getTopicInfo(e)).memo);return t?t.type!==Dh.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(dg){return{valid:!1,error:String(dg)}}}async getRecentMessages(e,t){const r=t?.limit??25,i=t?.order??"desc",o=await this.mirrorNode.getTopicMessages(e,{limit:r,order:i}),n=[];for(const s of o)try{if("hcs-17"!==s.p||"state_hash"!==s.op)continue;const e=s,{valid:t}=this.validateMessage(e);if(!t)continue;n.push({message:{p:"hcs-17",op:"state_hash",state_hash:e.state_hash,topics:e.topics,account_id:e.account_id,timestamp:e.timestamp,m:e.m},consensus_timestamp:e.consensus_timestamp,sequence_number:Number(e.sequence_number),payer:e.payer})}catch(ug){this.logger.debug(`Failed to parse HCS-17 message: ${ug}`)}return n}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:o}=t[0];return Object.assign({},r,{consensus_timestamp:i,sequence_number:o})}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 o=I.createHash("sha384");o.update(r);const n=o.digest("hex");return this.logger.debug("Account state hash calculated",{accountId:e.accountId,stateHash:n}),{stateHash:n,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 o=I.createHash("sha384");o.update(i);const n=o.digest("hex");return this.logger.debug("Composite state hash calculated",{compositeAccountId:e.compositeAccountId,stateHash:n}),{stateHash:n,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=I.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,o="accountId"in e?e.accountId:e.compositeAccountId;return this.logger.debug("State hash verification",{accountId:o,isValid:i,expected:t,calculated:r}),i}catch(r){return this.logger.error("Failed to verify state hash",r),!1}}}function Lh(e){return X({memo:Bh(e.ttl),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Kh(e){const t={p:"hcs-17",op:"state_hash",state_hash:e.stateHash,topics:e.topics,account_id:e.accountId,timestamp:(new Date).toISOString(),m:e.memo};return Z({topicId:e.topicId,message:JSON.stringify(t),transactionMemo:e.transactionMemo})}var $h=(e=>(e.ANNOUNCE="announce",e.PROPOSE="propose",e.RESPOND="respond",e.COMPLETE="complete",e.WITHDRAW="withdraw",e))($h||{});function Hh(e){return"object"==typeof e&&null!==e}function qh(e){return"string"==typeof e}function jh(e){return"number"==typeof e&&Number.isFinite(e)}function Wh(e){if(!Hh(e))return!1;if("hcs-18"!==e.p)return!1;if(!qh(e.op))return!1;const t=e.op;return!!["announce","propose","respond","complete","withdraw"].includes(t)&&"data"in e}var Vh=(e=>(e.IDLE="idle",e.ANNOUNCED="announced",e.PROPOSING="proposing",e.FORMING="forming",e.ACTIVE="active",e.WITHDRAWN="withdrawn",e))(Vh||{});class Gh extends Error{constructor(e,t){super(e),this.code=t,this.name="DiscoveryError"}}function Jh(e,t){return t&&t.trim().length>0?t:e&&e>0?`hcs-18:0:${e}`:"hcs-18:0"}function Yh(e){return X({memo:Jh(e.ttlSeconds,e.memoOverride),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}function Xh(e){const t="string"==typeof e.transactionMemo&&e.transactionMemo.length>0?e.transactionMemo:`hcs-18:op:${function(e){switch(e){case $h.ANNOUNCE:return 0;case $h.PROPOSE:return 1;case $h.RESPOND:return 2;case $h.COMPLETE:return 3;case $h.WITHDRAW:return 4;default:return 0}}(e.message.op)}`;return(new i.TopicMessageSubmitTransaction).setTopicId(e.topicId).setMessage(JSON.stringify(e.message)).setTransactionMemo(t)}function Zh(e){return{p:"hcs-18",op:$h.ANNOUNCE,data:e}}function Qh(e){return{p:"hcs-18",op:$h.PROPOSE,data:e}}function eg(e){return{p:"hcs-18",op:$h.RESPOND,data:e}}function tg(e){return{p:"hcs-18",op:$h.COMPLETE,data:e}}function rg(e){return{p:"hcs-18",op:$h.WITHDRAW,data:e}}class ig{constructor(e){this.network=e.network,this.logger=e.logger||B.getInstance({module:"HCS-18"}),this.mirrorNode=new J(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}}var og=(e=>(e.FIXED_FEE="FIXED_FEE",e.FRACTIONAL_FEE="FRACTIONAL_FEE",e.ROYALTY_FEE="ROYALTY_FEE",e))(og||{});class ng{constructor(e){this.customFees=[],this.logger=e.logger,this.mirrorNode=new J(e.network,e.logger),this.defaultCollectorAccountId=e.defaultCollectorAccountId||""}static forHbar(e,t,r,i,o=[]){return new ng({network:r,logger:i,defaultCollectorAccountId:t}).addHbarFee(e,t,o)}static async forToken(e,t,r,i,o,n=[],s){const a=new ng({network:i,logger:o,defaultCollectorAccountId:r});return await a.addTokenFee(e,t,r,s,n),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:og.FIXED_FEE}),this}async addTokenFee(e,t,r,i,o=[]){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 n=i;if(void 0===n)try{const e=await this.mirrorNode.getTokenInfo(t);e?.decimals?(n=parseInt(e.decimals,10),this.logger.info(`Fetched decimals for ${t}: ${n}`)):(this.logger.warn(`Could not fetch decimals for ${t}, defaulting to 0.`),n=0)}catch(s){this.logger.error(`Error fetching decimals for ${t}, defaulting to 0: ${s}`),n=0}return this.customFees.push({feeAmount:{amount:e*10**n,decimals:n},feeCollectorAccountId:r||this.defaultCollectorAccountId,feeTokenId:t,exemptAccounts:[...o],type:og.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 sg{constructor(){this.resolver=null,this.onUnavailableCallbacks=[],this.logger=B.getInstance({module:"ContentResolverRegistry"})}static getInstance(){return sg._instance||(sg._instance=new sg),sg._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 ag=sg.getInstance();class cg{constructor(){this.contentStore=null,this.logger=B.getInstance({module:"ContentStoreService"})}static getInstance(){return cg._instance||(cg._instance=new cg),cg._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 lg=cg.getInstance();exports.AIAgentCapability=Td,exports.AIAgentDetailsSchema=Cd,exports.AIAgentProfileSchema=Dd,exports.AIAgentType=wd,exports.AccountCreationError=iu,exports.ActionBuilder=class{constructor(e){this.cryptoAdapter=cd(),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(td())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(td())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(td())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 o=0;o<Math.min(r.length,256);o++)i=(i<<5)-i+r[o]&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),o=await this.generateInfoHash(r),n=this.registration.js_t_id,s=this.registration.js_hash,a=this.registration.interface_version;return this.reset().setTopicId(e).setHash(o).setWasmHash(i),n&&this.setJsTopicId(n),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=Ru,exports.AgentBuilder=su,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 B({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(),o=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 n={p:"hcs-12",op:"add-block",block_t_id:t,...Object.keys(i).length>0&&{actions:i},attributes:o};return this.operations.push(n),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=Fu,exports.AssemblyRegistry=_u,exports.BaseProfileSchema=Od,exports.BaseRegistry=du,exports.BlockBuilder=zu,exports.BlockLoader=Nu,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 Bu(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 Du(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={},o=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||{},o={...t.attributes,...o})}const n={};e.attributes&&Object.entries(e.attributes).forEach(([e,t])=>{t&&"object"==typeof t&&"default"in t&&(n[e]=t.default)});const s={...n};o&&"object"==typeof o&&Object.entries(o).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,o=e.dataset.params;this.logger.debug("Action button clicked",{actionTopicId:i,paramsStr:o,hasAction:!!i}),i&&await this.executeAction(t,i,o)})})}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(dg){this.logger.warn("Failed to parse action params",{paramsStr:r})}const o=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:o.attributes});const n=await this.wasmExecutor.execute(r,{method:"POST",params:i,state:o.attributes});if(this.logger.debug("WASM execution result",{result:n}),n.success&&n.data){const t=i.operation||"default";let r=n.data;r.success&&r.data&&(r=r.data);const s={...o,attributes:{...o.attributes,...r},actionResults:{...o.actionResults,[t]:r}};this.stateManager.updateBlockState(e,s),await this.updateBlockDisplay(e,s)}else this.logger.error("Action execution failed",{result:n})}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 Mu(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 o=await this.hashLinkScanner.scanTemplate(e);if(0===o.length)return e;this.logger.debug("Processing HashLinks",{parentBlockId:t.id,referenceCount:o.length});const n={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&&(n.actions=e.actions)}let s=e;for(let e=0;e<o.length;e++){const t=o[e];try{const e=await this.hashLinkResolver.resolveReference(t,n);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},o={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:n.depth,parentContext:n,initialState:o};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 o=this.stateListeners.get(e)||[];for(const s of o)try{s(i,r,e)}catch(n){this.logger.error("State change listener error",{blockId:e,error:n})}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 o={type:r,payload:i,fromBlock:e,toBlock:t},n=this.messageHandlers.get(t)||[];for(const a of n)try{a(o)}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 o=this.messageHandlers.get(i)||[],n={type:e,payload:t,fromBlock:"system",toBlock:i};for(const t of o)try{t(n)}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 o=this.getBlockState(e);let n;try{if(r.success&&i.onSuccess)n=i.onSuccess(o,r);else{if(r.success||!i.onError)return;n=i.onError(o,r)}n&&this.updateBlockState(e,n),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],o=i.type;if("string"===o&&"string"!=typeof r)throw new Error(`State validation failed: property '${e}' must be string`);if("number"===o&&"number"!=typeof r)throw new Error(`State validation failed: property '${e}' must be number`);if("number"===o&&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 o=this.messageHandlers.get(e)||[],n={type:t,payload:r,fromBlock:i,toBlock:e};for(const a of o)try{a(n)}catch(s){this.logger.error("Message handler error",{blockId:e,type:t,error:s})}}},exports.BrowserHCS20Client=class extends Xp{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 Pp({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 Pp({hwc:this.hwc,network:this.network}),o=await r.createRegistry({submitKey:e.toString(),adminKey:e.toString()});if(!o.success)throw new Error("Failed to create topic");i=o.topicId,this.logger.info(`Created private topic: ${i}`)}else i=this.publicTopicId;r?.({stage:"submitting-deploy",percentage:50,topicId:i});const o={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},n=this.validateMessage(o);if(!n.valid)throw new Gp("Invalid deploy message",n.errors);const s=await this.submitPayload(i,o,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,o=await this.submitPayload(i,r,!1),n=o.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,mintTxId:n}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,mintTxId:n}),{id:n,operation:"mint",tick:this.normalizeTick(e.tick),amount:e.amount,to:this.accountToString(e.to),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:n,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,o=await this.submitPayload(i,r,!1),n=o.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,transferTxId:n}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,transferTxId:n}),{id:n,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:n,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,o=await this.submitPayload(i,r,!1),n=o.transactionHash?.toString()||"";return t?.({stage:"confirming",percentage:80,burnTxId:n}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,burnTxId:n}),{id:n,operation:"burn",tick:this.normalizeTick(e.tick),amount:e.amount,from:this.accountToString(e.from),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:n,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 Gp("Invalid register message",i.errors);t?.({stage:"submitting",percentage:50});const o=await this.submitPayload(this.registryTopicId,r,!1),n=o.transactionHash?.toString()||"";t?.({stage:"confirming",percentage:80,registerTxId:n}),await new Promise(e=>setTimeout(e,2e3)),t?.({stage:"complete",percentage:100,registerTxId:n})}catch(r){throw t?.({stage:"complete",percentage:100,error:r instanceof Error?r.message:"Unknown error"}),new Jp(r instanceof Error?r.message:"Unknown error",this.topicToString(e.topicId))}}async submitPayload(e,t,r){let o;this.logger.debug(`Submitting payload to topic ${e}`),o="string"==typeof t?t:JSON.stringify(t);const n=(new i.TopicMessageSubmitTransaction).setTopicId(i.TopicId.fromString(e)).setMessage(o);r&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),n.setMaxTransactionFee(new i.Hbar(this.feeAmount)));const s=await this.hwc.executeTransactionWithErrorHandling(n,!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=Pp,exports.BrowserHCSClient=class extends eu{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=B.getInstance({level:t,module:"HCS-Browser",prettyPrint:e.prettyPrint,silent:e.silent}),cu)try{const{accountId:t,signer:r}=this.getAccountAndSigner();this.hcs11Client=new Ld({network:e.network,auth:{operatorId:t,signer:r},logLevel:e.logLevel,silent:e.silent})}catch(ug){this.logger.warn(`Failed to initialize HCS11Client: ${ug}`)}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,o){this.logger.info("Sending message");const n={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(n);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:o?.progressCallback,waitMaxAttempts:o?.waitMaxAttempts,waitIntervalMs:o?.waitIntervalMs});if(!La(i))throw new Error("Failed to inscribe large message content");n.data=`hcs://1/${La(i)}`,this.logger.info(`Large message inscribed with topic ID: ${La(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,n,i,s.requiresFee)}async getPublicKey(e){return await this.mirrorNode.getPublicKey(e)}async handleConnectionRequest(e,t,r,o="Connection accepted. Looking forward to collaborating!",n=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 i.KeyList([c,a],1),d=this._generateHcs10Memo(Qd.CONNECTION,{ttl:n,inboundTopicId:e,connectionId:r}),u=(new i.TopicCreateTransaction).setTopicMemo(d).setAutoRenewAccountId(i.AccountId.fromString(s)).setAdminKey(l).setSubmitKey(l);this.logger.debug("Executing topic creation transaction");const p=await this.hwc.executeTransactionWithErrorHandling(u,!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,r,m,o),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:r,confirmedRequestId:f,connectionTopicId:g,operatorId:w,memo:`Connection established with ${t}`}),{connectionTopicId:g,confirmedConnectionSequenceNumber:f,operatorId:m}}async confirmConnection(e,t,r,i,o,n){this.logger.info("Confirming connection");const s={p:"hcs-10",op:"connection_created",connection_topic_id:t,connected_account_id:r,operator_id:o,connection_id:i,m:n},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 hs({module:"ProfileCreate",logger:this.logger,callback:r});try{const r=e instanceof su;let o;if(o=t?.existingState?t.existingState:{currentStage:"init",completedPercentage:0,createdResources:[]},r){this.logger.info("Creating Agent Profile and HCS-10 Topics");const t=e.build();o.agentMetadata=t.metadata}else this.logger.info("Creating Person HCS-11 Profile");i.preparing(`Starting ${r?"agent":"person"} resource creation`,0,{state:o});const{inboundTopicId:n,outboundTopicId:s,state:a}=await this.createCommunicationTopics(t,i);let c,l,d;if(o=a,e.setInboundTopicId(n),e.setOutboundTopicId(s),r){const t=e.build();c=t.existingPfpTopicId||o.pfpTopicId,l=t.pfpBuffer,d=t.pfpFileName||"pfp.png"}else{const t=e.build();c=o.pfpTopicId,l=t.pfpBuffer,d=t.pfpFileName}!c&&l&&d?c=await this.handleProfilePictureCreation(l,d,o,i):c&&(i.preparing(`Using existing profile picture: ${c}`,50,{state:o}),o.pfpTopicId=c),await this.createAndInscribeProfile(r,e,c,o,n,s,t,i),o.currentStage="complete",o.completedPercentage=100,i.completed((r?"Agent":"Person")+" profile created successfully",{profileTopicId:o.profileTopicId,inboundTopicId:n,outboundTopicId:s,pfpTopicId:c,state:o});let u="";o.outboundTopicId&&(u=o.outboundTopicId);let p="";o.inboundTopicId&&(p=o.inboundTopicId);let h="";o.pfpTopicId&&(h=o.pfpTopicId);let g="";return o.profileTopicId&&(g=o.profileTopicId),{outboundTopicId:u,inboundTopicId:p,pfpTopicId:h,profileTopicId:g,success:!0,state:o}}catch(o){return i.failed("Error during profile creation",{error:o.message}),{outboundTopicId:"",inboundTopicId:"",pfpTopicId:"",profileTopicId:"",success:!1,error:o.message,state:{currentStage:"init",completedPercentage:0,error:o.message}}}}async handleProfilePictureCreation(e,t,r,i){r.currentStage="pfp",i.preparing("Creating profile picture",30,{state:r});const o=i.createSubProgress({minPercent:30,maxPercent:50,logPrefix:"PFP"}),n=await this.inscribePfp(e,t,{progressCallback:e=>o.report({...e,progressPercent:e.progressPercent??0,details:{...e.details,state:r}})});if(!n.success){let e="Failed to inscribe profile picture";throw n.error&&(e=n.error),new Error(e)}const s=n.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,o,n,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:o,outboundTopicId:n,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:o,outboundTopicId:n})}const d=await this.hcs11Client.createAndInscribeProfile(l,s?.updateAccountMemo??!0,{progressCallback:e=>c?.report({...e,progressPercent:e.progressPercent??0})});if(!d.success){a&&a.failed(`Failed to inscribe ${e?"agent":"person"} profile`,{error:d.error});let t=`Failed to inscribe ${e?"agent":"person"} profile`;throw d.error&&(t=d.error),new Error(t)}i.profileTopicId=d.profileTopicId,i.createdResources&&i.createdResources.push(`profile:${d.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,r){try{let o;if(this.logger.info("Registering agent with guarded registry"),r?.existingState?.inboundTopicId)this.logger.info("Using inboundTopicId from existing state"),o=r.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}}}o=t.topicInfo.inboundTopic}const n=this.initializeRegistrationState(o,r?.existingState),s=new hs({module:"AgentRegistration",logger:this.logger,callback:r?.progressCallback});s.preparing("Preparing agent registration",10,{inboundTopicId:o,accountId:e});const a=await this.executeRegistration(e,t,this.guardedRegistryBaseUrl,this.logger);if(!a.success)return{...a,state:n};if(s.submitting("Submitting registration to registry",30,{transactionId:a.transactionId}),a.transaction){const e=i.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:n};this.logger.info("Successfully processed registration transaction")}s.confirming("Confirming registration transaction",60,{accountId:e,inboundTopicId:o,transactionId:a.transactionId});const c=r?.maxAttempts??60,l=r?.delayMs??2e3,d=await this.waitForRegistrationConfirmation(a.transactionId,t,this.guardedRegistryBaseUrl,c,l,this.logger);return this.updateStateForCompletedRegistration(n,o),s.completed("Agent registration complete",{transactionId:a.transactionId,inboundTopicId:o,state:n,confirmed:d}),{...a,confirmed:d,state:n}}catch(o){return this.logger.error(`Registration error: ${o.message}`),{error:`Error during registration: ${o.message}`,success:!1,state:{currentStage:"registration",completedPercentage:0,error:o.message}}}}async createAndRegisterAgent(e,t){try{const r=e.build(),i=t?.progressCallback,o=new hs({module:"AgentCreateRegister",logger:this.logger,callback:i});let n=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};if(n.agentMetadata=r.metadata,o.preparing("Starting agent creation process",0,{state:n}),"complete"!==n.currentStage||!n.inboundTopicId||!n.outboundTopicId||!n.profileTopicId){const t=await this.create(e,{progressCallback:e=>{const t=.3*(e.progressPercent||0);o.report({...e,progressPercent:t,details:{...e.details,state:e.details?.state||n}})},existingState:n,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");n=t.state,n.agentMetadata=r.metadata,this.logger.info("Waiting for account memo update to propagate..."),await new Promise(e=>setTimeout(e,5e3))}o.preparing(`Agent creation status: ${n.currentStage}, ${n.completedPercentage}%`,30,{state:n});const{accountId:s}=this.getAccountAndSigner();if("complete"!==n.currentStage||!n.createdResources?.includes(`registration:${n.inboundTopicId}`)){t?.baseUrl&&(this.guardedRegistryBaseUrl=t.baseUrl);const e=await this.registerAgentWithGuardedRegistry(s,r.network,{progressCallback:e=>{const t=30+.7*(e.progressPercent||0);o.report({...e,progressPercent:t,details:{...e.details,state:e.details?.state||n}})},maxAttempts:t?.maxAttempts,delayMs:t?.delayMs,existingState:n});if(!e.success)throw new Error(e.error||"Failed to register agent with registry");n=e.state}return o.completed("Agent creation and registration complete",{state:n}),{success:!0,state:n,metadata:{accountId:s,operatorId:`${n.inboundTopicId}@${s}`,inboundTopicId:n.inboundTopicId,outboundTopicId:n.outboundTopicId,profileTopicId:n.profileTopicId,pfpTopicId:n.pfpTopicId,privateKey:null,...n.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,o=[],n={},s,a,c,l){try{const d=l?.progressCallback,u=new hs({module:"StoreHCS11Profile",logger:this.logger,callback:d});u.preparing("Preparing agent profile data",0);let p=c;if(!p&&s&&a){const e=u.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:u.failed("Failed to inscribe profile picture, continuing without PFP")}else c?u.preparing(`Using existing profile picture: ${c}`,30):u.preparing("No profile picture provided",30);if(!this.hcs11Client)return u.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:n.type||"autonomous"});u.preparing("Building agent profile",65);const g=n.socials?Object.entries(n.socials).filter(([e,t])=>t).map(([e,t])=>({platform:e,handle:t})):void 0,m=this.hcs11Client.createAIAgentProfile(e,h,o,n.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:p?`hcs://1/${p}`:void 0,socials:g,properties:{version:n.version||"1.0.0",creator:n.creator||"Unknown",supported_languages:n.supported_languages||["en"],permissions:n.permissions||[],model_details:n.model_details,training:n.training,capabilities_description:n.capabilities_description,...n},inboundTopicId:r,outboundTopicId:i,creator:n.creator}),f=u.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?(u.completed("Profile stored successfully",{profileTopicId:y.profileTopicId}),{profileTopicId:y.profileTopicId,pfpTopicId:p,success:!0,transactionId:y.transactionId||""}):(u.failed("Failed to inscribe profile"),{profileTopicId:"",success:!1,error:y.error||"Failed to inscribe profile",transactionId:y.transactionId||""})}catch(d){return this.logger.error(`Error storing HCS11 profile: ${d.message}`),{profileTopicId:"",success:!1,error:d.message,transactionId:""}}}async createTopic(e,t,r){this.logger.info("Creating topic");const{accountId:o,signer:n}=this.getAccountAndSigner(),s=(new i.TopicCreateTransaction).setTopicMemo(e),a=await this.mirrorNode.getPublicKey(o);t&&a&&(s.setAdminKey(a),s.setAutoRenewAccountId(o)),r&&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 d=c.result;return d?.topicId?{success:!0,topicId:d.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,r,o){let n;this.logger.debug(`Submitting payload to topic ${e}`),n="string"==typeof t?t:JSON.stringify(t);const s=(new i.TopicMessageSubmitTransaction).setTopicId(e).setMessage(n),a=this.getHcs10TransactionMemo(t);let c;if(a&&s.setTransactionMemo(a),o&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),s.setMaxTransactionFee(new i.Hbar(this.feeAmount))),r){const{signer:e}=this.getAccountAndSigner();s.freezeWithSigner(e);const t=await s.sign(r);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:o}=this.getAccountAndSigner(),n=E.lookup(t)||"application/octet-stream",s=await ps.createWithAuth({type:"client",accountId:i,signer:o,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 za({type:"buffer",buffer:e,fileName:t,mimeType:n},o,{...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,o=new hs({module:"PFP-Inscription",logger:this.logger,callback:i});if(!this.hcs11Client)return o.failed("HCS11Client is not available in this environment"),{pfpTopicId:"",success:!1,error:"HCS11Client is not available in this environment",transactionId:""};o.preparing("Preparing to inscribe profile picture",10),this.logger.info("Inscribing profile picture using HCS-11 client");const n=e=>{o.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:n});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 o.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 o=this._generateHcs10Memo(Qd.OUTBOUND,{ttl:e?.ttl,accountId:i}),n=await this.createTopic(o,!0,!0);if(!n.success||!n.topicId)throw new Error(n.error||"Failed to create outbound topic");r.outboundTopicId=n.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 o=this._generateHcs10Memo(Qd.INBOUND,{ttl:e?.ttl,accountId:i}),n=await this.createTopic(o,!0,!1);if(!n.success||!n.topicId)throw new Error(n.error||"Failed to create inbound topic");r.inboundTopicId=n.topicId,r.createdResources&&r.createdResources.push(`inbound:${r.inboundTopicId}`)}return{inboundTopicId:r.inboundTopicId,outboundTopicId:r.outboundTopicId,state:r}}},exports.CanonicalAgentDataSchema=$u,exports.ConnectionConfirmationError=nu,exports.ConnectionsManager=class{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=B.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,o]=await Promise.all([this.baseClient.getMessages(t?.outboundTopic),this.baseClient.getMessages(t?.inboundTopic)]);this.processOutboundMessages(i.messages||[],e),this.processInboundMessages(o.messages||[]);const n=Array.from(this.connections.values()).filter(e=>"pending"===e.status||e.isPending).length;return this.logger.debug(`Processed ${i.messages?.length||0} outbound and ${o.messages?.length||0} inbound messages. Found ${n} 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,o]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 o){const i=e.connectionRequestId;if(!i)continue;const o=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(o?.connection_topic_id){r=!0;const t=o.connection_topic_id;let n=e.uniqueRequestKey;const s={connectionTopicId:t,targetAccountId:e.targetAccountId,targetAgentName:e.targetAgentName,targetInboundTopicId:e.targetInboundTopicId,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(o.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),n&&this.connections.delete(n),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 o of r){if(this.logger.debug(`Processing pending connection: ${o.connectionTopicId}`),!o.targetAccountId){this.logger.debug(`Skipping connection ${o.connectionTopicId} - no targetAccountId`);continue}let e=o.targetInboundTopicId;if(!e)try{const t=await this.baseClient.retrieveProfile(o.targetAccountId);if(!t?.profile?.inboundTopicId){this.logger.debug(`Couldn't get inbound topic ID for account ${o.targetAccountId}`);continue}e=t.profile.inboundTopicId,this.connections.set(o.connectionTopicId,{...o,targetInboundTopicId:e}),this.logger.debug(`Updated connection ${o.connectionTopicId} with inbound topic ID: ${e}`)}catch(i){this.logger.debug(`Error fetching profile for ${o.targetAccountId}: ${i}`);continue}if(!e||e.includes(":")){this.logger.debug(`Skipping invalid inbound topic format: ${e}`);continue}const t=o.connectionRequestId||o.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 ${o.targetAccountId} on their inbound topic`);const r={connectionTopicId:e,targetAccountId:o.targetAccountId,targetAgentName:o.targetAgentName,targetInboundTopicId:o.targetInboundTopicId,targetOutboundTopicId:o.targetOutboundTopicId,status:"established",isPending:!1,needsConfirmation:!1,created:new Date(i.created||o.created),lastActivity:new Date(i.created||o.created),profileInfo:o.profileInfo,connectionRequestId:o.connectionRequestId,confirmedRequestId:o.confirmedRequestId,requesterOutboundTopicId:o.requesterOutboundTopicId,inboundRequestId:o.inboundRequestId,closedReason:o.closedReason,closeMethod:o.closeMethod,uniqueRequestKey:o.uniqueRequestKey,originTopicId:o.originTopicId,processed:o.processed,memo:o.memo};this.connections.set(e,r),o.connectionTopicId&&this.connections.delete(o.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 ${o.targetAccountId}: ${i}`)}else this.logger.debug(`Skipping connection ${o.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 n of r){const e=n.connection_request_id,r=n.operator_id||"",i=this.baseClient.extractAccountFromOperatorId(r),o=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:n.outbound_topic_id||"",targetAccountId:i,targetTopicId:o,operatorId:r,sequenceNumber:n.sequence_number,created:n.created||new Date,memo:n.m,status:"pending"};if(this.pendingRequests.set(a,s),!this.connections.has(a)){const t={connectionTopicId:a,targetAccountId:i,targetInboundTopicId:o,status:"pending",isPending:!0,needsConfirmation:!1,created:n.created||new Date,connectionRequestId:e,uniqueRequestKey:a,originTopicId:n.outbound_topic_id||"",processed:!1,memo:n.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 n of i){const e=n.connection_request_id,t=n.connection_topic_id,r=this.baseClient.extractAccountFromOperatorId(n.operator_id||"");if(this.shouldFilterAccount(r)){this.logger.debug(`Filtering out outbound confirmation to account: ${r}`);continue}const i=`req-${e}:${n.operator_id}`,o=this.pendingRequests.get(i);if(o&&(o.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:n.confirmed_request_id,requesterOutboundTopicId:n.outbound_topic_id,uniqueRequestKey:i,originTopicId:n.outbound_topic_id||"",processed:!1,memo:n.m})}else this.connections.set(t,{connectionTopicId:t,targetAccountId:r,status:"established",isPending:!1,needsConfirmation:!1,created:n.created||new Date,connectionRequestId:e,confirmedRequestId:n.confirmed_request_id,requesterOutboundTopicId:n.outbound_topic_id,uniqueRequestKey:i,originTopicId:n.outbound_topic_id||"",processed:!1,memo:n.m})}const o=e.filter(e=>"connection_closed"===e.op||"close_connection"===e.op&&e.connection_topic_id);for(const n of o){const e=n.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=n.connection_request_id&&n.operator_id?`req-${n.connection_request_id}:${n.operator_id}`:void 0;this.connections.set(e,{...t,status:"closed",isPending:!1,needsConfirmation:!1,lastActivity:n.created||new Date,closedReason:n.reason,closeMethod:n.close_method,uniqueRequestKey:r,originTopicId:t.originTopicId,processed:!1,memo:n.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||"",o=this.baseClient.extractAccountFromOperatorId(t),n=this.baseClient.extractTopicFromOperatorId(t);if(this.shouldFilterAccount(o)){this.logger.debug(`Filtering out request from account: ${o}`);continue}const s=`inb-${e}:${t}`;r.some(t=>t.connection_id===e)?this.logger.debug(`Skipping request from ${o} as it has already been confirmed`):this.connections.has(s)||this.connections.set(s,{connectionTopicId:s,targetAccountId:o,targetInboundTopicId:n,status:"needs_confirmation",isPending:!1,needsConfirmation:!0,created:i.created||new Date,inboundRequestId:e,uniqueRequestKey:s,originTopicId:n,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||"",o=i.operator_id||"";if(this.shouldFilterAccount(r)){this.logger.debug(`Filtering out confirmation for account: ${r}`);continue}const n=`inb-${e}:${o}`;if(this.connections.has(n)&&this.connections.delete(n),this.connections.has(t)){const r=this.connections.get(t);this.connections.set(t,{...r,status:"established",isPending:!1,needsConfirmation:!1,inboundRequestId:e,uniqueRequestKey:n,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:n,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,o]of this.connections.entries())o.originTopicId===e&&o.inboundRequestId===t&&(this.connections.set(i,{...o,processed:!0}),r=!0,this.logger.debug(`Marked inbound connection request #${t} on topic ${e} as processed`)),o.originTopicId===e&&o.connectionRequestId===t&&(this.connections.set(i,{...o,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),o=[];for(const e of i)try{const t=await this.baseClient.mirrorNode.getScheduledTransactionStatus(e.schedule_id);t.executed||t.deleted||o.push(e)}catch(r){this.logger.error(`Error checking transaction status: ${r}`),o.push(e)}return o}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}`)}}},exports.ContentResolverRegistry=ag,exports.ContentResolverRegistryImpl=sg,exports.ContentStoreService=lg,exports.CustomFeeType=og,exports.DiscoveryError=Gh,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=$h,exports.DiscoveryState=Vh,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 tc,this.logger=B.getInstance({module:"EVMBridge"})}async executeCommands(e,t={}){let r={...t};const o={};for(const s of e){const e=`${s.c.contractAddress}-${s.c.abi.name}`,t=await this.cache.get(e);if(t)o[s.c.abi.name]=JSON.parse(t),Object.assign(r,o[s.c.abi.name]);else try{const t=new c.ethers.Interface([{...s.c.abi}]),n=t.encodeFunctionData(s.c.abi.name),a=i.ContractId.fromSolidityAddress(s.c.contractAddress),l=await this.readFromMirrorNode(n,i.AccountId.fromString("0.0.800"),a);if(this.logger.info(`Result for ${s.c.contractAddress}:`,l?.result),!l?.result){this.logger.warn(`Failed to get result from mirror node for ${s.c.contractAddress}`),o[s.c.abi.name]="0",Object.assign(r,o[s.c.abi.name]);continue}const d=t?.decodeFunctionResult(s.c.abi.name,l.result);let u={values:[]};d&&s.c.abi.outputs?.forEach((e,t)=>{const r=rc(d[t],e.type);u.values.push(r),e.name&&(u[e.name]=r)}),await this.cache.set(e,JSON.stringify(u)),o[s.c.abi.name]=u,r[s.c.abi.name]=u}catch(n){this.logger.error(`Error executing command for ${s.c.contractAddress}:`,n),o[s.c.abi.name]="0",Object.assign(r,o[s.c.abi.name])}}return{results:o,stateData:r}}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(),o=t.toSolidityAddress(),n=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:o.startsWith("0x")?o:`0x${o}`,to:i?.startsWith("0x")?i:`0x${i}`,value:0})});if(!n.ok)throw new Error(`HTTP error! status: ${n.status}`);return await n.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=Id,exports.FallbackCryptoAdapter=ad,exports.FallbackHashAdapter=Ql,exports.FallbackHmacAdapter=od,exports.FeeConfigBuilder=ng,exports.FloraBuilder=class{constructor(){this.config={version:"1.0",type:3},this.logger=B.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}},exports.FloraError=kh,exports.FloraOperation=Sh,exports.FloraTopicType=Th,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[o,n]of Object.entries(r))n.type?(i.includes(n.type)||t.errors.push({code:"INVALID_ATTRIBUTE_TYPE",message:`Attribute '${o}' has invalid type '${n.type}'`,field:`attributes.${o}.type`,severity:"high"}),n.enum&&n.default&&!n.enum.includes(n.default)&&t.warnings.push({code:"DEFAULT_NOT_IN_ENUM",message:`Attribute '${o}' default value not in enum`,field:`attributes.${o}.default`,impact:"functionality"})):t.errors.push({code:"MISSING_ATTRIBUTE_TYPE",message:`Attribute '${o}' must specify a type`,field:`attributes.${o}.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=U,exports.HCS10BaseClient=eu,exports.HCS10Cache=tu,exports.HCS10Client=au,exports.HCS11Client=Ld,exports.HCS11ProfileSchema=Ud,exports.HCS12BaseClient=Ou,exports.HCS12BrowserClient=class extends Ou{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 Ru(this.network,this.logger,this.actionRegistryTopicId,this),this._blockLoader=new Nu(this.network,this.logger,this),this._assemblyRegistry=new _u(this.network,this.logger,this._assemblyRegistryTopicId,this),this._hashLinksRegistry=new Pu(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,r){const{accountId:o,signer:n}=await this.getAccountAndSigner(),s={[lu.ACTION]:"hcs-12:1:60:0",[lu.ASSEMBLY]:"hcs-12:1:60:2",[lu.HASHLINKS]:"hcs-12:1:60:3"}[e];this.logger.info("Creating registry topic via wallet",{registryType:lu[e],memo:s,accountId:o});const a=(new i.TopicCreateTransaction).setTopicMemo(s).setTransactionId(i.TransactionId.generate(o));if(t)if("boolean"==typeof t&&t){const e=await n.getAccountKey();a.setAdminKey(e),a.setAutoRenewAccountId(i.AccountId.fromString(o))}else(t instanceof i.PublicKey||t instanceof i.KeyList)&&(a.setAdminKey(t),a.setAutoRenewAccountId(i.AccountId.fromString(o)));if(r)if("boolean"==typeof r&&r){const e=await n.getAccountKey();a.setSubmitKey(e)}else(r instanceof i.PublicKey||r instanceof i.KeyList)&&a.setSubmitKey(r);const c=await a.freezeWithSigner(n),l=await c.executeWithSigner(n),d=await l.getReceiptWithSigner(n);if(!d.topicId)throw new Error("Failed to create topic: topicId is null");const u=d.topicId.toString();switch(this.logger.info("Registry topic created via wallet",{topicId:u,registryType:lu[e]}),e){case lu.ACTION:this.actionRegistryTopicId=u;break;case lu.ASSEMBLY:this._assemblyRegistryTopicId=u;case lu.HASHLINKS:}return u}async createAssemblyTopic(){this.logger.info("Creating new assembly topic");return await this.createRegistryTopic(lu.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,r){const{accountId:o,signer:n}=await this.getAccountAndSigner();this.logger.debug("Submitting message to topic via wallet",{topicId:e,messageLength:t.length,accountId:o});const s=(new i.TopicMessageSubmitTransaction).setTopicId(i.TopicId.fromString(e)).setMessage(t).setTransactionId(i.TransactionId.generate(o));r&&this.logger.warn("Submit key parameter ignored in browser client - using wallet signer");const a=await s.freezeWithSigner(n),c=await a.executeWithSigner(n),l=await c.getReceiptWithSigner(n);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:o}=await this.getAccountAndSigner();this.logger.info("Inscribing file via HCS-1 (browser)",{fileName:t});const n=E.lookup(t)||"application/octet-stream",s=await ps.createWithAuth({type:"client",accountId:i,signer:o,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 za({type:"buffer",buffer:e,fileName:t,mimeType:n},o,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 o of i)switch(o.op){case"add-block":await this.addBlockToAssembly(r,o);break;case"add-action":await this.addActionToAssembly(r,o);break;case"update":await this.updateAssembly(r,o)}return this.logger.info("Assembly created (browser)",{topicId:r,name:t.name,version:t.version,operations:i.length}),r}},exports.HCS12Client=class extends Ou{constructor(e){super(e),this.operatorAccountId=e.operatorId,this.operatorCtx=ne({network:this.network,operatorId:this.operatorAccountId,operatorKey:e.operatorPrivateKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:"mainnet"===e.network?i.Client.forMainnet():i.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 Ru(this.network,this.logger,this.actionRegistryTopicId,this),this._blockLoader=new Nu(this.network,this.logger,this),this._assemblyRegistry=new _u(this.network,this.logger,this._assemblyRegistryTopicId,this),this._hashLinksRegistry=new Pu(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={[lu.ACTION]:"hcs-12:1:60:0",[lu.ASSEMBLY]:"hcs-12:1:60:2",[lu.HASHLINKS]:"hcs-12:1:60:3"}[e];this.logger.info("Creating registry topic",{registryType:lu[e],memo:i});const o=X({memo:i,adminKey:t,submitKey:r,operatorPublicKey:this.client.operatorPublicKey||void 0}),n=await o.execute(this.client),s=await n.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:lu[e]}),e){case lu.ACTION:this.actionRegistryTopicId=a;break;case lu.ASSEMBLY:this._assemblyRegistryTopicId=a;case lu.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=Z({topicId:e,message:t});let o;if(r){const e=i.freezeWith(this.client),t=await e.sign(r);o=await t.execute(this.client)}else o=await i.execute(this.client);const n=await o.getReceipt(this.client);return this.logger.info("Message submitted successfully",{topicId:e,transactionId:o.transactionId.toString(),sequenceNumber:n.topicSequenceNumber?.toString()}),{transactionId:o.transactionId.toString(),sequenceNumber:n.topicSequenceNumber?Number(n.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=E.lookup(t)||"application/octet-stream",o=await ps.createWithAuth({type:"server",accountId:this.operatorAccountId,privateKey:this.operatorCtx.operatorKey.toString(),network:this.network}),n={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},n,o);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 o of i)switch(o.op){case"add-block":await this.addBlockToAssembly(r,o);break;case"add-action":await this.addActionToAssembly(r,o);break;case"update":await this.updateAssembly(r,o)}return this.logger.info("Assembly created",{topicId:r,name:t.name,version:t.version,operations:i.length}),r}},exports.HCS14Client=gp,exports.HCS14_PROTOCOL_REGEX=Ku,exports.HCS15BaseClient=Ih,exports.HCS15BrowserClient=class extends Ih{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 DAppSigner");return this.signer}async createBaseAccount(e){const t=this.requireSigner(),r=i.PrivateKey.generateECDSA(),o=r.publicKey,n=bh({publicKey:o,initialBalance:new i.Hbar(e?.initialBalance??10),maxAutomaticTokenAssociations:e?.maxAutomaticTokenAssociations,accountMemo:e?.accountMemo}),s=await n.freezeWithSigner(t),a=await s.executeWithSigner(t),c=await a.getReceiptWithSigner(t),l=c?.accountId?.toString?.(),d=`0x${o.toEvmAddress()}`;return this.logger.info("Created HCS-15 base account (browser)",{accountId:l,evmAddress:d}),{accountId:l,privateKey:r,privateKeyHex:r.toStringRaw(),publicKey:o,evmAddress:d}}async createPetalAccount(e){const t=this.requireSigner(),r=wh({publicKey:("string"==typeof e.basePrivateKey?i.PrivateKey.fromStringECDSA(e.basePrivateKey):e.basePrivateKey).publicKey,initialBalance:new i.Hbar(e.initialBalance??1),maxAutomaticTokenAssociations:e.maxAutomaticTokenAssociations,accountMemo:e.accountMemo}),o=await r.freezeWithSigner(t),n=await o.executeWithSigner(t),s=await n.getReceiptWithSigner(t),a=s?.accountId?.toString?.();return this.logger.info("Created HCS-15 petal account (browser)",{accountId:a}),{accountId:a}}},exports.HCS15Client=class extends Ih{constructor(e){super(e),this.operatorId=i.AccountId.fromString(e.operatorId),this.operatorCtx=ne({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:"mainnet"===this.network?i.Client.forMainnet():i.Client.forTestnet()}),this.client=this.operatorCtx.client}getKeyType(){return this.operatorCtx.keyType}async close(){try{this.client.close()}catch{}}async createBaseAccount(e){const t=i.PrivateKey.generateECDSA(),r=t.publicKey,o=bh({publicKey:r,initialBalance:new i.Hbar(e?.initialBalance??10),maxAutomaticTokenAssociations:e?.maxAutomaticTokenAssociations,accountMemo:e?.accountMemo}),n=await o.execute(this.client),s=await n.getReceipt(this.client);if(!s.accountId)throw new Error("HCS-15 BASE_ACCOUNT_CREATE_FAILED");const a=s.accountId.toString(),c=`0x${r.toEvmAddress()}`;return this.logger.info("Created HCS-15 base account",{accountId:a,evmAddress:c}),{accountId:a,privateKey:t,privateKeyHex:t.toStringRaw(),publicKey:r,evmAddress:c,receipt:s}}async createPetalAccount(e){const t=wh({publicKey:("string"==typeof e.basePrivateKey?i.PrivateKey.fromStringECDSA(e.basePrivateKey):e.basePrivateKey).publicKey,initialBalance:new i.Hbar(e.initialBalance??1),maxAutomaticTokenAssociations:e.maxAutomaticTokenAssociations,accountMemo:e.accountMemo}),r=await t.execute(this.client),o=await r.getReceipt(this.client);if(!o.accountId)throw new Error("HCS-15 PETAL_ACCOUNT_CREATE_FAILED");const n=o.accountId.toString();return this.logger.info("Created HCS-15 petal account",{accountId:n}),{accountId:n,receipt:o}}},exports.HCS16BaseClient=Fh,exports.HCS16BrowserClient=class extends Fh{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=Eh({floraAccountId:e.floraAccountId,topicType:e.topicType,adminKey:e.adminKey,submitKey:e.submitKey,autoRenewAccountId:e.autoRenewAccountId}),i=await r.freezeWithSigner(t),o=await i.executeWithSigner(t),n=await o.getReceiptWithSigner(t);return n?.topicId?.toString?.()||""}async sendFloraCreated(e){const t=this.getSigner(),r=Ch(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendTransaction(e){const t=this.getSigner(),r=xh(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async signSchedule(e){const t=this.getSigner(),r=await(new i.ScheduleSignTransaction).setScheduleId(e.scheduleId).freezeWithSigner(t);await r.executeWithSigner(t)}async sendStateUpdate(e){const t=this.getSigner(),r=Rh(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),o=Ah({keyList:r,initialBalanceHbar:"number"==typeof e.initialBalanceHbar?e.initialBalanceHbar:5,maxAutomaticTokenAssociations:-1}),n=await o.freezeWithSigner(t),s=await n.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:d,state:u}=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 d.freezeWithSigner(t)).executeWithSigner(t)).getReceiptWithSigner(t),g=await(await(await u.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=Ch({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=Nh(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendFloraJoinVote(e){const t=this.getSigner(),r=_h(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}async sendFloraJoinAccepted(e){const t=this.getSigner(),r=Ph(e),i=await r.freezeWithSigner(t);await i.executeWithSigner(t)}},exports.HCS16Client=class extends Fh{constructor(e){super({network:e.network,logger:e.logger}),this.operatorId=i.AccountId.fromString(e.operatorId);const t=new J(e.network,this.logger);this.operatorCtx=ne({network:e.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:t,logger:this.logger,client:"mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet()}),this.client=this.operatorCtx.client}async createFloraTopic(e){const t=Eh({floraAccountId:e.floraAccountId,topicType:e.topicType,adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:this.client.operatorPublicKey||void 0,autoRenewAccountId:e.autoRenewAccountId}),r=await t.execute(this.client),i=await r.getReceipt(this.client);if(!i.topicId)throw new Error("Failed to create Flora topic");return i.topicId.toString()}async sendFloraCreated(e){const t=Ch(e);return(await t.execute(this.client)).getReceipt(this.client)}async sendTransaction(e){const t=xh(e);return(await t.execute(this.client)).getReceipt(this.client)}async signSchedule(e){const t=await(new i.ScheduleSignTransaction).setScheduleId(e.scheduleId).freezeWith(this.client),r=await t.sign(e.signerKey);return(await r.execute(this.client)).getReceipt(this.client)}async sendStateUpdate(e){const t=Rh(e);return(await t.execute(this.client)).getReceipt(this.client)}async assembleKeyList(e){return super.assembleKeyList(e)}async createFloraAccountWithTopics(e){const t=await this.assembleKeyList({members:e.members,threshold:e.threshold}),r=await this.assembleSubmitKeyList(e.members),i=Ah({keyList:t,initialBalanceHbar:"number"==typeof e.initialBalanceHbar?e.initialBalanceHbar:5,maxAutomaticTokenAssociations:-1}),o=await i.execute(this.client),n=await o.getReceipt(this.client);if(!n.accountId)throw new Error("Failed to create Flora account");const s=n.accountId.toString(),{communication:a,transaction:c,state:l}=this.buildFloraTopicCreateTxs({floraAccountId:s,keyList:t,submitList:r,autoRenewAccountId:e.autoRenewAccountId}),d=await a.execute(this.client).then(e=>e.getReceipt(this.client)),u=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:d.topicId.toString(),transaction:u.topicId.toString(),state:p.topicId.toString()}}}async publishFloraCreated(e){const t=Ch({topicId:e.communicationTopicId,operatorId:e.operatorId,floraAccountId:e.floraAccountId,topics:e.topics});return(await t.execute(this.client)).getReceipt(this.client)}},exports.HCS17BaseClient=Uh,exports.HCS17BrowserClient=class extends Uh{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=Lh({ttl:e?.ttl??86400}),i=await r.freezeWithSigner(t),o=await i.executeWithSigner(t),n=await o.getReceiptWithSigner(t),s=n?.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 o=this.getSigner(),n=Kh({topicId:e,stateHash:t.state_hash,accountId:t.account_id,topics:t.topics,memo:t.m}),s=await n.freezeWithSigner(o),a=await s.executeWithSigner(o);return await a.getReceiptWithSigner(o),{}}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},o=this.calculateAccountStateHash(i),n=Kh({topicId:e.publishTopicId,stateHash:o.stateHash,accountId:e.accountId,topics:e.topics,memo:e.memo}),s=await n.freezeWithSigner(t);return await s.executeWithSigner(t),{stateHash:o.stateHash}}},exports.HCS17Client=class extends Uh{constructor(e){super(e),this.operatorId=i.AccountId.fromString(e.operatorId),this.operatorCtx=ne({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:"mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet()}),this.client=this.operatorCtx.client}getKeyType(){return this.operatorCtx.keyType}async createStateTopic(e){const t=Lh({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 o=i.topicId.toString();return this.logger.info(`Created HCS-17 state topic ${o}`),o}async submitMessage(e,t){const{valid:r,errors:i}=this.validateMessage(t);if(!r)throw new Error(`Invalid HCS-17 message: ${i.join(", ")}`);const o=Kh({topicId:e,stateHash:t.state_hash,accountId:t.account_id,topics:t.topics,memo:t.m}),n=await o.execute(this.client);return await n.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 o=Kh({topicId:e.publishTopicId,stateHash:i.stateHash,accountId:e.accountId,topics:e.topics,memo:e.memo}),n=await o.execute(this.client),s=await n.getReceipt(this.client);return{stateHash:i.stateHash,receipt:s}}},exports.HCS17TopicType=Dh,exports.HCS18BaseClient=ig,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=Zh(e.data);return this.submit(e.discoveryTopicId,t)}async propose(e){const t=Qh(e.data);return this.submit(e.discoveryTopicId,t)}async respond(e){const t=eg(e.data);return this.submit(e.discoveryTopicId,t)}async complete(e){const t=tg(e.data);return this.submit(e.discoveryTopicId,t)}async withdraw(e){const t=rg(e.data);return this.submit(e.discoveryTopicId,t)}},exports.HCS18Client=class extends ig{constructor(e){super({network:e.network,logger:B.getInstance({level:e.logLevel||"info",module:"HCS-18",silent:e.silent})}),this.operatorCtx=ne({network:this.network,operatorId:e.operatorId,operatorKey:e.operatorKey,mirrorNode:this.mirrorNode,logger:this.logger,client:i.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=Yh({ttlSeconds:t,adminKey:e?.adminKey,submitKey:e?.submitKey,operatorPublicKey:r,memoOverride:e?.memoOverride}),o=await i.execute(this.client),n=await o.getReceipt(this.client),s=n.topicId?.toString();if(!s)throw new Error("Failed to create discovery topic");return{topicId:s,receipt:n}}async announce(e){await this.ensureInitialized();const t=Zh(e.data),r=Xh({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client),o=await i.getReceipt(this.client),n=o.topicSequenceNumber.toNumber();return{receipt:o,sequenceNumber:n}}async propose(e){await this.ensureInitialized();const t=Qh(e.data),r=Xh({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client),o=await i.getReceipt(this.client),n=o.topicSequenceNumber.toNumber();return{receipt:o,sequenceNumber:n}}async respond(e){await this.ensureInitialized();const t=eg(e.data),r=Xh({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=tg(e.data),r=Xh({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=rg(e.data),r=Xh({topicId:e.discoveryTopicId,message:t,transactionMemo:e.memo}),i=await r.execute(this.client);return await i.getReceipt(this.client)}},exports.HCS20BaseClient=Xp,exports.HCS20BurnMessageSchema=Lp,exports.HCS20Client=class extends Xp{constructor(e){super(e),this.operatorAccountId="string"==typeof e.operatorId?i.AccountId.fromString(e.operatorId):e.operatorId,this.operatorId=this.operatorAccountId.toString();const t="mainnet"===this.network?i.Client.forMainnet():i.Client.forTestnet();this.operatorCtx=ne({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 r;if(t){const i=e.freezeWith(this.client),o=await i.sign(t);r=await o.execute(this.client)}else r=await e.execute(this.client);const o=await r.getReceipt(this.client);if(!o||o.status!==i.Status.Success)throw new Error("Failed to submit message to topic");return{receipt:o,transactionId:r.transactionId.toString()}}async createPublicTopic(e){await this.ensureInitialized(),this.logger.info("Creating public HCS-20 topic...");const t=await(new i.TopicCreateTransaction).setTopicMemo(e||"HCS-20 Public Topic").execute(this.client),r=await t.getReceipt(this.client);if(r.status!==i.Status.Success||!r.topicId)throw new Error("Failed to create public topic");const o=r.topicId.toString();return this.logger.info(`Created public topic: ${o}`),this.publicTopicId=o,o}async createRegistryTopic(){await this.ensureInitialized(),this.logger.info("Creating HCS-20 registry topic...");const e=new _p({operatorId:this.operatorId,operatorKey:this.operatorCtx.operatorKey,network:this.network}),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 _p({operatorId:this.operatorId,operatorKey:this.operatorCtx.operatorKey,network:this.network});if(e.usePrivateTopic){const t=await i.createRegistry({submitKey:this.operatorCtx.operatorKey,adminKey:this.operatorCtx.operatorKey});if(!t.success)throw new jp("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 o={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},n=this.validateMessage(o);if(!n.valid)throw new Gp("Invalid deploy message",n.errors);const s=Zp({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,o=Qp({topicId:i,tick:e.tick,amt:e.amount,to:this.accountToString(e.to),memo:e.memo}),{transactionId:n}=await this.submitPayload(o);t?.({stage:"confirming",percentage:80,mintTxId:n}),await this.waitForMirrorNodeConfirmation(i,n),t?.({stage:"complete",percentage:100,mintTxId:n});return{id:n,operation:"mint",tick:r,amount:e.amount,to:this.accountToString(e.to),timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:i,transactionId:n,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),o=this.accountToString(e.to);if(i!==this.operatorId)throw new Wp("For public topics, transaction payer must match sender",e.tick,i,o,e.amount);t?.({stage:"submitting",percentage:50});const n=e.topicId?this.topicToString(e.topicId):this.publicTopicId,s=eh({topicId:n,tick:e.tick,amt:e.amount,from:i,to:o,memo:e.memo}),{transactionId:a}=await this.submitPayload(s);t?.({stage:"confirming",percentage:80,transferTxId:a}),await this.waitForMirrorNodeConfirmation(n,a),t?.({stage:"complete",percentage:100,transferTxId:a});return{id:a,operation:"transfer",tick:r,amount:e.amount,from:i,to:o,timestamp:(new Date).toISOString(),sequenceNumber:0,topicId:n,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 Vp("For public topics, transaction payer must match burner",e.tick,i,e.amount);t?.({stage:"submitting",percentage:50});const o=e.topicId?this.topicToString(e.topicId):this.publicTopicId,n=th({topicId:o,tick:e.tick,amt:e.amount,from:i,memo:e.memo}),{transactionId:s}=await this.submitPayload(n);t?.({stage:"confirming",percentage:80,burnTxId:s}),await this.waitForMirrorNodeConfirmation(o,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:o,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 Gp("Invalid register message",i.errors);if(!this.registryTopicId)throw new jp("Registry topic not available",e.name);t?.({stage:"submitting",percentage:50});const o=rh({registryTopicId:this.registryTopicId,name:e.name,topicId:this.topicToString(e.topicId),isPrivate:e.isPrivate,metadata:e.metadata,memo:e.memo}),{transactionId:n}=await this.submitPayload(o,this.operatorCtx.operatorKey);t?.({stage:"confirming",percentage:80,registerTxId:n}),await this.waitForMirrorNodeConfirmation(this.registryTopicId,n),t?.({stage:"complete",percentage:100,registerTxId:n}),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 o=0;o<r;o++){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 ${o+1} failed:`,i)}await M(2e3)}this.logger.warn(`Transaction ${t} not found on mirror node after ${r} attempts`)}},exports.HCS20DeployMessageSchema=Mp,exports.HCS20Error=qp,exports.HCS20MessageSchema=Hp,exports.HCS20MintMessageSchema=Up,exports.HCS20PointsIndexer=class{constructor(e,t,r){this.isProcessing=!1,this.lastIndexedSequence=new Map,this.logger=t||new B({level:"info",module:"HCS20PointsIndexer"}),this.mirrorNode=new J(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 o=i.get(t);return o?.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||Fp.PUBLIC_TOPIC_ID:null,o=r?e?.registryTopicId||Fp.REGISTRY_TOPIC_ID:null,n=e?.pollInterval||3e4;await this.indexTopics(i,o,e?.privateTopics);const s=async()=>{if(this.isProcessing){try{await this.indexTopics(i,o,e?.privateTopics)}catch(t){this.logger.error("Polling error:",t)}this.isProcessing&&setTimeout(s,n)}};setTimeout(s,n)}async indexOnce(e){const t=!1!==e?.includePublicTopic,r=!1!==e?.includeRegistryTopic,i=t?e?.publicTopicId||Fp.PUBLIC_TOPIC_ID:null,o=r?e?.registryTopicId||Fp.REGISTRY_TOPIC_ID:null;await this.indexTopics(i,o,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 o of i)await this.indexTopic(o,!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 o=r||0;for(const n of i){if("hcs-20"!==n.p)continue;const r=Hp.safeParse(n);if(!r.success){this.logger.debug("Skipping message due to schema mismatch");continue}const i=r.data,s=n.sequence_number??0;this.logger.debug(`Found HCS-20 message: op=${i.op}, sequence=${s}`),s>o&&(o=s);const a={consensus_timestamp:n.consensus_timestamp??"",sequence_number:s,payer_account_id:n.payer_account_id??n.payer??"",transaction_id:n.transaction_id??""};this.processMessage(i,a,e,t),this.state.lastProcessedSequence++,this.state.lastProcessedTimestamp=n.consensus_timestamp||""}o>(r||0)&&this.lastIndexedSequence.set(e,o)}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 o=this.normalizeTick(e.tick);if(this.state.deployedPoints.has(o))return;const n={name:e.name,tick:o,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(o,n),this.logger.info(`Deployed points: ${o}`)}processMintMessage(e,t,r,i){const o=this.normalizeTick(e.tick),n=this.state.deployedPoints.get(o);if(!n)return;const s=BigInt(e.amt),a=BigInt(n.currentSupply);if(a+s>BigInt(n.maxSupply))return;if(n.limitPerMint&&s>BigInt(n.limitPerMint))return;n.currentSupply=(a+s).toString();let c=this.state.balances.get(o);c||(c=new Map,this.state.balances.set(o,c));const l=c.get(e.to),d=l?(BigInt(l.balance)+s).toString():e.amt;c.set(e.to,{tick:o,accountId:e.to,balance:d,lastUpdated:t.consensus_timestamp}),this.state.transactions.push({id:t.transaction_id||`${r}-${t.sequence_number}`,operation:"mint",tick:o,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 o=this.normalizeTick(e.tick),n=this.state.balances.get(o);if(!n)return;if(!i&&t.payer_account_id!==e.from)return;const s=n.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=n.get(e.to);c?(c.balance=(BigInt(c.balance)+a).toString(),c.lastUpdated=t.consensus_timestamp):n.set(e.to,{tick:o,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:o,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 o=this.normalizeTick(e.tick),n=this.state.deployedPoints.get(o),s=this.state.balances.get(o);if(!n||!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,n.currentSupply=(BigInt(n.currentSupply)-c).toString(),this.state.transactions.push({id:t.transaction_id||`${r}-${t.sequence_number}`,operation:"burn",tick:o,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=$p,exports.HCS20TransferMessageSchema=Kp,exports.HCS20_CONSTANTS=Fp,exports.HCS21BaseClient=yh,exports.HCS21BrowserClient=class extends yh{constructor(e){super({network:e.network,logger:e.logger}),this.hwc=e.hwc}async publishDeclaration(e){const t="p"in e.declaration?this.validateDeclaration(e.declaration):this.buildDeclaration(e.declaration);await this.hwc.submitMessageToTopic(e.topicId,JSON.stringify(t))}async fetchDeclarations(e){const{messages:t=[]}=await this.hwc.getMessages(e),r=[];for(const o of t)try{const e=this.validateDeclaration(o.message);r.push({declaration:e,consensusTimestamp:o.consensus_timestamp,sequenceNumber:Number(o.sequence_number||0),payer:o.payer_account_id})}catch(i){const e=i instanceof Error?i.message:"unknown error";this.logger.warn(`Skipping invalid HCS-21 browser message: ${e}`)}return r}},exports.HCS21Client=class extends yh{constructor(e){const t=e.logger||new B({level:e.logLevel||"info",module:"HCS-21"});super({network:e.network,logger:t,mirrorNodeUrl:e.mirrorNodeUrl});const r="mainnet"===e.network?i.Client.forMainnet():i.Client.forTestnet();this.operatorCtx=ne({network:e.network,operatorId:e.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:r}),this.operatorCtx.ensureInitialized(),this.client=this.operatorCtx.client}async inscribeMetadata(e){await this.operatorCtx.ensureInitialized();const t=ph.parse(e.document),r=JSON.stringify(t,null,2),i=globalThis.Buffer.from(r,"utf8"),o={waitForConfirmation:!0,connectionMode:e.inscriptionOptions?.connectionMode??(!1===e.inscriptionOptions?.websocket?"http":"auto"),websocket:e.inscriptionOptions?.websocket??!1,...e.inscriptionOptions||{},metadata:{...e.inscriptionOptions?.metadata||{},...t}},n=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},o);if(!n.confirmed||!n.inscription)throw new hh("Failed to inscribe HCS-21 metadata","invalid_payload");const s=n.inscription.jsonTopicId||n.inscription.topic_id||La(n.inscription);if(!s)throw new hh("Metadata inscription did not return a topic ID","invalid_payload");const a=n.inscription.sequence_number??n.inscription.sequenceNumber,c=await this.resolveManifestPointer(s,a),l=n.result&&"jobId"in n.result?{jobId:n.result.jobId,transactionId:n.result.transactionId}:{};return{pointer:c.pointer,topicId:s,sequenceNumber:c.sequenceNumber,...l}}async createRegistryTopic(e){await this.operatorCtx.ensureInitialized();const t=mh({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 r=await t.execute(this.client),o=await r.getReceipt(this.client);if(o.status!==i.Status.Success||!o.topicId)throw new hh("Failed to create HCS-21 registry topic","invalid_payload");return o.topicId.toString()}async publishDeclaration(e){await this.operatorCtx.ensureInitialized();const t=this.normalizeDeclarationInput(e.declaration),r=fh({topicId:e.topicId,declaration:t,transactionMemo:e.transactionMemo}),o=await r.execute(this.client),n=await o.getReceipt(this.client);if(n.status!==i.Status.Success)throw new hh("Failed to submit HCS-21 declaration","invalid_payload");return{sequenceNumber:n.topicSequenceNumber?.toNumber(),transactionId:o.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 hh("Unable to resolve manifest sequence number","invalid_payload");i=Number(t.sequence_number)}if(!Number.isFinite(i))throw new hh("Invalid manifest sequence number","invalid_payload");const o=`hcs://1/${e}/${i}`;if(!oh.test(o))throw new hh("Manifest pointer format is invalid","invalid_payload");return{pointer:o,sequenceNumber:i}}},exports.HCS21ManifestPointerPattern=oh,exports.HCS21TopicIdPattern=nh,exports.HCS21TopicType=sh,exports.HCS21ValidationError=hh,exports.HCS21_MAX_MESSAGE_BYTES=1024,exports.HCS21_PROTOCOL=ih,exports.HCS2BaseClient=xp,exports.HCS2Client=_p,exports.HCS2Operation=wp,exports.HCS2RegistryType=Ip,exports.HCS5BrowserClient=class extends yp{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=fp(e.metadataTopicId),r=bp({tokenId:e.tokenId,metadata:t});let o;if(e.supplyKey&&e.supplyKey instanceof i.PrivateKey){const t=this.getSigner();r.freezeWithSigner(t);const i=await r.sign(e.supplyKey);o=await this.hwc.executeTransactionWithErrorHandling(i,!0)}else o=await this.hwc.executeTransactionWithErrorHandling(r,!1);if(o.error)return{success:!1,error:o.error};const n=o.result;return{success:!0,serialNumber:n.serials?.[0]?Number(n.serials[0].toString()):void 0,transactionId:n?.transactionId?.toString?.(),metadata:t}}catch(dg){return{success:!1,error:String(dg)}}}async createHashinal(e){try{const t=this.getSigner(),r={...e.inscriptionOptions,mode:"hashinal",waitForConfirmation:!0,network:this.network},i=await za(e.inscriptionInput,t,r),o=i.inscription?.jsonTopicId||i.inscription?.topic_id;return i.confirmed&&o?await this.mint({tokenId:e.tokenId,metadataTopicId:o,supplyKey:e.supplyKey,memo:e.memo}):{success:!1,error:"Failed to inscribe content"}}catch(dg){return{success:!1,error:String(dg)}}}},exports.HCS5Client=class extends yp{constructor(e){super(e),this.operatorId=i.AccountId.fromString(e.operatorId),this.operatorCtx=ne({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,mirrorNode:this.mirrorNode,logger:this.logger}),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=fp(e.metadataTopicId),r=bp({tokenId:e.tokenId,metadata:t}),i=await r.freezeWith(this.client);if(e.supplyKey){const t=new oe({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 o=await i.execute(this.client),n=await o.getReceipt(this.client);return{success:!0,serialNumber:n.serials&&n.serials[0]?Number(n.serials[0].toString()):void 0,transactionId:o.transactionId?.toString?.(),metadata:t}}catch(dg){const t=dg;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(dg){const t=dg;return this.logger.error(`Failed to inscribe and mint HCS-5 Hashinal: ${t.message}`),{success:!1,error:t.message}}}},exports.HCS6BaseClient=Y,exports.HCS6BrowserClient=class extends Y{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),o=i.topicSequenceNumber;return{success:!0,receipt:i,sequenceNumber:"number"==typeof o?o:o?.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 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"}),n=t.limit?o.slice(0,t.limit):o;return this.logger.debug(`Retrieved ${o.length} messages, using ${n.length} after applying limit.`),this.parseRegistryEntries(e,n,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 za(r,this.signer,t),o=i.inscription?.jsonTopicId||La(i.inscription);if(!o)return{success:!1,error:"Failed to inscribe metadata"};let n=e.registryTopicId;if(!n){const t=await this.createRegistry({ttl:e.ttl});if(!t.success||!t.topicId)return{success:!1,error:t.error};n=t.topicId}const s=await this.registerEntry(n,{targetTopicId:o,memo:e.memo||"Initial dynamic hashinal registration"});return s.success?{success:!0,registryTopicId:n,inscriptionTopicId:o}:{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 za(t,this.signer,r),o=i.inscription?.jsonTopicId||La(i.inscription);if(!o)return{success:!1,error:"Failed to inscribe data"};let n=e.registryTopicId;if(!n){const t=await this.createRegistry({ttl:e.ttl});if(!t.success||!t.topicId)return{success:!1,error:t.error};n=t.topicId}const s=await this.registerEntry(n,{targetTopicId:o,memo:e.memo||"Dynamic hashinal registration"});return s.success?{success:!0,registryTopicId:n,inscriptionTopicId:o}:{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===K.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 Y{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,mirrorNodeUrl:e.mirrorNodeUrl,logger:e.logger}),this.operatorId="string"==typeof e.operatorId?i.AccountId.fromString(e.operatorId):e.operatorId,this.operatorCtx=ne({network:this.network,operatorId:this.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger,client:this.createClient(e.network)}),this.client=this.operatorCtx.client}async ensureInitialized(){await this.operatorCtx.ensureInitialized()}createClient(e){return"mainnet"===e?i.Client.forMainnet():i.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,r){const{valid:o,errors:n}=this.validateMessage(t);if(!o)throw new Error(`Invalid HCS-6 message: ${n.join(", ")}`);let s=(new i.TopicMessageSubmitTransaction).setTopicId(i.TopicId.fromString(e)).setMessage(JSON.stringify(t));if(!r){const e=await s.execute(this.client);return await e.getReceipt(this.client)}const a="string"==typeof r?i.PrivateKey.fromString(r):r,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),o=await this.submitMessageWithKey(e,i,r),n=o.topicSequenceNumber?.toNumber();return{success:!0,receipt:o,sequenceNumber:n}}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 r,o;if(e.submitKey)if("string"==typeof e.submitKey)try{r=i.PublicKey.fromString(e.submitKey)}catch{const t=globalThis.Buffer.from(e.submitKey.replace(/^0x/i,""),"hex");r="ed25519"===this.operatorCtx.keyType?i.PublicKey.fromBytesED25519(t):i.PublicKey.fromBytesECDSA(t)}else"boolean"==typeof e.submitKey?r=this.operatorCtx.operatorKey.publicKey:(r=e.submitKey.publicKey,o=e.submitKey);let n=Q({ttl:t,submitKey:r,adminKey:this.operatorCtx.operatorKey.publicKey,operatorPublicKey:this.operatorCtx.operatorKey.publicKey});const s=await n.freezeWith(this.client);o&&await s.sign(o);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]),o=parseInt(r[1]),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"})).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:o}:null}catch{return null}}).filter(e=>Boolean(e)),s=n.length>0?n[n.length-1]:void 0;return{topicId:e,registryType:o,ttl:i,entries:n,latestEntry:s}}async mint(e){try{if(await this.ensureInitialized(),!e.metadataTopicId)return{success:!1,error:"metadataTopicId is required for mint()"};const t=$(e.metadataTopicId);let r=(new i.TokenMintTransaction).setTokenId(i.TokenId.fromString(e.tokenId)).setMetadata([globalThis.Buffer.from(t)]);const o=await r.freezeWith(this.client);if(e.supplyKey){const t=new oe({mirrorNode:this.mirrorNode,logger:this.logger}),r="string"==typeof e.supplyKey?await t.resolveSupplyKey(e.tokenId,e.supplyKey,this.operatorCtx.keyType):e.supplyKey;await o.sign(r)}const n=await o.execute(this.client),s=await n.getReceipt(this.client);return{success:!0,serialNumber:s.serials&&s.serials[0]?Number(s.serials[0].toString()):void 0,transactionId:n.transactionId?.toString?.(),metadata:t}}catch(dg){return{success:!1,error:String(dg)}}}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(dg){return{success:!1,error:String(dg)}}}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)),o={...e.inscriptionOptions,mode:"hashinal",metadata:e.metadata,waitForConfirmation:!0},n=await Oa({type:"buffer",buffer:i,fileName:"metadata.json",mimeType:"application/json"},{accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},o);if(!n.confirmed||!n.inscription)throw new Error("Failed to inscribe metadata");const s=n.inscription.jsonTopicId||n.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(dg){return{success:!1,error:String(dg)}}}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 o={...e.inscriptionOptions,mode:"hashinal",metadata:e.metadata,waitForConfirmation:!0},n=await Oa(i,{accountId:this.operatorId.toString(),privateKey:this.operatorCtx.operatorKey,network:this.network},o);if(!n.confirmed||!n.inscription)throw new Error("Failed to inscribe data");const s=n.inscription.jsonTopicId||n.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(dg){return{success:!1,error:String(dg)}}}},exports.HCS6Operation=L,exports.HCS6RegistryType=K,exports.HCS7BaseClient=Xa,exports.HCS7BrowserClient=class extends Xa{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:Za(i)}}catch(t){return this.logger.error("Failed to submit HCS-7 browser message",t),{success:!1,error:String(t)}}}},exports.HCS7Client=class extends Xa{constructor(e){super(e),this.closed=!1,this.operatorCtx=ne({network:this.network,operatorId:e.operatorId,operatorKey:e.operatorKey,keyType:e.keyType,mirrorNode:this.mirrorNode,logger:this.logger}),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 i.PublicKey.fromString(e)}catch{return}return e.publicKey}}coercePrivateKey(e){if(e instanceof i.PrivateKey)return e;try{return i.PrivateKey.fromStringED25519(e)}catch{return i.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=Qa({ttl:t,submitKey:r,adminKey:this.resolvePublicKey(e.adminKey),operatorPublicKey:this.operatorCtx.operatorKey.publicKey});i=await i.freezeWith(this.client);const o=await i.execute(this.client),n=await o.getReceipt(this.client),s=n.topicId?.toString();return s?{success:!0,topicId:s,transactionId:o.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=ec({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),o=await i.getReceipt(this.client);return{success:!0,receipt:o,sequenceNumber:o.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=$a,exports.HCS7Operation=Ka,exports.HRLResolver=Yl,exports.HTSParser=ha,exports.HashLinkResolver=Mu,exports.HashLinkScanner=Bu,exports.HashLinksRegistry=Pu,exports.Hcs10MemoType=Qd,exports.HederaHieroIssuer=hp,exports.HederaMirrorNode=J,exports.HieroDidResolver=np,exports.InboundTopicType=Ed,exports.InsufficientBalanceError=class extends qp{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=Yp,exports.InvalidMessageFormatError=class extends qp{constructor(e,t){super(e),this.messageData=t,this.name="InvalidMessageFormatError"}},exports.InvalidNumberFormatError=class extends qp{constructor(e,t){super(`Invalid number format for ${t}: ${e}`),this.value=e,this.field=t,this.name="InvalidNumberFormatError"}},exports.InvalidTickFormatError=class extends qp{constructor(e){super(`Invalid tick format: ${e}`),this.tick=e,this.name="InvalidTickFormatError"}},exports.IssuerRegistry=lp,exports.KeyType=ee,exports.KeyTypeDetector=re,exports.Logger=B,exports.MAINNET_EXAMPLES=Lu,exports.MCPServerBuilder=class{constructor(){this.config={mcpServer:{}},this.socials=[],this.logger=B.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:kd.DNS,value:e,dns_field:t};return this.config.mcpServer.verification=r,this}addVerificationSignature(e){this.config.mcpServer||(this.config.mcpServer={});const t={type:kd.SIGNATURE,value:e};return this.config.mcpServer.verification=t,this}addVerificationChallenge(e){this.config.mcpServer||(this.config.mcpServer={});const t={type:kd.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}},exports.MCPServerCapability=Sd,exports.MCPServerConnectionInfoSchema=xd,exports.MCPServerDetailsSchema=Fd,exports.MCPServerHostSchema=Nd,exports.MCPServerProfileSchema=Bd,exports.MCPServerResourceSchema=_d,exports.MCPServerToolSchema=Pd,exports.MCPServerVerificationSchema=Rd,exports.MapCache=tc,exports.MintLimitExceededError=class extends qp{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=nd,exports.NodeHashAdapter=Xl,exports.NodeHmacAdapter=rd,exports.PayloadSizeError=ru,exports.PersonBuilder=class{constructor(){this.config={version:"1.0",type:0},this.logger=B.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}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,properties:this.config.properties,inboundTopicId:this.config.inboundTopicId,outboundTopicId:this.config.outboundTopicId,pfpBuffer:this.config.pfpBuffer,pfpFileName:this.config.pfpFileName}}},exports.PersonalProfileSchema=zd,exports.PointsBurnError=Vp,exports.PointsDeploymentError=jp,exports.PointsMintError=class extends qp{constructor(e,t,r,i){super(e),this.tick=t,this.requestedAmount=r,this.availableSupply=i,this.name="PointsMintError"}},exports.PointsNotFoundError=class extends qp{constructor(e){super(`Points with tick "${e}" not found`),this.tick=e,this.name="PointsNotFoundError"}},exports.PointsTransferError=Wp,exports.PointsValidationError=Gp,exports.ProfileType=bd,exports.ProgressReporter=hs,exports.REFERENCE_THRESHOLD=51200,exports.RedisCache=class{constructor(e={}){const{host:t="localhost",port:r=6379,password:i,db:o=0,keyPrefix:n="",tls:s=!1,connectTimeout:a=5e3,retryStrategy:c,logLevel:l="info"}=e;this.prefix=n,this.logger=B.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:o,tls:s?{}:void 0,keyPrefix:n,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=Kd,exports.RegistryBrokerClient=Vl,exports.RegistryBrokerError=jl,exports.RegistryBrokerParseError=Wl,exports.RegistryType=lu,exports.ResolverRegistry=sp,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 U,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),o=new Blob([i.buffer],{type:t.contentType});return this.logger.debug("Image resource loaded successfully",{topicId:e,size:r.length,type:t.contentType}),o}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(td())return this.logger.warn("Integrity verification skipped in SSR environment"),!0;if("undefined"==typeof crypto||!crypto.subtle)return this.logger.warn("WebCrypto not available, skipping integrity verification"),!0;const r="string"==typeof e?(new TextEncoder).encode(e):e,i=r instanceof Uint8Array?r:new Uint8Array(r),o=new Uint8Array(i),n=await crypto.subtle.digest("SHA-256",o.buffer),s=Array.from(new Uint8Array(n));return s.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 o;o=i.startsWith("text/")||i.includes("javascript")||i.includes("json")?await r.text():new Uint8Array(await r.arrayBuffer());const n={content:o,contentType:i,size:r.size};return this.addToCache(e,n),n}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 n of e)t.set(n.topicId,n.depends||[]);const r=new Set,i=new Set,o=e=>{if(i.has(e))throw new Error("Circular dependency detected");if(r.has(e))return;i.add(e);const n=t.get(e)||[];for(const t of n)o(t);i.delete(e),r.add(e)};for(const n of e)o(n.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=[],o=new Set,n=e=>{if(o.has(e))return;const s=r.get(e)||[];for(const t of s)n(t);o.add(e);const a=t.get(e);a&&i.push(a)};for(const s of e)n(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=["twitter","github","discord","telegram","linkedin","youtube","website","x"],exports.ScheduleParser=wa,exports.SocialLinkSchema=vd,exports.StateHashError=zh,exports.SupplyLimitExceededError=class extends qp{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=Uu,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 o=i.render(this.sanitizeContext(t));return this.logger.debug("Template rendered successfully",{resultLength:o.length}),o}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,o,n,s,a)=>{if(!this.evaluateCondition(r,t))return"";return i+(this.evaluateCondition(o,t)?n:s)+a});r=r.replace(/\{\{#if\s+([^}]+)\}\}((?:[^{]|\{(?!\{)|\{\{(?!else|\/if))*?)\{\{else\}\}((?:[^{]|\{(?!\{)|\{\{(?!\/if))*?)\{\{\/if\}\}/gs,(e,r,i,o)=>this.evaluateCondition(r,t)?i:o);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 o=this.getNestedValue(r,t);if(!o)return"";let n="";if(Array.isArray(o))o.forEach((e,r)=>{let o=i;if(o=o.replace(/\{\{this\}\}/g,this.escapeHtml(String(e))),o=o.replace(/\{\{@index\}\}/g,String(r)),"object"==typeof e&&null!==e)for(const[t,i]of Object.entries(e)){const e=new RegExp(`\\{\\{${t}\\}\\}`,"g");o=o.replace(e,this.escapeHtml(String(i)))}o=o.replace(/\{\{\.\.\/([^}]+)\}\}/g,(e,r)=>{const i=this.getNestedValue(r,t);return this.escapeHtml(String(i||""))}),n+=o});else if("object"==typeof o)for(const[t,s]of Object.entries(o)){let e=i;e=e.replace(/\{\{@key\}\}/g,this.escapeHtml(t)),e=e.replace(/\{\{this\}\}/g,this.escapeHtml(String(s))),n+=e}return n}),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 o=this.getNestedValue(i,t);return 0===o||!1===o?this.escapeHtml(String(o)):this.escapeHtml(String(o||""))}),r}processHelpers(e,t){let r=e;r=r.replace(/\{\{#with\s+([^}]+)\}\}(.*?)\{\{\/with\}\}/gs,(e,r,i)=>{const o=this.getNestedValue(r.trim(),t);return o?this.executeTemplate(i,o):""});for(const[i,o]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(o.call(t,e))}catch(n){return this.logger.warn("Helper execution failed",{helperName:i,error:n}),""}})}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 o of r){if(null==i||"object"!=typeof i)return;i=i[o]}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,o]of Object.entries(e))i[t]=r(o);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=ou,exports.TopicRegistrationError=Jp,exports.TransactionParser=va,exports.TransactionParsingError=gs,exports.VerificationType=kd,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=B.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,o=t(i,1);const n=this.getUint8Memory();let s=0;for(;s<i;s++){const t=e.charCodeAt(s);if(t>127)break;n[o+s]=t}if(s!==i){0!==s&&(e=e.slice(s)),o=r(o,i,i=s+3*this.textEncoder.encode(e).length,1);const t=this.getUint8Memory().subarray(o+s,o+i);s+=this.encodeString(e,t).written}return this.WASM_VECTOR_LEN=s,o}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 o=[r,...t.map(e=>[this.passStringToWasm(e,this.wasm.__wbindgen_malloc,this.wasm.__wbindgen_realloc),this.WASM_VECTOR_LEN]).flat()];e.apply(this.wasm,o);const n=this.getDataViewMemory().getInt32(r+0,!0),s=this.getDataViewMemory().getInt32(r+4,!0);return i=[n,s],this.getStringFromWasm(n,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 o=t[e];o&&"object"==typeof o&&"values"in o&&o.values.length>0?r[e]=String(o.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=Du,exports.WasmValidator=class{constructor(e){this.cryptoAdapter=cd(),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 o=this.getWasmVersion(e);if(i.version=o,1!==o)return t.push(`Unsupported WASM version: ${o}`),i.isValid=!1,i;const n=await this.parseModule(e);i.exports=n.exports;for(const e of this.REQUIRED_EXPORTS)n.exports.includes(e)||(t.push(`Missing required export: ${e}`),i.isValid=!1);i.imports=n.imports;for(const e of n.imports){const r=`${e.module}.${e.name}`;this.ALLOWED_IMPORTS.has(r)||(t.push(`Disallowed import: ${r}`),i.isValid=!1)}n.memory&&(i.memoryRequirements=n.memory,n.memory.initial>this.MAX_INITIAL_MEMORY&&(t.push(`Excessive initial memory: ${n.memory.initial} pages`),i.isValid=!1)),n.hasStartFunction&&r.push("Module has start function - may execute code on load"),n.functionCount>100&&r.push(`High function count: ${n.functionCount}`),this.hasSuspiciousPatterns(e)&&r.push("Potentially unsafe operation detected"),i.exportSignatures=n.exportSignatures}catch(o){this.logger.error("WASM validation failed",{error:o}),t.push(`Validation error: ${o instanceof Error?o.message:"Unknown error"}`),i.isValid=!1}return i}async validateInfoFunction(e){const t=[],r=[];try{const i=await e(),o=JSON.parse(i);return o.name&&o.version&&o.hashlinks_version?{isValid:!0,errors:t,warnings:r,moduleInfo:o}:(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(td())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 o=[],n=r.split("import:");for(let u=1;u<n.length;u++){const e=n[u].match(/^([a-zA-Z_]+[a-zA-Z0-9_]*)\.([a-zA-Z_]+[a-zA-Z0-9_]*)/);e&&o.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 d=r.match(/functions:(\d+)/);d&&(l=parseInt(d[1]));return{exports:i,imports:o,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=sd,exports.WebHashAdapter=Zl,exports.WebHmacAdapter=id,exports.accountIdsToExemptKeys=nc,exports.actionRegistrationSchema=yu,exports.adapterDeclarationSchema=lh,exports.adapterManifestSchema=dh,exports.adapterPackageSchema=ah,exports.assemblyMessageSchema=ku,exports.assemblyRegistrationSchema=Eu,exports.baseMessageSchema=Sp,exports.blockRegistrationSchema=bu,exports.buildHcs10ConfirmConnectionTx=Gd,exports.buildHcs10CreateConnectionTopicTx=jd,exports.buildHcs10CreateInboundTopicTx=Hd,exports.buildHcs10CreateOutboundTopicTx=qd,exports.buildHcs10CreateRegistryTopicTx=Wd,exports.buildHcs10OutboundConnectionCreatedRecordTx=Yd,exports.buildHcs10OutboundConnectionRequestRecordTx=Jd,exports.buildHcs10RegistryDeleteTx=function(e){const t={p:"hcs-10",op:"delete",uid:e.uid,m:e.memo};return Z({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:$d(1,0)})},exports.buildHcs10RegistryMigrateTx=function(e){const t={p:"hcs-10",op:"migrate",t_id:e.targetTopicId,m:e.memo};return Z({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:$d(2,0)})},exports.buildHcs10RegistryRegisterTx=Zd,exports.buildHcs10SendMessageTx=Xd,exports.buildHcs10SubmitConnectionRequestTx=Vd,exports.buildHcs12AddActionToAssemblyTx=function(e){return Z({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs12AddBlockToAssemblyTx=function(e){return Z({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs12CreateRegistryTopicTx=function(e){var t;return X({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 Z({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 Z({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs12UpdateAssemblyTx=function(e){return Z({topicId:e.assemblyTopicId,message:JSON.stringify(e.operation)})},exports.buildHcs15BaseAccountCreateTx=bh,exports.buildHcs15PetalAccountCreateTx=wh,exports.buildHcs16CreateAccountTx=Ah,exports.buildHcs16CreateFloraTopicTx=Eh,exports.buildHcs16CreateTransactionTopicTx=function(e){const t=(new i.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 r=e.customFees.map(e=>{const t=(new i.CustomFixedFee).setAmount(e.amount).setFeeCollectorAccountId(i.AccountId.fromString(e.feeCollectorAccountId));return e.denominatingTokenId&&t.setDenominatingTokenId(i.TokenId.fromString(e.denominatingTokenId)),t});t.setCustomFees(r)}if(e.feeExemptKeys&&e.feeExemptKeys.length>0)throw new Error("feeExemptKeys not supported by installed @hashgraph/sdk");return t},exports.buildHcs16FloraCreatedTx=Ch,exports.buildHcs16FloraJoinAcceptedTx=Ph,exports.buildHcs16FloraJoinRequestTx=Nh,exports.buildHcs16FloraJoinVoteTx=_h,exports.buildHcs16MessageTx=vh,exports.buildHcs16ScheduleAccountKeyUpdateTx=function(e){const t=(new i.AccountUpdateTransaction).setAccountId(i.AccountId.fromString(e.floraAccountId)).setKey(e.newKeyList);return e.memo&&t.setTransactionMemo(e.memo),(new i.ScheduleCreateTransaction).setScheduledTransaction(t)},exports.buildHcs16ScheduleTopicKeyUpdateTx=function(e){const t=(new i.TopicUpdateTransaction).setTopicId(e.topicId);return e.adminKey&&t.setAdminKey(e.adminKey),e.submitKey&&t.setSubmitKey(e.submitKey),e.memo&&t.setTransactionMemo(e.memo),(new i.ScheduleCreateTransaction).setScheduledTransaction(t)},exports.buildHcs16StateUpdateTx=Rh,exports.buildHcs16TransactionTx=xh,exports.buildHcs17CreateTopicTx=Lh,exports.buildHcs17MessageTx=Kh,exports.buildHcs18AnnounceMessage=Zh,exports.buildHcs18CompleteMessage=tg,exports.buildHcs18CreateDiscoveryTopicTx=Yh,exports.buildHcs18DiscoveryMemo=Jh,exports.buildHcs18ProposeMessage=Qh,exports.buildHcs18RespondMessage=eg,exports.buildHcs18SubmitDiscoveryMessageTx=Xh,exports.buildHcs18WithdrawMessage=rg,exports.buildHcs1Hrl=fp,exports.buildHcs20BurnTx=th,exports.buildHcs20DeployTx=Zp,exports.buildHcs20MintTx=Qp,exports.buildHcs20RegisterTx=rh,exports.buildHcs20SubmitMessageTx=function(e){const t="string"==typeof e.payload?e.payload:JSON.stringify(e.payload);return Z({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs20TransferTx=eh,exports.buildHcs21CreateRegistryTx=mh,exports.buildHcs21MessageTx=fh,exports.buildHcs21RegistryMemo=gh,exports.buildHcs2CreateRegistryTx=Rp,exports.buildHcs2DeleteTx=function(e){const t={p:"hcs-2",op:wp.DELETE,uid:e.uid,m:e.memo};return Z({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs2MigrateTx=function(e){const t={p:"hcs-2",op:wp.MIGRATE,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return Z({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs2RegisterTx=function(e){const t={p:"hcs-2",op:wp.REGISTER,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return Z({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs2UpdateTx=function(e){const t={p:"hcs-2",op:wp.UPDATE,uid:e.uid,t_id:e.targetTopicId,metadata:e.metadata,m:e.memo};return Z({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs5MintTx=bp,exports.buildHcs5MintWithHrlTx=function(e){const t=fp(e.metadataTopicId);return bp({tokenId:e.tokenId,metadata:t,transactionMemo:e.transactionMemo})},exports.buildHcs6CreateRegistryTx=Q,exports.buildHcs6Hrl=$,exports.buildHcs6RegisterEntryTx=function(e){const t={p:"hcs-6",op:L.REGISTER,t_id:e.targetTopicId,m:e.memo};return Z({topicId:e.registryTopicId,message:JSON.stringify(t),transactionMemo:e.analyticsMemo})},exports.buildHcs7CreateRegistryTx=Qa,exports.buildHcs7EvmMessageTx=function(e){const t={p:"hcs-7",op:Ka.REGISTER_CONFIG,t:$a.EVM,c:{contractAddress:e.config.contractAddress,abi:e.config.abi},m:e.config.memo??""};return ec({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.buildHcs7SubmitMessageTx=ec,exports.buildHcs7WasmMessageTx=function(e){const t={p:"hcs-7",op:Ka.REGISTER_CONFIG,t:$a.WASM,c:{wasmTopicId:e.config.wasmTopicId,inputType:e.config.inputType,outputType:e.config.outputType},m:e.config.memo??""};return ec({topicId:e.topicId,message:t,transactionMemo:e.transactionMemo})},exports.canonicalizeAgentData=ju,exports.canonicalizeLedgerNetwork=uc,exports.capabilityNameToCapabilityMap=Ad,exports.createLoggerAdapter=ic,exports.createPrivateKeySigner=zl,exports.createUaid=Xu,exports.defaultIssuerRegistry=dp,exports.defaultResolverRegistry=ap,exports.deleteMessageSchema=Ap,exports.detectCryptoEnvironment=ed,exports.detectKeyTypeFromString=ie,exports.ensureLoggerType=function(e){return oc(e)?e:ic(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.floraContextSchema=ch,exports.generateHCS17Memo=Bh,exports.generateHCS6RegistryMemo=G,exports.generateQuote=Ma,exports.getCryptoAdapter=cd,exports.getExampleTopics=function(e){return"mainnet"===e?Lu:Uu},exports.getHumanReadableTransactionType=Aa,exports.getOrCreateSDK=Na,exports.getParserConfig=function(e){return Ia[e]},exports.getSchedulableTransactionType=function(e){for(const[t,r]of Object.entries(ka))if(e[t])return r;return"unknown"},exports.getSupportedTransactionTypes=function(){return Object.keys(Ia)},exports.getTopicId=La,exports.getTransactionTypeFromBody=Ea,exports.hash=async function(e,t="sha256"){const r=cd().createHash(t),i="string"==typeof e?globalThis.Buffer.from(e):e,o=r.update(i).digest("hex");return o instanceof Promise?await o:o},exports.hashLinksRegistrationSchema=Au,exports.hcs17MessageSchema=Oh,exports.hcs2MessageSchema=Cp,exports.hcs6BaseMessageSchema=q,exports.hcs6MessageSchema=W,exports.hcs6RegisterMessageSchema=j,exports.hcs6TopicIdSchema=H,exports.hcs7MessageSchema=Ya,exports.humanReadableTypeRegistry=Sa,exports.inscribe=Oa,exports.inscribeWithSigner=za,exports.isAnnounceMessage=function(e){if(!Wh(e))return!1;const t=e;if("announce"!==t.op)return!1;if(!Hh(t.data))return!1;const r=t.data;if(!qh(r.account))return!1;if(!Hh(r.petal))return!1;const i=r.petal;return!(!qh(i.name)||!jh(i.priority))&&(!!Hh(r.capabilities)&&(!!function(e){return Array.isArray(e)&&e.every(qh)}(r.capabilities.protocols)&&!("valid_for"in r&&void 0!==r.valid_for&&null!==r.valid_for&&!jh(r.valid_for))))},exports.isBrowser=Ca,exports.isCompleteMessage=function(e){if(!Wh(e))return!1;const t=e;if("complete"!==t.op)return!1;if(!Hh(t.data))return!1;const r=t.data;if(!qh(r.proposer))return!1;if(!jh(r.proposal_seq))return!1;if(!qh(r.flora_account))return!1;if(!Hh(r.topics))return!1;const i=r.topics;return!!(qh(i.communication)&&qh(i.transaction)&&qh(i.state))},exports.isConcreteLogger=oc,exports.isCryptoAvailable=function(){return"none"!==ed().preferredAPI},exports.isDiscoveryMessage=Wh,exports.isEip155Caip10=fd,exports.isHederaCaip10=pd,exports.isHederaNetwork=dd,exports.isPartialRegisterAgentResponse=e=>"partial"===e.status&&!1===e.success,exports.isPendingRegisterAgentResponse=e=>"pending"===e.status,exports.isProposeMessage=function(e){if(!Wh(e))return!1;const t=e;if("propose"!==t.op)return!1;if(!Hh(t.data))return!1;const r=t.data;if(!qh(r.proposer))return!1;if(!function(e){return Array.isArray(e)}(r.members))return!1;if(!r.members.every(e=>{if(!Hh(e))return!1;const t=e;return!!qh(t.account)&&(!(!("priority"in t)||!jh(t.priority))&&!("announce_seq"in t&&void 0!==t.announce_seq&&null!==t.announce_seq&&!jh(t.announce_seq)))}))return!1;if(!Hh(r.config))return!1;const i=r.config;return!(!qh(i.name)||!jh(i.threshold))},exports.isRespondMessage=function(e){if(!Wh(e))return!1;const t=e;if("respond"!==t.op)return!1;if(!Hh(t.data))return!1;const r=t.data;return!!qh(r.responder)&&(!!jh(r.proposal_seq)&&(!!qh(r.decision)&&!!["accept","reject"].includes(r.decision)))},exports.isSSREnvironment=td,exports.isSuccessRegisterAgentResponse=e=>!0===e.success&&"pending"!==e.status,exports.isTransactionTypeSupported=function(e){return e in Ia},exports.isWithdrawMessage=function(e){if(!Wh(e))return!1;const t=e;if("withdraw"!==t.op)return!1;if(!Hh(t.data))return!1;const r=t.data;return!!qh(r.account)&&(!!jh(r.announce_seq)&&!("reason"in r&&void 0!==r.reason&&null!==r.reason&&!qh(r.reason)))},exports.mcpServiceNameToCapabilityMap={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},exports.metadataDocumentSchema=ph,exports.migrateMessageSchema=vp,exports.parseHCS17Memo=Mh,exports.parseHcs14Did=Zu,exports.parseHederaCaip10=gd,exports.protoFieldToTypeRegistry=Ta,exports.registerDefaultResolvers=cp,exports.registerMessageSchema=kp,exports.registryMetadataSchema=uh,exports.resolveTransactionSummary=la,exports.retrieveInscription=Da,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=ka,exports.setLoggerFactory=function(e){D=e,B.clearInstances()},exports.shouldUseReference=function(e){return("string"==typeof e?globalThis.Buffer.byteLength(e,"utf8"):e.length)>51200},exports.sleep=M,exports.toEip155Caip10=yd,exports.toHederaCaip10=hd,exports.topicIdSchema=Tp,exports.transactionParserRegistry=Ia,exports.transactionSummaryRegistry=ca,exports.updateMessageSchema=Ep,exports.validateActionRegistration=vu,exports.validateAssemblyMessage=Cu,exports.validateAssemblyRegistration=function(e){return Eu.parse(e)},exports.validateBlockRegistration=function(e){return bu.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&&V(i)},exports.validateHCS6TTL=V,exports.validateHashLinksRegistration=function(e){return Au.parse(e)},exports.validateWithSchema=xu,exports.waitForInscriptionConfirmation=Ua;
|
|
11
11
|
//# sourceMappingURL=standards-sdk.cjs.map
|