w3pk 0.10.4 → 0.11.1

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.
Files changed (63) hide show
  1. package/README.md +47 -95
  2. package/dist/chainlist/index.d.mts +2 -2
  3. package/dist/chainlist/index.d.ts +2 -2
  4. package/dist/chainlist/index.js.map +1 -1
  5. package/dist/chainlist/index.mjs.map +1 -1
  6. package/dist/index.d.mts +940 -892
  7. package/dist/index.d.ts +940 -892
  8. package/dist/index.js +1135 -470
  9. package/dist/index.js.map +1 -1
  10. package/dist/index.mjs +1135 -470
  11. package/dist/index.mjs.map +1 -1
  12. package/dist/zk/index.d.mts +177 -4
  13. package/dist/zk/index.d.ts +177 -4
  14. package/dist/zk/index.js +5 -5
  15. package/dist/zk/index.js.map +1 -1
  16. package/dist/zk/index.mjs +5 -5
  17. package/dist/zk/index.mjs.map +1 -1
  18. package/dist/zk/prove-worker.mjs.map +1 -0
  19. package/dist/zk/utils.js +3 -3
  20. package/dist/zk/utils.js.map +1 -1
  21. package/dist/zk/utils.mjs +3 -3
  22. package/dist/zk/utils.mjs.map +1 -1
  23. package/docs/API_REFERENCE.md +517 -843
  24. package/docs/ARCHITECTURE.md +86 -106
  25. package/docs/BROWSER_COMPATIBILITY.md +15 -2
  26. package/docs/BUILD_VERIFICATION.md +35 -8
  27. package/docs/EIP-7951.md +1 -8
  28. package/docs/EIP_7702.md +35 -395
  29. package/docs/INTEGRATION_GUIDELINES.md +69 -818
  30. package/docs/JUNE_9_2026_AUDIT.md +207 -0
  31. package/docs/PORTABILITY.md +41 -186
  32. package/docs/POST_QUANTUM.md +61 -39
  33. package/docs/RECOVERY.md +165 -173
  34. package/docs/SECURITY.md +301 -891
  35. package/docs/ZK.md +250 -0
  36. package/package.json +32 -54
  37. package/dist/chainlist/index.js +0 -2
  38. package/dist/chainlist/index.mjs +0 -2
  39. package/dist/inspect/browser.d.mts +0 -106
  40. package/dist/inspect/browser.d.ts +0 -106
  41. package/dist/inspect/browser.js +0 -194
  42. package/dist/inspect/browser.js.map +0 -1
  43. package/dist/inspect/browser.mjs +0 -173
  44. package/dist/inspect/browser.mjs.map +0 -1
  45. package/dist/inspect/index.d.mts +0 -1
  46. package/dist/inspect/index.d.ts +0 -1
  47. package/dist/inspect/index.js +0 -196
  48. package/dist/inspect/index.js.map +0 -1
  49. package/dist/inspect/index.mjs +0 -173
  50. package/dist/inspect/index.mjs.map +0 -1
  51. package/dist/inspect/node.d.mts +0 -112
  52. package/dist/inspect/node.d.ts +0 -112
  53. package/dist/inspect/node.js +0 -287
  54. package/dist/inspect/node.js.map +0 -1
  55. package/dist/inspect/node.mjs +0 -251
  56. package/dist/inspect/node.mjs.map +0 -1
  57. package/docs/notes/IFRAME_IMPLEMENTATION_PLAN.md +0 -197
  58. package/docs/notes/JULY_13_ROADMAP.md +0 -29
  59. package/docs/notes/NOTES.md +0 -333
  60. package/docs/notes/SIWE_IMPLEMENTATION.md +0 -129
  61. package/docs/notes/SYNCING_ACROSS_DEVICES.md +0 -127
  62. package/docs/notes/ethereum-post-quantum-roadmap.md +0 -213
  63. package/docs/notes/wulong-building-finding.md +0 -109
package/dist/index.js CHANGED
@@ -1,314 +1,1028 @@
1
- "use strict";var Uh=Object.create;var ur=Object.defineProperty;var Nh=Object.getOwnPropertyDescriptor;var Lh=Object.getOwnPropertyNames;var _h=Object.getPrototypeOf,Kh=Object.prototype.hasOwnProperty;var Oh=(r,e,t)=>e in r?ur(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var p=(r,e)=>()=>(r&&(e=r(r=0)),e);var C=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),x=(r,e)=>{for(var t in e)ur(r,t,{get:e[t],enumerable:!0})},xa=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Lh(e))!Kh.call(r,s)&&s!==t&&ur(r,s,{get:()=>e[s],enumerable:!(n=Nh(e,s))||n.enumerable});return r};var z=(r,e,t)=>(t=r!=null?Uh(_h(r)):{},xa(e||!r||!r.__esModule?ur(t,"default",{value:r,enumerable:!0}):t,r)),zh=r=>xa(ur({},"__esModule",{value:!0}),r);var f=(r,e,t)=>Oh(r,typeof e!="symbol"?e+"":e,t);var $s={};x($s,{ApiError:()=>dr,AuthenticationError:()=>N,CryptoError:()=>P,PrfUnsupportedError:()=>Le,RegistrationError:()=>et,StorageError:()=>k,SyncBootstrapError:()=>ye,SyncRequiredError:()=>tt,WalletError:()=>g,WalletMissingError:()=>rt,Web3PasskeyError:()=>_});var _,N,et,g,P,k,dr,tt,rt,Wh,ye,Le,W=p(()=>{"use strict";_=class extends Error{constructor(t,n,s){super(t);this.code=n;this.originalError=s;this.name="Web3PasskeyError"}},N=class extends _{constructor(e,t){super(e,"AUTHENTICATION_ERROR",t),this.name="AuthenticationError"}},et=class extends _{constructor(e,t){super(e,"REGISTRATION_ERROR",t),this.name="RegistrationError"}},g=class extends _{constructor(e,t){super(e,"WALLET_ERROR",t),this.name="WalletError"}},P=class extends _{constructor(e,t){super(e,"CRYPTO_ERROR",t),this.name="CryptoError"}},k=class extends _{constructor(e,t){super(e,"STORAGE_ERROR",t),this.name="StorageError"}},dr=class extends _{constructor(t,n,s){super(t,"API_ERROR",s);this.statusCode=n;this.name="ApiError"}},tt=class extends _{constructor(t){super("Passkey authenticated but this device has no data for it. Sync this device or restore from a backup.","SYNC_REQUIRED");this.credentialId=t;this.name="SyncRequiredError"}},rt=class extends _{constructor(t,n){super("Passkey authenticated but no wallet was found on this device. Restore it from a backup.","WALLET_MISSING");this.credentialId=t;this.ethereumAddress=n;this.name="WalletMissingError"}},Wh={PASSKEY_BACKUP:"This device has no data for the passkey, and a passkey-encrypted backup can't set it up. Sync with a backup from exportForSync() or a password backup instead.",NO_CREDENTIAL:"This backup doesn't name its passkey, so it can't set up this device. Create a new password backup on a device where you're logged in.",CREDENTIAL_MISMATCH:"This backup belongs to a different passkey than the one selected.",PUBLIC_KEY_MISMATCH:"The passkey's signature doesn't match the public key in this backup. The backup may have been tampered with."},ye=class extends _{constructor(t,n){super(Wh[t],"SYNC_BOOTSTRAP_FAILED");this.reason=t;this.credentialId=n;this.name="SyncBootstrapError"}},Le=class extends _{constructor(t){super("This passkey's authenticator doesn't support the WebAuthn PRF extension.","PRF_UNSUPPORTED");this.credentialId=t;this.name="PrfUnsupportedError"}}});var Js={};x(Js,{arrayBufferToBase64Url:()=>ne,base64ToArrayBuffer:()=>Gs,base64UrlDecode:()=>js,base64UrlToArrayBuffer:()=>T,safeAtob:()=>nt,safeBtoa:()=>Ys});function T(r){try{let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;e+="=".repeat(t);let n=atob(e),s=new Uint8Array(n.length);for(let i=0;i<n.length;i++)s[i]=n.charCodeAt(i);return s.buffer}catch(e){throw new Error(`Failed to decode base64url string: ${e instanceof Error?e.message:"Invalid format"}`)}}function ne(r){let e=r instanceof Uint8Array?r:new Uint8Array(r),t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Gs(r){try{let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t.buffer}catch(e){throw new Error(`Failed to decode base64 string: ${e instanceof Error?e.message:"Invalid format"}`)}}function nt(r){try{let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;return e+="=".repeat(t),atob(e)}catch(e){throw new Error(`Failed to decode base64 string: ${e instanceof Error?e.message:"Invalid format"}`)}}function Ys(r){try{let e=new TextEncoder().encode(r),t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}catch(e){throw new Error(`Failed to encode string: ${e instanceof Error?e.message:"Invalid input"}`)}}function js(r){return T(r)}var ce=p(()=>{"use strict"});var fr={};x(fr,{PRF_INPUT:()=>hr,decryptData:()=>Q,deriveEncryptionKey:()=>Hh,deriveEncryptionKeyFromWebAuthn:()=>le,derivePrfSessionKey:()=>kt,encryptData:()=>J,exportSessionKey:()=>Qs,generateChallenge:()=>Ee,hashCredentialId:()=>Et,hashPublicKey:()=>Zs,importSessionKey:()=>Xs});async function kt(r,e=!1){try{let t=(r instanceof ArrayBuffer,r.byteLength);if(t!==32)throw new Error(`PRF output must be 32 bytes, got ${t}`);let n=await crypto.subtle.importKey("raw",r,"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:new Uint8Array(32),info:$h},n,{name:"AES-GCM",length:256},e,["encrypt","decrypt"])}catch(t){throw new P("Failed to derive session key from PRF output",t)}}async function Qs(r){try{return ne(await crypto.subtle.exportKey("raw",r))}catch(e){throw new P("Failed to export session key",e)}}async function Xs(r){try{return await crypto.subtle.importKey("raw",T(r),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}catch(e){throw new P("Failed to import session key",e)}}async function le(r,e){try{let t=e?`w3pk-v4:${r}:${e}`:`w3pk-v4:${r}`,n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)),s=await crypto.subtle.importKey("raw",n,{name:"PBKDF2"},!1,["deriveKey"]),i=await crypto.subtle.digest("SHA-256",new TextEncoder().encode("w3pk-salt-v4"));return crypto.subtle.deriveKey({name:"PBKDF2",salt:new Uint8Array(i),iterations:21e4,hash:"SHA-256"},s,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}catch(t){throw new P("Failed to derive encryption key from WebAuthn",t)}}async function Hh(r,e){try{let t=e?`w3pk-v2:${r}:${e}`:`w3pk-v2:${r}`,n=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)),s=await crypto.subtle.importKey("raw",n,{name:"PBKDF2"},!1,["deriveKey"]),i=await crypto.subtle.digest("SHA-256",new TextEncoder().encode("w3pk-salt-v2"));return crypto.subtle.deriveKey({name:"PBKDF2",salt:new Uint8Array(i),iterations:21e4,hash:"SHA-256"},s,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}catch(t){throw new P("Failed to derive encryption key",t)}}function Ee(){let r=new Uint8Array(32);return crypto.getRandomValues(r),ne(r)}async function J(r,e){try{let t=crypto.getRandomValues(new Uint8Array(12)),n=new TextEncoder().encode(r),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:t},e,n),i=new Uint8Array(t.length+s.byteLength);i.set(t),i.set(new Uint8Array(s),t.length);let o="";for(let a=0;a<i.length;a++)o+=String.fromCharCode(i[a]);return btoa(o)}catch(t){throw new P("Failed to encrypt data",t)}}async function Q(r,e){try{if(!r||r.length<16)throw new Error("Invalid encrypted data: too small");let t=nt(r),n=new Uint8Array(t.length);for(let a=0;a<t.length;a++)n[a]=t.charCodeAt(a);if(n.length<12)throw new Error("Invalid encrypted data: missing IV");let s=n.slice(0,12),i=n.slice(12);if(i.length===0)throw new Error("Invalid encrypted data: no content");let o=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},e,i);return new TextDecoder().decode(o)}catch(t){throw new P(`Data decryption failed: ${t instanceof Error?t.message:"Unknown error"}`,t)}}async function Et(r){try{let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`w3pk-cred-id:${r}`));return ne(e)}catch(e){throw new P("Failed to hash credential ID",e)}}async function Zs(r){try{let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r));return ne(e)}catch(e){throw new P("Failed to hash public key",e)}}var hr,$h,se=p(()=>{"use strict";W();ce();hr=new TextEncoder().encode("w3pk-prf-input-v1"),$h=new TextEncoder().encode("w3pk-prf-session-key-v1")});var mn={};x(mn,{CredentialStorage:()=>D});async function Ea(r){let e=new TextEncoder().encode(`w3pk-metadata-v1:${r}`),t=await crypto.subtle.digest("SHA-256",e),n=await crypto.subtle.importKey("raw",t,{name:"PBKDF2"},!1,["deriveKey"]);return await crypto.subtle.deriveKey({name:"PBKDF2",salt:new TextEncoder().encode("w3pk-metadata-salt-v1"),iterations:1e5,hash:"SHA-256"},n,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}var fn,pn,D,_e=p(()=>{"use strict";W();se();fn="w3pk_credential_",pn="w3pk_credential_index";D=class{constructor(e){if(e)this.storage=e;else if(typeof window<"u"&&window.localStorage)this.storage=window.localStorage;else throw new k("localStorage is not available")}async saveCredential(e){try{let t=await Ea(e.id),n=await Et(e.id),s={id:n,encryptedUsername:await J(e.username,t),encryptedAddress:await J(e.ethereumAddress,t),publicKey:e.publicKey,publicKeyFingerprint:await Zs(e.publicKey),createdAt:e.createdAt,lastUsed:e.lastUsed},i=`${fn}${n}`;this.storage.setItem(i,JSON.stringify(s)),await this.addToIndex(e.id)}catch(t){throw new k("Failed to save credential",t)}}async getCredentialById(e){try{let t=await Et(e),n=`${fn}${t}`,s=this.storage.getItem(n);if(!s)return null;let i=JSON.parse(s),o=await Ea(e);return{id:e,publicKey:i.publicKey,username:await Q(i.encryptedUsername,o),ethereumAddress:await Q(i.encryptedAddress,o),createdAt:i.createdAt,lastUsed:i.lastUsed}}catch(t){throw new k("Failed to retrieve credential",t)}}async getCredentialByUsername(e){try{return(await this.getAllCredentials()).find(n=>n.username===e)||null}catch(t){throw new k("Failed to retrieve credential",t)}}async getCredentialByAddress(e){try{return(await this.getAllCredentials()).find(n=>n.ethereumAddress.toLowerCase()===e.toLowerCase())||null}catch(t){throw new k("Failed to retrieve credential",t)}}async getAllCredentials(){try{let e=await this.getIndex();return(await Promise.all(e.map(async n=>await this.getCredentialById(n)))).filter(n=>n!==null)}catch(e){throw new k("Failed to retrieve credentials",e)}}async userExists(e){return await this.getCredentialByUsername(e)!==null}async updateLastUsed(e){try{let t=await this.getCredentialById(e);t&&(t.lastUsed=new Date().toISOString(),await this.saveCredential(t))}catch(t){throw new k("Failed to update timestamp",t)}}async updateSignatureCounter(e,t){try{let n=await this.getCredentialById(e);n&&(n.signCount=t,n.lastUsed=new Date().toISOString(),await this.saveCredential(n))}catch(n){throw new k("Failed to update signature counter",n)}}async updateCredentialAddress(e,t){try{let n=await this.getCredentialById(e);n&&(n.ethereumAddress=t,n.lastUsed=new Date().toISOString(),await this.saveCredential(n))}catch(n){throw new k("Failed to update credential address",n)}}async deleteCredential(e){try{let t=await Et(e),n=`${fn}${t}`;this.storage.removeItem(n),await this.removeFromIndex(e)}catch(t){throw new k("Failed to delete credential",t)}}async clearAll(){try{let e=await this.getIndex();(await Promise.all(e.map(async n=>await Et(n)))).forEach(n=>{let s=`${fn}${n}`;this.storage.removeItem(s)}),this.storage.removeItem(pn)}catch(e){throw new k("Failed to clear credentials",e)}}async getIndex(){try{let e=this.storage.getItem(pn);return e?JSON.parse(e):[]}catch{return[]}}async addToIndex(e){let t=await this.getIndex();t.includes(e)||(t.push(e),this.storage.setItem(pn,JSON.stringify(t)))}async removeFromIndex(e){let n=(await this.getIndex()).filter(s=>s!==e);this.storage.setItem(pn,JSON.stringify(n))}}});var Ia={};x(Ia,{login:()=>pr,verifyAssertionSignature:()=>yn});async function pr(){try{let r=new D,e=Ee(),t=[];try{let l=await r.getAllCredentials();l.length>0&&(t=l.map(u=>({id:u.id,type:"public-key",transports:["internal","hybrid","usb","nfc","ble"]})))}catch{}let s={challenge:T(e),rpId:window.location.hostname,userVerification:"required",timeout:6e4,extensions:{prf:{eval:{first:hr}}}};t.length>0&&(s.allowCredentials=t.map(l=>({id:T(l.id),type:l.type,transports:l.transports})));let i;try{let l=await navigator.credentials.get({publicKey:s});if(!l)throw new Error("Authentication failed - no credential returned");i=l}catch(l){throw l?.name==="NotAllowedError"||l?.message?.toLowerCase().includes("no credentials available")||l?.message?.toLowerCase().includes("no access key")?(await r.getAllCredentials()).length>0?new N("Your passkey is not available on this device. You may need to restore your wallet from a backup, or login on the device where you registered."):new N("No passkey found. Please register first or restore from a backup."):l}let o=await r.getCredentialById(i.id);if(!o)throw new tt(i.id);if(!await Yh(i,o,r))throw new Error("Signature verification failed");let c=i.getClientExtensionResults?.().prf?.results?.first;return{verified:!0,user:{username:o.username,ethereumAddress:o.ethereumAddress,credentialId:o.id},signature:i.response.signature,prfOutput:c}}catch(r){throw r instanceof _?r:new N(r instanceof Error?r.message:"Authentication failed",r)}}async function Yh(r,e,t){try{if(!await yn(r,e.publicKey))return!1;let n=new DataView(r.response.authenticatorData).getUint32(33,!1);if(n>0||e.signCount&&e.signCount>0){let s=e.signCount||0;if(n<=s)return console.error(`Authenticator cloning detected! Counter did not increase: stored=${s}, received=${n}`),!1}return await t.updateSignatureCounter(e.id,n),!0}catch(n){return console.error("Signature verification error:",n),!1}}async function yn(r,e){try{let t=r.response.authenticatorData,n=new Uint8Array(t),s=n.slice(0,32),i=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(window.location.hostname)));if(!jh(s,i))return console.error("RP ID hash mismatch - possible phishing attack"),!1;let o=await crypto.subtle.importKey("spki",T(e),{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),a=await crypto.subtle.digest("SHA-256",r.response.clientDataJSON),c=new Uint8Array(t.byteLength+a.byteLength);c.set(n,0),c.set(new Uint8Array(a),t.byteLength);let l=Jh(new Uint8Array(r.response.signature));return await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},o,l,c)}catch(t){return console.error("Signature verification error:",t),!1}}function jh(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}function Jh(r){let e=2;e++;let t=r[e++];t>32&&(e++,t--);let n=r.slice(e,e+t);e+=t,e++;let s=r[e++];s>32&&(e++,s--);let i=r.slice(e,e+s),o=new Uint8Array(64);return o.set(n,32-n.length),o.set(i,64-i.length),o.buffer}var ei=p(()=>{"use strict";W();_e();ce();se()});var Ct={};x(Ct,{createWalletFromMnemonic:()=>ti,deriveWalletFromMnemonic:()=>gr,generateBIP39Wallet:()=>yr});function yr(){try{let r=mr.ethers.Wallet.createRandom().mnemonic;if(!r)throw new Error("Failed to generate mnemonic");let e=r.phrase;return{address:mr.ethers.HDNodeWallet.fromPhrase(e,void 0,"m/44'/60'/0'/0/0").address,mnemonic:e}}catch(r){throw new g("Wallet generation failed",r)}}function ti(r){try{if(!r||r.trim().split(/\s+/).length<12)throw new Error("Invalid mnemonic: must be at least 12 words");return mr.ethers.HDNodeWallet.fromPhrase(r.trim(),void 0,"m/44'/60'/0'/0/0")}catch(e){throw new g(`Wallet creation failed: ${e instanceof Error?e.message:"Invalid mnemonic"}`,e)}}function gr(r,e=0){try{if(!r||r.trim().split(/\s+/).length<12)throw new Error("Invalid mnemonic: must be at least 12 words");if(e<0||!Number.isInteger(e))throw new Error("Index must be a non-negative integer");let t=`m/44'/60'/0'/0/${e}`,n=mr.ethers.HDNodeWallet.fromPhrase(r.trim(),void 0,t);return{address:n.address,privateKey:n.privateKey}}catch(t){throw new g(`HD wallet derivation failed: ${t instanceof Error?t.message:"Unknown error"}`,t)}}var mr,Te=p(()=>{"use strict";mr=require("ethers");W()});var Sn={};x(Sn,{DEFAULT_MODE:()=>ge,DEFAULT_TAG:()=>X,deriveAddressFromP256PublicKey:()=>ri,deriveIndexFromOriginModeAndTag:()=>bn,getCurrentOrigin:()=>ue,getOriginSpecificAddress:()=>we,normalizeOrigin:()=>st});function st(r){try{let e=new URL(r),t=`${e.protocol}//${e.hostname.toLowerCase()}`,n=e.port;return n&&!(e.protocol==="https:"&&n==="443"||e.protocol==="http:"&&n==="80")&&(t+=`:${n}`),t}catch(e){throw new g(`Invalid origin URL: ${r}`,e)}}async function bn(r,e=ge,t=X){try{let s=`${st(r)}:${e}:${t.toUpperCase()}`,o=new TextEncoder().encode(s),a=await crypto.subtle.digest("SHA-256",o);return new DataView(a).getUint32(0,!1)%Qh}catch(n){throw new g(`Failed to derive index from origin "${r}", mode "${e}", and tag "${t}"`,n)}}async function we(r,e,t,n){try{let s=t||ge,i=(n||X).toUpperCase(),o=st(e),a=await bn(o,s,i),{address:c,privateKey:l}=gr(r,a),u={address:c,index:a,origin:o,mode:s,tag:i};return s==="YOLO"&&(u.privateKey=l),u}catch(s){throw new g(`Failed to derive origin-specific address for "${e}" with mode "${t||ge}" and tag "${n||X}"`,s)}}function ue(){if(typeof window>"u"||!window.location)throw new g("getCurrentOrigin() only works in browser environments");return window.location.origin}async function ri(r){try{let e=T(r),t=await crypto.subtle.importKey("spki",e,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),n=await crypto.subtle.exportKey("jwk",t);if(!n.x||!n.y)throw new Error("Invalid P-256 public key: missing x or y coordinates");let s=T(n.x),i=T(n.y),o=new Uint8Array(64);return o.set(new Uint8Array(s),0),o.set(new Uint8Array(i),32),"0x"+(0,Ba.keccak256)(o).slice(-40)}catch(e){throw new g("Failed to derive address from P-256 public key",e)}}var Ba,ge,X,Qh,Pt=p(()=>{"use strict";Te();W();Ba=require("ethers");ce();ge="STANDARD",X="MAIN",Qh=2147483647});var oi={};x(oi,{derivePrfSecret:()=>ii,evaluatePrf:()=>Na});async function Na(r,e){let t;try{let i={challenge:T(Ee()),rpId:window.location.hostname,userVerification:"required",timeout:6e4,extensions:{prf:{eval:{first:r}}}};e&&(i.allowCredentials=[{id:T(e),type:"public-key",transports:["internal","hybrid","usb","nfc","ble"]}]);let o=await navigator.credentials.get({publicKey:i});if(!o)throw new N("Authentication failed - no credential returned");t=o}catch(i){throw i instanceof N?i:i?.name==="NotAllowedError"?new N("Authentication was cancelled or the passkey is not available on this device.",i):new N(`Passkey authentication failed: ${i instanceof Error?i.message:"Unknown error"}`,i)}let n=t.getClientExtensionResults?.().prf?.results?.first;if(!n)throw new Le(t.id);let s=ArrayBuffer.isView(n)?new Uint8Array(n.buffer,n.byteOffset,n.byteLength).slice().buffer:n.slice(0);if(s.byteLength!==32)throw new Le(t.id);return{output:s,credentialId:t.id,assertion:t}}function tf(r,e){if(typeof e!="string"||e.length===0||e.includes(":"))throw new P("PRF secret tag must be a non-empty string without ':'");return new TextEncoder().encode(`${Zh}:${r}:${e}`)}async function ii(r,e,t){let n=tf(r,e),s=await crypto.subtle.digest("SHA-256",n),i=await Na(s,t);try{let o=await crypto.subtle.importKey("raw",i.output,"HKDF",!1,["deriveBits"]),a=await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:ef,info:n},o,256);return{secret:new Uint8Array(a),credentialId:i.credentialId}}catch(o){throw new P("Failed to derive secret from PRF output",o)}finally{new Uint8Array(i.output).fill(0)}}var Zh,ef,En=p(()=>{"use strict";W();ce();se();Zh="w3pk-prf-v1",ef=new TextEncoder().encode("w3pk-prf-secret-v1")});function rf(r,e=0){return/iPhone|iPad|iPod/.test(r)||/Macintosh/.test(r)&&e>1?!0:/AppleWebKit/.test(r)&&!/Chrome|Chromium|Android/.test(r)}function nf(){return navigator.standalone===!0?!0:typeof globalThis.matchMedia=="function"&&globalThis.matchMedia("(display-mode: standalone)").matches}async function Cn(){if(typeof navigator>"u"||!rf(navigator.userAgent??"",navigator.maxTouchPoints??0)||nf())return!1;try{return!await navigator.storage?.persisted?.()}catch{return!0}}var ai=p(()=>{"use strict"});var li={};x(li,{encodeEIP7702AuthorizationMessage:()=>Ar,hashEIP7702AuthorizationMessage:()=>xr,verifyEIP7702Authorization:()=>Bn});function Ar(r,e,t){let n=[r===0n?"0x":(0,ie.toBeHex)(r),e.toLowerCase(),t===0n?"0x":(0,ie.toBeHex)(t)],s=(0,ie.encodeRlp)(n);return(0,ie.concat)(["0x05",s])}function xr(r,e,t){let n=Ar(r,e,t);return(0,ie.keccak256)(n)}function Bn(r,e,t,n,s){try{let i=xr(r,e,t),o;return typeof n=="string"?o=ie.Signature.from(n):o=n,(0,ie.recoverAddress)(i,o).toLowerCase()===s.toLowerCase()}catch{return!1}}var ie,Tn=p(()=>{"use strict";ie=require("ethers")});var za={};x(za,{detectWalletProvider:()=>Fn,getDefaultProvider:()=>Dn,requestExternalWalletAuthorization:()=>Rn,supportsEIP7702Authorization:()=>Mn});async function Rn(r,e){if(!r)throw new Error("No external wallet provider found. Please install MetaMask or similar wallet.");let t=BigInt(e.chainId||1),n=e.nonce||0n,s=e.accountIndex||0,i=await r.request({method:"eth_requestAccounts"});if(!i||i.length===0)throw new Error("No accounts found in external wallet");if(s>=i.length)throw new Error(`Account index ${s} out of range. Wallet has ${i.length} accounts.`);let o=i[s],{hashEIP7702AuthorizationMessage:a,verifyEIP7702Authorization:c}=await Promise.resolve().then(()=>(Tn(),li)),{Signature:l}=await import("ethers"),u=a(t,e.delegateToAddress,n),d;try{d=await r.request({method:"eth_sign",params:[o,u]})}catch(w){try{d=await r.request({method:"personal_sign",params:[u,o]})}catch(b){throw new Error(`Failed to request signature from wallet. eth_sign error: ${w.message}, personal_sign error: ${b.message}`)}}let h=l.from(d),m={chainId:t,address:e.delegateToAddress.toLowerCase(),nonce:n,yParity:h.yParity,r:h.r,s:h.s};if(!c(t,e.delegateToAddress,n,m,o))throw new Error(`Signature verification failed. Expected signer: ${o}, but signature does not match. This may indicate a wallet implementation issue.`);return m}function Dn(){if(typeof window>"u")return null;let r=window;return r.ethereum?r.ethereum:r.web3?.currentProvider?r.web3.currentProvider:null}function Fn(r){let e=r;return e.isMetaMask?"MetaMask":e.isRabby?"Rabby":e.isCoinbaseWallet?"Coinbase Wallet":e.isBraveWallet?"Brave Wallet":e.isTokenPocket?"TokenPocket":e.isTrust?"Trust Wallet":"Unknown Wallet"}async function Mn(r){try{let e=await r.request({method:"eth_accounts"});return Array.isArray(e)}catch{return!1}}var ui=p(()=>{"use strict"});var Ha={};x(Ha,{BackupStorage:()=>it});var $a,it,Un=p(()=>{"use strict";$a="w3pk_backups",it=class{constructor(e){this.customStorage=e}get storage(){return this.customStorage?this.customStorage:typeof window<"u"&&window.localStorage?window.localStorage:null}async init(){}async storeBackupMetadata(e){let t=this.readAll().filter(n=>n.id!==e.id);t.push(e),this.writeAll(t)}async getBackupsByAddress(e){return this.readAll().filter(t=>t.ethereumAddress===e)}async getBackupById(e){return this.readAll().find(t=>t.id===e)??null}async deleteBackup(e){this.writeAll(this.readAll().filter(t=>t.id!==e))}async getBackupCountByMethod(e){return this.readAll().filter(t=>t.method===e).length}readAll(){let e=this.storage?.getItem($a);return e?JSON.parse(e):[]}writeAll(e){this.storage?.setItem($a,JSON.stringify(e))}}});var hi={};x(hi,{decryptWithPassword:()=>kr,deriveAddressChecksum:()=>V,deriveKeyFromPassword:()=>Nn,encryptWithPassword:()=>ot,getDeviceFingerprint:()=>Ce,validatePasswordStrength:()=>qa});async function Nn(r,e,t=31e4){let s=new TextEncoder().encode(r),i=await crypto.subtle.importKey("raw",s,"PBKDF2",!1,["deriveBits","deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:e,iterations:t,hash:"SHA-256"},i,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function ot(r,e,t){let s=await Nn(e,t,31e4),o=new TextEncoder().encode(r),a=crypto.getRandomValues(new Uint8Array(12)),c=await crypto.subtle.encrypt({name:"AES-GCM",iv:a},s,o);return{encrypted:vr(c),iv:vr(a),salt:vr(t),iterations:31e4}}async function kr(r,e,t,n,s=31e4){let i=di(t),o=await Nn(e,i,s),a=di(n),c=di(r),l=await crypto.subtle.decrypt({name:"AES-GCM",iv:a},o,c);return new TextDecoder().decode(l)}async function Ce(){let e=[navigator.userAgent,navigator.language,new Date().getTimezoneOffset().toString(),screen.width+"x"+screen.height,screen.colorDepth.toString()].join("|"),n=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-256",n);return vr(s)}async function V(r){let t=new TextEncoder().encode(r.toLowerCase()),n=await crypto.subtle.digest("SHA-256",t);return vr(n).substring(0,16)}function qa(r){let e=[],t=0;return r.length<12?e.push("Password must be at least 12 characters"):t+=25,/[A-Z]/.test(r)?t+=15:e.push("Add at least one uppercase letter"),/[a-z]/.test(r)?t+=15:e.push("Add at least one lowercase letter"),/[0-9]/.test(r)?t+=15:e.push("Add at least one number"),/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(r)?t+=15:e.push("Add at least one special character"),r.length>=16&&(t+=10),r.length>=20&&(t+=5),["password","12345678","qwerty","abc123","password123","admin","letmein"].some(s=>r.toLowerCase().includes(s))&&(e.push("Password is too common"),t=Math.min(t,25)),{valid:t>=50&&e.length===0,score:Math.min(t,100),feedback:e}}function vr(r){let e=r instanceof Uint8Array?r:new Uint8Array(r),t="";for(let n=0;n<e.byteLength;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function di(r){let e=nt(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}var Ke=p(()=>{"use strict";ce()});var Ga=C((Jg,Va)=>{"use strict";Va.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var Oe=C(at=>{"use strict";var fi,uf=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];at.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};at.getSymbolTotalCodewords=function(e){return uf[e]};at.getBCHDigit=function(r){let e=0;for(;r!==0;)e++,r>>>=1;return e};at.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');fi=e};at.isKanjiModeEnabled=function(){return typeof fi<"u"};at.toSJIS=function(e){return fi(e)}});var Ln=C(de=>{"use strict";de.L={bit:1};de.M={bit:0};de.Q={bit:3};de.H={bit:2};function df(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return de.L;case"m":case"medium":return de.M;case"q":case"quartile":return de.Q;case"h":case"high":return de.H;default:throw new Error("Unknown EC Level: "+r)}}de.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};de.from=function(e,t){if(de.isValid(e))return e;try{return df(e)}catch{return t}}});var Ja=C((Zg,ja)=>{"use strict";function Ya(){this.buffer=[],this.length=0}Ya.prototype={get:function(r){let e=Math.floor(r/8);return(this.buffer[e]>>>7-r%8&1)===1},put:function(r,e){for(let t=0;t<e;t++)this.putBit((r>>>e-t-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(r){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),r&&(this.buffer[e]|=128>>>this.length%8),this.length++}};ja.exports=Ya});var Xa=C((ew,Qa)=>{"use strict";function Er(r){if(!r||r<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=r,this.data=new Uint8Array(r*r),this.reservedBit=new Uint8Array(r*r)}Er.prototype.set=function(r,e,t,n){let s=r*this.size+e;this.data[s]=t,n&&(this.reservedBit[s]=!0)};Er.prototype.get=function(r,e){return this.data[r*this.size+e]};Er.prototype.xor=function(r,e,t){this.data[r*this.size+e]^=t};Er.prototype.isReserved=function(r,e){return this.reservedBit[r*this.size+e]};Qa.exports=Er});var Za=C(_n=>{"use strict";var hf=Oe().getSymbolSize;_n.getRowColCoords=function(e){if(e===1)return[];let t=Math.floor(e/7)+2,n=hf(e),s=n===145?26:Math.ceil((n-13)/(2*t-2))*2,i=[n-7];for(let o=1;o<t-1;o++)i[o]=i[o-1]-s;return i.push(6),i.reverse()};_n.getPositions=function(e){let t=[],n=_n.getRowColCoords(e),s=n.length;for(let i=0;i<s;i++)for(let o=0;o<s;o++)i===0&&o===0||i===0&&o===s-1||i===s-1&&o===0||t.push([n[i],n[o]]);return t}});var rc=C(tc=>{"use strict";var ff=Oe().getSymbolSize,ec=7;tc.getPositions=function(e){let t=ff(e);return[[0,0],[t-ec,0],[0,t-ec]]}});var nc=C(M=>{"use strict";M.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var ct={N1:3,N2:3,N3:40,N4:10};M.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};M.from=function(e){return M.isValid(e)?parseInt(e,10):void 0};M.getPenaltyN1=function(e){let t=e.size,n=0,s=0,i=0,o=null,a=null;for(let c=0;c<t;c++){s=i=0,o=a=null;for(let l=0;l<t;l++){let u=e.get(c,l);u===o?s++:(s>=5&&(n+=ct.N1+(s-5)),o=u,s=1),u=e.get(l,c),u===a?i++:(i>=5&&(n+=ct.N1+(i-5)),a=u,i=1)}s>=5&&(n+=ct.N1+(s-5)),i>=5&&(n+=ct.N1+(i-5))}return n};M.getPenaltyN2=function(e){let t=e.size,n=0;for(let s=0;s<t-1;s++)for(let i=0;i<t-1;i++){let o=e.get(s,i)+e.get(s,i+1)+e.get(s+1,i)+e.get(s+1,i+1);(o===4||o===0)&&n++}return n*ct.N2};M.getPenaltyN3=function(e){let t=e.size,n=0,s=0,i=0;for(let o=0;o<t;o++){s=i=0;for(let a=0;a<t;a++)s=s<<1&2047|e.get(o,a),a>=10&&(s===1488||s===93)&&n++,i=i<<1&2047|e.get(a,o),a>=10&&(i===1488||i===93)&&n++}return n*ct.N3};M.getPenaltyN4=function(e){let t=0,n=e.data.length;for(let i=0;i<n;i++)t+=e.data[i];return Math.abs(Math.ceil(t*100/n/5)-10)*ct.N4};function pf(r,e,t){switch(r){case M.Patterns.PATTERN000:return(e+t)%2===0;case M.Patterns.PATTERN001:return e%2===0;case M.Patterns.PATTERN010:return t%3===0;case M.Patterns.PATTERN011:return(e+t)%3===0;case M.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(t/3))%2===0;case M.Patterns.PATTERN101:return e*t%2+e*t%3===0;case M.Patterns.PATTERN110:return(e*t%2+e*t%3)%2===0;case M.Patterns.PATTERN111:return(e*t%3+(e+t)%2)%2===0;default:throw new Error("bad maskPattern:"+r)}}M.applyMask=function(e,t){let n=t.size;for(let s=0;s<n;s++)for(let i=0;i<n;i++)t.isReserved(i,s)||t.xor(i,s,pf(e,i,s))};M.getBestMask=function(e,t){let n=Object.keys(M.Patterns).length,s=0,i=1/0;for(let o=0;o<n;o++){t(o),M.applyMask(o,e);let a=M.getPenaltyN1(e)+M.getPenaltyN2(e)+M.getPenaltyN3(e)+M.getPenaltyN4(e);M.applyMask(o,e),a<i&&(i=a,s=o)}return s}});var mi=C(pi=>{"use strict";var ze=Ln(),Kn=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],On=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];pi.getBlocksCount=function(e,t){switch(t){case ze.L:return Kn[(e-1)*4+0];case ze.M:return Kn[(e-1)*4+1];case ze.Q:return Kn[(e-1)*4+2];case ze.H:return Kn[(e-1)*4+3];default:return}};pi.getTotalCodewordsCount=function(e,t){switch(t){case ze.L:return On[(e-1)*4+0];case ze.M:return On[(e-1)*4+1];case ze.Q:return On[(e-1)*4+2];case ze.H:return On[(e-1)*4+3];default:return}}});var sc=C(Wn=>{"use strict";var Cr=new Uint8Array(512),zn=new Uint8Array(256);(function(){let e=1;for(let t=0;t<255;t++)Cr[t]=e,zn[e]=t,e<<=1,e&256&&(e^=285);for(let t=255;t<512;t++)Cr[t]=Cr[t-255]})();Wn.log=function(e){if(e<1)throw new Error("log("+e+")");return zn[e]};Wn.exp=function(e){return Cr[e]};Wn.mul=function(e,t){return e===0||t===0?0:Cr[zn[e]+zn[t]]}});var ic=C(Pr=>{"use strict";var yi=sc();Pr.mul=function(e,t){let n=new Uint8Array(e.length+t.length-1);for(let s=0;s<e.length;s++)for(let i=0;i<t.length;i++)n[s+i]^=yi.mul(e[s],t[i]);return n};Pr.mod=function(e,t){let n=new Uint8Array(e);for(;n.length-t.length>=0;){let s=n[0];for(let o=0;o<t.length;o++)n[o]^=yi.mul(t[o],s);let i=0;for(;i<n.length&&n[i]===0;)i++;n=n.slice(i)}return n};Pr.generateECPolynomial=function(e){let t=new Uint8Array([1]);for(let n=0;n<e;n++)t=Pr.mul(t,new Uint8Array([1,yi.exp(n)]));return t}});var cc=C((aw,ac)=>{"use strict";var oc=ic();function gi(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}gi.prototype.initialize=function(e){this.degree=e,this.genPoly=oc.generateECPolynomial(this.degree)};gi.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let t=new Uint8Array(e.length+this.degree);t.set(e);let n=oc.mod(t,this.genPoly),s=this.degree-n.length;if(s>0){let i=new Uint8Array(this.degree);return i.set(n,s),i}return n};ac.exports=gi});var wi=C(lc=>{"use strict";lc.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var bi=C(Re=>{"use strict";var uc="[0-9]+",mf="[A-Z $%*+\\-./:]+",Ir="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";Ir=Ir.replace(/u/g,"\\u");var yf="(?:(?![A-Z0-9 $%*+\\-./:]|"+Ir+`)(?:.|[\r
2
- ]))+`;Re.KANJI=new RegExp(Ir,"g");Re.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");Re.BYTE=new RegExp(yf,"g");Re.NUMERIC=new RegExp(uc,"g");Re.ALPHANUMERIC=new RegExp(mf,"g");var gf=new RegExp("^"+Ir+"$"),wf=new RegExp("^"+uc+"$"),bf=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");Re.testKanji=function(e){return gf.test(e)};Re.testNumeric=function(e){return wf.test(e)};Re.testAlphanumeric=function(e){return bf.test(e)}});var We=C(O=>{"use strict";var Sf=wi(),Si=bi();O.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};O.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};O.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};O.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};O.MIXED={bit:-1};O.getCharCountIndicator=function(e,t){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Sf.isValid(t))throw new Error("Invalid version: "+t);return t>=1&&t<10?e.ccBits[0]:t<27?e.ccBits[1]:e.ccBits[2]};O.getBestModeForData=function(e){return Si.testNumeric(e)?O.NUMERIC:Si.testAlphanumeric(e)?O.ALPHANUMERIC:Si.testKanji(e)?O.KANJI:O.BYTE};O.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};O.isValid=function(e){return e&&e.bit&&e.ccBits};function Af(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"numeric":return O.NUMERIC;case"alphanumeric":return O.ALPHANUMERIC;case"kanji":return O.KANJI;case"byte":return O.BYTE;default:throw new Error("Unknown mode: "+r)}}O.from=function(e,t){if(O.isValid(e))return e;try{return Af(e)}catch{return t}}});var mc=C(lt=>{"use strict";var $n=Oe(),xf=mi(),dc=Ln(),$e=We(),Ai=wi(),fc=7973,hc=$n.getBCHDigit(fc);function vf(r,e,t){for(let n=1;n<=40;n++)if(e<=lt.getCapacity(n,t,r))return n}function pc(r,e){return $e.getCharCountIndicator(r,e)+4}function kf(r,e){let t=0;return r.forEach(function(n){let s=pc(n.mode,e);t+=s+n.getBitsLength()}),t}function Ef(r,e){for(let t=1;t<=40;t++)if(kf(r,t)<=lt.getCapacity(t,e,$e.MIXED))return t}lt.from=function(e,t){return Ai.isValid(e)?parseInt(e,10):t};lt.getCapacity=function(e,t,n){if(!Ai.isValid(e))throw new Error("Invalid QR Code version");typeof n>"u"&&(n=$e.BYTE);let s=$n.getSymbolTotalCodewords(e),i=xf.getTotalCodewordsCount(e,t),o=(s-i)*8;if(n===$e.MIXED)return o;let a=o-pc(n,e);switch(n){case $e.NUMERIC:return Math.floor(a/10*3);case $e.ALPHANUMERIC:return Math.floor(a/11*2);case $e.KANJI:return Math.floor(a/13);case $e.BYTE:default:return Math.floor(a/8)}};lt.getBestVersionForData=function(e,t){let n,s=dc.from(t,dc.M);if(Array.isArray(e)){if(e.length>1)return Ef(e,s);if(e.length===0)return 1;n=e[0]}else n=e;return vf(n.mode,n.getLength(),s)};lt.getEncodedBits=function(e){if(!Ai.isValid(e)||e<7)throw new Error("Invalid QR Code version");let t=e<<12;for(;$n.getBCHDigit(t)-hc>=0;)t^=fc<<$n.getBCHDigit(t)-hc;return e<<12|t}});var bc=C(wc=>{"use strict";var xi=Oe(),gc=1335,Cf=21522,yc=xi.getBCHDigit(gc);wc.getEncodedBits=function(e,t){let n=e.bit<<3|t,s=n<<10;for(;xi.getBCHDigit(s)-yc>=0;)s^=gc<<xi.getBCHDigit(s)-yc;return(n<<10|s)^Cf}});var Ac=C((fw,Sc)=>{"use strict";var Pf=We();function Tt(r){this.mode=Pf.NUMERIC,this.data=r.toString()}Tt.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};Tt.prototype.getLength=function(){return this.data.length};Tt.prototype.getBitsLength=function(){return Tt.getBitsLength(this.data.length)};Tt.prototype.write=function(e){let t,n,s;for(t=0;t+3<=this.data.length;t+=3)n=this.data.substr(t,3),s=parseInt(n,10),e.put(s,10);let i=this.data.length-t;i>0&&(n=this.data.substr(t),s=parseInt(n,10),e.put(s,i*3+1))};Sc.exports=Tt});var vc=C((pw,xc)=>{"use strict";var If=We(),vi=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function Rt(r){this.mode=If.ALPHANUMERIC,this.data=r}Rt.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};Rt.prototype.getLength=function(){return this.data.length};Rt.prototype.getBitsLength=function(){return Rt.getBitsLength(this.data.length)};Rt.prototype.write=function(e){let t;for(t=0;t+2<=this.data.length;t+=2){let n=vi.indexOf(this.data[t])*45;n+=vi.indexOf(this.data[t+1]),e.put(n,11)}this.data.length%2&&e.put(vi.indexOf(this.data[t]),6)};xc.exports=Rt});var Ec=C((mw,kc)=>{"use strict";var Bf=We();function Dt(r){this.mode=Bf.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}Dt.getBitsLength=function(e){return e*8};Dt.prototype.getLength=function(){return this.data.length};Dt.prototype.getBitsLength=function(){return Dt.getBitsLength(this.data.length)};Dt.prototype.write=function(r){for(let e=0,t=this.data.length;e<t;e++)r.put(this.data[e],8)};kc.exports=Dt});var Pc=C((yw,Cc)=>{"use strict";var Tf=We(),Rf=Oe();function Ft(r){this.mode=Tf.KANJI,this.data=r}Ft.getBitsLength=function(e){return e*13};Ft.prototype.getLength=function(){return this.data.length};Ft.prototype.getBitsLength=function(){return Ft.getBitsLength(this.data.length)};Ft.prototype.write=function(r){let e;for(e=0;e<this.data.length;e++){let t=Rf.toSJIS(this.data[e]);if(t>=33088&&t<=40956)t-=33088;else if(t>=57408&&t<=60351)t-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
3
- Make sure your charset is UTF-8`);t=(t>>>8&255)*192+(t&255),r.put(t,13)}};Cc.exports=Ft});var Ic=C((gw,ki)=>{"use strict";var Br={single_source_shortest_paths:function(r,e,t){var n={},s={};s[e]=0;var i=Br.PriorityQueue.make();i.push(e,0);for(var o,a,c,l,u,d,h,m,y;!i.empty();){o=i.pop(),a=o.value,l=o.cost,u=r[a]||{};for(c in u)u.hasOwnProperty(c)&&(d=u[c],h=l+d,m=s[c],y=typeof s[c]>"u",(y||m>h)&&(s[c]=h,i.push(c,h),n[c]=a))}if(typeof t<"u"&&typeof s[t]>"u"){var w=["Could not find a path from ",e," to ",t,"."].join("");throw new Error(w)}return n},extract_shortest_path_from_predecessor_list:function(r,e){for(var t=[],n=e,s;n;)t.push(n),s=r[n],n=r[n];return t.reverse(),t},find_path:function(r,e,t){var n=Br.single_source_shortest_paths(r,e,t);return Br.extract_shortest_path_from_predecessor_list(n,t)},PriorityQueue:{make:function(r){var e=Br.PriorityQueue,t={},n;r=r||{};for(n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);return t.queue=[],t.sorter=r.sorter||e.default_sorter,t},default_sorter:function(r,e){return r.cost-e.cost},push:function(r,e){var t={value:r,cost:e};this.queue.push(t),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof ki<"u"&&(ki.exports=Br)});var Nc=C(Mt=>{"use strict";var I=We(),Rc=Ac(),Dc=vc(),Fc=Ec(),Mc=Pc(),Tr=bi(),Hn=Oe(),Df=Ic();function Bc(r){return unescape(encodeURIComponent(r)).length}function Rr(r,e,t){let n=[],s;for(;(s=r.exec(t))!==null;)n.push({data:s[0],index:s.index,mode:e,length:s[0].length});return n}function Uc(r){let e=Rr(Tr.NUMERIC,I.NUMERIC,r),t=Rr(Tr.ALPHANUMERIC,I.ALPHANUMERIC,r),n,s;return Hn.isKanjiModeEnabled()?(n=Rr(Tr.BYTE,I.BYTE,r),s=Rr(Tr.KANJI,I.KANJI,r)):(n=Rr(Tr.BYTE_KANJI,I.BYTE,r),s=[]),e.concat(t,n,s).sort(function(o,a){return o.index-a.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function Ei(r,e){switch(e){case I.NUMERIC:return Rc.getBitsLength(r);case I.ALPHANUMERIC:return Dc.getBitsLength(r);case I.KANJI:return Mc.getBitsLength(r);case I.BYTE:return Fc.getBitsLength(r)}}function Ff(r){return r.reduce(function(e,t){let n=e.length-1>=0?e[e.length-1]:null;return n&&n.mode===t.mode?(e[e.length-1].data+=t.data,e):(e.push(t),e)},[])}function Mf(r){let e=[];for(let t=0;t<r.length;t++){let n=r[t];switch(n.mode){case I.NUMERIC:e.push([n,{data:n.data,mode:I.ALPHANUMERIC,length:n.length},{data:n.data,mode:I.BYTE,length:n.length}]);break;case I.ALPHANUMERIC:e.push([n,{data:n.data,mode:I.BYTE,length:n.length}]);break;case I.KANJI:e.push([n,{data:n.data,mode:I.BYTE,length:Bc(n.data)}]);break;case I.BYTE:e.push([{data:n.data,mode:I.BYTE,length:Bc(n.data)}])}}return e}function Uf(r,e){let t={},n={start:{}},s=["start"];for(let i=0;i<r.length;i++){let o=r[i],a=[];for(let c=0;c<o.length;c++){let l=o[c],u=""+i+c;a.push(u),t[u]={node:l,lastCount:0},n[u]={};for(let d=0;d<s.length;d++){let h=s[d];t[h]&&t[h].node.mode===l.mode?(n[h][u]=Ei(t[h].lastCount+l.length,l.mode)-Ei(t[h].lastCount,l.mode),t[h].lastCount+=l.length):(t[h]&&(t[h].lastCount=l.length),n[h][u]=Ei(l.length,l.mode)+4+I.getCharCountIndicator(l.mode,e))}}s=a}for(let i=0;i<s.length;i++)n[s[i]].end=0;return{map:n,table:t}}function Tc(r,e){let t,n=I.getBestModeForData(r);if(t=I.from(e,n),t!==I.BYTE&&t.bit<n.bit)throw new Error('"'+r+'" cannot be encoded with mode '+I.toString(t)+`.
4
- Suggested mode is: `+I.toString(n));switch(t===I.KANJI&&!Hn.isKanjiModeEnabled()&&(t=I.BYTE),t){case I.NUMERIC:return new Rc(r);case I.ALPHANUMERIC:return new Dc(r);case I.KANJI:return new Mc(r);case I.BYTE:return new Fc(r)}}Mt.fromArray=function(e){return e.reduce(function(t,n){return typeof n=="string"?t.push(Tc(n,null)):n.data&&t.push(Tc(n.data,n.mode)),t},[])};Mt.fromString=function(e,t){let n=Uc(e,Hn.isKanjiModeEnabled()),s=Mf(n),i=Uf(s,t),o=Df.find_path(i.map,"start","end"),a=[];for(let c=1;c<o.length-1;c++)a.push(i.table[o[c]].node);return Mt.fromArray(Ff(a))};Mt.rawSplit=function(e){return Mt.fromArray(Uc(e,Hn.isKanjiModeEnabled()))}});var _c=C(Lc=>{"use strict";var Vn=Oe(),Ci=Ln(),Nf=Ja(),Lf=Xa(),_f=Za(),Kf=rc(),Bi=nc(),Ti=mi(),Of=cc(),qn=mc(),zf=bc(),Wf=We(),Pi=Nc();function $f(r,e){let t=r.size,n=Kf.getPositions(e);for(let s=0;s<n.length;s++){let i=n[s][0],o=n[s][1];for(let a=-1;a<=7;a++)if(!(i+a<=-1||t<=i+a))for(let c=-1;c<=7;c++)o+c<=-1||t<=o+c||(a>=0&&a<=6&&(c===0||c===6)||c>=0&&c<=6&&(a===0||a===6)||a>=2&&a<=4&&c>=2&&c<=4?r.set(i+a,o+c,!0,!0):r.set(i+a,o+c,!1,!0))}}function Hf(r){let e=r.size;for(let t=8;t<e-8;t++){let n=t%2===0;r.set(t,6,n,!0),r.set(6,t,n,!0)}}function qf(r,e){let t=_f.getPositions(e);for(let n=0;n<t.length;n++){let s=t[n][0],i=t[n][1];for(let o=-2;o<=2;o++)for(let a=-2;a<=2;a++)o===-2||o===2||a===-2||a===2||o===0&&a===0?r.set(s+o,i+a,!0,!0):r.set(s+o,i+a,!1,!0)}}function Vf(r,e){let t=r.size,n=qn.getEncodedBits(e),s,i,o;for(let a=0;a<18;a++)s=Math.floor(a/3),i=a%3+t-8-3,o=(n>>a&1)===1,r.set(s,i,o,!0),r.set(i,s,o,!0)}function Ii(r,e,t){let n=r.size,s=zf.getEncodedBits(e,t),i,o;for(i=0;i<15;i++)o=(s>>i&1)===1,i<6?r.set(i,8,o,!0):i<8?r.set(i+1,8,o,!0):r.set(n-15+i,8,o,!0),i<8?r.set(8,n-i-1,o,!0):i<9?r.set(8,15-i-1+1,o,!0):r.set(8,15-i-1,o,!0);r.set(n-8,8,1,!0)}function Gf(r,e){let t=r.size,n=-1,s=t-1,i=7,o=0;for(let a=t-1;a>0;a-=2)for(a===6&&a--;;){for(let c=0;c<2;c++)if(!r.isReserved(s,a-c)){let l=!1;o<e.length&&(l=(e[o]>>>i&1)===1),r.set(s,a-c,l),i--,i===-1&&(o++,i=7)}if(s+=n,s<0||t<=s){s-=n,n=-n;break}}}function Yf(r,e,t){let n=new Nf;t.forEach(function(c){n.put(c.mode.bit,4),n.put(c.getLength(),Wf.getCharCountIndicator(c.mode,r)),c.write(n)});let s=Vn.getSymbolTotalCodewords(r),i=Ti.getTotalCodewordsCount(r,e),o=(s-i)*8;for(n.getLengthInBits()+4<=o&&n.put(0,4);n.getLengthInBits()%8!==0;)n.putBit(0);let a=(o-n.getLengthInBits())/8;for(let c=0;c<a;c++)n.put(c%2?17:236,8);return jf(n,r,e)}function jf(r,e,t){let n=Vn.getSymbolTotalCodewords(e),s=Ti.getTotalCodewordsCount(e,t),i=n-s,o=Ti.getBlocksCount(e,t),a=n%o,c=o-a,l=Math.floor(n/o),u=Math.floor(i/o),d=u+1,h=l-u,m=new Of(h),y=0,w=new Array(o),b=new Array(o),S=0,A=new Uint8Array(r.buffer);for(let F=0;F<o;F++){let $=F<c?u:d;w[F]=A.slice(y,y+$),b[F]=m.encode(w[F]),y+=$,S=Math.max(S,$)}let v=new Uint8Array(n),B=0,E,U;for(E=0;E<S;E++)for(U=0;U<o;U++)E<w[U].length&&(v[B++]=w[U][E]);for(E=0;E<h;E++)for(U=0;U<o;U++)v[B++]=b[U][E];return v}function Jf(r,e,t,n){let s;if(Array.isArray(r))s=Pi.fromArray(r);else if(typeof r=="string"){let l=e;if(!l){let u=Pi.rawSplit(r);l=qn.getBestVersionForData(u,t)}s=Pi.fromString(r,l||40)}else throw new Error("Invalid data");let i=qn.getBestVersionForData(s,t);if(!i)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=i;else if(e<i)throw new Error(`
1
+ "use strict";var Tf=Object.create;var hr=Object.defineProperty;var Rf=Object.getOwnPropertyDescriptor;var Df=Object.getOwnPropertyNames;var Ff=Object.getPrototypeOf,Mf=Object.prototype.hasOwnProperty;var Uf=(r,e,t)=>e in r?hr(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var p=(r,e)=>()=>(r&&(e=r(r=0)),e);var B=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),A=(r,e)=>{for(var t in e)hr(r,t,{get:e[t],enumerable:!0})},La=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Df(e))!Mf.call(r,i)&&i!==t&&hr(r,i,{get:()=>e[i],enumerable:!(n=Rf(e,i))||n.enumerable});return r};var W=(r,e,t)=>(t=r!=null?Tf(Ff(r)):{},La(e||!r||!r.__esModule?hr(t,"default",{value:r,enumerable:!0}):t,r)),_f=r=>La(hr({},"__esModule",{value:!0}),r);var f=(r,e,t)=>Uf(r,typeof e!="symbol"?e+"":e,t);var Hi={};A(Hi,{AddressChangeError:()=>Ne,ApiError:()=>fr,AuthenticationError:()=>F,CryptoError:()=>x,PrfUnsupportedError:()=>ee,RegistrationError:()=>tt,RemovedBackupMethodError:()=>nt,StorageError:()=>P,SyncBootstrapError:()=>he,SyncRequiredError:()=>rt,UnsupportedBackupVersionError:()=>Te,WalletError:()=>g,WalletMissingError:()=>Le,WeakPasswordError:()=>it,Web3PasskeyError:()=>E,ZkArtifactMismatchError:()=>st});var E,F,tt,g,x,P,fr,rt,Le,Lf,he,ee,Ne,nt,Te,it,st,T=p(()=>{"use strict";E=class extends Error{constructor(t,n,i){super(t);this.code=n;this.originalError=i;this.name="Web3PasskeyError"}},F=class extends E{constructor(e,t){super(e,"AUTHENTICATION_ERROR",t),this.name="AuthenticationError"}},tt=class extends E{constructor(e,t){super(e,"REGISTRATION_ERROR",t),this.name="RegistrationError"}},g=class extends E{constructor(e,t){super(e,"WALLET_ERROR",t),this.name="WalletError"}},x=class extends E{constructor(e,t){super(e,"CRYPTO_ERROR",t),this.name="CryptoError"}},P=class extends E{constructor(e,t){super(e,"STORAGE_ERROR",t),this.name="StorageError"}},fr=class extends E{constructor(t,n,i){super(t,"API_ERROR",i);this.statusCode=n;this.name="ApiError"}},rt=class extends E{constructor(t){super("Passkey authenticated but this device has no data for it. Sync this device or restore from a backup.","SYNC_REQUIRED");this.credentialId=t;this.name="SyncRequiredError"}},Le=class extends E{constructor(t,n){super("Passkey authenticated but no wallet was found on this device. Restore it from a backup.","WALLET_MISSING");this.credentialId=t;this.ethereumAddress=n;this.name="WalletMissingError"}},Lf={NO_CREDENTIAL:"This backup doesn't name its passkey, so it can't set up this device. Create a new password backup on a device where you're logged in.",CREDENTIAL_MISMATCH:"This backup belongs to a different passkey than the one selected.",PUBLIC_KEY_MISMATCH:"The passkey's signature doesn't match the public key in this backup. The backup may have been tampered with."},he=class extends E{constructor(t,n){super(Lf[t],"SYNC_BOOTSTRAP_FAILED");this.reason=t;this.credentialId=n;this.name="SyncBootstrapError"}},ee=class extends E{constructor(t){super("This passkey's authenticator doesn't support the WebAuthn PRF extension.","PRF_UNSUPPORTED");this.credentialId=t;this.name="PrfUnsupportedError"}},Ne=class extends E{constructor(t,n){super(`This backup holds wallet ${n}, not ${t}. Restoring it replaces the wallet on this device.`,"ADDRESS_CHANGE_NOT_ALLOWED");this.currentAddress=t;this.newAddress=n;this.name="AddressChangeError"}},nt=class extends E{constructor(t){super(`This ${t} backup is no longer supported: its key came from the passkey's public data, not from the passkey. Create a new password or PRF backup on a device where you're logged in.`,"BACKUP_METHOD_REMOVED");this.method=t;this.name="RemovedBackupMethodError"}},Te=class extends E{constructor(t,n){let i=t===void 0?"v2 or earlier":`version ${String(t)}`;super(`This backup file uses an unsupported format (${i}). w3pk restores BackupFile v3 only. ${n==="prf"?"Export a new backup with exportForSync() on a device where the wallet is.":"Decrypt a v2 password backup with the v0.10.6 offline tool (https://github.com/w3hc/w3pk/blob/v0.10.6/standalone/extract-mnemonic.html), then create a new backup."}`,"BACKUP_VERSION_UNSUPPORTED");this.version=t;this.name="UnsupportedBackupVersionError"}},it=class extends E{constructor(t){super(`Password is too weak: ${t.join("; ")}`,"WEAK_PASSWORD");this.feedback=t;this.name="WeakPasswordError"}},st=class extends E{constructor(t,n,i){super(`The ${t} artifact's CID ${i} doesn't match the pinned CID ${n}.`,"ZK_ARTIFACT_MISMATCH");this.artifact=t;this.expectedCid=n;this.actualCid=i;this.name="ZkArtifactMismatchError"}}});var $i,Na=p(()=>{"use strict";$i=new Set(`
2
+ mailcreated5240
3
+ polniypizdec0211
4
+ 123456789987654321
5
+ 1qaz2wsx3edc4rfv
6
+ 123456789123456789
7
+ momsanaladventure
8
+ hd764nw5d7e1vb1
9
+ qazwsxedcrfvtgb
10
+ 23176djivanfros
11
+ 123456789qwerty
12
+ 12345678900987654321
13
+ 12345678901234567890
14
+ qwerty123456789
15
+ zqjphsyf6ctifgu
16
+ 12345678987654321
17
+ lhbjkjubz2957704
18
+ q1w2e3r4t5y6u7i8
19
+ 1qazxsw23edcvfr4
20
+ 11111111111111111111
21
+ nemvxyheqdd5oqxyxyzi
22
+ 123123123123123
23
+ passwordstandard
24
+ bpgjldsgjldthnf
25
+ 1qa2ws3ed4rf5tg
26
+ 1234qwerasdfzxcv
27
+ passwordpassword
28
+ polniypizdec110211
29
+ 1234567890qwerty
30
+ 1234567890987654321
31
+ 122333444455555
32
+ 111222333444555
33
+ qwertasdfgzxcvb
34
+ q1w2e3r4t5y6u7i8o9p0
35
+ ne_e_pod_chehyl
36
+ 1234567887654321
37
+ 111111111111111
38
+ zxcvbnm123456789
39
+ qwertyuiop12345
40
+ hjpjxrf23062007
41
+ aksjdlasdakj89879
42
+ nick1234-rem936
43
+ 420842084208555
44
+ 123451234512345
45
+ lytdybrbdfvgbhf
46
+ hd764nw5d7e1vbv
47
+ bhrh0h2oof6xbqjeh
48
+ 1234567890qwertyuiop
49
+ qwertyuiopasdfg
50
+ qwertyuiop123456789
51
+ perasperaadastra
52
+ cheaphornybastard
53
+ polniypizdec1102
54
+ efwe5tgwa5twhgd
55
+ 30secondstomars
56
+ 2222333344445555
57
+ 1324354657687980
58
+ 12345678qwertyu
59
+ 1213141516171819
60
+ qwertyuiopasdfghjkl
61
+ qwertyuiopasdfgh
62
+ perfectexploiter
63
+ neversaymypassword
64
+ manchesterunited
65
+ cfvfzcxfcnkbdfz
66
+ passwordassword
67
+ 277rte87hryloitru
68
+ 1234567899876543
69
+ 123456789123456
70
+ 123456789101112
71
+ 1234567812345678
72
+ 010203040506070809
73
+ parliament12345
74
+ fypjhbr007dfcz007rfr
75
+ 923650asdfghjkl
76
+ 555555555555555
77
+ 09876543211234567890
78
+ worldofwarcraft
79
+ wegangster4lifebitch
80
+ stairwaytoheaven
81
+ ske9k9tch3r5w9s
82
+ qazxswedcvfrtgb
83
+ qazwsxedcrfvtgbyhn
84
+ prigoda25392637
85
+ justinkislyanka
86
+ ikhouvanjeomer12345
87
+ gygypyfyyyposhy
88
+ drift89094072877
89
+ cristianoronaldo
90
+ asdfghjklzxcvbnm
91
+ asdfghjkl123456
92
+ 321673216732167
93
+ 12345qwertasdfg
94
+ 123456789qwertyu
95
+ 1234567890qweasd
96
+ 112233445566778899
97
+ 102030405060708090
98
+ zxcvbnmasdfghjkl
99
+ youngandrestless
100
+ xf6cmqlrpeuhjuvv
101
+ xkzwnuxkdn9a8kcykuitbkg1g
102
+ wsxz3823922163845
103
+ vfcnthbvfhufhbnf
104
+ samsungkoze176351
105
+ relaxwebbewxaler
106
+ qwertyuiopasdfghjklzxcvbnm
107
+ qwerty1234567890
108
+ quant4307quant4307
109
+ qawsedrftgyhujik
110
+ professionaltools
111
+ kyk1rbk1hbw0uqkckwbh
112
+ incrediblereview
113
+ hgdxtgttgfdtdtes
114
+ gjgeufqhjvfyfzif
115
+ ejxjzgbgunaz9z6j6exbniqga
116
+ dima324315198540
117
+ a1s2d3f4g5h6j7k8
118
+ 12345678qwertyui
119
+ 123456789qazwsx
120
+ 11223344556677889900
121
+ zxcvbnm12345678
122
+ zeus7169-ladidadi
123
+ zaq12wsxcde34rfv
124
+ y5hjkdg82490840
125
+ vjqvfktymrbqvbh
126
+ spectrumsonline
127
+ qwerty123qwerty
128
+ qwerasdfzxcv1234
129
+ pedrolucasmunhoz
130
+ orientepetroler
131
+ onlyone4-myxworld
132
+ nbkbvbkbnhzvlbz
133
+ muslim0626461997
134
+ heatoclevaedr36
135
+ gthtgjldsgjldthn
136
+ gordolee85-mac2olli
137
+ eropokereropoker
138
+ ereyes4269-ryan1199
139
+ eagle1110-stimpy
140
+ dust360271212009
141
+ dsgtylhbdfntkm82
142
+ cjdthityyjctrhtnyj
143
+ changed_due_to_fraud
144
+ yfltymrfxgjr0707
145
+ rfewtww5tgregtr
146
+ gbplfnsqgfhjkm1
147
+ gqlsstfhqgwwvqxjx
148
+ fuckyourbrain13
149
+ euq8pvhrnpssdymizqx+
150
+ egew5twt3tgh65y
151
+ ds6tetsfdsrfdfgd
152
+ c3hfpyteuflftim
153
+ 987654321987654321
154
+ 987654321123456789
155
+ 85fg754kl62br853lpq7
156
+ 2sexy2hottoh2yxes2
157
+ 258456789qazzaq5
158
+ 1a2s3d4f5g6h7j8k
159
+ 1xpx66blrumblst6bbus3
160
+ 147258369147258369
161
+ 14021992004urban
162
+ 12qwaszx34erdfcv
163
+ 123qwe123qwe123
164
+ 123456789qwertyuiop
165
+ 1234567890anton
166
+ 1234567890123456789
167
+ 123456787654321
168
+ 1111111111111111
169
+ 0k1o2v3a4l5e6v7
170
+ 00rdtsau4leyzunckj121dwm
171
+ zghjcnjgfifujleyjd
172
+ zcfvfzcxfcnkbdfz
173
+ yfcnzyfcnzyfcnz
174
+ vtyltkttdrfrfhf
175
+ vsebudethorosho
176
+ vladivostok2000
177
+ ulrace173rfhgjd
178
+ teshka_poltavka
179
+ supercutekawaii
180
+ ssssssssssssssss
181
+ sashasashasasha
182
+ sasha1993150205
183
+ rumpelstiltzkin
184
+ rmracinggnicarmr
185
+ rainbowskittles
186
+ qweasdzxc123321
187
+ passworddrowssap
188
+ omegamircolaura
189
+ mychemicalromance
190
+ moneyfornothing
191
+ mogilev368088193
192
+ mnbvcxzasdfghjkl
193
+ mihamihamiharap
194
+ methamphetamine
195
+ messygirl-girlmessy
196
+ lolfriendslaugh
197
+ letadlo741852963
198
+ jenniferjennifer
199
+ iaxe105-lanceman
200
+ htcnhernehbpfwbz
201
+ hgfedcbaabcdefgh
202
+ heckfydrjynfrnt
203
+ happytreefriends
204
+ gfhjkmgfhjkmgfhjkm
205
+ gfhjkm123456789
206
+ gergdsfgedhjdrg
207
+ deusdoimpossivel
208
+ danilka123123456
209
+ crusadercrusader
210
+ cristianoronald
211
+ cheaphornybastar
212
+ cgjldsgjldthnjv
213
+ boosucka-wanger
214
+ birkjen-jengele
215
+ bendis-chrisbln
216
+ balloonssnoollab
217
+ avengedsevenfold
218
+ ashleywilliams2010
219
+ anhyeuemnhieulam
220
+ anhchiyeuminhem
221
+ allyouneedislove
222
+ aleks1236556321
223
+ adidasonparas123
224
+ aaaaaaaaaaaaaaaaaaaa
225
+ aaaaaaaaaaaaaaaa
226
+ a1s2d3f4g5h6j7k8l9
227
+ x4cc355b10wsy0urm1nd
228
+ rgihlxoyoclmgiqsu
229
+ popovich250293sanek
230
+ nikita9609595982
231
+ jeffersonlibrar
232
+ f1x753951753951
233
+ djpdhfotybt1992
234
+ byyf1991vensuper
235
+ 89116446869tema
236
+ 80688800742ilona
237
+ 543279937954lol
238
+ 2010benvanburen
239
+ 1qaz2wsx3edc4rfv5tgb
240
+ 1q2w3e4r1q2w3e4r
241
+ 123qweasdzxc123
242
+ 123456789zxcvbnm
243
+ 123456789012345
244
+ 1234554321vfrcbv
245
+ 090807060504030201
246
+ 057yeja1zpc3ljx8ci
247
+ 00000000000000000000
248
+ 000000000000000
249
+ zxcvbnm1234567890
250
+ znfrfzrfrfztcnm
251
+ zlodeivot88w3er
252
+ zcfvfzcfvfzcfvfz
253
+ zaq1xsw2cde3vfr4
254
+ zaibuneng198710
255
+ yjplhtvjxrf0102
256
+ yfujhirtcbltkrjhjkm
257
+ yfcntyfckfcntyf
258
+ www9356527575195
259
+ websolutions007
260
+ vsebudetxorosho
261
+ vehfnjdfqaz123496
262
+ valerakish963210
263
+ uthvfybzrfekbnw
264
+ trafficexchange
265
+ thisismypassword
266
+ thiesing-daniela
267
+ tbrunson-serihs
268
+ tanya1234567890
269
+ t6dlniahehjsktr60vp8rb50e2
270
+ stargateasgard2009
271
+ sliueaproulou81
272
+ shithappendsshit
273
+ sharpandshiny121
274
+ rrrrrrrrrrrrrrrr
275
+ romkathepapavk147896325
276
+ romasxodizaxlebo
277
+ robertpattinson
278
+ rjyutybfkmyjcnm
279
+ rhfcjnfcgfctnvbh
280
+ rfgyuji8il0oksdfzx
281
+ randomdude12000
282
+ raidersofthelostark
283
+ radeonradeon159
284
+ qwertyuiopzxcvbnm
285
+ qwertyuiopasdfghjklz
286
+ qwertyuiasdfghjk
287
+ qwertyasdfghzxcvbn
288
+ qwerty987654321
289
+ qwe9876543211234567
290
+ qwaszx987412369
291
+ qq11ww22ee33rr44
292
+ qazwsxedcrfvtgbyhnujm
293
+ qazwsxedcrfvtgby
294
+ qaz123wsx456edc
295
+ qawsedrftgyhujikol
296
+ preciousprotection
297
+ pogo22-omegaome
298
+ phs16l31pogosta
299
+ philipdannypaul
300
+ ped100ananacnaveka
301
+ parasha11uvarova
302
+ p140499417feef870
303
+ opezassociateslb
304
+ nuttertools1234
305
+ nissanskylinegtr
306
+ nhfdfytyfhrjnbr
307
+ nevershoutnever
308
+ nastyanastya123
309
+ myponycancelled
310
+ minhafelicidade
311
+ mikeybihon-post12
312
+ mihaisurleanu2561
313
+ michaeljacksonj
314
+ merkava-ivanhar1
315
+ merchantmerchant
316
+ mashamashamasha
317
+ masa3364-33645962
318
+ martenson908884
319
+ marinanastua1313
320
+ marie-madeleine
321
+ luvbekkikkevbul
322
+ lrodney-rrodney
323
+ lrh195005041971
324
+ louisdog-hattydog
325
+ louis.vd.bongaert
326
+ loco68-impossib
327
+ laurelindorenan
328
+ lasnaloveafrosja
329
+ kumarsouravarzoo
330
+ kirill123456789
331
+ kfdhtynmtdf112233
332
+ jenniferrefinnej
333
+ jazzymanlfuckem
334
+ jamestkirk7769h
335
+ jackasslolfr21345
336
+ iwillk03657320258
337
+ iseedeadpeople1
338
+ iofdmaaycdbvrlbi
339
+ incredibleguest
340
+ ilikedressingup
341
+ iamalocksmith25
342
+ hs49zu7wzpk2r5ac
343
+ hl3fp5sjer8wmcyk
344
+ gtnhjpfdjlcr123
345
+ greedisgood10987
346
+ gjkbyf123ghjybyf
347
+ ghtlghbybvfntkm
348
+ ghjcnj15z04jdty88
349
+ gfifvtldtltdghjcnjkfgjxrf
350
+ garciamartin1995
351
+ fussballverruckte
352
+ frephiotohaij65
353
+ freetrafficworld
354
+ franklinnilknarf
355
+ fltkbyf13122009
356
+ farida1a-rem710
357
+ euamominhafamilia
358
+ erocdrahhardcore
359
+ emyeuanhnhieulam
360
+ dontworrybehappy
361
+ dominik563431995
362
+ dkflcjrjkjdcrbq
363
+ dflbvybrjkftdbx
364
+ devilmaycry1991
365
+ deflep27-starwars
366
+ deatiphiliato27
367
+ dbrnjhbzdbrnjhbz
368
+ daytrip-daycamp
369
+ dashatwilight305
370
+ dasha1234567890
371
+ darinkabibalova
372
+ cthuttd123fhntv
373
+ counterstrike16
374
+ coubeahecrubi49
375
+ contraspemspero
376
+ cjkytxysqpfqxbr
377
+ chouraethiaci10
378
+ cfvfpyftimrfrjq
379
+ c0904fd726fc565
380
+ bylecnhbfkbpfwbz
381
+ br76vt466464443
382
+ bones69-bones69
383
+ biosnex-hardrive
384
+ bcgjldsgjldthnf
385
+ bbbbbbbbbbbbbbbb
386
+ bawcat-taebo101
387
+ balloonsballoons
388
+ azsxdcfvgbhnjmk
389
+ assemyouaretheking
390
+ antoniobanderas
391
+ antifamilymang1
392
+ andrejs-iii0649
393
+ andrei123456789
394
+ altaltaltaltalt
395
+ alisha1234567899
396
+ aian123321456654
397
+ achilleus-chrisbln
398
+ abcdefghijklmnop
399
+ aaaaaaaaaaaaaaa
400
+ wso9rycamguchqpdwwvbad
401
+ primavera2006casa
402
+ patricia.miguel
403
+ nhbujyjvtnhbz212
404
+ navykentron1994
405
+ kalmar801415854
406
+ gettingthenetfucker
407
+ eveningcucumber
408
+ digitalplayground
409
+ americandream23
410
+ 999999999frbnzy
411
+ 9946755822zoomin
412
+ 96014430windowslive
413
+ 8m917a753k98s25
414
+ 89502727543lexa
415
+ 89278724282serg
416
+ 89031719600bhbyf
417
+ 8765432112345678
418
+ 80971542123gfif
419
+ 789456123qwerty
420
+ 789456123789456123
421
+ 789456123321654987
422
+ 721174730459913
423
+ 666xbckjlmzdjkf
424
+ 654634536365354
425
+ 6521bf42403fc9d8
426
+ 555032212333366
427
+ 4815162342lost4
428
+ 4733473347334733
429
+ 351795067351795067
430
+ 336755aa336755aa
431
+ 24kent04kent83.
432
+ 2345zet56776869
433
+ 2222222222222222
434
+ 218362kikakotik
435
+ 2014526rfyrelfq
436
+ 1wdx3wax1wdx3wax
437
+ 1qazxsw21qazxsw2
438
+ 1q2q3q4q5q6q7q8q
439
+ 1pwhon42nnlvh1b
440
+ 19061995yulenka
441
+ 159357159357159357
442
+ 1505199129041991
443
+ 15003f640a10fd13
444
+ 147258369147258
445
+ 12qw90op12qw90op
446
+ 12qw34er56ty78ui
447
+ 123qwezxc123asd
448
+ 123boots1123boots2
449
+ 123789456123789456
450
+ 12345qwertyuiop
451
+ 123456qwertyuiop
452
+ 123456789valera
453
+ 123456789ghbdtn
454
+ 12345678987456321
455
+ 1234567891234567
456
+ 12345678910111213141
457
+ 1234567891011121314
458
+ 12345678910111213
459
+ 1234567890qwert
460
+ 1234567890qazwsx
461
+ 1234567890123456
462
+ 1234567890098765
463
+ 11c645df6bc8a365
464
+ 10293847561029384756
465
+ 0997450201cthbq
466
+ 09876543210987654321
467
+ 054624917100225588
468
+ 0509672427nastya
469
+ 0302multiblkjdcrbq0302
470
+ 025230230243639
471
+ 01234567890123456789
472
+ 010519961111gfhjkm
473
+ !qazxsw2#edcvfr4
474
+ zyfujhfr16021997
475
+ zxczxczxczxczxc
476
+ zxcvbnmmnbvcxzx
477
+ zxcvbnmlkjhgfdsa
478
+ zxcasdqwe123valera
479
+ zwy5ftneynaibtgxalqc
480
+ zrjdktd22121986
481
+ zpnz8tt9hdyvz5bz
482
+ zippy222-rem757
483
+ zimbabweewbabmiz
484
+ zhenya123456789
485
+ zerocool9445346
486
+ zcfvfzghbrjkmyfz
487
+ zcfvfzcxfcnkbdf
488
+ zcegth123456789
489
+ zarembitska46011
490
+ zaqwsxcderfvbgtyhn
491
+ z1c9r2m4l6v8sd54
492
+ yuliyabanny030302
493
+ ytjghtltktyyjcnm
494
+ ytgjdnjhbvfz923
495
+ yousexymfyousexymf
496
+ yourguardianangel
497
+ youngestamateurs
498
+ youknowyouloveme
499
+ youarethekingnoob
500
+ ylzzirg11grizzly
501
+ yjdsqgfhjkm531466
502
+ ygfgdfhjrrtree2
503
+ yfcnz1234567890
504
+ ybrrblbrbycjy1992
505
+ ybrnjytdpkjvftn
506
+ ybrjkfqbdfyjdbx
507
+ ybrbnfhjvfyfnfif
508
+ yankapartizanka
509
+ yaddayaddayadda
510
+ ydnm5xmznozagt3
511
+ y0cq9fpk9xz4vr5v
512
+ xxxxxxxxxxxxxxxx
513
+ xtkjdtrvjktrekf
514
+ xthtpnthybbrpdtplfv
515
+ xpressmusic5530
516
+ xarlamoff20003000
517
+ xovbjnfyn2fghsdv
518
+ www123456321www
519
+ wuxiaofei19866110
520
+ wutanga-killabee
521
+ worldofwarkraft
522
+ woaded1-vampish7
523
+ wladwladwlad24413wlad
524
+ withintemptation
525
+ wilmer-usmcduck
526
+ wilco791-12345678
527
+ whysoserious2012
528
+ whitezazabrowny
529
+ whiskeydynomite
530
+ whigginb1-s739rht8
531
+ wheelman15011998
532
+ westcoastcustoms
533
+ weihnachtsmarkt
534
+ weihnachtskugel
535
+ wehotandwesmokin182
536
+ webcrackers2oo3
537
+ wbrkfvtyskyblue
538
+ wbfghjnb56zxc39as
539
+ waychuck-diamond
540
+ watashiwadesuka
541
+ w4606086013369w
542
+ w1w2w3w4w5w6w7w8w9
543
+ w!2e3b#pszd9fxav
544
+ vocevirousaudad
545
+ vlad911009291998
546
+ vkliferita31214
547
+ vjqukflbfnjh123
548
+ vjhtdjkyetnczhfp
549
+ vividdottle2000
550
+ vit38960540alik
551
+ vioqwert14041990
552
+ vfvjxrfbgfgjxrf
553
+ vfnbkmlf2010cjfrf
554
+ vfkmxbrcgfkmxbr
555
+ vfhujif21052007
556
+ vfhnjdcrfzrjirf
557
+ vertii1999masha1
558
+ veronika2786350
559
+ veritas-chrisbln
560
+ velesnickaya525
561
+ vbn322jfg434rty
562
+ vbkkbjyljkkfhjd
563
+ vbhjckfdfrfhgjdbx
564
+ vbh7vfrcbvjdf14
565
+ vasilevich1967m
566
+ vashthestampede
567
+ vakinnkrutoi4el
568
+ vadimpustovoitov
569
+ vyhkbhe7gtvwjfv5
570
+ voe0eqh4f0pzhqon
571
+ vior3luzl6u1ry2e1
572
+ vgtkau8f5zzimt6j
573
+ v1o9v7a8tulupov
574
+ uuuuuuuuuuuuuuuu
575
+ utopiahillhorses
576
+ uthjbvtxfbvfubb
577
+ usernameemanresu
578
+ upm6pcsfxrrgsff5
579
+ uomapheveadou51-moudaicr
580
+ uomapheveadou51
581
+ unlimitedqwerty
582
+ unitedsheffield
583
+ ulysses-chrisbln
584
+ ukfvehysqgjljyjr1993
585
+ ujcfdnjljhyflpjh
586
+ uhtntkmvfhufhbnf
587
+ ufyttdhfabcjdbxnbveh
588
+ ufkbyfdbrnjhjdyf
589
+ uzf$vgpiwrobuxrc
590
+ twilighttennispenguins
591
+ tutephoconani40
592
+ tupacamarushakur
593
+ tttttttttttttttt
594
+ tstapes5990comc
595
+ trying2getphatw00t
596
+ trusov4003014665
597
+ trepescienucachisso
598
+ treawrihaiphe58
599
+ transplantation
600
+ translatability
601
+ trafficwonderland
602
+ tpepsucolia@1209
603
+ toshiakitoshiaki
604
+ tltprokopyn199229
605
+ tktyfghtrhfcyfz
606
+ tktyfdbnfkmtdyf18
607
+ thxthxcancelled
608
+ throwyourassout
609
+ threelittlebirds
610
+ threatenedagrip
611
+ thompsonthompson
612
+ thnarchyhalf3613
613
+ thisweekinpalestine
614
+ thisisapassword
615
+ theylovemehbad123
616
+ theworldisyours
617
+ thetruesightomg333222444
618
+ thegimp-gr5av8b
619
+ thegathering1993
620
+ theforceunleashed
621
+ thedeej-alex266
622
+ thedarkride2000
623
+ thechampaloushi
624
+ thatmeansrevenge-xxx
625
+ thatmeansrevenge
626
+ thamires123456789
627
+ thalesaugusto37027269*
628
+ thafriauuwrea21
629
+ texnolog511akatj
630
+ testingcheatsenabled
631
+ terremotoenchil
632
+ terezaefernando
633
+ teerbob1-faceman1
634
+ taynagamaprimavera
635
+ tawny21bii-access
636
+ taniafernandes_87
637
+ talamort?dukolak
638
+ takekazu7-kamikitakeiko
639
+ takehana-take8422
640
+ syncmaster793df
641
+ syncmaster763mb
642
+ syncmaster757nf
643
+ syncmaster755dfx
644
+ syncmaster753dfx
645
+ susie65-eurostra
646
+ supplementalincome
647
+ suellembarbosadossan
648
+ stoudriaslama55
649
+ stlkylilix100pr
650
+ stilllikedressingup
651
+ starwarsstarwars
652
+ starwarsjfkrush
653
+ srinivassavinirs
654
+ sri2ivassri9ivas
655
+ sri0ivassri3ivas
656
+ sportsinengland
657
+ sport80984975792
658
+ spliffed-spliffer
659
+ speakersystem22
660
+ spdjgutnvhfjghdnqliu
661
+ spalermo-middle
662
+ sonyericssons312
663
+ sonyericsson777
664
+ soeuseiminhasenha
665
+ snowbars481516234270119
666
+ smoke5577sunday
667
+ smirnov.lizuncova
668
+ smileystolen101201
669
+ smashingsundays
670
+ sliueaproulou81-druphach
671
+ sliajoraephae86
672
+ sl8facl7vrwfwvro
673
+ shrike01-hyperion
674
+ shishkabarakalum
675
+ sheffieldsheffield
676
+ shaxidshaxid1983
677
+ shanekilpatrick
678
+ sexmaniacs-liverune
679
+ sex.com77snnkesnakeman
680
+ sergiomonterrey
681
+ sergeyt08980898
682
+ sergey987654321
683
+ sergey1234567890
684
+ sergei123456789
685
+ serejenka2613982
686
+ sentinellenitnes
687
+ sempreeparasempre
688
+ semaj700007james
689
+ securedbymelannie
690
+ sdwhd6533vo32fjs
691
+ sddpcht-1234567
692
+ scrotumniger11va
693
+ scofie4815162342
694
+ schneefloeckche
695
+ sbrouse-awesome
696
+ saturn159248137
697
+ satogonap080718
698
+ sataniquemizo-19
699
+ sashastalkerxaaa
700
+ saransk03513rus
701
+ sarahbenalvarez
702
+ sarabelle252000
703
+ sanscontrefacons
704
+ sanju582realmadrid
705
+ sanik89286532300
706
+ sandralanoeskaa
707
+ sandalio2906fhe
708
+ san4er123san4er
709
+ salvowebsolutions
710
+ salfetka11121992
711
+ saijajantunen94
712
+ sadlukkbnmz1234
713
+ sachintendulkar
714
+ s1o2r3k4a5n6g7e8l
715
+ rydolf230031551
716
+ ruqiyahlovemuaz
717
+ ruenharn8ekzji4z
718
+ rtxbyf9491856061
719
+ rrrrrrrrrrrrrrr
720
+ rosemaryrosemary
721
+ roscoejschweins
722
+ romik199520109040465697
723
+ rockalivesolomax
724
+ robert123456789
725
+ rmracingrmracing
726
+ rjulfjyljrehbn24
727
+ rjnvfnhjcrby1982
728
+ rjnsdjbntkb1998
729
+ richardkiehn588
730
+ rich1963-debbie
731
+ rhfcrf1999ghjikf
732
+ rhfcbdstvjycnhs
733
+ rhenjq159634789
734
+ rhbcnbyfrhbcnbyf
735
+ rfpfynbgxbr1234
736
+ rfpfrcdtnkfyfutyflmtdyf45984
737
+ rfnhbyghbdfkjdf
738
+ rfgbnfycrfzljxrf
739
+ repea0978102889
740
+ reibreh11herbier
741
+ rdtynbynfhfynbyj
742
+ rbcf11219112008
743
+ rastamanrastaman
744
+ rainbowinthesky
745
+ rada89248682908
746
+ rachelilletschko
747
+ r4e3w2q1r4e3w2q1
748
+ r16241924132400
749
+ qwqw12233445qwqw
750
+ qwqeqrqtqyquqiqoqp
751
+ qwertyuiopqwertyuiop
752
+ qwertyuioppoiuytrewq
753
+ qwertyuiop1234567890
754
+ qwertyasdfgh1971
755
+ qwertyasdfgh123
756
+ qwerty123451994
757
+ qwerasdfzxcvqaz
758
+ qwerasdfzxcv123
759
+ qweasdzxcrfv123
760
+ qweasdzxcqweasdzxc
761
+ qweasd123456789
762
+ quiveringotter-im4sin
763
+ quienlovaasaber
764
+ qqqqqqqqqqqqqqqqqqqq
765
+ qqqqqqqqqqqqqqqq
766
+ qqqqqqqqqq00000
767
+ qpwoeirutyqpwoeiruty
768
+ qdwlrsfy9ddqqgbsyx
769
+ qazxswedcvfrtgbnhyuj
770
+ qazxswedcvfrtgbnhy
771
+ qazwsxedcrfvtgbyhnujmikolp
772
+ qazwsxedcrfvtgbyhnuj
773
+ qazwsxedcrfv123
774
+ qazwsxedc1234567
775
+ qaz123wsx123edc
776
+ qaedrw9707134625
777
+ q1w2e3r4t5y6u7i8o9
778
+ q1q1q1q1q1q1q1q1
779
+ pyqdtmed8thirci
780
+ pyjdbvhjrjv2011
781
+ psychedelic2010
782
+ progressivehouse
783
+ prisonfor10years
784
+ princeofdarkness
785
+ prestigiousmodels
786
+ practicepractice
787
+ practiceecitcarp
788
+ pr1wualb179861p
789
+ poweroverwhelming
790
+ powerdestiny090
791
+ potqwerty545214
792
+ poppers4-4r5t6y7u
793
+ poleuretan42rus
794
+ poiuytrewqpoiuytrewq
795
+ poiuytrewq12345
796
+ poiuytrewq0987654321
797
+ platinumpussy47
798
+ plasmaticrick69
799
+ pistoolboekjemetinho
800
+ piratesofcaribea
801
+ pineapplehair887
802
+ pidaras12345098
803
+ phuslipraedre22-trimasto
804
+ phuslipraedre22
805
+ photosmartexpres
806
+ phillipmichelle
807
+ pfvjrpfvjrpfvjr
808
+ pezaregood88854
809
+ peterrbaskerville
810
+ peter.g.robinson
811
+ pepperminttea88
812
+ pedrocagatinhodanet140594
813
+ pearson_88earson
814
+ patrakovserega23
815
+ password123456789
816
+ pashastolenn110601s
817
+ parolparolparol
818
+ parba09305232165
819
+ paralelipiped98
820
+ papaandthewhitehouse
821
+ panicatthedisco
822
+ p6gfyojtl5artjb
823
+ p4swd_6c805c3ad8
824
+ p38p38p38p38p38
825
+ p0o9i8u7y6t5r4e3w2q1
826
+ p.pz03012010rerepz
827
+ oscar_jose_2007
828
+ originalganjaman
829
+ opalpussycat334
830
+ oooooooooooooooooooo
831
+ onlyone4-excess
832
+ onetwothreefour
833
+ oliviaisamazing
834
+ oliveiraanthony
835
+ oliischdebescht
836
+ olegfirstalways
837
+ ola5velq2pp093m
838
+ oglocoglocogloc
839
+ ofokeha9hy8oifen6
840
+ oezininainnaa11
841
+ obskaya2akv71995
842
+ nopasswordinass
843
+ noneofyourbusiness
844
+ nokiaxpressmusic
845
+ nokia2700classic
846
+ noblekamael2010
847
+ njwanazam6qazwsx
848
+ nimajnebbenjamin
849
+ nikitasergeevich
850
+ nikita485974147
851
+ niceangelbaby2008
852
+ nhlzl1idnhlzl1id
853
+ nguoitoiyeulaai
854
+ nfhfrfybpfwbz62
855
+ newyork2newyork1
856
+ newsarama1pass1
857
+ needforspeed123
858
+ nbkbvbkbnhzylbz
859
+ naughtyscotty4u
860
+ natalu007025270
861
+ natali3344223xxx
862
+ natali123456789
863
+ nastyahapaevalove
864
+ nastyachestardolia
865
+ nastya2010nastya
866
+ nastya1234567890
867
+ narsula20252401
868
+ naglyphsinsp8249
869
+ nagato123456789
870
+ nadyamayher1982
871
+ na1fikovai1bulat
872
+ nsbfibd35mcrspc
873
+ myztee-trish123
874
+ myiqwvrkvf1pmiwqbdf4kneq
875
+ mv36hw74fcdub2rk
876
+ musicitislive12345
877
+ mullummul758712
878
+ mrscristinagoncalves
879
+ mrsbuttersworth
880
+ moviedude1122fdd
881
+ mountainman1952
882
+ mothercicket2001
883
+ mostafa@halo1203405600
884
+ morethanicansay
885
+ mono.01.06.1995
886
+ moinomer0632969509
887
+ moi9643179063wow
888
+ mod=billing_core
889
+ mnbvcxzlkjhgfdsa
890
+ mjbalogh-19janu64
891
+ misskris4849004
892
+ missionimpossible
893
+ misha80685562476
894
+ minimonk1997797
895
+ minimicraft-youtube
896
+ milana4772871714
897
+ mikimousemylife
898
+ mifuckeduphentai
899
+ midnite.fantasy
900
+ michaelk-britney6
901
+ michael@gangbang
902
+ mersedesbenz123
903
+ meninadosolhosdedeus
904
+ meb266lavi11ym22
905
+ mdmichener-kaines
906
+ mcc1188391257ad
907
+ mazelaaleksandr
908
+ maxsive23021997
909
+ maximka1234kent
910
+ mauroalessandro
911
+ matheus34518247
912
+ mateusz123456789
913
+ masterofpuppets
914
+ masterimargarita
915
+ mashabogak1234561995
916
+ masha10031981mart
917
+ masha0663655464
918
+ marty_klopfenstein
919
+ marounhajjloveyou
920
+ markus000-lovelybo
921
+ mariarenemivida
922
+ margohamakarevij
923
+ marco.baumstark-5828
924
+ marcelo35641782
925
+ maksmaksim300300
926
+ maimaimottinhyeu
927
+ madinashahmanova
928
+ maddinibiza2004
929
+ madaclioweaph61
930
+ mkjleepyaitorddz
931
+ m1dd2l3n414092002
932
+ m0ynqplxama0yve
933
+ m#xi!rzyvh681=fn
934
+ lvbnhbq1990psrjd
935
+ luvstosuckcocks
936
+ luvbekkiluvbekki
937
+ luvbekkiikkebvul
938
+ luvamami-visacard
939
+ lumpkin-sandman
940
+ lukaslukaslukas1
941
+ lukaslopas860660501
942
+ lubluanutu4326vv1
943
+ ltdjxrfcgktthjv
944
+ lovingirishprincess
945
+ lovethewayyoulie
946
+ lovesyoulovesyou
947
+ losangeleslakers
948
+ loris1-tatjana9
949
+ loosersneverwin
950
+ longlivepakistan
951
+ loki2496-nightwin
952
+ llllllllllllllllll
953
+ lifeisbeautiful
954
+ lfybbkcthuttdbx
955
+ lfif89184833900
956
+ levchenkoaleksey
957
+ leticiaeestrela
958
+ lera10041997sveta
959
+ lena89149404636
960
+ lbublhjrdthwtnby
961
+ lavidaesuncarnava
962
+ lastlight-killyou
963
+ languagepowerboo
964
+ lamismadesiempr
965
+ ladkaringmybells1
966
+ labradorretriever
967
+ l7dg980a43rijfcnr3puk5faj
968
+ ktonerabotaettotest
969
+ ktlybrjdsqgthbjl
970
+ ktjyblidthbl80965137150
971
+ kthrf.czcegthjr
972
+ ksenia1995ksenia1995
973
+ kristyna_samsonova
974
+ kristinakristina
975
+ korolevskii2409
976
+ korolevakrasoti
977
+ kootergirl-kooter11
978
+ kolya1234567890
979
+ kolob@ster720303
980
+ kolechka9qwe12345
981
+ km694nbv45fa8phg
982
+ klocknerklockner
983
+ kklages-slugger
984
+ kjkyjqpeirfybvthekbn
985
+ kiogouniakoui79-saecloub
986
+ kikuchi-1023kiku
987
+ kfhbcfcfyfrbtdyf1
988
+ kensai-athena00
989
+ keepitsimpletwo
990
+ keeperofsecrets
991
+ kawasakikawasaki
992
+ katya89166172604
993
+ katya0932687854
994
+ katerinakaterina
995
+ katerina09091976
996
+ karmapachena49876302
997
+ kapitoshkaivolk111
998
+ kaledinjora2002
999
+ kaeannadhyleantonette
1000
+ justice4allepier
1001
+ joseph31-lindsay
1002
+ `.trim().split(`
1003
+ `))});var ot={};A(ot,{ARGON2ID_MAX_PARAMS:()=>mr,ARGON2ID_PARAMS:()=>pr,PASSWORD_MAX_LENGTH:()=>Vi,PASSWORD_MIN_LENGTH:()=>Gi,assertStrongPassword:()=>Yi,deriveAddressChecksum:()=>Nf,deriveKeyFromPasswordArgon2id:()=>bn,validatePasswordStrength:()=>kn});async function bn(r,e,t=pr){let n=await(0,za.argon2idAsync)(new TextEncoder().encode(r.normalize("NFC")),e,{m:t.memoryKiB,t:t.passes,p:t.parallelism,dkLen:32});try{return await crypto.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["encrypt","decrypt"])}finally{n.fill(0)}}async function Nf(r){let t=new TextEncoder().encode(r.toLowerCase()),n=await crypto.subtle.digest("SHA-256",t);return zf(n).substring(0,16)}function kn(r){let e=typeof r=="string"?r.normalize("NFC"):"",t=[...e],n=t.length,i=e.toLowerCase(),s=[];return n<Gi&&s.push(`Password must be at least ${Gi} characters`),n>Vi&&s.push(`Password must be at most ${Vi} characters`),($i.has(i)||$i.has(i.replace(/[\s._-]+/gu,"")))&&s.push("Password is too common"),n>1&&new Set(t).size===1&&s.push("Password must not repeat a single character"),{valid:s.length===0,feedback:s}}function Yi(r){let{valid:e,feedback:t}=kn(r);if(!e)throw new it(t)}function zf(r){let e=r instanceof Uint8Array?r:new Uint8Array(r),t="";for(let n=0;n<e.byteLength;n++)t+=String.fromCharCode(e[n]);return btoa(t)}var za,pr,mr,Gi,Vi,Re=p(()=>{"use strict";za=require("@noble/hashes/argon2.js");T();Na();pr=Object.freeze({memoryKiB:65536,passes:3,parallelism:4}),mr=Object.freeze({memoryKiB:65536,passes:3,parallelism:4});Gi=15,Vi=256});function Ji(r){return/^0x[a-fA-F0-9]{40}$/.test(r)}function at(r){return r.length<3||r.length>50?!1:/^[a-zA-Z0-9]([a-zA-Z0-9_-]*[a-zA-Z0-9])?$/.test(r)}function Zi(r){let e=r.trim().split(/\s+/);return e.length===12||e.length===24}function xn(r){if(!Ji(r))throw new Error("Invalid Ethereum address format")}function Sn(r){if(!at(r))throw new Error("Username must be 3-50 characters long and contain only letters, numbers, underscores, and hyphens. Must start and end with a letter or number.")}function Ka(r){if(!Zi(r))throw new Error("Invalid mnemonic: must be 12 or 24 words")}function Oa(r){return kn(r).valid}var yr=p(()=>{"use strict";Re()});var es={};A(es,{arrayBufferToBase64Url:()=>fe,base64ToArrayBuffer:()=>Ct,base64UrlDecode:()=>Qi,base64UrlToArrayBuffer:()=>D,safeAtob:()=>gr,safeBtoa:()=>Xi});function D(r){try{let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;e+="=".repeat(t);let n=atob(e),i=new Uint8Array(n.length);for(let s=0;s<n.length;s++)i[s]=n.charCodeAt(s);return i.buffer}catch(e){throw new Error(`Failed to decode base64url string: ${e instanceof Error?e.message:"Invalid format"}`)}}function fe(r){let e=r instanceof Uint8Array?r:new Uint8Array(r),t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ct(r){try{let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t.buffer}catch(e){throw new Error(`Failed to decode base64 string: ${e instanceof Error?e.message:"Invalid format"}`)}}function gr(r){try{let e=r.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;return e+="=".repeat(t),atob(e)}catch(e){throw new Error(`Failed to decode base64 string: ${e instanceof Error?e.message:"Invalid format"}`)}}function Xi(r){try{let e=new TextEncoder().encode(r),t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}catch(e){throw new Error(`Failed to encode string: ${e instanceof Error?e.message:"Invalid input"}`)}}function Qi(r){return D(r)}var pe=p(()=>{"use strict"});var ja={};A(ja,{PRF_INPUT:()=>me,decryptData:()=>ye,derivePrfSessionKey:()=>ct,deriveWalletKey:()=>Bt,encryptData:()=>ze,exportSessionKey:()=>ts,generateChallenge:()=>ve,hashCredentialId:()=>Tt,importSessionKey:()=>rs});async function qa(r,e,t){let n=r.byteLength;if(n!==32)throw new Error(`PRF output must be 32 bytes, got ${n}`);let i=await crypto.subtle.importKey("raw",r,"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:new Uint8Array(32),info:e},i,{name:"AES-GCM",length:256},t,["encrypt","decrypt"])}async function ct(r,e=!1){try{return await qa(r,Kf,e)}catch(t){throw new x("Failed to derive session key from PRF output",t)}}async function Bt(r){try{return await qa(r,Of,!1)}catch(e){throw new x("Failed to derive wallet key from PRF output",e)}}async function ts(r){try{return fe(await crypto.subtle.exportKey("raw",r))}catch(e){throw new x("Failed to export session key",e)}}async function rs(r){try{return await crypto.subtle.importKey("raw",D(r),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}catch(e){throw new x("Failed to import session key",e)}}function ve(){let r=new Uint8Array(32);return crypto.getRandomValues(r),fe(r)}async function ze(r,e){try{let t=crypto.getRandomValues(new Uint8Array(12)),n=new TextEncoder().encode(r),i=await crypto.subtle.encrypt({name:"AES-GCM",iv:t},e,n),s=new Uint8Array(t.length+i.byteLength);s.set(t),s.set(new Uint8Array(i),t.length);let o="";for(let a=0;a<s.length;a++)o+=String.fromCharCode(s[a]);return btoa(o)}catch(t){throw new x("Failed to encrypt data",t)}}async function ye(r,e){try{if(!r||r.length<16)throw new Error("Invalid encrypted data: too small");let t=gr(r),n=new Uint8Array(t.length);for(let a=0;a<t.length;a++)n[a]=t.charCodeAt(a);if(n.length<12)throw new Error("Invalid encrypted data: missing IV");let i=n.slice(0,12),s=n.slice(12);if(s.length===0)throw new Error("Invalid encrypted data: no content");let o=await crypto.subtle.decrypt({name:"AES-GCM",iv:i},e,s);return new TextDecoder().decode(o)}catch(t){throw new x(`Data decryption failed: ${t instanceof Error?t.message:"Unknown error"}`,t)}}async function Tt(r){try{let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`w3pk-cred-id:${r}`));return fe(e)}catch(e){throw new x("Failed to hash credential ID",e)}}var me,Kf,Of,ge=p(()=>{"use strict";T();pe();me=new TextEncoder().encode("w3pk-prf-input-v1"),Kf=new TextEncoder().encode("w3pk-prf-session-key-v1"),Of=new TextEncoder().encode("w3pk-prf-wallet-key-v1")});var En={};A(En,{CredentialStorage:()=>z});var An,vn,z,De=p(()=>{"use strict";T();ge();An="w3pk_credential_",vn="w3pk_credential_index",z=class{constructor(e){if(e)this.storage=e;else if(typeof window<"u"&&window.localStorage)this.storage=window.localStorage;else throw new P("localStorage is not available")}async saveCredential(e){try{let t=await Tt(e.id),n=`${An}${t}`;this.storage.setItem(n,JSON.stringify(e)),await this.addToIndex(e.id)}catch(t){throw new P("Failed to save credential",t)}}async getCredentialById(e){try{let t=await Tt(e),n=`${An}${t}`,i=this.storage.getItem(n);if(!i)return null;let s=JSON.parse(i);return s?.id!==e||typeof s.publicKey!="string"||typeof s.username!="string"||typeof s.ethereumAddress!="string"?null:s}catch(t){throw new P("Failed to retrieve credential",t)}}async getCredentialByUsername(e){try{return(await this.getAllCredentials()).find(n=>n.username===e)||null}catch(t){throw new P("Failed to retrieve credential",t)}}async getCredentialByAddress(e){try{return(await this.getAllCredentials()).find(n=>n.ethereumAddress.toLowerCase()===e.toLowerCase())||null}catch(t){throw new P("Failed to retrieve credential",t)}}async getAllCredentials(){try{let e=await this.getIndex();return(await Promise.all(e.map(async n=>await this.getCredentialById(n)))).filter(n=>n!==null)}catch(e){throw new P("Failed to retrieve credentials",e)}}async userExists(e){return await this.getCredentialByUsername(e)!==null}async updateLastUsed(e){try{let t=await this.getCredentialById(e);t&&(t.lastUsed=new Date().toISOString(),await this.saveCredential(t))}catch(t){throw new P("Failed to update timestamp",t)}}async updateSignatureCounter(e,t){try{let n=await this.getCredentialById(e);n&&(n.signCount=t,n.lastUsed=new Date().toISOString(),await this.saveCredential(n))}catch(n){throw new P("Failed to update signature counter",n)}}async updateCredentialAddress(e,t){try{let n=await this.getCredentialById(e);n&&(n.ethereumAddress=t,n.lastUsed=new Date().toISOString(),await this.saveCredential(n))}catch(n){throw new P("Failed to update credential address",n)}}async deleteCredential(e){try{let t=await Tt(e),n=`${An}${t}`;this.storage.removeItem(n),await this.removeFromIndex(e)}catch(t){throw new P("Failed to delete credential",t)}}async clearAll(){try{let e=await this.getIndex();(await Promise.all(e.map(async n=>await Tt(n)))).forEach(n=>{let i=`${An}${n}`;this.storage.removeItem(i)}),this.storage.removeItem(vn)}catch(e){throw new P("Failed to clear credentials",e)}}async getIndex(){try{let e=this.storage.getItem(vn);return e?JSON.parse(e):[]}catch{return[]}}async addToIndex(e){let t=await this.getIndex();t.includes(e)||(t.push(e),this.storage.setItem(vn,JSON.stringify(t)))}async removeFromIndex(e){let n=(await this.getIndex()).filter(i=>i!==e);this.storage.setItem(vn,JSON.stringify(n))}}});function Pn(r){return r.length>32&&(r[32]&1)!==0}function Rt(r){return r.length>32&&(r[32]&4)!==0}var In=p(()=>{"use strict"});var Wa={};A(Wa,{extractRS:()=>is,parseDerSignature:()=>Cn});function Cn(r){if(r.length<8||r[0]!==48)throw new Error("Invalid DER signature: missing sequence tag");if(r[1]!==r.length-2)throw new Error("Invalid DER signature: sequence length mismatch");let e=2,t=s=>{if(e+2>r.length||r[e]!==2)throw new Error(`Invalid DER signature: missing ${s} integer tag`);let o=r[e+1];if(e+=2,o===0||o>33||e+o>r.length)throw new Error(`Invalid DER signature: bad ${s} length`);let a=r.subarray(e,e+o);if(e+=o,o===33){if(a[0]!==0)throw new Error(`Invalid DER signature: ${s} longer than 32 bytes`);a=a.subarray(1)}let c=new Uint8Array(32);return c.set(a,32-a.length),c},n=t("r"),i=t("s");if(e!==r.length)throw new Error("Invalid DER signature: trailing bytes");return{r:n,s:i}}function is(r){let{r:e,s:t}=Cn(r),n=BigInt("0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"),i=BigInt("0x"+(0,ns.bytesToHex)(t));return i>n/2n&&(i=n-i),{r:"0x"+(0,ns.bytesToHex)(e),s:"0x"+i.toString(16).padStart(64,"0")}}var ns,Bn=p(()=>{"use strict";ns=require("@noble/hashes/utils.js")});var Ha={};A(Ha,{login:()=>wr,verifyAssertion:()=>Tn,verifyAssertionSignature:()=>Rn,verifyClientData:()=>Dn,verifyRpIdHash:()=>Fn});async function wr(r="required"){try{let e=new z,t=ve(),n=[];try{let l=await e.getAllCredentials();l.length>0&&(n=l.map(d=>({id:d.id,type:"public-key",transports:["internal","hybrid","usb","nfc","ble"]})))}catch{}let s={challenge:D(t),rpId:window.location.hostname,userVerification:r,timeout:6e4,extensions:{prf:{eval:{first:me}}}};n.length>0&&(s.allowCredentials=n.map(l=>({id:D(l.id),type:l.type,transports:l.transports})));let o;try{let l=await navigator.credentials.get({publicKey:s});if(!l)throw new Error("Authentication failed - no credential returned");o=l}catch(l){throw l?.name==="NotAllowedError"||l?.message?.toLowerCase().includes("no credentials available")||l?.message?.toLowerCase().includes("no access key")?(await e.getAllCredentials()).length>0?new F("Your passkey is not available on this device. You may need to restore your wallet from a backup, or login on the device where you registered."):new F("No passkey found. Please register first or restore from a backup."):l}let a=await e.getCredentialById(o.id);if(!a)throw new rt(o.id);if(!await Tn(o,a,e,t))throw new Error("Signature verification failed");let u=Rt(new Uint8Array(o.response.authenticatorData))?o.getClientExtensionResults?.().prf?.results?.first:void 0;return{verified:!0,user:{username:a.username,ethereumAddress:a.ethereumAddress,credentialId:a.id},signature:o.response.signature,prfOutput:u}}catch(e){throw e instanceof E?e:new F(e instanceof Error?e.message:"Authentication failed",e)}}async function Tn(r,e,t,n){try{if(!await Rn(r,e.publicKey,n))return!1;let i=new DataView(r.response.authenticatorData).getUint32(33,!1);if(i>0||e.signCount&&e.signCount>0){let s=e.signCount||0;if(i<=s)return console.error(`Authenticator cloning detected! Counter did not increase: stored=${s}, received=${i}`),!1}return await t.updateSignatureCounter(e.id,i),!0}catch(i){return console.error("Signature verification error:",i),!1}}async function Rn(r,e,t){try{if(!Dn(r.response.clientDataJSON,t,"webauthn.get"))return!1;let n=r.response.authenticatorData,i=new Uint8Array(n);if(!Pn(i))return console.error("User presence flag not set"),!1;if(!await Fn(i))return!1;let s=await crypto.subtle.importKey("spki",D(e),{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),o=await crypto.subtle.digest("SHA-256",r.response.clientDataJSON),a=new Uint8Array(n.byteLength+o.byteLength);a.set(i,0),a.set(new Uint8Array(o),n.byteLength);let{r:c,s:u}=Cn(new Uint8Array(r.response.signature)),l=new Uint8Array(64);return l.set(c,0),l.set(u,32),await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},s,l,a)}catch(n){return console.error("Signature verification error:",n),!1}}function Dn(r,e,t){let n;try{n=JSON.parse(new TextDecoder().decode(r))}catch{return console.error("Invalid clientDataJSON"),!1}return n?.type!==t?(console.error("Unexpected clientDataJSON type"),!1):n.challenge!==e?(console.error("Challenge mismatch - possible replay"),!1):n.origin!==window.location.origin?(console.error("Origin mismatch - possible phishing attack"),!1):!0}async function Fn(r){let e=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(window.location.hostname)));return qf(r.slice(0,32),e)?!0:(console.error("RP ID hash mismatch - possible phishing attack"),!1)}function qf(r,e){if(r.length!==e.length)return!1;for(let t=0;t<r.length;t++)if(r[t]!==e[t])return!1;return!0}var br=p(()=>{"use strict";T();De();pe();ge();In();Bn()});var lt={};A(lt,{createWalletFromMnemonic:()=>Sr,deriveWalletFromMnemonic:()=>Ar,generateBIP39Wallet:()=>xr});function xr(){try{let r=kr.ethers.Wallet.createRandom().mnemonic;if(!r)throw new Error("Failed to generate mnemonic");let e=r.phrase;return{address:kr.ethers.HDNodeWallet.fromPhrase(e,void 0,"m/44'/60'/0'/0/0").address,mnemonic:e}}catch(r){throw new g("Wallet generation failed",r)}}function Sr(r){try{if(!r||r.trim().split(/\s+/).length<12)throw new Error("Invalid mnemonic: must be at least 12 words");return kr.ethers.HDNodeWallet.fromPhrase(r.trim(),void 0,"m/44'/60'/0'/0/0")}catch(e){throw new g(`Wallet creation failed: ${e instanceof Error?e.message:"Invalid mnemonic"}`,e)}}function Ar(r,e=0){try{if(!r||r.trim().split(/\s+/).length<12)throw new Error("Invalid mnemonic: must be at least 12 words");if(e<0||!Number.isInteger(e))throw new Error("Index must be a non-negative integer");let t=`m/44'/60'/0'/0/${e}`,n=kr.ethers.HDNodeWallet.fromPhrase(r.trim(),void 0,t);return{address:n.address,privateKey:n.privateKey}}catch(t){throw new g(`HD wallet derivation failed: ${t instanceof Error?t.message:"Unknown error"}`,t)}}var kr,Ee=p(()=>{"use strict";kr=require("ethers");T()});var Ln={};A(Ln,{DEFAULT_MODE:()=>ae,DEFAULT_TAG:()=>H,deriveAddressFromP256PublicKey:()=>ss,deriveIndexFromOriginModeAndTag:()=>_n,getCurrentOrigin:()=>$,getOriginSpecificAddress:()=>te,normalizeOrigin:()=>Fe});function Fe(r){try{let e=new URL(r),t=`${e.protocol}//${e.hostname.toLowerCase()}`,n=e.port;return n&&!(e.protocol==="https:"&&n==="443"||e.protocol==="http:"&&n==="80")&&(t+=`:${n}`),t}catch(e){throw new g(`Invalid origin URL: ${r}`,e)}}async function _n(r,e=ae,t=H){try{let i=`${Fe(r)}:${e}:${t.toUpperCase()}`,o=new TextEncoder().encode(i),a=await crypto.subtle.digest("SHA-256",o);return new DataView(a).getUint32(0,!1)%$f}catch(n){throw new g(`Failed to derive index from origin "${r}", mode "${e}", and tag "${t}"`,n)}}async function te(r,e,t,n){try{let i=t||ae,s=(n||H).toUpperCase(),o=Fe(e),a=await _n(o,i,s),{address:c,privateKey:u}=Ar(r,a),l={address:c,index:a,origin:o,mode:i,tag:s};return i==="YOLO"&&(l.privateKey=u),l}catch(i){throw new g(`Failed to derive origin-specific address for "${e}" with mode "${t||ae}" and tag "${n||H}"`,i)}}function $(){if(typeof window>"u"||!window.location)throw new g("getCurrentOrigin() only works in browser environments");return window.location.origin}async function ss(r){try{let e=D(r),t=await crypto.subtle.importKey("spki",e,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),n=await crypto.subtle.exportKey("jwk",t);if(!n.x||!n.y)throw new Error("Invalid P-256 public key: missing x or y coordinates");let i=D(n.x),s=D(n.y),o=new Uint8Array(64);return o.set(new Uint8Array(i),0),o.set(new Uint8Array(s),32),"0x"+(0,Ya.keccak256)(o).slice(-40)}catch(e){throw new g("Failed to derive address from P-256 public key",e)}}var Ya,ae,H,$f,ut=p(()=>{"use strict";Ee();T();Ya=require("ethers");pe();ae="STANDARD",H="MAIN",$f=2147483647});var ls={};A(ls,{PRF_SECRET_LABEL:()=>cs,assertPrfSecretTag:()=>qn,derivePrfSecret:()=>Pr,evaluatePrf:()=>Ft});async function Ft(r,e,t){let n,i=ve();try{let c={challenge:D(i),rpId:window.location.hostname,userVerification:"required",timeout:6e4,extensions:{prf:{eval:t?{first:r,second:t}:{first:r}}}};e&&(c.allowCredentials=[{id:D(e),type:"public-key",transports:["internal","hybrid","usb","nfc","ble"]}]);let u=await navigator.credentials.get({publicKey:c});if(!u)throw new F("Authentication failed - no credential returned");n=u}catch(c){throw c instanceof F?c:c?.name==="NotAllowedError"?new F("Authentication was cancelled or the passkey is not available on this device.",c):new F(`Passkey authentication failed: ${c instanceof Error?c.message:"Unknown error"}`,c)}let s=n.getClientExtensionResults?.().prf?.results,o=ic(s?.first);if(!o)throw new ee(n.id);let a=t?ic(s?.second):void 0;return{output:o,secondOutput:a,credentialId:n.id,assertion:n,challenge:i}}function ic(r){if(!r)return;let e=ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength).slice().buffer:r.slice(0);return e.byteLength===32?e:void 0}function qn(r){if(typeof r!="string"||r.length===0||r.includes(":"))throw new x("PRF secret tag must be a non-empty string without ':'")}function Yf(r,e,t){if(r.length===0||r.includes(":"))throw new x("PRF secret label must be a non-empty string without ':'");return qn(t),new TextEncoder().encode(`${r}:${e}:${t}`)}async function Pr(r,e,t,n){let i=Yf(r,e,t),s=await crypto.subtle.digest("SHA-256",i),o=await Ft(s,n);try{let a=await crypto.subtle.importKey("raw",o.output,"HKDF",!1,["deriveBits"]),c=await crypto.subtle.deriveBits({name:"HKDF",hash:"SHA-256",salt:Vf,info:i},a,256);return{secret:new Uint8Array(c),credentialId:o.credentialId}}catch(a){throw new x("Failed to derive secret from PRF output",a)}finally{new Uint8Array(o.output).fill(0)}}var cs,Vf,Ir=p(()=>{"use strict";T();pe();ge();cs="w3pk-prf-v1",Vf=new TextEncoder().encode("w3pk-prf-secret-v1")});function Jf(r,e=0){return/iPhone|iPad|iPod/.test(r)||/Macintosh/.test(r)&&e>1?!0:/AppleWebKit/.test(r)&&!/Chrome|Chromium|Android/.test(r)}function Zf(){return navigator.standalone===!0?!0:typeof globalThis.matchMedia=="function"&&globalThis.matchMedia("(display-mode: standalone)").matches}async function jn(){if(typeof navigator>"u"||!Jf(navigator.userAgent??"",navigator.maxTouchPoints??0)||Zf())return!1;try{return!await navigator.storage?.persisted?.()}catch{return!0}}var us=p(()=>{"use strict"});var oc={};A(oc,{SIWE_HEADER:()=>fs,assertSiweDomain:()=>Qf,createSiweMessage:()=>ps,generateSiweNonce:()=>hs,parseSiweMessage:()=>Mt,validateSiweMessage:()=>ms,verifySiweSignature:()=>ys});function hs(r=11){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=new Uint8Array(r);return crypto.getRandomValues(t),Array.from(t).map(n=>e[n%e.length]).join("")}function sc(r){if(r.statement&&Hn.test(r.statement))return"Statement cannot contain line breaks";if(Hn.test(r.domain))return"Domain cannot contain line breaks";if(Hn.test(r.uri))return"URI cannot contain line breaks";if(r.resources?.some(e=>Hn.test(e)))return"Resources cannot contain line breaks"}function ds(r){if(!Xf.test(r))return;let e=new Date(r);return isNaN(e.getTime())?void 0:e}function ps(r){if(!r.domain||!r.address||!r.uri||!r.version||r.chainId===void 0||!r.nonce||!r.issuedAt)throw new Error("Missing required SIWE message fields");if(r.version!=="1")throw new Error('SIWE version must be "1"');if(r.nonce.length<8||!/^[a-zA-Z0-9]+$/.test(r.nonce))throw new Error("Nonce must be at least 8 alphanumeric characters");let e=sc(r);if(e)throw new Error(e);let t=`${r.domain} wants you to sign in with your Ethereum account:
1004
+ `;if(t+=`${r.address}
1005
+ `,t+=`
1006
+ `,r.statement&&(t+=`${r.statement}
1007
+ `),t+=`
1008
+ `,t+=`URI: ${r.uri}
1009
+ `,t+=`Version: ${r.version}
1010
+ `,t+=`Chain ID: ${r.chainId}
1011
+ `,t+=`Nonce: ${r.nonce}
1012
+ `,t+=`Issued At: ${r.issuedAt}`,r.expirationTime&&(t+=`
1013
+ Expiration Time: ${r.expirationTime}`),r.notBefore&&(t+=`
1014
+ Not Before: ${r.notBefore}`),r.requestId&&(t+=`
1015
+ Request ID: ${r.requestId}`),r.resources&&r.resources.length>0){t+=`
1016
+ Resources:`;for(let n of r.resources)t+=`
1017
+ - ${n}`}return t}function Mt(r){let e=r.split(`
1018
+ `);if(e.length<7)throw new Error("Invalid SIWE message: too few lines");let n=e[0].match(/^(.+) wants you to sign in with your Ethereum account:$/);if(!n)throw new Error("Invalid SIWE message: malformed domain line");let i=n[1],s=e[1];if(!s.match(/^0x[a-fA-F0-9]{40}$/))throw new Error("Invalid SIWE message: malformed address");if(e[2]!=="")throw new Error("Invalid SIWE message: expected empty line after address");let o,a="",c="",u=0,l="",d="",h,m,y,w=[],k=3;for(e[k]&&!e[k].startsWith("URI: ")&&(o=e[k],k++,e[k]===""&&k++);k<e.length;k++){let b=e[k];if(b.startsWith("URI: "))a=b.substring(5);else if(b.startsWith("Version: "))c=b.substring(9);else if(b.startsWith("Chain ID: "))u=parseInt(b.substring(10),10);else if(b.startsWith("Nonce: "))l=b.substring(7);else if(b.startsWith("Issued At: "))d=b.substring(11);else if(b.startsWith("Expiration Time: "))h=b.substring(17);else if(b.startsWith("Not Before: "))m=b.substring(12);else if(b.startsWith("Request ID: "))y=b.substring(12);else if(b.startsWith("Resources:")){for(k++;k<e.length&&e[k].startsWith("- ");)w.push(e[k].substring(2)),k++;break}}if(!a||!c||!u||!l||!d)throw new Error("Invalid SIWE message: missing required fields");return{domain:i,address:s,statement:o,uri:a,version:c,chainId:u,nonce:l,issuedAt:d,expirationTime:h,notBefore:m,requestId:y,resources:w.length>0?w:void 0}}function ms(r,e){let t=[];try{let n=typeof r=="string"?Mt(r):r;e?.domain&&n.domain!==e.domain&&t.push(`Domain mismatch: expected "${e.domain}", got "${n.domain}"`),e?.chainId!==void 0&&n.chainId!==e.chainId&&t.push(`Chain ID mismatch: expected ${e.chainId}, got ${n.chainId}`),n.version!=="1"&&t.push(`Invalid version: must be "1", got "${n.version}"`),(n.nonce.length<8||!/^[a-zA-Z0-9]+$/.test(n.nonce))&&t.push("Nonce must be at least 8 alphanumeric characters");let i=sc(n);i&&t.push(i);let s=new Date;if(ds(n.issuedAt)||t.push(`Invalid Issued At date: "${n.issuedAt}"`),n.expirationTime!==void 0){let o=ds(n.expirationTime);o?o<=s&&t.push("Message has expired"):t.push(`Invalid Expiration Time date: "${n.expirationTime}"`)}if(n.notBefore!==void 0){let o=ds(n.notBefore);o?o>s&&t.push("Message is not yet valid (not-before constraint)"):t.push(`Invalid Not Before date: "${n.notBefore}"`)}return{valid:t.length===0,errors:t,parsed:n}}catch(n){return t.push(n.message),{valid:!1,errors:t}}}function Qf(r,e){let{domain:t}=Mt(r),n=new URL(e),i;try{i=new URL(t.includes("://")?t:`${n.protocol}//${t}`)}catch{throw new Error(`Invalid SIWE message domain "${t}"`)}if(i.protocol!==n.protocol||i.host!==n.host)throw new Error(`SIWE message domain "${t}" does not match the current origin "${n.host}"`)}async function ys(r,e,t){try{let{verifyMessage:n}=await import("ethers"),i=n(r,e),s=Mt(r);return i.toLowerCase()!==s.address.toLowerCase()?{valid:!1,error:"Signature does not match address in message"}:t&&i.toLowerCase()!==t.toLowerCase()?{valid:!1,error:"Signature does not match expected address"}:{valid:!0,address:i}}catch(n){return{valid:!1,error:n.message}}}var fs,Hn,Xf,$n=p(()=>{"use strict";fs=" wants you to sign in with your Ethereum account:",Hn=/[\r\n]/,Xf=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/i});var dc={};A(dc,{encodeEIP7702AuthorizationMessage:()=>Br,hashEIP7702AuthorizationMessage:()=>Tr,verifyEIP7702Authorization:()=>Gn});function Br(r,e,t){let n=[r===0n?"0x":(0,re.toBeHex)(r),e.toLowerCase(),t===0n?"0x":(0,re.toBeHex)(t)],i=(0,re.encodeRlp)(n);return(0,re.concat)(["0x05",i])}function Tr(r,e,t){let n=Br(r,e,t);return(0,re.keccak256)(n)}function Gn(r,e,t,n,i){try{let s=Tr(r,e,t),o;return typeof n=="string"?o=re.Signature.from(n):o=n,(0,re.recoverAddress)(s,o).toLowerCase()===i.toLowerCase()}catch{return!1}}var re,ws=p(()=>{"use strict";re=require("ethers")});var ri={};A(ri,{MLKEM_DEFAULT_CONTEXT:()=>Ie,deriveMLKemKeypair:()=>Fr,hpkeKeySchedule:()=>Ec,mlkemDecrypt:()=>ti,mlkemDecryptWithKey:()=>Ps,mlkemEncrypt:()=>ei,mlkemEncryptWithKey:()=>Es});function K(r){r.fill(0)}function Vn(r,e){let t=new Uint8Array(e);for(let n=e-1;n>=0;n--)t[n]=r&255,r>>>=8;return t}function hp(r,e,t){return(0,ne.concatBytes)(Pe.encode("HPKE"),Vn(r,2),Vn(e,2),Vn(t,2))}function _t(r){let e=Array.from(r).map(t=>String.fromCharCode(t)).join("");return btoa(e)}function ht(r){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function pp(r){return(0,ne.hexToBytes)(r.startsWith("0x")?r.slice(2):r)}function Ac(r){return typeof r=="string"?ht(r):r}function vc(r,e,t,n,i,s){let o=(0,ne.concatBytes)(r,e,t,n,i,s,op);try{return(0,As.sha3_256)(o)}finally{K(o)}}function Ec(r,e,t,n,i,s){let o=new Uint8Array(0),a=(m,y,w)=>(0,pt.extract)(r,(0,ne.concatBytes)(kc,e,Pe.encode(y),w),m),c=(m,y,w,k)=>(0,pt.expand)(r,m,(0,ne.concatBytes)(Vn(k,2),kc,e,Pe.encode(y),w),k),u=a(o,"psk_id_hash",o),l=a(o,"info_hash",n),d=(0,ne.concatBytes)(new Uint8Array([dp]),u,l),h=a(t,"secret",o);try{return{key:c(h,"key",d,i),baseNonce:c(h,"base_nonce",d,s)}}finally{K(h)}}async function Zn(r,e){return crypto.subtle.importKey("raw",r,{name:"AES-GCM"},!1,[e])}async function Pc(r,e,t){let{key:n,baseNonce:i}=Ec(Rr.sha256,fp,e,up,32,Jn);try{let s={name:"AES-GCM",iv:i,tagLength:128};if(r==="seal"){let a=await Zn(n,"encrypt");return new Uint8Array(await crypto.subtle.encrypt(s,a,t))}let o=await Zn(n,"decrypt");return new Uint8Array(await crypto.subtle.decrypt(s,o,t))}finally{K(n)}}function mp(r){let e=r.subarray(0,xs),t=r.subarray(xs),n=e.slice(xc,ks);if(!(0,vs.equalBytes)((0,As.sha3_256)(n),e.subarray(ks,ks+32)))throw new Error("Invalid ML-KEM private key: embedded public key hash mismatch");return{skM:e,skX:t,pkM:n,pkX:ft.x25519.getPublicKey(t)}}async function Fr(r,e=Ie){let t=await(0,Xn.createMlKem1024)(),n=typeof r=="string"?pp(r):r,i=(0,pt.extract)(Rr.sha256,n,sp),s=(0,pt.expand)(Rr.sha256,i,Pe.encode(`ml-kem-1024:${e}`),64),o=(0,pt.expand)(Rr.sha256,i,Pe.encode(`x25519:${e}`),Qn);try{let[a,c]=t.deriveKeyPair(s),u=ft.x25519.getPublicKey(o),l={publicKey:(0,ne.concatBytes)(a,u),privateKey:(0,ne.concatBytes)(c,o)};return K(c),l}finally{K(i),K(s),K(o),typeof r=="string"&&K(n)}}async function ei(r,e){let t=await(0,Xn.createMlKem1024)(),n=(Array.isArray(e)?e:[e]).map(Ac);if(n.length===0)throw new Error("At least one public key is required");for(let s of n)if(s.length!==yc)throw new Error(`Invalid public key size: ${s.length} (expected ${yc})`);let i=crypto.getRandomValues(new Uint8Array(Sc));try{let s=crypto.getRandomValues(new Uint8Array(Jn)),o=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:s,tagLength:128},await Zn(i,"encrypt"),Pe.encode(r))),a=[];for(let c of n){let u=c.subarray(0,Yn),l=c.subarray(Yn),d=ft.x25519.utils.randomSecretKey(),h,m,y;try{let w=ft.x25519.getPublicKey(d);h=ft.x25519.getSharedSecret(d,l);let k;[k,m]=t.encap(u),y=vc(m,h,k,w,u,l),a.push({publicKey:_t(c),enc:_t((0,ne.concatBytes)(k,w)),ciphertext:_t(await Pc("seal",y,i))})}finally{K(d),h&&K(h),m&&K(m),y&&K(y)}}return{version:3,recipients:a,encryptedData:_t(o.slice(0,-Dr)),iv:_t(s),authTag:_t(o.slice(-Dr))}}finally{K(i)}}async function ti(r,e){if(r.version!==3)throw new Error(`Unsupported payload version: ${String(r.version)}`);let t=Ac(e);try{return await yp(r,t)}finally{typeof e=="string"&&K(t)}}async function yp(r,e){if(e.length!==gc)throw new Error(`Invalid private key size: ${e.length} (expected ${gc})`);let t=ht(r.encryptedData),n=ht(r.iv),i=ht(r.authTag);if(n.length!==Jn)throw new Error(`Invalid IV size: ${n.length} (expected ${Jn})`);if(i.length!==Dr)throw new Error(`Invalid auth tag size: ${i.length} (expected ${Dr})`);let{skM:s,skX:o,pkM:a,pkX:c}=mp(e),u=(0,ne.concatBytes)(a,c),l=r.recipients.find(I=>(0,vs.equalBytes)(ht(I.publicKey),u));if(!l)throw new Error("Public key not found in recipients list");let d=ht(l.enc),h=ht(l.ciphertext);if(d.length!==wc)throw new Error(`Invalid enc size: ${d.length} (expected ${wc})`);if(h.length!==bc)throw new Error(`Invalid sealed key size: ${h.length} (expected ${bc})`);let m=d.subarray(0,Ss),y=d.subarray(Ss),k=(await(0,Xn.createMlKem1024)()).decap(m,s),b,S,v;try{b=ft.x25519.getSharedSecret(o,y),S=vc(k,b,m,y,a,c),v=await Pc("open",S,h);let I=await crypto.subtle.decrypt({name:"AES-GCM",iv:n,tagLength:128},await Zn(v,"decrypt"),(0,ne.concatBytes)(t,i));return new TextDecoder().decode(I)}finally{K(k),b&&K(b),S&&K(S),v&&K(v)}}async function Es(r,e,t,n=Ie){let i=await Fr(e,n);try{return await ei(r,[i.publicKey,...t])}finally{K(i.privateKey)}}async function Ps(r,e,t=Ie){let n=await Fr(e,t);try{return await ti(r,n.privateKey)}finally{K(n.privateKey)}}var Xn,ft,pt,Rr,As,ne,vs,Ie,Yn,xs,Ss,xc,ks,Qn,yc,gc,wc,Sc,Jn,Dr,bc,Pe,sp,op,ap,cp,lp,kc,up,dp,fp,Lt=p(()=>{"use strict";Xn=require("mlkem"),ft=require("@noble/curves/ed25519.js"),pt=require("@noble/hashes/hkdf.js"),Rr=require("@noble/hashes/sha2.js"),As=require("@noble/hashes/sha3.js"),ne=require("@noble/hashes/utils.js"),vs=require("@noble/curves/utils.js"),Ie="mlkem-v1",Yn=1568,xs=3168,Ss=1568,xc=1536,ks=xc+Yn,Qn=32,yc=Yn+Qn,gc=xs+Qn,wc=Ss+Qn,Sc=32,Jn=12,Dr=16,bc=Sc+Dr,Pe=new TextEncoder,sp=Pe.encode("w3pk-kem-keypair-v3"),op=Pe.encode("w3pk-MLKEM1024-X25519-v3"),ap=65090,cp=1,lp=2,kc=Pe.encode("HPKE-v1"),up=Pe.encode("w3pk-payload-v3"),dp=0;fp=hp(ap,cp,lp)});var Is,Tc=p(()=>{"use strict";Is=["file","qr","phrase"]});var Dc={};A(Dc,{BackupStorage:()=>Mr});var Rc,Mr,Cs=p(()=>{"use strict";Rc="w3pk_backups",Mr=class{constructor(e){this.customStorage=e}get storage(){return this.customStorage?this.customStorage:typeof window<"u"&&window.localStorage?window.localStorage:null}async init(){}async storeBackupMetadata(e){let t=this.readAll().filter(n=>n.id!==e.id);t.push(e),this.writeAll(t)}async getBackupsByAddress(e){return this.readAll().filter(t=>t.ethereumAddress===e)}async getBackupById(e){return this.readAll().find(t=>t.id===e)??null}async deleteBackup(e){this.writeAll(this.readAll().filter(t=>t.id!==e))}async getBackupCountByMethod(e){return this.readAll().filter(t=>t.method===e).length}readAll(){let e=this.storage?.getItem(Rc);return e?JSON.parse(e):[]}writeAll(e){this.storage?.setItem(Rc,JSON.stringify(e))}}});var Ke={};A(Ke,{BackupManager:()=>Bs});var Bs,Oe=p(()=>{"use strict";Tc();Cs();us();Bs=class{constructor(){this.verificationStorageKey="w3pk_backup_verifications";this.storage=new Mr}async getBackupStatus(e){let t=await this.storage.getBackupsByAddress(e),n=await this.detectPasskeySync(),i=[...new Set(t.map(d=>d.method))],s=t.map(d=>d.createdAt).sort().pop(),o=t.filter(d=>d.method!=="phrase").map(d=>({id:d.id,method:d.method,location:"local",createdAt:d.createdAt,deviceFingerprint:d.deviceFingerprint})),a=this.getVerificationStatus(e),c=i.some(d=>Is.includes(d)),u=c?i.includes("prf")?void 0:"prf":"password";return{hasBackup:c,...u&&{recommendedMode:u},evictionRisk:await jn(),lastBackupAt:s,methods:i,passkeySync:n,recoveryPhrase:{verified:a.verified,verificationCount:a.count,encryptedBackups:o},securityScore:this.calculateSecurityScore(n,o,a,c)}}async detectPasskeySync(){if(typeof navigator>"u")return{enabled:!1,deviceCount:0,lastSyncTime:void 0,platform:"unknown"};let e=navigator.userAgent.toLowerCase(),t="unknown";e.includes("mac")||e.includes("iphone")||e.includes("ipad")?t="apple":e.includes("android")?t="google":e.includes("windows")&&(t="microsoft");let n=await this.checkResidentKeySupport();return{enabled:n,deviceCount:1,lastSyncTime:n?new Date().toISOString():void 0,platform:t}}async checkResidentKeySupport(){if(typeof window>"u"||!window.PublicKeyCredential)return!1;try{return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}getVerificationStatus(e){try{let t=typeof localStorage<"u"?localStorage.getItem(this.verificationStorageKey):null;return t?JSON.parse(t)[e.toLowerCase()]||{verified:!1,count:0}:{verified:!1,count:0}}catch{return{verified:!1,count:0}}}async hasBackup(e){return(await this.storage.getBackupsByAddress(e)).some(n=>Is.includes(n.method))}async confirmRecoveryPhraseBackup(e,t){await this.storage.storeBackupMetadata({id:crypto.randomUUID(),ethereumAddress:e,method:"phrase",createdAt:new Date().toISOString(),addressChecksum:t})}markBackupVerified(e){try{let t=typeof localStorage<"u"?localStorage.getItem(this.verificationStorageKey):null,n=t?JSON.parse(t):{},i=e.toLowerCase();n[i]||(n[i]={verified:!1,count:0}),n[i].verified=!0,n[i].count+=1,n[i].lastVerifiedAt=new Date().toISOString(),typeof localStorage<"u"&&localStorage.setItem(this.verificationStorageKey,JSON.stringify(n))}catch(t){console.error("Failed to mark backup as verified:",t)}}calculateSecurityScore(e,t,n,i=!1){let s=0;n?.verified&&(s=10,s+=Math.min(n.count-1,10));let o={passkeyActive:e.enabled?20:0,passkeyMultiDevice:e.deviceCount>1?10:0,phraseVerified:s,encryptedBackup:t.length>0?20:0},a=Object.values(o).reduce((m,y)=>m+y,0),c=i?a:Math.min(a,20),u=[!o.passkeyActive&&"enable passkey sync",!o.passkeyMultiDevice&&"sync your passkey to another device",!o.encryptedBackup&&"create an encrypted backup",o.phraseVerified<20&&(o.phraseVerified?"verify your backup again":"verify your backup")].filter(Boolean).join(", "),l=m=>`Reach ${m}: ${u}`,d,h;return i?c<=20?(d="vulnerable",h=l('"protected" (21+ pts)')):c<=40?(d="protected",h=l('"secured" (41+ pts)')):c<=60?(d="secured",h=l('"fort-knox" (61+ pts)')):(d="fort-knox",h=c<70?l("the maximum (70 pts)"):"Maximum security achieved!"):(d="vulnerable",h="Create a password backup file or confirm your recovery phrase: without a backup that restores without a passkey, losing this device can lose the wallet"),{total:c,breakdown:o,level:d,nextMilestone:h}}}});var we={};A(we,{BackupFileManager:()=>Rs,generatePrfSalt:()=>gp,prfSyncInput:()=>wp,validateBackupFile:()=>Nt});function gp(){return fe(crypto.getRandomValues(new Uint8Array(32)).buffer)}async function wp(r){let e=new Uint8Array(D(r));return crypto.subtle.digest("SHA-256",new Uint8Array([...Nc,...e]))}async function Mc(r,e){try{let t=await crypto.subtle.importKey("raw",r,"HKDF",!1,["deriveKey"]);return await crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:D(e),info:Nc},t,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}catch(t){throw new x("Failed to derive backup key from PRF output",t)}}function Ur(r){throw new Error(`Invalid backup file: ${r}`)}function Ts(r,e){return Number.isInteger(r)&&r>=1&&r<=e}function Uc(r){try{return typeof r=="string"?Ct(r).byteLength:0}catch{return 0}}function Nt(r){(!r||typeof r!="object")&&Ur("not a JSON object");let e=r;if(bp.includes(e.encryptionMethod))throw new nt(e.encryptionMethod);if(e.version!==3)throw new Te(e.version,e.encryptionMethod);if((typeof e.createdAt!="string"||typeof e.encryptedMnemonic!="string")&&Ur("missing required fields"),e.encryptionMethod==="password"){let t=e.passwordEncryption;(!t||t.kdf!=="argon2id"||Uc(t.salt)<16||Uc(t.salt)>64||!Ts(t.memoryKiB,mr.memoryKiB)||!Ts(t.passes,mr.passes)||!Ts(t.parallelism,mr.parallelism)||t.memoryKiB<8*t.parallelism)&&Ur("password backup without valid Argon2id parameters")}else e.encryptionMethod==="prf"?(!e.prfSalt||!e.credential?.id||!e.credential.publicKey)&&Ur("PRF backup without its salt or passkey"):Ur(`unknown encryption method ${e.encryptionMethod}`);return e}async function _c(r){let{Wallet:e}=await import("ethers");try{return e.fromPhrase(r).address}catch(t){throw new x("Decrypted backup is not a valid mnemonic",t)}}function Lc(r){let e=JSON.stringify(r,null,2);return{backupFile:r,json:e,blob:new Blob([e],{type:"application/json"})}}var Nc,bp,Rs,ce=p(()=>{"use strict";Re();ge();T();pe();Nc=new TextEncoder().encode("w3pk-prf-sync-v1");bp=["passkey","hybrid"];Rs=class{async createPasswordBackup(e,t,n,i){Yi(t);let s=crypto.getRandomValues(new Uint8Array(16)),o=await bn(t,s,pr);return Lc({version:3,createdAt:new Date().toISOString(),encryptedMnemonic:await ze(e,o),encryptionMethod:"password",passwordEncryption:{kdf:"argon2id",salt:btoa(String.fromCharCode(...s)),...pr},...n&&{credential:{id:n.id,publicKey:n.publicKey}},...i&&{username:i}})}async createPrfBackup(e,t,n,i,s){let o=await Mc(s,i);return Lc({version:3,createdAt:new Date().toISOString(),encryptedMnemonic:await ze(e,o),encryptionMethod:"prf",credential:{id:t.id,publicKey:t.publicKey},prfSalt:i,username:n})}async restoreWithPrf(e,t){if(Nt(e),e.encryptionMethod!=="prf"||!e.prfSalt)throw new Error("This backup is not a PRF backup.");let n=await Mc(t,e.prfSalt),i=await ye(e.encryptedMnemonic,n);return{mnemonic:i,ethereumAddress:await _c(i)}}async restoreWithPassword(e,t){Nt(e);let n=e.passwordEncryption;if(e.encryptionMethod!=="password"||!n)throw new Error("This backup is not password-protected.");let i=new Uint8Array(Ct(n.salt)),s=await bn(t,i,n),o;try{o=await ye(e.encryptedMnemonic,s)}catch(a){throw new x("Wrong password or corrupted backup",a)}return{mnemonic:o,ethereumAddress:await _c(o)}}async parseBackupFile(e){let t=e instanceof Blob?await e.text():e;return Nt(JSON.parse(t))}createDownloadableBackup(e,t){let n=JSON.stringify(e,null,2),i=new Blob([n],{type:"application/json"}),s=`w3pk-backup-${new Date().toISOString().split("T")[0]}.json`;return{blob:i,filename:t||s}}}});var zc={};A(zc,{authenticateWithPasskey:()=>Fs,promptPasskeySelection:()=>Ds});function kp(r){if(r?.byteLength)try{let e=new TextDecoder("utf-8",{fatal:!0}).decode(r);return at(e)?e:void 0}catch{return}}async function Ds(){try{let r=new z,e=ve(),t=D(e),n=[];try{let l=await r.getAllCredentials();l.length>0&&(n=l.map(d=>({id:d.id,type:"public-key",transports:["internal","hybrid","usb","nfc","ble"]})))}catch{}let i={challenge:t,rpId:window.location.hostname,userVerification:"required",timeout:12e4,extensions:{prf:{eval:{first:me}}}};n.length>0&&(i.allowCredentials=n.map(l=>({id:D(l.id),type:l.type,transports:l.transports})));let s=await navigator.credentials.get({publicKey:i});if(!s)throw new F("No passkey selected. Please select a passkey to continue with sync.");let o=s.id,a=Rt(new Uint8Array(s.response.authenticatorData))?s.getClientExtensionResults?.().prf?.results?.first:void 0,c=kp(s.response.userHandle),u=await r.getCredentialById(o);return u?{credentialId:o,publicKey:u.publicKey,ethereumAddress:u.ethereumAddress,username:u.username,assertion:s,challenge:e,prfOutput:a}:{credentialId:o,publicKey:"",ethereumAddress:void 0,username:c,assertion:s,challenge:e,prfOutput:a}}catch(r){throw r?.name==="NotAllowedError"?new F("Passkey selection was cancelled. Please try again and select your passkey."):r instanceof F?r:new F(`Failed to select passkey: ${r instanceof Error?r.message:"Unknown error"}`,r)}}async function Fs(r){try{let e=ve(),n={challenge:D(e),rpId:window.location.hostname,userVerification:"required",timeout:6e4,allowCredentials:[{id:D(r),type:"public-key",transports:["internal","hybrid","usb","nfc","ble"]}]},i=await navigator.credentials.get({publicKey:n});if(!i)throw new F("Authentication failed - no credential returned");return i}catch(e){throw e?.name==="NotAllowedError"?new F("Authentication was cancelled or the passkey is not available on this device."):new F(`Passkey authentication failed: ${e instanceof Error?e.message:"Unknown error"}`,e)}}var Ms=p(()=>{"use strict";T();De();pe();ge();In();yr()});var Oc=B((E0,Kc)=>{"use strict";Kc.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var qe=B(mt=>{"use strict";var Us,xp=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];mt.getSymbolSize=function(e){if(!e)throw new Error('"version" cannot be null or undefined');if(e<1||e>40)throw new Error('"version" should be in range from 1 to 40');return e*4+17};mt.getSymbolTotalCodewords=function(e){return xp[e]};mt.getBCHDigit=function(r){let e=0;for(;r!==0;)e++,r>>>=1;return e};mt.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');Us=e};mt.isKanjiModeEnabled=function(){return typeof Us<"u"};mt.toSJIS=function(e){return Us(e)}});var ni=B(le=>{"use strict";le.L={bit:1};le.M={bit:0};le.Q={bit:3};le.H={bit:2};function Sp(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return le.L;case"m":case"medium":return le.M;case"q":case"quartile":return le.Q;case"h":case"high":return le.H;default:throw new Error("Unknown EC Level: "+r)}}le.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};le.from=function(e,t){if(le.isValid(e))return e;try{return Sp(e)}catch{return t}}});var Wc=B((C0,jc)=>{"use strict";function qc(){this.buffer=[],this.length=0}qc.prototype={get:function(r){let e=Math.floor(r/8);return(this.buffer[e]>>>7-r%8&1)===1},put:function(r,e){for(let t=0;t<e;t++)this.putBit((r>>>e-t-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(r){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),r&&(this.buffer[e]|=128>>>this.length%8),this.length++}};jc.exports=qc});var $c=B((B0,Hc)=>{"use strict";function _r(r){if(!r||r<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=r,this.data=new Uint8Array(r*r),this.reservedBit=new Uint8Array(r*r)}_r.prototype.set=function(r,e,t,n){let i=r*this.size+e;this.data[i]=t,n&&(this.reservedBit[i]=!0)};_r.prototype.get=function(r,e){return this.data[r*this.size+e]};_r.prototype.xor=function(r,e,t){this.data[r*this.size+e]^=t};_r.prototype.isReserved=function(r,e){return this.reservedBit[r*this.size+e]};Hc.exports=_r});var Gc=B(ii=>{"use strict";var Ap=qe().getSymbolSize;ii.getRowColCoords=function(e){if(e===1)return[];let t=Math.floor(e/7)+2,n=Ap(e),i=n===145?26:Math.ceil((n-13)/(2*t-2))*2,s=[n-7];for(let o=1;o<t-1;o++)s[o]=s[o-1]-i;return s.push(6),s.reverse()};ii.getPositions=function(e){let t=[],n=ii.getRowColCoords(e),i=n.length;for(let s=0;s<i;s++)for(let o=0;o<i;o++)s===0&&o===0||s===0&&o===i-1||s===i-1&&o===0||t.push([n[s],n[o]]);return t}});var Jc=B(Yc=>{"use strict";var vp=qe().getSymbolSize,Vc=7;Yc.getPositions=function(e){let t=vp(e);return[[0,0],[t-Vc,0],[0,t-Vc]]}});var Zc=B(M=>{"use strict";M.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var yt={N1:3,N2:3,N3:40,N4:10};M.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};M.from=function(e){return M.isValid(e)?parseInt(e,10):void 0};M.getPenaltyN1=function(e){let t=e.size,n=0,i=0,s=0,o=null,a=null;for(let c=0;c<t;c++){i=s=0,o=a=null;for(let u=0;u<t;u++){let l=e.get(c,u);l===o?i++:(i>=5&&(n+=yt.N1+(i-5)),o=l,i=1),l=e.get(u,c),l===a?s++:(s>=5&&(n+=yt.N1+(s-5)),a=l,s=1)}i>=5&&(n+=yt.N1+(i-5)),s>=5&&(n+=yt.N1+(s-5))}return n};M.getPenaltyN2=function(e){let t=e.size,n=0;for(let i=0;i<t-1;i++)for(let s=0;s<t-1;s++){let o=e.get(i,s)+e.get(i,s+1)+e.get(i+1,s)+e.get(i+1,s+1);(o===4||o===0)&&n++}return n*yt.N2};M.getPenaltyN3=function(e){let t=e.size,n=0,i=0,s=0;for(let o=0;o<t;o++){i=s=0;for(let a=0;a<t;a++)i=i<<1&2047|e.get(o,a),a>=10&&(i===1488||i===93)&&n++,s=s<<1&2047|e.get(a,o),a>=10&&(s===1488||s===93)&&n++}return n*yt.N3};M.getPenaltyN4=function(e){let t=0,n=e.data.length;for(let s=0;s<n;s++)t+=e.data[s];return Math.abs(Math.ceil(t*100/n/5)-10)*yt.N4};function Ep(r,e,t){switch(r){case M.Patterns.PATTERN000:return(e+t)%2===0;case M.Patterns.PATTERN001:return e%2===0;case M.Patterns.PATTERN010:return t%3===0;case M.Patterns.PATTERN011:return(e+t)%3===0;case M.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(t/3))%2===0;case M.Patterns.PATTERN101:return e*t%2+e*t%3===0;case M.Patterns.PATTERN110:return(e*t%2+e*t%3)%2===0;case M.Patterns.PATTERN111:return(e*t%3+(e+t)%2)%2===0;default:throw new Error("bad maskPattern:"+r)}}M.applyMask=function(e,t){let n=t.size;for(let i=0;i<n;i++)for(let s=0;s<n;s++)t.isReserved(s,i)||t.xor(s,i,Ep(e,s,i))};M.getBestMask=function(e,t){let n=Object.keys(M.Patterns).length,i=0,s=1/0;for(let o=0;o<n;o++){t(o),M.applyMask(o,e);let a=M.getPenaltyN1(e)+M.getPenaltyN2(e)+M.getPenaltyN3(e)+M.getPenaltyN4(e);M.applyMask(o,e),a<s&&(s=a,i=o)}return i}});var Ls=B(_s=>{"use strict";var je=ni(),si=[1,1,1,1,1,1,1,1,1,1,2,2,1,2,2,4,1,2,4,4,2,4,4,4,2,4,6,5,2,4,6,6,2,5,8,8,4,5,8,8,4,5,8,11,4,8,10,11,4,9,12,16,4,9,16,16,6,10,12,18,6,10,17,16,6,11,16,19,6,13,18,21,7,14,21,25,8,16,20,25,8,17,23,25,9,17,23,34,9,18,25,30,10,20,27,32,12,21,29,35,12,23,34,37,12,25,34,40,13,26,35,42,14,28,38,45,15,29,40,48,16,31,43,51,17,33,45,54,18,35,48,57,19,37,51,60,19,38,53,63,20,40,56,66,21,43,59,70,22,45,62,74,24,47,65,77,25,49,68,81],oi=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];_s.getBlocksCount=function(e,t){switch(t){case je.L:return si[(e-1)*4+0];case je.M:return si[(e-1)*4+1];case je.Q:return si[(e-1)*4+2];case je.H:return si[(e-1)*4+3];default:return}};_s.getTotalCodewordsCount=function(e,t){switch(t){case je.L:return oi[(e-1)*4+0];case je.M:return oi[(e-1)*4+1];case je.Q:return oi[(e-1)*4+2];case je.H:return oi[(e-1)*4+3];default:return}}});var Xc=B(ci=>{"use strict";var Lr=new Uint8Array(512),ai=new Uint8Array(256);(function(){let e=1;for(let t=0;t<255;t++)Lr[t]=e,ai[e]=t,e<<=1,e&256&&(e^=285);for(let t=255;t<512;t++)Lr[t]=Lr[t-255]})();ci.log=function(e){if(e<1)throw new Error("log("+e+")");return ai[e]};ci.exp=function(e){return Lr[e]};ci.mul=function(e,t){return e===0||t===0?0:Lr[ai[e]+ai[t]]}});var Qc=B(Nr=>{"use strict";var Ns=Xc();Nr.mul=function(e,t){let n=new Uint8Array(e.length+t.length-1);for(let i=0;i<e.length;i++)for(let s=0;s<t.length;s++)n[i+s]^=Ns.mul(e[i],t[s]);return n};Nr.mod=function(e,t){let n=new Uint8Array(e);for(;n.length-t.length>=0;){let i=n[0];for(let o=0;o<t.length;o++)n[o]^=Ns.mul(t[o],i);let s=0;for(;s<n.length&&n[s]===0;)s++;n=n.slice(s)}return n};Nr.generateECPolynomial=function(e){let t=new Uint8Array([1]);for(let n=0;n<e;n++)t=Nr.mul(t,new Uint8Array([1,Ns.exp(n)]));return t}});var rl=B((_0,tl)=>{"use strict";var el=Qc();function zs(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}zs.prototype.initialize=function(e){this.degree=e,this.genPoly=el.generateECPolynomial(this.degree)};zs.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let t=new Uint8Array(e.length+this.degree);t.set(e);let n=el.mod(t,this.genPoly),i=this.degree-n.length;if(i>0){let s=new Uint8Array(this.degree);return s.set(n,i),s}return n};tl.exports=zs});var Ks=B(nl=>{"use strict";nl.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var Os=B(Me=>{"use strict";var il="[0-9]+",Pp="[A-Z $%*+\\-./:]+",zr="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";zr=zr.replace(/u/g,"\\u");var Ip="(?:(?![A-Z0-9 $%*+\\-./:]|"+zr+`)(?:.|[\r
1019
+ ]))+`;Me.KANJI=new RegExp(zr,"g");Me.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");Me.BYTE=new RegExp(Ip,"g");Me.NUMERIC=new RegExp(il,"g");Me.ALPHANUMERIC=new RegExp(Pp,"g");var Cp=new RegExp("^"+zr+"$"),Bp=new RegExp("^"+il+"$"),Tp=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");Me.testKanji=function(e){return Cp.test(e)};Me.testNumeric=function(e){return Bp.test(e)};Me.testAlphanumeric=function(e){return Tp.test(e)}});var We=B(O=>{"use strict";var Rp=Ks(),qs=Os();O.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};O.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};O.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};O.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};O.MIXED={bit:-1};O.getCharCountIndicator=function(e,t){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Rp.isValid(t))throw new Error("Invalid version: "+t);return t>=1&&t<10?e.ccBits[0]:t<27?e.ccBits[1]:e.ccBits[2]};O.getBestModeForData=function(e){return qs.testNumeric(e)?O.NUMERIC:qs.testAlphanumeric(e)?O.ALPHANUMERIC:qs.testKanji(e)?O.KANJI:O.BYTE};O.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};O.isValid=function(e){return e&&e.bit&&e.ccBits};function Dp(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"numeric":return O.NUMERIC;case"alphanumeric":return O.ALPHANUMERIC;case"kanji":return O.KANJI;case"byte":return O.BYTE;default:throw new Error("Unknown mode: "+r)}}O.from=function(e,t){if(O.isValid(e))return e;try{return Dp(e)}catch{return t}}});var ll=B(gt=>{"use strict";var li=qe(),Fp=Ls(),sl=ni(),He=We(),js=Ks(),al=7973,ol=li.getBCHDigit(al);function Mp(r,e,t){for(let n=1;n<=40;n++)if(e<=gt.getCapacity(n,t,r))return n}function cl(r,e){return He.getCharCountIndicator(r,e)+4}function Up(r,e){let t=0;return r.forEach(function(n){let i=cl(n.mode,e);t+=i+n.getBitsLength()}),t}function _p(r,e){for(let t=1;t<=40;t++)if(Up(r,t)<=gt.getCapacity(t,e,He.MIXED))return t}gt.from=function(e,t){return js.isValid(e)?parseInt(e,10):t};gt.getCapacity=function(e,t,n){if(!js.isValid(e))throw new Error("Invalid QR Code version");typeof n>"u"&&(n=He.BYTE);let i=li.getSymbolTotalCodewords(e),s=Fp.getTotalCodewordsCount(e,t),o=(i-s)*8;if(n===He.MIXED)return o;let a=o-cl(n,e);switch(n){case He.NUMERIC:return Math.floor(a/10*3);case He.ALPHANUMERIC:return Math.floor(a/11*2);case He.KANJI:return Math.floor(a/13);case He.BYTE:default:return Math.floor(a/8)}};gt.getBestVersionForData=function(e,t){let n,i=sl.from(t,sl.M);if(Array.isArray(e)){if(e.length>1)return _p(e,i);if(e.length===0)return 1;n=e[0]}else n=e;return Mp(n.mode,n.getLength(),i)};gt.getEncodedBits=function(e){if(!js.isValid(e)||e<7)throw new Error("Invalid QR Code version");let t=e<<12;for(;li.getBCHDigit(t)-ol>=0;)t^=al<<li.getBCHDigit(t)-ol;return e<<12|t}});var fl=B(hl=>{"use strict";var Ws=qe(),dl=1335,Lp=21522,ul=Ws.getBCHDigit(dl);hl.getEncodedBits=function(e,t){let n=e.bit<<3|t,i=n<<10;for(;Ws.getBCHDigit(i)-ul>=0;)i^=dl<<Ws.getBCHDigit(i)-ul;return(n<<10|i)^Lp}});var ml=B((q0,pl)=>{"use strict";var Np=We();function zt(r){this.mode=Np.NUMERIC,this.data=r.toString()}zt.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};zt.prototype.getLength=function(){return this.data.length};zt.prototype.getBitsLength=function(){return zt.getBitsLength(this.data.length)};zt.prototype.write=function(e){let t,n,i;for(t=0;t+3<=this.data.length;t+=3)n=this.data.substr(t,3),i=parseInt(n,10),e.put(i,10);let s=this.data.length-t;s>0&&(n=this.data.substr(t),i=parseInt(n,10),e.put(i,s*3+1))};pl.exports=zt});var gl=B((j0,yl)=>{"use strict";var zp=We(),Hs=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function Kt(r){this.mode=zp.ALPHANUMERIC,this.data=r}Kt.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};Kt.prototype.getLength=function(){return this.data.length};Kt.prototype.getBitsLength=function(){return Kt.getBitsLength(this.data.length)};Kt.prototype.write=function(e){let t;for(t=0;t+2<=this.data.length;t+=2){let n=Hs.indexOf(this.data[t])*45;n+=Hs.indexOf(this.data[t+1]),e.put(n,11)}this.data.length%2&&e.put(Hs.indexOf(this.data[t]),6)};yl.exports=Kt});var bl=B((W0,wl)=>{"use strict";var Kp=We();function Ot(r){this.mode=Kp.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}Ot.getBitsLength=function(e){return e*8};Ot.prototype.getLength=function(){return this.data.length};Ot.prototype.getBitsLength=function(){return Ot.getBitsLength(this.data.length)};Ot.prototype.write=function(r){for(let e=0,t=this.data.length;e<t;e++)r.put(this.data[e],8)};wl.exports=Ot});var xl=B((H0,kl)=>{"use strict";var Op=We(),qp=qe();function qt(r){this.mode=Op.KANJI,this.data=r}qt.getBitsLength=function(e){return e*13};qt.prototype.getLength=function(){return this.data.length};qt.prototype.getBitsLength=function(){return qt.getBitsLength(this.data.length)};qt.prototype.write=function(r){let e;for(e=0;e<this.data.length;e++){let t=qp.toSJIS(this.data[e]);if(t>=33088&&t<=40956)t-=33088;else if(t>=57408&&t<=60351)t-=49472;else throw new Error("Invalid SJIS character: "+this.data[e]+`
1020
+ Make sure your charset is UTF-8`);t=(t>>>8&255)*192+(t&255),r.put(t,13)}};kl.exports=qt});var Sl=B(($0,$s)=>{"use strict";var Kr={single_source_shortest_paths:function(r,e,t){var n={},i={};i[e]=0;var s=Kr.PriorityQueue.make();s.push(e,0);for(var o,a,c,u,l,d,h,m,y;!s.empty();){o=s.pop(),a=o.value,u=o.cost,l=r[a]||{};for(c in l)l.hasOwnProperty(c)&&(d=l[c],h=u+d,m=i[c],y=typeof i[c]>"u",(y||m>h)&&(i[c]=h,s.push(c,h),n[c]=a))}if(typeof t<"u"&&typeof i[t]>"u"){var w=["Could not find a path from ",e," to ",t,"."].join("");throw new Error(w)}return n},extract_shortest_path_from_predecessor_list:function(r,e){for(var t=[],n=e,i;n;)t.push(n),i=r[n],n=r[n];return t.reverse(),t},find_path:function(r,e,t){var n=Kr.single_source_shortest_paths(r,e,t);return Kr.extract_shortest_path_from_predecessor_list(n,t)},PriorityQueue:{make:function(r){var e=Kr.PriorityQueue,t={},n;r=r||{};for(n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);return t.queue=[],t.sorter=r.sorter||e.default_sorter,t},default_sorter:function(r,e){return r.cost-e.cost},push:function(r,e){var t={value:r,cost:e};this.queue.push(t),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};typeof $s<"u"&&($s.exports=Kr)});var Tl=B(jt=>{"use strict";var C=We(),El=ml(),Pl=gl(),Il=bl(),Cl=xl(),Or=Os(),ui=qe(),jp=Sl();function Al(r){return unescape(encodeURIComponent(r)).length}function qr(r,e,t){let n=[],i;for(;(i=r.exec(t))!==null;)n.push({data:i[0],index:i.index,mode:e,length:i[0].length});return n}function Bl(r){let e=qr(Or.NUMERIC,C.NUMERIC,r),t=qr(Or.ALPHANUMERIC,C.ALPHANUMERIC,r),n,i;return ui.isKanjiModeEnabled()?(n=qr(Or.BYTE,C.BYTE,r),i=qr(Or.KANJI,C.KANJI,r)):(n=qr(Or.BYTE_KANJI,C.BYTE,r),i=[]),e.concat(t,n,i).sort(function(o,a){return o.index-a.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function Gs(r,e){switch(e){case C.NUMERIC:return El.getBitsLength(r);case C.ALPHANUMERIC:return Pl.getBitsLength(r);case C.KANJI:return Cl.getBitsLength(r);case C.BYTE:return Il.getBitsLength(r)}}function Wp(r){return r.reduce(function(e,t){let n=e.length-1>=0?e[e.length-1]:null;return n&&n.mode===t.mode?(e[e.length-1].data+=t.data,e):(e.push(t),e)},[])}function Hp(r){let e=[];for(let t=0;t<r.length;t++){let n=r[t];switch(n.mode){case C.NUMERIC:e.push([n,{data:n.data,mode:C.ALPHANUMERIC,length:n.length},{data:n.data,mode:C.BYTE,length:n.length}]);break;case C.ALPHANUMERIC:e.push([n,{data:n.data,mode:C.BYTE,length:n.length}]);break;case C.KANJI:e.push([n,{data:n.data,mode:C.BYTE,length:Al(n.data)}]);break;case C.BYTE:e.push([{data:n.data,mode:C.BYTE,length:Al(n.data)}])}}return e}function $p(r,e){let t={},n={start:{}},i=["start"];for(let s=0;s<r.length;s++){let o=r[s],a=[];for(let c=0;c<o.length;c++){let u=o[c],l=""+s+c;a.push(l),t[l]={node:u,lastCount:0},n[l]={};for(let d=0;d<i.length;d++){let h=i[d];t[h]&&t[h].node.mode===u.mode?(n[h][l]=Gs(t[h].lastCount+u.length,u.mode)-Gs(t[h].lastCount,u.mode),t[h].lastCount+=u.length):(t[h]&&(t[h].lastCount=u.length),n[h][l]=Gs(u.length,u.mode)+4+C.getCharCountIndicator(u.mode,e))}}i=a}for(let s=0;s<i.length;s++)n[i[s]].end=0;return{map:n,table:t}}function vl(r,e){let t,n=C.getBestModeForData(r);if(t=C.from(e,n),t!==C.BYTE&&t.bit<n.bit)throw new Error('"'+r+'" cannot be encoded with mode '+C.toString(t)+`.
1021
+ Suggested mode is: `+C.toString(n));switch(t===C.KANJI&&!ui.isKanjiModeEnabled()&&(t=C.BYTE),t){case C.NUMERIC:return new El(r);case C.ALPHANUMERIC:return new Pl(r);case C.KANJI:return new Cl(r);case C.BYTE:return new Il(r)}}jt.fromArray=function(e){return e.reduce(function(t,n){return typeof n=="string"?t.push(vl(n,null)):n.data&&t.push(vl(n.data,n.mode)),t},[])};jt.fromString=function(e,t){let n=Bl(e,ui.isKanjiModeEnabled()),i=Hp(n),s=$p(i,t),o=jp.find_path(s.map,"start","end"),a=[];for(let c=1;c<o.length-1;c++)a.push(s.table[o[c]].node);return jt.fromArray(Wp(a))};jt.rawSplit=function(e){return jt.fromArray(Bl(e,ui.isKanjiModeEnabled()))}});var Dl=B(Rl=>{"use strict";var hi=qe(),Vs=ni(),Gp=Wc(),Vp=$c(),Yp=Gc(),Jp=Jc(),Zs=Zc(),Xs=Ls(),Zp=rl(),di=ll(),Xp=fl(),Qp=We(),Ys=Tl();function em(r,e){let t=r.size,n=Jp.getPositions(e);for(let i=0;i<n.length;i++){let s=n[i][0],o=n[i][1];for(let a=-1;a<=7;a++)if(!(s+a<=-1||t<=s+a))for(let c=-1;c<=7;c++)o+c<=-1||t<=o+c||(a>=0&&a<=6&&(c===0||c===6)||c>=0&&c<=6&&(a===0||a===6)||a>=2&&a<=4&&c>=2&&c<=4?r.set(s+a,o+c,!0,!0):r.set(s+a,o+c,!1,!0))}}function tm(r){let e=r.size;for(let t=8;t<e-8;t++){let n=t%2===0;r.set(t,6,n,!0),r.set(6,t,n,!0)}}function rm(r,e){let t=Yp.getPositions(e);for(let n=0;n<t.length;n++){let i=t[n][0],s=t[n][1];for(let o=-2;o<=2;o++)for(let a=-2;a<=2;a++)o===-2||o===2||a===-2||a===2||o===0&&a===0?r.set(i+o,s+a,!0,!0):r.set(i+o,s+a,!1,!0)}}function nm(r,e){let t=r.size,n=di.getEncodedBits(e),i,s,o;for(let a=0;a<18;a++)i=Math.floor(a/3),s=a%3+t-8-3,o=(n>>a&1)===1,r.set(i,s,o,!0),r.set(s,i,o,!0)}function Js(r,e,t){let n=r.size,i=Xp.getEncodedBits(e,t),s,o;for(s=0;s<15;s++)o=(i>>s&1)===1,s<6?r.set(s,8,o,!0):s<8?r.set(s+1,8,o,!0):r.set(n-15+s,8,o,!0),s<8?r.set(8,n-s-1,o,!0):s<9?r.set(8,15-s-1+1,o,!0):r.set(8,15-s-1,o,!0);r.set(n-8,8,1,!0)}function im(r,e){let t=r.size,n=-1,i=t-1,s=7,o=0;for(let a=t-1;a>0;a-=2)for(a===6&&a--;;){for(let c=0;c<2;c++)if(!r.isReserved(i,a-c)){let u=!1;o<e.length&&(u=(e[o]>>>s&1)===1),r.set(i,a-c,u),s--,s===-1&&(o++,s=7)}if(i+=n,i<0||t<=i){i-=n,n=-n;break}}}function sm(r,e,t){let n=new Gp;t.forEach(function(c){n.put(c.mode.bit,4),n.put(c.getLength(),Qp.getCharCountIndicator(c.mode,r)),c.write(n)});let i=hi.getSymbolTotalCodewords(r),s=Xs.getTotalCodewordsCount(r,e),o=(i-s)*8;for(n.getLengthInBits()+4<=o&&n.put(0,4);n.getLengthInBits()%8!==0;)n.putBit(0);let a=(o-n.getLengthInBits())/8;for(let c=0;c<a;c++)n.put(c%2?17:236,8);return om(n,r,e)}function om(r,e,t){let n=hi.getSymbolTotalCodewords(e),i=Xs.getTotalCodewordsCount(e,t),s=n-i,o=Xs.getBlocksCount(e,t),a=n%o,c=o-a,u=Math.floor(n/o),l=Math.floor(s/o),d=l+1,h=u-l,m=new Zp(h),y=0,w=new Array(o),k=new Array(o),b=0,S=new Uint8Array(r.buffer);for(let L=0;L<o;L++){let j=L<c?l:d;w[L]=S.slice(y,y+j),k[L]=m.encode(w[L]),y+=j,b=Math.max(b,j)}let v=new Uint8Array(n),I=0,U,q;for(U=0;U<b;U++)for(q=0;q<o;q++)U<w[q].length&&(v[I++]=w[q][U]);for(U=0;U<h;U++)for(q=0;q<o;q++)v[I++]=k[q][U];return v}function am(r,e,t,n){let i;if(Array.isArray(r))i=Ys.fromArray(r);else if(typeof r=="string"){let u=e;if(!u){let l=Ys.rawSplit(r);u=di.getBestVersionForData(l,t)}i=Ys.fromString(r,u||40)}else throw new Error("Invalid data");let s=di.getBestVersionForData(i,t);if(!s)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=s;else if(e<s)throw new Error(`
5
1022
  The chosen QR Code version cannot contain this amount of data.
6
- Minimum version required to store current data is: `+i+`.
7
- `);let o=Yf(e,t,s),a=Vn.getSymbolSize(e),c=new Lf(a);return $f(c,e),Hf(c),qf(c,e),Ii(c,t,0),e>=7&&Vf(c,e),Gf(c,o),isNaN(n)&&(n=Bi.getBestMask(c,Ii.bind(null,c,t))),Bi.applyMask(n,c),Ii(c,t,n),{modules:c,version:e,errorCorrectionLevel:t,maskPattern:n,segments:s}}Lc.create=function(e,t){if(typeof e>"u"||e==="")throw new Error("No input text");let n=Ci.M,s,i;return typeof t<"u"&&(n=Ci.from(t.errorCorrectionLevel,Ci.M),s=qn.from(t.version),i=Bi.from(t.maskPattern),t.toSJISFunc&&Vn.setToSJISFunction(t.toSJISFunc)),Jf(e,s,n,i)}});var Ri=C(ut=>{"use strict";function Kc(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let e=r.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+r);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(n){return[n,n]}))),e.length===6&&e.push("F","F");let t=parseInt(e.join(""),16);return{r:t>>24&255,g:t>>16&255,b:t>>8&255,a:t&255,hex:"#"+e.slice(0,6).join("")}}ut.getOptions=function(e){e||(e={}),e.color||(e.color={});let t=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,n=e.width&&e.width>=21?e.width:void 0,s=e.scale||4;return{width:n,scale:n?4:s,margin:t,color:{dark:Kc(e.color.dark||"#000000ff"),light:Kc(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};ut.getScale=function(e,t){return t.width&&t.width>=e+t.margin*2?t.width/(e+t.margin*2):t.scale};ut.getImageWidth=function(e,t){let n=ut.getScale(e,t);return Math.floor((e+t.margin*2)*n)};ut.qrToImageData=function(e,t,n){let s=t.modules.size,i=t.modules.data,o=ut.getScale(s,n),a=Math.floor((s+n.margin*2)*o),c=n.margin*o,l=[n.color.light,n.color.dark];for(let u=0;u<a;u++)for(let d=0;d<a;d++){let h=(u*a+d)*4,m=n.color.light;if(u>=c&&d>=c&&u<a-c&&d<a-c){let y=Math.floor((u-c)/o),w=Math.floor((d-c)/o);m=l[i[y*s+w]?1:0]}e[h++]=m.r,e[h++]=m.g,e[h++]=m.b,e[h]=m.a}}});var Oc=C(Gn=>{"use strict";var Di=Ri();function Qf(r,e,t){r.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=t,e.width=t,e.style.height=t+"px",e.style.width=t+"px"}function Xf(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Gn.render=function(e,t,n){let s=n,i=t;typeof s>"u"&&(!t||!t.getContext)&&(s=t,t=void 0),t||(i=Xf()),s=Di.getOptions(s);let o=Di.getImageWidth(e.modules.size,s),a=i.getContext("2d"),c=a.createImageData(o,o);return Di.qrToImageData(c.data,e,s),Qf(a,i,o),a.putImageData(c,0,0),i};Gn.renderToDataURL=function(e,t,n){let s=n;typeof s>"u"&&(!t||!t.getContext)&&(s=t,t=void 0),s||(s={});let i=Gn.render(e,t,s),o=s.type||"image/png",a=s.rendererOpts||{};return i.toDataURL(o,a.quality)}});var $c=C(Wc=>{"use strict";var Zf=Ri();function zc(r,e){let t=r.a/255,n=e+'="'+r.hex+'"';return t<1?n+" "+e+'-opacity="'+t.toFixed(2).slice(1)+'"':n}function Fi(r,e,t){let n=r+e;return typeof t<"u"&&(n+=" "+t),n}function ep(r,e,t){let n="",s=0,i=!1,o=0;for(let a=0;a<r.length;a++){let c=Math.floor(a%e),l=Math.floor(a/e);!c&&!i&&(i=!0),r[a]?(o++,a>0&&c>0&&r[a-1]||(n+=i?Fi("M",c+t,.5+l+t):Fi("m",s,0),s=0,i=!1),c+1<e&&r[a+1]||(n+=Fi("h",o),o=0)):s++}return n}Wc.render=function(e,t,n){let s=Zf.getOptions(t),i=e.modules.size,o=e.modules.data,a=i+s.margin*2,c=s.color.light.a?"<path "+zc(s.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",l="<path "+zc(s.color.dark,"stroke")+' d="'+ep(o,i,s.margin)+'"/>',u='viewBox="0 0 '+a+" "+a+'"',h='<svg xmlns="http://www.w3.org/2000/svg" '+(s.width?'width="'+s.width+'" height="'+s.width+'" ':"")+u+' shape-rendering="crispEdges">'+c+l+`</svg>
8
- `;return typeof n=="function"&&n(null,h),h}});var Fr=C(Dr=>{"use strict";var tp=Ga(),Mi=_c(),Hc=Oc(),rp=$c();function Ui(r,e,t,n,s){let i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!tp())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(s=t,t=e,e=n=void 0):o===3&&(e.getContext&&typeof s>"u"?(s=n,n=void 0):(s=n,n=t,t=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(t=e,e=n=void 0):o===2&&!e.getContext&&(n=t,t=e,e=void 0),new Promise(function(c,l){try{let u=Mi.create(t,n);c(r(u,e,n))}catch(u){l(u)}})}try{let c=Mi.create(t,n);s(null,r(c,e,n))}catch(c){s(c)}}Dr.create=Mi.create;Dr.toCanvas=Ui.bind(null,Hc.render);Dr.toDataURL=Ui.bind(null,Hc.renderToDataURL);Dr.toString=Ui.bind(null,function(r,e,t){return rp.render(r,t)})});var Ut,Ni=p(()=>{"use strict";Ke();Ut=class{async createQRBackup(e,t,n={}){let s=n.errorCorrection||"H",i;if(n.password){let l=crypto.getRandomValues(new Uint8Array(32)),u=await ot(e,n.password,l);i={version:1,type:"encrypted",data:u.encrypted,iv:u.iv,salt:u.salt,iterations:u.iterations,checksum:await V(t)}}else i={version:1,type:"plain",data:e,checksum:await V(t)};let o=JSON.stringify(i),a=await this.generateQRCode(o,s),c=this.getInstructions(t,!!n.password);return{qrCodeDataURL:a,rawData:o,instructions:c}}async generateQRCode(e,t){try{return await(await Promise.resolve().then(()=>z(Fr()))).default.toDataURL(e,{errorCorrectionLevel:t,width:512,margin:2})}catch{return this.createFallbackQRDataURL(e)}}createFallbackQRDataURL(e){if(typeof document>"u")return`data:text/plain;base64,${Buffer.from(e).toString("base64")}`;let t=document.createElement("canvas");t.width=512,t.height=512;let n=t.getContext("2d");if(!n)throw new Error("Canvas not supported");n.fillStyle="white",n.fillRect(0,0,512,512),n.fillStyle="black",n.font="12px monospace",n.textAlign="center",n.textBaseline="middle";let s=this.wrapText(e,50),i=14,o=256-s.length*i/2;return s.forEach((a,c)=>{n.fillText(a,256,o+c*i)}),n.font="bold 16px sans-serif",n.fillText('Install "qrcode" package for QR codes',256,480),t.toDataURL("image/png")}wrapText(e,t){let n=[];for(let s=0;s<e.length;s+=t)n.push(e.substring(s,s+t));return n}getInstructions(e,t){return`
9
- W3PK QR CODE BACKUP
10
- ==================
11
-
12
- Ethereum Address: ${e}
13
- Backup Date: ${new Date().toISOString()}
14
- Type: ${t?"Encrypted":"Plain"}
15
-
16
- STORAGE INSTRUCTIONS:
17
- --------------------
18
-
19
- \u{1F4F8} Print this QR code and store securely:
20
- \u2713 Safe deposit box
21
- \u2713 Home safe
22
- \u2713 Trusted family member
23
- \u2713 Multiple physical locations
24
-
25
- \u26A0\uFE0F DO NOT:
26
- \u2717 Store digitally (screenshot/photo)
27
- \u2717 Upload to cloud
28
- \u2717 Email or message
29
- \u2717 Share publicly
30
-
31
- RECOVERY STEPS:
32
- --------------
33
-
34
- 1. Scan QR code with your phone camera or QR scanner app
35
-
36
- 2. Import the scanned data to w3pk recovery page
37
-
38
- 3. ${t?"Enter your backup password":"No password needed (plain backup)"}
39
-
40
- 4. Wallet will be restored
41
-
42
- SECURITY NOTES:
43
- --------------
44
-
45
- ${t?`
46
- \u2713 This QR code is ENCRYPTED
47
- \u2713 Password required to decrypt
48
- \u2713 Safe to store in multiple locations
49
- \u2713 Share with trusted family (they can't access without password)
50
- `:`
51
- \u26A0\uFE0F This QR code is NOT ENCRYPTED
52
- \u26A0\uFE0F Anyone with access can recover your wallet
53
- \u26A0\uFE0F Store with maximum security
54
- \u26A0\uFE0F Do not photograph or copy
55
- `}
56
-
57
- ERROR CORRECTION:
58
- ----------------
59
-
60
- This QR code has HIGH error correction (30% damage tolerance)
61
- - Can survive partial damage
62
- - Can handle folding/creasing
63
- - Ensure good print quality
64
-
65
- VERIFICATION:
66
- ------------
67
-
68
- Address checksum is embedded in QR code
69
- After scanning, verify address matches: ${e}
70
-
71
- ALTERNATIVE RECOVERY:
72
- -------------------
73
-
74
- If QR code is lost/damaged, you can still recover using:
75
- - Encrypted backup file
76
- - Social recovery
77
- - Passkey sync
78
- - Manual mnemonic entry (if you wrote down the words)
79
-
80
- ---
81
-
82
- Generated by w3pk Recovery System
83
- https://docs.w3pk.org/recovery
84
- `}async restoreFromQR(e,t){let n=JSON.parse(e);if(n.version!==1)throw new Error("Unsupported QR backup version");let s;if(n.type==="encrypted"){if(!t)throw new Error("Password required for encrypted QR backup");let{decryptWithPassword:c}=await Promise.resolve().then(()=>(Ke(),hi));s=await c(n.data,t,n.salt,n.iv,n.iterations)}else if(n.type==="plain")s=n.data;else throw new Error("Unknown QR backup type");let{Wallet:i}=await import("ethers"),o=i.fromPhrase(s);if(await V(o.address)!==n.checksum)throw new Error("Address checksum mismatch - corrupted QR or wrong password");return{mnemonic:s,ethereumAddress:o.address}}}});function np(){let r=new Uint8Array(1);return crypto.getRandomValues(r),r[0]}function jn(r,e,t){if(e>t)throw new Error("Threshold cannot be greater than total shares");if(e<2)throw new Error("Threshold must be at least 2");if(t>255)throw new Error("Cannot create more than 255 shares");let n=[];for(let s=0;s<t;s++)n[s]=new Uint8Array(r.length+1),n[s][0]=s+1;for(let s=0;s<r.length;s++){let o=[r[s]];for(let a=1;a<e;a++)o.push(np());for(let a=0;a<t;a++){let c=a+1,l=Yn.evaluatePolynomial(o,c);n[a][s+1]=l}}return n}function Jn(r,e){if(r.length<e)throw new Error(`Need at least ${e} shares to recover secret, got ${r.length}`);let t=r.slice(0,e),n=t[0].length;for(let o of t)if(o.length!==n)throw new Error("All shares must have the same length");let s=n-1,i=new Uint8Array(s);for(let o=0;o<s;o++){let a=[];for(let c of t)a.push({x:c[0],y:c[o+1]});i[o]=Yn.interpolate(a)}return i}function Qn(r){return new TextEncoder().encode(r)}function Xn(r){return new TextDecoder().decode(r)}function Zn(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function es(r){let e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2)e[t/2]=parseInt(r.substring(t,t+2),16);return e}var He,Yn,ts=p(()=>{"use strict";He=class He{static multiply(e,t){return e===0||t===0?0:this.EXP_TABLE[(this.LOG_TABLE[e]+this.LOG_TABLE[t])%255]}static divide(e,t){if(t===0)throw new Error("Division by zero in GF(256)");return e===0?0:this.EXP_TABLE[(this.LOG_TABLE[e]-this.LOG_TABLE[t]+255)%255]}static add(e,t){return e^t}static evaluatePolynomial(e,t){let n=0;for(let s=e.length-1;s>=0;s--)n=this.add(this.multiply(n,t),e[s]);return n}static interpolate(e){let t=0;for(let n=0;n<e.length;n++){let s=e[n].y,i=1;for(let o=0;o<e.length;o++)n!==o&&(s=this.multiply(s,e[o].x),i=this.multiply(i,this.add(e[n].x,e[o].x)));t=this.add(t,this.divide(s,i))}return t}};He.LOG_TABLE=[],He.EXP_TABLE=[],(()=>{let e=(n,s)=>{let i=0;for(let o=0;o<8;o++){s&1&&(i^=n);let a=n&128;n<<=1,a&&(n^=283),s>>=1}return i&255},t=1;for(let n=0;n<255;n++)He.EXP_TABLE[n]=t,He.LOG_TABLE[t]=n,t=e(t,3);He.EXP_TABLE[255]=He.EXP_TABLE[0]})();Yn=He});var qc,dt,Li=p(()=>{"use strict";ts();qc=new Map,dt=class{constructor(){this.storageKey="w3pk_social_recovery"}getItem(e){return typeof localStorage<"u"?localStorage.getItem(e):qc.get(e)||null}setItem(e,t){typeof localStorage<"u"?localStorage.setItem(e,t):qc.set(e,t)}async setupSocialRecovery(e,t,n,s){if(s>n.length)throw new Error("Threshold cannot be greater than number of guardians");if(s<2)throw new Error("Threshold must be at least 2");if(n.length>255)throw new Error("Cannot have more than 255 guardians");let i=Qn(e),o=jn(i,s,n.length),a=n.map((l,u)=>({id:crypto.randomUUID(),name:l.name,email:l.email,phone:l.phone,shareEncrypted:Zn(o[u]),status:"pending",addedAt:new Date().toISOString()})),c={threshold:s,totalGuardians:n.length,guardians:a,createdAt:new Date().toISOString(),ethereumAddress:t};return this.setItem(this.storageKey,JSON.stringify(c)),a}getSocialRecoveryConfig(){let e=this.getItem(this.storageKey);if(!e)return null;try{return JSON.parse(e)}catch{return null}}async generateGuardianInvite(e){let t=this.getSocialRecoveryConfig();if(!t)throw new Error("Social recovery not configured");let n=t.guardians.findIndex(c=>c.id===e.id);if(n===-1)throw new Error("Guardian not found");let s={version:1,guardianId:e.id,guardianName:e.name,guardianIndex:n+1,totalGuardians:t.totalGuardians,threshold:t.threshold,share:e.shareEncrypted,ethereumAddress:t.ethereumAddress,createdAt:t.createdAt},i=JSON.stringify(s),o=await this.generateQRCode(i),a=this.getGuardianExplainer(e.name,n+1,t.totalGuardians,t.threshold);return{guardianId:e.id,qrCode:o,shareCode:i,explainer:a}}async generateQRCode(e){try{return await(await Promise.resolve().then(()=>z(Fr()))).toDataURL(e,{errorCorrectionLevel:"H",width:512,margin:2})}catch{return this.createPlaceholderQR(e)}}createPlaceholderQR(e){if(typeof document>"u")return`data:text/plain;base64,${Buffer.from(e).toString("base64")}`;let t=document.createElement("canvas");t.width=512,t.height=512;let n=t.getContext("2d");return n?(n.fillStyle="white",n.fillRect(0,0,512,512),n.fillStyle="black",n.font="bold 20px sans-serif",n.textAlign="center",n.textBaseline="middle",n.fillText("Guardian Recovery Share",256,100),n.font="14px monospace",n.fillText('Install "qrcode" for QR codes',256,480),n.font="10px monospace",this.wrapText(e.substring(0,200)+"...",60).forEach((i,o)=>{n.fillText(i,256,150+o*12)}),t.toDataURL("image/png")):""}wrapText(e,t){let n=[];for(let s=0;s<e.length;s+=t)n.push(e.substring(s,s+t));return n}getGuardianExplainer(e,t,n,s){return`
85
- \u{1F6E1}\uFE0F GUARDIAN RECOVERY SHARE
86
-
87
- Dear ${e},
88
-
89
- You have been chosen as Guardian ${t} of ${n}
90
-
91
- YOUR ROLE:
92
- ----------
93
-
94
- Your friend has entrusted you with a recovery share for their encrypted wallet backup.
95
-
96
- WHAT THIS MEANS:
97
- - You hold 1 piece of a ${s}-piece puzzle
98
- - ${s} guardians needed to reconstruct the backup file
99
- - You cannot access the wallet alone
100
- - The backup is encrypted and requires a password
101
- - This is a responsibility and honor
102
-
103
- HOW IT WORKS:
104
- -------------
105
-
106
- If your friend loses access to their wallet:
107
-
108
- 1. They will contact you to request your share
109
- 2. You provide the QR code or share code below
110
- 3. System collects shares from ${s} guardians
111
- 4. Encrypted backup file is mathematically reconstructed
112
- 5. Your friend decrypts it with their password and regains access \u2713
113
-
114
- SECURITY:
115
- ---------
116
-
117
- \u2713 Your share contains encrypted data only
118
- \u2713 Cannot be decrypted without password
119
- \u2713 Cannot be used alone
120
- \u2713 ${s-1} other guardians needed
121
- \u2713 Safe to store digitally
122
-
123
- YOUR RESPONSIBILITIES:
124
- ---------------------
125
-
126
- DO:
127
- \u2713 Keep this share safe and accessible
128
- \u2713 Store in password manager or secure location
129
- \u2713 Respond promptly if friend requests recovery
130
- \u2713 Verify identity before sharing
131
-
132
- DON'T:
133
- \u2717 Share unless friend explicitly requests it
134
- \u2717 Post publicly or send unsecured
135
- \u2717 Lose or delete (friend depends on you!)
136
-
137
- VERIFICATION:
138
- ------------
139
-
140
- Before sharing, verify your friend's identity:
141
- - Video call to confirm
142
- - Ask security questions
143
- - Check contact method is authentic
144
-
145
- RECOVERY PROCESS:
146
- ----------------
147
-
148
- If requested:
149
- 1. Friend will contact you
150
- 2. Verify their identity
151
- 3. Provide this QR code or share code
152
- 4. System reconstructs encrypted backup file
153
- 5. Friend decrypts with their password
154
-
155
- HOW TO STORE:
156
- ------------
157
-
158
- Recommended storage:
159
- \u2713 Password manager (1Password, Bitwarden)
160
- \u2713 Encrypted note
161
- \u2713 Print and store physically
162
- \u2713 Screenshot (encrypted phone)
163
-
164
- ---
165
-
166
- Guardian ${t}/${n} | Threshold: ${s}/${n}
167
- Created: ${new Date().toISOString()}
168
-
169
- Thank you for being a trusted guardian!
170
-
171
- ---
172
-
173
- NEED HELP?
174
- Visit: https://docs.w3pk.org/social-recovery
175
- `}async recoverFromGuardians(e){if(!e||e.length===0)throw new Error("No guardian shares provided");let t=JSON.parse(e[0]),n=t.threshold,s=t.ethereumAddress;if(!n)throw new Error("Invalid share data: missing threshold information");if(e.length<n)throw new Error(`Need at least ${n} shares, got ${e.length}`);let o=e.map(u=>{let d=JSON.parse(u);if(d.ethereumAddress?.toLowerCase()!==s?.toLowerCase())throw new Error("Shares are from different wallets - cannot combine");return{guardianId:d.guardianId,share:d.share,index:d.guardianIndex}}).map(u=>es(u.share)),a=Jn(o,n),c=Xn(a),l;try{l=JSON.parse(c)}catch{throw new Error("Recovered data is not valid JSON - invalid shares")}if(!l.ethereumAddress)throw new Error("Recovered backup file is missing ethereum address");if(s&&l.ethereumAddress.toLowerCase()!==s.toLowerCase())throw new Error("Recovered address does not match share data - invalid shares");return{backupFileJson:c,ethereumAddress:l.ethereumAddress}}getRecoveryProgress(e){let t=this.getSocialRecoveryConfig();if(!t)throw new Error("Social recovery not configured");let n=new Set(e.map(s=>{try{return JSON.parse(s).guardianId}catch{return null}}).filter(Boolean));return{collected:n.size,required:t.threshold,guardians:t.guardians.map(s=>({id:s.id,name:s.name,hasProvided:n.has(s.id)})),canRecover:n.size>=t.threshold}}markGuardianVerified(e){let t=this.getSocialRecoveryConfig();if(!t)throw new Error("Social recovery not configured");let n=t.guardians.find(s=>s.id===e);if(!n)throw new Error("Guardian not found");n.status="active",n.lastVerified=new Date().toISOString(),this.setItem(this.storageKey,JSON.stringify(t))}revokeGuardian(e){let t=this.getSocialRecoveryConfig();if(!t)throw new Error("Social recovery not configured");let n=t.guardians.find(s=>s.id===e);if(!n)throw new Error("Guardian not found");n.status="revoked",this.setItem(this.storageKey,JSON.stringify(t))}async addGuardian(e,t){let n=this.getSocialRecoveryConfig();if(!n)throw new Error("Social recovery not configured");let s=[...n.guardians.filter(o=>o.status!=="revoked").map(o=>({name:o.name,email:o.email,phone:o.phone})),t],i=await this.setupSocialRecovery(e,n.ethereumAddress,s,n.threshold);return i[i.length-1]}}});var rs,Vc=p(()=>{"use strict";Un();Ni();Li();ai();rs=class{constructor(){this.verificationStorageKey="w3pk_backup_verifications";this.storage=new it,this.qrCreator=new Ut,this.socialRecoveryManager=new dt}async getBackupStatus(e){let t=await this.storage.getBackupsByAddress(e),n=await this.detectPasskeySync(),s=[...new Set(t.map(u=>u.method))],i=t.map(u=>u.createdAt).sort().pop(),o=t.filter(u=>u.method!=="phrase").map(u=>({id:u.id,method:u.method,location:"local",createdAt:u.createdAt,deviceFingerprint:u.deviceFingerprint})),a=this.getSocialRecoveryStatus(),c=this.getVerificationStatus(e);return{hasBackup:s.length>0,evictionRisk:await Cn(),lastBackupAt:i,methods:s,passkeySync:n,recoveryPhrase:{verified:c.verified,verificationCount:c.count,encryptedBackups:o},socialRecovery:a,securityScore:this.calculateSecurityScore(n,o,a,c,s)}}async detectPasskeySync(){if(typeof navigator>"u")return{enabled:!1,deviceCount:0,lastSyncTime:void 0,platform:"unknown"};let e=navigator.userAgent.toLowerCase(),t="unknown";e.includes("mac")||e.includes("iphone")||e.includes("ipad")?t="apple":e.includes("android")?t="google":e.includes("windows")&&(t="microsoft");let n=await this.checkResidentKeySupport();return{enabled:n,deviceCount:1,lastSyncTime:n?new Date().toISOString():void 0,platform:t}}async checkResidentKeySupport(){if(typeof window>"u"||!window.PublicKeyCredential)return!1;try{return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}getSocialRecoveryStatus(){let e=this.socialRecoveryManager.getSocialRecoveryConfig();if(!e)return;let t=e.guardians.filter(n=>n.status==="active").length;return{enabled:!0,guardians:e.guardians,threshold:e.threshold,sharesDistributed:e.guardians.length,verifiedGuardians:t}}getVerificationStatus(e){try{let t=typeof localStorage<"u"?localStorage.getItem(this.verificationStorageKey):null;return t?JSON.parse(t)[e.toLowerCase()]||{verified:!1,count:0}:{verified:!1,count:0}}catch{return{verified:!1,count:0}}}async hasBackup(e){return(await this.storage.getBackupsByAddress(e)).length>0}async confirmRecoveryPhraseBackup(e,t){await this.storage.storeBackupMetadata({id:crypto.randomUUID(),ethereumAddress:e,method:"phrase",createdAt:new Date().toISOString(),addressChecksum:t})}markBackupVerified(e){try{let t=typeof localStorage<"u"?localStorage.getItem(this.verificationStorageKey):null,n=t?JSON.parse(t):{},s=e.toLowerCase();n[s]||(n[s]={verified:!1,count:0}),n[s].verified=!0,n[s].count+=1,n[s].lastVerifiedAt=new Date().toISOString(),typeof localStorage<"u"&&localStorage.setItem(this.verificationStorageKey,JSON.stringify(n))}catch(t){console.error("Failed to mark backup as verified:",t)}}calculateSecurityScore(e,t,n,s,i=[]){let o=0;n?.enabled&&(o=20,n.verifiedGuardians>=n.threshold&&(o+=10));let a=0;s?.verified&&(a=10,a+=Math.min(s.count-1,10));let c={passkeyActive:e.enabled?20:0,passkeyMultiDevice:e.deviceCount>1?10:0,phraseVerified:a,encryptedBackup:t.length>0?20:0,socialRecovery:o},l=Object.values(c).reduce((m,y)=>m+y,0),u=i.length>0?l:Math.min(l,20),d,h;return i.length===0?(d="vulnerable",h="Create a backup file or confirm your recovery phrase: browser storage can be wiped"):u<=20?(d="vulnerable",h='Create encrypted backup to reach "protected" (40+ pts)'):u<=50?(d="protected",h='Set up social recovery to reach "secured" (70+ pts)'):u<=80?(d="secured",h='Enable all methods to reach "fort-knox" (100 pts)'):(d="fort-knox",h="Maximum security achieved!"),{total:u,breakdown:c,level:d,nextMilestone:h}}async createQRBackup(e,t,n){let{qrCodeDataURL:s,rawData:i,instructions:o}=await this.qrCreator.createQRBackup(e,t,n),a={id:crypto.randomUUID(),ethereumAddress:t,method:"qr",createdAt:new Date().toISOString(),addressChecksum:JSON.parse(i).checksum};return await this.storage.storeBackupMetadata(a),{qrCodeDataURL:s,instructions:o}}async restoreFromQR(e,t){return await this.qrCreator.restoreFromQR(e,t)}async simulateRecoveryScenario(e,t){let n=[];switch(e.type){case"lost-device":t.passkeySync.enabled&&t.passkeySync.deviceCount>1&&n.push({method:"Passkey Sync (iCloud/Google)",success:!0,time:"5 minutes",requirements:["Sign in to cloud account","Authenticate on new device"]}),t.recoveryPhrase.encryptedBackups.length>0&&n.push({method:"Encrypted Backup",success:!0,time:"2 minutes",requirements:["Backup file","Password"]}),t.socialRecovery?.enabled&&n.push({method:"Social Recovery",success:!0,time:"24 hours",requirements:[`${t.socialRecovery.threshold} guardian shares`]});break;case"lost-phrase":t.passkeySync.enabled&&n.push({method:"Passkey (current device)",success:!0,time:"instant",requirements:["Current device","Biometric/PIN"]}),t.socialRecovery?.enabled&&n.push({method:"Social Recovery",success:!0,time:"24 hours",requirements:[`${t.socialRecovery.threshold} guardian shares`]});break;case"lost-both":t.passkeySync.enabled&&t.passkeySync.deviceCount>1&&n.push({method:"Passkey Sync",success:!0,time:"5 minutes",requirements:["Cloud account access","New device"]}),t.socialRecovery?.enabled&&n.push({method:"Social Recovery",success:!0,time:"24 hours",requirements:[`${t.socialRecovery.threshold} guardian shares`]});break;case"switch-platform":t.recoveryPhrase.encryptedBackups.length>0&&n.push({method:"Encrypted Backup",success:!0,time:"2 minutes",requirements:["Backup file","Password"]}),t.socialRecovery?.enabled&&n.push({method:"Social Recovery",success:!0,time:"24 hours",requirements:[`${t.socialRecovery.threshold} guardian shares`]});break}let s=n.length>0&&n.some(o=>o.success),i="";return s?(i=`\u2705 You're safe! ${n.length} way${n.length>1?"s":""} to recover.
176
-
177
- `,i+=`Available recovery methods:
178
- `,n.forEach(o=>{i+=`- ${o.method} (~${o.time})
179
- `})):(i=`\u274C Wallet cannot be recovered in this scenario.
180
-
181
- `,i+="Recommendation: Set up at least 2 backup methods to prevent total loss."),{scenario:e,success:s,availableMethods:n,timeEstimate:s?n[0].time:"N/A",educationalNote:i}}}});var be={};x(be,{BackupFileManager:()=>Mr,generatePrfSalt:()=>sp,prfSyncInput:()=>ip});function sp(){return ne(crypto.getRandomValues(new Uint8Array(32)).buffer)}async function ip(r){let e=new Uint8Array(T(r));return crypto.subtle.digest("SHA-256",new Uint8Array([...Yc,...e]))}async function Gc(r,e){try{let t=await crypto.subtle.importKey("raw",r,"HKDF",!1,["deriveKey"]);return await crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:T(e),info:Yc},t,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}catch(t){throw new P("Failed to derive backup key from PRF output",t)}}var Yc,Mr,he=p(()=>{"use strict";Ke();se();W();ce();Yc=new TextEncoder().encode("w3pk-prf-sync-v1");Mr=class{async createPasswordBackup(e,t,n,s){if(!n||n.length<1)throw new Error("Password is required for password-based backup");let i=crypto.getRandomValues(new Uint8Array(32)),o=await ot(e,n,i),a=await V(t),c={createdAt:new Date().toISOString(),ethereumAddress:t,encryptedMnemonic:o.encrypted,encryptionMethod:"password",passwordEncryption:{salt:o.salt,iv:o.iv,iterations:o.iterations},...s&&{credential:{id:s.id,publicKey:s.publicKey}},addressChecksum:a},l=JSON.stringify(c,null,2),u=new Blob([l],{type:"application/json"});return{backupFile:c,json:l,blob:u}}async createPasskeyBackup(e,t,n,s){let i=await le(n,s),o=await J(e,i),a=await V(t),l=new TextEncoder().encode(s),u=await crypto.subtle.digest("SHA-256",l),h=Array.from(new Uint8Array(u)).map(b=>b.toString(16).padStart(2,"0")).join("").substring(0,16),m={createdAt:new Date().toISOString(),ethereumAddress:t,encryptedMnemonic:o,encryptionMethod:"passkey",credentialId:n,publicKeyFingerprint:h,addressChecksum:a},y=JSON.stringify(m,null,2),w=new Blob([y],{type:"application/json"});return{backupFile:m,json:y,blob:w}}async createHybridBackup(e,t,n,s,i){let o=await le(s,i),a=await J(e,o),c=crypto.getRandomValues(new Uint8Array(32)),l=await ot(a,n,c),u=await V(t),h=new TextEncoder().encode(i),m=await crypto.subtle.digest("SHA-256",h),w=Array.from(new Uint8Array(m)).map(v=>v.toString(16).padStart(2,"0")).join("").substring(0,16),b={createdAt:new Date().toISOString(),ethereumAddress:t,encryptedMnemonic:l.encrypted,encryptionMethod:"hybrid",credentialId:s,publicKeyFingerprint:w,passwordEncryption:{salt:l.salt,iv:l.iv,iterations:l.iterations},addressChecksum:u},S=JSON.stringify(b,null,2),A=new Blob([S],{type:"application/json"});return{backupFile:b,json:S,blob:A}}async createPrfBackup(e,t,n,s,i,o){let a=await Gc(o,i),c=await J(e,a),l=await V(t),u={createdAt:new Date().toISOString(),ethereumAddress:t,encryptedMnemonic:c,encryptionMethod:"prf",credential:{id:n.id,publicKey:n.publicKey},prfSalt:i,username:s,addressChecksum:l},d=JSON.stringify(u,null,2),h=new Blob([d],{type:"application/json"});return{backupFile:u,json:d,blob:h}}async restoreWithPrf(e,t){if(e.encryptionMethod!=="prf"||!e.prfSalt)throw new Error("This backup is not a PRF backup.");let n=await Gc(t,e.prfSalt),s=await Q(e.encryptedMnemonic,n),{Wallet:i}=await import("ethers"),o=i.fromPhrase(s);if(await V(o.address)!==e.addressChecksum||o.address.toLowerCase()!==e.ethereumAddress.toLowerCase())throw new Error("Address checksum mismatch - corrupted backup or decryption failure");return{mnemonic:s,ethereumAddress:o.address}}async restoreWithExistingPasskey(e,t,n){if(e.encryptionMethod==="password")throw new Error("This backup is password-protected. Use restoreWithPassword() instead.");if(e.encryptionMethod==="prf")throw new Error("This backup is PRF-encrypted. Use restoreWithPrf() instead.");if(e.credentialId&&e.credentialId!==t)throw new Error("Credential ID mismatch. This backup was created with a different passkey.");let s;if(e.encryptionMethod==="passkey"){let c=await le(t,n);s=await Q(e.encryptedMnemonic,c)}else throw new Error("This backup requires both passkey and password. Use restoreWithHybrid() instead.");let{Wallet:i}=await import("ethers"),o=i.fromPhrase(s);if(await V(o.address)!==e.addressChecksum)throw new Error("Address checksum mismatch - corrupted backup or decryption failure");return{mnemonic:s,ethereumAddress:e.ethereumAddress}}async restoreWithPassword(e,t){if(!e.passwordEncryption)throw new Error("This backup is not password-protected.");let n;if(e.encryptionMethod==="password")n=await kr(e.encryptedMnemonic,t,e.passwordEncryption.salt,e.passwordEncryption.iv,e.passwordEncryption.iterations);else throw e.encryptionMethod==="hybrid"?new Error("This backup requires both passkey and password. Use restoreWithHybrid() instead."):new Error("This backup is passkey-only. Use restoreWithExistingPasskey() instead.");let{Wallet:s}=await import("ethers"),i=s.fromPhrase(n);if(await V(i.address)!==e.addressChecksum)throw new Error("Address checksum mismatch - corrupted backup or wrong password");return{mnemonic:n,ethereumAddress:e.ethereumAddress}}async restoreWithHybrid(e,t,n,s){if(e.encryptionMethod!=="hybrid")throw new Error("This backup is not a hybrid backup.");if(!e.passwordEncryption)throw new Error("Missing password encryption data in hybrid backup.");let i=await kr(e.encryptedMnemonic,t,e.passwordEncryption.salt,e.passwordEncryption.iv,e.passwordEncryption.iterations),o=await le(n,s),a=await Q(i,o),{Wallet:c}=await import("ethers"),l=c.fromPhrase(a);if(await V(l.address)!==e.addressChecksum)throw new Error("Address checksum mismatch - corrupted backup or decryption failure");return{mnemonic:a,ethereumAddress:e.ethereumAddress}}async parseBackupFile(e){let t;e instanceof Blob?t=await e.text():t=e;let n=JSON.parse(t);if(!n.createdAt||!n.ethereumAddress||!n.encryptedMnemonic)throw new Error("Invalid backup file: missing required fields");if(n.encryptionMethod==="prf"&&(!n.prfSalt||!n.credential?.id||!n.credential.publicKey))throw new Error("Invalid backup file: PRF backup without its salt or passkey");return n}createDownloadableBackup(e,t){let n=JSON.stringify(e,null,2),s=new Blob([n],{type:"application/json"}),i=`w3pk-backup-${e.ethereumAddress.substring(0,8)}-${new Date().toISOString().split("T")[0]}.json`;return{blob:s,filename:t||i}}}});var jc=p(()=>{"use strict"});var De={};x(De,{BackupFileManager:()=>Mr,BackupManager:()=>rs,BackupStorage:()=>it,QRBackupCreator:()=>Ut,decryptWithPassword:()=>kr,deriveAddressChecksum:()=>V,deriveKeyFromPassword:()=>Nn,encryptWithPassword:()=>ot,getDeviceFingerprint:()=>Ce,validatePasswordStrength:()=>qa});var Fe=p(()=>{"use strict";Vc();Un();Ni();he();jc();Ke()});var Jc={};x(Jc,{extractRS:()=>_i});function _i(r){let e=0;if(r[e++]!==48)throw new Error("Invalid DER signature: missing sequence tag");if(e++,r[e++]!==2)throw new Error("Invalid DER signature: missing r integer tag");let t=r[e++];t>32&&(e++,t--);let n=r.slice(e,e+t);if(e+=t,r[e++]!==2)throw new Error("Invalid DER signature: missing s integer tag");let s=r[e++];s>32&&(e++,s--);let i=r.slice(e,e+s),o=new Uint8Array(32),a=new Uint8Array(32);o.set(n,32-n.length),a.set(i,32-i.length);let c=BigInt("0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"),l=BigInt("0x"+Buffer.from(a).toString("hex"));l>c/2n&&(l=c-l);let u="0x"+Buffer.from(o).toString("hex"),d="0x"+l.toString(16).padStart(64,"0");return{r:u,s:d}}var Ki=p(()=>{"use strict"});var ns={};x(ns,{SocialRecovery:()=>Oi});var Oi,ss=p(()=>{"use strict";ts();Oi=class{async splitAmongGuardians(e,t,n){if(n>t.length)throw new Error("Threshold cannot exceed number of guardians");if(n<2)throw new Error("Threshold must be at least 2 for security");if(t.length>255)throw new Error("Cannot have more than 255 guardians");let s=JSON.stringify(e),i=Qn(s),o=jn(i,n,t.length),a=t.map((c,l)=>({guardianId:crypto.randomUUID(),guardianName:c.name,shareData:Zn(o[l]),shareIndex:l+1,threshold:n,createdAt:new Date().toISOString(),walletAddress:e.ethereumAddress}));return{threshold:n,totalShares:t.length,guardianShares:a,backupFile:e,setupDate:new Date().toISOString()}}async recoverFromShares(e){if(e.length<2)throw new Error("At least 2 shares required for recovery");let t=e[0].threshold,n=e[0].walletAddress;if(!t)throw new Error("Invalid share: missing threshold information");if(e.length<t)throw new Error(`Need at least ${t} shares to recover, but only ${e.length} provided`);if(!e.every(l=>l.walletAddress===n&&l.threshold===t))throw new Error("Shares are from different wallets or have inconsistent thresholds");let i=e.map(l=>es(l.shareData)),o=Jn(i,t),a=Xn(o),c=JSON.parse(a);if(c.ethereumAddress!==n)throw new Error("Recovered backup address mismatch - corrupted shares");return c}async createGuardianInvitation(e,t){let n={type:"w3pk-guardian-share",version:1,guardianName:e.guardianName,walletAddress:e.walletAddress,shareData:e.shareData,shareIndex:e.shareIndex,threshold:e.threshold,createdAt:e.createdAt,message:t||`You have been chosen as a recovery guardian for wallet ${e.walletAddress.substring(0,10)}...`},s=JSON.stringify(n,null,2),i;try{i=await(await Promise.resolve().then(()=>z(Fr()))).toDataURL(s,{errorCorrectionLevel:"H",width:512})}catch(a){console.warn("QR code generation not available:",a)}let o=`
182
- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
183
- W3PK GUARDIAN RECOVERY SHARE
184
- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
185
-
186
- Guardian: ${e.guardianName}
187
- Wallet Address: ${e.walletAddress}
188
- Share Index: ${e.shareIndex}
189
- Created: ${new Date(e.createdAt).toLocaleDateString()}
190
-
191
- ${t||"You have been chosen as a recovery guardian for this wallet."}
192
-
193
- IMPORTANT INSTRUCTIONS:
194
- -----------------------
195
-
196
- 1. KEEP THIS SAFE
197
- This share is part of a ${e.shareIndex}-of-N social recovery system.
198
- Multiple guardians need to combine their shares to recover the wallet.
199
-
200
- 2. NEVER SHARE THIS ALONE
201
- A single share cannot recover the wallet - it's secure to store.
202
- However, keep it confidential to maintain the owner's security.
203
-
204
- 3. WHEN NEEDED FOR RECOVERY
205
- The wallet owner will contact you and other guardians.
206
- You'll need to provide this share data for wallet recovery.
207
-
208
- 4. STORAGE RECOMMENDATIONS
209
- \u2713 Save this file in a password manager
210
- \u2713 Print and store in a safe place
211
- \u2713 Save to encrypted cloud storage
212
- \u2717 Do NOT email unencrypted
213
- \u2717 Do NOT post publicly
214
-
215
- SHARE DATA:
216
- -----------
217
- ${e.shareData}
218
-
219
- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
220
- Generated by w3pk - Web3 Passkey SDK
221
- https://github.com/w3hc/w3pk
222
- \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
223
- `;return{qrCodeDataURL:i,shareDocument:o,shareJson:s}}parseGuardianShare(e){let t=JSON.parse(e);if(t.type!=="w3pk-guardian-share")throw new Error("Invalid guardian share format");if(!t.threshold)throw new Error("Invalid guardian share: missing threshold information");return{guardianId:crypto.randomUUID(),guardianName:t.guardianName,shareData:t.shareData,shareIndex:t.shareIndex,threshold:t.threshold,createdAt:t.createdAt,walletAddress:t.walletAddress}}async verifyRecovery(e){try{return{canRecover:!0,recoveredAddress:(await this.recoverFromShares(e)).ethereumAddress}}catch(t){return{canRecover:!1,error:t instanceof Error?t.message:"Unknown error"}}}createShareDownload(e){let t=JSON.stringify({type:"w3pk-guardian-share",version:1,guardianName:e.guardianName,walletAddress:e.walletAddress,shareData:e.shareData,shareIndex:e.shareIndex,threshold:e.threshold,createdAt:e.createdAt},null,2),n=new Blob([t],{type:"application/json"}),s=`w3pk-guardian-${e.guardianName.replace(/\s+/g,"-")}-share-${e.shareIndex}.json`;return{blob:n,filename:s}}}});var Qc={};x(Qc,{authenticateWithPasskey:()=>Wi,promptPasskeySelection:()=>zi});async function zi(){try{let r=new D,e=Ee(),t=T(e),n=[];try{let u=await r.getAllCredentials();u.length>0&&(n=u.map(d=>({id:d.id,type:"public-key",transports:["internal","hybrid","usb","nfc","ble"]})))}catch{}let s={challenge:t,rpId:window.location.hostname,userVerification:"required",timeout:12e4};n.length>0&&(s.allowCredentials=n.map(u=>({id:T(u.id),type:u.type,transports:u.transports})));let i=await navigator.credentials.get({publicKey:s});if(!i)throw new N("No passkey selected. Please select a passkey to continue with sync.");let o=i.id,a=i.response.userHandle,c=a?.byteLength?new TextDecoder().decode(a):void 0,l=await r.getCredentialById(o);return l?{credentialId:o,publicKey:l.publicKey,ethereumAddress:l.ethereumAddress,username:l.username,assertion:i}:{credentialId:o,publicKey:"",ethereumAddress:void 0,username:c,assertion:i}}catch(r){throw r?.name==="NotAllowedError"?new N("Passkey selection was cancelled. Please try again and select your passkey."):r instanceof N?r:new N(`Failed to select passkey: ${r instanceof Error?r.message:"Unknown error"}`,r)}}async function Wi(r){try{let e=Ee(),n={challenge:T(e),rpId:window.location.hostname,userVerification:"required",timeout:6e4,allowCredentials:[{id:T(r),type:"public-key",transports:["internal","hybrid","usb","nfc","ble"]}]},s=await navigator.credentials.get({publicKey:n});if(!s)throw new N("Authentication failed - no credential returned");return s}catch(e){throw e?.name==="NotAllowedError"?new N("Authentication was cancelled or the passkey is not available on this device."):new N(`Passkey authentication failed: ${e instanceof Error?e.message:"Unknown error"}`,e)}}var $i=p(()=>{"use strict";W();_e();ce();se()});var is={};x(is,{DeviceSyncManager:()=>Ur});var Ur,Nr=p(()=>{"use strict";Ur=class{constructor(){this.SYNC_STORAGE_KEY="w3pk_sync_info"}async getSyncInfo(){try{let e=localStorage.getItem(this.SYNC_STORAGE_KEY);return e?JSON.parse(e):null}catch(e){return console.error("Failed to get sync info:",e),null}}async updateSyncInfo(e){let t=await this.getSyncInfo(),n=this.detectPlatform(),s={deviceName:t?.deviceName||this.generateDeviceName(),platform:n,lastSyncTime:new Date().toISOString(),walletsSynced:t?.walletsSynced||[]};s.walletsSynced.includes(e)||s.walletsSynced.push(e),localStorage.setItem(this.SYNC_STORAGE_KEY,JSON.stringify(s))}detectPlatform(){let e=navigator.userAgent.toLowerCase();return/iphone|ipad|ipod/.test(e)?"ios":/android/.test(e)?"android":/mac/.test(e)?"macos":/win/.test(e)?"windows":/linux/.test(e)?"linux":"unknown"}generateDeviceName(){let e=this.detectPlatform(),t=new Date().toISOString().split("T")[0];return`${e}-device-${t}`}async exportForSync(e,t,n,s,i){let{BackupFileManager:o,generatePrfSalt:a,prfSyncInput:c}=await Promise.resolve().then(()=>(he(),be)),{evaluatePrf:l}=await Promise.resolve().then(()=>(En(),oi)),{PrfUnsupportedError:u}=await Promise.resolve().then(()=>(W(),$s)),d=new o,h=a(),m;try{({output:m}=await l(await c(h),n.id))}catch(y){if(y instanceof u&&i)return d.createPasswordBackup(e,t,i,n);throw y}try{return await d.createPrfBackup(e,t,n,s,h,m)}finally{new Uint8Array(m).fill(0)}}async importFromSync(e,t){let{BackupFileManager:n,prfSyncInput:s}=await Promise.resolve().then(()=>(he(),be)),{evaluatePrf:i}=await Promise.resolve().then(()=>(En(),oi)),{verifyAssertionSignature:o}=await Promise.resolve().then(()=>(ei(),Ia)),{SyncBootstrapError:a}=await Promise.resolve().then(()=>(W(),$s)),c=new n;if(e.encryptionMethod!=="prf"||!e.prfSalt||!e.credential)throw new Error("This backup is not a PRF backup.");let l=e.credential.id,u=await i(await s(e.prfSalt),l),d;try{if(u.credentialId!==l)throw new a("CREDENTIAL_MISMATCH",u.credentialId);if(!await o(u.assertion,t))throw new a("PUBLIC_KEY_MISMATCH",l);d=await c.restoreWithPrf(e,u.output)}finally{new Uint8Array(u.output).fill(0)}return await this.updateSyncInfo(d.ethereumAddress),d}async canSyncBackup(e,t){return e.encryptionMethod!=="passkey"?!0:e.publicKeyFingerprint?t.some(n=>n.publicKeyFingerprint===e.publicKeyFingerprint):!1}async generateSyncQR(e){try{let t=await Promise.resolve().then(()=>z(Fr())),n=JSON.stringify(e);if(n.length>2953)throw new Error("Backup file too large for QR code. Use file transfer instead.");return t.toDataURL(n,{errorCorrectionLevel:"H",margin:2,width:512})}catch(t){throw t.code==="ERR_MODULE_NOT_FOUND"?new Error("QR code generation requires qrcode package: npm install qrcode"):t}}async parseSyncQR(e){let{BackupFileManager:t}=await Promise.resolve().then(()=>(he(),be));return new t().parseBackupFile(e)}}});var os,Xc=p(()=>{"use strict";Ke();os=class{async createSyncPackage(e,t,n){let s=await Ce(),{deriveEncryptionKeyFromWebAuthn:i,encryptData:o}=await Promise.resolve().then(()=>(se(),fr)),a=await i(t,n),c=await o(e,a),l=this.detectSyncMethod();return{id:crypto.randomUUID(),encryptedData:c,deviceFingerprints:[s],syncMethod:l,version:1,updatedAt:new Date().toISOString()}}detectSyncMethod(){let e=navigator.userAgent.toLowerCase();return e.includes("mac")||e.includes("iphone")||e.includes("ipad")?"icloud":e.includes("android")||e.includes("chrome")?"google":e.includes("windows")?"microsoft":"custom"}async restoreFromSync(e,t,n){let{deriveEncryptionKeyFromWebAuthn:s,decryptData:i}=await Promise.resolve().then(()=>(se(),fr)),o=await s(t,n),a=await i(e.encryptedData,o),c=await Ce();return e.deviceFingerprints.includes(c)||(e.deviceFingerprints.push(c),e.updatedAt=new Date().toISOString()),a}async getSetupFlow(){return{success:!1,steps:[{title:"1. Authenticate on New Device",action:"Use Touch ID/Face ID",educational:"Your passkey is automatically synced via iCloud/Google",status:"waiting"},{title:"2. Decrypt Wallet Data",action:"System validates device",educational:"Only your trusted devices can decrypt the wallet",status:"waiting"},{title:"3. Verify Recovery",action:"Check partial address",educational:"Confirm address matches your wallet",status:"waiting"},{title:"4. Ready!",action:"Wallet synced",educational:"All devices now have access",status:"waiting"}]}}getSyncExplainer(){return`
224
- HOW CROSS-DEVICE SYNC WORKS
225
- ===========================
226
-
227
- Your wallet is protected by TWO layers:
228
-
229
- Layer 1: Passkey (Auto-Syncs)
230
- -----------------------------
231
- \u2713 Your fingerprint/Face ID credential
232
- \u2713 Syncs via iCloud Keychain or Google
233
- \u2713 Available on all your devices
234
- \u2713 Cannot be stolen (hardware-protected)
235
-
236
- Layer 2: Encrypted Wallet (In Browser)
237
- --------------------------------------
238
- \u2713 Your 12-word mnemonic (encrypted)
239
- \u2713 Stored in browser's localStorage
240
- \u2713 Can ONLY be decrypted with passkey
241
- \u2713 Requires authentication to access
242
-
243
- How They Work Together:
244
- ----------------------
245
-
246
- Device 1 (iPhone) iCloud Keychain Device 2 (Mac)
247
- | | |
248
- |-- Passkey Created -------->| |
249
- | | |
250
- |-- Wallet Encrypted --------| |
251
- | (in localStorage) | |
252
- | | |
253
- | |<----- Login on Mac -----|
254
- | | |
255
- | Passkey Synced |
256
- | |------- Unlock --------->|
257
- | | Passkey |
258
- | | |
259
- | |<----- Decrypt ----------|
260
- | | Wallet |
261
-
262
- Security Benefits:
263
- -----------------
264
-
265
- \u2713 Passkey syncs automatically (convenient)
266
- \u2713 Wallet ONLY decrypts with passkey (secure)
267
- \u2713 Cannot access wallet without biometric
268
- \u2713 Works seamlessly across devices
269
- \u2713 No passwords to remember
270
-
271
- What Gets Synced:
272
- ----------------
273
-
274
- \u2713 Passkey credential (via platform sync)
275
- \u2713 Credential metadata (localStorage)
276
-
277
- What Stays Local:
278
- ----------------
279
-
280
- \u2717 Encrypted mnemonic (in localStorage)
281
- - Must authenticate to decrypt
282
- - Requires passkey access
283
- - Platform-specific storage
284
-
285
- Recovery Options:
286
- ----------------
287
-
288
- If you lose a device:
289
- 1. \u2713 Sign in on new device
290
- 2. \u2713 Passkey auto-syncs
291
- 3. \u2713 Authenticate to decrypt wallet
292
- 4. \u2713 Wallet restored!
293
-
294
- If passkey doesn't sync:
295
- 1. \u2713 Use encrypted backup
296
- 2. \u2713 Use 12-word recovery phrase
297
- 3. \u2713 Use social recovery
298
-
299
- ---
300
-
301
- Think of it like:
302
- \u{1F511} Passkey = Your car key (syncs via keychain)
303
- \u{1F697} Wallet = Your car (locked, needs key to start)
304
- `}}});var as,Zc=p(()=>{"use strict";Ke();as=class{constructor(){this.storageKey="w3pk_devices"}async registerDevice(){let e={id:await Ce(),name:this.getDeviceName(),platform:this.detectPlatform(),lastActive:new Date().toISOString(),trusted:!0,canRevoke:!1},t=await this.getDevices(),n=t.find(s=>s.id===e.id);return n?(n.lastActive=new Date().toISOString(),localStorage.setItem(this.storageKey,JSON.stringify(t))):(t.push(e),localStorage.setItem(this.storageKey,JSON.stringify(t))),e}async getDevices(){let e=localStorage.getItem(this.storageKey);if(!e)return[];try{return JSON.parse(e)}catch{return[]}}async getSyncStatus(){let e=await this.getDevices(),t=await Ce();e.forEach(i=>{i.canRevoke=i.id!==t}),e.sort((i,o)=>new Date(o.lastActive).getTime()-new Date(i.lastActive).getTime());let n=this.detectPlatform(),s=e.length>1?new Date(Math.max(...e.map(i=>new Date(i.lastActive).getTime()))).toISOString():void 0;return{enabled:e.length>1,devices:e,lastSyncTime:s,platform:this.getPlatformName(n)}}async revokeDevice(e){let t=await this.getDevices(),n=await Ce();if(e===n)throw new Error("Cannot revoke current device");let s=t.filter(i=>i.id!==e);localStorage.setItem(this.storageKey,JSON.stringify(s))}async updateLastActive(){let e=await this.getDevices(),t=await Ce(),n=e.find(s=>s.id===t);n&&(n.lastActive=new Date().toISOString(),localStorage.setItem(this.storageKey,JSON.stringify(e)))}getDeviceName(){let e=this.detectPlatform(),t=navigator.userAgent;if(e==="ios")return t.includes("iPhone")?"iPhone":t.includes("iPad")?"iPad":t.includes("iPod")?"iPod":"iOS Device";if(e==="android"){let n=t.match(/Android.*;\s([^)]+)\)/);return n?n[1]:"Android Device"}return e==="macos"?"Mac":e==="windows"?"Windows PC":e==="linux"?"Linux PC":"Unknown Device"}detectPlatform(){let e=navigator.userAgent.toLowerCase();return e.includes("iphone")||e.includes("ipad")||e.includes("ipod")?"ios":e.includes("android")?"android":e.includes("mac")?"macos":e.includes("windows")?"windows":e.includes("linux")?"linux":"unknown"}getPlatformName(e){switch(e){case"ios":return"iOS (iCloud Keychain)";case"android":return"Android (Google)";case"macos":return"macOS (iCloud Keychain)";case"windows":return"Windows (Microsoft)";case"linux":return"Linux";default:return"Unknown"}}async getDeviceListFormatted(){let e=await this.getSyncStatus();if(e.devices.length===0)return"No devices registered";let t=`Your Devices (${e.devices.length}):
305
-
306
- `;return e.devices.forEach((n,s)=>{let i=Date.now()-new Date(n.lastActive).getTime(),o=this.formatTimeDiff(i);t+=`${s+1}. ${n.name}
307
- `,t+=` Platform: ${this.getPlatformName(n.platform)}
308
- `,t+=` Last active: ${o}
309
- `,t+=` ${n.canRevoke?"":"(Current device)"}
310
-
311
- `}),t}formatTimeDiff(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),s=Math.floor(n/60),i=Math.floor(s/24);return i>0?`${i} day${i>1?"s":""} ago`:s>0?`${s} hour${s>1?"s":""} ago`:n>0?`${n} minute${n>1?"s":""} ago`:"just now"}}});var cs,el=p(()=>{"use strict";cs=class{async detectSyncCapabilities(){let e=this.detectPlatform(),t=await this.checkPasskeySync(),n=this.estimateDeviceCount();return{passkeysSync:t,platform:e,estimatedDevices:n,syncEnabled:t&&e!=="none"}}detectPlatform(){let e=navigator.userAgent.toLowerCase();return e.includes("mac")||e.includes("iphone")||e.includes("ipad")||e.includes("ipod")?"apple":e.includes("android")?"google":e.includes("windows")?"microsoft":"none"}async checkPasskeySync(){if(!window.PublicKeyCredential)return!1;try{return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}estimateDeviceCount(){return 1}getPlatformEducation(e){switch(e){case"apple":return`
1023
+ Minimum version required to store current data is: `+s+`.
1024
+ `);let o=sm(e,t,i),a=hi.getSymbolSize(e),c=new Vp(a);return em(c,e),tm(c),rm(c,e),Js(c,t,0),e>=7&&nm(c,e),im(c,o),isNaN(n)&&(n=Zs.getBestMask(c,Js.bind(null,c,t))),Zs.applyMask(n,c),Js(c,t,n),{modules:c,version:e,errorCorrectionLevel:t,maskPattern:n,segments:i}}Rl.create=function(e,t){if(typeof e>"u"||e==="")throw new Error("No input text");let n=Vs.M,i,s;return typeof t<"u"&&(n=Vs.from(t.errorCorrectionLevel,Vs.M),i=di.from(t.version),s=Zs.from(t.maskPattern),t.toSJISFunc&&hi.setToSJISFunction(t.toSJISFunc)),am(e,i,n,s)}});var Qs=B(wt=>{"use strict";function Fl(r){if(typeof r=="number"&&(r=r.toString()),typeof r!="string")throw new Error("Color should be defined as hex string");let e=r.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+r);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(n){return[n,n]}))),e.length===6&&e.push("F","F");let t=parseInt(e.join(""),16);return{r:t>>24&255,g:t>>16&255,b:t>>8&255,a:t&255,hex:"#"+e.slice(0,6).join("")}}wt.getOptions=function(e){e||(e={}),e.color||(e.color={});let t=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,n=e.width&&e.width>=21?e.width:void 0,i=e.scale||4;return{width:n,scale:n?4:i,margin:t,color:{dark:Fl(e.color.dark||"#000000ff"),light:Fl(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};wt.getScale=function(e,t){return t.width&&t.width>=e+t.margin*2?t.width/(e+t.margin*2):t.scale};wt.getImageWidth=function(e,t){let n=wt.getScale(e,t);return Math.floor((e+t.margin*2)*n)};wt.qrToImageData=function(e,t,n){let i=t.modules.size,s=t.modules.data,o=wt.getScale(i,n),a=Math.floor((i+n.margin*2)*o),c=n.margin*o,u=[n.color.light,n.color.dark];for(let l=0;l<a;l++)for(let d=0;d<a;d++){let h=(l*a+d)*4,m=n.color.light;if(l>=c&&d>=c&&l<a-c&&d<a-c){let y=Math.floor((l-c)/o),w=Math.floor((d-c)/o);m=u[s[y*i+w]?1:0]}e[h++]=m.r,e[h++]=m.g,e[h++]=m.b,e[h]=m.a}}});var Ml=B(fi=>{"use strict";var eo=Qs();function cm(r,e,t){r.clearRect(0,0,e.width,e.height),e.style||(e.style={}),e.height=t,e.width=t,e.style.height=t+"px",e.style.width=t+"px"}function lm(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}fi.render=function(e,t,n){let i=n,s=t;typeof i>"u"&&(!t||!t.getContext)&&(i=t,t=void 0),t||(s=lm()),i=eo.getOptions(i);let o=eo.getImageWidth(e.modules.size,i),a=s.getContext("2d"),c=a.createImageData(o,o);return eo.qrToImageData(c.data,e,i),cm(a,s,o),a.putImageData(c,0,0),s};fi.renderToDataURL=function(e,t,n){let i=n;typeof i>"u"&&(!t||!t.getContext)&&(i=t,t=void 0),i||(i={});let s=fi.render(e,t,i),o=i.type||"image/png",a=i.rendererOpts||{};return s.toDataURL(o,a.quality)}});var Ll=B(_l=>{"use strict";var um=Qs();function Ul(r,e){let t=r.a/255,n=e+'="'+r.hex+'"';return t<1?n+" "+e+'-opacity="'+t.toFixed(2).slice(1)+'"':n}function to(r,e,t){let n=r+e;return typeof t<"u"&&(n+=" "+t),n}function dm(r,e,t){let n="",i=0,s=!1,o=0;for(let a=0;a<r.length;a++){let c=Math.floor(a%e),u=Math.floor(a/e);!c&&!s&&(s=!0),r[a]?(o++,a>0&&c>0&&r[a-1]||(n+=s?to("M",c+t,.5+u+t):to("m",i,0),i=0,s=!1),c+1<e&&r[a+1]||(n+=to("h",o),o=0)):i++}return n}_l.render=function(e,t,n){let i=um.getOptions(t),s=e.modules.size,o=e.modules.data,a=s+i.margin*2,c=i.color.light.a?"<path "+Ul(i.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",u="<path "+Ul(i.color.dark,"stroke")+' d="'+dm(o,s,i.margin)+'"/>',l='viewBox="0 0 '+a+" "+a+'"',h='<svg xmlns="http://www.w3.org/2000/svg" '+(i.width?'width="'+i.width+'" height="'+i.width+'" ':"")+l+' shape-rendering="crispEdges">'+c+u+`</svg>
1025
+ `;return typeof n=="function"&&n(null,h),h}});var io=B(jr=>{"use strict";var hm=Oc(),ro=Dl(),Nl=Ml(),fm=Ll();function no(r,e,t,n,i){let s=[].slice.call(arguments,1),o=s.length,a=typeof s[o-1]=="function";if(!a&&!hm())throw new Error("Callback required as last argument");if(a){if(o<2)throw new Error("Too few arguments provided");o===2?(i=t,t=e,e=n=void 0):o===3&&(e.getContext&&typeof i>"u"?(i=n,n=void 0):(i=n,n=t,t=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(t=e,e=n=void 0):o===2&&!e.getContext&&(n=t,t=e,e=void 0),new Promise(function(c,u){try{let l=ro.create(t,n);c(r(l,e,n))}catch(l){u(l)}})}try{let c=ro.create(t,n);i(null,r(c,e,n))}catch(c){i(c)}}jr.create=ro.create;jr.toCanvas=no.bind(null,Nl.render);jr.toDataURL=no.bind(null,Nl.renderToDataURL);jr.toString=no.bind(null,function(r,e,t){return fm.render(r,t)})});var pi={};A(pi,{DeviceSyncManager:()=>so});var so,mi=p(()=>{"use strict";so=class{constructor(){this.SYNC_STORAGE_KEY="w3pk_sync_info"}async getSyncInfo(){try{let e=localStorage.getItem(this.SYNC_STORAGE_KEY);return e?JSON.parse(e):null}catch(e){return console.error("Failed to get sync info:",e),null}}async updateSyncInfo(e){let t=await this.getSyncInfo(),n=this.detectPlatform(),i={deviceName:t?.deviceName||this.generateDeviceName(),platform:n,lastSyncTime:new Date().toISOString(),walletsSynced:t?.walletsSynced||[]};i.walletsSynced.includes(e)||i.walletsSynced.push(e),localStorage.setItem(this.SYNC_STORAGE_KEY,JSON.stringify(i))}detectPlatform(){let e=navigator.userAgent.toLowerCase();return/iphone|ipad|ipod/.test(e)?"ios":/android/.test(e)?"android":/mac/.test(e)?"macos":/win/.test(e)?"windows":/linux/.test(e)?"linux":"unknown"}generateDeviceName(){let e=this.detectPlatform(),t=new Date().toISOString().split("T")[0];return`${e}-device-${t}`}async exportForSync(e,t,n,i){let{BackupFileManager:s,generatePrfSalt:o,prfSyncInput:a}=await Promise.resolve().then(()=>(ce(),we)),{evaluatePrf:c}=await Promise.resolve().then(()=>(Ir(),ls)),{PrfUnsupportedError:u}=await Promise.resolve().then(()=>(T(),Hi)),l=new s;if(i){let{assertStrongPassword:m}=await Promise.resolve().then(()=>(Re(),ot));m(i)}let d=o(),h;try{({output:h}=await c(await a(d),t.id))}catch(m){if(m instanceof u&&i)return l.createPasswordBackup(e,i,t,n);throw m}try{return await l.createPrfBackup(e,t,n,d,h)}finally{new Uint8Array(h).fill(0)}}async importFromSync(e,t){let{BackupFileManager:n,prfSyncInput:i}=await Promise.resolve().then(()=>(ce(),we)),{PRF_INPUT:s}=await Promise.resolve().then(()=>(ge(),ja)),{evaluatePrf:o}=await Promise.resolve().then(()=>(Ir(),ls)),{verifyAssertionSignature:a}=await Promise.resolve().then(()=>(br(),Ha)),{SyncBootstrapError:c}=await Promise.resolve().then(()=>(T(),Hi)),u=new n;if(e.encryptionMethod!=="prf"||!e.prfSalt||!e.credential)throw new Error("This backup is not a PRF backup.");let l=e.credential.id,d=await o(await i(e.prfSalt),l,s),h;try{if(d.credentialId!==l)throw new c("CREDENTIAL_MISMATCH",d.credentialId);if(!await a(d.assertion,t,d.challenge))throw new c("PUBLIC_KEY_MISMATCH",l);h=await u.restoreWithPrf(e,d.output)}catch(m){throw d.secondOutput&&new Uint8Array(d.secondOutput).fill(0),m}finally{new Uint8Array(d.output).fill(0)}return await this.updateSyncInfo(h.ethereumAddress),{...h,walletPrfOutput:d.secondOutput}}async generateSyncQR(e){try{let t=await Promise.resolve().then(()=>W(io())),n=JSON.stringify(e);if(n.length>2953)throw new Error("Backup file too large for QR code. Use file transfer instead.");return t.toDataURL(n,{errorCorrectionLevel:"H",margin:2,width:512})}catch(t){throw t.code==="ERR_MODULE_NOT_FOUND"?new Error("QR code generation requires qrcode package: npm install qrcode"):t}}async parseSyncQR(e){let{BackupFileManager:t}=await Promise.resolve().then(()=>(ce(),we));return new t().parseBackupFile(e)}}});var zl={};A(zl,{PlatformDetector:()=>oo});var oo,Kl=p(()=>{"use strict";oo=class{async detectSyncCapabilities(){let e=this.detectPlatform(),t=await this.checkPasskeySync(),n=this.estimateDeviceCount();return{passkeysSync:t,platform:e,estimatedDevices:n,syncEnabled:t&&e!=="none"}}detectPlatform(){let e=navigator.userAgent.toLowerCase();return e.includes("mac")||e.includes("iphone")||e.includes("ipad")||e.includes("ipod")?"apple":e.includes("android")?"google":e.includes("windows")?"microsoft":"none"}async checkPasskeySync(){if(!window.PublicKeyCredential)return!1;try{return await PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}estimateDeviceCount(){return 1}getPlatformEducation(e){switch(e){case"apple":return`
312
1026
  \u{1F34E} Apple iCloud Keychain
313
1027
 
314
1028
  Your passkey automatically syncs across:
@@ -387,11 +1101,53 @@ This ensures you can recover if:
387
1101
  - Device is lost/stolen
388
1102
  - Device is damaged
389
1103
  - You switch devices
390
- `}}getSyncInstructions(e){switch(e){case"apple":return["Open Settings on your iPhone/iPad/Mac","Tap your name at the top",'Tap "iCloud"','Enable "Keychain"','Enable "iCloud Backup" (recommended)'];case"google":return["Open Chrome Settings",'Click "You and Google"','Enable "Sync"','Ensure "Passwords" is checked',"Sign in on other devices with same Google account"];case"microsoft":return["Windows Hello sync is limited","Consider using:","- Encrypted backup file","- Social recovery","- Cloud backup (password-protected)"];case"none":return["Platform sync not available","Use alternative backup methods:","- Create encrypted backup file","- Set up social recovery","- Save recovery phrase securely"]}}}});var tl=p(()=>{"use strict"});var rl={};x(rl,{DeviceManager:()=>as,DeviceSyncManager:()=>Ur,PlatformDetector:()=>cs,VaultSync:()=>os});var nl=p(()=>{"use strict";Xc();Zc();el();Nr();tl()});var Nt,sl=p(()=>{"use strict";Nt=class{getScenarios(){return[{type:"lost-device",description:"Your phone fell in the ocean"},{type:"lost-phrase",description:"Your paper backup burned in a fire"},{type:"lost-both",description:"Phone stolen AND forgot recovery phrase"},{type:"switch-platform",description:"Switching from iPhone to Android"}]}async simulateScenario(e,t){let n=[];switch(e.type){case"lost-device":t.passkeySync.enabled&&t.passkeySync.deviceCount>1&&n.push({method:`Passkey Sync (${t.passkeySync.platform})`,success:!0,time:"5 minutes",requirements:["Sign in to cloud account on new device","Authenticate with biometric/PIN"]}),t.recoveryPhrase.encryptedBackups.length>0&&t.recoveryPhrase.encryptedBackups.forEach(o=>{n.push({method:`Encrypted ${o.method.toUpperCase()} Backup`,success:!0,time:"2 minutes",requirements:["Backup file/QR code","Backup password"]})}),t.socialRecovery?.enabled&&n.push({method:"Social Recovery",success:!0,time:"24 hours",requirements:[`Contact ${t.socialRecovery.threshold} guardians`,"Collect shares from guardians","Verify identity with each guardian"]});break;case"lost-phrase":t.passkeySync.enabled&&n.push({method:"Passkey (current device)",success:!0,time:"Instant",requirements:["Access to current device","Biometric/PIN authentication"]}),t.passkeySync.deviceCount>1&&n.push({method:"Passkey Sync",success:!0,time:"5 minutes",requirements:["Any synced device","Biometric authentication"]}),t.recoveryPhrase.encryptedBackups.length>0&&n.push({method:"Encrypted Backup",success:!0,time:"2 minutes",requirements:["Backup file","Password"]}),t.socialRecovery?.enabled&&n.push({method:"Social Recovery",success:!0,time:"24 hours",requirements:[`${t.socialRecovery.threshold} guardian shares`]});break;case"lost-both":t.passkeySync.deviceCount>1&&n.push({method:"Passkey Sync",success:!0,time:"5 minutes",requirements:["Cloud account access","New device","Biometric setup"]}),t.socialRecovery?.enabled&&n.push({method:"Social Recovery",success:!0,time:"24 hours",requirements:[`${t.socialRecovery.threshold} guardian shares`,"Identity verification with guardians"]});break;case"switch-platform":t.recoveryPhrase.encryptedBackups.length>0&&n.push({method:"Encrypted Backup",success:!0,time:"2 minutes",requirements:["Backup file","Password"]}),t.socialRecovery?.enabled&&n.push({method:"Social Recovery",success:!0,time:"24 hours",requirements:[`${t.socialRecovery.threshold} guardian shares`]});break}let s=n.length>0,i=this.getEducationalNote(e,n,t);return{scenario:e,success:s,availableMethods:n,timeEstimate:s?this.estimateFastestRecovery(n):"Cannot recover",educationalNote:i}}estimateFastestRecovery(e){let t=e.map(n=>n.time.toLowerCase());if(t.some(n=>n.includes("instant")))return"Instant";if(t.some(n=>n.includes("minute"))){let n=t.filter(s=>s.includes("minute")).map(s=>parseInt(s));return`${Math.min(...n)} minutes`}return t.some(n=>n.includes("hour"))?"24 hours":"Unknown"}getEducationalNote(e,t,n){let s=n.securityScore.total,i=n.securityScore.level;if(t.length===0)return`
1104
+ `}}getSyncInstructions(e){switch(e){case"apple":return["Open Settings on your iPhone/iPad/Mac","Tap your name at the top",'Tap "iCloud"','Enable "Keychain"','Enable "iCloud Backup" (recommended)'];case"google":return["Open Chrome Settings",'Click "You and Google"','Enable "Sync"','Ensure "Passwords" is checked',"Sign in on other devices with same Google account"];case"microsoft":return["Windows Hello sync is limited","Consider using:","- Encrypted backup file","- Social recovery","- Cloud backup (password-protected)"];case"none":return["Platform sync not available","Use alternative backup methods:","- Create encrypted backup file","- Set up social recovery","- Save recovery phrase securely"]}}}});function pm(){let r=new Uint8Array(1);return crypto.getRandomValues(r),r[0]}function Ql(r,e,t){if(e>t)throw new Error("Threshold cannot be greater than total shares");if(e<2)throw new Error("Threshold must be at least 2");if(t>255)throw new Error("Cannot create more than 255 shares");let n=[];for(let i=0;i<t;i++)n[i]=new Uint8Array(r.length+1),n[i][0]=i+1;for(let i=0;i<r.length;i++){let o=[r[i]];for(let a=1;a<e;a++)o.push(pm());for(let a=0;a<t;a++){let c=a+1,u=yi.evaluatePolynomial(o,c);n[a][i+1]=u}}return n}function eu(r,e){if(r.length<e)throw new Error(`Need at least ${e} shares to recover secret, got ${r.length}`);let t=r.slice(0,e),n=t[0].length;for(let o of t)if(o.length!==n)throw new Error("All shares must have the same length");let i=n-1,s=new Uint8Array(i);for(let o=0;o<i;o++){let a=[];for(let c of t)a.push({x:c[0],y:c[o+1]});s[o]=yi.interpolate(a)}return s}function tu(r){return new TextEncoder().encode(r)}function ru(r){return new TextDecoder().decode(r)}function nu(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function iu(r){let e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2)e[t/2]=parseInt(r.substring(t,t+2),16);return e}var $e,yi,su=p(()=>{"use strict";$e=class $e{static multiply(e,t){return e===0||t===0?0:this.EXP_TABLE[(this.LOG_TABLE[e]+this.LOG_TABLE[t])%255]}static divide(e,t){if(t===0)throw new Error("Division by zero in GF(256)");return e===0?0:this.EXP_TABLE[(this.LOG_TABLE[e]-this.LOG_TABLE[t]+255)%255]}static add(e,t){return e^t}static evaluatePolynomial(e,t){let n=0;for(let i=e.length-1;i>=0;i--)n=this.add(this.multiply(n,t),e[i]);return n}static interpolate(e){let t=0;for(let n=0;n<e.length;n++){let i=e[n].y,s=1;for(let o=0;o<e.length;o++)n!==o&&(i=this.multiply(i,e[o].x),s=this.multiply(s,this.add(e[n].x,e[o].x)));t=this.add(t,this.divide(i,s))}return t}};$e.LOG_TABLE=[],$e.EXP_TABLE=[],(()=>{let e=(n,i)=>{let s=0;for(let o=0;o<8;o++){i&1&&(s^=n);let a=n&128;n<<=1,a&&(n^=283),i>>=1}return s&255},t=1;for(let n=0;n<255;n++)$e.EXP_TABLE[n]=t,$e.LOG_TABLE[t]=n,t=e(t,3);$e.EXP_TABLE[255]=$e.EXP_TABLE[0]})();yi=$e});var gi={};A(gi,{SocialRecovery:()=>uo});var uo,wi=p(()=>{"use strict";ce();T();su();uo=class{async splitAmongGuardians(e,t,n,i){if(n>t.length)throw new Error("Threshold cannot exceed number of guardians");if(n<2)throw new Error("Threshold must be at least 2 for security");if(t.length>255)throw new Error("Cannot have more than 255 guardians");let s=JSON.stringify(e),o=tu(s),a=Ql(o,n,t.length),c=t.map((u,l)=>({guardianId:crypto.randomUUID(),guardianName:u.name,shareData:nu(a[l]),shareIndex:l+1,threshold:n,createdAt:new Date().toISOString(),walletAddress:i}));return{threshold:n,totalShares:t.length,guardianShares:c,backupFile:e,setupDate:new Date().toISOString()}}async recoverFromShares(e){if(e.length<2)throw new Error("At least 2 shares required for recovery");let t=e[0].threshold,n=e[0].walletAddress;if(!t)throw new Error("Invalid share: missing threshold information");if(e.length<t)throw new Error(`Need at least ${t} shares to recover, but only ${e.length} provided`);if(!e.every(u=>u.walletAddress===n&&u.threshold===t))throw new Error("Shares are from different wallets or have inconsistent thresholds");let s=e.map(u=>iu(u.shareData)),o=eu(s,t),a=ru(o),c;try{c=JSON.parse(a)}catch{throw new Error("Recovered data is not a backup file - corrupted shares")}try{return Nt(c)}catch(u){throw u instanceof Te&&(u.backupFileJson=a),u}}async createGuardianInvitation(e,t){let n={type:"w3pk-guardian-share",version:1,guardianName:e.guardianName,walletAddress:e.walletAddress,shareData:e.shareData,shareIndex:e.shareIndex,threshold:e.threshold,createdAt:e.createdAt,message:t||`You have been chosen as a recovery guardian for wallet ${e.walletAddress.substring(0,10)}...`},i=JSON.stringify(n,null,2),s;try{s=await(await Promise.resolve().then(()=>W(io()))).toDataURL(i,{errorCorrectionLevel:"H",width:512})}catch(a){console.warn("QR code generation not available:",a)}let o=`
1105
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
1106
+ W3PK GUARDIAN RECOVERY SHARE
1107
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
1108
+
1109
+ Guardian: ${e.guardianName}
1110
+ Wallet Address: ${e.walletAddress}
1111
+ Share Index: ${e.shareIndex}
1112
+ Created: ${new Date(e.createdAt).toLocaleDateString()}
1113
+
1114
+ ${t||"You have been chosen as a recovery guardian for this wallet."}
1115
+
1116
+ IMPORTANT INSTRUCTIONS:
1117
+ -----------------------
1118
+
1119
+ 1. KEEP THIS SAFE
1120
+ This share is part of a social recovery system: the shares of any
1121
+ ${e.threshold} guardians combined recover the wallet.
1122
+
1123
+ 2. NEVER SHARE THIS ALONE
1124
+ A single share cannot recover the wallet - it's secure to store.
1125
+ However, keep it confidential to maintain the owner's security.
1126
+
1127
+ 3. WHEN NEEDED FOR RECOVERY
1128
+ The wallet owner will contact you and other guardians.
1129
+ You'll need to provide this share data for wallet recovery.
1130
+
1131
+ 4. STORAGE RECOMMENDATIONS
1132
+ \u2713 Save this file in a password manager
1133
+ \u2713 Print and store in a safe place
1134
+ \u2713 Save to encrypted cloud storage
1135
+ \u2717 Do NOT email unencrypted
1136
+ \u2717 Do NOT post publicly
1137
+
1138
+ SHARE DATA:
1139
+ -----------
1140
+ ${e.shareData}
1141
+
1142
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
1143
+ Generated by w3pk - Web3 Passkey SDK
1144
+ https://github.com/w3hc/w3pk
1145
+ \u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550
1146
+ `;return{qrCodeDataURL:s,shareDocument:o,shareJson:i}}parseGuardianShare(e){let t=JSON.parse(e);if(t.type!=="w3pk-guardian-share")throw new Error("Invalid guardian share format");if(!t.threshold)throw new Error("Invalid guardian share: missing threshold information");return{guardianId:crypto.randomUUID(),guardianName:t.guardianName,shareData:t.shareData,shareIndex:t.shareIndex,threshold:t.threshold,createdAt:t.createdAt,walletAddress:t.walletAddress}}async verifyRecovery(e){try{return await this.recoverFromShares(e),{canRecover:!0,recoveredAddress:e[0].walletAddress}}catch(t){return{canRecover:!1,error:t instanceof Error?t.message:"Unknown error"}}}createShareDownload(e){let t=JSON.stringify({type:"w3pk-guardian-share",version:1,guardianName:e.guardianName,walletAddress:e.walletAddress,shareData:e.shareData,shareIndex:e.shareIndex,threshold:e.threshold,createdAt:e.createdAt},null,2),n=new Blob([t],{type:"application/json"}),i=`w3pk-guardian-${e.guardianName.replace(/\s+/g,"-")}-share-${e.shareIndex}.json`;return{blob:n,filename:i}}}});var uu={};A(uu,{SEMAPHORE_PRF_LABEL:()=>ho,loadSemaphoreCommitment:()=>mm,loadSemaphoreSecretScalar:()=>fo});async function lu(){try{return(await import("@semaphore-protocol/identity")).Identity}catch(r){throw new x("Semaphore identities require @semaphore-protocol/identity. Install with: pnpm add @semaphore-protocol/identity",r)}}async function mm(){let r=await lu();return e=>{try{return new r(e).commitment}finally{e.fill(0)}}}async function fo(){let r=await lu();return e=>{try{return new r(e).secretScalar}finally{e.fill(0)}}}var ho,po=p(()=>{"use strict";T();ho="w3pk-semaphore-v1"});function ym(r){return r[Symbol.asyncIterator]!=null}function gm(r){if(ym(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var mo,du=p(()=>{"use strict";mo=gm});function wm(r){return r[Symbol.asyncIterator]!=null}function bm(r,e=1){return e=Number(e),wm(r)?(async function*(){let t=[];if(e<1&&(e=1),e!==Math.round(e))throw new Error("Batch size must be an integer");for await(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)})():(function*(){let t=[];if(e<1&&(e=1),e!==Math.round(e))throw new Error("Batch size must be an integer");for(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)})()}var bi,yo=p(()=>{"use strict";bi=bm});async function*Hr(r,e=1){for await(let t of bi(r,e)){let n=t.map(async i=>i().then(s=>({ok:!0,value:s}),s=>({ok:!1,err:s})));for(let i=0;i<n.length;i++){let s=await n[i];if(s.ok)yield s.value;else throw s.err}}}var go=p(()=>{"use strict";yo()});function Ue(r=0){return new Uint8Array(r)}function ie(r=0){return new Uint8Array(r)}var bt=p(()=>{"use strict"});function km(r){return r?.buffer instanceof ArrayBuffer}function hu(r){if(km(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}var fu=p(()=>{"use strict"});function $r(r,e){e==null&&(e=r.reduce((i,s)=>i+s.length,0));let t=ie(e),n=0;for(let i of r)t.set(i,n),n+=i.length;return hu(t)}var wo=p(()=>{"use strict";bt();fu()});function pu(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var mu=p(()=>{"use strict"});function yu(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let i=t+n.byteLength;if(e<i)return{buf:n,index:e-t};t=i}throw new RangeError("index is out of bounds")}function ki(r){return!!r?.[wu]}var wu,gu,Wt,bu=p(()=>{"use strict";bt();wo();mu();wu=Symbol.for("@achingbrain/uint8arraylist");Wt=class r{constructor(...e){f(this,"bufs");f(this,"length");f(this,gu,!0);this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[(gu=wu,Symbol.iterator)](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(ki(n)){t+=n.byteLength;for(let i of n.bufs)this.bufs.push(i)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(ki(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=yu(this.bufs,e);return t.buf[t.index]}set(e,t){let n=yu(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(ki(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:i}=this._subList(e,t);return $r(n,i)}subarray(e,t){let{bufs:n,length:i}=this._subList(e,t);return n.length===1?n[0]:$r(n,i)}sublist(e,t){let{bufs:n,length:i}=this._subList(e,t),s=new r;return s.length=i,s.bufs=n,s}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],i=0;for(let s=0;s<this.bufs.length;s++){let o=this.bufs[s],a=i,c=a+o.byteLength;if(i=c,e>=c)continue;let u=e>=a&&e<c,l=t>a&&t<=c;if(u&&l){if(e===a&&t===c){n.push(o);break}let d=e-a;n.push(o.subarray(d,d+(t-e)));break}if(u){if(e===0){n.push(o);continue}n.push(o.subarray(e-a));continue}if(l){if(t===c){n.push(o);break}n.push(o.subarray(0,t-a));break}n.push(o)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!ki(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let i=n.byteLength;if(i===0)throw new TypeError("search must be at least 1 byte long");let s=256,o=new Int32Array(s);for(let d=0;d<s;d++)o[d]=-1;for(let d=0;d<i;d++)o[n[d]]=d;let a=o,c=this.byteLength-n.byteLength,u=n.byteLength-1,l;for(let d=t;d<=c;d+=l){l=0;for(let h=u;h>=0;h--){let m=this.get(d+h);if(n[h]!==m){l=Math.max(1,h-a[m]);break}}if(l===0)return d}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=ie(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let i=Ue(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt16(0,t,n),this.write(i,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let i=Ue(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setInt32(0,t,n),this.write(i,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let i=Ue(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigInt64(0,t,n),this.write(i,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=ie(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let i=Ue(2);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint16(0,t,n),this.write(i,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let i=Ue(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setUint32(0,t,n),this.write(i,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let i=Ue(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setBigUint64(0,t,n),this.write(i,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let i=Ue(4);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat32(0,t,n),this.write(i,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let i=Ue(8);new DataView(i.buffer,i.byteOffset,i.byteLength).setFloat64(0,t,n),this.write(i,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!pu(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((i,s)=>i+s.byteLength,0)),n.length=t,n}}});var bo,xi,Si,ku,Ai,xu,Su,Au,vu,Eu,Pu,Iu,Gr=p(()=>{"use strict";bo=BigInt(34),xi=8,Si=262144,ku="links-bytes",Ai=262144,xu=1048576,Su=50,Au=10,vu=!0,Eu=!0,Pu=!1,Iu="file"});var Cu,Bu=p(()=>{"use strict";bu();Gr();Cu=(r={})=>{let e=r.chunkSize??Ai;return async function*(n){let i=new Wt,s=0,o=!1;for await(let a of n)for(i.append(a),s+=a.length;s>=e;)if(yield i.subarray(0,e),o=!0,e===i.length)i=new Wt,s=0;else{let u=new Wt;u.append(i.sublist(e)),i=u,s-=e}(!o||s>0)&&(yield i.subarray(0,s))}}});function Tu(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function be(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return kt(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return kt(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function Ru(r){return new TextEncoder().encode(r)}function Du(r){return new TextDecoder().decode(r)}function xm(r){return r?.buffer instanceof ArrayBuffer}function kt(r){return xm(r)?r:r.slice()}var Fb,Ge=p(()=>{"use strict";Fb=new Uint8Array(0)});function Sm(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var i=0;i<r.length;i++){var s=r.charAt(i),o=s.charCodeAt(0);if(t[o]!==255)throw new TypeError(s+" is ambiguous");t[o]=i}var a=r.length,c=r.charAt(0),u=Math.log(a)/Math.log(256),l=Math.log(256)/Math.log(a);function d(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var w=0,k=0,b=0,S=y.length;b!==S&&y[b]===0;)b++,w++;for(var v=(S-b)*l+1>>>0,I=new Uint8Array(v);b!==S;){for(var U=y[b],q=0,L=v-1;(U!==0||q<k)&&L!==-1;L--,q++)U+=256*I[L]>>>0,I[L]=U%a>>>0,U=U/a>>>0;if(U!==0)throw new Error("Non-zero carry");k=q,b++}for(var j=v-k;j!==v&&I[j]===0;)j++;for(var It=c.repeat(w);j<v;++j)It+=r.charAt(I[j]);return It}function h(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;var w=0;if(y[w]!==" "){for(var k=0,b=0;y[w]===c;)k++,w++;for(var S=(y.length-w)*u+1>>>0,v=new Uint8Array(S);y[w];){var I=t[y.charCodeAt(w)];if(I===255)return;for(var U=0,q=S-1;(I!==0||U<b)&&q!==-1;q--,U++)I+=a*v[q]>>>0,v[q]=I%256>>>0,I=I/256>>>0;if(I!==0)throw new Error("Non-zero carry");b=U,w++}if(y[w]!==" "){for(var L=S-b;L!==S&&v[L]===0;)L++;for(var j=new Uint8Array(k+(S-L)),It=k;L!==S;)j[It++]=v[L++];return j}}}function m(y){var w=h(y);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:m}}var Am,vm,Mu,Uu=p(()=>{"use strict";Am=Sm,vm=Am,Mu=vm});function _u(r,e){return new So({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}function Ht({name:r,prefix:e,encode:t,decode:n}){return new Ao(r,e,t,n)}function Ve({name:r,prefix:e,alphabet:t}){let{encode:n,decode:i}=Mu(t,r);return Ht({prefix:e,name:r,encode:n,decode:s=>be(i(s))})}function Em(r,e,t,n){let i=r.length;for(;r[i-1]==="=";)--i;let s=new Uint8Array(i*t/8|0),o=0,a=0,c=0;for(let u=0;u<i;++u){let l=e[r[u]];if(l===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|l,o+=t,o>=8&&(o-=8,s[c++]=255&a>>o)}if(o>=t||(255&a<<8-o)!==0)throw new SyntaxError("Unexpected end of data");return s}function Pm(r,e,t){let n=e[e.length-1]==="=",i=(1<<t)-1,s="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,s+=e[i&a>>o];if(o!==0&&(s+=e[i&a<<t-o]),n)for(;(s.length*t&7)!==0;)s+="=";return s}function Im(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function N({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let i=Im(n);return Ht({prefix:e,name:r,encode(s){return Pm(s,n,t)},decode(s){return Em(s,i,t,r)}})}var ko,xo,So,Ao,ke=p(()=>{"use strict";Ge();Uu();ko=class{constructor(e,t,n){f(this,"name");f(this,"prefix");f(this,"baseEncode");this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},xo=class{constructor(e,t,n){f(this,"name");f(this,"prefix");f(this,"baseDecode");f(this,"prefixCodePoint");this.name=e,this.prefix=t;let i=t.codePointAt(0);if(i===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=i,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return _u(this,e)}},So=class{constructor(e){f(this,"decoders");this.decoders=e}or(e){return _u(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};Ao=class{constructor(e,t,n,i){f(this,"name");f(this,"prefix");f(this,"baseEncode");f(this,"baseDecode");f(this,"encoder");f(this,"decoder");this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=i,this.encoder=new ko(e,t,n),this.decoder=new xo(e,t,i)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}});var vo={};A(vo,{base32:()=>$t,base32hex:()=>Rm,base32hexpad:()=>Fm,base32hexpadupper:()=>Mm,base32hexupper:()=>Dm,base32pad:()=>Bm,base32padupper:()=>Tm,base32upper:()=>Cm,base32z:()=>Um});var $t,Cm,Bm,Tm,Rm,Dm,Fm,Mm,Um,Eo=p(()=>{"use strict";ke();$t=N({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Cm=N({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Bm=N({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Tm=N({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Rm=N({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Dm=N({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Fm=N({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Mm=N({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Um=N({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var Po={};A(Po,{base36:()=>Vr,base36upper:()=>_m});var Vr,_m,Io=p(()=>{"use strict";ke();Vr=Ve({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),_m=Ve({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var Co={};A(Co,{base58btc:()=>Ce,base58flickr:()=>Lm});var Ce,Lm,Bo=p(()=>{"use strict";ke();Ce=Ve({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Lm=Ve({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});function zu(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Om;)e[t++]=r&255|Lu,r/=128;for(;r&Km;)e[t++]=r&255|Lu,r>>>=7;return e[t]=r|0,zu.bytes=t-n+1,e}function To(r,n){var t=0,n=n||0,i=0,s=n,o,a=r.length;do{if(s>=a)throw To.bytes=0,new RangeError("Could not decode varint");o=r[s++],t+=i<28?(o&Nu)<<i:(o&Nu)*Math.pow(2,i),i+=7}while(o>=jm);return To.bytes=s-n,t}var Nm,Lu,zm,Km,Om,qm,jm,Nu,Wm,Hm,$m,Gm,Vm,Ym,Jm,Zm,Xm,Qm,ey,ty,Yr,Ku=p(()=>{"use strict";Nm=zu,Lu=128,zm=127,Km=~zm,Om=Math.pow(2,31);qm=To,jm=128,Nu=127;Wm=Math.pow(2,7),Hm=Math.pow(2,14),$m=Math.pow(2,21),Gm=Math.pow(2,28),Vm=Math.pow(2,35),Ym=Math.pow(2,42),Jm=Math.pow(2,49),Zm=Math.pow(2,56),Xm=Math.pow(2,63),Qm=function(r){return r<Wm?1:r<Hm?2:r<$m?3:r<Gm?4:r<Vm?5:r<Ym?6:r<Jm?7:r<Zm?8:r<Xm?9:10},ey={encode:Nm,decode:qm,encodingLength:Qm},ty=ey,Yr=ty});function Jr(r,e=0){return[Yr.decode(r,e),Yr.decode.bytes]}function Gt(r,e,t=0){return Yr.encode(r,e,t),e}function Vt(r){return Yr.encodingLength(r)}var Ei=p(()=>{"use strict";Ku()});function Jt(r,e){let t=e.byteLength,n=Vt(r),i=n+Vt(t),s=new Uint8Array(i+t);return Gt(r,s,0),Gt(t,s,n),s.set(e,i),new Yt(r,t,e,s)}function Ou(r){let e=be(r),[t,n]=Jr(e),[i,s]=Jr(e.subarray(n)),o=e.subarray(n+s);if(o.byteLength!==i)throw new Error("Incorrect length");return new Yt(t,i,o,e)}function qu(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Tu(r.bytes,t.bytes)}}var Yt,Xr=p(()=>{"use strict";Ge();Ei();Yt=class{constructor(e,t,n,i){f(this,"code");f(this,"size");f(this,"digest");f(this,"bytes");this.code=e,this.size=t,this.digest=kt(n),this.bytes=kt(i)}}});var Ro=p(()=>{"use strict"});function ju(r,e){let{bytes:t,version:n}=r;return n===0?ny(t,Do(r),e??Ce.encoder):iy(t,Do(r),e??$t.encoder)}function Do(r){let e=Wu.get(r);if(e==null){let t=new Map;return Wu.set(r,t),t}return e}function ry(r,e){switch(r[0]){case"Q":{let t=e??Ce;return[Ce.prefix,t.decode(`${Ce.prefix}${r}`)]}case Ce.prefix:{let t=e??Ce;return[Ce.prefix,t.decode(r)]}case $t.prefix:{let t=e??$t;return[$t.prefix,t.decode(r)]}case Vr.prefix:{let t=e??Vr;return[Vr.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function ny(r,e,t){let{prefix:n}=t;if(n!==Ce.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let i=e.get(n);if(i==null){let s=t.encode(r).slice(1);return e.set(n,s),s}else return i}function iy(r,e,t){let{prefix:n}=t,i=e.get(n);if(i==null){let s=t.encode(r);return e.set(n,s),s}else return i}function Hu(r,e,t){let n=Vt(r),i=n+Vt(e),s=new Uint8Array(i+t.byteLength);return Gt(r,s,0),Gt(e,s,n),s.set(t,i),s}var Wu,$u,se,Qr,sy,oy,Zt=p(()=>{"use strict";Eo();Io();Bo();Ge();Xr();Ei();Ro();Wu=new WeakMap;se=class r{constructor(e,t,n,i){f(this,"code");f(this,"version");f(this,"multihash");f(this,"bytes");f(this,"/");f(this,$u,"CID");this.code=t,this.version=e,this.multihash=n,this.bytes=kt(i),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Qr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==sy)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Jt(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&qu(e.multihash,n.multihash)}toString(e){return ju(this,e)}toJSON(){return{"/":ju(this)}}link(){return this}[($u=Symbol.toStringTag,Symbol.for("nodejs.util.inspect.custom"))](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:i,multihash:s,bytes:o}=t;return new r(n,i,s,o??Hu(n,i,s.bytes))}else if(t[oy]===!0){let{version:n,multihash:i,code:s}=t,o=Ou(i);return r.create(n,s,o)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Qr)throw new Error(`Version 0 CID must use dag-pb (code: ${Qr}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let i=Hu(e,t,n.bytes);return new r(e,t,n,i)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Qr,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,i=be(e.subarray(n,n+t.multihashSize));if(i.byteLength!==t.multihashSize)throw new Error("Incorrect length");let s=i.subarray(t.multihashSize-t.digestSize),o=new Yt(t.multihashCode,t.digestSize,s,i);return[t.version===0?r.createV0(o):r.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,h]=Jr(e.subarray(t));return t+=h,d},i=n(),s=Qr;if(i===18?(i=0,t=0):s=n(),i!==0&&i!==1)throw new RangeError(`Invalid CID version ${i}`);let o=t,a=n(),c=n(),u=t+c,l=u-o;return{version:i,codec:s,multihashCode:a,digestSize:c,multihashSize:l,size:u}}static parse(e,t){let[n,i]=ry(e,t),s=r.decode(i);if(s.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Do(s).set(n,e),s}};Qr=112,sy=18;oy=Symbol.for("@ipld/js-cid/CID")});function Fo(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let i=r[e++];if(t+=n<28?(i&127)<<n:(i&127)*2**n,i<128)break}return[t,e]}function Pi(r,e){let t;[t,e]=Fo(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function Gu(r,e){let t;return[t,e]=Fo(r,e),[t&7,t>>3,e]}function cy(r){let e={},t=r.length,n=0;for(;n<t;){let i,s;if([i,s,n]=Gu(r,n),s===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=Pi(r,n)}else if(s===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(i!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let o;[o,n]=Pi(r,n),e.Name=ay.decode(o)}else if(s===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(i!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${i}) for Tsize`);[e.Tsize,n]=Fo(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${s}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function Vu(r){let e=r.length,t=0,n,i=!1,s;for(;t<e;){let a,c;if([a,c,t]=Gu(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(s)throw new Error("protobuf: (PBNode) duplicate Data section");[s,t]=Pi(r,t),n&&(i=!0)}else if(c===2){if(i)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let u;[u,t]=Pi(r,t),n.push(cy(u))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let o={};return s&&(o.Data=s),o.Links=n||[],o}var ay,Yu=p(()=>{"use strict";ay=new TextDecoder});function uy(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=en(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=Zu.encode(r.Name);t-=n.length,e.set(n,t),t=en(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=en(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function Xu(r){let e=hy(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=en(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let i=r.Links.length-1;i>=0;i--){let s=uy(r.Links[i],t.subarray(0,n));n-=s,n=en(t,n,s)-1,t[n]=18}return t}function dy(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+Xt(t)}if(typeof r.Name=="string"){let t=Zu.encode(r.Name).length;e+=1+t+Xt(t)}return typeof r.Tsize=="number"&&(e+=1+Xt(r.Tsize)),e}function hy(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+Xt(t)}if(r.Links)for(let t of r.Links){let n=dy(t);e+=1+n+Xt(n)}return e}function en(r,e,t){e-=Xt(t);let n=e;for(;t>=ly;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function Xt(r){return r%2===0&&r++,Math.floor((fy(r)+6)/7)}function fy(r){let e=0;return r>=Ju&&(r=Math.floor(r/Ju),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+py[r]}var Zu,Ju,ly,py,Qu=p(()=>{"use strict";Zu=new TextEncoder,Ju=2**32,ly=2**31;py=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8]});function td(r,e){if(r===e)return 0;let t=r.Name?Mo.encode(r.Name):[],n=e.Name?Mo.encode(e.Name):[],i=t.length,s=n.length;for(let o=0,a=Math.min(i,s);o<a;++o)if(t[o]!==n[o]){i=t[o],s=n[o];break}return i<s?-1:s<i?1:0}function ed(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function rd(r){if(typeof r.asCID=="object"){let t=se.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=se.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=se.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=se.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function X(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=Mo.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(rd),e.Links.sort(td);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function Uo(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!ed(r,my))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!ed(t,yy))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&td(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function nd(r,e=[]){return X({Data:r,Links:e})}function id(r,e,t){return rd({Hash:t,Name:r,Tsize:e})}function sd(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var my,yy,Mo,od=p(()=>{"use strict";Zt();my=["Data","Links"],yy=["Hash","Name","Tsize"],Mo=new TextEncoder});var tn={};A(tn,{code:()=>wy,createLink:()=>id,createNode:()=>nd,decode:()=>by,encode:()=>Q,name:()=>gy,prepare:()=>X,validate:()=>Uo});function Q(r){Uo(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),Xu(e)}function by(r){let e=sd(r),t=Vu(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(i=>{let s={};try{s.Hash=se.decode(i.Hash)}catch{}if(!s.Hash)throw new Error("Invalid Hash field found in link, expected CID");return i.Name!==void 0&&(s.Name=i.Name),i.Tsize!==void 0&&(s.Tsize=i.Tsize),s})),n}var gy,wy,xt=p(()=>{"use strict";Zt();Yu();Qu();od();gy="dag-pb",wy=112});var Qt,rn,_o=p(()=>{"use strict";Qt=class Qt extends Error{constructor(t="Invalid type"){super(t);f(this,"name",Qt.name);f(this,"code",Qt.code)}};f(Qt,"name","InvalidTypeError"),f(Qt,"code","ERR_INVALID_TYPE");rn=Qt});function nn(r){if(r<ky)return 1;if(r<xy)return 2;if(r<Sy)return 3;if(r<ad)return 4;if(r<cd)return 5;if(r<ld)return 6;if(r<ud)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function dd(r,e,t=0){switch(nn(r)){case 8:e[t++]=r&255|Y,r/=128;case 7:e[t++]=r&255|Y,r/=128;case 6:e[t++]=r&255|Y,r/=128;case 5:e[t++]=r&255|Y,r/=128;case 4:e[t++]=r&255|Y,r>>>=7;case 3:e[t++]=r&255|Y,r>>>=7;case 2:e[t++]=r&255|Y,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function hd(r,e){let t=r[e],n=0;if(n+=t&Ye,t<Y||(t=r[e+1],n+=(t&Ye)<<7,t<Y)||(t=r[e+2],n+=(t&Ye)<<14,t<Y)||(t=r[e+3],n+=(t&Ye)<<21,t<Y)||(t=r[e+4],n+=(t&Ye)*ad,t<Y)||(t=r[e+5],n+=(t&Ye)*cd,t<Y)||(t=r[e+6],n+=(t&Ye)*ld,t<Y)||(t=r[e+7],n+=(t&Ye)*ud,t<Y))return n;throw new RangeError("Could not decode varint")}var ky,xy,Sy,ad,cd,ld,ud,Y,Ye,Lo=p(()=>{"use strict";bt();ky=Math.pow(2,7),xy=Math.pow(2,14),Sy=Math.pow(2,21),ad=Math.pow(2,28),cd=Math.pow(2,35),ld=Math.pow(2,42),ud=Math.pow(2,49),Y=128,Ye=127});function Ay(r){return r.buffer instanceof ArrayBuffer}function fd(r){return Ay(r)?r:r.slice()}var pd=p(()=>{"use strict"});function md(r,e,t){No[0]=r,e[t]=Je[0],e[t+1]=Je[1],e[t+2]=Je[2],e[t+3]=Je[3]}function yd(r,e){return Je[0]=r[e],Je[1]=r[e+1],Je[2]=r[e+2],Je[3]=r[e+3],No[0]}function gd(r,e,t){zo[0]=r,e[t]=G[0],e[t+1]=G[1],e[t+2]=G[2],e[t+3]=G[3],e[t+4]=G[4],e[t+5]=G[5],e[t+6]=G[6],e[t+7]=G[7]}function wd(r,e){return G[0]=r[e],G[1]=r[e+1],G[2]=r[e+2],G[3]=r[e+3],G[4]=r[e+4],G[5]=r[e+5],G[6]=r[e+6],G[7]=r[e+7],zo[0]}var No,Je,zo,G,Ko=p(()=>{"use strict";No=new Float32Array([-0]),Je=new Uint8Array(No.buffer);zo=new Float64Array([-0]),G=new Uint8Array(zo.buffer)});var vy,Ey,oe,St,bd,Oo=p(()=>{"use strict";vy=BigInt(Number.MAX_SAFE_INTEGER),Ey=BigInt(Number.MIN_SAFE_INTEGER),oe=class r{constructor(e,t){f(this,"lo");f(this,"hi");this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return St;if(e<vy&&e>Ey)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,i=e-(n<<32n);return t&&(n=~n|0n,i=~i|0n,++i>bd&&(i=0n,++n>bd&&(n=0n))),new r(Number(i),Number(n))}static fromNumber(e){if(e===0)return St;let t=e<0;t&&(e=-e);let n=e>>>0,i=(e-n)/4294967296>>>0;return t&&(i=~i>>>0,n=~n>>>0,++n>4294967295&&(n=0,++i>4294967295&&(i=0))),new r(n,i)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):St}},St=new oe(0,0);St.toBigInt=function(){return 0n};St.zzEncode=St.zzDecode=function(){return this};St.length=function(){return 1};bd=4294967296n});function kd(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function xd(r,e,t){if(t-e<1)return"";let i,s=[],o=0,a;for(;e<t;)a=r[e++],a<128?s[o++]=a:a>191&&a<224?s[o++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,s[o++]=55296+(a>>10),s[o++]=56320+(a&1023)):s[o++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,o>8191&&((i??(i=[])).push(String.fromCharCode.apply(String,s)),o=0);return i!=null?(o>0&&i.push(String.fromCharCode.apply(String,s.slice(0,o))),i.join("")):String.fromCharCode.apply(String,s.slice(0,o))}function qo(r,e,t){let n=t,i,s;for(let o=0;o<r.length;++o)i=r.charCodeAt(o),i<128?e[t++]=i:i<2048?(e[t++]=i>>6|192,e[t++]=i&63|128):(i&64512)===55296&&((s=r.charCodeAt(o+1))&64512)===56320?(i=65536+((i&1023)<<10)+(s&1023),++o,e[t++]=i>>18|240,e[t++]=i>>12&63|128,e[t++]=i>>6&63|128,e[t++]=i&63|128):(e[t++]=i>>12|224,e[t++]=i>>6&63|128,e[t++]=i&63|128);return t-n}var jo=p(()=>{"use strict"});function xe(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Ii(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}function sn(r){return new Wo(r instanceof Uint8Array?r:r.subarray())}var Wo,Ci=p(()=>{"use strict";Lo();pd();Ko();Oo();jo();Wo=class{constructor(e){f(this,"buf");f(this,"pos");f(this,"len");f(this,"_slice",Uint8Array.prototype.subarray);this.buf=fd(e),this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,xe(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw xe(this,4);return Ii(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw xe(this,4);return Ii(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw xe(this,4);let e=yd(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw xe(this,4);let e=wd(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw xe(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return xd(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw xe(this,e);this.pos+=e}else do if(this.pos>=this.len)throw xe(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new oe(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw xe(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw xe(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw xe(this,8);let e=Ii(this.buf,this.pos+=4),t=Ii(this.buf,this.pos+=4);return new oe(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=hd(this.buf,this.pos);return this.pos+=nn(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}});function on(r,e,t){let n=sn(r);return e.decode(n,void 0,t)}var Ad=p(()=>{"use strict";Ci()});var Ho={};A(Ho,{base10:()=>Py});var Py,vd=p(()=>{"use strict";ke();Py=Ve({prefix:"9",name:"base10",alphabet:"0123456789"})});var $o={};A($o,{base16:()=>Iy,base16upper:()=>Cy});var Iy,Cy,Ed=p(()=>{"use strict";ke();Iy=N({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Cy=N({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var Go={};A(Go,{base2:()=>By});var By,Pd=p(()=>{"use strict";ke();By=N({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var Vo={};A(Vo,{base256emoji:()=>My});function Dy(r){return r.reduce((e,t)=>(e+=Ty[t],e),"")}function Fy(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let i=Ry[n];if(i==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(i)}return new Uint8Array(e)}var Id,Ty,Ry,My,Cd=p(()=>{"use strict";ke();Id=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),Ty=Id.reduce((r,e,t)=>(r[t]=e,r),[]),Ry=Id.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);My=Ht({prefix:"\u{1F680}",name:"base256emoji",encode:Dy,decode:Fy})});var Yo={};A(Yo,{base64:()=>Uy,base64pad:()=>_y,base64url:()=>Ly,base64urlpad:()=>Ny});var Uy,_y,Ly,Ny,Bd=p(()=>{"use strict";ke();Uy=N({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),_y=N({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Ly=N({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Ny=N({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var Jo={};A(Jo,{base8:()=>zy});var zy,Td=p(()=>{"use strict";ke();zy=N({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var Zo={};A(Zo,{identity:()=>Ky});var Ky,Rd=p(()=>{"use strict";Ge();ke();Ky=Ht({prefix:"\0",name:"identity",encode:r=>Du(r),decode:r=>Ru(r)})});var R1,D1,Dd=p(()=>{"use strict";R1=new TextEncoder,D1=new TextDecoder});var an={};A(an,{code:()=>Bi,decode:()=>Wy,encode:()=>jy,name:()=>qy});function jy(r){return be(r)}function Wy(r){return be(r)}var qy,Bi,Ti=p(()=>{"use strict";Ge();qy="raw",Bi=85});var Xo={};A(Xo,{identity:()=>Gy});function $y(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Jt(Fd,Md(r))}var Fd,Hy,Md,Gy,Ud=p(()=>{"use strict";Ge();Xr();Fd=0,Hy="identity",Md=be;Gy={code:Fd,name:Hy,encode:Md,digest:$y}});function At({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:i}){return new Qo(r,e,t,n,i)}function _d(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Jt(e,r)}var Vy,Qo,Ri=p(()=>{"use strict";Xr();Vy=20;Qo=class{constructor(e,t,n,i,s){f(this,"name");f(this,"code");f(this,"encode");f(this,"minDigestLength");f(this,"maxDigestLength");this.name=e,this.code=t,this.encode=n,this.minDigestLength=i??Vy,this.maxDigestLength=s}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?_d(n,this.code,t?.truncate):n.then(i=>_d(i,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}}});var ta={};A(ta,{sha256:()=>ea,sha512:()=>Yy});function Nd(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var ea,Yy,ra=p(()=>{"use strict";Ri();ea=At({name:"sha2-256",code:18,encode:Nd("SHA-256")}),Yy=At({name:"sha2-512",code:19,encode:Nd("SHA-512")})});var zd=p(()=>{"use strict"});var Kd=p(()=>{"use strict"});var Od=p(()=>{"use strict"});var qd=p(()=>{"use strict"});var jd=p(()=>{"use strict";zd();Kd();Od();Ro();qd()});var Wd=p(()=>{"use strict";Ge();Zt();Xr();Ri();Ei();jd()});var na,$1,Hd=p(()=>{"use strict";vd();Ed();Pd();Cd();Eo();Io();Bo();Bd();Td();Rd();Dd();Ti();Ud();ra();Wd();na={...Zo,...Go,...Jo,...Ho,...$o,...vo,...Po,...Co,...Yo,...Vo},$1={...ta,...Xo}});function Gd(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var $d,ia,Jy,Vd,Yd=p(()=>{"use strict";Hd();bt();$d=Gd("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ia=Gd("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=ie(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Jy={utf8:$d,"utf-8":$d,hex:na.base16,latin1:ia,ascii:ia,binary:ia,...na},Vd=Jy});function er(r,e="utf8"){let t=Vd[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Di=p(()=>{"use strict";Yd()});function sa(r){let e=r??8192,t=e>>>1,n,i=e;return function(o){if(o<1||o>t)return ie(o);i+o>e&&(n=ie(e),i=0);let a=n.subarray(i,i+=o);return(i&7)!==0&&(i=(i|7)+1),a}}var Jd=p(()=>{"use strict";bt()});function oa(){}function Xy(r){return globalThis.Buffer!=null?ie(r):Zy(r)}function aa(r,e,t){e[t]=r&255}function Qy(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function Fi(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function cn(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function eg(r,e,t){e.set(r,t)}function tg(r,e,t){e.set(r,t)}function rg(r,e,t){r.length<40?qo(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(er(r),t)}function ua(){return new ln}var vt,ca,Zy,ln,la,da=p(()=>{"use strict";Lo();bt();Di();Ko();Oo();Jd();jo();vt=class{constructor(e,t,n){f(this,"fn");f(this,"len");f(this,"next");f(this,"val");this.fn=e,this.len=t,this.next=void 0,this.val=n}};ca=class{constructor(e){f(this,"head");f(this,"tail");f(this,"len");f(this,"next");this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},Zy=sa();ln=class{constructor(){f(this,"len");f(this,"head");f(this,"tail");f(this,"states");this.len=0,this.head=new vt(oa,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new vt(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new la((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Fi,10,oe.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=oe.fromBigInt(e);return this._push(Fi,t.length(),t)}uint64Number(e){return this._push(dd,nn(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=oe.fromBigInt(e).zzEncode();return this._push(Fi,t.length(),t)}sint64Number(e){let t=oe.fromNumber(e).zzEncode();return this._push(Fi,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(aa,1,e?1:0)}fixed32(e){return this._push(cn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=oe.fromBigInt(e);return this._push(cn,4,t.lo)._push(cn,4,t.hi)}fixed64Number(e){let t=oe.fromNumber(e);return this._push(cn,4,t.lo)._push(cn,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(md,4,e)}double(e){return this._push(gd,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(aa,1,0):this.uint32(t)._push(eg,t,e)}string(e){let t=kd(e);return t!==0?this.uint32(t)._push(qo,t,e):this._push(aa,1,0)}fork(){return this.states=new ca(this),this.head=this.tail=new vt(oa,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new vt(oa,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=Xy(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};la=class extends vt{constructor(t,n){super(Qy,t,n);f(this,"next");this.next=void 0}};globalThis.Buffer!=null&&(ln.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(tg,e,r),this},ln.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(rg,e,r),this})});function un(r,e){let t=ua();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var Zd=p(()=>{"use strict";da()});function*dn(r,e,t){let n=sn(r);yield*e.stream(n,void 0,"$",t)}var Xd=p(()=>{"use strict";Ci()});function Ui(r,e,t,n,i){return{name:r,type:e,encode:t,decode:n,stream:i}}var Mi,ha=p(()=>{"use strict";Mi={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5}});function fa(r){function e(s){if(r[s.toString()]==null)throw new Error("Invalid enum value");return r[s]}let t=function(o,a){let c=e(o);a.int32(c)},n=function(o){let a=o.int32();return e(a)},i=function*(o){let a=o.int32();yield e(a)};return Ui("enum",Mi.VARINT,t,n,i)}var Qd=p(()=>{"use strict";ha()});function hn(r,e,t){return Ui("message",Mi.LENGTH_DELIMITED,r,e,t)}var eh=p(()=>{"use strict";ha()});var fn,th=p(()=>{"use strict";Ad();Zd();Xd();Qd();eh();Ci();da();fn=class extends Error{constructor(){super(...arguments);f(this,"code","ERR_MAX_LENGTH");f(this,"name","MaxLengthError")}}});var Se,pn,rh,nh=p(()=>{"use strict";th();(function(r){let e;(function(a){a.Raw="Raw",a.Directory="Directory",a.File="File",a.Metadata="Metadata",a.Symlink="Symlink",a.HAMTShard="HAMTShard"})(e=r.DataType||(r.DataType={}));let t;(function(a){a[a.Raw=0]="Raw",a[a.Directory=1]="Directory",a[a.File=2]="File",a[a.Metadata=3]="Metadata",a[a.Symlink=4]="Symlink",a[a.HAMTShard=5]="HAMTShard"})(t||(t={})),(function(a){a.codec=()=>fa(t)})(e=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=hn((a,c,u={})=>{if(u.lengthDelimited!==!1&&c.fork(),a.Type!=null&&(c.uint32(8),r.DataType.codec().encode(a.Type,c)),a.Data!=null&&(c.uint32(18),c.bytes(a.Data)),a.filesize!=null&&(c.uint32(24),c.uint64(a.filesize)),a.blocksizes!=null&&a.blocksizes.length>0)for(let l of a.blocksizes)c.uint32(32),c.uint64(l);a.hashType!=null&&(c.uint32(40),c.uint64(a.hashType)),a.fanout!=null&&(c.uint32(48),c.uint64(a.fanout)),a.mode!=null&&(c.uint32(56),c.uint32(a.mode)),a.mtime!=null&&(c.uint32(66),pn.codec().encode(a.mtime,c)),u.lengthDelimited!==!1&&c.ldelim()},(a,c,u={})=>{let l={blocksizes:[]},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let h=a.uint32();switch(h>>>3){case 1:{l.Type=r.DataType.codec().decode(a);break}case 2:{l.Data=a.bytes();break}case 3:{l.filesize=a.uint64();break}case 4:{if(u.limits?.blocksizes!=null&&l.blocksizes.length===u.limits.blocksizes)throw new fn('Decode error - repeated field "blocksizes" had too many elements');l.blocksizes.push(a.uint64());break}case 5:{l.hashType=a.uint64();break}case 6:{l.fanout=a.uint64();break}case 7:{l.mode=a.uint32();break}case 8:{l.mtime=pn.codec().decode(a,a.uint32(),{limits:u.limits?.mtime});break}default:{a.skipType(h&7);break}}}return l},function*(a,c,u,l={}){let d={blocksizes:0},h=c==null?a.len:a.pos+c;for(;a.pos<h;){let m=a.uint32();switch(m>>>3){case 1:{yield{field:`${u}.Type`,value:r.DataType.codec().decode(a)};break}case 2:{yield{field:`${u}.Data`,value:a.bytes()};break}case 3:{yield{field:`${u}.filesize`,value:a.uint64()};break}case 4:{if(l.limits?.blocksizes!=null&&d.blocksizes===l.limits.blocksizes)throw new fn('Streaming decode error - repeated field "blocksizes" had too many elements');yield{field:`${u}.blocksizes[]`,index:d.blocksizes,value:a.uint64()},d.blocksizes++;break}case 5:{yield{field:`${u}.hashType`,value:a.uint64()};break}case 6:{yield{field:`${u}.fanout`,value:a.uint64()};break}case 7:{yield{field:`${u}.mode`,value:a.uint32()};break}case 8:{yield*pn.codec().stream(a,a.uint32(),`${u}.mtime`,{limits:l.limits?.mtime});break}default:{a.skipType(m&7);break}}}})),n);function i(a){return un(a,r.codec())}r.encode=i;function s(a,c){return on(a,r.codec(),c)}r.decode=s;function o(a,c){return dn(a,r.codec(),c)}r.stream=o})(Se||(Se={}));(function(r){let e;r.codec=()=>(e==null&&(e=hn((s,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),s.Seconds!=null&&(o.uint32(8),o.int64(s.Seconds)),s.FractionalNanoseconds!=null&&(o.uint32(21),o.fixed32(s.FractionalNanoseconds)),a.lengthDelimited!==!1&&o.ldelim()},(s,o,a={})=>{let c={},u=o==null?s.len:s.pos+o;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{c.Seconds=s.int64();break}case 2:{c.FractionalNanoseconds=s.fixed32();break}default:{s.skipType(l&7);break}}}return c},function*(s,o,a,c={}){let u=o==null?s.len:s.pos+o;for(;s.pos<u;){let l=s.uint32();switch(l>>>3){case 1:{yield{field:`${a}.Seconds`,value:s.int64()};break}case 2:{yield{field:`${a}.FractionalNanoseconds`,value:s.fixed32()};break}default:{s.skipType(l&7);break}}}})),e);function t(s){return un(s,r.codec())}r.encode=t;function n(s,o){return on(s,r.codec(),o)}r.decode=n;function i(s,o){return dn(s,r.codec(),o)}r.stream=i})(pn||(pn={}));(function(r){let e;r.codec=()=>(e==null&&(e=hn((s,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),s.MimeType!=null&&(o.uint32(10),o.string(s.MimeType)),a.lengthDelimited!==!1&&o.ldelim()},(s,o,a={})=>{let c={},u=o==null?s.len:s.pos+o;for(;s.pos<u;){let l=s.uint32();l>>>3===1?c.MimeType=s.string():s.skipType(l&7)}return c},function*(s,o,a,c={}){let u=o==null?s.len:s.pos+o;for(;s.pos<u;){let l=s.uint32();l>>>3===1?yield{field:`${a}.MimeType`,value:s.string()}:s.skipType(l&7)}})),e);function t(s){return un(s,r.codec())}r.encode=t;function n(s,o){return on(s,r.codec(),o)}r.decode=n;function i(s,o){return dn(s,r.codec(),o)}r.stream=i})(rh||(rh={}))});var ih,ng,sh,oh,J,tr=p(()=>{"use strict";_o();nh();_o();ih={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},ng=["directory","hamt-sharded-directory"],sh=parseInt("0644",8),oh=parseInt("0755",8),J=class r{constructor(e={type:"file"}){f(this,"type");f(this,"data");f(this,"blockSizes");f(this,"hashType");f(this,"fanout");f(this,"mtime");f(this,"_mode");f(this,"_originalMode");let{type:t,data:n,blockSizes:i,hashType:s,fanout:o,mtime:a,mode:c}=e;if(t!=null&&!Object.values(ih).includes(t))throw new rn("Type: "+t+" is not valid");this.type=t??"file",this.data=n,this.hashType=s,this.fanout=o,this.blockSizes=i??[],this._originalMode=0,this.mode=c,this.mtime=a}static unmarshal(e){let t=Se.decode(e),n=new r({type:ih[t.Type!=null?t.Type.toString():"File"],data:t.Data,blockSizes:t.blocksizes,mode:t.mode,mtime:t.mtime!=null?{secs:t.mtime.Seconds??0n,nsecs:t.mtime.FractionalNanoseconds}:void 0,fanout:t.fanout});return n._originalMode=t.mode??0,n}set mode(e){e==null?this._mode=this.isDirectory()?oh:sh:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return ng.includes(this.type)}addBlockSize(e){this.blockSizes.push(e)}removeBlockSize(e){this.blockSizes.splice(e,1)}fileSize(){if(this.isDirectory())return 0n;let e=0n;return this.blockSizes.forEach(t=>{e+=t}),this.data!=null&&(e+=BigInt(this.data.length)),e}marshal(){let e;switch(this.type){case"raw":e=Se.DataType.Raw;break;case"directory":e=Se.DataType.Directory;break;case"file":e=Se.DataType.File;break;case"metadata":e=Se.DataType.Metadata;break;case"symlink":e=Se.DataType.Symlink;break;case"hamt-sharded-directory":e=Se.DataType.HAMTShard;break;default:throw new rn(`Type: ${e} is not valid`)}let t=this.data;(this.data==null||this.data.length===0)&&(t=void 0);let n;this.mode!=null&&(n=this._originalMode&4294963200|(this.mode??0),n===sh&&!this.isDirectory()&&(n=void 0),n===oh&&this.isDirectory()&&(n=void 0));let i;return this.mtime!=null&&(i={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),Se.encode({Type:e,Data:t,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:i})}}});var _e,_i=p(()=>{"use strict";_e=class extends Event{constructor(t,n){super(t);f(this,"type");f(this,"detail");this.type=t,this.detail=n}}});var ue,rr=p(()=>{"use strict";xt();Zt();ra();ue=async(r,e,t)=>{t.codec==null&&(t.codec=tn);let n=await ea.digest(r),i=se.create(t.cidVersion??1,t.codec.code,n);return await e.put(i,r,t),i}});function ch(r){return async function*(t,n){let i=0n;for await(let s of t.content)yield async()=>{let o,a={codec:tn,cidVersion:r.cidVersion,onProgress:r.onProgress};r.rawLeaves?(a.codec=an,a.cidVersion=1):(o=new J({type:r.leafType,data:s}),s=Q({Data:o.marshal(),Links:[]}));let c=await ue(s,n,a);return i+=BigInt(s.byteLength),r.onProgress?.(new _e("unixfs:importer:progress:file:write",{bytesWritten:i,cid:c,path:t.path})),{cid:c,unixfs:o,size:BigInt(s.length),block:s}}}}var lh=p(()=>{"use strict";xt();tr();Ti();_i();rr()});var nr,cr,ir,pa,sr,ma,or,ya,ar,Ae,Ze,mn=p(()=>{"use strict";nr=class nr extends Error{constructor(t="Invalid parameters"){super(t);f(this,"name",nr.name);f(this,"code",nr.code)}};f(nr,"name","InvalidParametersError"),f(nr,"code","ERR_INVALID_PARAMS");cr=nr,ir=class ir extends Error{constructor(t="Invalid avg chunk size"){super(t);f(this,"name",ir.name);f(this,"code",ir.code)}};f(ir,"name","InvalidAvgChunkSizeError"),f(ir,"code","ERR_INVALID_AVG_CHUNK_SIZE");pa=ir,sr=class sr extends Error{constructor(t="Invalid chunk size"){super(t);f(this,"name",sr.name);f(this,"code",sr.code)}};f(sr,"name","InvalidChunkSizeError"),f(sr,"code","ERR_INVALID_CHUNK_SIZE");ma=sr,or=class or extends Error{constructor(t="Invalid min chunk size"){super(t);f(this,"name",or.name);f(this,"code",or.code)}};f(or,"name","InvalidMinChunkSizeError"),f(or,"code","ERR_INVALID_MIN_CHUNK_SIZE");ya=or,ar=class ar extends Error{constructor(t="Invalid content"){super(t);f(this,"name",ar.name);f(this,"code",ar.code)}};f(ar,"name","InvalidContentError"),f(ar,"code","ERR_INVALID_CONTENT");Ae=ar,Ze=class extends Error{constructor(){super(...arguments);f(this,"name",Ae.name);f(this,"code",Ae.code)}};f(Ze,"name","InvalidShardingStrategyError"),f(Ze,"code","ERR_SHARDING_STRATEGY")});var uh,dh=p(()=>{"use strict";xt();tr();rr();uh=async(r,e,t)=>{let n=new J({type:"directory",mtime:r.mtime,mode:r.mode}),i=Q(X({Data:n.marshal()})),s=await ue(i,e,t),o=r.path;return{cid:s,path:o,unixfs:n,size:BigInt(i.length),originalPath:r.originalPath,block:i}}});async function*ig(r,e,t){let n=-1,i;for await(let s of Hr(t.bufferImporter(r,e),t.blockWriteConcurrency)){if(n++,n===0){i={...s,single:!0};continue}else n===1&&i!=null&&(yield{...i,block:void 0,single:void 0},i=void 0);yield{...s,block:void 0}}i!=null&&(yield i)}function hh(r){return r.single===!0}var sg,fh,ph=p(()=>{"use strict";xt();tr();go();Ti();_i();rr();sg=(r,e,t)=>async function(i){if(i.length===1&&hh(i[0])&&t.reduceSingleLeafToSelf){let l=i[0],d=l.block;return hh(l)&&(r.mtime!==void 0||r.mode!==void 0)&&(l.unixfs=new J({type:"file",mtime:r.mtime,mode:r.mode,data:l.block}),d={Data:l.unixfs.marshal(),Links:[]},l.block=Q(X(d)),l.cid=await ue(l.block,e,{...t,cidVersion:t.cidVersion}),l.size=BigInt(l.block.length)),t.onProgress?.(new _e("unixfs:importer:progress:file:layout",{cid:l.cid,path:r.originalPath})),{cid:l.cid,path:r.path,unixfs:l.unixfs,size:l.size,originalPath:r.originalPath}}let s=new J({type:"file",mtime:r.mtime,mode:r.mode}),o=i.filter(l=>l.cid.code===Bi&&l.size>0||l.unixfs!=null&&l.unixfs.data==null&&l.unixfs.fileSize()>0n?!0:!!l.unixfs?.data?.length).map(l=>l.cid.code===Bi?(s.addBlockSize(l.size),{Name:"",Tsize:Number(l.size),Hash:l.cid}):(l.unixfs?.data==null?s.addBlockSize(l.unixfs?.fileSize()??0n):s.addBlockSize(BigInt(l.unixfs.data.length)),{Name:"",Tsize:Number(l.size),Hash:l.cid})),a={Data:s.marshal(),Links:o},c=Q(X(a)),u=await ue(c,e,t);return t.onProgress?.(new _e("unixfs:importer:progress:file:layout",{cid:u,path:r.originalPath})),{cid:u,path:r.path,unixfs:s,size:BigInt(c.length+a.Links.reduce((l,d)=>l+(d.Tsize??0),0)),originalPath:r.originalPath,block:c}},fh=async(r,e,t)=>t.layout(ig(r,e,t),sg(r,e,t))});function og(r){return Symbol.iterator in r}function ag(r){return Symbol.asyncIterator in r}function cg(r){try{if(r instanceof Uint8Array)return(async function*(){yield r})();if(og(r))return(async function*(){yield*r})();if(ag(r))return r}catch{throw new Ae("Content was invalid")}throw new Ae("Content was invalid")}function mh(r){return async function*(t,n){for await(let i of t){let s;if(i.path!=null&&(s=i.path,i.path=i.path.split("/").filter(o=>o!=null&&o!==".").join("/")),lg(i)){let o={path:i.path,mtime:i.mtime,mode:i.mode,content:(async function*(){let c=0n;for await(let u of r.chunker(r.chunkValidator(cg(i.content)))){let l=BigInt(u.byteLength);c+=l,r.onProgress?.(new _e("unixfs:importer:progress:file:read",{bytesRead:c,chunkSize:l,path:i.path})),yield u}})(),originalPath:s},a=r.fileBuilder??fh;yield async()=>a(o,n,r)}else if(i.path!=null){let o={path:i.path,mtime:i.mtime,mode:i.mode,originalPath:s},a=r.dirBuilder??uh;yield async()=>a(o,n,r)}else throw new Error("Import candidate must have content or path or both")}}}function lg(r){return r.content!=null}var yh=p(()=>{"use strict";_i();mn();dh();ph()});var gh,wh=p(()=>{"use strict";Di();mn();gh=()=>async function*(e){for await(let t of e){if(t.length===void 0)throw new Ae("Content was invalid");if(typeof t=="string"||t instanceof String)yield er(t.toString());else if(Array.isArray(t))yield Uint8Array.from(t);else if(t instanceof Uint8Array)yield t;else throw new Ae("Content was invalid")}}});function ga(r){let e=r?.maxChildrenPerNode??ug;return async function t(n,i){let s=[];for await(let o of bi(n,e))s.push(await i(o));return s.length>1?t(s,i):s[0]}}var ug,bh=p(()=>{"use strict";yo();ug=174});var kh=p(()=>{"use strict";bh()});var Be,Li=p(()=>{"use strict";Zt();Be=class{constructor(e,t){f(this,"options");f(this,"root");f(this,"dir");f(this,"path");f(this,"dirty");f(this,"flat");f(this,"parent");f(this,"parentKey");f(this,"unixfs");f(this,"mode");f(this,"mtime");f(this,"cid");f(this,"size");f(this,"nodeSize");this.options=t??{},this.root=e.root,this.dir=e.dir,this.path=e.path,this.dirty=e.dirty,this.flat=e.flat,this.parent=e.parent,this.parentKey=e.parentKey,this.unixfs=e.unixfs,this.mode=e.mode,this.mtime=e.mtime}}});function hg(r){let e=0;return r>=4294967296&&(r=Math.floor(r/4294967296),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+dg[r]}function Xe(r){return r%2===0&&r++,Math.floor((hg(r)+6)/7)}function Ni(r){let e=0;for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);n<128?e++:n<2048?e+=2:n>=55296&&n<=56319&&t+1<r.length?(t++,e+=4):e+=3}return e}function xh(r,e,t){let n=1+Xe(e)+e;return n+=1+Xe(r)+r,n+=1+Xe(t),1+Xe(n)+n}function Sh(r,e){let t=2;if(r!==void 0&&r!==fg&&(t+=1+Xe(r)),e!=null){let n=0,i=Number(e.secs);i<0?n+=11:n+=1+Xe(i),e.nsecs!=null&&(n+=5),t+=1+Xe(n)+n}return 1+Xe(t)+t}var dg,fg,Ah=p(()=>{"use strict";dg=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];fg=493});function wa(r,e){return e?.cid!=null&&e?.size!=null?r+e.cid.byteLength:0}function ba(r,e){return e?.cid!=null&&e?.size!=null?xh(r,e.cid.byteLength,Number(e.size)):0}var Et,ka=p(()=>{"use strict";xt();tr();Li();xa();Ah();rr();Et=class extends Be{constructor(t,n){super(t,n);f(this,"_children");this._children=new Map}async put(t,n){if(this.nodeSize!==void 0){let i=this._children.get(t),s=Ni(t),o=this.options?.shardSplitStrategy;if(o==="links-bytes")this.nodeSize-=wa(s,i),this.nodeSize+=wa(s,n);else if(o==="block-bytes")this.nodeSize-=ba(s,i),this.nodeSize+=ba(s,n);else throw new Ze(`Invalid shardSplitStrategy: ${o}`);this.nodeSize<0&&(this.nodeSize=void 0)}this.cid=void 0,this.size=void 0,this._children.set(t,n)}async get(t){return Promise.resolve(this._children.get(t))}childCount(){return this._children.size}directChildrenCount(){return this.childCount()}onlyChild(){return this._children.values().next().value}*eachChildSeries(){for(let[t,n]of this._children.entries())yield{key:t,child:n}}marshal(){let t=new J({type:"directory",mtime:this.mtime,mode:this.mode}),n=[];for(let[s,o]of this._children.entries())if(!(o.size==null||o.cid==null)){if(o.cid==null)throw new Error("Directory contents must be flushed before marshaling");n.push({Hash:o.cid,Name:s,Tsize:o.size==null?void 0:Number(o.size)})}let i={Data:t.marshal(),Links:n};return Q(X(i))}async estimateNodeSize(){if(this.nodeSize!==void 0)return this.nodeSize;let t=this.options?.shardSplitStrategy;if(t==="links-bytes"){this.nodeSize=0;for(let[n,i]of this._children.entries())this.nodeSize+=wa(Ni(n),i)}else if(t==="block-bytes"){this.nodeSize=Sh(this.mode,this.mtime);for(let[n,i]of this._children.entries())this.nodeSize+=ba(Ni(n),i)}else throw new Ze(`Invalid shardSplitStrategy: ${t}`);return this.nodeSize}async*flush(t){let n=[];for(let[u,l]of this._children.entries()){let d=l;if(l instanceof Be)for await(let h of l.flush(t))d=h,yield h;d.size!=null&&d.cid!=null&&n.push({Name:u,Tsize:Number(d.size),Hash:d.cid})}let i=new J({type:"directory",mtime:this.mtime,mode:this.mode}),s={Data:i.marshal(),Links:n},o=Q(X(s)),a=await ue(o,t,this.options),c=o.length+s.Links.reduce((u,l)=>u+(l.Tsize??0),0);this.cid=a,this.size=c,yield{cid:a,unixfs:i,path:this.path,size:BigInt(c)}}}});function Qe(r,e){let t=r.lo+e.lo>>>0,n=r.hi+e.hi+(t<r.lo?1:0)>>>0;return{lo:t,hi:n}}function pg(r,e){return r+e>>>0}function de(r,e){let t=r.lo&65535,n=r.lo>>>16,i=e.lo&65535,s=e.lo>>>16,o=t*i,a=t*s,c=n*i,u=n*s,l=(o>>>16)+(a&65535)+(c&65535)>>>0,d=(l<<16|o&65535)>>>0,h=u+(a>>>16)+(c>>>16)+(l>>>16),m=Math.imul(r.lo,e.hi),y=Math.imul(r.hi,e.lo),w=h+m+y>>>0;return{lo:d,hi:w}}function Pt(r,e){return Math.imul(r,e)>>>0}function lr(r,e){if(e===0)return r;if(e===32)return{lo:r.hi,hi:r.lo};if(e<32){let i=(r.lo<<e|r.hi>>>32-e)>>>0,s=(r.hi<<e|r.lo>>>32-e)>>>0;return{lo:i,hi:s}}e-=32;let t=(r.hi<<e|r.lo>>>32-e)>>>0,n=(r.lo<<e|r.hi>>>32-e)>>>0;return{lo:t,hi:n}}function _(r,e){return{lo:(r.lo^e.lo)>>>0,hi:(r.hi^e.hi)>>>0}}function Sa(r,e){if(e===0)return r;if(e<32){let t=(r.lo>>>e|r.hi<<32-e)>>>0,n=r.hi>>>e;return{lo:t,hi:n}}return{lo:r.hi>>>e-32,hi:0}}function R(r,e){return{lo:r>>>0,hi:e>>>0}}function Aa(r,e){return(r<<e|r>>>32-e)>>>0}function vh(r,e){let t=e*8,n=r[t]|r[t+1]<<8|r[t+2]<<16|r[t+3]<<24,i=r[t+4]|r[t+5]<<8|r[t+6]<<16|r[t+7]<<24;return{lo:n>>>0,hi:i>>>0}}function mg(r,e){let t=e*4;return(r[t]|r[t+1]<<8|r[t+2]<<16|r[t+3]<<24)>>>0}function Eh(r){return r=_(r,Sa(r,33)),r=de(r,R(3981806797,4283543511)),r=_(r,Sa(r,33)),r=de(r,R(444984403,3301882366)),r=_(r,Sa(r,33)),r}function yg(r){return r^=r>>>16,r=Pt(r,2246822507),r^=r>>>13,r=Pt(r,3266489909),r^=r>>>16,r}function va(r,e=0){let t=R(e,0),n=R(e,0),i=r.length,s=Math.floor(i/16),o=R(289559509,2277735313),a=R(658871167,1291169091);for(let h=0;h<s;h++){let m=vh(r,h*2),y=vh(r,h*2+1);m=de(m,o),m=lr(m,31),m=de(m,a),t=_(t,m),t=lr(t,27),t=Qe(t,n),t=Qe(de(t,R(5,0)),R(1390208809,0)),y=de(y,a),y=lr(y,33),y=de(y,o),n=_(n,y),n=lr(n,31),n=Qe(n,t),n=Qe(de(n,R(5,0)),R(944331445,0))}let c=R(0,0),u=R(0,0),l=r.slice(s*16);switch(l.length){case 15:u=_(u,R(0,l[14]<<16));case 14:u=_(u,R(0,l[13]<<8));case 13:u=_(u,R(0,l[12]));case 12:u=_(u,R(l[11]<<24,0));case 11:u=_(u,R(l[10]<<16,0));case 10:u=_(u,R(l[9]<<8,0));case 9:u=_(u,R(l[8],0)),u=de(u,a),u=lr(u,33),u=de(u,o),n=_(n,u);case 8:c=_(c,R(0,l[7]<<24));case 7:c=_(c,R(0,l[6]<<16));case 6:c=_(c,R(0,l[5]<<8));case 5:c=_(c,R(0,l[4]));case 4:c=_(c,R(l[3]<<24,0));case 3:c=_(c,R(l[2]<<16,0));case 2:c=_(c,R(l[1]<<8,0));case 1:c=_(c,R(l[0],0)),c=de(c,o),c=lr(c,31),c=de(c,a),t=_(t,c)}let d=R(i,0);return t=_(t,d),n=_(n,d),t=Qe(t,n),n=Qe(n,t),t=Eh(t),n=Eh(n),t=Qe(t,n),n=Qe(n,t),new Uint8Array([t.hi>>>24&255,t.hi>>>16&255,t.hi>>>8&255,t.hi&255,t.lo>>>24&255,t.lo>>>16&255,t.lo>>>8&255,t.lo&255,n.hi>>>24&255,n.hi>>>16&255,n.hi>>>8&255,n.hi&255,n.lo>>>24&255,n.lo>>>16&255,n.lo>>>8&255,n.lo&255])}function Ph(r,e=0){let t=e>>>0,n=r.length,i=Math.floor(n/4),s=3432918353,o=461845907;for(let u=0;u<i;u++){let l=mg(r,u);l=Pt(l,s),l=Aa(l,15),l=Pt(l,o),t^=l,t=Aa(t,13),t=pg(Pt(t,5),3864292196)}let a=r.slice(i*4),c=0;switch(a.length){case 3:c^=a[2]<<16;case 2:c^=a[1]<<8;case 1:c^=a[0],c=Pt(c,s),c=Aa(c,15),c=Pt(c,o),t^=c}return t^=n,t=yg(t),t}var Ih=p(()=>{"use strict"});function wg(r){let e=new Array(4);for(let t=0;t<4;t++)e[t]=r&255,r=r>>8;return new Uint8Array(e)}var Ik,Ch,Ck,Bh=p(()=>{"use strict";Ri();Ih();Ik=At({name:"murmur3-32",code:35,encode:r=>wg(Ph(r))}),Ch=At({name:"murmur3-128",code:34,encode:r=>va(r)}),Ck=At({name:"murmur3-x64-64",code:34,encode:r=>va(r).subarray(0,8)})});var ur,zi,Th=p(()=>{"use strict";ur=class ur extends Error{constructor(t="Not Found"){super(t);f(this,"name",ur.name);f(this,"code",ur.code)}};f(ur,"name","NotFoundError"),f(ur,"code","ERR_NOT_FOUND");zi=ur});var Rh=p(()=>{"use strict";Th()});var Ki,Dh=p(()=>{"use strict";Ki=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,bytes:i}of e)await this.put(n,i,t),yield n}get(e,t){throw new Error(".get is not implemented")}async*getMany(e,t){for await(let n of e)yield{cid:n,bytes:this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}}});var Oi,Fh=p(()=>{"use strict";Rh();Dh();Oi=class extends Ki{put(e,t,n){return n?.signal?.throwIfAborted(),e}get(e,t){throw t?.signal?.throwIfAborted(),new zi}has(e,t){return t?.signal?.throwIfAborted(),!1}async delete(e,t){t?.signal?.throwIfAborted()}async*getAll(e){e?.signal?.throwIfAborted()}}});var _h=B((zk,Uh)=>{"use strict";Uh.exports=class{constructor(){this._bitArrays=[],this._data=[],this._length=0,this._changedLength=!1,this._changedData=!1}set(e,t){let n=this._internalPositionFor(e,!1);if(t===void 0)n!==-1&&(this._unsetInternalPos(n),this._unsetBit(e),this._changedLength=!0,this._changedData=!0);else{let i=!1;n===-1?(n=this._data.length,this._setBit(e),this._changedData=!0):i=!0,this._setInternalPos(n,e,t,i),this._changedLength=!0}}unset(e){this.set(e,void 0)}get(e){this._sortData();let t=this._internalPositionFor(e,!0);if(t!==-1)return this._data[t][1]}push(e){return this.set(this.length,e),this.length}get length(){if(this._sortData(),this._changedLength){let e=this._data[this._data.length-1];this._length=e?e[0]+1:0,this._changedLength=!1}return this._length}forEach(e){let t=0;for(;t<this.length;)e(this.get(t),t,this),t++}map(e){let t=0,n=new Array(this.length);for(;t<this.length;)n[t]=e(this.get(t),t,this),t++;return n}reduce(e,t){let n=0,i=t;for(;n<this.length;){let s=this.get(n);i=e(i,s,n),n++}return i}find(e){let t=0,n,i;for(;t<this.length&&!n;)i=this.get(t),n=e(i),t++;return n?i:void 0}_internalPositionFor(e,t){let n=this._bytePosFor(e,t);if(n>=this._bitArrays.length)return-1;let i=this._bitArrays[n],s=e-n*7;if(!((i&1<<s)>0))return-1;let a=this._bitArrays.slice(0,n).reduce(bg,0),c=~(4294967295<<s+1),u=Mh(i&c);return a+u-1}_bytePosFor(e,t){let n=Math.floor(e/7),i=n+1;for(;!t&&this._bitArrays.length<i;)this._bitArrays.push(0);return n}_setBit(e){let t=this._bytePosFor(e,!1);this._bitArrays[t]|=1<<e-t*7}_unsetBit(e){let t=this._bytePosFor(e,!1);this._bitArrays[t]&=~(1<<e-t*7)}_setInternalPos(e,t,n,i){let s=this._data,o=[t,n];if(i)this._sortData(),s[e]=o;else{if(s.length)if(s[s.length-1][0]>=t)s.push(o);else if(s[0][0]<=t)s.unshift(o);else{let a=Math.round(s.length/2);this._data=s.slice(0,a).concat(o).concat(s.slice(a))}else this._data.push(o);this._changedData=!0,this._changedLength=!0}}_unsetInternalPos(e){this._data.splice(e,1)}_sortData(){this._changedData&&this._data.sort(kg),this._changedData=!1}bitField(){let e=[],t=8,n=0,i=0,s,o=this._bitArrays.slice();for(;o.length||n;){n===0&&(s=o.shift(),n=7);let c=Math.min(n,t),u=~(255<<c),l=s&u;i|=l<<8-t,s=s>>>c,n-=c,t-=c,(!t||!n&&!o.length)&&(e.push(i),i=0,t=8)}for(var a=e.length-1;a>0&&e[a]===0;a--)e.pop();return e}compactArray(){return this._sortData(),this._data.map(xg)}};function bg(r,e){return r+Mh(e)}function Mh(r){let e=r;return e=e-(e>>1&1431655765),e=(e&858993459)+(e>>2&858993459),(e+(e>>4)&252645135)*16843009>>24}function kg(r,e){return r[0]-e[0]}function xg(r){return r[1]}});function Sg(r){return!!r}function Ag(r,e){return r.key}function vg(r){return r}async function Nh(r,e,t){let n=[];for(let i of r._children.compactArray())if(i instanceof et)await Nh(i,e,t);else{let s=await e(i);n.push({bitField:r._children.bitField(),children:s})}return t(n)}var Lh,et,zh=p(()=>{"use strict";Lh=W(_h(),1);Di();et=class r{constructor(e,t,n=0){f(this,"_options");f(this,"_popCount");f(this,"_parent");f(this,"_posAtParent");f(this,"_children");f(this,"key");this._options=e,this._popCount=0,this._parent=t,this._posAtParent=n,this._children=new Lh.default,this.key=null}async put(e,t){let n=await this._findNewBucketAndPos(e);n.bucket._putAt(n,e,t)}async get(e){let t=await this._findChild(e);if(t!=null)return t.value}async del(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);n!=null&&n.key===e&&t.bucket._delAt(t.pos)}leafCount(){return this._children.compactArray().reduce((t,n)=>n instanceof r?t+n.leafCount():t+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let e=this._children.compactArray();for(let t of e)t instanceof r?yield*t.eachLeafSeries():yield t}serialize(e,t){let n=[];return t(this._children.reduce((i,s,o)=>(s!=null&&(s instanceof r?i.push(s.serialize(e,t)):i.push(e(s,o))),i),n))}async asyncTransform(e,t){return Nh(this,e,t)}toJSON(){return this.serialize(Ag,vg)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);if(!(n instanceof r)&&n!=null&&n.key===e)return n}async _findPlace(e){let t=this._options.hash(typeof e=="string"?er(e):e),n=await t.take(this._options.bits),i=this._children.get(n);return i instanceof r?i._findPlace(t):{bucket:this,pos:n,hash:t,existingChild:i}}async _findNewBucketAndPos(e){let t=await this._findPlace(e);if(t.existingChild!=null&&t.existingChild.key!==e){let n=new r(this._options,t.bucket,t.pos);t.bucket._putObjectAt(t.pos,n);let i=await n._findPlace(t.existingChild.hash);return i.bucket._putAt(i,t.existingChild.key,t.existingChild.value),n._findNewBucketAndPos(t.hash)}return t}_putAt(e,t,n){this._putObjectAt(e.pos,{key:t,value:n,hash:e.hash})}_putObjectAt(e,t){this._children.get(e)==null&&this._popCount++,this._children.set(e,t)}_delAt(e){if(e===-1)throw new Error("Invalid position");this._children.get(e)!=null&&this._popCount--,this._children.unset(e),this._level()}_level(){if(this._parent!=null&&this._popCount<=1)if(this._popCount===1){let e=this._children.find(Sg);if(e!=null&&!(e instanceof r)){let t=e.hash;t.untake(this._options.bits);let n={pos:this._posAtParent,hash:t,bucket:this._parent};this._parent._putAt(n,e.key,e.value)}}else this._parent._delAt(this._posAtParent)}_at(e){return this._children.get(e)}}});function Ig(r,e,t){let n=Cg(e,t);return(r&n)>>>e}function Cg(r,e){return Eg[r]&Pg[Math.min(e+r-1,7)]}var Eg,Pg,qi,Kh=p(()=>{"use strict";Eg=[255,254,252,248,240,224,192,128],Pg=[1,3,7,15,31,63,127,255],qi=class{constructor(e){f(this,"_value");f(this,"_currentBytePos");f(this,"_currentBitPos");this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let i=this._value[this._currentBytePos],s=this._currentBitPos+1,o=Math.min(s,t),a=Ig(i,s-o,o);n=(n<<o)+a,t-=o,this._currentBitPos-=o,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}}});function Oh(r){function e(t){return t instanceof ji?t:new ji(t,r)}return e}var ji,qh=p(()=>{"use strict";wo();Kh();ji=class{constructor(e,t){f(this,"_value");f(this,"_hashFn");f(this,"_depth");f(this,"_availableBits");f(this,"_currentBufferIndex");f(this,"_buffers");if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits<t;)await this._produceMoreBits();let n=0;for(;t>0;){let i=this._buffers[this._currentBufferIndex],s=Math.min(i.availableBits(),t),o=i.take(s);n=(n<<s)+o,t-=s,this._availableBits-=s,i.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],i=Math.min(n.totalBits()-n.availableBits(),t);n.untake(i),t-=i,this._availableBits+=i,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?$r([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new qi(t);this._buffers.push(n),this._availableBits+=n.availableBits()}}});function jh(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:Oh(r.hashFn)};return new et(e)}var Wh=p(()=>{"use strict";zh();qh()});async function Bg(r){return(await Ch.encode(r)).slice(0,8).reverse()}async function*$h(r,e,t,n){let i=r._children,s=(r.tableSize()-1).toString(16).length,o=[],a=0n;for(let y=0;y<i.length;y++){let w=i.get(y);if(w==null)continue;let k=y.toString(16).toUpperCase().padStart(s,"0");if(w instanceof et){let b;for await(let S of $h(w,e,null,n))b=S;if(b==null)throw new Error("Could not flush sharded directory, no sub-shard found");o.push({Name:k,Tsize:Number(b.size),Hash:b.cid}),a+=b.size}else if(Gh(w.value)){let b=w.value,S;for await(let I of b.flush(e))S=I,yield S;if(S==null)throw new Error("Did not flush dir");let v=k+w.key;o.push({Name:v,Tsize:Number(S.size),Hash:S.cid}),a+=S.size}else{let b=w.value;if(b.cid==null)continue;let S=k+w.key,v=b.size;o.push({Name:S,Tsize:Number(v),Hash:b.cid}),a+=BigInt(v??0)}}let c=Uint8Array.from(i.bitField().reverse()),u=new J({type:"hamt-sharded-directory",data:c,fanout:BigInt(r.tableSize()),hashType:bo,mtime:t?.mtime,mode:t?.mode}),l={Data:u.marshal(),Links:o},d=Q(X(l)),h=await ue(d,e,n),m=BigInt(d.byteLength)+a;yield{cid:h,unixfs:u,size:m}}function Gh(r){return typeof r.flush=="function"}async function Vh(r,e,t,n){let i=r._children,s=(r.tableSize()-1).toString(16).length,o=[],a=0;for(let h=0;h<i.length;h++){let m=i.get(h);if(m==null)continue;let y=h.toString(16).toUpperCase().padStart(s,"0");if(m instanceof et){let{size:w,cid:k}=await Vh(m,null,t,n);o.push({Name:y,Tsize:Number(w),Hash:k}),a+=y.length+k.byteLength}else if(Gh(m.value)){let w=m.value,k=w.nodeSize;if(w.cid==null)throw new Error("Child directory has not been persisted");o.push({Name:y+m.key,Tsize:Number(k),Hash:w.cid}),a+=y.length+w.cid.byteLength}else{let w=m.value,k=y+m.key,b=w.size;o.push({Name:k,Tsize:Number(b),Hash:w.cid}),a+=y.length+w.cid.byteLength}}let c=Uint8Array.from(i.bitField().reverse()),u=new J({type:"hamt-sharded-directory",data:c,fanout:BigInt(r.tableSize()),hashType:bo,mtime:e?.mtime,mode:e?.mode}),l=Q(X({Data:u.marshal(),Links:o}));return{cid:await ue(l,t,n),size:n.shardSplitStrategy==="links-bytes"?a:l.length}}var Ea,Hh,Yh=p(()=>{"use strict";xt();Bh();Fh();Wh();tr();Gr();Li();rr();Ea=class extends Be{constructor(t,n){super(t,n);f(this,"bucket");this.bucket=jh({hashFn:Bg,bits:n.shardFanoutBits??xi})}async put(t,n){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,await this.bucket.put(t,n)}async get(t){return this.bucket.get(t)}childCount(){return this.bucket.leafCount()}directChildrenCount(){return this.bucket.childrenCount()}onlyChild(){return this.bucket.onlyChild()}*eachChildSeries(){for(let{key:t,value:n}of this.bucket.eachLeafSeries())yield{key:t,child:n}}async estimateNodeSize(){if(this.nodeSize!==void 0)return this.nodeSize;let t=new Oi,n=await Vh(this.bucket,this,t,this.options);return this.nodeSize=n.size,this.nodeSize}async*flush(t){for await(let n of $h(this.bucket,t,this,this.options))yield{...n,path:this.path}}},Hh=Ea});async function Pa(r,e){let t=e,n=e.options.shardSplitThresholdBytes??Si;e instanceof Et&&await e.estimateNodeSize()>n&&(t=await Tg(e));let i=t.parent;if(i!=null){if(t!==e){if(r!=null&&(r.parent=t),t.parentKey==null)throw new Error("No parent key found");await i.put(t.parentKey,t)}return Pa(t,i)}return t}async function Tg(r){let e=new Hh({root:r.root,dir:!0,parent:r.parent,parentKey:r.parentKey,path:r.path,dirty:r.dirty,flat:!1,mtime:r.mtime,mode:r.mode},r.options);for(let{key:t,child:n}of r.eachChildSeries())await e.put(t,n);return e}var Jh=p(()=>{"use strict";Gr();ka();Yh()});var Zh,Xh=p(()=>{"use strict";Zh=(r="")=>r.split(/(?<!\\)\//).filter(Boolean)});async function Rg(r,e,t){let n=Zh(r.path??""),i=n.length-1,s=e,o="";for(let a=0;a<n.length;a++){let c=n[a];o+=`${o!==""?"/":""}${c}`;let u=a===i;if(s.dirty=!0,s.cid=void 0,s.size=void 0,u)await s.put(c,r),e=await Pa(null,s);else{let l=await s.get(c);(l==null||!(l instanceof Be))&&(l=new Et({root:!1,dir:!0,parent:s,parentKey:c,path:o,dirty:!0,flat:!0,mtime:l?.unixfs?.mtime,mode:l?.unixfs?.mode},t)),await s.put(c,l),s=l}}return e}async function*Qh(r,e){if(!(r instanceof Be)){r.unixfs?.isDirectory()===!0&&(yield r);return}yield*r.flush(e)}function ef(r){return async function*(t,n){let i=new Et({root:!0,dir:!0,path:"",dirty:!0,flat:!0},r),s,o=!1;for await(let a of t){if(a==null)continue;let c=`${a.originalPath??""}`.split("/")[0];c!=null&&c!==""&&(s==null?(s=c,o=!0):s!==c&&(o=!1)),i=await Rg(a,i,r),a.unixfs?.isDirectory()!==!0&&(yield a)}if(r.wrapWithDirectory||o&&i.childCount()>1)yield*Qh(i,n);else for(let a of i.eachChildSeries())a!=null&&(yield*Qh(a.child,n))}}var tf=p(()=>{"use strict";ka();Li();Jh();Xh()});var rf={};A(rf,{InvalidAvgChunkSizeError:()=>pa,InvalidChunkSizeError:()=>ma,InvalidContentError:()=>Ae,InvalidMinChunkSizeError:()=>ya,InvalidParametersError:()=>cr,InvalidShardingStrategyError:()=>Ze,importByteStream:()=>Mg,importBytes:()=>Fg,importDirectory:()=>Dg,importFile:()=>Ca,importer:()=>Ia});async function*Ia(r,e,t={}){let n;Symbol.asyncIterator in r||Symbol.iterator in r?n=r:n=[r];let i,s;t.profile==="unixfs-v0-2015"?(t.shardSplitStrategy=t.shardSplitStrategy??"links-bytes",t.cidVersion=t.cidVersion??0,t.rawLeaves=t.rawLeaves??!1,i=Ai,s=174):t.profile==="unixfs-v1-2025"&&(t.shardSplitStrategy=t.shardSplitStrategy??"block-bytes",t.cidVersion=t.cidVersion??1,t.rawLeaves=t.rawLeaves??!0,i=xu,s=1024);let o=t.wrapWithDirectory??Pu,a=t.shardSplitThresholdBytes??Si,c=t.shardSplitStrategy??ku,u=t.shardFanoutBits??xi,l=t.cidVersion??1,d=t.rawLeaves??Eu,h=t.leafType??Iu,m=t.fileImportConcurrency??Su,y=t.blockWriteConcurrency??Au,w=t.reduceSingleLeafToSelf??vu,k=t.chunker??Cu({chunkSize:i}),b=t.chunkValidator??gh(),S=t.dagBuilder??mh({chunker:k,chunkValidator:b,wrapWithDirectory:o,layout:t.layout??ga({maxChildrenPerNode:s}),bufferImporter:t.bufferImporter??ch({cidVersion:l,rawLeaves:d,leafType:h,onProgress:t.onProgress}),blockWriteConcurrency:y,reduceSingleLeafToSelf:w,cidVersion:l,onProgress:t.onProgress,dirBuilder:t.dirBuilder,fileBuilder:t.fileBuilder}),v=t.treeBuilder??ef({wrapWithDirectory:o,shardSplitThresholdBytes:a,shardSplitStrategy:c,shardFanoutBits:u,cidVersion:l,onProgress:t.onProgress});for await(let I of v(Hr(S(n,e),m),e))yield{cid:I.cid,path:I.path,unixfs:I.unixfs,size:I.size}}async function Ca(r,e,t={}){let n=await mo(Ia([r],e,t));if(n==null)throw new cr("Nothing imported");return n}async function Dg(r,e,t={}){let n=await mo(Ia([r],e,t));if(n==null)throw new cr("Nothing imported");return n}async function Fg(r,e,t={}){return Ca({content:r},e,t)}async function Mg(r,e,t={}){return Ca({content:r},e,t)}var xa=p(()=>{"use strict";du();go();Bu();Gr();lh();yh();wh();mn();kh();tf();mn()});async function Wi(r){let{importBytes:e}=await Promise.resolve().then(()=>(xa(),rf)),{cid:t}=await e(r,Ug,{cidVersion:1,rawLeaves:!0,wrapWithDirectory:!1});return t.toString()}var Ug,Ba=p(()=>{"use strict";Ug={put:r=>r}});async function Lg(r,e){if(e instanceof Uint8Array)return e;if(typeof e!="string")return ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e);let t;try{t=await fetch(e)}catch(n){throw new E(`Failed to fetch the ${r} artifact from ${e}`,"ZK_ARTIFACT_FETCH_ERROR",n)}if(!t.ok)throw new E(`Failed to fetch the ${r} artifact from ${e}: ${t.status} ${t.statusText}`,"ZK_ARTIFACT_FETCH_ERROR");return new Uint8Array(await t.arrayBuffer())}async function nf(r,e){let[t,n]=await Promise.all(_g.map(async i=>{let s=await Lg(i,r[i]),o=await Wi(s);if(o!==e[i])throw new st(i,e[i],o);return s}));return{wasm:t,zkey:n}}var _g,sf=p(()=>{"use strict";T();Ba();_g=["wasm","zkey"]});function of(r){let e=0n;for(let t=0;t<r.length;t++)e=e<<8n|BigInt(r[t]);return e}var af=p(()=>{"use strict"});function yn(r){let e=r%Z;return e<0n?e+Z:e}function Wg(r){let[e,t]=[yn(r),Z],[n,i]=[1n,0n];if(e===0n)throw new x("Division by zero in Baby Jubjub field");for(;t!==0n;){let s=e/t;[e,t]=[t,e-s*t],[n,i]=[i,n-s*i]}return yn(n)}function Ta(r,e){let[t,n,i]=r,[s,o,a]=e,c=i*a%Z,u=c*c%Z,l=t*s%Z,d=n*o%Z,h=zg*l%Z*d%Z,m=yn(u-h),y=(u+h)%Z,w=yn(c*m*((t+n)*(s+o)-l-d)),k=yn(c*y*(d-Ng*l)),b=m*y%Z;return[w,k,b]}function $g([r,e,t]){let n=Wg(t);return[r*n%Z,e*n%Z]}function Gg(r,e){let t=[0n,1n,1n],n=[r[0],r[1],1n],i=Math.max(jg,e.toString(2).length);for(let s=i-1;s>=0;s--){let o=e>>BigInt(s)&1n,a=Ta(t,n),c=o?Ta(n,n):Ta(t,t);t=o?a:c,n=o?c:a}return $g(t)}function Vg(r){if(typeof r!="bigint"||r<1n||r>=uf)throw new x("Baby Jubjub private key must be in [1, l)")}function df(r){return of(r)%(uf-1n)+1n}function hf(){let r=new Uint8Array(64);return crypto.getRandomValues(r),df(r)}function Yg(r){return Vg(r),Gg(Og,r)}function ff(r){if(!(r instanceof Uint8Array)||r.length<16)throw new x("Baby Jubjub key secret must be at least 16 bytes");let e=df((0,cf.hkdf)(lf.sha256,r,void 0,qg,64));return{privateKey:e,publicKey:Yg(e)}}var cf,lf,Ra,Ng,zg,Kg,uf,Og,Z,_x,qg,jg,Lx,Hg,Nx,pf=p(()=>{"use strict";cf=require("@noble/hashes/hkdf.js"),lf=require("@noble/hashes/sha2.js");T();af();Ra=21888242871839275222246405745257275088548364400416034343698204186575808495617n,Ng=168700n,zg=168696n,Kg=21888242871839275222246405745257275088614511777268538073601725287587578984328n,uf=Kg>>3n,Og=[5299619240641551281634865583518297030282874472190772894086521144482721001553n,16950150798460657717958625567821834550301663161624707787222815936182638968203n],Z=Ra,_x=Z-1n>>1n,qg=new TextEncoder().encode("w3pk-babyjub-v1"),jg=256,Lx=2**32;Hg=28n,Nx=Z-1n>>Hg});var gf={};A(gf,{ZK_PRF_LABEL:()=>yf,zkProve:()=>rw});function Da(r,e){let t;try{if(typeof r=="bigint")t=r;else if(typeof r=="number"&&Number.isSafeInteger(r))t=BigInt(r);else if(typeof r=="string"&&r.trim()!=="")t=BigInt(r);else throw new Error}catch{throw new x(`Input '${e}' is not a field element`)}if(t<0n||t>=Ra)throw new x(`Input '${e}' is not in the BN254 scalar field`);return t}function mf(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function Jg(r,e,t){let n={...r};for(let[u,l]of Object.entries(e)){if(mf(n,u))throw new x(`Input '${u}' is in both publicInputs and extraWitness`);n[u]=l}let i=t.secretInput??"secret",s=t.random??[];if(!Array.isArray(s))throw new x("options.random must be an array of input names");let o=Object.entries(t.derive??{}),a=new Set(Object.keys(n));for(let u of[i,...s,...o.map(([l])=>l)]){if(typeof u!="string"||u.length===0)throw new x("Input names must be non-empty strings");if(a.has(u))throw new x(`Input '${u}' is set by w3pk and can't be given or declared twice`);a.add(u)}let c=new Set([i,...s]);for(let[u,l]of o){if(!Array.isArray(l)||l.length<1||l.length>16)throw new x(`Derivation '${u}' needs 1 to 16 terms`);for(let d of l)if(typeof d=="bigint")Da(d,`${u} constant`);else if(typeof d=="string"&&mf(n,d))Da(n[d],d);else if(!(typeof d=="string"&&c.has(d)))throw new x(`Derivation '${u}' uses '${String(d)}', which isn't an input set before it`);c.add(u)}return{inputs:n,secretInput:i,random:s,derive:o}}async function Zg(){let r;try{r=await import("poseidon-lite")}catch(e){throw new x("zkProve derivations require poseidon-lite. Install with: pnpm add poseidon-lite",e)}return e=>r[`poseidon${e.length}`](e)}function Xg(r){try{return ff(r).privateKey}finally{r.fill(0)}}async function Qg({wasm:r,zkey:e}){let t;try{t=await import("snarkjs")}catch(n){throw new x("ZK proofs require snarkjs. Install with: pnpm add snarkjs",n)}return{async prove(n){try{return await t.groth16.fullProve(n,r,e)}catch(i){throw new x(`Failed to generate proof: ${i instanceof Error?i.message:String(i)}`,i)}},close(){}}}async function ew({wasm:r,zkey:e}){let t;try{t=new Worker(new URL("./zk/prove-worker.mjs",nw.url),{type:"module"})}catch(i){throw new x("Failed to start the proving worker",i)}let n=()=>new Promise((i,s)=>{t.onmessage=o=>o.data?.error?s(new x(o.data.error)):i(o.data),t.onerror=o=>{o.preventDefault(),s(new x(`Proving worker failed: ${o.message||"failed to load"}`))}});try{await n()}catch(i){throw t.terminate(),i}return{prove(i){let s=n();return t.postMessage({input:i,wasm:r,zkey:e}),s},close:()=>t.terminate()}}async function tw(r){if(typeof Worker<"u")try{return await ew(r)}catch{}return Qg(r)}async function rw(r,e,t,n={},i={}){let s=Jg(t,n,i),o=i.secret??"zk";if(o!=="zk"&&o!=="semaphore")throw new x(`Unknown secret source '${String(o)}'`);let a=o==="semaphore"?await fo():Xg,c=s.derive.length>0?await Zg():void 0,u=await nf({wasm:e.wasm,zkey:e.zkey},e.pins),l=await tw(u);try{let d=a(await r(o==="semaphore"?ho:yf)),h=new Set([d.toString()]),m={...s.inputs,[s.secretInput]:d};for(let b of s.random){let S=hf();m[b]=S,h.add(S.toString())}for(let[b,S]of s.derive)m[b]=c(S.map(v=>typeof v=="bigint"?v:Da(m[v],v)));let{proof:y,publicSignals:w}=await l.prove(m),k=w.map(String);if(k.some(b=>h.has(b)))throw new x("The circuit makes the secret or a random input public; proof refused");return{proof:{pi_a:y.pi_a.map(String),pi_b:y.pi_b.map(b=>b.map(String)),pi_c:y.pi_c.map(String),protocol:y.protocol,curve:y.curve},publicSignals:k}}finally{l.close()}}var nw,yf,wf=p(()=>{"use strict";T();sf();pf();po();nw={},yf="w3pk-zk-v1"});var aw={};A(aw,{AddressChangeError:()=>Ne,ApiError:()=>fr,AuthenticationError:()=>F,CryptoError:()=>x,DEFAULT_MODE:()=>ae,DEFAULT_TAG:()=>H,MLKEM_DEFAULT_CONTEXT:()=>Ie,PrfUnsupportedError:()=>ee,RecoverySimulator:()=>gn,RegistrationError:()=>tt,RemovedBackupMethodError:()=>nt,StealthAddressModule:()=>Dt,StorageError:()=>P,SyncBootstrapError:()=>he,SyncRequiredError:()=>rt,UnsupportedBackupVersionError:()=>Te,WalletError:()=>g,WalletMissingError:()=>Le,WeakPasswordError:()=>it,Web3Passkey:()=>dr,Web3PasskeyError:()=>E,ZkArtifactMismatchError:()=>st,arrayBufferToBase64Url:()=>fe,assertEthereumAddress:()=>xn,assertMnemonic:()=>Ka,assertUsername:()=>Sn,authenticateWithPasskey:()=>Fs,base64ToArrayBuffer:()=>Ct,base64UrlDecode:()=>Qi,base64UrlToArrayBuffer:()=>D,canControlStealthAddress:()=>Xa,checkStealthAddress:()=>vr,clearCache:()=>uc,computeStealthPrivateKey:()=>Er,createSiweMessage:()=>ps,createWalletFromMnemonic:()=>Sr,createWeb3Passkey:()=>vf,default:()=>ow,deriveAddressFromP256PublicKey:()=>ss,deriveIndexFromOriginModeAndTag:()=>_n,deriveMLKemKeypair:()=>Fr,deriveStealthKeys:()=>dt,deriveWalletFromMnemonic:()=>Ar,encodeEIP7702AuthorizationMessage:()=>Br,extractRS:()=>is,generateBIP39Wallet:()=>xr,generateSiweNonce:()=>hs,generateStealthAddress:()=>Nn,getAllChains:()=>cc,getAllTopics:()=>kf,getChainById:()=>lc,getCurrentBuildHash:()=>_a,getCurrentOrigin:()=>$,getEndpoints:()=>Ut,getExplainer:()=>bf,getOriginSpecificAddress:()=>te,getPackageVersion:()=>Ua,getW3pkBuildHash:()=>Ma,hashEIP7702AuthorizationMessage:()=>Tr,isStrongPassword:()=>Oa,mlkemDecrypt:()=>ti,mlkemDecryptWithKey:()=>Ps,mlkemEncrypt:()=>ei,mlkemEncryptWithKey:()=>Es,normalizeOrigin:()=>Fe,parseSiweMessage:()=>Mt,promptPasskeySelection:()=>Ds,safeAtob:()=>gr,safeBtoa:()=>Xi,searchExplainers:()=>xf,validateEthereumAddress:()=>Ji,validateMnemonic:()=>Zi,validateSiweMessage:()=>ms,validateUsername:()=>at,verifyBuildHash:()=>Af,verifyEIP7702Authorization:()=>Gn,verifySiweSignature:()=>ys});module.exports=_f(aw);T();yr();De();pe();ge();In();br();async function jf(r){try{let e=Ga(r);if(!e||!((e[32]&64)!==0))return null;let i=37;i+=16;let s=e[i]<<8|e[i+1];i+=2,i+=s;let o=e.slice(i),a=await Hf(o);return fe(a)}catch(e){return console.error("Failed to extract public key:",e),null}}function Ga(r){let e=new Uint8Array(r),t=Wf(e);return t===-1?null:e.slice(t)}function Wf(r){let e=new Uint8Array([104,97,117,116,104,68,97,116,97]);for(let t=0;t<r.length-e.length;t++){let n=!0;for(let i=0;i<e.length;i++)if(r[t+i]!==e[i]){n=!1;break}if(n){let i=r[t+e.length],s=t+e.length+1;if(i>=88&&i<=91){let o=i-87;s+=o}return s}}return-1}async function Hf(r){let e=$a(r,-2),t=$a(r,-3);if(!e||!t)throw new Error("Failed to extract EC coordinates from COSE key");let n=new Uint8Array(65);n[0]=4,n.set(e,1),n.set(t,33);let i=new Uint8Array([48,89,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,3,66,0]),s=new Uint8Array(i.length+n.length);return s.set(i,0),s.set(n,i.length),s.buffer}function $a(r,e){let t=e<0?32+(-1-e):e;for(let n=0;n<r.length-33;n++)if(r[n]===t&&(r[n+1]===88&&r[n+2]===32||r[n+1]===88&&r[n+2]===32))return r.slice(n+3,n+35);return null}async function Va(r){try{let{username:e,ethereumAddress:t,userVerification:n="required"}=r;Sn(e),xn(t);let i=new z;if(await i.userExists(e))throw new Error("Username already registered");let s=ve(),o=D(s),a=crypto.getRandomValues(new Uint8Array(32)),c={challenge:o,rp:{name:"w3pk",id:window.location.hostname},user:{id:a,name:e,displayName:e},pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],authenticatorSelection:{userVerification:n,residentKey:"required",requireResidentKey:!0},timeout:6e4,attestation:"none",extensions:{prf:{eval:{first:me}}}},u=await navigator.credentials.create({publicKey:c});if(!u)throw new Error("Failed to create credential");let l=u.response.attestationObject;if(!Dn(u.response.clientDataJSON,s,"webauthn.create"))throw new Error("Invalid client data");let d=Ga(l);if(!d||!await Fn(d))throw new Error("RP ID hash mismatch");if(!Pn(d))throw new Error("User presence flag not set");let h=await jf(l);if(!h)throw new Error("Public key not returned from authenticator");await i.saveCredential({id:u.id,publicKey:h,username:e,ethereumAddress:t,createdAt:new Date().toISOString(),lastUsed:new Date().toISOString(),signCount:0});let m=Rt(d)?u.getClientExtensionResults?.().prf?.results?.first:void 0;return{signature:l,prfOutput:m}}catch(e){throw new tt(e instanceof Error?e.message:"Registration failed",e)}}br();T();var Mn="w3pk_wallet_",Un=class{constructor(e){this.customStorage=e}get storage(){if(this.customStorage)return this.customStorage;if(typeof window<"u"&&window.localStorage)return window.localStorage;throw new P("localStorage is not available")}async init(){}async store(e){try{this.storage.setItem(Mn+e.ethereumAddress,JSON.stringify(e))}catch(t){throw new P("Failed to store wallet data",t)}}async retrieve(e){try{let t=this.storage.getItem(Mn+e);return t?JSON.parse(t):null}catch(t){throw new P("Failed to retrieve wallet data",t)}}async delete(e){try{this.storage.removeItem(Mn+e)}catch(t){throw new P("Failed to delete wallet data",t)}}async clear(){try{for(let e of this.keys())this.storage.removeItem(e)}catch(e){throw new P("Failed to clear wallet data",e)}}keys(){let e=[];for(let t=0;t<this.storage.length;t++){let n=this.storage.key(t);n?.startsWith(Mn)&&e.push(n)}return e}};Ee();ut();ge();var nc=require("ethers");T();var V=require("ethers");T();function dt(r){try{let e=V.ethers.HDNodeWallet.fromPhrase(r,void 0,"m/44'/60'/1'/0/0"),t=V.ethers.HDNodeWallet.fromPhrase(r,void 0,"m/44'/60'/1'/0/1"),n=t.signingKey.compressedPublicKey,i=e.signingKey.compressedPublicKey;return{stealthMetaAddress:n+i.slice(2),spendingPubKey:n,viewingPubKey:i,viewingKey:e.privateKey,spendingKey:t.privateKey}}catch(e){throw new x("Failed to derive stealth keys",e)}}function Nn(r){try{let e="0x"+r.slice(2,68),t="0x"+r.slice(68),n=V.ethers.Wallet.createRandom(),i=n.signingKey.compressedPublicKey,s=os(n.privateKey,t),o=V.ethers.keccak256(s),a="0x"+o.slice(2,4),c=as(o),u=ec(e,Qa(c));return{stealthAddress:tc(u),ephemeralPubKey:i,viewTag:a}}catch(e){throw new x("Failed to generate stealth address",e)}}function vr(r,e,t,n,i){try{let s=os(r,t),o=V.ethers.keccak256(s);if(i&&("0x"+o.slice(2,4)).toLowerCase()!==i.toLowerCase())return{isForUser:!1};let a=as(o),c=ec(e,Qa(a)),u=tc(c);return u.toLowerCase()!==n.toLowerCase()?{isForUser:!1}:{isForUser:!0,stealthAddress:u}}catch{return{isForUser:!1}}}function Er(r,e,t){try{let n=os(r,t),i=V.ethers.keccak256(n),s=as(i);return Gf(e,s)}catch(n){throw new x("Failed to compute stealth private key",n)}}function Xa(r,e,t,n,i,s){try{if(!vr(r,t,n,i,s).isForUser)return!1;let a=Er(r,e,n);return new V.ethers.Wallet(a).address.toLowerCase()===i.toLowerCase()}catch{return!1}}function os(r,e){try{return new V.ethers.Wallet(r).signingKey.computeSharedSecret(e)}catch(t){throw new x("Failed to compute shared secret",t)}}function Qa(r){try{return new V.ethers.Wallet(r).signingKey.compressedPublicKey}catch(e){throw new x("Failed to multiply generator by scalar",e)}}function ec(r,e){try{let t=V.ethers.SigningKey.computePublicKey(r,!1),n=V.ethers.SigningKey.computePublicKey(e,!1),i=BigInt("0x"+t.slice(4,68)),s=BigInt("0x"+t.slice(68)),o=BigInt("0x"+n.slice(4,68)),a=BigInt("0x"+n.slice(68)),c=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F");if(i===o&&s===a){let y=3n*i*i%c,w=2n*s%c,k=y*Za(w,c)%c,b=(k*k-2n*i)%c,S=(k*(i-b)-s)%c;return Ja((b+c)%c,(S+c)%c)}let u=((a-s)%c+c)%c,l=((o-i)%c+c)%c,d=u*Za(l,c)%c,h=(d*d-i-o)%c,m=(d*(i-h)-s)%c;return Ja((h+c)%c,(m+c)%c)}catch(t){throw new x("Failed to add public keys",t)}}function as(r){try{let e=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"),n=BigInt(r)%e;if(n===0n)throw new Error("Scalar reduced to zero (invalid)");return"0x"+n.toString(16).padStart(64,"0")}catch(e){throw new x("Failed to reduce scalar modulo curve order",e)}}function Gf(r,e){try{let t=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"),n=BigInt(r),i=BigInt(e);return"0x"+((n+i)%t).toString(16).padStart(64,"0")}catch(t){throw new x("Failed to add private keys",t)}}function Ja(r,e){return"0x"+(e%2n===0n?"02":"03")+r.toString(16).padStart(64,"0")}function Za(r,e){r=(r%e+e)%e;let[t,n]=[r,e],[i,s]=[1n,0n];for(;n!==0n;){let o=t/n;[t,n]=[n,t-o*n],[i,s]=[s,i-o*s]}return(i%e+e)%e}function tc(r){try{let e=V.ethers.SigningKey.computePublicKey(r,!1),t=V.ethers.keccak256("0x"+e.slice(4));return V.ethers.getAddress("0x"+t.slice(-40))}catch(e){throw new x("Failed to derive address from public key",e)}}var Dt=class{constructor(e,t){this.getMnemonic=t}async generateStealthAddress(e){try{let t=await this.getMnemonic(e?.requireAuth),n=dt(t),i=Nn(n.stealthMetaAddress);return{stealthAddress:i.stealthAddress,ephemeralPublicKey:i.ephemeralPubKey,viewTag:i.viewTag}}catch(t){throw new E("Failed to generate stealth address","STEALTH_GENERATION_ERROR",t)}}async parseAnnouncement(e,t){try{let n=await this.getMnemonic(t?.requireAuth),i=rc(dt(n),e);return i.isForUser?{isForUser:!0,stealthAddress:i.stealthAddress}:{isForUser:!1}}catch(n){throw new E("Failed to parse announcement","ANNOUNCEMENT_PARSE_ERROR",n)}}async scanAnnouncements(e,t){let n=[];for(let i of e){let s=await this.parseAnnouncement(i,t);s.isForUser&&n.push(s)}return n}async signTransaction(e,t){try{let n=await this.getMnemonic(!0),i=dt(n);if(!rc(i,e).isForUser)throw new Error("Announcement is not for this user");return await new nc.ethers.Wallet(Er(i.viewingKey,i.spendingKey,e.ephemeralPublicKey)).signTransaction({type:2,to:t.to,value:t.value,data:t.data??"0x",chainId:t.chainId,nonce:t.nonce,gasLimit:t.gasLimit,maxFeePerGas:t.maxFeePerGas,maxPriorityFeePerGas:t.maxPriorityFeePerGas})}catch(n){throw new E("Failed to sign stealth transaction","STEALTH_SIGN_ERROR",n)}}async getKeys(e){try{let t=await this.getMnemonic(e?.requireAuth),{stealthMetaAddress:n,spendingPubKey:i,viewingPubKey:s,viewingKey:o}=dt(t);return{stealthMetaAddress:n,spendingPubKey:i,viewingPubKey:s,viewingKey:o}}catch(t){throw new E("Failed to get stealth keys","STEALTH_KEYS_ERROR",t)}}async getStealthMetaAddress(e){try{return(await this.getKeys(e)).stealthMetaAddress}catch(t){throw new E("Failed to get stealth meta-address","STEALTH_META_ADDRESS_ERROR",t)}}get isAvailable(){return!0}};function rc(r,e){return vr(r.viewingKey,r.spendingPubKey,e.ephemeralPublicKey,e.stealthAddress,e.viewTag)}T();var zn="w3pk_session_",Kn=class{constructor(e){this.customStorage=e}get storage(){if(this.customStorage)return this.customStorage;if(typeof window<"u"&&window.localStorage)return window.localStorage;throw new P("localStorage is not available")}async init(){}async store(e){if(e.securityMode==="STRICT")throw new P("Cannot persist STRICT mode sessions");try{this.storage.setItem(zn+e.ethereumAddress,JSON.stringify(e))}catch(t){throw new P("Failed to store persistent session",t)}}async retrieve(e){let t;try{let n=this.storage.getItem(zn+e);t=n?JSON.parse(n):null}catch(n){throw new P("Failed to retrieve persistent session",n)}return t&&Date.now()>t.expiresAt?(await this.delete(e),null):t}async delete(e){try{this.storage.removeItem(zn+e)}catch(t){throw new P("Failed to delete persistent session",t)}}async clear(){try{for(let e of this.keys())this.storage.removeItem(e)}catch(e){throw new P("Failed to clear persistent sessions",e)}}async cleanupExpired(){try{let e=Date.now();for(let t of this.keys()){let n=this.storage.getItem(t),i=n?JSON.parse(n):null;(!i||e>i.expiresAt)&&this.storage.removeItem(t)}}catch(e){throw new P("Failed to cleanup expired sessions",e)}}keys(){let e=[];for(let t=0;t<this.storage.length;t++){let n=this.storage.key(t);n?.startsWith(zn)&&e.push(n)}return e}};ge();var On=class{constructor(e=1,t){this.session=null;this.sessionDuration=e*60*60*1e3,this.persistentConfig={enabled:t?.enabled??!1,duration:t?.duration??168,requireReauth:t?.requireReauth??!0},this.persistentStorage=new Kn}async startSession(e,t,n,i,s){let o=new Date(Date.now()+this.sessionDuration).toISOString();if(this.session={mnemonic:e,expiresAt:o,credentialId:t},this.persistentConfig.enabled&&s!=="STRICT"&&n){if(!i){console.info("[w3pk] Authenticator did not provide a PRF output \u2014 persistent session not stored on this device (in-memory session only)");return}try{let a=await ze(e,i),c=Date.now()+this.persistentConfig.duration*60*60*1e3;await this.persistentStorage.store({encryptedMnemonic:a,sessionKey:this.persistentConfig.requireReauth?void 0:await ts(i),expiresAt:c,credentialId:t,ethereumAddress:n,securityMode:s||"STANDARD",createdAt:Date.now()})}catch(a){console.warn("[w3pk] Failed to persist session:",a)}}}getMnemonic(){return this.session?new Date>new Date(this.session.expiresAt)?(this.clearSession().catch(e=>console.warn("[w3pk] Failed to clear expired session:",e)),null):this.session.mnemonic:null}getCredentialId(){return this.session?new Date>new Date(this.session.expiresAt)?(this.clearSession().catch(e=>console.warn("[w3pk] Failed to clear expired session:",e)),null):this.session.credentialId:null}isActive(){return this.getMnemonic()!==null}getRemainingTime(){return this.session?new Date>new Date(this.session.expiresAt)?(this.clearSession().catch(e=>console.warn("[w3pk] Failed to clear expired session:",e)),0):Math.floor((new Date(this.session.expiresAt).getTime()-Date.now())/1e3):0}extendSession(){if(!this.session)throw new Error("No active session to extend");if(new Date>new Date(this.session.expiresAt))throw this.clearSession().catch(e=>console.warn("[w3pk] Failed to clear expired session:",e)),new Error("Session expired, cannot extend");this.session.expiresAt=new Date(Date.now()+this.sessionDuration).toISOString()}async restoreFromPersistentStorage(e,t,n){if(!this.persistentConfig.enabled||!n)return null;try{let i=await this.persistentStorage.retrieve(e);if(!i)return null;if(i.credentialId!==t)return console.warn("[w3pk] Credential ID mismatch, clearing persistent session"),await this.persistentStorage.delete(e),null;let s=await ye(i.encryptedMnemonic,n),o=new Date(Date.now()+this.sessionDuration).toISOString();return this.session={mnemonic:s,expiresAt:o,credentialId:t},s}catch(i){console.warn("[w3pk] Failed to restore persistent session:",i);try{await this.persistentStorage.delete(e)}catch{}return null}}async attemptSilentRestore(){if(!this.persistentConfig.enabled||this.persistentConfig.requireReauth)return null;try{let{CredentialStorage:e}=await Promise.resolve().then(()=>(De(),En)),n=await new e().getAllCredentials();if(n.length===0)return null;for(let i of n){let s=await this.persistentStorage.retrieve(i.ethereumAddress);if(!s)continue;if(s.credentialId!==i.id){console.warn("[w3pk] Credential ID mismatch, skipping this session");continue}if(!s.sessionKey)continue;let o=await ye(s.encryptedMnemonic,await rs(s.sessionKey)),a=new Date(Date.now()+this.sessionDuration).toISOString();return this.session={mnemonic:o,expiresAt:a,credentialId:i.id},{mnemonic:o,ethereumAddress:i.ethereumAddress,credentialId:i.id}}return null}catch(e){return console.warn("[w3pk] Failed to attempt silent restore:",e),null}}async clearSession(){this.session&&(this.session.mnemonic="0".repeat(this.session.mnemonic.length)),this.session=null,this.persistentConfig.enabled&&await this.persistentStorage.clear()}get storesSessionKey(){return this.persistentConfig.enabled&&!this.persistentConfig.requireReauth}setSessionDuration(e){this.sessionDuration=e*60*60*1e3}setPersistentSessionDuration(e){this.persistentConfig.duration=e}};De();Ir();us();var Wn={debug:!1,sessionDuration:1,userVerification:"required",rpcUrls:{},persistentSession:{enabled:!1,duration:168,requireReauth:!0},onError:r=>{Wn.debug&&console.error("[w3pk]",r)}};$n();T();var ac="https://chainid.network/chains.json";var Cr=null,ep=[/\$\{[\w_]+\}/i,/\{[\w_]+\}/i,/<[\w_]+>/i,/YOUR[-_]?API[-_]?KEY/i,/INSERT[-_]?API[-_]?KEY/i,/API[-_]?KEY[-_]?HERE/i];function tp(r){return ep.some(e=>e.test(r))}async function rp(r=ac){let e=await fetch(r);if(!e.ok)throw new Error(`Failed to fetch chains data: ${e.status} ${e.statusText}`);return await e.json()}async function gs(r){let e=r?.chainsJsonUrl??ac,t=r?.cacheDuration??36e5,n=Date.now();if(Cr&&n-Cr.timestamp<t)return Cr.data;let i=await rp(e);return Cr={data:i,timestamp:n},i}async function Ut(r,e){let n=(await gs(e)).find(i=>i.chainId===r);return n?n.rpc.filter(i=>i.startsWith("https://")&&!tp(i)):[]}async function cc(r){return gs(r)}async function lc(r,e){return(await gs(e)).find(n=>n.chainId===r)}function uc(){Cr=null}ws();var np=new Set([1,10,8453,42161,57073,100,42220,137,42,15,40,41,44,46,47,50,51,56,61,71,82,83,95,97,112,123,130,146,151,153,171,180,183,185,195,215,228,247,248,252,261,267,291,293,311,332,336,395,401,416,466,480,488,510,545,634,647,648,747,831,919,938,945,957,964,970,980,995,997,1001,1003,1024,1030,1114,1125,1135,1149,1188,1284,1285,1287,1300,1301,1315,1337,1338,1339,1424,1514,1687,1727,1729,1740,1750,1829,1868,1946,1961,1962,1969,1989,1995,2017,2020,2031,2043,2109,2241,2340,2345,2440,2522,2559,2649,3068,3109,3338,3502,3799,3888,3889,4e3,4048,4078,4162,4201,4202,4460,4488,4661,4689,4690,4888,5e3,5003,5124,5234,5330,5424,5522,6283,6342,6398,6678,6806,6934,6942,6969,7117,7171,7200,7208,7368,7518,7668,7672,7744,7771,7869,7897,8008,8118,8217,8408,8700,8726,8727,8844,8880,8881,8882,8889,9372,9496,9700,9745,9746,9899,9990,9996,10011,10085,10143,10200,11221,11501,11504,11891,13370,14853,16602,16661,17e3,18880,18881,19991,21e3,21816,21912,25327,32323,33401,34443,41923,42170,43111,44787,47805,48898,48900,49049,49088,5e4,50312,53302,53456,53457,55244,56288,59141,60808,60850,62320,62850,64002,71402,72080,73114,73115,75338,78281,80002,80008,80069,80094,80451,80931,84532,88899,91342,92278,94524,96970,97476,97477,98985,100021,100501,101010,102030,102031,102032,112358,120893,121212,121213,121214,121215,129399,161803,175188,192940,193939,198989,212013,222222,240241,325e3,355110,355113,421614,555777,560048,656476,713715,743111,747474,763373,763375,777777,806582,808813,810180,839999,888991,2019775,2222222,4278608,5734951,6666689,6985385,7080969,7777777,9999999,11142220,11155111,11155420,11155931,16969696,19850818,20180427,20250825,28122024,34949059,37084624,52164803,61022448,79479957,96969696,420420421,420420422,888888888,974399131,999999999,1020352220,1273227453,1313161560,1350216234,1380996178,1417429182,1444673419,1482601649,1564830818,2046399126,11297108099,11297108109,88153591557,123420000220,123420001114]);async function ip(r,e=1e4){try{let t=new AbortController,n=setTimeout(()=>t.abort(),e),i=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},signal:t.signal,body:JSON.stringify({jsonrpc:"2.0",method:"eth_estimateGas",params:[{from:"0xdeadbeef00000000000000000000000000000000",to:"0xdeadbeef00000000000000000000000000000000",data:"0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",value:"0x0"},"latest",{"0xdeadbeef00000000000000000000000000000000":{code:"0xef01000000000000000000000000000000000000000001"}}],id:1})});if(clearTimeout(n),!i.ok)return!1;let s=await i.json();if(s.error){let o=(s.error.message||"").toLowerCase();return!["unsupported","not supported","unknown","invalid","unrecognized","does not support","not implemented"].some(c=>o.includes(c))}return s.result!==void 0}catch{return!1}}async function hc(r,e,t){if(np.has(r))return!0;let n=t?.maxEndpoints||3,i=t?.timeout||1e4;try{let s=await e(r);if(s.length===0)return!1;let o=s.slice(0,n);for(let a of o)if(await ip(a,i))return!0;return!1}catch{return!1}}var bs=require("ethers");T();function fc(r){return typeof r=="string"&&/^0x(?:[0-9a-fA-F]{2})*$/.test(r)}function pc(r){try{return BigInt(r)}catch{throw new g(`Invalid chainId: ${String(r)}`)}}function mc(r,e){let t=e?.chainId??1,n={},i=(o,...a)=>{(n[o]??[]).forEach(c=>c(...a))};return{async request({method:o,params:a}){let c=a;switch(o){case"eth_accounts":case"eth_requestAccounts":return[await r.getAddress(e?.mode??"STANDARD",e?.tag??"MAIN")];case"eth_chainId":return"0x"+t.toString(16);case"eth_sendTransaction":{let u=(c??[])[0]??{};if(!u.chainId&&!t)throw new g("eth_sendTransaction: chainId is required");if(u.chainId!=null&&pc(u.chainId)!==BigInt(t))throw new g(`eth_sendTransaction: chainId ${u.chainId} does not match the active chain ${t}`);let l=t;return(await r.sendTransaction({to:u.to,value:u.value!==void 0?BigInt(u.value):void 0,data:u.data??"0x",chainId:l,gasLimit:u.gas!==void 0?BigInt(u.gas):void 0,maxFeePerGas:u.maxFeePerGas!==void 0?BigInt(u.maxFeePerGas):void 0,maxPriorityFeePerGas:u.maxPriorityFeePerGas!==void 0?BigInt(u.maxPriorityFeePerGas):void 0,nonce:u.nonce!==void 0?parseInt(u.nonce,16):void 0},{mode:e?.mode,tag:e?.tag,rpcUrl:e?.rpcUrl})).hash}case"personal_sign":{let[u]=c??[],l=fc(u)?(0,bs.getBytes)(u):u;return(await r.signMessage(l,{mode:e?.mode,tag:e?.tag,signingMethod:"EIP191"})).signature}case"eth_sign":{let[,u]=c??[],l=fc(u)?(0,bs.getBytes)(u):u;return(await r.signMessage(l,{mode:e?.mode,tag:e?.tag,signingMethod:"EIP191"})).signature}case"eth_signTypedData_v4":{let[,u]=c??[],l=typeof u=="string"?JSON.parse(u):u,{domain:d,types:h,message:m,primaryType:y}=l;if(d?.chainId!=null&&pc(d.chainId)!==BigInt(t))throw new g(`eth_signTypedData_v4: domain chainId ${d.chainId} does not match the active chain ${t}`);let w={...h};return delete w.EIP712Domain,(await r.signMessage(JSON.stringify(m),{mode:e?.mode,tag:e?.tag,signingMethod:"EIP712",eip712Domain:d,eip712Types:w,eip712PrimaryType:y})).signature}case"wallet_switchEthereumChain":{let u=parseInt((c??[])[0]?.chainId??"0x1",16);return t=u,i("chainChanged","0x"+u.toString(16)),null}default:throw new g(`w3pk EIP-1193: unsupported method "${o}"`)}},on(o,a){(n[o]??(n[o]=[])).push(a)},removeListener(o,a){n[o]&&(n[o]=n[o].filter(c=>c!==a))}}}ut();Lt();T();async function Ic(r,e){if(!r.currentUser)throw new g("Must be authenticated to derive ML-KEM public key");let{deriveMLKemKeypair:t}=await Promise.resolve().then(()=>(Lt(),ri)),{Wallet:n}=await import("ethers"),i=e?.mode||"STANDARD",s=e?.tag||H,o=$(),a=e?.context||Ie,c=i==="STRICT"?!0:e?.requireAuth||!1;if(i==="PRIMARY")throw new g("ML-KEM encryption is not supported in PRIMARY mode. PRIMARY mode uses P-256 WebAuthn keys which cannot derive ML-KEM keypairs. Use STANDARD, STRICT, or YOLO mode instead.");let u=await r.getMnemonicFromSession(c,i),l=await te(u,o,i,s),d;if(l.privateKey)d=l.privateKey;else{let{deriveWalletFromMnemonic:m}=await Promise.resolve().then(()=>(Ee(),lt));d=m(u,l.index).privateKey}let h=await t(d,a);return btoa(String.fromCharCode(...Array.from(h.publicKey)))}async function Cc(r,e,t,n){if(!r.currentUser)throw new g("Must be authenticated to encrypt data");let{mlkemEncryptWithKey:i}=await Promise.resolve().then(()=>(Lt(),ri)),s=n?.mode||"STANDARD",o=n?.tag||H,a=$(),c=n?.context||Ie,u=s==="STRICT"?!0:n?.requireAuth||!1;if(s==="PRIMARY")throw new g("ML-KEM encryption is not supported in PRIMARY mode. Use STANDARD, STRICT, or YOLO mode instead.");let l=await r.getMnemonicFromSession(u,s),d=await te(l,a,s,o),h;if(d.privateKey)h=d.privateKey;else{let{deriveWalletFromMnemonic:m}=await Promise.resolve().then(()=>(Ee(),lt));h=m(l,d.index).privateKey}return await i(e,h,t,c)}async function Bc(r,e,t){if(!r.currentUser)throw new g("Must be authenticated to decrypt data");let{mlkemDecryptWithKey:n}=await Promise.resolve().then(()=>(Lt(),ri)),i=t?.mode||"STANDARD",s=t?.tag||H,o=$(),a=t?.context||Ie,c=i==="STRICT"?!0:t?.requireAuth||!1;if(i==="PRIMARY")throw new g("ML-KEM encryption is not supported in PRIMARY mode. Use STANDARD, STRICT, or YOLO mode instead.");let u=await r.getMnemonicFromSession(c,i),l=await te(u,o,i,s),d;if(l.privateKey)d=l.privateKey;else{let{deriveWalletFromMnemonic:h}=await Promise.resolve().then(()=>(Ee(),lt));d=h(u,l.index).privateKey}return await n(e,d,a)}T();br();Ir();De();yr();ge();T();async function Ol(r){if(!r.currentUser)throw new g("Must be authenticated to check backup status");let{BackupManager:e}=await Promise.resolve().then(()=>(Oe(),Ke));return new e().getBackupStatus(r.currentUser.ethereumAddress)}async function ql(r){if(!r.currentUser)throw new g("Must be authenticated to confirm a backup");let{BackupManager:e}=await Promise.resolve().then(()=>(Oe(),Ke)),{deriveAddressChecksum:t}=await Promise.resolve().then(()=>(Re(),ot)),{ethereumAddress:n}=r.currentUser;await new e().confirmRecoveryPhraseBackup(n,await t(n))}async function jl(r,e){if(!r.currentUser)throw new g("Must be authenticated to create backup");let{assertStrongPassword:t}=await Promise.resolve().then(()=>(Re(),ot));t(e);let n=await r.getMnemonicFromSession(!0),{BackupFileManager:i}=await Promise.resolve().then(()=>(ce(),we)),s=new i,{backupFile:o}=await s.createPasswordBackup(n,e,await ao(r),r.currentUser.username);return await Wl(r,"file"),s.createDownloadableBackup(o)}async function Wl(r,e){let{BackupStorage:t}=await Promise.resolve().then(()=>(Cs(),Dc)),{deriveAddressChecksum:n}=await Promise.resolve().then(()=>(Re(),ot)),{ethereumAddress:i}=r.currentUser;await new t().storeBackupMetadata({id:crypto.randomUUID(),ethereumAddress:i,method:e,createdAt:new Date().toISOString(),addressChecksum:await n(i)})}async function ao(r){let e=await new z().getCredentialById(r.currentUser.credentialId);return e?{id:e.id,publicKey:e.publicKey}:void 0}async function Hl(r,e,t,n={}){let{BackupFileManager:i}=await Promise.resolve().then(()=>(ce(),we)),s=new i,o=n.allowAddressChange??!1,a=await s.parseBackupFile(e);if(a.encryptionMethod==="prf"){if(r.currentUser&&r.currentUser.credentialId!==a.credential.id)throw new he("CREDENTIAL_MISMATCH",r.currentUser.credentialId);return lo(r,a,o)}if(!t)throw new g("Password required to restore password-encrypted backup");let{mnemonic:c,ethereumAddress:u}=await s.restoreWithPassword(a,t);return co(r,c,u,o)}async function co(r,e,t,n){let{BackupManager:i}=await Promise.resolve().then(()=>(Oe(),Ke)),s=new i,o=new z,a=r.currentUser?await o.getCredentialById(r.currentUser.credentialId):null;if(!r.currentUser||!a)return s.markBackupVerified(t),r.currentWallet={address:t,mnemonic:e},{ethereumAddress:t};let c=r.currentUser.ethereumAddress;if(c.toLowerCase()!==t.toLowerCase()&&!n)throw new Ne(c,t);let{output:u,assertion:l,challenge:d}=await Ft(me,a.id);if(!await Tn(l,a,o,d))throw new Uint8Array(u).fill(0),new F("Signature verification failed");return await Wr(r,a,e,t,u,n),s.markBackupVerified(t),r.currentWallet={address:t,mnemonic:e},{ethereumAddress:t}}async function $l(r,e,t,n={}){let{BackupFileManager:i}=await Promise.resolve().then(()=>(ce(),we)),{BackupManager:s}=await Promise.resolve().then(()=>(Oe(),Ke)),{promptPasskeySelection:o}=await Promise.resolve().then(()=>(Ms(),zc)),a=new i,c=new s,u=n.allowAddressChange??!1,l=await a.parseBackupFile(e);if(l.encryptionMethod==="prf")return lo(r,l,u);let d=await o(),h=d.credentialId,m=d.publicKey;if(!m){if(!l.credential)throw new he("NO_CREDENTIAL",h);if(l.credential.id!==h)throw new he("CREDENTIAL_MISMATCH",h);if(m=l.credential.publicKey,!await Rn(d.assertion,m,d.challenge))throw new he("PUBLIC_KEY_MISMATCH",h)}if(!t)throw new g("Password required to restore password-encrypted backup");let{mnemonic:y,ethereumAddress:w}=await a.restoreWithPassword(l,t);return await Wr(r,{id:h,publicKey:m,username:d.username??Gl(l)??w},y,w,d.prfOutput,u),c.markBackupVerified(w),{ethereumAddress:w}}function Gl(r){let{username:e}=r;return typeof e=="string"&&at(e)?e:void 0}async function lo(r,e,t){let{DeviceSyncManager:n}=await Promise.resolve().then(()=>(mi(),pi)),{BackupManager:i}=await Promise.resolve().then(()=>(Oe(),Ke)),s=e.credential,a=(await new z().getCredentialById(s.id))?.publicKey??s.publicKey,{mnemonic:c,ethereumAddress:u,walletPrfOutput:l}=await new n().importFromSync(e,a);return await Wr(r,{id:s.id,publicKey:a,username:Gl(e)??u},c,u,l,t),new i().markBackupVerified(u),{ethereumAddress:u}}async function Wr(r,e,t,n,i,s){let o=new z,a=await o.getCredentialById(e.id),c=!!a&&a.ethereumAddress.toLowerCase()!==n.toLowerCase();if(c&&(!s||!i))throw i&&new Uint8Array(i).fill(0),s?new ee(e.id):new Ne(a.ethereumAddress,n);i?await r.storeWallet(n,t,e.id,i):a||await r.walletStorage.delete(n);let u=!a&&await o.userExists(e.username)?n:e.username;if(a)c&&(await o.updateCredentialAddress(e.id,n),await r.walletStorage.delete(a.ethereumAddress));else{let l=new Date().toISOString();await o.saveCredential({id:e.id,publicKey:e.publicKey,username:u,ethereumAddress:n,createdAt:l,lastUsed:l})}r.currentUser={username:a?.username??u,ethereumAddress:n,credentialId:e.id},await r.sessionManager.startSession(t,e.id,n,i?await ct(i,r.sessionManager.storesSessionKey):void 0,"STANDARD"),r.requestPersistentStorage(),r.config.onAuthStateChanged?.(!0,r.currentUser)}async function Vl(r,e,t,n){let{BackupFileManager:i}=await Promise.resolve().then(()=>(ce(),we)),{BackupManager:s}=await Promise.resolve().then(()=>(Oe(),Ke)),o=new i,a=new s,c=await o.parseBackupFile(e);if(c.encryptionMethod!=="password")throw new g("Can only register with password-encrypted backups. Use syncWalletWithPasskey() or importFromSync() for PRF backups.");let{mnemonic:u,ethereumAddress:l}=await o.restoreWithPassword(c,t),{Wallet:d}=await import("ethers");if(d.fromPhrase(u).address.toLowerCase()!==l.toLowerCase())throw new g("Backup verification failed: address mismatch");return a.markBackupVerified(l),r.currentWallet={address:l,mnemonic:u},r.register({username:n})}async function Yl(){let{DeviceSyncManager:r}=await Promise.resolve().then(()=>(mi(),pi));return new r().getSyncInfo()}async function Jl(r,e){if(!r.currentUser)throw new g("Must be authenticated to export for sync");if(e){let{assertStrongPassword:h}=await Promise.resolve().then(()=>(Re(),ot));h(e)}let t=await r.getMnemonicFromSession(),n=await r.walletStorage.retrieve(r.currentUser.ethereumAddress);if(!n)throw new g("No wallet data found");let s=await new z().getCredentialById(n.credentialId);if(!s)throw new g("Credential not found");let{DeviceSyncManager:o}=await Promise.resolve().then(()=>(mi(),pi)),a=new o,{backupFile:c,blob:u}=await a.exportForSync(t,{id:s.id,publicKey:s.publicKey},r.currentUser.username,e);await Wl(r,c.encryptionMethod==="prf"?"prf":"file");let l=`w3pk-sync-${new Date().toISOString().split("T")[0]}.json`,d;try{d=await a.generateSyncQR(c)}catch(h){console.warn("QR code generation failed:",h)}return{blob:u,filename:l,qrCode:d}}async function Zl(r,e,t={}){let{BackupFileManager:n}=await Promise.resolve().then(()=>(ce(),we)),i=await new n().parseBackupFile(e);if(i.encryptionMethod!=="prf")throw new g("importFromSync() takes PRF backups from exportForSync(). Use syncWalletWithPasskey() for other backups.");if(r.currentUser&&r.currentUser.credentialId!==i.credential.id)throw new he("CREDENTIAL_MISMATCH",r.currentUser.credentialId);let{ethereumAddress:s}=await lo(r,i,t.allowAddressChange??!1);return{ethereumAddress:s,success:!0}}async function Xl(){let{PlatformDetector:r}=await Promise.resolve().then(()=>(Kl(),zl));return new r().detectSyncCapabilities()}async function ou(r,e,t,n){if(!r.currentUser)throw new g("Must be authenticated to set up social recovery");let{assertStrongPassword:i}=await Promise.resolve().then(()=>(Re(),ot));i(n);let s=await r.getMnemonicFromSession(!0),{BackupFileManager:o}=await Promise.resolve().then(()=>(ce(),we)),{backupFile:a}=await new o().createPasswordBackup(s,n,await ao(r),r.currentUser.username),{SocialRecovery:c}=await Promise.resolve().then(()=>(wi(),gi));return{guardianShares:(await new c().splitAmongGuardians(a,e,t,r.currentUser.ethereumAddress)).guardianShares,setupComplete:!0}}async function au(r,e){let{SocialRecovery:t}=await Promise.resolve().then(()=>(wi(),gi)),n=new t,i=await n.createGuardianInvitation(r,e),s=n.createShareDownload(r);return{qrCodeDataURL:i.qrCodeDataURL,shareDocument:i.shareDocument,downloadBlob:s.blob,filename:s.filename}}async function cu(r,e,t,n={}){let{SocialRecovery:i}=await Promise.resolve().then(()=>(wi(),gi)),{BackupFileManager:s}=await Promise.resolve().then(()=>(ce(),we)),o=new i,a=new s,c=e.map(d=>typeof d=="string"?o.parseGuardianShare(d):d),u=await o.recoverFromShares(c),l;if(u.encryptionMethod==="password"){if(!t)throw new g("Password required to decrypt password-protected backup");l=await a.restoreWithPassword(u,t)}else throw new g("PRF backups are not supported for guardian recovery. Use password-protected backups.");if(l.ethereumAddress.toLowerCase()!==c[0].walletAddress.toLowerCase())throw new g("Recovered wallet doesn't match the guardian shares' address");return co(r,l.mnemonic,l.ethereumAddress,n.allowAddressChange??!1)}var dr=class{constructor(e={}){this.currentUser=null;this.currentWallet=null;this.persisted=null;this.ctx=this.createContext();this.config={...Wn,...e},this.walletStorage=new Un;let t={...Wn.persistentSession,...e.persistentSession};this.sessionManager=new On(e.sessionDuration||1,t),e.stealthAddresses!==void 0&&(this.stealth=new Dt(e.stealthAddresses,n=>this.getMnemonicFromSession(n)))}createContext(){let e=this;return{get currentUser(){return e.currentUser},set currentUser(t){e.currentUser=t},get currentWallet(){return e.currentWallet},set currentWallet(t){e.currentWallet=t},get config(){return e.config},get walletStorage(){return e.walletStorage},get sessionManager(){return e.sessionManager},getMnemonicFromSession:(t,n)=>e.getMnemonicFromSession(t,n),storeWallet:(...t)=>e.storeWallet(...t),requestPersistentStorage:()=>e.requestPersistentStorage(),register:t=>e.register(t)}}async loadZKModule(){if(this.zkModule)return this.zkModule;try{let{ZKProofModule:e}=await import("w3pk/zk"),t=this.config.zkProofs||{};return this.zkModule=new e(t),this.zkModule}catch{throw new Error("ZK module not available. Install the optional dependencies snarkjs and circomlibjs")}}async getMnemonicFromSession(e=!1,t="STANDARD"){let n=t;if(!e){let c=this.sessionManager.getMnemonic();if(c)return c}if(!this.currentUser)throw new g("Must be authenticated. Call login() first.");let i=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!i)throw new g("No wallet found. Generate a wallet first.");let s=await wr(this.config.userVerification);if(!s.user)throw new g("Authentication failed");if(!s.prfOutput)throw new ee(s.user.credentialId);let o=await ye(i.encryptedMnemonic,await Bt(s.prfOutput)),a=s.prfOutput?await ct(s.prfOutput,this.sessionManager.storesSessionKey):void 0;return await this.sessionManager.startSession(o,i.credentialId,this.currentUser.ethereumAddress,a,n),o}async storeWallet(e,t,n,i,s=new Date().toISOString()){await this.walletStorage.store({ethereumAddress:e,encryptedMnemonic:await ze(t,await Bt(i)),credentialId:n,createdAt:s})}async register(e){try{this.currentWallet?.address||await this.generateWallet();let t=this.currentWallet.address,n=this.currentWallet.mnemonic,i=await Va({username:e.username,ethereumAddress:t,userVerification:this.config.userVerification}),o=await new z().getCredentialByAddress(t);if(this.currentUser={username:e.username,ethereumAddress:t,credentialId:o?.id||""},!o)throw new g("Credential not found after registration");let a=o.id,c=i.prfOutput;if(!c)try{c=(await Ft(me,a)).output}catch(m){if(!(m instanceof ee))throw m}c&&await this.storeWallet(t,n,a,c);let u=c?await ct(c,this.sessionManager.storesSessionKey):void 0;await this.sessionManager.startSession(n,a,t,u,"STANDARD"),this.currentWallet={address:t,mnemonic:n};let{BackupManager:l}=await Promise.resolve().then(()=>(Oe(),Ke)),d=await new l().hasBackup(t),h=await jn();return this.requestPersistentStorage(),this.config.onAuthStateChanged?.(!0,this.currentUser),{address:t,username:e.username,hasBackup:d,evictionRisk:h}}catch(t){throw this.config.onError?.(t),t}}async login(){try{let e=await this.sessionManager.attemptSilentRestore();if(e){let a=await new z().getCredentialById(e.credentialId);return await this.walletStorage.retrieve(e.ethereumAddress)?(this.currentUser={username:a?.username||e.ethereumAddress,ethereumAddress:e.ethereumAddress,credentialId:e.credentialId},this.requestPersistentStorage(),this.config.onAuthStateChanged?.(!0,this.currentUser),this.currentUser):(await this.sessionManager.clearSession().catch(u=>console.warn("[w3pk] Failed to clear stale session:",u)),this.login())}let t=await wr(this.config.userVerification);if(!t.verified||!t.user)throw new F("Login failed");let n=await this.walletStorage.retrieve(t.user.ethereumAddress);if(!n)throw new Le(t.user.credentialId,t.user.ethereumAddress);this.currentUser={username:t.user.username,ethereumAddress:t.user.ethereumAddress,credentialId:t.user.credentialId};let i=t.prfOutput?await ct(t.prfOutput,this.sessionManager.storesSessionKey):void 0,s=await this.sessionManager.restoreFromPersistentStorage(this.currentUser.ethereumAddress,n.credentialId,i);if(s){if(t.prfOutput){let o=await Bt(t.prfOutput);await ye(n.encryptedMnemonic,o).then(()=>!0,()=>!1)||await this.storeWallet(n.ethereumAddress,s,n.credentialId,t.prfOutput,n.createdAt)}}else{let o=()=>(this.currentUser=null,new Le(t.user.credentialId,t.user.ethereumAddress));if(!t.prfOutput)throw o();let a;try{a=await ye(n.encryptedMnemonic,await Bt(t.prfOutput))}catch(c){throw c instanceof x?o():c}await this.sessionManager.startSession(a,n.credentialId,this.currentUser.ethereumAddress,i,"STANDARD")}return this.requestPersistentStorage(),this.config.onAuthStateChanged?.(!0,this.currentUser),this.currentUser}catch(e){throw this.config.onError?.(e),e}}async logout(){this.currentUser=null,this.currentWallet=null;try{await this.sessionManager.clearSession()}finally{this.config.onAuthStateChanged?.(!1,void 0)}}get isAuthenticated(){return this.currentUser!==null}get user(){return this.currentUser}get storagePersisted(){return this.persisted}async requestPersistentStorage(){if(!(typeof navigator>"u"||!navigator.storage?.persist))try{this.persisted=await navigator.storage.persist()}catch{this.persisted=!1}}async listExistingCredentials(){try{return(await new z().getAllCredentials()).map(n=>({username:n.username,ethereumAddress:n.ethereumAddress,createdAt:n.createdAt,lastUsed:n.lastUsed}))}catch{return[]}}async generateWallet(){try{let e=xr();return this.currentWallet={address:e.address,mnemonic:e.mnemonic},{address:e.address,mnemonic:e.mnemonic}}catch(e){throw this.config.onError?.(e),new g("Failed to generate wallet",e)}}async deriveWallet(e,t,n){try{if(!this.currentUser)throw new g("Must be authenticated to derive wallet");let i=e||ae,s=t||H,o=$();if(i==="PRIMARY"){let{CredentialStorage:l}=await Promise.resolve().then(()=>(De(),En)),{deriveAddressFromP256PublicKey:d}=await Promise.resolve().then(()=>(ut(),Ln)),m=await new l().getCredentialById(this.currentUser.credentialId);if(!m||!m.publicKey)throw new g("No WebAuthn credential found for PRIMARY mode");return{address:await d(m.publicKey),origin:o,mode:i,tag:s,publicKey:m.publicKey}}let a=i==="STRICT"?!0:n?.requireAuth||!1,c=await this.getMnemonicFromSession(a,i),u=await te(c,o,i,s);return{address:u.address,privateKey:u.privateKey,index:u.index,origin:u.origin,mode:u.mode,tag:u.tag}}catch(i){throw this.config.onError?.(i),new g("Failed to derive wallet",i)}}async getAddress(e,t){try{if(!this.currentUser)throw new g("Must be authenticated to get address");let n=e||ae,i=t||H,s=$();if(n==="PRIMARY"){let{deriveAddressFromP256PublicKey:u}=await Promise.resolve().then(()=>(ut(),Ln)),d=await new z().getCredentialById(this.currentUser.credentialId);if(!d||!d.publicKey)throw new g("No WebAuthn credential found for PRIMARY mode");return await u(d.publicKey)}let o=n==="STRICT",a=await this.getMnemonicFromSession(o,n);return(await te(a,s,n,i)).address}catch(n){throw this.config.onError?.(n),new g("Failed to get address",n)}}async importMnemonic(e){try{if(!this.currentUser)throw new g("Must be authenticated to import mnemonic");let t=(e??"").trim().split(/\s+/).join(" "),n=Sr(t).address,i=await wr(this.config.userVerification);if(i.user?.credentialId!==this.currentUser.credentialId)throw new g("Authenticate with the logged-in passkey to import a mnemonic");if(!i.prfOutput)throw new ee(this.currentUser.credentialId);let s=i.prfOutput,o=await new z().getCredentialById(this.currentUser.credentialId);if(!o)throw new g("Credential not found");await Wr(this.ctx,o,t,n,s,!0),this.currentWallet={address:n,mnemonic:t}}catch(t){throw this.config.onError?.(t),t}}async signMessage(e,t){try{let n=t?.mode||ae,i=t?.signingMethod||"EIP191";if(typeof e!="string"&&i!=="EIP191")throw new g(`${i} signing requires a string message`);if(n==="PRIMARY"&&i==="SIWE")throw new g("SIWE signing is not supported in PRIMARY mode. Use STANDARD, STRICT or YOLO mode.");let s=$();if(i==="SIWE"||i==="EIP191"&&typeof e=="string"&&e.includes(fs)){let{assertSiweDomain:m}=await Promise.resolve().then(()=>($n(),oc));m(e,s)}if(i==="rawHash"&&!/^(0x)?[0-9a-fA-F]{64}$/.test(e))throw new g("rawHash signing method requires a 32-byte hash (64 hex characters)");if(!this.currentUser)throw new g("Must be authenticated to sign message");let o=t?.tag||H,a=n==="STRICT"||i==="rawHash"||t?.requireAuth||!1,c=await this.getMnemonicFromSession(a,n),u=await te(c,s,n,o),{Wallet:l}=await import("ethers"),d;if(u.privateKey)d=new l(u.privateKey);else{let{deriveWalletFromMnemonic:m}=await Promise.resolve().then(()=>(Ee(),lt)),{privateKey:y}=m(c,u.index);d=new l(y)}let h;switch(i){case"EIP191":case"SIWE":h=await d.signMessage(e);break;case"EIP712":if(!t?.eip712Domain||!t?.eip712Types||!t?.eip712PrimaryType)throw new g("EIP712 signing requires eip712Domain, eip712Types, and eip712PrimaryType in options");let m;try{m=typeof e=="string"?JSON.parse(e):e}catch{throw new g("EIP712 message must be valid JSON or an object")}h=await d.signTypedData(t.eip712Domain,t.eip712Types,m);break;case"rawHash":let{SigningKey:y}=await import("ethers"),w=e;w.startsWith("0x")&&(w=w.slice(2)),h=new y(d.privateKey).sign("0x"+w).serialized;break;default:throw new g(`Unsupported signing method: ${i}`)}return{signature:h,address:u.address,mode:u.mode,tag:u.tag,origin:u.origin}}catch(n){throw this.config.onError?.(n),new g("Failed to sign message",n)}}async signMessageWithPasskey(e){try{if(!this.currentUser)throw new g("Must be authenticated to sign message");let{extractRS:t}=await Promise.resolve().then(()=>(Bn(),Wa)),{base64UrlDecode:n}=await Promise.resolve().then(()=>(pe(),es)),{bytesToHex:i}=await import("@noble/hashes/utils.js"),s=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)),o="0x"+i(new Uint8Array(s)),a=new Uint8Array(s),c=this.currentUser.credentialId;if(!c)throw new g("Credential ID not found in user object");let u={challenge:a,rpId:window.location.hostname,allowCredentials:[{id:n(c),type:"public-key",transports:["internal","hybrid","usb","nfc","ble"]}],userVerification:this.config.userVerification,timeout:6e4},l=await navigator.credentials.get({publicKey:u});if(!l||!l.response)throw new g("WebAuthn signature failed");let d=l.response,h=new Uint8Array(d.authenticatorData),m=new Uint8Array(d.clientDataJSON),y=await crypto.subtle.digest("SHA-256",m),w=new Uint8Array(h.length+y.byteLength);w.set(h,0),w.set(new Uint8Array(y),h.length);let k=await crypto.subtle.digest("SHA-256",w.buffer),b="0x"+i(new Uint8Array(k)),S=new Uint8Array(d.signature),{r:v,s:I}=t(S),{CredentialStorage:U}=await Promise.resolve().then(()=>(De(),En)),L=await new U().getCredentialById(c);if(!L||!L.publicKey)throw new g("No WebAuthn credential found for PRIMARY mode");let{base64UrlToArrayBuffer:j}=await Promise.resolve().then(()=>(pe(),es)),It=j(L.publicKey),Ef=await crypto.subtle.importKey("spki",It,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),wn=await crypto.subtle.exportKey("jwk",Ef);if(!wn.x||!wn.y)throw new g("Invalid P-256 public key: missing x or y coordinates");let Pf="0x"+i(new Uint8Array(j(wn.x))),If="0x"+i(new Uint8Array(j(wn.y))),{deriveAddressFromP256PublicKey:Cf}=await Promise.resolve().then(()=>(ut(),Ln)),Bf=await Cf(L.publicKey);return{signature:{r:v,s:I},messageHash:o,signedHash:b,address:Bf,publicKey:{qx:Pf,qy:If}}}catch(t){throw this.config.onError?.(t),new g("Failed to sign message with passkey",t)}}async sendTransaction(e,t){try{if(!this.currentUser)throw new g("Must be authenticated to send transaction");let n=t?.mode||ae,i=t?.tag||H,s=$();if(n==="PRIMARY")throw t?.rpcUrl?new g("PRIMARY mode sendTransaction is not yet supported. Use signMessageWithPasskey() to obtain a P-256 signature and submit via a bundler manually."):new g("PRIMARY mode requires options.rpcUrl pointing to a bundler or sponsoring relayer. The P-256 address cannot pay gas directly without a deployed P-256-verifier contract via EIP-7702.");let o=n==="STRICT"?!0:t?.requireAuth||!1,a=await this.getMnemonicFromSession(o,n),c=await te(a,s,n,i),{Wallet:u,JsonRpcProvider:l}=await import("ethers"),d;if(c.privateKey)d=new u(c.privateKey);else{let{deriveWalletFromMnemonic:k}=await Promise.resolve().then(()=>(Ee(),lt)),{privateKey:b}=k(a,c.index);d=new u(b)}let h=t?.rpcUrl??this.config.rpcUrls?.[e.chainId]?.[0]??(await Ut(e.chainId))[0];if(!h)throw new g(`No RPC endpoint found for chainId ${e.chainId}. Set rpcUrls in the config or pass options.rpcUrl.`);let m=new l(h);return{hash:(await d.connect(m).sendTransaction({to:e.to,value:e.value,data:e.data??"0x",chainId:e.chainId,gasLimit:e.gasLimit,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce})).hash,from:c.address,chainId:e.chainId,mode:c.mode,tag:c.tag,origin:c.origin}}catch(n){throw this.config.onError?.(n),new g("Failed to send transaction",n)}}async signAuthorization(e,t){try{if(!this.currentUser)throw new g("Must be authenticated to sign authorization");if("privateKey"in e)throw new g("signAuthorization() takes no privateKey: it signs with the origin-derived key for options.mode and options.tag");let{Wallet:n,Signature:i}=await import("ethers"),{hashEIP7702AuthorizationMessage:s,verifyEIP7702Authorization:o}=await Promise.resolve().then(()=>(ws(),dc)),a=t?.mode||ae,c=t?.tag||H;if(a==="PRIMARY")throw new g("PRIMARY mode cannot sign EIP-7702 authorizations: its P-256 passkey address has no secp256k1 key. Use STANDARD, STRICT or YOLO mode.");let u=$(),l=await this.getMnemonicFromSession(!0,a),d=await te(l,u,a,c),h;if(d.privateKey)h=new n(d.privateKey);else{let{deriveWalletFromMnemonic:I}=await Promise.resolve().then(()=>(Ee(),lt)),{privateKey:U}=I(l,d.index);h=new n(U)}let m=BigInt(e.chainId||1),y=e.nonce||0n,w=s(m,e.contractAddress,y),k=h.signingKey.sign(w),b=i.from(k),S={chainId:m,address:e.contractAddress.toLowerCase(),nonce:y,yParity:b.yParity,r:b.r,s:b.s};if(!o(m,e.contractAddress,y,S,h.address))throw new g("Signature verification failed - this should not happen");return S}catch(n){throw this.config.onError?.(n),new g("Failed to sign authorization",n)}}async getEndpoints(e){let t=this.config.rpcUrls?.[e]??[],n=t.length>0?await Ut(e).catch(()=>[]):await Ut(e);return[...new Set([...t,...n])]}async supportsEIP7702(e,t){return hc(e,this.getEndpoints.bind(this),t)}getEIP1193Provider(e){return mc(this,e)}get zk(){return new Proxy({},{get:(e,t)=>{if(!(typeof t=="symbol"||t==="then"))return async(...n)=>{let i=t==="isAvailable"?await this.loadZKModule().catch(()=>null):await this.loadZKModule();if(!i)return!1;if(!(t in i)||t in Object.prototype)throw new TypeError(`w3pk.zk.${t} is not a function`);let s=i[t];return typeof s=="function"?s.apply(i,n):s}}})}async getBackupStatus(){return Ol(this.ctx)}async confirmRecoveryPhraseBackup(){return ql(this.ctx)}async createBackupFile(e){if(arguments.length>1)throw new g("createBackupFile() takes only the password: createBackupFile(password)");return jl(this.ctx,e)}async setupSocialRecovery(e,t,n){return ou(this.ctx,e,t,n)}async generateGuardianInvite(e,t){return au(e,t)}async recoverFromGuardians(e,t,n){return cu(this.ctx,e,t,n)}async restoreFromBackupFile(e,t,n){return Hl(this.ctx,e,t,n)}async syncWalletWithPasskey(e,t,n){return $l(this.ctx,e,t,n)}async registerWithBackupFile(e,t,n){return Vl(this.ctx,e,t,n)}async getSyncStatus(){return Yl()}async exportForSync(e){return Jl(this.ctx,e)}async importFromSync(e,t){return Zl(this.ctx,e,t)}async detectSyncCapabilities(){return Xl()}hasActiveSession(){return this.sessionManager.isActive()}getSessionRemainingTime(){return this.sessionManager.getRemainingTime()}extendSession(){try{this.sessionManager.extendSession()}catch(e){throw new g("Cannot extend session",e)}}async clearSession(){await this.sessionManager.clearSession()}setSessionDuration(e){this.sessionManager.setSessionDuration(e)}setPersistentSessionDuration(e){this.sessionManager.setPersistentSessionDuration(e)}async derivePrfSecret(e){try{return await Pr(cs,Fe($()),e,this.currentUser?.credentialId)}catch(t){throw this.config.onError?.(t),t}}async getSemaphoreIdentity(e){try{let{SEMAPHORE_PRF_LABEL:t,loadSemaphoreCommitment:n}=await Promise.resolve().then(()=>(po(),uu)),i=await n(),{secret:s,credentialId:o}=await Pr(t,Fe($()),e,this.currentUser?.credentialId);return{commitment:i(s),credentialId:o}}catch(t){throw this.config.onError?.(t),t}}async zkProve(e,t,n,i={},s={}){try{qn(e);let{zkProve:o}=await Promise.resolve().then(()=>(wf(),gf)),a=Fe($()),c=this.currentUser?.credentialId;return await o(async u=>(await Pr(u,a,e,c)).secret,t,n,i,s)}catch(o){throw this.config.onError?.(o),o}}async deriveMLKemPublicKey(e){return Ic(this.ctx,e)}async mlkemEncrypt(e,t,n){return Cc(this.ctx,e,t,n)}async mlkemDecrypt(e,t){return Bc(this.ctx,e,t)}};T();Ms();ut();var gn=class{getScenarios(){return[{type:"lost-device",description:"Your phone fell in the ocean"},{type:"lost-phrase",description:"Your paper backup burned in a fire"},{type:"lost-both",description:"Phone stolen AND forgot recovery phrase"},{type:"switch-platform",description:"Switching from iPhone to Android"}]}async simulateScenario(e,t){let n=[];switch(e.type){case"lost-device":t.passkeySync.enabled&&t.passkeySync.deviceCount>1&&n.push({method:`Passkey Sync (${t.passkeySync.platform})`,success:!0,time:"5 minutes",requirements:["Sign in to cloud account on new device","Authenticate with biometric/PIN"]}),t.recoveryPhrase.encryptedBackups.length>0&&t.recoveryPhrase.encryptedBackups.forEach(o=>{n.push({method:`Encrypted ${o.method.toUpperCase()} Backup`,success:!0,time:"2 minutes",requirements:["Backup file/QR code","Backup password"]})});break;case"lost-phrase":t.passkeySync.enabled&&n.push({method:"Passkey (current device)",success:!0,time:"Instant",requirements:["Access to current device","Biometric/PIN authentication"]}),t.passkeySync.deviceCount>1&&n.push({method:"Passkey Sync",success:!0,time:"5 minutes",requirements:["Any synced device","Biometric authentication"]}),t.recoveryPhrase.encryptedBackups.length>0&&n.push({method:"Encrypted Backup",success:!0,time:"2 minutes",requirements:["Backup file","Password"]});break;case"lost-both":t.passkeySync.deviceCount>1&&n.push({method:"Passkey Sync",success:!0,time:"5 minutes",requirements:["Cloud account access","New device","Biometric setup"]});break;case"switch-platform":t.recoveryPhrase.encryptedBackups.length>0&&n.push({method:"Encrypted Backup",success:!0,time:"2 minutes",requirements:["Backup file","Password"]});break}let i=n.length>0,s=this.getEducationalNote(e,n,t);return{scenario:e,success:i,availableMethods:n,timeEstimate:i?this.estimateFastestRecovery(n):"Cannot recover",educationalNote:s}}estimateFastestRecovery(e){let t=e.map(n=>n.time.toLowerCase());if(t.some(n=>n.includes("instant")))return"Instant";if(t.some(n=>n.includes("minute"))){let n=t.filter(i=>i.includes("minute")).map(i=>parseInt(i));return`${Math.min(...n)} minutes`}return t.some(n=>n.includes("hour"))?"24 hours":"Unknown"}getEducationalNote(e,t,n){let i=n.securityScore.total,s=n.securityScore.level;if(t.length===0)return`
391
1147
  \u274C WALLET CANNOT BE RECOVERED
392
1148
 
393
1149
  Scenario: ${e.description}
394
- Current Security Score: ${s}/100 (${i})
1150
+ Current Security Score: ${i}/70 (${s})
395
1151
 
396
1152
  Unfortunately, you have no recovery options for this scenario.
397
1153
 
@@ -400,7 +1156,7 @@ This is why backup is critical!
400
1156
  IMMEDIATE ACTION REQUIRED:
401
1157
  -------------------------
402
1158
 
403
- To prevent permanent loss, set up AT LEAST TWO of these:
1159
+ To prevent permanent loss, set up both of these:
404
1160
 
405
1161
  1. Encrypted Backup (+20 pts)
406
1162
  - Takes 2 minutes
@@ -408,19 +1164,13 @@ To prevent permanent loss, set up AT LEAST TWO of these:
408
1164
  - Requires password
409
1165
  [Create backup now]
410
1166
 
411
- 2. Social Recovery (+20-30 pts)
412
- - Takes 30 minutes setup
413
- - Most secure
414
- - Requires 3-5 trusted friends
415
- [Set up guardians]
416
-
417
- 3. Verify Your Backup (+10 pts)
1167
+ 2. Verify Your Backup (+10 pts)
418
1168
  - Test restore process
419
1169
  - Proves backup works
420
1170
  - Takes 5 minutes
421
1171
  [Test backup now]
422
1172
 
423
- Target: Reach at least 50/100 for basic protection!
1173
+ Target: Reach at least 21/70 for basic protection!
424
1174
 
425
1175
  ---
426
1176
 
@@ -428,82 +1178,62 @@ Don't wait until it's too late!
428
1178
  `;let o=`\u2705 YOU CAN RECOVER!
429
1179
 
430
1180
  Scenario: ${e.description}
431
- `;return o+=`Security Score: ${s}/100 (${i})
1181
+ `;o+=`Security Score: ${i}/70 (${s})
432
1182
 
433
1183
  `,o+=`Available recovery methods (${t.length}):
434
1184
 
435
- `,t.forEach((a,c)=>{o+=`${c+1}. ${a.method}
436
- `,o+=` \u23F1 Time: ~${a.time}
1185
+ `,t.forEach((c,u)=>{o+=`${u+1}. ${c.method}
1186
+ `,o+=` \u23F1 Time: ~${c.time}
437
1187
  `,o+=` Requirements:
438
- `,a.requirements.forEach(l=>{o+=` - ${l}
1188
+ `,c.requirements.forEach(l=>{o+=` - ${l}
439
1189
  `}),o+=`
440
1190
  `}),o+=`
441
1191
  SECURITY RECOMMENDATIONS:
442
- `,s<50?(o+=`\u26A0\uFE0F Your score is below 50/100.
443
- `,o+=` Add more backups to improve protection:
444
-
445
- `,n.recoveryPhrase.encryptedBackups.length||(o+=` \u{1F4E5} Create encrypted backup \u2192 +20 pts
446
- `),n.recoveryPhrase.verified||(o+=` \u2705 Verify your backup \u2192 +10 pts
447
- `),n.socialRecovery?.enabled||(o+=` \u{1F465} Set up social recovery \u2192 +20-30 pts
448
- `)):s<70?(o+=`\u{1F7E1} Good start! Score: ${s}/100
449
-
450
- `,n.socialRecovery?.enabled||(o+=` \u{1F465} Add social recovery \u2192 +20-30 pts
451
- `),n.recoveryPhrase.verified||(o+=` \u2705 Verify your backup \u2192 +10 pts
452
- `),o+=`
453
- Target: Reach 70+ for "secured" status!
454
- `):s<80?(o+=`\u{1F7E2} Great! Score: ${s}/100
455
-
456
- `,n.socialRecovery&&n.socialRecovery.verifiedGuardians<n.socialRecovery.threshold&&(o+=` \u{1F465} Verify your guardians \u2192 +10 pts
457
- `),n.passkeySync.deviceCount===1&&(o+=` \u{1F4F1} Sync passkey to another device \u2192 +10 pts
458
- `),o+=`
1192
+ `;let{nextMilestone:a}=n.securityScore;return s==="vulnerable"?(o+=`\u26A0\uFE0F Your score is 20/70 or below.
1193
+ `,o+=` ${a}
1194
+ `):s==="protected"?(o+=`\u{1F7E1} Good start! Score: ${i}/70
1195
+
1196
+ `,o+=` ${a}
1197
+ `):s==="secured"?(o+=`\u{1F7E2} Great! Score: ${i}/70
1198
+
1199
+ `,o+=` ${a}
1200
+ `,o+=`
459
1201
  You're close to "fort-knox" status!
460
- `):(o+=`\u{1F3C6} Excellent! Score: ${s}/100
1202
+ `):(o+=`\u{1F3C6} Excellent! Score: ${i}/70
461
1203
  `,o+=` Your wallet is extremely well-protected!
462
1204
  `,o+=` You can survive almost any disaster scenario.
463
- `),o}async runInteractiveTest(e){let t=this.getScenarios(),n=[];for(let u of t){let d=await this.simulateScenario(u,e);n.push(d)}let s=n.filter(u=>u.success).length,i=s/t.length*100,o=e.securityScore.total,a=e.securityScore.level,c="";c+=`RECOVERY TEST RESULTS
1205
+ `),o}async runInteractiveTest(e){let t=this.getScenarios(),n=[];for(let d of t){let h=await this.simulateScenario(d,e);n.push(h)}let i=n.filter(d=>d.success).length,s=i/t.length*100,o=e.securityScore.total,a=e.securityScore.level,c="";c+=`RECOVERY TEST RESULTS
464
1206
  `,c+=`${"=".repeat(50)}
465
1207
 
466
- `,i===100?c+=`\u{1F3C6} PERFECT! You can recover in ALL scenarios.
467
- `:i>=75?c+=`\u{1F7E2} GREAT! You can recover in ${s}/${t.length} scenarios.
468
- `:i>=50?c+=`\u{1F7E1} GOOD! You can recover in ${s}/${t.length} scenarios.
469
- `:c+=`\u26A0\uFE0F AT RISK! You can only recover in ${s}/${t.length} scenarios.
1208
+ `,s===100?c+=`\u{1F3C6} PERFECT! You can recover in ALL scenarios.
1209
+ `:s>=75?c+=`\u{1F7E2} GREAT! You can recover in ${i}/${t.length} scenarios.
1210
+ `:s>=50?c+=`\u{1F7E1} GOOD! You can recover in ${i}/${t.length} scenarios.
1211
+ `:c+=`\u26A0\uFE0F AT RISK! You can only recover in ${i}/${t.length} scenarios.
470
1212
  `,c+=`
471
- SECURITY SCORE: ${o}/100 (${a})
1213
+ SECURITY SCORE: ${o}/70 (${a})
472
1214
  `,c+=`${"=".repeat(50)}
473
1215
 
474
1216
  `,c+=`SCORE BREAKDOWN:
475
1217
 
476
- `;let l=e.securityScore.breakdown;return c+=`\u{1F511} Passkey Active: ${l.passkeyActive}/20
477
- `,c+=`\u{1F4F1} Multi-Device Sync: ${l.passkeyMultiDevice}/10
478
- `,c+=`\u{1F4BE} Encrypted Backup: ${l.encryptedBackup}/20
479
- `,c+=`\u2705 Backup Verified: ${l.phraseVerified}/20
480
- `,c+=`\u{1F465} Social Recovery: ${l.socialRecovery}/30
1218
+ `;let u=e.securityScore.breakdown;c+=`\u{1F511} Passkey Active: ${u.passkeyActive}/20
1219
+ `,c+=`\u{1F4F1} Multi-Device Sync: ${u.passkeyMultiDevice}/10
1220
+ `,c+=`\u{1F4BE} Encrypted Backup: ${u.encryptedBackup}/20
1221
+ `,c+=`\u2705 Backup Verified: ${u.phraseVerified}/20
481
1222
 
482
1223
  `,c+=`NEXT STEPS:
483
1224
  `,c+=`${"=".repeat(50)}
484
1225
 
485
- `,o>=80?(c+=`\u{1F3C6} Excellent security posture!
1226
+ `;let{nextMilestone:l}=e.securityScore;return a==="fort-knox"?(c+=`\u{1F3C6} Excellent security posture!
486
1227
  `,c+=`Your wallet is extremely well-protected.
487
1228
 
488
- `,o<100&&(c+=`To reach perfect 100/100:
489
- `,l.passkeyMultiDevice===0&&(c+=` \u2022 Sync passkey to another device (+10 pts)
490
- `),l.phraseVerified<20&&(c+=` \u2022 Verify your backup multiple times (+${20-l.phraseVerified} pts)
491
- `),l.socialRecovery<30&&(c+=` \u2022 Verify all your guardians (+${30-l.socialRecovery} pts)
492
- `))):o>=50?(c+=`${e.securityScore.nextMilestone}
493
-
494
- `,c+=`Recommended actions:
495
- `,l.encryptedBackup===0&&(c+=` 1. Create encrypted backup (+20 pts)
496
- `),l.phraseVerified===0&&(c+=` 2. Test your backup (+10 pts)
497
- `),l.socialRecovery===0&&(c+=` 3. Set up social recovery (+20-30 pts)
498
- `)):(c+=`\u26A0\uFE0F URGENT: Your wallet security is at risk!
499
-
500
- `,c+=`Critical actions needed:
501
- `,c+=` 1. Create encrypted backup NOW (+20 pts)
502
- `,c+=` 2. Test the backup immediately (+10 pts)
503
- `,c+=` 3. Set up social recovery (+20-30 pts)
504
-
505
- `,c+=`Target: Reach at least 50/100 for basic protection.
506
- `),{scenarios:n,overallScore:i,securityScore:o,feedback:c}}}});function Hi(r){return ls[r]||null}function qi(){return Object.keys(ls)}function Vi(r){let e=r.toLowerCase();return Object.values(ls).filter(t=>t.title.toLowerCase().includes(e)||t.content.toLowerCase().includes(e))}var ls,il=p(()=>{"use strict";ls={whatIsPasskey:{title:"What is a Passkey?",content:`
1229
+ `,o<70&&(c+=`${l}
1230
+ `)):a!=="vulnerable"?c+=`${l}
1231
+ `:(c+=`\u26A0\uFE0F URGENT: Your wallet security is at risk!
1232
+
1233
+ `,c+=`${l}
1234
+
1235
+ `,c+=`Target: Reach at least 21/70 for basic protection.
1236
+ `),{scenarios:n,overallScore:s,securityScore:o,feedback:c}}};var Fa={whatIsPasskey:{title:"What is a Passkey?",content:`
507
1237
  Think of a passkey like your house smart lock:
508
1238
 
509
1239
  \u{1F511} Traditional Key (Password):
@@ -741,7 +1471,7 @@ Your encrypted backup uses military-grade encryption.
741
1471
  ENCRYPTION DETAILS:
742
1472
  ------------------
743
1473
 
744
- Password \u2192 PBKDF2 (310,000 iterations)
1474
+ Password \u2192 Argon2id (64 MiB memory, 3 passes)
745
1475
  \u2193
746
1476
  256-bit AES Key
747
1477
  \u2193
@@ -752,10 +1482,11 @@ Password \u2192 PBKDF2 (310,000 iterations)
752
1482
  WHAT THIS MEANS:
753
1483
  ---------------
754
1484
 
755
- 310,000 iterations:
756
- - Makes brute-force extremely slow
757
- - Would take centuries to crack
758
- - OWASP 2025 standard
1485
+ Argon2id:
1486
+ - Memory-hard: each guess needs 64 MiB of memory,
1487
+ which limits how many guesses a GPU can run at once
1488
+ - Recommended by RFC 9106 and OWASP
1489
+ - The file holds no address, so it doesn't say whose wallet it is
759
1490
 
760
1491
  AES-256-GCM:
761
1492
  - Used by governments/military
@@ -772,7 +1503,7 @@ Q: What if someone gets your password?
772
1503
  A: Need BOTH password AND backup file
773
1504
 
774
1505
  Q: What if someone tries to brute-force?
775
- A: 310,000 iterations makes this impractical
1506
+ A: Argon2id makes each guess slow and memory-hungry; a strong password makes it impractical
776
1507
 
777
1508
  Q: Can the backup be tampered with?
778
1509
  A: No - GCM mode detects any changes
@@ -788,7 +1519,7 @@ WEAK (\u274C Rejected):
788
1519
  GOOD (\u2713 Accepted):
789
1520
  - "MyDog-Loves-Pizza-2025!"
790
1521
  - "Tr0ub4dor&3-Extra-Secure"
791
- - "correct-horse-battery-staple-99"
1522
+ - "Correct-Horse-Battery-Staple-99"
792
1523
 
793
1524
  STRONG (\u2713\u2713 Recommended):
794
1525
  - 16+ characters
@@ -815,11 +1546,11 @@ WHAT IS IT?
815
1546
 
816
1547
  Think of it like a health score for your wallet:
817
1548
  - 0-20 pts: Vulnerable (\u274C At risk!)
818
- - 21-50 pts: Protected (\u{1F7E1} Basic security)
819
- - 51-80 pts: Secured (\u{1F7E2} Strong protection)
820
- - 81-100 pts: Fort Knox (\u{1F3C6} Maximum security)
1549
+ - 21-40 pts: Protected (\u{1F7E1} Basic security)
1550
+ - 41-60 pts: Secured (\u{1F7E2} Strong protection)
1551
+ - 61-70 pts: Fort Knox (\u{1F3C6} Maximum security)
821
1552
 
822
- HOW IT'S CALCULATED (Max 100 Points):
1553
+ HOW IT'S CALCULATED (Max 70 Points):
823
1554
  ------------------------------------
824
1555
 
825
1556
  \u{1F511} Passkey Active (20 pts)
@@ -843,44 +1574,37 @@ HOW IT'S CALCULATED (Max 100 Points):
843
1574
  - Password-protected
844
1575
  - Works anywhere
845
1576
 
846
- \u{1F465} Social Recovery (20-30 pts)
847
- - Guardians can help you
848
- - 20 pts for setup
849
- - +10 pts bonus if guardians verified
850
- - Ultimate safety net
851
-
852
1577
  REAL EXAMPLE:
853
1578
  ------------
854
1579
 
855
1580
  Sarah's wallet evolution:
856
1581
 
857
1582
  Day 1: Just created wallet
858
- Score: 20/100 (Vulnerable)
1583
+ Score: 20/70 (Vulnerable)
859
1584
  - Passkey only
860
1585
  - No backup
861
1586
  - One device failure = total loss
862
1587
 
863
1588
  Day 2: Created encrypted backup
864
- Score: 40/100 (Protected)
1589
+ Score: 40/70 (Protected)
865
1590
  - Passkey + backup
866
1591
  - Can recover if device lost
867
1592
  - Still risky if both fail
868
1593
 
869
1594
  Day 5: Tested backup restore
870
- Score: 50/100 (Protected)
1595
+ Score: 50/70 (Secured)
871
1596
  - Verified backup works!
872
1597
  - Proven recovery path
873
1598
  - More confident
874
1599
 
875
- Week 2: Set up social recovery
876
- Score: 70/100 (Secured)
877
- - 5 trusted guardians
878
- - Need 3 to recover
879
- - Multiple safety nets
1600
+ Week 2: Synced passkey to her laptop
1601
+ Score: 60/70 (Secured)
1602
+ - Passkey on 2 devices
1603
+ - Survives losing either one
880
1604
 
881
- Week 3: Guardians verified
882
- Score: 80/100 (Secured)
883
- - All guardians confirmed
1605
+ Week 3: Tested the backup again
1606
+ Score: 61/70 (Fort Knox)
1607
+ - Each extra test adds a point, up to 70
884
1608
  - Strong multi-layer protection
885
1609
  - Can survive almost any disaster
886
1610
 
@@ -910,8 +1634,6 @@ AUTOMATIC TRACKING:
910
1634
  Your score updates automatically when you:
911
1635
  \u2713 Create a backup file
912
1636
  \u2713 Restore from backup
913
- \u2713 Set up social recovery
914
- \u2713 Verify guardians
915
1637
  \u2713 Sync across devices
916
1638
 
917
1639
  No manual tracking needed!
@@ -927,78 +1649,21 @@ From 40 \u2192 50 pts:
927
1649
  2. Test your backup (5 minutes)
928
1650
  + 10 points
929
1651
 
930
- From 50 \u2192 70 pts:
931
- 3. Set up social recovery (30 minutes)
932
- + 20 points
933
-
934
- From 70 \u2192 80 pts:
935
- 4. Verify your guardians
1652
+ From 50 \u2192 60 pts:
1653
+ 3. Sync passkey to another device
936
1654
  + 10 points
937
1655
 
938
- From 80 \u2192 90 pts:
939
- 5. Sync passkey to another device
940
- + 10 points
1656
+ From 60 \u2192 70 pts:
1657
+ 4. Test your backup again
1658
+ + 1 point per test, up to 10
941
1659
 
942
1660
  TARGET SCORE:
943
1661
  ------------
944
1662
 
945
- Minimum: 50 pts (at least verified backup)
946
- Good: 70 pts (backup + social recovery)
947
- Excellent: 80+ pts (all layers enabled)
1663
+ Minimum: 41 pts (backup + one more layer)
1664
+ Good: 50 pts (verified backup)
1665
+ Excellent: 61+ pts (all layers enabled)
948
1666
 
949
1667
  Remember: Higher score = Lower chance of loss!
950
- `}}});var us={};x(us,{RecoverySimulator:()=>Nt,educationalModules:()=>ls,getAllTopics:()=>qi,getExplainer:()=>Hi,searchExplainers:()=>Vi});var Lr=p(()=>{"use strict";sl();il()});var ps={};x(ps,{deriveMLKemKeypair:()=>_r,mlkemDecrypt:()=>fs,mlkemDecryptWithKey:()=>Qi,mlkemEncrypt:()=>hs,mlkemEncryptWithKey:()=>Ji});function Me(r){r.fill(0)}function Lt(r){if(typeof btoa<"u"){let e=Array.from(r).map(t=>String.fromCharCode(t)).join("");return btoa(e)}return Buffer.from(r).toString("base64")}function ht(r){if(typeof atob<"u"){let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}return new Uint8Array(Buffer.from(r,"base64"))}async function cl(r,e){let t=(0,Yi.hkdf)(ji.sha256,r,new Uint8Array(0),new TextEncoder().encode(ap),32);try{return await crypto.subtle.importKey("raw",t,"AES-KW",!1,[e])}finally{Me(t)}}async function cp(r,e,t){if(r===2){let s=await cl(e,"unwrapKey");return crypto.subtle.unwrapKey("raw",t,s,"AES-KW",{name:"AES-GCM"},!1,["decrypt"])}let n=new Uint8Array(32);try{for(let s=0;s<32;s++)n[s]=t[s]^e[s];return await crypto.subtle.importKey("raw",n,{name:"AES-GCM"},!1,["decrypt"])}finally{Me(n)}}async function _r(r,e="mlkem-v1"){let t=await(0,ds.createMlKem1024)(),n;if(typeof r=="string"){let i=r.startsWith("0x")?r.slice(2):r;if(typeof Buffer<"u")n=new Uint8Array(Buffer.from(i,"hex"));else{let o=new Uint8Array(i.length/2);for(let a=0;a<i.length;a+=2)o[a/2]=parseInt(i.substring(a,a+2),16);n=o}}else n=r;let s=(0,Yi.hkdf)(ji.sha256,n,new Uint8Array(Buffer.from("mlkem-keypair-v1","utf-8")),new Uint8Array(Buffer.from(e,"utf-8")),64);try{let[i,o]=t.deriveKeyPair(s);return{publicKey:i,privateKey:o}}finally{Me(s),Me(n)}}async function hs(r,e){let t=await(0,ds.createMlKem1024)(),n=Array.isArray(e)?e:[e];if(n.length===0)throw new Error("At least one public key is required");let s=new Uint8Array(32);crypto.getRandomValues(s);try{let i=new Uint8Array(12);crypto.getRandomValues(i);let a=new TextEncoder().encode(r),c=await crypto.subtle.importKey("raw",s,{name:"AES-GCM"},!0,["encrypt"]),l=await crypto.subtle.encrypt({name:"AES-GCM",iv:i,tagLength:128},c,a),u=new Uint8Array(l),d=16;if(u.length<d)throw new Error("Encrypted data too short to contain auth tag");let h=u.slice(0,-d),m=u.slice(-d),y=[];for(let w of n){let b=typeof w=="string"?ht(w):w;if(b.length!==1568)throw new Error(`Invalid ML-KEM public key size: ${b.length} (expected 1568)`);let[S,A]=t.encap(b);try{let v=await cl(A,"wrapKey"),B=new Uint8Array(await crypto.subtle.wrapKey("raw",c,v,"AES-KW")),E=new Uint8Array(S.length+B.length);E.set(S,0),E.set(B,S.length),y.push({publicKey:Lt(b),ciphertext:Lt(E)})}finally{Me(A)}}return{version:2,recipients:y,encryptedData:Lt(h),iv:Lt(i),authTag:Lt(m)}}finally{Me(s)}}async function fs(r,e,t){let n=await(0,ds.createMlKem1024)(),s=typeof e=="string"?ht(e):e;if(s.length!==3168)throw new Error(`Invalid ML-KEM private key size: ${s.length} (expected 3168)`);let i=r.version??1;if(i!==1&&i!==2)throw new Error(`Unsupported payload version: ${String(i)}`);let o=ht(r.encryptedData),a=ht(r.iv),c=ht(r.authTag);if(a.length!==ol)throw new Error(`Invalid IV size: ${a.length} (expected ${ol})`);if(c.length!==al)throw new Error(`Invalid auth tag size: ${c.length} (expected ${al})`);let l=Gi+op[i],u=async m=>{let y=ht(m);if(y.length!==l)throw new Error(`Invalid combined ciphertext size: ${y.length} (expected ${l})`);let w=y.slice(0,Gi),b=y.slice(Gi),S=n.decap(w,s);try{return await cp(i,S,b)}finally{Me(S)}},d=new Uint8Array(o.length+c.length);d.set(o,0),d.set(c,o.length);let h=async m=>{let y=await u(m),w=await crypto.subtle.decrypt({name:"AES-GCM",iv:a,tagLength:128},y,d);return new TextDecoder().decode(w)};if(t){let m=typeof t=="string"?ht(t):t,y=Lt(m),w=r.recipients.find(b=>b.publicKey===y);if(!w)throw new Error("Public key not found in recipients list");return h(w.ciphertext)}for(let m of r.recipients)try{return await h(m.ciphertext)}catch{continue}throw new Error("No matching recipient found for this private key")}async function Ji(r,e,t,n="mlkem-v1"){let s=await _r(e,n);try{let i=[s.publicKey,...t];return await hs(r,i)}finally{Me(s.privateKey)}}async function Qi(r,e,t="mlkem-v1"){let n=await _r(e,t);try{return await fs(r,n.privateKey,n.publicKey)}finally{Me(n.privateKey)}}var ds,Yi,ji,Gi,op,ol,al,ap,Kr=p(()=>{"use strict";ds=require("mlkem"),Yi=require("@noble/hashes/hkdf.js"),ji=require("@noble/hashes/sha2.js"),Gi=1568,op={1:32,2:40},ol=12,al=16,ap="w3pk-mlkem-kek-v2"});function lp(r){return r[Symbol.asyncIterator]!=null}function up(r){if(lp(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var Xi,dl=p(()=>{"use strict";Xi=up});function dp(r){return r[Symbol.asyncIterator]!=null}function hp(r,e=1){return e=Number(e),dp(r)?(async function*(){let t=[];if(e<1&&(e=1),e!==Math.round(e))throw new Error("Batch size must be an integer");for await(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)})():(function*(){let t=[];if(e<1&&(e=1),e!==Math.round(e))throw new Error("Batch size must be an integer");for(let n of r)for(t.push(n);t.length>=e;)yield t.slice(0,e),t=t.slice(e);for(;t.length>0;)yield t.slice(0,e),t=t.slice(e)})()}var ms,Zi=p(()=>{"use strict";ms=hp});async function*Or(r,e=1){for await(let t of ms(r,e)){let n=t.map(async s=>s().then(i=>({ok:!0,value:i}),i=>({ok:!1,err:i})));for(let s=0;s<n.length;s++){let i=await n[s];if(i.ok)yield i.value;else throw i.err}}}var eo=p(()=>{"use strict";Zi()});function Ue(r=0){return new Uint8Array(r)}function oe(r=0){return new Uint8Array(r)}var ft=p(()=>{"use strict"});function fp(r){return r?.buffer instanceof ArrayBuffer}function hl(r){if(fp(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}var fl=p(()=>{"use strict"});function zr(r,e){e==null&&(e=r.reduce((s,i)=>s+i.length,0));let t=oe(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return hl(t)}var to=p(()=>{"use strict";ft();fl()});function pl(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}var ml=p(()=>{"use strict"});function yl(r,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let n of r){let s=t+n.byteLength;if(e<s)return{buf:n,index:e-t};t=s}throw new RangeError("index is out of bounds")}function ys(r){return!!r?.[wl]}var wl,gl,Kt,bl=p(()=>{"use strict";ft();to();ml();wl=Symbol.for("@achingbrain/uint8arraylist");Kt=class r{constructor(...e){f(this,"bufs");f(this,"length");f(this,gl,!0);this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[(gl=wl,Symbol.iterator)](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let n of e)if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.push(n);else if(ys(n)){t+=n.byteLength;for(let s of n.bufs)this.bufs.push(s)}else throw new Error("Could not append value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}prepend(...e){this.prependAll(e)}prependAll(e){let t=0;for(let n of e.reverse())if(n instanceof Uint8Array)t+=n.byteLength,this.bufs.unshift(n);else if(ys(n))t+=n.byteLength,this.bufs.unshift(...n.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=yl(this.bufs,e);return t.buf[t.index]}set(e,t){let n=yl(this.bufs,e);n.buf[n.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let n=0;n<e.length;n++)this.set(t+n,e[n]);else if(ys(e))for(let n=0;n<e.length;n++)this.set(t+n,e.get(n));else throw new Error("Could not write value, must be an Uint8Array or a Uint8ArrayList")}consume(e){if(e=Math.trunc(e),!(Number.isNaN(e)||e<=0)){if(e===this.byteLength){this.bufs=[],this.length=0;return}for(;this.bufs.length>0;)if(e>=this.bufs[0].byteLength)e-=this.bufs[0].byteLength,this.length-=this.bufs[0].byteLength,this.bufs.shift();else{this.bufs[0]=this.bufs[0].subarray(e),this.length-=e;break}}}slice(e,t){let{bufs:n,length:s}=this._subList(e,t);return zr(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:zr(n,s)}sublist(e,t){let{bufs:n,length:s}=this._subList(e,t),i=new r;return i.length=s,i.bufs=n,i}_subList(e,t){if(e=e??0,t=t??this.length,e<0&&(e=this.length+e),t<0&&(t=this.length+t),e<0||t>this.length)throw new RangeError("index is out of bounds");if(e===t)return{bufs:[],length:0};if(e===0&&t===this.length)return{bufs:[...this.bufs],length:this.length};let n=[],s=0;for(let i=0;i<this.bufs.length;i++){let o=this.bufs[i],a=s,c=a+o.byteLength;if(s=c,e>=c)continue;let l=e>=a&&e<c,u=t>a&&t<=c;if(l&&u){if(e===a&&t===c){n.push(o);break}let d=e-a;n.push(o.subarray(d,d+(t-e)));break}if(l){if(e===0){n.push(o);continue}n.push(o.subarray(e-a));continue}if(u){if(t===c){n.push(o);break}n.push(o.subarray(0,t-a));break}n.push(o)}return{bufs:n,length:t-e}}indexOf(e,t=0){if(!ys(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let n=e instanceof Uint8Array?e:e.subarray();if(t=Number(t??0),isNaN(t)&&(t=0),t<0&&(t=this.length+t),t<0&&(t=0),e.length===0)return t>this.length?this.length:t;let s=n.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let i=256,o=new Int32Array(i);for(let d=0;d<i;d++)o[d]=-1;for(let d=0;d<s;d++)o[n[d]]=d;let a=o,c=this.byteLength-n.byteLength,l=n.byteLength-1,u;for(let d=t;d<=c;d+=u){u=0;for(let h=l;h>=0;h--){let m=this.get(d+h);if(n[h]!==m){u=Math.max(1,h-a[m]);break}}if(u===0)return d}return-1}getInt8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getInt8(0)}setInt8(e,t){let n=oe(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setInt8(0,t),this.write(n,e)}getInt16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt16(0,t)}setInt16(e,t,n){let s=Ue(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,n),this.write(s,e)}getInt32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getInt32(0,t)}setInt32(e,t,n){let s=Ue(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,n),this.write(s,e)}getBigInt64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigInt64(0,t)}setBigInt64(e,t,n){let s=Ue(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,n),this.write(s,e)}getUint8(e){let t=this.subarray(e,e+1);return new DataView(t.buffer,t.byteOffset,t.byteLength).getUint8(0)}setUint8(e,t){let n=oe(1);new DataView(n.buffer,n.byteOffset,n.byteLength).setUint8(0,t),this.write(n,e)}getUint16(e,t){let n=this.subarray(e,e+2);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint16(0,t)}setUint16(e,t,n){let s=Ue(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,n),this.write(s,e)}getUint32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getUint32(0,t)}setUint32(e,t,n){let s=Ue(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,n),this.write(s,e)}getBigUint64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getBigUint64(0,t)}setBigUint64(e,t,n){let s=Ue(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,n),this.write(s,e)}getFloat32(e,t){let n=this.subarray(e,e+4);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat32(0,t)}setFloat32(e,t,n){let s=Ue(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,n),this.write(s,e)}getFloat64(e,t){let n=this.subarray(e,e+8);return new DataView(n.buffer,n.byteOffset,n.byteLength).getFloat64(0,t)}setFloat64(e,t,n){let s=Ue(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,n),this.write(s,e)}equals(e){if(e==null||!(e instanceof r)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!pl(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let n=new r;return n.bufs=e,t==null&&(t=e.reduce((s,i)=>s+i.byteLength,0)),n.length=t,n}}});var ro,gs,ws,Sl,bs,Al,xl,vl,kl,El,Cl,Pl,Wr=p(()=>{"use strict";ro=BigInt(34),gs=8,ws=262144,Sl="links-bytes",bs=262144,Al=1048576,xl=50,vl=10,kl=!0,El=!0,Cl=!1,Pl="file"});var Il,Bl=p(()=>{"use strict";bl();Wr();Il=(r={})=>{let e=r.chunkSize??bs;return async function*(n){let s=new Kt,i=0,o=!1;for await(let a of n)for(s.append(a),i+=a.length;i>=e;)if(yield s.subarray(0,e),o=!0,e===s.length)s=new Kt,i=0;else{let l=new Kt;l.append(s.sublist(e)),s=l,i-=e}(!o||i>0)&&(yield s.subarray(0,i))}}});function Tl(r,e){if(r===e)return!0;if(r.byteLength!==e.byteLength)return!1;for(let t=0;t<r.byteLength;t++)if(r[t]!==e[t])return!1;return!0}function Se(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return pt(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return pt(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function Rl(r){return new TextEncoder().encode(r)}function Dl(r){return new TextDecoder().decode(r)}function pp(r){return r?.buffer instanceof ArrayBuffer}function pt(r){return pp(r)?r:r.slice()}var q0,qe=p(()=>{"use strict";q0=new Uint8Array(0)});function mp(r,e){if(r.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var s=0;s<r.length;s++){var i=r.charAt(s),o=i.charCodeAt(0);if(t[o]!==255)throw new TypeError(i+" is ambiguous");t[o]=s}var a=r.length,c=r.charAt(0),l=Math.log(a)/Math.log(256),u=Math.log(256)/Math.log(a);function d(y){if(y instanceof Uint8Array||(ArrayBuffer.isView(y)?y=new Uint8Array(y.buffer,y.byteOffset,y.byteLength):Array.isArray(y)&&(y=Uint8Array.from(y))),!(y instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(y.length===0)return"";for(var w=0,b=0,S=0,A=y.length;S!==A&&y[S]===0;)S++,w++;for(var v=(A-S)*u+1>>>0,B=new Uint8Array(v);S!==A;){for(var E=y[S],U=0,F=v-1;(E!==0||U<b)&&F!==-1;F--,U++)E+=256*B[F]>>>0,B[F]=E%a>>>0,E=E/a>>>0;if(E!==0)throw new Error("Non-zero carry");b=U,S++}for(var $=v-b;$!==v&&B[$]===0;)$++;for(var Be=c.repeat(w);$<v;++$)Be+=r.charAt(B[$]);return Be}function h(y){if(typeof y!="string")throw new TypeError("Expected String");if(y.length===0)return new Uint8Array;var w=0;if(y[w]!==" "){for(var b=0,S=0;y[w]===c;)b++,w++;for(var A=(y.length-w)*l+1>>>0,v=new Uint8Array(A);y[w];){var B=t[y.charCodeAt(w)];if(B===255)return;for(var E=0,U=A-1;(B!==0||E<S)&&U!==-1;U--,E++)B+=a*v[U]>>>0,v[U]=B%256>>>0,B=B/256>>>0;if(B!==0)throw new Error("Non-zero carry");S=E,w++}if(y[w]!==" "){for(var F=A-S;F!==A&&v[F]===0;)F++;for(var $=new Uint8Array(b+(A-F)),Be=b;F!==A;)$[Be++]=v[F++];return $}}}function m(y){var w=h(y);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:m}}var yp,gp,Ml,Ul=p(()=>{"use strict";yp=mp,gp=yp,Ml=gp});function Nl(r,e){return new io({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}function Ot({name:r,prefix:e,encode:t,decode:n}){return new oo(r,e,t,n)}function Ve({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=Ml(t,r);return Ot({prefix:e,name:r,encode:n,decode:i=>Se(s(i))})}function wp(r,e,t,n){let s=r.length;for(;r[s-1]==="=";)--s;let i=new Uint8Array(s*t/8|0),o=0,a=0,c=0;for(let l=0;l<s;++l){let u=e[r[l]];if(u===void 0)throw new SyntaxError(`Non-${n} character`);a=a<<t|u,o+=t,o>=8&&(o-=8,i[c++]=255&a>>o)}if(o>=t||(255&a<<8-o)!==0)throw new SyntaxError("Unexpected end of data");return i}function bp(r,e,t){let n=e[e.length-1]==="=",s=(1<<t)-1,i="",o=0,a=0;for(let c=0;c<r.length;++c)for(a=a<<8|r[c],o+=8;o>t;)o-=t,i+=e[s&a>>o];if(o!==0&&(i+=e[s&a<<t-o]),n)for(;(i.length*t&7)!==0;)i+="=";return i}function Sp(r){let e={};for(let t=0;t<r.length;++t)e[r[t]]=t;return e}function K({name:r,prefix:e,bitsPerChar:t,alphabet:n}){let s=Sp(n);return Ot({prefix:e,name:r,encode(i){return bp(i,n,t)},decode(i){return wp(i,s,t,r)}})}var no,so,io,oo,Ae=p(()=>{"use strict";qe();Ul();no=class{constructor(e,t,n){f(this,"name");f(this,"prefix");f(this,"baseEncode");this.name=e,this.prefix=t,this.baseEncode=n}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},so=class{constructor(e,t,n){f(this,"name");f(this,"prefix");f(this,"baseDecode");f(this,"prefixCodePoint");this.name=e,this.prefix=t;let s=t.codePointAt(0);if(s===void 0)throw new Error("Invalid prefix character");this.prefixCodePoint=s,this.baseDecode=n}decode(e){if(typeof e=="string"){if(e.codePointAt(0)!==this.prefixCodePoint)throw Error(`Unable to decode multibase string ${JSON.stringify(e)}, ${this.name} decoder only supports inputs prefixed with ${this.prefix}`);return this.baseDecode(e.slice(this.prefix.length))}else throw Error("Can only multibase decode strings")}or(e){return Nl(this,e)}},io=class{constructor(e){f(this,"decoders");this.decoders=e}or(e){return Nl(this,e)}decode(e){let t=e[0],n=this.decoders[t];if(n!=null)return n.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};oo=class{constructor(e,t,n,s){f(this,"name");f(this,"prefix");f(this,"baseEncode");f(this,"baseDecode");f(this,"encoder");f(this,"decoder");this.name=e,this.prefix=t,this.baseEncode=n,this.baseDecode=s,this.encoder=new no(e,t,n),this.decoder=new so(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}});var ao={};x(ao,{base32:()=>Z,base32hex:()=>kp,base32hexpad:()=>Cp,base32hexpadupper:()=>Pp,base32hexupper:()=>Ep,base32pad:()=>xp,base32padupper:()=>vp,base32upper:()=>Ap,base32z:()=>Ip});var Z,Ap,xp,vp,kp,Ep,Cp,Pp,Ip,$r=p(()=>{"use strict";Ae();Z=K({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Ap=K({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),xp=K({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),vp=K({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),kp=K({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Ep=K({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Cp=K({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),Pp=K({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Ip=K({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var co={};x(co,{base36:()=>Hr,base36upper:()=>Bp});var Hr,Bp,lo=p(()=>{"use strict";Ae();Hr=Ve({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Bp=Ve({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var uo={};x(uo,{base58btc:()=>fe,base58flickr:()=>Tp});var fe,Tp,Ss=p(()=>{"use strict";Ae();fe=Ve({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Tp=Ve({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});function Kl(r,e,t){e=e||[],t=t||0;for(var n=t;r>=Mp;)e[t++]=r&255|Ll,r/=128;for(;r&Fp;)e[t++]=r&255|Ll,r>>>=7;return e[t]=r|0,Kl.bytes=t-n+1,e}function ho(r,n){var t=0,n=n||0,s=0,i=n,o,a=r.length;do{if(i>=a)throw ho.bytes=0,new RangeError("Could not decode varint");o=r[i++],t+=s<28?(o&_l)<<s:(o&_l)*Math.pow(2,s),s+=7}while(o>=Np);return ho.bytes=i-n,t}var Rp,Ll,Dp,Fp,Mp,Up,Np,_l,Lp,_p,Kp,Op,zp,Wp,$p,Hp,qp,Vp,Gp,Yp,qr,Ol=p(()=>{"use strict";Rp=Kl,Ll=128,Dp=127,Fp=~Dp,Mp=Math.pow(2,31);Up=ho,Np=128,_l=127;Lp=Math.pow(2,7),_p=Math.pow(2,14),Kp=Math.pow(2,21),Op=Math.pow(2,28),zp=Math.pow(2,35),Wp=Math.pow(2,42),$p=Math.pow(2,49),Hp=Math.pow(2,56),qp=Math.pow(2,63),Vp=function(r){return r<Lp?1:r<_p?2:r<Kp?3:r<Op?4:r<zp?5:r<Wp?6:r<$p?7:r<Hp?8:r<qp?9:10},Gp={encode:Rp,decode:Up,encodingLength:Vp},Yp=Gp,qr=Yp});function Vr(r,e=0){return[qr.decode(r,e),qr.decode.bytes]}function zt(r,e,t=0){return qr.encode(r,e,t),e}function Wt(r){return qr.encodingLength(r)}var xs=p(()=>{"use strict";Ol()});function Ht(r,e){let t=e.byteLength,n=Wt(r),s=n+Wt(t),i=new Uint8Array(s+t);return zt(r,i,0),zt(t,i,n),i.set(e,s),new $t(r,t,e,i)}function vs(r){let e=Se(r),[t,n]=Vr(e),[s,i]=Vr(e.subarray(n)),o=e.subarray(n+i);if(o.byteLength!==s)throw new Error("Incorrect length");return new $t(t,s,o,e)}function zl(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&Tl(r.bytes,t.bytes)}}var $t,Vt=p(()=>{"use strict";qe();xs();$t=class{constructor(e,t,n,s){f(this,"code");f(this,"size");f(this,"digest");f(this,"bytes");this.code=e,this.size=t,this.digest=pt(n),this.bytes=pt(s)}}});var fo=p(()=>{"use strict"});function Wl(r,e){let{bytes:t,version:n}=r;return n===0?Jp(t,po(r),e??fe.encoder):Qp(t,po(r),e??Z.encoder)}function po(r){let e=$l.get(r);if(e==null){let t=new Map;return $l.set(r,t),t}return e}function jp(r,e){switch(r[0]){case"Q":{let t=e??fe;return[fe.prefix,t.decode(`${fe.prefix}${r}`)]}case fe.prefix:{let t=e??fe;return[fe.prefix,t.decode(r)]}case Z.prefix:{let t=e??Z;return[Z.prefix,t.decode(r)]}case Hr.prefix:{let t=e??Hr;return[Hr.prefix,t.decode(r)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[r[0],e.decode(r)]}}}function Jp(r,e,t){let{prefix:n}=t;if(n!==fe.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(n);if(s==null){let i=t.encode(r).slice(1);return e.set(n,i),i}else return s}function Qp(r,e,t){let{prefix:n}=t,s=e.get(n);if(s==null){let i=t.encode(r);return e.set(n,i),i}else return s}function Hl(r,e,t){let n=Wt(r),s=n+Wt(e),i=new Uint8Array(s+t.byteLength);return zt(r,i,0),zt(e,i,n),i.set(t,s),i}var $l,ql,G,Gr,Xp,Zp,mt=p(()=>{"use strict";$r();lo();Ss();qe();Vt();xs();fo();$l=new WeakMap;G=class r{constructor(e,t,n,s){f(this,"code");f(this,"version");f(this,"multihash");f(this,"bytes");f(this,"/");f(this,ql,"CID");this.code=t,this.version=e,this.multihash=n,this.bytes=pt(s),this["/"]=this.bytes}get asCID(){return this}get byteOffset(){return this.bytes.byteOffset}get byteLength(){return this.bytes.byteLength}toV0(){switch(this.version){case 0:return this;case 1:{let{code:e,multihash:t}=this;if(e!==Gr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Xp)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return r.createV0(t)}default:throw Error(`Can not convert CID version ${this.version} to version 0. This is a bug please report`)}}toV1(){switch(this.version){case 0:{let{code:e,digest:t}=this.multihash,n=Ht(e,t);return r.createV1(this.code,n)}case 1:return this;default:throw Error(`Can not convert CID version ${this.version} to version 1. This is a bug please report`)}}equals(e){return r.equals(this,e)}static equals(e,t){let n=t;return n!=null&&e.code===n.code&&e.version===n.version&&zl(e.multihash,n.multihash)}toString(e){return Wl(this,e)}toJSON(){return{"/":Wl(this)}}link(){return this}[(ql=Symbol.toStringTag,Symbol.for("nodejs.util.inspect.custom"))](){return`CID(${this.toString()})`}static asCID(e){if(e==null)return null;let t=e;if(t instanceof r)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:n,code:s,multihash:i,bytes:o}=t;return new r(n,s,i,o??Hl(n,s,i.bytes))}else if(t[Zp]===!0){let{version:n,multihash:s,code:i}=t,o=vs(s);return r.create(n,i,o)}else return null}static create(e,t,n){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(n.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Gr)throw new Error(`Version 0 CID must use dag-pb (code: ${Gr}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=Hl(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Gr,e)}static createV1(e,t){return r.create(1,e,t)}static decode(e){let[t,n]=r.decodeFirst(e);if(n.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=r.inspectBytes(e),n=t.size-t.multihashSize,s=Se(e.subarray(n,n+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=s.subarray(t.multihashSize-t.digestSize),o=new $t(t.multihashCode,t.digestSize,i,s);return[t.version===0?r.createV0(o):r.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,n=()=>{let[d,h]=Vr(e.subarray(t));return t+=h,d},s=n(),i=Gr;if(s===18?(s=0,t=0):i=n(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let o=t,a=n(),c=n(),l=t+c,u=l-o;return{version:s,codec:i,multihashCode:a,digestSize:c,multihashSize:u,size:l}}static parse(e,t){let[n,s]=jp(e,t),i=r.decode(s);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return po(i).set(n,e),i}};Gr=112,Xp=18;Zp=Symbol.for("@ipld/js-cid/CID")});function mo(r,e){let t=0;for(let n=0;;n+=7){if(n>=64)throw new Error("protobuf: varint overflow");if(e>=r.length)throw new Error("protobuf: unexpected end of data");let s=r[e++];if(t+=n<28?(s&127)<<n:(s&127)*2**n,s<128)break}return[t,e]}function ks(r,e){let t;[t,e]=mo(r,e);let n=e+t;if(t<0||n<0)throw new Error("protobuf: invalid length");if(n>r.length)throw new Error("protobuf: unexpected end of data");return[r.subarray(e,n),n]}function Vl(r,e){let t;return[t,e]=mo(r,e),[t&7,t>>3,e]}function tm(r){let e={},t=r.length,n=0;for(;n<t;){let s,i;if([s,i,n]=Vl(r,n),i===1){if(e.Hash)throw new Error("protobuf: (PBLink) duplicate Hash section");if(s!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${s}) for Hash`);if(e.Name!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Name before Hash");if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Hash");[e.Hash,n]=ks(r,n)}else if(i===2){if(e.Name!==void 0)throw new Error("protobuf: (PBLink) duplicate Name section");if(s!==2)throw new Error(`protobuf: (PBLink) wrong wireType (${s}) for Name`);if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) invalid order, found Tsize before Name");let o;[o,n]=ks(r,n),e.Name=em.decode(o)}else if(i===3){if(e.Tsize!==void 0)throw new Error("protobuf: (PBLink) duplicate Tsize section");if(s!==0)throw new Error(`protobuf: (PBLink) wrong wireType (${s}) for Tsize`);[e.Tsize,n]=mo(r,n)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${i}`)}if(n>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function Gl(r){let e=r.length,t=0,n,s=!1,i;for(;t<e;){let a,c;if([a,c,t]=Vl(r,t),a!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${a}`);if(c===1){if(i)throw new Error("protobuf: (PBNode) duplicate Data section");[i,t]=ks(r,t),n&&(s=!0)}else if(c===2){if(s)throw new Error("protobuf: (PBNode) duplicate Links section");n||(n=[]);let l;[l,t]=ks(r,t),n.push(tm(l))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${c}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let o={};return i&&(o.Data=i),o.Links=n||[],o}var em,Yl=p(()=>{"use strict";em=new TextDecoder});function nm(r,e){let t=e.length;if(typeof r.Tsize=="number"){if(r.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(r.Tsize))throw new Error("Tsize too large for encoding");t=Yr(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=Jl.encode(r.Name);t-=n.length,e.set(n,t),t=Yr(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=Yr(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function Ql(r){let e=im(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=Yr(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let s=r.Links.length-1;s>=0;s--){let i=nm(r.Links[s],t.subarray(0,n));n-=i,n=Yr(t,n,i)-1,t[n]=18}return t}function sm(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+Gt(t)}if(typeof r.Name=="string"){let t=Jl.encode(r.Name).length;e+=1+t+Gt(t)}return typeof r.Tsize=="number"&&(e+=1+Gt(r.Tsize)),e}function im(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+Gt(t)}if(r.Links)for(let t of r.Links){let n=sm(t);e+=1+n+Gt(n)}return e}function Yr(r,e,t){e-=Gt(t);let n=e;for(;t>=rm;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function Gt(r){return r%2===0&&r++,Math.floor((om(r)+6)/7)}function om(r){let e=0;return r>=jl&&(r=Math.floor(r/jl),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+am[r]}var Jl,jl,rm,am,Xl=p(()=>{"use strict";Jl=new TextEncoder,jl=2**32,rm=2**31;am=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8]});function eu(r,e){if(r===e)return 0;let t=r.Name?yo.encode(r.Name):[],n=e.Name?yo.encode(e.Name):[],s=t.length,i=n.length;for(let o=0,a=Math.min(s,i);o<a;++o)if(t[o]!==n[o]){s=t[o],i=n[o];break}return s<i?-1:i<s?1:0}function Zl(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function tu(r){if(typeof r.asCID=="object"){let t=G.asCID(r);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Hash){let t=G.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=G.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=G.decode(r.Hash)))}catch(n){throw new TypeError(`Invalid DAG-PB form: ${n.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof r.Name=="string"&&(e.Name=r.Name),typeof r.Tsize=="number"&&(e.Tsize=r.Tsize),e}function ee(r){if((r instanceof Uint8Array||typeof r=="string")&&(r={Data:r}),typeof r!="object"||Array.isArray(r))throw new TypeError("Invalid DAG-PB form");let e={};if(r.Data!==void 0)if(typeof r.Data=="string")e.Data=yo.encode(r.Data);else if(r.Data instanceof Uint8Array)e.Data=r.Data;else throw new TypeError("Invalid DAG-PB form");if(r.Links!==void 0)if(Array.isArray(r.Links))e.Links=r.Links.map(tu),e.Links.sort(eu);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function go(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!Zl(r,cm))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(r.Data!==void 0&&!(r.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(r.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<r.Links.length;e++){let t=r.Links[e];if(!t||typeof t!="object"||Array.isArray(t)||t instanceof Uint8Array||t["/"]&&t["/"]===t.bytes)throw new TypeError("Invalid DAG-PB form (bad link)");if(!Zl(t,lm))throw new TypeError("Invalid DAG-PB form (extraneous properties on link)");if(t.Hash===void 0)throw new TypeError("Invalid DAG-PB form (link must have a Hash)");if(t.Hash==null||!t.Hash["/"]||t.Hash["/"]!==t.Hash.bytes)throw new TypeError("Invalid DAG-PB form (link Hash must be a CID)");if(t.Name!==void 0&&typeof t.Name!="string")throw new TypeError("Invalid DAG-PB form (link Name must be a string)");if(t.Tsize!==void 0){if(typeof t.Tsize!="number"||t.Tsize%1!==0)throw new TypeError("Invalid DAG-PB form (link Tsize must be an integer)");if(t.Tsize<0)throw new TypeError("Invalid DAG-PB form (link Tsize cannot be negative)")}if(e>0&&eu(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function ru(r,e=[]){return ee({Data:r,Links:e})}function nu(r,e,t){return tu({Hash:t,Name:r,Tsize:e})}function su(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var cm,lm,yo,iu=p(()=>{"use strict";mt();cm=["Data","Links"],lm=["Hash","Name","Tsize"],yo=new TextEncoder});var jr={};x(jr,{code:()=>dm,createLink:()=>nu,createNode:()=>ru,decode:()=>hm,encode:()=>te,name:()=>um,prepare:()=>ee,validate:()=>go});function te(r){go(r);let e={};return r.Links&&(e.Links=r.Links.map(t=>{let n={};return t.Hash&&(n.Hash=t.Hash.bytes),t.Name!==void 0&&(n.Name=t.Name),t.Tsize!==void 0&&(n.Tsize=t.Tsize),n})),r.Data&&(e.Data=r.Data),Ql(e)}function hm(r){let e=su(r),t=Gl(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(s=>{let i={};try{i.Hash=G.decode(s.Hash)}catch{}if(!i.Hash)throw new Error("Invalid Hash field found in link, expected CID");return s.Name!==void 0&&(i.Name=s.Name),s.Tsize!==void 0&&(i.Tsize=s.Tsize),i})),n}var um,dm,yt=p(()=>{"use strict";mt();Yl();Xl();iu();um="dag-pb",dm=112});var Yt,Jr,wo=p(()=>{"use strict";Yt=class Yt extends Error{constructor(t="Invalid type"){super(t);f(this,"name",Yt.name);f(this,"code",Yt.code)}};f(Yt,"name","InvalidTypeError"),f(Yt,"code","ERR_INVALID_TYPE");Jr=Yt});function Qr(r){if(r<fm)return 1;if(r<pm)return 2;if(r<mm)return 3;if(r<ou)return 4;if(r<au)return 5;if(r<cu)return 6;if(r<lu)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function uu(r,e,t=0){switch(Qr(r)){case 8:e[t++]=r&255|Y,r/=128;case 7:e[t++]=r&255|Y,r/=128;case 6:e[t++]=r&255|Y,r/=128;case 5:e[t++]=r&255|Y,r/=128;case 4:e[t++]=r&255|Y,r>>>=7;case 3:e[t++]=r&255|Y,r>>>=7;case 2:e[t++]=r&255|Y,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function du(r,e){let t=r[e],n=0;if(n+=t&Ge,t<Y||(t=r[e+1],n+=(t&Ge)<<7,t<Y)||(t=r[e+2],n+=(t&Ge)<<14,t<Y)||(t=r[e+3],n+=(t&Ge)<<21,t<Y)||(t=r[e+4],n+=(t&Ge)*ou,t<Y)||(t=r[e+5],n+=(t&Ge)*au,t<Y)||(t=r[e+6],n+=(t&Ge)*cu,t<Y)||(t=r[e+7],n+=(t&Ge)*lu,t<Y))return n;throw new RangeError("Could not decode varint")}var fm,pm,mm,ou,au,cu,lu,Y,Ge,bo=p(()=>{"use strict";ft();fm=Math.pow(2,7),pm=Math.pow(2,14),mm=Math.pow(2,21),ou=Math.pow(2,28),au=Math.pow(2,35),cu=Math.pow(2,42),lu=Math.pow(2,49),Y=128,Ge=127});function ym(r){return r.buffer instanceof ArrayBuffer}function hu(r){return ym(r)?r:r.slice()}var fu=p(()=>{"use strict"});function pu(r,e,t){So[0]=r,e[t]=Ye[0],e[t+1]=Ye[1],e[t+2]=Ye[2],e[t+3]=Ye[3]}function mu(r,e){return Ye[0]=r[e],Ye[1]=r[e+1],Ye[2]=r[e+2],Ye[3]=r[e+3],So[0]}function yu(r,e,t){Ao[0]=r,e[t]=H[0],e[t+1]=H[1],e[t+2]=H[2],e[t+3]=H[3],e[t+4]=H[4],e[t+5]=H[5],e[t+6]=H[6],e[t+7]=H[7]}function gu(r,e){return H[0]=r[e],H[1]=r[e+1],H[2]=r[e+2],H[3]=r[e+3],H[4]=r[e+4],H[5]=r[e+5],H[6]=r[e+6],H[7]=r[e+7],Ao[0]}var So,Ye,Ao,H,xo=p(()=>{"use strict";So=new Float32Array([-0]),Ye=new Uint8Array(So.buffer);Ao=new Float64Array([-0]),H=new Uint8Array(Ao.buffer)});var gm,wm,ae,gt,wu,vo=p(()=>{"use strict";gm=BigInt(Number.MAX_SAFE_INTEGER),wm=BigInt(Number.MIN_SAFE_INTEGER),ae=class r{constructor(e,t){f(this,"lo");f(this,"hi");this.lo=e|0,this.hi=t|0}toNumber(e=!1){if(!e&&this.hi>>>31>0){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(t+n*4294967296)}return this.lo+this.hi*4294967296}toBigInt(e=!1){if(e)return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n);if(this.hi>>>31){let t=~this.lo+1>>>0,n=~this.hi>>>0;return t===0&&(n=n+1>>>0),-(BigInt(t)+(BigInt(n)<<32n))}return BigInt(this.lo>>>0)+(BigInt(this.hi>>>0)<<32n)}toString(e=!1){return this.toBigInt(e).toString()}zzEncode(){let e=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^e)>>>0,this.lo=(this.lo<<1^e)>>>0,this}zzDecode(){let e=-(this.lo&1);return this.lo=((this.lo>>>1|this.hi<<31)^e)>>>0,this.hi=(this.hi>>>1^e)>>>0,this}length(){let e=this.lo,t=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return n===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:n<128?9:10}static fromBigInt(e){if(e===0n)return gt;if(e<gm&&e>wm)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let n=e>>32n,s=e-(n<<32n);return t&&(n=~n|0n,s=~s|0n,++s>wu&&(s=0n,++n>wu&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return gt;let t=e<0;t&&(e=-e);let n=e>>>0,s=(e-n)/4294967296>>>0;return t&&(s=~s>>>0,n=~n>>>0,++n>4294967295&&(n=0,++s>4294967295&&(s=0))),new r(n,s)}static from(e){return typeof e=="number"?r.fromNumber(e):typeof e=="bigint"?r.fromBigInt(e):typeof e=="string"?r.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new r(e.low>>>0,e.high>>>0):gt}},gt=new ae(0,0);gt.toBigInt=function(){return 0n};gt.zzEncode=gt.zzDecode=function(){return this};gt.length=function(){return 1};wu=4294967296n});function bu(r){let e=0,t=0;for(let n=0;n<r.length;++n)t=r.charCodeAt(n),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(r.charCodeAt(n+1)&64512)===56320?(++n,e+=4):e+=3;return e}function Su(r,e,t){if(t-e<1)return"";let s,i=[],o=0,a;for(;e<t;)a=r[e++],a<128?i[o++]=a:a>191&&a<224?i[o++]=(a&31)<<6|r[e++]&63:a>239&&a<365?(a=((a&7)<<18|(r[e++]&63)<<12|(r[e++]&63)<<6|r[e++]&63)-65536,i[o++]=55296+(a>>10),i[o++]=56320+(a&1023)):i[o++]=(a&15)<<12|(r[e++]&63)<<6|r[e++]&63,o>8191&&((s??(s=[])).push(String.fromCharCode.apply(String,i)),o=0);return s!=null?(o>0&&s.push(String.fromCharCode.apply(String,i.slice(0,o))),s.join("")):String.fromCharCode.apply(String,i.slice(0,o))}function ko(r,e,t){let n=t,s,i;for(let o=0;o<r.length;++o)s=r.charCodeAt(o),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((i=r.charCodeAt(o+1))&64512)===56320?(s=65536+((s&1023)<<10)+(i&1023),++o,e[t++]=s>>18|240,e[t++]=s>>12&63|128,e[t++]=s>>6&63|128,e[t++]=s&63|128):(e[t++]=s>>12|224,e[t++]=s>>6&63|128,e[t++]=s&63|128);return t-n}var Eo=p(()=>{"use strict"});function xe(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function Es(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}function Xr(r){return new Co(r instanceof Uint8Array?r:r.subarray())}var Co,Cs=p(()=>{"use strict";bo();fu();xo();vo();Eo();Co=class{constructor(e){f(this,"buf");f(this,"pos");f(this,"len");f(this,"_slice",Uint8Array.prototype.subarray);this.buf=hu(e),this.pos=0,this.len=e.length}uint32(){let e=4294967295;if(e=(this.buf[this.pos]&127)>>>0,this.buf[this.pos++]<128||(e=(e|(this.buf[this.pos]&127)<<7)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<14)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&127)<<21)>>>0,this.buf[this.pos++]<128)||(e=(e|(this.buf[this.pos]&15)<<28)>>>0,this.buf[this.pos++]<128))return e;if((this.pos+=5)>this.len)throw this.pos=this.len,xe(this,10);return e}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)|0}bool(){return this.uint32()!==0}fixed32(){if(this.pos+4>this.len)throw xe(this,4);return Es(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw xe(this,4);return Es(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw xe(this,4);let e=mu(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw xe(this,4);let e=gu(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,n=this.pos+e;if(n>this.len)throw xe(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Su(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw xe(this,e);this.pos+=e}else do if(this.pos>=this.len)throw xe(this);while((this.buf[this.pos++]&128)!==0);return this}skipType(e){switch(e){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;(e=this.uint32()&7)!==4;)this.skipType(e);break;case 5:this.skip(4);break;default:throw Error(`invalid wire type ${e} at offset ${this.pos}`)}return this}readLongVarint(){let e=new ae(0,0),t=0;if(this.len-this.pos>4){for(;t<4;++t)if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e;if(e.lo=(e.lo|(this.buf[this.pos]&127)<<28)>>>0,e.hi=(e.hi|(this.buf[this.pos]&127)>>4)>>>0,this.buf[this.pos++]<128)return e;t=0}else{for(;t<3;++t){if(this.pos>=this.len)throw xe(this);if(e.lo=(e.lo|(this.buf[this.pos]&127)<<t*7)>>>0,this.buf[this.pos++]<128)return e}return e.lo=(e.lo|(this.buf[this.pos++]&127)<<t*7)>>>0,e}if(this.len-this.pos>4){for(;t<5;++t)if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}else for(;t<5;++t){if(this.pos>=this.len)throw xe(this);if(e.hi=(e.hi|(this.buf[this.pos]&127)<<t*7+3)>>>0,this.buf[this.pos++]<128)return e}throw Error("invalid varint encoding")}readFixed64(){if(this.pos+8>this.len)throw xe(this,8);let e=Es(this.buf,this.pos+=4),t=Es(this.buf,this.pos+=4);return new ae(e,t)}int64(){return this.readLongVarint().toBigInt()}int64Number(){return this.readLongVarint().toNumber()}int64String(){return this.readLongVarint().toString()}uint64(){return this.readLongVarint().toBigInt(!0)}uint64Number(){let e=du(this.buf,this.pos);return this.pos+=Qr(e),e}uint64String(){return this.readLongVarint().toString(!0)}sint64(){return this.readLongVarint().zzDecode().toBigInt()}sint64Number(){return this.readLongVarint().zzDecode().toNumber()}sint64String(){return this.readLongVarint().zzDecode().toString()}fixed64(){return this.readFixed64().toBigInt()}fixed64Number(){return this.readFixed64().toNumber()}fixed64String(){return this.readFixed64().toString()}sfixed64(){return this.readFixed64().toBigInt()}sfixed64Number(){return this.readFixed64().toNumber()}sfixed64String(){return this.readFixed64().toString()}}});function Zr(r,e,t){let n=Xr(r);return e.decode(n,void 0,t)}var xu=p(()=>{"use strict";Cs()});var Po={};x(Po,{base10:()=>bm});var bm,vu=p(()=>{"use strict";Ae();bm=Ve({prefix:"9",name:"base10",alphabet:"0123456789"})});var Io={};x(Io,{base16:()=>Sm,base16upper:()=>Am});var Sm,Am,ku=p(()=>{"use strict";Ae();Sm=K({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Am=K({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var Bo={};x(Bo,{base2:()=>xm});var xm,Eu=p(()=>{"use strict";Ae();xm=K({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var To={};x(To,{base256emoji:()=>Pm});function Em(r){return r.reduce((e,t)=>(e+=vm[t],e),"")}function Cm(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=km[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var Cu,vm,km,Pm,Pu=p(()=>{"use strict";Ae();Cu=Array.from("\u{1F680}\u{1FA90}\u2604\u{1F6F0}\u{1F30C}\u{1F311}\u{1F312}\u{1F313}\u{1F314}\u{1F315}\u{1F316}\u{1F317}\u{1F318}\u{1F30D}\u{1F30F}\u{1F30E}\u{1F409}\u2600\u{1F4BB}\u{1F5A5}\u{1F4BE}\u{1F4BF}\u{1F602}\u2764\u{1F60D}\u{1F923}\u{1F60A}\u{1F64F}\u{1F495}\u{1F62D}\u{1F618}\u{1F44D}\u{1F605}\u{1F44F}\u{1F601}\u{1F525}\u{1F970}\u{1F494}\u{1F496}\u{1F499}\u{1F622}\u{1F914}\u{1F606}\u{1F644}\u{1F4AA}\u{1F609}\u263A\u{1F44C}\u{1F917}\u{1F49C}\u{1F614}\u{1F60E}\u{1F607}\u{1F339}\u{1F926}\u{1F389}\u{1F49E}\u270C\u2728\u{1F937}\u{1F631}\u{1F60C}\u{1F338}\u{1F64C}\u{1F60B}\u{1F497}\u{1F49A}\u{1F60F}\u{1F49B}\u{1F642}\u{1F493}\u{1F929}\u{1F604}\u{1F600}\u{1F5A4}\u{1F603}\u{1F4AF}\u{1F648}\u{1F447}\u{1F3B6}\u{1F612}\u{1F92D}\u2763\u{1F61C}\u{1F48B}\u{1F440}\u{1F62A}\u{1F611}\u{1F4A5}\u{1F64B}\u{1F61E}\u{1F629}\u{1F621}\u{1F92A}\u{1F44A}\u{1F973}\u{1F625}\u{1F924}\u{1F449}\u{1F483}\u{1F633}\u270B\u{1F61A}\u{1F61D}\u{1F634}\u{1F31F}\u{1F62C}\u{1F643}\u{1F340}\u{1F337}\u{1F63B}\u{1F613}\u2B50\u2705\u{1F97A}\u{1F308}\u{1F608}\u{1F918}\u{1F4A6}\u2714\u{1F623}\u{1F3C3}\u{1F490}\u2639\u{1F38A}\u{1F498}\u{1F620}\u261D\u{1F615}\u{1F33A}\u{1F382}\u{1F33B}\u{1F610}\u{1F595}\u{1F49D}\u{1F64A}\u{1F639}\u{1F5E3}\u{1F4AB}\u{1F480}\u{1F451}\u{1F3B5}\u{1F91E}\u{1F61B}\u{1F534}\u{1F624}\u{1F33C}\u{1F62B}\u26BD\u{1F919}\u2615\u{1F3C6}\u{1F92B}\u{1F448}\u{1F62E}\u{1F646}\u{1F37B}\u{1F343}\u{1F436}\u{1F481}\u{1F632}\u{1F33F}\u{1F9E1}\u{1F381}\u26A1\u{1F31E}\u{1F388}\u274C\u270A\u{1F44B}\u{1F630}\u{1F928}\u{1F636}\u{1F91D}\u{1F6B6}\u{1F4B0}\u{1F353}\u{1F4A2}\u{1F91F}\u{1F641}\u{1F6A8}\u{1F4A8}\u{1F92C}\u2708\u{1F380}\u{1F37A}\u{1F913}\u{1F619}\u{1F49F}\u{1F331}\u{1F616}\u{1F476}\u{1F974}\u25B6\u27A1\u2753\u{1F48E}\u{1F4B8}\u2B07\u{1F628}\u{1F31A}\u{1F98B}\u{1F637}\u{1F57A}\u26A0\u{1F645}\u{1F61F}\u{1F635}\u{1F44E}\u{1F932}\u{1F920}\u{1F927}\u{1F4CC}\u{1F535}\u{1F485}\u{1F9D0}\u{1F43E}\u{1F352}\u{1F617}\u{1F911}\u{1F30A}\u{1F92F}\u{1F437}\u260E\u{1F4A7}\u{1F62F}\u{1F486}\u{1F446}\u{1F3A4}\u{1F647}\u{1F351}\u2744\u{1F334}\u{1F4A3}\u{1F438}\u{1F48C}\u{1F4CD}\u{1F940}\u{1F922}\u{1F445}\u{1F4A1}\u{1F4A9}\u{1F450}\u{1F4F8}\u{1F47B}\u{1F910}\u{1F92E}\u{1F3BC}\u{1F975}\u{1F6A9}\u{1F34E}\u{1F34A}\u{1F47C}\u{1F48D}\u{1F4E3}\u{1F942}"),vm=Cu.reduce((r,e,t)=>(r[t]=e,r),[]),km=Cu.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);Pm=Ot({prefix:"\u{1F680}",name:"base256emoji",encode:Em,decode:Cm})});var Do={};x(Do,{base64:()=>Ro,base64pad:()=>Im,base64url:()=>Bm,base64urlpad:()=>Tm});var Ro,Im,Bm,Tm,Fo=p(()=>{"use strict";Ae();Ro=K({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Im=K({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Bm=K({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Tm=K({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var Mo={};x(Mo,{base8:()=>Rm});var Rm,Iu=p(()=>{"use strict";Ae();Rm=K({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var Uo={};x(Uo,{identity:()=>Dm});var Dm,Bu=p(()=>{"use strict";qe();Ae();Dm=Ot({prefix:"\0",name:"identity",encode:r=>Dl(r),decode:r=>Rl(r)})});var $b,Hb,Tu=p(()=>{"use strict";$b=new TextEncoder,Hb=new TextDecoder});var Jt={};x(Jt,{code:()=>jt,decode:()=>Nm,encode:()=>Um,name:()=>Mm});function Um(r){return Se(r)}function Nm(r){return Se(r)}var Mm,jt,en=p(()=>{"use strict";qe();Mm="raw",jt=85});var No={};x(No,{identity:()=>Km});function _m(r,e){if(e?.truncate!=null&&e.truncate!==r.byteLength){if(e.truncate<0||e.truncate>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,e.truncate)}return Ht(Ru,Du(r))}var Ru,Lm,Du,Km,Fu=p(()=>{"use strict";qe();Vt();Ru=0,Lm="identity",Du=Se;Km={code:Ru,name:Lm,encode:Du,digest:_m}});function wt({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new Lo(r,e,t,n,s)}function Mu(r,e,t){if(t!=null&&t!==r.byteLength){if(t>r.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${r.byteLength}`);r=r.subarray(0,t)}return Ht(e,r)}var Om,Lo,Ps=p(()=>{"use strict";Vt();Om=20;Lo=class{constructor(e,t,n,s,i){f(this,"name");f(this,"code");f(this,"encode");f(this,"minDigestLength");f(this,"maxDigestLength");this.name=e,this.code=t,this.encode=n,this.minDigestLength=s??Om,this.maxDigestLength=i}digest(e,t){if(t?.truncate!=null){if(t.truncate<this.minDigestLength)throw new Error(`Invalid truncate option, must be greater than or equal to ${this.minDigestLength}`);if(this.maxDigestLength!=null&&t.truncate>this.maxDigestLength)throw new Error(`Invalid truncate option, must be less than or equal to ${this.maxDigestLength}`)}if(e instanceof Uint8Array){let n=this.encode(e);return n instanceof Uint8Array?Mu(n,this.code,t?.truncate):n.then(s=>Mu(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}}});var Ko={};x(Ko,{sha256:()=>_o,sha512:()=>zm});function Nu(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var _o,zm,Oo=p(()=>{"use strict";Ps();_o=wt({name:"sha2-256",code:18,encode:Nu("SHA-256")}),zm=wt({name:"sha2-512",code:19,encode:Nu("SHA-512")})});var Lu=p(()=>{"use strict"});var _u=p(()=>{"use strict"});var Ku=p(()=>{"use strict"});var Ou=p(()=>{"use strict"});var zu=p(()=>{"use strict";Lu();_u();Ku();fo();Ou()});var Wu=p(()=>{"use strict";qe();mt();Vt();Ps();xs();zu()});var zo,sS,$u=p(()=>{"use strict";vu();ku();Eu();Pu();$r();lo();Ss();Fo();Iu();Bu();Tu();en();Fu();Oo();Wu();zo={...Uo,...Bo,...Mo,...Po,...Io,...ao,...co,...uo,...Do,...To},sS={...Ko,...No}});function qu(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var Hu,Wo,Wm,Vu,Gu=p(()=>{"use strict";$u();ft();Hu=qu("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),Wo=qu("ascii","a",r=>{let e="a";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return e},r=>{r=r.substring(1);let e=oe(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),Wm={utf8:Hu,"utf-8":Hu,hex:zo.base16,latin1:Wo,ascii:Wo,binary:Wo,...zo},Vu=Wm});function Qt(r,e="utf8"){let t=Vu[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var Is=p(()=>{"use strict";Gu()});function $o(r){let e=r??8192,t=e>>>1,n,s=e;return function(o){if(o<1||o>t)return oe(o);s+o>e&&(n=oe(e),s=0);let a=n.subarray(s,s+=o);return(s&7)!==0&&(s=(s|7)+1),a}}var Yu=p(()=>{"use strict";ft()});function Ho(){}function Hm(r){return globalThis.Buffer!=null?oe(r):$m(r)}function qo(r,e,t){e[t]=r&255}function qm(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function Bs(r,e,t){for(;r.hi!==0;)e[t++]=r.lo&127|128,r.lo=(r.lo>>>7|r.hi<<25)>>>0,r.hi>>>=7;for(;r.lo>127;)e[t++]=r.lo&127|128,r.lo=r.lo>>>7;e[t++]=r.lo}function tn(r,e,t){e[t]=r&255,e[t+1]=r>>>8&255,e[t+2]=r>>>16&255,e[t+3]=r>>>24}function Vm(r,e,t){e.set(r,t)}function Gm(r,e,t){e.set(r,t)}function Ym(r,e,t){r.length<40?ko(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(Qt(r),t)}function Yo(){return new rn}var bt,Vo,$m,rn,Go,jo=p(()=>{"use strict";bo();ft();Is();xo();vo();Yu();Eo();bt=class{constructor(e,t,n){f(this,"fn");f(this,"len");f(this,"next");f(this,"val");this.fn=e,this.len=t,this.next=void 0,this.val=n}};Vo=class{constructor(e){f(this,"head");f(this,"tail");f(this,"len");f(this,"next");this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},$m=$o();rn=class{constructor(){f(this,"len");f(this,"head");f(this,"tail");f(this,"states");this.len=0,this.head=new bt(Ho,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new bt(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new Go((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(Bs,10,ae.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=ae.fromBigInt(e);return this._push(Bs,t.length(),t)}uint64Number(e){return this._push(uu,Qr(e),e)}uint64String(e){return this.uint64(BigInt(e))}int64(e){return this.uint64(e)}int64Number(e){return this.uint64Number(e)}int64String(e){return this.uint64String(e)}sint64(e){let t=ae.fromBigInt(e).zzEncode();return this._push(Bs,t.length(),t)}sint64Number(e){let t=ae.fromNumber(e).zzEncode();return this._push(Bs,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(qo,1,e?1:0)}fixed32(e){return this._push(tn,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=ae.fromBigInt(e);return this._push(tn,4,t.lo)._push(tn,4,t.hi)}fixed64Number(e){let t=ae.fromNumber(e);return this._push(tn,4,t.lo)._push(tn,4,t.hi)}fixed64String(e){return this.fixed64(BigInt(e))}sfixed64(e){return this.fixed64(e)}sfixed64Number(e){return this.fixed64Number(e)}sfixed64String(e){return this.fixed64String(e)}float(e){return this._push(pu,4,e)}double(e){return this._push(yu,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(qo,1,0):this.uint32(t)._push(Vm,t,e)}string(e){let t=bu(e);return t!==0?this.uint32(t)._push(ko,t,e):this._push(qo,1,0)}fork(){return this.states=new Vo(this),this.head=this.tail=new bt(Ho,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new bt(Ho,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,n=this.len;return this.reset().uint32(n),n!==0&&(this.tail.next=e.next,this.tail=t,this.len+=n),this}finish(){let e=this.head.next,t=Hm(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};Go=class extends bt{constructor(t,n){super(qm,t,n);f(this,"next");this.next=void 0}};globalThis.Buffer!=null&&(rn.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(Gm,e,r),this},rn.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(Ym,e,r),this})});function nn(r,e){let t=Yo();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var ju=p(()=>{"use strict";jo()});function*sn(r,e,t){let n=Xr(r);yield*e.stream(n,void 0,"$",t)}var Ju=p(()=>{"use strict";Cs()});function Rs(r,e,t,n,s){return{name:r,type:e,encode:t,decode:n,stream:s}}var Ts,Jo=p(()=>{"use strict";Ts={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5}});function Qo(r){function e(i){if(r[i.toString()]==null)throw new Error("Invalid enum value");return r[i]}let t=function(o,a){let c=e(o);a.int32(c)},n=function(o){let a=o.int32();return e(a)},s=function*(o){let a=o.int32();yield e(a)};return Rs("enum",Ts.VARINT,t,n,s)}var Qu=p(()=>{"use strict";Jo()});function on(r,e,t){return Rs("message",Ts.LENGTH_DELIMITED,r,e,t)}var Xu=p(()=>{"use strict";Jo()});var an,Zu=p(()=>{"use strict";xu();ju();Ju();Qu();Xu();Cs();jo();an=class extends Error{constructor(){super(...arguments);f(this,"code","ERR_MAX_LENGTH");f(this,"name","MaxLengthError")}}});var ve,cn,ed,td=p(()=>{"use strict";Zu();(function(r){let e;(function(a){a.Raw="Raw",a.Directory="Directory",a.File="File",a.Metadata="Metadata",a.Symlink="Symlink",a.HAMTShard="HAMTShard"})(e=r.DataType||(r.DataType={}));let t;(function(a){a[a.Raw=0]="Raw",a[a.Directory=1]="Directory",a[a.File=2]="File",a[a.Metadata=3]="Metadata",a[a.Symlink=4]="Symlink",a[a.HAMTShard=5]="HAMTShard"})(t||(t={})),(function(a){a.codec=()=>Qo(t)})(e=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=on((a,c,l={})=>{if(l.lengthDelimited!==!1&&c.fork(),a.Type!=null&&(c.uint32(8),r.DataType.codec().encode(a.Type,c)),a.Data!=null&&(c.uint32(18),c.bytes(a.Data)),a.filesize!=null&&(c.uint32(24),c.uint64(a.filesize)),a.blocksizes!=null&&a.blocksizes.length>0)for(let u of a.blocksizes)c.uint32(32),c.uint64(u);a.hashType!=null&&(c.uint32(40),c.uint64(a.hashType)),a.fanout!=null&&(c.uint32(48),c.uint64(a.fanout)),a.mode!=null&&(c.uint32(56),c.uint32(a.mode)),a.mtime!=null&&(c.uint32(66),cn.codec().encode(a.mtime,c)),l.lengthDelimited!==!1&&c.ldelim()},(a,c,l={})=>{let u={blocksizes:[]},d=c==null?a.len:a.pos+c;for(;a.pos<d;){let h=a.uint32();switch(h>>>3){case 1:{u.Type=r.DataType.codec().decode(a);break}case 2:{u.Data=a.bytes();break}case 3:{u.filesize=a.uint64();break}case 4:{if(l.limits?.blocksizes!=null&&u.blocksizes.length===l.limits.blocksizes)throw new an('Decode error - repeated field "blocksizes" had too many elements');u.blocksizes.push(a.uint64());break}case 5:{u.hashType=a.uint64();break}case 6:{u.fanout=a.uint64();break}case 7:{u.mode=a.uint32();break}case 8:{u.mtime=cn.codec().decode(a,a.uint32(),{limits:l.limits?.mtime});break}default:{a.skipType(h&7);break}}}return u},function*(a,c,l,u={}){let d={blocksizes:0},h=c==null?a.len:a.pos+c;for(;a.pos<h;){let m=a.uint32();switch(m>>>3){case 1:{yield{field:`${l}.Type`,value:r.DataType.codec().decode(a)};break}case 2:{yield{field:`${l}.Data`,value:a.bytes()};break}case 3:{yield{field:`${l}.filesize`,value:a.uint64()};break}case 4:{if(u.limits?.blocksizes!=null&&d.blocksizes===u.limits.blocksizes)throw new an('Streaming decode error - repeated field "blocksizes" had too many elements');yield{field:`${l}.blocksizes[]`,index:d.blocksizes,value:a.uint64()},d.blocksizes++;break}case 5:{yield{field:`${l}.hashType`,value:a.uint64()};break}case 6:{yield{field:`${l}.fanout`,value:a.uint64()};break}case 7:{yield{field:`${l}.mode`,value:a.uint32()};break}case 8:{yield*cn.codec().stream(a,a.uint32(),`${l}.mtime`,{limits:u.limits?.mtime});break}default:{a.skipType(m&7);break}}}})),n);function s(a){return nn(a,r.codec())}r.encode=s;function i(a,c){return Zr(a,r.codec(),c)}r.decode=i;function o(a,c){return sn(a,r.codec(),c)}r.stream=o})(ve||(ve={}));(function(r){let e;r.codec=()=>(e==null&&(e=on((i,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),i.Seconds!=null&&(o.uint32(8),o.int64(i.Seconds)),i.FractionalNanoseconds!=null&&(o.uint32(21),o.fixed32(i.FractionalNanoseconds)),a.lengthDelimited!==!1&&o.ldelim()},(i,o,a={})=>{let c={},l=o==null?i.len:i.pos+o;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{c.Seconds=i.int64();break}case 2:{c.FractionalNanoseconds=i.fixed32();break}default:{i.skipType(u&7);break}}}return c},function*(i,o,a,c={}){let l=o==null?i.len:i.pos+o;for(;i.pos<l;){let u=i.uint32();switch(u>>>3){case 1:{yield{field:`${a}.Seconds`,value:i.int64()};break}case 2:{yield{field:`${a}.FractionalNanoseconds`,value:i.fixed32()};break}default:{i.skipType(u&7);break}}}})),e);function t(i){return nn(i,r.codec())}r.encode=t;function n(i,o){return Zr(i,r.codec(),o)}r.decode=n;function s(i,o){return sn(i,r.codec(),o)}r.stream=s})(cn||(cn={}));(function(r){let e;r.codec=()=>(e==null&&(e=on((i,o,a={})=>{a.lengthDelimited!==!1&&o.fork(),i.MimeType!=null&&(o.uint32(10),o.string(i.MimeType)),a.lengthDelimited!==!1&&o.ldelim()},(i,o,a={})=>{let c={},l=o==null?i.len:i.pos+o;for(;i.pos<l;){let u=i.uint32();u>>>3===1?c.MimeType=i.string():i.skipType(u&7)}return c},function*(i,o,a,c={}){let l=o==null?i.len:i.pos+o;for(;i.pos<l;){let u=i.uint32();u>>>3===1?yield{field:`${a}.MimeType`,value:i.string()}:i.skipType(u&7)}})),e);function t(i){return nn(i,r.codec())}r.encode=t;function n(i,o){return Zr(i,r.codec(),o)}r.decode=n;function s(i,o){return sn(i,r.codec(),o)}r.stream=s})(ed||(ed={}))});var rd,jm,nd,sd,j,Xt=p(()=>{"use strict";wo();td();wo();rd={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},jm=["directory","hamt-sharded-directory"],nd=parseInt("0644",8),sd=parseInt("0755",8),j=class r{constructor(e={type:"file"}){f(this,"type");f(this,"data");f(this,"blockSizes");f(this,"hashType");f(this,"fanout");f(this,"mtime");f(this,"_mode");f(this,"_originalMode");let{type:t,data:n,blockSizes:s,hashType:i,fanout:o,mtime:a,mode:c}=e;if(t!=null&&!Object.values(rd).includes(t))throw new Jr("Type: "+t+" is not valid");this.type=t??"file",this.data=n,this.hashType=i,this.fanout=o,this.blockSizes=s??[],this._originalMode=0,this.mode=c,this.mtime=a}static unmarshal(e){let t=ve.decode(e),n=new r({type:rd[t.Type!=null?t.Type.toString():"File"],data:t.Data,blockSizes:t.blocksizes,mode:t.mode,mtime:t.mtime!=null?{secs:t.mtime.Seconds??0n,nsecs:t.mtime.FractionalNanoseconds}:void 0,fanout:t.fanout});return n._originalMode=t.mode??0,n}set mode(e){e==null?this._mode=this.isDirectory()?sd:nd:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return jm.includes(this.type)}addBlockSize(e){this.blockSizes.push(e)}removeBlockSize(e){this.blockSizes.splice(e,1)}fileSize(){if(this.isDirectory())return 0n;let e=0n;return this.blockSizes.forEach(t=>{e+=t}),this.data!=null&&(e+=BigInt(this.data.length)),e}marshal(){let e;switch(this.type){case"raw":e=ve.DataType.Raw;break;case"directory":e=ve.DataType.Directory;break;case"file":e=ve.DataType.File;break;case"metadata":e=ve.DataType.Metadata;break;case"symlink":e=ve.DataType.Symlink;break;case"hamt-sharded-directory":e=ve.DataType.HAMTShard;break;default:throw new Jr(`Type: ${e} is not valid`)}let t=this.data;(this.data==null||this.data.length===0)&&(t=void 0);let n;this.mode!=null&&(n=this._originalMode&4294963200|(this.mode??0),n===nd&&!this.isDirectory()&&(n=void 0),n===sd&&this.isDirectory()&&(n=void 0));let s;return this.mtime!=null&&(s={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),ve.encode({Type:e,Data:t,filesize:this.isDirectory()?void 0:this.fileSize(),blocksizes:this.blockSizes,hashType:this.hashType,fanout:this.fanout,mode:n,mtime:s})}}});var Ne,Ds=p(()=>{"use strict";Ne=class extends Event{constructor(t,n){super(t);f(this,"type");f(this,"detail");this.type=t,this.detail=n}}});var pe,Zt=p(()=>{"use strict";yt();mt();Oo();pe=async(r,e,t)=>{t.codec==null&&(t.codec=jr);let n=await _o.digest(r),s=G.create(t.cidVersion??1,t.codec.code,n);return await e.put(s,r,t),s}});function od(r){return async function*(t,n){let s=0n;for await(let i of t.content)yield async()=>{let o,a={codec:jr,cidVersion:r.cidVersion,onProgress:r.onProgress};r.rawLeaves?(a.codec=Jt,a.cidVersion=1):(o=new j({type:r.leafType,data:i}),i=te({Data:o.marshal(),Links:[]}));let c=await pe(i,n,a);return s+=BigInt(i.byteLength),r.onProgress?.(new Ne("unixfs:importer:progress:file:write",{bytesWritten:s,cid:c,path:t.path})),{cid:c,unixfs:o,size:BigInt(i.length),block:i}}}}var ad=p(()=>{"use strict";yt();Xt();en();Ds();Zt()});var er,ir,tr,Xo,rr,Zo,nr,ea,sr,ke,je,ln=p(()=>{"use strict";er=class er extends Error{constructor(t="Invalid parameters"){super(t);f(this,"name",er.name);f(this,"code",er.code)}};f(er,"name","InvalidParametersError"),f(er,"code","ERR_INVALID_PARAMS");ir=er,tr=class tr extends Error{constructor(t="Invalid avg chunk size"){super(t);f(this,"name",tr.name);f(this,"code",tr.code)}};f(tr,"name","InvalidAvgChunkSizeError"),f(tr,"code","ERR_INVALID_AVG_CHUNK_SIZE");Xo=tr,rr=class rr extends Error{constructor(t="Invalid chunk size"){super(t);f(this,"name",rr.name);f(this,"code",rr.code)}};f(rr,"name","InvalidChunkSizeError"),f(rr,"code","ERR_INVALID_CHUNK_SIZE");Zo=rr,nr=class nr extends Error{constructor(t="Invalid min chunk size"){super(t);f(this,"name",nr.name);f(this,"code",nr.code)}};f(nr,"name","InvalidMinChunkSizeError"),f(nr,"code","ERR_INVALID_MIN_CHUNK_SIZE");ea=nr,sr=class sr extends Error{constructor(t="Invalid content"){super(t);f(this,"name",sr.name);f(this,"code",sr.code)}};f(sr,"name","InvalidContentError"),f(sr,"code","ERR_INVALID_CONTENT");ke=sr,je=class extends Error{constructor(){super(...arguments);f(this,"name",ke.name);f(this,"code",ke.code)}};f(je,"name","InvalidShardingStrategyError"),f(je,"code","ERR_SHARDING_STRATEGY")});var cd,ld=p(()=>{"use strict";yt();Xt();Zt();cd=async(r,e,t)=>{let n=new j({type:"directory",mtime:r.mtime,mode:r.mode}),s=te(ee({Data:n.marshal()})),i=await pe(s,e,t),o=r.path;return{cid:i,path:o,unixfs:n,size:BigInt(s.length),originalPath:r.originalPath,block:s}}});async function*Jm(r,e,t){let n=-1,s;for await(let i of Or(t.bufferImporter(r,e),t.blockWriteConcurrency)){if(n++,n===0){s={...i,single:!0};continue}else n===1&&s!=null&&(yield{...s,block:void 0,single:void 0},s=void 0);yield{...i,block:void 0}}s!=null&&(yield s)}function ud(r){return r.single===!0}var Qm,dd,hd=p(()=>{"use strict";yt();Xt();eo();en();Ds();Zt();Qm=(r,e,t)=>async function(s){if(s.length===1&&ud(s[0])&&t.reduceSingleLeafToSelf){let u=s[0],d=u.block;return ud(u)&&(r.mtime!==void 0||r.mode!==void 0)&&(u.unixfs=new j({type:"file",mtime:r.mtime,mode:r.mode,data:u.block}),d={Data:u.unixfs.marshal(),Links:[]},u.block=te(ee(d)),u.cid=await pe(u.block,e,{...t,cidVersion:t.cidVersion}),u.size=BigInt(u.block.length)),t.onProgress?.(new Ne("unixfs:importer:progress:file:layout",{cid:u.cid,path:r.originalPath})),{cid:u.cid,path:r.path,unixfs:u.unixfs,size:u.size,originalPath:r.originalPath}}let i=new j({type:"file",mtime:r.mtime,mode:r.mode}),o=s.filter(u=>u.cid.code===jt&&u.size>0||u.unixfs!=null&&u.unixfs.data==null&&u.unixfs.fileSize()>0n?!0:!!u.unixfs?.data?.length).map(u=>u.cid.code===jt?(i.addBlockSize(u.size),{Name:"",Tsize:Number(u.size),Hash:u.cid}):(u.unixfs?.data==null?i.addBlockSize(u.unixfs?.fileSize()??0n):i.addBlockSize(BigInt(u.unixfs.data.length)),{Name:"",Tsize:Number(u.size),Hash:u.cid})),a={Data:i.marshal(),Links:o},c=te(ee(a)),l=await pe(c,e,t);return t.onProgress?.(new Ne("unixfs:importer:progress:file:layout",{cid:l,path:r.originalPath})),{cid:l,path:r.path,unixfs:i,size:BigInt(c.length+a.Links.reduce((u,d)=>u+(d.Tsize??0),0)),originalPath:r.originalPath,block:c}},dd=async(r,e,t)=>t.layout(Jm(r,e,t),Qm(r,e,t))});function Xm(r){return Symbol.iterator in r}function Zm(r){return Symbol.asyncIterator in r}function ey(r){try{if(r instanceof Uint8Array)return(async function*(){yield r})();if(Xm(r))return(async function*(){yield*r})();if(Zm(r))return r}catch{throw new ke("Content was invalid")}throw new ke("Content was invalid")}function fd(r){return async function*(t,n){for await(let s of t){let i;if(s.path!=null&&(i=s.path,s.path=s.path.split("/").filter(o=>o!=null&&o!==".").join("/")),ty(s)){let o={path:s.path,mtime:s.mtime,mode:s.mode,content:(async function*(){let c=0n;for await(let l of r.chunker(r.chunkValidator(ey(s.content)))){let u=BigInt(l.byteLength);c+=u,r.onProgress?.(new Ne("unixfs:importer:progress:file:read",{bytesRead:c,chunkSize:u,path:s.path})),yield l}})(),originalPath:i},a=r.fileBuilder??dd;yield async()=>a(o,n,r)}else if(s.path!=null){let o={path:s.path,mtime:s.mtime,mode:s.mode,originalPath:i},a=r.dirBuilder??cd;yield async()=>a(o,n,r)}else throw new Error("Import candidate must have content or path or both")}}}function ty(r){return r.content!=null}var pd=p(()=>{"use strict";Ds();ln();ld();hd()});var md,yd=p(()=>{"use strict";Is();ln();md=()=>async function*(e){for await(let t of e){if(t.length===void 0)throw new ke("Content was invalid");if(typeof t=="string"||t instanceof String)yield Qt(t.toString());else if(Array.isArray(t))yield Uint8Array.from(t);else if(t instanceof Uint8Array)yield t;else throw new ke("Content was invalid")}}});function ta(r){let e=r?.maxChildrenPerNode??ry;return async function t(n,s){let i=[];for await(let o of ms(n,e))i.push(await s(o));return i.length>1?t(i,s):i[0]}}var ry,gd=p(()=>{"use strict";Zi();ry=174});function ny(r){return r[Symbol.asyncIterator]!=null}function sy(r){if(ny(r))return(async()=>{let t=[];for await(let n of r)t.push(n);return t})();let e=[];for(let t of r)e.push(t);return e}var wd,bd=p(()=>{"use strict";wd=sy});var Sd=p(()=>{"use strict";gd()});var Pe,Fs=p(()=>{"use strict";mt();Pe=class{constructor(e,t){f(this,"options");f(this,"root");f(this,"dir");f(this,"path");f(this,"dirty");f(this,"flat");f(this,"parent");f(this,"parentKey");f(this,"unixfs");f(this,"mode");f(this,"mtime");f(this,"cid");f(this,"size");f(this,"nodeSize");this.options=t??{},this.root=e.root,this.dir=e.dir,this.path=e.path,this.dirty=e.dirty,this.flat=e.flat,this.parent=e.parent,this.parentKey=e.parentKey,this.unixfs=e.unixfs,this.mode=e.mode,this.mtime=e.mtime}}});function oy(r){let e=0;return r>=4294967296&&(r=Math.floor(r/4294967296),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+iy[r]}function Je(r){return r%2===0&&r++,Math.floor((oy(r)+6)/7)}function Ms(r){let e=0;for(let t=0;t<r.length;t++){let n=r.charCodeAt(t);n<128?e++:n<2048?e+=2:n>=55296&&n<=56319&&t+1<r.length?(t++,e+=4):e+=3}return e}function Ad(r,e,t){let n=1+Je(e)+e;return n+=1+Je(r)+r,n+=1+Je(t),1+Je(n)+n}function xd(r,e){let t=2;if(r!==void 0&&r!==ay&&(t+=1+Je(r)),e!=null){let n=0,s=Number(e.secs);s<0?n+=11:n+=1+Je(s),e.nsecs!=null&&(n+=5),t+=1+Je(n)+n}return 1+Je(t)+t}var iy,ay,vd=p(()=>{"use strict";iy=[0,1,2,2,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8,8];ay=493});function ra(r,e){return e?.cid!=null&&e?.size!=null?r+e.cid.byteLength:0}function na(r,e){return e?.cid!=null&&e?.size!=null?Ad(r,e.cid.byteLength,Number(e.size)):0}var St,sa=p(()=>{"use strict";yt();Xt();Fs();ia();vd();Zt();St=class extends Pe{constructor(t,n){super(t,n);f(this,"_children");this._children=new Map}async put(t,n){if(this.nodeSize!==void 0){let s=this._children.get(t),i=Ms(t),o=this.options?.shardSplitStrategy;if(o==="links-bytes")this.nodeSize-=ra(i,s),this.nodeSize+=ra(i,n);else if(o==="block-bytes")this.nodeSize-=na(i,s),this.nodeSize+=na(i,n);else throw new je(`Invalid shardSplitStrategy: ${o}`);this.nodeSize<0&&(this.nodeSize=void 0)}this.cid=void 0,this.size=void 0,this._children.set(t,n)}async get(t){return Promise.resolve(this._children.get(t))}childCount(){return this._children.size}directChildrenCount(){return this.childCount()}onlyChild(){return this._children.values().next().value}*eachChildSeries(){for(let[t,n]of this._children.entries())yield{key:t,child:n}}marshal(){let t=new j({type:"directory",mtime:this.mtime,mode:this.mode}),n=[];for(let[i,o]of this._children.entries())if(!(o.size==null||o.cid==null)){if(o.cid==null)throw new Error("Directory contents must be flushed before marshaling");n.push({Hash:o.cid,Name:i,Tsize:o.size==null?void 0:Number(o.size)})}let s={Data:t.marshal(),Links:n};return te(ee(s))}async estimateNodeSize(){if(this.nodeSize!==void 0)return this.nodeSize;let t=this.options?.shardSplitStrategy;if(t==="links-bytes"){this.nodeSize=0;for(let[n,s]of this._children.entries())this.nodeSize+=ra(Ms(n),s)}else if(t==="block-bytes"){this.nodeSize=xd(this.mode,this.mtime);for(let[n,s]of this._children.entries())this.nodeSize+=na(Ms(n),s)}else throw new je(`Invalid shardSplitStrategy: ${t}`);return this.nodeSize}async*flush(t){let n=[];for(let[l,u]of this._children.entries()){let d=u;if(u instanceof Pe)for await(let h of u.flush(t))d=h,yield h;d.size!=null&&d.cid!=null&&n.push({Name:l,Tsize:Number(d.size),Hash:d.cid})}let s=new j({type:"directory",mtime:this.mtime,mode:this.mode}),i={Data:s.marshal(),Links:n},o=te(ee(i)),a=await pe(o,t,this.options),c=o.length+i.Links.reduce((l,u)=>l+(u.Tsize??0),0);this.cid=a,this.size=c,yield{cid:a,unixfs:s,path:this.path,size:BigInt(c)}}}});function Qe(r,e){let t=r.lo+e.lo>>>0,n=r.hi+e.hi+(t<r.lo?1:0)>>>0;return{lo:t,hi:n}}function cy(r,e){return r+e>>>0}function me(r,e){let t=r.lo&65535,n=r.lo>>>16,s=e.lo&65535,i=e.lo>>>16,o=t*s,a=t*i,c=n*s,l=n*i,u=(o>>>16)+(a&65535)+(c&65535)>>>0,d=(u<<16|o&65535)>>>0,h=l+(a>>>16)+(c>>>16)+(u>>>16),m=Math.imul(r.lo,e.hi),y=Math.imul(r.hi,e.lo),w=h+m+y>>>0;return{lo:d,hi:w}}function At(r,e){return Math.imul(r,e)>>>0}function or(r,e){if(e===0)return r;if(e===32)return{lo:r.hi,hi:r.lo};if(e<32){let s=(r.lo<<e|r.hi>>>32-e)>>>0,i=(r.hi<<e|r.lo>>>32-e)>>>0;return{lo:s,hi:i}}e-=32;let t=(r.hi<<e|r.lo>>>32-e)>>>0,n=(r.lo<<e|r.hi>>>32-e)>>>0;return{lo:t,hi:n}}function L(r,e){return{lo:(r.lo^e.lo)>>>0,hi:(r.hi^e.hi)>>>0}}function oa(r,e){if(e===0)return r;if(e<32){let t=(r.lo>>>e|r.hi<<32-e)>>>0,n=r.hi>>>e;return{lo:t,hi:n}}return{lo:r.hi>>>e-32,hi:0}}function R(r,e){return{lo:r>>>0,hi:e>>>0}}function aa(r,e){return(r<<e|r>>>32-e)>>>0}function kd(r,e){let t=e*8,n=r[t]|r[t+1]<<8|r[t+2]<<16|r[t+3]<<24,s=r[t+4]|r[t+5]<<8|r[t+6]<<16|r[t+7]<<24;return{lo:n>>>0,hi:s>>>0}}function ly(r,e){let t=e*4;return(r[t]|r[t+1]<<8|r[t+2]<<16|r[t+3]<<24)>>>0}function Ed(r){return r=L(r,oa(r,33)),r=me(r,R(3981806797,4283543511)),r=L(r,oa(r,33)),r=me(r,R(444984403,3301882366)),r=L(r,oa(r,33)),r}function uy(r){return r^=r>>>16,r=At(r,2246822507),r^=r>>>13,r=At(r,3266489909),r^=r>>>16,r}function ca(r,e=0){let t=R(e,0),n=R(e,0),s=r.length,i=Math.floor(s/16),o=R(289559509,2277735313),a=R(658871167,1291169091);for(let h=0;h<i;h++){let m=kd(r,h*2),y=kd(r,h*2+1);m=me(m,o),m=or(m,31),m=me(m,a),t=L(t,m),t=or(t,27),t=Qe(t,n),t=Qe(me(t,R(5,0)),R(1390208809,0)),y=me(y,a),y=or(y,33),y=me(y,o),n=L(n,y),n=or(n,31),n=Qe(n,t),n=Qe(me(n,R(5,0)),R(944331445,0))}let c=R(0,0),l=R(0,0),u=r.slice(i*16);switch(u.length){case 15:l=L(l,R(0,u[14]<<16));case 14:l=L(l,R(0,u[13]<<8));case 13:l=L(l,R(0,u[12]));case 12:l=L(l,R(u[11]<<24,0));case 11:l=L(l,R(u[10]<<16,0));case 10:l=L(l,R(u[9]<<8,0));case 9:l=L(l,R(u[8],0)),l=me(l,a),l=or(l,33),l=me(l,o),n=L(n,l);case 8:c=L(c,R(0,u[7]<<24));case 7:c=L(c,R(0,u[6]<<16));case 6:c=L(c,R(0,u[5]<<8));case 5:c=L(c,R(0,u[4]));case 4:c=L(c,R(u[3]<<24,0));case 3:c=L(c,R(u[2]<<16,0));case 2:c=L(c,R(u[1]<<8,0));case 1:c=L(c,R(u[0],0)),c=me(c,o),c=or(c,31),c=me(c,a),t=L(t,c)}let d=R(s,0);return t=L(t,d),n=L(n,d),t=Qe(t,n),n=Qe(n,t),t=Ed(t),n=Ed(n),t=Qe(t,n),n=Qe(n,t),new Uint8Array([t.hi>>>24&255,t.hi>>>16&255,t.hi>>>8&255,t.hi&255,t.lo>>>24&255,t.lo>>>16&255,t.lo>>>8&255,t.lo&255,n.hi>>>24&255,n.hi>>>16&255,n.hi>>>8&255,n.hi&255,n.lo>>>24&255,n.lo>>>16&255,n.lo>>>8&255,n.lo&255])}function Cd(r,e=0){let t=e>>>0,n=r.length,s=Math.floor(n/4),i=3432918353,o=461845907;for(let l=0;l<s;l++){let u=ly(r,l);u=At(u,i),u=aa(u,15),u=At(u,o),t^=u,t=aa(t,13),t=cy(At(t,5),3864292196)}let a=r.slice(s*4),c=0;switch(a.length){case 3:c^=a[2]<<16;case 2:c^=a[1]<<8;case 1:c^=a[0],c=At(c,i),c=aa(c,15),c=At(c,o),t^=c}return t^=n,t=uy(t),t}var Pd=p(()=>{"use strict"});function hy(r){let e=new Array(4);for(let t=0;t<4;t++)e[t]=r&255,r=r>>8;return new Uint8Array(e)}var O1,Id,z1,Bd=p(()=>{"use strict";Ps();Pd();O1=wt({name:"murmur3-32",code:35,encode:r=>hy(Cd(r))}),Id=wt({name:"murmur3-128",code:34,encode:r=>ca(r)}),z1=wt({name:"murmur3-x64-64",code:34,encode:r=>ca(r).subarray(0,8)})});var ar,Xe,Td=p(()=>{"use strict";ar=class ar extends Error{constructor(t="Not Found"){super(t);f(this,"name",ar.name);f(this,"code",ar.code)}};f(ar,"name","NotFoundError"),f(ar,"code","ERR_NOT_FOUND");Xe=ar});var Us=p(()=>{"use strict";Td()});var Ie,un=p(()=>{"use strict";Ie=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,n){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:n,bytes:s}of e)await this.put(n,s,t),yield n}get(e,t){throw new Error(".get is not implemented")}async*getMany(e,t){for await(let n of e)yield{cid:n,bytes:this.get(n,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let n of e)await this.delete(n,t),yield n}async*getAll(e){throw new Error(".getAll is not implemented")}}});var cr,la=p(()=>{"use strict";Us();un();cr=class extends Ie{put(e,t,n){return n?.signal?.throwIfAborted(),e}get(e,t){throw t?.signal?.throwIfAborted(),new Xe}has(e,t){return t?.signal?.throwIfAborted(),!1}async delete(e,t){t?.signal?.throwIfAborted()}async*getAll(e){e?.signal?.throwIfAborted()}}});var Fd=C((X1,Dd)=>{"use strict";Dd.exports=class{constructor(){this._bitArrays=[],this._data=[],this._length=0,this._changedLength=!1,this._changedData=!1}set(e,t){let n=this._internalPositionFor(e,!1);if(t===void 0)n!==-1&&(this._unsetInternalPos(n),this._unsetBit(e),this._changedLength=!0,this._changedData=!0);else{let s=!1;n===-1?(n=this._data.length,this._setBit(e),this._changedData=!0):s=!0,this._setInternalPos(n,e,t,s),this._changedLength=!0}}unset(e){this.set(e,void 0)}get(e){this._sortData();let t=this._internalPositionFor(e,!0);if(t!==-1)return this._data[t][1]}push(e){return this.set(this.length,e),this.length}get length(){if(this._sortData(),this._changedLength){let e=this._data[this._data.length-1];this._length=e?e[0]+1:0,this._changedLength=!1}return this._length}forEach(e){let t=0;for(;t<this.length;)e(this.get(t),t,this),t++}map(e){let t=0,n=new Array(this.length);for(;t<this.length;)n[t]=e(this.get(t),t,this),t++;return n}reduce(e,t){let n=0,s=t;for(;n<this.length;){let i=this.get(n);s=e(s,i,n),n++}return s}find(e){let t=0,n,s;for(;t<this.length&&!n;)s=this.get(t),n=e(s),t++;return n?s:void 0}_internalPositionFor(e,t){let n=this._bytePosFor(e,t);if(n>=this._bitArrays.length)return-1;let s=this._bitArrays[n],i=e-n*7;if(!((s&1<<i)>0))return-1;let a=this._bitArrays.slice(0,n).reduce(fy,0),c=~(4294967295<<i+1),l=Rd(s&c);return a+l-1}_bytePosFor(e,t){let n=Math.floor(e/7),s=n+1;for(;!t&&this._bitArrays.length<s;)this._bitArrays.push(0);return n}_setBit(e){let t=this._bytePosFor(e,!1);this._bitArrays[t]|=1<<e-t*7}_unsetBit(e){let t=this._bytePosFor(e,!1);this._bitArrays[t]&=~(1<<e-t*7)}_setInternalPos(e,t,n,s){let i=this._data,o=[t,n];if(s)this._sortData(),i[e]=o;else{if(i.length)if(i[i.length-1][0]>=t)i.push(o);else if(i[0][0]<=t)i.unshift(o);else{let a=Math.round(i.length/2);this._data=i.slice(0,a).concat(o).concat(i.slice(a))}else this._data.push(o);this._changedData=!0,this._changedLength=!0}}_unsetInternalPos(e){this._data.splice(e,1)}_sortData(){this._changedData&&this._data.sort(py),this._changedData=!1}bitField(){let e=[],t=8,n=0,s=0,i,o=this._bitArrays.slice();for(;o.length||n;){n===0&&(i=o.shift(),n=7);let c=Math.min(n,t),l=~(255<<c),u=i&l;s|=u<<8-t,i=i>>>c,n-=c,t-=c,(!t||!n&&!o.length)&&(e.push(s),s=0,t=8)}for(var a=e.length-1;a>0&&e[a]===0;a--)e.pop();return e}compactArray(){return this._sortData(),this._data.map(my)}};function fy(r,e){return r+Rd(e)}function Rd(r){let e=r;return e=e-(e>>1&1431655765),e=(e&858993459)+(e>>2&858993459),(e+(e>>4)&252645135)*16843009>>24}function py(r,e){return r[0]-e[0]}function my(r){return r[1]}});function yy(r){return!!r}function gy(r,e){return r.key}function wy(r){return r}async function Ud(r,e,t){let n=[];for(let s of r._children.compactArray())if(s instanceof Ze)await Ud(s,e,t);else{let i=await e(s);n.push({bitField:r._children.bitField(),children:i})}return t(n)}var Md,Ze,Nd=p(()=>{"use strict";Md=z(Fd(),1);Is();Ze=class r{constructor(e,t,n=0){f(this,"_options");f(this,"_popCount");f(this,"_parent");f(this,"_posAtParent");f(this,"_children");f(this,"key");this._options=e,this._popCount=0,this._parent=t,this._posAtParent=n,this._children=new Md.default,this.key=null}async put(e,t){let n=await this._findNewBucketAndPos(e);n.bucket._putAt(n,e,t)}async get(e){let t=await this._findChild(e);if(t!=null)return t.value}async del(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);n!=null&&n.key===e&&t.bucket._delAt(t.pos)}leafCount(){return this._children.compactArray().reduce((t,n)=>n instanceof r?t+n.leafCount():t+1,0)}childrenCount(){return this._children.length}onlyChild(){return this._children.get(0)}*eachLeafSeries(){let e=this._children.compactArray();for(let t of e)t instanceof r?yield*t.eachLeafSeries():yield t}serialize(e,t){let n=[];return t(this._children.reduce((s,i,o)=>(i!=null&&(i instanceof r?s.push(i.serialize(e,t)):s.push(e(i,o))),s),n))}async asyncTransform(e,t){return Ud(this,e,t)}toJSON(){return this.serialize(gy,wy)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(e){let t=await this._findPlace(e),n=t.bucket._at(t.pos);if(!(n instanceof r)&&n!=null&&n.key===e)return n}async _findPlace(e){let t=this._options.hash(typeof e=="string"?Qt(e):e),n=await t.take(this._options.bits),s=this._children.get(n);return s instanceof r?s._findPlace(t):{bucket:this,pos:n,hash:t,existingChild:s}}async _findNewBucketAndPos(e){let t=await this._findPlace(e);if(t.existingChild!=null&&t.existingChild.key!==e){let n=new r(this._options,t.bucket,t.pos);t.bucket._putObjectAt(t.pos,n);let s=await n._findPlace(t.existingChild.hash);return s.bucket._putAt(s,t.existingChild.key,t.existingChild.value),n._findNewBucketAndPos(t.hash)}return t}_putAt(e,t,n){this._putObjectAt(e.pos,{key:t,value:n,hash:e.hash})}_putObjectAt(e,t){this._children.get(e)==null&&this._popCount++,this._children.set(e,t)}_delAt(e){if(e===-1)throw new Error("Invalid position");this._children.get(e)!=null&&this._popCount--,this._children.unset(e),this._level()}_level(){if(this._parent!=null&&this._popCount<=1)if(this._popCount===1){let e=this._children.find(yy);if(e!=null&&!(e instanceof r)){let t=e.hash;t.untake(this._options.bits);let n={pos:this._posAtParent,hash:t,bucket:this._parent};this._parent._putAt(n,e.key,e.value)}}else this._parent._delAt(this._posAtParent)}_at(e){return this._children.get(e)}}});function Ay(r,e,t){let n=xy(e,t);return(r&n)>>>e}function xy(r,e){return by[r]&Sy[Math.min(e+r-1,7)]}var by,Sy,Ns,Ld=p(()=>{"use strict";by=[255,254,252,248,240,224,192,128],Sy=[1,3,7,15,31,63,127,255],Ns=class{constructor(e){f(this,"_value");f(this,"_currentBytePos");f(this,"_currentBitPos");this._value=e,this._currentBytePos=e.length-1,this._currentBitPos=7}availableBits(){return this._currentBitPos+1+this._currentBytePos*8}totalBits(){return this._value.length*8}take(e){let t=e,n=0;for(;t>0&&this._haveBits();){let s=this._value[this._currentBytePos],i=this._currentBitPos+1,o=Math.min(i,t),a=Ay(s,i-o,o);n=(n<<o)+a,t-=o,this._currentBitPos-=o,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return n}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}}});function _d(r){function e(t){return t instanceof Ls?t:new Ls(t,r)}return e}var Ls,Kd=p(()=>{"use strict";to();Ld();Ls=class{constructor(e,t){f(this,"_value");f(this,"_hashFn");f(this,"_depth");f(this,"_availableBits");f(this,"_currentBufferIndex");f(this,"_buffers");if(!(e instanceof Uint8Array))throw new Error("can only hash Uint8Arrays");this._value=e,this._hashFn=t,this._depth=-1,this._availableBits=0,this._currentBufferIndex=0,this._buffers=[]}async take(e){let t=e;for(;this._availableBits<t;)await this._produceMoreBits();let n=0;for(;t>0;){let s=this._buffers[this._currentBufferIndex],i=Math.min(s.availableBits(),t),o=s.take(i);n=(n<<i)+o,t-=i,this._availableBits-=i,s.availableBits()===0&&this._currentBufferIndex++}return n}untake(e){let t=e;for(;t>0;){let n=this._buffers[this._currentBufferIndex],s=Math.min(n.totalBits()-n.availableBits(),t);n.untake(s),t-=s,this._availableBits+=s,this._currentBufferIndex>0&&n.totalBits()===n.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?zr([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new Ns(t);this._buffers.push(n),this._availableBits+=n.availableBits()}}});function Od(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:_d(r.hashFn)};return new Ze(e)}var zd=p(()=>{"use strict";Nd();Kd()});async function vy(r){return(await Id.encode(r)).slice(0,8).reverse()}async function*$d(r,e,t,n){let s=r._children,i=(r.tableSize()-1).toString(16).length,o=[],a=0n;for(let y=0;y<s.length;y++){let w=s.get(y);if(w==null)continue;let b=y.toString(16).toUpperCase().padStart(i,"0");if(w instanceof Ze){let S;for await(let A of $d(w,e,null,n))S=A;if(S==null)throw new Error("Could not flush sharded directory, no sub-shard found");o.push({Name:b,Tsize:Number(S.size),Hash:S.cid}),a+=S.size}else if(Hd(w.value)){let S=w.value,A;for await(let B of S.flush(e))A=B,yield A;if(A==null)throw new Error("Did not flush dir");let v=b+w.key;o.push({Name:v,Tsize:Number(A.size),Hash:A.cid}),a+=A.size}else{let S=w.value;if(S.cid==null)continue;let A=b+w.key,v=S.size;o.push({Name:A,Tsize:Number(v),Hash:S.cid}),a+=BigInt(v??0)}}let c=Uint8Array.from(s.bitField().reverse()),l=new j({type:"hamt-sharded-directory",data:c,fanout:BigInt(r.tableSize()),hashType:ro,mtime:t?.mtime,mode:t?.mode}),u={Data:l.marshal(),Links:o},d=te(ee(u)),h=await pe(d,e,n),m=BigInt(d.byteLength)+a;yield{cid:h,unixfs:l,size:m}}function Hd(r){return typeof r.flush=="function"}async function qd(r,e,t,n){let s=r._children,i=(r.tableSize()-1).toString(16).length,o=[],a=0;for(let h=0;h<s.length;h++){let m=s.get(h);if(m==null)continue;let y=h.toString(16).toUpperCase().padStart(i,"0");if(m instanceof Ze){let{size:w,cid:b}=await qd(m,null,t,n);o.push({Name:y,Tsize:Number(w),Hash:b}),a+=y.length+b.byteLength}else if(Hd(m.value)){let w=m.value,b=w.nodeSize;if(w.cid==null)throw new Error("Child directory has not been persisted");o.push({Name:y+m.key,Tsize:Number(b),Hash:w.cid}),a+=y.length+w.cid.byteLength}else{let w=m.value,b=y+m.key,S=w.size;o.push({Name:b,Tsize:Number(S),Hash:w.cid}),a+=y.length+w.cid.byteLength}}let c=Uint8Array.from(s.bitField().reverse()),l=new j({type:"hamt-sharded-directory",data:c,fanout:BigInt(r.tableSize()),hashType:ro,mtime:e?.mtime,mode:e?.mode}),u=te(ee({Data:l.marshal(),Links:o}));return{cid:await pe(u,t,n),size:n.shardSplitStrategy==="links-bytes"?a:u.length}}var ua,Wd,Vd=p(()=>{"use strict";yt();Bd();la();zd();Xt();Wr();Fs();Zt();ua=class extends Pe{constructor(t,n){super(t,n);f(this,"bucket");this.bucket=Od({hashFn:vy,bits:n.shardFanoutBits??gs})}async put(t,n){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,await this.bucket.put(t,n)}async get(t){return this.bucket.get(t)}childCount(){return this.bucket.leafCount()}directChildrenCount(){return this.bucket.childrenCount()}onlyChild(){return this.bucket.onlyChild()}*eachChildSeries(){for(let{key:t,value:n}of this.bucket.eachLeafSeries())yield{key:t,child:n}}async estimateNodeSize(){if(this.nodeSize!==void 0)return this.nodeSize;let t=new cr,n=await qd(this.bucket,this,t,this.options);return this.nodeSize=n.size,this.nodeSize}async*flush(t){for await(let n of $d(this.bucket,t,this,this.options))yield{...n,path:this.path}}},Wd=ua});async function da(r,e){let t=e,n=e.options.shardSplitThresholdBytes??ws;e instanceof St&&await e.estimateNodeSize()>n&&(t=await ky(e));let s=t.parent;if(s!=null){if(t!==e){if(r!=null&&(r.parent=t),t.parentKey==null)throw new Error("No parent key found");await s.put(t.parentKey,t)}return da(t,s)}return t}async function ky(r){let e=new Wd({root:r.root,dir:!0,parent:r.parent,parentKey:r.parentKey,path:r.path,dirty:r.dirty,flat:!1,mtime:r.mtime,mode:r.mode},r.options);for(let{key:t,child:n}of r.eachChildSeries())await e.put(t,n);return e}var Gd=p(()=>{"use strict";Wr();sa();Vd()});var Yd,jd=p(()=>{"use strict";Yd=(r="")=>r.split(/(?<!\\)\//).filter(Boolean)});async function Ey(r,e,t){let n=Yd(r.path??""),s=n.length-1,i=e,o="";for(let a=0;a<n.length;a++){let c=n[a];o+=`${o!==""?"/":""}${c}`;let l=a===s;if(i.dirty=!0,i.cid=void 0,i.size=void 0,l)await i.put(c,r),e=await da(null,i);else{let u=await i.get(c);(u==null||!(u instanceof Pe))&&(u=new St({root:!1,dir:!0,parent:i,parentKey:c,path:o,dirty:!0,flat:!0,mtime:u?.unixfs?.mtime,mode:u?.unixfs?.mode},t)),await i.put(c,u),i=u}}return e}async function*Jd(r,e){if(!(r instanceof Pe)){r.unixfs?.isDirectory()===!0&&(yield r);return}yield*r.flush(e)}function Qd(r){return async function*(t,n){let s=new St({root:!0,dir:!0,path:"",dirty:!0,flat:!0},r),i,o=!1;for await(let a of t){if(a==null)continue;let c=`${a.originalPath??""}`.split("/")[0];c!=null&&c!==""&&(i==null?(i=c,o=!0):i!==c&&(o=!1)),s=await Ey(a,s,r),a.unixfs?.isDirectory()!==!0&&(yield a)}if(r.wrapWithDirectory||o&&s.childCount()>1)yield*Jd(s,n);else for(let a of s.eachChildSeries())a!=null&&(yield*Jd(a.child,n))}}var Xd=p(()=>{"use strict";sa();Fs();Gd();jd()});var Zd={};x(Zd,{InvalidAvgChunkSizeError:()=>Xo,InvalidChunkSizeError:()=>Zo,InvalidContentError:()=>ke,InvalidMinChunkSizeError:()=>ea,InvalidParametersError:()=>ir,InvalidShardingStrategyError:()=>je,importByteStream:()=>Iy,importBytes:()=>Py,importDirectory:()=>Cy,importFile:()=>fa,importer:()=>ha});async function*ha(r,e,t={}){let n;Symbol.asyncIterator in r||Symbol.iterator in r?n=r:n=[r];let s,i;t.profile==="unixfs-v0-2015"?(t.shardSplitStrategy=t.shardSplitStrategy??"links-bytes",t.cidVersion=t.cidVersion??0,t.rawLeaves=t.rawLeaves??!1,s=bs,i=174):t.profile==="unixfs-v1-2025"&&(t.shardSplitStrategy=t.shardSplitStrategy??"block-bytes",t.cidVersion=t.cidVersion??1,t.rawLeaves=t.rawLeaves??!0,s=Al,i=1024);let o=t.wrapWithDirectory??Cl,a=t.shardSplitThresholdBytes??ws,c=t.shardSplitStrategy??Sl,l=t.shardFanoutBits??gs,u=t.cidVersion??1,d=t.rawLeaves??El,h=t.leafType??Pl,m=t.fileImportConcurrency??xl,y=t.blockWriteConcurrency??vl,w=t.reduceSingleLeafToSelf??kl,b=t.chunker??Il({chunkSize:s}),S=t.chunkValidator??md(),A=t.dagBuilder??fd({chunker:b,chunkValidator:S,wrapWithDirectory:o,layout:t.layout??ta({maxChildrenPerNode:i}),bufferImporter:t.bufferImporter??od({cidVersion:u,rawLeaves:d,leafType:h,onProgress:t.onProgress}),blockWriteConcurrency:y,reduceSingleLeafToSelf:w,cidVersion:u,onProgress:t.onProgress,dirBuilder:t.dirBuilder,fileBuilder:t.fileBuilder}),v=t.treeBuilder??Qd({wrapWithDirectory:o,shardSplitThresholdBytes:a,shardSplitStrategy:c,shardFanoutBits:l,cidVersion:u,onProgress:t.onProgress});for await(let B of v(Or(A(n,e),m),e))yield{cid:B.cid,path:B.path,unixfs:B.unixfs,size:B.size}}async function fa(r,e,t={}){let n=await Xi(ha([r],e,t));if(n==null)throw new ir("Nothing imported");return n}async function Cy(r,e,t={}){let n=await Xi(ha([r],e,t));if(n==null)throw new ir("Nothing imported");return n}async function Py(r,e,t={}){return fa({content:r},e,t)}async function Iy(r,e,t={}){return fa({content:r},e,t)}var ia=p(()=>{"use strict";dl();eo();Bl();Wr();ad();pd();yd();ln();Sd();Xd();ln()});function By(r){return typeof r?.then=="function"}var _s,eh=p(()=>{"use strict";Us();bd();$r();mt();en();Vt();un();_s=class extends Ie{constructor(){super();f(this,"data");this.data=new Map}put(t,n,s){s?.signal?.throwIfAborted();let i;if(n instanceof Uint8Array)i=[n];else{let o=wd(n);if(By(o))return o.then(a=>this._put(t,a,s));i=o}return this._put(t,i,s)}_put(t,n,s){return s?.signal?.throwIfAborted(),this.data.set(Z.encode(t.multihash.bytes),n),t}*get(t,n){n?.signal?.throwIfAborted();let s=this.data.get(Z.encode(t.multihash.bytes));if(s==null)throw new Xe;yield*s}has(t,n){return n?.signal?.throwIfAborted(),this.data.has(Z.encode(t.multihash.bytes))}async delete(t,n){n?.signal?.throwIfAborted(),this.data.delete(Z.encode(t.multihash.bytes))}*getAll(t){t?.signal?.throwIfAborted();for(let[n,s]of this.data.entries())yield{cid:G.createV1(jt,vs(Z.decode(n))),bytes:(async function*(){yield*s})()},t?.signal?.throwIfAborted()}}});function Ks(r,e){if(typeof r=="string")return Ty(r);if(typeof r=="number")return Fy(r,e);throw new Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}function Ty(r){if(typeof r!="string"||r.length===0||r.length>100)throw new Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(r)}`);let e=/^(?<value>-?\d*\.?\d+) *(?<unit>milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|months?|mo|years?|yrs?|y)?$/i.exec(r);if(!e?.groups)return NaN;let{value:t,unit:n="ms"}=e.groups,s=parseFloat(t),i=n.toLowerCase();switch(i){case"years":case"year":case"yrs":case"yr":case"y":return s*315576e5;case"months":case"month":case"mo":return s*26298e5;case"weeks":case"week":case"w":return s*6048e5;case"days":case"day":case"d":return s*864e5;case"hours":case"hour":case"hrs":case"hr":case"h":return s*36e5;case"minutes":case"minute":case"mins":case"min":case"m":return s*6e4;case"seconds":case"second":case"secs":case"sec":case"s":return s*1e3;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return s;default:throw new Error(`Unknown unit "${i}" provided to ms.parse(). value=${JSON.stringify(r)}`)}}function Ry(r){let e=Math.abs(r);return e>=315576e5?`${Math.round(r/315576e5)}y`:e>=26298e5?`${Math.round(r/26298e5)}mo`:e>=6048e5?`${Math.round(r/6048e5)}w`:e>=864e5?`${Math.round(r/864e5)}d`:e>=36e5?`${Math.round(r/36e5)}h`:e>=6e4?`${Math.round(r/6e4)}m`:e>=1e3?`${Math.round(r/1e3)}s`:`${r}ms`}function Dy(r){let e=Math.abs(r);return e>=315576e5?xt(r,e,315576e5,"year"):e>=26298e5?xt(r,e,26298e5,"month"):e>=6048e5?xt(r,e,6048e5,"week"):e>=864e5?xt(r,e,864e5,"day"):e>=36e5?xt(r,e,36e5,"hour"):e>=6e4?xt(r,e,6e4,"minute"):e>=1e3?xt(r,e,1e3,"second"):`${r} ms`}function Fy(r,e){if(typeof r!="number"||!Number.isFinite(r))throw new Error("Value provided to ms.format() must be of type number.");return e?.long?Dy(r):Ry(r)}function xt(r,e,t,n){let s=e>=t*1.5;return`${Math.round(r/t)} ${n}${s?"s":""}`}var pa=p(()=>{"use strict"});function ma(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=s,t.enabled=o,t.humanize=Ks,t.destroy=l,Object.keys(r).forEach(u=>{t[u]=r[u]}),t.names=[],t.skips=[],t.formatters={};function e(u){let d=0;for(let h=0;h<u.length;h++)d=(d<<5)-d+u.charCodeAt(h),d|=0;return t.colors[Math.abs(d)%t.colors.length]}t.selectColor=e;function t(u,d){let h,m=null,y,w;function b(...S){if(!b.enabled)return;let A=b,v=Number(new Date),B=v-(h||v);A.diff=B,A.prev=h,A.curr=v,h=v,S[0]=t.coerce(S[0]),typeof S[0]!="string"&&S.unshift("%O");let E=0;S[0]=S[0].replace(/%([a-zA-Z%])/g,(F,$)=>{if(F==="%%")return"%";E++;let Be=t.formatters[$];if(typeof Be=="function"){let vt=S[E];F=Be.call(A,vt),S.splice(E,1),E--}return F}),t.formatArgs.call(A,S),d?.onLog!=null&&d.onLog(...S),(A.log||t.log).apply(A,S)}return b.namespace=u,b.useColors=t.useColors(),b.color=t.selectColor(u),b.extend=n,b.destroy=t.destroy,Object.defineProperty(b,"enabled",{enumerable:!0,configurable:!1,get:()=>m!==null?m:(y!==t.namespaces&&(y=t.namespaces,w=t.enabled(u)),w),set:S=>{m=S}}),typeof t.init=="function"&&t.init(b),b}function n(u,d){let h=t(this.namespace+(typeof d>"u"?":":d)+u);return h.log=this.log,h}function s(u){t.save(u),t.namespaces=u,t.names=[],t.skips=[];let d,h=(typeof u=="string"?u:"").split(/[\s,]+/),m=h.length;for(d=0;d<m;d++)h[d]&&(u=h[d].replace(/\*/g,".*?"),u[0]==="-"?t.skips.push(new RegExp("^"+u.substr(1)+"$")):t.names.push(new RegExp("^"+u+"$")))}function i(){let u=[...t.names.map(a),...t.skips.map(a).map(d=>"-"+d)].join(",");return t.enable(""),u}function o(u){if(u[u.length-1]==="*")return!0;let d,h;for(d=0,h=t.skips.length;d<h;d++)if(t.skips[d].test(u))return!1;for(d=0,h=t.names.length;d<h;d++)if(t.names[d].test(u))return!0;return!1}function a(u){return u.toString().substring(2,u.toString().length-2).replace(/\.\*\?$/,"*")}function c(u){return u instanceof Error?u.stack??u.message:u}function l(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.setupFormatters(t.formatters),t.enable(t.load()),t}var th=p(()=>{"use strict";pa()});function Uy(){return typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs)?!0:typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/(edge|trident)\/(\d+)/)!=null?!1:typeof document<"u"&&document.documentElement?.style?.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/firefox\/(\d+)/)!=null&&parseInt(RegExp.$1,10)>=31||typeof navigator<"u"&&navigator.userAgent?.toLowerCase().match(/applewebkit\/(\d+)/)}function Ny(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+Ks(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(n=t))}),r.splice(n,0,e)}function _y(r){try{r?Os?.setItem("debug",r):Os?.removeItem("debug")}catch{}}function Ky(){let r;try{r=Os?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function Oy(){try{return localStorage}catch{}}function zy(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var Os,My,Ly,rh,nh=p(()=>{"use strict";pa();th();Os=Oy(),My=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];Ly=console.debug??console.log??(()=>{});rh=ma({formatArgs:Ny,save:_y,load:Ky,useColors:Uy,setupFormatters:zy,colors:My,storage:Os,log:Ly})});var re,sh=p(()=>{"use strict";nh();re=rh});function ih(r,e=""){let t=oh(r.message),n=oh(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
951
- `).join(`
952
- ${e}`)}`:`${t}
953
- ${e}${n.split(`
954
- `).join(`
955
- ${e}`)}`:n!=null?`${n.split(`
956
- `).join(`
957
- ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function Wy(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function ah(r,e=""){if(Wy(r)){let t=ih(r,e);return r.errors.length>0?(e=`${e} `,t+=`
958
- ${e}${r.errors.map(n=>`${ah(n,`${e}`)}`).join(`
959
- ${e}`)}`):t+=`
960
- ${e}[Error list was empty]`,t.trim()}return ih(r,e)}function $y(r){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=r,e.destroy=()=>!0,e.extend=()=>e,e.useColors=()=>!1,e}function ya(r,e){let t=$y(`${r}:trace`);return re.enabled(`${r}:trace`)&&re.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=re(`${r}:trace`,e)),Object.assign(re(r,e),{error:re(`${r}:error`,e),trace:t,newScope:n=>ya(`${r}:${n}`,e)})}function oh(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var ch=p(()=>{"use strict";$r();Ss();Fo();sh();re.formatters.b=r=>r==null?"undefined":fe.baseEncode(r);re.formatters.t=r=>r==null?"undefined":Z.baseEncode(r);re.formatters.m=r=>r==null?"undefined":Ro.baseEncode(r);re.formatters.p=r=>r==null?"undefined":r.toString();re.formatters.c=r=>r==null?"undefined":r.toString();re.formatters.k=r=>r==null?"undefined":r.toString();re.formatters.a=r=>r==null?"undefined":r.toString();re.formatters.e=r=>r==null?"undefined":ah(r)});function Hy(r){let[e,t]=r[Symbol.asyncIterator]!=null?[r[Symbol.asyncIterator](),Symbol.asyncIterator]:[r[Symbol.iterator](),Symbol.iterator],n=[];return{peek:()=>e.next(),push:s=>{n.push(s)},next:()=>n.length>0?{done:!1,value:n.shift()}:e.next(),[t](){return this}}}var lh,uh=p(()=>{"use strict";lh=Hy});function qy(r){return r[Symbol.asyncIterator]!=null}function Vy(r,e){let t=0;if(qy(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=lh(r),{value:s,done:i}=n.next();if(i===!0)return(function*(){})();let o=e(s,t++);if(typeof o.then=="function")return(async function*(){await o&&(yield s);for(let c of n)await e(c,t++)&&(yield c)})();let a=e;return(function*(){o===!0&&(yield s);for(let c of n)a(c,t++)&&(yield c)})()}var dh,hh=p(()=>{"use strict";uh();dh=Vy});function lr(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var fh=p(()=>{"use strict"});function Gy(r){return r.reason}async function ph(r,e,t){if(e==null)return r;let n=t?.translateError??Gy;if(e.aborted)return r.catch(()=>{}),Promise.reject(n(e));let s;try{return await Promise.race([r,new Promise((i,o)=>{s=()=>{o(n(e))},e.addEventListener("abort",s)})])}finally{s!=null&&e.removeEventListener("abort",s)}}var mh=p(()=>{"use strict"});function yh(){return new ga}var ga,gh=p(()=>{"use strict";fh();mh();ga=class{constructor(){f(this,"readNext");f(this,"haveNext");f(this,"ended");f(this,"nextResult");f(this,"error");this.ended=!1,this.readNext=lr(),this.haveNext=lr()}[Symbol.asyncIterator](){return this}async next(){if(this.nextResult==null&&await this.haveNext.promise,this.nextResult==null)throw new Error("HaveNext promise resolved but nextResult was undefined");let e=this.nextResult;return this.nextResult=void 0,this.readNext.resolve(),this.readNext=lr(),e}async throw(e){return this.ended=!0,this.error=e,e!=null&&(this.haveNext.promise.catch(()=>{}),this.haveNext.reject(e)),{done:!0,value:void 0}}async return(){let e={done:!0,value:void 0};return this.ended=!0,this.nextResult=e,this.haveNext.resolve(),e}async push(e,t){await this._push(e,t)}async end(e,t){e!=null?await this.throw(e):await this._push(void 0,t)}async _push(e,t){if(e!=null&&this.ended)throw this.error??new Error("Cannot push value onto an ended pushable");for(;this.nextResult!=null;)await this.readNext.promise;e!=null?this.nextResult={done:!1,value:e}:(this.ended=!0,this.nextResult={done:!0,value:void 0}),this.haveNext.resolve(),this.haveNext=lr(),await ph(this.readNext.promise,t?.signal,t)}}});function Yy(r){return r[Symbol.asyncIterator]!=null}async function jy(r,e,t){try{await Promise.all(r.map(async n=>{for await(let s of n)await e.push(s,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(n){await e.end(n,{signal:t}).catch(()=>{})}}async function*Jy(r){let e=new AbortController,t=yh();jy(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Qy(r){for(let e of r)yield*e}function Xy(...r){let e=[];for(let t of r)Yy(t)||e.push(t);return e.length===r.length?Qy(e):Jy(r)}var wh,bh=p(()=>{"use strict";gh();wh=Xy});var Zy,zs,Sh=p(()=>{"use strict";ch();Us();hh();bh();un();Zy=ya("blockstore:core:tiered"),zs=class extends Ie{constructor(t){super();f(this,"stores");this.stores=t.slice()}async put(t,n,s){return await Promise.all(this.stores.map(async i=>{await i.put(t,n,s)})),t}async*get(t,n){let s;for(let i of this.stores)try{yield*i.get(t,n);return}catch(o){s=o,Zy.error(o)}throw s??new Xe}async has(t,n){for(let s of this.stores)if(await s.has(t,n))return!0;return!1}async delete(t,n){await Promise.all(this.stores.map(async s=>{await s.delete(t,n)}))}async*putMany(t,n={}){for await(let s of t)await this.put(s.cid,s.bytes,n),yield s.cid}async*deleteMany(t,n={}){for await(let s of t)await this.delete(s,n),yield s}async*getAll(t){let n=new Set;yield*dh(wh(...this.stores.map(s=>s.getAll(t))),s=>{let i=s.cid.toString();return n.has(i)?!1:(n.add(i),!0)})}}});var Ah={};x(Ah,{BaseBlockstore:()=>Ie,BlackHoleBlockstore:()=>cr,MemoryBlockstore:()=>_s,TieredBlockstore:()=>zs});var xh=p(()=>{"use strict";un();eh();la();Sh()});var vh=C((Tx,eg)=>{eg.exports={name:"w3pk",version:"0.10.4",description:"WebAuthn SDK for passwordless authentication, encrypted wallets, ERC-5564 stealth addresses, and zero-knowledge proofs",author:"Julien B\xE9ranger",license:"GPL-3.0",repository:{type:"git",url:"https://github.com/w3hc/w3pk.git"},bugs:{url:"https://github.com/w3hc/w3pk/issues"},homepage:"https://github.com/w3hc/w3pk#readme",keywords:["webauthn","passkey","authentication","passwordless","fido2","biometric","ethereum","web3","encryption","zero-knowledge","zk-proofs","zk-snarks","privacy","stealth-address","erc-5564","erc-6538","unlinkable","anonymous-transactions","privacy-preserving","ecdh","secp256k1","view-tags","circom","groth16","merkle-tree","commitment-scheme"],main:"./dist/index.js",module:"./dist/index.mjs",types:"./dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.mjs",require:"./dist/index.js"},"./zk":{types:"./dist/zk/index.d.ts",import:"./dist/zk/index.mjs",require:"./dist/zk/index.js"},"./zk/utils":{types:"./dist/zk/utils.d.ts",import:"./dist/zk/utils.mjs",require:"./dist/zk/utils.js"},"./chainlist":{types:"./dist/chainlist/index.d.ts",import:"./dist/chainlist/index.mjs",require:"./dist/chainlist/index.js"},"./inspect":{types:"./dist/inspect/index.d.ts",import:"./dist/inspect/index.mjs",require:"./dist/inspect/index.js"},"./inspect/node":{types:"./dist/inspect/node.d.ts",import:"./dist/inspect/node.mjs",require:"./dist/inspect/node.js"}},sideEffects:!1,files:["dist","README.md","LICENSE","docs/","scripts/compute-build-hash.mjs"],scripts:{build:"tsup","build:zk":"npm run build && npm run compile:circuits","compile:circuits":"node scripts/compile-circuits.js",dev:"tsup --watch",test:"tsx test/test.ts && tsx test/comprehensive.test.ts && tsx test/backup.test.ts && tsx test/social-recovery.test.ts && tsx test/recovery-education.test.ts && tsx test/zk/zk.test.ts && tsx test/nft-ownership.test.ts && tsx test/chainlist.test.ts && tsx test/eip7702.test.ts && tsx test/external-wallet.test.ts && tsx test/erc5564.test.ts && tsx test/zk/key-stretching.test.ts && tsx test/username-encoding.test.ts && tsx test/username-validation.test.ts && tsx test/origin-derivation.test.ts && tsx test/build-hash.test.ts && tsx test/credential-checking.test.ts && tsx test/webauthn-native.test.ts && tsx test/persistent-session.test.ts && tsx test/local-storage.test.ts && tsx test/sign-message.test.ts && tsx test/siwe.test.ts && tsx test/requirereauth.test.ts && tsx test/eip7951.test.ts && tsx test/send-transaction.test.ts && tsx test/eip1193-provider.test.ts && tsx test/mlkem.test.ts && tsx test/login-missing-wallet.test.ts && tsx test/backup-status.test.ts && tsx test/eviction-risk.test.ts && tsx test/fresh-device-sync.test.ts && tsx test/prf-secret.test.ts && tsx test/prf-sync.test.ts","test:basic":"tsx test/test.ts","test:comprehensive":"tsx test/comprehensive.test.ts","test:backup":"tsx test/backup.test.ts","test:social-recovery":"tsx test/social-recovery.test.ts","test:education":"tsx test/recovery-education.test.ts","test:username":"tsx test/username-encoding.test.ts && tsx test/username-validation.test.ts","test:recovery":"tsx test/backup.test.ts && tsx test/social-recovery.test.ts && tsx test/recovery-education.test.ts","test:zk":"tsx test/zk/zk.test.ts","test:nft":"tsx test/nft-ownership.test.ts","test:chainlist":"tsx test/chainlist.test.ts","test:eip7702":"tsx test/eip7702.test.ts","test:external-wallet":"tsx test/external-wallet.test.ts","test:eip7951":"tsx test/eip7951.test.ts","test:erc5564":"tsx test/erc5564.test.ts","test:sign-message":"tsx test/sign-message.test.ts","test:siwe":"tsx test/siwe.test.ts",prepublishOnly:"pnpm build","build:hash":"node scripts/compute-build-hash.mjs",html:"lsof -ti:3000 | xargs kill -9 2>/dev/null || true && tsup && npx serve . -l 3000 & sleep 5 && open http://localhost:3000/standalone/checker.html"},packageManager:"pnpm@10.6.4",devDependencies:{"@types/node":"^25.9.2","@types/qrcode":"^1.5.5",circomlib:"^2.0.5",siwe:"3.0.0",tsup:"^8.5.1",tsx:"^4.22.4",typescript:"^6.0.3"},peerDependencies:{ethers:"^6.0.0"},optionalDependencies:{"@ipld/car":"^5.4.6","blockstore-core":"^7.0.1",circomlibjs:"^0.1.7","ipfs-unixfs-importer":"^17.0.1",qrcode:"^1.5.4",snarkjs:"^0.7.6"},dependencies:{"@noble/hashes":"^2.2.0",mlkem:"^2.7.0"},pnpm:{overrides:{"jsonpath@<1.2.0":">=1.2.0","bn.js@>=5.0.0 <5.2.3":">=5.2.3","bn.js@<4.12.3":">=4.12.3","minimatch@>=5.0.0 <5.1.7":">=5.1.7","rollup@>=4.0.0 <4.59.0":">=4.59.0","minimatch@>=5.0.0 <5.1.8":">=5.1.8","jsonpath@<=1.2.1":">=1.3.0","brace-expansion@>=2.0.0 <2.0.3":">=2.0.3","picomatch@>=4.0.0 <4.0.4":">=4.0.4","underscore@<=1.13.7":">=1.13.8","ws@>=8.0.0 <8.20.1":">=8.20.1"}}}});var og={};x(og,{ApiError:()=>dr,AuthenticationError:()=>N,CryptoError:()=>P,DEFAULT_MODE:()=>ge,DEFAULT_TAG:()=>X,PrfUnsupportedError:()=>Le,RecoverySimulator:()=>Nt,RegistrationError:()=>et,SocialRecoveryManager:()=>dt,StealthAddressModule:()=>Bt,StorageError:()=>k,SyncBootstrapError:()=>ye,SyncRequiredError:()=>tt,WalletError:()=>g,WalletMissingError:()=>rt,Web3Passkey:()=>_t,Web3PasskeyError:()=>_,arrayBufferToBase64Url:()=>ne,assertEthereumAddress:()=>dn,assertMnemonic:()=>va,assertUsername:()=>hn,authenticateWithPasskey:()=>Wi,base64ToArrayBuffer:()=>Gs,base64UrlDecode:()=>js,base64UrlToArrayBuffer:()=>T,canControlStealthAddress:()=>Da,checkStealthAddress:()=>wr,clearCache:()=>Oa,computeStealthPrivateKey:()=>br,createSiweMessage:()=>Ch,createWalletFromMnemonic:()=>ti,createWeb3Passkey:()=>Th,default:()=>ig,deriveAddressFromP256PublicKey:()=>ri,deriveIndexFromOriginModeAndTag:()=>bn,deriveMLKemKeypair:()=>_r,deriveStealthKeys:()=>It,deriveWalletFromMnemonic:()=>gr,detectWalletProvider:()=>Fn,encodeEIP7702AuthorizationMessage:()=>Ar,extractRS:()=>_i,generateBIP39Wallet:()=>yr,generateSiweNonce:()=>Eh,generateStealthAddress:()=>An,getAllChains:()=>_a,getAllTopics:()=>qi,getChainById:()=>Ka,getCurrentBuildHash:()=>Sa,getCurrentOrigin:()=>ue,getDefaultProvider:()=>Dn,getEndpoints:()=>In,getExplainer:()=>Hi,getOriginSpecificAddress:()=>we,getPackageVersion:()=>ba,getW3pkBuildHash:()=>wa,hashEIP7702AuthorizationMessage:()=>xr,inspect:()=>Aa,inspectNow:()=>Bh,isStrongPassword:()=>ka,mlkemDecrypt:()=>fs,mlkemDecryptWithKey:()=>Qi,mlkemEncrypt:()=>hs,mlkemEncryptWithKey:()=>Ji,normalizeOrigin:()=>st,parseSiweMessage:()=>Ws,promptPasskeySelection:()=>zi,requestExternalWalletAuthorization:()=>Rn,safeAtob:()=>nt,safeBtoa:()=>Ys,searchExplainers:()=>Vi,supportsEIP7702Authorization:()=>Mn,validateEthereumAddress:()=>Hs,validateMnemonic:()=>Vs,validateSiweMessage:()=>Ph,validateUsername:()=>qs,verifyBuildHash:()=>kh,verifyEIP7702Authorization:()=>Bn,verifySiweSignature:()=>Ih});module.exports=zh(og);W();function Hs(r){return/^0x[a-fA-F0-9]{40}$/.test(r)}function qs(r){return r.length<3||r.length>50?!1:/^[a-zA-Z0-9]([a-zA-Z0-9_-]*[a-zA-Z0-9])?$/.test(r)}function Vs(r){let e=r.trim().split(/\s+/);return e.length===12||e.length===24}function dn(r){if(!Hs(r))throw new Error("Invalid Ethereum address format")}function hn(r){if(!qs(r))throw new Error("Username must be 3-50 characters long and contain only letters, numbers, underscores, and hyphens. Must start and end with a letter or number.")}function va(r){if(!Vs(r))throw new Error("Invalid mnemonic: must be 12 or 24 words")}function ka(r){if(r.length<12)return!1;let e=/[A-Z]/.test(r),t=/[a-z]/.test(r),n=/[0-9]/.test(r),s=/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(r);return!(!e||!t||!n||!s||["password","12345678","qwerty","abc123","password123","admin","letmein"].some(o=>r.toLowerCase().includes(o)))}_e();ce();se();async function qh(r){try{let e=new Uint8Array(r),t=Vh(e);if(t===-1)return null;let n=e.slice(t);if(!((n[32]&64)!==0))return null;let o=37;o+=16;let a=n[o]<<8|n[o+1];o+=2,o+=a;let c=n.slice(o),l=await Gh(c);return ne(l)}catch(e){return console.error("Failed to extract public key:",e),null}}function Vh(r){let e=new Uint8Array([104,97,117,116,104,68,97,116,97]);for(let t=0;t<r.length-e.length;t++){let n=!0;for(let s=0;s<e.length;s++)if(r[t+s]!==e[s]){n=!1;break}if(n){let s=r[t+e.length],i=t+e.length+1;if(s>=88&&s<=91){let o=s-87;i+=o}return i}}return-1}async function Gh(r){let e=Ca(r,-2),t=Ca(r,-3);if(!e||!t)throw new Error("Failed to extract EC coordinates from COSE key");let n=new Uint8Array(65);n[0]=4,n.set(e,1),n.set(t,33);let s=new Uint8Array([48,89,48,19,6,7,42,134,72,206,61,2,1,6,8,42,134,72,206,61,3,1,7,3,66,0]),i=new Uint8Array(s.length+n.length);return i.set(s,0),i.set(n,s.length),i.buffer}function Ca(r,e){let t=e<0?32+(-1-e):e;for(let n=0;n<r.length-33;n++)if(r[n]===t&&(r[n+1]===88&&r[n+2]===32||r[n+1]===88&&r[n+2]===32))return r.slice(n+3,n+35);return null}async function Pa(r){try{let{username:e,ethereumAddress:t}=r;hn(e),dn(t);let n=new D;if(await n.userExists(e))throw new Error("Username already registered");let s=Ee(),o=new TextEncoder().encode(e),a=ne(o),c=T(s),l=T(a),u={challenge:c,rp:{name:"w3pk",id:window.location.hostname},user:{id:l,name:e,displayName:e},pubKeyCredParams:[{type:"public-key",alg:-7},{type:"public-key",alg:-257}],authenticatorSelection:{authenticatorAttachment:"platform",userVerification:"required",residentKey:"required",requireResidentKey:!0},timeout:6e4,attestation:"none",extensions:{prf:{eval:{first:hr}}}},d=await navigator.credentials.create({publicKey:u});if(!d)throw new Error("Failed to create credential");let h=await qh(d.response.attestationObject);if(!h)throw new Error("Public key not returned from authenticator");await n.saveCredential({id:d.id,publicKey:h,username:e,ethereumAddress:t,createdAt:new Date().toISOString(),lastUsed:new Date().toISOString(),signCount:0});let m=d.response.attestationObject,y=d.getClientExtensionResults?.().prf?.results?.first;return{signature:m,prfOutput:y}}catch(e){throw new et(e instanceof Error?e.message:"Registration failed",e)}}ei();W();var gn="w3pk_wallet_",wn=class{constructor(e){this.customStorage=e}get storage(){if(this.customStorage)return this.customStorage;if(typeof window<"u"&&window.localStorage)return window.localStorage;throw new k("localStorage is not available")}async init(){}async store(e){try{this.storage.setItem(gn+e.ethereumAddress,JSON.stringify(e))}catch(t){throw new k("Failed to store wallet data",t)}}async retrieve(e){try{let t=this.storage.getItem(gn+e);return t?JSON.parse(t):null}catch(t){throw new k("Failed to retrieve wallet data",t)}}async delete(e){try{this.storage.removeItem(gn+e)}catch(t){throw new k("Failed to delete wallet data",t)}}async clear(){try{for(let e of this.keys())this.storage.removeItem(e)}catch(e){throw new k("Failed to clear wallet data",e)}}keys(){let e=[];for(let t=0;t<this.storage.length;t++){let n=this.storage.key(t);n?.startsWith(gn)&&e.push(n)}return e}};Te();Pt();se();W();var q=require("ethers");W();function It(r){try{let e=q.ethers.HDNodeWallet.fromPhrase(r,void 0,"m/44'/60'/1'/0/0"),t=q.ethers.HDNodeWallet.fromPhrase(r,void 0,"m/44'/60'/1'/0/1"),n=t.signingKey.compressedPublicKey,s=e.signingKey.compressedPublicKey;return{stealthMetaAddress:n+s.slice(2),spendingPubKey:n,viewingPubKey:s,viewingKey:e.privateKey,spendingKey:t.privateKey}}catch(e){throw new P("Failed to derive stealth keys",e)}}function An(r){try{let e="0x"+r.slice(2,68),t="0x"+r.slice(68),n=q.ethers.Wallet.createRandom(),s=n.signingKey.compressedPublicKey,i=ni(n.privateKey,t),o=q.ethers.keccak256(i),a="0x"+o.slice(2,4),c=si(o),l=Ma(e,Fa(c));return{stealthAddress:Ua(l),ephemeralPubKey:s,viewTag:a}}catch(e){throw new P("Failed to generate stealth address",e)}}function wr(r,e,t,n,s){try{let i=ni(r,t),o=q.ethers.keccak256(i);if(s&&("0x"+o.slice(2,4)).toLowerCase()!==s.toLowerCase())return{isForUser:!1};let a=si(o),c=Ma(e,Fa(a)),l=Ua(c);return l.toLowerCase()!==n.toLowerCase()?{isForUser:!1}:{isForUser:!0,stealthAddress:l}}catch{return{isForUser:!1}}}function br(r,e,t){try{let n=ni(r,t),s=q.ethers.keccak256(n),i=si(s);return Xh(e,i)}catch(n){throw new P("Failed to compute stealth private key",n)}}function Da(r,e,t,n,s,i){try{if(!wr(r,t,n,s,i).isForUser)return!1;let a=br(r,e,n);return new q.ethers.Wallet(a).address.toLowerCase()===s.toLowerCase()}catch{return!1}}function ni(r,e){try{return new q.ethers.Wallet(r).signingKey.computeSharedSecret(e)}catch(t){throw new P("Failed to compute shared secret",t)}}function Fa(r){try{return new q.ethers.Wallet(r).signingKey.compressedPublicKey}catch(e){throw new P("Failed to multiply generator by scalar",e)}}function Ma(r,e){try{let t=q.ethers.SigningKey.computePublicKey(r,!1),n=q.ethers.SigningKey.computePublicKey(e,!1),s=BigInt("0x"+t.slice(4,68)),i=BigInt("0x"+t.slice(68)),o=BigInt("0x"+n.slice(4,68)),a=BigInt("0x"+n.slice(68)),c=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F");if(s===o&&i===a){let y=3n*s*s%c,w=2n*i%c,b=y*Ra(w,c)%c,S=(b*b-2n*s)%c,A=(b*(s-S)-i)%c;return Ta((S+c)%c,(A+c)%c)}let l=((a-i)%c+c)%c,u=((o-s)%c+c)%c,d=l*Ra(u,c)%c,h=(d*d-s-o)%c,m=(d*(s-h)-i)%c;return Ta((h+c)%c,(m+c)%c)}catch(t){throw new P("Failed to add public keys",t)}}function si(r){try{let e=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"),n=BigInt(r)%e;if(n===0n)throw new Error("Scalar reduced to zero (invalid)");return"0x"+n.toString(16).padStart(64,"0")}catch(e){throw new P("Failed to reduce scalar modulo curve order",e)}}function Xh(r,e){try{let t=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"),n=BigInt(r),s=BigInt(e);return"0x"+((n+s)%t).toString(16).padStart(64,"0")}catch(t){throw new P("Failed to add private keys",t)}}function Ta(r,e){return"0x"+(e%2n===0n?"02":"03")+r.toString(16).padStart(64,"0")}function Ra(r,e){r=(r%e+e)%e;let[t,n]=[r,e],[s,i]=[1n,0n];for(;n!==0n;){let o=t/n;[t,n]=[n,t-o*n],[s,i]=[i,s-o*i]}return(s%e+e)%e}function Ua(r){try{let e=q.ethers.SigningKey.computePublicKey(r,!1),t=q.ethers.keccak256("0x"+e.slice(4));return q.ethers.getAddress("0x"+t.slice(-40))}catch(e){throw new P("Failed to derive address from public key",e)}}var Bt=class{constructor(e,t){this.getMnemonic=t}async generateStealthAddress(e){try{let t=await this.getMnemonic(e?.requireAuth),n=It(t),s=An(n.stealthMetaAddress);return{stealthAddress:s.stealthAddress,ephemeralPublicKey:s.ephemeralPubKey,viewTag:s.viewTag}}catch(t){throw new _("Failed to generate stealth address","STEALTH_GENERATION_ERROR",t)}}async parseAnnouncement(e,t){try{let n=await this.getMnemonic(t?.requireAuth),s=It(n),i=wr(s.viewingKey,s.spendingPubKey,e.ephemeralPublicKey,e.stealthAddress,e.viewTag);if(!i.isForUser)return{isForUser:!1};let o=br(s.viewingKey,s.spendingKey,e.ephemeralPublicKey);return{isForUser:!0,stealthAddress:i.stealthAddress,stealthPrivateKey:o}}catch(n){throw new _("Failed to parse announcement","ANNOUNCEMENT_PARSE_ERROR",n)}}async scanAnnouncements(e,t){let n=[];for(let s of e){let i=await this.parseAnnouncement(s,t);i.isForUser&&n.push(i)}return n}async getKeys(e){try{let t=await this.getMnemonic(e?.requireAuth);return It(t)}catch(t){throw new _("Failed to get stealth keys","STEALTH_KEYS_ERROR",t)}}async getStealthMetaAddress(e){try{return(await this.getKeys(e)).stealthMetaAddress}catch(t){throw new _("Failed to get stealth meta-address","STEALTH_META_ADDRESS_ERROR",t)}}get isAvailable(){return!0}};W();var xn="w3pk_session_",vn=class{constructor(e){this.customStorage=e}get storage(){if(this.customStorage)return this.customStorage;if(typeof window<"u"&&window.localStorage)return window.localStorage;throw new k("localStorage is not available")}async init(){}async store(e){if(e.securityMode==="STRICT")throw new k("Cannot persist STRICT mode sessions");try{this.storage.setItem(xn+e.ethereumAddress,JSON.stringify(e))}catch(t){throw new k("Failed to store persistent session",t)}}async retrieve(e){let t;try{let n=this.storage.getItem(xn+e);t=n?JSON.parse(n):null}catch(n){throw new k("Failed to retrieve persistent session",n)}return t&&Date.now()>t.expiresAt?(await this.delete(e),null):t}async delete(e){try{this.storage.removeItem(xn+e)}catch(t){throw new k("Failed to delete persistent session",t)}}async clear(){try{for(let e of this.keys())this.storage.removeItem(e)}catch(e){throw new k("Failed to clear persistent sessions",e)}}async cleanupExpired(){try{let e=Date.now();for(let t of this.keys()){let n=this.storage.getItem(t),s=n?JSON.parse(n):null;(!s||e>s.expiresAt)&&this.storage.removeItem(t)}}catch(e){throw new k("Failed to cleanup expired sessions",e)}}keys(){let e=[];for(let t=0;t<this.storage.length;t++){let n=this.storage.key(t);n?.startsWith(xn)&&e.push(n)}return e}};se();var kn=class{constructor(e=1,t){this.session=null;this.sessionDuration=e*60*60*1e3,this.persistentConfig={enabled:t?.enabled??!1,duration:t?.duration??168,requireReauth:t?.requireReauth??!0},this.persistentStorage=new vn}async startSession(e,t,n,s,i){let o=new Date(Date.now()+this.sessionDuration).toISOString();if(this.session={mnemonic:e,expiresAt:o,credentialId:t},this.persistentConfig.enabled&&i!=="STRICT"&&n){if(!s){console.info("[w3pk] Authenticator did not provide a PRF output \u2014 persistent session not stored on this device (in-memory session only)");return}try{let a=await J(e,s),c=Date.now()+this.persistentConfig.duration*60*60*1e3;await this.persistentStorage.store({encryptedMnemonic:a,sessionKey:this.persistentConfig.requireReauth?void 0:await Qs(s),expiresAt:c,credentialId:t,ethereumAddress:n,securityMode:i||"STANDARD",createdAt:Date.now()})}catch(a){console.warn("[w3pk] Failed to persist session:",a)}}}getMnemonic(){return this.session?new Date>new Date(this.session.expiresAt)?(this.clearSession().catch(e=>console.warn("[w3pk] Failed to clear expired session:",e)),null):this.session.mnemonic:null}getCredentialId(){return this.session?new Date>new Date(this.session.expiresAt)?(this.clearSession().catch(e=>console.warn("[w3pk] Failed to clear expired session:",e)),null):this.session.credentialId:null}isActive(){return this.getMnemonic()!==null}getRemainingTime(){return this.session?new Date>new Date(this.session.expiresAt)?(this.clearSession().catch(e=>console.warn("[w3pk] Failed to clear expired session:",e)),0):Math.floor((new Date(this.session.expiresAt).getTime()-Date.now())/1e3):0}extendSession(){if(!this.session)throw new Error("No active session to extend");if(new Date>new Date(this.session.expiresAt))throw this.clearSession().catch(e=>console.warn("[w3pk] Failed to clear expired session:",e)),new Error("Session expired, cannot extend");this.session.expiresAt=new Date(Date.now()+this.sessionDuration).toISOString()}async restoreFromPersistentStorage(e,t,n){if(!this.persistentConfig.enabled||!n)return null;try{let s=await this.persistentStorage.retrieve(e);if(!s)return null;if(s.credentialId!==t)return console.warn("[w3pk] Credential ID mismatch, clearing persistent session"),await this.persistentStorage.delete(e),null;let i=await Q(s.encryptedMnemonic,n),o=new Date(Date.now()+this.sessionDuration).toISOString();return this.session={mnemonic:i,expiresAt:o,credentialId:t},i}catch(s){console.warn("[w3pk] Failed to restore persistent session:",s);try{await this.persistentStorage.delete(e)}catch{}return null}}async attemptSilentRestore(){if(!this.persistentConfig.enabled||this.persistentConfig.requireReauth)return null;try{let{CredentialStorage:e}=await Promise.resolve().then(()=>(_e(),mn)),n=await new e().getAllCredentials();if(n.length===0)return null;for(let s of n){let i=await this.persistentStorage.retrieve(s.ethereumAddress);if(!i)continue;if(i.credentialId!==s.id){console.warn("[w3pk] Credential ID mismatch, skipping this session");continue}if(!i.sessionKey)continue;let o=await Q(i.encryptedMnemonic,await Xs(i.sessionKey)),a=new Date(Date.now()+this.sessionDuration).toISOString();return this.session={mnemonic:o,expiresAt:a,credentialId:s.id},{mnemonic:o,ethereumAddress:s.ethereumAddress,credentialId:s.id}}return null}catch(e){return console.warn("[w3pk] Failed to attempt silent restore:",e),null}}async clearSession(){this.session&&(this.session.mnemonic="0".repeat(this.session.mnemonic.length)),this.session=null,this.persistentConfig.enabled&&await this.persistentStorage.clear()}get storesSessionKey(){return this.persistentConfig.enabled&&!this.persistentConfig.requireReauth}setSessionDuration(e){this.sessionDuration=e*60*60*1e3}setPersistentSessionDuration(e){this.persistentConfig.duration=e}};_e();En();ai();var Pn={debug:!1,sessionDuration:1,persistentSession:{enabled:!1,duration:168,requireReauth:!0},onError:r=>{Pn.debug&&console.error("[w3pk]",r)}};W();var La="https://chainid.network/chains.json";var Sr=null,sf=[/\$\{[\w_]+\}/i,/\{[\w_]+\}/i,/<[\w_]+>/i,/YOUR[-_]?API[-_]?KEY/i,/INSERT[-_]?API[-_]?KEY/i,/API[-_]?KEY[-_]?HERE/i];function of(r){return sf.some(e=>e.test(r))}async function af(r=La){let e=await fetch(r);if(!e.ok)throw new Error(`Failed to fetch chains data: ${e.status} ${e.statusText}`);return await e.json()}async function ci(r){let e=r?.chainsJsonUrl??La,t=r?.cacheDuration??36e5,n=Date.now();if(Sr&&n-Sr.timestamp<t)return Sr.data;let s=await af(e);return Sr={data:s,timestamp:n},s}async function In(r,e){let n=(await ci(e)).find(s=>s.chainId===r);return n?n.rpc.filter(s=>!of(s)&&!s.startsWith("wss://")&&!s.startsWith("ws://")):[]}async function _a(r){return ci(r)}async function Ka(r,e){return(await ci(e)).find(n=>n.chainId===r)}function Oa(){Sr=null}ui();Tn();var cf=new Set([1,10,8453,42161,57073,100,42220,137,42,15,40,41,44,46,47,50,51,56,61,71,82,83,95,97,112,123,130,146,151,153,171,180,183,185,195,215,228,247,248,252,261,267,291,293,311,332,336,395,401,416,466,480,488,510,545,634,647,648,747,831,919,938,945,957,964,970,980,995,997,1001,1003,1024,1030,1114,1125,1135,1149,1188,1284,1285,1287,1300,1301,1315,1337,1338,1339,1424,1514,1687,1727,1729,1740,1750,1829,1868,1946,1961,1962,1969,1989,1995,2017,2020,2031,2043,2109,2241,2340,2345,2440,2522,2559,2649,3068,3109,3338,3502,3799,3888,3889,4e3,4048,4078,4162,4201,4202,4460,4488,4661,4689,4690,4888,5e3,5003,5124,5234,5330,5424,5522,6283,6342,6398,6678,6806,6934,6942,6969,7117,7171,7200,7208,7368,7518,7668,7672,7744,7771,7869,7897,8008,8118,8217,8408,8700,8726,8727,8844,8880,8881,8882,8889,9372,9496,9700,9745,9746,9899,9990,9996,10011,10085,10143,10200,11221,11501,11504,11891,13370,14853,16602,16661,17e3,18880,18881,19991,21e3,21816,21912,25327,32323,33401,34443,41923,42170,43111,44787,47805,48898,48900,49049,49088,5e4,50312,53302,53456,53457,55244,56288,59141,60808,60850,62320,62850,64002,71402,72080,73114,73115,75338,78281,80002,80008,80069,80094,80451,80931,84532,88899,91342,92278,94524,96970,97476,97477,98985,100021,100501,101010,102030,102031,102032,112358,120893,121212,121213,121214,121215,129399,161803,175188,192940,193939,198989,212013,222222,240241,325e3,355110,355113,421614,555777,560048,656476,713715,743111,747474,763373,763375,777777,806582,808813,810180,839999,888991,2019775,2222222,4278608,5734951,6666689,6985385,7080969,7777777,9999999,11142220,11155111,11155420,11155931,16969696,19850818,20180427,20250825,28122024,34949059,37084624,52164803,61022448,79479957,96969696,420420421,420420422,888888888,974399131,999999999,1020352220,1273227453,1313161560,1350216234,1380996178,1417429182,1444673419,1482601649,1564830818,2046399126,11297108099,11297108109,88153591557,123420000220,123420001114]);async function lf(r,e=1e4){try{let t=new AbortController,n=setTimeout(()=>t.abort(),e),s=await fetch(r,{method:"POST",headers:{"Content-Type":"application/json"},signal:t.signal,body:JSON.stringify({jsonrpc:"2.0",method:"eth_estimateGas",params:[{from:"0xdeadbeef00000000000000000000000000000000",to:"0xdeadbeef00000000000000000000000000000000",data:"0x0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",value:"0x0"},"latest",{"0xdeadbeef00000000000000000000000000000000":{code:"0xef01000000000000000000000000000000000000000001"}}],id:1})});if(clearTimeout(n),!s.ok)return!1;let i=await s.json();if(i.error){let o=(i.error.message||"").toLowerCase();return!["unsupported","not supported","unknown","invalid","unrecognized","does not support","not implemented"].some(c=>o.includes(c))}return i.result!==void 0}catch{return!1}}async function Wa(r,e,t){if(cf.has(r))return!0;let n=t?.maxEndpoints||3,s=t?.timeout||1e4;try{let i=await e(r);if(i.length===0)return!1;let o=i.slice(0,n);for(let a of o)if(await lf(a,s))return!0;return!1}catch{return!1}}function ll(r){return typeof r=="string"&&/^0x[0-9a-fA-F]*$/.test(r)}function ul(r){let e=r.startsWith("0x")?r.slice(2):r,t=new Uint8Array(e.match(/.{1,2}/g).map(n=>parseInt(n,16)));return new TextDecoder().decode(t)}var _t=class{constructor(e={}){this.currentUser=null;this.currentWallet=null;this.persisted=null;this.config={...Pn,...e},this.walletStorage=new wn;let t={...Pn.persistentSession,...e.persistentSession};this.sessionManager=new kn(e.sessionDuration||1,t),e.stealthAddresses!==void 0&&(this.stealth=new Bt(e.stealthAddresses,n=>this.getMnemonicFromSession(n)))}async loadZKModule(){if(this.zkModule)return this.zkModule;try{let e=new Function("path","return import(path)"),{ZKProofModule:t}=await e("w3pk/zk"),n=this.config.zkProofs||{};return this.zkModule=new t(n),this.zkModule}catch{throw new Error("ZK module not available. Install dependencies: npm install snarkjs circomlibjs")}}async getMnemonicFromSession(e=!1,t="STANDARD"){let n=t;if(!e){let h=this.sessionManager.getMnemonic();if(h)return h}if(!this.currentUser)throw new g("Must be authenticated. Call login() first.");let s=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!s)throw new g("No wallet found. Generate a wallet first.");let i=await pr();if(!i.user)throw new g("Authentication failed");let c=(await new D().getCredentialById(s.credentialId))?.publicKey,l=await le(s.credentialId,c),u=await Q(s.encryptedMnemonic,l),d=i.prfOutput?await kt(i.prfOutput,this.sessionManager.storesSessionKey):void 0;return await this.sessionManager.startSession(u,s.credentialId,this.currentUser.ethereumAddress,d,n),u}async register(e){try{this.currentWallet?.address||await this.generateWallet();let t=this.currentWallet.address,n=this.currentWallet.mnemonic,s=await Pa({username:e.username,ethereumAddress:t}),o=await new D().getCredentialByAddress(t);if(this.currentUser={username:e.username,ethereumAddress:t,credentialId:o?.id||""},!o)throw new g("Credential not found after registration");let a=o.id,c=o.publicKey,l=await le(a,c),u=await J(n,l);await this.walletStorage.store({ethereumAddress:this.currentUser.ethereumAddress,encryptedMnemonic:u,credentialId:a,createdAt:new Date().toISOString()});let d=s.prfOutput?await kt(s.prfOutput,this.sessionManager.storesSessionKey):void 0;await this.sessionManager.startSession(n,a,t,d,"STANDARD"),this.currentWallet={address:t,mnemonic:n};let{BackupManager:h}=await Promise.resolve().then(()=>(Fe(),De)),m=await new h().hasBackup(t),y=await Cn();return this.requestPersistentStorage(),this.config.onAuthStateChanged?.(!0,this.currentUser),{address:t,username:e.username,hasBackup:m,evictionRisk:y}}catch(t){throw this.config.onError?.(t),t}}async login(){try{let e=await this.sessionManager.attemptSilentRestore();if(e){let d=await new D().getCredentialById(e.credentialId);return await this.walletStorage.retrieve(e.ethereumAddress)?(this.currentUser={username:d?.username||e.ethereumAddress,ethereumAddress:e.ethereumAddress,credentialId:e.credentialId},this.requestPersistentStorage(),this.config.onAuthStateChanged?.(!0,this.currentUser),this.currentUser):(await this.sessionManager.clearSession().catch(m=>console.warn("[w3pk] Failed to clear stale session:",m)),this.login())}let t=await pr();if(!t.verified||!t.user)throw new N("Login failed");let n=await this.walletStorage.retrieve(t.user.ethereumAddress);if(!n)throw new rt(t.user.credentialId,t.user.ethereumAddress);this.currentUser={username:t.user.username,ethereumAddress:t.user.ethereumAddress,credentialId:t.user.credentialId};let o=(await new D().getCredentialById(n.credentialId))?.publicKey,a=t.prfOutput?await kt(t.prfOutput,this.sessionManager.storesSessionKey):void 0,c=await this.sessionManager.restoreFromPersistentStorage(this.currentUser.ethereumAddress,n.credentialId,a),l;if(c)l=c;else{let u=await le(n.credentialId,o);l=await Q(n.encryptedMnemonic,u),await this.sessionManager.startSession(l,n.credentialId,this.currentUser.ethereumAddress,a,"STANDARD")}return this.requestPersistentStorage(),this.config.onAuthStateChanged?.(!0,this.currentUser),this.currentUser}catch(e){throw this.config.onError?.(e),e}}async logout(){this.currentUser=null,this.currentWallet=null;try{await this.sessionManager.clearSession()}finally{this.config.onAuthStateChanged?.(!1,void 0)}}get isAuthenticated(){return this.currentUser!==null}get user(){return this.currentUser}get storagePersisted(){return this.persisted}async requestPersistentStorage(){if(!(typeof navigator>"u"||!navigator.storage?.persist))try{this.persisted=await navigator.storage.persist()}catch{this.persisted=!1}}async listExistingCredentials(){try{return(await new D().getAllCredentials()).map(n=>({username:n.username,ethereumAddress:n.ethereumAddress,createdAt:n.createdAt,lastUsed:n.lastUsed}))}catch{return[]}}async hasExistingCredential(){return(await this.listExistingCredentials()).length>0}async getExistingCredentialCount(){return(await this.listExistingCredentials()).length}async generateWallet(){try{let e=yr();return this.currentWallet={address:e.address,mnemonic:e.mnemonic},{address:e.address,mnemonic:e.mnemonic}}catch(e){throw this.config.onError?.(e),new g("Failed to generate wallet",e)}}async deriveWallet(e,t,n){try{if(!this.currentUser)throw new g("Must be authenticated to derive wallet");let s=e||ge,i=t||X,o=n?.origin||ue();if(s==="PRIMARY"){let{CredentialStorage:u}=await Promise.resolve().then(()=>(_e(),mn)),{deriveAddressFromP256PublicKey:d}=await Promise.resolve().then(()=>(Pt(),Sn)),m=await new u().getCredentialById(this.currentUser.credentialId);if(!m||!m.publicKey)throw new g("No WebAuthn credential found for PRIMARY mode");return{address:await d(m.publicKey),origin:o,mode:s,tag:i,publicKey:m.publicKey}}let a=s==="STRICT"?!0:n?.requireAuth||!1,c=await this.getMnemonicFromSession(a,s),l=await we(c,o,s,i);return{address:l.address,privateKey:l.privateKey,index:l.index,origin:l.origin,mode:l.mode,tag:l.tag}}catch(s){throw this.config.onError?.(s),new g("Failed to derive wallet",s)}}async getAddress(e,t,n){try{if(!this.currentUser)throw new g("Must be authenticated to get address");let s=e||ge,i=t||X,o=n?.origin||ue();if(s==="PRIMARY"){let{deriveAddressFromP256PublicKey:u}=await Promise.resolve().then(()=>(Pt(),Sn)),h=await new D().getCredentialById(this.currentUser.credentialId);if(!h||!h.publicKey)throw new g("No WebAuthn credential found for PRIMARY mode");return await u(h.publicKey)}let a=s==="STRICT",c=await this.getMnemonicFromSession(a,s);return(await we(c,o,s,i)).address}catch(s){throw this.config.onError?.(s),new g("Failed to get address",s)}}async importMnemonic(e){try{if(!this.currentUser)throw new g("Must be authenticated to import mnemonic");if(!e||e.trim().split(/\s+/).length<12)throw new g("Invalid mnemonic: must be at least 12 words");let t=await pr();if(!t.user)throw new g("Authentication failed");let n=t.user.credentialId,o=(await new D().getCredentialById(n))?.publicKey,a=await le(n,o),c=await J(e.trim(),a);await this.walletStorage.store({ethereumAddress:this.currentUser.ethereumAddress,encryptedMnemonic:c,credentialId:n,createdAt:new Date().toISOString()}),this.currentWallet={address:this.currentUser.ethereumAddress,mnemonic:e.trim()};let l=t.prfOutput?await kt(t.prfOutput,this.sessionManager.storesSessionKey):void 0;await this.sessionManager.startSession(e.trim(),n,this.currentUser.ethereumAddress,l,"STANDARD")}catch(t){throw this.config.onError?.(t),new g("Failed to import mnemonic",t)}}async signMessage(e,t){try{let n=t?.mode||ge,s=t?.signingMethod||"EIP191";if(n==="PRIMARY"&&s==="SIWE")throw new g("SIWE signing is not supported in PRIMARY mode. Use STANDARD, STRICT or YOLO mode.");if(!this.currentUser)throw new g("Must be authenticated to sign message");let i=t?.tag||X,o=t?.origin||ue(),a=n==="STRICT"?!0:t?.requireAuth||!1,c=await this.getMnemonicFromSession(a,n),l=await we(c,o,n,i),{Wallet:u}=await import("ethers"),d;if(l.privateKey)d=new u(l.privateKey);else{let{deriveWalletFromMnemonic:m}=await Promise.resolve().then(()=>(Te(),Ct)),{privateKey:y}=m(c,l.index);d=new u(y)}let h;switch(s){case"EIP191":case"SIWE":h=await d.signMessage(e);break;case"EIP712":if(!t?.eip712Domain||!t?.eip712Types||!t?.eip712PrimaryType)throw new g("EIP712 signing requires eip712Domain, eip712Types, and eip712PrimaryType in options");let m;try{m=typeof e=="string"?JSON.parse(e):e}catch{throw new g("EIP712 message must be valid JSON or an object")}h=await d.signTypedData(t.eip712Domain,t.eip712Types,m);break;case"rawHash":let{SigningKey:y}=await import("ethers"),w=e;if(w.startsWith("0x")&&(w=w.slice(2)),w.length!==64)throw new g("rawHash signing method requires a 32-byte hash (64 hex characters)");h=new y(d.privateKey).sign("0x"+w).serialized;break;default:throw new g(`Unsupported signing method: ${s}`)}return{signature:h,address:l.address,mode:l.mode,tag:l.tag,origin:l.origin}}catch(n){throw this.config.onError?.(n),new g("Failed to sign message",n)}}async signMessageWithPasskey(e){try{if(!this.currentUser)throw new g("Must be authenticated to sign message");let{extractRS:t}=await Promise.resolve().then(()=>(Ki(),Jc)),{base64UrlDecode:n}=await Promise.resolve().then(()=>(ce(),Js)),s=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e)),i="0x"+Buffer.from(s).toString("hex"),o=new Uint8Array(Buffer.from(i.slice(2),"hex")),a=this.currentUser.credentialId;if(!a)throw new g("Credential ID not found in user object");let c={challenge:o,rpId:window.location.hostname,allowCredentials:[{id:n(a),type:"public-key",transports:["internal","hybrid","usb","nfc","ble"]}],userVerification:"required",timeout:6e4},l=await navigator.credentials.get({publicKey:c});if(!l||!l.response)throw new g("WebAuthn signature failed");let u=l.response,d=new Uint8Array(u.authenticatorData),h=new Uint8Array(u.clientDataJSON),m=await crypto.subtle.digest("SHA-256",h),y=new Uint8Array(d.length+m.byteLength);y.set(d,0),y.set(new Uint8Array(m),d.length);let w=await crypto.subtle.digest("SHA-256",y.buffer),b="0x"+Buffer.from(w).toString("hex"),S=new Uint8Array(u.signature),{r:A,s:v}=t(S),{CredentialStorage:B}=await Promise.resolve().then(()=>(_e(),mn)),U=await new B().getCredentialById(a);if(!U||!U.publicKey)throw new g("No WebAuthn credential found for PRIMARY mode");let{base64UrlToArrayBuffer:F}=await Promise.resolve().then(()=>(ce(),Js)),$=F(U.publicKey),Be=await crypto.subtle.importKey("spki",$,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),vt=await crypto.subtle.exportKey("jwk",Be);if(!vt.x||!vt.y)throw new g("Invalid P-256 public key: missing x or y coordinates");let Rh="0x"+Buffer.from(F(vt.x)).toString("hex"),Dh="0x"+Buffer.from(F(vt.y)).toString("hex"),{deriveAddressFromP256PublicKey:Fh}=await Promise.resolve().then(()=>(Pt(),Sn)),Mh=await Fh(U.publicKey);return{signature:{r:A,s:v},messageHash:i,signedHash:b,address:Mh,publicKey:{qx:Rh,qy:Dh}}}catch(t){throw this.config.onError?.(t),new g("Failed to sign message with passkey",t)}}async sendTransaction(e,t){try{if(!this.currentUser)throw new g("Must be authenticated to send transaction");let n=t?.mode||ge,s=t?.tag||X,i=t?.origin||ue();if(n==="PRIMARY")throw t?.rpcUrl?new g("PRIMARY mode sendTransaction is not yet supported. Use signMessageWithPasskey() to obtain a P-256 signature and submit via a bundler manually."):new g("PRIMARY mode requires options.rpcUrl pointing to a bundler or sponsoring relayer. The P-256 address cannot pay gas directly without a deployed P-256-verifier contract via EIP-7702.");let o=n==="STRICT"?!0:t?.requireAuth||!1,a=await this.getMnemonicFromSession(o,n),c=await we(a,i,n,s),{Wallet:l,JsonRpcProvider:u}=await import("ethers"),d;if(c.privateKey)d=new l(c.privateKey);else{let{deriveWalletFromMnemonic:b}=await Promise.resolve().then(()=>(Te(),Ct)),{privateKey:S}=b(a,c.index);d=new l(S)}let h=t?.rpcUrl??(await this.getEndpoints(e.chainId))[0];if(!h)throw new g(`No RPC endpoint found for chainId ${e.chainId}. Pass options.rpcUrl.`);let m=new u(h);return{hash:(await d.connect(m).sendTransaction({to:e.to,value:e.value,data:e.data??"0x",chainId:e.chainId,gasLimit:e.gasLimit,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce})).hash,from:c.address,chainId:e.chainId,mode:c.mode,tag:c.tag,origin:c.origin}}catch(n){throw this.config.onError?.(n),new g("Failed to send transaction",n)}}async signAuthorization(e,t){try{if(!this.currentUser)throw new g("Must be authenticated to sign authorization");let{Wallet:n,Signature:s}=await import("ethers"),{hashEIP7702AuthorizationMessage:i,verifyEIP7702Authorization:o}=await Promise.resolve().then(()=>(Tn(),li)),a;if(e.privateKey)a=new n(e.privateKey);else{let w=await this.getMnemonicFromSession(t?.requireAuth);a=n.fromPhrase(w)}let c=BigInt(e.chainId||1),l=e.nonce||0n,u=i(c,e.contractAddress,l),d=a.signingKey.sign(u),h=s.from(d),m={chainId:c,address:e.contractAddress.toLowerCase(),nonce:l,yParity:h.yParity,r:h.r,s:h.s};if(!o(c,e.contractAddress,l,m,a.address))throw new g("Signature verification failed - this should not happen");return m}catch(n){throw this.config.onError?.(n),new g("Failed to sign authorization",n)}}async getEndpoints(e){return In(e)}async supportsEIP7702(e,t){return Wa(e,this.getEndpoints.bind(this),t)}getEIP1193Provider(e){let t=e?.chainId??1,n=this,s={},i=(a,...c)=>{(s[a]??[]).forEach(l=>l(...c))};return{async request({method:a,params:c}){switch(a){case"eth_accounts":case"eth_requestAccounts":return[await n.getAddress(e?.mode??"STANDARD",e?.tag??"MAIN")];case"eth_chainId":return"0x"+t.toString(16);case"eth_sendTransaction":{let l=(c??[])[0]??{};if(!l.chainId&&!t)throw new g("eth_sendTransaction: chainId is required");let u=l.chainId?parseInt(l.chainId,16):t;return(await n.sendTransaction({to:l.to,value:l.value!==void 0?BigInt(l.value):void 0,data:l.data??"0x",chainId:u,gasLimit:l.gas!==void 0?BigInt(l.gas):void 0,maxFeePerGas:l.maxFeePerGas!==void 0?BigInt(l.maxFeePerGas):void 0,maxPriorityFeePerGas:l.maxPriorityFeePerGas!==void 0?BigInt(l.maxPriorityFeePerGas):void 0,nonce:l.nonce!==void 0?parseInt(l.nonce,16):void 0},{mode:e?.mode,tag:e?.tag,rpcUrl:e?.rpcUrl})).hash}case"personal_sign":{let[l]=c??[],u=ll(l)?ul(l):l;return(await n.signMessage(u,{mode:e?.mode,tag:e?.tag,signingMethod:"EIP191"})).signature}case"eth_sign":{let[,l]=c??[],u=ll(l)?ul(l):l;return(await n.signMessage(u,{mode:e?.mode,tag:e?.tag,signingMethod:"EIP191"})).signature}case"eth_signTypedData_v4":{let[,l]=c??[],u=typeof l=="string"?JSON.parse(l):l,{domain:d,types:h,message:m,primaryType:y}=u,w={...h};return delete w.EIP712Domain,(await n.signMessage(JSON.stringify(m),{mode:e?.mode,tag:e?.tag,signingMethod:"EIP712",eip712Domain:d,eip712Types:w,eip712PrimaryType:y})).signature}case"wallet_switchEthereumChain":{let l=parseInt((c??[])[0]?.chainId??"0x1",16);return t=l,i("chainChanged","0x"+l.toString(16)),null}default:throw new g(`w3pk EIP-1193: unsupported method "${a}"`)}},on(a,c){s[a]||(s[a]=[]),s[a].push(c)},removeListener(a,c){s[a]&&(s[a]=s[a].filter(l=>l!==c))}}}async requestExternalWalletDelegation(e){if(!this.currentUser)throw new g("Must be authenticated to get w3pk delegation address. Call login() or register() first.");let{requestExternalWalletAuthorization:t,getDefaultProvider:n}=await Promise.resolve().then(()=>(ui(),za)),s=e?.provider||n();if(!s)throw new g("No external wallet provider found. Please install MetaMask, Rabby, or similar wallet.");let i=this.currentUser.ethereumAddress;return t(s,{delegateToAddress:i,chainId:e?.chainId,nonce:e?.nonce,accountIndex:e?.accountIndex})}get zk(){return new Proxy({},{get:(e,t)=>async(...n)=>(await this.loadZKModule())[t](...n)})}async getBackupStatus(){if(!this.currentUser)throw new g("Must be authenticated to check backup status");let{BackupManager:e}=await Promise.resolve().then(()=>(Fe(),De));return new e().getBackupStatus(this.currentUser.ethereumAddress)}async confirmRecoveryPhraseBackup(){if(!this.currentUser)throw new g("Must be authenticated to confirm a backup");let{BackupManager:e}=await Promise.resolve().then(()=>(Fe(),De)),{deriveAddressChecksum:t}=await Promise.resolve().then(()=>(Ke(),hi)),{ethereumAddress:n}=this.currentUser;await new e().confirmRecoveryPhraseBackup(n,await t(n))}async createBackupFile(e="password",t){if(!this.currentUser)throw new g("Must be authenticated to create backup");let n=await this.getMnemonicFromSession(!0),{BackupFileManager:s}=await Promise.resolve().then(()=>(he(),be)),{BackupStorage:i}=await Promise.resolve().then(()=>(Un(),Ha)),o=new s,a=new i,c,l;if(e==="password"){if(!t)throw new g("Password required for password-based backup");l=(await o.createPasswordBackup(n,this.currentUser.ethereumAddress,t,await this.backupCredential())).backupFile,c=o.createDownloadableBackup(l)}else if(e==="passkey"){let u=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!u)throw new g("No wallet data found");let h=await new D().getCredentialById(u.credentialId);if(!h)throw new g("Credential not found");l=(await o.createPasskeyBackup(n,this.currentUser.ethereumAddress,h.id,h.publicKey)).backupFile,c=o.createDownloadableBackup(l)}else if(e==="hybrid"){if(!t)throw new g("Password required for hybrid backup");let u=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!u)throw new g("No wallet data found");let h=await new D().getCredentialById(u.credentialId);if(!h)throw new g("Credential not found");l=(await o.createHybridBackup(n,this.currentUser.ethereumAddress,t,h.id,h.publicKey)).backupFile,c=o.createDownloadableBackup(l)}else throw new g(`Unknown encryption type: ${e}`);return await a.storeBackupMetadata({id:crypto.randomUUID(),ethereumAddress:this.currentUser.ethereumAddress,method:"file",createdAt:new Date().toISOString(),addressChecksum:l.addressChecksum}),c}async backupCredential(){let e=await new D().getCredentialById(this.currentUser.credentialId);return e?{id:e.id,publicKey:e.publicKey}:void 0}async setupSocialRecovery(e,t,n){if(!this.currentUser)throw new g("Must be authenticated to set up social recovery");let s=await this.getMnemonicFromSession(!0),{BackupFileManager:i}=await Promise.resolve().then(()=>(he(),be)),o=new i,a;if(n)a=(await o.createPasswordBackup(s,this.currentUser.ethereumAddress,n,await this.backupCredential())).backupFile;else{let d=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!d)throw new g("No wallet data found");let m=await new D().getCredentialById(d.credentialId);if(!m)throw new g("Credential not found");a=(await o.createPasskeyBackup(s,this.currentUser.ethereumAddress,m.id,m.publicKey)).backupFile}let{SocialRecovery:c}=await Promise.resolve().then(()=>(ss(),ns));return{guardianShares:(await new c().splitAmongGuardians(a,e,t)).guardianShares,setupComplete:!0}}async generateGuardianInvite(e,t){let{SocialRecovery:n}=await Promise.resolve().then(()=>(ss(),ns)),s=new n,i=await s.createGuardianInvitation(e,t),o=s.createShareDownload(e);return{qrCodeDataURL:i.qrCodeDataURL,shareDocument:i.shareDocument,downloadBlob:o.blob,filename:o.filename}}async recoverFromGuardians(e,t){let{SocialRecovery:n}=await Promise.resolve().then(()=>(ss(),ns)),{BackupFileManager:s}=await Promise.resolve().then(()=>(he(),be)),{BackupManager:i}=await Promise.resolve().then(()=>(Fe(),De)),o=new n,a=new s,c=new i,l=e.map(h=>typeof h=="string"?o.parseGuardianShare(h):h),u=await o.recoverFromShares(l),d;if(u.encryptionMethod==="password"){if(!t)throw new g("Password required to decrypt password-protected backup");d=await a.restoreWithPassword(u,t)}else throw new g("Passkey-encrypted backups not supported for guardian recovery. Use password-protected backups.");return c.markBackupVerified(d.ethereumAddress),d}async restoreFromBackupFile(e,t){let{BackupFileManager:n}=await Promise.resolve().then(()=>(he(),be)),{BackupManager:s}=await Promise.resolve().then(()=>(Fe(),De)),i=new n,o=new s,a=await i.parseBackupFile(e),c,l;if(a.encryptionMethod==="password"){if(!t)throw new g("Password required to restore password-encrypted backup");let u=await i.restoreWithPassword(a,t);c=u.mnemonic,l=u.ethereumAddress}else if(a.encryptionMethod==="passkey"){if(!this.currentUser)throw new g("Must be logged in with passkey to restore passkey-encrypted backup. Call login() first.");let h=(await new D().getAllCredentials()).find(y=>y.ethereumAddress.toLowerCase()===this.currentUser.ethereumAddress.toLowerCase());if(!h)throw new g("Credential not found for current user");let m=await i.restoreWithExistingPasskey(a,h.id,h.publicKey);c=m.mnemonic,l=m.ethereumAddress}else if(a.encryptionMethod==="hybrid"){if(!t)throw new g("Password required to restore hybrid backup");if(!this.currentUser)throw new g("Must be logged in with passkey to restore hybrid backup. Call login() first.");let h=(await new D().getAllCredentials()).find(y=>y.ethereumAddress.toLowerCase()===this.currentUser.ethereumAddress.toLowerCase());if(!h)throw new g("Credential not found for current user");let m=await i.restoreWithHybrid(a,t,h.id,h.publicKey);c=m.mnemonic,l=m.ethereumAddress}else throw new g(`Unknown encryption method: ${a.encryptionMethod}`);if(o.markBackupVerified(l),this.currentWallet={address:l,mnemonic:c},this.currentUser){let u=new D,h=(await u.getAllCredentials()).find(m=>m.ethereumAddress.toLowerCase()===this.currentUser.ethereumAddress.toLowerCase());if(h){let m=this.currentUser.ethereumAddress;m.toLowerCase()!==l.toLowerCase()&&await this.walletStorage.delete(m),await u.updateCredentialAddress(h.id,l);let y=await(await Promise.resolve().then(()=>(se(),fr))).deriveEncryptionKeyFromWebAuthn(h.id,h.publicKey),w=await(await Promise.resolve().then(()=>(se(),fr))).encryptData(c,y);await this.walletStorage.store({ethereumAddress:l,encryptedMnemonic:w,credentialId:h.id,createdAt:new Date().toISOString()}),this.currentUser={...this.currentUser,ethereumAddress:l},await this.sessionManager.startSession(c,h.id,l,void 0,"STANDARD"),this.requestPersistentStorage(),this.config.onAuthStateChanged?.(!0,this.currentUser)}}return{mnemonic:c,ethereumAddress:l}}async syncWalletWithPasskey(e,t){let{BackupFileManager:n}=await Promise.resolve().then(()=>(he(),be)),{BackupManager:s}=await Promise.resolve().then(()=>(Fe(),De)),{promptPasskeySelection:i}=await Promise.resolve().then(()=>($i(),Qc)),o=new n,a=new s,c=await o.parseBackupFile(e);if(c.encryptionMethod==="prf")return this.restorePrfBackup(c);let l=await i(),u=l.credentialId,d=l.publicKey;if(!d){if(c.encryptionMethod!=="password")throw new ye("PASSKEY_BACKUP",u);if(!c.credential)throw new ye("NO_CREDENTIAL",u);if(c.credential.id!==u)throw new ye("CREDENTIAL_MISMATCH",u);if(d=c.credential.publicKey,!await yn(l.assertion,d))throw new ye("PUBLIC_KEY_MISMATCH",u)}let h,m;if(c.encryptionMethod==="password"){if(!t)throw new g("Password required to restore password-encrypted backup");let y=await o.restoreWithPassword(c,t);h=y.mnemonic,m=y.ethereumAddress}else if(c.encryptionMethod==="passkey"){let y=await o.restoreWithExistingPasskey(c,u,d);h=y.mnemonic,m=y.ethereumAddress}else if(c.encryptionMethod==="hybrid"){if(!t)throw new g("Password required to restore hybrid backup");let y=await o.restoreWithHybrid(c,t,u,d);h=y.mnemonic,m=y.ethereumAddress}else throw new g(`Unknown encryption method: ${c.encryptionMethod}`);return a.markBackupVerified(m),await this.bootstrapCredential({id:u,publicKey:d,username:l.username??m},h,m),{mnemonic:h,ethereumAddress:m}}async restorePrfBackup(e){let{DeviceSyncManager:t}=await Promise.resolve().then(()=>(Nr(),is)),{BackupManager:n}=await Promise.resolve().then(()=>(Fe(),De)),s=e.credential,o=(await new D().getCredentialById(s.id))?.publicKey??s.publicKey,{mnemonic:a,ethereumAddress:c}=await new t().importFromSync(e,o);return new n().markBackupVerified(c),await this.bootstrapCredential({id:s.id,publicKey:o,username:e.username??c},a,c),{mnemonic:a,ethereumAddress:c}}async bootstrapCredential(e,t,n){let s=new D,i=await s.getCredentialById(e.id);if(i)i.ethereumAddress.toLowerCase()!==n.toLowerCase()&&await s.updateCredentialAddress(e.id,n);else{let c=new Date().toISOString();await s.saveCredential({id:e.id,publicKey:e.publicKey,username:e.username,ethereumAddress:n,createdAt:c,lastUsed:c})}let o=await le(e.id,e.publicKey),a=await J(t,o);await this.walletStorage.store({ethereumAddress:n,encryptedMnemonic:a,credentialId:e.id,createdAt:new Date().toISOString()}),this.currentUser={username:i?.username??e.username,ethereumAddress:n,credentialId:e.id},await this.sessionManager.startSession(t,e.id,n,void 0,"STANDARD"),this.requestPersistentStorage(),this.config.onAuthStateChanged?.(!0,this.currentUser)}async registerWithBackupFile(e,t,n){let{BackupFileManager:s}=await Promise.resolve().then(()=>(he(),be)),{BackupManager:i}=await Promise.resolve().then(()=>(Fe(),De)),o=new s,a=new i,c=await o.parseBackupFile(e);if(c.encryptionMethod!=="password")throw new g("Can only register with password-encrypted backups. Use restoreFromBackupFile() for passkey-encrypted backups.");let{mnemonic:l,ethereumAddress:u}=await o.restoreWithPassword(c,t),{Wallet:d}=await import("ethers");if(d.fromPhrase(l).address.toLowerCase()!==u.toLowerCase())throw new g("Backup verification failed: address mismatch");return a.markBackupVerified(u),this.currentWallet={address:u,mnemonic:l},this.register({username:n})}async getSyncStatus(){let{DeviceSyncManager:e}=await Promise.resolve().then(()=>(Nr(),is));return new e().getSyncInfo()}async exportForSync(e){if(!this.currentUser)throw new g("Must be authenticated to export for sync");let t=await this.getMnemonicFromSession(),n=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!n)throw new g("No wallet data found");let i=await new D().getCredentialById(n.credentialId);if(!i)throw new g("Credential not found");let{DeviceSyncManager:o}=await Promise.resolve().then(()=>(Nr(),is)),a=new o,{backupFile:c,blob:l}=await a.exportForSync(t,this.currentUser.ethereumAddress,{id:i.id,publicKey:i.publicKey},this.currentUser.username,e),u=`w3pk-sync-${this.currentUser.ethereumAddress.substring(0,8)}.json`,d;try{d=await a.generateSyncQR(c)}catch(h){console.warn("QR code generation failed:",h)}return{blob:l,filename:u,qrCode:d}}async importFromSync(e){let{BackupFileManager:t}=await Promise.resolve().then(()=>(he(),be)),n=await new t().parseBackupFile(e);if(n.encryptionMethod!=="prf")throw new g("importFromSync() takes PRF backups from exportForSync(). Use syncWalletWithPasskey() for other backups.");if(this.currentUser&&this.currentUser.credentialId!==n.credential.id)throw new ye("CREDENTIAL_MISMATCH",this.currentUser.credentialId);let{ethereumAddress:s}=await this.restorePrfBackup(n);return{ethereumAddress:s,success:!0}}async detectSyncCapabilities(){let{PlatformDetector:e}=await Promise.resolve().then(()=>(nl(),rl));return new e().detectSyncCapabilities()}async simulateRecoveryScenario(e){if(!this.currentUser)throw new g("Must be authenticated to run recovery simulation");let t=await this.getBackupStatus(),{RecoverySimulator:n}=await Promise.resolve().then(()=>(Lr(),us));return new n().simulateScenario(e,t)}async runRecoveryTest(){if(!this.currentUser)throw new g("Must be authenticated to run recovery test");let e=await this.getBackupStatus(),{RecoverySimulator:t}=await Promise.resolve().then(()=>(Lr(),us));return new t().runInteractiveTest(e)}async getEducation(e){let{getExplainer:t}=await Promise.resolve().then(()=>(Lr(),us)),n=t(e);if(!n)throw new g(`Unknown education topic: ${e}`);return n}hasActiveSession(){return this.sessionManager.isActive()}getSessionRemainingTime(){return this.sessionManager.getRemainingTime()}extendSession(){try{this.sessionManager.extendSession()}catch(e){throw new g("Cannot extend session",e)}}async clearSession(){await this.sessionManager.clearSession()}setSessionDuration(e){this.sessionManager.setSessionDuration(e)}setPersistentSessionDuration(e){this.sessionManager.setPersistentSessionDuration(e)}async derivePrfSecret(e){try{return await ii(st(ue()),e,this.currentUser?.credentialId)}catch(t){throw this.config.onError?.(t),t}}async deriveMLKemPublicKey(e){if(!this.currentUser)throw new g("Must be authenticated to derive ML-KEM public key");let{deriveMLKemKeypair:t}=await Promise.resolve().then(()=>(Kr(),ps)),{Wallet:n}=await import("ethers"),s=e?.mode||"STANDARD",i=e?.tag||X,o=e?.origin||ue(),a=e?.context||"mlkem-v1",c=s==="STRICT"?!0:e?.requireAuth||!1;if(s==="PRIMARY")throw new g("ML-KEM encryption is not supported in PRIMARY mode. PRIMARY mode uses P-256 WebAuthn keys which cannot derive ML-KEM keypairs. Use STANDARD, STRICT, or YOLO mode instead.");let l=await this.getMnemonicFromSession(c,s),u=await we(l,o,s,i),d;if(u.privateKey)d=u.privateKey;else{let{deriveWalletFromMnemonic:m}=await Promise.resolve().then(()=>(Te(),Ct));d=m(l,u.index).privateKey}let h=await t(d,a);return typeof Buffer<"u"?Buffer.from(h.publicKey).toString("base64"):btoa(String.fromCharCode(...Array.from(h.publicKey)))}async mlkemEncrypt(e,t,n){if(!this.currentUser)throw new g("Must be authenticated to encrypt data");let{mlkemEncryptWithKey:s}=await Promise.resolve().then(()=>(Kr(),ps)),i=n?.mode||"STANDARD",o=n?.tag||X,a=n?.origin||ue(),c=n?.context||"mlkem-v1",l=i==="STRICT"?!0:n?.requireAuth||!1;if(i==="PRIMARY")throw new g("ML-KEM encryption is not supported in PRIMARY mode. Use STANDARD, STRICT, or YOLO mode instead.");let u=await this.getMnemonicFromSession(l,i),d=await we(u,a,i,o),h;if(d.privateKey)h=d.privateKey;else{let{deriveWalletFromMnemonic:m}=await Promise.resolve().then(()=>(Te(),Ct));h=m(u,d.index).privateKey}return await s(e,h,t,c)}async mlkemDecrypt(e,t){if(!this.currentUser)throw new g("Must be authenticated to decrypt data");let{mlkemDecryptWithKey:n}=await Promise.resolve().then(()=>(Kr(),ps)),s=t?.mode||"STANDARD",i=t?.tag||X,o=t?.origin||ue(),a=t?.context||"mlkem-v1",c=s==="STRICT"?!0:t?.requireAuth||!1;if(s==="PRIMARY")throw new g("ML-KEM encryption is not supported in PRIMARY mode. Use STANDARD, STRICT, or YOLO mode instead.");let l=await this.getMnemonicFromSession(c,s),u=await we(l,o,s,i),d;if(u.privateKey)d=u.privateKey;else{let{deriveWalletFromMnemonic:h}=await Promise.resolve().then(()=>(Te(),Ct));d=h(l,u.index).privateKey}return await n(e,d,a)}};W();$i();Pt();Lr();async function tg(r,e="build"){let{importer:t}=await Promise.resolve().then(()=>(ia(),Zd)),{MemoryBlockstore:n}=await Promise.resolve().then(()=>(xh(),Ah)),s=new n,o=t(async function*(){yield{path:e,content:r}}(),s,{cidVersion:1,rawLeaves:!0,wrapWithDirectory:!1});for await(let a of o)return a.cid.toString();throw new Error("Failed to generate CID")}async function rg(r){let e=["index.js","index.mjs","index.d.ts"],t=[],n=0;for(let o of e){let a=`${r}/${o}`,c=await fetch(a);if(!c.ok)throw new Error(`Failed to fetch ${o}: ${c.statusText}`);let l=await c.arrayBuffer(),u=new Uint8Array(l);t.push(u),n+=u.length}let s=new Uint8Array(n),i=0;for(let o of t)s.set(o,i),i+=o.length;return s}async function wa(r){let e=await rg(r);return tg(e)}function ba(){try{return vh().version}catch{throw new Error("Failed to read package version")}}async function Sa(){let r=ba();return wa(`https://unpkg.com/w3pk@${r}/dist`)}async function kh(r){return await Sa()===r}ce();Ki();Te();function Eh(r=11){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=new Uint8Array(r);return crypto.getRandomValues(t),Array.from(t).map(n=>e[n%e.length]).join("")}function Ch(r){if(!r.domain||!r.address||!r.uri||!r.version||r.chainId===void 0||!r.nonce||!r.issuedAt)throw new Error("Missing required SIWE message fields");if(r.version!=="1")throw new Error('SIWE version must be "1"');if(r.nonce.length<8||!/^[a-zA-Z0-9]+$/.test(r.nonce))throw new Error("Nonce must be at least 8 alphanumeric characters");if(r.statement&&r.statement.includes(`
961
- `))throw new Error("Statement cannot contain newlines");let e=`${r.domain} wants you to sign in with your Ethereum account:
962
- `;if(e+=`${r.address}
963
- `,e+=`
964
- `,r.statement&&(e+=`${r.statement}
965
- `),e+=`
966
- `,e+=`URI: ${r.uri}
967
- `,e+=`Version: ${r.version}
968
- `,e+=`Chain ID: ${r.chainId}
969
- `,e+=`Nonce: ${r.nonce}
970
- `,e+=`Issued At: ${r.issuedAt}`,r.expirationTime&&(e+=`
971
- Expiration Time: ${r.expirationTime}`),r.notBefore&&(e+=`
972
- Not Before: ${r.notBefore}`),r.requestId&&(e+=`
973
- Request ID: ${r.requestId}`),r.resources&&r.resources.length>0){e+=`
974
- Resources:`;for(let t of r.resources)e+=`
975
- - ${t}`}return e}function Ws(r){let e=r.split(`
976
- `);if(e.length<7)throw new Error("Invalid SIWE message: too few lines");let n=e[0].match(/^(.+) wants you to sign in with your Ethereum account:$/);if(!n)throw new Error("Invalid SIWE message: malformed domain line");let s=n[1],i=e[1];if(!i.match(/^0x[a-fA-F0-9]{40}$/))throw new Error("Invalid SIWE message: malformed address");if(e[2]!=="")throw new Error("Invalid SIWE message: expected empty line after address");let o,a="",c="",l=0,u="",d="",h,m,y,w=[],b=3;for(e[b]&&!e[b].startsWith("URI: ")&&(o=e[b],b++,e[b]===""&&b++);b<e.length;b++){let S=e[b];if(S.startsWith("URI: "))a=S.substring(5);else if(S.startsWith("Version: "))c=S.substring(9);else if(S.startsWith("Chain ID: "))l=parseInt(S.substring(10),10);else if(S.startsWith("Nonce: "))u=S.substring(7);else if(S.startsWith("Issued At: "))d=S.substring(11);else if(S.startsWith("Expiration Time: "))h=S.substring(17);else if(S.startsWith("Not Before: "))m=S.substring(12);else if(S.startsWith("Request ID: "))y=S.substring(12);else if(S.startsWith("Resources:")){for(b++;b<e.length&&e[b].startsWith("- ");)w.push(e[b].substring(2)),b++;break}}if(!a||!c||!l||!u||!d)throw new Error("Invalid SIWE message: missing required fields");return{domain:s,address:i,statement:o,uri:a,version:c,chainId:l,nonce:u,issuedAt:d,expirationTime:h,notBefore:m,requestId:y,resources:w.length>0?w:void 0}}function Ph(r,e){let t=[];try{let n=typeof r=="string"?Ws(r):r;return e?.domain&&n.domain!==e.domain&&t.push(`Domain mismatch: expected "${e.domain}", got "${n.domain}"`),e?.chainId!==void 0&&n.chainId!==e.chainId&&t.push(`Chain ID mismatch: expected ${e.chainId}, got ${n.chainId}`),n.version!=="1"&&t.push(`Invalid version: must be "1", got "${n.version}"`),(n.nonce.length<8||!/^[a-zA-Z0-9]+$/.test(n.nonce))&&t.push("Nonce must be at least 8 alphanumeric characters"),e?.checkExpiration&&n.expirationTime&&new Date(n.expirationTime)<new Date&&t.push("Message has expired"),e?.checkNotBefore&&n.notBefore&&new Date(n.notBefore)>new Date&&t.push("Message is not yet valid (not-before constraint)"),{valid:t.length===0,errors:t,parsed:n}}catch(n){return t.push(n.message),{valid:!1,errors:t}}}async function Ih(r,e,t){try{let{verifyMessage:n}=await import("ethers"),s=n(r,e),i=Ws(r);return s.toLowerCase()!==i.address.toLowerCase()?{valid:!1,error:"Signature does not match address in message"}:t&&s.toLowerCase()!==t.toLowerCase()?{valid:!1,error:"Signature does not match expected address"}:{valid:!0,address:s}}catch(n){return{valid:!1,error:n.message}}}Li();ts();function ng(r,e=3e4){let t=["signMessage","signTypedData","sign(","signature","sendTransaction","transaction","eth_sign","Contract(","ethers.Contract","new Contract","w3pk","Web3Passkey","useW3PK","wallet","signer","provider","authorization","delegation","EIP7702"],n=r.split(`
977
- `),s=[],i=500;for(let a=0;a<n.length&&s.length<i;a++){let l=n[a].toLowerCase();if(t.some(u=>l.includes(u.toLowerCase()))){let u=Math.max(0,a-2),d=Math.min(n.length,a+3);for(let h=u;h<d;h++)s.includes(n[h])||s.push(n[h])}}let o=s.join(`
978
- `);return o.length>e?o.substring(0,e)+`
979
-
980
- // ... (truncated)`:o||"// No transaction code found"}async function sg(r,e=100){let t=`# Application Code Analysis
981
-
982
- `;t+=`**App URL:** ${r}
983
-
984
- `,t+=`**Note:** Only transaction-related code snippets shown
985
-
986
- `,t+=`---
987
-
988
- `;let s=Array.from(document.querySelectorAll("script[src]")).map(c=>c.src).filter(c=>c&&!c.includes("node_modules")&&!c.includes("chrome-extension"));t+=`## JavaScript Files (${s.length})
989
-
990
- `;let i=0,o=0,a=e*1024;for(let c of s.slice(0,15)){if(o>=e){console.warn(`[W3PK Inspect] Reached total size limit of ${e} KB - stopping collection`),t+=`
991
- **Note:** Collection stopped - reached ${e} KB limit
992
- `;break}try{let l=await fetch(c);if(!l.ok)continue;let u=await l.text(),d=ng(u);if(d&&!d.includes("No transaction code found")){let h=new Blob([d]).size/1024;if(o+h>e){console.warn(`[W3PK Inspect] Skipping ${new URL(c).pathname} - would exceed total size limit`);break}t+=`### \`${new URL(c).pathname}\`
993
-
994
- `,t+="```javascript\n",t+=d,t+=`
995
- \`\`\`
996
-
997
- ---
998
-
999
- `,i++,o+=h}}catch{}}return i===0&&(t+=`No transaction-related code found in JavaScript files.
1000
- `),t}async function Aa(r={}){if(typeof window>"u")throw new Error("Browser inspect() can only be called in browser environments. For Node.js, use the CLI or Node.js API.");let{appUrl:e=window.location.origin,rukhUrl:t="https://rukh.w3hc.org",context:n="w3pk",model:s="anthropic",focusMode:i="transactions",maxTotalSizeKB:o=100}=r;console.log("[W3PK Inspect] Starting inspection of",e),console.log("[W3PK Inspect] Focus mode:",i),console.log("[W3PK Inspect] Max total size:",o,"KB");let a=await sg(e,o);console.log("[W3PK Inspect] Collected source code, sending to Rukh API...");let c="Analyze this web application and provide a security report listing all transaction and signing methods.",l=new FormData;l.append("message",c),l.append("model",s),l.append("context",n);let u=new Blob([a],{type:"text/markdown"});l.append("file",u,"app-source.md");let d=await fetch(`${t}/ask`,{method:"POST",body:l});if(!d.ok){let b=await d.text();throw new Error(`Rukh API error: ${d.status} - ${b}`)}let h=await d.json(),m=h.output||h.response||h.message||JSON.stringify(h);console.log("[W3PK Inspect] Analysis complete!");let w=Array.from(document.querySelectorAll("script[src]")).map(b=>new URL(b.src).pathname).filter(b=>b&&!b.includes("node_modules"));return{report:m,analyzedFiles:w,appUrl:e}}async function Bh(r){console.log(`\u{1F50D} W3PK Security Inspection Starting...
1001
- `);try{let e=await Aa(r);console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),console.log("\u{1F4CB} SECURITY REPORT"),console.log(`\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501
1002
- `),console.log(e.report),console.log(`
1003
- \u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`),console.log(`\u2705 Analyzed ${e.analyzedFiles.length} files from ${e.appUrl}`),console.log("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501")}catch(e){throw console.error("\u274C Inspection failed:",e),e}}Kr();function Th(r={}){return new _t(r)}var ig=Th;
1668
+ `}};function bf(r){return Fa[r]||null}function kf(){return Object.keys(Fa)}function xf(r){let e=r.toLowerCase();return Object.values(Fa).filter(t=>t.title.toLowerCase().includes(e)||t.content.toLowerCase().includes(e))}yr();var Sf="0.11.1";Ba();async function sw(r){let e=["index.js","index.mjs","index.d.ts"],t=[],n=0;for(let o of e){let a=`${r}/${o}`,c=await fetch(a);if(!c.ok)throw new Error(`Failed to fetch ${o}: ${c.statusText}`);let u=await c.arrayBuffer(),l=new Uint8Array(u);t.push(l),n+=l.length}let i=new Uint8Array(n),s=0;for(let o of t)i.set(o,s),s+=o.length;return i}async function Ma(r){let e=await sw(r);return Wi(e)}function Ua(){return Sf}async function _a(){return Ma(`https://unpkg.com/w3pk@${Ua()}/dist`)}async function Af(r){return await _a()===r}pe();Bn();Ee();$n();Lt();function vf(r={}){return new dr(r)}var ow=vf;
1004
1669
  //# sourceMappingURL=index.js.map