@hashgraphonline/standards-sdk 0.0.130 → 0.0.131
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.
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).StandardsSDK={})}(this,(function(exports){"use strict";var __defProp3=Object.defineProperty,__typeError=e=>{throw TypeError(e)},__defNormalProp3=(e,t,r)=>t in e?__defProp3(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,__publicField3=(e,t,r)=>__defNormalProp3(e,"symbol"!=typeof t?t+"":t,r),__accessCheck=(e,t,r)=>t.has(e)||__typeError("Cannot "+r),__privateGet=(e,t,r)=>(__accessCheck(e,t,"read from private field"),r?r.call(e):t.get(e)),__privateAdd=(e,t,r)=>t.has(e)?__typeError("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),__privateSet=(e,t,r,n)=>(__accessCheck(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r),__privateMethod=(e,t,r)=>(__accessCheck(e,t,"access private method"),r),__privateWrapper=(e,t,r,n)=>({set _(n){__privateSet(e,t,n,r)},get _(){return __privateGet(e,t,n)}}),_a2,_names,_data,_dataLength,_Writer_instances,writeData_fn,_data2,_offset,_bytesRead,_parent,_maxInflation,_Reader_instances,incrementBytesRead_fn,peekBytes_fn,_options,_offset2,_tokens,_TokenString_instances,subTokenString_fn,_ParamType_instances,walkAsync_fn,_AbiCoder_instances,getCoder_fn,_errors,_events,_functions,_abiCoder,_Interface_instances,getFunction_fn,getEvent_fn;function _mergeNamespaces(e,t){for(var r=0;r<t.length;r++){const n=t[r];if("string"!=typeof n&&!Array.isArray(n))for(const t in n)if("default"!==t&&!(t in e)){const r=Object.getOwnPropertyDescriptor(n,t);r&&Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>n[t]})}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}function getDefaultExportFromCjs$4(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var browser$h={exports:{}},process$3=browser$h.exports={},cachedSetTimeout$2,cachedClearTimeout$2;function defaultSetTimout$2(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout$2(){throw new Error("clearTimeout has not been defined")}function runTimeout$2(e){if(cachedSetTimeout$2===setTimeout)return setTimeout(e,0);if((cachedSetTimeout$2===defaultSetTimout$2||!cachedSetTimeout$2)&&setTimeout)return cachedSetTimeout$2=setTimeout,setTimeout(e,0);try{return cachedSetTimeout$2(e,0)}catch(t){try{return cachedSetTimeout$2.call(null,e,0)}catch(r){return cachedSetTimeout$2.call(this,e,0)}}}function runClearTimeout$2(e){if(cachedClearTimeout$2===clearTimeout)return clearTimeout(e);if((cachedClearTimeout$2===defaultClearTimeout$2||!cachedClearTimeout$2)&&clearTimeout)return cachedClearTimeout$2=clearTimeout,clearTimeout(e);try{return cachedClearTimeout$2(e)}catch(t){try{return cachedClearTimeout$2.call(null,e)}catch(r){return cachedClearTimeout$2.call(this,e)}}}!function(){try{cachedSetTimeout$2="function"==typeof setTimeout?setTimeout:defaultSetTimout$2}catch(e){cachedSetTimeout$2=defaultSetTimout$2}try{cachedClearTimeout$2="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout$2}catch(e){cachedClearTimeout$2=defaultClearTimeout$2}}();var queue$2=[],draining$2=!1,currentQueue$2,queueIndex$2=-1;function cleanUpNextTick$2(){draining$2&¤tQueue$2&&(draining$2=!1,currentQueue$2.length?queue$2=currentQueue$2.concat(queue$2):queueIndex$2=-1,queue$2.length&&drainQueue$2())}function drainQueue$2(){if(!draining$2){var e=runTimeout$2(cleanUpNextTick$2);draining$2=!0;for(var t=queue$2.length;t;){for(currentQueue$2=queue$2,queue$2=[];++queueIndex$2<t;)currentQueue$2&¤tQueue$2[queueIndex$2].run();queueIndex$2=-1,t=queue$2.length}currentQueue$2=null,draining$2=!1,runClearTimeout$2(e)}}function Item$2(e,t){this.fun=e,this.array=t}function noop$5(){}process$3.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];queue$2.push(new Item$2(e,t)),1!==queue$2.length||draining$2||runTimeout$2(drainQueue$2)},Item$2.prototype.run=function(){this.fun.apply(null,this.array)},process$3.title="browser",process$3.browser=!0,process$3.env={},process$3.argv=[],process$3.version="",process$3.versions={},process$3.on=noop$5,process$3.addListener=noop$5,process$3.once=noop$5,process$3.off=noop$5,process$3.removeListener=noop$5,process$3.removeAllListeners=noop$5,process$3.emit=noop$5,process$3.prependListener=noop$5,process$3.prependOnceListener=noop$5,process$3.listeners=function(e){return[]},process$3.binding=function(e){throw new Error("process.binding is not supported")},process$3.cwd=function(){return"/"},process$3.chdir=function(e){throw new Error("process.chdir is not supported")},process$3.umask=function(){return 0};var browserExports$3=browser$h.exports;const process$1$2=getDefaultExportFromCjs$4(browserExports$3);var commonjsGlobal$2="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs$3(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var browser$g={exports:{}},quickFormatUnescaped$1,hasRequiredQuickFormatUnescaped$1,hasRequiredBrowser$f;function requireQuickFormatUnescaped$1(){if(hasRequiredQuickFormatUnescaped$1)return quickFormatUnescaped$1;function e(e){try{return JSON.stringify(e)}catch(t){return'"[Circular]"'}}return hasRequiredQuickFormatUnescaped$1=1,quickFormatUnescaped$1=function(t,r,n){var i=n&&n.stringify||e;if("object"==typeof t&&null!==t){var o=r.length+1;if(1===o)return t;var a=new Array(o);a[0]=i(t);for(var s=1;s<o;s++)a[s]=i(r[s]);return a.join(" ")}if("string"!=typeof t)return t;var c=r.length;if(0===c)return t;for(var u="",l=0,d=-1,p=t&&t.length||0,f=0;f<p;){if(37===t.charCodeAt(f)&&f+1<p){switch(d=d>-1?d:0,t.charCodeAt(f+1)){case 100:case 102:if(l>=c)break;if(null==r[l])break;d<f&&(u+=t.slice(d,f)),u+=Number(r[l]),d=f+2,f++;break;case 105:if(l>=c)break;if(null==r[l])break;d<f&&(u+=t.slice(d,f)),u+=Math.floor(Number(r[l])),d=f+2,f++;break;case 79:case 111:case 106:if(l>=c)break;if(void 0===r[l])break;d<f&&(u+=t.slice(d,f));var h=typeof r[l];if("string"===h){u+="'"+r[l]+"'",d=f+2,f++;break}if("function"===h){u+=r[l].name||"<anonymous>",d=f+2,f++;break}u+=i(r[l]),d=f+2,f++;break;case 115:if(l>=c)break;d<f&&(u+=t.slice(d,f)),u+=String(r[l]),d=f+2,f++;break;case 37:d<f&&(u+=t.slice(d,f)),u+="%",d=f+2,f++,l--}++l}++f}if(-1===d)return t;d<p&&(u+=t.slice(d));return u}}function requireBrowser$f(){if(hasRequiredBrowser$f)return browser$g.exports;hasRequiredBrowser$f=1;const e=requireQuickFormatUnescaped$1();browser$g.exports=c;const t=function(){function e(e){return void 0!==e&&e}try{return"undefined"!=typeof globalThis||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch(t){return e(self)||e(window)||e(this)||{}}}().console||{},r={mapHttpRequest:h,mapHttpResponse:h,wrapRequestSerializer:m,wrapResponseSerializer:m,wrapErrorSerializer:m,req:h,res:h,err:p,errWithCause:p};function n(e,t){return"silent"===e?1/0:t.levels.values[e]}const i=Symbol("pino.logFuncs"),o=Symbol("pino.hierarchy"),a={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function s(e,t){const r={logger:t,parent:e[o]};t[o]=r}function c(e){(e=e||{}).browser=e.browser||{};const r=e.browser.transmit;if(r&&"function"!=typeof r.send)throw Error("pino: transmit option must have a send function");const o=e.browser.write||t;e.browser.write&&(e.browser.asObject=!0);const p=e.serializers||{},h=function(e,t){if(Array.isArray(e))return e.filter((function(e){return"!stdSerializers.err"!==e}));return!0===e&&Object.keys(t)}(e.browser.serialize,p);let m=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(m=!1);const y=Object.keys(e.customLevels||{}),b=["error","fatal","warn","info","debug","trace"].concat(y);"function"==typeof o&&b.forEach((function(e){o[e]=o})),(!1===e.enabled||e.browser.disabled)&&(e.level="silent");const v=e.level||"info",w=Object.create(o);w.log||(w.log=g),function(e,r,n){const o={};r.forEach((e=>{o[e]=n[e]?n[e]:t[e]||t[a[e]||"log"]||g})),e[i]=o}(w,b,o),s({},w),Object.defineProperty(w,"levelVal",{get:function(){return n(this.level,this)}}),Object.defineProperty(w,"level",{get:function(){return this._level},set:function(e){if("silent"!==e&&!this.levels.values[e])throw Error("unknown level "+e);this._level=e,u(this,_,w,"error"),u(this,_,w,"fatal"),u(this,_,w,"warn"),u(this,_,w,"info"),u(this,_,w,"debug"),u(this,_,w,"trace"),y.forEach((e=>{u(this,_,w,e)}))}});const _={transmit:r,serialize:h,asObject:e.browser.asObject,formatters:e.browser.formatters,levels:b,timestamp:f(e),messageKey:e.messageKey||"msg",onChild:e.onChild||g};function k(t,n,i){if(!n)throw new Error("missing bindings for child Pino");i=i||{},h&&n.serializers&&(i.serializers=n.serializers);const o=i.serializers;if(h&&o){var a=Object.assign({},p,o),c=!0===e.browser.serialize?Object.keys(a):h;delete n.serializers,l([n],c,a,this._stdErrSerialize)}function u(e){this._childLevel=1+(0|e._childLevel),this.bindings=n,a&&(this.serializers=a,this._serialize=c),r&&(this._logEvent=d([].concat(e._logEvent.bindings,n)))}u.prototype=this;const f=new u(this);return s(this,f),f.child=function(...e){return k.call(this,t,...e)},f.level=i.level||this.level,t.onChild(f),f}return w.levels=function(e){const t=e.customLevels||{},r=Object.assign({},c.levels.values,t),n=Object.assign({},c.levels.labels,function(e){const t={};return Object.keys(e).forEach((function(r){t[e[r]]=r})),t}(t));return{values:r,labels:n}}(e),w.level=v,w.setMaxListeners=w.getMaxListeners=w.emit=w.addListener=w.on=w.prependListener=w.once=w.prependOnceListener=w.removeListener=w.removeAllListeners=w.listeners=w.listenerCount=w.eventNames=w.write=w.flush=g,w.serializers=p,w._serialize=h,w._stdErrSerialize=m,w.child=function(...e){return k.call(this,_,...e)},r&&(w._logEvent=d()),w}function u(r,a,s,c){if(Object.defineProperty(r,c,{value:n(r.level,s)>n(c,s)?g:s[i][c],writable:!0,enumerable:!0,configurable:!0}),r[c]===g){if(!a.transmit)return;const e=n(a.transmit.level||r.level,s);if(n(c,s)<e)return}r[c]=function(r,o,a,s){return function(i){return function(){const c=o.timestamp(),u=new Array(arguments.length),p=Object.getPrototypeOf&&Object.getPrototypeOf(this)===t?t:this;for(var f=0;f<u.length;f++)u[f]=arguments[f];var h=!1;if(o.serialize&&(l(u,this._serialize,this.serializers,this._stdErrSerialize),h=!0),o.asObject||o.formatters?i.call(p,function(t,r,n,i,o){const{level:a,log:s=e=>e}=o.formatters||{},c=n.slice();let u=c[0];const l={};i&&(l.time=i);if(a){const e=a(r,t.levels.values[r]);Object.assign(l,e)}else l.level=t.levels.values[r];let d=1+(0|t._childLevel);d<1&&(d=1);if(null!==u&&"object"==typeof u){for(;d--&&"object"==typeof c[0];)Object.assign(l,c.shift());u=c.length?e(c.shift(),c):void 0}else"string"==typeof u&&(u=e(c.shift(),c));void 0!==u&&(l[o.messageKey]=u);return s(l)}(this,s,u,c,o)):i.apply(p,u),o.transmit){const e=n(o.transmit.level||r._level,a),t=n(s,a);if(t<e)return;!function(e,t,r,n=!1){const i=t.send,o=t.ts,a=t.methodLevel,s=t.methodValue,c=t.val,u=e._logEvent.bindings;n||l(r,e._serialize||Object.keys(e.serializers),e.serializers,void 0===e._stdErrSerialize||e._stdErrSerialize);e._logEvent.ts=o,e._logEvent.messages=r.filter((function(e){return-1===u.indexOf(e)})),e._logEvent.level.label=a,e._logEvent.level.value=s,i(a,e._logEvent,c),e._logEvent=d(u)}(this,{ts:c,methodLevel:s,methodValue:t,transmitValue:a.levels.values[o.transmit.level||r._level],send:o.transmit.send,val:n(r._level,a)},u,h)}}}(r[i][s])}(r,a,s,c);const u=function(e){const t=[];e.bindings&&t.push(e.bindings);let r=e[o];for(;r.parent;)r=r.parent,r.logger.bindings&&t.push(r.logger.bindings);return t.reverse()}(r);0!==u.length&&(r[c]=function(e,t){return function(){return t.apply(this,[...e,...arguments])}}(u,r[c]))}function l(e,t,r,n){for(const i in e)if(n&&e[i]instanceof Error)e[i]=c.stdSerializers.err(e[i]);else if("object"==typeof e[i]&&!Array.isArray(e[i])&&t)for(const n in e[i])t.indexOf(n)>-1&&n in r&&(e[i][n]=r[n](e[i][n]))}function d(e){return{ts:0,messages:[],bindings:e||[],level:{label:"",value:0}}}function p(e){const t={type:e.constructor.name,msg:e.message,stack:e.stack};for(const r in e)void 0===t[r]&&(t[r]=e[r]);return t}function f(e){return"function"==typeof e.timestamp?e.timestamp:!1===e.timestamp?y:b}function h(){return{}}function m(e){return e}function g(){}function y(){return!1}function b(){return Date.now()}return c.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},c.stdSerializers=r,c.stdTimeFunctions=Object.assign({},{nullTime:y,epochTime:b,unixTime:function(){return Math.round(Date.now()/1e3)},isoTime:function(){return new Date(Date.now()).toISOString()}}),browser$g.exports.default=c,browser$g.exports.pino=c,browser$g.exports}var browserExports$2=requireBrowser$f();const e$c=getDefaultExportFromCjs$3(browserExports$2);let Logger$3=(_a2=class{constructor(e={}){const t="true"===process$1$2.env.DISABLE_LOGS,r=e.silent||t,n=r?"silent":e.level||"info";this.moduleContext=e.module||"app";const i={level:n,enabled:!r,transport:!r&&!1!==e.prettyPrint?{target:"pino-pretty",options:{colorize:!0,translateTime:"SYS:standard",ignore:"pid,hostname"}}:void 0};this.logger=e$c(i)}static getInstance(e={}){const t=e.module||"default";if("true"===process$1$2.env.DISABLE_LOGS&&_a2.instances.has(t)){"silent"!==_a2.instances.get(t).getLevel()&&_a2.instances.delete(t)}return _a2.instances.has(t)||_a2.instances.set(t,new _a2(e)),_a2.instances.get(t)}setLogLevel(e){this.logger.level=e}getLevel(){return this.logger.level}setSilent(e){e&&(this.logger.level="silent")}setModule(e){this.moduleContext=e}debug(...e){this.logger.debug({module:this.moduleContext},...e)}info(...e){this.logger.info({module:this.moduleContext},...e)}warn(...e){this.logger.warn({module:this.moduleContext},...e)}error(...e){this.logger.error({module:this.moduleContext},...e)}trace(...e){this.logger.trace({module:this.moduleContext},...e)}},_a2.instances=new Map,_a2);const sleep$1=e=>new Promise((t=>setTimeout(t,e)));class HCS{constructor(){this.modelViewerLoaded=!1,this.modelViewerLoading=null,this.config={cdnUrl:"https://kiloscribe.com/api/inscription-cdn/",network:"mainnet",retryAttempts:3,retryBackoff:300,debug:!1,showLoadingIndicator:!1,loadingCallbackName:null},this.configMapping={hcsCdnUrl:"cdnUrl",hcsNetwork:"network",hcsRetryAttempts:"retryAttempts",hcsRetryBackoff:"retryBackoff",hcsDebug:"debug",hcsShowLoadingIndicator:"showLoadingIndicator",hcsLoadingCallbackName:"loadingCallbackName"},this.LoadedScripts={},this.LoadedWasm={},this.LoadedImages={},this.LoadedVideos={},this.LoadedAudios={},this.LoadedAudioUrls={},this.LoadedGLBs={},this.scriptLoadedEvent=new Event("HCSScriptLoaded"),this.loadQueue=[],this.isProcessingQueue=!1;try{this.logger=Logger$3.getInstance({module:"HCS-3",level:this.config.debug?"debug":"error"})}catch(e){this.logger=this.createFallbackLogger()}}createFallbackLogger(){return{debug:(...e)=>this.config.debug&&console.debug("[HCS-3]",...e),info:(...e)=>this.config.debug&&console.info("[HCS-3]",...e),warn:(...e)=>console.warn("[HCS-3]",...e),error:(...e)=>console.error("[HCS-3]",...e),setLogLevel:e=>{this.config.debug="debug"===e}}}log(...e){if(0===e.length)this.logger.debug("");else if(1===e.length)this.logger.debug(String(e[0]));else{const t=String(e[0]),r=e.slice(1);this.logger.debug(t,r)}}error(...e){if(0===e.length)this.logger.error("");else if(1===e.length)this.logger.error(String(e[0]));else{const t=String(e[0]),r=e.slice(1);this.logger.error(t,r)}}loadConfigFromHTML(){const e=document.querySelector("script[data-hcs-config]");e&&(Object.keys(this.configMapping).forEach((t=>{if(e.dataset[t]){const r=this.configMapping[t];let n=e.dataset[t];"true"===n&&(n=!0),"false"===n&&(n=!1),isNaN(Number(n))||""===n||(n=Number(n)),this.config[r]=n}})),this.logger.setLogLevel(this.config.debug?"debug":"error")),this.log("Loaded config:",this.config)}updateLoadingStatus(e,t){if("loaded"!==this.LoadedScripts[e]&&(this.config.showLoadingIndicator&&console.log("[HCS Loading] "+e+" : "+t),this.LoadedScripts[e]=t,this.config.loadingCallbackName&&"function"==typeof window[this.config.loadingCallbackName])){const r=window[this.config.loadingCallbackName];"function"==typeof r&&r(e,t)}}async fetchWithRetry(e,t=this.config.retryAttempts,r=this.config.retryBackoff){try{const t=await fetch(e);if(!t.ok)throw new Error("HTTP error! status: "+t.status);return t}catch(n){if(t>0)return this.log("Retrying fetch for "+e+" Attempts left: "+(t-1)),await this.sleep(r),this.fetchWithRetry(e,t-1,2*r);throw n}}sleep(e){return new Promise((t=>setTimeout(t,e)))}isDuplicate(e){return!!this.LoadedScripts[e]}async retrieveHCS1Data(e,t=this.config.cdnUrl,r=this.config.network){const n=r.replace(/['"]+/g,""),i=await this.fetchWithRetry(t+e+"?network="+n);return await i.blob()}async loadScript(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),n=t?.split("/").pop(),i=e.getAttribute("type"),o=e.hasAttribute("data-required"),a="module"===e.getAttribute("type");if(!this.isDuplicate(n||"")){this.updateLoadingStatus(r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,s=e.getAttribute("data-network")||this.config.network,c=await this.retrieveHCS1Data(n,t,s);if("wasm"===i){const t=await c.arrayBuffer(),n=await WebAssembly.compile(t);this.LoadedWasm[r]=await WebAssembly.instantiate(n,{env:{},...e.dataset}),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded wasm: "+r)}else{const e=await c.text(),t=document.createElement("script");if(t.textContent=e,t.className="hcs-inline-script",r&&t.setAttribute("data-loaded-script-id",r),a){t.type="module";const r=new Blob([e],{type:"application/javascript"});t.src=URL.createObjectURL(r)}document.body.appendChild(t),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded script: "+r),t.onerror=e=>{if(this.error("Failed to load "+i+": "+r,e),this.updateLoadingStatus(r,"failed"),o)throw e}}}catch(s){if(this.error("Failed to load "+i+": "+r,s),this.updateLoadingStatus(r,"failed"),o)throw s}}}async loadModuleExports(e){const t=document.querySelector('script[data-loaded-script-id="'+e+'"]');if(!t)throw new Error("Module script with id "+e+" not found");const r=t.getAttribute("src");if(!r)throw new Error("Module script "+e+" has no src attribute");try{return await import(r)}catch(n){throw this.error("Failed to import module",n),n}}async loadStylesheet(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),n=t?.split("/").pop(),i=e.hasAttribute("data-required");if(!this.isDuplicate(n||"")){this.updateLoadingStatus(r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,i=e.getAttribute("data-network")||this.config.network,o=await this.retrieveHCS1Data(n,t,i),a=await o.text(),s=document.createElement("style");s.textContent=a,document.head.appendChild(s),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded and inlined stylesheet: "+r)}catch(o){if(this.error("Failed to load stylesheet: "+r,o),this.updateLoadingStatus(r,"failed"),i)throw o}}}async loadImage(e){const t=e.getAttribute("data-src"),r=t?.split("/").pop();this.log("Loading image: "+r),this.updateLoadingStatus("Image: "+r,"loaded");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,n=e.getAttribute("data-network")||this.config.network,i=await this.retrieveHCS1Data(r,t,n),o=URL.createObjectURL(i);e.src=o,this.LoadedImages[r]=o,this.updateLoadingStatus("Image: "+r,"loaded"),this.log("Loaded image: "+r)}catch(n){this.error("Failed to load image: "+r,n),this.updateLoadingStatus("Image: "+r,"failed")}}async loadMedia(e,t){const r=e.getAttribute("data-src"),n=r?.split("/").pop();this.log("Loading "+t+": "+n),this.updateLoadingStatus(t+": "+n,"loading");try{const r=e.getAttribute("data-cdn-url")||this.config.cdnUrl,i=e.getAttribute("data-network")||this.config.network,o=await this.retrieveHCS1Data(n,r,i),a=URL.createObjectURL(o);e.src=a,"video"===t?this.LoadedVideos[n]=a:this.LoadedAudioUrls[n]=a,this.updateLoadingStatus(t+": "+n,"loaded"),this.log("Loaded "+t+": "+n)}catch(i){this.error("Failed to load "+t+": "+n,i),this.updateLoadingStatus(t+": "+n,"failed")}}async loadModelViewer(){return this.modelViewerLoading?this.modelViewerLoading:this.modelViewerLoaded?Promise.resolve():(this.modelViewerLoading=new Promise((e=>{const t=document.createElement("script");t.setAttribute("data-src","hcs://1/0.0.7293044"),t.setAttribute("data-script-id","model-viewer"),t.setAttribute("type","module"),window.addEventListener("HCSScriptLoaded",(()=>{this.modelViewerLoaded=!0,e()}),{once:!0}),this.loadScript(t)})),this.modelViewerLoading)}async loadGLB(e){await this.loadModelViewer();const t=e.getAttribute("data-src"),r=t?.split("/").pop();this.log("Loading GLB: "+r),this.updateLoadingStatus("GLB: "+r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,n=e.getAttribute("data-network")||this.config.network;let i;"model-viewer"!==e.tagName.toLowerCase()?(i=document.createElement("model-viewer"),Array.from(e.attributes).forEach((e=>{i.setAttribute(e.name,e.value)})),i.setAttribute("camera-controls",""),i.setAttribute("auto-rotate",""),i.setAttribute("ar",""),e.parentNode?.replaceChild(i,e)):i=e;const o=await this.retrieveHCS1Data(r,t,n),a=URL.createObjectURL(o);i.setAttribute("src",a),this.LoadedGLBs[r]=a,this.updateLoadingStatus("GLB: "+r,"loaded"),this.log("Loaded GLB: "+r)}catch(n){this.error("Failed to load GLB: "+r,n),this.updateLoadingStatus("GLB: "+r,"failed")}}async loadResource(e,t,r){return new Promise((n=>{this.loadQueue.push({element:e,type:t,order:r,resolve:n}),this.processQueue()}))}async processQueue(){if(!this.isProcessingQueue){for(this.isProcessingQueue=!0;this.loadQueue.length>0;){const t=this.loadQueue.shift();try{"script"===t.type?await this.loadScript(t.element):"image"===t.type?await this.loadImage(t.element):"video"===t.type||"audio"===t.type?await this.loadMedia(t.element,t.type):"glb"===t.type?await this.loadGLB(t.element):"css"===t.type&&await this.loadStylesheet(t.element),t.resolve()}catch(e){if(this.error("Error processing queue item:",e),"script"===t.type&&t.element.hasAttribute("data-required"))break}}this.isProcessingQueue=!1}}async replaceHCSInStyle(e){let t=e,r=t.indexOf("hcs://");for(;-1!==r;){let e=r;for(;e<t.length&&!["'",'"'," ",")"].includes(t[e]);)e++;const i=t.substring(r,e),o=i.split("/").pop();try{const n=this.config.cdnUrl,a=this.config.network,s=await this.retrieveHCS1Data(o,n,a),c=URL.createObjectURL(s);t=t.substring(0,r)+c+t.substring(e),this.LoadedImages[o]=c,this.log("Replaced CSS HCS URL: "+i+" with "+c)}catch(n){this.error("Failed to load CSS image: "+o,n)}r=t.indexOf("hcs://",r+1)}return t}async processInlineStyles(){const e=document.querySelectorAll('[style*="hcs://"]');this.log("Found "+e.length+" elements with HCS style references");for(const r of Array.from(e)){const e=r.getAttribute("style");if(e){this.log("Processing style: "+e);const t=await this.replaceHCSInStyle(e);e!==t&&(r.setAttribute("style",t),this.log("Updated style to: "+t))}}const t=document.querySelectorAll("style");for(const r of Array.from(t))if(r.textContent?.includes("hcs://")){const e=await this.replaceHCSInStyle(r.textContent);r.textContent!==e&&(r.textContent=e)}}async init(){return this.loadConfigFromHTML(),new Promise((e=>{const t=async()=>{const t=document.querySelectorAll('script[data-src^="hcs://"]'),r=document.querySelectorAll('img[data-src^="hcs://"], img[src^="hcs://"]'),n=document.querySelectorAll('video[data-src^="hcs://"], video[src^="hcs://"]'),i=document.querySelectorAll('audio[data-src^="hcs://"], audio[src^="hcs://"]'),o=document.querySelectorAll('model-viewer[data-src^="hcs://"]'),a=document.querySelectorAll('link[data-src^="hcs://"]');document.querySelectorAll('[src^="hcs://"]').forEach((e=>{const t=e.getAttribute("src");t&&(e.setAttribute("data-src",t),e.removeAttribute("src"))})),await this.processInlineStyles();const s=[];[{elements:t,type:"script"},{elements:r,type:"image"},{elements:n,type:"video"},{elements:i,type:"audio"},{elements:o,type:"glb"},{elements:a,type:"css"}].forEach((({elements:e,type:t})=>{e.forEach((e=>{const r=parseInt(e.getAttribute("data-load-order")||"")||1/0;s.push(this.loadResource(e,t,r))}))})),await Promise.all(s);const c=new MutationObserver((e=>{e.forEach((e=>{if(e.addedNodes.forEach((e=>{if(e.nodeType===Node.ELEMENT_NODE){const t=e;if(t.getAttribute("style")?.includes("hcs://")&&this.processInlineStyles(),"style"===t.tagName.toLowerCase()&&t.textContent?.includes("hcs://")&&this.processInlineStyles(),t.getAttribute("src")?.startsWith("hcs://")){const e=t.getAttribute("src");t.setAttribute("data-src",e),t.removeAttribute("src");switch(t.tagName.toLowerCase()){case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"script":this.loadResource(t,"script",1/0)}}t.matches('script[data-src^="hcs://"]')?this.loadResource(t,"script",1/0):t.matches('img[data-src^="hcs://"]')?this.loadResource(t,"image",1/0):t.matches('video[data-src^="hcs://"]')?this.loadResource(t,"video",1/0):t.matches('audio[data-src^="hcs://"]')?this.loadResource(t,"audio",1/0):t.matches('model-viewer[data-src^="hcs://"]')?this.loadResource(t,"glb",1/0):t.matches('link[data-src^="hcs://"]')&&this.loadResource(t,"css",1/0);t.querySelectorAll('[data-src^="hcs://"], [src^="hcs://"]').forEach((e=>{const t=e,r=t.tagName.toLowerCase(),n=t.getAttribute("src");switch(n?.startsWith("hcs://")&&(t.setAttribute("data-src",n),t.removeAttribute("src")),r){case"script":this.loadResource(t,"script",1/0);break;case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"model-viewer":this.loadResource(t,"glb",1/0);break;case"link":this.loadResource(t,"css",1/0)}}))}})),"attributes"===e.type){const t=e.target;if("style"===e.attributeName&&t.getAttribute("style")?.includes("hcs://"))this.processInlineStyles();else if("src"===e.attributeName){const e=t.getAttribute("src");if(e?.startsWith("hcs://")){t.setAttribute("data-src",e),t.removeAttribute("src");const r=t.tagName.toLowerCase();["img","video","audio"].includes(r)&&this.loadResource(t,r,1/0)}}}}))}));document.body?c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]}):document.addEventListener("DOMContentLoaded",(()=>{c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]})})),e()};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()}))}async preloadImage(e){this.log("Loading image:"+e),this.updateLoadingStatus("image: "+e,"loading");const t=await this.retrieveHCS1Data(e),r=URL.createObjectURL(t);return this.LoadedImages[e]=r,this.updateLoadingStatus("image: "+e,"loaded"),r}async preloadAudio(e){const t=document.createElement("audio");t.setAttribute("data-topic-id",e),t.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(t),await this.loadMedia(t,"audio");const r=document.querySelector('audio[data-topic-id="'+e+'"]');return r?this.LoadedAudioUrls[e]=r.src:console.error("Failed to preload audio: "+e),this.LoadedAudioUrls[e]}async playAudio(e,t=1){const r=this.LoadedAudioUrls[e];if(r){const n=new Audio(r);n.volume=t,this.LoadedAudios[e]=n,n.play().catch((e=>{console.error("Failed to play audio:",e)})),n.addEventListener("ended",(()=>{n.remove(),delete this.LoadedAudios[e]}))}else console.error("Audio not preloaded: "+e)}async pauseAudio(e){const t=document.querySelector('audio[data-topic-id="'+e+'"]');t?(console.log("found element",t),t.pause(),this.LoadedAudios[e]?.pause()):this.LoadedAudios[e]?.pause()}async loadAndPlayAudio(e,t=!1,r=1){let n=document.querySelector('audio[data-topic-id="'+e+'"]');if(n)n.volume=r,await n.play();else{const i=document.createElement("audio");i.volume=r,t&&i.setAttribute("autoplay","autoplay"),i.setAttribute("data-topic-id",e),i.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(i),await this.loadMedia(i,"audio"),n=document.querySelector('audio[data-topic-id="'+e+'"]'),t||await n.play()}}}class WasmBridge{constructor(){this.wasm=null,this.WASM_VECTOR_LEN=0,this.cachedUint8Memory=null,this.cachedDataViewMemory=null,this.textEncoder=new TextEncoder,this.textDecoder=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),this.textDecoder.decode(),this.logger=Logger$3.getInstance({module:"WasmBridge"})}setLogLevel(e){this.logger.setLogLevel(e)}get wasmInstance(){if(!this.wasm)throw new Error("WASM not initialized");return this.wasm}getUint8Memory(){if(!this.wasm)throw new Error("WASM not initialized");return null!==this.cachedUint8Memory&&0!==this.cachedUint8Memory.byteLength||(this.cachedUint8Memory=new Uint8Array(this.wasm.memory.buffer)),this.cachedUint8Memory}getDataViewMemory(){if(!this.wasm)throw new Error("WASM not initialized");return null!==this.cachedDataViewMemory&&this.cachedDataViewMemory.buffer===this.wasm.memory.buffer||(this.cachedDataViewMemory=new DataView(this.wasm.memory.buffer)),this.cachedDataViewMemory}encodeString(e,t){if(0===e.length)return{read:0,written:0};const r=this.textEncoder.encode(e);return t.set(r),{read:e.length,written:r.length}}passStringToWasm(e,t,r){if(void 0===r){const r=this.textEncoder.encode(e),n=t(r.length,1);return this.getUint8Memory().set(r,n),this.WASM_VECTOR_LEN=r.length,n}let n=this.textEncoder.encode(e).length,i=t(n,1);const o=this.getUint8Memory();let a=0;for(;a<n;a++){const t=e.charCodeAt(a);if(t>127)break;o[i+a]=t}if(a!==n){0!==a&&(e=e.slice(a)),i=r(i,n,n=a+3*this.textEncoder.encode(e).length,1);const t=this.getUint8Memory().subarray(i+a,i+n);a+=this.encodeString(e,t).written}return this.WASM_VECTOR_LEN=a,i}getStringFromWasm(e,t){return e>>>=0,this.textDecoder.decode(this.getUint8Memory().subarray(e,e+t))}createWasmFunction(e){if(!this.wasm)throw new Error("WASM not initialized");return(...t)=>{const r=this.wasm.__wbindgen_add_to_stack_pointer(-16);let n=[0,0];try{const i=[r,...t.map((e=>[this.passStringToWasm(e,this.wasm.__wbindgen_malloc,this.wasm.__wbindgen_realloc),this.WASM_VECTOR_LEN])).flat()];e.apply(this.wasm,i);const o=this.getDataViewMemory().getInt32(r+0,!0),a=this.getDataViewMemory().getInt32(r+4,!0);return n=[o,a],this.getStringFromWasm(o,a)}finally{this.wasm.__wbindgen_add_to_stack_pointer(16),this.wasm.__wbindgen_free(n[0],n[1],1)}}}async initWasm(e){const t=this,r={__wbindgen_placeholder__:{__wbindgen_throw:function(e,r){const n=t.getStringFromWasm(e,r);throw t.logger.error(`WASM error: ${n}`),new Error(n)}}};try{this.logger.debug("Compiling WASM module");const t=await WebAssembly.compile(e);this.logger.debug("Instantiating WASM module");const n=await WebAssembly.instantiate(t,r);return this.wasm=n.exports,this.logger.info("WASM module initialized successfully"),this.wasm}catch(n){throw this.logger.error("Failed to initialize WASM module",n),n}}createStateData(e,t={}){let r={};return e?.c?.inputType?.stateData&&(t.latestRoundData&&Object.keys(e.c.inputType.stateData).every((e=>e in t.latestRoundData))?(r.latestRoundData={},Object.entries(e.c.inputType.stateData).forEach((([e,n])=>{r.latestRoundData[e]=String(t.latestRoundData[e])}))):Object.entries(e.c.inputType.stateData).forEach((([e,n])=>{const i=t[e];i&&"object"==typeof i&&"values"in i&&i.values.length>0?r[e]=String(i.values[0]):r[e]=this.getDefaultValueForType(n)}))),r}getDefaultValueForType(e){return e.startsWith("uint")||e.startsWith("int")||"number"===e?"0":"bool"===e?"false":""}executeWasm(e,t){if(!this.wasm)throw this.logger.error("WASM not initialized"),new Error("WASM not initialized");try{this.logger.debug("Executing WASM with stateData",e);return this.createWasmFunction(this.wasmInstance.process_state)(JSON.stringify(e),JSON.stringify(t))}catch(r){throw this.logger.error("Error executing WASM",r),r}}getParams(){return this.createWasmFunction(this.wasmInstance.get_params)()}}
|
|
1
|
+
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).StandardsSDK={})}(this,(function(exports){"use strict";var __defProp3=Object.defineProperty,__typeError=e=>{throw TypeError(e)},__defNormalProp3=(e,t,r)=>t in e?__defProp3(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r,__publicField3=(e,t,r)=>__defNormalProp3(e,"symbol"!=typeof t?t+"":t,r),__accessCheck=(e,t,r)=>t.has(e)||__typeError("Cannot "+r),__privateGet=(e,t,r)=>(__accessCheck(e,t,"read from private field"),r?r.call(e):t.get(e)),__privateAdd=(e,t,r)=>t.has(e)?__typeError("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,r),__privateSet=(e,t,r,n)=>(__accessCheck(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r),__privateMethod=(e,t,r)=>(__accessCheck(e,t,"access private method"),r),__privateWrapper=(e,t,r,n)=>({set _(n){__privateSet(e,t,n,r)},get _(){return __privateGet(e,t,n)}}),_a2,_names,_data,_dataLength,_Writer_instances,writeData_fn,_data2,_offset,_bytesRead,_parent,_maxInflation,_Reader_instances,incrementBytesRead_fn,peekBytes_fn,_options,_offset2,_tokens,_TokenString_instances,subTokenString_fn,_ParamType_instances,walkAsync_fn,_AbiCoder_instances,getCoder_fn,_errors,_events,_functions,_abiCoder,_Interface_instances,getFunction_fn,getEvent_fn;function _mergeNamespaces(e,t){for(var r=0;r<t.length;r++){const n=t[r];if("string"!=typeof n&&!Array.isArray(n))for(const t in n)if("default"!==t&&!(t in e)){const r=Object.getOwnPropertyDescriptor(n,t);r&&Object.defineProperty(e,t,r.get?r:{enumerable:!0,get:()=>n[t]})}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}function getDefaultExportFromCjs$4(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var browser$h={exports:{}},process$3=browser$h.exports={},cachedSetTimeout$2,cachedClearTimeout$2;function defaultSetTimout$2(){throw new Error("setTimeout has not been defined")}function defaultClearTimeout$2(){throw new Error("clearTimeout has not been defined")}function runTimeout$2(e){if(cachedSetTimeout$2===setTimeout)return setTimeout(e,0);if((cachedSetTimeout$2===defaultSetTimout$2||!cachedSetTimeout$2)&&setTimeout)return cachedSetTimeout$2=setTimeout,setTimeout(e,0);try{return cachedSetTimeout$2(e,0)}catch(t){try{return cachedSetTimeout$2.call(null,e,0)}catch(r){return cachedSetTimeout$2.call(this,e,0)}}}function runClearTimeout$2(e){if(cachedClearTimeout$2===clearTimeout)return clearTimeout(e);if((cachedClearTimeout$2===defaultClearTimeout$2||!cachedClearTimeout$2)&&clearTimeout)return cachedClearTimeout$2=clearTimeout,clearTimeout(e);try{return cachedClearTimeout$2(e)}catch(t){try{return cachedClearTimeout$2.call(null,e)}catch(r){return cachedClearTimeout$2.call(this,e)}}}!function(){try{cachedSetTimeout$2="function"==typeof setTimeout?setTimeout:defaultSetTimout$2}catch(e){cachedSetTimeout$2=defaultSetTimout$2}try{cachedClearTimeout$2="function"==typeof clearTimeout?clearTimeout:defaultClearTimeout$2}catch(e){cachedClearTimeout$2=defaultClearTimeout$2}}();var queue$2=[],draining$2=!1,currentQueue$2,queueIndex$2=-1;function cleanUpNextTick$2(){draining$2&¤tQueue$2&&(draining$2=!1,currentQueue$2.length?queue$2=currentQueue$2.concat(queue$2):queueIndex$2=-1,queue$2.length&&drainQueue$2())}function drainQueue$2(){if(!draining$2){var e=runTimeout$2(cleanUpNextTick$2);draining$2=!0;for(var t=queue$2.length;t;){for(currentQueue$2=queue$2,queue$2=[];++queueIndex$2<t;)currentQueue$2&¤tQueue$2[queueIndex$2].run();queueIndex$2=-1,t=queue$2.length}currentQueue$2=null,draining$2=!1,runClearTimeout$2(e)}}function Item$2(e,t){this.fun=e,this.array=t}function noop$5(){}process$3.nextTick=function(e){var t=new Array(arguments.length-1);if(arguments.length>1)for(var r=1;r<arguments.length;r++)t[r-1]=arguments[r];queue$2.push(new Item$2(e,t)),1!==queue$2.length||draining$2||runTimeout$2(drainQueue$2)},Item$2.prototype.run=function(){this.fun.apply(null,this.array)},process$3.title="browser",process$3.browser=!0,process$3.env={},process$3.argv=[],process$3.version="",process$3.versions={},process$3.on=noop$5,process$3.addListener=noop$5,process$3.once=noop$5,process$3.off=noop$5,process$3.removeListener=noop$5,process$3.removeAllListeners=noop$5,process$3.emit=noop$5,process$3.prependListener=noop$5,process$3.prependOnceListener=noop$5,process$3.listeners=function(e){return[]},process$3.binding=function(e){throw new Error("process.binding is not supported")},process$3.cwd=function(){return"/"},process$3.chdir=function(e){throw new Error("process.chdir is not supported")},process$3.umask=function(){return 0};var browserExports$3=browser$h.exports;const process$1$2=getDefaultExportFromCjs$4(browserExports$3);var commonjsGlobal$2="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function getDefaultExportFromCjs$3(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var browser$g={exports:{}},quickFormatUnescaped$1,hasRequiredQuickFormatUnescaped$1,hasRequiredBrowser$f;function requireQuickFormatUnescaped$1(){if(hasRequiredQuickFormatUnescaped$1)return quickFormatUnescaped$1;function e(e){try{return JSON.stringify(e)}catch(t){return'"[Circular]"'}}return hasRequiredQuickFormatUnescaped$1=1,quickFormatUnescaped$1=function(t,r,n){var i=n&&n.stringify||e;if("object"==typeof t&&null!==t){var o=r.length+1;if(1===o)return t;var a=new Array(o);a[0]=i(t);for(var s=1;s<o;s++)a[s]=i(r[s]);return a.join(" ")}if("string"!=typeof t)return t;var c=r.length;if(0===c)return t;for(var u="",l=0,d=-1,p=t&&t.length||0,f=0;f<p;){if(37===t.charCodeAt(f)&&f+1<p){switch(d=d>-1?d:0,t.charCodeAt(f+1)){case 100:case 102:if(l>=c)break;if(null==r[l])break;d<f&&(u+=t.slice(d,f)),u+=Number(r[l]),d=f+2,f++;break;case 105:if(l>=c)break;if(null==r[l])break;d<f&&(u+=t.slice(d,f)),u+=Math.floor(Number(r[l])),d=f+2,f++;break;case 79:case 111:case 106:if(l>=c)break;if(void 0===r[l])break;d<f&&(u+=t.slice(d,f));var h=typeof r[l];if("string"===h){u+="'"+r[l]+"'",d=f+2,f++;break}if("function"===h){u+=r[l].name||"<anonymous>",d=f+2,f++;break}u+=i(r[l]),d=f+2,f++;break;case 115:if(l>=c)break;d<f&&(u+=t.slice(d,f)),u+=String(r[l]),d=f+2,f++;break;case 37:d<f&&(u+=t.slice(d,f)),u+="%",d=f+2,f++,l--}++l}++f}if(-1===d)return t;d<p&&(u+=t.slice(d));return u}}function requireBrowser$f(){if(hasRequiredBrowser$f)return browser$g.exports;hasRequiredBrowser$f=1;const e=requireQuickFormatUnescaped$1();browser$g.exports=c;const t=function(){function e(e){return void 0!==e&&e}try{return"undefined"!=typeof globalThis||Object.defineProperty(Object.prototype,"globalThis",{get:function(){return delete Object.prototype.globalThis,this.globalThis=this},configurable:!0}),globalThis}catch(t){return e(self)||e(window)||e(this)||{}}}().console||{},r={mapHttpRequest:h,mapHttpResponse:h,wrapRequestSerializer:m,wrapResponseSerializer:m,wrapErrorSerializer:m,req:h,res:h,err:p,errWithCause:p};function n(e,t){return"silent"===e?1/0:t.levels.values[e]}const i=Symbol("pino.logFuncs"),o=Symbol("pino.hierarchy"),a={error:"log",fatal:"error",warn:"error",info:"log",debug:"log",trace:"log"};function s(e,t){const r={logger:t,parent:e[o]};t[o]=r}function c(e){(e=e||{}).browser=e.browser||{};const r=e.browser.transmit;if(r&&"function"!=typeof r.send)throw Error("pino: transmit option must have a send function");const o=e.browser.write||t;e.browser.write&&(e.browser.asObject=!0);const p=e.serializers||{},h=function(e,t){if(Array.isArray(e))return e.filter((function(e){return"!stdSerializers.err"!==e}));return!0===e&&Object.keys(t)}(e.browser.serialize,p);let m=e.browser.serialize;Array.isArray(e.browser.serialize)&&e.browser.serialize.indexOf("!stdSerializers.err")>-1&&(m=!1);const y=Object.keys(e.customLevels||{}),b=["error","fatal","warn","info","debug","trace"].concat(y);"function"==typeof o&&b.forEach((function(e){o[e]=o})),(!1===e.enabled||e.browser.disabled)&&(e.level="silent");const v=e.level||"info",w=Object.create(o);w.log||(w.log=g),function(e,r,n){const o={};r.forEach((e=>{o[e]=n[e]?n[e]:t[e]||t[a[e]||"log"]||g})),e[i]=o}(w,b,o),s({},w),Object.defineProperty(w,"levelVal",{get:function(){return n(this.level,this)}}),Object.defineProperty(w,"level",{get:function(){return this._level},set:function(e){if("silent"!==e&&!this.levels.values[e])throw Error("unknown level "+e);this._level=e,u(this,_,w,"error"),u(this,_,w,"fatal"),u(this,_,w,"warn"),u(this,_,w,"info"),u(this,_,w,"debug"),u(this,_,w,"trace"),y.forEach((e=>{u(this,_,w,e)}))}});const _={transmit:r,serialize:h,asObject:e.browser.asObject,asObjectBindingsOnly:e.browser.asObjectBindingsOnly,formatters:e.browser.formatters,levels:b,timestamp:f(e),messageKey:e.messageKey||"msg",onChild:e.onChild||g};function k(t,n,i){if(!n)throw new Error("missing bindings for child Pino");i=i||{},h&&n.serializers&&(i.serializers=n.serializers);const o=i.serializers;if(h&&o){var a=Object.assign({},p,o),c=!0===e.browser.serialize?Object.keys(a):h;delete n.serializers,l([n],c,a,this._stdErrSerialize)}function u(e){this._childLevel=1+(0|e._childLevel),this.bindings=n,a&&(this.serializers=a,this._serialize=c),r&&(this._logEvent=d([].concat(e._logEvent.bindings,n)))}u.prototype=this;const f=new u(this);return s(this,f),f.child=function(...e){return k.call(this,t,...e)},f.level=i.level||this.level,t.onChild(f),f}return w.levels=function(e){const t=e.customLevels||{},r=Object.assign({},c.levels.values,t),n=Object.assign({},c.levels.labels,function(e){const t={};return Object.keys(e).forEach((function(r){t[e[r]]=r})),t}(t));return{values:r,labels:n}}(e),w.level=v,w.isLevelEnabled=function(e){return!!this.levels.values[e]&&this.levels.values[e]>=this.levels.values[this.level]},w.setMaxListeners=w.getMaxListeners=w.emit=w.addListener=w.on=w.prependListener=w.once=w.prependOnceListener=w.removeListener=w.removeAllListeners=w.listeners=w.listenerCount=w.eventNames=w.write=w.flush=g,w.serializers=p,w._serialize=h,w._stdErrSerialize=m,w.child=function(...e){return k.call(this,_,...e)},r&&(w._logEvent=d()),w}function u(r,a,s,c){if(Object.defineProperty(r,c,{value:n(r.level,s)>n(c,s)?g:s[i][c],writable:!0,enumerable:!0,configurable:!0}),r[c]===g){if(!a.transmit)return;const e=n(a.transmit.level||r.level,s);if(n(c,s)<e)return}r[c]=function(r,o,a,s){return function(i){return function(){const c=o.timestamp(),u=new Array(arguments.length),p=Object.getPrototypeOf&&Object.getPrototypeOf(this)===t?t:this;for(var f=0;f<u.length;f++)u[f]=arguments[f];var h=!1;if(o.serialize&&(l(u,this._serialize,this.serializers,this._stdErrSerialize),h=!0),o.asObject||o.formatters?i.call(p,...function(t,r,n,i,o){const{level:a,log:s=e=>e}=o.formatters||{},c=n.slice();let u=c[0];const l={};let d=1+(0|t._childLevel);d<1&&(d=1);i&&(l.time=i);if(a){const e=a(r,t.levels.values[r]);Object.assign(l,e)}else l.level=t.levels.values[r];if(o.asObjectBindingsOnly){if(null!==u&&"object"==typeof u)for(;d--&&"object"==typeof c[0];)Object.assign(l,c.shift());return[s(l),...c]}if(null!==u&&"object"==typeof u){for(;d--&&"object"==typeof c[0];)Object.assign(l,c.shift());u=c.length?e(c.shift(),c):void 0}else"string"==typeof u&&(u=e(c.shift(),c));void 0!==u&&(l[o.messageKey]=u);return[s(l)]}(this,s,u,c,o)):i.apply(p,u),o.transmit){const e=n(o.transmit.level||r._level,a),t=n(s,a);if(t<e)return;!function(e,t,r,n=!1){const i=t.send,o=t.ts,a=t.methodLevel,s=t.methodValue,c=t.val,u=e._logEvent.bindings;n||l(r,e._serialize||Object.keys(e.serializers),e.serializers,void 0===e._stdErrSerialize||e._stdErrSerialize);e._logEvent.ts=o,e._logEvent.messages=r.filter((function(e){return-1===u.indexOf(e)})),e._logEvent.level.label=a,e._logEvent.level.value=s,i(a,e._logEvent,c),e._logEvent=d(u)}(this,{ts:c,methodLevel:s,methodValue:t,transmitValue:a.levels.values[o.transmit.level||r._level],send:o.transmit.send,val:n(r._level,a)},u,h)}}}(r[i][s])}(r,a,s,c);const u=function(e){const t=[];e.bindings&&t.push(e.bindings);let r=e[o];for(;r.parent;)r=r.parent,r.logger.bindings&&t.push(r.logger.bindings);return t.reverse()}(r);0!==u.length&&(r[c]=function(e,t){return function(){return t.apply(this,[...e,...arguments])}}(u,r[c]))}function l(e,t,r,n){for(const i in e)if(n&&e[i]instanceof Error)e[i]=c.stdSerializers.err(e[i]);else if("object"==typeof e[i]&&!Array.isArray(e[i])&&t)for(const n in e[i])t.indexOf(n)>-1&&n in r&&(e[i][n]=r[n](e[i][n]))}function d(e){return{ts:0,messages:[],bindings:e||[],level:{label:"",value:0}}}function p(e){const t={type:e.constructor.name,msg:e.message,stack:e.stack};for(const r in e)void 0===t[r]&&(t[r]=e[r]);return t}function f(e){return"function"==typeof e.timestamp?e.timestamp:!1===e.timestamp?y:b}function h(){return{}}function m(e){return e}function g(){}function y(){return!1}function b(){return Date.now()}return c.levels={values:{fatal:60,error:50,warn:40,info:30,debug:20,trace:10},labels:{10:"trace",20:"debug",30:"info",40:"warn",50:"error",60:"fatal"}},c.stdSerializers=r,c.stdTimeFunctions=Object.assign({},{nullTime:y,epochTime:b,unixTime:function(){return Math.round(Date.now()/1e3)},isoTime:function(){return new Date(Date.now()).toISOString()}}),browser$g.exports.default=c,browser$g.exports.pino=c,browser$g.exports}var browserExports$2=requireBrowser$f();const e$c=getDefaultExportFromCjs$3(browserExports$2);let Logger$3=(_a2=class{constructor(e={}){const t="true"===process$1$2.env.DISABLE_LOGS,r=e.silent||t,n=r?"silent":e.level||"info";this.moduleContext=e.module||"app";const i={level:n,enabled:!r,transport:!r&&!1!==e.prettyPrint?{target:"pino-pretty",options:{colorize:!0,translateTime:"SYS:standard",ignore:"pid,hostname"}}:void 0};this.logger=e$c(i)}static getInstance(e={}){const t=e.module||"default";if("true"===process$1$2.env.DISABLE_LOGS&&_a2.instances.has(t)){"silent"!==_a2.instances.get(t).getLevel()&&_a2.instances.delete(t)}return _a2.instances.has(t)||_a2.instances.set(t,new _a2(e)),_a2.instances.get(t)}setLogLevel(e){this.logger.level=e}getLevel(){return this.logger.level}setSilent(e){e&&(this.logger.level="silent")}setModule(e){this.moduleContext=e}debug(...e){this.logger.debug({module:this.moduleContext},...e)}info(...e){this.logger.info({module:this.moduleContext},...e)}warn(...e){this.logger.warn({module:this.moduleContext},...e)}error(...e){this.logger.error({module:this.moduleContext},...e)}trace(...e){this.logger.trace({module:this.moduleContext},...e)}},_a2.instances=new Map,_a2);const sleep$1=e=>new Promise((t=>setTimeout(t,e)));class HCS{constructor(){this.modelViewerLoaded=!1,this.modelViewerLoading=null,this.config={cdnUrl:"https://kiloscribe.com/api/inscription-cdn/",network:"mainnet",retryAttempts:3,retryBackoff:300,debug:!1,showLoadingIndicator:!1,loadingCallbackName:null},this.configMapping={hcsCdnUrl:"cdnUrl",hcsNetwork:"network",hcsRetryAttempts:"retryAttempts",hcsRetryBackoff:"retryBackoff",hcsDebug:"debug",hcsShowLoadingIndicator:"showLoadingIndicator",hcsLoadingCallbackName:"loadingCallbackName"},this.LoadedScripts={},this.LoadedWasm={},this.LoadedImages={},this.LoadedVideos={},this.LoadedAudios={},this.LoadedAudioUrls={},this.LoadedGLBs={},this.scriptLoadedEvent=new Event("HCSScriptLoaded"),this.loadQueue=[],this.isProcessingQueue=!1;try{this.logger=Logger$3.getInstance({module:"HCS-3",level:this.config.debug?"debug":"error"})}catch(e){this.logger=this.createFallbackLogger()}}createFallbackLogger(){return{debug:(...e)=>this.config.debug&&console.debug("[HCS-3]",...e),info:(...e)=>this.config.debug&&console.info("[HCS-3]",...e),warn:(...e)=>console.warn("[HCS-3]",...e),error:(...e)=>console.error("[HCS-3]",...e),setLogLevel:e=>{this.config.debug="debug"===e}}}log(...e){if(0===e.length)this.logger.debug("");else if(1===e.length)this.logger.debug(String(e[0]));else{const t=String(e[0]),r=e.slice(1);this.logger.debug(t,r)}}error(...e){if(0===e.length)this.logger.error("");else if(1===e.length)this.logger.error(String(e[0]));else{const t=String(e[0]),r=e.slice(1);this.logger.error(t,r)}}loadConfigFromHTML(){const e=document.querySelector("script[data-hcs-config]");e&&(Object.keys(this.configMapping).forEach((t=>{if(e.dataset[t]){const r=this.configMapping[t];let n=e.dataset[t];"true"===n&&(n=!0),"false"===n&&(n=!1),isNaN(Number(n))||""===n||(n=Number(n)),this.config[r]=n}})),this.logger.setLogLevel(this.config.debug?"debug":"error")),this.log("Loaded config:",this.config)}updateLoadingStatus(e,t){if("loaded"!==this.LoadedScripts[e]&&(this.config.showLoadingIndicator&&console.log("[HCS Loading] "+e+" : "+t),this.LoadedScripts[e]=t,this.config.loadingCallbackName&&"function"==typeof window[this.config.loadingCallbackName])){const r=window[this.config.loadingCallbackName];"function"==typeof r&&r(e,t)}}async fetchWithRetry(e,t=this.config.retryAttempts,r=this.config.retryBackoff){try{const t=await fetch(e);if(!t.ok)throw new Error("HTTP error! status: "+t.status);return t}catch(n){if(t>0)return this.log("Retrying fetch for "+e+" Attempts left: "+(t-1)),await this.sleep(r),this.fetchWithRetry(e,t-1,2*r);throw n}}sleep(e){return new Promise((t=>setTimeout(t,e)))}isDuplicate(e){return!!this.LoadedScripts[e]}async retrieveHCS1Data(e,t=this.config.cdnUrl,r=this.config.network){const n=r.replace(/['"]+/g,""),i=await this.fetchWithRetry(t+e+"?network="+n);return await i.blob()}async loadScript(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),n=t?.split("/").pop(),i=e.getAttribute("type"),o=e.hasAttribute("data-required"),a="module"===e.getAttribute("type");if(!this.isDuplicate(n||"")){this.updateLoadingStatus(r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,s=e.getAttribute("data-network")||this.config.network,c=await this.retrieveHCS1Data(n,t,s);if("wasm"===i){const t=await c.arrayBuffer(),n=await WebAssembly.compile(t);this.LoadedWasm[r]=await WebAssembly.instantiate(n,{env:{},...e.dataset}),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded wasm: "+r)}else{const e=await c.text(),t=document.createElement("script");if(t.textContent=e,t.className="hcs-inline-script",r&&t.setAttribute("data-loaded-script-id",r),a){t.type="module";const r=new Blob([e],{type:"application/javascript"});t.src=URL.createObjectURL(r)}document.body.appendChild(t),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded script: "+r),t.onerror=e=>{if(this.error("Failed to load "+i+": "+r,e),this.updateLoadingStatus(r,"failed"),o)throw e}}}catch(s){if(this.error("Failed to load "+i+": "+r,s),this.updateLoadingStatus(r,"failed"),o)throw s}}}async loadModuleExports(e){const t=document.querySelector('script[data-loaded-script-id="'+e+'"]');if(!t)throw new Error("Module script with id "+e+" not found");const r=t.getAttribute("src");if(!r)throw new Error("Module script "+e+" has no src attribute");try{return await import(r)}catch(n){throw this.error("Failed to import module",n),n}}async loadStylesheet(e){const t=e.getAttribute("data-src"),r=e.getAttribute("data-script-id"),n=t?.split("/").pop(),i=e.hasAttribute("data-required");if(!this.isDuplicate(n||"")){this.updateLoadingStatus(r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,i=e.getAttribute("data-network")||this.config.network,o=await this.retrieveHCS1Data(n,t,i),a=await o.text(),s=document.createElement("style");s.textContent=a,document.head.appendChild(s),this.updateLoadingStatus(r,"loaded"),window.dispatchEvent(this.scriptLoadedEvent),this.log("Loaded and inlined stylesheet: "+r)}catch(o){if(this.error("Failed to load stylesheet: "+r,o),this.updateLoadingStatus(r,"failed"),i)throw o}}}async loadImage(e){const t=e.getAttribute("data-src"),r=t?.split("/").pop();this.log("Loading image: "+r),this.updateLoadingStatus("Image: "+r,"loaded");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,n=e.getAttribute("data-network")||this.config.network,i=await this.retrieveHCS1Data(r,t,n),o=URL.createObjectURL(i);e.src=o,this.LoadedImages[r]=o,this.updateLoadingStatus("Image: "+r,"loaded"),this.log("Loaded image: "+r)}catch(n){this.error("Failed to load image: "+r,n),this.updateLoadingStatus("Image: "+r,"failed")}}async loadMedia(e,t){const r=e.getAttribute("data-src"),n=r?.split("/").pop();this.log("Loading "+t+": "+n),this.updateLoadingStatus(t+": "+n,"loading");try{const r=e.getAttribute("data-cdn-url")||this.config.cdnUrl,i=e.getAttribute("data-network")||this.config.network,o=await this.retrieveHCS1Data(n,r,i),a=URL.createObjectURL(o);e.src=a,"video"===t?this.LoadedVideos[n]=a:this.LoadedAudioUrls[n]=a,this.updateLoadingStatus(t+": "+n,"loaded"),this.log("Loaded "+t+": "+n)}catch(i){this.error("Failed to load "+t+": "+n,i),this.updateLoadingStatus(t+": "+n,"failed")}}async loadModelViewer(){return this.modelViewerLoading?this.modelViewerLoading:this.modelViewerLoaded?Promise.resolve():(this.modelViewerLoading=new Promise((e=>{const t=document.createElement("script");t.setAttribute("data-src","hcs://1/0.0.7293044"),t.setAttribute("data-script-id","model-viewer"),t.setAttribute("type","module"),window.addEventListener("HCSScriptLoaded",(()=>{this.modelViewerLoaded=!0,e()}),{once:!0}),this.loadScript(t)})),this.modelViewerLoading)}async loadGLB(e){await this.loadModelViewer();const t=e.getAttribute("data-src"),r=t?.split("/").pop();this.log("Loading GLB: "+r),this.updateLoadingStatus("GLB: "+r,"loading");try{const t=e.getAttribute("data-cdn-url")||this.config.cdnUrl,n=e.getAttribute("data-network")||this.config.network;let i;"model-viewer"!==e.tagName.toLowerCase()?(i=document.createElement("model-viewer"),Array.from(e.attributes).forEach((e=>{i.setAttribute(e.name,e.value)})),i.setAttribute("camera-controls",""),i.setAttribute("auto-rotate",""),i.setAttribute("ar",""),e.parentNode?.replaceChild(i,e)):i=e;const o=await this.retrieveHCS1Data(r,t,n),a=URL.createObjectURL(o);i.setAttribute("src",a),this.LoadedGLBs[r]=a,this.updateLoadingStatus("GLB: "+r,"loaded"),this.log("Loaded GLB: "+r)}catch(n){this.error("Failed to load GLB: "+r,n),this.updateLoadingStatus("GLB: "+r,"failed")}}async loadResource(e,t,r){return new Promise((n=>{this.loadQueue.push({element:e,type:t,order:r,resolve:n}),this.processQueue()}))}async processQueue(){if(!this.isProcessingQueue){for(this.isProcessingQueue=!0;this.loadQueue.length>0;){const t=this.loadQueue.shift();try{"script"===t.type?await this.loadScript(t.element):"image"===t.type?await this.loadImage(t.element):"video"===t.type||"audio"===t.type?await this.loadMedia(t.element,t.type):"glb"===t.type?await this.loadGLB(t.element):"css"===t.type&&await this.loadStylesheet(t.element),t.resolve()}catch(e){if(this.error("Error processing queue item:",e),"script"===t.type&&t.element.hasAttribute("data-required"))break}}this.isProcessingQueue=!1}}async replaceHCSInStyle(e){let t=e,r=t.indexOf("hcs://");for(;-1!==r;){let e=r;for(;e<t.length&&!["'",'"'," ",")"].includes(t[e]);)e++;const i=t.substring(r,e),o=i.split("/").pop();try{const n=this.config.cdnUrl,a=this.config.network,s=await this.retrieveHCS1Data(o,n,a),c=URL.createObjectURL(s);t=t.substring(0,r)+c+t.substring(e),this.LoadedImages[o]=c,this.log("Replaced CSS HCS URL: "+i+" with "+c)}catch(n){this.error("Failed to load CSS image: "+o,n)}r=t.indexOf("hcs://",r+1)}return t}async processInlineStyles(){const e=document.querySelectorAll('[style*="hcs://"]');this.log("Found "+e.length+" elements with HCS style references");for(const r of Array.from(e)){const e=r.getAttribute("style");if(e){this.log("Processing style: "+e);const t=await this.replaceHCSInStyle(e);e!==t&&(r.setAttribute("style",t),this.log("Updated style to: "+t))}}const t=document.querySelectorAll("style");for(const r of Array.from(t))if(r.textContent?.includes("hcs://")){const e=await this.replaceHCSInStyle(r.textContent);r.textContent!==e&&(r.textContent=e)}}async init(){return this.loadConfigFromHTML(),new Promise((e=>{const t=async()=>{const t=document.querySelectorAll('script[data-src^="hcs://"]'),r=document.querySelectorAll('img[data-src^="hcs://"], img[src^="hcs://"]'),n=document.querySelectorAll('video[data-src^="hcs://"], video[src^="hcs://"]'),i=document.querySelectorAll('audio[data-src^="hcs://"], audio[src^="hcs://"]'),o=document.querySelectorAll('model-viewer[data-src^="hcs://"]'),a=document.querySelectorAll('link[data-src^="hcs://"]');document.querySelectorAll('[src^="hcs://"]').forEach((e=>{const t=e.getAttribute("src");t&&(e.setAttribute("data-src",t),e.removeAttribute("src"))})),await this.processInlineStyles();const s=[];[{elements:t,type:"script"},{elements:r,type:"image"},{elements:n,type:"video"},{elements:i,type:"audio"},{elements:o,type:"glb"},{elements:a,type:"css"}].forEach((({elements:e,type:t})=>{e.forEach((e=>{const r=parseInt(e.getAttribute("data-load-order")||"")||1/0;s.push(this.loadResource(e,t,r))}))})),await Promise.all(s);const c=new MutationObserver((e=>{e.forEach((e=>{if(e.addedNodes.forEach((e=>{if(e.nodeType===Node.ELEMENT_NODE){const t=e;if(t.getAttribute("style")?.includes("hcs://")&&this.processInlineStyles(),"style"===t.tagName.toLowerCase()&&t.textContent?.includes("hcs://")&&this.processInlineStyles(),t.getAttribute("src")?.startsWith("hcs://")){const e=t.getAttribute("src");t.setAttribute("data-src",e),t.removeAttribute("src");switch(t.tagName.toLowerCase()){case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"script":this.loadResource(t,"script",1/0)}}t.matches('script[data-src^="hcs://"]')?this.loadResource(t,"script",1/0):t.matches('img[data-src^="hcs://"]')?this.loadResource(t,"image",1/0):t.matches('video[data-src^="hcs://"]')?this.loadResource(t,"video",1/0):t.matches('audio[data-src^="hcs://"]')?this.loadResource(t,"audio",1/0):t.matches('model-viewer[data-src^="hcs://"]')?this.loadResource(t,"glb",1/0):t.matches('link[data-src^="hcs://"]')&&this.loadResource(t,"css",1/0);t.querySelectorAll('[data-src^="hcs://"], [src^="hcs://"]').forEach((e=>{const t=e,r=t.tagName.toLowerCase(),n=t.getAttribute("src");switch(n?.startsWith("hcs://")&&(t.setAttribute("data-src",n),t.removeAttribute("src")),r){case"script":this.loadResource(t,"script",1/0);break;case"img":this.loadResource(t,"image",1/0);break;case"video":this.loadResource(t,"video",1/0);break;case"audio":this.loadResource(t,"audio",1/0);break;case"model-viewer":this.loadResource(t,"glb",1/0);break;case"link":this.loadResource(t,"css",1/0)}}))}})),"attributes"===e.type){const t=e.target;if("style"===e.attributeName&&t.getAttribute("style")?.includes("hcs://"))this.processInlineStyles();else if("src"===e.attributeName){const e=t.getAttribute("src");if(e?.startsWith("hcs://")){t.setAttribute("data-src",e),t.removeAttribute("src");const r=t.tagName.toLowerCase();["img","video","audio"].includes(r)&&this.loadResource(t,r,1/0)}}}}))}));document.body?c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]}):document.addEventListener("DOMContentLoaded",(()=>{c.observe(document.body,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["style","src","data-src"]})})),e()};"loading"===document.readyState?document.addEventListener("DOMContentLoaded",t):t()}))}async preloadImage(e){this.log("Loading image:"+e),this.updateLoadingStatus("image: "+e,"loading");const t=await this.retrieveHCS1Data(e),r=URL.createObjectURL(t);return this.LoadedImages[e]=r,this.updateLoadingStatus("image: "+e,"loaded"),r}async preloadAudio(e){const t=document.createElement("audio");t.setAttribute("data-topic-id",e),t.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(t),await this.loadMedia(t,"audio");const r=document.querySelector('audio[data-topic-id="'+e+'"]');return r?this.LoadedAudioUrls[e]=r.src:console.error("Failed to preload audio: "+e),this.LoadedAudioUrls[e]}async playAudio(e,t=1){const r=this.LoadedAudioUrls[e];if(r){const n=new Audio(r);n.volume=t,this.LoadedAudios[e]=n,n.play().catch((e=>{console.error("Failed to play audio:",e)})),n.addEventListener("ended",(()=>{n.remove(),delete this.LoadedAudios[e]}))}else console.error("Audio not preloaded: "+e)}async pauseAudio(e){const t=document.querySelector('audio[data-topic-id="'+e+'"]');t?(console.log("found element",t),t.pause(),this.LoadedAudios[e]?.pause()):this.LoadedAudios[e]?.pause()}async loadAndPlayAudio(e,t=!1,r=1){let n=document.querySelector('audio[data-topic-id="'+e+'"]');if(n)n.volume=r,await n.play();else{const i=document.createElement("audio");i.volume=r,t&&i.setAttribute("autoplay","autoplay"),i.setAttribute("data-topic-id",e),i.setAttribute("data-src","hcs://1/"+e),document.body.appendChild(i),await this.loadMedia(i,"audio"),n=document.querySelector('audio[data-topic-id="'+e+'"]'),t||await n.play()}}}class WasmBridge{constructor(){this.wasm=null,this.WASM_VECTOR_LEN=0,this.cachedUint8Memory=null,this.cachedDataViewMemory=null,this.textEncoder=new TextEncoder,this.textDecoder=new TextDecoder("utf-8",{ignoreBOM:!0,fatal:!0}),this.textDecoder.decode(),this.logger=Logger$3.getInstance({module:"WasmBridge"})}setLogLevel(e){this.logger.setLogLevel(e)}get wasmInstance(){if(!this.wasm)throw new Error("WASM not initialized");return this.wasm}getUint8Memory(){if(!this.wasm)throw new Error("WASM not initialized");return null!==this.cachedUint8Memory&&0!==this.cachedUint8Memory.byteLength||(this.cachedUint8Memory=new Uint8Array(this.wasm.memory.buffer)),this.cachedUint8Memory}getDataViewMemory(){if(!this.wasm)throw new Error("WASM not initialized");return null!==this.cachedDataViewMemory&&this.cachedDataViewMemory.buffer===this.wasm.memory.buffer||(this.cachedDataViewMemory=new DataView(this.wasm.memory.buffer)),this.cachedDataViewMemory}encodeString(e,t){if(0===e.length)return{read:0,written:0};const r=this.textEncoder.encode(e);return t.set(r),{read:e.length,written:r.length}}passStringToWasm(e,t,r){if(void 0===r){const r=this.textEncoder.encode(e),n=t(r.length,1);return this.getUint8Memory().set(r,n),this.WASM_VECTOR_LEN=r.length,n}let n=this.textEncoder.encode(e).length,i=t(n,1);const o=this.getUint8Memory();let a=0;for(;a<n;a++){const t=e.charCodeAt(a);if(t>127)break;o[i+a]=t}if(a!==n){0!==a&&(e=e.slice(a)),i=r(i,n,n=a+3*this.textEncoder.encode(e).length,1);const t=this.getUint8Memory().subarray(i+a,i+n);a+=this.encodeString(e,t).written}return this.WASM_VECTOR_LEN=a,i}getStringFromWasm(e,t){return e>>>=0,this.textDecoder.decode(this.getUint8Memory().subarray(e,e+t))}createWasmFunction(e){if(!this.wasm)throw new Error("WASM not initialized");return(...t)=>{const r=this.wasm.__wbindgen_add_to_stack_pointer(-16);let n=[0,0];try{const i=[r,...t.map((e=>[this.passStringToWasm(e,this.wasm.__wbindgen_malloc,this.wasm.__wbindgen_realloc),this.WASM_VECTOR_LEN])).flat()];e.apply(this.wasm,i);const o=this.getDataViewMemory().getInt32(r+0,!0),a=this.getDataViewMemory().getInt32(r+4,!0);return n=[o,a],this.getStringFromWasm(o,a)}finally{this.wasm.__wbindgen_add_to_stack_pointer(16),this.wasm.__wbindgen_free(n[0],n[1],1)}}}async initWasm(e){const t=this,r={__wbindgen_placeholder__:{__wbindgen_throw:function(e,r){const n=t.getStringFromWasm(e,r);throw t.logger.error(`WASM error: ${n}`),new Error(n)}}};try{this.logger.debug("Compiling WASM module");const t=await WebAssembly.compile(e);this.logger.debug("Instantiating WASM module");const n=await WebAssembly.instantiate(t,r);return this.wasm=n.exports,this.logger.info("WASM module initialized successfully"),this.wasm}catch(n){throw this.logger.error("Failed to initialize WASM module",n),n}}createStateData(e,t={}){let r={};return e?.c?.inputType?.stateData&&(t.latestRoundData&&Object.keys(e.c.inputType.stateData).every((e=>e in t.latestRoundData))?(r.latestRoundData={},Object.entries(e.c.inputType.stateData).forEach((([e,n])=>{r.latestRoundData[e]=String(t.latestRoundData[e])}))):Object.entries(e.c.inputType.stateData).forEach((([e,n])=>{const i=t[e];i&&"object"==typeof i&&"values"in i&&i.values.length>0?r[e]=String(i.values[0]):r[e]=this.getDefaultValueForType(n)}))),r}getDefaultValueForType(e){return e.startsWith("uint")||e.startsWith("int")||"number"===e?"0":"bool"===e?"false":""}executeWasm(e,t){if(!this.wasm)throw this.logger.error("WASM not initialized"),new Error("WASM not initialized");try{this.logger.debug("Executing WASM with stateData",e);return this.createWasmFunction(this.wasmInstance.process_state)(JSON.stringify(e),JSON.stringify(t))}catch(r){throw this.logger.error("Error executing WASM",r),r}}getParams(){return this.createWasmFunction(this.wasmInstance.get_params)()}}
|
|
2
2
|
/**
|
|
3
3
|
* @license
|
|
4
4
|
* Copyright 2009 The Closure Library Authors
|