w3pk 0.10.1 → 0.10.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,11 +1,11 @@
1
- var Qd=Object.create;var Gr=Object.defineProperty;var Zd=Object.getOwnPropertyDescriptor;var Xd=Object.getOwnPropertyNames;var eh=Object.getPrototypeOf,th=Object.prototype.hasOwnProperty;var rh=(r,e,t)=>e in r?Gr(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var p=(r,e)=>()=>(r&&(e=r(r=0)),e);var P=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),E=(r,e)=>{for(var t in e)Gr(r,t,{get:e[t],enumerable:!0})},nh=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Xd(e))!th.call(r,s)&&s!==t&&Gr(r,s,{get:()=>e[s],enumerable:!(n=Zd(e,s))||n.enumerable});return r};var er=(r,e,t)=>(t=r!=null?Qd(eh(r)):{},nh(e||!r||!r.__esModule?Gr(t,"default",{value:r,enumerable:!0}):t,r));var f=(r,e,t)=>rh(r,typeof e!="symbol"?e+"":e,t);var V,K,tr,w,M,B,ws,G=p(()=>{"use strict";V=class extends Error{constructor(t,n,s){super(t);this.code=n;this.originalError=s;this.name="Web3PasskeyError"}},K=class extends V{constructor(e,t){super(e,"AUTHENTICATION_ERROR",t),this.name="AuthenticationError"}},tr=class extends V{constructor(e,t){super(e,"REGISTRATION_ERROR",t),this.name="RegistrationError"}},w=class extends V{constructor(e,t){super(e,"WALLET_ERROR",t),this.name="WalletError"}},M=class extends V{constructor(e,t){super(e,"CRYPTO_ERROR",t),this.name="CryptoError"}},B=class extends V{constructor(e,t){super(e,"STORAGE_ERROR",t),this.name="StorageError"}},ws=class extends V{constructor(t,n,s){super(t,"API_ERROR",s);this.statusCode=n;this.name="ApiError"}}});var As={};E(As,{arrayBufferToBase64Url:()=>he,base64ToArrayBuffer:()=>Oo,base64UrlDecode:()=>Wo,base64UrlToArrayBuffer:()=>L,safeAtob:()=>yt,safeBtoa:()=>zo});function L(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 he(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 Oo(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 yt(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 zo(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 Wo(r){return L(r)}var fe=p(()=>{"use strict"});var Me={};E(Me,{decryptData:()=>ie,deriveEncryptionKey:()=>oh,deriveEncryptionKeyAuto:()=>Y,deriveEncryptionKeyFromWebAuthn:()=>$o,encryptData:()=>se,generateChallenge:()=>Fe,generateSalt:()=>xs,hashCredentialId:()=>wt,hashPublicKey:()=>vs});async function $o(r,e){try{if(r.byteLength!==32)throw new Error("PRF output must be 32 bytes");if(e.byteLength!==32)throw new Error("Salt must be 32 bytes");let t=await crypto.subtle.importKey("raw",r,{name:"PBKDF2"},!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:e,iterations:21e4,hash:"SHA-256"},t,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}catch(t){throw new M("Failed to derive encryption key from WebAuthn PRF",t)}}function xs(){return crypto.getRandomValues(new Uint8Array(32))}async function Y(r,e,t,n){if(r&&e)return $o(r,e);console.warn("\u26A0\uFE0F SECURITY WARNING: Using insecure legacy encryption. Wallet is vulnerable to offline decryption attacks. Migrate to PRF-based encryption immediately.");try{let s=n?`w3pk-v4:${t}:${n}`:`w3pk-v4:${t}`,i=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(s)),o=await crypto.subtle.importKey("raw",i,{name:"PBKDF2"},!1,["deriveKey"]),a=await crypto.subtle.digest("SHA-256",new TextEncoder().encode("w3pk-salt-v4"));return crypto.subtle.deriveKey({name:"PBKDF2",salt:new Uint8Array(a),iterations:21e4,hash:"SHA-256"},o,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}catch(s){throw new M("Failed to derive encryption key from WebAuthn",s)}}async function oh(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 M("Failed to derive encryption key",t)}}function Fe(){let r=new Uint8Array(32);return crypto.getRandomValues(r),he(r)}async function se(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 M("Failed to encrypt data",t)}}async function ie(r,e){try{if(!r||r.length<16)throw new Error("Invalid encrypted data: too small");let t=yt(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 M(`Data decryption failed: ${t instanceof Error?t.message:"Unknown error"}`,t)}}async function wt(r){try{let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`w3pk-cred-id:${r}`));return he(e)}catch(e){throw new M("Failed to hash credential ID",e)}}async function vs(r){try{let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r));return he(e)}catch(e){throw new M("Failed to hash public key",e)}}var W=p(()=>{"use strict";G();fe()});var Jr={};E(Jr,{CredentialStorage:()=>R});async function qo(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 Yr,jr,R,Ue=p(()=>{"use strict";G();W();Yr="w3pk_credential_",jr="w3pk_credential_index";R=class{constructor(e){if(e)this.storage=e;else if(typeof window<"u"&&window.localStorage)this.storage=window.localStorage;else throw new B("localStorage is not available")}async saveCredential(e){try{let t=await qo(e.id),n=await wt(e.id),s={id:n,encryptedUsername:await se(e.username,t),encryptedAddress:await se(e.ethereumAddress,t),publicKey:e.publicKey,publicKeyFingerprint:await vs(e.publicKey),createdAt:e.createdAt,lastUsed:e.lastUsed},i=`${Yr}${n}`;this.storage.setItem(i,JSON.stringify(s)),await this.addToIndex(e.id)}catch(t){throw new B("Failed to save credential",t)}}async getCredentialById(e){try{let t=await wt(e),n=`${Yr}${t}`,s=this.storage.getItem(n);if(!s)return null;let i=JSON.parse(s),o=await qo(e);return{id:e,publicKey:i.publicKey,username:await ie(i.encryptedUsername,o),ethereumAddress:await ie(i.encryptedAddress,o),createdAt:i.createdAt,lastUsed:i.lastUsed}}catch(t){throw new B("Failed to retrieve credential",t)}}async getCredentialByUsername(e){try{return(await this.getAllCredentials()).find(n=>n.username===e)||null}catch(t){throw new B("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 B("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 B("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 B("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 B("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 B("Failed to update credential address",n)}}async deleteCredential(e){try{let t=await wt(e),n=`${Yr}${t}`;this.storage.removeItem(n),await this.removeFromIndex(e)}catch(t){throw new B("Failed to delete credential",t)}}async clearAll(){try{let e=await this.getIndex();(await Promise.all(e.map(async n=>await wt(n)))).forEach(n=>{let s=`${Yr}${n}`;this.storage.removeItem(s)}),this.storage.removeItem(jr)}catch(e){throw new B("Failed to clear credentials",e)}}async getIndex(){try{let e=this.storage.getItem(jr);return e?JSON.parse(e):[]}catch{return[]}}async addToIndex(e){let t=await this.getIndex();t.includes(e)||(t.push(e),this.storage.setItem(jr,JSON.stringify(t)))}async removeFromIndex(e){let n=(await this.getIndex()).filter(s=>s!==e);this.storage.setItem(jr,JSON.stringify(n))}}});var bt={};E(bt,{createWalletFromMnemonic:()=>Go,deriveWalletFromMnemonic:()=>tn,generateBIP39Wallet:()=>en});import{ethers as Xr}from"ethers";function en(){try{let r=Xr.Wallet.createRandom().mnemonic;if(!r)throw new Error("Failed to generate mnemonic");let e=r.phrase;return{address:Xr.HDNodeWallet.fromPhrase(e,void 0,"m/44'/60'/0'/0/0").address,mnemonic:e}}catch(r){throw new w("Wallet generation failed",r)}}function Go(r){try{if(!r||r.trim().split(/\s+/).length<12)throw new Error("Invalid mnemonic: must be at least 12 words");return Xr.HDNodeWallet.fromPhrase(r.trim(),void 0,"m/44'/60'/0'/0/0")}catch(e){throw new w(`Wallet creation failed: ${e instanceof Error?e.message:"Invalid mnemonic"}`,e)}}function tn(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=Xr.HDNodeWallet.fromPhrase(r.trim(),void 0,t);return{address:n.address,privateKey:n.privateKey}}catch(t){throw new w(`HD wallet derivation failed: ${t instanceof Error?t.message:"Unknown error"}`,t)}}var Ie=p(()=>{"use strict";G()});var nn={};E(nn,{DEFAULT_MODE:()=>Ae,DEFAULT_TAG:()=>ee,deriveAddressFromP256PublicKey:()=>Yo,deriveIndexFromOriginModeAndTag:()=>Es,getCurrentOrigin:()=>ve,getOriginSpecificAddress:()=>xe,normalizeOrigin:()=>rn});import{keccak256 as mh}from"ethers";function rn(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 w(`Invalid origin URL: ${r}`,e)}}async function Es(r,e=Ae,t=ee){try{let s=`${rn(r)}:${e}:${t.toUpperCase()}`,o=new TextEncoder().encode(s),a=await crypto.subtle.digest("SHA-256",o);return new DataView(a).getUint32(0,!1)%gh}catch(n){throw new w(`Failed to derive index from origin "${r}", mode "${e}", and tag "${t}"`,n)}}async function xe(r,e,t,n){try{let s=t||Ae,i=(n||ee).toUpperCase(),o=rn(e),a=await Es(o,s,i),{address:c,privateKey:l}=tn(r,a),u={address:c,index:a,origin:o,mode:s,tag:i};return s==="YOLO"&&(u.privateKey=l),u}catch(s){throw new w(`Failed to derive origin-specific address for "${e}" with mode "${t||Ae}" and tag "${n||ee}"`,s)}}function ve(){if(typeof window>"u"||!window.location)throw new w("getCurrentOrigin() only works in browser environments");return window.location.origin}async function Yo(r){try{let e=L(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=L(n.x),i=L(n.y),o=new Uint8Array(64);return o.set(new Uint8Array(s),0),o.set(new Uint8Array(i),32),"0x"+mh(o).slice(-40)}catch(e){throw new w("Failed to derive address from P-256 public key",e)}}var Ae,ee,gh,St=p(()=>{"use strict";Ie();G();fe();Ae="STANDARD",ee="MAIN",gh=2147483647});var Rs={};E(Rs,{encodeEIP7702AuthorizationMessage:()=>un,hashEIP7702AuthorizationMessage:()=>dn,verifyEIP7702Authorization:()=>Ts});import{encodeRlp as Ph,concat as Ih,keccak256 as Bh,toBeHex as ra,recoverAddress as Dh,Signature as Th}from"ethers";function un(r,e,t){let n=[r===0n?"0x":ra(r),e.toLowerCase(),t===0n?"0x":ra(t)],s=Ph(n);return Ih(["0x05",s])}function dn(r,e,t){let n=un(r,e,t);return Bh(n)}function Ts(r,e,t,n,s){try{let i=dn(r,e,t),o;return typeof n=="string"?o=Th.from(n):o=n,Dh(i,o).toLowerCase()===s.toLowerCase()}catch{return!1}}var hn=p(()=>{"use strict"});var na={};E(na,{detectWalletProvider:()=>Us,getDefaultProvider:()=>Ms,requestExternalWalletAuthorization:()=>Fs,supportsEIP7702Authorization:()=>Ns});async function Fs(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(()=>(hn(),Rs)),{Signature:l}=await import("ethers"),u=a(t,e.delegateToAddress,n),d;try{d=await r.request({method:"eth_sign",params:[o,u]})}catch(y){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: ${y.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 Ms(){if(typeof window>"u")return null;let r=window;return r.ethereum?r.ethereum:r.web3?.currentProvider?r.web3.currentProvider:null}function Us(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 Ns(r){try{let e=await r.request({method:"eth_accounts"});return Array.isArray(e)}catch{return!1}}var Ls=p(()=>{"use strict"});var oa={};E(oa,{extractRS:()=>ia});function ia(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 _s=p(()=>{"use strict"});var aa={};E(aa,{BackupStorage:()=>Qe});var Qe,fn=p(()=>{"use strict";Qe=class{constructor(){this.dbName="Web3PasskeyBackup";this.version=1;this.db=null}async init(){return typeof indexedDB>"u"?Promise.resolve():new Promise((e,t)=>{let n=indexedDB.open(this.dbName,this.version);n.onerror=()=>t(n.error),n.onsuccess=()=>{this.db=n.result,e()},n.onupgradeneeded=s=>{let i=s.target.result;if(!i.objectStoreNames.contains("backups")){let o=i.createObjectStore("backups",{keyPath:"id"});o.createIndex("ethereumAddress","ethereumAddress",{unique:!1}),o.createIndex("method","method",{unique:!1}),o.createIndex("createdAt","createdAt",{unique:!1})}}})}async storeBackupMetadata(e){return this.db||await this.init(),this.db?new Promise((t,n)=>{let o=this.db.transaction(["backups"],"readwrite").objectStore("backups").put(e);o.onsuccess=()=>t(),o.onerror=()=>n(o.error)}):Promise.resolve()}async getBackupsByAddress(e){return this.db||await this.init(),this.db?new Promise((t,n)=>{let a=this.db.transaction(["backups"],"readonly").objectStore("backups").index("ethereumAddress").getAll(e);a.onsuccess=()=>t(a.result),a.onerror=()=>n(a.error)}):Promise.resolve([])}async getBackupById(e){return this.db||await this.init(),this.db?new Promise((t,n)=>{let o=this.db.transaction(["backups"],"readonly").objectStore("backups").get(e);o.onsuccess=()=>t(o.result||null),o.onerror=()=>n(o.error)}):Promise.resolve(null)}async deleteBackup(e){return this.db||await this.init(),this.db?new Promise((t,n)=>{let o=this.db.transaction(["backups"],"readwrite").objectStore("backups").delete(e);o.onsuccess=()=>t(),o.onerror=()=>n(o.error)}):Promise.resolve()}async getBackupCountByMethod(e){return this.db||await this.init(),this.db?new Promise((t,n)=>{let a=this.db.transaction(["backups"],"readonly").objectStore("backups").index("method").count(e);a.onsuccess=()=>t(a.result),a.onerror=()=>n(a.error)}):Promise.resolve(0)}}});var la={};E(la,{decryptWithPassword:()=>or,deriveAddressChecksum:()=>te,deriveKeyFromPassword:()=>pn,encryptWithPassword:()=>Ze,getDeviceFingerprint:()=>Ee,validatePasswordStrength:()=>ca});async function pn(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 Ze(r,e,t){let s=await pn(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:ir(c),iv:ir(a),salt:ir(t),iterations:31e4}}async function or(r,e,t,n,s=31e4){let i=Ks(t),o=await pn(e,i,s),a=Ks(n),c=Ks(r),l=await crypto.subtle.decrypt({name:"AES-GCM",iv:a},o,c);return new TextDecoder().decode(l)}async function Ee(){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 ir(s)}async function te(r){let t=new TextEncoder().encode(r.toLowerCase()),n=await crypto.subtle.digest("SHA-256",t);return ir(n).substring(0,16)}function ca(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 ir(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 Ks(r){let e=yt(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}var Xe=p(()=>{"use strict";fe()});var da=P((ky,ua)=>{"use strict";ua.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var Ne=P(et=>{"use strict";var Os,Mh=[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];et.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};et.getSymbolTotalCodewords=function(e){return Mh[e]};et.getBCHDigit=function(r){let e=0;for(;r!==0;)e++,r>>>=1;return e};et.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');Os=e};et.isKanjiModeEnabled=function(){return typeof Os<"u"};et.toSJIS=function(e){return Os(e)}});var mn=P(ae=>{"use strict";ae.L={bit:1};ae.M={bit:0};ae.Q={bit:3};ae.H={bit:2};function Uh(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return ae.L;case"m":case"medium":return ae.M;case"q":case"quartile":return ae.Q;case"h":case"high":return ae.H;default:throw new Error("Unknown EC Level: "+r)}}ae.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};ae.from=function(e,t){if(ae.isValid(e))return e;try{return Uh(e)}catch{return t}}});var pa=P((Iy,fa)=>{"use strict";function ha(){this.buffer=[],this.length=0}ha.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++}};fa.exports=ha});var ga=P((By,ma)=>{"use strict";function ar(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)}ar.prototype.set=function(r,e,t,n){let s=r*this.size+e;this.data[s]=t,n&&(this.reservedBit[s]=!0)};ar.prototype.get=function(r,e){return this.data[r*this.size+e]};ar.prototype.xor=function(r,e,t){this.data[r*this.size+e]^=t};ar.prototype.isReserved=function(r,e){return this.reservedBit[r*this.size+e]};ma.exports=ar});var ya=P(gn=>{"use strict";var Nh=Ne().getSymbolSize;gn.getRowColCoords=function(e){if(e===1)return[];let t=Math.floor(e/7)+2,n=Nh(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()};gn.getPositions=function(e){let t=[],n=gn.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 Sa=P(ba=>{"use strict";var Lh=Ne().getSymbolSize,wa=7;ba.getPositions=function(e){let t=Lh(e);return[[0,0],[t-wa,0],[0,t-wa]]}});var Aa=P(F=>{"use strict";F.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var tt={N1:3,N2:3,N3:40,N4:10};F.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};F.from=function(e){return F.isValid(e)?parseInt(e,10):void 0};F.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+=tt.N1+(s-5)),o=u,s=1),u=e.get(l,c),u===a?i++:(i>=5&&(n+=tt.N1+(i-5)),a=u,i=1)}s>=5&&(n+=tt.N1+(s-5)),i>=5&&(n+=tt.N1+(i-5))}return n};F.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*tt.N2};F.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*tt.N3};F.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)*tt.N4};function _h(r,e,t){switch(r){case F.Patterns.PATTERN000:return(e+t)%2===0;case F.Patterns.PATTERN001:return e%2===0;case F.Patterns.PATTERN010:return t%3===0;case F.Patterns.PATTERN011:return(e+t)%3===0;case F.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(t/3))%2===0;case F.Patterns.PATTERN101:return e*t%2+e*t%3===0;case F.Patterns.PATTERN110:return(e*t%2+e*t%3)%2===0;case F.Patterns.PATTERN111:return(e*t%3+(e+t)%2)%2===0;default:throw new Error("bad maskPattern:"+r)}}F.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,_h(e,i,s))};F.getBestMask=function(e,t){let n=Object.keys(F.Patterns).length,s=0,i=1/0;for(let o=0;o<n;o++){t(o),F.applyMask(o,e);let a=F.getPenaltyN1(e)+F.getPenaltyN2(e)+F.getPenaltyN3(e)+F.getPenaltyN4(e);F.applyMask(o,e),a<i&&(i=a,s=o)}return s}});var Ws=P(zs=>{"use strict";var Le=mn(),yn=[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],wn=[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];zs.getBlocksCount=function(e,t){switch(t){case Le.L:return yn[(e-1)*4+0];case Le.M:return yn[(e-1)*4+1];case Le.Q:return yn[(e-1)*4+2];case Le.H:return yn[(e-1)*4+3];default:return}};zs.getTotalCodewordsCount=function(e,t){switch(t){case Le.L:return wn[(e-1)*4+0];case Le.M:return wn[(e-1)*4+1];case Le.Q:return wn[(e-1)*4+2];case Le.H:return wn[(e-1)*4+3];default:return}}});var xa=P(Sn=>{"use strict";var cr=new Uint8Array(512),bn=new Uint8Array(256);(function(){let e=1;for(let t=0;t<255;t++)cr[t]=e,bn[e]=t,e<<=1,e&256&&(e^=285);for(let t=255;t<512;t++)cr[t]=cr[t-255]})();Sn.log=function(e){if(e<1)throw new Error("log("+e+")");return bn[e]};Sn.exp=function(e){return cr[e]};Sn.mul=function(e,t){return e===0||t===0?0:cr[bn[e]+bn[t]]}});var va=P(lr=>{"use strict";var $s=xa();lr.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]^=$s.mul(e[s],t[i]);return n};lr.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]^=$s.mul(t[o],s);let i=0;for(;i<n.length&&n[i]===0;)i++;n=n.slice(i)}return n};lr.generateECPolynomial=function(e){let t=new Uint8Array([1]);for(let n=0;n<e;n++)t=lr.mul(t,new Uint8Array([1,$s.exp(n)]));return t}});var Ca=P((Ny,ka)=>{"use strict";var Ea=va();function qs(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}qs.prototype.initialize=function(e){this.degree=e,this.genPoly=Ea.generateECPolynomial(this.degree)};qs.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=Ea.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};ka.exports=qs});var Hs=P(Pa=>{"use strict";Pa.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var Vs=P(Be=>{"use strict";var Ia="[0-9]+",Kh="[A-Z $%*+\\-./:]+",ur="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";ur=ur.replace(/u/g,"\\u");var Oh="(?:(?![A-Z0-9 $%*+\\-./:]|"+ur+`)(?:.|[\r
2
- ]))+`;Be.KANJI=new RegExp(ur,"g");Be.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");Be.BYTE=new RegExp(Oh,"g");Be.NUMERIC=new RegExp(Ia,"g");Be.ALPHANUMERIC=new RegExp(Kh,"g");var zh=new RegExp("^"+ur+"$"),Wh=new RegExp("^"+Ia+"$"),$h=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");Be.testKanji=function(e){return zh.test(e)};Be.testNumeric=function(e){return Wh.test(e)};Be.testAlphanumeric=function(e){return $h.test(e)}});var _e=P(_=>{"use strict";var qh=Hs(),Gs=Vs();_.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};_.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};_.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};_.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};_.MIXED={bit:-1};_.getCharCountIndicator=function(e,t){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!qh.isValid(t))throw new Error("Invalid version: "+t);return t>=1&&t<10?e.ccBits[0]:t<27?e.ccBits[1]:e.ccBits[2]};_.getBestModeForData=function(e){return Gs.testNumeric(e)?_.NUMERIC:Gs.testAlphanumeric(e)?_.ALPHANUMERIC:Gs.testKanji(e)?_.KANJI:_.BYTE};_.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};_.isValid=function(e){return e&&e.bit&&e.ccBits};function Hh(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"numeric":return _.NUMERIC;case"alphanumeric":return _.ALPHANUMERIC;case"kanji":return _.KANJI;case"byte":return _.BYTE;default:throw new Error("Unknown mode: "+r)}}_.from=function(e,t){if(_.isValid(e))return e;try{return Hh(e)}catch{return t}}});var Fa=P(rt=>{"use strict";var An=Ne(),Vh=Ws(),Ba=mn(),Ke=_e(),Ys=Hs(),Ta=7973,Da=An.getBCHDigit(Ta);function Gh(r,e,t){for(let n=1;n<=40;n++)if(e<=rt.getCapacity(n,t,r))return n}function Ra(r,e){return Ke.getCharCountIndicator(r,e)+4}function Yh(r,e){let t=0;return r.forEach(function(n){let s=Ra(n.mode,e);t+=s+n.getBitsLength()}),t}function jh(r,e){for(let t=1;t<=40;t++)if(Yh(r,t)<=rt.getCapacity(t,e,Ke.MIXED))return t}rt.from=function(e,t){return Ys.isValid(e)?parseInt(e,10):t};rt.getCapacity=function(e,t,n){if(!Ys.isValid(e))throw new Error("Invalid QR Code version");typeof n>"u"&&(n=Ke.BYTE);let s=An.getSymbolTotalCodewords(e),i=Vh.getTotalCodewordsCount(e,t),o=(s-i)*8;if(n===Ke.MIXED)return o;let a=o-Ra(n,e);switch(n){case Ke.NUMERIC:return Math.floor(a/10*3);case Ke.ALPHANUMERIC:return Math.floor(a/11*2);case Ke.KANJI:return Math.floor(a/13);case Ke.BYTE:default:return Math.floor(a/8)}};rt.getBestVersionForData=function(e,t){let n,s=Ba.from(t,Ba.M);if(Array.isArray(e)){if(e.length>1)return jh(e,s);if(e.length===0)return 1;n=e[0]}else n=e;return Gh(n.mode,n.getLength(),s)};rt.getEncodedBits=function(e){if(!Ys.isValid(e)||e<7)throw new Error("Invalid QR Code version");let t=e<<12;for(;An.getBCHDigit(t)-Da>=0;)t^=Ta<<An.getBCHDigit(t)-Da;return e<<12|t}});var La=P(Na=>{"use strict";var js=Ne(),Ua=1335,Jh=21522,Ma=js.getBCHDigit(Ua);Na.getEncodedBits=function(e,t){let n=e.bit<<3|t,s=n<<10;for(;js.getBCHDigit(s)-Ma>=0;)s^=Ua<<js.getBCHDigit(s)-Ma;return(n<<10|s)^Jh}});var Ka=P((Wy,_a)=>{"use strict";var Qh=_e();function At(r){this.mode=Qh.NUMERIC,this.data=r.toString()}At.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};At.prototype.getLength=function(){return this.data.length};At.prototype.getBitsLength=function(){return At.getBitsLength(this.data.length)};At.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))};_a.exports=At});var za=P(($y,Oa)=>{"use strict";var Zh=_e(),Js=["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 xt(r){this.mode=Zh.ALPHANUMERIC,this.data=r}xt.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};xt.prototype.getLength=function(){return this.data.length};xt.prototype.getBitsLength=function(){return xt.getBitsLength(this.data.length)};xt.prototype.write=function(e){let t;for(t=0;t+2<=this.data.length;t+=2){let n=Js.indexOf(this.data[t])*45;n+=Js.indexOf(this.data[t+1]),e.put(n,11)}this.data.length%2&&e.put(Js.indexOf(this.data[t]),6)};Oa.exports=xt});var $a=P((qy,Wa)=>{"use strict";var Xh=_e();function vt(r){this.mode=Xh.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}vt.getBitsLength=function(e){return e*8};vt.prototype.getLength=function(){return this.data.length};vt.prototype.getBitsLength=function(){return vt.getBitsLength(this.data.length)};vt.prototype.write=function(r){for(let e=0,t=this.data.length;e<t;e++)r.put(this.data[e],8)};Wa.exports=vt});var Ha=P((Hy,qa)=>{"use strict";var ef=_e(),tf=Ne();function Et(r){this.mode=ef.KANJI,this.data=r}Et.getBitsLength=function(e){return e*13};Et.prototype.getLength=function(){return this.data.length};Et.prototype.getBitsLength=function(){return Et.getBitsLength(this.data.length)};Et.prototype.write=function(r){let e;for(e=0;e<this.data.length;e++){let t=tf.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)}};qa.exports=Et});var Va=P((Vy,Qs)=>{"use strict";var dr={single_source_shortest_paths:function(r,e,t){var n={},s={};s[e]=0;var i=dr.PriorityQueue.make();i.push(e,0);for(var o,a,c,l,u,d,h,m,g;!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],g=typeof s[c]>"u",(g||m>h)&&(s[c]=h,i.push(c,h),n[c]=a))}if(typeof t<"u"&&typeof s[t]>"u"){var y=["Could not find a path from ",e," to ",t,"."].join("");throw new Error(y)}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=dr.single_source_shortest_paths(r,e,t);return dr.extract_shortest_path_from_predecessor_list(n,t)},PriorityQueue:{make:function(r){var e=dr.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 Qs<"u"&&(Qs.exports=dr)});var ec=P(kt=>{"use strict";var I=_e(),ja=Ka(),Ja=za(),Qa=$a(),Za=Ha(),hr=Vs(),xn=Ne(),rf=Va();function Ga(r){return unescape(encodeURIComponent(r)).length}function fr(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 Xa(r){let e=fr(hr.NUMERIC,I.NUMERIC,r),t=fr(hr.ALPHANUMERIC,I.ALPHANUMERIC,r),n,s;return xn.isKanjiModeEnabled()?(n=fr(hr.BYTE,I.BYTE,r),s=fr(hr.KANJI,I.KANJI,r)):(n=fr(hr.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 Zs(r,e){switch(e){case I.NUMERIC:return ja.getBitsLength(r);case I.ALPHANUMERIC:return Ja.getBitsLength(r);case I.KANJI:return Za.getBitsLength(r);case I.BYTE:return Qa.getBitsLength(r)}}function nf(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 sf(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:Ga(n.data)}]);break;case I.BYTE:e.push([{data:n.data,mode:I.BYTE,length:Ga(n.data)}])}}return e}function of(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]=Zs(t[h].lastCount+l.length,l.mode)-Zs(t[h].lastCount,l.mode),t[h].lastCount+=l.length):(t[h]&&(t[h].lastCount=l.length),n[h][u]=Zs(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 Ya(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&&!xn.isKanjiModeEnabled()&&(t=I.BYTE),t){case I.NUMERIC:return new ja(r);case I.ALPHANUMERIC:return new Ja(r);case I.KANJI:return new Za(r);case I.BYTE:return new Qa(r)}}kt.fromArray=function(e){return e.reduce(function(t,n){return typeof n=="string"?t.push(Ya(n,null)):n.data&&t.push(Ya(n.data,n.mode)),t},[])};kt.fromString=function(e,t){let n=Xa(e,xn.isKanjiModeEnabled()),s=sf(n),i=of(s,t),o=rf.find_path(i.map,"start","end"),a=[];for(let c=1;c<o.length-1;c++)a.push(i.table[o[c]].node);return kt.fromArray(nf(a))};kt.rawSplit=function(e){return kt.fromArray(Xa(e,xn.isKanjiModeEnabled()))}});var rc=P(tc=>{"use strict";var En=Ne(),Xs=mn(),af=pa(),cf=ga(),lf=ya(),uf=Sa(),ri=Aa(),ni=Ws(),df=Ca(),vn=Fa(),hf=La(),ff=_e(),ei=ec();function pf(r,e){let t=r.size,n=uf.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 mf(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 gf(r,e){let t=lf.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 yf(r,e){let t=r.size,n=vn.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 ti(r,e,t){let n=r.size,s=hf.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 wf(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 bf(r,e,t){let n=new af;t.forEach(function(c){n.put(c.mode.bit,4),n.put(c.getLength(),ff.getCharCountIndicator(c.mode,r)),c.write(n)});let s=En.getSymbolTotalCodewords(r),i=ni.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 Sf(n,r,e)}function Sf(r,e,t){let n=En.getSymbolTotalCodewords(e),s=ni.getTotalCodewordsCount(e,t),i=n-s,o=ni.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 df(h),g=0,y=new Array(o),b=new Array(o),S=0,A=new Uint8Array(r.buffer);for(let T=0;T<o;T++){let O=T<c?u:d;y[T]=A.slice(g,g+O),b[T]=m.encode(y[T]),g+=O,S=Math.max(S,O)}let v=new Uint8Array(n),k=0,C,x;for(C=0;C<S;C++)for(x=0;x<o;x++)C<y[x].length&&(v[k++]=y[x][C]);for(C=0;C<h;C++)for(x=0;x<o;x++)v[k++]=b[x][C];return v}function Af(r,e,t,n){let s;if(Array.isArray(r))s=ei.fromArray(r);else if(typeof r=="string"){let l=e;if(!l){let u=ei.rawSplit(r);l=vn.getBestVersionForData(u,t)}s=ei.fromString(r,l||40)}else throw new Error("Invalid data");let i=vn.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
+ var oh=Object.create;var jr=Object.defineProperty;var ah=Object.getOwnPropertyDescriptor;var ch=Object.getOwnPropertyNames;var lh=Object.getPrototypeOf,uh=Object.prototype.hasOwnProperty;var dh=(r,e,t)=>e in r?jr(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var m=(r,e)=>()=>(r&&(e=r(r=0)),e);var E=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),x=(r,e)=>{for(var t in e)jr(r,t,{get:e[t],enumerable:!0})},hh=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of ch(e))!uh.call(r,s)&&s!==t&&jr(r,s,{get:()=>e[s],enumerable:!(n=ah(e,s))||n.enumerable});return r};var Zt=(r,e,t)=>(t=r!=null?oh(lh(r)):{},hh(e||!r||!r.__esModule?jr(t,"default",{value:r,enumerable:!0}):t,r));var f=(r,e,t)=>dh(r,typeof e!="symbol"?e+"":e,t);var K,z,er,y,U,I,xs,tr,rr,G=m(()=>{"use strict";K=class extends Error{constructor(t,n,s){super(t);this.code=n;this.originalError=s;this.name="Web3PasskeyError"}},z=class extends K{constructor(e,t){super(e,"AUTHENTICATION_ERROR",t),this.name="AuthenticationError"}},er=class extends K{constructor(e,t){super(e,"REGISTRATION_ERROR",t),this.name="RegistrationError"}},y=class extends K{constructor(e,t){super(e,"WALLET_ERROR",t),this.name="WalletError"}},U=class extends K{constructor(e,t){super(e,"CRYPTO_ERROR",t),this.name="CryptoError"}},I=class extends K{constructor(e,t){super(e,"STORAGE_ERROR",t),this.name="StorageError"}},xs=class extends K{constructor(t,n,s){super(t,"API_ERROR",s);this.statusCode=n;this.name="ApiError"}},tr=class extends K{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"}},rr=class extends K{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"}}});var Es={};x(Es,{arrayBufferToBase64Url:()=>ye,base64ToArrayBuffer:()=>Vo,base64UrlDecode:()=>Yo,base64UrlToArrayBuffer:()=>L,safeAtob:()=>mt,safeBtoa:()=>Go});function L(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 ye(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 Vo(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 mt(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 Go(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 Yo(r){return L(r)}var we=m(()=>{"use strict"});var Me={};x(Me,{PRF_INPUT:()=>nr,decryptData:()=>Z,deriveEncryptionKey:()=>gh,deriveEncryptionKeyFromWebAuthn:()=>ue,derivePrfSessionKey:()=>gt,encryptData:()=>se,exportSessionKey:()=>Cs,generateChallenge:()=>Fe,hashCredentialId:()=>yt,hashPublicKey:()=>Is,importSessionKey:()=>Ps});async function gt(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:mh},n,{name:"AES-GCM",length:256},e,["encrypt","decrypt"])}catch(t){throw new U("Failed to derive session key from PRF output",t)}}async function Cs(r){try{return ye(await crypto.subtle.exportKey("raw",r))}catch(e){throw new U("Failed to export session key",e)}}async function Ps(r){try{return await crypto.subtle.importKey("raw",L(r),{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}catch(e){throw new U("Failed to import session key",e)}}async function ue(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 U("Failed to derive encryption key from WebAuthn",t)}}async function gh(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 U("Failed to derive encryption key",t)}}function Fe(){let r=new Uint8Array(32);return crypto.getRandomValues(r),ye(r)}async function se(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 U("Failed to encrypt data",t)}}async function Z(r,e){try{if(!r||r.length<16)throw new Error("Invalid encrypted data: too small");let t=mt(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 U(`Data decryption failed: ${t instanceof Error?t.message:"Unknown error"}`,t)}}async function yt(r){try{let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`w3pk-cred-id:${r}`));return ye(e)}catch(e){throw new U("Failed to hash credential ID",e)}}async function Is(r){try{let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(r));return ye(e)}catch(e){throw new U("Failed to hash public key",e)}}var nr,mh,$=m(()=>{"use strict";G();we();nr=new TextEncoder().encode("w3pk-prf-input-v1"),mh=new TextEncoder().encode("w3pk-prf-session-key-v1")});var Xr={};x(Xr,{CredentialStorage:()=>R});async function jo(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 Jr,Qr,R,Ue=m(()=>{"use strict";G();$();Jr="w3pk_credential_",Qr="w3pk_credential_index";R=class{constructor(e){if(e)this.storage=e;else if(typeof window<"u"&&window.localStorage)this.storage=window.localStorage;else throw new I("localStorage is not available")}async saveCredential(e){try{let t=await jo(e.id),n=await yt(e.id),s={id:n,encryptedUsername:await se(e.username,t),encryptedAddress:await se(e.ethereumAddress,t),publicKey:e.publicKey,publicKeyFingerprint:await Is(e.publicKey),createdAt:e.createdAt,lastUsed:e.lastUsed},i=`${Jr}${n}`;this.storage.setItem(i,JSON.stringify(s)),await this.addToIndex(e.id)}catch(t){throw new I("Failed to save credential",t)}}async getCredentialById(e){try{let t=await yt(e),n=`${Jr}${t}`,s=this.storage.getItem(n);if(!s)return null;let i=JSON.parse(s),o=await jo(e);return{id:e,publicKey:i.publicKey,username:await Z(i.encryptedUsername,o),ethereumAddress:await Z(i.encryptedAddress,o),createdAt:i.createdAt,lastUsed:i.lastUsed}}catch(t){throw new I("Failed to retrieve credential",t)}}async getCredentialByUsername(e){try{return(await this.getAllCredentials()).find(n=>n.username===e)||null}catch(t){throw new I("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 I("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 I("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 I("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 I("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 I("Failed to update credential address",n)}}async deleteCredential(e){try{let t=await yt(e),n=`${Jr}${t}`;this.storage.removeItem(n),await this.removeFromIndex(e)}catch(t){throw new I("Failed to delete credential",t)}}async clearAll(){try{let e=await this.getIndex();(await Promise.all(e.map(async n=>await yt(n)))).forEach(n=>{let s=`${Jr}${n}`;this.storage.removeItem(s)}),this.storage.removeItem(Qr)}catch(e){throw new I("Failed to clear credentials",e)}}async getIndex(){try{let e=this.storage.getItem(Qr);return e?JSON.parse(e):[]}catch{return[]}}async addToIndex(e){let t=await this.getIndex();t.includes(e)||(t.push(e),this.storage.setItem(Qr,JSON.stringify(t)))}async removeFromIndex(e){let n=(await this.getIndex()).filter(s=>s!==e);this.storage.setItem(Qr,JSON.stringify(n))}}});var wt={};x(wt,{createWalletFromMnemonic:()=>Xo,deriveWalletFromMnemonic:()=>sn,generateBIP39Wallet:()=>nn});import{ethers as rn}from"ethers";function nn(){try{let r=rn.Wallet.createRandom().mnemonic;if(!r)throw new Error("Failed to generate mnemonic");let e=r.phrase;return{address:rn.HDNodeWallet.fromPhrase(e,void 0,"m/44'/60'/0'/0/0").address,mnemonic:e}}catch(r){throw new y("Wallet generation failed",r)}}function Xo(r){try{if(!r||r.trim().split(/\s+/).length<12)throw new Error("Invalid mnemonic: must be at least 12 words");return rn.HDNodeWallet.fromPhrase(r.trim(),void 0,"m/44'/60'/0'/0/0")}catch(e){throw new y(`Wallet creation failed: ${e instanceof Error?e.message:"Invalid mnemonic"}`,e)}}function sn(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=rn.HDNodeWallet.fromPhrase(r.trim(),void 0,t);return{address:n.address,privateKey:n.privateKey}}catch(t){throw new y(`HD wallet derivation failed: ${t instanceof Error?t.message:"Unknown error"}`,t)}}var Ce=m(()=>{"use strict";G()});var an={};x(an,{DEFAULT_MODE:()=>be,DEFAULT_TAG:()=>ee,deriveAddressFromP256PublicKey:()=>Zo,deriveIndexFromOriginModeAndTag:()=>Bs,getCurrentOrigin:()=>Ae,getOriginSpecificAddress:()=>Se,normalizeOrigin:()=>on});import{keccak256 as vh}from"ethers";function on(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 y(`Invalid origin URL: ${r}`,e)}}async function Bs(r,e=be,t=ee){try{let s=`${on(r)}:${e}:${t.toUpperCase()}`,o=new TextEncoder().encode(s),a=await crypto.subtle.digest("SHA-256",o);return new DataView(a).getUint32(0,!1)%kh}catch(n){throw new y(`Failed to derive index from origin "${r}", mode "${e}", and tag "${t}"`,n)}}async function Se(r,e,t,n){try{let s=t||be,i=(n||ee).toUpperCase(),o=on(e),a=await Bs(o,s,i),{address:c,privateKey:l}=sn(r,a),u={address:c,index:a,origin:o,mode:s,tag:i};return s==="YOLO"&&(u.privateKey=l),u}catch(s){throw new y(`Failed to derive origin-specific address for "${e}" with mode "${t||be}" and tag "${n||ee}"`,s)}}function Ae(){if(typeof window>"u"||!window.location)throw new y("getCurrentOrigin() only works in browser environments");return window.location.origin}async function Zo(r){try{let e=L(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=L(n.x),i=L(n.y),o=new Uint8Array(64);return o.set(new Uint8Array(s),0),o.set(new Uint8Array(i),32),"0x"+vh(o).slice(-40)}catch(e){throw new y("Failed to derive address from P-256 public key",e)}}var be,ee,kh,bt=m(()=>{"use strict";Ce();G();we();be="STANDARD",ee="MAIN",kh=2147483647});var Ns={};x(Ns,{encodeEIP7702AuthorizationMessage:()=>pn,hashEIP7702AuthorizationMessage:()=>mn,verifyEIP7702Authorization:()=>Us});import{encodeRlp as Fh,concat as Mh,keccak256 as Uh,toBeHex as oa,recoverAddress as Nh,Signature as Lh}from"ethers";function pn(r,e,t){let n=[r===0n?"0x":oa(r),e.toLowerCase(),t===0n?"0x":oa(t)],s=Fh(n);return Mh(["0x05",s])}function mn(r,e,t){let n=pn(r,e,t);return Uh(n)}function Us(r,e,t,n,s){try{let i=mn(r,e,t),o;return typeof n=="string"?o=Lh.from(n):o=n,Nh(i,o).toLowerCase()===s.toLowerCase()}catch{return!1}}var gn=m(()=>{"use strict"});var aa={};x(aa,{detectWalletProvider:()=>Ks,getDefaultProvider:()=>_s,requestExternalWalletAuthorization:()=>Ls,supportsEIP7702Authorization:()=>Os});async function Ls(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(()=>(gn(),Ns)),{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),p={chainId:t,address:e.delegateToAddress.toLowerCase(),nonce:n,yParity:h.yParity,r:h.r,s:h.s};if(!c(t,e.delegateToAddress,n,p,o))throw new Error(`Signature verification failed. Expected signer: ${o}, but signature does not match. This may indicate a wallet implementation issue.`);return p}function _s(){if(typeof window>"u")return null;let r=window;return r.ethereum?r.ethereum:r.web3?.currentProvider?r.web3.currentProvider:null}function Ks(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 Os(r){try{let e=await r.request({method:"eth_accounts"});return Array.isArray(e)}catch{return!1}}var zs=m(()=>{"use strict"});var ua={};x(ua,{BackupStorage:()=>Qe});var la,Qe,yn=m(()=>{"use strict";la="w3pk_backups",Qe=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(la);return e?JSON.parse(e):[]}writeAll(e){this.storage?.setItem(la,JSON.stringify(e))}}});var $s={};x($s,{decryptWithPassword:()=>cr,deriveAddressChecksum:()=>te,deriveKeyFromPassword:()=>wn,encryptWithPassword:()=>Xe,getDeviceFingerprint:()=>xe,validatePasswordStrength:()=>da});async function wn(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 Xe(r,e,t){let s=await wn(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:ar(c),iv:ar(a),salt:ar(t),iterations:31e4}}async function cr(r,e,t,n,s=31e4){let i=Ws(t),o=await wn(e,i,s),a=Ws(n),c=Ws(r),l=await crypto.subtle.decrypt({name:"AES-GCM",iv:a},o,c);return new TextDecoder().decode(l)}async function xe(){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 ar(s)}async function te(r){let t=new TextEncoder().encode(r.toLowerCase()),n=await crypto.subtle.digest("SHA-256",t);return ar(n).substring(0,16)}function da(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 ar(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 Ws(r){let e=mt(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}var Ne=m(()=>{"use strict";we()});var fa=E((Dy,ha)=>{"use strict";ha.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var Le=E(Ze=>{"use strict";var Hs,Oh=[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];Ze.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};Ze.getSymbolTotalCodewords=function(e){return Oh[e]};Ze.getBCHDigit=function(r){let e=0;for(;r!==0;)e++,r>>>=1;return e};Ze.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');Hs=e};Ze.isKanjiModeEnabled=function(){return typeof Hs<"u"};Ze.toSJIS=function(e){return Hs(e)}});var bn=E(ie=>{"use strict";ie.L={bit:1};ie.M={bit:0};ie.Q={bit:3};ie.H={bit:2};function zh(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"l":case"low":return ie.L;case"m":case"medium":return ie.M;case"q":case"quartile":return ie.Q;case"h":case"high":return ie.H;default:throw new Error("Unknown EC Level: "+r)}}ie.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};ie.from=function(e,t){if(ie.isValid(e))return e;try{return zh(e)}catch{return t}}});var ga=E((Uy,ma)=>{"use strict";function pa(){this.buffer=[],this.length=0}pa.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++}};ma.exports=pa});var wa=E((Ny,ya)=>{"use strict";function lr(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)}lr.prototype.set=function(r,e,t,n){let s=r*this.size+e;this.data[s]=t,n&&(this.reservedBit[s]=!0)};lr.prototype.get=function(r,e){return this.data[r*this.size+e]};lr.prototype.xor=function(r,e,t){this.data[r*this.size+e]^=t};lr.prototype.isReserved=function(r,e){return this.reservedBit[r*this.size+e]};ya.exports=lr});var ba=E(Sn=>{"use strict";var Wh=Le().getSymbolSize;Sn.getRowColCoords=function(e){if(e===1)return[];let t=Math.floor(e/7)+2,n=Wh(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()};Sn.getPositions=function(e){let t=[],n=Sn.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 xa=E(Aa=>{"use strict";var $h=Le().getSymbolSize,Sa=7;Aa.getPositions=function(e){let t=$h(e);return[[0,0],[t-Sa,0],[0,t-Sa]]}});var va=E(D=>{"use strict";D.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var et={N1:3,N2:3,N3:40,N4:10};D.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};D.from=function(e){return D.isValid(e)?parseInt(e,10):void 0};D.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+=et.N1+(s-5)),o=u,s=1),u=e.get(l,c),u===a?i++:(i>=5&&(n+=et.N1+(i-5)),a=u,i=1)}s>=5&&(n+=et.N1+(s-5)),i>=5&&(n+=et.N1+(i-5))}return n};D.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*et.N2};D.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*et.N3};D.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)*et.N4};function Hh(r,e,t){switch(r){case D.Patterns.PATTERN000:return(e+t)%2===0;case D.Patterns.PATTERN001:return e%2===0;case D.Patterns.PATTERN010:return t%3===0;case D.Patterns.PATTERN011:return(e+t)%3===0;case D.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(t/3))%2===0;case D.Patterns.PATTERN101:return e*t%2+e*t%3===0;case D.Patterns.PATTERN110:return(e*t%2+e*t%3)%2===0;case D.Patterns.PATTERN111:return(e*t%3+(e+t)%2)%2===0;default:throw new Error("bad maskPattern:"+r)}}D.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,Hh(e,i,s))};D.getBestMask=function(e,t){let n=Object.keys(D.Patterns).length,s=0,i=1/0;for(let o=0;o<n;o++){t(o),D.applyMask(o,e);let a=D.getPenaltyN1(e)+D.getPenaltyN2(e)+D.getPenaltyN3(e)+D.getPenaltyN4(e);D.applyMask(o,e),a<i&&(i=a,s=o)}return s}});var Vs=E(qs=>{"use strict";var _e=bn(),An=[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],xn=[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];qs.getBlocksCount=function(e,t){switch(t){case _e.L:return An[(e-1)*4+0];case _e.M:return An[(e-1)*4+1];case _e.Q:return An[(e-1)*4+2];case _e.H:return An[(e-1)*4+3];default:return}};qs.getTotalCodewordsCount=function(e,t){switch(t){case _e.L:return xn[(e-1)*4+0];case _e.M:return xn[(e-1)*4+1];case _e.Q:return xn[(e-1)*4+2];case _e.H:return xn[(e-1)*4+3];default:return}}});var ka=E(kn=>{"use strict";var ur=new Uint8Array(512),vn=new Uint8Array(256);(function(){let e=1;for(let t=0;t<255;t++)ur[t]=e,vn[e]=t,e<<=1,e&256&&(e^=285);for(let t=255;t<512;t++)ur[t]=ur[t-255]})();kn.log=function(e){if(e<1)throw new Error("log("+e+")");return vn[e]};kn.exp=function(e){return ur[e]};kn.mul=function(e,t){return e===0||t===0?0:ur[vn[e]+vn[t]]}});var Ea=E(dr=>{"use strict";var Gs=ka();dr.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]^=Gs.mul(e[s],t[i]);return n};dr.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]^=Gs.mul(t[o],s);let i=0;for(;i<n.length&&n[i]===0;)i++;n=n.slice(i)}return n};dr.generateECPolynomial=function(e){let t=new Uint8Array([1]);for(let n=0;n<e;n++)t=dr.mul(t,new Uint8Array([1,Gs.exp(n)]));return t}});var Ia=E(($y,Pa)=>{"use strict";var Ca=Ea();function Ys(r){this.genPoly=void 0,this.degree=r,this.degree&&this.initialize(this.degree)}Ys.prototype.initialize=function(e){this.degree=e,this.genPoly=Ca.generateECPolynomial(this.degree)};Ys.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=Ca.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};Pa.exports=Ys});var js=E(Ba=>{"use strict";Ba.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var Js=E(Pe=>{"use strict";var Ta="[0-9]+",qh="[A-Z $%*+\\-./:]+",hr="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";hr=hr.replace(/u/g,"\\u");var Vh="(?:(?![A-Z0-9 $%*+\\-./:]|"+hr+`)(?:.|[\r
2
+ ]))+`;Pe.KANJI=new RegExp(hr,"g");Pe.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");Pe.BYTE=new RegExp(Vh,"g");Pe.NUMERIC=new RegExp(Ta,"g");Pe.ALPHANUMERIC=new RegExp(qh,"g");var Gh=new RegExp("^"+hr+"$"),Yh=new RegExp("^"+Ta+"$"),jh=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");Pe.testKanji=function(e){return Gh.test(e)};Pe.testNumeric=function(e){return Yh.test(e)};Pe.testAlphanumeric=function(e){return jh.test(e)}});var Ke=E(_=>{"use strict";var Jh=js(),Qs=Js();_.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]};_.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]};_.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]};_.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]};_.MIXED={bit:-1};_.getCharCountIndicator=function(e,t){if(!e.ccBits)throw new Error("Invalid mode: "+e);if(!Jh.isValid(t))throw new Error("Invalid version: "+t);return t>=1&&t<10?e.ccBits[0]:t<27?e.ccBits[1]:e.ccBits[2]};_.getBestModeForData=function(e){return Qs.testNumeric(e)?_.NUMERIC:Qs.testAlphanumeric(e)?_.ALPHANUMERIC:Qs.testKanji(e)?_.KANJI:_.BYTE};_.toString=function(e){if(e&&e.id)return e.id;throw new Error("Invalid mode")};_.isValid=function(e){return e&&e.bit&&e.ccBits};function Qh(r){if(typeof r!="string")throw new Error("Param is not a string");switch(r.toLowerCase()){case"numeric":return _.NUMERIC;case"alphanumeric":return _.ALPHANUMERIC;case"kanji":return _.KANJI;case"byte":return _.BYTE;default:throw new Error("Unknown mode: "+r)}}_.from=function(e,t){if(_.isValid(e))return e;try{return Qh(e)}catch{return t}}});var Ua=E(tt=>{"use strict";var En=Le(),Xh=Vs(),Ra=bn(),Oe=Ke(),Xs=js(),Fa=7973,Da=En.getBCHDigit(Fa);function Zh(r,e,t){for(let n=1;n<=40;n++)if(e<=tt.getCapacity(n,t,r))return n}function Ma(r,e){return Oe.getCharCountIndicator(r,e)+4}function ef(r,e){let t=0;return r.forEach(function(n){let s=Ma(n.mode,e);t+=s+n.getBitsLength()}),t}function tf(r,e){for(let t=1;t<=40;t++)if(ef(r,t)<=tt.getCapacity(t,e,Oe.MIXED))return t}tt.from=function(e,t){return Xs.isValid(e)?parseInt(e,10):t};tt.getCapacity=function(e,t,n){if(!Xs.isValid(e))throw new Error("Invalid QR Code version");typeof n>"u"&&(n=Oe.BYTE);let s=En.getSymbolTotalCodewords(e),i=Xh.getTotalCodewordsCount(e,t),o=(s-i)*8;if(n===Oe.MIXED)return o;let a=o-Ma(n,e);switch(n){case Oe.NUMERIC:return Math.floor(a/10*3);case Oe.ALPHANUMERIC:return Math.floor(a/11*2);case Oe.KANJI:return Math.floor(a/13);case Oe.BYTE:default:return Math.floor(a/8)}};tt.getBestVersionForData=function(e,t){let n,s=Ra.from(t,Ra.M);if(Array.isArray(e)){if(e.length>1)return tf(e,s);if(e.length===0)return 1;n=e[0]}else n=e;return Zh(n.mode,n.getLength(),s)};tt.getEncodedBits=function(e){if(!Xs.isValid(e)||e<7)throw new Error("Invalid QR Code version");let t=e<<12;for(;En.getBCHDigit(t)-Da>=0;)t^=Fa<<En.getBCHDigit(t)-Da;return e<<12|t}});var Ka=E(_a=>{"use strict";var Zs=Le(),La=1335,rf=21522,Na=Zs.getBCHDigit(La);_a.getEncodedBits=function(e,t){let n=e.bit<<3|t,s=n<<10;for(;Zs.getBCHDigit(s)-Na>=0;)s^=La<<Zs.getBCHDigit(s)-Na;return(n<<10|s)^rf}});var za=E((jy,Oa)=>{"use strict";var nf=Ke();function St(r){this.mode=nf.NUMERIC,this.data=r.toString()}St.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};St.prototype.getLength=function(){return this.data.length};St.prototype.getBitsLength=function(){return St.getBitsLength(this.data.length)};St.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))};Oa.exports=St});var $a=E((Jy,Wa)=>{"use strict";var sf=Ke(),ei=["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 At(r){this.mode=sf.ALPHANUMERIC,this.data=r}At.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};At.prototype.getLength=function(){return this.data.length};At.prototype.getBitsLength=function(){return At.getBitsLength(this.data.length)};At.prototype.write=function(e){let t;for(t=0;t+2<=this.data.length;t+=2){let n=ei.indexOf(this.data[t])*45;n+=ei.indexOf(this.data[t+1]),e.put(n,11)}this.data.length%2&&e.put(ei.indexOf(this.data[t]),6)};Wa.exports=At});var qa=E((Qy,Ha)=>{"use strict";var of=Ke();function xt(r){this.mode=of.BYTE,typeof r=="string"?this.data=new TextEncoder().encode(r):this.data=new Uint8Array(r)}xt.getBitsLength=function(e){return e*8};xt.prototype.getLength=function(){return this.data.length};xt.prototype.getBitsLength=function(){return xt.getBitsLength(this.data.length)};xt.prototype.write=function(r){for(let e=0,t=this.data.length;e<t;e++)r.put(this.data[e],8)};Ha.exports=xt});var Ga=E((Xy,Va)=>{"use strict";var af=Ke(),cf=Le();function vt(r){this.mode=af.KANJI,this.data=r}vt.getBitsLength=function(e){return e*13};vt.prototype.getLength=function(){return this.data.length};vt.prototype.getBitsLength=function(){return vt.getBitsLength(this.data.length)};vt.prototype.write=function(r){let e;for(e=0;e<this.data.length;e++){let t=cf.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)}};Va.exports=vt});var Ya=E((Zy,ti)=>{"use strict";var fr={single_source_shortest_paths:function(r,e,t){var n={},s={};s[e]=0;var i=fr.PriorityQueue.make();i.push(e,0);for(var o,a,c,l,u,d,h,p,g;!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,p=s[c],g=typeof s[c]>"u",(g||p>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=fr.single_source_shortest_paths(r,e,t);return fr.extract_shortest_path_from_predecessor_list(n,t)},PriorityQueue:{make:function(r){var e=fr.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 ti<"u"&&(ti.exports=fr)});var rc=E(kt=>{"use strict";var C=Ke(),Qa=za(),Xa=$a(),Za=qa(),ec=Ga(),pr=Js(),Cn=Le(),lf=Ya();function ja(r){return unescape(encodeURIComponent(r)).length}function mr(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 tc(r){let e=mr(pr.NUMERIC,C.NUMERIC,r),t=mr(pr.ALPHANUMERIC,C.ALPHANUMERIC,r),n,s;return Cn.isKanjiModeEnabled()?(n=mr(pr.BYTE,C.BYTE,r),s=mr(pr.KANJI,C.KANJI,r)):(n=mr(pr.BYTE_KANJI,C.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 ri(r,e){switch(e){case C.NUMERIC:return Qa.getBitsLength(r);case C.ALPHANUMERIC:return Xa.getBitsLength(r);case C.KANJI:return ec.getBitsLength(r);case C.BYTE:return Za.getBitsLength(r)}}function uf(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 df(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:ja(n.data)}]);break;case C.BYTE:e.push([{data:n.data,mode:C.BYTE,length:ja(n.data)}])}}return e}function hf(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]=ri(t[h].lastCount+l.length,l.mode)-ri(t[h].lastCount,l.mode),t[h].lastCount+=l.length):(t[h]&&(t[h].lastCount=l.length),n[h][u]=ri(l.length,l.mode)+4+C.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 Ja(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)+`.
4
+ Suggested mode is: `+C.toString(n));switch(t===C.KANJI&&!Cn.isKanjiModeEnabled()&&(t=C.BYTE),t){case C.NUMERIC:return new Qa(r);case C.ALPHANUMERIC:return new Xa(r);case C.KANJI:return new ec(r);case C.BYTE:return new Za(r)}}kt.fromArray=function(e){return e.reduce(function(t,n){return typeof n=="string"?t.push(Ja(n,null)):n.data&&t.push(Ja(n.data,n.mode)),t},[])};kt.fromString=function(e,t){let n=tc(e,Cn.isKanjiModeEnabled()),s=df(n),i=hf(s,t),o=lf.find_path(i.map,"start","end"),a=[];for(let c=1;c<o.length-1;c++)a.push(i.table[o[c]].node);return kt.fromArray(uf(a))};kt.rawSplit=function(e){return kt.fromArray(tc(e,Cn.isKanjiModeEnabled()))}});var sc=E(nc=>{"use strict";var In=Le(),ni=bn(),ff=ga(),pf=wa(),mf=ba(),gf=xa(),oi=va(),ai=Vs(),yf=Ia(),Pn=Ua(),wf=Ka(),bf=Ke(),si=rc();function Sf(r,e){let t=r.size,n=gf.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 Af(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 xf(r,e){let t=mf.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=Pn.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=wf.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 kf(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 Ef(r,e,t){let n=new ff;t.forEach(function(c){n.put(c.mode.bit,4),n.put(c.getLength(),bf.getCharCountIndicator(c.mode,r)),c.write(n)});let s=In.getSymbolTotalCodewords(r),i=ai.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 Cf(n,r,e)}function Cf(r,e,t){let n=In.getSymbolTotalCodewords(e),s=ai.getTotalCodewordsCount(e,t),i=n-s,o=ai.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,p=new yf(h),g=0,w=new Array(o),b=new Array(o),S=0,A=new Uint8Array(r.buffer);for(let T=0;T<o;T++){let O=T<c?u:d;w[T]=A.slice(g,g+O),b[T]=p.encode(w[T]),g+=O,S=Math.max(S,O)}let v=new Uint8Array(n),P=0,k,F;for(k=0;k<S;k++)for(F=0;F<o;F++)k<w[F].length&&(v[P++]=w[F][k]);for(k=0;k<h;k++)for(F=0;F<o;F++)v[P++]=b[F][k];return v}function Pf(r,e,t,n){let s;if(Array.isArray(r))s=si.fromArray(r);else if(typeof r=="string"){let l=e;if(!l){let u=si.rawSplit(r);l=Pn.getBestVersionForData(u,t)}s=si.fromString(r,l||40)}else throw new Error("Invalid data");let i=Pn.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(`
5
5
  The chosen QR Code version cannot contain this amount of data.
6
6
  Minimum version required to store current data is: `+i+`.
7
- `);let o=bf(e,t,s),a=En.getSymbolSize(e),c=new cf(a);return pf(c,e),mf(c),gf(c,e),ti(c,t,0),e>=7&&yf(c,e),wf(c,o),isNaN(n)&&(n=ri.getBestMask(c,ti.bind(null,c,t))),ri.applyMask(n,c),ti(c,t,n),{modules:c,version:e,errorCorrectionLevel:t,maskPattern:n,segments:s}}tc.create=function(e,t){if(typeof e>"u"||e==="")throw new Error("No input text");let n=Xs.M,s,i;return typeof t<"u"&&(n=Xs.from(t.errorCorrectionLevel,Xs.M),s=vn.from(t.version),i=ri.from(t.maskPattern),t.toSJISFunc&&En.setToSJISFunction(t.toSJISFunc)),Af(e,s,n,i)}});var si=P(nt=>{"use strict";function nc(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("")}}nt.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:nc(e.color.dark||"#000000ff"),light:nc(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};nt.getScale=function(e,t){return t.width&&t.width>=e+t.margin*2?t.width/(e+t.margin*2):t.scale};nt.getImageWidth=function(e,t){let n=nt.getScale(e,t);return Math.floor((e+t.margin*2)*n)};nt.qrToImageData=function(e,t,n){let s=t.modules.size,i=t.modules.data,o=nt.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 g=Math.floor((u-c)/o),y=Math.floor((d-c)/o);m=l[i[g*s+y]?1:0]}e[h++]=m.r,e[h++]=m.g,e[h++]=m.b,e[h]=m.a}}});var sc=P(kn=>{"use strict";var ii=si();function xf(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 vf(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}kn.render=function(e,t,n){let s=n,i=t;typeof s>"u"&&(!t||!t.getContext)&&(s=t,t=void 0),t||(i=vf()),s=ii.getOptions(s);let o=ii.getImageWidth(e.modules.size,s),a=i.getContext("2d"),c=a.createImageData(o,o);return ii.qrToImageData(c.data,e,s),xf(a,i,o),a.putImageData(c,0,0),i};kn.renderToDataURL=function(e,t,n){let s=n;typeof s>"u"&&(!t||!t.getContext)&&(s=t,t=void 0),s||(s={});let i=kn.render(e,t,s),o=s.type||"image/png",a=s.rendererOpts||{};return i.toDataURL(o,a.quality)}});var ac=P(oc=>{"use strict";var Ef=si();function ic(r,e){let t=r.a/255,n=e+'="'+r.hex+'"';return t<1?n+" "+e+'-opacity="'+t.toFixed(2).slice(1)+'"':n}function oi(r,e,t){let n=r+e;return typeof t<"u"&&(n+=" "+t),n}function kf(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?oi("M",c+t,.5+l+t):oi("m",s,0),s=0,i=!1),c+1<e&&r[a+1]||(n+=oi("h",o),o=0)):s++}return n}oc.render=function(e,t,n){let s=Ef.getOptions(t),i=e.modules.size,o=e.modules.data,a=i+s.margin*2,c=s.color.light.a?"<path "+ic(s.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",l="<path "+ic(s.color.dark,"stroke")+' d="'+kf(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 mr=P(pr=>{"use strict";var Cf=da(),ai=rc(),cc=sc(),Pf=ac();function ci(r,e,t,n,s){let i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!Cf())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=ai.create(t,n);c(r(u,e,n))}catch(u){l(u)}})}try{let c=ai.create(t,n);s(null,r(c,e,n))}catch(c){s(c)}}pr.create=ai.create;pr.toCanvas=ci.bind(null,cc.render);pr.toDataURL=ci.bind(null,cc.renderToDataURL);pr.toString=ci.bind(null,function(r,e,t){return Pf.render(r,t)})});var Ct,li=p(()=>{"use strict";Xe();Ct=class{async createQRBackup(e,t,n={}){let s=n.errorCorrection||"H",i;if(n.password){let l=crypto.getRandomValues(new Uint8Array(32)),u=await Ze(e,n.password,l);i={version:1,type:"encrypted",data:u.encrypted,iv:u.iv,salt:u.salt,iterations:u.iterations,checksum:await te(t)}}else i={version:1,type:"plain",data:e,checksum:await te(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(()=>er(mr()))).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`
7
+ `);let o=Ef(e,t,s),a=In.getSymbolSize(e),c=new pf(a);return Sf(c,e),Af(c),xf(c,e),ii(c,t,0),e>=7&&vf(c,e),kf(c,o),isNaN(n)&&(n=oi.getBestMask(c,ii.bind(null,c,t))),oi.applyMask(n,c),ii(c,t,n),{modules:c,version:e,errorCorrectionLevel:t,maskPattern:n,segments:s}}nc.create=function(e,t){if(typeof e>"u"||e==="")throw new Error("No input text");let n=ni.M,s,i;return typeof t<"u"&&(n=ni.from(t.errorCorrectionLevel,ni.M),s=Pn.from(t.version),i=oi.from(t.maskPattern),t.toSJISFunc&&In.setToSJISFunction(t.toSJISFunc)),Pf(e,s,n,i)}});var ci=E(rt=>{"use strict";function ic(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("")}}rt.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:ic(e.color.dark||"#000000ff"),light:ic(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};rt.getScale=function(e,t){return t.width&&t.width>=e+t.margin*2?t.width/(e+t.margin*2):t.scale};rt.getImageWidth=function(e,t){let n=rt.getScale(e,t);return Math.floor((e+t.margin*2)*n)};rt.qrToImageData=function(e,t,n){let s=t.modules.size,i=t.modules.data,o=rt.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,p=n.color.light;if(u>=c&&d>=c&&u<a-c&&d<a-c){let g=Math.floor((u-c)/o),w=Math.floor((d-c)/o);p=l[i[g*s+w]?1:0]}e[h++]=p.r,e[h++]=p.g,e[h++]=p.b,e[h]=p.a}}});var oc=E(Bn=>{"use strict";var li=ci();function If(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 Bf(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Bn.render=function(e,t,n){let s=n,i=t;typeof s>"u"&&(!t||!t.getContext)&&(s=t,t=void 0),t||(i=Bf()),s=li.getOptions(s);let o=li.getImageWidth(e.modules.size,s),a=i.getContext("2d"),c=a.createImageData(o,o);return li.qrToImageData(c.data,e,s),If(a,i,o),a.putImageData(c,0,0),i};Bn.renderToDataURL=function(e,t,n){let s=n;typeof s>"u"&&(!t||!t.getContext)&&(s=t,t=void 0),s||(s={});let i=Bn.render(e,t,s),o=s.type||"image/png",a=s.rendererOpts||{};return i.toDataURL(o,a.quality)}});var lc=E(cc=>{"use strict";var Tf=ci();function ac(r,e){let t=r.a/255,n=e+'="'+r.hex+'"';return t<1?n+" "+e+'-opacity="'+t.toFixed(2).slice(1)+'"':n}function ui(r,e,t){let n=r+e;return typeof t<"u"&&(n+=" "+t),n}function Rf(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?ui("M",c+t,.5+l+t):ui("m",s,0),s=0,i=!1),c+1<e&&r[a+1]||(n+=ui("h",o),o=0)):s++}return n}cc.render=function(e,t,n){let s=Tf.getOptions(t),i=e.modules.size,o=e.modules.data,a=i+s.margin*2,c=s.color.light.a?"<path "+ac(s.color.light,"fill")+' d="M0 0h'+a+"v"+a+'H0z"/>':"",l="<path "+ac(s.color.dark,"stroke")+' d="'+Rf(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 yr=E(gr=>{"use strict";var Df=fa(),di=sc(),uc=oc(),Ff=lc();function hi(r,e,t,n,s){let i=[].slice.call(arguments,1),o=i.length,a=typeof i[o-1]=="function";if(!a&&!Df())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=di.create(t,n);c(r(u,e,n))}catch(u){l(u)}})}try{let c=di.create(t,n);s(null,r(c,e,n))}catch(c){s(c)}}gr.create=di.create;gr.toCanvas=hi.bind(null,uc.render);gr.toDataURL=hi.bind(null,uc.renderToDataURL);gr.toString=hi.bind(null,function(r,e,t){return Ff.render(r,t)})});var Et,fi=m(()=>{"use strict";Ne();Et=class{async createQRBackup(e,t,n={}){let s=n.errorCorrection||"H",i;if(n.password){let l=crypto.getRandomValues(new Uint8Array(32)),u=await Xe(e,n.password,l);i={version:1,type:"encrypted",data:u.encrypted,iv:u.iv,salt:u.salt,iterations:u.iterations,checksum:await te(t)}}else i={version:1,type:"plain",data:e,checksum:await te(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(()=>Zt(yr()))).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
9
  W3PK QR CODE BACKUP
10
10
  ==================
11
11
 
@@ -81,7 +81,7 @@ If QR code is lost/damaged, you can still recover using:
81
81
 
82
82
  Generated by w3pk Recovery System
83
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(()=>(Xe(),la));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 te(o.address)!==n.checksum)throw new Error("Address checksum mismatch - corrupted QR or wrong password");return{mnemonic:s,ethereumAddress:o.address}}}});function If(){let r=new Uint8Array(1);return crypto.getRandomValues(r),r[0]}function Pn(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(If());for(let a=0;a<t;a++){let c=a+1,l=Cn.evaluatePolynomial(o,c);n[a][s+1]=l}}return n}function In(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]=Cn.interpolate(a)}return i}function Bn(r){return new TextEncoder().encode(r)}function Dn(r){return new TextDecoder().decode(r)}function Tn(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function Rn(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 Oe,Cn,Fn=p(()=>{"use strict";Oe=class Oe{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}};Oe.LOG_TABLE=[],Oe.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++)Oe.EXP_TABLE[n]=t,Oe.LOG_TABLE[t]=n,t=e(t,3);Oe.EXP_TABLE[255]=Oe.EXP_TABLE[0]})();Cn=Oe});var lc,Pt,ui=p(()=>{"use strict";Fn();lc=new Map,Pt=class{constructor(){this.storageKey="w3pk_social_recovery"}getItem(e){return typeof localStorage<"u"?localStorage.getItem(e):lc.get(e)||null}setItem(e,t){typeof localStorage<"u"?localStorage.setItem(e,t):lc.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=Bn(e),o=Pn(i,s,n.length),a=n.map((l,u)=>({id:crypto.randomUUID(),name:l.name,email:l.email,phone:l.phone,shareEncrypted:Tn(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(()=>er(mr()))).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`
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(()=>(Ne(),$s));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 te(o.address)!==n.checksum)throw new Error("Address checksum mismatch - corrupted QR or wrong password");return{mnemonic:s,ethereumAddress:o.address}}}});function Mf(){let r=new Uint8Array(1);return crypto.getRandomValues(r),r[0]}function Rn(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(Mf());for(let a=0;a<t;a++){let c=a+1,l=Tn.evaluatePolynomial(o,c);n[a][s+1]=l}}return n}function Dn(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]=Tn.interpolate(a)}return i}function Fn(r){return new TextEncoder().encode(r)}function Mn(r){return new TextDecoder().decode(r)}function Un(r){return Array.from(r).map(e=>e.toString(16).padStart(2,"0")).join("")}function Nn(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 ze,Tn,Ln=m(()=>{"use strict";ze=class ze{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}};ze.LOG_TABLE=[],ze.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++)ze.EXP_TABLE[n]=t,ze.LOG_TABLE[t]=n,t=e(t,3);ze.EXP_TABLE[255]=ze.EXP_TABLE[0]})();Tn=ze});var dc,Ct,pi=m(()=>{"use strict";Ln();dc=new Map,Ct=class{constructor(){this.storageKey="w3pk_social_recovery"}getItem(e){return typeof localStorage<"u"?localStorage.getItem(e):dc.get(e)||null}setItem(e,t){typeof localStorage<"u"?localStorage.setItem(e,t):dc.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=Fn(e),o=Rn(i,s,n.length),a=n.map((l,u)=>({id:crypto.randomUUID(),name:l.name,email:l.email,phone:l.phone,shareEncrypted:Un(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(()=>Zt(yr()))).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
85
  \u{1F6E1}\uFE0F GUARDIAN RECOVERY SHARE
86
86
 
87
87
  Dear ${e},
@@ -172,13 +172,13 @@ Thank you for being a trusted guardian!
172
172
 
173
173
  NEED HELP?
174
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=>Rn(u.share)),a=In(o,n),c=Dn(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 Mn,uc=p(()=>{"use strict";fn();li();ui();Mn=class{constructor(){this.verificationStorageKey="w3pk_backup_verifications";this.storage=new Qe,this.qrCreator=new Ct,this.socialRecoveryManager=new Pt}async getBackupStatus(e){let t=await this.storage.getBackupsByAddress(e),n=await this.detectPasskeySync(),s=t.map(c=>({id:c.id,method:c.method,location:"local",createdAt:c.createdAt,deviceFingerprint:c.deviceFingerprint})),i=this.getSocialRecoveryStatus(),o=this.getVerificationStatus(e);return{passkeySync:n,recoveryPhrase:{verified:o.verified,verificationCount:o.count,encryptedBackups:s},socialRecovery:i,securityScore:this.calculateSecurityScore(n,s,i,o)}}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}}}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){let i=0;n?.enabled&&(i=20,n.verifiedGuardians>=n.threshold&&(i+=10));let o=0;s?.verified&&(o=10,o+=Math.min(s.count-1,10));let a={passkeyActive:e.enabled?20:0,passkeyMultiDevice:e.deviceCount>1?10:0,phraseVerified:o,encryptedBackup:t.length>0?20:0,socialRecovery:i},c=Object.values(a).reduce((d,h)=>d+h,0),l,u;return c<=20?(l="vulnerable",u='Create encrypted backup to reach "protected" (40+ pts)'):c<=50?(l="protected",u='Set up social recovery to reach "secured" (70+ pts)'):c<=80?(l="secured",u='Enable all methods to reach "fort-knox" (100 pts)'):(l="fort-knox",u="Maximum security achieved!"),{total:c,breakdown:a,level:l,nextMilestone:u}}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.
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=>Nn(u.share)),a=Dn(o,n),c=Mn(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 _n,hc=m(()=>{"use strict";yn();fi();pi();_n=class{constructor(){this.verificationStorageKey="w3pk_backup_verifications";this.storage=new Qe,this.qrCreator=new Et,this.socialRecoveryManager=new Ct}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,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((p,g)=>p+g,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
176
 
177
177
  `,i+=`Available recovery methods:
178
178
  `,n.forEach(o=>{i+=`- ${o.method} (~${o.time})
179
179
  `})):(i=`\u274C Wallet cannot be recovered in this scenario.
180
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 pe={};E(pe,{BackupFileManager:()=>gr});var gr,ce=p(()=>{"use strict";Xe();W();gr=class{async createPasswordBackup(e,t,n){if(!n||n.length<1)throw new Error("Password is required for password-based backup");let s=crypto.getRandomValues(new Uint8Array(32)),i=await Ze(e,n,s),o=await te(t),a={createdAt:new Date().toISOString(),ethereumAddress:t,encryptedMnemonic:i.encrypted,encryptionMethod:"password",passwordEncryption:{salt:i.salt,iv:i.iv,iterations:i.iterations},addressChecksum:o},c=JSON.stringify(a,null,2),l=new Blob([c],{type:"application/json"});return{backupFile:a,json:c,blob:l}}async createPasskeyBackup(e,t,n,s){let i=await Y(n,s),o=await se(e,i),a=await te(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},g=JSON.stringify(m,null,2),y=new Blob([g],{type:"application/json"});return{backupFile:m,json:g,blob:y}}async createHybridBackup(e,t,n,s,i){let o=await Y(s,i),a=await se(e,o),c=crypto.getRandomValues(new Uint8Array(32)),l=await Ze(a,n,c),u=await te(t),h=new TextEncoder().encode(i),m=await crypto.subtle.digest("SHA-256",h),y=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:y,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 restoreWithExistingPasskey(e,t,n){if(e.encryptionMethod==="password")throw new Error("This backup is password-protected. Use restoreWithPassword() 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 Y(t,n);s=await ie(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 te(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 or(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 te(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 or(e.encryptedMnemonic,t,e.passwordEncryption.salt,e.passwordEncryption.iv,e.passwordEncryption.iterations),o=await Y(n,s),a=await ie(i,o),{Wallet:c}=await import("ethers"),l=c.fromPhrase(a);if(await te(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");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 dc=p(()=>{"use strict"});var st={};E(st,{BackupFileManager:()=>gr,BackupManager:()=>Mn,BackupStorage:()=>Qe,QRBackupCreator:()=>Ct,decryptWithPassword:()=>or,deriveAddressChecksum:()=>te,deriveKeyFromPassword:()=>pn,encryptWithPassword:()=>Ze,getDeviceFingerprint:()=>Ee,validatePasswordStrength:()=>ca});var it=p(()=>{"use strict";uc();fn();li();ce();dc();Xe()});var Un={};E(Un,{SocialRecovery:()=>di});var di,Nn=p(()=>{"use strict";Fn();di=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=Bn(s),o=Pn(i,n,t.length),a=t.map((c,l)=>({guardianId:crypto.randomUUID(),guardianName:c.name,shareData:Tn(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=>Rn(l.shareData)),o=In(i,t),a=Dn(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(()=>er(mr()))).toDataURL(s,{errorCorrectionLevel:"H",width:512})}catch(a){console.warn("QR code generation not available:",a)}let o=`
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 de={};x(de,{BackupFileManager:()=>wr});var wr,oe=m(()=>{"use strict";Ne();$();wr=class{async createPasswordBackup(e,t,n){if(!n||n.length<1)throw new Error("Password is required for password-based backup");let s=crypto.getRandomValues(new Uint8Array(32)),i=await Xe(e,n,s),o=await te(t),a={createdAt:new Date().toISOString(),ethereumAddress:t,encryptedMnemonic:i.encrypted,encryptionMethod:"password",passwordEncryption:{salt:i.salt,iv:i.iv,iterations:i.iterations},addressChecksum:o},c=JSON.stringify(a,null,2),l=new Blob([c],{type:"application/json"});return{backupFile:a,json:c,blob:l}}async createPasskeyBackup(e,t,n,s){let i=await ue(n,s),o=await se(e,i),a=await te(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),p={createdAt:new Date().toISOString(),ethereumAddress:t,encryptedMnemonic:o,encryptionMethod:"passkey",credentialId:n,publicKeyFingerprint:h,addressChecksum:a},g=JSON.stringify(p,null,2),w=new Blob([g],{type:"application/json"});return{backupFile:p,json:g,blob:w}}async createHybridBackup(e,t,n,s,i){let o=await ue(s,i),a=await se(e,o),c=crypto.getRandomValues(new Uint8Array(32)),l=await Xe(a,n,c),u=await te(t),h=new TextEncoder().encode(i),p=await crypto.subtle.digest("SHA-256",h),w=Array.from(new Uint8Array(p)).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 restoreWithExistingPasskey(e,t,n){if(e.encryptionMethod==="password")throw new Error("This backup is password-protected. Use restoreWithPassword() 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 ue(t,n);s=await Z(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 te(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 cr(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 te(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 cr(e.encryptedMnemonic,t,e.passwordEncryption.salt,e.passwordEncryption.iv,e.passwordEncryption.iterations),o=await ue(n,s),a=await Z(i,o),{Wallet:c}=await import("ethers"),l=c.fromPhrase(a);if(await te(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");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 fc=m(()=>{"use strict"});var Ie={};x(Ie,{BackupFileManager:()=>wr,BackupManager:()=>_n,BackupStorage:()=>Qe,QRBackupCreator:()=>Et,decryptWithPassword:()=>cr,deriveAddressChecksum:()=>te,deriveKeyFromPassword:()=>wn,encryptWithPassword:()=>Xe,getDeviceFingerprint:()=>xe,validatePasswordStrength:()=>da});var Be=m(()=>{"use strict";hc();yn();fi();oe();fc();Ne()});var mc={};x(mc,{extractRS:()=>pc});function pc(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 mi=m(()=>{"use strict"});var Kn={};x(Kn,{SocialRecovery:()=>gi});var gi,On=m(()=>{"use strict";Ln();gi=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=Fn(s),o=Rn(i,n,t.length),a=t.map((c,l)=>({guardianId:crypto.randomUUID(),guardianName:c.name,shareData:Un(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=>Nn(l.shareData)),o=Dn(i,t),a=Mn(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(()=>Zt(yr()))).toDataURL(s,{errorCorrectionLevel:"H",width:512})}catch(a){console.warn("QR code generation not available:",a)}let o=`
182
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
183
  W3PK GUARDIAN RECOVERY SHARE
184
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
@@ -220,7 +220,7 @@ ${e.shareData}
220
220
  Generated by w3pk - Web3 Passkey SDK
221
221
  https://github.com/w3hc/w3pk
222
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 pc={};E(pc,{authenticateWithPasskey:()=>fc,promptPasskeySelection:()=>hc});async function hc(){try{let r=new R,e=Fe(),t=L(e),n=[];try{let c=await r.getAllCredentials();c.length>0&&(n=c.map(l=>({id:l.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(c=>({id:L(c.id),type:c.type,transports:c.transports})));let i=await navigator.credentials.get({publicKey:s});if(!i)throw new K("No passkey selected. Please select a passkey to continue with sync.");let o=i.id,a=await r.getCredentialById(o);return a?{credentialId:o,publicKey:a.publicKey,ethereumAddress:a.ethereumAddress}:{credentialId:o,publicKey:"",ethereumAddress:void 0}}catch(r){throw r?.name==="NotAllowedError"?new K("Passkey selection was cancelled. Please try again and select your passkey."):r instanceof K?r:new K(`Failed to select passkey: ${r instanceof Error?r.message:"Unknown error"}`,r)}}async function fc(r){try{let e=Fe(),n={challenge:L(e),rpId:window.location.hostname,userVerification:"required",timeout:6e4,allowCredentials:[{id:L(r),type:"public-key",transports:["internal","hybrid","usb","nfc","ble"]}]},s=await navigator.credentials.get({publicKey:n});if(!s)throw new K("Authentication failed - no credential returned");return s}catch(e){throw e?.name==="NotAllowedError"?new K("Authentication was cancelled or the passkey is not available on this device."):new K(`Passkey authentication failed: ${e instanceof Error?e.message:"Unknown error"}`,e)}}var hi=p(()=>{"use strict";G();Ue();fe();W()});var Ln={};E(Ln,{DeviceSyncManager:()=>yr});var yr,wr=p(()=>{"use strict";yr=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){let{BackupFileManager:i}=await Promise.resolve().then(()=>(ce(),pe));return new i().createPasskeyBackup(e,t,n,s)}async importFromSync(e,t,n){let{BackupFileManager:s}=await Promise.resolve().then(()=>(ce(),pe)),o=await new s().restoreWithExistingPasskey(e,t,n);return await this.updateSyncInfo(o.ethereumAddress),o}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(()=>er(mr())),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(),pe));return new t().parseBackupFile(e)}}});var _n,mc=p(()=>{"use strict";Xe();_n=class{async createSyncPackage(e,t,n){let s=await Ee(),{deriveEncryptionKeyAuto:i,encryptData:o}=await Promise.resolve().then(()=>(W(),Me)),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{deriveEncryptionKeyAuto:s,decryptData:i}=await Promise.resolve().then(()=>(W(),Me)),o=await s(t,n),a=await i(e.encryptedData,o),c=await Ee();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`
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 wc={};x(wc,{authenticateWithPasskey:()=>yc,promptPasskeySelection:()=>gc});async function gc(){try{let r=new R,e=Fe(),t=L(e),n=[];try{let c=await r.getAllCredentials();c.length>0&&(n=c.map(l=>({id:l.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(c=>({id:L(c.id),type:c.type,transports:c.transports})));let i=await navigator.credentials.get({publicKey:s});if(!i)throw new z("No passkey selected. Please select a passkey to continue with sync.");let o=i.id,a=await r.getCredentialById(o);return a?{credentialId:o,publicKey:a.publicKey,ethereumAddress:a.ethereumAddress}:{credentialId:o,publicKey:"",ethereumAddress:void 0}}catch(r){throw r?.name==="NotAllowedError"?new z("Passkey selection was cancelled. Please try again and select your passkey."):r instanceof z?r:new z(`Failed to select passkey: ${r instanceof Error?r.message:"Unknown error"}`,r)}}async function yc(r){try{let e=Fe(),n={challenge:L(e),rpId:window.location.hostname,userVerification:"required",timeout:6e4,allowCredentials:[{id:L(r),type:"public-key",transports:["internal","hybrid","usb","nfc","ble"]}]},s=await navigator.credentials.get({publicKey:n});if(!s)throw new z("Authentication failed - no credential returned");return s}catch(e){throw e?.name==="NotAllowedError"?new z("Authentication was cancelled or the passkey is not available on this device."):new z(`Passkey authentication failed: ${e instanceof Error?e.message:"Unknown error"}`,e)}}var yi=m(()=>{"use strict";G();Ue();we();$()});var zn={};x(zn,{DeviceSyncManager:()=>br});var br,Sr=m(()=>{"use strict";br=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){let{BackupFileManager:i}=await Promise.resolve().then(()=>(oe(),de));return new i().createPasskeyBackup(e,t,n,s)}async importFromSync(e,t,n){let{BackupFileManager:s}=await Promise.resolve().then(()=>(oe(),de)),o=await new s().restoreWithExistingPasskey(e,t,n);return await this.updateSyncInfo(o.ethereumAddress),o}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(()=>Zt(yr())),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(()=>(oe(),de));return new t().parseBackupFile(e)}}});var Wn,bc=m(()=>{"use strict";Ne();Wn=class{async createSyncPackage(e,t,n){let s=await xe(),{deriveEncryptionKeyFromWebAuthn:i,encryptData:o}=await Promise.resolve().then(()=>($(),Me)),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(()=>($(),Me)),o=await s(t,n),a=await i(e.encryptedData,o),c=await xe();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
224
  HOW CROSS-DEVICE SYNC WORKS
225
225
  ===========================
226
226
 
@@ -236,7 +236,7 @@ Layer 1: Passkey (Auto-Syncs)
236
236
  Layer 2: Encrypted Wallet (In Browser)
237
237
  --------------------------------------
238
238
  \u2713 Your 12-word mnemonic (encrypted)
239
- \u2713 Stored in browser's IndexedDB
239
+ \u2713 Stored in browser's localStorage
240
240
  \u2713 Can ONLY be decrypted with passkey
241
241
  \u2713 Requires authentication to access
242
242
 
@@ -248,7 +248,7 @@ Device 1 (iPhone) iCloud Keychain Device 2 (Mac)
248
248
  |-- Passkey Created -------->| |
249
249
  | | |
250
250
  |-- Wallet Encrypted --------| |
251
- | (in IndexedDB) | |
251
+ | (in localStorage) | |
252
252
  | | |
253
253
  | |<----- Login on Mac -----|
254
254
  | | |
@@ -277,7 +277,7 @@ What Gets Synced:
277
277
  What Stays Local:
278
278
  ----------------
279
279
 
280
- \u2717 Encrypted mnemonic (in IndexedDB)
280
+ \u2717 Encrypted mnemonic (in localStorage)
281
281
  - Must authenticate to decrypt
282
282
  - Requires passkey access
283
283
  - Platform-specific storage
@@ -301,14 +301,14 @@ If passkey doesn't sync:
301
301
  Think of it like:
302
302
  \u{1F511} Passkey = Your car key (syncs via keychain)
303
303
  \u{1F697} Wallet = Your car (locked, needs key to start)
304
- `}}});var Kn,gc=p(()=>{"use strict";Xe();Kn=class{constructor(){this.storageKey="w3pk_devices"}async registerDevice(){let e={id:await Ee(),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 Ee();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 Ee();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 Ee(),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}):
304
+ `}}});var $n,Sc=m(()=>{"use strict";Ne();$n=class{constructor(){this.storageKey="w3pk_devices"}async registerDevice(){let e={id:await xe(),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 xe();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 xe();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 xe(),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
305
 
306
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
307
  `,t+=` Platform: ${this.getPlatformName(n.platform)}
308
308
  `,t+=` Last active: ${o}
309
309
  `,t+=` ${n.canRevoke?"":"(Current device)"}
310
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 On,yc=p(()=>{"use strict";On=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`
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 Hn,Ac=m(()=>{"use strict";Hn=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
312
  \u{1F34E} Apple iCloud Keychain
313
313
 
314
314
  Your passkey automatically syncs across:
@@ -387,7 +387,7 @@ This ensures you can recover if:
387
387
  - Device is lost/stolen
388
388
  - Device is damaged
389
389
  - 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 wc=p(()=>{"use strict"});var bc={};E(bc,{DeviceManager:()=>Kn,DeviceSyncManager:()=>yr,PlatformDetector:()=>On,VaultSync:()=>_n});var Sc=p(()=>{"use strict";mc();gc();yc();wr();wc()});var br,Ac=p(()=>{"use strict";br=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`
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 xc=m(()=>{"use strict"});var vc={};x(vc,{DeviceManager:()=>$n,DeviceSyncManager:()=>br,PlatformDetector:()=>Hn,VaultSync:()=>Wn});var kc=m(()=>{"use strict";bc();Sc();Ac();Sr();xc()});var Ar,Ec=m(()=>{"use strict";Ar=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`
391
391
  \u274C WALLET CANNOT BE RECOVERED
392
392
 
393
393
  Scenario: ${e.description}
@@ -503,7 +503,7 @@ SECURITY SCORE: ${o}/100 (${a})
503
503
  `,c+=` 3. Set up social recovery (+20-30 pts)
504
504
 
505
505
  `,c+=`Target: Reach at least 50/100 for basic protection.
506
- `),{scenarios:n,overallScore:i,securityScore:o,feedback:c}}}});function xc(r){return zn[r]||null}function vc(){return Object.keys(zn)}function Ec(r){let e=r.toLowerCase();return Object.values(zn).filter(t=>t.title.toLowerCase().includes(e)||t.content.toLowerCase().includes(e))}var zn,kc=p(()=>{"use strict";zn={whatIsPasskey:{title:"What is a Passkey?",content:`
506
+ `),{scenarios:n,overallScore:i,securityScore:o,feedback:c}}}});function Cc(r){return qn[r]||null}function Pc(){return Object.keys(qn)}function Ic(r){let e=r.toLowerCase();return Object.values(qn).filter(t=>t.title.toLowerCase().includes(e)||t.content.toLowerCase().includes(e))}var qn,Bc=m(()=>{"use strict";qn={whatIsPasskey:{title:"What is a Passkey?",content:`
507
507
  Think of a passkey like your house smart lock:
508
508
 
509
509
  \u{1F511} Traditional Key (Password):
@@ -586,7 +586,7 @@ What DOESN'T sync:
586
586
  LAYER 2: ENCRYPTED WALLET (Local)
587
587
  ----------------------------------
588
588
  Your wallet is encrypted and stored in:
589
- - Browser's IndexedDB
589
+ - Browser's localStorage
590
590
  - Encrypted with passkey-derived key
591
591
  - Can ONLY be decrypted with passkey
592
592
 
@@ -947,23 +947,23 @@ Good: 70 pts (backup + social recovery)
947
947
  Excellent: 80+ pts (all layers enabled)
948
948
 
949
949
  Remember: Higher score = Lower chance of loss!
950
- `}}});var Wn={};E(Wn,{RecoverySimulator:()=>br,educationalModules:()=>zn,getAllTopics:()=>vc,getExplainer:()=>xc,searchExplainers:()=>Ec});var Sr=p(()=>{"use strict";Ac();kc()});var qn={};E(qn,{deriveMLKemKeypair:()=>$n,mlkemDecrypt:()=>mi,mlkemDecryptWithKey:()=>Pc,mlkemEncrypt:()=>pi,mlkemEncryptWithKey:()=>Cc});import{createMlKem1024 as fi}from"mlkem";import{hkdf as Bf}from"@noble/hashes/hkdf.js";import{sha256 as Df}from"@noble/hashes/sha2.js";function De(r){r.fill(0)}function It(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 ze(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 $n(r,e="mlkem-v1"){let t=await fi(),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=Bf(Df,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{De(s),De(n)}}async function pi(r,e){let t=await fi(),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"},!1,["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),g=[];for(let y of n){let b=typeof y=="string"?ze(y):y;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=A.slice(0,32),k=new Uint8Array(32);for(let x=0;x<32;x++)k[x]=s[x]^v[x];let C=new Uint8Array(S.length+k.length);C.set(S,0),C.set(k,S.length),g.push({publicKey:It(b),ciphertext:It(C)})}finally{De(A)}}return{recipients:g,encryptedData:It(h),iv:It(i),authTag:It(m)}}finally{De(s)}}async function mi(r,e,t){let n=await fi(),s=typeof e=="string"?ze(e):e;if(s.length!==3168)throw new Error(`Invalid ML-KEM private key size: ${s.length} (expected 3168)`);let i=ze(r.encryptedData),o=ze(r.iv),a=ze(r.authTag),c=null;if(t){let y=typeof t=="string"?ze(t):t,b=It(y);if(c=r.recipients.find(S=>S.publicKey===b),!c)throw new Error("Public key not found in recipients list")}else{for(let y of r.recipients)try{let b=ze(y.ciphertext),S=n.decap(b,s);c=y,De(S);break}catch{continue}if(!c)throw new Error("No matching recipient found for this private key")}let l=ze(c.ciphertext),u=1568,d=l.slice(0,u),h=l.slice(u),m=n.decap(d,s),g=null;try{let y=m.slice(0,32);g=new Uint8Array(32);for(let x=0;x<32;x++)g[x]=h[x]^y[x];let b=await crypto.subtle.importKey("raw",g,{name:"AES-GCM"},!1,["decrypt"]),S=i.length+a.length,A=new ArrayBuffer(S),v=new Uint8Array(A);v.set(i,0),v.set(a,i.length);let k=await crypto.subtle.decrypt({name:"AES-GCM",iv:o.buffer,tagLength:128},b,A);return new TextDecoder().decode(k)}finally{De(m),g&&De(g)}}async function Cc(r,e,t,n="mlkem-v1"){let s=await $n(e,n);try{let i=[s.publicKey,...t];return await pi(r,i)}finally{De(s.privateKey)}}async function Pc(r,e,t="mlkem-v1"){let n=await $n(e,t);try{return await mi(r,n.privateKey,n.publicKey)}finally{De(n.privateKey)}}var Ar=p(()=>{"use strict"});function Tf(r){return r[Symbol.asyncIterator]!=null}function Rf(r){if(Tf(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var gi,Dc=p(()=>{"use strict";gi=Rf});function Ff(r){return r[Symbol.asyncIterator]!=null}function Mf(r,e=1){return e=Number(e),Ff(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 Hn,yi=p(()=>{"use strict";Hn=Mf});async function*vr(r,e=1){for await(let t of Hn(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 wi=p(()=>{"use strict";yi()});function Te(r=0){return new Uint8Array(r)}function re(r=0){return new Uint8Array(r)}var ot=p(()=>{"use strict"});function Uf(r){return r?.buffer instanceof ArrayBuffer}function Tc(r){if(Uf(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}var Rc=p(()=>{"use strict"});function Er(r,e){e==null&&(e=r.reduce((s,i)=>s+i.length,0));let t=re(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return Tc(t)}var bi=p(()=>{"use strict";ot();Rc()});function Fc(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 Mc=p(()=>{"use strict"});function Uc(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 Vn(r){return!!r?.[Lc]}var Lc,Nc,Bt,_c=p(()=>{"use strict";ot();bi();Mc();Lc=Symbol.for("@achingbrain/uint8arraylist");Bt=class r{constructor(...e){f(this,"bufs");f(this,"length");f(this,Nc,!0);this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[(Nc=Lc,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(Vn(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(Vn(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=Uc(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Uc(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(Vn(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 Er(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:Er(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(!Vn(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=re(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=Te(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=Te(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=Te(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=re(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=Te(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=Te(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=Te(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=Te(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=Te(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(!Fc(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 Si,Gn,Yn,Kc,jn,Oc,zc,Wc,$c,qc,Hc,Vc,kr=p(()=>{"use strict";Si=BigInt(34),Gn=8,Yn=262144,Kc="links-bytes",jn=262144,Oc=1048576,zc=50,Wc=10,$c=!0,qc=!0,Hc=!1,Vc="file"});var Gc,Yc=p(()=>{"use strict";_c();kr();Gc=(r={})=>{let e=r.chunkSize??jn;return async function*(n){let s=new Bt,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 Bt,i=0;else{let l=new Bt;l.append(s.sublist(e)),s=l,i-=e}(!o||i>0)&&(yield s.subarray(0,i))}}});function jc(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 me(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return at(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return at(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function Jc(r){return new TextEncoder().encode(r)}function Qc(r){return new TextDecoder().decode(r)}function Nf(r){return r?.buffer instanceof ArrayBuffer}function at(r){return Nf(r)?r:r.slice()}var b0,We=p(()=>{"use strict";b0=new Uint8Array(0)});function Lf(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(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var y=0,b=0,S=0,A=g.length;S!==A&&g[S]===0;)S++,y++;for(var v=(A-S)*u+1>>>0,k=new Uint8Array(v);S!==A;){for(var C=g[S],x=0,T=v-1;(C!==0||x<b)&&T!==-1;T--,x++)C+=256*k[T]>>>0,k[T]=C%a>>>0,C=C/a>>>0;if(C!==0)throw new Error("Non-zero carry");b=x,S++}for(var O=v-b;O!==v&&k[O]===0;)O++;for(var Pe=c.repeat(y);O<v;++O)Pe+=r.charAt(k[O]);return Pe}function h(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var y=0;if(g[y]!==" "){for(var b=0,S=0;g[y]===c;)b++,y++;for(var A=(g.length-y)*l+1>>>0,v=new Uint8Array(A);g[y];){var k=t[g.charCodeAt(y)];if(k===255)return;for(var C=0,x=A-1;(k!==0||C<S)&&x!==-1;x--,C++)k+=a*v[x]>>>0,v[x]=k%256>>>0,k=k/256>>>0;if(k!==0)throw new Error("Non-zero carry");S=C,y++}if(g[y]!==" "){for(var T=A-S;T!==A&&v[T]===0;)T++;for(var O=new Uint8Array(b+(A-T)),Pe=b;T!==A;)O[Pe++]=v[T++];return O}}}function m(g){var y=h(g);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:m}}var _f,Kf,Xc,el=p(()=>{"use strict";_f=Lf,Kf=_f,Xc=Kf});function tl(r,e){return new vi({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}function Dt({name:r,prefix:e,encode:t,decode:n}){return new Ei(r,e,t,n)}function $e({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=Xc(t,r);return Dt({prefix:e,name:r,encode:n,decode:i=>me(s(i))})}function Of(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 zf(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 Wf(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 s=Wf(n);return Dt({prefix:e,name:r,encode(i){return zf(i,n,t)},decode(i){return Of(i,s,t,r)}})}var Ai,xi,vi,Ei,ge=p(()=>{"use strict";We();el();Ai=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")}},xi=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 tl(this,e)}},vi=class{constructor(e){f(this,"decoders");this.decoders=e}or(e){return tl(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`)}};Ei=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 Ai(e,t,n),this.decoder=new xi(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}});var ki={};E(ki,{base32:()=>J,base32hex:()=>Vf,base32hexpad:()=>Yf,base32hexpadupper:()=>jf,base32hexupper:()=>Gf,base32pad:()=>qf,base32padupper:()=>Hf,base32upper:()=>$f,base32z:()=>Jf});var J,$f,qf,Hf,Vf,Gf,Yf,jf,Jf,Cr=p(()=>{"use strict";ge();J=N({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),$f=N({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),qf=N({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Hf=N({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Vf=N({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),Gf=N({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),Yf=N({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),jf=N({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),Jf=N({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var Ci={};E(Ci,{base36:()=>Pr,base36upper:()=>Qf});var Pr,Qf,Pi=p(()=>{"use strict";ge();Pr=$e({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),Qf=$e({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var Ii={};E(Ii,{base58btc:()=>le,base58flickr:()=>Zf});var le,Zf,Jn=p(()=>{"use strict";ge();le=$e({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),Zf=$e({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});function sl(r,e,t){e=e||[],t=t||0;for(var n=t;r>=rp;)e[t++]=r&255|rl,r/=128;for(;r&tp;)e[t++]=r&255|rl,r>>>=7;return e[t]=r|0,sl.bytes=t-n+1,e}function Bi(r,n){var t=0,n=n||0,s=0,i=n,o,a=r.length;do{if(i>=a)throw Bi.bytes=0,new RangeError("Could not decode varint");o=r[i++],t+=s<28?(o&nl)<<s:(o&nl)*Math.pow(2,s),s+=7}while(o>=sp);return Bi.bytes=i-n,t}var Xf,rl,ep,tp,rp,np,sp,nl,ip,op,ap,cp,lp,up,dp,hp,fp,pp,mp,gp,Ir,il=p(()=>{"use strict";Xf=sl,rl=128,ep=127,tp=~ep,rp=Math.pow(2,31);np=Bi,sp=128,nl=127;ip=Math.pow(2,7),op=Math.pow(2,14),ap=Math.pow(2,21),cp=Math.pow(2,28),lp=Math.pow(2,35),up=Math.pow(2,42),dp=Math.pow(2,49),hp=Math.pow(2,56),fp=Math.pow(2,63),pp=function(r){return r<ip?1:r<op?2:r<ap?3:r<cp?4:r<lp?5:r<up?6:r<dp?7:r<hp?8:r<fp?9:10},mp={encode:Xf,decode:np,encodingLength:pp},gp=mp,Ir=gp});function Br(r,e=0){return[Ir.decode(r,e),Ir.decode.bytes]}function Tt(r,e,t=0){return Ir.encode(r,e,t),e}function Rt(r){return Ir.encodingLength(r)}var Zn=p(()=>{"use strict";il()});function Mt(r,e){let t=e.byteLength,n=Rt(r),s=n+Rt(t),i=new Uint8Array(s+t);return Tt(r,i,0),Tt(t,i,n),i.set(e,s),new Ft(r,t,e,i)}function Xn(r){let e=me(r),[t,n]=Br(e),[s,i]=Br(e.subarray(n)),o=e.subarray(n+i);if(o.byteLength!==s)throw new Error("Incorrect length");return new Ft(t,s,o,e)}function ol(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&jc(r.bytes,t.bytes)}}var Ft,Nt=p(()=>{"use strict";We();Zn();Ft=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=at(n),this.bytes=at(s)}}});var Di=p(()=>{"use strict"});function al(r,e){let{bytes:t,version:n}=r;return n===0?wp(t,Ti(r),e??le.encoder):bp(t,Ti(r),e??J.encoder)}function Ti(r){let e=cl.get(r);if(e==null){let t=new Map;return cl.set(r,t),t}return e}function yp(r,e){switch(r[0]){case"Q":{let t=e??le;return[le.prefix,t.decode(`${le.prefix}${r}`)]}case le.prefix:{let t=e??le;return[le.prefix,t.decode(r)]}case J.prefix:{let t=e??J;return[J.prefix,t.decode(r)]}case Pr.prefix:{let t=e??Pr;return[Pr.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 wp(r,e,t){let{prefix:n}=t;if(n!==le.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 bp(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 ll(r,e,t){let n=Rt(r),s=n+Rt(e),i=new Uint8Array(s+t.byteLength);return Tt(r,i,0),Tt(e,i,n),i.set(t,s),i}var cl,ul,$,Dr,Sp,Ap,ct=p(()=>{"use strict";Cr();Pi();Jn();We();Nt();Zn();Di();cl=new WeakMap;$=class r{constructor(e,t,n,s){f(this,"code");f(this,"version");f(this,"multihash");f(this,"bytes");f(this,"/");f(this,ul,"CID");this.code=t,this.version=e,this.multihash=n,this.bytes=at(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!==Dr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Sp)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=Mt(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&&ol(e.multihash,n.multihash)}toString(e){return al(this,e)}toJSON(){return{"/":al(this)}}link(){return this}[(ul=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??ll(n,s,i.bytes))}else if(t[Ap]===!0){let{version:n,multihash:s,code:i}=t,o=Xn(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!==Dr)throw new Error(`Version 0 CID must use dag-pb (code: ${Dr}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=ll(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Dr,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=me(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 Ft(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]=Br(e.subarray(t));return t+=h,d},s=n(),i=Dr;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]=yp(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 Ti(i).set(n,e),i}};Dr=112,Sp=18;Ap=Symbol.for("@ipld/js-cid/CID")});function Ri(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 es(r,e){let t;[t,e]=Ri(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 dl(r,e){let t;return[t,e]=Ri(r,e),[t&7,t>>3,e]}function vp(r){let e={},t=r.length,n=0;for(;n<t;){let s,i;if([s,i,n]=dl(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]=es(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]=es(r,n),e.Name=xp.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]=Ri(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 hl(r){let e=r.length,t=0,n,s=!1,i;for(;t<e;){let a,c;if([a,c,t]=dl(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]=es(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]=es(r,t),n.push(vp(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 xp,fl=p(()=>{"use strict";xp=new TextDecoder});function kp(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=Tr(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=ml.encode(r.Name);t-=n.length,e.set(n,t),t=Tr(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=Tr(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function gl(r){let e=Pp(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=Tr(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let s=r.Links.length-1;s>=0;s--){let i=kp(r.Links[s],t.subarray(0,n));n-=i,n=Tr(t,n,i)-1,t[n]=18}return t}function Cp(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+Lt(t)}if(typeof r.Name=="string"){let t=ml.encode(r.Name).length;e+=1+t+Lt(t)}return typeof r.Tsize=="number"&&(e+=1+Lt(r.Tsize)),e}function Pp(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+Lt(t)}if(r.Links)for(let t of r.Links){let n=Cp(t);e+=1+n+Lt(n)}return e}function Tr(r,e,t){e-=Lt(t);let n=e;for(;t>=Ep;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function Lt(r){return r%2===0&&r++,Math.floor((Ip(r)+6)/7)}function Ip(r){let e=0;return r>=pl&&(r=Math.floor(r/pl),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+Bp[r]}var ml,pl,Ep,Bp,yl=p(()=>{"use strict";ml=new TextEncoder,pl=2**32,Ep=2**31;Bp=[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 bl(r,e){if(r===e)return 0;let t=r.Name?Fi.encode(r.Name):[],n=e.Name?Fi.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 wl(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function Sl(r){if(typeof r.asCID=="object"){let t=$.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=$.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=$.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=$.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 Q(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=Fi.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(Sl),e.Links.sort(bl);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function Mi(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!wl(r,Dp))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(!wl(t,Tp))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&&bl(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function Al(r,e=[]){return Q({Data:r,Links:e})}function xl(r,e,t){return Sl({Hash:t,Name:r,Tsize:e})}function vl(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var Dp,Tp,Fi,El=p(()=>{"use strict";ct();Dp=["Data","Links"],Tp=["Hash","Name","Tsize"],Fi=new TextEncoder});var Rr={};E(Rr,{code:()=>Fp,createLink:()=>xl,createNode:()=>Al,decode:()=>Mp,encode:()=>Z,name:()=>Rp,prepare:()=>Q,validate:()=>Mi});function Z(r){Mi(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),gl(e)}function Mp(r){let e=vl(r),t=hl(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(s=>{let i={};try{i.Hash=$.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 Rp,Fp,lt=p(()=>{"use strict";ct();fl();yl();El();Rp="dag-pb",Fp=112});var _t,Fr,Ui=p(()=>{"use strict";_t=class _t extends Error{constructor(t="Invalid type"){super(t);f(this,"name",_t.name);f(this,"code",_t.code)}};f(_t,"name","InvalidTypeError"),f(_t,"code","ERR_INVALID_TYPE");Fr=_t});function Mr(r){if(r<Up)return 1;if(r<Np)return 2;if(r<Lp)return 3;if(r<kl)return 4;if(r<Cl)return 5;if(r<Pl)return 6;if(r<Il)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function Bl(r,e,t=0){switch(Mr(r)){case 8:e[t++]=r&255|q,r/=128;case 7:e[t++]=r&255|q,r/=128;case 6:e[t++]=r&255|q,r/=128;case 5:e[t++]=r&255|q,r/=128;case 4:e[t++]=r&255|q,r>>>=7;case 3:e[t++]=r&255|q,r>>>=7;case 2:e[t++]=r&255|q,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Dl(r,e){let t=r[e],n=0;if(n+=t&qe,t<q||(t=r[e+1],n+=(t&qe)<<7,t<q)||(t=r[e+2],n+=(t&qe)<<14,t<q)||(t=r[e+3],n+=(t&qe)<<21,t<q)||(t=r[e+4],n+=(t&qe)*kl,t<q)||(t=r[e+5],n+=(t&qe)*Cl,t<q)||(t=r[e+6],n+=(t&qe)*Pl,t<q)||(t=r[e+7],n+=(t&qe)*Il,t<q))return n;throw new RangeError("Could not decode varint")}var Up,Np,Lp,kl,Cl,Pl,Il,q,qe,Ni=p(()=>{"use strict";ot();Up=Math.pow(2,7),Np=Math.pow(2,14),Lp=Math.pow(2,21),kl=Math.pow(2,28),Cl=Math.pow(2,35),Pl=Math.pow(2,42),Il=Math.pow(2,49),q=128,qe=127});function _p(r){return r.buffer instanceof ArrayBuffer}function Tl(r){return _p(r)?r:r.slice()}var Rl=p(()=>{"use strict"});function Fl(r,e,t){Li[0]=r,e[t]=He[0],e[t+1]=He[1],e[t+2]=He[2],e[t+3]=He[3]}function Ml(r,e){return He[0]=r[e],He[1]=r[e+1],He[2]=r[e+2],He[3]=r[e+3],Li[0]}function Ul(r,e,t){_i[0]=r,e[t]=z[0],e[t+1]=z[1],e[t+2]=z[2],e[t+3]=z[3],e[t+4]=z[4],e[t+5]=z[5],e[t+6]=z[6],e[t+7]=z[7]}function Nl(r,e){return z[0]=r[e],z[1]=r[e+1],z[2]=r[e+2],z[3]=r[e+3],z[4]=r[e+4],z[5]=r[e+5],z[6]=r[e+6],z[7]=r[e+7],_i[0]}var Li,He,_i,z,Ki=p(()=>{"use strict";Li=new Float32Array([-0]),He=new Uint8Array(Li.buffer);_i=new Float64Array([-0]),z=new Uint8Array(_i.buffer)});var Kp,Op,ne,ut,Ll,Oi=p(()=>{"use strict";Kp=BigInt(Number.MAX_SAFE_INTEGER),Op=BigInt(Number.MIN_SAFE_INTEGER),ne=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 ut;if(e<Kp&&e>Op)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>Ll&&(s=0n,++n>Ll&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return ut;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):ut}},ut=new ne(0,0);ut.toBigInt=function(){return 0n};ut.zzEncode=ut.zzDecode=function(){return this};ut.length=function(){return 1};Ll=4294967296n});function _l(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 Kl(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 zi(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 Wi=p(()=>{"use strict"});function ye(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function ts(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}function Ur(r){return new $i(r instanceof Uint8Array?r:r.subarray())}var $i,rs=p(()=>{"use strict";Ni();Rl();Ki();Oi();Wi();$i=class{constructor(e){f(this,"buf");f(this,"pos");f(this,"len");f(this,"_slice",Uint8Array.prototype.subarray);this.buf=Tl(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,ye(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 ye(this,4);return ts(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ye(this,4);return ts(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ye(this,4);let e=Ml(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ye(this,4);let e=Nl(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 ye(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Kl(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw ye(this,e);this.pos+=e}else do if(this.pos>=this.len)throw ye(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 ne(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 ye(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 ye(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 ye(this,8);let e=ts(this.buf,this.pos+=4),t=ts(this.buf,this.pos+=4);return new ne(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=Dl(this.buf,this.pos);return this.pos+=Mr(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 Nr(r,e,t){let n=Ur(r);return e.decode(n,void 0,t)}var zl=p(()=>{"use strict";rs()});var qi={};E(qi,{base10:()=>zp});var zp,Wl=p(()=>{"use strict";ge();zp=$e({prefix:"9",name:"base10",alphabet:"0123456789"})});var Hi={};E(Hi,{base16:()=>Wp,base16upper:()=>$p});var Wp,$p,$l=p(()=>{"use strict";ge();Wp=N({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),$p=N({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var Vi={};E(Vi,{base2:()=>qp});var qp,ql=p(()=>{"use strict";ge();qp=N({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var Gi={};E(Gi,{base256emoji:()=>jp});function Gp(r){return r.reduce((e,t)=>(e+=Hp[t],e),"")}function Yp(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=Vp[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var Hl,Hp,Vp,jp,Vl=p(()=>{"use strict";ge();Hl=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}"),Hp=Hl.reduce((r,e,t)=>(r[t]=e,r),[]),Vp=Hl.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);jp=Dt({prefix:"\u{1F680}",name:"base256emoji",encode:Gp,decode:Yp})});var ji={};E(ji,{base64:()=>Yi,base64pad:()=>Jp,base64url:()=>Qp,base64urlpad:()=>Zp});var Yi,Jp,Qp,Zp,Ji=p(()=>{"use strict";ge();Yi=N({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),Jp=N({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),Qp=N({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),Zp=N({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var Qi={};E(Qi,{base8:()=>Xp});var Xp,Gl=p(()=>{"use strict";ge();Xp=N({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var Zi={};E(Zi,{identity:()=>em});var em,Yl=p(()=>{"use strict";We();ge();em=Dt({prefix:"\0",name:"identity",encode:r=>Qc(r),decode:r=>Jc(r)})});var yb,wb,jl=p(()=>{"use strict";yb=new TextEncoder,wb=new TextDecoder});var Ot={};E(Ot,{code:()=>Kt,decode:()=>sm,encode:()=>nm,name:()=>rm});function nm(r){return me(r)}function sm(r){return me(r)}var rm,Kt,Lr=p(()=>{"use strict";We();rm="raw",Kt=85});var Xi={};E(Xi,{identity:()=>am});function om(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 Mt(Jl,Ql(r))}var Jl,im,Ql,am,Zl=p(()=>{"use strict";We();Nt();Jl=0,im="identity",Ql=me;am={code:Jl,name:im,encode:Ql,digest:om}});function dt({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new eo(r,e,t,n,s)}function Xl(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 Mt(e,r)}var cm,eo,ns=p(()=>{"use strict";Nt();cm=20;eo=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??cm,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?Xl(n,this.code,t?.truncate):n.then(s=>Xl(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}}});var ro={};E(ro,{sha256:()=>to,sha512:()=>lm});function tu(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var to,lm,no=p(()=>{"use strict";ns();to=dt({name:"sha2-256",code:18,encode:tu("SHA-256")}),lm=dt({name:"sha2-512",code:19,encode:tu("SHA-512")})});var ru=p(()=>{"use strict"});var nu=p(()=>{"use strict"});var su=p(()=>{"use strict"});var iu=p(()=>{"use strict"});var ou=p(()=>{"use strict";ru();nu();su();Di();iu()});var au=p(()=>{"use strict";We();ct();Nt();ns();Zn();ou()});var so,Rb,cu=p(()=>{"use strict";Wl();$l();ql();Vl();Cr();Pi();Jn();Ji();Gl();Yl();jl();Lr();Zl();no();au();so={...Zi,...Vi,...Qi,...qi,...Hi,...ki,...Ci,...Ii,...ji,...Gi},Rb={...ro,...Xi}});function uu(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var lu,io,um,du,hu=p(()=>{"use strict";cu();ot();lu=uu("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),io=uu("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=re(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),um={utf8:lu,"utf-8":lu,hex:so.base16,latin1:io,ascii:io,binary:io,...so},du=um});function zt(r,e="utf8"){let t=du[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var ss=p(()=>{"use strict";hu()});function oo(r){let e=r??8192,t=e>>>1,n,s=e;return function(o){if(o<1||o>t)return re(o);s+o>e&&(n=re(e),s=0);let a=n.subarray(s,s+=o);return(s&7)!==0&&(s=(s|7)+1),a}}var fu=p(()=>{"use strict";ot()});function ao(){}function hm(r){return globalThis.Buffer!=null?re(r):dm(r)}function co(r,e,t){e[t]=r&255}function fm(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function is(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 _r(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 pm(r,e,t){e.set(r,t)}function mm(r,e,t){e.set(r,t)}function gm(r,e,t){r.length<40?zi(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(zt(r),t)}function ho(){return new Kr}var ht,lo,dm,Kr,uo,fo=p(()=>{"use strict";Ni();ot();ss();Ki();Oi();fu();Wi();ht=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}};lo=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}},dm=oo();Kr=class{constructor(){f(this,"len");f(this,"head");f(this,"tail");f(this,"states");this.len=0,this.head=new ht(ao,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new ht(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new uo((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(is,10,ne.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=ne.fromBigInt(e);return this._push(is,t.length(),t)}uint64Number(e){return this._push(Bl,Mr(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=ne.fromBigInt(e).zzEncode();return this._push(is,t.length(),t)}sint64Number(e){let t=ne.fromNumber(e).zzEncode();return this._push(is,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(co,1,e?1:0)}fixed32(e){return this._push(_r,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=ne.fromBigInt(e);return this._push(_r,4,t.lo)._push(_r,4,t.hi)}fixed64Number(e){let t=ne.fromNumber(e);return this._push(_r,4,t.lo)._push(_r,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(Fl,4,e)}double(e){return this._push(Ul,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(co,1,0):this.uint32(t)._push(pm,t,e)}string(e){let t=_l(e);return t!==0?this.uint32(t)._push(zi,t,e):this._push(co,1,0)}fork(){return this.states=new lo(this),this.head=this.tail=new ht(ao,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 ht(ao,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}};uo=class extends ht{constructor(t,n){super(fm,t,n);f(this,"next");this.next=void 0}};globalThis.Buffer!=null&&(Kr.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(mm,e,r),this},Kr.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(gm,e,r),this})});function Or(r,e){let t=ho();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var pu=p(()=>{"use strict";fo()});function*zr(r,e,t){let n=Ur(r);yield*e.stream(n,void 0,"$",t)}var mu=p(()=>{"use strict";rs()});function as(r,e,t,n,s){return{name:r,type:e,encode:t,decode:n,stream:s}}var os,po=p(()=>{"use strict";os={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5}});function mo(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 as("enum",os.VARINT,t,n,s)}var gu=p(()=>{"use strict";po()});function Wr(r,e,t){return as("message",os.LENGTH_DELIMITED,r,e,t)}var yu=p(()=>{"use strict";po()});var $r,wu=p(()=>{"use strict";zl();pu();mu();gu();yu();rs();fo();$r=class extends Error{constructor(){super(...arguments);f(this,"code","ERR_MAX_LENGTH");f(this,"name","MaxLengthError")}}});var we,qr,bu,Su=p(()=>{"use strict";wu();(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=()=>mo(t)})(e=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=Wr((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),qr.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 $r('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=qr.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 $r('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*qr.codec().stream(a,a.uint32(),`${l}.mtime`,{limits:u.limits?.mtime});break}default:{a.skipType(m&7);break}}}})),n);function s(a){return Or(a,r.codec())}r.encode=s;function i(a,c){return Nr(a,r.codec(),c)}r.decode=i;function o(a,c){return zr(a,r.codec(),c)}r.stream=o})(we||(we={}));(function(r){let e;r.codec=()=>(e==null&&(e=Wr((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 Or(i,r.codec())}r.encode=t;function n(i,o){return Nr(i,r.codec(),o)}r.decode=n;function s(i,o){return zr(i,r.codec(),o)}r.stream=s})(qr||(qr={}));(function(r){let e;r.codec=()=>(e==null&&(e=Wr((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 Or(i,r.codec())}r.encode=t;function n(i,o){return Nr(i,r.codec(),o)}r.decode=n;function s(i,o){return zr(i,r.codec(),o)}r.stream=s})(bu||(bu={}))});var Au,ym,xu,vu,H,Wt=p(()=>{"use strict";Ui();Su();Ui();Au={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},ym=["directory","hamt-sharded-directory"],xu=parseInt("0644",8),vu=parseInt("0755",8),H=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(Au).includes(t))throw new Fr("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=we.decode(e),n=new r({type:Au[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()?vu:xu:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return ym.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=we.DataType.Raw;break;case"directory":e=we.DataType.Directory;break;case"file":e=we.DataType.File;break;case"metadata":e=we.DataType.Metadata;break;case"symlink":e=we.DataType.Symlink;break;case"hamt-sharded-directory":e=we.DataType.HAMTShard;break;default:throw new Fr(`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===xu&&!this.isDirectory()&&(n=void 0),n===vu&&this.isDirectory()&&(n=void 0));let s;return this.mtime!=null&&(s={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),we.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 Re,cs=p(()=>{"use strict";Re=class extends Event{constructor(t,n){super(t);f(this,"type");f(this,"detail");this.type=t,this.detail=n}}});var ue,$t=p(()=>{"use strict";lt();ct();no();ue=async(r,e,t)=>{t.codec==null&&(t.codec=Rr);let n=await to.digest(r),s=$.create(t.cidVersion??1,t.codec.code,n);return await e.put(s,r,t),s}});function ku(r){return async function*(t,n){let s=0n;for await(let i of t.content)yield async()=>{let o,a={codec:Rr,cidVersion:r.cidVersion,onProgress:r.onProgress};r.rawLeaves?(a.codec=Ot,a.cidVersion=1):(o=new H({type:r.leafType,data:i}),i=Z({Data:o.marshal(),Links:[]}));let c=await ue(i,n,a);return s+=BigInt(i.byteLength),r.onProgress?.(new Re("unixfs:importer:progress:file:write",{bytesWritten:s,cid:c,path:t.path})),{cid:c,unixfs:o,size:BigInt(i.length),block:i}}}}var Cu=p(()=>{"use strict";lt();Wt();Lr();cs();$t()});var qt,jt,Ht,go,Vt,yo,Gt,wo,Yt,be,Ve,Hr=p(()=>{"use strict";qt=class qt extends Error{constructor(t="Invalid parameters"){super(t);f(this,"name",qt.name);f(this,"code",qt.code)}};f(qt,"name","InvalidParametersError"),f(qt,"code","ERR_INVALID_PARAMS");jt=qt,Ht=class Ht extends Error{constructor(t="Invalid avg chunk size"){super(t);f(this,"name",Ht.name);f(this,"code",Ht.code)}};f(Ht,"name","InvalidAvgChunkSizeError"),f(Ht,"code","ERR_INVALID_AVG_CHUNK_SIZE");go=Ht,Vt=class Vt extends Error{constructor(t="Invalid chunk size"){super(t);f(this,"name",Vt.name);f(this,"code",Vt.code)}};f(Vt,"name","InvalidChunkSizeError"),f(Vt,"code","ERR_INVALID_CHUNK_SIZE");yo=Vt,Gt=class Gt extends Error{constructor(t="Invalid min chunk size"){super(t);f(this,"name",Gt.name);f(this,"code",Gt.code)}};f(Gt,"name","InvalidMinChunkSizeError"),f(Gt,"code","ERR_INVALID_MIN_CHUNK_SIZE");wo=Gt,Yt=class Yt extends Error{constructor(t="Invalid content"){super(t);f(this,"name",Yt.name);f(this,"code",Yt.code)}};f(Yt,"name","InvalidContentError"),f(Yt,"code","ERR_INVALID_CONTENT");be=Yt,Ve=class extends Error{constructor(){super(...arguments);f(this,"name",be.name);f(this,"code",be.code)}};f(Ve,"name","InvalidShardingStrategyError"),f(Ve,"code","ERR_SHARDING_STRATEGY")});var Pu,Iu=p(()=>{"use strict";lt();Wt();$t();Pu=async(r,e,t)=>{let n=new H({type:"directory",mtime:r.mtime,mode:r.mode}),s=Z(Q({Data:n.marshal()})),i=await ue(s,e,t),o=r.path;return{cid:i,path:o,unixfs:n,size:BigInt(s.length),originalPath:r.originalPath,block:s}}});async function*wm(r,e,t){let n=-1,s;for await(let i of vr(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 Bu(r){return r.single===!0}var bm,Du,Tu=p(()=>{"use strict";lt();Wt();wi();Lr();cs();$t();bm=(r,e,t)=>async function(s){if(s.length===1&&Bu(s[0])&&t.reduceSingleLeafToSelf){let u=s[0],d=u.block;return Bu(u)&&(r.mtime!==void 0||r.mode!==void 0)&&(u.unixfs=new H({type:"file",mtime:r.mtime,mode:r.mode,data:u.block}),d={Data:u.unixfs.marshal(),Links:[]},u.block=Z(Q(d)),u.cid=await ue(u.block,e,{...t,cidVersion:t.cidVersion}),u.size=BigInt(u.block.length)),t.onProgress?.(new Re("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 H({type:"file",mtime:r.mtime,mode:r.mode}),o=s.filter(u=>u.cid.code===Kt&&u.size>0||u.unixfs!=null&&u.unixfs.data==null&&u.unixfs.fileSize()>0n?!0:!!u.unixfs?.data?.length).map(u=>u.cid.code===Kt?(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=Z(Q(a)),l=await ue(c,e,t);return t.onProgress?.(new Re("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}},Du=async(r,e,t)=>t.layout(wm(r,e,t),bm(r,e,t))});function Sm(r){return Symbol.iterator in r}function Am(r){return Symbol.asyncIterator in r}function xm(r){try{if(r instanceof Uint8Array)return(async function*(){yield r})();if(Sm(r))return(async function*(){yield*r})();if(Am(r))return r}catch{throw new be("Content was invalid")}throw new be("Content was invalid")}function Ru(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("/")),vm(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(xm(s.content)))){let u=BigInt(l.byteLength);c+=u,r.onProgress?.(new Re("unixfs:importer:progress:file:read",{bytesRead:c,chunkSize:u,path:s.path})),yield l}})(),originalPath:i},a=r.fileBuilder??Du;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??Pu;yield async()=>a(o,n,r)}else throw new Error("Import candidate must have content or path or both")}}}function vm(r){return r.content!=null}var Fu=p(()=>{"use strict";cs();Hr();Iu();Tu()});var Mu,Uu=p(()=>{"use strict";ss();Hr();Mu=()=>async function*(e){for await(let t of e){if(t.length===void 0)throw new be("Content was invalid");if(typeof t=="string"||t instanceof String)yield zt(t.toString());else if(Array.isArray(t))yield Uint8Array.from(t);else if(t instanceof Uint8Array)yield t;else throw new be("Content was invalid")}}});function bo(r){let e=r?.maxChildrenPerNode??Em;return async function t(n,s){let i=[];for await(let o of Hn(n,e))i.push(await s(o));return i.length>1?t(i,s):i[0]}}var Em,Nu=p(()=>{"use strict";yi();Em=174});function km(r){return r[Symbol.asyncIterator]!=null}function Cm(r){if(km(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 Lu,_u=p(()=>{"use strict";Lu=Cm});var Ku=p(()=>{"use strict";Nu()});var ke,ls=p(()=>{"use strict";ct();ke=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 Im(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+Pm[r]}function Ge(r){return r%2===0&&r++,Math.floor((Im(r)+6)/7)}function us(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 Ou(r,e,t){let n=1+Ge(e)+e;return n+=1+Ge(r)+r,n+=1+Ge(t),1+Ge(n)+n}function zu(r,e){let t=2;if(r!==void 0&&r!==Bm&&(t+=1+Ge(r)),e!=null){let n=0,s=Number(e.secs);s<0?n+=11:n+=1+Ge(s),e.nsecs!=null&&(n+=5),t+=1+Ge(n)+n}return 1+Ge(t)+t}var Pm,Bm,Wu=p(()=>{"use strict";Pm=[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];Bm=493});function So(r,e){return e?.cid!=null&&e?.size!=null?r+e.cid.byteLength:0}function Ao(r,e){return e?.cid!=null&&e?.size!=null?Ou(r,e.cid.byteLength,Number(e.size)):0}var ft,xo=p(()=>{"use strict";lt();Wt();ls();vo();Wu();$t();ft=class extends ke{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=us(t),o=this.options?.shardSplitStrategy;if(o==="links-bytes")this.nodeSize-=So(i,s),this.nodeSize+=So(i,n);else if(o==="block-bytes")this.nodeSize-=Ao(i,s),this.nodeSize+=Ao(i,n);else throw new Ve(`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 H({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 Z(Q(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+=So(us(n),s)}else if(t==="block-bytes"){this.nodeSize=zu(this.mode,this.mtime);for(let[n,s]of this._children.entries())this.nodeSize+=Ao(us(n),s)}else throw new Ve(`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 ke)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 H({type:"directory",mtime:this.mtime,mode:this.mode}),i={Data:s.marshal(),Links:n},o=Z(Q(i)),a=await ue(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 Ye(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 Dm(r,e){return r+e>>>0}function de(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),g=Math.imul(r.hi,e.lo),y=h+m+g>>>0;return{lo:d,hi:y}}function pt(r,e){return Math.imul(r,e)>>>0}function Jt(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 U(r,e){return{lo:(r.lo^e.lo)>>>0,hi:(r.hi^e.hi)>>>0}}function Eo(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 D(r,e){return{lo:r>>>0,hi:e>>>0}}function ko(r,e){return(r<<e|r>>>32-e)>>>0}function $u(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 Tm(r,e){let t=e*4;return(r[t]|r[t+1]<<8|r[t+2]<<16|r[t+3]<<24)>>>0}function qu(r){return r=U(r,Eo(r,33)),r=de(r,D(3981806797,4283543511)),r=U(r,Eo(r,33)),r=de(r,D(444984403,3301882366)),r=U(r,Eo(r,33)),r}function Rm(r){return r^=r>>>16,r=pt(r,2246822507),r^=r>>>13,r=pt(r,3266489909),r^=r>>>16,r}function Co(r,e=0){let t=D(e,0),n=D(e,0),s=r.length,i=Math.floor(s/16),o=D(289559509,2277735313),a=D(658871167,1291169091);for(let h=0;h<i;h++){let m=$u(r,h*2),g=$u(r,h*2+1);m=de(m,o),m=Jt(m,31),m=de(m,a),t=U(t,m),t=Jt(t,27),t=Ye(t,n),t=Ye(de(t,D(5,0)),D(1390208809,0)),g=de(g,a),g=Jt(g,33),g=de(g,o),n=U(n,g),n=Jt(n,31),n=Ye(n,t),n=Ye(de(n,D(5,0)),D(944331445,0))}let c=D(0,0),l=D(0,0),u=r.slice(i*16);switch(u.length){case 15:l=U(l,D(0,u[14]<<16));case 14:l=U(l,D(0,u[13]<<8));case 13:l=U(l,D(0,u[12]));case 12:l=U(l,D(u[11]<<24,0));case 11:l=U(l,D(u[10]<<16,0));case 10:l=U(l,D(u[9]<<8,0));case 9:l=U(l,D(u[8],0)),l=de(l,a),l=Jt(l,33),l=de(l,o),n=U(n,l);case 8:c=U(c,D(0,u[7]<<24));case 7:c=U(c,D(0,u[6]<<16));case 6:c=U(c,D(0,u[5]<<8));case 5:c=U(c,D(0,u[4]));case 4:c=U(c,D(u[3]<<24,0));case 3:c=U(c,D(u[2]<<16,0));case 2:c=U(c,D(u[1]<<8,0));case 1:c=U(c,D(u[0],0)),c=de(c,o),c=Jt(c,31),c=de(c,a),t=U(t,c)}let d=D(s,0);return t=U(t,d),n=U(n,d),t=Ye(t,n),n=Ye(n,t),t=qu(t),n=qu(n),t=Ye(t,n),n=Ye(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 Hu(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=Tm(r,l);u=pt(u,i),u=ko(u,15),u=pt(u,o),t^=u,t=ko(t,13),t=Dm(pt(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=pt(c,i),c=ko(c,15),c=pt(c,o),t^=c}return t^=n,t=Rm(t),t}var Vu=p(()=>{"use strict"});function Mm(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 pS,Gu,mS,Yu=p(()=>{"use strict";ns();Vu();pS=dt({name:"murmur3-32",code:35,encode:r=>Mm(Hu(r))}),Gu=dt({name:"murmur3-128",code:34,encode:r=>Co(r)}),mS=dt({name:"murmur3-x64-64",code:34,encode:r=>Co(r).subarray(0,8)})});var Qt,je,ju=p(()=>{"use strict";Qt=class Qt extends Error{constructor(t="Not Found"){super(t);f(this,"name",Qt.name);f(this,"code",Qt.code)}};f(Qt,"name","NotFoundError"),f(Qt,"code","ERR_NOT_FOUND");je=Qt});var ds=p(()=>{"use strict";ju()});var Ce,Vr=p(()=>{"use strict";Ce=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 Zt,Po=p(()=>{"use strict";ds();Vr();Zt=class extends Ce{put(e,t,n){return n?.signal?.throwIfAborted(),e}get(e,t){throw t?.signal?.throwIfAborted(),new je}has(e,t){return t?.signal?.throwIfAborted(),!1}async delete(e,t){t?.signal?.throwIfAborted()}async*getAll(e){e?.signal?.throwIfAborted()}}});var Zu=P((CS,Qu)=>{"use strict";Qu.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(Um,0),c=~(4294967295<<i+1),l=Ju(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(Nm),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(Lm)}};function Um(r,e){return r+Ju(e)}function Ju(r){let e=r;return e=e-(e>>1&1431655765),e=(e&858993459)+(e>>2&858993459),(e+(e>>4)&252645135)*16843009>>24}function Nm(r,e){return r[0]-e[0]}function Lm(r){return r[1]}});function _m(r){return!!r}function Km(r,e){return r.key}function Om(r){return r}async function ed(r,e,t){let n=[];for(let s of r._children.compactArray())if(s instanceof Je)await ed(s,e,t);else{let i=await e(s);n.push({bitField:r._children.bitField(),children:i})}return t(n)}var Xu,Je,td=p(()=>{"use strict";Xu=er(Zu(),1);ss();Je=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 Xu.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 ed(this,e,t)}toJSON(){return this.serialize(Km,Om)}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"?zt(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(_m);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 $m(r,e,t){let n=qm(e,t);return(r&n)>>>e}function qm(r,e){return zm[r]&Wm[Math.min(e+r-1,7)]}var zm,Wm,hs,rd=p(()=>{"use strict";zm=[255,254,252,248,240,224,192,128],Wm=[1,3,7,15,31,63,127,255],hs=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=$m(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 nd(r){function e(t){return t instanceof fs?t:new fs(t,r)}return e}var fs,sd=p(()=>{"use strict";bi();rd();fs=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?Er([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new hs(t);this._buffers.push(n),this._availableBits+=n.availableBits()}}});function id(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:nd(r.hashFn)};return new Je(e)}var od=p(()=>{"use strict";td();sd()});async function Hm(r){return(await Gu.encode(r)).slice(0,8).reverse()}async function*cd(r,e,t,n){let s=r._children,i=(r.tableSize()-1).toString(16).length,o=[],a=0n;for(let g=0;g<s.length;g++){let y=s.get(g);if(y==null)continue;let b=g.toString(16).toUpperCase().padStart(i,"0");if(y instanceof Je){let S;for await(let A of cd(y,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(ld(y.value)){let S=y.value,A;for await(let k of S.flush(e))A=k,yield A;if(A==null)throw new Error("Did not flush dir");let v=b+y.key;o.push({Name:v,Tsize:Number(A.size),Hash:A.cid}),a+=A.size}else{let S=y.value;if(S.cid==null)continue;let A=b+y.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 H({type:"hamt-sharded-directory",data:c,fanout:BigInt(r.tableSize()),hashType:Si,mtime:t?.mtime,mode:t?.mode}),u={Data:l.marshal(),Links:o},d=Z(Q(u)),h=await ue(d,e,n),m=BigInt(d.byteLength)+a;yield{cid:h,unixfs:l,size:m}}function ld(r){return typeof r.flush=="function"}async function ud(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 g=h.toString(16).toUpperCase().padStart(i,"0");if(m instanceof Je){let{size:y,cid:b}=await ud(m,null,t,n);o.push({Name:g,Tsize:Number(y),Hash:b}),a+=g.length+b.byteLength}else if(ld(m.value)){let y=m.value,b=y.nodeSize;if(y.cid==null)throw new Error("Child directory has not been persisted");o.push({Name:g+m.key,Tsize:Number(b),Hash:y.cid}),a+=g.length+y.cid.byteLength}else{let y=m.value,b=g+m.key,S=y.size;o.push({Name:b,Tsize:Number(S),Hash:y.cid}),a+=g.length+y.cid.byteLength}}let c=Uint8Array.from(s.bitField().reverse()),l=new H({type:"hamt-sharded-directory",data:c,fanout:BigInt(r.tableSize()),hashType:Si,mtime:e?.mtime,mode:e?.mode}),u=Z(Q({Data:l.marshal(),Links:o}));return{cid:await ue(u,t,n),size:n.shardSplitStrategy==="links-bytes"?a:u.length}}var Io,ad,dd=p(()=>{"use strict";lt();Yu();Po();od();Wt();kr();ls();$t();Io=class extends ke{constructor(t,n){super(t,n);f(this,"bucket");this.bucket=id({hashFn:Hm,bits:n.shardFanoutBits??Gn})}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 Zt,n=await ud(this.bucket,this,t,this.options);return this.nodeSize=n.size,this.nodeSize}async*flush(t){for await(let n of cd(this.bucket,t,this,this.options))yield{...n,path:this.path}}},ad=Io});async function Bo(r,e){let t=e,n=e.options.shardSplitThresholdBytes??Yn;e instanceof ft&&await e.estimateNodeSize()>n&&(t=await Vm(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 Bo(t,s)}return t}async function Vm(r){let e=new ad({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 hd=p(()=>{"use strict";kr();xo();dd()});var fd,pd=p(()=>{"use strict";fd=(r="")=>r.split(/(?<!\\)\//).filter(Boolean)});async function Gm(r,e,t){let n=fd(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 Bo(null,i);else{let u=await i.get(c);(u==null||!(u instanceof ke))&&(u=new ft({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*md(r,e){if(!(r instanceof ke)){r.unixfs?.isDirectory()===!0&&(yield r);return}yield*r.flush(e)}function gd(r){return async function*(t,n){let s=new ft({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 Gm(a,s,r),a.unixfs?.isDirectory()!==!0&&(yield a)}if(r.wrapWithDirectory||o&&s.childCount()>1)yield*md(s,n);else for(let a of s.eachChildSeries())a!=null&&(yield*md(a.child,n))}}var yd=p(()=>{"use strict";xo();ls();hd();pd()});var wd={};E(wd,{InvalidAvgChunkSizeError:()=>go,InvalidChunkSizeError:()=>yo,InvalidContentError:()=>be,InvalidMinChunkSizeError:()=>wo,InvalidParametersError:()=>jt,InvalidShardingStrategyError:()=>Ve,importByteStream:()=>Jm,importBytes:()=>jm,importDirectory:()=>Ym,importFile:()=>To,importer:()=>Do});async function*Do(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=jn,i=174):t.profile==="unixfs-v1-2025"&&(t.shardSplitStrategy=t.shardSplitStrategy??"block-bytes",t.cidVersion=t.cidVersion??1,t.rawLeaves=t.rawLeaves??!0,s=Oc,i=1024);let o=t.wrapWithDirectory??Hc,a=t.shardSplitThresholdBytes??Yn,c=t.shardSplitStrategy??Kc,l=t.shardFanoutBits??Gn,u=t.cidVersion??1,d=t.rawLeaves??qc,h=t.leafType??Vc,m=t.fileImportConcurrency??zc,g=t.blockWriteConcurrency??Wc,y=t.reduceSingleLeafToSelf??$c,b=t.chunker??Gc({chunkSize:s}),S=t.chunkValidator??Mu(),A=t.dagBuilder??Ru({chunker:b,chunkValidator:S,wrapWithDirectory:o,layout:t.layout??bo({maxChildrenPerNode:i}),bufferImporter:t.bufferImporter??ku({cidVersion:u,rawLeaves:d,leafType:h,onProgress:t.onProgress}),blockWriteConcurrency:g,reduceSingleLeafToSelf:y,cidVersion:u,onProgress:t.onProgress,dirBuilder:t.dirBuilder,fileBuilder:t.fileBuilder}),v=t.treeBuilder??gd({wrapWithDirectory:o,shardSplitThresholdBytes:a,shardSplitStrategy:c,shardFanoutBits:l,cidVersion:u,onProgress:t.onProgress});for await(let k of v(vr(A(n,e),m),e))yield{cid:k.cid,path:k.path,unixfs:k.unixfs,size:k.size}}async function To(r,e,t={}){let n=await gi(Do([r],e,t));if(n==null)throw new jt("Nothing imported");return n}async function Ym(r,e,t={}){let n=await gi(Do([r],e,t));if(n==null)throw new jt("Nothing imported");return n}async function jm(r,e,t={}){return To({content:r},e,t)}async function Jm(r,e,t={}){return To({content:r},e,t)}var vo=p(()=>{"use strict";Dc();wi();Yc();kr();Cu();Fu();Uu();Hr();Ku();yd();Hr()});function Qm(r){return typeof r?.then=="function"}var ps,bd=p(()=>{"use strict";ds();_u();Cr();ct();Lr();Nt();Vr();ps=class extends Ce{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=Lu(n);if(Qm(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(J.encode(t.multihash.bytes),n),t}*get(t,n){n?.signal?.throwIfAborted();let s=this.data.get(J.encode(t.multihash.bytes));if(s==null)throw new je;yield*s}has(t,n){return n?.signal?.throwIfAborted(),this.data.has(J.encode(t.multihash.bytes))}async delete(t,n){n?.signal?.throwIfAborted(),this.data.delete(J.encode(t.multihash.bytes))}*getAll(t){t?.signal?.throwIfAborted();for(let[n,s]of this.data.entries())yield{cid:$.createV1(Kt,Xn(J.decode(n))),bytes:(async function*(){yield*s})()},t?.signal?.throwIfAborted()}}});function ms(r,e){if(typeof r=="string")return Zm(r);if(typeof r=="number")return tg(r,e);throw new Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}function Zm(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 Xm(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 eg(r){let e=Math.abs(r);return e>=315576e5?mt(r,e,315576e5,"year"):e>=26298e5?mt(r,e,26298e5,"month"):e>=6048e5?mt(r,e,6048e5,"week"):e>=864e5?mt(r,e,864e5,"day"):e>=36e5?mt(r,e,36e5,"hour"):e>=6e4?mt(r,e,6e4,"minute"):e>=1e3?mt(r,e,1e3,"second"):`${r} ms`}function tg(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?eg(r):Xm(r)}function mt(r,e,t,n){let s=e>=t*1.5;return`${Math.round(r/t)} ${n}${s?"s":""}`}var Ro=p(()=>{"use strict"});function Fo(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=s,t.enabled=o,t.humanize=ms,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,g,y;function b(...S){if(!b.enabled)return;let A=b,v=Number(new Date),k=v-(h||v);A.diff=k,A.prev=h,A.curr=v,h=v,S[0]=t.coerce(S[0]),typeof S[0]!="string"&&S.unshift("%O");let C=0;S[0]=S[0].replace(/%([a-zA-Z%])/g,(T,O)=>{if(T==="%%")return"%";C++;let Pe=t.formatters[O];if(typeof Pe=="function"){let gt=S[C];T=Pe.call(A,gt),S.splice(C,1),C--}return T}),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:(g!==t.namespaces&&(g=t.namespaces,y=t.enabled(u)),y),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 Sd=p(()=>{"use strict";Ro()});function ng(){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 sg(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+ms(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 og(r){try{r?gs?.setItem("debug",r):gs?.removeItem("debug")}catch{}}function ag(){let r;try{r=gs?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function cg(){try{return localStorage}catch{}}function lg(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var gs,rg,ig,Ad,xd=p(()=>{"use strict";Ro();Sd();gs=cg(),rg=["#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"];ig=console.debug??console.log??(()=>{});Ad=Fo({formatArgs:sg,save:og,load:ag,useColors:ng,setupFormatters:lg,colors:rg,storage:gs,log:ig})});var X,vd=p(()=>{"use strict";xd();X=Ad});function Ed(r,e=""){let t=kd(r.message),n=kd(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
950
+ `}}});var Vn={};x(Vn,{RecoverySimulator:()=>Ar,educationalModules:()=>qn,getAllTopics:()=>Pc,getExplainer:()=>Cc,searchExplainers:()=>Ic});var xr=m(()=>{"use strict";Ec();Bc()});var Yn={};x(Yn,{deriveMLKemKeypair:()=>Gn,mlkemDecrypt:()=>Ai,mlkemDecryptWithKey:()=>Nc,mlkemEncrypt:()=>Si,mlkemEncryptWithKey:()=>Uc});import{createMlKem1024 as bi}from"mlkem";import{hkdf as Dc}from"@noble/hashes/hkdf.js";import{sha256 as Fc}from"@noble/hashes/sha2.js";function Te(r){r.fill(0)}function Pt(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 nt(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 Mc(r,e){let t=Dc(Fc,r,new Uint8Array(0),new TextEncoder().encode(Nf),32);try{return await crypto.subtle.importKey("raw",t,"AES-KW",!1,[e])}finally{Te(t)}}async function Lf(r,e,t){if(r===2){let s=await Mc(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{Te(n)}}async function Gn(r,e="mlkem-v1"){let t=await bi(),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=Dc(Fc,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{Te(s),Te(n)}}async function Si(r,e){let t=await bi(),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),p=u.slice(-d),g=[];for(let w of n){let b=typeof w=="string"?nt(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 Mc(A,"wrapKey"),P=new Uint8Array(await crypto.subtle.wrapKey("raw",c,v,"AES-KW")),k=new Uint8Array(S.length+P.length);k.set(S,0),k.set(P,S.length),g.push({publicKey:Pt(b),ciphertext:Pt(k)})}finally{Te(A)}}return{version:2,recipients:g,encryptedData:Pt(h),iv:Pt(i),authTag:Pt(p)}}finally{Te(s)}}async function Ai(r,e,t){let n=await bi(),s=typeof e=="string"?nt(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=nt(r.encryptedData),a=nt(r.iv),c=nt(r.authTag);if(a.length!==Tc)throw new Error(`Invalid IV size: ${a.length} (expected ${Tc})`);if(c.length!==Rc)throw new Error(`Invalid auth tag size: ${c.length} (expected ${Rc})`);let l=wi+Uf[i],u=async p=>{let g=nt(p);if(g.length!==l)throw new Error(`Invalid combined ciphertext size: ${g.length} (expected ${l})`);let w=g.slice(0,wi),b=g.slice(wi),S=n.decap(w,s);try{return await Lf(i,S,b)}finally{Te(S)}},d=new Uint8Array(o.length+c.length);d.set(o,0),d.set(c,o.length);let h=async p=>{let g=await u(p),w=await crypto.subtle.decrypt({name:"AES-GCM",iv:a,tagLength:128},g,d);return new TextDecoder().decode(w)};if(t){let p=typeof t=="string"?nt(t):t,g=Pt(p),w=r.recipients.find(b=>b.publicKey===g);if(!w)throw new Error("Public key not found in recipients list");return h(w.ciphertext)}for(let p of r.recipients)try{return await h(p.ciphertext)}catch{continue}throw new Error("No matching recipient found for this private key")}async function Uc(r,e,t,n="mlkem-v1"){let s=await Gn(e,n);try{let i=[s.publicKey,...t];return await Si(r,i)}finally{Te(s.privateKey)}}async function Nc(r,e,t="mlkem-v1"){let n=await Gn(e,t);try{return await Ai(r,n.privateKey,n.publicKey)}finally{Te(n.privateKey)}}var wi,Uf,Tc,Rc,Nf,vr=m(()=>{"use strict";wi=1568,Uf={1:32,2:40},Tc=12,Rc=16,Nf="w3pk-mlkem-kek-v2"});function _f(r){return r[Symbol.asyncIterator]!=null}function Kf(r){if(_f(r))return(async()=>{for await(let e of r)return e})();for(let e of r)return e}var xi,Kc=m(()=>{"use strict";xi=Kf});function Of(r){return r[Symbol.asyncIterator]!=null}function zf(r,e=1){return e=Number(e),Of(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 jn,vi=m(()=>{"use strict";jn=zf});async function*Er(r,e=1){for await(let t of jn(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 ki=m(()=>{"use strict";vi()});function Re(r=0){return new Uint8Array(r)}function re(r=0){return new Uint8Array(r)}var st=m(()=>{"use strict"});function Wf(r){return r?.buffer instanceof ArrayBuffer}function Oc(r){if(Wf(r))return r;let e=r.slice();return new Uint8Array(e.buffer,0,e.byteLength)}var zc=m(()=>{"use strict"});function Cr(r,e){e==null&&(e=r.reduce((s,i)=>s+i.length,0));let t=re(e),n=0;for(let s of r)t.set(s,n),n+=s.length;return Oc(t)}var Ei=m(()=>{"use strict";st();zc()});function Wc(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 $c=m(()=>{"use strict"});function Hc(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 Jn(r){return!!r?.[Vc]}var Vc,qc,It,Gc=m(()=>{"use strict";st();Ei();$c();Vc=Symbol.for("@achingbrain/uint8arraylist");It=class r{constructor(...e){f(this,"bufs");f(this,"length");f(this,qc,!0);this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[(qc=Vc,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(Jn(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(Jn(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=Hc(this.bufs,e);return t.buf[t.index]}set(e,t){let n=Hc(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(Jn(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 Cr(n,s)}subarray(e,t){let{bufs:n,length:s}=this._subList(e,t);return n.length===1?n[0]:Cr(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(!Jn(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 p=this.get(d+h);if(n[h]!==p){u=Math.max(1,h-a[p]);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=re(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=Re(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=Re(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=Re(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=re(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=Re(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=Re(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=Re(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=Re(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=Re(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(!Wc(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 Ci,Qn,Xn,Yc,Zn,jc,Jc,Qc,Xc,Zc,el,tl,Pr=m(()=>{"use strict";Ci=BigInt(34),Qn=8,Xn=262144,Yc="links-bytes",Zn=262144,jc=1048576,Jc=50,Qc=10,Xc=!0,Zc=!0,el=!1,tl="file"});var rl,nl=m(()=>{"use strict";Gc();Pr();rl=(r={})=>{let e=r.chunkSize??Zn;return async function*(n){let s=new It,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 It,i=0;else{let l=new It;l.append(s.sublist(e)),s=l,i-=e}(!o||i>0)&&(yield s.subarray(0,i))}}});function sl(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 he(r){if(r instanceof Uint8Array&&r.constructor.name==="Uint8Array")return it(r);if(r instanceof ArrayBuffer)return new Uint8Array(r);if(ArrayBuffer.isView(r))return it(new Uint8Array(r.buffer,r.byteOffset,r.byteLength));throw new Error("Unknown type, must be binary type")}function il(r){return new TextEncoder().encode(r)}function ol(r){return new TextDecoder().decode(r)}function $f(r){return r?.buffer instanceof ArrayBuffer}function it(r){return $f(r)?r:r.slice()}var E0,We=m(()=>{"use strict";E0=new Uint8Array(0)});function Hf(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(g){if(g instanceof Uint8Array||(ArrayBuffer.isView(g)?g=new Uint8Array(g.buffer,g.byteOffset,g.byteLength):Array.isArray(g)&&(g=Uint8Array.from(g))),!(g instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(g.length===0)return"";for(var w=0,b=0,S=0,A=g.length;S!==A&&g[S]===0;)S++,w++;for(var v=(A-S)*u+1>>>0,P=new Uint8Array(v);S!==A;){for(var k=g[S],F=0,T=v-1;(k!==0||F<b)&&T!==-1;T--,F++)k+=256*P[T]>>>0,P[T]=k%a>>>0,k=k/a>>>0;if(k!==0)throw new Error("Non-zero carry");b=F,S++}for(var O=v-b;O!==v&&P[O]===0;)O++;for(var Ee=c.repeat(w);O<v;++O)Ee+=r.charAt(P[O]);return Ee}function h(g){if(typeof g!="string")throw new TypeError("Expected String");if(g.length===0)return new Uint8Array;var w=0;if(g[w]!==" "){for(var b=0,S=0;g[w]===c;)b++,w++;for(var A=(g.length-w)*l+1>>>0,v=new Uint8Array(A);g[w];){var P=t[g.charCodeAt(w)];if(P===255)return;for(var k=0,F=A-1;(P!==0||k<S)&&F!==-1;F--,k++)P+=a*v[F]>>>0,v[F]=P%256>>>0,P=P/256>>>0;if(P!==0)throw new Error("Non-zero carry");S=k,w++}if(g[w]!==" "){for(var T=A-S;T!==A&&v[T]===0;)T++;for(var O=new Uint8Array(b+(A-T)),Ee=b;T!==A;)O[Ee++]=v[T++];return O}}}function p(g){var w=h(g);if(w)return w;throw new Error(`Non-${e} character`)}return{encode:d,decodeUnsafe:h,decode:p}}var qf,Vf,cl,ll=m(()=>{"use strict";qf=Hf,Vf=qf,cl=Vf});function ul(r,e){return new Bi({...r.decoders??{[r.prefix]:r},...e.decoders??{[e.prefix]:e}})}function Bt({name:r,prefix:e,encode:t,decode:n}){return new Ti(r,e,t,n)}function $e({name:r,prefix:e,alphabet:t}){let{encode:n,decode:s}=cl(t,r);return Bt({prefix:e,name:r,encode:n,decode:i=>he(s(i))})}function Gf(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 Yf(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 jf(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 s=jf(n);return Bt({prefix:e,name:r,encode(i){return Yf(i,n,t)},decode(i){return Gf(i,s,t,r)}})}var Pi,Ii,Bi,Ti,fe=m(()=>{"use strict";We();ll();Pi=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")}},Ii=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 ul(this,e)}},Bi=class{constructor(e){f(this,"decoders");this.decoders=e}or(e){return ul(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`)}};Ti=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 Pi(e,t,n),this.decoder=new Ii(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}});var Ri={};x(Ri,{base32:()=>j,base32hex:()=>Zf,base32hexpad:()=>tp,base32hexpadupper:()=>rp,base32hexupper:()=>ep,base32pad:()=>Qf,base32padupper:()=>Xf,base32upper:()=>Jf,base32z:()=>np});var j,Jf,Qf,Xf,Zf,ep,tp,rp,np,Ir=m(()=>{"use strict";fe();j=N({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),Jf=N({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),Qf=N({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),Xf=N({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),Zf=N({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),ep=N({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),tp=N({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),rp=N({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),np=N({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var Di={};x(Di,{base36:()=>Br,base36upper:()=>sp});var Br,sp,Fi=m(()=>{"use strict";fe();Br=$e({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),sp=$e({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var Mi={};x(Mi,{base58btc:()=>ae,base58flickr:()=>ip});var ae,ip,es=m(()=>{"use strict";fe();ae=$e({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),ip=$e({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});function fl(r,e,t){e=e||[],t=t||0;for(var n=t;r>=lp;)e[t++]=r&255|dl,r/=128;for(;r&cp;)e[t++]=r&255|dl,r>>>=7;return e[t]=r|0,fl.bytes=t-n+1,e}function Ui(r,n){var t=0,n=n||0,s=0,i=n,o,a=r.length;do{if(i>=a)throw Ui.bytes=0,new RangeError("Could not decode varint");o=r[i++],t+=s<28?(o&hl)<<s:(o&hl)*Math.pow(2,s),s+=7}while(o>=dp);return Ui.bytes=i-n,t}var op,dl,ap,cp,lp,up,dp,hl,hp,fp,pp,mp,gp,yp,wp,bp,Sp,Ap,xp,vp,Tr,pl=m(()=>{"use strict";op=fl,dl=128,ap=127,cp=~ap,lp=Math.pow(2,31);up=Ui,dp=128,hl=127;hp=Math.pow(2,7),fp=Math.pow(2,14),pp=Math.pow(2,21),mp=Math.pow(2,28),gp=Math.pow(2,35),yp=Math.pow(2,42),wp=Math.pow(2,49),bp=Math.pow(2,56),Sp=Math.pow(2,63),Ap=function(r){return r<hp?1:r<fp?2:r<pp?3:r<mp?4:r<gp?5:r<yp?6:r<wp?7:r<bp?8:r<Sp?9:10},xp={encode:op,decode:up,encodingLength:Ap},vp=xp,Tr=vp});function Rr(r,e=0){return[Tr.decode(r,e),Tr.decode.bytes]}function Tt(r,e,t=0){return Tr.encode(r,e,t),e}function Rt(r){return Tr.encodingLength(r)}var rs=m(()=>{"use strict";pl()});function Ft(r,e){let t=e.byteLength,n=Rt(r),s=n+Rt(t),i=new Uint8Array(s+t);return Tt(r,i,0),Tt(t,i,n),i.set(e,s),new Dt(r,t,e,i)}function ns(r){let e=he(r),[t,n]=Rr(e),[s,i]=Rr(e.subarray(n)),o=e.subarray(n+i);if(o.byteLength!==s)throw new Error("Incorrect length");return new Dt(t,s,o,e)}function ml(r,e){if(r===e)return!0;{let t=e;return r.code===t.code&&r.size===t.size&&t.bytes instanceof Uint8Array&&sl(r.bytes,t.bytes)}}var Dt,Ut=m(()=>{"use strict";We();rs();Dt=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=it(n),this.bytes=it(s)}}});var Ni=m(()=>{"use strict"});function gl(r,e){let{bytes:t,version:n}=r;return n===0?Ep(t,Li(r),e??ae.encoder):Cp(t,Li(r),e??j.encoder)}function Li(r){let e=yl.get(r);if(e==null){let t=new Map;return yl.set(r,t),t}return e}function kp(r,e){switch(r[0]){case"Q":{let t=e??ae;return[ae.prefix,t.decode(`${ae.prefix}${r}`)]}case ae.prefix:{let t=e??ae;return[ae.prefix,t.decode(r)]}case j.prefix:{let t=e??j;return[j.prefix,t.decode(r)]}case Br.prefix:{let t=e??Br;return[Br.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 Ep(r,e,t){let{prefix:n}=t;if(n!==ae.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 Cp(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 wl(r,e,t){let n=Rt(r),s=n+Rt(e),i=new Uint8Array(s+t.byteLength);return Tt(r,i,0),Tt(e,i,n),i.set(t,s),i}var yl,bl,H,Dr,Pp,Ip,ot=m(()=>{"use strict";Ir();Fi();es();We();Ut();rs();Ni();yl=new WeakMap;H=class r{constructor(e,t,n,s){f(this,"code");f(this,"version");f(this,"multihash");f(this,"bytes");f(this,"/");f(this,bl,"CID");this.code=t,this.version=e,this.multihash=n,this.bytes=it(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!==Dr)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Pp)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=Ft(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&&ml(e.multihash,n.multihash)}toString(e){return gl(this,e)}toJSON(){return{"/":gl(this)}}link(){return this}[(bl=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??wl(n,s,i.bytes))}else if(t[Ip]===!0){let{version:n,multihash:s,code:i}=t,o=ns(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!==Dr)throw new Error(`Version 0 CID must use dag-pb (code: ${Dr}) block encoding`);return new r(e,t,n,n.bytes)}case 1:{let s=wl(e,t,n.bytes);return new r(e,t,n,s)}default:throw new Error("Invalid version")}}static createV0(e){return r.create(0,Dr,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=he(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 Dt(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]=Rr(e.subarray(t));return t+=h,d},s=n(),i=Dr;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]=kp(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 Li(i).set(n,e),i}};Dr=112,Pp=18;Ip=Symbol.for("@ipld/js-cid/CID")});function _i(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 ss(r,e){let t;[t,e]=_i(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 Sl(r,e){let t;return[t,e]=_i(r,e),[t&7,t>>3,e]}function Tp(r){let e={},t=r.length,n=0;for(;n<t;){let s,i;if([s,i,n]=Sl(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]=ss(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]=ss(r,n),e.Name=Bp.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]=_i(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 Al(r){let e=r.length,t=0,n,s=!1,i;for(;t<e;){let a,c;if([a,c,t]=Sl(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]=ss(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]=ss(r,t),n.push(Tp(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 Bp,xl=m(()=>{"use strict";Bp=new TextDecoder});function Dp(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=Fr(e,t,r.Tsize)-1,e[t]=24}if(typeof r.Name=="string"){let n=kl.encode(r.Name);t-=n.length,e.set(n,t),t=Fr(e,t,n.length)-1,e[t]=18}return r.Hash&&(t-=r.Hash.length,e.set(r.Hash,t),t=Fr(e,t,r.Hash.length)-1,e[t]=10),e.length-t}function El(r){let e=Mp(r),t=new Uint8Array(e),n=e;if(r.Data&&(n-=r.Data.length,t.set(r.Data,n),n=Fr(t,n,r.Data.length)-1,t[n]=10),r.Links)for(let s=r.Links.length-1;s>=0;s--){let i=Dp(r.Links[s],t.subarray(0,n));n-=i,n=Fr(t,n,i)-1,t[n]=18}return t}function Fp(r){let e=0;if(r.Hash){let t=r.Hash.length;e+=1+t+Nt(t)}if(typeof r.Name=="string"){let t=kl.encode(r.Name).length;e+=1+t+Nt(t)}return typeof r.Tsize=="number"&&(e+=1+Nt(r.Tsize)),e}function Mp(r){let e=0;if(r.Data){let t=r.Data.length;e+=1+t+Nt(t)}if(r.Links)for(let t of r.Links){let n=Fp(t);e+=1+n+Nt(n)}return e}function Fr(r,e,t){e-=Nt(t);let n=e;for(;t>=Rp;)r[e++]=t&127|128,t/=128;for(;t>=128;)r[e++]=t&127|128,t>>>=7;return r[e]=t,n}function Nt(r){return r%2===0&&r++,Math.floor((Up(r)+6)/7)}function Up(r){let e=0;return r>=vl&&(r=Math.floor(r/vl),e=32),r>=65536&&(r>>>=16,e+=16),r>=256&&(r>>>=8,e+=8),e+Np[r]}var kl,vl,Rp,Np,Cl=m(()=>{"use strict";kl=new TextEncoder,vl=2**32,Rp=2**31;Np=[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 Il(r,e){if(r===e)return 0;let t=r.Name?Ki.encode(r.Name):[],n=e.Name?Ki.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 Pl(r,e){return!Object.keys(r).some(t=>!e.includes(t))}function Bl(r){if(typeof r.asCID=="object"){let t=H.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=H.asCID(r.Hash);try{t||(typeof r.Hash=="string"?t=H.parse(r.Hash):r.Hash instanceof Uint8Array&&(t=H.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 J(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=Ki.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(Bl),e.Links.sort(Il);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function Oi(r){if(!r||typeof r!="object"||Array.isArray(r)||r instanceof Uint8Array||r["/"]&&r["/"]===r.bytes)throw new TypeError("Invalid DAG-PB form");if(!Pl(r,Lp))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(!Pl(t,_p))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&&Il(t,r.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function Tl(r,e=[]){return J({Data:r,Links:e})}function Rl(r,e,t){return Bl({Hash:t,Name:r,Tsize:e})}function Dl(r){return r instanceof ArrayBuffer?new Uint8Array(r,0,r.byteLength):r}var Lp,_p,Ki,Fl=m(()=>{"use strict";ot();Lp=["Data","Links"],_p=["Hash","Name","Tsize"],Ki=new TextEncoder});var Mr={};x(Mr,{code:()=>Op,createLink:()=>Rl,createNode:()=>Tl,decode:()=>zp,encode:()=>Q,name:()=>Kp,prepare:()=>J,validate:()=>Oi});function Q(r){Oi(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),El(e)}function zp(r){let e=Dl(r),t=Al(e),n={};return t.Data&&(n.Data=t.Data),t.Links&&(n.Links=t.Links.map(s=>{let i={};try{i.Hash=H.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 Kp,Op,at=m(()=>{"use strict";ot();xl();Cl();Fl();Kp="dag-pb",Op=112});var Lt,Ur,zi=m(()=>{"use strict";Lt=class Lt extends Error{constructor(t="Invalid type"){super(t);f(this,"name",Lt.name);f(this,"code",Lt.code)}};f(Lt,"name","InvalidTypeError"),f(Lt,"code","ERR_INVALID_TYPE");Ur=Lt});function Nr(r){if(r<Wp)return 1;if(r<$p)return 2;if(r<Hp)return 3;if(r<Ml)return 4;if(r<Ul)return 5;if(r<Nl)return 6;if(r<Ll)return 7;if(Number.MAX_SAFE_INTEGER!=null&&r>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function _l(r,e,t=0){switch(Nr(r)){case 8:e[t++]=r&255|q,r/=128;case 7:e[t++]=r&255|q,r/=128;case 6:e[t++]=r&255|q,r/=128;case 5:e[t++]=r&255|q,r/=128;case 4:e[t++]=r&255|q,r>>>=7;case 3:e[t++]=r&255|q,r>>>=7;case 2:e[t++]=r&255|q,r>>>=7;case 1:{e[t++]=r&255,r>>>=7;break}default:throw new Error("unreachable")}return e}function Kl(r,e){let t=r[e],n=0;if(n+=t&He,t<q||(t=r[e+1],n+=(t&He)<<7,t<q)||(t=r[e+2],n+=(t&He)<<14,t<q)||(t=r[e+3],n+=(t&He)<<21,t<q)||(t=r[e+4],n+=(t&He)*Ml,t<q)||(t=r[e+5],n+=(t&He)*Ul,t<q)||(t=r[e+6],n+=(t&He)*Nl,t<q)||(t=r[e+7],n+=(t&He)*Ll,t<q))return n;throw new RangeError("Could not decode varint")}var Wp,$p,Hp,Ml,Ul,Nl,Ll,q,He,Wi=m(()=>{"use strict";st();Wp=Math.pow(2,7),$p=Math.pow(2,14),Hp=Math.pow(2,21),Ml=Math.pow(2,28),Ul=Math.pow(2,35),Nl=Math.pow(2,42),Ll=Math.pow(2,49),q=128,He=127});function qp(r){return r.buffer instanceof ArrayBuffer}function Ol(r){return qp(r)?r:r.slice()}var zl=m(()=>{"use strict"});function Wl(r,e,t){$i[0]=r,e[t]=qe[0],e[t+1]=qe[1],e[t+2]=qe[2],e[t+3]=qe[3]}function $l(r,e){return qe[0]=r[e],qe[1]=r[e+1],qe[2]=r[e+2],qe[3]=r[e+3],$i[0]}function Hl(r,e,t){Hi[0]=r,e[t]=W[0],e[t+1]=W[1],e[t+2]=W[2],e[t+3]=W[3],e[t+4]=W[4],e[t+5]=W[5],e[t+6]=W[6],e[t+7]=W[7]}function ql(r,e){return W[0]=r[e],W[1]=r[e+1],W[2]=r[e+2],W[3]=r[e+3],W[4]=r[e+4],W[5]=r[e+5],W[6]=r[e+6],W[7]=r[e+7],Hi[0]}var $i,qe,Hi,W,qi=m(()=>{"use strict";$i=new Float32Array([-0]),qe=new Uint8Array($i.buffer);Hi=new Float64Array([-0]),W=new Uint8Array(Hi.buffer)});var Vp,Gp,ne,ct,Vl,Vi=m(()=>{"use strict";Vp=BigInt(Number.MAX_SAFE_INTEGER),Gp=BigInt(Number.MIN_SAFE_INTEGER),ne=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 ct;if(e<Vp&&e>Gp)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>Vl&&(s=0n,++n>Vl&&(n=0n))),new r(Number(s),Number(n))}static fromNumber(e){if(e===0)return ct;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):ct}},ct=new ne(0,0);ct.toBigInt=function(){return 0n};ct.zzEncode=ct.zzDecode=function(){return this};ct.length=function(){return 1};Vl=4294967296n});function Gl(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 Yl(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 Gi(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 Yi=m(()=>{"use strict"});function pe(r,e){return RangeError(`index out of range: ${r.pos} + ${e??1} > ${r.len}`)}function is(r,e){return(r[e-4]|r[e-3]<<8|r[e-2]<<16|r[e-1]<<24)>>>0}function Lr(r){return new ji(r instanceof Uint8Array?r:r.subarray())}var ji,os=m(()=>{"use strict";Wi();zl();qi();Vi();Yi();ji=class{constructor(e){f(this,"buf");f(this,"pos");f(this,"len");f(this,"_slice",Uint8Array.prototype.subarray);this.buf=Ol(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,pe(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 pe(this,4);return is(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw pe(this,4);return is(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw pe(this,4);let e=$l(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw pe(this,4);let e=ql(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 pe(this,e);return this.pos+=e,t===n?new Uint8Array(0):this.buf.subarray(t,n)}string(){let e=this.bytes();return Yl(e,0,e.length)}skip(e){if(typeof e=="number"){if(this.pos+e>this.len)throw pe(this,e);this.pos+=e}else do if(this.pos>=this.len)throw pe(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 ne(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 pe(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 pe(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 pe(this,8);let e=is(this.buf,this.pos+=4),t=is(this.buf,this.pos+=4);return new ne(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=Kl(this.buf,this.pos);return this.pos+=Nr(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 _r(r,e,t){let n=Lr(r);return e.decode(n,void 0,t)}var Jl=m(()=>{"use strict";os()});var Ji={};x(Ji,{base10:()=>Yp});var Yp,Ql=m(()=>{"use strict";fe();Yp=$e({prefix:"9",name:"base10",alphabet:"0123456789"})});var Qi={};x(Qi,{base16:()=>jp,base16upper:()=>Jp});var jp,Jp,Xl=m(()=>{"use strict";fe();jp=N({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),Jp=N({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var Xi={};x(Xi,{base2:()=>Qp});var Qp,Zl=m(()=>{"use strict";fe();Qp=N({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var Zi={};x(Zi,{base256emoji:()=>rm});function em(r){return r.reduce((e,t)=>(e+=Xp[t],e),"")}function tm(r){let e=[];for(let t of r){let n=t.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${t}`);let s=Zp[n];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var eu,Xp,Zp,rm,tu=m(()=>{"use strict";fe();eu=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}"),Xp=eu.reduce((r,e,t)=>(r[t]=e,r),[]),Zp=eu.reduce((r,e,t)=>{let n=e.codePointAt(0);if(n==null)throw new Error(`Invalid character: ${e}`);return r[n]=t,r},[]);rm=Bt({prefix:"\u{1F680}",name:"base256emoji",encode:em,decode:tm})});var to={};x(to,{base64:()=>eo,base64pad:()=>nm,base64url:()=>sm,base64urlpad:()=>im});var eo,nm,sm,im,ro=m(()=>{"use strict";fe();eo=N({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),nm=N({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),sm=N({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),im=N({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var no={};x(no,{base8:()=>om});var om,ru=m(()=>{"use strict";fe();om=N({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var so={};x(so,{identity:()=>am});var am,nu=m(()=>{"use strict";We();fe();am=Bt({prefix:"\0",name:"identity",encode:r=>ol(r),decode:r=>il(r)})});var vb,kb,su=m(()=>{"use strict";vb=new TextEncoder,kb=new TextDecoder});var Kt={};x(Kt,{code:()=>_t,decode:()=>dm,encode:()=>um,name:()=>lm});function um(r){return he(r)}function dm(r){return he(r)}var lm,_t,Kr=m(()=>{"use strict";We();lm="raw",_t=85});var io={};x(io,{identity:()=>pm});function fm(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 Ft(iu,ou(r))}var iu,hm,ou,pm,au=m(()=>{"use strict";We();Ut();iu=0,hm="identity",ou=he;pm={code:iu,name:hm,encode:ou,digest:fm}});function lt({name:r,code:e,encode:t,minDigestLength:n,maxDigestLength:s}){return new oo(r,e,t,n,s)}function cu(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 Ft(e,r)}var mm,oo,as=m(()=>{"use strict";Ut();mm=20;oo=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??mm,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?cu(n,this.code,t?.truncate):n.then(s=>cu(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}}});var co={};x(co,{sha256:()=>ao,sha512:()=>gm});function uu(r){return async e=>new Uint8Array(await crypto.subtle.digest(r,e))}var ao,gm,lo=m(()=>{"use strict";as();ao=lt({name:"sha2-256",code:18,encode:uu("SHA-256")}),gm=lt({name:"sha2-512",code:19,encode:uu("SHA-512")})});var du=m(()=>{"use strict"});var hu=m(()=>{"use strict"});var fu=m(()=>{"use strict"});var pu=m(()=>{"use strict"});var mu=m(()=>{"use strict";du();hu();fu();Ni();pu()});var gu=m(()=>{"use strict";We();ot();Ut();as();rs();mu()});var uo,_b,yu=m(()=>{"use strict";Ql();Xl();Zl();tu();Ir();Fi();es();ro();ru();nu();su();Kr();au();lo();gu();uo={...so,...Xi,...no,...Ji,...Qi,...Ri,...Di,...Mi,...to,...Zi},_b={...co,...io}});function bu(r,e,t,n){return{name:r,prefix:e,encoder:{name:r,prefix:e,encode:t},decoder:{decode:n}}}var wu,ho,ym,Su,Au=m(()=>{"use strict";yu();st();wu=bu("utf8","u",r=>"u"+new TextDecoder("utf8").decode(r),r=>new TextEncoder().encode(r.substring(1))),ho=bu("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=re(r.length);for(let t=0;t<r.length;t++)e[t]=r.charCodeAt(t);return e}),ym={utf8:wu,"utf-8":wu,hex:uo.base16,latin1:ho,ascii:ho,binary:ho,...uo},Su=ym});function Ot(r,e="utf8"){let t=Su[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${r}`)}var cs=m(()=>{"use strict";Au()});function fo(r){let e=r??8192,t=e>>>1,n,s=e;return function(o){if(o<1||o>t)return re(o);s+o>e&&(n=re(e),s=0);let a=n.subarray(s,s+=o);return(s&7)!==0&&(s=(s|7)+1),a}}var xu=m(()=>{"use strict";st()});function po(){}function bm(r){return globalThis.Buffer!=null?re(r):wm(r)}function mo(r,e,t){e[t]=r&255}function Sm(r,e,t){for(;r>127;)e[t++]=r&127|128,r>>>=7;e[t]=r}function ls(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 Or(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 Am(r,e,t){e.set(r,t)}function xm(r,e,t){e.set(r,t)}function vm(r,e,t){r.length<40?Gi(r,e,t):e.utf8Write!=null?e.utf8Write(r,t):e.set(Ot(r),t)}function wo(){return new zr}var ut,go,wm,zr,yo,bo=m(()=>{"use strict";Wi();st();cs();qi();Vi();xu();Yi();ut=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}};go=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}},wm=fo();zr=class{constructor(){f(this,"len");f(this,"head");f(this,"tail");f(this,"states");this.len=0,this.head=new ut(po,0,0),this.tail=this.head,this.states=null}_push(e,t,n){return this.tail=this.tail.next=new ut(e,t,n),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new yo((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(ls,10,ne.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=ne.fromBigInt(e);return this._push(ls,t.length(),t)}uint64Number(e){return this._push(_l,Nr(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=ne.fromBigInt(e).zzEncode();return this._push(ls,t.length(),t)}sint64Number(e){let t=ne.fromNumber(e).zzEncode();return this._push(ls,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(mo,1,e?1:0)}fixed32(e){return this._push(Or,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=ne.fromBigInt(e);return this._push(Or,4,t.lo)._push(Or,4,t.hi)}fixed64Number(e){let t=ne.fromNumber(e);return this._push(Or,4,t.lo)._push(Or,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(Wl,4,e)}double(e){return this._push(Hl,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(mo,1,0):this.uint32(t)._push(Am,t,e)}string(e){let t=Gl(e);return t!==0?this.uint32(t)._push(Gi,t,e):this._push(mo,1,0)}fork(){return this.states=new go(this),this.head=this.tail=new ut(po,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 ut(po,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=bm(this.len),n=0;for(;e!=null;)e.fn(e.val,t,n),n+=e.len,e=e.next;return t}};yo=class extends ut{constructor(t,n){super(Sm,t,n);f(this,"next");this.next=void 0}};globalThis.Buffer!=null&&(zr.prototype.bytes=function(r){let e=r.length>>>0;return this.uint32(e),e>0&&this._push(xm,e,r),this},zr.prototype.string=function(r){let e=globalThis.Buffer.byteLength(r);return this.uint32(e),e>0&&this._push(vm,e,r),this})});function Wr(r,e){let t=wo();return e.encode(r,t,{lengthDelimited:!1}),t.finish()}var vu=m(()=>{"use strict";bo()});function*$r(r,e,t){let n=Lr(r);yield*e.stream(n,void 0,"$",t)}var ku=m(()=>{"use strict";os()});function ds(r,e,t,n,s){return{name:r,type:e,encode:t,decode:n,stream:s}}var us,So=m(()=>{"use strict";us={VARINT:0,BIT64:1,LENGTH_DELIMITED:2,START_GROUP:3,END_GROUP:4,BIT32:5}});function Ao(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 ds("enum",us.VARINT,t,n,s)}var Eu=m(()=>{"use strict";So()});function Hr(r,e,t){return ds("message",us.LENGTH_DELIMITED,r,e,t)}var Cu=m(()=>{"use strict";So()});var qr,Pu=m(()=>{"use strict";Jl();vu();ku();Eu();Cu();os();bo();qr=class extends Error{constructor(){super(...arguments);f(this,"code","ERR_MAX_LENGTH");f(this,"name","MaxLengthError")}}});var me,Vr,Iu,Bu=m(()=>{"use strict";Pu();(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=()=>Ao(t)})(e=r.DataType||(r.DataType={}));let n;r.codec=()=>(n==null&&(n=Hr((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),Vr.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 qr('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=Vr.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 p=a.uint32();switch(p>>>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 qr('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*Vr.codec().stream(a,a.uint32(),`${l}.mtime`,{limits:u.limits?.mtime});break}default:{a.skipType(p&7);break}}}})),n);function s(a){return Wr(a,r.codec())}r.encode=s;function i(a,c){return _r(a,r.codec(),c)}r.decode=i;function o(a,c){return $r(a,r.codec(),c)}r.stream=o})(me||(me={}));(function(r){let e;r.codec=()=>(e==null&&(e=Hr((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 Wr(i,r.codec())}r.encode=t;function n(i,o){return _r(i,r.codec(),o)}r.decode=n;function s(i,o){return $r(i,r.codec(),o)}r.stream=s})(Vr||(Vr={}));(function(r){let e;r.codec=()=>(e==null&&(e=Hr((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 Wr(i,r.codec())}r.encode=t;function n(i,o){return _r(i,r.codec(),o)}r.decode=n;function s(i,o){return $r(i,r.codec(),o)}r.stream=s})(Iu||(Iu={}))});var Tu,km,Ru,Du,V,zt=m(()=>{"use strict";zi();Bu();zi();Tu={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},km=["directory","hamt-sharded-directory"],Ru=parseInt("0644",8),Du=parseInt("0755",8),V=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(Tu).includes(t))throw new Ur("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=me.decode(e),n=new r({type:Tu[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()?Du:Ru:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return km.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=me.DataType.Raw;break;case"directory":e=me.DataType.Directory;break;case"file":e=me.DataType.File;break;case"metadata":e=me.DataType.Metadata;break;case"symlink":e=me.DataType.Symlink;break;case"hamt-sharded-directory":e=me.DataType.HAMTShard;break;default:throw new Ur(`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===Ru&&!this.isDirectory()&&(n=void 0),n===Du&&this.isDirectory()&&(n=void 0));let s;return this.mtime!=null&&(s={Seconds:this.mtime.secs,FractionalNanoseconds:this.mtime.nsecs}),me.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 De,hs=m(()=>{"use strict";De=class extends Event{constructor(t,n){super(t);f(this,"type");f(this,"detail");this.type=t,this.detail=n}}});var ce,Wt=m(()=>{"use strict";at();ot();lo();ce=async(r,e,t)=>{t.codec==null&&(t.codec=Mr);let n=await ao.digest(r),s=H.create(t.cidVersion??1,t.codec.code,n);return await e.put(s,r,t),s}});function Mu(r){return async function*(t,n){let s=0n;for await(let i of t.content)yield async()=>{let o,a={codec:Mr,cidVersion:r.cidVersion,onProgress:r.onProgress};r.rawLeaves?(a.codec=Kt,a.cidVersion=1):(o=new V({type:r.leafType,data:i}),i=Q({Data:o.marshal(),Links:[]}));let c=await ce(i,n,a);return s+=BigInt(i.byteLength),r.onProgress?.(new De("unixfs:importer:progress:file:write",{bytesWritten:s,cid:c,path:t.path})),{cid:c,unixfs:o,size:BigInt(i.length),block:i}}}}var Uu=m(()=>{"use strict";at();zt();Kr();hs();Wt()});var $t,Yt,Ht,xo,qt,vo,Vt,ko,Gt,ge,Ve,Gr=m(()=>{"use strict";$t=class $t extends Error{constructor(t="Invalid parameters"){super(t);f(this,"name",$t.name);f(this,"code",$t.code)}};f($t,"name","InvalidParametersError"),f($t,"code","ERR_INVALID_PARAMS");Yt=$t,Ht=class Ht extends Error{constructor(t="Invalid avg chunk size"){super(t);f(this,"name",Ht.name);f(this,"code",Ht.code)}};f(Ht,"name","InvalidAvgChunkSizeError"),f(Ht,"code","ERR_INVALID_AVG_CHUNK_SIZE");xo=Ht,qt=class qt extends Error{constructor(t="Invalid chunk size"){super(t);f(this,"name",qt.name);f(this,"code",qt.code)}};f(qt,"name","InvalidChunkSizeError"),f(qt,"code","ERR_INVALID_CHUNK_SIZE");vo=qt,Vt=class Vt extends Error{constructor(t="Invalid min chunk size"){super(t);f(this,"name",Vt.name);f(this,"code",Vt.code)}};f(Vt,"name","InvalidMinChunkSizeError"),f(Vt,"code","ERR_INVALID_MIN_CHUNK_SIZE");ko=Vt,Gt=class Gt extends Error{constructor(t="Invalid content"){super(t);f(this,"name",Gt.name);f(this,"code",Gt.code)}};f(Gt,"name","InvalidContentError"),f(Gt,"code","ERR_INVALID_CONTENT");ge=Gt,Ve=class extends Error{constructor(){super(...arguments);f(this,"name",ge.name);f(this,"code",ge.code)}};f(Ve,"name","InvalidShardingStrategyError"),f(Ve,"code","ERR_SHARDING_STRATEGY")});var Nu,Lu=m(()=>{"use strict";at();zt();Wt();Nu=async(r,e,t)=>{let n=new V({type:"directory",mtime:r.mtime,mode:r.mode}),s=Q(J({Data:n.marshal()})),i=await ce(s,e,t),o=r.path;return{cid:i,path:o,unixfs:n,size:BigInt(s.length),originalPath:r.originalPath,block:s}}});async function*Em(r,e,t){let n=-1,s;for await(let i of Er(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 _u(r){return r.single===!0}var Cm,Ku,Ou=m(()=>{"use strict";at();zt();ki();Kr();hs();Wt();Cm=(r,e,t)=>async function(s){if(s.length===1&&_u(s[0])&&t.reduceSingleLeafToSelf){let u=s[0],d=u.block;return _u(u)&&(r.mtime!==void 0||r.mode!==void 0)&&(u.unixfs=new V({type:"file",mtime:r.mtime,mode:r.mode,data:u.block}),d={Data:u.unixfs.marshal(),Links:[]},u.block=Q(J(d)),u.cid=await ce(u.block,e,{...t,cidVersion:t.cidVersion}),u.size=BigInt(u.block.length)),t.onProgress?.(new De("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 V({type:"file",mtime:r.mtime,mode:r.mode}),o=s.filter(u=>u.cid.code===_t&&u.size>0||u.unixfs!=null&&u.unixfs.data==null&&u.unixfs.fileSize()>0n?!0:!!u.unixfs?.data?.length).map(u=>u.cid.code===_t?(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=Q(J(a)),l=await ce(c,e,t);return t.onProgress?.(new De("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}},Ku=async(r,e,t)=>t.layout(Em(r,e,t),Cm(r,e,t))});function Pm(r){return Symbol.iterator in r}function Im(r){return Symbol.asyncIterator in r}function Bm(r){try{if(r instanceof Uint8Array)return(async function*(){yield r})();if(Pm(r))return(async function*(){yield*r})();if(Im(r))return r}catch{throw new ge("Content was invalid")}throw new ge("Content was invalid")}function zu(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("/")),Tm(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(Bm(s.content)))){let u=BigInt(l.byteLength);c+=u,r.onProgress?.(new De("unixfs:importer:progress:file:read",{bytesRead:c,chunkSize:u,path:s.path})),yield l}})(),originalPath:i},a=r.fileBuilder??Ku;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??Nu;yield async()=>a(o,n,r)}else throw new Error("Import candidate must have content or path or both")}}}function Tm(r){return r.content!=null}var Wu=m(()=>{"use strict";hs();Gr();Lu();Ou()});var $u,Hu=m(()=>{"use strict";cs();Gr();$u=()=>async function*(e){for await(let t of e){if(t.length===void 0)throw new ge("Content was invalid");if(typeof t=="string"||t instanceof String)yield Ot(t.toString());else if(Array.isArray(t))yield Uint8Array.from(t);else if(t instanceof Uint8Array)yield t;else throw new ge("Content was invalid")}}});function Eo(r){let e=r?.maxChildrenPerNode??Rm;return async function t(n,s){let i=[];for await(let o of jn(n,e))i.push(await s(o));return i.length>1?t(i,s):i[0]}}var Rm,qu=m(()=>{"use strict";vi();Rm=174});function Dm(r){return r[Symbol.asyncIterator]!=null}function Fm(r){if(Dm(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 Vu,Gu=m(()=>{"use strict";Vu=Fm});var Yu=m(()=>{"use strict";qu()});var ve,fs=m(()=>{"use strict";ot();ve=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 Um(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+Mm[r]}function Ge(r){return r%2===0&&r++,Math.floor((Um(r)+6)/7)}function ps(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 ju(r,e,t){let n=1+Ge(e)+e;return n+=1+Ge(r)+r,n+=1+Ge(t),1+Ge(n)+n}function Ju(r,e){let t=2;if(r!==void 0&&r!==Nm&&(t+=1+Ge(r)),e!=null){let n=0,s=Number(e.secs);s<0?n+=11:n+=1+Ge(s),e.nsecs!=null&&(n+=5),t+=1+Ge(n)+n}return 1+Ge(t)+t}var Mm,Nm,Qu=m(()=>{"use strict";Mm=[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];Nm=493});function Co(r,e){return e?.cid!=null&&e?.size!=null?r+e.cid.byteLength:0}function Po(r,e){return e?.cid!=null&&e?.size!=null?ju(r,e.cid.byteLength,Number(e.size)):0}var dt,Io=m(()=>{"use strict";at();zt();fs();Bo();Qu();Wt();dt=class extends ve{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=ps(t),o=this.options?.shardSplitStrategy;if(o==="links-bytes")this.nodeSize-=Co(i,s),this.nodeSize+=Co(i,n);else if(o==="block-bytes")this.nodeSize-=Po(i,s),this.nodeSize+=Po(i,n);else throw new Ve(`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 V({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 Q(J(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+=Co(ps(n),s)}else if(t==="block-bytes"){this.nodeSize=Ju(this.mode,this.mtime);for(let[n,s]of this._children.entries())this.nodeSize+=Po(ps(n),s)}else throw new Ve(`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 ve)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 V({type:"directory",mtime:this.mtime,mode:this.mode}),i={Data:s.marshal(),Links:n},o=Q(J(i)),a=await ce(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 Ye(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 Lm(r,e){return r+e>>>0}function le(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),p=Math.imul(r.lo,e.hi),g=Math.imul(r.hi,e.lo),w=h+p+g>>>0;return{lo:d,hi:w}}function ht(r,e){return Math.imul(r,e)>>>0}function jt(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 M(r,e){return{lo:(r.lo^e.lo)>>>0,hi:(r.hi^e.hi)>>>0}}function To(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 B(r,e){return{lo:r>>>0,hi:e>>>0}}function Ro(r,e){return(r<<e|r>>>32-e)>>>0}function Xu(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 _m(r,e){let t=e*4;return(r[t]|r[t+1]<<8|r[t+2]<<16|r[t+3]<<24)>>>0}function Zu(r){return r=M(r,To(r,33)),r=le(r,B(3981806797,4283543511)),r=M(r,To(r,33)),r=le(r,B(444984403,3301882366)),r=M(r,To(r,33)),r}function Km(r){return r^=r>>>16,r=ht(r,2246822507),r^=r>>>13,r=ht(r,3266489909),r^=r>>>16,r}function Do(r,e=0){let t=B(e,0),n=B(e,0),s=r.length,i=Math.floor(s/16),o=B(289559509,2277735313),a=B(658871167,1291169091);for(let h=0;h<i;h++){let p=Xu(r,h*2),g=Xu(r,h*2+1);p=le(p,o),p=jt(p,31),p=le(p,a),t=M(t,p),t=jt(t,27),t=Ye(t,n),t=Ye(le(t,B(5,0)),B(1390208809,0)),g=le(g,a),g=jt(g,33),g=le(g,o),n=M(n,g),n=jt(n,31),n=Ye(n,t),n=Ye(le(n,B(5,0)),B(944331445,0))}let c=B(0,0),l=B(0,0),u=r.slice(i*16);switch(u.length){case 15:l=M(l,B(0,u[14]<<16));case 14:l=M(l,B(0,u[13]<<8));case 13:l=M(l,B(0,u[12]));case 12:l=M(l,B(u[11]<<24,0));case 11:l=M(l,B(u[10]<<16,0));case 10:l=M(l,B(u[9]<<8,0));case 9:l=M(l,B(u[8],0)),l=le(l,a),l=jt(l,33),l=le(l,o),n=M(n,l);case 8:c=M(c,B(0,u[7]<<24));case 7:c=M(c,B(0,u[6]<<16));case 6:c=M(c,B(0,u[5]<<8));case 5:c=M(c,B(0,u[4]));case 4:c=M(c,B(u[3]<<24,0));case 3:c=M(c,B(u[2]<<16,0));case 2:c=M(c,B(u[1]<<8,0));case 1:c=M(c,B(u[0],0)),c=le(c,o),c=jt(c,31),c=le(c,a),t=M(t,c)}let d=B(s,0);return t=M(t,d),n=M(n,d),t=Ye(t,n),n=Ye(n,t),t=Zu(t),n=Zu(n),t=Ye(t,n),n=Ye(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 ed(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=_m(r,l);u=ht(u,i),u=Ro(u,15),u=ht(u,o),t^=u,t=Ro(t,13),t=Lm(ht(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=ht(c,i),c=Ro(c,15),c=ht(c,o),t^=c}return t^=n,t=Km(t),t}var td=m(()=>{"use strict"});function zm(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 SS,rd,AS,nd=m(()=>{"use strict";as();td();SS=lt({name:"murmur3-32",code:35,encode:r=>zm(ed(r))}),rd=lt({name:"murmur3-128",code:34,encode:r=>Do(r)}),AS=lt({name:"murmur3-x64-64",code:34,encode:r=>Do(r).subarray(0,8)})});var Jt,je,sd=m(()=>{"use strict";Jt=class Jt extends Error{constructor(t="Not Found"){super(t);f(this,"name",Jt.name);f(this,"code",Jt.code)}};f(Jt,"name","NotFoundError"),f(Jt,"code","ERR_NOT_FOUND");je=Jt});var ms=m(()=>{"use strict";sd()});var ke,Yr=m(()=>{"use strict";ke=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 Qt,Fo=m(()=>{"use strict";ms();Yr();Qt=class extends ke{put(e,t,n){return n?.signal?.throwIfAborted(),e}get(e,t){throw t?.signal?.throwIfAborted(),new je}has(e,t){return t?.signal?.throwIfAborted(),!1}async delete(e,t){t?.signal?.throwIfAborted()}async*getAll(e){e?.signal?.throwIfAborted()}}});var ad=E((DS,od)=>{"use strict";od.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(Wm,0),c=~(4294967295<<i+1),l=id(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($m),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(Hm)}};function Wm(r,e){return r+id(e)}function id(r){let e=r;return e=e-(e>>1&1431655765),e=(e&858993459)+(e>>2&858993459),(e+(e>>4)&252645135)*16843009>>24}function $m(r,e){return r[0]-e[0]}function Hm(r){return r[1]}});function qm(r){return!!r}function Vm(r,e){return r.key}function Gm(r){return r}async function ld(r,e,t){let n=[];for(let s of r._children.compactArray())if(s instanceof Je)await ld(s,e,t);else{let i=await e(s);n.push({bitField:r._children.bitField(),children:i})}return t(n)}var cd,Je,ud=m(()=>{"use strict";cd=Zt(ad(),1);cs();Je=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 cd.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 ld(this,e,t)}toJSON(){return this.serialize(Vm,Gm)}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"?Ot(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(qm);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 Jm(r,e,t){let n=Qm(e,t);return(r&n)>>>e}function Qm(r,e){return Ym[r]&jm[Math.min(e+r-1,7)]}var Ym,jm,gs,dd=m(()=>{"use strict";Ym=[255,254,252,248,240,224,192,128],jm=[1,3,7,15,31,63,127,255],gs=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=Jm(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 hd(r){function e(t){return t instanceof ys?t:new ys(t,r)}return e}var ys,fd=m(()=>{"use strict";Ei();dd();ys=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?Cr([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),n=new gs(t);this._buffers.push(n),this._availableBits+=n.availableBits()}}});function pd(r){if(r==null||r.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:r.bits??8,hash:hd(r.hashFn)};return new Je(e)}var md=m(()=>{"use strict";ud();fd()});async function Xm(r){return(await rd.encode(r)).slice(0,8).reverse()}async function*yd(r,e,t,n){let s=r._children,i=(r.tableSize()-1).toString(16).length,o=[],a=0n;for(let g=0;g<s.length;g++){let w=s.get(g);if(w==null)continue;let b=g.toString(16).toUpperCase().padStart(i,"0");if(w instanceof Je){let S;for await(let A of yd(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(wd(w.value)){let S=w.value,A;for await(let P of S.flush(e))A=P,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 V({type:"hamt-sharded-directory",data:c,fanout:BigInt(r.tableSize()),hashType:Ci,mtime:t?.mtime,mode:t?.mode}),u={Data:l.marshal(),Links:o},d=Q(J(u)),h=await ce(d,e,n),p=BigInt(d.byteLength)+a;yield{cid:h,unixfs:l,size:p}}function wd(r){return typeof r.flush=="function"}async function bd(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 p=s.get(h);if(p==null)continue;let g=h.toString(16).toUpperCase().padStart(i,"0");if(p instanceof Je){let{size:w,cid:b}=await bd(p,null,t,n);o.push({Name:g,Tsize:Number(w),Hash:b}),a+=g.length+b.byteLength}else if(wd(p.value)){let w=p.value,b=w.nodeSize;if(w.cid==null)throw new Error("Child directory has not been persisted");o.push({Name:g+p.key,Tsize:Number(b),Hash:w.cid}),a+=g.length+w.cid.byteLength}else{let w=p.value,b=g+p.key,S=w.size;o.push({Name:b,Tsize:Number(S),Hash:w.cid}),a+=g.length+w.cid.byteLength}}let c=Uint8Array.from(s.bitField().reverse()),l=new V({type:"hamt-sharded-directory",data:c,fanout:BigInt(r.tableSize()),hashType:Ci,mtime:e?.mtime,mode:e?.mode}),u=Q(J({Data:l.marshal(),Links:o}));return{cid:await ce(u,t,n),size:n.shardSplitStrategy==="links-bytes"?a:u.length}}var Mo,gd,Sd=m(()=>{"use strict";at();nd();Fo();md();zt();Pr();fs();Wt();Mo=class extends ve{constructor(t,n){super(t,n);f(this,"bucket");this.bucket=pd({hashFn:Xm,bits:n.shardFanoutBits??Qn})}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 Qt,n=await bd(this.bucket,this,t,this.options);return this.nodeSize=n.size,this.nodeSize}async*flush(t){for await(let n of yd(this.bucket,t,this,this.options))yield{...n,path:this.path}}},gd=Mo});async function Uo(r,e){let t=e,n=e.options.shardSplitThresholdBytes??Xn;e instanceof dt&&await e.estimateNodeSize()>n&&(t=await Zm(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 Uo(t,s)}return t}async function Zm(r){let e=new gd({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 Ad=m(()=>{"use strict";Pr();Io();Sd()});var xd,vd=m(()=>{"use strict";xd=(r="")=>r.split(/(?<!\\)\//).filter(Boolean)});async function eg(r,e,t){let n=xd(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 Uo(null,i);else{let u=await i.get(c);(u==null||!(u instanceof ve))&&(u=new dt({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*kd(r,e){if(!(r instanceof ve)){r.unixfs?.isDirectory()===!0&&(yield r);return}yield*r.flush(e)}function Ed(r){return async function*(t,n){let s=new dt({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 eg(a,s,r),a.unixfs?.isDirectory()!==!0&&(yield a)}if(r.wrapWithDirectory||o&&s.childCount()>1)yield*kd(s,n);else for(let a of s.eachChildSeries())a!=null&&(yield*kd(a.child,n))}}var Cd=m(()=>{"use strict";Io();fs();Ad();vd()});var Pd={};x(Pd,{InvalidAvgChunkSizeError:()=>xo,InvalidChunkSizeError:()=>vo,InvalidContentError:()=>ge,InvalidMinChunkSizeError:()=>ko,InvalidParametersError:()=>Yt,InvalidShardingStrategyError:()=>Ve,importByteStream:()=>ng,importBytes:()=>rg,importDirectory:()=>tg,importFile:()=>Lo,importer:()=>No});async function*No(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=Zn,i=174):t.profile==="unixfs-v1-2025"&&(t.shardSplitStrategy=t.shardSplitStrategy??"block-bytes",t.cidVersion=t.cidVersion??1,t.rawLeaves=t.rawLeaves??!0,s=jc,i=1024);let o=t.wrapWithDirectory??el,a=t.shardSplitThresholdBytes??Xn,c=t.shardSplitStrategy??Yc,l=t.shardFanoutBits??Qn,u=t.cidVersion??1,d=t.rawLeaves??Zc,h=t.leafType??tl,p=t.fileImportConcurrency??Jc,g=t.blockWriteConcurrency??Qc,w=t.reduceSingleLeafToSelf??Xc,b=t.chunker??rl({chunkSize:s}),S=t.chunkValidator??$u(),A=t.dagBuilder??zu({chunker:b,chunkValidator:S,wrapWithDirectory:o,layout:t.layout??Eo({maxChildrenPerNode:i}),bufferImporter:t.bufferImporter??Mu({cidVersion:u,rawLeaves:d,leafType:h,onProgress:t.onProgress}),blockWriteConcurrency:g,reduceSingleLeafToSelf:w,cidVersion:u,onProgress:t.onProgress,dirBuilder:t.dirBuilder,fileBuilder:t.fileBuilder}),v=t.treeBuilder??Ed({wrapWithDirectory:o,shardSplitThresholdBytes:a,shardSplitStrategy:c,shardFanoutBits:l,cidVersion:u,onProgress:t.onProgress});for await(let P of v(Er(A(n,e),p),e))yield{cid:P.cid,path:P.path,unixfs:P.unixfs,size:P.size}}async function Lo(r,e,t={}){let n=await xi(No([r],e,t));if(n==null)throw new Yt("Nothing imported");return n}async function tg(r,e,t={}){let n=await xi(No([r],e,t));if(n==null)throw new Yt("Nothing imported");return n}async function rg(r,e,t={}){return Lo({content:r},e,t)}async function ng(r,e,t={}){return Lo({content:r},e,t)}var Bo=m(()=>{"use strict";Kc();ki();nl();Pr();Uu();Wu();Hu();Gr();Yu();Cd();Gr()});function sg(r){return typeof r?.then=="function"}var ws,Id=m(()=>{"use strict";ms();Gu();Ir();ot();Kr();Ut();Yr();ws=class extends ke{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=Vu(n);if(sg(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(j.encode(t.multihash.bytes),n),t}*get(t,n){n?.signal?.throwIfAborted();let s=this.data.get(j.encode(t.multihash.bytes));if(s==null)throw new je;yield*s}has(t,n){return n?.signal?.throwIfAborted(),this.data.has(j.encode(t.multihash.bytes))}async delete(t,n){n?.signal?.throwIfAborted(),this.data.delete(j.encode(t.multihash.bytes))}*getAll(t){t?.signal?.throwIfAborted();for(let[n,s]of this.data.entries())yield{cid:H.createV1(_t,ns(j.decode(n))),bytes:(async function*(){yield*s})()},t?.signal?.throwIfAborted()}}});function bs(r,e){if(typeof r=="string")return ig(r);if(typeof r=="number")return cg(r,e);throw new Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(r)}`)}function ig(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 og(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 ag(r){let e=Math.abs(r);return e>=315576e5?ft(r,e,315576e5,"year"):e>=26298e5?ft(r,e,26298e5,"month"):e>=6048e5?ft(r,e,6048e5,"week"):e>=864e5?ft(r,e,864e5,"day"):e>=36e5?ft(r,e,36e5,"hour"):e>=6e4?ft(r,e,6e4,"minute"):e>=1e3?ft(r,e,1e3,"second"):`${r} ms`}function cg(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?ag(r):og(r)}function ft(r,e,t,n){let s=e>=t*1.5;return`${Math.round(r/t)} ${n}${s?"s":""}`}var _o=m(()=>{"use strict"});function Ko(r){t.debug=t,t.default=t,t.coerce=c,t.disable=i,t.enable=s,t.enabled=o,t.humanize=bs,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,p=null,g,w;function b(...S){if(!b.enabled)return;let A=b,v=Number(new Date),P=v-(h||v);A.diff=P,A.prev=h,A.curr=v,h=v,S[0]=t.coerce(S[0]),typeof S[0]!="string"&&S.unshift("%O");let k=0;S[0]=S[0].replace(/%([a-zA-Z%])/g,(T,O)=>{if(T==="%%")return"%";k++;let Ee=t.formatters[O];if(typeof Ee=="function"){let pt=S[k];T=Ee.call(A,pt),S.splice(k,1),k--}return T}),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:()=>p!==null?p:(g!==t.namespaces&&(g=t.namespaces,w=t.enabled(u)),w),set:S=>{p=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,]+/),p=h.length;for(d=0;d<p;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 Bd=m(()=>{"use strict";_o()});function ug(){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 dg(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+bs(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 fg(r){try{r?Ss?.setItem("debug",r):Ss?.removeItem("debug")}catch{}}function pg(){let r;try{r=Ss?.getItem("debug")}catch{}return!r&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(r=globalThis.process.env.DEBUG),r}function mg(){try{return localStorage}catch{}}function gg(r){r.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var Ss,lg,hg,Td,Rd=m(()=>{"use strict";_o();Bd();Ss=mg(),lg=["#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"];hg=console.debug??console.log??(()=>{});Td=Ko({formatArgs:dg,save:fg,load:pg,useColors:ug,setupFormatters:gg,colors:lg,storage:Ss,log:hg})});var X,Dd=m(()=>{"use strict";Rd();X=Td});function Fd(r,e=""){let t=Md(r.message),n=Md(r.stack);return t!=null&&n!=null?n.includes(t)?`${n.split(`
951
951
  `).join(`
952
952
  ${e}`)}`:`${t}
953
953
  ${e}${n.split(`
954
954
  `).join(`
955
955
  ${e}`)}`:n!=null?`${n.split(`
956
956
  `).join(`
957
- ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function ug(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function Cd(r,e=""){if(ug(r)){let t=Ed(r,e);return r.errors.length>0?(e=`${e} `,t+=`
958
- ${e}${r.errors.map(n=>`${Cd(n,`${e}`)}`).join(`
957
+ ${e}`)}`:t!=null?`${t}`:`${r.toString()}`}function yg(r){return r instanceof AggregateError||r?.name==="AggregateError"&&Array.isArray(r.errors)}function Ud(r,e=""){if(yg(r)){let t=Fd(r,e);return r.errors.length>0?(e=`${e} `,t+=`
958
+ ${e}${r.errors.map(n=>`${Ud(n,`${e}`)}`).join(`
959
959
  ${e}`)}`):t+=`
960
- ${e}[Error list was empty]`,t.trim()}return Ed(r,e)}function dg(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 Mo(r,e){let t=dg(`${r}:trace`);return X.enabled(`${r}:trace`)&&X.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=X(`${r}:trace`,e)),Object.assign(X(r,e),{error:X(`${r}:error`,e),trace:t,newScope:n=>Mo(`${r}:${n}`,e)})}function kd(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var Pd=p(()=>{"use strict";Cr();Jn();Ji();vd();X.formatters.b=r=>r==null?"undefined":le.baseEncode(r);X.formatters.t=r=>r==null?"undefined":J.baseEncode(r);X.formatters.m=r=>r==null?"undefined":Yi.baseEncode(r);X.formatters.p=r=>r==null?"undefined":r.toString();X.formatters.c=r=>r==null?"undefined":r.toString();X.formatters.k=r=>r==null?"undefined":r.toString();X.formatters.a=r=>r==null?"undefined":r.toString();X.formatters.e=r=>r==null?"undefined":Cd(r)});function hg(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 Id,Bd=p(()=>{"use strict";Id=hg});function fg(r){return r[Symbol.asyncIterator]!=null}function pg(r,e){let t=0;if(fg(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=Id(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 Dd,Td=p(()=>{"use strict";Bd();Dd=pg});function Xt(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var Rd=p(()=>{"use strict"});function mg(r){return r.reason}async function Fd(r,e,t){if(e==null)return r;let n=t?.translateError??mg;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 Md=p(()=>{"use strict"});function Ud(){return new Uo}var Uo,Nd=p(()=>{"use strict";Rd();Md();Uo=class{constructor(){f(this,"readNext");f(this,"haveNext");f(this,"ended");f(this,"nextResult");f(this,"error");this.ended=!1,this.readNext=Xt(),this.haveNext=Xt()}[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=Xt(),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=Xt(),await Fd(this.readNext.promise,t?.signal,t)}}});function gg(r){return r[Symbol.asyncIterator]!=null}async function yg(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*wg(r){let e=new AbortController,t=Ud();yg(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*bg(r){for(let e of r)yield*e}function Sg(...r){let e=[];for(let t of r)gg(t)||e.push(t);return e.length===r.length?bg(e):wg(r)}var Ld,_d=p(()=>{"use strict";Nd();Ld=Sg});var Ag,ys,Kd=p(()=>{"use strict";Pd();ds();Td();_d();Vr();Ag=Mo("blockstore:core:tiered"),ys=class extends Ce{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,Ag.error(o)}throw s??new je}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*Dd(Ld(...this.stores.map(s=>s.getAll(t))),s=>{let i=s.cid.toString();return n.has(i)?!1:(n.add(i),!0)})}}});var Od={};E(Od,{BaseBlockstore:()=>Ce,BlackHoleBlockstore:()=>Zt,MemoryBlockstore:()=>ps,TieredBlockstore:()=>ys});var zd=p(()=>{"use strict";Vr();bd();Po();Kd()});var Wd=P((sx,xg)=>{xg.exports={name:"w3pk",version:"0.10.1",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/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","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",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"}}}});G();function Lo(r){return/^0x[a-fA-F0-9]{40}$/.test(r)}function _o(r){return r.length<3||r.length>50?!1:/^[a-zA-Z0-9]([a-zA-Z0-9_-]*[a-zA-Z0-9])?$/.test(r)}function Ko(r){let e=r.trim().split(/\s+/);return e.length===12||e.length===24}function bs(r){if(!Lo(r))throw new Error("Invalid Ethereum address format")}function Ss(r){if(!_o(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 sh(r){if(!Ko(r))throw new Error("Invalid mnemonic: must be 12 or 24 words")}function ih(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)))}Ue();fe();W();async function ah(r){try{let e=new Uint8Array(r),t=ch(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 lh(c);return he(l)}catch(e){return console.error("Failed to extract public key:",e),null}}function ch(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 lh(r){let e=Ho(r,-2),t=Ho(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 Ho(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 Vo(r){try{let{username:e,ethereumAddress:t}=r;Ss(e),bs(t);let n=new R;if(await n.userExists(e))throw new Error("Username already registered");let s=Fe(),o=new TextEncoder().encode(e),a=he(o),c=L(s),l=L(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:{}}},d=await navigator.credentials.create({publicKey:u});if(!d)throw new Error("Failed to create credential");let h=d.getClientExtensionResults().prf?.enabled;h||console.warn("\u26A0\uFE0F PRF extension not supported - falling back to legacy encryption");let m=await ah(d.response.attestationObject);if(!m)throw new Error("Public key not returned from authenticator");return await n.saveCredential({id:d.id,publicKey:m,username:e,ethereumAddress:t,createdAt:new Date().toISOString(),lastUsed:new Date().toISOString(),signCount:0,prfEnabled:h||!1}),{signature:d.response.attestationObject}}catch(e){throw new tr(e instanceof Error?e.message:"Registration failed",e)}}G();Ue();fe();W();async function Qr(){try{let r=new R,e=Fe(),t=[];try{let d=await r.getAllCredentials();d.length>0&&(t=d.map(h=>({id:h.id,type:"public-key",transports:["internal","hybrid","usb","nfc","ble"]})))}catch{}let n=L(e),s=new Uint8Array(32);crypto.getRandomValues(s);let i={challenge:n,rpId:window.location.hostname,userVerification:"required",timeout:6e4,extensions:{prf:{eval:{first:s}}}};t.length>0&&(i.allowCredentials=t.map(d=>({id:L(d.id),type:d.type,transports:d.transports})));let o;try{let d=await navigator.credentials.get({publicKey:i});if(!d)throw new Error("Authentication failed - no credential returned");o=d}catch(d){throw d?.name==="NotAllowedError"||d?.message?.toLowerCase().includes("no credentials available")||d?.message?.toLowerCase().includes("no access key")?(await r.getAllCredentials()).length>0?new K("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 K("No passkey found. Please register first or restore from a backup."):d}let a=await r.getCredentialById(o.id);if(!a)throw new K("Passkey authenticated but wallet data not found on this device. To sync your account: 1) Select your passkey when prompted, then 2) Provide your backup file. This allows you to use the same passkey on multiple devices.");if(!await uh(o,a,r))throw new Error("Signature verification failed");let u=o.getClientExtensionResults().prf?.results?.first;return!u&&a.prfEnabled&&console.warn("\u26A0\uFE0F PRF was enabled but output not available"),{verified:!0,user:{username:a.username,ethereumAddress:a.ethereumAddress,credentialId:a.id},signature:o.response.signature,prfOutput:u||void 0}}catch(r){throw new K(r instanceof Error?r.message:"Authentication failed",r)}}async function uh(r,e,t){try{let n=r.response.authenticatorData,s=new DataView(n),o=new Uint8Array(n).slice(0,32),a=window.location.hostname,c=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(a)));if(!dh(o,c))return console.error("RP ID hash mismatch - possible phishing attack"),!1;let l=s.getUint32(33,!1);if(l>0||e.signCount&&e.signCount>0){let A=e.signCount||0;if(l<=A)return console.error(`Authenticator cloning detected! Counter did not increase: stored=${A}, received=${l}`),!1}let u=L(e.publicKey),d=await crypto.subtle.importKey("spki",u,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),h=r.response.clientDataJSON,m=await crypto.subtle.digest("SHA-256",h),g=new Uint8Array(n.byteLength+m.byteLength);g.set(new Uint8Array(n),0),g.set(new Uint8Array(m),n.byteLength);let y=r.response.signature,b=hh(new Uint8Array(y));return await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},d,b,g)?(await t.updateSignatureCounter(e.id,l),!0):!1}catch(n){return console.error("Signature verification error:",n),!1}}function dh(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 hh(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}G();var fh="Web3PasskeyWallet",ph=1,Se="wallets",Zr=class{constructor(){this.db=null}async init(){return new Promise((e,t)=>{let n=indexedDB.open(fh,ph);n.onerror=()=>t(new B("Failed to open database",n.error)),n.onsuccess=()=>{this.db=n.result,e()},n.onupgradeneeded=()=>{let s=n.result;s.objectStoreNames.contains(Se)||s.createObjectStore(Se,{keyPath:"ethereumAddress"})}})}async store(e){return this.db||await this.init(),new Promise((t,n)=>{let o=this.db.transaction([Se],"readwrite").objectStore(Se).put(e);o.onerror=()=>n(new B("Failed to store wallet data",o.error)),o.onsuccess=()=>t()})}async retrieve(e){return this.db||await this.init(),new Promise((t,n)=>{let o=this.db.transaction([Se],"readonly").objectStore(Se).get(e);o.onerror=()=>n(new B("Failed to retrieve wallet data",o.error)),o.onsuccess=()=>t(o.result||null)})}async delete(e){return this.db||await this.init(),new Promise((t,n)=>{let o=this.db.transaction([Se],"readwrite").objectStore(Se).delete(e);o.onerror=()=>n(new B("Failed to delete wallet data",o.error)),o.onsuccess=()=>t()})}async clear(){return this.db||await this.init(),new Promise((e,t)=>{let i=this.db.transaction([Se],"readwrite").objectStore(Se).clear();i.onerror=()=>t(new B("Failed to clear wallet data",i.error)),i.onsuccess=()=>e()})}};Ie();St();W();fe();G();G();import{ethers as j}from"ethers";function rr(r){try{let e=j.HDNodeWallet.fromPhrase(r,void 0,"m/44'/60'/1'/0/0"),t=j.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 M("Failed to derive stealth keys",e)}}function ks(r){try{let e="0x"+r.slice(2,68),t="0x"+r.slice(68),n=j.Wallet.createRandom(),s=n.signingKey.compressedPublicKey,i=Cs(n.privateKey,t),o=j.keccak256(i),a="0x"+o.slice(2,4),c=Ps(o),l=Zo(e,Qo(c));return{stealthAddress:Xo(l),ephemeralPubKey:s,viewTag:a}}catch(e){throw new M("Failed to generate stealth address",e)}}function sn(r,e,t,n,s){try{let i=Cs(r,t),o=j.keccak256(i);if(s&&("0x"+o.slice(2,4)).toLowerCase()!==s.toLowerCase())return{isForUser:!1};let a=Ps(o),c=Zo(e,Qo(a)),l=Xo(c);return l.toLowerCase()!==n.toLowerCase()?{isForUser:!1}:{isForUser:!0,stealthAddress:l}}catch{return{isForUser:!1}}}function on(r,e,t){try{let n=Cs(r,t),s=j.keccak256(n),i=Ps(s);return wh(e,i)}catch(n){throw new M("Failed to compute stealth private key",n)}}function yh(r,e,t,n,s,i){try{if(!sn(r,t,n,s,i).isForUser)return!1;let a=on(r,e,n);return new j.Wallet(a).address.toLowerCase()===s.toLowerCase()}catch{return!1}}function Cs(r,e){try{return new j.Wallet(r).signingKey.computeSharedSecret(e)}catch(t){throw new M("Failed to compute shared secret",t)}}function Qo(r){try{return new j.Wallet(r).signingKey.compressedPublicKey}catch(e){throw new M("Failed to multiply generator by scalar",e)}}function Zo(r,e){try{let t=j.SigningKey.computePublicKey(r,!1),n=j.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 g=3n*s*s%c,y=2n*i%c,b=g*Jo(y,c)%c,S=(b*b-2n*s)%c,A=(b*(s-S)-i)%c;return jo((S+c)%c,(A+c)%c)}let l=((a-i)%c+c)%c,u=((o-s)%c+c)%c,d=l*Jo(u,c)%c,h=(d*d-s-o)%c,m=(d*(s-h)-i)%c;return jo((h+c)%c,(m+c)%c)}catch(t){throw new M("Failed to add public keys",t)}}function Ps(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 M("Failed to reduce scalar modulo curve order",e)}}function wh(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 M("Failed to add private keys",t)}}function jo(r,e){return"0x"+(e%2n===0n?"02":"03")+r.toString(16).padStart(64,"0")}function Jo(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 Xo(r){try{let e=j.SigningKey.computePublicKey(r,!1),t=j.keccak256("0x"+e.slice(4));return j.getAddress("0x"+t.slice(-40))}catch(e){throw new M("Failed to derive address from public key",e)}}var nr=class{constructor(e,t){this.getMnemonic=t}async generateStealthAddress(e){try{let t=await this.getMnemonic(e?.requireAuth),n=rr(t),s=ks(n.stealthMetaAddress);return{stealthAddress:s.stealthAddress,ephemeralPublicKey:s.ephemeralPubKey,viewTag:s.viewTag}}catch(t){throw new V("Failed to generate stealth address","STEALTH_GENERATION_ERROR",t)}}async parseAnnouncement(e,t){try{let n=await this.getMnemonic(t?.requireAuth),s=rr(n),i=sn(s.viewingKey,s.spendingPubKey,e.ephemeralPublicKey,e.stealthAddress,e.viewTag);if(!i.isForUser)return{isForUser:!1};let o=on(s.viewingKey,s.spendingKey,e.ephemeralPublicKey);return{isForUser:!0,stealthAddress:i.stealthAddress,stealthPrivateKey:o}}catch(n){throw new V("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 rr(t)}catch(t){throw new V("Failed to get stealth keys","STEALTH_KEYS_ERROR",t)}}async getStealthMetaAddress(e){try{return(await this.getKeys(e)).stealthMetaAddress}catch(t){throw new V("Failed to get stealth meta-address","STEALTH_META_ADDRESS_ERROR",t)}}get isAvailable(){return!0}};G();W();var bh="Web3PasskeyPersistentSessions",Sh=2,oe="sessions",an=class{constructor(){this.db=null;this.initPromise=null}async init(){return this.initPromise?this.initPromise:this.db?Promise.resolve():(this.initPromise=new Promise((e,t)=>{let n=indexedDB.open(bh,Sh);n.onupgradeneeded=s=>{let i=s.target.result;i.objectStoreNames.contains(oe)||i.createObjectStore(oe,{keyPath:"ethereumAddress"}).createIndex("expiresAt","expiresAt",{unique:!1})},n.onsuccess=()=>{this.db=n.result,this.initPromise=null,e()},n.onerror=()=>{this.initPromise=null,t(new B("Failed to open persistent session database",n.error))}}),this.initPromise)}async store(e){if(e.securityMode==="STRICT")throw new B("Cannot persist STRICT mode sessions");return this.db||await this.init(),new Promise((t,n)=>{let o=this.db.transaction([oe],"readwrite").objectStore(oe).put(e);o.onerror=()=>n(new B("Failed to store persistent session",o.error)),o.onsuccess=()=>t()})}async retrieve(e){return this.db||await this.init(),new Promise((t,n)=>{let o=this.db.transaction([oe],"readonly").objectStore(oe).get(e);o.onerror=()=>n(new B("Failed to retrieve persistent session",o.error)),o.onsuccess=()=>{let a=o.result||null;if(a&&Date.now()>a.expiresAt){this.delete(e).catch(console.error),t(null);return}t(a)}})}async delete(e){return this.db||await this.init(),new Promise((t,n)=>{let o=this.db.transaction([oe],"readwrite").objectStore(oe).delete(e);o.onerror=()=>n(new B("Failed to delete persistent session",o.error)),o.onsuccess=()=>t()})}async clear(){return this.db||await this.init(),new Promise((e,t)=>{let i=this.db.transaction([oe],"readwrite").objectStore(oe).clear();i.onerror=()=>t(new B("Failed to clear persistent sessions",i.error)),i.onsuccess=()=>e()})}async cleanupExpired(){return this.db||await this.init(),new Promise((e,t)=>{let i=this.db.transaction([oe],"readwrite").objectStore(oe).index("expiresAt"),o=Date.now(),a=IDBKeyRange.upperBound(o),c=i.openCursor(a);c.onsuccess=l=>{let u=l.target.result;u?(u.delete(),u.continue()):e()},c.onerror=()=>t(new B("Failed to cleanup expired sessions",c.error))})}};async function ea(r,e,t){try{let n=await Y(void 0,void 0,e,t);return await se(r,n)}catch(n){throw new M("Failed to encrypt mnemonic for persistence",n)}}async function Is(r,e,t){try{let n=await Y(void 0,void 0,e,t);return await ie(r,n)}catch(n){throw new M("Failed to decrypt mnemonic from persistence",n)}}var cn=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 an}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&&s)try{let a=await ea(e,t,s),c=Date.now()+this.persistentConfig.duration*60*60*1e3;await this.persistentStorage.store({encryptedMnemonic:a,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(),null):this.session.mnemonic:null}getCredentialId(){return this.session?new Date>new Date(this.session.expiresAt)?(this.clearSession(),null):this.session.credentialId:null}isActive(){return this.getMnemonic()!==null}getRemainingTime(){return this.session?new Date>new Date(this.session.expiresAt)?(this.clearSession(),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(),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)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 Is(s.encryptedMnemonic,t,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(()=>(Ue(),Jr)),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}let o=await Is(i.encryptedMnemonic,s.id,s.publicKey),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,publicKey:s.publicKey}}return null}catch(e){return console.warn("[w3pk] Failed to attempt silent restore:",e),null}}async clearSession(){if(this.session&&(this.session.mnemonic="0".repeat(this.session.mnemonic.length)),this.session=null,this.persistentConfig.enabled)try{await this.persistentStorage.clear()}catch(e){console.warn("[w3pk] Failed to clear persistent sessions:",e)}}setSessionDuration(e){this.sessionDuration=e*60*60*1e3}};Ue();var ln={debug:!1,sessionDuration:1,persistentSession:{enabled:!1,duration:168,requireReauth:!0},onError:r=>{ln.debug&&console.error("[w3pk]",r)}};G();var ta="https://chainid.network/chains.json";var sr=null,Ah=[/\$\{[\w_]+\}/i,/\{[\w_]+\}/i,/<[\w_]+>/i,/YOUR[-_]?API[-_]?KEY/i,/INSERT[-_]?API[-_]?KEY/i,/API[-_]?KEY[-_]?HERE/i];function xh(r){return Ah.some(e=>e.test(r))}async function vh(r=ta){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 Bs(r){let e=r?.chainsJsonUrl??ta,t=r?.cacheDuration??36e5,n=Date.now();if(sr&&n-sr.timestamp<t)return sr.data;let s=await vh(e);return sr={data:s,timestamp:n},s}async function Ds(r,e){let n=(await Bs(e)).find(s=>s.chainId===r);return n?n.rpc.filter(s=>!xh(s)&&!s.startsWith("wss://")&&!s.startsWith("ws://")):[]}async function Eh(r){return Bs(r)}async function kh(r,e){return(await Bs(e)).find(n=>n.chainId===r)}function Ch(){sr=null}Ls();hn();var Rh=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 Fh(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 sa(r,e,t){if(Rh.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 Fh(a,s))return!0;return!1}catch{return!1}}function Ic(r){return typeof r=="string"&&/^0x[0-9a-fA-F]*$/.test(r)}function Bc(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 xr=class{constructor(e={}){this.currentUser=null;this.currentWallet=null;this.config={...ln,...e},this.walletStorage=new Zr;let t={...ln.persistentSession,...e.persistentSession};this.sessionManager=new cn(e.sessionDuration||1,t),e.stealthAddresses!==void 0&&(this.stealth=new nr(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 w("Must be authenticated. Call login() first.");let s=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!s)throw new w("No wallet found. Generate a wallet first.");let i=await Qr();if(!i.user)throw new w("Authentication failed");let c=(await new R().getCredentialById(s.credentialId))?.publicKey,l=s.salt?L(s.salt):void 0,u=await Y(i.prfOutput,l?new Uint8Array(l):void 0,s.credentialId,c),d=await ie(s.encryptedMnemonic,u);return await this.sessionManager.startSession(d,s.credentialId,this.currentUser.ethereumAddress,c,n),d}async register(e){try{this.currentWallet?.address||await this.generateWallet();let t=this.currentWallet.address,n=this.currentWallet.mnemonic;await Vo({username:e.username,ethereumAddress:t});let i=await new R().getCredentialByAddress(t);if(this.currentUser={username:e.username,ethereumAddress:t,credentialId:i?.id||""},!i)throw new w("Credential not found after registration");let o=i.id,a=i.publicKey,c=xs(),l=await Y(void 0,void 0,o,a),u=await se(n,l);return await this.walletStorage.store({ethereumAddress:this.currentUser.ethereumAddress,encryptedMnemonic:u,credentialId:o,createdAt:new Date().toISOString(),salt:i.prfEnabled?he(c):void 0}),await this.sessionManager.startSession(n,o,t,a,"STANDARD"),this.currentWallet={address:t,mnemonic:n},this.config.onAuthStateChanged?.(!0,this.currentUser),{address:t,username:e.username}}catch(t){throw this.config.onError?.(t),t}}async login(){try{let e=await this.sessionManager.attemptSilentRestore();if(e){let u=await new R().getCredentialById(e.credentialId);return this.currentUser={username:u?.username||e.ethereumAddress,ethereumAddress:e.ethereumAddress,credentialId:e.credentialId},await this.walletStorage.retrieve(this.currentUser.ethereumAddress)?(this.config.onAuthStateChanged?.(!0,this.currentUser),this.currentUser):(await this.sessionManager.clearSession(),this.login())}let t=await Qr();if(!t.verified||!t.user)throw new K("Login failed");this.currentUser={username:t.user.username,ethereumAddress:t.user.ethereumAddress,credentialId:t.user.credentialId};let n=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!n)return this.config.onAuthStateChanged?.(!0,this.currentUser),this.currentUser;let o=(await new R().getCredentialById(n.credentialId))?.publicKey,a=await this.sessionManager.restoreFromPersistentStorage(this.currentUser.ethereumAddress,n.credentialId,o||""),c;if(a)c=a;else{let l=await Y(void 0,void 0,n.credentialId,o);c=await ie(n.encryptedMnemonic,l),await this.sessionManager.startSession(c,n.credentialId,this.currentUser.ethereumAddress,o,"STANDARD")}return this.config.onAuthStateChanged?.(!0,this.currentUser),this.currentUser}catch(e){throw this.config.onError?.(e),e}}async logout(){this.currentUser=null,this.currentWallet=null,await this.sessionManager.clearSession(),this.config.onAuthStateChanged?.(!1,void 0)}get isAuthenticated(){return this.currentUser!==null}get user(){return this.currentUser}async listExistingCredentials(){try{return(await new R().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=en();return this.currentWallet={address:e.address,mnemonic:e.mnemonic},{address:e.address,mnemonic:e.mnemonic}}catch(e){throw this.config.onError?.(e),new w("Failed to generate wallet",e)}}async deriveWallet(e,t,n){try{if(!this.currentUser)throw new w("Must be authenticated to derive wallet");let s=e||Ae,i=t||ee,o=n?.origin||ve();if(s==="PRIMARY"){let{CredentialStorage:u}=await Promise.resolve().then(()=>(Ue(),Jr)),{deriveAddressFromP256PublicKey:d}=await Promise.resolve().then(()=>(St(),nn)),m=await new u().getCredentialById(this.currentUser.credentialId);if(!m||!m.publicKey)throw new w("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 xe(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 w("Failed to derive wallet",s)}}async getAddress(e,t,n){try{if(!this.currentUser)throw new w("Must be authenticated to get address");let s=e||Ae,i=t||ee,o=n?.origin||ve();if(s==="PRIMARY"){let{deriveAddressFromP256PublicKey:u}=await Promise.resolve().then(()=>(St(),nn)),h=await new R().getCredentialById(this.currentUser.credentialId);if(!h||!h.publicKey)throw new w("No WebAuthn credential found for PRIMARY mode");return await u(h.publicKey)}let a=s==="STRICT",c=await this.getMnemonicFromSession(a,s);return(await xe(c,o,s,i)).address}catch(s){throw this.config.onError?.(s),new w("Failed to get address",s)}}async importMnemonic(e){try{if(!this.currentUser)throw new w("Must be authenticated to import mnemonic");if(!e||e.trim().split(/\s+/).length<12)throw new w("Invalid mnemonic: must be at least 12 words");let t=await Qr();if(!t.user)throw new w("Authentication failed");let n=t.user.credentialId,o=(await new R().getCredentialById(n))?.publicKey,a=await Y(void 0,void 0,n,o),c=await se(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()},await this.sessionManager.startSession(e.trim(),n,this.currentUser.ethereumAddress,o,"STANDARD")}catch(t){throw this.config.onError?.(t),new w("Failed to import mnemonic",t)}}async signMessage(e,t){try{if(!this.currentUser)throw new w("Must be authenticated to sign message");let n=t?.mode||Ae,s=t?.tag||ee,i=t?.origin||ve(),o=t?.signingMethod||"EIP191",a=n==="STRICT"?!0:t?.requireAuth||!1,c=await this.getMnemonicFromSession(a,n),l=await xe(c,i,n,s),{Wallet:u}=await import("ethers"),d;if(l.privateKey)d=new u(l.privateKey);else{let{deriveWalletFromMnemonic:m}=await Promise.resolve().then(()=>(Ie(),bt)),{privateKey:g}=m(c,l.index);d=new u(g)}let h;switch(o){case"EIP191":case"SIWE":h=await d.signMessage(e);break;case"EIP712":if(!t?.eip712Domain||!t?.eip712Types||!t?.eip712PrimaryType)throw new w("EIP712 signing requires eip712Domain, eip712Types, and eip712PrimaryType in options");let m;try{m=typeof e=="string"?JSON.parse(e):e}catch{throw new w("EIP712 message must be valid JSON or an object")}h=await d.signTypedData(t.eip712Domain,t.eip712Types,m);break;case"rawHash":let{SigningKey:g}=await import("ethers"),y=e;if(y.startsWith("0x")&&(y=y.slice(2)),y.length!==64)throw new w("rawHash signing method requires a 32-byte hash (64 hex characters)");h=new g(d.privateKey).sign("0x"+y).serialized;break;default:throw new w(`Unsupported signing method: ${o}`)}return{signature:h,address:l.address,mode:l.mode,tag:l.tag,origin:l.origin}}catch(n){throw this.config.onError?.(n),new w("Failed to sign message",n)}}async signMessageWithPasskey(e){try{if(!this.currentUser)throw new w("Must be authenticated to sign message");let{extractRS:t}=await Promise.resolve().then(()=>(_s(),oa)),{base64UrlDecode:n}=await Promise.resolve().then(()=>(fe(),As)),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 w("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 w("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),g=new Uint8Array(d.length+m.byteLength);g.set(d,0),g.set(new Uint8Array(m),d.length);let y=await crypto.subtle.digest("SHA-256",g.buffer),b="0x"+Buffer.from(y).toString("hex"),S=new Uint8Array(u.signature),{r:A,s:v}=t(S),{CredentialStorage:k}=await Promise.resolve().then(()=>(Ue(),Jr)),x=await new k().getCredentialById(a);if(!x||!x.publicKey)throw new w("No WebAuthn credential found for PRIMARY mode");let{base64UrlToArrayBuffer:T}=await Promise.resolve().then(()=>(fe(),As)),O=T(x.publicKey),Pe=await crypto.subtle.importKey("spki",O,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),gt=await crypto.subtle.exportKey("jwk",Pe);if(!gt.x||!gt.y)throw new w("Invalid P-256 public key: missing x or y coordinates");let Gd="0x"+Buffer.from(T(gt.x)).toString("hex"),Yd="0x"+Buffer.from(T(gt.y)).toString("hex"),{deriveAddressFromP256PublicKey:jd}=await Promise.resolve().then(()=>(St(),nn)),Jd=await jd(x.publicKey);return{signature:{r:A,s:v},messageHash:i,signedHash:b,address:Jd,publicKey:{qx:Gd,qy:Yd}}}catch(t){throw this.config.onError?.(t),new w("Failed to sign message with passkey",t)}}async sendTransaction(e,t){try{if(!this.currentUser)throw new w("Must be authenticated to send transaction");let n=t?.mode||Ae,s=t?.tag||ee,i=t?.origin||ve();if(n==="PRIMARY")throw t?.rpcUrl?new w("PRIMARY mode sendTransaction is not yet supported. Use signMessageWithPasskey() to obtain a P-256 signature and submit via a bundler manually."):new w("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 xe(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(()=>(Ie(),bt)),{privateKey:S}=b(a,c.index);d=new l(S)}let h=t?.rpcUrl??(await this.getEndpoints(e.chainId))[0];if(!h)throw new w(`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 w("Failed to send transaction",n)}}async signAuthorization(e,t){try{if(!this.currentUser)throw new w("Must be authenticated to sign authorization");let{Wallet:n,Signature:s}=await import("ethers"),{hashEIP7702AuthorizationMessage:i,verifyEIP7702Authorization:o}=await Promise.resolve().then(()=>(hn(),Rs)),a;if(e.privateKey)a=new n(e.privateKey);else{let y=await this.getMnemonicFromSession(t?.requireAuth);a=n.fromPhrase(y)}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 w("Signature verification failed - this should not happen");return m}catch(n){throw this.config.onError?.(n),new w("Failed to sign authorization",n)}}async getEndpoints(e){return Ds(e)}async supportsEIP7702(e,t){return sa(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 w("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=Ic(l)?Bc(l):l;return(await n.signMessage(u,{mode:e?.mode,tag:e?.tag,signingMethod:"EIP191"})).signature}case"eth_sign":{let[,l]=c??[],u=Ic(l)?Bc(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:g}=u,y={...h};return delete y.EIP712Domain,(await n.signMessage(JSON.stringify(m),{mode:e?.mode,tag:e?.tag,signingMethod:"EIP712",eip712Domain:d,eip712Types:y,eip712PrimaryType:g})).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 w(`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 w("Must be authenticated to get w3pk delegation address. Call login() or register() first.");let{requestExternalWalletAuthorization:t,getDefaultProvider:n}=await Promise.resolve().then(()=>(Ls(),na)),s=e?.provider||n();if(!s)throw new w("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 w("Must be authenticated to check backup status");let{BackupManager:e}=await Promise.resolve().then(()=>(it(),st));return new e().getBackupStatus(this.currentUser.ethereumAddress)}async createBackupFile(e="password",t){if(!this.currentUser)throw new w("Must be authenticated to create backup");let n=await this.getMnemonicFromSession(!0),{BackupFileManager:s}=await Promise.resolve().then(()=>(ce(),pe)),{BackupStorage:i}=await Promise.resolve().then(()=>(fn(),aa)),o=new s,a=new i,c,l;if(e==="password"){if(!t)throw new w("Password required for password-based backup");l=(await o.createPasswordBackup(n,this.currentUser.ethereumAddress,t)).backupFile,c=o.createDownloadableBackup(l)}else if(e==="passkey"){let u=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!u)throw new w("No wallet data found");let h=await new R().getCredentialById(u.credentialId);if(!h)throw new w("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 w("Password required for hybrid backup");let u=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!u)throw new w("No wallet data found");let h=await new R().getCredentialById(u.credentialId);if(!h)throw new w("Credential not found");l=(await o.createHybridBackup(n,this.currentUser.ethereumAddress,t,h.id,h.publicKey)).backupFile,c=o.createDownloadableBackup(l)}else throw new w(`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 setupSocialRecovery(e,t,n){if(!this.currentUser)throw new w("Must be authenticated to set up social recovery");let s=await this.getMnemonicFromSession(!0),{BackupFileManager:i}=await Promise.resolve().then(()=>(ce(),pe)),o=new i,a;if(n)a=(await o.createPasswordBackup(s,this.currentUser.ethereumAddress,n)).backupFile;else{let d=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!d)throw new w("No wallet data found");let m=await new R().getCredentialById(d.credentialId);if(!m)throw new w("Credential not found");a=(await o.createPasskeyBackup(s,this.currentUser.ethereumAddress,m.id,m.publicKey)).backupFile}let{SocialRecovery:c}=await Promise.resolve().then(()=>(Nn(),Un));return{guardianShares:(await new c().splitAmongGuardians(a,e,t)).guardianShares,setupComplete:!0}}async generateGuardianInvite(e,t){let{SocialRecovery:n}=await Promise.resolve().then(()=>(Nn(),Un)),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(()=>(Nn(),Un)),{BackupFileManager:s}=await Promise.resolve().then(()=>(ce(),pe)),{BackupManager:i}=await Promise.resolve().then(()=>(it(),st)),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 w("Password required to decrypt password-protected backup");d=await a.restoreWithPassword(u,t)}else throw new w("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(()=>(ce(),pe)),{BackupManager:s}=await Promise.resolve().then(()=>(it(),st)),i=new n,o=new s,a=await i.parseBackupFile(e),c,l;if(a.encryptionMethod==="password"){if(!t)throw new w("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 w("Must be logged in with passkey to restore passkey-encrypted backup. Call login() first.");let h=(await new R().getAllCredentials()).find(g=>g.ethereumAddress.toLowerCase()===this.currentUser.ethereumAddress.toLowerCase());if(!h)throw new w("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 w("Password required to restore hybrid backup");if(!this.currentUser)throw new w("Must be logged in with passkey to restore hybrid backup. Call login() first.");let h=(await new R().getAllCredentials()).find(g=>g.ethereumAddress.toLowerCase()===this.currentUser.ethereumAddress.toLowerCase());if(!h)throw new w("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 w(`Unknown encryption method: ${a.encryptionMethod}`);if(o.markBackupVerified(l),this.currentWallet={address:l,mnemonic:c},this.currentUser){let u=new R,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 g=await(await Promise.resolve().then(()=>(W(),Me))).deriveEncryptionKeyAuto(void 0,void 0,h.id,h.publicKey),y=await(await Promise.resolve().then(()=>(W(),Me))).encryptData(c,g);await this.walletStorage.store({ethereumAddress:l,encryptedMnemonic:y,credentialId:h.id,createdAt:new Date().toISOString()}),this.currentUser={...this.currentUser,ethereumAddress:l},await this.sessionManager.startSession(c,h.id,l,h.publicKey,"STANDARD"),this.config.onAuthStateChanged?.(!0,this.currentUser)}}return{mnemonic:c,ethereumAddress:l}}async syncWalletWithPasskey(e,t){let{BackupFileManager:n}=await Promise.resolve().then(()=>(ce(),pe)),{BackupManager:s}=await Promise.resolve().then(()=>(it(),st)),{promptPasskeySelection:i}=await Promise.resolve().then(()=>(hi(),pc)),o=new n,a=new s,c=await i(),l=await o.parseBackupFile(e),u,d;if(l.encryptionMethod==="password"){if(!t)throw new w("Password required to restore password-encrypted backup");let g=await o.restoreWithPassword(l,t);u=g.mnemonic,d=g.ethereumAddress}else if(l.encryptionMethod==="passkey"){if(!c.publicKey)throw new w("Passkey public key not found. The passkey may not be registered on this device yet.");let g=await o.restoreWithExistingPasskey(l,c.credentialId,c.publicKey);u=g.mnemonic,d=g.ethereumAddress}else if(l.encryptionMethod==="hybrid"){if(!t)throw new w("Password required to restore hybrid backup");if(!c.publicKey)throw new w("Passkey public key not found. The passkey may not be registered on this device yet.");let g=await o.restoreWithHybrid(l,t,c.credentialId,c.publicKey);u=g.mnemonic,d=g.ethereumAddress}else throw new w(`Unknown encryption method: ${l.encryptionMethod}`);a.markBackupVerified(d);let m=await new R().getCredentialById(c.credentialId);if(m){let{deriveEncryptionKeyAuto:g,encryptData:y}=await Promise.resolve().then(()=>(W(),Me)),b=await g(void 0,void 0,m.id,m.publicKey),S=await y(u,b);await this.walletStorage.store({ethereumAddress:d,encryptedMnemonic:S,credentialId:m.id,createdAt:new Date().toISOString()}),this.currentUser={username:m.username,ethereumAddress:d,credentialId:m.id},await this.sessionManager.startSession(u,m.id,d,m.publicKey,"STANDARD"),this.config.onAuthStateChanged?.(!0,this.currentUser)}return{mnemonic:u,ethereumAddress:d}}async registerWithBackupFile(e,t,n){let{BackupFileManager:s}=await Promise.resolve().then(()=>(ce(),pe)),{BackupManager:i}=await Promise.resolve().then(()=>(it(),st)),o=new s,a=new i,c=await o.parseBackupFile(e);if(c.encryptionMethod!=="password")throw new w("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 w("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(()=>(wr(),Ln));return new e().getSyncInfo()}async exportForSync(){if(!this.currentUser)throw new w("Must be authenticated to export for sync");let e=await this.getMnemonicFromSession(!0),t=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!t)throw new w("No wallet data found");let s=await new R().getCredentialById(t.credentialId);if(!s)throw new w("Credential not found");let{DeviceSyncManager:i}=await Promise.resolve().then(()=>(wr(),Ln)),o=new i,{backupFile:a,blob:c}=await o.exportForSync(e,this.currentUser.ethereumAddress,s.id,s.publicKey),l=`w3pk-sync-${this.currentUser.ethereumAddress.substring(0,8)}.json`,u;try{u=await o.generateSyncQR(a)}catch(d){console.warn("QR code generation failed:",d)}return{blob:c,filename:l,qrCode:u}}async importFromSync(e){if(!this.currentUser)throw new w("Must be logged in to import from sync. Call login() first.");let{DeviceSyncManager:t}=await Promise.resolve().then(()=>(wr(),Ln)),{BackupFileManager:n}=await Promise.resolve().then(()=>(ce(),pe)),{BackupManager:s}=await Promise.resolve().then(()=>(it(),st)),i=new n,o=new t,a=new s,c=await i.parseBackupFile(e),l=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!l)throw new w("No wallet data found for current user");let d=await new R().getCredentialById(l.credentialId);if(!d)throw new w("Credential not found");let{mnemonic:h,ethereumAddress:m}=await o.importFromSync(c,d.id,d.publicKey);a.markBackupVerified(m);let g=await(await Promise.resolve().then(()=>(W(),Me))).deriveEncryptionKeyAuto(void 0,void 0,d.id,d.publicKey),y=await(await Promise.resolve().then(()=>(W(),Me))).encryptData(h,g);return await this.walletStorage.store({ethereumAddress:m,encryptedMnemonic:y,credentialId:d.id,createdAt:new Date().toISOString()}),{ethereumAddress:m,success:!0}}async detectSyncCapabilities(){let{PlatformDetector:e}=await Promise.resolve().then(()=>(Sc(),bc));return new e().detectSyncCapabilities()}async simulateRecoveryScenario(e){if(!this.currentUser)throw new w("Must be authenticated to run recovery simulation");let t=await this.getBackupStatus(),{RecoverySimulator:n}=await Promise.resolve().then(()=>(Sr(),Wn));return new n().simulateScenario(e,t)}async runRecoveryTest(){if(!this.currentUser)throw new w("Must be authenticated to run recovery test");let e=await this.getBackupStatus(),{RecoverySimulator:t}=await Promise.resolve().then(()=>(Sr(),Wn));return new t().runInteractiveTest(e)}async getEducation(e){let{getExplainer:t}=await Promise.resolve().then(()=>(Sr(),Wn)),n=t(e);if(!n)throw new w(`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 w("Cannot extend session",e)}}async clearSession(){await this.sessionManager.clearSession()}setSessionDuration(e){this.sessionManager.setSessionDuration(e)}async deriveMLKemPublicKey(e){if(!this.currentUser)throw new w("Must be authenticated to derive ML-KEM public key");let{deriveMLKemKeypair:t}=await Promise.resolve().then(()=>(Ar(),qn)),{Wallet:n}=await import("ethers"),s=e?.mode||"STANDARD",i=e?.tag||ee,o=e?.origin||ve(),a=e?.context||"mlkem-v1",c=s==="STRICT"?!0:e?.requireAuth||!1;if(s==="PRIMARY")throw new w("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 xe(l,o,s,i),d;if(u.privateKey)d=u.privateKey;else{let{deriveWalletFromMnemonic:m}=await Promise.resolve().then(()=>(Ie(),bt));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 w("Must be authenticated to encrypt data");let{mlkemEncryptWithKey:s}=await Promise.resolve().then(()=>(Ar(),qn)),i=n?.mode||"STANDARD",o=n?.tag||ee,a=n?.origin||ve(),c=n?.context||"mlkem-v1",l=i==="STRICT"?!0:n?.requireAuth||!1;if(i==="PRIMARY")throw new w("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 xe(u,a,i,o),h;if(d.privateKey)h=d.privateKey;else{let{deriveWalletFromMnemonic:m}=await Promise.resolve().then(()=>(Ie(),bt));h=m(u,d.index).privateKey}return await s(e,h,t,c)}async mlkemDecrypt(e,t){if(!this.currentUser)throw new w("Must be authenticated to decrypt data");let{mlkemDecryptWithKey:n}=await Promise.resolve().then(()=>(Ar(),qn)),s=t?.mode||"STANDARD",i=t?.tag||ee,o=t?.origin||ve(),a=t?.context||"mlkem-v1",c=s==="STRICT"?!0:t?.requireAuth||!1;if(s==="PRIMARY")throw new w("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 xe(l,o,s,i),d;if(u.privateKey)d=u.privateKey;else{let{deriveWalletFromMnemonic:h}=await Promise.resolve().then(()=>(Ie(),bt));d=h(l,u.index).privateKey}return await n(e,d,a)}};G();hi();St();Sr();async function vg(r,e="build"){let{importer:t}=await Promise.resolve().then(()=>(vo(),wd)),{MemoryBlockstore:n}=await Promise.resolve().then(()=>(zd(),Od)),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 Eg(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 $d(r){let e=await Eg(r);return vg(e)}function qd(){try{return Wd().version}catch{throw new Error("Failed to read package version")}}async function Hd(){let r=qd();return $d(`https://unpkg.com/w3pk@${r}/dist`)}async function kg(r){return await Hd()===r}fe();_s();Ie();function Cg(r=11){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=new Uint8Array(r);return crypto.getRandomValues(t),Array.from(t).map(n=>e[n%e.length]).join("")}function Pg(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(`
960
+ ${e}[Error list was empty]`,t.trim()}return Fd(r,e)}function wg(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 Oo(r,e){let t=wg(`${r}:trace`);return X.enabled(`${r}:trace`)&&X.names.map(n=>n.toString()).find(n=>n.includes(":trace"))!=null&&(t=X(`${r}:trace`,e)),Object.assign(X(r,e),{error:X(`${r}:error`,e),trace:t,newScope:n=>Oo(`${r}:${n}`,e)})}function Md(r){if(r!=null&&(r=r.trim(),r.length!==0))return r}var Nd=m(()=>{"use strict";Ir();es();ro();Dd();X.formatters.b=r=>r==null?"undefined":ae.baseEncode(r);X.formatters.t=r=>r==null?"undefined":j.baseEncode(r);X.formatters.m=r=>r==null?"undefined":eo.baseEncode(r);X.formatters.p=r=>r==null?"undefined":r.toString();X.formatters.c=r=>r==null?"undefined":r.toString();X.formatters.k=r=>r==null?"undefined":r.toString();X.formatters.a=r=>r==null?"undefined":r.toString();X.formatters.e=r=>r==null?"undefined":Ud(r)});function bg(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 Ld,_d=m(()=>{"use strict";Ld=bg});function Sg(r){return r[Symbol.asyncIterator]!=null}function Ag(r,e){let t=0;if(Sg(r))return(async function*(){for await(let c of r)await e(c,t++)&&(yield c)})();let n=Ld(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 Kd,Od=m(()=>{"use strict";_d();Kd=Ag});function Xt(){let r={};return r.promise=new Promise((e,t)=>{r.resolve=e,r.reject=t}),r}var zd=m(()=>{"use strict"});function xg(r){return r.reason}async function Wd(r,e,t){if(e==null)return r;let n=t?.translateError??xg;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 $d=m(()=>{"use strict"});function Hd(){return new zo}var zo,qd=m(()=>{"use strict";zd();$d();zo=class{constructor(){f(this,"readNext");f(this,"haveNext");f(this,"ended");f(this,"nextResult");f(this,"error");this.ended=!1,this.readNext=Xt(),this.haveNext=Xt()}[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=Xt(),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=Xt(),await Wd(this.readNext.promise,t?.signal,t)}}});function vg(r){return r[Symbol.asyncIterator]!=null}async function kg(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*Eg(r){let e=new AbortController,t=Hd();kg(r,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Cg(r){for(let e of r)yield*e}function Pg(...r){let e=[];for(let t of r)vg(t)||e.push(t);return e.length===r.length?Cg(e):Eg(r)}var Vd,Gd=m(()=>{"use strict";qd();Vd=Pg});var Ig,As,Yd=m(()=>{"use strict";Nd();ms();Od();Gd();Yr();Ig=Oo("blockstore:core:tiered"),As=class extends ke{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,Ig.error(o)}throw s??new je}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*Kd(Vd(...this.stores.map(s=>s.getAll(t))),s=>{let i=s.cid.toString();return n.has(i)?!1:(n.add(i),!0)})}}});var jd={};x(jd,{BaseBlockstore:()=>ke,BlackHoleBlockstore:()=>Qt,MemoryBlockstore:()=>ws,TieredBlockstore:()=>As});var Jd=m(()=>{"use strict";Yr();Id();Fo();Yd()});var Qd=E((ux,Bg)=>{Bg.exports={name:"w3pk",version:"0.10.3",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","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"}}}});G();function $o(r){return/^0x[a-fA-F0-9]{40}$/.test(r)}function Ho(r){return r.length<3||r.length>50?!1:/^[a-zA-Z0-9]([a-zA-Z0-9_-]*[a-zA-Z0-9])?$/.test(r)}function qo(r){let e=r.trim().split(/\s+/);return e.length===12||e.length===24}function vs(r){if(!$o(r))throw new Error("Invalid Ethereum address format")}function ks(r){if(!Ho(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 fh(r){if(!qo(r))throw new Error("Invalid mnemonic: must be 12 or 24 words")}function ph(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)))}Ue();we();$();async function yh(r){try{let e=new Uint8Array(r),t=wh(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 bh(c);return ye(l)}catch(e){return console.error("Failed to extract public key:",e),null}}function wh(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 bh(r){let e=Jo(r,-2),t=Jo(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 Jo(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 Qo(r){try{let{username:e,ethereumAddress:t}=r;ks(e),vs(t);let n=new R;if(await n.userExists(e))throw new Error("Username already registered");let s=Fe(),o=new TextEncoder().encode(e),a=ye(o),c=L(s),l=L(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:nr}}}},d=await navigator.credentials.create({publicKey:u});if(!d)throw new Error("Failed to create credential");let h=await yh(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 p=d.response.attestationObject,g=d.getClientExtensionResults?.().prf?.results?.first;return{signature:p,prfOutput:g}}catch(e){throw new er(e instanceof Error?e.message:"Registration failed",e)}}G();Ue();we();$();async function Zr(){try{let r=new R,e=Fe(),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:L(e),rpId:window.location.hostname,userVerification:"required",timeout:6e4,extensions:{prf:{eval:{first:nr}}}};t.length>0&&(s.allowCredentials=t.map(l=>({id:L(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 z("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 z("No passkey found. Please register first or restore from a backup."):l}let o=await r.getCredentialById(i.id);if(!o)throw new tr(i.id);if(!await Sh(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 K?r:new z(r instanceof Error?r.message:"Authentication failed",r)}}async function Sh(r,e,t){try{let n=r.response.authenticatorData,s=new DataView(n),o=new Uint8Array(n).slice(0,32),a=window.location.hostname,c=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(a)));if(!Ah(o,c))return console.error("RP ID hash mismatch - possible phishing attack"),!1;let l=s.getUint32(33,!1);if(l>0||e.signCount&&e.signCount>0){let A=e.signCount||0;if(l<=A)return console.error(`Authenticator cloning detected! Counter did not increase: stored=${A}, received=${l}`),!1}let u=L(e.publicKey),d=await crypto.subtle.importKey("spki",u,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),h=r.response.clientDataJSON,p=await crypto.subtle.digest("SHA-256",h),g=new Uint8Array(n.byteLength+p.byteLength);g.set(new Uint8Array(n),0),g.set(new Uint8Array(p),n.byteLength);let w=r.response.signature,b=xh(new Uint8Array(w));return await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},d,b,g)?(await t.updateSignatureCounter(e.id,l),!0):!1}catch(n){return console.error("Signature verification error:",n),!1}}function Ah(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 xh(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}G();var en="w3pk_wallet_",tn=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 I("localStorage is not available")}async init(){}async store(e){try{this.storage.setItem(en+e.ethereumAddress,JSON.stringify(e))}catch(t){throw new I("Failed to store wallet data",t)}}async retrieve(e){try{let t=this.storage.getItem(en+e);return t?JSON.parse(t):null}catch(t){throw new I("Failed to retrieve wallet data",t)}}async delete(e){try{this.storage.removeItem(en+e)}catch(t){throw new I("Failed to delete wallet data",t)}}async clear(){try{for(let e of this.keys())this.storage.removeItem(e)}catch(e){throw new I("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(en)&&e.push(n)}return e}};Ce();bt();$();G();G();import{ethers as Y}from"ethers";function sr(r){try{let e=Y.HDNodeWallet.fromPhrase(r,void 0,"m/44'/60'/1'/0/0"),t=Y.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 U("Failed to derive stealth keys",e)}}function Ts(r){try{let e="0x"+r.slice(2,68),t="0x"+r.slice(68),n=Y.Wallet.createRandom(),s=n.signingKey.compressedPublicKey,i=Rs(n.privateKey,t),o=Y.keccak256(i),a="0x"+o.slice(2,4),c=Ds(o),l=na(e,ra(c));return{stealthAddress:sa(l),ephemeralPubKey:s,viewTag:a}}catch(e){throw new U("Failed to generate stealth address",e)}}function cn(r,e,t,n,s){try{let i=Rs(r,t),o=Y.keccak256(i);if(s&&("0x"+o.slice(2,4)).toLowerCase()!==s.toLowerCase())return{isForUser:!1};let a=Ds(o),c=na(e,ra(a)),l=sa(c);return l.toLowerCase()!==n.toLowerCase()?{isForUser:!1}:{isForUser:!0,stealthAddress:l}}catch{return{isForUser:!1}}}function ln(r,e,t){try{let n=Rs(r,t),s=Y.keccak256(n),i=Ds(s);return Ch(e,i)}catch(n){throw new U("Failed to compute stealth private key",n)}}function Eh(r,e,t,n,s,i){try{if(!cn(r,t,n,s,i).isForUser)return!1;let a=ln(r,e,n);return new Y.Wallet(a).address.toLowerCase()===s.toLowerCase()}catch{return!1}}function Rs(r,e){try{return new Y.Wallet(r).signingKey.computeSharedSecret(e)}catch(t){throw new U("Failed to compute shared secret",t)}}function ra(r){try{return new Y.Wallet(r).signingKey.compressedPublicKey}catch(e){throw new U("Failed to multiply generator by scalar",e)}}function na(r,e){try{let t=Y.SigningKey.computePublicKey(r,!1),n=Y.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 g=3n*s*s%c,w=2n*i%c,b=g*ta(w,c)%c,S=(b*b-2n*s)%c,A=(b*(s-S)-i)%c;return ea((S+c)%c,(A+c)%c)}let l=((a-i)%c+c)%c,u=((o-s)%c+c)%c,d=l*ta(u,c)%c,h=(d*d-s-o)%c,p=(d*(s-h)-i)%c;return ea((h+c)%c,(p+c)%c)}catch(t){throw new U("Failed to add public keys",t)}}function Ds(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 U("Failed to reduce scalar modulo curve order",e)}}function Ch(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 U("Failed to add private keys",t)}}function ea(r,e){return"0x"+(e%2n===0n?"02":"03")+r.toString(16).padStart(64,"0")}function ta(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 sa(r){try{let e=Y.SigningKey.computePublicKey(r,!1),t=Y.keccak256("0x"+e.slice(4));return Y.getAddress("0x"+t.slice(-40))}catch(e){throw new U("Failed to derive address from public key",e)}}var ir=class{constructor(e,t){this.getMnemonic=t}async generateStealthAddress(e){try{let t=await this.getMnemonic(e?.requireAuth),n=sr(t),s=Ts(n.stealthMetaAddress);return{stealthAddress:s.stealthAddress,ephemeralPublicKey:s.ephemeralPubKey,viewTag:s.viewTag}}catch(t){throw new K("Failed to generate stealth address","STEALTH_GENERATION_ERROR",t)}}async parseAnnouncement(e,t){try{let n=await this.getMnemonic(t?.requireAuth),s=sr(n),i=cn(s.viewingKey,s.spendingPubKey,e.ephemeralPublicKey,e.stealthAddress,e.viewTag);if(!i.isForUser)return{isForUser:!1};let o=ln(s.viewingKey,s.spendingKey,e.ephemeralPublicKey);return{isForUser:!0,stealthAddress:i.stealthAddress,stealthPrivateKey:o}}catch(n){throw new K("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 sr(t)}catch(t){throw new K("Failed to get stealth keys","STEALTH_KEYS_ERROR",t)}}async getStealthMetaAddress(e){try{return(await this.getKeys(e)).stealthMetaAddress}catch(t){throw new K("Failed to get stealth meta-address","STEALTH_META_ADDRESS_ERROR",t)}}get isAvailable(){return!0}};G();var un="w3pk_session_",dn=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 I("localStorage is not available")}async init(){}async store(e){if(e.securityMode==="STRICT")throw new I("Cannot persist STRICT mode sessions");try{this.storage.setItem(un+e.ethereumAddress,JSON.stringify(e))}catch(t){throw new I("Failed to store persistent session",t)}}async retrieve(e){let t;try{let n=this.storage.getItem(un+e);t=n?JSON.parse(n):null}catch(n){throw new I("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(un+e)}catch(t){throw new I("Failed to delete persistent session",t)}}async clear(){try{for(let e of this.keys())this.storage.removeItem(e)}catch(e){throw new I("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 I("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(un)&&e.push(n)}return e}};$();var hn=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 dn}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 se(e,s),c=Date.now()+this.persistentConfig.duration*60*60*1e3;await this.persistentStorage.store({encryptedMnemonic:a,sessionKey:this.persistentConfig.requireReauth?void 0:await Cs(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 Z(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(()=>(Ue(),Xr)),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 Z(i.encryptedMnemonic,await Ps(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}};Ue();var fn={debug:!1,sessionDuration:1,persistentSession:{enabled:!1,duration:168,requireReauth:!0},onError:r=>{fn.debug&&console.error("[w3pk]",r)}};G();var ia="https://chainid.network/chains.json";var or=null,Ph=[/\$\{[\w_]+\}/i,/\{[\w_]+\}/i,/<[\w_]+>/i,/YOUR[-_]?API[-_]?KEY/i,/INSERT[-_]?API[-_]?KEY/i,/API[-_]?KEY[-_]?HERE/i];function Ih(r){return Ph.some(e=>e.test(r))}async function Bh(r=ia){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 Fs(r){let e=r?.chainsJsonUrl??ia,t=r?.cacheDuration??36e5,n=Date.now();if(or&&n-or.timestamp<t)return or.data;let s=await Bh(e);return or={data:s,timestamp:n},s}async function Ms(r,e){let n=(await Fs(e)).find(s=>s.chainId===r);return n?n.rpc.filter(s=>!Ih(s)&&!s.startsWith("wss://")&&!s.startsWith("ws://")):[]}async function Th(r){return Fs(r)}async function Rh(r,e){return(await Fs(e)).find(n=>n.chainId===r)}function Dh(){or=null}zs();gn();var _h=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 Kh(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 ca(r,e,t){if(_h.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 Kh(a,s))return!0;return!1}catch{return!1}}function Lc(r){return typeof r=="string"&&/^0x[0-9a-fA-F]*$/.test(r)}function _c(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 kr=class{constructor(e={}){this.currentUser=null;this.currentWallet=null;this.persisted=null;this.config={...fn,...e},this.walletStorage=new tn;let t={...fn.persistentSession,...e.persistentSession};this.sessionManager=new hn(e.sessionDuration||1,t),e.stealthAddresses!==void 0&&(this.stealth=new ir(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 y("Must be authenticated. Call login() first.");let s=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!s)throw new y("No wallet found. Generate a wallet first.");let i=await Zr();if(!i.user)throw new y("Authentication failed");let c=(await new R().getCredentialById(s.credentialId))?.publicKey,l=await ue(s.credentialId,c),u=await Z(s.encryptedMnemonic,l),d=i.prfOutput?await gt(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 Qo({username:e.username,ethereumAddress:t}),o=await new R().getCredentialByAddress(t);if(this.currentUser={username:e.username,ethereumAddress:t,credentialId:o?.id||""},!o)throw new y("Credential not found after registration");let a=o.id,c=o.publicKey,l=await ue(a,c),u=await se(n,l);await this.walletStorage.store({ethereumAddress:this.currentUser.ethereumAddress,encryptedMnemonic:u,credentialId:a,createdAt:new Date().toISOString()});let d=s.prfOutput?await gt(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(()=>(Be(),Ie)),p=await new h().hasBackup(t);return this.requestPersistentStorage(),this.config.onAuthStateChanged?.(!0,this.currentUser),{address:t,username:e.username,hasBackup:p}}catch(t){throw this.config.onError?.(t),t}}async login(){try{let e=await this.sessionManager.attemptSilentRestore();if(e){let d=await new R().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(p=>console.warn("[w3pk] Failed to clear stale session:",p)),this.login())}let t=await Zr();if(!t.verified||!t.user)throw new z("Login failed");let n=await this.walletStorage.retrieve(t.user.ethereumAddress);if(!n)throw new rr(t.user.credentialId,t.user.ethereumAddress);this.currentUser={username:t.user.username,ethereumAddress:t.user.ethereumAddress,credentialId:t.user.credentialId};let o=(await new R().getCredentialById(n.credentialId))?.publicKey,a=t.prfOutput?await gt(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 ue(n.credentialId,o);l=await Z(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 R().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=nn();return this.currentWallet={address:e.address,mnemonic:e.mnemonic},{address:e.address,mnemonic:e.mnemonic}}catch(e){throw this.config.onError?.(e),new y("Failed to generate wallet",e)}}async deriveWallet(e,t,n){try{if(!this.currentUser)throw new y("Must be authenticated to derive wallet");let s=e||be,i=t||ee,o=n?.origin||Ae();if(s==="PRIMARY"){let{CredentialStorage:u}=await Promise.resolve().then(()=>(Ue(),Xr)),{deriveAddressFromP256PublicKey:d}=await Promise.resolve().then(()=>(bt(),an)),p=await new u().getCredentialById(this.currentUser.credentialId);if(!p||!p.publicKey)throw new y("No WebAuthn credential found for PRIMARY mode");return{address:await d(p.publicKey),origin:o,mode:s,tag:i,publicKey:p.publicKey}}let a=s==="STRICT"?!0:n?.requireAuth||!1,c=await this.getMnemonicFromSession(a,s),l=await Se(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 y("Failed to derive wallet",s)}}async getAddress(e,t,n){try{if(!this.currentUser)throw new y("Must be authenticated to get address");let s=e||be,i=t||ee,o=n?.origin||Ae();if(s==="PRIMARY"){let{deriveAddressFromP256PublicKey:u}=await Promise.resolve().then(()=>(bt(),an)),h=await new R().getCredentialById(this.currentUser.credentialId);if(!h||!h.publicKey)throw new y("No WebAuthn credential found for PRIMARY mode");return await u(h.publicKey)}let a=s==="STRICT",c=await this.getMnemonicFromSession(a,s);return(await Se(c,o,s,i)).address}catch(s){throw this.config.onError?.(s),new y("Failed to get address",s)}}async importMnemonic(e){try{if(!this.currentUser)throw new y("Must be authenticated to import mnemonic");if(!e||e.trim().split(/\s+/).length<12)throw new y("Invalid mnemonic: must be at least 12 words");let t=await Zr();if(!t.user)throw new y("Authentication failed");let n=t.user.credentialId,o=(await new R().getCredentialById(n))?.publicKey,a=await ue(n,o),c=await se(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 gt(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 y("Failed to import mnemonic",t)}}async signMessage(e,t){try{let n=t?.mode||be,s=t?.signingMethod||"EIP191";if(n==="PRIMARY"&&s==="SIWE")throw new y("SIWE signing is not supported in PRIMARY mode. Use STANDARD, STRICT or YOLO mode.");if(!this.currentUser)throw new y("Must be authenticated to sign message");let i=t?.tag||ee,o=t?.origin||Ae(),a=n==="STRICT"?!0:t?.requireAuth||!1,c=await this.getMnemonicFromSession(a,n),l=await Se(c,o,n,i),{Wallet:u}=await import("ethers"),d;if(l.privateKey)d=new u(l.privateKey);else{let{deriveWalletFromMnemonic:p}=await Promise.resolve().then(()=>(Ce(),wt)),{privateKey:g}=p(c,l.index);d=new u(g)}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 y("EIP712 signing requires eip712Domain, eip712Types, and eip712PrimaryType in options");let p;try{p=typeof e=="string"?JSON.parse(e):e}catch{throw new y("EIP712 message must be valid JSON or an object")}h=await d.signTypedData(t.eip712Domain,t.eip712Types,p);break;case"rawHash":let{SigningKey:g}=await import("ethers"),w=e;if(w.startsWith("0x")&&(w=w.slice(2)),w.length!==64)throw new y("rawHash signing method requires a 32-byte hash (64 hex characters)");h=new g(d.privateKey).sign("0x"+w).serialized;break;default:throw new y(`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 y("Failed to sign message",n)}}async signMessageWithPasskey(e){try{if(!this.currentUser)throw new y("Must be authenticated to sign message");let{extractRS:t}=await Promise.resolve().then(()=>(mi(),mc)),{base64UrlDecode:n}=await Promise.resolve().then(()=>(we(),Es)),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 y("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 y("WebAuthn signature failed");let u=l.response,d=new Uint8Array(u.authenticatorData),h=new Uint8Array(u.clientDataJSON),p=await crypto.subtle.digest("SHA-256",h),g=new Uint8Array(d.length+p.byteLength);g.set(d,0),g.set(new Uint8Array(p),d.length);let w=await crypto.subtle.digest("SHA-256",g.buffer),b="0x"+Buffer.from(w).toString("hex"),S=new Uint8Array(u.signature),{r:A,s:v}=t(S),{CredentialStorage:P}=await Promise.resolve().then(()=>(Ue(),Xr)),F=await new P().getCredentialById(a);if(!F||!F.publicKey)throw new y("No WebAuthn credential found for PRIMARY mode");let{base64UrlToArrayBuffer:T}=await Promise.resolve().then(()=>(we(),Es)),O=T(F.publicKey),Ee=await crypto.subtle.importKey("spki",O,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),pt=await crypto.subtle.exportKey("jwk",Ee);if(!pt.x||!pt.y)throw new y("Invalid P-256 public key: missing x or y coordinates");let rh="0x"+Buffer.from(T(pt.x)).toString("hex"),nh="0x"+Buffer.from(T(pt.y)).toString("hex"),{deriveAddressFromP256PublicKey:sh}=await Promise.resolve().then(()=>(bt(),an)),ih=await sh(F.publicKey);return{signature:{r:A,s:v},messageHash:i,signedHash:b,address:ih,publicKey:{qx:rh,qy:nh}}}catch(t){throw this.config.onError?.(t),new y("Failed to sign message with passkey",t)}}async sendTransaction(e,t){try{if(!this.currentUser)throw new y("Must be authenticated to send transaction");let n=t?.mode||be,s=t?.tag||ee,i=t?.origin||Ae();if(n==="PRIMARY")throw t?.rpcUrl?new y("PRIMARY mode sendTransaction is not yet supported. Use signMessageWithPasskey() to obtain a P-256 signature and submit via a bundler manually."):new y("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 Se(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(()=>(Ce(),wt)),{privateKey:S}=b(a,c.index);d=new l(S)}let h=t?.rpcUrl??(await this.getEndpoints(e.chainId))[0];if(!h)throw new y(`No RPC endpoint found for chainId ${e.chainId}. Pass options.rpcUrl.`);let p=new u(h);return{hash:(await d.connect(p).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 y("Failed to send transaction",n)}}async signAuthorization(e,t){try{if(!this.currentUser)throw new y("Must be authenticated to sign authorization");let{Wallet:n,Signature:s}=await import("ethers"),{hashEIP7702AuthorizationMessage:i,verifyEIP7702Authorization:o}=await Promise.resolve().then(()=>(gn(),Ns)),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),p={chainId:c,address:e.contractAddress.toLowerCase(),nonce:l,yParity:h.yParity,r:h.r,s:h.s};if(!o(c,e.contractAddress,l,p,a.address))throw new y("Signature verification failed - this should not happen");return p}catch(n){throw this.config.onError?.(n),new y("Failed to sign authorization",n)}}async getEndpoints(e){return Ms(e)}async supportsEIP7702(e,t){return ca(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 y("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=Lc(l)?_c(l):l;return(await n.signMessage(u,{mode:e?.mode,tag:e?.tag,signingMethod:"EIP191"})).signature}case"eth_sign":{let[,l]=c??[],u=Lc(l)?_c(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:p,primaryType:g}=u,w={...h};return delete w.EIP712Domain,(await n.signMessage(JSON.stringify(p),{mode:e?.mode,tag:e?.tag,signingMethod:"EIP712",eip712Domain:d,eip712Types:w,eip712PrimaryType:g})).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 y(`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 y("Must be authenticated to get w3pk delegation address. Call login() or register() first.");let{requestExternalWalletAuthorization:t,getDefaultProvider:n}=await Promise.resolve().then(()=>(zs(),aa)),s=e?.provider||n();if(!s)throw new y("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 y("Must be authenticated to check backup status");let{BackupManager:e}=await Promise.resolve().then(()=>(Be(),Ie));return new e().getBackupStatus(this.currentUser.ethereumAddress)}async confirmRecoveryPhraseBackup(){if(!this.currentUser)throw new y("Must be authenticated to confirm a backup");let{BackupManager:e}=await Promise.resolve().then(()=>(Be(),Ie)),{deriveAddressChecksum:t}=await Promise.resolve().then(()=>(Ne(),$s)),{ethereumAddress:n}=this.currentUser;await new e().confirmRecoveryPhraseBackup(n,await t(n))}async createBackupFile(e="password",t){if(!this.currentUser)throw new y("Must be authenticated to create backup");let n=await this.getMnemonicFromSession(!0),{BackupFileManager:s}=await Promise.resolve().then(()=>(oe(),de)),{BackupStorage:i}=await Promise.resolve().then(()=>(yn(),ua)),o=new s,a=new i,c,l;if(e==="password"){if(!t)throw new y("Password required for password-based backup");l=(await o.createPasswordBackup(n,this.currentUser.ethereumAddress,t)).backupFile,c=o.createDownloadableBackup(l)}else if(e==="passkey"){let u=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!u)throw new y("No wallet data found");let h=await new R().getCredentialById(u.credentialId);if(!h)throw new y("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 y("Password required for hybrid backup");let u=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!u)throw new y("No wallet data found");let h=await new R().getCredentialById(u.credentialId);if(!h)throw new y("Credential not found");l=(await o.createHybridBackup(n,this.currentUser.ethereumAddress,t,h.id,h.publicKey)).backupFile,c=o.createDownloadableBackup(l)}else throw new y(`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 setupSocialRecovery(e,t,n){if(!this.currentUser)throw new y("Must be authenticated to set up social recovery");let s=await this.getMnemonicFromSession(!0),{BackupFileManager:i}=await Promise.resolve().then(()=>(oe(),de)),o=new i,a;if(n)a=(await o.createPasswordBackup(s,this.currentUser.ethereumAddress,n)).backupFile;else{let d=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!d)throw new y("No wallet data found");let p=await new R().getCredentialById(d.credentialId);if(!p)throw new y("Credential not found");a=(await o.createPasskeyBackup(s,this.currentUser.ethereumAddress,p.id,p.publicKey)).backupFile}let{SocialRecovery:c}=await Promise.resolve().then(()=>(On(),Kn));return{guardianShares:(await new c().splitAmongGuardians(a,e,t)).guardianShares,setupComplete:!0}}async generateGuardianInvite(e,t){let{SocialRecovery:n}=await Promise.resolve().then(()=>(On(),Kn)),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(()=>(On(),Kn)),{BackupFileManager:s}=await Promise.resolve().then(()=>(oe(),de)),{BackupManager:i}=await Promise.resolve().then(()=>(Be(),Ie)),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 y("Password required to decrypt password-protected backup");d=await a.restoreWithPassword(u,t)}else throw new y("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(()=>(oe(),de)),{BackupManager:s}=await Promise.resolve().then(()=>(Be(),Ie)),i=new n,o=new s,a=await i.parseBackupFile(e),c,l;if(a.encryptionMethod==="password"){if(!t)throw new y("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 y("Must be logged in with passkey to restore passkey-encrypted backup. Call login() first.");let h=(await new R().getAllCredentials()).find(g=>g.ethereumAddress.toLowerCase()===this.currentUser.ethereumAddress.toLowerCase());if(!h)throw new y("Credential not found for current user");let p=await i.restoreWithExistingPasskey(a,h.id,h.publicKey);c=p.mnemonic,l=p.ethereumAddress}else if(a.encryptionMethod==="hybrid"){if(!t)throw new y("Password required to restore hybrid backup");if(!this.currentUser)throw new y("Must be logged in with passkey to restore hybrid backup. Call login() first.");let h=(await new R().getAllCredentials()).find(g=>g.ethereumAddress.toLowerCase()===this.currentUser.ethereumAddress.toLowerCase());if(!h)throw new y("Credential not found for current user");let p=await i.restoreWithHybrid(a,t,h.id,h.publicKey);c=p.mnemonic,l=p.ethereumAddress}else throw new y(`Unknown encryption method: ${a.encryptionMethod}`);if(o.markBackupVerified(l),this.currentWallet={address:l,mnemonic:c},this.currentUser){let u=new R,h=(await u.getAllCredentials()).find(p=>p.ethereumAddress.toLowerCase()===this.currentUser.ethereumAddress.toLowerCase());if(h){let p=this.currentUser.ethereumAddress;p.toLowerCase()!==l.toLowerCase()&&await this.walletStorage.delete(p),await u.updateCredentialAddress(h.id,l);let g=await(await Promise.resolve().then(()=>($(),Me))).deriveEncryptionKeyFromWebAuthn(h.id,h.publicKey),w=await(await Promise.resolve().then(()=>($(),Me))).encryptData(c,g);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(()=>(oe(),de)),{BackupManager:s}=await Promise.resolve().then(()=>(Be(),Ie)),{promptPasskeySelection:i}=await Promise.resolve().then(()=>(yi(),wc)),o=new n,a=new s,c=await i(),l=await o.parseBackupFile(e),u,d;if(l.encryptionMethod==="password"){if(!t)throw new y("Password required to restore password-encrypted backup");let g=await o.restoreWithPassword(l,t);u=g.mnemonic,d=g.ethereumAddress}else if(l.encryptionMethod==="passkey"){if(!c.publicKey)throw new y("Passkey public key not found. The passkey may not be registered on this device yet.");let g=await o.restoreWithExistingPasskey(l,c.credentialId,c.publicKey);u=g.mnemonic,d=g.ethereumAddress}else if(l.encryptionMethod==="hybrid"){if(!t)throw new y("Password required to restore hybrid backup");if(!c.publicKey)throw new y("Passkey public key not found. The passkey may not be registered on this device yet.");let g=await o.restoreWithHybrid(l,t,c.credentialId,c.publicKey);u=g.mnemonic,d=g.ethereumAddress}else throw new y(`Unknown encryption method: ${l.encryptionMethod}`);a.markBackupVerified(d);let p=await new R().getCredentialById(c.credentialId);if(p){let{deriveEncryptionKeyFromWebAuthn:g,encryptData:w}=await Promise.resolve().then(()=>($(),Me)),b=await g(p.id,p.publicKey),S=await w(u,b);await this.walletStorage.store({ethereumAddress:d,encryptedMnemonic:S,credentialId:p.id,createdAt:new Date().toISOString()}),this.currentUser={username:p.username,ethereumAddress:d,credentialId:p.id},await this.sessionManager.startSession(u,p.id,d,void 0,"STANDARD"),this.requestPersistentStorage(),this.config.onAuthStateChanged?.(!0,this.currentUser)}return{mnemonic:u,ethereumAddress:d}}async registerWithBackupFile(e,t,n){let{BackupFileManager:s}=await Promise.resolve().then(()=>(oe(),de)),{BackupManager:i}=await Promise.resolve().then(()=>(Be(),Ie)),o=new s,a=new i,c=await o.parseBackupFile(e);if(c.encryptionMethod!=="password")throw new y("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 y("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(()=>(Sr(),zn));return new e().getSyncInfo()}async exportForSync(){if(!this.currentUser)throw new y("Must be authenticated to export for sync");let e=await this.getMnemonicFromSession(!0),t=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!t)throw new y("No wallet data found");let s=await new R().getCredentialById(t.credentialId);if(!s)throw new y("Credential not found");let{DeviceSyncManager:i}=await Promise.resolve().then(()=>(Sr(),zn)),o=new i,{backupFile:a,blob:c}=await o.exportForSync(e,this.currentUser.ethereumAddress,s.id,s.publicKey),l=`w3pk-sync-${this.currentUser.ethereumAddress.substring(0,8)}.json`,u;try{u=await o.generateSyncQR(a)}catch(d){console.warn("QR code generation failed:",d)}return{blob:c,filename:l,qrCode:u}}async importFromSync(e){if(!this.currentUser)throw new y("Must be logged in to import from sync. Call login() first.");let{DeviceSyncManager:t}=await Promise.resolve().then(()=>(Sr(),zn)),{BackupFileManager:n}=await Promise.resolve().then(()=>(oe(),de)),{BackupManager:s}=await Promise.resolve().then(()=>(Be(),Ie)),i=new n,o=new t,a=new s,c=await i.parseBackupFile(e),l=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!l)throw new y("No wallet data found for current user");let d=await new R().getCredentialById(l.credentialId);if(!d)throw new y("Credential not found");let{mnemonic:h,ethereumAddress:p}=await o.importFromSync(c,d.id,d.publicKey);a.markBackupVerified(p);let g=await(await Promise.resolve().then(()=>($(),Me))).deriveEncryptionKeyFromWebAuthn(d.id,d.publicKey),w=await(await Promise.resolve().then(()=>($(),Me))).encryptData(h,g);return await this.walletStorage.store({ethereumAddress:p,encryptedMnemonic:w,credentialId:d.id,createdAt:new Date().toISOString()}),{ethereumAddress:p,success:!0}}async detectSyncCapabilities(){let{PlatformDetector:e}=await Promise.resolve().then(()=>(kc(),vc));return new e().detectSyncCapabilities()}async simulateRecoveryScenario(e){if(!this.currentUser)throw new y("Must be authenticated to run recovery simulation");let t=await this.getBackupStatus(),{RecoverySimulator:n}=await Promise.resolve().then(()=>(xr(),Vn));return new n().simulateScenario(e,t)}async runRecoveryTest(){if(!this.currentUser)throw new y("Must be authenticated to run recovery test");let e=await this.getBackupStatus(),{RecoverySimulator:t}=await Promise.resolve().then(()=>(xr(),Vn));return new t().runInteractiveTest(e)}async getEducation(e){let{getExplainer:t}=await Promise.resolve().then(()=>(xr(),Vn)),n=t(e);if(!n)throw new y(`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 y("Cannot extend session",e)}}async clearSession(){await this.sessionManager.clearSession()}setSessionDuration(e){this.sessionManager.setSessionDuration(e)}setPersistentSessionDuration(e){this.sessionManager.setPersistentSessionDuration(e)}async deriveMLKemPublicKey(e){if(!this.currentUser)throw new y("Must be authenticated to derive ML-KEM public key");let{deriveMLKemKeypair:t}=await Promise.resolve().then(()=>(vr(),Yn)),{Wallet:n}=await import("ethers"),s=e?.mode||"STANDARD",i=e?.tag||ee,o=e?.origin||Ae(),a=e?.context||"mlkem-v1",c=s==="STRICT"?!0:e?.requireAuth||!1;if(s==="PRIMARY")throw new y("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 Se(l,o,s,i),d;if(u.privateKey)d=u.privateKey;else{let{deriveWalletFromMnemonic:p}=await Promise.resolve().then(()=>(Ce(),wt));d=p(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 y("Must be authenticated to encrypt data");let{mlkemEncryptWithKey:s}=await Promise.resolve().then(()=>(vr(),Yn)),i=n?.mode||"STANDARD",o=n?.tag||ee,a=n?.origin||Ae(),c=n?.context||"mlkem-v1",l=i==="STRICT"?!0:n?.requireAuth||!1;if(i==="PRIMARY")throw new y("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 Se(u,a,i,o),h;if(d.privateKey)h=d.privateKey;else{let{deriveWalletFromMnemonic:p}=await Promise.resolve().then(()=>(Ce(),wt));h=p(u,d.index).privateKey}return await s(e,h,t,c)}async mlkemDecrypt(e,t){if(!this.currentUser)throw new y("Must be authenticated to decrypt data");let{mlkemDecryptWithKey:n}=await Promise.resolve().then(()=>(vr(),Yn)),s=t?.mode||"STANDARD",i=t?.tag||ee,o=t?.origin||Ae(),a=t?.context||"mlkem-v1",c=s==="STRICT"?!0:t?.requireAuth||!1;if(s==="PRIMARY")throw new y("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 Se(l,o,s,i),d;if(u.privateKey)d=u.privateKey;else{let{deriveWalletFromMnemonic:h}=await Promise.resolve().then(()=>(Ce(),wt));d=h(l,u.index).privateKey}return await n(e,d,a)}};G();yi();bt();xr();async function Tg(r,e="build"){let{importer:t}=await Promise.resolve().then(()=>(Bo(),Pd)),{MemoryBlockstore:n}=await Promise.resolve().then(()=>(Jd(),jd)),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 Xd(r){let e=await Rg(r);return Tg(e)}function Zd(){try{return Qd().version}catch{throw new Error("Failed to read package version")}}async function eh(){let r=Zd();return Xd(`https://unpkg.com/w3pk@${r}/dist`)}async function Dg(r){return await eh()===r}we();mi();Ce();function Fg(r=11){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=new Uint8Array(r);return crypto.getRandomValues(t),Array.from(t).map(n=>e[n%e.length]).join("")}function Mg(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
961
  `))throw new Error("Statement cannot contain newlines");let e=`${r.domain} wants you to sign in with your Ethereum account:
962
962
  `;if(e+=`${r.address}
963
963
  `,e+=`
964
964
  `,r.statement&&(e+=`${r.statement}
965
- `,e+=`
966
- `),e+=`URI: ${r.uri}
965
+ `),e+=`
966
+ `,e+=`URI: ${r.uri}
967
967
  `,e+=`Version: ${r.version}
968
968
  `,e+=`Chain ID: ${r.chainId}
969
969
  `,e+=`Nonce: ${r.nonce}
@@ -972,12 +972,12 @@ Expiration Time: ${r.expirationTime}`),r.notBefore&&(e+=`
972
972
  Not Before: ${r.notBefore}`),r.requestId&&(e+=`
973
973
  Request ID: ${r.requestId}`),r.resources&&r.resources.length>0){e+=`
974
974
  Resources:`;for(let t of r.resources)e+=`
975
- - ${t}`}return e}function No(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,g,y=[],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: "))g=S.substring(12);else if(S.startsWith("Resources:")){for(b++;b<e.length&&e[b].startsWith("- ");)y.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:g,resources:y.length>0?y:void 0}}function Ig(r,e){let t=[];try{let n=typeof r=="string"?No(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 Bg(r,e,t){try{let{verifyMessage:n}=await import("ethers"),s=n(r,e),i=No(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}}}ui();Fn();function Dg(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(`
975
+ - ${t}`}return e}function Wo(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,p,g,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: "))p=S.substring(12);else if(S.startsWith("Request ID: "))g=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:p,requestId:g,resources:w.length>0?w:void 0}}function Ug(r,e){let t=[];try{let n=typeof r=="string"?Wo(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 Ng(r,e,t){try{let{verifyMessage:n}=await import("ethers"),s=n(r,e),i=Wo(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}}}pi();Ln();function Lg(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
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
978
  `);return o.length>e?o.substring(0,e)+`
979
979
 
980
- // ... (truncated)`:o||"// No transaction code found"}async function Tg(r,e=100){let t=`# Application Code Analysis
980
+ // ... (truncated)`:o||"// No transaction code found"}async function _g(r,e=100){let t=`# Application Code Analysis
981
981
 
982
982
  `;t+=`**App URL:** ${r}
983
983
 
@@ -989,7 +989,7 @@ Resources:`;for(let t of r.resources)e+=`
989
989
 
990
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
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=Dg(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}\`
992
+ `;break}try{let l=await fetch(c);if(!l.ok)continue;let u=await l.text(),d=Lg(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
993
 
994
994
  `,t+="```javascript\n",t+=d,t+=`
995
995
  \`\`\`
@@ -997,8 +997,8 @@ Resources:`;for(let t of r.resources)e+=`
997
997
  ---
998
998
 
999
999
  `,i++,o+=h}}catch{}}return i===0&&(t+=`No transaction-related code found in JavaScript files.
1000
- `),t}async function Vd(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 Tg(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 y=Array.from(document.querySelectorAll("script[src]")).map(b=>new URL(b.src).pathname).filter(b=>b&&!b.includes("node_modules"));return{report:m,analyzedFiles:y,appUrl:e}}async function Rg(r){console.log(`\u{1F50D} W3PK Security Inspection Starting...
1001
- `);try{let e=await Vd(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
1000
+ `),t}async function th(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 _g(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(),p=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:p,analyzedFiles:w,appUrl:e}}async function Kg(r){console.log(`\u{1F50D} W3PK Security Inspection Starting...
1001
+ `);try{let e=await th(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
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}}Ar();function Fg(r={}){return new xr(r)}var fx=Fg;export{ws as ApiError,K as AuthenticationError,M as CryptoError,Ae as DEFAULT_MODE,ee as DEFAULT_TAG,br as RecoverySimulator,tr as RegistrationError,Pt as SocialRecoveryManager,nr as StealthAddressModule,B as StorageError,w as WalletError,xr as Web3Passkey,V as Web3PasskeyError,he as arrayBufferToBase64Url,bs as assertEthereumAddress,sh as assertMnemonic,Ss as assertUsername,fc as authenticateWithPasskey,Oo as base64ToArrayBuffer,Wo as base64UrlDecode,L as base64UrlToArrayBuffer,yh as canControlStealthAddress,sn as checkStealthAddress,Ch as clearCache,on as computeStealthPrivateKey,Pg as createSiweMessage,Go as createWalletFromMnemonic,Fg as createWeb3Passkey,fx as default,Yo as deriveAddressFromP256PublicKey,Es as deriveIndexFromOriginModeAndTag,$n as deriveMLKemKeypair,rr as deriveStealthKeys,tn as deriveWalletFromMnemonic,Us as detectWalletProvider,un as encodeEIP7702AuthorizationMessage,ia as extractRS,en as generateBIP39Wallet,Cg as generateSiweNonce,ks as generateStealthAddress,Eh as getAllChains,vc as getAllTopics,kh as getChainById,Hd as getCurrentBuildHash,ve as getCurrentOrigin,Ms as getDefaultProvider,Ds as getEndpoints,xc as getExplainer,xe as getOriginSpecificAddress,qd as getPackageVersion,$d as getW3pkBuildHash,dn as hashEIP7702AuthorizationMessage,Vd as inspect,Rg as inspectNow,ih as isStrongPassword,mi as mlkemDecrypt,Pc as mlkemDecryptWithKey,pi as mlkemEncrypt,Cc as mlkemEncryptWithKey,rn as normalizeOrigin,No as parseSiweMessage,hc as promptPasskeySelection,Fs as requestExternalWalletAuthorization,yt as safeAtob,zo as safeBtoa,Ec as searchExplainers,Ns as supportsEIP7702Authorization,Lo as validateEthereumAddress,Ko as validateMnemonic,Ig as validateSiweMessage,_o as validateUsername,kg as verifyBuildHash,Ts as verifyEIP7702Authorization,Bg as verifySiweSignature};
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}}vr();function Og(r={}){return new kr(r)}var bx=Og;export{xs as ApiError,z as AuthenticationError,U as CryptoError,be as DEFAULT_MODE,ee as DEFAULT_TAG,Ar as RecoverySimulator,er as RegistrationError,Ct as SocialRecoveryManager,ir as StealthAddressModule,I as StorageError,tr as SyncRequiredError,y as WalletError,rr as WalletMissingError,kr as Web3Passkey,K as Web3PasskeyError,ye as arrayBufferToBase64Url,vs as assertEthereumAddress,fh as assertMnemonic,ks as assertUsername,yc as authenticateWithPasskey,Vo as base64ToArrayBuffer,Yo as base64UrlDecode,L as base64UrlToArrayBuffer,Eh as canControlStealthAddress,cn as checkStealthAddress,Dh as clearCache,ln as computeStealthPrivateKey,Mg as createSiweMessage,Xo as createWalletFromMnemonic,Og as createWeb3Passkey,bx as default,Zo as deriveAddressFromP256PublicKey,Bs as deriveIndexFromOriginModeAndTag,Gn as deriveMLKemKeypair,sr as deriveStealthKeys,sn as deriveWalletFromMnemonic,Ks as detectWalletProvider,pn as encodeEIP7702AuthorizationMessage,pc as extractRS,nn as generateBIP39Wallet,Fg as generateSiweNonce,Ts as generateStealthAddress,Th as getAllChains,Pc as getAllTopics,Rh as getChainById,eh as getCurrentBuildHash,Ae as getCurrentOrigin,_s as getDefaultProvider,Ms as getEndpoints,Cc as getExplainer,Se as getOriginSpecificAddress,Zd as getPackageVersion,Xd as getW3pkBuildHash,mn as hashEIP7702AuthorizationMessage,th as inspect,Kg as inspectNow,ph as isStrongPassword,Ai as mlkemDecrypt,Nc as mlkemDecryptWithKey,Si as mlkemEncrypt,Uc as mlkemEncryptWithKey,on as normalizeOrigin,Wo as parseSiweMessage,gc as promptPasskeySelection,Ls as requestExternalWalletAuthorization,mt as safeAtob,Go as safeBtoa,Ic as searchExplainers,Os as supportsEIP7702Authorization,$o as validateEthereumAddress,qo as validateMnemonic,Ug as validateSiweMessage,Ho as validateUsername,Dg as verifyBuildHash,Us as verifyEIP7702Authorization,Ng as verifySiweSignature};
1004
1004
  //# sourceMappingURL=index.mjs.map