@ada-anvil/weld-plugin-hodei 0.0.6 → 0.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/cdn.min.js CHANGED
@@ -1,4 +1,4 @@
1
- var HodeiPlugin=function(v,y){"use strict";var ue=Object.defineProperty;var he=(v,y,_)=>y in v?ue(v,y,{enumerable:!0,configurable:!0,writable:!0,value:_}):v[y]=_;var w=(v,y,_)=>he(v,typeof y!="symbol"?y+"":y,_);async function _(t){const{baseUrl:e,apiKey:n}=t.config.anvil[t.network],o=new URL(`${e}/wallets/utxos`);return o.searchParams.set("address",t.address),o.searchParams.set("includeMempool","true"),(await fetch(o,{headers:{"x-api-key":n}})).json()}async function N(t){const{baseUrl:e,apiKey:n}=t.config.anvil[t.network],o=new URL(`${e}/wallets/balance`);return o.searchParams.set("address",t.address),(await fetch(o,{headers:{"x-api-key":n}})).json()}async function j(t){const{baseUrl:e,apiKey:n}=t.config.anvil[t.network];return(await fetch(`${e}/transactions/submit`,{method:"POST",headers:{"x-api-key":n,"content-type":"application/json"},body:JSON.stringify({transaction:t.transaction,signatures:t.signature?[t.signature]:[]})})).json()}const T={maxRetries:void 0,baseDelay:2e3,maxDelay:32e3,backoff:!0,skipImmediate:!1},H={bridge:{baseUrl:"https://bridge.hodei.io/api/dev"},anvil:{mainnet:{baseUrl:"https://prod.api.ada-anvil.app/v2/services",apiKey:"mainnet_IIrhwohjiEAJ2LFOgI8p5F735xz4C6XsgH6KfzpC"},preprod:{baseUrl:"https://preprod.api.ada-anvil.app/v2/services",apiKey:"testnet_C301LOscFsUccwR4zCqEtTJvizEAUc3AaVhRDdcY"}},debug:!1,retry:!0,waitForPairing:!0,onError:({error:t})=>console.error("[HODEI] unhandled error:",t??"unknown"),onClose:({code:t,reason:e})=>console.error("[HODEI] unhandled closure:",t,e)};function E(){let t="pending",e=()=>{},n=()=>{};const o=new Promise((s,a)=>{e=c=>{t="resolved",s(c)},n=c=>{t="rejected",a(c)}});return{status:t,promise:o,resolve:e,reject:n}}function b(t){if(t){if((t instanceof Error||S(t,"message"))&&typeof t.message=="string"&&t.message.length>0)return t.message;if(S(t,"data")&&S(t.data,"message")&&typeof t.data.message=="string"&&t.data.message.length>0)return t.data.message;if(typeof t=="string"&&t.length>0)return t}}function S(t,e){return typeof t=="object"&&t!==null&&e in t}function W(t,e){let n;return()=>{n&&clearTimeout(n),n=setTimeout(()=>{t(),n=void 0},e)}}const z={refused:1,failure:2};function M(t,e){return{code:z[t],info:b(e)??"unknown"}}const J={invalidRequest:-1,internalError:-2,refused:-3,accountChange:-4};function L(t,e){return{code:J[t],info:b(e)??"unknown"}}const F={proofGeneration:1,userDeclined:2};function G(t,e){let n=b(e)??"unknown";for(const o of["ProofGeneration: ","UserDeclined: "])if(n.startsWith(o)){n=n.slice(o.length);break}return n==="UserDeclined"&&(n="User declined"),n==="ProofGeneration"&&(n="Unable to sign the transaction"),{code:F[t],info:n}}const I="hodei-token";function x(){return localStorage.getItem(I)??void 0}function K(t){localStorage.setItem(I,t)}function P(){localStorage.removeItem(I)}const k={NormalClosure:1e3,SessionDeleted:4001},V={[WebSocket.CONNECTING]:"connecting",[WebSocket.OPEN]:"open",[WebSocket.CLOSING]:"closing",[WebSocket.CLOSED]:"closed"};class U{constructor(e){w(this,"config");w(this,"_onStateChange");w(this,"_debug");w(this,"_sigReqPromises",new Map);w(this,"_connectPromise");w(this,"_connection");var n;this.config=e.config,this._onStateChange=e.onStateChange,this._debug=((n=e.config)==null?void 0:n.debug)??!1}setDebug(e){this._debug=e}debugLog(...e){if(!this._debug)return;let n="[HODEI]";this.connection&&(n+=` (${this.connection.id})`),console.log(n,...e)}debugLogState(){var e;this.debugLog(JSON.stringify({isConnected:this.isConnected(),connection:this.connection?{id:this.connection.id,ws:V[this.connection.ws.readyState],state:this.connection.state,controller:{aborted:this.connection.controller.signal.aborted},reconnection:{status:this.connection.reconnection?"active":"inactive",aborted:(e=this.connection.reconnection)==null?void 0:e.signal.aborted}}:void 0,sigReqPromises:Array.from(this._sigReqPromises.keys())},null,2))}get connection(){return this._connection}isConnected(){var e,n;return((e=this.connection)==null?void 0:e.state.status)==="paired"||((n=this.connection)==null?void 0:n.state.status)==="pairing"}async connect(){var e;if(this._connectPromise)return this._connectPromise;if(this.isConnected())return this.connection.state;(e=this._connection)==null||e.ws.close(k.NormalClosure,"reconnecting"),this._connectPromise=this._connect();try{return await this._connectPromise}finally{this._connectPromise=void 0}}disconnect(){var e,n,o;this.debugLog("disconnecting"),(n=(e=this._connection)==null?void 0:e.reconnection)==null||n.abort("disconnecting"),(o=this._connection)==null||o.ws.close(k.NormalClosure,"disconnected"),this._connection=void 0}unlink(){this.send({type:"client.session_unlinked",payload:{}})}getState(){var e;return(e=this.connection)==null?void 0:e.state}async _connect(){var r,d,h,p;(r=this._connection)==null||r.ws.close(k.NormalClosure,"reconnecting");const e=this.config.bridge.baseUrl.replace("http","ws"),n=new URL(`${e}/client/ws`),o=await this._getToken();o&&n.searchParams.set("token",o);const s=(((d=this.connection)==null?void 0:d.id)??0)+1,a=new WebSocket(n),c=new AbortController,u=E();this.debugLog("connecting"),a.addEventListener("message",l=>{try{const i=JSON.parse(l.data);if(Y(i),this.debugLog("received connection message"),i.payload.status==="paired"&&this._sigReqPromises.size>0){const g=new Map;for(const f of i.payload.sigReqs??[]){const m=this._sigReqPromises.get(f.requestId);if(m){if(this._sigReqPromises.delete(f.requestId),!f.response){g.set(f.requestId,m);continue}a.send(JSON.stringify({type:"client.sig_req_ack",payload:{vaultId:i.payload.vaultId,requestId:f.requestId}})),f.response.status==="accepted"?m.resolve(f.response.data):m.reject(f.response.data)}}for(const f of this._sigReqPromises.values())f.reject("request expired");this._sigReqPromises=g}u.resolve(i.payload)}catch(i){u.reject(`Error parsing connection message ${l.data}: ${b(i)}`)}finally{c.abort()}},{signal:c.signal}),a.addEventListener("close",l=>{this.debugLog("ws closed while connecting"),u.reject(`Closed while connecting: ${b(l)}`),c.abort()},{signal:c.signal}),a.addEventListener("error",l=>{this.debugLog("received connection error"),u.reject(`Error connecting: ${b(l)}`),c.abort()},{signal:c.signal});try{const l=await u.promise;this.debugLog("connected"),K(l.token);const i={id:s,ws:a,state:l,controller:new AbortController,events:((h=this._connection)==null?void 0:h.events)??new EventTarget,reconnection:(p=this._connection)==null?void 0:p.reconnection};return this._connection=i,this._onStateChange(i.state),a.addEventListener("message",g=>{var f;try{if(i.state.status==="error")throw new Error("Received message after error");if(i.state.status==="closed")throw new Error("Received message after closed");const m=JSON.parse(g.data);D(m),this.debugLog("received message",m),(f=this._connection)==null||f.events.dispatchEvent(new CustomEvent("message",{detail:m})),m.type==="client.wallet_updated"&&(this.debugLog("received wallet_updated message"),i.state={...m.payload,status:"paired",sessionId:i.state.sessionId,token:i.state.token},this._onStateChange(i.state))}catch(m){this.debugLog(`error parsing message ${g.data}: ${b(m)}`)}},{signal:i.controller.signal}),a.addEventListener("error",async g=>{if(await this.reconnect()){this.debugLog("scheduled reconnect after error");return}this.debugLog(`received error: ${b(g)}`),i.state={status:"error",error:b(g)},this._onStateChange(i.state),i.controller.abort("socket error")},{signal:i.controller.signal}),a.addEventListener("close",async g=>{if(g.code===k.SessionDeleted&&(this.debugLog("session deleted"),P()),g.code!==k.NormalClosure&&g.code!==k.SessionDeleted&&await this.reconnect()){this.debugLog("reconnected after close");return}this.debugLog(`received close: ${g.code} ${g.reason}`),i.state={status:"closed",reason:g.reason,code:g.code},this._onStateChange(i.state),i.controller.abort("socket closed")},{signal:i.controller.signal}),l}catch(l){throw a.close(void 0,`failed to connect: ${b(l)}`),l}}send(e){var n;(n=this.connection)==null||n.ws.send(JSON.stringify(e))}handleSigReq(e){if(!this.isConnected())throw L("refused",new Error("Wallet is not connected"));const n=E();return this._sigReqPromises.set(e.requestId,n),this.connection.events.addEventListener("message",o=>{if(o instanceof CustomEvent)try{const s=o.detail;if(Q(s),s.payload.requestId!==e.requestId)return;this._sigReqPromises.delete(e.requestId),this.connection.state.status==="paired"&&this.send({type:"client.sig_req_ack",payload:{vaultId:this.connection.state.vaultId,requestId:e.requestId}}),s.type==="client.sig_req_accepted"?n.resolve(s.payload.signature):n.reject(s.payload.reason)}catch(s){this.debugLog(`error parsing message ${o.detail}: ${b(s)}`)}}),this.send({type:"client.sig_req_created",payload:e}),n.promise}async reconnect(){var a;if(!this.isConnected()){this.debugLog("failed to reconnect: not connected");return}(a=this.connection.reconnection)==null||a.abort("reconnection was re-triggered");const e=new AbortController;e.signal.addEventListener("abort",()=>{this.debugLog("reconnection aborted:",e.signal.reason),this.connection.reconnection===e?(this.debugLog("clearing reconnection"),this.connection.reconnection=void 0):this.debugLog("clearing reconnection")},{once:!0}),this.connection.controller.signal.addEventListener("abort",()=>e.abort("parent connection aborted"),{signal:e.signal}),this.connection.reconnection=e;const n=this.config.retry===!0?T:this.config.retry;let o,s=0;n!==!1&&n.skipImmediate&&(this.debugLog("skipping immediate reconnect attempt"),s=1);do{let c;if(!n||s===0)c=0;else{const i=Math.max(0,n.baseDelay);n.backoff?c=i*2**(s-1):c=i,n.maxDelay&&(c=Math.min(c,n.maxDelay))}s>0&&this.debugLog(`next attempt in ${c/1e3} seconds`);const u=E(),r=setTimeout(async()=>{var i;if(this.isConnected()&&((i=this.connection)==null?void 0:i.ws.readyState)===WebSocket.OPEN){u.resolve(this.connection.state);return}try{const g=await this._connect();u.resolve(g)}catch(g){u.reject(g)}},c),d=()=>{clearTimeout(r),u.resolve(void 0)},h=W(()=>{this.debugLog("restarting connection process: window focused"),s=-1,d()},250),p=()=>{document.visibilityState==="visible"&&h()},l={signal:e.signal,once:!0};e.signal.addEventListener("abort",d,l),document.addEventListener("visibilitychange",p,l),window.addEventListener("focus",h,l),o=await u.promise.catch(()=>{}),e.signal.removeEventListener("abort",d),document.removeEventListener("visibilitychange",p),window.removeEventListener("focus",h),o||this.debugLog("reconnection attempt failed")}while(!e.signal.aborted&&!o&&n&&s++<(n.maxRetries??Number.POSITIVE_INFINITY));if(e.signal.aborted){this.debugLog("reconnection was aborted, cancelling reconnection");return}return e.abort("done"),o?this.debugLog("reconnection successful"):this.debugLog("reconnection failed"),o}async _getToken(){const e=x();if(!e)return;const n=await A({config:this.config,token:e});if(this.debugLog(`checked token: ${n.valid?"valid":`invalid: ${n.reason}`}`),n.valid)return e;if(n.reason==="tooManyConnections")throw new Error("Too many connections");n.reason==="notFound"&&P()}}async function A(t){const e=new URL(`${t.config.bridge.baseUrl}/client/check`),n=await fetch(e,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}});return n.status===404?{valid:!1,reason:"notFound"}:n.status===409?{valid:!1,reason:"tooManyConnections"}:{valid:!0,token:t.token}}function C(t){return typeof t=="object"&&t!==null}function B(t){return C(t)&&(t.status==="pairing"||t.status==="paired")}function Y(t){if(!C(t)||t.type!=="client.connected"||!B(t.payload))throw new Error("Invalid connected message")}const X=new Set(["client.wallet_updated","client.sig_req_accepted","client.sig_req_rejected"]);function D(t){if(!C(t)||typeof t.type!="string"||!X.has(t.type))throw new Error("Invalid incoming message")}function Q(t){if(!C(t)||t.type!=="client.sig_req_accepted"&&t.type!=="client.sig_req_rejected")throw new Error("Invalid sig req response")}const Z=new Set(["pairing","paired","closed","error"]);function ee(t){return C(t)&&typeof t.status=="string"&&Z.has(t.status)}function q(t,e){t.dispatchEvent(new CustomEvent("command",{detail:e}))}function R(t,e,n){const o=s=>{const a=te(s);a&&e(a)};return t.addEventListener("command",o,n),()=>{t.removeEventListener("command",o,n)}}function te(t){if(t instanceof CustomEvent)return oe(t.detail)?t.detail:void 0}const ne=new Set(["disconnecting","disconnected","unlinked","dialog_closed"]);function oe(t){if(typeof t!="object"||t===null)return!1;const e=t;return typeof e.type!="string"?!1:ne.has(e.type)?!0:e.type==="state_changed"&&ee(e.payload)}function se(t){if(!(typeof window>"u"))return window.cardano||(window.cardano={}),"hodei"in window.cardano||(window.cardano.hodei=ie(t)),window.cardano.hodei}function ie(t={}){const e={config:{...H,...t}},n=async o=>{var s,a,c,u;await((s=e.promise)==null?void 0:s.catch(()=>{})),o.status==="error"&&e.config.onError(o),o.status==="closed"&&e.config.onClose(o),o.status==="paired"&&((c=(a=e.config).onWalletUpdate)==null||c.call(a,{baseAddress:o.baseAddress,stakeAddress:o.stakeAddress,network:o.network})),e.resolved?(u=e.resolved)==null||u.client.sendCommand({sender:"wallet",type:"state_changed",payload:o}):console.error("[HODEI] (state_changed)",o)};return{name:"hodei",icon:"https://raw.githubusercontent.com/cardano-forge/weld/main/images/wallets/hodei.png",apiVersion:"1",async enable(){var o;if((o=e.resolved)!=null&&o.bridge.isConnected())return e.resolved.api;!e.promise&&e.resolved&&(e.promise=O(e.resolved.bridge)),e.promise||(e.promise=O({config:e.config,onStateChange:n}));try{const s=await e.promise;return e.resolved=s,e.config.waitForPairing?await s.pairingPromise:s.pairingPromise.catch(()=>{}),s.api}finally{e.promise=void 0}},async isEnabled(){if(e.promise)try{return await e.promise,!0}catch{return!1}if(e.resolved)return e.resolved.bridge.isConnected();const o=x();if(!o)return!1;try{return(await A({config:e.config,token:o})).valid}catch{return!1}}}}async function O(t){var c,u;const e=await re(),n=t instanceof U?t:new U(t);await n.connect(),R(e.element,r=>{var d;if(r.sender==="client")switch(r.type){case"dialog_closed":{((d=n.getState())==null?void 0:d.status)==="pairing"&&n.disconnect();break}case"disconnected":{n.disconnect();break}case"unlinked":{n.unlink();break}default:{n.debugLog(`unhandled command received from client: ${JSON.stringify(r)}`);break}}},{signal:(c=n.connection)==null?void 0:c.controller.signal});const o=()=>{const r=n.getState();if((r==null?void 0:r.status)!=="paired")throw L("refused",new Error("Wallet is not connected"));return r},s={getNetworkId:async()=>o().network==="mainnet"?1:0,getUtxos:async()=>{const r=o();try{return await _({config:n.config,network:r.network,address:r.baseAddress})}catch(d){throw L("internalError",d)}},getBalance:async()=>{const r=o();try{return await N({config:n.config,network:r.network,address:r.baseAddress})}catch(d){throw L("internalError",d)}},getUsedAddresses:async()=>[o().baseAddress],getUnusedAddresses:async()=>[],getChangeAddress:async()=>o().baseAddress,getRewardAddresses:async()=>[o().stakeAddress],signTx:async(r,d=!1)=>{try{return await n.handleSigReq({requestId:crypto.randomUUID(),tx:r,partialSign:d,capabilities:["ack"]})}catch(h){const p=b(h),l=p!=null&&p.startsWith("ProofGeneration")?"proofGeneration":"userDeclined";throw G(l,p)}},signData:async(r,d)=>{const h=await n.handleSigReq({requestId:crypto.randomUUID(),address:r,data:d,capabilities:["ack"]}),[p,l]=h.split("::");if(!p||!l)throw L("internalError",new Error("Invalid signature"));return{signature:p,key:l}},submitTx:async r=>{const d=o();try{return(await j({config:n.config,network:d.network,transaction:r})).txHash}catch(h){throw M("failure",h)}},disconnect:async()=>{e.sendCommand({sender:"wallet",type:"disconnecting"})}},a=E();if(n.connection&&((u=n.getState())==null?void 0:u.status)==="pairing"){const r=new AbortController;n.connection.controller.signal.addEventListener("abort",()=>{r.abort(),a.reject(new Error("Aborted"))},{signal:r.signal}),n.connection.events.addEventListener("message",d=>{if(d instanceof CustomEvent)try{const h=d.detail;D(h),h.type==="client.wallet_updated"&&(a.resolve(),r.abort())}catch{}},{signal:r.signal})}else a.resolve();return{api:s,bridge:n,client:e,pairingPromise:a.promise}}async function re(){if(!customElements.get("hodei-client")){const e=await Promise.resolve().then(()=>ge);customElements.define("hodei-client",e.HodeiClient)}let t=document.querySelector("hodei-client")??void 0;if(!t){t=document.createElement("hodei-client");const e=E();t.addEventListener("mounted",()=>e.resolve(),{once:!0}),document.body.appendChild(t),await e.promise}return{element:t,sendCommand:e=>q(t,e)}}class $ extends y.DefaultWalletHandler{async disconnect(){var e;if("disconnect"in this.enabledApi&&typeof this.enabledApi.disconnect=="function")return(e=this.enabledApi)==null?void 0:e.disconnect()}}function ae(t){return{key:"hodei",connector:y.getDefaultWalletConnector($),initialize:y.runOnce(e=>se({debug:e.config.debug,...t,onError:o=>{var s;e.config.debug&&console.error("[WELD] Hodei socket error, disconnecting.",o),(s=t==null?void 0:t.onError)==null||s.call(t,o,e),e.wallet.disconnect()},onClose:o=>{var s;e.config.debug&&console.error("[WELD] Hodei socket closed, disconnecting.",o),(s=t==null?void 0:t.onClose)==null||s.call(t,o,e),e.wallet.disconnect()},onWalletUpdate:o=>{var s;e.config.debug&&console.log("[WELD] Hodei wallet updated, updating state.",o),(s=t==null?void 0:t.onWalletUpdate)==null||s.call(t,o,e),e.wallet.updateState()}})?(e.extensions.registerWallets([{supported:!0,key:"hodei",displayName:"Hodei",icon:"https://raw.githubusercontent.com/cardano-forge/weld/main/images/wallets/hodei.png",website:"https://github.com/cardano-forge/hodei-client",supportsTxChaining:!1}]),!0):!1)}}const ce="*{box-sizing:border-box}:host{font-family:Roboto,Arial,Helvetica,sans-serif;pointer-events:auto}dialog{width:100%;max-width:300px;outline:none;border:none;padding:24px;background:transparent}dialog::backdrop{background:#00000052}article{padding:24px;border-radius:22px;display:flex;flex-direction:column;align-items:center;justify-content:center;flex:1;overflow:hidden;text-align:center;background:linear-gradient(to bottom right,#ebdee8,#fff7fa);color:#1e191e}h1{margin:12px 0 16px;font-size:20px;font-weight:400}p{margin:0;font-size:14px}h2{margin:0 0 24px;font-size:24px;font-weight:600;letter-spacing:.2em}img{width:75px;height:75px}button{--bg: #69548e;--fg: #ffffff;background:var(--bg);color:var(--fg);outline:none;border:none;height:32px;padding:0 12px;border-radius:24px;position:relative;overflow:hidden;transition:all .2s ease-in-out}button:hover{cursor:pointer;--bg: #746197;--fg: #ffffff}button.tonal{--bg: #e8dff8;--fg: #1e182b}button.tonal:hover{--bg: #d9cfe7;--fg: #1f182b}footer{margin-top:24px}@media(prefers-color-scheme:dark){article{background:linear-gradient(to bottom right,#362a36,#181215);color:#eadfe6}button{--bg: #d3bcfd;--fg: #37265c}button:hover{--bg: #c6b0f0;--fg: #37265c}button.tonal{--bg: #4b4358;--fg: #e8dff8}button.tonal:hover{--bg: #574f63;--fg: #e9def8}}",de=`<dialog></dialog>
1
+ var HodeiPlugin=function(y,w){"use strict";var ue=Object.defineProperty;var he=(y,w,_)=>w in y?ue(y,w,{enumerable:!0,configurable:!0,writable:!0,value:_}):y[w]=_;var m=(y,w,_)=>he(y,typeof w!="symbol"?w+"":w,_);async function _(t){const{baseUrl:e,apiKey:n}=t.config.anvil[t.network],o=new URL(`${e}/wallets/utxos`);return o.searchParams.set("address",t.address),o.searchParams.set("includeMempool","true"),(await fetch(o,{headers:{"x-api-key":n}})).json()}async function R(t){const{baseUrl:e,apiKey:n}=t.config.anvil[t.network],o=new URL(`${e}/wallets/balance`);return o.searchParams.set("address",t.address),(await fetch(o,{headers:{"x-api-key":n}})).json()}async function j(t){const{baseUrl:e,apiKey:n}=t.config.anvil[t.network];return(await fetch(`${e}/transactions/submit`,{method:"POST",headers:{"x-api-key":n,"content-type":"application/json"},body:JSON.stringify({transaction:t.transaction,signatures:t.signature?[t.signature]:[]})})).json()}const T={maxRetries:void 0,baseDelay:2e3,maxDelay:32e3,backoff:!0,skipImmediate:!1},H={bridge:{baseUrl:"https://bridge.hodei.io/api/dev"},anvil:{mainnet:{baseUrl:"https://prod.api.ada-anvil.app/v2/services",apiKey:"mainnet_IIrhwohjiEAJ2LFOgI8p5F735xz4C6XsgH6KfzpC"},preprod:{baseUrl:"https://preprod.api.ada-anvil.app/v2/services",apiKey:"testnet_C301LOscFsUccwR4zCqEtTJvizEAUc3AaVhRDdcY"}},debug:!1,retry:!0,waitForPairing:!0,onError:({error:t})=>console.error("[HODEI] unhandled error:",t??"unknown"),onClose:({code:t,reason:e})=>console.error("[HODEI] unhandled closure:",t,e)};function k(){let t="pending",e=()=>{},n=()=>{};const o=new Promise((s,i)=>{e=d=>{t="resolved",s(d)},n=d=>{t="rejected",i(d)}});return{status:t,promise:o,resolve:e,reject:n}}function v(t){if(t){if((t instanceof Error||S(t,"message"))&&typeof t.message=="string"&&t.message.length>0)return t.message;if(S(t,"data")&&S(t.data,"message")&&typeof t.data.message=="string"&&t.data.message.length>0)return t.data.message;if(typeof t=="string"&&t.length>0)return t}}function S(t,e){return typeof t=="object"&&t!==null&&e in t}function W(t,e){let n;return()=>{n&&clearTimeout(n),n=setTimeout(()=>{t(),n=void 0},e)}}const z={refused:1,failure:2};function M(t,e){return{code:z[t],info:v(e)??"unknown"}}const J={invalidRequest:-1,internalError:-2,refused:-3,accountChange:-4};function L(t,e){return{code:J[t],info:v(e)??"unknown"}}const F={proofGeneration:1,userDeclined:2};function G(t,e){let n=v(e)??"unknown";for(const o of["ProofGeneration: ","UserDeclined: "])if(n.startsWith(o)){n=n.slice(o.length);break}return n==="UserDeclined"&&(n="User declined"),n==="ProofGeneration"&&(n="Unable to sign the transaction"),{code:F[t],info:n}}const I="hodei-token";function x(){return localStorage.getItem(I)??void 0}function K(t){localStorage.setItem(I,t)}function P(){localStorage.removeItem(I)}const E={NormalClosure:1e3,SessionDeleted:4001},V={[WebSocket.CONNECTING]:"connecting",[WebSocket.OPEN]:"open",[WebSocket.CLOSING]:"closing",[WebSocket.CLOSED]:"closed"};class U{constructor(e){m(this,"config");m(this,"_onStateChange");m(this,"_debug");m(this,"_sigReqPromises",new Map);m(this,"_connectPromise");m(this,"_connection");var n;this.config=e.config,this._onStateChange=e.onStateChange,this._debug=((n=e.config)==null?void 0:n.debug)??!1}setDebug(e){this._debug=e}debugLog(...e){if(!this._debug)return;let n="[HODEI]";this.connection&&(n+=` (${this.connection.id})`),console.log(n,...e)}debugLogState(){var e;this.debugLog(JSON.stringify({isConnected:this.isConnected(),connection:this.connection?{id:this.connection.id,ws:V[this.connection.ws.readyState],state:this.connection.state,controller:{aborted:this.connection.controller.signal.aborted},reconnection:{status:this.connection.reconnection?"active":"inactive",aborted:(e=this.connection.reconnection)==null?void 0:e.controller.signal.aborted}}:void 0,sigReqPromises:Array.from(this._sigReqPromises.keys())},null,2))}get connection(){return this._connection}isConnected(){var e,n;return((e=this.connection)==null?void 0:e.state.status)==="paired"||((n=this.connection)==null?void 0:n.state.status)==="pairing"}async connect(){var e;if(this._connectPromise)return this._connectPromise;if(this.isConnected())return this.connection.state;(e=this._connection)==null||e.ws.close(E.NormalClosure,"reconnecting"),this._connectPromise=this._connect();try{return await this._connectPromise}finally{this._connectPromise=void 0}}disconnect(){var e,n,o;this.debugLog("disconnecting"),(n=(e=this._connection)==null?void 0:e.reconnection)==null||n.controller.abort("disconnecting"),(o=this._connection)==null||o.ws.close(E.NormalClosure,"disconnected"),this._connection=void 0}unlink(){this.send({type:"client.session_unlinked",payload:{}})}getState(){var e;return(e=this.connection)==null?void 0:e.state}async _connect(){var r,l,u,h;(r=this._connection)==null||r.ws.close(E.NormalClosure,"reconnecting");const e=this.config.bridge.baseUrl.replace("http","ws"),n=new URL(`${e}/client/ws`),o=await this._getToken();o&&n.searchParams.set("token",o);const s=(((l=this.connection)==null?void 0:l.id)??0)+1,i=new WebSocket(n),d=new AbortController,p=k();this.debugLog("connecting"),i.addEventListener("message",c=>{try{const a=JSON.parse(c.data);if(Y(a),this.debugLog("received connection message"),a.payload.status==="paired"&&this._sigReqPromises.size>0){const g=new Map;for(const f of a.payload.sigReqs??[]){const b=this._sigReqPromises.get(f.requestId);if(b){if(this._sigReqPromises.delete(f.requestId),!f.response){g.set(f.requestId,b);continue}i.send(JSON.stringify({type:"client.sig_req_ack",payload:{vaultId:a.payload.vaultId,requestId:f.requestId}})),f.response.status==="accepted"?b.resolve(f.response.data):b.reject(f.response.data)}}for(const f of this._sigReqPromises.values())f.reject("request expired");this._sigReqPromises=g}p.resolve(a.payload)}catch(a){p.reject(`Error parsing connection message ${c.data}: ${v(a)}`)}finally{d.abort()}},{signal:d.signal}),i.addEventListener("close",c=>{this.debugLog("ws closed while connecting"),p.reject(`Closed while connecting: ${v(c)}`),d.abort()},{signal:d.signal}),i.addEventListener("error",c=>{this.debugLog("received connection error"),p.reject(`Error connecting: ${v(c)}`),d.abort()},{signal:d.signal});try{const c=await p.promise;this.debugLog("connected"),K(c.token);const a={id:s,ws:i,state:c,controller:new AbortController,events:((u=this._connection)==null?void 0:u.events)??new EventTarget,reconnection:(h=this._connection)==null?void 0:h.reconnection};return this._connection=a,this._onStateChange(a.state),i.addEventListener("message",g=>{var f;try{if(a.state.status==="error")throw new Error("Received message after error");if(a.state.status==="closed")throw new Error("Received message after closed");const b=JSON.parse(g.data);D(b),this.debugLog("received message",b),(f=this._connection)==null||f.events.dispatchEvent(new CustomEvent("message",{detail:b})),b.type==="client.wallet_updated"&&(this.debugLog("received wallet_updated message"),a.state={...b.payload,status:"paired",sessionId:a.state.sessionId,token:a.state.token},this._onStateChange(a.state))}catch(b){this.debugLog(`error parsing message ${g.data}: ${v(b)}`)}},{signal:a.controller.signal}),i.addEventListener("error",async g=>{if(this.debugLog("received error, will try to reconnect"),await this.reconnect()){this.debugLog("scheduled reconnect after error");return}else this.debugLog("wasn't able to reconnect");this.debugLog(`received error: ${JSON.stringify(g)}`),a.state={status:"error",error:JSON.stringify(g)},this._onStateChange(a.state),a.controller.abort("socket error")},{signal:a.controller.signal}),i.addEventListener("close",async g=>{if(g.code===E.SessionDeleted&&(this.debugLog("session deleted"),P()),g.code!==E.NormalClosure&&g.code!==E.SessionDeleted)if(this.debugLog(`socket closed with code ${g.code} and reason ${g.reason} but will try to reconnect`),await this.reconnect()){this.debugLog("reconnected after close");return}else this.debugLog("didn't reconnect");this.debugLog(`received close: ${g.code} ${g.reason}`),a.state={status:"closed",reason:g.reason,code:g.code},this._onStateChange(a.state),a.controller.abort("socket closed")},{signal:a.controller.signal}),c}catch(c){throw i.close(void 0,`failed to connect: ${v(c)}`),c}}send(e){var n;(n=this.connection)==null||n.ws.send(JSON.stringify(e))}handleSigReq(e){if(!this.isConnected())throw L("refused",new Error("Wallet is not connected"));const n=k();return this._sigReqPromises.set(e.requestId,n),this.connection.events.addEventListener("message",o=>{if(o instanceof CustomEvent)try{const s=o.detail;if(Q(s),s.payload.requestId!==e.requestId)return;this._sigReqPromises.delete(e.requestId),this.connection.state.status==="paired"&&this.send({type:"client.sig_req_ack",payload:{vaultId:this.connection.state.vaultId,requestId:e.requestId}}),s.type==="client.sig_req_accepted"?n.resolve(s.payload.signature):n.reject(s.payload.reason)}catch(s){this.debugLog(`error parsing message ${o.detail}: ${v(s)}`)}}),this.send({type:"client.sig_req_created",payload:e}),n.promise}async reconnect(){if(!this.isConnected()){this.debugLog("failed to reconnect: not connected");return}if(this.connection.reconnection)return this.debugLog("returning existing reconnection promise"),this.connection.reconnection.deferred.promise;const e={controller:new AbortController,deferred:k()};e.controller.signal.addEventListener("abort",()=>{this.debugLog("reconnection aborted:",e.controller.signal.reason),this.connection.reconnection===e?(this.debugLog("clearing reconnection"),this.connection.reconnection=void 0):this.debugLog("clearing reconnection")},{once:!0}),this.connection.controller.signal.addEventListener("abort",()=>e.controller.abort(`parent connection aborted (${this.connection.controller.signal.reason})`),{signal:e.controller.signal}),this.connection.reconnection=e;const n=this.config.retry===!0?T:this.config.retry;let o,s=0;n!==!1&&n.skipImmediate&&(this.debugLog("skipping immediate reconnect attempt"),s=1);do{let i;if(!n||s===0)i=0;else{const c=Math.max(0,n.baseDelay);n.backoff?i=c*2**(s-1):i=c,n.maxDelay&&(i=Math.min(i,n.maxDelay))}s>0&&this.debugLog(`next attempt in ${i/1e3} seconds`);const d=k(),p=setTimeout(async()=>{var c;if(this.isConnected()&&((c=this.connection)==null?void 0:c.ws.readyState)===WebSocket.OPEN){d.resolve(this.connection.state);return}try{const a=await this._connect();d.resolve(a)}catch(a){d.reject(a)}},i),r=()=>{clearTimeout(p),d.resolve(void 0)},l=W(()=>{this.debugLog("restarting connection process: window focused"),s=-1,r()},250),u=()=>{document.visibilityState==="visible"&&l()},h={signal:e.controller.signal,once:!0};e.controller.signal.addEventListener("abort",r,h),document.addEventListener("visibilitychange",u,h),window.addEventListener("focus",l,h),o=await d.promise.catch(()=>{}),e.controller.signal.removeEventListener("abort",r),document.removeEventListener("visibilitychange",u),window.removeEventListener("focus",l),o||this.debugLog("reconnection attempt failed")}while(!e.controller.signal.aborted&&!o&&n&&s++<(n.maxRetries??Number.POSITIVE_INFINITY));return e.controller.signal.aborted?this.debugLog(`reconnection was aborted (${e.controller.signal.reason}), cancelling reconnection`):(e.controller.abort("done"),o?this.debugLog("reconnection successful"):this.debugLog("reconnection failed")),this.debugLog("resolving reconnection promise"),e.deferred.resolve(o),o}async _getToken(){const e=x();if(!e)return;const n=await A({config:this.config,token:e});if(this.debugLog(`checked token: ${n.valid?"valid":`invalid: ${n.reason}`}`),n.valid)return e;if(n.reason==="tooManyConnections")throw new Error("Too many connections");n.reason==="notFound"&&P()}}async function A(t){const e=new URL(`${t.config.bridge.baseUrl}/client/check`),n=await fetch(e,{method:"POST",headers:{Authorization:`Bearer ${t.token}`}});return n.status===404?{valid:!1,reason:"notFound"}:n.status===409?{valid:!1,reason:"tooManyConnections"}:{valid:!0,token:t.token}}function C(t){return typeof t=="object"&&t!==null}function B(t){return C(t)&&(t.status==="pairing"||t.status==="paired")}function Y(t){if(!C(t)||t.type!=="client.connected"||!B(t.payload))throw new Error("Invalid connected message")}const X=new Set(["client.wallet_updated","client.sig_req_accepted","client.sig_req_rejected"]);function D(t){if(!C(t)||typeof t.type!="string"||!X.has(t.type))throw new Error("Invalid incoming message")}function Q(t){if(!C(t)||t.type!=="client.sig_req_accepted"&&t.type!=="client.sig_req_rejected")throw new Error("Invalid sig req response")}const Z=new Set(["pairing","paired","closed","error"]);function ee(t){return C(t)&&typeof t.status=="string"&&Z.has(t.status)}function q(t,e){t.dispatchEvent(new CustomEvent("command",{detail:e}))}function $(t,e,n){const o=s=>{const i=te(s);i&&e(i)};return t.addEventListener("command",o,n),()=>{t.removeEventListener("command",o,n)}}function te(t){if(t instanceof CustomEvent)return oe(t.detail)?t.detail:void 0}const ne=new Set(["disconnecting","disconnected","unlinked","dialog_closed"]);function oe(t){if(typeof t!="object"||t===null)return!1;const e=t;return typeof e.type!="string"?!1:ne.has(e.type)?!0:e.type==="state_changed"&&ee(e.payload)}function se(t){if(!(typeof window>"u"))return window.cardano||(window.cardano={}),"hodei"in window.cardano||(window.cardano.hodei=ie(t)),window.cardano.hodei}function ie(t={}){const e={config:{...H,...t}},n=async o=>{var s,i,d,p;await((s=e.promise)==null?void 0:s.catch(()=>{})),o.status==="error"&&e.config.onError(o),o.status==="closed"&&e.config.onClose(o),o.status==="paired"&&((d=(i=e.config).onWalletUpdate)==null||d.call(i,{baseAddress:o.baseAddress,stakeAddress:o.stakeAddress,network:o.network})),e.resolved?(p=e.resolved)==null||p.client.sendCommand({sender:"wallet",type:"state_changed",payload:o}):console.error("[HODEI] (state_changed)",o)};return{name:"hodei",icon:"https://raw.githubusercontent.com/cardano-forge/weld/main/images/wallets/hodei.png",apiVersion:"1",async enable(){var o;if((o=e.resolved)!=null&&o.bridge.isConnected())return e.resolved.api;!e.promise&&e.resolved&&(e.promise=N(e.resolved.bridge)),e.promise||(e.promise=N({config:e.config,onStateChange:n}));try{const s=await e.promise;return e.resolved=s,e.config.waitForPairing?await s.pairingPromise:s.pairingPromise.catch(()=>{}),s.api}finally{e.promise=void 0}},async isEnabled(){if(e.promise)try{return await e.promise,!0}catch{return!1}if(e.resolved)return e.resolved.bridge.isConnected();const o=x();if(!o)return!1;try{return(await A({config:e.config,token:o})).valid}catch{return!1}}}}async function N(t){var d,p;const e=await re(),n=t instanceof U?t:new U(t);await n.connect(),$(e.element,r=>{var l;if(r.sender==="client")switch(r.type){case"dialog_closed":{((l=n.getState())==null?void 0:l.status)==="pairing"&&n.disconnect();break}case"disconnected":{n.disconnect();break}case"unlinked":{n.unlink();break}default:{n.debugLog(`unhandled command received from client: ${JSON.stringify(r)}`);break}}},{signal:(d=n.connection)==null?void 0:d.controller.signal});const o=()=>{const r=n.getState();if((r==null?void 0:r.status)!=="paired")throw L("refused",new Error("Wallet is not connected"));return r},s={getNetworkId:async()=>o().network==="mainnet"?1:0,getUtxos:async()=>{const r=o();try{return await _({config:n.config,network:r.network,address:r.baseAddress})}catch(l){throw L("internalError",l)}},getBalance:async()=>{const r=o();try{return await R({config:n.config,network:r.network,address:r.baseAddress})}catch(l){throw L("internalError",l)}},getUsedAddresses:async()=>[o().baseAddress],getUnusedAddresses:async()=>[],getChangeAddress:async()=>o().baseAddress,getRewardAddresses:async()=>[o().stakeAddress],signTx:async(r,l=!1)=>{try{return await n.handleSigReq({requestId:crypto.randomUUID(),tx:r,partialSign:l,capabilities:["ack"]})}catch(u){const h=v(u),c=h!=null&&h.startsWith("ProofGeneration")?"proofGeneration":"userDeclined";throw G(c,h)}},signData:async(r,l)=>{const u=await n.handleSigReq({requestId:crypto.randomUUID(),address:r,data:l,capabilities:["ack"]}),[h,c]=u.split("::");if(!h||!c)throw L("internalError",new Error("Invalid signature"));return{signature:h,key:c}},submitTx:async r=>{const l=o();try{return(await j({config:n.config,network:l.network,transaction:r})).txHash}catch(u){throw M("failure",u)}},disconnect:async()=>{e.sendCommand({sender:"wallet",type:"disconnecting"})}},i=k();if(n.connection&&((p=n.getState())==null?void 0:p.status)==="pairing"){const r=new AbortController;n.connection.controller.signal.addEventListener("abort",()=>{r.abort(),i.reject(new Error("Aborted"))},{signal:r.signal}),n.connection.events.addEventListener("message",l=>{if(l instanceof CustomEvent)try{const u=l.detail;D(u),u.type==="client.wallet_updated"&&(i.resolve(),r.abort())}catch{}},{signal:r.signal})}else i.resolve();return{api:s,bridge:n,client:e,pairingPromise:i.promise}}async function re(){if(!customElements.get("hodei-client")){const e=await Promise.resolve().then(()=>ge);customElements.define("hodei-client",e.HodeiClient)}let t=document.querySelector("hodei-client")??void 0;if(!t){t=document.createElement("hodei-client");const e=k();t.addEventListener("mounted",()=>e.resolve(),{once:!0}),document.body.appendChild(t),await e.promise}return{element:t,sendCommand:e=>q(t,e)}}class O extends w.DefaultWalletHandler{async disconnect(){var e;if("disconnect"in this.enabledApi&&typeof this.enabledApi.disconnect=="function")return(e=this.enabledApi)==null?void 0:e.disconnect()}}function ae(t){return{key:"hodei",connector:w.getDefaultWalletConnector(O),initialize:w.runOnce(e=>((t==null?void 0:t.initialize)??se)({debug:e.config.debug,...t,onError:s=>{var i;e.wallet.key==="hodei"&&(e.config.debug&&console.error("[WELD] Hodei socket error, disconnecting.",s),(i=t==null?void 0:t.onError)==null||i.call(t,s,e),e.wallet.disconnect())},onClose:s=>{var i;e.wallet.key==="hodei"&&(e.config.debug&&console.error("[WELD] Hodei socket closed, disconnecting.",s),(i=t==null?void 0:t.onClose)==null||i.call(t,s,e),e.wallet.disconnect())},onWalletUpdate:s=>{var i;e.wallet.key==="hodei"&&(e.config.debug&&console.log("[WELD] Hodei wallet updated, updating state.",s),(i=t==null?void 0:t.onWalletUpdate)==null||i.call(t,s,e),e.wallet.updateState())}})?(e.extensions.registerWallets([{supported:!0,key:"hodei",displayName:"Hodei",icon:"https://raw.githubusercontent.com/cardano-forge/weld/main/images/wallets/hodei.png",website:"https://github.com/cardano-forge/hodei-client",supportsTxChaining:!1}]),!0):!1)}}const ce="*{box-sizing:border-box}:host{font-family:Roboto,Arial,Helvetica,sans-serif;pointer-events:auto}dialog{width:100%;max-width:300px;outline:none;border:none;padding:24px;background:transparent}dialog::backdrop{background:#00000052}article{padding:24px;border-radius:22px;display:flex;flex-direction:column;align-items:center;justify-content:center;flex:1;overflow:hidden;text-align:center;background:linear-gradient(to bottom right,#ebdee8,#fff7fa);color:#1e191e}h1{margin:12px 0 16px;font-size:20px;font-weight:400}p{margin:0;font-size:14px}h2{margin:0 0 24px;font-size:24px;font-weight:600;letter-spacing:.2em}img{width:75px;height:75px}button{--bg: #69548e;--fg: #ffffff;background:var(--bg);color:var(--fg);outline:none;border:none;height:32px;padding:0 12px;border-radius:24px;position:relative;overflow:hidden;transition:all .2s ease-in-out}button:hover{cursor:pointer;--bg: #746197;--fg: #ffffff}button.tonal{--bg: #e8dff8;--fg: #1e182b}button.tonal:hover{--bg: #d9cfe7;--fg: #1f182b}footer{margin-top:24px}@media(prefers-color-scheme:dark){article{background:linear-gradient(to bottom right,#362a36,#181215);color:#eadfe6}button{--bg: #d3bcfd;--fg: #37265c}button:hover{--bg: #c6b0f0;--fg: #37265c}button.tonal{--bg: #4b4358;--fg: #e8dff8}button.tonal:hover{--bg: #574f63;--fg: #e9def8}}",de=`<dialog></dialog>
2
2
 
