@nexus-cross/crossx-sdk-core 1.4.2 → 1.4.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/crossx.global
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
var CROSSx=function(
|
|
1
|
+
var CROSSx=function(j){"use strict";var Vo=Object.defineProperty;var zo=(j,h,x)=>h in j?Vo(j,h,{enumerable:!0,configurable:!0,writable:!0,value:x}):j[h]=x;var O=(j,h,x)=>zo(j,typeof h!="symbol"?h+"":h,x);var yt,Ms;var h=(s=>(s.AUTH_NOT_INITIALIZED="AUTH_NOT_INITIALIZED",s.AUTH_FAILED="AUTH_FAILED",s.AUTH_TOKEN_INVALID="AUTH_TOKEN_INVALID",s.AUTH_TOKEN_EXPIRED="AUTH_TOKEN_EXPIRED",s.AUTH_NOT_AUTHENTICATED="AUTH_NOT_AUTHENTICATED",s.ALREADY_AUTHENTICATED="ALREADY_AUTHENTICATED",s.SESSION_EXPIRED="SESSION_EXPIRED",s.OAUTH_POPUP_BLOCKED="OAUTH_POPUP_BLOCKED",s.WALLET_NOT_FOUND="WALLET_NOT_FOUND",s.WALLET_CREATION_FAILED="WALLET_CREATION_FAILED",s.WALLET_ALREADY_EXISTS="WALLET_ALREADY_EXISTS",s.SIGN_FAILED="SIGN_FAILED",s.SIGN_REJECTED="SIGN_REJECTED",s.TX_FAILED="TX_FAILED",s.TX_REJECTED="TX_REJECTED",s.BROADCAST_FAILED="BROADCAST_FAILED",s.USER_REJECTED="USER_REJECTED",s.TX_INVALID_PARAMS="TX_INVALID_PARAMS",s.NETWORK_ERROR="NETWORK_ERROR",s.NETWORK_NOT_CONFIGURED="NETWORK_NOT_CONFIGURED",s.INVALID_CHAIN="INVALID_CHAIN",s.CHAIN_NOT_SUPPORTED="CHAIN_NOT_SUPPORTED",s.CHAIN_ADAPTER_NOT_FOUND="CHAIN_ADAPTER_NOT_FOUND",s.NOT_IMPLEMENTED="NOT_IMPLEMENTED",s.SIGNATURE_FAILED="SIGNATURE_FAILED",s.TRANSACTION_FAILED="TRANSACTION_FAILED",s.PREPARE_FAILED="PREPARE_FAILED",s.PREPARE_EXPIRED="PREPARE_EXPIRED",s.PREPARE_MISMATCH="PREPARE_MISMATCH",s.MIGRATION_FAILED="MIGRATION_FAILED",s.MIGRATION_BACKUP_EXISTS="MIGRATION_BACKUP_EXISTS",s.MIGRATION_PIN_LOCKED="MIGRATION_PIN_LOCKED",s.GATEWAY_INTERNAL_ERROR="GATEWAY_INTERNAL_ERROR",s.GATEWAY_LOCK_CONFLICT="GATEWAY_LOCK_CONFLICT",s.WALLET_INCONSISTENT_STATE="WALLET_INCONSISTENT_STATE",s.PROJECT_ID_MISSING="PROJECT_ID_MISSING",s.ORIGIN_NOT_ALLOWED="ORIGIN_NOT_ALLOWED",s.APP_IDENTIFIER_MISSING="APP_IDENTIFIER_MISSING",s.INVALID_APP_TYPE="INVALID_APP_TYPE",s.PROJECT_NOT_REGISTERED="PROJECT_NOT_REGISTERED",s.SIGNATURE_SIGNER_MISMATCH="SIGNATURE_SIGNER_MISMATCH",s.GAS_ESTIMATION_FAILED="GAS_ESTIMATION_FAILED",s.TYPED_DATA_CHAIN_ID_MISMATCH="TYPED_DATA_CHAIN_ID_MISMATCH",s.PIN_NOT_SET="PIN_NOT_SET",s.PIN_WRONG="PIN_WRONG",s.PIN_INVALID="PIN_INVALID",s.PIN_REPEATED_PATTERN="PIN_REPEATED_PATTERN",s.PIN_CANCELLED="PIN_CANCELLED",s.EXTERNAL_WALLET_REQUESTED="EXTERNAL_WALLET_REQUESTED",s.PIN_LOCKED="PIN_LOCKED",s.HMAC_REQUIRED="HMAC_REQUIRED",s.HMAC_VERIFICATION_FAILED="HMAC_VERIFICATION_FAILED",s.WITHDRAW_FAILED="WITHDRAW_FAILED",s.USER_NOT_FOUND="USER_NOT_FOUND",s.INVALID_CONFIG="INVALID_CONFIG",s.UNKNOWN_ERROR="UNKNOWN_ERROR",s))(h||{});class x extends Error{constructor(e,r,t){super(r),this.code=e,this.details=t,this.name="CROSSxError",Object.setPrototypeOf(this,x.prototype)}toJSON(){return{name:this.name,code:this.code,message:this.message,details:this.details}}}const tt={CROSS_MAINNET:{caipId:"eip155:612055",chainId:612055,name:"CROSS Mainnet",nativeCurrency:{symbol:"CROSS",decimals:18},rpcUrl:"https://mainnet.crosstoken.io:22001"},CROSS_TESTNET:{caipId:"eip155:612044",chainId:612044,name:"CROSS Testnet",nativeCurrency:{symbol:"tCROSS",decimals:18},rpcUrl:"https://testnet.crosstoken.io:22001",testnet:!0},BSC_MAINNET:{caipId:"eip155:56",chainId:56,name:"BNB Smart Chain",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-mainnet.crosstoken.io/2272489872e4f1475ff25d57ce93b51989f933c7"},BSC_TESTNET:{caipId:"eip155:97",chainId:97,name:"BNB Smart Chain Testnet",nativeCurrency:{symbol:"BNB",decimals:18},rpcUrl:"https://bsc-testnet.crosstoken.io/110ea3628b77f244e5dbab16790d81bba874b962",testnet:!0},RONIN_MAINNET:{caipId:"eip155:2020",chainId:2020,name:"Ronin",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://api.roninchain.com/rpc"},RONIN_SAIGON:{caipId:"eip155:202601",chainId:202601,name:"Ronin Saigon",nativeCurrency:{symbol:"RON",decimals:18},rpcUrl:"https://saigon-testnet.roninchain.com/rpc",testnet:!0}},Us=Object.fromEntries(Object.entries(tt).map(([s,e])=>[s,e.caipId])),Hs=new Map(Object.values(tt).map(s=>[s.caipId,s]));new Map(Object.values(tt).map(s=>[s.chainId,s]));const Bs={symbol:"",decimals:18};function bt(s){var e;return((e=Hs.get(s))==null?void 0:e.nativeCurrency)??Bs}class tr{constructor(e,r){this.sdk=e,this.chainId=r,this._listeners=new Map}async request({method:e,params:r=[]}){switch(e){case"eth_accounts":case"eth_requestAccounts":{const t=await this.sdk.getAddress();return t?[t.address]:[]}case"eth_chainId":return this._caip2ToHex(this.chainId);case"net_version":return this.chainId.split(":")[1]??"1";case"eth_signTransaction":{const t=this._normalizeEIP1193Tx(r[0]);return(await this.sdk.signTransaction(this.chainId,t)).signedTx}case"eth_sendTransaction":{const t=this._normalizeEIP1193Tx(r[0]);return(await this.sdk.sendTransaction(this.chainId,t)).txHash}case"personal_sign":case"eth_sign":throw new x(h.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signMessage()를 직접 사용하세요.`);case"eth_signTypedData":case"eth_signTypedData_v1":case"eth_signTypedData_v3":case"eth_signTypedData_v4":throw new x(h.NOT_IMPLEMENTED,`${e}은(는) 아직 지원되지 않습니다. sdk.signTypedData() 또는 sdk.signTypedDataOffchain()을 직접 사용하세요.`);default:return this.sdk.walletRpc(e,r,this.chainId)}}on(e,r){return this._listeners.has(e)||this._listeners.set(e,new Set),this._listeners.get(e).add(r),this}removeListener(e,r){var t;return(t=this._listeners.get(e))==null||t.delete(r),this}emit(e,...r){var t;(t=this._listeners.get(e))==null||t.forEach(n=>n(...r))}_caip2ToHex(e){const r=e.split(":");return`0x${parseInt(r[1]??"1",10).toString(16)}`}_normalizeEIP1193Tx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,gasLimit:e.gasLimit??e.gas,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,nonce:e.nonce!==void 0?parseInt(String(e.nonce),16):void 0,chainId:parseInt(this.chainId.split(":")[1]??"1",10)}}}let be=null;function Yo(s){}function rr(s){be=s}const d={info(...s){if(be){be.log(...s);return}console.log(...s)},log(...s){if(be){be.log(...s);return}},warn(...s){if(be){be.warn(...s);return}},error(...s){if(be){be.error(...s);return}}},Fs={confirm:"확인",cancel:"취소",close:"닫기",signMessage_title:"메시지 서명",signTypedData_title:"데이터 서명",signTransaction_title:"트랜잭션 서명",sendTransaction_title:"트랜잭션 전송",tx_pending:"트랜잭션 처리 중...",tx_success:"트랜잭션이 완료되었습니다",tx_failed:"트랜잭션이 실패했습니다",tx_timeout:"트랜잭션 확인 시간이 초과되었습니다",loginSelector_title:"로그인 방법 선택",loginSelector_google:"Google로 계속하기",loginSelector_apple:"Apple로 계속하기",loginSelector_connectOtherWallets:"다른 지갑으로 연결",loginSelector_connectOtherWalletsDesc:"기존 Web3 지갑을 연결하여 자산을 관리하세요.",migration_foundTitle:"기존 지갑 발견",migration_foundDescription:"기존 CROSSx 지갑이 발견되었습니다. 복구하시겠습니까?",migration_recoverButton:"복구하기",migration_skipButton:"건너뛰기",recoveryPinInput_title:"PIN 입력",recoveryPinInput_placeholder:"4자리 PIN을 입력하세요",recoveryPinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",walletSelector_title:"지갑 선택",walletSelector_addButton:"지갑 추가",walletSelector_selected:"선택됨",pinNotice_headerSubtitle:"트랜잭션, PK/니모닉 내보내기 및 계정 삭제 시 필요합니다.",pinNotice_title:"PIN 설정 주의사항",pinNotice_description:"보안을 위해 이 PIN은 재설정하거나 복구할 수 없습니다. 반드시 기억해 두거나 안전한 곳에 보관하세요.",pinNotice_check1:"이 PIN을 분실하면 지갑과 자산에 영구적으로 접근이 불가능해진다는 것을 이해합니다.",pinNotice_check2:"지원팀을 포함한 어느 누구도 이 PIN을 복구하거나 재설정해 줄 수 없다는 것을 이해합니다.",pinNotice_nextButton:"다음",pinNotice_submitButton:"동의합니다",pinSetup_title:"PIN 만들기",pinSetup_headerSubtitle:"이 PIN은 거래 승인에 사용됩니다.",pinSetup_subtitle:"거래 승인을 위한 6자리 PIN을 설정하세요.",pinSetup_confirmTitle:"PIN 확인",pinSetup_confirmSubtitle:"확인을 위해 PIN을 다시 입력하세요.",pinSetup_mismatchError:"PIN이 일치하지 않습니다. 다시 시도해 주세요.",pinValidation_tooShort:"6자리 PIN을 입력해 주세요.",pinValidation_numbersOnly:"숫자(0-9)만 입력할 수 있습니다.",pinValidation_repeatingDigit:"같은 숫자를 연속으로 3번 이상 사용할 수 없습니다.",pinValidation_sequential:"연속된 숫자(예: 123456)는 사용할 수 없습니다.",pinValidation_alternatingPattern:"반복 패턴(예: 121212)은 사용할 수 없습니다.",pinInput_title:"PIN 입력",pinInput_subtitle:"계속하려면 6자리 PIN을 입력하세요.",pinInput_error:"PIN이 올바르지 않습니다. 다시 시도해 주세요.",verifyPin_title:"PIN 확인",verifyPin_subtitle:"계속하려면 PIN을 확인해 주세요.",pinLocked_message:"잠금이 해제된 후 다시 시도해 주세요.",pinLocked_availableFrom:"이용 가능 시간",pinLocked_failureWarning:"추가 실패 시 계정이 잠금됩니다.",pinLocked_permanent:"너무 많은 시도 실패로 계정이 영구 잠금되었습니다.",alert_sessionExpired:"세션이 만료되었습니다. 다시 로그인해 주세요.",alert_accountWithdrawn:"계정이 탈퇴 처리되었거나 더 이상 사용할 수 없습니다. 다시 로그인해 주세요.",alert_walletNotFound:"지갑 정보를 찾을 수 없습니다. 다시 로그인해 주세요.",alert_differentAccount:`이전에 사용하던 계정이 아닌 다른 계정으로 로그인되었습니다.
|
|
2
2
|
|
|
3
|
-
보안을 위해 동일한 Google/Apple 계정으로만 이어서 사용할 수 있습니다.`,sessionAlert_title:"세션 만료",sessionAlert_accountLabel:"계정",sessionAlert_signOutButton:"로그아웃",sessionAlert_signInAgainButton:"다시 로그인"},sr={confirm:"Confirm",cancel:"Cancel",close:"Close",signMessage_title:"Sign Message",signTypedData_title:"Sign Data",signTransaction_title:"Sign Transaction",sendTransaction_title:"Send Transaction",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",loginSelector_title:"Choose a sign-in method",loginSelector_google:"Continue with Google",loginSelector_apple:"Continue with Apple",loginSelector_connectOtherWallets:"Connect with Other Wallets",loginSelector_connectOtherWalletsDesc:"Connect your existing Web3 wallet to manage your assets.",migration_foundTitle:"Existing Wallet Found",migration_foundDescription:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recoverButton:"Recover",migration_skipButton:"Skip",recoveryPinInput_title:"Enter PIN",recoveryPinInput_placeholder:"Enter your 4-digit PIN",recoveryPinInput_error:"Incorrect PIN. Please try again.",walletSelector_title:"Select Wallet",walletSelector_addButton:"Add Wallet",walletSelector_selected:"Selected",pinNotice_headerSubtitle:"Required for transactions, PK/mnemonic export & account deletion.",pinNotice_title:"PIN Setup Notice",pinNotice_description:"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",pinNotice_check1:"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",pinNotice_check2:"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",pinNotice_nextButton:"Next",pinNotice_submitButton:"I Understand",pinSetup_title:"Create PIN",pinSetup_headerSubtitle:"This PIN is used to authorize your transactions.",pinSetup_subtitle:"Set a 6-digit PIN to authorize transactions.",pinSetup_confirmTitle:"Confirm PIN",pinSetup_confirmSubtitle:"Enter your PIN again to confirm.",pinSetup_mismatchError:"PINs do not match. Please try again.",pinValidation_tooShort:"Please enter a 6-digit PIN.",pinValidation_numbersOnly:"Only numbers (0-9) are allowed.",pinValidation_repeatingDigit:"Cannot use the same number 3+ times in a row.",pinValidation_sequential:"Sequential numbers (e.g., 123456) are not allowed.",pinValidation_alternatingPattern:"Repeating patterns (e.g., 121212) are not allowed.",pinInput_title:"Enter PIN",pinInput_subtitle:"Enter your 6-digit PIN to continue.",pinInput_error:"Incorrect PIN. Please try again.",verifyPin_title:"Verify Your PIN",verifyPin_subtitle:"To continue, please confirm your PIN.",pinLocked_message:"Please try again after the lock expires.",pinLocked_availableFrom:"Available from",pinLocked_failureWarning:"
|
|
3
|
+
보안을 위해 동일한 Google/Apple 계정으로만 이어서 사용할 수 있습니다.`,sessionAlert_title:"세션 만료",sessionAlert_accountLabel:"계정",sessionAlert_signOutButton:"로그아웃",sessionAlert_signInAgainButton:"다시 로그인"},sr={confirm:"Confirm",cancel:"Cancel",close:"Close",signMessage_title:"Sign Message",signTypedData_title:"Sign Data",signTransaction_title:"Sign Transaction",sendTransaction_title:"Send Transaction",tx_pending:"Processing transaction...",tx_success:"Transaction completed",tx_failed:"Transaction failed",tx_timeout:"Transaction confirmation timed out",loginSelector_title:"Choose a sign-in method",loginSelector_google:"Continue with Google",loginSelector_apple:"Continue with Apple",loginSelector_connectOtherWallets:"Connect with Other Wallets",loginSelector_connectOtherWalletsDesc:"Connect your existing Web3 wallet to manage your assets.",migration_foundTitle:"Existing Wallet Found",migration_foundDescription:"An existing CROSSx wallet was found. Would you like to recover it?",migration_recoverButton:"Recover",migration_skipButton:"Skip",recoveryPinInput_title:"Enter PIN",recoveryPinInput_placeholder:"Enter your 4-digit PIN",recoveryPinInput_error:"Incorrect PIN. Please try again.",walletSelector_title:"Select Wallet",walletSelector_addButton:"Add Wallet",walletSelector_selected:"Selected",pinNotice_headerSubtitle:"Required for transactions, PK/mnemonic export & account deletion.",pinNotice_title:"PIN Setup Notice",pinNotice_description:"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",pinNotice_check1:"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",pinNotice_check2:"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",pinNotice_nextButton:"Next",pinNotice_submitButton:"I Understand",pinSetup_title:"Create PIN",pinSetup_headerSubtitle:"This PIN is used to authorize your transactions.",pinSetup_subtitle:"Set a 6-digit PIN to authorize transactions.",pinSetup_confirmTitle:"Confirm PIN",pinSetup_confirmSubtitle:"Enter your PIN again to confirm.",pinSetup_mismatchError:"PINs do not match. Please try again.",pinValidation_tooShort:"Please enter a 6-digit PIN.",pinValidation_numbersOnly:"Only numbers (0-9) are allowed.",pinValidation_repeatingDigit:"Cannot use the same number 3+ times in a row.",pinValidation_sequential:"Sequential numbers (e.g., 123456) are not allowed.",pinValidation_alternatingPattern:"Repeating patterns (e.g., 121212) are not allowed.",pinInput_title:"Enter PIN",pinInput_subtitle:"Enter your 6-digit PIN to continue.",pinInput_error:"Incorrect PIN. Please try again.",verifyPin_title:"Verify Your PIN",verifyPin_subtitle:"To continue, please confirm your PIN.",pinLocked_message:"Please try again after the lock expires.",pinLocked_availableFrom:"Available from",pinLocked_failureWarning:"Your account will be locked after further failures.",pinLocked_permanent:"Your account has been permanently locked due to too many failed attempts.",alert_sessionExpired:"Your session has expired. Please sign in again.",alert_accountWithdrawn:"This account is no longer available or has been withdrawn. Please sign in again.",alert_walletNotFound:"Wallet data could not be found. Please sign in again.",alert_differentAccount:`You signed in with a different Google/Apple account than before.
|
|
4
4
|
|
|
5
|
-
For security, you must continue with the same account.`,sessionAlert_title:"Session expired",sessionAlert_accountLabel:"Account",sessionAlert_signOutButton:"Sign out",sessionAlert_signInAgainButton:"Sign in again"},Ks={ko:Fs,en:sr};function Se(s="en",e){return Ks[s]??sr}const nr="crossx_access_token",ir="crossx_refresh_token",or="crossx_user_info",wt=class wt{constructor(e,r,t,n,i,o,a){this.config=e,this.storage=r,this.crypto=t,this.oauth=n,this.transport=i,this.walletProvider=o,this.tokenStore=a,this._refreshPromise=null,this._migrated=!1;const c=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${c}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${c}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${c}_user_info`}get useCookieAuth(){return this.config.authMode==="cookie"}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const r=e==null?void 0:e.data;if(typeof r=="object"&&r!==null&&"code"in r){const t=r;if(t.code&&t.code!==200&&t.code>0)return{code:t.code,message:t.message??""}}return null}checkResponseError(e,r){const t=this.extractResponseErrorCode(e);if(t)throw new _(h.AUTH_FAILED,`${r} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let r,t;try{const n=e==null?void 0:e.provider;let i="/login";n==="google"?i="/google":n==="apple"&&(i="/apple");const{oauthServiceUrl:o}=this.config,a=`${o}${i}`;u.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`);const c=await this.oauth.openAuth({authUrl:a,expectedOrigin:new URL(o).origin});r=c.token,t=c.email,u.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",r.length,")"),t&&u.log("[CROSSx] OAuth 콜백 email:",t)}catch(n){u.error("[CROSSx] SignIn 에러 (OAuth 단계):",n);const i=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(i)?new _(h.OAUTH_POPUP_BLOCKED,i):new _(h.AUTH_FAILED,i)}return this.processFirebaseToken(r,t)}async executeWithOAuthToken(e){return u.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async processFirebaseToken(e,r){var i,o,a,c,l;let t,n=!1;try{const{authApiUrl:d}=this.config,{accessToken:f,refreshToken:g}=await this.exchangeFirebaseToken(e,d);let p,w,b;try{const I=this.crypto.decodeJWT(e);u.log("[CROSSx] Firebase JWT 필드:",Object.keys(I).join(", ")),w=(i=I.firebase)==null?void 0:i.sign_in_provider;const C=((o=I.firebase)==null?void 0:o.identities)??{};b=I.email??((a=C.email)==null?void 0:a[0]),w==="google.com"?p=(c=C["google.com"])==null?void 0:c[0]:w==="apple.com"&&(p=(l=C["apple.com"])==null?void 0:l[0]),u.log("[CROSSx] OAuth provider sub 추출 — provider:",w,"hasProviderSub:",!!p,"email:",b??"(없음)")}catch{u.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(f){const I=this.crypto.decodeJWT(f);u.log("[CROSSx] access_token 디코딩 — sub:",I.sub,"exp:",I.exp,"필드:",Object.keys(I).join(", "));const C=await this.crypto.verifyJWT(f);if(n=C.signatureVerified??!1,!C.valid)throw u.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const H=C.payload,D=H.email??b??r;u.log("[CROSSx] email 소스 — CROSSx JWT:",H.email??"(없음)","/ Firebase JWT:",b??"(없음)","/ OAuth 콜백:",r??"(없음)","→",D??"(없음)"),t={id:H.sub,email:D,signInProvider:w,providerSub:p},this.tokenStore.set(f),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,f),g&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,g):g&&u.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const I=this.crypto.decodeJWT(e);t={id:I.sub,email:I.email??r,signInProvider:w,providerSub:p},u.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}u.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const y=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,y),u.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(d){return u.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",d),{success:!1,error:d instanceof Error?d.message:"Sign in failed"}}return u.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,n)}async exchangeFirebaseToken(e,r){const t=this.useCookieAuth,n=t?`${r}/cross-auth/social/login/cookie`:`${r}/cross-auth/social/login`;u.log("[CROSSx] Firebase 토큰 교환 요청");const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});u.log("[CROSSx] 토큰 교환 응답 — status:",i.status);const o=i.data;this.checkResponseError(o,"Token exchange");const a=this.extractAccessToken(o);if(t&&!a)return u.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new _(h.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");u.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(o)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const r=(e==null?void 0:e.data)??e;if(this.isJwtString(r))return r;if(typeof r=="object"&&r!==null){const t=r;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.access_token??i.token;if(typeof o=="string")return o}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const r=(e==null?void 0:e.data)??e;if(typeof r!="object"||r===null)return;const t=r;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.refresh_token??i.refresh;if(typeof o=="string")return o}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return u.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){u.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),n=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(u.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),!n)return u.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const i=await this.silentRefresh(n);u.log("[CROSSx] restoreSession — silentRefresh 결과:",i?"토큰 발급 성공":"토큰 없음"),i&&this.tokenStore.set(i)}const r=await this.storage.get(this.STORAGE_KEY_USER);if(u.log("[CROSSx] restoreSession — userInfo 조회:",r?`있음 (id: ${r.id})`:"없음"),!r)return null;u.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",r.id);try{return await this.loadWallet(r,!1)}catch(t){return u.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:r,tokenSignatureVerified:!1}}}catch(e){const r=e instanceof _&&e.code===h.SESSION_EXPIRED;return u.log("[CROSSx] restoreSession —",r?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),r&&(this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER)),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:r}=this.config,t=this.useCookieAuth,n=`${r}/cross-auth/social/refresh/simple`,i={};if(!t){const d=this.tokenStore.get()??"";d&&(i.access_token=d),e&&(i.refresh_token=e)}const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:i,...t?{credentials:"include"}:{}});u.log("[CROSSx] silentRefresh 응답 — status:",o.status);const a=o.data,c=this.extractResponseErrorCode(a);if(c){const d=wt.REFRESH_RELOGIN_CODES.has(c.code);throw new _(d?h.SESSION_EXPIRED:h.AUTH_FAILED,`토큰 갱신 실패 (코드 ${c.code}): ${c.message}`)}const l=this.extractAccessToken(a);if(t&&!l){u.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!l)throw new _(h.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(l),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,l);const d=this.extractRefreshToken(a);d&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,d)}return u.log("[CROSSx] silentRefresh 성공"),l}async refreshAccessToken(){try{if(this.useCookieAuth)return!!await this.silentRefresh()||this.tokenStore.has();const e=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);return e?!!await this.silentRefresh(e):(u.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof _&&e.code===h.SESSION_EXPIRED?(u.warn("[CROSSx] refreshAccessToken: 세션 만료 — 재로그인 필요"),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)):u.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,r){let t,n=!1;try{let i=await this.crypto.verifyJWT(e);if(n=i.signatureVerified??!1,!i.valid){if(!r)return u.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};u.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(r);if(!a)return u.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,i=await this.crypto.verifyJWT(e),n=i.signatureVerified??!1,!i.valid)return u.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};u.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const o=i.payload;u.log("[CROSSx] signInWithJWT — sub:",o.sub,"signatureVerified:",n),t={id:o.sub,email:o.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),r&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,r)),await this.storage.set(this.STORAGE_KEY_USER,t),u.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(i){return u.error("[CROSSx] signInWithJWT 에러:",i),{success:!1,error:i instanceof Error?i.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(or);if(!e||await this.storage.get(this.STORAGE_KEY_USER))return;await this.storage.set(this.STORAGE_KEY_USER,e);const t=await this.storage.get(nr);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(ir);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(or),await this.storage.remove(nr),await this.storage.remove(ir),u.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){u.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,r){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){u.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const i=await this.walletProvider.checkWallet();if(u.log("[CROSSx] 지갑 상태:",i),i==="migration_required")u.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(i==="exists")try{const o=await this.walletProvider.getAddresses(e.id);o.length>0?(t=o[0].address,u.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):u.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(o){u.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",o)}}else u.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,u.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(i){if(i instanceof _&&i.code===h.MIGRATION_BACKUP_EXISTS)u.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(i instanceof _&&(i.code===h.PROJECT_NOT_REGISTERED||i.code===h.PROJECT_ID_MISSING||i.code===h.ORIGIN_NOT_ALLOWED))throw u.error("[CROSSx] 프로젝트 설정 에러:",i.message),i;u.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",i)}}return u.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:r}}};wt.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let St=wt;class Gs{constructor(e,r,t){this.config=e,this.storage=r,this.tokenStore=t;const n=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${n}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${n}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${n}_user_info`}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(this.STORAGE_KEY_ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)),await this.storage.remove(this.STORAGE_KEY_USER),await this.storage.clear()}}class qs{constructor(e,r){this.storage=e,this.walletProvider=r}async execute(e,r){if(!this.walletProvider.migrateWallet)throw new _(h.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");u.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",r);const t=await this.walletProvider.migrateWallet(e,r);return u.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class vt{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const r=new TextEncoder().encode(e),t=new Uint8Array(r.length);crypto.getRandomValues(t);const n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r[i]^t[i];r.fill(0),this.xorKey=t,this.encryptedBytes=n}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const r=new TextDecoder().decode(e);return e.fill(0),r}clear(){var e,r;(e=this.encryptedBytes)==null||e.fill(0),(r=this.xorKey)==null||r.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class Js{constructor(e,r){this.chainRegistry=e,this.transport=r,this._nextId=1}async call(e,r,t){const n=await this.chainRegistry.getChain(t),i={jsonrpc:"2.0",method:e,params:r,id:this._nextId++},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:i})).data;if(a!=null&&a.error)throw new _(h.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class Vs{constructor(){this.listeners=new Map}on(e,r){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),()=>this.off(e,r)}off(e,r){var t;(t=this.listeners.get(e))==null||t.delete(r)}emit(e,r){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(r))}removeAllListeners(){this.listeners.clear()}}var rt={environment:"production"};const We={production:{oauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1"},staging:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1"},development:{oauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1"}};function zs(s){const e=s.environment;return e&&e in We?We[e]:null}function Ys(){try{if(typeof rt<"u"){const s=typeof rt=="string"?JSON.parse(rt):rt,e=zs(s);if(e)return e}}catch{}try{const s=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(s&&s in We)return We[s]}catch{}return We.production}const js=2e3,ar=6e4,Xs=1e3,Zs=1e4,Qs="0x77359400",cr="0x3B9ACA00",lr=130,dr=6,ur=18,hr=3e4,en=5*60*1e3,tn=30*1e3;function ze(s){const e=s.indexOf("@");if(e<0)return"***";const r=s.substring(0,e),t=s.substring(e);return r.length<=1?`${r}***${t}`:`${r[0]}***${t}`}const se=class se extends Vs{constructor(e,r,t,n,i,o,a,c,l,d,f){var g,p;super(),this.storage=t,this.crypto=n,this.transport=i,this.oauth=o,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._verifyPinMutex=null,this._themeMediaCleanup=null,this._isRecoveringSession=!1,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=r,e.logger&&rr(e.logger),this.confirmation=l,this.pinStore=f??new vt,this.chainRegistry=d,this.jsonRpc=new Js(d,i),this.signInUseCase=new St(this.internalConfig,t,n,o,i,a,c),this.signOutUseCase=new Gs(this.internalConfig,t,c),this.migrateWalletUseCase=new qs(t,a),(g=a.setOnUnauthorized)==null||g.call(a,()=>this.forceLogout()),(p=a.setTokenRefresher)==null||p.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}get config(){return this._config}async initialize(e){return this.initialized?this.authenticated?{success:!0,address:this.address??void 0}:null:this._initPromise?this._initPromise:(this._initPromise=this._doInitialize(e).finally(()=>{this._initPromise=null}),this._initPromise)}async _doInitialize(e){var r,t;u.log("[CROSSx SDK] v1.4.2 초기화 중..."),this.confirmation.setMessages(Se(this._config.locale));try{const n=Ys();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(t=(r=this.crypto).setJWKSEndpoint)==null||t.call(r,`${n.authApiUrl}/.well-known/jwks.json`);const i=await this.signInUseCase.restoreSession();if(i!=null&&i.success){this.applyAuthResult(i);try{await this.loadWalletAfterAuth(e==null?void 0:e.preferredWalletIndex)}catch(o){if(!(o instanceof _&&o.code===h.PIN_CANCELLED))throw o;u.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,u.info("[CROSSx SDK] v1.4.2 초기화 완료"),this.emit("initialized",{restored:!!(i!=null&&i.success)}),i??null}catch(n){throw new _(h.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new _(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let r=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector({showConnectOtherWallets:this._config.showConnectOtherWallets});if(t==="external")throw this.emit("connectExternalWallet",{}),new _(h.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");if(t===null)return{success:!1,error:"User cancelled login"};r={...e,provider:t}}try{const t=await this.signInUseCase.execute(r);return t.success&&this.applyAuthResult(t),t}catch(t){throw t instanceof _?t:new _(h.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const r=await this.signIn(e);if(!r.success)return{...r,addresses:[]};try{if(r.needsMigration||!r.address){const{address:i}=await this.createWallet(),o=await this.getAddresses(),a=await this.selectWalletIfMultiple(o);return{...r,address:(a==null?void 0:a.address)??i,needsMigration:!1,addresses:o}}const t=await this.getAddresses(),n=await this.selectWalletIfMultiple(t);return{...r,address:(n==null?void 0:n.address)??r.address,addresses:t}}catch(t){throw t instanceof _&&t.code===h.PIN_CANCELLED&&(u.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(n=>u.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",n))),t}}async signInWithOAuthToken(e){if(this.ensureInitialized(),this.authenticated)throw new _(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const r=await this.signInUseCase.executeWithOAuthToken(e);return r.success&&this.applyAuthResult(r),r}catch(r){throw new _(h.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",r)}}async signInWithJWT(e,r){if(this.ensureInitialized(),this.authenticated)throw new _(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,r);return t.success&&this.applyAuthResult(t),t}catch(t){throw new _(h.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new _(h.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}async whenReady(){if(this.initialized)return!0;if(this._initPromise)try{return await this._initPromise,this.initialized}catch{return!1}return!1}get currentAddress(){return this.address}get currentUserId(){return this.userId}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this.signInUseCase.restoreSession();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth()}catch(r){r instanceof _&&r.code===h.PIN_CANCELLED||u.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",r)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const r=await this.migrateWalletUseCase.execute(e,this.userId);return this.address=r.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:r.address,index:0}),u.log("[CROSSx] migrateWallet 완료 — address:",r.address),r}catch(r){throw r instanceof _?r:new _(h.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",r)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:this.activeWalletIndex}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));return e.length===0&&this.address?[{address:this.address,index:0}]:e}async selectWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let r=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));r.length===0&&this.address&&(r=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(r,async()=>{await this.ensurePinForSigning();const n=r.length,o={address:(await this.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,n)))).address,index:n};return r.push(o),o},e);return t&&(this.address=t.address,this.activeWalletIndex=t.index,this.emit("addressChanged",{address:t.address,index:t.index})),t}async selectWalletIfMultiple(e){return e.length<2?null:this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof _?e:new _(h.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(r){throw r instanceof _?r:new _(h.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,r)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),r=n=>{const i=n?"dark":"light";this.applyTheme(i,this._config.themeTokens??{})};r(e.matches);const t=n=>r(n.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",r=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:r}),this.confirmation.setTheme(e,r)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(Se(e))}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");u.log("[CROSSx] createWallet 시작");const e=await this.fetchWalletStatus();if(u.log("[CROSSx] 지갑 상태:",e),e==="migration_required"){const r=this.providerSub??this.userId;u.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",r);const t=await this.handleMigrationFlow(r);if(t)return this.address=t.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:t.address,index:0}),{address:t.address};throw new _(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(e==="exists"){await this.ensureVerifiedPin();try{const r=await this.withPinRetry(()=>this.walletProvider.getOrCreateWallet(this.userId));return this.address=r.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:r.address,index:0}),u.log("[CROSSx] 지갑 준비 완료:",r.address),{address:r.address}}catch(r){if(r instanceof _&&r.code===h.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;u.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new _(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw r}}await this.ensurePinSetup();try{const r=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=r.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:r.address,index:0}),u.log("[CROSSx] 지갑 준비 완료:",r.address),{address:r.address}}catch(r){if(r instanceof _&&r.code===h.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;u.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new _(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw r}}async fetchWalletStatus(){if(typeof this.walletProvider.checkWallet=="function")try{return await this.walletProvider.checkWallet()}catch(e){return u.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async signMessage(e,r,t){return this.withSessionRecovery(()=>this._signMessage(e,r,t))}async _signMessage(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.resolveAddress(t==null?void 0:t.index);if(!await this.confirmation.requestConfirmation({type:"sign-message",chainId:e,from:n.address,message:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new _(h.USER_REJECTED,"User rejected the message signing request");try{const o=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-message",{message:r,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signMessage(this.userId,e,r,t==null?void 0:t.index,a,n.address)});return this.verifySignatureSigner(r,o.signature,n.address),{chainId:e,signature:o.signature,message:r,address:n.address}}catch(o){throw o instanceof _?o:new _(h.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,o)}}async signTypedData(e,r,t){return this.withSessionRecovery(()=>this._signTypedData(e,r,t))}async _signTypedData(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new _(h.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");se.validateTypedDataChainId(e,r);const n=await this.resolveAddress(t==null?void 0:t.index);if(!await this.confirmation.requestConfirmation({type:"sign-typed-data",chainId:e,from:n.address,typedData:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new _(h.USER_REJECTED,"User rejected the typed data signing request");try{const o=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-typed-data",{typedData:r,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTypedData(this.userId,e,r,t==null?void 0:t.index,a,n.address)});return se.validateSignatureFormat(o.signature),{chainId:e,signature:o.signature,address:n.address}}catch(o){throw o instanceof _?o:new _(h.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,o)}}async signTypedDataOffchain(e,r){return this.signTypedData(se.OFFCHAIN_CHAIN_ID,e,r)}async signTransaction(e,r,t){return this.withSessionRecovery(()=>this._signTransaction(e,r,t))}async _signTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=bt(e);if(!await this.confirmation.requestConfirmation({type:"sign",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new _(h.USER_REJECTED,"User rejected the transaction signing request");try{const a=await this.withPinRetry(async()=>{let c;return this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("sign",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c)});return se.validateSignedTxFormat(a.signature),{chainId:e,signedTx:a.signature,txHash:a.txHash??""}}catch(a){if(a instanceof _)throw a;const c=a instanceof Error?a.message:String(a);throw new _(h.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${c}`,a)}}async sendTransaction(e,r,t){return this.withSessionRecovery(()=>this._sendTransaction(e,r,t))}async _sendTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new _(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=bt(e);if(!await this.confirmation.requestConfirmation({type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new _(h.USER_REJECTED,"User rejected the transaction request");try{const a=await this.withPinRetry(async()=>{let c;if(this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("send",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,c)).txHash;const l=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c);return l.txHash??l.signature});return{chainId:e,txHash:a,status:"pending"}}catch(a){if(a instanceof _)throw a;const c=a instanceof Error?a.message:String(a);throw new _(h.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${c}`,a)}}async getTransactionReceipt(e,r){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],r)??null}catch{return null}}async waitForTxAndGetReceipt(e,r,t={}){const n=t.intervalMs??Xs,i=Zs,o=t.timeoutMs??ar,a=Date.now()+o;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,r);if(l)return l;await new Promise(d=>setTimeout(d,c)),c=Math.min(c*2,i)}throw new _(h.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,r,t={}){var b,y;const{intervalMs:n,timeoutMs:i,...o}=t,{txHash:a}=await this.sendTransaction(e,r,o),c=n??((b=this._config.receiptPolling)==null?void 0:b.intervalMs)??js,l=i??((y=this._config.receiptPolling)==null?void 0:y.timeoutMs)??ar,d=bt(e),f=r.from??"";let g,p;const w=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(I=>{g=I;const C=BigInt(I.gasUsed)*BigInt(I.effectiveGasPrice),H=r.value?BigInt(r.value):0n,D=se.formatTxAmount(r.value,d.symbol,d.decimals),q=se.formatTxAmount("0x"+C.toString(16),d.symbol,d.decimals),F=se.formatTxAmount("0x"+(H+C).toString(16),d.symbol,d.decimals);return{chainId:e,txHash:a,from:I.from,to:I.to??r.to,amount:D,fees:q,total:F,nativeSymbol:d.symbol,status:I.status==="0x1"?"success":"reverted"}}).catch(I=>(p=I instanceof Error?I:new Error(String(I)),{chainId:e,txHash:a,from:f,to:r.to,amount:se.formatTxAmount(r.value,d.symbol,d.decimals),nativeSymbol:d.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:f,to:r.to},w),p)throw p;return{chainId:e,txHash:a,receipt:g}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}async changePin(e,r){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new _(h.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,r),this.pinStore.set(r),u.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof _?n:new _(h.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",n)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new _(h.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,r)}}async estimateGas(e,r){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],r)}catch(n){const i=n instanceof Error?n.message:String(n);throw new _(h.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${r}): ${i}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const r=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(r==null?void 0:r.baseFeePerGas)??null}catch(r){const t=r instanceof Error?r.message:String(r);throw new _(h.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new _(h.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getNonce(e){this.ensureAuthenticated();const r=this.address;if(!r)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[r,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof _)throw t;const n=t instanceof Error?t.message:String(t);throw new _(h.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const r=this.address;if(!r)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[r,"latest"],e)??"0x0";return{wei:n,formatted:se.formatWei(n),chainId:e}}catch(t){if(t instanceof _)throw t;const n=t instanceof Error?t.message:String(t);throw new _(h.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}static formatWei(e){if(!e||e==="0x0"||e==="0x")return"0";try{const r=BigInt(e);if(r===0n)return"0";const t=10n**BigInt(ur),n=r/t,o=(r%t).toString().padStart(ur,"0").replace(/0+$/,"").slice(0,dr);return o?`${n}.${o}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new tr(this,e)}async walletRpc(e,r,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,r,t)}catch(n){if(n instanceof _)throw n;const i=n instanceof Error?n.message:String(n);throw new _(h.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${i}`,n)}}static formatTxAmount(e,r,t){if(!(!e||e==="0x"||e==="0x0"))try{const n=BigInt(e);if(n===0n)return;const i=10n**BigInt(t),o=n/i,c=(n%i).toString().padStart(t,"0").slice(0,dr).replace(/0+$/,"");return`${c?`${o}.${c}`:`${o}`} ${r}`}catch{return}}async handleMigrationFlow(e){var c,l,d;u.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const r=((c=this._config.migration)==null?void 0:c.allowSkip)??!0,t=await this.confirmation.showMigrationFoundPrompt({allowSkip:r});if(u.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return u.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,i=0,o=5,a=null;for(;;){i++,u.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${i}/${o})`,n?`— 이전 메시지: ${n}`:"");const f=await this.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:i>1?i-1:void 0,maxAttempts:o});if(f===null)return u.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;u.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),n=void 0;try{const g=await((d=(l=this.walletProvider).verifyRecoveryPin)==null?void 0:d.call(l,f,e));if(!g){u.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=f;break}if(g.valid){u.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=f;break}const p=g.pinStatus;if(o=p.maxAttempts,i=o-p.remainingAttempts,p.remainingAttempts===0&&p.lockExpiresAt){const w=p.lockExpiresAt*1e3,b=Math.max(1,Math.round((w-Date.now())/1e3)),y=b<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";u.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${b}초, 메시지: ${y}`),await this.confirmation.showRecoveryPinLockedPrompt(b,y),i=0,n="Your account lock has been lifted. You may try again."}else u.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${i}/${o})`),n="Incorrect PIN."}catch(g){if(!(g instanceof _))throw g;if(g.code===h.SESSION_EXPIRED){u.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const p=Se(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:p.sessionAlert_title,message:p.alert_sessionExpired,email:this.userEmail?ze(this.userEmail):void 0})==="signin-again"&&(await this.signInAgain()).success){u.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),i--;continue}throw this.clearAuthState(),g}if(g.code===h.MIGRATION_PIN_LOCKED){const p=g.details;if(o=(p==null?void 0:p.maxAttempts)??5,(p==null?void 0:p.permanent)===!0)return u.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const w=((p==null?void 0:p.lockExpiresAt)??0)*1e3,b=Math.max(1,Math.round((w-Date.now())/1e3)),y=b<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";u.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${b}초`),await this.confirmation.showRecoveryPinLockedPrompt(b,y),i=0,n="Your account lock has been lifted. You may try again."}else throw u.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",g),g}}u.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.ensurePinSetup();const f=await this.migrateWalletUseCase.execute(a,e);return u.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",f.address),f}catch(f){if(f instanceof _&&f.code===h.MIGRATION_FAILED)return u.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(f instanceof _&&f.code===h.SESSION_EXPIRED){u.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const g=Se(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:g.sessionAlert_title,message:g.alert_sessionExpired,email:this.userEmail?ze(this.userEmail):void 0})==="signin-again"&&(await this.signInAgain()).success){u.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const b=await this.migrateWalletUseCase.execute(a,e);return u.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",b.address),b}catch(b){throw u.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",b),b}}throw this.clearAuthState(),f}throw u.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",f),f}}async withResolvedGasAndFee(e,r){const t=p=>!(p!=null&&p.trim()),n=e.nonce===void 0||e.nonce===null,i=t(e.gasLimit),o=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!i&&!o&&!a)return e;const c={...e},l=n?c.from??this.address:void 0;l&&u.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),i&&u.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),o&&u.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[d,f,g]=await Promise.all([l?this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],r):null,i?this.estimateGas(e,r):null,o?this.getBaseFeePerGas(r):null]);if(l&&(c.nonce=parseInt(d??"0x0",16),u.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=f,u.log("[CROSSx] estimateGas 결과:",c.gasLimit)),o){const p=g;if(p){const w=cr;c.maxFeePerGas="0x"+(BigInt(p)+BigInt(w)).toString(16),c.maxPriorityFeePerGas=w,u.log("[CROSSx] Dynamic 체인 감지 — baseFee:",p,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=Qs,u.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(c.maxPriorityFeePerGas=cr,u.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}static validateTypedDataChainId(e,r){const t=se.extractDomainChainId(r);if(e==="0"){if(t!==void 0&&t!==0)throw new _(h.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${t}`);return}const n=e.match(/^eip155:(\d+)$/);if(n){const i=Number(n[1]);if(t===void 0)throw new _(h.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${e})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==i)throw new _(h.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t})가 chainId (${e}, 예상값: ${i})와 일치하지 않습니다`)}}static extractDomainChainId(e){if(e==null||typeof e!="object")return;const r=e.domain;if(r==null||typeof r!="object")return;const t=r.chainId;if(t==null)return;const n=Number(t);return Number.isFinite(n)?n:void 0}static validateSignatureFormat(e){const r=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(r))throw new _(h.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(r.length!==lr)throw new _(h.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${lr} hex 문자(65 바이트) 예상, 현재 ${r.length}`)}static validateSignedTxFormat(e){const r=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(r))throw new _(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(r.length<2)throw new _(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}verifySignatureSigner(e,r,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,r);if(n.toLowerCase()!==t.toLowerCase())throw u.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new _(h.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);u.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof _)throw n;u.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}applyAuthResult(e){var r,t,n,i;this.authenticated=e.success,this.userId=((r=e.user)==null?void 0:r.id)??null,this.address=e.address??null,this.activeWalletIndex=0,this.userEmail=((t=e.user)==null?void 0:t.email)??null,this.providerSub=((n=e.user)==null?void 0:n.providerSub)??null,this.loginType=se.normalizeLoginType((i=e.user)==null?void 0:i.signInProvider),this.tokenSignatureVerified=e.tokenSignatureVerified??!1,this._isRecoveringSession||this.emit("authChanged",{isAuthenticated:this.authenticated,address:this.address,userId:this.userId})}clearAuthState(){this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.providerSub=null,this.loginType=null,this.tokenSignatureVerified=!1,this.pinStore.clear(),this._isRecoveringSession||this.emit("authChanged",{isAuthenticated:!1,address:null,userId:null})}forceLogout(){this.authenticated&&(u.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){var n,i;this.ensureInitialized();const e=this.providerSub,r=this.userId,t=this.loginType;this._isRecoveringSession=!0;try{this.authenticated=!1,this.tokenStore.clear();const o=t?{provider:t}:void 0;let a;try{a=await this.signInUseCase.execute(o)}catch(f){throw this.clearAuthState(),f}if(!a.success)return this.clearAuthState(),a;const c=((n=a.user)==null?void 0:n.providerSub)??null,l=((i=a.user)==null?void 0:i.id)??null;if(!(e?!!c&&c===e:r?!!l&&r===l:!0)){u.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.signOutUseCase.execute().catch(()=>{});const f=Se(this._config.locale??"en");return await this.confirmation.showSessionAlert({title:f.sessionAlert_title,message:f.alert_differentAccount,email:this.userEmail?ze(this.userEmail):void 0})==="signin-again"?(this._isRecoveringSession=!1,this.signInAgain()):(this.clearAuthState(),{success:!1,error:"Different account signed in"})}this.applyAuthResult(a);try{await this.loadWalletAfterAuth()}catch{u.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return u.log("[CROSSx] signInAgain: 세션 복구 성공"),a}finally{this._isRecoveringSession=!1}}async withSessionRecovery(e){try{return await e()}catch(r){const t=Se(this._config.locale??"en"),n=this.userEmail?ze(this.userEmail):void 0;if(r instanceof _&&r.code===h.WITHDRAW_FAILED){if(u.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.confirmation.showSessionAlert({title:t.sessionAlert_title,message:t.alert_accountWithdrawn,email:n})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.clearAuthState(),r}if(r instanceof _&&r.code===h.WALLET_NOT_FOUND){if(u.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.confirmation.showSessionAlert({title:t.sessionAlert_title,message:t.alert_walletNotFound,email:n})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.clearAuthState(),r}if(!(r instanceof _)||r.code!==h.SESSION_EXPIRED)throw r;if(u.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.confirmation.showSessionAlert({title:t.sessionAlert_title,message:t.alert_sessionExpired,email:n})==="signout")throw this.clearAuthState(),new _(h.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const o=await this.signInAgain();if(!o.success)throw new _(h.SESSION_EXPIRED,o.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}static normalizeLoginType(e){return e?e.includes("google")?"google":e.includes("apple")?"apple":e:null}async ensurePinSetup(){if(this.pinStore.has())return;const e=await this.confirmation.showPinSetupPrompt();if(!e)throw new _(h.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.pinStore.set(e),u.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){if(this.pinStore.has()&&!e)return;e&&this.pinStore.clear();const r=await this.confirmation.showPinInputPrompt({errorMessage:e});if(!r)throw new _(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(r),u.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,r,t,n){if(e)this.pinStore.clear();else if(this.pinStore.has())return;if(this._verifyPinMutex&&!e){u.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this._verifyPinMutex;return}let i,o;this._verifyPinMutex=new Promise((c,l)=>{i=c,o=l});const a=Se(this._config.locale??"en");try{if(typeof this.walletProvider.verifyPin!="function"){const l=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n});if(!l)throw new _(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(l),u.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),i();return}const c=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n,onSubmit:async l=>{this.pinStore.set(l);try{return await this.walletProvider.verifyPin(l)?(u.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.pinStore.clear(),{ok:!1,error:a.pinInput_error})}catch(d){if(this.pinStore.clear(),d instanceof _){if(d.code===h.PIN_WRONG)return{ok:!1,error:a.pinInput_error};if(d.code===h.PIN_INVALID)return{ok:!1,error:d.message};if(d.code===h.PIN_LOCKED)return se.buildPinLockedResult(d,a)}throw d}}});if(!c)throw new _(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(c),u.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(c){if(c instanceof _&&(c.code===h.AUTH_NOT_AUTHENTICATED||c.code===h.AUTH_TOKEN_EXPIRED||c.code===h.SESSION_EXPIRED)&&c.code!==h.SESSION_EXPIRED){const l=Se(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:l.sessionAlert_title,message:l.alert_sessionExpired,email:this.userEmail?ze(this.userEmail):void 0})==="signin-again"&&(await this.signInAgain()).success)throw o(c),c}throw o(c),c}finally{this._verifyPinMutex=null}}static buildPinLockedResult(e,r){const t=e.details;if(t!=null&&t.permanent)return{ok:!1,error:r.pinLocked_permanent};if((t==null?void 0:t.remainingAttempts)!=null&&t.remainingAttempts>0&&t.maxAttempts){const n=t.maxAttempts-t.remainingAttempts;return{ok:!1,error:r.pinLocked_failureWarning,attemptCount:n,maxAttempts:t.maxAttempts}}return{ok:!1,error:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:t==null?void 0:t.lockExpiresAt}}async loadWalletAfterAuth(e){if(!this.userId)return;const r=await this.fetchWalletStatus();if(u.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",r),r!=="exists")return;const t=await this.walletProvider.getAddresses(this.userId);if(t.length>0){const i=e!==void 0?t.find(o=>o.index===e)??t[0]:t[0];this.address=i.address,this.activeWalletIndex=i.index,u.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",this.address),this.emit("addressChanged",{address:i.address,index:i.index});return}u.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.ensureVerifiedPin();const n=await this.walletProvider.getAddress(this.userId,0);this.address=n.address,this.activeWalletIndex=0,u.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",this.address),this.emit("addressChanged",{address:n.address,index:0})}async withPinRetry(e){const r=Se(this._config.locale??"en");let t,n,i,o;const a=c=>{if(c.code===h.PIN_WRONG)return t=r.pinInput_error,n=void 0,i=void 0,o=void 0,!0;if(c.code===h.PIN_INVALID)return t=c.message,n=void 0,i=void 0,o=void 0,!0;if(c.code===h.PIN_LOCKED){const l=c.details;return l!=null&&l.permanent?(t=r.pinLocked_permanent,n=void 0,i=void 0,o=void 0):(l==null?void 0:l.remainingAttempts)!=null&&l.remainingAttempts>0&&l.maxAttempts?(t=r.pinLocked_failureWarning,n=void 0,i=l.maxAttempts-l.remainingAttempts,o=l.maxAttempts):(t="Too many failed attempts. Your account is temporarily locked.",n=l==null?void 0:l.lockExpiresAt,i=void 0,o=void 0),!0}return!1};try{return await e()}catch(c){if(!(c instanceof _&&a(c)))throw c}for(;;){u.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t),this.pinStore.clear(),await this.ensureVerifiedPin(t,n,i,o),n=void 0,i=void 0,o=void 0;try{return await e()}catch(c){if(c instanceof _&&a(c))continue;throw c}}}async resolveAddress(e){if(e===void 0||e===this.activeWalletIndex){if(!this.address)throw new _(h.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:this.address,index:this.activeWalletIndex}}return{address:(await this.withPinRetry(()=>this.walletProvider.getAddress(this.userId,e))).address,index:e}}ensureInitialized(){if(!this.initialized)throw new _(h.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new _(h.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()을 먼저 호출하세요.")}dispose(){var e;(e=this._themeMediaCleanup)==null||e.call(this),this._themeMediaCleanup=null,this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),rr(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};se.OFFCHAIN_CHAIN_ID="0";let st=se;class rn{constructor(){this.prefix="crossx_"}async set(e,r){try{const t=JSON.stringify(r);localStorage.setItem(this.prefix+e,t)}catch(t){throw u.error("Storage set error:",t),t}}async get(e){try{const r=localStorage.getItem(this.prefix+e);return r?JSON.parse(r):null}catch(r){return u.error("Storage get error:",r),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(r){throw u.error("Storage remove error:",r),r}}async clear(){try{Object.keys(localStorage).forEach(r=>{r.startsWith(this.prefix)&&localStorage.removeItem(r)})}catch(e){throw u.error("Storage clear error:",e),e}}}const Et="crossx-sdk",sn=1,ge="data",Ne="keys",nt="aes-primary",nn=12;class fr{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(e=this.dbName){return new Promise((r,t)=>{const n=indexedDB.open(e,sn);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(ge)||i.createObjectStore(ge),i.objectStoreNames.contains(Ne)||i.createObjectStore(Ne)},n.onsuccess=()=>r(n.result),n.onerror=()=>t(n.error)})}idbGet(e,r){return new Promise((t,n)=>{const o=this.db.transaction(e,"readonly").objectStore(e).get(r);o.onsuccess=()=>t(o.result),o.onerror=()=>n(o.error)})}idbPut(e,r,t){return new Promise((n,i)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,r);a.onsuccess=()=>n(),a.onerror=()=>i(a.error)})}idbDelete(e,r){return new Promise((t,n)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).delete(r);o.onsuccess=()=>t(),o.onerror=()=>n(o.error)})}idbClear(e){return new Promise((r,t)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).clear();i.onsuccess=()=>r(),i.onerror=()=>t(i.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Ne,nt);if(e){this.cryptoKey=e;return}const r=await this.migrateFromLegacyDB();if(r){this.cryptoKey=r;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Ne,nt,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===Et)return null;try{const e=await this.openDB(Et),r=e.transaction([Ne,ge],"readonly"),t=r.objectStore(Ne).get(nt),n=await new Promise((l,d)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>d(t.error)});if(!n)return e.close(),null;const i=r.objectStore(ge).getAll(),o=r.objectStore(ge).getAllKeys(),[a,c]=await Promise.all([new Promise((l,d)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>d(i.error)}),new Promise((l,d)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>d(o.error)})]);e.close(),await this.idbPut(Ne,nt,n);for(let l=0;l<c.length;l++)await this.idbPut(ge,String(c[l]),a[l]);return indexedDB.deleteDatabase(Et),u.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return u.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const r=new Uint8Array(nn);crypto.getRandomValues(r);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},this.cryptoKey,t);return{iv:r,ciphertext:n}}async decrypt(e){const r=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,r){try{await this.ensureReady();const t=JSON.stringify(r),n=await this.encrypt(t);await this.idbPut(ge,e,n)}catch(t){throw u.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const r=await this.idbGet(ge,e);if(!r)return null;const t=await this.decrypt(r);return JSON.parse(t)}catch(r){return u.error("[CROSSx] IndexedDB get error:",r),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(ge,e)}catch(r){throw u.error("[CROSSx] IndexedDB remove error:",r),r}}async clear(){try{await this.ensureReady(),await this.idbClear(ge)}catch(e){throw u.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}const It=crypto,pr=s=>s instanceof CryptoKey,it=new TextEncoder,Ye=new TextDecoder;function on(...s){const e=s.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(e);let t=0;for(const n of s)r.set(n,t),t+=n.length;return r}const an=s=>{const e=atob(s),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r},Re=s=>{let e=s;e instanceof Uint8Array&&(e=Ye.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return an(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class Z extends Error{constructor(e,r){var t;super(e,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}}Z.code="ERR_JOSE_GENERIC";class he extends Z{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=n,this.payload=r}}he.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class At extends Z{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=n,this.payload=r}}At.code="ERR_JWT_EXPIRED";class _r extends Z{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}_r.code="ERR_JOSE_ALG_NOT_ALLOWED";class xe extends Z{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}xe.code="ERR_JOSE_NOT_SUPPORTED";class cn extends Z{constructor(e="decryption operation failed",r){super(e,r),this.code="ERR_JWE_DECRYPTION_FAILED"}}cn.code="ERR_JWE_DECRYPTION_FAILED";class ln extends Z{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}ln.code="ERR_JWE_INVALID";class Y extends Z{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}Y.code="ERR_JWS_INVALID";class me extends Z{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}me.code="ERR_JWT_INVALID";class dn extends Z{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}dn.code="ERR_JWK_INVALID";class Tt extends Z{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}Tt.code="ERR_JWKS_INVALID";class Rt extends Z{constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Rt.code="ERR_JWKS_NO_MATCHING_KEY";class gr extends Z{constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}gr.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class xr extends Z{constructor(e="request timed out",r){super(e,r),this.code="ERR_JWKS_TIMEOUT"}}xr.code="ERR_JWKS_TIMEOUT";class mr extends Z{constructor(e="signature verification failed",r){super(e,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}mr.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function we(s,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${s}`)}function je(s,e){return s.name===e}function Ot(s){return parseInt(s.name.slice(4),10)}function un(s){switch(s){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function hn(s,e){if(e.length&&!e.some(r=>s.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const t=e.pop();r+=`one of ${e.join(", ")}, or ${t}.`}else e.length===2?r+=`one of ${e[0]} or ${e[1]}.`:r+=`${e[0]}.`;throw new TypeError(r)}}function fn(s,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!je(s.algorithm,"HMAC"))throw we("HMAC");const t=parseInt(e.slice(2),10);if(Ot(s.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!je(s.algorithm,"RSASSA-PKCS1-v1_5"))throw we("RSASSA-PKCS1-v1_5");const t=parseInt(e.slice(2),10);if(Ot(s.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!je(s.algorithm,"RSA-PSS"))throw we("RSA-PSS");const t=parseInt(e.slice(2),10);if(Ot(s.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"EdDSA":{if(s.algorithm.name!=="Ed25519"&&s.algorithm.name!=="Ed448")throw we("Ed25519 or Ed448");break}case"Ed25519":{if(!je(s.algorithm,"Ed25519"))throw we("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!je(s.algorithm,"ECDSA"))throw we("ECDSA");const t=un(e);if(s.algorithm.namedCurve!==t)throw we(t,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}hn(s,r)}function wr(s,e,...r){var t;if(r=r.filter(Boolean),r.length>2){const n=r.pop();s+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?s+=`one of type ${r[0]} or ${r[1]}.`:s+=`of type ${r[0]}.`;return e==null?s+=` Received ${e}`:typeof e=="function"&&e.name?s+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(t=e.constructor)!=null&&t.name&&(s+=` Received an instance of ${e.constructor.name}`),s}const yr=(s,...e)=>wr("Key must be ",s,...e);function br(s,e,...r){return wr(`Key for the ${s} algorithm must be `,e,...r)}const Sr=s=>pr(s)?!0:(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",ot=["CryptoKey"],pn=(...s)=>{const e=s.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(const t of e){const n=Object.keys(t);if(!r||r.size===0){r=new Set(n);continue}for(const i of n){if(r.has(i))return!1;r.add(i)}}return!0};function _n(s){return typeof s=="object"&&s!==null}function ve(s){if(!_n(s)||Object.prototype.toString.call(s)!=="[object Object]")return!1;if(Object.getPrototypeOf(s)===null)return!0;let e=s;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(s)===e}const gn=(s,e)=>{if(s.startsWith("RS")||s.startsWith("PS")){const{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${s} requires key modulusLength to be 2048 bits or larger`)}};function Ue(s){return ve(s)&&typeof s.kty=="string"}function xn(s){return s.kty!=="oct"&&typeof s.d=="string"}function mn(s){return s.kty!=="oct"&&typeof s.d>"u"}function wn(s){return Ue(s)&&s.kty==="oct"&&typeof s.k=="string"}function yn(s){let e,r;switch(s.kty){case"RSA":{switch(s.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(s.alg.slice(-3),10)||1}`},r=s.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new xe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(s.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=s.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=s.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new xe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(s.alg){case"Ed25519":e={name:"Ed25519"},r=s.d?["sign"]:["verify"];break;case"EdDSA":e={name:s.crv},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new xe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new xe('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}const vr=async s=>{if(!s.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:r}=yn(s),t=[e,s.ext??!1,s.key_ops??r],n={...s};return delete n.alg,delete n.use,It.subtle.importKey("jwk",n,...t)},Er=s=>Re(s);let He,Be;const Ir=s=>(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",at=async(s,e,r,t,n=!1)=>{let i=s.get(e);if(i!=null&&i[t])return i[t];const o=await vr({...r,alg:t});return n&&Object.freeze(e),i?i[t]=o:s.set(e,{[t]:o}),o},bn={normalizePublicKey:(s,e)=>{if(Ir(s)){let r=s.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?Er(r.k):(Be||(Be=new WeakMap),at(Be,s,r,e))}return Ue(s)?s.k?Re(s.k):(Be||(Be=new WeakMap),at(Be,s,s,e,!0)):s},normalizePrivateKey:(s,e)=>{if(Ir(s)){let r=s.export({format:"jwk"});return r.k?Er(r.k):(He||(He=new WeakMap),at(He,s,r,e))}return Ue(s)?s.k?Re(s.k):(He||(He=new WeakMap),at(He,s,s,e,!0)):s}};async function Ar(s,e){if(!ve(s))throw new TypeError("JWK must be an object");switch(e||(e=s.alg),s.kty){case"oct":if(typeof s.k!="string"||!s.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Re(s.k);case"RSA":if("oth"in s&&s.oth!==void 0)throw new xe('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return vr({...s,alg:e});default:throw new xe('Unsupported "kty" (Key Type) Parameter value')}}const Fe=s=>s==null?void 0:s[Symbol.toStringTag],Pt=(s,e,r)=>{var t,n;if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&((n=(t=e.key_ops).includes)==null?void 0:n.call(t,r))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(e.alg!==void 0&&e.alg!==s)throw new TypeError(`Invalid key for this operation, when present its alg must be ${s}`);return!0},Sn=(s,e,r,t)=>{if(!(e instanceof Uint8Array)){if(t&&Ue(e)){if(wn(e)&&Pt(s,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Sr(e))throw new TypeError(br(s,e,...ot,"Uint8Array",t?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${Fe(e)} instances for symmetric algorithms must be of type "secret"`)}},vn=(s,e,r,t)=>{if(t&&Ue(e))switch(r){case"sign":if(xn(e)&&Pt(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(mn(e)&&Pt(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Sr(e))throw new TypeError(br(s,e,...ot,t?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${Fe(e)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${Fe(e)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${Fe(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${Fe(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${Fe(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function Tr(s,e,r,t){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Sn(e,r,t,s):vn(e,r,t,s)}Tr.bind(void 0,!1);const Rr=Tr.bind(void 0,!0);function En(s,e,r,t,n){if(n.crit!==void 0&&(t==null?void 0:t.crit)===void 0)throw new s('"crit" (Critical) Header Parameter MUST be integrity protected');if(!t||t.crit===void 0)return new Set;if(!Array.isArray(t.crit)||t.crit.length===0||t.crit.some(o=>typeof o!="string"||o.length===0))throw new s('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...e.entries()]):i=e;for(const o of t.crit){if(!i.has(o))throw new xe(`Extension Header Parameter "${o}" is not recognized`);if(n[o]===void 0)throw new s(`Extension Header Parameter "${o}" is missing`);if(i.get(o)&&t[o]===void 0)throw new s(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(t.crit)}const In=(s,e)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${s}" option must be an array of strings`);if(e)return new Set(e)};function An(s,e){const r=`SHA-${s.slice(-3)}`;switch(s){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:s.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new xe(`alg ${s} is not supported either by JOSE or your javascript runtime`)}}async function Tn(s,e,r){if(e=await bn.normalizePublicKey(e,s),pr(e))return fn(e,s,r),e;if(e instanceof Uint8Array){if(!s.startsWith("HS"))throw new TypeError(yr(e,...ot));return It.subtle.importKey("raw",e,{hash:`SHA-${s.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(yr(e,...ot,"Uint8Array","JSON Web Key"))}const Rn=async(s,e,r,t)=>{const n=await Tn(s,e,"verify");gn(s,n);const i=An(s,n.algorithm);try{return await It.subtle.verify(i,n,r,t)}catch{return!1}};async function On(s,e,r){if(!ve(s))throw new Y("Flattened JWS must be an object");if(s.protected===void 0&&s.header===void 0)throw new Y('Flattened JWS must have either of the "protected" or "header" members');if(s.protected!==void 0&&typeof s.protected!="string")throw new Y("JWS Protected Header incorrect type");if(s.payload===void 0)throw new Y("JWS Payload missing");if(typeof s.signature!="string")throw new Y("JWS Signature missing or incorrect type");if(s.header!==void 0&&!ve(s.header))throw new Y("JWS Unprotected Header incorrect type");let t={};if(s.protected)try{const b=Re(s.protected);t=JSON.parse(Ye.decode(b))}catch{throw new Y("JWS Protected Header is invalid")}if(!pn(t,s.header))throw new Y("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...t,...s.header},i=En(Y,new Map([["b64",!0]]),r==null?void 0:r.crit,t,n);let o=!0;if(i.has("b64")&&(o=t.b64,typeof o!="boolean"))throw new Y('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=n;if(typeof a!="string"||!a)throw new Y('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=r&&In("algorithms",r.algorithms);if(c&&!c.has(a))throw new _r('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof s.payload!="string")throw new Y("JWS Payload must be a string")}else if(typeof s.payload!="string"&&!(s.payload instanceof Uint8Array))throw new Y("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"?(e=await e(t,s),l=!0,Rr(a,e,"verify"),Ue(e)&&(e=await Ar(e,a))):Rr(a,e,"verify");const d=on(it.encode(s.protected??""),it.encode("."),typeof s.payload=="string"?it.encode(s.payload):s.payload);let f;try{f=Re(s.signature)}catch{throw new Y("Failed to base64url decode the signature")}if(!await Rn(a,e,f,d))throw new mr;let p;if(o)try{p=Re(s.payload)}catch{throw new Y("Failed to base64url decode the payload")}else typeof s.payload=="string"?p=it.encode(s.payload):p=s.payload;const w={payload:p};return s.protected!==void 0&&(w.protectedHeader=t),s.header!==void 0&&(w.unprotectedHeader=s.header),l?{...w,key:e}:w}async function Pn(s,e,r){if(s instanceof Uint8Array&&(s=Ye.decode(s)),typeof s!="string")throw new Y("Compact JWS must be a string or Uint8Array");const{0:t,1:n,2:i,length:o}=s.split(".");if(o!==3)throw new Y("Invalid Compact JWS");const a=await On({payload:n,protected:t,signature:i},e,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const Cn=s=>Math.floor(s.getTime()/1e3),Or=60,Pr=Or*60,Ct=Pr*24,kn=Ct*7,Nn=Ct*365.25,Ln=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Cr=s=>{const e=Ln.exec(s);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const r=parseFloat(e[2]),t=e[3].toLowerCase();let n;switch(t){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*Or);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*Pr);break;case"day":case"days":case"d":n=Math.round(r*Ct);break;case"week":case"weeks":case"w":n=Math.round(r*kn);break;default:n=Math.round(r*Nn);break}return e[1]==="-"||e[4]==="ago"?-n:n},kr=s=>s.toLowerCase().replace(/^application\//,""),Dn=(s,e)=>typeof s=="string"?e.includes(s):Array.isArray(s)?e.some(Set.prototype.has.bind(new Set(s))):!1,Mn=(s,e,r={})=>{let t;try{t=JSON.parse(Ye.decode(e))}catch{}if(!ve(t))throw new me("JWT Claims Set must be a top-level JSON object");const{typ:n}=r;if(n&&(typeof s.typ!="string"||kr(s.typ)!==kr(n)))throw new he('unexpected "typ" JWT header value',t,"typ","check_failed");const{requiredClaims:i=[],issuer:o,subject:a,audience:c,maxTokenAge:l}=r,d=[...i];l!==void 0&&d.push("iat"),c!==void 0&&d.push("aud"),a!==void 0&&d.push("sub"),o!==void 0&&d.push("iss");for(const w of new Set(d.reverse()))if(!(w in t))throw new he(`missing required "${w}" claim`,t,w,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(t.iss))throw new he('unexpected "iss" claim value',t,"iss","check_failed");if(a&&t.sub!==a)throw new he('unexpected "sub" claim value',t,"sub","check_failed");if(c&&!Dn(t.aud,typeof c=="string"?[c]:c))throw new he('unexpected "aud" claim value',t,"aud","check_failed");let f;switch(typeof r.clockTolerance){case"string":f=Cr(r.clockTolerance);break;case"number":f=r.clockTolerance;break;case"undefined":f=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:g}=r,p=Cn(g||new Date);if((t.iat!==void 0||l)&&typeof t.iat!="number")throw new he('"iat" claim must be a number',t,"iat","invalid");if(t.nbf!==void 0){if(typeof t.nbf!="number")throw new he('"nbf" claim must be a number',t,"nbf","invalid");if(t.nbf>p+f)throw new he('"nbf" claim timestamp check failed',t,"nbf","check_failed")}if(t.exp!==void 0){if(typeof t.exp!="number")throw new he('"exp" claim must be a number',t,"exp","invalid");if(t.exp<=p-f)throw new At('"exp" claim timestamp check failed',t,"exp","check_failed")}if(l){const w=p-t.iat,b=typeof l=="number"?l:Cr(l);if(w-f>b)throw new At('"iat" claim timestamp check failed (too far in the past)',t,"iat","check_failed");if(w<0-f)throw new he('"iat" claim timestamp check failed (it should be in the past)',t,"iat","check_failed")}return t};async function $n(s,e,r){var o;const t=await Pn(s,e,r);if((o=t.protectedHeader.crit)!=null&&o.includes("b64")&&t.protectedHeader.b64===!1)throw new me("JWTs MUST NOT use unencoded payload");const i={payload:Mn(t.protectedHeader,t.payload,r),protectedHeader:t.protectedHeader};return typeof e=="function"?{...i,key:t.key}:i}function Wn(s){switch(typeof s=="string"&&s.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new xe('Unsupported "alg" value for a JSON Web Key Set')}}function Un(s){return s&&typeof s=="object"&&Array.isArray(s.keys)&&s.keys.every(Hn)}function Hn(s){return ve(s)}function Nr(s){return typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}class Bn{constructor(e){if(this._cached=new WeakMap,!Un(e))throw new Tt("JSON Web Key Set malformed");this._jwks=Nr(e)}async getKey(e,r){const{alg:t,kid:n}={...e,...r==null?void 0:r.header},i=Wn(t),o=this._jwks.keys.filter(l=>{let d=i===l.kty;if(d&&typeof n=="string"&&(d=n===l.kid),d&&typeof l.alg=="string"&&(d=t===l.alg),d&&typeof l.use=="string"&&(d=l.use==="sig"),d&&Array.isArray(l.key_ops)&&(d=l.key_ops.includes("verify")),d)switch(t){case"ES256":d=l.crv==="P-256";break;case"ES256K":d=l.crv==="secp256k1";break;case"ES384":d=l.crv==="P-384";break;case"ES512":d=l.crv==="P-521";break;case"Ed25519":d=l.crv==="Ed25519";break;case"EdDSA":d=l.crv==="Ed25519"||l.crv==="Ed448";break}return d}),{0:a,length:c}=o;if(c===0)throw new Rt;if(c!==1){const l=new gr,{_cached:d}=this;throw l[Symbol.asyncIterator]=async function*(){for(const f of o)try{yield await Lr(d,f,t)}catch{}},l}return Lr(this._cached,a,t)}}async function Lr(s,e,r){const t=s.get(e)||s.set(e,{}).get(e);if(t[r]===void 0){const n=await Ar({...e,ext:!0},r);if(n instanceof Uint8Array||n.type!=="public")throw new Tt("JSON Web Key Set members must be public keys");t[r]=n}return t[r]}function Dr(s){const e=new Bn(s),r=async(t,n)=>e.getKey(t,n);return Object.defineProperties(r,{jwks:{value:()=>Nr(e._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}const Fn=async(s,e,r)=>{let t,n,i=!1;typeof AbortController=="function"&&(t=new AbortController,n=setTimeout(()=>{i=!0,t.abort()},e));const o=await fetch(s.href,{signal:t?t.signal:void 0,redirect:"manual",headers:r.headers}).catch(a=>{throw i?new xr:a});if(n!==void 0&&clearTimeout(n),o.status!==200)throw new Z("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new Z("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function Kn(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let kt;(typeof navigator>"u"||!((Ms=(yt=navigator.userAgent)==null?void 0:yt.startsWith)!=null&&Ms.call(yt,"Mozilla/5.0 ")))&&(kt="jose/v5.10.0");const Nt=Symbol();function Gn(s,e){return!(typeof s!="object"||s===null||!("uat"in s)||typeof s.uat!="number"||Date.now()-s.uat>=e||!("jwks"in s)||!ve(s.jwks)||!Array.isArray(s.jwks.keys)||!Array.prototype.every.call(s.jwks.keys,ve))}class qn{constructor(e,r){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:r==null?void 0:r.agent,headers:r==null?void 0:r.headers},this._timeoutDuration=typeof(r==null?void 0:r.timeoutDuration)=="number"?r==null?void 0:r.timeoutDuration:5e3,this._cooldownDuration=typeof(r==null?void 0:r.cooldownDuration)=="number"?r==null?void 0:r.cooldownDuration:3e4,this._cacheMaxAge=typeof(r==null?void 0:r.cacheMaxAge)=="number"?r==null?void 0:r.cacheMaxAge:6e5,(r==null?void 0:r[Nt])!==void 0&&(this._cache=r==null?void 0:r[Nt],Gn(r==null?void 0:r[Nt],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=Dr(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(e,r){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(e,r)}catch(t){if(t instanceof Rt&&this.coolingDown()===!1)return await this.reload(),this._local(e,r);throw t}}async reload(){this._pendingFetch&&Kn()&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);kt&&!e.has("User-Agent")&&(e.set("User-Agent",kt),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=Fn(this._url,this._timeoutDuration,this._options).then(r=>{this._local=Dr(r),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=r),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(r=>{throw this._pendingFetch=void 0,r})),await this._pendingFetch}}function Jn(s,e){const r=new qn(s,e),t=async(n,i)=>r.getKey(n,i);return Object.defineProperties(t,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>{var n;return(n=r._local)==null?void 0:n.jwks()},enumerable:!0,configurable:!1,writable:!1}}),t}const Vn=Re;function zn(s){if(typeof s!="string")throw new me("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:r}=s.split(".");if(r===5)throw new me("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new me("Invalid JWT");if(!e)throw new me("JWTs must contain a payload");let t;try{t=Vn(e)}catch{throw new me("Failed to base64url decode the payload")}let n;try{n=JSON.parse(Ye.decode(t))}catch{throw new me("Failed to parse the decoded payload as JSON")}if(!ve(n))throw new me("Invalid JWT Claims Set");return n}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Lt(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Ee(s,e=""){if(!Number.isSafeInteger(s)||s<0){const r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${s}`)}}function G(s,e,r=""){const t=Lt(s),n=s==null?void 0:s.length,i=e!==void 0;if(!t||i&&n!==e){const o=r&&`"${r}" `,a=i?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof s}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return s}function Mr(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Ee(s.outputLen),Ee(s.blockLen)}function Ke(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function $r(s,e){G(s,void 0,"digestInto() output");const r=e.outputLen;if(s.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function Yn(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function Ge(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function Dt(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function ye(s,e){return s<<32-e|s>>>e}const jn=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Xn(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Zn(s){for(let e=0;e<s.length;e++)s[e]=Xn(s[e]);return s}const Wr=jn?s=>s:Zn,Ur=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Qn=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Xe(s){if(G(s),Ur)return s.toHex();let e="";for(let r=0;r<s.length;r++)e+=Qn[s[r]];return e}const Ie={_0:48,_9:57,A:65,F:70,a:97,f:102};function Hr(s){if(s>=Ie._0&&s<=Ie._9)return s-Ie._0;if(s>=Ie.A&&s<=Ie.F)return s-(Ie.A-10);if(s>=Ie.a&&s<=Ie.f)return s-(Ie.a-10)}function ct(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(Ur)return Uint8Array.fromHex(s);const e=s.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){const o=Hr(s.charCodeAt(i)),a=Hr(s.charCodeAt(i+1));if(o===void 0||a===void 0){const c=s[i]+s[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}t[n]=o*16+a}return t}function Oe(...s){let e=0;for(let t=0;t<s.length;t++){const n=s[t];G(n),e+=n.length}const r=new Uint8Array(e);for(let t=0,n=0;t<s.length;t++){const i=s[t];r.set(i,n),n+=i.length}return r}function Br(s,e={}){const r=(n,i)=>s(i).update(n).digest(),t=s(void 0);return r.outputLen=t.outputLen,r.blockLen=t.blockLen,r.create=n=>s(n),Object.assign(r,e),Object.freeze(r)}function Fr(s=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(s))}const ei=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function ti(s,e,r){return s&e^~s&r}function ri(s,e,r){return s&e^s&r^e&r}class si{constructor(e,r,t,n){R(this,"blockLen");R(this,"outputLen");R(this,"padOffset");R(this,"isLE");R(this,"buffer");R(this,"view");R(this,"finished",!1);R(this,"length",0);R(this,"pos",0);R(this,"destroyed",!1);this.blockLen=e,this.outputLen=r,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Dt(this.buffer)}update(e){Ke(this),G(e);const{view:r,buffer:t,blockLen:n}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(n-this.pos,i-o);if(a===n){const c=Dt(e);for(;n<=i-o;o+=n)this.process(c,o);continue}t.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ke(this),$r(e,this),this.finished=!0;const{buffer:r,view:t,blockLen:n,isLE:i}=this;let{pos:o}=this;r[o++]=128,Ge(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(t,0),o=0);for(let f=o;f<n;f++)r[f]=0;t.setBigUint64(n-8,BigInt(this.length*8),i),this.process(t,0);const a=Dt(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,d=this.get();if(l>d.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,d[f],i)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const t=e.slice(0,r);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:t,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%r&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const Pe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),lt=BigInt(2**32-1),Kr=BigInt(32);function ni(s,e=!1){return e?{h:Number(s<),l:Number(s>>Kr<)}:{h:Number(s>>Kr<)|0,l:Number(s<)|0}}function ii(s,e=!1){const r=s.length;let t=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){const{h:o,l:a}=ni(s[i],e);[t[i],n[i]]=[o,a]}return[t,n]}const oi=(s,e,r)=>s<<r|e>>>32-r,ai=(s,e,r)=>e<<r|s>>>32-r,ci=(s,e,r)=>e<<r-32|s>>>64-r,li=(s,e,r)=>s<<r-32|e>>>64-r,di=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ce=new Uint32Array(64);class ui extends si{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:r,C:t,D:n,E:i,F:o,G:a,H:c}=this;return[e,r,t,n,i,o,a,c]}set(e,r,t,n,i,o,a,c){this.A=e|0,this.B=r|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let f=0;f<16;f++,r+=4)Ce[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){const g=Ce[f-15],p=Ce[f-2],w=ye(g,7)^ye(g,18)^g>>>3,b=ye(p,17)^ye(p,19)^p>>>10;Ce[f]=b+Ce[f-7]+w+Ce[f-16]|0}let{A:t,B:n,C:i,D:o,E:a,F:c,G:l,H:d}=this;for(let f=0;f<64;f++){const g=ye(a,6)^ye(a,11)^ye(a,25),p=d+g+ti(a,c,l)+di[f]+Ce[f]|0,b=(ye(t,2)^ye(t,13)^ye(t,22))+ri(t,n,i)|0;d=l,l=c,c=a,a=o+p|0,o=i,i=n,n=t,t=p+b|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,d=d+this.H|0,this.set(t,n,i,o,a,c,l,d)}roundClean(){Ge(Ce)}destroy(){this.set(0,0,0,0,0,0,0,0),Ge(this.buffer)}}class hi extends ui{constructor(){super(32);R(this,"A",Pe[0]|0);R(this,"B",Pe[1]|0);R(this,"C",Pe[2]|0);R(this,"D",Pe[3]|0);R(this,"E",Pe[4]|0);R(this,"F",Pe[5]|0);R(this,"G",Pe[6]|0);R(this,"H",Pe[7]|0)}}const fi=Br(()=>new hi,ei(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Mt=BigInt(0),$t=BigInt(1);function dt(s,e=""){if(typeof s!="boolean"){const r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof s)}return s}function Gr(s){if(typeof s=="bigint"){if(!ft(s))throw new Error("positive bigint expected, got "+s)}else Ee(s);return s}function ut(s){const e=Gr(s).toString(16);return e.length&1?"0"+e:e}function qr(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?Mt:BigInt("0x"+s)}function ht(s){return qr(Xe(s))}function Jr(s){return qr(Xe(pi(G(s)).reverse()))}function Wt(s,e){Ee(e),s=Gr(s);const r=ct(s.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function Vr(s,e){return Wt(s,e).reverse()}function pi(s){return Uint8Array.from(s)}const ft=s=>typeof s=="bigint"&&Mt<=s;function _i(s,e,r){return ft(s)&&ft(e)&&ft(r)&&e<=s&&s<r}function gi(s,e,r,t){if(!_i(e,r,t))throw new Error("expected valid "+s+": "+r+" <= n < "+t+", got "+e)}function xi(s){let e;for(e=0;s>Mt;s>>=$t,e+=1);return e}const Ut=s=>($t<<BigInt(s))-$t;function mi(s,e,r){if(Ee(s,"hashLen"),Ee(e,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");const t=y=>new Uint8Array(y),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3;let c=t(s),l=t(s),d=0;const f=()=>{c.fill(1),l.fill(0),d=0},g=(...y)=>r(l,Oe(c,...y)),p=(y=n)=>{l=g(i,y),c=g(),y.length!==0&&(l=g(o,y),c=g())},w=()=>{if(d++>=a)throw new Error("drbg: tried max amount of iterations");let y=0;const I=[];for(;y<e;){c=g();const C=c.slice();I.push(C),y+=c.length}return Oe(...I)};return(y,I)=>{f(),p(y);let C;for(;!(C=I(w()));)p();return f(),C}}function Ht(s,e={},r={}){if(!s||typeof s!="object")throw new Error("expected valid options object");function t(i,o,a){const c=s[i];if(a&&c===void 0)return;const l=typeof c;if(l!==o||c===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${l}`)}const n=(i,o)=>Object.entries(i).forEach(([a,c])=>t(a,c,o));n(e,!1),n(r,!0)}function zr(s){const e=new WeakMap;return(r,...t)=>{const n=e.get(r);if(n!==void 0)return n;const i=s(r,...t);return e.set(r,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const ae=BigInt(0),te=BigInt(1),Le=BigInt(2),Yr=BigInt(3),jr=BigInt(4),Xr=BigInt(5),wi=BigInt(7),Zr=BigInt(8),yi=BigInt(9),Qr=BigInt(16);function fe(s,e){const r=s%e;return r>=ae?r:e+r}function ue(s,e,r){let t=s;for(;e-- >ae;)t*=t,t%=r;return t}function es(s,e){if(s===ae)throw new Error("invert: expected non-zero number");if(e<=ae)throw new Error("invert: expected positive modulus, got "+e);let r=fe(s,e),t=e,n=ae,i=te;for(;r!==ae;){const a=t/r,c=t%r,l=n-i*a;t=r,r=c,n=i,i=l}if(t!==te)throw new Error("invert: does not exist");return fe(n,e)}function Bt(s,e,r){if(!s.eql(s.sqr(e),r))throw new Error("Cannot find square root")}function ts(s,e){const r=(s.ORDER+te)/jr,t=s.pow(e,r);return Bt(s,t,e),t}function bi(s,e){const r=(s.ORDER-Xr)/Zr,t=s.mul(e,Le),n=s.pow(t,r),i=s.mul(e,n),o=s.mul(s.mul(i,Le),n),a=s.mul(i,s.sub(o,s.ONE));return Bt(s,a,e),a}function Si(s){const e=pt(s),r=rs(s),t=r(e,e.neg(e.ONE)),n=r(e,t),i=r(e,e.neg(t)),o=(s+wi)/Qr;return(a,c)=>{let l=a.pow(c,o),d=a.mul(l,t);const f=a.mul(l,n),g=a.mul(l,i),p=a.eql(a.sqr(d),c),w=a.eql(a.sqr(f),c);l=a.cmov(l,d,p),d=a.cmov(g,f,w);const b=a.eql(a.sqr(d),c),y=a.cmov(l,d,b);return Bt(a,y,c),y}}function rs(s){if(s<Yr)throw new Error("sqrt is not defined for small field");let e=s-te,r=0;for(;e%Le===ae;)e/=Le,r++;let t=Le;const n=pt(s);for(;ns(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return ts;let i=n.pow(t,e);const o=(e+te)/Le;return function(c,l){if(c.is0(l))return l;if(ns(c,l)!==1)throw new Error("Cannot find square root");let d=r,f=c.mul(c.ONE,i),g=c.pow(l,e),p=c.pow(l,o);for(;!c.eql(g,c.ONE);){if(c.is0(g))return c.ZERO;let w=1,b=c.sqr(g);for(;!c.eql(b,c.ONE);)if(w++,b=c.sqr(b),w===d)throw new Error("Cannot find square root");const y=te<<BigInt(d-w-1),I=c.pow(f,y);d=w,f=c.sqr(I),g=c.mul(g,f),p=c.mul(p,I)}return p}}function vi(s){return s%jr===Yr?ts:s%Zr===Xr?bi:s%Qr===yi?Si(s):rs(s)}const Ei=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ii(s){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=Ei.reduce((t,n)=>(t[n]="function",t),e);return Ht(s,r),s}function Ai(s,e,r){if(r<ae)throw new Error("invalid exponent, negatives unsupported");if(r===ae)return s.ONE;if(r===te)return e;let t=s.ONE,n=e;for(;r>ae;)r&te&&(t=s.mul(t,n)),n=s.sqr(n),r>>=te;return t}function ss(s,e,r=!1){const t=new Array(e.length).fill(r?s.ZERO:void 0),n=e.reduce((o,a,c)=>s.is0(a)?o:(t[c]=o,s.mul(o,a)),s.ONE),i=s.inv(n);return e.reduceRight((o,a,c)=>s.is0(a)?o:(t[c]=s.mul(o,t[c]),s.mul(o,a)),i),t}function ns(s,e){const r=(s.ORDER-te)/Le,t=s.pow(e,r),n=s.eql(t,s.ONE),i=s.eql(t,s.ZERO),o=s.eql(t,s.neg(s.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function Ti(s,e){e!==void 0&&Ee(e);const r=e!==void 0?e:s.toString(2).length,t=Math.ceil(r/8);return{nBitLength:r,nByteLength:t}}class Ri{constructor(e,r={}){R(this,"ORDER");R(this,"BITS");R(this,"BYTES");R(this,"isLE");R(this,"ZERO",ae);R(this,"ONE",te);R(this,"_lengths");R(this,"_sqrt");R(this,"_mod");var o;if(e<=ae)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(t=r.BITS),typeof r.sqrt=="function"&&(this.sqrt=r.sqrt),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=(o=r.allowedLengths)==null?void 0:o.slice()),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));const{nBitLength:n,nByteLength:i}=Ti(e,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return fe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return ae<=e&&e<this.ORDER}is0(e){return e===ae}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&te)===te}neg(e){return fe(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return fe(e*e,this.ORDER)}add(e,r){return fe(e+r,this.ORDER)}sub(e,r){return fe(e-r,this.ORDER)}mul(e,r){return fe(e*r,this.ORDER)}pow(e,r){return Ai(this,e,r)}div(e,r){return fe(e*es(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return es(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=vi(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Vr(e,this.BYTES):Wt(e,this.BYTES)}fromBytes(e,r=!1){G(e);const{_lengths:t,BYTES:n,isLE:i,ORDER:o,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(n);l.set(e,i?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=i?Jr(e):ht(e);if(a&&(c=fe(c,o)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return ss(this,e)}cmov(e,r,t){return t?r:e}}function pt(s,e={}){return new Ri(s,e)}function is(s){if(typeof s!="bigint")throw new Error("field order must be bigint");const e=s.toString(2).length;return Math.ceil(e/8)}function os(s){const e=is(s);return e+Math.ceil(e/2)}function Oi(s,e,r=!1){G(s);const t=s.length,n=is(e),i=os(e);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=r?Jr(s):ht(s),a=fe(o,e-te)+te;return r?Vr(a,n):Wt(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const qe=BigInt(0),De=BigInt(1);function _t(s,e){const r=e.negate();return s?r:e}function as(s,e){const r=ss(s.Fp,e.map(t=>t.Z));return e.map((t,n)=>s.fromAffine(t.toAffine(r[n])))}function cs(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function Ft(s,e){cs(s,e);const r=Math.ceil(e/s)+1,t=2**(s-1),n=2**s,i=Ut(s),o=BigInt(s);return{windows:r,windowSize:t,mask:i,maxNumber:n,shiftBy:o}}function ls(s,e,r){const{windowSize:t,mask:n,maxNumber:i,shiftBy:o}=r;let a=Number(s&n),c=s>>o;a>t&&(a-=i,c+=De);const l=e*t,d=l+Math.abs(a)-1,f=a===0,g=a<0,p=e%2!==0;return{nextN:c,offset:d,isZero:f,isNeg:g,isNegF:p,offsetF:l}}const Kt=new WeakMap,ds=new WeakMap;function Gt(s){return ds.get(s)||1}function us(s){if(s!==qe)throw new Error("invalid wNAF")}class Pi{constructor(e,r){R(this,"BASE");R(this,"ZERO");R(this,"Fn");R(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,t=this.ZERO){let n=e;for(;r>qe;)r&De&&(t=t.add(n)),n=n.double(),r>>=De;return t}precomputeWindow(e,r){const{windows:t,windowSize:n}=Ft(r,this.bits),i=[];let o=e,a=o;for(let c=0;c<t;c++){a=o,i.push(a);for(let l=1;l<n;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,r,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const o=Ft(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:d,isNeg:f,isNegF:g,offsetF:p}=ls(t,a,o);t=c,d?i=i.add(_t(g,r[p])):n=n.add(_t(f,r[l]))}return us(t),{p:n,f:i}}wNAFUnsafe(e,r,t,n=this.ZERO){const i=Ft(e,this.bits);for(let o=0;o<i.windows&&t!==qe;o++){const{nextN:a,offset:c,isZero:l,isNeg:d}=ls(t,o,i);if(t=a,!l){const f=r[c];n=n.add(d?f.negate():f)}}return us(t),n}getPrecomputes(e,r,t){let n=Kt.get(r);return n||(n=this.precomputeWindow(r,e),e!==1&&(typeof t=="function"&&(n=t(n)),Kt.set(r,n))),n}cached(e,r,t){const n=Gt(e);return this.wNAF(n,this.getPrecomputes(n,e,t),r)}unsafe(e,r,t,n){const i=Gt(e);return i===1?this._unsafeLadder(e,r,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,t),r,n)}createCache(e,r){cs(r,this.bits),ds.set(e,r),Kt.delete(e)}hasCache(e){return Gt(e)!==1}}function Ci(s,e,r,t){let n=e,i=s.ZERO,o=s.ZERO;for(;r>qe||t>qe;)r&De&&(i=i.add(n)),t&De&&(o=o.add(n)),n=n.double(),r>>=De,t>>=De;return{p1:i,p2:o}}function hs(s,e,r){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ii(e),e}else return pt(s,{isLE:r})}function ki(s,e,r={},t){if(t===void 0&&(t=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>qe))throw new Error(`CURVE.${c} must be positive bigint`)}const n=hs(e.p,r.Fp,t),i=hs(e.n,r.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}function Ni(s,e){return function(t){const n=s(t);return{secretKey:n,publicKey:e(n)}}}class fs{constructor(e,r){R(this,"oHash");R(this,"iHash");R(this,"blockLen");R(this,"outputLen");R(this,"finished",!1);R(this,"destroyed",!1);if(Mr(e),G(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(r.length>t?e.create().update(r).digest():r);for(let i=0;i<n.length;i++)n[i]^=54;this.iHash.update(n),this.oHash=e.create();for(let i=0;i<n.length;i++)n[i]^=106;this.oHash.update(n),Ge(n)}update(e){return Ke(this),this.iHash.update(e),this}digestInto(e){Ke(this),G(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:t,finished:n,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const ps=(s,e,r)=>new fs(s,e).update(r).digest();ps.create=(s,e)=>new fs(s,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _s=(s,e)=>(s+(s>=0?e:-e)/gs)/e;function Li(s,e,r){const[[t,n],[i,o]]=e,a=_s(o*s,r),c=_s(-n*s,r);let l=s-a*t-c*i,d=-a*n-c*o;const f=l<Ae,g=d<Ae;f&&(l=-l),g&&(d=-d);const p=Ut(Math.ceil(xi(r)/2))+Je;if(l<Ae||l>=p||d<Ae||d>=p)throw new Error("splitScalar (endomorphism): failed, k="+s);return{k1neg:f,k1:l,k2neg:g,k2:d}}function qt(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function Jt(s,e){const r={};for(let t of Object.keys(e))r[t]=s[t]===void 0?e[t]:s[t];return dt(r.lowS,"lowS"),dt(r.prehash,"prehash"),r.format!==void 0&&qt(r.format),r}class Di extends Error{constructor(e=""){super(e)}}const ke={Err:Di,_tlv:{encode:(s,e)=>{const{Err:r}=ke;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const t=e.length/2,n=ut(t);if(n.length/2&128)throw new r("tlv.encode: long form length too big");const i=t>127?ut(n.length/2|128):"";return ut(s)+i+n+e},decode(s,e){const{Err:r}=ke;let t=0;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[t++]!==s)throw new r("tlv.decode: wrong tlv");const n=e[t++],i=!!(n&128);let o=0;if(!i)o=n;else{const c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const d of l)o=o<<8|d;if(t+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+o)}}},_int:{encode(s){const{Err:e}=ke;if(s<Ae)throw new e("integer: negative integers are not allowed");let r=ut(s);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(s){const{Err:e}=ke;if(s[0]&128)throw new e("invalid signature integer: negative");if(s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return ht(s)}},toSig(s){const{Err:e,_int:r,_tlv:t}=ke,n=G(s,void 0,"signature"),{v:i,l:o}=t.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,i),{v:l,l:d}=t.decode(2,c);if(d.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(s){const{_tlv:e,_int:r}=ke,t=e.encode(2,r.encode(s.r)),n=e.encode(2,r.encode(s.s)),i=t+n;return e.encode(48,i)}},Ae=BigInt(0),Je=BigInt(1),gs=BigInt(2),gt=BigInt(3),Mi=BigInt(4);function $i(s,e={}){const r=ki("weierstrass",s,e),{Fp:t,Fn:n}=r;let i=r.CURVE;const{h:o,n:a}=i;Ht(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=ms(t,n);function d(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(T,x,m){const{x:S,y:A}=x.toAffine(),N=t.toBytes(S);if(dt(m,"isCompressed"),m){d();const k=!t.isOdd(A);return Oe(xs(k),N)}else return Oe(Uint8Array.of(4),N,t.toBytes(A))}function g(T){G(T,void 0,"Point");const{publicKey:x,publicKeyUncompressed:m}=l,S=T.length,A=T[0],N=T.subarray(1);if(S===x&&(A===2||A===3)){const k=t.fromBytes(N);if(!t.isValid(k))throw new Error("bad point: is not on curve, wrong x");const M=b(k);let P;try{P=t.sqrt(M)}catch(j){const K=j instanceof Error?": "+j.message:"";throw new Error("bad point: is not on curve, sqrt error"+K)}d();const $=t.isOdd(P);return(A&1)===1!==$&&(P=t.neg(P)),{x:k,y:P}}else if(S===m&&A===4){const k=t.BYTES,M=t.fromBytes(N.subarray(0,k)),P=t.fromBytes(N.subarray(k,k*2));if(!y(M,P))throw new Error("bad point: is not on curve");return{x:M,y:P}}else throw new Error(`bad point: got length ${S}, expected compressed=${x} or uncompressed=${m}`)}const p=e.toBytes||f,w=e.fromBytes||g;function b(T){const x=t.sqr(T),m=t.mul(x,T);return t.add(t.add(m,t.mul(T,i.a)),i.b)}function y(T,x){const m=t.sqr(x),S=b(T);return t.eql(m,S)}if(!y(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const I=t.mul(t.pow(i.a,gt),Mi),C=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(I,C)))throw new Error("bad curve params: a or b");function H(T,x,m=!1){if(!t.isValid(x)||m&&t.is0(x))throw new Error(`bad point coordinate ${T}`);return x}function D(T){if(!(T instanceof z))throw new Error("Weierstrass Point expected")}function q(T){if(!c||!c.basises)throw new Error("no endo");return Li(T,c.basises,n.ORDER)}const F=zr((T,x)=>{const{X:m,Y:S,Z:A}=T;if(t.eql(A,t.ONE))return{x:m,y:S};const N=T.is0();x==null&&(x=N?t.ONE:t.inv(A));const k=t.mul(m,x),M=t.mul(S,x),P=t.mul(A,x);if(N)return{x:t.ZERO,y:t.ZERO};if(!t.eql(P,t.ONE))throw new Error("invZ was invalid");return{x:k,y:M}}),ne=zr(T=>{if(T.is0()){if(e.allowInfinityPoint&&!t.is0(T.Y))return;throw new Error("bad point: ZERO")}const{x,y:m}=T.toAffine();if(!t.isValid(x)||!t.isValid(m))throw new Error("bad point: x or y not field elements");if(!y(x,m))throw new Error("bad point: equation left != right");if(!T.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function U(T,x,m,S,A){return m=new z(t.mul(m.X,T),m.Y,m.Z),x=_t(S,x),m=_t(A,m),x.add(m)}const E=class E{constructor(x,m,S){R(this,"X");R(this,"Y");R(this,"Z");this.X=H("x",x),this.Y=H("y",m,!0),this.Z=H("z",S),Object.freeze(this)}static CURVE(){return i}static fromAffine(x){const{x:m,y:S}=x||{};if(!x||!t.isValid(m)||!t.isValid(S))throw new Error("invalid affine point");if(x instanceof E)throw new Error("projective point not allowed");return t.is0(m)&&t.is0(S)?E.ZERO:new E(m,S,t.ONE)}static fromBytes(x){const m=E.fromAffine(w(G(x,void 0,"point")));return m.assertValidity(),m}static fromHex(x){return E.fromBytes(ct(x))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(x=8,m=!0){return v.createCache(this,x),m||this.multiply(gt),this}assertValidity(){ne(this)}hasEvenY(){const{y:x}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(x)}equals(x){D(x);const{X:m,Y:S,Z:A}=this,{X:N,Y:k,Z:M}=x,P=t.eql(t.mul(m,M),t.mul(N,A)),$=t.eql(t.mul(S,M),t.mul(k,A));return P&&$}negate(){return new E(this.X,t.neg(this.Y),this.Z)}double(){const{a:x,b:m}=i,S=t.mul(m,gt),{X:A,Y:N,Z:k}=this;let M=t.ZERO,P=t.ZERO,$=t.ZERO,B=t.mul(A,A),j=t.mul(N,N),K=t.mul(k,k),W=t.mul(A,N);return W=t.add(W,W),$=t.mul(A,k),$=t.add($,$),M=t.mul(x,$),P=t.mul(S,K),P=t.add(M,P),M=t.sub(j,P),P=t.add(j,P),P=t.mul(M,P),M=t.mul(W,M),$=t.mul(S,$),K=t.mul(x,K),W=t.sub(B,K),W=t.mul(x,W),W=t.add(W,$),$=t.add(B,B),B=t.add($,B),B=t.add(B,K),B=t.mul(B,W),P=t.add(P,B),K=t.mul(N,k),K=t.add(K,K),B=t.mul(K,W),M=t.sub(M,B),$=t.mul(K,j),$=t.add($,$),$=t.add($,$),new E(M,P,$)}add(x){D(x);const{X:m,Y:S,Z:A}=this,{X:N,Y:k,Z:M}=x;let P=t.ZERO,$=t.ZERO,B=t.ZERO;const j=i.a,K=t.mul(i.b,gt);let W=t.mul(m,N),Q=t.mul(S,k),ie=t.mul(A,M),de=t.add(m,S),J=t.add(N,k);de=t.mul(de,J),J=t.add(W,Q),de=t.sub(de,J),J=t.add(m,A);let oe=t.add(N,M);return J=t.mul(J,oe),oe=t.add(W,ie),J=t.sub(J,oe),oe=t.add(S,A),P=t.add(k,M),oe=t.mul(oe,P),P=t.add(Q,ie),oe=t.sub(oe,P),B=t.mul(j,J),P=t.mul(K,ie),B=t.add(P,B),P=t.sub(Q,B),B=t.add(Q,B),$=t.mul(P,B),Q=t.add(W,W),Q=t.add(Q,W),ie=t.mul(j,ie),J=t.mul(K,J),Q=t.add(Q,ie),ie=t.sub(W,ie),ie=t.mul(j,ie),J=t.add(J,ie),W=t.mul(Q,J),$=t.add($,W),W=t.mul(oe,J),P=t.mul(de,P),P=t.sub(P,W),W=t.mul(de,Q),B=t.mul(oe,B),B=t.add(B,W),new E(P,$,B)}subtract(x){return this.add(x.negate())}is0(){return this.equals(E.ZERO)}multiply(x){const{endo:m}=e;if(!n.isValidNot0(x))throw new Error("invalid scalar: out of range");let S,A;const N=k=>v.cached(this,k,M=>as(E,M));if(m){const{k1neg:k,k1:M,k2neg:P,k2:$}=q(x),{p:B,f:j}=N(M),{p:K,f:W}=N($);A=j.add(W),S=U(m.beta,B,K,k,P)}else{const{p:k,f:M}=N(x);S=k,A=M}return as(E,[S,A])[0]}multiplyUnsafe(x){const{endo:m}=e,S=this;if(!n.isValid(x))throw new Error("invalid scalar: out of range");if(x===Ae||S.is0())return E.ZERO;if(x===Je)return S;if(v.hasCache(this))return this.multiply(x);if(m){const{k1neg:A,k1:N,k2neg:k,k2:M}=q(x),{p1:P,p2:$}=Ci(E,S,N,M);return U(m.beta,P,$,A,k)}else return v.unsafe(S,x)}toAffine(x){return F(this,x)}isTorsionFree(){const{isTorsionFree:x}=e;return o===Je?!0:x?x(E,this):v.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:x}=e;return o===Je?this:x?x(E,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(x=!0){return dt(x,"isCompressed"),this.assertValidity(),p(E,this,x)}toHex(x=!0){return Xe(this.toBytes(x))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};R(E,"BASE",new E(i.Gx,i.Gy,t.ONE)),R(E,"ZERO",new E(t.ZERO,t.ONE,t.ZERO)),R(E,"Fp",t),R(E,"Fn",n);let z=E;const O=n.BITS,v=new Pi(z,e.endo?Math.ceil(O/2):O);return z.BASE.precompute(8),z}function xs(s){return Uint8Array.of(s?2:3)}function ms(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Wi(s,e={}){const{Fn:r}=s,t=e.randomBytes||Fr,n=Object.assign(ms(s.Fp,r),{seed:os(r.ORDER)});function i(p){try{const w=r.fromBytes(p);return r.isValidNot0(w)}catch{return!1}}function o(p,w){const{publicKey:b,publicKeyUncompressed:y}=n;try{const I=p.length;return w===!0&&I!==b||w===!1&&I!==y?!1:!!s.fromBytes(p)}catch{return!1}}function a(p=t(n.seed)){return Oi(G(p,n.seed,"seed"),r.ORDER)}function c(p,w=!0){return s.BASE.multiply(r.fromBytes(p)).toBytes(w)}function l(p){const{secretKey:w,publicKey:b,publicKeyUncompressed:y}=n;if(!Lt(p)||"_lengths"in r&&r._lengths||w===b)return;const I=G(p,void 0,"key").length;return I===b||I===y}function d(p,w,b=!0){if(l(p)===!0)throw new Error("first arg must be private key");if(l(w)===!1)throw new Error("second arg must be public key");const y=r.fromBytes(p);return s.fromBytes(w).multiply(y).toBytes(b)}const f={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},g=Ni(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:d,keygen:g,Point:s,utils:f,lengths:n})}function Ui(s,e,r={}){Mr(e),Ht(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);const t=r.randomBytes||Fr,n=r.hmac||((x,m)=>ps(e,x,m)),{Fp:i,Fn:o}=s,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:d,getSharedSecret:f,utils:g,lengths:p}=Wi(s,r),w={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},b=a*gs<i.ORDER;function y(x){const m=a>>Je;return x>m}function I(x,m){if(!o.isValidNot0(m))throw new Error(`invalid signature ${x}: out of range 1..Point.Fn.ORDER`);return m}function C(){if(b)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function H(x,m){qt(m);const S=p.signature,A=m==="compact"?S:m==="recovered"?S+1:void 0;return G(x,A)}class D{constructor(m,S,A){R(this,"r");R(this,"s");R(this,"recovery");if(this.r=I("r",m),this.s=I("s",S),A!=null){if(C(),![0,1,2,3].includes(A))throw new Error("invalid recovery id");this.recovery=A}Object.freeze(this)}static fromBytes(m,S=w.format){H(m,S);let A;if(S==="der"){const{r:P,s:$}=ke.toSig(G(m));return new D(P,$)}S==="recovered"&&(A=m[0],S="compact",m=m.subarray(1));const N=p.signature/2,k=m.subarray(0,N),M=m.subarray(N,N*2);return new D(o.fromBytes(k),o.fromBytes(M),A)}static fromHex(m,S){return this.fromBytes(ct(m),S)}assertRecovery(){const{recovery:m}=this;if(m==null)throw new Error("invalid recovery id: must be present");return m}addRecoveryBit(m){return new D(this.r,this.s,m)}recoverPublicKey(m){const{r:S,s:A}=this,N=this.assertRecovery(),k=N===2||N===3?S+a:S;if(!i.isValid(k))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const M=i.toBytes(k),P=s.fromBytes(Oe(xs((N&1)===0),M)),$=o.inv(k),B=F(G(m,void 0,"msgHash")),j=o.create(-B*$),K=o.create(A*$),W=s.BASE.multiplyUnsafe(j).add(P.multiplyUnsafe(K));if(W.is0())throw new Error("invalid recovery: point at infinify");return W.assertValidity(),W}hasHighS(){return y(this.s)}toBytes(m=w.format){if(qt(m),m==="der")return ct(ke.hexFromSig(this));const{r:S,s:A}=this,N=o.toBytes(S),k=o.toBytes(A);return m==="recovered"?(C(),Oe(Uint8Array.of(this.assertRecovery()),N,k)):Oe(N,k)}toHex(m){return Xe(this.toBytes(m))}}const q=r.bits2int||function(m){if(m.length>8192)throw new Error("input is too large");const S=ht(m),A=m.length*8-c;return A>0?S>>BigInt(A):S},F=r.bits2int_modN||function(m){return o.create(q(m))},ne=Ut(c);function U(x){return gi("num < 2^"+c,x,Ae,ne),o.toBytes(x)}function z(x,m){return G(x,void 0,"message"),m?G(e(x),void 0,"prehashed message"):x}function O(x,m,S){const{lowS:A,prehash:N,extraEntropy:k}=Jt(S,w);x=z(x,N);const M=F(x),P=o.fromBytes(m);if(!o.isValidNot0(P))throw new Error("invalid private key");const $=[U(P),U(M)];if(k!=null&&k!==!1){const W=k===!0?t(p.secretKey):k;$.push(G(W,void 0,"extraEntropy"))}const B=Oe(...$),j=M;function K(W){const Q=q(W);if(!o.isValidNot0(Q))return;const ie=o.inv(Q),de=s.BASE.multiply(Q).toAffine(),J=o.create(de.x);if(J===Ae)return;const oe=o.create(ie*o.create(j+J*P));if(oe===Ae)return;let $s=(de.x===J?0:2)|Number(de.y&Je),Ws=oe;return A&&y(oe)&&(Ws=o.neg(oe),$s^=1),new D(J,Ws,b?void 0:$s)}return{seed:B,k2sig:K}}function v(x,m,S={}){const{seed:A,k2sig:N}=O(x,m,S);return mi(e.outputLen,o.BYTES,n)(A,N).toBytes(S.format)}function E(x,m,S,A={}){const{lowS:N,prehash:k,format:M}=Jt(A,w);if(S=G(S,void 0,"publicKey"),m=z(m,k),!Lt(x)){const P=x instanceof D?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+P)}H(x,M);try{const P=D.fromBytes(x,M),$=s.fromBytes(S);if(N&&P.hasHighS())return!1;const{r:B,s:j}=P,K=F(m),W=o.inv(j),Q=o.create(K*W),ie=o.create(B*W),de=s.BASE.multiplyUnsafe(Q).add($.multiplyUnsafe(ie));return de.is0()?!1:o.create(de.x)===B}catch{return!1}}function T(x,m,S={}){const{prehash:A}=Jt(S,w);return m=z(m,A),D.fromBytes(x,"recovered").recoverPublicKey(m).toBytes()}return Object.freeze({keygen:l,getPublicKey:d,getSharedSecret:f,utils:g,lengths:p,Point:s,sign:v,verify:E,recoverPublicKey:T,Signature:D,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Vt={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Hi={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},ws=BigInt(2);function Bi(s){const e=Vt.p,r=BigInt(3),t=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=s*s*s%e,d=l*l*s%e,f=ue(d,r,e)*d%e,g=ue(f,r,e)*d%e,p=ue(g,ws,e)*l%e,w=ue(p,n,e)*p%e,b=ue(w,i,e)*w%e,y=ue(b,a,e)*b%e,I=ue(y,c,e)*y%e,C=ue(I,a,e)*b%e,H=ue(C,r,e)*d%e,D=ue(H,o,e)*w%e,q=ue(D,t,e)*l%e,F=ue(q,ws,e);if(!zt.eql(zt.sqr(F),s))throw new Error("Cannot find square root");return F}const zt=pt(Vt.p,{sqrt:Bi}),Fi=Ui($i(Vt,{Fp:zt,endo:Hi}),fi),Ki=BigInt(0),Ze=BigInt(1),Gi=BigInt(2),qi=BigInt(7),Ji=BigInt(256),Vi=BigInt(113),ys=[],bs=[],Ss=[];for(let s=0,e=Ze,r=1,t=0;s<24;s++){[r,t]=[t,(2*r+3*t)%5],ys.push(2*(5*t+r)),bs.push((s+1)*(s+2)/2%64);let n=Ki;for(let i=0;i<7;i++)e=(e<<Ze^(e>>qi)*Vi)%Ji,e&Gi&&(n^=Ze<<(Ze<<BigInt(i))-Ze);Ss.push(n)}const vs=ii(Ss,!0),zi=vs[0],Yi=vs[1],Es=(s,e,r)=>r>32?ci(s,e,r):oi(s,e,r),Is=(s,e,r)=>r>32?li(s,e,r):ai(s,e,r);function ji(s,e=24){const r=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let o=0;o<10;o++)r[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=r[c],d=r[c+1],f=Es(l,d,1)^r[a],g=Is(l,d,1)^r[a+1];for(let p=0;p<50;p+=10)s[o+p]^=f,s[o+p+1]^=g}let n=s[2],i=s[3];for(let o=0;o<24;o++){const a=bs[o],c=Es(n,i,a),l=Is(n,i,a),d=ys[o];n=s[d],i=s[d+1],s[d]=c,s[d+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}s[0]^=zi[t],s[1]^=Yi[t]}Ge(r)}class Yt{constructor(e,r,t,n=!1,i=24){R(this,"state");R(this,"pos",0);R(this,"posOut",0);R(this,"finished",!1);R(this,"state32");R(this,"destroyed",!1);R(this,"blockLen");R(this,"suffix");R(this,"outputLen");R(this,"enableXOF",!1);R(this,"rounds");if(this.blockLen=e,this.suffix=r,this.outputLen=t,this.enableXOF=n,this.rounds=i,Ee(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Yn(this.state)}clone(){return this._cloneInto()}keccak(){Wr(this.state32),ji(this.state32,this.rounds),Wr(this.state32),this.posOut=0,this.pos=0}update(e){Ke(this),G(e);const{blockLen:r,state:t}=this,n=e.length;for(let i=0;i<n;){const o=Math.min(r-this.pos,n-i);for(let a=0;a<o;a++)t[this.pos++]^=e[i++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:t,blockLen:n}=this;e[t]^=r,r&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Ke(this,!1),G(e),this.finish();const r=this.state,{blockLen:t}=this;for(let n=0,i=e.length;n<i;){this.posOut>=t&&this.keccak();const o=Math.min(t-this.posOut,i-n);e.set(r.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Ee(e),this.xofInto(new Uint8Array(e))}digestInto(e){if($r(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Ge(this.state)}_cloneInto(e){const{blockLen:r,suffix:t,outputLen:n,rounds:i,enableXOF:o}=this;return e||(e=new Yt(r,t,n,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=t,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}}const As=((s,e,r,t={})=>Br(()=>new Yt(e,s,r),t))(1,136,32),Xi=60;class Zi{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=Jn(new URL(e)),u.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(r){u.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",r)}}async verifyJWT(e,r){try{const t=this.decodeJWT(e);u.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const n=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+Xi<n)return u.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1};if(!t.sub)return u.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:i}=await $n(e,this.jwks,{algorithms:["RS256","ES256"]});return u.log("[CROSSx] JWT 서명 검증 성공"),{payload:i,valid:!0,signatureVerified:!0}}catch(i){if(i instanceof Error&&(i.name==="JWSSignatureVerificationFailed"||i.name==="JWTClaimValidationFailed"))return u.error("[CROSSx] JWT 서명 검증 실패:",i),{payload:t,valid:!1,signatureVerified:!1};u.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return u.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw u.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return zn(e)}recoverPersonalSignSigner(e,r){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
|
|
6
|
-
${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);const o=As(i),a=r.startsWith("0x")?r.slice(2):r;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=Qi(a),l=c.slice(0,32),d=c.slice(32,64),f=c[64],g=f>=27?f-27:f,b=new Fi.Signature(Ts(l),Ts(d)).addRecoveryBit(g).recoverPublicKey(o).toBytes(!1).slice(1),y=As(b);return"0x"+Xe(y.slice(12))}}function Qi(s){const e=new Uint8Array(s.length/2);for(let r=0;r<e.length;r++)e[r]=parseInt(s.substring(r*2,r*2+2),16);return e}function Ts(s){let e="0x";for(const r of s)e+=r.toString(16).padStart(2,"0");return BigInt(e)}const eo=3e4,to=1e3;class ro{async request(e){const r=e.retries??0;for(let t=0;t<=r;t++){try{const n=await this._doRequest(e);if(n.status<500||t===r)return n}catch(n){if(t===r)throw n}await new Promise(n=>setTimeout(n,to*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const r=new AbortController,t=setTimeout(()=>r.abort(),e.timeoutMs??eo);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:r.signal,credentials:e.credentials});let i;const o=await n.text();try{i=o?JSON.parse(o):null}catch{i={_raw:o}}return{status:n.status,data:i,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const so=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io"]);class Me{static generateRandom16Hex(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}static parseJwtPayload(e){const r=e.split(".");if(r.length<2)throw new Error("Invalid JWT format");const t=(r[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=atob(t);return JSON.parse(n)}static async sha256Hex(e){const r=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,r){const t=Me.parseJwtPayload(e),n=t.nonce,i=typeof t.iss=="string"?t.iss:"(unknown)";if(u.log("[CROSSx] nonce 검증 시작 —",{iss:i,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),i.includes("securetoken.google.com")){u.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n===""){u.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:i,keys:Object.keys(t)});return}if(i.includes("appleid.apple.com")){const o=await Me.sha256Hex(r);if(u.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:o.length,receivedHashLength:n.length,match:n===o}),n!==o)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(u.log("[CROSSx] Google nonce 검증 —",{expectedLength:r.length,receivedLength:n.length,match:n===r}),n!==r)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");u.log("[CROSSx] nonce 검증 성공 —",{iss:i})}openAuth(e){return new Promise((r,t)=>{const n=Math.max(e.width??500,500),i=Math.max(e.height??700,700),o=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-i)/2,c=Me.generateRandom16Hex(),l=Me.generateRandom16Hex(),d=e.authUrl.includes("?")?"&":"?",f=`${e.authUrl}${d}state=${c}&nonce=${l}`;u.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const g=window.open(f,"CROSSx OAuth",`width=${n},height=${i},left=${o},top=${a}`);if(!g){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const p=setTimeout(()=>{u.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),D(),t(new Error("Authentication timeout"))},5*60*1e3),w=10,b=30;let y=0,I=null;const C=()=>{clearInterval(H),u.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+b+"초간 대기합니다"),I=setTimeout(()=>{D(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},b*1e3)},H=setInterval(()=>{y++;try{g.closed&&(y<=w?C():(D(),t(new Error("로그인이 취소되었습니다"))))}catch{C()}},1e3),D=()=>{clearTimeout(p),clearInterval(H),I&&clearTimeout(I),window.removeEventListener("message",q)},q=F=>{if(F.origin!==e.expectedOrigin)return;if(!so.has(F.origin)){u.error("[CROSSx] postMessage origin이 허용 목록에 없음:",F.origin),D(),t(new Error("Unauthorized OAuth origin"));return}D();const ne=typeof F.data.status=="string",U=ne?F.data.data??{}:F.data;u.log("[CROSSx] OAuth postMessage 수신 —",{format:ne?"wrapped":"flat",status:ne?F.data.status:"(flat)"});const z=(U==null?void 0:U.state)??F.data.state;if(!z||z!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(ne&&F.data.status!=="success"){u.error("[CROSSx] OAuth 실패:",U==null?void 0:U.error),t(new Error((U==null?void 0:U.error)||"Authentication failed"));return}if(!ne&&(U!=null&&U.error)){u.error("[CROSSx] OAuth 실패:",U.error),t(new Error(U.error||"Authentication failed"));return}const O=U==null?void 0:U.idToken,v=U==null?void 0:U.accessToken,E=v??O,T=(U==null?void 0:U.email)||void 0;if(u.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!v,hasIdToken:!!O,hasEmail:!!T}),!E){u.error("[CROSSx] 토큰을 찾을 수 없음:",F.data),t(new Error("Token not found in response"));return}const x={token:E,email:T},m=S=>{Me.verifyIdTokenNonce(S,l).then(()=>r(x)).catch(A=>{u.error("[CROSSx] nonce 검증 실패:",A),t(A instanceof Error?A:new Error("nonce verification failed"))})};v?v.split(".").length===3?m(v):O?m(O):(u.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),r(x)):O?m(O):t(new Error("Token not found in response"))};window.addEventListener("message",q)})}}const Qe="crossx_wallet_data",Ve="crossx_mock_pin_hash";class no{constructor(e,r){this.storage=e,this.pinStore=r??null}async checkWallet(){if(this.migrateScenario!==void 0)return u.log("[Mock] checkWallet → migration_required"),"migration_required";const r=await this.storage.get(Qe)?"exists":"not_found";return u.log(`[Mock] checkWallet → ${r}`),r}async getOrCreateWallet(e){var r;try{const t=await this.storage.get(Qe);if(t)return t;const n={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(Qe,n);const i=(r=this.pinStore)==null?void 0:r.get();return i&&(await this.storage.set(Ve,i),u.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new _(h.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const r=await this.storage.get(Qe);return r?[{address:r.address,index:0}]:[]}async getAddress(e,r){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){const t="mock-"+crypto.randomUUID();return u.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+3e5).toISOString()}}async signMessage(e,r,t,n=0,i,o){return u.log(`[Mock] signMessage chainId=${r} index=${n} uuid=${i} from=${o}: "${t}"`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,r,t,n=0,i,o){return u.log(`[Mock] signTypedData chainId=${r} index=${n} uuid=${i} from=${o}`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,r,t,n=0,i){u.log(`[Mock] signTransaction chainId=${r} index=${n} uuid=${i}:`,t);const o="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:r,signature:this.generateMockSignature(),txHash:o,format:"hex"}}async sendTransaction(e,r,t,n){return u.log(`[Mock] sendTransaction chainId=${r} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(u.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const r=await this.storage.get(Ve);return r&&r!==e?!1:(r||await this.storage.set(Ve,e),(t=this.pinStore)==null||t.set(e),u.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,r){var i;if(u.log("[Mock] changePin"),this.pinScenario==="wrong")throw new _(h.PIN_WRONG,"Incorrect PIN.");const t=(i=this.pinStore)==null?void 0:i.get(),n=await this.storage.get(Ve);if(n&&t&&n!==t)throw new _(h.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Ve,r),u.log("[Mock] changePin 완료")}async migrateWallet(e,r){var i;if(u.log(`[Mock] migrateWallet pin=${e} sub=${r}`),this.migrateScenario==="wrong_pin")throw new _(h.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new _(h.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",a)}const t={id:r,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(Qe,t);const n=(i=this.pinStore)==null?void 0:i.get();return n&&(await this.storage.set(Ve,n),u.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return u.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,r){return u.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class $e{constructor(e,r,t,n,i){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=r,this.transport=t,this.tokenStore=n,this.pinStore=i??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(hr))return e;const r=!e||this.tokenStore.isExpiringSoon(hr);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const n=this.tokenStore.get();if(n)return n}if(r)throw new _(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return u.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new _(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(u.log("[CROSSx] 토큰 만료 임박/만료 — 자동 갱신 시도"),this._refreshPromise=this._onTokenRefresh().finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async request(e,r,t,n=!1){var c,l,d,f;const i=await this.ensureValidToken(),o=`${this.baseUrl}${r}`,a={Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const p=(await this.transport.request({url:o,method:e,headers:a,body:t??void 0})).data;if(p&&typeof p.code=="number"){if(p.code<0||p.code>=400){const w=p.message||p.data||"API 요청에 실패했습니다";u.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:p.code,message:w,url:o,method:e});const b=$e.mapGatewayError(p.code,p.data);if(b===h.AUTH_NOT_AUTHENTICATED&&!n&&this._onTokenRefresh){if(u.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,r,t,!0);throw new _(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(b===h.USER_NOT_FOUND)throw u.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(c=this._onUnauthorized)==null||c.call(this),new _(h.USER_NOT_FOUND,$e.getGatewayErrorMessage(p.code,w));const y=b===h.AUTH_NOT_AUTHENTICATED?h.SESSION_EXPIRED:b,I=y===h.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":$e.getGatewayErrorMessage(p.code,w),C=p.data,H=b===h.PIN_LOCKED?$e.extractLockDetails(C):C??void 0;throw new _(y,I,H)}return u.log("[CROSSx] Wallet Gateway API 성공:",{code:p.code,url:o,method:e}),p.data??p}return p}catch(g){if(g instanceof _)throw g;const p=((l=g.response)==null?void 0:l.status)??g.status;if((p===401||p===403)&&!n&&this._onTokenRefresh){if(u.warn(`[CROSSx] HTTP ${p} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,r,t,!0);throw new _(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((d=g.response)!=null&&d.data){const w=g.response.data,b=w.message||w.data||"API 요청에 실패했습니다",y=w.code||"UNKNOWN";throw u.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:y,message:b,url:o,method:e,status:(f=g.response)==null?void 0:f.status}),new _(h.UNKNOWN_ERROR,`Wallet Gateway 오류 (${y}): ${b}`)}throw g}}async checkWallet(){u.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return u.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let r;if(this._walletStatusCache!==null?(r=this._walletStatusCache,this._walletStatusCache=null,u.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",r)):(u.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),r=await this.checkWallet(),this._walletStatusCache=null),r==="migration_required")throw u.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new _(h.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(r==="exists"){u.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const i=await this.getAddress(e,0);return u.log("[CROSSx] 주소 조회 완료 — address:",i.address),{id:e,address:i.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}u.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return u.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index}))}async getAddress(e,r){const t={password:this.requirePin(),index:r};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){let t;switch(e){case"sign":case"send":if(!r.tx)throw new _(h.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(r.tx)};break;case"sign-message":if(!r.message)throw new _(h.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:r.message},r.from&&(t.from=r.from);break;case"sign-typed-data":if(!r.typedData)throw new _(h.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:r.typedData},r.from&&(t.from=r.from);break}const n={action:e,params:t},i=await this.request("POST","/mnemonic/prepare",n);return{uuid:i.uuid,expiresAt:i.expiresAt}}async signMessage(e,r,t,n,i,o){const a={message:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:r,signature:c.signature,format:"hex"}}async signTypedData(e,r,t,n,i,o){const a={typedData:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(r)}`,a);return{chainId:r,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,r,t,n,i){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};i&&(o.uuid=i);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(r)}`,o);return{chainId:r,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,r,t,n){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(i.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(r)}`,i)).txHash}}async migrateWallet(e,r){u.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:r,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return u.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:r,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const r={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",r)}async verifyPin(e){const r={password:e};return(await this.request("POST","/mnemonic/verify-password",r)).valid}async changePin(e,r){const t={password:this.requirePin(),newPassword:r};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePin()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyRecoveryPin(e,r){const t={recoveryPin:e,sub:r};return this.request("POST","/mnemonic/verify-recovery-pin",t)}requirePin(){const e=this.getPin();if(!e)throw new _(h.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e,t={},n=(r==null?void 0:r.lockExpiresAt)??(r==null?void 0:r.lock_expires_at);n&&(t.lockExpiresAt=n>1e10?n:n*1e3);const i=(r==null?void 0:r.remainingAttempts)??(r==null?void 0:r.remaining_attempts);typeof i=="number"&&(t.remainingAttempts=i);const o=(r==null?void 0:r.maxAttempts)??(r==null?void 0:r.max_attempts);return typeof o=="number"&&(t.maxAttempts=o),typeof(r==null?void 0:r.permanent)=="boolean"&&(t.permanent=r.permanent),t}static hasLockInfo(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e;return!r||typeof r!="object"?!1:typeof r.remainingAttempts=="number"||typeof r.remaining_attempts=="number"||typeof r.maxAttempts=="number"||typeof r.max_attempts=="number"}static mapGatewayError(e,r){switch(e){case-10002:return h.AUTH_NOT_AUTHENTICATED;case-10001:return h.UNKNOWN_ERROR;case-10006:return h.GATEWAY_INTERNAL_ERROR;case-10007:return h.BROADCAST_FAILED;case-10008:return h.GATEWAY_LOCK_CONFLICT;case-10004:return h.WALLET_ALREADY_EXISTS;case-10005:return h.WALLET_NOT_FOUND;case-10011:return h.WALLET_NOT_FOUND;case-10030:return h.WALLET_INCONSISTENT_STATE;case-10010:return h.MIGRATION_FAILED;case-10012:return h.MIGRATION_BACKUP_EXISTS;case-10013:return h.WITHDRAW_FAILED;case-10033:return h.USER_NOT_FOUND;case-10027:return h.MIGRATION_PIN_LOCKED;case-10022:return h.PROJECT_NOT_REGISTERED;case-10023:return h.PROJECT_ID_MISSING;case-10024:return h.ORIGIN_NOT_ALLOWED;case-10025:return h.INVALID_APP_TYPE;case-10028:return $e.hasLockInfo(r)?h.PIN_LOCKED:h.PIN_WRONG;case-10029:return h.PIN_INVALID;case-10031:return h.PIN_LOCKED;case-10032:return h.PIN_REPEATED_PATTERN;case-10026:return h.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return h.PREPARE_FAILED;case-10016:return h.PREPARE_EXPIRED;case-10017:case-10018:return h.PREPARE_MISMATCH;case-10020:return h.CHAIN_NOT_SUPPORTED;case-10021:return h.INVALID_CHAIN;case-10040:return h.HMAC_REQUIRED;case-10041:return h.HMAC_VERIFICATION_FAILED;default:return h.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,r){switch(e){case-10002:return"Session expired. Please sign in again.";case-10004:return"Wallet already exists for this user.";case-10005:return"User wallet not found.";case-10006:return"Internal server error. Please try again later.";case-10007:return"Transaction broadcast failed. Please try again.";case-10008:return"Another operation is in progress. Please try again later.";case-10013:return"Withdraw failed. Please try again.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin or App ID is required. Register the current domain or set X-App-Id header.";case-10025:return"Invalid app type. X-App-Type must be android, ios, or windows.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Sequential PIN is not allowed. Please choose a different PIN.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10032:return"Repeated digit pattern is not allowed. Please choose a different PIN.";case-10033:return"User not found. You have been signed out.";case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${r}`}}}class et{constructor(e,r){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this.adapterConfig=e,this.projectId=e.projectId,this.transport=r}get baseUrl(){return this.adapterConfig.gatewayUrl}async getChains(){if(this.isCacheValid())return Array.from(this.cache.values());try{const e=await this.request("/chains");this.handleEnvelopeError(e);const r=e.data.chains;return this.populateCache(r,!1),r}catch{const e=et.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(n=>n.chainId===e);return t||this.fallbackOrThrow(e)}invalidateCache(){this.cache.clear(),this.loadedAt=0,this.usingFallback=!1}isCacheValid(){if(this.loadedAt===0)return!1;const e=this.usingFallback?tn:en;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,r){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=r}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const r=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new _(et.mapErrorCode(e.code),r)}}fallbackOrThrow(e){const r=et.fallbackChains().find(t=>t.chainId===e);if(r)return r;throw new _(h.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(tt).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return h.CHAIN_NOT_SUPPORTED;case-10021:return h.INVALID_CHAIN;case-10022:return h.PROJECT_NOT_REGISTERED;case-10023:return h.PROJECT_ID_MISSING;case-10024:return h.APP_IDENTIFIER_MISSING;case-10025:return h.INVALID_APP_TYPE;default:return h.UNKNOWN_ERROR}}}const Rs="__crossx-confirm-style",ee="__crossx-confirm-overlay",io={light:{bg:"#FFFFFF",border:"rgba(18,18,18,0.05)",titleColor:"#121212",subtitleColor:"rgba(18,18,18,0.7)",labelColor:"rgba(18,18,18,0.5)",valueColor:"#121212",pillBg:"rgba(18,18,18,0.05)",pillFromColor:"rgba(18,18,18,0.5)",pillAmtColor:"#121212",divider:"rgba(18,18,18,0.1)",closeColor:"#121212",closeHoverBg:"rgba(18,18,18,0.05)",copyColor:"rgba(18,18,18,0.5)",inputBg:"rgba(18,18,18,0.05)",inputBorder:"rgba(18,18,18,0.1)",hintColor:"rgba(18,18,18,0.5)",surfaceSubtle:"rgba(18,18,18,0.1)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#E70077",errorColor:"#E70077",onPrimary:"#FFFFFF"},dark:{bg:"#121212",border:"rgba(255,255,255,0.05)",titleColor:"#FFFFFF",subtitleColor:"rgba(255,255,255,0.7)",labelColor:"rgba(255,255,255,0.5)",valueColor:"#FFFFFF",pillBg:"rgba(255,255,255,0.05)",pillFromColor:"rgba(255,255,255,0.5)",pillAmtColor:"#FFFFFF",divider:"rgba(255,255,255,0.1)",closeColor:"#FFFFFF",closeHoverBg:"rgba(255,255,255,0.05)",copyColor:"rgba(255,255,255,0.5)",inputBg:"rgba(255,255,255,0.05)",inputBorder:"rgba(255,255,255,0.1)",hintColor:"rgba(255,255,255,0.5)",surfaceSubtle:"rgba(255,255,255,0.1)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#E70077",errorColor:"#E70077",onPrimary:"#FFFFFF"}};function Os(s,e){const r=io[s],t=e==null?void 0:e[s];return t?{...r,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault,inputBg:t.surfaceDefault},...t.surfaceSubtle!==void 0&&{surfaceSubtle:t.surfaceSubtle},...t.bg!==void 0&&{bg:t.bg},...t.error!==void 0&&{errorColor:t.error}}:r}const oo=`
|
|
5
|
+
For security, you must continue with the same account.`,sessionAlert_title:"Session expired",sessionAlert_accountLabel:"Account",sessionAlert_signOutButton:"Sign out",sessionAlert_signInAgainButton:"Sign in again"},Ks={ko:Fs,en:sr};function Se(s="en",e){return Ks[s]??sr}const nr="crossx_access_token",ir="crossx_refresh_token",or="crossx_user_info",wt=class wt{constructor(e,r,t,n,i,o,a){this.config=e,this.storage=r,this.crypto=t,this.oauth=n,this.transport=i,this.walletProvider=o,this.tokenStore=a,this._refreshPromise=null,this._migrated=!1;const c=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${c}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${c}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${c}_user_info`}get useCookieAuth(){return this.config.authMode==="cookie"}extractResponseErrorCode(e){if(e!=null&&e.code&&e.code!==200&&e.code>0)return{code:e.code,message:e.message??""};const r=e==null?void 0:e.data;if(typeof r=="object"&&r!==null&&"code"in r){const t=r;if(t.code&&t.code!==200&&t.code>0)return{code:t.code,message:t.message??""}}return null}checkResponseError(e,r){const t=this.extractResponseErrorCode(e);if(t)throw new x(h.AUTH_FAILED,`${r} 실패 (코드 ${t.code}): ${t.message}`)}async execute(e){let r,t;try{const n=e==null?void 0:e.provider;let i="/login";n==="google"?i="/google":n==="apple"&&(i="/apple");const{oauthServiceUrl:o}=this.config,a=`${o}${i}`;d.log(`[CROSSx] OAuth 팝업 열기 (${n||"일반"} 로그인)`);const c=await this.oauth.openAuth({authUrl:a,expectedOrigin:new URL(o).origin});r=c.token,t=c.email,d.log("[CROSSx] OAuth Firebase 토큰 받음 (length:",r.length,")"),t&&d.log("[CROSSx] OAuth 콜백 email:",t)}catch(n){d.error("[CROSSx] SignIn 에러 (OAuth 단계):",n);const i=n instanceof Error?n.message:"Sign in failed";throw/팝업|popup/i.test(i)?new x(h.OAUTH_POPUP_BLOCKED,i):new x(h.AUTH_FAILED,i)}return this.processFirebaseToken(r,t)}async executeWithOAuthToken(e){return d.log("[CROSSx] signInWithOAuthToken — Firebase 토큰 주입 (length:",e.length,")"),this.processFirebaseToken(e)}async processFirebaseToken(e,r){var i,o,a,c,l;let t,n=!1;try{const{authApiUrl:u}=this.config,{accessToken:f,refreshToken:g}=await this.exchangeFirebaseToken(e,u);let p,y,v;try{const I=this.crypto.decodeJWT(e);d.log("[CROSSx] Firebase JWT 필드:",Object.keys(I).join(", ")),y=(i=I.firebase)==null?void 0:i.sign_in_provider;const T=((o=I.firebase)==null?void 0:o.identities)??{};v=I.email??((a=T.email)==null?void 0:a[0]),y==="google.com"?p=(c=T["google.com"])==null?void 0:c[0]:y==="apple.com"&&(p=(l=T["apple.com"])==null?void 0:l[0]),d.log("[CROSSx] OAuth provider sub 추출 — provider:",y,"hasProviderSub:",!!p,"email:",v??"(없음)")}catch{d.warn("[CROSSx] firebaseToken에서 providerSub 추출 실패")}if(f){const I=this.crypto.decodeJWT(f);d.log("[CROSSx] access_token 디코딩 — sub:",I.sub,"exp:",I.exp,"필드:",Object.keys(I).join(", "));const T=await this.crypto.verifyJWT(f);if(n=T.signatureVerified??!1,!T.valid)throw d.error("[CROSSx] access_token 검증 실패"),new Error("유효하지 않은 access token");const H=T.payload,L=H.email??v??r;d.log("[CROSSx] email 소스 — CROSSx JWT:",H.email??"(없음)","/ Firebase JWT:",v??"(없음)","/ OAuth 콜백:",r??"(없음)","→",L??"(없음)"),t={id:H.sub,email:L,signInProvider:y,providerSub:p},this.tokenStore.set(f),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,f),g&&this.config.secureStorageAvailable!==!1?await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,g):g&&d.warn("[CROSSx] 안전한 스토리지 미사용 — refresh_token 영속 저장을 건너뜁니다"))}else{const I=this.crypto.decodeJWT(e);t={id:I.sub,email:I.email??r,signInProvider:y,providerSub:p},d.log("[CROSSx] Cookie 모드 — Firebase 토큰에서 사용자 정보 추출 — id:",t.id)}d.log("[CROSSx] 사용자 정보 — id:",t.id,"email:",t.email??"(없음)");const S=this.useCookieAuth?{id:t.id,email:t.email,signInProvider:t.signInProvider,providerSub:t.providerSub}:t;await this.storage.set(this.STORAGE_KEY_USER,S),d.log("[CROSSx] 사용자 정보 저장 완료 (authMode:",this.useCookieAuth?"cookie":"token",")")}catch(u){return d.error("[CROSSx] SignIn 에러 (토큰 교환 단계):",u),{success:!1,error:u instanceof Error?u.message:"Sign in failed"}}return d.log("[CROSSx][Migration Phase 1] 로그인 완료, 지갑 로드 시작 — userId:",t.id),this.loadWallet(t,n)}async exchangeFirebaseToken(e,r){const t=this.useCookieAuth,n=t?`${r}/cross-auth/social/login/cookie`:`${r}/cross-auth/social/login`;d.log("[CROSSx] Firebase 토큰 교환 요청");const i=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:{auth_code:e,login_type:"firebase"},...t?{credentials:"include"}:{}});d.log("[CROSSx] 토큰 교환 응답 — status:",i.status);const o=i.data;this.checkResponseError(o,"Token exchange");const a=this.extractAccessToken(o);if(t&&!a)return d.log("[CROSSx] Cookie 모드 — 로그인 성공 (JWT는 HttpOnly 쿠키)"),{};if(!a)throw new x(h.AUTH_FAILED,"토큰 교환 응답에서 access_token을 찾을 수 없습니다");d.log("[CROSSx] access_token 교환 성공");let c;return t||(c=this.extractRefreshToken(o)),{accessToken:a,refreshToken:c}}extractAccessToken(e){const r=(e==null?void 0:e.data)??e;if(this.isJwtString(r))return r;if(typeof r=="object"&&r!==null){const t=r;if(this.isJwtString(t.data))return t.data;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.access_token??i.token;if(typeof o=="string")return o}const n=t.access_token??t.token;if(typeof n=="string")return n}}extractRefreshToken(e){const r=(e==null?void 0:e.data)??e;if(typeof r!="object"||r===null)return;const t=r;if(typeof t.data=="object"&&t.data!==null){const i=t.data,o=i.refresh_token??i.refresh;if(typeof o=="string")return o}const n=t.refresh_token??t.refresh;if(typeof n=="string")return n}isJwtString(e){return typeof e=="string"&&e.split(".").length===3}async restoreSession(){try{await this.migrateStorageKeys();const e=this.tokenStore.get();if(e){const t=await this.crypto.verifyJWT(e);if(t.valid){const n=await this.storage.get(this.STORAGE_KEY_USER);if(n)return d.log("[CROSSx] restoreSession — 메모리 토큰 유효, 세션 복원"),this.loadWallet(n,t.signatureVerified)}this.tokenStore.clear()}if(this.useCookieAuth){d.log("[CROSSx] restoreSession — 쿠키 기반 silentRefresh 시도");const t=await this.silentRefresh();t&&this.tokenStore.set(t)}else{const t=await this.storage.get(this.STORAGE_KEY_ACCESS_TOKEN),n=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);if(d.log("[CROSSx] restoreSession — access_token:",t?"있음":"없음","refresh_token:",n?"있음":"없음"),!n)return d.log("[CROSSx] restoreSession — refresh_token 없음, 세션 복원 생략"),null;t&&this.tokenStore.set(t);const i=await this.silentRefresh(n);d.log("[CROSSx] restoreSession — silentRefresh 결과:",i?"토큰 발급 성공":"토큰 없음"),i&&this.tokenStore.set(i)}const r=await this.storage.get(this.STORAGE_KEY_USER);if(d.log("[CROSSx] restoreSession — userInfo 조회:",r?`있음 (id: ${r.id})`:"없음"),!r)return null;d.log("[CROSSx] restoreSession — silentRefresh 성공, 세션 복원 — userId:",r.id);try{return await this.loadWallet(r,!1)}catch(t){return d.warn("[CROSSx] restoreSession — 지갑 로드 실패 (세션은 유지):",t),{success:!0,user:r,tokenSignatureVerified:!1}}}catch(e){const r=e instanceof x&&e.code===h.SESSION_EXPIRED;return d.log("[CROSSx] restoreSession —",r?"세션 만료 (재로그인 필요)":"세션 복원 실패:",e),this.tokenStore.clear(),r&&(this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN),await this.storage.remove(this.STORAGE_KEY_USER)),null}}silentRefresh(e){return this._refreshPromise&&this._lastRefreshToken===e?this._refreshPromise:(this._lastRefreshToken=e,this._refreshPromise=this._doSilentRefresh(e).finally(()=>{this._refreshPromise=null,this._lastRefreshToken=void 0}),this._refreshPromise)}async _doSilentRefresh(e){const{authApiUrl:r}=this.config,t=this.useCookieAuth,n=`${r}/cross-auth/social/refresh/simple`,i={};if(!t){const u=this.tokenStore.get()??"";u&&(i.access_token=u),e&&(i.refresh_token=e)}const o=await this.transport.request({url:n,method:"POST",headers:{"Content-Type":"application/json"},body:i,...t?{credentials:"include"}:{}});d.log("[CROSSx] silentRefresh 응답 — status:",o.status);const a=o.data,c=this.extractResponseErrorCode(a);if(c){const u=wt.REFRESH_RELOGIN_CODES.has(c.code);throw new x(u?h.SESSION_EXPIRED:h.AUTH_FAILED,`토큰 갱신 실패 (코드 ${c.code}): ${c.message}`)}const l=this.extractAccessToken(a);if(t&&!l){d.log("[CROSSx] silentRefresh 성공 (cookie 갱신)");return}if(!l)throw new x(h.AUTH_FAILED,"토큰 자동 갱신 실패: 응답에 토큰이 없습니다");if(this.tokenStore.set(l),!t){await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,l);const u=this.extractRefreshToken(a);u&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,u)}return d.log("[CROSSx] silentRefresh 성공"),l}async refreshAccessToken(){try{if(this.useCookieAuth)return!!await this.silentRefresh()||this.tokenStore.has();const e=await this.storage.get(this.STORAGE_KEY_REFRESH_TOKEN);return e?!!await this.silentRefresh(e):(d.warn("[CROSSx] refreshAccessToken: refresh_token 없음 — 갱신 불가"),!1)}catch(e){return e instanceof x&&e.code===h.SESSION_EXPIRED?(d.warn("[CROSSx] refreshAccessToken: 세션 만료 — 재로그인 필요"),this.tokenStore.clear(),this.useCookieAuth||await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)):d.warn("[CROSSx] refreshAccessToken 실패:",e),!1}}async executeWithJWT(e,r){let t,n=!1;try{let i=await this.crypto.verifyJWT(e);if(n=i.signatureVerified??!1,!i.valid){if(!r)return d.error("[CROSSx] signInWithJWT: access_token 검증 실패, refreshToken 없음"),{success:!1,error:"유효하지 않은 access token"};d.log("[CROSSx] signInWithJWT: access_token 만료, refreshToken으로 갱신 시도");const a=await this.silentRefresh(r);if(!a)return d.error("[CROSSx] signInWithJWT: silentRefresh 실패"),{success:!1,error:"access token이 만료되었고 갱신에 실패했습니다"};if(e=a,i=await this.crypto.verifyJWT(e),n=i.signatureVerified??!1,!i.valid)return d.error("[CROSSx] signInWithJWT: 갱신된 access_token도 유효하지 않음"),{success:!1,error:"갱신된 access token이 유효하지 않습니다"};d.log("[CROSSx] signInWithJWT: silentRefresh 성공, 새 access_token 사용")}const o=i.payload;d.log("[CROSSx] signInWithJWT — sub:",o.sub,"signatureVerified:",n),t={id:o.sub,email:o.email},this.tokenStore.set(e),this.useCookieAuth||(await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,e),r&&this.config.secureStorageAvailable!==!1&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,r)),await this.storage.set(this.STORAGE_KEY_USER,t),d.log("[CROSSx] signInWithJWT — 토큰 및 사용자 정보 저장 완료")}catch(i){return d.error("[CROSSx] signInWithJWT 에러:",i),{success:!1,error:i instanceof Error?i.message:"JWT sign in failed"}}return this.loadWallet(t,n)}async migrateStorageKeys(){if(!this._migrated){this._migrated=!0;try{const e=await this.storage.get(or);if(!e||await this.storage.get(this.STORAGE_KEY_USER))return;await this.storage.set(this.STORAGE_KEY_USER,e);const t=await this.storage.get(nr);t&&await this.storage.set(this.STORAGE_KEY_ACCESS_TOKEN,t);const n=await this.storage.get(ir);n&&await this.storage.set(this.STORAGE_KEY_REFRESH_TOKEN,n),await this.storage.remove(or),await this.storage.remove(nr),await this.storage.remove(ir),d.log("[CROSSx] 스토리지 키 마이그레이션 완료 (projectId 스코프)")}catch(e){d.warn("[CROSSx] 스토리지 키 마이그레이션 실패:",e)}}}async loadWallet(e,r){let t,n=!1;try{if(typeof this.walletProvider.checkWallet=="function"){d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인 (비밀번호 불필요)");const i=await this.walletProvider.checkWallet();if(d.log("[CROSSx] 지갑 상태:",i),i==="migration_required")d.log("[CROSSx] migration_required → needsMigration = true"),n=!0;else if(i==="exists")try{const o=await this.walletProvider.getAddresses(e.id);o.length>0?(t=o[0].address,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",t)):d.log("[CROSSx] 주소 캐시 없음 — createWallet 단계에서 비밀번호 입력 후 로드")}catch(o){d.warn("[CROSSx] getAddresses 실패, createWallet 단계에서 재시도:",o)}}else d.log("[CROSSx] getOrCreateWallet 직접 호출 (폴백)"),t=(await this.walletProvider.getOrCreateWallet(e.id)).address,d.log("[CROSSx] 지갑 로드 완료 — address:",t)}catch(i){if(i instanceof x&&i.code===h.MIGRATION_BACKUP_EXISTS)d.log("[CROSSx] MIGRATION_BACKUP_EXISTS 감지 → needsMigration = true"),n=!0;else{if(i instanceof x&&(i.code===h.PROJECT_NOT_REGISTERED||i.code===h.PROJECT_ID_MISSING||i.code===h.ORIGIN_NOT_ALLOWED))throw d.error("[CROSSx] 프로젝트 설정 에러:",i.message),i;d.warn("[CROSSx] 지갑 상태 확인 실패 (로그인은 유지):",i)}}return d.log("[CROSSx] loadWallet 결과 — address:",t,"needsMigration:",n),{success:!0,address:t,user:e,needsMigration:n,tokenSignatureVerified:r}}};wt.REFRESH_RELOGIN_CODES=new Set([1007,1008]);let St=wt;class Gs{constructor(e,r,t){this.config=e,this.storage=r,this.tokenStore=t;const n=e.projectId;this.STORAGE_KEY_ACCESS_TOKEN=`crossx_${n}_access_token`,this.STORAGE_KEY_REFRESH_TOKEN=`crossx_${n}_refresh_token`,this.STORAGE_KEY_USER=`crossx_${n}_user_info`}async execute(){this.tokenStore.clear(),this.config.authMode!=="cookie"&&(await this.storage.remove(this.STORAGE_KEY_ACCESS_TOKEN),await this.storage.remove(this.STORAGE_KEY_REFRESH_TOKEN)),await this.storage.remove(this.STORAGE_KEY_USER),await this.storage.clear()}}class qs{constructor(e,r){this.storage=e,this.walletProvider=r}async execute(e,r){if(!this.walletProvider.migrateWallet)throw new x(h.NOT_IMPLEMENTED,"현재 환경에서는 마이그레이션이 지원되지 않습니다");d.log("[CROSSx][Migration Phase 4] MigrateWalletUseCase.execute() — pin 길이:",e.length,"sub:",r);const t=await this.walletProvider.migrateWallet(e,r);return d.log("[CROSSx][Migration Phase 5] MigrateWalletUseCase 완료 — address:",t.address),{address:t.address}}}class vt{constructor(){this.encryptedBytes=null,this.xorKey=null}set(e){this.clear();const r=new TextEncoder().encode(e),t=new Uint8Array(r.length);crypto.getRandomValues(t);const n=new Uint8Array(r.length);for(let i=0;i<r.length;i++)n[i]=r[i]^t[i];r.fill(0),this.xorKey=t,this.encryptedBytes=n}get(){if(!this.encryptedBytes||!this.xorKey)return null;const e=new Uint8Array(this.encryptedBytes.length);for(let t=0;t<this.encryptedBytes.length;t++)e[t]=this.encryptedBytes[t]^this.xorKey[t];const r=new TextDecoder().decode(e);return e.fill(0),r}clear(){var e,r;(e=this.encryptedBytes)==null||e.fill(0),(r=this.xorKey)==null||r.fill(0),this.encryptedBytes=null,this.xorKey=null}has(){return this.encryptedBytes!==null}}class Js{constructor(e,r){this.chainRegistry=e,this.transport=r,this._nextId=1}async call(e,r,t){const n=await this.chainRegistry.getChain(t),i={jsonrpc:"2.0",method:e,params:r,id:this._nextId++},a=(await this.transport.request({url:n.rpcUrl,method:"POST",headers:{"Content-Type":"application/json"},body:i})).data;if(a!=null&&a.error)throw new x(h.UNKNOWN_ERROR,`RPC 오류 [${e}] (${t}): ${a.error.message} (코드: ${a.error.code})`);return a==null?void 0:a.result}}class Vs{constructor(){this.listeners=new Map}on(e,r){return this.listeners.has(e)||this.listeners.set(e,new Set),this.listeners.get(e).add(r),()=>this.off(e,r)}off(e,r){var t;(t=this.listeners.get(e))==null||t.delete(r)}emit(e,r){var t;(t=this.listeners.get(e))==null||t.forEach(n=>n(r))}removeAllListeners(){this.listeners.clear()}}var rt={environment:"production"};const We={production:{oauthServiceUrl:"https://cross-wallet-oauth.crosstoken.io",authApiUrl:"https://cross-auth.crosstoken.io",walletGatewayUrl:"https://embedded-wallet-gateway.crosstoken.io/api/v1"},staging:{oauthServiceUrl:"https://stg-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://stg-cross-auth.crosstoken.io",walletGatewayUrl:"https://stg-embedded-wallet-gateway.crosstoken.io/api/v1"},development:{oauthServiceUrl:"https://dev-cross-wallet-oauth.crosstoken.io",authApiUrl:"https://dev-cross-auth.crosstoken.io",walletGatewayUrl:"https://dev-embedded-wallet-gateway.crosstoken.io/api/v1"}};function zs(s){const e=s.environment;return e&&e in We?We[e]:null}function Ys(){try{if(typeof rt<"u"){const s=typeof rt=="string"?JSON.parse(rt):rt,e=zs(s);if(e)return e}}catch{}try{const s=process.env.NEXT_PUBLIC_CROSSX_ENVIRONMENT;if(s&&s in We)return We[s]}catch{}return We.production}const js=2e3,ar=6e4,Xs=1e3,Zs=1e4,Qs="0x77359400",cr="0x3B9ACA00",lr=130,dr=6,ur=18,hr=3e4,en=5*60*1e3,tn=30*1e3;function ze(s){const e=s.indexOf("@");if(e<0)return"***";const r=s.substring(0,e),t=s.substring(e);return r.length<=1?`${r}***${t}`:`${r[0]}***${t}`}const se=class se extends Vs{constructor(e,r,t,n,i,o,a,c,l,u,f){var g,p;super(),this.storage=t,this.crypto=n,this.transport=i,this.oauth=o,this.walletProvider=a,this.tokenStore=c,this.initialized=!1,this._initPromise=null,this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.loginType=null,this.providerSub=null,this.tokenSignatureVerified=!1,this._verifyPinMutex=null,this._themeMediaCleanup=null,this._isRecoveringSession=!1,this._config=Object.freeze({...e}),this.internalConfig=e,this.adapterConfig=r,e.logger&&rr(e.logger),this.confirmation=l,this.pinStore=f??new vt,this.chainRegistry=u,this.jsonRpc=new Js(u,i),this.signInUseCase=new St(this.internalConfig,t,n,o,i,a,c),this.signOutUseCase=new Gs(this.internalConfig,t,c),this.migrateWalletUseCase=new qs(t,a),(g=a.setOnUnauthorized)==null||g.call(a,()=>this.forceLogout()),(p=a.setTokenRefresher)==null||p.call(a,()=>this.signInUseCase.refreshAccessToken()),e.autoDetectTheme&&this._setupAutoDetectTheme()}get config(){return this._config}async initialize(e){return this.initialized?this.authenticated?{success:!0,address:this.address??void 0}:null:this._initPromise?this._initPromise:(this._initPromise=this._doInitialize(e).finally(()=>{this._initPromise=null}),this._initPromise)}async _doInitialize(e){var r,t;d.log("[CROSSx SDK] v1.4.3 초기화 중..."),this.confirmation.setMessages(Se(this._config.locale));try{const n=Ys();this.internalConfig.oauthServiceUrl=n.oauthServiceUrl,this.internalConfig.authApiUrl=n.authApiUrl,this.internalConfig.walletGatewayUrl=n.walletGatewayUrl,this.adapterConfig.gatewayUrl=n.walletGatewayUrl,(t=(r=this.crypto).setJWKSEndpoint)==null||t.call(r,`${n.authApiUrl}/.well-known/jwks.json`);const i=await this.signInUseCase.restoreSession();if(i!=null&&i.success){this.applyAuthResult(i);try{await this.loadWalletAfterAuth(e==null?void 0:e.preferredWalletIndex)}catch(o){if(!(o instanceof x&&o.code===h.PIN_CANCELLED))throw o;d.log("[CROSSx] initialize: 비밀번호 입력 취소 — 지갑 미로드 상태로 계속")}}return this.initialized=!0,d.info("[CROSSx SDK] v1.4.3 초기화 완료"),this.emit("initialized",{restored:!!(i!=null&&i.success)}),i??null}catch(n){throw new x(h.AUTH_NOT_INITIALIZED,"SDK 초기화에 실패했습니다",n)}}async signIn(e){if(this.ensureInitialized(),this.authenticated)throw new x(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");let r=e;if(!(e!=null&&e.provider)){const t=await this.confirmation.showLoginSelector({showConnectOtherWallets:this._config.showConnectOtherWallets});if(t==="external")throw this.emit("connectExternalWallet",{}),new x(h.EXTERNAL_WALLET_REQUESTED,"User requested external wallet connection");if(t===null)return{success:!1,error:"User cancelled login"};r={...e,provider:t}}try{const t=await this.signInUseCase.execute(r);return t.success&&this.applyAuthResult(t),t}catch(t){throw t instanceof x?t:new x(h.AUTH_FAILED,"로그인에 실패했습니다",t)}}async signInWithCreate(e){const r=await this.signIn(e);if(!r.success)return{...r,addresses:[]};try{if(r.needsMigration||!r.address){const{address:i}=await this.createWallet(),o=await this.getAddresses(),a=await this.selectWalletIfMultiple(o);return{...r,address:(a==null?void 0:a.address)??i,needsMigration:!1,addresses:o}}const t=await this.getAddresses(),n=await this.selectWalletIfMultiple(t);return{...r,address:(n==null?void 0:n.address)??r.address,addresses:t}}catch(t){throw t instanceof x&&t.code===h.PIN_CANCELLED&&(d.log("[CROSSx] signInWithCreate: 비밀번호 설정 취소 — 자동 로그아웃 진행"),await this.signOut().catch(n=>d.warn("[CROSSx] signInWithCreate: 자동 로그아웃 실패",n))),t}}async signInWithOAuthToken(e){if(this.ensureInitialized(),this.authenticated)throw new x(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const r=await this.signInUseCase.executeWithOAuthToken(e);return r.success&&this.applyAuthResult(r),r}catch(r){throw new x(h.AUTH_FAILED,"OAuth 토큰 로그인에 실패했습니다",r)}}async signInWithJWT(e,r){if(this.ensureInitialized(),this.authenticated)throw new x(h.ALREADY_AUTHENTICATED,"이미 로그인된 상태입니다. signOut()을 먼저 호출하세요.");try{const t=await this.signInUseCase.executeWithJWT(e,r);return t.success&&this.applyAuthResult(t),t}catch(t){throw new x(h.AUTH_FAILED,"JWT 로그인에 실패했습니다",t)}}async signOut(){this.ensureInitialized();try{await this.signOutUseCase.execute(),this.clearAuthState()}catch(e){throw new x(h.UNKNOWN_ERROR,"로그아웃에 실패했습니다",e)}}isAuthenticated(){return this.authenticated}async whenReady(){if(this.initialized)return!0;if(this._initPromise)try{return await this._initPromise,this.initialized}catch{return!1}return!1}get currentAddress(){return this.address}get currentUserId(){return this.userId}isLoggedIn(){return this.isAuthenticated()}async ensureLoggedIn(){if(!this.initialized)return!1;if(this.authenticated)return!0;try{const e=await this.signInUseCase.restoreSession();if(e!=null&&e.success){this.applyAuthResult(e);try{await this.loadWalletAfterAuth()}catch(r){r instanceof x&&r.code===h.PIN_CANCELLED||d.warn("[CROSSx] ensureLoggedIn: loadWalletAfterAuth 실패:",r)}return!0}return!1}catch{return!1}}async getUserInfo(){return this.ensureAuthenticated(),{id:this.userId,email:this.userEmail??void 0,loginType:this.loginType??void 0,addresses:this.address?[this.address]:[],tokenSignatureVerified:this.tokenSignatureVerified}}async migrateWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");try{const r=await this.migrateWalletUseCase.execute(e,this.userId);return this.address=r.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:r.address,index:0}),d.log("[CROSSx] migrateWallet 완료 — address:",r.address),r}catch(r){throw r instanceof x?r:new x(h.MIGRATION_FAILED,"지갑 마이그레이션에 실패했습니다",r)}}async getAddress(e){if(e!==void 0){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");return{address:(await this.walletProvider.getAddress(this.userId,e)).address,index:e}}return!this.authenticated||!this.address?null:{address:this.address,index:this.activeWalletIndex}}async getAddresses(){if(this.ensureAuthenticated(),!this.userId)return[];const e=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));return e.length===0&&this.address?[{address:this.address,index:0}]:e}async selectWallet(e){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");let r=await this.withSessionRecovery(()=>this.walletProvider.getAddresses(this.userId));r.length===0&&this.address&&(r=[{address:this.address,index:0}]);const t=await this.confirmation.showWalletSelector(r,async()=>{await this.ensurePinForSigning();const n=r.length,o={address:(await this.withPinRetry(()=>this.withSessionRecovery(()=>this.walletProvider.getAddress(this.userId,n)))).address,index:n};return r.push(o),o},e);return t&&(this.address=t.address,this.activeWalletIndex=t.index,this.emit("addressChanged",{address:t.address,index:t.index})),t}async selectWalletIfMultiple(e){return e.length<2?null:this.selectWallet()}async getChains(){this.ensureInitialized();try{return await this.chainRegistry.getChains()}catch(e){throw e instanceof x?e:new x(h.UNKNOWN_ERROR,"체인 목록 조회에 실패했습니다",e)}}async getChain(e){this.ensureInitialized();try{return await this.chainRegistry.getChain(e)}catch(r){throw r instanceof x?r:new x(h.CHAIN_NOT_SUPPORTED,`체인 조회에 실패했습니다: ${e}`,r)}}_setupAutoDetectTheme(){if(typeof window>"u"||!window.matchMedia)return;const e=window.matchMedia("(prefers-color-scheme: dark)"),r=n=>{const i=n?"dark":"light";this.applyTheme(i,this._config.themeTokens??{})};r(e.matches);const t=n=>r(n.matches);e.addEventListener("change",t),this._themeMediaCleanup=()=>e.removeEventListener("change",t)}applyTheme(e=this._config.theme??"light",r=this._config.themeTokens??{}){this._config=Object.freeze({...this._config,theme:e,themeTokens:r}),this.confirmation.setTheme(e,r)}applyLocale(e=this._config.locale??"en"){this._config=Object.freeze({...this._config,locale:e}),this.confirmation.setMessages(Se(e))}async createWallet(){return this.withSessionRecovery(()=>this._createWallet())}async _createWallet(){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");d.log("[CROSSx] createWallet 시작");const e=await this.fetchWalletStatus();if(d.log("[CROSSx] 지갑 상태:",e),e==="migration_required"){const r=this.providerSub??this.userId;d.log("[CROSSx] migration_required → 마이그레이션 UI 시작 — sub:",r);const t=await this.handleMigrationFlow(r);if(t)return this.address=t.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:t.address,index:0}),{address:t.address};throw new x(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}if(e==="exists"){await this.ensureVerifiedPin();try{const r=await this.withPinRetry(()=>this.walletProvider.getOrCreateWallet(this.userId));return this.address=r.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:r.address,index:0}),d.log("[CROSSx] 지갑 준비 완료:",r.address),{address:r.address}}catch(r){if(r instanceof x&&r.code===h.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new x(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw r}}await this.ensurePinSetup();try{const r=await this.walletProvider.getOrCreateWallet(this.userId);return this.address=r.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:r.address,index:0}),d.log("[CROSSx] 지갑 준비 완료:",r.address),{address:r.address}}catch(r){if(r instanceof x&&r.code===h.MIGRATION_BACKUP_EXISTS){const t=this.providerSub??this.userId;d.log("[CROSSx] MIGRATION_BACKUP_EXISTS (폴백) → 마이그레이션 UI 시작");const n=await this.handleMigrationFlow(t);if(n)return this.address=n.address,this.activeWalletIndex=0,this.emit("addressChanged",{address:n.address,index:0}),{address:n.address};throw new x(h.MIGRATION_FAILED,"사용자가 마이그레이션을 건너뛰었습니다")}throw r}}async fetchWalletStatus(){if(typeof this.walletProvider.checkWallet=="function")try{return await this.walletProvider.checkWallet()}catch(e){return d.warn("[CROSSx] checkWallet 실패 (폴백: not_found 처리):",e),"not_found"}return null}async signMessage(e,r,t){return this.withSessionRecovery(()=>this._signMessage(e,r,t))}async _signMessage(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.resolveAddress(t==null?void 0:t.index);if(!await this.confirmation.requestConfirmation({type:"sign-message",chainId:e,from:n.address,message:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new x(h.USER_REJECTED,"User rejected the message signing request");try{const o=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-message",{message:r,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signMessage(this.userId,e,r,t==null?void 0:t.index,a,n.address)});return this.verifySignatureSigner(r,o.signature,n.address),{chainId:e,signature:o.signature,message:r,address:n.address}}catch(o){throw o instanceof x?o:new x(h.SIGNATURE_FAILED,`메시지 서명에 실패했습니다 (${e})`,o)}}async signTypedData(e,r,t){return this.withSessionRecovery(()=>this._signTypedData(e,r,t))}async _signTypedData(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");if(!this.walletProvider.signTypedData)throw new x(h.NOT_IMPLEMENTED,"signTypedData가 구현되어 있지 않습니다");se.validateTypedDataChainId(e,r);const n=await this.resolveAddress(t==null?void 0:t.index);if(!await this.confirmation.requestConfirmation({type:"sign-typed-data",chainId:e,from:n.address,typedData:r,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new x(h.USER_REJECTED,"User rejected the typed data signing request");try{const o=await this.withPinRetry(async()=>{let a;return this.walletProvider.prepare&&(a=(await this.walletProvider.prepare("sign-typed-data",{typedData:r,from:n.address})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTypedData(this.userId,e,r,t==null?void 0:t.index,a,n.address)});return se.validateSignatureFormat(o.signature),{chainId:e,signature:o.signature,address:n.address}}catch(o){throw o instanceof x?o:new x(h.SIGNATURE_FAILED,`타입 데이터 서명에 실패했습니다 (${e})`,o)}}async signTypedDataOffchain(e,r){return this.signTypedData(se.OFFCHAIN_CHAIN_ID,e,r)}async signTransaction(e,r,t){return this.withSessionRecovery(()=>this._signTransaction(e,r,t))}async _signTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=bt(e);if(!await this.confirmation.requestConfirmation({type:"sign",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new x(h.USER_REJECTED,"User rejected the transaction signing request");try{const a=await this.withPinRetry(async()=>{let c;return this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("sign",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c)});return se.validateSignedTxFormat(a.signature),{chainId:e,signedTx:a.signature,txHash:a.txHash??""}}catch(a){if(a instanceof x)throw a;const c=a instanceof Error?a.message:String(a);throw new x(h.SIGNATURE_FAILED,`트랜잭션 서명에 실패했습니다 (${e}): ${c}`,a)}}async sendTransaction(e,r,t){return this.withSessionRecovery(()=>this._sendTransaction(e,r,t))}async _sendTransaction(e,r,t){if(this.ensureAuthenticated(),!this.userId)throw new x(h.AUTH_NOT_AUTHENTICATED,"사용자 ID를 찾을 수 없습니다");const n=await this.withResolvedGasAndFee(r,e);n.from||(n.from=(await this.resolveAddress(t==null?void 0:t.index)).address);const i=bt(e);if(!await this.confirmation.requestConfirmation({type:"send",chainId:e,from:n.from,to:n.to,value:n.value,data:n.data,gasLimit:n.gasLimit,gasPrice:n.gasPrice,maxFeePerGas:n.maxFeePerGas,maxPriorityFeePerGas:n.maxPriorityFeePerGas,nativeSymbol:i.symbol,nativeDecimals:i.decimals,dappName:(t==null?void 0:t.dappName)??this._config.appName,accountName:t==null?void 0:t.accountName}))throw new x(h.USER_REJECTED,"User rejected the transaction request");try{const a=await this.withPinRetry(async()=>{let c;if(this.walletProvider.prepare&&(c=(await this.walletProvider.prepare("send",{tx:n})).uuid),await this.ensureVerifiedPin(),this.walletProvider.sendTransaction)return(await this.walletProvider.sendTransaction(this.userId,e,n,c)).txHash;const l=await this.walletProvider.signTransaction(this.userId,e,n,t==null?void 0:t.index,c);return l.txHash??l.signature});return{chainId:e,txHash:a,status:"pending"}}catch(a){if(a instanceof x)throw a;const c=a instanceof Error?a.message:String(a);throw new x(h.TRANSACTION_FAILED,`트랜잭션 전송에 실패했습니다 (${e}): ${c}`,a)}}async getTransactionReceipt(e,r){try{return await this.jsonRpc.call("eth_getTransactionReceipt",[e],r)??null}catch{return null}}async waitForTxAndGetReceipt(e,r,t={}){const n=t.intervalMs??Xs,i=Zs,o=t.timeoutMs??ar,a=Date.now()+o;let c=n;for(;Date.now()<a;){const l=await this.getTransactionReceipt(e,r);if(l)return l;await new Promise(u=>setTimeout(u,c)),c=Math.min(c*2,i)}throw new x(h.UNKNOWN_ERROR,`트랜잭션 영수증 조회 시간이 초과되었습니다 (${e})`)}async sendTransactionWithWaitForReceipt(e,r,t={}){var v,S;const{intervalMs:n,timeoutMs:i,...o}=t,{txHash:a}=await this.sendTransaction(e,r,o),c=n??((v=this._config.receiptPolling)==null?void 0:v.intervalMs)??js,l=i??((S=this._config.receiptPolling)==null?void 0:S.timeoutMs)??ar,u=bt(e),f=r.from??"";let g,p;const y=this.waitForTxAndGetReceipt(a,e,{intervalMs:c,timeoutMs:l}).then(I=>{g=I;const T=BigInt(I.gasUsed)*BigInt(I.effectiveGasPrice),H=r.value?BigInt(r.value):0n,L=se.formatTxAmount(r.value,u.symbol,u.decimals),V=se.formatTxAmount("0x"+T.toString(16),u.symbol,u.decimals),B=se.formatTxAmount("0x"+(H+T).toString(16),u.symbol,u.decimals);return{chainId:e,txHash:a,from:I.from,to:I.to??r.to,amount:L,fees:V,total:B,nativeSymbol:u.symbol,status:I.status==="0x1"?"success":"reverted"}}).catch(I=>(p=I instanceof Error?I:new Error(String(I)),{chainId:e,txHash:a,from:f,to:r.to,amount:se.formatTxAmount(r.value,u.symbol,u.decimals),nativeSymbol:u.symbol,status:"timeout"}));if(await this.confirmation.showTransactionProgress({chainId:e,txHash:a,from:f,to:r.to},y),p)throw p;return{chainId:e,txHash:a,receipt:g}}setPin(e){this.pinStore.set(e)}clearPin(){this.pinStore.clear()}hasPin(){return this.pinStore.has()}async changePin(e,r){this.ensureAuthenticated();const t=this.walletProvider;if(typeof t.changePin!="function")throw new x(h.NOT_IMPLEMENTED,"changePin이 구현되어 있지 않습니다");this.pinStore.set(e);try{await t.changePin(e,r),this.pinStore.set(r),d.log("[CROSSx] PIN 변경 완료")}catch(n){throw n instanceof x?n:new x(h.UNKNOWN_ERROR,"PIN 변경에 실패했습니다",n)}}async getGasPrice(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_gasPrice",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new x(h.GAS_ESTIMATION_FAILED,`가스 가격 조회에 실패했습니다 (${e}): ${t}`,r)}}async estimateGas(e,r){this.ensureAuthenticated();const t={};e.from&&(t.from=e.from),e.to&&(t.to=e.to),e.value&&(t.value=e.value),e.data&&(t.data=e.data),e.gasPrice&&(t.gasPrice=e.gasPrice),e.maxFeePerGas&&(t.maxFeePerGas=e.maxFeePerGas),e.maxPriorityFeePerGas&&(t.maxPriorityFeePerGas=e.maxPriorityFeePerGas),e.nonce!==void 0&&(t.nonce="0x"+e.nonce.toString(16));try{return await this.walletRpc("eth_estimateGas",[t],r)}catch(n){const i=n instanceof Error?n.message:String(n);throw new x(h.GAS_ESTIMATION_FAILED,`가스 추정에 실패했습니다 (${r}): ${i}`,n)}}async getBaseFeePerGas(e){this.ensureAuthenticated();try{const r=await this.walletRpc("eth_getBlockByNumber",["latest",!1],e);return(r==null?void 0:r.baseFeePerGas)??null}catch(r){const t=r instanceof Error?r.message:String(r);throw new x(h.GAS_ESTIMATION_FAILED,`baseFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getMaxPriorityFeePerGas(e){this.ensureAuthenticated();try{return await this.walletRpc("eth_maxPriorityFeePerGas",[],e)}catch(r){const t=r instanceof Error?r.message:String(r);throw new x(h.GAS_ESTIMATION_FAILED,`maxPriorityFeePerGas 조회에 실패했습니다 (${e}): ${t}`,r)}}async getNonce(e){this.ensureAuthenticated();const r=this.address;if(!r)return 0;try{const t=await this.jsonRpc.call("eth_getTransactionCount",[r,"pending"],e);return parseInt(t??"0x0",16)}catch(t){if(t instanceof x)throw t;const n=t instanceof Error?t.message:String(t);throw new x(h.UNKNOWN_ERROR,`Nonce 조회에 실패했습니다: ${n}`,t)}}async getBalance(e){this.ensureAuthenticated();const r=this.address;if(!r)return{wei:"0x0",formatted:"0",chainId:e};try{const n=await this.jsonRpc.call("eth_getBalance",[r,"latest"],e)??"0x0";return{wei:n,formatted:se.formatWei(n),chainId:e}}catch(t){if(t instanceof x)throw t;const n=t instanceof Error?t.message:String(t);throw new x(h.UNKNOWN_ERROR,`잔액 조회에 실패했습니다 (${e}): ${n}`,t)}}static formatWei(e){if(!e||e==="0x0"||e==="0x")return"0";try{const r=BigInt(e);if(r===0n)return"0";const t=10n**BigInt(ur),n=r/t,o=(r%t).toString().padStart(ur,"0").replace(/0+$/,"").slice(0,dr);return o?`${n}.${o}`:`${n}`}catch{return"?"}}getProvider(e){return this.ensureAuthenticated(),new tr(this,e)}async walletRpc(e,r,t){this.ensureAuthenticated();try{return await this.jsonRpc.call(e,r,t)}catch(n){if(n instanceof x)throw n;const i=n instanceof Error?n.message:String(n);throw new x(h.UNKNOWN_ERROR,`walletRpc 호출에 실패했습니다 [${e}] (${t}): ${i}`,n)}}static formatTxAmount(e,r,t){if(!(!e||e==="0x"||e==="0x0"))try{const n=BigInt(e);if(n===0n)return;const i=10n**BigInt(t),o=n/i,c=(n%i).toString().padStart(t,"0").slice(0,dr).replace(/0+$/,"");return`${c?`${o}.${c}`:`${o}`} ${r}`}catch{return}}async handleMigrationFlow(e){var c,l,u;d.log('[CROSSx][Migration Phase 3] "Wallet Found" 팝업 표시');const r=((c=this._config.migration)==null?void 0:c.allowSkip)??!0,t=await this.confirmation.showMigrationFoundPrompt({allowSkip:r});if(d.log("[CROSSx][Migration Phase 3] 사용자 선택:",t),t==="skip")return d.log("[CROSSx][Migration Phase 3] 사용자가 마이그레이션을 건너뜀 → 종료"),null;let n,i=0,o=5,a=null;for(;;){i++,d.log(`[CROSSx][Migration Phase 4] PIN 입력 팝업 표시 (시도 #${i}/${o})`,n?`— 이전 메시지: ${n}`:"");const f=await this.confirmation.showRecoveryPinInputPrompt({errorMessage:n,attemptCount:i>1?i-1:void 0,maxAttempts:o});if(f===null)return d.log("[CROSSx][Migration Phase 4] 사용자가 PIN 입력을 취소함 → 종료"),null;d.log("[CROSSx][Migration Phase 4] PIN 입력 완료 — verify-recovery-pin API 호출"),n=void 0;try{const g=await((u=(l=this.walletProvider).verifyRecoveryPin)==null?void 0:u.call(l,f,e));if(!g){d.log("[CROSSx][Migration Phase 4] verifyRecoveryPin 미지원 — PIN 검증 생략"),a=f;break}if(g.valid){d.log("[CROSSx][Migration Phase 4] PIN 검증 성공"),a=f;break}const p=g.pinStatus;if(o=p.maxAttempts,i=o-p.remainingAttempts,p.remainingAttempts===0&&p.lockExpiresAt){const y=p.lockExpiresAt*1e3,v=Math.max(1,Math.round((y-Date.now())/1e3)),S=v<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 잠금 — ${v}초, 메시지: ${S}`),await this.confirmation.showRecoveryPinLockedPrompt(v,S),i=0,n="Your account lock has been lifted. You may try again."}else d.warn(`[CROSSx][Migration Phase 4] PIN 불일치 (시도 ${i}/${o})`),n="Incorrect PIN."}catch(g){if(!(g instanceof x))throw g;if(g.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 4] 세션 만료 — 재로그인 후 PIN 입력 재시도");const p=Se(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:p.sessionAlert_title,message:p.alert_sessionExpired,email:this.userEmail?ze(this.userEmail):void 0})==="signin-again"&&(await this.signInAgain()).success){d.log("[CROSSx][Migration Phase 4] 재로그인 성공 — PIN 입력 루프 계속"),i--;continue}throw this.clearAuthState(),g}if(g.code===h.MIGRATION_PIN_LOCKED){const p=g.details;if(o=(p==null?void 0:p.maxAttempts)??5,(p==null?void 0:p.permanent)===!0)return d.warn("[CROSSx][Migration Phase 4] PIN 영구 잠금 (verify-recovery-pin)"),await this.confirmation.showRecoveryPinLockedPrompt(0,"Your account has been permanently locked due to too many failed attempts."),null;const y=((p==null?void 0:p.lockExpiresAt)??0)*1e3,v=Math.max(1,Math.round((y-Date.now())/1e3)),S=v<=1800?"Too many failed attempts. Please try again in 30 minutes.":"Too many failed attempts. Please try again in 24 hours.";d.warn(`[CROSSx][Migration Phase 4] verify-recovery-pin 이미 잠금 — ${v}초`),await this.confirmation.showRecoveryPinLockedPrompt(v,S),i=0,n="Your account lock has been lifted. You may try again."}else throw d.error("[CROSSx][Migration Phase 4] verify-recovery-pin 실패 (복구 불가):",g),g}}d.log("[CROSSx][Migration Phase 5] PIN 검증 완료 — 비밀번호 설정 및 마이그레이션 진행");try{await this.ensurePinSetup();const f=await this.migrateWalletUseCase.execute(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 성공 — address:",f.address),f}catch(f){if(f instanceof x&&f.code===h.MIGRATION_FAILED)return d.warn("[CROSSx][Migration Phase 5] migrate PIN 불일치 (경합) — 처음부터 재시도"),this.handleMigrationFlow(e);if(f instanceof x&&f.code===h.SESSION_EXPIRED){d.warn("[CROSSx][Migration Phase 5] 세션 만료 — 재로그인 후 마이그레이션 재시도");const g=Se(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:g.sessionAlert_title,message:g.alert_sessionExpired,email:this.userEmail?ze(this.userEmail):void 0})==="signin-again"&&(await this.signInAgain()).success){d.log("[CROSSx][Migration Phase 5] 재로그인 성공 — 마이그레이션 재시도 (검증된 PIN 유지)");try{const v=await this.migrateWalletUseCase.execute(a,e);return d.log("[CROSSx][Migration Phase 5] 마이그레이션 재시도 성공 — address:",v.address),v}catch(v){throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 재시도 실패:",v),v}}throw this.clearAuthState(),f}throw d.error("[CROSSx][Migration Phase 5] 마이그레이션 실패 (복구 불가):",f),f}}async withResolvedGasAndFee(e,r){const t=p=>!(p!=null&&p.trim()),n=e.nonce===void 0||e.nonce===null,i=t(e.gasLimit),o=t(e.gasPrice)&&t(e.maxFeePerGas),a=!t(e.maxFeePerGas)&&t(e.maxPriorityFeePerGas);if(!n&&!i&&!o&&!a)return e;const c={...e},l=n?c.from??this.address:void 0;l&&d.log("[CROSSx] nonce 비어있음 → eth_getTransactionCount 호출 (from:",l,")"),i&&d.log("[CROSSx] gasLimit 비어있음 → eth_estimateGas 호출"),o&&d.log("[CROSSx] gasPrice & maxFeePerGas 비어있음 → baseFee 조회로 Dynamic/Legacy 판별");const[u,f,g]=await Promise.all([l?this.jsonRpc.call("eth_getTransactionCount",[l,"pending"],r):null,i?this.estimateGas(e,r):null,o?this.getBaseFeePerGas(r):null]);if(l&&(c.nonce=parseInt(u??"0x0",16),d.log("[CROSSx] nonce 결과:",c.nonce)),i&&(c.gasLimit=f,d.log("[CROSSx] estimateGas 결과:",c.gasLimit)),o){const p=g;if(p){const y=cr;c.maxFeePerGas="0x"+(BigInt(p)+BigInt(y)).toString(16),c.maxPriorityFeePerGas=y,d.log("[CROSSx] Dynamic 체인 감지 — baseFee:",p,"maxFeePerGas:",c.maxFeePerGas,"maxPriorityFeePerGas: 1 Gwei")}else c.gasPrice=Qs,d.log("[CROSSx] Legacy 체인 감지 — gasPrice: 2 Gwei")}return!o&&a&&(c.maxPriorityFeePerGas=cr,d.log("[CROSSx] maxPriorityFeePerGas 비어있음 → 1 Gwei 기본값 적용")),c}static validateTypedDataChainId(e,r){const t=se.extractDomainChainId(r);if(e==="0"){if(t!==void 0&&t!==0)throw new x(h.TYPED_DATA_CHAIN_ID_MISMATCH,`오프체인 서명(chainId=0)에서는 typedData.domain.chainId가 없거나 0이어야 합니다. 현재 값: ${t}`);return}const n=e.match(/^eip155:(\d+)$/);if(n){const i=Number(n[1]);if(t===void 0)throw new x(h.TYPED_DATA_CHAIN_ID_MISMATCH,`온체인 서명(${e})에서는 typedData.domain.chainId가 반드시 있어야 합니다`);if(t!==i)throw new x(h.TYPED_DATA_CHAIN_ID_MISMATCH,`typedData.domain.chainId (${t})가 chainId (${e}, 예상값: ${i})와 일치하지 않습니다`)}}static extractDomainChainId(e){if(e==null||typeof e!="object")return;const r=e.domain;if(r==null||typeof r!="object")return;const t=r.chainId;if(t==null)return;const n=Number(t);return Number.isFinite(n)?n:void 0}static validateSignatureFormat(e){const r=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(r))throw new x(h.SIGNATURE_FAILED,"유효하지 않은 서명: 올바른 hex 문자열이 아닙니다");if(r.length!==lr)throw new x(h.SIGNATURE_FAILED,`서명 길이가 유효하지 않습니다: ${lr} hex 문자(65 바이트) 예상, 현재 ${r.length}`)}static validateSignedTxFormat(e){const r=e.startsWith("0x")?e.slice(2):e;if(!/^[0-9a-fA-F]+$/.test(r))throw new x(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 올바른 hex 문자열이 아닙니다");if(r.length<2)throw new x(h.SIGNATURE_FAILED,"유효하지 않은 서명된 트랜잭션: 너무 짧습니다")}verifySignatureSigner(e,r,t){if(this.crypto.recoverPersonalSignSigner)try{const n=this.crypto.recoverPersonalSignSigner(e,r);if(n.toLowerCase()!==t.toLowerCase())throw d.error("[CROSSx] 서명 검증 실패: 서명자 주소 불일치",{expected:t,recovered:n}),new x(h.SIGNATURE_SIGNER_MISMATCH,`서명자 주소가 일치하지 않습니다: 예상 ${t}, 복원된 주소 ${n}`);d.log("[CROSSx] 서명 ecrecover 검증 성공")}catch(n){if(n instanceof x)throw n;d.warn("[CROSSx] ecrecover 검증 중 예외 (무시):",n)}}applyAuthResult(e){var r,t,n,i;this.authenticated=e.success,this.userId=((r=e.user)==null?void 0:r.id)??null,this.address=e.address??null,this.activeWalletIndex=0,this.userEmail=((t=e.user)==null?void 0:t.email)??null,this.providerSub=((n=e.user)==null?void 0:n.providerSub)??null,this.loginType=se.normalizeLoginType((i=e.user)==null?void 0:i.signInProvider),this.tokenSignatureVerified=e.tokenSignatureVerified??!1,this._isRecoveringSession||this.emit("authChanged",{isAuthenticated:this.authenticated,address:this.address,userId:this.userId})}clearAuthState(){this.authenticated=!1,this.userId=null,this.address=null,this.activeWalletIndex=0,this.userEmail=null,this.providerSub=null,this.loginType=null,this.tokenSignatureVerified=!1,this.pinStore.clear(),this._isRecoveringSession||this.emit("authChanged",{isAuthenticated:!1,address:null,userId:null})}forceLogout(){this.authenticated&&(d.warn("[CROSSx] 강제 로그아웃 (Gateway -10002/-10033)"),this.clearAuthState())}async signInAgain(){var n,i;this.ensureInitialized();const e=this.providerSub,r=this.userId,t=this.loginType;this._isRecoveringSession=!0;try{this.authenticated=!1,this.tokenStore.clear();const o=t?{provider:t}:void 0;let a;try{a=await this.signInUseCase.execute(o)}catch(f){throw this.clearAuthState(),f}if(!a.success)return this.clearAuthState(),a;const c=((n=a.user)==null?void 0:n.providerSub)??null,l=((i=a.user)==null?void 0:i.id)??null;if(!(e?!!c&&c===e:r?!!l&&r===l:!0)){d.warn("[CROSSx] signInAgain: providerSub/userId 불일치 — 잘못된 계정으로 로그인됨"),await this.signOutUseCase.execute().catch(()=>{});const f=Se(this._config.locale??"en");return await this.confirmation.showSessionAlert({title:f.sessionAlert_title,message:f.alert_differentAccount,email:this.userEmail?ze(this.userEmail):void 0})==="signin-again"?(this._isRecoveringSession=!1,this.signInAgain()):(this.clearAuthState(),{success:!1,error:"Different account signed in"})}this.applyAuthResult(a);try{await this.loadWalletAfterAuth()}catch{d.warn("[CROSSx] signInAgain: loadWalletAfterAuth 실패 (로그인은 유지)")}return d.log("[CROSSx] signInAgain: 세션 복구 성공"),a}finally{this._isRecoveringSession=!1}}async withSessionRecovery(e){try{return await e()}catch(r){const t=Se(this._config.locale??"en"),n=this.userEmail?ze(this.userEmail):void 0;if(r instanceof x&&r.code===h.WITHDRAW_FAILED){if(d.warn("[CROSSx] WITHDRAW_FAILED — 로컬 인증 초기화"),await this.confirmation.showSessionAlert({title:t.sessionAlert_title,message:t.alert_accountWithdrawn,email:n})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.clearAuthState(),r}if(r instanceof x&&r.code===h.WALLET_NOT_FOUND){if(d.warn("[CROSSx] WALLET_NOT_FOUND — 로컬 인증 초기화"),await this.confirmation.showSessionAlert({title:t.sessionAlert_title,message:t.alert_walletNotFound,email:n})==="signin-again"&&(await this.signInAgain()).success)return e();throw this.clearAuthState(),r}if(!(r instanceof x)||r.code!==h.SESSION_EXPIRED)throw r;if(d.warn("[CROSSx] SESSION_EXPIRED 감지 — 자동 재인증 시도"),await this.confirmation.showSessionAlert({title:t.sessionAlert_title,message:t.alert_sessionExpired,email:n})==="signout")throw this.clearAuthState(),new x(h.SESSION_EXPIRED,"세션이 만료되었습니다. 다시 로그인해 주세요.");const o=await this.signInAgain();if(!o.success)throw new x(h.SESSION_EXPIRED,o.error??"세션이 만료되었습니다. 다시 로그인해 주세요.");return e()}}static normalizeLoginType(e){return e?e.includes("google")?"google":e.includes("apple")?"apple":e:null}async ensurePinSetup(){if(this.pinStore.has())return;const e=await this.confirmation.showPinSetupPrompt();if(!e)throw new x(h.PIN_CANCELLED,"사용자가 PIN 설정을 취소했습니다");this.pinStore.set(e),d.log("[CROSSx] PIN 설정 완료 (메모리 캐시)")}async ensurePinForSigning(e){if(this.pinStore.has()&&!e)return;e&&this.pinStore.clear();const r=await this.confirmation.showPinInputPrompt({errorMessage:e});if(!r)throw new x(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(r),d.log("[CROSSx] PIN 입력 완료 (메모리 캐시)")}async ensureVerifiedPin(e,r,t,n){if(e)this.pinStore.clear();else if(this.pinStore.has())return;if(this._verifyPinMutex&&!e){d.log("[CROSSx] ensureVerifiedPin: 진행 중인 검증 대기"),await this._verifyPinMutex;return}let i,o;this._verifyPinMutex=new Promise((c,l)=>{i=c,o=l});const a=Se(this._config.locale??"en");try{if(typeof this.walletProvider.verifyPin!="function"){const l=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n});if(!l)throw new x(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(l),d.log("[CROSSx] PIN 캐시 완료 (verifyPin 미지원, 로컬 전용)"),i();return}const c=await this.confirmation.showPinInputPrompt({verifyMode:!0,errorMessage:e,lockExpiresAt:r,attemptCount:t,maxAttempts:n,onSubmit:async l=>{this.pinStore.set(l);try{return await this.walletProvider.verifyPin(l)?(d.log("[CROSSx] PIN 서버 검증 완료 (verify-password)"),{ok:!0}):(this.pinStore.clear(),{ok:!1,error:a.pinInput_error})}catch(u){if(this.pinStore.clear(),u instanceof x){if(u.code===h.PIN_WRONG)return{ok:!1,error:a.pinInput_error};if(u.code===h.PIN_INVALID)return{ok:!1,error:u.message};if(u.code===h.PIN_LOCKED)return se.buildPinLockedResult(u,a)}throw u}}});if(!c)throw new x(h.PIN_CANCELLED,"사용자가 PIN 입력을 취소했습니다");this.pinStore.set(c),d.log("[CROSSx] PIN 갱신 완료 (verify 모달 닫힘)"),i()}catch(c){if(c instanceof x&&(c.code===h.AUTH_NOT_AUTHENTICATED||c.code===h.AUTH_TOKEN_EXPIRED||c.code===h.SESSION_EXPIRED)&&c.code!==h.SESSION_EXPIRED){const l=Se(this._config.locale??"en");if(await this.confirmation.showSessionAlert({title:l.sessionAlert_title,message:l.alert_sessionExpired,email:this.userEmail?ze(this.userEmail):void 0})==="signin-again"&&(await this.signInAgain()).success)throw o(c),c}throw o(c),c}finally{this._verifyPinMutex=null}}static buildPinLockedResult(e,r){const t=e.details;if(t!=null&&t.permanent)return{ok:!1,error:r.pinLocked_permanent};if((t==null?void 0:t.remainingAttempts)!=null&&t.remainingAttempts>0&&t.maxAttempts){const n=t.maxAttempts-t.remainingAttempts;return{ok:!1,error:r.pinInput_error,attemptCount:n,maxAttempts:t.maxAttempts}}return{ok:!1,error:"Too many failed attempts. Your account is temporarily locked.",lockExpiresAt:t==null?void 0:t.lockExpiresAt}}async loadWalletAfterAuth(e){if(!this.userId)return;const r=await this.fetchWalletStatus();if(d.log("[CROSSx] loadWalletAfterAuth 지갑 상태:",r),r!=="exists")return;const t=await this.walletProvider.getAddresses(this.userId);if(t.length>0){const i=e!==void 0?t.find(o=>o.index===e)??t[0]:t[0];this.address=i.address,this.activeWalletIndex=i.index,d.log("[CROSSx] 캐시된 주소 로드 완료 (비밀번호 불필요):",this.address),this.emit("addressChanged",{address:i.address,index:i.index});return}d.log("[CROSSx] 주소 캐시 없음 — 비밀번호 확인 후 address(0) 조회"),await this.ensureVerifiedPin();const n=await this.walletProvider.getAddress(this.userId,0);this.address=n.address,this.activeWalletIndex=0,d.log("[CROSSx] 세션 복원 후 지갑 주소 로드 완료:",this.address),this.emit("addressChanged",{address:n.address,index:0})}async withPinRetry(e){const r=Se(this._config.locale??"en");let t,n,i,o;const a=c=>{if(c.code===h.PIN_WRONG)return t=r.pinInput_error,n=void 0,i=void 0,o=void 0,!0;if(c.code===h.PIN_INVALID)return t=c.message,n=void 0,i=void 0,o=void 0,!0;if(c.code===h.PIN_LOCKED){const l=c.details;return l!=null&&l.permanent?(t=r.pinLocked_permanent,n=void 0,i=void 0,o=void 0):(l==null?void 0:l.remainingAttempts)!=null&&l.remainingAttempts>0&&l.maxAttempts?(t=r.pinInput_error,n=void 0,i=l.maxAttempts-l.remainingAttempts,o=l.maxAttempts):(t="Too many failed attempts. Your account is temporarily locked.",n=l==null?void 0:l.lockExpiresAt,i=void 0,o=void 0),!0}return!1};try{return await e()}catch(c){if(!(c instanceof x&&a(c)))throw c}for(;;){d.warn("[CROSSx] PIN 불일치/잠금 — 재입력 요청:",t),this.pinStore.clear(),await this.ensureVerifiedPin(t,n,i,o),n=void 0,i=void 0,o=void 0;try{return await e()}catch(c){if(c instanceof x&&a(c))continue;throw c}}}async resolveAddress(e){if(e===void 0||e===this.activeWalletIndex){if(!this.address)throw new x(h.AUTH_NOT_AUTHENTICATED,"활성 지갑 주소를 찾을 수 없습니다");return{address:this.address,index:this.activeWalletIndex}}return{address:(await this.withPinRetry(()=>this.walletProvider.getAddress(this.userId,e))).address,index:e}}ensureInitialized(){if(!this.initialized)throw new x(h.AUTH_NOT_INITIALIZED,"SDK가 초기화되지 않았습니다. initialize()를 먼저 호출하세요.")}ensureAuthenticated(){if(this.ensureInitialized(),!this.authenticated)throw new x(h.AUTH_NOT_AUTHENTICATED,"인증되지 않은 상태입니다. signIn()을 먼저 호출하세요.")}dispose(){var e;(e=this._themeMediaCleanup)==null||e.call(this),this._themeMediaCleanup=null,this.clearAuthState(),this.tokenStore.clear(),this.pinStore.clear(),this.initialized=!1,this.removeAllListeners(),rr(null)}_getInternalContext(){return{transport:this.transport,storage:this.storage,walletProvider:this.walletProvider,confirmation:this.confirmation,tokenStore:this.tokenStore,pinStore:this.pinStore,adapterConfig:this.adapterConfig}}};se.OFFCHAIN_CHAIN_ID="0";let st=se;class rn{constructor(){this.prefix="crossx_"}async set(e,r){try{const t=JSON.stringify(r);localStorage.setItem(this.prefix+e,t)}catch(t){throw d.error("Storage set error:",t),t}}async get(e){try{const r=localStorage.getItem(this.prefix+e);return r?JSON.parse(r):null}catch(r){return d.error("Storage get error:",r),null}}async remove(e){try{localStorage.removeItem(this.prefix+e)}catch(r){throw d.error("Storage remove error:",r),r}}async clear(){try{Object.keys(localStorage).forEach(r=>{r.startsWith(this.prefix)&&localStorage.removeItem(r)})}catch(e){throw d.error("Storage clear error:",e),e}}}const Et="crossx-sdk",sn=1,ge="data",Ne="keys",nt="aes-primary",nn=12;class fr{constructor(e){this.db=null,this.cryptoKey=null,this.initPromise=null,this.dbName=`crossx-sdk-${e}`}async ensureReady(){this.db&&this.cryptoKey||(this.initPromise||(this.initPromise=this.init()),await this.initPromise)}openDB(e=this.dbName){return new Promise((r,t)=>{const n=indexedDB.open(e,sn);n.onupgradeneeded=()=>{const i=n.result;i.objectStoreNames.contains(ge)||i.createObjectStore(ge),i.objectStoreNames.contains(Ne)||i.createObjectStore(Ne)},n.onsuccess=()=>r(n.result),n.onerror=()=>t(n.error)})}idbGet(e,r){return new Promise((t,n)=>{const o=this.db.transaction(e,"readonly").objectStore(e).get(r);o.onsuccess=()=>t(o.result),o.onerror=()=>n(o.error)})}idbPut(e,r,t){return new Promise((n,i)=>{const a=this.db.transaction(e,"readwrite").objectStore(e).put(t,r);a.onsuccess=()=>n(),a.onerror=()=>i(a.error)})}idbDelete(e,r){return new Promise((t,n)=>{const o=this.db.transaction(e,"readwrite").objectStore(e).delete(r);o.onsuccess=()=>t(),o.onerror=()=>n(o.error)})}idbClear(e){return new Promise((r,t)=>{const i=this.db.transaction(e,"readwrite").objectStore(e).clear();i.onsuccess=()=>r(),i.onerror=()=>t(i.error)})}async init(){this.db=await this.openDB();const e=await this.idbGet(Ne,nt);if(e){this.cryptoKey=e;return}const r=await this.migrateFromLegacyDB();if(r){this.cryptoKey=r;return}this.cryptoKey=await crypto.subtle.generateKey({name:"AES-GCM",length:256},!1,["encrypt","decrypt"]),await this.idbPut(Ne,nt,this.cryptoKey)}async migrateFromLegacyDB(){if(this.dbName===Et)return null;try{const e=await this.openDB(Et),r=e.transaction([Ne,ge],"readonly"),t=r.objectStore(Ne).get(nt),n=await new Promise((l,u)=>{t.onsuccess=()=>l(t.result),t.onerror=()=>u(t.error)});if(!n)return e.close(),null;const i=r.objectStore(ge).getAll(),o=r.objectStore(ge).getAllKeys(),[a,c]=await Promise.all([new Promise((l,u)=>{i.onsuccess=()=>l(i.result),i.onerror=()=>u(i.error)}),new Promise((l,u)=>{o.onsuccess=()=>l(o.result),o.onerror=()=>u(o.error)})]);e.close(),await this.idbPut(Ne,nt,n);for(let l=0;l<c.length;l++)await this.idbPut(ge,String(c[l]),a[l]);return indexedDB.deleteDatabase(Et),d.log("[CROSSx] IndexedDB 레거시 DB 마이그레이션 완료"),n}catch(e){return d.warn("[CROSSx] IndexedDB 레거시 DB 마이그레이션 실패:",e),null}}async encrypt(e){const r=new Uint8Array(nn);crypto.getRandomValues(r);const t=new TextEncoder().encode(e),n=await crypto.subtle.encrypt({name:"AES-GCM",iv:r},this.cryptoKey,t);return{iv:r,ciphertext:n}}async decrypt(e){const r=new Uint8Array(e.iv),t=await crypto.subtle.decrypt({name:"AES-GCM",iv:r},this.cryptoKey,e.ciphertext);return new TextDecoder().decode(t)}async set(e,r){try{await this.ensureReady();const t=JSON.stringify(r),n=await this.encrypt(t);await this.idbPut(ge,e,n)}catch(t){throw d.error("[CROSSx] IndexedDB set error:",t),t}}async get(e){try{await this.ensureReady();const r=await this.idbGet(ge,e);if(!r)return null;const t=await this.decrypt(r);return JSON.parse(t)}catch(r){return d.error("[CROSSx] IndexedDB get error:",r),null}}async remove(e){try{await this.ensureReady(),await this.idbDelete(ge,e)}catch(r){throw d.error("[CROSSx] IndexedDB remove error:",r),r}}async clear(){try{await this.ensureReady(),await this.idbClear(ge)}catch(e){throw d.error("[CROSSx] IndexedDB clear error:",e),e}}static isAvailable(){return typeof indexedDB<"u"&&typeof crypto<"u"&&typeof crypto.subtle<"u"}}const At=crypto,pr=s=>s instanceof CryptoKey,it=new TextEncoder,Ye=new TextDecoder;function on(...s){const e=s.reduce((n,{length:i})=>n+i,0),r=new Uint8Array(e);let t=0;for(const n of s)r.set(n,t),t+=n.length;return r}const an=s=>{const e=atob(s),r=new Uint8Array(e.length);for(let t=0;t<e.length;t++)r[t]=e.charCodeAt(t);return r},Re=s=>{let e=s;e instanceof Uint8Array&&(e=Ye.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return an(e)}catch{throw new TypeError("The input to be decoded is not correctly encoded.")}};class X extends Error{constructor(e,r){var t;super(e,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(t=Error.captureStackTrace)==null||t.call(Error,this,this.constructor)}}X.code="ERR_JOSE_GENERIC";class he extends X{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=t,this.reason=n,this.payload=r}}he.code="ERR_JWT_CLAIM_VALIDATION_FAILED";class It extends X{constructor(e,r,t="unspecified",n="unspecified"){super(e,{cause:{claim:t,reason:n,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=t,this.reason=n,this.payload=r}}It.code="ERR_JWT_EXPIRED";class _r extends X{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}}_r.code="ERR_JOSE_ALG_NOT_ALLOWED";class xe extends X{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}}xe.code="ERR_JOSE_NOT_SUPPORTED";class cn extends X{constructor(e="decryption operation failed",r){super(e,r),this.code="ERR_JWE_DECRYPTION_FAILED"}}cn.code="ERR_JWE_DECRYPTION_FAILED";class ln extends X{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}}ln.code="ERR_JWE_INVALID";class Y extends X{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}}Y.code="ERR_JWS_INVALID";class me extends X{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}}me.code="ERR_JWT_INVALID";class dn extends X{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}}dn.code="ERR_JWK_INVALID";class Tt extends X{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}}Tt.code="ERR_JWKS_INVALID";class Rt extends X{constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}}Rt.code="ERR_JWKS_NO_MATCHING_KEY";class gr extends X{constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}}gr.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";class xr extends X{constructor(e="request timed out",r){super(e,r),this.code="ERR_JWKS_TIMEOUT"}}xr.code="ERR_JWKS_TIMEOUT";class mr extends X{constructor(e="signature verification failed",r){super(e,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}}mr.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function we(s,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${s}`)}function je(s,e){return s.name===e}function Ot(s){return parseInt(s.name.slice(4),10)}function un(s){switch(s){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function hn(s,e){if(e.length&&!e.some(r=>s.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(e.length>2){const t=e.pop();r+=`one of ${e.join(", ")}, or ${t}.`}else e.length===2?r+=`one of ${e[0]} or ${e[1]}.`:r+=`${e[0]}.`;throw new TypeError(r)}}function fn(s,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!je(s.algorithm,"HMAC"))throw we("HMAC");const t=parseInt(e.slice(2),10);if(Ot(s.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!je(s.algorithm,"RSASSA-PKCS1-v1_5"))throw we("RSASSA-PKCS1-v1_5");const t=parseInt(e.slice(2),10);if(Ot(s.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!je(s.algorithm,"RSA-PSS"))throw we("RSA-PSS");const t=parseInt(e.slice(2),10);if(Ot(s.algorithm.hash)!==t)throw we(`SHA-${t}`,"algorithm.hash");break}case"EdDSA":{if(s.algorithm.name!=="Ed25519"&&s.algorithm.name!=="Ed448")throw we("Ed25519 or Ed448");break}case"Ed25519":{if(!je(s.algorithm,"Ed25519"))throw we("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!je(s.algorithm,"ECDSA"))throw we("ECDSA");const t=un(e);if(s.algorithm.namedCurve!==t)throw we(t,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}hn(s,r)}function wr(s,e,...r){var t;if(r=r.filter(Boolean),r.length>2){const n=r.pop();s+=`one of type ${r.join(", ")}, or ${n}.`}else r.length===2?s+=`one of type ${r[0]} or ${r[1]}.`:s+=`of type ${r[0]}.`;return e==null?s+=` Received ${e}`:typeof e=="function"&&e.name?s+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(t=e.constructor)!=null&&t.name&&(s+=` Received an instance of ${e.constructor.name}`),s}const yr=(s,...e)=>wr("Key must be ",s,...e);function br(s,e,...r){return wr(`Key for the ${s} algorithm must be `,e,...r)}const Sr=s=>pr(s)?!0:(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",ot=["CryptoKey"],pn=(...s)=>{const e=s.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(const t of e){const n=Object.keys(t);if(!r||r.size===0){r=new Set(n);continue}for(const i of n){if(r.has(i))return!1;r.add(i)}}return!0};function _n(s){return typeof s=="object"&&s!==null}function ve(s){if(!_n(s)||Object.prototype.toString.call(s)!=="[object Object]")return!1;if(Object.getPrototypeOf(s)===null)return!0;let e=s;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(s)===e}const gn=(s,e)=>{if(s.startsWith("RS")||s.startsWith("PS")){const{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${s} requires key modulusLength to be 2048 bits or larger`)}};function Ue(s){return ve(s)&&typeof s.kty=="string"}function xn(s){return s.kty!=="oct"&&typeof s.d=="string"}function mn(s){return s.kty!=="oct"&&typeof s.d>"u"}function wn(s){return Ue(s)&&s.kty==="oct"&&typeof s.k=="string"}function yn(s){let e,r;switch(s.kty){case"RSA":{switch(s.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${s.alg.slice(-3)}`},r=s.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(s.alg.slice(-3),10)||1}`},r=s.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new xe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(s.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=s.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=s.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new xe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(s.alg){case"Ed25519":e={name:"Ed25519"},r=s.d?["sign"]:["verify"];break;case"EdDSA":e={name:s.crv},r=s.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:s.crv},r=s.d?["deriveBits"]:[];break;default:throw new xe('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new xe('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}const vr=async s=>{if(!s.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');const{algorithm:e,keyUsages:r}=yn(s),t=[e,s.ext??!1,s.key_ops??r],n={...s};return delete n.alg,delete n.use,At.subtle.importKey("jwk",n,...t)},Er=s=>Re(s);let He,Be;const Ar=s=>(s==null?void 0:s[Symbol.toStringTag])==="KeyObject",at=async(s,e,r,t,n=!1)=>{let i=s.get(e);if(i!=null&&i[t])return i[t];const o=await vr({...r,alg:t});return n&&Object.freeze(e),i?i[t]=o:s.set(e,{[t]:o}),o},bn={normalizePublicKey:(s,e)=>{if(Ar(s)){let r=s.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?Er(r.k):(Be||(Be=new WeakMap),at(Be,s,r,e))}return Ue(s)?s.k?Re(s.k):(Be||(Be=new WeakMap),at(Be,s,s,e,!0)):s},normalizePrivateKey:(s,e)=>{if(Ar(s)){let r=s.export({format:"jwk"});return r.k?Er(r.k):(He||(He=new WeakMap),at(He,s,r,e))}return Ue(s)?s.k?Re(s.k):(He||(He=new WeakMap),at(He,s,s,e,!0)):s}};async function Ir(s,e){if(!ve(s))throw new TypeError("JWK must be an object");switch(e||(e=s.alg),s.kty){case"oct":if(typeof s.k!="string"||!s.k)throw new TypeError('missing "k" (Key Value) Parameter value');return Re(s.k);case"RSA":if("oth"in s&&s.oth!==void 0)throw new xe('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return vr({...s,alg:e});default:throw new xe('Unsupported "kty" (Key Type) Parameter value')}}const Fe=s=>s==null?void 0:s[Symbol.toStringTag],Pt=(s,e,r)=>{var t,n;if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&((n=(t=e.key_ops).includes)==null?void 0:n.call(t,r))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(e.alg!==void 0&&e.alg!==s)throw new TypeError(`Invalid key for this operation, when present its alg must be ${s}`);return!0},Sn=(s,e,r,t)=>{if(!(e instanceof Uint8Array)){if(t&&Ue(e)){if(wn(e)&&Pt(s,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!Sr(e))throw new TypeError(br(s,e,...ot,"Uint8Array",t?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${Fe(e)} instances for symmetric algorithms must be of type "secret"`)}},vn=(s,e,r,t)=>{if(t&&Ue(e))switch(r){case"sign":if(xn(e)&&Pt(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(mn(e)&&Pt(s,e,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!Sr(e))throw new TypeError(br(s,e,...ot,t?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${Fe(e)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${Fe(e)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${Fe(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${Fe(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${Fe(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function Tr(s,e,r,t){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?Sn(e,r,t,s):vn(e,r,t,s)}Tr.bind(void 0,!1);const Rr=Tr.bind(void 0,!0);function En(s,e,r,t,n){if(n.crit!==void 0&&(t==null?void 0:t.crit)===void 0)throw new s('"crit" (Critical) Header Parameter MUST be integrity protected');if(!t||t.crit===void 0)return new Set;if(!Array.isArray(t.crit)||t.crit.length===0||t.crit.some(o=>typeof o!="string"||o.length===0))throw new s('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let i;r!==void 0?i=new Map([...Object.entries(r),...e.entries()]):i=e;for(const o of t.crit){if(!i.has(o))throw new xe(`Extension Header Parameter "${o}" is not recognized`);if(n[o]===void 0)throw new s(`Extension Header Parameter "${o}" is missing`);if(i.get(o)&&t[o]===void 0)throw new s(`Extension Header Parameter "${o}" MUST be integrity protected`)}return new Set(t.crit)}const An=(s,e)=>{if(e!==void 0&&(!Array.isArray(e)||e.some(r=>typeof r!="string")))throw new TypeError(`"${s}" option must be an array of strings`);if(e)return new Set(e)};function In(s,e){const r=`SHA-${s.slice(-3)}`;switch(s){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:s.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"Ed25519":return{name:"Ed25519"};case"EdDSA":return{name:e.name};default:throw new xe(`alg ${s} is not supported either by JOSE or your javascript runtime`)}}async function Tn(s,e,r){if(e=await bn.normalizePublicKey(e,s),pr(e))return fn(e,s,r),e;if(e instanceof Uint8Array){if(!s.startsWith("HS"))throw new TypeError(yr(e,...ot));return At.subtle.importKey("raw",e,{hash:`SHA-${s.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(yr(e,...ot,"Uint8Array","JSON Web Key"))}const Rn=async(s,e,r,t)=>{const n=await Tn(s,e,"verify");gn(s,n);const i=In(s,n.algorithm);try{return await At.subtle.verify(i,n,r,t)}catch{return!1}};async function On(s,e,r){if(!ve(s))throw new Y("Flattened JWS must be an object");if(s.protected===void 0&&s.header===void 0)throw new Y('Flattened JWS must have either of the "protected" or "header" members');if(s.protected!==void 0&&typeof s.protected!="string")throw new Y("JWS Protected Header incorrect type");if(s.payload===void 0)throw new Y("JWS Payload missing");if(typeof s.signature!="string")throw new Y("JWS Signature missing or incorrect type");if(s.header!==void 0&&!ve(s.header))throw new Y("JWS Unprotected Header incorrect type");let t={};if(s.protected)try{const v=Re(s.protected);t=JSON.parse(Ye.decode(v))}catch{throw new Y("JWS Protected Header is invalid")}if(!pn(t,s.header))throw new Y("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");const n={...t,...s.header},i=En(Y,new Map([["b64",!0]]),r==null?void 0:r.crit,t,n);let o=!0;if(i.has("b64")&&(o=t.b64,typeof o!="boolean"))throw new Y('The "b64" (base64url-encode payload) Header Parameter must be a boolean');const{alg:a}=n;if(typeof a!="string"||!a)throw new Y('JWS "alg" (Algorithm) Header Parameter missing or invalid');const c=r&&An("algorithms",r.algorithms);if(c&&!c.has(a))throw new _r('"alg" (Algorithm) Header Parameter value not allowed');if(o){if(typeof s.payload!="string")throw new Y("JWS Payload must be a string")}else if(typeof s.payload!="string"&&!(s.payload instanceof Uint8Array))throw new Y("JWS Payload must be a string or an Uint8Array instance");let l=!1;typeof e=="function"?(e=await e(t,s),l=!0,Rr(a,e,"verify"),Ue(e)&&(e=await Ir(e,a))):Rr(a,e,"verify");const u=on(it.encode(s.protected??""),it.encode("."),typeof s.payload=="string"?it.encode(s.payload):s.payload);let f;try{f=Re(s.signature)}catch{throw new Y("Failed to base64url decode the signature")}if(!await Rn(a,e,f,u))throw new mr;let p;if(o)try{p=Re(s.payload)}catch{throw new Y("Failed to base64url decode the payload")}else typeof s.payload=="string"?p=it.encode(s.payload):p=s.payload;const y={payload:p};return s.protected!==void 0&&(y.protectedHeader=t),s.header!==void 0&&(y.unprotectedHeader=s.header),l?{...y,key:e}:y}async function Pn(s,e,r){if(s instanceof Uint8Array&&(s=Ye.decode(s)),typeof s!="string")throw new Y("Compact JWS must be a string or Uint8Array");const{0:t,1:n,2:i,length:o}=s.split(".");if(o!==3)throw new Y("Invalid Compact JWS");const a=await On({payload:n,protected:t,signature:i},e,r),c={payload:a.payload,protectedHeader:a.protectedHeader};return typeof e=="function"?{...c,key:a.key}:c}const Cn=s=>Math.floor(s.getTime()/1e3),Or=60,Pr=Or*60,Ct=Pr*24,kn=Ct*7,Nn=Ct*365.25,Ln=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,Cr=s=>{const e=Ln.exec(s);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");const r=parseFloat(e[2]),t=e[3].toLowerCase();let n;switch(t){case"sec":case"secs":case"second":case"seconds":case"s":n=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":n=Math.round(r*Or);break;case"hour":case"hours":case"hr":case"hrs":case"h":n=Math.round(r*Pr);break;case"day":case"days":case"d":n=Math.round(r*Ct);break;case"week":case"weeks":case"w":n=Math.round(r*kn);break;default:n=Math.round(r*Nn);break}return e[1]==="-"||e[4]==="ago"?-n:n},kr=s=>s.toLowerCase().replace(/^application\//,""),Dn=(s,e)=>typeof s=="string"?e.includes(s):Array.isArray(s)?e.some(Set.prototype.has.bind(new Set(s))):!1,Mn=(s,e,r={})=>{let t;try{t=JSON.parse(Ye.decode(e))}catch{}if(!ve(t))throw new me("JWT Claims Set must be a top-level JSON object");const{typ:n}=r;if(n&&(typeof s.typ!="string"||kr(s.typ)!==kr(n)))throw new he('unexpected "typ" JWT header value',t,"typ","check_failed");const{requiredClaims:i=[],issuer:o,subject:a,audience:c,maxTokenAge:l}=r,u=[...i];l!==void 0&&u.push("iat"),c!==void 0&&u.push("aud"),a!==void 0&&u.push("sub"),o!==void 0&&u.push("iss");for(const y of new Set(u.reverse()))if(!(y in t))throw new he(`missing required "${y}" claim`,t,y,"missing");if(o&&!(Array.isArray(o)?o:[o]).includes(t.iss))throw new he('unexpected "iss" claim value',t,"iss","check_failed");if(a&&t.sub!==a)throw new he('unexpected "sub" claim value',t,"sub","check_failed");if(c&&!Dn(t.aud,typeof c=="string"?[c]:c))throw new he('unexpected "aud" claim value',t,"aud","check_failed");let f;switch(typeof r.clockTolerance){case"string":f=Cr(r.clockTolerance);break;case"number":f=r.clockTolerance;break;case"undefined":f=0;break;default:throw new TypeError("Invalid clockTolerance option type")}const{currentDate:g}=r,p=Cn(g||new Date);if((t.iat!==void 0||l)&&typeof t.iat!="number")throw new he('"iat" claim must be a number',t,"iat","invalid");if(t.nbf!==void 0){if(typeof t.nbf!="number")throw new he('"nbf" claim must be a number',t,"nbf","invalid");if(t.nbf>p+f)throw new he('"nbf" claim timestamp check failed',t,"nbf","check_failed")}if(t.exp!==void 0){if(typeof t.exp!="number")throw new he('"exp" claim must be a number',t,"exp","invalid");if(t.exp<=p-f)throw new It('"exp" claim timestamp check failed',t,"exp","check_failed")}if(l){const y=p-t.iat,v=typeof l=="number"?l:Cr(l);if(y-f>v)throw new It('"iat" claim timestamp check failed (too far in the past)',t,"iat","check_failed");if(y<0-f)throw new he('"iat" claim timestamp check failed (it should be in the past)',t,"iat","check_failed")}return t};async function $n(s,e,r){var o;const t=await Pn(s,e,r);if((o=t.protectedHeader.crit)!=null&&o.includes("b64")&&t.protectedHeader.b64===!1)throw new me("JWTs MUST NOT use unencoded payload");const i={payload:Mn(t.protectedHeader,t.payload,r),protectedHeader:t.protectedHeader};return typeof e=="function"?{...i,key:t.key}:i}function Wn(s){switch(typeof s=="string"&&s.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new xe('Unsupported "alg" value for a JSON Web Key Set')}}function Un(s){return s&&typeof s=="object"&&Array.isArray(s.keys)&&s.keys.every(Hn)}function Hn(s){return ve(s)}function Nr(s){return typeof structuredClone=="function"?structuredClone(s):JSON.parse(JSON.stringify(s))}class Bn{constructor(e){if(this._cached=new WeakMap,!Un(e))throw new Tt("JSON Web Key Set malformed");this._jwks=Nr(e)}async getKey(e,r){const{alg:t,kid:n}={...e,...r==null?void 0:r.header},i=Wn(t),o=this._jwks.keys.filter(l=>{let u=i===l.kty;if(u&&typeof n=="string"&&(u=n===l.kid),u&&typeof l.alg=="string"&&(u=t===l.alg),u&&typeof l.use=="string"&&(u=l.use==="sig"),u&&Array.isArray(l.key_ops)&&(u=l.key_ops.includes("verify")),u)switch(t){case"ES256":u=l.crv==="P-256";break;case"ES256K":u=l.crv==="secp256k1";break;case"ES384":u=l.crv==="P-384";break;case"ES512":u=l.crv==="P-521";break;case"Ed25519":u=l.crv==="Ed25519";break;case"EdDSA":u=l.crv==="Ed25519"||l.crv==="Ed448";break}return u}),{0:a,length:c}=o;if(c===0)throw new Rt;if(c!==1){const l=new gr,{_cached:u}=this;throw l[Symbol.asyncIterator]=async function*(){for(const f of o)try{yield await Lr(u,f,t)}catch{}},l}return Lr(this._cached,a,t)}}async function Lr(s,e,r){const t=s.get(e)||s.set(e,{}).get(e);if(t[r]===void 0){const n=await Ir({...e,ext:!0},r);if(n instanceof Uint8Array||n.type!=="public")throw new Tt("JSON Web Key Set members must be public keys");t[r]=n}return t[r]}function Dr(s){const e=new Bn(s),r=async(t,n)=>e.getKey(t,n);return Object.defineProperties(r,{jwks:{value:()=>Nr(e._jwks),enumerable:!0,configurable:!1,writable:!1}}),r}const Fn=async(s,e,r)=>{let t,n,i=!1;typeof AbortController=="function"&&(t=new AbortController,n=setTimeout(()=>{i=!0,t.abort()},e));const o=await fetch(s.href,{signal:t?t.signal:void 0,redirect:"manual",headers:r.headers}).catch(a=>{throw i?new xr:a});if(n!==void 0&&clearTimeout(n),o.status!==200)throw new X("Expected 200 OK from the JSON Web Key Set HTTP response");try{return await o.json()}catch{throw new X("Failed to parse the JSON Web Key Set HTTP response as JSON")}};function Kn(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}let kt;(typeof navigator>"u"||!((Ms=(yt=navigator.userAgent)==null?void 0:yt.startsWith)!=null&&Ms.call(yt,"Mozilla/5.0 ")))&&(kt="jose/v5.10.0");const Nt=Symbol();function Gn(s,e){return!(typeof s!="object"||s===null||!("uat"in s)||typeof s.uat!="number"||Date.now()-s.uat>=e||!("jwks"in s)||!ve(s.jwks)||!Array.isArray(s.jwks.keys)||!Array.prototype.every.call(s.jwks.keys,ve))}class qn{constructor(e,r){if(!(e instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(e.href),this._options={agent:r==null?void 0:r.agent,headers:r==null?void 0:r.headers},this._timeoutDuration=typeof(r==null?void 0:r.timeoutDuration)=="number"?r==null?void 0:r.timeoutDuration:5e3,this._cooldownDuration=typeof(r==null?void 0:r.cooldownDuration)=="number"?r==null?void 0:r.cooldownDuration:3e4,this._cacheMaxAge=typeof(r==null?void 0:r.cacheMaxAge)=="number"?r==null?void 0:r.cacheMaxAge:6e5,(r==null?void 0:r[Nt])!==void 0&&(this._cache=r==null?void 0:r[Nt],Gn(r==null?void 0:r[Nt],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=Dr(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(e,r){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(e,r)}catch(t){if(t instanceof Rt&&this.coolingDown()===!1)return await this.reload(),this._local(e,r);throw t}}async reload(){this._pendingFetch&&Kn()&&(this._pendingFetch=void 0);const e=new Headers(this._options.headers);kt&&!e.has("User-Agent")&&(e.set("User-Agent",kt),this._options.headers=Object.fromEntries(e.entries())),this._pendingFetch||(this._pendingFetch=Fn(this._url,this._timeoutDuration,this._options).then(r=>{this._local=Dr(r),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=r),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(r=>{throw this._pendingFetch=void 0,r})),await this._pendingFetch}}function Jn(s,e){const r=new qn(s,e),t=async(n,i)=>r.getKey(n,i);return Object.defineProperties(t,{coolingDown:{get:()=>r.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>r.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>r.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!r._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>{var n;return(n=r._local)==null?void 0:n.jwks()},enumerable:!0,configurable:!1,writable:!1}}),t}const Vn=Re;function zn(s){if(typeof s!="string")throw new me("JWTs must use Compact JWS serialization, JWT must be a string");const{1:e,length:r}=s.split(".");if(r===5)throw new me("Only JWTs using Compact JWS serialization can be decoded");if(r!==3)throw new me("Invalid JWT");if(!e)throw new me("JWTs must contain a payload");let t;try{t=Vn(e)}catch{throw new me("Failed to base64url decode the payload")}let n;try{n=JSON.parse(Ye.decode(t))}catch{throw new me("Failed to parse the decoded payload as JSON")}if(!ve(n))throw new me("Invalid JWT Claims Set");return n}/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */function Lt(s){return s instanceof Uint8Array||ArrayBuffer.isView(s)&&s.constructor.name==="Uint8Array"}function Ee(s,e=""){if(!Number.isSafeInteger(s)||s<0){const r=e&&`"${e}" `;throw new Error(`${r}expected integer >= 0, got ${s}`)}}function K(s,e,r=""){const t=Lt(s),n=s==null?void 0:s.length,i=e!==void 0;if(!t||i&&n!==e){const o=r&&`"${r}" `,a=i?` of length ${e}`:"",c=t?`length=${n}`:`type=${typeof s}`;throw new Error(o+"expected Uint8Array"+a+", got "+c)}return s}function Mr(s){if(typeof s!="function"||typeof s.create!="function")throw new Error("Hash must wrapped by utils.createHasher");Ee(s.outputLen),Ee(s.blockLen)}function Ke(s,e=!0){if(s.destroyed)throw new Error("Hash instance has been destroyed");if(e&&s.finished)throw new Error("Hash#digest() has already been called")}function $r(s,e){K(s,void 0,"digestInto() output");const r=e.outputLen;if(s.length<r)throw new Error('"digestInto() output" expected to be of length >='+r)}function Yn(s){return new Uint32Array(s.buffer,s.byteOffset,Math.floor(s.byteLength/4))}function Ge(...s){for(let e=0;e<s.length;e++)s[e].fill(0)}function Dt(s){return new DataView(s.buffer,s.byteOffset,s.byteLength)}function ye(s,e){return s<<32-e|s>>>e}const jn=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;function Xn(s){return s<<24&4278190080|s<<8&16711680|s>>>8&65280|s>>>24&255}function Zn(s){for(let e=0;e<s.length;e++)s[e]=Xn(s[e]);return s}const Wr=jn?s=>s:Zn,Ur=typeof Uint8Array.from([]).toHex=="function"&&typeof Uint8Array.fromHex=="function",Qn=Array.from({length:256},(s,e)=>e.toString(16).padStart(2,"0"));function Xe(s){if(K(s),Ur)return s.toHex();let e="";for(let r=0;r<s.length;r++)e+=Qn[s[r]];return e}const Ae={_0:48,_9:57,A:65,F:70,a:97,f:102};function Hr(s){if(s>=Ae._0&&s<=Ae._9)return s-Ae._0;if(s>=Ae.A&&s<=Ae.F)return s-(Ae.A-10);if(s>=Ae.a&&s<=Ae.f)return s-(Ae.a-10)}function ct(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);if(Ur)return Uint8Array.fromHex(s);const e=s.length,r=e/2;if(e%2)throw new Error("hex string expected, got unpadded hex of length "+e);const t=new Uint8Array(r);for(let n=0,i=0;n<r;n++,i+=2){const o=Hr(s.charCodeAt(i)),a=Hr(s.charCodeAt(i+1));if(o===void 0||a===void 0){const c=s[i]+s[i+1];throw new Error('hex string expected, got non-hex character "'+c+'" at index '+i)}t[n]=o*16+a}return t}function Oe(...s){let e=0;for(let t=0;t<s.length;t++){const n=s[t];K(n),e+=n.length}const r=new Uint8Array(e);for(let t=0,n=0;t<s.length;t++){const i=s[t];r.set(i,n),n+=i.length}return r}function Br(s,e={}){const r=(n,i)=>s(i).update(n).digest(),t=s(void 0);return r.outputLen=t.outputLen,r.blockLen=t.blockLen,r.create=n=>s(n),Object.assign(r,e),Object.freeze(r)}function Fr(s=32){const e=typeof globalThis=="object"?globalThis.crypto:null;if(typeof(e==null?void 0:e.getRandomValues)!="function")throw new Error("crypto.getRandomValues must be defined");return e.getRandomValues(new Uint8Array(s))}const ei=s=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,s])});function ti(s,e,r){return s&e^~s&r}function ri(s,e,r){return s&e^s&r^e&r}class si{constructor(e,r,t,n){O(this,"blockLen");O(this,"outputLen");O(this,"padOffset");O(this,"isLE");O(this,"buffer");O(this,"view");O(this,"finished",!1);O(this,"length",0);O(this,"pos",0);O(this,"destroyed",!1);this.blockLen=e,this.outputLen=r,this.padOffset=t,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Dt(this.buffer)}update(e){Ke(this),K(e);const{view:r,buffer:t,blockLen:n}=this,i=e.length;for(let o=0;o<i;){const a=Math.min(n-this.pos,i-o);if(a===n){const c=Dt(e);for(;n<=i-o;o+=n)this.process(c,o);continue}t.set(e.subarray(o,o+a),this.pos),this.pos+=a,o+=a,this.pos===n&&(this.process(r,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){Ke(this),$r(e,this),this.finished=!0;const{buffer:r,view:t,blockLen:n,isLE:i}=this;let{pos:o}=this;r[o++]=128,Ge(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(t,0),o=0);for(let f=o;f<n;f++)r[f]=0;t.setBigUint64(n-8,BigInt(this.length*8),i),this.process(t,0);const a=Dt(e),c=this.outputLen;if(c%4)throw new Error("_sha2: outputLen must be aligned to 32bit");const l=c/4,u=this.get();if(l>u.length)throw new Error("_sha2: outputLen bigger than state");for(let f=0;f<l;f++)a.setUint32(4*f,u[f],i)}digest(){const{buffer:e,outputLen:r}=this;this.digestInto(e);const t=e.slice(0,r);return this.destroy(),t}_cloneInto(e){e||(e=new this.constructor),e.set(...this.get());const{blockLen:r,buffer:t,length:n,finished:i,destroyed:o,pos:a}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=a,n%r&&e.buffer.set(t),e}clone(){return this._cloneInto()}}const Pe=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),lt=BigInt(2**32-1),Kr=BigInt(32);function ni(s,e=!1){return e?{h:Number(s<),l:Number(s>>Kr<)}:{h:Number(s>>Kr<)|0,l:Number(s<)|0}}function ii(s,e=!1){const r=s.length;let t=new Uint32Array(r),n=new Uint32Array(r);for(let i=0;i<r;i++){const{h:o,l:a}=ni(s[i],e);[t[i],n[i]]=[o,a]}return[t,n]}const oi=(s,e,r)=>s<<r|e>>>32-r,ai=(s,e,r)=>e<<r|s>>>32-r,ci=(s,e,r)=>e<<r-32|s>>>64-r,li=(s,e,r)=>s<<r-32|e>>>64-r,di=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ce=new Uint32Array(64);class ui extends si{constructor(e){super(64,e,8,!1)}get(){const{A:e,B:r,C:t,D:n,E:i,F:o,G:a,H:c}=this;return[e,r,t,n,i,o,a,c]}set(e,r,t,n,i,o,a,c){this.A=e|0,this.B=r|0,this.C=t|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=c|0}process(e,r){for(let f=0;f<16;f++,r+=4)Ce[f]=e.getUint32(r,!1);for(let f=16;f<64;f++){const g=Ce[f-15],p=Ce[f-2],y=ye(g,7)^ye(g,18)^g>>>3,v=ye(p,17)^ye(p,19)^p>>>10;Ce[f]=v+Ce[f-7]+y+Ce[f-16]|0}let{A:t,B:n,C:i,D:o,E:a,F:c,G:l,H:u}=this;for(let f=0;f<64;f++){const g=ye(a,6)^ye(a,11)^ye(a,25),p=u+g+ti(a,c,l)+di[f]+Ce[f]|0,v=(ye(t,2)^ye(t,13)^ye(t,22))+ri(t,n,i)|0;u=l,l=c,c=a,a=o+p|0,o=i,i=n,n=t,t=p+v|0}t=t+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,c=c+this.F|0,l=l+this.G|0,u=u+this.H|0,this.set(t,n,i,o,a,c,l,u)}roundClean(){Ge(Ce)}destroy(){this.set(0,0,0,0,0,0,0,0),Ge(this.buffer)}}class hi extends ui{constructor(){super(32);O(this,"A",Pe[0]|0);O(this,"B",Pe[1]|0);O(this,"C",Pe[2]|0);O(this,"D",Pe[3]|0);O(this,"E",Pe[4]|0);O(this,"F",Pe[5]|0);O(this,"G",Pe[6]|0);O(this,"H",Pe[7]|0)}}const fi=Br(()=>new hi,ei(1));/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Mt=BigInt(0),$t=BigInt(1);function dt(s,e=""){if(typeof s!="boolean"){const r=e&&`"${e}" `;throw new Error(r+"expected boolean, got type="+typeof s)}return s}function Gr(s){if(typeof s=="bigint"){if(!ft(s))throw new Error("positive bigint expected, got "+s)}else Ee(s);return s}function ut(s){const e=Gr(s).toString(16);return e.length&1?"0"+e:e}function qr(s){if(typeof s!="string")throw new Error("hex string expected, got "+typeof s);return s===""?Mt:BigInt("0x"+s)}function ht(s){return qr(Xe(s))}function Jr(s){return qr(Xe(pi(K(s)).reverse()))}function Wt(s,e){Ee(e),s=Gr(s);const r=ct(s.toString(16).padStart(e*2,"0"));if(r.length!==e)throw new Error("number too large");return r}function Vr(s,e){return Wt(s,e).reverse()}function pi(s){return Uint8Array.from(s)}const ft=s=>typeof s=="bigint"&&Mt<=s;function _i(s,e,r){return ft(s)&&ft(e)&&ft(r)&&e<=s&&s<r}function gi(s,e,r,t){if(!_i(e,r,t))throw new Error("expected valid "+s+": "+r+" <= n < "+t+", got "+e)}function xi(s){let e;for(e=0;s>Mt;s>>=$t,e+=1);return e}const Ut=s=>($t<<BigInt(s))-$t;function mi(s,e,r){if(Ee(s,"hashLen"),Ee(e,"qByteLen"),typeof r!="function")throw new Error("hmacFn must be a function");const t=S=>new Uint8Array(S),n=Uint8Array.of(),i=Uint8Array.of(0),o=Uint8Array.of(1),a=1e3;let c=t(s),l=t(s),u=0;const f=()=>{c.fill(1),l.fill(0),u=0},g=(...S)=>r(l,Oe(c,...S)),p=(S=n)=>{l=g(i,S),c=g(),S.length!==0&&(l=g(o,S),c=g())},y=()=>{if(u++>=a)throw new Error("drbg: tried max amount of iterations");let S=0;const I=[];for(;S<e;){c=g();const T=c.slice();I.push(T),S+=c.length}return Oe(...I)};return(S,I)=>{f(),p(S);let T;for(;!(T=I(y()));)p();return f(),T}}function Ht(s,e={},r={}){if(!s||typeof s!="object")throw new Error("expected valid options object");function t(i,o,a){const c=s[i];if(a&&c===void 0)return;const l=typeof c;if(l!==o||c===null)throw new Error(`param "${i}" is invalid: expected ${o}, got ${l}`)}const n=(i,o)=>Object.entries(i).forEach(([a,c])=>t(a,c,o));n(e,!1),n(r,!0)}function zr(s){const e=new WeakMap;return(r,...t)=>{const n=e.get(r);if(n!==void 0)return n;const i=s(r,...t);return e.set(r,i),i}}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const oe=BigInt(0),te=BigInt(1),Le=BigInt(2),Yr=BigInt(3),jr=BigInt(4),Xr=BigInt(5),wi=BigInt(7),Zr=BigInt(8),yi=BigInt(9),Qr=BigInt(16);function fe(s,e){const r=s%e;return r>=oe?r:e+r}function ue(s,e,r){let t=s;for(;e-- >oe;)t*=t,t%=r;return t}function es(s,e){if(s===oe)throw new Error("invert: expected non-zero number");if(e<=oe)throw new Error("invert: expected positive modulus, got "+e);let r=fe(s,e),t=e,n=oe,i=te;for(;r!==oe;){const a=t/r,c=t%r,l=n-i*a;t=r,r=c,n=i,i=l}if(t!==te)throw new Error("invert: does not exist");return fe(n,e)}function Bt(s,e,r){if(!s.eql(s.sqr(e),r))throw new Error("Cannot find square root")}function ts(s,e){const r=(s.ORDER+te)/jr,t=s.pow(e,r);return Bt(s,t,e),t}function bi(s,e){const r=(s.ORDER-Xr)/Zr,t=s.mul(e,Le),n=s.pow(t,r),i=s.mul(e,n),o=s.mul(s.mul(i,Le),n),a=s.mul(i,s.sub(o,s.ONE));return Bt(s,a,e),a}function Si(s){const e=pt(s),r=rs(s),t=r(e,e.neg(e.ONE)),n=r(e,t),i=r(e,e.neg(t)),o=(s+wi)/Qr;return(a,c)=>{let l=a.pow(c,o),u=a.mul(l,t);const f=a.mul(l,n),g=a.mul(l,i),p=a.eql(a.sqr(u),c),y=a.eql(a.sqr(f),c);l=a.cmov(l,u,p),u=a.cmov(g,f,y);const v=a.eql(a.sqr(u),c),S=a.cmov(l,u,v);return Bt(a,S,c),S}}function rs(s){if(s<Yr)throw new Error("sqrt is not defined for small field");let e=s-te,r=0;for(;e%Le===oe;)e/=Le,r++;let t=Le;const n=pt(s);for(;ns(n,t)===1;)if(t++>1e3)throw new Error("Cannot find square root: probably non-prime P");if(r===1)return ts;let i=n.pow(t,e);const o=(e+te)/Le;return function(c,l){if(c.is0(l))return l;if(ns(c,l)!==1)throw new Error("Cannot find square root");let u=r,f=c.mul(c.ONE,i),g=c.pow(l,e),p=c.pow(l,o);for(;!c.eql(g,c.ONE);){if(c.is0(g))return c.ZERO;let y=1,v=c.sqr(g);for(;!c.eql(v,c.ONE);)if(y++,v=c.sqr(v),y===u)throw new Error("Cannot find square root");const S=te<<BigInt(u-y-1),I=c.pow(f,S);u=y,f=c.sqr(I),g=c.mul(g,f),p=c.mul(p,I)}return p}}function vi(s){return s%jr===Yr?ts:s%Zr===Xr?bi:s%Qr===yi?Si(s):rs(s)}const Ei=["create","isValid","is0","neg","inv","sqrt","sqr","eql","add","sub","mul","pow","div","addN","subN","mulN","sqrN"];function Ai(s){const e={ORDER:"bigint",BYTES:"number",BITS:"number"},r=Ei.reduce((t,n)=>(t[n]="function",t),e);return Ht(s,r),s}function Ii(s,e,r){if(r<oe)throw new Error("invalid exponent, negatives unsupported");if(r===oe)return s.ONE;if(r===te)return e;let t=s.ONE,n=e;for(;r>oe;)r&te&&(t=s.mul(t,n)),n=s.sqr(n),r>>=te;return t}function ss(s,e,r=!1){const t=new Array(e.length).fill(r?s.ZERO:void 0),n=e.reduce((o,a,c)=>s.is0(a)?o:(t[c]=o,s.mul(o,a)),s.ONE),i=s.inv(n);return e.reduceRight((o,a,c)=>s.is0(a)?o:(t[c]=s.mul(o,t[c]),s.mul(o,a)),i),t}function ns(s,e){const r=(s.ORDER-te)/Le,t=s.pow(e,r),n=s.eql(t,s.ONE),i=s.eql(t,s.ZERO),o=s.eql(t,s.neg(s.ONE));if(!n&&!i&&!o)throw new Error("invalid Legendre symbol result");return n?1:i?0:-1}function Ti(s,e){e!==void 0&&Ee(e);const r=e!==void 0?e:s.toString(2).length,t=Math.ceil(r/8);return{nBitLength:r,nByteLength:t}}class Ri{constructor(e,r={}){O(this,"ORDER");O(this,"BITS");O(this,"BYTES");O(this,"isLE");O(this,"ZERO",oe);O(this,"ONE",te);O(this,"_lengths");O(this,"_sqrt");O(this,"_mod");var o;if(e<=oe)throw new Error("invalid field: expected ORDER > 0, got "+e);let t;this.isLE=!1,r!=null&&typeof r=="object"&&(typeof r.BITS=="number"&&(t=r.BITS),typeof r.sqrt=="function"&&(this.sqrt=r.sqrt),typeof r.isLE=="boolean"&&(this.isLE=r.isLE),r.allowedLengths&&(this._lengths=(o=r.allowedLengths)==null?void 0:o.slice()),typeof r.modFromBytes=="boolean"&&(this._mod=r.modFromBytes));const{nBitLength:n,nByteLength:i}=Ti(e,t);if(i>2048)throw new Error("invalid field: expected ORDER of <= 2048 bytes");this.ORDER=e,this.BITS=n,this.BYTES=i,this._sqrt=void 0,Object.preventExtensions(this)}create(e){return fe(e,this.ORDER)}isValid(e){if(typeof e!="bigint")throw new Error("invalid field element: expected bigint, got "+typeof e);return oe<=e&&e<this.ORDER}is0(e){return e===oe}isValidNot0(e){return!this.is0(e)&&this.isValid(e)}isOdd(e){return(e&te)===te}neg(e){return fe(-e,this.ORDER)}eql(e,r){return e===r}sqr(e){return fe(e*e,this.ORDER)}add(e,r){return fe(e+r,this.ORDER)}sub(e,r){return fe(e-r,this.ORDER)}mul(e,r){return fe(e*r,this.ORDER)}pow(e,r){return Ii(this,e,r)}div(e,r){return fe(e*es(r,this.ORDER),this.ORDER)}sqrN(e){return e*e}addN(e,r){return e+r}subN(e,r){return e-r}mulN(e,r){return e*r}inv(e){return es(e,this.ORDER)}sqrt(e){return this._sqrt||(this._sqrt=vi(this.ORDER)),this._sqrt(this,e)}toBytes(e){return this.isLE?Vr(e,this.BYTES):Wt(e,this.BYTES)}fromBytes(e,r=!1){K(e);const{_lengths:t,BYTES:n,isLE:i,ORDER:o,_mod:a}=this;if(t){if(!t.includes(e.length)||e.length>n)throw new Error("Field.fromBytes: expected "+t+" bytes, got "+e.length);const l=new Uint8Array(n);l.set(e,i?0:l.length-e.length),e=l}if(e.length!==n)throw new Error("Field.fromBytes: expected "+n+" bytes, got "+e.length);let c=i?Jr(e):ht(e);if(a&&(c=fe(c,o)),!r&&!this.isValid(c))throw new Error("invalid field element: outside of range 0..ORDER");return c}invertBatch(e){return ss(this,e)}cmov(e,r,t){return t?r:e}}function pt(s,e={}){return new Ri(s,e)}function is(s){if(typeof s!="bigint")throw new Error("field order must be bigint");const e=s.toString(2).length;return Math.ceil(e/8)}function os(s){const e=is(s);return e+Math.ceil(e/2)}function Oi(s,e,r=!1){K(s);const t=s.length,n=is(e),i=os(e);if(t<16||t<i||t>1024)throw new Error("expected "+i+"-1024 bytes of input, got "+t);const o=r?Jr(s):ht(s),a=fe(o,e-te)+te;return r?Vr(a,n):Wt(a,n)}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const qe=BigInt(0),De=BigInt(1);function _t(s,e){const r=e.negate();return s?r:e}function as(s,e){const r=ss(s.Fp,e.map(t=>t.Z));return e.map((t,n)=>s.fromAffine(t.toAffine(r[n])))}function cs(s,e){if(!Number.isSafeInteger(s)||s<=0||s>e)throw new Error("invalid window size, expected [1.."+e+"], got W="+s)}function Ft(s,e){cs(s,e);const r=Math.ceil(e/s)+1,t=2**(s-1),n=2**s,i=Ut(s),o=BigInt(s);return{windows:r,windowSize:t,mask:i,maxNumber:n,shiftBy:o}}function ls(s,e,r){const{windowSize:t,mask:n,maxNumber:i,shiftBy:o}=r;let a=Number(s&n),c=s>>o;a>t&&(a-=i,c+=De);const l=e*t,u=l+Math.abs(a)-1,f=a===0,g=a<0,p=e%2!==0;return{nextN:c,offset:u,isZero:f,isNeg:g,isNegF:p,offsetF:l}}const Kt=new WeakMap,ds=new WeakMap;function Gt(s){return ds.get(s)||1}function us(s){if(s!==qe)throw new Error("invalid wNAF")}class Pi{constructor(e,r){O(this,"BASE");O(this,"ZERO");O(this,"Fn");O(this,"bits");this.BASE=e.BASE,this.ZERO=e.ZERO,this.Fn=e.Fn,this.bits=r}_unsafeLadder(e,r,t=this.ZERO){let n=e;for(;r>qe;)r&De&&(t=t.add(n)),n=n.double(),r>>=De;return t}precomputeWindow(e,r){const{windows:t,windowSize:n}=Ft(r,this.bits),i=[];let o=e,a=o;for(let c=0;c<t;c++){a=o,i.push(a);for(let l=1;l<n;l++)a=a.add(o),i.push(a);o=a.double()}return i}wNAF(e,r,t){if(!this.Fn.isValid(t))throw new Error("invalid scalar");let n=this.ZERO,i=this.BASE;const o=Ft(e,this.bits);for(let a=0;a<o.windows;a++){const{nextN:c,offset:l,isZero:u,isNeg:f,isNegF:g,offsetF:p}=ls(t,a,o);t=c,u?i=i.add(_t(g,r[p])):n=n.add(_t(f,r[l]))}return us(t),{p:n,f:i}}wNAFUnsafe(e,r,t,n=this.ZERO){const i=Ft(e,this.bits);for(let o=0;o<i.windows&&t!==qe;o++){const{nextN:a,offset:c,isZero:l,isNeg:u}=ls(t,o,i);if(t=a,!l){const f=r[c];n=n.add(u?f.negate():f)}}return us(t),n}getPrecomputes(e,r,t){let n=Kt.get(r);return n||(n=this.precomputeWindow(r,e),e!==1&&(typeof t=="function"&&(n=t(n)),Kt.set(r,n))),n}cached(e,r,t){const n=Gt(e);return this.wNAF(n,this.getPrecomputes(n,e,t),r)}unsafe(e,r,t,n){const i=Gt(e);return i===1?this._unsafeLadder(e,r,n):this.wNAFUnsafe(i,this.getPrecomputes(i,e,t),r,n)}createCache(e,r){cs(r,this.bits),ds.set(e,r),Kt.delete(e)}hasCache(e){return Gt(e)!==1}}function Ci(s,e,r,t){let n=e,i=s.ZERO,o=s.ZERO;for(;r>qe||t>qe;)r&De&&(i=i.add(n)),t&De&&(o=o.add(n)),n=n.double(),r>>=De,t>>=De;return{p1:i,p2:o}}function hs(s,e,r){if(e){if(e.ORDER!==s)throw new Error("Field.ORDER must match order: Fp == p, Fn == n");return Ai(e),e}else return pt(s,{isLE:r})}function ki(s,e,r={},t){if(t===void 0&&(t=s==="edwards"),!e||typeof e!="object")throw new Error(`expected valid ${s} CURVE object`);for(const c of["p","n","h"]){const l=e[c];if(!(typeof l=="bigint"&&l>qe))throw new Error(`CURVE.${c} must be positive bigint`)}const n=hs(e.p,r.Fp,t),i=hs(e.n,r.Fn,t),a=["Gx","Gy","a","b"];for(const c of a)if(!n.isValid(e[c]))throw new Error(`CURVE.${c} must be valid field element of CURVE.Fp`);return e=Object.freeze(Object.assign({},e)),{CURVE:e,Fp:n,Fn:i}}function Ni(s,e){return function(t){const n=s(t);return{secretKey:n,publicKey:e(n)}}}class fs{constructor(e,r){O(this,"oHash");O(this,"iHash");O(this,"blockLen");O(this,"outputLen");O(this,"finished",!1);O(this,"destroyed",!1);if(Mr(e),K(r,void 0,"key"),this.iHash=e.create(),typeof this.iHash.update!="function")throw new Error("Expected instance of class which extends utils.Hash");this.blockLen=this.iHash.blockLen,this.outputLen=this.iHash.outputLen;const t=this.blockLen,n=new Uint8Array(t);n.set(r.length>t?e.create().update(r).digest():r);for(let i=0;i<n.length;i++)n[i]^=54;this.iHash.update(n),this.oHash=e.create();for(let i=0;i<n.length;i++)n[i]^=106;this.oHash.update(n),Ge(n)}update(e){return Ke(this),this.iHash.update(e),this}digestInto(e){Ke(this),K(e,this.outputLen,"output"),this.finished=!0,this.iHash.digestInto(e),this.oHash.update(e),this.oHash.digestInto(e),this.destroy()}digest(){const e=new Uint8Array(this.oHash.outputLen);return this.digestInto(e),e}_cloneInto(e){e||(e=Object.create(Object.getPrototypeOf(this),{}));const{oHash:r,iHash:t,finished:n,destroyed:i,blockLen:o,outputLen:a}=this;return e=e,e.finished=n,e.destroyed=i,e.blockLen=o,e.outputLen=a,e.oHash=r._cloneInto(e.oHash),e.iHash=t._cloneInto(e.iHash),e}clone(){return this._cloneInto()}destroy(){this.destroyed=!0,this.oHash.destroy(),this.iHash.destroy()}}const ps=(s,e,r)=>new fs(s,e).update(r).digest();ps.create=(s,e)=>new fs(s,e);/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const _s=(s,e)=>(s+(s>=0?e:-e)/gs)/e;function Li(s,e,r){const[[t,n],[i,o]]=e,a=_s(o*s,r),c=_s(-n*s,r);let l=s-a*t-c*i,u=-a*n-c*o;const f=l<Ie,g=u<Ie;f&&(l=-l),g&&(u=-u);const p=Ut(Math.ceil(xi(r)/2))+Je;if(l<Ie||l>=p||u<Ie||u>=p)throw new Error("splitScalar (endomorphism): failed, k="+s);return{k1neg:f,k1:l,k2neg:g,k2:u}}function qt(s){if(!["compact","recovered","der"].includes(s))throw new Error('Signature format must be "compact", "recovered", or "der"');return s}function Jt(s,e){const r={};for(let t of Object.keys(e))r[t]=s[t]===void 0?e[t]:s[t];return dt(r.lowS,"lowS"),dt(r.prehash,"prehash"),r.format!==void 0&&qt(r.format),r}class Di extends Error{constructor(e=""){super(e)}}const ke={Err:Di,_tlv:{encode:(s,e)=>{const{Err:r}=ke;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length&1)throw new r("tlv.encode: unpadded data");const t=e.length/2,n=ut(t);if(n.length/2&128)throw new r("tlv.encode: long form length too big");const i=t>127?ut(n.length/2|128):"";return ut(s)+i+n+e},decode(s,e){const{Err:r}=ke;let t=0;if(s<0||s>256)throw new r("tlv.encode: wrong tag");if(e.length<2||e[t++]!==s)throw new r("tlv.decode: wrong tlv");const n=e[t++],i=!!(n&128);let o=0;if(!i)o=n;else{const c=n&127;if(!c)throw new r("tlv.decode(long): indefinite length not supported");if(c>4)throw new r("tlv.decode(long): byte length is too big");const l=e.subarray(t,t+c);if(l.length!==c)throw new r("tlv.decode: length bytes not complete");if(l[0]===0)throw new r("tlv.decode(long): zero leftmost byte");for(const u of l)o=o<<8|u;if(t+=c,o<128)throw new r("tlv.decode(long): not minimal encoding")}const a=e.subarray(t,t+o);if(a.length!==o)throw new r("tlv.decode: wrong value length");return{v:a,l:e.subarray(t+o)}}},_int:{encode(s){const{Err:e}=ke;if(s<Ie)throw new e("integer: negative integers are not allowed");let r=ut(s);if(Number.parseInt(r[0],16)&8&&(r="00"+r),r.length&1)throw new e("unexpected DER parsing assertion: unpadded hex");return r},decode(s){const{Err:e}=ke;if(s[0]&128)throw new e("invalid signature integer: negative");if(s[0]===0&&!(s[1]&128))throw new e("invalid signature integer: unnecessary leading zero");return ht(s)}},toSig(s){const{Err:e,_int:r,_tlv:t}=ke,n=K(s,void 0,"signature"),{v:i,l:o}=t.decode(48,n);if(o.length)throw new e("invalid signature: left bytes after parsing");const{v:a,l:c}=t.decode(2,i),{v:l,l:u}=t.decode(2,c);if(u.length)throw new e("invalid signature: left bytes after parsing");return{r:r.decode(a),s:r.decode(l)}},hexFromSig(s){const{_tlv:e,_int:r}=ke,t=e.encode(2,r.encode(s.r)),n=e.encode(2,r.encode(s.s)),i=t+n;return e.encode(48,i)}},Ie=BigInt(0),Je=BigInt(1),gs=BigInt(2),gt=BigInt(3),Mi=BigInt(4);function $i(s,e={}){const r=ki("weierstrass",s,e),{Fp:t,Fn:n}=r;let i=r.CURVE;const{h:o,n:a}=i;Ht(e,{},{allowInfinityPoint:"boolean",clearCofactor:"function",isTorsionFree:"function",fromBytes:"function",toBytes:"function",endo:"object"});const{endo:c}=e;if(c&&(!t.is0(i.a)||typeof c.beta!="bigint"||!Array.isArray(c.basises)))throw new Error('invalid endo: expected "beta": bigint and "basises": array');const l=ms(t,n);function u(){if(!t.isOdd)throw new Error("compression is not supported: Field does not have .isOdd()")}function f(D,w,_){const{x:m,y:b}=w.toAffine(),A=t.toBytes(m);if(dt(_,"isCompressed"),_){u();const R=!t.isOdd(b);return Oe(xs(R),A)}else return Oe(Uint8Array.of(4),A,t.toBytes(b))}function g(D){K(D,void 0,"Point");const{publicKey:w,publicKeyUncompressed:_}=l,m=D.length,b=D[0],A=D.subarray(1);if(m===w&&(b===2||b===3)){const R=t.fromBytes(A);if(!t.isValid(R))throw new Error("bad point: is not on curve, wrong x");const P=v(R);let E;try{E=t.sqrt(P)}catch(G){const F=G instanceof Error?": "+G.message:"";throw new Error("bad point: is not on curve, sqrt error"+F)}u();const k=t.isOdd(E);return(b&1)===1!==k&&(E=t.neg(E)),{x:R,y:E}}else if(m===_&&b===4){const R=t.BYTES,P=t.fromBytes(A.subarray(0,R)),E=t.fromBytes(A.subarray(R,R*2));if(!S(P,E))throw new Error("bad point: is not on curve");return{x:P,y:E}}else throw new Error(`bad point: got length ${m}, expected compressed=${w} or uncompressed=${_}`)}const p=e.toBytes||f,y=e.fromBytes||g;function v(D){const w=t.sqr(D),_=t.mul(w,D);return t.add(t.add(_,t.mul(D,i.a)),i.b)}function S(D,w){const _=t.sqr(w),m=v(D);return t.eql(_,m)}if(!S(i.Gx,i.Gy))throw new Error("bad curve params: generator point");const I=t.mul(t.pow(i.a,gt),Mi),T=t.mul(t.sqr(i.b),BigInt(27));if(t.is0(t.add(I,T)))throw new Error("bad curve params: a or b");function H(D,w,_=!1){if(!t.isValid(w)||_&&t.is0(w))throw new Error(`bad point coordinate ${D}`);return w}function L(D){if(!(D instanceof z))throw new Error("Weierstrass Point expected")}function V(D){if(!c||!c.basises)throw new Error("no endo");return Li(D,c.basises,n.ORDER)}const B=zr((D,w)=>{const{X:_,Y:m,Z:b}=D;if(t.eql(b,t.ONE))return{x:_,y:m};const A=D.is0();w==null&&(w=A?t.ONE:t.inv(b));const R=t.mul(_,w),P=t.mul(m,w),E=t.mul(b,w);if(A)return{x:t.ZERO,y:t.ZERO};if(!t.eql(E,t.ONE))throw new Error("invZ was invalid");return{x:R,y:P}}),ce=zr(D=>{if(D.is0()){if(e.allowInfinityPoint&&!t.is0(D.Y))return;throw new Error("bad point: ZERO")}const{x:w,y:_}=D.toAffine();if(!t.isValid(w)||!t.isValid(_))throw new Error("bad point: x or y not field elements");if(!S(w,_))throw new Error("bad point: equation left != right");if(!D.isTorsionFree())throw new Error("bad point: not in prime-order subgroup");return!0});function U(D,w,_,m,b){return _=new z(t.mul(_.X,D),_.Y,_.Z),w=_t(m,w),_=_t(b,_),w.add(_)}const C=class C{constructor(w,_,m){O(this,"X");O(this,"Y");O(this,"Z");this.X=H("x",w),this.Y=H("y",_,!0),this.Z=H("z",m),Object.freeze(this)}static CURVE(){return i}static fromAffine(w){const{x:_,y:m}=w||{};if(!w||!t.isValid(_)||!t.isValid(m))throw new Error("invalid affine point");if(w instanceof C)throw new Error("projective point not allowed");return t.is0(_)&&t.is0(m)?C.ZERO:new C(_,m,t.ONE)}static fromBytes(w){const _=C.fromAffine(y(K(w,void 0,"point")));return _.assertValidity(),_}static fromHex(w){return C.fromBytes(ct(w))}get x(){return this.toAffine().x}get y(){return this.toAffine().y}precompute(w=8,_=!0){return $.createCache(this,w),_||this.multiply(gt),this}assertValidity(){ce(this)}hasEvenY(){const{y:w}=this.toAffine();if(!t.isOdd)throw new Error("Field doesn't support isOdd");return!t.isOdd(w)}equals(w){L(w);const{X:_,Y:m,Z:b}=this,{X:A,Y:R,Z:P}=w,E=t.eql(t.mul(_,P),t.mul(A,b)),k=t.eql(t.mul(m,P),t.mul(R,b));return E&&k}negate(){return new C(this.X,t.neg(this.Y),this.Z)}double(){const{a:w,b:_}=i,m=t.mul(_,gt),{X:b,Y:A,Z:R}=this;let P=t.ZERO,E=t.ZERO,k=t.ZERO,M=t.mul(b,b),G=t.mul(A,A),F=t.mul(R,R),W=t.mul(b,A);return W=t.add(W,W),k=t.mul(b,R),k=t.add(k,k),P=t.mul(w,k),E=t.mul(m,F),E=t.add(P,E),P=t.sub(G,E),E=t.add(G,E),E=t.mul(P,E),P=t.mul(W,P),k=t.mul(m,k),F=t.mul(w,F),W=t.sub(M,F),W=t.mul(w,W),W=t.add(W,k),k=t.add(M,M),M=t.add(k,M),M=t.add(M,F),M=t.mul(M,W),E=t.add(E,M),F=t.mul(A,R),F=t.add(F,F),M=t.mul(F,W),P=t.sub(P,M),k=t.mul(F,G),k=t.add(k,k),k=t.add(k,k),new C(P,E,k)}add(w){L(w);const{X:_,Y:m,Z:b}=this,{X:A,Y:R,Z:P}=w;let E=t.ZERO,k=t.ZERO,M=t.ZERO;const G=i.a,F=t.mul(i.b,gt);let W=t.mul(_,A),Q=t.mul(m,R),ne=t.mul(b,P),de=t.add(_,m),q=t.add(A,R);de=t.mul(de,q),q=t.add(W,Q),de=t.sub(de,q),q=t.add(_,b);let ie=t.add(A,P);return q=t.mul(q,ie),ie=t.add(W,ne),q=t.sub(q,ie),ie=t.add(m,b),E=t.add(R,P),ie=t.mul(ie,E),E=t.add(Q,ne),ie=t.sub(ie,E),M=t.mul(G,q),E=t.mul(F,ne),M=t.add(E,M),E=t.sub(Q,M),M=t.add(Q,M),k=t.mul(E,M),Q=t.add(W,W),Q=t.add(Q,W),ne=t.mul(G,ne),q=t.mul(F,q),Q=t.add(Q,ne),ne=t.sub(W,ne),ne=t.mul(G,ne),q=t.add(q,ne),W=t.mul(Q,q),k=t.add(k,W),W=t.mul(ie,q),E=t.mul(de,E),E=t.sub(E,W),W=t.mul(de,Q),M=t.mul(ie,M),M=t.add(M,W),new C(E,k,M)}subtract(w){return this.add(w.negate())}is0(){return this.equals(C.ZERO)}multiply(w){const{endo:_}=e;if(!n.isValidNot0(w))throw new Error("invalid scalar: out of range");let m,b;const A=R=>$.cached(this,R,P=>as(C,P));if(_){const{k1neg:R,k1:P,k2neg:E,k2:k}=V(w),{p:M,f:G}=A(P),{p:F,f:W}=A(k);b=G.add(W),m=U(_.beta,M,F,R,E)}else{const{p:R,f:P}=A(w);m=R,b=P}return as(C,[m,b])[0]}multiplyUnsafe(w){const{endo:_}=e,m=this;if(!n.isValid(w))throw new Error("invalid scalar: out of range");if(w===Ie||m.is0())return C.ZERO;if(w===Je)return m;if($.hasCache(this))return this.multiply(w);if(_){const{k1neg:b,k1:A,k2neg:R,k2:P}=V(w),{p1:E,p2:k}=Ci(C,m,A,P);return U(_.beta,E,k,b,R)}else return $.unsafe(m,w)}toAffine(w){return B(this,w)}isTorsionFree(){const{isTorsionFree:w}=e;return o===Je?!0:w?w(C,this):$.unsafe(this,a).is0()}clearCofactor(){const{clearCofactor:w}=e;return o===Je?this:w?w(C,this):this.multiplyUnsafe(o)}isSmallOrder(){return this.multiplyUnsafe(o).is0()}toBytes(w=!0){return dt(w,"isCompressed"),this.assertValidity(),p(C,this,w)}toHex(w=!0){return Xe(this.toBytes(w))}toString(){return`<Point ${this.is0()?"ZERO":this.toHex()}>`}};O(C,"BASE",new C(i.Gx,i.Gy,t.ONE)),O(C,"ZERO",new C(t.ZERO,t.ONE,t.ZERO)),O(C,"Fp",t),O(C,"Fn",n);let z=C;const Z=n.BITS,$=new Pi(z,e.endo?Math.ceil(Z/2):Z);return z.BASE.precompute(8),z}function xs(s){return Uint8Array.of(s?2:3)}function ms(s,e){return{secretKey:e.BYTES,publicKey:1+s.BYTES,publicKeyUncompressed:1+2*s.BYTES,publicKeyHasPrefix:!0,signature:2*e.BYTES}}function Wi(s,e={}){const{Fn:r}=s,t=e.randomBytes||Fr,n=Object.assign(ms(s.Fp,r),{seed:os(r.ORDER)});function i(p){try{const y=r.fromBytes(p);return r.isValidNot0(y)}catch{return!1}}function o(p,y){const{publicKey:v,publicKeyUncompressed:S}=n;try{const I=p.length;return y===!0&&I!==v||y===!1&&I!==S?!1:!!s.fromBytes(p)}catch{return!1}}function a(p=t(n.seed)){return Oi(K(p,n.seed,"seed"),r.ORDER)}function c(p,y=!0){return s.BASE.multiply(r.fromBytes(p)).toBytes(y)}function l(p){const{secretKey:y,publicKey:v,publicKeyUncompressed:S}=n;if(!Lt(p)||"_lengths"in r&&r._lengths||y===v)return;const I=K(p,void 0,"key").length;return I===v||I===S}function u(p,y,v=!0){if(l(p)===!0)throw new Error("first arg must be private key");if(l(y)===!1)throw new Error("second arg must be public key");const S=r.fromBytes(p);return s.fromBytes(y).multiply(S).toBytes(v)}const f={isValidSecretKey:i,isValidPublicKey:o,randomSecretKey:a},g=Ni(a,c);return Object.freeze({getPublicKey:c,getSharedSecret:u,keygen:g,Point:s,utils:f,lengths:n})}function Ui(s,e,r={}){Mr(e),Ht(r,{},{hmac:"function",lowS:"boolean",randomBytes:"function",bits2int:"function",bits2int_modN:"function"}),r=Object.assign({},r);const t=r.randomBytes||Fr,n=r.hmac||((w,_)=>ps(e,w,_)),{Fp:i,Fn:o}=s,{ORDER:a,BITS:c}=o,{keygen:l,getPublicKey:u,getSharedSecret:f,utils:g,lengths:p}=Wi(s,r),y={prehash:!0,lowS:typeof r.lowS=="boolean"?r.lowS:!0,format:"compact",extraEntropy:!1},v=a*gs<i.ORDER;function S(w){const _=a>>Je;return w>_}function I(w,_){if(!o.isValidNot0(_))throw new Error(`invalid signature ${w}: out of range 1..Point.Fn.ORDER`);return _}function T(){if(v)throw new Error('"recovered" sig type is not supported for cofactor >2 curves')}function H(w,_){qt(_);const m=p.signature,b=_==="compact"?m:_==="recovered"?m+1:void 0;return K(w,b)}class L{constructor(_,m,b){O(this,"r");O(this,"s");O(this,"recovery");if(this.r=I("r",_),this.s=I("s",m),b!=null){if(T(),![0,1,2,3].includes(b))throw new Error("invalid recovery id");this.recovery=b}Object.freeze(this)}static fromBytes(_,m=y.format){H(_,m);let b;if(m==="der"){const{r:E,s:k}=ke.toSig(K(_));return new L(E,k)}m==="recovered"&&(b=_[0],m="compact",_=_.subarray(1));const A=p.signature/2,R=_.subarray(0,A),P=_.subarray(A,A*2);return new L(o.fromBytes(R),o.fromBytes(P),b)}static fromHex(_,m){return this.fromBytes(ct(_),m)}assertRecovery(){const{recovery:_}=this;if(_==null)throw new Error("invalid recovery id: must be present");return _}addRecoveryBit(_){return new L(this.r,this.s,_)}recoverPublicKey(_){const{r:m,s:b}=this,A=this.assertRecovery(),R=A===2||A===3?m+a:m;if(!i.isValid(R))throw new Error("invalid recovery id: sig.r+curve.n != R.x");const P=i.toBytes(R),E=s.fromBytes(Oe(xs((A&1)===0),P)),k=o.inv(R),M=B(K(_,void 0,"msgHash")),G=o.create(-M*k),F=o.create(b*k),W=s.BASE.multiplyUnsafe(G).add(E.multiplyUnsafe(F));if(W.is0())throw new Error("invalid recovery: point at infinify");return W.assertValidity(),W}hasHighS(){return S(this.s)}toBytes(_=y.format){if(qt(_),_==="der")return ct(ke.hexFromSig(this));const{r:m,s:b}=this,A=o.toBytes(m),R=o.toBytes(b);return _==="recovered"?(T(),Oe(Uint8Array.of(this.assertRecovery()),A,R)):Oe(A,R)}toHex(_){return Xe(this.toBytes(_))}}const V=r.bits2int||function(_){if(_.length>8192)throw new Error("input is too large");const m=ht(_),b=_.length*8-c;return b>0?m>>BigInt(b):m},B=r.bits2int_modN||function(_){return o.create(V(_))},ce=Ut(c);function U(w){return gi("num < 2^"+c,w,Ie,ce),o.toBytes(w)}function z(w,_){return K(w,void 0,"message"),_?K(e(w),void 0,"prehashed message"):w}function Z(w,_,m){const{lowS:b,prehash:A,extraEntropy:R}=Jt(m,y);w=z(w,A);const P=B(w),E=o.fromBytes(_);if(!o.isValidNot0(E))throw new Error("invalid private key");const k=[U(E),U(P)];if(R!=null&&R!==!1){const W=R===!0?t(p.secretKey):R;k.push(K(W,void 0,"extraEntropy"))}const M=Oe(...k),G=P;function F(W){const Q=V(W);if(!o.isValidNot0(Q))return;const ne=o.inv(Q),de=s.BASE.multiply(Q).toAffine(),q=o.create(de.x);if(q===Ie)return;const ie=o.create(ne*o.create(G+q*E));if(ie===Ie)return;let $s=(de.x===q?0:2)|Number(de.y&Je),Ws=ie;return b&&S(ie)&&(Ws=o.neg(ie),$s^=1),new L(q,Ws,v?void 0:$s)}return{seed:M,k2sig:F}}function $(w,_,m={}){const{seed:b,k2sig:A}=Z(w,_,m);return mi(e.outputLen,o.BYTES,n)(b,A).toBytes(m.format)}function C(w,_,m,b={}){const{lowS:A,prehash:R,format:P}=Jt(b,y);if(m=K(m,void 0,"publicKey"),_=z(_,R),!Lt(w)){const E=w instanceof L?", use sig.toBytes()":"";throw new Error("verify expects Uint8Array signature"+E)}H(w,P);try{const E=L.fromBytes(w,P),k=s.fromBytes(m);if(A&&E.hasHighS())return!1;const{r:M,s:G}=E,F=B(_),W=o.inv(G),Q=o.create(F*W),ne=o.create(M*W),de=s.BASE.multiplyUnsafe(Q).add(k.multiplyUnsafe(ne));return de.is0()?!1:o.create(de.x)===M}catch{return!1}}function D(w,_,m={}){const{prehash:b}=Jt(m,y);return _=z(_,b),L.fromBytes(w,"recovered").recoverPublicKey(_).toBytes()}return Object.freeze({keygen:l,getPublicKey:u,getSharedSecret:f,utils:g,lengths:p,Point:s,sign:$,verify:C,recoverPublicKey:D,Signature:L,hash:e})}/*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */const Vt={p:BigInt("0xfffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f"),n:BigInt("0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"),h:BigInt(1),a:BigInt(0),b:BigInt(7),Gx:BigInt("0x79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"),Gy:BigInt("0x483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8")},Hi={beta:BigInt("0x7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee"),basises:[[BigInt("0x3086d221a7d46bcde86c90e49284eb15"),-BigInt("0xe4437ed6010e88286f547fa90abfe4c3")],[BigInt("0x114ca50f7a8e2f3f657c1108d9d44cfd8"),BigInt("0x3086d221a7d46bcde86c90e49284eb15")]]},ws=BigInt(2);function Bi(s){const e=Vt.p,r=BigInt(3),t=BigInt(6),n=BigInt(11),i=BigInt(22),o=BigInt(23),a=BigInt(44),c=BigInt(88),l=s*s*s%e,u=l*l*s%e,f=ue(u,r,e)*u%e,g=ue(f,r,e)*u%e,p=ue(g,ws,e)*l%e,y=ue(p,n,e)*p%e,v=ue(y,i,e)*y%e,S=ue(v,a,e)*v%e,I=ue(S,c,e)*S%e,T=ue(I,a,e)*v%e,H=ue(T,r,e)*u%e,L=ue(H,o,e)*y%e,V=ue(L,t,e)*l%e,B=ue(V,ws,e);if(!zt.eql(zt.sqr(B),s))throw new Error("Cannot find square root");return B}const zt=pt(Vt.p,{sqrt:Bi}),Fi=Ui($i(Vt,{Fp:zt,endo:Hi}),fi),Ki=BigInt(0),Ze=BigInt(1),Gi=BigInt(2),qi=BigInt(7),Ji=BigInt(256),Vi=BigInt(113),ys=[],bs=[],Ss=[];for(let s=0,e=Ze,r=1,t=0;s<24;s++){[r,t]=[t,(2*r+3*t)%5],ys.push(2*(5*t+r)),bs.push((s+1)*(s+2)/2%64);let n=Ki;for(let i=0;i<7;i++)e=(e<<Ze^(e>>qi)*Vi)%Ji,e&Gi&&(n^=Ze<<(Ze<<BigInt(i))-Ze);Ss.push(n)}const vs=ii(Ss,!0),zi=vs[0],Yi=vs[1],Es=(s,e,r)=>r>32?ci(s,e,r):oi(s,e,r),As=(s,e,r)=>r>32?li(s,e,r):ai(s,e,r);function ji(s,e=24){const r=new Uint32Array(10);for(let t=24-e;t<24;t++){for(let o=0;o<10;o++)r[o]=s[o]^s[o+10]^s[o+20]^s[o+30]^s[o+40];for(let o=0;o<10;o+=2){const a=(o+8)%10,c=(o+2)%10,l=r[c],u=r[c+1],f=Es(l,u,1)^r[a],g=As(l,u,1)^r[a+1];for(let p=0;p<50;p+=10)s[o+p]^=f,s[o+p+1]^=g}let n=s[2],i=s[3];for(let o=0;o<24;o++){const a=bs[o],c=Es(n,i,a),l=As(n,i,a),u=ys[o];n=s[u],i=s[u+1],s[u]=c,s[u+1]=l}for(let o=0;o<50;o+=10){for(let a=0;a<10;a++)r[a]=s[o+a];for(let a=0;a<10;a++)s[o+a]^=~r[(a+2)%10]&r[(a+4)%10]}s[0]^=zi[t],s[1]^=Yi[t]}Ge(r)}class Yt{constructor(e,r,t,n=!1,i=24){O(this,"state");O(this,"pos",0);O(this,"posOut",0);O(this,"finished",!1);O(this,"state32");O(this,"destroyed",!1);O(this,"blockLen");O(this,"suffix");O(this,"outputLen");O(this,"enableXOF",!1);O(this,"rounds");if(this.blockLen=e,this.suffix=r,this.outputLen=t,this.enableXOF=n,this.rounds=i,Ee(t,"outputLen"),!(0<e&&e<200))throw new Error("only keccak-f1600 function is supported");this.state=new Uint8Array(200),this.state32=Yn(this.state)}clone(){return this._cloneInto()}keccak(){Wr(this.state32),ji(this.state32,this.rounds),Wr(this.state32),this.posOut=0,this.pos=0}update(e){Ke(this),K(e);const{blockLen:r,state:t}=this,n=e.length;for(let i=0;i<n;){const o=Math.min(r-this.pos,n-i);for(let a=0;a<o;a++)t[this.pos++]^=e[i++];this.pos===r&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;const{state:e,suffix:r,pos:t,blockLen:n}=this;e[t]^=r,r&128&&t===n-1&&this.keccak(),e[n-1]^=128,this.keccak()}writeInto(e){Ke(this,!1),K(e),this.finish();const r=this.state,{blockLen:t}=this;for(let n=0,i=e.length;n<i;){this.posOut>=t&&this.keccak();const o=Math.min(t-this.posOut,i-n);e.set(r.subarray(this.posOut,this.posOut+o),n),this.posOut+=o,n+=o}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return Ee(e),this.xofInto(new Uint8Array(e))}digestInto(e){if($r(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,Ge(this.state)}_cloneInto(e){const{blockLen:r,suffix:t,outputLen:n,rounds:i,enableXOF:o}=this;return e||(e=new Yt(r,t,n,o,i)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=i,e.suffix=t,e.outputLen=n,e.enableXOF=o,e.destroyed=this.destroyed,e}}const Is=((s,e,r,t={})=>Br(()=>new Yt(e,s,r),t))(1,136,32),Xi=60;class Zi{constructor(){this.jwks=null}setJWKSEndpoint(e){try{this.jwks=Jn(new URL(e)),d.log("[CROSSx] JWKS 엔드포인트 설정:",e)}catch(r){d.warn("[CROSSx] JWKS 엔드포인트 URL 파싱 실패:",r)}}async verifyJWT(e,r){try{const t=this.decodeJWT(e);d.log("[CROSSx] JWT 디코딩 성공:",{sub:t.sub,exp:t.exp,iat:t.iat});const n=Math.floor(Date.now()/1e3);if(t.exp&&t.exp+Xi<n)return d.warn("[CROSSx] 토큰 만료:",{exp:t.exp,now:n,만료시간:new Date(t.exp*1e3).toISOString()}),{payload:t,valid:!1,signatureVerified:!1};if(!t.sub)return d.warn("[CROSSx] JWT에 sub(사용자ID) 없음"),{payload:t,valid:!1,signatureVerified:!1};if(this.jwks)try{const{payload:i}=await $n(e,this.jwks,{algorithms:["RS256","ES256"]});return d.log("[CROSSx] JWT 서명 검증 성공"),{payload:i,valid:!0,signatureVerified:!0}}catch(i){if(i instanceof Error&&(i.name==="JWSSignatureVerificationFailed"||i.name==="JWTClaimValidationFailed"))return d.error("[CROSSx] JWT 서명 검증 실패:",i),{payload:t,valid:!1,signatureVerified:!1};d.warn("[CROSSx] JWKS 엔드포인트 접근 불가 — 서명 미검증 모드로 전환")}return d.log("[CROSSx] JWT 검증 성공 (서명 미검증 — JWKS 미설정 또는 접근 불가)"),{payload:t,valid:!0,signatureVerified:!1}}catch(t){throw d.error("[CROSSx] JWT 검증 중 에러:",t),t}}decodeJWT(e){return zn(e)}recoverPersonalSignSigner(e,r){const t=new TextEncoder().encode(e),n=new TextEncoder().encode(`Ethereum Signed Message:
|
|
6
|
+
${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);const o=Is(i),a=r.startsWith("0x")?r.slice(2):r;if(a.length!==130)throw new Error(`서명 길이가 유효하지 않습니다: 130 hex 문자 예상, 현재 ${a.length}`);const c=Qi(a),l=c.slice(0,32),u=c.slice(32,64),f=c[64],g=f>=27?f-27:f,v=new Fi.Signature(Ts(l),Ts(u)).addRecoveryBit(g).recoverPublicKey(o).toBytes(!1).slice(1),S=Is(v);return"0x"+Xe(S.slice(12))}}function Qi(s){const e=new Uint8Array(s.length/2);for(let r=0;r<e.length;r++)e[r]=parseInt(s.substring(r*2,r*2+2),16);return e}function Ts(s){let e="0x";for(const r of s)e+=r.toString(16).padStart(2,"0");return BigInt(e)}const eo=3e4,to=1e3;class ro{async request(e){const r=e.retries??0;for(let t=0;t<=r;t++){try{const n=await this._doRequest(e);if(n.status<500||t===r)return n}catch(n){if(t===r)throw n}await new Promise(n=>setTimeout(n,to*2**t))}throw new Error("Unexpected: retry loop exited without result")}async _doRequest(e){const r=new AbortController,t=setTimeout(()=>r.abort(),e.timeoutMs??eo);try{const n=await fetch(e.url,{method:e.method,headers:e.headers,body:e.body?JSON.stringify(e.body):void 0,signal:r.signal,credentials:e.credentials});let i;const o=await n.text();try{i=o?JSON.parse(o):null}catch{i={_raw:o}}return{status:n.status,data:i,headers:Object.fromEntries(n.headers.entries())}}finally{clearTimeout(t)}}}const so=new Set(["https://cross-wallet-oauth.crosstoken.io","https://stg-cross-wallet-oauth.crosstoken.io","https://dev-cross-wallet-oauth.crosstoken.io"]);class Me{static generateRandom16Hex(){const e=new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,r=>r.toString(16).padStart(2,"0")).join("")}static parseJwtPayload(e){const r=e.split(".");if(r.length<2)throw new Error("Invalid JWT format");const t=(r[1]??"").replace(/-/g,"+").replace(/_/g,"/"),n=atob(t);return JSON.parse(n)}static async sha256Hex(e){const r=new TextEncoder().encode(e),t=await crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(t),n=>n.toString(16).padStart(2,"0")).join("")}static async verifyIdTokenNonce(e,r){const t=Me.parseJwtPayload(e),n=t.nonce,i=typeof t.iss=="string"?t.iss:"(unknown)";if(d.log("[CROSSx] nonce 검증 시작 —",{iss:i,nonceClaimType:typeof n,nonceClaimPresent:typeof n=="string"&&n!=="",appleNonceSupported:t.nonce_supported??"(field absent)"}),i.includes("securetoken.google.com")){d.log("[CROSSx] Firebase ID Token 감지 — nonce 검증 skip.","서버 측에서 Google/Apple nonce 검증이 완료된 것으로 간주합니다.");return}if(typeof n!="string"||n===""){d.warn("[CROSSx] nonce claim 누락 — nonce 검증 skip.",{iss:i,keys:Object.keys(t)});return}if(i.includes("appleid.apple.com")){const o=await Me.sha256Hex(r);if(d.log("[CROSSx] Apple nonce 검증 —",{expectedHashLength:o.length,receivedHashLength:n.length,match:n===o}),n!==o)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다")}else if(d.log("[CROSSx] Google nonce 검증 —",{expectedLength:r.length,receivedLength:n.length,match:n===r}),n!==r)throw new Error("ID Token nonce 불일치 — replay attack 가능성이 있습니다");d.log("[CROSSx] nonce 검증 성공 —",{iss:i})}openAuth(e){return new Promise((r,t)=>{const n=Math.max(e.width??500,500),i=Math.max(e.height??700,700),o=window.screenX+(window.outerWidth-n)/2,a=window.screenY+(window.outerHeight-i)/2,c=Me.generateRandom16Hex(),l=Me.generateRandom16Hex(),u=e.authUrl.includes("?")?"&":"?",f=`${e.authUrl}${u}state=${c}&nonce=${l}`;d.log("[CROSSx] OAuth 팝업 열기 — state, nonce 생성 완료:",{stateLength:c.length,nonceLength:l.length,authUrlBase:e.authUrl});const g=window.open(f,"CROSSx OAuth",`width=${n},height=${i},left=${o},top=${a}`);if(!g){t(new Error("팝업 창을 열 수 없습니다. 팝업 차단을 해제해 주세요."));return}const p=setTimeout(()=>{d.warn("[CROSSx] OAuth 타임아웃 (5분) — postMessage를 수신하지 못했습니다"),L(),t(new Error("Authentication timeout"))},5*60*1e3),y=10,v=30;let S=0,I=null;const T=()=>{clearInterval(H),d.warn("[CROSSx] COOP 감지 — OAuth 서버 응답을 "+v+"초간 대기합니다"),I=setTimeout(()=>{L(),t(new Error("OAuth 서버로부터 응답을 받지 못했습니다. 브라우저 보안 정책(COOP)으로 인해 팝업 통신이 차단되었을 수 있습니다. 다시 시도해 주세요."))},v*1e3)},H=setInterval(()=>{S++;try{g.closed&&(S<=y?T():(L(),t(new Error("로그인이 취소되었습니다"))))}catch{T()}},1e3),L=()=>{clearTimeout(p),clearInterval(H),I&&clearTimeout(I),window.removeEventListener("message",V)},V=B=>{if(B.origin!==e.expectedOrigin)return;if(!so.has(B.origin)){d.error("[CROSSx] postMessage origin이 허용 목록에 없음:",B.origin),L(),t(new Error("Unauthorized OAuth origin"));return}L();const ce=typeof B.data.status=="string",U=ce?B.data.data??{}:B.data;d.log("[CROSSx] OAuth postMessage 수신 —",{format:ce?"wrapped":"flat",status:ce?B.data.status:"(flat)"});const z=(U==null?void 0:U.state)??B.data.state;if(!z||z!==c){t(new Error("OAuth state mismatch — possible CSRF attack"));return}if(ce&&B.data.status!=="success"){d.error("[CROSSx] OAuth 실패:",U==null?void 0:U.error),t(new Error((U==null?void 0:U.error)||"Authentication failed"));return}if(!ce&&(U!=null&&U.error)){d.error("[CROSSx] OAuth 실패:",U.error),t(new Error(U.error||"Authentication failed"));return}const Z=U==null?void 0:U.idToken,$=U==null?void 0:U.accessToken,C=$??Z,D=(U==null?void 0:U.email)||void 0;if(d.log("[CROSSx] OAuth 토큰 수신:",{hasAccessToken:!!$,hasIdToken:!!Z,hasEmail:!!D}),!C){d.error("[CROSSx] 토큰을 찾을 수 없음:",B.data),t(new Error("Token not found in response"));return}const w={token:C,email:D},_=m=>{Me.verifyIdTokenNonce(m,l).then(()=>r(w)).catch(b=>{d.error("[CROSSx] nonce 검증 실패:",b),t(b instanceof Error?b:new Error("nonce verification failed"))})};$?$.split(".").length===3?_($):Z?_(Z):(d.warn("[CROSSx] opaque accessToken만 수신 (idToken 없음) — nonce 검증 불가.","서버 측 nonce 검증이 필요합니다."),r(w)):Z?_(Z):t(new Error("Token not found in response"))};window.addEventListener("message",V)})}}const Qe="crossx_wallet_data",Ve="crossx_mock_pin_hash";class no{constructor(e,r){this.storage=e,this.pinStore=r??null}async checkWallet(){if(this.migrateScenario!==void 0)return d.log("[Mock] checkWallet → migration_required"),"migration_required";const r=await this.storage.get(Qe)?"exists":"not_found";return d.log(`[Mock] checkWallet → ${r}`),r}async getOrCreateWallet(e){var r;try{const t=await this.storage.get(Qe);if(t)return t;const n={id:e,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(Qe,n);const i=(r=this.pinStore)==null?void 0:r.get();return i&&(await this.storage.set(Ve,i),d.log("[Mock] 지갑 생성 — PIN 저장됨")),n}catch(t){throw new x(h.WALLET_CREATION_FAILED,"지갑 생성에 실패했습니다",t)}}async getAddresses(e){const r=await this.storage.get(Qe);return r?[{address:r.address,index:0}]:[]}async getAddress(e,r){return{address:this.generateMockEvmAddress(),derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){const t="mock-"+crypto.randomUUID();return d.log(`[Mock] prepare action=${e} → uuid=${t}`),{uuid:t,expiresAt:new Date(Date.now()+3e5).toISOString()}}async signMessage(e,r,t,n=0,i,o){return d.log(`[Mock] signMessage chainId=${r} index=${n} uuid=${i} from=${o}: "${t}"`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTypedData(e,r,t,n=0,i,o){return d.log(`[Mock] signTypedData chainId=${r} index=${n} uuid=${i} from=${o}`),{chainId:r,signature:this.generateMockSignature(),format:"hex"}}async signTransaction(e,r,t,n=0,i){d.log(`[Mock] signTransaction chainId=${r} index=${n} uuid=${i}:`,t);const o="0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("");return{chainId:r,signature:this.generateMockSignature(),txHash:o,format:"hex"}}async sendTransaction(e,r,t,n){return d.log(`[Mock] sendTransaction chainId=${r} uuid=${n}:`,t),{txHash:"0x"+Array(64).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}async verifyPin(e){var t;if(d.log("[Mock] verifyPin"),this.pinScenario==="wrong")return!1;const r=await this.storage.get(Ve);return r&&r!==e?!1:(r||await this.storage.set(Ve,e),(t=this.pinStore)==null||t.set(e),d.log("[Mock] verifyPin → 성공"),!0)}async changePin(e,r){var i;if(d.log("[Mock] changePin"),this.pinScenario==="wrong")throw new x(h.PIN_WRONG,"Incorrect PIN.");const t=(i=this.pinStore)==null?void 0:i.get(),n=await this.storage.get(Ve);if(n&&t&&n!==t)throw new x(h.PIN_WRONG,"Incorrect PIN.");await this.storage.set(Ve,r),d.log("[Mock] changePin 완료")}async migrateWallet(e,r){var i;if(d.log(`[Mock] migrateWallet pin=${e} sub=${r}`),this.migrateScenario==="wrong_pin")throw new x(h.MIGRATION_FAILED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:4,maxAttempts:5});if(this.migrateScenario!==void 0&&typeof this.migrateScenario=="object"&&"locked"in this.migrateScenario){const a={permanent:!1,lockExpiresAt:Math.floor(Date.now()/1e3)+1800,remainingAttempts:0,maxAttempts:5,...this.migrateScenario.locked};throw new x(h.MIGRATION_PIN_LOCKED,"Too many incorrect PIN attempts. Your account has been temporarily locked.",a)}const t={id:r,address:this.generateMockEvmAddress(),derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()};await this.storage.set(Qe,t);const n=(i=this.pinStore)==null?void 0:i.get();return n&&(await this.storage.set(Ve,n),d.log("[Mock] 마이그레이션 — PIN 저장됨")),t}async getShareC(){return d.log("[Mock] getShareC"),"mock-share-c-"+crypto.randomUUID()}async verifyRecoveryPin(e,r){return d.log("[Mock] verifyRecoveryPin"),{valid:!0}}generateMockEvmAddress(){return"0x"+Array(40).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}generateMockSignature(){return"0x"+Array(130).fill(0).map(()=>Math.floor(Math.random()*16).toString(16)).join("")}}class $e{constructor(e,r,t,n,i){this._refreshPromise=null,this._walletStatusCache=null,this.adapterConfig=e,this.projectId=e.projectId,this.storage=r,this.transport=t,this.tokenStore=n,this.pinStore=i??null}setOnUnauthorized(e){this._onUnauthorized=e}setTokenRefresher(e){this._onTokenRefresh=e}getPin(){var e;return((e=this.pinStore)==null?void 0:e.get())??void 0}get baseUrl(){return this.adapterConfig.gatewayUrl}async ensureValidToken(){const e=this.tokenStore.get();if(e&&!this.tokenStore.isExpiringSoon(hr))return e;const r=!e||this.tokenStore.isExpiringSoon(hr);if(this._onTokenRefresh){if(await this.deduplicatedRefresh()){const n=this.tokenStore.get();if(n)return n}if(r)throw new x(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(e)return d.warn("[CROSSx] 토큰 갱신 실패 — 기존 토큰으로 요청 시도"),e;throw new x(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}deduplicatedRefresh(){return this._refreshPromise?this._refreshPromise:(d.log("[CROSSx] 토큰 만료 임박/만료 — 자동 갱신 시도"),this._refreshPromise=this._onTokenRefresh().finally(()=>{this._refreshPromise=null}),this._refreshPromise)}async request(e,r,t,n=!1){var c,l,u,f;const i=await this.ensureValidToken(),o=`${this.baseUrl}${r}`,a={Authorization:`Bearer ${i}`,"Content-Type":"application/json","X-Project-Id":this.projectId};try{const p=(await this.transport.request({url:o,method:e,headers:a,body:t??void 0})).data;if(p&&typeof p.code=="number"){if(p.code<0||p.code>=400){const y=p.message||p.data||"API 요청에 실패했습니다";d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 200):",{code:p.code,message:y,url:o,method:e});const v=$e.mapGatewayError(p.code,p.data);if(v===h.AUTH_NOT_AUTHENTICATED&&!n&&this._onTokenRefresh){if(d.warn("[CROSSx] Gateway -10002 감지 — 토큰 갱신 후 재시도"),await this.deduplicatedRefresh())return this.request(e,r,t,!0);throw new x(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if(v===h.USER_NOT_FOUND)throw d.warn("[CROSSx] Gateway -10033 감지 — 유저 미존재, 강제 로그아웃"),(c=this._onUnauthorized)==null||c.call(this),new x(h.USER_NOT_FOUND,$e.getGatewayErrorMessage(p.code,y));const S=v===h.AUTH_NOT_AUTHENTICATED?h.SESSION_EXPIRED:v,I=S===h.SESSION_EXPIRED?"인증 세션이 만료되었습니다. 다시 로그인해 주세요.":$e.getGatewayErrorMessage(p.code,y),T=p.data,H=v===h.PIN_LOCKED?$e.extractLockDetails(T):T??void 0;throw new x(S,I,H)}return d.log("[CROSSx] Wallet Gateway API 성공:",{code:p.code,url:o,method:e}),p.data??p}return p}catch(g){if(g instanceof x)throw g;const p=((l=g.response)==null?void 0:l.status)??g.status;if((p===401||p===403)&&!n&&this._onTokenRefresh){if(d.warn(`[CROSSx] HTTP ${p} 감지 — 토큰 갱신 후 재시도`),await this.deduplicatedRefresh())return this.request(e,r,t,!0);throw new x(h.SESSION_EXPIRED,"인증 세션이 만료되었습니다. 다시 로그인해 주세요.")}if((u=g.response)!=null&&u.data){const y=g.response.data,v=y.message||y.data||"API 요청에 실패했습니다",S=y.code||"UNKNOWN";throw d.error("[CROSSx] Wallet Gateway API 에러 (HTTP 에러):",{code:S,message:v,url:o,method:e,status:(f=g.response)==null?void 0:f.status}),new x(h.UNKNOWN_ERROR,`Wallet Gateway 오류 (${S}): ${v}`)}throw g}}async checkWallet(){d.log("[CROSSx] GET /mnemonic/check");const e=await this.request("GET","/mnemonic/check");return d.log("[CROSSx] /mnemonic/check 결과:",e.result),this._walletStatusCache=e.result,e.result}async getOrCreateWallet(e){let r;if(this._walletStatusCache!==null?(r=this._walletStatusCache,this._walletStatusCache=null,d.log("[CROSSx] getOrCreateWallet — 캐시된 상태 사용:",r)):(d.log("[CROSSx] GET /mnemonic/check — 지갑 상태 확인"),r=await this.checkWallet(),this._walletStatusCache=null),r==="migration_required")throw d.log("[CROSSx] migration_required → MIGRATION_BACKUP_EXISTS throw"),new x(h.MIGRATION_BACKUP_EXISTS,"CROSSx 백업이 존재합니다. 마이그레이션을 진행해 주세요.");if(r==="exists"){d.log("[CROSSx] 기존 지갑 발견 — POST /mnemonic/address(0)로 주소 조회");const i=await this.getAddress(e,0);return d.log("[CROSSx] 주소 조회 완료 — address:",i.address),{id:e,address:i.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}d.log("[CROSSx] POST /mnemonic/create — 신규 지갑 생성");const t={ignoreBackup:!1,password:this.requirePin()},n=await this.request("POST","/mnemonic/create",t);return d.log("[CROSSx] /mnemonic/create 완료 — address:",n.address),{id:e,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async getAddresses(e){return((await this.request("GET","/mnemonic/addresses")).addresses??[]).map(t=>({address:t.address,index:t.index}))}async getAddress(e,r){const t={password:this.requirePin(),index:r};return{address:(await this.request("POST","/mnemonic/address",t)).address,derivationPath:`m/44'/60'/0'/0/${r}`}}async prepare(e,r){let t;switch(e){case"sign":case"send":if(!r.tx)throw new x(h.TX_INVALID_PARAMS,"prepare: tx가 필요합니다");t={unsignedTx:this.buildUnsignedTx(r.tx)};break;case"sign-message":if(!r.message)throw new x(h.TX_INVALID_PARAMS,"prepare: message가 필요합니다");t={message:r.message},r.from&&(t.from=r.from);break;case"sign-typed-data":if(!r.typedData)throw new x(h.TX_INVALID_PARAMS,"prepare: typedData가 필요합니다");t={typedData:r.typedData},r.from&&(t.from=r.from);break}const n={action:e,params:t},i=await this.request("POST","/mnemonic/prepare",n);return{uuid:i.uuid,expiresAt:i.expiresAt}}async signMessage(e,r,t,n,i,o){const a={message:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST","/mnemonic/sign-message",a);return{chainId:r,signature:c.signature,format:"hex"}}async signTypedData(e,r,t,n,i,o){const a={typedData:t,password:this.requirePin()};i&&(a.uuid=i),o&&(a.from=o);const c=await this.request("POST",`/mnemonic/sign-typed-data/${encodeURIComponent(r)}`,a);return{chainId:r,signature:c.signature,format:"hex"}}buildUnsignedTx(e){return{from:e.from,to:e.to,value:e.value,data:e.data,nonce:e.nonce!==void 0?`0x${e.nonce.toString(16)}`:void 0,gasLimit:e.gasLimit,gasPrice:e.gasPrice,maxFeePerGas:e.maxFeePerGas,maxPriorityFeePerGas:e.maxPriorityFeePerGas,chainId:e.chainId!==void 0?`0x${e.chainId.toString(16)}`:void 0}}async signTransaction(e,r,t,n,i){const o={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};i&&(o.uuid=i);const a=await this.request("POST",`/mnemonic/sign/${encodeURIComponent(r)}`,o);return{chainId:r,signature:a.signedTx,txHash:a.txHash,format:"hex"}}async sendTransaction(e,r,t,n){const i={unsignedTx:this.buildUnsignedTx(t),password:this.requirePin()};return n&&(i.uuid=n),{txHash:(await this.request("POST",`/mnemonic/send/${encodeURIComponent(r)}`,i)).txHash}}async migrateWallet(e,r){d.log("[CROSSx][Migration Phase 4] POST /mnemonic/migrate 호출");const t={recoveryPin:e,sub:r,password:this.requirePin()},n=await this.request("POST","/mnemonic/migrate",t);return d.log("[CROSSx][Migration Phase 4] /mnemonic/migrate 완료 — address:",n.address),{id:r,address:n.address,derivationPath:"m/44'/60'/0'/0/0",createdAt:Date.now()}}async withdrawWallet(e){const r={confirmation:e,password:this.requirePin()};await this.request("POST","/mnemonic/withdraw",r)}async verifyPin(e){const r={password:e},t=await this.request("POST","/mnemonic/verify-password",r);if(!t.valid&&t.passwordStatus){const n=t.passwordStatus;if(n.permanent)throw new x(h.PIN_LOCKED,"Incorrect PIN.",{permanent:!0,lockExpiresAt:n.lockExpiresAt,remainingAttempts:0,maxAttempts:n.maxAttempts});if(n.remainingAttempts===0&&n.lockExpiresAt){const i=n.lockExpiresAt>1e10?n.lockExpiresAt:n.lockExpiresAt*1e3;throw new x(h.PIN_LOCKED,"Too many failed PIN attempts.",{permanent:!1,lockExpiresAt:i,remainingAttempts:0,maxAttempts:n.maxAttempts})}if(n.remainingAttempts!=null&&n.remainingAttempts>0)throw new x(h.PIN_LOCKED,"Incorrect PIN.",{permanent:!1,lockExpiresAt:0,remainingAttempts:n.remainingAttempts,maxAttempts:n.maxAttempts})}return t.valid}async changePin(e,r){const t={password:this.requirePin(),newPassword:r};await this.request("POST","/mnemonic/change-password",t)}async getShareC(){const e={password:this.requirePin()};return(await this.request("POST","/mnemonic/share-c",e)).shareC}async verifyRecoveryPin(e,r){const t={recoveryPin:e,sub:r};return this.request("POST","/mnemonic/verify-recovery-pin",t)}requirePin(){const e=this.getPin();if(!e)throw new x(h.PIN_NOT_SET,"PIN이 설정되지 않았습니다. PIN을 입력해 주세요.");return e}static extractLockDetails(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e,t={},n=(r==null?void 0:r.lockExpiresAt)??(r==null?void 0:r.lock_expires_at);n&&(t.lockExpiresAt=n>1e10?n:n*1e3);const i=(r==null?void 0:r.remainingAttempts)??(r==null?void 0:r.remaining_attempts);typeof i=="number"&&(t.remainingAttempts=i);const o=(r==null?void 0:r.maxAttempts)??(r==null?void 0:r.max_attempts);return typeof o=="number"&&(t.maxAttempts=o),typeof(r==null?void 0:r.permanent)=="boolean"&&(t.permanent=r.permanent),t}static hasLockInfo(e){const r=(e==null?void 0:e.lockStatus)??(e==null?void 0:e.lock_status)??e;return!r||typeof r!="object"?!1:typeof r.remainingAttempts=="number"||typeof r.remaining_attempts=="number"||typeof r.maxAttempts=="number"||typeof r.max_attempts=="number"}static mapGatewayError(e,r){switch(e){case-10002:return h.AUTH_NOT_AUTHENTICATED;case-10001:return h.UNKNOWN_ERROR;case-10006:return h.GATEWAY_INTERNAL_ERROR;case-10007:return h.BROADCAST_FAILED;case-10008:return h.GATEWAY_LOCK_CONFLICT;case-10004:return h.WALLET_ALREADY_EXISTS;case-10005:return h.WALLET_NOT_FOUND;case-10011:return h.WALLET_NOT_FOUND;case-10030:return h.WALLET_INCONSISTENT_STATE;case-10010:return h.MIGRATION_FAILED;case-10012:return h.MIGRATION_BACKUP_EXISTS;case-10013:return h.WITHDRAW_FAILED;case-10033:return h.USER_NOT_FOUND;case-10027:return h.MIGRATION_PIN_LOCKED;case-10022:return h.PROJECT_NOT_REGISTERED;case-10023:return h.PROJECT_ID_MISSING;case-10024:return h.ORIGIN_NOT_ALLOWED;case-10025:return h.INVALID_APP_TYPE;case-10028:return $e.hasLockInfo(r)?h.PIN_LOCKED:h.PIN_WRONG;case-10029:return h.PIN_INVALID;case-10031:return h.PIN_LOCKED;case-10032:return h.PIN_REPEATED_PATTERN;case-10026:return h.TYPED_DATA_CHAIN_ID_MISMATCH;case-10014:case-10015:case-10019:return h.PREPARE_FAILED;case-10016:return h.PREPARE_EXPIRED;case-10017:case-10018:return h.PREPARE_MISMATCH;case-10020:return h.CHAIN_NOT_SUPPORTED;case-10021:return h.INVALID_CHAIN;case-10040:return h.HMAC_REQUIRED;case-10041:return h.HMAC_VERIFICATION_FAILED;default:return h.UNKNOWN_ERROR}}static getGatewayErrorMessage(e,r){switch(e){case-10002:return"Session expired. Please sign in again.";case-10004:return"Wallet already exists for this user.";case-10005:return"User wallet not found.";case-10006:return"Internal server error. Please try again later.";case-10007:return"Transaction broadcast failed. Please try again.";case-10008:return"Another operation is in progress. Please try again later.";case-10013:return"Withdraw failed. Please try again.";case-10022:return"Project is not whitelisted. Verify your projectId and register the current origin in the management console.";case-10023:return"Project ID is required. Set the projectId field in SDKConfig.";case-10024:return"Origin or App ID is required. Register the current domain or set X-App-Id header.";case-10025:return"Invalid app type. X-App-Type must be android, ios, or windows.";case-10026:return"Domain chainId mismatch: the chainId in typedData.domain does not match the request chainId.";case-10027:return"Too many incorrect PIN attempts. Your account has been temporarily locked.";case-10028:return"Incorrect PIN. Please try again.";case-10029:return"Sequential PIN is not allowed. Please choose a different PIN.";case-10030:return"Wallet is in an inconsistent state. Please contact support.";case-10031:return"Too many failed PIN attempts. Your account is temporarily locked.";case-10032:return"Repeated digit pattern is not allowed. Please choose a different PIN.";case-10033:return"User not found. You have been signed out.";case-10040:return"HMAC signature header is required.";case-10041:return"HMAC signature verification failed.";default:return`Request failed (${e}): ${r}`}}}class et{constructor(e,r){this.cache=new Map,this.loadedAt=0,this.usingFallback=!1,this.adapterConfig=e,this.projectId=e.projectId,this.transport=r}get baseUrl(){return this.adapterConfig.gatewayUrl}async getChains(){if(this.isCacheValid())return Array.from(this.cache.values());try{const e=await this.request("/chains");this.handleEnvelopeError(e);const r=e.data.chains;return this.populateCache(r,!1),r}catch{const e=et.fallbackChains();return this.populateCache(e,!0),e}}async getChain(e){const t=(await this.getChains()).find(n=>n.chainId===e);return t||this.fallbackOrThrow(e)}invalidateCache(){this.cache.clear(),this.loadedAt=0,this.usingFallback=!1}isCacheValid(){if(this.loadedAt===0)return!1;const e=this.usingFallback?tn:en;return e===0?!0:Date.now()-this.loadedAt<e}populateCache(e,r){this.cache.clear();for(const t of e)this.cache.set(t.chainId,t);this.loadedAt=Date.now(),this.usingFallback=r}async request(e){return(await this.transport.request({url:`${this.baseUrl}${e}`,method:"GET",headers:{"X-Project-Id":this.projectId}})).data}handleEnvelopeError(e){if(e.code<0){const r=typeof e.data=="string"?e.data:e.message??"체인 레지스트리 요청에 실패했습니다";throw new x(et.mapErrorCode(e.code),r)}}fallbackOrThrow(e){const r=et.fallbackChains().find(t=>t.chainId===e);if(r)return r;throw new x(h.CHAIN_NOT_SUPPORTED,`지원하지 않는 체인: ${e}`)}static fallbackChains(){return Object.values(tt).map(e=>({chainId:e.caipId,rpcUrl:e.rpcUrl}))}static mapErrorCode(e){switch(e){case-10020:return h.CHAIN_NOT_SUPPORTED;case-10021:return h.INVALID_CHAIN;case-10022:return h.PROJECT_NOT_REGISTERED;case-10023:return h.PROJECT_ID_MISSING;case-10024:return h.APP_IDENTIFIER_MISSING;case-10025:return h.INVALID_APP_TYPE;default:return h.UNKNOWN_ERROR}}}const Rs="__crossx-confirm-style",ee="__crossx-confirm-overlay",io={light:{bg:"#FFFFFF",border:"rgba(18,18,18,0.05)",titleColor:"#121212",subtitleColor:"rgba(18,18,18,0.7)",labelColor:"rgba(18,18,18,0.5)",valueColor:"#121212",pillBg:"rgba(18,18,18,0.05)",pillFromColor:"rgba(18,18,18,0.5)",pillAmtColor:"#121212",divider:"rgba(18,18,18,0.1)",closeColor:"#121212",closeHoverBg:"rgba(18,18,18,0.05)",copyColor:"rgba(18,18,18,0.5)",inputBg:"rgba(18,18,18,0.05)",inputBorder:"rgba(18,18,18,0.1)",hintColor:"rgba(18,18,18,0.5)",surfaceSubtle:"rgba(18,18,18,0.1)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#E70077",errorColor:"#E70077",onPrimary:"#FFFFFF"},dark:{bg:"#121212",border:"rgba(255,255,255,0.05)",titleColor:"#FFFFFF",subtitleColor:"rgba(255,255,255,0.7)",labelColor:"rgba(255,255,255,0.5)",valueColor:"#FFFFFF",pillBg:"rgba(255,255,255,0.05)",pillFromColor:"rgba(255,255,255,0.5)",pillAmtColor:"#FFFFFF",divider:"rgba(255,255,255,0.1)",closeColor:"#FFFFFF",closeHoverBg:"rgba(255,255,255,0.05)",copyColor:"rgba(255,255,255,0.5)",inputBg:"rgba(255,255,255,0.05)",inputBorder:"rgba(255,255,255,0.1)",hintColor:"rgba(255,255,255,0.5)",surfaceSubtle:"rgba(255,255,255,0.1)",primary:"#019D92",primaryGlow:"rgba(1,157,146,0.15)",secondary:"#E70077",errorColor:"#E70077",onPrimary:"#FFFFFF"}};function Os(s,e){const r=io[s],t=e==null?void 0:e[s];return t?{...r,...t.primary!==void 0&&{primary:t.primary},...t.secondary!==void 0&&{secondary:t.secondary},...t.onPrimary!==void 0&&{onPrimary:t.onPrimary},...t.borderDefault!==void 0&&{border:t.borderDefault},...t.borderSubtle!==void 0&&{divider:t.borderSubtle,inputBorder:t.borderSubtle},...t.textIconPrimary!==void 0&&{titleColor:t.textIconPrimary,valueColor:t.textIconPrimary,pillAmtColor:t.textIconPrimary,closeColor:t.textIconPrimary},...t.textIconSecondary!==void 0&&{subtitleColor:t.textIconSecondary},...t.textIconTertiary!==void 0&&{labelColor:t.textIconTertiary,pillFromColor:t.textIconTertiary,copyColor:t.textIconTertiary,hintColor:t.textIconTertiary},...t.surfaceDefault!==void 0&&{pillBg:t.surfaceDefault,closeHoverBg:t.surfaceDefault,inputBg:t.surfaceDefault},...t.surfaceSubtle!==void 0&&{surfaceSubtle:t.surfaceSubtle},...t.bg!==void 0&&{bg:t.bg},...t.error!==void 0&&{errorColor:t.error}}:r}const oo=`
|
|
7
7
|
@import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;600&display=swap');
|
|
8
8
|
|
|
9
9
|
#${ee} {
|
|
@@ -1847,10 +1847,10 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
1847
1847
|
color: var(--cx-title);
|
|
1848
1848
|
margin: 0;
|
|
1849
1849
|
}
|
|
1850
|
-
`;function pe(){let s=document.getElementById(Rs);s||(s=document.createElement("style"),s.id=Rs,document.head.appendChild(s)),s.textContent=oo}function _e(s){const e=r=>r.stopPropagation();for(const r of["pointerdown","pointerup","mousedown","mouseup","click"])s.addEventListener(r,e);s.setAttribute("data-vaul-no-drag","");for(const r of["touchstart","touchend"])s.addEventListener(r,e);s.addEventListener("touchmove",r=>{r.stopPropagation();let t=r.target;for(;t&&t!==s;){const n=window.getComputedStyle(t);if((n.overflowY==="auto"||n.overflowY==="scroll")&&t.scrollHeight>t.clientHeight)return;t=t.parentElement}r.preventDefault()},{passive:!1}),document.body.appendChild(s)}const ao=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;function xt(){if(ao()){const e=window.scrollY;return document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.left="0",document.body.style.right="0",()=>{document.body.style.position="",document.body.style.top="",document.body.style.left="",document.body.style.right="",window.scrollTo(0,e)}}const s=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=s}}function re(s){return s?s.length<=13?s:`${s.slice(0,6)}…${s.slice(-4)}`:"—"}function co(s,e="CROSS",r=18){if(!s||s==="0x"||s==="0x0")return null;try{const t=BigInt(s);if(t===0n)return null;const n=jt(t,r);return n==="0"?null:`${n} ${e}`}catch{return null}}const Ps={1:"Ethereum Mainnet",5:"Goerli Testnet",11155111:"Ethereum Sepolia",17e3:"Ethereum Holesky",10:"Optimism",420:"Optimism Goerli",42161:"Arbitrum One",421614:"Arbitrum Sepolia",8453:"Base",84532:"Base Sepolia",137:"Polygon",80002:"Polygon Amoy",56:"BNB Smart Chain",97:"BNB Testnet",43114:"Avalanche C-Chain",43113:"Avalanche Fuji",250:"Fantom Opera",2020:"Ronin",202601:"Ronin Saigon",612044:"CROSS Testnet",612055:"CROSS Mainnet"};function Cs(s){const e=parseInt(s.split(":")[1]??"",10);return!isNaN(e)&&Ps[e]?Ps[e]:s}function jt(s,e){if(s===0n)return"0";const r=10n**BigInt(e),t=s/r,o=(s%r).toString().padStart(e,"0").slice(0,6).replace(/0+$/,"");return o?`${t}.${o}`:`${t}`}function Xt(s){try{const e=BigInt(s),r=e/1000000000n,n=(e%1000000000n).toString().padStart(9,"0").slice(0,2).replace(/0+$/,"");return n?`${r}.${n}`:`${r}`}catch{return s}}function lo(s){try{return BigInt(s).toLocaleString()}catch{return s}}function uo(s){const{gasLimit:e,gasPrice:r,maxFeePerGas:t,maxPriorityFeePerGas:n,nativeSymbol:i="ETH",nativeDecimals:o=18}=s;if(!e)return null;try{const a=BigInt(e),c=lo(e);if(t){const l=a*BigInt(t);return{isDynamic:!0,estTxFee:`${jt(l,o)} ${i}`,maxFeeGwei:Xt(t),maxPriorityFeeGwei:n?Xt(n):void 0,gasLimitFormatted:c}}if(r){const l=a*BigInt(r);return{isDynamic:!1,estTxFee:`${jt(l,o)} ${i}`,gasPriceGwei:Xt(r),gasLimitFormatted:c}}return{isDynamic:!1,estTxFee:`${a.toLocaleString()} gas`,gasLimitFormatted:c}}catch{return null}}function ks(s){const e=uo(s);if(!e)return
|
|
1850
|
+
`;function pe(){let s=document.getElementById(Rs);s||(s=document.createElement("style"),s.id=Rs,document.head.appendChild(s)),s.textContent=oo}function _e(s){const e=r=>r.stopPropagation();for(const r of["pointerdown","pointerup","mousedown","mouseup","click"])s.addEventListener(r,e);s.setAttribute("data-vaul-no-drag","");for(const r of["touchstart","touchend"])s.addEventListener(r,e);s.addEventListener("touchmove",r=>{r.stopPropagation();let t=r.target;for(;t&&t!==s;){const n=window.getComputedStyle(t);if((n.overflowY==="auto"||n.overflowY==="scroll")&&t.scrollHeight>t.clientHeight)return;t=t.parentElement}r.preventDefault()},{passive:!1}),document.body.appendChild(s)}const ao=()=>/iPad|iPhone|iPod/.test(navigator.userAgent)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1;function xt(){if(ao()){const e=window.scrollY;return document.body.style.position="fixed",document.body.style.top=`-${e}px`,document.body.style.left="0",document.body.style.right="0",()=>{document.body.style.position="",document.body.style.top="",document.body.style.left="",document.body.style.right="",window.scrollTo(0,e)}}const s=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=s}}function re(s){return s?s.length<=13?s:`${s.slice(0,6)}…${s.slice(-4)}`:"—"}function co(s,e="CROSS",r=18){if(!s||s==="0x"||s==="0x0")return null;try{const t=BigInt(s);if(t===0n)return null;const n=jt(t,r);return n==="0"?null:`${n} ${e}`}catch{return null}}const Ps={1:"Ethereum Mainnet",5:"Goerli Testnet",11155111:"Ethereum Sepolia",17e3:"Ethereum Holesky",10:"Optimism",420:"Optimism Goerli",42161:"Arbitrum One",421614:"Arbitrum Sepolia",8453:"Base",84532:"Base Sepolia",137:"Polygon",80002:"Polygon Amoy",56:"BNB Smart Chain",97:"BNB Testnet",43114:"Avalanche C-Chain",43113:"Avalanche Fuji",250:"Fantom Opera",2020:"Ronin",202601:"Ronin Saigon",612044:"CROSS Testnet",612055:"CROSS Mainnet"};function Cs(s){const e=parseInt(s.split(":")[1]??"",10);return!isNaN(e)&&Ps[e]?Ps[e]:s}function jt(s,e){if(s===0n)return"0";const r=10n**BigInt(e),t=s/r,o=(s%r).toString().padStart(e,"0").slice(0,6).replace(/0+$/,"");return o?`${t}.${o}`:`${t}`}function Xt(s){try{const e=BigInt(s),r=e/1000000000n,n=(e%1000000000n).toString().padStart(9,"0").slice(0,2).replace(/0+$/,"");return n?`${r}.${n}`:`${r}`}catch{return s}}function lo(s){try{return BigInt(s).toLocaleString()}catch{return s}}function uo(s){const{gasLimit:e,gasPrice:r,maxFeePerGas:t,maxPriorityFeePerGas:n,nativeSymbol:i="ETH",nativeDecimals:o=18}=s;if(!e)return null;try{const a=BigInt(e),c=lo(e);if(t){const l=a*BigInt(t);return{isDynamic:!0,estTxFee:`${jt(l,o)} ${i}`,maxFeeGwei:Xt(t),maxPriorityFeeGwei:n?Xt(n):void 0,gasLimitFormatted:c}}if(r){const l=a*BigInt(r);return{isDynamic:!1,estTxFee:`${jt(l,o)} ${i}`,gasPriceGwei:Xt(r),gasLimitFormatted:c}}return{isDynamic:!1,estTxFee:`${a.toLocaleString()} gas`,gasLimitFormatted:c}}catch{return null}}function ks(s){const e=uo(s);if(!e)return J("Estimated fee","<span>—</span>");let r=J("Est. Tx Fee",`<span>${e.estTxFee}</span>`);return e.isDynamic?(e.maxPriorityFeeGwei!==void 0&&(r+=J("Max Priority Fee",`<span>${e.maxPriorityFeeGwei} Gwei</span>`)),e.maxFeeGwei!==void 0&&(r+=J("Max Gas Fee",`<span>${e.maxFeeGwei} Gwei</span>`))):e.gasPriceGwei!==void 0&&(r+=J("Gas Price",`<span>${e.gasPriceGwei} Gwei</span>`)),e.gasLimitFormatted&&(r+=J("Gas Limit",`<span>${e.gasLimitFormatted}</span>`)),r}const Te=`<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
|
1851
1851
|
<rect x="9" y="9" width="13" height="13" rx="2"/>
|
|
1852
1852
|
<path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/>
|
|
1853
|
-
</svg>`,
|
|
1853
|
+
</svg>`,ae=`<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round">
|
|
1854
1854
|
<line x1="18" y1="6" x2="6" y2="18"/>
|
|
1855
1855
|
<line x1="6" y1="6" x2="18" y2="18"/>
|
|
1856
1856
|
</svg>`,ho=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
@@ -1866,23 +1866,23 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
1866
1866
|
<circle cx="12" cy="12" r="12" fill="var(--cx-error)"/>
|
|
1867
1867
|
<circle cx="12" cy="12" r="5.5" stroke="white" stroke-width="1.5"/>
|
|
1868
1868
|
<path d="M12 9.5v3l2 1.5" stroke="white" stroke-width="1.5" stroke-linecap="round"/>
|
|
1869
|
-
</svg>`;function le(s){return[`--cx-bg:${s.bg}`,`--cx-border:${s.border}`,`--cx-title:${s.titleColor}`,`--cx-subtitle:${s.subtitleColor}`,`--cx-label:${s.labelColor}`,`--cx-value:${s.valueColor}`,`--cx-pill-bg:${s.pillBg}`,`--cx-pill-from:${s.pillFromColor}`,`--cx-pill-amt:${s.pillAmtColor}`,`--cx-divider:${s.divider}`,`--cx-close:${s.closeColor}`,`--cx-close-hover:${s.closeHoverBg}`,`--cx-copy:${s.copyColor}`,`--cx-input-bg:${s.inputBg}`,`--cx-input-border:${s.inputBorder}`,`--cx-hint:${s.hintColor}`,`--cx-surface-subtle:${s.surfaceSubtle}`,`--cx-primary:${s.primary}`,`--cx-primary-glow:${s.primaryGlow}`,`--cx-secondary:${s.secondary}`,`--cx-error:${s.errorColor}`,`--cx-on-primary:${s.onPrimary}`].join(";")}function
|
|
1869
|
+
</svg>`;function le(s){return[`--cx-bg:${s.bg}`,`--cx-border:${s.border}`,`--cx-title:${s.titleColor}`,`--cx-subtitle:${s.subtitleColor}`,`--cx-label:${s.labelColor}`,`--cx-value:${s.valueColor}`,`--cx-pill-bg:${s.pillBg}`,`--cx-pill-from:${s.pillFromColor}`,`--cx-pill-amt:${s.pillAmtColor}`,`--cx-divider:${s.divider}`,`--cx-close:${s.closeColor}`,`--cx-close-hover:${s.closeHoverBg}`,`--cx-copy:${s.copyColor}`,`--cx-input-bg:${s.inputBg}`,`--cx-input-border:${s.inputBorder}`,`--cx-hint:${s.hintColor}`,`--cx-surface-subtle:${s.surfaceSubtle}`,`--cx-primary:${s.primary}`,`--cx-primary-glow:${s.primaryGlow}`,`--cx-secondary:${s.secondary}`,`--cx-error:${s.errorColor}`,`--cx-on-primary:${s.onPrimary}`].join(";")}function J(s,e){return`
|
|
1870
1870
|
<div class="__crossx-row">
|
|
1871
1871
|
<span class="__crossx-row-label">${s}</span>
|
|
1872
1872
|
<div class="__crossx-row-value">${e}</div>
|
|
1873
1873
|
</div>`}function _o(s,e){const r=e,t=mt(s.dappName),n=s.to?`<span class="__crossx-addr-text">${re(s.to)}</span>
|
|
1874
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1874
|
+
<button class="__crossx-copy-btn" data-copy="${N(s.to)}" title="Copy address">${Te}</button>`:"<span>—</span>",i=ks(s),o=s.data??"0x",a=document.createElement("div");return a.id=ee,a.innerHTML=`
|
|
1875
1875
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-tx" style="${le(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1876
1876
|
<div class="__crossx-header">
|
|
1877
1877
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
1878
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
1878
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
|
|
1879
1879
|
</div>
|
|
1880
1880
|
<hr class="__crossx-divider">
|
|
1881
1881
|
<div class="__crossx-body">
|
|
1882
1882
|
<div class="__crossx-body-cols">
|
|
1883
1883
|
<div class="__crossx-col-left">
|
|
1884
1884
|
<p class="__crossx-sig-subtitle">
|
|
1885
|
-
<span class="__crossx-sig-origin">${
|
|
1885
|
+
<span class="__crossx-sig-origin">${N(t)} </span>is requesting a Signature
|
|
1886
1886
|
</p>
|
|
1887
1887
|
<div class="__crossx-addr-pill">
|
|
1888
1888
|
${Zt}
|
|
@@ -1893,11 +1893,11 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
1893
1893
|
<hr class="__crossx-divider __crossx-divider--cols">
|
|
1894
1894
|
<div class="__crossx-col-right-sign">
|
|
1895
1895
|
<div class="__crossx-rows">
|
|
1896
|
-
${
|
|
1897
|
-
${
|
|
1896
|
+
${J("To",n)}
|
|
1897
|
+
${J("Network",`<span>${Cs(s.chainId)}</span>`)}
|
|
1898
1898
|
${i}
|
|
1899
1899
|
</div>
|
|
1900
|
-
<pre class="__crossx-raw-tx">${
|
|
1900
|
+
<pre class="__crossx-raw-tx">${N(o)}</pre>
|
|
1901
1901
|
</div>
|
|
1902
1902
|
</div>
|
|
1903
1903
|
<div class="__crossx-btn-row">
|
|
@@ -1907,21 +1907,21 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
1907
1907
|
</div>
|
|
1908
1908
|
</div>
|
|
1909
1909
|
`,a}function go(s,e){const r=e,t=s.nativeSymbol??"ETH",n=s.nativeDecimals??18,i=mt(s.dappName),o=s.to?`<span class="__crossx-addr-text">${re(s.to)}</span>
|
|
1910
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1910
|
+
<button class="__crossx-copy-btn" data-copy="${N(s.to)}" title="Copy address">${Te}</button>`:"<span>—</span>",a=ks(s),l=co(s.value,t,n)??"—",u=document.createElement("div");return u.id=ee,u.innerHTML=`
|
|
1911
1911
|
<div class="__crossx-card __crossx-card--migration __crossx-card--send-tx" style="${le(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1912
1912
|
<div class="__crossx-header">
|
|
1913
1913
|
<p class="__crossx-title" id="__crossx-ttl">Approve transaction</p>
|
|
1914
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
1914
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
|
|
1915
1915
|
</div>
|
|
1916
1916
|
<hr class="__crossx-divider">
|
|
1917
1917
|
<div class="__crossx-body">
|
|
1918
1918
|
<p class="__crossx-tx-subtitle">
|
|
1919
|
-
<span class="__crossx-sig-origin">${
|
|
1919
|
+
<span class="__crossx-sig-origin">${N(i)}</span> wants your permission to approve the following transaction.
|
|
1920
1920
|
</p>
|
|
1921
1921
|
<div class="__crossx-body-cols">
|
|
1922
1922
|
<div class="__crossx-rows">
|
|
1923
|
-
${
|
|
1924
|
-
${
|
|
1923
|
+
${J("To",o)}
|
|
1924
|
+
${J("Network",`<span>${Cs(s.chainId)}</span>`)}
|
|
1925
1925
|
${a}
|
|
1926
1926
|
</div>
|
|
1927
1927
|
<div class="__crossx-pill">
|
|
@@ -1932,17 +1932,17 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
1932
1932
|
<button class="__crossx-approve-btn" id="__crossx-confirm-btn">Approve</button>
|
|
1933
1933
|
</div>
|
|
1934
1934
|
</div>
|
|
1935
|
-
`,
|
|
1936
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1937
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1938
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1935
|
+
`,u}function mt(s){var e;if(s)return s;try{return((e=window.location)==null?void 0:e.hostname)||"This site"}catch{return"This site"}}function N(s){return s.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function xo(s){return typeof s=="string"&&/^0x[0-9a-fA-F]{40}$/i.test(s)}function mo(s){if(typeof s=="string")return N(s);if(typeof s=="number"||typeof s=="bigint"||typeof s=="boolean")return String(s);try{return N(JSON.stringify(s))}catch{return String(s)}}function wo(s,e){const r=J("From",`<span class="__crossx-addr-text">${re(s.from)}</span>
|
|
1936
|
+
<button class="__crossx-copy-btn" data-copy="${N(s.from)}" title="Copy address">${Te}</button>`),t=s.to?J("To",`<span class="__crossx-addr-text">${re(s.to)}</span>
|
|
1937
|
+
<button class="__crossx-copy-btn" data-copy="${N(s.to)}" title="Copy address">${Te}</button>`):"",n=s.amount?J("Transfer",`<span>${N(s.amount)}</span>`):"",i=s.fees?J("Tx Fee",`<span>${N(s.fees)}</span>`):"",o=s.txHash?J("Tx Hash",`<span class="__crossx-addr-text">${re(s.txHash)}</span>
|
|
1938
|
+
<button class="__crossx-copy-btn" data-copy="${N(s.txHash)}" title="Copy hash">${Te}</button>`):"",a=s.total?`<div class="__crossx-total-pill">
|
|
1939
1939
|
<span class="__crossx-total-label">Total<br>(including fees)</span>
|
|
1940
|
-
<span class="__crossx-total-amount">${
|
|
1940
|
+
<span class="__crossx-total-amount">${N(s.total)}</span>
|
|
1941
1941
|
</div>`:"",c=document.createElement("div");return c.id=ee,c.innerHTML=`
|
|
1942
1942
|
<div class="__crossx-card __crossx-card--migration" style="${le(e)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1943
1943
|
<div class="__crossx-header">
|
|
1944
1944
|
<p class="__crossx-title" id="__crossx-ttl">Transaction complete</p>
|
|
1945
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
1945
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
|
|
1946
1946
|
</div>
|
|
1947
1947
|
<hr class="__crossx-divider">
|
|
1948
1948
|
<div class="__crossx-body">
|
|
@@ -1970,34 +1970,34 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
1970
1970
|
</div>
|
|
1971
1971
|
</div>
|
|
1972
1972
|
</div>
|
|
1973
|
-
`,r}function bo(s,e,r){const t=e.status!=="reverted"&&e.status!=="timeout",n=e.status==="timeout",i=s.querySelector("#__crossx-ttl"),o=s.querySelector(".__crossx-header");if(i){const
|
|
1974
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1975
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1976
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
1973
|
+
`,r}function bo(s,e,r){const t=e.status!=="reverted"&&e.status!=="timeout",n=e.status==="timeout",i=s.querySelector("#__crossx-ttl"),o=s.querySelector(".__crossx-header");if(i){const y=n?po:t?"":fo,v=n?"Transaction timeout":t?"Transaction complete":"Transaction failed";y?(i.style.display="flex",i.style.alignItems="center",i.style.gap="8px",i.innerHTML=`${y}<span>${v}</span>`):i.textContent=v}if(o&&!s.querySelector("#__crossx-close-btn")){const y=document.createElement("button");y.className="__crossx-close",y.id="__crossx-close-btn",y.setAttribute("aria-label","Close"),y.innerHTML=ae,o.appendChild(y)}const a=s.querySelector("#__crossx-progress-body");if(!a)return;const c=e.from?J("From",`<span class="__crossx-addr-text">${re(e.from)}</span>
|
|
1974
|
+
<button class="__crossx-copy-btn" data-copy="${N(e.from)}" title="Copy address">${Te}</button>`):"",l=e.to?J("To",`<span class="__crossx-addr-text">${re(e.to)}</span>
|
|
1975
|
+
<button class="__crossx-copy-btn" data-copy="${N(e.to)}" title="Copy address">${Te}</button>`):"",u=e.amount?J("Transfer",`<span>${N(e.amount)}</span>`):"",f=e.fees?J("Tx Fee",`<span>${N(e.fees)}</span>`):"",g=e.txHash?J("Tx Hash",`<span class="__crossx-addr-text">${re(e.txHash)}</span>
|
|
1976
|
+
<button class="__crossx-copy-btn" data-copy="${N(e.txHash)}" title="Copy hash">${Te}</button>`):"",p=e.total?`<div class="__crossx-total-pill">
|
|
1977
1977
|
<span class="__crossx-total-label">Total<br>(including fees)</span>
|
|
1978
|
-
<span class="__crossx-total-amount">${
|
|
1978
|
+
<span class="__crossx-total-amount">${N(e.total)}</span>
|
|
1979
1979
|
</div>`:"";a.innerHTML=`
|
|
1980
1980
|
<div class="__crossx-rows">
|
|
1981
1981
|
${c}
|
|
1982
1982
|
${l}
|
|
1983
|
-
${
|
|
1983
|
+
${u}
|
|
1984
1984
|
${f}
|
|
1985
1985
|
${g}
|
|
1986
1986
|
</div>
|
|
1987
1987
|
${p}
|
|
1988
1988
|
<button class="__crossx-approve-btn" id="__crossx-done-btn">${t?"All Done":"Done"}</button>
|
|
1989
|
-
`,a.querySelectorAll(".__crossx-copy-btn").forEach(
|
|
1989
|
+
`,a.querySelectorAll(".__crossx-copy-btn").forEach(y=>{y.addEventListener("click",v=>{var I;v.stopPropagation();const S=y.dataset.copy;S&&((I=navigator.clipboard)==null||I.writeText(S).catch(()=>{}))})})}function So(s,e){const r=e,t=mt(s.dappName),n=N(s.message),i=document.createElement("div");return i.id=ee,i.innerHTML=`
|
|
1990
1990
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-msg" style="${le(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
1991
1991
|
<div class="__crossx-header">
|
|
1992
1992
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
1993
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
1993
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
|
|
1994
1994
|
</div>
|
|
1995
1995
|
<hr class="__crossx-divider">
|
|
1996
1996
|
<div class="__crossx-body">
|
|
1997
1997
|
<div class="__crossx-body-cols">
|
|
1998
1998
|
<div class="__crossx-col-left">
|
|
1999
1999
|
<p class="__crossx-sig-subtitle">
|
|
2000
|
-
<span class="__crossx-sig-origin">${
|
|
2000
|
+
<span class="__crossx-sig-origin">${N(t)} </span>is requesting a Signature
|
|
2001
2001
|
</p>
|
|
2002
2002
|
<div class="__crossx-addr-pill">
|
|
2003
2003
|
${Zt}
|
|
@@ -2017,24 +2017,24 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2017
2017
|
`,i}function vo(s,e){const r=e,t=mt(s.dappName);let n={};if(typeof s.typedData=="string")try{n=JSON.parse(s.typedData)}catch{}else s.typedData&&typeof s.typedData=="object"&&(n=s.typedData);const i=n.primaryType??"—",o=n.message??{};let a=`
|
|
2018
2018
|
<div class="__crossx-td-row">
|
|
2019
2019
|
<span class="__crossx-td-label">Primary Type</span>
|
|
2020
|
-
<span class="__crossx-td-value">${
|
|
2021
|
-
</div>`;for(const[l,
|
|
2022
|
-
<button class="__crossx-copy-btn" data-copy="${
|
|
2020
|
+
<span class="__crossx-td-value">${N(i)}</span>
|
|
2021
|
+
</div>`;for(const[l,u]of Object.entries(o)){const f=mo(u),p=xo(u)?`<span class="__crossx-addr-text">${re(u)}</span>
|
|
2022
|
+
<button class="__crossx-copy-btn" data-copy="${N(String(u))}" title="Copy">${Te}</button>`:`<span>${f}</span>`;a+=`
|
|
2023
2023
|
<div class="__crossx-td-row">
|
|
2024
|
-
<span class="__crossx-td-label">${
|
|
2024
|
+
<span class="__crossx-td-label">${N(l)}</span>
|
|
2025
2025
|
<div class="__crossx-td-value">${p}</div>
|
|
2026
2026
|
</div>`}const c=document.createElement("div");return c.id=ee,c.innerHTML=`
|
|
2027
2027
|
<div class="__crossx-card __crossx-card--migration __crossx-card--sign-typed" style="${le(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2028
2028
|
<div class="__crossx-header">
|
|
2029
2029
|
<p class="__crossx-title" id="__crossx-ttl">Signature Request</p>
|
|
2030
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
2030
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
|
|
2031
2031
|
</div>
|
|
2032
2032
|
<hr class="__crossx-divider">
|
|
2033
2033
|
<div class="__crossx-body">
|
|
2034
2034
|
<div class="__crossx-body-cols">
|
|
2035
2035
|
<div class="__crossx-col-left">
|
|
2036
2036
|
<p class="__crossx-sig-subtitle">
|
|
2037
|
-
<span class="__crossx-sig-origin">${
|
|
2037
|
+
<span class="__crossx-sig-origin">${N(t)} </span>is requesting a Signature
|
|
2038
2038
|
</p>
|
|
2039
2039
|
<div class="__crossx-addr-pill">
|
|
2040
2040
|
${Zt}
|
|
@@ -2054,7 +2054,7 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2054
2054
|
`,c}const Eo=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round">
|
|
2055
2055
|
<line x1="12" y1="5" x2="12" y2="19"/>
|
|
2056
2056
|
<line x1="5" y1="12" x2="19" y2="12"/>
|
|
2057
|
-
</svg>`;function
|
|
2057
|
+
</svg>`;function Ao(s,e,r){const t=r==null?void 0:r.toLowerCase(),n=s.map(o=>{const a=t&&o.address.toLowerCase()===t;return`<button class="__crossx-wallet-item" data-wallet-index="${o.index}" data-wallet-address="${N(o.address)}">
|
|
2058
2058
|
<span class="__crossx-wallet-idx">${o.index+1}</span>
|
|
2059
2059
|
<span class="__crossx-wallet-addr">${re(o.address)}</span>${a?'<span class="__crossx-wallet-selected">selected</span>':""}
|
|
2060
2060
|
</button>`}).join(""),i=document.createElement("div");return i.id=ee,i.innerHTML=`
|
|
@@ -2064,7 +2064,7 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2064
2064
|
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:0;">Select Connected Wallet</p>
|
|
2065
2065
|
<p class="__crossx-subtitle--body">Please select the wallet you previously used for this game to continue.</p>
|
|
2066
2066
|
</div>
|
|
2067
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
2067
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
|
|
2068
2068
|
</div>
|
|
2069
2069
|
<hr class="__crossx-divider">
|
|
2070
2070
|
<div class="__crossx-body">
|
|
@@ -2088,7 +2088,7 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2088
2088
|
</div>
|
|
2089
2089
|
</div>
|
|
2090
2090
|
</div>
|
|
2091
|
-
`,i}const
|
|
2091
|
+
`,i}const Io=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2092
2092
|
<path d="M26.693 21.193c-.028-3.168 2.587-4.712 2.706-4.786-1.477-2.16-3.77-2.454-4.58-2.484-1.944-.197-3.804 1.148-4.793 1.148-.992 0-2.52-1.12-4.147-1.09-2.13.032-4.1 1.239-5.198 3.133-2.222 3.855-.569 9.562 1.593 12.69 1.061 1.535 2.318 3.258 3.975 3.196 1.6-.064 2.2-1.03 4.133-1.03 1.928 0 2.48 1.03 4.172.997 1.72-.03 2.806-1.56 3.862-3.1 1.211-1.779 1.713-3.495 1.74-3.583-.037-.017-3.427-1.316-3.463-5.09z" fill="currentColor"/>
|
|
2093
2093
|
<path d="M23.527 11.876c.877-1.065 1.471-2.545 1.31-4.024-1.266.053-2.807.845-3.718 1.907-.813.946-1.53 2.468-1.34 3.915 1.41.107 2.852-.716 3.748-1.798z" fill="currentColor"/>
|
|
2094
2094
|
</svg>`,To=`<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
@@ -2112,13 +2112,13 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2112
2112
|
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:0;">CROSS Wallet</p>
|
|
2113
2113
|
<p class="__crossx-subtitle">Sign in instantly with your social account</p>
|
|
2114
2114
|
</div>
|
|
2115
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
2115
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
|
|
2116
2116
|
</div>
|
|
2117
2117
|
<hr class="__crossx-divider">
|
|
2118
2118
|
<div class="__crossx-body">
|
|
2119
2119
|
<div class="__crossx-login-btn-row">
|
|
2120
2120
|
<button class="__crossx-login-btn" id="__crossx-apple-btn" type="button">
|
|
2121
|
-
<span class="__crossx-login-icon" style="color:var(--cx-value);">${
|
|
2121
|
+
<span class="__crossx-login-icon" style="color:var(--cx-value);">${Io}</span>
|
|
2122
2122
|
<span class="__crossx-login-btn-label">Sign in with Apple</span>
|
|
2123
2123
|
</button>
|
|
2124
2124
|
<button class="__crossx-login-btn" id="__crossx-google-btn" type="button">
|
|
@@ -2131,29 +2131,29 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2131
2131
|
</p>
|
|
2132
2132
|
</div>
|
|
2133
2133
|
</div>
|
|
2134
|
-
`,n}function Oo(s,e){const r=s,t=document.createElement("div");t.id=ee;const n=
|
|
2135
|
-
<p class="__crossx-session-account-label">${
|
|
2136
|
-
<p class="__crossx-session-account-email">${
|
|
2134
|
+
`,n}function Oo(s,e){const r=s,t=document.createElement("div");t.id=ee;const n=N(e.message).replace(/\n/g,"<br>"),i=e.email?`<div class="__crossx-session-account-card">
|
|
2135
|
+
<p class="__crossx-session-account-label">${N(e.accountLabel)}</p>
|
|
2136
|
+
<p class="__crossx-session-account-email">${N(e.email)}</p>
|
|
2137
2137
|
</div>`:"";return t.innerHTML=`
|
|
2138
2138
|
<div class="__crossx-card __crossx-card--migration" style="${le(r)}" role="alertdialog" aria-modal="true" aria-labelledby="__crossx-session-header-title" aria-describedby="__crossx-session-msg">
|
|
2139
2139
|
<div class="__crossx-header">
|
|
2140
|
-
<p class="__crossx-title" id="__crossx-session-header-title">${
|
|
2141
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
2140
|
+
<p class="__crossx-title" id="__crossx-session-header-title">${N(e.title)}</p>
|
|
2141
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
|
|
2142
2142
|
</div>
|
|
2143
2143
|
<hr class="__crossx-divider">
|
|
2144
2144
|
<div class="__crossx-body" style="padding:20px 24px 24px;display:flex;flex-direction:column;gap:16px;">
|
|
2145
2145
|
<div class="__crossx-session-hero">
|
|
2146
|
-
<p class="__crossx-session-hero-title">${
|
|
2146
|
+
<p class="__crossx-session-hero-title">${N(e.title)}</p>
|
|
2147
2147
|
<p class="__crossx-session-hero-message" id="__crossx-session-msg">${n}</p>
|
|
2148
2148
|
</div>
|
|
2149
2149
|
${i}
|
|
2150
2150
|
<div class="__crossx-btn-row">
|
|
2151
|
-
<button class="__crossx-cancel-btn" id="__crossx-session-signout">${
|
|
2152
|
-
<button class="__crossx-confirm-btn" id="__crossx-session-signin">${
|
|
2151
|
+
<button class="__crossx-cancel-btn" id="__crossx-session-signout">${N(e.signOutLabel)}</button>
|
|
2152
|
+
<button class="__crossx-confirm-btn" id="__crossx-session-signin">${N(e.signInAgainLabel)}</button>
|
|
2153
2153
|
</div>
|
|
2154
2154
|
</div>
|
|
2155
2155
|
</div>
|
|
2156
|
-
`,t}function Po(s,e=!0){const r=s,t=e?`<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
2156
|
+
`,t}function Po(s,e=!0){const r=s,t=e?`<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>`:"",n=e?'<button class="__crossx-skip-btn" id="__crossx-skip-btn">Skip for Now</button>':"",i=document.createElement("div");return i.id=ee,i.innerHTML=`
|
|
2157
2157
|
<div class="__crossx-card __crossx-card--migration" style="${le(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2158
2158
|
<div class="__crossx-header">
|
|
2159
2159
|
<p class="__crossx-title" id="__crossx-ttl">Wallet Found on Social Account 🎉</p>
|
|
@@ -2173,11 +2173,11 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2173
2173
|
${n}
|
|
2174
2174
|
</div>
|
|
2175
2175
|
</div>
|
|
2176
|
-
`,i}function Co(s,e){const r=s,{errorMessage:t,attemptCount:n,maxAttempts:i=5}=e??{},o=!!t,a=o?" --error":"",c=n!=null&&n>0?`<p class="__crossx-pin-attempt">${n}/${i}</p>`:"",l=n!=null&&n>=3?'<p class="__crossx-pin-warning">Your account will be locked after further failures.</p>':"",
|
|
2176
|
+
`,i}function Co(s,e){const r=s,{errorMessage:t,attemptCount:n,maxAttempts:i=5}=e??{},o=!!t,a=o?" --error":"",c=n!=null&&n>0?`<p class="__crossx-pin-attempt">${n}/${i}</p>`:"",l=n!=null&&n>=3?'<p class="__crossx-pin-warning">Your account will be locked after further failures.</p>':"",u=o?`<p class="__crossx-pin-error-text">${t}</p>`:"",f=document.createElement("div");return f.id=ee,f.innerHTML=`
|
|
2177
2177
|
<div class="__crossx-card __crossx-card--migration" style="${le(r)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2178
2178
|
<div class="__crossx-header">
|
|
2179
2179
|
<p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
|
|
2180
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
2180
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
|
|
2181
2181
|
</div>
|
|
2182
2182
|
<hr class="__crossx-divider">
|
|
2183
2183
|
<div class="__crossx-pin-center">
|
|
@@ -2190,14 +2190,14 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2190
2190
|
<input class="__crossx-pin-input${a}" type="tel" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off">
|
|
2191
2191
|
</div>
|
|
2192
2192
|
<p class="__crossx-pin-hint">Enter your 4-digit PIN to recover your wallet.</p>
|
|
2193
|
-
${
|
|
2193
|
+
${u}
|
|
2194
2194
|
</div>
|
|
2195
2195
|
</div>
|
|
2196
2196
|
`,f}function ko(s){const e=new Date(s),r=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],t=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=r[e.getDay()],i=t[e.getMonth()],o=e.getDate(),a=String(e.getHours()).padStart(2,"0"),c=String(e.getMinutes()).padStart(2,"0");return`${n}, ${i} ${o} ${a}:${c}`}function No(s,e,r){const t=s,n=e<=0,i=n?null:Date.now()+e*1e3,o=i?ko(i):null,a=document.createElement("div");return a.id=ee,a.innerHTML=`
|
|
2197
2197
|
<div class="__crossx-card __crossx-card--migration" style="${le(t)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2198
2198
|
<div class="__crossx-header">
|
|
2199
2199
|
<p class="__crossx-title" id="__crossx-ttl">Import from Social Backup</p>
|
|
2200
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
2200
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
|
|
2201
2201
|
</div>
|
|
2202
2202
|
<hr class="__crossx-divider">
|
|
2203
2203
|
<div class="__crossx-pin-center">
|
|
@@ -2216,13 +2216,13 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2216
2216
|
`,{overlay:a,startCountdown:l=>{if(n||!i)return()=>{};const f=setInterval(()=>{Date.now()>=i&&(clearInterval(f),l())},1e3);return()=>clearInterval(f)}}}function Lo(s){const r=[s.check1,s.check2].map((t,n)=>`
|
|
2217
2217
|
<div class="__crossx-pw-notice-item" data-check-index="${n}" role="checkbox" aria-checked="false" tabindex="0">
|
|
2218
2218
|
<div class="__crossx-pw-notice-check" id="__crossx-notice-check-${n}">${$o}</div>
|
|
2219
|
-
<span class="__crossx-pw-notice-item-text">${
|
|
2219
|
+
<span class="__crossx-pw-notice-item-text">${N(t)}</span>
|
|
2220
2220
|
</div>
|
|
2221
2221
|
`).join("");return`
|
|
2222
2222
|
<div class="__crossx-header">
|
|
2223
|
-
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${
|
|
2224
|
-
<p class="__crossx-pw-subtitle">${
|
|
2225
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
2223
|
+
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${N(s.title)}</p>
|
|
2224
|
+
<p class="__crossx-pw-subtitle">${N(s.headerSubtitle)}</p>
|
|
2225
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
|
|
2226
2226
|
</div>
|
|
2227
2227
|
<hr class="__crossx-divider">
|
|
2228
2228
|
<div class="__crossx-pw-body">
|
|
@@ -2230,38 +2230,39 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2230
2230
|
<div class="__crossx-pw-notice-header">
|
|
2231
2231
|
<div class="__crossx-pw-notice-title-row">
|
|
2232
2232
|
<span class="__crossx-pw-notice-icon">${Wo}</span>
|
|
2233
|
-
<p class="__crossx-pw-notice-title">${
|
|
2233
|
+
<p class="__crossx-pw-notice-title">${N(s.noticeTitle)}</p>
|
|
2234
2234
|
</div>
|
|
2235
|
-
<p class="__crossx-pw-notice-desc">${
|
|
2235
|
+
<p class="__crossx-pw-notice-desc">${N(s.noticeDesc)}</p>
|
|
2236
2236
|
</div>
|
|
2237
2237
|
<div class="__crossx-pw-notice-checks" id="__crossx-notice-checks">
|
|
2238
2238
|
${r}
|
|
2239
2239
|
</div>
|
|
2240
2240
|
</div>
|
|
2241
2241
|
<button class="__crossx-pw-btn --disabled" id="__crossx-pin-notice-next"
|
|
2242
|
-
data-next-label="${
|
|
2243
|
-
data-submit-label="${
|
|
2244
|
-
${
|
|
2242
|
+
data-next-label="${N(s.nextButton)}"
|
|
2243
|
+
data-submit-label="${N(s.submitButton)}">
|
|
2244
|
+
${N(s.nextButton)}
|
|
2245
2245
|
</button>
|
|
2246
2246
|
</div>
|
|
2247
2247
|
<div class="__crossx-home-indicator"></div>
|
|
2248
|
-
`}function Qt(s){const e=!!s.lockExpiresAt&&s.lockExpiresAt>Date.now(),r=s.lockExpiresAt?` data-lock-expires="${s.lockExpiresAt}"`:"",t=s.headerSubtitle?`<p class="__crossx-pin6-header-sub">${
|
|
2248
|
+
`}function Qt(s){const e=!!s.lockExpiresAt&&s.lockExpiresAt>Date.now(),r=s.lockExpiresAt?` data-lock-expires="${s.lockExpiresAt}"`:"",t=s.headerSubtitle?`<p class="__crossx-pin6-header-sub">${N(s.headerSubtitle)}</p>`:"",n=s.subtitle?`<p class="__crossx-pin6-subtitle">${N(s.subtitle)}</p>`:"",i=s.errorMessage?`<p class="__crossx-pin6-error" id="__crossx-pin6-error">${N(s.errorMessage)}</p>`:'<p class="__crossx-pin6-error" id="__crossx-pin6-error"></p>',o=e?`<p class="__crossx-pin6-lock-msg" id="__crossx-pin6-lock-msg">
|
|
2249
2249
|
${Ls}
|
|
2250
2250
|
<span id="__crossx-pin6-lock-countdown"></span>
|
|
2251
|
-
</p>`:"",a=s.attemptCount!=null&&s.attemptCount>0?`<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt">${s.attemptCount}/${s.maxAttempts??"?"}</p>`:'<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt"></p>',
|
|
2251
|
+
</p>`:"",a=s.warningMessage&&s.attemptCount!=null&&s.attemptCount>0?`<p class="__crossx-pin6-warning" id="__crossx-pin6-warning">${N(s.warningMessage)}</p>`:'<p class="__crossx-pin6-warning" id="__crossx-pin6-warning"></p>',c=s.attemptCount!=null&&s.attemptCount>0?`<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt">${s.attemptCount}/${s.maxAttempts??"?"}</p>`:'<p class="__crossx-pin6-attempt" id="__crossx-pin6-attempt"></p>',l=e?" --locked":"",u=Array.from({length:6},(f,g)=>`<input class="__crossx-pin6-box${l}" type="password" maxlength="1" inputmode="numeric" pattern="[0-9]" autocomplete="off" aria-label="PIN digit ${g+1}"${e?" disabled":""}>`).join("");return`
|
|
2252
2252
|
<div class="__crossx-header">
|
|
2253
|
-
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${
|
|
2253
|
+
<p class="__crossx-title" id="__crossx-ttl" style="padding-right:48px;">${N(s.title)}</p>
|
|
2254
2254
|
${t}
|
|
2255
|
-
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${
|
|
2255
|
+
<button class="__crossx-close" id="__crossx-close-btn" aria-label="Close">${ae}</button>
|
|
2256
2256
|
</div>
|
|
2257
2257
|
<hr class="__crossx-divider">
|
|
2258
2258
|
<div class="__crossx-pin6-body"${r}>
|
|
2259
2259
|
${n}
|
|
2260
2260
|
<div class="__crossx-pin6-boxes" id="__crossx-pin6-boxes">
|
|
2261
|
-
${
|
|
2261
|
+
${u}
|
|
2262
2262
|
</div>
|
|
2263
2263
|
${i}
|
|
2264
2264
|
${a}
|
|
2265
|
+
${c}
|
|
2265
2266
|
${o}
|
|
2266
2267
|
</div>
|
|
2267
2268
|
<div class="__crossx-home-indicator"></div>
|
|
@@ -2269,10 +2270,10 @@ ${t.length}`),i=new Uint8Array(n.length+t.length);i.set(n,0),i.set(t,n.length);c
|
|
|
2269
2270
|
<div class="__crossx-card __crossx-card--pin6" style="${le(s)}" role="dialog" aria-modal="true" aria-labelledby="__crossx-ttl">
|
|
2270
2271
|
${e}
|
|
2271
2272
|
</div>
|
|
2272
|
-
`,r}function Do(s,e){if(s.length!==6)return e.tooShort;if(!/^\d+$/.test(s))return e.numbersOnly;if(/(.)\1{2}/.test(s))return e.repeatingDigit;const r=s.split("").map(Number),t=r.every((i,o)=>o===0||i===(r[o-1]+1)%10),n=r.every((i,o)=>o===0||i===(r[o-1]+9)%10);return t||n?e.sequential:s[0]!==s[1]&&s===s.slice(0,2).repeat(3)?e.alternatingPattern:null}function Mo(s){const e=Math.max(0,Math.ceil(s/1e3)),r=Math.floor(e/3600),t=Math.floor(e%3600/60),n=e%60;return r>0?`${r}h ${String(t).padStart(2,"0")}m`:`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`}function er(s,e,r,t,n,i){var
|
|
2273
|
+
`,r}function Do(s,e){if(s.length!==6)return e.tooShort;if(!/^\d+$/.test(s))return e.numbersOnly;if(/(.)\1{2}/.test(s))return e.repeatingDigit;const r=s.split("").map(Number),t=r.every((i,o)=>o===0||i===(r[o-1]+1)%10),n=r.every((i,o)=>o===0||i===(r[o-1]+9)%10);return t||n?e.sequential:s[0]!==s[1]&&s===s.slice(0,2).repeat(3)?e.alternatingPattern:null}function Mo(s){const e=Math.max(0,Math.ceil(s/1e3)),r=Math.floor(e/3600),t=Math.floor(e%3600/60),n=e%60;return r>0?`${r}h ${String(t).padStart(2,"0")}m`:`${String(t).padStart(2,"0")}:${String(n).padStart(2,"0")}`}function er(s,e,r,t,n,i,o){var D,w;let a=!!(i&&i>Date.now()),c=!1;const l=()=>Array.from(s.querySelectorAll(".__crossx-pin6-box")),u=()=>s.querySelector("#__crossx-pin6-boxes"),f=()=>s.querySelector("#__crossx-pin6-error"),g=()=>s.querySelector("#__crossx-pin6-lock-msg"),p=()=>s.querySelector("#__crossx-pin6-lock-countdown"),y=()=>s.querySelector(".__crossx-pin6-body"),v=()=>l().map(_=>_.value).join(""),S=_=>{a=_,l().forEach(m=>{m.disabled=_,m.classList.toggle("--locked",_)})},I=()=>s.querySelector("#__crossx-pin6-attempt"),T=()=>{const _=f();_&&(_.textContent="")},H=()=>o??"Your account will be locked after further failures.",L=()=>s.querySelector("#__crossx-pin6-warning"),V=_=>{var b;let m=L();if(!m){m=document.createElement("p"),m.className="__crossx-pin6-warning",m.id="__crossx-pin6-warning";const A=f();A?A.insertAdjacentElement("afterend",m):(b=y())==null||b.appendChild(m)}m.textContent=_},B=()=>{const _=L();_&&(_.textContent="")},ce=(_,m)=>{var A;let b=I();if(!b){b=document.createElement("p"),b.className="__crossx-pin6-attempt",b.id="__crossx-pin6-attempt";const R=L()??f();R?R.insertAdjacentElement("afterend",b):(A=y())==null||A.appendChild(b)}b.textContent=`${_}/${m}`},U=()=>{const _=I();_&&(_.textContent="")},z=_=>{const m=f();m&&(m.textContent=_);const b=u();b==null||b.classList.add("--shake"),setTimeout(()=>b==null?void 0:b.classList.remove("--shake"),500),l().forEach(A=>{A.value=""}),setTimeout(()=>{var A;return(A=l()[0])==null?void 0:A.focus()},50)},Z=_=>{var P;S(!0),l().forEach(E=>{E.value=""});const m=f();if(m&&(m.textContent="Too many failed attempts. Please wait."),!g()){const E=document.createElement("p");E.className="__crossx-pin6-lock-msg",E.id="__crossx-pin6-lock-msg",E.innerHTML=`${Ls}<span id="__crossx-pin6-lock-countdown"></span>`;const k=f();k?k.insertAdjacentElement("afterend",E):(P=y())==null||P.appendChild(E)}const b=()=>{var M;const E=_-Date.now(),k=p();E<=0?(clearInterval(A),S(!1),(M=g())==null||M.remove(),m&&(m.textContent=""),setTimeout(()=>{var G;return(G=l()[0])==null?void 0:G.focus()},50)):k&&(k.textContent=` ${Mo(E)}`)},A=setInterval(b,1e3);b();const R=new MutationObserver(()=>{document.contains(s)||(clearInterval(A),R.disconnect())});R.observe(document.body,{childList:!0,subtree:!1})},$=async()=>{if(a||c)return;const _=v();if(_.length===6){c=!0,l().forEach(m=>{m.disabled=!0});try{if(n){const m=await n(_);m.ok?e(_):m.lockExpiresAt?(U(),Z(m.lockExpiresAt)):(z(m.error??"Incorrect PIN. Please try again."),m.attemptCount!=null&&m.maxAttempts!=null?(V(H()),ce(m.attemptCount,m.maxAttempts)):(B(),U()))}else e(_)}catch(m){t&&t(m)}finally{c=!1,a||l().forEach(m=>{m.disabled=!1})}}};i&&i>Date.now()?Z(i):setTimeout(()=>{var _;return(_=l()[0])==null?void 0:_.focus()},100);const C=()=>{if(a||c)return;const _=l(),m=_.find(b=>!b.value)??_[_.length-1];m==null||m.focus()};(D=u())==null||D.addEventListener("click",_=>{_.target.classList.contains("__crossx-pin6-box")||C()}),(w=y())==null||w.addEventListener("click",_=>{const m=_.target;m.classList.contains("__crossx-pin6-box")||m.closest("button")||C()}),l().forEach((_,m)=>{_.addEventListener("input",()=>{var A;const b=_.value.replace(/\D/g,"").slice(-1);_.value=b,T(),b&&m<5&&((A=l()[m+1])==null||A.focus()),v().length===6&&setTimeout($,80)}),_.addEventListener("keydown",b=>{var A,R;if(b.key==="Backspace"){if(b.preventDefault(),_.value)_.value="";else if(m>0){const P=l()[m-1];P.value="",P.focus()}}else b.key==="ArrowLeft"&&m>0?(b.preventDefault(),(A=l()[m-1])==null||A.focus()):b.key==="ArrowRight"&&m<5?(b.preventDefault(),(R=l()[m+1])==null||R.focus()):b.key==="Escape"&&r()}),_.addEventListener("paste",b=>{var P,E;b.preventDefault();const A=(((P=b.clipboardData)==null?void 0:P.getData("text"))??"").replace(/\D/g,"").slice(0,6);if(!A)return;const R=l();A.split("").forEach((k,M)=>{R[M]&&(R[M].value=k)}),(E=R[Math.min(A.length-1,5)])==null||E.focus(),T(),v().length===6&&setTimeout($,80)}),_.addEventListener("focus",()=>_.select())})}const Ls=`<svg width="20" height="20" viewBox="0 0 20 20" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2273
2274
|
<path d="M14.5 8.5H14V6.5C14 4.015 11.985 2 9.5 2C7.015 2 5 4.015 5 6.5V8.5H4.5C3.672 8.5 3 9.172 3 10V16.5C3 17.328 3.672 18 4.5 18H14.5C15.328 18 16 17.328 16 16.5V10C16 9.172 15.328 8.5 14.5 8.5ZM10.5 13.415V15C10.5 15.276 10.276 15.5 10 15.5H9C8.724 15.5 8.5 15.276 8.5 15V13.415C8.187 13.196 8 12.847 8 12.5C8 11.672 8.672 11 9.5 11C10.328 11 11 11.672 11 12.5C11 12.847 10.813 13.196 10.5 13.415ZM12.5 8.5H6.5V6.5C6.5 4.843 7.843 3.5 9.5 3.5C11.157 3.5 12.5 4.843 12.5 6.5V8.5Z" fill="currentColor"/>
|
|
2274
2275
|
</svg>`,$o=`<svg width="11" height="9" viewBox="0 0 11 9" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2275
2276
|
<path d="M1 4.5L4 7.5L10 1" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
|
|
2276
2277
|
</svg>`,Wo=`<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
|
|
2277
2278
|
<path d="M12 0C18.6274 0 24 5.37258 24 12C23.9999 18.6273 18.6274 24 12 24C5.37264 24 9.89594e-05 18.6273 0 12C0 5.37258 5.37258 0 12 0ZM10.875 15.127V17.377H13.125V15.127H10.875ZM10.875 6.62207V13.627H13.125V6.62207H10.875Z" fill="currentColor"/>
|
|
2278
|
-
</svg>`;function Uo(s,e,r){var i;const t=s.querySelectorAll(".__crossx-pin-input");t.forEach((o,a)=>{o.addEventListener("input",()=>{const c=o.value.replace(/\D/g,"");o.value=c?c[0]:"",c&&a<3&&t[a+1].focus();const l=Array.from(t).map(d=>d.value).join("");l.length===4&&setTimeout(()=>e(l),200)}),o.addEventListener("keydown",c=>{c.key==="Backspace"&&!o.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),c.key==="Escape"&&r()}),o.addEventListener("keypress",c=>{/[0-9]/.test(c.key)||c.preventDefault()}),o.addEventListener("paste",c=>{var f;c.preventDefault();const l=(((f=c.clipboardData)==null?void 0:f.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!l)return;l.split("").forEach((g,p)=>{t[p]&&(t[p].value=g)});const d=Math.min(l.length,3);t[d].focus(),l.length===4&&setTimeout(()=>e(l),200)})});const n=s.querySelector(".__crossx-pin-inputs");n==null||n.addEventListener("click",o=>{if(!o.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(c=>!c.value)??t[t.length-1];a==null||a.focus()}}),(i=t[0])==null||i.focus()}class Ho{constructor(e="light",r){this.theme=e,this.overrides=r,this.tokens=Os(e,r)}setTheme(e,r){this.theme=e,r!==void 0&&(this.overrides=r),this.tokens=Os(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,r,t){return new Promise(n=>{var b;pe();const i=[...e],o=Io(i,this.tokens,t),a=xt();_e(o);let c=!1;const l=()=>{c||(c=!0,o.remove(),a())},d=y=>{l(),n(y)},f=()=>{l(),n(null)};(()=>{o.querySelectorAll(".__crossx-wallet-item").forEach(y=>{y.addEventListener("click",()=>{const I=y.dataset.walletAddress??"",C=parseInt(y.dataset.walletIndex??"0",10);d({address:I,index:C})})})})();const p=o.querySelector("#__crossx-add-wallet-btn");p&&p.addEventListener("click",async()=>{p.disabled=!0;try{const y=await r();i.push(y);const I=o.querySelector("#__crossx-wallet-list");if(I){const C=document.createElement("button");C.className="__crossx-wallet-item",C.dataset.walletIndex=String(y.index),C.dataset.walletAddress=y.address,C.innerHTML=`<span class="__crossx-wallet-idx">${y.index+1}</span><span class="__crossx-wallet-addr">${re(y.address)}</span>`,C.addEventListener("click",()=>d(y)),I.appendChild(C),C.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{p.disabled=!1}}),(b=o.querySelector("#__crossx-close-btn"))==null||b.addEventListener("click",f),o.addEventListener("click",y=>{y.target===o&&f()});const w=y=>{y.key==="Escape"&&(document.removeEventListener("keydown",w),f())};document.addEventListener("keydown",w)})}showLoginSelector(e){return new Promise(r=>{var c,l,d,f;pe();const t=Ro(this.tokens,e==null?void 0:e.showConnectOtherWallets);_e(t);const n=()=>t.remove(),i=g=>{n(),r(g)},o=()=>{n(),r(null)};(c=t.querySelector("#__crossx-apple-btn"))==null||c.addEventListener("click",()=>i("apple")),(l=t.querySelector("#__crossx-google-btn"))==null||l.addEventListener("click",()=>i("google")),(d=t.querySelector("#__crossx-connect-btn"))==null||d.addEventListener("click",()=>i("external")),(f=t.querySelector("#__crossx-close-btn"))==null||f.addEventListener("click",o),t.addEventListener("click",g=>{g.target===t&&o()}),t.querySelectorAll(".__crossx-login-terms-link").forEach(g=>{g.addEventListener("click",p=>p.stopPropagation())});const a=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",a),o())};document.addEventListener("keydown",a)})}showSessionAlert(e){return new Promise(r=>{var d,f,g;pe();const t=this.messages,n=Oo(this.tokens,{title:e.title,message:e.message,email:e.email,accountLabel:(t==null?void 0:t.sessionAlert_accountLabel)??"Account",signOutLabel:(t==null?void 0:t.sessionAlert_signOutButton)??"Sign out",signInAgainLabel:(t==null?void 0:t.sessionAlert_signInAgainButton)??"Sign in again"}),i=xt();_e(n);let o=!1;const a=()=>{o||(o=!0,n.remove(),i())},c=()=>{a(),r("signout")},l=()=>{a(),r("signin-again")};(d=n.querySelector("#__crossx-session-signout"))==null||d.addEventListener("click",c),(f=n.querySelector("#__crossx-session-signin"))==null||f.addEventListener("click",l),(g=n.querySelector("#__crossx-close-btn"))==null||g.addEventListener("click",c)})}showMigrationFoundPrompt(e){const r=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,c,l;pe();const n=Po(this.tokens,r);_e(n);const i=()=>n.remove(),o=()=>{i(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",o),r){const d=()=>{i(),t("skip")};(c=n.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",d),(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",d),n.addEventListener("click",g=>{g.target===n&&d()});const f=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",f),d())};document.addEventListener("keydown",f)}})}showPinSetupPrompt(e){return new Promise(r=>{pe();const t=this.messages,n={title:(t==null?void 0:t.pinSetup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pinNotice_headerSubtitle)??"Required for transactions, PK/mnemonic export & account deletion.",noticeTitle:(t==null?void 0:t.pinNotice_title)??"PIN Setup Notice",noticeDesc:(t==null?void 0:t.pinNotice_description)??"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",check1:(t==null?void 0:t.pinNotice_check1)??"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",check2:(t==null?void 0:t.pinNotice_check2)??"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",nextButton:(t==null?void 0:t.pinNotice_nextButton)??"Next",submitButton:(t==null?void 0:t.pinNotice_submitButton)??"I Understand"},i={title:(t==null?void 0:t.pinSetup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pinSetup_headerSubtitle)??"This PIN is used to authorize your transactions.",subtitle:(t==null?void 0:t.pinSetup_subtitle)??"Set a 6-digit PIN to authorize transactions.",mismatchError:(t==null?void 0:t.pinSetup_mismatchError)??"PINs do not match. Please try again."},o={title:(t==null?void 0:t.pinSetup_confirmTitle)??"Confirm PIN",headerSubtitle:(t==null?void 0:t.pinSetup_confirmSubtitle)??"Enter your PIN again to confirm."},a=Ns(this.tokens,Lo(n)),c=xt();_e(a);let l=!1;const d=()=>{l||(l=!0,a.remove(),c())},f=C=>{d(),r(C)},g=()=>{d(),r(null)},p=a.querySelector(".__crossx-card"),w={tooShort:(t==null?void 0:t.pinValidation_tooShort)??"Please enter a 6-digit PIN.",numbersOnly:(t==null?void 0:t.pinValidation_numbersOnly)??"Only numbers (0-9) are allowed.",repeatingDigit:(t==null?void 0:t.pinValidation_repeatingDigit)??"Cannot use the same number 3+ times in a row.",sequential:(t==null?void 0:t.pinValidation_sequential)??"Sequential numbers (e.g., 123456) are not allowed.",alternatingPattern:(t==null?void 0:t.pinValidation_alternatingPattern)??"Repeating patterns (e.g., 121212) are not allowed."},b=C=>{var H;p.innerHTML=Qt({title:o.title,headerSubtitle:o.headerSubtitle}),(H=p.querySelector("#__crossx-close-btn"))==null||H.addEventListener("click",g),er(p,D=>{D===C?f(C):y(i.mismatchError)},g)},y=C=>{var H;p.innerHTML=Qt({title:i.title,headerSubtitle:i.headerSubtitle,subtitle:i.subtitle,errorMessage:C}),(H=p.querySelector("#__crossx-close-btn"))==null||H.addEventListener("click",g),er(p,D=>{const q=Do(D,w);q?y(q):b(D)},g)};(()=>{var O;const C=Array.from(p.querySelectorAll(".__crossx-pw-notice-item")),H=p.querySelector("#__crossx-pin-notice-next"),D=new Set;H.removeAttribute("disabled");const q=H.dataset.nextLabel??"Next",F=H.dataset.submitLabel??"I Understand",ne=()=>{const v=D.size===C.length;H.classList.toggle("--disabled",!v),H.textContent=v?F:q},U=(v,E)=>{if(D.has(E))return;const T=v.querySelector(`#__crossx-notice-check-${E}`);D.add(E),T.classList.add("--checked"),v.setAttribute("aria-checked","true"),ne()},z=(v,E)=>{if(!D.has(E))return;const T=v.querySelector(`#__crossx-notice-check-${E}`);D.delete(E),T.classList.remove("--checked"),v.setAttribute("aria-checked","false"),ne()};C.forEach(v=>{const E=parseInt(v.dataset.checkIndex??"0",10);v.addEventListener("click",()=>{D.has(E)?z(v,E):U(v,E)}),v.addEventListener("keydown",T=>{(T.key===" "||T.key==="Enter")&&(T.preventDefault(),D.has(E)?z(v,E):U(v,E))})}),H.addEventListener("click",()=>{if(D.size===C.length){y(e==null?void 0:e.errorMessage);return}const v=C.find(T=>{const x=parseInt(T.dataset.checkIndex??"0",10);return!D.has(x)});if(!v)return;const E=parseInt(v.dataset.checkIndex??"0",10);v.scrollIntoView({behavior:"smooth",block:"nearest"}),v.classList.add("--highlight"),setTimeout(()=>{v.classList.remove("--highlight"),U(v,E)},400)}),(O=p.querySelector("#__crossx-close-btn"))==null||O.addEventListener("click",g)})(),a.addEventListener("click",C=>{C.target===a&&g()})})}showPinInputPrompt(e){return new Promise((r,t)=>{var y;pe();const n=this.messages,i=(e==null?void 0:e.verifyMode)===!0,o=i?(n==null?void 0:n.verifyPin_title)??"Verify Your PIN":(n==null?void 0:n.pinInput_title)??"Enter PIN",a=i?(n==null?void 0:n.verifyPin_subtitle)??"Enter your PIN to authorize this transaction.":(n==null?void 0:n.pinInput_subtitle)??"Enter your 6-digit PIN to continue.",c=Ns(this.tokens,Qt({title:o,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,lockExpiresAt:e==null?void 0:e.lockExpiresAt,attemptCount:e==null?void 0:e.attemptCount,maxAttempts:e==null?void 0:e.maxAttempts})),l=xt();_e(c);let d=!1;const f=()=>{d||(d=!0,c.remove(),l())},g=I=>{f(),r(I)},p=()=>{f(),r(null)},w=I=>{f(),t(I)},b=c.querySelector(".__crossx-card");(y=b.querySelector("#__crossx-close-btn"))==null||y.addEventListener("click",p),er(b,g,p,w,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt),c.addEventListener("click",I=>{I.target===c&&p()})})}showRecoveryPinInputPrompt(e){return new Promise(r=>{var a;pe();const t=Co(this.tokens,e);_e(t);const n=()=>t.remove(),i=c=>{n(),r(c)},o=()=>{n(),r(null)};Uo(t,i,o),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",o),t.addEventListener("click",c=>{c.target===t&&o()})})}showRecoveryPinLockedPrompt(e,r){return new Promise(t=>{var l;pe();const{overlay:n,startCountdown:i}=No(this.tokens,e,r);_e(n);const o=()=>{c(),n.remove()},a=()=>{o(),t()},c=i(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",d=>{d.target===n&&a()})})}showTransactionComplete(e){return new Promise(r=>{var a,c;pe();const t=wo(e,this.tokens);_e(t);const n=()=>t.remove(),i=()=>{n(),r()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",i),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",d=>{var g;d.stopPropagation();const f=l.dataset.copy;f&&((g=navigator.clipboard)==null||g.writeText(f).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&i()});const o=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",o),i())};document.addEventListener("keydown",o)})}showTransactionProgress(e,r){return new Promise(t=>{pe();const n=yo(e,this.tokens);_e(n);const i=()=>n.remove();let o=!1;const a=()=>{o||(o=!0,i(),t())},c=()=>{var d,f;(d=n.querySelector("#__crossx-done-btn"))==null||d.addEventListener("click",a),(f=n.querySelector("#__crossx-close-btn"))==null||f.addEventListener("click",a),n.addEventListener("click",g=>{g.target===n&&a()});const l=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};r.then(l=>{o||(bo(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(r=>{var c,l,d;pe();let t;e.type==="sign-message"?t=So(e,this.tokens):e.type==="sign-typed-data"?t=vo(e,this.tokens):e.type==="sign"?t=_o(e,this.tokens):t=go(e,this.tokens),_e(t);const n=()=>t.remove(),i=()=>{n(),r(!0)},o=()=>{n(),r(!1)};(c=t.querySelector("#__crossx-confirm-btn"))==null||c.addEventListener("click",i),(l=t.querySelector("#__crossx-cancel-btn"))==null||l.addEventListener("click",o),(d=t.querySelector("#__crossx-close-btn"))==null||d.addEventListener("click",o),t.querySelectorAll(".__crossx-copy-btn").forEach(f=>{f.addEventListener("click",g=>{var w;g.stopPropagation();const p=f.dataset.copy;p&&((w=navigator.clipboard)==null||w.writeText(p).catch(()=>{}))})}),t.addEventListener("click",f=>{f.target===t&&o()});const a=f=>{f.key==="Escape"&&(document.removeEventListener("keydown",a),o())};document.addEventListener("keydown",a)})}}class Ds{constructor(){this._accessToken=null,this._expiresAt=0}set(e){this._accessToken=e;try{const r=JSON.parse(atob(e.split(".")[1]));this._expiresAt=typeof r.exp=="number"?r.exp*1e3:0}catch{this._expiresAt=0}}get(){return this._accessToken&&this._expiresAt>0&&Date.now()>=this._expiresAt?(this.clear(),null):this._accessToken}clear(){this._accessToken=null,this._expiresAt=0}has(){return this.get()!==null}isExpiringSoon(e=3e4){return!this._accessToken||this._expiresAt<=0?!0:Date.now()>=this._expiresAt-e}}function Bo(s,e){s.debug;const r=We.production,t={...s,oauthServiceUrl:r.oauthServiceUrl,authApiUrl:r.authApiUrl,walletGatewayUrl:r.walletGatewayUrl},n={gatewayUrl:r.walletGatewayUrl,projectId:s.projectId},i=t.authMode!=="cookie"&&fr.isAvailable();!i&&t.authMode!=="cookie"&&u.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=i;const o=i?new fr(s.projectId):new rn,a=new Zi,c=new ro,l=new Me,d=new Ds,f=new vt;let g;s.useMockWallet?(u.log("[CROSSx] Mock Wallet Provider 사용"),g=new no(o,f)):(u.log("[CROSSx] Remote Wallet Provider 사용"),g=new $e(n,o,c,d,f));const p=new et(n,c),w=new Ho(s.theme??"light",s.themeTokens),b=e!=null&&e.wrapConfirmation?e.wrapConfirmation(w):w,y=new st(t,n,o,a,c,l,g,d,b,p,f);return typeof window<"u"&&(window.__crossxSDK=y),y}function Fo(s){const e=Ko(s),r=Go(e),t=JSON.parse(r);Jo(t);const{data:n}=t;return{status:t.status,state:t.state,firebaseToken:n.accessToken,provider:n.provider,email:n.email,providerSub:n.sub,tokenType:n.tokenType,expiresIn:n.expiresIn,raw:t}}function Ko(s){if(s.includes("://")&&s.includes("?")){const e=new URL(s),r=e.searchParams.get("crossx_oauth_result");if(r)return r;const t=e.searchParams.get("data");if(t)return t;throw new Error("Deeplink URL에 crossx_oauth_result 또는 data 파라미터가 없습니다")}return s}function Go(s){if(s.startsWith("{"))return s;if(s.startsWith("%7B")||s.startsWith("%7b"))return decodeURIComponent(s);const e=qo(s);return decodeURIComponent(e)}function qo(s){if(typeof atob=="function")return atob(s);if(typeof Buffer<"u")return Buffer.from(s,"base64").toString("utf-8");throw new Error("Base64 디코딩을 지원하는 환경이 아닙니다")}function Jo(s){if(typeof s!="object"||s===null)throw new Error("Deeplink payload가 유효한 객체가 아닙니다");const e=s;if(typeof e.status!="string")throw new Error("Deeplink payload에 status 필드가 없습니다");if(typeof e.state!="string")throw new Error("Deeplink payload에 state 필드가 없습니다");if(typeof e.data!="object"||e.data===null)throw new Error("Deeplink payload에 data 필드가 없습니다");const r=e.data;if(typeof r.provider!="string")throw new Error("Deeplink data에 provider 필드가 없습니다");if(typeof r.accessToken!="string")throw new Error("Deeplink data에 accessToken 필드가 없습니다")}return X.CROSSxError=_,X.CROSSxEthereumProvider=tr,X.CROSSxSDK=st,X.ChainId=Us,X.ErrorCode=h,X.PinMemoryStore=vt,X.TokenMemoryStore=Ds,X.createCROSSxSDK=Bo,X.parseOAuthDeeplink=Fo,Object.defineProperty(X,Symbol.toStringTag,{value:"Module"}),X}({});
|
|
2279
|
+
</svg>`;function Uo(s,e,r){var i;const t=s.querySelectorAll(".__crossx-pin-input");t.forEach((o,a)=>{o.addEventListener("input",()=>{const c=o.value.replace(/\D/g,"");o.value=c?c[0]:"",c&&a<3&&t[a+1].focus();const l=Array.from(t).map(u=>u.value).join("");l.length===4&&setTimeout(()=>e(l),200)}),o.addEventListener("keydown",c=>{c.key==="Backspace"&&!o.value&&a>0&&(t[a-1].focus(),t[a-1].value=""),c.key==="Escape"&&r()}),o.addEventListener("keypress",c=>{/[0-9]/.test(c.key)||c.preventDefault()}),o.addEventListener("paste",c=>{var f;c.preventDefault();const l=(((f=c.clipboardData)==null?void 0:f.getData("text"))??"").replace(/\D/g,"").slice(0,4);if(!l)return;l.split("").forEach((g,p)=>{t[p]&&(t[p].value=g)});const u=Math.min(l.length,3);t[u].focus(),l.length===4&&setTimeout(()=>e(l),200)})});const n=s.querySelector(".__crossx-pin-inputs");n==null||n.addEventListener("click",o=>{if(!o.target.classList.contains("__crossx-pin-input")){const a=Array.from(t).find(c=>!c.value)??t[t.length-1];a==null||a.focus()}}),(i=t[0])==null||i.focus()}class Ho{constructor(e="light",r){this.theme=e,this.overrides=r,this.tokens=Os(e,r)}setTheme(e,r){this.theme=e,r!==void 0&&(this.overrides=r),this.tokens=Os(e,this.overrides)}setMessages(e){this.messages=e}getTheme(){return this.theme}showWalletSelector(e,r,t){return new Promise(n=>{var v;pe();const i=[...e],o=Ao(i,this.tokens,t),a=xt();_e(o);let c=!1;const l=()=>{c||(c=!0,o.remove(),a())},u=S=>{l(),n(S)},f=()=>{l(),n(null)};(()=>{o.querySelectorAll(".__crossx-wallet-item").forEach(S=>{S.addEventListener("click",()=>{const I=S.dataset.walletAddress??"",T=parseInt(S.dataset.walletIndex??"0",10);u({address:I,index:T})})})})();const p=o.querySelector("#__crossx-add-wallet-btn");p&&p.addEventListener("click",async()=>{p.disabled=!0;try{const S=await r();i.push(S);const I=o.querySelector("#__crossx-wallet-list");if(I){const T=document.createElement("button");T.className="__crossx-wallet-item",T.dataset.walletIndex=String(S.index),T.dataset.walletAddress=S.address,T.innerHTML=`<span class="__crossx-wallet-idx">${S.index+1}</span><span class="__crossx-wallet-addr">${re(S.address)}</span>`,T.addEventListener("click",()=>u(S)),I.appendChild(T),T.scrollIntoView({behavior:"smooth",block:"nearest"})}}catch{}finally{p.disabled=!1}}),(v=o.querySelector("#__crossx-close-btn"))==null||v.addEventListener("click",f),o.addEventListener("click",S=>{S.target===o&&f()});const y=S=>{S.key==="Escape"&&(document.removeEventListener("keydown",y),f())};document.addEventListener("keydown",y)})}showLoginSelector(e){return new Promise(r=>{var c,l,u,f;pe();const t=Ro(this.tokens,e==null?void 0:e.showConnectOtherWallets);_e(t);const n=()=>t.remove(),i=g=>{n(),r(g)},o=()=>{n(),r(null)};(c=t.querySelector("#__crossx-apple-btn"))==null||c.addEventListener("click",()=>i("apple")),(l=t.querySelector("#__crossx-google-btn"))==null||l.addEventListener("click",()=>i("google")),(u=t.querySelector("#__crossx-connect-btn"))==null||u.addEventListener("click",()=>i("external")),(f=t.querySelector("#__crossx-close-btn"))==null||f.addEventListener("click",o),t.addEventListener("click",g=>{g.target===t&&o()}),t.querySelectorAll(".__crossx-login-terms-link").forEach(g=>{g.addEventListener("click",p=>p.stopPropagation())});const a=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",a),o())};document.addEventListener("keydown",a)})}showSessionAlert(e){return new Promise(r=>{var u,f,g;pe();const t=this.messages,n=Oo(this.tokens,{title:e.title,message:e.message,email:e.email,accountLabel:(t==null?void 0:t.sessionAlert_accountLabel)??"Account",signOutLabel:(t==null?void 0:t.sessionAlert_signOutButton)??"Sign out",signInAgainLabel:(t==null?void 0:t.sessionAlert_signInAgainButton)??"Sign in again"}),i=xt();_e(n);let o=!1;const a=()=>{o||(o=!0,n.remove(),i())},c=()=>{a(),r("signout")},l=()=>{a(),r("signin-again")};(u=n.querySelector("#__crossx-session-signout"))==null||u.addEventListener("click",c),(f=n.querySelector("#__crossx-session-signin"))==null||f.addEventListener("click",l),(g=n.querySelector("#__crossx-close-btn"))==null||g.addEventListener("click",c)})}showMigrationFoundPrompt(e){const r=(e==null?void 0:e.allowSkip)??!0;return new Promise(t=>{var a,c,l;pe();const n=Po(this.tokens,r);_e(n);const i=()=>n.remove(),o=()=>{i(),t("recover")};if((a=n.querySelector("#__crossx-recover-btn"))==null||a.addEventListener("click",o),r){const u=()=>{i(),t("skip")};(c=n.querySelector("#__crossx-skip-btn"))==null||c.addEventListener("click",u),(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",u),n.addEventListener("click",g=>{g.target===n&&u()});const f=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",f),u())};document.addEventListener("keydown",f)}})}showPinSetupPrompt(e){return new Promise(r=>{pe();const t=this.messages,n={title:(t==null?void 0:t.pinSetup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pinNotice_headerSubtitle)??"Required for transactions, PK/mnemonic export & account deletion.",noticeTitle:(t==null?void 0:t.pinNotice_title)??"PIN Setup Notice",noticeDesc:(t==null?void 0:t.pinNotice_description)??"For your security, this PIN cannot be reset or recovered. Please make sure you remember it or store it in a safe place.",check1:(t==null?void 0:t.pinNotice_check1)??"I understand that losing this PIN will result in permanent loss of access to my wallet and assets.",check2:(t==null?void 0:t.pinNotice_check2)??"I understand that no one, including the support team, can recover or reset this PIN on my behalf.",nextButton:(t==null?void 0:t.pinNotice_nextButton)??"Next",submitButton:(t==null?void 0:t.pinNotice_submitButton)??"I Understand"},i={title:(t==null?void 0:t.pinSetup_title)??"Create PIN",headerSubtitle:(t==null?void 0:t.pinSetup_headerSubtitle)??"This PIN is used to authorize your transactions.",subtitle:(t==null?void 0:t.pinSetup_subtitle)??"Set a 6-digit PIN to authorize transactions.",mismatchError:(t==null?void 0:t.pinSetup_mismatchError)??"PINs do not match. Please try again."},o={title:(t==null?void 0:t.pinSetup_confirmTitle)??"Confirm PIN",headerSubtitle:(t==null?void 0:t.pinSetup_confirmSubtitle)??"Enter your PIN again to confirm."},a=Ns(this.tokens,Lo(n)),c=xt();_e(a);let l=!1;const u=()=>{l||(l=!0,a.remove(),c())},f=T=>{u(),r(T)},g=()=>{u(),r(null)},p=a.querySelector(".__crossx-card"),y={tooShort:(t==null?void 0:t.pinValidation_tooShort)??"Please enter a 6-digit PIN.",numbersOnly:(t==null?void 0:t.pinValidation_numbersOnly)??"Only numbers (0-9) are allowed.",repeatingDigit:(t==null?void 0:t.pinValidation_repeatingDigit)??"Cannot use the same number 3+ times in a row.",sequential:(t==null?void 0:t.pinValidation_sequential)??"Sequential numbers (e.g., 123456) are not allowed.",alternatingPattern:(t==null?void 0:t.pinValidation_alternatingPattern)??"Repeating patterns (e.g., 121212) are not allowed."},v=T=>{var H;p.innerHTML=Qt({title:o.title,headerSubtitle:o.headerSubtitle}),(H=p.querySelector("#__crossx-close-btn"))==null||H.addEventListener("click",g),er(p,L=>{L===T?f(T):S(i.mismatchError)},g)},S=T=>{var H;p.innerHTML=Qt({title:i.title,headerSubtitle:i.headerSubtitle,subtitle:i.subtitle,errorMessage:T}),(H=p.querySelector("#__crossx-close-btn"))==null||H.addEventListener("click",g),er(p,L=>{const V=Do(L,y);V?S(V):v(L)},g)};(()=>{var Z;const T=Array.from(p.querySelectorAll(".__crossx-pw-notice-item")),H=p.querySelector("#__crossx-pin-notice-next"),L=new Set;H.removeAttribute("disabled");const V=H.dataset.nextLabel??"Next",B=H.dataset.submitLabel??"I Understand",ce=()=>{const $=L.size===T.length;H.classList.toggle("--disabled",!$),H.textContent=$?B:V},U=($,C)=>{if(L.has(C))return;const D=$.querySelector(`#__crossx-notice-check-${C}`);L.add(C),D.classList.add("--checked"),$.setAttribute("aria-checked","true"),ce()},z=($,C)=>{if(!L.has(C))return;const D=$.querySelector(`#__crossx-notice-check-${C}`);L.delete(C),D.classList.remove("--checked"),$.setAttribute("aria-checked","false"),ce()};T.forEach($=>{const C=parseInt($.dataset.checkIndex??"0",10);$.addEventListener("click",()=>{L.has(C)?z($,C):U($,C)}),$.addEventListener("keydown",D=>{(D.key===" "||D.key==="Enter")&&(D.preventDefault(),L.has(C)?z($,C):U($,C))})}),H.addEventListener("click",()=>{if(L.size===T.length){S(e==null?void 0:e.errorMessage);return}const $=T.find(D=>{const w=parseInt(D.dataset.checkIndex??"0",10);return!L.has(w)});if(!$)return;const C=parseInt($.dataset.checkIndex??"0",10);$.scrollIntoView({behavior:"smooth",block:"nearest"}),$.classList.add("--highlight"),setTimeout(()=>{$.classList.remove("--highlight"),U($,C)},400)}),(Z=p.querySelector("#__crossx-close-btn"))==null||Z.addEventListener("click",g)})(),a.addEventListener("click",T=>{T.target===a&&g()})})}showPinInputPrompt(e){return new Promise((r,t)=>{var I;pe();const n=this.messages,i=(e==null?void 0:e.verifyMode)===!0,o=i?(n==null?void 0:n.verifyPin_title)??"Verify Your PIN":(n==null?void 0:n.pinInput_title)??"Enter PIN",a=i?(n==null?void 0:n.verifyPin_subtitle)??"Enter your PIN to authorize this transaction.":(n==null?void 0:n.pinInput_subtitle)??"Enter your 6-digit PIN to continue.",c=(n==null?void 0:n.pinLocked_failureWarning)??"Your account will be locked after further failures.",l=Ns(this.tokens,Qt({title:o,headerSubtitle:a,errorMessage:e==null?void 0:e.errorMessage,warningMessage:c,lockExpiresAt:e==null?void 0:e.lockExpiresAt,attemptCount:e==null?void 0:e.attemptCount,maxAttempts:e==null?void 0:e.maxAttempts})),u=xt();_e(l);let f=!1;const g=()=>{f||(f=!0,l.remove(),u())},p=T=>{g(),r(T)},y=()=>{g(),r(null)},v=T=>{g(),t(T)},S=l.querySelector(".__crossx-card");(I=S.querySelector("#__crossx-close-btn"))==null||I.addEventListener("click",y),er(S,p,y,v,e==null?void 0:e.onSubmit,e==null?void 0:e.lockExpiresAt,c),l.addEventListener("click",T=>{T.target===l&&y()})})}showRecoveryPinInputPrompt(e){return new Promise(r=>{var a;pe();const t=Co(this.tokens,e);_e(t);const n=()=>t.remove(),i=c=>{n(),r(c)},o=()=>{n(),r(null)};Uo(t,i,o),(a=t.querySelector("#__crossx-close-btn"))==null||a.addEventListener("click",o),t.addEventListener("click",c=>{c.target===t&&o()})})}showRecoveryPinLockedPrompt(e,r){return new Promise(t=>{var l;pe();const{overlay:n,startCountdown:i}=No(this.tokens,e,r);_e(n);const o=()=>{c(),n.remove()},a=()=>{o(),t()},c=i(a);(l=n.querySelector("#__crossx-close-btn"))==null||l.addEventListener("click",a),n.addEventListener("click",u=>{u.target===n&&a()})})}showTransactionComplete(e){return new Promise(r=>{var a,c;pe();const t=wo(e,this.tokens);_e(t);const n=()=>t.remove(),i=()=>{n(),r()};(a=t.querySelector("#__crossx-done-btn"))==null||a.addEventListener("click",i),(c=t.querySelector("#__crossx-close-btn"))==null||c.addEventListener("click",i),t.querySelectorAll(".__crossx-copy-btn").forEach(l=>{l.addEventListener("click",u=>{var g;u.stopPropagation();const f=l.dataset.copy;f&&((g=navigator.clipboard)==null||g.writeText(f).catch(()=>{}))})}),t.addEventListener("click",l=>{l.target===t&&i()});const o=l=>{l.key==="Escape"&&(document.removeEventListener("keydown",o),i())};document.addEventListener("keydown",o)})}showTransactionProgress(e,r){return new Promise(t=>{pe();const n=yo(e,this.tokens);_e(n);const i=()=>n.remove();let o=!1;const a=()=>{o||(o=!0,i(),t())},c=()=>{var u,f;(u=n.querySelector("#__crossx-done-btn"))==null||u.addEventListener("click",a),(f=n.querySelector("#__crossx-close-btn"))==null||f.addEventListener("click",a),n.addEventListener("click",g=>{g.target===n&&a()});const l=g=>{g.key==="Escape"&&(document.removeEventListener("keydown",l),a())};document.addEventListener("keydown",l)};r.then(l=>{o||(bo(n,l,this.tokens),c())})})}requestConfirmation(e){return new Promise(r=>{var c,l,u;pe();let t;e.type==="sign-message"?t=So(e,this.tokens):e.type==="sign-typed-data"?t=vo(e,this.tokens):e.type==="sign"?t=_o(e,this.tokens):t=go(e,this.tokens),_e(t);const n=()=>t.remove(),i=()=>{n(),r(!0)},o=()=>{n(),r(!1)};(c=t.querySelector("#__crossx-confirm-btn"))==null||c.addEventListener("click",i),(l=t.querySelector("#__crossx-cancel-btn"))==null||l.addEventListener("click",o),(u=t.querySelector("#__crossx-close-btn"))==null||u.addEventListener("click",o),t.querySelectorAll(".__crossx-copy-btn").forEach(f=>{f.addEventListener("click",g=>{var y;g.stopPropagation();const p=f.dataset.copy;p&&((y=navigator.clipboard)==null||y.writeText(p).catch(()=>{}))})}),t.addEventListener("click",f=>{f.target===t&&o()});const a=f=>{f.key==="Escape"&&(document.removeEventListener("keydown",a),o())};document.addEventListener("keydown",a)})}}class Ds{constructor(){this._accessToken=null,this._expiresAt=0}set(e){this._accessToken=e;try{const r=JSON.parse(atob(e.split(".")[1]));this._expiresAt=typeof r.exp=="number"?r.exp*1e3:0}catch{this._expiresAt=0}}get(){return this._accessToken&&this._expiresAt>0&&Date.now()>=this._expiresAt?(this.clear(),null):this._accessToken}clear(){this._accessToken=null,this._expiresAt=0}has(){return this.get()!==null}isExpiringSoon(e=3e4){return!this._accessToken||this._expiresAt<=0?!0:Date.now()>=this._expiresAt-e}}function Bo(s,e){s.debug;const r=We.production,t={...s,oauthServiceUrl:r.oauthServiceUrl,authApiUrl:r.authApiUrl,walletGatewayUrl:r.walletGatewayUrl},n={gatewayUrl:r.walletGatewayUrl,projectId:s.projectId},i=t.authMode!=="cookie"&&fr.isAvailable();!i&&t.authMode!=="cookie"&&d.warn("[CROSSx] IndexedDB 사용 불가 — LocalStorage fallback 사용 중.","refresh_token이 평문 저장되지 않도록 세션 영속성이 제한됩니다.","IndexedDB를 지원하는 브라우저 사용을 권장합니다."),t.secureStorageAvailable=i;const o=i?new fr(s.projectId):new rn,a=new Zi,c=new ro,l=new Me,u=new Ds,f=new vt;let g;s.useMockWallet?(d.log("[CROSSx] Mock Wallet Provider 사용"),g=new no(o,f)):(d.log("[CROSSx] Remote Wallet Provider 사용"),g=new $e(n,o,c,u,f));const p=new et(n,c),y=new Ho(s.theme??"light",s.themeTokens),v=e!=null&&e.wrapConfirmation?e.wrapConfirmation(y):y,S=new st(t,n,o,a,c,l,g,u,v,p,f);return typeof window<"u"&&(window.__crossxSDK=S),S}function Fo(s){const e=Ko(s),r=Go(e),t=JSON.parse(r);Jo(t);const{data:n}=t;return{status:t.status,state:t.state,firebaseToken:n.accessToken,provider:n.provider,email:n.email,providerSub:n.sub,tokenType:n.tokenType,expiresIn:n.expiresIn,raw:t}}function Ko(s){if(s.includes("://")&&s.includes("?")){const e=new URL(s),r=e.searchParams.get("crossx_oauth_result");if(r)return r;const t=e.searchParams.get("data");if(t)return t;throw new Error("Deeplink URL에 crossx_oauth_result 또는 data 파라미터가 없습니다")}return s}function Go(s){if(s.startsWith("{"))return s;if(s.startsWith("%7B")||s.startsWith("%7b"))return decodeURIComponent(s);const e=qo(s);return decodeURIComponent(e)}function qo(s){if(typeof atob=="function")return atob(s);if(typeof Buffer<"u")return Buffer.from(s,"base64").toString("utf-8");throw new Error("Base64 디코딩을 지원하는 환경이 아닙니다")}function Jo(s){if(typeof s!="object"||s===null)throw new Error("Deeplink payload가 유효한 객체가 아닙니다");const e=s;if(typeof e.status!="string")throw new Error("Deeplink payload에 status 필드가 없습니다");if(typeof e.state!="string")throw new Error("Deeplink payload에 state 필드가 없습니다");if(typeof e.data!="object"||e.data===null)throw new Error("Deeplink payload에 data 필드가 없습니다");const r=e.data;if(typeof r.provider!="string")throw new Error("Deeplink data에 provider 필드가 없습니다");if(typeof r.accessToken!="string")throw new Error("Deeplink data에 accessToken 필드가 없습니다")}return j.CROSSxError=x,j.CROSSxEthereumProvider=tr,j.CROSSxSDK=st,j.ChainId=Us,j.ErrorCode=h,j.PinMemoryStore=vt,j.TokenMemoryStore=Ds,j.createCROSSxSDK=Bo,j.parseOAuthDeeplink=Fo,Object.defineProperty(j,Symbol.toStringTag,{value:"Module"}),j}({});
|