w3pk 0.9.2 → 0.9.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.js CHANGED
@@ -1,11 +1,11 @@
1
- "use strict";var Ad=Object.create;var Xt=Object.defineProperty;var kd=Object.getOwnPropertyDescriptor;var Ed=Object.getOwnPropertyNames;var Cd=Object.getPrototypeOf,Pd=Object.prototype.hasOwnProperty;var Id=(n,e,t)=>e in n?Xt(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var w=(n,e)=>()=>(n&&(e=n(n=0)),e);var D=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),B=(n,e)=>{for(var t in e)Xt(n,t,{get:e[t],enumerable:!0})},Uo=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ed(e))!Pd.call(n,s)&&s!==t&&Xt(n,s,{get:()=>e[s],enumerable:!(r=kd(e,s))||r.enumerable});return n};var K=(n,e,t)=>(t=n!=null?Ad(Cd(n)):{},Uo(e||!n||!n.__esModule?Xt(t,"default",{value:n,enumerable:!0}):t,n)),Bd=n=>Uo(Xt({},"__esModule",{value:!0}),n);var p=(n,e,t)=>Id(n,typeof e!="symbol"?e+"":e,t);var $,O,ht,S,N,R,Hr,Y=w(()=>{"use strict";$=class extends Error{constructor(t,r,s){super(t);this.code=r;this.originalError=s;this.name="Web3PasskeyError"}},O=class extends ${constructor(e,t){super(e,"AUTHENTICATION_ERROR",t),this.name="AuthenticationError"}},ht=class extends ${constructor(e,t){super(e,"REGISTRATION_ERROR",t),this.name="RegistrationError"}},S=class extends ${constructor(e,t){super(e,"WALLET_ERROR",t),this.name="WalletError"}},N=class extends ${constructor(e,t){super(e,"CRYPTO_ERROR",t),this.name="CryptoError"}},R=class extends ${constructor(e,t){super(e,"STORAGE_ERROR",t),this.name="StorageError"}},Hr=class extends ${constructor(t,r,s){super(t,"API_ERROR",s);this.statusCode=r;this.name="ApiError"}}});var As={};B(As,{arrayBufferToBase64Url:()=>Se,base64ToArrayBuffer:()=>Ss,base64UrlDecode:()=>vs,base64UrlToArrayBuffer:()=>L,safeAtob:()=>Ve,safeBtoa:()=>xs});function L(n){try{let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;e+="=".repeat(t);let r=atob(e),s=new Uint8Array(r.length);for(let i=0;i<r.length;i++)s[i]=r.charCodeAt(i);return s.buffer}catch(e){throw new Error(`Failed to decode base64url string: ${e instanceof Error?e.message:"Invalid format"}`)}}function Se(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function Ss(n){try{let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t.buffer}catch(e){throw new Error(`Failed to decode base64 string: ${e instanceof Error?e.message:"Invalid format"}`)}}function Ve(n){try{let e=n.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 xs(n){try{let e=new TextEncoder().encode(n),t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}catch(e){throw new Error(`Failed to encode string: ${e instanceof Error?e.message:"Invalid input"}`)}}function vs(n){return L(n)}var xe=w(()=>{"use strict"});var Re={};B(Re,{decryptData:()=>oe,deriveEncryptionKey:()=>Dd,deriveEncryptionKeyFromWebAuthn:()=>j,encryptData:()=>ie,generateChallenge:()=>De,hashCredentialId:()=>ft,hashPublicKey:()=>ks});async function j(n,e){try{let t=e?`w3pk-v4:${n}:${e}`:`w3pk-v4:${n}`,r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)),s=await crypto.subtle.importKey("raw",r,{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 N("Failed to derive encryption key from WebAuthn",t)}}async function Dd(n,e){try{let t=e?`w3pk-v2:${n}:${e}`:`w3pk-v2:${n}`,r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)),s=await crypto.subtle.importKey("raw",r,{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 N("Failed to derive encryption key",t)}}function De(){let n=new Uint8Array(32);return crypto.getRandomValues(n),Se(n)}async function ie(n,e){try{let t=crypto.getRandomValues(new Uint8Array(12)),r=new TextEncoder().encode(n),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:t},e,r),i=new Uint8Array(t.length+s.byteLength);i.set(t),i.set(new Uint8Array(s),t.length);let o="";for(let c=0;c<i.length;c++)o+=String.fromCharCode(i[c]);return btoa(o)}catch(t){throw new N("Failed to encrypt data",t)}}async function oe(n,e){try{if(!n||n.length<16)throw new Error("Invalid encrypted data: too small");let t=Ve(n),r=new Uint8Array(t.length);for(let c=0;c<t.length;c++)r[c]=t.charCodeAt(c);if(r.length<12)throw new Error("Invalid encrypted data: missing IV");let s=r.slice(0,12),i=r.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 N(`Data decryption failed: ${t instanceof Error?t.message:"Unknown error"}`,t)}}async function ft(n){try{let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`w3pk-cred-id:${n}`));return Se(e)}catch(e){throw new N("Failed to hash credential ID",e)}}async function ks(n){try{let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));return Se(e)}catch(e){throw new N("Failed to hash public key",e)}}var q=w(()=>{"use strict";Y();xe()});var Jr={};B(Jr,{CredentialStorage:()=>F});async function Oo(n){let e=new TextEncoder().encode(`w3pk-metadata-v1:${n}`),t=await crypto.subtle.digest("SHA-256",e),r=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"},r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}var Yr,jr,F,Te=w(()=>{"use strict";Y();q();Yr="w3pk_credential_",jr="w3pk_credential_index";F=class{constructor(e){if(e)this.storage=e;else if(typeof window<"u"&&window.localStorage)this.storage=window.localStorage;else throw new R("localStorage is not available")}async saveCredential(e){try{let t=await Oo(e.id),r=await ft(e.id),s={id:r,encryptedUsername:await ie(e.username,t),encryptedAddress:await ie(e.ethereumAddress,t),publicKey:e.publicKey,publicKeyFingerprint:await ks(e.publicKey),createdAt:e.createdAt,lastUsed:e.lastUsed},i=`${Yr}${r}`;this.storage.setItem(i,JSON.stringify(s)),await this.addToIndex(e.id)}catch(t){throw new R("Failed to save credential",t)}}async getCredentialById(e){try{let t=await ft(e),r=`${Yr}${t}`,s=this.storage.getItem(r);if(!s)return null;let i=JSON.parse(s),o=await Oo(e);return{id:e,publicKey:i.publicKey,username:await oe(i.encryptedUsername,o),ethereumAddress:await oe(i.encryptedAddress,o),createdAt:i.createdAt,lastUsed:i.lastUsed}}catch(t){throw new R("Failed to retrieve credential",t)}}async getCredentialByUsername(e){try{return(await this.getAllCredentials()).find(r=>r.username===e)||null}catch(t){throw new R("Failed to retrieve credential",t)}}async getCredentialByAddress(e){try{return(await this.getAllCredentials()).find(r=>r.ethereumAddress.toLowerCase()===e.toLowerCase())||null}catch(t){throw new R("Failed to retrieve credential",t)}}async getAllCredentials(){try{let e=await this.getIndex();return(await Promise.all(e.map(async r=>await this.getCredentialById(r)))).filter(r=>r!==null)}catch(e){throw new R("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 R("Failed to update timestamp",t)}}async updateSignatureCounter(e,t){try{let r=await this.getCredentialById(e);r&&(r.signCount=t,r.lastUsed=new Date().toISOString(),await this.saveCredential(r))}catch(r){throw new R("Failed to update signature counter",r)}}async updateCredentialAddress(e,t){try{let r=await this.getCredentialById(e);r&&(r.ethereumAddress=t,r.lastUsed=new Date().toISOString(),await this.saveCredential(r))}catch(r){throw new R("Failed to update credential address",r)}}async deleteCredential(e){try{let t=await ft(e),r=`${Yr}${t}`;this.storage.removeItem(r),await this.removeFromIndex(e)}catch(t){throw new R("Failed to delete credential",t)}}async clearAll(){try{let e=await this.getIndex();(await Promise.all(e.map(async r=>await ft(r)))).forEach(r=>{let s=`${Yr}${r}`;this.storage.removeItem(s)}),this.storage.removeItem(jr)}catch(e){throw new R("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 r=(await this.getIndex()).filter(s=>s!==e);this.storage.setItem(jr,JSON.stringify(r))}}});var Cs={};B(Cs,{createWalletFromMnemonic:()=>Es,deriveWalletFromMnemonic:()=>tr,generateBIP39Wallet:()=>er});function er(){try{let n=Zt.ethers.Wallet.createRandom().mnemonic;if(!n)throw new Error("Failed to generate mnemonic");let e=n.phrase;return{address:Zt.ethers.HDNodeWallet.fromPhrase(e,void 0,"m/44'/60'/0'/0/0").address,mnemonic:e}}catch(n){throw new S("Wallet generation failed",n)}}function Es(n){try{if(!n||n.trim().split(/\s+/).length<12)throw new Error("Invalid mnemonic: must be at least 12 words");return Zt.ethers.HDNodeWallet.fromPhrase(n.trim(),void 0,"m/44'/60'/0'/0/0")}catch(e){throw new S(`Wallet creation failed: ${e instanceof Error?e.message:"Invalid mnemonic"}`,e)}}function tr(n,e=0){try{if(!n||n.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}`,r=Zt.ethers.HDNodeWallet.fromPhrase(n.trim(),void 0,t);return{address:r.address,privateKey:r.privateKey}}catch(t){throw new S(`HD wallet derivation failed: ${t instanceof Error?t.message:"Unknown error"}`,t)}}var Zt,pt=w(()=>{"use strict";Zt=require("ethers");Y()});var en={};B(en,{DEFAULT_MODE:()=>fe,DEFAULT_TAG:()=>pe,deriveAddressFromP256PublicKey:()=>Ps,deriveIndexFromOriginModeAndTag:()=>Zr,getCurrentOrigin:()=>Me,getOriginSpecificAddress:()=>Fe,normalizeOrigin:()=>rr});function rr(n){try{let e=new URL(n),t=`${e.protocol}//${e.hostname.toLowerCase()}`,r=e.port;return r&&!(e.protocol==="https:"&&r==="443"||e.protocol==="http:"&&r==="80")&&(t+=`:${r}`),t}catch(e){throw new S(`Invalid origin URL: ${n}`,e)}}async function Zr(n,e=fe,t=pe){try{let s=`${rr(n)}:${e}:${t.toUpperCase()}`,o=new TextEncoder().encode(s),c=await crypto.subtle.digest("SHA-256",o);return new DataView(c).getUint32(0,!1)%Od}catch(r){throw new S(`Failed to derive index from origin "${n}", mode "${e}", and tag "${t}"`,r)}}async function Fe(n,e,t,r){try{let s=t||fe,i=(r||pe).toUpperCase(),o=rr(e),c=await Zr(o,s,i),{address:a,privateKey:u}=tr(n,c),l={address:a,index:c,origin:o,mode:s,tag:i};return s==="YOLO"&&(l.privateKey=u),l}catch(s){throw new S(`Failed to derive origin-specific address for "${e}" with mode "${t||fe}" and tag "${r||pe}"`,s)}}function Me(){if(typeof window>"u"||!window.location)throw new S("getCurrentOrigin() only works in browser environments");return window.location.origin}async function Ps(n){try{let e=L(n),t=await crypto.subtle.importKey("spki",e,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),r=await crypto.subtle.exportKey("jwk",t);if(!r.x||!r.y)throw new Error("Invalid P-256 public key: missing x or y coordinates");let s=L(r.x),i=L(r.y),o=new Uint8Array(64);return o.set(new Uint8Array(s),0),o.set(new Uint8Array(i),32),"0x"+(0,Wo.keccak256)(o).slice(-40)}catch(e){throw new S("Failed to derive address from P-256 public key",e)}}var Wo,fe,pe,Od,gt=w(()=>{"use strict";pt();Y();Wo=require("ethers");xe();fe="STANDARD",pe="MAIN",Od=2147483647});var Rs={};B(Rs,{encodeEIP7702AuthorizationMessage:()=>or,hashEIP7702AuthorizationMessage:()=>ar,verifyEIP7702Authorization:()=>an});function or(n,e,t){let r=[n===0n?"0x":(0,Z.toBeHex)(n),e.toLowerCase(),t===0n?"0x":(0,Z.toBeHex)(t)],s=(0,Z.encodeRlp)(r);return(0,Z.concat)(["0x05",s])}function ar(n,e,t){let r=or(n,e,t);return(0,Z.keccak256)(r)}function an(n,e,t,r,s){try{let i=ar(n,e,t),o;return typeof r=="string"?o=Z.Signature.from(r):o=r,(0,Z.recoverAddress)(i,o).toLowerCase()===s.toLowerCase()}catch{return!1}}var Z,cn=w(()=>{"use strict";Z=require("ethers")});var ea={};B(ea,{detectWalletProvider:()=>dn,getDefaultProvider:()=>un,requestExternalWalletAuthorization:()=>ln,supportsEIP7702Authorization:()=>hn});async function ln(n,e){if(!n)throw new Error("No external wallet provider found. Please install MetaMask or similar wallet.");let t=BigInt(e.chainId||1),r=e.nonce||0n,s=e.accountIndex||0,i=await n.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:c,verifyEIP7702Authorization:a}=await Promise.resolve().then(()=>(cn(),Rs)),{Signature:u}=await import("ethers"),l=c(t,e.delegateToAddress,r),h;try{h=await n.request({method:"eth_sign",params:[o,l]})}catch(y){try{h=await n.request({method:"personal_sign",params:[l,o]})}catch(k){throw new Error(`Failed to request signature from wallet. eth_sign error: ${y.message}, personal_sign error: ${k.message}`)}}let g=u.from(h),d={chainId:t,address:e.delegateToAddress.toLowerCase(),nonce:r,yParity:g.yParity,r:g.r,s:g.s};if(!a(t,e.delegateToAddress,r,d,o))throw new Error(`Signature verification failed. Expected signer: ${o}, but signature does not match. This may indicate a wallet implementation issue.`);return d}function un(){if(typeof window>"u")return null;let n=window;return n.ethereum?n.ethereum:n.web3?.currentProvider?n.web3.currentProvider:null}function dn(n){let e=n;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 hn(n){try{let e=await n.request({method:"eth_accounts"});return Array.isArray(e)}catch{return!1}}var Ts=w(()=>{"use strict"});var ra={};B(ra,{extractRS:()=>Fs});function Fs(n){let e=0;if(n[e++]!==48)throw new Error("Invalid DER signature: missing sequence tag");if(e++,n[e++]!==2)throw new Error("Invalid DER signature: missing r integer tag");let t=n[e++];t>32&&(e++,t--);let r=n.slice(e,e+t);if(e+=t,n[e++]!==2)throw new Error("Invalid DER signature: missing s integer tag");let s=n[e++];s>32&&(e++,s--);let i=n.slice(e,e+s),o=new Uint8Array(32),c=new Uint8Array(32);o.set(r,32-r.length),c.set(i,32-i.length);let a=BigInt("0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"),u=BigInt("0x"+Buffer.from(c).toString("hex"));u>a/2n&&(u=a-u);let l="0x"+Buffer.from(o).toString("hex"),h="0x"+u.toString(16).padStart(64,"0");return{r:l,s:h}}var Ms=w(()=>{"use strict"});var na={};B(na,{BackupStorage:()=>Ge});var Ge,fn=w(()=>{"use strict";Ge=class{constructor(){this.dbName="Web3PasskeyBackup";this.version=1;this.db=null}async init(){return typeof indexedDB>"u"?Promise.resolve():new Promise((e,t)=>{let r=indexedDB.open(this.dbName,this.version);r.onerror=()=>t(r.error),r.onsuccess=()=>{this.db=r.result,e()},r.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,r)=>{let o=this.db.transaction(["backups"],"readwrite").objectStore("backups").put(e);o.onsuccess=()=>t(),o.onerror=()=>r(o.error)}):Promise.resolve()}async getBackupsByAddress(e){return this.db||await this.init(),this.db?new Promise((t,r)=>{let c=this.db.transaction(["backups"],"readonly").objectStore("backups").index("ethereumAddress").getAll(e);c.onsuccess=()=>t(c.result),c.onerror=()=>r(c.error)}):Promise.resolve([])}async getBackupById(e){return this.db||await this.init(),this.db?new Promise((t,r)=>{let o=this.db.transaction(["backups"],"readonly").objectStore("backups").get(e);o.onsuccess=()=>t(o.result||null),o.onerror=()=>r(o.error)}):Promise.resolve(null)}async deleteBackup(e){return this.db||await this.init(),this.db?new Promise((t,r)=>{let o=this.db.transaction(["backups"],"readwrite").objectStore("backups").delete(e);o.onsuccess=()=>t(),o.onerror=()=>r(o.error)}):Promise.resolve()}async getBackupCountByMethod(e){return this.db||await this.init(),this.db?new Promise((t,r)=>{let c=this.db.transaction(["backups"],"readonly").objectStore("backups").index("method").count(e);c.onsuccess=()=>t(c.result),c.onerror=()=>r(c.error)}):Promise.resolve(0)}}});var ia={};B(ia,{decryptWithPassword:()=>lr,deriveAddressChecksum:()=>ee,deriveKeyFromPassword:()=>pn,encryptWithPassword:()=>Ye,getDeviceFingerprint:()=>Ae,validatePasswordStrength:()=>sa});async function pn(n,e,t=31e4){let s=new TextEncoder().encode(n),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 Ye(n,e,t){let s=await pn(e,t,31e4),o=new TextEncoder().encode(n),c=crypto.getRandomValues(new Uint8Array(12)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:c},s,o);return{encrypted:cr(a),iv:cr(c),salt:cr(t),iterations:31e4}}async function lr(n,e,t,r,s=31e4){let i=Ns(t),o=await pn(e,i,s),c=Ns(r),a=Ns(n),u=await crypto.subtle.decrypt({name:"AES-GCM",iv:c},o,a);return new TextDecoder().decode(u)}async function Ae(){let e=[navigator.userAgent,navigator.language,new Date().getTimezoneOffset().toString(),screen.width+"x"+screen.height,screen.colorDepth.toString()].join("|"),r=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-256",r);return cr(s)}async function ee(n){let t=new TextEncoder().encode(n.toLowerCase()),r=await crypto.subtle.digest("SHA-256",t);return cr(r).substring(0,16)}function sa(n){let e=[],t=0;return n.length<12?e.push("Password must be at least 12 characters"):t+=25,/[A-Z]/.test(n)?t+=15:e.push("Add at least one uppercase letter"),/[a-z]/.test(n)?t+=15:e.push("Add at least one lowercase letter"),/[0-9]/.test(n)?t+=15:e.push("Add at least one number"),/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(n)?t+=15:e.push("Add at least one special character"),n.length>=16&&(t+=10),n.length>=20&&(t+=5),["password","12345678","qwerty","abc123","password123","admin","letmein"].some(s=>n.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 cr(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r=0;r<e.byteLength;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Ns(n){let e=Ve(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}var je=w(()=>{"use strict";xe()});var aa=D((km,oa)=>{"use strict";oa.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var Ne=D(Je=>{"use strict";var Us,Yd=[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];Je.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};Je.getSymbolTotalCodewords=function(e){return Yd[e]};Je.getBCHDigit=function(n){let e=0;for(;n!==0;)e++,n>>>=1;return e};Je.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');Us=e};Je.isKanjiModeEnabled=function(){return typeof Us<"u"};Je.toSJIS=function(e){return Us(e)}});var gn=D(ce=>{"use strict";ce.L={bit:1};ce.M={bit:0};ce.Q={bit:3};ce.H={bit:2};function jd(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return ce.L;case"m":case"medium":return ce.M;case"q":case"quartile":return ce.Q;case"h":case"high":return ce.H;default:throw new Error("Unknown EC Level: "+n)}}ce.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};ce.from=function(e,t){if(ce.isValid(e))return e;try{return jd(e)}catch{return t}}});var ua=D((Pm,la)=>{"use strict";function ca(){this.buffer=[],this.length=0}ca.prototype={get:function(n){let e=Math.floor(n/8);return(this.buffer[e]>>>7-n%8&1)===1},put:function(n,e){for(let t=0;t<e;t++)this.putBit((n>>>e-t-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(n){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),n&&(this.buffer[e]|=128>>>this.length%8),this.length++}};la.exports=ca});var ha=D((Im,da)=>{"use strict";function ur(n){if(!n||n<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=n,this.data=new Uint8Array(n*n),this.reservedBit=new Uint8Array(n*n)}ur.prototype.set=function(n,e,t,r){let s=n*this.size+e;this.data[s]=t,r&&(this.reservedBit[s]=!0)};ur.prototype.get=function(n,e){return this.data[n*this.size+e]};ur.prototype.xor=function(n,e,t){this.data[n*this.size+e]^=t};ur.prototype.isReserved=function(n,e){return this.reservedBit[n*this.size+e]};da.exports=ur});var fa=D(mn=>{"use strict";var Jd=Ne().getSymbolSize;mn.getRowColCoords=function(e){if(e===1)return[];let t=Math.floor(e/7)+2,r=Jd(e),s=r===145?26:Math.ceil((r-13)/(2*t-2))*2,i=[r-7];for(let o=1;o<t-1;o++)i[o]=i[o-1]-s;return i.push(6),i.reverse()};mn.getPositions=function(e){let t=[],r=mn.getRowColCoords(e),s=r.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([r[i],r[o]]);return t}});var ma=D(ga=>{"use strict";var Qd=Ne().getSymbolSize,pa=7;ga.getPositions=function(e){let t=Qd(e);return[[0,0],[t-pa,0],[0,t-pa]]}});var ya=D(M=>{"use strict";M.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var Qe={N1:3,N2:3,N3:40,N4:10};M.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};M.from=function(e){return M.isValid(e)?parseInt(e,10):void 0};M.getPenaltyN1=function(e){let t=e.size,r=0,s=0,i=0,o=null,c=null;for(let a=0;a<t;a++){s=i=0,o=c=null;for(let u=0;u<t;u++){let l=e.get(a,u);l===o?s++:(s>=5&&(r+=Qe.N1+(s-5)),o=l,s=1),l=e.get(u,a),l===c?i++:(i>=5&&(r+=Qe.N1+(i-5)),c=l,i=1)}s>=5&&(r+=Qe.N1+(s-5)),i>=5&&(r+=Qe.N1+(i-5))}return r};M.getPenaltyN2=function(e){let t=e.size,r=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)&&r++}return r*Qe.N2};M.getPenaltyN3=function(e){let t=e.size,r=0,s=0,i=0;for(let o=0;o<t;o++){s=i=0;for(let c=0;c<t;c++)s=s<<1&2047|e.get(o,c),c>=10&&(s===1488||s===93)&&r++,i=i<<1&2047|e.get(c,o),c>=10&&(i===1488||i===93)&&r++}return r*Qe.N3};M.getPenaltyN4=function(e){let t=0,r=e.data.length;for(let i=0;i<r;i++)t+=e.data[i];return Math.abs(Math.ceil(t*100/r/5)-10)*Qe.N4};function Xd(n,e,t){switch(n){case M.Patterns.PATTERN000:return(e+t)%2===0;case M.Patterns.PATTERN001:return e%2===0;case M.Patterns.PATTERN010:return t%3===0;case M.Patterns.PATTERN011:return(e+t)%3===0;case M.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(t/3))%2===0;case M.Patterns.PATTERN101:return e*t%2+e*t%3===0;case M.Patterns.PATTERN110:return(e*t%2+e*t%3)%2===0;case M.Patterns.PATTERN111:return(e*t%3+(e+t)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}M.applyMask=function(e,t){let r=t.size;for(let s=0;s<r;s++)for(let i=0;i<r;i++)t.isReserved(i,s)||t.xor(i,s,Xd(e,i,s))};M.getBestMask=function(e,t){let r=Object.keys(M.Patterns).length,s=0,i=1/0;for(let o=0;o<r;o++){t(o),M.applyMask(o,e);let c=M.getPenaltyN1(e)+M.getPenaltyN2(e)+M.getPenaltyN3(e)+M.getPenaltyN4(e);M.applyMask(o,e),c<i&&(i=c,s=o)}return s}});var _s=D(Ls=>{"use strict";var Ue=gn(),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];Ls.getBlocksCount=function(e,t){switch(t){case Ue.L:return yn[(e-1)*4+0];case Ue.M:return yn[(e-1)*4+1];case Ue.Q:return yn[(e-1)*4+2];case Ue.H:return yn[(e-1)*4+3];default:return}};Ls.getTotalCodewordsCount=function(e,t){switch(t){case Ue.L:return wn[(e-1)*4+0];case Ue.M:return wn[(e-1)*4+1];case Ue.Q:return wn[(e-1)*4+2];case Ue.H:return wn[(e-1)*4+3];default:return}}});var wa=D(Sn=>{"use strict";var dr=new Uint8Array(512),bn=new Uint8Array(256);(function(){let e=1;for(let t=0;t<255;t++)dr[t]=e,bn[e]=t,e<<=1,e&256&&(e^=285);for(let t=255;t<512;t++)dr[t]=dr[t-255]})();Sn.log=function(e){if(e<1)throw new Error("log("+e+")");return bn[e]};Sn.exp=function(e){return dr[e]};Sn.mul=function(e,t){return e===0||t===0?0:dr[bn[e]+bn[t]]}});var ba=D(hr=>{"use strict";var Os=wa();hr.mul=function(e,t){let r=new Uint8Array(e.length+t.length-1);for(let s=0;s<e.length;s++)for(let i=0;i<t.length;i++)r[s+i]^=Os.mul(e[s],t[i]);return r};hr.mod=function(e,t){let r=new Uint8Array(e);for(;r.length-t.length>=0;){let s=r[0];for(let o=0;o<t.length;o++)r[o]^=Os.mul(t[o],s);let i=0;for(;i<r.length&&r[i]===0;)i++;r=r.slice(i)}return r};hr.generateECPolynomial=function(e){let t=new Uint8Array([1]);for(let r=0;r<e;r++)t=hr.mul(t,new Uint8Array([1,Os.exp(r)]));return t}});var va=D((Nm,xa)=>{"use strict";var Sa=ba();function Ks(n){this.genPoly=void 0,this.degree=n,this.degree&&this.initialize(this.degree)}Ks.prototype.initialize=function(e){this.degree=e,this.genPoly=Sa.generateECPolynomial(this.degree)};Ks.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 r=Sa.mod(t,this.genPoly),s=this.degree-r.length;if(s>0){let i=new Uint8Array(this.degree);return i.set(r,s),i}return r};xa.exports=Ks});var zs=D(Aa=>{"use strict";Aa.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var Ws=D(Ce=>{"use strict";var ka="[0-9]+",Zd="[A-Z $%*+\\-./:]+",fr="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";fr=fr.replace(/u/g,"\\u");var eh="(?:(?![A-Z0-9 $%*+\\-./:]|"+fr+`)(?:.|[\r
2
- ]))+`;Ce.KANJI=new RegExp(fr,"g");Ce.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");Ce.BYTE=new RegExp(eh,"g");Ce.NUMERIC=new RegExp(ka,"g");Ce.ALPHANUMERIC=new RegExp(Zd,"g");var th=new RegExp("^"+fr+"$"),rh=new RegExp("^"+ka+"$"),nh=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");Ce.testKanji=function(e){return th.test(e)};Ce.testNumeric=function(e){return rh.test(e)};Ce.testAlphanumeric=function(e){return nh.test(e)}});var Le=D(_=>{"use strict";var sh=zs(),$s=Ws();_.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(!sh.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 $s.testNumeric(e)?_.NUMERIC:$s.testAlphanumeric(e)?_.ALPHANUMERIC:$s.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 ih(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"numeric":return _.NUMERIC;case"alphanumeric":return _.ALPHANUMERIC;case"kanji":return _.KANJI;case"byte":return _.BYTE;default:throw new Error("Unknown mode: "+n)}}_.from=function(e,t){if(_.isValid(e))return e;try{return ih(e)}catch{return t}}});var Ba=D(Xe=>{"use strict";var xn=Ne(),oh=_s(),Ea=gn(),_e=Le(),qs=zs(),Pa=7973,Ca=xn.getBCHDigit(Pa);function ah(n,e,t){for(let r=1;r<=40;r++)if(e<=Xe.getCapacity(r,t,n))return r}function Ia(n,e){return _e.getCharCountIndicator(n,e)+4}function ch(n,e){let t=0;return n.forEach(function(r){let s=Ia(r.mode,e);t+=s+r.getBitsLength()}),t}function lh(n,e){for(let t=1;t<=40;t++)if(ch(n,t)<=Xe.getCapacity(t,e,_e.MIXED))return t}Xe.from=function(e,t){return qs.isValid(e)?parseInt(e,10):t};Xe.getCapacity=function(e,t,r){if(!qs.isValid(e))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=_e.BYTE);let s=xn.getSymbolTotalCodewords(e),i=oh.getTotalCodewordsCount(e,t),o=(s-i)*8;if(r===_e.MIXED)return o;let c=o-Ia(r,e);switch(r){case _e.NUMERIC:return Math.floor(c/10*3);case _e.ALPHANUMERIC:return Math.floor(c/11*2);case _e.KANJI:return Math.floor(c/13);case _e.BYTE:default:return Math.floor(c/8)}};Xe.getBestVersionForData=function(e,t){let r,s=Ea.from(t,Ea.M);if(Array.isArray(e)){if(e.length>1)return lh(e,s);if(e.length===0)return 1;r=e[0]}else r=e;return ah(r.mode,r.getLength(),s)};Xe.getEncodedBits=function(e){if(!qs.isValid(e)||e<7)throw new Error("Invalid QR Code version");let t=e<<12;for(;xn.getBCHDigit(t)-Ca>=0;)t^=Pa<<xn.getBCHDigit(t)-Ca;return e<<12|t}});var Fa=D(Ta=>{"use strict";var Hs=Ne(),Ra=1335,uh=21522,Da=Hs.getBCHDigit(Ra);Ta.getEncodedBits=function(e,t){let r=e.bit<<3|t,s=r<<10;for(;Hs.getBCHDigit(s)-Da>=0;)s^=Ra<<Hs.getBCHDigit(s)-Da;return(r<<10|s)^uh}});var Na=D((zm,Ma)=>{"use strict";var dh=Le();function wt(n){this.mode=dh.NUMERIC,this.data=n.toString()}wt.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};wt.prototype.getLength=function(){return this.data.length};wt.prototype.getBitsLength=function(){return wt.getBitsLength(this.data.length)};wt.prototype.write=function(e){let t,r,s;for(t=0;t+3<=this.data.length;t+=3)r=this.data.substr(t,3),s=parseInt(r,10),e.put(s,10);let i=this.data.length-t;i>0&&(r=this.data.substr(t),s=parseInt(r,10),e.put(s,i*3+1))};Ma.exports=wt});var La=D((Wm,Ua)=>{"use strict";var hh=Le(),Vs=["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 bt(n){this.mode=hh.ALPHANUMERIC,this.data=n}bt.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};bt.prototype.getLength=function(){return this.data.length};bt.prototype.getBitsLength=function(){return bt.getBitsLength(this.data.length)};bt.prototype.write=function(e){let t;for(t=0;t+2<=this.data.length;t+=2){let r=Vs.indexOf(this.data[t])*45;r+=Vs.indexOf(this.data[t+1]),e.put(r,11)}this.data.length%2&&e.put(Vs.indexOf(this.data[t]),6)};Ua.exports=bt});var Oa=D(($m,_a)=>{"use strict";var fh=Le();function St(n){this.mode=fh.BYTE,typeof n=="string"?this.data=new TextEncoder().encode(n):this.data=new Uint8Array(n)}St.getBitsLength=function(e){return e*8};St.prototype.getLength=function(){return this.data.length};St.prototype.getBitsLength=function(){return St.getBitsLength(this.data.length)};St.prototype.write=function(n){for(let e=0,t=this.data.length;e<t;e++)n.put(this.data[e],8)};_a.exports=St});var za=D((qm,Ka)=>{"use strict";var ph=Le(),gh=Ne();function xt(n){this.mode=ph.KANJI,this.data=n}xt.getBitsLength=function(e){return e*13};xt.prototype.getLength=function(){return this.data.length};xt.prototype.getBitsLength=function(){return xt.getBitsLength(this.data.length)};xt.prototype.write=function(n){let e;for(e=0;e<this.data.length;e++){let t=gh.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),n.put(t,13)}};Ka.exports=xt});var Wa=D((Hm,Gs)=>{"use strict";var pr={single_source_shortest_paths:function(n,e,t){var r={},s={};s[e]=0;var i=pr.PriorityQueue.make();i.push(e,0);for(var o,c,a,u,l,h,g,d,f;!i.empty();){o=i.pop(),c=o.value,u=o.cost,l=n[c]||{};for(a in l)l.hasOwnProperty(a)&&(h=l[a],g=u+h,d=s[a],f=typeof s[a]>"u",(f||d>g)&&(s[a]=g,i.push(a,g),r[a]=c))}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 r},extract_shortest_path_from_predecessor_list:function(n,e){for(var t=[],r=e,s;r;)t.push(r),s=n[r],r=n[r];return t.reverse(),t},find_path:function(n,e,t){var r=pr.single_source_shortest_paths(n,e,t);return pr.extract_shortest_path_from_predecessor_list(r,t)},PriorityQueue:{make:function(n){var e=pr.PriorityQueue,t={},r;n=n||{};for(r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);return t.queue=[],t.sorter=n.sorter||e.default_sorter,t},default_sorter:function(n,e){return n.cost-e.cost},push:function(n,e){var t={value:n,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 Gs<"u"&&(Gs.exports=pr)});var Ja=D(vt=>{"use strict";var T=Le(),Ha=Na(),Va=La(),Ga=Oa(),Ya=za(),gr=Ws(),vn=Ne(),mh=Wa();function $a(n){return unescape(encodeURIComponent(n)).length}function mr(n,e,t){let r=[],s;for(;(s=n.exec(t))!==null;)r.push({data:s[0],index:s.index,mode:e,length:s[0].length});return r}function ja(n){let e=mr(gr.NUMERIC,T.NUMERIC,n),t=mr(gr.ALPHANUMERIC,T.ALPHANUMERIC,n),r,s;return vn.isKanjiModeEnabled()?(r=mr(gr.BYTE,T.BYTE,n),s=mr(gr.KANJI,T.KANJI,n)):(r=mr(gr.BYTE_KANJI,T.BYTE,n),s=[]),e.concat(t,r,s).sort(function(o,c){return o.index-c.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function Ys(n,e){switch(e){case T.NUMERIC:return Ha.getBitsLength(n);case T.ALPHANUMERIC:return Va.getBitsLength(n);case T.KANJI:return Ya.getBitsLength(n);case T.BYTE:return Ga.getBitsLength(n)}}function yh(n){return n.reduce(function(e,t){let r=e.length-1>=0?e[e.length-1]:null;return r&&r.mode===t.mode?(e[e.length-1].data+=t.data,e):(e.push(t),e)},[])}function wh(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t];switch(r.mode){case T.NUMERIC:e.push([r,{data:r.data,mode:T.ALPHANUMERIC,length:r.length},{data:r.data,mode:T.BYTE,length:r.length}]);break;case T.ALPHANUMERIC:e.push([r,{data:r.data,mode:T.BYTE,length:r.length}]);break;case T.KANJI:e.push([r,{data:r.data,mode:T.BYTE,length:$a(r.data)}]);break;case T.BYTE:e.push([{data:r.data,mode:T.BYTE,length:$a(r.data)}])}}return e}function bh(n,e){let t={},r={start:{}},s=["start"];for(let i=0;i<n.length;i++){let o=n[i],c=[];for(let a=0;a<o.length;a++){let u=o[a],l=""+i+a;c.push(l),t[l]={node:u,lastCount:0},r[l]={};for(let h=0;h<s.length;h++){let g=s[h];t[g]&&t[g].node.mode===u.mode?(r[g][l]=Ys(t[g].lastCount+u.length,u.mode)-Ys(t[g].lastCount,u.mode),t[g].lastCount+=u.length):(t[g]&&(t[g].lastCount=u.length),r[g][l]=Ys(u.length,u.mode)+4+T.getCharCountIndicator(u.mode,e))}}s=c}for(let i=0;i<s.length;i++)r[s[i]].end=0;return{map:r,table:t}}function qa(n,e){let t,r=T.getBestModeForData(n);if(t=T.from(e,r),t!==T.BYTE&&t.bit<r.bit)throw new Error('"'+n+'" cannot be encoded with mode '+T.toString(t)+`.
4
- Suggested mode is: `+T.toString(r));switch(t===T.KANJI&&!vn.isKanjiModeEnabled()&&(t=T.BYTE),t){case T.NUMERIC:return new Ha(n);case T.ALPHANUMERIC:return new Va(n);case T.KANJI:return new Ya(n);case T.BYTE:return new Ga(n)}}vt.fromArray=function(e){return e.reduce(function(t,r){return typeof r=="string"?t.push(qa(r,null)):r.data&&t.push(qa(r.data,r.mode)),t},[])};vt.fromString=function(e,t){let r=ja(e,vn.isKanjiModeEnabled()),s=wh(r),i=bh(s,t),o=mh.find_path(i.map,"start","end"),c=[];for(let a=1;a<o.length-1;a++)c.push(i.table[o[a]].node);return vt.fromArray(yh(c))};vt.rawSplit=function(e){return vt.fromArray(ja(e,vn.isKanjiModeEnabled()))}});var Xa=D(Qa=>{"use strict";var kn=Ne(),js=gn(),Sh=ua(),xh=ha(),vh=fa(),Ah=ma(),Xs=ya(),Zs=_s(),kh=va(),An=Ba(),Eh=Fa(),Ch=Le(),Js=Ja();function Ph(n,e){let t=n.size,r=Ah.getPositions(e);for(let s=0;s<r.length;s++){let i=r[s][0],o=r[s][1];for(let c=-1;c<=7;c++)if(!(i+c<=-1||t<=i+c))for(let a=-1;a<=7;a++)o+a<=-1||t<=o+a||(c>=0&&c<=6&&(a===0||a===6)||a>=0&&a<=6&&(c===0||c===6)||c>=2&&c<=4&&a>=2&&a<=4?n.set(i+c,o+a,!0,!0):n.set(i+c,o+a,!1,!0))}}function Ih(n){let e=n.size;for(let t=8;t<e-8;t++){let r=t%2===0;n.set(t,6,r,!0),n.set(6,t,r,!0)}}function Bh(n,e){let t=vh.getPositions(e);for(let r=0;r<t.length;r++){let s=t[r][0],i=t[r][1];for(let o=-2;o<=2;o++)for(let c=-2;c<=2;c++)o===-2||o===2||c===-2||c===2||o===0&&c===0?n.set(s+o,i+c,!0,!0):n.set(s+o,i+c,!1,!0)}}function Dh(n,e){let t=n.size,r=An.getEncodedBits(e),s,i,o;for(let c=0;c<18;c++)s=Math.floor(c/3),i=c%3+t-8-3,o=(r>>c&1)===1,n.set(s,i,o,!0),n.set(i,s,o,!0)}function Qs(n,e,t){let r=n.size,s=Eh.getEncodedBits(e,t),i,o;for(i=0;i<15;i++)o=(s>>i&1)===1,i<6?n.set(i,8,o,!0):i<8?n.set(i+1,8,o,!0):n.set(r-15+i,8,o,!0),i<8?n.set(8,r-i-1,o,!0):i<9?n.set(8,15-i-1+1,o,!0):n.set(8,15-i-1,o,!0);n.set(r-8,8,1,!0)}function Rh(n,e){let t=n.size,r=-1,s=t-1,i=7,o=0;for(let c=t-1;c>0;c-=2)for(c===6&&c--;;){for(let a=0;a<2;a++)if(!n.isReserved(s,c-a)){let u=!1;o<e.length&&(u=(e[o]>>>i&1)===1),n.set(s,c-a,u),i--,i===-1&&(o++,i=7)}if(s+=r,s<0||t<=s){s-=r,r=-r;break}}}function Th(n,e,t){let r=new Sh;t.forEach(function(a){r.put(a.mode.bit,4),r.put(a.getLength(),Ch.getCharCountIndicator(a.mode,n)),a.write(r)});let s=kn.getSymbolTotalCodewords(n),i=Zs.getTotalCodewordsCount(n,e),o=(s-i)*8;for(r.getLengthInBits()+4<=o&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);let c=(o-r.getLengthInBits())/8;for(let a=0;a<c;a++)r.put(a%2?17:236,8);return Fh(r,n,e)}function Fh(n,e,t){let r=kn.getSymbolTotalCodewords(e),s=Zs.getTotalCodewordsCount(e,t),i=r-s,o=Zs.getBlocksCount(e,t),c=r%o,a=o-c,u=Math.floor(r/o),l=Math.floor(i/o),h=l+1,g=u-l,d=new kh(g),f=0,y=new Array(o),k=new Array(o),m=0,b=new Uint8Array(n.buffer);for(let x=0;x<o;x++){let P=x<a?l:h;y[x]=b.slice(f,f+P),k[x]=d.encode(y[x]),f+=P,m=Math.max(m,P)}let v=new Uint8Array(r),A=0,E,C;for(E=0;E<m;E++)for(C=0;C<o;C++)E<y[C].length&&(v[A++]=y[C][E]);for(E=0;E<g;E++)for(C=0;C<o;C++)v[A++]=k[C][E];return v}function Mh(n,e,t,r){let s;if(Array.isArray(n))s=Js.fromArray(n);else if(typeof n=="string"){let u=e;if(!u){let l=Js.rawSplit(n);u=An.getBestVersionForData(l,t)}s=Js.fromString(n,u||40)}else throw new Error("Invalid data");let i=An.getBestVersionForData(s,t);if(!i)throw new Error("The amount of data is too big to be stored in a QR Code");if(!e)e=i;else if(e<i)throw new Error(`
1
+ "use strict";var Ad=Object.create;var Zt=Object.defineProperty;var kd=Object.getOwnPropertyDescriptor;var Ed=Object.getOwnPropertyNames;var Cd=Object.getPrototypeOf,Pd=Object.prototype.hasOwnProperty;var Id=(n,e,t)=>e in n?Zt(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var w=(n,e)=>()=>(n&&(e=n(n=0)),e);var D=(n,e)=>()=>(e||n((e={exports:{}}).exports,e),e.exports),B=(n,e)=>{for(var t in e)Zt(n,t,{get:e[t],enumerable:!0})},Lo=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ed(e))!Pd.call(n,s)&&s!==t&&Zt(n,s,{get:()=>e[s],enumerable:!(r=kd(e,s))||r.enumerable});return n};var z=(n,e,t)=>(t=n!=null?Ad(Cd(n)):{},Lo(e||!n||!n.__esModule?Zt(t,"default",{value:n,enumerable:!0}):t,n)),Bd=n=>Lo(Zt({},"__esModule",{value:!0}),n);var p=(n,e,t)=>Id(n,typeof e!="symbol"?e+"":e,t);var $,O,ft,S,N,R,Vr,Y=w(()=>{"use strict";$=class extends Error{constructor(t,r,s){super(t);this.code=r;this.originalError=s;this.name="Web3PasskeyError"}},O=class extends ${constructor(e,t){super(e,"AUTHENTICATION_ERROR",t),this.name="AuthenticationError"}},ft=class extends ${constructor(e,t){super(e,"REGISTRATION_ERROR",t),this.name="RegistrationError"}},S=class extends ${constructor(e,t){super(e,"WALLET_ERROR",t),this.name="WalletError"}},N=class extends ${constructor(e,t){super(e,"CRYPTO_ERROR",t),this.name="CryptoError"}},R=class extends ${constructor(e,t){super(e,"STORAGE_ERROR",t),this.name="StorageError"}},Vr=class extends ${constructor(t,r,s){super(t,"API_ERROR",s);this.statusCode=r;this.name="ApiError"}}});var ks={};B(ks,{arrayBufferToBase64Url:()=>Se,base64ToArrayBuffer:()=>xs,base64UrlDecode:()=>As,base64UrlToArrayBuffer:()=>L,safeAtob:()=>Ve,safeBtoa:()=>vs});function L(n){try{let e=n.replace(/-/g,"+").replace(/_/g,"/"),t=(4-e.length%4)%4;e+="=".repeat(t);let r=atob(e),s=new Uint8Array(r.length);for(let i=0;i<r.length;i++)s[i]=r.charCodeAt(i);return s.buffer}catch(e){throw new Error(`Failed to decode base64url string: ${e instanceof Error?e.message:"Invalid format"}`)}}function Se(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function xs(n){try{let e=atob(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t.buffer}catch(e){throw new Error(`Failed to decode base64 string: ${e instanceof Error?e.message:"Invalid format"}`)}}function Ve(n){try{let e=n.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 vs(n){try{let e=new TextEncoder().encode(n),t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}catch(e){throw new Error(`Failed to encode string: ${e instanceof Error?e.message:"Invalid input"}`)}}function As(n){return L(n)}var xe=w(()=>{"use strict"});var Re={};B(Re,{decryptData:()=>oe,deriveEncryptionKey:()=>Dd,deriveEncryptionKeyFromWebAuthn:()=>j,encryptData:()=>ie,generateChallenge:()=>De,hashCredentialId:()=>pt,hashPublicKey:()=>Es});async function j(n,e){try{let t=e?`w3pk-v4:${n}:${e}`:`w3pk-v4:${n}`,r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)),s=await crypto.subtle.importKey("raw",r,{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 N("Failed to derive encryption key from WebAuthn",t)}}async function Dd(n,e){try{let t=e?`w3pk-v2:${n}:${e}`:`w3pk-v2:${n}`,r=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t)),s=await crypto.subtle.importKey("raw",r,{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 N("Failed to derive encryption key",t)}}function De(){let n=new Uint8Array(32);return crypto.getRandomValues(n),Se(n)}async function ie(n,e){try{let t=crypto.getRandomValues(new Uint8Array(12)),r=new TextEncoder().encode(n),s=await crypto.subtle.encrypt({name:"AES-GCM",iv:t},e,r),i=new Uint8Array(t.length+s.byteLength);i.set(t),i.set(new Uint8Array(s),t.length);let o="";for(let c=0;c<i.length;c++)o+=String.fromCharCode(i[c]);return btoa(o)}catch(t){throw new N("Failed to encrypt data",t)}}async function oe(n,e){try{if(!n||n.length<16)throw new Error("Invalid encrypted data: too small");let t=Ve(n),r=new Uint8Array(t.length);for(let c=0;c<t.length;c++)r[c]=t.charCodeAt(c);if(r.length<12)throw new Error("Invalid encrypted data: missing IV");let s=r.slice(0,12),i=r.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 N(`Data decryption failed: ${t instanceof Error?t.message:"Unknown error"}`,t)}}async function pt(n){try{let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(`w3pk-cred-id:${n}`));return Se(e)}catch(e){throw new N("Failed to hash credential ID",e)}}async function Es(n){try{let e=await crypto.subtle.digest("SHA-256",new TextEncoder().encode(n));return Se(e)}catch(e){throw new N("Failed to hash public key",e)}}var q=w(()=>{"use strict";Y();xe()});var Qr={};B(Qr,{CredentialStorage:()=>F});async function Ko(n){let e=new TextEncoder().encode(`w3pk-metadata-v1:${n}`),t=await crypto.subtle.digest("SHA-256",e),r=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"},r,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}var jr,Jr,F,Te=w(()=>{"use strict";Y();q();jr="w3pk_credential_",Jr="w3pk_credential_index";F=class{constructor(e){if(e)this.storage=e;else if(typeof window<"u"&&window.localStorage)this.storage=window.localStorage;else throw new R("localStorage is not available")}async saveCredential(e){try{let t=await Ko(e.id),r=await pt(e.id),s={id:r,encryptedUsername:await ie(e.username,t),encryptedAddress:await ie(e.ethereumAddress,t),publicKey:e.publicKey,publicKeyFingerprint:await Es(e.publicKey),createdAt:e.createdAt,lastUsed:e.lastUsed},i=`${jr}${r}`;this.storage.setItem(i,JSON.stringify(s)),await this.addToIndex(e.id)}catch(t){throw new R("Failed to save credential",t)}}async getCredentialById(e){try{let t=await pt(e),r=`${jr}${t}`,s=this.storage.getItem(r);if(!s)return null;let i=JSON.parse(s),o=await Ko(e);return{id:e,publicKey:i.publicKey,username:await oe(i.encryptedUsername,o),ethereumAddress:await oe(i.encryptedAddress,o),createdAt:i.createdAt,lastUsed:i.lastUsed}}catch(t){throw new R("Failed to retrieve credential",t)}}async getCredentialByUsername(e){try{return(await this.getAllCredentials()).find(r=>r.username===e)||null}catch(t){throw new R("Failed to retrieve credential",t)}}async getCredentialByAddress(e){try{return(await this.getAllCredentials()).find(r=>r.ethereumAddress.toLowerCase()===e.toLowerCase())||null}catch(t){throw new R("Failed to retrieve credential",t)}}async getAllCredentials(){try{let e=await this.getIndex();return(await Promise.all(e.map(async r=>await this.getCredentialById(r)))).filter(r=>r!==null)}catch(e){throw new R("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 R("Failed to update timestamp",t)}}async updateSignatureCounter(e,t){try{let r=await this.getCredentialById(e);r&&(r.signCount=t,r.lastUsed=new Date().toISOString(),await this.saveCredential(r))}catch(r){throw new R("Failed to update signature counter",r)}}async updateCredentialAddress(e,t){try{let r=await this.getCredentialById(e);r&&(r.ethereumAddress=t,r.lastUsed=new Date().toISOString(),await this.saveCredential(r))}catch(r){throw new R("Failed to update credential address",r)}}async deleteCredential(e){try{let t=await pt(e),r=`${jr}${t}`;this.storage.removeItem(r),await this.removeFromIndex(e)}catch(t){throw new R("Failed to delete credential",t)}}async clearAll(){try{let e=await this.getIndex();(await Promise.all(e.map(async r=>await pt(r)))).forEach(r=>{let s=`${jr}${r}`;this.storage.removeItem(s)}),this.storage.removeItem(Jr)}catch(e){throw new R("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 r=(await this.getIndex()).filter(s=>s!==e);this.storage.setItem(Jr,JSON.stringify(r))}}});var Ps={};B(Ps,{createWalletFromMnemonic:()=>Cs,deriveWalletFromMnemonic:()=>rr,generateBIP39Wallet:()=>tr});function tr(){try{let n=er.ethers.Wallet.createRandom().mnemonic;if(!n)throw new Error("Failed to generate mnemonic");let e=n.phrase;return{address:er.ethers.HDNodeWallet.fromPhrase(e,void 0,"m/44'/60'/0'/0/0").address,mnemonic:e}}catch(n){throw new S("Wallet generation failed",n)}}function Cs(n){try{if(!n||n.trim().split(/\s+/).length<12)throw new Error("Invalid mnemonic: must be at least 12 words");return er.ethers.HDNodeWallet.fromPhrase(n.trim(),void 0,"m/44'/60'/0'/0/0")}catch(e){throw new S(`Wallet creation failed: ${e instanceof Error?e.message:"Invalid mnemonic"}`,e)}}function rr(n,e=0){try{if(!n||n.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}`,r=er.ethers.HDNodeWallet.fromPhrase(n.trim(),void 0,t);return{address:r.address,privateKey:r.privateKey}}catch(t){throw new S(`HD wallet derivation failed: ${t instanceof Error?t.message:"Unknown error"}`,t)}}var er,gt=w(()=>{"use strict";er=require("ethers");Y()});var tn={};B(tn,{DEFAULT_MODE:()=>fe,DEFAULT_TAG:()=>pe,deriveAddressFromP256PublicKey:()=>Is,deriveIndexFromOriginModeAndTag:()=>en,getCurrentOrigin:()=>Me,getOriginSpecificAddress:()=>Fe,normalizeOrigin:()=>nr});function nr(n){try{let e=new URL(n),t=`${e.protocol}//${e.hostname.toLowerCase()}`,r=e.port;return r&&!(e.protocol==="https:"&&r==="443"||e.protocol==="http:"&&r==="80")&&(t+=`:${r}`),t}catch(e){throw new S(`Invalid origin URL: ${n}`,e)}}async function en(n,e=fe,t=pe){try{let s=`${nr(n)}:${e}:${t.toUpperCase()}`,o=new TextEncoder().encode(s),c=await crypto.subtle.digest("SHA-256",o);return new DataView(c).getUint32(0,!1)%Od}catch(r){throw new S(`Failed to derive index from origin "${n}", mode "${e}", and tag "${t}"`,r)}}async function Fe(n,e,t,r){try{let s=t||fe,i=(r||pe).toUpperCase(),o=nr(e),c=await en(o,s,i),{address:a,privateKey:u}=rr(n,c),l={address:a,index:c,origin:o,mode:s,tag:i};return s==="YOLO"&&(l.privateKey=u),l}catch(s){throw new S(`Failed to derive origin-specific address for "${e}" with mode "${t||fe}" and tag "${r||pe}"`,s)}}function Me(){if(typeof window>"u"||!window.location)throw new S("getCurrentOrigin() only works in browser environments");return window.location.origin}async function Is(n){try{let e=L(n),t=await crypto.subtle.importKey("spki",e,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),r=await crypto.subtle.exportKey("jwk",t);if(!r.x||!r.y)throw new Error("Invalid P-256 public key: missing x or y coordinates");let s=L(r.x),i=L(r.y),o=new Uint8Array(64);return o.set(new Uint8Array(s),0),o.set(new Uint8Array(i),32),"0x"+(0,$o.keccak256)(o).slice(-40)}catch(e){throw new S("Failed to derive address from P-256 public key",e)}}var $o,fe,pe,Od,mt=w(()=>{"use strict";gt();Y();$o=require("ethers");xe();fe="STANDARD",pe="MAIN",Od=2147483647});var Ts={};B(Ts,{encodeEIP7702AuthorizationMessage:()=>ar,hashEIP7702AuthorizationMessage:()=>cr,verifyEIP7702Authorization:()=>cn});function ar(n,e,t){let r=[n===0n?"0x":(0,Z.toBeHex)(n),e.toLowerCase(),t===0n?"0x":(0,Z.toBeHex)(t)],s=(0,Z.encodeRlp)(r);return(0,Z.concat)(["0x05",s])}function cr(n,e,t){let r=ar(n,e,t);return(0,Z.keccak256)(r)}function cn(n,e,t,r,s){try{let i=cr(n,e,t),o;return typeof r=="string"?o=Z.Signature.from(r):o=r,(0,Z.recoverAddress)(i,o).toLowerCase()===s.toLowerCase()}catch{return!1}}var Z,ln=w(()=>{"use strict";Z=require("ethers")});var ta={};B(ta,{detectWalletProvider:()=>hn,getDefaultProvider:()=>dn,requestExternalWalletAuthorization:()=>un,supportsEIP7702Authorization:()=>fn});async function un(n,e){if(!n)throw new Error("No external wallet provider found. Please install MetaMask or similar wallet.");let t=BigInt(e.chainId||1),r=e.nonce||0n,s=e.accountIndex||0,i=await n.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:c,verifyEIP7702Authorization:a}=await Promise.resolve().then(()=>(ln(),Ts)),{Signature:u}=await import("ethers"),l=c(t,e.delegateToAddress,r),h;try{h=await n.request({method:"eth_sign",params:[o,l]})}catch(y){try{h=await n.request({method:"personal_sign",params:[l,o]})}catch(k){throw new Error(`Failed to request signature from wallet. eth_sign error: ${y.message}, personal_sign error: ${k.message}`)}}let g=u.from(h),d={chainId:t,address:e.delegateToAddress.toLowerCase(),nonce:r,yParity:g.yParity,r:g.r,s:g.s};if(!a(t,e.delegateToAddress,r,d,o))throw new Error(`Signature verification failed. Expected signer: ${o}, but signature does not match. This may indicate a wallet implementation issue.`);return d}function dn(){if(typeof window>"u")return null;let n=window;return n.ethereum?n.ethereum:n.web3?.currentProvider?n.web3.currentProvider:null}function hn(n){let e=n;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 fn(n){try{let e=await n.request({method:"eth_accounts"});return Array.isArray(e)}catch{return!1}}var Fs=w(()=>{"use strict"});var na={};B(na,{extractRS:()=>Ms});function Ms(n){let e=0;if(n[e++]!==48)throw new Error("Invalid DER signature: missing sequence tag");if(e++,n[e++]!==2)throw new Error("Invalid DER signature: missing r integer tag");let t=n[e++];t>32&&(e++,t--);let r=n.slice(e,e+t);if(e+=t,n[e++]!==2)throw new Error("Invalid DER signature: missing s integer tag");let s=n[e++];s>32&&(e++,s--);let i=n.slice(e,e+s),o=new Uint8Array(32),c=new Uint8Array(32);o.set(r,32-r.length),c.set(i,32-i.length);let a=BigInt("0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551"),u=BigInt("0x"+Buffer.from(c).toString("hex"));u>a/2n&&(u=a-u);let l="0x"+Buffer.from(o).toString("hex"),h="0x"+u.toString(16).padStart(64,"0");return{r:l,s:h}}var Ns=w(()=>{"use strict"});var sa={};B(sa,{BackupStorage:()=>Ge});var Ge,pn=w(()=>{"use strict";Ge=class{constructor(){this.dbName="Web3PasskeyBackup";this.version=1;this.db=null}async init(){return typeof indexedDB>"u"?Promise.resolve():new Promise((e,t)=>{let r=indexedDB.open(this.dbName,this.version);r.onerror=()=>t(r.error),r.onsuccess=()=>{this.db=r.result,e()},r.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,r)=>{let o=this.db.transaction(["backups"],"readwrite").objectStore("backups").put(e);o.onsuccess=()=>t(),o.onerror=()=>r(o.error)}):Promise.resolve()}async getBackupsByAddress(e){return this.db||await this.init(),this.db?new Promise((t,r)=>{let c=this.db.transaction(["backups"],"readonly").objectStore("backups").index("ethereumAddress").getAll(e);c.onsuccess=()=>t(c.result),c.onerror=()=>r(c.error)}):Promise.resolve([])}async getBackupById(e){return this.db||await this.init(),this.db?new Promise((t,r)=>{let o=this.db.transaction(["backups"],"readonly").objectStore("backups").get(e);o.onsuccess=()=>t(o.result||null),o.onerror=()=>r(o.error)}):Promise.resolve(null)}async deleteBackup(e){return this.db||await this.init(),this.db?new Promise((t,r)=>{let o=this.db.transaction(["backups"],"readwrite").objectStore("backups").delete(e);o.onsuccess=()=>t(),o.onerror=()=>r(o.error)}):Promise.resolve()}async getBackupCountByMethod(e){return this.db||await this.init(),this.db?new Promise((t,r)=>{let c=this.db.transaction(["backups"],"readonly").objectStore("backups").index("method").count(e);c.onsuccess=()=>t(c.result),c.onerror=()=>r(c.error)}):Promise.resolve(0)}}});var oa={};B(oa,{decryptWithPassword:()=>ur,deriveAddressChecksum:()=>ee,deriveKeyFromPassword:()=>gn,encryptWithPassword:()=>Ye,getDeviceFingerprint:()=>Ae,validatePasswordStrength:()=>ia});async function gn(n,e,t=31e4){let s=new TextEncoder().encode(n),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 Ye(n,e,t){let s=await gn(e,t,31e4),o=new TextEncoder().encode(n),c=crypto.getRandomValues(new Uint8Array(12)),a=await crypto.subtle.encrypt({name:"AES-GCM",iv:c},s,o);return{encrypted:lr(a),iv:lr(c),salt:lr(t),iterations:31e4}}async function ur(n,e,t,r,s=31e4){let i=Us(t),o=await gn(e,i,s),c=Us(r),a=Us(n),u=await crypto.subtle.decrypt({name:"AES-GCM",iv:c},o,a);return new TextDecoder().decode(u)}async function Ae(){let e=[navigator.userAgent,navigator.language,new Date().getTimezoneOffset().toString(),screen.width+"x"+screen.height,screen.colorDepth.toString()].join("|"),r=new TextEncoder().encode(e),s=await crypto.subtle.digest("SHA-256",r);return lr(s)}async function ee(n){let t=new TextEncoder().encode(n.toLowerCase()),r=await crypto.subtle.digest("SHA-256",t);return lr(r).substring(0,16)}function ia(n){let e=[],t=0;return n.length<12?e.push("Password must be at least 12 characters"):t+=25,/[A-Z]/.test(n)?t+=15:e.push("Add at least one uppercase letter"),/[a-z]/.test(n)?t+=15:e.push("Add at least one lowercase letter"),/[0-9]/.test(n)?t+=15:e.push("Add at least one number"),/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(n)?t+=15:e.push("Add at least one special character"),n.length>=16&&(t+=10),n.length>=20&&(t+=5),["password","12345678","qwerty","abc123","password123","admin","letmein"].some(s=>n.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 lr(n){let e=n instanceof Uint8Array?n:new Uint8Array(n),t="";for(let r=0;r<e.byteLength;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Us(n){let e=Ve(n),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t}var je=w(()=>{"use strict";xe()});var ca=D((km,aa)=>{"use strict";aa.exports=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then}});var Ne=D(Je=>{"use strict";var Ls,Yd=[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];Je.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};Je.getSymbolTotalCodewords=function(e){return Yd[e]};Je.getBCHDigit=function(n){let e=0;for(;n!==0;)e++,n>>>=1;return e};Je.setToSJISFunction=function(e){if(typeof e!="function")throw new Error('"toSJISFunc" is not a valid function.');Ls=e};Je.isKanjiModeEnabled=function(){return typeof Ls<"u"};Je.toSJIS=function(e){return Ls(e)}});var mn=D(ce=>{"use strict";ce.L={bit:1};ce.M={bit:0};ce.Q={bit:3};ce.H={bit:2};function jd(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return ce.L;case"m":case"medium":return ce.M;case"q":case"quartile":return ce.Q;case"h":case"high":return ce.H;default:throw new Error("Unknown EC Level: "+n)}}ce.isValid=function(e){return e&&typeof e.bit<"u"&&e.bit>=0&&e.bit<4};ce.from=function(e,t){if(ce.isValid(e))return e;try{return jd(e)}catch{return t}}});var da=D((Pm,ua)=>{"use strict";function la(){this.buffer=[],this.length=0}la.prototype={get:function(n){let e=Math.floor(n/8);return(this.buffer[e]>>>7-n%8&1)===1},put:function(n,e){for(let t=0;t<e;t++)this.putBit((n>>>e-t-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(n){let e=Math.floor(this.length/8);this.buffer.length<=e&&this.buffer.push(0),n&&(this.buffer[e]|=128>>>this.length%8),this.length++}};ua.exports=la});var fa=D((Im,ha)=>{"use strict";function dr(n){if(!n||n<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=n,this.data=new Uint8Array(n*n),this.reservedBit=new Uint8Array(n*n)}dr.prototype.set=function(n,e,t,r){let s=n*this.size+e;this.data[s]=t,r&&(this.reservedBit[s]=!0)};dr.prototype.get=function(n,e){return this.data[n*this.size+e]};dr.prototype.xor=function(n,e,t){this.data[n*this.size+e]^=t};dr.prototype.isReserved=function(n,e){return this.reservedBit[n*this.size+e]};ha.exports=dr});var pa=D(yn=>{"use strict";var Jd=Ne().getSymbolSize;yn.getRowColCoords=function(e){if(e===1)return[];let t=Math.floor(e/7)+2,r=Jd(e),s=r===145?26:Math.ceil((r-13)/(2*t-2))*2,i=[r-7];for(let o=1;o<t-1;o++)i[o]=i[o-1]-s;return i.push(6),i.reverse()};yn.getPositions=function(e){let t=[],r=yn.getRowColCoords(e),s=r.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([r[i],r[o]]);return t}});var ya=D(ma=>{"use strict";var Qd=Ne().getSymbolSize,ga=7;ma.getPositions=function(e){let t=Qd(e);return[[0,0],[t-ga,0],[0,t-ga]]}});var wa=D(M=>{"use strict";M.Patterns={PATTERN000:0,PATTERN001:1,PATTERN010:2,PATTERN011:3,PATTERN100:4,PATTERN101:5,PATTERN110:6,PATTERN111:7};var Qe={N1:3,N2:3,N3:40,N4:10};M.isValid=function(e){return e!=null&&e!==""&&!isNaN(e)&&e>=0&&e<=7};M.from=function(e){return M.isValid(e)?parseInt(e,10):void 0};M.getPenaltyN1=function(e){let t=e.size,r=0,s=0,i=0,o=null,c=null;for(let a=0;a<t;a++){s=i=0,o=c=null;for(let u=0;u<t;u++){let l=e.get(a,u);l===o?s++:(s>=5&&(r+=Qe.N1+(s-5)),o=l,s=1),l=e.get(u,a),l===c?i++:(i>=5&&(r+=Qe.N1+(i-5)),c=l,i=1)}s>=5&&(r+=Qe.N1+(s-5)),i>=5&&(r+=Qe.N1+(i-5))}return r};M.getPenaltyN2=function(e){let t=e.size,r=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)&&r++}return r*Qe.N2};M.getPenaltyN3=function(e){let t=e.size,r=0,s=0,i=0;for(let o=0;o<t;o++){s=i=0;for(let c=0;c<t;c++)s=s<<1&2047|e.get(o,c),c>=10&&(s===1488||s===93)&&r++,i=i<<1&2047|e.get(c,o),c>=10&&(i===1488||i===93)&&r++}return r*Qe.N3};M.getPenaltyN4=function(e){let t=0,r=e.data.length;for(let i=0;i<r;i++)t+=e.data[i];return Math.abs(Math.ceil(t*100/r/5)-10)*Qe.N4};function Xd(n,e,t){switch(n){case M.Patterns.PATTERN000:return(e+t)%2===0;case M.Patterns.PATTERN001:return e%2===0;case M.Patterns.PATTERN010:return t%3===0;case M.Patterns.PATTERN011:return(e+t)%3===0;case M.Patterns.PATTERN100:return(Math.floor(e/2)+Math.floor(t/3))%2===0;case M.Patterns.PATTERN101:return e*t%2+e*t%3===0;case M.Patterns.PATTERN110:return(e*t%2+e*t%3)%2===0;case M.Patterns.PATTERN111:return(e*t%3+(e+t)%2)%2===0;default:throw new Error("bad maskPattern:"+n)}}M.applyMask=function(e,t){let r=t.size;for(let s=0;s<r;s++)for(let i=0;i<r;i++)t.isReserved(i,s)||t.xor(i,s,Xd(e,i,s))};M.getBestMask=function(e,t){let r=Object.keys(M.Patterns).length,s=0,i=1/0;for(let o=0;o<r;o++){t(o),M.applyMask(o,e);let c=M.getPenaltyN1(e)+M.getPenaltyN2(e)+M.getPenaltyN3(e)+M.getPenaltyN4(e);M.applyMask(o,e),c<i&&(i=c,s=o)}return s}});var Os=D(_s=>{"use strict";var Ue=mn(),wn=[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],bn=[7,10,13,17,10,16,22,28,15,26,36,44,20,36,52,64,26,48,72,88,36,64,96,112,40,72,108,130,48,88,132,156,60,110,160,192,72,130,192,224,80,150,224,264,96,176,260,308,104,198,288,352,120,216,320,384,132,240,360,432,144,280,408,480,168,308,448,532,180,338,504,588,196,364,546,650,224,416,600,700,224,442,644,750,252,476,690,816,270,504,750,900,300,560,810,960,312,588,870,1050,336,644,952,1110,360,700,1020,1200,390,728,1050,1260,420,784,1140,1350,450,812,1200,1440,480,868,1290,1530,510,924,1350,1620,540,980,1440,1710,570,1036,1530,1800,570,1064,1590,1890,600,1120,1680,1980,630,1204,1770,2100,660,1260,1860,2220,720,1316,1950,2310,750,1372,2040,2430];_s.getBlocksCount=function(e,t){switch(t){case Ue.L:return wn[(e-1)*4+0];case Ue.M:return wn[(e-1)*4+1];case Ue.Q:return wn[(e-1)*4+2];case Ue.H:return wn[(e-1)*4+3];default:return}};_s.getTotalCodewordsCount=function(e,t){switch(t){case Ue.L:return bn[(e-1)*4+0];case Ue.M:return bn[(e-1)*4+1];case Ue.Q:return bn[(e-1)*4+2];case Ue.H:return bn[(e-1)*4+3];default:return}}});var ba=D(xn=>{"use strict";var hr=new Uint8Array(512),Sn=new Uint8Array(256);(function(){let e=1;for(let t=0;t<255;t++)hr[t]=e,Sn[e]=t,e<<=1,e&256&&(e^=285);for(let t=255;t<512;t++)hr[t]=hr[t-255]})();xn.log=function(e){if(e<1)throw new Error("log("+e+")");return Sn[e]};xn.exp=function(e){return hr[e]};xn.mul=function(e,t){return e===0||t===0?0:hr[Sn[e]+Sn[t]]}});var Sa=D(fr=>{"use strict";var Ks=ba();fr.mul=function(e,t){let r=new Uint8Array(e.length+t.length-1);for(let s=0;s<e.length;s++)for(let i=0;i<t.length;i++)r[s+i]^=Ks.mul(e[s],t[i]);return r};fr.mod=function(e,t){let r=new Uint8Array(e);for(;r.length-t.length>=0;){let s=r[0];for(let o=0;o<t.length;o++)r[o]^=Ks.mul(t[o],s);let i=0;for(;i<r.length&&r[i]===0;)i++;r=r.slice(i)}return r};fr.generateECPolynomial=function(e){let t=new Uint8Array([1]);for(let r=0;r<e;r++)t=fr.mul(t,new Uint8Array([1,Ks.exp(r)]));return t}});var Aa=D((Nm,va)=>{"use strict";var xa=Sa();function zs(n){this.genPoly=void 0,this.degree=n,this.degree&&this.initialize(this.degree)}zs.prototype.initialize=function(e){this.degree=e,this.genPoly=xa.generateECPolynomial(this.degree)};zs.prototype.encode=function(e){if(!this.genPoly)throw new Error("Encoder not initialized");let t=new Uint8Array(e.length+this.degree);t.set(e);let r=xa.mod(t,this.genPoly),s=this.degree-r.length;if(s>0){let i=new Uint8Array(this.degree);return i.set(r,s),i}return r};va.exports=zs});var Ws=D(ka=>{"use strict";ka.isValid=function(e){return!isNaN(e)&&e>=1&&e<=40}});var $s=D(Ce=>{"use strict";var Ea="[0-9]+",Zd="[A-Z $%*+\\-./:]+",pr="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";pr=pr.replace(/u/g,"\\u");var eh="(?:(?![A-Z0-9 $%*+\\-./:]|"+pr+`)(?:.|[\r
2
+ ]))+`;Ce.KANJI=new RegExp(pr,"g");Ce.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");Ce.BYTE=new RegExp(eh,"g");Ce.NUMERIC=new RegExp(Ea,"g");Ce.ALPHANUMERIC=new RegExp(Zd,"g");var th=new RegExp("^"+pr+"$"),rh=new RegExp("^"+Ea+"$"),nh=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");Ce.testKanji=function(e){return th.test(e)};Ce.testNumeric=function(e){return rh.test(e)};Ce.testAlphanumeric=function(e){return nh.test(e)}});var Le=D(_=>{"use strict";var sh=Ws(),qs=$s();_.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(!sh.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 ih(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"numeric":return _.NUMERIC;case"alphanumeric":return _.ALPHANUMERIC;case"kanji":return _.KANJI;case"byte":return _.BYTE;default:throw new Error("Unknown mode: "+n)}}_.from=function(e,t){if(_.isValid(e))return e;try{return ih(e)}catch{return t}}});var Da=D(Xe=>{"use strict";var vn=Ne(),oh=Os(),Ca=mn(),_e=Le(),Hs=Ws(),Ia=7973,Pa=vn.getBCHDigit(Ia);function ah(n,e,t){for(let r=1;r<=40;r++)if(e<=Xe.getCapacity(r,t,n))return r}function Ba(n,e){return _e.getCharCountIndicator(n,e)+4}function ch(n,e){let t=0;return n.forEach(function(r){let s=Ba(r.mode,e);t+=s+r.getBitsLength()}),t}function lh(n,e){for(let t=1;t<=40;t++)if(ch(n,t)<=Xe.getCapacity(t,e,_e.MIXED))return t}Xe.from=function(e,t){return Hs.isValid(e)?parseInt(e,10):t};Xe.getCapacity=function(e,t,r){if(!Hs.isValid(e))throw new Error("Invalid QR Code version");typeof r>"u"&&(r=_e.BYTE);let s=vn.getSymbolTotalCodewords(e),i=oh.getTotalCodewordsCount(e,t),o=(s-i)*8;if(r===_e.MIXED)return o;let c=o-Ba(r,e);switch(r){case _e.NUMERIC:return Math.floor(c/10*3);case _e.ALPHANUMERIC:return Math.floor(c/11*2);case _e.KANJI:return Math.floor(c/13);case _e.BYTE:default:return Math.floor(c/8)}};Xe.getBestVersionForData=function(e,t){let r,s=Ca.from(t,Ca.M);if(Array.isArray(e)){if(e.length>1)return lh(e,s);if(e.length===0)return 1;r=e[0]}else r=e;return ah(r.mode,r.getLength(),s)};Xe.getEncodedBits=function(e){if(!Hs.isValid(e)||e<7)throw new Error("Invalid QR Code version");let t=e<<12;for(;vn.getBCHDigit(t)-Pa>=0;)t^=Ia<<vn.getBCHDigit(t)-Pa;return e<<12|t}});var Ma=D(Fa=>{"use strict";var Vs=Ne(),Ta=1335,uh=21522,Ra=Vs.getBCHDigit(Ta);Fa.getEncodedBits=function(e,t){let r=e.bit<<3|t,s=r<<10;for(;Vs.getBCHDigit(s)-Ra>=0;)s^=Ta<<Vs.getBCHDigit(s)-Ra;return(r<<10|s)^uh}});var Ua=D((zm,Na)=>{"use strict";var dh=Le();function bt(n){this.mode=dh.NUMERIC,this.data=n.toString()}bt.getBitsLength=function(e){return 10*Math.floor(e/3)+(e%3?e%3*3+1:0)};bt.prototype.getLength=function(){return this.data.length};bt.prototype.getBitsLength=function(){return bt.getBitsLength(this.data.length)};bt.prototype.write=function(e){let t,r,s;for(t=0;t+3<=this.data.length;t+=3)r=this.data.substr(t,3),s=parseInt(r,10),e.put(s,10);let i=this.data.length-t;i>0&&(r=this.data.substr(t),s=parseInt(r,10),e.put(s,i*3+1))};Na.exports=bt});var _a=D((Wm,La)=>{"use strict";var hh=Le(),Gs=["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 St(n){this.mode=hh.ALPHANUMERIC,this.data=n}St.getBitsLength=function(e){return 11*Math.floor(e/2)+6*(e%2)};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;for(t=0;t+2<=this.data.length;t+=2){let r=Gs.indexOf(this.data[t])*45;r+=Gs.indexOf(this.data[t+1]),e.put(r,11)}this.data.length%2&&e.put(Gs.indexOf(this.data[t]),6)};La.exports=St});var Ka=D(($m,Oa)=>{"use strict";var fh=Le();function xt(n){this.mode=fh.BYTE,typeof n=="string"?this.data=new TextEncoder().encode(n):this.data=new Uint8Array(n)}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(n){for(let e=0,t=this.data.length;e<t;e++)n.put(this.data[e],8)};Oa.exports=xt});var Wa=D((qm,za)=>{"use strict";var ph=Le(),gh=Ne();function vt(n){this.mode=ph.KANJI,this.data=n}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(n){let e;for(e=0;e<this.data.length;e++){let t=gh.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),n.put(t,13)}};za.exports=vt});var $a=D((Hm,Ys)=>{"use strict";var gr={single_source_shortest_paths:function(n,e,t){var r={},s={};s[e]=0;var i=gr.PriorityQueue.make();i.push(e,0);for(var o,c,a,u,l,h,g,d,f;!i.empty();){o=i.pop(),c=o.value,u=o.cost,l=n[c]||{};for(a in l)l.hasOwnProperty(a)&&(h=l[a],g=u+h,d=s[a],f=typeof s[a]>"u",(f||d>g)&&(s[a]=g,i.push(a,g),r[a]=c))}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 r},extract_shortest_path_from_predecessor_list:function(n,e){for(var t=[],r=e,s;r;)t.push(r),s=n[r],r=n[r];return t.reverse(),t},find_path:function(n,e,t){var r=gr.single_source_shortest_paths(n,e,t);return gr.extract_shortest_path_from_predecessor_list(r,t)},PriorityQueue:{make:function(n){var e=gr.PriorityQueue,t={},r;n=n||{};for(r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);return t.queue=[],t.sorter=n.sorter||e.default_sorter,t},default_sorter:function(n,e){return n.cost-e.cost},push:function(n,e){var t={value:n,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 Ys<"u"&&(Ys.exports=gr)});var Qa=D(At=>{"use strict";var T=Le(),Va=Ua(),Ga=_a(),Ya=Ka(),ja=Wa(),mr=$s(),An=Ne(),mh=$a();function qa(n){return unescape(encodeURIComponent(n)).length}function yr(n,e,t){let r=[],s;for(;(s=n.exec(t))!==null;)r.push({data:s[0],index:s.index,mode:e,length:s[0].length});return r}function Ja(n){let e=yr(mr.NUMERIC,T.NUMERIC,n),t=yr(mr.ALPHANUMERIC,T.ALPHANUMERIC,n),r,s;return An.isKanjiModeEnabled()?(r=yr(mr.BYTE,T.BYTE,n),s=yr(mr.KANJI,T.KANJI,n)):(r=yr(mr.BYTE_KANJI,T.BYTE,n),s=[]),e.concat(t,r,s).sort(function(o,c){return o.index-c.index}).map(function(o){return{data:o.data,mode:o.mode,length:o.length}})}function js(n,e){switch(e){case T.NUMERIC:return Va.getBitsLength(n);case T.ALPHANUMERIC:return Ga.getBitsLength(n);case T.KANJI:return ja.getBitsLength(n);case T.BYTE:return Ya.getBitsLength(n)}}function yh(n){return n.reduce(function(e,t){let r=e.length-1>=0?e[e.length-1]:null;return r&&r.mode===t.mode?(e[e.length-1].data+=t.data,e):(e.push(t),e)},[])}function wh(n){let e=[];for(let t=0;t<n.length;t++){let r=n[t];switch(r.mode){case T.NUMERIC:e.push([r,{data:r.data,mode:T.ALPHANUMERIC,length:r.length},{data:r.data,mode:T.BYTE,length:r.length}]);break;case T.ALPHANUMERIC:e.push([r,{data:r.data,mode:T.BYTE,length:r.length}]);break;case T.KANJI:e.push([r,{data:r.data,mode:T.BYTE,length:qa(r.data)}]);break;case T.BYTE:e.push([{data:r.data,mode:T.BYTE,length:qa(r.data)}])}}return e}function bh(n,e){let t={},r={start:{}},s=["start"];for(let i=0;i<n.length;i++){let o=n[i],c=[];for(let a=0;a<o.length;a++){let u=o[a],l=""+i+a;c.push(l),t[l]={node:u,lastCount:0},r[l]={};for(let h=0;h<s.length;h++){let g=s[h];t[g]&&t[g].node.mode===u.mode?(r[g][l]=js(t[g].lastCount+u.length,u.mode)-js(t[g].lastCount,u.mode),t[g].lastCount+=u.length):(t[g]&&(t[g].lastCount=u.length),r[g][l]=js(u.length,u.mode)+4+T.getCharCountIndicator(u.mode,e))}}s=c}for(let i=0;i<s.length;i++)r[s[i]].end=0;return{map:r,table:t}}function Ha(n,e){let t,r=T.getBestModeForData(n);if(t=T.from(e,r),t!==T.BYTE&&t.bit<r.bit)throw new Error('"'+n+'" cannot be encoded with mode '+T.toString(t)+`.
4
+ Suggested mode is: `+T.toString(r));switch(t===T.KANJI&&!An.isKanjiModeEnabled()&&(t=T.BYTE),t){case T.NUMERIC:return new Va(n);case T.ALPHANUMERIC:return new Ga(n);case T.KANJI:return new ja(n);case T.BYTE:return new Ya(n)}}At.fromArray=function(e){return e.reduce(function(t,r){return typeof r=="string"?t.push(Ha(r,null)):r.data&&t.push(Ha(r.data,r.mode)),t},[])};At.fromString=function(e,t){let r=Ja(e,An.isKanjiModeEnabled()),s=wh(r),i=bh(s,t),o=mh.find_path(i.map,"start","end"),c=[];for(let a=1;a<o.length-1;a++)c.push(i.table[o[a]].node);return At.fromArray(yh(c))};At.rawSplit=function(e){return At.fromArray(Ja(e,An.isKanjiModeEnabled()))}});var Za=D(Xa=>{"use strict";var En=Ne(),Js=mn(),Sh=da(),xh=fa(),vh=pa(),Ah=ya(),Zs=wa(),ei=Os(),kh=Aa(),kn=Da(),Eh=Ma(),Ch=Le(),Qs=Qa();function Ph(n,e){let t=n.size,r=Ah.getPositions(e);for(let s=0;s<r.length;s++){let i=r[s][0],o=r[s][1];for(let c=-1;c<=7;c++)if(!(i+c<=-1||t<=i+c))for(let a=-1;a<=7;a++)o+a<=-1||t<=o+a||(c>=0&&c<=6&&(a===0||a===6)||a>=0&&a<=6&&(c===0||c===6)||c>=2&&c<=4&&a>=2&&a<=4?n.set(i+c,o+a,!0,!0):n.set(i+c,o+a,!1,!0))}}function Ih(n){let e=n.size;for(let t=8;t<e-8;t++){let r=t%2===0;n.set(t,6,r,!0),n.set(6,t,r,!0)}}function Bh(n,e){let t=vh.getPositions(e);for(let r=0;r<t.length;r++){let s=t[r][0],i=t[r][1];for(let o=-2;o<=2;o++)for(let c=-2;c<=2;c++)o===-2||o===2||c===-2||c===2||o===0&&c===0?n.set(s+o,i+c,!0,!0):n.set(s+o,i+c,!1,!0)}}function Dh(n,e){let t=n.size,r=kn.getEncodedBits(e),s,i,o;for(let c=0;c<18;c++)s=Math.floor(c/3),i=c%3+t-8-3,o=(r>>c&1)===1,n.set(s,i,o,!0),n.set(i,s,o,!0)}function Xs(n,e,t){let r=n.size,s=Eh.getEncodedBits(e,t),i,o;for(i=0;i<15;i++)o=(s>>i&1)===1,i<6?n.set(i,8,o,!0):i<8?n.set(i+1,8,o,!0):n.set(r-15+i,8,o,!0),i<8?n.set(8,r-i-1,o,!0):i<9?n.set(8,15-i-1+1,o,!0):n.set(8,15-i-1,o,!0);n.set(r-8,8,1,!0)}function Rh(n,e){let t=n.size,r=-1,s=t-1,i=7,o=0;for(let c=t-1;c>0;c-=2)for(c===6&&c--;;){for(let a=0;a<2;a++)if(!n.isReserved(s,c-a)){let u=!1;o<e.length&&(u=(e[o]>>>i&1)===1),n.set(s,c-a,u),i--,i===-1&&(o++,i=7)}if(s+=r,s<0||t<=s){s-=r,r=-r;break}}}function Th(n,e,t){let r=new Sh;t.forEach(function(a){r.put(a.mode.bit,4),r.put(a.getLength(),Ch.getCharCountIndicator(a.mode,n)),a.write(r)});let s=En.getSymbolTotalCodewords(n),i=ei.getTotalCodewordsCount(n,e),o=(s-i)*8;for(r.getLengthInBits()+4<=o&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);let c=(o-r.getLengthInBits())/8;for(let a=0;a<c;a++)r.put(a%2?17:236,8);return Fh(r,n,e)}function Fh(n,e,t){let r=En.getSymbolTotalCodewords(e),s=ei.getTotalCodewordsCount(e,t),i=r-s,o=ei.getBlocksCount(e,t),c=r%o,a=o-c,u=Math.floor(r/o),l=Math.floor(i/o),h=l+1,g=u-l,d=new kh(g),f=0,y=new Array(o),k=new Array(o),m=0,b=new Uint8Array(n.buffer);for(let x=0;x<o;x++){let P=x<a?l:h;y[x]=b.slice(f,f+P),k[x]=d.encode(y[x]),f+=P,m=Math.max(m,P)}let v=new Uint8Array(r),A=0,E,C;for(E=0;E<m;E++)for(C=0;C<o;C++)E<y[C].length&&(v[A++]=y[C][E]);for(E=0;E<g;E++)for(C=0;C<o;C++)v[A++]=k[C][E];return v}function Mh(n,e,t,r){let s;if(Array.isArray(n))s=Qs.fromArray(n);else if(typeof n=="string"){let u=e;if(!u){let l=Qs.rawSplit(n);u=kn.getBestVersionForData(l,t)}s=Qs.fromString(n,u||40)}else throw new Error("Invalid data");let i=kn.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=Th(e,t,s),c=kn.getSymbolSize(e),a=new xh(c);return Ph(a,e),Ih(a),Bh(a,e),Qs(a,t,0),e>=7&&Dh(a,e),Rh(a,o),isNaN(r)&&(r=Xs.getBestMask(a,Qs.bind(null,a,t))),Xs.applyMask(r,a),Qs(a,t,r),{modules:a,version:e,errorCorrectionLevel:t,maskPattern:r,segments:s}}Qa.create=function(e,t){if(typeof e>"u"||e==="")throw new Error("No input text");let r=js.M,s,i;return typeof t<"u"&&(r=js.from(t.errorCorrectionLevel,js.M),s=An.from(t.version),i=Xs.from(t.maskPattern),t.toSJISFunc&&kn.setToSJISFunction(t.toSJISFunc)),Mh(e,s,r,i)}});var ei=D(Ze=>{"use strict";function Za(n){if(typeof n=="number"&&(n=n.toString()),typeof n!="string")throw new Error("Color should be defined as hex string");let e=n.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+n);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(r){return[r,r]}))),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("")}}Ze.getOptions=function(e){e||(e={}),e.color||(e.color={});let t=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,r=e.width&&e.width>=21?e.width:void 0,s=e.scale||4;return{width:r,scale:r?4:s,margin:t,color:{dark:Za(e.color.dark||"#000000ff"),light:Za(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Ze.getScale=function(e,t){return t.width&&t.width>=e+t.margin*2?t.width/(e+t.margin*2):t.scale};Ze.getImageWidth=function(e,t){let r=Ze.getScale(e,t);return Math.floor((e+t.margin*2)*r)};Ze.qrToImageData=function(e,t,r){let s=t.modules.size,i=t.modules.data,o=Ze.getScale(s,r),c=Math.floor((s+r.margin*2)*o),a=r.margin*o,u=[r.color.light,r.color.dark];for(let l=0;l<c;l++)for(let h=0;h<c;h++){let g=(l*c+h)*4,d=r.color.light;if(l>=a&&h>=a&&l<c-a&&h<c-a){let f=Math.floor((l-a)/o),y=Math.floor((h-a)/o);d=u[i[f*s+y]?1:0]}e[g++]=d.r,e[g++]=d.g,e[g++]=d.b,e[g]=d.a}}});var ec=D(En=>{"use strict";var ti=ei();function Nh(n,e,t){n.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 Uh(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}En.render=function(e,t,r){let s=r,i=t;typeof s>"u"&&(!t||!t.getContext)&&(s=t,t=void 0),t||(i=Uh()),s=ti.getOptions(s);let o=ti.getImageWidth(e.modules.size,s),c=i.getContext("2d"),a=c.createImageData(o,o);return ti.qrToImageData(a.data,e,s),Nh(c,i,o),c.putImageData(a,0,0),i};En.renderToDataURL=function(e,t,r){let s=r;typeof s>"u"&&(!t||!t.getContext)&&(s=t,t=void 0),s||(s={});let i=En.render(e,t,s),o=s.type||"image/png",c=s.rendererOpts||{};return i.toDataURL(o,c.quality)}});var nc=D(rc=>{"use strict";var Lh=ei();function tc(n,e){let t=n.a/255,r=e+'="'+n.hex+'"';return t<1?r+" "+e+'-opacity="'+t.toFixed(2).slice(1)+'"':r}function ri(n,e,t){let r=n+e;return typeof t<"u"&&(r+=" "+t),r}function _h(n,e,t){let r="",s=0,i=!1,o=0;for(let c=0;c<n.length;c++){let a=Math.floor(c%e),u=Math.floor(c/e);!a&&!i&&(i=!0),n[c]?(o++,c>0&&a>0&&n[c-1]||(r+=i?ri("M",a+t,.5+u+t):ri("m",s,0),s=0,i=!1),a+1<e&&n[c+1]||(r+=ri("h",o),o=0)):s++}return r}rc.render=function(e,t,r){let s=Lh.getOptions(t),i=e.modules.size,o=e.modules.data,c=i+s.margin*2,a=s.color.light.a?"<path "+tc(s.color.light,"fill")+' d="M0 0h'+c+"v"+c+'H0z"/>':"",u="<path "+tc(s.color.dark,"stroke")+' d="'+_h(o,i,s.margin)+'"/>',l='viewBox="0 0 '+c+" "+c+'"',g='<svg xmlns="http://www.w3.org/2000/svg" '+(s.width?'width="'+s.width+'" height="'+s.width+'" ':"")+l+' shape-rendering="crispEdges">'+a+u+`</svg>
8
- `;return typeof r=="function"&&r(null,g),g}});var wr=D(yr=>{"use strict";var Oh=aa(),ni=Xa(),sc=ec(),Kh=nc();function si(n,e,t,r,s){let i=[].slice.call(arguments,1),o=i.length,c=typeof i[o-1]=="function";if(!c&&!Oh())throw new Error("Callback required as last argument");if(c){if(o<2)throw new Error("Too few arguments provided");o===2?(s=t,t=e,e=r=void 0):o===3&&(e.getContext&&typeof s>"u"?(s=r,r=void 0):(s=r,r=t,t=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(t=e,e=r=void 0):o===2&&!e.getContext&&(r=t,t=e,e=void 0),new Promise(function(a,u){try{let l=ni.create(t,r);a(n(l,e,r))}catch(l){u(l)}})}try{let a=ni.create(t,r);s(null,n(a,e,r))}catch(a){s(a)}}yr.create=ni.create;yr.toCanvas=si.bind(null,sc.render);yr.toDataURL=si.bind(null,sc.renderToDataURL);yr.toString=si.bind(null,function(n,e,t){return Kh.render(n,t)})});var At,ii=w(()=>{"use strict";je();At=class{async createQRBackup(e,t,r={}){let s=r.errorCorrection||"H",i;if(r.password){let u=crypto.getRandomValues(new Uint8Array(32)),l=await Ye(e,r.password,u);i={version:1,type:"encrypted",data:l.encrypted,iv:l.iv,salt:l.salt,iterations:l.iterations,checksum:await ee(t)}}else i={version:1,type:"plain",data:e,checksum:await ee(t)};let o=JSON.stringify(i),c=await this.generateQRCode(o,s),a=this.getInstructions(t,!!r.password);return{qrCodeDataURL:c,rawData:o,instructions:a}}async generateQRCode(e,t){try{return await(await Promise.resolve().then(()=>K(wr()))).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 r=t.getContext("2d");if(!r)throw new Error("Canvas not supported");r.fillStyle="white",r.fillRect(0,0,512,512),r.fillStyle="black",r.font="12px monospace",r.textAlign="center",r.textBaseline="middle";let s=this.wrapText(e,50),i=14,o=256-s.length*i/2;return s.forEach((c,a)=>{r.fillText(c,256,o+a*i)}),r.font="bold 16px sans-serif",r.fillText('Install "qrcode" package for QR codes',256,480),t.toDataURL("image/png")}wrapText(e,t){let r=[];for(let s=0;s<e.length;s+=t)r.push(e.substring(s,s+t));return r}getInstructions(e,t){return`
7
+ `);let o=Th(e,t,s),c=En.getSymbolSize(e),a=new xh(c);return Ph(a,e),Ih(a),Bh(a,e),Xs(a,t,0),e>=7&&Dh(a,e),Rh(a,o),isNaN(r)&&(r=Zs.getBestMask(a,Xs.bind(null,a,t))),Zs.applyMask(r,a),Xs(a,t,r),{modules:a,version:e,errorCorrectionLevel:t,maskPattern:r,segments:s}}Xa.create=function(e,t){if(typeof e>"u"||e==="")throw new Error("No input text");let r=Js.M,s,i;return typeof t<"u"&&(r=Js.from(t.errorCorrectionLevel,Js.M),s=kn.from(t.version),i=Zs.from(t.maskPattern),t.toSJISFunc&&En.setToSJISFunction(t.toSJISFunc)),Mh(e,s,r,i)}});var ti=D(Ze=>{"use strict";function ec(n){if(typeof n=="number"&&(n=n.toString()),typeof n!="string")throw new Error("Color should be defined as hex string");let e=n.slice().replace("#","").split("");if(e.length<3||e.length===5||e.length>8)throw new Error("Invalid hex color: "+n);(e.length===3||e.length===4)&&(e=Array.prototype.concat.apply([],e.map(function(r){return[r,r]}))),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("")}}Ze.getOptions=function(e){e||(e={}),e.color||(e.color={});let t=typeof e.margin>"u"||e.margin===null||e.margin<0?4:e.margin,r=e.width&&e.width>=21?e.width:void 0,s=e.scale||4;return{width:r,scale:r?4:s,margin:t,color:{dark:ec(e.color.dark||"#000000ff"),light:ec(e.color.light||"#ffffffff")},type:e.type,rendererOpts:e.rendererOpts||{}}};Ze.getScale=function(e,t){return t.width&&t.width>=e+t.margin*2?t.width/(e+t.margin*2):t.scale};Ze.getImageWidth=function(e,t){let r=Ze.getScale(e,t);return Math.floor((e+t.margin*2)*r)};Ze.qrToImageData=function(e,t,r){let s=t.modules.size,i=t.modules.data,o=Ze.getScale(s,r),c=Math.floor((s+r.margin*2)*o),a=r.margin*o,u=[r.color.light,r.color.dark];for(let l=0;l<c;l++)for(let h=0;h<c;h++){let g=(l*c+h)*4,d=r.color.light;if(l>=a&&h>=a&&l<c-a&&h<c-a){let f=Math.floor((l-a)/o),y=Math.floor((h-a)/o);d=u[i[f*s+y]?1:0]}e[g++]=d.r,e[g++]=d.g,e[g++]=d.b,e[g]=d.a}}});var tc=D(Cn=>{"use strict";var ri=ti();function Nh(n,e,t){n.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 Uh(){try{return document.createElement("canvas")}catch{throw new Error("You need to specify a canvas element")}}Cn.render=function(e,t,r){let s=r,i=t;typeof s>"u"&&(!t||!t.getContext)&&(s=t,t=void 0),t||(i=Uh()),s=ri.getOptions(s);let o=ri.getImageWidth(e.modules.size,s),c=i.getContext("2d"),a=c.createImageData(o,o);return ri.qrToImageData(a.data,e,s),Nh(c,i,o),c.putImageData(a,0,0),i};Cn.renderToDataURL=function(e,t,r){let s=r;typeof s>"u"&&(!t||!t.getContext)&&(s=t,t=void 0),s||(s={});let i=Cn.render(e,t,s),o=s.type||"image/png",c=s.rendererOpts||{};return i.toDataURL(o,c.quality)}});var sc=D(nc=>{"use strict";var Lh=ti();function rc(n,e){let t=n.a/255,r=e+'="'+n.hex+'"';return t<1?r+" "+e+'-opacity="'+t.toFixed(2).slice(1)+'"':r}function ni(n,e,t){let r=n+e;return typeof t<"u"&&(r+=" "+t),r}function _h(n,e,t){let r="",s=0,i=!1,o=0;for(let c=0;c<n.length;c++){let a=Math.floor(c%e),u=Math.floor(c/e);!a&&!i&&(i=!0),n[c]?(o++,c>0&&a>0&&n[c-1]||(r+=i?ni("M",a+t,.5+u+t):ni("m",s,0),s=0,i=!1),a+1<e&&n[c+1]||(r+=ni("h",o),o=0)):s++}return r}nc.render=function(e,t,r){let s=Lh.getOptions(t),i=e.modules.size,o=e.modules.data,c=i+s.margin*2,a=s.color.light.a?"<path "+rc(s.color.light,"fill")+' d="M0 0h'+c+"v"+c+'H0z"/>':"",u="<path "+rc(s.color.dark,"stroke")+' d="'+_h(o,i,s.margin)+'"/>',l='viewBox="0 0 '+c+" "+c+'"',g='<svg xmlns="http://www.w3.org/2000/svg" '+(s.width?'width="'+s.width+'" height="'+s.width+'" ':"")+l+' shape-rendering="crispEdges">'+a+u+`</svg>
8
+ `;return typeof r=="function"&&r(null,g),g}});var br=D(wr=>{"use strict";var Oh=ca(),si=Za(),ic=tc(),Kh=sc();function ii(n,e,t,r,s){let i=[].slice.call(arguments,1),o=i.length,c=typeof i[o-1]=="function";if(!c&&!Oh())throw new Error("Callback required as last argument");if(c){if(o<2)throw new Error("Too few arguments provided");o===2?(s=t,t=e,e=r=void 0):o===3&&(e.getContext&&typeof s>"u"?(s=r,r=void 0):(s=r,r=t,t=e,e=void 0))}else{if(o<1)throw new Error("Too few arguments provided");return o===1?(t=e,e=r=void 0):o===2&&!e.getContext&&(r=t,t=e,e=void 0),new Promise(function(a,u){try{let l=si.create(t,r);a(n(l,e,r))}catch(l){u(l)}})}try{let a=si.create(t,r);s(null,n(a,e,r))}catch(a){s(a)}}wr.create=si.create;wr.toCanvas=ii.bind(null,ic.render);wr.toDataURL=ii.bind(null,ic.renderToDataURL);wr.toString=ii.bind(null,function(n,e,t){return Kh.render(n,t)})});var kt,oi=w(()=>{"use strict";je();kt=class{async createQRBackup(e,t,r={}){let s=r.errorCorrection||"H",i;if(r.password){let u=crypto.getRandomValues(new Uint8Array(32)),l=await Ye(e,r.password,u);i={version:1,type:"encrypted",data:l.encrypted,iv:l.iv,salt:l.salt,iterations:l.iterations,checksum:await ee(t)}}else i={version:1,type:"plain",data:e,checksum:await ee(t)};let o=JSON.stringify(i),c=await this.generateQRCode(o,s),a=this.getInstructions(t,!!r.password);return{qrCodeDataURL:c,rawData:o,instructions:a}}async generateQRCode(e,t){try{return await(await Promise.resolve().then(()=>z(br()))).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 r=t.getContext("2d");if(!r)throw new Error("Canvas not supported");r.fillStyle="white",r.fillRect(0,0,512,512),r.fillStyle="black",r.font="12px monospace",r.textAlign="center",r.textBaseline="middle";let s=this.wrapText(e,50),i=14,o=256-s.length*i/2;return s.forEach((c,a)=>{r.fillText(c,256,o+a*i)}),r.font="bold 16px sans-serif",r.fillText('Install "qrcode" package for QR codes',256,480),t.toDataURL("image/png")}wrapText(e,t){let r=[];for(let s=0;s<e.length;s+=t)r.push(e.substring(s,s+t));return r}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 r=JSON.parse(e);if(r.version!==1)throw new Error("Unsupported QR backup version");let s;if(r.type==="encrypted"){if(!t)throw new Error("Password required for encrypted QR backup");let{decryptWithPassword:a}=await Promise.resolve().then(()=>(je(),ia));s=await a(r.data,t,r.salt,r.iv,r.iterations)}else if(r.type==="plain")s=r.data;else throw new Error("Unknown QR backup type");let{Wallet:i}=await import("ethers"),o=i.fromPhrase(s);if(await ee(o.address)!==r.checksum)throw new Error("Address checksum mismatch - corrupted QR or wrong password");return{mnemonic:s,ethereumAddress:o.address}}}});function zh(){let n=new Uint8Array(1);return crypto.getRandomValues(n),n[0]}function Pn(n,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 r=[];for(let s=0;s<t;s++)r[s]=new Uint8Array(n.length+1),r[s][0]=s+1;for(let s=0;s<n.length;s++){let o=[n[s]];for(let c=1;c<e;c++)o.push(zh());for(let c=0;c<t;c++){let a=c+1,u=Cn.evaluatePolynomial(o,a);r[c][s+1]=u}}return r}function In(n,e){if(n.length<e)throw new Error(`Need at least ${e} shares to recover secret, got ${n.length}`);let t=n.slice(0,e),r=t[0].length;for(let o of t)if(o.length!==r)throw new Error("All shares must have the same length");let s=r-1,i=new Uint8Array(s);for(let o=0;o<s;o++){let c=[];for(let a of t)c.push({x:a[0],y:a[o+1]});i[o]=Cn.interpolate(c)}return i}function Bn(n){return new TextEncoder().encode(n)}function Dn(n){return new TextDecoder().decode(n)}function Rn(n){return Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join("")}function Tn(n){let e=new Uint8Array(n.length/2);for(let t=0;t<n.length;t+=2)e[t/2]=parseInt(n.substring(t,t+2),16);return e}var Oe,Cn,oi=w(()=>{"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 r=0;for(let s=e.length-1;s>=0;s--)r=this.add(this.multiply(r,t),e[s]);return r}static interpolate(e){let t=0;for(let r=0;r<e.length;r++){let s=e[r].y,i=1;for(let o=0;o<e.length;o++)r!==o&&(s=this.multiply(s,e[o].x),i=this.multiply(i,this.add(e[r].x,e[o].x)));t=this.add(t,this.divide(s,i))}return t}};Oe.LOG_TABLE=[],Oe.EXP_TABLE=[],(()=>{let e=(r,s)=>{let i=0;for(let o=0;o<8;o++){s&1&&(i^=r);let c=r&128;r<<=1,c&&(r^=283),s>>=1}return i&255},t=1;for(let r=0;r<255;r++)Oe.EXP_TABLE[r]=t,Oe.LOG_TABLE[t]=r,t=e(t,3);Oe.EXP_TABLE[255]=Oe.EXP_TABLE[0]})();Cn=Oe});var ic,Fn,oc=w(()=>{"use strict";oi();ic=new Map,Fn=class{constructor(){this.storageKey="w3pk_social_recovery"}getItem(e){return typeof localStorage<"u"?localStorage.getItem(e):ic.get(e)||null}setItem(e,t){typeof localStorage<"u"?localStorage.setItem(e,t):ic.set(e,t)}async setupSocialRecovery(e,t,r,s){if(s>r.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(r.length>255)throw new Error("Cannot have more than 255 guardians");let i=Bn(e),o=Pn(i,s,r.length),c=r.map((u,l)=>({id:crypto.randomUUID(),name:u.name,email:u.email,phone:u.phone,shareEncrypted:Rn(o[l]),status:"pending",addedAt:new Date().toISOString()})),a={threshold:s,totalGuardians:r.length,guardians:c,createdAt:new Date().toISOString(),ethereumAddress:t};return this.setItem(this.storageKey,JSON.stringify(a)),c}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 r=t.guardians.findIndex(a=>a.id===e.id);if(r===-1)throw new Error("Guardian not found");let s={version:1,guardianId:e.id,guardianName:e.name,guardianIndex:r+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),c=this.getGuardianExplainer(e.name,r+1,t.totalGuardians,t.threshold);return{guardianId:e.id,qrCode:o,shareCode:i,explainer:c}}async generateQRCode(e){try{return await(await Promise.resolve().then(()=>K(wr()))).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 r=t.getContext("2d");return r?(r.fillStyle="white",r.fillRect(0,0,512,512),r.fillStyle="black",r.font="bold 20px sans-serif",r.textAlign="center",r.textBaseline="middle",r.fillText("Guardian Recovery Share",256,100),r.font="14px monospace",r.fillText('Install "qrcode" for QR codes',256,480),r.font="10px monospace",this.wrapText(e.substring(0,200)+"...",60).forEach((i,o)=>{r.fillText(i,256,150+o*12)}),t.toDataURL("image/png")):""}wrapText(e,t){let r=[];for(let s=0;s<e.length;s+=t)r.push(e.substring(s,s+t));return r}getGuardianExplainer(e,t,r,s){return`
84
+ `}async restoreFromQR(e,t){let r=JSON.parse(e);if(r.version!==1)throw new Error("Unsupported QR backup version");let s;if(r.type==="encrypted"){if(!t)throw new Error("Password required for encrypted QR backup");let{decryptWithPassword:a}=await Promise.resolve().then(()=>(je(),oa));s=await a(r.data,t,r.salt,r.iv,r.iterations)}else if(r.type==="plain")s=r.data;else throw new Error("Unknown QR backup type");let{Wallet:i}=await import("ethers"),o=i.fromPhrase(s);if(await ee(o.address)!==r.checksum)throw new Error("Address checksum mismatch - corrupted QR or wrong password");return{mnemonic:s,ethereumAddress:o.address}}}});function zh(){let n=new Uint8Array(1);return crypto.getRandomValues(n),n[0]}function In(n,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 r=[];for(let s=0;s<t;s++)r[s]=new Uint8Array(n.length+1),r[s][0]=s+1;for(let s=0;s<n.length;s++){let o=[n[s]];for(let c=1;c<e;c++)o.push(zh());for(let c=0;c<t;c++){let a=c+1,u=Pn.evaluatePolynomial(o,a);r[c][s+1]=u}}return r}function Bn(n,e){if(n.length<e)throw new Error(`Need at least ${e} shares to recover secret, got ${n.length}`);let t=n.slice(0,e),r=t[0].length;for(let o of t)if(o.length!==r)throw new Error("All shares must have the same length");let s=r-1,i=new Uint8Array(s);for(let o=0;o<s;o++){let c=[];for(let a of t)c.push({x:a[0],y:a[o+1]});i[o]=Pn.interpolate(c)}return i}function Dn(n){return new TextEncoder().encode(n)}function Rn(n){return new TextDecoder().decode(n)}function Tn(n){return Array.from(n).map(e=>e.toString(16).padStart(2,"0")).join("")}function Fn(n){let e=new Uint8Array(n.length/2);for(let t=0;t<n.length;t+=2)e[t/2]=parseInt(n.substring(t,t+2),16);return e}var Oe,Pn,Mn=w(()=>{"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 r=0;for(let s=e.length-1;s>=0;s--)r=this.add(this.multiply(r,t),e[s]);return r}static interpolate(e){let t=0;for(let r=0;r<e.length;r++){let s=e[r].y,i=1;for(let o=0;o<e.length;o++)r!==o&&(s=this.multiply(s,e[o].x),i=this.multiply(i,this.add(e[r].x,e[o].x)));t=this.add(t,this.divide(s,i))}return t}};Oe.LOG_TABLE=[],Oe.EXP_TABLE=[],(()=>{let e=(r,s)=>{let i=0;for(let o=0;o<8;o++){s&1&&(i^=r);let c=r&128;r<<=1,c&&(r^=283),s>>=1}return i&255},t=1;for(let r=0;r<255;r++)Oe.EXP_TABLE[r]=t,Oe.LOG_TABLE[t]=r,t=e(t,3);Oe.EXP_TABLE[255]=Oe.EXP_TABLE[0]})();Pn=Oe});var oc,et,ai=w(()=>{"use strict";Mn();oc=new Map,et=class{constructor(){this.storageKey="w3pk_social_recovery"}getItem(e){return typeof localStorage<"u"?localStorage.getItem(e):oc.get(e)||null}setItem(e,t){typeof localStorage<"u"?localStorage.setItem(e,t):oc.set(e,t)}async setupSocialRecovery(e,t,r,s){if(s>r.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(r.length>255)throw new Error("Cannot have more than 255 guardians");let i=Dn(e),o=In(i,s,r.length),c=r.map((u,l)=>({id:crypto.randomUUID(),name:u.name,email:u.email,phone:u.phone,shareEncrypted:Tn(o[l]),status:"pending",addedAt:new Date().toISOString()})),a={threshold:s,totalGuardians:r.length,guardians:c,createdAt:new Date().toISOString(),ethereumAddress:t};return this.setItem(this.storageKey,JSON.stringify(a)),c}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 r=t.guardians.findIndex(a=>a.id===e.id);if(r===-1)throw new Error("Guardian not found");let s={version:1,guardianId:e.id,guardianName:e.name,guardianIndex:r+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),c=this.getGuardianExplainer(e.name,r+1,t.totalGuardians,t.threshold);return{guardianId:e.id,qrCode:o,shareCode:i,explainer:c}}async generateQRCode(e){try{return await(await Promise.resolve().then(()=>z(br()))).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 r=t.getContext("2d");return r?(r.fillStyle="white",r.fillRect(0,0,512,512),r.fillStyle="black",r.font="bold 20px sans-serif",r.textAlign="center",r.textBaseline="middle",r.fillText("Guardian Recovery Share",256,100),r.font="14px monospace",r.fillText('Install "qrcode" for QR codes',256,480),r.font="10px monospace",this.wrapText(e.substring(0,200)+"...",60).forEach((i,o)=>{r.fillText(i,256,150+o*12)}),t.toDataURL("image/png")):""}wrapText(e,t){let r=[];for(let s=0;s<e.length;s+=t)r.push(e.substring(s,s+t));return r}getGuardianExplainer(e,t,r,s){return`
85
85
  \u{1F6E1}\uFE0F GUARDIAN RECOVERY SHARE
86
86
 
87
87
  Dear ${e},
@@ -91,12 +91,13 @@ You have been chosen as Guardian ${t} of ${r}
91
91
  YOUR ROLE:
92
92
  ----------
93
93
 
94
- Your friend has entrusted you with a recovery share for their cryptocurrency wallet.
94
+ Your friend has entrusted you with a recovery share for their encrypted wallet backup.
95
95
 
96
96
  WHAT THIS MEANS:
97
97
  - You hold 1 piece of a ${s}-piece puzzle
98
- - ${s} guardians needed to recover the wallet
98
+ - ${s} guardians needed to reconstruct the backup file
99
99
  - You cannot access the wallet alone
100
+ - The backup is encrypted and requires a password
100
101
  - This is a responsibility and honor
101
102
 
102
103
  HOW IT WORKS:
@@ -107,13 +108,14 @@ If your friend loses access to their wallet:
107
108
  1. They will contact you to request your share
108
109
  2. You provide the QR code or share code below
109
110
  3. System collects shares from ${s} guardians
110
- 4. Wallet is mathematically reconstructed
111
- 5. Your friend regains access \u2713
111
+ 4. Encrypted backup file is mathematically reconstructed
112
+ 5. Your friend decrypts it with their password and regains access \u2713
112
113
 
113
114
  SECURITY:
114
115
  ---------
115
116
 
116
- \u2713 Your share is encrypted
117
+ \u2713 Your share contains encrypted data only
118
+ \u2713 Cannot be decrypted without password
117
119
  \u2713 Cannot be used alone
118
120
  \u2713 ${s-1} other guardians needed
119
121
  \u2713 Safe to store digitally
@@ -147,7 +149,8 @@ If requested:
147
149
  1. Friend will contact you
148
150
  2. Verify their identity
149
151
  3. Provide this QR code or share code
150
- 4. System handles the rest
152
+ 4. System reconstructs encrypted backup file
153
+ 5. Friend decrypts with their password
151
154
 
152
155
  HOW TO STORE:
153
156
  ------------
@@ -169,13 +172,13 @@ Thank you for being a trusted guardian!
169
172
 
170
173
  NEED HELP?
171
174
  Visit: https://docs.w3pk.org/social-recovery
172
- `}async recoverFromGuardians(e){let t=this.getSocialRecoveryConfig();if(!t)throw new Error("Social recovery not configured");if(e.length<t.threshold)throw new Error(`Need at least ${t.threshold} shares, got ${e.length}`);let s=e.map(u=>{let l=JSON.parse(u);return{guardianId:l.guardianId,share:l.share,index:l.guardianIndex}}).map(u=>Tn(u.share)),i=In(s,t.threshold),o=Dn(i),{Wallet:c}=await import("ethers"),a=c.fromPhrase(o);if(a.address.toLowerCase()!==t.ethereumAddress.toLowerCase())throw new Error("Recovered address does not match - invalid shares");return{mnemonic:o,ethereumAddress:a.address}}getRecoveryProgress(e){let t=this.getSocialRecoveryConfig();if(!t)throw new Error("Social recovery not configured");let r=new Set(e.map(s=>{try{return JSON.parse(s).guardianId}catch{return null}}).filter(Boolean));return{collected:r.size,required:t.threshold,guardians:t.guardians.map(s=>({id:s.id,name:s.name,hasProvided:r.has(s.id)})),canRecover:r.size>=t.threshold}}markGuardianVerified(e){let t=this.getSocialRecoveryConfig();if(!t)throw new Error("Social recovery not configured");let r=t.guardians.find(s=>s.id===e);if(!r)throw new Error("Guardian not found");r.status="active",r.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 r=t.guardians.find(s=>s.id===e);if(!r)throw new Error("Guardian not found");r.status="revoked",this.setItem(this.storageKey,JSON.stringify(t))}async addGuardian(e,t){let r=this.getSocialRecoveryConfig();if(!r)throw new Error("Social recovery not configured");let s=[...r.guardians.filter(o=>o.status!=="revoked").map(o=>({name:o.name,email:o.email,phone:o.phone})),t],i=await this.setupSocialRecovery(e,r.ethereumAddress,s,r.threshold);return i[i.length-1]}}});var Mn,ac=w(()=>{"use strict";fn();ii();oc();Mn=class{constructor(){this.verificationStorageKey="w3pk_backup_verifications";this.storage=new Ge,this.qrCreator=new At,this.socialRecoveryManager=new Fn}async getBackupStatus(e){let t=await this.storage.getBackupsByAddress(e),r=await this.detectPasskeySync(),s=t.map(a=>({id:a.id,method:a.method,location:"local",createdAt:a.createdAt,deviceFingerprint:a.deviceFingerprint})),i=this.getSocialRecoveryStatus(),o=this.getVerificationStatus(e);return{passkeySync:r,recoveryPhrase:{verified:o.verified,verificationCount:o.count,encryptedBackups:s},socialRecovery:i,securityScore:this.calculateSecurityScore(r,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 r=await this.checkResidentKeySupport();return{enabled:r,deviceCount:1,lastSyncTime:r?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(r=>r.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,r=t?JSON.parse(t):{},s=e.toLowerCase();r[s]||(r[s]={verified:!1,count:0}),r[s].verified=!0,r[s].count+=1,r[s].lastVerifiedAt=new Date().toISOString(),typeof localStorage<"u"&&localStorage.setItem(this.verificationStorageKey,JSON.stringify(r))}catch(t){console.error("Failed to mark backup as verified:",t)}}calculateSecurityScore(e,t,r,s){let i=0;r?.enabled&&(i=20,r.verifiedGuardians>=r.threshold&&(i+=10));let o=0;s?.verified&&(o=10,o+=Math.min(s.count-1,10));let c={passkeyActive:e.enabled?20:0,passkeyMultiDevice:e.deviceCount>1?10:0,phraseVerified:o,encryptedBackup:t.length>0?20:0,socialRecovery:i},a=Object.values(c).reduce((h,g)=>h+g,0),u,l;return a<=20?(u="vulnerable",l='Create encrypted backup to reach "protected" (40+ pts)'):a<=50?(u="protected",l='Set up social recovery to reach "secured" (70+ pts)'):a<=80?(u="secured",l='Enable all methods to reach "fort-knox" (100 pts)'):(u="fort-knox",l="Maximum security achieved!"),{total:a,breakdown:c,level:u,nextMilestone:l}}async createQRBackup(e,t,r){let{qrCodeDataURL:s,rawData:i,instructions:o}=await this.qrCreator.createQRBackup(e,t,r),c={id:crypto.randomUUID(),ethereumAddress:t,method:"qr",createdAt:new Date().toISOString(),addressChecksum:JSON.parse(i).checksum};return await this.storage.storeBackupMetadata(c),{qrCodeDataURL:s,instructions:o}}async restoreFromQR(e,t){return await this.qrCreator.restoreFromQR(e,t)}async simulateRecoveryScenario(e,t){let r=[];switch(e.type){case"lost-device":t.passkeySync.enabled&&t.passkeySync.deviceCount>1&&r.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&&r.push({method:"Encrypted Backup",success:!0,time:"2 minutes",requirements:["Backup file","Password"]}),t.socialRecovery?.enabled&&r.push({method:"Social Recovery",success:!0,time:"24 hours",requirements:[`${t.socialRecovery.threshold} guardian shares`]});break;case"lost-phrase":t.passkeySync.enabled&&r.push({method:"Passkey (current device)",success:!0,time:"instant",requirements:["Current device","Biometric/PIN"]}),t.socialRecovery?.enabled&&r.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&&r.push({method:"Passkey Sync",success:!0,time:"5 minutes",requirements:["Cloud account access","New device"]}),t.socialRecovery?.enabled&&r.push({method:"Social Recovery",success:!0,time:"24 hours",requirements:[`${t.socialRecovery.threshold} guardian shares`]});break;case"switch-platform":t.recoveryPhrase.encryptedBackups.length>0&&r.push({method:"Encrypted Backup",success:!0,time:"2 minutes",requirements:["Backup file","Password"]}),t.socialRecovery?.enabled&&r.push({method:"Social Recovery",success:!0,time:"24 hours",requirements:[`${t.socialRecovery.threshold} guardian shares`]});break}let s=r.length>0&&r.some(o=>o.success),i="";return s?(i=`\u2705 You're safe! ${r.length} way${r.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]),r=t.threshold,s=t.ethereumAddress;if(!r)throw new Error("Invalid share data: missing threshold information");if(e.length<r)throw new Error(`Need at least ${r} shares, got ${e.length}`);let o=e.map(l=>{let h=JSON.parse(l);if(h.ethereumAddress?.toLowerCase()!==s?.toLowerCase())throw new Error("Shares are from different wallets - cannot combine");return{guardianId:h.guardianId,share:h.share,index:h.guardianIndex}}).map(l=>Fn(l.share)),c=Bn(o,r),a=Rn(c),u;try{u=JSON.parse(a)}catch{throw new Error("Recovered data is not valid JSON - invalid shares")}if(!u.ethereumAddress)throw new Error("Recovered backup file is missing ethereum address");if(s&&u.ethereumAddress.toLowerCase()!==s.toLowerCase())throw new Error("Recovered address does not match share data - invalid shares");return{backupFileJson:a,ethereumAddress:u.ethereumAddress}}getRecoveryProgress(e){let t=this.getSocialRecoveryConfig();if(!t)throw new Error("Social recovery not configured");let r=new Set(e.map(s=>{try{return JSON.parse(s).guardianId}catch{return null}}).filter(Boolean));return{collected:r.size,required:t.threshold,guardians:t.guardians.map(s=>({id:s.id,name:s.name,hasProvided:r.has(s.id)})),canRecover:r.size>=t.threshold}}markGuardianVerified(e){let t=this.getSocialRecoveryConfig();if(!t)throw new Error("Social recovery not configured");let r=t.guardians.find(s=>s.id===e);if(!r)throw new Error("Guardian not found");r.status="active",r.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 r=t.guardians.find(s=>s.id===e);if(!r)throw new Error("Guardian not found");r.status="revoked",this.setItem(this.storageKey,JSON.stringify(t))}async addGuardian(e,t){let r=this.getSocialRecoveryConfig();if(!r)throw new Error("Social recovery not configured");let s=[...r.guardians.filter(o=>o.status!=="revoked").map(o=>({name:o.name,email:o.email,phone:o.phone})),t],i=await this.setupSocialRecovery(e,r.ethereumAddress,s,r.threshold);return i[i.length-1]}}});var Nn,ac=w(()=>{"use strict";pn();oi();ai();Nn=class{constructor(){this.verificationStorageKey="w3pk_backup_verifications";this.storage=new Ge,this.qrCreator=new kt,this.socialRecoveryManager=new et}async getBackupStatus(e){let t=await this.storage.getBackupsByAddress(e),r=await this.detectPasskeySync(),s=t.map(a=>({id:a.id,method:a.method,location:"local",createdAt:a.createdAt,deviceFingerprint:a.deviceFingerprint})),i=this.getSocialRecoveryStatus(),o=this.getVerificationStatus(e);return{passkeySync:r,recoveryPhrase:{verified:o.verified,verificationCount:o.count,encryptedBackups:s},socialRecovery:i,securityScore:this.calculateSecurityScore(r,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 r=await this.checkResidentKeySupport();return{enabled:r,deviceCount:1,lastSyncTime:r?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(r=>r.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,r=t?JSON.parse(t):{},s=e.toLowerCase();r[s]||(r[s]={verified:!1,count:0}),r[s].verified=!0,r[s].count+=1,r[s].lastVerifiedAt=new Date().toISOString(),typeof localStorage<"u"&&localStorage.setItem(this.verificationStorageKey,JSON.stringify(r))}catch(t){console.error("Failed to mark backup as verified:",t)}}calculateSecurityScore(e,t,r,s){let i=0;r?.enabled&&(i=20,r.verifiedGuardians>=r.threshold&&(i+=10));let o=0;s?.verified&&(o=10,o+=Math.min(s.count-1,10));let c={passkeyActive:e.enabled?20:0,passkeyMultiDevice:e.deviceCount>1?10:0,phraseVerified:o,encryptedBackup:t.length>0?20:0,socialRecovery:i},a=Object.values(c).reduce((h,g)=>h+g,0),u,l;return a<=20?(u="vulnerable",l='Create encrypted backup to reach "protected" (40+ pts)'):a<=50?(u="protected",l='Set up social recovery to reach "secured" (70+ pts)'):a<=80?(u="secured",l='Enable all methods to reach "fort-knox" (100 pts)'):(u="fort-knox",l="Maximum security achieved!"),{total:a,breakdown:c,level:u,nextMilestone:l}}async createQRBackup(e,t,r){let{qrCodeDataURL:s,rawData:i,instructions:o}=await this.qrCreator.createQRBackup(e,t,r),c={id:crypto.randomUUID(),ethereumAddress:t,method:"qr",createdAt:new Date().toISOString(),addressChecksum:JSON.parse(i).checksum};return await this.storage.storeBackupMetadata(c),{qrCodeDataURL:s,instructions:o}}async restoreFromQR(e,t){return await this.qrCreator.restoreFromQR(e,t)}async simulateRecoveryScenario(e,t){let r=[];switch(e.type){case"lost-device":t.passkeySync.enabled&&t.passkeySync.deviceCount>1&&r.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&&r.push({method:"Encrypted Backup",success:!0,time:"2 minutes",requirements:["Backup file","Password"]}),t.socialRecovery?.enabled&&r.push({method:"Social Recovery",success:!0,time:"24 hours",requirements:[`${t.socialRecovery.threshold} guardian shares`]});break;case"lost-phrase":t.passkeySync.enabled&&r.push({method:"Passkey (current device)",success:!0,time:"instant",requirements:["Current device","Biometric/PIN"]}),t.socialRecovery?.enabled&&r.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&&r.push({method:"Passkey Sync",success:!0,time:"5 minutes",requirements:["Cloud account access","New device"]}),t.socialRecovery?.enabled&&r.push({method:"Social Recovery",success:!0,time:"24 hours",requirements:[`${t.socialRecovery.threshold} guardian shares`]});break;case"switch-platform":t.recoveryPhrase.encryptedBackups.length>0&&r.push({method:"Encrypted Backup",success:!0,time:"2 minutes",requirements:["Backup file","Password"]}),t.socialRecovery?.enabled&&r.push({method:"Social Recovery",success:!0,time:"24 hours",requirements:[`${t.socialRecovery.threshold} guardian shares`]});break}let s=r.length>0&&r.some(o=>o.success),i="";return s?(i=`\u2705 You're safe! ${r.length} way${r.length>1?"s":""} to recover.
173
176
 
174
177
  `,i+=`Available recovery methods:
175
178
  `,r.forEach(o=>{i+=`- ${o.method} (~${o.time})
176
179
  `})):(i=`\u274C Wallet cannot be recovered in this scenario.
177
180
 
178
- `,i+="Recommendation: Set up at least 2 backup methods to prevent total loss."),{scenario:e,success:s,availableMethods:r,timeEstimate:s?r[0].time:"N/A",educationalNote:i}}}});var ge={};B(ge,{BackupFileManager:()=>br});var br,le=w(()=>{"use strict";je();q();br=class{async createPasswordBackup(e,t,r){if(!r||r.length<1)throw new Error("Password is required for password-based backup");let s=crypto.getRandomValues(new Uint8Array(32)),i=await Ye(e,r,s),o=await ee(t),c={createdAt:new Date().toISOString(),ethereumAddress:t,encryptedMnemonic:i.encrypted,encryptionMethod:"password",passwordEncryption:{salt:i.salt,iv:i.iv,iterations:i.iterations},addressChecksum:o},a=JSON.stringify(c,null,2),u=new Blob([a],{type:"application/json"});return{backupFile:c,json:a,blob:u}}async createPasskeyBackup(e,t,r,s){let i=await j(r,s),o=await ie(e,i),c=await ee(t),u=new TextEncoder().encode(s),l=await crypto.subtle.digest("SHA-256",u),g=Array.from(new Uint8Array(l)).map(k=>k.toString(16).padStart(2,"0")).join("").substring(0,16),d={createdAt:new Date().toISOString(),ethereumAddress:t,encryptedMnemonic:o,encryptionMethod:"passkey",credentialId:r,publicKeyFingerprint:g,addressChecksum:c},f=JSON.stringify(d,null,2),y=new Blob([f],{type:"application/json"});return{backupFile:d,json:f,blob:y}}async createHybridBackup(e,t,r,s,i){let o=await j(s,i),c=await ie(e,o),a=crypto.getRandomValues(new Uint8Array(32)),u=await Ye(c,r,a),l=await ee(t),g=new TextEncoder().encode(i),d=await crypto.subtle.digest("SHA-256",g),y=Array.from(new Uint8Array(d)).map(v=>v.toString(16).padStart(2,"0")).join("").substring(0,16),k={createdAt:new Date().toISOString(),ethereumAddress:t,encryptedMnemonic:u.encrypted,encryptionMethod:"hybrid",credentialId:s,publicKeyFingerprint:y,passwordEncryption:{salt:u.salt,iv:u.iv,iterations:u.iterations},addressChecksum:l},m=JSON.stringify(k,null,2),b=new Blob([m],{type:"application/json"});return{backupFile:k,json:m,blob:b}}async restoreWithExistingPasskey(e,t,r){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 a=await j(t,r);s=await oe(e.encryptedMnemonic,a)}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 ee(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 r;if(e.encryptionMethod==="password")r=await lr(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(r);if(await ee(i.address)!==e.addressChecksum)throw new Error("Address checksum mismatch - corrupted backup or wrong password");return{mnemonic:r,ethereumAddress:e.ethereumAddress}}async restoreWithHybrid(e,t,r,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 lr(e.encryptedMnemonic,t,e.passwordEncryption.salt,e.passwordEncryption.iv,e.passwordEncryption.iterations),o=await j(r,s),c=await oe(i,o),{Wallet:a}=await import("ethers"),u=a.fromPhrase(c);if(await ee(u.address)!==e.addressChecksum)throw new Error("Address checksum mismatch - corrupted backup or decryption failure");return{mnemonic:c,ethereumAddress:e.ethereumAddress}}async parseBackupFile(e){let t;e instanceof Blob?t=await e.text():t=e;let r=JSON.parse(t);if(!r.createdAt||!r.ethereumAddress||!r.encryptedMnemonic)throw new Error("Invalid backup file: missing required fields");return r}createDownloadableBackup(e,t){let r=JSON.stringify(e,null,2),s=new Blob([r],{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 cc=w(()=>{"use strict"});var et={};B(et,{BackupFileManager:()=>br,BackupManager:()=>Mn,BackupStorage:()=>Ge,QRBackupCreator:()=>At,decryptWithPassword:()=>lr,deriveAddressChecksum:()=>ee,deriveKeyFromPassword:()=>pn,encryptWithPassword:()=>Ye,getDeviceFingerprint:()=>Ae,validatePasswordStrength:()=>sa});var tt=w(()=>{"use strict";ac();fn();ii();le();cc();je()});var Nn={};B(Nn,{SocialRecovery:()=>ai});var ai,Un=w(()=>{"use strict";oi();ai=class{async splitAmongGuardians(e,t,r){if(r>t.length)throw new Error("Threshold cannot exceed number of guardians");if(r<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,r,t.length),c=t.map((a,u)=>({guardianId:crypto.randomUUID(),guardianName:a.name,shareData:Rn(o[u]),shareIndex:u+1,createdAt:new Date().toISOString(),walletAddress:e.ethereumAddress}));return{threshold:r,totalShares:t.length,guardianShares:c,backupFile:e,setupDate:new Date().toISOString()}}async recoverFromShares(e){if(e.length<2)throw new Error("At least 2 shares required for recovery");let t=e[0].walletAddress;if(!e.every(a=>a.walletAddress===t))throw new Error("Shares are from different wallets - cannot combine");let s=e.map(a=>Tn(a.shareData)),i=In(s,e.length),o=Dn(i),c=JSON.parse(o);if(c.ethereumAddress!==t)throw new Error("Recovered backup address mismatch - corrupted shares");return c}async createGuardianInvitation(e,t){let r={type:"w3pk-guardian-share",version:1,guardianName:e.guardianName,walletAddress:e.walletAddress,shareData:e.shareData,shareIndex:e.shareIndex,createdAt:e.createdAt,message:t||`You have been chosen as a recovery guardian for wallet ${e.walletAddress.substring(0,10)}...`},s=JSON.stringify(r,null,2),i;try{i=await(await Promise.resolve().then(()=>K(wr()))).toDataURL(s,{errorCorrectionLevel:"H",width:512})}catch(c){console.warn("QR code generation not available:",c)}let o=`
181
+ `,i+="Recommendation: Set up at least 2 backup methods to prevent total loss."),{scenario:e,success:s,availableMethods:r,timeEstimate:s?r[0].time:"N/A",educationalNote:i}}}});var ge={};B(ge,{BackupFileManager:()=>Sr});var Sr,le=w(()=>{"use strict";je();q();Sr=class{async createPasswordBackup(e,t,r){if(!r||r.length<1)throw new Error("Password is required for password-based backup");let s=crypto.getRandomValues(new Uint8Array(32)),i=await Ye(e,r,s),o=await ee(t),c={createdAt:new Date().toISOString(),ethereumAddress:t,encryptedMnemonic:i.encrypted,encryptionMethod:"password",passwordEncryption:{salt:i.salt,iv:i.iv,iterations:i.iterations},addressChecksum:o},a=JSON.stringify(c,null,2),u=new Blob([a],{type:"application/json"});return{backupFile:c,json:a,blob:u}}async createPasskeyBackup(e,t,r,s){let i=await j(r,s),o=await ie(e,i),c=await ee(t),u=new TextEncoder().encode(s),l=await crypto.subtle.digest("SHA-256",u),g=Array.from(new Uint8Array(l)).map(k=>k.toString(16).padStart(2,"0")).join("").substring(0,16),d={createdAt:new Date().toISOString(),ethereumAddress:t,encryptedMnemonic:o,encryptionMethod:"passkey",credentialId:r,publicKeyFingerprint:g,addressChecksum:c},f=JSON.stringify(d,null,2),y=new Blob([f],{type:"application/json"});return{backupFile:d,json:f,blob:y}}async createHybridBackup(e,t,r,s,i){let o=await j(s,i),c=await ie(e,o),a=crypto.getRandomValues(new Uint8Array(32)),u=await Ye(c,r,a),l=await ee(t),g=new TextEncoder().encode(i),d=await crypto.subtle.digest("SHA-256",g),y=Array.from(new Uint8Array(d)).map(v=>v.toString(16).padStart(2,"0")).join("").substring(0,16),k={createdAt:new Date().toISOString(),ethereumAddress:t,encryptedMnemonic:u.encrypted,encryptionMethod:"hybrid",credentialId:s,publicKeyFingerprint:y,passwordEncryption:{salt:u.salt,iv:u.iv,iterations:u.iterations},addressChecksum:l},m=JSON.stringify(k,null,2),b=new Blob([m],{type:"application/json"});return{backupFile:k,json:m,blob:b}}async restoreWithExistingPasskey(e,t,r){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 a=await j(t,r);s=await oe(e.encryptedMnemonic,a)}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 ee(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 r;if(e.encryptionMethod==="password")r=await ur(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(r);if(await ee(i.address)!==e.addressChecksum)throw new Error("Address checksum mismatch - corrupted backup or wrong password");return{mnemonic:r,ethereumAddress:e.ethereumAddress}}async restoreWithHybrid(e,t,r,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 ur(e.encryptedMnemonic,t,e.passwordEncryption.salt,e.passwordEncryption.iv,e.passwordEncryption.iterations),o=await j(r,s),c=await oe(i,o),{Wallet:a}=await import("ethers"),u=a.fromPhrase(c);if(await ee(u.address)!==e.addressChecksum)throw new Error("Address checksum mismatch - corrupted backup or decryption failure");return{mnemonic:c,ethereumAddress:e.ethereumAddress}}async parseBackupFile(e){let t;e instanceof Blob?t=await e.text():t=e;let r=JSON.parse(t);if(!r.createdAt||!r.ethereumAddress||!r.encryptedMnemonic)throw new Error("Invalid backup file: missing required fields");return r}createDownloadableBackup(e,t){let r=JSON.stringify(e,null,2),s=new Blob([r],{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 cc=w(()=>{"use strict"});var tt={};B(tt,{BackupFileManager:()=>Sr,BackupManager:()=>Nn,BackupStorage:()=>Ge,QRBackupCreator:()=>kt,decryptWithPassword:()=>ur,deriveAddressChecksum:()=>ee,deriveKeyFromPassword:()=>gn,encryptWithPassword:()=>Ye,getDeviceFingerprint:()=>Ae,validatePasswordStrength:()=>ia});var rt=w(()=>{"use strict";ac();pn();oi();le();cc();je()});var Un={};B(Un,{SocialRecovery:()=>ci});var ci,Ln=w(()=>{"use strict";Mn();ci=class{async splitAmongGuardians(e,t,r){if(r>t.length)throw new Error("Threshold cannot exceed number of guardians");if(r<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=Dn(s),o=In(i,r,t.length),c=t.map((a,u)=>({guardianId:crypto.randomUUID(),guardianName:a.name,shareData:Tn(o[u]),shareIndex:u+1,createdAt:new Date().toISOString(),walletAddress:e.ethereumAddress}));return{threshold:r,totalShares:t.length,guardianShares:c,backupFile:e,setupDate:new Date().toISOString()}}async recoverFromShares(e){if(e.length<2)throw new Error("At least 2 shares required for recovery");let t=e[0].walletAddress;if(!e.every(a=>a.walletAddress===t))throw new Error("Shares are from different wallets - cannot combine");let s=e.map(a=>Fn(a.shareData)),i=Bn(s,e.length),o=Rn(i),c=JSON.parse(o);if(c.ethereumAddress!==t)throw new Error("Recovered backup address mismatch - corrupted shares");return c}async createGuardianInvitation(e,t){let r={type:"w3pk-guardian-share",version:1,guardianName:e.guardianName,walletAddress:e.walletAddress,shareData:e.shareData,shareIndex:e.shareIndex,createdAt:e.createdAt,message:t||`You have been chosen as a recovery guardian for wallet ${e.walletAddress.substring(0,10)}...`},s=JSON.stringify(r,null,2),i;try{i=await(await Promise.resolve().then(()=>z(br()))).toDataURL(s,{errorCorrectionLevel:"H",width:512})}catch(c){console.warn("QR code generation not available:",c)}let o=`
179
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
180
183
  W3PK GUARDIAN RECOVERY SHARE
181
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
@@ -217,7 +220,7 @@ ${e.shareData}
217
220
  Generated by w3pk - Web3 Passkey SDK
218
221
  https://github.com/w3hc/w3pk
219
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
220
- `;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");return{guardianId:crypto.randomUUID(),guardianName:t.guardianName,shareData:t.shareData,shareIndex:t.shareIndex,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,createdAt:e.createdAt},null,2),r=new Blob([t],{type:"application/json"}),s=`w3pk-guardian-${e.guardianName.replace(/\s+/g,"-")}-share-${e.shareIndex}.json`;return{blob:r,filename:s}}}});var lc={};B(lc,{authenticateWithPasskey:()=>li,promptPasskeySelection:()=>ci});async function ci(){try{let n=new F,e=De(),t=L(e),r=[];try{let a=await n.getAllCredentials();a.length>0&&(r=a.map(u=>({id:u.id,type:"public-key",transports:["internal","hybrid","usb","nfc","ble"]})))}catch{}let s={challenge:t,rpId:window.location.hostname,userVerification:"required",timeout:12e4};r.length>0&&(s.allowCredentials=r.map(a=>({id:L(a.id),type:a.type,transports:a.transports})));let i=await navigator.credentials.get({publicKey:s});if(!i)throw new O("No passkey selected. Please select a passkey to continue with sync.");let o=i.id,c=await n.getCredentialById(o);return c?{credentialId:o,publicKey:c.publicKey,ethereumAddress:c.ethereumAddress}:{credentialId:o,publicKey:"",ethereumAddress:void 0}}catch(n){throw n?.name==="NotAllowedError"?new O("Passkey selection was cancelled. Please try again and select your passkey."):n instanceof O?n:new O(`Failed to select passkey: ${n instanceof Error?n.message:"Unknown error"}`,n)}}async function li(n){try{let e=De(),r={challenge:L(e),rpId:window.location.hostname,userVerification:"required",timeout:6e4,allowCredentials:[{id:L(n),type:"public-key",transports:["internal","hybrid","usb","nfc","ble"]}]},s=await navigator.credentials.get({publicKey:r});if(!s)throw new O("Authentication failed - no credential returned");return s}catch(e){throw e?.name==="NotAllowedError"?new O("Authentication was cancelled or the passkey is not available on this device."):new O(`Passkey authentication failed: ${e instanceof Error?e.message:"Unknown error"}`,e)}}var ui=w(()=>{"use strict";Y();Te();xe();q()});var Ln={};B(Ln,{DeviceSyncManager:()=>Sr});var Sr,xr=w(()=>{"use strict";Sr=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(),r=this.detectPlatform(),s={deviceName:t?.deviceName||this.generateDeviceName(),platform:r,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,r,s){let{BackupFileManager:i}=await Promise.resolve().then(()=>(le(),ge));return new i().createPasskeyBackup(e,t,r,s)}async importFromSync(e,t,r){let{BackupFileManager:s}=await Promise.resolve().then(()=>(le(),ge)),o=await new s().restoreWithExistingPasskey(e,t,r);return await this.updateSyncInfo(o.ethereumAddress),o}async canSyncBackup(e,t){return e.encryptionMethod!=="passkey"?!0:e.publicKeyFingerprint?t.some(r=>r.publicKeyFingerprint===e.publicKeyFingerprint):!1}async generateSyncQR(e){try{let t=await Promise.resolve().then(()=>K(wr())),r=JSON.stringify(e);if(r.length>2953)throw new Error("Backup file too large for QR code. Use file transfer instead.");return t.toDataURL(r,{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(()=>(le(),ge));return new t().parseBackupFile(e)}}});var _n,uc=w(()=>{"use strict";je();_n=class{async createSyncPackage(e,t,r){let s=await Ae(),{deriveEncryptionKeyFromWebAuthn:i,encryptData:o}=await Promise.resolve().then(()=>(q(),Re)),c=await i(t,r),a=await o(e,c),u=this.detectSyncMethod();return{id:crypto.randomUUID(),encryptedData:a,deviceFingerprints:[s],syncMethod:u,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,r){let{deriveEncryptionKeyFromWebAuthn:s,decryptData:i}=await Promise.resolve().then(()=>(q(),Re)),o=await s(t,r),c=await i(e.encryptedData,o),a=await Ae();return e.deviceFingerprints.includes(a)||(e.deviceFingerprints.push(a),e.updatedAt=new Date().toISOString()),c}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");return{guardianId:crypto.randomUUID(),guardianName:t.guardianName,shareData:t.shareData,shareIndex:t.shareIndex,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,createdAt:e.createdAt},null,2),r=new Blob([t],{type:"application/json"}),s=`w3pk-guardian-${e.guardianName.replace(/\s+/g,"-")}-share-${e.shareIndex}.json`;return{blob:r,filename:s}}}});var lc={};B(lc,{authenticateWithPasskey:()=>ui,promptPasskeySelection:()=>li});async function li(){try{let n=new F,e=De(),t=L(e),r=[];try{let a=await n.getAllCredentials();a.length>0&&(r=a.map(u=>({id:u.id,type:"public-key",transports:["internal","hybrid","usb","nfc","ble"]})))}catch{}let s={challenge:t,rpId:window.location.hostname,userVerification:"required",timeout:12e4};r.length>0&&(s.allowCredentials=r.map(a=>({id:L(a.id),type:a.type,transports:a.transports})));let i=await navigator.credentials.get({publicKey:s});if(!i)throw new O("No passkey selected. Please select a passkey to continue with sync.");let o=i.id,c=await n.getCredentialById(o);return c?{credentialId:o,publicKey:c.publicKey,ethereumAddress:c.ethereumAddress}:{credentialId:o,publicKey:"",ethereumAddress:void 0}}catch(n){throw n?.name==="NotAllowedError"?new O("Passkey selection was cancelled. Please try again and select your passkey."):n instanceof O?n:new O(`Failed to select passkey: ${n instanceof Error?n.message:"Unknown error"}`,n)}}async function ui(n){try{let e=De(),r={challenge:L(e),rpId:window.location.hostname,userVerification:"required",timeout:6e4,allowCredentials:[{id:L(n),type:"public-key",transports:["internal","hybrid","usb","nfc","ble"]}]},s=await navigator.credentials.get({publicKey:r});if(!s)throw new O("Authentication failed - no credential returned");return s}catch(e){throw e?.name==="NotAllowedError"?new O("Authentication was cancelled or the passkey is not available on this device."):new O(`Passkey authentication failed: ${e instanceof Error?e.message:"Unknown error"}`,e)}}var di=w(()=>{"use strict";Y();Te();xe();q()});var _n={};B(_n,{DeviceSyncManager:()=>xr});var xr,vr=w(()=>{"use strict";xr=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(),r=this.detectPlatform(),s={deviceName:t?.deviceName||this.generateDeviceName(),platform:r,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,r,s){let{BackupFileManager:i}=await Promise.resolve().then(()=>(le(),ge));return new i().createPasskeyBackup(e,t,r,s)}async importFromSync(e,t,r){let{BackupFileManager:s}=await Promise.resolve().then(()=>(le(),ge)),o=await new s().restoreWithExistingPasskey(e,t,r);return await this.updateSyncInfo(o.ethereumAddress),o}async canSyncBackup(e,t){return e.encryptionMethod!=="passkey"?!0:e.publicKeyFingerprint?t.some(r=>r.publicKeyFingerprint===e.publicKeyFingerprint):!1}async generateSyncQR(e){try{let t=await Promise.resolve().then(()=>z(br())),r=JSON.stringify(e);if(r.length>2953)throw new Error("Backup file too large for QR code. Use file transfer instead.");return t.toDataURL(r,{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(()=>(le(),ge));return new t().parseBackupFile(e)}}});var On,uc=w(()=>{"use strict";je();On=class{async createSyncPackage(e,t,r){let s=await Ae(),{deriveEncryptionKeyFromWebAuthn:i,encryptData:o}=await Promise.resolve().then(()=>(q(),Re)),c=await i(t,r),a=await o(e,c),u=this.detectSyncMethod();return{id:crypto.randomUUID(),encryptedData:a,deviceFingerprints:[s],syncMethod:u,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,r){let{deriveEncryptionKeyFromWebAuthn:s,decryptData:i}=await Promise.resolve().then(()=>(q(),Re)),o=await s(t,r),c=await i(e.encryptedData,o),a=await Ae();return e.deviceFingerprints.includes(a)||(e.deviceFingerprints.push(a),e.updatedAt=new Date().toISOString()),c}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`
221
224
  HOW CROSS-DEVICE SYNC WORKS
222
225
  ===========================
223
226
 
@@ -298,14 +301,14 @@ If passkey doesn't sync:
298
301
  Think of it like:
299
302
  \u{1F511} Passkey = Your car key (syncs via keychain)
300
303
  \u{1F697} Wallet = Your car (locked, needs key to start)
301
- `}}});var On,dc=w(()=>{"use strict";je();On=class{constructor(){this.storageKey="w3pk_devices"}async registerDevice(){let e={id:await Ae(),name:this.getDeviceName(),platform:this.detectPlatform(),lastActive:new Date().toISOString(),trusted:!0,canRevoke:!1},t=await this.getDevices(),r=t.find(s=>s.id===e.id);return r?(r.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 Ae();e.forEach(i=>{i.canRevoke=i.id!==t}),e.sort((i,o)=>new Date(o.lastActive).getTime()-new Date(i.lastActive).getTime());let r=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(r)}}async revokeDevice(e){let t=await this.getDevices(),r=await Ae();if(e===r)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 Ae(),r=e.find(s=>s.id===t);r&&(r.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 r=t.match(/Android.*;\s([^)]+)\)/);return r?r[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 Kn,dc=w(()=>{"use strict";je();Kn=class{constructor(){this.storageKey="w3pk_devices"}async registerDevice(){let e={id:await Ae(),name:this.getDeviceName(),platform:this.detectPlatform(),lastActive:new Date().toISOString(),trusted:!0,canRevoke:!1},t=await this.getDevices(),r=t.find(s=>s.id===e.id);return r?(r.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 Ae();e.forEach(i=>{i.canRevoke=i.id!==t}),e.sort((i,o)=>new Date(o.lastActive).getTime()-new Date(i.lastActive).getTime());let r=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(r)}}async revokeDevice(e){let t=await this.getDevices(),r=await Ae();if(e===r)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 Ae(),r=e.find(s=>s.id===t);r&&(r.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 r=t.match(/Android.*;\s([^)]+)\)/);return r?r[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}):
302
305
 
303
306
  `;return e.devices.forEach((r,s)=>{let i=Date.now()-new Date(r.lastActive).getTime(),o=this.formatTimeDiff(i);t+=`${s+1}. ${r.name}
304
307
  `,t+=` Platform: ${this.getPlatformName(r.platform)}
305
308
  `,t+=` Last active: ${o}
306
309
  `,t+=` ${r.canRevoke?"":"(Current device)"}
307
310
 
308
- `}),t}formatTimeDiff(e){let t=Math.floor(e/1e3),r=Math.floor(t/60),s=Math.floor(r/60),i=Math.floor(s/24);return i>0?`${i} day${i>1?"s":""} ago`:s>0?`${s} hour${s>1?"s":""} ago`:r>0?`${r} minute${r>1?"s":""} ago`:"just now"}}});var Kn,hc=w(()=>{"use strict";Kn=class{async detectSyncCapabilities(){let e=this.detectPlatform(),t=await this.checkPasskeySync(),r=this.estimateDeviceCount();return{passkeysSync:t,platform:e,estimatedDevices:r,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),r=Math.floor(t/60),s=Math.floor(r/60),i=Math.floor(s/24);return i>0?`${i} day${i>1?"s":""} ago`:s>0?`${s} hour${s>1?"s":""} ago`:r>0?`${r} minute${r>1?"s":""} ago`:"just now"}}});var zn,hc=w(()=>{"use strict";zn=class{async detectSyncCapabilities(){let e=this.detectPlatform(),t=await this.checkPasskeySync(),r=this.estimateDeviceCount();return{passkeysSync:t,platform:e,estimatedDevices:r,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`
309
312
  \u{1F34E} Apple iCloud Keychain
310
313
 
311
314
  Your passkey automatically syncs across:
@@ -384,7 +387,7 @@ This ensures you can recover if:
384
387
  - Device is lost/stolen
385
388
  - Device is damaged
386
389
  - You switch devices
387
- `}}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 fc=w(()=>{"use strict"});var pc={};B(pc,{DeviceManager:()=>On,DeviceSyncManager:()=>Sr,PlatformDetector:()=>Kn,VaultSync:()=>_n});var gc=w(()=>{"use strict";uc();dc();hc();xr();fc()});var kt,mc=w(()=>{"use strict";kt=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 r=[];switch(e.type){case"lost-device":t.passkeySync.enabled&&t.passkeySync.deviceCount>1&&r.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=>{r.push({method:`Encrypted ${o.method.toUpperCase()} Backup`,success:!0,time:"2 minutes",requirements:["Backup file/QR code","Backup password"]})}),t.socialRecovery?.enabled&&r.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&&r.push({method:"Passkey (current device)",success:!0,time:"Instant",requirements:["Access to current device","Biometric/PIN authentication"]}),t.passkeySync.deviceCount>1&&r.push({method:"Passkey Sync",success:!0,time:"5 minutes",requirements:["Any synced device","Biometric authentication"]}),t.recoveryPhrase.encryptedBackups.length>0&&r.push({method:"Encrypted Backup",success:!0,time:"2 minutes",requirements:["Backup file","Password"]}),t.socialRecovery?.enabled&&r.push({method:"Social Recovery",success:!0,time:"24 hours",requirements:[`${t.socialRecovery.threshold} guardian shares`]});break;case"lost-both":t.passkeySync.deviceCount>1&&r.push({method:"Passkey Sync",success:!0,time:"5 minutes",requirements:["Cloud account access","New device","Biometric setup"]}),t.socialRecovery?.enabled&&r.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&&r.push({method:"Encrypted Backup",success:!0,time:"2 minutes",requirements:["Backup file","Password"]}),t.socialRecovery?.enabled&&r.push({method:"Social Recovery",success:!0,time:"24 hours",requirements:[`${t.socialRecovery.threshold} guardian shares`]});break}let s=r.length>0,i=this.getEducationalNote(e,r,t);return{scenario:e,success:s,availableMethods:r,timeEstimate:s?this.estimateFastestRecovery(r):"Cannot recover",educationalNote:i}}estimateFastestRecovery(e){let t=e.map(r=>r.time.toLowerCase());if(t.some(r=>r.includes("instant")))return"Instant";if(t.some(r=>r.includes("minute"))){let r=t.filter(s=>s.includes("minute")).map(s=>parseInt(s));return`${Math.min(...r)} minutes`}return t.some(r=>r.includes("hour"))?"24 hours":"Unknown"}getEducationalNote(e,t,r){let s=r.securityScore.total,i=r.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 fc=w(()=>{"use strict"});var pc={};B(pc,{DeviceManager:()=>Kn,DeviceSyncManager:()=>xr,PlatformDetector:()=>zn,VaultSync:()=>On});var gc=w(()=>{"use strict";uc();dc();hc();vr();fc()});var Et,mc=w(()=>{"use strict";Et=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 r=[];switch(e.type){case"lost-device":t.passkeySync.enabled&&t.passkeySync.deviceCount>1&&r.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=>{r.push({method:`Encrypted ${o.method.toUpperCase()} Backup`,success:!0,time:"2 minutes",requirements:["Backup file/QR code","Backup password"]})}),t.socialRecovery?.enabled&&r.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&&r.push({method:"Passkey (current device)",success:!0,time:"Instant",requirements:["Access to current device","Biometric/PIN authentication"]}),t.passkeySync.deviceCount>1&&r.push({method:"Passkey Sync",success:!0,time:"5 minutes",requirements:["Any synced device","Biometric authentication"]}),t.recoveryPhrase.encryptedBackups.length>0&&r.push({method:"Encrypted Backup",success:!0,time:"2 minutes",requirements:["Backup file","Password"]}),t.socialRecovery?.enabled&&r.push({method:"Social Recovery",success:!0,time:"24 hours",requirements:[`${t.socialRecovery.threshold} guardian shares`]});break;case"lost-both":t.passkeySync.deviceCount>1&&r.push({method:"Passkey Sync",success:!0,time:"5 minutes",requirements:["Cloud account access","New device","Biometric setup"]}),t.socialRecovery?.enabled&&r.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&&r.push({method:"Encrypted Backup",success:!0,time:"2 minutes",requirements:["Backup file","Password"]}),t.socialRecovery?.enabled&&r.push({method:"Social Recovery",success:!0,time:"24 hours",requirements:[`${t.socialRecovery.threshold} guardian shares`]});break}let s=r.length>0,i=this.getEducationalNote(e,r,t);return{scenario:e,success:s,availableMethods:r,timeEstimate:s?this.estimateFastestRecovery(r):"Cannot recover",educationalNote:i}}estimateFastestRecovery(e){let t=e.map(r=>r.time.toLowerCase());if(t.some(r=>r.includes("instant")))return"Instant";if(t.some(r=>r.includes("minute"))){let r=t.filter(s=>s.includes("minute")).map(s=>parseInt(s));return`${Math.min(...r)} minutes`}return t.some(r=>r.includes("hour"))?"24 hours":"Unknown"}getEducationalNote(e,t,r){let s=r.securityScore.total,i=r.securityScore.level;if(t.length===0)return`
388
391
  \u274C WALLET CANNOT BE RECOVERED
389
392
 
390
393
  Scenario: ${e.description}
@@ -500,7 +503,7 @@ SECURITY SCORE: ${o}/100 (${c})
500
503
  `,a+=` 3. Set up social recovery (+20-30 pts)
501
504
 
502
505
  `,a+=`Target: Reach at least 50/100 for basic protection.
503
- `),{scenarios:r,overallScore:i,securityScore:o,feedback:a}}}});function di(n){return zn[n]||null}function hi(){return Object.keys(zn)}function fi(n){let e=n.toLowerCase();return Object.values(zn).filter(t=>t.title.toLowerCase().includes(e)||t.content.toLowerCase().includes(e))}var zn,yc=w(()=>{"use strict";zn={whatIsPasskey:{title:"What is a Passkey?",content:`
506
+ `),{scenarios:r,overallScore:i,securityScore:o,feedback:a}}}});function hi(n){return Wn[n]||null}function fi(){return Object.keys(Wn)}function pi(n){let e=n.toLowerCase();return Object.values(Wn).filter(t=>t.title.toLowerCase().includes(e)||t.content.toLowerCase().includes(e))}var Wn,yc=w(()=>{"use strict";Wn={whatIsPasskey:{title:"What is a Passkey?",content:`
504
507
  Think of a passkey like your house smart lock:
505
508
 
506
509
  \u{1F511} Traditional Key (Password):
@@ -944,7 +947,7 @@ Good: 70 pts (backup + social recovery)
944
947
  Excellent: 80+ pts (all layers enabled)
945
948
 
946
949
  Remember: Higher score = Lower chance of loss!
947
- `}}});var Wn={};B(Wn,{RecoverySimulator:()=>kt,educationalModules:()=>zn,getAllTopics:()=>hi,getExplainer:()=>di,searchExplainers:()=>fi});var vr=w(()=>{"use strict";mc();yc()});function Wh(n){return n[Symbol.asyncIterator]!=null}function $h(n){if(Wh(n))return(async()=>{for await(let e of n)return e})();for(let e of n)return e}var pi,Sc=w(()=>{"use strict";pi=$h});function qh(n){return n[Symbol.asyncIterator]!=null}function Hh(n,e=1){return e=Number(e),qh(n)?(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 r of n)for(t.push(r);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 r of n)for(t.push(r);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 $n,gi=w(()=>{"use strict";$n=Hh});async function*Ar(n,e=1){for await(let t of $n(n,e)){let r=t.map(async s=>s().then(i=>({ok:!0,value:i}),i=>({ok:!1,err:i})));for(let s=0;s<r.length;s++){let i=await r[s];if(i.ok)yield i.value;else throw i.err}}}var mi=w(()=>{"use strict";gi()});function Pe(n=0){return new Uint8Array(n)}function te(n=0){return new Uint8Array(n)}var rt=w(()=>{"use strict"});var xc=w(()=>{"use strict"});function kr(n,e){e==null&&(e=n.reduce((s,i)=>s+i.length,0));let t=te(e),r=0;for(let s of n)t.set(s,r),r+=s.length;return t}var yi=w(()=>{"use strict";rt();xc()});function vc(n,e){if(n===e)return!0;if(n.byteLength!==e.byteLength)return!1;for(let t=0;t<n.byteLength;t++)if(n[t]!==e[t])return!1;return!0}var Ac=w(()=>{"use strict"});function kc(n,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let r of n){let s=t+r.byteLength;if(e<s)return{buf:r,index:e-t};t=s}throw new RangeError("index is out of bounds")}function qn(n){return!!n?.[Cc]}var Cc,Ec,Ct,Pc=w(()=>{"use strict";rt();yi();Ac();Cc=Symbol.for("@achingbrain/uint8arraylist");Ct=class n{constructor(...e){p(this,"bufs");p(this,"length");p(this,Ec,!0);this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[(Ec=Cc,Symbol.iterator)](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else if(qn(r))t+=r.byteLength,this.bufs.push(...r.bufs);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 r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else if(qn(r))t+=r.byteLength,this.bufs.unshift(...r.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=kc(this.bufs,e);return t.buf[t.index]}set(e,t){let r=kc(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r<e.length;r++)this.set(t+r,e[r]);else if(qn(e))for(let r=0;r<e.length;r++)this.set(t+r,e.get(r));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:r,length:s}=this._subList(e,t);return kr(r,s)}subarray(e,t){let{bufs:r,length:s}=this._subList(e,t);return r.length===1?r[0]:kr(r,s)}sublist(e,t){let{bufs:r,length:s}=this._subList(e,t),i=new n;return i.length=s,i.bufs=[...r],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 r=[],s=0;for(let i=0;i<this.bufs.length;i++){let o=this.bufs[i],c=s,a=c+o.byteLength;if(s=a,e>=a)continue;let u=e>=c&&e<a,l=t>c&&t<=a;if(u&&l){if(e===c&&t===a){r.push(o);break}let h=e-c;r.push(o.subarray(h,h+(t-e)));break}if(u){if(e===0){r.push(o);continue}r.push(o.subarray(e-c));continue}if(l){if(t===a){r.push(o);break}r.push(o.subarray(0,t-c));break}r.push(o)}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!qn(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let r=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=r.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let i=256,o=new Int32Array(i);for(let h=0;h<i;h++)o[h]=-1;for(let h=0;h<s;h++)o[r[h]]=h;let c=o,a=this.byteLength-r.byteLength,u=r.byteLength-1,l;for(let h=t;h<=a;h+=l){l=0;for(let g=u;g>=0;g--){let d=this.get(h+g);if(r[g]!==d){l=Math.max(1,g-c[d]);break}}if(l===0)return h}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 r=te(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){let r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){let s=Pe(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,r),this.write(s,e)}getInt32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){let s=Pe(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,r),this.write(s,e)}getBigInt64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){let s=Pe(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,r),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 r=te(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){let r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){let s=Pe(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,r),this.write(s,e)}getUint32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){let s=Pe(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,r),this.write(s,e)}getBigUint64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){let s=Pe(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,r),this.write(s,e)}getFloat32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){let s=Pe(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,r),this.write(s,e)}getFloat64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){let s=Pe(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,r),this.write(s,e)}equals(e){if(e==null||!(e instanceof n)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!vc(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let r=new n;return r.bufs=e,t==null&&(t=e.reduce((s,i)=>s+i.byteLength,0)),r.length=t,r}}});var Vh,Ic,Bc=w(()=>{"use strict";Pc();Vh=262144,Ic=(n={})=>{let e=n.chunkSize??Vh;return async function*(r){let s=new Ct,i=0,o=!1;for await(let c of r)for(s.append(c),i+=c.length;i>=e;)if(yield s.slice(0,e),o=!0,e===s.length)s=new Ct,i=0;else{let a=new Ct;a.append(s.sublist(e)),s=a,i-=e}(!o||i>0)&&(yield s.subarray(0,i))}}});var Pt={};B(Pt,{coerce:()=>ue,empty:()=>Dc,equals:()=>wi,fromHex:()=>Yh,fromString:()=>bi,isBinary:()=>jh,toHex:()=>Gh,toString:()=>Si});function Gh(n){return n.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"")}function Yh(n){let e=n.match(/../g);return e!=null?new Uint8Array(e.map(t=>parseInt(t,16))):Dc}function wi(n,e){if(n===e)return!0;if(n.byteLength!==e.byteLength)return!1;for(let t=0;t<n.byteLength;t++)if(n[t]!==e[t])return!1;return!0}function ue(n){if(n instanceof Uint8Array&&n.constructor.name==="Uint8Array")return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);if(ArrayBuffer.isView(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength);throw new Error("Unknown type, must be binary type")}function jh(n){return n instanceof ArrayBuffer||ArrayBuffer.isView(n)}function bi(n){return new TextEncoder().encode(n)}function Si(n){return new TextDecoder().decode(n)}var Dc,Ke=w(()=>{"use strict";Dc=new Uint8Array(0)});function Jh(n,e){if(n.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var s=0;s<n.length;s++){var i=n.charAt(s),o=i.charCodeAt(0);if(t[o]!==255)throw new TypeError(i+" is ambiguous");t[o]=s}var c=n.length,a=n.charAt(0),u=Math.log(c)/Math.log(256),l=Math.log(256)/Math.log(c);function h(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var y=0,k=0,m=0,b=f.length;m!==b&&f[m]===0;)m++,y++;for(var v=(b-m)*l+1>>>0,A=new Uint8Array(v);m!==b;){for(var E=f[m],C=0,x=v-1;(E!==0||C<k)&&x!==-1;x--,C++)E+=256*A[x]>>>0,A[x]=E%c>>>0,E=E/c>>>0;if(E!==0)throw new Error("Non-zero carry");k=C,m++}for(var P=v-k;P!==v&&A[P]===0;)P++;for(var G=a.repeat(y);P<v;++P)G+=n.charAt(A[P]);return G}function g(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var y=0;if(f[y]!==" "){for(var k=0,m=0;f[y]===a;)k++,y++;for(var b=(f.length-y)*u+1>>>0,v=new Uint8Array(b);f[y];){var A=t[f.charCodeAt(y)];if(A===255)return;for(var E=0,C=b-1;(A!==0||E<m)&&C!==-1;C--,E++)A+=c*v[C]>>>0,v[C]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");m=E,y++}if(f[y]!==" "){for(var x=b-m;x!==b&&v[x]===0;)x++;for(var P=new Uint8Array(k+(b-x)),G=k;x!==b;)P[G++]=v[x++];return P}}}function d(f){var y=g(f);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:g,decode:d}}var Qh,Xh,Rc,Tc=w(()=>{"use strict";Qh=Jh,Xh=Qh,Rc=Xh});function Fc(n,e){return new Ai({...n.decoders??{[n.prefix]:n},...e.decoders??{[e.prefix]:e}})}function It({name:n,prefix:e,encode:t,decode:r}){return new ki(n,e,t,r)}function ze({name:n,prefix:e,alphabet:t}){let{encode:r,decode:s}=Rc(t,n);return It({prefix:e,name:n,encode:r,decode:i=>ue(s(i))})}function Zh(n,e,t,r){let s=n.length;for(;n[s-1]==="=";)--s;let i=new Uint8Array(s*t/8|0),o=0,c=0,a=0;for(let u=0;u<s;++u){let l=e[n[u]];if(l===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<t|l,o+=t,o>=8&&(o-=8,i[a++]=255&c>>o)}if(o>=t||(255&c<<8-o)!==0)throw new SyntaxError("Unexpected end of data");return i}function ef(n,e,t){let r=e[e.length-1]==="=",s=(1<<t)-1,i="",o=0,c=0;for(let a=0;a<n.length;++a)for(c=c<<8|n[a],o+=8;o>t;)o-=t,i+=e[s&c>>o];if(o!==0&&(i+=e[s&c<<t-o]),r)for(;(i.length*t&7)!==0;)i+="=";return i}function tf(n){let e={};for(let t=0;t<n.length;++t)e[n[t]]=t;return e}function U({name:n,prefix:e,bitsPerChar:t,alphabet:r}){let s=tf(r);return It({prefix:e,name:n,encode(i){return ef(i,r,t)},decode(i){return Zh(i,s,t,n)}})}var xi,vi,Ai,ki,me=w(()=>{"use strict";Ke();Tc();xi=class{constructor(e,t,r){p(this,"name");p(this,"prefix");p(this,"baseEncode");this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},vi=class{constructor(e,t,r){p(this,"name");p(this,"prefix");p(this,"baseDecode");p(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=r}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 Fc(this,e)}},Ai=class{constructor(e){p(this,"decoders");this.decoders=e}or(e){return Fc(this,e)}decode(e){let t=e[0],r=this.decoders[t];if(r!=null)return r.decode(e);throw RangeError(`Unable to decode multibase string ${JSON.stringify(e)}, only inputs prefixed with ${Object.keys(this.decoders)} are supported`)}};ki=class{constructor(e,t,r,s){p(this,"name");p(this,"prefix");p(this,"baseEncode");p(this,"baseDecode");p(this,"encoder");p(this,"decoder");this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=s,this.encoder=new xi(e,t,r),this.decoder=new vi(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}});var Ei={};B(Ei,{base32:()=>J,base32hex:()=>of,base32hexpad:()=>cf,base32hexpadupper:()=>lf,base32hexupper:()=>af,base32pad:()=>nf,base32padupper:()=>sf,base32upper:()=>rf,base32z:()=>uf});var J,rf,nf,sf,of,af,cf,lf,uf,Er=w(()=>{"use strict";me();J=U({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),rf=U({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),nf=U({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),sf=U({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),of=U({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),af=U({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),cf=U({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),lf=U({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),uf=U({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var Ci={};B(Ci,{base36:()=>Cr,base36upper:()=>df});var Cr,df,Pi=w(()=>{"use strict";me();Cr=ze({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),df=ze({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var Ii={};B(Ii,{base58btc:()=>de,base58flickr:()=>hf});var de,hf,Hn=w(()=>{"use strict";me();de=ze({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),hf=ze({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});function Uc(n,e,t){e=e||[],t=t||0;for(var r=t;n>=mf;)e[t++]=n&255|Mc,n/=128;for(;n&gf;)e[t++]=n&255|Mc,n>>>=7;return e[t]=n|0,Uc.bytes=t-r+1,e}function Bi(n,r){var t=0,r=r||0,s=0,i=r,o,c=n.length;do{if(i>=c)throw Bi.bytes=0,new RangeError("Could not decode varint");o=n[i++],t+=s<28?(o&Nc)<<s:(o&Nc)*Math.pow(2,s),s+=7}while(o>=wf);return Bi.bytes=i-r,t}var ff,Mc,pf,gf,mf,yf,wf,Nc,bf,Sf,xf,vf,Af,kf,Ef,Cf,Pf,If,Bf,Df,Pr,Lc=w(()=>{"use strict";ff=Uc,Mc=128,pf=127,gf=~pf,mf=Math.pow(2,31);yf=Bi,wf=128,Nc=127;bf=Math.pow(2,7),Sf=Math.pow(2,14),xf=Math.pow(2,21),vf=Math.pow(2,28),Af=Math.pow(2,35),kf=Math.pow(2,42),Ef=Math.pow(2,49),Cf=Math.pow(2,56),Pf=Math.pow(2,63),If=function(n){return n<bf?1:n<Sf?2:n<xf?3:n<vf?4:n<Af?5:n<kf?6:n<Ef?7:n<Cf?8:n<Pf?9:10},Bf={encode:ff,decode:yf,encodingLength:If},Df=Bf,Pr=Df});function Ir(n,e=0){return[Pr.decode(n,e),Pr.decode.bytes]}function Bt(n,e,t=0){return Pr.encode(n,e,t),e}function Dt(n){return Pr.encodingLength(n)}var Gn=w(()=>{"use strict";Lc()});function Tt(n,e){let t=e.byteLength,r=Dt(n),s=r+Dt(t),i=new Uint8Array(s+t);return Bt(n,i,0),Bt(t,i,r),i.set(e,s),new Rt(n,t,e,i)}function Yn(n){let e=ue(n),[t,r]=Ir(e),[s,i]=Ir(e.subarray(r)),o=e.subarray(r+i);if(o.byteLength!==s)throw new Error("Incorrect length");return new Rt(t,s,o,e)}function _c(n,e){if(n===e)return!0;{let t=e;return n.code===t.code&&n.size===t.size&&t.bytes instanceof Uint8Array&&wi(n.bytes,t.bytes)}}var Rt,Mt=w(()=>{"use strict";Ke();Gn();Rt=class{constructor(e,t,r,s){p(this,"code");p(this,"size");p(this,"digest");p(this,"bytes");this.code=e,this.size=t,this.digest=r,this.bytes=s}}});var Di=w(()=>{"use strict"});function Oc(n,e){let{bytes:t,version:r}=n;return r===0?Tf(t,Ri(n),e??de.encoder):Ff(t,Ri(n),e??J.encoder)}function Ri(n){let e=Kc.get(n);if(e==null){let t=new Map;return Kc.set(n,t),t}return e}function Rf(n,e){switch(n[0]){case"Q":{let t=e??de;return[de.prefix,t.decode(`${de.prefix}${n}`)]}case de.prefix:{let t=e??de;return[de.prefix,t.decode(n)]}case J.prefix:{let t=e??J;return[J.prefix,t.decode(n)]}case Cr.prefix:{let t=e??Cr;return[Cr.prefix,t.decode(n)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[n[0],e.decode(n)]}}}function Tf(n,e,t){let{prefix:r}=t;if(r!==de.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(r);if(s==null){let i=t.encode(n).slice(1);return e.set(r,i),i}else return s}function Ff(n,e,t){let{prefix:r}=t,s=e.get(r);if(s==null){let i=t.encode(n);return e.set(r,i),i}else return s}function zc(n,e,t){let r=Dt(n),s=r+Dt(e),i=new Uint8Array(s+t.byteLength);return Bt(n,i,0),Bt(e,i,r),i.set(t,s),i}var Kc,Wc,z,Br,Mf,Nf,nt=w(()=>{"use strict";Er();Pi();Hn();Ke();Mt();Gn();Di();Kc=new WeakMap;z=class n{constructor(e,t,r,s){p(this,"code");p(this,"version");p(this,"multihash");p(this,"bytes");p(this,"/");p(this,Wc,"CID");this.code=t,this.version=e,this.multihash=r,this.bytes=s,this["/"]=s}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!==Br)throw new Error("Cannot convert a non dag-pb CID to CIDv0");if(t.code!==Mf)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return n.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,r=Tt(e,t);return n.createV1(this.code,r)}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 n.equals(this,e)}static equals(e,t){let r=t;return r!=null&&e.code===r.code&&e.version===r.version&&_c(e.multihash,r.multihash)}toString(e){return Oc(this,e)}toJSON(){return{"/":Oc(this)}}link(){return this}[(Wc=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 n)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:r,code:s,multihash:i,bytes:o}=t;return new n(r,s,i,o??zc(r,s,i.bytes))}else if(t[Nf]===!0){let{version:r,multihash:s,code:i}=t,o=Yn(s);return n.create(r,i,o)}else return null}static create(e,t,r){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(r.bytes instanceof Uint8Array))throw new Error("Invalid digest");switch(e){case 0:{if(t!==Br)throw new Error(`Version 0 CID must use dag-pb (code: ${Br}) block encoding`);return new n(e,t,r,r.bytes)}case 1:{let s=zc(e,t,r.bytes);return new n(e,t,r,s)}default:throw new Error("Invalid version")}}static createV0(e){return n.create(0,Br,e)}static createV1(e,t){return n.create(1,e,t)}static decode(e){let[t,r]=n.decodeFirst(e);if(r.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=n.inspectBytes(e),r=t.size-t.multihashSize,s=ue(e.subarray(r,r+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=s.subarray(t.multihashSize-t.digestSize),o=new Rt(t.multihashCode,t.digestSize,i,s);return[t.version===0?n.createV0(o):n.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,r=()=>{let[h,g]=Ir(e.subarray(t));return t+=g,h},s=r(),i=Br;if(s===18?(s=0,t=0):i=r(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let o=t,c=r(),a=r(),u=t+a,l=u-o;return{version:s,codec:i,multihashCode:c,digestSize:a,multihashSize:l,size:u}}static parse(e,t){let[r,s]=Rf(e,t),i=n.decode(s);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ri(i).set(r,e),i}};Br=112,Mf=18;Nf=Symbol.for("@ipld/js-cid/CID")});function Ti(n,e){let t=0;for(let r=0;;r+=7){if(r>=64)throw new Error("protobuf: varint overflow");if(e>=n.length)throw new Error("protobuf: unexpected end of data");let s=n[e++];if(t+=r<28?(s&127)<<r:(s&127)*2**r,s<128)break}return[t,e]}function jn(n,e){let t;[t,e]=Ti(n,e);let r=e+t;if(t<0||r<0)throw new Error("protobuf: invalid length");if(r>n.length)throw new Error("protobuf: unexpected end of data");return[n.subarray(e,r),r]}function $c(n,e){let t;return[t,e]=Ti(n,e),[t&7,t>>3,e]}function Lf(n){let e={},t=n.length,r=0;for(;r<t;){let s,i;if([s,i,r]=$c(n,r),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,r]=jn(n,r)}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,r]=jn(n,r),e.Name=Uf.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,r]=Ti(n,r)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${i}`)}if(r>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function qc(n){let e=n.length,t=0,r,s=!1,i;for(;t<e;){let c,a;if([c,a,t]=$c(n,t),c!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${c}`);if(a===1){if(i)throw new Error("protobuf: (PBNode) duplicate Data section");[i,t]=jn(n,t),r&&(s=!0)}else if(a===2){if(s)throw new Error("protobuf: (PBNode) duplicate Links section");r||(r=[]);let u;[u,t]=jn(n,t),r.push(Lf(u))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${a}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let o={};return i&&(o.Data=i),o.Links=r||[],o}var Uf,Hc=w(()=>{"use strict";Uf=new TextDecoder});function Of(n,e){let t=e.length;if(typeof n.Tsize=="number"){if(n.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(n.Tsize))throw new Error("Tsize too large for encoding");t=Dr(e,t,n.Tsize)-1,e[t]=24}if(typeof n.Name=="string"){let r=Gc.encode(n.Name);t-=r.length,e.set(r,t),t=Dr(e,t,r.length)-1,e[t]=18}return n.Hash&&(t-=n.Hash.length,e.set(n.Hash,t),t=Dr(e,t,n.Hash.length)-1,e[t]=10),e.length-t}function Yc(n){let e=zf(n),t=new Uint8Array(e),r=e;if(n.Data&&(r-=n.Data.length,t.set(n.Data,r),r=Dr(t,r,n.Data.length)-1,t[r]=10),n.Links)for(let s=n.Links.length-1;s>=0;s--){let i=Of(n.Links[s],t.subarray(0,r));r-=i,r=Dr(t,r,i)-1,t[r]=18}return t}function Kf(n){let e=0;if(n.Hash){let t=n.Hash.length;e+=1+t+Nt(t)}if(typeof n.Name=="string"){let t=Gc.encode(n.Name).length;e+=1+t+Nt(t)}return typeof n.Tsize=="number"&&(e+=1+Nt(n.Tsize)),e}function zf(n){let e=0;if(n.Data){let t=n.Data.length;e+=1+t+Nt(t)}if(n.Links)for(let t of n.Links){let r=Kf(t);e+=1+r+Nt(r)}return e}function Dr(n,e,t){e-=Nt(t);let r=e;for(;t>=_f;)n[e++]=t&127|128,t/=128;for(;t>=128;)n[e++]=t&127|128,t>>>=7;return n[e]=t,r}function Nt(n){return n%2===0&&n++,Math.floor((Wf(n)+6)/7)}function Wf(n){let e=0;return n>=Vc&&(n=Math.floor(n/Vc),e=32),n>=65536&&(n>>>=16,e+=16),n>=256&&(n>>>=8,e+=8),e+$f[n]}var Gc,Vc,_f,$f,jc=w(()=>{"use strict";Gc=new TextEncoder,Vc=2**32,_f=2**31;$f=[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 Qc(n,e){if(n===e)return 0;let t=n.Name?Fi.encode(n.Name):[],r=e.Name?Fi.encode(e.Name):[],s=t.length,i=r.length;for(let o=0,c=Math.min(s,i);o<c;++o)if(t[o]!==r[o]){s=t[o],i=r[o];break}return s<i?-1:i<s?1:0}function Jc(n,e){return!Object.keys(n).some(t=>!e.includes(t))}function Xc(n){if(typeof n.asCID=="object"){let t=z.asCID(n);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof n!="object"||Array.isArray(n))throw new TypeError("Invalid DAG-PB form");let e={};if(n.Hash){let t=z.asCID(n.Hash);try{t||(typeof n.Hash=="string"?t=z.parse(n.Hash):n.Hash instanceof Uint8Array&&(t=z.decode(n.Hash)))}catch(r){throw new TypeError(`Invalid DAG-PB form: ${r.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof n.Name=="string"&&(e.Name=n.Name),typeof n.Tsize=="number"&&(e.Tsize=n.Tsize),e}function re(n){if((n instanceof Uint8Array||typeof n=="string")&&(n={Data:n}),typeof n!="object"||Array.isArray(n))throw new TypeError("Invalid DAG-PB form");let e={};if(n.Data!==void 0)if(typeof n.Data=="string")e.Data=Fi.encode(n.Data);else if(n.Data instanceof Uint8Array)e.Data=n.Data;else throw new TypeError("Invalid DAG-PB form");if(n.Links!==void 0)if(Array.isArray(n.Links))e.Links=n.Links.map(Xc),e.Links.sort(Qc);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function Mi(n){if(!n||typeof n!="object"||Array.isArray(n)||n instanceof Uint8Array||n["/"]&&n["/"]===n.bytes)throw new TypeError("Invalid DAG-PB form");if(!Jc(n,qf))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(n.Data!==void 0&&!(n.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(n.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<n.Links.length;e++){let t=n.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(!Jc(t,Hf))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&&Qc(t,n.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function Zc(n,e=[]){return re({Data:n,Links:e})}function el(n,e,t){return Xc({Hash:t,Name:n,Tsize:e})}function tl(n){return n instanceof ArrayBuffer?new Uint8Array(n,0,n.byteLength):n}var qf,Hf,Fi,rl=w(()=>{"use strict";nt();qf=["Data","Links"],Hf=["Hash","Name","Tsize"],Fi=new TextEncoder});var Rr={};B(Rr,{code:()=>Gf,createLink:()=>el,createNode:()=>Zc,decode:()=>Yf,encode:()=>ne,name:()=>Vf,prepare:()=>re,validate:()=>Mi});function ne(n){Mi(n);let e={};return n.Links&&(e.Links=n.Links.map(t=>{let r={};return t.Hash&&(r.Hash=t.Hash.bytes),t.Name!==void 0&&(r.Name=t.Name),t.Tsize!==void 0&&(r.Tsize=t.Tsize),r})),n.Data&&(e.Data=n.Data),Yc(e)}function Yf(n){let e=tl(n),t=qc(e),r={};return t.Data&&(r.Data=t.Data),t.Links&&(r.Links=t.Links.map(s=>{let i={};try{i.Hash=z.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})),r}var Vf,Gf,st=w(()=>{"use strict";nt();Hc();jc();rl();Vf="dag-pb",Gf=112});var Ut,Tr,Lt,Jn,Ni=w(()=>{"use strict";Ut=class Ut extends Error{constructor(t="Invalid type"){super(t);p(this,"name",Ut.name);p(this,"code",Ut.code)}};p(Ut,"name","InvalidTypeError"),p(Ut,"code","ERR_INVALID_TYPE");Tr=Ut,Lt=class Lt extends Error{constructor(t="Invalid message"){super(t);p(this,"name",Lt.name);p(this,"code",Lt.code)}};p(Lt,"name","InvalidUnixFSMessageError"),p(Lt,"code","ERR_INVALID_MESSAGE");Jn=Lt});function Fr(n){if(n<jf)return 1;if(n<Jf)return 2;if(n<Qf)return 3;if(n<nl)return 4;if(n<sl)return 5;if(n<il)return 6;if(n<ol)return 7;if(Number.MAX_SAFE_INTEGER!=null&&n>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function al(n,e,t=0){switch(Fr(n)){case 8:e[t++]=n&255|V,n/=128;case 7:e[t++]=n&255|V,n/=128;case 6:e[t++]=n&255|V,n/=128;case 5:e[t++]=n&255|V,n/=128;case 4:e[t++]=n&255|V,n>>>=7;case 3:e[t++]=n&255|V,n>>>=7;case 2:e[t++]=n&255|V,n>>>=7;case 1:{e[t++]=n&255,n>>>=7;break}default:throw new Error("unreachable")}return e}function cl(n,e){let t=n[e],r=0;if(r+=t&We,t<V||(t=n[e+1],r+=(t&We)<<7,t<V)||(t=n[e+2],r+=(t&We)<<14,t<V)||(t=n[e+3],r+=(t&We)<<21,t<V)||(t=n[e+4],r+=(t&We)*nl,t<V)||(t=n[e+5],r+=(t&We)*sl,t<V)||(t=n[e+6],r+=(t&We)*il,t<V)||(t=n[e+7],r+=(t&We)*ol,t<V))return r;throw new RangeError("Could not decode varint")}var jf,Jf,Qf,nl,sl,il,ol,V,We,Ui=w(()=>{"use strict";rt();jf=Math.pow(2,7),Jf=Math.pow(2,14),Qf=Math.pow(2,21),nl=Math.pow(2,28),sl=Math.pow(2,35),il=Math.pow(2,42),ol=Math.pow(2,49),V=128,We=127});function ll(n,e,t){Li[0]=n,e[t]=$e[0],e[t+1]=$e[1],e[t+2]=$e[2],e[t+3]=$e[3]}function ul(n,e){return $e[0]=n[e],$e[1]=n[e+1],$e[2]=n[e+2],$e[3]=n[e+3],Li[0]}function dl(n,e,t){_i[0]=n,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 hl(n,e){return W[0]=n[e],W[1]=n[e+1],W[2]=n[e+2],W[3]=n[e+3],W[4]=n[e+4],W[5]=n[e+5],W[6]=n[e+6],W[7]=n[e+7],_i[0]}var Li,$e,_i,W,Oi=w(()=>{"use strict";Li=new Float32Array([-0]),$e=new Uint8Array(Li.buffer);_i=new Float64Array([-0]),W=new Uint8Array(_i.buffer)});var Xf,Zf,se,it,fl,Ki=w(()=>{"use strict";Xf=BigInt(Number.MAX_SAFE_INTEGER),Zf=BigInt(Number.MIN_SAFE_INTEGER),se=class n{constructor(e,t){p(this,"lo");p(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,r=~this.hi>>>0;return t===0&&(r=r+1>>>0),-(t+r*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,r=~this.hi>>>0;return t===0&&(r=r+1>>>0),-(BigInt(t)+(BigInt(r)<<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,r=this.hi>>>24;return r===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}static fromBigInt(e){if(e===0n)return it;if(e<Xf&&e>Zf)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let r=e>>32n,s=e-(r<<32n);return t&&(r=~r|0n,s=~s|0n,++s>fl&&(s=0n,++r>fl&&(r=0n))),new n(Number(s),Number(r))}static fromNumber(e){if(e===0)return it;let t=e<0;t&&(e=-e);let r=e>>>0,s=(e-r)/4294967296>>>0;return t&&(s=~s>>>0,r=~r>>>0,++r>4294967295&&(r=0,++s>4294967295&&(s=0))),new n(r,s)}static from(e){return typeof e=="number"?n.fromNumber(e):typeof e=="bigint"?n.fromBigInt(e):typeof e=="string"?n.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new n(e.low>>>0,e.high>>>0):it}},it=new se(0,0);it.toBigInt=function(){return 0n};it.zzEncode=it.zzDecode=function(){return this};it.length=function(){return 1};fl=4294967296n});function pl(n){let e=0,t=0;for(let r=0;r<n.length;++r)t=n.charCodeAt(r),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(n.charCodeAt(r+1)&64512)===56320?(++r,e+=4):e+=3;return e}function gl(n,e,t){if(t-e<1)return"";let s,i=[],o=0,c;for(;e<t;)c=n[e++],c<128?i[o++]=c:c>191&&c<224?i[o++]=(c&31)<<6|n[e++]&63:c>239&&c<365?(c=((c&7)<<18|(n[e++]&63)<<12|(n[e++]&63)<<6|n[e++]&63)-65536,i[o++]=55296+(c>>10),i[o++]=56320+(c&1023)):i[o++]=(c&15)<<12|(n[e++]&63)<<6|n[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(n,e,t){let r=t,s,i;for(let o=0;o<n.length;++o)s=n.charCodeAt(o),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((i=n.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-r}var Wi=w(()=>{"use strict"});function ye(n,e){return RangeError(`index out of range: ${n.pos} + ${e??1} > ${n.len}`)}function Qn(n,e){return(n[e-4]|n[e-3]<<8|n[e-2]<<16|n[e-1]<<24)>>>0}function qi(n){return new $i(n instanceof Uint8Array?n:n.subarray())}var $i,Hi=w(()=>{"use strict";Ui();Oi();Ki();Wi();$i=class{constructor(e){p(this,"buf");p(this,"pos");p(this,"len");p(this,"_slice",Uint8Array.prototype.subarray);this.buf=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 Qn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ye(this,4);return Qn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ye(this,4);let e=ul(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ye(this,4);let e=hl(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw ye(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){let e=this.bytes();return gl(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 se(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=Qn(this.buf,this.pos+=4),t=Qn(this.buf,this.pos+=4);return new se(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=cl(this.buf,this.pos);return this.pos+=Fr(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 Mr(n,e,t){let r=qi(n);return e.decode(r,void 0,t)}var yl=w(()=>{"use strict";Hi()});var Vi={};B(Vi,{base10:()=>ep});var ep,wl=w(()=>{"use strict";me();ep=ze({prefix:"9",name:"base10",alphabet:"0123456789"})});var Gi={};B(Gi,{base16:()=>tp,base16upper:()=>rp});var tp,rp,bl=w(()=>{"use strict";me();tp=U({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),rp=U({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var Yi={};B(Yi,{base2:()=>np});var np,Sl=w(()=>{"use strict";me();np=U({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var ji={};B(ji,{base256emoji:()=>cp});function op(n){return n.reduce((e,t)=>(e+=sp[t],e),"")}function ap(n){let e=[];for(let t of n){let r=t.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${t}`);let s=ip[r];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var xl,sp,ip,cp,vl=w(()=>{"use strict";me();xl=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}"),sp=xl.reduce((n,e,t)=>(n[t]=e,n),[]),ip=xl.reduce((n,e,t)=>{let r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return n[r]=t,n},[]);cp=It({prefix:"\u{1F680}",name:"base256emoji",encode:op,decode:ap})});var Qi={};B(Qi,{base64:()=>Ji,base64pad:()=>lp,base64url:()=>up,base64urlpad:()=>dp});var Ji,lp,up,dp,Xi=w(()=>{"use strict";me();Ji=U({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),lp=U({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),up=U({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),dp=U({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var Zi={};B(Zi,{base8:()=>hp});var hp,Al=w(()=>{"use strict";me();hp=U({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var eo={};B(eo,{identity:()=>fp});var fp,kl=w(()=>{"use strict";Ke();me();fp=It({prefix:"\0",name:"identity",encode:n=>Si(n),decode:n=>bi(n)})});var c0,l0,El=w(()=>{"use strict";c0=new TextEncoder,l0=new TextDecoder});var Ot={};B(Ot,{code:()=>_t,decode:()=>yp,encode:()=>mp,name:()=>gp});function mp(n){return ue(n)}function yp(n){return ue(n)}var gp,_t,Nr=w(()=>{"use strict";Ke();gp="raw",_t=85});var to={};B(to,{identity:()=>Sp});function bp(n,e){if(e?.truncate!=null&&e.truncate!==n.byteLength){if(e.truncate<0||e.truncate>n.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${n.byteLength}`);n=n.subarray(0,e.truncate)}return Tt(Cl,Pl(n))}var Cl,wp,Pl,Sp,Il=w(()=>{"use strict";Ke();Mt();Cl=0,wp="identity",Pl=ue;Sp={code:Cl,name:wp,encode:Pl,digest:bp}});function ot({name:n,code:e,encode:t,minDigestLength:r,maxDigestLength:s}){return new ro(n,e,t,r,s)}function Bl(n,e,t){if(t!=null&&t!==n.byteLength){if(t>n.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${n.byteLength}`);n=n.subarray(0,t)}return Tt(e,n)}var xp,ro,Xn=w(()=>{"use strict";Mt();xp=20;ro=class{constructor(e,t,r,s,i){p(this,"name");p(this,"code");p(this,"encode");p(this,"minDigestLength");p(this,"maxDigestLength");this.name=e,this.code=t,this.encode=r,this.minDigestLength=s??xp,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 r=this.encode(e);return r instanceof Uint8Array?Bl(r,this.code,t?.truncate):r.then(s=>Bl(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}}});var so={};B(so,{sha256:()=>no,sha512:()=>vp});function Rl(n){return async e=>new Uint8Array(await crypto.subtle.digest(n,e))}var no,vp,io=w(()=>{"use strict";Xn();no=ot({name:"sha2-256",code:18,encode:Rl("SHA-256")}),vp=ot({name:"sha2-512",code:19,encode:Rl("SHA-512")})});var Tl=w(()=>{"use strict"});var Fl=w(()=>{"use strict"});var Ml=w(()=>{"use strict"});var Nl=w(()=>{"use strict"});var Ul=w(()=>{"use strict";Tl();Fl();Ml();Di();Nl()});var oo=w(()=>{"use strict";Ke();nt();Mt();Xn();Gn();Ul()});var ao,A0,Ll=w(()=>{"use strict";wl();bl();Sl();vl();Er();Pi();Hn();Xi();Al();kl();El();Nr();Il();io();oo();ao={...eo,...Yi,...Zi,...Vi,...Gi,...Ei,...Ci,...Ii,...Qi,...ji},A0={...so,...to}});function Ol(n,e,t,r){return{name:n,prefix:e,encoder:{name:n,prefix:e,encode:t},decoder:{decode:r}}}var _l,co,Ap,Kl,zl=w(()=>{"use strict";Ll();rt();_l=Ol("utf8","u",n=>"u"+new TextDecoder("utf8").decode(n),n=>new TextEncoder().encode(n.substring(1))),co=Ol("ascii","a",n=>{let e="a";for(let t=0;t<n.length;t++)e+=String.fromCharCode(n[t]);return e},n=>{n=n.substring(1);let e=te(n.length);for(let t=0;t<n.length;t++)e[t]=n.charCodeAt(t);return e}),Ap={utf8:_l,"utf-8":_l,hex:ao.base16,latin1:co,ascii:co,binary:co,...ao},Kl=Ap});function Kt(n,e="utf8"){let t=Kl[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${n}`)}var Zn=w(()=>{"use strict";zl()});function lo(n){let e=n??8192,t=e>>>1,r,s=e;return function(o){if(o<1||o>t)return te(o);s+o>e&&(r=te(e),s=0);let c=r.subarray(s,s+=o);return(s&7)!==0&&(s=(s|7)+1),c}}var Wl=w(()=>{"use strict";rt()});function uo(){}function Ep(n){return globalThis.Buffer!=null?te(n):kp(n)}function ho(n,e,t){e[t]=n&255}function Cp(n,e,t){for(;n>127;)e[t++]=n&127|128,n>>>=7;e[t]=n}function es(n,e,t){for(;n.hi!==0;)e[t++]=n.lo&127|128,n.lo=(n.lo>>>7|n.hi<<25)>>>0,n.hi>>>=7;for(;n.lo>127;)e[t++]=n.lo&127|128,n.lo=n.lo>>>7;e[t++]=n.lo}function Ur(n,e,t){e[t]=n&255,e[t+1]=n>>>8&255,e[t+2]=n>>>16&255,e[t+3]=n>>>24}function Pp(n,e,t){e.set(n,t)}function Ip(n,e,t){e.set(n,t)}function Bp(n,e,t){n.length<40?zi(n,e,t):e.utf8Write!=null?e.utf8Write(n,t):e.set(Kt(n),t)}function go(){return new Lr}var at,fo,kp,Lr,po,mo=w(()=>{"use strict";Ui();rt();Zn();Oi();Ki();Wl();Wi();at=class{constructor(e,t,r){p(this,"fn");p(this,"len");p(this,"next");p(this,"val");this.fn=e,this.len=t,this.next=void 0,this.val=r}};fo=class{constructor(e){p(this,"head");p(this,"tail");p(this,"len");p(this,"next");this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},kp=lo();Lr=class{constructor(){p(this,"len");p(this,"head");p(this,"tail");p(this,"states");this.len=0,this.head=new at(uo,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new at(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new po((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(es,10,se.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=se.fromBigInt(e);return this._push(es,t.length(),t)}uint64Number(e){return this._push(al,Fr(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=se.fromBigInt(e).zzEncode();return this._push(es,t.length(),t)}sint64Number(e){let t=se.fromNumber(e).zzEncode();return this._push(es,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(ho,1,e?1:0)}fixed32(e){return this._push(Ur,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=se.fromBigInt(e);return this._push(Ur,4,t.lo)._push(Ur,4,t.hi)}fixed64Number(e){let t=se.fromNumber(e);return this._push(Ur,4,t.lo)._push(Ur,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(ll,4,e)}double(e){return this._push(dl,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(ho,1,0):this.uint32(t)._push(Pp,t,e)}string(e){let t=pl(e);return t!==0?this.uint32(t)._push(zi,t,e):this._push(ho,1,0)}fork(){return this.states=new fo(this),this.head=this.tail=new at(uo,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 at(uo,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r!==0&&(this.tail.next=e.next,this.tail=t,this.len+=r),this}finish(){let e=this.head.next,t=Ep(this.len),r=0;for(;e!=null;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}};po=class extends at{constructor(t,r){super(Cp,t,r);p(this,"next");this.next=void 0}};globalThis.Buffer!=null&&(Lr.prototype.bytes=function(n){let e=n.length>>>0;return this.uint32(e),e>0&&this._push(Ip,e,n),this},Lr.prototype.string=function(n){let e=globalThis.Buffer.byteLength(n);return this.uint32(e),e>0&&this._push(Bp,e,n),this})});function _r(n,e){let t=go();return e.encode(n,t,{lengthDelimited:!1}),t.finish()}var $l=w(()=>{"use strict";mo()});function ts(n,e,t,r){return{name:n,type:e,encode:t,decode:r}}var zt,yo=w(()=>{"use strict";(function(n){n[n.VARINT=0]="VARINT",n[n.BIT64=1]="BIT64",n[n.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",n[n.START_GROUP=3]="START_GROUP",n[n.END_GROUP=4]="END_GROUP",n[n.BIT32=5]="BIT32"})(zt||(zt={}))});function wo(n){function e(s){if(n[s.toString()]==null)throw new Error("Invalid enum value");return n[s]}let t=function(i,o){let c=e(i);o.int32(c)},r=function(i){let o=i.int32();return e(o)};return ts("enum",zt.VARINT,t,r)}var ql=w(()=>{"use strict";yo()});function Or(n,e){return ts("message",zt.LENGTH_DELIMITED,n,e)}var Hl=w(()=>{"use strict";yo()});var Vl=w(()=>{"use strict";yl();$l();ql();Hl();Hi();mo()});var we,rs,Gl,Yl=w(()=>{"use strict";Vl();(function(n){let e;(function(s){s.Raw="Raw",s.Directory="Directory",s.File="File",s.Metadata="Metadata",s.Symlink="Symlink",s.HAMTShard="HAMTShard"})(e=n.DataType||(n.DataType={}));let t;(function(s){s[s.Raw=0]="Raw",s[s.Directory=1]="Directory",s[s.File=2]="File",s[s.Metadata=3]="Metadata",s[s.Symlink=4]="Symlink",s[s.HAMTShard=5]="HAMTShard"})(t||(t={})),(function(s){s.codec=()=>wo(t)})(e=n.DataType||(n.DataType={}));let r;n.codec=()=>(r==null&&(r=Or((s,i,o={})=>{if(o.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),n.DataType.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),s.filesize!=null&&(i.uint32(24),i.uint64(s.filesize)),s.blocksizes!=null)for(let c of s.blocksizes)i.uint32(32),i.uint64(c);s.hashType!=null&&(i.uint32(40),i.uint64(s.hashType)),s.fanout!=null&&(i.uint32(48),i.uint64(s.fanout)),s.mode!=null&&(i.uint32(56),i.uint32(s.mode)),s.mtime!=null&&(i.uint32(66),rs.codec().encode(s.mtime,i)),o.lengthDelimited!==!1&&i.ldelim()},(s,i)=>{let o={blocksizes:[]},c=i==null?s.len:s.pos+i;for(;s.pos<c;){let a=s.uint32();switch(a>>>3){case 1:o.Type=n.DataType.codec().decode(s);break;case 2:o.Data=s.bytes();break;case 3:o.filesize=s.uint64();break;case 4:o.blocksizes.push(s.uint64());break;case 5:o.hashType=s.uint64();break;case 6:o.fanout=s.uint64();break;case 7:o.mode=s.uint32();break;case 8:o.mtime=rs.codec().decode(s,s.uint32());break;default:s.skipType(a&7);break}}return o})),r),n.encode=s=>_r(s,n.codec()),n.decode=s=>Mr(s,n.codec())})(we||(we={}));(function(n){let e;n.codec=()=>(e==null&&(e=Or((t,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),t.Seconds!=null&&(r.uint32(8),r.int64(t.Seconds)),t.FractionalNanoseconds!=null&&(r.uint32(21),r.fixed32(t.FractionalNanoseconds)),s.lengthDelimited!==!1&&r.ldelim()},(t,r)=>{let s={},i=r==null?t.len:t.pos+r;for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:s.Seconds=t.int64();break;case 2:s.FractionalNanoseconds=t.fixed32();break;default:t.skipType(o&7);break}}return s})),e),n.encode=t=>_r(t,n.codec()),n.decode=t=>Mr(t,n.codec())})(rs||(rs={}));(function(n){let e;n.codec=()=>(e==null&&(e=Or((t,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),t.MimeType!=null&&(r.uint32(10),r.string(t.MimeType)),s.lengthDelimited!==!1&&r.ldelim()},(t,r)=>{let s={},i=r==null?t.len:t.pos+r;for(;t.pos<i;){let o=t.uint32();o>>>3===1?s.MimeType=t.string():t.skipType(o&7)}return s})),e),n.encode=t=>_r(t,n.codec()),n.decode=t=>Mr(t,n.codec())})(Gl||(Gl={}))});var jl,Dp,Jl,Ql,Xl,Q,Wt=w(()=>{"use strict";Ni();Yl();Ni();jl={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},Dp=["directory","hamt-sharded-directory"],Jl=parseInt("0644",8),Ql=parseInt("0755",8),Xl=BigInt(1024),Q=class n{constructor(e={type:"file"}){p(this,"type");p(this,"data");p(this,"blockSizes");p(this,"hashType");p(this,"fanout");p(this,"mtime");p(this,"_mode");p(this,"_originalMode");let{type:t,data:r,blockSizes:s,hashType:i,fanout:o,mtime:c,mode:a}=e;if(t!=null&&!Object.values(jl).includes(t))throw new Tr("Type: "+t+" is not valid");this.type=t??"file",this.data=r,this.hashType=i,this.fanout=o,this.blockSizes=s??[],this._originalMode=0,this.mode=a,this.mtime=c}static unmarshal(e){let t=we.decode(e);if(t.fanout!=null&&t.fanout>Xl)throw new Jn(`Fanout size was too large - ${t.fanout} > ${Xl}`);let r=new n({type:jl[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 r._originalMode=t.mode??0,r}set mode(e){e==null?this._mode=this.isDirectory()?Ql:Jl:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return Dp.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 Tr(`Type: ${e} is not valid`)}let t=this.data;(this.data==null||this.data.length===0)&&(t=void 0);let r;this.mode!=null&&(r=this._originalMode&4294963200|(this.mode??0),r===Jl&&!this.isDirectory()&&(r=void 0),r===Ql&&this.isDirectory()&&(r=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:r,mtime:s})}}});var Ie,ns=w(()=>{"use strict";Ie=class extends Event{constructor(t,r){super(t);p(this,"type");p(this,"detail");this.type=t,this.detail=r}}});var be,$t=w(()=>{"use strict";st();nt();io();be=async(n,e,t)=>{t.codec==null&&(t.codec=Rr);let r=await no.digest(n),s=z.create(t.cidVersion,t.codec.code,r);return await e.put(s,n,t),s}});function Zl(n){return async function*(t,r){let s=0n;for await(let i of t.content)yield async()=>{let o,c={codec:Rr,cidVersion:n.cidVersion,onProgress:n.onProgress};n.rawLeaves?(c.codec=Ot,c.cidVersion=1):(o=new Q({type:n.leafType,data:i}),i=ne({Data:o.marshal(),Links:[]}));let a=await be(i,r,c);return s+=BigInt(i.byteLength),n.onProgress?.(new Ie("unixfs:importer:progress:file:write",{bytesWritten:s,cid:a,path:t.path})),{cid:a,unixfs:o,size:BigInt(i.length),block:i}}}}var eu=w(()=>{"use strict";st();Wt();Nr();ns();$t()});var qt,jt,Ht,bo,Vt,So,Gt,xo,Yt,Be,Kr=w(()=>{"use strict";qt=class qt extends Error{constructor(t="Invalid parameters"){super(t);p(this,"name",qt.name);p(this,"code",qt.code)}};p(qt,"name","InvalidParametersError"),p(qt,"code","ERR_INVALID_PARAMS");jt=qt,Ht=class Ht extends Error{constructor(t="Invalid avg chunk size"){super(t);p(this,"name",Ht.name);p(this,"code",Ht.code)}};p(Ht,"name","InvalidAvgChunkSizeError"),p(Ht,"code","ERR_INVALID_AVG_CHUNK_SIZE");bo=Ht,Vt=class Vt extends Error{constructor(t="Invalid chunk size"){super(t);p(this,"name",Vt.name);p(this,"code",Vt.code)}};p(Vt,"name","InvalidChunkSizeError"),p(Vt,"code","ERR_INVALID_CHUNK_SIZE");So=Vt,Gt=class Gt extends Error{constructor(t="Invalid min chunk size"){super(t);p(this,"name",Gt.name);p(this,"code",Gt.code)}};p(Gt,"name","InvalidMinChunkSizeError"),p(Gt,"code","ERR_INVALID_MIN_CHUNK_SIZE");xo=Gt,Yt=class Yt extends Error{constructor(t="Invalid content"){super(t);p(this,"name",Yt.name);p(this,"code",Yt.code)}};p(Yt,"name","InvalidContentError"),p(Yt,"code","ERR_INVALID_CONTENT");Be=Yt});var tu,ru=w(()=>{"use strict";st();Wt();$t();tu=async(n,e,t)=>{let r=new Q({type:"directory",mtime:n.mtime,mode:n.mode}),s=ne(re({Data:r.marshal()})),i=await be(s,e,t),o=n.path;return{cid:i,path:o,unixfs:r,size:BigInt(s.length),originalPath:n.originalPath,block:s}}});async function*Rp(n,e,t){let r=-1,s;for await(let i of Ar(t.bufferImporter(n,e),t.blockWriteConcurrency)){if(r++,r===0){s={...i,single:!0};continue}else r===1&&s!=null&&(yield{...s,block:void 0,single:void 0},s=void 0);yield{...i,block:void 0}}s!=null&&(yield s)}function nu(n){return n.single===!0}var Tp,su,iu=w(()=>{"use strict";st();Wt();mi();Nr();ns();$t();Tp=(n,e,t)=>async function(s){if(s.length===1&&nu(s[0])&&t.reduceSingleLeafToSelf){let l=s[0],h=l.block;return nu(l)&&(n.mtime!==void 0||n.mode!==void 0)&&(l.unixfs=new Q({type:"file",mtime:n.mtime,mode:n.mode,data:l.block}),h={Data:l.unixfs.marshal(),Links:[]},l.block=ne(re(h)),l.cid=await be(l.block,e,{...t,cidVersion:t.cidVersion}),l.size=BigInt(l.block.length)),t.onProgress?.(new Ie("unixfs:importer:progress:file:layout",{cid:l.cid,path:l.originalPath})),{cid:l.cid,path:n.path,unixfs:l.unixfs,size:l.size,originalPath:l.originalPath}}let i=new Q({type:"file",mtime:n.mtime,mode:n.mode}),o=s.filter(l=>l.cid.code===_t&&l.size>0||l.unixfs!=null&&l.unixfs.data==null&&l.unixfs.fileSize()>0n?!0:!!l.unixfs?.data?.length).map(l=>l.cid.code===_t?(i.addBlockSize(l.size),{Name:"",Tsize:Number(l.size),Hash:l.cid}):(l.unixfs?.data==null?i.addBlockSize(l.unixfs?.fileSize()??0n):i.addBlockSize(BigInt(l.unixfs.data.length)),{Name:"",Tsize:Number(l.size),Hash:l.cid})),c={Data:i.marshal(),Links:o},a=ne(re(c)),u=await be(a,e,t);return t.onProgress?.(new Ie("unixfs:importer:progress:file:layout",{cid:u,path:n.originalPath})),{cid:u,path:n.path,unixfs:i,size:BigInt(a.length+c.Links.reduce((l,h)=>l+(h.Tsize??0),0)),originalPath:n.originalPath,block:a}},su=async(n,e,t)=>t.layout(Rp(n,e,t),Tp(n,e,t))});function Fp(n){return Symbol.iterator in n}function Mp(n){return Symbol.asyncIterator in n}function Np(n){try{if(n instanceof Uint8Array)return(async function*(){yield n})();if(Fp(n))return(async function*(){yield*n})();if(Mp(n))return n}catch{throw new Be("Content was invalid")}throw new Be("Content was invalid")}function ou(n){return async function*(t,r){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("/")),Up(s)){let o={path:s.path,mtime:s.mtime,mode:s.mode,content:(async function*(){let a=0n;for await(let u of n.chunker(n.chunkValidator(Np(s.content)))){let l=BigInt(u.byteLength);a+=l,n.onProgress?.(new Ie("unixfs:importer:progress:file:read",{bytesRead:a,chunkSize:l,path:s.path})),yield u}})(),originalPath:i},c=n.fileBuilder??su;yield async()=>c(o,r,n)}else if(s.path!=null){let o={path:s.path,mtime:s.mtime,mode:s.mode,originalPath:i},c=n.dirBuilder??tu;yield async()=>c(o,r,n)}else throw new Error("Import candidate must have content or path or both")}}}function Up(n){return n.content!=null}var au=w(()=>{"use strict";ns();Kr();ru();iu()});var cu,lu=w(()=>{"use strict";Zn();Kr();cu=()=>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 Kt(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 vo(n){let e=n?.maxChildrenPerNode??Lp;return async function t(r,s){let i=[];for await(let o of $n(r,e))i.push(await s(o));return i.length>1?t(i,s):i[0]}}var Lp,uu=w(()=>{"use strict";gi();Lp=174});function _p(n){return n[Symbol.asyncIterator]!=null}function Op(n){if(_p(n))return(async()=>{let t=[];for await(let r of n)t.push(r);return t})();let e=[];for(let t of n)e.push(t);return e}var du,hu=w(()=>{"use strict";du=Op});var fu=w(()=>{"use strict";uu()});var ke,zr,Wr,ss=w(()=>{"use strict";nt();ke=class{constructor(e,t){p(this,"options");p(this,"root");p(this,"dir");p(this,"path");p(this,"dirty");p(this,"flat");p(this,"parent");p(this,"parentKey");p(this,"unixfs");p(this,"mode");p(this,"mtime");p(this,"cid");p(this,"size");p(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}},zr=z.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),Wr=z.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi")});var ct,Ao=w(()=>{"use strict";st();Wt();ss();$t();ct=class extends ke{constructor(t,r){super(t,r);p(this,"_children");this._children=new Map}async put(t,r){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,this._children.set(t,r)}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,r]of this._children.entries())yield{key:t,child:r}}estimateNodeSize(){if(this.nodeSize!==void 0)return this.nodeSize;this.nodeSize=0;for(let[t,r]of this._children.entries())r.size!=null&&r.cid!=null&&(this.nodeSize+=t.length+(this.options.cidVersion===1?Wr.bytes.byteLength:zr.bytes.byteLength));return this.nodeSize}async*flush(t){let r=[];for(let[u,l]of this._children.entries()){let h=l;if(l instanceof ke)for await(let g of l.flush(t))h=g,yield g;h.size!=null&&h.cid!=null&&r.push({Name:u,Tsize:Number(h.size),Hash:h.cid})}let s=new Q({type:"directory",mtime:this.mtime,mode:this.mode}),i={Data:s.marshal(),Links:r},o=ne(re(i)),c=await be(o,t,this.options),a=o.length+i.Links.reduce((u,l)=>u+(l.Tsize??0),0);this.cid=c,this.size=a,yield{cid:c,unixfs:s,path:this.path,size:BigInt(a)}}}});var pu=D(($r,is)=>{"use strict";(function(n,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function r(d){if(!Array.isArray(d)&&!ArrayBuffer.isView(d))return!1;for(var f=0;f<d.length;f++)if(!Number.isInteger(d[f])||d[f]<0||d[f]>255)return!1;return!0}function s(d,f){return(d&65535)*f+(((d>>>16)*f&65535)<<16)}function i(d,f){return d<<f|d>>>32-f}function o(d){return d^=d>>>16,d=s(d,2246822507),d^=d>>>13,d=s(d,3266489909),d^=d>>>16,d}function c(d,f){d=[d[0]>>>16,d[0]&65535,d[1]>>>16,d[1]&65535],f=[f[0]>>>16,f[0]&65535,f[1]>>>16,f[1]&65535];var y=[0,0,0,0];return y[3]+=d[3]+f[3],y[2]+=y[3]>>>16,y[3]&=65535,y[2]+=d[2]+f[2],y[1]+=y[2]>>>16,y[2]&=65535,y[1]+=d[1]+f[1],y[0]+=y[1]>>>16,y[1]&=65535,y[0]+=d[0]+f[0],y[0]&=65535,[y[0]<<16|y[1],y[2]<<16|y[3]]}function a(d,f){d=[d[0]>>>16,d[0]&65535,d[1]>>>16,d[1]&65535],f=[f[0]>>>16,f[0]&65535,f[1]>>>16,f[1]&65535];var y=[0,0,0,0];return y[3]+=d[3]*f[3],y[2]+=y[3]>>>16,y[3]&=65535,y[2]+=d[2]*f[3],y[1]+=y[2]>>>16,y[2]&=65535,y[2]+=d[3]*f[2],y[1]+=y[2]>>>16,y[2]&=65535,y[1]+=d[1]*f[3],y[0]+=y[1]>>>16,y[1]&=65535,y[1]+=d[2]*f[2],y[0]+=y[1]>>>16,y[1]&=65535,y[1]+=d[3]*f[1],y[0]+=y[1]>>>16,y[1]&=65535,y[0]+=d[0]*f[3]+d[1]*f[2]+d[2]*f[1]+d[3]*f[0],y[0]&=65535,[y[0]<<16|y[1],y[2]<<16|y[3]]}function u(d,f){return f%=64,f===32?[d[1],d[0]]:f<32?[d[0]<<f|d[1]>>>32-f,d[1]<<f|d[0]>>>32-f]:(f-=32,[d[1]<<f|d[0]>>>32-f,d[0]<<f|d[1]>>>32-f])}function l(d,f){return f%=64,f===0?d:f<32?[d[0]<<f|d[1]>>>32-f,d[1]<<f]:[d[1]<<f-32,0]}function h(d,f){return[d[0]^f[0],d[1]^f[1]]}function g(d){return d=h(d,[0,d[0]>>>1]),d=a(d,[4283543511,3981806797]),d=h(d,[0,d[0]>>>1]),d=a(d,[3301882366,444984403]),d=h(d,[0,d[0]>>>1]),d}t.x86.hash32=function(d,f){if(t.inputValidation&&!r(d))return e;f=f||0;for(var y=d.length%4,k=d.length-y,m=f,b=0,v=3432918353,A=461845907,E=0;E<k;E=E+4)b=d[E]|d[E+1]<<8|d[E+2]<<16|d[E+3]<<24,b=s(b,v),b=i(b,15),b=s(b,A),m^=b,m=i(m,13),m=s(m,5)+3864292196;switch(b=0,y){case 3:b^=d[E+2]<<16;case 2:b^=d[E+1]<<8;case 1:b^=d[E],b=s(b,v),b=i(b,15),b=s(b,A),m^=b}return m^=d.length,m=o(m),m>>>0},t.x86.hash128=function(d,f){if(t.inputValidation&&!r(d))return e;f=f||0;for(var y=d.length%16,k=d.length-y,m=f,b=f,v=f,A=f,E=0,C=0,x=0,P=0,G=597399067,he=2869860233,ut=951274213,dt=2716044179,I=0;I<k;I=I+16)E=d[I]|d[I+1]<<8|d[I+2]<<16|d[I+3]<<24,C=d[I+4]|d[I+5]<<8|d[I+6]<<16|d[I+7]<<24,x=d[I+8]|d[I+9]<<8|d[I+10]<<16|d[I+11]<<24,P=d[I+12]|d[I+13]<<8|d[I+14]<<16|d[I+15]<<24,E=s(E,G),E=i(E,15),E=s(E,he),m^=E,m=i(m,19),m+=b,m=s(m,5)+1444728091,C=s(C,he),C=i(C,16),C=s(C,ut),b^=C,b=i(b,17),b+=v,b=s(b,5)+197830471,x=s(x,ut),x=i(x,17),x=s(x,dt),v^=x,v=i(v,15),v+=A,v=s(v,5)+2530024501,P=s(P,dt),P=i(P,18),P=s(P,G),A^=P,A=i(A,13),A+=m,A=s(A,5)+850148119;switch(E=0,C=0,x=0,P=0,y){case 15:P^=d[I+14]<<16;case 14:P^=d[I+13]<<8;case 13:P^=d[I+12],P=s(P,dt),P=i(P,18),P=s(P,G),A^=P;case 12:x^=d[I+11]<<24;case 11:x^=d[I+10]<<16;case 10:x^=d[I+9]<<8;case 9:x^=d[I+8],x=s(x,ut),x=i(x,17),x=s(x,dt),v^=x;case 8:C^=d[I+7]<<24;case 7:C^=d[I+6]<<16;case 6:C^=d[I+5]<<8;case 5:C^=d[I+4],C=s(C,he),C=i(C,16),C=s(C,ut),b^=C;case 4:E^=d[I+3]<<24;case 3:E^=d[I+2]<<16;case 2:E^=d[I+1]<<8;case 1:E^=d[I],E=s(E,G),E=i(E,15),E=s(E,he),m^=E}return m^=d.length,b^=d.length,v^=d.length,A^=d.length,m+=b,m+=v,m+=A,b+=m,v+=m,A+=m,m=o(m),b=o(b),v=o(v),A=o(A),m+=b,m+=v,m+=A,b+=m,v+=m,A+=m,("00000000"+(m>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(v>>>0).toString(16)).slice(-8)+("00000000"+(A>>>0).toString(16)).slice(-8)},t.x64.hash128=function(d,f){if(t.inputValidation&&!r(d))return e;f=f||0;for(var y=d.length%16,k=d.length-y,m=[0,f],b=[0,f],v=[0,0],A=[0,0],E=[2277735313,289559509],C=[1291169091,658871167],x=0;x<k;x=x+16)v=[d[x+4]|d[x+5]<<8|d[x+6]<<16|d[x+7]<<24,d[x]|d[x+1]<<8|d[x+2]<<16|d[x+3]<<24],A=[d[x+12]|d[x+13]<<8|d[x+14]<<16|d[x+15]<<24,d[x+8]|d[x+9]<<8|d[x+10]<<16|d[x+11]<<24],v=a(v,E),v=u(v,31),v=a(v,C),m=h(m,v),m=u(m,27),m=c(m,b),m=c(a(m,[0,5]),[0,1390208809]),A=a(A,C),A=u(A,33),A=a(A,E),b=h(b,A),b=u(b,31),b=c(b,m),b=c(a(b,[0,5]),[0,944331445]);switch(v=[0,0],A=[0,0],y){case 15:A=h(A,l([0,d[x+14]],48));case 14:A=h(A,l([0,d[x+13]],40));case 13:A=h(A,l([0,d[x+12]],32));case 12:A=h(A,l([0,d[x+11]],24));case 11:A=h(A,l([0,d[x+10]],16));case 10:A=h(A,l([0,d[x+9]],8));case 9:A=h(A,[0,d[x+8]]),A=a(A,C),A=u(A,33),A=a(A,E),b=h(b,A);case 8:v=h(v,l([0,d[x+7]],56));case 7:v=h(v,l([0,d[x+6]],48));case 6:v=h(v,l([0,d[x+5]],40));case 5:v=h(v,l([0,d[x+4]],32));case 4:v=h(v,l([0,d[x+3]],24));case 3:v=h(v,l([0,d[x+2]],16));case 2:v=h(v,l([0,d[x+1]],8));case 1:v=h(v,[0,d[x]]),v=a(v,E),v=u(v,31),v=a(v,C),m=h(m,v)}return m=h(m,[0,d.length]),b=h(b,[0,d.length]),m=c(m,b),b=c(b,m),m=g(m),b=g(b),m=c(m,b),b=c(b,m),("00000000"+(m[0]>>>0).toString(16)).slice(-8)+("00000000"+(m[1]>>>0).toString(16)).slice(-8)+("00000000"+(b[0]>>>0).toString(16)).slice(-8)+("00000000"+(b[1]>>>0).toString(16)).slice(-8)},typeof $r<"u"?(typeof is<"u"&&is.exports&&($r=is.exports=t),$r.murmurHash3=t):typeof define=="function"&&define.amd?define([],function(){return t}):(t._murmurHash3=n.murmurHash3,t.noConflict=function(){return n.murmurHash3=t._murmurHash3,t._murmurHash3=e,t.noConflict=e,t},n.murmurHash3=t)})($r)});var mu=D((Qb,gu)=>{"use strict";gu.exports=pu()});function Kp(n){let e=new Array(4);for(let t=0;t<4;t++)e[t]=n&255,n=n>>8;return new Uint8Array(e)}var os,e1,yu,t1,wu=w(()=>{"use strict";oo();Xn();os=K(mu(),1);e1=ot({name:"murmur3-32",code:35,encode:n=>Kp(os.default.x86.hash32(n))}),yu=ot({name:"murmur3-128",code:34,encode:n=>Pt.fromHex(os.default.x64.hash128(n))}),t1=ot({name:"murmur3-x64-64",code:34,encode:n=>Pt.fromHex(os.default.x64.hash128(n)).subarray(0,8)})});var xu=D((s1,Su)=>{"use strict";Su.exports=class{constructor(){this._bitArrays=[],this._data=[],this._length=0,this._changedLength=!1,this._changedData=!1}set(e,t){let r=this._internalPositionFor(e,!1);if(t===void 0)r!==-1&&(this._unsetInternalPos(r),this._unsetBit(e),this._changedLength=!0,this._changedData=!0);else{let s=!1;r===-1?(r=this._data.length,this._setBit(e),this._changedData=!0):s=!0,this._setInternalPos(r,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,r=new Array(this.length);for(;t<this.length;)r[t]=e(this.get(t),t,this),t++;return r}reduce(e,t){let r=0,s=t;for(;r<this.length;){let i=this.get(r);s=e(s,i,r),r++}return s}find(e){let t=0,r,s;for(;t<this.length&&!r;)s=this.get(t),r=e(s),t++;return r?s:void 0}_internalPositionFor(e,t){let r=this._bytePosFor(e,t);if(r>=this._bitArrays.length)return-1;let s=this._bitArrays[r],i=e-r*7;if(!((s&1<<i)>0))return-1;let c=this._bitArrays.slice(0,r).reduce(zp,0),a=~(4294967295<<i+1),u=bu(s&a);return c+u-1}_bytePosFor(e,t){let r=Math.floor(e/7),s=r+1;for(;!t&&this._bitArrays.length<s;)this._bitArrays.push(0);return r}_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,r,s){let i=this._data,o=[t,r];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 c=Math.round(i.length/2);this._data=i.slice(0,c).concat(o).concat(i.slice(c))}else this._data.push(o);this._changedData=!0,this._changedLength=!0}}_unsetInternalPos(e){this._data.splice(e,1)}_sortData(){this._changedData&&this._data.sort(Wp),this._changedData=!1}bitField(){let e=[],t=8,r=0,s=0,i,o=this._bitArrays.slice();for(;o.length||r;){r===0&&(i=o.shift(),r=7);let a=Math.min(r,t),u=~(255<<a),l=i&u;s|=l<<8-t,i=i>>>a,r-=a,t-=a,(!t||!r&&!o.length)&&(e.push(s),s=0,t=8)}for(var c=e.length-1;c>0&&e[c]===0;c--)e.pop();return e}compactArray(){return this._sortData(),this._data.map($p)}};function zp(n,e){return n+bu(e)}function bu(n){let e=n;return e=e-(e>>1&1431655765),e=(e&858993459)+(e>>2&858993459),(e+(e>>4)&252645135)*16843009>>24}function Wp(n,e){return n[0]-e[0]}function $p(n){return n[1]}});function qp(n){return!!n}function Hp(n,e){return n.key}function Vp(n){return n}async function Au(n,e,t){let r=[];for(let s of n._children.compactArray())if(s instanceof qe)await Au(s,e,t);else{let i=await e(s);r.push({bitField:n._children.bitField(),children:i})}return t(r)}var vu,qe,ku=w(()=>{"use strict";vu=K(xu(),1);Zn();qe=class n{constructor(e,t,r=0){p(this,"_options");p(this,"_popCount");p(this,"_parent");p(this,"_posAtParent");p(this,"_children");p(this,"key");this._options=e,this._popCount=0,this._parent=t,this._posAtParent=r,this._children=new vu.default,this.key=null}async put(e,t){let r=await this._findNewBucketAndPos(e);r.bucket._putAt(r,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),r=t.bucket._at(t.pos);r!=null&&r.key===e&&t.bucket._delAt(t.pos)}leafCount(){return this._children.compactArray().reduce((t,r)=>r instanceof n?t+r.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 n?yield*t.eachLeafSeries():yield t}serialize(e,t){let r=[];return t(this._children.reduce((s,i,o)=>(i!=null&&(i instanceof n?s.push(i.serialize(e,t)):s.push(e(i,o))),s),r))}async asyncTransform(e,t){return Au(this,e,t)}toJSON(){return this.serialize(Hp,Vp)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(e){let t=await this._findPlace(e),r=t.bucket._at(t.pos);if(!(r instanceof n)&&r!=null&&r.key===e)return r}async _findPlace(e){let t=this._options.hash(typeof e=="string"?Kt(e):e),r=await t.take(this._options.bits),s=this._children.get(r);return s instanceof n?s._findPlace(t):{bucket:this,pos:r,hash:t,existingChild:s}}async _findNewBucketAndPos(e){let t=await this._findPlace(e);if(t.existingChild!=null&&t.existingChild.key!==e){let r=new n(this._options,t.bucket,t.pos);t.bucket._putObjectAt(t.pos,r);let s=await r._findPlace(t.existingChild.hash);return s.bucket._putAt(s,t.existingChild.key,t.existingChild.value),r._findNewBucketAndPos(t.hash)}return t}_putAt(e,t,r){this._putObjectAt(e.pos,{key:t,value:r,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(qp);if(e!=null&&!(e instanceof n)){let t=e.hash;t.untake(this._options.bits);let r={pos:this._posAtParent,hash:t,bucket:this._parent};this._parent._putAt(r,e.key,e.value)}}else this._parent._delAt(this._posAtParent)}_at(e){return this._children.get(e)}}});function jp(n,e,t){let r=Jp(e,t);return(n&r)>>>e}function Jp(n,e){return Gp[n]&Yp[Math.min(e+n-1,7)]}var Gp,Yp,as,Eu=w(()=>{"use strict";Gp=[255,254,252,248,240,224,192,128],Yp=[1,3,7,15,31,63,127,255],as=class{constructor(e){p(this,"_value");p(this,"_currentBytePos");p(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,r=0;for(;t>0&&this._haveBits();){let s=this._value[this._currentBytePos],i=this._currentBitPos+1,o=Math.min(i,t),c=jp(s,i-o,o);r=(r<<o)+c,t-=o,this._currentBitPos-=o,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return r}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}}});function Cu(n){function e(t){return t instanceof cs?t:new cs(t,n)}return e}var cs,Pu=w(()=>{"use strict";yi();Eu();cs=class{constructor(e,t){p(this,"_value");p(this,"_hashFn");p(this,"_depth");p(this,"_availableBits");p(this,"_currentBufferIndex");p(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 r=0;for(;t>0;){let s=this._buffers[this._currentBufferIndex],i=Math.min(s.availableBits(),t),o=s.take(i);r=(r<<i)+o,t-=i,this._availableBits-=i,s.availableBits()===0&&this._currentBufferIndex++}return r}untake(e){let t=e;for(;t>0;){let r=this._buffers[this._currentBufferIndex],s=Math.min(r.totalBits()-r.availableBits(),t);r.untake(s),t-=s,this._availableBits+=s,this._currentBufferIndex>0&&r.totalBits()===r.availableBits()&&(this._depth--,this._currentBufferIndex--)}}async _produceMoreBits(){this._depth++;let e=this._depth>0?kr([this._value,Uint8Array.from([this._depth])]):this._value,t=await this._hashFn(e),r=new as(t);this._buffers.push(r),this._availableBits+=r.availableBits()}}});function Iu(n){if(n==null||n.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:n.bits??8,hash:Cu(n.hashFn)};return new qe(e)}var Bu=w(()=>{"use strict";ku();Pu()});async function Qp(n){return(await yu.encode(n)).slice(0,8).reverse()}async function*Tu(n,e,t,r){let s=n._children,i=(n.tableSize()-1).toString(16).length,o=[],c=0n;for(let f=0;f<s.length;f++){let y=s.get(f);if(y==null)continue;let k=f.toString(16).toUpperCase().padStart(i,"0");if(y instanceof qe){let m;for await(let b of Tu(y,e,null,r))m=b;if(m==null)throw new Error("Could not flush sharded directory, no subshard found");o.push({Name:k,Tsize:Number(m.size),Hash:m.cid}),c+=m.size}else if(Zp(y.value)){let m=y.value,b;for await(let A of m.flush(e))b=A,yield b;if(b==null)throw new Error("Did not flush dir");let v=k+y.key;o.push({Name:v,Tsize:Number(b.size),Hash:b.cid}),c+=b.size}else{let m=y.value;if(m.cid==null)continue;let b=k+y.key,v=m.size;o.push({Name:b,Tsize:Number(v),Hash:m.cid}),c+=BigInt(v??0)}}let a=Uint8Array.from(s.bitField().reverse()),u=new Q({type:"hamt-sharded-directory",data:a,fanout:BigInt(n.tableSize()),hashType:Du,mtime:t?.mtime,mode:t?.mode}),l={Data:u.marshal(),Links:o},h=ne(re(l)),g=await be(h,e,r),d=BigInt(h.byteLength)+c;yield{cid:g,unixfs:u,size:d}}function Zp(n){return typeof n.flush=="function"}function Fu(n,e,t){let r=n._children,s=(n.tableSize()-1).toString(16).length,i=[];for(let u=0;u<r.length;u++){let l=r.get(u);if(l==null)continue;let h=u.toString(16).toUpperCase().padStart(s,"0");if(l instanceof qe){let g=Fu(l,null,t);i.push({Name:h,Tsize:Number(g),Hash:t.cidVersion===0?zr:Wr})}else if(typeof l.value.flush=="function"){let d=l.value.nodeSize();i.push({Name:h+l.key,Tsize:Number(d),Hash:t.cidVersion===0?zr:Wr})}else{let g=l.value;if(g.cid==null)continue;let d=h+l.key,f=g.size;i.push({Name:d,Tsize:Number(f),Hash:g.cid})}}let o=Uint8Array.from(r.bitField().reverse()),c=new Q({type:"hamt-sharded-directory",data:o,fanout:BigInt(n.tableSize()),hashType:Du,mtime:e?.mtime,mode:e?.mode});return ne(re({Data:c.marshal(),Links:i})).length}var Du,Xp,ko,Ru,Mu=w(()=>{"use strict";st();wu();Bu();Wt();ss();$t();Du=BigInt(34),Xp=8,ko=class extends ke{constructor(t,r){super(t,r);p(this,"_bucket");this._bucket=Iu({hashFn:Qp,bits:r.shardFanoutBits??Xp})}async put(t,r){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,await this._bucket.put(t,r)}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:r}of this._bucket.eachLeafSeries())yield{key:t,child:r}}estimateNodeSize(){return this.nodeSize!==void 0?this.nodeSize:(this.nodeSize=Fu(this._bucket,this,this.options),this.nodeSize)}async*flush(t){for await(let r of Tu(this._bucket,t,this,this.options))yield{...r,path:this.path}}},Ru=ko});async function Eo(n,e,t,r){let s=e;e instanceof ct&&e.estimateNodeSize()>t&&(s=await eg(e,r));let i=s.parent;if(i!=null){if(s!==e){if(n!=null&&(n.parent=s),s.parentKey==null)throw new Error("No parent key found");await i.put(s.parentKey,s)}return Eo(s,i,t,r)}return s}async function eg(n,e){let t=new Ru({root:n.root,dir:!0,parent:n.parent,parentKey:n.parentKey,path:n.path,dirty:n.dirty,flat:!1,mtime:n.mtime,mode:n.mode},e);for(let{key:r,child:s}of n.eachChildSeries())await t.put(r,s);return t}var Nu=w(()=>{"use strict";Ao();Mu()});var Uu,Lu=w(()=>{"use strict";Uu=(n="")=>n.split(/(?<!\\)\//).filter(Boolean)});async function tg(n,e,t){let r=Uu(n.path??""),s=r.length-1,i=e,o="";for(let c=0;c<r.length;c++){let a=r[c];o+=`${o!==""?"/":""}${a}`;let u=c===s;if(i.dirty=!0,i.cid=void 0,i.size=void 0,u)await i.put(a,n),e=await Eo(null,i,t.shardSplitThresholdBytes,t);else{let l=await i.get(a);(l==null||!(l instanceof ke))&&(l=new ct({root:!1,dir:!0,parent:i,parentKey:a,path:o,dirty:!0,flat:!0,mtime:l?.unixfs?.mtime,mode:l?.unixfs?.mode},t)),await i.put(a,l),i=l}}return e}async function*_u(n,e){if(!(n instanceof ke)){n.unixfs?.isDirectory()===!0&&(yield n);return}yield*n.flush(e)}function Ou(n){return async function*(t,r){let s=new ct({root:!0,dir:!0,path:"",dirty:!0,flat:!0},n),i,o=!1;for await(let c of t){if(c==null)continue;let a=`${c.originalPath??""}`.split("/")[0];a!=null&&a!==""&&(i==null?(i=a,o=!0):i!==a&&(o=!1)),s=await tg(c,s,n),c.unixfs?.isDirectory()!==!0&&(yield c)}if(n.wrapWithDirectory||o&&s.childCount()>1)yield*_u(s,r);else for(let c of s.eachChildSeries())c!=null&&(yield*_u(c.child,r))}}var Ku=w(()=>{"use strict";Ao();ss();Nu();Lu()});var zu={};B(zu,{InvalidAvgChunkSizeError:()=>bo,InvalidChunkSizeError:()=>So,InvalidContentError:()=>Be,InvalidMinChunkSizeError:()=>xo,InvalidParametersError:()=>jt,importByteStream:()=>sg,importBytes:()=>ng,importDirectory:()=>rg,importFile:()=>Po,importer:()=>Co});async function*Co(n,e,t={}){let r;Symbol.asyncIterator in n||Symbol.iterator in n?r=n:r=[n];let s=t.wrapWithDirectory??!1,i=t.shardSplitThresholdBytes??262144,o=t.shardFanoutBits??8,c=t.cidVersion??1,a=t.rawLeaves??!0,u=t.leafType??"file",l=t.fileImportConcurrency??50,h=t.blockWriteConcurrency??10,g=t.reduceSingleLeafToSelf??!0,d=t.chunker??Ic(),f=t.chunkValidator??cu(),y=t.dagBuilder??ou({chunker:d,chunkValidator:f,wrapWithDirectory:s,layout:t.layout??vo(),bufferImporter:t.bufferImporter??Zl({cidVersion:c,rawLeaves:a,leafType:u,onProgress:t.onProgress}),blockWriteConcurrency:h,reduceSingleLeafToSelf:g,cidVersion:c,onProgress:t.onProgress,dirBuilder:t.dirBuilder,fileBuilder:t.fileBuilder}),k=t.treeBuilder??Ou({wrapWithDirectory:s,shardSplitThresholdBytes:i,shardFanoutBits:o,cidVersion:c,onProgress:t.onProgress});for await(let m of k(Ar(y(r,e),l),e))yield{cid:m.cid,path:m.path,unixfs:m.unixfs,size:m.size}}async function Po(n,e,t={}){let r=await pi(Co([n],e,t));if(r==null)throw new jt("Nothing imported");return r}async function rg(n,e,t={}){let r=await pi(Co([n],e,t));if(r==null)throw new jt("Nothing imported");return r}async function ng(n,e,t={}){return Po({content:n},e,t)}async function sg(n,e,t={}){return Po({content:n},e,t)}var Wu=w(()=>{"use strict";Sc();mi();Bc();eu();au();lu();Kr();fu();Ku();Kr()});var Ee,qr=w(()=>{"use strict";Ee=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,r){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:r,bytes:s}of e)await this.put(r,s,t),yield r}get(e,t){throw new Error(".get is not implemented")}async*getMany(e,t){for await(let r of e)yield{cid:r,bytes:this.get(r,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let r of e)await this.delete(r,t),yield r}async*getAll(e){throw new Error(".getAll is not implemented")}}});var Jt,He,$u=w(()=>{"use strict";Jt=class Jt extends Error{constructor(t="Not Found"){super(t);p(this,"name",Jt.name);p(this,"code",Jt.code)}};p(Jt,"name","NotFoundError"),p(Jt,"code","ERR_NOT_FOUND");He=Jt});var ls=w(()=>{"use strict";$u()});function ig(n){return typeof n?.then=="function"}var us,qu=w(()=>{"use strict";ls();hu();Er();nt();Nr();Mt();qr();us=class extends Ee{constructor(){super();p(this,"data");this.data=new Map}put(t,r,s){s?.signal?.throwIfAborted();let i;if(r instanceof Uint8Array)i=[r];else{let o=du(r);if(ig(o))return o.then(c=>this._put(t,c,s));i=o}return this._put(t,i,s)}_put(t,r,s){return s?.signal?.throwIfAborted(),this.data.set(J.encode(t.multihash.bytes),r),t}*get(t,r){r?.signal?.throwIfAborted();let s=this.data.get(J.encode(t.multihash.bytes));if(s==null)throw new He;yield*s}has(t,r){return r?.signal?.throwIfAborted(),this.data.has(J.encode(t.multihash.bytes))}async delete(t,r){r?.signal?.throwIfAborted(),this.data.delete(J.encode(t.multihash.bytes))}*getAll(t){t?.signal?.throwIfAborted();for(let[r,s]of this.data.entries())yield{cid:z.createV1(_t,Yn(J.decode(r))),bytes:(async function*(){yield*s})()},t?.signal?.throwIfAborted()}}});var ds,Hu=w(()=>{"use strict";ls();qr();ds=class extends Ee{put(e,t,r){return r?.signal?.throwIfAborted(),e}get(e,t){throw t?.signal?.throwIfAborted(),new He}has(e,t){return t?.signal?.throwIfAborted(),!1}async delete(e,t){t?.signal?.throwIfAborted()}async*getAll(e){e?.signal?.throwIfAborted()}}});function og(n,e){if(typeof n=="string")return ag(n);if(typeof n=="number")return ug(n,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(n)}`)}function ag(n){if(typeof n!="string"||n.length===0||n.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(n)}`);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(n);if(!e?.groups)return NaN;let{value:t,unit:r="ms"}=e.groups,s=parseFloat(t),i=r.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 Error(`Unknown unit "${i}" provided to ms.parse(). value=${JSON.stringify(n)}`)}}function cg(n){let e=Math.abs(n);return e>=315576e5?`${Math.round(n/315576e5)}y`:e>=26298e5?`${Math.round(n/26298e5)}mo`:e>=6048e5?`${Math.round(n/6048e5)}w`:e>=864e5?`${Math.round(n/864e5)}d`:e>=36e5?`${Math.round(n/36e5)}h`:e>=6e4?`${Math.round(n/6e4)}m`:e>=1e3?`${Math.round(n/1e3)}s`:`${n}ms`}function lg(n){let e=Math.abs(n);return e>=315576e5?lt(n,e,315576e5,"year"):e>=26298e5?lt(n,e,26298e5,"month"):e>=6048e5?lt(n,e,6048e5,"week"):e>=864e5?lt(n,e,864e5,"day"):e>=36e5?lt(n,e,36e5,"hour"):e>=6e4?lt(n,e,6e4,"minute"):e>=1e3?lt(n,e,1e3,"second"):`${n} ms`}function ug(n,e){if(typeof n!="number"||!Number.isFinite(n))throw Error("Value provided to ms.format() must be of type number.");return e?.long?lg(n):cg(n)}function lt(n,e,t,r){let s=e>=t*1.5;return`${Math.round(n/t)} ${r}${s?"s":""}`}var hs,Io=w(()=>{"use strict";hs=og});function Bo(n){t.debug=t,t.default=t,t.coerce=a,t.disable=i,t.enable=s,t.enabled=o,t.humanize=hs,t.destroy=u,Object.keys(n).forEach(l=>{t[l]=n[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let h=0;for(let g=0;g<l.length;g++)h=(h<<5)-h+l.charCodeAt(g),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(l,h){let g,d=null,f,y;function k(...m){if(!k.enabled)return;let b=k,v=Number(new Date),A=v-(g||v);b.diff=A,b.prev=g,b.curr=v,g=v,m[0]=t.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let E=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(x,P)=>{if(x==="%%")return"%";E++;let G=t.formatters[P];if(typeof G=="function"){let he=m[E];x=G.call(b,he),m.splice(E,1),E--}return x}),t.formatArgs.call(b,m),h?.onLog!=null&&h.onLog(...m),(b.log||t.log).apply(b,m)}return k.namespace=l,k.useColors=t.useColors(),k.color=t.selectColor(l),k.extend=r,k.destroy=t.destroy,Object.defineProperty(k,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(f!==t.namespaces&&(f=t.namespaces,y=t.enabled(l)),y),set:m=>{d=m}}),typeof t.init=="function"&&t.init(k),k}function r(l,h){let g=t(this.namespace+(typeof h>"u"?":":h)+l);return g.log=this.log,g}function s(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let h,g=(typeof l=="string"?l:"").split(/[\s,]+/),d=g.length;for(h=0;h<d;h++)g[h]&&(l=g[h].replace(/\*/g,".*?"),l[0]==="-"?t.skips.push(new RegExp("^"+l.substr(1)+"$")):t.names.push(new RegExp("^"+l+"$")))}function i(){let l=[...t.names.map(c),...t.skips.map(c).map(h=>"-"+h)].join(",");return t.enable(""),l}function o(l){if(l[l.length-1]==="*")return!0;let h,g;for(h=0,g=t.skips.length;h<g;h++)if(t.skips[h].test(l))return!1;for(h=0,g=t.names.length;h<g;h++)if(t.names[h].test(l))return!0;return!1}function c(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function a(l){return l instanceof Error?l.stack??l.message:l}function u(){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 Vu=w(()=>{"use strict";Io()});function hg(){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 fg(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+hs(this.diff),!this.useColors)return;let e="color: "+this.color;n.splice(1,0,e,"color: inherit");let t=0,r=0;n[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(r=t))}),n.splice(r,0,e)}function gg(n){try{n?fs?.setItem("debug",n):fs?.removeItem("debug")}catch{}}function mg(){let n;try{n=fs?.getItem("debug")}catch{}return!n&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(n=globalThis.process.env.DEBUG),n}function yg(){try{return localStorage}catch{}}function wg(n){n.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var fs,dg,pg,Gu,Yu=w(()=>{"use strict";Io();Vu();fs=yg(),dg=["#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"];pg=console.debug??console.log??(()=>{});Gu=Bo({formatArgs:fg,save:gg,load:mg,useColors:hg,setupFormatters:wg,colors:dg,storage:fs,log:pg})});var X,ju=w(()=>{"use strict";Yu();X=Gu});function Ju(n,e=""){let t=Qu(n.message),r=Qu(n.stack);return t!=null&&r!=null?r.includes(t)?`${r.split(`
950
+ `}}});var $n={};B($n,{RecoverySimulator:()=>Et,educationalModules:()=>Wn,getAllTopics:()=>fi,getExplainer:()=>hi,searchExplainers:()=>pi});var Ar=w(()=>{"use strict";mc();yc()});function Wh(n){return n[Symbol.asyncIterator]!=null}function $h(n){if(Wh(n))return(async()=>{for await(let e of n)return e})();for(let e of n)return e}var gi,Sc=w(()=>{"use strict";gi=$h});function qh(n){return n[Symbol.asyncIterator]!=null}function Hh(n,e=1){return e=Number(e),qh(n)?(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 r of n)for(t.push(r);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 r of n)for(t.push(r);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 qn,mi=w(()=>{"use strict";qn=Hh});async function*kr(n,e=1){for await(let t of qn(n,e)){let r=t.map(async s=>s().then(i=>({ok:!0,value:i}),i=>({ok:!1,err:i})));for(let s=0;s<r.length;s++){let i=await r[s];if(i.ok)yield i.value;else throw i.err}}}var yi=w(()=>{"use strict";mi()});function Pe(n=0){return new Uint8Array(n)}function te(n=0){return new Uint8Array(n)}var nt=w(()=>{"use strict"});var xc=w(()=>{"use strict"});function Er(n,e){e==null&&(e=n.reduce((s,i)=>s+i.length,0));let t=te(e),r=0;for(let s of n)t.set(s,r),r+=s.length;return t}var wi=w(()=>{"use strict";nt();xc()});function vc(n,e){if(n===e)return!0;if(n.byteLength!==e.byteLength)return!1;for(let t=0;t<n.byteLength;t++)if(n[t]!==e[t])return!1;return!0}var Ac=w(()=>{"use strict"});function kc(n,e){if(e==null||e<0)throw new RangeError("index is out of bounds");let t=0;for(let r of n){let s=t+r.byteLength;if(e<s)return{buf:r,index:e-t};t=s}throw new RangeError("index is out of bounds")}function Hn(n){return!!n?.[Cc]}var Cc,Ec,Pt,Pc=w(()=>{"use strict";nt();wi();Ac();Cc=Symbol.for("@achingbrain/uint8arraylist");Pt=class n{constructor(...e){p(this,"bufs");p(this,"length");p(this,Ec,!0);this.bufs=[],this.length=0,e.length>0&&this.appendAll(e)}*[(Ec=Cc,Symbol.iterator)](){yield*this.bufs}get byteLength(){return this.length}append(...e){this.appendAll(e)}appendAll(e){let t=0;for(let r of e)if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.push(r);else if(Hn(r))t+=r.byteLength,this.bufs.push(...r.bufs);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 r of e.reverse())if(r instanceof Uint8Array)t+=r.byteLength,this.bufs.unshift(r);else if(Hn(r))t+=r.byteLength,this.bufs.unshift(...r.bufs);else throw new Error("Could not prepend value, must be an Uint8Array or a Uint8ArrayList");this.length+=t}get(e){let t=kc(this.bufs,e);return t.buf[t.index]}set(e,t){let r=kc(this.bufs,e);r.buf[r.index]=t}write(e,t=0){if(e instanceof Uint8Array)for(let r=0;r<e.length;r++)this.set(t+r,e[r]);else if(Hn(e))for(let r=0;r<e.length;r++)this.set(t+r,e.get(r));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:r,length:s}=this._subList(e,t);return Er(r,s)}subarray(e,t){let{bufs:r,length:s}=this._subList(e,t);return r.length===1?r[0]:Er(r,s)}sublist(e,t){let{bufs:r,length:s}=this._subList(e,t),i=new n;return i.length=s,i.bufs=[...r],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 r=[],s=0;for(let i=0;i<this.bufs.length;i++){let o=this.bufs[i],c=s,a=c+o.byteLength;if(s=a,e>=a)continue;let u=e>=c&&e<a,l=t>c&&t<=a;if(u&&l){if(e===c&&t===a){r.push(o);break}let h=e-c;r.push(o.subarray(h,h+(t-e)));break}if(u){if(e===0){r.push(o);continue}r.push(o.subarray(e-c));continue}if(l){if(t===a){r.push(o);break}r.push(o.subarray(0,t-c));break}r.push(o)}return{bufs:r,length:t-e}}indexOf(e,t=0){if(!Hn(e)&&!(e instanceof Uint8Array))throw new TypeError('The "value" argument must be a Uint8ArrayList or Uint8Array');let r=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=r.byteLength;if(s===0)throw new TypeError("search must be at least 1 byte long");let i=256,o=new Int32Array(i);for(let h=0;h<i;h++)o[h]=-1;for(let h=0;h<s;h++)o[r[h]]=h;let c=o,a=this.byteLength-r.byteLength,u=r.byteLength-1,l;for(let h=t;h<=a;h+=l){l=0;for(let g=u;g>=0;g--){let d=this.get(h+g);if(r[g]!==d){l=Math.max(1,g-c[d]);break}}if(l===0)return h}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 r=te(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setInt8(0,t),this.write(r,e)}getInt16(e,t){let r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt16(0,t)}setInt16(e,t,r){let s=Pe(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt16(0,t,r),this.write(s,e)}getInt32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getInt32(0,t)}setInt32(e,t,r){let s=Pe(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setInt32(0,t,r),this.write(s,e)}getBigInt64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigInt64(0,t)}setBigInt64(e,t,r){let s=Pe(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigInt64(0,t,r),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 r=te(1);new DataView(r.buffer,r.byteOffset,r.byteLength).setUint8(0,t),this.write(r,e)}getUint16(e,t){let r=this.subarray(e,e+2);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint16(0,t)}setUint16(e,t,r){let s=Pe(2);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint16(0,t,r),this.write(s,e)}getUint32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getUint32(0,t)}setUint32(e,t,r){let s=Pe(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setUint32(0,t,r),this.write(s,e)}getBigUint64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getBigUint64(0,t)}setBigUint64(e,t,r){let s=Pe(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setBigUint64(0,t,r),this.write(s,e)}getFloat32(e,t){let r=this.subarray(e,e+4);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat32(0,t)}setFloat32(e,t,r){let s=Pe(4);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat32(0,t,r),this.write(s,e)}getFloat64(e,t){let r=this.subarray(e,e+8);return new DataView(r.buffer,r.byteOffset,r.byteLength).getFloat64(0,t)}setFloat64(e,t,r){let s=Pe(8);new DataView(s.buffer,s.byteOffset,s.byteLength).setFloat64(0,t,r),this.write(s,e)}equals(e){if(e==null||!(e instanceof n)||e.bufs.length!==this.bufs.length)return!1;for(let t=0;t<this.bufs.length;t++)if(!vc(this.bufs[t],e.bufs[t]))return!1;return!0}static fromUint8Arrays(e,t){let r=new n;return r.bufs=e,t==null&&(t=e.reduce((s,i)=>s+i.byteLength,0)),r.length=t,r}}});var Vh,Ic,Bc=w(()=>{"use strict";Pc();Vh=262144,Ic=(n={})=>{let e=n.chunkSize??Vh;return async function*(r){let s=new Pt,i=0,o=!1;for await(let c of r)for(s.append(c),i+=c.length;i>=e;)if(yield s.slice(0,e),o=!0,e===s.length)s=new Pt,i=0;else{let a=new Pt;a.append(s.sublist(e)),s=a,i-=e}(!o||i>0)&&(yield s.subarray(0,i))}}});var It={};B(It,{coerce:()=>ue,empty:()=>Dc,equals:()=>bi,fromHex:()=>Yh,fromString:()=>Si,isBinary:()=>jh,toHex:()=>Gh,toString:()=>xi});function Gh(n){return n.reduce((e,t)=>e+t.toString(16).padStart(2,"0"),"")}function Yh(n){let e=n.match(/../g);return e!=null?new Uint8Array(e.map(t=>parseInt(t,16))):Dc}function bi(n,e){if(n===e)return!0;if(n.byteLength!==e.byteLength)return!1;for(let t=0;t<n.byteLength;t++)if(n[t]!==e[t])return!1;return!0}function ue(n){if(n instanceof Uint8Array&&n.constructor.name==="Uint8Array")return n;if(n instanceof ArrayBuffer)return new Uint8Array(n);if(ArrayBuffer.isView(n))return new Uint8Array(n.buffer,n.byteOffset,n.byteLength);throw new Error("Unknown type, must be binary type")}function jh(n){return n instanceof ArrayBuffer||ArrayBuffer.isView(n)}function Si(n){return new TextEncoder().encode(n)}function xi(n){return new TextDecoder().decode(n)}var Dc,Ke=w(()=>{"use strict";Dc=new Uint8Array(0)});function Jh(n,e){if(n.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),r=0;r<t.length;r++)t[r]=255;for(var s=0;s<n.length;s++){var i=n.charAt(s),o=i.charCodeAt(0);if(t[o]!==255)throw new TypeError(i+" is ambiguous");t[o]=s}var c=n.length,a=n.charAt(0),u=Math.log(c)/Math.log(256),l=Math.log(256)/Math.log(c);function h(f){if(f instanceof Uint8Array||(ArrayBuffer.isView(f)?f=new Uint8Array(f.buffer,f.byteOffset,f.byteLength):Array.isArray(f)&&(f=Uint8Array.from(f))),!(f instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(f.length===0)return"";for(var y=0,k=0,m=0,b=f.length;m!==b&&f[m]===0;)m++,y++;for(var v=(b-m)*l+1>>>0,A=new Uint8Array(v);m!==b;){for(var E=f[m],C=0,x=v-1;(E!==0||C<k)&&x!==-1;x--,C++)E+=256*A[x]>>>0,A[x]=E%c>>>0,E=E/c>>>0;if(E!==0)throw new Error("Non-zero carry");k=C,m++}for(var P=v-k;P!==v&&A[P]===0;)P++;for(var G=a.repeat(y);P<v;++P)G+=n.charAt(A[P]);return G}function g(f){if(typeof f!="string")throw new TypeError("Expected String");if(f.length===0)return new Uint8Array;var y=0;if(f[y]!==" "){for(var k=0,m=0;f[y]===a;)k++,y++;for(var b=(f.length-y)*u+1>>>0,v=new Uint8Array(b);f[y];){var A=t[f.charCodeAt(y)];if(A===255)return;for(var E=0,C=b-1;(A!==0||E<m)&&C!==-1;C--,E++)A+=c*v[C]>>>0,v[C]=A%256>>>0,A=A/256>>>0;if(A!==0)throw new Error("Non-zero carry");m=E,y++}if(f[y]!==" "){for(var x=b-m;x!==b&&v[x]===0;)x++;for(var P=new Uint8Array(k+(b-x)),G=k;x!==b;)P[G++]=v[x++];return P}}}function d(f){var y=g(f);if(y)return y;throw new Error(`Non-${e} character`)}return{encode:h,decodeUnsafe:g,decode:d}}var Qh,Xh,Rc,Tc=w(()=>{"use strict";Qh=Jh,Xh=Qh,Rc=Xh});function Fc(n,e){return new ki({...n.decoders??{[n.prefix]:n},...e.decoders??{[e.prefix]:e}})}function Bt({name:n,prefix:e,encode:t,decode:r}){return new Ei(n,e,t,r)}function ze({name:n,prefix:e,alphabet:t}){let{encode:r,decode:s}=Rc(t,n);return Bt({prefix:e,name:n,encode:r,decode:i=>ue(s(i))})}function Zh(n,e,t,r){let s=n.length;for(;n[s-1]==="=";)--s;let i=new Uint8Array(s*t/8|0),o=0,c=0,a=0;for(let u=0;u<s;++u){let l=e[n[u]];if(l===void 0)throw new SyntaxError(`Non-${r} character`);c=c<<t|l,o+=t,o>=8&&(o-=8,i[a++]=255&c>>o)}if(o>=t||(255&c<<8-o)!==0)throw new SyntaxError("Unexpected end of data");return i}function ef(n,e,t){let r=e[e.length-1]==="=",s=(1<<t)-1,i="",o=0,c=0;for(let a=0;a<n.length;++a)for(c=c<<8|n[a],o+=8;o>t;)o-=t,i+=e[s&c>>o];if(o!==0&&(i+=e[s&c<<t-o]),r)for(;(i.length*t&7)!==0;)i+="=";return i}function tf(n){let e={};for(let t=0;t<n.length;++t)e[n[t]]=t;return e}function U({name:n,prefix:e,bitsPerChar:t,alphabet:r}){let s=tf(r);return Bt({prefix:e,name:n,encode(i){return ef(i,r,t)},decode(i){return Zh(i,s,t,n)}})}var vi,Ai,ki,Ei,me=w(()=>{"use strict";Ke();Tc();vi=class{constructor(e,t,r){p(this,"name");p(this,"prefix");p(this,"baseEncode");this.name=e,this.prefix=t,this.baseEncode=r}encode(e){if(e instanceof Uint8Array)return`${this.prefix}${this.baseEncode(e)}`;throw Error("Unknown type, must be binary type")}},Ai=class{constructor(e,t,r){p(this,"name");p(this,"prefix");p(this,"baseDecode");p(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=r}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 Fc(this,e)}},ki=class{constructor(e){p(this,"decoders");this.decoders=e}or(e){return Fc(this,e)}decode(e){let t=e[0],r=this.decoders[t];if(r!=null)return r.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,r,s){p(this,"name");p(this,"prefix");p(this,"baseEncode");p(this,"baseDecode");p(this,"encoder");p(this,"decoder");this.name=e,this.prefix=t,this.baseEncode=r,this.baseDecode=s,this.encoder=new vi(e,t,r),this.decoder=new Ai(e,t,s)}encode(e){return this.encoder.encode(e)}decode(e){return this.decoder.decode(e)}}});var Ci={};B(Ci,{base32:()=>J,base32hex:()=>of,base32hexpad:()=>cf,base32hexpadupper:()=>lf,base32hexupper:()=>af,base32pad:()=>nf,base32padupper:()=>sf,base32upper:()=>rf,base32z:()=>uf});var J,rf,nf,sf,of,af,cf,lf,uf,Cr=w(()=>{"use strict";me();J=U({prefix:"b",name:"base32",alphabet:"abcdefghijklmnopqrstuvwxyz234567",bitsPerChar:5}),rf=U({prefix:"B",name:"base32upper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567",bitsPerChar:5}),nf=U({prefix:"c",name:"base32pad",alphabet:"abcdefghijklmnopqrstuvwxyz234567=",bitsPerChar:5}),sf=U({prefix:"C",name:"base32padupper",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567=",bitsPerChar:5}),of=U({prefix:"v",name:"base32hex",alphabet:"0123456789abcdefghijklmnopqrstuv",bitsPerChar:5}),af=U({prefix:"V",name:"base32hexupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV",bitsPerChar:5}),cf=U({prefix:"t",name:"base32hexpad",alphabet:"0123456789abcdefghijklmnopqrstuv=",bitsPerChar:5}),lf=U({prefix:"T",name:"base32hexpadupper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUV=",bitsPerChar:5}),uf=U({prefix:"h",name:"base32z",alphabet:"ybndrfg8ejkmcpqxot1uwisza345h769",bitsPerChar:5})});var Pi={};B(Pi,{base36:()=>Pr,base36upper:()=>df});var Pr,df,Ii=w(()=>{"use strict";me();Pr=ze({prefix:"k",name:"base36",alphabet:"0123456789abcdefghijklmnopqrstuvwxyz"}),df=ze({prefix:"K",name:"base36upper",alphabet:"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"})});var Bi={};B(Bi,{base58btc:()=>de,base58flickr:()=>hf});var de,hf,Vn=w(()=>{"use strict";me();de=ze({name:"base58btc",prefix:"z",alphabet:"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"}),hf=ze({name:"base58flickr",prefix:"Z",alphabet:"123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"})});function Uc(n,e,t){e=e||[],t=t||0;for(var r=t;n>=mf;)e[t++]=n&255|Mc,n/=128;for(;n&gf;)e[t++]=n&255|Mc,n>>>=7;return e[t]=n|0,Uc.bytes=t-r+1,e}function Di(n,r){var t=0,r=r||0,s=0,i=r,o,c=n.length;do{if(i>=c)throw Di.bytes=0,new RangeError("Could not decode varint");o=n[i++],t+=s<28?(o&Nc)<<s:(o&Nc)*Math.pow(2,s),s+=7}while(o>=wf);return Di.bytes=i-r,t}var ff,Mc,pf,gf,mf,yf,wf,Nc,bf,Sf,xf,vf,Af,kf,Ef,Cf,Pf,If,Bf,Df,Ir,Lc=w(()=>{"use strict";ff=Uc,Mc=128,pf=127,gf=~pf,mf=Math.pow(2,31);yf=Di,wf=128,Nc=127;bf=Math.pow(2,7),Sf=Math.pow(2,14),xf=Math.pow(2,21),vf=Math.pow(2,28),Af=Math.pow(2,35),kf=Math.pow(2,42),Ef=Math.pow(2,49),Cf=Math.pow(2,56),Pf=Math.pow(2,63),If=function(n){return n<bf?1:n<Sf?2:n<xf?3:n<vf?4:n<Af?5:n<kf?6:n<Ef?7:n<Cf?8:n<Pf?9:10},Bf={encode:ff,decode:yf,encodingLength:If},Df=Bf,Ir=Df});function Br(n,e=0){return[Ir.decode(n,e),Ir.decode.bytes]}function Dt(n,e,t=0){return Ir.encode(n,e,t),e}function Rt(n){return Ir.encodingLength(n)}var Yn=w(()=>{"use strict";Lc()});function Ft(n,e){let t=e.byteLength,r=Rt(n),s=r+Rt(t),i=new Uint8Array(s+t);return Dt(n,i,0),Dt(t,i,r),i.set(e,s),new Tt(n,t,e,i)}function jn(n){let e=ue(n),[t,r]=Br(e),[s,i]=Br(e.subarray(r)),o=e.subarray(r+i);if(o.byteLength!==s)throw new Error("Incorrect length");return new Tt(t,s,o,e)}function _c(n,e){if(n===e)return!0;{let t=e;return n.code===t.code&&n.size===t.size&&t.bytes instanceof Uint8Array&&bi(n.bytes,t.bytes)}}var Tt,Nt=w(()=>{"use strict";Ke();Yn();Tt=class{constructor(e,t,r,s){p(this,"code");p(this,"size");p(this,"digest");p(this,"bytes");this.code=e,this.size=t,this.digest=r,this.bytes=s}}});var Ri=w(()=>{"use strict"});function Oc(n,e){let{bytes:t,version:r}=n;return r===0?Tf(t,Ti(n),e??de.encoder):Ff(t,Ti(n),e??J.encoder)}function Ti(n){let e=Kc.get(n);if(e==null){let t=new Map;return Kc.set(n,t),t}return e}function Rf(n,e){switch(n[0]){case"Q":{let t=e??de;return[de.prefix,t.decode(`${de.prefix}${n}`)]}case de.prefix:{let t=e??de;return[de.prefix,t.decode(n)]}case J.prefix:{let t=e??J;return[J.prefix,t.decode(n)]}case Pr.prefix:{let t=e??Pr;return[Pr.prefix,t.decode(n)]}default:{if(e==null)throw Error("To parse non base32, base36 or base58btc encoded CID multibase decoder must be provided");return[n[0],e.decode(n)]}}}function Tf(n,e,t){let{prefix:r}=t;if(r!==de.prefix)throw Error(`Cannot string encode V0 in ${t.name} encoding`);let s=e.get(r);if(s==null){let i=t.encode(n).slice(1);return e.set(r,i),i}else return s}function Ff(n,e,t){let{prefix:r}=t,s=e.get(r);if(s==null){let i=t.encode(n);return e.set(r,i),i}else return s}function zc(n,e,t){let r=Rt(n),s=r+Rt(e),i=new Uint8Array(s+t.byteLength);return Dt(n,i,0),Dt(e,i,r),i.set(t,s),i}var Kc,Wc,K,Dr,Mf,Nf,st=w(()=>{"use strict";Cr();Ii();Vn();Ke();Nt();Yn();Ri();Kc=new WeakMap;K=class n{constructor(e,t,r,s){p(this,"code");p(this,"version");p(this,"multihash");p(this,"bytes");p(this,"/");p(this,Wc,"CID");this.code=t,this.version=e,this.multihash=r,this.bytes=s,this["/"]=s}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!==Mf)throw new Error("Cannot convert non sha2-256 multihash CID to CIDv0");return n.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,r=Ft(e,t);return n.createV1(this.code,r)}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 n.equals(this,e)}static equals(e,t){let r=t;return r!=null&&e.code===r.code&&e.version===r.version&&_c(e.multihash,r.multihash)}toString(e){return Oc(this,e)}toJSON(){return{"/":Oc(this)}}link(){return this}[(Wc=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 n)return t;if(t["/"]!=null&&t["/"]===t.bytes||t.asCID===t){let{version:r,code:s,multihash:i,bytes:o}=t;return new n(r,s,i,o??zc(r,s,i.bytes))}else if(t[Nf]===!0){let{version:r,multihash:s,code:i}=t,o=jn(s);return n.create(r,i,o)}else return null}static create(e,t,r){if(typeof t!="number")throw new Error("String codecs are no longer supported");if(!(r.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 n(e,t,r,r.bytes)}case 1:{let s=zc(e,t,r.bytes);return new n(e,t,r,s)}default:throw new Error("Invalid version")}}static createV0(e){return n.create(0,Dr,e)}static createV1(e,t){return n.create(1,e,t)}static decode(e){let[t,r]=n.decodeFirst(e);if(r.length!==0)throw new Error("Incorrect length");return t}static decodeFirst(e){let t=n.inspectBytes(e),r=t.size-t.multihashSize,s=ue(e.subarray(r,r+t.multihashSize));if(s.byteLength!==t.multihashSize)throw new Error("Incorrect length");let i=s.subarray(t.multihashSize-t.digestSize),o=new Tt(t.multihashCode,t.digestSize,i,s);return[t.version===0?n.createV0(o):n.createV1(t.codec,o),e.subarray(t.size)]}static inspectBytes(e){let t=0,r=()=>{let[h,g]=Br(e.subarray(t));return t+=g,h},s=r(),i=Dr;if(s===18?(s=0,t=0):i=r(),s!==0&&s!==1)throw new RangeError(`Invalid CID version ${s}`);let o=t,c=r(),a=r(),u=t+a,l=u-o;return{version:s,codec:i,multihashCode:c,digestSize:a,multihashSize:l,size:u}}static parse(e,t){let[r,s]=Rf(e,t),i=n.decode(s);if(i.version===0&&e[0]!=="Q")throw Error("Version 0 CID string must not include multibase prefix");return Ti(i).set(r,e),i}};Dr=112,Mf=18;Nf=Symbol.for("@ipld/js-cid/CID")});function Fi(n,e){let t=0;for(let r=0;;r+=7){if(r>=64)throw new Error("protobuf: varint overflow");if(e>=n.length)throw new Error("protobuf: unexpected end of data");let s=n[e++];if(t+=r<28?(s&127)<<r:(s&127)*2**r,s<128)break}return[t,e]}function Jn(n,e){let t;[t,e]=Fi(n,e);let r=e+t;if(t<0||r<0)throw new Error("protobuf: invalid length");if(r>n.length)throw new Error("protobuf: unexpected end of data");return[n.subarray(e,r),r]}function $c(n,e){let t;return[t,e]=Fi(n,e),[t&7,t>>3,e]}function Lf(n){let e={},t=n.length,r=0;for(;r<t;){let s,i;if([s,i,r]=$c(n,r),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,r]=Jn(n,r)}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,r]=Jn(n,r),e.Name=Uf.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,r]=Fi(n,r)}else throw new Error(`protobuf: (PBLink) invalid fieldNumber, expected 1, 2 or 3, got ${i}`)}if(r>t)throw new Error("protobuf: (PBLink) unexpected end of data");return e}function qc(n){let e=n.length,t=0,r,s=!1,i;for(;t<e;){let c,a;if([c,a,t]=$c(n,t),c!==2)throw new Error(`protobuf: (PBNode) invalid wireType, expected 2, got ${c}`);if(a===1){if(i)throw new Error("protobuf: (PBNode) duplicate Data section");[i,t]=Jn(n,t),r&&(s=!0)}else if(a===2){if(s)throw new Error("protobuf: (PBNode) duplicate Links section");r||(r=[]);let u;[u,t]=Jn(n,t),r.push(Lf(u))}else throw new Error(`protobuf: (PBNode) invalid fieldNumber, expected 1 or 2, got ${a}`)}if(t>e)throw new Error("protobuf: (PBNode) unexpected end of data");let o={};return i&&(o.Data=i),o.Links=r||[],o}var Uf,Hc=w(()=>{"use strict";Uf=new TextDecoder});function Of(n,e){let t=e.length;if(typeof n.Tsize=="number"){if(n.Tsize<0)throw new Error("Tsize cannot be negative");if(!Number.isSafeInteger(n.Tsize))throw new Error("Tsize too large for encoding");t=Rr(e,t,n.Tsize)-1,e[t]=24}if(typeof n.Name=="string"){let r=Gc.encode(n.Name);t-=r.length,e.set(r,t),t=Rr(e,t,r.length)-1,e[t]=18}return n.Hash&&(t-=n.Hash.length,e.set(n.Hash,t),t=Rr(e,t,n.Hash.length)-1,e[t]=10),e.length-t}function Yc(n){let e=zf(n),t=new Uint8Array(e),r=e;if(n.Data&&(r-=n.Data.length,t.set(n.Data,r),r=Rr(t,r,n.Data.length)-1,t[r]=10),n.Links)for(let s=n.Links.length-1;s>=0;s--){let i=Of(n.Links[s],t.subarray(0,r));r-=i,r=Rr(t,r,i)-1,t[r]=18}return t}function Kf(n){let e=0;if(n.Hash){let t=n.Hash.length;e+=1+t+Ut(t)}if(typeof n.Name=="string"){let t=Gc.encode(n.Name).length;e+=1+t+Ut(t)}return typeof n.Tsize=="number"&&(e+=1+Ut(n.Tsize)),e}function zf(n){let e=0;if(n.Data){let t=n.Data.length;e+=1+t+Ut(t)}if(n.Links)for(let t of n.Links){let r=Kf(t);e+=1+r+Ut(r)}return e}function Rr(n,e,t){e-=Ut(t);let r=e;for(;t>=_f;)n[e++]=t&127|128,t/=128;for(;t>=128;)n[e++]=t&127|128,t>>>=7;return n[e]=t,r}function Ut(n){return n%2===0&&n++,Math.floor((Wf(n)+6)/7)}function Wf(n){let e=0;return n>=Vc&&(n=Math.floor(n/Vc),e=32),n>=65536&&(n>>>=16,e+=16),n>=256&&(n>>>=8,e+=8),e+$f[n]}var Gc,Vc,_f,$f,jc=w(()=>{"use strict";Gc=new TextEncoder,Vc=2**32,_f=2**31;$f=[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 Qc(n,e){if(n===e)return 0;let t=n.Name?Mi.encode(n.Name):[],r=e.Name?Mi.encode(e.Name):[],s=t.length,i=r.length;for(let o=0,c=Math.min(s,i);o<c;++o)if(t[o]!==r[o]){s=t[o],i=r[o];break}return s<i?-1:i<s?1:0}function Jc(n,e){return!Object.keys(n).some(t=>!e.includes(t))}function Xc(n){if(typeof n.asCID=="object"){let t=K.asCID(n);if(!t)throw new TypeError("Invalid DAG-PB form");return{Hash:t}}if(typeof n!="object"||Array.isArray(n))throw new TypeError("Invalid DAG-PB form");let e={};if(n.Hash){let t=K.asCID(n.Hash);try{t||(typeof n.Hash=="string"?t=K.parse(n.Hash):n.Hash instanceof Uint8Array&&(t=K.decode(n.Hash)))}catch(r){throw new TypeError(`Invalid DAG-PB form: ${r.message}`)}t&&(e.Hash=t)}if(!e.Hash)throw new TypeError("Invalid DAG-PB form");return typeof n.Name=="string"&&(e.Name=n.Name),typeof n.Tsize=="number"&&(e.Tsize=n.Tsize),e}function re(n){if((n instanceof Uint8Array||typeof n=="string")&&(n={Data:n}),typeof n!="object"||Array.isArray(n))throw new TypeError("Invalid DAG-PB form");let e={};if(n.Data!==void 0)if(typeof n.Data=="string")e.Data=Mi.encode(n.Data);else if(n.Data instanceof Uint8Array)e.Data=n.Data;else throw new TypeError("Invalid DAG-PB form");if(n.Links!==void 0)if(Array.isArray(n.Links))e.Links=n.Links.map(Xc),e.Links.sort(Qc);else throw new TypeError("Invalid DAG-PB form");else e.Links=[];return e}function Ni(n){if(!n||typeof n!="object"||Array.isArray(n)||n instanceof Uint8Array||n["/"]&&n["/"]===n.bytes)throw new TypeError("Invalid DAG-PB form");if(!Jc(n,qf))throw new TypeError("Invalid DAG-PB form (extraneous properties)");if(n.Data!==void 0&&!(n.Data instanceof Uint8Array))throw new TypeError("Invalid DAG-PB form (Data must be bytes)");if(!Array.isArray(n.Links))throw new TypeError("Invalid DAG-PB form (Links must be a list)");for(let e=0;e<n.Links.length;e++){let t=n.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(!Jc(t,Hf))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&&Qc(t,n.Links[e-1])===-1)throw new TypeError("Invalid DAG-PB form (links must be sorted by Name bytes)")}}function Zc(n,e=[]){return re({Data:n,Links:e})}function el(n,e,t){return Xc({Hash:t,Name:n,Tsize:e})}function tl(n){return n instanceof ArrayBuffer?new Uint8Array(n,0,n.byteLength):n}var qf,Hf,Mi,rl=w(()=>{"use strict";st();qf=["Data","Links"],Hf=["Hash","Name","Tsize"],Mi=new TextEncoder});var Tr={};B(Tr,{code:()=>Gf,createLink:()=>el,createNode:()=>Zc,decode:()=>Yf,encode:()=>ne,name:()=>Vf,prepare:()=>re,validate:()=>Ni});function ne(n){Ni(n);let e={};return n.Links&&(e.Links=n.Links.map(t=>{let r={};return t.Hash&&(r.Hash=t.Hash.bytes),t.Name!==void 0&&(r.Name=t.Name),t.Tsize!==void 0&&(r.Tsize=t.Tsize),r})),n.Data&&(e.Data=n.Data),Yc(e)}function Yf(n){let e=tl(n),t=qc(e),r={};return t.Data&&(r.Data=t.Data),t.Links&&(r.Links=t.Links.map(s=>{let i={};try{i.Hash=K.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})),r}var Vf,Gf,it=w(()=>{"use strict";st();Hc();jc();rl();Vf="dag-pb",Gf=112});var Lt,Fr,_t,Qn,Ui=w(()=>{"use strict";Lt=class Lt extends Error{constructor(t="Invalid type"){super(t);p(this,"name",Lt.name);p(this,"code",Lt.code)}};p(Lt,"name","InvalidTypeError"),p(Lt,"code","ERR_INVALID_TYPE");Fr=Lt,_t=class _t extends Error{constructor(t="Invalid message"){super(t);p(this,"name",_t.name);p(this,"code",_t.code)}};p(_t,"name","InvalidUnixFSMessageError"),p(_t,"code","ERR_INVALID_MESSAGE");Qn=_t});function Mr(n){if(n<jf)return 1;if(n<Jf)return 2;if(n<Qf)return 3;if(n<nl)return 4;if(n<sl)return 5;if(n<il)return 6;if(n<ol)return 7;if(Number.MAX_SAFE_INTEGER!=null&&n>Number.MAX_SAFE_INTEGER)throw new RangeError("Could not encode varint");return 8}function al(n,e,t=0){switch(Mr(n)){case 8:e[t++]=n&255|V,n/=128;case 7:e[t++]=n&255|V,n/=128;case 6:e[t++]=n&255|V,n/=128;case 5:e[t++]=n&255|V,n/=128;case 4:e[t++]=n&255|V,n>>>=7;case 3:e[t++]=n&255|V,n>>>=7;case 2:e[t++]=n&255|V,n>>>=7;case 1:{e[t++]=n&255,n>>>=7;break}default:throw new Error("unreachable")}return e}function cl(n,e){let t=n[e],r=0;if(r+=t&We,t<V||(t=n[e+1],r+=(t&We)<<7,t<V)||(t=n[e+2],r+=(t&We)<<14,t<V)||(t=n[e+3],r+=(t&We)<<21,t<V)||(t=n[e+4],r+=(t&We)*nl,t<V)||(t=n[e+5],r+=(t&We)*sl,t<V)||(t=n[e+6],r+=(t&We)*il,t<V)||(t=n[e+7],r+=(t&We)*ol,t<V))return r;throw new RangeError("Could not decode varint")}var jf,Jf,Qf,nl,sl,il,ol,V,We,Li=w(()=>{"use strict";nt();jf=Math.pow(2,7),Jf=Math.pow(2,14),Qf=Math.pow(2,21),nl=Math.pow(2,28),sl=Math.pow(2,35),il=Math.pow(2,42),ol=Math.pow(2,49),V=128,We=127});function ll(n,e,t){_i[0]=n,e[t]=$e[0],e[t+1]=$e[1],e[t+2]=$e[2],e[t+3]=$e[3]}function ul(n,e){return $e[0]=n[e],$e[1]=n[e+1],$e[2]=n[e+2],$e[3]=n[e+3],_i[0]}function dl(n,e,t){Oi[0]=n,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 hl(n,e){return W[0]=n[e],W[1]=n[e+1],W[2]=n[e+2],W[3]=n[e+3],W[4]=n[e+4],W[5]=n[e+5],W[6]=n[e+6],W[7]=n[e+7],Oi[0]}var _i,$e,Oi,W,Ki=w(()=>{"use strict";_i=new Float32Array([-0]),$e=new Uint8Array(_i.buffer);Oi=new Float64Array([-0]),W=new Uint8Array(Oi.buffer)});var Xf,Zf,se,ot,fl,zi=w(()=>{"use strict";Xf=BigInt(Number.MAX_SAFE_INTEGER),Zf=BigInt(Number.MIN_SAFE_INTEGER),se=class n{constructor(e,t){p(this,"lo");p(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,r=~this.hi>>>0;return t===0&&(r=r+1>>>0),-(t+r*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,r=~this.hi>>>0;return t===0&&(r=r+1>>>0),-(BigInt(t)+(BigInt(r)<<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,r=this.hi>>>24;return r===0?t===0?e<16384?e<128?1:2:e<2097152?3:4:t<16384?t<128?5:6:t<2097152?7:8:r<128?9:10}static fromBigInt(e){if(e===0n)return ot;if(e<Xf&&e>Zf)return this.fromNumber(Number(e));let t=e<0n;t&&(e=-e);let r=e>>32n,s=e-(r<<32n);return t&&(r=~r|0n,s=~s|0n,++s>fl&&(s=0n,++r>fl&&(r=0n))),new n(Number(s),Number(r))}static fromNumber(e){if(e===0)return ot;let t=e<0;t&&(e=-e);let r=e>>>0,s=(e-r)/4294967296>>>0;return t&&(s=~s>>>0,r=~r>>>0,++r>4294967295&&(r=0,++s>4294967295&&(s=0))),new n(r,s)}static from(e){return typeof e=="number"?n.fromNumber(e):typeof e=="bigint"?n.fromBigInt(e):typeof e=="string"?n.fromBigInt(BigInt(e)):e.low!=null||e.high!=null?new n(e.low>>>0,e.high>>>0):ot}},ot=new se(0,0);ot.toBigInt=function(){return 0n};ot.zzEncode=ot.zzDecode=function(){return this};ot.length=function(){return 1};fl=4294967296n});function pl(n){let e=0,t=0;for(let r=0;r<n.length;++r)t=n.charCodeAt(r),t<128?e+=1:t<2048?e+=2:(t&64512)===55296&&(n.charCodeAt(r+1)&64512)===56320?(++r,e+=4):e+=3;return e}function gl(n,e,t){if(t-e<1)return"";let s,i=[],o=0,c;for(;e<t;)c=n[e++],c<128?i[o++]=c:c>191&&c<224?i[o++]=(c&31)<<6|n[e++]&63:c>239&&c<365?(c=((c&7)<<18|(n[e++]&63)<<12|(n[e++]&63)<<6|n[e++]&63)-65536,i[o++]=55296+(c>>10),i[o++]=56320+(c&1023)):i[o++]=(c&15)<<12|(n[e++]&63)<<6|n[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 Wi(n,e,t){let r=t,s,i;for(let o=0;o<n.length;++o)s=n.charCodeAt(o),s<128?e[t++]=s:s<2048?(e[t++]=s>>6|192,e[t++]=s&63|128):(s&64512)===55296&&((i=n.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-r}var $i=w(()=>{"use strict"});function ye(n,e){return RangeError(`index out of range: ${n.pos} + ${e??1} > ${n.len}`)}function Xn(n,e){return(n[e-4]|n[e-3]<<8|n[e-2]<<16|n[e-1]<<24)>>>0}function Hi(n){return new qi(n instanceof Uint8Array?n:n.subarray())}var qi,Vi=w(()=>{"use strict";Li();Ki();zi();$i();qi=class{constructor(e){p(this,"buf");p(this,"pos");p(this,"len");p(this,"_slice",Uint8Array.prototype.subarray);this.buf=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 Xn(this.buf,this.pos+=4)}sfixed32(){if(this.pos+4>this.len)throw ye(this,4);return Xn(this.buf,this.pos+=4)|0}float(){if(this.pos+4>this.len)throw ye(this,4);let e=ul(this.buf,this.pos);return this.pos+=4,e}double(){if(this.pos+8>this.len)throw ye(this,4);let e=hl(this.buf,this.pos);return this.pos+=8,e}bytes(){let e=this.uint32(),t=this.pos,r=this.pos+e;if(r>this.len)throw ye(this,e);return this.pos+=e,t===r?new Uint8Array(0):this.buf.subarray(t,r)}string(){let e=this.bytes();return gl(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 se(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=Xn(this.buf,this.pos+=4),t=Xn(this.buf,this.pos+=4);return new se(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=cl(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(n,e,t){let r=Hi(n);return e.decode(r,void 0,t)}var yl=w(()=>{"use strict";Vi()});var Gi={};B(Gi,{base10:()=>ep});var ep,wl=w(()=>{"use strict";me();ep=ze({prefix:"9",name:"base10",alphabet:"0123456789"})});var Yi={};B(Yi,{base16:()=>tp,base16upper:()=>rp});var tp,rp,bl=w(()=>{"use strict";me();tp=U({prefix:"f",name:"base16",alphabet:"0123456789abcdef",bitsPerChar:4}),rp=U({prefix:"F",name:"base16upper",alphabet:"0123456789ABCDEF",bitsPerChar:4})});var ji={};B(ji,{base2:()=>np});var np,Sl=w(()=>{"use strict";me();np=U({prefix:"0",name:"base2",alphabet:"01",bitsPerChar:1})});var Ji={};B(Ji,{base256emoji:()=>cp});function op(n){return n.reduce((e,t)=>(e+=sp[t],e),"")}function ap(n){let e=[];for(let t of n){let r=t.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${t}`);let s=ip[r];if(s==null)throw new Error(`Non-base256emoji character: ${t}`);e.push(s)}return new Uint8Array(e)}var xl,sp,ip,cp,vl=w(()=>{"use strict";me();xl=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}"),sp=xl.reduce((n,e,t)=>(n[t]=e,n),[]),ip=xl.reduce((n,e,t)=>{let r=e.codePointAt(0);if(r==null)throw new Error(`Invalid character: ${e}`);return n[r]=t,n},[]);cp=Bt({prefix:"\u{1F680}",name:"base256emoji",encode:op,decode:ap})});var Xi={};B(Xi,{base64:()=>Qi,base64pad:()=>lp,base64url:()=>up,base64urlpad:()=>dp});var Qi,lp,up,dp,Zi=w(()=>{"use strict";me();Qi=U({prefix:"m",name:"base64",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bitsPerChar:6}),lp=U({prefix:"M",name:"base64pad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",bitsPerChar:6}),up=U({prefix:"u",name:"base64url",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_",bitsPerChar:6}),dp=U({prefix:"U",name:"base64urlpad",alphabet:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_=",bitsPerChar:6})});var eo={};B(eo,{base8:()=>hp});var hp,Al=w(()=>{"use strict";me();hp=U({prefix:"7",name:"base8",alphabet:"01234567",bitsPerChar:3})});var to={};B(to,{identity:()=>fp});var fp,kl=w(()=>{"use strict";Ke();me();fp=Bt({prefix:"\0",name:"identity",encode:n=>xi(n),decode:n=>Si(n)})});var c0,l0,El=w(()=>{"use strict";c0=new TextEncoder,l0=new TextDecoder});var Kt={};B(Kt,{code:()=>Ot,decode:()=>yp,encode:()=>mp,name:()=>gp});function mp(n){return ue(n)}function yp(n){return ue(n)}var gp,Ot,Ur=w(()=>{"use strict";Ke();gp="raw",Ot=85});var ro={};B(ro,{identity:()=>Sp});function bp(n,e){if(e?.truncate!=null&&e.truncate!==n.byteLength){if(e.truncate<0||e.truncate>n.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${n.byteLength}`);n=n.subarray(0,e.truncate)}return Ft(Cl,Pl(n))}var Cl,wp,Pl,Sp,Il=w(()=>{"use strict";Ke();Nt();Cl=0,wp="identity",Pl=ue;Sp={code:Cl,name:wp,encode:Pl,digest:bp}});function at({name:n,code:e,encode:t,minDigestLength:r,maxDigestLength:s}){return new no(n,e,t,r,s)}function Bl(n,e,t){if(t!=null&&t!==n.byteLength){if(t>n.byteLength)throw new Error(`Invalid truncate option, must be less than or equal to ${n.byteLength}`);n=n.subarray(0,t)}return Ft(e,n)}var xp,no,Zn=w(()=>{"use strict";Nt();xp=20;no=class{constructor(e,t,r,s,i){p(this,"name");p(this,"code");p(this,"encode");p(this,"minDigestLength");p(this,"maxDigestLength");this.name=e,this.code=t,this.encode=r,this.minDigestLength=s??xp,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 r=this.encode(e);return r instanceof Uint8Array?Bl(r,this.code,t?.truncate):r.then(s=>Bl(s,this.code,t?.truncate))}else throw Error("Unknown type, must be binary type")}}});var io={};B(io,{sha256:()=>so,sha512:()=>vp});function Rl(n){return async e=>new Uint8Array(await crypto.subtle.digest(n,e))}var so,vp,oo=w(()=>{"use strict";Zn();so=at({name:"sha2-256",code:18,encode:Rl("SHA-256")}),vp=at({name:"sha2-512",code:19,encode:Rl("SHA-512")})});var Tl=w(()=>{"use strict"});var Fl=w(()=>{"use strict"});var Ml=w(()=>{"use strict"});var Nl=w(()=>{"use strict"});var Ul=w(()=>{"use strict";Tl();Fl();Ml();Ri();Nl()});var ao=w(()=>{"use strict";Ke();st();Nt();Zn();Yn();Ul()});var co,A0,Ll=w(()=>{"use strict";wl();bl();Sl();vl();Cr();Ii();Vn();Zi();Al();kl();El();Ur();Il();oo();ao();co={...to,...ji,...eo,...Gi,...Yi,...Ci,...Pi,...Bi,...Xi,...Ji},A0={...io,...ro}});function Ol(n,e,t,r){return{name:n,prefix:e,encoder:{name:n,prefix:e,encode:t},decoder:{decode:r}}}var _l,lo,Ap,Kl,zl=w(()=>{"use strict";Ll();nt();_l=Ol("utf8","u",n=>"u"+new TextDecoder("utf8").decode(n),n=>new TextEncoder().encode(n.substring(1))),lo=Ol("ascii","a",n=>{let e="a";for(let t=0;t<n.length;t++)e+=String.fromCharCode(n[t]);return e},n=>{n=n.substring(1);let e=te(n.length);for(let t=0;t<n.length;t++)e[t]=n.charCodeAt(t);return e}),Ap={utf8:_l,"utf-8":_l,hex:co.base16,latin1:lo,ascii:lo,binary:lo,...co},Kl=Ap});function zt(n,e="utf8"){let t=Kl[e];if(t==null)throw new Error(`Unsupported encoding "${e}"`);return t.decoder.decode(`${t.prefix}${n}`)}var es=w(()=>{"use strict";zl()});function uo(n){let e=n??8192,t=e>>>1,r,s=e;return function(o){if(o<1||o>t)return te(o);s+o>e&&(r=te(e),s=0);let c=r.subarray(s,s+=o);return(s&7)!==0&&(s=(s|7)+1),c}}var Wl=w(()=>{"use strict";nt()});function ho(){}function Ep(n){return globalThis.Buffer!=null?te(n):kp(n)}function fo(n,e,t){e[t]=n&255}function Cp(n,e,t){for(;n>127;)e[t++]=n&127|128,n>>>=7;e[t]=n}function ts(n,e,t){for(;n.hi!==0;)e[t++]=n.lo&127|128,n.lo=(n.lo>>>7|n.hi<<25)>>>0,n.hi>>>=7;for(;n.lo>127;)e[t++]=n.lo&127|128,n.lo=n.lo>>>7;e[t++]=n.lo}function Lr(n,e,t){e[t]=n&255,e[t+1]=n>>>8&255,e[t+2]=n>>>16&255,e[t+3]=n>>>24}function Pp(n,e,t){e.set(n,t)}function Ip(n,e,t){e.set(n,t)}function Bp(n,e,t){n.length<40?Wi(n,e,t):e.utf8Write!=null?e.utf8Write(n,t):e.set(zt(n),t)}function mo(){return new _r}var ct,po,kp,_r,go,yo=w(()=>{"use strict";Li();nt();es();Ki();zi();Wl();$i();ct=class{constructor(e,t,r){p(this,"fn");p(this,"len");p(this,"next");p(this,"val");this.fn=e,this.len=t,this.next=void 0,this.val=r}};po=class{constructor(e){p(this,"head");p(this,"tail");p(this,"len");p(this,"next");this.head=e.head,this.tail=e.tail,this.len=e.len,this.next=e.states}},kp=uo();_r=class{constructor(){p(this,"len");p(this,"head");p(this,"tail");p(this,"states");this.len=0,this.head=new ct(ho,0,0),this.tail=this.head,this.states=null}_push(e,t,r){return this.tail=this.tail.next=new ct(e,t,r),this.len+=t,this}uint32(e){return this.len+=(this.tail=this.tail.next=new go((e=e>>>0)<128?1:e<16384?2:e<2097152?3:e<268435456?4:5,e)).len,this}int32(e){return e<0?this._push(ts,10,se.fromNumber(e)):this.uint32(e)}sint32(e){return this.uint32((e<<1^e>>31)>>>0)}uint64(e){let t=se.fromBigInt(e);return this._push(ts,t.length(),t)}uint64Number(e){return this._push(al,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=se.fromBigInt(e).zzEncode();return this._push(ts,t.length(),t)}sint64Number(e){let t=se.fromNumber(e).zzEncode();return this._push(ts,t.length(),t)}sint64String(e){return this.sint64(BigInt(e))}bool(e){return this._push(fo,1,e?1:0)}fixed32(e){return this._push(Lr,4,e>>>0)}sfixed32(e){return this.fixed32(e)}fixed64(e){let t=se.fromBigInt(e);return this._push(Lr,4,t.lo)._push(Lr,4,t.hi)}fixed64Number(e){let t=se.fromNumber(e);return this._push(Lr,4,t.lo)._push(Lr,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(ll,4,e)}double(e){return this._push(dl,8,e)}bytes(e){let t=e.length>>>0;return t===0?this._push(fo,1,0):this.uint32(t)._push(Pp,t,e)}string(e){let t=pl(e);return t!==0?this.uint32(t)._push(Wi,t,e):this._push(fo,1,0)}fork(){return this.states=new po(this),this.head=this.tail=new ct(ho,0,0),this.len=0,this}reset(){return this.states!=null?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new ct(ho,0,0),this.len=0),this}ldelim(){let e=this.head,t=this.tail,r=this.len;return this.reset().uint32(r),r!==0&&(this.tail.next=e.next,this.tail=t,this.len+=r),this}finish(){let e=this.head.next,t=Ep(this.len),r=0;for(;e!=null;)e.fn(e.val,t,r),r+=e.len,e=e.next;return t}};go=class extends ct{constructor(t,r){super(Cp,t,r);p(this,"next");this.next=void 0}};globalThis.Buffer!=null&&(_r.prototype.bytes=function(n){let e=n.length>>>0;return this.uint32(e),e>0&&this._push(Ip,e,n),this},_r.prototype.string=function(n){let e=globalThis.Buffer.byteLength(n);return this.uint32(e),e>0&&this._push(Bp,e,n),this})});function Or(n,e){let t=mo();return e.encode(n,t,{lengthDelimited:!1}),t.finish()}var $l=w(()=>{"use strict";yo()});function rs(n,e,t,r){return{name:n,type:e,encode:t,decode:r}}var Wt,wo=w(()=>{"use strict";(function(n){n[n.VARINT=0]="VARINT",n[n.BIT64=1]="BIT64",n[n.LENGTH_DELIMITED=2]="LENGTH_DELIMITED",n[n.START_GROUP=3]="START_GROUP",n[n.END_GROUP=4]="END_GROUP",n[n.BIT32=5]="BIT32"})(Wt||(Wt={}))});function bo(n){function e(s){if(n[s.toString()]==null)throw new Error("Invalid enum value");return n[s]}let t=function(i,o){let c=e(i);o.int32(c)},r=function(i){let o=i.int32();return e(o)};return rs("enum",Wt.VARINT,t,r)}var ql=w(()=>{"use strict";wo()});function Kr(n,e){return rs("message",Wt.LENGTH_DELIMITED,n,e)}var Hl=w(()=>{"use strict";wo()});var Vl=w(()=>{"use strict";yl();$l();ql();Hl();Vi();yo()});var we,ns,Gl,Yl=w(()=>{"use strict";Vl();(function(n){let e;(function(s){s.Raw="Raw",s.Directory="Directory",s.File="File",s.Metadata="Metadata",s.Symlink="Symlink",s.HAMTShard="HAMTShard"})(e=n.DataType||(n.DataType={}));let t;(function(s){s[s.Raw=0]="Raw",s[s.Directory=1]="Directory",s[s.File=2]="File",s[s.Metadata=3]="Metadata",s[s.Symlink=4]="Symlink",s[s.HAMTShard=5]="HAMTShard"})(t||(t={})),(function(s){s.codec=()=>bo(t)})(e=n.DataType||(n.DataType={}));let r;n.codec=()=>(r==null&&(r=Kr((s,i,o={})=>{if(o.lengthDelimited!==!1&&i.fork(),s.Type!=null&&(i.uint32(8),n.DataType.codec().encode(s.Type,i)),s.Data!=null&&(i.uint32(18),i.bytes(s.Data)),s.filesize!=null&&(i.uint32(24),i.uint64(s.filesize)),s.blocksizes!=null)for(let c of s.blocksizes)i.uint32(32),i.uint64(c);s.hashType!=null&&(i.uint32(40),i.uint64(s.hashType)),s.fanout!=null&&(i.uint32(48),i.uint64(s.fanout)),s.mode!=null&&(i.uint32(56),i.uint32(s.mode)),s.mtime!=null&&(i.uint32(66),ns.codec().encode(s.mtime,i)),o.lengthDelimited!==!1&&i.ldelim()},(s,i)=>{let o={blocksizes:[]},c=i==null?s.len:s.pos+i;for(;s.pos<c;){let a=s.uint32();switch(a>>>3){case 1:o.Type=n.DataType.codec().decode(s);break;case 2:o.Data=s.bytes();break;case 3:o.filesize=s.uint64();break;case 4:o.blocksizes.push(s.uint64());break;case 5:o.hashType=s.uint64();break;case 6:o.fanout=s.uint64();break;case 7:o.mode=s.uint32();break;case 8:o.mtime=ns.codec().decode(s,s.uint32());break;default:s.skipType(a&7);break}}return o})),r),n.encode=s=>Or(s,n.codec()),n.decode=s=>Nr(s,n.codec())})(we||(we={}));(function(n){let e;n.codec=()=>(e==null&&(e=Kr((t,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),t.Seconds!=null&&(r.uint32(8),r.int64(t.Seconds)),t.FractionalNanoseconds!=null&&(r.uint32(21),r.fixed32(t.FractionalNanoseconds)),s.lengthDelimited!==!1&&r.ldelim()},(t,r)=>{let s={},i=r==null?t.len:t.pos+r;for(;t.pos<i;){let o=t.uint32();switch(o>>>3){case 1:s.Seconds=t.int64();break;case 2:s.FractionalNanoseconds=t.fixed32();break;default:t.skipType(o&7);break}}return s})),e),n.encode=t=>Or(t,n.codec()),n.decode=t=>Nr(t,n.codec())})(ns||(ns={}));(function(n){let e;n.codec=()=>(e==null&&(e=Kr((t,r,s={})=>{s.lengthDelimited!==!1&&r.fork(),t.MimeType!=null&&(r.uint32(10),r.string(t.MimeType)),s.lengthDelimited!==!1&&r.ldelim()},(t,r)=>{let s={},i=r==null?t.len:t.pos+r;for(;t.pos<i;){let o=t.uint32();o>>>3===1?s.MimeType=t.string():t.skipType(o&7)}return s})),e),n.encode=t=>Or(t,n.codec()),n.decode=t=>Nr(t,n.codec())})(Gl||(Gl={}))});var jl,Dp,Jl,Ql,Xl,Q,$t=w(()=>{"use strict";Ui();Yl();Ui();jl={Raw:"raw",Directory:"directory",File:"file",Metadata:"metadata",Symlink:"symlink",HAMTShard:"hamt-sharded-directory"},Dp=["directory","hamt-sharded-directory"],Jl=parseInt("0644",8),Ql=parseInt("0755",8),Xl=BigInt(1024),Q=class n{constructor(e={type:"file"}){p(this,"type");p(this,"data");p(this,"blockSizes");p(this,"hashType");p(this,"fanout");p(this,"mtime");p(this,"_mode");p(this,"_originalMode");let{type:t,data:r,blockSizes:s,hashType:i,fanout:o,mtime:c,mode:a}=e;if(t!=null&&!Object.values(jl).includes(t))throw new Fr("Type: "+t+" is not valid");this.type=t??"file",this.data=r,this.hashType=i,this.fanout=o,this.blockSizes=s??[],this._originalMode=0,this.mode=a,this.mtime=c}static unmarshal(e){let t=we.decode(e);if(t.fanout!=null&&t.fanout>Xl)throw new Qn(`Fanout size was too large - ${t.fanout} > ${Xl}`);let r=new n({type:jl[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 r._originalMode=t.mode??0,r}set mode(e){e==null?this._mode=this.isDirectory()?Ql:Jl:this._mode=e&4095}get mode(){return this._mode}isDirectory(){return Dp.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 r;this.mode!=null&&(r=this._originalMode&4294963200|(this.mode??0),r===Jl&&!this.isDirectory()&&(r=void 0),r===Ql&&this.isDirectory()&&(r=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:r,mtime:s})}}});var Ie,ss=w(()=>{"use strict";Ie=class extends Event{constructor(t,r){super(t);p(this,"type");p(this,"detail");this.type=t,this.detail=r}}});var be,qt=w(()=>{"use strict";it();st();oo();be=async(n,e,t)=>{t.codec==null&&(t.codec=Tr);let r=await so.digest(n),s=K.create(t.cidVersion,t.codec.code,r);return await e.put(s,n,t),s}});function Zl(n){return async function*(t,r){let s=0n;for await(let i of t.content)yield async()=>{let o,c={codec:Tr,cidVersion:n.cidVersion,onProgress:n.onProgress};n.rawLeaves?(c.codec=Kt,c.cidVersion=1):(o=new Q({type:n.leafType,data:i}),i=ne({Data:o.marshal(),Links:[]}));let a=await be(i,r,c);return s+=BigInt(i.byteLength),n.onProgress?.(new Ie("unixfs:importer:progress:file:write",{bytesWritten:s,cid:a,path:t.path})),{cid:a,unixfs:o,size:BigInt(i.length),block:i}}}}var eu=w(()=>{"use strict";it();$t();Ur();ss();qt()});var Ht,Jt,Vt,So,Gt,xo,Yt,vo,jt,Be,zr=w(()=>{"use strict";Ht=class Ht extends Error{constructor(t="Invalid parameters"){super(t);p(this,"name",Ht.name);p(this,"code",Ht.code)}};p(Ht,"name","InvalidParametersError"),p(Ht,"code","ERR_INVALID_PARAMS");Jt=Ht,Vt=class Vt extends Error{constructor(t="Invalid avg chunk size"){super(t);p(this,"name",Vt.name);p(this,"code",Vt.code)}};p(Vt,"name","InvalidAvgChunkSizeError"),p(Vt,"code","ERR_INVALID_AVG_CHUNK_SIZE");So=Vt,Gt=class Gt extends Error{constructor(t="Invalid chunk size"){super(t);p(this,"name",Gt.name);p(this,"code",Gt.code)}};p(Gt,"name","InvalidChunkSizeError"),p(Gt,"code","ERR_INVALID_CHUNK_SIZE");xo=Gt,Yt=class Yt extends Error{constructor(t="Invalid min chunk size"){super(t);p(this,"name",Yt.name);p(this,"code",Yt.code)}};p(Yt,"name","InvalidMinChunkSizeError"),p(Yt,"code","ERR_INVALID_MIN_CHUNK_SIZE");vo=Yt,jt=class jt extends Error{constructor(t="Invalid content"){super(t);p(this,"name",jt.name);p(this,"code",jt.code)}};p(jt,"name","InvalidContentError"),p(jt,"code","ERR_INVALID_CONTENT");Be=jt});var tu,ru=w(()=>{"use strict";it();$t();qt();tu=async(n,e,t)=>{let r=new Q({type:"directory",mtime:n.mtime,mode:n.mode}),s=ne(re({Data:r.marshal()})),i=await be(s,e,t),o=n.path;return{cid:i,path:o,unixfs:r,size:BigInt(s.length),originalPath:n.originalPath,block:s}}});async function*Rp(n,e,t){let r=-1,s;for await(let i of kr(t.bufferImporter(n,e),t.blockWriteConcurrency)){if(r++,r===0){s={...i,single:!0};continue}else r===1&&s!=null&&(yield{...s,block:void 0,single:void 0},s=void 0);yield{...i,block:void 0}}s!=null&&(yield s)}function nu(n){return n.single===!0}var Tp,su,iu=w(()=>{"use strict";it();$t();yi();Ur();ss();qt();Tp=(n,e,t)=>async function(s){if(s.length===1&&nu(s[0])&&t.reduceSingleLeafToSelf){let l=s[0],h=l.block;return nu(l)&&(n.mtime!==void 0||n.mode!==void 0)&&(l.unixfs=new Q({type:"file",mtime:n.mtime,mode:n.mode,data:l.block}),h={Data:l.unixfs.marshal(),Links:[]},l.block=ne(re(h)),l.cid=await be(l.block,e,{...t,cidVersion:t.cidVersion}),l.size=BigInt(l.block.length)),t.onProgress?.(new Ie("unixfs:importer:progress:file:layout",{cid:l.cid,path:l.originalPath})),{cid:l.cid,path:n.path,unixfs:l.unixfs,size:l.size,originalPath:l.originalPath}}let i=new Q({type:"file",mtime:n.mtime,mode:n.mode}),o=s.filter(l=>l.cid.code===Ot&&l.size>0||l.unixfs!=null&&l.unixfs.data==null&&l.unixfs.fileSize()>0n?!0:!!l.unixfs?.data?.length).map(l=>l.cid.code===Ot?(i.addBlockSize(l.size),{Name:"",Tsize:Number(l.size),Hash:l.cid}):(l.unixfs?.data==null?i.addBlockSize(l.unixfs?.fileSize()??0n):i.addBlockSize(BigInt(l.unixfs.data.length)),{Name:"",Tsize:Number(l.size),Hash:l.cid})),c={Data:i.marshal(),Links:o},a=ne(re(c)),u=await be(a,e,t);return t.onProgress?.(new Ie("unixfs:importer:progress:file:layout",{cid:u,path:n.originalPath})),{cid:u,path:n.path,unixfs:i,size:BigInt(a.length+c.Links.reduce((l,h)=>l+(h.Tsize??0),0)),originalPath:n.originalPath,block:a}},su=async(n,e,t)=>t.layout(Rp(n,e,t),Tp(n,e,t))});function Fp(n){return Symbol.iterator in n}function Mp(n){return Symbol.asyncIterator in n}function Np(n){try{if(n instanceof Uint8Array)return(async function*(){yield n})();if(Fp(n))return(async function*(){yield*n})();if(Mp(n))return n}catch{throw new Be("Content was invalid")}throw new Be("Content was invalid")}function ou(n){return async function*(t,r){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("/")),Up(s)){let o={path:s.path,mtime:s.mtime,mode:s.mode,content:(async function*(){let a=0n;for await(let u of n.chunker(n.chunkValidator(Np(s.content)))){let l=BigInt(u.byteLength);a+=l,n.onProgress?.(new Ie("unixfs:importer:progress:file:read",{bytesRead:a,chunkSize:l,path:s.path})),yield u}})(),originalPath:i},c=n.fileBuilder??su;yield async()=>c(o,r,n)}else if(s.path!=null){let o={path:s.path,mtime:s.mtime,mode:s.mode,originalPath:i},c=n.dirBuilder??tu;yield async()=>c(o,r,n)}else throw new Error("Import candidate must have content or path or both")}}}function Up(n){return n.content!=null}var au=w(()=>{"use strict";ss();zr();ru();iu()});var cu,lu=w(()=>{"use strict";es();zr();cu=()=>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 Ao(n){let e=n?.maxChildrenPerNode??Lp;return async function t(r,s){let i=[];for await(let o of qn(r,e))i.push(await s(o));return i.length>1?t(i,s):i[0]}}var Lp,uu=w(()=>{"use strict";mi();Lp=174});function _p(n){return n[Symbol.asyncIterator]!=null}function Op(n){if(_p(n))return(async()=>{let t=[];for await(let r of n)t.push(r);return t})();let e=[];for(let t of n)e.push(t);return e}var du,hu=w(()=>{"use strict";du=Op});var fu=w(()=>{"use strict";uu()});var ke,Wr,$r,is=w(()=>{"use strict";st();ke=class{constructor(e,t){p(this,"options");p(this,"root");p(this,"dir");p(this,"path");p(this,"dirty");p(this,"flat");p(this,"parent");p(this,"parentKey");p(this,"unixfs");p(this,"mode");p(this,"mtime");p(this,"cid");p(this,"size");p(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}},Wr=K.parse("QmUNLLsPACCz1vLxQVkXqqLX5R1X345qqfHbsf67hvA3Nn"),$r=K.parse("zdj7WbTaiJT1fgatdet9Ei9iDB5hdCxkbVyhyh8YTUnXMiwYi")});var lt,ko=w(()=>{"use strict";it();$t();is();qt();lt=class extends ke{constructor(t,r){super(t,r);p(this,"_children");this._children=new Map}async put(t,r){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,this._children.set(t,r)}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,r]of this._children.entries())yield{key:t,child:r}}estimateNodeSize(){if(this.nodeSize!==void 0)return this.nodeSize;this.nodeSize=0;for(let[t,r]of this._children.entries())r.size!=null&&r.cid!=null&&(this.nodeSize+=t.length+(this.options.cidVersion===1?$r.bytes.byteLength:Wr.bytes.byteLength));return this.nodeSize}async*flush(t){let r=[];for(let[u,l]of this._children.entries()){let h=l;if(l instanceof ke)for await(let g of l.flush(t))h=g,yield g;h.size!=null&&h.cid!=null&&r.push({Name:u,Tsize:Number(h.size),Hash:h.cid})}let s=new Q({type:"directory",mtime:this.mtime,mode:this.mode}),i={Data:s.marshal(),Links:r},o=ne(re(i)),c=await be(o,t,this.options),a=o.length+i.Links.reduce((u,l)=>u+(l.Tsize??0),0);this.cid=c,this.size=a,yield{cid:c,unixfs:s,path:this.path,size:BigInt(a)}}}});var pu=D((qr,os)=>{"use strict";(function(n,e){"use strict";var t={version:"3.0.0",x86:{},x64:{},inputValidation:!0};function r(d){if(!Array.isArray(d)&&!ArrayBuffer.isView(d))return!1;for(var f=0;f<d.length;f++)if(!Number.isInteger(d[f])||d[f]<0||d[f]>255)return!1;return!0}function s(d,f){return(d&65535)*f+(((d>>>16)*f&65535)<<16)}function i(d,f){return d<<f|d>>>32-f}function o(d){return d^=d>>>16,d=s(d,2246822507),d^=d>>>13,d=s(d,3266489909),d^=d>>>16,d}function c(d,f){d=[d[0]>>>16,d[0]&65535,d[1]>>>16,d[1]&65535],f=[f[0]>>>16,f[0]&65535,f[1]>>>16,f[1]&65535];var y=[0,0,0,0];return y[3]+=d[3]+f[3],y[2]+=y[3]>>>16,y[3]&=65535,y[2]+=d[2]+f[2],y[1]+=y[2]>>>16,y[2]&=65535,y[1]+=d[1]+f[1],y[0]+=y[1]>>>16,y[1]&=65535,y[0]+=d[0]+f[0],y[0]&=65535,[y[0]<<16|y[1],y[2]<<16|y[3]]}function a(d,f){d=[d[0]>>>16,d[0]&65535,d[1]>>>16,d[1]&65535],f=[f[0]>>>16,f[0]&65535,f[1]>>>16,f[1]&65535];var y=[0,0,0,0];return y[3]+=d[3]*f[3],y[2]+=y[3]>>>16,y[3]&=65535,y[2]+=d[2]*f[3],y[1]+=y[2]>>>16,y[2]&=65535,y[2]+=d[3]*f[2],y[1]+=y[2]>>>16,y[2]&=65535,y[1]+=d[1]*f[3],y[0]+=y[1]>>>16,y[1]&=65535,y[1]+=d[2]*f[2],y[0]+=y[1]>>>16,y[1]&=65535,y[1]+=d[3]*f[1],y[0]+=y[1]>>>16,y[1]&=65535,y[0]+=d[0]*f[3]+d[1]*f[2]+d[2]*f[1]+d[3]*f[0],y[0]&=65535,[y[0]<<16|y[1],y[2]<<16|y[3]]}function u(d,f){return f%=64,f===32?[d[1],d[0]]:f<32?[d[0]<<f|d[1]>>>32-f,d[1]<<f|d[0]>>>32-f]:(f-=32,[d[1]<<f|d[0]>>>32-f,d[0]<<f|d[1]>>>32-f])}function l(d,f){return f%=64,f===0?d:f<32?[d[0]<<f|d[1]>>>32-f,d[1]<<f]:[d[1]<<f-32,0]}function h(d,f){return[d[0]^f[0],d[1]^f[1]]}function g(d){return d=h(d,[0,d[0]>>>1]),d=a(d,[4283543511,3981806797]),d=h(d,[0,d[0]>>>1]),d=a(d,[3301882366,444984403]),d=h(d,[0,d[0]>>>1]),d}t.x86.hash32=function(d,f){if(t.inputValidation&&!r(d))return e;f=f||0;for(var y=d.length%4,k=d.length-y,m=f,b=0,v=3432918353,A=461845907,E=0;E<k;E=E+4)b=d[E]|d[E+1]<<8|d[E+2]<<16|d[E+3]<<24,b=s(b,v),b=i(b,15),b=s(b,A),m^=b,m=i(m,13),m=s(m,5)+3864292196;switch(b=0,y){case 3:b^=d[E+2]<<16;case 2:b^=d[E+1]<<8;case 1:b^=d[E],b=s(b,v),b=i(b,15),b=s(b,A),m^=b}return m^=d.length,m=o(m),m>>>0},t.x86.hash128=function(d,f){if(t.inputValidation&&!r(d))return e;f=f||0;for(var y=d.length%16,k=d.length-y,m=f,b=f,v=f,A=f,E=0,C=0,x=0,P=0,G=597399067,he=2869860233,dt=951274213,ht=2716044179,I=0;I<k;I=I+16)E=d[I]|d[I+1]<<8|d[I+2]<<16|d[I+3]<<24,C=d[I+4]|d[I+5]<<8|d[I+6]<<16|d[I+7]<<24,x=d[I+8]|d[I+9]<<8|d[I+10]<<16|d[I+11]<<24,P=d[I+12]|d[I+13]<<8|d[I+14]<<16|d[I+15]<<24,E=s(E,G),E=i(E,15),E=s(E,he),m^=E,m=i(m,19),m+=b,m=s(m,5)+1444728091,C=s(C,he),C=i(C,16),C=s(C,dt),b^=C,b=i(b,17),b+=v,b=s(b,5)+197830471,x=s(x,dt),x=i(x,17),x=s(x,ht),v^=x,v=i(v,15),v+=A,v=s(v,5)+2530024501,P=s(P,ht),P=i(P,18),P=s(P,G),A^=P,A=i(A,13),A+=m,A=s(A,5)+850148119;switch(E=0,C=0,x=0,P=0,y){case 15:P^=d[I+14]<<16;case 14:P^=d[I+13]<<8;case 13:P^=d[I+12],P=s(P,ht),P=i(P,18),P=s(P,G),A^=P;case 12:x^=d[I+11]<<24;case 11:x^=d[I+10]<<16;case 10:x^=d[I+9]<<8;case 9:x^=d[I+8],x=s(x,dt),x=i(x,17),x=s(x,ht),v^=x;case 8:C^=d[I+7]<<24;case 7:C^=d[I+6]<<16;case 6:C^=d[I+5]<<8;case 5:C^=d[I+4],C=s(C,he),C=i(C,16),C=s(C,dt),b^=C;case 4:E^=d[I+3]<<24;case 3:E^=d[I+2]<<16;case 2:E^=d[I+1]<<8;case 1:E^=d[I],E=s(E,G),E=i(E,15),E=s(E,he),m^=E}return m^=d.length,b^=d.length,v^=d.length,A^=d.length,m+=b,m+=v,m+=A,b+=m,v+=m,A+=m,m=o(m),b=o(b),v=o(v),A=o(A),m+=b,m+=v,m+=A,b+=m,v+=m,A+=m,("00000000"+(m>>>0).toString(16)).slice(-8)+("00000000"+(b>>>0).toString(16)).slice(-8)+("00000000"+(v>>>0).toString(16)).slice(-8)+("00000000"+(A>>>0).toString(16)).slice(-8)},t.x64.hash128=function(d,f){if(t.inputValidation&&!r(d))return e;f=f||0;for(var y=d.length%16,k=d.length-y,m=[0,f],b=[0,f],v=[0,0],A=[0,0],E=[2277735313,289559509],C=[1291169091,658871167],x=0;x<k;x=x+16)v=[d[x+4]|d[x+5]<<8|d[x+6]<<16|d[x+7]<<24,d[x]|d[x+1]<<8|d[x+2]<<16|d[x+3]<<24],A=[d[x+12]|d[x+13]<<8|d[x+14]<<16|d[x+15]<<24,d[x+8]|d[x+9]<<8|d[x+10]<<16|d[x+11]<<24],v=a(v,E),v=u(v,31),v=a(v,C),m=h(m,v),m=u(m,27),m=c(m,b),m=c(a(m,[0,5]),[0,1390208809]),A=a(A,C),A=u(A,33),A=a(A,E),b=h(b,A),b=u(b,31),b=c(b,m),b=c(a(b,[0,5]),[0,944331445]);switch(v=[0,0],A=[0,0],y){case 15:A=h(A,l([0,d[x+14]],48));case 14:A=h(A,l([0,d[x+13]],40));case 13:A=h(A,l([0,d[x+12]],32));case 12:A=h(A,l([0,d[x+11]],24));case 11:A=h(A,l([0,d[x+10]],16));case 10:A=h(A,l([0,d[x+9]],8));case 9:A=h(A,[0,d[x+8]]),A=a(A,C),A=u(A,33),A=a(A,E),b=h(b,A);case 8:v=h(v,l([0,d[x+7]],56));case 7:v=h(v,l([0,d[x+6]],48));case 6:v=h(v,l([0,d[x+5]],40));case 5:v=h(v,l([0,d[x+4]],32));case 4:v=h(v,l([0,d[x+3]],24));case 3:v=h(v,l([0,d[x+2]],16));case 2:v=h(v,l([0,d[x+1]],8));case 1:v=h(v,[0,d[x]]),v=a(v,E),v=u(v,31),v=a(v,C),m=h(m,v)}return m=h(m,[0,d.length]),b=h(b,[0,d.length]),m=c(m,b),b=c(b,m),m=g(m),b=g(b),m=c(m,b),b=c(b,m),("00000000"+(m[0]>>>0).toString(16)).slice(-8)+("00000000"+(m[1]>>>0).toString(16)).slice(-8)+("00000000"+(b[0]>>>0).toString(16)).slice(-8)+("00000000"+(b[1]>>>0).toString(16)).slice(-8)},typeof qr<"u"?(typeof os<"u"&&os.exports&&(qr=os.exports=t),qr.murmurHash3=t):typeof define=="function"&&define.amd?define([],function(){return t}):(t._murmurHash3=n.murmurHash3,t.noConflict=function(){return n.murmurHash3=t._murmurHash3,t._murmurHash3=e,t.noConflict=e,t},n.murmurHash3=t)})(qr)});var mu=D((Qb,gu)=>{"use strict";gu.exports=pu()});function Kp(n){let e=new Array(4);for(let t=0;t<4;t++)e[t]=n&255,n=n>>8;return new Uint8Array(e)}var as,e1,yu,t1,wu=w(()=>{"use strict";ao();Zn();as=z(mu(),1);e1=at({name:"murmur3-32",code:35,encode:n=>Kp(as.default.x86.hash32(n))}),yu=at({name:"murmur3-128",code:34,encode:n=>It.fromHex(as.default.x64.hash128(n))}),t1=at({name:"murmur3-x64-64",code:34,encode:n=>It.fromHex(as.default.x64.hash128(n)).subarray(0,8)})});var xu=D((s1,Su)=>{"use strict";Su.exports=class{constructor(){this._bitArrays=[],this._data=[],this._length=0,this._changedLength=!1,this._changedData=!1}set(e,t){let r=this._internalPositionFor(e,!1);if(t===void 0)r!==-1&&(this._unsetInternalPos(r),this._unsetBit(e),this._changedLength=!0,this._changedData=!0);else{let s=!1;r===-1?(r=this._data.length,this._setBit(e),this._changedData=!0):s=!0,this._setInternalPos(r,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,r=new Array(this.length);for(;t<this.length;)r[t]=e(this.get(t),t,this),t++;return r}reduce(e,t){let r=0,s=t;for(;r<this.length;){let i=this.get(r);s=e(s,i,r),r++}return s}find(e){let t=0,r,s;for(;t<this.length&&!r;)s=this.get(t),r=e(s),t++;return r?s:void 0}_internalPositionFor(e,t){let r=this._bytePosFor(e,t);if(r>=this._bitArrays.length)return-1;let s=this._bitArrays[r],i=e-r*7;if(!((s&1<<i)>0))return-1;let c=this._bitArrays.slice(0,r).reduce(zp,0),a=~(4294967295<<i+1),u=bu(s&a);return c+u-1}_bytePosFor(e,t){let r=Math.floor(e/7),s=r+1;for(;!t&&this._bitArrays.length<s;)this._bitArrays.push(0);return r}_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,r,s){let i=this._data,o=[t,r];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 c=Math.round(i.length/2);this._data=i.slice(0,c).concat(o).concat(i.slice(c))}else this._data.push(o);this._changedData=!0,this._changedLength=!0}}_unsetInternalPos(e){this._data.splice(e,1)}_sortData(){this._changedData&&this._data.sort(Wp),this._changedData=!1}bitField(){let e=[],t=8,r=0,s=0,i,o=this._bitArrays.slice();for(;o.length||r;){r===0&&(i=o.shift(),r=7);let a=Math.min(r,t),u=~(255<<a),l=i&u;s|=l<<8-t,i=i>>>a,r-=a,t-=a,(!t||!r&&!o.length)&&(e.push(s),s=0,t=8)}for(var c=e.length-1;c>0&&e[c]===0;c--)e.pop();return e}compactArray(){return this._sortData(),this._data.map($p)}};function zp(n,e){return n+bu(e)}function bu(n){let e=n;return e=e-(e>>1&1431655765),e=(e&858993459)+(e>>2&858993459),(e+(e>>4)&252645135)*16843009>>24}function Wp(n,e){return n[0]-e[0]}function $p(n){return n[1]}});function qp(n){return!!n}function Hp(n,e){return n.key}function Vp(n){return n}async function Au(n,e,t){let r=[];for(let s of n._children.compactArray())if(s instanceof qe)await Au(s,e,t);else{let i=await e(s);r.push({bitField:n._children.bitField(),children:i})}return t(r)}var vu,qe,ku=w(()=>{"use strict";vu=z(xu(),1);es();qe=class n{constructor(e,t,r=0){p(this,"_options");p(this,"_popCount");p(this,"_parent");p(this,"_posAtParent");p(this,"_children");p(this,"key");this._options=e,this._popCount=0,this._parent=t,this._posAtParent=r,this._children=new vu.default,this.key=null}async put(e,t){let r=await this._findNewBucketAndPos(e);r.bucket._putAt(r,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),r=t.bucket._at(t.pos);r!=null&&r.key===e&&t.bucket._delAt(t.pos)}leafCount(){return this._children.compactArray().reduce((t,r)=>r instanceof n?t+r.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 n?yield*t.eachLeafSeries():yield t}serialize(e,t){let r=[];return t(this._children.reduce((s,i,o)=>(i!=null&&(i instanceof n?s.push(i.serialize(e,t)):s.push(e(i,o))),s),r))}async asyncTransform(e,t){return Au(this,e,t)}toJSON(){return this.serialize(Hp,Vp)}prettyPrint(){return JSON.stringify(this.toJSON(),null," ")}tableSize(){return Math.pow(2,this._options.bits)}async _findChild(e){let t=await this._findPlace(e),r=t.bucket._at(t.pos);if(!(r instanceof n)&&r!=null&&r.key===e)return r}async _findPlace(e){let t=this._options.hash(typeof e=="string"?zt(e):e),r=await t.take(this._options.bits),s=this._children.get(r);return s instanceof n?s._findPlace(t):{bucket:this,pos:r,hash:t,existingChild:s}}async _findNewBucketAndPos(e){let t=await this._findPlace(e);if(t.existingChild!=null&&t.existingChild.key!==e){let r=new n(this._options,t.bucket,t.pos);t.bucket._putObjectAt(t.pos,r);let s=await r._findPlace(t.existingChild.hash);return s.bucket._putAt(s,t.existingChild.key,t.existingChild.value),r._findNewBucketAndPos(t.hash)}return t}_putAt(e,t,r){this._putObjectAt(e.pos,{key:t,value:r,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(qp);if(e!=null&&!(e instanceof n)){let t=e.hash;t.untake(this._options.bits);let r={pos:this._posAtParent,hash:t,bucket:this._parent};this._parent._putAt(r,e.key,e.value)}}else this._parent._delAt(this._posAtParent)}_at(e){return this._children.get(e)}}});function jp(n,e,t){let r=Jp(e,t);return(n&r)>>>e}function Jp(n,e){return Gp[n]&Yp[Math.min(e+n-1,7)]}var Gp,Yp,cs,Eu=w(()=>{"use strict";Gp=[255,254,252,248,240,224,192,128],Yp=[1,3,7,15,31,63,127,255],cs=class{constructor(e){p(this,"_value");p(this,"_currentBytePos");p(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,r=0;for(;t>0&&this._haveBits();){let s=this._value[this._currentBytePos],i=this._currentBitPos+1,o=Math.min(i,t),c=jp(s,i-o,o);r=(r<<o)+c,t-=o,this._currentBitPos-=o,this._currentBitPos<0&&(this._currentBitPos=7,this._currentBytePos--)}return r}untake(e){for(this._currentBitPos+=e;this._currentBitPos>7;)this._currentBitPos-=8,this._currentBytePos+=1}_haveBits(){return this._currentBytePos>=0}}});function Cu(n){function e(t){return t instanceof ls?t:new ls(t,n)}return e}var ls,Pu=w(()=>{"use strict";wi();Eu();ls=class{constructor(e,t){p(this,"_value");p(this,"_hashFn");p(this,"_depth");p(this,"_availableBits");p(this,"_currentBufferIndex");p(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 r=0;for(;t>0;){let s=this._buffers[this._currentBufferIndex],i=Math.min(s.availableBits(),t),o=s.take(i);r=(r<<i)+o,t-=i,this._availableBits-=i,s.availableBits()===0&&this._currentBufferIndex++}return r}untake(e){let t=e;for(;t>0;){let r=this._buffers[this._currentBufferIndex],s=Math.min(r.totalBits()-r.availableBits(),t);r.untake(s),t-=s,this._availableBits+=s,this._currentBufferIndex>0&&r.totalBits()===r.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),r=new cs(t);this._buffers.push(r),this._availableBits+=r.availableBits()}}});function Iu(n){if(n==null||n.hashFn==null)throw new Error("please define an options.hashFn");let e={bits:n.bits??8,hash:Cu(n.hashFn)};return new qe(e)}var Bu=w(()=>{"use strict";ku();Pu()});async function Qp(n){return(await yu.encode(n)).slice(0,8).reverse()}async function*Tu(n,e,t,r){let s=n._children,i=(n.tableSize()-1).toString(16).length,o=[],c=0n;for(let f=0;f<s.length;f++){let y=s.get(f);if(y==null)continue;let k=f.toString(16).toUpperCase().padStart(i,"0");if(y instanceof qe){let m;for await(let b of Tu(y,e,null,r))m=b;if(m==null)throw new Error("Could not flush sharded directory, no subshard found");o.push({Name:k,Tsize:Number(m.size),Hash:m.cid}),c+=m.size}else if(Zp(y.value)){let m=y.value,b;for await(let A of m.flush(e))b=A,yield b;if(b==null)throw new Error("Did not flush dir");let v=k+y.key;o.push({Name:v,Tsize:Number(b.size),Hash:b.cid}),c+=b.size}else{let m=y.value;if(m.cid==null)continue;let b=k+y.key,v=m.size;o.push({Name:b,Tsize:Number(v),Hash:m.cid}),c+=BigInt(v??0)}}let a=Uint8Array.from(s.bitField().reverse()),u=new Q({type:"hamt-sharded-directory",data:a,fanout:BigInt(n.tableSize()),hashType:Du,mtime:t?.mtime,mode:t?.mode}),l={Data:u.marshal(),Links:o},h=ne(re(l)),g=await be(h,e,r),d=BigInt(h.byteLength)+c;yield{cid:g,unixfs:u,size:d}}function Zp(n){return typeof n.flush=="function"}function Fu(n,e,t){let r=n._children,s=(n.tableSize()-1).toString(16).length,i=[];for(let u=0;u<r.length;u++){let l=r.get(u);if(l==null)continue;let h=u.toString(16).toUpperCase().padStart(s,"0");if(l instanceof qe){let g=Fu(l,null,t);i.push({Name:h,Tsize:Number(g),Hash:t.cidVersion===0?Wr:$r})}else if(typeof l.value.flush=="function"){let d=l.value.nodeSize();i.push({Name:h+l.key,Tsize:Number(d),Hash:t.cidVersion===0?Wr:$r})}else{let g=l.value;if(g.cid==null)continue;let d=h+l.key,f=g.size;i.push({Name:d,Tsize:Number(f),Hash:g.cid})}}let o=Uint8Array.from(r.bitField().reverse()),c=new Q({type:"hamt-sharded-directory",data:o,fanout:BigInt(n.tableSize()),hashType:Du,mtime:e?.mtime,mode:e?.mode});return ne(re({Data:c.marshal(),Links:i})).length}var Du,Xp,Eo,Ru,Mu=w(()=>{"use strict";it();wu();Bu();$t();is();qt();Du=BigInt(34),Xp=8,Eo=class extends ke{constructor(t,r){super(t,r);p(this,"_bucket");this._bucket=Iu({hashFn:Qp,bits:r.shardFanoutBits??Xp})}async put(t,r){this.cid=void 0,this.size=void 0,this.nodeSize=void 0,await this._bucket.put(t,r)}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:r}of this._bucket.eachLeafSeries())yield{key:t,child:r}}estimateNodeSize(){return this.nodeSize!==void 0?this.nodeSize:(this.nodeSize=Fu(this._bucket,this,this.options),this.nodeSize)}async*flush(t){for await(let r of Tu(this._bucket,t,this,this.options))yield{...r,path:this.path}}},Ru=Eo});async function Co(n,e,t,r){let s=e;e instanceof lt&&e.estimateNodeSize()>t&&(s=await eg(e,r));let i=s.parent;if(i!=null){if(s!==e){if(n!=null&&(n.parent=s),s.parentKey==null)throw new Error("No parent key found");await i.put(s.parentKey,s)}return Co(s,i,t,r)}return s}async function eg(n,e){let t=new Ru({root:n.root,dir:!0,parent:n.parent,parentKey:n.parentKey,path:n.path,dirty:n.dirty,flat:!1,mtime:n.mtime,mode:n.mode},e);for(let{key:r,child:s}of n.eachChildSeries())await t.put(r,s);return t}var Nu=w(()=>{"use strict";ko();Mu()});var Uu,Lu=w(()=>{"use strict";Uu=(n="")=>n.split(/(?<!\\)\//).filter(Boolean)});async function tg(n,e,t){let r=Uu(n.path??""),s=r.length-1,i=e,o="";for(let c=0;c<r.length;c++){let a=r[c];o+=`${o!==""?"/":""}${a}`;let u=c===s;if(i.dirty=!0,i.cid=void 0,i.size=void 0,u)await i.put(a,n),e=await Co(null,i,t.shardSplitThresholdBytes,t);else{let l=await i.get(a);(l==null||!(l instanceof ke))&&(l=new lt({root:!1,dir:!0,parent:i,parentKey:a,path:o,dirty:!0,flat:!0,mtime:l?.unixfs?.mtime,mode:l?.unixfs?.mode},t)),await i.put(a,l),i=l}}return e}async function*_u(n,e){if(!(n instanceof ke)){n.unixfs?.isDirectory()===!0&&(yield n);return}yield*n.flush(e)}function Ou(n){return async function*(t,r){let s=new lt({root:!0,dir:!0,path:"",dirty:!0,flat:!0},n),i,o=!1;for await(let c of t){if(c==null)continue;let a=`${c.originalPath??""}`.split("/")[0];a!=null&&a!==""&&(i==null?(i=a,o=!0):i!==a&&(o=!1)),s=await tg(c,s,n),c.unixfs?.isDirectory()!==!0&&(yield c)}if(n.wrapWithDirectory||o&&s.childCount()>1)yield*_u(s,r);else for(let c of s.eachChildSeries())c!=null&&(yield*_u(c.child,r))}}var Ku=w(()=>{"use strict";ko();is();Nu();Lu()});var zu={};B(zu,{InvalidAvgChunkSizeError:()=>So,InvalidChunkSizeError:()=>xo,InvalidContentError:()=>Be,InvalidMinChunkSizeError:()=>vo,InvalidParametersError:()=>Jt,importByteStream:()=>sg,importBytes:()=>ng,importDirectory:()=>rg,importFile:()=>Io,importer:()=>Po});async function*Po(n,e,t={}){let r;Symbol.asyncIterator in n||Symbol.iterator in n?r=n:r=[n];let s=t.wrapWithDirectory??!1,i=t.shardSplitThresholdBytes??262144,o=t.shardFanoutBits??8,c=t.cidVersion??1,a=t.rawLeaves??!0,u=t.leafType??"file",l=t.fileImportConcurrency??50,h=t.blockWriteConcurrency??10,g=t.reduceSingleLeafToSelf??!0,d=t.chunker??Ic(),f=t.chunkValidator??cu(),y=t.dagBuilder??ou({chunker:d,chunkValidator:f,wrapWithDirectory:s,layout:t.layout??Ao(),bufferImporter:t.bufferImporter??Zl({cidVersion:c,rawLeaves:a,leafType:u,onProgress:t.onProgress}),blockWriteConcurrency:h,reduceSingleLeafToSelf:g,cidVersion:c,onProgress:t.onProgress,dirBuilder:t.dirBuilder,fileBuilder:t.fileBuilder}),k=t.treeBuilder??Ou({wrapWithDirectory:s,shardSplitThresholdBytes:i,shardFanoutBits:o,cidVersion:c,onProgress:t.onProgress});for await(let m of k(kr(y(r,e),l),e))yield{cid:m.cid,path:m.path,unixfs:m.unixfs,size:m.size}}async function Io(n,e,t={}){let r=await gi(Po([n],e,t));if(r==null)throw new Jt("Nothing imported");return r}async function rg(n,e,t={}){let r=await gi(Po([n],e,t));if(r==null)throw new Jt("Nothing imported");return r}async function ng(n,e,t={}){return Io({content:n},e,t)}async function sg(n,e,t={}){return Io({content:n},e,t)}var Wu=w(()=>{"use strict";Sc();yi();Bc();eu();au();lu();zr();fu();Ku();zr()});var Ee,Hr=w(()=>{"use strict";Ee=class{has(e,t){return Promise.reject(new Error(".has is not implemented"))}put(e,t,r){return Promise.reject(new Error(".put is not implemented"))}async*putMany(e,t){for await(let{cid:r,bytes:s}of e)await this.put(r,s,t),yield r}get(e,t){throw new Error(".get is not implemented")}async*getMany(e,t){for await(let r of e)yield{cid:r,bytes:this.get(r,t)}}delete(e,t){return Promise.reject(new Error(".delete is not implemented"))}async*deleteMany(e,t){for await(let r of e)await this.delete(r,t),yield r}async*getAll(e){throw new Error(".getAll is not implemented")}}});var Qt,He,$u=w(()=>{"use strict";Qt=class Qt extends Error{constructor(t="Not Found"){super(t);p(this,"name",Qt.name);p(this,"code",Qt.code)}};p(Qt,"name","NotFoundError"),p(Qt,"code","ERR_NOT_FOUND");He=Qt});var us=w(()=>{"use strict";$u()});function ig(n){return typeof n?.then=="function"}var ds,qu=w(()=>{"use strict";us();hu();Cr();st();Ur();Nt();Hr();ds=class extends Ee{constructor(){super();p(this,"data");this.data=new Map}put(t,r,s){s?.signal?.throwIfAborted();let i;if(r instanceof Uint8Array)i=[r];else{let o=du(r);if(ig(o))return o.then(c=>this._put(t,c,s));i=o}return this._put(t,i,s)}_put(t,r,s){return s?.signal?.throwIfAborted(),this.data.set(J.encode(t.multihash.bytes),r),t}*get(t,r){r?.signal?.throwIfAborted();let s=this.data.get(J.encode(t.multihash.bytes));if(s==null)throw new He;yield*s}has(t,r){return r?.signal?.throwIfAborted(),this.data.has(J.encode(t.multihash.bytes))}async delete(t,r){r?.signal?.throwIfAborted(),this.data.delete(J.encode(t.multihash.bytes))}*getAll(t){t?.signal?.throwIfAborted();for(let[r,s]of this.data.entries())yield{cid:K.createV1(Ot,jn(J.decode(r))),bytes:(async function*(){yield*s})()},t?.signal?.throwIfAborted()}}});var hs,Hu=w(()=>{"use strict";us();Hr();hs=class extends Ee{put(e,t,r){return r?.signal?.throwIfAborted(),e}get(e,t){throw t?.signal?.throwIfAborted(),new He}has(e,t){return t?.signal?.throwIfAborted(),!1}async delete(e,t){t?.signal?.throwIfAborted()}async*getAll(e){e?.signal?.throwIfAborted()}}});function og(n,e){if(typeof n=="string")return ag(n);if(typeof n=="number")return ug(n,e);throw Error(`Value provided to ms() must be a string or number. value=${JSON.stringify(n)}`)}function ag(n){if(typeof n!="string"||n.length===0||n.length>100)throw Error(`Value provided to ms.parse() must be a string with length between 1 and 99. value=${JSON.stringify(n)}`);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(n);if(!e?.groups)return NaN;let{value:t,unit:r="ms"}=e.groups,s=parseFloat(t),i=r.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 Error(`Unknown unit "${i}" provided to ms.parse(). value=${JSON.stringify(n)}`)}}function cg(n){let e=Math.abs(n);return e>=315576e5?`${Math.round(n/315576e5)}y`:e>=26298e5?`${Math.round(n/26298e5)}mo`:e>=6048e5?`${Math.round(n/6048e5)}w`:e>=864e5?`${Math.round(n/864e5)}d`:e>=36e5?`${Math.round(n/36e5)}h`:e>=6e4?`${Math.round(n/6e4)}m`:e>=1e3?`${Math.round(n/1e3)}s`:`${n}ms`}function lg(n){let e=Math.abs(n);return e>=315576e5?ut(n,e,315576e5,"year"):e>=26298e5?ut(n,e,26298e5,"month"):e>=6048e5?ut(n,e,6048e5,"week"):e>=864e5?ut(n,e,864e5,"day"):e>=36e5?ut(n,e,36e5,"hour"):e>=6e4?ut(n,e,6e4,"minute"):e>=1e3?ut(n,e,1e3,"second"):`${n} ms`}function ug(n,e){if(typeof n!="number"||!Number.isFinite(n))throw Error("Value provided to ms.format() must be of type number.");return e?.long?lg(n):cg(n)}function ut(n,e,t,r){let s=e>=t*1.5;return`${Math.round(n/t)} ${r}${s?"s":""}`}var fs,Bo=w(()=>{"use strict";fs=og});function Do(n){t.debug=t,t.default=t,t.coerce=a,t.disable=i,t.enable=s,t.enabled=o,t.humanize=fs,t.destroy=u,Object.keys(n).forEach(l=>{t[l]=n[l]}),t.names=[],t.skips=[],t.formatters={};function e(l){let h=0;for(let g=0;g<l.length;g++)h=(h<<5)-h+l.charCodeAt(g),h|=0;return t.colors[Math.abs(h)%t.colors.length]}t.selectColor=e;function t(l,h){let g,d=null,f,y;function k(...m){if(!k.enabled)return;let b=k,v=Number(new Date),A=v-(g||v);b.diff=A,b.prev=g,b.curr=v,g=v,m[0]=t.coerce(m[0]),typeof m[0]!="string"&&m.unshift("%O");let E=0;m[0]=m[0].replace(/%([a-zA-Z%])/g,(x,P)=>{if(x==="%%")return"%";E++;let G=t.formatters[P];if(typeof G=="function"){let he=m[E];x=G.call(b,he),m.splice(E,1),E--}return x}),t.formatArgs.call(b,m),h?.onLog!=null&&h.onLog(...m),(b.log||t.log).apply(b,m)}return k.namespace=l,k.useColors=t.useColors(),k.color=t.selectColor(l),k.extend=r,k.destroy=t.destroy,Object.defineProperty(k,"enabled",{enumerable:!0,configurable:!1,get:()=>d!==null?d:(f!==t.namespaces&&(f=t.namespaces,y=t.enabled(l)),y),set:m=>{d=m}}),typeof t.init=="function"&&t.init(k),k}function r(l,h){let g=t(this.namespace+(typeof h>"u"?":":h)+l);return g.log=this.log,g}function s(l){t.save(l),t.namespaces=l,t.names=[],t.skips=[];let h,g=(typeof l=="string"?l:"").split(/[\s,]+/),d=g.length;for(h=0;h<d;h++)g[h]&&(l=g[h].replace(/\*/g,".*?"),l[0]==="-"?t.skips.push(new RegExp("^"+l.substr(1)+"$")):t.names.push(new RegExp("^"+l+"$")))}function i(){let l=[...t.names.map(c),...t.skips.map(c).map(h=>"-"+h)].join(",");return t.enable(""),l}function o(l){if(l[l.length-1]==="*")return!0;let h,g;for(h=0,g=t.skips.length;h<g;h++)if(t.skips[h].test(l))return!1;for(h=0,g=t.names.length;h<g;h++)if(t.names[h].test(l))return!0;return!1}function c(l){return l.toString().substring(2,l.toString().length-2).replace(/\.\*\?$/,"*")}function a(l){return l instanceof Error?l.stack??l.message:l}function u(){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 Vu=w(()=>{"use strict";Bo()});function hg(){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 fg(n){if(n[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+n[0]+(this.useColors?"%c ":" ")+"+"+fs(this.diff),!this.useColors)return;let e="color: "+this.color;n.splice(1,0,e,"color: inherit");let t=0,r=0;n[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(r=t))}),n.splice(r,0,e)}function gg(n){try{n?ps?.setItem("debug",n):ps?.removeItem("debug")}catch{}}function mg(){let n;try{n=ps?.getItem("debug")}catch{}return!n&&typeof globalThis.process<"u"&&"env"in globalThis.process&&(n=globalThis.process.env.DEBUG),n}function yg(){try{return localStorage}catch{}}function wg(n){n.j=function(e){try{return JSON.stringify(e)}catch(t){return"[UnexpectedJSONParseError]: "+t.message}}}var ps,dg,pg,Gu,Yu=w(()=>{"use strict";Bo();Vu();ps=yg(),dg=["#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"];pg=console.debug??console.log??(()=>{});Gu=Do({formatArgs:fg,save:gg,load:mg,useColors:hg,setupFormatters:wg,colors:dg,storage:ps,log:pg})});var X,ju=w(()=>{"use strict";Yu();X=Gu});function Ju(n,e=""){let t=Qu(n.message),r=Qu(n.stack);return t!=null&&r!=null?r.includes(t)?`${r.split(`
948
951
  `).join(`
949
952
  ${e}`)}`:`${t}
950
953
  ${e}${r.split(`
@@ -954,7 +957,7 @@ ${e}`)}`:r!=null?`${r.split(`
954
957
  ${e}`)}`:t!=null?`${t}`:`${n.toString()}`}function bg(n){return n instanceof AggregateError||n?.name==="AggregateError"&&Array.isArray(n.errors)}function Xu(n,e=""){if(bg(n)){let t=Ju(n,e);return n.errors.length>0?(e=`${e} `,t+=`
955
958
  ${e}${n.errors.map(r=>`${Xu(r,`${e}`)}`).join(`
956
959
  ${e}`)}`):t+=`
957
- ${e}[Error list was empty]`,t.trim()}return Ju(n,e)}function Sg(n){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=n,e.destroy=()=>!0,e.extend=()=>e,e}function Do(n,e){let t=Sg(`${n}:trace`);return X.enabled(`${n}:trace`)&&X.names.map(r=>r.toString()).find(r=>r.includes(":trace"))!=null&&(t=X(`${n}:trace`,e)),Object.assign(X(n,e),{error:X(`${n}:error`,e),trace:t,newScope:r=>Do(`${n}:${r}`,e)})}function Qu(n){if(n!=null&&(n=n.trim(),n.length!==0))return n}var Zu=w(()=>{"use strict";Er();Hn();Xi();ju();X.formatters.b=n=>n==null?"undefined":de.baseEncode(n);X.formatters.t=n=>n==null?"undefined":J.baseEncode(n);X.formatters.m=n=>n==null?"undefined":Ji.baseEncode(n);X.formatters.p=n=>n==null?"undefined":n.toString();X.formatters.c=n=>n==null?"undefined":n.toString();X.formatters.k=n=>n==null?"undefined":n.toString();X.formatters.a=n=>n==null?"undefined":n.toString();X.formatters.e=n=>n==null?"undefined":Xu(n)});function xg(n){let[e,t]=n[Symbol.asyncIterator]!=null?[n[Symbol.asyncIterator](),Symbol.asyncIterator]:[n[Symbol.iterator](),Symbol.iterator],r=[];return{peek:()=>e.next(),push:s=>{r.push(s)},next:()=>r.length>0?{done:!1,value:r.shift()}:e.next(),[t](){return this}}}var ed,td=w(()=>{"use strict";ed=xg});function vg(n){return n[Symbol.asyncIterator]!=null}function Ag(n,e){let t=0;if(vg(n))return(async function*(){for await(let a of n)await e(a,t++)&&(yield a)})();let r=ed(n),{value:s,done:i}=r.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 a of r)await e(a,t++)&&(yield a)})();let c=e;return(function*(){o===!0&&(yield s);for(let a of r)c(a,t++)&&(yield a)})()}var rd,nd=w(()=>{"use strict";td();rd=Ag});function Qt(){let n={};return n.promise=new Promise((e,t)=>{n.resolve=e,n.reject=t}),n}var sd=w(()=>{"use strict"});async function id(n,e,t){if(e==null)return n;if(e.aborted)return n.catch(()=>{}),Promise.reject(new ps(t?.errorMessage,t?.errorCode,t?.errorName));let r,s=new ps(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([n,new Promise((i,o)=>{r=()=>{o(s)},e.addEventListener("abort",r)})])}finally{r!=null&&e.removeEventListener("abort",r)}}var ps,od=w(()=>{"use strict";ps=class extends Error{constructor(t,r,s){super(t??"The operation was aborted");p(this,"type");p(this,"code");this.type="aborted",this.name=s??"AbortError",this.code=r??"ABORT_ERR"}}});function ad(){return new Ro}var Ro,cd=w(()=>{"use strict";sd();od();Ro=class{constructor(){p(this,"readNext");p(this,"haveNext");p(this,"ended");p(this,"nextResult");p(this,"error");this.ended=!1,this.readNext=Qt(),this.haveNext=Qt()}[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=Qt(),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=Qt(),await id(this.readNext.promise,t?.signal,t)}}});function kg(n){return n[Symbol.asyncIterator]!=null}async function Eg(n,e,t){try{await Promise.all(n.map(async r=>{for await(let s of r)await e.push(s,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(r){await e.end(r,{signal:t}).catch(()=>{})}}async function*Cg(n){let e=new AbortController,t=ad();Eg(n,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Pg(n){for(let e of n)yield*e}function Ig(...n){let e=[];for(let t of n)kg(t)||e.push(t);return e.length===n.length?Pg(e):Cg(n)}var ld,ud=w(()=>{"use strict";cd();ld=Ig});var Bg,gs,dd=w(()=>{"use strict";Zu();ls();nd();ud();qr();Bg=Do("blockstore:core:tiered"),gs=class extends Ee{constructor(t){super();p(this,"stores");this.stores=t.slice()}async put(t,r,s){return await Promise.all(this.stores.map(async i=>{await i.put(t,r,s)})),t}async*get(t,r){let s;for(let i of this.stores)try{yield*i.get(t,r);return}catch(o){s=o,Bg.error(o)}throw s??new He}async has(t,r){for(let s of this.stores)if(await s.has(t,r))return!0;return!1}async delete(t,r){await Promise.all(this.stores.map(async s=>{await s.delete(t,r)}))}async*putMany(t,r={}){for await(let s of t)await this.put(s.cid,s.bytes,r),yield s.cid}async*deleteMany(t,r={}){for await(let s of t)await this.delete(s,r),yield s}async*getAll(t){let r=new Set;yield*rd(ld(...this.stores.map(s=>s.getAll(t))),s=>{let i=s.cid.toString();return r.has(i)?!1:(r.add(i),!0)})}}});var hd={};B(hd,{BaseBlockstore:()=>Ee,BlackHoleBlockstore:()=>ds,MemoryBlockstore:()=>us,TieredBlockstore:()=>gs});var fd=w(()=>{"use strict";qr();qu();Hu();dd()});var pd=D((zS,Dg)=>{Dg.exports={name:"w3pk",version:"0.9.2",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","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","release:notes":"node scripts/generate-release-notes.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":"^24.9.0","@types/qrcode":"^1.5.5",circomlib:"^2.0.5",tsup:"^8.5.1",tsx:"^4.21.0",typescript:"^5.9.3"},peerDependencies:{ethers:"^6.0.0"},optionalDependencies:{"@ipld/car":"^5.4.2","blockstore-core":"^6.1.1",circomlibjs:"^0.1.7","ipfs-unixfs-importer":"^16.0.1",qrcode:"^1.5.4",snarkjs:"^0.7.5"}}});var Ug={};B(Ug,{ApiError:()=>Hr,AuthenticationError:()=>O,CryptoError:()=>N,DEFAULT_MODE:()=>fe,DEFAULT_TAG:()=>pe,RecoverySimulator:()=>kt,RegistrationError:()=>ht,StealthAddressModule:()=>yt,StorageError:()=>R,WalletError:()=>S,Web3Passkey:()=>Et,Web3PasskeyError:()=>$,arrayBufferToBase64Url:()=>Se,assertEthereumAddress:()=>Vr,assertMnemonic:()=>Lo,assertUsername:()=>Gr,authenticateWithPasskey:()=>li,base64ToArrayBuffer:()=>Ss,base64UrlDecode:()=>vs,base64UrlToArrayBuffer:()=>L,canControlStealthAddress:()=>Ho,checkStealthAddress:()=>nr,clearCache:()=>Zo,computeStealthPrivateKey:()=>sr,createSiweMessage:()=>yd,createWalletFromMnemonic:()=>Es,createWeb3Passkey:()=>xd,default:()=>Ng,deriveAddressFromP256PublicKey:()=>Ps,deriveIndexFromOriginModeAndTag:()=>Zr,deriveStealthKeys:()=>mt,deriveWalletFromMnemonic:()=>tr,detectWalletProvider:()=>dn,encodeEIP7702AuthorizationMessage:()=>or,extractRS:()=>Fs,generateBIP39Wallet:()=>er,generateSiweNonce:()=>md,generateStealthAddress:()=>tn,getAllChains:()=>Qo,getAllTopics:()=>hi,getChainById:()=>Xo,getCurrentBuildHash:()=>Mo,getCurrentOrigin:()=>Me,getDefaultProvider:()=>un,getEndpoints:()=>on,getExplainer:()=>di,getOriginSpecificAddress:()=>Fe,getPackageVersion:()=>Fo,getW3pkBuildHash:()=>To,hashEIP7702AuthorizationMessage:()=>ar,inspect:()=>No,inspectNow:()=>Sd,isStrongPassword:()=>_o,normalizeOrigin:()=>rr,parseSiweMessage:()=>ms,promptPasskeySelection:()=>ci,requestExternalWalletAuthorization:()=>ln,safeAtob:()=>Ve,safeBtoa:()=>xs,searchExplainers:()=>fi,supportsEIP7702Authorization:()=>hn,validateEthereumAddress:()=>ys,validateMnemonic:()=>bs,validateSiweMessage:()=>wd,validateUsername:()=>ws,verifyBuildHash:()=>gd,verifyEIP7702Authorization:()=>an,verifySiweSignature:()=>bd});module.exports=Bd(Ug);Y();function ys(n){return/^0x[a-fA-F0-9]{40}$/.test(n)}function ws(n){return n.length<3||n.length>50?!1:/^[a-zA-Z0-9]([a-zA-Z0-9_-]*[a-zA-Z0-9])?$/.test(n)}function bs(n){let e=n.trim().split(/\s+/);return e.length===12||e.length===24}function Vr(n){if(!ys(n))throw new Error("Invalid Ethereum address format")}function Gr(n){if(!ws(n))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 Lo(n){if(!bs(n))throw new Error("Invalid mnemonic: must be 12 or 24 words")}function _o(n){if(n.length<12)return!1;let e=/[A-Z]/.test(n),t=/[a-z]/.test(n),r=/[0-9]/.test(n),s=/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(n);return!(!e||!t||!r||!s||["password","12345678","qwerty","abc123","password123","admin","letmein"].some(o=>n.toLowerCase().includes(o)))}Te();xe();q();async function Rd(n){try{let e=new Uint8Array(n),t=Td(e);if(t===-1)return null;let r=e.slice(t);if(!((r[32]&64)!==0))return null;let o=37;o+=16;let c=r[o]<<8|r[o+1];o+=2,o+=c;let a=r.slice(o),u=await Fd(a);return Se(u)}catch(e){return console.error("Failed to extract public key:",e),null}}function Td(n){let e=new Uint8Array([104,97,117,116,104,68,97,116,97]);for(let t=0;t<n.length-e.length;t++){let r=!0;for(let s=0;s<e.length;s++)if(n[t+s]!==e[s]){r=!1;break}if(r){let s=n[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 Fd(n){let e=Ko(n,-2),t=Ko(n,-3);if(!e||!t)throw new Error("Failed to extract EC coordinates from COSE key");let r=new Uint8Array(65);r[0]=4,r.set(e,1),r.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+r.length);return i.set(s,0),i.set(r,s.length),i.buffer}function Ko(n,e){let t=e<0?32+(-1-e):e;for(let r=0;r<n.length-33;r++)if(n[r]===t&&(n[r+1]===88&&n[r+2]===32||n[r+1]===88&&n[r+2]===32))return n.slice(r+3,r+35);return null}async function zo(n){try{let{username:e,ethereumAddress:t}=n;Gr(e),Vr(t);let r=new F;if(await r.userExists(e))throw new Error("Username already registered");let s=De(),o=new TextEncoder().encode(e),c=Se(o),a=L(s),u=L(c),l={challenge:a,rp:{name:"w3pk",id:window.location.hostname},user:{id:u,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"},h=await navigator.credentials.create({publicKey:l});if(!h)throw new Error("Failed to create credential");let g=await Rd(h.response.attestationObject);if(!g)throw new Error("Public key not returned from authenticator");return await r.saveCredential({id:h.id,publicKey:g,username:e,ethereumAddress:t,createdAt:new Date().toISOString(),lastUsed:new Date().toISOString(),signCount:0}),{signature:h.response.attestationObject}}catch(e){throw new ht(e instanceof Error?e.message:"Registration failed",e)}}Y();Te();xe();q();async function Qr(){try{let n=new F,e=De(),t=[];try{let a=await n.getAllCredentials();a.length>0&&(t=a.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};t.length>0&&(s.allowCredentials=t.map(a=>({id:L(a.id),type:a.type,transports:a.transports})));let i;try{let a=await navigator.credentials.get({publicKey:s});if(!a)throw new Error("Authentication failed - no credential returned");i=a}catch(a){throw a?.name==="NotAllowedError"||a?.message?.toLowerCase().includes("no credentials available")||a?.message?.toLowerCase().includes("no access key")?(await n.getAllCredentials()).length>0?new O("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 O("No passkey found. Please register first or restore from a backup."):a}let o=await n.getCredentialById(i.id);if(!o)throw new O("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 Md(i,o,n))throw new Error("Signature verification failed");return{verified:!0,user:{username:o.username,ethereumAddress:o.ethereumAddress,credentialId:o.id},signature:i.response.signature}}catch(n){throw new O(n instanceof Error?n.message:"Authentication failed",n)}}async function Md(n,e,t){try{let r=n.response.authenticatorData,s=new DataView(r),o=new Uint8Array(r).slice(0,32),c=window.location.hostname,a=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c)));if(!Nd(o,a))return console.error("RP ID hash mismatch - possible phishing attack"),!1;let u=s.getUint32(33,!1);if(u>0||e.signCount&&e.signCount>0){let b=e.signCount||0;if(u<=b)return console.error(`Authenticator cloning detected! Counter did not increase: stored=${b}, received=${u}`),!1}let l=L(e.publicKey),h=await crypto.subtle.importKey("spki",l,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),g=n.response.clientDataJSON,d=await crypto.subtle.digest("SHA-256",g),f=new Uint8Array(r.byteLength+d.byteLength);f.set(new Uint8Array(r),0),f.set(new Uint8Array(d),r.byteLength);let y=n.response.signature,k=Ud(new Uint8Array(y));return await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},h,k,f)?(await t.updateSignatureCounter(e.id,u),!0):!1}catch(r){return console.error("Signature verification error:",r),!1}}function Nd(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]!==e[t])return!1;return!0}function Ud(n){let e=2;e++;let t=n[e++];t>32&&(e++,t--);let r=n.slice(e,e+t);e+=t,e++;let s=n[e++];s>32&&(e++,s--);let i=n.slice(e,e+s),o=new Uint8Array(64);return o.set(r,32-r.length),o.set(i,64-i.length),o.buffer}Y();var Ld="Web3PasskeyWallet",_d=1,ve="wallets",Xr=class{constructor(){this.db=null}async init(){return new Promise((e,t)=>{let r=indexedDB.open(Ld,_d);r.onerror=()=>t(new R("Failed to open database",r.error)),r.onsuccess=()=>{this.db=r.result,e()},r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(ve)||s.createObjectStore(ve,{keyPath:"ethereumAddress"})}})}async store(e){return this.db||await this.init(),new Promise((t,r)=>{let o=this.db.transaction([ve],"readwrite").objectStore(ve).put(e);o.onerror=()=>r(new R("Failed to store wallet data",o.error)),o.onsuccess=()=>t()})}async retrieve(e){return this.db||await this.init(),new Promise((t,r)=>{let o=this.db.transaction([ve],"readonly").objectStore(ve).get(e);o.onerror=()=>r(new R("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,r)=>{let o=this.db.transaction([ve],"readwrite").objectStore(ve).delete(e);o.onerror=()=>r(new R("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([ve],"readwrite").objectStore(ve).clear();i.onerror=()=>t(new R("Failed to clear wallet data",i.error)),i.onsuccess=()=>e()})}};pt();gt();q();Y();var H=require("ethers");Y();function mt(n){try{let e=H.ethers.HDNodeWallet.fromPhrase(n,void 0,"m/44'/60'/1'/0/0"),t=H.ethers.HDNodeWallet.fromPhrase(n,void 0,"m/44'/60'/1'/0/1"),r=t.signingKey.compressedPublicKey,s=e.signingKey.compressedPublicKey;return{stealthMetaAddress:r+s.slice(2),spendingPubKey:r,viewingPubKey:s,viewingKey:e.privateKey,spendingKey:t.privateKey}}catch(e){throw new N("Failed to derive stealth keys",e)}}function tn(n){try{let e="0x"+n.slice(2,68),t="0x"+n.slice(68),r=H.ethers.Wallet.createRandom(),s=r.signingKey.compressedPublicKey,i=Is(r.privateKey,t),o=H.ethers.keccak256(i),c="0x"+o.slice(2,4),a=Go(e,Vo(o));return{stealthAddress:Yo(a),ephemeralPubKey:s,viewTag:c}}catch(e){throw new N("Failed to generate stealth address",e)}}function nr(n,e,t,r,s){try{let i=Is(n,t),o=H.ethers.keccak256(i);if(s&&("0x"+o.slice(2,4)).toLowerCase()!==s.toLowerCase())return{isForUser:!1};let c=Go(e,Vo(o)),a=Yo(c);return a.toLowerCase()!==r.toLowerCase()?{isForUser:!1}:{isForUser:!0,stealthAddress:a}}catch{return{isForUser:!1}}}function sr(n,e,t){try{let r=Is(n,t),s=H.ethers.keccak256(r);return Kd(e,s)}catch(r){throw new N("Failed to compute stealth private key",r)}}function Ho(n,e,t,r,s,i){try{if(!nr(n,t,r,s,i).isForUser)return!1;let c=sr(n,e,r);return new H.ethers.Wallet(c).address.toLowerCase()===s.toLowerCase()}catch{return!1}}function Is(n,e){try{return new H.ethers.Wallet(n).signingKey.computeSharedSecret(e)}catch(t){throw new N("Failed to compute shared secret",t)}}function Vo(n){try{return new H.ethers.Wallet(n).signingKey.compressedPublicKey}catch(e){throw new N("Failed to multiply generator by scalar",e)}}function Go(n,e){try{let t=H.ethers.SigningKey.computePublicKey(n,!1),r=H.ethers.SigningKey.computePublicKey(e,!1),s=BigInt("0x"+t.slice(4,68)),i=BigInt("0x"+t.slice(68)),o=BigInt("0x"+r.slice(4,68)),c=BigInt("0x"+r.slice(68)),a=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F");if(s===o&&i===c){let f=3n*s*s%a,y=2n*i%a,k=f*qo(y,a)%a,m=(k*k-2n*s)%a,b=(k*(s-m)-i)%a;return $o((m+a)%a,(b+a)%a)}let u=((c-i)%a+a)%a,l=((o-s)%a+a)%a,h=u*qo(l,a)%a,g=(h*h-s-o)%a,d=(h*(s-g)-i)%a;return $o((g+a)%a,(d+a)%a)}catch(t){throw new N("Failed to add public keys",t)}}function Kd(n,e){try{let t=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"),r=BigInt(n),s=BigInt(e);return"0x"+((r+s)%t).toString(16).padStart(64,"0")}catch(t){throw new N("Failed to add private keys",t)}}function $o(n,e){return"0x"+(e%2n===0n?"02":"03")+n.toString(16).padStart(64,"0")}function qo(n,e){n=(n%e+e)%e;let[t,r]=[n,e],[s,i]=[1n,0n];for(;r!==0n;){let o=t/r;[t,r]=[r,t-o*r],[s,i]=[i,s-o*i]}return(s%e+e)%e}function Yo(n){try{let e=H.ethers.SigningKey.computePublicKey(n,!1),t=H.ethers.keccak256("0x"+e.slice(4));return H.ethers.getAddress("0x"+t.slice(-40))}catch(e){throw new N("Failed to derive address from public key",e)}}var yt=class{constructor(e,t){this.getMnemonic=t}async generateStealthAddress(e){try{let t=await this.getMnemonic(e?.requireAuth),r=mt(t),s=tn(r.stealthMetaAddress);return{stealthAddress:s.stealthAddress,ephemeralPublicKey:s.ephemeralPubKey,viewTag:s.viewTag}}catch(t){throw new $("Failed to generate stealth address","STEALTH_GENERATION_ERROR",t)}}async parseAnnouncement(e,t){try{let r=await this.getMnemonic(t?.requireAuth),s=mt(r),i=nr(s.viewingKey,s.spendingPubKey,e.ephemeralPublicKey,e.stealthAddress,e.viewTag);if(!i.isForUser)return{isForUser:!1};let o=sr(s.viewingKey,s.spendingKey,e.ephemeralPublicKey);return{isForUser:!0,stealthAddress:i.stealthAddress,stealthPrivateKey:o}}catch(r){throw new $("Failed to parse announcement","ANNOUNCEMENT_PARSE_ERROR",r)}}async scanAnnouncements(e,t){let r=[];for(let s of e){let i=await this.parseAnnouncement(s,t);i.isForUser&&r.push(i)}return r}async getKeys(e){try{let t=await this.getMnemonic(e?.requireAuth);return mt(t)}catch(t){throw new $("Failed to get stealth keys","STEALTH_KEYS_ERROR",t)}}async getStealthMetaAddress(e){try{return(await this.getKeys(e)).stealthMetaAddress}catch(t){throw new $("Failed to get stealth meta-address","STEALTH_META_ADDRESS_ERROR",t)}}get isAvailable(){return!0}};Y();q();var zd="Web3PasskeyPersistentSessions",Wd=2,ae="sessions",rn=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 r=indexedDB.open(zd,Wd);r.onupgradeneeded=s=>{let i=s.target.result;i.objectStoreNames.contains(ae)||i.createObjectStore(ae,{keyPath:"ethereumAddress"}).createIndex("expiresAt","expiresAt",{unique:!1})},r.onsuccess=()=>{this.db=r.result,this.initPromise=null,e()},r.onerror=()=>{this.initPromise=null,t(new R("Failed to open persistent session database",r.error))}}),this.initPromise)}async store(e){if(e.securityMode==="STRICT")throw new R("Cannot persist STRICT mode sessions");return this.db||await this.init(),new Promise((t,r)=>{let o=this.db.transaction([ae],"readwrite").objectStore(ae).put(e);o.onerror=()=>r(new R("Failed to store persistent session",o.error)),o.onsuccess=()=>t()})}async retrieve(e){return this.db||await this.init(),new Promise((t,r)=>{let o=this.db.transaction([ae],"readonly").objectStore(ae).get(e);o.onerror=()=>r(new R("Failed to retrieve persistent session",o.error)),o.onsuccess=()=>{let c=o.result||null;if(c&&Date.now()>c.expiresAt){this.delete(e).catch(console.error),t(null);return}t(c)}})}async delete(e){return this.db||await this.init(),new Promise((t,r)=>{let o=this.db.transaction([ae],"readwrite").objectStore(ae).delete(e);o.onerror=()=>r(new R("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([ae],"readwrite").objectStore(ae).clear();i.onerror=()=>t(new R("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([ae],"readwrite").objectStore(ae).index("expiresAt"),o=Date.now(),c=IDBKeyRange.upperBound(o),a=i.openCursor(c);a.onsuccess=u=>{let l=u.target.result;l?(l.delete(),l.continue()):e()},a.onerror=()=>t(new R("Failed to cleanup expired sessions",a.error))})}};async function jo(n,e,t){try{let r=await j(e,t);return await ie(n,r)}catch(r){throw new N("Failed to encrypt mnemonic for persistence",r)}}async function Bs(n,e,t){try{let r=await j(e,t);return await oe(n,r)}catch(r){throw new N("Failed to decrypt mnemonic from persistence",r)}}var nn=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 rn}async startSession(e,t,r,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"&&r&&s)try{let c=await jo(e,t,s),a=Date.now()+this.persistentConfig.duration*60*60*1e3;await this.persistentStorage.store({encryptedMnemonic:c,expiresAt:a,credentialId:t,ethereumAddress:r,securityMode:i||"STANDARD",createdAt:Date.now()})}catch(c){console.warn("[w3pk] Failed to persist session:",c)}}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,r){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 Bs(s.encryptedMnemonic,t,r),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(()=>(Te(),Jr)),r=await new e().getAllCredentials();if(r.length===0)return null;for(let s of r){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 Bs(i.encryptedMnemonic,s.id,s.publicKey),c=new Date(Date.now()+this.sessionDuration).toISOString();return this.session={mnemonic:o,expiresAt:c,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}};Te();var sn={debug:!1,sessionDuration:1,persistentSession:{enabled:!1,duration:168,requireReauth:!0},onError:n=>{sn.debug&&console.error("[w3pk]",n)}};Y();var Jo="https://chainid.network/chains.json";var ir=null,$d=[/\$\{[\w_]+\}/i,/\{[\w_]+\}/i,/<[\w_]+>/i,/YOUR[-_]?API[-_]?KEY/i,/INSERT[-_]?API[-_]?KEY/i,/API[-_]?KEY[-_]?HERE/i];function qd(n){return $d.some(e=>e.test(n))}async function Hd(n=Jo){let e=await fetch(n);if(!e.ok)throw new Error(`Failed to fetch chains data: ${e.status} ${e.statusText}`);return await e.json()}async function Ds(n){let e=n?.chainsJsonUrl??Jo,t=n?.cacheDuration??36e5,r=Date.now();if(ir&&r-ir.timestamp<t)return ir.data;let s=await Hd(e);return ir={data:s,timestamp:r},s}async function on(n,e){let r=(await Ds(e)).find(s=>s.chainId===n);return r?r.rpc.filter(s=>!qd(s)&&!s.startsWith("wss://")&&!s.startsWith("ws://")):[]}async function Qo(n){return Ds(n)}async function Xo(n,e){return(await Ds(e)).find(r=>r.chainId===n)}function Zo(){ir=null}Ts();cn();var Vd=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 Gd(n,e=1e4){try{let t=new AbortController,r=setTimeout(()=>t.abort(),e),s=await fetch(n,{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(r),!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(a=>o.includes(a))}return i.result!==void 0}catch{return!1}}async function ta(n,e,t){if(Vd.has(n))return!0;let r=t?.maxEndpoints||3,s=t?.timeout||1e4;try{let i=await e(n);if(i.length===0)return!1;let o=i.slice(0,r);for(let c of o)if(await Gd(c,s))return!0;return!1}catch{return!1}}function wc(n){return typeof n=="string"&&/^0x[0-9a-fA-F]*$/.test(n)}function bc(n){let e=n.startsWith("0x")?n.slice(2):n,t=new Uint8Array(e.match(/.{1,2}/g).map(r=>parseInt(r,16)));return new TextDecoder().decode(t)}var Et=class{constructor(e={}){this.currentUser=null;this.currentWallet=null;this.config={...sn,...e},this.walletStorage=new Xr;let t={...sn.persistentSession,...e.persistentSession};this.sessionManager=new nn(e.sessionDuration||1,t),e.stealthAddresses!==void 0&&(this.stealth=new yt(e.stealthAddresses,r=>this.getMnemonicFromSession(r)))}async loadZKModule(){if(this.zkModule)return this.zkModule;try{let e=new Function("path","return import(path)"),{ZKProofModule:t}=await e("w3pk/zk"),r=this.config.zkProofs||{};return this.zkModule=new t(r),this.zkModule}catch{throw new Error("ZK module not available. Install dependencies: npm install snarkjs circomlibjs")}}async getMnemonicFromSession(e=!1,t="STANDARD"){let r=t;if(!e){let h=this.sessionManager.getMnemonic();if(h)return h}if(!this.currentUser)throw new S("Must be authenticated. Call login() first.");let s=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!s)throw new S("No wallet found. Generate a wallet first.");if(!(await Qr()).user)throw new S("Authentication failed");let a=(await new F().getCredentialById(s.credentialId))?.publicKey,u=await j(s.credentialId,a),l=await oe(s.encryptedMnemonic,u);return await this.sessionManager.startSession(l,s.credentialId,this.currentUser.ethereumAddress,a,r),l}async register(e){try{this.currentWallet?.address||await this.generateWallet();let t=this.currentWallet.address,r=this.currentWallet.mnemonic;await zo({username:e.username,ethereumAddress:t});let i=await new F().getCredentialByAddress(t);if(this.currentUser={username:e.username,ethereumAddress:t,credentialId:i?.id||""},!i)throw new S("Credential not found after registration");let o=i.id,c=i.publicKey,a=await j(o,c),u=await ie(r,a);return await this.walletStorage.store({ethereumAddress:this.currentUser.ethereumAddress,encryptedMnemonic:u,credentialId:o,createdAt:new Date().toISOString()}),await this.sessionManager.startSession(r,o,t,c,"STANDARD"),this.currentWallet={address:t,mnemonic:r},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 l=await new F().getCredentialById(e.credentialId);return this.currentUser={username:l?.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 O("Login failed");this.currentUser={username:t.user.username,ethereumAddress:t.user.ethereumAddress,credentialId:t.user.credentialId};let r=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!r)return this.config.onAuthStateChanged?.(!0,this.currentUser),this.currentUser;let o=(await new F().getCredentialById(r.credentialId))?.publicKey,c=await this.sessionManager.restoreFromPersistentStorage(this.currentUser.ethereumAddress,r.credentialId,o||""),a;if(c)a=c;else{let u=await j(r.credentialId,o);a=await oe(r.encryptedMnemonic,u),await this.sessionManager.startSession(a,r.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 F().getAllCredentials()).map(r=>({username:r.username,ethereumAddress:r.ethereumAddress,createdAt:r.createdAt,lastUsed:r.lastUsed}))}catch{return[]}}async hasExistingCredential(){return(await this.listExistingCredentials()).length>0}async getExistingCredentialCount(){return(await this.listExistingCredentials()).length}async generateWallet(){try{let e=er();return this.currentWallet={address:e.address,mnemonic:e.mnemonic},{address:e.address,mnemonic:e.mnemonic}}catch(e){throw this.config.onError?.(e),new S("Failed to generate wallet",e)}}async deriveWallet(e,t,r){try{if(!this.currentUser)throw new S("Must be authenticated to derive wallet");let s=e||fe,i=t||pe,o=r?.origin||Me();if(s==="PRIMARY"){let{CredentialStorage:l}=await Promise.resolve().then(()=>(Te(),Jr)),{deriveAddressFromP256PublicKey:h}=await Promise.resolve().then(()=>(gt(),en)),d=await new l().getCredentialById(this.currentUser.credentialId);if(!d||!d.publicKey)throw new S("No WebAuthn credential found for PRIMARY mode");return{address:await h(d.publicKey),origin:o,mode:s,tag:i,publicKey:d.publicKey}}let c=s==="STRICT"?!0:r?.requireAuth||!1,a=await this.getMnemonicFromSession(c,s),u=await Fe(a,o,s,i);return{address:u.address,privateKey:u.privateKey,index:u.index,origin:u.origin,mode:u.mode,tag:u.tag}}catch(s){throw this.config.onError?.(s),new S("Failed to derive wallet",s)}}async getAddress(e,t,r){try{if(!this.currentUser)throw new S("Must be authenticated to get address");let s=e||fe,i=t||pe,o=r?.origin||Me();if(s==="PRIMARY"){let{deriveAddressFromP256PublicKey:l}=await Promise.resolve().then(()=>(gt(),en)),g=await new F().getCredentialById(this.currentUser.credentialId);if(!g||!g.publicKey)throw new S("No WebAuthn credential found for PRIMARY mode");return await l(g.publicKey)}let c=s==="STRICT",a=await this.getMnemonicFromSession(c,s);return(await Fe(a,o,s,i)).address}catch(s){throw this.config.onError?.(s),new S("Failed to get address",s)}}async importMnemonic(e){try{if(!this.currentUser)throw new S("Must be authenticated to import mnemonic");if(!e||e.trim().split(/\s+/).length<12)throw new S("Invalid mnemonic: must be at least 12 words");let t=await Qr();if(!t.user)throw new S("Authentication failed");let r=t.user.credentialId,o=(await new F().getCredentialById(r))?.publicKey,c=await j(r,o),a=await ie(e.trim(),c);await this.walletStorage.store({ethereumAddress:this.currentUser.ethereumAddress,encryptedMnemonic:a,credentialId:r,createdAt:new Date().toISOString()}),this.currentWallet={address:this.currentUser.ethereumAddress,mnemonic:e.trim()},await this.sessionManager.startSession(e.trim(),r,this.currentUser.ethereumAddress,o,"STANDARD")}catch(t){throw this.config.onError?.(t),new S("Failed to import mnemonic",t)}}async signMessage(e,t){try{if(!this.currentUser)throw new S("Must be authenticated to sign message");let r=t?.mode||fe,s=t?.tag||pe,i=t?.origin||Me(),o=t?.signingMethod||"EIP191",c=r==="STRICT"?!0:t?.requireAuth||!1,a=await this.getMnemonicFromSession(c,r),u=await Fe(a,i,r,s),{Wallet:l}=await import("ethers"),h;if(u.privateKey)h=new l(u.privateKey);else{let{deriveWalletFromMnemonic:d}=await Promise.resolve().then(()=>(pt(),Cs)),{privateKey:f}=d(a,u.index);h=new l(f)}let g;switch(o){case"EIP191":case"SIWE":g=await h.signMessage(e);break;case"EIP712":if(!t?.eip712Domain||!t?.eip712Types||!t?.eip712PrimaryType)throw new S("EIP712 signing requires eip712Domain, eip712Types, and eip712PrimaryType in options");let d;try{d=typeof e=="string"?JSON.parse(e):e}catch{throw new S("EIP712 message must be valid JSON or an object")}g=await h.signTypedData(t.eip712Domain,t.eip712Types,d);break;case"rawHash":let{SigningKey:f}=await import("ethers"),y=e;if(y.startsWith("0x")&&(y=y.slice(2)),y.length!==64)throw new S("rawHash signing method requires a 32-byte hash (64 hex characters)");g=new f(h.privateKey).sign("0x"+y).serialized;break;default:throw new S(`Unsupported signing method: ${o}`)}return{signature:g,address:u.address,mode:u.mode,tag:u.tag,origin:u.origin}}catch(r){throw this.config.onError?.(r),new S("Failed to sign message",r)}}async signMessageWithPasskey(e){try{if(!this.currentUser)throw new S("Must be authenticated to sign message");let{extractRS:t}=await Promise.resolve().then(()=>(Ms(),ra)),{base64UrlDecode:r}=await Promise.resolve().then(()=>(xe(),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")),c=this.currentUser.credentialId;if(!c)throw new S("Credential ID not found in user object");let a={challenge:o,rpId:window.location.hostname,allowCredentials:[{id:r(c),type:"public-key",transports:["internal","hybrid","usb","nfc","ble"]}],userVerification:"required",timeout:6e4},u=await navigator.credentials.get({publicKey:a});if(!u||!u.response)throw new S("WebAuthn signature failed");let l=u.response,h=new Uint8Array(l.authenticatorData),g=new Uint8Array(l.clientDataJSON),d=await crypto.subtle.digest("SHA-256",g),f=new Uint8Array(h.length+d.byteLength);f.set(h,0),f.set(new Uint8Array(d),h.length);let y=await crypto.subtle.digest("SHA-256",f.buffer),k="0x"+Buffer.from(y).toString("hex"),m=new Uint8Array(l.signature),{r:b,s:v}=t(m),{CredentialStorage:A}=await Promise.resolve().then(()=>(Te(),Jr)),C=await new A().getCredentialById(c);if(!C||!C.publicKey)throw new S("No WebAuthn credential found for PRIMARY mode");let{base64UrlToArrayBuffer:x}=await Promise.resolve().then(()=>(xe(),As)),P=x(C.publicKey),G=await crypto.subtle.importKey("spki",P,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),he=await crypto.subtle.exportKey("jwk",G);if(!he.x||!he.y)throw new S("Invalid P-256 public key: missing x or y coordinates");let ut="0x"+Buffer.from(x(he.x)).toString("hex"),dt="0x"+Buffer.from(x(he.y)).toString("hex"),{deriveAddressFromP256PublicKey:I}=await Promise.resolve().then(()=>(gt(),en)),vd=await I(C.publicKey);return{signature:{r:b,s:v},messageHash:i,signedHash:k,address:vd,publicKey:{qx:ut,qy:dt}}}catch(t){throw this.config.onError?.(t),new S("Failed to sign message with passkey",t)}}async sendTransaction(e,t){try{if(!this.currentUser)throw new S("Must be authenticated to send transaction");let r=t?.mode||fe,s=t?.tag||pe,i=t?.origin||Me();if(r==="PRIMARY")throw t?.rpcUrl?new S("PRIMARY mode sendTransaction is not yet supported. Use signMessageWithPasskey() to obtain a P-256 signature and submit via a bundler manually."):new S("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=r==="STRICT"?!0:t?.requireAuth||!1,c=await this.getMnemonicFromSession(o,r),a=await Fe(c,i,r,s),{Wallet:u,JsonRpcProvider:l}=await import("ethers"),h;if(a.privateKey)h=new u(a.privateKey);else{let{deriveWalletFromMnemonic:k}=await Promise.resolve().then(()=>(pt(),Cs)),{privateKey:m}=k(c,a.index);h=new u(m)}let g=t?.rpcUrl??(await this.getEndpoints(e.chainId))[0];if(!g)throw new S(`No RPC endpoint found for chainId ${e.chainId}. Pass options.rpcUrl.`);let d=new l(g);return{hash:(await h.connect(d).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:a.address,chainId:e.chainId,mode:a.mode,tag:a.tag,origin:a.origin}}catch(r){throw this.config.onError?.(r),new S("Failed to send transaction",r)}}async signAuthorization(e,t){try{if(!this.currentUser)throw new S("Must be authenticated to sign authorization");let{Wallet:r,Signature:s}=await import("ethers"),{hashEIP7702AuthorizationMessage:i,verifyEIP7702Authorization:o}=await Promise.resolve().then(()=>(cn(),Rs)),c;if(e.privateKey)c=new r(e.privateKey);else{let y=await this.getMnemonicFromSession(t?.requireAuth);c=r.fromPhrase(y)}let a=BigInt(e.chainId||1),u=e.nonce||0n,l=i(a,e.contractAddress,u),h=c.signingKey.sign(l),g=s.from(h),d={chainId:a,address:e.contractAddress.toLowerCase(),nonce:u,yParity:g.yParity,r:g.r,s:g.s};if(!o(a,e.contractAddress,u,d,c.address))throw new S("Signature verification failed - this should not happen");return d}catch(r){throw this.config.onError?.(r),new S("Failed to sign authorization",r)}}async getEndpoints(e){return on(e)}async supportsEIP7702(e,t){return ta(e,this.getEndpoints.bind(this),t)}getEIP1193Provider(e){let t=e?.chainId??1,r=this,s={},i=(c,...a)=>{(s[c]??[]).forEach(u=>u(...a))};return{async request({method:c,params:a}){switch(c){case"eth_accounts":case"eth_requestAccounts":return[await r.getAddress(e?.mode??"STANDARD",e?.tag??"MAIN")];case"eth_chainId":return"0x"+t.toString(16);case"eth_sendTransaction":{let u=(a??[])[0]??{};if(!u.chainId&&!t)throw new S("eth_sendTransaction: chainId is required");let l=u.chainId?parseInt(u.chainId,16):t;return(await r.sendTransaction({to:u.to,value:u.value!==void 0?BigInt(u.value):void 0,data:u.data??"0x",chainId:l,gasLimit:u.gas!==void 0?BigInt(u.gas):void 0,maxFeePerGas:u.maxFeePerGas!==void 0?BigInt(u.maxFeePerGas):void 0,maxPriorityFeePerGas:u.maxPriorityFeePerGas!==void 0?BigInt(u.maxPriorityFeePerGas):void 0,nonce:u.nonce!==void 0?parseInt(u.nonce,16):void 0},{mode:e?.mode,tag:e?.tag,rpcUrl:e?.rpcUrl})).hash}case"personal_sign":{let[u]=a??[],l=wc(u)?bc(u):u;return(await r.signMessage(l,{mode:e?.mode,tag:e?.tag,signingMethod:"EIP191"})).signature}case"eth_sign":{let[,u]=a??[],l=wc(u)?bc(u):u;return(await r.signMessage(l,{mode:e?.mode,tag:e?.tag,signingMethod:"EIP191"})).signature}case"eth_signTypedData_v4":{let[,u]=a??[],l=typeof u=="string"?JSON.parse(u):u,{domain:h,types:g,message:d,primaryType:f}=l,y={...g};return delete y.EIP712Domain,(await r.signMessage(JSON.stringify(d),{mode:e?.mode,tag:e?.tag,signingMethod:"EIP712",eip712Domain:h,eip712Types:y,eip712PrimaryType:f})).signature}case"wallet_switchEthereumChain":{let u=parseInt((a??[])[0]?.chainId??"0x1",16);return t=u,i("chainChanged","0x"+u.toString(16)),null}default:throw new S(`w3pk EIP-1193: unsupported method "${c}"`)}},on(c,a){s[c]||(s[c]=[]),s[c].push(a)},removeListener(c,a){s[c]&&(s[c]=s[c].filter(u=>u!==a))}}}async requestExternalWalletDelegation(e){if(!this.currentUser)throw new S("Must be authenticated to get w3pk delegation address. Call login() or register() first.");let{requestExternalWalletAuthorization:t,getDefaultProvider:r}=await Promise.resolve().then(()=>(Ts(),ea)),s=e?.provider||r();if(!s)throw new S("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(...r)=>(await this.loadZKModule())[t](...r)})}async getBackupStatus(){if(!this.currentUser)throw new S("Must be authenticated to check backup status");let{BackupManager:e}=await Promise.resolve().then(()=>(tt(),et));return new e().getBackupStatus(this.currentUser.ethereumAddress)}async createBackupFile(e="password",t){if(!this.currentUser)throw new S("Must be authenticated to create backup");let r=await this.getMnemonicFromSession(!0),{BackupFileManager:s}=await Promise.resolve().then(()=>(le(),ge)),{BackupStorage:i}=await Promise.resolve().then(()=>(fn(),na)),o=new s,c=new i,a,u;if(e==="password"){if(!t)throw new S("Password required for password-based backup");u=(await o.createPasswordBackup(r,this.currentUser.ethereumAddress,t)).backupFile,a=o.createDownloadableBackup(u)}else if(e==="passkey"){let l=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!l)throw new S("No wallet data found");let g=await new F().getCredentialById(l.credentialId);if(!g)throw new S("Credential not found");u=(await o.createPasskeyBackup(r,this.currentUser.ethereumAddress,g.id,g.publicKey)).backupFile,a=o.createDownloadableBackup(u)}else if(e==="hybrid"){if(!t)throw new S("Password required for hybrid backup");let l=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!l)throw new S("No wallet data found");let g=await new F().getCredentialById(l.credentialId);if(!g)throw new S("Credential not found");u=(await o.createHybridBackup(r,this.currentUser.ethereumAddress,t,g.id,g.publicKey)).backupFile,a=o.createDownloadableBackup(u)}else throw new S(`Unknown encryption type: ${e}`);return await c.storeBackupMetadata({id:crypto.randomUUID(),ethereumAddress:this.currentUser.ethereumAddress,method:"file",createdAt:new Date().toISOString(),addressChecksum:u.addressChecksum}),a}async setupSocialRecovery(e,t,r){if(!this.currentUser)throw new S("Must be authenticated to set up social recovery");let s=await this.getMnemonicFromSession(!0),{BackupFileManager:i}=await Promise.resolve().then(()=>(le(),ge)),o=new i,c;if(r)c=(await o.createPasswordBackup(s,this.currentUser.ethereumAddress,r)).backupFile;else{let h=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!h)throw new S("No wallet data found");let d=await new F().getCredentialById(h.credentialId);if(!d)throw new S("Credential not found");c=(await o.createPasskeyBackup(s,this.currentUser.ethereumAddress,d.id,d.publicKey)).backupFile}let{SocialRecovery:a}=await Promise.resolve().then(()=>(Un(),Nn));return{guardianShares:(await new a().splitAmongGuardians(c,e,t)).guardianShares,setupComplete:!0}}async generateGuardianInvite(e,t){let{SocialRecovery:r}=await Promise.resolve().then(()=>(Un(),Nn)),s=new r,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:r}=await Promise.resolve().then(()=>(Un(),Nn)),{BackupFileManager:s}=await Promise.resolve().then(()=>(le(),ge)),{BackupManager:i}=await Promise.resolve().then(()=>(tt(),et)),o=new r,c=new s,a=new i,u=e.map(g=>typeof g=="string"?o.parseGuardianShare(g):g),l=await o.recoverFromShares(u),h;if(l.encryptionMethod==="password"){if(!t)throw new S("Password required to decrypt password-protected backup");h=await c.restoreWithPassword(l,t)}else throw new S("Passkey-encrypted backups not supported for guardian recovery. Use password-protected backups.");return a.markBackupVerified(h.ethereumAddress),h}async restoreFromBackupFile(e,t){let{BackupFileManager:r}=await Promise.resolve().then(()=>(le(),ge)),{BackupManager:s}=await Promise.resolve().then(()=>(tt(),et)),i=new r,o=new s,c=await i.parseBackupFile(e),a,u;if(c.encryptionMethod==="password"){if(!t)throw new S("Password required to restore password-encrypted backup");let l=await i.restoreWithPassword(c,t);a=l.mnemonic,u=l.ethereumAddress}else if(c.encryptionMethod==="passkey"){if(!this.currentUser)throw new S("Must be logged in with passkey to restore passkey-encrypted backup. Call login() first.");let g=(await new F().getAllCredentials()).find(f=>f.ethereumAddress.toLowerCase()===this.currentUser.ethereumAddress.toLowerCase());if(!g)throw new S("Credential not found for current user");let d=await i.restoreWithExistingPasskey(c,g.id,g.publicKey);a=d.mnemonic,u=d.ethereumAddress}else if(c.encryptionMethod==="hybrid"){if(!t)throw new S("Password required to restore hybrid backup");if(!this.currentUser)throw new S("Must be logged in with passkey to restore hybrid backup. Call login() first.");let g=(await new F().getAllCredentials()).find(f=>f.ethereumAddress.toLowerCase()===this.currentUser.ethereumAddress.toLowerCase());if(!g)throw new S("Credential not found for current user");let d=await i.restoreWithHybrid(c,t,g.id,g.publicKey);a=d.mnemonic,u=d.ethereumAddress}else throw new S(`Unknown encryption method: ${c.encryptionMethod}`);if(o.markBackupVerified(u),this.currentWallet={address:u,mnemonic:a},this.currentUser){let l=new F,g=(await l.getAllCredentials()).find(d=>d.ethereumAddress.toLowerCase()===this.currentUser.ethereumAddress.toLowerCase());if(g){let d=this.currentUser.ethereumAddress;d.toLowerCase()!==u.toLowerCase()&&await this.walletStorage.delete(d),await l.updateCredentialAddress(g.id,u);let f=await(await Promise.resolve().then(()=>(q(),Re))).deriveEncryptionKeyFromWebAuthn(g.id,g.publicKey),y=await(await Promise.resolve().then(()=>(q(),Re))).encryptData(a,f);await this.walletStorage.store({ethereumAddress:u,encryptedMnemonic:y,credentialId:g.id,createdAt:new Date().toISOString()}),this.currentUser={...this.currentUser,ethereumAddress:u},await this.sessionManager.startSession(a,g.id,u,g.publicKey,"STANDARD"),this.config.onAuthStateChanged?.(!0,this.currentUser)}}return{mnemonic:a,ethereumAddress:u}}async syncWalletWithPasskey(e,t){let{BackupFileManager:r}=await Promise.resolve().then(()=>(le(),ge)),{BackupManager:s}=await Promise.resolve().then(()=>(tt(),et)),{promptPasskeySelection:i}=await Promise.resolve().then(()=>(ui(),lc)),o=new r,c=new s,a=await i(),u=await o.parseBackupFile(e),l,h;if(u.encryptionMethod==="password"){if(!t)throw new S("Password required to restore password-encrypted backup");let f=await o.restoreWithPassword(u,t);l=f.mnemonic,h=f.ethereumAddress}else if(u.encryptionMethod==="passkey"){if(!a.publicKey)throw new S("Passkey public key not found. The passkey may not be registered on this device yet.");let f=await o.restoreWithExistingPasskey(u,a.credentialId,a.publicKey);l=f.mnemonic,h=f.ethereumAddress}else if(u.encryptionMethod==="hybrid"){if(!t)throw new S("Password required to restore hybrid backup");if(!a.publicKey)throw new S("Passkey public key not found. The passkey may not be registered on this device yet.");let f=await o.restoreWithHybrid(u,t,a.credentialId,a.publicKey);l=f.mnemonic,h=f.ethereumAddress}else throw new S(`Unknown encryption method: ${u.encryptionMethod}`);c.markBackupVerified(h);let d=await new F().getCredentialById(a.credentialId);if(d){let{deriveEncryptionKeyFromWebAuthn:f,encryptData:y}=await Promise.resolve().then(()=>(q(),Re)),k=await f(d.id,d.publicKey),m=await y(l,k);await this.walletStorage.store({ethereumAddress:h,encryptedMnemonic:m,credentialId:d.id,createdAt:new Date().toISOString()}),this.currentUser={username:d.username,ethereumAddress:h,credentialId:d.id},await this.sessionManager.startSession(l,d.id,h,d.publicKey,"STANDARD"),this.config.onAuthStateChanged?.(!0,this.currentUser)}return{mnemonic:l,ethereumAddress:h}}async registerWithBackupFile(e,t,r){let{BackupFileManager:s}=await Promise.resolve().then(()=>(le(),ge)),{BackupManager:i}=await Promise.resolve().then(()=>(tt(),et)),o=new s,c=new i,a=await o.parseBackupFile(e);if(a.encryptionMethod!=="password")throw new S("Can only register with password-encrypted backups. Use restoreFromBackupFile() for passkey-encrypted backups.");let{mnemonic:u,ethereumAddress:l}=await o.restoreWithPassword(a,t),{Wallet:h}=await import("ethers");if(h.fromPhrase(u).address.toLowerCase()!==l.toLowerCase())throw new S("Backup verification failed: address mismatch");return c.markBackupVerified(l),this.currentWallet={address:l,mnemonic:u},this.register({username:r})}async getSyncStatus(){let{DeviceSyncManager:e}=await Promise.resolve().then(()=>(xr(),Ln));return new e().getSyncInfo()}async exportForSync(){if(!this.currentUser)throw new S("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 S("No wallet data found");let s=await new F().getCredentialById(t.credentialId);if(!s)throw new S("Credential not found");let{DeviceSyncManager:i}=await Promise.resolve().then(()=>(xr(),Ln)),o=new i,{backupFile:c,blob:a}=await o.exportForSync(e,this.currentUser.ethereumAddress,s.id,s.publicKey),u=`w3pk-sync-${this.currentUser.ethereumAddress.substring(0,8)}.json`,l;try{l=await o.generateSyncQR(c)}catch(h){console.warn("QR code generation failed:",h)}return{blob:a,filename:u,qrCode:l}}async importFromSync(e){if(!this.currentUser)throw new S("Must be logged in to import from sync. Call login() first.");let{DeviceSyncManager:t}=await Promise.resolve().then(()=>(xr(),Ln)),{BackupFileManager:r}=await Promise.resolve().then(()=>(le(),ge)),{BackupManager:s}=await Promise.resolve().then(()=>(tt(),et)),i=new r,o=new t,c=new s,a=await i.parseBackupFile(e),u=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!u)throw new S("No wallet data found for current user");let h=await new F().getCredentialById(u.credentialId);if(!h)throw new S("Credential not found");let{mnemonic:g,ethereumAddress:d}=await o.importFromSync(a,h.id,h.publicKey);c.markBackupVerified(d);let f=await(await Promise.resolve().then(()=>(q(),Re))).deriveEncryptionKeyFromWebAuthn(h.id,h.publicKey),y=await(await Promise.resolve().then(()=>(q(),Re))).encryptData(g,f);return await this.walletStorage.store({ethereumAddress:d,encryptedMnemonic:y,credentialId:h.id,createdAt:new Date().toISOString()}),{ethereumAddress:d,success:!0}}async detectSyncCapabilities(){let{PlatformDetector:e}=await Promise.resolve().then(()=>(gc(),pc));return new e().detectSyncCapabilities()}async simulateRecoveryScenario(e){if(!this.currentUser)throw new S("Must be authenticated to run recovery simulation");let t=await this.getBackupStatus(),{RecoverySimulator:r}=await Promise.resolve().then(()=>(vr(),Wn));return new r().simulateScenario(e,t)}async runRecoveryTest(){if(!this.currentUser)throw new S("Must be authenticated to run recovery test");let e=await this.getBackupStatus(),{RecoverySimulator:t}=await Promise.resolve().then(()=>(vr(),Wn));return new t().runInteractiveTest(e)}async getEducation(e){let{getExplainer:t}=await Promise.resolve().then(()=>(vr(),Wn)),r=t(e);if(!r)throw new S(`Unknown education topic: ${e}`);return r}hasActiveSession(){return this.sessionManager.isActive()}getSessionRemainingTime(){return this.sessionManager.getRemainingTime()}extendSession(){try{this.sessionManager.extendSession()}catch(e){throw new S("Cannot extend session",e)}}async clearSession(){await this.sessionManager.clearSession()}setSessionDuration(e){this.sessionManager.setSessionDuration(e)}};Y();ui();gt();vr();async function Rg(n,e="build"){let{importer:t}=await Promise.resolve().then(()=>(Wu(),zu)),{MemoryBlockstore:r}=await Promise.resolve().then(()=>(fd(),hd)),s=new r,o=t(async function*(){yield{path:e,content:n}}(),s,{cidVersion:1,rawLeaves:!0,wrapWithDirectory:!1});for await(let c of o)return c.cid.toString();throw new Error("Failed to generate CID")}async function Tg(n){let e=["index.js","index.mjs","index.d.ts"],t=[],r=0;for(let o of e){let c=`${n}/${o}`,a=await fetch(c);if(!a.ok)throw new Error(`Failed to fetch ${o}: ${a.statusText}`);let u=await a.arrayBuffer(),l=new Uint8Array(u);t.push(l),r+=l.length}let s=new Uint8Array(r),i=0;for(let o of t)s.set(o,i),i+=o.length;return s}async function To(n){let e=await Tg(n);return Rg(e)}function Fo(){try{return pd().version}catch{throw new Error("Failed to read package version")}}async function Mo(){let n=Fo();return To(`https://unpkg.com/w3pk@${n}/dist`)}async function gd(n){return await Mo()===n}xe();Ms();pt();function md(n=11){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=new Uint8Array(n);return crypto.getRandomValues(t),Array.from(t).map(r=>e[r%e.length]).join("")}function yd(n){if(!n.domain||!n.address||!n.uri||!n.version||n.chainId===void 0||!n.nonce||!n.issuedAt)throw new Error("Missing required SIWE message fields");if(n.version!=="1")throw new Error('SIWE version must be "1"');if(n.nonce.length<8||!/^[a-zA-Z0-9]+$/.test(n.nonce))throw new Error("Nonce must be at least 8 alphanumeric characters");if(n.statement&&n.statement.includes(`
960
+ ${e}[Error list was empty]`,t.trim()}return Ju(n,e)}function Sg(n){let e=()=>{};return e.enabled=!1,e.color="",e.diff=0,e.log=()=>{},e.namespace=n,e.destroy=()=>!0,e.extend=()=>e,e}function Ro(n,e){let t=Sg(`${n}:trace`);return X.enabled(`${n}:trace`)&&X.names.map(r=>r.toString()).find(r=>r.includes(":trace"))!=null&&(t=X(`${n}:trace`,e)),Object.assign(X(n,e),{error:X(`${n}:error`,e),trace:t,newScope:r=>Ro(`${n}:${r}`,e)})}function Qu(n){if(n!=null&&(n=n.trim(),n.length!==0))return n}var Zu=w(()=>{"use strict";Cr();Vn();Zi();ju();X.formatters.b=n=>n==null?"undefined":de.baseEncode(n);X.formatters.t=n=>n==null?"undefined":J.baseEncode(n);X.formatters.m=n=>n==null?"undefined":Qi.baseEncode(n);X.formatters.p=n=>n==null?"undefined":n.toString();X.formatters.c=n=>n==null?"undefined":n.toString();X.formatters.k=n=>n==null?"undefined":n.toString();X.formatters.a=n=>n==null?"undefined":n.toString();X.formatters.e=n=>n==null?"undefined":Xu(n)});function xg(n){let[e,t]=n[Symbol.asyncIterator]!=null?[n[Symbol.asyncIterator](),Symbol.asyncIterator]:[n[Symbol.iterator](),Symbol.iterator],r=[];return{peek:()=>e.next(),push:s=>{r.push(s)},next:()=>r.length>0?{done:!1,value:r.shift()}:e.next(),[t](){return this}}}var ed,td=w(()=>{"use strict";ed=xg});function vg(n){return n[Symbol.asyncIterator]!=null}function Ag(n,e){let t=0;if(vg(n))return(async function*(){for await(let a of n)await e(a,t++)&&(yield a)})();let r=ed(n),{value:s,done:i}=r.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 a of r)await e(a,t++)&&(yield a)})();let c=e;return(function*(){o===!0&&(yield s);for(let a of r)c(a,t++)&&(yield a)})()}var rd,nd=w(()=>{"use strict";td();rd=Ag});function Xt(){let n={};return n.promise=new Promise((e,t)=>{n.resolve=e,n.reject=t}),n}var sd=w(()=>{"use strict"});async function id(n,e,t){if(e==null)return n;if(e.aborted)return n.catch(()=>{}),Promise.reject(new gs(t?.errorMessage,t?.errorCode,t?.errorName));let r,s=new gs(t?.errorMessage,t?.errorCode,t?.errorName);try{return await Promise.race([n,new Promise((i,o)=>{r=()=>{o(s)},e.addEventListener("abort",r)})])}finally{r!=null&&e.removeEventListener("abort",r)}}var gs,od=w(()=>{"use strict";gs=class extends Error{constructor(t,r,s){super(t??"The operation was aborted");p(this,"type");p(this,"code");this.type="aborted",this.name=s??"AbortError",this.code=r??"ABORT_ERR"}}});function ad(){return new To}var To,cd=w(()=>{"use strict";sd();od();To=class{constructor(){p(this,"readNext");p(this,"haveNext");p(this,"ended");p(this,"nextResult");p(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 id(this.readNext.promise,t?.signal,t)}}});function kg(n){return n[Symbol.asyncIterator]!=null}async function Eg(n,e,t){try{await Promise.all(n.map(async r=>{for await(let s of r)await e.push(s,{signal:t}),t.throwIfAborted()})),await e.end(void 0,{signal:t})}catch(r){await e.end(r,{signal:t}).catch(()=>{})}}async function*Cg(n){let e=new AbortController,t=ad();Eg(n,t,e.signal).catch(()=>{});try{yield*t}finally{e.abort()}}function*Pg(n){for(let e of n)yield*e}function Ig(...n){let e=[];for(let t of n)kg(t)||e.push(t);return e.length===n.length?Pg(e):Cg(n)}var ld,ud=w(()=>{"use strict";cd();ld=Ig});var Bg,ms,dd=w(()=>{"use strict";Zu();us();nd();ud();Hr();Bg=Ro("blockstore:core:tiered"),ms=class extends Ee{constructor(t){super();p(this,"stores");this.stores=t.slice()}async put(t,r,s){return await Promise.all(this.stores.map(async i=>{await i.put(t,r,s)})),t}async*get(t,r){let s;for(let i of this.stores)try{yield*i.get(t,r);return}catch(o){s=o,Bg.error(o)}throw s??new He}async has(t,r){for(let s of this.stores)if(await s.has(t,r))return!0;return!1}async delete(t,r){await Promise.all(this.stores.map(async s=>{await s.delete(t,r)}))}async*putMany(t,r={}){for await(let s of t)await this.put(s.cid,s.bytes,r),yield s.cid}async*deleteMany(t,r={}){for await(let s of t)await this.delete(s,r),yield s}async*getAll(t){let r=new Set;yield*rd(ld(...this.stores.map(s=>s.getAll(t))),s=>{let i=s.cid.toString();return r.has(i)?!1:(r.add(i),!0)})}}});var hd={};B(hd,{BaseBlockstore:()=>Ee,BlackHoleBlockstore:()=>hs,MemoryBlockstore:()=>ds,TieredBlockstore:()=>ms});var fd=w(()=>{"use strict";Hr();qu();Hu();dd()});var pd=D((zS,Dg)=>{Dg.exports={name:"w3pk",version:"0.9.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/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","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","release:notes":"node scripts/generate-release-notes.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":"^24.9.0","@types/qrcode":"^1.5.5",circomlib:"^2.0.5",tsup:"^8.5.1",tsx:"^4.21.0",typescript:"^5.9.3"},peerDependencies:{ethers:"^6.0.0"},optionalDependencies:{"@ipld/car":"^5.4.2","blockstore-core":"^6.1.1",circomlibjs:"^0.1.7","ipfs-unixfs-importer":"^16.0.1",qrcode:"^1.5.4",snarkjs:"^0.7.5"}}});var Ug={};B(Ug,{ApiError:()=>Vr,AuthenticationError:()=>O,CryptoError:()=>N,DEFAULT_MODE:()=>fe,DEFAULT_TAG:()=>pe,RecoverySimulator:()=>Et,RegistrationError:()=>ft,SocialRecoveryManager:()=>et,StealthAddressModule:()=>wt,StorageError:()=>R,WalletError:()=>S,Web3Passkey:()=>Ct,Web3PasskeyError:()=>$,arrayBufferToBase64Url:()=>Se,assertEthereumAddress:()=>Gr,assertMnemonic:()=>_o,assertUsername:()=>Yr,authenticateWithPasskey:()=>ui,base64ToArrayBuffer:()=>xs,base64UrlDecode:()=>As,base64UrlToArrayBuffer:()=>L,canControlStealthAddress:()=>Vo,checkStealthAddress:()=>sr,clearCache:()=>ea,computeStealthPrivateKey:()=>ir,createSiweMessage:()=>yd,createWalletFromMnemonic:()=>Cs,createWeb3Passkey:()=>xd,default:()=>Ng,deriveAddressFromP256PublicKey:()=>Is,deriveIndexFromOriginModeAndTag:()=>en,deriveStealthKeys:()=>yt,deriveWalletFromMnemonic:()=>rr,detectWalletProvider:()=>hn,encodeEIP7702AuthorizationMessage:()=>ar,extractRS:()=>Ms,generateBIP39Wallet:()=>tr,generateSiweNonce:()=>md,generateStealthAddress:()=>rn,getAllChains:()=>Xo,getAllTopics:()=>fi,getChainById:()=>Zo,getCurrentBuildHash:()=>No,getCurrentOrigin:()=>Me,getDefaultProvider:()=>dn,getEndpoints:()=>an,getExplainer:()=>hi,getOriginSpecificAddress:()=>Fe,getPackageVersion:()=>Mo,getW3pkBuildHash:()=>Fo,hashEIP7702AuthorizationMessage:()=>cr,inspect:()=>Uo,inspectNow:()=>Sd,isStrongPassword:()=>Oo,normalizeOrigin:()=>nr,parseSiweMessage:()=>ys,promptPasskeySelection:()=>li,requestExternalWalletAuthorization:()=>un,safeAtob:()=>Ve,safeBtoa:()=>vs,searchExplainers:()=>pi,supportsEIP7702Authorization:()=>fn,validateEthereumAddress:()=>ws,validateMnemonic:()=>Ss,validateSiweMessage:()=>wd,validateUsername:()=>bs,verifyBuildHash:()=>gd,verifyEIP7702Authorization:()=>cn,verifySiweSignature:()=>bd});module.exports=Bd(Ug);Y();function ws(n){return/^0x[a-fA-F0-9]{40}$/.test(n)}function bs(n){return n.length<3||n.length>50?!1:/^[a-zA-Z0-9]([a-zA-Z0-9_-]*[a-zA-Z0-9])?$/.test(n)}function Ss(n){let e=n.trim().split(/\s+/);return e.length===12||e.length===24}function Gr(n){if(!ws(n))throw new Error("Invalid Ethereum address format")}function Yr(n){if(!bs(n))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 _o(n){if(!Ss(n))throw new Error("Invalid mnemonic: must be 12 or 24 words")}function Oo(n){if(n.length<12)return!1;let e=/[A-Z]/.test(n),t=/[a-z]/.test(n),r=/[0-9]/.test(n),s=/[!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(n);return!(!e||!t||!r||!s||["password","12345678","qwerty","abc123","password123","admin","letmein"].some(o=>n.toLowerCase().includes(o)))}Te();xe();q();async function Rd(n){try{let e=new Uint8Array(n),t=Td(e);if(t===-1)return null;let r=e.slice(t);if(!((r[32]&64)!==0))return null;let o=37;o+=16;let c=r[o]<<8|r[o+1];o+=2,o+=c;let a=r.slice(o),u=await Fd(a);return Se(u)}catch(e){return console.error("Failed to extract public key:",e),null}}function Td(n){let e=new Uint8Array([104,97,117,116,104,68,97,116,97]);for(let t=0;t<n.length-e.length;t++){let r=!0;for(let s=0;s<e.length;s++)if(n[t+s]!==e[s]){r=!1;break}if(r){let s=n[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 Fd(n){let e=zo(n,-2),t=zo(n,-3);if(!e||!t)throw new Error("Failed to extract EC coordinates from COSE key");let r=new Uint8Array(65);r[0]=4,r.set(e,1),r.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+r.length);return i.set(s,0),i.set(r,s.length),i.buffer}function zo(n,e){let t=e<0?32+(-1-e):e;for(let r=0;r<n.length-33;r++)if(n[r]===t&&(n[r+1]===88&&n[r+2]===32||n[r+1]===88&&n[r+2]===32))return n.slice(r+3,r+35);return null}async function Wo(n){try{let{username:e,ethereumAddress:t}=n;Yr(e),Gr(t);let r=new F;if(await r.userExists(e))throw new Error("Username already registered");let s=De(),o=new TextEncoder().encode(e),c=Se(o),a=L(s),u=L(c),l={challenge:a,rp:{name:"w3pk",id:window.location.hostname},user:{id:u,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"},h=await navigator.credentials.create({publicKey:l});if(!h)throw new Error("Failed to create credential");let g=await Rd(h.response.attestationObject);if(!g)throw new Error("Public key not returned from authenticator");return await r.saveCredential({id:h.id,publicKey:g,username:e,ethereumAddress:t,createdAt:new Date().toISOString(),lastUsed:new Date().toISOString(),signCount:0}),{signature:h.response.attestationObject}}catch(e){throw new ft(e instanceof Error?e.message:"Registration failed",e)}}Y();Te();xe();q();async function Xr(){try{let n=new F,e=De(),t=[];try{let a=await n.getAllCredentials();a.length>0&&(t=a.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};t.length>0&&(s.allowCredentials=t.map(a=>({id:L(a.id),type:a.type,transports:a.transports})));let i;try{let a=await navigator.credentials.get({publicKey:s});if(!a)throw new Error("Authentication failed - no credential returned");i=a}catch(a){throw a?.name==="NotAllowedError"||a?.message?.toLowerCase().includes("no credentials available")||a?.message?.toLowerCase().includes("no access key")?(await n.getAllCredentials()).length>0?new O("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 O("No passkey found. Please register first or restore from a backup."):a}let o=await n.getCredentialById(i.id);if(!o)throw new O("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 Md(i,o,n))throw new Error("Signature verification failed");return{verified:!0,user:{username:o.username,ethereumAddress:o.ethereumAddress,credentialId:o.id},signature:i.response.signature}}catch(n){throw new O(n instanceof Error?n.message:"Authentication failed",n)}}async function Md(n,e,t){try{let r=n.response.authenticatorData,s=new DataView(r),o=new Uint8Array(r).slice(0,32),c=window.location.hostname,a=new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(c)));if(!Nd(o,a))return console.error("RP ID hash mismatch - possible phishing attack"),!1;let u=s.getUint32(33,!1);if(u>0||e.signCount&&e.signCount>0){let b=e.signCount||0;if(u<=b)return console.error(`Authenticator cloning detected! Counter did not increase: stored=${b}, received=${u}`),!1}let l=L(e.publicKey),h=await crypto.subtle.importKey("spki",l,{name:"ECDSA",namedCurve:"P-256"},!1,["verify"]),g=n.response.clientDataJSON,d=await crypto.subtle.digest("SHA-256",g),f=new Uint8Array(r.byteLength+d.byteLength);f.set(new Uint8Array(r),0),f.set(new Uint8Array(d),r.byteLength);let y=n.response.signature,k=Ud(new Uint8Array(y));return await crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},h,k,f)?(await t.updateSignatureCounter(e.id,u),!0):!1}catch(r){return console.error("Signature verification error:",r),!1}}function Nd(n,e){if(n.length!==e.length)return!1;for(let t=0;t<n.length;t++)if(n[t]!==e[t])return!1;return!0}function Ud(n){let e=2;e++;let t=n[e++];t>32&&(e++,t--);let r=n.slice(e,e+t);e+=t,e++;let s=n[e++];s>32&&(e++,s--);let i=n.slice(e,e+s),o=new Uint8Array(64);return o.set(r,32-r.length),o.set(i,64-i.length),o.buffer}Y();var Ld="Web3PasskeyWallet",_d=1,ve="wallets",Zr=class{constructor(){this.db=null}async init(){return new Promise((e,t)=>{let r=indexedDB.open(Ld,_d);r.onerror=()=>t(new R("Failed to open database",r.error)),r.onsuccess=()=>{this.db=r.result,e()},r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(ve)||s.createObjectStore(ve,{keyPath:"ethereumAddress"})}})}async store(e){return this.db||await this.init(),new Promise((t,r)=>{let o=this.db.transaction([ve],"readwrite").objectStore(ve).put(e);o.onerror=()=>r(new R("Failed to store wallet data",o.error)),o.onsuccess=()=>t()})}async retrieve(e){return this.db||await this.init(),new Promise((t,r)=>{let o=this.db.transaction([ve],"readonly").objectStore(ve).get(e);o.onerror=()=>r(new R("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,r)=>{let o=this.db.transaction([ve],"readwrite").objectStore(ve).delete(e);o.onerror=()=>r(new R("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([ve],"readwrite").objectStore(ve).clear();i.onerror=()=>t(new R("Failed to clear wallet data",i.error)),i.onsuccess=()=>e()})}};gt();mt();q();Y();var H=require("ethers");Y();function yt(n){try{let e=H.ethers.HDNodeWallet.fromPhrase(n,void 0,"m/44'/60'/1'/0/0"),t=H.ethers.HDNodeWallet.fromPhrase(n,void 0,"m/44'/60'/1'/0/1"),r=t.signingKey.compressedPublicKey,s=e.signingKey.compressedPublicKey;return{stealthMetaAddress:r+s.slice(2),spendingPubKey:r,viewingPubKey:s,viewingKey:e.privateKey,spendingKey:t.privateKey}}catch(e){throw new N("Failed to derive stealth keys",e)}}function rn(n){try{let e="0x"+n.slice(2,68),t="0x"+n.slice(68),r=H.ethers.Wallet.createRandom(),s=r.signingKey.compressedPublicKey,i=Bs(r.privateKey,t),o=H.ethers.keccak256(i),c="0x"+o.slice(2,4),a=Yo(e,Go(o));return{stealthAddress:jo(a),ephemeralPubKey:s,viewTag:c}}catch(e){throw new N("Failed to generate stealth address",e)}}function sr(n,e,t,r,s){try{let i=Bs(n,t),o=H.ethers.keccak256(i);if(s&&("0x"+o.slice(2,4)).toLowerCase()!==s.toLowerCase())return{isForUser:!1};let c=Yo(e,Go(o)),a=jo(c);return a.toLowerCase()!==r.toLowerCase()?{isForUser:!1}:{isForUser:!0,stealthAddress:a}}catch{return{isForUser:!1}}}function ir(n,e,t){try{let r=Bs(n,t),s=H.ethers.keccak256(r);return Kd(e,s)}catch(r){throw new N("Failed to compute stealth private key",r)}}function Vo(n,e,t,r,s,i){try{if(!sr(n,t,r,s,i).isForUser)return!1;let c=ir(n,e,r);return new H.ethers.Wallet(c).address.toLowerCase()===s.toLowerCase()}catch{return!1}}function Bs(n,e){try{return new H.ethers.Wallet(n).signingKey.computeSharedSecret(e)}catch(t){throw new N("Failed to compute shared secret",t)}}function Go(n){try{return new H.ethers.Wallet(n).signingKey.compressedPublicKey}catch(e){throw new N("Failed to multiply generator by scalar",e)}}function Yo(n,e){try{let t=H.ethers.SigningKey.computePublicKey(n,!1),r=H.ethers.SigningKey.computePublicKey(e,!1),s=BigInt("0x"+t.slice(4,68)),i=BigInt("0x"+t.slice(68)),o=BigInt("0x"+r.slice(4,68)),c=BigInt("0x"+r.slice(68)),a=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F");if(s===o&&i===c){let f=3n*s*s%a,y=2n*i%a,k=f*Ho(y,a)%a,m=(k*k-2n*s)%a,b=(k*(s-m)-i)%a;return qo((m+a)%a,(b+a)%a)}let u=((c-i)%a+a)%a,l=((o-s)%a+a)%a,h=u*Ho(l,a)%a,g=(h*h-s-o)%a,d=(h*(s-g)-i)%a;return qo((g+a)%a,(d+a)%a)}catch(t){throw new N("Failed to add public keys",t)}}function Kd(n,e){try{let t=BigInt("0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141"),r=BigInt(n),s=BigInt(e);return"0x"+((r+s)%t).toString(16).padStart(64,"0")}catch(t){throw new N("Failed to add private keys",t)}}function qo(n,e){return"0x"+(e%2n===0n?"02":"03")+n.toString(16).padStart(64,"0")}function Ho(n,e){n=(n%e+e)%e;let[t,r]=[n,e],[s,i]=[1n,0n];for(;r!==0n;){let o=t/r;[t,r]=[r,t-o*r],[s,i]=[i,s-o*i]}return(s%e+e)%e}function jo(n){try{let e=H.ethers.SigningKey.computePublicKey(n,!1),t=H.ethers.keccak256("0x"+e.slice(4));return H.ethers.getAddress("0x"+t.slice(-40))}catch(e){throw new N("Failed to derive address from public key",e)}}var wt=class{constructor(e,t){this.getMnemonic=t}async generateStealthAddress(e){try{let t=await this.getMnemonic(e?.requireAuth),r=yt(t),s=rn(r.stealthMetaAddress);return{stealthAddress:s.stealthAddress,ephemeralPublicKey:s.ephemeralPubKey,viewTag:s.viewTag}}catch(t){throw new $("Failed to generate stealth address","STEALTH_GENERATION_ERROR",t)}}async parseAnnouncement(e,t){try{let r=await this.getMnemonic(t?.requireAuth),s=yt(r),i=sr(s.viewingKey,s.spendingPubKey,e.ephemeralPublicKey,e.stealthAddress,e.viewTag);if(!i.isForUser)return{isForUser:!1};let o=ir(s.viewingKey,s.spendingKey,e.ephemeralPublicKey);return{isForUser:!0,stealthAddress:i.stealthAddress,stealthPrivateKey:o}}catch(r){throw new $("Failed to parse announcement","ANNOUNCEMENT_PARSE_ERROR",r)}}async scanAnnouncements(e,t){let r=[];for(let s of e){let i=await this.parseAnnouncement(s,t);i.isForUser&&r.push(i)}return r}async getKeys(e){try{let t=await this.getMnemonic(e?.requireAuth);return yt(t)}catch(t){throw new $("Failed to get stealth keys","STEALTH_KEYS_ERROR",t)}}async getStealthMetaAddress(e){try{return(await this.getKeys(e)).stealthMetaAddress}catch(t){throw new $("Failed to get stealth meta-address","STEALTH_META_ADDRESS_ERROR",t)}}get isAvailable(){return!0}};Y();q();var zd="Web3PasskeyPersistentSessions",Wd=2,ae="sessions",nn=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 r=indexedDB.open(zd,Wd);r.onupgradeneeded=s=>{let i=s.target.result;i.objectStoreNames.contains(ae)||i.createObjectStore(ae,{keyPath:"ethereumAddress"}).createIndex("expiresAt","expiresAt",{unique:!1})},r.onsuccess=()=>{this.db=r.result,this.initPromise=null,e()},r.onerror=()=>{this.initPromise=null,t(new R("Failed to open persistent session database",r.error))}}),this.initPromise)}async store(e){if(e.securityMode==="STRICT")throw new R("Cannot persist STRICT mode sessions");return this.db||await this.init(),new Promise((t,r)=>{let o=this.db.transaction([ae],"readwrite").objectStore(ae).put(e);o.onerror=()=>r(new R("Failed to store persistent session",o.error)),o.onsuccess=()=>t()})}async retrieve(e){return this.db||await this.init(),new Promise((t,r)=>{let o=this.db.transaction([ae],"readonly").objectStore(ae).get(e);o.onerror=()=>r(new R("Failed to retrieve persistent session",o.error)),o.onsuccess=()=>{let c=o.result||null;if(c&&Date.now()>c.expiresAt){this.delete(e).catch(console.error),t(null);return}t(c)}})}async delete(e){return this.db||await this.init(),new Promise((t,r)=>{let o=this.db.transaction([ae],"readwrite").objectStore(ae).delete(e);o.onerror=()=>r(new R("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([ae],"readwrite").objectStore(ae).clear();i.onerror=()=>t(new R("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([ae],"readwrite").objectStore(ae).index("expiresAt"),o=Date.now(),c=IDBKeyRange.upperBound(o),a=i.openCursor(c);a.onsuccess=u=>{let l=u.target.result;l?(l.delete(),l.continue()):e()},a.onerror=()=>t(new R("Failed to cleanup expired sessions",a.error))})}};async function Jo(n,e,t){try{let r=await j(e,t);return await ie(n,r)}catch(r){throw new N("Failed to encrypt mnemonic for persistence",r)}}async function Ds(n,e,t){try{let r=await j(e,t);return await oe(n,r)}catch(r){throw new N("Failed to decrypt mnemonic from persistence",r)}}var sn=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 nn}async startSession(e,t,r,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"&&r&&s)try{let c=await Jo(e,t,s),a=Date.now()+this.persistentConfig.duration*60*60*1e3;await this.persistentStorage.store({encryptedMnemonic:c,expiresAt:a,credentialId:t,ethereumAddress:r,securityMode:i||"STANDARD",createdAt:Date.now()})}catch(c){console.warn("[w3pk] Failed to persist session:",c)}}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,r){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 Ds(s.encryptedMnemonic,t,r),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(()=>(Te(),Qr)),r=await new e().getAllCredentials();if(r.length===0)return null;for(let s of r){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 Ds(i.encryptedMnemonic,s.id,s.publicKey),c=new Date(Date.now()+this.sessionDuration).toISOString();return this.session={mnemonic:o,expiresAt:c,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}};Te();var on={debug:!1,sessionDuration:1,persistentSession:{enabled:!1,duration:168,requireReauth:!0},onError:n=>{on.debug&&console.error("[w3pk]",n)}};Y();var Qo="https://chainid.network/chains.json";var or=null,$d=[/\$\{[\w_]+\}/i,/\{[\w_]+\}/i,/<[\w_]+>/i,/YOUR[-_]?API[-_]?KEY/i,/INSERT[-_]?API[-_]?KEY/i,/API[-_]?KEY[-_]?HERE/i];function qd(n){return $d.some(e=>e.test(n))}async function Hd(n=Qo){let e=await fetch(n);if(!e.ok)throw new Error(`Failed to fetch chains data: ${e.status} ${e.statusText}`);return await e.json()}async function Rs(n){let e=n?.chainsJsonUrl??Qo,t=n?.cacheDuration??36e5,r=Date.now();if(or&&r-or.timestamp<t)return or.data;let s=await Hd(e);return or={data:s,timestamp:r},s}async function an(n,e){let r=(await Rs(e)).find(s=>s.chainId===n);return r?r.rpc.filter(s=>!qd(s)&&!s.startsWith("wss://")&&!s.startsWith("ws://")):[]}async function Xo(n){return Rs(n)}async function Zo(n,e){return(await Rs(e)).find(r=>r.chainId===n)}function ea(){or=null}Fs();ln();var Vd=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 Gd(n,e=1e4){try{let t=new AbortController,r=setTimeout(()=>t.abort(),e),s=await fetch(n,{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(r),!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(a=>o.includes(a))}return i.result!==void 0}catch{return!1}}async function ra(n,e,t){if(Vd.has(n))return!0;let r=t?.maxEndpoints||3,s=t?.timeout||1e4;try{let i=await e(n);if(i.length===0)return!1;let o=i.slice(0,r);for(let c of o)if(await Gd(c,s))return!0;return!1}catch{return!1}}function wc(n){return typeof n=="string"&&/^0x[0-9a-fA-F]*$/.test(n)}function bc(n){let e=n.startsWith("0x")?n.slice(2):n,t=new Uint8Array(e.match(/.{1,2}/g).map(r=>parseInt(r,16)));return new TextDecoder().decode(t)}var Ct=class{constructor(e={}){this.currentUser=null;this.currentWallet=null;this.config={...on,...e},this.walletStorage=new Zr;let t={...on.persistentSession,...e.persistentSession};this.sessionManager=new sn(e.sessionDuration||1,t),e.stealthAddresses!==void 0&&(this.stealth=new wt(e.stealthAddresses,r=>this.getMnemonicFromSession(r)))}async loadZKModule(){if(this.zkModule)return this.zkModule;try{let e=new Function("path","return import(path)"),{ZKProofModule:t}=await e("w3pk/zk"),r=this.config.zkProofs||{};return this.zkModule=new t(r),this.zkModule}catch{throw new Error("ZK module not available. Install dependencies: npm install snarkjs circomlibjs")}}async getMnemonicFromSession(e=!1,t="STANDARD"){let r=t;if(!e){let h=this.sessionManager.getMnemonic();if(h)return h}if(!this.currentUser)throw new S("Must be authenticated. Call login() first.");let s=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!s)throw new S("No wallet found. Generate a wallet first.");if(!(await Xr()).user)throw new S("Authentication failed");let a=(await new F().getCredentialById(s.credentialId))?.publicKey,u=await j(s.credentialId,a),l=await oe(s.encryptedMnemonic,u);return await this.sessionManager.startSession(l,s.credentialId,this.currentUser.ethereumAddress,a,r),l}async register(e){try{this.currentWallet?.address||await this.generateWallet();let t=this.currentWallet.address,r=this.currentWallet.mnemonic;await Wo({username:e.username,ethereumAddress:t});let i=await new F().getCredentialByAddress(t);if(this.currentUser={username:e.username,ethereumAddress:t,credentialId:i?.id||""},!i)throw new S("Credential not found after registration");let o=i.id,c=i.publicKey,a=await j(o,c),u=await ie(r,a);return await this.walletStorage.store({ethereumAddress:this.currentUser.ethereumAddress,encryptedMnemonic:u,credentialId:o,createdAt:new Date().toISOString()}),await this.sessionManager.startSession(r,o,t,c,"STANDARD"),this.currentWallet={address:t,mnemonic:r},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 l=await new F().getCredentialById(e.credentialId);return this.currentUser={username:l?.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 Xr();if(!t.verified||!t.user)throw new O("Login failed");this.currentUser={username:t.user.username,ethereumAddress:t.user.ethereumAddress,credentialId:t.user.credentialId};let r=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!r)return this.config.onAuthStateChanged?.(!0,this.currentUser),this.currentUser;let o=(await new F().getCredentialById(r.credentialId))?.publicKey,c=await this.sessionManager.restoreFromPersistentStorage(this.currentUser.ethereumAddress,r.credentialId,o||""),a;if(c)a=c;else{let u=await j(r.credentialId,o);a=await oe(r.encryptedMnemonic,u),await this.sessionManager.startSession(a,r.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 F().getAllCredentials()).map(r=>({username:r.username,ethereumAddress:r.ethereumAddress,createdAt:r.createdAt,lastUsed:r.lastUsed}))}catch{return[]}}async hasExistingCredential(){return(await this.listExistingCredentials()).length>0}async getExistingCredentialCount(){return(await this.listExistingCredentials()).length}async generateWallet(){try{let e=tr();return this.currentWallet={address:e.address,mnemonic:e.mnemonic},{address:e.address,mnemonic:e.mnemonic}}catch(e){throw this.config.onError?.(e),new S("Failed to generate wallet",e)}}async deriveWallet(e,t,r){try{if(!this.currentUser)throw new S("Must be authenticated to derive wallet");let s=e||fe,i=t||pe,o=r?.origin||Me();if(s==="PRIMARY"){let{CredentialStorage:l}=await Promise.resolve().then(()=>(Te(),Qr)),{deriveAddressFromP256PublicKey:h}=await Promise.resolve().then(()=>(mt(),tn)),d=await new l().getCredentialById(this.currentUser.credentialId);if(!d||!d.publicKey)throw new S("No WebAuthn credential found for PRIMARY mode");return{address:await h(d.publicKey),origin:o,mode:s,tag:i,publicKey:d.publicKey}}let c=s==="STRICT"?!0:r?.requireAuth||!1,a=await this.getMnemonicFromSession(c,s),u=await Fe(a,o,s,i);return{address:u.address,privateKey:u.privateKey,index:u.index,origin:u.origin,mode:u.mode,tag:u.tag}}catch(s){throw this.config.onError?.(s),new S("Failed to derive wallet",s)}}async getAddress(e,t,r){try{if(!this.currentUser)throw new S("Must be authenticated to get address");let s=e||fe,i=t||pe,o=r?.origin||Me();if(s==="PRIMARY"){let{deriveAddressFromP256PublicKey:l}=await Promise.resolve().then(()=>(mt(),tn)),g=await new F().getCredentialById(this.currentUser.credentialId);if(!g||!g.publicKey)throw new S("No WebAuthn credential found for PRIMARY mode");return await l(g.publicKey)}let c=s==="STRICT",a=await this.getMnemonicFromSession(c,s);return(await Fe(a,o,s,i)).address}catch(s){throw this.config.onError?.(s),new S("Failed to get address",s)}}async importMnemonic(e){try{if(!this.currentUser)throw new S("Must be authenticated to import mnemonic");if(!e||e.trim().split(/\s+/).length<12)throw new S("Invalid mnemonic: must be at least 12 words");let t=await Xr();if(!t.user)throw new S("Authentication failed");let r=t.user.credentialId,o=(await new F().getCredentialById(r))?.publicKey,c=await j(r,o),a=await ie(e.trim(),c);await this.walletStorage.store({ethereumAddress:this.currentUser.ethereumAddress,encryptedMnemonic:a,credentialId:r,createdAt:new Date().toISOString()}),this.currentWallet={address:this.currentUser.ethereumAddress,mnemonic:e.trim()},await this.sessionManager.startSession(e.trim(),r,this.currentUser.ethereumAddress,o,"STANDARD")}catch(t){throw this.config.onError?.(t),new S("Failed to import mnemonic",t)}}async signMessage(e,t){try{if(!this.currentUser)throw new S("Must be authenticated to sign message");let r=t?.mode||fe,s=t?.tag||pe,i=t?.origin||Me(),o=t?.signingMethod||"EIP191",c=r==="STRICT"?!0:t?.requireAuth||!1,a=await this.getMnemonicFromSession(c,r),u=await Fe(a,i,r,s),{Wallet:l}=await import("ethers"),h;if(u.privateKey)h=new l(u.privateKey);else{let{deriveWalletFromMnemonic:d}=await Promise.resolve().then(()=>(gt(),Ps)),{privateKey:f}=d(a,u.index);h=new l(f)}let g;switch(o){case"EIP191":case"SIWE":g=await h.signMessage(e);break;case"EIP712":if(!t?.eip712Domain||!t?.eip712Types||!t?.eip712PrimaryType)throw new S("EIP712 signing requires eip712Domain, eip712Types, and eip712PrimaryType in options");let d;try{d=typeof e=="string"?JSON.parse(e):e}catch{throw new S("EIP712 message must be valid JSON or an object")}g=await h.signTypedData(t.eip712Domain,t.eip712Types,d);break;case"rawHash":let{SigningKey:f}=await import("ethers"),y=e;if(y.startsWith("0x")&&(y=y.slice(2)),y.length!==64)throw new S("rawHash signing method requires a 32-byte hash (64 hex characters)");g=new f(h.privateKey).sign("0x"+y).serialized;break;default:throw new S(`Unsupported signing method: ${o}`)}return{signature:g,address:u.address,mode:u.mode,tag:u.tag,origin:u.origin}}catch(r){throw this.config.onError?.(r),new S("Failed to sign message",r)}}async signMessageWithPasskey(e){try{if(!this.currentUser)throw new S("Must be authenticated to sign message");let{extractRS:t}=await Promise.resolve().then(()=>(Ns(),na)),{base64UrlDecode:r}=await Promise.resolve().then(()=>(xe(),ks)),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")),c=this.currentUser.credentialId;if(!c)throw new S("Credential ID not found in user object");let a={challenge:o,rpId:window.location.hostname,allowCredentials:[{id:r(c),type:"public-key",transports:["internal","hybrid","usb","nfc","ble"]}],userVerification:"required",timeout:6e4},u=await navigator.credentials.get({publicKey:a});if(!u||!u.response)throw new S("WebAuthn signature failed");let l=u.response,h=new Uint8Array(l.authenticatorData),g=new Uint8Array(l.clientDataJSON),d=await crypto.subtle.digest("SHA-256",g),f=new Uint8Array(h.length+d.byteLength);f.set(h,0),f.set(new Uint8Array(d),h.length);let y=await crypto.subtle.digest("SHA-256",f.buffer),k="0x"+Buffer.from(y).toString("hex"),m=new Uint8Array(l.signature),{r:b,s:v}=t(m),{CredentialStorage:A}=await Promise.resolve().then(()=>(Te(),Qr)),C=await new A().getCredentialById(c);if(!C||!C.publicKey)throw new S("No WebAuthn credential found for PRIMARY mode");let{base64UrlToArrayBuffer:x}=await Promise.resolve().then(()=>(xe(),ks)),P=x(C.publicKey),G=await crypto.subtle.importKey("spki",P,{name:"ECDSA",namedCurve:"P-256"},!0,["verify"]),he=await crypto.subtle.exportKey("jwk",G);if(!he.x||!he.y)throw new S("Invalid P-256 public key: missing x or y coordinates");let dt="0x"+Buffer.from(x(he.x)).toString("hex"),ht="0x"+Buffer.from(x(he.y)).toString("hex"),{deriveAddressFromP256PublicKey:I}=await Promise.resolve().then(()=>(mt(),tn)),vd=await I(C.publicKey);return{signature:{r:b,s:v},messageHash:i,signedHash:k,address:vd,publicKey:{qx:dt,qy:ht}}}catch(t){throw this.config.onError?.(t),new S("Failed to sign message with passkey",t)}}async sendTransaction(e,t){try{if(!this.currentUser)throw new S("Must be authenticated to send transaction");let r=t?.mode||fe,s=t?.tag||pe,i=t?.origin||Me();if(r==="PRIMARY")throw t?.rpcUrl?new S("PRIMARY mode sendTransaction is not yet supported. Use signMessageWithPasskey() to obtain a P-256 signature and submit via a bundler manually."):new S("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=r==="STRICT"?!0:t?.requireAuth||!1,c=await this.getMnemonicFromSession(o,r),a=await Fe(c,i,r,s),{Wallet:u,JsonRpcProvider:l}=await import("ethers"),h;if(a.privateKey)h=new u(a.privateKey);else{let{deriveWalletFromMnemonic:k}=await Promise.resolve().then(()=>(gt(),Ps)),{privateKey:m}=k(c,a.index);h=new u(m)}let g=t?.rpcUrl??(await this.getEndpoints(e.chainId))[0];if(!g)throw new S(`No RPC endpoint found for chainId ${e.chainId}. Pass options.rpcUrl.`);let d=new l(g);return{hash:(await h.connect(d).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:a.address,chainId:e.chainId,mode:a.mode,tag:a.tag,origin:a.origin}}catch(r){throw this.config.onError?.(r),new S("Failed to send transaction",r)}}async signAuthorization(e,t){try{if(!this.currentUser)throw new S("Must be authenticated to sign authorization");let{Wallet:r,Signature:s}=await import("ethers"),{hashEIP7702AuthorizationMessage:i,verifyEIP7702Authorization:o}=await Promise.resolve().then(()=>(ln(),Ts)),c;if(e.privateKey)c=new r(e.privateKey);else{let y=await this.getMnemonicFromSession(t?.requireAuth);c=r.fromPhrase(y)}let a=BigInt(e.chainId||1),u=e.nonce||0n,l=i(a,e.contractAddress,u),h=c.signingKey.sign(l),g=s.from(h),d={chainId:a,address:e.contractAddress.toLowerCase(),nonce:u,yParity:g.yParity,r:g.r,s:g.s};if(!o(a,e.contractAddress,u,d,c.address))throw new S("Signature verification failed - this should not happen");return d}catch(r){throw this.config.onError?.(r),new S("Failed to sign authorization",r)}}async getEndpoints(e){return an(e)}async supportsEIP7702(e,t){return ra(e,this.getEndpoints.bind(this),t)}getEIP1193Provider(e){let t=e?.chainId??1,r=this,s={},i=(c,...a)=>{(s[c]??[]).forEach(u=>u(...a))};return{async request({method:c,params:a}){switch(c){case"eth_accounts":case"eth_requestAccounts":return[await r.getAddress(e?.mode??"STANDARD",e?.tag??"MAIN")];case"eth_chainId":return"0x"+t.toString(16);case"eth_sendTransaction":{let u=(a??[])[0]??{};if(!u.chainId&&!t)throw new S("eth_sendTransaction: chainId is required");let l=u.chainId?parseInt(u.chainId,16):t;return(await r.sendTransaction({to:u.to,value:u.value!==void 0?BigInt(u.value):void 0,data:u.data??"0x",chainId:l,gasLimit:u.gas!==void 0?BigInt(u.gas):void 0,maxFeePerGas:u.maxFeePerGas!==void 0?BigInt(u.maxFeePerGas):void 0,maxPriorityFeePerGas:u.maxPriorityFeePerGas!==void 0?BigInt(u.maxPriorityFeePerGas):void 0,nonce:u.nonce!==void 0?parseInt(u.nonce,16):void 0},{mode:e?.mode,tag:e?.tag,rpcUrl:e?.rpcUrl})).hash}case"personal_sign":{let[u]=a??[],l=wc(u)?bc(u):u;return(await r.signMessage(l,{mode:e?.mode,tag:e?.tag,signingMethod:"EIP191"})).signature}case"eth_sign":{let[,u]=a??[],l=wc(u)?bc(u):u;return(await r.signMessage(l,{mode:e?.mode,tag:e?.tag,signingMethod:"EIP191"})).signature}case"eth_signTypedData_v4":{let[,u]=a??[],l=typeof u=="string"?JSON.parse(u):u,{domain:h,types:g,message:d,primaryType:f}=l,y={...g};return delete y.EIP712Domain,(await r.signMessage(JSON.stringify(d),{mode:e?.mode,tag:e?.tag,signingMethod:"EIP712",eip712Domain:h,eip712Types:y,eip712PrimaryType:f})).signature}case"wallet_switchEthereumChain":{let u=parseInt((a??[])[0]?.chainId??"0x1",16);return t=u,i("chainChanged","0x"+u.toString(16)),null}default:throw new S(`w3pk EIP-1193: unsupported method "${c}"`)}},on(c,a){s[c]||(s[c]=[]),s[c].push(a)},removeListener(c,a){s[c]&&(s[c]=s[c].filter(u=>u!==a))}}}async requestExternalWalletDelegation(e){if(!this.currentUser)throw new S("Must be authenticated to get w3pk delegation address. Call login() or register() first.");let{requestExternalWalletAuthorization:t,getDefaultProvider:r}=await Promise.resolve().then(()=>(Fs(),ta)),s=e?.provider||r();if(!s)throw new S("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(...r)=>(await this.loadZKModule())[t](...r)})}async getBackupStatus(){if(!this.currentUser)throw new S("Must be authenticated to check backup status");let{BackupManager:e}=await Promise.resolve().then(()=>(rt(),tt));return new e().getBackupStatus(this.currentUser.ethereumAddress)}async createBackupFile(e="password",t){if(!this.currentUser)throw new S("Must be authenticated to create backup");let r=await this.getMnemonicFromSession(!0),{BackupFileManager:s}=await Promise.resolve().then(()=>(le(),ge)),{BackupStorage:i}=await Promise.resolve().then(()=>(pn(),sa)),o=new s,c=new i,a,u;if(e==="password"){if(!t)throw new S("Password required for password-based backup");u=(await o.createPasswordBackup(r,this.currentUser.ethereumAddress,t)).backupFile,a=o.createDownloadableBackup(u)}else if(e==="passkey"){let l=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!l)throw new S("No wallet data found");let g=await new F().getCredentialById(l.credentialId);if(!g)throw new S("Credential not found");u=(await o.createPasskeyBackup(r,this.currentUser.ethereumAddress,g.id,g.publicKey)).backupFile,a=o.createDownloadableBackup(u)}else if(e==="hybrid"){if(!t)throw new S("Password required for hybrid backup");let l=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!l)throw new S("No wallet data found");let g=await new F().getCredentialById(l.credentialId);if(!g)throw new S("Credential not found");u=(await o.createHybridBackup(r,this.currentUser.ethereumAddress,t,g.id,g.publicKey)).backupFile,a=o.createDownloadableBackup(u)}else throw new S(`Unknown encryption type: ${e}`);return await c.storeBackupMetadata({id:crypto.randomUUID(),ethereumAddress:this.currentUser.ethereumAddress,method:"file",createdAt:new Date().toISOString(),addressChecksum:u.addressChecksum}),a}async setupSocialRecovery(e,t,r){if(!this.currentUser)throw new S("Must be authenticated to set up social recovery");let s=await this.getMnemonicFromSession(!0),{BackupFileManager:i}=await Promise.resolve().then(()=>(le(),ge)),o=new i,c;if(r)c=(await o.createPasswordBackup(s,this.currentUser.ethereumAddress,r)).backupFile;else{let h=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!h)throw new S("No wallet data found");let d=await new F().getCredentialById(h.credentialId);if(!d)throw new S("Credential not found");c=(await o.createPasskeyBackup(s,this.currentUser.ethereumAddress,d.id,d.publicKey)).backupFile}let{SocialRecovery:a}=await Promise.resolve().then(()=>(Ln(),Un));return{guardianShares:(await new a().splitAmongGuardians(c,e,t)).guardianShares,setupComplete:!0}}async generateGuardianInvite(e,t){let{SocialRecovery:r}=await Promise.resolve().then(()=>(Ln(),Un)),s=new r,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:r}=await Promise.resolve().then(()=>(Ln(),Un)),{BackupFileManager:s}=await Promise.resolve().then(()=>(le(),ge)),{BackupManager:i}=await Promise.resolve().then(()=>(rt(),tt)),o=new r,c=new s,a=new i,u=e.map(g=>typeof g=="string"?o.parseGuardianShare(g):g),l=await o.recoverFromShares(u),h;if(l.encryptionMethod==="password"){if(!t)throw new S("Password required to decrypt password-protected backup");h=await c.restoreWithPassword(l,t)}else throw new S("Passkey-encrypted backups not supported for guardian recovery. Use password-protected backups.");return a.markBackupVerified(h.ethereumAddress),h}async restoreFromBackupFile(e,t){let{BackupFileManager:r}=await Promise.resolve().then(()=>(le(),ge)),{BackupManager:s}=await Promise.resolve().then(()=>(rt(),tt)),i=new r,o=new s,c=await i.parseBackupFile(e),a,u;if(c.encryptionMethod==="password"){if(!t)throw new S("Password required to restore password-encrypted backup");let l=await i.restoreWithPassword(c,t);a=l.mnemonic,u=l.ethereumAddress}else if(c.encryptionMethod==="passkey"){if(!this.currentUser)throw new S("Must be logged in with passkey to restore passkey-encrypted backup. Call login() first.");let g=(await new F().getAllCredentials()).find(f=>f.ethereumAddress.toLowerCase()===this.currentUser.ethereumAddress.toLowerCase());if(!g)throw new S("Credential not found for current user");let d=await i.restoreWithExistingPasskey(c,g.id,g.publicKey);a=d.mnemonic,u=d.ethereumAddress}else if(c.encryptionMethod==="hybrid"){if(!t)throw new S("Password required to restore hybrid backup");if(!this.currentUser)throw new S("Must be logged in with passkey to restore hybrid backup. Call login() first.");let g=(await new F().getAllCredentials()).find(f=>f.ethereumAddress.toLowerCase()===this.currentUser.ethereumAddress.toLowerCase());if(!g)throw new S("Credential not found for current user");let d=await i.restoreWithHybrid(c,t,g.id,g.publicKey);a=d.mnemonic,u=d.ethereumAddress}else throw new S(`Unknown encryption method: ${c.encryptionMethod}`);if(o.markBackupVerified(u),this.currentWallet={address:u,mnemonic:a},this.currentUser){let l=new F,g=(await l.getAllCredentials()).find(d=>d.ethereumAddress.toLowerCase()===this.currentUser.ethereumAddress.toLowerCase());if(g){let d=this.currentUser.ethereumAddress;d.toLowerCase()!==u.toLowerCase()&&await this.walletStorage.delete(d),await l.updateCredentialAddress(g.id,u);let f=await(await Promise.resolve().then(()=>(q(),Re))).deriveEncryptionKeyFromWebAuthn(g.id,g.publicKey),y=await(await Promise.resolve().then(()=>(q(),Re))).encryptData(a,f);await this.walletStorage.store({ethereumAddress:u,encryptedMnemonic:y,credentialId:g.id,createdAt:new Date().toISOString()}),this.currentUser={...this.currentUser,ethereumAddress:u},await this.sessionManager.startSession(a,g.id,u,g.publicKey,"STANDARD"),this.config.onAuthStateChanged?.(!0,this.currentUser)}}return{mnemonic:a,ethereumAddress:u}}async syncWalletWithPasskey(e,t){let{BackupFileManager:r}=await Promise.resolve().then(()=>(le(),ge)),{BackupManager:s}=await Promise.resolve().then(()=>(rt(),tt)),{promptPasskeySelection:i}=await Promise.resolve().then(()=>(di(),lc)),o=new r,c=new s,a=await i(),u=await o.parseBackupFile(e),l,h;if(u.encryptionMethod==="password"){if(!t)throw new S("Password required to restore password-encrypted backup");let f=await o.restoreWithPassword(u,t);l=f.mnemonic,h=f.ethereumAddress}else if(u.encryptionMethod==="passkey"){if(!a.publicKey)throw new S("Passkey public key not found. The passkey may not be registered on this device yet.");let f=await o.restoreWithExistingPasskey(u,a.credentialId,a.publicKey);l=f.mnemonic,h=f.ethereumAddress}else if(u.encryptionMethod==="hybrid"){if(!t)throw new S("Password required to restore hybrid backup");if(!a.publicKey)throw new S("Passkey public key not found. The passkey may not be registered on this device yet.");let f=await o.restoreWithHybrid(u,t,a.credentialId,a.publicKey);l=f.mnemonic,h=f.ethereumAddress}else throw new S(`Unknown encryption method: ${u.encryptionMethod}`);c.markBackupVerified(h);let d=await new F().getCredentialById(a.credentialId);if(d){let{deriveEncryptionKeyFromWebAuthn:f,encryptData:y}=await Promise.resolve().then(()=>(q(),Re)),k=await f(d.id,d.publicKey),m=await y(l,k);await this.walletStorage.store({ethereumAddress:h,encryptedMnemonic:m,credentialId:d.id,createdAt:new Date().toISOString()}),this.currentUser={username:d.username,ethereumAddress:h,credentialId:d.id},await this.sessionManager.startSession(l,d.id,h,d.publicKey,"STANDARD"),this.config.onAuthStateChanged?.(!0,this.currentUser)}return{mnemonic:l,ethereumAddress:h}}async registerWithBackupFile(e,t,r){let{BackupFileManager:s}=await Promise.resolve().then(()=>(le(),ge)),{BackupManager:i}=await Promise.resolve().then(()=>(rt(),tt)),o=new s,c=new i,a=await o.parseBackupFile(e);if(a.encryptionMethod!=="password")throw new S("Can only register with password-encrypted backups. Use restoreFromBackupFile() for passkey-encrypted backups.");let{mnemonic:u,ethereumAddress:l}=await o.restoreWithPassword(a,t),{Wallet:h}=await import("ethers");if(h.fromPhrase(u).address.toLowerCase()!==l.toLowerCase())throw new S("Backup verification failed: address mismatch");return c.markBackupVerified(l),this.currentWallet={address:l,mnemonic:u},this.register({username:r})}async getSyncStatus(){let{DeviceSyncManager:e}=await Promise.resolve().then(()=>(vr(),_n));return new e().getSyncInfo()}async exportForSync(){if(!this.currentUser)throw new S("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 S("No wallet data found");let s=await new F().getCredentialById(t.credentialId);if(!s)throw new S("Credential not found");let{DeviceSyncManager:i}=await Promise.resolve().then(()=>(vr(),_n)),o=new i,{backupFile:c,blob:a}=await o.exportForSync(e,this.currentUser.ethereumAddress,s.id,s.publicKey),u=`w3pk-sync-${this.currentUser.ethereumAddress.substring(0,8)}.json`,l;try{l=await o.generateSyncQR(c)}catch(h){console.warn("QR code generation failed:",h)}return{blob:a,filename:u,qrCode:l}}async importFromSync(e){if(!this.currentUser)throw new S("Must be logged in to import from sync. Call login() first.");let{DeviceSyncManager:t}=await Promise.resolve().then(()=>(vr(),_n)),{BackupFileManager:r}=await Promise.resolve().then(()=>(le(),ge)),{BackupManager:s}=await Promise.resolve().then(()=>(rt(),tt)),i=new r,o=new t,c=new s,a=await i.parseBackupFile(e),u=await this.walletStorage.retrieve(this.currentUser.ethereumAddress);if(!u)throw new S("No wallet data found for current user");let h=await new F().getCredentialById(u.credentialId);if(!h)throw new S("Credential not found");let{mnemonic:g,ethereumAddress:d}=await o.importFromSync(a,h.id,h.publicKey);c.markBackupVerified(d);let f=await(await Promise.resolve().then(()=>(q(),Re))).deriveEncryptionKeyFromWebAuthn(h.id,h.publicKey),y=await(await Promise.resolve().then(()=>(q(),Re))).encryptData(g,f);return await this.walletStorage.store({ethereumAddress:d,encryptedMnemonic:y,credentialId:h.id,createdAt:new Date().toISOString()}),{ethereumAddress:d,success:!0}}async detectSyncCapabilities(){let{PlatformDetector:e}=await Promise.resolve().then(()=>(gc(),pc));return new e().detectSyncCapabilities()}async simulateRecoveryScenario(e){if(!this.currentUser)throw new S("Must be authenticated to run recovery simulation");let t=await this.getBackupStatus(),{RecoverySimulator:r}=await Promise.resolve().then(()=>(Ar(),$n));return new r().simulateScenario(e,t)}async runRecoveryTest(){if(!this.currentUser)throw new S("Must be authenticated to run recovery test");let e=await this.getBackupStatus(),{RecoverySimulator:t}=await Promise.resolve().then(()=>(Ar(),$n));return new t().runInteractiveTest(e)}async getEducation(e){let{getExplainer:t}=await Promise.resolve().then(()=>(Ar(),$n)),r=t(e);if(!r)throw new S(`Unknown education topic: ${e}`);return r}hasActiveSession(){return this.sessionManager.isActive()}getSessionRemainingTime(){return this.sessionManager.getRemainingTime()}extendSession(){try{this.sessionManager.extendSession()}catch(e){throw new S("Cannot extend session",e)}}async clearSession(){await this.sessionManager.clearSession()}setSessionDuration(e){this.sessionManager.setSessionDuration(e)}};Y();di();mt();Ar();async function Rg(n,e="build"){let{importer:t}=await Promise.resolve().then(()=>(Wu(),zu)),{MemoryBlockstore:r}=await Promise.resolve().then(()=>(fd(),hd)),s=new r,o=t(async function*(){yield{path:e,content:n}}(),s,{cidVersion:1,rawLeaves:!0,wrapWithDirectory:!1});for await(let c of o)return c.cid.toString();throw new Error("Failed to generate CID")}async function Tg(n){let e=["index.js","index.mjs","index.d.ts"],t=[],r=0;for(let o of e){let c=`${n}/${o}`,a=await fetch(c);if(!a.ok)throw new Error(`Failed to fetch ${o}: ${a.statusText}`);let u=await a.arrayBuffer(),l=new Uint8Array(u);t.push(l),r+=l.length}let s=new Uint8Array(r),i=0;for(let o of t)s.set(o,i),i+=o.length;return s}async function Fo(n){let e=await Tg(n);return Rg(e)}function Mo(){try{return pd().version}catch{throw new Error("Failed to read package version")}}async function No(){let n=Mo();return Fo(`https://unpkg.com/w3pk@${n}/dist`)}async function gd(n){return await No()===n}xe();Ns();gt();function md(n=11){let e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",t=new Uint8Array(n);return crypto.getRandomValues(t),Array.from(t).map(r=>e[r%e.length]).join("")}function yd(n){if(!n.domain||!n.address||!n.uri||!n.version||n.chainId===void 0||!n.nonce||!n.issuedAt)throw new Error("Missing required SIWE message fields");if(n.version!=="1")throw new Error('SIWE version must be "1"');if(n.nonce.length<8||!/^[a-zA-Z0-9]+$/.test(n.nonce))throw new Error("Nonce must be at least 8 alphanumeric characters");if(n.statement&&n.statement.includes(`
958
961
  `))throw new Error("Statement cannot contain newlines");let e=`${n.domain} wants you to sign in with your Ethereum account:
959
962
  `;if(e+=`${n.address}
960
963
  `,e+=`
@@ -969,8 +972,8 @@ Expiration Time: ${n.expirationTime}`),n.notBefore&&(e+=`
969
972
  Not Before: ${n.notBefore}`),n.requestId&&(e+=`
970
973
  Request ID: ${n.requestId}`),n.resources&&n.resources.length>0){e+=`
971
974
  Resources:`;for(let t of n.resources)e+=`
972
- - ${t}`}return e}function ms(n){let e=n.split(`
973
- `);if(e.length<7)throw new Error("Invalid SIWE message: too few lines");let r=e[0].match(/^(.+) wants you to sign in with your Ethereum account:$/);if(!r)throw new Error("Invalid SIWE message: malformed domain line");let s=r[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,c="",a="",u=0,l="",h="",g,d,f,y=[],k=3;for(e[k]&&!e[k].startsWith("URI: ")&&(o=e[k],k++,e[k]===""&&k++);k<e.length;k++){let m=e[k];if(m.startsWith("URI: "))c=m.substring(5);else if(m.startsWith("Version: "))a=m.substring(9);else if(m.startsWith("Chain ID: "))u=parseInt(m.substring(10),10);else if(m.startsWith("Nonce: "))l=m.substring(7);else if(m.startsWith("Issued At: "))h=m.substring(11);else if(m.startsWith("Expiration Time: "))g=m.substring(17);else if(m.startsWith("Not Before: "))d=m.substring(12);else if(m.startsWith("Request ID: "))f=m.substring(12);else if(m.startsWith("Resources:")){for(k++;k<e.length&&e[k].startsWith("- ");)y.push(e[k].substring(2)),k++;break}}if(!c||!a||!u||!l||!h)throw new Error("Invalid SIWE message: missing required fields");return{domain:s,address:i,statement:o,uri:c,version:a,chainId:u,nonce:l,issuedAt:h,expirationTime:g,notBefore:d,requestId:f,resources:y.length>0?y:void 0}}function wd(n,e){let t=[];try{let r=typeof n=="string"?ms(n):n;return e?.domain&&r.domain!==e.domain&&t.push(`Domain mismatch: expected "${e.domain}", got "${r.domain}"`),e?.chainId!==void 0&&r.chainId!==e.chainId&&t.push(`Chain ID mismatch: expected ${e.chainId}, got ${r.chainId}`),r.version!=="1"&&t.push(`Invalid version: must be "1", got "${r.version}"`),(r.nonce.length<8||!/^[a-zA-Z0-9]+$/.test(r.nonce))&&t.push("Nonce must be at least 8 alphanumeric characters"),e?.checkExpiration&&r.expirationTime&&new Date(r.expirationTime)<new Date&&t.push("Message has expired"),e?.checkNotBefore&&r.notBefore&&new Date(r.notBefore)>new Date&&t.push("Message is not yet valid (not-before constraint)"),{valid:t.length===0,errors:t,parsed:r}}catch(r){return t.push(r.message),{valid:!1,errors:t}}}async function bd(n,e,t){try{let{verifyMessage:r}=await import("ethers"),s=r(n,e),i=ms(n);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(r){return{valid:!1,error:r.message}}}function Fg(n,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"],r=n.split(`
975
+ - ${t}`}return e}function ys(n){let e=n.split(`
976
+ `);if(e.length<7)throw new Error("Invalid SIWE message: too few lines");let r=e[0].match(/^(.+) wants you to sign in with your Ethereum account:$/);if(!r)throw new Error("Invalid SIWE message: malformed domain line");let s=r[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,c="",a="",u=0,l="",h="",g,d,f,y=[],k=3;for(e[k]&&!e[k].startsWith("URI: ")&&(o=e[k],k++,e[k]===""&&k++);k<e.length;k++){let m=e[k];if(m.startsWith("URI: "))c=m.substring(5);else if(m.startsWith("Version: "))a=m.substring(9);else if(m.startsWith("Chain ID: "))u=parseInt(m.substring(10),10);else if(m.startsWith("Nonce: "))l=m.substring(7);else if(m.startsWith("Issued At: "))h=m.substring(11);else if(m.startsWith("Expiration Time: "))g=m.substring(17);else if(m.startsWith("Not Before: "))d=m.substring(12);else if(m.startsWith("Request ID: "))f=m.substring(12);else if(m.startsWith("Resources:")){for(k++;k<e.length&&e[k].startsWith("- ");)y.push(e[k].substring(2)),k++;break}}if(!c||!a||!u||!l||!h)throw new Error("Invalid SIWE message: missing required fields");return{domain:s,address:i,statement:o,uri:c,version:a,chainId:u,nonce:l,issuedAt:h,expirationTime:g,notBefore:d,requestId:f,resources:y.length>0?y:void 0}}function wd(n,e){let t=[];try{let r=typeof n=="string"?ys(n):n;return e?.domain&&r.domain!==e.domain&&t.push(`Domain mismatch: expected "${e.domain}", got "${r.domain}"`),e?.chainId!==void 0&&r.chainId!==e.chainId&&t.push(`Chain ID mismatch: expected ${e.chainId}, got ${r.chainId}`),r.version!=="1"&&t.push(`Invalid version: must be "1", got "${r.version}"`),(r.nonce.length<8||!/^[a-zA-Z0-9]+$/.test(r.nonce))&&t.push("Nonce must be at least 8 alphanumeric characters"),e?.checkExpiration&&r.expirationTime&&new Date(r.expirationTime)<new Date&&t.push("Message has expired"),e?.checkNotBefore&&r.notBefore&&new Date(r.notBefore)>new Date&&t.push("Message is not yet valid (not-before constraint)"),{valid:t.length===0,errors:t,parsed:r}}catch(r){return t.push(r.message),{valid:!1,errors:t}}}async function bd(n,e,t){try{let{verifyMessage:r}=await import("ethers"),s=r(n,e),i=ys(n);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(r){return{valid:!1,error:r.message}}}ai();Mn();function Fg(n,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"],r=n.split(`
974
977
  `),s=[],i=500;for(let c=0;c<r.length&&s.length<i;c++){let u=r[c].toLowerCase();if(t.some(l=>u.includes(l.toLowerCase()))){let l=Math.max(0,c-2),h=Math.min(r.length,c+3);for(let g=l;g<h;g++)s.includes(r[g])||s.push(r[g])}}let o=s.join(`
975
978
  `);return o.length>e?o.substring(0,e)+`
976
979
 
@@ -992,8 +995,8 @@ Resources:`;for(let t of n.resources)e+=`
992
995
  ---
993
996
 
994
997
  `,s++)}catch{}return s===0&&(e+=`No transaction-related code found in JavaScript files.
995
- `),e}async function No(n={}){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:r="w3pk",model:s="anthropic",focusMode:i="transactions"}=n;console.log("[W3PK Inspect] Starting inspection of",e),console.log("[W3PK Inspect] Focus mode:",i);let o=await Mg(e);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.",a=new FormData;a.append("message",c),a.append("model",s),a.append("context",r);let u=new Blob([o],{type:"text/markdown"});a.append("file",u,"app-source.md");let l=await fetch(`${t}/ask`,{method:"POST",body:a});if(!l.ok){let y=await l.text();throw new Error(`Rukh API error: ${l.status} - ${y}`)}let h=await l.json(),g=h.output||h.response||h.message||JSON.stringify(h);console.log("[W3PK Inspect] Analysis complete!");let f=Array.from(document.querySelectorAll("script[src]")).map(y=>new URL(y.src).pathname).filter(y=>y&&!y.includes("node_modules"));return{report:g,analyzedFiles:f,appUrl:e}}async function Sd(n){console.log(`\u{1F50D} W3PK Security Inspection Starting...
996
- `);try{let e=await No(n);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
998
+ `),e}async function Uo(n={}){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:r="w3pk",model:s="anthropic",focusMode:i="transactions"}=n;console.log("[W3PK Inspect] Starting inspection of",e),console.log("[W3PK Inspect] Focus mode:",i);let o=await Mg(e);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.",a=new FormData;a.append("message",c),a.append("model",s),a.append("context",r);let u=new Blob([o],{type:"text/markdown"});a.append("file",u,"app-source.md");let l=await fetch(`${t}/ask`,{method:"POST",body:a});if(!l.ok){let y=await l.text();throw new Error(`Rukh API error: ${l.status} - ${y}`)}let h=await l.json(),g=h.output||h.response||h.message||JSON.stringify(h);console.log("[W3PK Inspect] Analysis complete!");let f=Array.from(document.querySelectorAll("script[src]")).map(y=>new URL(y.src).pathname).filter(y=>y&&!y.includes("node_modules"));return{report:g,analyzedFiles:f,appUrl:e}}async function Sd(n){console.log(`\u{1F50D} W3PK Security Inspection Starting...
999
+ `);try{let e=await Uo(n);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
997
1000
  `),console.log(e.report),console.log(`
998
- \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}}function xd(n={}){return new Et(n)}var Ng=xd;
1001
+ \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}}function xd(n={}){return new Ct(n)}var Ng=xd;
999
1002
  //# sourceMappingURL=index.js.map