@hashgraphonline/standards-sdk 0.0.199 → 0.0.200
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.
|
@@ -154,7 +154,7 @@ read:function(e,t,i,n,o){var r,a,s=8*o-n-1,c=(1<<s)-1,p=c>>1,l=-7,u=i?o-1:0,d=i?
|
|
|
154
154
|
* Copyright(c) 2014 Jonathan Ong
|
|
155
155
|
* Copyright(c) 2015 Douglas Christopher Wilson
|
|
156
156
|
* MIT Licensed
|
|
157
|
-
*/().extname,a=/^\s*([^;\s]*)(?:;|\s|$)/,s=/^text\//i;function c(e){if(!e||"string"!=typeof e)return!1;var t=a.exec(e),i=t&&o[t[1].toLowerCase()];return i&&i.charset?i.charset:!(!t||!s.test(t[1]))&&"UTF-8"}e.charset=c,e.charsets={lookup:c},e.contentType=function(t){if(!t||"string"!=typeof t)return!1;var i=-1===t.indexOf("/")?e.lookup(t):t;if(!i)return!1;if(-1===i.indexOf("charset")){var n=e.charset(i);n&&(i+="; charset="+n.toLowerCase())}return i},e.extension=function(t){if(!t||"string"!=typeof t)return!1;var i=a.exec(t),n=i&&e.extensions[i[1].toLowerCase()];return!(!n||!n.length)&&n[0]},e.extensions=Object.create(null),e.lookup=function(t){if(!t||"string"!=typeof t)return!1;var i=r("x."+t).toLowerCase().substr(1);return i&&e.types[i]||!1},e.types=Object.create(null),t=e.extensions,i=e.types,n=["nginx","apache",void 0,"iana"],Object.keys(o).forEach(function(e){var r=o[e],a=r.extensions;if(a&&a.length){t[e]=a;for(var s=0;s<a.length;s++){var c=a[s];if(i[c]){var p=n.indexOf(o[i[c]].source),l=n.indexOf(r.source);if("application/octet-stream"!==i[c]&&(p>l||p===l&&"application/"===i[c].substr(0,12)))continue}i[c]=e}}})}(EZ));var jZ=(e=>(e[e.PERSONAL=0]="PERSONAL",e[e.AI_AGENT=1]="AI_AGENT",e[e.MCP_SERVER=2]="MCP_SERVER",e))(jZ||{}),CZ=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(CZ||{}),NZ=(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))(NZ||{}),BZ=(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))(BZ||{}),PZ=(e=>(e.DNS="dns",e.SIGNATURE="signature",e.CHALLENGE="challenge",e))(PZ||{});const LZ=Uo({platform:Co().min(1),handle:Co().min(1)}),UZ=Uo({type:Ko(CZ),capabilities:Lo(Ko(NZ)).min(1),model:Co().min(1),creator:Co().optional()}),FZ=Uo({url:Co().min(1),transport:qo(["stdio","sse"])}),MZ=Uo({type:Ko(PZ),value:Co(),dns_field:Co().optional(),challenge_path:Co().optional()}),DZ=Uo({minVersion:Co().optional()}),zZ=Uo({name:Co().min(1),description:Co().min(1)}),$Z=Uo({name:Co().min(1),description:Co().min(1)}),qZ=Uo({version:Co().min(1),connectionInfo:FZ,services:Lo(Ko(BZ)).min(1),description:Co().min(1),verification:MZ.optional(),host:DZ.optional(),capabilities:Lo(Co()).optional(),resources:Lo(zZ).optional(),tools:Lo($Z).optional(),maintainer:Co().optional(),repository:Co().optional(),docs:Co().optional()}),KZ=Uo({version:Co().min(1),type:Ko(jZ),display_name:Co().min(1),alias:Co().optional(),bio:Co().optional(),socials:Lo(LZ).optional(),profileImage:Co().optional(),properties:Do(Po()).optional(),inboundTopicId:Co().optional(),outboundTopicId:Co().optional()}),WZ=KZ.extend({type:$o(jZ.PERSONAL),language:Co().optional(),timezone:Co().optional()}),HZ=KZ.extend({type:$o(jZ.AI_AGENT),aiAgent:UZ}),VZ=KZ.extend({type:$o(jZ.MCP_SERVER),mcpServer:qZ});Fo([WZ,HZ,VZ]);const GZ=Uo({p:$o("hcs-12")}),ZZ=Co().regex(/^\d+\.\d+\.\d+$/,"Invalid Hedera address format"),JZ=Co().regex(/^[a-f0-9]{64}$/,"Invalid SHA-256 hash format"),YZ=Uo({format:qo(["tar.gz","zip","car"]),root_manifest:Co(),includes_lockfile:Bo(),workspace_members:Lo(Co()).optional()}),XZ=Uo({source_t_id:ZZ,source_hash:JZ,compiler_version:Co(),cargo_version:Co(),target:$o("wasm32-unknown-unknown"),profile:Co(),build_flags:Lo(Co()),lockfile_hash:JZ,source_structure:YZ}),QZ=zo(()=>Uo({type:Co().optional(),required:Lo(Co()).optional(),properties:Do(QZ).optional(),pattern:Co().optional(),minimum:No().optional(),maximum:No().optional(),regex:Co().optional(),min:No().optional(),max:No().optional(),length:No().optional(),email:Bo().optional(),url:Bo().optional(),uuid:Bo().optional(),cuid:Bo().optional(),cuid2:Bo().optional(),ulid:Bo().optional(),datetime:Bo().optional(),ip:Bo().optional(),startsWith:Co().optional(),endsWith:Co().optional(),includes:Co().optional(),gt:No().optional(),gte:No().optional(),lt:No().optional(),lte:No().optional(),int:Bo().optional(),positive:Bo().optional(),nonnegative:Bo().optional(),negative:Bo().optional(),nonpositive:Bo().optional(),multipleOf:No().optional(),finite:Bo().optional(),safe:Bo().optional(),nonempty:Bo().optional(),literal:Fo([Co(),No(),Bo()]).optional(),enum:Lo(Co()).optional(),nullable:Bo().optional(),nullish:Bo().optional(),optional:Bo().optional(),element:Po().optional(),shape:Do(Po()).optional(),strict:Bo().optional(),passthrough:Bo().optional(),catchall:Po().optional()}));Uo({p:$o("hcs-12"),op:$o("register"),t_id:ZZ,hash:JZ,wasm_hash:JZ,js_t_id:ZZ.optional(),js_hash:JZ.optional(),interface_version:Co().regex(/^\d+\.\d+\.\d+$/,"Invalid version format").optional(),info_t_id:ZZ.optional(),source_verification:XZ.optional(),previous_version:Co().optional(),migration_notes:Co().optional(),validation_rules:Do(QZ).optional(),m:Co().optional()}),Uo({p:$o("hcs-12"),op:qo(["register","template"]),name:Co(),version:Co().regex(/^\d+\.\d+\.\d+$/,"Invalid semver format"),data:Fo([Po(),Co()]).optional(),t_id:ZZ.optional()}),qo(["register","add-action","add-block","update"]);const eJ=GZ.extend({op:$o("register"),name:Co(),version:Co().regex(/^\d+\.\d+\.\d+$/,"Invalid semver format"),description:Co().optional(),tags:Lo(Co()).optional(),author:Co().optional()}),tJ=GZ.extend({op:$o("add-action"),t_id:ZZ,alias:Co(),config:Po().optional(),data:ZZ.optional()}),iJ=GZ.extend({op:$o("add-block"),block_t_id:ZZ,actions:Do(Co(),ZZ).optional(),attributes:Do(Po()).optional(),children:Lo(Co()).optional(),data:ZZ.optional()}),nJ=GZ.extend({op:$o("update"),description:Co().optional(),tags:Lo(Co()).optional()});Uo({type:qo(["vertical","horizontal","grid"]),responsive:Bo().optional(),containerClass:Co().optional()}),Uo({source_t_id:ZZ,source_hash:JZ,description:Co().optional()}),Mo("op",[eJ,tJ,iJ,nJ]),GZ.extend({op:$o("register"),t_id:ZZ,name:Co().max(100,"Name must be 100 characters or less"),description:Co().max(500,"Description must be 500 characters or less").optional(),tags:Lo(Co()).max(10,"Maximum 10 tags allowed").optional(),category:Co().optional(),featured:Bo().optional(),icon:Co().optional(),author:Co().optional(),website:Co().url().optional()});const oJ=Co().regex(/^\d+\.\d+\.\d+$/,{message:"Topic ID must be in Hedera format (e.g., '0.0.123456')"}),rJ=Uo({p:Co().regex(/^hcs-\d+$/,{message:"Protocol must be in format 'hcs-N' where N is a number"}),op:qo(["register","update","delete","migrate"]),m:Co().max(500,"Memo must not exceed 500 characters").optional(),ttl:No().int().positive().optional()});Mo("op",[rJ.extend({op:$o("register"),t_id:oJ,metadata:Co().optional()}),rJ.extend({op:$o("update"),uid:Co(),t_id:oJ,metadata:Co().optional()}),rJ.extend({op:$o("delete"),uid:Co()}),rJ.extend({op:$o("migrate"),t_id:oJ,metadata:Co().optional()})]);const aJ=18,sJ=100,cJ=100,pJ=/^(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))$/,lJ=Co().regex(pJ,"Invalid Hedera account ID format"),uJ=Co().regex(/^\d+$/,"Must be a valid number").max(aJ,`Max ${aJ} digits`),dJ=Co().min(1,"Tick cannot be empty").transform(e=>e.toLowerCase().trim()),fJ=Uo({p:$o("hcs-20"),m:Co().optional()});Mo("op",[fJ.extend({op:$o("deploy"),name:Co().min(1).max(sJ),tick:dJ,max:uJ,lim:uJ.optional(),metadata:Co().max(cJ).optional()}),fJ.extend({op:$o("mint"),tick:dJ,amt:uJ,to:lJ}),fJ.extend({op:$o("burn"),tick:dJ,amt:uJ,from:lJ}),fJ.extend({op:$o("transfer"),tick:dJ,amt:uJ,from:lJ,to:lJ}),fJ.extend({op:$o("register"),name:Co().min(1).max(sJ),metadata:Co().max(cJ).optional(),private:Bo(),t_id:lJ})]);(class e{constructor(){this.resolver=null,this.onUnavailableCallbacks=[],this.logger=Gi.getInstance({module:"ContentResolverRegistry"})}static getInstance(){return e._instance||(e._instance=new e),e._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(i){return this.logger.warn("Resolver operation failed, using fallback:",i),await t()}}}).getInstance();(class e{constructor(){this.contentStore=null,this.logger=Gi.getInstance({module:"ContentStoreService"})}static getInstance(){return e._instance||(e._instance=new e),e._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}}).getInstance();class mJ{constructor(e){if(F(this,"accountId"),F(this,"privateKey"),F(this,"baseUrl"),F(this,"network"),this.accountId=e.accountId,"string"==typeof e.privateKey){const t=Zo(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,i;const n=await wi.get(`${this.baseUrl}/api/auth/request-signature`,{headers:{"x-session":this.accountId}});if(!(null==(e=n.data)?void 0:e.message))throw new Error("Failed to get signature message");const o=n.data.message,r=await this.signMessage(o),a=await wi.post(`${this.baseUrl}/api/auth/authenticate`,{authData:{id:this.accountId,signature:r,data:o,network:this.network},include:"apiKey"});if(!(null==(i=null==(t=a.data)?void 0:t.user)?void 0:i.sessionToken))throw new Error("Authentication failed");return{apiKey:a.data.apiKey}}async signMessage(e){const t=(new TextEncoder).encode(e),i=await this.privateKey.sign(t);return Y.from(i).toString("hex")}}class hJ{constructor(e){F(this,"accountId"),F(this,"signer"),F(this,"baseUrl"),F(this,"network"),F(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,i;const n=await wi.get(`${this.baseUrl}/api/auth/request-signature`,{headers:{"x-session":this.accountId}});if(!(null==(e=n.data)?void 0:e.message))throw new Error("Failed to get signature message");const o=n.data.message,r=await this.signMessage(JSON.stringify(o)),a=await wi.post(`${this.baseUrl}/api/auth/authenticate`,{authData:{id:this.accountId,signature:r,data:o,network:this.network},include:"apiKey"});if(!(null==(i=null==(t=a.data)?void 0:t.user)?void 0:i.sessionToken))throw new Error("Authentication failed");return{apiKey:a.data.apiKey}}async signMessage(e){try{const t=(new TextEncoder).encode(e);this.logger.debug("signing message");const i=await this.signer.sign([t],{encoding:"utf-8"});return Y.from(null==i?void 0:i[0].signature).toString("hex")}catch(mxe){throw this.logger.error("Failed to sign message",mxe),new Error("Failed to sign message")}}}const gJ={get:(e,t)=>127&e[t+3]|e[t+2]<<7|e[t+1]<<14|e[t]<<21,len:4},yJ=4100;function vJ(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 bJ(e,t,i){i={offset:0,...i};for(const[n,o]of t.entries())if(i.mask){if(o!==(i.mask[n]&e[n+i.offset]))return!1}else if(o!==e[n+i.offset])return!1;return!0}class xJ{constructor(e){F(this,"detectConfident",async e=>{if(this.buffer=new Uint8Array(yJ),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(gJ);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 i;return await new xZ(e).unzip(e=>{switch(e.filename){case"META-INF/mozilla.rsa":return i={ext:"xpi",mime:"application/x-xpinstall"},{stop:!0};case"META-INF/MANIFEST.MF":return i={ext:"jar",mime:"application/java-archive"},{stop:!0};case"mimetype":return{async handler(e){const t=new TextDecoder("utf-8").decode(e).trim();i=vJ(t)},stop:!0};case"[Content_Types].xml":return{async handler(e){let t=new TextDecoder("utf-8").decode(e);const n=t.indexOf('.main+xml"');if(-1===n){const e="application/vnd.ms-package.3dmanufacturing-3dmodel+xml";t.includes(`ContentType="${e}"`)&&(i=vJ(e))}else{t=t.slice(0,Math.max(0,n));const e=t.lastIndexOf('"'),o=t.slice(Math.max(0,e+1));i=vJ(o)}},stop:!0};default:return/classes\d*\.dex/.test(e.filename)?(i={ext:"apk",mime:"application/vnd.android.package-archive"},{stop:!0}):{}}}),i??{ext:"zip",mime:"application/zip"}}if(this.checkString("OggS")){await e.ignore(28);const n=new Uint8Array(8);return await e.readBuffer(n),bJ(n,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/ogg; codecs=opus"}:bJ(n,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:bJ(n,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:bJ(n,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:bJ(n,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:bJ(n,[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 r=await this.readTiffHeader(!0);if(r)return r}if(this.checkString("MAC "))return{ext:"ape",mime:"audio/ape"};if(this.check([26,69,223,163])){async function a(){const t=await e.peekNumber(nG);let i=128,n=0;for(;0===(t&i)&&0!==i;)++n,i>>=1;const o=new Uint8Array(n+1);return await e.readBuffer(o),o}async function s(){const e=await a(),t=await a();t[0]^=128>>t.length-1;const i=Math.min(6,t.length),n=new DataView(e.buffer),o=new DataView(t.buffer,t.length-i,i);return{id:_Z(n),len:_Z(o)}}async function c(t){for(;t>0;){const i=await s();if(17026===i.id){return(await e.readToken(new lG(i.len))).replaceAll(/\00.*$/g,"")}await e.ignore(i.len),--t}}const p=await s();switch(await c(p.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 l=new lG(4,"latin1").get(this.buffer,2);if(l.match("^d*")&&l>=1e3&&l<=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 lG(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(cG),type:await e.readToken(new lG(4,"latin1"))}}await e.ignore(8);do{const d=await u();if(d.length<0)return;switch(d.type){case"IDAT":return{ext:"png",mime:"image/png"};case"acTL":return{ext:"apng",mime:"image/apng"};default:await e.ignore(d.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 f=new lG(4,"latin1").get(this.buffer,8).replace("\0"," ").trim();switch(f){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 f.startsWith("3g")?f.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 m(){const t=new Uint8Array(16);return await e.readBuffer(t),{id:t,size:Number(await e.readToken(pG))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){const h=await m();let g=h.size-24;if(bJ(h.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){const y=new Uint8Array(16);if(g-=await e.readBuffer(y),bJ(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(bJ(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(g)}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 lG(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 v=new DataView(this.buffer.buffer).getUint32(12,!0);if(v>12&&this.buffer.length>=v+16)try{const b=(new TextDecoder).decode(this.buffer.subarray(16,v+16));if(JSON.parse(b).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 i=Number.parseInt(new lG(6).get(e,148).replace(/\0.*$/,"").trim(),8);if(Number.isNaN(i))return!1;let n=256;for(let o=t;o<t+148;o++)n+=e[o];for(let o=t+156;o<t+512;o++)n+=e[o];return i===n}(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)}),F(this,"detectImprecise",async e=>{if(this.buffer=new Uint8Array(yJ),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 i of this.detectors){const n=await i.detect(e);if(n)return n;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 i,n;if((null==t?void 0:t.length)>1)return this.fromTokenizer((i=t,n=this.tokenizerOptions,new bG(i,n)))}async fromBlob(e){return this.fromStream(e.stream())}async fromStream(e){const t=await xG(e,this.tokenizerOptions);try{return await this.fromTokenizer(t)}finally{await t.close()}}async toDetectionStream(e,t){const{sampleSize:i=yJ}=t;let n,o;const r=e.getReader({mode:"byob"});try{const{value:e,done:t}=await r.read(new Uint8Array(i));if(o=e,!t&&e)try{n=await this.fromBuffer(e.subarray(0,i))}catch(c){if(!(c instanceof uG))throw c;n=void 0}o=e}finally{r.releaseLock()}const a=new TransformStream({async start(e){e.enqueue(o)},transform(e,t){t.enqueue(e)}}),s=e.pipeThrough(a);return s.fileType=n,s}check(e,t){return bJ(this.buffer,e,t)}checkString(e,t){return this.check((i=e,[...i].map(e=>e.charCodeAt(0))),t);var i}async readTiffTag(e){const t=await this.tokenizer.readToken(e?rG:oG);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?rG:oG);for(let i=0;i<t;++i){const t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){const t=(e?rG:oG).get(this.buffer,2),i=(e?sG:aG).get(this.buffer,4);if(42===t){if(i>=6){if(this.checkString("CR",{offset:8}))return{ext:"cr2",mime:"image/x-canon-cr2"};if(i>=8){const t=(e?rG:oG).get(this.buffer,8),i=(e?rG:oG).get(this.buffer,10);if(28===t&&254===i||31===t&&11===i)return{ext:"nef",mime:"image/x-nikon-nef"}}}await this.tokenizer.ignore(i);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 wJ=Object.create(null);wJ.open="0",wJ.close="1",wJ.ping="2",wJ.pong="3",wJ.message="4",wJ.upgrade="5",wJ.noop="6";const kJ=Object.create(null);Object.keys(wJ).forEach(e=>{kJ[wJ[e]]=e});const _J={type:"error",data:"parser error"},EJ="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),SJ="function"==typeof ArrayBuffer,TJ=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,AJ=({type:e,data:t},i,n)=>EJ&&t instanceof Blob?i?n(t):IJ(t,n):SJ&&(t instanceof ArrayBuffer||TJ(t))?i?n(t):IJ(new Blob([t]),n):n(wJ[e]+(t||"")),IJ=(e,t)=>{const i=new FileReader;return i.onload=function(){const e=i.result.split(",")[1];t("b"+(e||""))},i.readAsDataURL(e)};function RJ(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let OJ;const jJ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",CJ="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let hxe=0;hxe<64;hxe++)CJ[jJ.charCodeAt(hxe)]=hxe;const NJ="function"==typeof ArrayBuffer,BJ=(e,t)=>{if("string"!=typeof e)return{type:"message",data:LJ(e,t)};const i=e.charAt(0);if("b"===i)return{type:"message",data:PJ(e.substring(1),t)};return kJ[i]?e.length>1?{type:kJ[i],data:e.substring(1)}:{type:kJ[i]}:_J},PJ=(e,t)=>{if(NJ){const i=(e=>{let t,i,n,o,r,a=.75*e.length,s=e.length,c=0;"="===e[e.length-1]&&(a--,"="===e[e.length-2]&&a--);const p=new ArrayBuffer(a),l=new Uint8Array(p);for(t=0;t<s;t+=4)i=CJ[e.charCodeAt(t)],n=CJ[e.charCodeAt(t+1)],o=CJ[e.charCodeAt(t+2)],r=CJ[e.charCodeAt(t+3)],l[c++]=i<<2|n>>4,l[c++]=(15&n)<<4|o>>2,l[c++]=(3&o)<<6|63&r;return p})(e);return LJ(i,t)}return{base64:!0,data:e}},LJ=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,UJ=String.fromCharCode(30);function FJ(){return new TransformStream({transform(e,t){!function(e,t){EJ&&e.data instanceof Blob?e.data.arrayBuffer().then(RJ).then(t):SJ&&(e.data instanceof ArrayBuffer||TJ(e.data))?t(RJ(e.data)):AJ(e,!1,e=>{OJ||(OJ=new TextEncoder),t(OJ.encode(e))})}(e,i=>{const n=i.length;let o;if(n<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,n);else if(n<65536){o=new Uint8Array(3);const e=new DataView(o.buffer);e.setUint8(0,126),e.setUint16(1,n)}else{o=new Uint8Array(9);const e=new DataView(o.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(n))}e.data&&"string"!=typeof e.data&&(o[0]|=128),t.enqueue(o),t.enqueue(i)})}})}let MJ;function DJ(e){return e.reduce((e,t)=>e+t.length,0)}function zJ(e,t){if(e[0].length===t)return e.shift();const i=new Uint8Array(t);let n=0;for(let o=0;o<t;o++)i[o]=e[0][n++],n===e[0].length&&(e.shift(),n=0);return e.length&&n<e[0].length&&(e[0]=e[0].slice(n)),i}function $J(e){if(e)return function(e){for(var t in $J.prototype)e[t]=$J.prototype[t];return e}(e)}$J.prototype.on=$J.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},$J.prototype.once=function(e,t){function i(){this.off(e,i),t.apply(this,arguments)}return i.fn=t,this.on(e,i),this},$J.prototype.off=$J.prototype.removeListener=$J.prototype.removeAllListeners=$J.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var i,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var o=0;o<n.length;o++)if((i=n[o])===t||i.fn===t){n.splice(o,1);break}return 0===n.length&&delete this._callbacks["$"+e],this},$J.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),i=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(i){n=0;for(var o=(i=i.slice(0)).length;n<o;++n)i[n].apply(this,t)}return this},$J.prototype.emitReserved=$J.prototype.emit,$J.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},$J.prototype.hasListeners=function(e){return!!this.listeners(e).length};const qJ="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),KJ="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function WJ(e,...t){return t.reduce((t,i)=>(e.hasOwnProperty(i)&&(t[i]=e[i]),t),{})}const HJ=KJ.setTimeout,VJ=KJ.clearTimeout;function GJ(e,t){t.useNativeTimers?(e.setTimeoutFn=HJ.bind(KJ),e.clearTimeoutFn=VJ.bind(KJ)):(e.setTimeoutFn=KJ.setTimeout.bind(KJ),e.clearTimeoutFn=KJ.clearTimeout.bind(KJ))}function ZJ(e){return"string"==typeof e?function(e){let t=0,i=0;for(let n=0,o=e.length;n<o;n++)t=e.charCodeAt(n),t<128?i+=1:t<2048?i+=2:t<55296||t>=57344?i+=3:(n++,i+=4);return i}(e):Math.ceil(1.33*(e.byteLength||e.size))}function JJ(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class YJ extends Error{constructor(e,t,i){super(e),this.description=t,this.context=i,this.type="TransportError"}}class XJ extends $J{constructor(e){super(),this.writable=!1,GJ(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,i){return super.emitReserved("error",new YJ(e,t,i)),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=BJ(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 i in e)e.hasOwnProperty(i)&&(t.length&&(t+="&"),t+=encodeURIComponent(i)+"="+encodeURIComponent(e[i]));return t}(e);return t.length?"?"+t:""}}class QJ extends XJ{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 i=e.split(UJ),n=[];for(let o=0;o<i.length;o++){const e=BJ(i[o],t);if(n.push(e),"error"===e.type)break}return n})(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 i=e.length,n=new Array(i);let o=0;e.forEach((e,r)=>{AJ(e,!1,e=>{n[r]=e,++o===i&&t(n.join(UJ))})})})(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]=JJ()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let eY=!1;try{eY="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(fxe){}const tY=eY;function iY(){}class nY extends QJ{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let i=location.port;i||(i=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||i!==e.port}}doWrite(e,t){const i=this.request({method:"POST",data:e});i.on("success",t),i.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 oY=class e extends $J{constructor(e,t,i){super(),this.createRequest=e,GJ(this,i),this._opts=i,this._method=i.method||"GET",this._uri=t,this._data=void 0!==i.data?i.data:null,this._create()}_create(){var t;const i=WJ(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");i.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(i);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&n.setRequestHeader(e,this._opts.extraHeaders[e])}}catch(mxe){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(mxe){}try{n.setRequestHeader("Accept","*/*")}catch(mxe){}null===(t=this._opts.cookieJar)||void 0===t||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var e;3===n.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(mxe){return void this.setTimeoutFn(()=>{this._onError(mxe)},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=iY,t)try{this._xhr.abort()}catch(mxe){}"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(oY.requestsCount=0,oY.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",rY);else if("function"==typeof addEventListener){addEventListener("onpagehide"in KJ?"pagehide":"unload",rY,!1)}function rY(){for(let e in oY.requests)oY.requests.hasOwnProperty(e)&&oY.requests[e].abort()}const aY=function(){const e=sY({xdomain:!1});return e&&null!==e.responseType}();function sY(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||tY))return new XMLHttpRequest}catch(mxe){}if(!t)try{return new(KJ[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(mxe){}}const cY="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class pY extends XJ{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,i=cY?{}:WJ(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(i.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,i)}catch(fxe){return this.emitReserved("error",fxe)}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 i=e[t],n=t===e.length-1;AJ(i,this.supportsBinary,e=>{try{this.doWrite(i,e)}catch(mxe){}n&&qJ(()=>{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]=JJ()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const lY=KJ.WebSocket||KJ.MozWebSocket;const uY={websocket:class extends pY{createSocket(e,t,i){return cY?new lY(e,t,i):t?new lY(e,t):new lY(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends XJ{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(fxe){return this.emitReserved("error",fxe)}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){MJ||(MJ=new TextDecoder);const i=[];let n=0,o=-1,r=!1;return new TransformStream({transform(a,s){for(i.push(a);;){if(0===n){if(DJ(i)<1)break;const e=zJ(i,1);r=!(128&~e[0]),o=127&e[0],n=o<126?3:126===o?1:2}else if(1===n){if(DJ(i)<2)break;const e=zJ(i,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),n=3}else if(2===n){if(DJ(i)<8)break;const e=zJ(i,8),t=new DataView(e.buffer,e.byteOffset,e.length),r=t.getUint32(0);if(r>Math.pow(2,21)-1){s.enqueue(_J);break}o=r*Math.pow(2,32)+t.getUint32(4),n=3}else{if(DJ(i)<o)break;const e=zJ(i,o);s.enqueue(BJ(r?e:MJ.decode(e),t)),n=0}if(0===o||o>e){s.enqueue(_J);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=e.readable.pipeThrough(t).getReader(),n=FJ();n.readable.pipeTo(e.writable),this._writer=n.writable.getWriter();const o=()=>{i.read().then(({done:e,value:t})=>{e||(this.onPacket(t),o())}).catch(e=>{})};o();const r={type:"open"};this.query.sid&&(r.data=`{"sid":"${this.query.sid}"}`),this._writer.write(r).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const i=e[t],n=t===e.length-1;this._writer.write(i).then(()=>{n&&qJ(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends nY{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=aY&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new oY(sY,this.uri(),e)}}},dY=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,fY=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function mY(e){if(e.length>8e3)throw"URI too long";const t=e,i=e.indexOf("["),n=e.indexOf("]");-1!=i&&-1!=n&&(e=e.substring(0,i)+e.substring(i,n).replace(/:/g,";")+e.substring(n,e.length));let o=dY.exec(e||""),r={},a=14;for(;a--;)r[fY[a]]=o[a]||"";return-1!=i&&-1!=n&&(r.source=t,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=function(e,t){const i=/\/{2,9}/g,n=t.replace(i,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1);"/"==t.slice(-1)&&n.splice(n.length-1,1);return n}(0,r.path),r.queryKey=function(e,t){const i={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,n){t&&(i[t]=n)}),i}(0,r.query),r}const hY="function"==typeof addEventListener&&"function"==typeof removeEventListener,gY=[];hY&&addEventListener("offline",()=>{gY.forEach(e=>e())},!1);class yY extends $J{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 i=mY(e);t.hostname=i.host,t.secure="https"===i.protocol||"wss"===i.protocol,t.port=i.port,i.query&&(t.query=i.query)}else t.host&&(t.hostname=mY(t.host).host);GJ(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={},i=e.split("&");for(let n=0,o=i.length;n<o;n++){let e=i[n].split("=");t[decodeURIComponent(e[0])]=decodeURIComponent(e[1])}return t}(this.opts.query)),hY&&(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"})},gY.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 i=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](i)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&yY.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",yY.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 i=this.writeBuffer[t].data;if(i&&(e+=ZJ(i)),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,qJ(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,i){return this._sendPacket("message",e,t,i),this}send(e,t,i){return this._sendPacket("message",e,t,i),this}_sendPacket(e,t,i,n){if("function"==typeof t&&(n=t,t=void 0),"function"==typeof i&&(n=i,i=null),"closing"===this.readyState||"closed"===this.readyState)return;(i=i||{}).compress=!1!==i.compress;const o={type:e,data:t,options:i};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),n&&this.once("flush",n),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},i=()=>{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?i():e()}):this.upgrading?i():e()),this}_onError(e){if(yY.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(),hY&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=gY.indexOf(this._offlineEventListener);-1!==e&&gY.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}yY.protocol=4;class vY extends yY{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),i=!1;yY.priorWebsocketSuccess=!1;const n=()=>{i||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!i)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;yY.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{i||"closed"!==this.readyState&&(p(),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(){i||(i=!0,p(),t.close(),t=null)}const r=e=>{const i=new Error("probe error: "+e);i.transport=t.name,o(),this.emitReserved("upgradeError",i)};function a(){r("transport closed")}function s(){r("socket closed")}function c(e){t&&e.name!==t.name&&o()}const p=()=>{t.removeListener("open",n),t.removeListener("error",r),t.removeListener("close",a),this.off("close",s),this.off("upgrading",c)};t.once("open",n),t.once("error",r),t.once("close",a),this.once("close",s),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{i||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let i=0;i<e.length;i++)~this.transports.indexOf(e[i])&&t.push(e[i]);return t}}let bY=class extends vY{constructor(e,t={}){const i="object"==typeof e?e:t;(!i.transports||i.transports&&"string"==typeof i.transports[0])&&(i.transports=(i.transports||["polling","websocket","webtransport"]).map(e=>uY[e]).filter(e=>!!e)),super(e,i)}};const xY="function"==typeof ArrayBuffer,wY=Object.prototype.toString,kY="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===wY.call(Blob),_Y="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===wY.call(File);function EY(e){return xY&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||kY&&e instanceof Blob||_Y&&e instanceof File}function SY(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,i=e.length;t<i;t++)if(SY(e[t]))return!0;return!1}if(EY(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return SY(e.toJSON(),!0);for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)&&SY(e[i]))return!0;return!1}function TY(e){const t=[],i=e.data,n=e;return n.data=AY(i,t),n.attachments=t.length,{packet:n,buffers:t}}function AY(e,t){if(!e)return e;if(EY(e)){const i={_placeholder:!0,num:t.length};return t.push(e),i}if(Array.isArray(e)){const i=new Array(e.length);for(let n=0;n<e.length;n++)i[n]=AY(e[n],t);return i}if("object"==typeof e&&!(e instanceof Date)){const i={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(i[n]=AY(e[n],t));return i}return e}function IY(e,t){return e.data=RY(e.data,t),delete e.attachments,e}function RY(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 i=0;i<e.length;i++)e[i]=RY(e[i],t);else if("object"==typeof e)for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(e[i]=RY(e[i],t));return e}const OY=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var jY;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(jY||(jY={}));function CY(e){return"[object Object]"===Object.prototype.toString.call(e)}class NY extends $J{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 i=t.type===jY.BINARY_EVENT;i||t.type===jY.BINARY_ACK?(t.type=i?jY.EVENT:jY.ACK,this.reconstructor=new BY(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!EY(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 i={type:Number(e.charAt(0))};if(void 0===jY[i.type])throw new Error("unknown packet type "+i.type);if(i.type===jY.BINARY_EVENT||i.type===jY.BINARY_ACK){const n=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const o=e.substring(n,t);if(o!=Number(o)||"-"!==e.charAt(t))throw new Error("Illegal attachments");i.attachments=Number(o)}if("/"===e.charAt(t+1)){const n=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}i.nsp=e.substring(n,t)}else i.nsp="/";const n=e.charAt(t+1);if(""!==n&&Number(n)==n){const n=t+1;for(;++t;){const i=e.charAt(t);if(null==i||Number(i)!=i){--t;break}if(t===e.length)break}i.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){const n=this.tryParse(e.substr(t));if(!NY.isPayloadValid(i.type,n))throw new Error("invalid payload");i.data=n}return i}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(mxe){return!1}}static isPayloadValid(e,t){switch(e){case jY.CONNECT:return CY(t);case jY.DISCONNECT:return void 0===t;case jY.CONNECT_ERROR:return"string"==typeof t||CY(t);case jY.EVENT:case jY.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===OY.indexOf(t[0]));case jY.ACK:case jY.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class BY{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=IY(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const PY=Object.freeze(Object.defineProperty({__proto__:null,Decoder:NY,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==jY.EVENT&&e.type!==jY.ACK||!SY(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===jY.EVENT?jY.BINARY_EVENT:jY.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==jY.BINARY_EVENT&&e.type!==jY.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=TY(e),i=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(i),n}},get PacketType(){return jY},protocol:5},Symbol.toStringTag,{value:"Module"}));function LY(e,t,i){return e.on(t,i),function(){e.off(t,i)}}const UY=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class FY extends $J{constructor(e,t,i){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,i&&i.auth&&(this.auth=i.auth),this._opts=Object.assign({},i),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[LY(e,"open",this.onopen.bind(this)),LY(e,"packet",this.onpacket.bind(this)),LY(e,"error",this.onerror.bind(this)),LY(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 i,n,o;if(UY.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 r={type:jY.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,i=t.pop();this._registerAckCallback(e,i),r.id=e}const a=null===(n=null===(i=this.io.engine)||void 0===i?void 0:i.transport)||void 0===n?void 0:n.writable,s=this.connected&&!(null===(o=this.io.engine)||void 0===o?void 0:o._hasPingExpired());return this.flags.volatile&&!a||(s?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(e,t){var i;const n=null!==(i=this.flags.timeout)&&void 0!==i?i:this._opts.ackTimeout;if(void 0===n)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"))},n),r=(...e)=>{this.io.clearTimeoutFn(o),t.apply(this,e)};r.withError=!0,this.acks[e]=r}emitWithAck(e,...t){return new Promise((i,n)=>{const o=(e,t)=>e?n(e):i(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 i={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...n)=>{if(i!==this._queue[0])return;return null!==e?i.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...n)),i.pending=!1,this._drainQueue()}),this._queue.push(i),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:jY.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 jY.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 jY.EVENT:case jY.BINARY_EVENT:this.onevent(e);break;case jY.ACK:case jY.BINARY_ACK:this.onack(e);break;case jY.DISCONNECT:this.ondisconnect();break;case jY.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 i of t)i.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 i=!1;return function(...n){i||(i=!0,t.packet({type:jY.ACK,id:e,data:n}))}}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:jY.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 i=0;i<t.length;i++)if(e===t[i])return t.splice(i,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 i=0;i<t.length;i++)if(e===t[i])return t.splice(i,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 i of t)i.apply(this,e.data)}}}function MY(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}MY.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),i=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+i:e-i}return 0|Math.min(e,this.max)},MY.prototype.reset=function(){this.attempts=0},MY.prototype.setMin=function(e){this.ms=e},MY.prototype.setMax=function(e){this.max=e},MY.prototype.setJitter=function(e){this.jitter=e};class DY extends $J{constructor(e,t){var i;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,GJ(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!==(i=t.randomizationFactor)&&void 0!==i?i:.5),this.backoff=new MY({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const n=t.parser||PY;this.encoder=new n.Encoder,this.decoder=new n.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 bY(this.uri,this.opts);const t=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;const n=LY(t,"open",function(){i.onopen(),e&&e()}),o=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},r=LY(t,"error",o);if(!1!==this._timeout){const e=this._timeout,i=this.setTimeoutFn(()=>{n(),o(new Error("timeout")),t.close()},e);this.opts.autoUnref&&i.unref(),this.subs.push(()=>{this.clearTimeoutFn(i)})}return this.subs.push(n),this.subs.push(r),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(LY(e,"ping",this.onping.bind(this)),LY(e,"data",this.ondata.bind(this)),LY(e,"error",this.onerror.bind(this)),LY(e,"close",this.onclose.bind(this)),LY(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(mxe){this.onclose("parse error",mxe)}}ondecoded(e){qJ(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let i=this.nsps[e];return i?this._autoConnect&&!i.active&&i.connect():(i=new FY(this,e,t),this.nsps[e]=i),i}_destroy(e){const t=Object.keys(this.nsps);for(const i of t){if(this.nsps[i].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let i=0;i<t.length;i++)this.engine.write(t[i],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 i;this.cleanup(),null===(i=this.engine)||void 0===i||i.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 i=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&&i.unref(),this.subs.push(()=>{this.clearTimeoutFn(i)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const zY={};function $Y(e,t){"object"==typeof e&&(t=e,e=void 0);const i=function(e,t="",i){let n=e;i=i||"undefined"!=typeof location&&location,null==e&&(e=i.protocol+"//"+i.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?i.protocol+e:i.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==i?i.protocol+"//"+e:"https://"+e),n=mY(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const o=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+o+":"+n.port+t,n.href=n.protocol+"://"+o+(i&&i.port===n.port?"":":"+n.port),n}(e,(t=t||{}).path||"/socket.io"),n=i.source,o=i.id,r=i.path,a=zY[o]&&r in zY[o].nsps;let s;return t.forceNew||t["force new connection"]||!1===t.multiplex||a?s=new DY(n,t):(zY[o]||(zY[o]=new DY(n,t)),s=zY[o]),i.query&&!t.query&&(t.query=i.queryKey),s.socket(i.path,t)}Object.assign($Y,{Manager:DY,Socket:FY,io:$Y,connect:$Y});const qY=class e{constructor(e){if(F(this,"client"),F(this,"config"),F(this,"logger",Fi.getInstance()),F(this,"socket",null),F(this,"socketConnected",!1),F(this,"connectionMode","auto"),F(this,"wsBaseUrl",null),this.config=e,!e.apiKey)throw new Mi("API key is required");if(!e.network)throw new Mi("Network is required");const t={"x-api-key":e.apiKey,"Content-Type":"application/json"};this.client=wi.create({baseURL:"https://v2-api.tier.bot/api",headers:t}),this.logger=Fi.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 wi.get(e),i=t.headers["content-type"]||"";return{size:parseInt(t.headers["content-length"]||"0",10),mimeType:i}}catch(t){throw this.logger.error("Error fetching file metadata:",t),new Mi("Unable to fetch file metadata")}}getMimeType(t){const i=t.toLowerCase().split(".").pop();if(!i)throw new Mi("File must have an extension");const n=e.VALID_MIME_TYPES[i];if(!n)throw new Mi(`Unsupported file type: ${i}`);return n}validateRequest(t){if(this.logger.debug("Validating request:",t),!t.holderId||""===t.holderId.trim())throw this.logger.warn("holderId is missing or empty"),new Mi("holderId is required");if(!e.VALID_MODES.includes(t.mode))throw new Mi(`Invalid mode: ${t.mode}. Must be one of: ${e.VALID_MODES.join(", ")}`);if("hashinal"===t.mode&&!t.jsonFileURL&&!t.metadataObject)throw new Mi("Hashinal mode requires either jsonFileURL or metadataObject");if(t.onlyJSONCollection&&"hashinal-collection"!==t.mode)throw new Mi("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 Mi("Base64 data is required");const i=t.base64.replace(/^data:.*?;base64,/,"");if(Math.ceil(.75*i.length)>e.MAX_BASE64_SIZE)throw new Mi(`File size exceeds maximum limit of ${e.MAX_BASE64_SIZE/1024/1024}MB`);const n=t.mimeType||this.getMimeType(t.fileName);if(!this.validateMimeType(n))throw new Mi("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 Mi("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,""),i=J.from(t,"base64"),n=await async function(e,t){return new xJ(t).fromBuffer(e)}(i);return(null==n?void 0:n.mime)||"application/octet-stream"}catch(fxe){return this.logger.warn("Failed to detect MIME type from buffer"),"application/octet-stream"}}async startInscription(t){var i,n;try{this.validateRequest(t);let i=t.file.mimeType;if("url"===t.file.type){const n=await this.getFileMetadata(t.file.url);if(i=n.mimeType||i,n.size>e.MAX_URL_FILE_SIZE)throw new Mi(`File size exceeds maximum URL file limit of ${e.MAX_URL_FILE_SIZE/1024/1024}MB`)}else"base64"===t.file.type&&(i=await this.detectMimeTypeFromBase64(t.file.base64));if("image/vnd.microsoft.icon"===i&&(i=this.normalizeMimeType(i)),t.jsonFileURL){if("application/json"!==(await this.getFileMetadata(t.jsonFileURL)).mimeType)throw new Mi("JSON file must be of type application/json")}const n={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",{...n,fileURL:t.file.url}):await this.client.post("/inscriptions/start-inscription",{...n,fileBase64:t.file.base64,fileName:t.file.fileName,fileMimeType:i||this.getMimeType(t.file.fileName)}),o.data}catch(o){if(o instanceof Mi)throw o;if(wi.isAxiosError(o))throw new Error((null==(n=null==(i=o.response)?void 0:i.data)?void 0:n.message)||"Failed to start inscription");throw o}}async executeTransaction(e,t){var i,n;try{const r="mainnet"===t.network?o.Client.forMainnet():o.Client.forTestnet(),a=new Ho(t.network),s=await a.requestAccount(t.accountId),c=null==(i=null==s?void 0:s.key)?void 0:i._type,p="string"==typeof t.privateKey;let l;if(c&&p)l=(null==(n=null==c?void 0:c.toLowerCase())?void 0:n.includes("ecdsa"))?o.PrivateKey.fromStringECDSA(t.privateKey):o.PrivateKey.fromStringED25519(t.privateKey);else if(!c&&p){const e=p?Zo(t.privateKey):void 0;l="ed25519"===(null==e?void 0:e.detectedType)?o.PrivateKey.fromStringED25519(t.privateKey):o.PrivateKey.fromStringECDSA(t.privateKey)}else l=t.privateKey;r.setOperator(t.accountId,l);const u=o.TransferTransaction.fromBytes(J.from(e,"base64")),d=await u.sign(l),f=await d.execute(r),m=(await f.getReceipt(r)).status.toString();if("SUCCESS"!==m)throw new Error(`Transaction failed with status: ${m}`);return f.transactionId.toString()}catch(r){throw new Error(`Failed to execute transaction: ${r instanceof Error?r.message:"Unknown error"}`)}}async executeTransactionWithSigner(e,t){try{const i=o.TransferTransaction.fromBytes(J.from(e,"base64")),n=await i.executeWithSigner(t),r=(await n.getReceiptWithSigner(t)).status.toString();if("SUCCESS"!==r)throw new Error(`Transaction failed with status: ${r}`);return n.transactionId.toString()}catch(i){throw new Error(`Failed to execute transaction: ${i instanceof Error?i.message:"Unknown error"}`)}}async inscribeAndExecute(e,t,i,n){const o=(null==n?void 0:n.waitForCompletion)??!0,r=(null==n?void 0:n.maxWaitTime)??12e4,a=(null==n?void 0:n.checkInterval)??2e3;if(this.logger.debug("inscribeAndExecute called",{hasProgressCallback:!!i,connectionMode:this.connectionMode,wsBaseUrl:this.wsBaseUrl}),"http"!==this.connectionMode){const n="websocket"===this.connectionMode||"auto"===this.connectionMode&&await this.detectBestConnection();if(n)try{return await this.inscribeViaWebSocket(e,t,i)}catch(l){throw this.logger.error("WebSocket inscription failed, falling back to HTTP:",l),l}else this.logger.info(`Not using WebSocket: useWebSocket=${n}, wsBaseUrl=${this.wsBaseUrl}`)}else this.logger.info(`Not using WebSocket: hasCallback=${!!i}, connectionMode=${this.connectionMode}`);const s=await this.startInscription(e);if(!s.transactionBytes)throw this.logger.error("No transaction bytes returned from inscription request",s),new Error("No transaction bytes returned from inscription request");this.logger.info("executing transaction");const c=await this.executeTransaction(s.transactionBytes,t),p={jobId:s.tx_id,transactionId:c};if(o){i&&i({stage:"confirming",message:"Transaction executed, waiting for inscription to complete",progressPercent:5});const e=Math.floor(r/a),t=await this.waitForInscription(c,e,a,!0,i);return{...p,topicId:t.topic_id,status:t.status,completed:t.completed}}return p}async fetchWebSocketServers(){try{const e=await this.client.get("/inscriptions/websocket-servers"),{servers:t,recommended:i}=e.data;if(i)this.wsBaseUrl=i;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=$Y(this.wsBaseUrl,{auth:{apiKey:this.config.apiKey},transports:["websocket"],timeout:3e3});return new Promise(t=>{const i=setTimeout(()=>{e.disconnect(),t(!1)},3e3);e.on("connect",()=>{clearTimeout(i),e.disconnect(),t(!0)}),e.on("connect_error",()=>{clearTimeout(i),e.disconnect(),t(!1)})})}catch(mxe){return!1}}async inscribeViaWebSocket(e,t,i){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((n,o)=>{if(!this.socket)return o(new Error("WebSocket not connected"));let r,a,s,c;const p=()=>{var e,t,i;c&&clearTimeout(c),null==(e=this.socket)||e.off("inscription-progress",d),null==(t=this.socket)||t.off("inscription-complete",l),null==(i=this.socket)||i.off("inscription-error",u)};c=setTimeout(()=>{this.logger.error("WebSocket inscription timeout after 60 seconds",{jobId:r,transactionId:a,lastTopicId:s}),p(),n({jobId:r,transactionId:a,topicId:s,topic_id:s,status:"timeout",completed:!1})},6e4);const l=e=>{p(),n({jobId:r,transactionId:a,topicId:e.topicId||e.topic_id,topic_id:e.topicId||e.topic_id,status:"completed",completed:!0})},u=e=>{p(),o(new Error(e.error||"Inscription failed"))},d=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)&&(s=e.topicId||e.topic_id),i&&i({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||s,topic_id:e.topicId||e.topic_id||s}),p(),n({jobId:r,transactionId:a,topicId:e.topicId||e.topic_id||s,topic_id:e.topicId||e.topic_id||s,status:"completed",completed:!0}))};this.socket.on("inscription-progress",d),this.socket.on("inscription-complete",l),this.socket.on("inscription-error",u),this.socket.emit("start-inscription",{...e,network:this.config.network},async e=>{if(!e.success)return p(),o(new Error(e.error||"Inscription failed"));try{if(!e.transactionBytes)throw new Error("No transaction bytes returned from WebSocket inscription");if(a=await this.executeTransaction(e.transactionBytes,t),r=e.jobId||e.tx_id,!r)throw new Error("No job ID returned from WebSocket inscription");i&&i({stage:"confirming",message:"Transaction executed, inscribing to HCS...",progressPercent:5}),this.logger.info("Transaction executed, waiting for inscription completion...",{jobId:r,transactionId:a})}catch(n){p(),o(n)}})})}async connectWebSocket(){if(!this.socketConnected||!this.socket){if(!this.wsBaseUrl)throw new Error("WebSocket URL not configured");return new Promise((e,t)=>{this.socket=$Y(this.wsBaseUrl,{auth:{apiKey:this.config.apiKey},transports:["websocket","polling"]});const i=setTimeout(()=>{t(new Error("WebSocket connection timeout"))},1e4);this.socket.on("connect",()=>{clearTimeout(i),this.socketConnected=!0,this.logger.info("WebSocket connected"),e()}),this.socket.on("connect_error",e=>{clearTimeout(i),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 i=await this.startInscription(e);if(!i.transactionBytes)throw this.logger.error("No transaction bytes returned from inscription request",i),new Error("No transaction bytes returned from inscription request");this.logger.info("executing transaction");const n=await this.executeTransactionWithSigner(i.transactionBytes,t);return{jobId:i.tx_id,transactionId:n}}async retryWithBackoff(e,t=3,i=1e3){for(let o=0;o<t;o++)try{return await e()}catch(n){if(o===t-1)throw n;const e=i*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 Mi("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 mJ(e).authenticate()}static async createWithAuth(t){const i="client"===t.type?new hJ({...t,logger:Fi.getInstance()}):new mJ(t),{apiKey:n}=await i.authenticate();return new e({apiKey:n,network:t.network||"mainnet",wsBaseUrl:t.wsBaseUrl,connectionMode:t.connectionMode||"websocket"})}async waitForInscription(e,t=30,i=4e3,n=!1,o){var r;let a=0,s=0;const c=(i,n,r,c)=>{if(o)try{s=Math.max(s,r),o({stage:i,message:n,progressPercent:s,details:{...c,txId:e,currentAttempt:a,maxAttempts:t}})}catch(fxe){this.logger.warn(`Error in progress callback: ${fxe}`)}};for(c("confirming","Starting inscription verification",0);a<t;){c("confirming",`Verifying inscription status (attempt ${a+1}/${t})`,5,{attempt:a+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 s=5;void 0!==o.messages&&void 0!==o.maxMessages&&o.maxMessages>0?(s=Math.min(95,5+o.messages/o.maxMessages*90),o.completed&&(s=100)):"processing"===o.status?s=10:o.completed&&(s=100),c(o.completed?"completed":"confirming",o.completed?"Inscription completed successfully":`Processing inscription (${o.status})`,s,{status:o.status,messagesProcessed:o.messages,maxMessages:o.maxMessages,messageCount:o.messages,completed:o.completed,confirmedMessages:o.confirmedMessages,result:o});const p="hashinal"===o.mode,l="6"===(null==(r=o.fileStandard)?void 0:r.toString());if(p&&o.topic_id&&o.jsonTopicId&&(!n||o.completed))return c("completed","Inscription verification complete",100,{result:o}),o;if(!p&&!l&&o.topic_id&&(!n||o.completed))return c("completed","Inscription verification complete",100,{result:o}),o;if(l&&o.topic_id&&o.jsonTopicId&&o.registryTopicId&&(!n||o.completed))return c("completed","Inscription verification complete",100,{result:o}),o;await new Promise(e=>setTimeout(e,i)),a++}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,i;if(!e.holderId)throw new Mi("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(n){if(this.logger.error("Failed to fetch holder inscriptions:",n),wi.isAxiosError(n))throw new Error((null==(i=null==(t=n.response)?void 0:t.data)?void 0:i.message)||"Failed to fetch holder inscriptions");throw n}}};F(qY,"VALID_MODES",["file","upload","hashinal","hashinal-collection"]),F(qY,"MAX_BASE64_SIZE",2097152),F(qY,"MAX_URL_FILE_SIZE",104857600),F(qY,"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 KY=qY;class WY{constructor(e={}){this.module=e.module||"Progress",this.callback=e.callback,this.logger=e.logger||new y({level:"info",module:"ProgressReporter"}),this.logProgress=e.logProgress??!0,this.minPercent=e.minPercent??0,this.maxPercent=e.maxPercent??100,this.lastReportedPercent=-1,this.lastReportedTime=0,this.throttleMs=100}static getInstance(e={}){return WY.instance?(e.callback&&WY.instance.setCallback(e.callback),e.module&&WY.instance.setModule(e.module),e.logger&&WY.instance.setLogger(e.logger),void 0!==e.minPercent&&WY.instance.setMinPercent(e.minPercent),void 0!==e.maxPercent&&WY.instance.setMaxPercent(e.maxPercent)):WY.instance=new WY(e),WY.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 WY({module:this.module,logger:this.logger,logProgress:this.logProgress,minPercent:e.minPercent,maxPercent:e.maxPercent}),i=e.logPrefix||"";return t.setCallback(t=>{const n=this.scalePercent(t.progressPercent,e.minPercent,e.maxPercent);let o=t.message;i&&!o.startsWith(i)&&(o=`${i}: ${o}`),this.report({stage:t.stage,message:o,progressPercent:n,details:t.details})}),t}report(e){const t=e.progressPercent,i=Math.max(0,Math.min(100,t)),n=this.scalePercent(i,0,100),o=Date.now();if(n===this.lastReportedPercent&&o-this.lastReportedTime<this.throttleMs&&"completed"!==e.stage&&"failed"!==e.stage)return;this.lastReportedPercent=n,this.lastReportedTime=o;const r={...e,progressPercent:n};if(this.logProgress&&this.logger.debug(`[${this.module}] [${e.stage.toUpperCase()}] ${e.message} (${n.toFixed(1)}%)`,e.details),this.callback)try{this.callback(r)}catch(fxe){this.logger.warn(`Error in progress callback: ${fxe}`)}}scalePercent(e,t,i){const n=(this.maxPercent-this.minPercent)/(i-t);return this.minPercent+(e-t)*n}preparing(e,t,i){this.report({stage:"preparing",message:e,progressPercent:t,details:i})}submitting(e,t,i){this.report({stage:"submitting",message:e,progressPercent:t,details:i})}confirming(e,t,i){this.report({stage:"confirming",message:e,progressPercent:t,details:i})}verifying(e,t,i){this.report({stage:"verifying",message:e,progressPercent:t,details:i})}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 HY extends Error{constructor(e,t="PARSING_FAILED",i,n){super(e),this.name="TransactionParsingError",this.code=t,this.originalError=i,this.transactionBytes=n,Error.captureStackTrace&&Error.captureStackTrace(this,HY)}}const VY=(e,t)=>e.replace(/\{([^}]+)\}/g,(e,i)=>{const n=((e,t)=>{const i=t.split(".");let n=e;for(const o of i){if(null==n)return;n=n[o]}return n})(t,String(i).trim());return null==n?"(Unknown)":String(n)}),GY=e=>{const t=[],i=[];if(Array.isArray(e.transfers))for(const n of e.transfers){const e=parseFloat(n.amount);let o=n.amount;o.startsWith("-")&&(o=o.substring(1)),o=o.replace(/\s*ℏ$/,""),e<0?t.push(`${n.accountId} (${o} ℏ)`):e>0&&i.push(`${n.accountId} (${o} ℏ)`)}return t.length>0&&i.length>0?`Transfer of HBAR from ${t.join(", ")} to ${i.join(", ")}`:e.humanReadableType},ZY=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},JY=e=>e.tokenMint?`Mint ${e.tokenMint.amount} tokens for token ${e.tokenMint.tokenId}`:e.humanReadableType,YY=e=>e.tokenBurn?`Burn ${e.tokenBurn.amount} tokens for token ${e.tokenBurn.tokenId}`:e.humanReadableType,XY=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},QY=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},eX=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},tX=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},iX=e=>e.fileAppend?`Append to File ${e.fileAppend.fileId||"(Unknown ID)"}`:e.humanReadableType,nX=e=>e.fileUpdate?`Update File ${e.fileUpdate.fileId||"(Unknown ID)"}`:e.humanReadableType,oX=e=>e.fileDelete?`Delete File ${e.fileDelete.fileId||"(Unknown ID)"}`:e.humanReadableType,rX=e=>e.consensusUpdateTopic?`Update Topic ${e.consensusUpdateTopic.topicId||"(Unknown ID)"}`:e.humanReadableType,aX=e=>e.consensusDeleteTopic?`Delete Topic ${e.consensusDeleteTopic.topicId||"(Unknown ID)"}`:e.humanReadableType,sX=e=>e.tokenFreeze?`Freeze Token ${e.tokenFreeze.tokenId} for Account ${e.tokenFreeze.accountId}`:e.humanReadableType,cX=e=>e.tokenUnfreeze?`Unfreeze Token ${e.tokenUnfreeze.tokenId} for Account ${e.tokenUnfreeze.accountId}`:e.humanReadableType,pX=e=>e.tokenGrantKyc?`Grant KYC for Token ${e.tokenGrantKyc.tokenId} to Account ${e.tokenGrantKyc.accountId}`:e.humanReadableType,lX=e=>e.tokenRevokeKyc?`Revoke KYC for Token ${e.tokenRevokeKyc.tokenId} from Account ${e.tokenRevokeKyc.accountId}`:e.humanReadableType,uX=e=>e.tokenPause?`Pause Token ${e.tokenPause.tokenId}`:e.humanReadableType,dX=e=>e.tokenUnpause?`Unpause Token ${e.tokenUnpause.tokenId}`:e.humanReadableType,fX=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},mX=e=>e.tokenDelete?`Delete Token ${e.tokenDelete.tokenId}`:e.humanReadableType,hX=e=>e.tokenAssociate?`Associate Account ${e.tokenAssociate.accountId} with Tokens: ${(e.tokenAssociate.tokenIds||[]).join(", ")}`:e.humanReadableType,gX=e=>e.tokenDissociate?`Dissociate Account ${e.tokenDissociate.accountId} from Tokens: ${(e.tokenDissociate.tokenIds||[]).join(", ")}`:e.humanReadableType,yX=e=>e.cryptoDelete?`Delete Account ${e.cryptoDelete.deleteAccountId}`:e.humanReadableType,vX=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},bX=e=>e.cryptoUpdateAccount?`Update Account ${e.cryptoUpdateAccount.accountIdToUpdate||"(Unknown ID)"}`:e.humanReadableType,xX=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},wX=e=>{if(e.cryptoDeleteAllowance){return`Delete ${(e.cryptoDeleteAllowance.nftAllowancesToRemove||[]).length} NFT Crypto Allowance(s)`}return e.humanReadableType},kX=e=>{if(e.contractCreate){let t="Create Contract";return e.contractCreate.memo&&(t+=` (Memo: ${e.contractCreate.memo})`),t}return e.humanReadableType},_X=e=>e.contractUpdate?`Update Contract ${e.contractUpdate.contractIdToUpdate||"(Unknown ID)"}`:e.humanReadableType,EX=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},SX=e=>e.tokenUpdate?`Update Token ${e.tokenUpdate.tokenId||"(Unknown ID)"}`:e.humanReadableType,TX=e=>e.tokenFeeScheduleUpdate?`Update Fee Schedule for Token ${e.tokenFeeScheduleUpdate.tokenId||"(Unknown ID)"}`:e.humanReadableType,AX=e=>{if(!e.tokenAirdrop||!e.tokenAirdrop.tokenTransfers)return e.humanReadableType;let t=0,i=0;for(const n of e.tokenAirdrop.tokenTransfers)t+=1,i+=Array.isArray(n.transfers)?n.transfers.length:0;return`Token Airdrop across ${t} token(s), ${i} transfer(s)`},IX=e=>{if(!e.scheduleCreate)return e.humanReadableType;let t="Create Schedule";return e.scheduleCreate.memo&&(t+=` (Memo: ${e.scheduleCreate.memo})`),t},RX=e=>e.scheduleSign?"Sign Schedule":e.humanReadableType,OX=e=>e.scheduleDelete?"Delete Schedule":e.humanReadableType,jX=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,CX=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,NX=e=>"Network Freeze",BX=e=>"Ethereum Transaction",PX=e=>e.uncheckedSubmit&&e.uncheckedSubmit.topicId?`Unchecked Submit to topic ${e.uncheckedSubmit.topicId}`:"Unchecked Submit",LX=e=>"Create Node",UX=e=>"Update Node",FX=e=>"Delete Node",MX=e=>`Atomic Batch (${Array.isArray(e.atomicBatch?.transactions)?e.atomicBatch.transactions.length:0} transaction(s))`,DX={CRYPTOTRANSFER:{fn:GY},cryptoTransfer:{fn:GY},CONTRACTCALL:{fn:ZY},contractCall:{fn:ZY},TOKENMINT:{fn:JY},tokenMint:{fn:JY},TOKENBURN:{fn:YY},tokenBurn:{fn:YY},TOKENCREATE:{fn:XY},tokenCreation:{fn:XY},TOPICCREATE:{fn:QY},consensusCreateTopic:{fn:QY},CONSENSUSSUBMITMESSAGE:{fn:eX},consensusSubmitMessage:{fn:eX},TOPICUPDATE:{fn:rX},consensusUpdateTopic:{fn:rX},TOPICDELETE:{fn:aX},consensusDeleteTopic:{fn:aX},FILECREATE:{fn:tX},fileCreate:{fn:tX},FILEAPPEND:{fn:iX},fileAppend:{fn:iX},FILEUPDATE:{fn:nX},fileUpdate:{fn:nX},FILEDELETE:{fn:oX},fileDelete:{fn:oX},TOKENUPDATE:{fn:SX},tokenUpdate:{fn:SX},TOKENFEESCHEDULEUPDATE:{fn:TX},tokenFeeScheduleUpdate:{fn:TX},TOKENFREEZE:{fn:sX},tokenFreeze:{fn:sX},TOKENUNFREEZE:{fn:cX},tokenUnfreeze:{fn:cX},TOKENGRANTKYC:{fn:pX},tokenGrantKyc:{fn:pX},TOKENREVOKEKYC:{fn:lX},tokenRevokeKyc:{fn:lX},TOKENPAUSE:{fn:uX},tokenPause:{fn:uX},TOKENUNPAUSE:{fn:dX},tokenUnpause:{fn:dX},TOKENWIPE:{fn:fX},TOKENWIPEACCOUNT:{fn:fX},tokenWipe:{fn:fX},tokenWipeAccount:{fn:fX},TOKENDELETE:{fn:mX},tokenDelete:{fn:mX},TOKENASSOCIATE:{fn:hX},tokenAssociate:{fn:hX},TOKENDISSOCIATE:{fn:gX},tokenDissociate:{fn:gX},ACCOUNTDELETE:{fn:yX},cryptoDelete:{fn:yX},ACCOUNTCREATE:{fn:vX},cryptoCreateAccount:{fn:vX},ACCOUNTUPDATE:{fn:bX},cryptoUpdateAccount:{fn:bX},APPROVEALLOWANCE:{fn:xX},cryptoApproveAllowance:{fn:xX},DELETEALLOWANCE:{fn:wX},cryptoDeleteAllowance:{fn:wX},CONTRACTCREATE:{fn:kX},contractCreate:{fn:kX},CONTRACTUPDATE:{fn:_X},contractUpdate:{fn:_X},CONTRACTDELETE:{fn:EX},contractDelete:{fn:EX},TOKENAIRDROP:{fn:AX},tokenAirdrop:{fn:AX},SCHEDULECREATE:{fn:IX},scheduleCreate:{fn:IX},SCHEDULESIGN:{fn:RX},scheduleSign:{fn:RX},SCHEDULEDELETE:{fn:OX},scheduleDelete:{fn:OX},SYSTEMDELETE:{fn:jX},systemDelete:{fn:jX},SYSTEMUNDELETE:{fn:CX},systemUndelete:{fn:CX},FREEZE:{fn:NX},freeze:{fn:NX},ETHEREUMTRANSACTION:{fn:BX},ethereumTransaction:{fn:BX},UNCHECKEDSUBMIT:{fn:PX},uncheckedSubmit:{fn:PX},NODECREATE:{fn:LX},nodeCreate:{fn:LX},NODEUPDATE:{fn:UX},nodeUpdate:{fn:UX},NODEDELETE:{fn:FX},nodeDelete:{fn:FX},ATOMICBATCH:{fn:MX},atomicBatch:{fn:MX}},zX=e=>{const t=DX[e.type];if(t){if(t.fn)return t.fn(e);if(t.template)return VY(t.template,e)}const i=DX[e.humanReadableType];if(i){if(i.fn)return i.fn(e);if(i.template)return VY(i.template,e)}return"cryptoTransfer"===e.type||"CRYPTOTRANSFER"===e.type?GY(e):e.contractCall?ZY(e):Array.isArray(e.tokenTransfers)&&e.tokenTransfers.length>0?(e=>{const t=[],i=(e=>{const t={};for(const i of e)t[i.tokenId]||(t[i.tokenId]=[]),t[i.tokenId].push(i);return t})(e.tokenTransfers||[]);for(const[n,o]of Object.entries(i)){const e=[],i=[];for(const t of o){const n=parseFloat(String(t.amount));n<0?e.push(`${t.accountId} (${Math.abs(n)})`):n>0&&i.push(`${t.accountId} (${n})`)}e.length>0&&i.length>0&&t.push(`Transfer of token ${n} from ${e.join(", ")} to ${i.join(", ")}`)}return t.length>0?t.join("; "):e.humanReadableType})(e):e.humanReadableType&&"Unknown Transaction"!==e.humanReadableType?e.humanReadableType:"Unknown Transaction"};function $X(e){if(e){if(e.contractID)return`ContractID: ${new o.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()}`;if(e.ed25519)return`ED25519: ${s.Buffer.from(e.ed25519).toString("hex")}`;if(e.ECDSASecp256k1)return`ECDSA_secp256k1: ${s.Buffer.from(e.ECDSASecp256k1).toString("hex")}`;if(e?.keyList?.keys?.length>0){const t=e.keyList.keys.map(e=>$X(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=>$X(e)).filter(Boolean);return`ThresholdKey (${e.thresholdKey.threshold} of ${t.length}): [${t.join(", ")}]`}return e.delegatableContractId?`DelegatableContractID: ${new o.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 qX(e){try{const t=e.toBytes?e.toBytes():void 0;if(!t)return null;const i=a.proto.TransactionList.decode(t);if(!i.transactionList||0===i.transactionList.length)return null;const n=i.transactionList[0];if(n.bodyBytes&&n.bodyBytes.length>0)return a.proto.TransactionBody.decode(n.bodyBytes);if(n.signedTransactionBytes&&n.signedTransactionBytes.length>0){const e=a.proto.SignedTransaction.decode(n.signedTransactionBytes);if(e.bodyBytes)return a.proto.TransactionBody.decode(e.bodyBytes)}return null}catch(t){return null}}function KX(e,t){const i=qX(e);return!(!i||!i[t])}class WX{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 i=this.parseTokenAirdrop(e);return i?{type:"TOKENAIRDROP",humanReadableType:"Token Airdrop",tokenAirdrop:i}:{}}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 o.AccountId(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),e.initialSupply&&(t.initialSupply=o.Long.fromValue(e.initialSupply).toString()),void 0!==e.decimals&&null!==e.decimals&&(t.decimals=o.Long.fromValue(e.decimals).toNumber()),e.maxSupply&&(t.maxSupply=o.Long.fromValue(e.maxSupply).toString()),e.memo&&(t.memo=e.memo),null!==e.tokenType&&void 0!==e.tokenType&&(t.tokenType=a.proto.TokenType[e.tokenType]),null!==e.supplyType&&void 0!==e.supplyType&&(t.supplyType=a.proto.TokenSupplyType[e.supplyType]),t.adminKey=$X(e.adminKey),t.kycKey=$X(e.kycKey),t.freezeKey=$X(e.freezeKey),t.wipeKey=$X(e.wipeKey),t.supplyKey=$X(e.supplyKey),t.feeScheduleKey=$X(e.feeScheduleKey),t.pauseKey=$X(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccount=new o.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=o.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.customFees&&e.customFees.length>0&&(t.customFees=e.customFees.map(e=>{const t={feeCollectorAccountId:e.feeCollectorAccountId?new o.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:o.Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new o.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:o.Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:o.Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:o.Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:o.Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let i;return e.royaltyFee.fallbackFee&&(i={amount:o.Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new o.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:o.Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:o.Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:i}}}return{...t,feeType:"FIXED_FEE",fixedFee:{amount:"0"}}})),t}static parseTokenMint(e){if(!e||!e.token||null===e.amount||void 0===e.amount)return;const t={tokenId:new o.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:o.Long.fromValue(e.amount).toNumber()};return e.metadata&&e.metadata.length>0&&(t.metadata=e.metadata.map(e=>s.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 o.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:o.Long.fromValue(e.amount).toNumber()};return e.serialNumbers&&e.serialNumbers.length>0&&(t.serialNumbers=e.serialNumbers.map(e=>o.Long.fromValue(e).toNumber())),t}static parseTokenUpdate(e){if(!e)return;const t={};return e.token&&(t.tokenId=new o.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 o.AccountId(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),t.adminKey=$X(e.adminKey),t.kycKey=$X(e.kycKey),t.freezeKey=$X(e.freezeKey),t.wipeKey=$X(e.wipeKey),t.supplyKey=$X(e.supplyKey),t.feeScheduleKey=$X(e.feeScheduleKey),t.pauseKey=$X(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccountId=new o.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=o.Long.fromValue(e.autoRenewPeriod.seconds).toString()),void 0!==e.memo?.value&&(t.memo=e.memo.value),e.expiry?.seconds&&(t.expiry=`${o.Long.fromValue(e.expiry.seconds).toString()}.${e.expiry.nanos}`),t}static parseTokenFeeScheduleUpdate(e){if(!e)return;const t={};return e.tokenId&&(t.tokenId=new o.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 o.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:o.Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new o.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:o.Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:o.Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:o.Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:o.Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let i;return e.royaltyFee.fallbackFee&&(i={amount:o.Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new o.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:o.Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:o.Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:i}}}return{...t,feeType:"FIXED_FEE",fixedFee:{amount:"0"}}})),t}static parseTokenFreeze(e){if(!e)return;const t={};return e.token&&(t.tokenId=new o.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new o.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 o.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new o.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 o.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new o.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 o.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new o.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 o.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 o.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 o.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new o.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=>o.Long.fromValue(e).toString())),e.amount&&(t.amount=o.Long.fromValue(e.amount).toString()),t}static parseTokenDelete(e){if(!e)return;const t={};return e.token&&(t.tokenId=new o.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 o.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 o.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 o.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 o.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(KX(e,"tokenAirdrop")){const t=qX(e);if(t?.tokenAirdrop)return this.parseTokenAirdropFromProto(t.tokenAirdrop)}const i=e._tokenTransfers||[];return i.length>0?{tokenTransfers:i.map(e=>({tokenId:e.tokenId?.toString()||"Unknown",transfers:(e.transfers||[]).map(e=>({accountId:e.accountId?.toString()||"Unknown",amount:e.amount?.toString()||"0",serialNumbers:e.serialNumbers?.map(e=>e.toString())}))}))}:null}catch(t){return console.warn("[HTSParser] Failed to parse token airdrop:",t),null}}static parseTokenAirdropFromProto(e){const t=[];if(e.tokenTransfers)for(const i of e.tokenTransfers){const e=i.token?new o.TokenId(i.token.shardNum??0,i.token.realmNum??0,i.token.tokenNum??0):null,n=[];if(i.transfers)for(const t of i.transfers){const e=t.accountID?new o.AccountId(t.accountID.shardNum??0,t.accountID.realmNum??0,t.accountID.accountNum??0):null;n.push({accountId:e?.toString()||"Unknown",amount:t.amount?o.Long.fromValue(t.amount).toString():"0",serialNumbers:t.serialNumbers?.map(e=>o.Long.fromValue(e).toString())})}t.push({tokenId:e?.toString()||"Unknown",transfers:n})}return{tokenTransfers:t}}static extractTokenCreationFromTransaction(e){try{const t=e;if(t._tokenName||t._tokenSymbol){const e={tokenName:t._tokenName||"Unknown Token",tokenSymbol:t._tokenSymbol||"UNKNOWN",initialSupply:t._initialSupply?.toString()||"0",decimals:Number(t._decimals||0),treasuryAccountId:t._treasuryAccountId?.toString()||"Unknown"};return t._maxSupply&&(e.maxSupply=t._maxSupply.toString()),t._tokenType&&(e.tokenType=t._tokenType.toString?t._tokenType.toString():String(t._tokenType)),t._supplyType&&(e.supplyType=t._supplyType.toString?t._supplyType.toString():String(t._supplyType)),t._tokenMemo&&(e.memo=t._tokenMemo),t._adminKey&&(e.adminKey=t._adminKey.toString()),t._kycKey&&(e.kycKey=t._kycKey.toString()),t._freezeKey&&(e.freezeKey=t._freezeKey.toString()),t._wipeKey&&(e.wipeKey=t._wipeKey.toString()),t._supplyKey&&(e.supplyKey=t._supplyKey.toString()),t._feeScheduleKey&&(e.feeScheduleKey=t._feeScheduleKey.toString()),t._pauseKey&&(e.pauseKey=t._pauseKey.toString()),t._metadataKey&&(e.metadataKey=t._metadataKey.toString()),t._autoRenewAccountId&&(e.autoRenewAccount=t._autoRenewAccountId.toString()),t._autoRenewPeriod&&(e.autoRenewPeriod=t._autoRenewPeriod.seconds?.toString()||t._autoRenewPeriod.toString()),t._expirationTime&&(e.expiry=t._expirationTime.seconds?.toString()||t._expirationTime.toString()),t._customFees&&Array.isArray(t._customFees)&&t._customFees.length>0&&(e.customFees=t._customFees.map(e=>{const t={feeCollectorAccountId:e.feeCollectorAccountId?.toString()||"",feeType:"FIXED_FEE"};return e.fixedFee?(t.feeType="FIXED_FEE",t.fixedFee={amount:e.fixedFee.amount?.toString()||"0",denominatingTokenId:e.fixedFee.denominatingTokenId?.toString()}):e.fractionalFee?(t.feeType="FRACTIONAL_FEE",t.fractionalFee={numerator:e.fractionalFee.numerator?.toString()||"0",denominator:e.fractionalFee.denominator?.toString()||"1",minimumAmount:e.fractionalFee.minimumAmount?.toString()||"0",maximumAmount:e.fractionalFee.maximumAmount?.toString()||"0",netOfTransfers:e.fractionalFee.netOfTransfers||!1}):e.royaltyFee&&(t.feeType="ROYALTY_FEE",t.royaltyFee={numerator:e.royaltyFee.numerator?.toString()||"0",denominator:e.royaltyFee.denominator?.toString()||"1",fallbackFee:e.royaltyFee.fallbackFee?{amount:e.royaltyFee.fallbackFee.amount?.toString()||"0",denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?.toString()}:void 0}),t.allCollectorsAreExempt=e.allCollectorsAreExempt||!1,t})),e}return null}catch(t){return null}}static extractTokenAirdropFromTransaction(e){try{const t=e;if(t._tokenAirdrops&&Array.isArray(t._tokenAirdrops)){return{tokenTransfers:t._tokenAirdrops.map(e=>({tokenId:e.tokenId?.toString()||"Unknown",transfers:(e.transfers||[]).map(e=>({accountId:e.accountId?.toString()||"Unknown",amount:e.amount?.toString()||"0",serialNumbers:e.serialNumbers?.map(e=>e.toString())||[]}))}))}}return null}catch(t){return null}}static parseFromTransactionObject(e){try{try{const t=e.toBytes?e.toBytes():void 0;if(t){const e=a.proto.TransactionList.decode(t);if(e.transactionList&&e.transactionList.length>0){const t=e.transactionList[0];let i=null;if(t.bodyBytes&&t.bodyBytes.length>0)i=a.proto.TransactionBody.decode(t.bodyBytes);else if(t.signedTransactionBytes&&t.signedTransactionBytes.length>0){const e=a.proto.SignedTransaction.decode(t.signedTransactionBytes);e.bodyBytes&&(i=a.proto.TransactionBody.decode(e.bodyBytes))}if(i){if(i.tokenCreation){const e=this.parseTokenCreate(i.tokenCreation);if(e)return{type:"TOKENCREATE",humanReadableType:"Token Creation",tokenCreation:e}}if(i.tokenMint){const e=this.parseTokenMint(i.tokenMint);if(e)return{type:"TOKENMINT",humanReadableType:"Token Mint",tokenMint:e}}if(i.tokenBurn){const e=this.parseTokenBurn(i.tokenBurn);if(e)return{type:"TOKENBURN",humanReadableType:"Token Burn",tokenBurn:e}}if(i.tokenUpdate){const e=this.parseTokenUpdate(i.tokenUpdate);if(e)return{type:"TOKENUPDATE",humanReadableType:"Token Update",tokenUpdate:e}}if(i.tokenFreeze){const e=this.parseTokenFreeze(i.tokenFreeze);if(e)return{type:"TOKENFREEZE",humanReadableType:"Token Freeze",tokenFreeze:e}}if(i.tokenUnfreeze){const e=this.parseTokenUnfreeze(i.tokenUnfreeze);if(e)return{type:"TOKENUNFREEZE",humanReadableType:"Token Unfreeze",tokenUnfreeze:e}}if(i.tokenGrantKyc){const e=this.parseTokenGrantKyc(i.tokenGrantKyc);if(e)return{type:"TOKENGRANTKYC",humanReadableType:"Token Grant KYC",tokenGrantKyc:e}}if(i.tokenRevokeKyc){const e=this.parseTokenRevokeKyc(i.tokenRevokeKyc);if(e)return{type:"TOKENREVOKEKYC",humanReadableType:"Token Revoke KYC",tokenRevokeKyc:e}}if(i.tokenPause){const e=this.parseTokenPause(i.tokenPause);if(e)return{type:"TOKENPAUSE",humanReadableType:"Token Pause",tokenPause:e}}if(i.tokenUnpause){const e=this.parseTokenUnpause(i.tokenUnpause);if(e)return{type:"TOKENUNPAUSE",humanReadableType:"Token Unpause",tokenUnpause:e}}if(i.tokenWipe){const e=this.parseTokenWipeAccount(i.tokenWipe);if(e)return{type:"TOKENWIPEACCOUNT",humanReadableType:"Token Wipe Account",tokenWipeAccount:e}}if(i.tokenDeletion){const e=this.parseTokenDelete(i.tokenDeletion);if(e)return{type:"TOKENDELETE",humanReadableType:"Token Delete",tokenDelete:e}}if(i.tokenAssociate){const e=this.parseTokenAssociate(i.tokenAssociate);if(e)return{type:"TOKENASSOCIATE",humanReadableType:"Token Associate",tokenAssociate:e}}if(i.tokenDissociate){const e=this.parseTokenDissociate(i.tokenDissociate);if(e)return{type:"TOKENDISSOCIATE",humanReadableType:"Token Dissociate",tokenDissociate:e}}if(i.tokenFeeScheduleUpdate){const e=this.parseTokenFeeScheduleUpdate(i.tokenFeeScheduleUpdate);if(e)return{type:"TOKENFEESCHEDULEUPDATE",humanReadableType:"Token Fee Schedule Update",tokenFeeScheduleUpdate:e}}if(i.tokenAirdrop){const e=this.parseTokenAirdropFromProto(i.tokenAirdrop);if(e)return{type:"TOKENAIRDROP",humanReadableType:"Token Airdrop",tokenAirdrop:e}}}}}}catch(mxe){}const t=this.parseHTSTransaction(e);if(t.type)return t;const i=this.extractTokenCreationFromTransaction(e),n=this.extractTokenAirdropFromTransaction(e);return i?{type:"TOKENCREATE",humanReadableType:"Token Creation",tokenCreation:i}:n?{type:"TOKENAIRDROP",humanReadableType:"Token Airdrop",tokenAirdrop:n}:{}}catch(t){return{}}}}class HX{static parseConsensusCreateTopic(e){if(!e)return;const t={};return e.memo&&(t.memo=e.memo),t.adminKey=$X(e.adminKey),t.submitKey=$X(e.submitKey),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=o.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new o.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 i=s.Buffer.from(e.message),n=i.toString("utf8");/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(n)||n.includes("�")?(t.message=i.toString("base64"),t.messageEncoding="base64"):(t.message=n,t.messageEncoding="utf8")}if(e.chunkInfo){if(e.chunkInfo.initialTransactionID){const i=e.chunkInfo.initialTransactionID.accountID,n=e.chunkInfo.initialTransactionID.transactionValidStart;i&&n&&(t.chunkInfoInitialTransactionID=`${i.shardNum??0}.${i.realmNum??0}.${i.accountNum??0}@${n.seconds??0}.${n.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=$X(e.adminKey):t.adminKey=void 0,null===e.submitKey?(t.clearSubmitKey=!0,t.submitKey=void 0):e.submitKey?t.submitKey=$X(e.submitKey):t.submitKey=void 0,e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=o.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new o.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 VX{static parseFileTransaction(e,t){try{if(t||e.toBytes)try{const i=t||e.toBytes(),n=a.proto.TransactionList.decode(i);if(n.transactionList&&n.transactionList.length>0){const e=n.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=a.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const i=a.proto.SignedTransaction.decode(e.signedTransactionBytes);i.bodyBytes&&(t=a.proto.TransactionBody.decode(i.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(i){}return this.parseFromTransactionInternals(e)}catch(n){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(KX(e,"fileCreate")){const e={};if(t._contents){const i=this.analyzeContent(t._contents);e.contents=i.encoded,i.contentType&&(e.contentType=i.contentType),i.size&&(e.contentSize=i.size)}if(t._keys&&t._keys.length>0){const i={keys:t._keys};e.keys=$X({keyList:i})}return t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),t._memo&&(e.memo=t._memo),{type:"FILECREATE",humanReadableType:"File Create",fileCreate:e}}if(KX(e,"fileAppend")){const e={fileId:t._fileId.toString()};if(t._contents){const i=this.analyzeContent(t._contents);e.contents=i.encoded,i.size&&(e.contentSize=i.size)}return{type:"FILEAPPEND",humanReadableType:"File Append",fileAppend:e}}if(KX(e,"fileUpdate")){const e={fileId:t._fileId.toString()};if(t._contents){const i=this.analyzeContent(t._contents);e.contents=i.encoded,i.size&&(e.contentSize=i.size)}if(t._keys&&t._keys.length>0){const i={keys:t._keys};e.keys=$X({keyList:i})}return t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),t._memo&&(e.memo=t._memo),{type:"FILEUPDATE",humanReadableType:"File Update",fileUpdate:e}}if(KX(e,"fileDelete")){return{type:"FILEDELETE",humanReadableType:"File Delete",fileDelete:{fileId:t._fileId.toString()}}}return{}}catch(t){return{}}}static analyzeContent(e){const t=e.length,i=s.Buffer.from(e);let n,o;if(t>=4){n={"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"}[i.subarray(0,4).toString("hex").toLowerCase()]}if(!n)try{const e=i.toString("utf8"),t=/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(e),o=e.includes("�");n=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{n="application/octet-stream"}if(n?.startsWith("text/")||"application/json"===n)try{o=i.toString("utf8"),(o.includes("�")||/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(o))&&(o=i.toString("base64"))}catch{o=i.toString("base64")}else o=i.toString("base64");return{encoded:o,contentType:n,size:t}}static parseFileCreate(e){if(!e)return;const t={};return e.expirationTime?.seconds&&(t.expirationTime=`${o.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=$X({keyList:e.keys})),e.contents&&(t.contents=s.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=s.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=`${o.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=$X({keyList:e.keys})),e.contents&&(t.contents=s.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 GX{static parseCryptoTransfers(e,t){if(e.transfers?.accountAmounts&&(t.transfers=e.transfers.accountAmounts.map(e=>{const t=new o.AccountId(e.accountID.shardNum??0,e.accountID.realmNum??0,e.accountID.accountNum??0),i=o.Hbar.fromTinybars(o.Long.fromValue(e.amount));return{accountId:t.toString(),amount:i.toString(o.HbarUnit.Hbar),isDecimal:!0}})),e.tokenTransfers)for(const i of e.tokenTransfers){const e=new o.TokenId(i.token.shardNum??0,i.token.realmNum??0,i.token.tokenNum??0);if(i.transfers)for(const n of i.transfers){const i=new o.AccountId(n.accountID.shardNum??0,n.accountID.realmNum??0,n.accountID.accountNum??0),r=o.Long.fromValue(n.amount).toNumber();t.tokenTransfers.push({tokenId:e.toString(),accountId:i.toString(),amount:r})}}}static parseCryptoDelete(e){if(!e)return;const t={};return e.deleteAccountID&&(t.deleteAccountId=new o.AccountId(e.deleteAccountID.shardNum??0,e.deleteAccountID.realmNum??0,e.deleteAccountID.accountNum??0).toString()),e.transferAccountID&&(t.transferAccountId=new o.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=o.Hbar.fromTinybars(o.Long.fromValue(e.initialBalance)).toString(o.HbarUnit.Hbar)),e.key&&(t.key=$X(e.key)),void 0!==e.receiverSigRequired&&(t.receiverSigRequired=e.receiverSigRequired),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=o.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 o.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=o.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 o.AccountId(e.accountIDToUpdate.shardNum??0,e.accountIDToUpdate.realmNum??0,e.accountIDToUpdate.accountNum??0).toString()),e.key&&(t.key=$X(e.key)),e.expirationTime?.seconds&&(t.expirationTime=`${o.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=o.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 o.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=o.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 o.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new o.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount:o.Hbar.fromTinybars(o.Long.fromValue(e.amount)).toString(o.HbarUnit.Hbar)}))),e.tokenAllowances&&e.tokenAllowances.length>0&&(t.tokenAllowances=e.tokenAllowances.map(e=>({tokenId:new o.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),ownerAccountId:new o.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new o.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount:o.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 o.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString()),e.owner&&(t.ownerAccountId=new o.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString()),e.spender&&(t.spenderAccountId=new o.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=>o.Long.fromValue(e).toString())),void 0!==e.approvedForAll?.value&&(t.approvedForAll=e.approvedForAll.value),e.delegatingSpender&&(t.delegatingSpender=new o.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 o.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),tokenId:new o.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),serialNumbers:e.serialNumbers?e.serialNumbers.map(e=>o.Long.fromValue(e).toString()):[]}))),t}static extractHbarTransfersFromTransaction(e){const t=[];try{const i=e._hbarTransfers;Array.isArray(i)&&i.forEach(e=>{if(e.accountId&&e.amount){const i=e.amount.toTinybars(),n=Number(i)/1e8;t.push({accountId:e.accountId.toString(),amount:n})}})}catch(i){}return t}static extractTokenTransfersFromTransaction(e){const t=[];try{const i=e._tokenTransfers;Array.isArray(i)&&i.forEach(e=>{if(e.tokenId&&Array.isArray(e.transfers)){const i=e.transfers.map(e=>({accountId:e.accountId?.toString()||"Unknown",amount:Number(e.amount||0)}));t.push({tokenId:e.tokenId.toString(),transfers:i})}})}catch(i){}return t}static parseFromTransactionObject(e){try{const t=this.extractHbarTransfersFromTransaction(e),i=this.extractTokenTransfersFromTransaction(e);if(t.length>0||i.length>0){const e=t.map(e=>({accountId:e.accountId,amount:e.amount.toString()+" ℏ",isDecimal:!0})),n=i.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:n};if(i.length>0)return{type:"TOKENTRANSFER",humanReadableType:"Token Transfer",transfers:e,tokenTransfers:n}}return{}}catch(t){return{}}}}class ZX{static parseSCSTransaction(e,t){try{if(t||e.toBytes)try{const i=t||e.toBytes(),n=a.proto.TransactionList.decode(i);if(n.transactionList&&n.transactionList.length>0){const e=n.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=a.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const i=a.proto.SignedTransaction.decode(e.signedTransactionBytes);i.bodyBytes&&(t=a.proto.TransactionBody.decode(i.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(i){}return this.parseFromTransactionInternals(e)}catch(n){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:o.Long.fromValue(t._gas).toNumber(),amount:t._amount?parseFloat(t._amount.toString()):0};if(t._functionParameters){const i=s.Buffer.from(t._functionParameters).toString("hex");e.functionParameters=i,e.functionName=this.extractFunctionName(i)}return{type:"CONTRACTCALL",humanReadableType:"Contract Call",contractCall:e}}if(KX(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=s.Buffer.from(t._bytecode).toString("hex")),t._constructorParameters&&(e.constructorParameters=s.Buffer.from(t._constructorParameters).toString("hex")),t._memo&&(e.memo=t._memo),t._adminKey&&(e.adminKey=$X(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=o.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(KX(e,"contractUpdateInstance")){const e={contractIdToUpdate:t._contractId.toString()};return t._memo&&(e.memo=t._memo),t._adminKey&&(e.adminKey=$X(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=o.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(KX(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?o.Long.fromValue(e.maxGasAllowance).toNumber():0,amount:0};if(e.ethereumData&&e.ethereumData.length>0){const i=s.Buffer.from(e.ethereumData).toString("hex");t.functionParameters=i,i.length>=8&&(t.functionName=this.extractFunctionName(i))}return t}static parseContractCall(e){if(!e)return;const t=o.Hbar.fromTinybars(o.Long.fromValue(e.amount??0)),i={contractId:new o.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString(),gas:o.Long.fromValue(e.gas??0).toNumber(),amount:parseFloat(t.toString(o.HbarUnit.Hbar))};return e.functionParameters&&(i.functionParameters=s.Buffer.from(e.functionParameters).toString("hex"),i.functionParameters.length>=8&&(i.functionName=this.extractFunctionName(i.functionParameters))),i}static parseContractCreate(e){if(!e)return;const t={};return e.initialBalance&&(t.initialBalance=o.Hbar.fromTinybars(o.Long.fromValue(e.initialBalance)).toString(o.HbarUnit.Hbar)),e.gas&&(t.gas=o.Long.fromValue(e.gas).toString()),e.adminKey&&(t.adminKey=$X(e.adminKey)),e.constructorParameters&&(t.constructorParameters=s.Buffer.from(e.constructorParameters).toString("hex")),e.memo&&(t.memo=e.memo),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=o.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.stakedAccountId?t.stakedAccountId=new o.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=o.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 o.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=s.Buffer.from(e.initcode).toString("hex")),t}static parseContractUpdate(e){if(!e)return;const t={};if(e.contractID&&(t.contractIdToUpdate=new o.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.adminKey&&(t.adminKey=$X(e.adminKey)),e.expirationTime?.seconds&&(t.expirationTime=`${o.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=o.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.memo){const i=e.memo;if(i&&"object"==typeof i&&Object.prototype.hasOwnProperty.call(i,"value")){const e=i.value;t.memo=null==e?void 0:String(e)}else t.memo="string"==typeof i?i:void 0}else t.memo=void 0;return e.stakedAccountId?(t.stakedAccountId=new o.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&&o.Long.fromValue(e.stakedNodeId).notEquals(-1)?(t.stakedNodeId=o.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 o.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 o.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.transferAccountID?t.transferAccountId=new o.AccountId(e.transferAccountID.shardNum??0,e.transferAccountID.realmNum??0,e.transferAccountID.accountNum??0).toString():e.transferContractID&&(t.transferContractId=new o.ContractId(e.transferContractID.shardNum??0,e.transferContractID.realmNum??0,e.transferContractID.contractNum??0).toString()),t}static parseFromTransactionObject(e){return this.parseSCSTransaction(e)}}class JX{static parseUtilTransaction(e,t){try{if(t||e.toBytes)try{const i=t||e.toBytes(),n=a.proto.TransactionList.decode(i);if(n.transactionList&&n.transactionList.length>0){const e=n.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=a.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const i=a.proto.SignedTransaction.decode(e.signedTransactionBytes);i.bodyBytes&&(t=a.proto.TransactionBody.decode(i.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(i){}return this.parseFromTransactionInternals(e)}catch(n){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(KX(e,"utilPrng")){const e={};return t._range&&0!==t._range&&(e.range=t._range),{type:"PRNG",humanReadableType:"Pseudo Random Number",utilPrng:e}}if(KX(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(KX(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(KX(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=`${o.Long.fromValue(e.startTime.seconds).toString()}.${e.startTime.nanos??0}`),e.updateFile&&(t.updateFile=new o.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 i=["FREEZE_ONLY","PREPARE_UPGRADE","FREEZE_UPGRADE","FREEZE_ABORT"];t.freezeType=i[e.freezeType]||"FREEZE_ONLY"}return t}static parseSystemDeleteFromProto(e){if(!e)return;const t={};return e.fileID?t.fileId=new o.FileId(e.fileID.shardNum??0,e.fileID.realmNum??0,e.fileID.fileNum??0).toString():e.contractID&&(t.contractId=new o.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.expirationTime?.seconds&&(t.expirationTime=o.Long.fromValue(e.expirationTime.seconds).toString()),t}static parseSystemUndeleteFromProto(e){if(!e)return;const t={};return e.fileID?t.fileId=new o.FileId(e.fileID.shardNum??0,e.fileID.realmNum??0,e.fileID.fileNum??0).toString():e.contractID&&(t.contractId=new o.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=o.Long.fromValue(e.nodeId).toNumber()),t}static parseNodeUpdateFromProto(e){if(!e)return;const t={};return void 0!==e.nodeId&&(t.nodeId=o.Long.fromValue(e.nodeId).toNumber()),t}static parseNodeDeleteFromProto(e){if(!e)return;const t={};return void 0!==e.nodeId&&(t.nodeId=o.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 YX{static parseScheduleTransaction(e,t){try{if(t||e.toBytes)try{const i=t||e.toBytes(),n=a.proto.TransactionList.decode(i);if(n.transactionList&&n.transactionList.length>0){const e=n.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=a.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const i=a.proto.SignedTransaction.decode(e.signedTransactionBytes);i.bodyBytes&&(t=a.proto.TransactionBody.decode(i.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(i){}return this.parseFromTransactionInternals(e)}catch(n){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(KX(e,"scheduleCreate")){return{type:"SCHEDULECREATE",humanReadableType:"Schedule Create",scheduleCreate:{scheduledTransactionBody:globalThis.Buffer.from(t._scheduledTransaction).toString("base64"),memo:t._scheduleMemo,adminKey:t._adminKey?$X(t._adminKey):void 0,payerAccountId:t._payerAccountId?.toString(),expirationTime:t._expirationTime?.toString(),waitForExpiry:t._waitForExpiry||!1}}}if(KX(e,"scheduleSign")){return{type:"SCHEDULESIGN",humanReadableType:"Schedule Sign",scheduleSign:{scheduleId:t._scheduleId.toString()}}}if(KX(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 i=a.proto.SchedulableTransactionBody.encode(a.proto.SchedulableTransactionBody.create(e.scheduledTransactionBody)).finish();t.scheduledTransactionBody=globalThis.Buffer.from(i).toString("base64")}return e.memo&&(t.memo=e.memo),e.adminKey&&(t.adminKey=$X(e.adminKey)),e.payerAccountID&&(t.payerAccountId=new o.AccountId(e.payerAccountID.shardNum??0,e.payerAccountID.realmNum??0,e.payerAccountID.accountNum??0).toString()),e.expirationTime?.seconds&&(t.expirationTime=`${o.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 o.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 o.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 i=e;return i._scheduleId||i.scheduleId?{isScheduled:!0,scheduleRef:(i._scheduleId||i.scheduleId)?.toString()}:{isScheduled:!1}}catch(t){return{isScheduled:!1}}}static parseScheduledTransactionBody(e){try{let t;if(e.startsWith("0x")){const i=e.slice(2);t=new Uint8Array(globalThis.Buffer.from(i,"hex"))}else t=new Uint8Array(globalThis.Buffer.from(e,"base64"));const i=a.proto.SchedulableTransactionBody.decode(t),n=Object.keys(i).find(e=>null!==i[e]&&"transactionFee"!==e&&"memo"!==e);return n?{type:n.toUpperCase(),body:i[n],memo:i.memo,transactionFee:i.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 XX={TOKENCREATE:{bodyField:"tokenCreation",parser:WX.parseTokenCreate,resultField:"tokenCreation"},TOKENMINT:{bodyField:"tokenMint",parser:WX.parseTokenMint,resultField:"tokenMint"},TOKENBURN:{bodyField:"tokenBurn",parser:WX.parseTokenBurn,resultField:"tokenBurn"},TOKENUPDATE:{bodyField:"tokenUpdate",parser:WX.parseTokenUpdate,resultField:"tokenUpdate"},TOKENDELETE:{bodyField:"tokenDeletion",parser:WX.parseTokenDelete,resultField:"tokenDelete"},TOKENASSOCIATE:{bodyField:"tokenAssociate",parser:WX.parseTokenAssociate,resultField:"tokenAssociate"},TOKENDISSOCIATE:{bodyField:"tokenDissociate",parser:WX.parseTokenDissociate,resultField:"tokenDissociate"},TOKENFREEZE:{bodyField:"tokenFreeze",parser:WX.parseTokenFreeze,resultField:"tokenFreeze"},TOKENUNFREEZE:{bodyField:"tokenUnfreeze",parser:WX.parseTokenUnfreeze,resultField:"tokenUnfreeze"},TOKENGRANTKYC:{bodyField:"tokenGrantKyc",parser:WX.parseTokenGrantKyc,resultField:"tokenGrantKyc"},TOKENREVOKEKYC:{bodyField:"tokenRevokeKyc",parser:WX.parseTokenRevokeKyc,resultField:"tokenRevokeKyc"},TOKENPAUSE:{bodyField:"tokenPause",parser:WX.parseTokenPause,resultField:"tokenPause"},TOKENUNPAUSE:{bodyField:"tokenUnpause",parser:WX.parseTokenUnpause,resultField:"tokenUnpause"},TOKENWIPEACCOUNT:{bodyField:"tokenWipe",parser:WX.parseTokenWipeAccount,resultField:"tokenWipeAccount"},TOKENFEESCHEDULEUPDATE:{bodyField:"tokenFeeScheduleUpdate",parser:WX.parseTokenFeeScheduleUpdate,resultField:"tokenFeeScheduleUpdate"},TOKENAIRDROP:{bodyField:"tokenAirdrop",parser:WX.parseTokenAirdropFromProto,resultField:"tokenAirdrop"},TOPICCREATE:{bodyField:"consensusCreateTopic",parser:HX.parseConsensusCreateTopic,resultField:"consensusCreateTopic"},CONSENSUSSUBMITMESSAGE:{bodyField:"consensusSubmitMessage",parser:HX.parseConsensusSubmitMessage,resultField:"consensusSubmitMessage"},TOPICUPDATE:{bodyField:"consensusUpdateTopic",parser:HX.parseConsensusUpdateTopic,resultField:"consensusUpdateTopic"},TOPICDELETE:{bodyField:"consensusDeleteTopic",parser:HX.parseConsensusDeleteTopic,resultField:"consensusDeleteTopic"},ACCOUNTCREATE:{bodyField:"cryptoCreateAccount",parser:GX.parseCryptoCreateAccount,resultField:"cryptoCreateAccount"},ACCOUNTUPDATE:{bodyField:"cryptoUpdateAccount",parser:GX.parseCryptoUpdateAccount,resultField:"cryptoUpdateAccount"},ACCOUNTDELETE:{bodyField:"cryptoDelete",parser:GX.parseCryptoDelete,resultField:"cryptoDelete"},CRYPTOTRANSFER:{bodyField:"cryptoTransfer",parser:e=>{const t={transfers:[],tokenTransfers:[]};return GX.parseCryptoTransfers(e,t),t},resultField:"transfers",spreadResult:!0},APPROVEALLOWANCE:{bodyField:"cryptoApproveAllowance",parser:GX.parseCryptoApproveAllowance,resultField:"cryptoApproveAllowance"},DELETEALLOWANCE:{bodyField:"cryptoDeleteAllowance",parser:GX.parseCryptoDeleteAllowance,resultField:"cryptoDeleteAllowance"},FILECREATE:{bodyField:"fileCreate",parser:VX.parseFileCreate,resultField:"fileCreate"},FILEUPDATE:{bodyField:"fileUpdate",parser:VX.parseFileUpdate,resultField:"fileUpdate"},FILEDELETE:{bodyField:"fileDelete",parser:VX.parseFileDelete,resultField:"fileDelete"},FILEAPPEND:{bodyField:"fileAppend",parser:VX.parseFileAppend,resultField:"fileAppend"},CONTRACTCREATE:{bodyField:"contractCreateInstance",parser:ZX.parseContractCreate,resultField:"contractCreate"},CONTRACTUPDATE:{bodyField:"contractUpdateInstance",parser:ZX.parseContractUpdate,resultField:"contractUpdate"},CONTRACTDELETE:{bodyField:"contractDeleteInstance",parser:ZX.parseContractDelete,resultField:"contractDelete"},CONTRACTCALL:{bodyField:"contractCall",parser:ZX.parseContractCall,resultField:"contractCall"},ETHEREUMTRANSACTION:{bodyField:"ethereumTransaction",parser:ZX.parseEthereumTransaction,resultField:"ethereumTransaction"},SCHEDULECREATE:{bodyField:"scheduleCreate",parser:YX.parseScheduleCreateFromProto,resultField:"scheduleCreate"},SCHEDULESIGN:{bodyField:"scheduleSign",parser:YX.parseScheduleSignFromProto,resultField:"scheduleSign"},SCHEDULEDELETE:{bodyField:"scheduleDelete",parser:YX.parseScheduleDeleteFromProto,resultField:"scheduleDelete"},PRNG:{bodyField:"utilPrng",parser:JX.parseUtilPrng,resultField:"utilPrng"},FREEZE:{bodyField:"freeze",parser:JX.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:WX.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 QX={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"}},eQ={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"},tQ={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 iQ(e){for(const[t,i]of Object.entries(QX))if(e[t])return i;return{type:"UNKNOWN",humanReadableType:"Unknown Transaction"}}function nQ(e){return eQ[e]||"Unknown Transaction"}class oQ{static async parseTransactionBytes(e,t={}){const{enableFallback:i=!0,strictMode:n=!1,includeRaw:o=!0,maxRetries:r=2}=t,a=this.validateTransactionBytes(e);if(!a.isValid&&n)throw new HY(`Invalid transaction bytes format: ${a.error}`,"INVALID_FORMAT",void 0,e);let s,c=0;for(;c<=r;)try{const i=await this.parseTransaction(e,t);return i.formatDetection={originalFormat:a.format||"base64",wasConverted:"hex"===a.format,length:e.length},i}catch(l){if(s=l instanceof Error?l:new Error(String(l)),c++,!i||c>r){if(n)throw new HY("Failed to parse transaction after all attempts","PARSING_FAILED",s,e);break}try{const i=this.parseScheduledTransaction(e,t);return i.formatDetection={originalFormat:a.format||"base64",wasConverted:!1,length:e.length},i}catch(u){}}const p=this.createFallbackResult(e,s,void 0);return p.details&&(p.details.parseAttempts=Math.max(c,1)),p}static parseTransactionObject(e,t,i={}){let n,o;!t||s.Buffer.isBuffer(t)||t instanceof Uint8Array?(n=t,o=i):(o=t,n=void 0);try{const t=this.extractTransactionMetadata(e),i=WX.parseFromTransactionObject(e),s=GX.parseFromTransactionObject(e),c=HX.parseFromTransactionObject(e),p=VX.parseFromTransactionObject(e),l=ZX.parseFromTransactionObject(e),u=YX.parseFromTransactionObject(e),d=JX.parseFromTransactionObject(e),f=[i,s,c,p,l,u,d].find(e=>e.type&&"UNKNOWN"!==e.type)||{};let m,h="UNKNOWN",g="Unknown Transaction",y={};if(n||e.toBytes)try{const t=n||e.toBytes(),i=a.proto.TransactionList.decode(t);if(i.transactionList&&i.transactionList.length>0){const e=i.transactionList[0];if(e.bodyBytes&&e.bodyBytes.length>0){const t=a.proto.TransactionBody.decode(e.bodyBytes),i=this.detectTransactionTypeFromBody(t);h=i.type,g=i.humanReadableType,y=this.parseTransactionBodyDetails(t,h),y.tokenCreation&&(m=y.tokenCreation)}else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const t=a.proto.SignedTransaction.decode(e.signedTransactionBytes);if(t.bodyBytes){const e=a.proto.TransactionBody.decode(t.bodyBytes),i=this.detectTransactionTypeFromBody(e);h=i.type,g=i.humanReadableType,y=this.parseTransactionBodyDetails(e,h),y.tokenCreation&&(m=y.tokenCreation)}}}}catch(r){}"UNKNOWN"===h&&f.type&&(h=f.type,g=f.humanReadableType||g);const v={type:h,humanReadableType:g,transfers:[],tokenTransfers:[],...t,...f,raw:o.includeRaw?e._transactionBody||{}:void 0};return this.mergeProtoParsingResults(v,y,i,e,n),v.transfers=s.transfers||v.transfers||[],v.tokenTransfers=s.tokenTransfers||v.tokenTransfers||[],v}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),i=a.proto.SchedulableTransactionBody.decode(t),n=this.getTransactionType(i),r={type:n,humanReadableType:this.getHumanReadableType(n),transfers:[],tokenTransfers:[],raw:i};if(i.memo&&(r.memo=i.memo),i.transactionFee){const e=o.Hbar.fromTinybars(o.Long.fromValue(i.transactionFee));r.transactionFee=e.toString(o.HbarUnit.Hbar)}return this.applySchedulableTransactionParsing(i,r),r}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 iQ(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 iQ(e).type}static getHumanReadableType(e){return nQ(e)}static getTransactionSummary(e){return zX(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),i=/^[A-Za-z0-9+/]*={0,2}$/;let n,o=!1;return"hex"===t?(o=/^0x[0-9a-fA-F]+$/.test(e)&&e.length>2,o||(n="Invalid hex format")):(o=i.test(e)&&e.length>0,o||(n="Invalid base64 format")),{isValid:o,format:t,error:n,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(s.Buffer.from(t,"hex"))}return new Uint8Array(s.Buffer.from(e,"base64"))}catch(t){throw new HY("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 o.Transaction.fromBytes(t),!0}catch{return!1}}static decodeBytesLegacy(e){return this.decodeTransactionBytes(e)}static async parseTransaction(e,t={}){try{const i=this.decodeTransactionBytes(e),n=o.Transaction.fromBytes(i),r=this.extractTransactionMetadataEnhanced(n),a=this.runAllParsers(n),s=a.find(e=>e.type&&"UNKNOWN"!==e.type)||{},c=this.parseFromProtobuf(i),p=c.type||s.type||"UNKNOWN",l={type:p,humanReadableType:c.humanReadableType||s.humanReadableType||"Unknown Transaction",transfers:[],tokenTransfers:[],details:{...r},memo:"string"==typeof r.memo?r.memo:void 0,transactionId:"string"==typeof r.transactionId?r.transactionId:void 0,nodeAccountIds:Array.isArray(r.nodeAccountIds)?r.nodeAccountIds:[],maxTransactionFee:"string"==typeof r.maxTransactionFee?r.maxTransactionFee:void 0,validStart:"string"==typeof r.validStart?r.validStart:void 0,validDuration:"string"==typeof r.validDuration?r.validDuration:void 0,raw:t.includeRaw?{}:void 0};return this.mergeAllResults(l,c,s,a),l}catch(i){throw new HY("Failed to parse as regular transaction","REGULAR_PARSING_FAILED",i instanceof Error?i:void 0,e)}}static parseScheduledTransaction(e,t={}){try{const t=this.parseTransactionBody(e),i=this.validateTransactionBytes(e);return{...t,details:{...t.details||{},parseMethod:"scheduled",validation:i,parseAttempts:t.details?.parseAttempts||1},formatDetection:{originalFormat:i.format||"base64",wasConverted:!1,length:e.length}}}catch(i){throw new HY("Failed to parse as scheduled transaction","SCHEDULED_PARSING_FAILED",i instanceof Error?i: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[WX.parseFromTransactionObject(e),GX.parseFromTransactionObject(e),HX.parseFromTransactionObject(e),VX.parseFromTransactionObject(e),ZX.parseFromTransactionObject(e),YX.parseFromTransactionObject(e),JX.parseFromTransactionObject(e)]}static parseFromProtobuf(e){const t={};try{const i=a.proto.TransactionList.decode(e);if(i.transactionList&&i.transactionList.length>0){const e=i.transactionList[0];let n=null;if(e.bodyBytes&&e.bodyBytes.length>0)n=a.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const t=a.proto.SignedTransaction.decode(e.signedTransactionBytes);t.bodyBytes&&(n=a.proto.TransactionBody.decode(t.bodyBytes))}if(n){const e=this.detectTransactionTypeFromBody(n);t.type=e.type,t.humanReadableType=e.humanReadableType;const i=this.parseTransactionBodyDetails(n,e.type);Object.assign(t,i)}}}catch(i){}return t}static mergeAllResults(e,t,i,n){const o=n.find(e=>e.transfers||e.tokenTransfers)||{};e.transfers=o.transfers||e.transfers||[],e.tokenTransfers=o.tokenTransfers||e.tokenTransfers||[],Object.keys(t).forEach(i=>{void 0!==t[i]&&"type"!==i&&"humanReadableType"!==i&&(e[i]=t[i])}),Object.keys(i).forEach(t=>{void 0===i[t]||t in e||"type"===t||"humanReadableType"===t||(e[t]=i[t])})}static applySchedulableTransactionParsing(e,t){e.cryptoTransfer&&GX.parseCryptoTransfers(e.cryptoTransfer,t),e.cryptoDelete&&(t.cryptoDelete=GX.parseCryptoDelete(e.cryptoDelete)),e.cryptoCreateAccount&&(t.cryptoCreateAccount=GX.parseCryptoCreateAccount(e.cryptoCreateAccount)),e.cryptoUpdateAccount&&(t.cryptoUpdateAccount=GX.parseCryptoUpdateAccount(e.cryptoUpdateAccount)),e.cryptoApproveAllowance&&(t.cryptoApproveAllowance=GX.parseCryptoApproveAllowance(e.cryptoApproveAllowance)),e.cryptoDeleteAllowance&&(t.cryptoDeleteAllowance=GX.parseCryptoDeleteAllowance(e.cryptoDeleteAllowance)),e.contractCall&&(t.contractCall=ZX.parseContractCall(e.contractCall)),e.contractCreateInstance&&(t.contractCreate=ZX.parseContractCreate(e.contractCreateInstance)),e.contractUpdateInstance&&(t.contractUpdate=ZX.parseContractUpdate(e.contractUpdateInstance)),e.contractDeleteInstance&&(t.contractDelete=ZX.parseContractDelete(e.contractDeleteInstance)),e.tokenCreation&&(t.tokenCreation=WX.parseTokenCreate(e.tokenCreation)),e.tokenMint&&(t.tokenMint=WX.parseTokenMint(e.tokenMint)),e.tokenBurn&&(t.tokenBurn=WX.parseTokenBurn(e.tokenBurn)),e.tokenUpdate&&(t.tokenUpdate=WX.parseTokenUpdate(e.tokenUpdate)),e.tokenFeeScheduleUpdate&&(t.tokenFeeScheduleUpdate=WX.parseTokenFeeScheduleUpdate(e.tokenFeeScheduleUpdate)),e.tokenFreeze&&(t.tokenFreeze=WX.parseTokenFreeze(e.tokenFreeze)),e.tokenUnfreeze&&(t.tokenUnfreeze=WX.parseTokenUnfreeze(e.tokenUnfreeze)),e.tokenGrantKyc&&(t.tokenGrantKyc=WX.parseTokenGrantKyc(e.tokenGrantKyc)),e.tokenRevokeKyc&&(t.tokenRevokeKyc=WX.parseTokenRevokeKyc(e.tokenRevokeKyc)),e.tokenPause&&(t.tokenPause=WX.parseTokenPause(e.tokenPause)),e.tokenUnpause&&(t.tokenUnpause=WX.parseTokenUnpause(e.tokenUnpause)),e.tokenWipe&&(t.tokenWipeAccount=WX.parseTokenWipeAccount(e.tokenWipe)),e.tokenDeletion&&(t.tokenDelete=WX.parseTokenDelete(e.tokenDeletion)),e.tokenAssociate&&(t.tokenAssociate=WX.parseTokenAssociate(e.tokenAssociate)),e.tokenDissociate&&(t.tokenDissociate=WX.parseTokenDissociate(e.tokenDissociate)),e.tokenAirdrop&&(t.tokenAirdrop=WX.parseTokenAirdropFromProto(e.tokenAirdrop)),e.consensusCreateTopic&&(t.consensusCreateTopic=HX.parseConsensusCreateTopic(e.consensusCreateTopic)),e.consensusSubmitMessage&&(t.consensusSubmitMessage=HX.parseConsensusSubmitMessage(e.consensusSubmitMessage)),e.consensusUpdateTopic&&(t.consensusUpdateTopic=HX.parseConsensusUpdateTopic(e.consensusUpdateTopic)),e.consensusDeleteTopic&&(t.consensusDeleteTopic=HX.parseConsensusDeleteTopic(e.consensusDeleteTopic)),e.fileCreate&&(t.fileCreate=VX.parseFileCreate(e.fileCreate)),e.fileAppend&&(t.fileAppend=VX.parseFileAppend(e.fileAppend)),e.fileUpdate&&(t.fileUpdate=VX.parseFileUpdate(e.fileUpdate)),e.fileDelete&&(t.fileDelete=VX.parseFileDelete(e.fileDelete)),e.utilPrng&&(t.utilPrng=JX.parseUtilPrng(e.utilPrng))}static parseTransactionBodyDetails(e,t){const i={},n=XX[t];if(n){const t=e[n.bodyField];if(t){const e=n.parser(t);n.spreadResult?Object.assign(i,e):i[n.resultField]=e}}return i}static mergeProtoParsingResults(e,t,i,n,o){const r=Object.values(XX).map(e=>e.resultField);for(const a of r){const o=t[a],r=i[a];void 0!==o?e[a]=o:void 0!==r?e[a]=r:this.handleSpecialFieldExtraction(e,a,n)}}static handleSpecialFieldExtraction(e,t,i){if("tokenCreation"===t&&"TOKENCREATE"===e.type){const n=WX.extractTokenCreationFromTransaction(i);n&&(e[t]=n)}else if("tokenAirdrop"===t&&"TOKENAIRDROP"===e.type){const n=WX.extractTokenAirdropFromTransaction(i);n&&(e[t]=n)}}static createFallbackResult(e,t,i){const n=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:i?.message,parseAttempts:i?2:1,validation:n},formatDetection:{originalFormat:n.format||"base64",wasConverted:!1,length:e.length},raw:{}}}}const rQ="undefined"!=typeof window&&void 0!==window.document;const aQ=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,i){return{inputHash:this.hashObject(e),clientConfigHash:this.hashObject({accountId:t.accountId,network:t.network}),optionsHash:this.hashObject({mode:i.mode,apiKey:i.apiKey?"present":"absent",network:i.network,metadata:i.metadata})}}get(e){const t=this.generateKey(e),i=this.cache.get(t);if(!i)return null;return Date.now()-i.timestamp>i.ttlMs?(this.cache.delete(t),null):(this.cache.delete(t),this.cache.set(t,i),i.quote)}set(e,t,i=this.defaultTtlMs){const n=this.generateKey(e);if(this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}this.cache.set(n,{quote:t,timestamp:Date.now(),ttlMs:i})}clear(){this.cache.clear()}},sQ=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),i=this.cache.get(t);if(!i)return null;return Date.now()-i.timestamp>this.defaultTtlMs?(this.cache.delete(t),null):i.sdk}set(e,t){const i=this.generateConfigKey(e);if(this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}this.cache.set(i,{sdk:t,timestamp:Date.now(),config:i})}clear(){this.cache.clear()}};let cQ={};async function pQ(e){if(rQ)throw new Error("File path operations are not supported in browser environment. Use buffer input type instead.");if(await async function(){if(!rQ&&!cQ.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"),i=t("path");cQ.readFileSync=e.readFileSync,cQ.basename=i.basename,cQ.extname=i.extname}}catch(e){console.warn("Node.js modules not available, file path operations will be disabled")}}(),!cQ.readFileSync||!cQ.basename||!cQ.extname)throw new Error("Node.js file system modules are not available. Cannot read file from path.");try{const i=cQ.readFileSync(e),n=i.toString("base64"),o=cQ.basename(e);let r="application/octet-stream";try{const e=await p.fileTypeFromBuffer(i);e&&(r=e.mime)}catch(t){const i=cQ.extname(e).toLowerCase();r={".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"}[i]||"application/octet-stream"}return{base64:n,fileName:o,mimeType:r}}catch(t){throw new Error(`Failed to read file ${e}: ${t.message}`)}}async function lQ(e,t,i,n){const o=y.getInstance({module:"Inscriber",...i.logging});o.info("Starting inscription process",{type:e.type,mode:i.mode||"file",quoteOnly:i.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(i.quoteOnly)return o.debug("Quote-only mode requested, generating quote"),await mQ(e,t,i,n);let r;"hashinal"===i.mode&&i.metadata&&fQ(i.metadata,o),n?(o.debug("Using existing InscriptionSDK instance"),r=n):i.apiKey?(o.debug("Initializing InscriptionSDK with API key"),r=new KY({apiKey:i.apiKey,network:t.network||"mainnet"})):(o.debug("Initializing InscriptionSDK with server auth"),r=await KY.createWithAuth({type:"server",accountId:t.accountId,privateKey:t.privateKey,network:t.network||"mainnet"}));const a={holderId:t.accountId,metadata:i.metadata||{},tags:i.tags||[],mode:i.mode||"file",fileStandard:i.fileStandard,chunkSize:i.chunkSize};let s;switch(e.type){case"url":s={...a,file:{type:"url",url:e.url}};break;case"file":{const t=await pQ(e.path);s={...a,file:{type:"base64",base64:t.base64,fileName:t.fileName,mimeType:t.mimeType}};break}case"buffer":s={...a,file:{type:"base64",base64:globalThis.Buffer.from(e.buffer).toString("base64"),fileName:e.fileName,mimeType:e.mimeType}}}"hashinal"===i.mode&&(s.metadataObject=i.metadata,s.creator=i.metadata?.creator||t.accountId,s.description=i.metadata?.description,i.jsonFileURL&&(s.jsonFileURL=i.jsonFileURL)),o.debug("Preparing to inscribe content",{type:e.type,mode:i.mode||"file",holderId:t.accountId});const c=await r.inscribeAndExecute(s,t);if(o.info("Starting to inscribe.",{type:e.type,mode:i.mode||"file",transactionId:c.jobId}),i.waitForConfirmation){o.debug("Waiting for inscription confirmation",{transactionId:c.jobId,maxAttempts:i.waitMaxAttempts,intervalMs:i.waitIntervalMs});const e=await hQ(r,c.jobId,i.waitMaxAttempts,i.waitIntervalMs,i.progressCallback);return o.info("Inscription confirmation received",{transactionId:c.jobId}),{confirmed:!0,result:c,inscription:e,sdk:r}}return{confirmed:!1,result:c,sdk:r}}catch(r){throw o.error("Error during inscription process",r),r}}async function uQ(e,t,i,n){const o=y.getInstance({module:"Inscriber",...i.logging});o.info("Starting inscription process with signer",{type:e.type,mode:i.mode||"file",quoteOnly:i.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(i.quoteOnly){o.debug("Quote-only mode requested with signer, generating quote");const r={accountId:t.getAccountId().toString(),privateKey:"",network:i.network||"mainnet"};return await mQ(e,r,i,n)}"hashinal"===i.mode&&i.metadata&&fQ(i.metadata,o);const r=t.getAccountId().toString();let a;o.debug("Using account ID from signer",{accountId:r}),n?(o.debug("Using existing InscriptionSDK instance"),a=n):i.apiKey?(o.debug("Initializing InscriptionSDK with API key"),a=new KY({apiKey:i.apiKey,network:i.network||"mainnet",connectionMode:"websocket"})):(o.debug("Initializing InscriptionSDK with client auth (websocket)"),a=await KY.createWithAuth({type:"client",accountId:r,signer:t,network:i.network||"mainnet",connectionMode:"websocket"}));const s={holderId:r,metadata:i.metadata||{},tags:i.tags||[],mode:i.mode||"file",fileStandard:i.fileStandard,chunkSize:i.chunkSize};let c;switch(e.type){case"url":c={...s,file:{type:"url",url:e.url}};break;case"file":{const t=await pQ(e.path);c={...s,file:{type:"base64",base64:t.base64,fileName:t.fileName,mimeType:t.mimeType}};break}case"buffer":c={...s,file:{type:"base64",base64:globalThis.Buffer.from(e.buffer).toString("base64"),fileName:e.fileName,mimeType:e.mimeType}}}"hashinal"===i.mode&&(c.metadataObject=i.metadata,c.creator=i.metadata?.creator||r,c.description=i.metadata?.description,i.jsonFileURL&&(c.jsonFileURL=i.jsonFileURL)),o.debug("Starting inscription via startInscription (websocket)",{type:e.type,mode:i.mode||"file",holderId:r,usesStartInscription:!0});const p=await a.startInscription({...c,holderId:r,network:i.network||"mainnet"});if(o.info("about to start inscription",{type:e.type,mode:i.mode||"file",jobId:p.id||p.tx_id,...p}),"string"==typeof p?.transactionBytes?(o.debug("Executing inscription transaction with signer from bytes"),await a.executeTransactionWithSigner(p.transactionBytes,t)):"Buffer"===p?.transactionBytes?.type&&(o.debug("Executing inscription transaction with signer from buffer"),await a.executeTransactionWithSigner(globalThis.Buffer.from(p.transactionBytes.data).toString("base64"),t)),i.waitForConfirmation){o.debug("Waiting for inscription confirmation (websocket)",{jobId:p.id||p.tx_id,maxAttempts:i.waitMaxAttempts,intervalMs:i.waitIntervalMs});const e=p.tx_id||p.id,t=await hQ(a,e,i.waitMaxAttempts,i.waitIntervalMs,i.progressCallback);return o.info("Inscription confirmation received",{jobId:e}),{confirmed:!0,result:{jobId:p.id||p.tx_id,transactionId:p.tx_id||"",topic_id:p.topic_id,status:p.status,completed:p.completed},inscription:t,sdk:a}}return{confirmed:!1,result:{jobId:p.id||p.tx_id,transactionId:p.tx_id||"",topic_id:p.topic_id,status:p.status,completed:p.completed},sdk:a}}catch(r){throw o.error("Error during inscription process",r),r}}async function dQ(e,t){const i=y.getInstance({module:"Inscriber",...t?.logging||{}}),n=e.includes("@")?`${e.split("@")[0]}-${e.split("@")[1].replace(/\./g,"-")}`:e;i.info("Retrieving inscription",{originalTransactionId:e,formattedTransactionId:n});try{let e;if(t?.apiKey)i.debug("Initializing InscriptionSDK with API key"),e=new KY({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 i.error("Missing authentication credentials",{hasApiKey:Boolean(t?.apiKey),hasAccountId:Boolean(t?.accountId),hasPrivateKey:Boolean(t?.privateKey)}),e}i.debug("Initializing InscriptionSDK with server auth"),e=await KY.createWithAuth({type:"server",accountId:t.accountId,privateKey:t.privateKey,network:t.network||"mainnet"})}i.debug("Initialized SDK for inscription retrieval",{formattedTransactionId:n,network:t.network||"mainnet"});const o=await e.retrieveInscription(n);return i.info("Successfully retrieved inscription",{formattedTransactionId:n}),o}catch(o){throw i.error("Error retrieving inscription",{formattedTransactionId:n,error:o}),o}}function fQ(e,t){const i=["name","creator","description","type"].filter(t=>!e[t]);if(i.length>0){const e=new Error(`Missing required Hashinal metadata fields: ${i.join(", ")}`);throw t.error("Hashinal metadata validation failed",{missingFields:i}),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 mQ(e,t,i,n){const o=y.getInstance({module:"Inscriber",...i.logging});o.info("Generating inscription quote",{type:e.type,mode:i.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,i){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(!i)throw new Error("Options are required");if("hashinal"===i.mode){if(!i.metadata)throw new Error("Hashinal mode requires metadata");const e=["name","creator","description","type"].filter(e=>!i.metadata||!i.metadata[e]);if(e.length>0)throw new Error(`Missing required Hashinal metadata fields: ${e.join(", ")}`)}}(e,t,i);const r=function(e,t,i){const n=aQ.createCacheKey(e,t,i);return aQ.get(n)}(e,t,i);if(r)return o.debug("Returning cached quote"),{confirmed:!1,quote:!0,result:r};"hashinal"===i.mode&&i.metadata&&fQ(i.metadata,o);const a=await async function(e,t,i){if(i)return i;const n={apiKey:t.apiKey,accountId:e.accountId,network:e.network||"mainnet",authType:t.apiKey?"api":"server"},o=sQ.get(n);if(o)return o;let r;return r=t.apiKey?new KY({apiKey:t.apiKey,network:e.network||"mainnet"}):await KY.createWithAuth({type:"server",accountId:e.accountId,privateKey:e.privateKey,network:e.network||"mainnet"}),sQ.set(n,r),r}(t,i,n),s={holderId:t.accountId,metadata:i.metadata||{},tags:i.tags||[],mode:i.mode||"file",fileStandard:i.fileStandard,chunkSize:i.chunkSize};let c;switch(e.type){case"url":c={...s,file:{type:"url",url:e.url}};break;case"file":{const t=await pQ(e.path);c={...s,file:{type:"base64",base64:t.base64,fileName:t.fileName,mimeType:t.mimeType}};break}case"buffer":c={...s,file:{type:"base64",base64:globalThis.Buffer.from(e.buffer).toString("base64"),fileName:e.fileName,mimeType:e.mimeType}}}"hashinal"===i.mode&&(c.metadataObject=i.metadata,c.creator=i.metadata?.creator||t.accountId,c.description=i.metadata?.description,i.jsonFileURL&&(c.jsonFileURL=i.jsonFileURL)),o.debug("Calling inscription SDK startInscription for quote",{type:e.type,mode:i.mode||"file",holderId:t.accountId});const p=await a.startInscription(c);o.debug("Received inscription response for quote parsing",{hasTransactionBytes:!!p.transactionBytes,bytesLength:p.transactionBytes?.length||0,transactionBytesType:typeof p.transactionBytes,totalCost:p.totalCost});const l=await async function(e,t){try{let n="0.001";if(e.totalCost&&"number"==typeof e.totalCost){n=(e.totalCost/1e8).toString(),t.debug("Using totalCost from inscription response",{totalCostTinybars:e.totalCost,totalCostHbar:n})}else if(e.transactionBytes){t.debug("Parsing transaction bytes for cost information");try{let i;if("string"==typeof e.transactionBytes)i=e.transactionBytes;else{if(!e.transactionBytes||"object"!=typeof e.transactionBytes||!("data"in e.transactionBytes))throw new Error("Invalid transactionBytes format");i=globalThis.Buffer.from(e.transactionBytes.data).toString("base64")}t.debug("About to parse transaction bytes",{bytesLength:i.length,bytesPreview:i.slice(0,100)});const o=await oQ.parseTransactionBytes(i,{includeRaw:!1});t.debug("Parsed transaction for quote",{type:o.type,hasTransfers:!!o.transfers,transferCount:o.transfers?.length||0,transfers:o.transfers});let r=0;if(o.transfers&&o.transfers.length>0)for(const e of o.transfers){const i="string"==typeof e.amount?parseFloat(e.amount):e.amount;if(i<0){const n=Math.abs(i);r+=n,t.debug("Found HBAR transfer",{from:e.accountId,to:"service",amount:n})}}r>0&&(n=r.toString(),t.debug("Using parsed transaction transfer amount",{totalTransferAmount:r,totalCostHbar:n}))}catch(i){t.warn("Could not parse transaction bytes, using totalCost fallback",{error:i,errorMessage:i instanceof Error?i.message:String(i)})}}const o=[{to:"Inscription Service",amount:n,description:`Inscription fee (${n} HBAR)`}],r={totalCostHbar:n,validUntil:new Date(Date.now()+9e5).toISOString(),breakdown:{transfers:o}};return t.debug("Successfully parsed transaction for quote",{totalCostHbar:r.totalCostHbar,transferCount:o.length,hasTransactionBytes:!!e.transactionBytes,hasTotalCost:!!e.totalCost}),r}catch(n){throw t.error("Error parsing transaction for quote",n),n}}(p,o);return function(e,t,i,n){const o=aQ.createCacheKey(e,t,i);aQ.set(o,n,6e5)}(e,t,i,l),o.info("Successfully generated inscription quote",{totalCostHbar:l.totalCostHbar}),{confirmed:!1,quote:!0,result:l}}catch(r){throw o.error("Error generating inscription quote",r),r}}async function hQ(e,t,i=30,n=4e3,o){const r=y.getInstance({module:"Inscriber"}),a=new WY({module:"Inscriber",logger:r,callback:o});try{r.debug("Waiting for inscription confirmation",{transactionId:t,maxAttempts:i,intervalMs:n}),a.preparing("Preparing for inscription confirmation",5,{transactionId:t,maxAttempts:i,intervalMs:n});try{const o=e.waitForInscription.bind(e),r=e=>{const t=e.stage||"confirming",i=["preparing","submitting","confirming","verifying","completed","failed"].includes(t)?t:"confirming",n=e.message||"Processing inscription",o=e.progressPercent||50;a.report({stage:i,message:n,progressPercent:o,details:e.details})};return await o(t,i,n,!0,r)}catch(mxe){return r.debug("Falling back to standard waitForInscription method",{error:mxe}),a.verifying("Verifying inscription status",50,{error:mxe}),await e.waitForInscription(t,i,n,!0)}}catch(s){throw r.error("Error waiting for inscription confirmation",{transactionId:t,maxAttempts:i,intervalMs:n,error:s}),a.failed("Inscription confirmation failed",{transactionId:t,error:s}),s}}function gQ(e){return"object"==typeof e&&null!==e&&"sequence_number"in e&&"consensus_timestamp"in e&&"number"==typeof e.sequence_number&&"string"==typeof e.consensus_timestamp}function yQ(e){if(!e||"object"!=typeof e)return;const t=e,i=t.topicId||t.topic_id;if("string"==typeof i&&i.trim())return i;const n=t,o=n.topicId;if("string"==typeof o&&o.trim())return o;const r=n.topic_id;return"string"==typeof r&&r.trim()?r:void 0}class vQ{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 bQ(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 xQ(e){const t=Object.create(y.prototype);return t.debug=(...t)=>e.debug(...t),t.info=(...t)=>e.info(...t),t.warn=(...t)=>e.warn(...t),t.error=(...t)=>e.error(...t),t.trace=(...t)=>e.trace(...t),t.setLogLevel=t=>e.setLogLevel(t),t.getLevel=()=>e.getLevel(),t.setSilent=t=>e.setSilent(t),t.setModule=t=>e.setModule(t),t.logger={level:e.getLevel()},t.moduleContext="",t.formatArgs=()=>({msg:""}),t}function wQ(e){return e instanceof y}async function kQ(e,t,i){const n=new I(t,i),o=[];for(const a of e)try{const e=await n.getPublicKey(a);o.push(e)}catch(r){i&&i.warn(`Could not get public key for account ${a}: ${r}`)}return o}class _Q{constructor(e="info"){this.defaultEndpoint="https://kiloscribe.com/api/inscription-cdn",this.logger=y.getInstance({level:e,module:"HRLResolver"})}isBinaryContentType(e){return["image/","audio/","video/","application/octet-stream","application/pdf","application/zip","application/gzip","application/x-binary","application/vnd.ms-","application/x-msdownload","application/x-shockwave-flash","font/","application/wasm"].some(t=>e.startsWith(t))}parseHRL(e){if(!e)return null;const t=e.match(/^hcs:\/\/(\d+)\/([0-9]+\.[0-9]+\.[0-9]+)$/);return t?{standard:t[1],topicId:t[2]}:null}isValidHRL(e){if(!e||"string"!=typeof e)return!1;const t=this.parseHRL(e);if(!t)return!1;return!!/^[0-9]+\.[0-9]+\.[0-9]+$/.test(t.topicId)}isValidTopicId(e){return/^[0-9]+\.[0-9]+\.[0-9]+$/.test(e)}async resolve(e,t){if(this.isValidHRL(e))return this.resolveHRL(e,t);if(!this.isValidTopicId(e))throw new Error(`Invalid HRL or topic ID format: ${e}`);try{const i=new I(t.network,this.logger),n=await i.getTopicInfo(e),o=n?.memo||"";let r="1";if(o){const e=o.match(/^hcs-(\d+)/);e&&e[1]&&(r=e[1])}const a=`hcs://${r}/${e}`;return this.resolveHRL(a,t)}catch(i){this.logger.error(`Failed to get topic info for ${e}: ${i.message}`);const n=`hcs://1/${e}`;return this.resolveHRL(n,t)}}async getContentWithType(e,t){if(!this.isValidHRL(e))return{content:e,contentType:"text/plain",isBinary:!1};try{const i=await this.resolveHRL(e,t);return{content:i.content,contentType:i.contentType,isBinary:i.isBinary}}catch(mxe){const t=`Error resolving HRL for content and type: ${mxe.message}`;throw this.logger.error(t),new Error(t)}}async resolveHRL(e,t){const i=this.parseHRL(e);if(!i)throw new Error(`Invalid HRL format: ${e}`);const{standard:n,topicId:o}=i;this.logger.debug(`Resolving HRL reference: standard=${n}, topicId=${o}`);try{const e=`${t.cdnEndpoint||this.defaultEndpoint}/${o}?network=${t.network}`;this.logger.debug(`Fetching content from CDN: ${e}`);const i=(await r.head(e)).headers["content-type"]||"";if(this.isBinaryContentType(i)||t.returnRaw){return{content:(await r.get(e,{responseType:"arraybuffer"})).data,contentType:i,topicId:o,isBinary:!0}}if("application/json"===i){const t=await r.get(e,{responseType:"json"});if(!t.data)throw new Error(`Failed to fetch content from topic: ${o}`);return{content:t.data,contentType:i,topicId:o,isBinary:!1}}const n=await r.get(e);if(!n.data)throw new Error(`Failed to fetch content from topic: ${o}`);let a;return a="object"==typeof n.data?n.data.content||n.data.text||JSON.stringify(n.data):n.data,{content:a,contentType:i,topicId:o,isBinary:!1}}catch(mxe){const t=`Error resolving HRL reference: ${mxe.message}`;throw this.logger.error(t),new Error(t)}}}class EQ{constructor(e){this.nodeHash=e}update(e){return this.nodeHash.update(e),this}digest(e){return this.nodeHash.digest(e)}}class SQ{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),i=await crypto.subtle.digest(this.mapAlgorithm(this.algorithm),t);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),i=new Uint8Array(t);let n=0;for(const o of e)i.set(o,n),n+=o.length;return i}mapAlgorithm(e){return{sha256:"SHA-256",sha384:"SHA-384",sha1:"SHA-1",sha512:"SHA-512"}[e.toLowerCase()]||"SHA-256"}}class TQ{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),i=this.simpleHash(t);return"hex"===e?i.toString(16).padStart(8,"0"):i.toString()}simpleHash(e){let t=0;for(let i=0;i<e.length;i++)t=(t<<5)-t+e[i]&4294967295;return Math.abs(t)}}function AQ(){const e="undefined"==typeof window;let t,i=!1,n=!1;try{i="undefined"!=typeof require&&"undefined"!=typeof process&&!!process.versions?.node}catch{i=!1}try{n="undefined"!=typeof crypto&&void 0!==crypto.subtle&&!e}catch{n=!1}return t=i&&e?"node":n&&!e?"web":"none",{hasNodeCrypto:i,hasWebCrypto:n,isSSR:e,preferredAPI:t}}function IQ(){return"undefined"==typeof window}class RQ{constructor(e){this.nodeHmac=e}update(e){return this.nodeHmac.update(e),this}digest(e){return this.nodeHmac.digest(e)}}class OQ{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),i=await crypto.subtle.importKey("raw",this.key,{name:"HMAC",hash:this.mapAlgorithm(this.algorithm)},!1,["sign"]),n=await crypto.subtle.sign("HMAC",i,t);return"hex"===e?Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join(""):globalThis.Buffer.from(n)}mapAlgorithm(e){return{sha256:"SHA-256",sha1:"SHA-1",sha512:"SHA-512"}[e.toLowerCase()]||"SHA-256"}}class jQ{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),i=this.simpleHmac(t,this.key);return"hex"===e?i.toString(16).padStart(8,"0"):i.toString()}simpleHmac(e,t){let i=0;for(let n=0;n<e.length;n++){const o=t[n%t.length];i=(i<<5)-i+e[n]+o&4294967295}return Math.abs(i)}}class CQ{constructor(){try{const e="crypto";this.crypto=require(e)}catch(e){throw new Error("Node.js crypto module not available")}}createHash(e){return new EQ(this.crypto.createHash(e))}createHmac(e,t){return new RQ(this.crypto.createHmac(e,t))}async pbkdf2(e,t,i,n,o){return new Promise((r,a)=>{this.crypto.pbkdf2(e,t,i,n,o,(e,t)=>{e?a(e):r(t)})})}timingSafeEqual(e,t){return this.crypto.timingSafeEqual(e,t)}}class NQ{createHash(e){return new SQ(e)}createHmac(e,t){return new OQ(t,e)}async pbkdf2(e,t,i,n,o){const r=new TextEncoder,a=await crypto.subtle.importKey("raw",r.encode(e),{name:"PBKDF2"},!1,["deriveBits"]),s=await crypto.subtle.deriveBits({name:"PBKDF2",salt:t,iterations:i,hash:this.mapDigest(o)},a,8*n);return globalThis.Buffer.from(s)}timingSafeEqual(e,t){if(e.length!==t.length)return!1;let i=0;for(let n=0;n<e.length;n++)i|=e[n]^t[n];return 0===i}mapDigest(e){return{sha256:"SHA-256",sha1:"SHA-1",sha512:"SHA-512"}[e.toLowerCase()]||"SHA-256"}}class BQ{createHash(e){return new TQ(e)}createHmac(e,t){return new jQ(t,e)}async pbkdf2(e,t,i,n,o){const r=new TextEncoder,a=globalThis.Buffer.from(r.encode(e));let s=globalThis.Buffer.alloc(n);for(let c=0;c<i;c++){const e=globalThis.Buffer.concat([a,t,globalThis.Buffer.from([c])]);let i=0;for(let t=0;t<e.length;t++)i=(i<<5)-i+e[t]&4294967295;s[c%n]^=255&i}return s}timingSafeEqual(e,t){if(e.length!==t.length)return!1;let i=0;for(let n=0;n<e.length;n++)i|=e[n]^t[n];return 0===i}}function PQ(){switch(AQ().preferredAPI){case"node":try{return new CQ}catch{return new BQ}case"web":return new NQ;default:return new BQ}}const LQ=["mainnet","testnet","previewnet","devnet"];function UQ(e){return LQ.includes(e)}const FQ=/^hedera:(mainnet|testnet|previewnet|devnet):\d+\.\d+\.\d+(?:-[a-zA-Z0-9]{5})?$/;function MQ(e){return FQ.test(e)}function DQ(e,t){if(!UQ(e))throw new Error("Invalid Hedera network");if(t.startsWith("hedera:")){if(MQ(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 zQ(e){if(!MQ(e))throw new Error("Invalid Hedera CAIP-10");const[,t,i]=e.match(/^hedera:([^:]+):(.+)$/);return{network:t,accountId:i}}const $Q=/^eip155:(\d+):(0x[0-9a-fA-F]{39,40})$/;function qQ(e){return $Q.test(e)}function KQ(e,t){const i=`eip155:${"number"==typeof e?String(e):e}:${t.startsWith("0x")?t:`0x${t}`}`;if(!qQ(i))throw new Error("Invalid EIP-155 CAIP-10");return i}const WQ=n.z.object({registry:n.z.string().min(1),name:n.z.string().min(1),version:n.z.string().min(1),protocol:n.z.string().min(1),nativeId:n.z.string().min(1),skills:n.z.array(n.z.number().int().nonnegative())});function HQ(e){return e.trim()}function VQ(e){return e.trim().toLowerCase()}function GQ(e){const t=WQ.parse(e);if("hcs-10"===t.protocol.trim().toLowerCase()&&!MQ(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()&&!qQ(t.nativeId.trim()))throw new Error("HCS-14: For protocol acp-virtuals, nativeId must be EIP-155 CAIP-10 (eip155:<chainId>:<address>)");const i={registry:VQ(t.registry),name:HQ(t.name),version:HQ(t.version),protocol:VQ(t.protocol),nativeId:HQ(t.nativeId),skills:[...t.skills].sort((e,t)=>e-t)},n=["skills","name","nativeId","protocol","registry","version"],o={};for(const r of n)o[r]=i[r];return{normalized:i,canonicalJson:JSON.stringify(o)}}const ZQ="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function JQ(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 i=[0];for(let o=t;o<e.length;o++){let t=e[o];for(let e=0;e<i.length;e++){const n=(i[e]<<8)+t;i[e]=n%58,t=n/58|0}for(;t>0;)i.push(t%58),t=t/58|0}let n="";for(let o=0;o<t;o++)n+="1";for(let o=i.length-1;o>=0;o--)n+=ZQ[i[o]];return n}function YQ(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 i=[];for(let n=t;n<e.length;n++){const t=e[n],o=ZQ.indexOf(t);if(-1===o)throw new Error("Invalid Base58 character");let r=o;for(let e=0;e<i.length;e++){const t=58*i[e]+r;i[e]=255&t,r=t>>8}for(;r>0;)i.push(255&r),r>>=8}for(let n=0;n<t;n++)i.push(0);return i.reverse(),Uint8Array.from(i)}(e.slice(1))}function XQ(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 QQ(e,t){let i,n;if(e.startsWith("uaid:aid:"))i="aid",n=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");i=e.slice(t+1,o),n=e.slice(o+1)}}const{sanitized:o,hadSuffix:r}=function(e){const t=e.search(/[;?#]/);return-1===t?{sanitized:e,hadSuffix:!1}:{sanitized:e.slice(0,t),hadSuffix:!0}}(n);let a=o;if("hedera"===i){const e=o.match(/^(mainnet|testnet|previewnet|devnet):(.+)$/);e&&(a=e[2])}const s={...t||{}};var c;r&&!s.src&&(s.src=(c=e,"z"+JQ(globalThis.Buffer.from(c,"utf8"))));const p=XQ(s);return p?`uaid:did:${a};${p}`:`uaid:did:${a}`}function e0(e,t,i){return"string"==typeof e?QQ(e,t):async function(e,t,i){const{normalized:n,canonicalJson:o}=GQ(e),r=PQ().createHash("sha384").update(globalThis.Buffer.from(o,"utf8")).digest(),a=await Promise.resolve(r),s=JQ(globalThis.Buffer.isBuffer(a)?a:globalThis.Buffer.from(a)),c=!1!==i?.includeParams,p=c?function(e,t){const i={...t};return i.registry||(i.registry=e.registry),i.nativeId||(i.nativeId=e.nativeId),i.uid||(i.uid="0"),i}(n,t||{}):{},l=c?XQ(p):"";return l?`uaid:aid:${s};${l}`:`uaid:aid:${s}`}(e,t,i)}function t0(e){if(e.startsWith("uaid:")){const t=e.slice(5);let i,n;if(t.startsWith("did:"))i="did",n=t.slice(4);else{if(!t.startsWith("aid:"))throw new Error("Invalid UAID");i="aid",n=t.slice(4)}const o=n.indexOf(";"),r=o>=0?n.slice(0,o):n,a=(e=>{const t={};if(!e)return t;const i=e.split(";");for(const n of i){const e=n.indexOf("=");if(e>0){const i=n.slice(0,e),o=n.slice(e+1);t[i]=o}}return t})(o>=0?n.slice(o+1):"");return{method:"did"===i?"uaid":"aid",id:r,params:a}}throw new Error("Invalid DID")}class i0{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 u.resolveDID(e),i=t.id??t.didDocument?.id;return i?{id:i}:null}}class n0{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=t0(e);if("uaid"!==t.method)return null;const i=t.params.src;if(i){const e=globalThis.Buffer.from(YQ(i)).toString("utf8");return this.resolveDid(e)}const n=t.id;if(n.startsWith("testnet:")||n.startsWith("mainnet:")||n.startsWith("previewnet:")||n.startsWith("devnet:")){const e=`did:hedera:${n}`;return this.resolveDid(e)}const o=t.params.proto,r=t.params.nativeId;if("hcs-10"===o&&r){const e=r.match(/^hedera:(mainnet|testnet|previewnet|devnet):/);if(e){const t=`did:hedera:${e[1]}:${n}`;return this.resolveDid(t)}}return null}}const o0=new n0;class r0{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 a0=new r0;class s0{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");return(await d.createDID({},{client:e.client})).did}}class c0 extends Error{constructor(e,t){super(e),this.payloadSize=t,this.name="PayloadSizeError"}}class p0 extends Error{constructor(e){super(e),this.name="AccountCreationError"}}class l0 extends Error{constructor(e){super(e),this.name="TopicCreationError"}}class u0 extends Error{constructor(e){super(e),this.name="ConnectionConfirmationError"}}var d0=(e=>(e[e.PERSONAL=0]="PERSONAL",e[e.AI_AGENT=1]="AI_AGENT",e[e.MCP_SERVER=2]="MCP_SERVER",e))(d0||{}),f0=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(f0||{}),m0=(e=>(e[e.REST=0]="REST",e[e.WEBSOCKET=1]="WEBSOCKET",e[e.GRPC=2]="GRPC",e))(m0||{}),h0=(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))(h0||{}),g0=(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))(g0||{}),y0=(e=>(e.DNS="dns",e.SIGNATURE="signature",e.CHALLENGE="challenge",e))(y0||{}),v0=(e=>(e.PUBLIC="PUBLIC",e.CONTROLLED="CONTROLLED",e.FEE_BASED="FEE_BASED",e))(v0||{});const b0={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};class x0{constructor(){this.config={},this.logger=y.getInstance({module:"AgentBuilder"})}setName(e){return this.config.name=e,this}setAlias(e){return this.config.alias=e,this}setBio(e){return this.config.bio=e,this}setDescription(e){return this.config.bio=e,this}setCapabilities(e){return this.config.capabilities=e,this}setAgentType(e){return this.config.metadata?this.config.metadata.type=e:this.config.metadata={type:e},this}setType(e){return this.config.metadata?this.config.metadata.type=e:this.config.metadata={type:e},this}setModel(e){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.model=e,this}setCreator(e){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.creator=e,this}addSocial(e,t){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.socials||(this.config.metadata.socials={}),this.config.metadata.socials[e]=t,this}addProperty(e,t){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.properties||(this.config.metadata.properties={}),this.config.metadata.properties[e]=t,this}setMetadata(e){return this.config.metadata=e,this}setProfilePicture(e,t){return this.config.pfpBuffer=e,this.config.pfpFileName=t,this}setExistingProfilePicture(e){return this.config.existingPfpTopicId=e,this}setNetwork(e){return this.config.network=e,this}setInboundTopicType(e){return this.config.inboundTopicType=e,this}setFeeConfig(e){return this.config.feeConfig=e,this}setConnectionFeeConfig(e){return this.config.connectionFeeConfig=e,this}setExistingAccount(e,t){return this.config.existingAccount={accountId:e,privateKey:t},this}setInboundTopicId(e){return this.config.inboundTopicId=e,this}setOutboundTopicId(e){return this.config.outboundTopicId=e,this}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=v0.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===v0.FEE_BASED&&!this.config.feeConfig)throw new Error("Fee configuration is required for fee-based topics");return this.config}}class w0 extends M0{constructor(e){if(super({network:e.network,logLevel:e.logLevel,prettyPrint:e.prettyPrint,feeAmount:e.feeAmount,mirrorNode:e.mirrorNode,silent:e.silent,keyType:e.keyType}),this.logger=y.getInstance({level:e.logLevel||"info",module:"HCS-SDK",silent:e.silent}),this.client="mainnet"===e.network?o.Client.forMainnet():o.Client.forTestnet(),this.operatorPrivateKey=e.operatorPrivateKey,this.operatorAccountId=e.operatorId,e.keyType){this.keyType=e.keyType;const t="ecdsa"===this.keyType?o.PrivateKey.fromStringECDSA(this.operatorPrivateKey):o.PrivateKey.fromStringED25519(this.operatorPrivateKey);this.client.setOperator(e.operatorId,t)}else{try{const t=C(this.operatorPrivateKey);this.keyType=t.detectedType,t.warning&&this.logger.warn(t.warning),this.client.setOperator(e.operatorId,t.privateKey)}catch(t){this.logger.warn("Failed to detect key type from private key format, will query mirror node"),this.keyType="ecdsa"}this.initializeOperator()}this.network=e.network,this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl||"https://moonscape.tech",this.hcs11Client=new L0({network:e.network,auth:{operatorId:e.operatorId,privateKey:e.operatorPrivateKey},logLevel:e.logLevel,silent:e.silent,keyType:e.keyType})}async initializeOperator(){const e=await this.requestAccount(this.operatorAccountId),t=e?.key?._type;t&&t.includes("ECDSA")?this.keyType="ecdsa":t&&t.includes("ED25519")?this.keyType="ed25519":this.keyType="ecdsa";const i="ecdsa"===this.keyType?o.PrivateKey.fromStringECDSA(this.operatorPrivateKey):o.PrivateKey.fromStringED25519(this.operatorPrivateKey);return this.logger.debug(`Setting operator: ${this.operatorAccountId} with key type: ${this.keyType}`),this.client.setOperator(this.operatorAccountId,i),{accountId:this.operatorAccountId,privateKey:this.operatorPrivateKey,keyType:this.keyType,client:this.client}}getClient(){return this.client}async createAccount(e=50){this.keyType||await this.initializeOperator(),this.logger.info(`Creating new account with ${e} HBAR initial balance`);const t=o.PrivateKey.generateED25519(),i=(new o.AccountCreateTransaction).setKeyWithoutAlias(t.publicKey).setInitialBalance(new o.Hbar(e));this.logger.debug("Executing account creation transaction");const n=await i.execute(this.client),r=(await n.getReceipt(this.client)).accountId;if(!r)throw this.logger.error("Account creation failed: accountId is null"),new p0("Failed to create account: accountId is null");return this.logger.info(`Account created successfully: ${r.toString()}`),{accountId:r.toString(),privateKey:t.toString()}}async createInboundTopic(e,t,i=60,n){this.keyType||await this.initializeOperator();const o=this._generateHcs10Memo(F0.INBOUND,{accountId:e,ttl:i});let r,a;switch(t){case v0.PUBLIC:r=!1;break;case v0.CONTROLLED:r=!0;break;case v0.FEE_BASED:if(r=!1,!n)throw new Error("Fee configuration builder is required for fee-based topics");n.customFees.forEach(t=>{t.feeCollectorAccountId||(this.logger.debug(`Defaulting fee collector for token ${t.feeTokenId||"HBAR"} to agent ${e}`),t.feeCollectorAccountId=e)}),a=n.build(),a.customFees=a.customFees.map(t=>({...t,feeCollectorAccountId:t.feeCollectorAccountId||e}));break;default:throw new Error(`Unsupported inbound topic type: ${t}`)}return this.createTopic(o,!0,r,a)}async createAgent(e,t=60,i,n){this.keyType||await this.initializeOperator();const o=e.build(),r=this.client.operatorAccountId?.toString();if(!r)throw new Error("Failed to retrieve operator account ID");const a=await this._createEntityTopics(t,{outboundTopicId:i?.outboundTopicId||"",inboundTopicId:i?.inboundTopicId||"",pfpTopicId:i?.pfpTopicId||o.existingPfpTopicId||"",profileTopicId:i?.profileTopicId||""},r,o.inboundTopicType,o.feeConfig,o.pfpBuffer,o.pfpFileName,n);if(a.profileTopicId)this.logger.info(`Using existing profile topic ID: ${a.profileTopicId}`);else{n&&n({stage:"preparing",message:"Creating agent profile",progressPercent:60,details:{outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.pfpTopicId,state:{currentStage:"profile",completedPercentage:60}}});const e=await this.storeHCS11Profile(o.name,o.bio,a.inboundTopicId,a.outboundTopicId,o.capabilities,o.metadata,o.pfpBuffer&&o.pfpBuffer.length>0&&!a.pfpTopicId?o.pfpBuffer:void 0,o.pfpFileName,a.pfpTopicId);a.profileTopicId=e.profileTopicId,this.logger.info(`Profile stored with topic ID: ${a.profileTopicId}`),n&&n({stage:"preparing",message:"Agent profile created",progressPercent:70,details:{outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.pfpTopicId,profileTopicId:a.profileTopicId,state:{currentStage:"profile",completedPercentage:70}}})}return a}async create(e,t){const i=t?.progressCallback,n=new WY({module:"ProfileCreate",logger:this.logger,callback:i?e=>i({stage:e.stage,message:e.message,progressPercent:e.progressPercent,details:e.details}):void 0});try{const i=e instanceof x0;let o;if(o=t?.existingState?t.existingState:{currentStage:"init",completedPercentage:0,createdResources:[]},i){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");n.preparing(`Starting ${i?"agent":"person"} resource creation`,0,{state:o});const r=this.client.operatorAccountId?.toString();if(!r)throw new Error("Failed to retrieve operator account ID");const{inboundTopicId:a,outboundTopicId:s,state:c}=await this.createCommunicationTopics(r,t,n);let p,l,u;if(o=c,e.setInboundTopicId(a),e.setOutboundTopicId(s),i){const t=e.build();p=t.existingPfpTopicId||o.pfpTopicId,l=t.pfpBuffer,u=t.pfpFileName||"pfp.png"}else{const t=e.build();p=o.pfpTopicId,l=t.pfpBuffer,u=t.pfpFileName}!p&&l&&u?p=await this.handleProfilePictureCreation(l,u,o,n):p&&(n.preparing(`Using existing profile picture: ${p}`,50,{state:o}),o.pfpTopicId=p),await this.createAndInscribeProfile(i,e,p,o,a,s,t,n),o.currentStage="complete",o.completedPercentage=100,n.completed((i?"Agent":"Person")+" profile created successfully",{profileTopicId:o.profileTopicId,inboundTopicId:a,outboundTopicId:s,pfpTopicId:p,state:o});let d="";o.outboundTopicId&&(d=o.outboundTopicId);let f="";o.inboundTopicId&&(f=o.inboundTopicId);let m="";o.pfpTopicId&&(m=o.pfpTopicId);let h="";return o.profileTopicId&&(h=o.profileTopicId),{outboundTopicId:d,inboundTopicId:f,pfpTopicId:m,profileTopicId:h,success:!0,state:o}}catch(o){return n.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 i=await this.hcs11Client.inscribeImage(e,t);if(!i.success)throw this.logger.error(`Failed to inscribe profile picture: ${i.error}`),new Error(i?.error||"Failed to inscribe profile picture");return this.logger.info(`Successfully inscribed profile picture with topic ID: ${i.imageTopicId}`),{pfpTopicId:i.imageTopicId,transactionId:i.transactionId,success:!0}}catch(mxe){const t=mxe,i=`Error inscribing profile picture: ${t.message}`;return this.logger.error(i),{pfpTopicId:"",transactionId:"",success:!1,error:t.message}}}async storeHCS11Profile(e,t,i,n,o=[],r,a,s,c){try{let p=c||"";if(!p&&a&&s){this.logger.info("Inscribing profile picture for HCS-11 profile");const e=await this.inscribePfp(a,s);e.success?p=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`),p=c);const l=this.hcs11Client.getAgentTypeFromMetadata({type:r.type||"autonomous"}),u=r.socials?Object.entries(r.socials).filter(([e,t])=>t).map(([e,t])=>({platform:e,handle:t})):void 0,d=this.hcs11Client.createAIAgentProfile(e,l,o,r.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:p?`hcs://1/${p}`:void 0,socials:u,properties:r.properties,inboundTopicId:i,outboundTopicId:n,creator:r.creator}),f=await this.hcs11Client.createAndInscribeProfile(d,!0);if(!f.success)throw this.logger.error(`Failed to inscribe profile: ${f.error}`),new Error(f.error||"Failed to inscribe profile");return this.logger.info(`Profile inscribed with topic ID: ${f.profileTopicId}, transaction ID: ${f.transactionId}`),{profileTopicId:f.profileTopicId,pfpTopicId:p,transactionId:f.transactionId,success:!0}}catch(mxe){const t=mxe,i=`Error storing HCS-11 profile: ${t.message}`;return this.logger.error(i),{profileTopicId:"",pfpTopicId:"",transactionId:"",success:!1,error:t.message}}}async setupFees(e,t,i=[]){let n=e;if(!this.client.operatorPublicKey)return n;if(!t.customFees||0===t.customFees.length)return this.logger.warn("No custom fees provided in fee config for setupFees"),n;t.customFees.length>10&&(this.logger.warn("More than 10 custom fees provided, only the first 10 will be used"),t.customFees=t.customFees.slice(0,10));const r=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 o.CustomFixedFee).setAmount(Number(e.feeAmount.amount)).setFeeCollectorAccountId(o.AccountId.fromString(e.feeCollectorAccountId));return e.feeTokenId&&t.setDenominatingTokenId(o.TokenId.fromString(e.feeTokenId)),t}return null}).filter(Boolean);if(0===r.length)return this.logger.warn("No valid custom fees to apply in setupFees"),n;const a=[...t.exemptAccounts||[],...i];return a.length>0&&(n=await this.setupExemptKeys(e,a)),n.setFeeScheduleKey(this.client.operatorPublicKey).setCustomFees(r)}async setupExemptKeys(e,t){let i=e;const n=Array.from(new Set(t)).filter(e=>e!==this.client.operatorAccountId?.toString());let o=[];if(n.length>0)try{o=await kQ(n,this.network,this.logger)}catch(mxe){const t=`Error getting exempt keys: ${mxe.message}, continuing without exempt keys`;this.logger.warn(t)}return o.length>0&&(i=i.setFeeExemptKeys(o)),i}async handleConnectionRequest(e,t,i,n,r=60){const a=this._generateHcs10Memo(F0.CONNECTION,{ttl:r,inboundTopicId:e,connectionId:i});this.logger.info(`Handling connection request ${i} from ${t}`);const s=this.getClient().operatorAccountId?.toString();if(!s)throw new Error("Failed to retrieve operator account ID");let c=await this.mirrorNode.getPublicKey(t);const p=await this.mirrorNode.getPublicKey(s);if(!p)throw new Error("Failed to retrieve public key");const l=new o.KeyList([p,c],1);let u;try{if(n){const e=n.build(),t={...e,exemptAccounts:[...e.exemptAccounts||[]]};u=await this.createTopic(a,l,l,t)}else u=await this.createTopic(a,l,l);this.logger.info(`Created new connection topic ID: ${u}`)}catch(y){const e=`Failed to create connection topic: ${y}`;throw this.logger.error(e),new l0(e)}const d=`${e}@${s}`,f=await this.confirmConnection(e,u,t,i,"Connection accepted. Looking forward to collaborating!"),m=await this.retrieveCommunicationTopics(s),h=await this.retrieveCommunicationTopics(t),g=`${h.inboundTopic}@${t}`;return await this.recordOutboundConnectionConfirmation({outboundTopicId:m.outboundTopic,requestorOutboundTopicId:h.outboundTopic,connectionRequestId:i,confirmedRequestId:f,connectionTopicId:u,operatorId:g,memo:`Connection established with ${t}`}),{connectionTopicId:u,confirmedConnectionSequenceNumber:f,operatorId:d}}async confirmConnection(e,t,i,n,o,r){const a=await this.getOperatorId();this.logger.info(`Confirming connection with ID ${n}`);const s={p:"hcs-10",op:"connection_created",connection_topic_id:t,connected_account_id:i,operator_id:a,connection_id:n,m:o},c=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),p=await this.submitPayload(e,s,r,c.requiresFee),l=p.topicSequenceNumber?.toNumber();if(!l)throw new u0("Failed to confirm connection: sequence number is null");return l}async sendMessage(e,t,i,n,o){const r=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),a={p:"hcs-10",op:"message",operator_id:await this.getOperatorId(),data:t,m:i},s=JSON.stringify(a);if(globalThis.Buffer.from(s).length>1e3){this.logger.info("Message payload exceeds 1000 bytes, storing via inscription");try{const e=globalThis.Buffer.from(t),i=`message-${Date.now()}.json`,n=await this.inscribeFile(e,i,{progressCallback:o?.progressCallback,waitMaxAttempts:o?.waitMaxAttempts,waitIntervalMs:o?.waitIntervalMs});if(!yQ(n))throw new Error("Failed to inscribe large message content");a.data=`hcs://1/${yQ(n)}`,this.logger.info(`Large message inscribed with topic ID: ${yQ(n)}`)}catch(c){const e=`Error inscribing large message: ${c.message}`;throw this.logger.error(e),new Error(e)}}return this.logger.info("Submitting message to connection topic",a),await this.submitPayload(e,a,n,r.requiresFee)}async createTopic(e,t,i,n){this.logger.info("Creating topic");const o=N({memo:e,adminKey:t,submitKey:i,operatorPublicKey:this.client.operatorPublicKey||void 0});n&&await this.setupFees(o,n),this.logger.debug("Executing topic creation transaction");const r=await o.execute(this.client),a=await r.getReceipt(this.client);if(!a.topicId)throw this.logger.error("Failed to create topic: topicId is null"),new Error("Failed to create topic: topicId is null");return a.topicId.toString()}async submitPayload(e,t,i,n=!1){const r="string"==typeof t?t:JSON.stringify(t),a=globalThis.Buffer.byteLength(r,"utf8");if(a>1e3)throw new c0("Payload size exceeds 1000 bytes limit",a);const s=B({topicId:e,message:r,transactionMemo:this.getHcs10TransactionMemo(t)||void 0});let c;if(n&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),s.setMaxTransactionFee(new o.Hbar(this.feeAmount))),i){const e=s.freezeWith(this.client),t=await e.sign(i);c=await t.execute(this.client)}else c=await s.execute(this.client);const p=await c.getReceipt(this.client);if(!p)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"),p}async inscribeFile(e,t,i){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.operatorPrivateKey)throw this.logger.error("Operator private key is not set"),new Error("Operator private key is not set");const n=h.lookup(t)||"application/octet-stream",r="ecdsa"===this.keyType?o.PrivateKey.fromStringECDSA(this.operatorPrivateKey):o.PrivateKey.fromStringED25519(this.operatorPrivateKey),a=await KY.createWithAuth({type:"server",accountId:this.client.operatorAccountId.toString(),privateKey:r,network:this.network}),s={mode:"file",waitForConfirmation:!0,waitMaxAttempts:i?.waitMaxAttempts||30,waitIntervalMs:i?.waitIntervalMs||4e3,progressCallback:i?.progressCallback,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},c=await lQ({type:"buffer",buffer:e,fileName:t,mimeType:n},{accountId:this.client.operatorAccountId.toString(),privateKey:r,network:this.network},s,a);if(!c.confirmed||!c.inscription)throw new Error("Inscription was not confirmed");return c.inscription}async waitForConnectionConfirmation(e,t,i=60,n=2e3,o=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let r=0;r<i;r++){this.logger.info(`Attempt ${r+1}/${i} to find connection confirmation`);const a=(await this.mirrorNode.getTopicMessages(e)).filter(e=>"connection_created"===e.op);if(this.logger.info(`Found ${a.length} connection_created messages`),a.length>0)for(const e of a)if(Number(e.connection_id)===Number(t)){const i={connectionTopicId:e.connection_topic_id,sequence_number:Number(e.sequence_number),confirmedBy:e.operator_id,memo:e.m},n=this.extractAccountFromOperatorId(i.confirmedBy),r=this.getAccountAndSigner(),a=await this.retrieveCommunicationTopics(n),s=await this.retrieveCommunicationTopics(r.accountId);return this.logger.info("Connection confirmation found",i),o&&await this.recordOutboundConnectionConfirmation({requestorOutboundTopicId:a.outboundTopic,outboundTopicId:s.outboundTopic,connectionRequestId:t,confirmedRequestId:i.sequence_number,connectionTopicId:i.connectionTopicId,operatorId:i.confirmedBy,memo:i.memo||"Connection confirmed"}),i}r<i-1&&(this.logger.info(`No matching confirmation found, waiting ${n}ms before retrying...`),await new Promise(e=>setTimeout(e,n)))}throw new Error(`Connection confirmation not found after ${i} attempts for request ID ${t}`)}getAccountAndSigner(){const e="ecdsa"===this.keyType?o.PrivateKey.fromStringECDSA(this.operatorPrivateKey):o.PrivateKey.fromStringED25519(this.operatorPrivateKey);return{accountId:this.client.operatorAccountId.toString(),signer:e}}async createAndRegisterAgent(e,t){try{const i=e.build(),n=t?.progressCallback,r=t?.baseUrl||this.guardedRegistryBaseUrl;let a=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};a.agentMetadata=i.metadata,n&&n({stage:"preparing",message:"Starting agent creation process",progressPercent:0,details:{state:a}});let s,c=i.existingAccount;if(a.inboundTopicId&&a.outboundTopicId&&a.profileTopicId){if(c=c||i.existingAccount,!c)throw new Error("Cannot resume registration without account information");const e="ecdsa"===this.keyType?o.PrivateKey.fromStringECDSA(c.privateKey).publicKey.toString():o.PrivateKey.fromStringED25519(c.privateKey).publicKey.toString();s=new w0({network:i.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:e,logLevel:"info",guardedRegistryBaseUrl:r}),this.logger.info("Resuming registration with existing state",{inboundTopicId:a.inboundTopicId,outboundTopicId:a.outboundTopicId,profileTopicId:a.profileTopicId,pfpTopicId:a.pfpTopicId})}else{if(!c)if(a.createdResources&&a.createdResources.some(e=>e.startsWith("account:"))){const e=a.createdResources.find(e=>e.startsWith("account:")),n=e?.split(":")[1];n&&i.existingAccount?(c=i.existingAccount,this.logger.info(`Resuming with existing account: ${n}`)):(c=await this.createAccount(t?.initialBalance),a.createdResources=a.createdResources||[],a.createdResources.push(`account:${c.accountId}`))}else c=await this.createAccount(t?.initialBalance),a.createdResources=a.createdResources||[],a.createdResources.push(`account:${c.accountId}`);n&&n({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:a,account:c}});const p=C(c.privateKey),l=("ed25519"===p.detectedType?o.PrivateKey.fromStringED25519(c.privateKey):o.PrivateKey.fromStringECDSA(c.privateKey)).publicKey.toString();s=new w0({network:i.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:l,keyType:p.detectedType,logLevel:"info",guardedRegistryBaseUrl:r}),n&&n({stage:"preparing",message:"Initialized agent client",progressPercent:25,details:{state:a}});let u=a.outboundTopicId,d=a.inboundTopicId,f=a.pfpTopicId,m=a.profileTopicId;if(!u||!d||!m){f&&e.setExistingProfilePicture(f);const t=await s.createAgent(e,60,a,e=>{n&&n({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:{...e.details,state:{...a,...e.details?.state}}})});u=t.outboundTopicId,d=t.inboundTopicId,f=t.pfpTopicId,m=t.profileTopicId,a.outboundTopicId=u,a.inboundTopicId=d,a.pfpTopicId=f,a.profileTopicId=m,a.createdResources||(a.createdResources=[]),f&&!a.createdResources.includes(`pfp:${f}`)&&a.createdResources.push(`pfp:${f}`),a.createdResources.includes(`inbound:${d}`)||a.createdResources.push(`inbound:${d}`),a.createdResources.includes(`outbound:${u}`)||a.createdResources.push(`outbound:${u}`),a.createdResources.includes(`profile:${m}`)||a.createdResources.push(`profile:${m}`)}a.currentStage="profile",a.completedPercentage=60,n&&n({stage:"submitting",message:"Created agent with topics and profile",progressPercent:60,details:{state:a,outboundTopicId:u,inboundTopicId:d,pfpTopicId:f,profileTopicId:m}})}const p=`${a.inboundTopicId}@${c.accountId}`;if("complete"!==a.currentStage||!a.createdResources?.includes(`registration:${a.inboundTopicId}`)){const e=await s.registerAgentWithGuardedRegistry(c.accountId,i.network,{progressCallback:e=>{const t=60+.4*(e.progressPercent||0);n&&n({stage:e.stage,message:e.message,progressPercent:t,details:{...e.details,outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.pfpTopicId,profileTopicId:a.profileTopicId,operatorId:p,state:e.details?.state||a}})},existingState:a});if(!e.success)return{...e,state:a};a=e.state||a}return n&&n({stage:"completed",message:"Agent creation and registration complete",progressPercent:100,details:{outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.pfpTopicId,profileTopicId:a.profileTopicId,operatorId:p,state:a}}),{success:!0,state:a,metadata:{accountId:c.accountId,privateKey:c.privateKey,operatorId:p,inboundTopicId:a.inboundTopicId,outboundTopicId:a.outboundTopicId,profileTopicId:a.profileTopicId,pfpTopicId:a.pfpTopicId}}}catch(mxe){const i=mxe,n=`Failed to create and register agent: ${i.message}`;return this.logger.error(n),{error:i.message,success:!1,state:t?.existingState||{currentStage:"init",completedPercentage:0,error:i.message}}}}async registerAgentWithGuardedRegistry(e,t=this.network,i){try{this.logger.info("Registering agent with guarded registry");const n=i?.maxAttempts??60,r=i?.delayMs??2e3,a=i?.progressCallback;let s=i?.existingState||{currentStage:"registration",completedPercentage:0,createdResources:[]};a&&a({stage:"preparing",message:"Preparing agent registration",progressPercent:10,details:{state:s}});const c=await this.executeRegistration(e,t,this.guardedRegistryBaseUrl,this.logger);if(!c.success)return{...c,state:s};if(a&&a({stage:"submitting",message:"Submitting registration to registry",progressPercent:30,details:{transactionId:c.transactionId,state:s}}),c.transaction){const e=o.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")}a&&a({stage:"confirming",message:"Confirming registration transaction",progressPercent:60,details:{accountId:e,transactionId:c.transactionId,state:s}});const p=await this.waitForRegistrationConfirmation(c.transactionId,t,this.guardedRegistryBaseUrl,n,r,this.logger);return s.currentStage="complete",s.completedPercentage=100,s.createdResources||(s.createdResources=[]),c.transactionId&&s.createdResources.push(`registration:${c.transactionId}`),a&&a({stage:"completed",message:"Agent registration complete",progressPercent:100,details:{confirmed:p,transactionId:c.transactionId,state:s}}),{...c,confirmed:p,state:s}}catch(mxe){const t=mxe,i=`Failed to register agent: ${t.message}`;return this.logger.error(i),{error:t.message,success:!1}}}async registerAgent(e,t,i,n,o){this.logger.info("Registering agent");const r={p:"hcs-10",op:"register",account_id:t,inbound_topic_id:i,m:n};await this.submitPayload(e,r,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 v0.PUBLIC;if(t.fee_schedule_key&&t.fee_schedule_key.key&&t.custom_fees){const i=t.custom_fees;if(i&&i.fixed_fees&&i.fixed_fees.length>0)return this.logger.info(`Topic ${e} is fee-based with ${i.fixed_fees.length} custom fees`),v0.FEE_BASED}return v0.CONTROLLED}catch(mxe){const t=`Error determining topic type: ${mxe.message}`;throw this.logger.error(t),new Error(t)}}getNetwork(){return this.network}getLogger(){return this.logger}getOperatorAccountId(){return this.client.operatorAccountId?.toString()??null}async createScheduledTransaction(e,t,i,n){this.logger.info("Creating scheduled transaction");const r=(new o.ScheduleCreateTransaction).setScheduledTransaction(e).setPayerAccountId(n?o.AccountId.fromString(n):this.client.operatorAccountId);if(t&&r.setScheduleMemo(t),i){const e=f.addSeconds(new Date,i),t=o.Timestamp.fromDate(e);r.setExpirationTime(t)}this.logger.debug("Executing schedule create transaction");const a=await r.execute(this.client),s=await a.getReceipt(this.client);if(!s.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=s.scheduleId.toString(),p=a.transactionId.toString();return this.logger.info(`Scheduled transaction created successfully: ${c}`),{scheduleId:c,transactionId:p}}async sendTransactionOperation(e,t,i,n,o){const r=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),a={p:"hcs-10",op:"transaction",operator_id:await this.getOperatorId(),schedule_id:t,data:i,m:o?.memo};return this.logger.info("Submitting transaction operation to connection topic",a),await this.submitPayload(e,a,n,r.requiresFee)}async sendTransaction(e,t,i,n){this.logger.info("Creating scheduled transaction and sending transaction operation");const{scheduleId:o,transactionId:r}=await this.createScheduledTransaction(t,n?.scheduleMemo,n?.expirationTime,n?.schedulePayerAccountId);return{scheduleId:o,transactionId:r,receipt:await this.sendTransactionOperation(e,o,i,n?.submitKey,{memo:n?.operationMemo})}}async createCommunicationTopics(e,t,i){let n=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};if(i&&i.preparing("Starting communication topic creation",0,{state:n}),!n.outboundTopicId){n.currentStage="topics",i&&i.preparing("Creating outbound topic",5,{state:n});const o=this._generateHcs10Memo(F0.OUTBOUND,{ttl:t?.ttl,accountId:e}),r=await this.createTopic(o,!0,!0);n.outboundTopicId=r,n.createdResources&&n.createdResources.push(`outbound:${n.outboundTopicId}`)}if(!n.inboundTopicId){n.currentStage="topics",i&&i.preparing("Creating inbound topic",10,{state:n});const o=this._generateHcs10Memo(F0.INBOUND,{ttl:t?.ttl,accountId:e}),r=await this.createTopic(o,!0,!1);n.inboundTopicId=r,n.createdResources&&n.createdResources.push(`inbound:${n.inboundTopicId}`)}return{inboundTopicId:n.inboundTopicId,outboundTopicId:n.outboundTopicId,state:n}}async handleProfilePictureCreation(e,t,i,n){i.currentStage="pfp",n.preparing("Creating profile picture",30,{state:i}),n.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 r=o.pfpTopicId;return i.pfpTopicId=r,i.createdResources&&i.createdResources.push(`pfp:${i.pfpTopicId}`),n.preparing("Profile picture created",50,{state:i}),r}async createAndInscribeProfile(e,t,i,n,o,r,a,s){if(this.logger.info("Creating and inscribing profile"),n.profileTopicId)s&&s.preparing(`Using existing ${e?"agent":"person"} profile`,95,{state:n});else{let c;if(s&&s.preparing(`Storing HCS-11 ${e?"agent":"person"} profile`,80),s?.createSubProgress({minPercent:80,maxPercent:95,logPrefix:"StoreProfile"}),e){const e=t.build(),n=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:i?`hcs://1/${i}`:void 0,socials:n,properties:e.metadata?.properties||{},inboundTopicId:o,outboundTopicId:r,creator:e.metadata?.creator})}else{const e=t.build(),{pfpBuffer:n,pfpFileName:a,...s}=e;c=this.hcs11Client.createPersonalProfile(e.display_name,{alias:e.alias,bio:e.bio,socials:e.socials,profileImage:i?`hcs://1/${i}`:e.profileImage,properties:e.properties,inboundTopicId:o,outboundTopicId:r})}const p=await this.hcs11Client.createAndInscribeProfile(c,a?.updateAccountMemo??!0);if(!p.success){s&&s.failed(`Failed to inscribe ${e?"agent":"person"} profile`,{error:p.error});let t=`Failed to inscribe ${e?"agent":"person"} profile`;throw p.error&&(t=p.error),new Error(t)}n.profileTopicId=p.profileTopicId,n.createdResources&&n.createdResources.push(`profile:${p.profileTopicId}`),s&&s.preparing("HCS-11 Profile stored",95,{state:n})}}async createMCPServer(e,t=60,i,n){this.keyType||await this.initializeOperator();const o=e.build(),r=this.client.operatorAccountId?.toString();if(!r)throw new Error("Failed to retrieve operator account ID");const a=await this._createEntityTopics(t,{outboundTopicId:i?.outboundTopicId||"",inboundTopicId:i?.inboundTopicId||"",pfpTopicId:i?.pfpTopicId||o.existingPfpTopicId||"",profileTopicId:i?.profileTopicId||""},r,v0.PUBLIC,void 0,o.pfpBuffer,o.pfpFileName,n);if(a.profileTopicId)this.logger.info(`Using existing profile topic ID: ${a.profileTopicId}`);else{this.logger.info("Creating and storing HCS-11 MCP server profile"),n&&n({stage:"preparing",message:"Creating MCP server profile",progressPercent:60,details:{outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.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:a.inboundTopicId,outboundTopicId:a.outboundTopicId,profileImage:a.pfpTopicId?`hcs://1/${a.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");a.profileTopicId=t.profileTopicId,this.logger.info(`MCP server profile stored with topic ID: ${a.profileTopicId}`);const i=await this.hcs11Client.updateAccountMemoWithProfile(r,a.profileTopicId);i.success?this.logger.info("Updated account memo with profile reference"):this.logger.warn(`Failed to update account memo: ${i.error}, but continuing with MCP server creation`),n&&n({stage:"preparing",message:"MCP server profile created",progressPercent:70,details:{outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.pfpTopicId,profileTopicId:a.profileTopicId,state:{currentStage:"profile",completedPercentage:70}}})}return a}async _createEntityTopics(e,t,i,n,o,r,a,s){let{outboundTopicId:c,inboundTopicId:p,pfpTopicId:l,profileTopicId:u}=t;if(c)this.logger.info(`Using existing outbound topic ID: ${c}`);else{const t=this._generateHcs10Memo(F0.OUTBOUND,{ttl:e});c=await this.createTopic(t,!0,!0),this.logger.info(`Created new outbound topic ID: ${c}`),s&&s({stage:"preparing",message:"Created outbound topic",progressPercent:30,details:{outboundTopicId:c,state:{currentStage:"topics",completedPercentage:30}}})}if(p?this.logger.info(`Using existing inbound topic ID: ${p}`):(p=await this.createInboundTopic(i,n,e,n===v0.FEE_BASED?o:void 0),this.logger.info(`Created new inbound topic ID: ${p}`),s&&s({stage:"preparing",message:"Created inbound topic",progressPercent:40,details:{outboundTopicId:c,inboundTopicId:p,state:{currentStage:"topics",completedPercentage:40}}})),!l&&r&&r.length>0&&a){this.logger.info("Inscribing new profile picture"),s&&s({stage:"preparing",message:"Inscribing profile picture",progressPercent:50,details:{outboundTopicId:c,inboundTopicId:p,state:{currentStage:"pfp",completedPercentage:50}}});l=(await this.inscribePfp(r,a)).pfpTopicId,this.logger.info(`Profile picture inscribed with topic ID: ${l}`),s&&s({stage:"preparing",message:"Profile picture inscribed",progressPercent:55,details:{outboundTopicId:c,inboundTopicId:p,pfpTopicId:l,state:{currentStage:"pfp",completedPercentage:55}}})}else l&&this.logger.info(`Using existing profile picture with topic ID: ${l}`);return{inboundTopicId:p,outboundTopicId:c,pfpTopicId:l,profileTopicId:u}}async createAndRegisterMCPServer(e,t){try{const i=e.build(),n=t?.progressCallback,r=t?.baseUrl||this.guardedRegistryBaseUrl;let a=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};a.serverMetadata={name:i.name,description:i.mcpServer.description,services:i.mcpServer.services},n&&n({stage:"preparing",message:"Starting MCP server creation process",progressPercent:0,details:{state:a}});let s,c=i.existingAccount;if(a.inboundTopicId&&a.outboundTopicId&&a.profileTopicId){if(c=c||i.existingAccount,!c)throw new Error("Cannot resume registration without account information");const e=C(c.privateKey),t=("ed25519"===e.detectedType?o.PrivateKey.fromStringED25519(c.privateKey):o.PrivateKey.fromStringECDSA(c.privateKey)).publicKey.toString();s=new w0({network:i.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:t,keyType:e.detectedType,logLevel:"info",guardedRegistryBaseUrl:r}),this.logger.info("Resuming registration with existing state",{inboundTopicId:a.inboundTopicId,outboundTopicId:a.outboundTopicId,profileTopicId:a.profileTopicId,pfpTopicId:a.pfpTopicId})}else{if(!c)if(a.createdResources&&a.createdResources.some(e=>e.startsWith("account:"))){const e=a.createdResources.find(e=>e.startsWith("account:")),n=e?.split(":")[1];n&&i.existingAccount?(c=i.existingAccount,this.logger.info(`Resuming with existing account: ${n}`)):(c=await this.createAccount(t?.initialBalance),a.createdResources=a.createdResources||[],a.createdResources.push(`account:${c.accountId}`))}else c=await this.createAccount(t?.initialBalance),a.createdResources=a.createdResources||[],a.createdResources.push(`account:${c.accountId}`);n&&n({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:a,account:c}});const p=C(c.privateKey);e.setExistingAccount(c.accountId,c.privateKey);const l=("ed25519"===p.detectedType?o.PrivateKey.fromStringED25519(c.privateKey):o.PrivateKey.fromStringECDSA(c.privateKey)).publicKey.toString();s=new w0({network:i.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:l,logLevel:"info",guardedRegistryBaseUrl:r}),n&&n({stage:"preparing",message:"Initialized MCP server client",progressPercent:25,details:{state:a}});let u=a.outboundTopicId,d=a.inboundTopicId,f=a.pfpTopicId,m=a.profileTopicId;if(!u||!d||!m){f&&e.setExistingProfilePicture(f);const t=await s.createMCPServer(e,60,a,e=>{n&&n({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:{...e.details,state:{...a,...e.details?.state}}})});u=t.outboundTopicId,d=t.inboundTopicId,f=t.pfpTopicId,m=t.profileTopicId,a.outboundTopicId=u,a.inboundTopicId=d,a.pfpTopicId=f,a.profileTopicId=m,a.createdResources||(a.createdResources=[]),f&&!a.createdResources.includes(`pfp:${f}`)&&a.createdResources.push(`pfp:${f}`),a.createdResources.includes(`inbound:${d}`)||a.createdResources.push(`inbound:${d}`),a.createdResources.includes(`outbound:${u}`)||a.createdResources.push(`outbound:${u}`),a.createdResources.includes(`profile:${m}`)||a.createdResources.push(`profile:${m}`)}a.currentStage="profile",a.completedPercentage=60,n&&n({stage:"submitting",message:"Created MCP server with topics and profile",progressPercent:60,details:{state:a,outboundTopicId:u,inboundTopicId:d,pfpTopicId:f,profileTopicId:m}})}const p=`${a.inboundTopicId}@${c.accountId}`;if("complete"!==a.currentStage||!a.createdResources?.includes(`registration:${a.inboundTopicId}`)){const e=await s.registerAgentWithGuardedRegistry(c.accountId,i.network,{progressCallback:e=>{const t=60+.4*(e.progressPercent||0);n&&n({stage:e.stage,message:e.message,progressPercent:t,details:{...e.details,outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.pfpTopicId,profileTopicId:a.profileTopicId,operatorId:p,state:e.details?.state||a}})},existingState:a});if(!e.success)return{...e,state:a};a=e.state||a}return n&&n({stage:"completed",message:"MCP server creation and registration complete",progressPercent:100,details:{outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.pfpTopicId,profileTopicId:a.profileTopicId,operatorId:p,state:a}}),{success:!0,state:a,metadata:{accountId:c.accountId,privateKey:c.privateKey,operatorId:p,inboundTopicId:a.inboundTopicId,outboundTopicId:a.outboundTopicId,profileTopicId:a.profileTopicId,pfpTopicId:a.pfpTopicId}}}catch(mxe){const i=mxe,n=`Failed to create and register MCP server: ${i.message}`;return this.logger.error(n),{error:i.message,success:!1,state:t?.existingState||{currentStage:"init",completedPercentage:0,error:i.message}}}}async createRegistryTopic(e={}){const{ttl:t=86400,metadata:i,adminKey:n=!1,submitKey:r=!1,waitForConfirmation:a=!0,waitMaxAttempts:s=30,waitIntervalMs:c=4e3,progressCallback:p}=e;try{let e;if(this.keyType||await this.initializeOperator(),p&&p({stage:"preparing",message:"Preparing registry topic creation",progressPercent:10,details:{metadata:!!i}}),i){this.logger.info("Creating metadata inscription for registry"),p&&p({stage:"submitting",message:"Creating registry metadata inscription",progressPercent:30,details:{metadataName:i.name}});const t=globalThis.Buffer.from(JSON.stringify(i,null,2)),n={mode:"file",waitForConfirmation:a,waitMaxAttempts:s,waitIntervalMs:c,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},o=await lQ({type:"buffer",buffer:t,fileName:`registry-metadata-${Date.now()}.json`,mimeType:"application/json"},{accountId:this.client.operatorAccountId.toString(),privateKey:this.operatorPrivateKey.toString(),network:this.network},n);if(!o.confirmed||!o.inscription)throw new Error("Metadata inscription was not confirmed");e=yQ(o.inscription),this.logger.info(`Metadata inscribed to topic: ${e}`)}p&&p({stage:"submitting",message:"Creating registry topic",progressPercent:60,details:{metadataTopicId:e}});const l=`hcs-10:0:${t}:3${e?`:${e}`:""}`,u="ecdsa"===this.keyType?o.PrivateKey.fromStringECDSA(this.operatorPrivateKey):o.PrivateKey.fromStringED25519(this.operatorPrivateKey);let d=(new o.TopicCreateTransaction).setTopicMemo(l);n&&(d=d.setAdminKey(u.publicKey)),r&&(d=d.setSubmitKey(u.publicKey));const f=await d.execute(this.client),m=await f.getReceipt(this.client),h=m.topicId?.toString();if(!h)throw new Error("Failed to create registry topic");return p&&p({stage:"completed",message:"Registry topic created successfully",progressPercent:100,details:{topicId:h,metadataTopicId:e,transactionId:f.transactionId.toString()}}),this.logger.info(`Registry topic created successfully: ${h}`),{success:!0,topicId:h,transactionId:f.transactionId.toString(),metadataTopicId:e}}catch(l){const e=l instanceof Error?l.message:"Unknown error";return p&&p({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}}}}class k0{constructor(e){this.registry=e?.registry??o0,this.issuers=new r0,this.registerHederaIssuer(),this.client=e?.client,this.network=e?.network,this.operatorId=e?.operatorId,!this.client&&e?.network&&e?.operatorId&&e?.privateKey&&this.configureHederaClient(e.network,e.operatorId,e.privateKey),e?.privateKey&&(this.operatorPrivateKey=e.privateKey),e?.hcs10Client&&(this.hcs10Client=e.hcs10Client)}configureHederaClient(e,t,i){const n=o.Client.forName(e),r=C(i);n.setOperator(t,r.privateKey),(async()=>{try{const a=new I(e),s=await a.requestAccount(t),c=s?.key?._type||"",p=c.includes("ECDSA"),l=c.includes("ED25519");p&&"ecdsa"!==r.detectedType?n.setOperator(t,o.PrivateKey.fromStringECDSA(i)):l&&"ed25519"!==r.detectedType&&n.setOperator(t,o.PrivateKey.fromStringED25519(i))}catch{}})(),this.client=n,this.network=e,this.operatorId=t,this.operatorPrivateKey=i}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 s0)}async createDid(e){return this.issuers.issue(e)}canonicalizeAgentData(e){return GQ(e)}createUaid(e,t,i){return"string"==typeof e?e0(e,t):e0(e,t,i)}parseHcs14Did(e){return t0(e)}isHederaNetwork(e){return UQ(e)}isHederaCaip10(e){return MQ(e)}toHederaCaip10(e,t){return DQ(e,t)}parseHederaCaip10(e){return zQ(e)}isEip155Caip10(e){return qQ(e)}toEip155Caip10(e,t){return KQ(e,t)}getResolverRegistry(){return this.registry}registerHederaResolver(){this.registry.register(new i0)}async createDidWithUaid(e){const t=await this.createDid(e.issue);let i=e.uid;const n=e.proto;let o=e.nativeId;if("hedera"===e.issue.method){if(!o){if(!this.network||!this.operatorId)throw new Error("nativeId not provided and network/operatorId are not configured");o=DQ(this.network,this.operatorId)}if(!i&&"hcs-10"===n&&this.network&&this.operatorId)try{if(!this.hcs10Client&&this.operatorPrivateKey&&(this.hcs10Client=new w0({network:this.network,operatorId:this.operatorId,operatorPrivateKey:this.operatorPrivateKey,silent:!0})),this.hcs10Client)i=await this.hcs10Client.getOperatorId();else{const e=new L0({network:this.network,auth:{operatorId:this.operatorId},silent:!0}),t=await e.fetchProfileByAccountId(this.operatorId,this.network),n=t?.topicInfo?.inboundTopic;i=n?`${n}@${this.operatorId}`:this.operatorId}}catch{i=this.operatorId}}i=i??"0";const r=this.createUaid(t,{uid:i,proto:n,nativeId:o});return{did:t,uaid:r,parsed:t0(r)}}}const _0=n.z.object({platform:n.z.string().min(1),handle:n.z.string().min(1)}),E0=n.z.object({type:n.z.nativeEnum(f0),capabilities:n.z.array(n.z.nativeEnum(h0)).min(1),model:n.z.string().min(1),creator:n.z.string().optional()}),S0=n.z.object({url:n.z.string().min(1),transport:n.z.enum(["stdio","sse"])}),T0=n.z.object({type:n.z.nativeEnum(y0),value:n.z.string(),dns_field:n.z.string().optional(),challenge_path:n.z.string().optional()}),A0=n.z.object({minVersion:n.z.string().optional()}),I0=n.z.object({name:n.z.string().min(1),description:n.z.string().min(1)}),R0=n.z.object({name:n.z.string().min(1),description:n.z.string().min(1)}),O0=n.z.object({version:n.z.string().min(1),connectionInfo:S0,services:n.z.array(n.z.nativeEnum(g0)).min(1),description:n.z.string().min(1),verification:T0.optional(),host:A0.optional(),capabilities:n.z.array(n.z.string()).optional(),resources:n.z.array(I0).optional(),tools:n.z.array(R0).optional(),maintainer:n.z.string().optional(),repository:n.z.string().optional(),docs:n.z.string().optional()}),j0=n.z.object({version:n.z.string().min(1),type:n.z.nativeEnum(d0),display_name:n.z.string().min(1),alias:n.z.string().optional(),bio:n.z.string().optional(),socials:n.z.array(_0).optional(),profileImage:n.z.string().optional(),uaid:n.z.string().optional(),properties:n.z.record(n.z.any()).optional(),inboundTopicId:n.z.string().optional(),outboundTopicId:n.z.string().optional()}),C0=j0.extend({type:n.z.literal(d0.PERSONAL),language:n.z.string().optional(),timezone:n.z.string().optional()}),N0=j0.extend({type:n.z.literal(d0.AI_AGENT),aiAgent:E0}),B0=j0.extend({type:n.z.literal(d0.MCP_SERVER),mcpServer:O0}),P0=n.z.union([C0,N0,B0]);class L0{constructor(e){if(this.client="mainnet"===e.network?o.Client.forMainnet():o.Client.forTestnet(),this.auth=e.auth,this.network=e.network,this.operatorId=e.auth.operatorId,this.logger=y.getInstance({level:e.logLevel||"info",module:"HCS-11",silent:e.silent}),this.mirrorNode=new I(this.network,this.logger),this.auth.privateKey)if(e.keyType)this.keyType=e.keyType,this.initializeOperatorWithKeyType();else{try{const e=C(this.auth.privateKey);this.keyType=e.detectedType,e.warning&&this.logger.warn(e.warning),this.client.setOperator(this.operatorId,e.privateKey)}catch(t){this.logger.warn("Failed to detect key type from private key format, will query mirror node"),this.keyType="ecdsa"}this.initializeOperator()}}getClient(){return this.client}getOperatorId(){return this.auth.operatorId}async initializeOperator(){const e=await this.mirrorNode.requestAccount(this.operatorId),t=e?.key?._type;t&&t.includes("ECDSA")?this.keyType="ecdsa":t&&t.includes("ED25519")?this.keyType="ed25519":this.keyType="ecdsa",this.initializeOperatorWithKeyType()}initializeOperatorWithKeyType(){if(!this.auth.privateKey)return;const e="ecdsa"===this.keyType?o.PrivateKey.fromStringECDSA(this.auth.privateKey):o.PrivateKey.fromStringED25519(this.auth.privateKey);this.client.setOperator(this.operatorId,e)}createPersonalProfile(e,t){return{version:"1.0",type:d0.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}}createAIAgentProfile(e,t,i,n,o){const r=this.validateProfile({version:"1.0",type:d0.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,aiAgent:{type:t,capabilities:i,model:n,creator:o?.creator}});if(!r.valid)throw new Error(`Invalid AI Agent Profile: ${r.errors.join(", ")}`);return{version:"1.0",type:d0.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,aiAgent:{type:t,capabilities:i,model:n,creator:o?.creator}}}createMCPServerProfile(e,t,i){const n=this.validateProfile({version:"1.0",type:d0.MCP_SERVER,display_name:e,alias:i?.alias,bio:i?.bio,socials:i?.socials,profileImage:i?.profileImage,properties:i?.properties,inboundTopicId:i?.inboundTopicId,outboundTopicId:i?.outboundTopicId,mcpServer:t});if(!n.valid)throw new Error(`Invalid MCP Server Profile: ${n.errors.join(", ")}`);return{version:"1.0",type:d0.MCP_SERVER,display_name:e,alias:i?.alias,bio:i?.bio,socials:i?.socials,profileImage:i?.profileImage,properties:i?.properties,inboundTopicId:i?.inboundTopicId,outboundTopicId:i?.outboundTopicId,mcpServer:t}}validateProfile(e){const t=P0.safeParse(e);if(t.success)return{valid:!0,errors:[]};return{valid:!1,errors:t.error.errors.map(e=>{const t=e.path.join(".");let i=e.message;if("invalid_type"===e.code)i=`Expected ${e.expected}, got ${e.received}`;else if("invalid_enum_value"===e.code){const t=e.options?.join(", ");i=`Invalid value. Valid options are: ${t}`}else"too_small"===e.code&&"string"===e.type&&(i="Cannot be empty");return`${t}: ${i}`})}}profileToJSONString(e){return JSON.stringify(e)}parseProfileFromString(e){try{const t=JSON.parse(e),i=this.validateProfile(t);return i.valid?t:(this.logger.error("Invalid profile format:",i.errors),null)}catch(t){return this.logger.error("Error parsing profile:"),null}}setProfileForAccountMemo(e,t=1){return`hcs-11:hcs://${t}/${e}`}async executeTransaction(e){try{if(this.auth.privateKey){const t=await e.signWithOperator(this.client),i=await t.execute(this.client),n=await i.getReceipt(this.client);return n.status.toString()!==o.Status.Success.toString()?{success:!1,error:`Transaction failed: ${n.status.toString()}`}:{success:!0,result:n}}if(!this.auth.signer)throw new Error("No valid authentication method provided");const t=this.auth.signer,i=await e.freezeWithSigner(t),n=await i.executeWithSigner(t),r=await n.getReceiptWithSigner(t);return r.status.toString()!==o.Status.Success.toString()?{success:!1,error:`Transaction failed: ${r.status.toString()}: ${o.Status.Success.toString()}`}:{success:!0,result:r}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error during transaction execution"}}}async inscribeImage(e,t,i){try{const n=i?.progressCallback,r=new WY({module:"HCS11-Image",logger:this.logger,callback:n});r.preparing("Preparing to inscribe image",0);const a=h.lookup(t)||"application/octet-stream",s=i?.waitForConfirmation??!0;let c;if(this.auth.signer){if(!("accountId"in this.auth.signer))throw r.failed("Signer must be a DAppSigner for inscription"),new Error("Signer must be a DAppSigner for inscription");r.preparing("Using signer for inscription",10),c=await uQ({type:"buffer",buffer:e,fileName:t,mimeType:a},this.auth.signer,{network:this.network,waitForConfirmation:s,waitMaxAttempts:150,waitIntervalMs:4e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);r.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}else{if(!this.auth.privateKey)throw r.failed("Private key is required for inscription"),this.logger.error("Private key is required for inscription"),new Error("Private key is required for inscription");r.preparing("Using private key for inscription",10);const i="ecdsa"===this.keyType?o.PrivateKey.fromStringECDSA(this.auth.privateKey):o.PrivateKey.fromStringED25519(this.auth.privateKey);c=await lQ({type:"buffer",buffer:e,fileName:t,mimeType:a},{accountId:this.auth.operatorId,privateKey:i,network:this.network},{waitForConfirmation:s,waitMaxAttempts:150,waitIntervalMs:2e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);r.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}if(c.confirmed)return r.completed("Image inscription completed",{topicId:yQ(c.inscription)}),{imageTopicId:yQ(c.inscription)||"",transactionId:c.result.jobId,success:!0};{const e=c.quote?"quote-only":c.result.jobId;return r.verifying("Waiting for inscription confirmation",50,{jobId:e}),{imageTopicId:"",transactionId:e,success:!1,error:"Inscription not confirmed"}}}catch(n){return this.logger.error("Error inscribing image:",n),{imageTopicId:"",transactionId:"",success:!1,error:n instanceof Error?n.message:"Error inscribing image"}}}async inscribeProfile(e,t){this.logger.info("Inscribing HCS-11 profile");const i=t?.progressCallback,n=new WY({module:"HCS11-Profile",logger:this.logger,callback:i});await this.attachUaidIfMissing(e),n.preparing("Validating profile data",5);const r=this.validateProfile(e);if(!r.valid)return n.failed(`Invalid profile: ${r.errors.join(", ")}`),{profileTopicId:"",transactionId:"",success:!1,error:`Invalid profile: ${r.errors.join(", ")}`};n.preparing("Formatting profile for inscription",15);const a=this.profileToJSONString(e),s=`profile-${e.display_name.toLowerCase().replace(/\s+/g,"-")}.json`;try{const e=globalThis.Buffer.from(a,"utf-8"),t="application/json";n.preparing("Preparing profile for inscription",20);const i={type:"buffer",buffer:e,fileName:s,mimeType:t},r={waitForConfirmation:!0,mode:"file",network:this.network,waitMaxAttempts:100,waitIntervalMs:2e3,progressCallback:e=>{const t=20+.75*Number(e?.progressPercent||0);n?.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}};let c;if(n.submitting("Submitting profile to Hedera network",30),this.auth.privateKey){const e="ecdsa"===this.keyType?o.PrivateKey.fromStringECDSA(this.auth.privateKey):o.PrivateKey.fromStringED25519(this.auth.privateKey);c=await lQ(i,{accountId:this.auth.operatorId,privateKey:e,network:this.network},r)}else{if(!this.auth.signer)throw new Error("No authentication method available - neither private key nor signer");c=await uQ(i,this.auth.signer,r)}if(!c.confirmed||!yQ(c.inscription))return n.failed("Failed to inscribe profile content"),{profileTopicId:"",transactionId:"",success:!1,error:"Failed to inscribe profile content"};const p=yQ(c.inscription);return n.completed("Profile inscription completed",{topicId:p,transactionId:c.result.transactionId}),{profileTopicId:p,transactionId:c.result.transactionId,success:!0}}catch(c){return n.failed(`Error inscribing profile: ${c.message||"Unknown error"}`),{profileTopicId:"",transactionId:"",success:!1,error:c.message||"Unknown error during inscription"}}}async attachUaidIfMissing(e){if(!e.uaid&&UQ(this.network))try{const t=new k0({client:this.client}),i=await t.createDid({method:"hedera",client:this.client}),n=DQ(this.network,this.auth.operatorId);let o=this.auth.operatorId;const r=e.inboundTopicId;if(r&&r.trim().length>0)o=`${r}@${this.auth.operatorId}`;else try{const e=await this.fetchProfileByAccountId(this.auth.operatorId,this.network),t=e?.topicInfo?.inboundTopic;t&&t.trim().length>0&&(o=`${t}@${this.auth.operatorId}`)}catch{}const a=t.createUaid(i,{proto:"hcs-10",nativeId:n,uid:o});e.uaid=a}catch{this.logger.warn("Hiero registrar not available; skipping UAID generation for profile")}}async updateAccountMemoWithProfile(e,t){try{this.logger.info(`Updating account memo for ${e} with profile ${t}`);const i=this.setProfileForAccountMemo(t),n=(new o.AccountUpdateTransaction).setAccountMemo(i).setAccountId(e);return this.executeTransaction(n)}catch(i){return this.logger.error(`Error updating account memo: ${i instanceof Error?i.message:"Unknown error"}`),{success:!1,error:i instanceof Error?i.message:"Unknown error updating account memo"}}}async createAndInscribeProfile(e,t=!0,i){const n=i?.progressCallback,o=new WY({module:"HCS11-ProfileCreation",logger:this.logger,callback:n});o.preparing("Starting profile creation process",0);const r=o.createSubProgress({minPercent:0,maxPercent:80,logPrefix:"Inscription"}),a=await this.inscribeProfile(e,{...i,progressCallback:e=>{r.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent,details:e.details})}});if(!a?.success)return o.failed("Profile inscription failed",{error:a?.error}),a;if(o.confirming("Profile inscribed, updating account memo",85),t){const e=await this.updateAccountMemoWithProfile(this.auth.operatorId,a.profileTopicId);if(!e.success)return o.failed("Failed to update account memo",{error:e?.error}),{...a,success:!1,error:e?.error}}return o.completed("Profile creation completed successfully",{profileTopicId:a.profileTopicId,transactionId:a.transactionId}),a}async getCapabilitiesFromTags(e){const t=[];if(0===e.length)return[h0.TEXT_GENERATION];for(const i of e){const e=b0[i.toLowerCase()];void 0===e||t.includes(e)||t.push(e)}return 0===t.length&&t.push(h0.TEXT_GENERATION),t}getAgentTypeFromMetadata(e){return"autonomous"===e.type?f0.AUTONOMOUS:f0.MANUAL}async fetchProfileByAccountId(e,t){try{this.logger.debug(`Fetching profile for account ${e.toString()} on ${this.network}`);const n=await this.mirrorNode.getAccountMemo(e.toString());if(this.logger.debug(`Got account memo: ${n}`),!n?.startsWith("hcs-11:"))return{success:!1,error:`Account ${e.toString()} does not have a valid HCS-11 memo. Current memo: ${n||"empty"}`};this.logger.debug(`Found HCS-11 memo: ${n}`);const o=n.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(),i=P0.safeParse(t);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 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 i=await t.json(),n=P0.safeParse(i);return n.success?{success:!0,profile:n.data,topicInfo:{inboundTopic:n.data.inboundTopicId||"",outboundTopic:n.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[n,r,a]=e,s=t||this.network||"mainnet";this.logger.debug(`Retrieving profile from Kiloscribe CDN: ${a}`);const c=`https://kiloscribe.com/api/inscription-cdn/${a}?network=${s}`;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 ${a}`};const i=P0.safeParse(t);return i.success?{success:!0,profile:i.data,topicInfo:{inboundTopic:i.data.inboundTopicId||"",outboundTopic:i.data.outboundTopicId||"",profileTopicId:a}}:{success:!1,error:`Invalid HCS-11 profile data for topic ${a}`}}catch(i){return this.logger.error(`Error retrieving from Kiloscribe CDN: ${i.message}`),{success:!1,error:`Error retrieving from Kiloscribe CDN: ${i.message}`}}}}catch(n){return this.logger.error(`Error fetching profile: ${n.message}`),{success:!1,error:`Error fetching profile: ${n.message}`}}}}class U0{async checkRegistrationStatus(e,t,i,n){try{const o=await fetch(`${i}/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 n&&n.error(e),new Error(e)}return await o.json()}catch(o){throw n&&n.error(`Error checking registration status: ${o.message}`),o}}async waitForRegistrationConfirmation(e,t,i,n=60,o=2e3,r){let a=0;for(;a<n;){r&&r.info(`Checking registration status. Attempt ${a+1}/${n}`);const s=await this.checkRegistrationStatus(e,t,i,r);if("success"===s.status)return r&&r.info("Registration confirmed successfully"),!0;if("failed"===s.status)throw r&&r.error("Registration confirmation failed"),new Error("Registration confirmation failed");r&&r.info(`Registration still pending. Waiting ${o}ms before next attempt`),await new Promise(e=>setTimeout(e,o)),a++}return r&&r.warn(`Registration not confirmed after ${n} attempts`),!1}async executeRegistration(e,t="mainnet",i="https://moonscape.tech",n){try{n&&n.info("Registering agent with guarded registry");try{const i=new L0({network:t,auth:{operatorId:"0.0.0"}});n?.info(`Fetching profile by account ID ${e} on ${t}`),await v(5e3);const o=await i.fetchProfileByAccountId(e,t);if(n?.info("Profile fetched",o),o?.error)return n?.error("Error fetching profile",o.error),{error:o.error,success:!1};if(!o?.success||!o?.profile)return n&&n.error("Profile not found for agent registration"),{error:"Profile not found for the provided account ID",success:!1};if(!o.profile.inboundTopicId)return n&&n.error("Missing inbound topic ID in profile"),{error:"Profile is missing required inbound topic ID",success:!1};if(!o.profile.outboundTopicId)return n&&n.error("Missing outbound topic ID in profile"),{error:"Profile is missing required outbound topic ID",success:!1};n&&n.info(`Profile validation successful. Inbound topic: ${o.profile.inboundTopicId}, Outbound topic: ${o.profile.outboundTopicId}`)}catch(o){return n&&n.error(`Error validating profile: ${o.message}`),{error:`Error validating profile: ${o.message}`,success:!1}}const r=await fetch(`${i}/api/request-register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"*/*","Accept-Language":"en;q=0.5",Origin:i,Referer:`${i}/`,"X-Network":t},body:JSON.stringify({accountId:e})}),a=await r.json();return r.ok?(n&&n.info(`Created new registration request. Transaction ID: ${a.transaction_id}`),{transactionId:a.transaction_id,transaction:a.transaction,success:!0}):a.details?.length>0?{validationErrors:a.details,error:a.error||"Validation failed",success:!1}:{error:a.error||"Failed to register agent",success:!1}}catch(r){return{error:`Error during registration request: ${r.message}`,success:!1}}}async findRegistrations(e={},t="https://moonscape.tech"){try{const i=new URLSearchParams;e.tags?.forEach(e=>i.append("tags",e.toString())),e.accountId&&i.append("accountId",e.accountId),e.network&&i.append("network",e.network);const n=await fetch(`${t}/api/registrations?${i}`,{headers:{Accept:"*/*","Accept-Language":"en;q=0.5",Origin:t,Referer:`${t}/`}});if(!n.ok){return{registrations:[],error:await n.text()||"Failed to fetch registrations",success:!1}}const o=await n.json();return o.error?{registrations:[],error:o.error,success:!1}:{registrations:o.registrations||[],success:!0}}catch(mxe){return{registrations:[],error:`Error fetching registrations: ${mxe.message}`,success:!1}}}}var F0=(e=>(e.INBOUND="inbound",e.OUTBOUND="outbound",e.CONNECTION="connection",e.REGISTRY="registry",e))(F0||{});class M0 extends U0{constructor(e){super(),this.network=e.network,this.logger=y.getInstance({level:e.logLevel||"info",module:"HCS10-BaseClient",prettyPrint:e.prettyPrint,silent:e.silent}),this.mirrorNode=new I(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 i=await this.mirrorNode.getTopicMessages(e,t),n=["message","close_connection","transaction"];return{messages:i.filter(e=>{if("hcs-10"!==e.p||!n.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(i){return this.logger&&this.logger.error(`Error fetching messages: ${i.message}`),{messages:[]}}}async getPublicTopicInfo(e){try{return await this.mirrorNode.getTopicInfo(e)}catch(t){return this.logger.error(`Error getting public topic info for ${e}:`,t),null}}async canSubmitToTopic(e,t){try{const n=await this.mirrorNode.getTopicInfo(e);if(!n)return{canSubmit:!1,requiresFee:!1,reason:"Topic does not exist"};if(!n.submit_key?.key)return{canSubmit:!0,requiresFee:!1};try{const e=await this.mirrorNode.getPublicKey(t);if("ProtobufEncoded"===n.submit_key._type){const t=globalThis.Buffer.from(n.submit_key.key,"hex");if(await this.mirrorNode.checkKeyListAccess(t,e))return{canSubmit:!0,requiresFee:!1}}else{const t=o.PublicKey.fromString(n.submit_key.key);if(e.toString()===t.toString())return{canSubmit:!0,requiresFee:!1}}}catch(i){this.logger.error(`Key validation error: ${i instanceof Error?i.message:String(i)}`)}return n.fee_schedule_key?.key&&n.custom_fees?.fixed_fees?.length>0?{canSubmit:!0,requiresFee:!0,reason:"Requires fee payment via HIP-991"}:{canSubmit:!1,requiresFee:!1,reason:"User does not have submit permission for this topic"}}catch(i){const e=i instanceof Error?i.message:String(i);return this.logger.error(`Topic submission validation error: ${e}`),{canSubmit:!1,requiresFee:!1,reason:`Error: ${e}`}}}async getMessages(e,t){try{const i=await this.mirrorNode.getTopicMessages(e,t);return{messages:i.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(i){return this.logger&&this.logger.error(`Error fetching messages: ${i.message}`),{messages:[]}}}async requestAccount(e){try{if(!e)throw new Error("Account ID is required");return await this.mirrorNode.requestAccount(e)}catch(mxe){throw this.logger.error("Failed to fetch account",mxe),mxe}}async getAccountMemo(e){return await this.mirrorNode.getAccountMemo(e)}async retrieveProfile(e,t,i){const n=i?.maxRetries??0,o=i?.retryDelay??3e3;let r=0;for(;r<=n;){this.logger.debug(`Retrieving profile for account: ${e}${r>0?` (attempt ${r+1}/${n+1})`:""}`);const i=`${e}-${this.network}`;if(!t&&0===r){const t=D0.getInstance().get(i);if(t)return this.logger.debug(`Cache hit for profile: ${e}`),t}try{const t=new L0({network:this.network,auth:{operatorId:"0.0.0"},logLevel:this.logger.getLevel()}),a=await t.fetchProfileByAccountId(e,this.network);if(!a?.success){if(r<n){this.logger.info(`Profile not found for account ${e}, retrying in ${o}ms... (${a?.error})`),r++,await new Promise(e=>setTimeout(e,o));continue}return this.logger.error(`Failed to retrieve profile for account ID: ${e}`,a?.error),{profile:null,success:!1,error:a?.error||`Failed to retrieve profile for account ID: ${e}`}}const s=a?.profile;let c=null;a?.topicInfo?.inboundTopic&&a?.topicInfo?.outboundTopic&&a?.topicInfo?.profileTopicId&&(c={inboundTopic:a.topicInfo.inboundTopic,outboundTopic:a.topicInfo.outboundTopic,profileTopicId:a.topicInfo.profileTopicId});const p={profile:s,topicInfo:c,success:!0};return D0.getInstance().set(i,p),p}catch(mxe){if(r<n){this.logger.info(`Error retrieving profile for account ${e}, retrying in ${o}ms... (${mxe.message})`),r++,await new Promise(e=>setTimeout(e,o));continue}const i=`Failed to retrieve profile: ${mxe.message}`;return this.logger.error(i),{profile:null,success:!1,error:i}}}return{profile:null,success:!1,error:"Unexpected error in profile retrieval"}}async retrieveOutboundConnectTopic(e){return await this.retrieveCommunicationTopics(e,!0)}async retrieveCommunicationTopics(e,t,i){try{const n=await this.retrieveProfile(e,t,i);if(!n?.success)throw new Error(n.error||"Failed to retrieve profile");const o=n.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(!n.topicInfo)throw new Error(`TopicInfo is missing in the profile for account ${e}`);return n.topicInfo}catch(mxe){const t=mxe,i=`Failed to retrieve topic info: ${t.message}`;throw this.logger.error(i),t}}async retrieveOutboundMessages(e,t){try{const i=await this.retrieveCommunicationTopics(e);if(!i)return this.logger.warn(`No outbound connect topic found for agentAccountId: ${e}`),[];return(await this.getMessages(i.outboundTopic,t)).messages.filter(e=>"hcs-10"===e.p&&("connection_request"===e.op||"connection_created"===e.op||"message"===e.op))}catch(mxe){const t=`Failed to retrieve outbound messages: ${mxe.message}`;return this.logger.error(t),[]}}async hasConnectionCreated(e,t){try{const i=await this.retrieveCommunicationTopics(e);return(await this.retrieveOutboundMessages(i.outboundTopic)).some(e=>"connection_created"===e.op&&e.connection_id===t)}catch(mxe){const t=`Failed to check connection created: ${mxe.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 i=new _Q(this.logger.getLevel());if(!i.isValidHRL(e))return e;return(await i.resolveHRL(e,{network:this.network,returnRaw:t})).content}catch(mxe){const t=`Error resolving HRL reference: ${mxe.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 i=new _Q(this.logger.getLevel());return await i.getContentWithType(e,{network:this.network,returnRaw:t})}catch(mxe){const t=`Error resolving HRL reference with type: ${mxe.message}`;throw this.logger.error(t),new Error(t)}}async submitConnectionRequest(e,t){const i=this.getAccountAndSigner();if(!i?.accountId)throw new Error("Operator account ID is not set");const n=await this.getOperatorId(),o=i.accountId,r=await this.canSubmitToTopic(e,o);if(!r?.canSubmit)throw new Error(`Cannot submit to topic: ${r.reason}`);const a=await this.retrieveInboundAccountId(e);if(!a)throw new Error("Failed to retrieve topic info account ID");const s={p:"hcs-10",op:"connection_request",operator_id:n,m:t},c=r.requiresFee,p=await this.submitPayload(e,s,void 0,c);this.logger.info(`Submitted connection request to topic ID: ${e}`);const l=await this.retrieveCommunicationTopics(o);if(!l)throw new Error("Failed to retrieve outbound topic");const u=p.topicSequenceNumber?.toNumber();if(!u)throw new Error("Failed to get response sequence number");const d=`${e}@${a}`;return await this.submitPayload(l.outboundTopic,{...s,outbound_topic_id:l.outboundTopic,connection_request_id:u,operator_id:d}),p}async recordOutboundConnectionConfirmation({outboundTopicId:e,requestorOutboundTopicId:t,connectionRequestId:i,confirmedRequestId:n,connectionTopicId:o,operatorId:r,memo:a}){const s={p:"hcs-10",op:"connection_created",connection_topic_id:o,outbound_topic_id:e,requestor_outbound_topic_id:t,confirmed_request_id:n,connection_request_id:i,operator_id:r,m:a};return await this.submitPayload(e,s)}async waitForConnectionConfirmation(e,t,i=60,n=2e3,o=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let r=0;r<i;r++){this.logger.info(`Attempt ${r+1}/${i} to find connection confirmation`);const a=(await this.mirrorNode.getTopicMessages(e,{order:"desc",limit:100})).filter(e=>"connection_created"===e.op);if(this.logger.info(`Found ${a.length} connection_created messages`),a.length>0)for(const e of a)if(Number(e.connection_id)===Number(t)){const i={connectionTopicId:e.connection_topic_id,sequence_number:Number(e.sequence_number),confirmedBy:e.operator_id,memo:e.m},n=this.extractAccountFromOperatorId(i.confirmedBy),r=this.getAccountAndSigner(),a=await this.retrieveCommunicationTopics(n),s=await this.retrieveCommunicationTopics(r.accountId);return this.logger.info("Connection confirmation found",i),o&&await this.recordOutboundConnectionConfirmation({requestorOutboundTopicId:a.outboundTopic,outboundTopicId:s.outboundTopic,connectionRequestId:t,confirmedRequestId:i.sequence_number,connectionTopicId:i.connectionTopicId,operatorId:i.confirmedBy,memo:i.memo||"Connection confirmed"}),i}r<i-1&&(this.logger.info(`No matching confirmation found, waiting ${n}ms before retrying...`),await new Promise(e=>setTimeout(e,n)))}throw new Error(`Connection confirmation not found after ${i} 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 i=await this.retrieveProfile(t.accountId);if(!i?.success)throw new Error("Failed to retrieve profile");if(!i?.topicInfo?.inboundTopic)throw new Error("Failed to retrieve inbound topic");const n=`${i.topicInfo?.inboundTopic}@${t.accountId}`;return this.operatorId=n,n}async retrieveInboundAccountId(e){const t=await this.mirrorNode.getTopicInfo(e);if(!t?.memo)throw new Error("Failed to retrieve topic info");const i=t.memo.toString().split(":"),n=i?.[4];if(!n)throw new Error("Failed to retrieve topic info account ID");return n}clearCache(){D0.getInstance().clear()}_generateHcs10Memo(e,t){const i=t.ttl??60;switch(e){case"inbound":if(!t.accountId)throw new Error("accountId is required for inbound memo");return`hcs-10:0:${i}:0:${t.accountId}`;case"outbound":return`hcs-10:0:${i}: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:${i}: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 i=t.memo.toString();if(!i.startsWith("hcs-10:"))return this.logger.debug(`Topic ${e} is not an HCS-10 topic`),null;const n=i.split(":");if(n.length<4)return this.logger.warn(`Invalid HCS-10 memo format for topic ${e}: ${i}`),null;const o=n[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,i){try{const n=await fetch(`${i}/api/request-confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Network":t},body:JSON.stringify({transaction_id:e})});if(!n.ok)throw new Error(`Failed to confirm registration: ${n.statusText}`);return await n.json()}catch(mxe){const t=mxe,i=`Error checking registration status: ${t.message}`;throw this.logger.error(i),t}}isValidOperatorId(e){if(!e)return!1;const t=e.split("@");if(2!==t.length)return!1;const i=t[0],n=t[1];if(!i)return!1;if(!n)return!1;const o=/^[0-9]+\.[0-9]+\.[0-9]+$/;return!!o.test(n)&&!!o.test(i)}async getTransactionRequests(e,t){this.logger.debug(`Retrieving transaction requests from topic ${e}`);const{messages:i}=await this.getMessageStream(e,{limit:t?.limit,sequenceNumber:t?.sequenceNumber,order:t?.order||"desc"}),n=i.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?n.slice(0,t.limit):n}getHcs10TransactionMemo(e){if("object"!=typeof e||!("op"in e))return null;const t=e;let i,n;switch(t.op){case"register":i="0",n="0";break;case"delete":i="1",n="0";break;case"migrate":i="2",n="0";break;case"connection_request":i="3",n=t.outbound_topic_id?"2":"1";break;case"connection_created":i="4",n=t.outbound_topic_id?"2":"1";break;case"connection_closed":i="5",n=t.outbound_topic_id?"2":"3";break;case"message":case"transaction":default:i="6",n="3";break;case"close_connection":i="5",n="3"}return`hcs-10:op:${i}:${n}`}}class D0{constructor(){this.CACHE_TTL=36e5,this.cache=new Map,this.cacheExpiry=new Map}static getInstance(){return D0.instance||(D0.instance=new D0),D0.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()}}const z0="undefined"!=typeof window;function $0(e,t){return`hcs-10:op:${e}:${t}`}var q0=(e=>(e[e.ACTION=0]="ACTION",e[e.ASSEMBLY=2]="ASSEMBLY",e[e.HASHLINKS=3]="HASHLINKS",e))(q0||{});class K0{constructor(e,t,i,n,o){this.entries=new Map,this.networkType=e,this.logger=t,this.registryType=i,this.topicId=n,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 i=t[0];let n;if(i.raw_content)n=JSON.parse(i.raw_content);else{const e=i;if("hcs-12"!==e.p||!e.op)return null;n={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(n).forEach(e=>{void 0===n[e]&&delete n[e]})}return{id:i.sequence_number.toString(),sequenceNumber:i.sequence_number,timestamp:i.consensus_timestamp||(new Date).toISOString(),submitter:i.payer||"unknown",data:n}}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:q0[this.registryType],lastSync:this.lastSyncTimestamp});try{const t=await this.client.mirrorNode.getTopicMessagesByFilter(this.topicId,{startTime:this.lastSyncTimestamp,order:"asc",limit:100});for(const i of t)try{let e;if(i.raw_content)e=JSON.parse(i.raw_content);else{const t=i;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:i.sequence_number.toString(),sequenceNumber:i.sequence_number,timestamp:i.consensus_timestamp||(new Date).toISOString(),submitter:i.payer||"unknown",data:e};this.entries.set(t.id,t)}catch(e){this.logger.warn("Failed to parse registry message",{sequenceNumber:i.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,i){if(!this.client)throw new Error("Client required for inscription");const n="string"==typeof e?globalThis.Buffer.from(e):e;let o;if(this.logger.info("Inscribing content via HCS-1",{size:n.length,mimeType:t,registryType:q0[this.registryType]}),"getOperatorAccountId"in this.client)o=await lQ({type:"buffer",buffer:n,fileName:"application/octet-stream"===t&&"wasm"===i?.fileType?`${i?.name||"content"}.wasm`:i?.name||"content",mimeType:t},{accountId:this.client.getOperatorAccountId(),privateKey:this.client.getOperatorPrivateKey(),network:this.networkType},{mode:"file",metadata:i,waitForConfirmation:!0});else{const{accountId:e,signer:r}=await this.client.getAccountAndSigner();o=await uQ({type:"buffer",buffer:n,fileName:"application/octet-stream"===t&&"wasm"===i?.fileType?`${i?.name||"content"}.wasm`:i?.name||"content",mimeType:t},r,{mode:"file",metadata:i,waitForConfirmation:!0})}if(!o.confirmed)throw new Error("Failed to inscribe content");const r=o.inscription.topic_id;if(!r)throw new Error("No topic ID in inscription response");return this.logger.info("Content inscribed successfully",{topicId:r}),r}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:q0[this.registryType]})}getStats(){return{entryCount:this.entries.size,lastSync:this.lastSyncTimestamp,topicId:this.topicId,registryType:q0[this.registryType]}}}const W0=n.z.object({p:n.z.literal("hcs-12")}),H0=n.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid Hedera address format"),V0=n.z.string().regex(/^[a-f0-9]{64}$/,"Invalid SHA-256 hash format"),G0=n.z.object({format:n.z.enum(["tar.gz","zip","car"]),root_manifest:n.z.string(),includes_lockfile:n.z.boolean(),workspace_members:n.z.array(n.z.string()).optional()}),Z0=n.z.object({source_t_id:H0,source_hash:V0,compiler_version:n.z.string(),cargo_version:n.z.string(),target:n.z.literal("wasm32-unknown-unknown"),profile:n.z.string(),build_flags:n.z.array(n.z.string()),lockfile_hash:V0,source_structure:G0}),J0=n.z.lazy(()=>n.z.object({type:n.z.string().optional(),required:n.z.array(n.z.string()).optional(),properties:n.z.record(J0).optional(),pattern:n.z.string().optional(),minimum:n.z.number().optional(),maximum:n.z.number().optional(),regex:n.z.string().optional(),min:n.z.number().optional(),max:n.z.number().optional(),length:n.z.number().optional(),email:n.z.boolean().optional(),url:n.z.boolean().optional(),uuid:n.z.boolean().optional(),cuid:n.z.boolean().optional(),cuid2:n.z.boolean().optional(),ulid:n.z.boolean().optional(),datetime:n.z.boolean().optional(),ip:n.z.boolean().optional(),startsWith:n.z.string().optional(),endsWith:n.z.string().optional(),includes:n.z.string().optional(),gt:n.z.number().optional(),gte:n.z.number().optional(),lt:n.z.number().optional(),lte:n.z.number().optional(),int:n.z.boolean().optional(),positive:n.z.boolean().optional(),nonnegative:n.z.boolean().optional(),negative:n.z.boolean().optional(),nonpositive:n.z.boolean().optional(),multipleOf:n.z.number().optional(),finite:n.z.boolean().optional(),safe:n.z.boolean().optional(),nonempty:n.z.boolean().optional(),literal:n.z.union([n.z.string(),n.z.number(),n.z.boolean()]).optional(),enum:n.z.array(n.z.string()).optional(),nullable:n.z.boolean().optional(),nullish:n.z.boolean().optional(),optional:n.z.boolean().optional(),element:n.z.any().optional(),shape:n.z.record(n.z.any()).optional(),strict:n.z.boolean().optional(),passthrough:n.z.boolean().optional(),catchall:n.z.any().optional()})),Y0=n.z.object({p:n.z.literal("hcs-12"),op:n.z.literal("register"),t_id:H0,hash:V0,wasm_hash:V0,js_t_id:H0.optional(),js_hash:V0.optional(),interface_version:n.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid version format").optional(),info_t_id:H0.optional(),source_verification:Z0.optional(),previous_version:n.z.string().optional(),migration_notes:n.z.string().optional(),validation_rules:n.z.record(J0).optional(),m:n.z.string().optional()}),X0=n.z.object({p:n.z.literal("hcs-12"),op:n.z.enum(["register","template"]),name:n.z.string(),version:n.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid semver format"),data:n.z.union([n.z.any(),n.z.string()]).optional(),t_id:H0.optional()});n.z.enum(["register","add-action","add-block","update"]);const Q0=W0.extend({op:n.z.literal("register"),name:n.z.string(),version:n.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid semver format"),description:n.z.string().optional(),tags:n.z.array(n.z.string()).optional(),author:n.z.string().optional()}),e1=W0.extend({op:n.z.literal("add-action"),t_id:H0,alias:n.z.string(),config:n.z.any().optional(),data:H0.optional()}),t1=W0.extend({op:n.z.literal("add-block"),block_t_id:H0,actions:n.z.record(n.z.string(),H0).optional(),attributes:n.z.record(n.z.any()).optional(),children:n.z.array(n.z.string()).optional(),data:H0.optional()}),i1=W0.extend({op:n.z.literal("update"),description:n.z.string().optional(),tags:n.z.array(n.z.string()).optional()});n.z.object({type:n.z.enum(["vertical","horizontal","grid"]),responsive:n.z.boolean().optional(),containerClass:n.z.string().optional()}),n.z.object({source_t_id:H0,source_hash:V0,description:n.z.string().optional()});const n1=n.z.discriminatedUnion("op",[Q0,e1,t1,i1]),o1=Q0,r1=W0.extend({op:n.z.literal("register"),t_id:H0,name:n.z.string().max(100,"Name must be 100 characters or less"),description:n.z.string().max(500,"Description must be 500 characters or less").optional(),tags:n.z.array(n.z.string()).max(10,"Maximum 10 tags allowed").optional(),category:n.z.string().optional(),featured:n.z.boolean().optional(),icon:n.z.string().optional(),author:n.z.string().optional(),website:n.z.string().url().optional()});function a1(e){return Y0.parse(e)}function s1(e){return n1.parse(e)}function c1(e,t){const i=t.safeParse(e);return i.success?{isValid:!0,errors:[],data:i.data}:{isValid:!1,errors:i.error.errors.map(e=>`${e.path.join(".")}: ${e.message}`)}}class p1 extends K0{constructor(e,t,i,n){super(e,t,q0.ACTION,i,n),this.actionsByHash=new Map,this.cryptoAdapter=PQ()}async registerWithWasm(e,t,i){let n,o;if(IQ()){n=this.createSSRSafeHash(e,"wasm");const i=JSON.stringify(t);o=this.createSSRSafeHash(globalThis.Buffer.from(i),"info")}else{const i=this.cryptoAdapter.createHash("sha256").update(e).digest("hex"),r=i instanceof Promise?await i:i;n="string"==typeof r?r:r.toString("hex");const a=JSON.stringify(t),s=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(a)).digest("hex"),c=s instanceof Promise?await s:s;o="string"==typeof c?c:c.toString("hex")}const r=await this.inscribeContent(e,"application/octet-stream",{name:t.name,version:t.version,hash:n,fileType:"wasm"});let a;const s=JSON.stringify(t);globalThis.Buffer.byteLength(s,"utf8")>1024&&(a=await this.inscribeContent(s,"application/json",{name:`${t.name}-info`,version:t.version}));const c={p:"hcs-12",op:"register",t_id:r,hash:o,wasm_hash:n,info_t_id:a,source_verification:i,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 i={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(i.id,i),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,i={id:t.toString(),sequenceNumber:t,timestamp:(new Date).toISOString(),submitter:"local",data:e};return this.entries.set(i.id,i),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 i;if("getOperatorAccountId"in this.client)i=await dQ(t.info_t_id,{accountId:this.client.getOperatorAccountId(),privateKey:this.client.getOperatorPrivateKey(),network:this.networkType});else{const{accountId:e}=await this.client.getAccountAndSigner();i=await dQ(t.info_t_id,{accountId:e,network:this.networkType})}if(!i.content)return this.logger.error("No content in inscription response"),null;e="string"==typeof i.content?i.content:globalThis.Buffer.from(i.content).toString("utf8")}const i=JSON.parse(e);let n;if(IQ())n=this.createSSRSafeHash(globalThis.Buffer.from(e),"info");else{const t=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(e)).digest("hex"),i=t instanceof Promise?await t:t;n="string"==typeof i?i:i.toString("hex")}if(n!==t.hash)throw this.logger.error("INFO hash mismatch",{expected:t.hash,computed:n}),new Error("Module info verification failed");return i}catch(i){return this.logger.error("Failed to fetch action INFO",{hash:e,error:i}),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 dQ(t.t_id,{accountId:this.client.getOperatorAccountId(),privateKey:this.client.getOperatorPrivateKey(),network:this.networkType});else{const{accountId:i}=await this.client.getAccountAndSigner();e=await dQ(t.t_id,{accountId:i,network:this.networkType})}if(!e.content)return this.logger.error("No content in inscription response"),null;const i="string"==typeof e.content?globalThis.Buffer.from(e.content,"base64"):globalThis.Buffer.from(e.content);let n;if(IQ())n=this.createSSRSafeHash(i,"wasm");else{const e=this.cryptoAdapter.createHash("sha256").update(i).digest("hex"),t=e instanceof Promise?await e:e;n="string"==typeof t?t:t.toString("hex")}if(n!==t.wasm_hash)throw this.logger.error("WASM hash mismatch",{expected:t.wasm_hash,computed:n}),new Error("WASM binary verification failed");return new Uint8Array(i)}catch(i){return this.logger.error("Failed to fetch WASM from HCS-1",{topicId:t.t_id,error:i}),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 i=e;for(;i;){const e=await this.getAction(i);if(!e)break;t.push(e),i=void 0}return t}validateRegistration(e){try{a1(e)}catch(t){if(t instanceof n.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 i=0;for(let n=0;n<Math.min(e.length,256);n++)i=(i<<5)-i+e[n]&4294967295;return`ssr-${t}-${e.length}-${Math.abs(i).toString(16).padStart(8,"0")}`}}class l1{constructor(e,t,i){this.blockCache=new Map,this.templateCache=new Map,this.networkType=e,this.logger=t,this.client=i}async loadBlockDefinition(e){const t=this.blockCache.get(e);if(t)return t;try{const t=new _Q,i=await t.resolve(e,{network:this.networkType});if(!i.content)throw new Error(`Block definition not found: ${e}`);let n;return n="object"!=typeof i.content||null===i.content||i.content instanceof ArrayBuffer?JSON.parse("string"==typeof i.content?i.content:i.content.toString()):i.content,this.blockCache.set(e,n),n}catch(i){throw this.logger.error("Failed to load block definition",{blockTopicId:e,error:i.message}),new Error(`Failed to load block definition: ${i.message}`)}}async loadBlockTemplate(e){const t=this.templateCache.get(e);if(t)return t;try{const t=new _Q,i=await t.resolve(e,{network:this.networkType});if(!i.content)throw new Error(`Block template not found: ${e}`);let n;return n="string"==typeof i.content?i.content:"object"==typeof i.content&&null!==i.content?i.content.text||JSON.stringify(i.content):i.content.toString(),this.templateCache.set(e,n),n}catch(i){throw this.logger.error("Failed to load block template",{templateTopicId:e,error:i.message}),new Error(`Failed to load block template: ${i.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 i=globalThis.Buffer.from(e),n=await this.client.inscribeFile(i,`block-${t.name}-template.html`);if(!n?.topic_id)throw new Error("Failed to inscribe block template");const o={...t,template_t_id:n.topic_id},r=globalThis.Buffer.from(JSON.stringify(o)),a=await this.client.inscribeFile(r,`block-${t.name}-definition.json`);if(!a?.topic_id)throw new Error("Failed to inscribe block definition");return this.blockCache.set(a.topic_id,o),this.templateCache.set(n.topic_id,e),{definitionTopicId:a.topic_id,templateTopicId:n.topic_id}}catch(i){throw this.logger.error("Failed to store block",{error:i.message}),new Error(`Failed to store block: ${i.message}`)}}clearCache(){this.blockCache.clear(),this.templateCache.clear()}}class u1 extends K0{constructor(e,t,i,n){super(e,t,q0.ASSEMBLY,i,n),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 i={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(i.id,i),await this.processMessage(i),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 i=this.assemblyStates.get(this.topicId);switch(t.op){case"register":const n=t;i={topicId:this.topicId,name:n.name,version:n.version,description:n.description,tags:n.tags,author:n.author,actions:[],blocks:[],created:e.timestamp,updated:e.timestamp},this.assemblyStates.set(this.topicId,i);break;case"add-action":if(!i)return void this.logger.warn("Cannot add action without assembly registration");const o=t,r={t_id:o.t_id,alias:o.alias,config:o.config,data:o.data};i.actions.push(r),i.updated=e.timestamp;break;case"add-block":if(!i)return void this.logger.warn("Cannot add block without assembly registration");const a=t,s={block_t_id:a.block_t_id,actions:a.actions,attributes:a.attributes,children:a.children,data:a.data};i.blocks.push(s),i.updated=e.timestamp;break;case"update":if(!i)return void this.logger.warn("Cannot update without assembly registration");const c=t;void 0!==c.description&&(i.description=c.description),void 0!==c.tags&&(i.tags=c.tags),i.updated=e.timestamp}}async getAssemblyState(e){const t=e||this.topicId;if(!t||!this.client)return null;let i=this.assemblyStates.get(t);if(i)return i;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 i of this.entries.values())this.processAssemblyMessage(t,i);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}),i=Array.isArray(e)?e:[];this.logger.info("Processing assembly messages",{topicId:t,messageCount:i.length});for(const r of i)try{let e;if(!r.message)continue;try{let t;t="undefined"==typeof window?globalThis.Buffer.from(r.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(r.message),e=>e.charCodeAt(0))),e=JSON.parse(t),this.logger.debug("Successfully parsed message",{sequenceNumber:r.sequence_number,op:e.op,p:e.p})}catch(n){this.logger.debug("Failed to decode/parse message",{sequenceNumber:r.sequence_number,error:n});continue}if("hcs-12"!==e.p){this.logger.debug("Skipping non-HCS-12 message",{sequenceNumber:r.sequence_number,protocol:e.p});continue}const i={id:r.sequence_number.toString(),sequenceNumber:r.sequence_number,timestamp:r.consensus_timestamp||(new Date).toISOString(),submitter:r.payer_account_id||"unknown",data:e};this.processAssemblyMessage(t,i),this.logger.debug("Processed message for assembly",{topicId:t,sequenceNumber:i.sequenceNumber,op:i.data.op})}catch(n){this.logger.warn("Failed to parse assembly message",{sequenceNumber:r.sequence_number,error:n})}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(n){return this.logger.error("Failed to sync assembly state",{topicId:t,error:n}),null}}processAssemblyMessage(e,t){const i=t.data;let n=this.assemblyStates.get(e);switch(this.logger.debug("Processing assembly message",{topicId:e,op:i.op,hasState:!!n}),i.op){case"register":const o=i;n={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,n),this.logger.debug("Assembly registered",{topicId:e,name:o.name,version:o.version});break;case"add-action":if(!n)return void this.logger.warn("Cannot add action without assembly registration");const r=i,a={t_id:r.t_id,alias:r.alias,config:r.config,data:r.data};n.actions.push(a),n.updated=t.timestamp;break;case"add-block":if(!n)return void this.logger.warn("Cannot add block without assembly registration");const s=i,c={block_t_id:s.block_t_id,actions:s.actions,attributes:s.attributes,children:s.children,data:s.data};n.blocks.push(c),n.updated=t.timestamp;break;case"update":if(!n)return void this.logger.warn("Cannot update without assembly registration");const p=i;void 0!==p.description&&(n.description=p.description),void 0!==p.tags&&(n.tags=p.tags),n.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}),i=Array.isArray(t)?t:[];this.logger.info("Processing assembly messages",{topicId:this.topicId,messageCount:i.length});for(const n of i)try{let t;if(n.message)try{let e;e="undefined"==typeof window?globalThis.Buffer.from(n.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(n.message),e=>e.charCodeAt(0))),t=JSON.parse(e)}catch(e){this.logger.debug("Failed to decode/parse message in sync",{sequenceNumber:n.sequence_number,error:e});continue}else if(n.raw_content)try{t=JSON.parse(n.raw_content)}catch{continue}else{const e=n;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 i={id:n.sequence_number.toString(),sequenceNumber:n.sequence_number,timestamp:n.consensus_timestamp||(new Date).toISOString(),submitter:n.payer_account_id||"unknown",data:t};this.entries.set(i.id,i),await this.processMessage(i),this.logger.debug("Processed sync message",{sequenceNumber:i.sequenceNumber,op:i.data.op})}catch(e){this.logger.warn("Failed to parse assembly message",{sequenceNumber:n.sequence_number,error:e})}this.logger.info("Assembly sync completed",{topicId:this.topicId,messageCount:i.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{s1(e)}catch(t){if(t instanceof n.ZodError){const e=t.errors.map(e=>`${e.path.join(".")}: ${e.message}`);throw new Error(`Assembly validation failed: ${e.join("; ")}`)}throw t}}}class d1 extends K0{constructor(e,t,i,n){super(e,t,q0.HASHLINKS,i,n)}async register(e){this.validateRegistration(e);const t=`${this.topicId||"local"}_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,i={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,i),this.client&&this.topicId)try{const n=JSON.stringify(e),o=await this.client.submitMessage(this.topicId,n);return o.sequenceNumber&&(i.sequenceNumber=o.sequenceNumber,i.id=o.sequenceNumber.toString(),this.entries.delete(t),this.entries.set(i.id,i)),this.logger.info("HashLink submitted to HCS",{transactionId:o.transactionId,sequenceNumber:o.sequenceNumber,topicId:this.topicId}),i.id}catch(n){throw this.logger.error("Failed to submit HashLink to HCS",{error:n}),this.entries.delete(t),n}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(),i=e.toLowerCase();return t.map(e=>e.data).filter(e=>e.name.toLowerCase().includes(i)||(e.description?.toLowerCase().includes(i)??!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 i=e.data;i.category&&t.add(i.category)}),Array.from(t).sort()}async getAllTags(){const e=await this.listEntries(),t=new Set;return e.forEach(e=>{const i=e.data;i.tags&&i.tags.forEach(e=>t.add(e))}),Array.from(t).sort()}validateRegistration(e){this.validateBaseRegistration(e);const t=c1(e,r1);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()),i=new Set,n=new Set;let o=0;return t.forEach(e=>{const t=e.data;t.category&&i.add(t.category),t.tags&&t.tags.forEach(e=>n.add(e)),t.featured&&o++}),{...e,categories:i.size,totalTags:n.size,featuredCount:o}}}class f1{constructor(e,t,i,n){this.cache=new Map,this.logger=e,this.assemblyRegistry=t,this.actionRegistry=i,this.blockLoader=n}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 i={topicId:e,state:t,actions:[],blocks:[]};return this.cache.set(e,i),this.logger.debug("Assembly loaded successfully",{topicId:e,name:t.name,version:t.version,actionsCount:t.actions?.length||0,blocksCount:t.blocks?.length||0}),i}catch(i){throw this.logger.error("Failed to load assembly",{topicId:e,error:i}),new Error(`Failed to load assembly: ${i instanceof Error?i.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 n of e.actions)try{const e=await this.resolveActionReference(n);t.actions.push({alias:n.alias,t_id:n.t_id,definition:e,config:n.config})}catch(i){this.logger.warn("Failed to resolve action reference",{t_id:n.t_id,alias:n.alias,error:i}),t.actions.push({alias:n.alias,t_id:n.t_id,definition:null,config:n.config,error:i instanceof Error?i.message:"Unknown error"})}if(e.blocks)for(const n of e.blocks)try{const{definition:e,template:i}=await this.resolveBlockReference(n);t.blocks.push({block_t_id:n.block_t_id,definition:e,template:i,attributes:n.attributes,actions:n.actions,children:n.children})}catch(i){this.logger.warn("Failed to resolve block reference",{block_t_id:n.block_t_id,error:i}),t.blocks.push({block_t_id:n.block_t_id,definition:null,attributes:n.attributes,actions:n.actions,children:n.children,error:i instanceof Error?i.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 i of e.state.blocks){if(i.actions)for(const[n,o]of Object.entries(i.actions)){const r=e.state.actions?.some(e=>e.t_id===o);r||t.push(`Block ${i.block_t_id} references non-existent action: ${o} for key ${n}`)}if(i.children)for(const n of i.children){const o=e.state.blocks?.some(e=>e.block_t_id===n);o||t.push(`Block ${i.block_t_id} references non-existent child block: ${n}`)}}for(const i of e.actions)i.error&&t.push(`Action ${i.alias} has resolution error: ${i.error}`);for(const i of e.blocks)i.error&&t.push(`Block ${i.block_t_id} has resolution error: ${i.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),i=await this.resolveReferences(t.state),n=this.validateComposition(i);return n.valid||this.logger.warn("Assembly validation failed",{topicId:e,errors:n.errors}),i}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 m1{constructor(e){this.network=e.network,this.logger=e.logger||y.getInstance({level:e.logLevel||"info",module:"HCS12-BaseClient",prettyPrint:e.prettyPrint,silent:e.silent}),this.mirrorNode=new I(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 l1(this.network,this.logger,this)),this._blockLoader.loadBlock(e)}async getAssembly(e,t){if(!this._assemblyRegistry)throw new Error("Assembly registry not initialized");const i=await this._assemblyRegistry.listEntries();for(const n of i){const i=await this._assemblyRegistry.getAssemblyState(n.id);if(i&&i.name===e&&i.version===t)return i}return null}async loadAssembly(e){this._actionRegistry&&(this.logger.info("Syncing action registry before loading assembly"),await this._actionRegistry.sync());const t=new u1(this.network,this.logger,e,this);await t.sync();return new f1(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 f1(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 h1{constructor(){this.block={apiVersion:3},this.attributes={},this.supports={},this.actions={},this.logger=new y({module:"BlockBuilder"})}setName(e){return this.block.name=e,this}setTitle(e){return this.block.title=e,this}setDescription(e){return this.block.description=e,this}setCategory(e){return this.block.category=e,this}setIcon(e){return this.block.icon=e,this}setKeywords(e){return this.block.keywords=e,this}setApiVersion(e){return this.block.apiVersion=e,this}addAttribute(e,t,i,n){const o={type:t,default:i};return n?.enum&&(o.enum=n.enum),n?.source&&(o.source=n.source),n?.selector&&(o.selector=n.selector),n?.attribute&&(o.attribute=n.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 h1).setName(e).setTitle(t).setCategory("formatting").enableCommonSupports()}static createInteractiveBlock(e,t){return(new h1).setName(e).setTitle(t).setCategory("widgets").enableCommonSupports()}static createWidgetBlock(e,t){return this.createInteractiveBlock(e,t)}static createContainerBlock(e,t){return(new h1).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 g1{constructor(e,t){this.wasmCache=new Map,this.logger=e,this.network=t,this.hrlResolver=new _Q}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(i){return this.logger&&"function"==typeof this.logger.error?this.logger.error("WASM execution failed",{actionId:e.t_id,error:i.message}):console.error("WASM execution failed",{actionId:e.t_id,error:i.message}),{success:!1,error:i.message}}}readWasmString(e,t){const i=new Uint8Array(e.buffer);let n=0;for(;0!==i[t+n];)n++;return(new TextDecoder).decode(i.slice(t,t+n))}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 i=await this.hrlResolver.resolve(e.js_t_id,{network:this.network,returnRaw:!1});if(!i.content||"string"!=typeof i.content)throw new Error("Failed to load JavaScript module: invalid content");const n=new Blob([i.content],{type:"application/javascript"}),o=URL.createObjectURL(n);try{this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Importing JavaScript module from blob URL");const i=new Function("url","return import(url)"),n=await i(o);if(this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Module imported, exports:",Object.keys(n)),!n.default&&!n.init)throw new Error("No init function found in JavaScript module");{const t=n.default||n.init;this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Loading WASM bytes from topic:",e.t_id);const i=await this.hrlResolver.resolve(e.t_id,{network:this.network,returnRaw:!0});if(this.logger&&"function"==typeof this.logger.debug){const e=i.content instanceof ArrayBuffer?i.content.byteLength:i.content.length;this.logger.debug("WASM bytes loaded, size:",e)}await t({module_or_path:i.content}),this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("WASM module initialized successfully")}const r=n.WasmInterface;if(!r)throw new Error("WasmInterface not found in module exports. Available exports: "+Object.keys(n).join(", "));this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Creating WasmInterface instance");const a=new r;let s,c;if("POST"===t.method&&a.POST){const e=t.params.operation||"default",i={...t.params,...t.state},n=JSON.stringify(i);this.logger&&"function"==typeof this.logger.debug?this.logger.debug("Calling POST method",{actionName:e,paramsJson:n,allParams:i}):console.log("WASM POST params:",{actionName:e,paramsJson:n,allParams:i}),s=await a.POST(e,n,this.network.toString(),"")}else if("GET"===t.method&&a.GET){const e=t.params.operation||"default",i=JSON.stringify(t.params);this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Calling GET method",{actionName:e,paramsJson:i}),s=await a.GET(e,i,this.network.toString())}else{if("INFO"!==t.method||!a.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"),s=a.INFO()}try{c=JSON.parse(s)}catch{c={value:s}}return a.free&&a.free(),URL.revokeObjectURL(o),{success:!0,data:c}}catch(mxe){throw URL.revokeObjectURL(o),mxe}}}catch(i){const t=i instanceof Error?i.message:String(i),n=i instanceof Error?i.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:n,fullError:i}):console.error("JavaScript execution failed",{jsTopicId:e.js_t_id,error:t,stack:n,fullError:i}),{success:!1,error:t||"Unknown error"}}}clearCache(){this.wasmCache.clear()}}class y1{constructor(e){this.logger=e}async scanTemplate(e){const t=[],i=/<([^>]+)\s+data-hashlink=["']([^"']+)["']([^>]*)>/gs;let n;for(;null!==(n=i.exec(e));){const e=n[0],i=n[1].split(/\s+/)[0],r=n[2],a=n[3];try{const n=this.parseHashLinkURI(r),o=a.match(/data-attributes=(['"])((?:(?!\1).)*)\1/s);let s;if(o)try{const e=o[2];s=JSON.parse(e)}catch(mxe){this.logger.warn("Failed to parse data-attributes",{uri:r,attributes:o[2],error:mxe.message})}const c=a.match(/data-actions=(['"])((?:(?!\1).)*)\1/s);let p;if(c)try{const e=c[2];p=JSON.parse(e)}catch(mxe){this.logger.warn("Failed to parse data-actions",{uri:r,actions:c[2],error:mxe.message})}const l=a.match(/data-loading=['"]([^'"]+)['"]/),u=l?.[1]||"eager";t.push({element:i,uri:r,...n,attributes:s,actions:p,loading:u,placeholder:e}),this.logger.debug("Found HashLink reference",{uri:r,parsed:n})}catch(o){this.logger.error("Failed to parse HashLink URI",{uri:r,error:o.message})}}return t}parseHashLinkURI(e){const t=e.match(/^hcs:\/\/(\d+)\/(.+)$/);if(!t)throw new Error(`Invalid HashLink URI format: ${e}`);const i=t[1],n=t[2];if("2"===i){const e=n.split("/");if(2!==e.length)throw new Error(`Invalid HCS-2 reference format: ${n}`);return{protocol:i,reference:n,registryId:e[0],entryName:e[1]}}return{protocol:i,reference:n}}createPlaceholder(e,t){return`\x3c!-- HASHLINK_PLACEHOLDER_${t}_${e.uri.replace(/[^a-zA-Z0-9]/g,"_")} --\x3e`}}class v1{constructor(e,t,i,n){this.logger=e,this.blockLoader=t,this.hrlResolver=i,this.network=n,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(i){return this.logger.error("Failed to resolve HashLink",{uri:e.uri,error:i.message}),{blockId:e.reference,definition:null,template:null,attributes:{},actions:{},error:i.message}}}async resolveHCS12Block(e,t){const i=e.reference;if(this.renderStack.has(i))return{blockId:i,definition:null,template:null,attributes:{},actions:{},error:"Circular reference detected"};const n=this.getCacheKey(i,e.attributes,e.actions);if(this.cache.has(n))return this.cache.get(n);try{const o=await this.blockLoader.loadBlock(i);if(!o||!o.definition)throw new Error(`Block not found: ${i}`);const r={...this.extractDefaults(o.definition),...t.attributes,...e.attributes},a={...t.actions,...e.actions},s={blockId:i,definition:o.definition,template:o.template,attributes:r,actions:a};return this.cache.set(n,s),s}catch(o){throw this.renderStack.delete(i),new Error(`Failed to load HCS-12 block ${i}: ${o.message}`)}}async resolveHCS1Block(e,t){const i=e.reference;try{const t=await this.blockLoader.loadBlock(i);if(t&&t.definition)return{blockId:i,definition:t.definition,template:t.template,attributes:{...this.extractDefaults(t.definition),...e.attributes},actions:e.actions||{}};return{blockId:i,definition:null,template:(await this.hrlResolver.resolve(i,{network:this.network})).content,attributes:e.attributes||{},actions:e.actions||{}}}catch(n){throw new Error(`Failed to load HCS-1 content ${i}: ${n.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(i){throw new Error(`Failed to resolve HCS-2 entry: ${i.message}`)}}extractDefaults(e){const t={};return e.attributes&&Object.entries(e.attributes).forEach(([e,i])=>{i&&"object"==typeof i&&"default"in i&&(t[e]=i.default)}),t}getCacheKey(e,t,i){return`${e}:${t?JSON.stringify(t):""}:${i?JSON.stringify(i):""}`}pushRenderStack(e){this.renderStack.add(e)}popRenderStack(e){this.renderStack.delete(e)}clearCache(){this.cache.clear()}}const b1={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"}},x1={ACTIONS:{},BLOCKS:{},ASSEMBLIES:{}};var w1=(e=>(e.REGISTER="register",e.UPDATE="update",e.DELETE="delete",e.MIGRATE="migrate",e))(w1||{}),k1=(e=>(e[e.INDEXED=0]="INDEXED",e[e.NON_INDEXED=1]="NON_INDEXED",e))(k1||{});const _1=n.z.string().regex(/^\d+\.\d+\.\d+$/,{message:"Topic ID must be in Hedera format (e.g., '0.0.123456')"}),E1=n.z.object({p:n.z.string().regex(/^hcs-\d+$/,{message:"Protocol must be in format 'hcs-N' where N is a number"}),op:n.z.enum(["register","update","delete","migrate"]),m:n.z.string().max(500,"Memo must not exceed 500 characters").optional(),ttl:n.z.number().int().positive().optional()}),S1=E1.extend({op:n.z.literal("register"),t_id:_1,metadata:n.z.string().optional()}),T1=E1.extend({op:n.z.literal("update"),uid:n.z.string(),t_id:_1,metadata:n.z.string().optional()}),A1=E1.extend({op:n.z.literal("delete"),uid:n.z.string()}),I1=E1.extend({op:n.z.literal("migrate"),t_id:_1,metadata:n.z.string().optional()}),R1=n.z.discriminatedUnion("op",[S1,T1,A1,I1]);class O1{constructor(e){this.network=e.network,this.logger=e.logger||y.getInstance({level:e.logLevel||"info",module:"HCS2Client",silent:e.silent}),this.mirrorNode=new I(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0)}parseRegistryTypeFromMemo(e){try{const t=/hcs-2:(\d):(\d+)/,i=e.match(t);if(i&&3===i.length){const e=parseInt(i[1]),t=parseInt(i[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 R1.parse(e),{valid:!0,errors:[]}}catch(t){const e=[];return t instanceof n.ZodError?t.errors.forEach(t=>{const i=t.path.join(".");e.push(`${i?i+": ":""}${t.message}`)}):e.push(`Unexpected error: ${t}`),this.logger.debug(`Message validation failed: ${e.join(", ")}`),{valid:!1,errors:e}}}createRegisterMessage(e,t,i,n="hcs-2"){return{p:n,op:w1.REGISTER,t_id:e,metadata:t,m:i}}createUpdateMessage(e,t,i,n,o="hcs-2"){return{p:o,op:w1.UPDATE,t_id:e,uid:t,metadata:i,m:n}}createDeleteMessage(e,t,i="hcs-2"){return{p:i,op:w1.DELETE,uid:e,m:t}}createMigrateMessage(e,t,i,n="hcs-2"){return{p:n,op:w1.MIGRATE,t_id:e,metadata:t,m:i}}parseRegistryEntries(e,t,i,n){const o=[];let r;this.logger.debug(`Parsing ${t.length} messages for topic ${e}`);for(const s of t)try{if(!s.message){this.logger.debug(`Message is missing 'message' property: ${JSON.stringify(s)}`);continue}const t=globalThis.Buffer.from(s.message,"base64").toString("utf-8"),n=JSON.parse(t);this.logger.debug(`Successfully parsed message: ${JSON.stringify(n)}`);const{valid:a,errors:c}=this.validateMessage(n);if(!a){this.logger.warn(`Invalid HCS-2 message: ${c.join(", ")}`);continue}const p={topicId:e,sequence:s.sequence_number,timestamp:s.consensus_timestamp,payer:s.payer_account_id,message:n,consensus_timestamp:s.consensus_timestamp,registry_type:i};o.push(p),(i===k1.NON_INDEXED||!r||p.timestamp>r.timestamp)&&(r=p)}catch(a){this.logger.warn(`Error parsing message: ${a}`)}return this.logger.debug(`Parsed ${o.length} valid entries for topic ${e}`),{topicId:e,registryType:i,ttl:n,entries:i===k1.INDEXED?o:r?[r]:[],latestEntry:r}}}function j1(e){var t,i;return N({memo:e.memoOverride??(t=e.registryType,i=e.ttl,`hcs-2:${t}:${i}`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}class C1 extends O1{constructor(e){if(super({network:e.network,logLevel:e.logLevel,silent:e.silent,mirrorNodeUrl:e.mirrorNodeUrl,logger:e.logger}),this.initialized=!1,this.operatorId="string"==typeof e.operatorId?o.AccountId.fromString(e.operatorId):e.operatorId,e.keyType)this.keyType=e.keyType,this.operatorKey="string"==typeof e.operatorKey?"ecdsa"===this.keyType?o.PrivateKey.fromStringECDSA(e.operatorKey):o.PrivateKey.fromStringED25519(e.operatorKey):e.operatorKey;else if("string"==typeof e.operatorKey)try{const t=C(e.operatorKey);this.operatorKey=t.privateKey,this.keyType=t.detectedType,t.warning&&this.logger.warn(t.warning)}catch(t){this.logger.warn("Failed to detect key type from private key format, defaulting to ECDSA"),this.keyType="ecdsa",this.operatorKey=o.PrivateKey.fromStringECDSA(e.operatorKey)}else this.operatorKey=e.operatorKey,this.keyType="ecdsa";this.client=this.createClient(e.network),this.initializeClient()}initializeClient(){try{this.client.setOperator(this.operatorId,this.operatorKey),this.initialized=!0,this.logger.info(`HCS-2 client initialized successfully with key type: ${this.keyType}`)}catch(e){throw this.logger.error(`Failed to initialize HCS-2 client: ${e}`),e}}createClient(e){return"mainnet"===e?o.Client.forMainnet():o.Client.forTestnet()}async createRegistry(e={}){try{const t=e.registryType??k1.INDEXED,i=e.ttl??86400;this.generateRegistryMemo(t,i);let n,r,a,s;if(e.adminKey)if("string"==typeof e.adminKey)try{r=o.PublicKey.fromString(e.adminKey)}catch{const t=globalThis.Buffer.from(e.adminKey.replace(/^0x/i,""),"hex");r="ed25519"===this.keyType?o.PublicKey.fromBytesED25519(t):o.PublicKey.fromBytesECDSA(t)}else"boolean"==typeof e.adminKey?r=this.operatorKey.publicKey:(r=e.adminKey.publicKey,n=e.adminKey);if(e.submitKey)if("string"==typeof e.submitKey)try{s=o.PublicKey.fromString(e.submitKey)}catch{const t=globalThis.Buffer.from(e.submitKey.replace(/^0x/i,""),"hex");s="ed25519"===this.keyType?o.PublicKey.fromBytesED25519(t):o.PublicKey.fromBytesECDSA(t)}else"boolean"==typeof e.submitKey?s=this.operatorKey.publicKey:(s=e.submitKey.publicKey,a=e.submitKey);const c=j1({registryType:t,ttl:i,adminKey:r,submitKey:s,operatorPublicKey:this.operatorKey.publicKey}),p=await c.freezeWith(this.client);n&&await p.sign(n),a&&await p.sign(a);const l=await p.execute(this.client),u=(await l.getReceipt(this.client)).topicId;if(!u)throw new Error("Failed to create registry: No topic ID in receipt");const d=u.toString();return this.logger.info(`Created registry topic: ${d} (${t===k1.INDEXED?"Indexed":"Non-indexed"}, TTL: ${i}s)`),{success:!0,topicId:d,transactionId:l.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,i="hcs-2"){try{const n=this.createRegisterMessage(t.targetTopicId,t.metadata,t.memo,i),o=await this.submitMessage(e,n);return this.logger.info(`Registered entry in registry ${e} pointing to topic ${t.targetTopicId} using protocol ${i}`),{success:!0,receipt:o,sequenceNumber:o.topicSequenceNumber?.low??void 0}}catch(n){return this.logger.error(`Failed to register entry: ${n}`),{success:!1,error:`Failed to register entry: ${n}`}}}async updateEntry(e,t){try{const i=await this.mirrorNode.getTopicInfo(e),n=this.parseRegistryTypeFromMemo(i.memo);if(!n||n.registryType!==k1.INDEXED)throw new Error("Update operation is only valid for indexed registries");const o=this.createUpdateMessage(t.targetTopicId,t.uid,t.metadata,t.memo),r=await this.submitMessage(e,o);return this.logger.info(`Updated entry with UID ${t.uid} in registry ${e}`),{success:!0,receipt:r,sequenceNumber:r.topicSequenceNumber?.low??void 0}}catch(i){throw this.logger.error(`Failed to update entry: ${i}`),i}}async deleteEntry(e,t){try{const i=await this.mirrorNode.getTopicInfo(e),n=this.parseRegistryTypeFromMemo(i.memo);if(!n||n.registryType!==k1.INDEXED)throw new Error("Delete operation is only valid for indexed registries");const o=this.createDeleteMessage(t.uid,t.memo),r=await this.submitMessage(e,o);return this.logger.info(`Deleted entry with UID ${t.uid} from registry ${e}`),{success:!0,receipt:r,sequenceNumber:r.topicSequenceNumber?.low??void 0}}catch(i){throw this.logger.error(`Failed to delete entry: ${i}`),i}}async migrateRegistry(e,t){try{const i=this.createMigrateMessage(t.targetTopicId,t.metadata,t.memo),n=await this.submitMessage(e,i);return this.logger.info(`Migrated registry ${e} to ${t.targetTopicId}`),{success:!0,receipt:n,sequenceNumber:n.topicSequenceNumber?.low??void 0}}catch(i){throw this.logger.error(`Failed to migrate registry: ${i}`),i}}async getRegistry(e,t={}){try{const n=await this.mirrorNode.getTopicInfo(e);this.logger.debug(`Retrieved topic info for ${e}: ${JSON.stringify(n)}`);const o=this.parseRegistryTypeFromMemo(n.memo);if(!o)throw new Error(`Topic ${e} is not an HCS-2 registry (invalid memo format)`);this.logger.debug(`Retrieving messages for topic ${e} with limit ${t.limit??100}`);const r=await this.mirrorNode.getTopicMessages(e,{sequenceNumber:t.skip&&t.skip>0?`gt:${t.skip}`:void 0,limit:t.limit??100,order:t.order??"asc"}),a=t.limit?r.slice(0,t.limit):r;this.logger.debug(`Retrieved ${r.length} messages, using ${a.length} after applying limit.`);const s=[];let c;for(const t of a)try{const i={p:"hcs-2",op:t.op,t_id:t.t_id,uid:t.uid,metadata:t.metadata,m:t.m},{valid:n,errors:r}=this.validateMessage(i);if(!n){this.logger.warn(`Invalid HCS-2 message: ${r.join(", ")}`);continue}const a={topicId:e,sequence:t.sequence_number,timestamp:t.consensus_timestamp,payer:t.payer_account_id||t.payer||"",message:i,consensus_timestamp:t.consensus_timestamp,registry_type:o.registryType};s.push(a),(o.registryType===k1.NON_INDEXED||!c||a.timestamp>c.timestamp)&&(c=a)}catch(i){this.logger.warn(`Error processing message: ${i}`)}this.logger.debug(`Processed ${s.length} valid entries for registry ${e}`);return{topicId:e,registryType:o.registryType,ttl:o.ttl,entries:o.registryType===k1.INDEXED?s:c?[c]:[],latestEntry:c}}catch(i){throw this.logger.error(`Failed to get registry: ${i}`),i}}async submitMessage(e,t){try{const{valid:i,errors:n}=this.validateMessage(t);if(!i)throw new Error(`Invalid HCS-2 message: ${n.join(", ")}`);const o=B({topicId:e,message:JSON.stringify(t)}),r=await o.execute(this.client);return await r.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.keyType}getOperatorKey(){return this.operatorKey}}class N1 extends O1{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,mirrorNodeUrl:e.mirrorNodeUrl,logger:e.logger}),this.hwc=e.hwc,rQ?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??k1.INDEXED,i=e.ttl??86400,n=this.generateRegistryMemo(t,i);let r=(new o.TopicCreateTransaction).setTopicMemo(n);if(e.adminKey){let t;if("string"==typeof e.adminKey)try{t=o.PublicKey.fromString(e.adminKey)}catch{const i=j.detect(e.adminKey);if(!i.rawBytes)throw new Error("Failed to parse admin public key");t="ed25519"===i.type?o.PublicKey.fromBytesED25519(i.rawBytes):o.PublicKey.fromBytesECDSA(i.rawBytes)}else t="boolean"==typeof e.adminKey?await this.mirrorNode.getPublicKey(this.getOperatorId()):e.adminKey.publicKey;r=r.setAdminKey(t)}if(e.submitKey){let t;if("string"==typeof e.submitKey)try{t=o.PublicKey.fromString(e.submitKey)}catch{const i=j.detect(e.submitKey);if(!i.rawBytes)throw new Error("Failed to parse submit public key");t="ed25519"===i.type?o.PublicKey.fromBytesED25519(i.rawBytes):o.PublicKey.fromBytesECDSA(i.rawBytes)}else t="boolean"==typeof e.submitKey?await this.mirrorNode.getPublicKey(this.getOperatorId()):e.submitKey.publicKey;r=r.setSubmitKey(t)}const a=await this.executeWithWallet(r);if(a?.error)throw new Error(a.error);const s=a?.result;if(!s?.topicId)throw new Error("Failed to create registry: No topic ID in receipt");const c=s.topicId.toString();return this.logger.info(`Created registry topic: ${c} (${t===k1.INDEXED?"Indexed":"Non-indexed"}, TTL: ${i}s)`),{success:!0,topicId:c,transactionId:a.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 i=this.createRegisterMessage(t.targetTopicId,t.metadata,t.memo);if(i.op!==w1.REGISTER)throw new Error(`Invalid operation type: ${i.op}, expected ${w1.REGISTER}`);const n=await this.submitMessage(e,i);return this.logger.info(`Registered entry in registry ${e} pointing to topic ${t.targetTopicId}`),{success:!0,receipt:n,sequenceNumber:n.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{const i=await this.mirrorNode.getTopicInfo(e),n=this.parseRegistryTypeFromMemo(i.memo);if(!n||n.registryType!==k1.INDEXED)throw new Error("Update operation is only valid for indexed registries");const o=this.createUpdateMessage(t.targetTopicId,t.uid,t.metadata,t.memo),r=await this.submitMessage(e,o);return this.logger.info(`Updated entry with UID ${t.uid} in registry ${e}`),{success:!0,receipt:r,sequenceNumber:r.topicSequenceNumber?.low??void 0}}catch(i){return this.logger.error(`Failed to update entry: ${i}`),{success:!1,error:`Failed to update entry: ${i}`}}}async deleteEntry(e,t){try{const i=await this.mirrorNode.getTopicInfo(e),n=this.parseRegistryTypeFromMemo(i.memo);if(!n||n.registryType!==k1.INDEXED)throw new Error("Delete operation is only valid for indexed registries");const o=this.createDeleteMessage(t.uid,t.memo),r=await this.submitMessage(e,o);return this.logger.info(`Deleted entry with UID ${t.uid} from registry ${e}`),{success:!0,receipt:r,sequenceNumber:r.topicSequenceNumber?.low??void 0}}catch(i){return this.logger.error(`Failed to delete entry: ${i}`),{success:!1,error:`Failed to delete entry: ${i}`}}}async migrateRegistry(e,t){try{const i=this.createMigrateMessage(t.targetTopicId,t.metadata,t.memo),n=await this.submitMessage(e,i);return this.logger.info(`Migrated registry ${e} to ${t.targetTopicId}`),{success:!0,receipt:n,sequenceNumber:n.topicSequenceNumber?.low??void 0}}catch(i){return this.logger.error(`Failed to migrate registry: ${i}`),{success:!1,error:`Failed to migrate registry: ${i}`}}}async getRegistry(e,t={}){try{const i=await this.mirrorNode.getTopicInfo(e),n=this.parseRegistryTypeFromMemo(i.memo);if(!n)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"}),r=t.limit?o.slice(0,t.limit):o;return this.parseRegistryEntries(e,r,n.registryType,n.ttl)}catch(i){throw this.logger.error(`Failed to get registry: ${i}`),i}}async submitMessage(e,t){try{const{valid:i,errors:n}=this.validateMessage(t);if(!i)throw new Error(`Invalid HCS-2 message: ${n.join(", ")}`);const o=B({topicId:e,message:JSON.stringify(t)}),r=await this.executeWithWallet(o);if(r?.error)throw new Error(r.error);return r.result}catch(i){throw this.logger.error(`Failed to submit message: ${i}`),i}}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 B1={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*))$/},P1=n.z.string().regex(B1.HEDERA_ACCOUNT_REGEX,"Invalid Hedera account ID format"),L1=n.z.string().regex(/^\d+$/,"Must be a valid number").max(B1.MAX_NUMBER_LENGTH,`Max ${B1.MAX_NUMBER_LENGTH} digits`),U1=n.z.string().min(1,"Tick cannot be empty").transform(e=>e.toLowerCase().trim()),F1=n.z.object({p:n.z.literal("hcs-20"),m:n.z.string().optional()}),M1=F1.extend({op:n.z.literal("deploy"),name:n.z.string().min(1).max(B1.MAX_NAME_LENGTH),tick:U1,max:L1,lim:L1.optional(),metadata:n.z.string().max(B1.MAX_METADATA_LENGTH).optional()}),D1=F1.extend({op:n.z.literal("mint"),tick:U1,amt:L1,to:P1}),z1=F1.extend({op:n.z.literal("burn"),tick:U1,amt:L1,from:P1}),$1=F1.extend({op:n.z.literal("transfer"),tick:U1,amt:L1,from:P1,to:P1}),q1=F1.extend({op:n.z.literal("register"),name:n.z.string().min(1).max(B1.MAX_NAME_LENGTH),metadata:n.z.string().max(B1.MAX_METADATA_LENGTH).optional(),private:n.z.boolean(),t_id:P1}),K1=n.z.discriminatedUnion("op",[M1,D1,z1,$1,q1]);class W1 extends Error{constructor(e){super(e),this.name="HCS20Error"}}class H1 extends W1{constructor(e,t){super(e),this.tick=t,this.name="PointsDeploymentError"}}class V1 extends W1{constructor(e,t,i,n,o,r){super(e),this.tick=t,this.from=i,this.to=n,this.amount=o,this.availableBalance=r,this.name="PointsTransferError"}}class G1 extends W1{constructor(e,t,i,n,o){super(e),this.tick=t,this.from=i,this.amount=n,this.availableBalance=o,this.name="PointsBurnError"}}class Z1 extends W1{constructor(e,t){super(e),this.validationErrors=t,this.name="PointsValidationError"}}class J1 extends W1{constructor(e,t){super(e),this.topicId=t,this.name="TopicRegistrationError"}}class Y1 extends W1{constructor(e){super(`Invalid Hedera account format: ${e}`),this.account=e,this.name="InvalidAccountFormatError"}}class X1{constructor(e){this.logger=e.logger||new y({module:"HCS20Client"}),this.network="mainnet"===e.network?"mainnet":"testnet",this.mirrorNode=new I(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0),this.registryTopicId=e.registryTopicId||B1.REGISTRY_TOPIC_ID,this.publicTopicId=e.publicTopicId||B1.PUBLIC_TOPIC_ID}validateMessage(e){try{return K1.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(!B1.HEDERA_ACCOUNT_REGEX.test(e))throw new Y1(e);return e}return e.toString()}topicToString(e){if("string"==typeof e){if(!B1.HEDERA_ACCOUNT_REGEX.test(e))throw new Y1(e);return e}return e.toString()}}var Q1=(e=>(e.FIXED_FEE="FIXED_FEE",e.FRACTIONAL_FEE="FRACTIONAL_FEE",e.ROYALTY_FEE="ROYALTY_FEE",e))(Q1||{});class e2{constructor(e){this.customFees=[],this.logger=e.logger,this.mirrorNode=new I(e.network,e.logger),this.defaultCollectorAccountId=e.defaultCollectorAccountId||""}static forHbar(e,t,i,n,o=[]){return new e2({network:i,logger:n,defaultCollectorAccountId:t}).addHbarFee(e,t,o)}static async forToken(e,t,i,n,o,r=[],a){const s=new e2({network:n,logger:o,defaultCollectorAccountId:i});return await s.addTokenFee(e,t,i,a,r),s}addHbarFee(e,t,i=[]){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:[...i],type:Q1.FIXED_FEE}),this}async addTokenFee(e,t,i,n,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 r=n;if(void 0===r)try{const e=await this.mirrorNode.getTokenInfo(t);e?.decimals?(r=parseInt(e.decimals,10),this.logger.info(`Fetched decimals for ${t}: ${r}`)):(this.logger.warn(`Could not fetch decimals for ${t}, defaulting to 0.`),r=0)}catch(a){this.logger.error(`Error fetching decimals for ${t}, defaulting to 0: ${a}`),r=0}return this.customFees.push({feeAmount:{amount:e*10**r,decimals:r},feeCollectorAccountId:i||this.defaultCollectorAccountId,feeTokenId:t,exemptAccounts:[...o],type:Q1.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 t2{constructor(){this.resolver=null,this.onUnavailableCallbacks=[],this.logger=y.getInstance({module:"ContentResolverRegistry"})}static getInstance(){return t2._instance||(t2._instance=new t2),t2._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(i){return this.logger.warn("Resolver operation failed, using fallback:",i),await t()}}}const i2=t2.getInstance();class n2{constructor(){this.contentStore=null,this.logger=y.getInstance({module:"ContentStoreService"})}static getInstance(){return n2._instance||(n2._instance=new n2),n2._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 o2=n2.getInstance();var r2="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==fx?fx:"undefined"!=typeof self?self:{};function a2(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var s2,c2={};function p2(){return s2||(s2=1,function(e){Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});for(var t={},i={byteLength:function(e){var t=c(e),i=t[0],n=t[1];return 3*(i+n)/4-n},toByteArray:function(e){var t,i,n=c(e),a=n[0],s=n[1],p=new r(function(e,t,i){return 3*(t+i)/4-i}(0,a,s)),l=0,u=s>0?a-4:a;for(i=0;i<u;i+=4)t=o[e.charCodeAt(i)]<<18|o[e.charCodeAt(i+1)]<<12|o[e.charCodeAt(i+2)]<<6|o[e.charCodeAt(i+3)],p[l++]=t>>16&255,p[l++]=t>>8&255,p[l++]=255&t;2===s&&(t=o[e.charCodeAt(i)]<<2|o[e.charCodeAt(i+1)]>>4,p[l++]=255&t);1===s&&(t=o[e.charCodeAt(i)]<<10|o[e.charCodeAt(i+1)]<<4|o[e.charCodeAt(i+2)]>>2,p[l++]=t>>8&255,p[l++]=255&t);return p},fromByteArray:function(e){for(var t,i=e.length,o=i%3,r=[],a=16383,s=0,c=i-o;s<c;s+=a)r.push(l(e,s,s+a>c?c:s+a));1===o?(t=e[i-1],r.push(n[t>>2]+n[t<<4&63]+"==")):2===o&&(t=(e[i-2]<<8)+e[i-1],r.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return r.join("")}},n=[],o=[],r="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)n[s]=a[s],o[a.charCodeAt(s)]=s;function c(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var i=e.indexOf("=");return-1===i&&(i=t),[i,i===t?0:4-i%4]}function p(e){return n[e>>18&63]+n[e>>12&63]+n[e>>6&63]+n[63&e]}function l(e,t,i){for(var n,o=[],r=t;r<i;r+=3)n=(e[r]<<16&16711680)+(e[r+1]<<8&65280)+(255&e[r+2]),o.push(p(n));return o.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63;var u={
|
|
157
|
+
*/().extname,a=/^\s*([^;\s]*)(?:;|\s|$)/,s=/^text\//i;function c(e){if(!e||"string"!=typeof e)return!1;var t=a.exec(e),i=t&&o[t[1].toLowerCase()];return i&&i.charset?i.charset:!(!t||!s.test(t[1]))&&"UTF-8"}e.charset=c,e.charsets={lookup:c},e.contentType=function(t){if(!t||"string"!=typeof t)return!1;var i=-1===t.indexOf("/")?e.lookup(t):t;if(!i)return!1;if(-1===i.indexOf("charset")){var n=e.charset(i);n&&(i+="; charset="+n.toLowerCase())}return i},e.extension=function(t){if(!t||"string"!=typeof t)return!1;var i=a.exec(t),n=i&&e.extensions[i[1].toLowerCase()];return!(!n||!n.length)&&n[0]},e.extensions=Object.create(null),e.lookup=function(t){if(!t||"string"!=typeof t)return!1;var i=r("x."+t).toLowerCase().substr(1);return i&&e.types[i]||!1},e.types=Object.create(null),t=e.extensions,i=e.types,n=["nginx","apache",void 0,"iana"],Object.keys(o).forEach(function(e){var r=o[e],a=r.extensions;if(a&&a.length){t[e]=a;for(var s=0;s<a.length;s++){var c=a[s];if(i[c]){var p=n.indexOf(o[i[c]].source),l=n.indexOf(r.source);if("application/octet-stream"!==i[c]&&(p>l||p===l&&"application/"===i[c].substr(0,12)))continue}i[c]=e}}})}(EZ));var jZ=(e=>(e[e.PERSONAL=0]="PERSONAL",e[e.AI_AGENT=1]="AI_AGENT",e[e.MCP_SERVER=2]="MCP_SERVER",e))(jZ||{}),CZ=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(CZ||{}),NZ=(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))(NZ||{}),BZ=(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))(BZ||{}),PZ=(e=>(e.DNS="dns",e.SIGNATURE="signature",e.CHALLENGE="challenge",e))(PZ||{});const LZ=Uo({platform:Co().min(1),handle:Co().min(1)}),UZ=Uo({type:Ko(CZ),capabilities:Lo(Ko(NZ)).min(1),model:Co().min(1),creator:Co().optional()}),FZ=Uo({url:Co().min(1),transport:qo(["stdio","sse"])}),MZ=Uo({type:Ko(PZ),value:Co(),dns_field:Co().optional(),challenge_path:Co().optional()}),DZ=Uo({minVersion:Co().optional()}),zZ=Uo({name:Co().min(1),description:Co().min(1)}),$Z=Uo({name:Co().min(1),description:Co().min(1)}),qZ=Uo({version:Co().min(1),connectionInfo:FZ,services:Lo(Ko(BZ)).min(1),description:Co().min(1),verification:MZ.optional(),host:DZ.optional(),capabilities:Lo(Co()).optional(),resources:Lo(zZ).optional(),tools:Lo($Z).optional(),maintainer:Co().optional(),repository:Co().optional(),docs:Co().optional()}),KZ=Uo({version:Co().min(1),type:Ko(jZ),display_name:Co().min(1),alias:Co().optional(),bio:Co().optional(),socials:Lo(LZ).optional(),profileImage:Co().optional(),properties:Do(Po()).optional(),inboundTopicId:Co().optional(),outboundTopicId:Co().optional()}),WZ=KZ.extend({type:$o(jZ.PERSONAL),language:Co().optional(),timezone:Co().optional()}),HZ=KZ.extend({type:$o(jZ.AI_AGENT),aiAgent:UZ}),VZ=KZ.extend({type:$o(jZ.MCP_SERVER),mcpServer:qZ});Fo([WZ,HZ,VZ]);const GZ=Uo({p:$o("hcs-12")}),ZZ=Co().regex(/^\d+\.\d+\.\d+$/,"Invalid Hedera address format"),JZ=Co().regex(/^[a-f0-9]{64}$/,"Invalid SHA-256 hash format"),YZ=Uo({format:qo(["tar.gz","zip","car"]),root_manifest:Co(),includes_lockfile:Bo(),workspace_members:Lo(Co()).optional()}),XZ=Uo({source_t_id:ZZ,source_hash:JZ,compiler_version:Co(),cargo_version:Co(),target:$o("wasm32-unknown-unknown"),profile:Co(),build_flags:Lo(Co()),lockfile_hash:JZ,source_structure:YZ}),QZ=zo(()=>Uo({type:Co().optional(),required:Lo(Co()).optional(),properties:Do(QZ).optional(),pattern:Co().optional(),minimum:No().optional(),maximum:No().optional(),regex:Co().optional(),min:No().optional(),max:No().optional(),length:No().optional(),email:Bo().optional(),url:Bo().optional(),uuid:Bo().optional(),cuid:Bo().optional(),cuid2:Bo().optional(),ulid:Bo().optional(),datetime:Bo().optional(),ip:Bo().optional(),startsWith:Co().optional(),endsWith:Co().optional(),includes:Co().optional(),gt:No().optional(),gte:No().optional(),lt:No().optional(),lte:No().optional(),int:Bo().optional(),positive:Bo().optional(),nonnegative:Bo().optional(),negative:Bo().optional(),nonpositive:Bo().optional(),multipleOf:No().optional(),finite:Bo().optional(),safe:Bo().optional(),nonempty:Bo().optional(),literal:Fo([Co(),No(),Bo()]).optional(),enum:Lo(Co()).optional(),nullable:Bo().optional(),nullish:Bo().optional(),optional:Bo().optional(),element:Po().optional(),shape:Do(Po()).optional(),strict:Bo().optional(),passthrough:Bo().optional(),catchall:Po().optional()}));Uo({p:$o("hcs-12"),op:$o("register"),t_id:ZZ,hash:JZ,wasm_hash:JZ,js_t_id:ZZ.optional(),js_hash:JZ.optional(),interface_version:Co().regex(/^\d+\.\d+\.\d+$/,"Invalid version format").optional(),info_t_id:ZZ.optional(),source_verification:XZ.optional(),previous_version:Co().optional(),migration_notes:Co().optional(),validation_rules:Do(QZ).optional(),m:Co().optional()}),Uo({p:$o("hcs-12"),op:qo(["register","template"]),name:Co(),version:Co().regex(/^\d+\.\d+\.\d+$/,"Invalid semver format"),data:Fo([Po(),Co()]).optional(),t_id:ZZ.optional()}),qo(["register","add-action","add-block","update"]);const eJ=GZ.extend({op:$o("register"),name:Co(),version:Co().regex(/^\d+\.\d+\.\d+$/,"Invalid semver format"),description:Co().optional(),tags:Lo(Co()).optional(),author:Co().optional()}),tJ=GZ.extend({op:$o("add-action"),t_id:ZZ,alias:Co(),config:Po().optional(),data:ZZ.optional()}),iJ=GZ.extend({op:$o("add-block"),block_t_id:ZZ,actions:Do(Co(),ZZ).optional(),attributes:Do(Po()).optional(),children:Lo(Co()).optional(),data:ZZ.optional()}),nJ=GZ.extend({op:$o("update"),description:Co().optional(),tags:Lo(Co()).optional()});Uo({type:qo(["vertical","horizontal","grid"]),responsive:Bo().optional(),containerClass:Co().optional()}),Uo({source_t_id:ZZ,source_hash:JZ,description:Co().optional()}),Mo("op",[eJ,tJ,iJ,nJ]),GZ.extend({op:$o("register"),t_id:ZZ,name:Co().max(100,"Name must be 100 characters or less"),description:Co().max(500,"Description must be 500 characters or less").optional(),tags:Lo(Co()).max(10,"Maximum 10 tags allowed").optional(),category:Co().optional(),featured:Bo().optional(),icon:Co().optional(),author:Co().optional(),website:Co().url().optional()});const oJ=Co().regex(/^\d+\.\d+\.\d+$/,{message:"Topic ID must be in Hedera format (e.g., '0.0.123456')"}),rJ=Uo({p:Co().regex(/^hcs-\d+$/,{message:"Protocol must be in format 'hcs-N' where N is a number"}),op:qo(["register","update","delete","migrate"]),m:Co().max(500,"Memo must not exceed 500 characters").optional(),ttl:No().int().positive().optional()});Mo("op",[rJ.extend({op:$o("register"),t_id:oJ,metadata:Co().optional()}),rJ.extend({op:$o("update"),uid:Co(),t_id:oJ,metadata:Co().optional()}),rJ.extend({op:$o("delete"),uid:Co()}),rJ.extend({op:$o("migrate"),t_id:oJ,metadata:Co().optional()})]);const aJ=18,sJ=100,cJ=100,pJ=/^(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))\.(0|(?:[1-9]\d*))$/,lJ=Co().regex(pJ,"Invalid Hedera account ID format"),uJ=Co().regex(/^\d+$/,"Must be a valid number").max(aJ,`Max ${aJ} digits`),dJ=Co().min(1,"Tick cannot be empty").transform(e=>e.toLowerCase().trim()),fJ=Uo({p:$o("hcs-20"),m:Co().optional()});Mo("op",[fJ.extend({op:$o("deploy"),name:Co().min(1).max(sJ),tick:dJ,max:uJ,lim:uJ.optional(),metadata:Co().max(cJ).optional()}),fJ.extend({op:$o("mint"),tick:dJ,amt:uJ,to:lJ}),fJ.extend({op:$o("burn"),tick:dJ,amt:uJ,from:lJ}),fJ.extend({op:$o("transfer"),tick:dJ,amt:uJ,from:lJ,to:lJ}),fJ.extend({op:$o("register"),name:Co().min(1).max(sJ),metadata:Co().max(cJ).optional(),private:Bo(),t_id:lJ})]);(class e{constructor(){this.resolver=null,this.onUnavailableCallbacks=[],this.logger=Gi.getInstance({module:"ContentResolverRegistry"})}static getInstance(){return e._instance||(e._instance=new e),e._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(i){return this.logger.warn("Resolver operation failed, using fallback:",i),await t()}}}).getInstance();(class e{constructor(){this.contentStore=null,this.logger=Gi.getInstance({module:"ContentStoreService"})}static getInstance(){return e._instance||(e._instance=new e),e._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}}).getInstance();class mJ{constructor(e){if(F(this,"accountId"),F(this,"privateKey"),F(this,"baseUrl"),F(this,"network"),this.accountId=e.accountId,"string"==typeof e.privateKey){const t=Zo(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,i;const n=await wi.get(`${this.baseUrl}/api/auth/request-signature`,{headers:{"x-session":this.accountId}});if(!(null==(e=n.data)?void 0:e.message))throw new Error("Failed to get signature message");const o=n.data.message,r=await this.signMessage(o),a=await wi.post(`${this.baseUrl}/api/auth/authenticate`,{authData:{id:this.accountId,signature:r,data:o,network:this.network},include:"apiKey"});if(!(null==(i=null==(t=a.data)?void 0:t.user)?void 0:i.sessionToken))throw new Error("Authentication failed");return{apiKey:a.data.apiKey}}async signMessage(e){const t=(new TextEncoder).encode(e),i=await this.privateKey.sign(t);return Y.from(i).toString("hex")}}class hJ{constructor(e){F(this,"accountId"),F(this,"signer"),F(this,"baseUrl"),F(this,"network"),F(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,i;const n=await wi.get(`${this.baseUrl}/api/auth/request-signature`,{headers:{"x-session":this.accountId}});if(!(null==(e=n.data)?void 0:e.message))throw new Error("Failed to get signature message");const o=n.data.message,r=await this.signMessage(JSON.stringify(o)),a=await wi.post(`${this.baseUrl}/api/auth/authenticate`,{authData:{id:this.accountId,signature:r,data:o,network:this.network},include:"apiKey"});if(!(null==(i=null==(t=a.data)?void 0:t.user)?void 0:i.sessionToken))throw new Error("Authentication failed");return{apiKey:a.data.apiKey}}async signMessage(e){try{const t=(new TextEncoder).encode(e);this.logger.debug("signing message");const i=await this.signer.sign([t],{encoding:"utf-8"});return Y.from(null==i?void 0:i[0].signature).toString("hex")}catch(mxe){throw this.logger.error("Failed to sign message",mxe),new Error("Failed to sign message")}}}const gJ={get:(e,t)=>127&e[t+3]|e[t+2]<<7|e[t+1]<<14|e[t]<<21,len:4},yJ=4100;function vJ(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 bJ(e,t,i){i={offset:0,...i};for(const[n,o]of t.entries())if(i.mask){if(o!==(i.mask[n]&e[n+i.offset]))return!1}else if(o!==e[n+i.offset])return!1;return!0}class xJ{constructor(e){F(this,"detectConfident",async e=>{if(this.buffer=new Uint8Array(yJ),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(gJ);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 i;return await new xZ(e).unzip(e=>{switch(e.filename){case"META-INF/mozilla.rsa":return i={ext:"xpi",mime:"application/x-xpinstall"},{stop:!0};case"META-INF/MANIFEST.MF":return i={ext:"jar",mime:"application/java-archive"},{stop:!0};case"mimetype":return{async handler(e){const t=new TextDecoder("utf-8").decode(e).trim();i=vJ(t)},stop:!0};case"[Content_Types].xml":return{async handler(e){let t=new TextDecoder("utf-8").decode(e);const n=t.indexOf('.main+xml"');if(-1===n){const e="application/vnd.ms-package.3dmanufacturing-3dmodel+xml";t.includes(`ContentType="${e}"`)&&(i=vJ(e))}else{t=t.slice(0,Math.max(0,n));const e=t.lastIndexOf('"'),o=t.slice(Math.max(0,e+1));i=vJ(o)}},stop:!0};default:return/classes\d*\.dex/.test(e.filename)?(i={ext:"apk",mime:"application/vnd.android.package-archive"},{stop:!0}):{}}}),i??{ext:"zip",mime:"application/zip"}}if(this.checkString("OggS")){await e.ignore(28);const n=new Uint8Array(8);return await e.readBuffer(n),bJ(n,[79,112,117,115,72,101,97,100])?{ext:"opus",mime:"audio/ogg; codecs=opus"}:bJ(n,[128,116,104,101,111,114,97])?{ext:"ogv",mime:"video/ogg"}:bJ(n,[1,118,105,100,101,111,0])?{ext:"ogm",mime:"video/ogg"}:bJ(n,[127,70,76,65,67])?{ext:"oga",mime:"audio/ogg"}:bJ(n,[83,112,101,101,120,32,32])?{ext:"spx",mime:"audio/ogg"}:bJ(n,[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 r=await this.readTiffHeader(!0);if(r)return r}if(this.checkString("MAC "))return{ext:"ape",mime:"audio/ape"};if(this.check([26,69,223,163])){async function a(){const t=await e.peekNumber(nG);let i=128,n=0;for(;0===(t&i)&&0!==i;)++n,i>>=1;const o=new Uint8Array(n+1);return await e.readBuffer(o),o}async function s(){const e=await a(),t=await a();t[0]^=128>>t.length-1;const i=Math.min(6,t.length),n=new DataView(e.buffer),o=new DataView(t.buffer,t.length-i,i);return{id:_Z(n),len:_Z(o)}}async function c(t){for(;t>0;){const i=await s();if(17026===i.id){return(await e.readToken(new lG(i.len))).replaceAll(/\00.*$/g,"")}await e.ignore(i.len),--t}}const p=await s();switch(await c(p.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 l=new lG(4,"latin1").get(this.buffer,2);if(l.match("^d*")&&l>=1e3&&l<=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 lG(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(cG),type:await e.readToken(new lG(4,"latin1"))}}await e.ignore(8);do{const d=await u();if(d.length<0)return;switch(d.type){case"IDAT":return{ext:"png",mime:"image/png"};case"acTL":return{ext:"apng",mime:"image/apng"};default:await e.ignore(d.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 f=new lG(4,"latin1").get(this.buffer,8).replace("\0"," ").trim();switch(f){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 f.startsWith("3g")?f.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 m(){const t=new Uint8Array(16);return await e.readBuffer(t),{id:t,size:Number(await e.readToken(pG))}}for(await e.ignore(30);e.position+24<e.fileInfo.size;){const h=await m();let g=h.size-24;if(bJ(h.id,[145,7,220,183,183,169,207,17,142,230,0,192,12,32,83,101])){const y=new Uint8Array(16);if(g-=await e.readBuffer(y),bJ(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(bJ(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(g)}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 lG(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 v=new DataView(this.buffer.buffer).getUint32(12,!0);if(v>12&&this.buffer.length>=v+16)try{const b=(new TextDecoder).decode(this.buffer.subarray(16,v+16));if(JSON.parse(b).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 i=Number.parseInt(new lG(6).get(e,148).replace(/\0.*$/,"").trim(),8);if(Number.isNaN(i))return!1;let n=256;for(let o=t;o<t+148;o++)n+=e[o];for(let o=t+156;o<t+512;o++)n+=e[o];return i===n}(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)}),F(this,"detectImprecise",async e=>{if(this.buffer=new Uint8Array(yJ),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 i of this.detectors){const n=await i.detect(e);if(n)return n;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 i,n;if((null==t?void 0:t.length)>1)return this.fromTokenizer((i=t,n=this.tokenizerOptions,new bG(i,n)))}async fromBlob(e){return this.fromStream(e.stream())}async fromStream(e){const t=await xG(e,this.tokenizerOptions);try{return await this.fromTokenizer(t)}finally{await t.close()}}async toDetectionStream(e,t){const{sampleSize:i=yJ}=t;let n,o;const r=e.getReader({mode:"byob"});try{const{value:e,done:t}=await r.read(new Uint8Array(i));if(o=e,!t&&e)try{n=await this.fromBuffer(e.subarray(0,i))}catch(c){if(!(c instanceof uG))throw c;n=void 0}o=e}finally{r.releaseLock()}const a=new TransformStream({async start(e){e.enqueue(o)},transform(e,t){t.enqueue(e)}}),s=e.pipeThrough(a);return s.fileType=n,s}check(e,t){return bJ(this.buffer,e,t)}checkString(e,t){return this.check((i=e,[...i].map(e=>e.charCodeAt(0))),t);var i}async readTiffTag(e){const t=await this.tokenizer.readToken(e?rG:oG);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?rG:oG);for(let i=0;i<t;++i){const t=await this.readTiffTag(e);if(t)return t}}async readTiffHeader(e){const t=(e?rG:oG).get(this.buffer,2),i=(e?sG:aG).get(this.buffer,4);if(42===t){if(i>=6){if(this.checkString("CR",{offset:8}))return{ext:"cr2",mime:"image/x-canon-cr2"};if(i>=8){const t=(e?rG:oG).get(this.buffer,8),i=(e?rG:oG).get(this.buffer,10);if(28===t&&254===i||31===t&&11===i)return{ext:"nef",mime:"image/x-nikon-nef"}}}await this.tokenizer.ignore(i);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 wJ=Object.create(null);wJ.open="0",wJ.close="1",wJ.ping="2",wJ.pong="3",wJ.message="4",wJ.upgrade="5",wJ.noop="6";const kJ=Object.create(null);Object.keys(wJ).forEach(e=>{kJ[wJ[e]]=e});const _J={type:"error",data:"parser error"},EJ="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===Object.prototype.toString.call(Blob),SJ="function"==typeof ArrayBuffer,TJ=e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e&&e.buffer instanceof ArrayBuffer,AJ=({type:e,data:t},i,n)=>EJ&&t instanceof Blob?i?n(t):IJ(t,n):SJ&&(t instanceof ArrayBuffer||TJ(t))?i?n(t):IJ(new Blob([t]),n):n(wJ[e]+(t||"")),IJ=(e,t)=>{const i=new FileReader;return i.onload=function(){const e=i.result.split(",")[1];t("b"+(e||""))},i.readAsDataURL(e)};function RJ(e){return e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):new Uint8Array(e.buffer,e.byteOffset,e.byteLength)}let OJ;const jJ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",CJ="undefined"==typeof Uint8Array?[]:new Uint8Array(256);for(let hxe=0;hxe<64;hxe++)CJ[jJ.charCodeAt(hxe)]=hxe;const NJ="function"==typeof ArrayBuffer,BJ=(e,t)=>{if("string"!=typeof e)return{type:"message",data:LJ(e,t)};const i=e.charAt(0);if("b"===i)return{type:"message",data:PJ(e.substring(1),t)};return kJ[i]?e.length>1?{type:kJ[i],data:e.substring(1)}:{type:kJ[i]}:_J},PJ=(e,t)=>{if(NJ){const i=(e=>{let t,i,n,o,r,a=.75*e.length,s=e.length,c=0;"="===e[e.length-1]&&(a--,"="===e[e.length-2]&&a--);const p=new ArrayBuffer(a),l=new Uint8Array(p);for(t=0;t<s;t+=4)i=CJ[e.charCodeAt(t)],n=CJ[e.charCodeAt(t+1)],o=CJ[e.charCodeAt(t+2)],r=CJ[e.charCodeAt(t+3)],l[c++]=i<<2|n>>4,l[c++]=(15&n)<<4|o>>2,l[c++]=(3&o)<<6|63&r;return p})(e);return LJ(i,t)}return{base64:!0,data:e}},LJ=(e,t)=>"blob"===t?e instanceof Blob?e:new Blob([e]):e instanceof ArrayBuffer?e:e.buffer,UJ=String.fromCharCode(30);function FJ(){return new TransformStream({transform(e,t){!function(e,t){EJ&&e.data instanceof Blob?e.data.arrayBuffer().then(RJ).then(t):SJ&&(e.data instanceof ArrayBuffer||TJ(e.data))?t(RJ(e.data)):AJ(e,!1,e=>{OJ||(OJ=new TextEncoder),t(OJ.encode(e))})}(e,i=>{const n=i.length;let o;if(n<126)o=new Uint8Array(1),new DataView(o.buffer).setUint8(0,n);else if(n<65536){o=new Uint8Array(3);const e=new DataView(o.buffer);e.setUint8(0,126),e.setUint16(1,n)}else{o=new Uint8Array(9);const e=new DataView(o.buffer);e.setUint8(0,127),e.setBigUint64(1,BigInt(n))}e.data&&"string"!=typeof e.data&&(o[0]|=128),t.enqueue(o),t.enqueue(i)})}})}let MJ;function DJ(e){return e.reduce((e,t)=>e+t.length,0)}function zJ(e,t){if(e[0].length===t)return e.shift();const i=new Uint8Array(t);let n=0;for(let o=0;o<t;o++)i[o]=e[0][n++],n===e[0].length&&(e.shift(),n=0);return e.length&&n<e[0].length&&(e[0]=e[0].slice(n)),i}function $J(e){if(e)return function(e){for(var t in $J.prototype)e[t]=$J.prototype[t];return e}(e)}$J.prototype.on=$J.prototype.addEventListener=function(e,t){return this._callbacks=this._callbacks||{},(this._callbacks["$"+e]=this._callbacks["$"+e]||[]).push(t),this},$J.prototype.once=function(e,t){function i(){this.off(e,i),t.apply(this,arguments)}return i.fn=t,this.on(e,i),this},$J.prototype.off=$J.prototype.removeListener=$J.prototype.removeAllListeners=$J.prototype.removeEventListener=function(e,t){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var i,n=this._callbacks["$"+e];if(!n)return this;if(1==arguments.length)return delete this._callbacks["$"+e],this;for(var o=0;o<n.length;o++)if((i=n[o])===t||i.fn===t){n.splice(o,1);break}return 0===n.length&&delete this._callbacks["$"+e],this},$J.prototype.emit=function(e){this._callbacks=this._callbacks||{};for(var t=new Array(arguments.length-1),i=this._callbacks["$"+e],n=1;n<arguments.length;n++)t[n-1]=arguments[n];if(i){n=0;for(var o=(i=i.slice(0)).length;n<o;++n)i[n].apply(this,t)}return this},$J.prototype.emitReserved=$J.prototype.emit,$J.prototype.listeners=function(e){return this._callbacks=this._callbacks||{},this._callbacks["$"+e]||[]},$J.prototype.hasListeners=function(e){return!!this.listeners(e).length};const qJ="function"==typeof Promise&&"function"==typeof Promise.resolve?e=>Promise.resolve().then(e):(e,t)=>t(e,0),KJ="undefined"!=typeof self?self:"undefined"!=typeof window?window:Function("return this")();function WJ(e,...t){return t.reduce((t,i)=>(e.hasOwnProperty(i)&&(t[i]=e[i]),t),{})}const HJ=KJ.setTimeout,VJ=KJ.clearTimeout;function GJ(e,t){t.useNativeTimers?(e.setTimeoutFn=HJ.bind(KJ),e.clearTimeoutFn=VJ.bind(KJ)):(e.setTimeoutFn=KJ.setTimeout.bind(KJ),e.clearTimeoutFn=KJ.clearTimeout.bind(KJ))}function ZJ(e){return"string"==typeof e?function(e){let t=0,i=0;for(let n=0,o=e.length;n<o;n++)t=e.charCodeAt(n),t<128?i+=1:t<2048?i+=2:t<55296||t>=57344?i+=3:(n++,i+=4);return i}(e):Math.ceil(1.33*(e.byteLength||e.size))}function JJ(){return Date.now().toString(36).substring(3)+Math.random().toString(36).substring(2,5)}class YJ extends Error{constructor(e,t,i){super(e),this.description=t,this.context=i,this.type="TransportError"}}class XJ extends $J{constructor(e){super(),this.writable=!1,GJ(this,e),this.opts=e,this.query=e.query,this.socket=e.socket,this.supportsBinary=!e.forceBase64}onError(e,t,i){return super.emitReserved("error",new YJ(e,t,i)),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=BJ(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 i in e)e.hasOwnProperty(i)&&(t.length&&(t+="&"),t+=encodeURIComponent(i)+"="+encodeURIComponent(e[i]));return t}(e);return t.length?"?"+t:""}}class QJ extends XJ{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 i=e.split(UJ),n=[];for(let o=0;o<i.length;o++){const e=BJ(i[o],t);if(n.push(e),"error"===e.type)break}return n})(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 i=e.length,n=new Array(i);let o=0;e.forEach((e,r)=>{AJ(e,!1,e=>{n[r]=e,++o===i&&t(n.join(UJ))})})})(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]=JJ()),this.supportsBinary||t.sid||(t.b64=1),this.createUri(e,t)}}let eY=!1;try{eY="undefined"!=typeof XMLHttpRequest&&"withCredentials"in new XMLHttpRequest}catch(fxe){}const tY=eY;function iY(){}class nY extends QJ{constructor(e){if(super(e),"undefined"!=typeof location){const t="https:"===location.protocol;let i=location.port;i||(i=t?"443":"80"),this.xd="undefined"!=typeof location&&e.hostname!==location.hostname||i!==e.port}}doWrite(e,t){const i=this.request({method:"POST",data:e});i.on("success",t),i.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 oY=class e extends $J{constructor(e,t,i){super(),this.createRequest=e,GJ(this,i),this._opts=i,this._method=i.method||"GET",this._uri=t,this._data=void 0!==i.data?i.data:null,this._create()}_create(){var t;const i=WJ(this._opts,"agent","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","autoUnref");i.xdomain=!!this._opts.xd;const n=this._xhr=this.createRequest(i);try{n.open(this._method,this._uri,!0);try{if(this._opts.extraHeaders){n.setDisableHeaderCheck&&n.setDisableHeaderCheck(!0);for(let e in this._opts.extraHeaders)this._opts.extraHeaders.hasOwnProperty(e)&&n.setRequestHeader(e,this._opts.extraHeaders[e])}}catch(mxe){}if("POST"===this._method)try{n.setRequestHeader("Content-type","text/plain;charset=UTF-8")}catch(mxe){}try{n.setRequestHeader("Accept","*/*")}catch(mxe){}null===(t=this._opts.cookieJar)||void 0===t||t.addCookies(n),"withCredentials"in n&&(n.withCredentials=this._opts.withCredentials),this._opts.requestTimeout&&(n.timeout=this._opts.requestTimeout),n.onreadystatechange=()=>{var e;3===n.readyState&&(null===(e=this._opts.cookieJar)||void 0===e||e.parseCookies(n.getResponseHeader("set-cookie"))),4===n.readyState&&(200===n.status||1223===n.status?this._onLoad():this.setTimeoutFn(()=>{this._onError("number"==typeof n.status?n.status:0)},0))},n.send(this._data)}catch(mxe){return void this.setTimeoutFn(()=>{this._onError(mxe)},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=iY,t)try{this._xhr.abort()}catch(mxe){}"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(oY.requestsCount=0,oY.requests={},"undefined"!=typeof document)if("function"==typeof attachEvent)attachEvent("onunload",rY);else if("function"==typeof addEventListener){addEventListener("onpagehide"in KJ?"pagehide":"unload",rY,!1)}function rY(){for(let e in oY.requests)oY.requests.hasOwnProperty(e)&&oY.requests[e].abort()}const aY=function(){const e=sY({xdomain:!1});return e&&null!==e.responseType}();function sY(e){const t=e.xdomain;try{if("undefined"!=typeof XMLHttpRequest&&(!t||tY))return new XMLHttpRequest}catch(mxe){}if(!t)try{return new(KJ[["Active"].concat("Object").join("X")])("Microsoft.XMLHTTP")}catch(mxe){}}const cY="undefined"!=typeof navigator&&"string"==typeof navigator.product&&"reactnative"===navigator.product.toLowerCase();class pY extends XJ{get name(){return"websocket"}doOpen(){const e=this.uri(),t=this.opts.protocols,i=cY?{}:WJ(this.opts,"agent","perMessageDeflate","pfx","key","passphrase","cert","ca","ciphers","rejectUnauthorized","localAddress","protocolVersion","origin","maxPayload","family","checkServerIdentity");this.opts.extraHeaders&&(i.headers=this.opts.extraHeaders);try{this.ws=this.createSocket(e,t,i)}catch(fxe){return this.emitReserved("error",fxe)}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 i=e[t],n=t===e.length-1;AJ(i,this.supportsBinary,e=>{try{this.doWrite(i,e)}catch(mxe){}n&&qJ(()=>{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]=JJ()),this.supportsBinary||(t.b64=1),this.createUri(e,t)}}const lY=KJ.WebSocket||KJ.MozWebSocket;const uY={websocket:class extends pY{createSocket(e,t,i){return cY?new lY(e,t,i):t?new lY(e,t):new lY(e)}doWrite(e,t){this.ws.send(t)}},webtransport:class extends XJ{get name(){return"webtransport"}doOpen(){try{this._transport=new WebTransport(this.createUri("https"),this.opts.transportOptions[this.name])}catch(fxe){return this.emitReserved("error",fxe)}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){MJ||(MJ=new TextDecoder);const i=[];let n=0,o=-1,r=!1;return new TransformStream({transform(a,s){for(i.push(a);;){if(0===n){if(DJ(i)<1)break;const e=zJ(i,1);r=!(128&~e[0]),o=127&e[0],n=o<126?3:126===o?1:2}else if(1===n){if(DJ(i)<2)break;const e=zJ(i,2);o=new DataView(e.buffer,e.byteOffset,e.length).getUint16(0),n=3}else if(2===n){if(DJ(i)<8)break;const e=zJ(i,8),t=new DataView(e.buffer,e.byteOffset,e.length),r=t.getUint32(0);if(r>Math.pow(2,21)-1){s.enqueue(_J);break}o=r*Math.pow(2,32)+t.getUint32(4),n=3}else{if(DJ(i)<o)break;const e=zJ(i,o);s.enqueue(BJ(r?e:MJ.decode(e),t)),n=0}if(0===o||o>e){s.enqueue(_J);break}}}})}(Number.MAX_SAFE_INTEGER,this.socket.binaryType),i=e.readable.pipeThrough(t).getReader(),n=FJ();n.readable.pipeTo(e.writable),this._writer=n.writable.getWriter();const o=()=>{i.read().then(({done:e,value:t})=>{e||(this.onPacket(t),o())}).catch(e=>{})};o();const r={type:"open"};this.query.sid&&(r.data=`{"sid":"${this.query.sid}"}`),this._writer.write(r).then(()=>this.onOpen())})})}write(e){this.writable=!1;for(let t=0;t<e.length;t++){const i=e[t],n=t===e.length-1;this._writer.write(i).then(()=>{n&&qJ(()=>{this.writable=!0,this.emitReserved("drain")},this.setTimeoutFn)})}}doClose(){var e;null===(e=this._transport)||void 0===e||e.close()}},polling:class extends nY{constructor(e){super(e);const t=e&&e.forceBase64;this.supportsBinary=aY&&!t}request(e={}){return Object.assign(e,{xd:this.xd},this.opts),new oY(sY,this.uri(),e)}}},dY=/^(?:(?![^:@\/?#]+:[^:@\/]*@)(http|https|ws|wss):\/\/)?((?:(([^:@\/?#]*)(?::([^:@\/?#]*))?)?@)?((?:[a-f0-9]{0,4}:){2,7}[a-f0-9]{0,4}|[^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/,fY=["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"];function mY(e){if(e.length>8e3)throw"URI too long";const t=e,i=e.indexOf("["),n=e.indexOf("]");-1!=i&&-1!=n&&(e=e.substring(0,i)+e.substring(i,n).replace(/:/g,";")+e.substring(n,e.length));let o=dY.exec(e||""),r={},a=14;for(;a--;)r[fY[a]]=o[a]||"";return-1!=i&&-1!=n&&(r.source=t,r.host=r.host.substring(1,r.host.length-1).replace(/;/g,":"),r.authority=r.authority.replace("[","").replace("]","").replace(/;/g,":"),r.ipv6uri=!0),r.pathNames=function(e,t){const i=/\/{2,9}/g,n=t.replace(i,"/").split("/");"/"!=t.slice(0,1)&&0!==t.length||n.splice(0,1);"/"==t.slice(-1)&&n.splice(n.length-1,1);return n}(0,r.path),r.queryKey=function(e,t){const i={};return t.replace(/(?:^|&)([^&=]*)=?([^&]*)/g,function(e,t,n){t&&(i[t]=n)}),i}(0,r.query),r}const hY="function"==typeof addEventListener&&"function"==typeof removeEventListener,gY=[];hY&&addEventListener("offline",()=>{gY.forEach(e=>e())},!1);class yY extends $J{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 i=mY(e);t.hostname=i.host,t.secure="https"===i.protocol||"wss"===i.protocol,t.port=i.port,i.query&&(t.query=i.query)}else t.host&&(t.hostname=mY(t.host).host);GJ(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={},i=e.split("&");for(let n=0,o=i.length;n<o;n++){let e=i[n].split("=");t[decodeURIComponent(e[0])]=decodeURIComponent(e[1])}return t}(this.opts.query)),hY&&(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"})},gY.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 i=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](i)}_open(){if(0===this.transports.length)return void this.setTimeoutFn(()=>{this.emitReserved("error","No transports available")},0);const e=this.opts.rememberUpgrade&&yY.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",yY.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 i=this.writeBuffer[t].data;if(i&&(e+=ZJ(i)),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,qJ(()=>{this._onClose("ping timeout")},this.setTimeoutFn)),e}write(e,t,i){return this._sendPacket("message",e,t,i),this}send(e,t,i){return this._sendPacket("message",e,t,i),this}_sendPacket(e,t,i,n){if("function"==typeof t&&(n=t,t=void 0),"function"==typeof i&&(n=i,i=null),"closing"===this.readyState||"closed"===this.readyState)return;(i=i||{}).compress=!1!==i.compress;const o={type:e,data:t,options:i};this.emitReserved("packetCreate",o),this.writeBuffer.push(o),n&&this.once("flush",n),this.flush()}close(){const e=()=>{this._onClose("forced close"),this.transport.close()},t=()=>{this.off("upgrade",t),this.off("upgradeError",t),e()},i=()=>{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?i():e()}):this.upgrading?i():e()),this}_onError(e){if(yY.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(),hY&&(this._beforeunloadEventListener&&removeEventListener("beforeunload",this._beforeunloadEventListener,!1),this._offlineEventListener)){const e=gY.indexOf(this._offlineEventListener);-1!==e&&gY.splice(e,1)}this.readyState="closed",this.id=null,this.emitReserved("close",e,t),this.writeBuffer=[],this._prevBufferLen=0}}}yY.protocol=4;class vY extends yY{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),i=!1;yY.priorWebsocketSuccess=!1;const n=()=>{i||(t.send([{type:"ping",data:"probe"}]),t.once("packet",e=>{if(!i)if("pong"===e.type&&"probe"===e.data){if(this.upgrading=!0,this.emitReserved("upgrading",t),!t)return;yY.priorWebsocketSuccess="websocket"===t.name,this.transport.pause(()=>{i||"closed"!==this.readyState&&(p(),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(){i||(i=!0,p(),t.close(),t=null)}const r=e=>{const i=new Error("probe error: "+e);i.transport=t.name,o(),this.emitReserved("upgradeError",i)};function a(){r("transport closed")}function s(){r("socket closed")}function c(e){t&&e.name!==t.name&&o()}const p=()=>{t.removeListener("open",n),t.removeListener("error",r),t.removeListener("close",a),this.off("close",s),this.off("upgrading",c)};t.once("open",n),t.once("error",r),t.once("close",a),this.once("close",s),this.once("upgrading",c),-1!==this._upgrades.indexOf("webtransport")&&"webtransport"!==e?this.setTimeoutFn(()=>{i||t.open()},200):t.open()}onHandshake(e){this._upgrades=this._filterUpgrades(e.upgrades),super.onHandshake(e)}_filterUpgrades(e){const t=[];for(let i=0;i<e.length;i++)~this.transports.indexOf(e[i])&&t.push(e[i]);return t}}let bY=class extends vY{constructor(e,t={}){const i="object"==typeof e?e:t;(!i.transports||i.transports&&"string"==typeof i.transports[0])&&(i.transports=(i.transports||["polling","websocket","webtransport"]).map(e=>uY[e]).filter(e=>!!e)),super(e,i)}};const xY="function"==typeof ArrayBuffer,wY=Object.prototype.toString,kY="function"==typeof Blob||"undefined"!=typeof Blob&&"[object BlobConstructor]"===wY.call(Blob),_Y="function"==typeof File||"undefined"!=typeof File&&"[object FileConstructor]"===wY.call(File);function EY(e){return xY&&(e instanceof ArrayBuffer||(e=>"function"==typeof ArrayBuffer.isView?ArrayBuffer.isView(e):e.buffer instanceof ArrayBuffer)(e))||kY&&e instanceof Blob||_Y&&e instanceof File}function SY(e,t){if(!e||"object"!=typeof e)return!1;if(Array.isArray(e)){for(let t=0,i=e.length;t<i;t++)if(SY(e[t]))return!0;return!1}if(EY(e))return!0;if(e.toJSON&&"function"==typeof e.toJSON&&1===arguments.length)return SY(e.toJSON(),!0);for(const i in e)if(Object.prototype.hasOwnProperty.call(e,i)&&SY(e[i]))return!0;return!1}function TY(e){const t=[],i=e.data,n=e;return n.data=AY(i,t),n.attachments=t.length,{packet:n,buffers:t}}function AY(e,t){if(!e)return e;if(EY(e)){const i={_placeholder:!0,num:t.length};return t.push(e),i}if(Array.isArray(e)){const i=new Array(e.length);for(let n=0;n<e.length;n++)i[n]=AY(e[n],t);return i}if("object"==typeof e&&!(e instanceof Date)){const i={};for(const n in e)Object.prototype.hasOwnProperty.call(e,n)&&(i[n]=AY(e[n],t));return i}return e}function IY(e,t){return e.data=RY(e.data,t),delete e.attachments,e}function RY(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 i=0;i<e.length;i++)e[i]=RY(e[i],t);else if("object"==typeof e)for(const i in e)Object.prototype.hasOwnProperty.call(e,i)&&(e[i]=RY(e[i],t));return e}const OY=["connect","connect_error","disconnect","disconnecting","newListener","removeListener"];var jY;!function(e){e[e.CONNECT=0]="CONNECT",e[e.DISCONNECT=1]="DISCONNECT",e[e.EVENT=2]="EVENT",e[e.ACK=3]="ACK",e[e.CONNECT_ERROR=4]="CONNECT_ERROR",e[e.BINARY_EVENT=5]="BINARY_EVENT",e[e.BINARY_ACK=6]="BINARY_ACK"}(jY||(jY={}));function CY(e){return"[object Object]"===Object.prototype.toString.call(e)}class NY extends $J{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 i=t.type===jY.BINARY_EVENT;i||t.type===jY.BINARY_ACK?(t.type=i?jY.EVENT:jY.ACK,this.reconstructor=new BY(t),0===t.attachments&&super.emitReserved("decoded",t)):super.emitReserved("decoded",t)}else{if(!EY(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 i={type:Number(e.charAt(0))};if(void 0===jY[i.type])throw new Error("unknown packet type "+i.type);if(i.type===jY.BINARY_EVENT||i.type===jY.BINARY_ACK){const n=t+1;for(;"-"!==e.charAt(++t)&&t!=e.length;);const o=e.substring(n,t);if(o!=Number(o)||"-"!==e.charAt(t))throw new Error("Illegal attachments");i.attachments=Number(o)}if("/"===e.charAt(t+1)){const n=t+1;for(;++t;){if(","===e.charAt(t))break;if(t===e.length)break}i.nsp=e.substring(n,t)}else i.nsp="/";const n=e.charAt(t+1);if(""!==n&&Number(n)==n){const n=t+1;for(;++t;){const i=e.charAt(t);if(null==i||Number(i)!=i){--t;break}if(t===e.length)break}i.id=Number(e.substring(n,t+1))}if(e.charAt(++t)){const n=this.tryParse(e.substr(t));if(!NY.isPayloadValid(i.type,n))throw new Error("invalid payload");i.data=n}return i}tryParse(e){try{return JSON.parse(e,this.reviver)}catch(mxe){return!1}}static isPayloadValid(e,t){switch(e){case jY.CONNECT:return CY(t);case jY.DISCONNECT:return void 0===t;case jY.CONNECT_ERROR:return"string"==typeof t||CY(t);case jY.EVENT:case jY.BINARY_EVENT:return Array.isArray(t)&&("number"==typeof t[0]||"string"==typeof t[0]&&-1===OY.indexOf(t[0]));case jY.ACK:case jY.BINARY_ACK:return Array.isArray(t)}}destroy(){this.reconstructor&&(this.reconstructor.finishedReconstruction(),this.reconstructor=null)}}class BY{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=IY(this.reconPack,this.buffers);return this.finishedReconstruction(),e}return null}finishedReconstruction(){this.reconPack=null,this.buffers=[]}}const PY=Object.freeze(Object.defineProperty({__proto__:null,Decoder:NY,Encoder:class{constructor(e){this.replacer=e}encode(e){return e.type!==jY.EVENT&&e.type!==jY.ACK||!SY(e)?[this.encodeAsString(e)]:this.encodeAsBinary({type:e.type===jY.EVENT?jY.BINARY_EVENT:jY.BINARY_ACK,nsp:e.nsp,data:e.data,id:e.id})}encodeAsString(e){let t=""+e.type;return e.type!==jY.BINARY_EVENT&&e.type!==jY.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=TY(e),i=this.encodeAsString(t.packet),n=t.buffers;return n.unshift(i),n}},get PacketType(){return jY},protocol:5},Symbol.toStringTag,{value:"Module"}));function LY(e,t,i){return e.on(t,i),function(){e.off(t,i)}}const UY=Object.freeze({connect:1,connect_error:1,disconnect:1,disconnecting:1,newListener:1,removeListener:1});class FY extends $J{constructor(e,t,i){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,i&&i.auth&&(this.auth=i.auth),this._opts=Object.assign({},i),this.io._autoConnect&&this.open()}get disconnected(){return!this.connected}subEvents(){if(this.subs)return;const e=this.io;this.subs=[LY(e,"open",this.onopen.bind(this)),LY(e,"packet",this.onpacket.bind(this)),LY(e,"error",this.onerror.bind(this)),LY(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 i,n,o;if(UY.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 r={type:jY.EVENT,data:t,options:{}};if(r.options.compress=!1!==this.flags.compress,"function"==typeof t[t.length-1]){const e=this.ids++,i=t.pop();this._registerAckCallback(e,i),r.id=e}const a=null===(n=null===(i=this.io.engine)||void 0===i?void 0:i.transport)||void 0===n?void 0:n.writable,s=this.connected&&!(null===(o=this.io.engine)||void 0===o?void 0:o._hasPingExpired());return this.flags.volatile&&!a||(s?(this.notifyOutgoingListeners(r),this.packet(r)):this.sendBuffer.push(r)),this.flags={},this}_registerAckCallback(e,t){var i;const n=null!==(i=this.flags.timeout)&&void 0!==i?i:this._opts.ackTimeout;if(void 0===n)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"))},n),r=(...e)=>{this.io.clearTimeoutFn(o),t.apply(this,e)};r.withError=!0,this.acks[e]=r}emitWithAck(e,...t){return new Promise((i,n)=>{const o=(e,t)=>e?n(e):i(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 i={id:this._queueSeq++,tryCount:0,pending:!1,args:e,flags:Object.assign({fromQueue:!0},this.flags)};e.push((e,...n)=>{if(i!==this._queue[0])return;return null!==e?i.tryCount>this._opts.retries&&(this._queue.shift(),t&&t(e)):(this._queue.shift(),t&&t(null,...n)),i.pending=!1,this._drainQueue()}),this._queue.push(i),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:jY.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 jY.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 jY.EVENT:case jY.BINARY_EVENT:this.onevent(e);break;case jY.ACK:case jY.BINARY_ACK:this.onack(e);break;case jY.DISCONNECT:this.ondisconnect();break;case jY.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 i of t)i.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 i=!1;return function(...n){i||(i=!0,t.packet({type:jY.ACK,id:e,data:n}))}}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:jY.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 i=0;i<t.length;i++)if(e===t[i])return t.splice(i,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 i=0;i<t.length;i++)if(e===t[i])return t.splice(i,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 i of t)i.apply(this,e.data)}}}function MY(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}MY.prototype.duration=function(){var e=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var t=Math.random(),i=Math.floor(t*this.jitter*e);e=1&Math.floor(10*t)?e+i:e-i}return 0|Math.min(e,this.max)},MY.prototype.reset=function(){this.attempts=0},MY.prototype.setMin=function(e){this.ms=e},MY.prototype.setMax=function(e){this.max=e},MY.prototype.setJitter=function(e){this.jitter=e};class DY extends $J{constructor(e,t){var i;super(),this.nsps={},this.subs=[],e&&"object"==typeof e&&(t=e,e=void 0),(t=t||{}).path=t.path||"/socket.io",this.opts=t,GJ(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!==(i=t.randomizationFactor)&&void 0!==i?i:.5),this.backoff=new MY({min:this.reconnectionDelay(),max:this.reconnectionDelayMax(),jitter:this.randomizationFactor()}),this.timeout(null==t.timeout?2e4:t.timeout),this._readyState="closed",this.uri=e;const n=t.parser||PY;this.encoder=new n.Encoder,this.decoder=new n.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 bY(this.uri,this.opts);const t=this.engine,i=this;this._readyState="opening",this.skipReconnect=!1;const n=LY(t,"open",function(){i.onopen(),e&&e()}),o=t=>{this.cleanup(),this._readyState="closed",this.emitReserved("error",t),e?e(t):this.maybeReconnectOnOpen()},r=LY(t,"error",o);if(!1!==this._timeout){const e=this._timeout,i=this.setTimeoutFn(()=>{n(),o(new Error("timeout")),t.close()},e);this.opts.autoUnref&&i.unref(),this.subs.push(()=>{this.clearTimeoutFn(i)})}return this.subs.push(n),this.subs.push(r),this}connect(e){return this.open(e)}onopen(){this.cleanup(),this._readyState="open",this.emitReserved("open");const e=this.engine;this.subs.push(LY(e,"ping",this.onping.bind(this)),LY(e,"data",this.ondata.bind(this)),LY(e,"error",this.onerror.bind(this)),LY(e,"close",this.onclose.bind(this)),LY(this.decoder,"decoded",this.ondecoded.bind(this)))}onping(){this.emitReserved("ping")}ondata(e){try{this.decoder.add(e)}catch(mxe){this.onclose("parse error",mxe)}}ondecoded(e){qJ(()=>{this.emitReserved("packet",e)},this.setTimeoutFn)}onerror(e){this.emitReserved("error",e)}socket(e,t){let i=this.nsps[e];return i?this._autoConnect&&!i.active&&i.connect():(i=new FY(this,e,t),this.nsps[e]=i),i}_destroy(e){const t=Object.keys(this.nsps);for(const i of t){if(this.nsps[i].active)return}this._close()}_packet(e){const t=this.encoder.encode(e);for(let i=0;i<t.length;i++)this.engine.write(t[i],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 i;this.cleanup(),null===(i=this.engine)||void 0===i||i.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 i=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&&i.unref(),this.subs.push(()=>{this.clearTimeoutFn(i)})}}onreconnect(){const e=this.backoff.attempts;this._reconnecting=!1,this.backoff.reset(),this.emitReserved("reconnect",e)}}const zY={};function $Y(e,t){"object"==typeof e&&(t=e,e=void 0);const i=function(e,t="",i){let n=e;i=i||"undefined"!=typeof location&&location,null==e&&(e=i.protocol+"//"+i.host),"string"==typeof e&&("/"===e.charAt(0)&&(e="/"===e.charAt(1)?i.protocol+e:i.host+e),/^(https?|wss?):\/\//.test(e)||(e=void 0!==i?i.protocol+"//"+e:"https://"+e),n=mY(e)),n.port||(/^(http|ws)$/.test(n.protocol)?n.port="80":/^(http|ws)s$/.test(n.protocol)&&(n.port="443")),n.path=n.path||"/";const o=-1!==n.host.indexOf(":")?"["+n.host+"]":n.host;return n.id=n.protocol+"://"+o+":"+n.port+t,n.href=n.protocol+"://"+o+(i&&i.port===n.port?"":":"+n.port),n}(e,(t=t||{}).path||"/socket.io"),n=i.source,o=i.id,r=i.path,a=zY[o]&&r in zY[o].nsps;let s;return t.forceNew||t["force new connection"]||!1===t.multiplex||a?s=new DY(n,t):(zY[o]||(zY[o]=new DY(n,t)),s=zY[o]),i.query&&!t.query&&(t.query=i.queryKey),s.socket(i.path,t)}Object.assign($Y,{Manager:DY,Socket:FY,io:$Y,connect:$Y});const qY=class e{constructor(e){if(F(this,"client"),F(this,"config"),F(this,"logger",Fi.getInstance()),F(this,"socket",null),F(this,"socketConnected",!1),F(this,"connectionMode","auto"),F(this,"wsBaseUrl",null),this.config=e,!e.apiKey)throw new Mi("API key is required");if(!e.network)throw new Mi("Network is required");const t={"x-api-key":e.apiKey,"Content-Type":"application/json"};this.client=wi.create({baseURL:"https://v2-api.tier.bot/api",headers:t}),this.logger=Fi.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 wi.get(e),i=t.headers["content-type"]||"";return{size:parseInt(t.headers["content-length"]||"0",10),mimeType:i}}catch(t){throw this.logger.error("Error fetching file metadata:",t),new Mi("Unable to fetch file metadata")}}getMimeType(t){const i=t.toLowerCase().split(".").pop();if(!i)throw new Mi("File must have an extension");const n=e.VALID_MIME_TYPES[i];if(!n)throw new Mi(`Unsupported file type: ${i}`);return n}validateRequest(t){if(this.logger.debug("Validating request:",t),!t.holderId||""===t.holderId.trim())throw this.logger.warn("holderId is missing or empty"),new Mi("holderId is required");if(!e.VALID_MODES.includes(t.mode))throw new Mi(`Invalid mode: ${t.mode}. Must be one of: ${e.VALID_MODES.join(", ")}`);if("hashinal"===t.mode&&!t.jsonFileURL&&!t.metadataObject)throw new Mi("Hashinal mode requires either jsonFileURL or metadataObject");if(t.onlyJSONCollection&&"hashinal-collection"!==t.mode)throw new Mi("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 Mi("Base64 data is required");const i=t.base64.replace(/^data:.*?;base64,/,"");if(Math.ceil(.75*i.length)>e.MAX_BASE64_SIZE)throw new Mi(`File size exceeds maximum limit of ${e.MAX_BASE64_SIZE/1024/1024}MB`);const n=t.mimeType||this.getMimeType(t.fileName);if(!this.validateMimeType(n))throw new Mi("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 Mi("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,""),i=J.from(t,"base64"),n=await async function(e,t){return new xJ(t).fromBuffer(e)}(i);return(null==n?void 0:n.mime)||"application/octet-stream"}catch(fxe){return this.logger.warn("Failed to detect MIME type from buffer"),"application/octet-stream"}}async startInscription(t){var i,n;try{this.validateRequest(t);let i=t.file.mimeType;if("url"===t.file.type){const n=await this.getFileMetadata(t.file.url);if(i=n.mimeType||i,n.size>e.MAX_URL_FILE_SIZE)throw new Mi(`File size exceeds maximum URL file limit of ${e.MAX_URL_FILE_SIZE/1024/1024}MB`)}else"base64"===t.file.type&&(i=await this.detectMimeTypeFromBase64(t.file.base64));if("image/vnd.microsoft.icon"===i&&(i=this.normalizeMimeType(i)),t.jsonFileURL){if("application/json"!==(await this.getFileMetadata(t.jsonFileURL)).mimeType)throw new Mi("JSON file must be of type application/json")}const n={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",{...n,fileURL:t.file.url}):await this.client.post("/inscriptions/start-inscription",{...n,fileBase64:t.file.base64,fileName:t.file.fileName,fileMimeType:i||this.getMimeType(t.file.fileName)}),o.data}catch(o){if(o instanceof Mi)throw o;if(wi.isAxiosError(o))throw new Error((null==(n=null==(i=o.response)?void 0:i.data)?void 0:n.message)||"Failed to start inscription");throw o}}async executeTransaction(e,t){var i,n;try{const r="mainnet"===t.network?o.Client.forMainnet():o.Client.forTestnet(),a=new Ho(t.network),s=await a.requestAccount(t.accountId),c=null==(i=null==s?void 0:s.key)?void 0:i._type,p="string"==typeof t.privateKey;let l;if(c&&p)l=(null==(n=null==c?void 0:c.toLowerCase())?void 0:n.includes("ecdsa"))?o.PrivateKey.fromStringECDSA(t.privateKey):o.PrivateKey.fromStringED25519(t.privateKey);else if(!c&&p){const e=p?Zo(t.privateKey):void 0;l="ed25519"===(null==e?void 0:e.detectedType)?o.PrivateKey.fromStringED25519(t.privateKey):o.PrivateKey.fromStringECDSA(t.privateKey)}else l=t.privateKey;r.setOperator(t.accountId,l);const u=o.TransferTransaction.fromBytes(J.from(e,"base64")),d=await u.sign(l),f=await d.execute(r),m=(await f.getReceipt(r)).status.toString();if("SUCCESS"!==m)throw new Error(`Transaction failed with status: ${m}`);return f.transactionId.toString()}catch(r){throw new Error(`Failed to execute transaction: ${r instanceof Error?r.message:"Unknown error"}`)}}async executeTransactionWithSigner(e,t){try{const i=o.TransferTransaction.fromBytes(J.from(e,"base64")),n=await i.executeWithSigner(t),r=(await n.getReceiptWithSigner(t)).status.toString();if("SUCCESS"!==r)throw new Error(`Transaction failed with status: ${r}`);return n.transactionId.toString()}catch(i){throw new Error(`Failed to execute transaction: ${i instanceof Error?i.message:"Unknown error"}`)}}async inscribeAndExecute(e,t,i,n){const o=(null==n?void 0:n.waitForCompletion)??!0,r=(null==n?void 0:n.maxWaitTime)??12e4,a=(null==n?void 0:n.checkInterval)??2e3;if(this.logger.debug("inscribeAndExecute called",{hasProgressCallback:!!i,connectionMode:this.connectionMode,wsBaseUrl:this.wsBaseUrl}),"http"!==this.connectionMode){const n="websocket"===this.connectionMode||"auto"===this.connectionMode&&await this.detectBestConnection();if(n)try{return await this.inscribeViaWebSocket(e,t,i)}catch(l){throw this.logger.error("WebSocket inscription failed, falling back to HTTP:",l),l}else this.logger.info(`Not using WebSocket: useWebSocket=${n}, wsBaseUrl=${this.wsBaseUrl}`)}else this.logger.info(`Not using WebSocket: hasCallback=${!!i}, connectionMode=${this.connectionMode}`);const s=await this.startInscription(e);if(!s.transactionBytes)throw this.logger.error("No transaction bytes returned from inscription request",s),new Error("No transaction bytes returned from inscription request");this.logger.info("executing transaction");const c=await this.executeTransaction(s.transactionBytes,t),p={jobId:s.tx_id,transactionId:c};if(o){i&&i({stage:"confirming",message:"Transaction executed, waiting for inscription to complete",progressPercent:5});const e=Math.floor(r/a),t=await this.waitForInscription(c,e,a,!0,i);return{...p,topicId:t.topic_id,status:t.status,completed:t.completed}}return p}async fetchWebSocketServers(){try{const e=await this.client.get("/inscriptions/websocket-servers"),{servers:t,recommended:i}=e.data;if(i)this.wsBaseUrl=i;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=$Y(this.wsBaseUrl,{auth:{apiKey:this.config.apiKey},transports:["websocket"],timeout:3e3});return new Promise(t=>{const i=setTimeout(()=>{e.disconnect(),t(!1)},3e3);e.on("connect",()=>{clearTimeout(i),e.disconnect(),t(!0)}),e.on("connect_error",()=>{clearTimeout(i),e.disconnect(),t(!1)})})}catch(mxe){return!1}}async inscribeViaWebSocket(e,t,i){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((n,o)=>{if(!this.socket)return o(new Error("WebSocket not connected"));let r,a,s,c;const p=()=>{var e,t,i;c&&clearTimeout(c),null==(e=this.socket)||e.off("inscription-progress",d),null==(t=this.socket)||t.off("inscription-complete",l),null==(i=this.socket)||i.off("inscription-error",u)};c=setTimeout(()=>{this.logger.error("WebSocket inscription timeout after 60 seconds",{jobId:r,transactionId:a,lastTopicId:s}),p(),n({jobId:r,transactionId:a,topicId:s,topic_id:s,status:"timeout",completed:!1})},6e4);const l=e=>{p(),n({jobId:r,transactionId:a,topicId:e.topicId||e.topic_id,topic_id:e.topicId||e.topic_id,status:"completed",completed:!0})},u=e=>{p(),o(new Error(e.error||"Inscription failed"))},d=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)&&(s=e.topicId||e.topic_id),i&&i({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||s,topic_id:e.topicId||e.topic_id||s}),p(),n({jobId:r,transactionId:a,topicId:e.topicId||e.topic_id||s,topic_id:e.topicId||e.topic_id||s,status:"completed",completed:!0}))};this.socket.on("inscription-progress",d),this.socket.on("inscription-complete",l),this.socket.on("inscription-error",u),this.socket.emit("start-inscription",{...e,network:this.config.network},async e=>{if(!e.success)return p(),o(new Error(e.error||"Inscription failed"));try{if(!e.transactionBytes)throw new Error("No transaction bytes returned from WebSocket inscription");if(a=await this.executeTransaction(e.transactionBytes,t),r=e.jobId||e.tx_id,!r)throw new Error("No job ID returned from WebSocket inscription");i&&i({stage:"confirming",message:"Transaction executed, inscribing to HCS...",progressPercent:5}),this.logger.info("Transaction executed, waiting for inscription completion...",{jobId:r,transactionId:a})}catch(n){p(),o(n)}})})}async connectWebSocket(){if(!this.socketConnected||!this.socket){if(!this.wsBaseUrl)throw new Error("WebSocket URL not configured");return new Promise((e,t)=>{this.socket=$Y(this.wsBaseUrl,{auth:{apiKey:this.config.apiKey},transports:["websocket","polling"]});const i=setTimeout(()=>{t(new Error("WebSocket connection timeout"))},1e4);this.socket.on("connect",()=>{clearTimeout(i),this.socketConnected=!0,this.logger.info("WebSocket connected"),e()}),this.socket.on("connect_error",e=>{clearTimeout(i),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 i=await this.startInscription(e);if(!i.transactionBytes)throw this.logger.error("No transaction bytes returned from inscription request",i),new Error("No transaction bytes returned from inscription request");this.logger.info("executing transaction");const n=await this.executeTransactionWithSigner(i.transactionBytes,t);return{jobId:i.tx_id,transactionId:n}}async retryWithBackoff(e,t=3,i=1e3){for(let o=0;o<t;o++)try{return await e()}catch(n){if(o===t-1)throw n;const e=i*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 Mi("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 mJ(e).authenticate()}static async createWithAuth(t){const i="client"===t.type?new hJ({...t,logger:Fi.getInstance()}):new mJ(t),{apiKey:n}=await i.authenticate();return new e({apiKey:n,network:t.network||"mainnet",wsBaseUrl:t.wsBaseUrl,connectionMode:t.connectionMode||"websocket"})}async waitForInscription(e,t=30,i=4e3,n=!1,o){var r;let a=0,s=0;const c=(i,n,r,c)=>{if(o)try{s=Math.max(s,r),o({stage:i,message:n,progressPercent:s,details:{...c,txId:e,currentAttempt:a,maxAttempts:t}})}catch(fxe){this.logger.warn(`Error in progress callback: ${fxe}`)}};for(c("confirming","Starting inscription verification",0);a<t;){c("confirming",`Verifying inscription status (attempt ${a+1}/${t})`,5,{attempt:a+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 s=5;void 0!==o.messages&&void 0!==o.maxMessages&&o.maxMessages>0?(s=Math.min(95,5+o.messages/o.maxMessages*90),o.completed&&(s=100)):"processing"===o.status?s=10:o.completed&&(s=100),c(o.completed?"completed":"confirming",o.completed?"Inscription completed successfully":`Processing inscription (${o.status})`,s,{status:o.status,messagesProcessed:o.messages,maxMessages:o.maxMessages,messageCount:o.messages,completed:o.completed,confirmedMessages:o.confirmedMessages,result:o});const p="hashinal"===o.mode,l="6"===(null==(r=o.fileStandard)?void 0:r.toString());if(p&&o.topic_id&&o.jsonTopicId&&(!n||o.completed))return c("completed","Inscription verification complete",100,{result:o}),o;if(!p&&!l&&o.topic_id&&(!n||o.completed))return c("completed","Inscription verification complete",100,{result:o}),o;if(l&&o.topic_id&&o.jsonTopicId&&o.registryTopicId&&(!n||o.completed))return c("completed","Inscription verification complete",100,{result:o}),o;await new Promise(e=>setTimeout(e,i)),a++}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,i;if(!e.holderId)throw new Mi("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(n){if(this.logger.error("Failed to fetch holder inscriptions:",n),wi.isAxiosError(n))throw new Error((null==(i=null==(t=n.response)?void 0:t.data)?void 0:i.message)||"Failed to fetch holder inscriptions");throw n}}};F(qY,"VALID_MODES",["file","upload","hashinal","hashinal-collection"]),F(qY,"MAX_BASE64_SIZE",2097152),F(qY,"MAX_URL_FILE_SIZE",104857600),F(qY,"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 KY=qY;class WY{constructor(e={}){this.module=e.module||"Progress",this.callback=e.callback,this.logger=e.logger||new y({level:"info",module:"ProgressReporter"}),this.logProgress=e.logProgress??!0,this.minPercent=e.minPercent??0,this.maxPercent=e.maxPercent??100,this.lastReportedPercent=-1,this.lastReportedTime=0,this.throttleMs=100}static getInstance(e={}){return WY.instance?(e.callback&&WY.instance.setCallback(e.callback),e.module&&WY.instance.setModule(e.module),e.logger&&WY.instance.setLogger(e.logger),void 0!==e.minPercent&&WY.instance.setMinPercent(e.minPercent),void 0!==e.maxPercent&&WY.instance.setMaxPercent(e.maxPercent)):WY.instance=new WY(e),WY.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 WY({module:this.module,logger:this.logger,logProgress:this.logProgress,minPercent:e.minPercent,maxPercent:e.maxPercent}),i=e.logPrefix||"";return t.setCallback(t=>{const n=this.scalePercent(t.progressPercent,e.minPercent,e.maxPercent);let o=t.message;i&&!o.startsWith(i)&&(o=`${i}: ${o}`),this.report({stage:t.stage,message:o,progressPercent:n,details:t.details})}),t}report(e){const t=e.progressPercent,i=Math.max(0,Math.min(100,t)),n=this.scalePercent(i,0,100),o=Date.now();if(n===this.lastReportedPercent&&o-this.lastReportedTime<this.throttleMs&&"completed"!==e.stage&&"failed"!==e.stage)return;this.lastReportedPercent=n,this.lastReportedTime=o;const r={...e,progressPercent:n};if(this.logProgress&&this.logger.debug(`[${this.module}] [${e.stage.toUpperCase()}] ${e.message} (${n.toFixed(1)}%)`,e.details),this.callback)try{this.callback(r)}catch(fxe){this.logger.warn(`Error in progress callback: ${fxe}`)}}scalePercent(e,t,i){const n=(this.maxPercent-this.minPercent)/(i-t);return this.minPercent+(e-t)*n}preparing(e,t,i){this.report({stage:"preparing",message:e,progressPercent:t,details:i})}submitting(e,t,i){this.report({stage:"submitting",message:e,progressPercent:t,details:i})}confirming(e,t,i){this.report({stage:"confirming",message:e,progressPercent:t,details:i})}verifying(e,t,i){this.report({stage:"verifying",message:e,progressPercent:t,details:i})}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 HY extends Error{constructor(e,t="PARSING_FAILED",i,n){super(e),this.name="TransactionParsingError",this.code=t,this.originalError=i,this.transactionBytes=n,Error.captureStackTrace&&Error.captureStackTrace(this,HY)}}const VY=(e,t)=>e.replace(/\{([^}]+)\}/g,(e,i)=>{const n=((e,t)=>{const i=t.split(".");let n=e;for(const o of i){if(null==n)return;n=n[o]}return n})(t,String(i).trim());return null==n?"(Unknown)":String(n)}),GY=e=>{const t=[],i=[];if(Array.isArray(e.transfers))for(const n of e.transfers){const e=parseFloat(n.amount);let o=n.amount;o.startsWith("-")&&(o=o.substring(1)),o=o.replace(/\s*ℏ$/,""),e<0?t.push(`${n.accountId} (${o} ℏ)`):e>0&&i.push(`${n.accountId} (${o} ℏ)`)}return t.length>0&&i.length>0?`Transfer of HBAR from ${t.join(", ")} to ${i.join(", ")}`:e.humanReadableType},ZY=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},JY=e=>e.tokenMint?`Mint ${e.tokenMint.amount} tokens for token ${e.tokenMint.tokenId}`:e.humanReadableType,YY=e=>e.tokenBurn?`Burn ${e.tokenBurn.amount} tokens for token ${e.tokenBurn.tokenId}`:e.humanReadableType,XY=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},QY=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},eX=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},tX=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},iX=e=>e.fileAppend?`Append to File ${e.fileAppend.fileId||"(Unknown ID)"}`:e.humanReadableType,nX=e=>e.fileUpdate?`Update File ${e.fileUpdate.fileId||"(Unknown ID)"}`:e.humanReadableType,oX=e=>e.fileDelete?`Delete File ${e.fileDelete.fileId||"(Unknown ID)"}`:e.humanReadableType,rX=e=>e.consensusUpdateTopic?`Update Topic ${e.consensusUpdateTopic.topicId||"(Unknown ID)"}`:e.humanReadableType,aX=e=>e.consensusDeleteTopic?`Delete Topic ${e.consensusDeleteTopic.topicId||"(Unknown ID)"}`:e.humanReadableType,sX=e=>e.tokenFreeze?`Freeze Token ${e.tokenFreeze.tokenId} for Account ${e.tokenFreeze.accountId}`:e.humanReadableType,cX=e=>e.tokenUnfreeze?`Unfreeze Token ${e.tokenUnfreeze.tokenId} for Account ${e.tokenUnfreeze.accountId}`:e.humanReadableType,pX=e=>e.tokenGrantKyc?`Grant KYC for Token ${e.tokenGrantKyc.tokenId} to Account ${e.tokenGrantKyc.accountId}`:e.humanReadableType,lX=e=>e.tokenRevokeKyc?`Revoke KYC for Token ${e.tokenRevokeKyc.tokenId} from Account ${e.tokenRevokeKyc.accountId}`:e.humanReadableType,uX=e=>e.tokenPause?`Pause Token ${e.tokenPause.tokenId}`:e.humanReadableType,dX=e=>e.tokenUnpause?`Unpause Token ${e.tokenUnpause.tokenId}`:e.humanReadableType,fX=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},mX=e=>e.tokenDelete?`Delete Token ${e.tokenDelete.tokenId}`:e.humanReadableType,hX=e=>e.tokenAssociate?`Associate Account ${e.tokenAssociate.accountId} with Tokens: ${(e.tokenAssociate.tokenIds||[]).join(", ")}`:e.humanReadableType,gX=e=>e.tokenDissociate?`Dissociate Account ${e.tokenDissociate.accountId} from Tokens: ${(e.tokenDissociate.tokenIds||[]).join(", ")}`:e.humanReadableType,yX=e=>e.cryptoDelete?`Delete Account ${e.cryptoDelete.deleteAccountId}`:e.humanReadableType,vX=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},bX=e=>e.cryptoUpdateAccount?`Update Account ${e.cryptoUpdateAccount.accountIdToUpdate||"(Unknown ID)"}`:e.humanReadableType,xX=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},wX=e=>{if(e.cryptoDeleteAllowance){return`Delete ${(e.cryptoDeleteAllowance.nftAllowancesToRemove||[]).length} NFT Crypto Allowance(s)`}return e.humanReadableType},kX=e=>{if(e.contractCreate){let t="Create Contract";return e.contractCreate.memo&&(t+=` (Memo: ${e.contractCreate.memo})`),t}return e.humanReadableType},_X=e=>e.contractUpdate?`Update Contract ${e.contractUpdate.contractIdToUpdate||"(Unknown ID)"}`:e.humanReadableType,EX=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},SX=e=>e.tokenUpdate?`Update Token ${e.tokenUpdate.tokenId||"(Unknown ID)"}`:e.humanReadableType,TX=e=>e.tokenFeeScheduleUpdate?`Update Fee Schedule for Token ${e.tokenFeeScheduleUpdate.tokenId||"(Unknown ID)"}`:e.humanReadableType,AX=e=>{if(!e.tokenAirdrop||!e.tokenAirdrop.tokenTransfers)return e.humanReadableType;let t=0,i=0;for(const n of e.tokenAirdrop.tokenTransfers)t+=1,i+=Array.isArray(n.transfers)?n.transfers.length:0;return`Token Airdrop across ${t} token(s), ${i} transfer(s)`},IX=e=>{if(!e.scheduleCreate)return e.humanReadableType;let t="Create Schedule";return e.scheduleCreate.memo&&(t+=` (Memo: ${e.scheduleCreate.memo})`),t},RX=e=>e.scheduleSign?"Sign Schedule":e.humanReadableType,OX=e=>e.scheduleDelete?"Delete Schedule":e.humanReadableType,jX=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,CX=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,NX=e=>"Network Freeze",BX=e=>"Ethereum Transaction",PX=e=>e.uncheckedSubmit&&e.uncheckedSubmit.topicId?`Unchecked Submit to topic ${e.uncheckedSubmit.topicId}`:"Unchecked Submit",LX=e=>"Create Node",UX=e=>"Update Node",FX=e=>"Delete Node",MX=e=>`Atomic Batch (${Array.isArray(e.atomicBatch?.transactions)?e.atomicBatch.transactions.length:0} transaction(s))`,DX={CRYPTOTRANSFER:{fn:GY},cryptoTransfer:{fn:GY},CONTRACTCALL:{fn:ZY},contractCall:{fn:ZY},TOKENMINT:{fn:JY},tokenMint:{fn:JY},TOKENBURN:{fn:YY},tokenBurn:{fn:YY},TOKENCREATE:{fn:XY},tokenCreation:{fn:XY},TOPICCREATE:{fn:QY},consensusCreateTopic:{fn:QY},CONSENSUSSUBMITMESSAGE:{fn:eX},consensusSubmitMessage:{fn:eX},TOPICUPDATE:{fn:rX},consensusUpdateTopic:{fn:rX},TOPICDELETE:{fn:aX},consensusDeleteTopic:{fn:aX},FILECREATE:{fn:tX},fileCreate:{fn:tX},FILEAPPEND:{fn:iX},fileAppend:{fn:iX},FILEUPDATE:{fn:nX},fileUpdate:{fn:nX},FILEDELETE:{fn:oX},fileDelete:{fn:oX},TOKENUPDATE:{fn:SX},tokenUpdate:{fn:SX},TOKENFEESCHEDULEUPDATE:{fn:TX},tokenFeeScheduleUpdate:{fn:TX},TOKENFREEZE:{fn:sX},tokenFreeze:{fn:sX},TOKENUNFREEZE:{fn:cX},tokenUnfreeze:{fn:cX},TOKENGRANTKYC:{fn:pX},tokenGrantKyc:{fn:pX},TOKENREVOKEKYC:{fn:lX},tokenRevokeKyc:{fn:lX},TOKENPAUSE:{fn:uX},tokenPause:{fn:uX},TOKENUNPAUSE:{fn:dX},tokenUnpause:{fn:dX},TOKENWIPE:{fn:fX},TOKENWIPEACCOUNT:{fn:fX},tokenWipe:{fn:fX},tokenWipeAccount:{fn:fX},TOKENDELETE:{fn:mX},tokenDelete:{fn:mX},TOKENASSOCIATE:{fn:hX},tokenAssociate:{fn:hX},TOKENDISSOCIATE:{fn:gX},tokenDissociate:{fn:gX},ACCOUNTDELETE:{fn:yX},cryptoDelete:{fn:yX},ACCOUNTCREATE:{fn:vX},cryptoCreateAccount:{fn:vX},ACCOUNTUPDATE:{fn:bX},cryptoUpdateAccount:{fn:bX},APPROVEALLOWANCE:{fn:xX},cryptoApproveAllowance:{fn:xX},DELETEALLOWANCE:{fn:wX},cryptoDeleteAllowance:{fn:wX},CONTRACTCREATE:{fn:kX},contractCreate:{fn:kX},CONTRACTUPDATE:{fn:_X},contractUpdate:{fn:_X},CONTRACTDELETE:{fn:EX},contractDelete:{fn:EX},TOKENAIRDROP:{fn:AX},tokenAirdrop:{fn:AX},SCHEDULECREATE:{fn:IX},scheduleCreate:{fn:IX},SCHEDULESIGN:{fn:RX},scheduleSign:{fn:RX},SCHEDULEDELETE:{fn:OX},scheduleDelete:{fn:OX},SYSTEMDELETE:{fn:jX},systemDelete:{fn:jX},SYSTEMUNDELETE:{fn:CX},systemUndelete:{fn:CX},FREEZE:{fn:NX},freeze:{fn:NX},ETHEREUMTRANSACTION:{fn:BX},ethereumTransaction:{fn:BX},UNCHECKEDSUBMIT:{fn:PX},uncheckedSubmit:{fn:PX},NODECREATE:{fn:LX},nodeCreate:{fn:LX},NODEUPDATE:{fn:UX},nodeUpdate:{fn:UX},NODEDELETE:{fn:FX},nodeDelete:{fn:FX},ATOMICBATCH:{fn:MX},atomicBatch:{fn:MX}},zX=e=>{const t=DX[e.type];if(t){if(t.fn)return t.fn(e);if(t.template)return VY(t.template,e)}const i=DX[e.humanReadableType];if(i){if(i.fn)return i.fn(e);if(i.template)return VY(i.template,e)}return"cryptoTransfer"===e.type||"CRYPTOTRANSFER"===e.type?GY(e):e.contractCall?ZY(e):Array.isArray(e.tokenTransfers)&&e.tokenTransfers.length>0?(e=>{const t=[],i=(e=>{const t={};for(const i of e)t[i.tokenId]||(t[i.tokenId]=[]),t[i.tokenId].push(i);return t})(e.tokenTransfers||[]);for(const[n,o]of Object.entries(i)){const e=[],i=[];for(const t of o){const n=parseFloat(String(t.amount));n<0?e.push(`${t.accountId} (${Math.abs(n)})`):n>0&&i.push(`${t.accountId} (${n})`)}e.length>0&&i.length>0&&t.push(`Transfer of token ${n} from ${e.join(", ")} to ${i.join(", ")}`)}return t.length>0?t.join("; "):e.humanReadableType})(e):e.humanReadableType&&"Unknown Transaction"!==e.humanReadableType?e.humanReadableType:"Unknown Transaction"};function $X(e){if(e){if(e.contractID)return`ContractID: ${new o.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()}`;if(e.ed25519)return`ED25519: ${s.Buffer.from(e.ed25519).toString("hex")}`;if(e.ECDSASecp256k1)return`ECDSA_secp256k1: ${s.Buffer.from(e.ECDSASecp256k1).toString("hex")}`;if(e?.keyList?.keys?.length>0){const t=e.keyList.keys.map(e=>$X(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=>$X(e)).filter(Boolean);return`ThresholdKey (${e.thresholdKey.threshold} of ${t.length}): [${t.join(", ")}]`}return e.delegatableContractId?`DelegatableContractID: ${new o.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 qX(e){try{const t=e.toBytes?e.toBytes():void 0;if(!t)return null;const i=a.proto.TransactionList.decode(t);if(!i.transactionList||0===i.transactionList.length)return null;const n=i.transactionList[0];if(n.bodyBytes&&n.bodyBytes.length>0)return a.proto.TransactionBody.decode(n.bodyBytes);if(n.signedTransactionBytes&&n.signedTransactionBytes.length>0){const e=a.proto.SignedTransaction.decode(n.signedTransactionBytes);if(e.bodyBytes)return a.proto.TransactionBody.decode(e.bodyBytes)}return null}catch(t){return null}}function KX(e,t){const i=qX(e);return!(!i||!i[t])}class WX{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 i=this.parseTokenAirdrop(e);return i?{type:"TOKENAIRDROP",humanReadableType:"Token Airdrop",tokenAirdrop:i}:{}}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 o.AccountId(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),e.initialSupply&&(t.initialSupply=o.Long.fromValue(e.initialSupply).toString()),void 0!==e.decimals&&null!==e.decimals&&(t.decimals=o.Long.fromValue(e.decimals).toNumber()),e.maxSupply&&(t.maxSupply=o.Long.fromValue(e.maxSupply).toString()),e.memo&&(t.memo=e.memo),null!==e.tokenType&&void 0!==e.tokenType&&(t.tokenType=a.proto.TokenType[e.tokenType]),null!==e.supplyType&&void 0!==e.supplyType&&(t.supplyType=a.proto.TokenSupplyType[e.supplyType]),t.adminKey=$X(e.adminKey),t.kycKey=$X(e.kycKey),t.freezeKey=$X(e.freezeKey),t.wipeKey=$X(e.wipeKey),t.supplyKey=$X(e.supplyKey),t.feeScheduleKey=$X(e.feeScheduleKey),t.pauseKey=$X(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccount=new o.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=o.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.customFees&&e.customFees.length>0&&(t.customFees=e.customFees.map(e=>{const t={feeCollectorAccountId:e.feeCollectorAccountId?new o.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:o.Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new o.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:o.Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:o.Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:o.Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:o.Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let i;return e.royaltyFee.fallbackFee&&(i={amount:o.Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new o.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:o.Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:o.Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:i}}}return{...t,feeType:"FIXED_FEE",fixedFee:{amount:"0"}}})),t}static parseTokenMint(e){if(!e||!e.token||null===e.amount||void 0===e.amount)return;const t={tokenId:new o.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:o.Long.fromValue(e.amount).toNumber()};return e.metadata&&e.metadata.length>0&&(t.metadata=e.metadata.map(e=>s.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 o.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString(),amount:o.Long.fromValue(e.amount).toNumber()};return e.serialNumbers&&e.serialNumbers.length>0&&(t.serialNumbers=e.serialNumbers.map(e=>o.Long.fromValue(e).toNumber())),t}static parseTokenUpdate(e){if(!e)return;const t={};return e.token&&(t.tokenId=new o.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 o.AccountId(e.treasury.shardNum??0,e.treasury.realmNum??0,e.treasury.accountNum??0).toString()),t.adminKey=$X(e.adminKey),t.kycKey=$X(e.kycKey),t.freezeKey=$X(e.freezeKey),t.wipeKey=$X(e.wipeKey),t.supplyKey=$X(e.supplyKey),t.feeScheduleKey=$X(e.feeScheduleKey),t.pauseKey=$X(e.pauseKey),e.autoRenewAccount&&(t.autoRenewAccountId=new o.AccountId(e.autoRenewAccount.shardNum??0,e.autoRenewAccount.realmNum??0,e.autoRenewAccount.accountNum??0).toString()),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=o.Long.fromValue(e.autoRenewPeriod.seconds).toString()),void 0!==e.memo?.value&&(t.memo=e.memo.value),e.expiry?.seconds&&(t.expiry=`${o.Long.fromValue(e.expiry.seconds).toString()}.${e.expiry.nanos}`),t}static parseTokenFeeScheduleUpdate(e){if(!e)return;const t={};return e.tokenId&&(t.tokenId=new o.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 o.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:o.Long.fromValue(e.fixedFee.amount||0).toString(),denominatingTokenId:e.fixedFee.denominatingTokenId?new o.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:o.Long.fromValue(e.fractionalFee.fractionalAmount?.numerator||0).toString(),denominator:o.Long.fromValue(e.fractionalFee.fractionalAmount?.denominator||1).toString(),minimumAmount:o.Long.fromValue(e.fractionalFee.minimumAmount||0).toString(),maximumAmount:o.Long.fromValue(e.fractionalFee.maximumAmount||0).toString(),netOfTransfers:e.fractionalFee.netOfTransfers||!1}};if(e.royaltyFee){let i;return e.royaltyFee.fallbackFee&&(i={amount:o.Long.fromValue(e.royaltyFee.fallbackFee.amount||0).toString(),denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?new o.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:o.Long.fromValue(e.royaltyFee.exchangeValueFraction?.numerator||0).toString(),denominator:o.Long.fromValue(e.royaltyFee.exchangeValueFraction?.denominator||1).toString(),fallbackFee:i}}}return{...t,feeType:"FIXED_FEE",fixedFee:{amount:"0"}}})),t}static parseTokenFreeze(e){if(!e)return;const t={};return e.token&&(t.tokenId=new o.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new o.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 o.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new o.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 o.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new o.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 o.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new o.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 o.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 o.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 o.TokenId(e.token.shardNum??0,e.token.realmNum??0,e.token.tokenNum??0).toString()),e.account&&(t.accountId=new o.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=>o.Long.fromValue(e).toString())),e.amount&&(t.amount=o.Long.fromValue(e.amount).toString()),t}static parseTokenDelete(e){if(!e)return;const t={};return e.token&&(t.tokenId=new o.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 o.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 o.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 o.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 o.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(KX(e,"tokenAirdrop")){const t=qX(e);if(t?.tokenAirdrop)return this.parseTokenAirdropFromProto(t.tokenAirdrop)}const i=e._tokenTransfers||[];return i.length>0?{tokenTransfers:i.map(e=>({tokenId:e.tokenId?.toString()||"Unknown",transfers:(e.transfers||[]).map(e=>({accountId:e.accountId?.toString()||"Unknown",amount:e.amount?.toString()||"0",serialNumbers:e.serialNumbers?.map(e=>e.toString())}))}))}:null}catch(t){return console.warn("[HTSParser] Failed to parse token airdrop:",t),null}}static parseTokenAirdropFromProto(e){const t=[];if(e.tokenTransfers)for(const i of e.tokenTransfers){const e=i.token?new o.TokenId(i.token.shardNum??0,i.token.realmNum??0,i.token.tokenNum??0):null,n=[];if(i.transfers)for(const t of i.transfers){const e=t.accountID?new o.AccountId(t.accountID.shardNum??0,t.accountID.realmNum??0,t.accountID.accountNum??0):null;n.push({accountId:e?.toString()||"Unknown",amount:t.amount?o.Long.fromValue(t.amount).toString():"0",serialNumbers:t.serialNumbers?.map(e=>o.Long.fromValue(e).toString())})}t.push({tokenId:e?.toString()||"Unknown",transfers:n})}return{tokenTransfers:t}}static extractTokenCreationFromTransaction(e){try{const t=e;if(t._tokenName||t._tokenSymbol){const e={tokenName:t._tokenName||"Unknown Token",tokenSymbol:t._tokenSymbol||"UNKNOWN",initialSupply:t._initialSupply?.toString()||"0",decimals:Number(t._decimals||0),treasuryAccountId:t._treasuryAccountId?.toString()||"Unknown"};return t._maxSupply&&(e.maxSupply=t._maxSupply.toString()),t._tokenType&&(e.tokenType=t._tokenType.toString?t._tokenType.toString():String(t._tokenType)),t._supplyType&&(e.supplyType=t._supplyType.toString?t._supplyType.toString():String(t._supplyType)),t._tokenMemo&&(e.memo=t._tokenMemo),t._adminKey&&(e.adminKey=t._adminKey.toString()),t._kycKey&&(e.kycKey=t._kycKey.toString()),t._freezeKey&&(e.freezeKey=t._freezeKey.toString()),t._wipeKey&&(e.wipeKey=t._wipeKey.toString()),t._supplyKey&&(e.supplyKey=t._supplyKey.toString()),t._feeScheduleKey&&(e.feeScheduleKey=t._feeScheduleKey.toString()),t._pauseKey&&(e.pauseKey=t._pauseKey.toString()),t._metadataKey&&(e.metadataKey=t._metadataKey.toString()),t._autoRenewAccountId&&(e.autoRenewAccount=t._autoRenewAccountId.toString()),t._autoRenewPeriod&&(e.autoRenewPeriod=t._autoRenewPeriod.seconds?.toString()||t._autoRenewPeriod.toString()),t._expirationTime&&(e.expiry=t._expirationTime.seconds?.toString()||t._expirationTime.toString()),t._customFees&&Array.isArray(t._customFees)&&t._customFees.length>0&&(e.customFees=t._customFees.map(e=>{const t={feeCollectorAccountId:e.feeCollectorAccountId?.toString()||"",feeType:"FIXED_FEE"};return e.fixedFee?(t.feeType="FIXED_FEE",t.fixedFee={amount:e.fixedFee.amount?.toString()||"0",denominatingTokenId:e.fixedFee.denominatingTokenId?.toString()}):e.fractionalFee?(t.feeType="FRACTIONAL_FEE",t.fractionalFee={numerator:e.fractionalFee.numerator?.toString()||"0",denominator:e.fractionalFee.denominator?.toString()||"1",minimumAmount:e.fractionalFee.minimumAmount?.toString()||"0",maximumAmount:e.fractionalFee.maximumAmount?.toString()||"0",netOfTransfers:e.fractionalFee.netOfTransfers||!1}):e.royaltyFee&&(t.feeType="ROYALTY_FEE",t.royaltyFee={numerator:e.royaltyFee.numerator?.toString()||"0",denominator:e.royaltyFee.denominator?.toString()||"1",fallbackFee:e.royaltyFee.fallbackFee?{amount:e.royaltyFee.fallbackFee.amount?.toString()||"0",denominatingTokenId:e.royaltyFee.fallbackFee.denominatingTokenId?.toString()}:void 0}),t.allCollectorsAreExempt=e.allCollectorsAreExempt||!1,t})),e}return null}catch(t){return null}}static extractTokenAirdropFromTransaction(e){try{const t=e;if(t._tokenAirdrops&&Array.isArray(t._tokenAirdrops)){return{tokenTransfers:t._tokenAirdrops.map(e=>({tokenId:e.tokenId?.toString()||"Unknown",transfers:(e.transfers||[]).map(e=>({accountId:e.accountId?.toString()||"Unknown",amount:e.amount?.toString()||"0",serialNumbers:e.serialNumbers?.map(e=>e.toString())||[]}))}))}}return null}catch(t){return null}}static parseFromTransactionObject(e){try{try{const t=e.toBytes?e.toBytes():void 0;if(t){const e=a.proto.TransactionList.decode(t);if(e.transactionList&&e.transactionList.length>0){const t=e.transactionList[0];let i=null;if(t.bodyBytes&&t.bodyBytes.length>0)i=a.proto.TransactionBody.decode(t.bodyBytes);else if(t.signedTransactionBytes&&t.signedTransactionBytes.length>0){const e=a.proto.SignedTransaction.decode(t.signedTransactionBytes);e.bodyBytes&&(i=a.proto.TransactionBody.decode(e.bodyBytes))}if(i){if(i.tokenCreation){const e=this.parseTokenCreate(i.tokenCreation);if(e)return{type:"TOKENCREATE",humanReadableType:"Token Creation",tokenCreation:e}}if(i.tokenMint){const e=this.parseTokenMint(i.tokenMint);if(e)return{type:"TOKENMINT",humanReadableType:"Token Mint",tokenMint:e}}if(i.tokenBurn){const e=this.parseTokenBurn(i.tokenBurn);if(e)return{type:"TOKENBURN",humanReadableType:"Token Burn",tokenBurn:e}}if(i.tokenUpdate){const e=this.parseTokenUpdate(i.tokenUpdate);if(e)return{type:"TOKENUPDATE",humanReadableType:"Token Update",tokenUpdate:e}}if(i.tokenFreeze){const e=this.parseTokenFreeze(i.tokenFreeze);if(e)return{type:"TOKENFREEZE",humanReadableType:"Token Freeze",tokenFreeze:e}}if(i.tokenUnfreeze){const e=this.parseTokenUnfreeze(i.tokenUnfreeze);if(e)return{type:"TOKENUNFREEZE",humanReadableType:"Token Unfreeze",tokenUnfreeze:e}}if(i.tokenGrantKyc){const e=this.parseTokenGrantKyc(i.tokenGrantKyc);if(e)return{type:"TOKENGRANTKYC",humanReadableType:"Token Grant KYC",tokenGrantKyc:e}}if(i.tokenRevokeKyc){const e=this.parseTokenRevokeKyc(i.tokenRevokeKyc);if(e)return{type:"TOKENREVOKEKYC",humanReadableType:"Token Revoke KYC",tokenRevokeKyc:e}}if(i.tokenPause){const e=this.parseTokenPause(i.tokenPause);if(e)return{type:"TOKENPAUSE",humanReadableType:"Token Pause",tokenPause:e}}if(i.tokenUnpause){const e=this.parseTokenUnpause(i.tokenUnpause);if(e)return{type:"TOKENUNPAUSE",humanReadableType:"Token Unpause",tokenUnpause:e}}if(i.tokenWipe){const e=this.parseTokenWipeAccount(i.tokenWipe);if(e)return{type:"TOKENWIPEACCOUNT",humanReadableType:"Token Wipe Account",tokenWipeAccount:e}}if(i.tokenDeletion){const e=this.parseTokenDelete(i.tokenDeletion);if(e)return{type:"TOKENDELETE",humanReadableType:"Token Delete",tokenDelete:e}}if(i.tokenAssociate){const e=this.parseTokenAssociate(i.tokenAssociate);if(e)return{type:"TOKENASSOCIATE",humanReadableType:"Token Associate",tokenAssociate:e}}if(i.tokenDissociate){const e=this.parseTokenDissociate(i.tokenDissociate);if(e)return{type:"TOKENDISSOCIATE",humanReadableType:"Token Dissociate",tokenDissociate:e}}if(i.tokenFeeScheduleUpdate){const e=this.parseTokenFeeScheduleUpdate(i.tokenFeeScheduleUpdate);if(e)return{type:"TOKENFEESCHEDULEUPDATE",humanReadableType:"Token Fee Schedule Update",tokenFeeScheduleUpdate:e}}if(i.tokenAirdrop){const e=this.parseTokenAirdropFromProto(i.tokenAirdrop);if(e)return{type:"TOKENAIRDROP",humanReadableType:"Token Airdrop",tokenAirdrop:e}}}}}}catch(mxe){}const t=this.parseHTSTransaction(e);if(t.type)return t;const i=this.extractTokenCreationFromTransaction(e),n=this.extractTokenAirdropFromTransaction(e);return i?{type:"TOKENCREATE",humanReadableType:"Token Creation",tokenCreation:i}:n?{type:"TOKENAIRDROP",humanReadableType:"Token Airdrop",tokenAirdrop:n}:{}}catch(t){return{}}}}class HX{static parseConsensusCreateTopic(e){if(!e)return;const t={};return e.memo&&(t.memo=e.memo),t.adminKey=$X(e.adminKey),t.submitKey=$X(e.submitKey),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=o.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new o.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 i=s.Buffer.from(e.message),n=i.toString("utf8");/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(n)||n.includes("�")?(t.message=i.toString("base64"),t.messageEncoding="base64"):(t.message=n,t.messageEncoding="utf8")}if(e.chunkInfo){if(e.chunkInfo.initialTransactionID){const i=e.chunkInfo.initialTransactionID.accountID,n=e.chunkInfo.initialTransactionID.transactionValidStart;i&&n&&(t.chunkInfoInitialTransactionID=`${i.shardNum??0}.${i.realmNum??0}.${i.accountNum??0}@${n.seconds??0}.${n.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=$X(e.adminKey):t.adminKey=void 0,null===e.submitKey?(t.clearSubmitKey=!0,t.submitKey=void 0):e.submitKey?t.submitKey=$X(e.submitKey):t.submitKey=void 0,e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=o.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.autoRenewAccount&&(t.autoRenewAccountId=new o.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 VX{static parseFileTransaction(e,t){try{if(t||e.toBytes)try{const i=t||e.toBytes(),n=a.proto.TransactionList.decode(i);if(n.transactionList&&n.transactionList.length>0){const e=n.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=a.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const i=a.proto.SignedTransaction.decode(e.signedTransactionBytes);i.bodyBytes&&(t=a.proto.TransactionBody.decode(i.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(i){}return this.parseFromTransactionInternals(e)}catch(n){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(KX(e,"fileCreate")){const e={};if(t._contents){const i=this.analyzeContent(t._contents);e.contents=i.encoded,i.contentType&&(e.contentType=i.contentType),i.size&&(e.contentSize=i.size)}if(t._keys&&t._keys.length>0){const i={keys:t._keys};e.keys=$X({keyList:i})}return t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),t._memo&&(e.memo=t._memo),{type:"FILECREATE",humanReadableType:"File Create",fileCreate:e}}if(KX(e,"fileAppend")){const e={fileId:t._fileId.toString()};if(t._contents){const i=this.analyzeContent(t._contents);e.contents=i.encoded,i.size&&(e.contentSize=i.size)}return{type:"FILEAPPEND",humanReadableType:"File Append",fileAppend:e}}if(KX(e,"fileUpdate")){const e={fileId:t._fileId.toString()};if(t._contents){const i=this.analyzeContent(t._contents);e.contents=i.encoded,i.size&&(e.contentSize=i.size)}if(t._keys&&t._keys.length>0){const i={keys:t._keys};e.keys=$X({keyList:i})}return t._expirationTime&&(e.expirationTime=t._expirationTime.toString()),t._memo&&(e.memo=t._memo),{type:"FILEUPDATE",humanReadableType:"File Update",fileUpdate:e}}if(KX(e,"fileDelete")){return{type:"FILEDELETE",humanReadableType:"File Delete",fileDelete:{fileId:t._fileId.toString()}}}return{}}catch(t){return{}}}static analyzeContent(e){const t=e.length,i=s.Buffer.from(e);let n,o;if(t>=4){n={"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"}[i.subarray(0,4).toString("hex").toLowerCase()]}if(!n)try{const e=i.toString("utf8"),t=/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(e),o=e.includes("�");n=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{n="application/octet-stream"}if(n?.startsWith("text/")||"application/json"===n)try{o=i.toString("utf8"),(o.includes("�")||/[\x00-\x08\x0B\x0E-\x1F\x7F]/.test(o))&&(o=i.toString("base64"))}catch{o=i.toString("base64")}else o=i.toString("base64");return{encoded:o,contentType:n,size:t}}static parseFileCreate(e){if(!e)return;const t={};return e.expirationTime?.seconds&&(t.expirationTime=`${o.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=$X({keyList:e.keys})),e.contents&&(t.contents=s.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=s.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=`${o.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.keys&&(t.keys=$X({keyList:e.keys})),e.contents&&(t.contents=s.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 GX{static parseCryptoTransfers(e,t){if(e.transfers?.accountAmounts&&(t.transfers=e.transfers.accountAmounts.map(e=>{const t=new o.AccountId(e.accountID.shardNum??0,e.accountID.realmNum??0,e.accountID.accountNum??0),i=o.Hbar.fromTinybars(o.Long.fromValue(e.amount));return{accountId:t.toString(),amount:i.toString(o.HbarUnit.Hbar),isDecimal:!0}})),e.tokenTransfers)for(const i of e.tokenTransfers){const e=new o.TokenId(i.token.shardNum??0,i.token.realmNum??0,i.token.tokenNum??0);if(i.transfers)for(const n of i.transfers){const i=new o.AccountId(n.accountID.shardNum??0,n.accountID.realmNum??0,n.accountID.accountNum??0),r=o.Long.fromValue(n.amount).toNumber();t.tokenTransfers.push({tokenId:e.toString(),accountId:i.toString(),amount:r})}}}static parseCryptoDelete(e){if(!e)return;const t={};return e.deleteAccountID&&(t.deleteAccountId=new o.AccountId(e.deleteAccountID.shardNum??0,e.deleteAccountID.realmNum??0,e.deleteAccountID.accountNum??0).toString()),e.transferAccountID&&(t.transferAccountId=new o.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=o.Hbar.fromTinybars(o.Long.fromValue(e.initialBalance)).toString(o.HbarUnit.Hbar)),e.key&&(t.key=$X(e.key)),void 0!==e.receiverSigRequired&&(t.receiverSigRequired=e.receiverSigRequired),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=o.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 o.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=o.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 o.AccountId(e.accountIDToUpdate.shardNum??0,e.accountIDToUpdate.realmNum??0,e.accountIDToUpdate.accountNum??0).toString()),e.key&&(t.key=$X(e.key)),e.expirationTime?.seconds&&(t.expirationTime=`${o.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=o.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 o.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=o.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 o.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new o.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount:o.Hbar.fromTinybars(o.Long.fromValue(e.amount)).toString(o.HbarUnit.Hbar)}))),e.tokenAllowances&&e.tokenAllowances.length>0&&(t.tokenAllowances=e.tokenAllowances.map(e=>({tokenId:new o.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),ownerAccountId:new o.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),spenderAccountId:new o.AccountId(e.spender.shardNum??0,e.spender.realmNum??0,e.spender.accountNum??0).toString(),amount:o.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 o.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString()),e.owner&&(t.ownerAccountId=new o.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString()),e.spender&&(t.spenderAccountId=new o.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=>o.Long.fromValue(e).toString())),void 0!==e.approvedForAll?.value&&(t.approvedForAll=e.approvedForAll.value),e.delegatingSpender&&(t.delegatingSpender=new o.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 o.AccountId(e.owner.shardNum??0,e.owner.realmNum??0,e.owner.accountNum??0).toString(),tokenId:new o.TokenId(e.tokenId.shardNum??0,e.tokenId.realmNum??0,e.tokenId.tokenNum??0).toString(),serialNumbers:e.serialNumbers?e.serialNumbers.map(e=>o.Long.fromValue(e).toString()):[]}))),t}static extractHbarTransfersFromTransaction(e){const t=[];try{const i=e._hbarTransfers;Array.isArray(i)&&i.forEach(e=>{if(e.accountId&&e.amount){const i=e.amount.toTinybars(),n=Number(i)/1e8;t.push({accountId:e.accountId.toString(),amount:n})}})}catch(i){}return t}static extractTokenTransfersFromTransaction(e){const t=[];try{const i=e._tokenTransfers;Array.isArray(i)&&i.forEach(e=>{if(e.tokenId&&Array.isArray(e.transfers)){const i=e.transfers.map(e=>({accountId:e.accountId?.toString()||"Unknown",amount:Number(e.amount||0)}));t.push({tokenId:e.tokenId.toString(),transfers:i})}})}catch(i){}return t}static parseFromTransactionObject(e){try{const t=this.extractHbarTransfersFromTransaction(e),i=this.extractTokenTransfersFromTransaction(e);if(t.length>0||i.length>0){const e=t.map(e=>({accountId:e.accountId,amount:e.amount.toString()+" ℏ",isDecimal:!0})),n=i.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:n};if(i.length>0)return{type:"TOKENTRANSFER",humanReadableType:"Token Transfer",transfers:e,tokenTransfers:n}}return{}}catch(t){return{}}}}class ZX{static parseSCSTransaction(e,t){try{if(t||e.toBytes)try{const i=t||e.toBytes(),n=a.proto.TransactionList.decode(i);if(n.transactionList&&n.transactionList.length>0){const e=n.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=a.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const i=a.proto.SignedTransaction.decode(e.signedTransactionBytes);i.bodyBytes&&(t=a.proto.TransactionBody.decode(i.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(i){}return this.parseFromTransactionInternals(e)}catch(n){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:o.Long.fromValue(t._gas).toNumber(),amount:t._amount?parseFloat(t._amount.toString()):0};if(t._functionParameters){const i=s.Buffer.from(t._functionParameters).toString("hex");e.functionParameters=i,e.functionName=this.extractFunctionName(i)}return{type:"CONTRACTCALL",humanReadableType:"Contract Call",contractCall:e}}if(KX(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=s.Buffer.from(t._bytecode).toString("hex")),t._constructorParameters&&(e.constructorParameters=s.Buffer.from(t._constructorParameters).toString("hex")),t._memo&&(e.memo=t._memo),t._adminKey&&(e.adminKey=$X(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=o.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(KX(e,"contractUpdateInstance")){const e={contractIdToUpdate:t._contractId.toString()};return t._memo&&(e.memo=t._memo),t._adminKey&&(e.adminKey=$X(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=o.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(KX(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?o.Long.fromValue(e.maxGasAllowance).toNumber():0,amount:0};if(e.ethereumData&&e.ethereumData.length>0){const i=s.Buffer.from(e.ethereumData).toString("hex");t.functionParameters=i,i.length>=8&&(t.functionName=this.extractFunctionName(i))}return t}static parseContractCall(e){if(!e)return;const t=o.Hbar.fromTinybars(o.Long.fromValue(e.amount??0)),i={contractId:new o.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString(),gas:o.Long.fromValue(e.gas??0).toNumber(),amount:parseFloat(t.toString(o.HbarUnit.Hbar))};return e.functionParameters&&(i.functionParameters=s.Buffer.from(e.functionParameters).toString("hex"),i.functionParameters.length>=8&&(i.functionName=this.extractFunctionName(i.functionParameters))),i}static parseContractCreate(e){if(!e)return;const t={};return e.initialBalance&&(t.initialBalance=o.Hbar.fromTinybars(o.Long.fromValue(e.initialBalance)).toString(o.HbarUnit.Hbar)),e.gas&&(t.gas=o.Long.fromValue(e.gas).toString()),e.adminKey&&(t.adminKey=$X(e.adminKey)),e.constructorParameters&&(t.constructorParameters=s.Buffer.from(e.constructorParameters).toString("hex")),e.memo&&(t.memo=e.memo),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=o.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.stakedAccountId?t.stakedAccountId=new o.AccountId(e.stakedAccountId.shardNum??0,e.stakedAccountId.realmNum??0,e.stakedAccountId.accountNum??0).toString():null!==e.stakedNodeId&&void 0!==e.stakedNodeId&&(t.stakedNodeId=o.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 o.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=s.Buffer.from(e.initcode).toString("hex")),t}static parseContractUpdate(e){if(!e)return;const t={};if(e.contractID&&(t.contractIdToUpdate=new o.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.adminKey&&(t.adminKey=$X(e.adminKey)),e.expirationTime?.seconds&&(t.expirationTime=`${o.Long.fromValue(e.expirationTime.seconds).toString()}.${e.expirationTime.nanos}`),e.autoRenewPeriod?.seconds&&(t.autoRenewPeriod=o.Long.fromValue(e.autoRenewPeriod.seconds).toString()),e.memo){const i=e.memo;if(i&&"object"==typeof i&&Object.prototype.hasOwnProperty.call(i,"value")){const e=i.value;t.memo=null==e?void 0:String(e)}else t.memo="string"==typeof i?i:void 0}else t.memo=void 0;return e.stakedAccountId?(t.stakedAccountId=new o.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&&o.Long.fromValue(e.stakedNodeId).notEquals(-1)?(t.stakedNodeId=o.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 o.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 o.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.transferAccountID?t.transferAccountId=new o.AccountId(e.transferAccountID.shardNum??0,e.transferAccountID.realmNum??0,e.transferAccountID.accountNum??0).toString():e.transferContractID&&(t.transferContractId=new o.ContractId(e.transferContractID.shardNum??0,e.transferContractID.realmNum??0,e.transferContractID.contractNum??0).toString()),t}static parseFromTransactionObject(e){return this.parseSCSTransaction(e)}}class JX{static parseUtilTransaction(e,t){try{if(t||e.toBytes)try{const i=t||e.toBytes(),n=a.proto.TransactionList.decode(i);if(n.transactionList&&n.transactionList.length>0){const e=n.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=a.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const i=a.proto.SignedTransaction.decode(e.signedTransactionBytes);i.bodyBytes&&(t=a.proto.TransactionBody.decode(i.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(i){}return this.parseFromTransactionInternals(e)}catch(n){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(KX(e,"utilPrng")){const e={};return t._range&&0!==t._range&&(e.range=t._range),{type:"PRNG",humanReadableType:"Pseudo Random Number",utilPrng:e}}if(KX(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(KX(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(KX(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=`${o.Long.fromValue(e.startTime.seconds).toString()}.${e.startTime.nanos??0}`),e.updateFile&&(t.updateFile=new o.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 i=["FREEZE_ONLY","PREPARE_UPGRADE","FREEZE_UPGRADE","FREEZE_ABORT"];t.freezeType=i[e.freezeType]||"FREEZE_ONLY"}return t}static parseSystemDeleteFromProto(e){if(!e)return;const t={};return e.fileID?t.fileId=new o.FileId(e.fileID.shardNum??0,e.fileID.realmNum??0,e.fileID.fileNum??0).toString():e.contractID&&(t.contractId=new o.ContractId(e.contractID.shardNum??0,e.contractID.realmNum??0,e.contractID.contractNum??0).toString()),e.expirationTime?.seconds&&(t.expirationTime=o.Long.fromValue(e.expirationTime.seconds).toString()),t}static parseSystemUndeleteFromProto(e){if(!e)return;const t={};return e.fileID?t.fileId=new o.FileId(e.fileID.shardNum??0,e.fileID.realmNum??0,e.fileID.fileNum??0).toString():e.contractID&&(t.contractId=new o.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=o.Long.fromValue(e.nodeId).toNumber()),t}static parseNodeUpdateFromProto(e){if(!e)return;const t={};return void 0!==e.nodeId&&(t.nodeId=o.Long.fromValue(e.nodeId).toNumber()),t}static parseNodeDeleteFromProto(e){if(!e)return;const t={};return void 0!==e.nodeId&&(t.nodeId=o.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 YX{static parseScheduleTransaction(e,t){try{if(t||e.toBytes)try{const i=t||e.toBytes(),n=a.proto.TransactionList.decode(i);if(n.transactionList&&n.transactionList.length>0){const e=n.transactionList[0];let t=null;if(e.bodyBytes&&e.bodyBytes.length>0)t=a.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const i=a.proto.SignedTransaction.decode(e.signedTransactionBytes);i.bodyBytes&&(t=a.proto.TransactionBody.decode(i.bodyBytes))}if(t){const e=this.parseFromProtobufTxBody(t);if(e.type&&"UNKNOWN"!==e.type)return e}}}catch(i){}return this.parseFromTransactionInternals(e)}catch(n){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(KX(e,"scheduleCreate")){return{type:"SCHEDULECREATE",humanReadableType:"Schedule Create",scheduleCreate:{scheduledTransactionBody:globalThis.Buffer.from(t._scheduledTransaction).toString("base64"),memo:t._scheduleMemo,adminKey:t._adminKey?$X(t._adminKey):void 0,payerAccountId:t._payerAccountId?.toString(),expirationTime:t._expirationTime?.toString(),waitForExpiry:t._waitForExpiry||!1}}}if(KX(e,"scheduleSign")){return{type:"SCHEDULESIGN",humanReadableType:"Schedule Sign",scheduleSign:{scheduleId:t._scheduleId.toString()}}}if(KX(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 i=a.proto.SchedulableTransactionBody.encode(a.proto.SchedulableTransactionBody.create(e.scheduledTransactionBody)).finish();t.scheduledTransactionBody=globalThis.Buffer.from(i).toString("base64")}return e.memo&&(t.memo=e.memo),e.adminKey&&(t.adminKey=$X(e.adminKey)),e.payerAccountID&&(t.payerAccountId=new o.AccountId(e.payerAccountID.shardNum??0,e.payerAccountID.realmNum??0,e.payerAccountID.accountNum??0).toString()),e.expirationTime?.seconds&&(t.expirationTime=`${o.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 o.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 o.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 i=e;return i._scheduleId||i.scheduleId?{isScheduled:!0,scheduleRef:(i._scheduleId||i.scheduleId)?.toString()}:{isScheduled:!1}}catch(t){return{isScheduled:!1}}}static parseScheduledTransactionBody(e){try{let t;if(e.startsWith("0x")){const i=e.slice(2);t=new Uint8Array(globalThis.Buffer.from(i,"hex"))}else t=new Uint8Array(globalThis.Buffer.from(e,"base64"));const i=a.proto.SchedulableTransactionBody.decode(t),n=Object.keys(i).find(e=>null!==i[e]&&"transactionFee"!==e&&"memo"!==e);return n?{type:n.toUpperCase(),body:i[n],memo:i.memo,transactionFee:i.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 XX={TOKENCREATE:{bodyField:"tokenCreation",parser:WX.parseTokenCreate,resultField:"tokenCreation"},TOKENMINT:{bodyField:"tokenMint",parser:WX.parseTokenMint,resultField:"tokenMint"},TOKENBURN:{bodyField:"tokenBurn",parser:WX.parseTokenBurn,resultField:"tokenBurn"},TOKENUPDATE:{bodyField:"tokenUpdate",parser:WX.parseTokenUpdate,resultField:"tokenUpdate"},TOKENDELETE:{bodyField:"tokenDeletion",parser:WX.parseTokenDelete,resultField:"tokenDelete"},TOKENASSOCIATE:{bodyField:"tokenAssociate",parser:WX.parseTokenAssociate,resultField:"tokenAssociate"},TOKENDISSOCIATE:{bodyField:"tokenDissociate",parser:WX.parseTokenDissociate,resultField:"tokenDissociate"},TOKENFREEZE:{bodyField:"tokenFreeze",parser:WX.parseTokenFreeze,resultField:"tokenFreeze"},TOKENUNFREEZE:{bodyField:"tokenUnfreeze",parser:WX.parseTokenUnfreeze,resultField:"tokenUnfreeze"},TOKENGRANTKYC:{bodyField:"tokenGrantKyc",parser:WX.parseTokenGrantKyc,resultField:"tokenGrantKyc"},TOKENREVOKEKYC:{bodyField:"tokenRevokeKyc",parser:WX.parseTokenRevokeKyc,resultField:"tokenRevokeKyc"},TOKENPAUSE:{bodyField:"tokenPause",parser:WX.parseTokenPause,resultField:"tokenPause"},TOKENUNPAUSE:{bodyField:"tokenUnpause",parser:WX.parseTokenUnpause,resultField:"tokenUnpause"},TOKENWIPEACCOUNT:{bodyField:"tokenWipe",parser:WX.parseTokenWipeAccount,resultField:"tokenWipeAccount"},TOKENFEESCHEDULEUPDATE:{bodyField:"tokenFeeScheduleUpdate",parser:WX.parseTokenFeeScheduleUpdate,resultField:"tokenFeeScheduleUpdate"},TOKENAIRDROP:{bodyField:"tokenAirdrop",parser:WX.parseTokenAirdropFromProto,resultField:"tokenAirdrop"},TOPICCREATE:{bodyField:"consensusCreateTopic",parser:HX.parseConsensusCreateTopic,resultField:"consensusCreateTopic"},CONSENSUSSUBMITMESSAGE:{bodyField:"consensusSubmitMessage",parser:HX.parseConsensusSubmitMessage,resultField:"consensusSubmitMessage"},TOPICUPDATE:{bodyField:"consensusUpdateTopic",parser:HX.parseConsensusUpdateTopic,resultField:"consensusUpdateTopic"},TOPICDELETE:{bodyField:"consensusDeleteTopic",parser:HX.parseConsensusDeleteTopic,resultField:"consensusDeleteTopic"},ACCOUNTCREATE:{bodyField:"cryptoCreateAccount",parser:GX.parseCryptoCreateAccount,resultField:"cryptoCreateAccount"},ACCOUNTUPDATE:{bodyField:"cryptoUpdateAccount",parser:GX.parseCryptoUpdateAccount,resultField:"cryptoUpdateAccount"},ACCOUNTDELETE:{bodyField:"cryptoDelete",parser:GX.parseCryptoDelete,resultField:"cryptoDelete"},CRYPTOTRANSFER:{bodyField:"cryptoTransfer",parser:e=>{const t={transfers:[],tokenTransfers:[]};return GX.parseCryptoTransfers(e,t),t},resultField:"transfers",spreadResult:!0},APPROVEALLOWANCE:{bodyField:"cryptoApproveAllowance",parser:GX.parseCryptoApproveAllowance,resultField:"cryptoApproveAllowance"},DELETEALLOWANCE:{bodyField:"cryptoDeleteAllowance",parser:GX.parseCryptoDeleteAllowance,resultField:"cryptoDeleteAllowance"},FILECREATE:{bodyField:"fileCreate",parser:VX.parseFileCreate,resultField:"fileCreate"},FILEUPDATE:{bodyField:"fileUpdate",parser:VX.parseFileUpdate,resultField:"fileUpdate"},FILEDELETE:{bodyField:"fileDelete",parser:VX.parseFileDelete,resultField:"fileDelete"},FILEAPPEND:{bodyField:"fileAppend",parser:VX.parseFileAppend,resultField:"fileAppend"},CONTRACTCREATE:{bodyField:"contractCreateInstance",parser:ZX.parseContractCreate,resultField:"contractCreate"},CONTRACTUPDATE:{bodyField:"contractUpdateInstance",parser:ZX.parseContractUpdate,resultField:"contractUpdate"},CONTRACTDELETE:{bodyField:"contractDeleteInstance",parser:ZX.parseContractDelete,resultField:"contractDelete"},CONTRACTCALL:{bodyField:"contractCall",parser:ZX.parseContractCall,resultField:"contractCall"},ETHEREUMTRANSACTION:{bodyField:"ethereumTransaction",parser:ZX.parseEthereumTransaction,resultField:"ethereumTransaction"},SCHEDULECREATE:{bodyField:"scheduleCreate",parser:YX.parseScheduleCreateFromProto,resultField:"scheduleCreate"},SCHEDULESIGN:{bodyField:"scheduleSign",parser:YX.parseScheduleSignFromProto,resultField:"scheduleSign"},SCHEDULEDELETE:{bodyField:"scheduleDelete",parser:YX.parseScheduleDeleteFromProto,resultField:"scheduleDelete"},PRNG:{bodyField:"utilPrng",parser:JX.parseUtilPrng,resultField:"utilPrng"},FREEZE:{bodyField:"freeze",parser:JX.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:WX.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 QX={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"}},eQ={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"},tQ={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 iQ(e){for(const[t,i]of Object.entries(QX))if(e[t])return i;return{type:"UNKNOWN",humanReadableType:"Unknown Transaction"}}function nQ(e){return eQ[e]||"Unknown Transaction"}class oQ{static async parseTransactionBytes(e,t={}){const{enableFallback:i=!0,strictMode:n=!1,includeRaw:o=!0,maxRetries:r=2}=t,a=this.validateTransactionBytes(e);if(!a.isValid&&n)throw new HY(`Invalid transaction bytes format: ${a.error}`,"INVALID_FORMAT",void 0,e);let s,c=0;for(;c<=r;)try{const i=await this.parseTransaction(e,t);return i.formatDetection={originalFormat:a.format||"base64",wasConverted:"hex"===a.format,length:e.length},i}catch(l){if(s=l instanceof Error?l:new Error(String(l)),c++,!i||c>r){if(n)throw new HY("Failed to parse transaction after all attempts","PARSING_FAILED",s,e);break}try{const i=this.parseScheduledTransaction(e,t);return i.formatDetection={originalFormat:a.format||"base64",wasConverted:!1,length:e.length},i}catch(u){}}const p=this.createFallbackResult(e,s,void 0);return p.details&&(p.details.parseAttempts=Math.max(c,1)),p}static parseTransactionObject(e,t,i={}){let n,o;!t||s.Buffer.isBuffer(t)||t instanceof Uint8Array?(n=t,o=i):(o=t,n=void 0);try{const t=this.extractTransactionMetadata(e),i=WX.parseFromTransactionObject(e),s=GX.parseFromTransactionObject(e),c=HX.parseFromTransactionObject(e),p=VX.parseFromTransactionObject(e),l=ZX.parseFromTransactionObject(e),u=YX.parseFromTransactionObject(e),d=JX.parseFromTransactionObject(e),f=[i,s,c,p,l,u,d].find(e=>e.type&&"UNKNOWN"!==e.type)||{};let m,h="UNKNOWN",g="Unknown Transaction",y={};if(n||e.toBytes)try{const t=n||e.toBytes(),i=a.proto.TransactionList.decode(t);if(i.transactionList&&i.transactionList.length>0){const e=i.transactionList[0];if(e.bodyBytes&&e.bodyBytes.length>0){const t=a.proto.TransactionBody.decode(e.bodyBytes),i=this.detectTransactionTypeFromBody(t);h=i.type,g=i.humanReadableType,y=this.parseTransactionBodyDetails(t,h),y.tokenCreation&&(m=y.tokenCreation)}else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const t=a.proto.SignedTransaction.decode(e.signedTransactionBytes);if(t.bodyBytes){const e=a.proto.TransactionBody.decode(t.bodyBytes),i=this.detectTransactionTypeFromBody(e);h=i.type,g=i.humanReadableType,y=this.parseTransactionBodyDetails(e,h),y.tokenCreation&&(m=y.tokenCreation)}}}}catch(r){}"UNKNOWN"===h&&f.type&&(h=f.type,g=f.humanReadableType||g);const v={type:h,humanReadableType:g,transfers:[],tokenTransfers:[],...t,...f,raw:o.includeRaw?e._transactionBody||{}:void 0};return this.mergeProtoParsingResults(v,y,i,e,n),v.transfers=s.transfers||v.transfers||[],v.tokenTransfers=s.tokenTransfers||v.tokenTransfers||[],v}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),i=a.proto.SchedulableTransactionBody.decode(t),n=this.getTransactionType(i),r={type:n,humanReadableType:this.getHumanReadableType(n),transfers:[],tokenTransfers:[],raw:i};if(i.memo&&(r.memo=i.memo),i.transactionFee){const e=o.Hbar.fromTinybars(o.Long.fromValue(i.transactionFee));r.transactionFee=e.toString(o.HbarUnit.Hbar)}return this.applySchedulableTransactionParsing(i,r),r}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 iQ(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 iQ(e).type}static getHumanReadableType(e){return nQ(e)}static getTransactionSummary(e){return zX(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),i=/^[A-Za-z0-9+/]*={0,2}$/;let n,o=!1;return"hex"===t?(o=/^0x[0-9a-fA-F]+$/.test(e)&&e.length>2,o||(n="Invalid hex format")):(o=i.test(e)&&e.length>0,o||(n="Invalid base64 format")),{isValid:o,format:t,error:n,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(s.Buffer.from(t,"hex"))}return new Uint8Array(s.Buffer.from(e,"base64"))}catch(t){throw new HY("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 o.Transaction.fromBytes(t),!0}catch{return!1}}static decodeBytesLegacy(e){return this.decodeTransactionBytes(e)}static async parseTransaction(e,t={}){try{const i=this.decodeTransactionBytes(e),n=o.Transaction.fromBytes(i),r=this.extractTransactionMetadataEnhanced(n),a=this.runAllParsers(n),s=a.find(e=>e.type&&"UNKNOWN"!==e.type)||{},c=this.parseFromProtobuf(i),p=c.type||s.type||"UNKNOWN",l={type:p,humanReadableType:c.humanReadableType||s.humanReadableType||"Unknown Transaction",transfers:[],tokenTransfers:[],details:{...r},memo:"string"==typeof r.memo?r.memo:void 0,transactionId:"string"==typeof r.transactionId?r.transactionId:void 0,nodeAccountIds:Array.isArray(r.nodeAccountIds)?r.nodeAccountIds:[],maxTransactionFee:"string"==typeof r.maxTransactionFee?r.maxTransactionFee:void 0,validStart:"string"==typeof r.validStart?r.validStart:void 0,validDuration:"string"==typeof r.validDuration?r.validDuration:void 0,raw:t.includeRaw?{}:void 0};return this.mergeAllResults(l,c,s,a),l}catch(i){throw new HY("Failed to parse as regular transaction","REGULAR_PARSING_FAILED",i instanceof Error?i:void 0,e)}}static parseScheduledTransaction(e,t={}){try{const t=this.parseTransactionBody(e),i=this.validateTransactionBytes(e);return{...t,details:{...t.details||{},parseMethod:"scheduled",validation:i,parseAttempts:t.details?.parseAttempts||1},formatDetection:{originalFormat:i.format||"base64",wasConverted:!1,length:e.length}}}catch(i){throw new HY("Failed to parse as scheduled transaction","SCHEDULED_PARSING_FAILED",i instanceof Error?i: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[WX.parseFromTransactionObject(e),GX.parseFromTransactionObject(e),HX.parseFromTransactionObject(e),VX.parseFromTransactionObject(e),ZX.parseFromTransactionObject(e),YX.parseFromTransactionObject(e),JX.parseFromTransactionObject(e)]}static parseFromProtobuf(e){const t={};try{const i=a.proto.TransactionList.decode(e);if(i.transactionList&&i.transactionList.length>0){const e=i.transactionList[0];let n=null;if(e.bodyBytes&&e.bodyBytes.length>0)n=a.proto.TransactionBody.decode(e.bodyBytes);else if(e.signedTransactionBytes&&e.signedTransactionBytes.length>0){const t=a.proto.SignedTransaction.decode(e.signedTransactionBytes);t.bodyBytes&&(n=a.proto.TransactionBody.decode(t.bodyBytes))}if(n){const e=this.detectTransactionTypeFromBody(n);t.type=e.type,t.humanReadableType=e.humanReadableType;const i=this.parseTransactionBodyDetails(n,e.type);Object.assign(t,i)}}}catch(i){}return t}static mergeAllResults(e,t,i,n){const o=n.find(e=>e.transfers||e.tokenTransfers)||{};e.transfers=o.transfers||e.transfers||[],e.tokenTransfers=o.tokenTransfers||e.tokenTransfers||[],Object.keys(t).forEach(i=>{void 0!==t[i]&&"type"!==i&&"humanReadableType"!==i&&(e[i]=t[i])}),Object.keys(i).forEach(t=>{void 0===i[t]||t in e||"type"===t||"humanReadableType"===t||(e[t]=i[t])})}static applySchedulableTransactionParsing(e,t){e.cryptoTransfer&&GX.parseCryptoTransfers(e.cryptoTransfer,t),e.cryptoDelete&&(t.cryptoDelete=GX.parseCryptoDelete(e.cryptoDelete)),e.cryptoCreateAccount&&(t.cryptoCreateAccount=GX.parseCryptoCreateAccount(e.cryptoCreateAccount)),e.cryptoUpdateAccount&&(t.cryptoUpdateAccount=GX.parseCryptoUpdateAccount(e.cryptoUpdateAccount)),e.cryptoApproveAllowance&&(t.cryptoApproveAllowance=GX.parseCryptoApproveAllowance(e.cryptoApproveAllowance)),e.cryptoDeleteAllowance&&(t.cryptoDeleteAllowance=GX.parseCryptoDeleteAllowance(e.cryptoDeleteAllowance)),e.contractCall&&(t.contractCall=ZX.parseContractCall(e.contractCall)),e.contractCreateInstance&&(t.contractCreate=ZX.parseContractCreate(e.contractCreateInstance)),e.contractUpdateInstance&&(t.contractUpdate=ZX.parseContractUpdate(e.contractUpdateInstance)),e.contractDeleteInstance&&(t.contractDelete=ZX.parseContractDelete(e.contractDeleteInstance)),e.tokenCreation&&(t.tokenCreation=WX.parseTokenCreate(e.tokenCreation)),e.tokenMint&&(t.tokenMint=WX.parseTokenMint(e.tokenMint)),e.tokenBurn&&(t.tokenBurn=WX.parseTokenBurn(e.tokenBurn)),e.tokenUpdate&&(t.tokenUpdate=WX.parseTokenUpdate(e.tokenUpdate)),e.tokenFeeScheduleUpdate&&(t.tokenFeeScheduleUpdate=WX.parseTokenFeeScheduleUpdate(e.tokenFeeScheduleUpdate)),e.tokenFreeze&&(t.tokenFreeze=WX.parseTokenFreeze(e.tokenFreeze)),e.tokenUnfreeze&&(t.tokenUnfreeze=WX.parseTokenUnfreeze(e.tokenUnfreeze)),e.tokenGrantKyc&&(t.tokenGrantKyc=WX.parseTokenGrantKyc(e.tokenGrantKyc)),e.tokenRevokeKyc&&(t.tokenRevokeKyc=WX.parseTokenRevokeKyc(e.tokenRevokeKyc)),e.tokenPause&&(t.tokenPause=WX.parseTokenPause(e.tokenPause)),e.tokenUnpause&&(t.tokenUnpause=WX.parseTokenUnpause(e.tokenUnpause)),e.tokenWipe&&(t.tokenWipeAccount=WX.parseTokenWipeAccount(e.tokenWipe)),e.tokenDeletion&&(t.tokenDelete=WX.parseTokenDelete(e.tokenDeletion)),e.tokenAssociate&&(t.tokenAssociate=WX.parseTokenAssociate(e.tokenAssociate)),e.tokenDissociate&&(t.tokenDissociate=WX.parseTokenDissociate(e.tokenDissociate)),e.tokenAirdrop&&(t.tokenAirdrop=WX.parseTokenAirdropFromProto(e.tokenAirdrop)),e.consensusCreateTopic&&(t.consensusCreateTopic=HX.parseConsensusCreateTopic(e.consensusCreateTopic)),e.consensusSubmitMessage&&(t.consensusSubmitMessage=HX.parseConsensusSubmitMessage(e.consensusSubmitMessage)),e.consensusUpdateTopic&&(t.consensusUpdateTopic=HX.parseConsensusUpdateTopic(e.consensusUpdateTopic)),e.consensusDeleteTopic&&(t.consensusDeleteTopic=HX.parseConsensusDeleteTopic(e.consensusDeleteTopic)),e.fileCreate&&(t.fileCreate=VX.parseFileCreate(e.fileCreate)),e.fileAppend&&(t.fileAppend=VX.parseFileAppend(e.fileAppend)),e.fileUpdate&&(t.fileUpdate=VX.parseFileUpdate(e.fileUpdate)),e.fileDelete&&(t.fileDelete=VX.parseFileDelete(e.fileDelete)),e.utilPrng&&(t.utilPrng=JX.parseUtilPrng(e.utilPrng))}static parseTransactionBodyDetails(e,t){const i={},n=XX[t];if(n){const t=e[n.bodyField];if(t){const e=n.parser(t);n.spreadResult?Object.assign(i,e):i[n.resultField]=e}}return i}static mergeProtoParsingResults(e,t,i,n,o){const r=Object.values(XX).map(e=>e.resultField);for(const a of r){const o=t[a],r=i[a];void 0!==o?e[a]=o:void 0!==r?e[a]=r:this.handleSpecialFieldExtraction(e,a,n)}}static handleSpecialFieldExtraction(e,t,i){if("tokenCreation"===t&&"TOKENCREATE"===e.type){const n=WX.extractTokenCreationFromTransaction(i);n&&(e[t]=n)}else if("tokenAirdrop"===t&&"TOKENAIRDROP"===e.type){const n=WX.extractTokenAirdropFromTransaction(i);n&&(e[t]=n)}}static createFallbackResult(e,t,i){const n=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:i?.message,parseAttempts:i?2:1,validation:n},formatDetection:{originalFormat:n.format||"base64",wasConverted:!1,length:e.length},raw:{}}}}const rQ="undefined"!=typeof window&&void 0!==window.document;const aQ=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,i){return{inputHash:this.hashObject(e),clientConfigHash:this.hashObject({accountId:t.accountId,network:t.network}),optionsHash:this.hashObject({mode:i.mode,apiKey:i.apiKey?"present":"absent",network:i.network,metadata:i.metadata})}}get(e){const t=this.generateKey(e),i=this.cache.get(t);if(!i)return null;return Date.now()-i.timestamp>i.ttlMs?(this.cache.delete(t),null):(this.cache.delete(t),this.cache.set(t,i),i.quote)}set(e,t,i=this.defaultTtlMs){const n=this.generateKey(e);if(this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}this.cache.set(n,{quote:t,timestamp:Date.now(),ttlMs:i})}clear(){this.cache.clear()}},sQ=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),i=this.cache.get(t);if(!i)return null;return Date.now()-i.timestamp>this.defaultTtlMs?(this.cache.delete(t),null):i.sdk}set(e,t){const i=this.generateConfigKey(e);if(this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;e&&this.cache.delete(e)}this.cache.set(i,{sdk:t,timestamp:Date.now(),config:i})}clear(){this.cache.clear()}};let cQ={};async function pQ(e){if(rQ)throw new Error("File path operations are not supported in browser environment. Use buffer input type instead.");if(await async function(){if(!rQ&&!cQ.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"),i=t("path");cQ.readFileSync=e.readFileSync,cQ.basename=i.basename,cQ.extname=i.extname}}catch(e){console.warn("Node.js modules not available, file path operations will be disabled")}}(),!cQ.readFileSync||!cQ.basename||!cQ.extname)throw new Error("Node.js file system modules are not available. Cannot read file from path.");try{const i=cQ.readFileSync(e),n=i.toString("base64"),o=cQ.basename(e);let r="application/octet-stream";try{const e=await p.fileTypeFromBuffer(i);e&&(r=e.mime)}catch(t){const i=cQ.extname(e).toLowerCase();r={".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"}[i]||"application/octet-stream"}return{base64:n,fileName:o,mimeType:r}}catch(t){throw new Error(`Failed to read file ${e}: ${t.message}`)}}async function lQ(e,t,i,n){const o=y.getInstance({module:"Inscriber",...i.logging});o.info("Starting inscription process",{type:e.type,mode:i.mode||"file",quoteOnly:i.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(i.quoteOnly)return o.debug("Quote-only mode requested, generating quote"),await mQ(e,t,i,n);let r;"hashinal"===i.mode&&i.metadata&&fQ(i.metadata,o),n?(o.debug("Using existing InscriptionSDK instance"),r=n):i.apiKey?(o.debug("Initializing InscriptionSDK with API key"),r=new KY({apiKey:i.apiKey,network:t.network||"mainnet"})):(o.debug("Initializing InscriptionSDK with server auth"),r=await KY.createWithAuth({type:"server",accountId:t.accountId,privateKey:t.privateKey,network:t.network||"mainnet"}));const a={holderId:t.accountId,metadata:i.metadata||{},tags:i.tags||[],mode:i.mode||"file",fileStandard:i.fileStandard,chunkSize:i.chunkSize};let s;switch(e.type){case"url":s={...a,file:{type:"url",url:e.url}};break;case"file":{const t=await pQ(e.path);s={...a,file:{type:"base64",base64:t.base64,fileName:t.fileName,mimeType:t.mimeType}};break}case"buffer":s={...a,file:{type:"base64",base64:globalThis.Buffer.from(e.buffer).toString("base64"),fileName:e.fileName,mimeType:e.mimeType}}}"hashinal"===i.mode&&(s.metadataObject=i.metadata,s.creator=i.metadata?.creator||t.accountId,s.description=i.metadata?.description,i.jsonFileURL&&(s.jsonFileURL=i.jsonFileURL)),o.debug("Preparing to inscribe content",{type:e.type,mode:i.mode||"file",holderId:t.accountId});const c=await r.inscribeAndExecute(s,t);if(o.info("Starting to inscribe.",{type:e.type,mode:i.mode||"file",transactionId:c.jobId}),i.waitForConfirmation){o.debug("Waiting for inscription confirmation",{transactionId:c.jobId,maxAttempts:i.waitMaxAttempts,intervalMs:i.waitIntervalMs});const e=await hQ(r,c.jobId,i.waitMaxAttempts,i.waitIntervalMs,i.progressCallback);return o.info("Inscription confirmation received",{transactionId:c.jobId}),{confirmed:!0,result:c,inscription:e,sdk:r}}return{confirmed:!1,result:c,sdk:r}}catch(r){throw o.error("Error during inscription process",r),r}}async function uQ(e,t,i,n){const o=y.getInstance({module:"Inscriber",...i.logging});o.info("Starting inscription process with signer",{type:e.type,mode:i.mode||"file",quoteOnly:i.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(i.quoteOnly){o.debug("Quote-only mode requested with signer, generating quote");const r={accountId:t.getAccountId().toString(),privateKey:"",network:i.network||"mainnet"};return await mQ(e,r,i,n)}"hashinal"===i.mode&&i.metadata&&fQ(i.metadata,o);const r=t.getAccountId().toString();let a;o.debug("Using account ID from signer",{accountId:r}),n?(o.debug("Using existing InscriptionSDK instance"),a=n):i.apiKey?(o.debug("Initializing InscriptionSDK with API key"),a=new KY({apiKey:i.apiKey,network:i.network||"mainnet",connectionMode:"websocket"})):(o.debug("Initializing InscriptionSDK with client auth (websocket)"),a=await KY.createWithAuth({type:"client",accountId:r,signer:t,network:i.network||"mainnet",connectionMode:"websocket"}));const s={holderId:r,metadata:i.metadata||{},tags:i.tags||[],mode:i.mode||"file",fileStandard:i.fileStandard,chunkSize:i.chunkSize};let c;switch(e.type){case"url":c={...s,file:{type:"url",url:e.url}};break;case"file":{const t=await pQ(e.path);c={...s,file:{type:"base64",base64:t.base64,fileName:t.fileName,mimeType:t.mimeType}};break}case"buffer":c={...s,file:{type:"base64",base64:globalThis.Buffer.from(e.buffer).toString("base64"),fileName:e.fileName,mimeType:e.mimeType}}}"hashinal"===i.mode&&(c.metadataObject=i.metadata,c.creator=i.metadata?.creator||r,c.description=i.metadata?.description,i.jsonFileURL&&(c.jsonFileURL=i.jsonFileURL)),o.debug("Starting inscription via startInscription (websocket)",{type:e.type,mode:i.mode||"file",holderId:r,usesStartInscription:!0});const p=await a.startInscription({...c,holderId:r,network:i.network||"mainnet"});if(o.info("about to start inscription",{type:e.type,mode:i.mode||"file",jobId:p.id||p.tx_id,...p}),"string"==typeof p?.transactionBytes?(o.debug("Executing inscription transaction with signer from bytes"),await a.executeTransactionWithSigner(p.transactionBytes,t)):"Buffer"===p?.transactionBytes?.type&&(o.debug("Executing inscription transaction with signer from buffer"),await a.executeTransactionWithSigner(globalThis.Buffer.from(p.transactionBytes.data).toString("base64"),t)),i.waitForConfirmation){o.debug("Waiting for inscription confirmation (websocket)",{jobId:p.id||p.tx_id,maxAttempts:i.waitMaxAttempts,intervalMs:i.waitIntervalMs});const e=p.tx_id||p.id,t=await hQ(a,e,i.waitMaxAttempts,i.waitIntervalMs,i.progressCallback);return o.info("Inscription confirmation received",{jobId:e}),{confirmed:!0,result:{jobId:p.id||p.tx_id,transactionId:p.tx_id||"",topic_id:p.topic_id,status:p.status,completed:p.completed},inscription:t,sdk:a}}return{confirmed:!1,result:{jobId:p.id||p.tx_id,transactionId:p.tx_id||"",topic_id:p.topic_id,status:p.status,completed:p.completed},sdk:a}}catch(r){throw o.error("Error during inscription process",r),r}}async function dQ(e,t){const i=y.getInstance({module:"Inscriber",...t?.logging||{}}),n=e.includes("@")?`${e.split("@")[0]}-${e.split("@")[1].replace(/\./g,"-")}`:e;i.info("Retrieving inscription",{originalTransactionId:e,formattedTransactionId:n});try{let e;if(t?.apiKey)i.debug("Initializing InscriptionSDK with API key"),e=new KY({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 i.error("Missing authentication credentials",{hasApiKey:Boolean(t?.apiKey),hasAccountId:Boolean(t?.accountId),hasPrivateKey:Boolean(t?.privateKey)}),e}i.debug("Initializing InscriptionSDK with server auth"),e=await KY.createWithAuth({type:"server",accountId:t.accountId,privateKey:t.privateKey,network:t.network||"mainnet"})}i.debug("Initialized SDK for inscription retrieval",{formattedTransactionId:n,network:t.network||"mainnet"});const o=await e.retrieveInscription(n);return i.info("Successfully retrieved inscription",{formattedTransactionId:n}),o}catch(o){throw i.error("Error retrieving inscription",{formattedTransactionId:n,error:o}),o}}function fQ(e,t){const i=["name","creator","description","type"].filter(t=>!e[t]);if(i.length>0){const e=new Error(`Missing required Hashinal metadata fields: ${i.join(", ")}`);throw t.error("Hashinal metadata validation failed",{missingFields:i}),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 mQ(e,t,i,n){const o=y.getInstance({module:"Inscriber",...i.logging});o.info("Generating inscription quote",{type:e.type,mode:i.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,i){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(!i)throw new Error("Options are required");if("hashinal"===i.mode){if(!i.metadata)throw new Error("Hashinal mode requires metadata");const e=["name","creator","description","type"].filter(e=>!i.metadata||!i.metadata[e]);if(e.length>0)throw new Error(`Missing required Hashinal metadata fields: ${e.join(", ")}`)}}(e,t,i);const r=function(e,t,i){const n=aQ.createCacheKey(e,t,i);return aQ.get(n)}(e,t,i);if(r)return o.debug("Returning cached quote"),{confirmed:!1,quote:!0,result:r};"hashinal"===i.mode&&i.metadata&&fQ(i.metadata,o);const a=await async function(e,t,i){if(i)return i;const n={apiKey:t.apiKey,accountId:e.accountId,network:e.network||"mainnet",authType:t.apiKey?"api":"server"},o=sQ.get(n);if(o)return o;let r;return r=t.apiKey?new KY({apiKey:t.apiKey,network:e.network||"mainnet"}):await KY.createWithAuth({type:"server",accountId:e.accountId,privateKey:e.privateKey,network:e.network||"mainnet"}),sQ.set(n,r),r}(t,i,n),s={holderId:t.accountId,metadata:i.metadata||{},tags:i.tags||[],mode:i.mode||"file",fileStandard:i.fileStandard,chunkSize:i.chunkSize};let c;switch(e.type){case"url":c={...s,file:{type:"url",url:e.url}};break;case"file":{const t=await pQ(e.path);c={...s,file:{type:"base64",base64:t.base64,fileName:t.fileName,mimeType:t.mimeType}};break}case"buffer":c={...s,file:{type:"base64",base64:globalThis.Buffer.from(e.buffer).toString("base64"),fileName:e.fileName,mimeType:e.mimeType}}}"hashinal"===i.mode&&(c.metadataObject=i.metadata,c.creator=i.metadata?.creator||t.accountId,c.description=i.metadata?.description,i.jsonFileURL&&(c.jsonFileURL=i.jsonFileURL)),o.debug("Calling inscription SDK startInscription for quote",{type:e.type,mode:i.mode||"file",holderId:t.accountId});const p=await a.startInscription(c);o.debug("Received inscription response for quote parsing",{hasTransactionBytes:!!p.transactionBytes,bytesLength:p.transactionBytes?.length||0,transactionBytesType:typeof p.transactionBytes,totalCost:p.totalCost});const l=await async function(e,t){try{let n="0.001";if(e.totalCost&&"number"==typeof e.totalCost){n=(e.totalCost/1e8).toString(),t.debug("Using totalCost from inscription response",{totalCostTinybars:e.totalCost,totalCostHbar:n})}else if(e.transactionBytes){t.debug("Parsing transaction bytes for cost information");try{let i;if("string"==typeof e.transactionBytes)i=e.transactionBytes;else{if(!e.transactionBytes||"object"!=typeof e.transactionBytes||!("data"in e.transactionBytes))throw new Error("Invalid transactionBytes format");i=globalThis.Buffer.from(e.transactionBytes.data).toString("base64")}t.debug("About to parse transaction bytes",{bytesLength:i.length,bytesPreview:i.slice(0,100)});const o=await oQ.parseTransactionBytes(i,{includeRaw:!1});t.debug("Parsed transaction for quote",{type:o.type,hasTransfers:!!o.transfers,transferCount:o.transfers?.length||0,transfers:o.transfers});let r=0;if(o.transfers&&o.transfers.length>0)for(const e of o.transfers){const i="string"==typeof e.amount?parseFloat(e.amount):e.amount;if(i<0){const n=Math.abs(i);r+=n,t.debug("Found HBAR transfer",{from:e.accountId,to:"service",amount:n})}}r>0&&(n=r.toString(),t.debug("Using parsed transaction transfer amount",{totalTransferAmount:r,totalCostHbar:n}))}catch(i){t.warn("Could not parse transaction bytes, using totalCost fallback",{error:i,errorMessage:i instanceof Error?i.message:String(i)})}}const o=[{to:"Inscription Service",amount:n,description:`Inscription fee (${n} HBAR)`}],r={totalCostHbar:n,validUntil:new Date(Date.now()+9e5).toISOString(),breakdown:{transfers:o}};return t.debug("Successfully parsed transaction for quote",{totalCostHbar:r.totalCostHbar,transferCount:o.length,hasTransactionBytes:!!e.transactionBytes,hasTotalCost:!!e.totalCost}),r}catch(n){throw t.error("Error parsing transaction for quote",n),n}}(p,o);return function(e,t,i,n){const o=aQ.createCacheKey(e,t,i);aQ.set(o,n,6e5)}(e,t,i,l),o.info("Successfully generated inscription quote",{totalCostHbar:l.totalCostHbar}),{confirmed:!1,quote:!0,result:l}}catch(r){throw o.error("Error generating inscription quote",r),r}}async function hQ(e,t,i=30,n=4e3,o){const r=y.getInstance({module:"Inscriber"}),a=new WY({module:"Inscriber",logger:r,callback:o});try{r.debug("Waiting for inscription confirmation",{transactionId:t,maxAttempts:i,intervalMs:n}),a.preparing("Preparing for inscription confirmation",5,{transactionId:t,maxAttempts:i,intervalMs:n});try{const o=e.waitForInscription.bind(e),r=e=>{const t=e.stage||"confirming",i=["preparing","submitting","confirming","verifying","completed","failed"].includes(t)?t:"confirming",n=e.message||"Processing inscription",o=e.progressPercent||50;a.report({stage:i,message:n,progressPercent:o,details:e.details})};return await o(t,i,n,!0,r)}catch(mxe){return r.debug("Falling back to standard waitForInscription method",{error:mxe}),a.verifying("Verifying inscription status",50,{error:mxe}),await e.waitForInscription(t,i,n,!0)}}catch(s){throw r.error("Error waiting for inscription confirmation",{transactionId:t,maxAttempts:i,intervalMs:n,error:s}),a.failed("Inscription confirmation failed",{transactionId:t,error:s}),s}}function gQ(e){return"object"==typeof e&&null!==e&&"sequence_number"in e&&"consensus_timestamp"in e&&"number"==typeof e.sequence_number&&"string"==typeof e.consensus_timestamp}function yQ(e){if(!e||"object"!=typeof e)return;const t=e,i=t.topicId||t.topic_id;if("string"==typeof i&&i.trim())return i;const n=t,o=n.topicId;if("string"==typeof o&&o.trim())return o;const r=n.topic_id;return"string"==typeof r&&r.trim()?r:void 0}class vQ{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 bQ(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 xQ(e){const t=Object.create(y.prototype);return t.debug=(...t)=>e.debug(...t),t.info=(...t)=>e.info(...t),t.warn=(...t)=>e.warn(...t),t.error=(...t)=>e.error(...t),t.trace=(...t)=>e.trace(...t),t.setLogLevel=t=>e.setLogLevel(t),t.getLevel=()=>e.getLevel(),t.setSilent=t=>e.setSilent(t),t.setModule=t=>e.setModule(t),t.logger={level:e.getLevel()},t.moduleContext="",t.formatArgs=()=>({msg:""}),t}function wQ(e){return e instanceof y}async function kQ(e,t,i){const n=new I(t,i),o=[];for(const a of e)try{const e=await n.getPublicKey(a);o.push(e)}catch(r){i&&i.warn(`Could not get public key for account ${a}: ${r}`)}return o}class _Q{constructor(e="info"){this.defaultEndpoint="https://kiloscribe.com/api/inscription-cdn",this.logger=y.getInstance({level:e,module:"HRLResolver"})}isBinaryContentType(e){return["image/","audio/","video/","application/octet-stream","application/pdf","application/zip","application/gzip","application/x-binary","application/vnd.ms-","application/x-msdownload","application/x-shockwave-flash","font/","application/wasm"].some(t=>e.startsWith(t))}parseHRL(e){if(!e)return null;const t=e.match(/^hcs:\/\/(\d+)\/([0-9]+\.[0-9]+\.[0-9]+)$/);return t?{standard:t[1],topicId:t[2]}:null}isValidHRL(e){if(!e||"string"!=typeof e)return!1;const t=this.parseHRL(e);if(!t)return!1;return!!/^[0-9]+\.[0-9]+\.[0-9]+$/.test(t.topicId)}isValidTopicId(e){return/^[0-9]+\.[0-9]+\.[0-9]+$/.test(e)}async resolve(e,t){if(this.isValidHRL(e))return this.resolveHRL(e,t);if(!this.isValidTopicId(e))throw new Error(`Invalid HRL or topic ID format: ${e}`);try{const i=new I(t.network,this.logger),n=await i.getTopicInfo(e),o=n?.memo||"";let r="1";if(o){const e=o.match(/^hcs-(\d+)/);e&&e[1]&&(r=e[1])}const a=`hcs://${r}/${e}`;return this.resolveHRL(a,t)}catch(i){this.logger.error(`Failed to get topic info for ${e}: ${i.message}`);const n=`hcs://1/${e}`;return this.resolveHRL(n,t)}}async getContentWithType(e,t){if(!this.isValidHRL(e))return{content:e,contentType:"text/plain",isBinary:!1};try{const i=await this.resolveHRL(e,t);return{content:i.content,contentType:i.contentType,isBinary:i.isBinary}}catch(mxe){const t=`Error resolving HRL for content and type: ${mxe.message}`;throw this.logger.error(t),new Error(t)}}async resolveHRL(e,t){const i=this.parseHRL(e);if(!i)throw new Error(`Invalid HRL format: ${e}`);const{standard:n,topicId:o}=i;this.logger.debug(`Resolving HRL reference: standard=${n}, topicId=${o}`);try{const e=`${t.cdnEndpoint||this.defaultEndpoint}/${o}?network=${t.network}`;this.logger.debug(`Fetching content from CDN: ${e}`);const i=(await r.head(e)).headers["content-type"]||"";if(this.isBinaryContentType(i)||t.returnRaw){return{content:(await r.get(e,{responseType:"arraybuffer"})).data,contentType:i,topicId:o,isBinary:!0}}if("application/json"===i){const t=await r.get(e,{responseType:"json"});if(!t.data)throw new Error(`Failed to fetch content from topic: ${o}`);return{content:t.data,contentType:i,topicId:o,isBinary:!1}}const n=await r.get(e);if(!n.data)throw new Error(`Failed to fetch content from topic: ${o}`);let a;return a="object"==typeof n.data?n.data.content||n.data.text||JSON.stringify(n.data):n.data,{content:a,contentType:i,topicId:o,isBinary:!1}}catch(mxe){const t=`Error resolving HRL reference: ${mxe.message}`;throw this.logger.error(t),new Error(t)}}}class EQ{constructor(e){this.nodeHash=e}update(e){return this.nodeHash.update(e),this}digest(e){return this.nodeHash.digest(e)}}class SQ{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),i=await crypto.subtle.digest(this.mapAlgorithm(this.algorithm),t);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),i=new Uint8Array(t);let n=0;for(const o of e)i.set(o,n),n+=o.length;return i}mapAlgorithm(e){return{sha256:"SHA-256",sha384:"SHA-384",sha1:"SHA-1",sha512:"SHA-512"}[e.toLowerCase()]||"SHA-256"}}class TQ{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),i=this.simpleHash(t);return"hex"===e?i.toString(16).padStart(8,"0"):i.toString()}simpleHash(e){let t=0;for(let i=0;i<e.length;i++)t=(t<<5)-t+e[i]&4294967295;return Math.abs(t)}}function AQ(){const e="undefined"==typeof window;let t,i=!1,n=!1;try{i="undefined"!=typeof require&&"undefined"!=typeof process&&!!process.versions?.node}catch{i=!1}try{n="undefined"!=typeof crypto&&void 0!==crypto.subtle&&!e}catch{n=!1}return t=i&&e?"node":n&&!e?"web":"none",{hasNodeCrypto:i,hasWebCrypto:n,isSSR:e,preferredAPI:t}}function IQ(){return"undefined"==typeof window}class RQ{constructor(e){this.nodeHmac=e}update(e){return this.nodeHmac.update(e),this}digest(e){return this.nodeHmac.digest(e)}}class OQ{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),i=await crypto.subtle.importKey("raw",this.key,{name:"HMAC",hash:this.mapAlgorithm(this.algorithm)},!1,["sign"]),n=await crypto.subtle.sign("HMAC",i,t);return"hex"===e?Array.from(new Uint8Array(n)).map(e=>e.toString(16).padStart(2,"0")).join(""):globalThis.Buffer.from(n)}mapAlgorithm(e){return{sha256:"SHA-256",sha1:"SHA-1",sha512:"SHA-512"}[e.toLowerCase()]||"SHA-256"}}class jQ{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),i=this.simpleHmac(t,this.key);return"hex"===e?i.toString(16).padStart(8,"0"):i.toString()}simpleHmac(e,t){let i=0;for(let n=0;n<e.length;n++){const o=t[n%t.length];i=(i<<5)-i+e[n]+o&4294967295}return Math.abs(i)}}class CQ{constructor(){try{const e="crypto";this.crypto=require(e)}catch(e){throw new Error("Node.js crypto module not available")}}createHash(e){return new EQ(this.crypto.createHash(e))}createHmac(e,t){return new RQ(this.crypto.createHmac(e,t))}async pbkdf2(e,t,i,n,o){return new Promise((r,a)=>{this.crypto.pbkdf2(e,t,i,n,o,(e,t)=>{e?a(e):r(t)})})}timingSafeEqual(e,t){return this.crypto.timingSafeEqual(e,t)}}class NQ{createHash(e){return new SQ(e)}createHmac(e,t){return new OQ(t,e)}async pbkdf2(e,t,i,n,o){const r=new TextEncoder,a=await crypto.subtle.importKey("raw",r.encode(e),{name:"PBKDF2"},!1,["deriveBits"]),s=await crypto.subtle.deriveBits({name:"PBKDF2",salt:t,iterations:i,hash:this.mapDigest(o)},a,8*n);return globalThis.Buffer.from(s)}timingSafeEqual(e,t){if(e.length!==t.length)return!1;let i=0;for(let n=0;n<e.length;n++)i|=e[n]^t[n];return 0===i}mapDigest(e){return{sha256:"SHA-256",sha1:"SHA-1",sha512:"SHA-512"}[e.toLowerCase()]||"SHA-256"}}class BQ{createHash(e){return new TQ(e)}createHmac(e,t){return new jQ(t,e)}async pbkdf2(e,t,i,n,o){const r=new TextEncoder,a=globalThis.Buffer.from(r.encode(e));let s=globalThis.Buffer.alloc(n);for(let c=0;c<i;c++){const e=globalThis.Buffer.concat([a,t,globalThis.Buffer.from([c])]);let i=0;for(let t=0;t<e.length;t++)i=(i<<5)-i+e[t]&4294967295;s[c%n]^=255&i}return s}timingSafeEqual(e,t){if(e.length!==t.length)return!1;let i=0;for(let n=0;n<e.length;n++)i|=e[n]^t[n];return 0===i}}function PQ(){switch(AQ().preferredAPI){case"node":try{return new CQ}catch{return new BQ}case"web":return new NQ;default:return new BQ}}const LQ=["mainnet","testnet","previewnet","devnet"];function UQ(e){return LQ.includes(e)}const FQ=/^hedera:(mainnet|testnet|previewnet|devnet):\d+\.\d+\.\d+(?:-[a-zA-Z0-9]{5})?$/;function MQ(e){return FQ.test(e)}function DQ(e,t){if(!UQ(e))throw new Error("Invalid Hedera network");if(t.startsWith("hedera:")){if(MQ(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 zQ(e){if(!MQ(e))throw new Error("Invalid Hedera CAIP-10");const[,t,i]=e.match(/^hedera:([^:]+):(.+)$/);return{network:t,accountId:i}}const $Q=/^eip155:(\d+):(0x[0-9a-fA-F]{39,40})$/;function qQ(e){return $Q.test(e)}function KQ(e,t){const i=`eip155:${"number"==typeof e?String(e):e}:${t.startsWith("0x")?t:`0x${t}`}`;if(!qQ(i))throw new Error("Invalid EIP-155 CAIP-10");return i}const WQ=n.z.object({registry:n.z.string().min(1),name:n.z.string().min(1),version:n.z.string().min(1),protocol:n.z.string().min(1),nativeId:n.z.string().min(1),skills:n.z.array(n.z.number().int().nonnegative())});function HQ(e){return e.trim()}function VQ(e){return e.trim().toLowerCase()}function GQ(e){const t=WQ.parse(e);if("hcs-10"===t.protocol.trim().toLowerCase()&&!MQ(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()&&!qQ(t.nativeId.trim()))throw new Error("HCS-14: For protocol acp-virtuals, nativeId must be EIP-155 CAIP-10 (eip155:<chainId>:<address>)");const i={registry:VQ(t.registry),name:HQ(t.name),version:HQ(t.version),protocol:VQ(t.protocol),nativeId:HQ(t.nativeId),skills:[...t.skills].sort((e,t)=>e-t)},n=["skills","name","nativeId","protocol","registry","version"],o={};for(const r of n)o[r]=i[r];return{normalized:i,canonicalJson:JSON.stringify(o)}}const ZQ="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";function JQ(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 i=[0];for(let o=t;o<e.length;o++){let t=e[o];for(let e=0;e<i.length;e++){const n=(i[e]<<8)+t;i[e]=n%58,t=n/58|0}for(;t>0;)i.push(t%58),t=t/58|0}let n="";for(let o=0;o<t;o++)n+="1";for(let o=i.length-1;o>=0;o--)n+=ZQ[i[o]];return n}function YQ(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 i=[];for(let n=t;n<e.length;n++){const t=e[n],o=ZQ.indexOf(t);if(-1===o)throw new Error("Invalid Base58 character");let r=o;for(let e=0;e<i.length;e++){const t=58*i[e]+r;i[e]=255&t,r=t>>8}for(;r>0;)i.push(255&r),r>>=8}for(let n=0;n<t;n++)i.push(0);return i.reverse(),Uint8Array.from(i)}(e.slice(1))}function XQ(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 QQ(e,t){let i,n;if(e.startsWith("uaid:aid:"))i="aid",n=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");i=e.slice(t+1,o),n=e.slice(o+1)}}const{sanitized:o,hadSuffix:r}=function(e){const t=e.search(/[;?#]/);return-1===t?{sanitized:e,hadSuffix:!1}:{sanitized:e.slice(0,t),hadSuffix:!0}}(n);let a=o;if("hedera"===i){const e=o.match(/^(mainnet|testnet|previewnet|devnet):(.+)$/);e&&(a=e[2])}const s={...t||{}};var c;r&&!s.src&&(s.src=(c=e,"z"+JQ(globalThis.Buffer.from(c,"utf8"))));const p=XQ(s);return p?`uaid:did:${a};${p}`:`uaid:did:${a}`}function e0(e,t,i){return"string"==typeof e?QQ(e,t):async function(e,t,i){const{normalized:n,canonicalJson:o}=GQ(e),r=PQ().createHash("sha384").update(globalThis.Buffer.from(o,"utf8")).digest(),a=await Promise.resolve(r),s=JQ(globalThis.Buffer.isBuffer(a)?a:globalThis.Buffer.from(a)),c=!1!==i?.includeParams,p=c?function(e,t){const i={...t};return i.registry||(i.registry=e.registry),i.nativeId||(i.nativeId=e.nativeId),i.uid||(i.uid="0"),i}(n,t||{}):{},l=c?XQ(p):"";return l?`uaid:aid:${s};${l}`:`uaid:aid:${s}`}(e,t,i)}function t0(e){if(e.startsWith("uaid:")){const t=e.slice(5);let i,n;if(t.startsWith("did:"))i="did",n=t.slice(4);else{if(!t.startsWith("aid:"))throw new Error("Invalid UAID");i="aid",n=t.slice(4)}const o=n.indexOf(";"),r=o>=0?n.slice(0,o):n,a=(e=>{const t={};if(!e)return t;const i=e.split(";");for(const n of i){const e=n.indexOf("=");if(e>0){const i=n.slice(0,e),o=n.slice(e+1);t[i]=o}}return t})(o>=0?n.slice(o+1):"");return{method:"did"===i?"uaid":"aid",id:r,params:a}}throw new Error("Invalid DID")}class i0{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 u.resolveDID(e),i=t.id??t.didDocument?.id;return i?{id:i}:null}}class n0{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=t0(e);if("uaid"!==t.method)return null;const i=t.params.src;if(i){const e=globalThis.Buffer.from(YQ(i)).toString("utf8");return this.resolveDid(e)}const n=t.id;if(n.startsWith("testnet:")||n.startsWith("mainnet:")||n.startsWith("previewnet:")||n.startsWith("devnet:")){const e=`did:hedera:${n}`;return this.resolveDid(e)}const o=t.params.proto,r=t.params.nativeId;if("hcs-10"===o&&r){const e=r.match(/^hedera:(mainnet|testnet|previewnet|devnet):/);if(e){const t=`did:hedera:${e[1]}:${n}`;return this.resolveDid(t)}}return null}}const o0=new n0;class r0{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 a0=new r0;class s0{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");return(await d.createDID({},{client:e.client})).did}}class c0 extends Error{constructor(e,t){super(e),this.payloadSize=t,this.name="PayloadSizeError"}}class p0 extends Error{constructor(e){super(e),this.name="AccountCreationError"}}class l0 extends Error{constructor(e){super(e),this.name="TopicCreationError"}}class u0 extends Error{constructor(e){super(e),this.name="ConnectionConfirmationError"}}var d0=(e=>(e[e.PERSONAL=0]="PERSONAL",e[e.AI_AGENT=1]="AI_AGENT",e[e.MCP_SERVER=2]="MCP_SERVER",e))(d0||{}),f0=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTONOMOUS=1]="AUTONOMOUS",e))(f0||{}),m0=(e=>(e[e.REST=0]="REST",e[e.WEBSOCKET=1]="WEBSOCKET",e[e.GRPC=2]="GRPC",e))(m0||{}),h0=(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))(h0||{}),g0=(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))(g0||{}),y0=(e=>(e.DNS="dns",e.SIGNATURE="signature",e.CHALLENGE="challenge",e))(y0||{}),v0=(e=>(e.PUBLIC="PUBLIC",e.CONTROLLED="CONTROLLED",e.FEE_BASED="FEE_BASED",e))(v0||{});const b0={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};class x0{constructor(){this.config={},this.logger=y.getInstance({module:"AgentBuilder"})}setName(e){return this.config.name=e,this}setAlias(e){return this.config.alias=e,this}setBio(e){return this.config.bio=e,this}setDescription(e){return this.config.bio=e,this}setCapabilities(e){return this.config.capabilities=e,this}setAgentType(e){return this.config.metadata?this.config.metadata.type=e:this.config.metadata={type:e},this}setType(e){return this.config.metadata?this.config.metadata.type=e:this.config.metadata={type:e},this}setModel(e){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.model=e,this}setCreator(e){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.creator=e,this}addSocial(e,t){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.socials||(this.config.metadata.socials={}),this.config.metadata.socials[e]=t,this}addProperty(e,t){return this.config.metadata||(this.config.metadata={type:"manual"}),this.config.metadata.properties||(this.config.metadata.properties={}),this.config.metadata.properties[e]=t,this}setMetadata(e){return this.config.metadata=e,this}setProfilePicture(e,t){return this.config.pfpBuffer=e,this.config.pfpFileName=t,this}setExistingProfilePicture(e){return this.config.existingPfpTopicId=e,this}setNetwork(e){return this.config.network=e,this}setInboundTopicType(e){return this.config.inboundTopicType=e,this}setFeeConfig(e){return this.config.feeConfig=e,this}setConnectionFeeConfig(e){return this.config.connectionFeeConfig=e,this}setExistingAccount(e,t){return this.config.existingAccount={accountId:e,privateKey:t},this}setInboundTopicId(e){return this.config.inboundTopicId=e,this}setOutboundTopicId(e){return this.config.outboundTopicId=e,this}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=v0.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===v0.FEE_BASED&&!this.config.feeConfig)throw new Error("Fee configuration is required for fee-based topics");return this.config}}class w0 extends M0{constructor(e){if(super({network:e.network,logLevel:e.logLevel,prettyPrint:e.prettyPrint,feeAmount:e.feeAmount,mirrorNode:e.mirrorNode,silent:e.silent,keyType:e.keyType}),this.logger=y.getInstance({level:e.logLevel||"info",module:"HCS-SDK",silent:e.silent}),this.client="mainnet"===e.network?o.Client.forMainnet():o.Client.forTestnet(),this.operatorPrivateKey=e.operatorPrivateKey,this.operatorAccountId=e.operatorId,e.keyType){this.keyType=e.keyType;const t="ecdsa"===this.keyType?o.PrivateKey.fromStringECDSA(this.operatorPrivateKey):o.PrivateKey.fromStringED25519(this.operatorPrivateKey);this.client.setOperator(e.operatorId,t)}else{try{const t=C(this.operatorPrivateKey);this.keyType=t.detectedType,t.warning&&this.logger.warn(t.warning),this.client.setOperator(e.operatorId,t.privateKey)}catch(t){this.logger.warn("Failed to detect key type from private key format, will query mirror node"),this.keyType="ecdsa"}this.initializeOperator()}this.network=e.network,this.guardedRegistryBaseUrl=e.guardedRegistryBaseUrl||"https://moonscape.tech",this.hcs11Client=new L0({network:e.network,auth:{operatorId:e.operatorId,privateKey:e.operatorPrivateKey},logLevel:e.logLevel,silent:e.silent,keyType:e.keyType})}async initializeOperator(){const e=await this.requestAccount(this.operatorAccountId),t=e?.key?._type;t&&t.includes("ECDSA")?this.keyType="ecdsa":t&&t.includes("ED25519")?this.keyType="ed25519":this.keyType="ecdsa";const i="ecdsa"===this.keyType?o.PrivateKey.fromStringECDSA(this.operatorPrivateKey):o.PrivateKey.fromStringED25519(this.operatorPrivateKey);return this.logger.debug(`Setting operator: ${this.operatorAccountId} with key type: ${this.keyType}`),this.client.setOperator(this.operatorAccountId,i),{accountId:this.operatorAccountId,privateKey:this.operatorPrivateKey,keyType:this.keyType,client:this.client}}getClient(){return this.client}async createAccount(e=50){this.keyType||await this.initializeOperator(),this.logger.info(`Creating new account with ${e} HBAR initial balance`);const t=o.PrivateKey.generateED25519(),i=(new o.AccountCreateTransaction).setKeyWithoutAlias(t.publicKey).setInitialBalance(new o.Hbar(e));this.logger.debug("Executing account creation transaction");const n=await i.execute(this.client),r=(await n.getReceipt(this.client)).accountId;if(!r)throw this.logger.error("Account creation failed: accountId is null"),new p0("Failed to create account: accountId is null");return this.logger.info(`Account created successfully: ${r.toString()}`),{accountId:r.toString(),privateKey:t.toString()}}async createInboundTopic(e,t,i=60,n){this.keyType||await this.initializeOperator();const o=this._generateHcs10Memo(F0.INBOUND,{accountId:e,ttl:i});let r,a;switch(t){case v0.PUBLIC:r=!1;break;case v0.CONTROLLED:r=!0;break;case v0.FEE_BASED:if(r=!1,!n)throw new Error("Fee configuration builder is required for fee-based topics");n.customFees.forEach(t=>{t.feeCollectorAccountId||(this.logger.debug(`Defaulting fee collector for token ${t.feeTokenId||"HBAR"} to agent ${e}`),t.feeCollectorAccountId=e)}),a=n.build(),a.customFees=a.customFees.map(t=>({...t,feeCollectorAccountId:t.feeCollectorAccountId||e}));break;default:throw new Error(`Unsupported inbound topic type: ${t}`)}return this.createTopic(o,!0,r,a)}async createAgent(e,t=60,i,n){this.keyType||await this.initializeOperator();const o=e.build(),r=this.client.operatorAccountId?.toString();if(!r)throw new Error("Failed to retrieve operator account ID");const a=await this._createEntityTopics(t,{outboundTopicId:i?.outboundTopicId||"",inboundTopicId:i?.inboundTopicId||"",pfpTopicId:i?.pfpTopicId||o.existingPfpTopicId||"",profileTopicId:i?.profileTopicId||""},r,o.inboundTopicType,o.feeConfig,o.pfpBuffer,o.pfpFileName,n);if(a.profileTopicId)this.logger.info(`Using existing profile topic ID: ${a.profileTopicId}`);else{n&&n({stage:"preparing",message:"Creating agent profile",progressPercent:60,details:{outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.pfpTopicId,state:{currentStage:"profile",completedPercentage:60}}});const e=await this.storeHCS11Profile(o.name,o.bio,a.inboundTopicId,a.outboundTopicId,o.capabilities,o.metadata,o.pfpBuffer&&o.pfpBuffer.length>0&&!a.pfpTopicId?o.pfpBuffer:void 0,o.pfpFileName,a.pfpTopicId);a.profileTopicId=e.profileTopicId,this.logger.info(`Profile stored with topic ID: ${a.profileTopicId}`),n&&n({stage:"preparing",message:"Agent profile created",progressPercent:70,details:{outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.pfpTopicId,profileTopicId:a.profileTopicId,state:{currentStage:"profile",completedPercentage:70}}})}return a}async create(e,t){const i=t?.progressCallback,n=new WY({module:"ProfileCreate",logger:this.logger,callback:i?e=>i({stage:e.stage,message:e.message,progressPercent:e.progressPercent,details:e.details}):void 0});try{const i=e instanceof x0;let o;if(o=t?.existingState?t.existingState:{currentStage:"init",completedPercentage:0,createdResources:[]},i){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");n.preparing(`Starting ${i?"agent":"person"} resource creation`,0,{state:o});const r=this.client.operatorAccountId?.toString();if(!r)throw new Error("Failed to retrieve operator account ID");const{inboundTopicId:a,outboundTopicId:s,state:c}=await this.createCommunicationTopics(r,t,n);let p,l,u;if(o=c,e.setInboundTopicId(a),e.setOutboundTopicId(s),i){const t=e.build();p=t.existingPfpTopicId||o.pfpTopicId,l=t.pfpBuffer,u=t.pfpFileName||"pfp.png"}else{const t=e.build();p=o.pfpTopicId,l=t.pfpBuffer,u=t.pfpFileName}!p&&l&&u?p=await this.handleProfilePictureCreation(l,u,o,n):p&&(n.preparing(`Using existing profile picture: ${p}`,50,{state:o}),o.pfpTopicId=p),await this.createAndInscribeProfile(i,e,p,o,a,s,t,n),o.currentStage="complete",o.completedPercentage=100,n.completed((i?"Agent":"Person")+" profile created successfully",{profileTopicId:o.profileTopicId,inboundTopicId:a,outboundTopicId:s,pfpTopicId:p,state:o});let d="";o.outboundTopicId&&(d=o.outboundTopicId);let f="";o.inboundTopicId&&(f=o.inboundTopicId);let m="";o.pfpTopicId&&(m=o.pfpTopicId);let h="";return o.profileTopicId&&(h=o.profileTopicId),{outboundTopicId:d,inboundTopicId:f,pfpTopicId:m,profileTopicId:h,success:!0,state:o}}catch(o){return n.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 i=await this.hcs11Client.inscribeImage(e,t);if(!i.success)throw this.logger.error(`Failed to inscribe profile picture: ${i.error}`),new Error(i?.error||"Failed to inscribe profile picture");return this.logger.info(`Successfully inscribed profile picture with topic ID: ${i.imageTopicId}`),{pfpTopicId:i.imageTopicId,transactionId:i.transactionId,success:!0}}catch(mxe){const t=mxe,i=`Error inscribing profile picture: ${t.message}`;return this.logger.error(i),{pfpTopicId:"",transactionId:"",success:!1,error:t.message}}}async storeHCS11Profile(e,t,i,n,o=[],r,a,s,c){try{let p=c||"";if(!p&&a&&s){this.logger.info("Inscribing profile picture for HCS-11 profile");const e=await this.inscribePfp(a,s);e.success?p=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`),p=c);const l=this.hcs11Client.getAgentTypeFromMetadata({type:r.type||"autonomous"}),u=r.socials?Object.entries(r.socials).filter(([e,t])=>t).map(([e,t])=>({platform:e,handle:t})):void 0,d=this.hcs11Client.createAIAgentProfile(e,l,o,r.model||"unknown",{alias:e.toLowerCase().replace(/\s+/g,"_"),bio:t,profileImage:p?`hcs://1/${p}`:void 0,socials:u,properties:r.properties,inboundTopicId:i,outboundTopicId:n,creator:r.creator}),f=await this.hcs11Client.createAndInscribeProfile(d,!0);if(!f.success)throw this.logger.error(`Failed to inscribe profile: ${f.error}`),new Error(f.error||"Failed to inscribe profile");return this.logger.info(`Profile inscribed with topic ID: ${f.profileTopicId}, transaction ID: ${f.transactionId}`),{profileTopicId:f.profileTopicId,pfpTopicId:p,transactionId:f.transactionId,success:!0}}catch(mxe){const t=mxe,i=`Error storing HCS-11 profile: ${t.message}`;return this.logger.error(i),{profileTopicId:"",pfpTopicId:"",transactionId:"",success:!1,error:t.message}}}async setupFees(e,t,i=[]){let n=e;if(!this.client.operatorPublicKey)return n;if(!t.customFees||0===t.customFees.length)return this.logger.warn("No custom fees provided in fee config for setupFees"),n;t.customFees.length>10&&(this.logger.warn("More than 10 custom fees provided, only the first 10 will be used"),t.customFees=t.customFees.slice(0,10));const r=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 o.CustomFixedFee).setAmount(Number(e.feeAmount.amount)).setFeeCollectorAccountId(o.AccountId.fromString(e.feeCollectorAccountId));return e.feeTokenId&&t.setDenominatingTokenId(o.TokenId.fromString(e.feeTokenId)),t}return null}).filter(Boolean);if(0===r.length)return this.logger.warn("No valid custom fees to apply in setupFees"),n;const a=[...t.exemptAccounts||[],...i];return a.length>0&&(n=await this.setupExemptKeys(e,a)),n.setFeeScheduleKey(this.client.operatorPublicKey).setCustomFees(r)}async setupExemptKeys(e,t){let i=e;const n=Array.from(new Set(t)).filter(e=>e!==this.client.operatorAccountId?.toString());let o=[];if(n.length>0)try{o=await kQ(n,this.network,this.logger)}catch(mxe){const t=`Error getting exempt keys: ${mxe.message}, continuing without exempt keys`;this.logger.warn(t)}return o.length>0&&(i=i.setFeeExemptKeys(o)),i}async handleConnectionRequest(e,t,i,n,r=60){const a=this._generateHcs10Memo(F0.CONNECTION,{ttl:r,inboundTopicId:e,connectionId:i});this.logger.info(`Handling connection request ${i} from ${t}`);const s=this.getClient().operatorAccountId?.toString();if(!s)throw new Error("Failed to retrieve operator account ID");let c=await this.mirrorNode.getPublicKey(t);const p=await this.mirrorNode.getPublicKey(s);if(!p)throw new Error("Failed to retrieve public key");const l=new o.KeyList([p,c],1);let u;try{if(n){const e=n.build(),t={...e,exemptAccounts:[...e.exemptAccounts||[]]};u=await this.createTopic(a,l,l,t)}else u=await this.createTopic(a,l,l);this.logger.info(`Created new connection topic ID: ${u}`)}catch(y){const e=`Failed to create connection topic: ${y}`;throw this.logger.error(e),new l0(e)}const d=`${e}@${s}`,f=await this.confirmConnection(e,u,t,i,"Connection accepted. Looking forward to collaborating!"),m=await this.retrieveCommunicationTopics(s),h=await this.retrieveCommunicationTopics(t),g=`${h.inboundTopic}@${t}`;return await this.recordOutboundConnectionConfirmation({outboundTopicId:m.outboundTopic,requestorOutboundTopicId:h.outboundTopic,connectionRequestId:i,confirmedRequestId:f,connectionTopicId:u,operatorId:g,memo:`Connection established with ${t}`}),{connectionTopicId:u,confirmedConnectionSequenceNumber:f,operatorId:d}}async confirmConnection(e,t,i,n,o,r){const a=await this.getOperatorId();this.logger.info(`Confirming connection with ID ${n}`);const s={p:"hcs-10",op:"connection_created",connection_topic_id:t,connected_account_id:i,operator_id:a,connection_id:n,m:o},c=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),p=await this.submitPayload(e,s,r,c.requiresFee),l=p.topicSequenceNumber?.toNumber();if(!l)throw new u0("Failed to confirm connection: sequence number is null");return l}async sendMessage(e,t,i,n,o){const r=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),a={p:"hcs-10",op:"message",operator_id:await this.getOperatorId(),data:t,m:i},s=JSON.stringify(a);if(globalThis.Buffer.from(s).length>1e3){this.logger.info("Message payload exceeds 1000 bytes, storing via inscription");try{const e=globalThis.Buffer.from(t),i=`message-${Date.now()}.json`,n=await this.inscribeFile(e,i,{progressCallback:o?.progressCallback,waitMaxAttempts:o?.waitMaxAttempts,waitIntervalMs:o?.waitIntervalMs});if(!yQ(n))throw new Error("Failed to inscribe large message content");a.data=`hcs://1/${yQ(n)}`,this.logger.info(`Large message inscribed with topic ID: ${yQ(n)}`)}catch(c){const e=`Error inscribing large message: ${c.message}`;throw this.logger.error(e),new Error(e)}}return this.logger.info("Submitting message to connection topic",a),await this.submitPayload(e,a,n,r.requiresFee)}async createTopic(e,t,i,n){this.logger.info("Creating topic");const o=N({memo:e,adminKey:t,submitKey:i,operatorPublicKey:this.client.operatorPublicKey||void 0});n&&await this.setupFees(o,n),this.logger.debug("Executing topic creation transaction");const r=await o.execute(this.client),a=await r.getReceipt(this.client);if(!a.topicId)throw this.logger.error("Failed to create topic: topicId is null"),new Error("Failed to create topic: topicId is null");return a.topicId.toString()}async submitPayload(e,t,i,n=!1){const r="string"==typeof t?t:JSON.stringify(t),a=globalThis.Buffer.byteLength(r,"utf8");if(a>1e3)throw new c0("Payload size exceeds 1000 bytes limit",a);const s=B({topicId:e,message:r,transactionMemo:this.getHcs10TransactionMemo(t)||void 0});let c;if(n&&(this.logger.info("Topic requires fee payment, setting max transaction fee"),s.setMaxTransactionFee(new o.Hbar(this.feeAmount))),i){const e=s.freezeWith(this.client),t=await e.sign(i);c=await t.execute(this.client)}else c=await s.execute(this.client);const p=await c.getReceipt(this.client);if(!p)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"),p}async inscribeFile(e,t,i){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.operatorPrivateKey)throw this.logger.error("Operator private key is not set"),new Error("Operator private key is not set");const n=h.lookup(t)||"application/octet-stream",r="ecdsa"===this.keyType?o.PrivateKey.fromStringECDSA(this.operatorPrivateKey):o.PrivateKey.fromStringED25519(this.operatorPrivateKey),a=await KY.createWithAuth({type:"server",accountId:this.client.operatorAccountId.toString(),privateKey:r,network:this.network}),s={mode:"file",waitForConfirmation:!0,waitMaxAttempts:i?.waitMaxAttempts||30,waitIntervalMs:i?.waitIntervalMs||4e3,progressCallback:i?.progressCallback,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},c=await lQ({type:"buffer",buffer:e,fileName:t,mimeType:n},{accountId:this.client.operatorAccountId.toString(),privateKey:r,network:this.network},s,a);if(!c.confirmed||!c.inscription)throw new Error("Inscription was not confirmed");return c.inscription}async waitForConnectionConfirmation(e,t,i=60,n=2e3,o=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let r=0;r<i;r++){this.logger.info(`Attempt ${r+1}/${i} to find connection confirmation`);const a=(await this.mirrorNode.getTopicMessages(e)).filter(e=>"connection_created"===e.op);if(this.logger.info(`Found ${a.length} connection_created messages`),a.length>0)for(const e of a)if(Number(e.connection_id)===Number(t)){const i={connectionTopicId:e.connection_topic_id,sequence_number:Number(e.sequence_number),confirmedBy:e.operator_id,memo:e.m},n=this.extractAccountFromOperatorId(i.confirmedBy),r=this.getAccountAndSigner(),a=await this.retrieveCommunicationTopics(n),s=await this.retrieveCommunicationTopics(r.accountId);return this.logger.info("Connection confirmation found",i),o&&await this.recordOutboundConnectionConfirmation({requestorOutboundTopicId:a.outboundTopic,outboundTopicId:s.outboundTopic,connectionRequestId:t,confirmedRequestId:i.sequence_number,connectionTopicId:i.connectionTopicId,operatorId:i.confirmedBy,memo:i.memo||"Connection confirmed"}),i}r<i-1&&(this.logger.info(`No matching confirmation found, waiting ${n}ms before retrying...`),await new Promise(e=>setTimeout(e,n)))}throw new Error(`Connection confirmation not found after ${i} attempts for request ID ${t}`)}getAccountAndSigner(){const e="ecdsa"===this.keyType?o.PrivateKey.fromStringECDSA(this.operatorPrivateKey):o.PrivateKey.fromStringED25519(this.operatorPrivateKey);return{accountId:this.client.operatorAccountId.toString(),signer:e}}async createAndRegisterAgent(e,t){try{const i=e.build(),n=t?.progressCallback,r=t?.baseUrl||this.guardedRegistryBaseUrl;let a=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};a.agentMetadata=i.metadata,n&&n({stage:"preparing",message:"Starting agent creation process",progressPercent:0,details:{state:a}});let s,c=i.existingAccount;if(a.inboundTopicId&&a.outboundTopicId&&a.profileTopicId){if(c=c||i.existingAccount,!c)throw new Error("Cannot resume registration without account information");const e="ecdsa"===this.keyType?o.PrivateKey.fromStringECDSA(c.privateKey).publicKey.toString():o.PrivateKey.fromStringED25519(c.privateKey).publicKey.toString();s=new w0({network:i.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:e,logLevel:"info",guardedRegistryBaseUrl:r}),this.logger.info("Resuming registration with existing state",{inboundTopicId:a.inboundTopicId,outboundTopicId:a.outboundTopicId,profileTopicId:a.profileTopicId,pfpTopicId:a.pfpTopicId})}else{if(!c)if(a.createdResources&&a.createdResources.some(e=>e.startsWith("account:"))){const e=a.createdResources.find(e=>e.startsWith("account:")),n=e?.split(":")[1];n&&i.existingAccount?(c=i.existingAccount,this.logger.info(`Resuming with existing account: ${n}`)):(c=await this.createAccount(t?.initialBalance),a.createdResources=a.createdResources||[],a.createdResources.push(`account:${c.accountId}`))}else c=await this.createAccount(t?.initialBalance),a.createdResources=a.createdResources||[],a.createdResources.push(`account:${c.accountId}`);n&&n({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:a,account:c}});const p=C(c.privateKey),l=("ed25519"===p.detectedType?o.PrivateKey.fromStringED25519(c.privateKey):o.PrivateKey.fromStringECDSA(c.privateKey)).publicKey.toString();s=new w0({network:i.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:l,keyType:p.detectedType,logLevel:"info",guardedRegistryBaseUrl:r}),n&&n({stage:"preparing",message:"Initialized agent client",progressPercent:25,details:{state:a}});let u=a.outboundTopicId,d=a.inboundTopicId,f=a.pfpTopicId,m=a.profileTopicId;if(!u||!d||!m){f&&e.setExistingProfilePicture(f);const t=await s.createAgent(e,60,a,e=>{n&&n({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:{...e.details,state:{...a,...e.details?.state}}})});u=t.outboundTopicId,d=t.inboundTopicId,f=t.pfpTopicId,m=t.profileTopicId,a.outboundTopicId=u,a.inboundTopicId=d,a.pfpTopicId=f,a.profileTopicId=m,a.createdResources||(a.createdResources=[]),f&&!a.createdResources.includes(`pfp:${f}`)&&a.createdResources.push(`pfp:${f}`),a.createdResources.includes(`inbound:${d}`)||a.createdResources.push(`inbound:${d}`),a.createdResources.includes(`outbound:${u}`)||a.createdResources.push(`outbound:${u}`),a.createdResources.includes(`profile:${m}`)||a.createdResources.push(`profile:${m}`)}a.currentStage="profile",a.completedPercentage=60,n&&n({stage:"submitting",message:"Created agent with topics and profile",progressPercent:60,details:{state:a,outboundTopicId:u,inboundTopicId:d,pfpTopicId:f,profileTopicId:m}})}const p=`${a.inboundTopicId}@${c.accountId}`;if("complete"!==a.currentStage||!a.createdResources?.includes(`registration:${a.inboundTopicId}`)){const e=await s.registerAgentWithGuardedRegistry(c.accountId,i.network,{progressCallback:e=>{const t=60+.4*(e.progressPercent||0);n&&n({stage:e.stage,message:e.message,progressPercent:t,details:{...e.details,outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.pfpTopicId,profileTopicId:a.profileTopicId,operatorId:p,state:e.details?.state||a}})},existingState:a});if(!e.success)return{...e,state:a};a=e.state||a}return n&&n({stage:"completed",message:"Agent creation and registration complete",progressPercent:100,details:{outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.pfpTopicId,profileTopicId:a.profileTopicId,operatorId:p,state:a}}),{success:!0,state:a,metadata:{accountId:c.accountId,privateKey:c.privateKey,operatorId:p,inboundTopicId:a.inboundTopicId,outboundTopicId:a.outboundTopicId,profileTopicId:a.profileTopicId,pfpTopicId:a.pfpTopicId}}}catch(mxe){const i=mxe,n=`Failed to create and register agent: ${i.message}`;return this.logger.error(n),{error:i.message,success:!1,state:t?.existingState||{currentStage:"init",completedPercentage:0,error:i.message}}}}async registerAgentWithGuardedRegistry(e,t=this.network,i){try{this.logger.info("Registering agent with guarded registry");const n=i?.maxAttempts??60,r=i?.delayMs??2e3,a=i?.progressCallback;let s=i?.existingState||{currentStage:"registration",completedPercentage:0,createdResources:[]};a&&a({stage:"preparing",message:"Preparing agent registration",progressPercent:10,details:{state:s}});const c=await this.executeRegistration(e,t,this.guardedRegistryBaseUrl,this.logger);if(!c.success)return{...c,state:s};if(a&&a({stage:"submitting",message:"Submitting registration to registry",progressPercent:30,details:{transactionId:c.transactionId,state:s}}),c.transaction){const e=o.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")}a&&a({stage:"confirming",message:"Confirming registration transaction",progressPercent:60,details:{accountId:e,transactionId:c.transactionId,state:s}});const p=await this.waitForRegistrationConfirmation(c.transactionId,t,this.guardedRegistryBaseUrl,n,r,this.logger);return s.currentStage="complete",s.completedPercentage=100,s.createdResources||(s.createdResources=[]),c.transactionId&&s.createdResources.push(`registration:${c.transactionId}`),a&&a({stage:"completed",message:"Agent registration complete",progressPercent:100,details:{confirmed:p,transactionId:c.transactionId,state:s}}),{...c,confirmed:p,state:s}}catch(mxe){const t=mxe,i=`Failed to register agent: ${t.message}`;return this.logger.error(i),{error:t.message,success:!1}}}async registerAgent(e,t,i,n,o){this.logger.info("Registering agent");const r={p:"hcs-10",op:"register",account_id:t,inbound_topic_id:i,m:n};await this.submitPayload(e,r,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 v0.PUBLIC;if(t.fee_schedule_key&&t.fee_schedule_key.key&&t.custom_fees){const i=t.custom_fees;if(i&&i.fixed_fees&&i.fixed_fees.length>0)return this.logger.info(`Topic ${e} is fee-based with ${i.fixed_fees.length} custom fees`),v0.FEE_BASED}return v0.CONTROLLED}catch(mxe){const t=`Error determining topic type: ${mxe.message}`;throw this.logger.error(t),new Error(t)}}getNetwork(){return this.network}getLogger(){return this.logger}getOperatorAccountId(){return this.client.operatorAccountId?.toString()??null}async createScheduledTransaction(e,t,i,n){this.logger.info("Creating scheduled transaction");const r=(new o.ScheduleCreateTransaction).setScheduledTransaction(e).setPayerAccountId(n?o.AccountId.fromString(n):this.client.operatorAccountId);if(t&&r.setScheduleMemo(t),i){const e=f.addSeconds(new Date,i),t=o.Timestamp.fromDate(e);r.setExpirationTime(t)}this.logger.debug("Executing schedule create transaction");const a=await r.execute(this.client),s=await a.getReceipt(this.client);if(!s.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=s.scheduleId.toString(),p=a.transactionId.toString();return this.logger.info(`Scheduled transaction created successfully: ${c}`),{scheduleId:c,transactionId:p}}async sendTransactionOperation(e,t,i,n,o){const r=await this.canSubmitToTopic(e,this.client.operatorAccountId?.toString()||""),a={p:"hcs-10",op:"transaction",operator_id:await this.getOperatorId(),schedule_id:t,data:i,m:o?.memo};return this.logger.info("Submitting transaction operation to connection topic",a),await this.submitPayload(e,a,n,r.requiresFee)}async sendTransaction(e,t,i,n){this.logger.info("Creating scheduled transaction and sending transaction operation");const{scheduleId:o,transactionId:r}=await this.createScheduledTransaction(t,n?.scheduleMemo,n?.expirationTime,n?.schedulePayerAccountId);return{scheduleId:o,transactionId:r,receipt:await this.sendTransactionOperation(e,o,i,n?.submitKey,{memo:n?.operationMemo})}}async createCommunicationTopics(e,t,i){let n=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};if(i&&i.preparing("Starting communication topic creation",0,{state:n}),!n.outboundTopicId){n.currentStage="topics",i&&i.preparing("Creating outbound topic",5,{state:n});const o=this._generateHcs10Memo(F0.OUTBOUND,{ttl:t?.ttl,accountId:e}),r=await this.createTopic(o,!0,!0);n.outboundTopicId=r,n.createdResources&&n.createdResources.push(`outbound:${n.outboundTopicId}`)}if(!n.inboundTopicId){n.currentStage="topics",i&&i.preparing("Creating inbound topic",10,{state:n});const o=this._generateHcs10Memo(F0.INBOUND,{ttl:t?.ttl,accountId:e}),r=await this.createTopic(o,!0,!1);n.inboundTopicId=r,n.createdResources&&n.createdResources.push(`inbound:${n.inboundTopicId}`)}return{inboundTopicId:n.inboundTopicId,outboundTopicId:n.outboundTopicId,state:n}}async handleProfilePictureCreation(e,t,i,n){i.currentStage="pfp",n.preparing("Creating profile picture",30,{state:i}),n.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 r=o.pfpTopicId;return i.pfpTopicId=r,i.createdResources&&i.createdResources.push(`pfp:${i.pfpTopicId}`),n.preparing("Profile picture created",50,{state:i}),r}async createAndInscribeProfile(e,t,i,n,o,r,a,s){if(this.logger.info("Creating and inscribing profile"),n.profileTopicId)s&&s.preparing(`Using existing ${e?"agent":"person"} profile`,95,{state:n});else{let c;if(s&&s.preparing(`Storing HCS-11 ${e?"agent":"person"} profile`,80),s?.createSubProgress({minPercent:80,maxPercent:95,logPrefix:"StoreProfile"}),e){const e=t.build(),n=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:i?`hcs://1/${i}`:void 0,socials:n,properties:e.metadata?.properties||{},inboundTopicId:o,outboundTopicId:r,creator:e.metadata?.creator})}else{const e=t.build(),{pfpBuffer:n,pfpFileName:a,...s}=e;c=this.hcs11Client.createPersonalProfile(e.display_name,{alias:e.alias,bio:e.bio,socials:e.socials,profileImage:i?`hcs://1/${i}`:e.profileImage,properties:e.properties,inboundTopicId:o,outboundTopicId:r})}const p=await this.hcs11Client.createAndInscribeProfile(c,a?.updateAccountMemo??!0);if(!p.success){s&&s.failed(`Failed to inscribe ${e?"agent":"person"} profile`,{error:p.error});let t=`Failed to inscribe ${e?"agent":"person"} profile`;throw p.error&&(t=p.error),new Error(t)}n.profileTopicId=p.profileTopicId,n.createdResources&&n.createdResources.push(`profile:${p.profileTopicId}`),s&&s.preparing("HCS-11 Profile stored",95,{state:n})}}async createMCPServer(e,t=60,i,n){this.keyType||await this.initializeOperator();const o=e.build(),r=this.client.operatorAccountId?.toString();if(!r)throw new Error("Failed to retrieve operator account ID");const a=await this._createEntityTopics(t,{outboundTopicId:i?.outboundTopicId||"",inboundTopicId:i?.inboundTopicId||"",pfpTopicId:i?.pfpTopicId||o.existingPfpTopicId||"",profileTopicId:i?.profileTopicId||""},r,v0.PUBLIC,void 0,o.pfpBuffer,o.pfpFileName,n);if(a.profileTopicId)this.logger.info(`Using existing profile topic ID: ${a.profileTopicId}`);else{this.logger.info("Creating and storing HCS-11 MCP server profile"),n&&n({stage:"preparing",message:"Creating MCP server profile",progressPercent:60,details:{outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.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:a.inboundTopicId,outboundTopicId:a.outboundTopicId,profileImage:a.pfpTopicId?`hcs://1/${a.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");a.profileTopicId=t.profileTopicId,this.logger.info(`MCP server profile stored with topic ID: ${a.profileTopicId}`);const i=await this.hcs11Client.updateAccountMemoWithProfile(r,a.profileTopicId);i.success?this.logger.info("Updated account memo with profile reference"):this.logger.warn(`Failed to update account memo: ${i.error}, but continuing with MCP server creation`),n&&n({stage:"preparing",message:"MCP server profile created",progressPercent:70,details:{outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.pfpTopicId,profileTopicId:a.profileTopicId,state:{currentStage:"profile",completedPercentage:70}}})}return a}async _createEntityTopics(e,t,i,n,o,r,a,s){let{outboundTopicId:c,inboundTopicId:p,pfpTopicId:l,profileTopicId:u}=t;if(c)this.logger.info(`Using existing outbound topic ID: ${c}`);else{const t=this._generateHcs10Memo(F0.OUTBOUND,{ttl:e});c=await this.createTopic(t,!0,!0),this.logger.info(`Created new outbound topic ID: ${c}`),s&&s({stage:"preparing",message:"Created outbound topic",progressPercent:30,details:{outboundTopicId:c,state:{currentStage:"topics",completedPercentage:30}}})}if(p?this.logger.info(`Using existing inbound topic ID: ${p}`):(p=await this.createInboundTopic(i,n,e,n===v0.FEE_BASED?o:void 0),this.logger.info(`Created new inbound topic ID: ${p}`),s&&s({stage:"preparing",message:"Created inbound topic",progressPercent:40,details:{outboundTopicId:c,inboundTopicId:p,state:{currentStage:"topics",completedPercentage:40}}})),!l&&r&&r.length>0&&a){this.logger.info("Inscribing new profile picture"),s&&s({stage:"preparing",message:"Inscribing profile picture",progressPercent:50,details:{outboundTopicId:c,inboundTopicId:p,state:{currentStage:"pfp",completedPercentage:50}}});l=(await this.inscribePfp(r,a)).pfpTopicId,this.logger.info(`Profile picture inscribed with topic ID: ${l}`),s&&s({stage:"preparing",message:"Profile picture inscribed",progressPercent:55,details:{outboundTopicId:c,inboundTopicId:p,pfpTopicId:l,state:{currentStage:"pfp",completedPercentage:55}}})}else l&&this.logger.info(`Using existing profile picture with topic ID: ${l}`);return{inboundTopicId:p,outboundTopicId:c,pfpTopicId:l,profileTopicId:u}}async createAndRegisterMCPServer(e,t){try{const i=e.build(),n=t?.progressCallback,r=t?.baseUrl||this.guardedRegistryBaseUrl;let a=t?.existingState||{currentStage:"init",completedPercentage:0,createdResources:[]};a.serverMetadata={name:i.name,description:i.mcpServer.description,services:i.mcpServer.services},n&&n({stage:"preparing",message:"Starting MCP server creation process",progressPercent:0,details:{state:a}});let s,c=i.existingAccount;if(a.inboundTopicId&&a.outboundTopicId&&a.profileTopicId){if(c=c||i.existingAccount,!c)throw new Error("Cannot resume registration without account information");const e=C(c.privateKey),t=("ed25519"===e.detectedType?o.PrivateKey.fromStringED25519(c.privateKey):o.PrivateKey.fromStringECDSA(c.privateKey)).publicKey.toString();s=new w0({network:i.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:t,keyType:e.detectedType,logLevel:"info",guardedRegistryBaseUrl:r}),this.logger.info("Resuming registration with existing state",{inboundTopicId:a.inboundTopicId,outboundTopicId:a.outboundTopicId,profileTopicId:a.profileTopicId,pfpTopicId:a.pfpTopicId})}else{if(!c)if(a.createdResources&&a.createdResources.some(e=>e.startsWith("account:"))){const e=a.createdResources.find(e=>e.startsWith("account:")),n=e?.split(":")[1];n&&i.existingAccount?(c=i.existingAccount,this.logger.info(`Resuming with existing account: ${n}`)):(c=await this.createAccount(t?.initialBalance),a.createdResources=a.createdResources||[],a.createdResources.push(`account:${c.accountId}`))}else c=await this.createAccount(t?.initialBalance),a.createdResources=a.createdResources||[],a.createdResources.push(`account:${c.accountId}`);n&&n({stage:"preparing",message:"Created account or using existing account",progressPercent:20,details:{state:a,account:c}});const p=C(c.privateKey);e.setExistingAccount(c.accountId,c.privateKey);const l=("ed25519"===p.detectedType?o.PrivateKey.fromStringED25519(c.privateKey):o.PrivateKey.fromStringECDSA(c.privateKey)).publicKey.toString();s=new w0({network:i.network,operatorId:c.accountId,operatorPrivateKey:c.privateKey,operatorPublicKey:l,logLevel:"info",guardedRegistryBaseUrl:r}),n&&n({stage:"preparing",message:"Initialized MCP server client",progressPercent:25,details:{state:a}});let u=a.outboundTopicId,d=a.inboundTopicId,f=a.pfpTopicId,m=a.profileTopicId;if(!u||!d||!m){f&&e.setExistingProfilePicture(f);const t=await s.createMCPServer(e,60,a,e=>{n&&n({stage:e.stage,message:e.message,progressPercent:e.progressPercent||0,details:{...e.details,state:{...a,...e.details?.state}}})});u=t.outboundTopicId,d=t.inboundTopicId,f=t.pfpTopicId,m=t.profileTopicId,a.outboundTopicId=u,a.inboundTopicId=d,a.pfpTopicId=f,a.profileTopicId=m,a.createdResources||(a.createdResources=[]),f&&!a.createdResources.includes(`pfp:${f}`)&&a.createdResources.push(`pfp:${f}`),a.createdResources.includes(`inbound:${d}`)||a.createdResources.push(`inbound:${d}`),a.createdResources.includes(`outbound:${u}`)||a.createdResources.push(`outbound:${u}`),a.createdResources.includes(`profile:${m}`)||a.createdResources.push(`profile:${m}`)}a.currentStage="profile",a.completedPercentage=60,n&&n({stage:"submitting",message:"Created MCP server with topics and profile",progressPercent:60,details:{state:a,outboundTopicId:u,inboundTopicId:d,pfpTopicId:f,profileTopicId:m}})}const p=`${a.inboundTopicId}@${c.accountId}`;if("complete"!==a.currentStage||!a.createdResources?.includes(`registration:${a.inboundTopicId}`)){const e=await s.registerAgentWithGuardedRegistry(c.accountId,i.network,{progressCallback:e=>{const t=60+.4*(e.progressPercent||0);n&&n({stage:e.stage,message:e.message,progressPercent:t,details:{...e.details,outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.pfpTopicId,profileTopicId:a.profileTopicId,operatorId:p,state:e.details?.state||a}})},existingState:a});if(!e.success)return{...e,state:a};a=e.state||a}return n&&n({stage:"completed",message:"MCP server creation and registration complete",progressPercent:100,details:{outboundTopicId:a.outboundTopicId,inboundTopicId:a.inboundTopicId,pfpTopicId:a.pfpTopicId,profileTopicId:a.profileTopicId,operatorId:p,state:a}}),{success:!0,state:a,metadata:{accountId:c.accountId,privateKey:c.privateKey,operatorId:p,inboundTopicId:a.inboundTopicId,outboundTopicId:a.outboundTopicId,profileTopicId:a.profileTopicId,pfpTopicId:a.pfpTopicId}}}catch(mxe){const i=mxe,n=`Failed to create and register MCP server: ${i.message}`;return this.logger.error(n),{error:i.message,success:!1,state:t?.existingState||{currentStage:"init",completedPercentage:0,error:i.message}}}}async createRegistryTopic(e={}){const{ttl:t=86400,metadata:i,adminKey:n=!1,submitKey:r=!1,waitForConfirmation:a=!0,waitMaxAttempts:s=30,waitIntervalMs:c=4e3,progressCallback:p}=e;try{let e;if(this.keyType||await this.initializeOperator(),p&&p({stage:"preparing",message:"Preparing registry topic creation",progressPercent:10,details:{metadata:!!i}}),i){this.logger.info("Creating metadata inscription for registry"),p&&p({stage:"submitting",message:"Creating registry metadata inscription",progressPercent:30,details:{metadataName:i.name}});const t=globalThis.Buffer.from(JSON.stringify(i,null,2)),n={mode:"file",waitForConfirmation:a,waitMaxAttempts:s,waitIntervalMs:c,logging:{level:this.logger.getLevel?this.logger.getLevel():"info"}},o=await lQ({type:"buffer",buffer:t,fileName:`registry-metadata-${Date.now()}.json`,mimeType:"application/json"},{accountId:this.client.operatorAccountId.toString(),privateKey:this.operatorPrivateKey.toString(),network:this.network},n);if(!o.confirmed||!o.inscription)throw new Error("Metadata inscription was not confirmed");e=yQ(o.inscription),this.logger.info(`Metadata inscribed to topic: ${e}`)}p&&p({stage:"submitting",message:"Creating registry topic",progressPercent:60,details:{metadataTopicId:e}});const l=`hcs-10:0:${t}:3${e?`:${e}`:""}`,u="ecdsa"===this.keyType?o.PrivateKey.fromStringECDSA(this.operatorPrivateKey):o.PrivateKey.fromStringED25519(this.operatorPrivateKey);let d=(new o.TopicCreateTransaction).setTopicMemo(l);n&&(d=d.setAdminKey(u.publicKey)),r&&(d=d.setSubmitKey(u.publicKey));const f=await d.execute(this.client),m=await f.getReceipt(this.client),h=m.topicId?.toString();if(!h)throw new Error("Failed to create registry topic");return p&&p({stage:"completed",message:"Registry topic created successfully",progressPercent:100,details:{topicId:h,metadataTopicId:e,transactionId:f.transactionId.toString()}}),this.logger.info(`Registry topic created successfully: ${h}`),{success:!0,topicId:h,transactionId:f.transactionId.toString(),metadataTopicId:e}}catch(l){const e=l instanceof Error?l.message:"Unknown error";return p&&p({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}}}}class k0{constructor(e){this.registry=e?.registry??o0,this.issuers=new r0,this.registerHederaIssuer(),this.registerHederaResolver(),this.client=e?.client,this.network=e?.network,this.operatorId=e?.operatorId,!this.client&&e?.network&&e?.operatorId&&e?.privateKey&&this.configureHederaClient(e.network,e.operatorId,e.privateKey),e?.privateKey&&(this.operatorPrivateKey=e.privateKey),e?.hcs10Client&&(this.hcs10Client=e.hcs10Client)}configureHederaClient(e,t,i){const n=o.Client.forName(e),r=C(i);n.setOperator(t,r.privateKey),(async()=>{try{const a=new I(e),s=await a.requestAccount(t),c=s?.key?._type||"",p=c.includes("ECDSA"),l=c.includes("ED25519");p&&"ecdsa"!==r.detectedType?n.setOperator(t,o.PrivateKey.fromStringECDSA(i)):l&&"ed25519"!==r.detectedType&&n.setOperator(t,o.PrivateKey.fromStringED25519(i))}catch{}})(),this.client=n,this.network=e,this.operatorId=t,this.operatorPrivateKey=i}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 s0)}async createDid(e){return this.issuers.issue(e)}canonicalizeAgentData(e){return GQ(e)}createUaid(e,t,i){return"string"==typeof e?e0(e,t):e0(e,t,i)}parseHcs14Did(e){return t0(e)}isHederaNetwork(e){return UQ(e)}isHederaCaip10(e){return MQ(e)}toHederaCaip10(e,t){return DQ(e,t)}parseHederaCaip10(e){return zQ(e)}isEip155Caip10(e){return qQ(e)}toEip155Caip10(e,t){return KQ(e,t)}getResolverRegistry(){return this.registry}registerHederaResolver(){this.registry.register(new i0)}async createDidWithUaid(e){const t=await this.createDid(e.issue);let i=e.uid;const n=e.proto;let o=e.nativeId;if("hedera"===e.issue.method){if(!o){if(!this.network||!this.operatorId)throw new Error("nativeId not provided and network/operatorId are not configured");o=DQ(this.network,this.operatorId)}if(!i&&"hcs-10"===n&&this.network&&this.operatorId)try{if(!this.hcs10Client&&this.operatorPrivateKey&&(this.hcs10Client=new w0({network:this.network,operatorId:this.operatorId,operatorPrivateKey:this.operatorPrivateKey,silent:!0})),this.hcs10Client)i=await this.hcs10Client.getOperatorId();else{const e=new L0({network:this.network,auth:{operatorId:this.operatorId},silent:!0}),t=await e.fetchProfileByAccountId(this.operatorId,this.network),n=t?.topicInfo?.inboundTopic;i=n?`${n}@${this.operatorId}`:this.operatorId}}catch{i=this.operatorId}}i=i??"0";const r=this.createUaid(t,{uid:i,proto:n,nativeId:o});return{did:t,uaid:r,parsed:t0(r)}}}const _0=n.z.object({platform:n.z.string().min(1),handle:n.z.string().min(1)}),E0=n.z.object({type:n.z.nativeEnum(f0),capabilities:n.z.array(n.z.nativeEnum(h0)).min(1),model:n.z.string().min(1),creator:n.z.string().optional()}),S0=n.z.object({url:n.z.string().min(1),transport:n.z.enum(["stdio","sse"])}),T0=n.z.object({type:n.z.nativeEnum(y0),value:n.z.string(),dns_field:n.z.string().optional(),challenge_path:n.z.string().optional()}),A0=n.z.object({minVersion:n.z.string().optional()}),I0=n.z.object({name:n.z.string().min(1),description:n.z.string().min(1)}),R0=n.z.object({name:n.z.string().min(1),description:n.z.string().min(1)}),O0=n.z.object({version:n.z.string().min(1),connectionInfo:S0,services:n.z.array(n.z.nativeEnum(g0)).min(1),description:n.z.string().min(1),verification:T0.optional(),host:A0.optional(),capabilities:n.z.array(n.z.string()).optional(),resources:n.z.array(I0).optional(),tools:n.z.array(R0).optional(),maintainer:n.z.string().optional(),repository:n.z.string().optional(),docs:n.z.string().optional()}),j0=n.z.object({version:n.z.string().min(1),type:n.z.nativeEnum(d0),display_name:n.z.string().min(1),alias:n.z.string().optional(),bio:n.z.string().optional(),socials:n.z.array(_0).optional(),profileImage:n.z.string().optional(),uaid:n.z.string().optional(),properties:n.z.record(n.z.any()).optional(),inboundTopicId:n.z.string().optional(),outboundTopicId:n.z.string().optional()}),C0=j0.extend({type:n.z.literal(d0.PERSONAL),language:n.z.string().optional(),timezone:n.z.string().optional()}),N0=j0.extend({type:n.z.literal(d0.AI_AGENT),aiAgent:E0}),B0=j0.extend({type:n.z.literal(d0.MCP_SERVER),mcpServer:O0}),P0=n.z.union([C0,N0,B0]);class L0{constructor(e){if(this.client="mainnet"===e.network?o.Client.forMainnet():o.Client.forTestnet(),this.auth=e.auth,this.network=e.network,this.operatorId=e.auth.operatorId,this.logger=y.getInstance({level:e.logLevel||"info",module:"HCS-11",silent:e.silent}),this.mirrorNode=new I(this.network,this.logger),this.auth.privateKey)if(e.keyType)this.keyType=e.keyType,this.initializeOperatorWithKeyType();else{try{const e=C(this.auth.privateKey);this.keyType=e.detectedType,e.warning&&this.logger.warn(e.warning),this.client.setOperator(this.operatorId,e.privateKey)}catch(t){this.logger.warn("Failed to detect key type from private key format, will query mirror node"),this.keyType="ecdsa"}this.initializeOperator()}}getClient(){return this.client}getOperatorId(){return this.auth.operatorId}async initializeOperator(){const e=await this.mirrorNode.requestAccount(this.operatorId),t=e?.key?._type;t&&t.includes("ECDSA")?this.keyType="ecdsa":t&&t.includes("ED25519")?this.keyType="ed25519":this.keyType="ecdsa",this.initializeOperatorWithKeyType()}initializeOperatorWithKeyType(){if(!this.auth.privateKey)return;const e="ecdsa"===this.keyType?o.PrivateKey.fromStringECDSA(this.auth.privateKey):o.PrivateKey.fromStringED25519(this.auth.privateKey);this.client.setOperator(this.operatorId,e)}createPersonalProfile(e,t){return{version:"1.0",type:d0.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}}createAIAgentProfile(e,t,i,n,o){const r=this.validateProfile({version:"1.0",type:d0.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,aiAgent:{type:t,capabilities:i,model:n,creator:o?.creator}});if(!r.valid)throw new Error(`Invalid AI Agent Profile: ${r.errors.join(", ")}`);return{version:"1.0",type:d0.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,aiAgent:{type:t,capabilities:i,model:n,creator:o?.creator}}}createMCPServerProfile(e,t,i){const n=this.validateProfile({version:"1.0",type:d0.MCP_SERVER,display_name:e,alias:i?.alias,bio:i?.bio,socials:i?.socials,profileImage:i?.profileImage,properties:i?.properties,inboundTopicId:i?.inboundTopicId,outboundTopicId:i?.outboundTopicId,mcpServer:t});if(!n.valid)throw new Error(`Invalid MCP Server Profile: ${n.errors.join(", ")}`);return{version:"1.0",type:d0.MCP_SERVER,display_name:e,alias:i?.alias,bio:i?.bio,socials:i?.socials,profileImage:i?.profileImage,properties:i?.properties,inboundTopicId:i?.inboundTopicId,outboundTopicId:i?.outboundTopicId,mcpServer:t}}validateProfile(e){const t=P0.safeParse(e);if(t.success)return{valid:!0,errors:[]};return{valid:!1,errors:t.error.errors.map(e=>{const t=e.path.join(".");let i=e.message;if("invalid_type"===e.code)i=`Expected ${e.expected}, got ${e.received}`;else if("invalid_enum_value"===e.code){const t=e.options?.join(", ");i=`Invalid value. Valid options are: ${t}`}else"too_small"===e.code&&"string"===e.type&&(i="Cannot be empty");return`${t}: ${i}`})}}profileToJSONString(e){return JSON.stringify(e)}parseProfileFromString(e){try{const t=JSON.parse(e),i=this.validateProfile(t);return i.valid?t:(this.logger.error("Invalid profile format:",i.errors),null)}catch(t){return this.logger.error("Error parsing profile:"),null}}setProfileForAccountMemo(e,t=1){return`hcs-11:hcs://${t}/${e}`}async executeTransaction(e){try{if(this.auth.privateKey){const t=await e.signWithOperator(this.client),i=await t.execute(this.client),n=await i.getReceipt(this.client);return n.status.toString()!==o.Status.Success.toString()?{success:!1,error:`Transaction failed: ${n.status.toString()}`}:{success:!0,result:n}}if(!this.auth.signer)throw new Error("No valid authentication method provided");const t=this.auth.signer,i=await e.freezeWithSigner(t),n=await i.executeWithSigner(t),r=await n.getReceiptWithSigner(t);return r.status.toString()!==o.Status.Success.toString()?{success:!1,error:`Transaction failed: ${r.status.toString()}: ${o.Status.Success.toString()}`}:{success:!0,result:r}}catch(t){return{success:!1,error:t instanceof Error?t.message:"Unknown error during transaction execution"}}}async inscribeImage(e,t,i){try{const n=i?.progressCallback,r=new WY({module:"HCS11-Image",logger:this.logger,callback:n});r.preparing("Preparing to inscribe image",0);const a=h.lookup(t)||"application/octet-stream",s=i?.waitForConfirmation??!0;let c;if(this.auth.signer){if(!("accountId"in this.auth.signer))throw r.failed("Signer must be a DAppSigner for inscription"),new Error("Signer must be a DAppSigner for inscription");r.preparing("Using signer for inscription",10),c=await uQ({type:"buffer",buffer:e,fileName:t,mimeType:a},this.auth.signer,{network:this.network,waitForConfirmation:s,waitMaxAttempts:150,waitIntervalMs:4e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);r.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}else{if(!this.auth.privateKey)throw r.failed("Private key is required for inscription"),this.logger.error("Private key is required for inscription"),new Error("Private key is required for inscription");r.preparing("Using private key for inscription",10);const i="ecdsa"===this.keyType?o.PrivateKey.fromStringECDSA(this.auth.privateKey):o.PrivateKey.fromStringED25519(this.auth.privateKey);c=await lQ({type:"buffer",buffer:e,fileName:t,mimeType:a},{accountId:this.auth.operatorId,privateKey:i,network:this.network},{waitForConfirmation:s,waitMaxAttempts:150,waitIntervalMs:2e3,logging:{level:"debug"},progressCallback:e=>{const t=10+.8*(e.progressPercent||0);r.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}})}if(c.confirmed)return r.completed("Image inscription completed",{topicId:yQ(c.inscription)}),{imageTopicId:yQ(c.inscription)||"",transactionId:c.result.jobId,success:!0};{const e=c.quote?"quote-only":c.result.jobId;return r.verifying("Waiting for inscription confirmation",50,{jobId:e}),{imageTopicId:"",transactionId:e,success:!1,error:"Inscription not confirmed"}}}catch(n){return this.logger.error("Error inscribing image:",n),{imageTopicId:"",transactionId:"",success:!1,error:n instanceof Error?n.message:"Error inscribing image"}}}async inscribeProfile(e,t){this.logger.info("Inscribing HCS-11 profile");const i=t?.progressCallback,n=new WY({module:"HCS11-Profile",logger:this.logger,callback:i});await this.attachUaidIfMissing(e),n.preparing("Validating profile data",5);const r=this.validateProfile(e);if(!r.valid)return n.failed(`Invalid profile: ${r.errors.join(", ")}`),{profileTopicId:"",transactionId:"",success:!1,error:`Invalid profile: ${r.errors.join(", ")}`};n.preparing("Formatting profile for inscription",15);const a=this.profileToJSONString(e),s=`profile-${e.display_name.toLowerCase().replace(/\s+/g,"-")}.json`;try{const e=globalThis.Buffer.from(a,"utf-8"),t="application/json";n.preparing("Preparing profile for inscription",20);const i={type:"buffer",buffer:e,fileName:s,mimeType:t},r={waitForConfirmation:!0,mode:"file",network:this.network,waitMaxAttempts:100,waitIntervalMs:2e3,progressCallback:e=>{const t=20+.75*Number(e?.progressPercent||0);n?.report({stage:e.stage,message:e.message,progressPercent:t,details:e.details})}};let c;if(n.submitting("Submitting profile to Hedera network",30),this.auth.privateKey){const e="ecdsa"===this.keyType?o.PrivateKey.fromStringECDSA(this.auth.privateKey):o.PrivateKey.fromStringED25519(this.auth.privateKey);c=await lQ(i,{accountId:this.auth.operatorId,privateKey:e,network:this.network},r)}else{if(!this.auth.signer)throw new Error("No authentication method available - neither private key nor signer");c=await uQ(i,this.auth.signer,r)}if(!c.confirmed||!yQ(c.inscription))return n.failed("Failed to inscribe profile content"),{profileTopicId:"",transactionId:"",success:!1,error:"Failed to inscribe profile content"};const p=yQ(c.inscription);return n.completed("Profile inscription completed",{topicId:p,transactionId:c.result.transactionId}),{profileTopicId:p,transactionId:c.result.transactionId,success:!0}}catch(c){return n.failed(`Error inscribing profile: ${c.message||"Unknown error"}`),{profileTopicId:"",transactionId:"",success:!1,error:c.message||"Unknown error during inscription"}}}async attachUaidIfMissing(e){if(!e.uaid&&UQ(this.network))try{const t=new k0({client:this.client}),i=await t.createDid({method:"hedera",client:this.client}),n=DQ(this.network,this.auth.operatorId);let o=this.auth.operatorId;const r=e.inboundTopicId;if(r&&r.trim().length>0)o=`${r}@${this.auth.operatorId}`;else try{const e=await this.fetchProfileByAccountId(this.auth.operatorId,this.network),t=e?.topicInfo?.inboundTopic;t&&t.trim().length>0&&(o=`${t}@${this.auth.operatorId}`)}catch{}const a=t.createUaid(i,{proto:"hcs-10",nativeId:n,uid:o});e.uaid=a}catch{this.logger.warn("Hiero registrar not available; skipping UAID generation for profile")}}async updateAccountMemoWithProfile(e,t){try{this.logger.info(`Updating account memo for ${e} with profile ${t}`);const i=this.setProfileForAccountMemo(t),n=(new o.AccountUpdateTransaction).setAccountMemo(i).setAccountId(e);return this.executeTransaction(n)}catch(i){return this.logger.error(`Error updating account memo: ${i instanceof Error?i.message:"Unknown error"}`),{success:!1,error:i instanceof Error?i.message:"Unknown error updating account memo"}}}async createAndInscribeProfile(e,t=!0,i){const n=i?.progressCallback,o=new WY({module:"HCS11-ProfileCreation",logger:this.logger,callback:n});o.preparing("Starting profile creation process",0);const r=o.createSubProgress({minPercent:0,maxPercent:80,logPrefix:"Inscription"}),a=await this.inscribeProfile(e,{...i,progressCallback:e=>{r.report({stage:e.stage,message:e.message,progressPercent:e.progressPercent,details:e.details})}});if(!a?.success)return o.failed("Profile inscription failed",{error:a?.error}),a;if(o.confirming("Profile inscribed, updating account memo",85),t){const e=await this.updateAccountMemoWithProfile(this.auth.operatorId,a.profileTopicId);if(!e.success)return o.failed("Failed to update account memo",{error:e?.error}),{...a,success:!1,error:e?.error}}return o.completed("Profile creation completed successfully",{profileTopicId:a.profileTopicId,transactionId:a.transactionId}),a}async getCapabilitiesFromTags(e){const t=[];if(0===e.length)return[h0.TEXT_GENERATION];for(const i of e){const e=b0[i.toLowerCase()];void 0===e||t.includes(e)||t.push(e)}return 0===t.length&&t.push(h0.TEXT_GENERATION),t}getAgentTypeFromMetadata(e){return"autonomous"===e.type?f0.AUTONOMOUS:f0.MANUAL}async fetchProfileByAccountId(e,t){try{this.logger.debug(`Fetching profile for account ${e.toString()} on ${this.network}`);const n=await this.mirrorNode.getAccountMemo(e.toString());if(this.logger.debug(`Got account memo: ${n}`),!n?.startsWith("hcs-11:"))return{success:!1,error:`Account ${e.toString()} does not have a valid HCS-11 memo. Current memo: ${n||"empty"}`};this.logger.debug(`Found HCS-11 memo: ${n}`);const o=n.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(),i=P0.safeParse(t);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 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 i=await t.json(),n=P0.safeParse(i);return n.success?{success:!0,profile:n.data,topicInfo:{inboundTopic:n.data.inboundTopicId||"",outboundTopic:n.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[n,r,a]=e,s=t||this.network||"mainnet";this.logger.debug(`Retrieving profile from Kiloscribe CDN: ${a}`);const c=`https://kiloscribe.com/api/inscription-cdn/${a}?network=${s}`;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 ${a}`};const i=P0.safeParse(t);return i.success?{success:!0,profile:i.data,topicInfo:{inboundTopic:i.data.inboundTopicId||"",outboundTopic:i.data.outboundTopicId||"",profileTopicId:a}}:{success:!1,error:`Invalid HCS-11 profile data for topic ${a}`}}catch(i){return this.logger.error(`Error retrieving from Kiloscribe CDN: ${i.message}`),{success:!1,error:`Error retrieving from Kiloscribe CDN: ${i.message}`}}}}catch(n){return this.logger.error(`Error fetching profile: ${n.message}`),{success:!1,error:`Error fetching profile: ${n.message}`}}}}class U0{async checkRegistrationStatus(e,t,i,n){try{const o=await fetch(`${i}/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 n&&n.error(e),new Error(e)}return await o.json()}catch(o){throw n&&n.error(`Error checking registration status: ${o.message}`),o}}async waitForRegistrationConfirmation(e,t,i,n=60,o=2e3,r){let a=0;for(;a<n;){r&&r.info(`Checking registration status. Attempt ${a+1}/${n}`);const s=await this.checkRegistrationStatus(e,t,i,r);if("success"===s.status)return r&&r.info("Registration confirmed successfully"),!0;if("failed"===s.status)throw r&&r.error("Registration confirmation failed"),new Error("Registration confirmation failed");r&&r.info(`Registration still pending. Waiting ${o}ms before next attempt`),await new Promise(e=>setTimeout(e,o)),a++}return r&&r.warn(`Registration not confirmed after ${n} attempts`),!1}async executeRegistration(e,t="mainnet",i="https://moonscape.tech",n){try{n&&n.info("Registering agent with guarded registry");try{const i=new L0({network:t,auth:{operatorId:"0.0.0"}});n?.info(`Fetching profile by account ID ${e} on ${t}`),await v(5e3);const o=await i.fetchProfileByAccountId(e,t);if(n?.info("Profile fetched",o),o?.error)return n?.error("Error fetching profile",o.error),{error:o.error,success:!1};if(!o?.success||!o?.profile)return n&&n.error("Profile not found for agent registration"),{error:"Profile not found for the provided account ID",success:!1};if(!o.profile.inboundTopicId)return n&&n.error("Missing inbound topic ID in profile"),{error:"Profile is missing required inbound topic ID",success:!1};if(!o.profile.outboundTopicId)return n&&n.error("Missing outbound topic ID in profile"),{error:"Profile is missing required outbound topic ID",success:!1};n&&n.info(`Profile validation successful. Inbound topic: ${o.profile.inboundTopicId}, Outbound topic: ${o.profile.outboundTopicId}`)}catch(o){return n&&n.error(`Error validating profile: ${o.message}`),{error:`Error validating profile: ${o.message}`,success:!1}}const r=await fetch(`${i}/api/request-register`,{method:"POST",headers:{"Content-Type":"application/json",Accept:"*/*","Accept-Language":"en;q=0.5",Origin:i,Referer:`${i}/`,"X-Network":t},body:JSON.stringify({accountId:e})}),a=await r.json();return r.ok?(n&&n.info(`Created new registration request. Transaction ID: ${a.transaction_id}`),{transactionId:a.transaction_id,transaction:a.transaction,success:!0}):a.details?.length>0?{validationErrors:a.details,error:a.error||"Validation failed",success:!1}:{error:a.error||"Failed to register agent",success:!1}}catch(r){return{error:`Error during registration request: ${r.message}`,success:!1}}}async findRegistrations(e={},t="https://moonscape.tech"){try{const i=new URLSearchParams;e.tags?.forEach(e=>i.append("tags",e.toString())),e.accountId&&i.append("accountId",e.accountId),e.network&&i.append("network",e.network);const n=await fetch(`${t}/api/registrations?${i}`,{headers:{Accept:"*/*","Accept-Language":"en;q=0.5",Origin:t,Referer:`${t}/`}});if(!n.ok){return{registrations:[],error:await n.text()||"Failed to fetch registrations",success:!1}}const o=await n.json();return o.error?{registrations:[],error:o.error,success:!1}:{registrations:o.registrations||[],success:!0}}catch(mxe){return{registrations:[],error:`Error fetching registrations: ${mxe.message}`,success:!1}}}}var F0=(e=>(e.INBOUND="inbound",e.OUTBOUND="outbound",e.CONNECTION="connection",e.REGISTRY="registry",e))(F0||{});class M0 extends U0{constructor(e){super(),this.network=e.network,this.logger=y.getInstance({level:e.logLevel||"info",module:"HCS10-BaseClient",prettyPrint:e.prettyPrint,silent:e.silent}),this.mirrorNode=new I(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 i=await this.mirrorNode.getTopicMessages(e,t),n=["message","close_connection","transaction"];return{messages:i.filter(e=>{if("hcs-10"!==e.p||!n.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(i){return this.logger&&this.logger.error(`Error fetching messages: ${i.message}`),{messages:[]}}}async getPublicTopicInfo(e){try{return await this.mirrorNode.getTopicInfo(e)}catch(t){return this.logger.error(`Error getting public topic info for ${e}:`,t),null}}async canSubmitToTopic(e,t){try{const n=await this.mirrorNode.getTopicInfo(e);if(!n)return{canSubmit:!1,requiresFee:!1,reason:"Topic does not exist"};if(!n.submit_key?.key)return{canSubmit:!0,requiresFee:!1};try{const e=await this.mirrorNode.getPublicKey(t);if("ProtobufEncoded"===n.submit_key._type){const t=globalThis.Buffer.from(n.submit_key.key,"hex");if(await this.mirrorNode.checkKeyListAccess(t,e))return{canSubmit:!0,requiresFee:!1}}else{const t=o.PublicKey.fromString(n.submit_key.key);if(e.toString()===t.toString())return{canSubmit:!0,requiresFee:!1}}}catch(i){this.logger.error(`Key validation error: ${i instanceof Error?i.message:String(i)}`)}return n.fee_schedule_key?.key&&n.custom_fees?.fixed_fees?.length>0?{canSubmit:!0,requiresFee:!0,reason:"Requires fee payment via HIP-991"}:{canSubmit:!1,requiresFee:!1,reason:"User does not have submit permission for this topic"}}catch(i){const e=i instanceof Error?i.message:String(i);return this.logger.error(`Topic submission validation error: ${e}`),{canSubmit:!1,requiresFee:!1,reason:`Error: ${e}`}}}async getMessages(e,t){try{const i=await this.mirrorNode.getTopicMessages(e,t);return{messages:i.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(i){return this.logger&&this.logger.error(`Error fetching messages: ${i.message}`),{messages:[]}}}async requestAccount(e){try{if(!e)throw new Error("Account ID is required");return await this.mirrorNode.requestAccount(e)}catch(mxe){throw this.logger.error("Failed to fetch account",mxe),mxe}}async getAccountMemo(e){return await this.mirrorNode.getAccountMemo(e)}async retrieveProfile(e,t,i){const n=i?.maxRetries??0,o=i?.retryDelay??3e3;let r=0;for(;r<=n;){this.logger.debug(`Retrieving profile for account: ${e}${r>0?` (attempt ${r+1}/${n+1})`:""}`);const i=`${e}-${this.network}`;if(!t&&0===r){const t=D0.getInstance().get(i);if(t)return this.logger.debug(`Cache hit for profile: ${e}`),t}try{const t=new L0({network:this.network,auth:{operatorId:"0.0.0"},logLevel:this.logger.getLevel()}),a=await t.fetchProfileByAccountId(e,this.network);if(!a?.success){if(r<n){this.logger.info(`Profile not found for account ${e}, retrying in ${o}ms... (${a?.error})`),r++,await new Promise(e=>setTimeout(e,o));continue}return this.logger.error(`Failed to retrieve profile for account ID: ${e}`,a?.error),{profile:null,success:!1,error:a?.error||`Failed to retrieve profile for account ID: ${e}`}}const s=a?.profile;let c=null;a?.topicInfo?.inboundTopic&&a?.topicInfo?.outboundTopic&&a?.topicInfo?.profileTopicId&&(c={inboundTopic:a.topicInfo.inboundTopic,outboundTopic:a.topicInfo.outboundTopic,profileTopicId:a.topicInfo.profileTopicId});const p={profile:s,topicInfo:c,success:!0};return D0.getInstance().set(i,p),p}catch(mxe){if(r<n){this.logger.info(`Error retrieving profile for account ${e}, retrying in ${o}ms... (${mxe.message})`),r++,await new Promise(e=>setTimeout(e,o));continue}const i=`Failed to retrieve profile: ${mxe.message}`;return this.logger.error(i),{profile:null,success:!1,error:i}}}return{profile:null,success:!1,error:"Unexpected error in profile retrieval"}}async retrieveOutboundConnectTopic(e){return await this.retrieveCommunicationTopics(e,!0)}async retrieveCommunicationTopics(e,t,i){try{const n=await this.retrieveProfile(e,t,i);if(!n?.success)throw new Error(n.error||"Failed to retrieve profile");const o=n.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(!n.topicInfo)throw new Error(`TopicInfo is missing in the profile for account ${e}`);return n.topicInfo}catch(mxe){const t=mxe,i=`Failed to retrieve topic info: ${t.message}`;throw this.logger.error(i),t}}async retrieveOutboundMessages(e,t){try{const i=await this.retrieveCommunicationTopics(e);if(!i)return this.logger.warn(`No outbound connect topic found for agentAccountId: ${e}`),[];return(await this.getMessages(i.outboundTopic,t)).messages.filter(e=>"hcs-10"===e.p&&("connection_request"===e.op||"connection_created"===e.op||"message"===e.op))}catch(mxe){const t=`Failed to retrieve outbound messages: ${mxe.message}`;return this.logger.error(t),[]}}async hasConnectionCreated(e,t){try{const i=await this.retrieveCommunicationTopics(e);return(await this.retrieveOutboundMessages(i.outboundTopic)).some(e=>"connection_created"===e.op&&e.connection_id===t)}catch(mxe){const t=`Failed to check connection created: ${mxe.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 i=new _Q(this.logger.getLevel());if(!i.isValidHRL(e))return e;return(await i.resolveHRL(e,{network:this.network,returnRaw:t})).content}catch(mxe){const t=`Error resolving HRL reference: ${mxe.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 i=new _Q(this.logger.getLevel());return await i.getContentWithType(e,{network:this.network,returnRaw:t})}catch(mxe){const t=`Error resolving HRL reference with type: ${mxe.message}`;throw this.logger.error(t),new Error(t)}}async submitConnectionRequest(e,t){const i=this.getAccountAndSigner();if(!i?.accountId)throw new Error("Operator account ID is not set");const n=await this.getOperatorId(),o=i.accountId,r=await this.canSubmitToTopic(e,o);if(!r?.canSubmit)throw new Error(`Cannot submit to topic: ${r.reason}`);const a=await this.retrieveInboundAccountId(e);if(!a)throw new Error("Failed to retrieve topic info account ID");const s={p:"hcs-10",op:"connection_request",operator_id:n,m:t},c=r.requiresFee,p=await this.submitPayload(e,s,void 0,c);this.logger.info(`Submitted connection request to topic ID: ${e}`);const l=await this.retrieveCommunicationTopics(o);if(!l)throw new Error("Failed to retrieve outbound topic");const u=p.topicSequenceNumber?.toNumber();if(!u)throw new Error("Failed to get response sequence number");const d=`${e}@${a}`;return await this.submitPayload(l.outboundTopic,{...s,outbound_topic_id:l.outboundTopic,connection_request_id:u,operator_id:d}),p}async recordOutboundConnectionConfirmation({outboundTopicId:e,requestorOutboundTopicId:t,connectionRequestId:i,confirmedRequestId:n,connectionTopicId:o,operatorId:r,memo:a}){const s={p:"hcs-10",op:"connection_created",connection_topic_id:o,outbound_topic_id:e,requestor_outbound_topic_id:t,confirmed_request_id:n,connection_request_id:i,operator_id:r,m:a};return await this.submitPayload(e,s)}async waitForConnectionConfirmation(e,t,i=60,n=2e3,o=!0){this.logger.info(`Waiting for connection confirmation on inbound topic ${e} for request ID ${t}`);for(let r=0;r<i;r++){this.logger.info(`Attempt ${r+1}/${i} to find connection confirmation`);const a=(await this.mirrorNode.getTopicMessages(e,{order:"desc",limit:100})).filter(e=>"connection_created"===e.op);if(this.logger.info(`Found ${a.length} connection_created messages`),a.length>0)for(const e of a)if(Number(e.connection_id)===Number(t)){const i={connectionTopicId:e.connection_topic_id,sequence_number:Number(e.sequence_number),confirmedBy:e.operator_id,memo:e.m},n=this.extractAccountFromOperatorId(i.confirmedBy),r=this.getAccountAndSigner(),a=await this.retrieveCommunicationTopics(n),s=await this.retrieveCommunicationTopics(r.accountId);return this.logger.info("Connection confirmation found",i),o&&await this.recordOutboundConnectionConfirmation({requestorOutboundTopicId:a.outboundTopic,outboundTopicId:s.outboundTopic,connectionRequestId:t,confirmedRequestId:i.sequence_number,connectionTopicId:i.connectionTopicId,operatorId:i.confirmedBy,memo:i.memo||"Connection confirmed"}),i}r<i-1&&(this.logger.info(`No matching confirmation found, waiting ${n}ms before retrying...`),await new Promise(e=>setTimeout(e,n)))}throw new Error(`Connection confirmation not found after ${i} 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 i=await this.retrieveProfile(t.accountId);if(!i?.success)throw new Error("Failed to retrieve profile");if(!i?.topicInfo?.inboundTopic)throw new Error("Failed to retrieve inbound topic");const n=`${i.topicInfo?.inboundTopic}@${t.accountId}`;return this.operatorId=n,n}async retrieveInboundAccountId(e){const t=await this.mirrorNode.getTopicInfo(e);if(!t?.memo)throw new Error("Failed to retrieve topic info");const i=t.memo.toString().split(":"),n=i?.[4];if(!n)throw new Error("Failed to retrieve topic info account ID");return n}clearCache(){D0.getInstance().clear()}_generateHcs10Memo(e,t){const i=t.ttl??60;switch(e){case"inbound":if(!t.accountId)throw new Error("accountId is required for inbound memo");return`hcs-10:0:${i}:0:${t.accountId}`;case"outbound":return`hcs-10:0:${i}: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:${i}: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 i=t.memo.toString();if(!i.startsWith("hcs-10:"))return this.logger.debug(`Topic ${e} is not an HCS-10 topic`),null;const n=i.split(":");if(n.length<4)return this.logger.warn(`Invalid HCS-10 memo format for topic ${e}: ${i}`),null;const o=n[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,i){try{const n=await fetch(`${i}/api/request-confirm`,{method:"POST",headers:{"Content-Type":"application/json","X-Network":t},body:JSON.stringify({transaction_id:e})});if(!n.ok)throw new Error(`Failed to confirm registration: ${n.statusText}`);return await n.json()}catch(mxe){const t=mxe,i=`Error checking registration status: ${t.message}`;throw this.logger.error(i),t}}isValidOperatorId(e){if(!e)return!1;const t=e.split("@");if(2!==t.length)return!1;const i=t[0],n=t[1];if(!i)return!1;if(!n)return!1;const o=/^[0-9]+\.[0-9]+\.[0-9]+$/;return!!o.test(n)&&!!o.test(i)}async getTransactionRequests(e,t){this.logger.debug(`Retrieving transaction requests from topic ${e}`);const{messages:i}=await this.getMessageStream(e,{limit:t?.limit,sequenceNumber:t?.sequenceNumber,order:t?.order||"desc"}),n=i.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?n.slice(0,t.limit):n}getHcs10TransactionMemo(e){if("object"!=typeof e||!("op"in e))return null;const t=e;let i,n;switch(t.op){case"register":i="0",n="0";break;case"delete":i="1",n="0";break;case"migrate":i="2",n="0";break;case"connection_request":i="3",n=t.outbound_topic_id?"2":"1";break;case"connection_created":i="4",n=t.outbound_topic_id?"2":"1";break;case"connection_closed":i="5",n=t.outbound_topic_id?"2":"3";break;case"message":case"transaction":default:i="6",n="3";break;case"close_connection":i="5",n="3"}return`hcs-10:op:${i}:${n}`}}class D0{constructor(){this.CACHE_TTL=36e5,this.cache=new Map,this.cacheExpiry=new Map}static getInstance(){return D0.instance||(D0.instance=new D0),D0.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()}}const z0="undefined"!=typeof window;function $0(e,t){return`hcs-10:op:${e}:${t}`}var q0=(e=>(e[e.ACTION=0]="ACTION",e[e.ASSEMBLY=2]="ASSEMBLY",e[e.HASHLINKS=3]="HASHLINKS",e))(q0||{});class K0{constructor(e,t,i,n,o){this.entries=new Map,this.networkType=e,this.logger=t,this.registryType=i,this.topicId=n,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 i=t[0];let n;if(i.raw_content)n=JSON.parse(i.raw_content);else{const e=i;if("hcs-12"!==e.p||!e.op)return null;n={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(n).forEach(e=>{void 0===n[e]&&delete n[e]})}return{id:i.sequence_number.toString(),sequenceNumber:i.sequence_number,timestamp:i.consensus_timestamp||(new Date).toISOString(),submitter:i.payer||"unknown",data:n}}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:q0[this.registryType],lastSync:this.lastSyncTimestamp});try{const t=await this.client.mirrorNode.getTopicMessagesByFilter(this.topicId,{startTime:this.lastSyncTimestamp,order:"asc",limit:100});for(const i of t)try{let e;if(i.raw_content)e=JSON.parse(i.raw_content);else{const t=i;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:i.sequence_number.toString(),sequenceNumber:i.sequence_number,timestamp:i.consensus_timestamp||(new Date).toISOString(),submitter:i.payer||"unknown",data:e};this.entries.set(t.id,t)}catch(e){this.logger.warn("Failed to parse registry message",{sequenceNumber:i.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,i){if(!this.client)throw new Error("Client required for inscription");const n="string"==typeof e?globalThis.Buffer.from(e):e;let o;if(this.logger.info("Inscribing content via HCS-1",{size:n.length,mimeType:t,registryType:q0[this.registryType]}),"getOperatorAccountId"in this.client)o=await lQ({type:"buffer",buffer:n,fileName:"application/octet-stream"===t&&"wasm"===i?.fileType?`${i?.name||"content"}.wasm`:i?.name||"content",mimeType:t},{accountId:this.client.getOperatorAccountId(),privateKey:this.client.getOperatorPrivateKey(),network:this.networkType},{mode:"file",metadata:i,waitForConfirmation:!0});else{const{accountId:e,signer:r}=await this.client.getAccountAndSigner();o=await uQ({type:"buffer",buffer:n,fileName:"application/octet-stream"===t&&"wasm"===i?.fileType?`${i?.name||"content"}.wasm`:i?.name||"content",mimeType:t},r,{mode:"file",metadata:i,waitForConfirmation:!0})}if(!o.confirmed)throw new Error("Failed to inscribe content");const r=o.inscription.topic_id;if(!r)throw new Error("No topic ID in inscription response");return this.logger.info("Content inscribed successfully",{topicId:r}),r}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:q0[this.registryType]})}getStats(){return{entryCount:this.entries.size,lastSync:this.lastSyncTimestamp,topicId:this.topicId,registryType:q0[this.registryType]}}}const W0=n.z.object({p:n.z.literal("hcs-12")}),H0=n.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid Hedera address format"),V0=n.z.string().regex(/^[a-f0-9]{64}$/,"Invalid SHA-256 hash format"),G0=n.z.object({format:n.z.enum(["tar.gz","zip","car"]),root_manifest:n.z.string(),includes_lockfile:n.z.boolean(),workspace_members:n.z.array(n.z.string()).optional()}),Z0=n.z.object({source_t_id:H0,source_hash:V0,compiler_version:n.z.string(),cargo_version:n.z.string(),target:n.z.literal("wasm32-unknown-unknown"),profile:n.z.string(),build_flags:n.z.array(n.z.string()),lockfile_hash:V0,source_structure:G0}),J0=n.z.lazy(()=>n.z.object({type:n.z.string().optional(),required:n.z.array(n.z.string()).optional(),properties:n.z.record(J0).optional(),pattern:n.z.string().optional(),minimum:n.z.number().optional(),maximum:n.z.number().optional(),regex:n.z.string().optional(),min:n.z.number().optional(),max:n.z.number().optional(),length:n.z.number().optional(),email:n.z.boolean().optional(),url:n.z.boolean().optional(),uuid:n.z.boolean().optional(),cuid:n.z.boolean().optional(),cuid2:n.z.boolean().optional(),ulid:n.z.boolean().optional(),datetime:n.z.boolean().optional(),ip:n.z.boolean().optional(),startsWith:n.z.string().optional(),endsWith:n.z.string().optional(),includes:n.z.string().optional(),gt:n.z.number().optional(),gte:n.z.number().optional(),lt:n.z.number().optional(),lte:n.z.number().optional(),int:n.z.boolean().optional(),positive:n.z.boolean().optional(),nonnegative:n.z.boolean().optional(),negative:n.z.boolean().optional(),nonpositive:n.z.boolean().optional(),multipleOf:n.z.number().optional(),finite:n.z.boolean().optional(),safe:n.z.boolean().optional(),nonempty:n.z.boolean().optional(),literal:n.z.union([n.z.string(),n.z.number(),n.z.boolean()]).optional(),enum:n.z.array(n.z.string()).optional(),nullable:n.z.boolean().optional(),nullish:n.z.boolean().optional(),optional:n.z.boolean().optional(),element:n.z.any().optional(),shape:n.z.record(n.z.any()).optional(),strict:n.z.boolean().optional(),passthrough:n.z.boolean().optional(),catchall:n.z.any().optional()})),Y0=n.z.object({p:n.z.literal("hcs-12"),op:n.z.literal("register"),t_id:H0,hash:V0,wasm_hash:V0,js_t_id:H0.optional(),js_hash:V0.optional(),interface_version:n.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid version format").optional(),info_t_id:H0.optional(),source_verification:Z0.optional(),previous_version:n.z.string().optional(),migration_notes:n.z.string().optional(),validation_rules:n.z.record(J0).optional(),m:n.z.string().optional()}),X0=n.z.object({p:n.z.literal("hcs-12"),op:n.z.enum(["register","template"]),name:n.z.string(),version:n.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid semver format"),data:n.z.union([n.z.any(),n.z.string()]).optional(),t_id:H0.optional()});n.z.enum(["register","add-action","add-block","update"]);const Q0=W0.extend({op:n.z.literal("register"),name:n.z.string(),version:n.z.string().regex(/^\d+\.\d+\.\d+$/,"Invalid semver format"),description:n.z.string().optional(),tags:n.z.array(n.z.string()).optional(),author:n.z.string().optional()}),e1=W0.extend({op:n.z.literal("add-action"),t_id:H0,alias:n.z.string(),config:n.z.any().optional(),data:H0.optional()}),t1=W0.extend({op:n.z.literal("add-block"),block_t_id:H0,actions:n.z.record(n.z.string(),H0).optional(),attributes:n.z.record(n.z.any()).optional(),children:n.z.array(n.z.string()).optional(),data:H0.optional()}),i1=W0.extend({op:n.z.literal("update"),description:n.z.string().optional(),tags:n.z.array(n.z.string()).optional()});n.z.object({type:n.z.enum(["vertical","horizontal","grid"]),responsive:n.z.boolean().optional(),containerClass:n.z.string().optional()}),n.z.object({source_t_id:H0,source_hash:V0,description:n.z.string().optional()});const n1=n.z.discriminatedUnion("op",[Q0,e1,t1,i1]),o1=Q0,r1=W0.extend({op:n.z.literal("register"),t_id:H0,name:n.z.string().max(100,"Name must be 100 characters or less"),description:n.z.string().max(500,"Description must be 500 characters or less").optional(),tags:n.z.array(n.z.string()).max(10,"Maximum 10 tags allowed").optional(),category:n.z.string().optional(),featured:n.z.boolean().optional(),icon:n.z.string().optional(),author:n.z.string().optional(),website:n.z.string().url().optional()});function a1(e){return Y0.parse(e)}function s1(e){return n1.parse(e)}function c1(e,t){const i=t.safeParse(e);return i.success?{isValid:!0,errors:[],data:i.data}:{isValid:!1,errors:i.error.errors.map(e=>`${e.path.join(".")}: ${e.message}`)}}class p1 extends K0{constructor(e,t,i,n){super(e,t,q0.ACTION,i,n),this.actionsByHash=new Map,this.cryptoAdapter=PQ()}async registerWithWasm(e,t,i){let n,o;if(IQ()){n=this.createSSRSafeHash(e,"wasm");const i=JSON.stringify(t);o=this.createSSRSafeHash(globalThis.Buffer.from(i),"info")}else{const i=this.cryptoAdapter.createHash("sha256").update(e).digest("hex"),r=i instanceof Promise?await i:i;n="string"==typeof r?r:r.toString("hex");const a=JSON.stringify(t),s=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(a)).digest("hex"),c=s instanceof Promise?await s:s;o="string"==typeof c?c:c.toString("hex")}const r=await this.inscribeContent(e,"application/octet-stream",{name:t.name,version:t.version,hash:n,fileType:"wasm"});let a;const s=JSON.stringify(t);globalThis.Buffer.byteLength(s,"utf8")>1024&&(a=await this.inscribeContent(s,"application/json",{name:`${t.name}-info`,version:t.version}));const c={p:"hcs-12",op:"register",t_id:r,hash:o,wasm_hash:n,info_t_id:a,source_verification:i,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 i={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(i.id,i),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,i={id:t.toString(),sequenceNumber:t,timestamp:(new Date).toISOString(),submitter:"local",data:e};return this.entries.set(i.id,i),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 i;if("getOperatorAccountId"in this.client)i=await dQ(t.info_t_id,{accountId:this.client.getOperatorAccountId(),privateKey:this.client.getOperatorPrivateKey(),network:this.networkType});else{const{accountId:e}=await this.client.getAccountAndSigner();i=await dQ(t.info_t_id,{accountId:e,network:this.networkType})}if(!i.content)return this.logger.error("No content in inscription response"),null;e="string"==typeof i.content?i.content:globalThis.Buffer.from(i.content).toString("utf8")}const i=JSON.parse(e);let n;if(IQ())n=this.createSSRSafeHash(globalThis.Buffer.from(e),"info");else{const t=this.cryptoAdapter.createHash("sha256").update(globalThis.Buffer.from(e)).digest("hex"),i=t instanceof Promise?await t:t;n="string"==typeof i?i:i.toString("hex")}if(n!==t.hash)throw this.logger.error("INFO hash mismatch",{expected:t.hash,computed:n}),new Error("Module info verification failed");return i}catch(i){return this.logger.error("Failed to fetch action INFO",{hash:e,error:i}),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 dQ(t.t_id,{accountId:this.client.getOperatorAccountId(),privateKey:this.client.getOperatorPrivateKey(),network:this.networkType});else{const{accountId:i}=await this.client.getAccountAndSigner();e=await dQ(t.t_id,{accountId:i,network:this.networkType})}if(!e.content)return this.logger.error("No content in inscription response"),null;const i="string"==typeof e.content?globalThis.Buffer.from(e.content,"base64"):globalThis.Buffer.from(e.content);let n;if(IQ())n=this.createSSRSafeHash(i,"wasm");else{const e=this.cryptoAdapter.createHash("sha256").update(i).digest("hex"),t=e instanceof Promise?await e:e;n="string"==typeof t?t:t.toString("hex")}if(n!==t.wasm_hash)throw this.logger.error("WASM hash mismatch",{expected:t.wasm_hash,computed:n}),new Error("WASM binary verification failed");return new Uint8Array(i)}catch(i){return this.logger.error("Failed to fetch WASM from HCS-1",{topicId:t.t_id,error:i}),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 i=e;for(;i;){const e=await this.getAction(i);if(!e)break;t.push(e),i=void 0}return t}validateRegistration(e){try{a1(e)}catch(t){if(t instanceof n.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 i=0;for(let n=0;n<Math.min(e.length,256);n++)i=(i<<5)-i+e[n]&4294967295;return`ssr-${t}-${e.length}-${Math.abs(i).toString(16).padStart(8,"0")}`}}class l1{constructor(e,t,i){this.blockCache=new Map,this.templateCache=new Map,this.networkType=e,this.logger=t,this.client=i}async loadBlockDefinition(e){const t=this.blockCache.get(e);if(t)return t;try{const t=new _Q,i=await t.resolve(e,{network:this.networkType});if(!i.content)throw new Error(`Block definition not found: ${e}`);let n;return n="object"!=typeof i.content||null===i.content||i.content instanceof ArrayBuffer?JSON.parse("string"==typeof i.content?i.content:i.content.toString()):i.content,this.blockCache.set(e,n),n}catch(i){throw this.logger.error("Failed to load block definition",{blockTopicId:e,error:i.message}),new Error(`Failed to load block definition: ${i.message}`)}}async loadBlockTemplate(e){const t=this.templateCache.get(e);if(t)return t;try{const t=new _Q,i=await t.resolve(e,{network:this.networkType});if(!i.content)throw new Error(`Block template not found: ${e}`);let n;return n="string"==typeof i.content?i.content:"object"==typeof i.content&&null!==i.content?i.content.text||JSON.stringify(i.content):i.content.toString(),this.templateCache.set(e,n),n}catch(i){throw this.logger.error("Failed to load block template",{templateTopicId:e,error:i.message}),new Error(`Failed to load block template: ${i.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 i=globalThis.Buffer.from(e),n=await this.client.inscribeFile(i,`block-${t.name}-template.html`);if(!n?.topic_id)throw new Error("Failed to inscribe block template");const o={...t,template_t_id:n.topic_id},r=globalThis.Buffer.from(JSON.stringify(o)),a=await this.client.inscribeFile(r,`block-${t.name}-definition.json`);if(!a?.topic_id)throw new Error("Failed to inscribe block definition");return this.blockCache.set(a.topic_id,o),this.templateCache.set(n.topic_id,e),{definitionTopicId:a.topic_id,templateTopicId:n.topic_id}}catch(i){throw this.logger.error("Failed to store block",{error:i.message}),new Error(`Failed to store block: ${i.message}`)}}clearCache(){this.blockCache.clear(),this.templateCache.clear()}}class u1 extends K0{constructor(e,t,i,n){super(e,t,q0.ASSEMBLY,i,n),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 i={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(i.id,i),await this.processMessage(i),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 i=this.assemblyStates.get(this.topicId);switch(t.op){case"register":const n=t;i={topicId:this.topicId,name:n.name,version:n.version,description:n.description,tags:n.tags,author:n.author,actions:[],blocks:[],created:e.timestamp,updated:e.timestamp},this.assemblyStates.set(this.topicId,i);break;case"add-action":if(!i)return void this.logger.warn("Cannot add action without assembly registration");const o=t,r={t_id:o.t_id,alias:o.alias,config:o.config,data:o.data};i.actions.push(r),i.updated=e.timestamp;break;case"add-block":if(!i)return void this.logger.warn("Cannot add block without assembly registration");const a=t,s={block_t_id:a.block_t_id,actions:a.actions,attributes:a.attributes,children:a.children,data:a.data};i.blocks.push(s),i.updated=e.timestamp;break;case"update":if(!i)return void this.logger.warn("Cannot update without assembly registration");const c=t;void 0!==c.description&&(i.description=c.description),void 0!==c.tags&&(i.tags=c.tags),i.updated=e.timestamp}}async getAssemblyState(e){const t=e||this.topicId;if(!t||!this.client)return null;let i=this.assemblyStates.get(t);if(i)return i;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 i of this.entries.values())this.processAssemblyMessage(t,i);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}),i=Array.isArray(e)?e:[];this.logger.info("Processing assembly messages",{topicId:t,messageCount:i.length});for(const r of i)try{let e;if(!r.message)continue;try{let t;t="undefined"==typeof window?globalThis.Buffer.from(r.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(r.message),e=>e.charCodeAt(0))),e=JSON.parse(t),this.logger.debug("Successfully parsed message",{sequenceNumber:r.sequence_number,op:e.op,p:e.p})}catch(n){this.logger.debug("Failed to decode/parse message",{sequenceNumber:r.sequence_number,error:n});continue}if("hcs-12"!==e.p){this.logger.debug("Skipping non-HCS-12 message",{sequenceNumber:r.sequence_number,protocol:e.p});continue}const i={id:r.sequence_number.toString(),sequenceNumber:r.sequence_number,timestamp:r.consensus_timestamp||(new Date).toISOString(),submitter:r.payer_account_id||"unknown",data:e};this.processAssemblyMessage(t,i),this.logger.debug("Processed message for assembly",{topicId:t,sequenceNumber:i.sequenceNumber,op:i.data.op})}catch(n){this.logger.warn("Failed to parse assembly message",{sequenceNumber:r.sequence_number,error:n})}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(n){return this.logger.error("Failed to sync assembly state",{topicId:t,error:n}),null}}processAssemblyMessage(e,t){const i=t.data;let n=this.assemblyStates.get(e);switch(this.logger.debug("Processing assembly message",{topicId:e,op:i.op,hasState:!!n}),i.op){case"register":const o=i;n={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,n),this.logger.debug("Assembly registered",{topicId:e,name:o.name,version:o.version});break;case"add-action":if(!n)return void this.logger.warn("Cannot add action without assembly registration");const r=i,a={t_id:r.t_id,alias:r.alias,config:r.config,data:r.data};n.actions.push(a),n.updated=t.timestamp;break;case"add-block":if(!n)return void this.logger.warn("Cannot add block without assembly registration");const s=i,c={block_t_id:s.block_t_id,actions:s.actions,attributes:s.attributes,children:s.children,data:s.data};n.blocks.push(c),n.updated=t.timestamp;break;case"update":if(!n)return void this.logger.warn("Cannot update without assembly registration");const p=i;void 0!==p.description&&(n.description=p.description),void 0!==p.tags&&(n.tags=p.tags),n.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}),i=Array.isArray(t)?t:[];this.logger.info("Processing assembly messages",{topicId:this.topicId,messageCount:i.length});for(const n of i)try{let t;if(n.message)try{let e;e="undefined"==typeof window?globalThis.Buffer.from(n.message,"base64").toString("utf-8"):(new TextDecoder).decode(Uint8Array.from(atob(n.message),e=>e.charCodeAt(0))),t=JSON.parse(e)}catch(e){this.logger.debug("Failed to decode/parse message in sync",{sequenceNumber:n.sequence_number,error:e});continue}else if(n.raw_content)try{t=JSON.parse(n.raw_content)}catch{continue}else{const e=n;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 i={id:n.sequence_number.toString(),sequenceNumber:n.sequence_number,timestamp:n.consensus_timestamp||(new Date).toISOString(),submitter:n.payer_account_id||"unknown",data:t};this.entries.set(i.id,i),await this.processMessage(i),this.logger.debug("Processed sync message",{sequenceNumber:i.sequenceNumber,op:i.data.op})}catch(e){this.logger.warn("Failed to parse assembly message",{sequenceNumber:n.sequence_number,error:e})}this.logger.info("Assembly sync completed",{topicId:this.topicId,messageCount:i.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{s1(e)}catch(t){if(t instanceof n.ZodError){const e=t.errors.map(e=>`${e.path.join(".")}: ${e.message}`);throw new Error(`Assembly validation failed: ${e.join("; ")}`)}throw t}}}class d1 extends K0{constructor(e,t,i,n){super(e,t,q0.HASHLINKS,i,n)}async register(e){this.validateRegistration(e);const t=`${this.topicId||"local"}_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,i={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,i),this.client&&this.topicId)try{const n=JSON.stringify(e),o=await this.client.submitMessage(this.topicId,n);return o.sequenceNumber&&(i.sequenceNumber=o.sequenceNumber,i.id=o.sequenceNumber.toString(),this.entries.delete(t),this.entries.set(i.id,i)),this.logger.info("HashLink submitted to HCS",{transactionId:o.transactionId,sequenceNumber:o.sequenceNumber,topicId:this.topicId}),i.id}catch(n){throw this.logger.error("Failed to submit HashLink to HCS",{error:n}),this.entries.delete(t),n}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(),i=e.toLowerCase();return t.map(e=>e.data).filter(e=>e.name.toLowerCase().includes(i)||(e.description?.toLowerCase().includes(i)??!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 i=e.data;i.category&&t.add(i.category)}),Array.from(t).sort()}async getAllTags(){const e=await this.listEntries(),t=new Set;return e.forEach(e=>{const i=e.data;i.tags&&i.tags.forEach(e=>t.add(e))}),Array.from(t).sort()}validateRegistration(e){this.validateBaseRegistration(e);const t=c1(e,r1);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()),i=new Set,n=new Set;let o=0;return t.forEach(e=>{const t=e.data;t.category&&i.add(t.category),t.tags&&t.tags.forEach(e=>n.add(e)),t.featured&&o++}),{...e,categories:i.size,totalTags:n.size,featuredCount:o}}}class f1{constructor(e,t,i,n){this.cache=new Map,this.logger=e,this.assemblyRegistry=t,this.actionRegistry=i,this.blockLoader=n}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 i={topicId:e,state:t,actions:[],blocks:[]};return this.cache.set(e,i),this.logger.debug("Assembly loaded successfully",{topicId:e,name:t.name,version:t.version,actionsCount:t.actions?.length||0,blocksCount:t.blocks?.length||0}),i}catch(i){throw this.logger.error("Failed to load assembly",{topicId:e,error:i}),new Error(`Failed to load assembly: ${i instanceof Error?i.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 n of e.actions)try{const e=await this.resolveActionReference(n);t.actions.push({alias:n.alias,t_id:n.t_id,definition:e,config:n.config})}catch(i){this.logger.warn("Failed to resolve action reference",{t_id:n.t_id,alias:n.alias,error:i}),t.actions.push({alias:n.alias,t_id:n.t_id,definition:null,config:n.config,error:i instanceof Error?i.message:"Unknown error"})}if(e.blocks)for(const n of e.blocks)try{const{definition:e,template:i}=await this.resolveBlockReference(n);t.blocks.push({block_t_id:n.block_t_id,definition:e,template:i,attributes:n.attributes,actions:n.actions,children:n.children})}catch(i){this.logger.warn("Failed to resolve block reference",{block_t_id:n.block_t_id,error:i}),t.blocks.push({block_t_id:n.block_t_id,definition:null,attributes:n.attributes,actions:n.actions,children:n.children,error:i instanceof Error?i.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 i of e.state.blocks){if(i.actions)for(const[n,o]of Object.entries(i.actions)){const r=e.state.actions?.some(e=>e.t_id===o);r||t.push(`Block ${i.block_t_id} references non-existent action: ${o} for key ${n}`)}if(i.children)for(const n of i.children){const o=e.state.blocks?.some(e=>e.block_t_id===n);o||t.push(`Block ${i.block_t_id} references non-existent child block: ${n}`)}}for(const i of e.actions)i.error&&t.push(`Action ${i.alias} has resolution error: ${i.error}`);for(const i of e.blocks)i.error&&t.push(`Block ${i.block_t_id} has resolution error: ${i.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),i=await this.resolveReferences(t.state),n=this.validateComposition(i);return n.valid||this.logger.warn("Assembly validation failed",{topicId:e,errors:n.errors}),i}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 m1{constructor(e){this.network=e.network,this.logger=e.logger||y.getInstance({level:e.logLevel||"info",module:"HCS12-BaseClient",prettyPrint:e.prettyPrint,silent:e.silent}),this.mirrorNode=new I(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 l1(this.network,this.logger,this)),this._blockLoader.loadBlock(e)}async getAssembly(e,t){if(!this._assemblyRegistry)throw new Error("Assembly registry not initialized");const i=await this._assemblyRegistry.listEntries();for(const n of i){const i=await this._assemblyRegistry.getAssemblyState(n.id);if(i&&i.name===e&&i.version===t)return i}return null}async loadAssembly(e){this._actionRegistry&&(this.logger.info("Syncing action registry before loading assembly"),await this._actionRegistry.sync());const t=new u1(this.network,this.logger,e,this);await t.sync();return new f1(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 f1(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 h1{constructor(){this.block={apiVersion:3},this.attributes={},this.supports={},this.actions={},this.logger=new y({module:"BlockBuilder"})}setName(e){return this.block.name=e,this}setTitle(e){return this.block.title=e,this}setDescription(e){return this.block.description=e,this}setCategory(e){return this.block.category=e,this}setIcon(e){return this.block.icon=e,this}setKeywords(e){return this.block.keywords=e,this}setApiVersion(e){return this.block.apiVersion=e,this}addAttribute(e,t,i,n){const o={type:t,default:i};return n?.enum&&(o.enum=n.enum),n?.source&&(o.source=n.source),n?.selector&&(o.selector=n.selector),n?.attribute&&(o.attribute=n.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 h1).setName(e).setTitle(t).setCategory("formatting").enableCommonSupports()}static createInteractiveBlock(e,t){return(new h1).setName(e).setTitle(t).setCategory("widgets").enableCommonSupports()}static createWidgetBlock(e,t){return this.createInteractiveBlock(e,t)}static createContainerBlock(e,t){return(new h1).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 g1{constructor(e,t){this.wasmCache=new Map,this.logger=e,this.network=t,this.hrlResolver=new _Q}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(i){return this.logger&&"function"==typeof this.logger.error?this.logger.error("WASM execution failed",{actionId:e.t_id,error:i.message}):console.error("WASM execution failed",{actionId:e.t_id,error:i.message}),{success:!1,error:i.message}}}readWasmString(e,t){const i=new Uint8Array(e.buffer);let n=0;for(;0!==i[t+n];)n++;return(new TextDecoder).decode(i.slice(t,t+n))}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 i=await this.hrlResolver.resolve(e.js_t_id,{network:this.network,returnRaw:!1});if(!i.content||"string"!=typeof i.content)throw new Error("Failed to load JavaScript module: invalid content");const n=new Blob([i.content],{type:"application/javascript"}),o=URL.createObjectURL(n);try{this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Importing JavaScript module from blob URL");const i=new Function("url","return import(url)"),n=await i(o);if(this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Module imported, exports:",Object.keys(n)),!n.default&&!n.init)throw new Error("No init function found in JavaScript module");{const t=n.default||n.init;this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Loading WASM bytes from topic:",e.t_id);const i=await this.hrlResolver.resolve(e.t_id,{network:this.network,returnRaw:!0});if(this.logger&&"function"==typeof this.logger.debug){const e=i.content instanceof ArrayBuffer?i.content.byteLength:i.content.length;this.logger.debug("WASM bytes loaded, size:",e)}await t({module_or_path:i.content}),this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("WASM module initialized successfully")}const r=n.WasmInterface;if(!r)throw new Error("WasmInterface not found in module exports. Available exports: "+Object.keys(n).join(", "));this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Creating WasmInterface instance");const a=new r;let s,c;if("POST"===t.method&&a.POST){const e=t.params.operation||"default",i={...t.params,...t.state},n=JSON.stringify(i);this.logger&&"function"==typeof this.logger.debug?this.logger.debug("Calling POST method",{actionName:e,paramsJson:n,allParams:i}):console.log("WASM POST params:",{actionName:e,paramsJson:n,allParams:i}),s=await a.POST(e,n,this.network.toString(),"")}else if("GET"===t.method&&a.GET){const e=t.params.operation||"default",i=JSON.stringify(t.params);this.logger&&"function"==typeof this.logger.debug&&this.logger.debug("Calling GET method",{actionName:e,paramsJson:i}),s=await a.GET(e,i,this.network.toString())}else{if("INFO"!==t.method||!a.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"),s=a.INFO()}try{c=JSON.parse(s)}catch{c={value:s}}return a.free&&a.free(),URL.revokeObjectURL(o),{success:!0,data:c}}catch(mxe){throw URL.revokeObjectURL(o),mxe}}}catch(i){const t=i instanceof Error?i.message:String(i),n=i instanceof Error?i.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:n,fullError:i}):console.error("JavaScript execution failed",{jsTopicId:e.js_t_id,error:t,stack:n,fullError:i}),{success:!1,error:t||"Unknown error"}}}clearCache(){this.wasmCache.clear()}}class y1{constructor(e){this.logger=e}async scanTemplate(e){const t=[],i=/<([^>]+)\s+data-hashlink=["']([^"']+)["']([^>]*)>/gs;let n;for(;null!==(n=i.exec(e));){const e=n[0],i=n[1].split(/\s+/)[0],r=n[2],a=n[3];try{const n=this.parseHashLinkURI(r),o=a.match(/data-attributes=(['"])((?:(?!\1).)*)\1/s);let s;if(o)try{const e=o[2];s=JSON.parse(e)}catch(mxe){this.logger.warn("Failed to parse data-attributes",{uri:r,attributes:o[2],error:mxe.message})}const c=a.match(/data-actions=(['"])((?:(?!\1).)*)\1/s);let p;if(c)try{const e=c[2];p=JSON.parse(e)}catch(mxe){this.logger.warn("Failed to parse data-actions",{uri:r,actions:c[2],error:mxe.message})}const l=a.match(/data-loading=['"]([^'"]+)['"]/),u=l?.[1]||"eager";t.push({element:i,uri:r,...n,attributes:s,actions:p,loading:u,placeholder:e}),this.logger.debug("Found HashLink reference",{uri:r,parsed:n})}catch(o){this.logger.error("Failed to parse HashLink URI",{uri:r,error:o.message})}}return t}parseHashLinkURI(e){const t=e.match(/^hcs:\/\/(\d+)\/(.+)$/);if(!t)throw new Error(`Invalid HashLink URI format: ${e}`);const i=t[1],n=t[2];if("2"===i){const e=n.split("/");if(2!==e.length)throw new Error(`Invalid HCS-2 reference format: ${n}`);return{protocol:i,reference:n,registryId:e[0],entryName:e[1]}}return{protocol:i,reference:n}}createPlaceholder(e,t){return`\x3c!-- HASHLINK_PLACEHOLDER_${t}_${e.uri.replace(/[^a-zA-Z0-9]/g,"_")} --\x3e`}}class v1{constructor(e,t,i,n){this.logger=e,this.blockLoader=t,this.hrlResolver=i,this.network=n,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(i){return this.logger.error("Failed to resolve HashLink",{uri:e.uri,error:i.message}),{blockId:e.reference,definition:null,template:null,attributes:{},actions:{},error:i.message}}}async resolveHCS12Block(e,t){const i=e.reference;if(this.renderStack.has(i))return{blockId:i,definition:null,template:null,attributes:{},actions:{},error:"Circular reference detected"};const n=this.getCacheKey(i,e.attributes,e.actions);if(this.cache.has(n))return this.cache.get(n);try{const o=await this.blockLoader.loadBlock(i);if(!o||!o.definition)throw new Error(`Block not found: ${i}`);const r={...this.extractDefaults(o.definition),...t.attributes,...e.attributes},a={...t.actions,...e.actions},s={blockId:i,definition:o.definition,template:o.template,attributes:r,actions:a};return this.cache.set(n,s),s}catch(o){throw this.renderStack.delete(i),new Error(`Failed to load HCS-12 block ${i}: ${o.message}`)}}async resolveHCS1Block(e,t){const i=e.reference;try{const t=await this.blockLoader.loadBlock(i);if(t&&t.definition)return{blockId:i,definition:t.definition,template:t.template,attributes:{...this.extractDefaults(t.definition),...e.attributes},actions:e.actions||{}};return{blockId:i,definition:null,template:(await this.hrlResolver.resolve(i,{network:this.network})).content,attributes:e.attributes||{},actions:e.actions||{}}}catch(n){throw new Error(`Failed to load HCS-1 content ${i}: ${n.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(i){throw new Error(`Failed to resolve HCS-2 entry: ${i.message}`)}}extractDefaults(e){const t={};return e.attributes&&Object.entries(e.attributes).forEach(([e,i])=>{i&&"object"==typeof i&&"default"in i&&(t[e]=i.default)}),t}getCacheKey(e,t,i){return`${e}:${t?JSON.stringify(t):""}:${i?JSON.stringify(i):""}`}pushRenderStack(e){this.renderStack.add(e)}popRenderStack(e){this.renderStack.delete(e)}clearCache(){this.cache.clear()}}const b1={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"}},x1={ACTIONS:{},BLOCKS:{},ASSEMBLIES:{}};var w1=(e=>(e.REGISTER="register",e.UPDATE="update",e.DELETE="delete",e.MIGRATE="migrate",e))(w1||{}),k1=(e=>(e[e.INDEXED=0]="INDEXED",e[e.NON_INDEXED=1]="NON_INDEXED",e))(k1||{});const _1=n.z.string().regex(/^\d+\.\d+\.\d+$/,{message:"Topic ID must be in Hedera format (e.g., '0.0.123456')"}),E1=n.z.object({p:n.z.string().regex(/^hcs-\d+$/,{message:"Protocol must be in format 'hcs-N' where N is a number"}),op:n.z.enum(["register","update","delete","migrate"]),m:n.z.string().max(500,"Memo must not exceed 500 characters").optional(),ttl:n.z.number().int().positive().optional()}),S1=E1.extend({op:n.z.literal("register"),t_id:_1,metadata:n.z.string().optional()}),T1=E1.extend({op:n.z.literal("update"),uid:n.z.string(),t_id:_1,metadata:n.z.string().optional()}),A1=E1.extend({op:n.z.literal("delete"),uid:n.z.string()}),I1=E1.extend({op:n.z.literal("migrate"),t_id:_1,metadata:n.z.string().optional()}),R1=n.z.discriminatedUnion("op",[S1,T1,A1,I1]);class O1{constructor(e){this.network=e.network,this.logger=e.logger||y.getInstance({level:e.logLevel||"info",module:"HCS2Client",silent:e.silent}),this.mirrorNode=new I(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0)}parseRegistryTypeFromMemo(e){try{const t=/hcs-2:(\d):(\d+)/,i=e.match(t);if(i&&3===i.length){const e=parseInt(i[1]),t=parseInt(i[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 R1.parse(e),{valid:!0,errors:[]}}catch(t){const e=[];return t instanceof n.ZodError?t.errors.forEach(t=>{const i=t.path.join(".");e.push(`${i?i+": ":""}${t.message}`)}):e.push(`Unexpected error: ${t}`),this.logger.debug(`Message validation failed: ${e.join(", ")}`),{valid:!1,errors:e}}}createRegisterMessage(e,t,i,n="hcs-2"){return{p:n,op:w1.REGISTER,t_id:e,metadata:t,m:i}}createUpdateMessage(e,t,i,n,o="hcs-2"){return{p:o,op:w1.UPDATE,t_id:e,uid:t,metadata:i,m:n}}createDeleteMessage(e,t,i="hcs-2"){return{p:i,op:w1.DELETE,uid:e,m:t}}createMigrateMessage(e,t,i,n="hcs-2"){return{p:n,op:w1.MIGRATE,t_id:e,metadata:t,m:i}}parseRegistryEntries(e,t,i,n){const o=[];let r;this.logger.debug(`Parsing ${t.length} messages for topic ${e}`);for(const s of t)try{if(!s.message){this.logger.debug(`Message is missing 'message' property: ${JSON.stringify(s)}`);continue}const t=globalThis.Buffer.from(s.message,"base64").toString("utf-8"),n=JSON.parse(t);this.logger.debug(`Successfully parsed message: ${JSON.stringify(n)}`);const{valid:a,errors:c}=this.validateMessage(n);if(!a){this.logger.warn(`Invalid HCS-2 message: ${c.join(", ")}`);continue}const p={topicId:e,sequence:s.sequence_number,timestamp:s.consensus_timestamp,payer:s.payer_account_id,message:n,consensus_timestamp:s.consensus_timestamp,registry_type:i};o.push(p),(i===k1.NON_INDEXED||!r||p.timestamp>r.timestamp)&&(r=p)}catch(a){this.logger.warn(`Error parsing message: ${a}`)}return this.logger.debug(`Parsed ${o.length} valid entries for topic ${e}`),{topicId:e,registryType:i,ttl:n,entries:i===k1.INDEXED?o:r?[r]:[],latestEntry:r}}}function j1(e){var t,i;return N({memo:e.memoOverride??(t=e.registryType,i=e.ttl,`hcs-2:${t}:${i}`),adminKey:e.adminKey,submitKey:e.submitKey,operatorPublicKey:e.operatorPublicKey})}class C1 extends O1{constructor(e){if(super({network:e.network,logLevel:e.logLevel,silent:e.silent,mirrorNodeUrl:e.mirrorNodeUrl,logger:e.logger}),this.initialized=!1,this.operatorId="string"==typeof e.operatorId?o.AccountId.fromString(e.operatorId):e.operatorId,e.keyType)this.keyType=e.keyType,this.operatorKey="string"==typeof e.operatorKey?"ecdsa"===this.keyType?o.PrivateKey.fromStringECDSA(e.operatorKey):o.PrivateKey.fromStringED25519(e.operatorKey):e.operatorKey;else if("string"==typeof e.operatorKey)try{const t=C(e.operatorKey);this.operatorKey=t.privateKey,this.keyType=t.detectedType,t.warning&&this.logger.warn(t.warning)}catch(t){this.logger.warn("Failed to detect key type from private key format, defaulting to ECDSA"),this.keyType="ecdsa",this.operatorKey=o.PrivateKey.fromStringECDSA(e.operatorKey)}else this.operatorKey=e.operatorKey,this.keyType="ecdsa";this.client=this.createClient(e.network),this.initializeClient()}initializeClient(){try{this.client.setOperator(this.operatorId,this.operatorKey),this.initialized=!0,this.logger.info(`HCS-2 client initialized successfully with key type: ${this.keyType}`)}catch(e){throw this.logger.error(`Failed to initialize HCS-2 client: ${e}`),e}}createClient(e){return"mainnet"===e?o.Client.forMainnet():o.Client.forTestnet()}async createRegistry(e={}){try{const t=e.registryType??k1.INDEXED,i=e.ttl??86400;this.generateRegistryMemo(t,i);let n,r,a,s;if(e.adminKey)if("string"==typeof e.adminKey)try{r=o.PublicKey.fromString(e.adminKey)}catch{const t=globalThis.Buffer.from(e.adminKey.replace(/^0x/i,""),"hex");r="ed25519"===this.keyType?o.PublicKey.fromBytesED25519(t):o.PublicKey.fromBytesECDSA(t)}else"boolean"==typeof e.adminKey?r=this.operatorKey.publicKey:(r=e.adminKey.publicKey,n=e.adminKey);if(e.submitKey)if("string"==typeof e.submitKey)try{s=o.PublicKey.fromString(e.submitKey)}catch{const t=globalThis.Buffer.from(e.submitKey.replace(/^0x/i,""),"hex");s="ed25519"===this.keyType?o.PublicKey.fromBytesED25519(t):o.PublicKey.fromBytesECDSA(t)}else"boolean"==typeof e.submitKey?s=this.operatorKey.publicKey:(s=e.submitKey.publicKey,a=e.submitKey);const c=j1({registryType:t,ttl:i,adminKey:r,submitKey:s,operatorPublicKey:this.operatorKey.publicKey}),p=await c.freezeWith(this.client);n&&await p.sign(n),a&&await p.sign(a);const l=await p.execute(this.client),u=(await l.getReceipt(this.client)).topicId;if(!u)throw new Error("Failed to create registry: No topic ID in receipt");const d=u.toString();return this.logger.info(`Created registry topic: ${d} (${t===k1.INDEXED?"Indexed":"Non-indexed"}, TTL: ${i}s)`),{success:!0,topicId:d,transactionId:l.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,i="hcs-2"){try{const n=this.createRegisterMessage(t.targetTopicId,t.metadata,t.memo,i),o=await this.submitMessage(e,n);return this.logger.info(`Registered entry in registry ${e} pointing to topic ${t.targetTopicId} using protocol ${i}`),{success:!0,receipt:o,sequenceNumber:o.topicSequenceNumber?.low??void 0}}catch(n){return this.logger.error(`Failed to register entry: ${n}`),{success:!1,error:`Failed to register entry: ${n}`}}}async updateEntry(e,t){try{const i=await this.mirrorNode.getTopicInfo(e),n=this.parseRegistryTypeFromMemo(i.memo);if(!n||n.registryType!==k1.INDEXED)throw new Error("Update operation is only valid for indexed registries");const o=this.createUpdateMessage(t.targetTopicId,t.uid,t.metadata,t.memo),r=await this.submitMessage(e,o);return this.logger.info(`Updated entry with UID ${t.uid} in registry ${e}`),{success:!0,receipt:r,sequenceNumber:r.topicSequenceNumber?.low??void 0}}catch(i){throw this.logger.error(`Failed to update entry: ${i}`),i}}async deleteEntry(e,t){try{const i=await this.mirrorNode.getTopicInfo(e),n=this.parseRegistryTypeFromMemo(i.memo);if(!n||n.registryType!==k1.INDEXED)throw new Error("Delete operation is only valid for indexed registries");const o=this.createDeleteMessage(t.uid,t.memo),r=await this.submitMessage(e,o);return this.logger.info(`Deleted entry with UID ${t.uid} from registry ${e}`),{success:!0,receipt:r,sequenceNumber:r.topicSequenceNumber?.low??void 0}}catch(i){throw this.logger.error(`Failed to delete entry: ${i}`),i}}async migrateRegistry(e,t){try{const i=this.createMigrateMessage(t.targetTopicId,t.metadata,t.memo),n=await this.submitMessage(e,i);return this.logger.info(`Migrated registry ${e} to ${t.targetTopicId}`),{success:!0,receipt:n,sequenceNumber:n.topicSequenceNumber?.low??void 0}}catch(i){throw this.logger.error(`Failed to migrate registry: ${i}`),i}}async getRegistry(e,t={}){try{const n=await this.mirrorNode.getTopicInfo(e);this.logger.debug(`Retrieved topic info for ${e}: ${JSON.stringify(n)}`);const o=this.parseRegistryTypeFromMemo(n.memo);if(!o)throw new Error(`Topic ${e} is not an HCS-2 registry (invalid memo format)`);this.logger.debug(`Retrieving messages for topic ${e} with limit ${t.limit??100}`);const r=await this.mirrorNode.getTopicMessages(e,{sequenceNumber:t.skip&&t.skip>0?`gt:${t.skip}`:void 0,limit:t.limit??100,order:t.order??"asc"}),a=t.limit?r.slice(0,t.limit):r;this.logger.debug(`Retrieved ${r.length} messages, using ${a.length} after applying limit.`);const s=[];let c;for(const t of a)try{const i={p:"hcs-2",op:t.op,t_id:t.t_id,uid:t.uid,metadata:t.metadata,m:t.m},{valid:n,errors:r}=this.validateMessage(i);if(!n){this.logger.warn(`Invalid HCS-2 message: ${r.join(", ")}`);continue}const a={topicId:e,sequence:t.sequence_number,timestamp:t.consensus_timestamp,payer:t.payer_account_id||t.payer||"",message:i,consensus_timestamp:t.consensus_timestamp,registry_type:o.registryType};s.push(a),(o.registryType===k1.NON_INDEXED||!c||a.timestamp>c.timestamp)&&(c=a)}catch(i){this.logger.warn(`Error processing message: ${i}`)}this.logger.debug(`Processed ${s.length} valid entries for registry ${e}`);return{topicId:e,registryType:o.registryType,ttl:o.ttl,entries:o.registryType===k1.INDEXED?s:c?[c]:[],latestEntry:c}}catch(i){throw this.logger.error(`Failed to get registry: ${i}`),i}}async submitMessage(e,t){try{const{valid:i,errors:n}=this.validateMessage(t);if(!i)throw new Error(`Invalid HCS-2 message: ${n.join(", ")}`);const o=B({topicId:e,message:JSON.stringify(t)}),r=await o.execute(this.client);return await r.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.keyType}getOperatorKey(){return this.operatorKey}}class N1 extends O1{constructor(e){super({network:e.network,logLevel:e.logLevel,silent:e.silent,mirrorNodeUrl:e.mirrorNodeUrl,logger:e.logger}),this.hwc=e.hwc,rQ?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??k1.INDEXED,i=e.ttl??86400,n=this.generateRegistryMemo(t,i);let r=(new o.TopicCreateTransaction).setTopicMemo(n);if(e.adminKey){let t;if("string"==typeof e.adminKey)try{t=o.PublicKey.fromString(e.adminKey)}catch{const i=j.detect(e.adminKey);if(!i.rawBytes)throw new Error("Failed to parse admin public key");t="ed25519"===i.type?o.PublicKey.fromBytesED25519(i.rawBytes):o.PublicKey.fromBytesECDSA(i.rawBytes)}else t="boolean"==typeof e.adminKey?await this.mirrorNode.getPublicKey(this.getOperatorId()):e.adminKey.publicKey;r=r.setAdminKey(t)}if(e.submitKey){let t;if("string"==typeof e.submitKey)try{t=o.PublicKey.fromString(e.submitKey)}catch{const i=j.detect(e.submitKey);if(!i.rawBytes)throw new Error("Failed to parse submit public key");t="ed25519"===i.type?o.PublicKey.fromBytesED25519(i.rawBytes):o.PublicKey.fromBytesECDSA(i.rawBytes)}else t="boolean"==typeof e.submitKey?await this.mirrorNode.getPublicKey(this.getOperatorId()):e.submitKey.publicKey;r=r.setSubmitKey(t)}const a=await this.executeWithWallet(r);if(a?.error)throw new Error(a.error);const s=a?.result;if(!s?.topicId)throw new Error("Failed to create registry: No topic ID in receipt");const c=s.topicId.toString();return this.logger.info(`Created registry topic: ${c} (${t===k1.INDEXED?"Indexed":"Non-indexed"}, TTL: ${i}s)`),{success:!0,topicId:c,transactionId:a.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 i=this.createRegisterMessage(t.targetTopicId,t.metadata,t.memo);if(i.op!==w1.REGISTER)throw new Error(`Invalid operation type: ${i.op}, expected ${w1.REGISTER}`);const n=await this.submitMessage(e,i);return this.logger.info(`Registered entry in registry ${e} pointing to topic ${t.targetTopicId}`),{success:!0,receipt:n,sequenceNumber:n.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{const i=await this.mirrorNode.getTopicInfo(e),n=this.parseRegistryTypeFromMemo(i.memo);if(!n||n.registryType!==k1.INDEXED)throw new Error("Update operation is only valid for indexed registries");const o=this.createUpdateMessage(t.targetTopicId,t.uid,t.metadata,t.memo),r=await this.submitMessage(e,o);return this.logger.info(`Updated entry with UID ${t.uid} in registry ${e}`),{success:!0,receipt:r,sequenceNumber:r.topicSequenceNumber?.low??void 0}}catch(i){return this.logger.error(`Failed to update entry: ${i}`),{success:!1,error:`Failed to update entry: ${i}`}}}async deleteEntry(e,t){try{const i=await this.mirrorNode.getTopicInfo(e),n=this.parseRegistryTypeFromMemo(i.memo);if(!n||n.registryType!==k1.INDEXED)throw new Error("Delete operation is only valid for indexed registries");const o=this.createDeleteMessage(t.uid,t.memo),r=await this.submitMessage(e,o);return this.logger.info(`Deleted entry with UID ${t.uid} from registry ${e}`),{success:!0,receipt:r,sequenceNumber:r.topicSequenceNumber?.low??void 0}}catch(i){return this.logger.error(`Failed to delete entry: ${i}`),{success:!1,error:`Failed to delete entry: ${i}`}}}async migrateRegistry(e,t){try{const i=this.createMigrateMessage(t.targetTopicId,t.metadata,t.memo),n=await this.submitMessage(e,i);return this.logger.info(`Migrated registry ${e} to ${t.targetTopicId}`),{success:!0,receipt:n,sequenceNumber:n.topicSequenceNumber?.low??void 0}}catch(i){return this.logger.error(`Failed to migrate registry: ${i}`),{success:!1,error:`Failed to migrate registry: ${i}`}}}async getRegistry(e,t={}){try{const i=await this.mirrorNode.getTopicInfo(e),n=this.parseRegistryTypeFromMemo(i.memo);if(!n)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"}),r=t.limit?o.slice(0,t.limit):o;return this.parseRegistryEntries(e,r,n.registryType,n.ttl)}catch(i){throw this.logger.error(`Failed to get registry: ${i}`),i}}async submitMessage(e,t){try{const{valid:i,errors:n}=this.validateMessage(t);if(!i)throw new Error(`Invalid HCS-2 message: ${n.join(", ")}`);const o=B({topicId:e,message:JSON.stringify(t)}),r=await this.executeWithWallet(o);if(r?.error)throw new Error(r.error);return r.result}catch(i){throw this.logger.error(`Failed to submit message: ${i}`),i}}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 B1={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*))$/},P1=n.z.string().regex(B1.HEDERA_ACCOUNT_REGEX,"Invalid Hedera account ID format"),L1=n.z.string().regex(/^\d+$/,"Must be a valid number").max(B1.MAX_NUMBER_LENGTH,`Max ${B1.MAX_NUMBER_LENGTH} digits`),U1=n.z.string().min(1,"Tick cannot be empty").transform(e=>e.toLowerCase().trim()),F1=n.z.object({p:n.z.literal("hcs-20"),m:n.z.string().optional()}),M1=F1.extend({op:n.z.literal("deploy"),name:n.z.string().min(1).max(B1.MAX_NAME_LENGTH),tick:U1,max:L1,lim:L1.optional(),metadata:n.z.string().max(B1.MAX_METADATA_LENGTH).optional()}),D1=F1.extend({op:n.z.literal("mint"),tick:U1,amt:L1,to:P1}),z1=F1.extend({op:n.z.literal("burn"),tick:U1,amt:L1,from:P1}),$1=F1.extend({op:n.z.literal("transfer"),tick:U1,amt:L1,from:P1,to:P1}),q1=F1.extend({op:n.z.literal("register"),name:n.z.string().min(1).max(B1.MAX_NAME_LENGTH),metadata:n.z.string().max(B1.MAX_METADATA_LENGTH).optional(),private:n.z.boolean(),t_id:P1}),K1=n.z.discriminatedUnion("op",[M1,D1,z1,$1,q1]);class W1 extends Error{constructor(e){super(e),this.name="HCS20Error"}}class H1 extends W1{constructor(e,t){super(e),this.tick=t,this.name="PointsDeploymentError"}}class V1 extends W1{constructor(e,t,i,n,o,r){super(e),this.tick=t,this.from=i,this.to=n,this.amount=o,this.availableBalance=r,this.name="PointsTransferError"}}class G1 extends W1{constructor(e,t,i,n,o){super(e),this.tick=t,this.from=i,this.amount=n,this.availableBalance=o,this.name="PointsBurnError"}}class Z1 extends W1{constructor(e,t){super(e),this.validationErrors=t,this.name="PointsValidationError"}}class J1 extends W1{constructor(e,t){super(e),this.topicId=t,this.name="TopicRegistrationError"}}class Y1 extends W1{constructor(e){super(`Invalid Hedera account format: ${e}`),this.account=e,this.name="InvalidAccountFormatError"}}class X1{constructor(e){this.logger=e.logger||new y({module:"HCS20Client"}),this.network="mainnet"===e.network?"mainnet":"testnet",this.mirrorNode=new I(this.network,this.logger,e.mirrorNodeUrl?{customUrl:e.mirrorNodeUrl}:void 0),this.registryTopicId=e.registryTopicId||B1.REGISTRY_TOPIC_ID,this.publicTopicId=e.publicTopicId||B1.PUBLIC_TOPIC_ID}validateMessage(e){try{return K1.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(!B1.HEDERA_ACCOUNT_REGEX.test(e))throw new Y1(e);return e}return e.toString()}topicToString(e){if("string"==typeof e){if(!B1.HEDERA_ACCOUNT_REGEX.test(e))throw new Y1(e);return e}return e.toString()}}var Q1=(e=>(e.FIXED_FEE="FIXED_FEE",e.FRACTIONAL_FEE="FRACTIONAL_FEE",e.ROYALTY_FEE="ROYALTY_FEE",e))(Q1||{});class e2{constructor(e){this.customFees=[],this.logger=e.logger,this.mirrorNode=new I(e.network,e.logger),this.defaultCollectorAccountId=e.defaultCollectorAccountId||""}static forHbar(e,t,i,n,o=[]){return new e2({network:i,logger:n,defaultCollectorAccountId:t}).addHbarFee(e,t,o)}static async forToken(e,t,i,n,o,r=[],a){const s=new e2({network:n,logger:o,defaultCollectorAccountId:i});return await s.addTokenFee(e,t,i,a,r),s}addHbarFee(e,t,i=[]){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:[...i],type:Q1.FIXED_FEE}),this}async addTokenFee(e,t,i,n,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 r=n;if(void 0===r)try{const e=await this.mirrorNode.getTokenInfo(t);e?.decimals?(r=parseInt(e.decimals,10),this.logger.info(`Fetched decimals for ${t}: ${r}`)):(this.logger.warn(`Could not fetch decimals for ${t}, defaulting to 0.`),r=0)}catch(a){this.logger.error(`Error fetching decimals for ${t}, defaulting to 0: ${a}`),r=0}return this.customFees.push({feeAmount:{amount:e*10**r,decimals:r},feeCollectorAccountId:i||this.defaultCollectorAccountId,feeTokenId:t,exemptAccounts:[...o],type:Q1.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 t2{constructor(){this.resolver=null,this.onUnavailableCallbacks=[],this.logger=y.getInstance({module:"ContentResolverRegistry"})}static getInstance(){return t2._instance||(t2._instance=new t2),t2._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(i){return this.logger.warn("Resolver operation failed, using fallback:",i),await t()}}}const i2=t2.getInstance();class n2{constructor(){this.contentStore=null,this.logger=y.getInstance({module:"ContentStoreService"})}static getInstance(){return n2._instance||(n2._instance=new n2),n2._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 o2=n2.getInstance();var r2="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==fx?fx:"undefined"!=typeof self?self:{};function a2(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var s2,c2={};function p2(){return s2||(s2=1,function(e){Object.defineProperties(e,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});for(var t={},i={byteLength:function(e){var t=c(e),i=t[0],n=t[1];return 3*(i+n)/4-n},toByteArray:function(e){var t,i,n=c(e),a=n[0],s=n[1],p=new r(function(e,t,i){return 3*(t+i)/4-i}(0,a,s)),l=0,u=s>0?a-4:a;for(i=0;i<u;i+=4)t=o[e.charCodeAt(i)]<<18|o[e.charCodeAt(i+1)]<<12|o[e.charCodeAt(i+2)]<<6|o[e.charCodeAt(i+3)],p[l++]=t>>16&255,p[l++]=t>>8&255,p[l++]=255&t;2===s&&(t=o[e.charCodeAt(i)]<<2|o[e.charCodeAt(i+1)]>>4,p[l++]=255&t);1===s&&(t=o[e.charCodeAt(i)]<<10|o[e.charCodeAt(i+1)]<<4|o[e.charCodeAt(i+2)]>>2,p[l++]=t>>8&255,p[l++]=255&t);return p},fromByteArray:function(e){for(var t,i=e.length,o=i%3,r=[],a=16383,s=0,c=i-o;s<c;s+=a)r.push(l(e,s,s+a>c?c:s+a));1===o?(t=e[i-1],r.push(n[t>>2]+n[t<<4&63]+"==")):2===o&&(t=(e[i-2]<<8)+e[i-1],r.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"="));return r.join("")}},n=[],o=[],r="undefined"!=typeof Uint8Array?Uint8Array:Array,a="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0;s<64;++s)n[s]=a[s],o[a.charCodeAt(s)]=s;function c(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var i=e.indexOf("=");return-1===i&&(i=t),[i,i===t?0:4-i%4]}function p(e){return n[e>>18&63]+n[e>>12&63]+n[e>>6&63]+n[63&e]}function l(e,t,i){for(var n,o=[],r=t;r<i;r+=3)n=(e[r]<<16&16711680)+(e[r+1]<<8&65280)+(255&e[r+2]),o.push(p(n));return o.join("")}o["-".charCodeAt(0)]=62,o["_".charCodeAt(0)]=63;var u={
|
|
158
158
|
/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
|
|
159
159
|
read:function(e,t,i,n,o){var r,a,s=8*o-n-1,c=(1<<s)-1,p=c>>1,l=-7,u=i?o-1:0,d=i?-1:1,f=e[t+u];for(u+=d,r=f&(1<<-l)-1,f>>=-l,l+=s;l>0;r=256*r+e[t+u],u+=d,l-=8);for(a=r&(1<<-l)-1,r>>=-l,l+=n;l>0;a=256*a+e[t+u],u+=d,l-=8);if(0===r)r=1-p;else{if(r===c)return a?NaN:1/0*(f?-1:1);a+=Math.pow(2,n),r-=p}return(f?-1:1)*a*Math.pow(2,r-n)},write:function(e,t,i,n,o,r){var a,s,c,p=8*r-o-1,l=(1<<p)-1,u=l>>1,d=23===o?Math.pow(2,-24)-Math.pow(2,-77):0,f=n?0:r-1,m=n?1:-1,h=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(s=isNaN(t)?1:0,a=l):(a=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-a))<1&&(a--,c*=2),(t+=a+u>=1?d/c:d*Math.pow(2,1-u))*c>=2&&(a++,c/=2),a+u>=l?(s=0,a=l):a+u>=1?(s=(t*c-1)*Math.pow(2,o),a+=u):(s=t*Math.pow(2,u-1)*Math.pow(2,o),a=0));o>=8;e[i+f]=255&s,f+=m,s/=256,o-=8);for(a=a<<o|s,p+=o;p>0;e[i+f]=255&a,f+=m,a/=256,p-=8);e[i+f-m]|=128*h}};
|
|
160
160
|
/*!
|