3
3
  <template id="pairing">
4
4
  <article>
@@ -20,4 +20,4 @@ var HodeiPlugin=function(v,y){"use strict";var ue=Object.defineProperty;var he=(
20
20
  </footer>
21
21
  </article>
22
22
  </template>
23
- `;class le extends HTMLElement{constructor(){super();w(this,"_state",{status:"disconnected"});w(this,"_shadow");w(this,"_dialog");w(this,"_unsub");w(this,"_observer");this._shadow=this.attachShadow({mode:"open"}),this._shadow.innerHTML=`<style>${ce}</style>${de}`;const n=this._shadow.querySelector("dialog");if(n)this._dialog=n;else throw new Error("dialog not found");for(const o of["pointerdown","pointerup","click","mousedown","mouseup"])this.addEventListener(o,s=>s.stopPropagation());this._dialog.addEventListener("click",o=>{o.target===this._dialog&&this._dialog.close("backdrop")}),this._dialog.addEventListener("close",()=>{switch(this._state.status){case"pairing":q(this,{sender:"client",type:"dialog_closed"});break;case"disconnecting":this._dialog.returnValue==="backdrop"?this._state={status:"connected"}:q(this,{sender:"client",type:this._state.shouldUnlink?"unlinked":"disconnected"});break}})}connectedCallback(){this._unsub=R(this,o=>{if(o.sender==="wallet"&&!(o.type==="state_changed"&&o.payload.status==="paired"&&this._state.status==="disconnecting"))switch(o.type){case"state_changed":switch(o.payload.status){case"paired":this._state={status:"connected"};break;case"pairing":this._state={status:"pairing",pin:o.payload.pin};break;default:this._state={status:"disconnected"};break}this._update();break;case"disconnecting":this._state.status==="connected"&&(this._state={status:"disconnecting",shouldUnlink:!1},this._update());break}});const n=this.parentElement;n&&(this._observer=new MutationObserver(()=>{n.lastElementChild!==this&&(n.removeChild(this),n.appendChild(this))}),this._observer.observe(n,{childList:!0})),this.dispatchEvent(new CustomEvent("mounted"))}disconnectedCallback(){var n,o;(n=this._unsub)==null||n.call(this),(o=this._observer)==null||o.disconnect(),this.dispatchEvent(new CustomEvent("unmounted"))}_cloneTemplate(n){var o;return(o=this._shadow.querySelector(`#${n}`))==null?void 0:o.content.cloneNode(!0)}_update(){const n=this._state;switch(n.status){case"pairing":{const o=this._cloneTemplate(n.status),s=o.querySelector(".pin");s&&(s.textContent=n.pin),this._dialog.replaceChildren(o),this._dialog.open||this._dialog.showModal();break}case"disconnecting":{const o=this._cloneTemplate(n.status);this._dialog.replaceChildren(o);for(const s of this._dialog.querySelectorAll("button"))s.addEventListener("click",()=>{n.shouldUnlink=s.dataset.action==="unlink",this._dialog.close("disconnect")});this._dialog.open||this._dialog.showModal();break}default:{this._dialog.open&&this._dialog.close("no-content");break}}}}const ge=Object.freeze(Object.defineProperty({__proto__:null,HodeiClient:le},Symbol.toStringTag,{value:"Module"}));return v.HodeiHandler=$,v.hodeiPlugin=ae,Object.defineProperty(v,Symbol.toStringTag,{value:"Module"}),v}({},WeldCore);
23
+ `;class le extends HTMLElement{constructor(){super();m(this,"_state",{status:"disconnected"});m(this,"_shadow");m(this,"_dialog");m(this,"_unsub");m(this,"_observer");this._shadow=this.attachShadow({mode:"open"}),this._shadow.innerHTML=`<style>${ce}</style>${de}`;const n=this._shadow.querySelector("dialog");if(n)this._dialog=n;else throw new Error("dialog not found");for(const o of["pointerdown","pointerup","click","mousedown","mouseup"])this.addEventListener(o,s=>s.stopPropagation());this._dialog.addEventListener("click",o=>{o.target===this._dialog&&this._dialog.close("backdrop")}),this._dialog.addEventListener("close",()=>{switch(this._state.status){case"pairing":q(this,{sender:"client",type:"dialog_closed"});break;case"disconnecting":this._dialog.returnValue==="backdrop"?this._state={status:"connected"}:q(this,{sender:"client",type:this._state.shouldUnlink?"unlinked":"disconnected"});break}})}connectedCallback(){this._unsub=$(this,o=>{if(o.sender==="wallet"&&!(o.type==="state_changed"&&o.payload.status==="paired"&&this._state.status==="disconnecting"))switch(o.type){case"state_changed":switch(o.payload.status){case"paired":this._state={status:"connected"};break;case"pairing":this._state={status:"pairing",pin:o.payload.pin};break;default:this._state={status:"disconnected"};break}this._update();break;case"disconnecting":this._state.status==="connected"&&(this._state={status:"disconnecting",shouldUnlink:!1},this._update());break}});const n=this.parentElement;n&&(this._observer=new MutationObserver(()=>{n.lastElementChild!==this&&(n.removeChild(this),n.appendChild(this))}),this._observer.observe(n,{childList:!0})),this.dispatchEvent(new CustomEvent("mounted"))}disconnectedCallback(){var n,o;(n=this._unsub)==null||n.call(this),(o=this._observer)==null||o.disconnect(),this.dispatchEvent(new CustomEvent("unmounted"))}_cloneTemplate(n){var o;return(o=this._shadow.querySelector(`#${n}`))==null?void 0:o.content.cloneNode(!0)}_update(){const n=this._state;switch(n.status){case"pairing":{const o=this._cloneTemplate(n.status),s=o.querySelector(".pin");s&&(s.textContent=n.pin),this._dialog.replaceChildren(o),this._dialog.open||this._dialog.showModal();break}case"disconnecting":{const o=this._cloneTemplate(n.status);this._dialog.replaceChildren(o);for(const s of this._dialog.querySelectorAll("button"))s.addEventListener("click",()=>{n.shouldUnlink=s.dataset.action==="unlink",this._dialog.close("disconnect")});this._dialog.open||this._dialog.showModal();break}default:{this._dialog.open&&this._dialog.close("no-content");break}}}}const ge=Object.freeze(Object.defineProperty({__proto__:null,HodeiClient:le},Symbol.toStringTag,{value:"Module"}));return y.HodeiHandler=O,y.hodeiPlugin=ae,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"}),y}({},WeldCore);
package/lib.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("@ada-anvil/hodei-client"),o=require("@ada-anvil/weld/core");class i extends o.DefaultWalletHandler{async disconnect(){var t;if("disconnect"in this.enabledApi&&typeof this.enabledApi.disconnect=="function")return(t=this.enabledApi)==null?void 0:t.disconnect()}}function l(e){return{key:"hodei",connector:o.getDefaultWalletConnector(i),initialize:o.runOnce(t=>s.initialize({debug:t.config.debug,...e,onError:n=>{var r;t.config.debug&&console.error("[WELD] Hodei socket error, disconnecting.",n),(r=e==null?void 0:e.onError)==null||r.call(e,n,t),t.wallet.disconnect()},onClose:n=>{var r;t.config.debug&&console.error("[WELD] Hodei socket closed, disconnecting.",n),(r=e==null?void 0:e.onClose)==null||r.call(e,n,t),t.wallet.disconnect()},onWalletUpdate:n=>{var r;t.config.debug&&console.log("[WELD] Hodei wallet updated, updating state.",n),(r=e==null?void 0:e.onWalletUpdate)==null||r.call(e,n,t),t.wallet.updateState()}})?(t.extensions.registerWallets([{supported:!0,key:"hodei",displayName:"Hodei",icon:"https://raw.githubusercontent.com/cardano-forge/weld/main/images/wallets/hodei.png",website:"https://github.com/cardano-forge/hodei-client",supportsTxChaining:!1}]),!0):!1)}}exports.HodeiHandler=i;exports.hodeiPlugin=l;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("@ada-anvil/hodei-client"),r=require("@ada-anvil/weld/core");class o extends r.DefaultWalletHandler{async disconnect(){var t;if("disconnect"in this.enabledApi&&typeof this.enabledApi.disconnect=="function")return(t=this.enabledApi)==null?void 0:t.disconnect()}}function l(e){return{key:"hodei",connector:r.getDefaultWalletConnector(o),initialize:r.runOnce(t=>((e==null?void 0:e.initialize)??s.initialize)({debug:t.config.debug,...e,onError:i=>{var n;t.wallet.key==="hodei"&&(t.config.debug&&console.error("[WELD] Hodei socket error, disconnecting.",i),(n=e==null?void 0:e.onError)==null||n.call(e,i,t),t.wallet.disconnect())},onClose:i=>{var n;t.wallet.key==="hodei"&&(t.config.debug&&console.error("[WELD] Hodei socket closed, disconnecting.",i),(n=e==null?void 0:e.onClose)==null||n.call(e,i,t),t.wallet.disconnect())},onWalletUpdate:i=>{var n;t.wallet.key==="hodei"&&(t.config.debug&&console.log("[WELD] Hodei wallet updated, updating state.",i),(n=e==null?void 0:e.onWalletUpdate)==null||n.call(e,i,t),t.wallet.updateState())}})?(t.extensions.registerWallets([{supported:!0,key:"hodei",displayName:"Hodei",icon:"https://raw.githubusercontent.com/cardano-forge/weld/main/images/wallets/hodei.png",website:"https://github.com/cardano-forge/hodei-client",supportsTxChaining:!1}]),!0):!1)}}exports.HodeiHandler=o;exports.hodeiPlugin=l;
package/lib.js CHANGED
@@ -1,5 +1,5 @@
1
- import { initialize as o } from "@ada-anvil/hodei-client";
2
- import { DefaultWalletHandler as s, runOnce as a, getDefaultWalletConnector as i } from "@ada-anvil/weld/core";
1
+ import { initialize as n } from "@ada-anvil/hodei-client";
2
+ import { DefaultWalletHandler as s, runOnce as a, getDefaultWalletConnector as o } from "@ada-anvil/weld/core";
3
3
  class l extends s {
4
4
  async disconnect() {
5
5
  var t;
@@ -7,24 +7,24 @@ class l extends s {
7
7
  return (t = this.enabledApi) == null ? void 0 : t.disconnect();
8
8
  }
9
9
  }
10
- function c(e) {
10
+ function b(e) {
11
11
  return {
12
12
  key: "hodei",
13
- connector: i(l),
14
- initialize: a((t) => o({
13
+ connector: o(l),
14
+ initialize: a((t) => ((e == null ? void 0 : e.initialize) ?? n)({
15
15
  debug: t.config.debug,
16
16
  ...e,
17
- onError: (r) => {
18
- var n;
19
- t.config.debug && console.error("[WELD] Hodei socket error, disconnecting.", r), (n = e == null ? void 0 : e.onError) == null || n.call(e, r, t), t.wallet.disconnect();
17
+ onError: (i) => {
18
+ var r;
19
+ t.wallet.key === "hodei" && (t.config.debug && console.error("[WELD] Hodei socket error, disconnecting.", i), (r = e == null ? void 0 : e.onError) == null || r.call(e, i, t), t.wallet.disconnect());
20
20
  },
21
- onClose: (r) => {
22
- var n;
23
- t.config.debug && console.error("[WELD] Hodei socket closed, disconnecting.", r), (n = e == null ? void 0 : e.onClose) == null || n.call(e, r, t), t.wallet.disconnect();
21
+ onClose: (i) => {
22
+ var r;
23
+ t.wallet.key === "hodei" && (t.config.debug && console.error("[WELD] Hodei socket closed, disconnecting.", i), (r = e == null ? void 0 : e.onClose) == null || r.call(e, i, t), t.wallet.disconnect());
24
24
  },
25
- onWalletUpdate: (r) => {
26
- var n;
27
- t.config.debug && console.log("[WELD] Hodei wallet updated, updating state.", r), (n = e == null ? void 0 : e.onWalletUpdate) == null || n.call(e, r, t), t.wallet.updateState();
25
+ onWalletUpdate: (i) => {
26
+ var r;
27
+ t.wallet.key === "hodei" && (t.config.debug && console.log("[WELD] Hodei wallet updated, updating state.", i), (r = e == null ? void 0 : e.onWalletUpdate) == null || r.call(e, i, t), t.wallet.updateState());
28
28
  }
29
29
  }) ? (t.extensions.registerWallets([
30
30
  {
@@ -40,5 +40,5 @@ function c(e) {
40
40
  }
41
41
  export {
42
42
  l as HodeiHandler,
43
- c as hodeiPlugin
43
+ b as hodeiPlugin
44
44
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ada-anvil/weld-plugin-hodei",
3
- "version": "0.0.6",
3
+ "version": "0.0.8",
4
4
  "files": [
5
5
  "**"
6
6
  ],
@@ -19,7 +19,7 @@
19
19
  "@ada-anvil/weld": ">=0.7.0"
20
20
  },
21
21
  "dependencies": {
22
- "@ada-anvil/hodei-client": "^0.0.8"
22
+ "@ada-anvil/hodei-client": "^0.0.9"
23
23
  },
24
24
  "license": "MIT",
25
25
  "publishConfig": {
package/types/lib.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { initialize as defaultInitialize } from '@ada-anvil/hodei-client';
1
2
  import { WeldInstance } from '@ada-anvil/weld';
2
3
  import { DefaultWalletHandler } from '@ada-anvil/weld/core';
3
4
  import { WeldPlugin } from '@ada-anvil/weld/plugins';
@@ -35,5 +36,6 @@ export type HodeiPluginConfig = {
35
36
  reason: string;
36
37
  }, weld: WeldInstance): void;
37
38
  onWalletUpdate(data: WalletUpdateData, weld: WeldInstance): void;
39
+ initialize: typeof defaultInitialize;
38
40
  };
39
41
  export declare function hodeiPlugin(config?: Partial<HodeiPluginConfig>): WeldPlugin;