@clerk/clerk-js 6.0.0-canary.v20251217202303 → 6.0.0-canary.v20251217205250
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/clerk.browser.js +4 -4
- package/dist/clerk.chips.browser.js +7 -7
- package/dist/clerk.headless.browser.js +7 -7
- package/dist/clerk.headless.js +3 -3
- package/dist/clerk.js +1 -1
- package/dist/clerk.legacy.browser.js +1 -1
- package/dist/clerk.mjs +1 -1
- package/dist/clerk.no-rhc.js +1 -1
- package/dist/clerk.no-rhc.mjs +1 -1
- package/package.json +3 -3
- /package/dist/{197_clerk.browser_6040f9_6.0.0-canary.v20251217202303.js → 197_clerk.browser_318cfe_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{197_clerk.chips.browser_4e7092_6.0.0-canary.v20251217202303.js → 197_clerk.chips.browser_1c0bae_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{197_clerk.headless.browser_726c7c_6.0.0-canary.v20251217202303.js → 197_clerk.headless.browser_98ab2d_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{197_clerk.headless_427ec2_6.0.0-canary.v20251217202303.js → 197_clerk.headless_c2d948_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{197_clerk.legacy.browser_44ca91_6.0.0-canary.v20251217202303.js → 197_clerk.legacy.browser_2f8521_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{308_clerk.headless_427ec2_6.0.0-canary.v20251217202303.js → 308_clerk.headless_c2d948_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{507_clerk.browser_6040f9_6.0.0-canary.v20251217202303.js → 507_clerk.browser_318cfe_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{507_clerk.chips.browser_4e7092_6.0.0-canary.v20251217202303.js → 507_clerk.chips.browser_1c0bae_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{507_clerk.headless.browser_726c7c_6.0.0-canary.v20251217202303.js → 507_clerk.headless.browser_98ab2d_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{507_clerk.headless_427ec2_6.0.0-canary.v20251217202303.js → 507_clerk.headless_c2d948_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{507_clerk.legacy.browser_44ca91_6.0.0-canary.v20251217202303.js → 507_clerk.legacy.browser_2f8521_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{521_clerk.headless_427ec2_6.0.0-canary.v20251217202303.js → 521_clerk.headless_c2d948_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{527_clerk.browser_6040f9_6.0.0-canary.v20251217202303.js → 527_clerk.browser_318cfe_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{527_clerk.chips.browser_4e7092_6.0.0-canary.v20251217202303.js → 527_clerk.chips.browser_1c0bae_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{527_clerk.headless.browser_726c7c_6.0.0-canary.v20251217202303.js → 527_clerk.headless.browser_98ab2d_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{527_clerk.legacy.browser_44ca91_6.0.0-canary.v20251217202303.js → 527_clerk.legacy.browser_2f8521_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{537_clerk.headless_427ec2_6.0.0-canary.v20251217202303.js → 537_clerk.headless_c2d948_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{604_clerk.headless_427ec2_6.0.0-canary.v20251217202303.js → 604_clerk.headless_c2d948_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{783_clerk.headless_427ec2_6.0.0-canary.v20251217202303.js → 783_clerk.headless_c2d948_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{896_clerk.headless_427ec2_6.0.0-canary.v20251217202303.js → 896_clerk.headless_c2d948_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{973_clerk.headless_427ec2_6.0.0-canary.v20251217202303.js → 973_clerk.headless_c2d948_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{base-account-sdk_clerk.browser_6040f9_6.0.0-canary.v20251217202303.js → base-account-sdk_clerk.browser_318cfe_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{base-account-sdk_clerk.chips.browser_4e7092_6.0.0-canary.v20251217202303.js → base-account-sdk_clerk.chips.browser_1c0bae_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{base-account-sdk_clerk.headless.browser_726c7c_6.0.0-canary.v20251217202303.js → base-account-sdk_clerk.headless.browser_98ab2d_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{base-account-sdk_clerk.legacy.browser_44ca91_6.0.0-canary.v20251217202303.js → base-account-sdk_clerk.legacy.browser_2f8521_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.browser_6040f9_6.0.0-canary.v20251217202303.js → coinbase-wallet-sdk_clerk.browser_318cfe_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.chips.browser_4e7092_6.0.0-canary.v20251217202303.js → coinbase-wallet-sdk_clerk.chips.browser_1c0bae_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.headless.browser_726c7c_6.0.0-canary.v20251217202303.js → coinbase-wallet-sdk_clerk.headless.browser_98ab2d_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.legacy.browser_44ca91_6.0.0-canary.v20251217202303.js → coinbase-wallet-sdk_clerk.legacy.browser_2f8521_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{cookieSuffix_clerk.browser_6040f9_6.0.0-canary.v20251217202303.js → cookieSuffix_clerk.browser_318cfe_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{cookieSuffix_clerk.chips.browser_4e7092_6.0.0-canary.v20251217202303.js → cookieSuffix_clerk.chips.browser_1c0bae_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{cookieSuffix_clerk.headless.browser_726c7c_6.0.0-canary.v20251217202303.js → cookieSuffix_clerk.headless.browser_98ab2d_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{cookieSuffix_clerk.headless_427ec2_6.0.0-canary.v20251217202303.js → cookieSuffix_clerk.headless_c2d948_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{cookieSuffix_clerk.legacy.browser_44ca91_6.0.0-canary.v20251217202303.js → cookieSuffix_clerk.legacy.browser_2f8521_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{query-core-vendors_clerk.browser_6040f9_6.0.0-canary.v20251217202303.js → query-core-vendors_clerk.browser_318cfe_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{query-core-vendors_clerk.chips.browser_4e7092_6.0.0-canary.v20251217202303.js → query-core-vendors_clerk.chips.browser_1c0bae_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{query-core-vendors_clerk.headless.browser_726c7c_6.0.0-canary.v20251217202303.js → query-core-vendors_clerk.headless.browser_98ab2d_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{query-core-vendors_clerk.legacy.browser_44ca91_6.0.0-canary.v20251217202303.js → query-core-vendors_clerk.legacy.browser_2f8521_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{stripe-vendors_clerk.browser_6040f9_6.0.0-canary.v20251217202303.js → stripe-vendors_clerk.browser_318cfe_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{stripe-vendors_clerk.chips.browser_4e7092_6.0.0-canary.v20251217202303.js → stripe-vendors_clerk.chips.browser_1c0bae_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{stripe-vendors_clerk.headless.browser_726c7c_6.0.0-canary.v20251217202303.js → stripe-vendors_clerk.headless.browser_98ab2d_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{stripe-vendors_clerk.legacy.browser_44ca91_6.0.0-canary.v20251217202303.js → stripe-vendors_clerk.legacy.browser_2f8521_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{vendors_clerk.browser_6040f9_6.0.0-canary.v20251217202303.js → vendors_clerk.browser_318cfe_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{vendors_clerk.chips.browser_4e7092_6.0.0-canary.v20251217202303.js → vendors_clerk.chips.browser_1c0bae_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{vendors_clerk.headless.browser_726c7c_6.0.0-canary.v20251217202303.js → vendors_clerk.headless.browser_98ab2d_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{vendors_clerk.legacy.browser_44ca91_6.0.0-canary.v20251217202303.js → vendors_clerk.legacy.browser_2f8521_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.browser_6040f9_6.0.0-canary.v20251217202303.js → zxcvbn-common_clerk.browser_318cfe_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.chips.browser_4e7092_6.0.0-canary.v20251217202303.js → zxcvbn-common_clerk.chips.browser_1c0bae_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.headless.browser_726c7c_6.0.0-canary.v20251217202303.js → zxcvbn-common_clerk.headless.browser_98ab2d_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.legacy.browser_44ca91_6.0.0-canary.v20251217202303.js → zxcvbn-common_clerk.legacy.browser_2f8521_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.browser_6040f9_6.0.0-canary.v20251217202303.js → zxcvbn-ts-core_clerk.browser_318cfe_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.chips.browser_4e7092_6.0.0-canary.v20251217202303.js → zxcvbn-ts-core_clerk.chips.browser_1c0bae_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.headless.browser_726c7c_6.0.0-canary.v20251217202303.js → zxcvbn-ts-core_clerk.headless.browser_98ab2d_6.0.0-canary.v20251217205250.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.legacy.browser_44ca91_6.0.0-canary.v20251217202303.js → zxcvbn-ts-core_clerk.legacy.browser_2f8521_6.0.0-canary.v20251217205250.js} +0 -0
package/dist/clerk.mjs
CHANGED
|
@@ -59,4 +59,4 @@ ${t.message}`)}})(eA(e)):e).some(e=>e.test(eA(r.origin))));return i||X(`Clerk: R
|
|
|
59
59
|
${e.trim()}
|
|
60
60
|
(This notice only appears in development)`,eW={cannotRenderComponentWhenSessionExists:"The <SignUp/> and <SignIn/> components cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the Home URL instead.",cannotRenderSignUpComponentWhenSessionExists:"The <SignUp/> component cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the value set in `afterSignUp` URL instead.",cannotRenderSignUpComponentWhenTaskExists:"The <SignUp/> component cannot render when a user has a pending task, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the task instead.",cannotRenderComponentWhenTaskDoesNotExist:"<TaskChooseOrganization/> cannot render unless a session task is pending. Clerk is redirecting to the value set in `redirectUrlComplete` instead.",cannotRenderSignInComponentWhenSessionExists:"The <SignIn/> component cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the `afterSignIn` URL instead.",cannotRenderSignInComponentWhenTaskExists:"The <SignIn/> component cannot render when a user has a pending task, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the task instead.",cannotRenderComponentWhenUserDoesNotExist:"<UserProfile/> cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotRenderComponentWhenOrgDoesNotExist:"<OrganizationProfile/> cannot render unless an organization is active. Since no organization is currently active, this is no-op.",cannotRenderAnyOrganizationComponent:e=>eL(`The <${e}/> cannot be rendered when the feature is turned off. Visit 'dashboard.clerk.com' to enable the feature. Since the feature is turned off, this is no-op.`),cannotRenderAnyBillingComponent:e=>eL(`The <${e}/> component cannot be rendered when billing is disabled. Visit 'https://dashboard.clerk.com/last-active?path=billing/settings' to follow the necessary steps to enable billing. Since billing is disabled, this is no-op.`),cannotOpenUserProfile:"The UserProfile modal cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotOpenCheckout:"The Checkout drawer cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotOpenSignInOrSignUp:"The SignIn or SignUp modals do not render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, this is no-op.",cannotRenderAPIKeysComponent:"The <APIKeys/> component cannot be rendered when API keys is disabled. Since API keys is disabled, this is no-op.",cannotRenderAPIKeysComponentForOrgWhenUnauthorized:"The <APIKeys/> component cannot be rendered for an organization unless a user has the required permissions. Since the user does not have the necessary permissions, this is no-op.",cannotRenderAPIKeysComponentForUserWhenDisabled:"The <APIKeys/> component cannot be rendered when user API keys are disabled. Since user API keys are disabled, this is no-op.",cannotRenderAPIKeysComponentForOrgWhenDisabled:"The <APIKeys/> component cannot be rendered when organization API keys are disabled. Since organization API keys are disabled, this is no-op."};for(let e of Object.keys(eW)){let t=eW[e];"function"!=typeof t&&(eW[e]=eL(t))}let eK="clerk:beforeunload",eH=["http:","https:","wails:","chrome-extension:"];function eV(e){let t=new URL(e,window.location.href);window.dispatchEvent(new CustomEvent(eK)),window.location.href=t.href}function eG(e){return/^http(s)?:\/\//.test(e||"")}function eJ(e){return e.startsWith("/")}var eZ=class{#c;#U=864e5;constructor(e){this.#c=e}isEventThrottled(e){let t=Date.now(),a=this.#M(e),r=this.#c.getItem(a);return!!r&&!(t-r>this.#U)||(this.#c.setItem(a,t),!1)}#M(e){let{sk:t,pk:a,payload:r,...n}=e,i={...r,...n};return JSON.stringify(Object.keys({...r,...n}).sort().map(e=>i[e]))}},e$=class{#R="clerk_telemetry_throttler";getItem(e){return this.#B()[e]}setItem(e,t){try{let a=this.#B();a[e]=t,localStorage.setItem(this.#R,JSON.stringify(a))}catch(e){e instanceof DOMException&&("QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name)&&localStorage.length>0&&localStorage.removeItem(this.#R)}}removeItem(e){try{let t=this.#B();delete t[e],localStorage.setItem(this.#R,JSON.stringify(t))}catch{}}#B(){try{let e=localStorage.getItem(this.#R);if(!e)return{};return JSON.parse(e)}catch{return{}}}static isSupported(){return"undefined"!=typeof window&&!!window.localStorage}},eY=class{#c=new Map;#N=1e4;getItem(e){return this.#c.size>this.#N?void this.#c.clear():this.#c.get(e)}setItem(e,t){this.#c.set(e,t)}removeItem(e){this.#c.delete(e)}};let eQ=new Set(["error","warn","info","debug","trace"]);var eX=class{#D;#F;#L={};#W=[];#K=null;constructor(e){this.#D={maxBufferSize:e.maxBufferSize??5,samplingRate:e.samplingRate??1,perEventSampling:e.perEventSampling??!0,disabled:e.disabled??!1,debug:e.debug??!1,endpoint:"https://clerk-telemetry.com"},e.clerkVersion||"undefined"!=typeof window?this.#L.clerkVersion=e.clerkVersion??"":this.#L.clerkVersion="",this.#L.sdk=e.sdk,this.#L.sdkVersion=e.sdkVersion,this.#L.publishableKey=e.publishableKey??"";let t=ef(e.publishableKey);t&&(this.#L.instanceType=t.instanceType),e.secretKey&&(this.#L.secretKey=e.secretKey.substring(0,16)),this.#F=new eZ(e$.isSupported()?new e$:new eY)}get isEnabled(){return!("development"!==this.#L.instanceType||this.#D.disabled||"undefined"!=typeof process&&process.env&&eo(process.env.CLERK_TELEMETRY_DISABLED)||"undefined"!=typeof window&&window?.navigator?.webdriver)}get isDebug(){return this.#D.debug||"undefined"!=typeof process&&process.env&&eo(process.env.CLERK_TELEMETRY_DEBUG)}record(e){try{let t=this.#H(e.event,e.payload);if(this.#V(t.event,t),!this.#G(t,e.eventSamplingRate))return;this.#W.push({kind:"event",value:t}),this.#J()}catch(e){console.error("[clerk/telemetry] Error recording telemetry event",e)}}recordLog(e){try{if(!this.#Z(e))return;let t="string"==typeof e?.level&&eQ.has(e.level),a="string"==typeof e?.message&&e.message.trim().length>0,r=null,n=e?.timestamp;if("number"==typeof n||"string"==typeof n){let e=new Date(n);Number.isNaN(e.getTime())||(r=e)}if(!t||!a||null===r){this.isDebug&&"undefined"!=typeof console&&console.warn("[clerk/telemetry] Dropping invalid telemetry log entry",{levelIsValid:t,messageIsValid:a,timestampIsValid:null!==r});return}let i=this.#$(),s={sdk:i.name,sdkv:i.version,cv:this.#L.clerkVersion??"",lvl:e.level,msg:e.message,ts:r.toISOString(),pk:this.#L.publishableKey||null,payload:this.#Y(e.context)};this.#W.push({kind:"log",value:s}),this.#J()}catch(e){console.error("[clerk/telemetry] Error recording telemetry log entry",e)}}#G(e,t){return this.isEnabled&&!this.isDebug&&this.#Q(e,t)}#Z(e){return!0}#Q(e,t){let a=Math.random();return!!(a<=this.#D.samplingRate&&(!1===this.#D.perEventSampling||void 0===t||a<=t))&&!this.#F.isEventThrottled(e)}#J(){if("undefined"==typeof window)return void this.#X();if(this.#W.length>=this.#D.maxBufferSize){this.#K&&("undefined"!=typeof cancelIdleCallback?cancelIdleCallback(Number(this.#K)):clearTimeout(Number(this.#K))),this.#X();return}this.#K||("requestIdleCallback"in window?this.#K=requestIdleCallback(()=>{this.#X(),this.#K=null}):this.#K=setTimeout(()=>{this.#X(),this.#K=null},0))}#X(){let e=[...this.#W];if(this.#W=[],this.#K=null,0===e.length)return;let t=e.filter(e=>"event"===e.kind).map(e=>e.value),a=e.filter(e=>"log"===e.kind).map(e=>e.value);t.length>0&&fetch(new URL("/v1/event",this.#D.endpoint),{headers:{"Content-Type":"application/json"},keepalive:!0,method:"POST",body:JSON.stringify({events:t})}).catch(()=>void 0),a.length>0&&fetch(new URL("/v1/logs",this.#D.endpoint),{headers:{"Content-Type":"application/json"},keepalive:!0,method:"POST",body:JSON.stringify({logs:a})}).catch(()=>void 0)}#V(e,t){this.isDebug&&(void 0!==console.groupCollapsed?(console.groupCollapsed("[clerk/telemetry]",e),console.log(t),console.groupEnd()):console.log("[clerk/telemetry]",e,t))}#$(){let e={name:this.#L.sdk,version:this.#L.sdkVersion};if("undefined"!=typeof window){let t=window;if(t.Clerk){let a=t.Clerk;if("object"==typeof a&&null!==a&&"constructor"in a&&"function"==typeof a.constructor&&a.constructor.sdkMetadata){let{name:t,version:r}=a.constructor.sdkMetadata;void 0!==t&&(e.name=t),void 0!==r&&(e.version=r)}}}return e}#H(e,t){let a=this.#$();return{event:e,cv:this.#L.clerkVersion??"",it:this.#L.instanceType??"",sdk:a.name,sdkv:a.version,...this.#L.publishableKey?{pk:this.#L.publishableKey}:{},...this.#L.secretKey?{sk:this.#L.secretKey}:{},payload:t}}#Y(e){if(null==e||"object"!=typeof e)return null;try{let t=JSON.parse(JSON.stringify(e));if(t&&"object"==typeof t&&!Array.isArray(t))return t;return null}catch{return null}}};let e1="COMPONENT_MOUNTED",e0=new Set(["SignIn","SignUp"]);function e2(e){return function(t,a,r){return{event:e,eventSamplingRate:e===e1?e0.has(t)?1:.1:.1,payload:{component:t,appearanceProp:!!a?.appearance,theme:!!a?.appearance?.theme,elements:!!a?.appearance?.elements,variables:!!a?.appearance?.variables,...r}}}}function e3(e,t,a){return e2(e1)(e,t,a)}function e9(e,t,a){return e2("COMPONENT_OPENED")(e,t,a)}function e5(e){return"string"==typeof e?e:"object"==typeof e&&null!==e&&"name"in e&&"string"==typeof e.name?e.name:void 0}function e6(e,t,a){return"function"==typeof e?e(t):void 0!==e?e:void 0!==a?a:void 0}let e8=(...e)=>{},e4=!1,e7=null,te=!1,tt=[];function ta(e,t,a,r){e4&&(tt.push({level:e,message:t,context:a,source:r,ts:Date.now()}),tt.length>200&&tt.shift())}async function tr(e){try{if(!e4||e7)return;let{getDebugLogger:t}=await Promise.resolve().then(n.bind(n,9854)),a=await t({logLevel:e?.logLevel,telemetryCollector:e?.telemetryCollector});if(a&&(e7=a)&&0!==tt.length){for(let e of tt){let t={...e.context||{},__preInit:!0,__preInitTs:e.ts};switch(e.level){case"error":e7.error(e.message,t,e.source);break;case"warn":e7.warn(e.message,t,e.source);break;case"info":e7.info(e.message,t,e.source);break;case"debug":e7.debug(e.message,t,e.source)}}tt.length=0}}catch(e){try{console.debug?.("Debug logger initialization failed",e)}catch{}return}}let tn={debug(e,t,a){e7?e7.debug(e,t,a):ta("debug",e,t,a)},error(e,t,a){e7?e7.error(e,t,a):ta("error",e,t,a)},info(e,t,a){e7?e7.info(e,t,a):ta("info",e,t,a)},warn(e,t,a){e7?e7.warn(e,t,a):ta("warn",e,t,a)}},ti={initialDelay:125,maxDelayBetweenRetries:0,factor:2,shouldRetry:(e,t)=>t<5,retryImmediately:!1,jitter:!0},ts=async e=>new Promise(t=>setTimeout(t,e)),to=(e,t)=>t?e*(1+Math.random()):e,tl=async(e,t={})=>{var a;let r,n=0,{shouldRetry:i,initialDelay:s,maxDelayBetweenRetries:o,factor:l,retryImmediately:c,jitter:u,onBeforeRetry:d}={...ti,...t},h=(a={initialDelay:s,maxDelayBetweenRetries:o,factor:l,jitter:u},r=0,async()=>{let e;await ts((e=to(e=a.initialDelay*Math.pow(a.factor,r),a.jitter),Math.min(a.maxDelayBetweenRetries||e,e))),r++});for(;;)try{return await e()}catch(e){if(!i(e,++n))throw e;d&&await d(n),c&&1===n?await ts(to(100,u)):await h()}},tc=async e=>tl(e,{initialDelay:100,shouldRetry:(e,t)=>t<=3,retryImmediately:!0,factor:2});class tu{#ee={"@zxcvbn-ts/core":()=>tc(()=>Promise.resolve().then(n.bind(n,7010))),"@zxcvbn-ts/language-common":()=>tc(()=>Promise.resolve().then(n.bind(n,655))),"@base-org/account":()=>tc(()=>Promise.resolve().then(n.bind(n,272))),"@coinbase/wallet-sdk":()=>tc(()=>Promise.resolve().then(n.bind(n,2804))),"@stripe/stripe-js":()=>tc(()=>Promise.resolve().then(n.bind(n,5608)))};import(e){return this.#ee[e]?this.#ee[e]():Promise.resolve(void 0)}}let td=(e=!1)=>{let t,a;if(!e)return{track:async e=>{await e()},isUnloading:()=>!1};let r=(t=!1,a=()=>t=!0,{startListening:()=>{window.addEventListener("beforeunload",a),window.addEventListener(eK,a)},stopListening:()=>{window.removeEventListener("beforeunload",a),window.removeEventListener(eK,a)},isUnloading:()=>t});return{track:async e=>{r.startListening(),await e(),r.stopListening()},isUnloading:r.isUnloading}},th=e=>({amount:e.amount,amountFormatted:e.amount_formatted,currency:e.currency,currencySymbol:e.currency_symbol}),tm=e=>{let t={grandTotal:th(e.grand_total),subtotal:th(e.subtotal),taxTotal:th(e.tax_total)};return"past_due"in e&&(t.pastDue=e.past_due?th(e.past_due):null),"credit"in e&&(t.credit=e.credit?th(e.credit):null),"total_due_now"in e&&(t.totalDueNow=th(e.total_due_now)),"total_due_after_free_trial"in e&&(t.totalDueAfterFreeTrial=e.total_due_after_free_trial?th(e.total_due_after_free_trial):null),t};function tp(e,t=""){return e.errors&&!!e.errors.find(e=>e.code===t)}let tf=S({packageName:"@clerk/clerk-js"});function tg(e){return decodeURIComponent(globalThis.atob(e.replace(/_/g,"/").replace(/-/g,"+")).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""))}function tb(e){let t=(e||"").split("."),[a,r,n]=t;if(3!==t.length||!a||!r||!n)throw Error("JWT could not be decoded");let i=JSON.parse(tg(r)),s={__raw:e};return Object.keys(i).forEach(e=>{s[e]=i[e]}),{encoded:{header:a,payload:r,signature:n},header:JSON.parse(tg(a)),claims:s}}function ty(){if(!o())return null;try{let e=navigator?.language;if(!e||"string"!=typeof e||""===e.trim())return null;return e}catch{return null}}function tw(){return void 0!==globalThis.document}function tk(){if(!function(){if(!tw())return!1;try{return window.self!==window.top}catch{return!0}}())return!1;try{return window.top?.location.href,!1}catch{return!0}}var tv=class e{#et=[];#ea={metamask:"MetaMask",okx_wallet:"OKX Wallet"};static #er=null;constructor(){if("undefined"==typeof window)return;window.addEventListener("eip6963:announceProvider",this.#en),window.dispatchEvent(new Event("eip6963:requestProvider"))}static getInstance(){return e.#er||(e.#er=new e),e.#er}get=e=>{let t=this.#et.find(t=>t.info.name===this.#ea[e])?.provider;return void 0!==t?t:window.ethereum};#en=e=>{this.#et.some(t=>t.info.uuid===e.detail.info.uuid)||this.#et.push(e.detail)}},tx=class e{#ei=void 0;#es=!1;static #er=null;constructor(){}async #eo(){if(this.#es)return;this.#es=!0;let e=await Promise.resolve().then(n.bind(n,4076)).then(e=>e.getWallets());this.#ei=e.get(),e.on("register",()=>{this.#ei=e.get()}),e.on("unregister",()=>{this.#ei=e.get()})}#el(e){return e.chains?.some(e=>e.startsWith("solana:"))??!1}#ec(e){return"solana:signMessage"in e.features}static getInstance(){return e.#er||(e.#er=new e),e.#er}get=async e=>{await this.#eo();let t=(this.#ei||[]).find(t=>t.name===e&&this.#el(t)&&this.#ec(t));if(t&&this.#el(t))return t;if("undefined"==typeof window)return;let a=window.solana;if(a&&"function"==typeof a.connect&&"function"==typeof a.signMessage)return a}};let tj=()=>(function(e){let t=S({packageName:"@clerk/shared"});async function a(e){let{provider:t,walletName:a}=e,r=await p(t,a);if(!r)return"";if("solana"===t){let e=await r.features["standard:connect"].connect();return e&&e.accounts[0].address||""}let n=await r.request({method:"eth_requestAccounts"});return n&&n[0]||""}let r=async e=>{let{identifier:t,nonce:a,provider:r,walletName:n=""}=e,i=await p(r,n);if(!i)return"";if("solana"===r)try{let e=i.accounts.find(e=>e.address===t);if(!e)return console.warn(`Wallet account with address ${t} not found`),"";let r=await i.features["solana:signMessage"]?.signMessage({account:e,message:new TextEncoder().encode(a)});return r?.[0]?.signature?btoa(String.fromCharCode(...r[0].signature)):""}catch(e){if(e instanceof Error&&e.message.includes("User rejected the request."))throw new C("Web3 signature request was rejected by the user.",{code:"web3_signature_request_rejected"});throw new C("An error occurred while generating the Solana signature.",{code:"web3_solana_signature_generation_failed",cause:e instanceof Error?e:void 0})}return await i.request({method:"personal_sign",params:[`0x${a.split("").map(e=>e.charCodeAt(0).toString(16).padStart(2,"0")).join("")}`,t]})};async function n(){return await a({provider:"metamask"})}async function i(){return await a({provider:"coinbase_wallet"})}async function s(){return await a({provider:"okx_wallet"})}async function o(){return await a({provider:"base"})}async function l(e){return await a({provider:"solana",walletName:e})}async function c(e){return await r({...e,provider:"metamask"})}async function u(e){return await r({...e,provider:"coinbase_wallet"})}async function d(e){return await r({...e,provider:"okx_wallet"})}async function h(e){return await r({...e,provider:"base"})}async function m(e){return await r({...e,provider:"solana"})}async function p(a,r){if("coinbase_wallet"===a){let t=await e.import("@coinbase/wallet-sdk");return t?t.createCoinbaseWalletSDK({preference:{options:"all"}}).getProvider():null}if("base"===a)try{let t=await e.import("@base-org/account");if(!t)return null;return t.createBaseAccountSDK({appName:"undefined"!=typeof window&&window.Clerk?.__internal_environment?.displayConfig?.applicationName||"undefined"!=typeof document&&document.title||"Web3 Application"}).getProvider()}catch{return null}return"solana"===a?r&&0!==r.length?await tx.getInstance().get(r):void t.throw("Wallet name must be provided to get Solana wallet provider"):tv.getInstance().get(a)}return{getWeb3Identifier:a,generateWeb3Signature:r,getMetamaskIdentifier:n,getCoinbaseWalletIdentifier:i,getOKXWalletIdentifier:s,getBaseIdentifier:o,getSolanaIdentifier:l,generateSignatureWithMetamask:c,generateSignatureWithCoinbaseWallet:u,generateSignatureWithOKXWallet:d,generateSignatureWithBase:h,generateSignatureWithSolana:m}})(new tu),t_="environment",tz=JSON.stringify,tS=JSON.parse;class tE{static _key(e){return`__clerk_${e}`}static isExpired(e){return!!e.exp&&Date.now()>e.exp}static setItem(e,t,a){try{let r={value:t,...a&&{exp:Date.now()+a}};window.localStorage.setItem(this._key(e),tz(r))}catch{}}static getItem(e,t){try{let a=window.localStorage.getItem(this._key(e));if(!a)return t;let r=tS(a);if(!r)return t;if(this.isExpired(r))return this.removeItem(e),t;return r?.value??t}catch{return t}}static removeItem(e){try{window.localStorage.removeItem(this._key(e))}catch{}}}let tA="ClerkJS:";function tI(e=""){throw Error(`${tA} Something went wrong initializing Clerk in development mode.${e&&` ${e}`}`)}function tC(e){throw Error(`${tA} Something went wrong initializing Clerk during the ${e} flow. Please contact support.`)}function tP(e){throw Error(`${tA} You need to start a ${e} flow by calling ${e}.create() first.`)}function tq(e,t){throw Error(`${tA} Strategy "${t}" is not a valid strategy for ${e}.`)}function tO(e){throw Error(`${tA} You need to start a ${e} flow by calling ${e}.create({ identifier: 'your web3 wallet address' }) first`)}function tT(e=""){throw Error(`${tA} Missing '${e}' option`)}function tU(e,t){throw Error(`${tA} Response: ${e||0} not supported yet.
|
|
61
61
|
For more information contact us at ${t}`)}function tM(e){throw Error(`${tA} Missing publicKey. When calling 'navigator.credentials.${e}()' it is required to pass a publicKey object.`)}async function tR(e="",t){let{async:a,defer:r,beforeLoad:n,crossOrigin:i,nonce:s}=t||{};return tl(()=>new Promise((t,o)=>{e||o(Error("loadScript cannot be called without a src")),document&&document.body||o(Error("loadScript cannot be called when document does not exist"));let l=document.createElement("script");i&&l.setAttribute("crossorigin",i),l.async=a||!1,l.defer=r||!1,l.addEventListener("load",()=>{l.remove(),t(l)}),l.addEventListener("error",t=>{l.remove(),o(t.error??Error(`failed to load script: ${e}`))}),l.src=e,l.nonce=s,n?.(l),document.body.appendChild(l)}),{shouldRetry:(e,t)=>t<=5})}async function tB(e){return window.turnstile||await tN(e).catch(()=>{throw{captchaError:"captcha_script_failed_to_load"}}),window.turnstile}async function tN(e){try{return await tR("https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",{defer:!0,nonce:e})}catch(e){throw console.warn("Clerk: Failed to load the CAPTCHA script from Cloudflare. If you see a CSP error in your browser, please add the necessary CSP rules to your app. Visit https://clerk.com/docs/security/clerk-csp for more information."),e}}function tD(e){try{let t=e.getAttribute("data-cl-theme")||void 0,a=e.getAttribute("data-cl-language")||void 0,r=e.getAttribute("data-cl-size")||void 0;return{theme:t,language:a,size:r}}catch{return{theme:void 0,language:void 0,size:void 0}}}let tF=async e=>{let t,a,r,n,{siteKey:i,widgetType:s,invisibleSiteKey:o,nonce:l}=e,{modalContainerQuerySelector:c,modalWrapperQuerySelector:u,closeModal:d,openModal:h}=e,m=await tB(l),p=[],f="",g="",b=i,y=0,w=null,k="invisible";if(c&&u){w=s,n=c,k="modal";try{await h?.()}catch{throw{captchaError:"modal_component_not_ready"}}let e=await new Promise(e=>{if(document.querySelector(c))return e(document.querySelector(c));let t=new MutationObserver(()=>{document.querySelector(c)&&(t.disconnect(),e(document.querySelector(c)))});t.observe(document.body,{childList:!0,subtree:!0})});if(e){let{theme:n,language:i,size:s}=tD(e);t=n,r=i,a=s}}if(!n&&"smart"===s){let e=document.getElementById(Z);if(e){k="smart",w="smart",n=`#${Z}`,e.style.maxHeight="0";let{theme:i,language:s,size:o}=tD(e);t=i,r=s,a=o}else console.error("Cannot initialize Smart CAPTCHA widget because the `clerk-captcha` DOM element was not found; falling back to Invisible CAPTCHA widget. If you are using a custom flow, visit https://clerk.com/docs/guides/development/custom-flows/authentication/bot-sign-up-protection for instructions")}if(!n){k="invisible",b=o,w="invisible",n=`.${$}`;let e=document.createElement("div");e.classList.add($),e.style.display="none",document.body.appendChild(e)}let v=async()=>new Promise((i,s)=>{try{let o=m.render(n,{sitekey:b,appearance:"interaction-only",theme:t||"auto",size:a||"normal",language:r||"auto",action:e.action,retry:"never","refresh-expired":"auto",callback:function(e){d?.(),i([e,o])},"before-interactive-callback":()=>{if(u){let e=document.querySelector(u);e?.style.setProperty("visibility","visible"),e?.style.setProperty("pointer-events","all")}else{let e=document.getElementById(Z);e&&(e.style.maxHeight="unset",e.style.minHeight="compact"===a?"140px":"68px",e.style.marginBottom="1.5rem")}},"error-callback":function(e){var t;(p.push(e),y<2&&(t=e.toString(),["crashed","undefined_error","102","103","104","106","110600","300","600"].find(e=>t.startsWith(e))))?setTimeout(()=>{m.reset(o),y++},250):s([p.join(","),o])},"unsupported-callback":function(){return s(["This browser is not supported by the CAPTCHA.",o]),!0}})}catch(e){s([e,void 0])}});try{[f,g]=await v(),m.remove(g)}catch([e,t]){throw t&&m.remove(t),{captchaError:e}}finally{if("modal"===k&&d?.(),"invisible"===k){let e=document.querySelector(`.${$}`);e&&document.body.removeChild(e)}if("smart"===k){let e=document.getElementById(Z);e&&(e.style.maxHeight="0",e.style.minHeight="unset",e.style.marginBottom="unset")}}return{captchaToken:f,captchaWidgetType:w}},tL=e=>{let t=e.__internal_environment,a=t?t.displayConfig.captchaProvider:"turnstile",r=e.__internal_getOption?.("nonce");return{captchaSiteKey:t?t.displayConfig.captchaPublicKey:null,captchaWidgetType:t?t.displayConfig.captchaWidgetType:null,captchaProvider:a,captchaPublicKeyInvisible:t?t.displayConfig.captchaPublicKeyInvisible:null,canUseCaptcha:t?t.userSettings.signUp.captcha_enabled&&e.isStandardBrowser:null,nonce:r||void 0}};class tW{clerk;constructor(e){this.clerk=e}async invisible(e){let{captchaSiteKey:t,canUseCaptcha:a,captchaPublicKeyInvisible:r,nonce:n}=tL(this.clerk);return a&&t&&r?{...await tF({action:e?.action,captchaProvider:"turnstile",invisibleSiteKey:r,nonce:e?.nonce||n||void 0,siteKey:r,widgetType:"invisible"}).catch(e=>e.captchaError?{captchaError:e.captchaError}:{captchaError:e?.message||e||"unexpected_captcha_error"}),captchaAction:e?.action}:{captchaError:"captcha_unavailable",captchaAction:e?.action}}async managedOrInvisible(e){let{captchaSiteKey:t,canUseCaptcha:a,captchaWidgetType:r,captchaProvider:n,captchaPublicKeyInvisible:i,nonce:s}=tL(this.clerk);if(a&&t&&i){let a=await tF({captchaProvider:n,invisibleSiteKey:i,nonce:s||void 0,siteKey:t,widgetType:r,...e}).catch(t=>t.captchaError?{captchaError:t.captchaError}:e?.action==="verify"?{captchaError:t?.message||t||"unexpected_captcha_error"}:void 0);return e?.action==="verify"?{...a,captchaAction:"verify"}:a}return e?.action==="verify"?{captchaError:"captcha_unavailable",captchaAction:e?.action}:{}}async managedInModal(e){return this.managedOrInvisible({modalWrapperQuerySelector:"#cl-modal-captcha-wrapper",modalContainerQuerySelector:"#cl-modal-captcha-container",openModal:()=>this.clerk.__internal_openBlankCaptchaModal(),closeModal:()=>this.clerk.__internal_closeBlankCaptchaModal(),action:e?.action})}}class tK{client;CaptchaChallengeImpl;static instance;inflightException=null;captchaRetryCount=0;MAX_RETRY_ATTEMPTS=3;static getInstance(){return tK.instance||(tK.instance=new tK(aN,tW)),tK.instance}constructor(e,t){this.client=e,this.CaptchaChallengeImpl=t}async execute(e,t){if(this.captchaAttemptsExceeded())throw new C("Security verification failed. Please try again by refreshing the page, clearing your browser cookies, or using a different web browser.",{code:"captcha_client_attempts_exceeded"});try{return this.inflightException&&await this.inflightException,await t()}catch(r){let a;if(!M(r)||R(r)&&"network_error"===r.code||r.errors[0]?.code!=="requires_captcha")throw r;if(this.inflightException)return await this.inflightException,await t();this.inflightException=new Promise(e=>a=e);try{let t=await this.managedChallenge(e);t?.captchaError!=="modal_component_not_ready"&&(await this.client.getOrCreateInstance().__internal_sendCaptchaToken(t),this.captchaRetryCount=0)}catch(e){throw this.captchaRetryCount++,e}finally{a(),this.inflightException=null}return await t()}}managedChallenge(e){return new this.CaptchaChallengeImpl(e).managedInModal({action:"verify"})}captchaAttemptsExceeded=()=>this.captchaRetryCount>=this.MAX_RETRY_ATTEMPTS}class tH{static clerk;id;pathRoot="";static get fapiClient(){return tH.clerk.getFapiClient()}async reload(e){let{rotatingTokenNonce:t}=e||{};return this._baseGet({forceUpdateClient:!0,rotatingTokenNonce:t})}isNew(){return!this.id}static async _fetch(e,t={}){return tK.getInstance().execute(this.clerk,()=>this._baseFetch(e,t))}static async _baseFetch(e,t={}){let a;tH.fapiClient||function(){throw Error(`${tA} Missing FAPI client in resources.`)}();let{fetchMaxTries:r}=t;try{a=await tH.fapiClient.request(e,{fetchMaxTries:r})}catch(t){if(this.shouldRethrowOfflineNetworkErrors())throw new C(t?.message||t,{code:"network_error"});if(!d())return tn.warn("Network request failed while offline, returning null",{method:e.method,path:e.path},"baseResource"),null;throw t}let{payload:n,status:i,statusText:s,headers:o}=a;if(o){let e=o.get("x-country");this.clerk.__internal_setCountry(e?e.toLowerCase():null)}if(("GET"!==e.method||t.forceUpdateClient)&&this._updateClient(n),i>=200&&i<=299)return n;if(i>=400){let e=n?.errors,t=e?.[0]?.long_message,a=e?.[0]?.code;401===i&&"requires_captcha"!==a&&await tH.clerk.handleUnauthenticated(),function(e,t){var a;if(!t||!t[0])return;let r=t[0],n=r.long_message;if("origin_invalid"===r.code&&((a=tH.clerk.publishableKey).startsWith("live_")||a.startsWith("pk_live_"))){let a=tH.clerk.frontendApi.replace("clerk.","");throw new j(`Clerk: Production Keys are only allowed for domain "${a}".
|
|
62
|
-
API Error: ${n}`,{data:t,status:e})}}(i,e);let r={data:e,status:i};if(429===i&&o){let e=o.get("retry-after");if(e){let t=parseInt(e,10);isNaN(t)||(r.retryAfter=t)}}throw new j(t||s,r)}return null}static _updateClient(e){if(!e)return;let t=e.client||e.meta?.client;t&&tH.clerk&&tH.clerk.updateClient(aN.getOrCreateInstance().fromJSON(t))}path(e){let t=this.pathRoot;if(this.isNew())return t;let a=t.replace(/[^/]$/,"$&/")+encodeURIComponent(this.id);return e?a.replace(/[^/]$/,"$&/")+encodeURIComponent(e):a}withDefault(e,t){return e??t}async _baseGet(e={}){let t=await tH._fetch({method:"GET",path:this.path(),rotatingTokenNonce:e.rotatingTokenNonce},e);return this.fromJSON(t?.response||t)}async _baseMutate(e){let{action:t,body:a,method:r,path:n}=e,i=await tH._fetch({method:r,path:n||this.path(t),body:a});return this.fromJSON(i?.response||i)}async _baseMutateBypass(e){let{action:t,body:a,method:r,path:n}=e,i=await tH._baseFetch({method:r,path:n||this.path(t),body:a});return this.fromJSON(i?.response||i)}async _basePost(e={}){return this._baseMutate({...e,method:"POST"})}async _basePostBypass(e={}){return this._baseMutateBypass({...e,method:"POST"})}async _basePut(e={}){return this._baseMutate({...e,method:"PUT"})}async _basePatch(e={}){return this._baseMutate({...e,method:"PATCH"})}async _baseDelete(e={}){await this._baseMutate({...e,method:"DELETE"})}static shouldRethrowOfflineNetworkErrors(){let e=tH.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}function tV(e){let t=new Date(e||new Date);return t instanceof Date&&!isNaN(t.getTime())?t:new Date}class tG extends tH{pathRoot="/api_keys";id;type;name;subject;scopes;claims;revoked;revocationReason;expired;expiration;createdBy;description;secret;lastUsedAt;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.type=e.type,this.name=e.name,this.subject=e.subject,this.scopes=e.scopes,this.claims=e.claims,this.revoked=e.revoked,this.revocationReason=e.revocation_reason,this.expired=e.expired,this.expiration=e.expiration?tV(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?tV(e.last_used_at):null,this.updatedAt=tV(e.updated_at),this.createdAt=tV(e.created_at)),this}__internal_toSnapshot(){return{object:"api_key",id:this.id,type:this.type,name:this.name,subject:this.subject,scopes:this.scopes,claims:this.claims,revoked:this.revoked,revocation_reason:this.revocationReason,expired:this.expired,expiration:this.expiration?this.expiration.getTime():null,created_by:this.createdBy,description:this.description,last_used_at:this.lastUsedAt?this.lastUsedAt.getTime():null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}class tJ extends tH{claimedAt=null;reverification=!1;singleSessionMode=!1;preferredChannels=null;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.claimedAt=this.withDefault(e.claimed_at?tV(e.claimed_at):null,this.claimedAt),this.reverification=this.withDefault(e.reverification,this.reverification),this.singleSessionMode=this.withDefault(e.single_session_mode,this.singleSessionMode),this.preferredChannels=this.withDefault(e.preferred_channels,this.preferredChannels)),this}__internal_toSnapshot(){return{claimed_at:this.claimedAt?this.claimedAt.getTime():null,id:this.id??"",object:"auth_config",reverification:this.reverification,single_session_mode:this.singleSessionMode}}}(y=k||(k={}))[y.None=0]="None",y[y.Mutable=1]="Mutable",y[y.Watching=2]="Watching",y[y.RecursedCheck=4]="RecursedCheck",y[y.Recursed=8]="Recursed",y[y.Dirty=16]="Dirty",y[y.Pending=32]="Pending";let tZ=[],{link:t$,unlink:tY,propagate:tQ,checkDirty:tX,endTracking:t1,startTracking:t0,shallowPropagate:t2}=function({update:e,notify:t,unwatched:a}){let r=0;return{link:function(e,t){let a,n=t.depsTail;if(void 0!==n&&n.dep===e)return;if(4&t.flags&&void 0!==(a=void 0!==n?n.nextDep:t.deps)&&a.dep===e){a.version=r,t.depsTail=a;return}let i=e.subsTail;if(void 0!==i&&i.version===r&&i.sub===t)return;let s=t.depsTail=e.subsTail={version:r,dep:e,sub:t,prevDep:n,nextDep:a,prevSub:i,nextSub:void 0};void 0!==a&&(a.prevDep=s),void 0!==n?n.nextDep=s:t.deps=s,void 0!==i?i.nextSub=s:e.subs=s},unlink:n,propagate:function(e){let a,r=e.nextSub;t:for(;;){let n=e.sub,i=n.flags;if(3&i&&(60&i?12&i?4&i?!(48&i)&&function(e,t){let a=t.depsTail;if(void 0!==a){let r=t.deps;do{if(r===e)return!0;if(r===a)break;r=r.nextDep}while(void 0!==r)}return!1}(e,n)?(n.flags=40|i,i&=1):i=0:n.flags=-9&i|32:i=0:n.flags=32|i,2&i&&t(n),1&i)){let t=n.subs;if(void 0!==t){e=t,void 0!==t.nextSub&&(a={value:r,prev:a},r=e.nextSub);continue}}if(void 0!==(e=r)){r=e.nextSub;continue}for(;void 0!==a;)if(e=a.value,a=a.prev,void 0!==e){r=e.nextSub;continue t}break}},checkDirty:function(t,a){let r,n=0;t:for(;;){let s=t.dep,o=s.flags,l=!1;if(16&a.flags)l=!0;else if((17&o)==17){if(e(s)){let e=s.subs;void 0!==e.nextSub&&i(e),l=!0}}else if((33&o)==33){(void 0!==t.nextSub||void 0!==t.prevSub)&&(r={value:t,prev:r}),t=s.deps,a=s,++n;continue}if(!l&&void 0!==t.nextDep){t=t.nextDep;continue}for(;n;){--n;let s=a.subs,o=void 0!==s.nextSub;if(o?(t=r.value,r=r.prev):t=s,l){if(e(a)){o&&i(s),a=t.sub;continue}}else a.flags&=-33;if(a=t.sub,void 0!==t.nextDep){t=t.nextDep;continue t}l=!1}return l}},endTracking:function(e){let t=e.depsTail,a=void 0!==t?t.nextDep:e.deps;for(;void 0!==a;)a=n(a,e);e.flags&=-5},startTracking:function(e){++r,e.depsTail=void 0,e.flags=-57&e.flags|4},shallowPropagate:i};function n(e,t=e.sub){let r=e.dep,i=e.prevDep,s=e.nextDep,o=e.nextSub,l=e.prevSub;return void 0!==s?s.prevDep=i:t.depsTail=i,void 0!==i?i.nextDep=s:t.deps=s,void 0!==o?o.prevSub=l:r.subsTail=l,void 0!==l?l.nextSub=o:void 0===(r.subs=o)&&a(r),s}function i(e){do{let a=e.sub,r=e.nextSub,n=a.flags;(48&n)==32&&(a.flags=16|n,2&n&&t(a)),e=r}while(void 0!==e)}}({update:e=>"getter"in e?ae(e):at(e,e.value),notify:function e(t){let a=t.flags;if(!(64&a)){t.flags=64|a;let r=t.subs;void 0!==r?e(r.sub):tZ[t5++]=t}},unwatched(e){if("getter"in e){let t=e.deps;if(void 0!==t){e.flags=17;do t=tY(t,e);while(void 0!==t)}}else"previousValue"in e||ai.call(e)}}),t3=0,t9=0,t5=0;function t6(t){let a=e;return e=t,a}function t8(e){return an.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function t4(e){return ar.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function t7(a){let r={fn:a,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==e?t$(r,e):void 0!==t&&t$(r,t);let n=t6(r);try{r.fn()}finally{t6(n)}return ai.bind(r)}function ae(e){let t=t6(e);t0(e);try{let t=e.value;return t!==(e.value=e.getter(t))}finally{t6(t),t1(e)}}function at(e,t){return e.flags=1,e.previousValue!==(e.previousValue=t)}function aa(){for(;t9<t5;){let e=tZ[t9];tZ[t9++]=void 0,function e(t,a){if(16&a||32&a&&tX(t.deps,t)){let e=t6(t);t0(t);try{t.fn()}finally{t6(e),t1(t)}return}32&a&&(t.flags=-33&a);let r=t.deps;for(;void 0!==r;){let t=r.dep,a=t.flags;64&a&&e(t,t.flags=-65&a),r=r.nextDep}}(e,e.flags&=-65)}t9=0,t5=0}function ar(){let a=this.flags;if(16&a||32&a&&tX(this.deps,this)){if(ae(this)){let e=this.subs;void 0!==e&&t2(e)}}else 32&a&&(this.flags=-33&a);return void 0!==e?t$(this,e):void 0!==t&&t$(this,t),this.value}function an(...t){if(t.length){let e=t[0];if(this.value!==(this.value=e)){this.flags=17;let e=this.subs;void 0!==e&&(tQ(e),t3||aa())}}else{let t=this.value;if(16&this.flags&&at(this,t)){let e=this.subs;void 0!==e&&t2(e)}return void 0!==e&&t$(this,e),t}}function ai(){let e=this.deps;for(;void 0!==e;)e=tY(e,this);let t=this.subs;void 0!==t&&tY(t),this.flags=0}function as(e){let{pageSize:t,initialPage:a,...r}=e||{},n=t??10;return new URLSearchParams({...Object.entries(r).reduce((e,[t,a])=>(void 0!==a&&(e[t]=a),e),{}),limit:n+"",offset:((a??1)-1)*n+""})}class ao{static #eu="/billing";static path(e,t){let{orgId:a}=t||{},r=a?`/organizations/${a}`:"/me";return`${r}${ao.#eu}${e}`}getPlans=async e=>{let{for:t,...a}=e||{},r={...a,payer_type:"organization"===t?"org":"user"};return await tH._fetch({path:`${ao.#eu}/plans`,method:"GET",search:as(r)}).then(e=>{let{data:t,total_count:a}=e;return{total_count:a,data:t.map(e=>new aE(e))}})};getPlan=async e=>new aE(await tH._fetch({path:`${ao.#eu}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await tH._fetch({path:ao.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new aC(e?.response));getStatements=async e=>{let{orgId:t,...a}=e;return await tH._fetch({path:ao.path("/statements",{orgId:t}),method:"GET",search:as(a)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new aA(e))}})};getStatement=async e=>new aA((await tH._fetch({path:ao.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:t,...a}=e;return await tH._fetch({path:ao.path("/payment_attempts",{orgId:t}),method:"GET",search:as(a)}).then(e=>{let{data:t,total_count:a}=e;return{total_count:a,data:t.map(e=>new ak(e))}})};getPaymentAttempt=async e=>new ak(await tH._fetch({path:ao.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:t,...a}=e;return new ay((await tH._fetch({path:ao.path("/checkouts",{orgId:t}),method:"POST",body:a}))?.response)}}let al=t8({resource:null}),ac=t8({error:null}),au=t8({status:"idle"}),ad=t4(()=>{let e=al().resource,t=ac().error,a=au().status;return{errors:ag(t,{identifier:null,password:null,code:null}),fetchStatus:a,signIn:e?e.__internal_future:null}}),ah=t8({resource:null}),am=t8({error:null}),ap=t8({status:"idle"}),af=t4(()=>{let e=ah().resource,t=am().error,a=ap().status;return{errors:ag(t,{firstName:null,lastName:null,emailAddress:null,phoneNumber:null,password:null,username:null,code:null,captcha:null,legalAccepted:null}),fetchStatus:a,signUp:e?e.__internal_future:null}});function ag(e,t){let a={fields:{...t},raw:null,global:null};if(!e)return a;if(!M(e))return a.raw=[e],a.global=[F(e)],a;function r(e){return"meta"in e&&e.meta&&"paramName"in e.meta&&void 0!==e.meta.paramName}return e.errors.some(r)?e.errors.forEach(e=>{if(a.raw?a.raw.push(e):a.raw=[e],r(e)){let t=ea(e.meta.paramName);t in a.fields&&(a.fields[t]=e)}}):(a.raw=[e],a.global=[F(e)]),a}class ab extends tH{id;createdAt;updatedAt;imageUrl;userId=null;email;firstName;lastName;organizationId=null;organizationName;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,e.created_at&&(this.createdAt=tV(e.created_at)),e.updated_at&&(this.updatedAt=tV(e.updated_at)),this.imageUrl=e.image_url,this.userId=e.user_id,this.email=e.email,this.firstName=e.first_name,this.lastName=e.last_name,this.organizationId=e.organization_id,this.organizationName=e.organization_name),this}}class ay extends tH{id;externalClientSecret;externalGatewayId;paymentMethod;plan;planPeriod;planPeriodStart;status;totals;isImmediatePlanChange;freeTrialEndsAt;payer;needsPaymentMethod;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.externalClientSecret=e.external_client_secret,this.externalGatewayId=e.external_gateway_id,this.paymentMethod=e.payment_method?new az(e.payment_method):void 0,this.plan=new aE(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=tm(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change,e.free_trial_ends_at&&(this.freeTrialEndsAt=tV(e.free_trial_ends_at)),this.payer=new ab(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>tl(()=>this._basePatch({path:ao.path(`/checkouts/${this.id}/confirm`,{orgId:this.payer.organizationId}),body:e}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,t){if(!M(e)||t>=4)return!1;let a=e?.status,r=409===a&&e.errors?.[0]?.code==="checkout_already_in_progress";return a>=500||r}})}class aw{resource=new ay(null);config;signals;pendingOperations=new Map;constructor(e,t){this.config=t,this.signals=e,this.signals.resourceSignal({resource:this})}get status(){return this.resource.status??"needs_initialization"}get externalClientSecret(){return this.resource.externalClientSecret}get externalGatewayId(){return this.resource.externalGatewayId}get plan(){return this.resource.plan}get planPeriod(){return this.resource.planPeriod}get totals(){return this.resource.totals}get isImmediatePlanChange(){return this.resource.isImmediatePlanChange}get freeTrialEndsAt(){return this.resource.freeTrialEndsAt}get payer(){return this.resource.payer}get paymentMethod(){return this.resource.paymentMethod??null}get planPeriodStart(){return this.resource.planPeriodStart}get needsPaymentMethod(){return this.resource.needsPaymentMethod}async start(){return this.runAsyncCheckoutTask("start",async()=>{let e=await ay.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new ay(null),this.signals.resourceSignal({resource:this})})}async confirm(e){if(!this.resource.id)throw Error("Clerk: `start()` must be called before `confirm()`");return this.runAsyncCheckoutTask("confirm",async()=>{await this.resource.confirm(e)})}async finalize(e){let{navigate:t}=e||{};return this.runAsyncCheckoutTask("finalize",async()=>{if("completed"!==this.resource.status)throw Error("Clerk: `confirm()` must be called before `finalize()`");await ay.clerk.setActive({session:ay.clerk.session?.id,navigate:t})})}runAsyncCheckoutTask(e,t,a){var r,n,i;return void 0===ay.clerk.user?(console.warn("Clerk: Checkout operations cannot be performed during transitive state"),{error:null}):(r=this,n=this.signals,i=this.pendingOperations,async(e,t,a)=>{if(i.get(e))return i.get(e);let s=(async()=>{++t3,n.errorSignal({error:null}),n.fetchSignal({status:"fetching"}),a?.(),--t3||aa(),++t3;try{return await t(),n.resourceSignal({resource:r}),{error:null}}catch(e){return n.errorSignal({error:e}),{error:e}}finally{i.delete(e),n.fetchSignal({status:"idle"}),--t3||aa()}})();return i.set(e,s),s})(e,t,a)}}class ak extends tH{id;amount;failedAt=null;paidAt=null;updatedAt;paymentMethod=null;subscriptionItem;chargeType;status;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.amount=th(e.amount),this.paidAt=e.paid_at?tV(e.paid_at):null,this.failedAt=e.failed_at?tV(e.failed_at):null,this.updatedAt=tV(e.updated_at),this.paymentMethod=e.payment_method?new az(e.payment_method):null,this.subscriptionItem=new aP(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status),this}}let av="/payment_methods",ax=async e=>{let{orgId:t,...a}=e;return new aS((await tH._fetch({path:ao.path(`${av}/initialize`,{orgId:t}),method:"POST",body:a}))?.response)},aj=async e=>{let{orgId:t,...a}=e;return new az((await tH._fetch({path:ao.path(av,{orgId:t}),method:"POST",body:a}))?.response)},a_=async e=>{let{orgId:t,...a}=e??{};return await tH._fetch({path:ao.path(av,{orgId:t}),method:"GET",search:as(a)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new az(e))}})};class az extends tH{id;last4=null;paymentType;cardType=null;isDefault;isRemovable;status;walletType;expiryYear;expiryMonth;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.last4=e.last4,this.paymentType=e.payment_type,this.cardType=e.card_type,this.isDefault=e.is_default,this.isRemovable=e.is_removable,this.status=e.status,this.walletType=e.wallet_type,this.expiryYear=e.expiry_year,this.expiryMonth=e.expiry_month,this.createdAt=null==e.created_at?e.created_at:tV(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:tV(e.updated_at)),this}async remove(e){let{orgId:t}=e??{};return new aF((await tH._fetch({path:ao.path(`/payment_methods/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:t}=e??{};return await tH._fetch({path:ao.path("/payers/default_payment_method",{orgId:t}),method:"PUT",body:{payment_method_id:this.id}}),null}}class aS extends tH{externalClientSecret;externalGatewayId;paymentMethodOrder;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.externalClientSecret=e.external_client_secret,this.externalGatewayId=e.external_gateway_id,this.paymentMethodOrder=e.payment_method_order??["card"]),this}}class aE extends tH{id;name;fee;annualFee=null;annualMonthlyFee=null;description=null;isDefault;isRecurring;hasBaseFee;forPayerType;publiclyVisible;slug;avatarUrl=null;features;freeTrialDays;freeTrialEnabled;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.fee=th(e.fee),this.annualFee=e.annual_fee?th(e.annual_fee):null,this.annualMonthlyFee=e.annual_monthly_fee?th(e.annual_monthly_fee):null,this.description=e.description,this.isDefault=e.is_default,this.isRecurring=e.is_recurring,this.hasBaseFee=e.has_base_fee,this.forPayerType=e.for_payer_type,this.publiclyVisible=e.publicly_visible,this.slug=e.slug,this.avatarUrl=e.avatar_url,this.freeTrialDays=this.withDefault(e.free_trial_days,null),this.freeTrialEnabled=this.withDefault(e.free_trial_enabled,!1),this.features=(e.features||[]).map(e=>new rc(e))),this}}class aA extends tH{id;status;timestamp;totals;groups;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.timestamp=tV(e.timestamp),this.totals=tm(e.totals),this.groups=e.groups.map(e=>new aI(e))),this}}class aI{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=tV(e.timestamp),this.items=e.items.map(e=>new ak(e))),this}}class aC extends tH{id;status;activeAt;createdAt;pastDueAt;updatedAt;nextPayment;subscriptionItems;eligibleForFreeTrial;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.createdAt=tV(e.created_at),this.updatedAt=e.updated_at?tV(e.updated_at):null,this.activeAt=tV(e.active_at),this.pastDueAt=e.past_due_at?tV(e.past_due_at):null,e.next_payment&&(this.nextPayment={amount:th(e.next_payment.amount),date:tV(e.next_payment.date)}),this.subscriptionItems=(e.subscription_items||[]).map(e=>new aP(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1)),this}}class aP extends tH{id;plan;planPeriod;status;createdAt;periodStart;periodEnd;canceledAt;pastDueAt;amount;credit;isFreeTrial;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.plan=new aE(e.plan),this.planPeriod=e.plan_period,this.status=e.status,this.createdAt=tV(e.created_at),this.pastDueAt=e.past_due_at?tV(e.past_due_at):null,this.periodStart=tV(e.period_start),this.periodEnd=e.period_end?tV(e.period_end):null,this.canceledAt=e.canceled_at?tV(e.canceled_at):null,this.amount=e.amount?th(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:th(e.credit.amount)}:void 0,this.isFreeTrial=this.withDefault(e.is_free_trial,!1)),this}async cancel(e){let{orgId:t}=e;return new aF((await tH._fetch({path:ao.path(`/subscription_items/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}}let aq={build:(e,t,a)=>[e,t,a].filter(Boolean).join("-"),parse:(e,t,a)=>{let r=aq.extractTemplate(e,t,a);return{organizationId:a,sessionId:t,template:r}},extractTemplate:(e,t,a)=>{if(e===t||a&&e===`${t}-${a}`)return;let r=e.slice(t.length+1);return a&&r.endsWith(`-${a}`)&&(r=r.slice(0,-(a.length+1))),r||void 0}},aO="clerk",aT=10,aU={broadcast:!0},aM={broadcast:!1};class aR{prefix;data;static fromKey(e){let[t,a,r=""]=e.split("::");return new aR(t,{audience:r,tokenId:a})}constructor(e,t){this.prefix=e,this.data=t,this.prefix=e,this.data=t}toKey(){let{tokenId:e,audience:t}=this.data;return[this.prefix,e,t||""].join("::")}}let aB=((e=aO)=>{let t=new Map,a=Math.random().toString(36).slice(2),r=null,n=()=>r||("undefined"==typeof BroadcastChannel?null:((r=new BroadcastChannel("clerk:session_token")).addEventListener("message",e=>{s(e)}),r));n();let i=(a,r=aT)=>{n();let i=new aR(e,a),s=t.get(i.toKey());if(!s)return;let o=Math.floor(Date.now()/1e3)-s.createdAt;if(s.expiresIn-o<(r||1)+5){void 0!==s.timeoutId&&clearTimeout(s.timeoutId),t.delete(i.toKey());return}return s.entry},s=async({data:e})=>{let t,r=aq.build(e.sessionId,e.template,e.organizationId);if(e.tokenId!==r)return void tn.warn("Ignoring token broadcast with mismatched tokenId",{expectedTokenId:r,organizationId:e.organizationId,receivedTokenId:e.tokenId,tabId:a,template:e.template,traceId:e.traceId},"tokenCache");try{t=new rJ({id:e.tokenId,jwt:e.tokenRaw,object:"token"})}catch(t){tn.warn("Failed to parse token from broadcast, skipping cache update",{error:t,tabId:a,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");return}let n=t.jwt?.claims?.iat,s=t.jwt?.claims?.exp;if(!n||!s)return void tn.warn("Token missing iat/exp claim, skipping cache update",{tabId:a,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");try{let t=i({tokenId:e.tokenId});if(t){let r=await t.tokenResolver,i=r.jwt?.claims?.iat;if(i&&i>=n)return void tn.debug("Ignoring older token broadcast",{existingIat:i,incomingIat:n,tabId:a,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}}catch(t){tn.warn("Existing entry compare failed; proceeding with broadcast update",{error:t,tabId:a,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}tn.info("Updating token cache from broadcast",{iat:n,organizationId:e.organizationId,tabId:a,template:e.template,tokenId:e.tokenId,traceId:e.traceId},"tokenCache"),o({createdAt:n,tokenId:e.tokenId,tokenResolver:Promise.resolve(t)},aM)},o=(n,i=aU)=>{let s=new aR(e,{audience:n.audience,tokenId:n.tokenId}).toKey(),o=Math.floor(Date.now()/1e3),l={createdAt:n.createdAt??o,entry:n,expiresIn:void 0},c=()=>{let e=t.get(s);e===l&&(void 0!==e.timeoutId&&clearTimeout(e.timeoutId),t.delete(s))};n.tokenResolver.then(e=>{let t=e.jwt?.claims;if(!t||"number"!=typeof t.exp||"number"!=typeof t.iat)return c();let s=t.exp-t.iat;l.expiresIn=s;let o=setTimeout(c,1e3*s);l.timeoutId=o,"function"==typeof o.unref&&o.unref();let u=r;if(u&&i.broadcast){let r=e.getRawString();if(r&&t.sid){let e=t.sid,i=t.org_id||t.o?.id,s=aq.extractTemplate(n.tokenId,e,i),o=aq.build(e,s,i);if(n.tokenId===o){let t=`bc_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;tn.info("Broadcasting token update to other tabs",{organizationId:i,sessionId:e,tabId:a,template:s,tokenId:n.tokenId,traceId:t},"tokenCache");let o={organizationId:i,sessionId:e,template:s,tokenId:n.tokenId,tokenRaw:r,traceId:t};u.postMessage(o)}}}}).catch(()=>{c()}),t.set(s,l)};return{clear:()=>{t.forEach(e=>{void 0!==e.timeoutId&&clearTimeout(e.timeoutId)}),t.clear()},close:()=>{r&&(r.close(),r=null)},get:i,set:e=>{n(),o(e,aU)},size:()=>t.size}})();class aN extends tH{static instance;pathRoot="/client";sessions=[];signUp=new rH;signIn=new rL;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return aN.instance||(aN.instance=new aN(e)),aN.instance}static clearInstance(){aN.instance=null}static isClientResource(e){return!!e&&e instanceof aN}constructor(e=null){super(),this.fromJSON(e)}get signUpAttempt(){return this.signUp}get signInAttempt(){return this.signIn}get signedInSessions(){return this.sessions.filter(e=>"active"===e.status||"pending"===e.status)}create(){return this._basePut()}fetch({fetchMaxTries:e}={}){return this._baseGet({fetchMaxTries:e})}async destroy(){return this._baseDelete({path:"/client"}).then(()=>{aB.clear(),this.id="",this.sessions=[],this.signUp=new rH(null),this.signIn=new rL(null),this.lastActiveSessionId=null,this.lastAuthenticationStrategy=null,this.cookieExpiresAt=null,this.createdAt=null,this.updatedAt=null})}removeSessions(){return this._baseDelete({path:this.path()+"/sessions"}).then(e=>(aB.clear(),e))}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return tH.fapiClient.buildUrl({method:"GET",path:"/client/touch",pathPrefix:"v1",search:{redirect_url:e.toString()}}).toString()}__internal_sendCaptchaToken(e){return this._basePostBypass({body:e,path:this.path()+"/verify"})}fromJSON(e){return e&&(this.id=e.id,this.sessions=(e.sessions||[]).map(e=>new rO(e)),this.signUp=new rH(e.sign_up),this.signIn=new rL(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?tV(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=tV(e.created_at||void 0),this.updatedAt=tV(e.updated_at||void 0)),this}__internal_toSnapshot(){return{object:"client",id:this.id||"",sessions:this.sessions.map(e=>e.__internal_toSnapshot()),sign_up:this.signUp.__internal_toSnapshot(),sign_in:this.signIn.__internal_toSnapshot(),last_active_session_id:this.lastActiveSessionId,captcha_bypass:this.captchaBypass,cookie_expires_at:this.cookieExpiresAt?this.cookieExpiresAt.getTime():null,last_authentication_strategy:this.lastAuthenticationStrategy??null,created_at:this.createdAt?.getTime()??null,updated_at:this.updatedAt?.getTime()??null}}path(){return this.pathRoot}}class aD extends tH{billing={stripePublishableKey:null,organization:{enabled:!1,hasPaidPlans:!1},user:{enabled:!1,hasPaidPlans:!1}};constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.billing.stripePublishableKey=e.billing.stripe_publishable_key,this.billing.organization.enabled=e.billing.organization.enabled,this.billing.organization.hasPaidPlans=e.billing.organization.has_paid_plans,this.billing.user.enabled=e.billing.user.enabled,this.billing.user.hasPaidPlans=e.billing.user.has_paid_plans),this}__internal_toSnapshot(){return{billing:{stripe_publishable_key:this.billing.stripePublishableKey,organization:{enabled:this.billing.organization.enabled,has_paid_plans:this.billing.organization.hasPaidPlans},user:{enabled:this.billing.user.enabled,has_paid_plans:this.billing.user.hasPaidPlans}}}}}class aF{object="";id;slug;deleted=!1;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.object=e.object,this.id=e.id,this.slug=e.slug,this.deleted=e.deleted),this}}class aL extends tH{afterCreateOrganizationUrl="";afterJoinWaitlistUrl="";afterLeaveOrganizationUrl="";afterSignInUrl="";afterSignOutAllUrl="";afterSignOutOneUrl="";afterSignOutUrl="";afterSignUpUrl="";afterSwitchSessionUrl="";applicationName="";backendHost="";branded=!1;captchaHeartbeat=!1;captchaHeartbeatIntervalMs;captchaOauthBypass=["oauth_google","oauth_microsoft","oauth_apple"];captchaProvider="turnstile";captchaPublicKey=null;captchaPublicKeyInvisible=null;captchaWidgetType=null;clerkJSVersion;createOrganizationUrl="";faviconImageUrl="";googleOneTapClientId;homeUrl="";id="";instanceEnvironmentType="";logoImageUrl="";organizationProfileUrl="";preferredSignInStrategy="password";privacyPolicyUrl="";showDevModeWarning=!1;signInUrl="";signUpUrl="";supportEmail="";termsUrl="";theme={};userProfileUrl="";waitlistUrl="";constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.afterCreateOrganizationUrl=this.withDefault(e.after_create_organization_url,this.afterCreateOrganizationUrl),this.afterJoinWaitlistUrl=this.withDefault(e.after_join_waitlist_url,this.afterJoinWaitlistUrl),this.afterLeaveOrganizationUrl=this.withDefault(e.after_leave_organization_url,this.afterLeaveOrganizationUrl),this.afterSignInUrl=this.withDefault(e.after_sign_in_url,this.afterSignInUrl),this.afterSignOutAllUrl=this.withDefault(e.after_sign_out_all_url,this.afterSignOutAllUrl),this.afterSignOutOneUrl=this.withDefault(e.after_sign_out_one_url,this.afterSignOutOneUrl),this.afterSignUpUrl=this.withDefault(e.after_sign_up_url,this.afterSignUpUrl),this.afterSwitchSessionUrl=this.withDefault(e.after_switch_session_url,this.afterSwitchSessionUrl),this.applicationName=this.withDefault(e.application_name,this.applicationName),this.branded=this.withDefault(e.branded,this.branded),this.captchaHeartbeat=this.withDefault(e.captcha_heartbeat,this.captchaHeartbeat),this.captchaHeartbeatIntervalMs=this.withDefault(e.captcha_heartbeat_interval_ms,this.captchaHeartbeatIntervalMs),this.captchaOauthBypass=this.withDefault(e.captcha_oauth_bypass,this.captchaOauthBypass),this.captchaProvider=this.withDefault(e.captcha_provider,this.captchaProvider),this.captchaPublicKey=this.withDefault(e.captcha_public_key,this.captchaPublicKey),this.captchaPublicKeyInvisible=this.withDefault(e.captcha_public_key_invisible,this.captchaPublicKeyInvisible),this.captchaWidgetType=this.withDefault(e.captcha_widget_type,this.captchaWidgetType),this.clerkJSVersion=this.withDefault(e.clerk_js_version,this.clerkJSVersion),this.createOrganizationUrl=this.withDefault(e.create_organization_url,this.createOrganizationUrl),this.faviconImageUrl=this.withDefault(e.favicon_image_url,this.faviconImageUrl),this.googleOneTapClientId=this.withDefault(e.google_one_tap_client_id,this.googleOneTapClientId),this.homeUrl=this.withDefault(e.home_url,this.homeUrl),this.id=this.withDefault(e.id,this.id),this.instanceEnvironmentType=this.withDefault(e.instance_environment_type,this.instanceEnvironmentType),this.logoImageUrl=this.withDefault(e.logo_image_url,this.logoImageUrl),this.organizationProfileUrl=this.withDefault(e.organization_profile_url,this.organizationProfileUrl),this.preferredSignInStrategy=this.withDefault(e.preferred_sign_in_strategy,this.preferredSignInStrategy),this.privacyPolicyUrl=this.withDefault(e.privacy_policy_url,this.privacyPolicyUrl),this.showDevModeWarning=this.withDefault(e.show_devmode_warning,this.showDevModeWarning),this.signInUrl=this.withDefault(e.sign_in_url,this.signInUrl),this.signUpUrl=this.withDefault(e.sign_up_url,this.signUpUrl),this.supportEmail=this.withDefault(e.support_email,this.supportEmail),this.termsUrl=this.withDefault(e.terms_url,this.termsUrl),this.theme=this.withDefault(e.theme,this.theme),this.userProfileUrl=this.withDefault(e.user_profile_url,this.userProfileUrl),this.waitlistUrl=this.withDefault(e.waitlist_url,this.waitlistUrl)),this}__internal_toSnapshot(){return{object:"display_config",after_create_organization_url:this.afterCreateOrganizationUrl,after_join_waitlist_url:this.afterJoinWaitlistUrl,after_leave_organization_url:this.afterLeaveOrganizationUrl,after_sign_in_url:this.afterSignInUrl,after_sign_out_all_url:this.afterSignOutAllUrl,after_sign_out_one_url:this.afterSignOutOneUrl,after_sign_up_url:this.afterSignUpUrl,after_switch_session_url:this.afterSwitchSessionUrl,application_name:this.applicationName,branded:this.branded,captcha_heartbeat_interval_ms:this.captchaHeartbeatIntervalMs,captcha_heartbeat:this.captchaHeartbeat,captcha_oauth_bypass:this.captchaOauthBypass,captcha_provider:this.captchaProvider,captcha_public_key_invisible:this.captchaPublicKeyInvisible,captcha_public_key:this.captchaPublicKey,captcha_widget_type:this.captchaWidgetType,clerk_js_version:this.clerkJSVersion,create_organization_url:this.createOrganizationUrl,favicon_image_url:this.faviconImageUrl,google_one_tap_client_id:this.googleOneTapClientId,home_url:this.homeUrl,id:this.id,instance_environment_type:this.instanceEnvironmentType,logo_image_url:this.logoImageUrl,organization_profile_url:this.organizationProfileUrl,preferred_sign_in_strategy:this.preferredSignInStrategy,privacy_policy_url:this.privacyPolicyUrl,show_devmode_warning:this.showDevModeWarning,sign_in_url:this.signInUrl,sign_up_url:this.signUpUrl,support_email:this.supportEmail,terms_url:this.termsUrl,theme:this.theme,user_profile_url:this.userProfileUrl,waitlist_url:this.waitlistUrl}}}var aW='const respond=r=>{self.postMessage(r)},workerToTabIds={};self.addEventListener("message",r=>{const e=r.data;switch(e.type){case"setTimeout":workerToTabIds[e.id]=setTimeout(()=>{respond({id:e.id}),delete workerToTabIds[e.id]},e.ms);break;case"clearTimeout":workerToTabIds[e.id]&&(clearTimeout(workerToTabIds[e.id]),delete workerToTabIds[e.id]);break;case"setInterval":workerToTabIds[e.id]=setInterval(()=>{respond({id:e.id})},e.ms);break;case"clearInterval":workerToTabIds[e.id]&&(clearInterval(workerToTabIds[e.id]),delete workerToTabIds[e.id]);break}});\n';let aK=(e,t={})=>{if("undefined"==typeof Worker)return null;try{let a=new Blob([e],{type:"application/javascript; charset=utf-8"}),r=globalThis.URL.createObjectURL(a);return new Worker(r,t)}catch{return console.warn("Clerk: Cannot create worker from blob. Consider adding worker-src blob:; to your CSP"),null}},aH=()=>{let e=0,t=()=>e++,a=new Map,r=(e,t)=>e?.postMessage(t),n=e=>{a.get(e.data.id)?.()},i=aK(aW,{name:"clerk-timers"});if(i?.addEventListener("message",n),!i)return{setTimeout:globalThis.setTimeout.bind(globalThis),setInterval:globalThis.setInterval.bind(globalThis),clearTimeout:globalThis.clearTimeout.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis),cleanup:e8};let s=()=>{i||(i=aK(aW,{name:"clerk-timers"}),i?.addEventListener("message",n))};return{setTimeout:(e,n)=>{s();let o=t();return a.set(o,()=>{e(),a.delete(o)}),r(i,{type:"setTimeout",id:o,ms:n}),o},setInterval:(e,n)=>{s();let o=t();return a.set(o,e),r(i,{type:"setInterval",id:o,ms:n}),o},clearTimeout:e=>{s(),a.delete(e),r(i,{type:"clearTimeout",id:e})},clearInterval:e=>{s(),a.delete(e),r(i,{type:"clearInterval",id:e})},cleanup:()=>{i&&(i.terminate(),i=null,a.clear())}}};function aV({delayInMs:e}={delayInMs:1e3}){let t,a=aH(),r=!1,n=()=>{t&&(a.clearTimeout(t),a.cleanup()),r=!0},i=async s=>{r=!1,await s(n),r||(t=a.setTimeout(()=>{i(s)},e))};return{run:i,stop:n}}class aG extends tH{id;emailAddress="";matchesSsoConnection=!1;linkedTo=[];verification;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}create(){return this._basePost({body:{email_address:this.emailAddress}})}prepareVerification=e=>this._basePost({action:"prepare_verification",body:{...e}});attemptVerification=e=>{let{code:t}=e||{};return this._basePost({action:"attempt_verification",body:{code:t}})};createEmailLinkFlow=()=>{let{run:e,stop:t}=aV();return{startEmailLinkFlow:async({redirectUrl:a})=>(await this.prepareVerification({strategy:"email_link",redirectUrl:a}),new Promise((a,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),a(e))}).catch(e=>{t(),r(e)}))})),cancelEmailLinkFlow:t}};createEnterpriseSSOLinkFlow=()=>{let{run:e,stop:t}=aV();return{startEnterpriseSSOLinkFlow:async({redirectUrl:a})=>{if(!(await this.prepareVerification({strategy:"enterprise_sso",redirectUrl:a})).verification.externalVerificationRedirectURL)throw Error("Unexpected: External verification redirect URL is missing");return new Promise((a,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),a(e))}).catch(e=>{t(),r(e)}))})},cancelEnterpriseSSOLinkFlow:t}};destroy=()=>this._baseDelete();toString=()=>this.emailAddress;fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.verification=new a9(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new ru(e))),this}__internal_toSnapshot(){return{object:"email_address",id:this.id,email_address:this.emailAddress,verification:this.verification.__internal_toSnapshot(),linked_to:this.linkedTo.map(e=>e.__internal_toSnapshot()),matches_sso_connection:this.matchesSsoConnection}}}var aJ=class{static encode(e){return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}static decode(e){let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),a=t.length,r=new Uint8Array(a);for(let e=0;e<a;e++)r[e]=t.charCodeAt(e);return r.buffer}};async function aZ(e){try{let t=await navigator.credentials.create({publicKey:e});if(!t)return{error:new q("Browser failed to create credential",{code:"passkey_registration_failed"}),publicKeyCredential:null};return{publicKeyCredential:t,error:null}}catch(e){var t;return{error:"InvalidStateError"===(t=e).name?new q(t.message,{code:"passkey_already_exists"}):"NotAllowedError"===t.name?new q(t.message,{code:"passkey_registration_cancelled"}):aQ(t),publicKeyCredential:null}}}let a$=new class{controller;__abort(){if(!this.controller)return;let e=Error();e.name="AbortError",this.controller.abort(e)}createAbortSignal(){this.__abort();let e=new AbortController;return this.controller=e,e.signal}abort(){this.__abort(),this.controller=void 0}};async function aY({publicKeyOptions:e,conditionalUI:t}){try{let a=await navigator.credentials.get({publicKey:e,mediation:t?"conditional":"optional",signal:a$.createAbortSignal()});if(!a)return{error:new q("Browser failed to get credential",{code:"passkey_retrieval_failed"}),publicKeyCredential:null};return{publicKeyCredential:a,error:null}}catch(e){var a;return{error:"NotAllowedError"===(a=e).name?new q(a.message,{code:"passkey_retrieval_cancelled"}):aQ(a),publicKeyCredential:null}}}function aQ(e){return"AbortError"===e.name?new q(e.message,{code:"passkey_operation_aborted"}):"SecurityError"===e.name?new q(e.message,{code:"passkey_invalid_rpID_or_domain"}):e}function aX(e){let t=a3(e.challenge),a=(e.allowCredentials||[]).map(e=>({...e,id:a3(e.id)}));return{...e,allowCredentials:a,challenge:t}}function a1(e){return{type:e.type,id:e.id,rawId:a2(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function a0(e){let t=e.response;return{...a1(e),response:{clientDataJSON:a2(t.clientDataJSON),authenticatorData:a2(t.authenticatorData),signature:a2(t.signature),userHandle:t.userHandle?a2(t.userHandle):null}}}let a2=aJ.encode.bind(aJ),a3=aJ.decode.bind(aJ);class a9 extends tH{pathRoot="";status=null;strategy=null;nonce=null;message=null;externalVerificationRedirectURL=null;attempts=null;expireAt=null;error=null;verifiedAtClient=null;channel;constructor(e){super(),this.fromJSON(e)}verifiedFromTheSameClient=()=>this.verifiedAtClient===tH.clerk?.client?.id;fromJSON(e){return e&&(this.status=e.status,this.verifiedAtClient=e.verified_at_client,this.strategy=e.strategy,this.nonce=e.nonce||null,this.message=e.message||null,e.external_verification_redirect_url?this.externalVerificationRedirectURL=new URL(e.external_verification_redirect_url):this.externalVerificationRedirectURL=null,this.attempts=e.attempts,this.expireAt=tV(e.expire_at||void 0),this.error=e.error?new v(e.error):null,this.channel=e.channel||void 0),this}__internal_toSnapshot(){var e;return{object:"verification",id:this.id||"",status:this.status,strategy:this.strategy,nonce:this.nonce,message:this.message,external_verification_redirect_url:this.externalVerificationRedirectURL?.toString()||null,attempts:this.attempts,expire_at:this.expireAt?.getTime()||null,error:(e=this.error,{code:e?.code||"",message:e?.message||"",long_message:e?.longMessage,meta:{param_name:e?.meta?.paramName,session_id:e?.meta?.sessionId,email_addresses:e?.meta?.emailAddresses,identifiers:e?.meta?.identifiers,zxcvbn:e?.meta?.zxcvbn,plan:e?.meta?.plan,is_plan_upgrade_possible:e?.meta?.isPlanUpgradePossible}}),verified_at_client:this.verifiedAtClient}}}class a5 extends a9{publicKey=null;constructor(e){super(e),this.fromJSON(e)}fromJSON(e){var t;let a,r,n;return super.fromJSON(e),e?.nonce&&(this.publicKey=(a=a3((t=JSON.parse(e.nonce)).user.id),r=a3(t.challenge),n=(t.excludeCredentials||[]).map(e=>({...e,id:a3(e.id)})),{...t,excludeCredentials:n,challenge:r,user:{...t.user,id:a}})),this}}class a6{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new a8(e.email_address),this.phoneNumber=new a8(e.phone_number),this.web3Wallet=new a8(e.web3_wallet),this.externalAccount=new a9(e.external_account)):(this.emailAddress=new a8(null),this.phoneNumber=new a8(null),this.web3Wallet=new a8(null),this.externalAccount=new a9(null))}__internal_toSnapshot(){return{email_address:this.emailAddress.__internal_toSnapshot(),phone_number:this.phoneNumber.__internal_toSnapshot(),web3_wallet:this.web3Wallet.__internal_toSnapshot(),external_account:this.externalAccount.__internal_toSnapshot()}}}class a8 extends a9{nextAction;supportedStrategies;constructor(e){super(e),e?(this.nextAction=e.next_action,this.supportedStrategies=e.supported_strategies):(this.nextAction="",this.supportedStrategies=[])}__internal_toSnapshot(){return{...super.__internal_toSnapshot(),next_action:this.nextAction,supported_strategies:this.supportedStrategies}}}class a4 extends tH{id;protocol;provider;providerUserId=null;active;emailAddress="";firstName="";lastName="";publicMetadata={};verification=null;enterpriseConnection=null;lastAuthenticatedAt=null;enterpriseConnectionId=null;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.provider=e.provider,this.protocol=e.protocol,this.providerUserId=e.provider_user_id,this.active=e.active,this.emailAddress=e.email_address,this.firstName=e.first_name,this.lastName=e.last_name,this.publicMetadata=e.public_metadata,this.lastAuthenticatedAt=e.last_authenticated_at?tV(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new a9(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new a7(e.enterprise_connection))),this}__internal_toSnapshot(){return{object:"enterprise_account",id:this.id,provider:this.provider,protocol:this.protocol,provider_user_id:this.providerUserId,active:this.active,email_address:this.emailAddress,first_name:this.firstName,last_name:this.lastName,public_metadata:this.publicMetadata,verification:this.verification?.__internal_toSnapshot()||null,enterprise_connection:this.enterpriseConnection?.__internal_toSnapshot()||null,last_authenticated_at:this.lastAuthenticatedAt?this.lastAuthenticatedAt.getTime():null,enterprise_connection_id:this.enterpriseConnectionId}}}class a7 extends tH{id;active;allowIdpInitiated;allowSubdomains;disableAdditionalIdentifications;domain;logoPublicUrl="";name;protocol;provider;syncUserAttributes;createdAt;updatedAt;enterpriseConnectionId="";constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.domain=e.domain,this.active=e.active,this.provider=e.provider,this.logoPublicUrl=e.logo_public_url,this.syncUserAttributes=e.sync_user_attributes,this.allowSubdomains=e.allow_subdomains,this.allowIdpInitiated=e.allow_idp_initiated,this.disableAdditionalIdentifications=e.disable_additional_identifications,this.createdAt=tV(e.created_at),this.updatedAt=tV(e.updated_at),this.enterpriseConnectionId=e.enterprise_connection_id),this}__internal_toSnapshot(){return{object:"enterprise_account_connection",id:this.id,name:this.name,domain:this.domain,active:this.active,protocol:this.protocol,provider:this.provider,logo_public_url:this.logoPublicUrl,sync_user_attributes:this.syncUserAttributes,allow_subdomains:this.allowSubdomains,allow_idp_initiated:this.allowIdpInitiated,disable_additional_identifications:this.disableAdditionalIdentifications,enterprise_connection_id:this.enterpriseConnectionId,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}let re="token:update",rt="user:signOut",ra="environment:update",rr="session:tokenResolved",rn=f();class ri extends tH{user_api_keys_enabled=!1;orgs_api_keys_enabled=!1;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.user_api_keys_enabled=e.user_api_keys_enabled,this.orgs_api_keys_enabled=e.orgs_api_keys_enabled),this}__internal_toSnapshot(){return{user_api_keys_enabled:this.user_api_keys_enabled,orgs_api_keys_enabled:this.orgs_api_keys_enabled}}}class rs extends tH{actions={adminDelete:!1};domains={enabled:!1,enrollmentModes:[],defaultRole:null};slug={disabled:!1};enabled=!1;maxAllowedMemberships=1;forceOrganizationSelection;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(e.actions&&(this.actions.adminDelete=this.withDefault(e.actions.admin_delete,this.actions.adminDelete)),e.domains&&(this.domains.enabled=this.withDefault(e.domains.enabled,this.domains.enabled),this.domains.enrollmentModes=this.withDefault(e.domains.enrollment_modes,this.domains.enrollmentModes),this.domains.defaultRole=this.withDefault(e.domains.default_role,this.domains.defaultRole)),e.slug&&(this.slug.disabled=this.withDefault(e.slug.disabled,this.slug.disabled)),this.enabled=this.withDefault(e.enabled,this.enabled),this.maxAllowedMemberships=this.withDefault(e.max_allowed_memberships,this.maxAllowedMemberships),this.forceOrganizationSelection=this.withDefault(e.force_organization_selection,this.forceOrganizationSelection)),this}__internal_toSnapshot(){return{actions:{admin_delete:this.actions.adminDelete},domains:{enabled:this.domains.enabled,enrollment_modes:this.domains.enrollmentModes,default_role:this.domains.defaultRole},enabled:this.enabled,max_allowed_memberships:this.maxAllowedMemberships}}}class ro extends tH{static instance;authConfig=new tJ;displayConfig=new aL;maintenanceMode=!1;clientDebugMode=!1;pathRoot="/environment";userSettings=new r0;organizationSettings=new rs;commerceSettings=new aD;apiKeysSettings=new ri;protectConfig=new rz;static getInstance(){return ro.instance||(ro.instance=new ro),ro.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new tJ(e.auth_config),this.displayConfig=new aL(e.display_config),this.maintenanceMode=this.withDefault(e.maintenance_mode,this.maintenanceMode),this.clientDebugMode=this.withDefault(e.client_debug_mode,this.clientDebugMode),this.organizationSettings=new rs(e.organization_settings),this.userSettings=new r0(e.user_settings),this.commerceSettings=new aD(e.commerce_settings),this.apiKeysSettings=new ri(e.api_keys_settings),this.protectConfig=new rz(e.protect_config)),this}fetch({touch:e,fetchMaxTries:t}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:t})).then(e=>(rn.emit(ra,null),e))}isDevelopmentOrStaging=()=>!this.isProduction();isProduction=()=>"production"===this.displayConfig.instanceEnvironmentType;isSingleSession=()=>this.authConfig.singleSessionMode;onWindowLocationHost=()=>this.displayConfig.backendHost===window.location.host;__internal_toSnapshot(){return{object:"environment",auth_config:this.authConfig.__internal_toSnapshot(),display_config:this.displayConfig.__internal_toSnapshot(),id:this.id??"",maintenance_mode:this.maintenanceMode,client_debug_mode:this.clientDebugMode,organization_settings:this.organizationSettings.__internal_toSnapshot(),user_settings:this.userSettings.__internal_toSnapshot(),commerce_settings:this.commerceSettings.__internal_toSnapshot(),api_keys_settings:this.apiKeysSettings.__internal_toSnapshot(),protect_config:this.protectConfig.__internal_toSnapshot()}}async __internal_enableEnvironmentSetting(e){await this._basePatch({path:"/dev_tools/enable_environment_setting",body:e})}}class rl extends tH{id;identificationId;provider;providerUserId="";emailAddress="";approvedScopes="";firstName="";lastName="";imageUrl="";username="";phoneNumber="";publicMetadata={};label="";verification=null;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}reauthorize=e=>{let{additionalScopes:t,redirectUrl:a}=e||{};return this._basePatch({action:"reauthorize",body:{additional_scope:t,redirect_url:a}})};destroy=()=>this._baseDelete();fromJSON(e){return e&&(this.id=e.id,this.identificationId=e.identification_id,this.providerUserId=e.provider_user_id,this.approvedScopes=e.approved_scopes,this.imageUrl=e.image_url,this.emailAddress=e.email_address,this.firstName=e.first_name,this.lastName=e.last_name,this.provider=(e.provider||"").replace("oauth_",""),this.username=e.username,this.phoneNumber=e.phone_number,this.publicMetadata=e.public_metadata,this.label=e.label,e.verification&&(this.verification=new a9(e.verification))),this}__internal_toSnapshot(){return{object:"external_account",id:this.id,identification_id:this.identificationId,provider:this.provider,provider_user_id:this.providerUserId,email_address:this.emailAddress,approved_scopes:this.approvedScopes,first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl,username:this.username,phone_number:this.phoneNumber,public_metadata:this.publicMetadata,label:this.label,verification:this.verification?.__internal_toSnapshot()||null}}providerSlug(){return this.provider}providerTitle(){let e;return[(e=this.providerSlug()||"").charAt(0).toUpperCase()+e.slice(1),"Account"].join(" ")}accountIdentifier(){return this.username||this.emailAddress||this.label}}class rc extends tH{id;name;description=null;slug;avatarUrl=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.description=e.description,this.slug=e.slug,this.avatarUrl=e.avatar_url),this}}class ru extends tH{id;type;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.type=e.type),this}__internal_toSnapshot(){return{object:"identification_link",id:this.id,type:this.type}}}class rd extends tH{id;name=null;publicUrl=null;static async create(e,t={}){let a,r=t;return"string"==typeof t.file?(r=t.file,a=new Headers({"Content-Type":"application/octet-stream"})):t.file&&(r=new FormData).append("file",t.file),new rd((await tH._fetch({path:e,method:"POST",body:r,headers:a}))?.response)}static async delete(e){return new rd((await tH._fetch({path:e,method:"DELETE"}))?.response)}constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.publicUrl=e.public_url),this}}class rh extends tH{id;name;organizationId;enrollmentMode;verification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:t}){return new rh((await tH._fetch({path:`/organizations/${e}/domains`,method:"POST",body:{name:t}}))?.response)}prepareAffiliationVerification=async e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/prepare_affiliation_verification`,method:"POST",body:e});attemptAffiliationVerification=async e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/attempt_affiliation_verification`,method:"POST",body:e});updateEnrollmentMode=e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/update_enrollment_mode`,body:e});delete=()=>this._baseDelete({path:`/organizations/${this.organizationId}/domains/${this.id}`});fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.organizationId=e.organization_id,this.enrollmentMode=e.enrollment_mode,this.affiliationEmailAddress=e.affiliation_email_address,this.totalPendingSuggestions=e.total_pending_suggestions,this.totalPendingInvitations=e.total_pending_invitations,e.verification?this.verification={status:e.verification.status,strategy:e.verification.strategy,attempts:e.verification.attempts,expiresAt:tV(e.verification.expires_at)}:this.verification=null),this}}class rm extends tH{id;organizationId;status;publicUserData;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}accept=async()=>await this._basePost({path:`/organizations/${this.organizationId}/membership_requests/${this.id}/accept`});reject=async()=>await this._basePost({path:`/organizations/${this.organizationId}/membership_requests/${this.id}/reject`});fromJSON(e){return e&&(this.id=e.id,this.organizationId=e.organization_id,this.status=e.status,this.createdAt=tV(e.created_at),this.updatedAt=tV(e.updated_at),e.public_user_data&&(this.publicUserData=new rS(e.public_user_data))),this}}class rp extends tH{id;key;name;description;type;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.key=e.key,this.name=e.name,this.description=e.description,this.type=e.type,this.createdAt=tV(e.created_at),this.updatedAt=tV(e.updated_at)),this}}class rf extends tH{id;key;name;description;permissions=[];createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.key=e.key,this.name=e.name,this.description=e.description,this.permissions=e.permissions.map(e=>new rp(e)),this.createdAt=tV(e.created_at),this.updatedAt=tV(e.updated_at)),this}}class rg extends tH{pathRoot="/organizations";id;name;slug;imageUrl;hasImage;publicMetadata={};adminDeleteEnabled;createdAt;updatedAt;membersCount=0;pendingInvitationsCount=0;maxAllowedMemberships;constructor(e){super(),this.fromJSON(e)}static async create(e){return new rg((await tH._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new rg((await tH._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await tH._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:as(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rf(e))}});getDomains=async e=>await tH._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:as(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rh(e))}});getDomain=async({domainId:e})=>new rh((await tH._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getMembershipRequests=async e=>await tH._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:as(e)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rm(e))}});createDomain=async e=>rh.create(this.id,{name:e});getMemberships=async e=>await tH._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:as({...e,paginated:!0})}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new ry(e))}});getInvitations=async e=>await tH._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:as(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rb(e))}});addMember=async({userId:e,role:t})=>await tH._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:t}}).then(e=>new ry(e?.response));inviteMember=async e=>rb.create(this.id,e);inviteMembers=async e=>rb.createBulk(this.id,e);updateMember=async({userId:e,role:t})=>await tH._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:t}}).then(e=>new ry(e?.response));removeMember=async e=>await tH._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new ry(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let t,a;return null===e?await tH._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new rg(e?.response)):("string"==typeof e?(t=e,a=new Headers({"Content-Type":"application/octet-stream"})):(t=new FormData).append("file",e),await tH._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:t,headers:a}).then(e=>new rg(e?.response)))};initializePaymentMethod=e=>ax({...e,orgId:this.id});addPaymentMethod=e=>aj({...e,orgId:this.id});getPaymentMethods=e=>a_({...e,orgId:this.id});fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.slug=e.slug,this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.publicMetadata=e.public_metadata||{},this.membersCount=e.members_count||0,this.pendingInvitationsCount=e.pending_invitations_count||0,this.maxAllowedMemberships=e.max_allowed_memberships||0,this.adminDeleteEnabled=e.admin_delete_enabled||!1,this.createdAt=tV(e.created_at),this.updatedAt=tV(e.updated_at)),this}__internal_toSnapshot(){return{object:"organization",id:this.id,name:this.name,slug:this.slug,image_url:this.imageUrl,has_image:this.hasImage,public_metadata:this.publicMetadata,members_count:this.membersCount,pending_invitations_count:this.pendingInvitationsCount,max_allowed_memberships:this.maxAllowedMemberships,admin_delete_enabled:this.adminDeleteEnabled,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}async reload(e){let{rotatingTokenNonce:t}=e||{},a=(await tH._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:t},{forceUpdateClient:!0}))?.response;return this.fromJSON(a)}}class rb extends tH{id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:t,role:a}){return new rb((await tH._fetch({path:`/organizations/${e}/invitations`,method:"POST",body:{email_address:t,role:a}}))?.response)}static async createBulk(e,t){let{emailAddresses:a,role:r}=t;return((await tH._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:a,role:r}}))?.response).map(e=>new rb(e))}constructor(e){super(),this.fromJSON(e)}revoke=async()=>await this._basePost({path:`/organizations/${this.organizationId}/invitations/${this.id}/revoke`});fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.organizationId=e.organization_id,this.publicMetadata=e.public_metadata,this.role=e.role,this.roleName=e.role_name,this.status=e.status,this.createdAt=tV(e.created_at),this.updatedAt=tV(e.updated_at)),this}}class ry extends tH{id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await tH._fetch({path:"/me/organization_memberships",method:"GET",search:as({...e,paginated:!0})}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new ry(e))}});destroy=async()=>await this._baseDelete({path:`/organizations/${this.organization.id}/memberships/${this.publicUserData?.userId}`});update=async({role:e})=>await this._basePatch({path:`/organizations/${this.organization.id}/memberships/${this.publicUserData?.userId}`,body:{role:e}});fromJSON(e){return e&&(this.id=e.id,this.organization=new rg(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new rS(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=tV(e.created_at),this.updatedAt=tV(e.updated_at)),this}__internal_toSnapshot(){return{object:"organization_membership",id:this.id,organization:this.organization.__internal_toSnapshot(),public_metadata:this.publicMetadata,public_user_data:this.publicUserData?.__internal_toSnapshot(),permissions:this.permissions,role:this.role,role_name:this.roleName,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}reload(e){throw Error(`${tA} Calling OrganizationMembership.reload is not currently supported. Please contact support.`)}}class rw extends tH{id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await tH._fetch({path:"/me/organization_suggestions",method:"GET",search:as(e)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rw(e))}})}accept=async()=>await this._basePost({path:`/me/organization_suggestions/${this.id}/accept`});fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.publicOrganizationData={hasImage:e.public_organization_data.has_image,imageUrl:e.public_organization_data.image_url,name:e.public_organization_data.name,id:e.public_organization_data.id,slug:e.public_organization_data.slug},this.createdAt=tV(e.created_at),this.updatedAt=tV(e.updated_at)),this}}function rk(){return c()&&"function"==typeof window.PublicKeyCredential}async function rv(){try{return rk()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function rx(){try{return"undefined"!=typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class rj extends tH{id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return tH._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new rj(e?.response))}static async attemptVerification(e,t){let a,r=(a=t.response,{...a1(t),response:{clientDataJSON:a2(a.clientDataJSON),attestationObject:a2(a.attestationObject),transports:a.getTransports()}});return tH._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(r)}}).then(e=>new rj(e?.response))}static async registerPasskey(){let e=rj.clerk.__internal_isWebAuthnSupported||rk,t=rj.clerk.__internal_createPublicCredentials||aZ,a=rj.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||rx;if(!e())throw new q("Passkeys are not supported on this device.",{code:"passkey_not_supported"});let r=await this.create(),{verification:n}=r,i=n?.publicKey;if(i||tM("create"),i.authenticatorSelection?.authenticatorAttachment==="platform"&&!await a())throw new q("Registration requires a platform authenticator but the device does not support it.",{code:"passkey_pa_not_supported"});let{publicKeyCredential:s,error:o}=await t(i);if(!s)throw o;return this.attemptVerification(r.id,s)}update=e=>this._basePatch({body:e});delete=async()=>new aF((await tH._fetch({path:this.path(),method:"DELETE"}))?.response);fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.lastUsedAt=e.last_used_at?tV(e.last_used_at):null,this.createdAt=tV(e.created_at),this.updatedAt=tV(e.updated_at),e.verification&&(this.verification=new a5(e.verification))),this}__internal_toSnapshot(){return{object:"passkey",id:this.id,name:this.name,verification:this.verification?.__internal_toSnapshot()||null,last_used_at:this.lastUsedAt?.getTime()||null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}class r_ extends tH{id;phoneNumber="";reservedForSecondFactor=!1;defaultSecondFactor=!1;linkedTo=[];verification;backupCodes;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}create=()=>this._basePost({body:{phone_number:this.phoneNumber}});prepareVerification=()=>this._basePost({action:"prepare_verification",body:{strategy:"phone_code"}});attemptVerification=e=>{let{code:t}=e||{};return this._basePost({action:"attempt_verification",body:{code:t}})};setReservedForSecondFactor=e=>{let{reserved:t}=e||{};return this._basePatch({body:{reserved_for_second_factor:t}})};makeDefaultSecondFactor=()=>this._basePatch({body:{default_second_factor:!0}});destroy=()=>this._baseDelete();toString=()=>{let e=this.phoneNumber.match(/^(\d{3})(\d{3})(\d{4})$/);return e?"("+e[1]+") "+e[2]+"-"+e[3]:this.phoneNumber};fromJSON(e){return e&&(this.id=e.id,this.phoneNumber=e.phone_number,this.reservedForSecondFactor=e.reserved_for_second_factor,this.defaultSecondFactor=e.default_second_factor,this.verification=new a9(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new ru(e)),this.backupCodes=e.backup_codes),this}__internal_toSnapshot(){return{object:"phone_number",id:this.id||"",phone_number:this.phoneNumber,reserved_for_second_factor:this.reservedForSecondFactor,default_second_factor:this.defaultSecondFactor,verification:this.verification.__internal_toSnapshot(),linked_to:this.linkedTo.map(e=>e.__internal_toSnapshot()),backup_codes:this.backupCodes}}}class rz extends tH{id="";loaders;rollout;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=this.withDefault(e.id,this.id),this.loaders=this.withDefault(e.loaders,this.loaders)),this}__internal_toSnapshot(){return{object:"protect_config",id:this.id,loaders:this.loaders}}}class rS{firstName;lastName;imageUrl;hasImage;identifier;userId;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.firstName=e.first_name||null,this.lastName=e.last_name||null,this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.identifier=e.identifier||"",this.userId=e.user_id),this}__internal_toSnapshot(){return{first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl,has_image:this.hasImage,identifier:this.identifier,user_id:this.userId}}}let rE={strict_mfa:{afterMinutes:10,level:"multi_factor"},strict:{afterMinutes:10,level:"second_factor"},moderate:{afterMinutes:60,level:"second_factor"},lax:{afterMinutes:1440,level:"second_factor"}},rA=new Set(["first_factor","second_factor","multi_factor"]),rI=new Set(["strict_mfa","strict","moderate","lax"]),rC=(e,t)=>{let{org:a,user:r}=rP(e),[n,i]=t.split(":"),s=i||n;return"org"===n?a.includes(s):"user"===n?r.includes(s):[...a,...r].includes(s)},rP=e=>{let t=e?e.split(",").map(e=>e.trim()):[];return{org:t.filter(e=>e.split(":")[0].includes("o")).map(e=>e.split(":")[1]),user:t.filter(e=>e.split(":")[0].includes("u")).map(e=>e.split(":")[1])}};class rq extends tH{status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new a9(null);secondFactorVerification=new a9(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new rO(e.session),this.level=e.level,this.supportedFirstFactors=es(e.supported_first_factors),this.supportedSecondFactors=es(e.supported_second_factors),this.firstFactorVerification=new a9(e.first_factor_verification),this.secondFactorVerification=new a9(e.second_factor_verification)),this}}class rO extends tH{pathRoot="/client/sessions";id;status;lastActiveAt;lastActiveToken;lastActiveOrganizationId;actor;user;publicUserData;factorVerificationAge=null;tasks=null;expireAt;abandonAt;createdAt;updatedAt;static isSessionResource(e){return!!e&&e instanceof rO}constructor(e){super(),this.fromJSON(e),this.#ed(this.lastActiveToken)}end=()=>(aB.clear(),this._basePost({action:"end"}));remove=()=>(aB.clear(),this._basePost({action:"remove"}));touch=()=>this._basePost({action:"touch",body:{active_organization_id:this.lastActiveOrganizationId}}).then(e=>(e.lastActiveToken&&rn.emit(re,{token:e.lastActiveToken}),e));clearCache=()=>aB.clear();getToken=async e=>tl(()=>this._getToken(e),{factor:1.55,initialDelay:3e3,maxDelayBetweenRetries:5e4,jitter:!1,shouldRetry:(e,t)=>!T(e)&&t<=8});checkAuthorization=e=>{let t,a=(this.user?.organizationMemberships||[]).find(e=>e.organization.id===this.lastActiveOrganizationId);return(t={userId:this.user?.id,factorVerificationAge:this.factorVerificationAge,orgId:a?.id,orgRole:a?.role,orgPermissions:a?.permissions,features:this.lastActiveToken?.jwt?.claims.fea||"",plans:this.lastActiveToken?.jwt?.claims.pla||""},e=>{if(!t.userId)return!1;let a=((e,t)=>{let{features:a,plans:r}=t;return e.feature&&a?rC(a,e.feature):e.plan&&r?rC(r,e.plan):null})(e,t),r=((e,t)=>{let{orgId:a,orgRole:r,orgPermissions:n}=t;return(e.role||e.permission)&&a&&r&&n?e.permission?n.includes(e.permission.replace(/^(org:)*/,"org:")):e.role?r.replace(/^(org:)*/,"org:")===e.role.replace(/^(org:)*/,"org:"):null:null})(e,t),n=((e,{factorVerificationAge:t})=>{if(!e.reverification||!t)return null;let a=(e=>{let t,a;if(!e)return!1;let r="string"==typeof e&&rI.has(e),n="object"==typeof e&&(t=e.level,rA.has(t))&&"number"==typeof(a=e.afterMinutes)&&a>0;return(!!r||!!n)&&(e=>"string"==typeof e?rE[e]:e).bind(null,e)})(e.reverification);if(!a)return null;let{level:r,afterMinutes:n}=a(),[i,s]=t,o=-1!==i?n>i:null,l=-1!==s?n>s:null;switch(r){case"first_factor":return o;case"second_factor":return -1!==s?l:o;case"multi_factor":return -1===s?o:o&&l}})(e,t);return[a||r,n].some(e=>null===e)?[a||r,n].some(e=>!0===e):[a||r,n].every(e=>!0===e)})(e)};#ed=e=>{e&&aB.set({tokenId:this.#eh(),tokenResolver:Promise.resolve(e)})};#eh(e,t){let a=void 0===t?this.lastActiveOrganizationId:t;return aq.build(this.id,e,a)}startVerification=async({level:e})=>new rq((await tH._fetch({method:"POST",path:`/client/sessions/${this.id}/verify`,body:{level:e}}))?.response);prepareFirstFactorVerification=async e=>{let t;switch(e.strategy){case"email_code":t={emailAddressId:e.emailAddressId};break;case"phone_code":t={phoneNumberId:e.phoneNumberId,default:e.default};break;case"passkey":t={};break;case"enterprise_sso":t={emailAddressId:e.emailAddressId,enterpriseConnectionId:e.enterpriseConnectionId,redirectUrl:e.redirectUrl};break;default:tq("Session.prepareFirstFactorVerification",e.strategy)}return new rq((await tH._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_first_factor`,body:{...t,strategy:e.strategy}}))?.response)};attemptFirstFactorVerification=async e=>{let t;return t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(a0(e.publicKeyCredential))}:{...e},new rq((await tH._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_first_factor`,body:{...t,strategy:e.strategy}}))?.response)};verifyWithPasskey=async()=>{let{nonce:e=null}=(await this.prepareFirstFactorVerification({strategy:"passkey"})).firstFactorVerification,t=rO.clerk.__internal_isWebAuthnSupported||rk,a=rO.clerk.__internal_getPublicCredentials||aY;if(!t())throw new q("Passkeys are not supported",{code:"passkey_not_supported"});let r=e?aX(JSON.parse(e)):null;r||tM("get");let{publicKeyCredential:n,error:i}=await a({publicKeyOptions:r,conditionalUI:!1});if(!n)throw i;return this.attemptFirstFactorVerification({strategy:"passkey",publicKeyCredential:n})};prepareSecondFactorVerification=async e=>new rq((await tH._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>new rq((await tH._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_second_factor`,body:e}))?.response);fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.expireAt=tV(e.expire_at),this.abandonAt=tV(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=tV(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.createdAt=tV(e.created_at),this.updatedAt=tV(e.updated_at),this.user=new rY(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new rS(e.public_user_data)),this.lastActiveToken=e.last_active_token?new rJ(e.last_active_token):null),this}__internal_toSnapshot(){return{object:"session",id:this.id,status:this.status,expire_at:this.expireAt.getTime(),abandon_at:this.abandonAt.getTime(),factor_verification_age:this.factorVerificationAge,last_active_at:this.lastActiveAt.getTime(),last_active_organization_id:this.lastActiveOrganizationId,actor:this.actor,tasks:this.tasks,user:this.user?.__internal_toSnapshot()||null,public_user_data:this.publicUserData.__internal_toSnapshot(),last_active_token:this.lastActiveToken?.__internal_toSnapshot()||null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}async _getToken(e){if(!this.user)return null;let{leewayInSeconds:t,template:a,skipCache:r=!1}=e||{},n=void 0===e?.organizationId?this.lastActiveOrganizationId:e?.organizationId;if(!a&&Number(t)>=60)throw Error("Leeway can not exceed the token lifespan (60 seconds)");let i=this.#eh(a,n),s=r?void 0:aB.get({tokenId:i},t),o=!a&&n===this.lastActiveOrganizationId;if(s){tn.debug("Using cached token (no fetch needed)",{tokenId:i},"session");let e=await s.tokenResolver;return o&&rn.emit(re,{token:e}),e.getRawString()||null}tn.info("Fetching new token from API",{organizationId:n,template:a,tokenId:i},"session");let l=a?`${this.path()}/tokens/${a}`:`${this.path()}/tokens`,c=a?{}:{organizationId:n},u=rJ.create(l,c,r);return aB.set({tokenId:i,tokenResolver:u}),u.then(e=>(o&&(rn.emit(re,{token:e}),e.jwt&&(this.lastActiveToken=e,rn.emit(rr,null))),e.getRawString()||null))}get currentTask(){let[e]=this.tasks??[];return e}}class rT extends tH{pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}static retrieve(){let e=tH.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new rT(e,"/me/sessions"))).catch(()=>[])}revoke(){return this._basePost({action:"revoke",body:{}})}fromJSON(e){let t;return e?(this.id=e.id,this.status=e.status,this.expireAt=tV(e.expire_at),this.abandonAt=tV(e.abandon_at),this.lastActiveAt=tV(e.last_active_at||void 0),this.latestActivity={id:(t=e.latest_activity??{}).id,deviceType:t.device_type,browserName:t.browser_name,browserVersion:t.browser_version,country:t.country,city:t.city,isMobile:t.is_mobile,ipAddress:t.ip_address},this.actor=e.actor,this):this}}let rU=(e,t,a)=>{let{onValidation:r=e8,onValidationComplexity:n=e8}=a||{},{show_zxcvbn:i,validatePassword:s}=t,o=e=>((e,t)=>{let{max_length:a,min_length:r,require_special_char:n,require_lowercase:i,require_numbers:s,require_uppercase:o}=t,l=(e=>{let t;if(e.allowed_special_characters){let a=e.allowed_special_characters.replace("[","\\[");a=a.replace("]","\\]"),t=RegExp(`[${a}]`)}else t=/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/;return(e,{minLength:a,maxLength:r})=>({max_length:e.length<r,min_length:e.length>=a,require_numbers:/\d/.test(e),require_lowercase:/[a-z]/.test(e),require_uppercase:/[A-Z]/.test(e),require_special_char:t.test(e)})})(t)(e,{maxLength:t.max_length,minLength:t.min_length}),c={max_length:a,min_length:r,require_special_char:n,require_lowercase:i,require_numbers:s,require_uppercase:o},u=new Map;for(let e in c)c[e]&&!l[e]&&u.set(e,!0);return Object.freeze(Object.fromEntries(u))})(e,t),l=(({min_zxcvbn_strength:e,onResult:t})=>a=>r=>{let n=a(r);return(t?.(n),n.score>=e&&n.score<3)?{state:"pass",keys:["unstable__errors.zxcvbn.couldBeStronger"],result:n}:n.score>=e?{state:"excellent",result:n}:{state:"fail",keys:["unstable__errors.zxcvbn.notEnough",...n.feedback.suggestions.map(e=>`unstable__errors.zxcvbn.suggestions.${e}`)],result:n}})(t),c={};return(t,a)=>{let{onValidation:u=r,onValidationComplexity:d=n}=a||{};if(!s)return;let h=o(t);d(0===Object.keys(h).length),c={...c,complexity:h},i&&e().then(e=>{let a=l(e)(t);u({...c={...c,strength:a},strength:a})}),c.complexity&&0===Object.keys(c.complexity).length&&i||u(c)}};function rM(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function rR(e,t,a,r,n){if(!e.client||!r.popup)return;let i=rM(e.frontendApi),{redirectUrl:s}=r,o=new URL(s);o.searchParams.set("sign_in_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("sign_up_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("intent",t);let l=e.buildUrlWithAuth(o.toString()),c=e.buildUrlWithAuth(`${i}/popup-callback`),u=e.buildUrlWithAuth(`${i}/popup-callback?return_url=${encodeURIComponent(l)}`),d=async t=>{if(t.origin!==i)return;let a=!1;if(t.data.session){if(!e.client?.sessions.find(e=>e.id===t.data.session))try{await e.client?.reload()}catch(e){console.error(e)}await e.setActive({session:t.data.session,redirectUrl:r.redirectUrlComplete}),a=!0}else t.data.return_url&&(e.navigate(t.data.return_url),a=!0);a&&window.removeEventListener("message",d)};window.addEventListener("message",d),await a({...r,redirectUrlComplete:c,redirectUrl:u},n)}function rB(e,{redirectCallbackUrl:t,redirectUrl:a}){let r=rM(e.frontendApi),n=new URL(t);n.searchParams.set("sign_in_force_redirect_url",a),n.searchParams.set("sign_up_force_redirect_url",a);let i=e.buildUrlWithAuth(n.toString()),s=e.buildUrlWithAuth(`${r}/popup-callback`);return{redirectCallbackUrl:e.buildUrlWithAuth(`${r}/popup-callback?return_url=${encodeURIComponent(i)}`),redirectUrl:s}}function rN(e,t){return new Promise((a,r)=>{if(!e.client||!t.popup)return void r();let n=async t=>{t.origin===rM(e.frontendApi)&&(t.data.session||t.data.return_url?(window.removeEventListener("message",n),a()):r())};window.addEventListener("message",n),t.popup.location.href=t.externalVerificationRedirectURL.toString()})}async function rD(e,t){rn.emit("resource:error",{resource:e,error:null}),rn.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await t(),error:null}}catch(t){return rn.emit("resource:error",{resource:e,error:t}),{error:t}}finally{rn.emit("resource:fetch",{resource:e,status:"idle"})}}let rF=()=>{var e;return(e=new tu,{loadZxcvbn:()=>Promise.all([e.import("@zxcvbn-ts/core"),e.import("@zxcvbn-ts/language-common")]).then(([e,t])=>{if(!e||!t)throw Error("Failed to load zxcvbn modules");let{zxcvbnOptions:a,zxcvbn:r}=e,{dictionary:n,adjacencyGraphs:i}=t;return a.setOptions({dictionary:{...n},graphs:i}),r})}).loadZxcvbn};class rL extends tH{pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;firstFactorVerification=new a9(null);secondFactorVerification=new a9(null);identifier=null;createdSessionId=null;userData=new rQ(null);clientTrustState;get status(){return this._status}set status(e){let t=this._status;this._status=e,e&&t!==e&&tn.debug("SignIn.status",{id:this.id,from:t,to:e})}__internal_future=new rW(this);__internal_basePost=this._basePost.bind(this);__internal_baseGet=this._baseGet.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=e=>{tn.debug("SignIn.create",{id:this.id,strategy:"strategy"in e?e.strategy:void 0});let t=ty();return this._basePost({path:this.pathRoot,body:t?{locale:t,...e}:e})};resetPassword=e=>this._basePost({body:e,action:"reset_password"});prepareFirstFactor=e=>{let t;switch(tn.debug("SignIn.prepareFirstFactor",{id:this.id,strategy:e.strategy}),e.strategy){case"passkey":t={};break;case"email_link":t={emailAddressId:e.emailAddressId,redirectUrl:e.redirectUrl};break;case"email_code":case"reset_password_email_code":t={emailAddressId:e.emailAddressId};break;case"phone_code":t={phoneNumberId:e.phoneNumberId,default:e.default,channel:e.channel};break;case"web3_metamask_signature":case"web3_base_signature":case"web3_coinbase_wallet_signature":case"web3_okx_wallet_signature":case"web3_solana_signature":t={web3WalletId:e.web3WalletId};break;case"reset_password_phone_code":t={phoneNumberId:e.phoneNumberId};break;case"enterprise_sso":t={redirectUrl:e.redirectUrl,actionCompleteRedirectUrl:e.actionCompleteRedirectUrl,oidcPrompt:e.oidcPrompt,enterpriseConnectionId:e.enterpriseConnectionId};break;default:tq("SignIn.prepareFirstFactor",e.strategy)}return this._basePost({body:{...t,strategy:e.strategy},action:"prepare_first_factor"})};attemptFirstFactor=e=>{let t;return tn.debug("SignIn.attemptFirstFactor",{id:this.id,strategy:e.strategy}),t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(a0(e.publicKeyCredential))}:{...e},this._basePost({body:{...t,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:t}=aV();return{startEmailLinkFlow:async({emailAddressId:a,redirectUrl:r})=>{this.id||tP("SignIn");let n={strategy:"email_link",emailAddressId:a,redirectUrl:r},i="needs_second_factor"===this.status||"needs_client_trust"===this.status,s=i?"secondFactorVerification":"firstFactorVerification";return i?await this.prepareSecondFactor(n):await this.prepareFirstFactor(n),new Promise((a,r)=>{e(()=>this.reload().then(e=>{let r=e[s].status;("verified"===r||"expired"===r)&&(t(),a(e))}).catch(e=>{t(),r(e)}))})},cancelEmailLinkFlow:t}};prepareSecondFactor=e=>(tn.debug("SignIn.prepareSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_second_factor"}));attemptSecondFactor=e=>(tn.debug("SignIn.attemptSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_second_factor"}));authenticateWithRedirectOrPopup=async(e,t)=>{let{strategy:a,redirectUrlComplete:r,identifier:n,oidcPrompt:i,continueSignIn:s,enterpriseConnectionId:o}=e||{},l=rL.clerk.buildUrlWithAuth(e.redirectUrl);this.id&&s||await this.create({strategy:a,identifier:n,redirectUrl:l,actionCompleteRedirectUrl:r}),"enterprise_sso"===a&&await this.prepareFirstFactor({strategy:a,redirectUrl:l,actionCompleteRedirectUrl:r,oidcPrompt:i,enterpriseConnectionId:o});let{status:c,externalVerificationRedirectURL:u}=this.firstFactorVerification;"unverified"===c&&u?t(u):tU(c,rL.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eV);authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||tT("popup"),rR(rL.clerk,"signIn",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e.toString()})};authenticateWithWeb3=async e=>{let t,{identifier:a,generateSignature:r,strategy:n="web3_metamask_signature",walletName:i}=e||{},s=n.replace("web3_","").replace("_signature","");"function"!=typeof r&&tT("generateSignature"),"solana"!==s||i||tT("walletName"),await this.create({identifier:a});let o=this.supportedFirstFactors?.find(e=>e.strategy===n);o||tO("SignIn"),await this.prepareFirstFactor(o);let{message:l}=this.firstFactorVerification;l||tO("SignIn");try{t=await r({identifier:a,nonce:l,walletName:i,provider:s})}catch(e){if("coinbase_wallet"===s&&4001===e.code)t=await r({identifier:a,nonce:l,provider:s,walletName:i});else throw e}return this.attemptFirstFactor({signature:t,strategy:n})};authenticateWithMetamask=async()=>{let e=await tj().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tj().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await tj().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tj().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await tj().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tj().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await tj().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tj().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithSolana=async({walletName:e})=>{let t=await tj().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:t,generateSignature:t=>tj().generateSignatureWithSolana({...t,walletName:e}),strategy:"web3_solana_signature",walletName:e})};authenticateWithPasskey=async e=>{let{flow:t}=e||{},a=rL.clerk.__internal_isWebAuthnSupported||rk,r=rL.clerk.__internal_getPublicCredentials||aY,n=rL.clerk.__internal_isWebAuthnAutofillSupported||rv;if(!a())throw new q("Passkeys are not supported",{code:"passkey_not_supported"});if("autofill"===t||"discoverable"===t)await this.create({strategy:"passkey"});else{let e=this.supportedFirstFactors.find(e=>"passkey"===e.strategy);e||function(){throw Error(`${tA} You need to start a SignIn flow by calling SignIn.create({ strategy: 'passkey' }) first`)}(),await this.prepareFirstFactor(e)}let{nonce:i}=this.firstFactorVerification,s=i?aX(JSON.parse(i)):null;s||tM("get");let o=!1;"autofill"===t&&(o=await n());let{publicKeyCredential:l,error:c}=await r({publicKeyOptions:s,conditionalUI:o});if(!l)throw c;return this.attemptFirstFactor({publicKeyCredential:l,strategy:"passkey"})};validatePassword=(e,t)=>{if(rL.clerk.__internal_environment?.userSettings.passwordSettings)return rU(rF(),{...rL.clerk.__internal_environment?.userSettings.passwordSettings,validatePassword:!0})(e,t)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.supportedIdentifiers=e.supported_identifiers,this.identifier=e.identifier,this.supportedFirstFactors=es(e.supported_first_factors),this.supportedSecondFactors=es(e.supported_second_factors),this.firstFactorVerification=new a9(e.first_factor_verification),this.secondFactorVerification=new a9(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new rQ(e.user_data),this.clientTrustState=e.client_trust_state??void 0),rn.emit("resource:update",{resource:this}),this}__internal_toSnapshot(){return{object:"sign_in",id:this.id||"",status:this.status||null,supported_identifiers:this.supportedIdentifiers,supported_first_factors:ei(this.supportedFirstFactors),supported_second_factors:ei(this.supportedSecondFactors),first_factor_verification:this.firstFactorVerification.__internal_toSnapshot(),second_factor_verification:this.secondFactorVerification.__internal_toSnapshot(),identifier:this.identifier,created_session_id:this.createdSessionId,user_data:this.userData.__internal_toSnapshot()}}}class rW{emailCode={sendCode:this.sendEmailCode.bind(this),verifyCode:this.verifyEmailCode.bind(this)};emailLink={sendLink:this.sendEmailLink.bind(this),waitForVerification:this.waitForEmailLinkVerification.bind(this),get verification(){if(!o())return null;let e=eM("__clerk_status"),t=eM("__clerk_created_session");if(!e||!t)return null;let a="verified"===e&&void 0!==rL.clerk.client&&rL.clerk.client.sessions.some(e=>e.id===t);return{status:e,createdSessionId:t,verifiedFromTheSameClient:a}}};resetPasswordEmailCode={sendCode:this.sendResetPasswordEmailCode.bind(this),verifyCode:this.verifyResetPasswordEmailCode.bind(this),submitPassword:this.submitResetPassword.bind(this)};phoneCode={sendCode:this.sendPhoneCode.bind(this),verifyCode:this.verifyPhoneCode.bind(this)};mfa={sendPhoneCode:this.sendMFAPhoneCode.bind(this),verifyPhoneCode:this.verifyMFAPhoneCode.bind(this),verifyTOTP:this.verifyTOTP.bind(this),verifyBackupCode:this.verifyBackupCode.bind(this)};#em=!1;#ep;constructor(e){this.#ep=e}get id(){return this.#ep.id}get identifier(){return this.#ep.identifier}get createdSessionId(){return this.#ep.createdSessionId}get userData(){return this.#ep.userData}get status(){return this.#ep.status||"needs_identifier"}get supportedFirstFactors(){return this.#ep.supportedFirstFactors??[]}get supportedSecondFactors(){return this.#ep.supportedSecondFactors??[]}get isTransferable(){return"transferable"===this.#ep.firstFactorVerification.status}get existingSession(){if("failed"===this.#ep.firstFactorVerification.status&&this.#ep.firstFactorVerification.error?.code==="identifier_already_signed_in"&&this.#ep.firstFactorVerification.error?.meta?.sessionId)return{sessionId:this.#ep.firstFactorVerification.error?.meta?.sessionId}}get firstFactorVerification(){return this.#ep.firstFactorVerification}get secondFactorVerification(){return this.#ep.secondFactorVerification}get hasBeenFinalized(){return this.#em}async sendResetPasswordEmailCode(){if(!this.#ep.id)throw Error("Cannot reset password without a sign in.");return rD(this.#ep,async()=>{let e=this.#ep.supportedFirstFactors?.find(e=>"reset_password_email_code"===e.strategy);if(!e)throw new C("Reset password email code factor not found",{code:"factor_not_found"});let{emailAddressId:t}=e;await this.#ep.__internal_basePost({body:{emailAddressId:t,strategy:"reset_password_email_code"},action:"prepare_first_factor"})})}async verifyResetPasswordEmailCode(e){let{code:t}=e;return rD(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:t,strategy:"reset_password_email_code"},action:"attempt_first_factor"})})}async submitResetPassword(e){let{password:t,signOutOfOtherSessions:a=!0}=e;return rD(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{password:t,signOutOfOtherSessions:a},action:"reset_password"})})}async _create(e){let t=ty();await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:t?{locale:t,...e}:e})}async create(e){return rD(this.#ep,async()=>{await this._create(e)})}async password(e){if([e.identifier,e.emailAddress,e.phoneNumber].filter(Boolean).length>1)throw Error("Only one of identifier, emailAddress, or phoneNumber can be provided");return rD(this.#ep,async()=>{let t=e.identifier||e.emailAddress||e.phoneNumber,a=this.#ep.identifier,r=ty();await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:{identifier:t||a,password:e.password,...r?{locale:r}:{}}})})}async sendEmailCode(e={}){let{emailAddress:t,emailAddressId:a}=e;if(!this.#ep.id&&a)throw Error("signIn.emailCode.sendCode() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#ep.id&&!t)throw Error("signIn.emailCode.sendCode() cannot be called without an emailAddress if an existing signIn does not exist.");return rD(this.#ep,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_code",emailAddressId:a});if(!e)throw new C("Email code factor not found",{code:"factor_not_found"});await this.#ep.__internal_basePost({body:{emailAddressId:e.emailAddressId,strategy:"email_code"},action:"prepare_first_factor"})})}async verifyEmailCode(e){let{code:t}=e;return rD(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:t,strategy:"email_code"},action:"attempt_first_factor"})})}async sendEmailLink(e){let{emailAddress:t,verificationUrl:a,emailAddressId:r}=e;if(!this.#ep.id&&r)throw Error("signIn.emailLink.sendLink() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#ep.id&&!t)throw Error("signIn.emailLink.sendLink() cannot be called without an emailAddress if an existing signIn does not exist.");return rD(this.#ep,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_link",emailAddressId:r});if(!e)throw new C("Email link factor not found",{code:"factor_not_found"});let n=a;try{new URL(a)}catch{n=window.location.origin+a}await this.#ep.__internal_basePost({body:{emailAddressId:e.emailAddressId,redirectUrl:n,strategy:"email_link"},action:"prepare_first_factor"})})}async waitForEmailLinkVerification(){return rD(this.#ep,async()=>{let{run:e,stop:t}=aV();await new Promise((a,r)=>{e(async()=>{try{let e=await this.#ep.__internal_baseGet(),r=e.firstFactorVerification.status;("verified"===r||"expired"===r)&&(t(),a(e))}catch(e){t(),r(e)}})})})}async sendPhoneCode(e={}){let{phoneNumber:t,phoneNumberId:a,channel:r="sms"}=e;if(!this.#ep.id&&a)throw Error("signIn.phoneCode.sendCode() cannot be called with an phoneNumberId if an existing signIn does not exist.");if(!this.#ep.id&&!t)throw Error("signIn.phoneCode.sendCode() cannot be called without an phoneNumber if an existing signIn does not exist.");return rD(this.#ep,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"phone_code",phoneNumberId:a});if(!e)throw new C("Phone code factor not found",{code:"factor_not_found"});await this.#ep.__internal_basePost({body:{phoneNumberId:e.phoneNumberId,strategy:"phone_code",channel:r},action:"prepare_first_factor"})})}async verifyPhoneCode(e){let{code:t}=e;return rD(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_first_factor"})})}async sso(e){let{strategy:t,redirectUrl:a,redirectCallbackUrl:r,popup:n,oidcPrompt:i,enterpriseConnectionId:s,identifier:o}=e;return rD(this.#ep,async()=>{let e=a;try{new URL(a)}catch{e=window.location.origin+a}let l={redirectUrl:rL.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:e};if(n){let t=rB(rL.clerk,{redirectCallbackUrl:l.redirectUrl,redirectUrl:e});l.redirectUrl=t.redirectCallbackUrl,l.actionCompleteRedirectUrl=t.redirectUrl}await this._create({strategy:t,...l,identifier:o}),"enterprise_sso"===t&&await this.#ep.__internal_basePost({body:{...l,oidcPrompt:i,enterpriseConnectionId:s,strategy:"enterprise_sso"},action:"prepare_first_factor"});let{status:c,externalVerificationRedirectURL:u}=this.#ep.firstFactorVerification;"unverified"===c&&u&&(n?(await rN(rL.clerk,{popup:n,externalVerificationRedirectURL:u}),await this.#ep.reload()):eV(u))})}async web3(e){let{strategy:t}=e,a=t.replace("web3_","").replace("_signature","");return rD(this.#ep,async()=>{let r,n,i;switch(a){case"metamask":r=await tj().getMetamaskIdentifier(),n=tj().generateSignatureWithMetamask;break;case"coinbase_wallet":r=await tj().getCoinbaseWalletIdentifier(),n=tj().generateSignatureWithCoinbaseWallet;break;case"base":r=await tj().getBaseIdentifier(),n=tj().generateSignatureWithBase;break;case"okx_wallet":r=await tj().getOKXWalletIdentifier(),n=tj().generateSignatureWithOKXWallet;break;case"solana":if(!e.walletName)throw new C("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});r=await tj().getSolanaIdentifier(e.walletName),n=t=>tj().generateSignatureWithSolana({...t,walletName:e.walletName});break;default:throw Error(`Unsupported Web3 provider: ${a}`)}await this._create({identifier:r});let s=this.#ep.supportedFirstFactors?.find(e=>e.strategy===t);if(!s)throw new C("Web3 first factor not found",{code:"factor_not_found"});await this.#ep.__internal_basePost({body:{web3WalletId:s.web3WalletId,strategy:t},action:"prepare_first_factor"});let{message:o}=this.firstFactorVerification;if(!o)throw new C("Web3 nonce not found",{code:"web3_nonce_not_found"});try{i=await n({identifier:r,nonce:o,walletName:e?.walletName,provider:a})}catch(e){if("coinbase_wallet"===a&&4001===e.code)i=await n({identifier:r,nonce:o,provider:a});else throw e}await this.#ep.__internal_basePost({body:{signature:i,strategy:t},action:"attempt_first_factor"})})}async passkey(e){let{flow:t}=e||{},a=rL.clerk.__internal_isWebAuthnSupported||rk,r=rL.clerk.__internal_getPublicCredentials||aY,n=rL.clerk.__internal_isWebAuthnAutofillSupported||rv;if(!a())throw new q("Passkeys are not supported",{code:"passkey_not_supported"});return rD(this.#ep,async()=>{if("autofill"===t||"discoverable"===t)await this._create({strategy:"passkey"});else{if(!this.supportedFirstFactors.find(e=>"passkey"===e.strategy))throw new C("Passkey factor not found",{code:"factor_not_found"});await this.#ep.__internal_basePost({body:{strategy:"passkey"},action:"prepare_first_factor"})}let{nonce:e}=this.firstFactorVerification,a=e?aX(JSON.parse(e)):null;if(!a)throw new C("Missing public key options",{code:"missing_public_key_options"});let i=!1;"autofill"===t&&(i=await n());let{publicKeyCredential:s,error:o}=await r({publicKeyOptions:a,conditionalUI:i});if(!s)throw new q(o.message,{code:"passkey_retrieval_failed"});await this.#ep.__internal_basePost({body:{publicKeyCredential:JSON.stringify(a0(s)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return rD(this.#ep,async()=>{let e=this.#ep.supportedSecondFactors?.find(e=>"phone_code"===e.strategy);if(!e)throw new C("Phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:t}=e;await this.#ep.__internal_basePost({body:{phoneNumberId:t,strategy:"phone_code"},action:"prepare_second_factor"})})}async verifyMFAPhoneCode(e){let{code:t}=e;return rD(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_second_factor"})})}async verifyTOTP(e){let{code:t}=e;return rD(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:t,strategy:"totp"},action:"attempt_second_factor"})})}async verifyBackupCode(e){let{code:t}=e;return rD(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:t,strategy:"backup_code"},action:"attempt_second_factor"})})}async ticket(e){let t=e?.ticket??eM("__clerk_ticket");return this.create({ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};if(!this.#ep.createdSessionId)throw Error("Cannot finalize sign-in without a created session.");return rD(this.#ep,async()=>{rL.clerk.client&&!rL.clerk.client.sessions.some(e=>e.id===this.#ep.createdSessionId)&&await rL.clerk.client.reload(),this.#em=!0,await rL.clerk.setActive({session:this.#ep.createdSessionId,navigate:t})})}selectFirstFactor({strategy:e,emailAddressId:t,phoneNumberId:a}){if(!this.#ep.supportedFirstFactors)return null;if(t){let a=this.#ep.supportedFirstFactors.find(a=>a.strategy===e&&a.emailAddressId===t);if(a)return a}if(a){let t=this.#ep.supportedFirstFactors.find(t=>t.strategy===e&&t.phoneNumberId===a);if(t)return t}let r=this.#ep.supportedFirstFactors.find(t=>t.strategy===e&&t.safeIdentifier===this.#ep.identifier);if(r)return r;let n=this.#ep.supportedFirstFactors.find(t=>t.strategy===e);return n||null}}function rK(e){let{unsafeMetadata:t}={...e},a=t?"object"==typeof t?JSON.stringify(t):t:"";return{...e,...t?{unsafeMetadata:a}:{}}}class rH extends tH{pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new a6(null);username=null;firstName=null;lastName=null;emailAddress=null;phoneNumber=null;web3wallet=null;externalAccount;hasPassword=!1;unsafeMetadata={};createdSessionId=null;createdUserId=null;abandonAt=null;legalAcceptedAt=null;locale=null;get status(){return this._status}set status(e){let t=this._status;this._status=e,e&&t!==e&&tn.debug("SignUp.status",{id:this.id,from:t,to:e})}__internal_future=new rV(this);__internal_basePost=this._basePost.bind(this);__internal_basePatch=this._basePatch.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{tn.debug("SignUp.create",{id:this.id,strategy:e.strategy});let t={...e};if(!t.locale){let e=ty();e&&(t.locale=e)}if(!this.clientBypass()&&!this.shouldBypassCaptchaForAttempt(e)){let e=new tW(rH.clerk),a=await e.managedOrInvisible({action:"signup"});if(!a)throw new C("",{code:"captcha_unavailable"});t={...t,...a}}if(t.transfer&&this.shouldBypassCaptchaForAttempt(t)){let e=rH.clerk.client?.signIn.firstFactorVerification.strategy;e&&(t={...t,strategy:e})}return this._basePost({path:this.pathRoot,body:rK(t)})};prepareVerification=e=>(tn.debug("SignUp.prepareVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_verification"}));attemptVerification=e=>(tn.debug("SignUp.attemptVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_verification"}));prepareEmailAddressVerification=e=>this.prepareVerification(e||{strategy:"email_code"});attemptEmailAddressVerification=e=>this.attemptVerification({...e,strategy:"email_code"});createEmailLinkFlow=()=>{let{run:e,stop:t}=aV();return{startEmailLinkFlow:async({redirectUrl:a})=>(this.id||tP("SignUp"),await this.prepareEmailAddressVerification({strategy:"email_link",redirectUrl:a}),new Promise((a,r)=>{e(()=>this.reload().then(e=>{let r=e.verifications.emailAddress.status;("verified"===r||"expired"===r)&&(t(),a(e))}).catch(e=>{t(),r(e)}))})),cancelEmailLinkFlow:t}};preparePhoneNumberVerification=e=>this.prepareVerification(e||{strategy:"phone_code"});attemptPhoneNumberVerification=e=>this.attemptVerification({...e,strategy:"phone_code"});prepareWeb3WalletVerification=e=>this.prepareVerification({strategy:"web3_metamask_signature",...e});attemptWeb3WalletVerification=async e=>{let{signature:t,strategy:a="web3_metamask_signature"}=e;return this.attemptVerification({signature:t,strategy:a})};authenticateWithWeb3=async e=>{let t,{generateSignature:a,identifier:r,unsafeMetadata:n,strategy:i="web3_metamask_signature",legalAccepted:s,walletName:o}=e||{},l=i.replace("web3_","").replace("_signature","");"function"!=typeof a&&tT("generateSignature");let c=r||this.web3wallet;await this.create({web3Wallet:c,unsafeMetadata:n,legalAccepted:s}),await this.prepareWeb3WalletVerification({strategy:i});let{message:u}=this.verifications.web3Wallet;u||tO("SignUp");try{t=await a({identifier:r,nonce:u,provider:l,walletName:o})}catch(e){if("coinbase_wallet"===l&&4001===e.code)t=await a({identifier:r,nonce:u,provider:l});else throw e}return this.attemptWeb3WalletVerification({signature:t,strategy:i})};authenticateWithMetamask=async e=>{let t=await tj().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tj().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let t=await tj().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tj().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let t=await tj().getBaseIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tj().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let t=await tj().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tj().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithSolana=async({walletName:e,unsafeMetadata:t,legalAccepted:a})=>{let r=await tj().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:r,generateSignature:t=>tj().generateSignatureWithSolana({...t,walletName:e}),unsafeMetadata:t,strategy:"web3_solana_signature",legalAccepted:a,walletName:e})};authenticateWithRedirectOrPopup=async(e,t)=>{let{redirectUrl:a,redirectUrlComplete:r,strategy:n,continueSignUp:i=!1,unsafeMetadata:s,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:u}=e,d=rH.clerk.buildUrlWithAuth(a),h=()=>{let e={strategy:n,redirectUrl:d,actionCompleteRedirectUrl:r,unsafeMetadata:s,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:u};return i&&this.id?this.update(e):this.create(e)},{verifications:m}=await h().catch(async e=>{if(M(e)&&O(e))return await rH.clerk.__internal_environment.reload(),h();throw e}),{externalAccount:p}=m,{status:f,externalVerificationRedirectURL:g}=p;"unverified"===f&&g?t(g):tU(f,rH.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eV);authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||tT("popup"),rR(rH.clerk,"signUp",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e instanceof URL?e.toString():e})};update=e=>this._basePatch({body:rK(e)});upsert=e=>this.id?this.update(e):this.create(e);validatePassword=(e,t)=>{if(rH.clerk.__internal_environment?.userSettings.passwordSettings)return rU(rF(),{...rH.clerk.__internal_environment?.userSettings.passwordSettings,validatePassword:!0})(e,t)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.requiredFields=e.required_fields,this.optionalFields=e.optional_fields,this.missingFields=e.missing_fields,this.unverifiedFields=e.unverified_fields,this.verifications=new a6(e.verifications),this.username=e.username,this.firstName=e.first_name,this.lastName=e.last_name,this.emailAddress=e.email_address,this.phoneNumber=e.phone_number,this.hasPassword=e.has_password,this.unsafeMetadata=e.unsafe_metadata,this.createdSessionId=e.created_session_id,this.createdUserId=e.created_user_id,this.abandonAt=e.abandon_at,this.web3wallet=e.web3_wallet,this.legalAcceptedAt=e.legal_accepted_at,this.locale=e.locale),rn.emit("resource:update",{resource:this}),this}__internal_toSnapshot(){return{object:"sign_up",id:this.id||"",status:this.status||null,required_fields:this.requiredFields,optional_fields:this.optionalFields,missing_fields:this.missingFields,unverified_fields:this.unverifiedFields,verifications:this.verifications.__internal_toSnapshot(),username:this.username,first_name:this.firstName,last_name:this.lastName,email_address:this.emailAddress,phone_number:this.phoneNumber,has_password:this.hasPassword,unsafe_metadata:this.unsafeMetadata,created_session_id:this.createdSessionId,created_user_id:this.createdUserId,abandon_at:this.abandonAt,web3_wallet:this.web3wallet,legal_accepted_at:this.legalAcceptedAt,locale:this.locale,external_account:this.externalAccount,external_account_strategy:this.externalAccount?.strategy}}clientBypass(){return rH.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){if(!e.strategy)return!1;let t=rH.clerk.__internal_environment.displayConfig.captchaOauthBypass;return!!(t.some(t=>t===e.strategy)||e.transfer&&t.some(e=>e===rH.clerk.client.signIn.firstFactorVerification.strategy))}__experimental_getEnterpriseConnections=()=>tH._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new rG(e)))}class rV{verifications={sendEmailCode:this.sendEmailCode.bind(this),verifyEmailCode:this.verifyEmailCode.bind(this),sendPhoneCode:this.sendPhoneCode.bind(this),verifyPhoneCode:this.verifyPhoneCode.bind(this)};#em=!1;#ep;constructor(e){this.#ep=e}get id(){return this.#ep.id}get requiredFields(){return this.#ep.requiredFields}get optionalFields(){return this.#ep.optionalFields}get missingFields(){return this.#ep.missingFields}get status(){return this.#ep.status||"missing_requirements"}get username(){return this.#ep.username}get firstName(){return this.#ep.firstName}get lastName(){return this.#ep.lastName}get emailAddress(){return this.#ep.emailAddress}get phoneNumber(){return this.#ep.phoneNumber}get web3Wallet(){return this.#ep.web3wallet}get hasPassword(){return this.#ep.hasPassword}get unsafeMetadata(){return this.#ep.unsafeMetadata}get createdSessionId(){return this.#ep.createdSessionId}get createdUserId(){return this.#ep.createdUserId}get abandonAt(){return this.#ep.abandonAt}get legalAcceptedAt(){return this.#ep.legalAcceptedAt}get locale(){return this.#ep.locale}get unverifiedFields(){return this.#ep.unverifiedFields}get isTransferable(){return"transferable"===this.#ep.verifications.externalAccount.status&&this.#ep.verifications.externalAccount.error?.code==="external_account_exists"}get existingSession(){if(("failed"===this.#ep.verifications.externalAccount.status||"unverified"===this.#ep.verifications.externalAccount.status)&&this.#ep.verifications.externalAccount.error?.code==="identifier_already_signed_in"&&this.#ep.verifications.externalAccount.error?.meta?.sessionId)return{sessionId:this.#ep.verifications.externalAccount.error?.meta?.sessionId}}get hasBeenFinalized(){return this.#em}async getCaptchaToken(){let e=new tW(rH.clerk),t=await e.managedOrInvisible({action:"signup"});if(!t)throw Error("Captcha challenge failed");let{captchaError:a,captchaToken:r,captchaWidgetType:n}=t;return{captchaToken:r,captchaWidgetType:n,captchaError:a}}async _create(e){let{captchaToken:t,captchaWidgetType:a,captchaError:r}=await this.getCaptchaToken(),n={transfer:e.transfer,captchaToken:t,captchaWidgetType:a,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rK(e.unsafeMetadata):void 0,locale:e.locale??ty()};await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:n})}async create(e){return rD(this.#ep,async()=>{await this._create(e)})}async update(e){return rD(this.#ep,async()=>{let t={...e,unsafeMetadata:e.unsafeMetadata?rK(e.unsafeMetadata):void 0};await this.#ep.__internal_basePatch({path:this.#ep.pathRoot,body:t})})}async password(e){return rD(this.#ep,async()=>{let{captchaToken:t,captchaWidgetType:a,captchaError:r}=await this.getCaptchaToken(),n={strategy:"password",captchaToken:t,captchaWidgetType:a,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rK(e.unsafeMetadata):void 0};await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:n})})}async sendEmailCode(){return rD(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification"})})}async verifyEmailCode(e){let{code:t}=e;return rD(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{strategy:"email_code",code:t},action:"attempt_verification"})})}async sendPhoneCode(e){let{phoneNumber:t,channel:a="sms"}=e;return rD(this.#ep,async()=>{if(!this.#ep.id){let{captchaToken:e,captchaWidgetType:a,captchaError:r}=await this.getCaptchaToken();await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:{phoneNumber:t,captchaToken:e,captchaWidgetType:a,captchaError:r}})}await this.#ep.__internal_basePost({body:{strategy:"phone_code",channel:a},action:"prepare_verification"})})}async verifyPhoneCode(e){let{code:t}=e;return rD(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{strategy:"phone_code",code:t},action:"attempt_verification"})})}async sso(e){let{strategy:t,redirectUrl:a,redirectCallbackUrl:r,unsafeMetadata:n,legalAccepted:i,oidcPrompt:s,enterpriseConnectionId:o,emailAddress:l,popup:c}=e;return rD(this.#ep,async()=>{let{captchaToken:e,captchaWidgetType:u,captchaError:d}=await this.getCaptchaToken(),h=a;try{new URL(a)}catch{h=window.location.origin+a}let m={redirectUrl:rH.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:h};if(c){let e=rB(rH.clerk,{redirectCallbackUrl:m.redirectUrl,redirectUrl:h});m.redirectUrl=e.redirectCallbackUrl,m.actionCompleteRedirectUrl=e.redirectUrl}let p=()=>this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:{strategy:t,...m,unsafeMetadata:n,legalAccepted:i,oidcPrompt:s,enterpriseConnectionId:o,emailAddress:l,captchaToken:e,captchaWidgetType:u,captchaError:d}});await p().catch(async e=>{if(M(e)&&O(e))return await rH.clerk.__internal_environment.reload(),p();throw e});let{status:f,externalVerificationRedirectURL:g}=this.#ep.verifications.externalAccount;"unverified"===f&&g&&(c?(await rN(rH.clerk,{popup:c,externalVerificationRedirectURL:g}),await this.#ep.reload()):eV(g))})}async web3(e){let{strategy:t,unsafeMetadata:a,legalAccepted:r}=e,n=t.replace("web3_","").replace("_signature","");return rD(this.#ep,async()=>{let e,i,s;switch(n){case"metamask":e=await tj().getMetamaskIdentifier(),i=tj().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await tj().getCoinbaseWalletIdentifier(),i=tj().generateSignatureWithCoinbaseWallet;break;case"base":e=await tj().getBaseIdentifier(),i=tj().generateSignatureWithBase;break;case"okx_wallet":e=await tj().getOKXWalletIdentifier(),i=tj().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${n}`)}let o=e||this.#ep.web3wallet;await this._create({web3Wallet:o,unsafeMetadata:a,legalAccepted:r}),await this.#ep.__internal_basePost({body:{strategy:t},action:"prepare_verification"});let{message:l}=this.#ep.verifications.web3Wallet;l||tO("SignUp");try{s=await i({identifier:e,nonce:l})}catch(t){if("coinbase_wallet"===n&&4001===t.code)s=await i({identifier:e,nonce:l});else throw t}await this.#ep.__internal_basePost({body:{signature:s,strategy:t},action:"attempt_verification"})})}async ticket(e){let t=e?.ticket??eM("__clerk_ticket");return this.create({...e,ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};return rD(this.#ep,async()=>{if(!this.#ep.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#em=!0,await rH.clerk.setActive({session:this.#ep.createdSessionId,navigate:t})})}}class rG extends tH{id;name;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name),this}}class rJ extends tH{pathRoot="tokens";jwt;static async create(e,t={},a=!1){return new rJ(await tH._fetch({body:t,method:"POST",path:e,search:a?"debug=skip_cache":void 0}),e)}constructor(e,t){super(),t&&(this.pathRoot=t),e?.jwt&&(this.jwt=tb(e.jwt))}getRawString=()=>this.jwt?.claims.__raw||"";fromJSON(e){return e&&(this.jwt=tb(e.jwt)),this}__internal_toSnapshot(){return{object:"token",id:this.id||"",jwt:this.getRawString()}}}class rZ extends tH{pathRoot="/me";id="";secret;uri;verified=!1;backupCodes;updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.secret=e.secret,this.uri=e.uri,this.verified=e.verified,this.backupCodes=e.backup_codes,this.updatedAt=tV(e.updated_at),this.createdAt=tV(e.created_at)),this}}class r$ extends tH{pathRoot="/me";id;codes=[];updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.codes=e.codes,this.updatedAt=tV(e.updated_at),this.createdAt=tV(e.created_at)),this}}class rY extends tH{pathRoot="/me";id="";externalId=null;username=null;emailAddresses=[];phoneNumbers=[];web3Wallets=[];externalAccounts=[];enterpriseAccounts=[];passkeys=[];organizationMemberships=[];passwordEnabled=!1;firstName=null;lastName=null;fullName=null;primaryEmailAddressId=null;primaryEmailAddress=null;primaryPhoneNumberId=null;primaryPhoneNumber=null;primaryWeb3WalletId=null;primaryWeb3Wallet=null;imageUrl="";hasImage=!1;twoFactorEnabled=!1;totpEnabled=!1;backupCodeEnabled=!1;publicMetadata={};unsafeMetadata={};createOrganizationEnabled=!1;createOrganizationsLimit=null;deleteSelfEnabled=!1;lastSignInAt=null;legalAcceptedAt=null;updatedAt=null;createdAt=null;cachedSessionsWithActivities=null;static isUserResource(e){return!!e&&e instanceof rY}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case aG:return this.primaryEmailAddressId===e.id;case r_:return this.primaryPhoneNumberId===e.id;case r2:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:t}=e||{};return new aG({email_address:t},this.path()+"/email_addresses/").create()};createPasskey=()=>rj.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:t}=e||{};return new r_({phone_number:t},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:t}=e||{};return new r2({web3_wallet:t},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:t,redirectUrl:a,additionalScopes:r}=e||{};return new rl((await tH._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:t,redirect_url:a,additional_scope:r}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new rZ((await tH._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new rZ((await tH._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new aF((await tH._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new r$((await tH._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);update=e=>this._basePatch({body:rK(e)});updatePassword=e=>this._basePost({body:e,path:`${this.path()}/change_password`});removePassword=e=>this._basePost({body:e,path:`${this.path()}/remove_password`});delete=()=>this._baseDelete({path:"/me"}).then(e=>(rn.emit(rt,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await rT.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:t}=e||{};return null===t?rd.delete(`${this.path()}/profile_image`):rd.create(`${this.path()}/profile_image`,{file:t})};getOrganizationInvitations=e=>rX.retrieve(e);getOrganizationSuggestions=e=>rw.retrieve(e);getOrganizationMemberships=e=>ry.retrieve(e);leaveOrganization=async e=>new aF((await tH._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);initializePaymentMethod=e=>ax(e);addPaymentMethod=e=>aj(e);getPaymentMethods=e=>a_(e);get verifiedExternalAccounts(){return this.externalAccounts.filter(e=>e.verification?.status=="verified")}get unverifiedExternalAccounts(){return this.externalAccounts.filter(e=>e.verification?.status!="verified")}get verifiedWeb3Wallets(){return this.web3Wallets.filter(e=>e.verification?.status=="verified")}get hasVerifiedEmailAddress(){return this.emailAddresses.filter(e=>"verified"===e.verification.status).length>0}get hasVerifiedPhoneNumber(){return this.phoneNumbers.filter(e=>"verified"===e.verification.status).length>0}fromJSON(e){return e&&(this.id=e.id,this.externalId=e.external_id||null,this.firstName=e.first_name||null,this.lastName=e.last_name||null,(this.firstName||this.lastName)&&(this.fullName=(({firstName:e,lastName:t,name:a})=>a||[e,t].join(" ").trim()||"")({firstName:this.firstName,lastName:this.lastName})),this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.username=e.username||null,this.passwordEnabled=e.password_enabled||!1,this.emailAddresses=(e.email_addresses||[]).map(e=>new aG(e,this.path()+"/email_addresses")),this.primaryEmailAddressId=e.primary_email_address_id||null,this.primaryEmailAddress=this.emailAddresses.find(({id:e})=>e===this.primaryEmailAddressId)||null,this.phoneNumbers=(e.phone_numbers||[]).map(e=>new r_(e,this.path()+"/phone_numbers")),this.primaryPhoneNumberId=e.primary_phone_number_id||null,this.primaryPhoneNumber=this.phoneNumbers.find(({id:e})=>e===this.primaryPhoneNumberId)||null,this.web3Wallets=(e.web3_wallets||[]).map(e=>new r2(e,this.path()+"/web3_wallets")),this.primaryWeb3WalletId=e.primary_web3_wallet_id||null,this.primaryWeb3Wallet=this.web3Wallets.find(({id:e})=>e===this.primaryWeb3WalletId)||null,this.externalAccounts=(e.external_accounts||[]).map(e=>new rl(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new rj(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new ry(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new a4(e,this.path()+"/enterprise_accounts")),this.publicMetadata=e.public_metadata||{},this.unsafeMetadata=e.unsafe_metadata||{},this.totpEnabled=e.totp_enabled||!1,this.backupCodeEnabled=e.backup_code_enabled||!1,this.twoFactorEnabled=e.two_factor_enabled||!1,this.createOrganizationEnabled=e.create_organization_enabled||!1,this.createOrganizationsLimit=e.create_organizations_limit||null,this.deleteSelfEnabled=e.delete_self_enabled||!1,e.last_sign_in_at&&(this.lastSignInAt=tV(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=tV(e.legal_accepted_at)),this.updatedAt=tV(e.updated_at||void 0),this.createdAt=tV(e.created_at||void 0)),this}__internal_toSnapshot(){return{object:"user",id:this.id,external_id:this.externalId,first_name:this.firstName,last_name:this.lastName,username:this.username,public_metadata:this.publicMetadata,unsafe_metadata:this.unsafeMetadata,image_url:this.imageUrl,has_image:this.hasImage,email_addresses:this.emailAddresses.map(e=>e.__internal_toSnapshot()),phone_numbers:this.phoneNumbers.map(e=>e.__internal_toSnapshot()),web3_wallets:this.web3Wallets.map(e=>e.__internal_toSnapshot()),external_accounts:this.externalAccounts.map(e=>e.__internal_toSnapshot()),passkeys:this.passkeys.map(e=>e.__internal_toSnapshot()),organization_memberships:this.organizationMemberships.map(e=>e.__internal_toSnapshot()),enterprise_accounts:this.enterpriseAccounts.map(e=>e.__internal_toSnapshot()),totp_enabled:this.totpEnabled,backup_code_enabled:this.backupCodeEnabled,two_factor_enabled:this.twoFactorEnabled,create_organization_enabled:this.createOrganizationEnabled,create_organizations_limit:this.createOrganizationsLimit,delete_self_enabled:this.deleteSelfEnabled,primary_email_address_id:this.primaryEmailAddressId,primary_phone_number_id:this.primaryPhoneNumberId,primary_web3_wallet_id:this.primaryWeb3WalletId,password_enabled:this.passwordEnabled,profile_image_id:this.imageUrl,last_sign_in_at:this.lastSignInAt?.getTime()||null,legal_accepted_at:this.legalAcceptedAt?.getTime()||null,updated_at:this.updatedAt?.getTime()||null,created_at:this.createdAt?.getTime()||null}}}class rQ{firstName;lastName;imageUrl;hasImage;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.firstName=e.first_name,this.lastName=e.last_name,this.imageUrl=e.image_url??void 0,this.hasImage=e.has_image??void 0),this}__internal_toSnapshot(){return{first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl||null,has_image:this.hasImage||null}}}class rX extends tH{id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await tH._fetch({path:"/me/organization_invitations",method:"GET",search:as(e)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rX(e))}})}constructor(e){super(),this.fromJSON(e)}accept=async()=>await this._basePost({path:`/me/organization_invitations/${this.id}/accept`});fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.publicOrganizationData={hasImage:e.public_organization_data.has_image,imageUrl:e.public_organization_data.image_url,name:e.public_organization_data.name,id:e.public_organization_data.id,slug:e.public_organization_data.slug},this.publicMetadata=e.public_metadata,this.role=e.role,this.status=e.status,this.createdAt=tV(e.created_at),this.updatedAt=tV(e.updated_at)),this}}let r1={enabled:!1,first_factors:[],name:"phone_number",required:!1,second_factors:[],used_for_first_factor:!1,used_for_second_factor:!1,verifications:[],verify_at_sign_up:!1};class r0 extends tH{id=void 0;actions={create_organization:!1,delete_self:!1};attributes={email_address:{enabled:!0,first_factors:["email_code"],name:"email_address",required:!0,second_factors:[],used_for_first_factor:!0,used_for_second_factor:!1,verifications:["email_code"],verify_at_sign_up:!0},phone_number:{...r1,name:"phone_number"},username:{...r1,name:"username"},web3_wallet:{...r1,name:"web3_wallet"},first_name:{...r1,name:"first_name"},last_name:{...r1,name:"last_name"},password:{enabled:!0,first_factors:[],name:"password",required:!0,second_factors:[],used_for_first_factor:!1,used_for_second_factor:!1,verifications:[],verify_at_sign_up:!1},authenticator_app:{...r1,name:"authenticator_app"},backup_code:{...r1,name:"backup_code"},passkey:{...r1,name:"passkey"}};enterpriseSSO={enabled:!1};passkeySettings={allow_autofill:!1,show_sign_in_button:!1};passwordSettings={};signIn={second_factor:{required:!1,enabled:!1}};signUp={allowlist_only:!1,captcha_enabled:!1,legal_consent_enabled:!1,mode:"public",progressive:!0};social={};usernameSettings={};get authenticatableSocialStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled&&e.authenticatable).map(([,e])=>e.strategy).sort():[]}get enabledFirstFactorIdentifiers(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&!e.startsWith("web3")).map(([e])=>e):[]}get socialProviderStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled).map(([,e])=>e.strategy).sort():[]}get web3FirstFactors(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&e.startsWith("web3")).map(([,e])=>e.first_factors).flat():[]}get alternativePhoneCodeChannels(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&"phone_number"===e).map(([,e])=>e?.channels?.filter(e=>"sms"!==e)||[]).flat():[]}constructor(e=null){super(),this.fromJSON(e)}get instanceIsPasswordBased(){return!!(this.attributes?.password?.enabled&&this.attributes.password?.required)}get hasValidAuthFactor(){return!!(this.attributes?.email_address?.enabled||this.attributes?.phone_number?.enabled||this.attributes.password?.required&&this.attributes.username?.required)}fromJSON(e){return e&&(this.attributes=this.withDefault(e.attributes?Object.fromEntries(Object.entries(e.attributes).map(e=>[e[0],{...e[1],name:e[0]}])):null,this.attributes),this.actions=this.withDefault(e.actions,this.actions),this.enterpriseSSO=this.withDefault(e.enterprise_sso,this.enterpriseSSO),this.passkeySettings=this.withDefault(e.passkey_settings,this.passkeySettings),this.passwordSettings=e.password_settings?{...e.password_settings,min_length:Math.max(e.password_settings?.min_length??8,8),max_length:e.password_settings?.max_length===0?72:Math.min(e.password_settings?.max_length??72,72)}:this.passwordSettings,this.signIn=this.withDefault(e.sign_in,this.signIn),this.signUp=this.withDefault(e.sign_up,this.signUp),this.social=this.withDefault(e.social,this.social),this.usernameSettings=e.username_settings?{...e.username_settings,min_length:Math.max(e.username_settings?.min_length??4,4),max_length:Math.min(e.username_settings?.max_length??64,64)}:this.usernameSettings),this}__internal_toSnapshot(){return{actions:this.actions,attributes:this.attributes,passkey_settings:this.passkeySettings,password_settings:this.passwordSettings,sign_in:this.signIn,sign_up:this.signUp,social:this.social}}}class r2 extends tH{id;web3Wallet="";verification;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}create(){return this._basePost({body:{web3_wallet:this.web3Wallet}})}prepareVerification=e=>this._basePost({action:"prepare_verification",body:{...e}});attemptVerification=e=>{let{signature:t}=e;return this._basePost({action:"attempt_verification",body:{signature:t}})};destroy(){return this._baseDelete()}toString(){return this.web3Wallet}fromJSON(e){return e&&(this.id=e.id,this.web3Wallet=e.web3_wallet,this.verification=new a9(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}class r3 extends tH{pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=tV(e.updated_at),this.createdAt=tV(e.created_at)),this}static async join(e){return new r3((await tH._fetch({path:"/waitlist",method:"POST",body:e}))?.response)}}function r9(e,t){var a,r;return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||(a=t,r=e,a.organizationMemberships.length!==r.organizationMemberships.length||a.organizationMemberships[0]?.updatedAt!==r.organizationMemberships[0]?.updatedAt)}function r5(e,t){return!function(e,t){if(!e&&t||e&&!t)return!0;if(!e&&e===t)return!1;if(!e||!t)return!0;try{if(aN.isClientResource(e))return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.sessions.length!==t.sessions.length;if(rO.isSessionResource(e)){var a,r;return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.lastActiveToken?.jwt?.claims?.__raw!==t.lastActiveToken?.jwt?.claims?.__raw||function(e,t){if(e.lastActiveOrganizationId!==t.lastActiveOrganizationId)return!0;let a=e.user?.organizationMemberships?.find(t=>t.organization.id===e.lastActiveOrganizationId),r=t.user?.organizationMemberships?.find(t=>t.organization.id===e.lastActiveOrganizationId);return a?.permissions?.length!==r?.permissions?.length}(e,t)||(a=e,r=t,!!a.user!=!!r.user||!!a.user&&!!r.user&&r9(a.user,r.user))}if(rY.isUserResource(e))return r9(e,t)}catch{}return!0}(e,t)?e:t}let r6="__clerk_db_jwt";function r8(e,t){let a=new URL(e),r=a.searchParams.get(r6);a.searchParams.delete(r6);let n=r||t;return n&&a.searchParams.set(r6,n),a}let r4=e=>{let t=new URL(e);return t.searchParams.delete(r6),t},r7=e=>{let t=new URL(e);return t.searchParams.delete("__dev_session"),t.hash=decodeURI(t.hash).replace(/__clerk_db_jwt\[(.*)\]/,""),t.href.endsWith("#")&&(t.hash=""),t};function ne(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var r in a)e[r]=a[r]}return e}var nt=function e(t,a){function r(e,r,n){if("undefined"!=typeof document){"number"==typeof(n=ne({},a,n)).expires&&(n.expires=new Date(Date.now()+864e5*n.expires)),n.expires&&(n.expires=n.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var i="";for(var s in n)n[s]&&(i+="; "+s,!0!==n[s]&&(i+="="+n[s].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+i}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var a=document.cookie?document.cookie.split("; "):[],r={},n=0;n<a.length;n++){var i=a[n].split("="),s=i.slice(1).join("=");try{var o=decodeURIComponent(i[0]);if(r[o]=t.read(s,o),e===o)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",ne({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,ne({},this.attributes,t))},withConverter:function(t){return e(ne({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(a)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});function na(e){return{get:()=>nt.get(e),set(t,a={}){nt.set(e,t,a)},remove(t){nt.remove(e,t)}}}let nr=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function nn(e,t){let a=function(e){try{return new Date(e||new Date)}catch{return new Date}}(e);return a.setFullYear(a.getFullYear()+t),a}let ni=na("__clerk_test_etld"),ns="__client_uat",no="__session",nl=()=>{let e=tk()?"None":"Lax",t=nr(e);return{sameSite:e,secure:t,partitioned:!1}};async function nc(e){let t;try{t=await eb(e)}catch(o){var a;a=`Suffixed cookie failed due to ${o.message} (secure-context: ${window.isSecureContext}, url: ${window.location.href})`,Q.has(a)||(console.log(a),Q.add(a));let{default:r}=await Promise.resolve().then(n.t.bind(n,180,23)),{default:i}=await Promise.resolve().then(n.t.bind(n,3413,23)),s=r(e);t=i.stringify(s).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}return t}let nu=()=>{let e=tk()?"None":"Lax",t=nr(e);return{sameSite:e,secure:t}};var nd=n(5945),nh=n.n(nd);class nm{lock=(w="clerk.lock.refreshSessionToken",s=new(nh()),window.addEventListener("beforeunload",async()=>{await s.releaseLock(w)}),{acquireLockAndRun:async e=>{if("locks"in navigator&&isSecureContext){let t=new AbortController,a=setTimeout(()=>t.abort(),4999);return await navigator.locks.request(w,{signal:t.signal},async()=>(clearTimeout(a),await e())).catch(()=>!1)}if(await s.acquireLock(w,5e3))try{return await e()}finally{await s.releaseLock(w)}}});workerTimers=aH();timerId=null;initiated=!1;startPollingForSessionToken(e){if(this.timerId||this.initiated)return;let t=async()=>{this.initiated=!0,await this.lock.acquireLockAndRun(e),this.timerId=this.workerTimers.setTimeout(t,5e3)};t()}stopPollingForSessionToken(){null!=this.timerId&&(this.workerTimers.clearTimeout(this.timerId),this.timerId=null),this.initiated=!1}}class np{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,t,a,r){let n=await nc(e.publishableKey),i=new np(e,t,n,a,r);return await i.setup(),i}constructor(e,t,r,n,i){let s,o,l,c,u,d,h;this.clerk=e,this.instanceType=n,this.clerkEventBus=i,rn.on(re,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),rn.on(rt,()=>this.handleSignOut()),this.refreshTokenOnFocus(),this.startPollingForToken(),this.clientUat=(s=na(ns),o=na(ey(ns,r)),{set:e=>{let t=nn(Date.now(),1),r=tk()?"None":"Strict",n=nr(r),i=function(e=window.location.hostname,t=ni){if(a)return a;if(["localhost","127.0.0.1","0.0.0.0"].includes(e))return e;let r=e.split(".");if(1===r.length)return e;for(let e=r.length-2;e>=0;e--){let n=r.slice(e).join(".");if(t.set("1",{domain:n}),"1"===t.get())return t.remove({domain:n}),a=n,n;t.remove({domain:n})}}(),l="0";e&&e.updatedAt&&e.signedInSessions.length>0&&(l=Math.floor(e.updatedAt.getTime()/1e3).toString()),o.remove(),s.remove(),o.set(l,{domain:i,expires:t,partitioned:!1,sameSite:r,secure:n}),s.set(l,{domain:i,expires:t,partitioned:!1,sameSite:r,secure:n})},get:()=>parseInt(o.get()||s.get()||"0",10)}),this.sessionCookie=(l=na(no),c=na(ey(no,r)),{set:e=>{let t=nn(Date.now(),1),{sameSite:a,secure:r,partitioned:n}=nl();n&&u(),l.set(e,{expires:t,sameSite:a,secure:r,partitioned:n}),c.set(e,{expires:t,sameSite:a,secure:r,partitioned:n})},remove:u=()=>{let e=nl();l.remove(e),c.remove(e)},get:()=>c.get()||l.get()}),this.activeCookie=(d=na("clerk_active_context"),h={secure:nr("None")},{set:e=>{d.set(e,h)},get:()=>d.get(),remove:()=>d.remove(h)}),this.devBrowser=function({cookieSuffix:e,frontendApi:t,fapiClient:a}){let r,n,i=(r=na(r6),n=na(ey(r6,e)),{get:()=>n.get()||r.get(),set:e=>{let t=nn(Date.now(),1),{sameSite:a,secure:i}=nu();n.set(e,{expires:t,sameSite:a,secure:i}),r.set(e,{expires:t,sameSite:a,secure:i})},remove:()=>{let e=nu();n.remove(e),r.remove(e)}});function s(){return i.get()}function o(e){i.set(e)}function l(){i.remove()}return{clear:function(){l()},setup:async function(){var e;let r;if(!ej(t))return;a.onBeforeRequest(e=>{let t=s();t&&e?.url&&(e.url=r8(e.url,t))}),a.onAfterResponse((e,t)=>{let a=t?.headers?.get("Clerk-Db-Jwt");a&&o(a)});let n=(r=(e=new URL(window.location.href)).searchParams.get(r6)||"",r4(r7(e)).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",r4(r7(e))),r);if(n)return void o(n);if(i.get())return;let l=a.buildUrl({path:"/dev_browser"}),c=await fetch(l.toString(),{method:"POST"});if(!c.ok){let e=function(e=[]){return e.length>0?e.map(e=>new v(e)):[]}((await c.json()).errors);e[0]?tI(e[0].longMessage):tI()}let u=await c.json();o(u?.id)},getDevBrowserJWT:s,setDevBrowserJWT:o,removeDevBrowserJWT:l}}({frontendApi:e.frontendApi,fapiClient:t,cookieSuffix:r})}async setup(){return"production"===this.instanceType?this.setupProduction():this.setupDevelopment()}isSignedOut(){return this.clerk.loaded?!!this.clerk.user:0>=this.clientUat.get()}async handleUnauthenticatedDevBrowser(){this.devBrowser.clear(),await this.devBrowser.setup()}decorateUrlWithDevBrowserToken(e){let t=this.devBrowser.getDevBrowserJWT();if(!t)throw Error(`${tA} Missing dev browser jwt. Please contact support.`);return r8(e,t)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new nm,this.poller.startPollingForSessionToken(()=>this.refreshSessionToken()))}stopPollingForToken(){this.poller&&(this.poller.stopPollingForSessionToken(),this.poller=null)}refreshTokenOnFocus(){window.addEventListener("focus",()=>{"visible"===document.visibilityState&&this.refreshSessionToken({updateCookieImmediately:!0})})}async refreshSessionToken({updateCookieImmediately:e=!1}={}){if(this.clerk.session)try{let t=await this.clerk.session.getToken();e&&this.updateSessionCookie(t)}catch(e){return this.handleGetTokenError(e)}}updateSessionCookie(e){if(document.hasFocus()||this.isCurrentContextActive())return e||d()||tn.warn("Removing session cookie (offline)",{sessionId:this.clerk.session?.id},"authCookieService"),this.setActiveContextInStorage(),e?this.sessionCookie.set(e):this.sessionCookie.remove()}setClientUatCookieForDevelopmentInstances(){"production"!==this.instanceType&&this.inCustomDevelopmentDomain()&&this.clientUat.set(this.clerk.client)}inCustomDevelopmentDomain(){let e=this.clerk.frontendApi.replace("clerk.","");return!window.location.host.endsWith(e)}handleGetTokenError(e){if(M(e)||R(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(T(e))return void this.clerk.handleUnauthenticated().catch(e8);this.clerkEventBus.emit(g,"degraded")}}handleSignOut(){this.activeCookie.remove(),this.sessionCookie.remove(),this.setClientUatCookieForDevelopmentInstances()}setActiveContextInStorage(){let e=this.clerk.session?.id||"",t=this.clerk.organization?.id||"",a=`${e}:${t}`;":"!==a?this.activeCookie.set(a):this.activeCookie.remove()}isCurrentContextActive(){let e=this.activeCookie.get();if(!e)return!0;let[t,a]=e.split(":"),r=this.clerk.session?.id||"",n=this.clerk.organization?.id||"";return t===r&&a===n}getSessionCookie(){return this.sessionCookie.get()}}class nf{clerk;captchaChallenge;timers;constructor(e,t=new tW(e),a=aH()){this.clerk=e,this.captchaChallenge=t,this.timers=a}async start(){this.isEnabled()&&(await this.challengeAndSend(),this.timers.setInterval(()=>{this.challengeAndSend()},this.intervalInMs()))}async challengeAndSend(){if(!(!this.clerk.client||this.clientBypass()))try{let e=await this.captchaChallenge.invisible({action:"heartbeat"});await this.clerk.client.__internal_sendCaptchaToken(e)}catch{}}isEnabled(){return!!this.clerk.__internal_environment?.displayConfig?.captchaHeartbeat}clientBypass(){return this.clerk.client?.captchaBypass}intervalInMs(){return this.clerk.__internal_environment?.displayConfig?.captchaHeartbeatIntervalMs??6e5}}let ng=["/client","/waitlist"];class nb{async getBaseFapiProxyOptions(){let e=await tH.clerk.session?.getToken();if(!e)throw new C("No valid session token available",{code:"no_session_token"});return{pathPrefix:"",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},credentials:"same-origin"}}async getAll(e){return tH._fetch({...await this.getBaseFapiProxyOptions(),method:"GET",path:"/api_keys",search:as({...e,subject:e?.subject??tH.clerk.organization?.id??tH.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:t,total_count:a}=e;return{total_count:a,data:t.map(e=>new tG(e))}})}async create(e){return new tG(await tH._fetch({...await this.getBaseFapiProxyOptions(),path:"/api_keys",method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??tH.clerk.organization?.id??tH.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new tG(await tH._fetch({...await this.getBaseFapiProxyOptions(),method:"POST",path:`/api_keys/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let ny=new Map;class nw{#es=!1;load(e){let t=e?.protectConfig;if(t?.loaders&&Array.isArray(t.loaders)&&0!==t.loaders.length&&!this.#es){if(o())for(let e of(this.#es=!0,t.loaders))try{this.applyLoader(e)}catch(e){X(`[protect] failed to apply loader: ${e}`)}}}applyLoader(e){if(void 0!==e.rollout){let t=e.rollout;if("number"!=typeof t||t<0)return void X(`[protect] loader rollout value is invalid: ${t}`);if(0===t||Math.random()>t)return}let t=e.type||"script",a=e.target||"body",r=document.createElement(t);if(e.attributes)for(let[t,a]of Object.entries(e.attributes))switch(typeof a){case"string":case"number":case"boolean":r.setAttribute(t,String(a));break;default:X(`[protect] loader attribute is invalid type: ${t}=${a}`)}switch(e.textContent&&"string"==typeof e.textContent&&(r.textContent=e.textContent),a){case"head":document.head.appendChild(r);break;case"body":document.body.appendChild(r);break;default:if(a?.startsWith("#")){let e=document.getElementById(a.substring(1));if(!e)return void X(`[protect] loader target element not found: ${a}`);e.appendChild(r);return}X(`[protect] loader target is invalid: ${a}`)}}}class nk{signInResourceSignal=al;signInErrorSignal=ac;signInFetchSignal=au;signInSignal=ad;signUpResourceSignal=ah;signUpErrorSignal=am;signUpFetchSignal=ap;signUpSignal=af;__internal_effect=t7;__internal_computed=t4;constructor(){rn.on("resource:update",this.onResourceUpdated),rn.on("resource:error",this.onResourceError),rn.on("resource:fetch",this.onResourceFetch)}onResourceError=e=>{e.resource instanceof rL&&this.signInErrorSignal({error:e.error}),e.resource instanceof rH&&this.signUpErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof rL){if(nv(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof rH){if(nv(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}};onResourceFetch=e=>{e.resource instanceof rL&&this.signInFetchSignal({status:e.status}),e.resource instanceof rH&&this.signUpFetchSignal({status:e.status})}}function nv(e,t){return!t?.id&&e&&e.__internal_future?.hasBeenFinalized===!1}let nx="cannot_render_billing_disabled",nj="cannot_render_user_missing",n_="cannot_render_organizations_disabled",nz="cannot_render_organization_missing",nS="cannot_render_single_session_enabled",nE={polling:!0,standardBrowser:!0,touchSession:!0,isSatellite:!1,signInUrl:void 0,signUpUrl:void 0,afterSignOutUrl:void 0,signInFallbackRedirectUrl:void 0,signUpFallbackRedirectUrl:void 0,signInForceRedirectUrl:void 0,signUpForceRedirectUrl:void 0,newSubscriptionRedirectUrl:void 0};class nA{static version="6.0.0-canary.v20251217202303";static sdkMetadata={name:"@clerk/clerk-js",version:"6.0.0-canary.v20251217202303"};static _billing;static _apiKeys;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new nk;internal_last_error=null;environment;#ef;#eg="";#eb;#ey;#ew;#ek;#ev;#ex=null;#ej;#e_;#ez;#eS="loading";#eE=[];#eA=[];#eI={};#eC=null;#eP=0;#eq=f();get __internal_queryClient(){return this.#ef||Promise.resolve().then(n.bind(n,3303)).then(e=>e.QueryClient).then(e=>{this.#ef||(this.#ef=new e,this.#eq.emit("queryClientStatus","ready"))}),this.#ef?{__tag:"clerk-rq-client",client:this.#ef}:void 0}__internal_getCachedResources;__internal_createPublicCredentials;__internal_getPublicCredentials;__internal_isWebAuthnSupported;__internal_isWebAuthnAutofillSupported;__internal_isWebAuthnPlatformAuthenticatorSupported;__internal_setActiveInProgress=!1;get publishableKey(){return this.#eg}get version(){return nA.version}set sdkMetadata(e){nA.sdkMetadata=e}get sdkMetadata(){return nA.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#eS}get isSatellite(){return!!tw()&&e6(this.#eI.isSatellite,new URL(window.location.href),!1)}get domain(){if(tw()){let e=function(e=""){return(e||"").replace(/^.+:\/\//,"")}(e6(this.#eb,new URL(window.location.href)));if("production"===this.#ez){let t;if(!e)return"";if(e.match(/^(clerk\.)+\w*$/))t=/(clerk\.)*(?=clerk\.)/;else{if(e.match(/\.clerk.accounts/))return e;t=/^(clerk\.)*/gi}return`clerk.${e.replace(t,"")}`}return e}return""}get proxyUrl(){if(tw()){let e=e6(this.#ey,new URL(window.location.href));return!e||eG(e)||eJ(e)||tf.throwInvalidProxyUrl({url:e}),e?eJ(e)?new URL(e,window.location.origin).toString():e:""}return""}get frontendApi(){let e=ef(this.publishableKey);return e?e.frontendApi:tf.throwInvalidPublishableKeyError({key:this.publishableKey})}get instanceType(){return this.#ez}get isStandardBrowser(){return this.#eI.standardBrowser||!1}get billing(){return nA._billing||(nA._billing=new ao),nA._billing}get apiKeys(){return nA._apiKeys||(nA._apiKeys=new nb),nA._apiKeys}__experimental_checkout(e){return this._checkout||(this._checkout=e=>(function(e,t){let a,r,n,i,{for:s,planId:o,planPeriod:l}=t;if(null===e.user)throw Error("Clerk: User is not authenticated");if("organization"===s&&null===e.organization)throw Error("Clerk: The current session does not have an active organization. Use `setActive` to set the organization");let c=function(e){let{userId:t,orgId:a,planId:r,planPeriod:n}=e;return`${t}-${a||"user"}-${r}-${n}`}({userId:e.user?.id||"",orgId:"organization"===s?e.organization?.id:void 0,planId:o,planPeriod:l}),u=ny.get(c);if(u)return u.signals.computedSignal();let d=(a=t8({resource:null}),r=t8({error:null}),n=t8({status:"idle"}),i=t4(()=>{let e=a().resource,t=r().error,i=n().status;return{errors:ag(t,{}),fetchStatus:i,checkout:e}}),{resourceSignal:a,errorSignal:r,fetchSignal:n,computedSignal:i}),h=new aw(d,{..."organization"===s?{orgId:e.organization?.id}:{},planId:o,planPeriod:l});return ny.set(c,{resource:h,signals:d}),d.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#eI[e]}get isSignedIn(){return this?.session?.status!=="pending"&&!!this.session}constructor(e,t){if(!(e=(e||"").trim()))return tf.throwMissingPublishableKeyError();let a=ef(e);if(!a)return tf.throwInvalidPublishableKeyError({key:e});this.#eb=t?.domain,this.#ey=t?.proxyUrl,this.environment=ro.getInstance(),this.#ez=a.instanceType,this.#eg=e,this.#e_=function(e){let t=[],a=[];async function r(e){for await(let a of["undefined"!=typeof window&&window.__internal_onBeforeRequest,...t].filter(e=>e))if(await a(e)===!1)return!1;return!0}async function n(e,t){for await(let r of["undefined"!=typeof window&&window.__internal_onAfterResponse,...a].filter(e=>e))if(await r(e,t)===!1)return!1;return!0}function i({method:t,path:a,sessionId:r,search:n,rotatingTokenNonce:i}){let s=new URLSearchParams(n);return s.append("__clerk_api_version","2025-11-10"),s.append("_clerk_js_version","6.0.0-canary.v20251217202303"),i&&s.append("rotating_token_nonce",i),e.domain&&"development"===e.instanceType&&e.isSatellite&&s.append("__domain",e.domain),t&&"GET"!==t&&"POST"!==t&&s.append("_method",t),a&&!ng.some(e=>a.startsWith(e))&&r&&s.append("_clerk_session_id",r),ek([...s.entries()].reduce((e,[t,a])=>(e[t]=a.includes(",")?a.split(","):a,e),{}))}function s(t){let{path:a,pathPrefix:r="v1"}=t;if(e.proxyUrl){let n=new URL(e.proxyUrl),s=n.pathname.slice(1);return s.endsWith("/")&&(s=s.slice(0,-1)),eS({base:n.origin,pathname:`${s}/${r}${a}`,search:i(t)},{stringify:!1})}let n="production"===e.instanceType?e.domain:"";return eS({base:`https://${n||e.frontendApi}`,pathname:`${r}${a}`,search:i(t)},{stringify:!1})}async function o(t,a){let i,o={...t},{method:l="GET",body:c}=o;!c||"object"!=typeof c||c instanceof FormData||(o.body=function(e){if(!e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype)return e;let t={};for(let[a,r]of Object.entries(e))void 0!==r&&(t[a]=r);return t}(c)),o.url=s({...o,sessionId:e.getSessionId()}),o.headers=new Headers(o.headers),"GET"===l||c instanceof FormData||o.headers.has("content-type")||o.headers.set("content-type","application/x-www-form-urlencoded"),"application/x-www-form-urlencoded"===o.headers.get("content-type")&&(o.body=c?ek(c,{keyEncoder:er}):c);let d=await r(o),h="GET"===l?"GET":"POST",m=o.url,p={...o,method:h,credentials:o.credentials||"include"};try{if(d){let e=a?.fetchMaxTries??(u()?4:11);i=await tl(()=>fetch(m,p),{retryImmediately:!0,initialDelay:700,maxDelayBetweenRetries:5e3,shouldRetry:(t,a)=>"GET"===h&&a<e,onBeforeRetry:e=>{m.searchParams.set("_clerk_retry_attempt",e.toString())}})}else i=new Response("{}",o)}catch(t){let e=m.toString();tn.error("network error",{error:t,url:e,method:l},"fapiClient");throw Error(`${tA} Network error at "${e}" - ${t}. Please try again.`)}let f=204!==i.status?await i.json():null,g=Object.assign(i,{payload:f});return i.ok||tn.error("request failed",{method:l,path:o.path,status:i.status},"fapiClient"),await n(o,g),g}return{buildEmailAddress:function(t){return function({localPart:e,frontendApi:t}){return`${e}@${t?t.replace("clerk.",""):"clerk.com"}`}({localPart:t,frontendApi:e.frontendApi})},buildUrl:s,onAfterResponse:function(e){a.push(e)},onBeforeRequest:function(e){t.push(e)},request:o}}({domain:this.domain,frontendApi:this.frontendApi,instanceType:this.instanceType,isSatellite:this.isSatellite,getSessionId:()=>this.session?.id,proxyUrl:this.proxyUrl}),this.#eq.emit(g,"loading"),this.#eq.prioritizedOn(g,e=>this.#eS=e),tH.clerk=this,this.#ek=new nw}getFapiClient=()=>this.#e_;load=async e=>{if(tn.info("load() start",{},"clerk"),!this.loaded){if("development"===this.#ez&&X("Clerk: Clerk has been loaded with development keys. Development instances have strict usage limits and should not be used when deploying your application to production. Learn more: https://clerk.com/docs/deployments/overview"),this.#eI=this.#eO(e),this.#eI.clerkUiCtor&&(this.#ej=Promise.resolve(this.#eI.clerkUiCtor).then(e=>new e(()=>this,()=>this.environment,this.#eI,new tu))),"development"===this.#ez&&(this.#eI.routerPush||this.#eI.routerReplace)&&(!this.#eI.routerPush||!this.#eI.routerReplace)){let e=this.#eI.routerPush?"routerReplace":"routerPush";X(`Clerk: Both \`routerPush\` and \`routerReplace\` need to be defined, but \`${e}\` is not defined. This may cause issues with navigation in your application.`)}rn.on(rr,()=>{this.#eT(this.session),this.#eU()}),this.#eI.sdkMetadata&&(nA.sdkMetadata=this.#eI.sdkMetadata),!1!==this.#eI.telemetry&&(this.telemetry=new eX({clerkVersion:nA.version,samplingRate:1,perEventSampling:!this.#eI.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#eI.telemetry}),this.#eI.appearance&&this.telemetry.record({event:"THEME_USAGE",eventSamplingRate:1,payload:function(e){let t;if(!e||"object"!=typeof e)return{};let a=e.theme;if(!a)return{};if(Array.isArray(a))for(let e of a){let a=e5(e);if(a){t=a;break}}else t=e5(a);return{themeName:t}}(this.#eI.appearance)}));try{this.#eI.standardBrowser?await this.#eM():await this.#eR();let e=this.#eI.telemetry,t=!1!==e&&!e?.disabled,a=!!this.#eI.__internal_keyless_claimKeylessApplicationUrl,r=!!this.environment?.clientDebugMode,n=this.environment?.isProduction?.()??!1,i=r||a&&!n,s=a&&!r?"error":void 0;i&&function(e={}){if(te)return;let{enabled:t=!1,...a}=e;t&&(e4=!0,te=!0,tr(a))}({enabled:!0,...s?{logLevel:s}:{},...t&&this.telemetry?{telemetryCollector:this.telemetry}:{}}),this.#ek?.load(this.environment),tn.info("load() complete",{},"clerk")}catch(e){throw this.#eq.emit(g,"error"),tn.error("load() failed",{error:e},"clerk"),e}}};#eB(){let e;return!!(!this.#eI.signUpUrl&&this.#eI.signInUrl&&(e=this.#eI.signInUrl,!ew.test(e)))}signOut=async(e,t)=>{if(!this.client||0===this.client.sessions.length)return;let a="undefined"!=typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:e8,r="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e8,n=e&&"object"==typeof e?e:t||{},i=n?.redirectUrl||this.buildAfterSignOutUrl();tn.debug("signOut() start",{hasClient:!!this.client,multiSessionCount:this.client?.signedInSessions.length??0,redirectUrl:i,sessionTarget:n?.sessionId??null},"clerk");let s="function"==typeof e?e:void 0,o=async()=>{let e=td(this.#eI.standardBrowser);rn.emit(rt,null),this.#eN(),await e.track(async()=>{s?await s():await this.navigate(i)}),e.isUnloading()||(this.#eT(),this.#eU(),await r())};if(await a(),!n.sessionId||1===this.client.signedInSessions.length){this.#eI.experimental?.persistClient??!0?await this.client.removeSessions():await this.client.destroy(),await o(),tn.info("signOut() complete",{redirectUrl:eE(i)},"clerk");return}let l=this.client.signedInSessions.find(e=>e.id===n.sessionId),c=l?.id&&this.session?.id===l.id;await l?.remove(),c&&(await o(),tn.info("signOut() complete",{redirectUrl:eE(i)},"clerk"))};openGoogleOneTap=e=>{this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(t=>t.openModal("googleOneTap",e||{})),this.telemetry?.record(e9("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(L(this,this.environment)){if("development"===this.#ez)throw new C(eW.cannotOpenSignInOrSignUp,{code:nS});return}this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(t=>t.openModal("signIn",e||{}));let t={withSignUp:e?.withSignUp??this.#eB()};this.telemetry?.record(e9("SignIn",e,t))};closeSignIn=()=>{this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(W(this,this.environment)){if("development"===this.#ez)throw new C(eW.cannotRenderAnyBillingComponent("Checkout"),{code:nx});return}if(!this.user){if("development"===this.#ez)throw new C(eW.cannotOpenCheckout,{code:nj});return}this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(t=>t.openDrawer("checkout",e||{}))};__internal_closeCheckout=()=>{this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("checkout"))};__internal_openPlanDetails=e=>{if(W(this,this.environment)){if("development"===this.#ez)throw new C(eW.cannotRenderAnyBillingComponent("PlanDetails"),{code:nx});return}this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(t=>t.openDrawer("planDetails",e||{})),this.telemetry?.record(e9("PlanDetails",e))};__internal_closePlanDetails=()=>{this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("planDetails"))};__internal_openSubscriptionDetails=e=>{this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(t=>t.openDrawer("subscriptionDetails",e||{}))};__internal_closeSubscriptionDetails=()=>{this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("subscriptionDetails"))};__internal_openReverification=e=>{if(!this.user){if("development"===this.#ez)throw new C(eW.cannotOpenUserProfile,{code:nj});return}this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(t=>t.openModal("userVerification",e||{})),this.telemetry?.record(e9("UserVerification",e))};__internal_closeReverification=()=>{this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userVerification"))};__internal_attemptToEnableEnvironmentSetting=e=>{let{for:t,caller:a}=e;if(this.user||"development"!==this.#ez||X(`Clerk: "${a}" requires an active user session. Ensure a user is signed in before executing ${a}.`),"organizations"===t){let t;return(t=this.environment,t?.organizationSettings.enabled||this.session?.currentTask?.key==="choose-organization")?{isEnabled:!0}:("development"===this.#ez&&this.__internal_openEnableOrganizationsPrompt({caller:a,onSuccess:()=>window.location.reload(),onClose:e.onClose}),{isEnabled:!1})}throw Error(`Attempted to enable an unknown or unsupported setting "${t}".`)};__internal_openEnableOrganizationsPrompt=e=>{this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted({preloadHint:"EnableOrganizationsPrompt"})).then(t=>t.openModal("enableOrganizationsPrompt",e||{})),this.telemetry?.record(e3("EnableOrganizationsPrompt",e))};__internal_closeEnableOrganizationsPrompt=()=>{this.assertComponentsReady(this.#ej),this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeModal("enableOrganizationsPrompt"))};__internal_openBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(e=>e.openModal("blankCaptcha",{})));__internal_closeBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(e=>e.closeModal("blankCaptcha")));__internal_loadStripeJs=async()=>{let{loadStripe:e}=await Promise.resolve().then(n.bind(n,5608));return e};openSignUp=e=>{if(L(this,this.environment)){if("development"===this.#ez)throw new C(eW.cannotOpenSignInOrSignUp,{code:nS});return}this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(t=>t.openModal("signUp",e||{})),this.telemetry?.record(e9("SignUp",e))};closeSignUp=()=>{this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signUp"))};openUserProfile=e=>{if(!this.user){if("development"===this.#ez)throw new C(eW.cannotOpenUserProfile,{code:nj});return}this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(t=>t.openModal("userProfile",e||{}));let t=(e?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(e9("UserProfile",e,t))};closeUserProfile=()=>{this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userProfile"))};openOrganizationProfile=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new C(eW.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:n_})}});if(t){if(!this.organization){if("development"===this.#ez)throw new C(eW.cannotRenderComponentWhenOrgDoesNotExist,{code:nz});return}this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(t=>t.openModal("organizationProfile",e||{})),this.telemetry?.record(e9("OrganizationProfile",e))}};closeOrganizationProfile=()=>{this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeModal("organizationProfile"))};openCreateOrganization=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new C(eW.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:n_})}});t&&(this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(t=>t.openModal("createOrganization",e||{})),this.telemetry?.record(e9("CreateOrganization",e)))};closeCreateOrganization=()=>{this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeModal("createOrganization"))};openWaitlist=e=>{this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(t=>t.openModal("waitlist",e||{})),this.telemetry?.record(e9("Waitlist",e))};closeWaitlist=()=>{this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeModal("waitlist"))};mountSignIn=(e,t)=>{this.assertComponentsReady(this.#ej);let a="SignIn";this.#ej.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"signIn",node:e,props:t}));let r={withSignUp:t?.withSignUp??this.#eB()};this.telemetry?.record(e3(a,t,r))};unmountSignIn=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserAvatar=(e,t)=>{this.assertComponentsReady(this.#ej);let a="UserAvatar";this.#ej.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"userAvatar",node:e,props:t})),this.telemetry?.record(e3(a,t))};unmountUserAvatar=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountSignUp=(e,t)=>{this.assertComponentsReady(this.#ej);let a="SignUp";this.#ej.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"signUp",node:e,props:t})),this.telemetry?.record(e3(a,t))};unmountSignUp=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserProfile=(e,t)=>{if(!this.user){if("development"===this.#ez)throw new C(eW.cannotRenderComponentWhenUserDoesNotExist,{code:nj});return}this.assertComponentsReady(this.#ej);let a="UserProfile";this.#ej.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"userProfile",node:e,props:t}));let r=(t?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(e3(a,t,r))};unmountUserProfile=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOrganizationProfile=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new C(eW.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:n_})}});if(!a)return;let r=!!this.user;if(!this.organization&&r){if("development"===this.#ez)throw new C(eW.cannotRenderComponentWhenOrgDoesNotExist,{code:nz});return}this.assertComponentsReady(this.#ej);let n="OrganizationProfile";this.#ej.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:n,appearanceKey:"userProfile",node:e,props:t})),this.telemetry?.record(e3(n,t))};unmountOrganizationProfile=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountCreateOrganization=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new C(eW.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:n_})}});if(!a)return;this.assertComponentsReady(this.#ej);let r="CreateOrganization";this.#ej.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:r,appearanceKey:"createOrganization",node:e,props:t})),this.telemetry?.record(e3(r,t))};unmountCreateOrganization=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOrganizationSwitcher=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationSwitcher",onClose:()=>{throw new C(eW.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:n_})}});if(!a)return;this.assertComponentsReady(this.#ej);let r="OrganizationSwitcher";this.#ej.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:r,appearanceKey:"organizationSwitcher",node:e,props:t})),this.telemetry?.record(e3(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationSwitcher=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__experimental_prefetchOrganizationSwitcher=()=>{this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(e=>e.prefetch("organizationSwitcher"))};mountOrganizationList=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationList",onClose:()=>{throw new C(eW.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:n_})}});if(!a)return;this.assertComponentsReady(this.#ej);let r="OrganizationList";this.#ej.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:r,appearanceKey:"organizationList",node:e,props:t})),this.telemetry?.record(e3(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationList=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserButton=(e,t)=>{this.assertComponentsReady(this.#ej);let a="UserButton";this.#ej.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"userButton",node:e,props:t}));let r={...t?.customMenuItems?.length||0?{customItems:!0}:void 0,...t?.__experimental_asStandalone?{standalone:!0}:void 0};this.telemetry?.record(e3(a,t,r))};unmountUserButton=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountWaitlist=(e,t)=>{this.assertComponentsReady(this.#ej);let a="Waitlist";this.#ej.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"waitlist",node:e,props:t})),this.telemetry?.record(e3(a,t))};unmountWaitlist=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountPricingTable=(e,t)=>{if(W(this,this.environment)){if("development"===this.#ez)throw new C(eW.cannotRenderAnyBillingComponent("PricingTable"),{code:nx});return}this.assertComponentsReady(this.#ej);let a="PricingTable";this.#ej.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"pricingTable",node:e,props:t})),this.telemetry?.record(e3(a,t))};unmountPricingTable=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__internal_mountOAuthConsent=(e,t)=>{this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:"OAuthConsent",appearanceKey:"__internal_oauthConsent",node:e,props:t}))};__internal_unmountOAuthConsent=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountAPIKeys=(e,t)=>{let a;if(X("Clerk: <APIKeys /> component is in early access and not yet recommended for production use."),K(this,a=this.environment)&&H(this,a)){if("development"===this.#ez)throw new C(eW.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&H(this,this.environment)){if("development"===this.#ez)throw new C(eW.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if(K(this,this.environment)){if("development"===this.#ez)throw new C(eW.cannotRenderAPIKeysComponentForUserWhenDisabled,{code:"cannot_render_api_keys_user_disabled"});return}this.assertComponentsReady(this.#ej);let r="APIKeys";this.#ej.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:r,appearanceKey:"apiKeys",node:e,props:t})),this.telemetry?.record(e3(r,t))};unmountAPIKeys=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskChooseOrganization=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"TaskChooseOrganization",onClose:()=>{throw new C(eW.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:n_})}});if(!a)return;this.assertComponentsReady(this.#ej);let r="TaskChooseOrganization";this.#ej.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:r,appearanceKey:"taskChooseOrganization",node:e,props:t})),this.telemetry?.record(e3(r,t))};unmountTaskChooseOrganization=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskResetPassword=(e,t)=>{this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:"TaskResetPassword",appearanceKey:"taskResetPassword",node:e,props:t})),this.telemetry?.record(e3("TaskResetPassword",t))};unmountTaskResetPassword=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};setActive=async e=>{let{organization:t,redirectUrl:a,navigate:r}=e,{session:n}=e;this.__internal_setActiveInProgress=!0,tn.debug("setActive() start",{hasClient:!!this.client,sessionTarget:"string"==typeof n?n:n?.id??n??null,organizationTarget:"string"==typeof t?t:t?.id??t??null,redirectUrl:a??null},"clerk");try{var i;let s;if(!this.client)throw tn.warn("Clerk setActive called before client is loaded",{},"clerk"),Error("setActive is being called before the client is loaded. Wait for init.");if(void 0===n&&!this.session)throw tn.warn("Clerk setActive precondition not met: no target session and no active session",{},"clerk"),Error("setActive should either be called with a session param or there should be already an active session.");"string"==typeof n&&(n=this.client.sessions.find(e=>e.id===n)||null);let o="undefined"!=typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:e8,l="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e8,c=void 0===n?this.session:n;c?.status==="pending"&&(i={...this.#eI,...e},s=["taskUrls","navigate"],Object.keys(i).some(e=>s.includes(e))||X('Clerk: Session has pending tasks but no handling is configured. To handle pending tasks, provide either "taskUrls" for navigation to custom URLs or "navigate" for programmatic navigation. Without these options, users may get stuck on incomplete flows.'));let u=void 0!==t;if(c&&u){let e="string"==typeof t?t:t?.id;if("string"==typeof e&&e.startsWith("org_"))c.lastActiveOrganizationId=e||null;else{let t=c.user.organizationMemberships.find(t=>t.organization.slug===e),a=t?.organization.id||null,r=null===a;if(this.environment?.organizationSettings?.forceOrganizationSelection&&r)return;c.lastActiveOrganizationId=a}}c?.status!=="pending"&&await o(null===c?"sign-out":void 0),(tw()&&globalThis.document.hasFocus()||!this.#eI.standardBrowser)&&(await this.#eD(c),c=this.#eF(c?.id)),await c?.getToken()||(d()||tn.warn("Token is null when setting active session (offline)",{sessionId:c?.id},"clerk"),rn.emit(re,{token:null}));let h=td(this.#eI.standardBrowser),m=c?.status==="pending"&&c?.currentTask&&this.#eI.taskUrls?.[c?.currentTask.key];if((a||m||r)&&await h.track(async()=>{if(this.client){if(c?.status!=="pending"&&this.#eN(),m){let e=a?eS({base:m,hashSearchParams:{redirectUrl:a}},{stringify:!0}):m;await this.navigate(e)}else if(r&&c)await r({session:c});else if(a){if(this.client.isEligibleForTouch()){let e=new URL(a,window.location.href),t=this.buildUrlWithAuth(this.client.buildTouchUrl({redirectUrl:e}));await this.navigate(t)}await this.navigate(a)}}}),h.isUnloading())return;this.#eT(c),this.#eU(),c?.status!=="pending"&&await l()}finally{this.__internal_setActiveInProgress=!1}};addListener=e=>{var t;let a;return t=e,e=e=>{var r;a||={...e},t(a={...{client:r5((r=a).client,e.client),session:r5(r.session,e.session),user:r5(r.user,e.user),organization:r5(r.organization,e.organization)}})},this.#eE.push(e),this.client&&e({client:this.client,session:this.session,user:this.user,organization:this.organization}),()=>{this.#eE=this.#eE.filter(t=>t!==e)}};on=(...e)=>{this.#eq.on(...e)};off=(...e)=>{this.#eq.off(...e)};__internal_addNavigationListener=e=>(this.#eA.push(e),()=>{this.#eA=this.#eA.filter(t=>t!==e)});navigate=async(e,t)=>{if(!e||!tw())return;setTimeout(()=>{this.#eL()},0);let a=new URL(e,window.location.href);this.#eW.includes(a.protocol)||(console.warn(`Clerk: "${a.protocol}" is not a valid protocol. Redirecting to "/" instead. If you think this is a mistake, please open an issue.`),a=new URL("/",window.location.href));let r=t?.replace&&this.#eI.routerReplace?this.#eI.routerReplace:this.#eI.routerPush;if(tn.info(`Clerk is navigating to: ${a}`),this.#eI.routerDebug&&console.log(`Clerk is navigating to: ${a}`),"null"!==a.origin&&a.origin!==window.location.origin||!r)return void eV(a);let n={...t?.metadata?{__internal_metadata:t?.metadata}:{},windowNavigate:eV};return await r(eE(a),n)};buildUrlWithAuth(e){if("production"===this.#ez)return e;let t=new URL(e,window.location.origin);return t.origin!==window.location.origin&&this.#ew?this.#ew.decorateUrlWithDevBrowserToken(t).href:t.href}buildSignInUrl(e){return this.#eK("signInUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildSignUpUrl(e){return this.#eK("signUpUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildUserProfileUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.userProfileUrl):""}buildHomeUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.homeUrl):""}buildAfterSignInUrl({params:e}={}){return this.buildUrlWithAuth(new eO(this.#eI,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eO(this.#eI,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#eI.afterSignOutUrl?this.buildUrlWithAuth(this.#eI.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#eI.newSubscriptionRedirectUrl?this.#eI.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?eS({base:this.#eI.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#eI.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#eI.afterMultiSessionSingleSignOutUrl):this.#eI.signInUrl?this.buildUrlWithAuth(eS({base:this.#eI.signInUrl,hashPath:"choose"},{stringify:!0})):this.buildUrlWithAuth(this.environment.displayConfig.afterSignOutOneUrl):""}buildCreateOrganizationUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.createOrganizationUrl):""}buildOrganizationProfileUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.organizationProfileUrl):""}buildTasksUrl(e){let t=this.session?.currentTask;if(!t)return"";let a=this.#eI.taskUrls?.[t.key];return a||eS({base:this.buildSignInUrl(e),hashPath:eD(t)},{stringify:!0})}#eH=async()=>{if(!tw())return;let e=new URLSearchParams({[V]:"true"}),t=eM(J);t&&eG(t)||function(){throw Error(`${tA} Invalid redirect_url. A valid http or https url should be used for the redirection.`)}();let a=eS({base:eM(J),searchParams:e},{stringify:!0});return this.navigate(this.buildUrlWithAuth(a))};redirectWithAuth=async e=>{if(tw())return this.navigate(this.buildUrlWithAuth(e))};redirectToSignIn=async e=>{if(tw())return this.navigate(this.buildSignInUrl(e))};redirectToSignUp=async e=>{if(tw())return this.navigate(this.buildSignUpUrl(e))};redirectToUserProfile=async()=>{if(tw())return this.navigate(this.buildUserProfileUrl())};redirectToCreateOrganization=async()=>{if(tw())return this.navigate(this.buildCreateOrganizationUrl())};redirectToOrganizationProfile=async()=>{if(tw())return this.navigate(this.buildOrganizationProfileUrl())};redirectToAfterSignIn=async()=>{if(tw())return this.navigate(this.buildAfterSignInUrl())};redirectToAfterSignUp=async()=>{if(tw())return this.navigate(this.buildAfterSignUpUrl())};redirectToAfterSignOut=async()=>{if(tw())return this.navigate(this.buildAfterSignOutUrl())};redirectToWaitlist=async()=>{if(tw())return this.navigate(this.buildWaitlistUrl())};redirectToTasks=async e=>{if(tw())return this.navigate(this.buildTasksUrl(e))};handleEmailLinkVerification=async(e,t)=>{if(!this.client)return;let a=eM("__clerk_status");if("expired"===a)throw new E(I.Expired);if("client_mismatch"===a)throw new E(I.ClientMismatch);if("verified"!==a)throw new E(I.Failed);let r=eM("__clerk_created_session"),{signIn:n,signUp:i,sessions:s}=this.client,o=s.some(e=>e.id===r),l="needs_second_factor"===n.status||"missing_requirements"===i.status,c=e=>t&&"function"==typeof t?t(e):this.navigate(e),u=e.redirectUrl?()=>c(e.redirectUrl):e8;return o?this.setActive({session:r,redirectUrl:e.redirectUrlComplete}):l?u():("function"==typeof e.onVerifiedOnOtherDevice&&e.onVerifiedOnOtherDevice(),null)};handleGoogleOneTapCallback=async(e,t,a)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:r,signUp:n}=this.client,i="identifier"in(e||{})?e:r,s="missingFields"in(e||{})?e:n,o=e=>a&&"function"==typeof a?a(this.buildUrlWithAuth(e)):this.navigate(this.buildUrlWithAuth(e));return this._handleRedirectCallback(t,{signUp:s,signIn:i,navigate:o})};_handleRedirectCallback=async(e,{signIn:t,signUp:a,navigate:r})=>{if(!this.loaded||!this.environment||!this.client)return;if(!window.opener&&e.reloadResource)try{"signIn"===e.reloadResource?await t.reload():"signUp"===e.reloadResource&&await a.reload()}catch{}let{displayConfig:n}=this.environment,{firstFactorVerification:i}=t,{externalAccount:s}=a.verifications,o={status:a.status,missingFields:a.missingFields,externalAccountStatus:s.status,externalAccountErrorCode:s.error?.code,externalAccountSessionId:s.error?.meta?.sessionId,sessionId:a.createdSessionId},l={status:t.status,firstFactorVerificationStatus:i.status,firstFactorVerificationErrorCode:i.error?.code,firstFactorVerificationSessionId:i.error?.meta?.sessionId,sessionId:t.createdSessionId},c=e=>()=>r(e),u=c(e.signInUrl||n.signInUrl),d=c(e.signUpUrl||n.signUpUrl),h=c(e.firstFactorUrl||eS({base:n.signInUrl,hashPath:"/factor-one"},{stringify:!0})),m=c(e.secondFactorUrl||eS({base:n.signInUrl,hashPath:"/factor-two"},{stringify:!0})),p=c(e.resetPasswordUrl||eS({base:n.signInUrl,hashPath:"/reset-password"},{stringify:!0})),f=new eO(this.#eI,e),g=c(e.continueSignUpUrl||eS({base:n.signUpUrl,hashPath:"/continue"},{stringify:!0})),b=({missingFields:t})=>t.length?g():(({signUp:e,verifyEmailPath:t,verifyPhonePath:a,continuePath:r,navigate:n,handleComplete:i,redirectUrl:s="",redirectUrlComplete:o="",oidcPrompt:l})=>{if("complete"===e.status)return i&&i();if("missing_requirements"===e.status){if(e.missingFields.some(e=>"enterprise_sso"===e))return e.authenticateWithRedirect({strategy:"enterprise_sso",redirectUrl:s,redirectUrlComplete:o,continueSignUp:!0,oidcPrompt:l});let i=eB();if(e.unverifiedFields?.includes("email_address")&&t)return n(t,{searchParams:i});if(e.unverifiedFields?.includes("phone_number")&&a)return n(a,{searchParams:i});if(r)return n(r,{searchParams:i})}})({signUp:a,verifyEmailPath:e.verifyEmailAddressUrl||eS({base:n.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),verifyPhonePath:e.verifyPhoneNumberUrl||eS({base:n.signUpUrl,hashPath:"/verify-phone-number"},{stringify:!0}),navigate:r}),y=e.signInUrl||n.signInUrl,w=e.signUpUrl||n.signUpUrl,k=async({session:e,baseUrl:t,redirectUrl:a})=>{e.currentTask?await eF(e,{baseUrl:t,navigate:this.navigate}):await this.navigate(a)};if("complete"===l.status)return this.setActive({session:l.sessionId,navigate:async({session:e})=>{await k({session:e,baseUrl:y,redirectUrl:f.getAfterSignInUrl()})}});if("transferable"===o.externalAccountStatus&&"external_account_exists"===o.externalAccountErrorCode){let e=await t.create({transfer:!0});switch(e.status){case"complete":return this.setActive({session:e.createdSessionId,navigate:async({session:e})=>{await k({session:e,baseUrl:w,redirectUrl:f.getAfterSignInUrl()})}});case"needs_first_factor":return h();case"needs_second_factor":return m();case"needs_new_password":return p();default:tC("sign in")}}let v="user_locked"===o.externalAccountErrorCode,x="user_locked"===l.firstFactorVerificationErrorCode;if(v)return d();if(x)return u();if("needs_first_factor"===l.status&&!t.supportedFirstFactors?.every(e=>"enterprise_sso"===e.strategy))return h();if("needs_new_password"===l.status)return p();if("transferable"===l.firstFactorVerificationStatus){if(!1===e.transferable)return u();let t=await a.create({transfer:!0});switch(t.status){case"complete":return this.setActive({session:t.createdSessionId,navigate:async({session:e})=>{await k({session:e,baseUrl:w,redirectUrl:f.getAfterSignUpUrl()})}});case"missing_requirements":return b({missingFields:t.missingFields});default:tC("sign in")}}if("complete"===o.status)return this.setActive({session:o.sessionId,navigate:async({session:e})=>{await k({session:e,baseUrl:w,redirectUrl:f.getAfterSignUpUrl()})}});if("needs_second_factor"===l.status)return m();let j=("failed"===o.externalAccountStatus||"unverified"===o.externalAccountStatus)&&"identifier_already_signed_in"===o.externalAccountErrorCode&&o.externalAccountSessionId,_="failed"===l.firstFactorVerificationStatus&&"identifier_already_signed_in"===l.firstFactorVerificationErrorCode&&l.firstFactorVerificationSessionId;if(j||_){let e=l.firstFactorVerificationSessionId||o.externalAccountSessionId;if(e)return this.setActive({session:e,navigate:async({session:e})=>{await k({session:e,baseUrl:j?w:y,redirectUrl:f.getAfterSignInUrl()})}})}return(e=>{let{externalAccount:t}=e.verifications;return!!t.error})(a)?d():"verified"===o.externalAccountStatus&&"missing_requirements"===o.status?b({missingFields:a.missingFields}):this.session?.currentTask?void await this.redirectToTasks({redirectUrl:this.buildAfterSignInUrl()}):u()};handleRedirectCallback=async(e={},t)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:a,signUp:r}=this.client,n=e=>t&&"function"==typeof t?t(e):this.navigate(e);return this._handleRedirectCallback(e,{signUp:r,signIn:a,navigate:n})};handleUnauthenticated=async(e={broadcast:!0})=>{if(this.client&&this.session)try{let t=await aN.getOrCreateInstance().fetch();if(this.updateClient(t),this.session)return;return e.broadcast&&rn.emit(rt,null),this.setActive({session:null})}catch(e){if(M(e)&&[403,500].includes(e.status))return this.setActive({session:null});throw e}};authenticateWithGoogleOneTap=async e=>this.client?.signIn.create({strategy:"google_one_tap",token:e.token}).catch(t=>{if(M(t)&&"external_account_not_found"===t.errors[0].code)return this.client?.signUp.create({strategy:"google_one_tap",token:e.token,legalAccepted:e.legalAccepted});throw t});authenticateWithMetamask=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_okx_wallet_signature"})};authenticateWithSolana=async e=>{await this.authenticateWithWeb3({...e,strategy:"web3_solana_signature"})};authenticateWithWeb3=async({redirectUrl:e,signUpContinueUrl:t,customNavigate:a,unsafeMetadata:r,strategy:n,legalAccepted:i,secondFactorUrl:s,walletName:o})=>{let l,c;if(!this.client||!this.environment)return;let{displayConfig:u}=this.environment,d=n.replace("web3_","").replace("_signature",""),h=await tj().getWeb3Identifier({provider:d,walletName:o});switch(d){case"metamask":l=tj().generateSignatureWithMetamask;break;case"base":l=tj().generateSignatureWithBase;break;case"coinbase_wallet":l=tj().generateSignatureWithCoinbaseWallet;break;case"solana":if(!o)throw new C("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});l=e=>tj().generateSignatureWithSolana({...e,walletName:o});break;default:l=tj().generateSignatureWithOKXWallet}let m=e=>()=>a&&"function"==typeof a?a(e):this.navigate(e),p=m(s||eS({base:u.signInUrl,hashPath:"/factor-two"},{stringify:!0})),f=m(t||eS({base:u.signUpUrl,hashPath:"/continue"},{stringify:!0}));try{c=await this.client.signIn.authenticateWithWeb3({identifier:h,generateSignature:l,strategy:n,walletName:o})}catch(e){if(tp(e,"form_identifier_not_found"))c=await this.client.signUp.authenticateWithWeb3({identifier:h,generateSignature:l,unsafeMetadata:r,strategy:n,legalAccepted:i,walletName:o}),t&&"missing_requirements"===c.status&&"verified"===c.verifications.web3Wallet.status&&await f();else throw e}let g=async({session:e,redirectUrl:t})=>{e.currentTask?await eF(e,{baseUrl:u.signInUrl,navigate:this.navigate}):await this.navigate(t)};switch(c.status){case"needs_second_factor":await p();break;case"complete":c.createdSessionId&&await this.setActive({session:c.createdSessionId,navigate:async({session:t})=>{await g({session:t,redirectUrl:e??this.buildAfterSignInUrl()})}});break;default:return}};createOrganization=async({name:e,slug:t})=>rg.create({name:e,slug:t});getOrganization=async e=>rg.get(e);joinWaitlist=async({emailAddress:e})=>r3.join({emailAddress:e});updateEnvironment(e){this.environment=e}__internal_setCountry=e=>{this.__internal_country||(this.__internal_country=e)};get __internal_last_error(){let e=this.internal_last_error;return this.internal_last_error=null,e}set __internal_last_error(e){this.internal_last_error=e}updateClient=e=>{if(!this.client){let t=this.#eI.selectInitialSession?this.#eI.selectInitialSession(e):this.#eV(e);this.#eT(t)}if(this.client=e,this.session){let e=this.#eF(this.session.id);"active"===this.session.status&&e?.status==="pending"&&("undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e8)(),this.#eT(e),this.session?.lastActiveToken||d()||tn.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),rn.emit(re,{token:this.session?.lastActiveToken})}this.#eU()};get __internal_environment(){return this.environment}__internal_setEnvironment=async e=>{this.environment=new ro(e)};__internal_onBeforeRequest=e=>{this.#e_.onBeforeRequest(e)};__internal_onAfterResponse=e=>{this.#e_.onAfterResponse(e)};__internal_updateProps=e=>{let t={...e,options:this.#eO({...this.#eI,...e.options})};return this.#ej?.then(e=>e.ensureMounted()).then(e=>e.updateProps(t))};__internal_navigateWithError(e,t){return this.__internal_last_error=t,this.navigate(e)}#eG=()=>{let e=new URLSearchParams({[J]:window.location.href});return eS({base:this.#eI.signInUrl,searchParams:e},{stringify:!0})};#eJ=()=>{let e;if(this.proxyUrl){let t=new URL(this.proxyUrl);e=new URL(`${t.pathname}/v1/client/sync`,t.origin)}else this.domain&&(e=new URL("/v1/client/sync",`https://${this.domain}`));return e?.searchParams.append("redirect_url",window.location.href),e?.toString()||""};#eZ=()=>"true"!==eM(V)&&!!this.isSatellite&&!!this.#ew?.isSignedOut();#e$=()=>"production"!==this.#ez&&!this.isSatellite&&!!eM(J);#eY=async()=>{"development"===this.instanceType?await this.navigate(this.#eG()):"production"===this.instanceType&&await this.navigate(this.#eJ())};#eQ=(e,t)=>{let a;try{a=new URL(e)}catch{throw Error(`${tA} The signInUrl needs to have a absolute url format.`)}a.origin===t&&function(){throw Error(`${tA} The signInUrl needs to be on a different origin than your satellite application.`)}()};#eX=()=>{this.isSatellite&&("development"!==this.#ez||this.#eI.signInUrl||function(){throw Error(`${tA} Missing signInUrl. A satellite application needs to specify the signInUrl for development instances.`)}(),this.proxyUrl||this.domain||function(){throw Error(`${tA} Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl.`)}(),this.#eI.signInUrl&&this.#eQ(this.#eI.signInUrl,window.location.origin))};#eM=async()=>{if(this.#ew=await np.create(this,this.#e_,this.#ez,this.#eq),this.#eX(),this.#eZ())return void await this.#eY();if(this.#e$())return void await this.#eH();this.#eC=(()=>{if(!o())return{onPageFocus:e8};let e=[];return window.addEventListener("focus",()=>{"visible"===document.visibilityState&&e.forEach(e=>e())}),{onPageFocus:t=>{e.push(t)}}})(),"undefined"!=typeof BroadcastChannel&&(this.#ex=new BroadcastChannel("clerk")),this.#e1();let e=function(e=window.location.hostname){if(!e)return!1;let t=e_.get(e);void 0===t&&(t=ec.some(t=>e.startsWith("accounts.")&&e.endsWith(t))||eu.some(t=>e.endsWith(t)&&!e.endsWith(".clerk"+t)),e_.set(e,t));return t}(window?.location.hostname),t="development"===this.#ez&&!e,a=0,r=0;for(;r<2;){r++;try{var n;let e=ro.getInstance().fetch({touch:t}).then(e=>this.updateEnvironment(e)).catch(()=>{++a;let e=tE.getItem(t_,null);e&&this.updateEnvironment(new ro(e))}),r=async()=>aN.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(async e=>{if(T(e))throw e;++a;let t=this.#ew?.getSessionCookie(),r=function(e){let t;try{t=new rJ({jwt:e||"",object:"token",id:void 0})}catch{t=null}if(aN.clearInstance(),!t?.jwt)return aN.getOrCreateInstance({object:"client",last_active_session_id:null,id:"client_init",sessions:[]});let{sessionId:a,userId:r,orgId:n,orgRole:i,orgPermissions:s,orgSlug:o,factorVerificationAge:l}=(e=>{let t,a,r,n,i=e.fva??null,s=e.sts??null;if(2===e.v){if(e.o){t=e.o?.id,r=e.o?.slg,e.o?.rol&&(a=`org:${e.o?.rol}`);let{org:i}=rP(e.fea),{permissions:s,featurePermissionMap:o}=(({per:e,fpm:t})=>{if(!e||!t)return{permissions:[],featurePermissionMap:[]};let a=e.split(",").map(e=>e.trim());return{permissions:a,featurePermissionMap:t.split(",").map(e=>Number.parseInt(e.trim(),10)).map(e=>e.toString(2).padStart(a.length,"0").split("").map(e=>Number.parseInt(e,10)).reverse()).filter(Boolean)}})({per:e.o?.per,fpm:e.o?.fpm});n=function({features:e,permissions:t,featurePermissionMap:a}){if(!e||!t||!a)return[];let r=[];for(let n=0;n<e.length;n++){let i=e[n];if(n>=a.length)continue;let s=a[n];if(s)for(let e=0;e<s.length;e++)1===s[e]&&r.push(`org:${i}:${t[e]}`)}return r}({features:i,featurePermissionMap:o,permissions:s})}}else t=e.org_id,a=e.org_role,r=e.org_slug,n=e.org_permissions;return{sessionClaims:e,sessionId:e.sid,sessionStatus:s,actor:e.act,userId:e.sub,orgId:t,orgRole:a,orgSlug:r,orgPermissions:n,factorVerificationAge:i}})(t.jwt.claims),c={object:"client",last_active_session_id:a,id:"client_init",sessions:[{object:"session",id:a,status:"active",last_active_organization_id:n||null,last_active_token:{id:void 0,object:"token",jwt:e},factor_verification_age:l||null,public_user_data:{user_id:r},user:{object:"user",id:r,organization_memberships:n&&o&&i?[{object:"organization_membership",id:n,role:i,permissions:s||[],organization:{object:"organization",id:n,name:o,slug:o,members_count:1,max_allowed_memberships:1}}]:[]}}]};return aN.getOrCreateInstance(c)}(t);return this.updateClient(r),this.#ew?.stopPollingForToken(),await this.session?.getToken({skipCache:!0}).catch(()=>null).finally(()=>{this.#ew?.startPollingForToken()}),null}),[,i]=await (n=[e,r()],Promise.all(Array.from(n).map(e=>e.then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e})))));if("rejected"===i.status){let e=i.reason;if(tp(e,"requires_captcha"))await r();else throw e}if(this.#ew?.setClientUatCookieForDevelopmentInstances(),await this.#e0())return;break}catch(e){if(tp(e,"dev_browser_unauthenticated"))await this.#ew.handleUnauthenticatedDevBrowser();else if(!d())return void console.warn(e);else throw e}r>=2&&function(){throw Error(`${tA} Something went wrong initializing Clerk.`)}()}this.#ev=new nf(this),this.#ev.start(),this.#e2(),this.#e3(),this.#e9(),this.#eq.emit(g,a>0?"degraded":"ready")};shouldFallbackToCachedResources=()=>!!this.__internal_getCachedResources;#eR=async()=>{let e,t,a=this.shouldFallbackToCachedResources()?1:void 0,r=0;try{[e,t]=await Promise.all([ro.getInstance().fetch({touch:!1,fetchMaxTries:a}),aN.getOrCreateInstance().fetch({fetchMaxTries:a})])}catch(a){if(R(a)&&"network_error"===a.code&&this.shouldFallbackToCachedResources()){let a=await this.__internal_getCachedResources?.();e=new ro(a?.environment),aN.clearInstance(),t=aN.getOrCreateInstance(a?.client),++r}else throw a}this.updateClient(t),this.updateEnvironment(e),this.#eq.emit(g,r>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,t]=await Promise.all([ro.getInstance().fetch({touch:!1,fetchMaxTries:1}),aN.getOrCreateInstance().fetch({fetchMaxTries:1})]);this.updateClient(t),this.updateEnvironment(e),this.#eU()};#eV=e=>{if(e.lastActiveSessionId){let t=e.signedInSessions.find(t=>t.id===e.lastActiveSessionId);if(t)return t}return e.signedInSessions[0]||null};#e1=()=>{o()&&(this.#eC?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#eP>Date.now())&&(this.#eP=Date.now()+5e3,this.#eI.touchSession&&this.#eD(this.session))}),this.#ex?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),rn.on(rt,()=>{this.#ex?.postMessage({type:"signout"})}),rn.on(ra,()=>{tE.setItem(t_,this.environment?.__internal_toSnapshot(),864e5)}))};#eD=async e=>{if(!e)return Promise.resolve();await e.touch().catch(e=>{T(e)&&this.handleUnauthenticated()})};#eU=()=>{if(this.client)for(let e of this.#eE)e({client:this.client,session:this.session,user:this.user,organization:this.organization})};#eL=()=>{for(let e of this.#eA)e()};#eN=()=>{this.session=void 0,this.organization=void 0,this.user=void 0,this.#eU()};#e5=()=>(this.session?.user.organizationMemberships||[]).map(e=>e.organization).find(e=>e.id===this.session?.lastActiveOrganizationId)||null;#eT=e=>{this.session=e||null,this.organization=this.#e5(),this.user=this.session?this.session.user:null};#eF=e=>this.client?.signedInSessions.find(t=>t.id===e)||null;#e3=()=>{this.addListener(({session:e})=>{e?.actor&&this.#ej?.then(e=>e.ensureMounted()).then(e=>e.mountImpersonationFab())})};#e9=()=>{this.#eI.__internal_keyless_claimKeylessApplicationUrl&&this.#ej?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#eI.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#eI.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#eI.__internal_keyless_dismissPrompt}})})};#eK=(e,t,a)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let r=this.#eI[e]||this.environment.displayConfig[e];this.#eB()&&(r=this.#eI.signInUrl);let n=new eO(this.#eI,t).toSearchParams(),i=new URLSearchParams(a||{}),s=eS({base:r,hashPath:this.#eB()&&"signUpUrl"===e?"/create":"",hashSearchParams:[i,n]},{stringify:!0});return this.buildUrlWithAuth(s)};assertComponentsReady(e){if(!e)throw Error("Clerk was not loaded with Ui components")}#e0=async()=>{var e;let t,a,r,n,i=new URLSearchParams(window.location.search).get("redirect_url"),s="production"===this.instanceType,o=null!==i&&(e=this.frontendApi,a=(t=new URL(i,ev)).pathname,r=eP.includes(a)||eq.includes(a),e===t.host&&r);if(s||!o)return!1;let l=this.session,c=this.#eI.signInUrl||this.environment?.displayConfig.signInUrl,u=c&&window.location.href.startsWith(c),d=this.#eI.signUpUrl||this.environment?.displayConfig.signUpUrl,h=d&&window.location.href.startsWith(d);return n=new URL(i,ev),(!eP.includes(n.pathname)||!!l||!u&&!h)&&(await this.navigate(this.buildUrlWithAuth(i)),!0)};#eO=e=>({...nE,...e,allowedRedirectOrigins:function(e,t,a){if(Array.isArray(e)&&e.length)return e;let r=[];return"undefined"!=typeof window&&window.location&&r.push(window.location.origin),r.push(`https://${ez(t)}`),r.push(`https://*.${ez(t)}`),"development"===a&&r.push(`https://${t}`),r}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)});#e2=()=>{try{eR(V),eR(eT),eR(G),eR("__clerk_handshake"),eR("__clerk_handshake_nonce"),eR("__clerk_help")}catch{}};get #eW(){let e=eH;return this.#eI.allowedRedirectProtocols&&(e=e.concat(this.#eI.allowedRedirectProtocols)),e}}})();var s=i.c2,o=i.LR,l=i.cR,c=i.NZ,u=i.Ys,d=i.kl,h=i.$R,m=i.Cm,p=i.hl,f=i.ux,g=i.si,b=i._d;export{s as Clerk,o as ClerkAPIResponseError,l as ClerkRuntimeError,c as EmailLinkError,u as EmailLinkErrorCode,d as EmailLinkErrorCodeStatus,h as isClerkAPIResponseError,m as isClerkRuntimeError,p as isEmailLinkError,f as isKnownError,g as isMetamaskError,b as isUserLockedError};
|
|
62
|
+
API Error: ${n}`,{data:t,status:e})}}(i,e);let r={data:e,status:i};if(429===i&&o){let e=o.get("retry-after");if(e){let t=parseInt(e,10);isNaN(t)||(r.retryAfter=t)}}throw new j(t||s,r)}return null}static _updateClient(e){if(!e)return;let t=e.client||e.meta?.client;t&&tH.clerk&&tH.clerk.updateClient(aN.getOrCreateInstance().fromJSON(t))}path(e){let t=this.pathRoot;if(this.isNew())return t;let a=t.replace(/[^/]$/,"$&/")+encodeURIComponent(this.id);return e?a.replace(/[^/]$/,"$&/")+encodeURIComponent(e):a}withDefault(e,t){return e??t}async _baseGet(e={}){let t=await tH._fetch({method:"GET",path:this.path(),rotatingTokenNonce:e.rotatingTokenNonce},e);return this.fromJSON(t?.response||t)}async _baseMutate(e){let{action:t,body:a,method:r,path:n}=e,i=await tH._fetch({method:r,path:n||this.path(t),body:a});return this.fromJSON(i?.response||i)}async _baseMutateBypass(e){let{action:t,body:a,method:r,path:n}=e,i=await tH._baseFetch({method:r,path:n||this.path(t),body:a});return this.fromJSON(i?.response||i)}async _basePost(e={}){return this._baseMutate({...e,method:"POST"})}async _basePostBypass(e={}){return this._baseMutateBypass({...e,method:"POST"})}async _basePut(e={}){return this._baseMutate({...e,method:"PUT"})}async _basePatch(e={}){return this._baseMutate({...e,method:"PATCH"})}async _baseDelete(e={}){await this._baseMutate({...e,method:"DELETE"})}static shouldRethrowOfflineNetworkErrors(){let e=tH.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}function tV(e){let t=new Date(e||new Date);return t instanceof Date&&!isNaN(t.getTime())?t:new Date}class tG extends tH{pathRoot="/api_keys";id;type;name;subject;scopes;claims;revoked;revocationReason;expired;expiration;createdBy;description;secret;lastUsedAt;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.type=e.type,this.name=e.name,this.subject=e.subject,this.scopes=e.scopes,this.claims=e.claims,this.revoked=e.revoked,this.revocationReason=e.revocation_reason,this.expired=e.expired,this.expiration=e.expiration?tV(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?tV(e.last_used_at):null,this.updatedAt=tV(e.updated_at),this.createdAt=tV(e.created_at)),this}__internal_toSnapshot(){return{object:"api_key",id:this.id,type:this.type,name:this.name,subject:this.subject,scopes:this.scopes,claims:this.claims,revoked:this.revoked,revocation_reason:this.revocationReason,expired:this.expired,expiration:this.expiration?this.expiration.getTime():null,created_by:this.createdBy,description:this.description,last_used_at:this.lastUsedAt?this.lastUsedAt.getTime():null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}class tJ extends tH{claimedAt=null;reverification=!1;singleSessionMode=!1;preferredChannels=null;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.claimedAt=this.withDefault(e.claimed_at?tV(e.claimed_at):null,this.claimedAt),this.reverification=this.withDefault(e.reverification,this.reverification),this.singleSessionMode=this.withDefault(e.single_session_mode,this.singleSessionMode),this.preferredChannels=this.withDefault(e.preferred_channels,this.preferredChannels)),this}__internal_toSnapshot(){return{claimed_at:this.claimedAt?this.claimedAt.getTime():null,id:this.id??"",object:"auth_config",reverification:this.reverification,single_session_mode:this.singleSessionMode}}}(y=k||(k={}))[y.None=0]="None",y[y.Mutable=1]="Mutable",y[y.Watching=2]="Watching",y[y.RecursedCheck=4]="RecursedCheck",y[y.Recursed=8]="Recursed",y[y.Dirty=16]="Dirty",y[y.Pending=32]="Pending";let tZ=[],{link:t$,unlink:tY,propagate:tQ,checkDirty:tX,endTracking:t1,startTracking:t0,shallowPropagate:t2}=function({update:e,notify:t,unwatched:a}){let r=0;return{link:function(e,t){let a,n=t.depsTail;if(void 0!==n&&n.dep===e)return;if(4&t.flags&&void 0!==(a=void 0!==n?n.nextDep:t.deps)&&a.dep===e){a.version=r,t.depsTail=a;return}let i=e.subsTail;if(void 0!==i&&i.version===r&&i.sub===t)return;let s=t.depsTail=e.subsTail={version:r,dep:e,sub:t,prevDep:n,nextDep:a,prevSub:i,nextSub:void 0};void 0!==a&&(a.prevDep=s),void 0!==n?n.nextDep=s:t.deps=s,void 0!==i?i.nextSub=s:e.subs=s},unlink:n,propagate:function(e){let a,r=e.nextSub;t:for(;;){let n=e.sub,i=n.flags;if(3&i&&(60&i?12&i?4&i?!(48&i)&&function(e,t){let a=t.depsTail;if(void 0!==a){let r=t.deps;do{if(r===e)return!0;if(r===a)break;r=r.nextDep}while(void 0!==r)}return!1}(e,n)?(n.flags=40|i,i&=1):i=0:n.flags=-9&i|32:i=0:n.flags=32|i,2&i&&t(n),1&i)){let t=n.subs;if(void 0!==t){e=t,void 0!==t.nextSub&&(a={value:r,prev:a},r=e.nextSub);continue}}if(void 0!==(e=r)){r=e.nextSub;continue}for(;void 0!==a;)if(e=a.value,a=a.prev,void 0!==e){r=e.nextSub;continue t}break}},checkDirty:function(t,a){let r,n=0;t:for(;;){let s=t.dep,o=s.flags,l=!1;if(16&a.flags)l=!0;else if((17&o)==17){if(e(s)){let e=s.subs;void 0!==e.nextSub&&i(e),l=!0}}else if((33&o)==33){(void 0!==t.nextSub||void 0!==t.prevSub)&&(r={value:t,prev:r}),t=s.deps,a=s,++n;continue}if(!l&&void 0!==t.nextDep){t=t.nextDep;continue}for(;n;){--n;let s=a.subs,o=void 0!==s.nextSub;if(o?(t=r.value,r=r.prev):t=s,l){if(e(a)){o&&i(s),a=t.sub;continue}}else a.flags&=-33;if(a=t.sub,void 0!==t.nextDep){t=t.nextDep;continue t}l=!1}return l}},endTracking:function(e){let t=e.depsTail,a=void 0!==t?t.nextDep:e.deps;for(;void 0!==a;)a=n(a,e);e.flags&=-5},startTracking:function(e){++r,e.depsTail=void 0,e.flags=-57&e.flags|4},shallowPropagate:i};function n(e,t=e.sub){let r=e.dep,i=e.prevDep,s=e.nextDep,o=e.nextSub,l=e.prevSub;return void 0!==s?s.prevDep=i:t.depsTail=i,void 0!==i?i.nextDep=s:t.deps=s,void 0!==o?o.prevSub=l:r.subsTail=l,void 0!==l?l.nextSub=o:void 0===(r.subs=o)&&a(r),s}function i(e){do{let a=e.sub,r=e.nextSub,n=a.flags;(48&n)==32&&(a.flags=16|n,2&n&&t(a)),e=r}while(void 0!==e)}}({update:e=>"getter"in e?ae(e):at(e,e.value),notify:function e(t){let a=t.flags;if(!(64&a)){t.flags=64|a;let r=t.subs;void 0!==r?e(r.sub):tZ[t5++]=t}},unwatched(e){if("getter"in e){let t=e.deps;if(void 0!==t){e.flags=17;do t=tY(t,e);while(void 0!==t)}}else"previousValue"in e||ai.call(e)}}),t3=0,t9=0,t5=0;function t6(t){let a=e;return e=t,a}function t8(e){return an.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function t4(e){return ar.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function t7(a){let r={fn:a,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==e?t$(r,e):void 0!==t&&t$(r,t);let n=t6(r);try{r.fn()}finally{t6(n)}return ai.bind(r)}function ae(e){let t=t6(e);t0(e);try{let t=e.value;return t!==(e.value=e.getter(t))}finally{t6(t),t1(e)}}function at(e,t){return e.flags=1,e.previousValue!==(e.previousValue=t)}function aa(){for(;t9<t5;){let e=tZ[t9];tZ[t9++]=void 0,function e(t,a){if(16&a||32&a&&tX(t.deps,t)){let e=t6(t);t0(t);try{t.fn()}finally{t6(e),t1(t)}return}32&a&&(t.flags=-33&a);let r=t.deps;for(;void 0!==r;){let t=r.dep,a=t.flags;64&a&&e(t,t.flags=-65&a),r=r.nextDep}}(e,e.flags&=-65)}t9=0,t5=0}function ar(){let a=this.flags;if(16&a||32&a&&tX(this.deps,this)){if(ae(this)){let e=this.subs;void 0!==e&&t2(e)}}else 32&a&&(this.flags=-33&a);return void 0!==e?t$(this,e):void 0!==t&&t$(this,t),this.value}function an(...t){if(t.length){let e=t[0];if(this.value!==(this.value=e)){this.flags=17;let e=this.subs;void 0!==e&&(tQ(e),t3||aa())}}else{let t=this.value;if(16&this.flags&&at(this,t)){let e=this.subs;void 0!==e&&t2(e)}return void 0!==e&&t$(this,e),t}}function ai(){let e=this.deps;for(;void 0!==e;)e=tY(e,this);let t=this.subs;void 0!==t&&tY(t),this.flags=0}function as(e){let{pageSize:t,initialPage:a,...r}=e||{},n=t??10;return new URLSearchParams({...Object.entries(r).reduce((e,[t,a])=>(void 0!==a&&(e[t]=a),e),{}),limit:n+"",offset:((a??1)-1)*n+""})}class ao{static #eu="/billing";static path(e,t){let{orgId:a}=t||{},r=a?`/organizations/${a}`:"/me";return`${r}${ao.#eu}${e}`}getPlans=async e=>{let{for:t,...a}=e||{},r={...a,payer_type:"organization"===t?"org":"user"};return await tH._fetch({path:`${ao.#eu}/plans`,method:"GET",search:as(r)}).then(e=>{let{data:t,total_count:a}=e;return{total_count:a,data:t.map(e=>new aE(e))}})};getPlan=async e=>new aE(await tH._fetch({path:`${ao.#eu}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await tH._fetch({path:ao.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new aC(e?.response));getStatements=async e=>{let{orgId:t,...a}=e;return await tH._fetch({path:ao.path("/statements",{orgId:t}),method:"GET",search:as(a)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new aA(e))}})};getStatement=async e=>new aA((await tH._fetch({path:ao.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:t,...a}=e;return await tH._fetch({path:ao.path("/payment_attempts",{orgId:t}),method:"GET",search:as(a)}).then(e=>{let{data:t,total_count:a}=e;return{total_count:a,data:t.map(e=>new ak(e))}})};getPaymentAttempt=async e=>new ak(await tH._fetch({path:ao.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:t,...a}=e;return new ay((await tH._fetch({path:ao.path("/checkouts",{orgId:t}),method:"POST",body:a}))?.response)}}let al=t8({resource:null}),ac=t8({error:null}),au=t8({status:"idle"}),ad=t4(()=>{let e=al().resource,t=ac().error,a=au().status;return{errors:ag(t,{identifier:null,password:null,code:null}),fetchStatus:a,signIn:e?e.__internal_future:null}}),ah=t8({resource:null}),am=t8({error:null}),ap=t8({status:"idle"}),af=t4(()=>{let e=ah().resource,t=am().error,a=ap().status;return{errors:ag(t,{firstName:null,lastName:null,emailAddress:null,phoneNumber:null,password:null,username:null,code:null,captcha:null,legalAccepted:null}),fetchStatus:a,signUp:e?e.__internal_future:null}});function ag(e,t){let a={fields:{...t},raw:null,global:null};if(!e)return a;if(!M(e))return a.raw=[e],a.global=[F(e)],a;function r(e){return"meta"in e&&e.meta&&"paramName"in e.meta&&void 0!==e.meta.paramName}return e.errors.some(r)?e.errors.forEach(e=>{if(a.raw?a.raw.push(e):a.raw=[e],r(e)){let t=ea(e.meta.paramName);t in a.fields&&(a.fields[t]=e)}}):(a.raw=[e],a.global=[F(e)]),a}class ab extends tH{id;createdAt;updatedAt;imageUrl;userId=null;email;firstName;lastName;organizationId=null;organizationName;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,e.created_at&&(this.createdAt=tV(e.created_at)),e.updated_at&&(this.updatedAt=tV(e.updated_at)),this.imageUrl=e.image_url,this.userId=e.user_id,this.email=e.email,this.firstName=e.first_name,this.lastName=e.last_name,this.organizationId=e.organization_id,this.organizationName=e.organization_name),this}}class ay extends tH{id;externalClientSecret;externalGatewayId;paymentMethod;plan;planPeriod;planPeriodStart;status;totals;isImmediatePlanChange;freeTrialEndsAt;payer;needsPaymentMethod;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.externalClientSecret=e.external_client_secret,this.externalGatewayId=e.external_gateway_id,this.paymentMethod=e.payment_method?new az(e.payment_method):void 0,this.plan=new aE(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=tm(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change,e.free_trial_ends_at&&(this.freeTrialEndsAt=tV(e.free_trial_ends_at)),this.payer=new ab(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>tl(()=>this._basePatch({path:ao.path(`/checkouts/${this.id}/confirm`,{orgId:this.payer.organizationId}),body:e}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,t){if(!M(e)||t>=4)return!1;let a=e?.status,r=409===a&&e.errors?.[0]?.code==="checkout_already_in_progress";return a>=500||r}})}class aw{resource=new ay(null);config;signals;pendingOperations=new Map;constructor(e,t){this.config=t,this.signals=e,this.signals.resourceSignal({resource:this})}get status(){return this.resource.status??"needs_initialization"}get externalClientSecret(){return this.resource.externalClientSecret}get externalGatewayId(){return this.resource.externalGatewayId}get plan(){return this.resource.plan}get planPeriod(){return this.resource.planPeriod}get totals(){return this.resource.totals}get isImmediatePlanChange(){return this.resource.isImmediatePlanChange}get freeTrialEndsAt(){return this.resource.freeTrialEndsAt}get payer(){return this.resource.payer}get paymentMethod(){return this.resource.paymentMethod??null}get planPeriodStart(){return this.resource.planPeriodStart}get needsPaymentMethod(){return this.resource.needsPaymentMethod}async start(){return this.runAsyncCheckoutTask("start",async()=>{let e=await ay.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new ay(null),this.signals.resourceSignal({resource:this})})}async confirm(e){if(!this.resource.id)throw Error("Clerk: `start()` must be called before `confirm()`");return this.runAsyncCheckoutTask("confirm",async()=>{await this.resource.confirm(e)})}async finalize(e){let{navigate:t}=e||{};return this.runAsyncCheckoutTask("finalize",async()=>{if("completed"!==this.resource.status)throw Error("Clerk: `confirm()` must be called before `finalize()`");await ay.clerk.setActive({session:ay.clerk.session?.id,navigate:t})})}runAsyncCheckoutTask(e,t,a){var r,n,i;return void 0===ay.clerk.user?(console.warn("Clerk: Checkout operations cannot be performed during transitive state"),{error:null}):(r=this,n=this.signals,i=this.pendingOperations,async(e,t,a)=>{if(i.get(e))return i.get(e);let s=(async()=>{++t3,n.errorSignal({error:null}),n.fetchSignal({status:"fetching"}),a?.(),--t3||aa(),++t3;try{return await t(),n.resourceSignal({resource:r}),{error:null}}catch(e){return n.errorSignal({error:e}),{error:e}}finally{i.delete(e),n.fetchSignal({status:"idle"}),--t3||aa()}})();return i.set(e,s),s})(e,t,a)}}class ak extends tH{id;amount;failedAt=null;paidAt=null;updatedAt;paymentMethod=null;subscriptionItem;chargeType;status;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.amount=th(e.amount),this.paidAt=e.paid_at?tV(e.paid_at):null,this.failedAt=e.failed_at?tV(e.failed_at):null,this.updatedAt=tV(e.updated_at),this.paymentMethod=e.payment_method?new az(e.payment_method):null,this.subscriptionItem=new aP(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status),this}}let av="/payment_methods",ax=async e=>{let{orgId:t,...a}=e;return new aS((await tH._fetch({path:ao.path(`${av}/initialize`,{orgId:t}),method:"POST",body:a}))?.response)},aj=async e=>{let{orgId:t,...a}=e;return new az((await tH._fetch({path:ao.path(av,{orgId:t}),method:"POST",body:a}))?.response)},a_=async e=>{let{orgId:t,...a}=e??{};return await tH._fetch({path:ao.path(av,{orgId:t}),method:"GET",search:as(a)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new az(e))}})};class az extends tH{id;last4=null;paymentType;cardType=null;isDefault;isRemovable;status;walletType;expiryYear;expiryMonth;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.last4=e.last4,this.paymentType=e.payment_type,this.cardType=e.card_type,this.isDefault=e.is_default,this.isRemovable=e.is_removable,this.status=e.status,this.walletType=e.wallet_type,this.expiryYear=e.expiry_year,this.expiryMonth=e.expiry_month,this.createdAt=null==e.created_at?e.created_at:tV(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:tV(e.updated_at)),this}async remove(e){let{orgId:t}=e??{};return new aF((await tH._fetch({path:ao.path(`/payment_methods/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:t}=e??{};return await tH._fetch({path:ao.path("/payers/default_payment_method",{orgId:t}),method:"PUT",body:{payment_method_id:this.id}}),null}}class aS extends tH{externalClientSecret;externalGatewayId;paymentMethodOrder;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.externalClientSecret=e.external_client_secret,this.externalGatewayId=e.external_gateway_id,this.paymentMethodOrder=e.payment_method_order??["card"]),this}}class aE extends tH{id;name;fee;annualFee=null;annualMonthlyFee=null;description=null;isDefault;isRecurring;hasBaseFee;forPayerType;publiclyVisible;slug;avatarUrl=null;features;freeTrialDays;freeTrialEnabled;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.fee=th(e.fee),this.annualFee=e.annual_fee?th(e.annual_fee):null,this.annualMonthlyFee=e.annual_monthly_fee?th(e.annual_monthly_fee):null,this.description=e.description,this.isDefault=e.is_default,this.isRecurring=e.is_recurring,this.hasBaseFee=e.has_base_fee,this.forPayerType=e.for_payer_type,this.publiclyVisible=e.publicly_visible,this.slug=e.slug,this.avatarUrl=e.avatar_url,this.freeTrialDays=this.withDefault(e.free_trial_days,null),this.freeTrialEnabled=this.withDefault(e.free_trial_enabled,!1),this.features=(e.features||[]).map(e=>new rc(e))),this}}class aA extends tH{id;status;timestamp;totals;groups;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.timestamp=tV(e.timestamp),this.totals=tm(e.totals),this.groups=e.groups.map(e=>new aI(e))),this}}class aI{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=tV(e.timestamp),this.items=e.items.map(e=>new ak(e))),this}}class aC extends tH{id;status;activeAt;createdAt;pastDueAt;updatedAt;nextPayment;subscriptionItems;eligibleForFreeTrial;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.createdAt=tV(e.created_at),this.updatedAt=e.updated_at?tV(e.updated_at):null,this.activeAt=tV(e.active_at),this.pastDueAt=e.past_due_at?tV(e.past_due_at):null,e.next_payment&&(this.nextPayment={amount:th(e.next_payment.amount),date:tV(e.next_payment.date)}),this.subscriptionItems=(e.subscription_items||[]).map(e=>new aP(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1)),this}}class aP extends tH{id;plan;planPeriod;status;createdAt;periodStart;periodEnd;canceledAt;pastDueAt;amount;credit;isFreeTrial;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.plan=new aE(e.plan),this.planPeriod=e.plan_period,this.status=e.status,this.createdAt=tV(e.created_at),this.pastDueAt=e.past_due_at?tV(e.past_due_at):null,this.periodStart=tV(e.period_start),this.periodEnd=e.period_end?tV(e.period_end):null,this.canceledAt=e.canceled_at?tV(e.canceled_at):null,this.amount=e.amount?th(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:th(e.credit.amount)}:void 0,this.isFreeTrial=this.withDefault(e.is_free_trial,!1)),this}async cancel(e){let{orgId:t}=e;return new aF((await tH._fetch({path:ao.path(`/subscription_items/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}}let aq={build:(e,t,a)=>[e,t,a].filter(Boolean).join("-"),parse:(e,t,a)=>{let r=aq.extractTemplate(e,t,a);return{organizationId:a,sessionId:t,template:r}},extractTemplate:(e,t,a)=>{if(e===t||a&&e===`${t}-${a}`)return;let r=e.slice(t.length+1);return a&&r.endsWith(`-${a}`)&&(r=r.slice(0,-(a.length+1))),r||void 0}},aO="clerk",aT=10,aU={broadcast:!0},aM={broadcast:!1};class aR{prefix;data;static fromKey(e){let[t,a,r=""]=e.split("::");return new aR(t,{audience:r,tokenId:a})}constructor(e,t){this.prefix=e,this.data=t,this.prefix=e,this.data=t}toKey(){let{tokenId:e,audience:t}=this.data;return[this.prefix,e,t||""].join("::")}}let aB=((e=aO)=>{let t=new Map,a=Math.random().toString(36).slice(2),r=null,n=()=>r||("undefined"==typeof BroadcastChannel?null:((r=new BroadcastChannel("clerk:session_token")).addEventListener("message",e=>{s(e)}),r));n();let i=(a,r=aT)=>{n();let i=new aR(e,a),s=t.get(i.toKey());if(!s)return;let o=Math.floor(Date.now()/1e3)-s.createdAt;if(s.expiresIn-o<(r||1)+5){void 0!==s.timeoutId&&clearTimeout(s.timeoutId),t.delete(i.toKey());return}return s.entry},s=async({data:e})=>{let t,r=aq.build(e.sessionId,e.template,e.organizationId);if(e.tokenId!==r)return void tn.warn("Ignoring token broadcast with mismatched tokenId",{expectedTokenId:r,organizationId:e.organizationId,receivedTokenId:e.tokenId,tabId:a,template:e.template,traceId:e.traceId},"tokenCache");try{t=new rJ({id:e.tokenId,jwt:e.tokenRaw,object:"token"})}catch(t){tn.warn("Failed to parse token from broadcast, skipping cache update",{error:t,tabId:a,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");return}let n=t.jwt?.claims?.iat,s=t.jwt?.claims?.exp;if(!n||!s)return void tn.warn("Token missing iat/exp claim, skipping cache update",{tabId:a,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");try{let t=i({tokenId:e.tokenId});if(t){let r=await t.tokenResolver,i=r.jwt?.claims?.iat;if(i&&i>=n)return void tn.debug("Ignoring older token broadcast",{existingIat:i,incomingIat:n,tabId:a,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}}catch(t){tn.warn("Existing entry compare failed; proceeding with broadcast update",{error:t,tabId:a,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}tn.info("Updating token cache from broadcast",{iat:n,organizationId:e.organizationId,tabId:a,template:e.template,tokenId:e.tokenId,traceId:e.traceId},"tokenCache"),o({createdAt:n,tokenId:e.tokenId,tokenResolver:Promise.resolve(t)},aM)},o=(n,i=aU)=>{let s=new aR(e,{audience:n.audience,tokenId:n.tokenId}).toKey(),o=Math.floor(Date.now()/1e3),l={createdAt:n.createdAt??o,entry:n,expiresIn:void 0},c=()=>{let e=t.get(s);e===l&&(void 0!==e.timeoutId&&clearTimeout(e.timeoutId),t.delete(s))};n.tokenResolver.then(e=>{let t=e.jwt?.claims;if(!t||"number"!=typeof t.exp||"number"!=typeof t.iat)return c();let s=t.exp-t.iat;l.expiresIn=s;let o=setTimeout(c,1e3*s);l.timeoutId=o,"function"==typeof o.unref&&o.unref();let u=r;if(u&&i.broadcast){let r=e.getRawString();if(r&&t.sid){let e=t.sid,i=t.org_id||t.o?.id,s=aq.extractTemplate(n.tokenId,e,i),o=aq.build(e,s,i);if(n.tokenId===o){let t=`bc_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;tn.info("Broadcasting token update to other tabs",{organizationId:i,sessionId:e,tabId:a,template:s,tokenId:n.tokenId,traceId:t},"tokenCache");let o={organizationId:i,sessionId:e,template:s,tokenId:n.tokenId,tokenRaw:r,traceId:t};u.postMessage(o)}}}}).catch(()=>{c()}),t.set(s,l)};return{clear:()=>{t.forEach(e=>{void 0!==e.timeoutId&&clearTimeout(e.timeoutId)}),t.clear()},close:()=>{r&&(r.close(),r=null)},get:i,set:e=>{n(),o(e,aU)},size:()=>t.size}})();class aN extends tH{static instance;pathRoot="/client";sessions=[];signUp=new rH;signIn=new rL;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return aN.instance||(aN.instance=new aN(e)),aN.instance}static clearInstance(){aN.instance=null}static isClientResource(e){return!!e&&e instanceof aN}constructor(e=null){super(),this.fromJSON(e)}get signUpAttempt(){return this.signUp}get signInAttempt(){return this.signIn}get signedInSessions(){return this.sessions.filter(e=>"active"===e.status||"pending"===e.status)}create(){return this._basePut()}fetch({fetchMaxTries:e}={}){return this._baseGet({fetchMaxTries:e})}async destroy(){return this._baseDelete({path:"/client"}).then(()=>{aB.clear(),this.id="",this.sessions=[],this.signUp=new rH(null),this.signIn=new rL(null),this.lastActiveSessionId=null,this.lastAuthenticationStrategy=null,this.cookieExpiresAt=null,this.createdAt=null,this.updatedAt=null})}removeSessions(){return this._baseDelete({path:this.path()+"/sessions"}).then(e=>(aB.clear(),e))}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return tH.fapiClient.buildUrl({method:"GET",path:"/client/touch",pathPrefix:"v1",search:{redirect_url:e.toString()}}).toString()}__internal_sendCaptchaToken(e){return this._basePostBypass({body:e,path:this.path()+"/verify"})}fromJSON(e){return e&&(this.id=e.id,this.sessions=(e.sessions||[]).map(e=>new rO(e)),this.signUp=new rH(e.sign_up),this.signIn=new rL(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?tV(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=tV(e.created_at||void 0),this.updatedAt=tV(e.updated_at||void 0)),this}__internal_toSnapshot(){return{object:"client",id:this.id||"",sessions:this.sessions.map(e=>e.__internal_toSnapshot()),sign_up:this.signUp.__internal_toSnapshot(),sign_in:this.signIn.__internal_toSnapshot(),last_active_session_id:this.lastActiveSessionId,captcha_bypass:this.captchaBypass,cookie_expires_at:this.cookieExpiresAt?this.cookieExpiresAt.getTime():null,last_authentication_strategy:this.lastAuthenticationStrategy??null,created_at:this.createdAt?.getTime()??null,updated_at:this.updatedAt?.getTime()??null}}path(){return this.pathRoot}}class aD extends tH{billing={stripePublishableKey:null,organization:{enabled:!1,hasPaidPlans:!1},user:{enabled:!1,hasPaidPlans:!1}};constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.billing.stripePublishableKey=e.billing.stripe_publishable_key,this.billing.organization.enabled=e.billing.organization.enabled,this.billing.organization.hasPaidPlans=e.billing.organization.has_paid_plans,this.billing.user.enabled=e.billing.user.enabled,this.billing.user.hasPaidPlans=e.billing.user.has_paid_plans),this}__internal_toSnapshot(){return{billing:{stripe_publishable_key:this.billing.stripePublishableKey,organization:{enabled:this.billing.organization.enabled,has_paid_plans:this.billing.organization.hasPaidPlans},user:{enabled:this.billing.user.enabled,has_paid_plans:this.billing.user.hasPaidPlans}}}}}class aF{object="";id;slug;deleted=!1;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.object=e.object,this.id=e.id,this.slug=e.slug,this.deleted=e.deleted),this}}class aL extends tH{afterCreateOrganizationUrl="";afterJoinWaitlistUrl="";afterLeaveOrganizationUrl="";afterSignInUrl="";afterSignOutAllUrl="";afterSignOutOneUrl="";afterSignOutUrl="";afterSignUpUrl="";afterSwitchSessionUrl="";applicationName="";backendHost="";branded=!1;captchaHeartbeat=!1;captchaHeartbeatIntervalMs;captchaOauthBypass=["oauth_google","oauth_microsoft","oauth_apple"];captchaProvider="turnstile";captchaPublicKey=null;captchaPublicKeyInvisible=null;captchaWidgetType=null;clerkJSVersion;createOrganizationUrl="";faviconImageUrl="";googleOneTapClientId;homeUrl="";id="";instanceEnvironmentType="";logoImageUrl="";organizationProfileUrl="";preferredSignInStrategy="password";privacyPolicyUrl="";showDevModeWarning=!1;signInUrl="";signUpUrl="";supportEmail="";termsUrl="";theme={};userProfileUrl="";waitlistUrl="";constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.afterCreateOrganizationUrl=this.withDefault(e.after_create_organization_url,this.afterCreateOrganizationUrl),this.afterJoinWaitlistUrl=this.withDefault(e.after_join_waitlist_url,this.afterJoinWaitlistUrl),this.afterLeaveOrganizationUrl=this.withDefault(e.after_leave_organization_url,this.afterLeaveOrganizationUrl),this.afterSignInUrl=this.withDefault(e.after_sign_in_url,this.afterSignInUrl),this.afterSignOutAllUrl=this.withDefault(e.after_sign_out_all_url,this.afterSignOutAllUrl),this.afterSignOutOneUrl=this.withDefault(e.after_sign_out_one_url,this.afterSignOutOneUrl),this.afterSignUpUrl=this.withDefault(e.after_sign_up_url,this.afterSignUpUrl),this.afterSwitchSessionUrl=this.withDefault(e.after_switch_session_url,this.afterSwitchSessionUrl),this.applicationName=this.withDefault(e.application_name,this.applicationName),this.branded=this.withDefault(e.branded,this.branded),this.captchaHeartbeat=this.withDefault(e.captcha_heartbeat,this.captchaHeartbeat),this.captchaHeartbeatIntervalMs=this.withDefault(e.captcha_heartbeat_interval_ms,this.captchaHeartbeatIntervalMs),this.captchaOauthBypass=this.withDefault(e.captcha_oauth_bypass,this.captchaOauthBypass),this.captchaProvider=this.withDefault(e.captcha_provider,this.captchaProvider),this.captchaPublicKey=this.withDefault(e.captcha_public_key,this.captchaPublicKey),this.captchaPublicKeyInvisible=this.withDefault(e.captcha_public_key_invisible,this.captchaPublicKeyInvisible),this.captchaWidgetType=this.withDefault(e.captcha_widget_type,this.captchaWidgetType),this.clerkJSVersion=this.withDefault(e.clerk_js_version,this.clerkJSVersion),this.createOrganizationUrl=this.withDefault(e.create_organization_url,this.createOrganizationUrl),this.faviconImageUrl=this.withDefault(e.favicon_image_url,this.faviconImageUrl),this.googleOneTapClientId=this.withDefault(e.google_one_tap_client_id,this.googleOneTapClientId),this.homeUrl=this.withDefault(e.home_url,this.homeUrl),this.id=this.withDefault(e.id,this.id),this.instanceEnvironmentType=this.withDefault(e.instance_environment_type,this.instanceEnvironmentType),this.logoImageUrl=this.withDefault(e.logo_image_url,this.logoImageUrl),this.organizationProfileUrl=this.withDefault(e.organization_profile_url,this.organizationProfileUrl),this.preferredSignInStrategy=this.withDefault(e.preferred_sign_in_strategy,this.preferredSignInStrategy),this.privacyPolicyUrl=this.withDefault(e.privacy_policy_url,this.privacyPolicyUrl),this.showDevModeWarning=this.withDefault(e.show_devmode_warning,this.showDevModeWarning),this.signInUrl=this.withDefault(e.sign_in_url,this.signInUrl),this.signUpUrl=this.withDefault(e.sign_up_url,this.signUpUrl),this.supportEmail=this.withDefault(e.support_email,this.supportEmail),this.termsUrl=this.withDefault(e.terms_url,this.termsUrl),this.theme=this.withDefault(e.theme,this.theme),this.userProfileUrl=this.withDefault(e.user_profile_url,this.userProfileUrl),this.waitlistUrl=this.withDefault(e.waitlist_url,this.waitlistUrl)),this}__internal_toSnapshot(){return{object:"display_config",after_create_organization_url:this.afterCreateOrganizationUrl,after_join_waitlist_url:this.afterJoinWaitlistUrl,after_leave_organization_url:this.afterLeaveOrganizationUrl,after_sign_in_url:this.afterSignInUrl,after_sign_out_all_url:this.afterSignOutAllUrl,after_sign_out_one_url:this.afterSignOutOneUrl,after_sign_up_url:this.afterSignUpUrl,after_switch_session_url:this.afterSwitchSessionUrl,application_name:this.applicationName,branded:this.branded,captcha_heartbeat_interval_ms:this.captchaHeartbeatIntervalMs,captcha_heartbeat:this.captchaHeartbeat,captcha_oauth_bypass:this.captchaOauthBypass,captcha_provider:this.captchaProvider,captcha_public_key_invisible:this.captchaPublicKeyInvisible,captcha_public_key:this.captchaPublicKey,captcha_widget_type:this.captchaWidgetType,clerk_js_version:this.clerkJSVersion,create_organization_url:this.createOrganizationUrl,favicon_image_url:this.faviconImageUrl,google_one_tap_client_id:this.googleOneTapClientId,home_url:this.homeUrl,id:this.id,instance_environment_type:this.instanceEnvironmentType,logo_image_url:this.logoImageUrl,organization_profile_url:this.organizationProfileUrl,preferred_sign_in_strategy:this.preferredSignInStrategy,privacy_policy_url:this.privacyPolicyUrl,show_devmode_warning:this.showDevModeWarning,sign_in_url:this.signInUrl,sign_up_url:this.signUpUrl,support_email:this.supportEmail,terms_url:this.termsUrl,theme:this.theme,user_profile_url:this.userProfileUrl,waitlist_url:this.waitlistUrl}}}var aW='const respond=r=>{self.postMessage(r)},workerToTabIds={};self.addEventListener("message",r=>{const e=r.data;switch(e.type){case"setTimeout":workerToTabIds[e.id]=setTimeout(()=>{respond({id:e.id}),delete workerToTabIds[e.id]},e.ms);break;case"clearTimeout":workerToTabIds[e.id]&&(clearTimeout(workerToTabIds[e.id]),delete workerToTabIds[e.id]);break;case"setInterval":workerToTabIds[e.id]=setInterval(()=>{respond({id:e.id})},e.ms);break;case"clearInterval":workerToTabIds[e.id]&&(clearInterval(workerToTabIds[e.id]),delete workerToTabIds[e.id]);break}});\n';let aK=(e,t={})=>{if("undefined"==typeof Worker)return null;try{let a=new Blob([e],{type:"application/javascript; charset=utf-8"}),r=globalThis.URL.createObjectURL(a);return new Worker(r,t)}catch{return console.warn("Clerk: Cannot create worker from blob. Consider adding worker-src blob:; to your CSP"),null}},aH=()=>{let e=0,t=()=>e++,a=new Map,r=(e,t)=>e?.postMessage(t),n=e=>{a.get(e.data.id)?.()},i=aK(aW,{name:"clerk-timers"});if(i?.addEventListener("message",n),!i)return{setTimeout:globalThis.setTimeout.bind(globalThis),setInterval:globalThis.setInterval.bind(globalThis),clearTimeout:globalThis.clearTimeout.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis),cleanup:e8};let s=()=>{i||(i=aK(aW,{name:"clerk-timers"}),i?.addEventListener("message",n))};return{setTimeout:(e,n)=>{s();let o=t();return a.set(o,()=>{e(),a.delete(o)}),r(i,{type:"setTimeout",id:o,ms:n}),o},setInterval:(e,n)=>{s();let o=t();return a.set(o,e),r(i,{type:"setInterval",id:o,ms:n}),o},clearTimeout:e=>{s(),a.delete(e),r(i,{type:"clearTimeout",id:e})},clearInterval:e=>{s(),a.delete(e),r(i,{type:"clearInterval",id:e})},cleanup:()=>{i&&(i.terminate(),i=null,a.clear())}}};function aV({delayInMs:e}={delayInMs:1e3}){let t,a=aH(),r=!1,n=()=>{t&&(a.clearTimeout(t),a.cleanup()),r=!0},i=async s=>{r=!1,await s(n),r||(t=a.setTimeout(()=>{i(s)},e))};return{run:i,stop:n}}class aG extends tH{id;emailAddress="";matchesSsoConnection=!1;linkedTo=[];verification;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}create(){return this._basePost({body:{email_address:this.emailAddress}})}prepareVerification=e=>this._basePost({action:"prepare_verification",body:{...e}});attemptVerification=e=>{let{code:t}=e||{};return this._basePost({action:"attempt_verification",body:{code:t}})};createEmailLinkFlow=()=>{let{run:e,stop:t}=aV();return{startEmailLinkFlow:async({redirectUrl:a})=>(await this.prepareVerification({strategy:"email_link",redirectUrl:a}),new Promise((a,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),a(e))}).catch(e=>{t(),r(e)}))})),cancelEmailLinkFlow:t}};createEnterpriseSSOLinkFlow=()=>{let{run:e,stop:t}=aV();return{startEnterpriseSSOLinkFlow:async({redirectUrl:a})=>{if(!(await this.prepareVerification({strategy:"enterprise_sso",redirectUrl:a})).verification.externalVerificationRedirectURL)throw Error("Unexpected: External verification redirect URL is missing");return new Promise((a,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),a(e))}).catch(e=>{t(),r(e)}))})},cancelEnterpriseSSOLinkFlow:t}};destroy=()=>this._baseDelete();toString=()=>this.emailAddress;fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.verification=new a9(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new ru(e))),this}__internal_toSnapshot(){return{object:"email_address",id:this.id,email_address:this.emailAddress,verification:this.verification.__internal_toSnapshot(),linked_to:this.linkedTo.map(e=>e.__internal_toSnapshot()),matches_sso_connection:this.matchesSsoConnection}}}var aJ=class{static encode(e){return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}static decode(e){let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),a=t.length,r=new Uint8Array(a);for(let e=0;e<a;e++)r[e]=t.charCodeAt(e);return r.buffer}};async function aZ(e){try{let t=await navigator.credentials.create({publicKey:e});if(!t)return{error:new q("Browser failed to create credential",{code:"passkey_registration_failed"}),publicKeyCredential:null};return{publicKeyCredential:t,error:null}}catch(e){var t;return{error:"InvalidStateError"===(t=e).name?new q(t.message,{code:"passkey_already_exists"}):"NotAllowedError"===t.name?new q(t.message,{code:"passkey_registration_cancelled"}):aQ(t),publicKeyCredential:null}}}let a$=new class{controller;__abort(){if(!this.controller)return;let e=Error();e.name="AbortError",this.controller.abort(e)}createAbortSignal(){this.__abort();let e=new AbortController;return this.controller=e,e.signal}abort(){this.__abort(),this.controller=void 0}};async function aY({publicKeyOptions:e,conditionalUI:t}){try{let a=await navigator.credentials.get({publicKey:e,mediation:t?"conditional":"optional",signal:a$.createAbortSignal()});if(!a)return{error:new q("Browser failed to get credential",{code:"passkey_retrieval_failed"}),publicKeyCredential:null};return{publicKeyCredential:a,error:null}}catch(e){var a;return{error:"NotAllowedError"===(a=e).name?new q(a.message,{code:"passkey_retrieval_cancelled"}):aQ(a),publicKeyCredential:null}}}function aQ(e){return"AbortError"===e.name?new q(e.message,{code:"passkey_operation_aborted"}):"SecurityError"===e.name?new q(e.message,{code:"passkey_invalid_rpID_or_domain"}):e}function aX(e){let t=a3(e.challenge),a=(e.allowCredentials||[]).map(e=>({...e,id:a3(e.id)}));return{...e,allowCredentials:a,challenge:t}}function a1(e){return{type:e.type,id:e.id,rawId:a2(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function a0(e){let t=e.response;return{...a1(e),response:{clientDataJSON:a2(t.clientDataJSON),authenticatorData:a2(t.authenticatorData),signature:a2(t.signature),userHandle:t.userHandle?a2(t.userHandle):null}}}let a2=aJ.encode.bind(aJ),a3=aJ.decode.bind(aJ);class a9 extends tH{pathRoot="";status=null;strategy=null;nonce=null;message=null;externalVerificationRedirectURL=null;attempts=null;expireAt=null;error=null;verifiedAtClient=null;channel;constructor(e){super(),this.fromJSON(e)}verifiedFromTheSameClient=()=>this.verifiedAtClient===tH.clerk?.client?.id;fromJSON(e){return e&&(this.status=e.status,this.verifiedAtClient=e.verified_at_client,this.strategy=e.strategy,this.nonce=e.nonce||null,this.message=e.message||null,e.external_verification_redirect_url?this.externalVerificationRedirectURL=new URL(e.external_verification_redirect_url):this.externalVerificationRedirectURL=null,this.attempts=e.attempts,this.expireAt=tV(e.expire_at||void 0),this.error=e.error?new v(e.error):null,this.channel=e.channel||void 0),this}__internal_toSnapshot(){var e;return{object:"verification",id:this.id||"",status:this.status,strategy:this.strategy,nonce:this.nonce,message:this.message,external_verification_redirect_url:this.externalVerificationRedirectURL?.toString()||null,attempts:this.attempts,expire_at:this.expireAt?.getTime()||null,error:(e=this.error,{code:e?.code||"",message:e?.message||"",long_message:e?.longMessage,meta:{param_name:e?.meta?.paramName,session_id:e?.meta?.sessionId,email_addresses:e?.meta?.emailAddresses,identifiers:e?.meta?.identifiers,zxcvbn:e?.meta?.zxcvbn,plan:e?.meta?.plan,is_plan_upgrade_possible:e?.meta?.isPlanUpgradePossible}}),verified_at_client:this.verifiedAtClient}}}class a5 extends a9{publicKey=null;constructor(e){super(e),this.fromJSON(e)}fromJSON(e){var t;let a,r,n;return super.fromJSON(e),e?.nonce&&(this.publicKey=(a=a3((t=JSON.parse(e.nonce)).user.id),r=a3(t.challenge),n=(t.excludeCredentials||[]).map(e=>({...e,id:a3(e.id)})),{...t,excludeCredentials:n,challenge:r,user:{...t.user,id:a}})),this}}class a6{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new a8(e.email_address),this.phoneNumber=new a8(e.phone_number),this.web3Wallet=new a8(e.web3_wallet),this.externalAccount=new a9(e.external_account)):(this.emailAddress=new a8(null),this.phoneNumber=new a8(null),this.web3Wallet=new a8(null),this.externalAccount=new a9(null))}__internal_toSnapshot(){return{email_address:this.emailAddress.__internal_toSnapshot(),phone_number:this.phoneNumber.__internal_toSnapshot(),web3_wallet:this.web3Wallet.__internal_toSnapshot(),external_account:this.externalAccount.__internal_toSnapshot()}}}class a8 extends a9{nextAction;supportedStrategies;constructor(e){super(e),e?(this.nextAction=e.next_action,this.supportedStrategies=e.supported_strategies):(this.nextAction="",this.supportedStrategies=[])}__internal_toSnapshot(){return{...super.__internal_toSnapshot(),next_action:this.nextAction,supported_strategies:this.supportedStrategies}}}class a4 extends tH{id;protocol;provider;providerUserId=null;active;emailAddress="";firstName="";lastName="";publicMetadata={};verification=null;enterpriseConnection=null;lastAuthenticatedAt=null;enterpriseConnectionId=null;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.provider=e.provider,this.protocol=e.protocol,this.providerUserId=e.provider_user_id,this.active=e.active,this.emailAddress=e.email_address,this.firstName=e.first_name,this.lastName=e.last_name,this.publicMetadata=e.public_metadata,this.lastAuthenticatedAt=e.last_authenticated_at?tV(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new a9(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new a7(e.enterprise_connection))),this}__internal_toSnapshot(){return{object:"enterprise_account",id:this.id,provider:this.provider,protocol:this.protocol,provider_user_id:this.providerUserId,active:this.active,email_address:this.emailAddress,first_name:this.firstName,last_name:this.lastName,public_metadata:this.publicMetadata,verification:this.verification?.__internal_toSnapshot()||null,enterprise_connection:this.enterpriseConnection?.__internal_toSnapshot()||null,last_authenticated_at:this.lastAuthenticatedAt?this.lastAuthenticatedAt.getTime():null,enterprise_connection_id:this.enterpriseConnectionId}}}class a7 extends tH{id;active;allowIdpInitiated;allowSubdomains;disableAdditionalIdentifications;domain;logoPublicUrl="";name;protocol;provider;syncUserAttributes;createdAt;updatedAt;enterpriseConnectionId="";constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.domain=e.domain,this.active=e.active,this.provider=e.provider,this.logoPublicUrl=e.logo_public_url,this.syncUserAttributes=e.sync_user_attributes,this.allowSubdomains=e.allow_subdomains,this.allowIdpInitiated=e.allow_idp_initiated,this.disableAdditionalIdentifications=e.disable_additional_identifications,this.createdAt=tV(e.created_at),this.updatedAt=tV(e.updated_at),this.enterpriseConnectionId=e.enterprise_connection_id),this}__internal_toSnapshot(){return{object:"enterprise_account_connection",id:this.id,name:this.name,domain:this.domain,active:this.active,protocol:this.protocol,provider:this.provider,logo_public_url:this.logoPublicUrl,sync_user_attributes:this.syncUserAttributes,allow_subdomains:this.allowSubdomains,allow_idp_initiated:this.allowIdpInitiated,disable_additional_identifications:this.disableAdditionalIdentifications,enterprise_connection_id:this.enterpriseConnectionId,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}let re="token:update",rt="user:signOut",ra="environment:update",rr="session:tokenResolved",rn=f();class ri extends tH{user_api_keys_enabled=!1;orgs_api_keys_enabled=!1;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.user_api_keys_enabled=e.user_api_keys_enabled,this.orgs_api_keys_enabled=e.orgs_api_keys_enabled),this}__internal_toSnapshot(){return{user_api_keys_enabled:this.user_api_keys_enabled,orgs_api_keys_enabled:this.orgs_api_keys_enabled}}}class rs extends tH{actions={adminDelete:!1};domains={enabled:!1,enrollmentModes:[],defaultRole:null};slug={disabled:!1};enabled=!1;maxAllowedMemberships=1;forceOrganizationSelection;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(e.actions&&(this.actions.adminDelete=this.withDefault(e.actions.admin_delete,this.actions.adminDelete)),e.domains&&(this.domains.enabled=this.withDefault(e.domains.enabled,this.domains.enabled),this.domains.enrollmentModes=this.withDefault(e.domains.enrollment_modes,this.domains.enrollmentModes),this.domains.defaultRole=this.withDefault(e.domains.default_role,this.domains.defaultRole)),e.slug&&(this.slug.disabled=this.withDefault(e.slug.disabled,this.slug.disabled)),this.enabled=this.withDefault(e.enabled,this.enabled),this.maxAllowedMemberships=this.withDefault(e.max_allowed_memberships,this.maxAllowedMemberships),this.forceOrganizationSelection=this.withDefault(e.force_organization_selection,this.forceOrganizationSelection)),this}__internal_toSnapshot(){return{actions:{admin_delete:this.actions.adminDelete},domains:{enabled:this.domains.enabled,enrollment_modes:this.domains.enrollmentModes,default_role:this.domains.defaultRole},enabled:this.enabled,max_allowed_memberships:this.maxAllowedMemberships}}}class ro extends tH{static instance;authConfig=new tJ;displayConfig=new aL;maintenanceMode=!1;clientDebugMode=!1;pathRoot="/environment";userSettings=new r0;organizationSettings=new rs;commerceSettings=new aD;apiKeysSettings=new ri;protectConfig=new rz;static getInstance(){return ro.instance||(ro.instance=new ro),ro.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new tJ(e.auth_config),this.displayConfig=new aL(e.display_config),this.maintenanceMode=this.withDefault(e.maintenance_mode,this.maintenanceMode),this.clientDebugMode=this.withDefault(e.client_debug_mode,this.clientDebugMode),this.organizationSettings=new rs(e.organization_settings),this.userSettings=new r0(e.user_settings),this.commerceSettings=new aD(e.commerce_settings),this.apiKeysSettings=new ri(e.api_keys_settings),this.protectConfig=new rz(e.protect_config)),this}fetch({touch:e,fetchMaxTries:t}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:t})).then(e=>(rn.emit(ra,null),e))}isDevelopmentOrStaging=()=>!this.isProduction();isProduction=()=>"production"===this.displayConfig.instanceEnvironmentType;isSingleSession=()=>this.authConfig.singleSessionMode;onWindowLocationHost=()=>this.displayConfig.backendHost===window.location.host;__internal_toSnapshot(){return{object:"environment",auth_config:this.authConfig.__internal_toSnapshot(),display_config:this.displayConfig.__internal_toSnapshot(),id:this.id??"",maintenance_mode:this.maintenanceMode,client_debug_mode:this.clientDebugMode,organization_settings:this.organizationSettings.__internal_toSnapshot(),user_settings:this.userSettings.__internal_toSnapshot(),commerce_settings:this.commerceSettings.__internal_toSnapshot(),api_keys_settings:this.apiKeysSettings.__internal_toSnapshot(),protect_config:this.protectConfig.__internal_toSnapshot()}}async __internal_enableEnvironmentSetting(e){await this._basePatch({path:"/dev_tools/enable_environment_setting",body:e})}}class rl extends tH{id;identificationId;provider;providerUserId="";emailAddress="";approvedScopes="";firstName="";lastName="";imageUrl="";username="";phoneNumber="";publicMetadata={};label="";verification=null;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}reauthorize=e=>{let{additionalScopes:t,redirectUrl:a}=e||{};return this._basePatch({action:"reauthorize",body:{additional_scope:t,redirect_url:a}})};destroy=()=>this._baseDelete();fromJSON(e){return e&&(this.id=e.id,this.identificationId=e.identification_id,this.providerUserId=e.provider_user_id,this.approvedScopes=e.approved_scopes,this.imageUrl=e.image_url,this.emailAddress=e.email_address,this.firstName=e.first_name,this.lastName=e.last_name,this.provider=(e.provider||"").replace("oauth_",""),this.username=e.username,this.phoneNumber=e.phone_number,this.publicMetadata=e.public_metadata,this.label=e.label,e.verification&&(this.verification=new a9(e.verification))),this}__internal_toSnapshot(){return{object:"external_account",id:this.id,identification_id:this.identificationId,provider:this.provider,provider_user_id:this.providerUserId,email_address:this.emailAddress,approved_scopes:this.approvedScopes,first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl,username:this.username,phone_number:this.phoneNumber,public_metadata:this.publicMetadata,label:this.label,verification:this.verification?.__internal_toSnapshot()||null}}providerSlug(){return this.provider}providerTitle(){let e;return[(e=this.providerSlug()||"").charAt(0).toUpperCase()+e.slice(1),"Account"].join(" ")}accountIdentifier(){return this.username||this.emailAddress||this.label}}class rc extends tH{id;name;description=null;slug;avatarUrl=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.description=e.description,this.slug=e.slug,this.avatarUrl=e.avatar_url),this}}class ru extends tH{id;type;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.type=e.type),this}__internal_toSnapshot(){return{object:"identification_link",id:this.id,type:this.type}}}class rd extends tH{id;name=null;publicUrl=null;static async create(e,t={}){let a,r=t;return"string"==typeof t.file?(r=t.file,a=new Headers({"Content-Type":"application/octet-stream"})):t.file&&(r=new FormData).append("file",t.file),new rd((await tH._fetch({path:e,method:"POST",body:r,headers:a}))?.response)}static async delete(e){return new rd((await tH._fetch({path:e,method:"DELETE"}))?.response)}constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.publicUrl=e.public_url),this}}class rh extends tH{id;name;organizationId;enrollmentMode;verification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:t}){return new rh((await tH._fetch({path:`/organizations/${e}/domains`,method:"POST",body:{name:t}}))?.response)}prepareAffiliationVerification=async e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/prepare_affiliation_verification`,method:"POST",body:e});attemptAffiliationVerification=async e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/attempt_affiliation_verification`,method:"POST",body:e});updateEnrollmentMode=e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/update_enrollment_mode`,body:e});delete=()=>this._baseDelete({path:`/organizations/${this.organizationId}/domains/${this.id}`});fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.organizationId=e.organization_id,this.enrollmentMode=e.enrollment_mode,this.affiliationEmailAddress=e.affiliation_email_address,this.totalPendingSuggestions=e.total_pending_suggestions,this.totalPendingInvitations=e.total_pending_invitations,e.verification?this.verification={status:e.verification.status,strategy:e.verification.strategy,attempts:e.verification.attempts,expiresAt:tV(e.verification.expires_at)}:this.verification=null),this}}class rm extends tH{id;organizationId;status;publicUserData;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}accept=async()=>await this._basePost({path:`/organizations/${this.organizationId}/membership_requests/${this.id}/accept`});reject=async()=>await this._basePost({path:`/organizations/${this.organizationId}/membership_requests/${this.id}/reject`});fromJSON(e){return e&&(this.id=e.id,this.organizationId=e.organization_id,this.status=e.status,this.createdAt=tV(e.created_at),this.updatedAt=tV(e.updated_at),e.public_user_data&&(this.publicUserData=new rS(e.public_user_data))),this}}class rp extends tH{id;key;name;description;type;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.key=e.key,this.name=e.name,this.description=e.description,this.type=e.type,this.createdAt=tV(e.created_at),this.updatedAt=tV(e.updated_at)),this}}class rf extends tH{id;key;name;description;permissions=[];createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.key=e.key,this.name=e.name,this.description=e.description,this.permissions=e.permissions.map(e=>new rp(e)),this.createdAt=tV(e.created_at),this.updatedAt=tV(e.updated_at)),this}}class rg extends tH{pathRoot="/organizations";id;name;slug;imageUrl;hasImage;publicMetadata={};adminDeleteEnabled;createdAt;updatedAt;membersCount=0;pendingInvitationsCount=0;maxAllowedMemberships;constructor(e){super(),this.fromJSON(e)}static async create(e){return new rg((await tH._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new rg((await tH._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await tH._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:as(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rf(e))}});getDomains=async e=>await tH._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:as(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rh(e))}});getDomain=async({domainId:e})=>new rh((await tH._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getMembershipRequests=async e=>await tH._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:as(e)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rm(e))}});createDomain=async e=>rh.create(this.id,{name:e});getMemberships=async e=>await tH._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:as({...e,paginated:!0})}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new ry(e))}});getInvitations=async e=>await tH._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:as(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rb(e))}});addMember=async({userId:e,role:t})=>await tH._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:t}}).then(e=>new ry(e?.response));inviteMember=async e=>rb.create(this.id,e);inviteMembers=async e=>rb.createBulk(this.id,e);updateMember=async({userId:e,role:t})=>await tH._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:t}}).then(e=>new ry(e?.response));removeMember=async e=>await tH._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new ry(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let t,a;return null===e?await tH._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new rg(e?.response)):("string"==typeof e?(t=e,a=new Headers({"Content-Type":"application/octet-stream"})):(t=new FormData).append("file",e),await tH._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:t,headers:a}).then(e=>new rg(e?.response)))};initializePaymentMethod=e=>ax({...e,orgId:this.id});addPaymentMethod=e=>aj({...e,orgId:this.id});getPaymentMethods=e=>a_({...e,orgId:this.id});fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.slug=e.slug,this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.publicMetadata=e.public_metadata||{},this.membersCount=e.members_count||0,this.pendingInvitationsCount=e.pending_invitations_count||0,this.maxAllowedMemberships=e.max_allowed_memberships||0,this.adminDeleteEnabled=e.admin_delete_enabled||!1,this.createdAt=tV(e.created_at),this.updatedAt=tV(e.updated_at)),this}__internal_toSnapshot(){return{object:"organization",id:this.id,name:this.name,slug:this.slug,image_url:this.imageUrl,has_image:this.hasImage,public_metadata:this.publicMetadata,members_count:this.membersCount,pending_invitations_count:this.pendingInvitationsCount,max_allowed_memberships:this.maxAllowedMemberships,admin_delete_enabled:this.adminDeleteEnabled,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}async reload(e){let{rotatingTokenNonce:t}=e||{},a=(await tH._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:t},{forceUpdateClient:!0}))?.response;return this.fromJSON(a)}}class rb extends tH{id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:t,role:a}){return new rb((await tH._fetch({path:`/organizations/${e}/invitations`,method:"POST",body:{email_address:t,role:a}}))?.response)}static async createBulk(e,t){let{emailAddresses:a,role:r}=t;return((await tH._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:a,role:r}}))?.response).map(e=>new rb(e))}constructor(e){super(),this.fromJSON(e)}revoke=async()=>await this._basePost({path:`/organizations/${this.organizationId}/invitations/${this.id}/revoke`});fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.organizationId=e.organization_id,this.publicMetadata=e.public_metadata,this.role=e.role,this.roleName=e.role_name,this.status=e.status,this.createdAt=tV(e.created_at),this.updatedAt=tV(e.updated_at)),this}}class ry extends tH{id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await tH._fetch({path:"/me/organization_memberships",method:"GET",search:as({...e,paginated:!0})}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new ry(e))}});destroy=async()=>await this._baseDelete({path:`/organizations/${this.organization.id}/memberships/${this.publicUserData?.userId}`});update=async({role:e})=>await this._basePatch({path:`/organizations/${this.organization.id}/memberships/${this.publicUserData?.userId}`,body:{role:e}});fromJSON(e){return e&&(this.id=e.id,this.organization=new rg(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new rS(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=tV(e.created_at),this.updatedAt=tV(e.updated_at)),this}__internal_toSnapshot(){return{object:"organization_membership",id:this.id,organization:this.organization.__internal_toSnapshot(),public_metadata:this.publicMetadata,public_user_data:this.publicUserData?.__internal_toSnapshot(),permissions:this.permissions,role:this.role,role_name:this.roleName,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}reload(e){throw Error(`${tA} Calling OrganizationMembership.reload is not currently supported. Please contact support.`)}}class rw extends tH{id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await tH._fetch({path:"/me/organization_suggestions",method:"GET",search:as(e)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rw(e))}})}accept=async()=>await this._basePost({path:`/me/organization_suggestions/${this.id}/accept`});fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.publicOrganizationData={hasImage:e.public_organization_data.has_image,imageUrl:e.public_organization_data.image_url,name:e.public_organization_data.name,id:e.public_organization_data.id,slug:e.public_organization_data.slug},this.createdAt=tV(e.created_at),this.updatedAt=tV(e.updated_at)),this}}function rk(){return c()&&"function"==typeof window.PublicKeyCredential}async function rv(){try{return rk()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function rx(){try{return"undefined"!=typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class rj extends tH{id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return tH._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new rj(e?.response))}static async attemptVerification(e,t){let a,r=(a=t.response,{...a1(t),response:{clientDataJSON:a2(a.clientDataJSON),attestationObject:a2(a.attestationObject),transports:a.getTransports()}});return tH._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(r)}}).then(e=>new rj(e?.response))}static async registerPasskey(){let e=rj.clerk.__internal_isWebAuthnSupported||rk,t=rj.clerk.__internal_createPublicCredentials||aZ,a=rj.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||rx;if(!e())throw new q("Passkeys are not supported on this device.",{code:"passkey_not_supported"});let r=await this.create(),{verification:n}=r,i=n?.publicKey;if(i||tM("create"),i.authenticatorSelection?.authenticatorAttachment==="platform"&&!await a())throw new q("Registration requires a platform authenticator but the device does not support it.",{code:"passkey_pa_not_supported"});let{publicKeyCredential:s,error:o}=await t(i);if(!s)throw o;return this.attemptVerification(r.id,s)}update=e=>this._basePatch({body:e});delete=async()=>new aF((await tH._fetch({path:this.path(),method:"DELETE"}))?.response);fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.lastUsedAt=e.last_used_at?tV(e.last_used_at):null,this.createdAt=tV(e.created_at),this.updatedAt=tV(e.updated_at),e.verification&&(this.verification=new a5(e.verification))),this}__internal_toSnapshot(){return{object:"passkey",id:this.id,name:this.name,verification:this.verification?.__internal_toSnapshot()||null,last_used_at:this.lastUsedAt?.getTime()||null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}class r_ extends tH{id;phoneNumber="";reservedForSecondFactor=!1;defaultSecondFactor=!1;linkedTo=[];verification;backupCodes;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}create=()=>this._basePost({body:{phone_number:this.phoneNumber}});prepareVerification=()=>this._basePost({action:"prepare_verification",body:{strategy:"phone_code"}});attemptVerification=e=>{let{code:t}=e||{};return this._basePost({action:"attempt_verification",body:{code:t}})};setReservedForSecondFactor=e=>{let{reserved:t}=e||{};return this._basePatch({body:{reserved_for_second_factor:t}})};makeDefaultSecondFactor=()=>this._basePatch({body:{default_second_factor:!0}});destroy=()=>this._baseDelete();toString=()=>{let e=this.phoneNumber.match(/^(\d{3})(\d{3})(\d{4})$/);return e?"("+e[1]+") "+e[2]+"-"+e[3]:this.phoneNumber};fromJSON(e){return e&&(this.id=e.id,this.phoneNumber=e.phone_number,this.reservedForSecondFactor=e.reserved_for_second_factor,this.defaultSecondFactor=e.default_second_factor,this.verification=new a9(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new ru(e)),this.backupCodes=e.backup_codes),this}__internal_toSnapshot(){return{object:"phone_number",id:this.id||"",phone_number:this.phoneNumber,reserved_for_second_factor:this.reservedForSecondFactor,default_second_factor:this.defaultSecondFactor,verification:this.verification.__internal_toSnapshot(),linked_to:this.linkedTo.map(e=>e.__internal_toSnapshot()),backup_codes:this.backupCodes}}}class rz extends tH{id="";loaders;rollout;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=this.withDefault(e.id,this.id),this.loaders=this.withDefault(e.loaders,this.loaders)),this}__internal_toSnapshot(){return{object:"protect_config",id:this.id,loaders:this.loaders}}}class rS{firstName;lastName;imageUrl;hasImage;identifier;userId;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.firstName=e.first_name||null,this.lastName=e.last_name||null,this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.identifier=e.identifier||"",this.userId=e.user_id),this}__internal_toSnapshot(){return{first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl,has_image:this.hasImage,identifier:this.identifier,user_id:this.userId}}}let rE={strict_mfa:{afterMinutes:10,level:"multi_factor"},strict:{afterMinutes:10,level:"second_factor"},moderate:{afterMinutes:60,level:"second_factor"},lax:{afterMinutes:1440,level:"second_factor"}},rA=new Set(["first_factor","second_factor","multi_factor"]),rI=new Set(["strict_mfa","strict","moderate","lax"]),rC=(e,t)=>{let{org:a,user:r}=rP(e),[n,i]=t.split(":"),s=i||n;return"org"===n?a.includes(s):"user"===n?r.includes(s):[...a,...r].includes(s)},rP=e=>{let t=e?e.split(",").map(e=>e.trim()):[];return{org:t.filter(e=>e.split(":")[0].includes("o")).map(e=>e.split(":")[1]),user:t.filter(e=>e.split(":")[0].includes("u")).map(e=>e.split(":")[1])}};class rq extends tH{status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new a9(null);secondFactorVerification=new a9(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new rO(e.session),this.level=e.level,this.supportedFirstFactors=es(e.supported_first_factors),this.supportedSecondFactors=es(e.supported_second_factors),this.firstFactorVerification=new a9(e.first_factor_verification),this.secondFactorVerification=new a9(e.second_factor_verification)),this}}class rO extends tH{pathRoot="/client/sessions";id;status;lastActiveAt;lastActiveToken;lastActiveOrganizationId;actor;user;publicUserData;factorVerificationAge=null;tasks=null;expireAt;abandonAt;createdAt;updatedAt;static isSessionResource(e){return!!e&&e instanceof rO}constructor(e){super(),this.fromJSON(e),this.#ed(this.lastActiveToken)}end=()=>(aB.clear(),this._basePost({action:"end"}));remove=()=>(aB.clear(),this._basePost({action:"remove"}));touch=()=>this._basePost({action:"touch",body:{active_organization_id:this.lastActiveOrganizationId}}).then(e=>(e.lastActiveToken&&rn.emit(re,{token:e.lastActiveToken}),e));clearCache=()=>aB.clear();getToken=async e=>tl(()=>this._getToken(e),{factor:1.55,initialDelay:3e3,maxDelayBetweenRetries:5e4,jitter:!1,shouldRetry:(e,t)=>!T(e)&&t<=8});checkAuthorization=e=>{let t,a=(this.user?.organizationMemberships||[]).find(e=>e.organization.id===this.lastActiveOrganizationId);return(t={userId:this.user?.id,factorVerificationAge:this.factorVerificationAge,orgId:a?.id,orgRole:a?.role,orgPermissions:a?.permissions,features:this.lastActiveToken?.jwt?.claims.fea||"",plans:this.lastActiveToken?.jwt?.claims.pla||""},e=>{if(!t.userId)return!1;let a=((e,t)=>{let{features:a,plans:r}=t;return e.feature&&a?rC(a,e.feature):e.plan&&r?rC(r,e.plan):null})(e,t),r=((e,t)=>{let{orgId:a,orgRole:r,orgPermissions:n}=t;return(e.role||e.permission)&&a&&r&&n?e.permission?n.includes(e.permission.replace(/^(org:)*/,"org:")):e.role?r.replace(/^(org:)*/,"org:")===e.role.replace(/^(org:)*/,"org:"):null:null})(e,t),n=((e,{factorVerificationAge:t})=>{if(!e.reverification||!t)return null;let a=(e=>{let t,a;if(!e)return!1;let r="string"==typeof e&&rI.has(e),n="object"==typeof e&&(t=e.level,rA.has(t))&&"number"==typeof(a=e.afterMinutes)&&a>0;return(!!r||!!n)&&(e=>"string"==typeof e?rE[e]:e).bind(null,e)})(e.reverification);if(!a)return null;let{level:r,afterMinutes:n}=a(),[i,s]=t,o=-1!==i?n>i:null,l=-1!==s?n>s:null;switch(r){case"first_factor":return o;case"second_factor":return -1!==s?l:o;case"multi_factor":return -1===s?o:o&&l}})(e,t);return[a||r,n].some(e=>null===e)?[a||r,n].some(e=>!0===e):[a||r,n].every(e=>!0===e)})(e)};#ed=e=>{e&&aB.set({tokenId:this.#eh(),tokenResolver:Promise.resolve(e)})};#eh(e,t){let a=void 0===t?this.lastActiveOrganizationId:t;return aq.build(this.id,e,a)}startVerification=async({level:e})=>new rq((await tH._fetch({method:"POST",path:`/client/sessions/${this.id}/verify`,body:{level:e}}))?.response);prepareFirstFactorVerification=async e=>{let t;switch(e.strategy){case"email_code":t={emailAddressId:e.emailAddressId};break;case"phone_code":t={phoneNumberId:e.phoneNumberId,default:e.default};break;case"passkey":t={};break;case"enterprise_sso":t={emailAddressId:e.emailAddressId,enterpriseConnectionId:e.enterpriseConnectionId,redirectUrl:e.redirectUrl};break;default:tq("Session.prepareFirstFactorVerification",e.strategy)}return new rq((await tH._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_first_factor`,body:{...t,strategy:e.strategy}}))?.response)};attemptFirstFactorVerification=async e=>{let t;return t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(a0(e.publicKeyCredential))}:{...e},new rq((await tH._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_first_factor`,body:{...t,strategy:e.strategy}}))?.response)};verifyWithPasskey=async()=>{let{nonce:e=null}=(await this.prepareFirstFactorVerification({strategy:"passkey"})).firstFactorVerification,t=rO.clerk.__internal_isWebAuthnSupported||rk,a=rO.clerk.__internal_getPublicCredentials||aY;if(!t())throw new q("Passkeys are not supported",{code:"passkey_not_supported"});let r=e?aX(JSON.parse(e)):null;r||tM("get");let{publicKeyCredential:n,error:i}=await a({publicKeyOptions:r,conditionalUI:!1});if(!n)throw i;return this.attemptFirstFactorVerification({strategy:"passkey",publicKeyCredential:n})};prepareSecondFactorVerification=async e=>new rq((await tH._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>new rq((await tH._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_second_factor`,body:e}))?.response);fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.expireAt=tV(e.expire_at),this.abandonAt=tV(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=tV(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.createdAt=tV(e.created_at),this.updatedAt=tV(e.updated_at),this.user=new rY(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new rS(e.public_user_data)),this.lastActiveToken=e.last_active_token?new rJ(e.last_active_token):null),this}__internal_toSnapshot(){return{object:"session",id:this.id,status:this.status,expire_at:this.expireAt.getTime(),abandon_at:this.abandonAt.getTime(),factor_verification_age:this.factorVerificationAge,last_active_at:this.lastActiveAt.getTime(),last_active_organization_id:this.lastActiveOrganizationId,actor:this.actor,tasks:this.tasks,user:this.user?.__internal_toSnapshot()||null,public_user_data:this.publicUserData.__internal_toSnapshot(),last_active_token:this.lastActiveToken?.__internal_toSnapshot()||null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}async _getToken(e){if(!this.user)return null;let{leewayInSeconds:t,template:a,skipCache:r=!1}=e||{},n=void 0===e?.organizationId?this.lastActiveOrganizationId:e?.organizationId;if(!a&&Number(t)>=60)throw Error("Leeway can not exceed the token lifespan (60 seconds)");let i=this.#eh(a,n),s=r?void 0:aB.get({tokenId:i},t),o=!a&&n===this.lastActiveOrganizationId;if(s){tn.debug("Using cached token (no fetch needed)",{tokenId:i},"session");let e=await s.tokenResolver;return o&&rn.emit(re,{token:e}),e.getRawString()||null}tn.info("Fetching new token from API",{organizationId:n,template:a,tokenId:i},"session");let l=a?`${this.path()}/tokens/${a}`:`${this.path()}/tokens`,c=a?{}:{organizationId:n},u=rJ.create(l,c,r);return aB.set({tokenId:i,tokenResolver:u}),u.then(e=>(o&&(rn.emit(re,{token:e}),e.jwt&&(this.lastActiveToken=e,rn.emit(rr,null))),e.getRawString()||null))}get currentTask(){let[e]=this.tasks??[];return e}}class rT extends tH{pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}static retrieve(){let e=tH.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new rT(e,"/me/sessions"))).catch(()=>[])}revoke(){return this._basePost({action:"revoke",body:{}})}fromJSON(e){let t;return e?(this.id=e.id,this.status=e.status,this.expireAt=tV(e.expire_at),this.abandonAt=tV(e.abandon_at),this.lastActiveAt=tV(e.last_active_at||void 0),this.latestActivity={id:(t=e.latest_activity??{}).id,deviceType:t.device_type,browserName:t.browser_name,browserVersion:t.browser_version,country:t.country,city:t.city,isMobile:t.is_mobile,ipAddress:t.ip_address},this.actor=e.actor,this):this}}let rU=(e,t,a)=>{let{onValidation:r=e8,onValidationComplexity:n=e8}=a||{},{show_zxcvbn:i,validatePassword:s}=t,o=e=>((e,t)=>{let{max_length:a,min_length:r,require_special_char:n,require_lowercase:i,require_numbers:s,require_uppercase:o}=t,l=(e=>{let t;if(e.allowed_special_characters){let a=e.allowed_special_characters.replace("[","\\[");a=a.replace("]","\\]"),t=RegExp(`[${a}]`)}else t=/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/;return(e,{minLength:a,maxLength:r})=>({max_length:e.length<r,min_length:e.length>=a,require_numbers:/\d/.test(e),require_lowercase:/[a-z]/.test(e),require_uppercase:/[A-Z]/.test(e),require_special_char:t.test(e)})})(t)(e,{maxLength:t.max_length,minLength:t.min_length}),c={max_length:a,min_length:r,require_special_char:n,require_lowercase:i,require_numbers:s,require_uppercase:o},u=new Map;for(let e in c)c[e]&&!l[e]&&u.set(e,!0);return Object.freeze(Object.fromEntries(u))})(e,t),l=(({min_zxcvbn_strength:e,onResult:t})=>a=>r=>{let n=a(r);return(t?.(n),n.score>=e&&n.score<3)?{state:"pass",keys:["unstable__errors.zxcvbn.couldBeStronger"],result:n}:n.score>=e?{state:"excellent",result:n}:{state:"fail",keys:["unstable__errors.zxcvbn.notEnough",...n.feedback.suggestions.map(e=>`unstable__errors.zxcvbn.suggestions.${e}`)],result:n}})(t),c={};return(t,a)=>{let{onValidation:u=r,onValidationComplexity:d=n}=a||{};if(!s)return;let h=o(t);d(0===Object.keys(h).length),c={...c,complexity:h},i&&e().then(e=>{let a=l(e)(t);u({...c={...c,strength:a},strength:a})}),c.complexity&&0===Object.keys(c.complexity).length&&i||u(c)}};function rM(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function rR(e,t,a,r,n){if(!e.client||!r.popup)return;let i=rM(e.frontendApi),{redirectUrl:s}=r,o=new URL(s);o.searchParams.set("sign_in_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("sign_up_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("intent",t);let l=e.buildUrlWithAuth(o.toString()),c=e.buildUrlWithAuth(`${i}/popup-callback`),u=e.buildUrlWithAuth(`${i}/popup-callback?return_url=${encodeURIComponent(l)}`),d=async t=>{if(t.origin!==i)return;let a=!1;if(t.data.session){if(!e.client?.sessions.find(e=>e.id===t.data.session))try{await e.client?.reload()}catch(e){console.error(e)}await e.setActive({session:t.data.session,redirectUrl:r.redirectUrlComplete}),a=!0}else t.data.return_url&&(e.navigate(t.data.return_url),a=!0);a&&window.removeEventListener("message",d)};window.addEventListener("message",d),await a({...r,redirectUrlComplete:c,redirectUrl:u},n)}function rB(e,{redirectCallbackUrl:t,redirectUrl:a}){let r=rM(e.frontendApi),n=new URL(t);n.searchParams.set("sign_in_force_redirect_url",a),n.searchParams.set("sign_up_force_redirect_url",a);let i=e.buildUrlWithAuth(n.toString()),s=e.buildUrlWithAuth(`${r}/popup-callback`);return{redirectCallbackUrl:e.buildUrlWithAuth(`${r}/popup-callback?return_url=${encodeURIComponent(i)}`),redirectUrl:s}}function rN(e,t){return new Promise((a,r)=>{if(!e.client||!t.popup)return void r();let n=async t=>{t.origin===rM(e.frontendApi)&&(t.data.session||t.data.return_url?(window.removeEventListener("message",n),a()):r())};window.addEventListener("message",n),t.popup.location.href=t.externalVerificationRedirectURL.toString()})}async function rD(e,t){rn.emit("resource:error",{resource:e,error:null}),rn.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await t(),error:null}}catch(t){return rn.emit("resource:error",{resource:e,error:t}),{error:t}}finally{rn.emit("resource:fetch",{resource:e,status:"idle"})}}let rF=()=>{var e;return(e=new tu,{loadZxcvbn:()=>Promise.all([e.import("@zxcvbn-ts/core"),e.import("@zxcvbn-ts/language-common")]).then(([e,t])=>{if(!e||!t)throw Error("Failed to load zxcvbn modules");let{zxcvbnOptions:a,zxcvbn:r}=e,{dictionary:n,adjacencyGraphs:i}=t;return a.setOptions({dictionary:{...n},graphs:i}),r})}).loadZxcvbn};class rL extends tH{pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;firstFactorVerification=new a9(null);secondFactorVerification=new a9(null);identifier=null;createdSessionId=null;userData=new rQ(null);clientTrustState;get status(){return this._status}set status(e){let t=this._status;this._status=e,e&&t!==e&&tn.debug("SignIn.status",{id:this.id,from:t,to:e})}__internal_future=new rW(this);__internal_basePost=this._basePost.bind(this);__internal_baseGet=this._baseGet.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=e=>{tn.debug("SignIn.create",{id:this.id,strategy:"strategy"in e?e.strategy:void 0});let t=ty();return this._basePost({path:this.pathRoot,body:t?{locale:t,...e}:e})};resetPassword=e=>this._basePost({body:e,action:"reset_password"});prepareFirstFactor=e=>{let t;switch(tn.debug("SignIn.prepareFirstFactor",{id:this.id,strategy:e.strategy}),e.strategy){case"passkey":t={};break;case"email_link":t={emailAddressId:e.emailAddressId,redirectUrl:e.redirectUrl};break;case"email_code":case"reset_password_email_code":t={emailAddressId:e.emailAddressId};break;case"phone_code":t={phoneNumberId:e.phoneNumberId,default:e.default,channel:e.channel};break;case"web3_metamask_signature":case"web3_base_signature":case"web3_coinbase_wallet_signature":case"web3_okx_wallet_signature":case"web3_solana_signature":t={web3WalletId:e.web3WalletId};break;case"reset_password_phone_code":t={phoneNumberId:e.phoneNumberId};break;case"enterprise_sso":t={redirectUrl:e.redirectUrl,actionCompleteRedirectUrl:e.actionCompleteRedirectUrl,oidcPrompt:e.oidcPrompt,enterpriseConnectionId:e.enterpriseConnectionId};break;default:tq("SignIn.prepareFirstFactor",e.strategy)}return this._basePost({body:{...t,strategy:e.strategy},action:"prepare_first_factor"})};attemptFirstFactor=e=>{let t;return tn.debug("SignIn.attemptFirstFactor",{id:this.id,strategy:e.strategy}),t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(a0(e.publicKeyCredential))}:{...e},this._basePost({body:{...t,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:t}=aV();return{startEmailLinkFlow:async({emailAddressId:a,redirectUrl:r})=>{this.id||tP("SignIn");let n={strategy:"email_link",emailAddressId:a,redirectUrl:r},i="needs_second_factor"===this.status||"needs_client_trust"===this.status,s=i?"secondFactorVerification":"firstFactorVerification";return i?await this.prepareSecondFactor(n):await this.prepareFirstFactor(n),new Promise((a,r)=>{e(()=>this.reload().then(e=>{let r=e[s].status;("verified"===r||"expired"===r)&&(t(),a(e))}).catch(e=>{t(),r(e)}))})},cancelEmailLinkFlow:t}};prepareSecondFactor=e=>(tn.debug("SignIn.prepareSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_second_factor"}));attemptSecondFactor=e=>(tn.debug("SignIn.attemptSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_second_factor"}));authenticateWithRedirectOrPopup=async(e,t)=>{let{strategy:a,redirectUrlComplete:r,identifier:n,oidcPrompt:i,continueSignIn:s,enterpriseConnectionId:o}=e||{},l=rL.clerk.buildUrlWithAuth(e.redirectUrl);this.id&&s||await this.create({strategy:a,identifier:n,redirectUrl:l,actionCompleteRedirectUrl:r}),"enterprise_sso"===a&&await this.prepareFirstFactor({strategy:a,redirectUrl:l,actionCompleteRedirectUrl:r,oidcPrompt:i,enterpriseConnectionId:o});let{status:c,externalVerificationRedirectURL:u}=this.firstFactorVerification;"unverified"===c&&u?t(u):tU(c,rL.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eV);authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||tT("popup"),rR(rL.clerk,"signIn",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e.toString()})};authenticateWithWeb3=async e=>{let t,{identifier:a,generateSignature:r,strategy:n="web3_metamask_signature",walletName:i}=e||{},s=n.replace("web3_","").replace("_signature","");"function"!=typeof r&&tT("generateSignature"),"solana"!==s||i||tT("walletName"),await this.create({identifier:a});let o=this.supportedFirstFactors?.find(e=>e.strategy===n);o||tO("SignIn"),await this.prepareFirstFactor(o);let{message:l}=this.firstFactorVerification;l||tO("SignIn");try{t=await r({identifier:a,nonce:l,walletName:i,provider:s})}catch(e){if("coinbase_wallet"===s&&4001===e.code)t=await r({identifier:a,nonce:l,provider:s,walletName:i});else throw e}return this.attemptFirstFactor({signature:t,strategy:n})};authenticateWithMetamask=async()=>{let e=await tj().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tj().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await tj().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tj().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await tj().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tj().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await tj().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tj().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithSolana=async({walletName:e})=>{let t=await tj().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:t,generateSignature:t=>tj().generateSignatureWithSolana({...t,walletName:e}),strategy:"web3_solana_signature",walletName:e})};authenticateWithPasskey=async e=>{let{flow:t}=e||{},a=rL.clerk.__internal_isWebAuthnSupported||rk,r=rL.clerk.__internal_getPublicCredentials||aY,n=rL.clerk.__internal_isWebAuthnAutofillSupported||rv;if(!a())throw new q("Passkeys are not supported",{code:"passkey_not_supported"});if("autofill"===t||"discoverable"===t)await this.create({strategy:"passkey"});else{let e=this.supportedFirstFactors.find(e=>"passkey"===e.strategy);e||function(){throw Error(`${tA} You need to start a SignIn flow by calling SignIn.create({ strategy: 'passkey' }) first`)}(),await this.prepareFirstFactor(e)}let{nonce:i}=this.firstFactorVerification,s=i?aX(JSON.parse(i)):null;s||tM("get");let o=!1;"autofill"===t&&(o=await n());let{publicKeyCredential:l,error:c}=await r({publicKeyOptions:s,conditionalUI:o});if(!l)throw c;return this.attemptFirstFactor({publicKeyCredential:l,strategy:"passkey"})};validatePassword=(e,t)=>{if(rL.clerk.__internal_environment?.userSettings.passwordSettings)return rU(rF(),{...rL.clerk.__internal_environment?.userSettings.passwordSettings,validatePassword:!0})(e,t)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.supportedIdentifiers=e.supported_identifiers,this.identifier=e.identifier,this.supportedFirstFactors=es(e.supported_first_factors),this.supportedSecondFactors=es(e.supported_second_factors),this.firstFactorVerification=new a9(e.first_factor_verification),this.secondFactorVerification=new a9(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new rQ(e.user_data),this.clientTrustState=e.client_trust_state??void 0),rn.emit("resource:update",{resource:this}),this}__internal_toSnapshot(){return{object:"sign_in",id:this.id||"",status:this.status||null,supported_identifiers:this.supportedIdentifiers,supported_first_factors:ei(this.supportedFirstFactors),supported_second_factors:ei(this.supportedSecondFactors),first_factor_verification:this.firstFactorVerification.__internal_toSnapshot(),second_factor_verification:this.secondFactorVerification.__internal_toSnapshot(),identifier:this.identifier,created_session_id:this.createdSessionId,user_data:this.userData.__internal_toSnapshot()}}}class rW{emailCode={sendCode:this.sendEmailCode.bind(this),verifyCode:this.verifyEmailCode.bind(this)};emailLink={sendLink:this.sendEmailLink.bind(this),waitForVerification:this.waitForEmailLinkVerification.bind(this),get verification(){if(!o())return null;let e=eM("__clerk_status"),t=eM("__clerk_created_session");if(!e||!t)return null;let a="verified"===e&&void 0!==rL.clerk.client&&rL.clerk.client.sessions.some(e=>e.id===t);return{status:e,createdSessionId:t,verifiedFromTheSameClient:a}}};resetPasswordEmailCode={sendCode:this.sendResetPasswordEmailCode.bind(this),verifyCode:this.verifyResetPasswordEmailCode.bind(this),submitPassword:this.submitResetPassword.bind(this)};phoneCode={sendCode:this.sendPhoneCode.bind(this),verifyCode:this.verifyPhoneCode.bind(this)};mfa={sendPhoneCode:this.sendMFAPhoneCode.bind(this),verifyPhoneCode:this.verifyMFAPhoneCode.bind(this),verifyTOTP:this.verifyTOTP.bind(this),verifyBackupCode:this.verifyBackupCode.bind(this)};#em=!1;#ep;constructor(e){this.#ep=e}get id(){return this.#ep.id}get identifier(){return this.#ep.identifier}get createdSessionId(){return this.#ep.createdSessionId}get userData(){return this.#ep.userData}get status(){return this.#ep.status||"needs_identifier"}get supportedFirstFactors(){return this.#ep.supportedFirstFactors??[]}get supportedSecondFactors(){return this.#ep.supportedSecondFactors??[]}get isTransferable(){return"transferable"===this.#ep.firstFactorVerification.status}get existingSession(){if("failed"===this.#ep.firstFactorVerification.status&&this.#ep.firstFactorVerification.error?.code==="identifier_already_signed_in"&&this.#ep.firstFactorVerification.error?.meta?.sessionId)return{sessionId:this.#ep.firstFactorVerification.error?.meta?.sessionId}}get firstFactorVerification(){return this.#ep.firstFactorVerification}get secondFactorVerification(){return this.#ep.secondFactorVerification}get hasBeenFinalized(){return this.#em}async sendResetPasswordEmailCode(){if(!this.#ep.id)throw Error("Cannot reset password without a sign in.");return rD(this.#ep,async()=>{let e=this.#ep.supportedFirstFactors?.find(e=>"reset_password_email_code"===e.strategy);if(!e)throw new C("Reset password email code factor not found",{code:"factor_not_found"});let{emailAddressId:t}=e;await this.#ep.__internal_basePost({body:{emailAddressId:t,strategy:"reset_password_email_code"},action:"prepare_first_factor"})})}async verifyResetPasswordEmailCode(e){let{code:t}=e;return rD(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:t,strategy:"reset_password_email_code"},action:"attempt_first_factor"})})}async submitResetPassword(e){let{password:t,signOutOfOtherSessions:a=!0}=e;return rD(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{password:t,signOutOfOtherSessions:a},action:"reset_password"})})}async _create(e){let t=ty();await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:t?{locale:t,...e}:e})}async create(e){return rD(this.#ep,async()=>{await this._create(e)})}async password(e){if([e.identifier,e.emailAddress,e.phoneNumber].filter(Boolean).length>1)throw Error("Only one of identifier, emailAddress, or phoneNumber can be provided");return rD(this.#ep,async()=>{let t=e.identifier||e.emailAddress||e.phoneNumber,a=this.#ep.identifier,r=ty();await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:{identifier:t||a,password:e.password,...r?{locale:r}:{}}})})}async sendEmailCode(e={}){let{emailAddress:t,emailAddressId:a}=e;if(!this.#ep.id&&a)throw Error("signIn.emailCode.sendCode() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#ep.id&&!t)throw Error("signIn.emailCode.sendCode() cannot be called without an emailAddress if an existing signIn does not exist.");return rD(this.#ep,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_code",emailAddressId:a});if(!e)throw new C("Email code factor not found",{code:"factor_not_found"});await this.#ep.__internal_basePost({body:{emailAddressId:e.emailAddressId,strategy:"email_code"},action:"prepare_first_factor"})})}async verifyEmailCode(e){let{code:t}=e;return rD(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:t,strategy:"email_code"},action:"attempt_first_factor"})})}async sendEmailLink(e){let{emailAddress:t,verificationUrl:a,emailAddressId:r}=e;if(!this.#ep.id&&r)throw Error("signIn.emailLink.sendLink() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#ep.id&&!t)throw Error("signIn.emailLink.sendLink() cannot be called without an emailAddress if an existing signIn does not exist.");return rD(this.#ep,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_link",emailAddressId:r});if(!e)throw new C("Email link factor not found",{code:"factor_not_found"});let n=a;try{new URL(a)}catch{n=window.location.origin+a}await this.#ep.__internal_basePost({body:{emailAddressId:e.emailAddressId,redirectUrl:n,strategy:"email_link"},action:"prepare_first_factor"})})}async waitForEmailLinkVerification(){return rD(this.#ep,async()=>{let{run:e,stop:t}=aV();await new Promise((a,r)=>{e(async()=>{try{let e=await this.#ep.__internal_baseGet(),r=e.firstFactorVerification.status;("verified"===r||"expired"===r)&&(t(),a(e))}catch(e){t(),r(e)}})})})}async sendPhoneCode(e={}){let{phoneNumber:t,phoneNumberId:a,channel:r="sms"}=e;if(!this.#ep.id&&a)throw Error("signIn.phoneCode.sendCode() cannot be called with an phoneNumberId if an existing signIn does not exist.");if(!this.#ep.id&&!t)throw Error("signIn.phoneCode.sendCode() cannot be called without an phoneNumber if an existing signIn does not exist.");return rD(this.#ep,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"phone_code",phoneNumberId:a});if(!e)throw new C("Phone code factor not found",{code:"factor_not_found"});await this.#ep.__internal_basePost({body:{phoneNumberId:e.phoneNumberId,strategy:"phone_code",channel:r},action:"prepare_first_factor"})})}async verifyPhoneCode(e){let{code:t}=e;return rD(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_first_factor"})})}async sso(e){let{strategy:t,redirectUrl:a,redirectCallbackUrl:r,popup:n,oidcPrompt:i,enterpriseConnectionId:s,identifier:o}=e;return rD(this.#ep,async()=>{let e=a;try{new URL(a)}catch{e=window.location.origin+a}let l={redirectUrl:rL.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:e};if(n){let t=rB(rL.clerk,{redirectCallbackUrl:l.redirectUrl,redirectUrl:e});l.redirectUrl=t.redirectCallbackUrl,l.actionCompleteRedirectUrl=t.redirectUrl}await this._create({strategy:t,...l,identifier:o}),"enterprise_sso"===t&&await this.#ep.__internal_basePost({body:{...l,oidcPrompt:i,enterpriseConnectionId:s,strategy:"enterprise_sso"},action:"prepare_first_factor"});let{status:c,externalVerificationRedirectURL:u}=this.#ep.firstFactorVerification;"unverified"===c&&u&&(n?(await rN(rL.clerk,{popup:n,externalVerificationRedirectURL:u}),await this.#ep.reload()):eV(u))})}async web3(e){let{strategy:t}=e,a=t.replace("web3_","").replace("_signature","");return rD(this.#ep,async()=>{let r,n,i;switch(a){case"metamask":r=await tj().getMetamaskIdentifier(),n=tj().generateSignatureWithMetamask;break;case"coinbase_wallet":r=await tj().getCoinbaseWalletIdentifier(),n=tj().generateSignatureWithCoinbaseWallet;break;case"base":r=await tj().getBaseIdentifier(),n=tj().generateSignatureWithBase;break;case"okx_wallet":r=await tj().getOKXWalletIdentifier(),n=tj().generateSignatureWithOKXWallet;break;case"solana":if(!e.walletName)throw new C("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});r=await tj().getSolanaIdentifier(e.walletName),n=t=>tj().generateSignatureWithSolana({...t,walletName:e.walletName});break;default:throw Error(`Unsupported Web3 provider: ${a}`)}await this._create({identifier:r});let s=this.#ep.supportedFirstFactors?.find(e=>e.strategy===t);if(!s)throw new C("Web3 first factor not found",{code:"factor_not_found"});await this.#ep.__internal_basePost({body:{web3WalletId:s.web3WalletId,strategy:t},action:"prepare_first_factor"});let{message:o}=this.firstFactorVerification;if(!o)throw new C("Web3 nonce not found",{code:"web3_nonce_not_found"});try{i=await n({identifier:r,nonce:o,walletName:e?.walletName,provider:a})}catch(e){if("coinbase_wallet"===a&&4001===e.code)i=await n({identifier:r,nonce:o,provider:a});else throw e}await this.#ep.__internal_basePost({body:{signature:i,strategy:t},action:"attempt_first_factor"})})}async passkey(e){let{flow:t}=e||{},a=rL.clerk.__internal_isWebAuthnSupported||rk,r=rL.clerk.__internal_getPublicCredentials||aY,n=rL.clerk.__internal_isWebAuthnAutofillSupported||rv;if(!a())throw new q("Passkeys are not supported",{code:"passkey_not_supported"});return rD(this.#ep,async()=>{if("autofill"===t||"discoverable"===t)await this._create({strategy:"passkey"});else{if(!this.supportedFirstFactors.find(e=>"passkey"===e.strategy))throw new C("Passkey factor not found",{code:"factor_not_found"});await this.#ep.__internal_basePost({body:{strategy:"passkey"},action:"prepare_first_factor"})}let{nonce:e}=this.firstFactorVerification,a=e?aX(JSON.parse(e)):null;if(!a)throw new C("Missing public key options",{code:"missing_public_key_options"});let i=!1;"autofill"===t&&(i=await n());let{publicKeyCredential:s,error:o}=await r({publicKeyOptions:a,conditionalUI:i});if(!s)throw new q(o.message,{code:"passkey_retrieval_failed"});await this.#ep.__internal_basePost({body:{publicKeyCredential:JSON.stringify(a0(s)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return rD(this.#ep,async()=>{let e=this.#ep.supportedSecondFactors?.find(e=>"phone_code"===e.strategy);if(!e)throw new C("Phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:t}=e;await this.#ep.__internal_basePost({body:{phoneNumberId:t,strategy:"phone_code"},action:"prepare_second_factor"})})}async verifyMFAPhoneCode(e){let{code:t}=e;return rD(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_second_factor"})})}async verifyTOTP(e){let{code:t}=e;return rD(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:t,strategy:"totp"},action:"attempt_second_factor"})})}async verifyBackupCode(e){let{code:t}=e;return rD(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:t,strategy:"backup_code"},action:"attempt_second_factor"})})}async ticket(e){let t=e?.ticket??eM("__clerk_ticket");return this.create({ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};if(!this.#ep.createdSessionId)throw Error("Cannot finalize sign-in without a created session.");return rD(this.#ep,async()=>{rL.clerk.client&&!rL.clerk.client.sessions.some(e=>e.id===this.#ep.createdSessionId)&&await rL.clerk.client.reload(),this.#em=!0,await rL.clerk.setActive({session:this.#ep.createdSessionId,navigate:t})})}selectFirstFactor({strategy:e,emailAddressId:t,phoneNumberId:a}){if(!this.#ep.supportedFirstFactors)return null;if(t){let a=this.#ep.supportedFirstFactors.find(a=>a.strategy===e&&a.emailAddressId===t);if(a)return a}if(a){let t=this.#ep.supportedFirstFactors.find(t=>t.strategy===e&&t.phoneNumberId===a);if(t)return t}let r=this.#ep.supportedFirstFactors.find(t=>t.strategy===e&&t.safeIdentifier===this.#ep.identifier);if(r)return r;let n=this.#ep.supportedFirstFactors.find(t=>t.strategy===e);return n||null}}function rK(e){let{unsafeMetadata:t}={...e},a=t?"object"==typeof t?JSON.stringify(t):t:"";return{...e,...t?{unsafeMetadata:a}:{}}}class rH extends tH{pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new a6(null);username=null;firstName=null;lastName=null;emailAddress=null;phoneNumber=null;web3wallet=null;externalAccount;hasPassword=!1;unsafeMetadata={};createdSessionId=null;createdUserId=null;abandonAt=null;legalAcceptedAt=null;locale=null;get status(){return this._status}set status(e){let t=this._status;this._status=e,e&&t!==e&&tn.debug("SignUp.status",{id:this.id,from:t,to:e})}__internal_future=new rV(this);__internal_basePost=this._basePost.bind(this);__internal_basePatch=this._basePatch.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{tn.debug("SignUp.create",{id:this.id,strategy:e.strategy});let t={...e};if(!t.locale){let e=ty();e&&(t.locale=e)}if(!this.clientBypass()&&!this.shouldBypassCaptchaForAttempt(e)){let e=new tW(rH.clerk),a=await e.managedOrInvisible({action:"signup"});if(!a)throw new C("",{code:"captcha_unavailable"});t={...t,...a}}if(t.transfer&&this.shouldBypassCaptchaForAttempt(t)){let e=rH.clerk.client?.signIn.firstFactorVerification.strategy;e&&(t={...t,strategy:e})}return this._basePost({path:this.pathRoot,body:rK(t)})};prepareVerification=e=>(tn.debug("SignUp.prepareVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_verification"}));attemptVerification=e=>(tn.debug("SignUp.attemptVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_verification"}));prepareEmailAddressVerification=e=>this.prepareVerification(e||{strategy:"email_code"});attemptEmailAddressVerification=e=>this.attemptVerification({...e,strategy:"email_code"});createEmailLinkFlow=()=>{let{run:e,stop:t}=aV();return{startEmailLinkFlow:async({redirectUrl:a})=>(this.id||tP("SignUp"),await this.prepareEmailAddressVerification({strategy:"email_link",redirectUrl:a}),new Promise((a,r)=>{e(()=>this.reload().then(e=>{let r=e.verifications.emailAddress.status;("verified"===r||"expired"===r)&&(t(),a(e))}).catch(e=>{t(),r(e)}))})),cancelEmailLinkFlow:t}};preparePhoneNumberVerification=e=>this.prepareVerification(e||{strategy:"phone_code"});attemptPhoneNumberVerification=e=>this.attemptVerification({...e,strategy:"phone_code"});prepareWeb3WalletVerification=e=>this.prepareVerification({strategy:"web3_metamask_signature",...e});attemptWeb3WalletVerification=async e=>{let{signature:t,strategy:a="web3_metamask_signature"}=e;return this.attemptVerification({signature:t,strategy:a})};authenticateWithWeb3=async e=>{let t,{generateSignature:a,identifier:r,unsafeMetadata:n,strategy:i="web3_metamask_signature",legalAccepted:s,walletName:o}=e||{},l=i.replace("web3_","").replace("_signature","");"function"!=typeof a&&tT("generateSignature");let c=r||this.web3wallet;await this.create({web3Wallet:c,unsafeMetadata:n,legalAccepted:s}),await this.prepareWeb3WalletVerification({strategy:i});let{message:u}=this.verifications.web3Wallet;u||tO("SignUp");try{t=await a({identifier:r,nonce:u,provider:l,walletName:o})}catch(e){if("coinbase_wallet"===l&&4001===e.code)t=await a({identifier:r,nonce:u,provider:l});else throw e}return this.attemptWeb3WalletVerification({signature:t,strategy:i})};authenticateWithMetamask=async e=>{let t=await tj().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tj().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let t=await tj().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tj().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let t=await tj().getBaseIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tj().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let t=await tj().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tj().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithSolana=async({walletName:e,unsafeMetadata:t,legalAccepted:a})=>{let r=await tj().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:r,generateSignature:t=>tj().generateSignatureWithSolana({...t,walletName:e}),unsafeMetadata:t,strategy:"web3_solana_signature",legalAccepted:a,walletName:e})};authenticateWithRedirectOrPopup=async(e,t)=>{let{redirectUrl:a,redirectUrlComplete:r,strategy:n,continueSignUp:i=!1,unsafeMetadata:s,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:u}=e,d=rH.clerk.buildUrlWithAuth(a),h=()=>{let e={strategy:n,redirectUrl:d,actionCompleteRedirectUrl:r,unsafeMetadata:s,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:u};return i&&this.id?this.update(e):this.create(e)},{verifications:m}=await h().catch(async e=>{if(M(e)&&O(e))return await rH.clerk.__internal_environment.reload(),h();throw e}),{externalAccount:p}=m,{status:f,externalVerificationRedirectURL:g}=p;"unverified"===f&&g?t(g):tU(f,rH.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eV);authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||tT("popup"),rR(rH.clerk,"signUp",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e instanceof URL?e.toString():e})};update=e=>this._basePatch({body:rK(e)});upsert=e=>this.id?this.update(e):this.create(e);validatePassword=(e,t)=>{if(rH.clerk.__internal_environment?.userSettings.passwordSettings)return rU(rF(),{...rH.clerk.__internal_environment?.userSettings.passwordSettings,validatePassword:!0})(e,t)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.requiredFields=e.required_fields,this.optionalFields=e.optional_fields,this.missingFields=e.missing_fields,this.unverifiedFields=e.unverified_fields,this.verifications=new a6(e.verifications),this.username=e.username,this.firstName=e.first_name,this.lastName=e.last_name,this.emailAddress=e.email_address,this.phoneNumber=e.phone_number,this.hasPassword=e.has_password,this.unsafeMetadata=e.unsafe_metadata,this.createdSessionId=e.created_session_id,this.createdUserId=e.created_user_id,this.abandonAt=e.abandon_at,this.web3wallet=e.web3_wallet,this.legalAcceptedAt=e.legal_accepted_at,this.locale=e.locale),rn.emit("resource:update",{resource:this}),this}__internal_toSnapshot(){return{object:"sign_up",id:this.id||"",status:this.status||null,required_fields:this.requiredFields,optional_fields:this.optionalFields,missing_fields:this.missingFields,unverified_fields:this.unverifiedFields,verifications:this.verifications.__internal_toSnapshot(),username:this.username,first_name:this.firstName,last_name:this.lastName,email_address:this.emailAddress,phone_number:this.phoneNumber,has_password:this.hasPassword,unsafe_metadata:this.unsafeMetadata,created_session_id:this.createdSessionId,created_user_id:this.createdUserId,abandon_at:this.abandonAt,web3_wallet:this.web3wallet,legal_accepted_at:this.legalAcceptedAt,locale:this.locale,external_account:this.externalAccount,external_account_strategy:this.externalAccount?.strategy}}clientBypass(){return rH.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){if(!e.strategy)return!1;let t=rH.clerk.__internal_environment.displayConfig.captchaOauthBypass;return!!(t.some(t=>t===e.strategy)||e.transfer&&t.some(e=>e===rH.clerk.client.signIn.firstFactorVerification.strategy))}__experimental_getEnterpriseConnections=()=>tH._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new rG(e)))}class rV{verifications={sendEmailCode:this.sendEmailCode.bind(this),verifyEmailCode:this.verifyEmailCode.bind(this),sendPhoneCode:this.sendPhoneCode.bind(this),verifyPhoneCode:this.verifyPhoneCode.bind(this)};#em=!1;#ep;constructor(e){this.#ep=e}get id(){return this.#ep.id}get requiredFields(){return this.#ep.requiredFields}get optionalFields(){return this.#ep.optionalFields}get missingFields(){return this.#ep.missingFields}get status(){return this.#ep.status||"missing_requirements"}get username(){return this.#ep.username}get firstName(){return this.#ep.firstName}get lastName(){return this.#ep.lastName}get emailAddress(){return this.#ep.emailAddress}get phoneNumber(){return this.#ep.phoneNumber}get web3Wallet(){return this.#ep.web3wallet}get hasPassword(){return this.#ep.hasPassword}get unsafeMetadata(){return this.#ep.unsafeMetadata}get createdSessionId(){return this.#ep.createdSessionId}get createdUserId(){return this.#ep.createdUserId}get abandonAt(){return this.#ep.abandonAt}get legalAcceptedAt(){return this.#ep.legalAcceptedAt}get locale(){return this.#ep.locale}get unverifiedFields(){return this.#ep.unverifiedFields}get isTransferable(){return"transferable"===this.#ep.verifications.externalAccount.status&&this.#ep.verifications.externalAccount.error?.code==="external_account_exists"}get existingSession(){if(("failed"===this.#ep.verifications.externalAccount.status||"unverified"===this.#ep.verifications.externalAccount.status)&&this.#ep.verifications.externalAccount.error?.code==="identifier_already_signed_in"&&this.#ep.verifications.externalAccount.error?.meta?.sessionId)return{sessionId:this.#ep.verifications.externalAccount.error?.meta?.sessionId}}get hasBeenFinalized(){return this.#em}async getCaptchaToken(){let e=new tW(rH.clerk),t=await e.managedOrInvisible({action:"signup"});if(!t)throw Error("Captcha challenge failed");let{captchaError:a,captchaToken:r,captchaWidgetType:n}=t;return{captchaToken:r,captchaWidgetType:n,captchaError:a}}async _create(e){let{captchaToken:t,captchaWidgetType:a,captchaError:r}=await this.getCaptchaToken(),n={transfer:e.transfer,captchaToken:t,captchaWidgetType:a,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rK(e.unsafeMetadata):void 0,locale:e.locale??ty()};await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:n})}async create(e){return rD(this.#ep,async()=>{await this._create(e)})}async update(e){return rD(this.#ep,async()=>{let t={...e,unsafeMetadata:e.unsafeMetadata?rK(e.unsafeMetadata):void 0};await this.#ep.__internal_basePatch({path:this.#ep.pathRoot,body:t})})}async password(e){return rD(this.#ep,async()=>{let{captchaToken:t,captchaWidgetType:a,captchaError:r}=await this.getCaptchaToken(),n={strategy:"password",captchaToken:t,captchaWidgetType:a,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rK(e.unsafeMetadata):void 0};await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:n})})}async sendEmailCode(){return rD(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification"})})}async verifyEmailCode(e){let{code:t}=e;return rD(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{strategy:"email_code",code:t},action:"attempt_verification"})})}async sendPhoneCode(e){let{phoneNumber:t,channel:a="sms"}=e;return rD(this.#ep,async()=>{if(!this.#ep.id){let{captchaToken:e,captchaWidgetType:a,captchaError:r}=await this.getCaptchaToken();await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:{phoneNumber:t,captchaToken:e,captchaWidgetType:a,captchaError:r}})}await this.#ep.__internal_basePost({body:{strategy:"phone_code",channel:a},action:"prepare_verification"})})}async verifyPhoneCode(e){let{code:t}=e;return rD(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{strategy:"phone_code",code:t},action:"attempt_verification"})})}async sso(e){let{strategy:t,redirectUrl:a,redirectCallbackUrl:r,unsafeMetadata:n,legalAccepted:i,oidcPrompt:s,enterpriseConnectionId:o,emailAddress:l,popup:c}=e;return rD(this.#ep,async()=>{let{captchaToken:e,captchaWidgetType:u,captchaError:d}=await this.getCaptchaToken(),h=a;try{new URL(a)}catch{h=window.location.origin+a}let m={redirectUrl:rH.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:h};if(c){let e=rB(rH.clerk,{redirectCallbackUrl:m.redirectUrl,redirectUrl:h});m.redirectUrl=e.redirectCallbackUrl,m.actionCompleteRedirectUrl=e.redirectUrl}let p=()=>this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:{strategy:t,...m,unsafeMetadata:n,legalAccepted:i,oidcPrompt:s,enterpriseConnectionId:o,emailAddress:l,captchaToken:e,captchaWidgetType:u,captchaError:d}});await p().catch(async e=>{if(M(e)&&O(e))return await rH.clerk.__internal_environment.reload(),p();throw e});let{status:f,externalVerificationRedirectURL:g}=this.#ep.verifications.externalAccount;"unverified"===f&&g&&(c?(await rN(rH.clerk,{popup:c,externalVerificationRedirectURL:g}),await this.#ep.reload()):eV(g))})}async web3(e){let{strategy:t,unsafeMetadata:a,legalAccepted:r}=e,n=t.replace("web3_","").replace("_signature","");return rD(this.#ep,async()=>{let e,i,s;switch(n){case"metamask":e=await tj().getMetamaskIdentifier(),i=tj().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await tj().getCoinbaseWalletIdentifier(),i=tj().generateSignatureWithCoinbaseWallet;break;case"base":e=await tj().getBaseIdentifier(),i=tj().generateSignatureWithBase;break;case"okx_wallet":e=await tj().getOKXWalletIdentifier(),i=tj().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${n}`)}let o=e||this.#ep.web3wallet;await this._create({web3Wallet:o,unsafeMetadata:a,legalAccepted:r}),await this.#ep.__internal_basePost({body:{strategy:t},action:"prepare_verification"});let{message:l}=this.#ep.verifications.web3Wallet;l||tO("SignUp");try{s=await i({identifier:e,nonce:l})}catch(t){if("coinbase_wallet"===n&&4001===t.code)s=await i({identifier:e,nonce:l});else throw t}await this.#ep.__internal_basePost({body:{signature:s,strategy:t},action:"attempt_verification"})})}async ticket(e){let t=e?.ticket??eM("__clerk_ticket");return this.create({...e,ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};return rD(this.#ep,async()=>{if(!this.#ep.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#em=!0,await rH.clerk.setActive({session:this.#ep.createdSessionId,navigate:t})})}}class rG extends tH{id;name;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name),this}}class rJ extends tH{pathRoot="tokens";jwt;static async create(e,t={},a=!1){return new rJ(await tH._fetch({body:t,method:"POST",path:e,search:a?"debug=skip_cache":void 0}),e)}constructor(e,t){super(),t&&(this.pathRoot=t),e?.jwt&&(this.jwt=tb(e.jwt))}getRawString=()=>this.jwt?.claims.__raw||"";fromJSON(e){return e&&(this.jwt=tb(e.jwt)),this}__internal_toSnapshot(){return{object:"token",id:this.id||"",jwt:this.getRawString()}}}class rZ extends tH{pathRoot="/me";id="";secret;uri;verified=!1;backupCodes;updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.secret=e.secret,this.uri=e.uri,this.verified=e.verified,this.backupCodes=e.backup_codes,this.updatedAt=tV(e.updated_at),this.createdAt=tV(e.created_at)),this}}class r$ extends tH{pathRoot="/me";id;codes=[];updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.codes=e.codes,this.updatedAt=tV(e.updated_at),this.createdAt=tV(e.created_at)),this}}class rY extends tH{pathRoot="/me";id="";externalId=null;username=null;emailAddresses=[];phoneNumbers=[];web3Wallets=[];externalAccounts=[];enterpriseAccounts=[];passkeys=[];organizationMemberships=[];passwordEnabled=!1;firstName=null;lastName=null;fullName=null;primaryEmailAddressId=null;primaryEmailAddress=null;primaryPhoneNumberId=null;primaryPhoneNumber=null;primaryWeb3WalletId=null;primaryWeb3Wallet=null;imageUrl="";hasImage=!1;twoFactorEnabled=!1;totpEnabled=!1;backupCodeEnabled=!1;publicMetadata={};unsafeMetadata={};createOrganizationEnabled=!1;createOrganizationsLimit=null;deleteSelfEnabled=!1;lastSignInAt=null;legalAcceptedAt=null;updatedAt=null;createdAt=null;cachedSessionsWithActivities=null;static isUserResource(e){return!!e&&e instanceof rY}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case aG:return this.primaryEmailAddressId===e.id;case r_:return this.primaryPhoneNumberId===e.id;case r2:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:t}=e||{};return new aG({email_address:t},this.path()+"/email_addresses/").create()};createPasskey=()=>rj.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:t}=e||{};return new r_({phone_number:t},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:t}=e||{};return new r2({web3_wallet:t},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:t,redirectUrl:a,additionalScopes:r}=e||{};return new rl((await tH._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:t,redirect_url:a,additional_scope:r}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new rZ((await tH._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new rZ((await tH._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new aF((await tH._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new r$((await tH._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);update=e=>this._basePatch({body:rK(e)});updatePassword=e=>this._basePost({body:e,path:`${this.path()}/change_password`});removePassword=e=>this._basePost({body:e,path:`${this.path()}/remove_password`});delete=()=>this._baseDelete({path:"/me"}).then(e=>(rn.emit(rt,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await rT.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:t}=e||{};return null===t?rd.delete(`${this.path()}/profile_image`):rd.create(`${this.path()}/profile_image`,{file:t})};getOrganizationInvitations=e=>rX.retrieve(e);getOrganizationSuggestions=e=>rw.retrieve(e);getOrganizationMemberships=e=>ry.retrieve(e);leaveOrganization=async e=>new aF((await tH._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);initializePaymentMethod=e=>ax(e);addPaymentMethod=e=>aj(e);getPaymentMethods=e=>a_(e);get verifiedExternalAccounts(){return this.externalAccounts.filter(e=>e.verification?.status=="verified")}get unverifiedExternalAccounts(){return this.externalAccounts.filter(e=>e.verification?.status!="verified")}get verifiedWeb3Wallets(){return this.web3Wallets.filter(e=>e.verification?.status=="verified")}get hasVerifiedEmailAddress(){return this.emailAddresses.filter(e=>"verified"===e.verification.status).length>0}get hasVerifiedPhoneNumber(){return this.phoneNumbers.filter(e=>"verified"===e.verification.status).length>0}fromJSON(e){return e&&(this.id=e.id,this.externalId=e.external_id||null,this.firstName=e.first_name||null,this.lastName=e.last_name||null,(this.firstName||this.lastName)&&(this.fullName=(({firstName:e,lastName:t,name:a})=>a||[e,t].join(" ").trim()||"")({firstName:this.firstName,lastName:this.lastName})),this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.username=e.username||null,this.passwordEnabled=e.password_enabled||!1,this.emailAddresses=(e.email_addresses||[]).map(e=>new aG(e,this.path()+"/email_addresses")),this.primaryEmailAddressId=e.primary_email_address_id||null,this.primaryEmailAddress=this.emailAddresses.find(({id:e})=>e===this.primaryEmailAddressId)||null,this.phoneNumbers=(e.phone_numbers||[]).map(e=>new r_(e,this.path()+"/phone_numbers")),this.primaryPhoneNumberId=e.primary_phone_number_id||null,this.primaryPhoneNumber=this.phoneNumbers.find(({id:e})=>e===this.primaryPhoneNumberId)||null,this.web3Wallets=(e.web3_wallets||[]).map(e=>new r2(e,this.path()+"/web3_wallets")),this.primaryWeb3WalletId=e.primary_web3_wallet_id||null,this.primaryWeb3Wallet=this.web3Wallets.find(({id:e})=>e===this.primaryWeb3WalletId)||null,this.externalAccounts=(e.external_accounts||[]).map(e=>new rl(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new rj(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new ry(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new a4(e,this.path()+"/enterprise_accounts")),this.publicMetadata=e.public_metadata||{},this.unsafeMetadata=e.unsafe_metadata||{},this.totpEnabled=e.totp_enabled||!1,this.backupCodeEnabled=e.backup_code_enabled||!1,this.twoFactorEnabled=e.two_factor_enabled||!1,this.createOrganizationEnabled=e.create_organization_enabled||!1,this.createOrganizationsLimit=e.create_organizations_limit||null,this.deleteSelfEnabled=e.delete_self_enabled||!1,e.last_sign_in_at&&(this.lastSignInAt=tV(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=tV(e.legal_accepted_at)),this.updatedAt=tV(e.updated_at||void 0),this.createdAt=tV(e.created_at||void 0)),this}__internal_toSnapshot(){return{object:"user",id:this.id,external_id:this.externalId,first_name:this.firstName,last_name:this.lastName,username:this.username,public_metadata:this.publicMetadata,unsafe_metadata:this.unsafeMetadata,image_url:this.imageUrl,has_image:this.hasImage,email_addresses:this.emailAddresses.map(e=>e.__internal_toSnapshot()),phone_numbers:this.phoneNumbers.map(e=>e.__internal_toSnapshot()),web3_wallets:this.web3Wallets.map(e=>e.__internal_toSnapshot()),external_accounts:this.externalAccounts.map(e=>e.__internal_toSnapshot()),passkeys:this.passkeys.map(e=>e.__internal_toSnapshot()),organization_memberships:this.organizationMemberships.map(e=>e.__internal_toSnapshot()),enterprise_accounts:this.enterpriseAccounts.map(e=>e.__internal_toSnapshot()),totp_enabled:this.totpEnabled,backup_code_enabled:this.backupCodeEnabled,two_factor_enabled:this.twoFactorEnabled,create_organization_enabled:this.createOrganizationEnabled,create_organizations_limit:this.createOrganizationsLimit,delete_self_enabled:this.deleteSelfEnabled,primary_email_address_id:this.primaryEmailAddressId,primary_phone_number_id:this.primaryPhoneNumberId,primary_web3_wallet_id:this.primaryWeb3WalletId,password_enabled:this.passwordEnabled,profile_image_id:this.imageUrl,last_sign_in_at:this.lastSignInAt?.getTime()||null,legal_accepted_at:this.legalAcceptedAt?.getTime()||null,updated_at:this.updatedAt?.getTime()||null,created_at:this.createdAt?.getTime()||null}}}class rQ{firstName;lastName;imageUrl;hasImage;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.firstName=e.first_name,this.lastName=e.last_name,this.imageUrl=e.image_url??void 0,this.hasImage=e.has_image??void 0),this}__internal_toSnapshot(){return{first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl||null,has_image:this.hasImage||null}}}class rX extends tH{id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await tH._fetch({path:"/me/organization_invitations",method:"GET",search:as(e)}).then(e=>{let{data:t,total_count:a}=e?.response;return{total_count:a,data:t.map(e=>new rX(e))}})}constructor(e){super(),this.fromJSON(e)}accept=async()=>await this._basePost({path:`/me/organization_invitations/${this.id}/accept`});fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.publicOrganizationData={hasImage:e.public_organization_data.has_image,imageUrl:e.public_organization_data.image_url,name:e.public_organization_data.name,id:e.public_organization_data.id,slug:e.public_organization_data.slug},this.publicMetadata=e.public_metadata,this.role=e.role,this.status=e.status,this.createdAt=tV(e.created_at),this.updatedAt=tV(e.updated_at)),this}}let r1={enabled:!1,first_factors:[],name:"phone_number",required:!1,second_factors:[],used_for_first_factor:!1,used_for_second_factor:!1,verifications:[],verify_at_sign_up:!1};class r0 extends tH{id=void 0;actions={create_organization:!1,delete_self:!1};attributes={email_address:{enabled:!0,first_factors:["email_code"],name:"email_address",required:!0,second_factors:[],used_for_first_factor:!0,used_for_second_factor:!1,verifications:["email_code"],verify_at_sign_up:!0},phone_number:{...r1,name:"phone_number"},username:{...r1,name:"username"},web3_wallet:{...r1,name:"web3_wallet"},first_name:{...r1,name:"first_name"},last_name:{...r1,name:"last_name"},password:{enabled:!0,first_factors:[],name:"password",required:!0,second_factors:[],used_for_first_factor:!1,used_for_second_factor:!1,verifications:[],verify_at_sign_up:!1},authenticator_app:{...r1,name:"authenticator_app"},backup_code:{...r1,name:"backup_code"},passkey:{...r1,name:"passkey"}};enterpriseSSO={enabled:!1};passkeySettings={allow_autofill:!1,show_sign_in_button:!1};passwordSettings={};signIn={second_factor:{required:!1,enabled:!1}};signUp={allowlist_only:!1,captcha_enabled:!1,legal_consent_enabled:!1,mode:"public",progressive:!0};social={};usernameSettings={};get authenticatableSocialStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled&&e.authenticatable).map(([,e])=>e.strategy).sort():[]}get enabledFirstFactorIdentifiers(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&!e.startsWith("web3")).map(([e])=>e):[]}get socialProviderStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled).map(([,e])=>e.strategy).sort():[]}get web3FirstFactors(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&e.startsWith("web3")).map(([,e])=>e.first_factors).flat():[]}get alternativePhoneCodeChannels(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&"phone_number"===e).map(([,e])=>e?.channels?.filter(e=>"sms"!==e)||[]).flat():[]}constructor(e=null){super(),this.fromJSON(e)}get instanceIsPasswordBased(){return!!(this.attributes?.password?.enabled&&this.attributes.password?.required)}get hasValidAuthFactor(){return!!(this.attributes?.email_address?.enabled||this.attributes?.phone_number?.enabled||this.attributes.password?.required&&this.attributes.username?.required)}fromJSON(e){return e&&(this.attributes=this.withDefault(e.attributes?Object.fromEntries(Object.entries(e.attributes).map(e=>[e[0],{...e[1],name:e[0]}])):null,this.attributes),this.actions=this.withDefault(e.actions,this.actions),this.enterpriseSSO=this.withDefault(e.enterprise_sso,this.enterpriseSSO),this.passkeySettings=this.withDefault(e.passkey_settings,this.passkeySettings),this.passwordSettings=e.password_settings?{...e.password_settings,min_length:Math.max(e.password_settings?.min_length??8,8),max_length:e.password_settings?.max_length===0?72:Math.min(e.password_settings?.max_length??72,72)}:this.passwordSettings,this.signIn=this.withDefault(e.sign_in,this.signIn),this.signUp=this.withDefault(e.sign_up,this.signUp),this.social=this.withDefault(e.social,this.social),this.usernameSettings=e.username_settings?{...e.username_settings,min_length:Math.max(e.username_settings?.min_length??4,4),max_length:Math.min(e.username_settings?.max_length??64,64)}:this.usernameSettings),this}__internal_toSnapshot(){return{actions:this.actions,attributes:this.attributes,passkey_settings:this.passkeySettings,password_settings:this.passwordSettings,sign_in:this.signIn,sign_up:this.signUp,social:this.social}}}class r2 extends tH{id;web3Wallet="";verification;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}create(){return this._basePost({body:{web3_wallet:this.web3Wallet}})}prepareVerification=e=>this._basePost({action:"prepare_verification",body:{...e}});attemptVerification=e=>{let{signature:t}=e;return this._basePost({action:"attempt_verification",body:{signature:t}})};destroy(){return this._baseDelete()}toString(){return this.web3Wallet}fromJSON(e){return e&&(this.id=e.id,this.web3Wallet=e.web3_wallet,this.verification=new a9(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}class r3 extends tH{pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=tV(e.updated_at),this.createdAt=tV(e.created_at)),this}static async join(e){return new r3((await tH._fetch({path:"/waitlist",method:"POST",body:e}))?.response)}}function r9(e,t){var a,r;return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||(a=t,r=e,a.organizationMemberships.length!==r.organizationMemberships.length||a.organizationMemberships[0]?.updatedAt!==r.organizationMemberships[0]?.updatedAt)}function r5(e,t){return!function(e,t){if(!e&&t||e&&!t)return!0;if(!e&&e===t)return!1;if(!e||!t)return!0;try{if(aN.isClientResource(e))return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.sessions.length!==t.sessions.length;if(rO.isSessionResource(e)){var a,r;return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.lastActiveToken?.jwt?.claims?.__raw!==t.lastActiveToken?.jwt?.claims?.__raw||function(e,t){if(e.lastActiveOrganizationId!==t.lastActiveOrganizationId)return!0;let a=e.user?.organizationMemberships?.find(t=>t.organization.id===e.lastActiveOrganizationId),r=t.user?.organizationMemberships?.find(t=>t.organization.id===e.lastActiveOrganizationId);return a?.permissions?.length!==r?.permissions?.length}(e,t)||(a=e,r=t,!!a.user!=!!r.user||!!a.user&&!!r.user&&r9(a.user,r.user))}if(rY.isUserResource(e))return r9(e,t)}catch{}return!0}(e,t)?e:t}let r6="__clerk_db_jwt";function r8(e,t){let a=new URL(e),r=a.searchParams.get(r6);a.searchParams.delete(r6);let n=r||t;return n&&a.searchParams.set(r6,n),a}let r4=e=>{let t=new URL(e);return t.searchParams.delete(r6),t},r7=e=>{let t=new URL(e);return t.searchParams.delete("__dev_session"),t.hash=decodeURI(t.hash).replace(/__clerk_db_jwt\[(.*)\]/,""),t.href.endsWith("#")&&(t.hash=""),t};function ne(e){for(var t=1;t<arguments.length;t++){var a=arguments[t];for(var r in a)e[r]=a[r]}return e}var nt=function e(t,a){function r(e,r,n){if("undefined"!=typeof document){"number"==typeof(n=ne({},a,n)).expires&&(n.expires=new Date(Date.now()+864e5*n.expires)),n.expires&&(n.expires=n.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var i="";for(var s in n)n[s]&&(i+="; "+s,!0!==n[s]&&(i+="="+n[s].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+i}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var a=document.cookie?document.cookie.split("; "):[],r={},n=0;n<a.length;n++){var i=a[n].split("="),s=i.slice(1).join("=");try{var o=decodeURIComponent(i[0]);if(r[o]=t.read(s,o),e===o)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",ne({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,ne({},this.attributes,t))},withConverter:function(t){return e(ne({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(a)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});function na(e){return{get:()=>nt.get(e),set(t,a={}){nt.set(e,t,a)},remove(t){nt.remove(e,t)}}}let nr=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function nn(e,t){let a=function(e){try{return new Date(e||new Date)}catch{return new Date}}(e);return a.setFullYear(a.getFullYear()+t),a}let ni=na("__clerk_test_etld"),ns="__client_uat",no="__session",nl=()=>{let e=tk()?"None":"Lax",t=nr(e);return{sameSite:e,secure:t,partitioned:!1}};async function nc(e){let t;try{t=await eb(e)}catch(o){var a;a=`Suffixed cookie failed due to ${o.message} (secure-context: ${window.isSecureContext}, url: ${window.location.href})`,Q.has(a)||(console.log(a),Q.add(a));let{default:r}=await Promise.resolve().then(n.t.bind(n,180,23)),{default:i}=await Promise.resolve().then(n.t.bind(n,3413,23)),s=r(e);t=i.stringify(s).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}return t}let nu=()=>{let e=tk()?"None":"Lax",t=nr(e);return{sameSite:e,secure:t}};var nd=n(5945),nh=n.n(nd);class nm{lock=(w="clerk.lock.refreshSessionToken",s=new(nh()),window.addEventListener("beforeunload",async()=>{await s.releaseLock(w)}),{acquireLockAndRun:async e=>{if("locks"in navigator&&isSecureContext){let t=new AbortController,a=setTimeout(()=>t.abort(),4999);return await navigator.locks.request(w,{signal:t.signal},async()=>(clearTimeout(a),await e())).catch(()=>!1)}if(await s.acquireLock(w,5e3))try{return await e()}finally{await s.releaseLock(w)}}});workerTimers=aH();timerId=null;initiated=!1;startPollingForSessionToken(e){if(this.timerId||this.initiated)return;let t=async()=>{this.initiated=!0,await this.lock.acquireLockAndRun(e),this.timerId=this.workerTimers.setTimeout(t,5e3)};t()}stopPollingForSessionToken(){null!=this.timerId&&(this.workerTimers.clearTimeout(this.timerId),this.timerId=null),this.initiated=!1}}class np{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,t,a,r){let n=await nc(e.publishableKey),i=new np(e,t,n,a,r);return await i.setup(),i}constructor(e,t,r,n,i){let s,o,l,c,u,d,h;this.clerk=e,this.instanceType=n,this.clerkEventBus=i,rn.on(re,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),rn.on(rt,()=>this.handleSignOut()),this.refreshTokenOnFocus(),this.startPollingForToken(),this.clientUat=(s=na(ns),o=na(ey(ns,r)),{set:e=>{let t=nn(Date.now(),1),r=tk()?"None":"Strict",n=nr(r),i=function(e=window.location.hostname,t=ni){if(a)return a;if(["localhost","127.0.0.1","0.0.0.0"].includes(e))return e;let r=e.split(".");if(1===r.length)return e;for(let e=r.length-2;e>=0;e--){let n=r.slice(e).join(".");if(t.set("1",{domain:n}),"1"===t.get())return t.remove({domain:n}),a=n,n;t.remove({domain:n})}}(),l="0";e&&e.updatedAt&&e.signedInSessions.length>0&&(l=Math.floor(e.updatedAt.getTime()/1e3).toString()),o.remove(),s.remove(),o.set(l,{domain:i,expires:t,partitioned:!1,sameSite:r,secure:n}),s.set(l,{domain:i,expires:t,partitioned:!1,sameSite:r,secure:n})},get:()=>parseInt(o.get()||s.get()||"0",10)}),this.sessionCookie=(l=na(no),c=na(ey(no,r)),{set:e=>{let t=nn(Date.now(),1),{sameSite:a,secure:r,partitioned:n}=nl();n&&u(),l.set(e,{expires:t,sameSite:a,secure:r,partitioned:n}),c.set(e,{expires:t,sameSite:a,secure:r,partitioned:n})},remove:u=()=>{let e=nl();l.remove(e),c.remove(e)},get:()=>c.get()||l.get()}),this.activeCookie=(d=na("clerk_active_context"),h={secure:nr("None")},{set:e=>{d.set(e,h)},get:()=>d.get(),remove:()=>d.remove(h)}),this.devBrowser=function({cookieSuffix:e,frontendApi:t,fapiClient:a}){let r,n,i=(r=na(r6),n=na(ey(r6,e)),{get:()=>n.get()||r.get(),set:e=>{let t=nn(Date.now(),1),{sameSite:a,secure:i}=nu();n.set(e,{expires:t,sameSite:a,secure:i}),r.set(e,{expires:t,sameSite:a,secure:i})},remove:()=>{let e=nu();n.remove(e),r.remove(e)}});function s(){return i.get()}function o(e){i.set(e)}function l(){i.remove()}return{clear:function(){l()},setup:async function(){var e;let r;if(!ej(t))return;a.onBeforeRequest(e=>{let t=s();t&&e?.url&&(e.url=r8(e.url,t))}),a.onAfterResponse((e,t)=>{let a=t?.headers?.get("Clerk-Db-Jwt");a&&o(a)});let n=(r=(e=new URL(window.location.href)).searchParams.get(r6)||"",r4(r7(e)).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",r4(r7(e))),r);if(n)return void o(n);if(i.get())return;let l=a.buildUrl({path:"/dev_browser"}),c=await fetch(l.toString(),{method:"POST"});if(!c.ok){let e=function(e=[]){return e.length>0?e.map(e=>new v(e)):[]}((await c.json()).errors);e[0]?tI(e[0].longMessage):tI()}let u=await c.json();o(u?.id)},getDevBrowserJWT:s,setDevBrowserJWT:o,removeDevBrowserJWT:l}}({frontendApi:e.frontendApi,fapiClient:t,cookieSuffix:r})}async setup(){return"production"===this.instanceType?this.setupProduction():this.setupDevelopment()}isSignedOut(){return this.clerk.loaded?!!this.clerk.user:0>=this.clientUat.get()}async handleUnauthenticatedDevBrowser(){this.devBrowser.clear(),await this.devBrowser.setup()}decorateUrlWithDevBrowserToken(e){let t=this.devBrowser.getDevBrowserJWT();if(!t)throw Error(`${tA} Missing dev browser jwt. Please contact support.`);return r8(e,t)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new nm,this.poller.startPollingForSessionToken(()=>this.refreshSessionToken()))}stopPollingForToken(){this.poller&&(this.poller.stopPollingForSessionToken(),this.poller=null)}refreshTokenOnFocus(){window.addEventListener("focus",()=>{"visible"===document.visibilityState&&this.refreshSessionToken({updateCookieImmediately:!0})})}async refreshSessionToken({updateCookieImmediately:e=!1}={}){if(this.clerk.session)try{let t=await this.clerk.session.getToken();e&&this.updateSessionCookie(t)}catch(e){return this.handleGetTokenError(e)}}updateSessionCookie(e){if(document.hasFocus()||this.isCurrentContextActive())return e||d()||tn.warn("Removing session cookie (offline)",{sessionId:this.clerk.session?.id},"authCookieService"),this.setActiveContextInStorage(),e?this.sessionCookie.set(e):this.sessionCookie.remove()}setClientUatCookieForDevelopmentInstances(){"production"!==this.instanceType&&this.inCustomDevelopmentDomain()&&this.clientUat.set(this.clerk.client)}inCustomDevelopmentDomain(){let e=this.clerk.frontendApi.replace("clerk.","");return!window.location.host.endsWith(e)}handleGetTokenError(e){if(M(e)||R(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(T(e))return void this.clerk.handleUnauthenticated().catch(e8);this.clerkEventBus.emit(g,"degraded")}}handleSignOut(){this.activeCookie.remove(),this.sessionCookie.remove(),this.setClientUatCookieForDevelopmentInstances()}setActiveContextInStorage(){let e=this.clerk.session?.id||"",t=this.clerk.organization?.id||"",a=`${e}:${t}`;":"!==a?this.activeCookie.set(a):this.activeCookie.remove()}isCurrentContextActive(){let e=this.activeCookie.get();if(!e)return!0;let[t,a]=e.split(":"),r=this.clerk.session?.id||"",n=this.clerk.organization?.id||"";return t===r&&a===n}getSessionCookie(){return this.sessionCookie.get()}}class nf{clerk;captchaChallenge;timers;constructor(e,t=new tW(e),a=aH()){this.clerk=e,this.captchaChallenge=t,this.timers=a}async start(){this.isEnabled()&&(await this.challengeAndSend(),this.timers.setInterval(()=>{this.challengeAndSend()},this.intervalInMs()))}async challengeAndSend(){if(!(!this.clerk.client||this.clientBypass()))try{let e=await this.captchaChallenge.invisible({action:"heartbeat"});await this.clerk.client.__internal_sendCaptchaToken(e)}catch{}}isEnabled(){return!!this.clerk.__internal_environment?.displayConfig?.captchaHeartbeat}clientBypass(){return this.clerk.client?.captchaBypass}intervalInMs(){return this.clerk.__internal_environment?.displayConfig?.captchaHeartbeatIntervalMs??6e5}}let ng=["/client","/waitlist"];class nb{async getBaseFapiProxyOptions(){let e=await tH.clerk.session?.getToken();if(!e)throw new C("No valid session token available",{code:"no_session_token"});return{pathPrefix:"",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},credentials:"same-origin"}}async getAll(e){return tH._fetch({...await this.getBaseFapiProxyOptions(),method:"GET",path:"/api_keys",search:as({...e,subject:e?.subject??tH.clerk.organization?.id??tH.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:t,total_count:a}=e;return{total_count:a,data:t.map(e=>new tG(e))}})}async create(e){return new tG(await tH._fetch({...await this.getBaseFapiProxyOptions(),path:"/api_keys",method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??tH.clerk.organization?.id??tH.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new tG(await tH._fetch({...await this.getBaseFapiProxyOptions(),method:"POST",path:`/api_keys/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let ny=new Map;class nw{#es=!1;load(e){let t=e?.protectConfig;if(t?.loaders&&Array.isArray(t.loaders)&&0!==t.loaders.length&&!this.#es){if(o())for(let e of(this.#es=!0,t.loaders))try{this.applyLoader(e)}catch(e){X(`[protect] failed to apply loader: ${e}`)}}}applyLoader(e){if(void 0!==e.rollout){let t=e.rollout;if("number"!=typeof t||t<0)return void X(`[protect] loader rollout value is invalid: ${t}`);if(0===t||Math.random()>t)return}let t=e.type||"script",a=e.target||"body",r=document.createElement(t);if(e.attributes)for(let[t,a]of Object.entries(e.attributes))switch(typeof a){case"string":case"number":case"boolean":r.setAttribute(t,String(a));break;default:X(`[protect] loader attribute is invalid type: ${t}=${a}`)}switch(e.textContent&&"string"==typeof e.textContent&&(r.textContent=e.textContent),a){case"head":document.head.appendChild(r);break;case"body":document.body.appendChild(r);break;default:if(a?.startsWith("#")){let e=document.getElementById(a.substring(1));if(!e)return void X(`[protect] loader target element not found: ${a}`);e.appendChild(r);return}X(`[protect] loader target is invalid: ${a}`)}}}class nk{signInResourceSignal=al;signInErrorSignal=ac;signInFetchSignal=au;signInSignal=ad;signUpResourceSignal=ah;signUpErrorSignal=am;signUpFetchSignal=ap;signUpSignal=af;__internal_effect=t7;__internal_computed=t4;constructor(){rn.on("resource:update",this.onResourceUpdated),rn.on("resource:error",this.onResourceError),rn.on("resource:fetch",this.onResourceFetch)}onResourceError=e=>{e.resource instanceof rL&&this.signInErrorSignal({error:e.error}),e.resource instanceof rH&&this.signUpErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof rL){if(nv(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof rH){if(nv(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}};onResourceFetch=e=>{e.resource instanceof rL&&this.signInFetchSignal({status:e.status}),e.resource instanceof rH&&this.signUpFetchSignal({status:e.status})}}function nv(e,t){return!t?.id&&e&&e.__internal_future?.hasBeenFinalized===!1}let nx="cannot_render_billing_disabled",nj="cannot_render_user_missing",n_="cannot_render_organizations_disabled",nz="cannot_render_organization_missing",nS="cannot_render_single_session_enabled",nE={polling:!0,standardBrowser:!0,touchSession:!0,isSatellite:!1,signInUrl:void 0,signUpUrl:void 0,afterSignOutUrl:void 0,signInFallbackRedirectUrl:void 0,signUpFallbackRedirectUrl:void 0,signInForceRedirectUrl:void 0,signUpForceRedirectUrl:void 0,newSubscriptionRedirectUrl:void 0};class nA{static version="6.0.0-canary.v20251217205250";static sdkMetadata={name:"@clerk/clerk-js",version:"6.0.0-canary.v20251217205250"};static _billing;static _apiKeys;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new nk;internal_last_error=null;environment;#ef;#eg="";#eb;#ey;#ew;#ek;#ev;#ex=null;#ej;#e_;#ez;#eS="loading";#eE=[];#eA=[];#eI={};#eC=null;#eP=0;#eq=f();get __internal_queryClient(){return this.#ef||Promise.resolve().then(n.bind(n,3303)).then(e=>e.QueryClient).then(e=>{this.#ef||(this.#ef=new e,this.#eq.emit("queryClientStatus","ready"))}),this.#ef?{__tag:"clerk-rq-client",client:this.#ef}:void 0}__internal_getCachedResources;__internal_createPublicCredentials;__internal_getPublicCredentials;__internal_isWebAuthnSupported;__internal_isWebAuthnAutofillSupported;__internal_isWebAuthnPlatformAuthenticatorSupported;__internal_setActiveInProgress=!1;get publishableKey(){return this.#eg}get version(){return nA.version}set sdkMetadata(e){nA.sdkMetadata=e}get sdkMetadata(){return nA.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#eS}get isSatellite(){return!!tw()&&e6(this.#eI.isSatellite,new URL(window.location.href),!1)}get domain(){if(tw()){let e=function(e=""){return(e||"").replace(/^.+:\/\//,"")}(e6(this.#eb,new URL(window.location.href)));if("production"===this.#ez){let t;if(!e)return"";if(e.match(/^(clerk\.)+\w*$/))t=/(clerk\.)*(?=clerk\.)/;else{if(e.match(/\.clerk.accounts/))return e;t=/^(clerk\.)*/gi}return`clerk.${e.replace(t,"")}`}return e}return""}get proxyUrl(){if(tw()){let e=e6(this.#ey,new URL(window.location.href));return!e||eG(e)||eJ(e)||tf.throwInvalidProxyUrl({url:e}),e?eJ(e)?new URL(e,window.location.origin).toString():e:""}return""}get frontendApi(){let e=ef(this.publishableKey);return e?e.frontendApi:tf.throwInvalidPublishableKeyError({key:this.publishableKey})}get instanceType(){return this.#ez}get isStandardBrowser(){return this.#eI.standardBrowser||!1}get billing(){return nA._billing||(nA._billing=new ao),nA._billing}get apiKeys(){return nA._apiKeys||(nA._apiKeys=new nb),nA._apiKeys}__experimental_checkout(e){return this._checkout||(this._checkout=e=>(function(e,t){let a,r,n,i,{for:s,planId:o,planPeriod:l}=t;if(null===e.user)throw Error("Clerk: User is not authenticated");if("organization"===s&&null===e.organization)throw Error("Clerk: The current session does not have an active organization. Use `setActive` to set the organization");let c=function(e){let{userId:t,orgId:a,planId:r,planPeriod:n}=e;return`${t}-${a||"user"}-${r}-${n}`}({userId:e.user?.id||"",orgId:"organization"===s?e.organization?.id:void 0,planId:o,planPeriod:l}),u=ny.get(c);if(u)return u.signals.computedSignal();let d=(a=t8({resource:null}),r=t8({error:null}),n=t8({status:"idle"}),i=t4(()=>{let e=a().resource,t=r().error,i=n().status;return{errors:ag(t,{}),fetchStatus:i,checkout:e}}),{resourceSignal:a,errorSignal:r,fetchSignal:n,computedSignal:i}),h=new aw(d,{..."organization"===s?{orgId:e.organization?.id}:{},planId:o,planPeriod:l});return ny.set(c,{resource:h,signals:d}),d.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#eI[e]}get isSignedIn(){return this?.session?.status!=="pending"&&!!this.session}constructor(e,t){if(!(e=(e||"").trim()))return tf.throwMissingPublishableKeyError();let a=ef(e);if(!a)return tf.throwInvalidPublishableKeyError({key:e});this.#eb=t?.domain,this.#ey=t?.proxyUrl,this.environment=ro.getInstance(),this.#ez=a.instanceType,this.#eg=e,this.#e_=function(e){let t=[],a=[];async function r(e){for await(let a of["undefined"!=typeof window&&window.__internal_onBeforeRequest,...t].filter(e=>e))if(await a(e)===!1)return!1;return!0}async function n(e,t){for await(let r of["undefined"!=typeof window&&window.__internal_onAfterResponse,...a].filter(e=>e))if(await r(e,t)===!1)return!1;return!0}function i({method:t,path:a,sessionId:r,search:n,rotatingTokenNonce:i}){let s=new URLSearchParams(n);return s.append("__clerk_api_version","2025-11-10"),s.append("_clerk_js_version","6.0.0-canary.v20251217205250"),i&&s.append("rotating_token_nonce",i),e.domain&&"development"===e.instanceType&&e.isSatellite&&s.append("__domain",e.domain),t&&"GET"!==t&&"POST"!==t&&s.append("_method",t),a&&!ng.some(e=>a.startsWith(e))&&r&&s.append("_clerk_session_id",r),ek([...s.entries()].reduce((e,[t,a])=>(e[t]=a.includes(",")?a.split(","):a,e),{}))}function s(t){let{path:a,pathPrefix:r="v1"}=t;if(e.proxyUrl){let n=new URL(e.proxyUrl),s=n.pathname.slice(1);return s.endsWith("/")&&(s=s.slice(0,-1)),eS({base:n.origin,pathname:`${s}/${r}${a}`,search:i(t)},{stringify:!1})}let n="production"===e.instanceType?e.domain:"";return eS({base:`https://${n||e.frontendApi}`,pathname:`${r}${a}`,search:i(t)},{stringify:!1})}async function o(t,a){let i,o={...t},{method:l="GET",body:c}=o;!c||"object"!=typeof c||c instanceof FormData||(o.body=function(e){if(!e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype)return e;let t={};for(let[a,r]of Object.entries(e))void 0!==r&&(t[a]=r);return t}(c)),o.url=s({...o,sessionId:e.getSessionId()}),o.headers=new Headers(o.headers),"GET"===l||c instanceof FormData||o.headers.has("content-type")||o.headers.set("content-type","application/x-www-form-urlencoded"),"application/x-www-form-urlencoded"===o.headers.get("content-type")&&(o.body=c?ek(c,{keyEncoder:er}):c);let d=await r(o),h="GET"===l?"GET":"POST",m=o.url,p={...o,method:h,credentials:o.credentials||"include"};try{if(d){let e=a?.fetchMaxTries??(u()?4:11);i=await tl(()=>fetch(m,p),{retryImmediately:!0,initialDelay:700,maxDelayBetweenRetries:5e3,shouldRetry:(t,a)=>"GET"===h&&a<e,onBeforeRetry:e=>{m.searchParams.set("_clerk_retry_attempt",e.toString())}})}else i=new Response("{}",o)}catch(t){let e=m.toString();tn.error("network error",{error:t,url:e,method:l},"fapiClient");throw Error(`${tA} Network error at "${e}" - ${t}. Please try again.`)}let f=204!==i.status?await i.json():null,g=Object.assign(i,{payload:f});return i.ok||tn.error("request failed",{method:l,path:o.path,status:i.status},"fapiClient"),await n(o,g),g}return{buildEmailAddress:function(t){return function({localPart:e,frontendApi:t}){return`${e}@${t?t.replace("clerk.",""):"clerk.com"}`}({localPart:t,frontendApi:e.frontendApi})},buildUrl:s,onAfterResponse:function(e){a.push(e)},onBeforeRequest:function(e){t.push(e)},request:o}}({domain:this.domain,frontendApi:this.frontendApi,instanceType:this.instanceType,isSatellite:this.isSatellite,getSessionId:()=>this.session?.id,proxyUrl:this.proxyUrl}),this.#eq.emit(g,"loading"),this.#eq.prioritizedOn(g,e=>this.#eS=e),tH.clerk=this,this.#ek=new nw}getFapiClient=()=>this.#e_;load=async e=>{if(tn.info("load() start",{},"clerk"),!this.loaded){if("development"===this.#ez&&X("Clerk: Clerk has been loaded with development keys. Development instances have strict usage limits and should not be used when deploying your application to production. Learn more: https://clerk.com/docs/deployments/overview"),this.#eI=this.#eO(e),this.#eI.clerkUiCtor&&(this.#ej=Promise.resolve(this.#eI.clerkUiCtor).then(e=>new e(()=>this,()=>this.environment,this.#eI,new tu))),"development"===this.#ez&&(this.#eI.routerPush||this.#eI.routerReplace)&&(!this.#eI.routerPush||!this.#eI.routerReplace)){let e=this.#eI.routerPush?"routerReplace":"routerPush";X(`Clerk: Both \`routerPush\` and \`routerReplace\` need to be defined, but \`${e}\` is not defined. This may cause issues with navigation in your application.`)}rn.on(rr,()=>{this.#eT(this.session),this.#eU()}),this.#eI.sdkMetadata&&(nA.sdkMetadata=this.#eI.sdkMetadata),!1!==this.#eI.telemetry&&(this.telemetry=new eX({clerkVersion:nA.version,samplingRate:1,perEventSampling:!this.#eI.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#eI.telemetry}),this.#eI.appearance&&this.telemetry.record({event:"THEME_USAGE",eventSamplingRate:1,payload:function(e){let t;if(!e||"object"!=typeof e)return{};let a=e.theme;if(!a)return{};if(Array.isArray(a))for(let e of a){let a=e5(e);if(a){t=a;break}}else t=e5(a);return{themeName:t}}(this.#eI.appearance)}));try{this.#eI.standardBrowser?await this.#eM():await this.#eR();let e=this.#eI.telemetry,t=!1!==e&&!e?.disabled,a=!!this.#eI.__internal_keyless_claimKeylessApplicationUrl,r=!!this.environment?.clientDebugMode,n=this.environment?.isProduction?.()??!1,i=r||a&&!n,s=a&&!r?"error":void 0;i&&function(e={}){if(te)return;let{enabled:t=!1,...a}=e;t&&(e4=!0,te=!0,tr(a))}({enabled:!0,...s?{logLevel:s}:{},...t&&this.telemetry?{telemetryCollector:this.telemetry}:{}}),this.#ek?.load(this.environment),tn.info("load() complete",{},"clerk")}catch(e){throw this.#eq.emit(g,"error"),tn.error("load() failed",{error:e},"clerk"),e}}};#eB(){let e;return!!(!this.#eI.signUpUrl&&this.#eI.signInUrl&&(e=this.#eI.signInUrl,!ew.test(e)))}signOut=async(e,t)=>{if(!this.client||0===this.client.sessions.length)return;let a="undefined"!=typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:e8,r="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e8,n=e&&"object"==typeof e?e:t||{},i=n?.redirectUrl||this.buildAfterSignOutUrl();tn.debug("signOut() start",{hasClient:!!this.client,multiSessionCount:this.client?.signedInSessions.length??0,redirectUrl:i,sessionTarget:n?.sessionId??null},"clerk");let s="function"==typeof e?e:void 0,o=async()=>{let e=td(this.#eI.standardBrowser);rn.emit(rt,null),this.#eN(),await e.track(async()=>{s?await s():await this.navigate(i)}),e.isUnloading()||(this.#eT(),this.#eU(),await r())};if(await a(),!n.sessionId||1===this.client.signedInSessions.length){this.#eI.experimental?.persistClient??!0?await this.client.removeSessions():await this.client.destroy(),await o(),tn.info("signOut() complete",{redirectUrl:eE(i)},"clerk");return}let l=this.client.signedInSessions.find(e=>e.id===n.sessionId),c=l?.id&&this.session?.id===l.id;await l?.remove(),c&&(await o(),tn.info("signOut() complete",{redirectUrl:eE(i)},"clerk"))};openGoogleOneTap=e=>{this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(t=>t.openModal("googleOneTap",e||{})),this.telemetry?.record(e9("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(L(this,this.environment)){if("development"===this.#ez)throw new C(eW.cannotOpenSignInOrSignUp,{code:nS});return}this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(t=>t.openModal("signIn",e||{}));let t={withSignUp:e?.withSignUp??this.#eB()};this.telemetry?.record(e9("SignIn",e,t))};closeSignIn=()=>{this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(W(this,this.environment)){if("development"===this.#ez)throw new C(eW.cannotRenderAnyBillingComponent("Checkout"),{code:nx});return}if(!this.user){if("development"===this.#ez)throw new C(eW.cannotOpenCheckout,{code:nj});return}this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(t=>t.openDrawer("checkout",e||{}))};__internal_closeCheckout=()=>{this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("checkout"))};__internal_openPlanDetails=e=>{if(W(this,this.environment)){if("development"===this.#ez)throw new C(eW.cannotRenderAnyBillingComponent("PlanDetails"),{code:nx});return}this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(t=>t.openDrawer("planDetails",e||{})),this.telemetry?.record(e9("PlanDetails",e))};__internal_closePlanDetails=()=>{this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("planDetails"))};__internal_openSubscriptionDetails=e=>{this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(t=>t.openDrawer("subscriptionDetails",e||{}))};__internal_closeSubscriptionDetails=()=>{this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("subscriptionDetails"))};__internal_openReverification=e=>{if(!this.user){if("development"===this.#ez)throw new C(eW.cannotOpenUserProfile,{code:nj});return}this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(t=>t.openModal("userVerification",e||{})),this.telemetry?.record(e9("UserVerification",e))};__internal_closeReverification=()=>{this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userVerification"))};__internal_attemptToEnableEnvironmentSetting=e=>{let{for:t,caller:a}=e;if(this.user||"development"!==this.#ez||X(`Clerk: "${a}" requires an active user session. Ensure a user is signed in before executing ${a}.`),"organizations"===t){let t;return(t=this.environment,t?.organizationSettings.enabled||this.session?.currentTask?.key==="choose-organization")?{isEnabled:!0}:("development"===this.#ez&&this.__internal_openEnableOrganizationsPrompt({caller:a,onSuccess:()=>window.location.reload(),onClose:e.onClose}),{isEnabled:!1})}throw Error(`Attempted to enable an unknown or unsupported setting "${t}".`)};__internal_openEnableOrganizationsPrompt=e=>{this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted({preloadHint:"EnableOrganizationsPrompt"})).then(t=>t.openModal("enableOrganizationsPrompt",e||{})),this.telemetry?.record(e3("EnableOrganizationsPrompt",e))};__internal_closeEnableOrganizationsPrompt=()=>{this.assertComponentsReady(this.#ej),this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeModal("enableOrganizationsPrompt"))};__internal_openBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(e=>e.openModal("blankCaptcha",{})));__internal_closeBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(e=>e.closeModal("blankCaptcha")));__internal_loadStripeJs=async()=>{let{loadStripe:e}=await Promise.resolve().then(n.bind(n,5608));return e};openSignUp=e=>{if(L(this,this.environment)){if("development"===this.#ez)throw new C(eW.cannotOpenSignInOrSignUp,{code:nS});return}this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(t=>t.openModal("signUp",e||{})),this.telemetry?.record(e9("SignUp",e))};closeSignUp=()=>{this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signUp"))};openUserProfile=e=>{if(!this.user){if("development"===this.#ez)throw new C(eW.cannotOpenUserProfile,{code:nj});return}this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(t=>t.openModal("userProfile",e||{}));let t=(e?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(e9("UserProfile",e,t))};closeUserProfile=()=>{this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userProfile"))};openOrganizationProfile=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new C(eW.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:n_})}});if(t){if(!this.organization){if("development"===this.#ez)throw new C(eW.cannotRenderComponentWhenOrgDoesNotExist,{code:nz});return}this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(t=>t.openModal("organizationProfile",e||{})),this.telemetry?.record(e9("OrganizationProfile",e))}};closeOrganizationProfile=()=>{this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeModal("organizationProfile"))};openCreateOrganization=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new C(eW.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:n_})}});t&&(this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(t=>t.openModal("createOrganization",e||{})),this.telemetry?.record(e9("CreateOrganization",e)))};closeCreateOrganization=()=>{this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeModal("createOrganization"))};openWaitlist=e=>{this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(t=>t.openModal("waitlist",e||{})),this.telemetry?.record(e9("Waitlist",e))};closeWaitlist=()=>{this.#ej?.then(e=>e.ensureMounted()).then(e=>e.closeModal("waitlist"))};mountSignIn=(e,t)=>{this.assertComponentsReady(this.#ej);let a="SignIn";this.#ej.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"signIn",node:e,props:t}));let r={withSignUp:t?.withSignUp??this.#eB()};this.telemetry?.record(e3(a,t,r))};unmountSignIn=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserAvatar=(e,t)=>{this.assertComponentsReady(this.#ej);let a="UserAvatar";this.#ej.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"userAvatar",node:e,props:t})),this.telemetry?.record(e3(a,t))};unmountUserAvatar=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountSignUp=(e,t)=>{this.assertComponentsReady(this.#ej);let a="SignUp";this.#ej.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"signUp",node:e,props:t})),this.telemetry?.record(e3(a,t))};unmountSignUp=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserProfile=(e,t)=>{if(!this.user){if("development"===this.#ez)throw new C(eW.cannotRenderComponentWhenUserDoesNotExist,{code:nj});return}this.assertComponentsReady(this.#ej);let a="UserProfile";this.#ej.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"userProfile",node:e,props:t}));let r=(t?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(e3(a,t,r))};unmountUserProfile=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOrganizationProfile=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new C(eW.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:n_})}});if(!a)return;let r=!!this.user;if(!this.organization&&r){if("development"===this.#ez)throw new C(eW.cannotRenderComponentWhenOrgDoesNotExist,{code:nz});return}this.assertComponentsReady(this.#ej);let n="OrganizationProfile";this.#ej.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:n,appearanceKey:"userProfile",node:e,props:t})),this.telemetry?.record(e3(n,t))};unmountOrganizationProfile=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountCreateOrganization=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new C(eW.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:n_})}});if(!a)return;this.assertComponentsReady(this.#ej);let r="CreateOrganization";this.#ej.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:r,appearanceKey:"createOrganization",node:e,props:t})),this.telemetry?.record(e3(r,t))};unmountCreateOrganization=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOrganizationSwitcher=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationSwitcher",onClose:()=>{throw new C(eW.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:n_})}});if(!a)return;this.assertComponentsReady(this.#ej);let r="OrganizationSwitcher";this.#ej.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:r,appearanceKey:"organizationSwitcher",node:e,props:t})),this.telemetry?.record(e3(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationSwitcher=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__experimental_prefetchOrganizationSwitcher=()=>{this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(e=>e.prefetch("organizationSwitcher"))};mountOrganizationList=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationList",onClose:()=>{throw new C(eW.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:n_})}});if(!a)return;this.assertComponentsReady(this.#ej);let r="OrganizationList";this.#ej.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:r,appearanceKey:"organizationList",node:e,props:t})),this.telemetry?.record(e3(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationList=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserButton=(e,t)=>{this.assertComponentsReady(this.#ej);let a="UserButton";this.#ej.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"userButton",node:e,props:t}));let r={...t?.customMenuItems?.length||0?{customItems:!0}:void 0,...t?.__experimental_asStandalone?{standalone:!0}:void 0};this.telemetry?.record(e3(a,t,r))};unmountUserButton=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountWaitlist=(e,t)=>{this.assertComponentsReady(this.#ej);let a="Waitlist";this.#ej.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"waitlist",node:e,props:t})),this.telemetry?.record(e3(a,t))};unmountWaitlist=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountPricingTable=(e,t)=>{if(W(this,this.environment)){if("development"===this.#ez)throw new C(eW.cannotRenderAnyBillingComponent("PricingTable"),{code:nx});return}this.assertComponentsReady(this.#ej);let a="PricingTable";this.#ej.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:a,appearanceKey:"pricingTable",node:e,props:t})),this.telemetry?.record(e3(a,t))};unmountPricingTable=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__internal_mountOAuthConsent=(e,t)=>{this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:"OAuthConsent",appearanceKey:"__internal_oauthConsent",node:e,props:t}))};__internal_unmountOAuthConsent=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountAPIKeys=(e,t)=>{let a;if(X("Clerk: <APIKeys /> component is in early access and not yet recommended for production use."),K(this,a=this.environment)&&H(this,a)){if("development"===this.#ez)throw new C(eW.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&H(this,this.environment)){if("development"===this.#ez)throw new C(eW.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if(K(this,this.environment)){if("development"===this.#ez)throw new C(eW.cannotRenderAPIKeysComponentForUserWhenDisabled,{code:"cannot_render_api_keys_user_disabled"});return}this.assertComponentsReady(this.#ej);let r="APIKeys";this.#ej.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:r,appearanceKey:"apiKeys",node:e,props:t})),this.telemetry?.record(e3(r,t))};unmountAPIKeys=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskChooseOrganization=(e,t)=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"TaskChooseOrganization",onClose:()=>{throw new C(eW.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:n_})}});if(!a)return;this.assertComponentsReady(this.#ej);let r="TaskChooseOrganization";this.#ej.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:r,appearanceKey:"taskChooseOrganization",node:e,props:t})),this.telemetry?.record(e3(r,t))};unmountTaskChooseOrganization=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskResetPassword=(e,t)=>{this.assertComponentsReady(this.#ej),this.#ej.then(e=>e.ensureMounted()).then(a=>a.mountComponent({name:"TaskResetPassword",appearanceKey:"taskResetPassword",node:e,props:t})),this.telemetry?.record(e3("TaskResetPassword",t))};unmountTaskResetPassword=e=>{this.#ej?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};setActive=async e=>{let{organization:t,redirectUrl:a,navigate:r}=e,{session:n}=e;this.__internal_setActiveInProgress=!0,tn.debug("setActive() start",{hasClient:!!this.client,sessionTarget:"string"==typeof n?n:n?.id??n??null,organizationTarget:"string"==typeof t?t:t?.id??t??null,redirectUrl:a??null},"clerk");try{var i;let s;if(!this.client)throw tn.warn("Clerk setActive called before client is loaded",{},"clerk"),Error("setActive is being called before the client is loaded. Wait for init.");if(void 0===n&&!this.session)throw tn.warn("Clerk setActive precondition not met: no target session and no active session",{},"clerk"),Error("setActive should either be called with a session param or there should be already an active session.");"string"==typeof n&&(n=this.client.sessions.find(e=>e.id===n)||null);let o="undefined"!=typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:e8,l="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e8,c=void 0===n?this.session:n;c?.status==="pending"&&(i={...this.#eI,...e},s=["taskUrls","navigate"],Object.keys(i).some(e=>s.includes(e))||X('Clerk: Session has pending tasks but no handling is configured. To handle pending tasks, provide either "taskUrls" for navigation to custom URLs or "navigate" for programmatic navigation. Without these options, users may get stuck on incomplete flows.'));let u=void 0!==t;if(c&&u){let e="string"==typeof t?t:t?.id;if("string"==typeof e&&e.startsWith("org_"))c.lastActiveOrganizationId=e||null;else{let t=c.user.organizationMemberships.find(t=>t.organization.slug===e),a=t?.organization.id||null,r=null===a;if(this.environment?.organizationSettings?.forceOrganizationSelection&&r)return;c.lastActiveOrganizationId=a}}c?.status!=="pending"&&await o(null===c?"sign-out":void 0),(tw()&&globalThis.document.hasFocus()||!this.#eI.standardBrowser)&&(await this.#eD(c),c=this.#eF(c?.id)),await c?.getToken()||(d()||tn.warn("Token is null when setting active session (offline)",{sessionId:c?.id},"clerk"),rn.emit(re,{token:null}));let h=td(this.#eI.standardBrowser),m=c?.status==="pending"&&c?.currentTask&&this.#eI.taskUrls?.[c?.currentTask.key];if((a||m||r)&&await h.track(async()=>{if(this.client){if(c?.status!=="pending"&&this.#eN(),m){let e=a?eS({base:m,hashSearchParams:{redirectUrl:a}},{stringify:!0}):m;await this.navigate(e)}else if(r&&c)await r({session:c});else if(a){if(this.client.isEligibleForTouch()){let e=new URL(a,window.location.href),t=this.buildUrlWithAuth(this.client.buildTouchUrl({redirectUrl:e}));await this.navigate(t)}await this.navigate(a)}}}),h.isUnloading())return;this.#eT(c),this.#eU(),c?.status!=="pending"&&await l()}finally{this.__internal_setActiveInProgress=!1}};addListener=e=>{var t;let a;return t=e,e=e=>{var r;a||={...e},t(a={...{client:r5((r=a).client,e.client),session:r5(r.session,e.session),user:r5(r.user,e.user),organization:r5(r.organization,e.organization)}})},this.#eE.push(e),this.client&&e({client:this.client,session:this.session,user:this.user,organization:this.organization}),()=>{this.#eE=this.#eE.filter(t=>t!==e)}};on=(...e)=>{this.#eq.on(...e)};off=(...e)=>{this.#eq.off(...e)};__internal_addNavigationListener=e=>(this.#eA.push(e),()=>{this.#eA=this.#eA.filter(t=>t!==e)});navigate=async(e,t)=>{if(!e||!tw())return;setTimeout(()=>{this.#eL()},0);let a=new URL(e,window.location.href);this.#eW.includes(a.protocol)||(console.warn(`Clerk: "${a.protocol}" is not a valid protocol. Redirecting to "/" instead. If you think this is a mistake, please open an issue.`),a=new URL("/",window.location.href));let r=t?.replace&&this.#eI.routerReplace?this.#eI.routerReplace:this.#eI.routerPush;if(tn.info(`Clerk is navigating to: ${a}`),this.#eI.routerDebug&&console.log(`Clerk is navigating to: ${a}`),"null"!==a.origin&&a.origin!==window.location.origin||!r)return void eV(a);let n={...t?.metadata?{__internal_metadata:t?.metadata}:{},windowNavigate:eV};return await r(eE(a),n)};buildUrlWithAuth(e){if("production"===this.#ez)return e;let t=new URL(e,window.location.origin);return t.origin!==window.location.origin&&this.#ew?this.#ew.decorateUrlWithDevBrowserToken(t).href:t.href}buildSignInUrl(e){return this.#eK("signInUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildSignUpUrl(e){return this.#eK("signUpUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildUserProfileUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.userProfileUrl):""}buildHomeUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.homeUrl):""}buildAfterSignInUrl({params:e}={}){return this.buildUrlWithAuth(new eO(this.#eI,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eO(this.#eI,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#eI.afterSignOutUrl?this.buildUrlWithAuth(this.#eI.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#eI.newSubscriptionRedirectUrl?this.#eI.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?eS({base:this.#eI.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#eI.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#eI.afterMultiSessionSingleSignOutUrl):this.#eI.signInUrl?this.buildUrlWithAuth(eS({base:this.#eI.signInUrl,hashPath:"choose"},{stringify:!0})):this.buildUrlWithAuth(this.environment.displayConfig.afterSignOutOneUrl):""}buildCreateOrganizationUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.createOrganizationUrl):""}buildOrganizationProfileUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.organizationProfileUrl):""}buildTasksUrl(e){let t=this.session?.currentTask;if(!t)return"";let a=this.#eI.taskUrls?.[t.key];return a||eS({base:this.buildSignInUrl(e),hashPath:eD(t)},{stringify:!0})}#eH=async()=>{if(!tw())return;let e=new URLSearchParams({[V]:"true"}),t=eM(J);t&&eG(t)||function(){throw Error(`${tA} Invalid redirect_url. A valid http or https url should be used for the redirection.`)}();let a=eS({base:eM(J),searchParams:e},{stringify:!0});return this.navigate(this.buildUrlWithAuth(a))};redirectWithAuth=async e=>{if(tw())return this.navigate(this.buildUrlWithAuth(e))};redirectToSignIn=async e=>{if(tw())return this.navigate(this.buildSignInUrl(e))};redirectToSignUp=async e=>{if(tw())return this.navigate(this.buildSignUpUrl(e))};redirectToUserProfile=async()=>{if(tw())return this.navigate(this.buildUserProfileUrl())};redirectToCreateOrganization=async()=>{if(tw())return this.navigate(this.buildCreateOrganizationUrl())};redirectToOrganizationProfile=async()=>{if(tw())return this.navigate(this.buildOrganizationProfileUrl())};redirectToAfterSignIn=async()=>{if(tw())return this.navigate(this.buildAfterSignInUrl())};redirectToAfterSignUp=async()=>{if(tw())return this.navigate(this.buildAfterSignUpUrl())};redirectToAfterSignOut=async()=>{if(tw())return this.navigate(this.buildAfterSignOutUrl())};redirectToWaitlist=async()=>{if(tw())return this.navigate(this.buildWaitlistUrl())};redirectToTasks=async e=>{if(tw())return this.navigate(this.buildTasksUrl(e))};handleEmailLinkVerification=async(e,t)=>{if(!this.client)return;let a=eM("__clerk_status");if("expired"===a)throw new E(I.Expired);if("client_mismatch"===a)throw new E(I.ClientMismatch);if("verified"!==a)throw new E(I.Failed);let r=eM("__clerk_created_session"),{signIn:n,signUp:i,sessions:s}=this.client,o=s.some(e=>e.id===r),l="needs_second_factor"===n.status||"missing_requirements"===i.status,c=e=>t&&"function"==typeof t?t(e):this.navigate(e),u=e.redirectUrl?()=>c(e.redirectUrl):e8;return o?this.setActive({session:r,redirectUrl:e.redirectUrlComplete}):l?u():("function"==typeof e.onVerifiedOnOtherDevice&&e.onVerifiedOnOtherDevice(),null)};handleGoogleOneTapCallback=async(e,t,a)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:r,signUp:n}=this.client,i="identifier"in(e||{})?e:r,s="missingFields"in(e||{})?e:n,o=e=>a&&"function"==typeof a?a(this.buildUrlWithAuth(e)):this.navigate(this.buildUrlWithAuth(e));return this._handleRedirectCallback(t,{signUp:s,signIn:i,navigate:o})};_handleRedirectCallback=async(e,{signIn:t,signUp:a,navigate:r})=>{if(!this.loaded||!this.environment||!this.client)return;if(!window.opener&&e.reloadResource)try{"signIn"===e.reloadResource?await t.reload():"signUp"===e.reloadResource&&await a.reload()}catch{}let{displayConfig:n}=this.environment,{firstFactorVerification:i}=t,{externalAccount:s}=a.verifications,o={status:a.status,missingFields:a.missingFields,externalAccountStatus:s.status,externalAccountErrorCode:s.error?.code,externalAccountSessionId:s.error?.meta?.sessionId,sessionId:a.createdSessionId},l={status:t.status,firstFactorVerificationStatus:i.status,firstFactorVerificationErrorCode:i.error?.code,firstFactorVerificationSessionId:i.error?.meta?.sessionId,sessionId:t.createdSessionId},c=e=>()=>r(e),u=c(e.signInUrl||n.signInUrl),d=c(e.signUpUrl||n.signUpUrl),h=c(e.firstFactorUrl||eS({base:n.signInUrl,hashPath:"/factor-one"},{stringify:!0})),m=c(e.secondFactorUrl||eS({base:n.signInUrl,hashPath:"/factor-two"},{stringify:!0})),p=c(e.resetPasswordUrl||eS({base:n.signInUrl,hashPath:"/reset-password"},{stringify:!0})),f=new eO(this.#eI,e),g=c(e.continueSignUpUrl||eS({base:n.signUpUrl,hashPath:"/continue"},{stringify:!0})),b=({missingFields:t})=>t.length?g():(({signUp:e,verifyEmailPath:t,verifyPhonePath:a,continuePath:r,navigate:n,handleComplete:i,redirectUrl:s="",redirectUrlComplete:o="",oidcPrompt:l})=>{if("complete"===e.status)return i&&i();if("missing_requirements"===e.status){if(e.missingFields.some(e=>"enterprise_sso"===e))return e.authenticateWithRedirect({strategy:"enterprise_sso",redirectUrl:s,redirectUrlComplete:o,continueSignUp:!0,oidcPrompt:l});let i=eB();if(e.unverifiedFields?.includes("email_address")&&t)return n(t,{searchParams:i});if(e.unverifiedFields?.includes("phone_number")&&a)return n(a,{searchParams:i});if(r)return n(r,{searchParams:i})}})({signUp:a,verifyEmailPath:e.verifyEmailAddressUrl||eS({base:n.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),verifyPhonePath:e.verifyPhoneNumberUrl||eS({base:n.signUpUrl,hashPath:"/verify-phone-number"},{stringify:!0}),navigate:r}),y=e.signInUrl||n.signInUrl,w=e.signUpUrl||n.signUpUrl,k=async({session:e,baseUrl:t,redirectUrl:a})=>{e.currentTask?await eF(e,{baseUrl:t,navigate:this.navigate}):await this.navigate(a)};if("complete"===l.status)return this.setActive({session:l.sessionId,navigate:async({session:e})=>{await k({session:e,baseUrl:y,redirectUrl:f.getAfterSignInUrl()})}});if("transferable"===o.externalAccountStatus&&"external_account_exists"===o.externalAccountErrorCode){let e=await t.create({transfer:!0});switch(e.status){case"complete":return this.setActive({session:e.createdSessionId,navigate:async({session:e})=>{await k({session:e,baseUrl:w,redirectUrl:f.getAfterSignInUrl()})}});case"needs_first_factor":return h();case"needs_second_factor":return m();case"needs_new_password":return p();default:tC("sign in")}}let v="user_locked"===o.externalAccountErrorCode,x="user_locked"===l.firstFactorVerificationErrorCode;if(v)return d();if(x)return u();if("needs_first_factor"===l.status&&!t.supportedFirstFactors?.every(e=>"enterprise_sso"===e.strategy))return h();if("needs_new_password"===l.status)return p();if("transferable"===l.firstFactorVerificationStatus){if(!1===e.transferable)return u();let t=await a.create({transfer:!0});switch(t.status){case"complete":return this.setActive({session:t.createdSessionId,navigate:async({session:e})=>{await k({session:e,baseUrl:w,redirectUrl:f.getAfterSignUpUrl()})}});case"missing_requirements":return b({missingFields:t.missingFields});default:tC("sign in")}}if("complete"===o.status)return this.setActive({session:o.sessionId,navigate:async({session:e})=>{await k({session:e,baseUrl:w,redirectUrl:f.getAfterSignUpUrl()})}});if("needs_second_factor"===l.status)return m();let j=("failed"===o.externalAccountStatus||"unverified"===o.externalAccountStatus)&&"identifier_already_signed_in"===o.externalAccountErrorCode&&o.externalAccountSessionId,_="failed"===l.firstFactorVerificationStatus&&"identifier_already_signed_in"===l.firstFactorVerificationErrorCode&&l.firstFactorVerificationSessionId;if(j||_){let e=l.firstFactorVerificationSessionId||o.externalAccountSessionId;if(e)return this.setActive({session:e,navigate:async({session:e})=>{await k({session:e,baseUrl:j?w:y,redirectUrl:f.getAfterSignInUrl()})}})}return(e=>{let{externalAccount:t}=e.verifications;return!!t.error})(a)?d():"verified"===o.externalAccountStatus&&"missing_requirements"===o.status?b({missingFields:a.missingFields}):this.session?.currentTask?void await this.redirectToTasks({redirectUrl:this.buildAfterSignInUrl()}):u()};handleRedirectCallback=async(e={},t)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:a,signUp:r}=this.client,n=e=>t&&"function"==typeof t?t(e):this.navigate(e);return this._handleRedirectCallback(e,{signUp:r,signIn:a,navigate:n})};handleUnauthenticated=async(e={broadcast:!0})=>{if(this.client&&this.session)try{let t=await aN.getOrCreateInstance().fetch();if(this.updateClient(t),this.session)return;return e.broadcast&&rn.emit(rt,null),this.setActive({session:null})}catch(e){if(M(e)&&[403,500].includes(e.status))return this.setActive({session:null});throw e}};authenticateWithGoogleOneTap=async e=>this.client?.signIn.create({strategy:"google_one_tap",token:e.token}).catch(t=>{if(M(t)&&"external_account_not_found"===t.errors[0].code)return this.client?.signUp.create({strategy:"google_one_tap",token:e.token,legalAccepted:e.legalAccepted});throw t});authenticateWithMetamask=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_okx_wallet_signature"})};authenticateWithSolana=async e=>{await this.authenticateWithWeb3({...e,strategy:"web3_solana_signature"})};authenticateWithWeb3=async({redirectUrl:e,signUpContinueUrl:t,customNavigate:a,unsafeMetadata:r,strategy:n,legalAccepted:i,secondFactorUrl:s,walletName:o})=>{let l,c;if(!this.client||!this.environment)return;let{displayConfig:u}=this.environment,d=n.replace("web3_","").replace("_signature",""),h=await tj().getWeb3Identifier({provider:d,walletName:o});switch(d){case"metamask":l=tj().generateSignatureWithMetamask;break;case"base":l=tj().generateSignatureWithBase;break;case"coinbase_wallet":l=tj().generateSignatureWithCoinbaseWallet;break;case"solana":if(!o)throw new C("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});l=e=>tj().generateSignatureWithSolana({...e,walletName:o});break;default:l=tj().generateSignatureWithOKXWallet}let m=e=>()=>a&&"function"==typeof a?a(e):this.navigate(e),p=m(s||eS({base:u.signInUrl,hashPath:"/factor-two"},{stringify:!0})),f=m(t||eS({base:u.signUpUrl,hashPath:"/continue"},{stringify:!0}));try{c=await this.client.signIn.authenticateWithWeb3({identifier:h,generateSignature:l,strategy:n,walletName:o})}catch(e){if(tp(e,"form_identifier_not_found"))c=await this.client.signUp.authenticateWithWeb3({identifier:h,generateSignature:l,unsafeMetadata:r,strategy:n,legalAccepted:i,walletName:o}),t&&"missing_requirements"===c.status&&"verified"===c.verifications.web3Wallet.status&&await f();else throw e}let g=async({session:e,redirectUrl:t})=>{e.currentTask?await eF(e,{baseUrl:u.signInUrl,navigate:this.navigate}):await this.navigate(t)};switch(c.status){case"needs_second_factor":await p();break;case"complete":c.createdSessionId&&await this.setActive({session:c.createdSessionId,navigate:async({session:t})=>{await g({session:t,redirectUrl:e??this.buildAfterSignInUrl()})}});break;default:return}};createOrganization=async({name:e,slug:t})=>rg.create({name:e,slug:t});getOrganization=async e=>rg.get(e);joinWaitlist=async({emailAddress:e})=>r3.join({emailAddress:e});updateEnvironment(e){this.environment=e}__internal_setCountry=e=>{this.__internal_country||(this.__internal_country=e)};get __internal_last_error(){let e=this.internal_last_error;return this.internal_last_error=null,e}set __internal_last_error(e){this.internal_last_error=e}updateClient=e=>{if(!this.client){let t=this.#eI.selectInitialSession?this.#eI.selectInitialSession(e):this.#eV(e);this.#eT(t)}if(this.client=e,this.session){let e=this.#eF(this.session.id);"active"===this.session.status&&e?.status==="pending"&&("undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e8)(),this.#eT(e),this.session?.lastActiveToken||d()||tn.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),rn.emit(re,{token:this.session?.lastActiveToken})}this.#eU()};get __internal_environment(){return this.environment}__internal_setEnvironment=async e=>{this.environment=new ro(e)};__internal_onBeforeRequest=e=>{this.#e_.onBeforeRequest(e)};__internal_onAfterResponse=e=>{this.#e_.onAfterResponse(e)};__internal_updateProps=e=>{let t={...e,options:this.#eO({...this.#eI,...e.options})};return this.#ej?.then(e=>e.ensureMounted()).then(e=>e.updateProps(t))};__internal_navigateWithError(e,t){return this.__internal_last_error=t,this.navigate(e)}#eG=()=>{let e=new URLSearchParams({[J]:window.location.href});return eS({base:this.#eI.signInUrl,searchParams:e},{stringify:!0})};#eJ=()=>{let e;if(this.proxyUrl){let t=new URL(this.proxyUrl);e=new URL(`${t.pathname}/v1/client/sync`,t.origin)}else this.domain&&(e=new URL("/v1/client/sync",`https://${this.domain}`));return e?.searchParams.append("redirect_url",window.location.href),e?.toString()||""};#eZ=()=>"true"!==eM(V)&&!!this.isSatellite&&!!this.#ew?.isSignedOut();#e$=()=>"production"!==this.#ez&&!this.isSatellite&&!!eM(J);#eY=async()=>{"development"===this.instanceType?await this.navigate(this.#eG()):"production"===this.instanceType&&await this.navigate(this.#eJ())};#eQ=(e,t)=>{let a;try{a=new URL(e)}catch{throw Error(`${tA} The signInUrl needs to have a absolute url format.`)}a.origin===t&&function(){throw Error(`${tA} The signInUrl needs to be on a different origin than your satellite application.`)}()};#eX=()=>{this.isSatellite&&("development"!==this.#ez||this.#eI.signInUrl||function(){throw Error(`${tA} Missing signInUrl. A satellite application needs to specify the signInUrl for development instances.`)}(),this.proxyUrl||this.domain||function(){throw Error(`${tA} Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl.`)}(),this.#eI.signInUrl&&this.#eQ(this.#eI.signInUrl,window.location.origin))};#eM=async()=>{if(this.#ew=await np.create(this,this.#e_,this.#ez,this.#eq),this.#eX(),this.#eZ())return void await this.#eY();if(this.#e$())return void await this.#eH();this.#eC=(()=>{if(!o())return{onPageFocus:e8};let e=[];return window.addEventListener("focus",()=>{"visible"===document.visibilityState&&e.forEach(e=>e())}),{onPageFocus:t=>{e.push(t)}}})(),"undefined"!=typeof BroadcastChannel&&(this.#ex=new BroadcastChannel("clerk")),this.#e1();let e=function(e=window.location.hostname){if(!e)return!1;let t=e_.get(e);void 0===t&&(t=ec.some(t=>e.startsWith("accounts.")&&e.endsWith(t))||eu.some(t=>e.endsWith(t)&&!e.endsWith(".clerk"+t)),e_.set(e,t));return t}(window?.location.hostname),t="development"===this.#ez&&!e,a=0,r=0;for(;r<2;){r++;try{var n;let e=ro.getInstance().fetch({touch:t}).then(e=>this.updateEnvironment(e)).catch(()=>{++a;let e=tE.getItem(t_,null);e&&this.updateEnvironment(new ro(e))}),r=async()=>aN.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(async e=>{if(T(e))throw e;++a;let t=this.#ew?.getSessionCookie(),r=function(e){let t;try{t=new rJ({jwt:e||"",object:"token",id:void 0})}catch{t=null}if(aN.clearInstance(),!t?.jwt)return aN.getOrCreateInstance({object:"client",last_active_session_id:null,id:"client_init",sessions:[]});let{sessionId:a,userId:r,orgId:n,orgRole:i,orgPermissions:s,orgSlug:o,factorVerificationAge:l}=(e=>{let t,a,r,n,i=e.fva??null,s=e.sts??null;if(2===e.v){if(e.o){t=e.o?.id,r=e.o?.slg,e.o?.rol&&(a=`org:${e.o?.rol}`);let{org:i}=rP(e.fea),{permissions:s,featurePermissionMap:o}=(({per:e,fpm:t})=>{if(!e||!t)return{permissions:[],featurePermissionMap:[]};let a=e.split(",").map(e=>e.trim());return{permissions:a,featurePermissionMap:t.split(",").map(e=>Number.parseInt(e.trim(),10)).map(e=>e.toString(2).padStart(a.length,"0").split("").map(e=>Number.parseInt(e,10)).reverse()).filter(Boolean)}})({per:e.o?.per,fpm:e.o?.fpm});n=function({features:e,permissions:t,featurePermissionMap:a}){if(!e||!t||!a)return[];let r=[];for(let n=0;n<e.length;n++){let i=e[n];if(n>=a.length)continue;let s=a[n];if(s)for(let e=0;e<s.length;e++)1===s[e]&&r.push(`org:${i}:${t[e]}`)}return r}({features:i,featurePermissionMap:o,permissions:s})}}else t=e.org_id,a=e.org_role,r=e.org_slug,n=e.org_permissions;return{sessionClaims:e,sessionId:e.sid,sessionStatus:s,actor:e.act,userId:e.sub,orgId:t,orgRole:a,orgSlug:r,orgPermissions:n,factorVerificationAge:i}})(t.jwt.claims),c={object:"client",last_active_session_id:a,id:"client_init",sessions:[{object:"session",id:a,status:"active",last_active_organization_id:n||null,last_active_token:{id:void 0,object:"token",jwt:e},factor_verification_age:l||null,public_user_data:{user_id:r},user:{object:"user",id:r,organization_memberships:n&&o&&i?[{object:"organization_membership",id:n,role:i,permissions:s||[],organization:{object:"organization",id:n,name:o,slug:o,members_count:1,max_allowed_memberships:1}}]:[]}}]};return aN.getOrCreateInstance(c)}(t);return this.updateClient(r),this.#ew?.stopPollingForToken(),await this.session?.getToken({skipCache:!0}).catch(()=>null).finally(()=>{this.#ew?.startPollingForToken()}),null}),[,i]=await (n=[e,r()],Promise.all(Array.from(n).map(e=>e.then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e})))));if("rejected"===i.status){let e=i.reason;if(tp(e,"requires_captcha"))await r();else throw e}if(this.#ew?.setClientUatCookieForDevelopmentInstances(),await this.#e0())return;break}catch(e){if(tp(e,"dev_browser_unauthenticated"))await this.#ew.handleUnauthenticatedDevBrowser();else if(!d())return void console.warn(e);else throw e}r>=2&&function(){throw Error(`${tA} Something went wrong initializing Clerk.`)}()}this.#ev=new nf(this),this.#ev.start(),this.#e2(),this.#e3(),this.#e9(),this.#eq.emit(g,a>0?"degraded":"ready")};shouldFallbackToCachedResources=()=>!!this.__internal_getCachedResources;#eR=async()=>{let e,t,a=this.shouldFallbackToCachedResources()?1:void 0,r=0;try{[e,t]=await Promise.all([ro.getInstance().fetch({touch:!1,fetchMaxTries:a}),aN.getOrCreateInstance().fetch({fetchMaxTries:a})])}catch(a){if(R(a)&&"network_error"===a.code&&this.shouldFallbackToCachedResources()){let a=await this.__internal_getCachedResources?.();e=new ro(a?.environment),aN.clearInstance(),t=aN.getOrCreateInstance(a?.client),++r}else throw a}this.updateClient(t),this.updateEnvironment(e),this.#eq.emit(g,r>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,t]=await Promise.all([ro.getInstance().fetch({touch:!1,fetchMaxTries:1}),aN.getOrCreateInstance().fetch({fetchMaxTries:1})]);this.updateClient(t),this.updateEnvironment(e),this.#eU()};#eV=e=>{if(e.lastActiveSessionId){let t=e.signedInSessions.find(t=>t.id===e.lastActiveSessionId);if(t)return t}return e.signedInSessions[0]||null};#e1=()=>{o()&&(this.#eC?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#eP>Date.now())&&(this.#eP=Date.now()+5e3,this.#eI.touchSession&&this.#eD(this.session))}),this.#ex?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),rn.on(rt,()=>{this.#ex?.postMessage({type:"signout"})}),rn.on(ra,()=>{tE.setItem(t_,this.environment?.__internal_toSnapshot(),864e5)}))};#eD=async e=>{if(!e)return Promise.resolve();await e.touch().catch(e=>{T(e)&&this.handleUnauthenticated()})};#eU=()=>{if(this.client)for(let e of this.#eE)e({client:this.client,session:this.session,user:this.user,organization:this.organization})};#eL=()=>{for(let e of this.#eA)e()};#eN=()=>{this.session=void 0,this.organization=void 0,this.user=void 0,this.#eU()};#e5=()=>(this.session?.user.organizationMemberships||[]).map(e=>e.organization).find(e=>e.id===this.session?.lastActiveOrganizationId)||null;#eT=e=>{this.session=e||null,this.organization=this.#e5(),this.user=this.session?this.session.user:null};#eF=e=>this.client?.signedInSessions.find(t=>t.id===e)||null;#e3=()=>{this.addListener(({session:e})=>{e?.actor&&this.#ej?.then(e=>e.ensureMounted()).then(e=>e.mountImpersonationFab())})};#e9=()=>{this.#eI.__internal_keyless_claimKeylessApplicationUrl&&this.#ej?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#eI.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#eI.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#eI.__internal_keyless_dismissPrompt}})})};#eK=(e,t,a)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let r=this.#eI[e]||this.environment.displayConfig[e];this.#eB()&&(r=this.#eI.signInUrl);let n=new eO(this.#eI,t).toSearchParams(),i=new URLSearchParams(a||{}),s=eS({base:r,hashPath:this.#eB()&&"signUpUrl"===e?"/create":"",hashSearchParams:[i,n]},{stringify:!0});return this.buildUrlWithAuth(s)};assertComponentsReady(e){if(!e)throw Error("Clerk was not loaded with Ui components")}#e0=async()=>{var e;let t,a,r,n,i=new URLSearchParams(window.location.search).get("redirect_url"),s="production"===this.instanceType,o=null!==i&&(e=this.frontendApi,a=(t=new URL(i,ev)).pathname,r=eP.includes(a)||eq.includes(a),e===t.host&&r);if(s||!o)return!1;let l=this.session,c=this.#eI.signInUrl||this.environment?.displayConfig.signInUrl,u=c&&window.location.href.startsWith(c),d=this.#eI.signUpUrl||this.environment?.displayConfig.signUpUrl,h=d&&window.location.href.startsWith(d);return n=new URL(i,ev),(!eP.includes(n.pathname)||!!l||!u&&!h)&&(await this.navigate(this.buildUrlWithAuth(i)),!0)};#eO=e=>({...nE,...e,allowedRedirectOrigins:function(e,t,a){if(Array.isArray(e)&&e.length)return e;let r=[];return"undefined"!=typeof window&&window.location&&r.push(window.location.origin),r.push(`https://${ez(t)}`),r.push(`https://*.${ez(t)}`),"development"===a&&r.push(`https://${t}`),r}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)});#e2=()=>{try{eR(V),eR(eT),eR(G),eR("__clerk_handshake"),eR("__clerk_handshake_nonce"),eR("__clerk_help")}catch{}};get #eW(){let e=eH;return this.#eI.allowedRedirectProtocols&&(e=e.concat(this.#eI.allowedRedirectProtocols)),e}}})();var s=i.c2,o=i.LR,l=i.cR,c=i.NZ,u=i.Ys,d=i.kl,h=i.$R,m=i.Cm,p=i.hl,f=i.ux,g=i.si,b=i._d;export{s as Clerk,o as ClerkAPIResponseError,l as ClerkRuntimeError,c as EmailLinkError,u as EmailLinkErrorCode,d as EmailLinkErrorCodeStatus,h as isClerkAPIResponseError,m as isClerkRuntimeError,p as isEmailLinkError,f as isKnownError,g as isMetamaskError,b as isUserLockedError};
|