shogun-core
Version:
SHOGUN SDK - Core library for Shogun SDK
1 lines • 127 kB
JavaScript
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.ShogunCore=t():e.ShogunCore=t()}(this,(()=>(()=>{var e,t={197:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),t.ShogunCore=t.ShogunEventEmitter=t.ShogunStorage=t.Gun=t.SEA=void 0;const s=r(58851),o=r(2077),a=r(14134),c=r(45628),u=r(23358),l=r(4643),g=r(50074),d=r(4933),h=r(48098),f=r(48050),p=r(78371),w=r(16868);Object.defineProperty(t,"Gun",{enumerable:!0,get:function(){return w.Gun}}),Object.defineProperty(t,"SEA",{enumerable:!0,get:function(){return w.SEA}}),i(r(23358),t),i(r(58851),t),i(r(2077),t),i(r(5307),t),i(r(50074),t);var y=r(4643);Object.defineProperty(t,"ShogunStorage",{enumerable:!0,get:function(){return y.ShogunStorage}});var m=r(4465);Object.defineProperty(t,"ShogunEventEmitter",{enumerable:!0,get:function(){return m.ShogunEventEmitter}});t.ShogunCore=class{static API_VERSION="2.0.0";_gun;_user=null;gundb;storage;eventEmitter;provider;config;rx;plugins=new Map;currentAuthMethod;constructor(e){(0,c.log)("Initializing Shogun"),this.config=e,this.storage=new l.ShogunStorage,this.eventEmitter=new a.EventEmitter,e.logging&&(0,c.configureLogging)(e.logging),u.ErrorHandler.addListener((e=>{this.eventEmitter.emit("error",{action:e.code,message:e.message,type:e.type})}));try{e.gunInstance?this._gun=e.gunInstance:this._gun=(0,w.Gun)(e.peers||[])}catch(e){throw(0,c.logError)("Error creating Gun instance:",e),new Error(`Failed to create Gun instance: ${e}`)}try{this.gundb=new s.GunInstance(this._gun,e.scope||""),this._gun=this.gundb.gun}catch(e){throw(0,c.logError)("Error initializing GunInstance:",e),new Error(`Failed to initialize GunInstance: ${e}`)}try{this._user=this._gun.user().recall({sessionStorage:!0})}catch(e){throw(0,c.logError)("Error initializing Gun user:",e),new Error(`Failed to initialize Gun user: ${e}`)}if(this.rx=new o.GunRxJS(this._gun),this.registerBuiltinPlugins(e),e.plugins?.autoRegister&&e.plugins.autoRegister.length>0)for(const t of e.plugins.autoRegister)try{this.register(t)}catch(e){(0,c.logError)(`Failed to auto-register plugin ${t.name}:`,e)}(0,c.log)("ShogunSDK initialized! 🚀")}get gun(){return this._gun}get user(){return this._user}registerBuiltinPlugins(e){try{if(e.webauthn?.enabled){const e=new d.WebauthnPlugin;e._category=g.PluginCategory.Authentication,this.register(e),(0,c.log)("Webauthn plugin registered")}if(e.web3?.enabled){const e=new h.Web3ConnectorPlugin;e._category=g.PluginCategory.Authentication,this.register(e),(0,c.log)("Web3Connector plugin registered")}if(e.nostr?.enabled){const e=new f.NostrConnectorPlugin;e._category=g.PluginCategory.Authentication,this.register(e),(0,c.log)("NostrConnector plugin registered")}if(e.oauth?.enabled){const t=new p.OAuthPlugin;t._category=g.PluginCategory.Authentication,e.oauth.providers&&t.configure({providers:e.oauth.providers}),this.register(t),(0,c.log)("OAuth plugin registered with providers:",e.oauth.providers)}}catch(e){(0,c.logError)("Error registering builtin plugins:",e)}}register(e){if(this.plugins.has(e.name))throw new Error(`Plugin with name "${e.name}" already registered`);e.initialize(this),this.plugins.set(e.name,e),(0,c.log)(`Registered plugin: ${e.name}`)}unregister(e){const t=this.plugins.get(e);t?(t.destroy&&t.destroy(),this.plugins.delete(e),(0,c.log)(`Unregistered plugin: ${e}`)):(0,c.log)(`Plugin "${e}" not found, nothing to unregister`)}getPlugin(e){return this.plugins.get(e)}hasPlugin(e){return this.plugins.has(e)}getPluginsByCategory(e){const t=[];return this.plugins.forEach((r=>{r._category===e&&t.push(r)})),t}getAuthenticationMethod(e){switch(e){case"webauthn":return this.getPlugin(g.CorePlugins.WebAuthn);case"web3":return this.getPlugin(g.CorePlugins.Web3);case"nostr":return this.getPlugin(g.CorePlugins.Nostr);default:return{login:(e,t)=>{this.login(e,t)},signUp:(e,t,r)=>{this.signUp(e,t,r)}}}}getRecentErrors(e=10){return u.ErrorHandler.getRecentErrors(e)}configureLogging(e){(0,c.configureLogging)(e),(0,c.log)("Logging reconfigured with new settings")}isLoggedIn(){return this.gundb.isLoggedIn()}logout(){try{if(!this.isLoggedIn())return void(0,c.log)("Logout ignored: user not authenticated");this.gundb.logout(),this.eventEmitter.emit("auth:logout",{}),(0,c.log)("Logout completed successfully")}catch(e){u.ErrorHandler.handle(u.ErrorType.AUTHENTICATION,"LOGOUT_FAILED",e instanceof Error?e.message:"Error during logout",e)}}async login(e,t){(0,c.log)("Login");try{if((0,c.log)(`Login attempt for user: ${e}`),!e||!t)return{success:!1,error:"Username and password are required"};this.currentAuthMethod||(this.currentAuthMethod="password",(0,c.log)("Authentication method set to default: password"));const r=this.config?.timeouts?.login??15e3,n=new Promise((async n=>{const i=setTimeout((()=>{n({success:!1,error:"Login timeout"})}),r);try{const r=await this.gundb.login(e,t);clearTimeout(i),r.success?n({success:!0,userPub:r.userPub,username:r.username}):n({success:!1,error:r.error||"Wrong user or password"})}catch(e){clearTimeout(i),n({success:!1,error:e.message||"Login error"})}})),i=await n;return i.success&&(this.eventEmitter.emit("auth:login",{userPub:i.userPub??""}),(0,c.log)(`Current auth method before wallet check: ${this.currentAuthMethod}`)),i}catch(e){return u.ErrorHandler.handle(u.ErrorType.AUTHENTICATION,"LOGIN_FAILED",e.message??"Unknown error during login",e),{success:!1,error:e.message??"Unknown error during login"}}}async signUp(e,t,r){(0,c.log)("Sign up");try{if(!e||!t)return{success:!1,error:"Username and password are required"};if(void 0!==r&&t!==r)return{success:!1,error:"Passwords do not match"};if(t.length<6)return{success:!1,error:"Password must be at least 6 characters long"};this.eventEmitter.emit("debug",{action:"signup_start",username:e,timestamp:Date.now()}),(0,c.log)(`Attempting user registration: ${e}`);const n=this.config?.timeouts?.signup??3e4,i=new Promise((async r=>{const i=setTimeout((()=>{r({success:!1,error:"Registration timeout"})}),n);try{const n=await this.gundb.signUp(e,t);clearTimeout(i),n.success?(this.eventEmitter.emit("debug",{action:"signup_complete",username:e,userPub:n.userPub,timestamp:Date.now()}),this.eventEmitter.emit("auth:signup",{userPub:n.userPub??"",username:e})):this.eventEmitter.emit("debug",{action:"signup_failed",username:e,error:n.error,timestamp:Date.now()}),r(n)}catch(e){clearTimeout(i),r({success:!1,error:e.message||"Registration error"})}}));return await i}catch(t){return(0,c.logError)(`Error during registration for user ${e}:`,t),this.eventEmitter.emit("debug",{action:"signup_exception",username:e,error:t.message||"Unknown error",timestamp:Date.now()}),{success:!1,error:t.message??"Unknown error during registration"}}}emit(e,t){return this.eventEmitter.emit(e,t)}on(e,t){return this.eventEmitter.on(e,t),this}once(e,t){return this.eventEmitter.once(e,t),this}off(e,t){return this.eventEmitter.off(e,t),this}removeAllListeners(e){return this.eventEmitter.removeAllListeners(e),this}setAuthMethod(e){(0,c.log)(`Setting authentication method from '${this.currentAuthMethod}' to '${e}'`),this.currentAuthMethod=e,(0,c.log)(`Authentication method successfully set to: ${e}`)}getAuthMethod(){return this.currentAuthMethod}}},1126:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},2077:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.GunRxJS=void 0;const n=r(79364),i=r(92794);t.GunRxJS=class{gun;user;constructor(e){this.gun=e,this.user=e.user().recall({sessionStorage:!0})}getUser(){return this.user}getUserPub(){return this.user.is?.pub}observe(e){return new n.Observable((t=>{const r="string"==typeof e?this.gun.get(e):e,n=r.on(((e,r)=>{if(null!=e)if("object"==typeof e&&null!==e){const r=this.removeGunMeta(e);t.next(r)}else t.next(e);else t.next(null)}));return()=>{n&&"function"==typeof n&&n(),r.off()}})).pipe((0,i.distinctUntilChanged)(((e,t)=>JSON.stringify(e)===JSON.stringify(t))))}match(e,t){return new n.Observable((r=>{const n="string"==typeof e?this.gun.get(e):e,i={},s=n.map().on(((e,n)=>{if("_"===n||!e)return;if(t&&!t(e))return void(i[n]&&(delete i[n],r.next(Object.values(i))));const s="object"==typeof e?this.removeGunMeta(e):e;i[n]=s,r.next(Object.values(i))}));return()=>{s&&"function"==typeof s&&s(),n.off()}}))}put(e,t){const r="string"==typeof e?this.gun.get(e):e;return new n.Observable((e=>{r.put(t,(r=>{r.err?e.error(new Error(r.err)):(e.next(t),e.complete())}))}))}set(e,t){const r="string"==typeof e?this.gun.get(e):e;return new n.Observable((e=>{r.set(t,(r=>{r.err?e.error(new Error(r.err)):(e.next(t),e.complete())}))}))}once(e){const t="string"==typeof e?this.gun.get(e):e;return new n.Observable((e=>{t.once((t=>{if(null==t)return e.next(null),void e.complete();const r="object"==typeof t?this.removeGunMeta(t):t;e.next(r),e.complete()}))}))}compute(e,t){const r=e.map((e=>"string"==typeof e?this.observe(e):e));return new n.Observable((n=>{let i=new Array(e.length).fill(void 0),s=new Array(e.length).fill(!1);const o=r.map(((e,r)=>e.subscribe({next:e=>{if(i[r]=e,i.every((e=>void 0!==e)))try{const e=t(...i);n.next(e)}catch(e){n.error(e)}},error:e=>n.error(e),complete:()=>{s[r]=!0,s.every((e=>e))&&n.complete()}})));return()=>{o.forEach((e=>e.unsubscribe()))}}))}userPut(e,t){return new n.Observable((r=>{this.gun.user().get(e).put(t,(e=>{e.err?r.error(new Error(e.err)):(r.next(t),r.complete())}))}))}userGet(e){return this.observe(this.gun.user().get(e))}observeUser(e){return this.observe(this.gun.user().get(e))}removeGunMeta(e){if(!e||"object"!=typeof e)return e;const t=Array.isArray(e)?[]:{};return Object.keys(e).forEach((r=>{if("_"===r||"#"===r)return;const n=e[r];t[r]=n&&"object"==typeof n?this.removeGunMeta(n):n})),t}}},4465:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShogunEventEmitter=void 0;const n=r(14134);class i extends n.EventEmitter{emit(e,t){return super.emit(e,t)}on(e,t){super.on(e,t)}off(e,t){super.off(e,t)}}t.ShogunEventEmitter=i},4643:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ShogunStorage=void 0;t.ShogunStorage=class{store;isTestMode;useLocalStorage;constructor(){if(this.store=new Map,this.isTestMode=!1,this.useLocalStorage=!1,"undefined"!=typeof localStorage&&!this.isTestMode)try{localStorage.setItem("_shogun_test","_shogun_test"),localStorage.removeItem("_shogun_test"),this.useLocalStorage=!0;const e=localStorage.getItem("shogun_keypair");e&&this.store.set("keypair",JSON.parse(e))}catch(e){this.useLocalStorage=!1,this.isTestMode}}async getPair(){return this.getPairSync()}getPairSync(){return this.store.get("keypair")||null}async setPair(e){if(this.store.set("keypair",e),this.useLocalStorage)try{localStorage.setItem("shogun_keypair",JSON.stringify(e))}catch(e){this.isTestMode}}clearAll(){if(this.store.clear(),this.useLocalStorage)try{localStorage.removeItem("shogun_keypair")}catch(e){this.isTestMode}}getItem(e){const t=this.store.get(e);return void 0!==t?JSON.stringify(t):null}setItem(e,t){try{const r=JSON.parse(t);if(this.store.set(e,r),this.useLocalStorage)try{localStorage.setItem(e,t)}catch(e){this.isTestMode}}catch(r){if(this.store.set(e,t),this.useLocalStorage)try{localStorage.setItem(e,t)}catch(e){this.isTestMode}}}removeItem(e){if(this.store.delete(e),this.useLocalStorage)try{localStorage.removeItem(e)}catch(e){this.isTestMode}}}},4933:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.WebauthnPlugin=void 0;const n=r(34586),i=r(37510),s=r(43188),o=r(45628),a=r(14193),c=r(23358);class u extends n.BasePlugin{name="webauthn";version="1.0.0";description="Provides WebAuthn authentication functionality for ShogunCore";webauthn=null;signer=null;initialize(e){super.initialize(e),this.webauthn=new i.Webauthn(e.gun),this.signer=new s.WebAuthnSigner(this.webauthn),(0,o.log)("WebAuthn plugin initialized with signer support")}destroy(){this.webauthn=null,this.signer=null,super.destroy(),(0,o.log)("WebAuthn plugin destroyed")}assertWebauthn(){if(this.assertInitialized(),!this.webauthn)throw new Error("WebAuthn module not initialized");return this.webauthn}assertSigner(){if(this.assertInitialized(),!this.signer)throw new Error("WebAuthn signer not initialized");return this.signer}isSupported(){return this.assertWebauthn().isSupported()}async generateCredentials(e,t,r=!1){return this.assertWebauthn().generateCredentials(e,t,r)}async createAccount(e,t,r=!1){return this.assertWebauthn().createAccount(e,t,r)}async authenticateUser(e,t,r){return this.assertWebauthn().authenticateUser(e,t,r)}abortAuthentication(){this.assertWebauthn().abortAuthentication()}async removeDevice(e,t,r){return this.assertWebauthn().removeDevice(e,t,r)}async createSigningCredential(e){try{return(0,o.log)(`Creating signing credential for user: ${e}`),await this.assertSigner().createSigningCredential(e)}catch(e){throw(0,o.logError)(`Error creating signing credential: ${e.message}`),e}}createAuthenticator(e){try{return(0,o.log)(`Creating authenticator for credential: ${e}`),this.assertSigner().createAuthenticator(e)}catch(e){throw(0,o.logError)(`Error creating authenticator: ${e.message}`),e}}async createDerivedKeyPair(e,t,r){try{return(0,o.log)(`Creating derived key pair for credential: ${e}`),await this.assertSigner().createDerivedKeyPair(e,t,r)}catch(e){throw(0,o.logError)(`Error creating derived key pair: ${e.message}`),e}}async signWithDerivedKeys(e,t,r,n){try{return(0,o.log)(`Signing data with derived keys for credential: ${t}`),await this.assertSigner().signWithDerivedKeys(e,t,r,n)}catch(e){throw(0,o.logError)(`Error signing with derived keys: ${e.message}`),e}}getSigningCredential(e){return this.assertSigner().getCredential(e)}listSigningCredentials(){return this.assertSigner().listCredentials()}removeSigningCredential(e){return this.assertSigner().removeCredential(e)}async createGunUserFromSigningCredential(e,t){try{const r=this.assertInitialized();return(0,o.log)(`Creating Gun user from signing credential: ${e}`),await this.assertSigner().createGunUser(e,t,r.gun)}catch(e){throw(0,o.logError)(`Error creating Gun user from signing credential: ${e.message}`),e}}getGunUserPubFromSigningCredential(e){return this.assertSigner().getGunUserPub(e)}getHashedCredentialId(e){return this.assertSigner().getHashedCredentialId(e)}async verifyConsistency(e,t,r){try{return(0,o.log)(`Verifying consistency for credential: ${e}`),await this.assertSigner().verifyConsistency(e,t,r)}catch(e){return(0,o.logError)(`Error verifying consistency: ${e.message}`),{consistent:!1}}}async setupConsistentOneshotSigning(e){try{(0,o.log)(`Setting up consistent oneshot signing for: ${e}`);const t=await this.createSigningCredential(e),r=this.createAuthenticator(t.id);return{credential:t,authenticator:r,gunUser:await this.createGunUserFromSigningCredential(t.id,e),pub:t.pub,hashedCredentialId:t.hashedCredentialId}}catch(e){throw(0,o.logError)(`Error setting up consistent oneshot signing: ${e.message}`),e}}async login(e){(0,o.log)("Login with WebAuthn");try{const t=this.assertInitialized();if((0,o.log)(`Attempting WebAuthn login for user: ${e}`),!e)throw new Error("Username required for WebAuthn login");if(!this.isSupported())throw new Error("WebAuthn is not supported by this browser");const r=await this.generateCredentials(e,null,!0);if(!r?.success)throw new Error(r?.error||"WebAuthn verification failed");const n=a.ethers.keccak256(a.ethers.toUtf8Bytes(r.credentialId||""));t.setAuthMethod("webauthn");const i=await t.login(e,n);return i.success?((0,o.log)(`WebAuthn login completed successfully for user: ${e}`),{...i}):i}catch(e){return(0,o.logError)(`Error during WebAuthn login: ${e}`),c.ErrorHandler.handle(c.ErrorType.WEBAUTHN,"WEBAUTHN_LOGIN_ERROR",e.message||"Error during WebAuthn login",e),{success:!1,error:e.message||"Error during WebAuthn login"}}}async signUp(e){(0,o.log)("Sign up with WebAuthn");try{const t=this.assertInitialized();if((0,o.log)(`Attempting WebAuthn registration for user: ${e}`),!e)throw new Error("Username required for WebAuthn registration");if(!this.isSupported())throw new Error("WebAuthn is not supported by this browser");const r=await this.generateCredentials(e,null,!1);if(!r?.success)throw new Error(r?.error||"Unable to generate WebAuthn credentials");const n=a.ethers.keccak256(a.ethers.toUtf8Bytes(r.credentialId||""));t.setAuthMethod("webauthn");const i=await t.signUp(e,n);return i.success?((0,o.log)(`WebAuthn registration completed successfully for user: ${e}`),t.emit("webauthn:register",{username:e,credentialId:r.credentialId}),t.emit("auth:signup",{userPub:i.userPub,username:e,method:"webauthn"}),{...i}):i}catch(e){return(0,o.logError)(`Error during WebAuthn registration: ${e}`),c.ErrorHandler.handle(c.ErrorType.WEBAUTHN,"WEBAUTHN_SIGNUP_ERROR",e.message||"Error during WebAuthn registration",e),{success:!1,error:e.message||"Error during WebAuthn registration"}}}}t.WebauthnPlugin=u},5307:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)},s=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.oauthChain=t.OAuthPlugin=t.OAuthConnector=t.nostrChain=t.NostrConnectorPlugin=t.NostrConnector=t.web3Chain=t.Web3ConnectorPlugin=t.Web3Connector=t.webauthnChain=t.WebauthnPlugin=t.Webauthn=t.BasePlugin=void 0;var o=r(34586);Object.defineProperty(t,"BasePlugin",{enumerable:!0,get:function(){return o.BasePlugin}});var a=r(37510);Object.defineProperty(t,"Webauthn",{enumerable:!0,get:function(){return a.Webauthn}});var c=r(4933);Object.defineProperty(t,"WebauthnPlugin",{enumerable:!0,get:function(){return c.WebauthnPlugin}});var u=r(77909);Object.defineProperty(t,"webauthnChain",{enumerable:!0,get:function(){return s(u).default}});var l=r(48089);Object.defineProperty(t,"Web3Connector",{enumerable:!0,get:function(){return l.Web3Connector}});var g=r(48098);Object.defineProperty(t,"Web3ConnectorPlugin",{enumerable:!0,get:function(){return g.Web3ConnectorPlugin}});var d=r(75655);Object.defineProperty(t,"web3Chain",{enumerable:!0,get:function(){return s(d).default}});var h=r(37897);Object.defineProperty(t,"NostrConnector",{enumerable:!0,get:function(){return h.NostrConnector}});var f=r(48050);Object.defineProperty(t,"NostrConnectorPlugin",{enumerable:!0,get:function(){return f.NostrConnectorPlugin}});var p=r(84407);Object.defineProperty(t,"nostrChain",{enumerable:!0,get:function(){return s(p).default}});var w=r(17665);Object.defineProperty(t,"OAuthConnector",{enumerable:!0,get:function(){return w.OAuthConnector}});var y=r(78371);Object.defineProperty(t,"OAuthPlugin",{enumerable:!0,get:function(){return y.OAuthPlugin}}),i(r(1126),t);var m=r(90655);Object.defineProperty(t,"oauthChain",{enumerable:!0,get:function(){return s(m).default}})},7120:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.NetworkError=t.MultipleAuthError=t.TimeoutError=t.UserExists=t.InvalidCredentials=t.AuthError=t.GunError=void 0;class r extends Error{constructor(e){super(e),this.name="GunError"}}t.GunError=r;class n extends r{constructor(e){super(e),this.name="AuthError"}}t.AuthError=n;t.InvalidCredentials=class extends n{constructor(e="Credenziali non valide"){super(e),this.name="InvalidCredentials"}};t.UserExists=class extends n{constructor(e="Utente già esistente"){super(e),this.name="UserExists"}};t.TimeoutError=class extends r{constructor(e="Timeout durante l'operazione"){super(e),this.name="TimeoutError"}};t.MultipleAuthError=class extends n{constructor(e="Autenticazione multipla in corso"){super(e),this.name="MultipleAuthError"}};t.NetworkError=class extends r{}},14134:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.EventEmitter=void 0;const n=r(45628);t.EventEmitter=class{events;constructor(){this.events=new Map}on(e,t){this.events.has(e)||this.events.set(e,[]),this.events.get(e)?.push(t)}emit(e,t){if(!this.events.has(e))return!1;return(this.events.get(e)||[]).forEach((r=>{try{r(t)}catch(t){(0,n.logError)(`Error in event listener for ${String(e)}:`,t)}})),!0}off(e,t){if(!this.events.has(e))return;const r=this.events.get(e)||[],n=r.indexOf(t);-1!==n&&(r.splice(n,1),0===r.length?this.events.delete(e):this.events.set(e,r))}once(e,t){const r=n=>{t(n),this.off(e,r)};this.on(e,r)}removeAllListeners(e){e?this.events.delete(e):this.events.clear()}}},15340:()=>{},16868:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SEA=t.Gun=void 0;const n=r(24993);Object.defineProperty(t,"Gun",{enumerable:!0,get:function(){return n.Gun}}),Object.defineProperty(t,"SEA",{enumerable:!0,get:function(){return n.SEA}}),r(67410),r(78719),r(29617),r(10924),r(46402),r(76140)},17665:(e,t,r)=>{"use strict";var n=r(48287).Buffer;Object.defineProperty(t,"__esModule",{value:!0}),t.OAuthConnector=void 0;const i=r(14193),s=r(45628),o=r(14134);class a extends o.EventEmitter{DEFAULT_CONFIG={providers:{google:{clientId:"",clientSecret:"",redirectUri:`${this.getOrigin()}/auth/callback`,scope:["openid","email","profile"],authUrl:"https://accounts.google.com/o/oauth2/v2/auth",tokenUrl:"https://oauth2.googleapis.com/token",userInfoUrl:"https://www.googleapis.com/oauth2/v2/userinfo"},github:{clientId:"",clientSecret:"",redirectUri:`${this.getOrigin()}/auth/callback`,scope:["user:email"],authUrl:"https://github.com/login/oauth/authorize",tokenUrl:"https://github.com/login/oauth/access_token",userInfoUrl:"https://api.github.com/user"},discord:{clientId:"",clientSecret:"",redirectUri:`${this.getOrigin()}/auth/callback`,scope:["identify","email"],authUrl:"https://discord.com/api/oauth2/authorize",tokenUrl:"https://discord.com/api/oauth2/token",userInfoUrl:"https://discord.com/api/users/@me"},twitter:{clientId:"",clientSecret:"",redirectUri:`${this.getOrigin()}/auth/callback`,scope:["tweet.read","users.read"],authUrl:"https://twitter.com/i/oauth2/authorize",tokenUrl:"https://api.twitter.com/2/oauth2/token",userInfoUrl:"https://api.twitter.com/2/users/me"},custom:{clientId:"",clientSecret:"",redirectUri:"",scope:[],authUrl:"",tokenUrl:"",userInfoUrl:""}},usePKCE:!0,cacheDuration:864e5,timeout:6e4,maxRetries:3,retryDelay:1e3};config;userCache=new Map;memoryStorage=new Map;constructor(e={}){super(),this.config={...this.DEFAULT_CONFIG,...e,providers:{...this.DEFAULT_CONFIG.providers||{},...e.providers||{}}}}updateConfig(e){this.config={...this.config,...e,providers:{...this.config.providers||{},...e.providers||{}}},(0,s.logDebug)("OAuthConnector configuration updated",this.config)}getOrigin(){return"undefined"!=typeof window&&window.location?window.location.origin:"http://localhost:3000"}setItem(e,t){"undefined"!=typeof sessionStorage?sessionStorage.setItem(e,t):this.memoryStorage.set(e,t)}getItem(e){return"undefined"!=typeof sessionStorage?sessionStorage.getItem(e):this.memoryStorage.get(e)||null}removeItem(e){"undefined"!=typeof sessionStorage?sessionStorage.removeItem(e):this.memoryStorage.delete(e)}isSupported(){return"undefined"!=typeof URLSearchParams}getAvailableProviders(){return Object.keys(this.config.providers||{}).filter((e=>this.config.providers[e]?.clientId))}async generatePKCEChallenge(){const e=this.generateRandomString(128);return{codeVerifier:e,codeChallenge:await this.calculatePKCECodeChallenge(e)}}async calculatePKCECodeChallenge(e){if("undefined"!=typeof window&&window.crypto&&window.crypto.subtle){const t=(new TextEncoder).encode(e),r=await window.crypto.subtle.digest("SHA-256",t);return this.base64urlEncode(r)}{const t=r(91565).createHash("sha256").update(e).digest();return this.base64urlEncode(t)}}base64urlEncode(e){let t;if(void 0!==n&&n.isBuffer(e))t=e.toString("base64");else{const r=new Uint8Array(e);let n="";for(let e=0;e<r.length;e++)n+=String.fromCharCode(r[e]);t=window.btoa(n)}return t.replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}generateRandomString(e){const t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~";let n;if("undefined"!=typeof window&&window.crypto)n=new Uint8Array(e),window.crypto.getRandomValues(n);else{const t=r(91565);n=new Uint8Array(t.randomBytes(e))}return Array.from(n).map((e=>t[e%66])).join("")}async initiateOAuth(e){try{(0,s.logDebug)(`Initiating OAuth flow with ${e}`);const t=this.config.providers[e];if(!t||!t.clientId)throw new Error(`Provider ${e} not configured`);const r=this.generateRandomString(32);this.setItem(`oauth_state_${e}`,r);let n={};if(this.config.usePKCE){const{codeVerifier:t,codeChallenge:r}=await this.generatePKCEChallenge();this.setItem(`oauth_verifier_${e}`,t),n={code_challenge:r,code_challenge_method:"S256"}}const i=new URLSearchParams({client_id:t.clientId,redirect_uri:t.redirectUri,scope:t.scope.join(" "),response_type:"code",state:r,...n});let o=t.authUrl||"";if(!o)throw new Error(`Auth URL not configured for provider ${e}`);return o=o.includes("?")?`${o}&${i.toString()}`:`${o}?${i.toString()}`,this.emit("oauth_initiated",{provider:e,authUrl:o}),{success:!0,provider:e,authUrl:o}}catch(t){return(0,s.logError)(`Error initiating OAuth with ${e}:`,t),{success:!1,error:t.message}}}async completeOAuth(e,t,r){const n=this.config.providers?.[e];if(!n){const t=`Provider '${e}' is not configured.`;return(0,s.logError)(t),{success:!1,error:t}}try{const i=await this.exchangeCodeForToken(e,n,t,r);if(!i.access_token){const e="No access token received from provider";return(0,s.logError)(e,i),{success:!1,error:e}}const o=await this.fetchUserInfo(e,n,i.access_token);this.cacheUserInfo(o.id,e,o);const a=await this.generateCredentials(o,e);return this.emit("oauth_completed",{provider:e,userInfo:o,credentials:a}),{success:!0,provider:e,userInfo:o}}catch(t){return(0,s.logError)(`Error completing OAuth with ${e}:`,t),{success:!1,error:t.message}}}async generateCredentials(e,t){const r=this.config.providers?.[t];if(!r)throw new Error(`Provider ${t} is not configured.`);e.id;const n=e.email||`${e.id}@${t}.shogun`;try{(0,s.logDebug)(`Generating credentials for ${t} user: ${e.id}`);const r={username:n,password:await this.generateDeterministicPassword(e,t),provider:t};return this.cacheUserInfo(e.id,t,e),(0,s.logDebug)("OAuth credentials generated successfully"),r}catch(e){throw(0,s.logError)("Error generating OAuth credentials:",e),e}}async generateDeterministicPassword(e,t){const r=`${e.id}_${t}_${e.email||""}_shogun_oauth`;return i.ethers.keccak256(i.ethers.toUtf8Bytes(r)).slice(2,34)}async exchangeCodeForToken(e,t,r,n){const i=await this.getItem(`oauth_state_${e}`);if(n&&i!==n)throw new Error("Invalid state parameter");const o={client_id:t.clientId,code:r,redirect_uri:t.redirectUri,grant_type:"authorization_code"};if(t.clientSecret&&(o.client_secret=t.clientSecret),this.config.usePKCE){const t=await this.getItem(`oauth_verifier_${e}`);t?(o.code_verifier=t,this.removeItem(`oauth_verifier_${e}`)):(0,s.logWarn)(`PKCE is enabled, but no code verifier was found for ${e}.`)}const a=await fetch(t.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:new URLSearchParams(o)});if(!a.ok){const e=await a.json().catch((()=>({error:a.statusText})));throw new Error(`Token exchange failed: ${a.status} ${a.statusText} - ${JSON.stringify(e)}`)}return await a.json()}async fetchUserInfo(e,t,r){const n=await fetch(t.userInfoUrl,{headers:{Authorization:`Bearer ${r}`,Accept:"application/json"}});if(!n.ok)throw new Error(`Failed to get user info: ${n.statusText}`);const i=await n.json();return this.normalizeUserInfo(i,e)}normalizeUserInfo(e,t){switch(t){case"google":return{id:e.id,email:e.email,name:e.name,picture:e.picture,verified_email:e.verified_email,provider:t};case"github":return{id:e.id.toString(),email:e.email,name:e.name||e.login,picture:e.avatar_url,provider:t};default:return{id:e.id?.toString()||e.sub,email:e.email,name:e.name||e.username,picture:e.picture||e.avatar_url,provider:t}}}cacheUserInfo(e,t,r){const n=`${t}_${e}`,i={data:r,timestamp:Date.now(),provider:t,userId:e};this.userCache.set(n,i);try{localStorage.setItem(`shogun_oauth_user_${n}`,JSON.stringify(i))}catch(e){(0,s.logError)("Error caching user info:",e)}}getCachedUserInfo(e,t){const r=`${t}_${e}`,n=this.userCache.get(r);if(n&&n.data&&Date.now()-n.timestamp<=this.config.cacheDuration)return n.data;try{const e=localStorage.getItem(`shogun_oauth_user_${r}`);if(e){const t=JSON.parse(e);if(t.data&&Date.now()-t.timestamp<=this.config.cacheDuration)return this.userCache.set(r,t),t.data;localStorage.removeItem(`shogun_oauth_user_${r}`)}}catch(e){(0,s.logError)("Error reading cached user info:",e)}return null}clearUserCache(e,t){if(e&&t){const r=`${t}_${e}`;this.userCache.delete(r);try{localStorage.removeItem(`shogun_oauth_user_${r}`)}catch(e){(0,s.logError)("Error clearing user cache:",e)}}else{this.userCache.clear();try{const e=[];for(let t=0;t<localStorage.length;t++){const r=localStorage.key(t);r&&r.startsWith("shogun_oauth_user_")&&e.push(r)}e.forEach((e=>localStorage.removeItem(e)))}catch(e){(0,s.logError)("Error clearing all user caches:",e)}}}cleanup(){this.removeAllListeners(),this.userCache.clear()}}t.OAuthConnector=a},21302:function(e,t,r){"use strict";var n,i=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),s=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||(n=function(e){return n=Object.getOwnPropertyNames||function(e){var t=[];for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[t.length]=r);return t},n(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r=n(e),o=0;o<r.length;o++)"default"!==r[o]&&i(t,e,r[o]);return s(t,e),t}),a=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.GunInstance=void 0;const c=r(45628),u=r(23358),l=r(2077),g=o(r(7120)),d=o(r(90554)),h=o(r(50170)),f=a(r(67476));t.GunInstance=class{gun;user=null;crypto;utils;node;onAuthCallbacks=[];_rxjs;constructor(e,t="shogun"){if((0,c.log)("Initializing GunDB"),!e)throw new Error("Gun instance is required but was not provided");if("object"!=typeof e)throw new Error("Gun instance must be an object, received: "+typeof e);if("function"!=typeof e.user)throw new Error("Gun instance is invalid: gun.user is not a function. Received gun.user type: "+typeof e.user);if("function"!=typeof e.get)throw new Error("Gun instance is invalid: gun.get is not a function. Received gun.get type: "+typeof e.get);if("function"!=typeof e.on)throw new Error("Gun instance is invalid: gun.on is not a function. Received gun.on type: "+typeof e.on);this.gun=e,"undefined"!=typeof window?(window.ShogunDB=this,window.ShogunGun=e):void 0!==r.g&&(r.g.ShogunDB=this,r.g.ShogunGun=e);try{this.user=this.gun.user().recall({sessionStorage:!0})}catch(e){throw(0,c.logError)("Error initializing Gun user:",e),new Error(`Failed to initialize Gun user: ${e}`)}this.subscribeToAuthEvents(),this.crypto=d,this.utils=h,this.node=this.gun.get(t),setTimeout((async()=>{try{const e=await this.restoreSession();e.success?(0,c.log)(`Session automatically restored for user: ${e.userPub}`):(0,c.log)(`No previous session to restore: ${e.error}`)}catch(e){(0,c.logError)("Error during automatic session restoration:",e)}}),500)}subscribeToAuthEvents(){this.gun.on("auth",(e=>{(0,c.log)("Auth event received:",e),e.err?u.ErrorHandler.handle(u.ErrorType.GUN,"AUTH_EVENT_ERROR",e.err,new Error(e.err)):this.notifyAuthListeners(e.sea?.pub||"")}))}notifyAuthListeners(e){const t=this.gun.user();this.onAuthCallbacks.forEach((e=>e(t)))}addPeer(e){this.gun.opt({peers:[e]}),(0,c.log)(`Added new peer: ${e}`)}removePeer(e){try{const t=this.gun._.opt;if(t&&t.peers){delete t.peers[e];const r=t.peers[e];r&&"function"==typeof r.close&&r.close(),(0,c.log)(`Removed peer: ${e}`)}else(0,c.log)(`Peer not found in current connections: ${e}`)}catch(t){(0,c.logError)(`Error removing peer ${e}:`,t)}}getCurrentPeers(){try{const e=this.gun._.opt;return e&&e.peers?Object.keys(e.peers).filter((t=>{const r=e.peers[t];return r&&r.wire&&"bye"!==r.wire.hied})):[]}catch(e){return(0,c.logError)("Error getting current peers:",e),[]}}getAllConfiguredPeers(){try{const e=this.gun._.opt;return e&&e.peers?Object.keys(e.peers):[]}catch(e){return(0,c.logError)("Error getting configured peers:",e),[]}}getPeerInfo(){try{const e=this.gun._.opt,t={};return e&&e.peers&&Object.keys(e.peers).forEach((r=>{const n=e.peers[r],i=n&&n.wire&&"bye"!==n.wire.hied,s=i?"connected":n&&n.wire?"disconnected":"not_initialized";t[r]={connected:i,status:s}})),t}catch(e){return(0,c.logError)("Error getting peer info:",e),{}}}reconnectToPeer(e){try{this.removePeer(e),setTimeout((()=>{this.addPeer(e),(0,c.log)(`Reconnected to peer: ${e}`)}),1e3)}catch(t){(0,c.logError)(`Error reconnecting to peer ${e}:`,t)}}resetPeers(e){try{const t=this.gun._.opt;t&&t.peers&&(Object.keys(t.peers).forEach((e=>{this.removePeer(e)})),e&&e.length>0&&e.forEach((e=>{this.addPeer(e)})),(0,c.log)(`Reset peers. New peers: ${e?e.join(", "):"none"}`))}catch(e){(0,c.logError)("Error resetting peers:",e)}}onAuth(e){this.onAuthCallbacks.push(e);const t=this.gun.user();return t&&t.is&&e(t),()=>{const t=this.onAuthCallbacks.indexOf(e);-1!==t&&this.onAuthCallbacks.splice(t,1)}}navigateToPath(e,t){if(!t)return e;return t.split("/").filter((e=>e.length>0)).reduce(((e,t)=>e.get(t)),e)}getGun(){return this.gun}getUser(){return this.gun.user()}get(e){return this.navigateToPath(this.gun,e)}async put(e,t){return new Promise((r=>{this.navigateToPath(this.gun,e).put(t,(e=>{r(e.err?{success:!1,error:e.err}:{success:!0})}))}))}async set(e,t){return new Promise((r=>{this.navigateToPath(this.gun,e).set(t,(e=>{r(e.err?{success:!1,error:e.err}:{success:!0})}))}))}async remove(e){return new Promise((t=>{this.navigateToPath(this.gun,e).put(null,(e=>{t(e.err?{success:!1,error:e.err}:{success:!0})}))}))}async signUp(e,t){(0,c.log)("Attempting user registration:",e);try{if(t.length<8){const e="Passwords must be more than 8 characters long!";return(0,c.log)(e),{success:!1,error:e}}if(e.length<1){const e="Username must be more than 0 characters long!";return(0,c.log)(e),{success:!1,error:e}}(0,c.log)(`Checking if user ${e} exists in Gun's native system...`);const r=await new Promise((r=>{this.gun.user().auth(e,t,(e=>{e.err?r({exists:!1,error:e.err}):r({exists:!0,userPub:this.gun.user().is?.pub})}))}));if(r.exists){(0,c.log)(`User ${e} already exists and password is correct, syncing with tracking system...`);const t=r.userPub;if(!await this.checkUsernameExists(e)){(0,c.log)(`User ${e} not in tracking system, adding them...`);const r={username:e,pub:t,createdAt:Date.now(),lastLogin:Date.now()};await new Promise((n=>{this.gun.get(t).put(r,(t=>{t.err?(0,c.logError)(`Warning: Failed to save user metadata: ${t.err}`):(0,c.log)(`User metadata saved for: ${e}`),n()}))})),await new Promise((r=>{this.gun.get("users").set(this.gun.get(t),(t=>{t.err?(0,c.logError)(`Warning: Failed to add user to collection: ${t.err}`):(0,c.log)(`User added to collection: ${e}`),r()}))})),await new Promise((r=>{this.gun.get("usernames").get(e).put(t,(n=>{n.err?(0,c.logError)(`Warning: Could not create username mapping: ${n.err}`):(0,c.log)(`Username mapping created: ${e} -> ${t}`),r()}))}))}return{success:!0,userPub:t,username:e,message:"User already exists and was synced with tracking system"}}(0,c.log)(`Creating new user: ${e}`);const n=await new Promise((r=>{this.gun.user().create(e,t,(t=>{t.err?((0,c.logError)(`User creation error: ${t.err}`),r({success:!1,error:t.err})):((0,c.log)(`User created successfully: ${e}`),r({success:!0,pub:t.pub}))}))}));if(!n.success)return n;const i=await new Promise((r=>{this.gun.user().auth(e,t,(e=>{e.err?((0,c.logError)(`Authentication after creation failed: ${e.err}`),r({success:!1,error:e.err})):r({success:!0,userPub:this.gun.user().is?.pub})}))}));if(!i.success)return{success:!1,error:"User created but authentication failed"};const s=i.userPub;(0,c.log)(`User authentication successful after creation: ${e} (${s})`);const o={username:e,pub:s,createdAt:Date.now(),lastLogin:Date.now()};try{await new Promise((t=>{this.gun.get(s).put(o,(r=>{r.err?(0,c.logError)(`Warning: Failed to save user metadata: ${r.err}`):(0,c.log)(`User metadata saved for: ${e}`),t()}))})),await new Promise((t=>{this.gun.get("users").set(this.gun.get(s),(r=>{r.err?(0,c.logError)(`Warning: Failed to add user to collection: ${r.err}`):(0,c.log)(`User added to collection: ${e}`),t()}))})),await new Promise((t=>{this.gun.get("usernames").get(e).put(s,(r=>{r.err?(0,c.logError)(`Warning: Could not create username mapping: ${r.err}`):(0,c.log)(`Username mapping created: ${e} -> ${s}`),t()}))}))}catch(e){(0,c.logError)(`Warning: Could not update tracking system: ${e}`)}return this._savePair(),{success:!0,userPub:s,username:e,message:"User created successfully"}}catch(t){return(0,c.logError)(`Exception during signup for ${e}: ${t}`),{success:!1,error:String(t)}}}async checkUsernameExists(e){try{const t=await new Promise((t=>{this.gun.get("usernames").get(e).once((e=>{t(e||null)}))}));if(t){return await new Promise((e=>{this.gun.get(t).once((t=>{e(t)}))}))}return await new Promise((t=>{let r,n=!1;this.gun.get("users").map().once(((i,s)=>{!n&&i&&i.username===e&&(n=!0,clearTimeout(r),t(i))})),r=setTimeout((()=>{r&&clearTimeout(r),n||t(null)}),2e3)}))}catch(e){return(0,c.logError)(`Error checking username existence: ${e}`),null}}async login(e,t,r){(0,c.log)(`Attempting login for user: ${e}`);try{if(!(await new Promise((r=>{this.gun.user().auth(e,t,(t=>{t.err?((0,c.logError)(`Login error for ${e}: ${t.err}`),r({success:!1,error:t.err})):((0,c.log)(`Login successful for: ${e}`),r({success:!0,ack:t}))}))}))).success){const t={success:!1,error:`User '${e}' not found. Please check your username or register first.`};return r&&r(t),t}const n=this.gun.user().is?.pub;if(!n){const e={success:!1,error:"Authentication failed: No user pub returned."};return r&&r(e),e}(0,c.log)(`Gun.js authentication successful for: ${e} (${n})`);try{if(await this.checkUsernameExists(e))(0,c.log)(`User ${e} found in tracking system, updating last login...`),this.gun.get(n).get("lastLogin").put(Date.now());else{(0,c.log)(`User ${e} not found in tracking system, adding them...`);const t={username:e,pub:n,createdAt:Date.now(),lastLogin:Date.now()};await new Promise(((r,i)=>{this.gun.get(n).put(t,(t=>{t.err?((0,c.logError)(`Warning: Failed to save user metadata: ${t.err}`),r()):((0,c.log)(`User metadata saved for: ${e}`),r())}))})),await new Promise(((t,r)=>{this.gun.get("users").set(this.gun.get(n),(r=>{r.err?((0,c.logError)(`Warning: Failed to add user to collection: ${r.err}`),t()):((0,c.log)(`User added to collection: ${e}`),t())}))})),await new Promise(((t,r)=>{this.gun.get("usernames").get(e).put(n,(r=>{r.err?((0,c.logError)(`Warning: Could not create username mapping: ${r.err}`),t()):((0,c.log)(`Username mapping created: ${e} -> ${n}`),t())}))}))}}catch(e){(0,c.logError)(`Warning: Could not sync with tracking system: ${e}`)}(0,c.log)(`Login completed successfully for: ${e} (${n})`),this._savePair();const i={success:!0,userPub:n,username:e};return r&&r(i),i}catch(t){(0,c.logError)(`Exception during login for ${e}: ${t}`);const n={success:!1,error:String(t)};return r&&r(n),n}}_savePair(){try{const e=this.gun.user(),t=e?._?.sea,r=e?.is;if(t&&r&&"undefined"!=typeof localStorage){localStorage.setItem("gun/pair",JSON.stringify(t));const e={pub:r.pub,alias:r.alias||"",timestamp:Date.now()};localStorage.setItem("gun/session",JSON.stringify(e)),(0,c.log)(`Session saved for user: ${r.alias||r.pub}`)}}catch(e){(0,c.logError)("Error saving auth pair and session:",e)}}async restoreSession(){try{if("undefined"==typeof localStorage)return{success:!1,error:"localStorage not available"};const e=localStorage.getItem("gun/session"),t=localStorage.getItem("gun/pair");if(!e||!t)return(0,c.log)("No saved session found"),{success:!1,error:"No saved session"};const r=JSON.parse(e),n=JSON.parse(t),i=Date.now()-r.timestamp;if(i>6048e5)return(0,c.log)("Session expired, clearing storage"),localStorage.removeItem("gun/session"),localStorage.removeItem("gun/pair"),{success:!1,error:"Session expired"};(0,c.log)(`Attempting to restore session for user: ${r.alias||r.pub}`);const s=this.gun.user();s._={sea:n};return await new Promise((e=>{try{s.recall({sessionStorage:!0},(t=>{t.err?((0,c.logError)(`Session recall error: ${t.err}`),e(!1)):e(!0)}))}catch(t){(0,c.logError)(`Session recall exception: ${t}`),e(!1)}setTimeout((()=>e(!1)),3e3)}))&&s.is?.pub===r.pub?((0,c.log)(`Session restored successfully for: ${r.alias||r.pub}`),{success:!0,userPub:r.pub}):((0,c.log)("Session restoration failed, clearing storage"),localStorage.removeItem("gun/session"),localStorage.removeItem("gun/pair"),{success:!1,error:"Session restoration failed"})}catch(e){return(0,c.logError)(`Error restoring session: ${e}`),{success:!1,error:String(e)}}}logout(){try{if(!this.isLoggedIn())return void(0,c.log)("No user logged in, skipping logout");const e=this.getCurrentUser();(0,c.log)(`Logging out user: ${e?.pub||"unknown"}`),this.gun.user().leave(),"undefined"!=typeof localStorage&&(localStorage.removeItem("gun/pair"),localStorage.removeItem("gun/session"),localStorage.removeItem("pair"),(0,c.log)("Local session data cleared")),"undefined"!=typeof sessionStorage&&(sessionStorage.removeItem("gun/"),sessionStorage.removeItem("gun/user"),sessionStorage.removeItem("gun/auth"),(0,c.log)("Session storage cleared")),(0,c.log)("Logout completed successfully")}catch(e){(0,c.logError)("Error during logout:",e)}}isLoggedIn(){return!!this.gun.user()?.is?.pub}getCurrentUser(){const e=this.gun.user()?.is?.pub;return e?{pub:e,user:this.gun.user()}:null}rx(){return this._rxjs||(this._rxjs=new l.GunRxJS(this.gun)),this._rxjs}async setPasswordHint(e,t,r,n,i){(0,c.log)("Setting password hint for:",e);if(!(await this.login(e,t)).success)return{success:!1,error:"Authentication failed"};try{const e=await this.crypto.hashText(i.join("|")),t=await this.crypto.encrypt(r,e);return await this.saveUserData("security",{questions:n,hint:t}),{success:!0}}catch(e){return(0,c.logError)("Error setting password hint:",e),{success:!1,error:String(e)}}}async forgotPassword(e,t){(0,c.log)("Attempting password recovery for:",e);try{const e=this.gun.user().recall({sessionStorage:!0});if(!e||!e.is)return{success:!1,error:"User not found"};const r=await this.getUserData("security");if(!r||!r.hint)return{success:!1,error:"No password hint found"};const n=await this.crypto.decrypt(r.hint,await this.crypto.hashText(t.join("|")));return void 0===n?{success:!1,error:"Incorrect answers to security questions"}:{success:!0,hint:n}}catch(e){return(0,c.logError)("Error recovering password hint:",e),{success:!1,error:String(e)}}}async hashText(e){return this.crypto.hashText(e)}async encrypt(e,t){return this.crypto.encrypt(e,t)}async decrypt(e,t){return this.crypto.decrypt(e,t)}async saveUserData(e,t){return new Promise(((r,n)=>{const i=this.gun.user();i.is?this.navigateToPath(i,e).put(t,(e=>{e.err?n(new Error(e.err)):r()})):n(new Error("User not authenticated"))}))}async getUserData(e){return new Promise((t=>{const r=this.gun.user();r.is?this.navigateToPath(r,e).once((e=>{t(e)})):t(null)}))}async derive(e,t,r){try{(0,c.log)("Deriving cryptographic keys with options:",r);const n=await(0,f.default)(e,t,r);return(0,c.log)("Key derivation completed successfully"),n}catch(e){throw(0,c.logError)("Error during key derivation:",e),u.ErrorHandler.handle(u.ErrorType.ENCRYPTION,"KEY_DERIVATION_FAILED",e instanceof Error?e.message:"Failed to derive cryptographic keys",e),e}}async deriveP256(e,t){return this.derive(e,t,{includeP256:!0})}async deriveBitcoin(e,t){return this.derive(e,t,{includeSecp256k1Bitcoin:!0})}async deriveEthereum(e,t){return this.derive(e,t,{includeSecp256k1Ethereum:!0})}async deriveAll(e,t){return this.derive(e,t,{includeP256:!0,includeSecp256k1Bitcoin:!0,includeSecp256k1Ethereum:!0})}static Errors=g}},21638:()=>{},23358:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ErrorHandler=t.ErrorType=void 0,t.createError=s;const n=r(45628);var i;function s(e,t,r,n){return{type:e,code:t,message:r,originalError:n,timestamp:Date.now()}}!function(e){e.AUTHENTICATION="AuthenticationError",e.AUTHORIZATION="AuthorizationError",e.VALIDATION="ValidationError",e.NETWORK="NetworkError",e.DATABASE="DatabaseError",e.WALLET="WalletError",e.STORAGE="StorageError",e.ENCRYPTION="EncryptionError",e.SIGNATURE="SignatureError",e.ENVIRONMENT="EnvironmentError",e.SECURITY="SecurityError",e.GUN="GunError",e.STEALTH="StealthError",e.WEBAUTHN="WebAuthnError",e.PLUGIN="PluginError",e.UNKNOWN="UnknownError",e.CONNECTOR="ConnectorError",e.GENERAL="GeneralError",e.CONTRACT="ContractError",e.BIP32="BIP32Error",e.ETHEREUM="EthereumError",e.BITCOIN="BitcoinError"}(i||(t.ErrorType=i={}));t.ErrorHandler=class{static errors=[];static maxErrors=100;static listeners=[];static handleError(e){(0,n.logError)(`[${e.type}] ${e.code}: ${e.message}`),this.errors.push(e),this.errors.length>this.maxErrors&&(this.errors=this.errors.slice(-this.maxErrors)),this.notifyListeners(e)}static handle(e,t,r,i,o="error"){const a=i?`${r} - ${this.formatError(i)}`:r;switch(o){case"debug":(0,n.log)(`[${e}.${t}] (DEBUG) ${a}`);break;case"warn":(0,n.log)(`[${e}.${t}] (WARN) ${a}`);break;case"info":(0,n.log)(`[${e}.${t}] (INFO) ${a}`);break;default:(0,n.log)(`[${e}.${t}] (ERROR) ${a}`),i&&i instanceof Error&&(0,n.log)(i.stack||"No stack trace available")}const c=s(e,t,a,i);return this.handleError(c),c}static handleAndThrow(e,t,r,n){throw this.handle(e,t,r,n)}static getRecentErrors(e=10){return this.errors.slice(-Math.min(e,this.errors.length))}static addListener(e){this.listeners.push(e)}static removeListener(e){const t=this.listeners.indexOf(e);-1!==t&&this.listeners.splice(t,1)}static notifyListeners(e){for(const t of this.listeners)try{t(e)}catch(e){(0,n.logError)(`Error in error listener: ${e}`)}}static formatError(e){if(!e)return"Unknown error";if(e instanceof Error)return`${e.name}: ${e.message}`;if("string"==typeof e)return e;if("object"==typeof e)try{return JSON.stringify(e)}catch(t){return`Object: ${Object.prototype.toString.call(e)}`}return String(e)}static async withRetry(e,t,r,i=3,s=1e3){let o;for(let t=1;t<=i;t++)try{return await e()}catch(e){o=e;const r=s*t;t<i&&((0,n.log)(`Retrying operation after ${r}ms (attempt ${t}/${i})`),await new Promise((e=>setTimeout(e,r))))}throw this.handle(t,r,`Operation failed after ${i} attempts`,o)}static clearErrors(){this.errors=[]}static getErrorStats(){const e={total:this.errors.length,byType:{},byCode:{}};for(const t of this.errors)e.byType[t.type]=(e.byType[t.type]||0)+1,e.byCode[t.code]=(e.byCode[t.code]||0)+1;return e}}},24993:function(e,t,r){"use strict";var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.SEA=t.Gun=void 0;const i=n(r(54827));t.Gun=i.default;const s=n(r(38030));Object.defineProperty(t,"SEA",{enumerable:!0,get:function(){return s.default}})},28156:function(e,t,r){"use strict";var n=this&&this.__createBinding||(Object.create?function(e,t,r,n){void 0===n&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);i&&!("get"in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}:function(e,t,r,n){void 0===n&&(n=r),e[n]=t[r]}),i=this&&this.__exportStar||function(e,t){for(var r in e)"default"===r||Object.prototype.hasOwnProperty.call(t,r)||n(t,e,r)};Object.defineProperty(t,"__esModule",{value:!0}),i(r(197),t),i(r(5307),t)},34586:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.BasePlugin=void 0;const n=r(14134);class i extends n.EventEmitter{description;_category;core=null;initialize(e){this.core=e}destroy(){this.core=null}assertInitialized(){if(!this.core)throw new Error(`Plugin ${this.name} not initialized`);return this.core}}t.BasePlugin=i},37510:(e,t,r)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.Webauthn=void 0;const n=r(14193),i=r(23358),s=r(14134),o=r(45628),a=r(61731),c={rpName:"Shogun Wallet",timeout:6e4,userVerification:"preferred",attestation:"none",authenticatorAttachment:"platform",requireResidentKey:!1};class u extends s.EventEmitter{config;gunInstance;credential;abortController=null;constructor(e,t){super(),this.gunInstance=e,this.credential=null,this.config={...c,...t,rpId:t?.rpId??window.location.hostname.split(":")[0]}}validateUsername(e){if(!e||"string"!=typeof e)throw new Error("Username must be a non-empty string");if(e.length<3||e.length>64)throw new Error("Username must be between 3 and 64 characters");if(!/^[a-zA-Z0-9_-]+$/.test(e))throw new Error("Username can only contain letters, numbers, underscores and hyphens")}async createAccount(e,t,r=!1){try{this.validateUsername(e);const n=3