@clerk/clerk-js 6.0.0-canary-core3.v20251203181537 → 6.0.0-snapshot.v20251203203405
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.channel.browser.js +4 -4
- package/dist/clerk.chips.browser.js +4 -4
- package/dist/clerk.headless.browser.js +4 -4
- package/dist/clerk.headless.js +2 -2
- 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/dist/types/utils/errorThrower.d.ts +1 -1
- package/dist/types/utils/web3.d.ts +2 -2
- package/package.json +3 -3
- /package/dist/{308_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 308_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{415_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 415_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{507_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → 507_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{507_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → 507_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{507_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → 507_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{507_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → 507_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{507_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 507_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{507_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → 507_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{521_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 521_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{527_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → 527_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{527_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → 527_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{527_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → 527_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{527_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → 527_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{527_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → 527_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{604_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 604_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{694_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 694_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{783_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 783_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{973_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 973_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{base-account-sdk_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → base-account-sdk_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{base-account-sdk_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → base-account-sdk_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{base-account-sdk_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → base-account-sdk_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{base-account-sdk_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → base-account-sdk_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{base-account-sdk_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → base-account-sdk_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → coinbase-wallet-sdk_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → coinbase-wallet-sdk_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → coinbase-wallet-sdk_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → coinbase-wallet-sdk_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → coinbase-wallet-sdk_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{cookieSuffix_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → cookieSuffix_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{cookieSuffix_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → cookieSuffix_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{cookieSuffix_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → cookieSuffix_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{cookieSuffix_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → cookieSuffix_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{cookieSuffix_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → cookieSuffix_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{cookieSuffix_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → cookieSuffix_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{query-core-vendors_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → query-core-vendors_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{query-core-vendors_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → query-core-vendors_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{query-core-vendors_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → query-core-vendors_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{query-core-vendors_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → query-core-vendors_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{query-core-vendors_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → query-core-vendors_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{stripe-vendors_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → stripe-vendors_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{stripe-vendors_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → stripe-vendors_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{stripe-vendors_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → stripe-vendors_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{stripe-vendors_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → stripe-vendors_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{stripe-vendors_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → stripe-vendors_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{vendors_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → vendors_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{vendors_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → vendors_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{vendors_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → vendors_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{vendors_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → vendors_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{vendors_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → vendors_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → zxcvbn-common_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → zxcvbn-common_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → zxcvbn-common_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → zxcvbn-common_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → zxcvbn-common_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → zxcvbn-ts-core_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → zxcvbn-ts-core_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → zxcvbn-ts-core_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → zxcvbn-ts-core_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → zxcvbn-ts-core_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
package/dist/clerk.no-rhc.js
CHANGED
|
@@ -16,4 +16,4 @@ ${a.message}`)}})(ez(e)):e).some(e=>e.test(ez(r.origin))));return n||G(`Clerk: R
|
|
|
16
16
|
${e.trim()}
|
|
17
17
|
(This notice only appears in development)`,eF={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=>eR(`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=>eR(`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(eF)){let a=eF[e];"function"!=typeof a&&(eF[e]=eR(a))}let eD="clerk:beforeunload",eN=["http:","https:","wails:","chrome-extension:"];function eW(e){let a=new URL(e,window.location.href);window.dispatchEvent(new CustomEvent(eD)),window.location.href=a.href}function eL(e){return/^http(s)?:\/\//.test(e||"")}function e$(e){return e.startsWith("/")}var eK=class{#c;#E=864e5;constructor(e){this.#c=e}isEventThrottled(e){let a=Date.now(),t=this.#M(e),r=this.#c.getItem(t);return!!r&&!(a-r>this.#E)||(this.#c.setItem(t,a),!1)}#M(e){let{sk:a,pk:t,payload:r,...i}=e,n={...r,...i};return JSON.stringify(Object.keys({...r,...i}).sort().map(e=>n[e]))}},eB=class{#R="clerk_telemetry_throttler";getItem(e){return this.#F()[e]}setItem(e,a){try{let t=this.#F();t[e]=a,localStorage.setItem(this.#R,JSON.stringify(t))}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 a=this.#F();delete a[e],localStorage.setItem(this.#R,JSON.stringify(a))}catch{}}#F(){try{let e=localStorage.getItem(this.#R);if(!e)return{};return JSON.parse(e)}catch{return{}}}static isSupported(){return"undefined"!=typeof window&&!!window.localStorage}},eJ=class{#c=new Map;#D=1e4;getItem(e){return this.#c.size>this.#D?void this.#c.clear():this.#c.get(e)}setItem(e,a){this.#c.set(e,a)}removeItem(e){this.#c.delete(e)}};let eV=new Set(["error","warn","info","debug","trace"]);var eG=class{#N;#W;#L={};#$=[];#K=null;constructor(e){this.#N={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??"";const a=ed(e.publishableKey);a&&(this.#L.instanceType=a.instanceType),e.secretKey&&(this.#L.secretKey=e.secretKey.substring(0,16)),this.#W=new eK(eB.isSupported()?new eB:new eJ)}get isEnabled(){return!("development"!==this.#L.instanceType||this.#N.disabled||"undefined"!=typeof process&&process.env&&et(process.env.CLERK_TELEMETRY_DISABLED)||"undefined"!=typeof window&&window?.navigator?.webdriver)}get isDebug(){return this.#N.debug||"undefined"!=typeof process&&process.env&&et(process.env.CLERK_TELEMETRY_DEBUG)}record(e){try{let a=this.#B(e.event,e.payload);if(this.#J(a.event,a),!this.#V(a,e.eventSamplingRate))return;this.#$.push({kind:"event",value:a}),this.#G()}catch(e){console.error("[clerk/telemetry] Error recording telemetry event",e)}}recordLog(e){try{if(!this.#H(e))return;let a="string"==typeof e?.level&&eV.has(e.level),t="string"==typeof e?.message&&e.message.trim().length>0,r=null,i=e?.timestamp;if("number"==typeof i||"string"==typeof i){let e=new Date(i);Number.isNaN(e.getTime())||(r=e)}if(!a||!t||null===r){this.isDebug&&"undefined"!=typeof console&&console.warn("[clerk/telemetry] Dropping invalid telemetry log entry",{levelIsValid:a,messageIsValid:t,timestampIsValid:null!==r});return}let n=this.#Q(),s={sdk:n.name,sdkv:n.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.#$.push({kind:"log",value:s}),this.#G()}catch(e){console.error("[clerk/telemetry] Error recording telemetry log entry",e)}}#V(e,a){return this.isEnabled&&!this.isDebug&&this.#X(e,a)}#H(e){return!0}#X(e,a){let t=Math.random();return!!(t<=this.#N.samplingRate&&(!1===this.#N.perEventSampling||void 0===a||t<=a))&&!this.#W.isEventThrottled(e)}#G(){if("undefined"==typeof window)return void this.#Z();if(this.#$.length>=this.#N.maxBufferSize){this.#K&&("undefined"!=typeof cancelIdleCallback?cancelIdleCallback(Number(this.#K)):clearTimeout(Number(this.#K))),this.#Z();return}this.#K||("requestIdleCallback"in window?this.#K=requestIdleCallback(()=>{this.#Z(),this.#K=null}):this.#K=setTimeout(()=>{this.#Z(),this.#K=null},0))}#Z(){let e=[...this.#$];if(this.#$=[],this.#K=null,0===e.length)return;let a=e.filter(e=>"event"===e.kind).map(e=>e.value),t=e.filter(e=>"log"===e.kind).map(e=>e.value);a.length>0&&fetch(new URL("/v1/event",this.#N.endpoint),{headers:{"Content-Type":"application/json"},keepalive:!0,method:"POST",body:JSON.stringify({events:a})}).catch(()=>void 0),t.length>0&&fetch(new URL("/v1/logs",this.#N.endpoint),{headers:{"Content-Type":"application/json"},keepalive:!0,method:"POST",body:JSON.stringify({logs:t})}).catch(()=>void 0)}#J(e,a){this.isDebug&&(void 0!==console.groupCollapsed?(console.groupCollapsed("[clerk/telemetry]",e),console.log(a),console.groupEnd()):console.log("[clerk/telemetry]",e,a))}#Q(){let e={name:this.#L.sdk,version:this.#L.sdkVersion};if("undefined"!=typeof window){let a=window;if(a.Clerk){let t=a.Clerk;if("object"==typeof t&&null!==t&&"constructor"in t&&"function"==typeof t.constructor&&t.constructor.sdkMetadata){let{name:a,version:r}=t.constructor.sdkMetadata;void 0!==a&&(e.name=a),void 0!==r&&(e.version=r)}}}return e}#B(e,a){let t=this.#Q();return{event:e,cv:this.#L.clerkVersion??"",it:this.#L.instanceType??"",sdk:t.name,sdkv:t.version,...this.#L.publishableKey?{pk:this.#L.publishableKey}:{},...this.#L.secretKey?{sk:this.#L.secretKey}:{},payload:a}}#Y(e){if(null==e||"object"!=typeof e)return null;try{let a=JSON.parse(JSON.stringify(e));if(a&&"object"==typeof a&&!Array.isArray(a))return a;return null}catch{return null}}};let eH="COMPONENT_MOUNTED",eQ=new Set(["SignIn","SignUp"]);function eY(e){return function(a,t,r){return{event:e,eventSamplingRate:e===eH?eQ.has(a)?1:.1:.1,payload:{component:a,appearanceProp:!!t?.appearance,baseTheme:!!t?.appearance?.baseTheme,elements:!!t?.appearance?.elements,variables:!!t?.appearance?.variables,...r}}}}function eX(e,a,t){return eY(eH)(e,a,t)}function eZ(e,a,t){return eY("COMPONENT_OPENED")(e,a,t)}function e1(e){return"string"==typeof e?e:"object"==typeof e&&null!==e&&"name"in e&&"string"==typeof e.name?e.name:void 0}function e2(e,a,t){return"function"==typeof e?e(a):void 0!==e?e:void 0!==t?t:void 0}let e0=(...e)=>{},e9=!1,e3=null,e8=!1,e5=[];function e4(e,a,t,r){e9&&(e5.push({level:e,message:a,context:t,source:r,ts:Date.now()}),e5.length>200&&e5.shift())}async function e6(e){try{if(!e9||e3)return;let{getDebugLogger:a}=await Promise.resolve().then(i.bind(i,854)),t=await a({logLevel:e?.logLevel,telemetryCollector:e?.telemetryCollector});if(t&&(e3=t)&&0!==e5.length){for(let e of e5){let a={...e.context||{},__preInit:!0,__preInitTs:e.ts};switch(e.level){case"error":e3.error(e.message,a,e.source);break;case"warn":e3.warn(e.message,a,e.source);break;case"info":e3.info(e.message,a,e.source);break;case"debug":e3.debug(e.message,a,e.source)}}e5.length=0}}catch(e){try{console.debug?.("Debug logger initialization failed",e)}catch{}return}}let e7={debug(e,a,t){e3?e3.debug(e,a,t):e4("debug",e,a,t)},error(e,a,t){e3?e3.error(e,a,t):e4("error",e,a,t)},info(e,a,t){e3?e3.info(e,a,t):e4("info",e,a,t)},warn(e,a,t){e3?e3.warn(e,a,t):e4("warn",e,a,t)}},ae={initialDelay:125,maxDelayBetweenRetries:0,factor:2,shouldRetry:(e,a)=>a<5,retryImmediately:!1,jitter:!0},aa=async e=>new Promise(a=>setTimeout(a,e)),at=(e,a)=>a?e*(1+Math.random()):e,ar=async(e,a={})=>{var t;let r,i=0,{shouldRetry:n,initialDelay:s,maxDelayBetweenRetries:o,factor:l,retryImmediately:c,jitter:d,onBeforeRetry:u}={...ae,...a},h=(t={initialDelay:s,maxDelayBetweenRetries:o,factor:l,jitter:d},r=0,async()=>{let e;await aa((e=at(e=t.initialDelay*Math.pow(t.factor,r),t.jitter),Math.min(t.maxDelayBetweenRetries||e,e))),r++});for(;;)try{return await e()}catch(e){if(!n(e,++i))throw e;u&&await u(i),c&&1===i?await aa(at(100,d)):await h()}},ai=async e=>ar(e,{initialDelay:100,shouldRetry:(e,a)=>a<=3,retryImmediately:!0,factor:2});class an{#ee={"@zxcvbn-ts/core":()=>ai(()=>Promise.resolve().then(i.bind(i,10))),"@zxcvbn-ts/language-common":()=>ai(()=>Promise.resolve().then(i.bind(i,655))),"@base-org/account":()=>ai(()=>Promise.resolve().then(function(){var e=Error("Cannot find module '@base-org/account'");throw e.code="MODULE_NOT_FOUND",e})),"@coinbase/wallet-sdk":()=>ai(()=>Promise.resolve().then(function(){var e=Error("Cannot find module '@coinbase/wallet-sdk'");throw e.code="MODULE_NOT_FOUND",e})),"@stripe/stripe-js":()=>ai(()=>Promise.resolve().then(function(){var e=Error("Cannot find module '@stripe/stripe-js'");throw e.code="MODULE_NOT_FOUND",e}))};import(e){return this.#ee[e]?this.#ee[e]():Promise.resolve(void 0)}}let as=(e=!1)=>{let a,t;if(!e)return{track:async e=>{await e()},isUnloading:()=>!1};let r=(a=!1,t=()=>a=!0,{startListening:()=>{window.addEventListener("beforeunload",t),window.addEventListener(eD,t)},stopListening:()=>{window.removeEventListener("beforeunload",t),window.removeEventListener(eD,t)},isUnloading:()=>a});return{track:async e=>{r.startListening(),await e(),r.stopListening()},isUnloading:r.isUnloading}},ao=e=>({amount:e.amount,amountFormatted:e.amount_formatted,currency:e.currency,currencySymbol:e.currency_symbol}),al=e=>{let a={grandTotal:ao(e.grand_total),subtotal:ao(e.subtotal),taxTotal:ao(e.tax_total)};return"past_due"in e&&(a.pastDue=e.past_due?ao(e.past_due):null),"credit"in e&&(a.credit=e.credit?ao(e.credit):null),"total_due_now"in e&&(a.totalDueNow=ao(e.total_due_now)),"total_due_after_free_trial"in e&&(a.totalDueAfterFreeTrial=e.total_due_after_free_trial?ao(e.total_due_after_free_trial):null),a};function ac(e,a=""){return e.errors&&!!e.errors.find(e=>e.code===a)}let ad=function({packageName:e,customMessages:a}){let t=e;function r(e,a){if(!a)return`${t}: ${e}`;let r=e;for(let t of e.matchAll(/{{([a-zA-Z0-9-_]+)}}/g)){let e=(a[t[1]]||"").toString();r=r.replace(`{{${t[1]}}}`,e)}return`${t}: ${r}`}let i={...z,...a};return{setPackageName({packageName:e}){return"string"==typeof e&&(t=e),this},setMessages({customMessages:e}){return Object.assign(i,e||{}),this},throwInvalidPublishableKeyError(e){throw Error(r(i.InvalidPublishableKeyErrorMessage,e))},throwInvalidProxyUrl(e){throw Error(r(i.InvalidProxyUrlErrorMessage,e))},throwMissingPublishableKeyError(){throw Error(r(i.MissingPublishableKeyErrorMessage))},throwMissingSecretKeyError(){throw Error(r(i.MissingSecretKeyErrorMessage))},throwMissingClerkProviderError(e){throw Error(r(i.MissingClerkProvider,e))},throw(e){throw Error(r(e))}}}({packageName:"@clerk/clerk-js"});function au(e){return decodeURIComponent(globalThis.atob(e.replace(/_/g,"/").replace(/-/g,"+")).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""))}function ah(e){let a=(e||"").split("."),[t,r,i]=a;if(3!==a.length||!t||!r||!i)throw Error("JWT could not be decoded");let n=JSON.parse(au(r)),s={__raw:e};return Object.keys(n).forEach(e=>{s[e]=n[e]}),{encoded:{header:t,payload:r,signature:i},header:JSON.parse(au(t)),claims:s}}function am(){if(!s())return null;try{let e=navigator?.language;if(!e||"string"!=typeof e||""===e.trim())return null;return e}catch{return null}}function ap(){return void 0!==globalThis.document}function ag(){if(!function(){if(!ap())return!1;try{return window.self!==window.top}catch{return!0}}())return!1;try{return window.top?.location.href,!1}catch{return!0}}var ab=class e{#ea=[];#et={metamask:"MetaMask",okx_wallet:"OKX Wallet"};static #er=null;constructor(){if("undefined"==typeof window)return;window.addEventListener("eip6963:announceProvider",this.#ei),window.dispatchEvent(new Event("eip6963:requestProvider"))}static getInstance(){return e.#er||(e.#er=new e),e.#er}get=e=>{let a=this.#ea.find(a=>a.info.name===this.#et[e])?.provider;return void 0!==a?a:window.ethereum};#ei=e=>{this.#ea.some(a=>a.info.uuid===e.detail.info.uuid)||this.#ea.push(e.detail)}};let af=()=>(function(e){async function a(e){let{provider:a}=e,t=await u(a);if(!t)return"";let r=await t.request({method:"eth_requestAccounts"});return r&&r[0]||""}async function t(e){let{identifier:a,nonce:t,provider:r}=e,i=await u(r);return i?await i.request({method:"personal_sign",params:[`0x${t.split("").map(e=>e.charCodeAt(0).toString(16).padStart(2,"0")).join("")}`,a]}):""}async function r(){return await a({provider:"metamask"})}async function i(){return await a({provider:"coinbase_wallet"})}async function n(){return await a({provider:"okx_wallet"})}async function s(){return await a({provider:"base"})}async function o(e){return await t({...e,provider:"metamask"})}async function l(e){return await t({...e,provider:"coinbase_wallet"})}async function c(e){return await t({...e,provider:"okx_wallet"})}async function d(e){return await t({...e,provider:"base"})}async function u(a){if("coinbase_wallet"===a){let a=await e.import("@coinbase/wallet-sdk");return a?a.createCoinbaseWalletSDK({preference:{options:"all"}}).getProvider():null}if("base"===a)try{let a=await e.import("@base-org/account");if(!a)return null;return a.createBaseAccountSDK({appName:"undefined"!=typeof window&&window.Clerk?.__unstable__environment?.displayConfig?.applicationName||"undefined"!=typeof document&&document.title||"Web3 Application"}).getProvider()}catch{return null}return ab.getInstance().get(a)}return{getWeb3Identifier:a,generateWeb3Signature:t,getMetamaskIdentifier:r,getCoinbaseWalletIdentifier:i,getOKXWalletIdentifier:n,getBaseIdentifier:s,generateSignatureWithMetamask:o,generateSignatureWithCoinbaseWallet:l,generateSignatureWithOKXWallet:c,generateSignatureWithBase:d}})(new an),ay="environment",ak=JSON.stringify,aw=JSON.parse;class av{static _key(e){return`__clerk_${e}`}static isExpired(e){return!!e.exp&&Date.now()>e.exp}static setItem(e,a,t){try{let r={value:a,...t&&{exp:Date.now()+t}};window.localStorage.setItem(this._key(e),ak(r))}catch{}}static getItem(e,a){try{let t=window.localStorage.getItem(this._key(e));if(!t)return a;let r=aw(t);if(!r)return a;if(this.isExpired(r))return this.removeItem(e),a;return r?.value??a}catch{return a}}static removeItem(e){try{window.localStorage.removeItem(this._key(e))}catch{}}}let aj="ClerkJS:";function az(e){console.warn(`${aj} ${e} is not supported in this environment.`)}function a_(e=""){throw Error(`${aj} Something went wrong initializing Clerk in development mode.${e&&` ${e}`}`)}function ax(e){throw Error(`${aj} Something went wrong initializing Clerk during the ${e} flow. Please contact support.`)}function aq(e){throw Error(`${aj} You need to start a ${e} flow by calling ${e}.create() first.`)}function aS(e,a){throw Error(`${aj} Strategy "${a}" is not a valid strategy for ${e}.`)}function aU(e){throw Error(`${aj} You need to start a ${e} flow by calling ${e}.create({ identifier: 'your web3 wallet address' }) first`)}function aA(e=""){throw Error(`${aj} Missing '${e}' option`)}function aC(e,a){throw Error(`${aj} Response: ${e||0} not supported yet.
|
|
18
18
|
For more information contact us at ${a}`)}function aI(e){throw Error(`${aj} Missing publicKey. When calling 'navigator.credentials.${e}()' it is required to pass a publicKey object.`)}let aP=e=>Promise.reject(Error("Captcha not supported in this environment")),aO=e=>{let a=e.__unstable__environment,t=a?a.displayConfig.captchaProvider:"turnstile",r=e.__internal_getOption?.("nonce");return{captchaSiteKey:a?a.displayConfig.captchaPublicKey:null,captchaWidgetType:a?a.displayConfig.captchaWidgetType:null,captchaProvider:t,captchaPublicKeyInvisible:a?a.displayConfig.captchaPublicKeyInvisible:null,canUseCaptcha:a?a.userSettings.signUp.captcha_enabled&&e.isStandardBrowser:null,nonce:r||void 0}};class aT{clerk;constructor(e){this.clerk=e}async invisible(e){let{captchaSiteKey:a,canUseCaptcha:t,captchaPublicKeyInvisible:r,nonce:i}=aO(this.clerk);return t&&a&&r?{...await aP({action:e?.action,captchaProvider:"turnstile",invisibleSiteKey:r,nonce:e?.nonce||i||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:a,canUseCaptcha:t,captchaWidgetType:r,captchaProvider:i,captchaPublicKeyInvisible:n,nonce:s}=aO(this.clerk);if(t&&a&&n){let t=await aP({captchaProvider:i,invisibleSiteKey:n,nonce:s||void 0,siteKey:a,widgetType:r,...e}).catch(a=>a.captchaError?{captchaError:a.captchaError}:e?.action==="verify"?{captchaError:a?.message||a||"unexpected_captcha_error"}:void 0);return e?.action==="verify"?{...t,captchaAction:"verify"}:t}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 aE{client;CaptchaChallengeImpl;static instance;inflightException=null;captchaRetryCount=0;MAX_RETRY_ATTEMPTS=3;static getInstance(){return aE.instance||(aE.instance=new aE(tA,aT)),aE.instance}constructor(e,a){this.client=e,this.CaptchaChallengeImpl=a}async execute(e,a){if(this.captchaAttemptsExceeded())throw new S("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 a()}catch(r){let t;if(!O(r)||T(r)&&"network_error"===r.code||r.errors[0]?.code!=="requires_captcha")throw r;if(this.inflightException)return await this.inflightException,await a();this.inflightException=new Promise(e=>t=e);try{let a=await this.managedChallenge(e);a?.captchaError!=="modal_component_not_ready"&&(await this.client.getOrCreateInstance().__internal_sendCaptchaToken(a),this.captchaRetryCount=0)}catch(e){throw this.captchaRetryCount++,e}finally{t(),this.inflightException=null}return await a()}}managedChallenge(e){return new this.CaptchaChallengeImpl(e).managedInModal({action:"verify"})}captchaAttemptsExceeded=()=>this.captchaRetryCount>=this.MAX_RETRY_ATTEMPTS}class aM{static clerk;id;pathRoot="";static get fapiClient(){return aM.clerk.getFapiClient()}async reload(e){let{rotatingTokenNonce:a}=e||{};return this._baseGet({forceUpdateClient:!0,rotatingTokenNonce:a})}isNew(){return!this.id}static async _fetch(e,a={}){return aE.getInstance().execute(this.clerk,()=>this._baseFetch(e,a))}static async _baseFetch(e,a={}){let t;aM.fapiClient||function(){throw Error(`${aj} Missing FAPI client in resources.`)}();let{fetchMaxTries:r}=a;try{t=await aM.fapiClient.request(e,{fetchMaxTries:r})}catch(a){if(this.shouldRethrowOfflineNetworkErrors())throw new S(a?.message||a,{code:"network_error"});if(!d())return e7.warn("Network request failed while offline, returning null",{method:e.method,path:e.path},"baseResource"),null;throw a}let{payload:i,status:n,statusText:s,headers:o}=t;if(o){let e=o.get("x-country");this.clerk.__internal_setCountry(e?e.toLowerCase():null)}if(("GET"!==e.method||a.forceUpdateClient)&&this._updateClient(i),n>=200&&n<=299)return i;if(n>=400){let e=i?.errors,a=e?.[0]?.long_message,t=e?.[0]?.code;401===n&&"requires_captcha"!==t&&await aM.clerk.handleUnauthenticated(),function(e,a){var t;if(!a||!a[0])return;let r=a[0],i=r.long_message;if("origin_invalid"===r.code&&((t=aM.clerk.publishableKey).startsWith("live_")||t.startsWith("pk_live_"))){let t=aM.clerk.frontendApi.replace("clerk.","");throw new v(`Clerk: Production Keys are only allowed for domain "${t}".
|
|
19
|
-
API Error: ${i}`,{data:a,status:e})}}(n,e);let r={data:e,status:n};if(429===n&&o){let e=o.get("retry-after");if(e){let a=parseInt(e,10);isNaN(a)||(r.retryAfter=a)}}throw new v(a||s,r)}return null}static _updateClient(e){if(!e)return;let a=e.client||e.meta?.client;a&&aM.clerk&&aM.clerk.updateClient(tA.getOrCreateInstance().fromJSON(a))}path(e){let a=this.pathRoot;if(this.isNew())return a;let t=a.replace(/[^/]$/,"$&/")+encodeURIComponent(this.id);return e?t.replace(/[^/]$/,"$&/")+encodeURIComponent(e):t}withDefault(e,a){return e??a}async _baseGet(e={}){let a=await aM._fetch({method:"GET",path:this.path(),rotatingTokenNonce:e.rotatingTokenNonce},e);return this.fromJSON(a?.response||a)}async _baseMutate(e){let{action:a,body:t,method:r,path:i}=e,n=await aM._fetch({method:r,path:i||this.path(a),body:t});return this.fromJSON(n?.response||n)}async _baseMutateBypass(e){let{action:a,body:t,method:r,path:i}=e,n=await aM._baseFetch({method:r,path:i||this.path(a),body:t});return this.fromJSON(n?.response||n)}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=aM.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}function aR(e){let a=new Date(e||new Date);return a instanceof Date&&!isNaN(a.getTime())?a:new Date}class aF extends aM{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?aR(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?aR(e.last_used_at):null,this.updatedAt=aR(e.updated_at),this.createdAt=aR(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 aD extends aM{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?aR(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}}}(f=y||(y={}))[f.None=0]="None",f[f.Mutable=1]="Mutable",f[f.Watching=2]="Watching",f[f.RecursedCheck=4]="RecursedCheck",f[f.Recursed=8]="Recursed",f[f.Dirty=16]="Dirty",f[f.Pending=32]="Pending";let aN=[],{link:aW,unlink:aL,propagate:a$,checkDirty:aK,endTracking:aB,startTracking:aJ,shallowPropagate:aV}=function({update:e,notify:a,unwatched:t}){let r=0;return{link:function(e,a){let t,i=a.depsTail;if(void 0!==i&&i.dep===e)return;if(4&a.flags&&void 0!==(t=void 0!==i?i.nextDep:a.deps)&&t.dep===e){t.version=r,a.depsTail=t;return}let n=e.subsTail;if(void 0!==n&&n.version===r&&n.sub===a)return;let s=a.depsTail=e.subsTail={version:r,dep:e,sub:a,prevDep:i,nextDep:t,prevSub:n,nextSub:void 0};void 0!==t&&(t.prevDep=s),void 0!==i?i.nextDep=s:a.deps=s,void 0!==n?n.nextSub=s:e.subs=s},unlink:i,propagate:function(e){let t,r=e.nextSub;e:for(;;){let i=e.sub,n=i.flags;if(3&n&&(60&n?12&n?4&n?!(48&n)&&function(e,a){let t=a.depsTail;if(void 0!==t){let r=a.deps;do{if(r===e)return!0;if(r===t)break;r=r.nextDep}while(void 0!==r)}return!1}(e,i)?(i.flags=40|n,n&=1):n=0:i.flags=-9&n|32:n=0:i.flags=32|n,2&n&&a(i),1&n)){let a=i.subs;if(void 0!==a){e=a,void 0!==a.nextSub&&(t={value:r,prev:t},r=e.nextSub);continue}}if(void 0!==(e=r)){r=e.nextSub;continue}for(;void 0!==t;)if(e=t.value,t=t.prev,void 0!==e){r=e.nextSub;continue e}break}},checkDirty:function(a,t){let r,i=0;e:for(;;){let s=a.dep,o=s.flags,l=!1;if(16&t.flags)l=!0;else if((17&o)==17){if(e(s)){let e=s.subs;void 0!==e.nextSub&&n(e),l=!0}}else if((33&o)==33){(void 0!==a.nextSub||void 0!==a.prevSub)&&(r={value:a,prev:r}),a=s.deps,t=s,++i;continue}if(!l&&void 0!==a.nextDep){a=a.nextDep;continue}for(;i;){--i;let s=t.subs,o=void 0!==s.nextSub;if(o?(a=r.value,r=r.prev):a=s,l){if(e(t)){o&&n(s),t=a.sub;continue}}else t.flags&=-33;if(t=a.sub,void 0!==a.nextDep){a=a.nextDep;continue e}l=!1}return l}},endTracking:function(e){let a=e.depsTail,t=void 0!==a?a.nextDep:e.deps;for(;void 0!==t;)t=i(t,e);e.flags&=-5},startTracking:function(e){++r,e.depsTail=void 0,e.flags=-57&e.flags|4},shallowPropagate:n};function i(e,a=e.sub){let r=e.dep,n=e.prevDep,s=e.nextDep,o=e.nextSub,l=e.prevSub;return void 0!==s?s.prevDep=n:a.depsTail=n,void 0!==n?n.nextDep=s:a.deps=s,void 0!==o?o.prevSub=l:r.subsTail=l,void 0!==l?l.nextSub=o:void 0===(r.subs=o)&&t(r),s}function n(e){do{let t=e.sub,r=e.nextSub,i=t.flags;(48&i)==32&&(t.flags=16|i,2&i&&a(t)),e=r}while(void 0!==e)}}({update:e=>"getter"in e?a2(e):a0(e,e.value),notify:function e(a){let t=a.flags;if(!(64&t)){a.flags=64|t;let r=a.subs;void 0!==r?e(r.sub):aN[aQ++]=a}},unwatched(e){if("getter"in e){let a=e.deps;if(void 0!==a){e.flags=17;do a=aL(a,e);while(void 0!==a)}}else"previousValue"in e||a5.call(e)}}),aG=0,aH=0,aQ=0;function aY(a){let t=e;return e=a,t}function aX(e){return a8.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function aZ(e){return a3.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function a1(t){let r={fn:t,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==e?aW(r,e):void 0!==a&&aW(r,a);let i=aY(r);try{r.fn()}finally{aY(i)}return a5.bind(r)}function a2(e){let a=aY(e);aJ(e);try{let a=e.value;return a!==(e.value=e.getter(a))}finally{aY(a),aB(e)}}function a0(e,a){return e.flags=1,e.previousValue!==(e.previousValue=a)}function a9(){for(;aH<aQ;){let e=aN[aH];aN[aH++]=void 0,function e(a,t){if(16&t||32&t&&aK(a.deps,a)){let e=aY(a);aJ(a);try{a.fn()}finally{aY(e),aB(a)}return}32&t&&(a.flags=-33&t);let r=a.deps;for(;void 0!==r;){let a=r.dep,t=a.flags;64&t&&e(a,a.flags=-65&t),r=r.nextDep}}(e,e.flags&=-65)}aH=0,aQ=0}function a3(){let t=this.flags;if(16&t||32&t&&aK(this.deps,this)){if(a2(this)){let e=this.subs;void 0!==e&&aV(e)}}else 32&t&&(this.flags=-33&t);return void 0!==e?aW(this,e):void 0!==a&&aW(this,a),this.value}function a8(...a){if(a.length){let e=a[0];if(this.value!==(this.value=e)){this.flags=17;let e=this.subs;void 0!==e&&(a$(e),aG||a9())}}else{let a=this.value;if(16&this.flags&&a0(this,a)){let e=this.subs;void 0!==e&&aV(e)}return void 0!==e&&aW(this,e),a}}function a5(){let e=this.deps;for(;void 0!==e;)e=aL(e,this);let a=this.subs;void 0!==a&&aL(a),this.flags=0}function a4(e){let{pageSize:a,initialPage:t,...r}=e||{},i=a??10;return new URLSearchParams({...Object.entries(r).reduce((e,[a,t])=>(void 0!==t&&(e[a]=t),e),{}),limit:i+"",offset:((t??1)-1)*i+""})}class a6{static #en="/billing";static path(e,a){let{orgId:t}=a||{},r=t?`/organizations/${t}`:"/me";return`${r}${a6.#en}${e}`}getPlans=async e=>{let{for:a,...t}=e||{},r={...t,payer_type:"organization"===a?"org":"user"};return await aM._fetch({path:`${a6.#en}/plans`,method:"GET",search:a4(r)}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new ty(e))}})};getPlan=async e=>new ty(await aM._fetch({path:`${a6.#en}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await aM._fetch({path:a6.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new tv(e?.response));getStatements=async e=>{let{orgId:a,...t}=e;return await aM._fetch({path:a6.path("/statements",{orgId:a}),method:"GET",search:a4(t)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new tk(e))}})};getStatement=async e=>new tk((await aM._fetch({path:a6.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:a,...t}=e;return await aM._fetch({path:a6.path("/payment_attempts",{orgId:a}),method:"GET",search:a4(t)}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new tu(e))}})};getPaymentAttempt=async e=>new tu(await aM._fetch({path:a6.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:a,...t}=e;return new tc((await aM._fetch({path:a6.path("/checkouts",{orgId:a}),method:"POST",body:t}))?.response)}}let a7=aX({resource:null}),te=aX({error:null}),ta=aX({status:"idle"}),tt=aZ(()=>{let e=a7().resource,a=te().error,t=ta().status;return{errors:to(a,{identifier:null,password:null,code:null}),fetchStatus:t,signIn:e?e.__internal_future:null}}),tr=aX({resource:null}),ti=aX({error:null}),tn=aX({status:"idle"}),ts=aZ(()=>{let e=tr().resource,a=ti().error,t=tn().status;return{errors:to(a,{firstName:null,lastName:null,emailAddress:null,phoneNumber:null,password:null,username:null,code:null,captcha:null,legalAccepted:null}),fetchStatus:t,signUp:e?e.__internal_future:null}});function to(e,a){let t={fields:{...a},raw:null,global:null};if(!e)return t;if(!O(e))return t.raw=[e],t.global=[F(e)],t;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(t.raw?t.raw.push(e):t.raw=[e],r(e)){let a=Y(e.meta.paramName);a in t.fields&&(t.fields[a]=e)}}):(t.raw=[e],t.global=[F(e)]),t}class tl extends aM{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=aR(e.created_at)),e.updated_at&&(this.updatedAt=aR(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 tc extends aM{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 tb(e.payment_method):void 0,this.plan=new ty(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=al(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change,e.free_trial_ends_at&&(this.freeTrialEndsAt=aR(e.free_trial_ends_at)),this.payer=new tl(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>ar(()=>this._basePatch({path:a6.path(`/checkouts/${this.id}/confirm`,{orgId:this.payer.organizationId}),body:e}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,a){if(!O(e)||a>=4)return!1;let t=e?.status,r=409===t&&e.errors?.[0]?.code==="checkout_already_in_progress";return t>=500||r}})}class td{resource=new tc(null);config;signals;pendingOperations=new Map;constructor(e,a){this.config=a,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 tc.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new tc(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:a}=e||{};return this.runAsyncCheckoutTask("finalize",async()=>{if("completed"!==this.resource.status)throw Error("Clerk: `confirm()` must be called before `finalize()`");await tc.clerk.setActive({session:tc.clerk.session?.id,navigate:a})})}runAsyncCheckoutTask(e,a,t){var r,i,n;return void 0===tc.clerk.user?(console.warn("Clerk: Checkout operations cannot be performed during transitive state"),{error:null}):(r=this,i=this.signals,n=this.pendingOperations,async(e,a,t)=>{if(n.get(e))return n.get(e);let s=(async()=>{++aG,i.errorSignal({error:null}),i.fetchSignal({status:"fetching"}),t?.(),--aG||a9(),++aG;try{return await a(),i.resourceSignal({resource:r}),{error:null}}catch(e){return i.errorSignal({error:e}),{error:e}}finally{n.delete(e),i.fetchSignal({status:"idle"}),--aG||a9()}})();return n.set(e,s),s})(e,a,t)}}class tu extends aM{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=ao(e.amount),this.paidAt=e.paid_at?aR(e.paid_at):null,this.failedAt=e.failed_at?aR(e.failed_at):null,this.updatedAt=aR(e.updated_at),this.paymentMethod=e.payment_method?new tb(e.payment_method):null,this.subscriptionItem=new tj(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status),this}}let th="/payment_methods",tm=async e=>{let{orgId:a,...t}=e;return new tf((await aM._fetch({path:a6.path(`${th}/initialize`,{orgId:a}),method:"POST",body:t}))?.response)},tp=async e=>{let{orgId:a,...t}=e;return new tb((await aM._fetch({path:a6.path(th,{orgId:a}),method:"POST",body:t}))?.response)},tg=async e=>{let{orgId:a,...t}=e??{};return await aM._fetch({path:a6.path(th,{orgId:a}),method:"GET",search:a4(t)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new tb(e))}})};class tb extends aM{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:aR(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:aR(e.updated_at)),this}async remove(e){let{orgId:a}=e??{};return new tI((await aM._fetch({path:a6.path(`/payment_methods/${this.id}`,{orgId:a}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:a}=e??{};return await aM._fetch({path:a6.path("/payers/default_payment_method",{orgId:a}),method:"PUT",body:{payment_method_id:this.id}}),null}}class tf extends aM{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 ty extends aM{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=ao(e.fee),this.annualFee=e.annual_fee?ao(e.annual_fee):null,this.annualMonthlyFee=e.annual_monthly_fee?ao(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 t7(e))),this}}class tk extends aM{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=aR(e.timestamp),this.totals=al(e.totals),this.groups=e.groups.map(e=>new tw(e))),this}}class tw{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=aR(e.timestamp),this.items=e.items.map(e=>new tu(e))),this}}class tv extends aM{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=aR(e.created_at),this.updatedAt=e.updated_at?aR(e.updated_at):null,this.activeAt=aR(e.active_at),this.pastDueAt=e.past_due_at?aR(e.past_due_at):null,e.next_payment&&(this.nextPayment={amount:ao(e.next_payment.amount),date:aR(e.next_payment.date)}),this.subscriptionItems=(e.subscription_items||[]).map(e=>new tj(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1)),this}}class tj extends aM{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 ty(e.plan),this.planPeriod=e.plan_period,this.status=e.status,this.createdAt=aR(e.created_at),this.pastDueAt=e.past_due_at?aR(e.past_due_at):null,this.periodStart=aR(e.period_start),this.periodEnd=e.period_end?aR(e.period_end):null,this.canceledAt=e.canceled_at?aR(e.canceled_at):null,this.amount=e.amount?ao(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:ao(e.credit.amount)}:void 0,this.isFreeTrial=this.withDefault(e.is_free_trial,!1)),this}async cancel(e){let{orgId:a}=e;return new tI((await aM._fetch({path:a6.path(`/subscription_items/${this.id}`,{orgId:a}),method:"DELETE"}))?.response)}}let tz={build:(e,a,t)=>[e,a,t].filter(Boolean).join("-"),parse:(e,a,t)=>{let r=tz.extractTemplate(e,a,t);return{organizationId:t,sessionId:a,template:r}},extractTemplate:(e,a,t)=>{if(e===a||t&&e===`${a}-${t}`)return;let r=e.slice(a.length+1);return t&&r.endsWith(`-${t}`)&&(r=r.slice(0,-(t.length+1))),r||void 0}},t_="clerk",tx=10,tq={broadcast:!0};class tS{prefix;data;static fromKey(e){let[a,t,r=""]=e.split("::");return new tS(a,{audience:r,tokenId:t})}constructor(e,a){this.prefix=e,this.data=a,this.prefix=e,this.data=a}toKey(){let{tokenId:e,audience:a}=this.data;return[this.prefix,e,a||""].join("::")}}let tU=((e=t_)=>{let a=new Map,t=Math.random().toString(36).slice(2),r=null;return{clear:()=>{a.forEach(e=>{void 0!==e.timeoutId&&clearTimeout(e.timeoutId)}),a.clear()},close:()=>{r&&(r.close(),r=null)},get:(t,r=tx)=>{let i=new tS(e,t),n=a.get(i.toKey());if(!n)return;let s=Math.floor(Date.now()/1e3)-n.createdAt;if(n.expiresIn-s<(r||1)+5){void 0!==n.timeoutId&&clearTimeout(n.timeoutId),a.delete(i.toKey());return}return n.entry},set:i=>{((i,n=tq)=>{let s=new tS(e,{audience:i.audience,tokenId:i.tokenId}).toKey(),o=Math.floor(Date.now()/1e3),l={createdAt:i.createdAt??o,entry:i,expiresIn:void 0},c=()=>{let e=a.get(s);e===l&&(void 0!==e.timeoutId&&clearTimeout(e.timeoutId),a.delete(s))};i.tokenResolver.then(e=>{let a=e.jwt?.claims;if(!a||"number"!=typeof a.exp||"number"!=typeof a.iat)return c();let s=a.exp-a.iat;l.expiresIn=s;let o=setTimeout(c,1e3*s);l.timeoutId=o,"function"==typeof o.unref&&o.unref();let d=r;if(d&&n.broadcast){let r=e.getRawString();if(r&&a.sid){let e=a.sid,n=a.org_id||a.o?.id,s=tz.extractTemplate(i.tokenId,e,n),o=tz.build(e,s,n);if(i.tokenId===o){let a=`bc_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;e7.info("Broadcasting token update to other tabs",{organizationId:n,sessionId:e,tabId:t,template:s,tokenId:i.tokenId,traceId:a},"tokenCache");let o={organizationId:n,sessionId:e,template:s,tokenId:i.tokenId,tokenRaw:r,traceId:a};d.postMessage(o)}}}}).catch(()=>{c()}),a.set(s,l)})(i,tq)},size:()=>a.size}})();class tA extends aM{static instance;pathRoot="/client";sessions=[];signUp=new rE;signIn=new rP;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return tA.instance||(tA.instance=new tA(e)),tA.instance}static clearInstance(){tA.instance=null}static isClientResource(e){return!!e&&e instanceof tA}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(()=>{tU.clear(),this.id="",this.sessions=[],this.signUp=new rE(null),this.signIn=new rP(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=>(tU.clear(),e))}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return aM.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 rz(e)),this.signUp=new rE(e.sign_up),this.signIn=new rP(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?aR(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=aR(e.created_at||void 0),this.updatedAt=aR(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 tC extends aM{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 tI{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 tP extends aM{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="";experimental__forceOauthFirst;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 tO='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 tT=(e,a={})=>{if("undefined"==typeof Worker)return null;try{let t=new Blob([e],{type:"application/javascript; charset=utf-8"}),r=globalThis.URL.createObjectURL(t);return new Worker(r,a)}catch{return console.warn("Clerk: Cannot create worker from blob. Consider adding worker-src blob:; to your CSP"),null}},tE=()=>{let e=0,a=()=>e++,t=new Map,r=(e,a)=>e?.postMessage(a),i=e=>{t.get(e.data.id)?.()},n=tT(tO,{name:"clerk-timers"});if(n?.addEventListener("message",i),!n)return{setTimeout:globalThis.setTimeout.bind(globalThis),setInterval:globalThis.setInterval.bind(globalThis),clearTimeout:globalThis.clearTimeout.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis),cleanup:e0};let s=()=>{n||(n=tT(tO,{name:"clerk-timers"}),n?.addEventListener("message",i))};return{setTimeout:(e,i)=>{s();let o=a();return t.set(o,()=>{e(),t.delete(o)}),r(n,{type:"setTimeout",id:o,ms:i}),o},setInterval:(e,i)=>{s();let o=a();return t.set(o,e),r(n,{type:"setInterval",id:o,ms:i}),o},clearTimeout:e=>{s(),t.delete(e),r(n,{type:"clearTimeout",id:e})},clearInterval:e=>{s(),t.delete(e),r(n,{type:"clearInterval",id:e})},cleanup:()=>{n&&(n.terminate(),n=null,t.clear())}}};function tM({delayInMs:e}={delayInMs:1e3}){let a,t=tE(),r=!1,i=()=>{a&&(t.clearTimeout(a),t.cleanup()),r=!0},n=async s=>{r=!1,await s(i),r||(a=t.setTimeout(()=>{n(s)},e))};return{run:n,stop:i}}class tR extends aM{id;emailAddress="";matchesSsoConnection=!1;linkedTo=[];verification;constructor(e,a){super(),this.pathRoot=a,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:a}=e||{};return this._basePost({action:"attempt_verification",body:{code:a}})};createEmailLinkFlow=()=>{let{run:e,stop:a}=tM();return{startEmailLinkFlow:async({redirectUrl:t})=>(await this.prepareVerification({strategy:"email_link",redirectUrl:t}),new Promise((t,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(a(),t(e))}).catch(e=>{a(),r(e)}))})),cancelEmailLinkFlow:a}};createEnterpriseSSOLinkFlow=()=>{let{run:e,stop:a}=tM();return{startEnterpriseSSOLinkFlow:async({redirectUrl:t})=>{if(!(await this.prepareVerification({strategy:"enterprise_sso",redirectUrl:t})).verification.externalVerificationRedirectURL)throw Error("Unexpected: External verification redirect URL is missing");return new Promise((t,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(a(),t(e))}).catch(e=>{a(),r(e)}))})},cancelEnterpriseSSOLinkFlow:a}};destroy=()=>this._baseDelete();toString=()=>this.emailAddress;fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.verification=new tG(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new re(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 tF=class{static encode(e){return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}static decode(e){let a=atob(e.replace(/-/g,"+").replace(/_/g,"/")),t=a.length,r=new Uint8Array(t);for(let e=0;e<t;e++)r[e]=a.charCodeAt(e);return r.buffer}};async function tD(e){try{let a=await navigator.credentials.create({publicKey:e});if(!a)return{error:new A("Browser failed to create credential",{code:"passkey_registration_failed"}),publicKeyCredential:null};return{publicKeyCredential:a,error:null}}catch(e){var a;return{error:"InvalidStateError"===(a=e).name?new A(a.message,{code:"passkey_already_exists"}):"NotAllowedError"===a.name?new A(a.message,{code:"passkey_registration_cancelled"}):tL(a),publicKeyCredential:null}}}let tN=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 tW({publicKeyOptions:e,conditionalUI:a}){try{let t=await navigator.credentials.get({publicKey:e,mediation:a?"conditional":"optional",signal:tN.createAbortSignal()});if(!t)return{error:new A("Browser failed to get credential",{code:"passkey_retrieval_failed"}),publicKeyCredential:null};return{publicKeyCredential:t,error:null}}catch(e){var t;return{error:"NotAllowedError"===(t=e).name?new A(t.message,{code:"passkey_retrieval_cancelled"}):tL(t),publicKeyCredential:null}}}function tL(e){return"AbortError"===e.name?new A(e.message,{code:"passkey_operation_aborted"}):"SecurityError"===e.name?new A(e.message,{code:"passkey_invalid_rpID_or_domain"}):e}function t$(e){let a=tV(e.challenge),t=(e.allowCredentials||[]).map(e=>({...e,id:tV(e.id)}));return{...e,allowCredentials:t,challenge:a}}function tK(e){return{type:e.type,id:e.id,rawId:tJ(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function tB(e){let a=e.response;return{...tK(e),response:{clientDataJSON:tJ(a.clientDataJSON),authenticatorData:tJ(a.authenticatorData),signature:tJ(a.signature),userHandle:a.userHandle?tJ(a.userHandle):null}}}let tJ=tF.encode.bind(tF),tV=tF.decode.bind(tF);class tG extends aM{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===aM.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=aR(e.expire_at||void 0),this.error=e.error?new k(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 tH extends tG{publicKey=null;constructor(e){super(e),this.fromJSON(e)}fromJSON(e){var a;let t,r,i;return super.fromJSON(e),e?.nonce&&(this.publicKey=(t=tV((a=JSON.parse(e.nonce)).user.id),r=tV(a.challenge),i=(a.excludeCredentials||[]).map(e=>({...e,id:tV(e.id)})),{...a,excludeCredentials:i,challenge:r,user:{...a.user,id:t}})),this}}class tQ{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new tY(e.email_address),this.phoneNumber=new tY(e.phone_number),this.web3Wallet=new tY(e.web3_wallet),this.externalAccount=new tG(e.external_account)):(this.emailAddress=new tY(null),this.phoneNumber=new tY(null),this.web3Wallet=new tY(null),this.externalAccount=new tG(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 tY extends tG{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 tX extends aM{id;protocol;provider;providerUserId=null;active;emailAddress="";firstName="";lastName="";publicMetadata={};verification=null;enterpriseConnection=null;lastAuthenticatedAt=null;enterpriseConnectionId=null;constructor(e,a){super(),this.pathRoot=a,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?aR(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new tG(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new tZ(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 tZ extends aM{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=aR(e.created_at),this.updatedAt=aR(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 t1="token:update",t2="user:signOut",t0="environment:update",t9="session:tokenResolved",t3=p();class t8 extends aM{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 t5 extends aM{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 t4 extends aM{static instance;authConfig=new aD;displayConfig=new tP;maintenanceMode=!1;clientDebugMode=!1;pathRoot="/environment";userSettings=new rB;organizationSettings=new t5;commerceSettings=new tC;apiKeysSettings=new t8;protectConfig=new rg;static getInstance(){return t4.instance||(t4.instance=new t4),t4.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new aD(e.auth_config),this.displayConfig=new tP(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 t5(e.organization_settings),this.userSettings=new rB(e.user_settings),this.commerceSettings=new tC(e.commerce_settings),this.apiKeysSettings=new t8(e.api_keys_settings),this.protectConfig=new rg(e.protect_config)),this}fetch({touch:e,fetchMaxTries:a}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:a})).then(e=>(t3.emit(t0,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()}}}class t6 extends aM{id;identificationId;provider;providerUserId="";emailAddress="";approvedScopes="";firstName="";lastName="";imageUrl="";username="";phoneNumber="";publicMetadata={};label="";verification=null;constructor(e,a){super(),this.pathRoot=a,this.fromJSON(e)}reauthorize=e=>{let{additionalScopes:a,redirectUrl:t}=e||{};return this._basePatch({action:"reauthorize",body:{additional_scope:a,redirect_url:t}})};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 tG(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 t7 extends aM{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 re extends aM{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 ra extends aM{id;name=null;publicUrl=null;static async create(e,a={}){let t,r=a;return"string"==typeof a.file?(r=a.file,t=new Headers({"Content-Type":"application/octet-stream"})):a.file&&(r=new FormData).append("file",a.file),new ra((await aM._fetch({path:e,method:"POST",body:r,headers:t}))?.response)}static async delete(e){return new ra((await aM._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 rt extends aM{id;name;organizationId;enrollmentMode;verification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:a}){return new rt((await aM._fetch({path:`/organizations/${e}/domains`,method:"POST",body:{name:a}}))?.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:aR(e.verification.expires_at)}:this.verification=null),this}}class rr extends aM{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=aR(e.created_at),this.updatedAt=aR(e.updated_at),e.public_user_data&&(this.publicUserData=new rb(e.public_user_data))),this}}class ri extends aM{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=aR(e.created_at),this.updatedAt=aR(e.updated_at)),this}}class rn extends aM{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 ri(e)),this.createdAt=aR(e.created_at),this.updatedAt=aR(e.updated_at)),this}}class rs extends aM{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 rs((await aM._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new rs((await aM._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await aM._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:a4(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rn(e))}});getDomains=async e=>await aM._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:a4(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rt(e))}});getDomain=async({domainId:e})=>new rt((await aM._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getMembershipRequests=async e=>await aM._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:a4(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rr(e))}});createDomain=async e=>rt.create(this.id,{name:e});getMemberships=async e=>await aM._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:a4({...e,paginated:!0})}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rl(e))}});getInvitations=async e=>await aM._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:a4(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new ro(e))}});addMember=async({userId:e,role:a})=>await aM._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:a}}).then(e=>new rl(e?.response));inviteMember=async e=>ro.create(this.id,e);inviteMembers=async e=>ro.createBulk(this.id,e);updateMember=async({userId:e,role:a})=>await aM._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:a}}).then(e=>new rl(e?.response));removeMember=async e=>await aM._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new rl(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let a,t;return null===e?await aM._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new rs(e?.response)):("string"==typeof e?(a=e,t=new Headers({"Content-Type":"application/octet-stream"})):(a=new FormData).append("file",e),await aM._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:a,headers:t}).then(e=>new rs(e?.response)))};initializePaymentMethod=e=>tm({...e,orgId:this.id});addPaymentMethod=e=>tp({...e,orgId:this.id});getPaymentMethods=e=>tg({...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=aR(e.created_at),this.updatedAt=aR(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:a}=e||{},t=(await aM._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:a},{forceUpdateClient:!0}))?.response;return this.fromJSON(t)}}class ro extends aM{id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:a,role:t}){return new ro((await aM._fetch({path:`/organizations/${e}/invitations`,method:"POST",body:{email_address:a,role:t}}))?.response)}static async createBulk(e,a){let{emailAddresses:t,role:r}=a;return((await aM._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:t,role:r}}))?.response).map(e=>new ro(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=aR(e.created_at),this.updatedAt=aR(e.updated_at)),this}}class rl extends aM{id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await aM._fetch({path:"/me/organization_memberships",method:"GET",search:a4({...e,paginated:!0})}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rl(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 rs(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new rb(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=aR(e.created_at),this.updatedAt=aR(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(`${aj} Calling OrganizationMembership.reload is not currently supported. Please contact support.`)}}class rc extends aM{id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await aM._fetch({path:"/me/organization_suggestions",method:"GET",search:a4(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rc(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=aR(e.created_at),this.updatedAt=aR(e.updated_at)),this}}function rd(){return l()&&"function"==typeof window.PublicKeyCredential}async function ru(){try{return rd()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function rh(){try{return"undefined"!=typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class rm extends aM{id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return aM._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new rm(e?.response))}static async attemptVerification(e,a){let t,r=(t=a.response,{...tK(a),response:{clientDataJSON:tJ(t.clientDataJSON),attestationObject:tJ(t.attestationObject),transports:t.getTransports()}});return aM._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(r)}}).then(e=>new rm(e?.response))}static async registerPasskey(){let e=rm.clerk.__internal_isWebAuthnSupported||rd,a=rm.clerk.__internal_createPublicCredentials||tD,t=rm.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||rh;if(!e())throw new A("Passkeys are not supported on this device.",{code:"passkey_not_supported"});let r=await this.create(),{verification:i}=r,n=i?.publicKey;if(n||aI("create"),n.authenticatorSelection?.authenticatorAttachment==="platform"&&!await t())throw new A("Registration requires a platform authenticator but the device does not support it.",{code:"passkey_pa_not_supported"});let{publicKeyCredential:s,error:o}=await a(n);if(!s)throw o;return this.attemptVerification(r.id,s)}update=e=>this._basePatch({body:e});delete=async()=>new tI((await aM._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?aR(e.last_used_at):null,this.createdAt=aR(e.created_at),this.updatedAt=aR(e.updated_at),e.verification&&(this.verification=new tH(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 rp extends aM{id;phoneNumber="";reservedForSecondFactor=!1;defaultSecondFactor=!1;linkedTo=[];verification;backupCodes;constructor(e,a){super(),this.pathRoot=a,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:a}=e||{};return this._basePost({action:"attempt_verification",body:{code:a}})};setReservedForSecondFactor=e=>{let{reserved:a}=e||{};return this._basePatch({body:{reserved_for_second_factor:a}})};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 tG(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new re(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 rg extends aM{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 rb{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 rf={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"}},ry=new Set(["first_factor","second_factor","multi_factor"]),rk=new Set(["strict_mfa","strict","moderate","lax"]),rw=(e,a)=>{let{org:t,user:r}=rv(e),[i,n]=a.split(":"),s=n||i;return"org"===i?t.includes(s):"user"===i?r.includes(s):[...t,...r].includes(s)},rv=e=>{let a=e?e.split(",").map(e=>e.trim()):[];return{org:a.filter(e=>e.split(":")[0].includes("o")).map(e=>e.split(":")[1]),user:a.filter(e=>e.split(":")[0].includes("u")).map(e=>e.split(":")[1])}};class rj extends aM{status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new tG(null);secondFactorVerification=new tG(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new rz(e.session),this.level=e.level,this.supportedFirstFactors=ea(e.supported_first_factors),this.supportedSecondFactors=ea(e.supported_second_factors),this.firstFactorVerification=new tG(e.first_factor_verification),this.secondFactorVerification=new tG(e.second_factor_verification)),this}}class rz extends aM{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 rz}constructor(e){super(),this.fromJSON(e),this.#es(this.lastActiveToken)}end=()=>(tU.clear(),this._basePost({action:"end"}));remove=()=>(tU.clear(),this._basePost({action:"remove"}));touch=()=>this._basePost({action:"touch",body:{active_organization_id:this.lastActiveOrganizationId}}).then(e=>(e.lastActiveToken&&t3.emit(t1,{token:e.lastActiveToken}),e));clearCache=()=>tU.clear();getToken=async e=>ar(()=>this._getToken(e),{factor:1.55,initialDelay:3e3,maxDelayBetweenRetries:5e4,jitter:!1,shouldRetry:(e,a)=>!I(e)&&a<=8});checkAuthorization=e=>{let a,t=(this.user?.organizationMemberships||[]).find(e=>e.organization.id===this.lastActiveOrganizationId);return(a={userId:this.user?.id,factorVerificationAge:this.factorVerificationAge,orgId:t?.id,orgRole:t?.role,orgPermissions:t?.permissions,features:this.lastActiveToken?.jwt?.claims.fea||"",plans:this.lastActiveToken?.jwt?.claims.pla||""},e=>{if(!a.userId)return!1;let t=((e,a)=>{let{features:t,plans:r}=a;return e.feature&&t?rw(t,e.feature):e.plan&&r?rw(r,e.plan):null})(e,a),r=((e,a)=>{let{orgId:t,orgRole:r,orgPermissions:i}=a;return(e.role||e.permission)&&t&&r&&i?e.permission?i.includes(e.permission.replace(/^(org:)*/,"org:")):e.role?r.replace(/^(org:)*/,"org:")===e.role.replace(/^(org:)*/,"org:"):null:null})(e,a),i=((e,{factorVerificationAge:a})=>{if(!e.reverification||!a)return null;let t=(e=>{let a,t;if(!e)return!1;let r="string"==typeof e&&rk.has(e),i="object"==typeof e&&(a=e.level,ry.has(a))&&"number"==typeof(t=e.afterMinutes)&&t>0;return(!!r||!!i)&&(e=>"string"==typeof e?rf[e]:e).bind(null,e)})(e.reverification);if(!t)return null;let{level:r,afterMinutes:i}=t(),[n,s]=a,o=-1!==n?i>n:null,l=-1!==s?i>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,a);return[t||r,i].some(e=>null===e)?[t||r,i].some(e=>!0===e):[t||r,i].every(e=>!0===e)})(e)};#es=e=>{e&&tU.set({tokenId:this.#eo(),tokenResolver:Promise.resolve(e)})};#eo(e,a){let t=void 0===a?this.lastActiveOrganizationId:a;return tz.build(this.id,e,t)}startVerification=async({level:e})=>new rj((await aM._fetch({method:"POST",path:`/client/sessions/${this.id}/verify`,body:{level:e}}))?.response);prepareFirstFactorVerification=async e=>{let a;switch(e.strategy){case"email_code":a={emailAddressId:e.emailAddressId};break;case"phone_code":a={phoneNumberId:e.phoneNumberId,default:e.default};break;case"passkey":a={};break;case"enterprise_sso":a={emailAddressId:e.emailAddressId,enterpriseConnectionId:e.enterpriseConnectionId,redirectUrl:e.redirectUrl};break;default:aS("Session.prepareFirstFactorVerification",e.strategy)}return new rj((await aM._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_first_factor`,body:{...a,strategy:e.strategy}}))?.response)};attemptFirstFactorVerification=async e=>{let a;return a="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(tB(e.publicKeyCredential))}:{...e},new rj((await aM._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_first_factor`,body:{...a,strategy:e.strategy}}))?.response)};verifyWithPasskey=async()=>{let{nonce:e=null}=(await this.prepareFirstFactorVerification({strategy:"passkey"})).firstFactorVerification,a=rz.clerk.__internal_isWebAuthnSupported||rd,t=rz.clerk.__internal_getPublicCredentials||tW;if(!a())throw new A("Passkeys are not supported",{code:"passkey_not_supported"});let r=e?t$(JSON.parse(e)):null;r||aI("get");let{publicKeyCredential:i,error:n}=await t({publicKeyOptions:r,conditionalUI:!1});if(!i)throw n;return this.attemptFirstFactorVerification({strategy:"passkey",publicKeyCredential:i})};prepareSecondFactorVerification=async e=>new rj((await aM._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>new rj((await aM._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=aR(e.expire_at),this.abandonAt=aR(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=aR(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.createdAt=aR(e.created_at),this.updatedAt=aR(e.updated_at),this.user=new rW(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new rb(e.public_user_data)),this.lastActiveToken=e.last_active_token?new rF(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:a,template:t,skipCache:r=!1}=e||{},i=void 0===e?.organizationId?this.lastActiveOrganizationId:e?.organizationId;if(!t&&Number(a)>=60)throw Error("Leeway can not exceed the token lifespan (60 seconds)");let n=this.#eo(t,i),s=r?void 0:tU.get({tokenId:n},a),o=!t&&i===this.lastActiveOrganizationId;if(s){e7.debug("Using cached token (no fetch needed)",{tokenId:n},"session");let e=await s.tokenResolver;return o&&t3.emit(t1,{token:e}),e.getRawString()||null}e7.info("Fetching new token from API",{organizationId:i,template:t,tokenId:n},"session");let l=t?`${this.path()}/tokens/${t}`:`${this.path()}/tokens`,c=t?{}:{organizationId:i},d=rF.create(l,c,r);return tU.set({tokenId:n,tokenResolver:d}),d.then(e=>(o&&(t3.emit(t1,{token:e}),e.jwt&&(this.lastActiveToken=e,t3.emit(t9,null))),e.getRawString()||null))}get currentTask(){let[e]=this.tasks??[];return e}}class r_ extends aM{pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,a){super(),this.pathRoot=a,this.fromJSON(e)}static retrieve(){let e=aM.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new r_(e,"/me/sessions"))).catch(()=>[])}revoke(){return this._basePost({action:"revoke",body:{}})}fromJSON(e){let a;return e?(this.id=e.id,this.status=e.status,this.expireAt=aR(e.expire_at),this.abandonAt=aR(e.abandon_at),this.lastActiveAt=aR(e.last_active_at||void 0),this.latestActivity={id:(a=e.latest_activity??{}).id,deviceType:a.device_type,browserName:a.browser_name,browserVersion:a.browser_version,country:a.country,city:a.city,isMobile:a.is_mobile,ipAddress:a.ip_address},this.actor=e.actor,this):this}}let rx=(e,a,t)=>{let{onValidation:r=e0,onValidationComplexity:i=e0}=t||{},{show_zxcvbn:n,validatePassword:s}=a,o=e=>((e,a)=>{let{max_length:t,min_length:r,require_special_char:i,require_lowercase:n,require_numbers:s,require_uppercase:o}=a,l=(e=>{let a;if(e.allowed_special_characters){let t=e.allowed_special_characters.replace("[","\\[");t=t.replace("]","\\]"),a=RegExp(`[${t}]`)}else a=/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/;return(e,{minLength:t,maxLength:r})=>({max_length:e.length<r,min_length:e.length>=t,require_numbers:/\d/.test(e),require_lowercase:/[a-z]/.test(e),require_uppercase:/[A-Z]/.test(e),require_special_char:a.test(e)})})(a)(e,{maxLength:a.max_length,minLength:a.min_length}),c={max_length:t,min_length:r,require_special_char:i,require_lowercase:n,require_numbers:s,require_uppercase:o},d=new Map;for(let e in c)c[e]&&!l[e]&&d.set(e,!0);return Object.freeze(Object.fromEntries(d))})(e,a),l=(({min_zxcvbn_strength:e,onResult:a})=>t=>r=>{let i=t(r);return(a?.(i),i.score>=e&&i.score<3)?{state:"pass",keys:["unstable__errors.zxcvbn.couldBeStronger"],result:i}:i.score>=e?{state:"excellent",result:i}:{state:"fail",keys:["unstable__errors.zxcvbn.notEnough",...i.feedback.suggestions.map(e=>`unstable__errors.zxcvbn.suggestions.${e}`)],result:i}})(a),c={};return(a,t)=>{let{onValidation:d=r,onValidationComplexity:u=i}=t||{};if(!s)return;let h=o(a);u(0===Object.keys(h).length),c={...c,complexity:h},n&&e().then(e=>{let t=l(e)(a);d({...c={...c,strength:t},strength:t})}),c.complexity&&0===Object.keys(c.complexity).length&&n||d(c)}};function rq(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function rS(e,a,t,r,i){if(!e.client||!r.popup)return;let n=rq(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",a);let l=e.buildUrlWithAuth(o.toString()),c=e.buildUrlWithAuth(`${n}/popup-callback`),d=e.buildUrlWithAuth(`${n}/popup-callback?return_url=${encodeURIComponent(l)}`),u=async a=>{if(a.origin!==n)return;let t=!1;if(a.data.session){if(!e.client?.sessions.find(e=>e.id===a.data.session))try{await e.client?.reload()}catch(e){console.error(e)}await e.setActive({session:a.data.session,redirectUrl:r.redirectUrlComplete}),t=!0}else a.data.return_url&&(e.navigate(a.data.return_url),t=!0);t&&window.removeEventListener("message",u)};window.addEventListener("message",u),await t({...r,redirectUrlComplete:c,redirectUrl:d},i)}function rU(e,{redirectCallbackUrl:a,redirectUrl:t}){let r=rq(e.frontendApi),i=new URL(a);i.searchParams.set("sign_in_force_redirect_url",t),i.searchParams.set("sign_up_force_redirect_url",t);let n=e.buildUrlWithAuth(i.toString()),s=e.buildUrlWithAuth(`${r}/popup-callback`);return{redirectCallbackUrl:e.buildUrlWithAuth(`${r}/popup-callback?return_url=${encodeURIComponent(n)}`),redirectUrl:s}}function rA(e,a){return new Promise((t,r)=>{if(!e.client||!a.popup)return void r();let i=async a=>{a.origin===rq(e.frontendApi)&&(a.data.session||a.data.return_url?(window.removeEventListener("message",i),t()):r())};window.addEventListener("message",i),a.popup.location.href=a.externalVerificationRedirectURL.toString()})}async function rC(e,a){t3.emit("resource:error",{resource:e,error:null}),t3.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await a(),error:null}}catch(a){return t3.emit("resource:error",{resource:e,error:a}),{error:a}}finally{t3.emit("resource:fetch",{resource:e,status:"idle"})}}let rI=()=>{var e;return(e=new an,{loadZxcvbn:()=>Promise.all([e.import("@zxcvbn-ts/core"),e.import("@zxcvbn-ts/language-common")]).then(([e,a])=>{if(!e||!a)throw Error("Failed to load zxcvbn modules");let{zxcvbnOptions:t,zxcvbn:r}=e,{dictionary:i,adjacencyGraphs:n}=a;return t.setOptions({dictionary:{...i},graphs:n}),r})}).loadZxcvbn};class rP extends aM{pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;firstFactorVerification=new tG(null);secondFactorVerification=new tG(null);identifier=null;createdSessionId=null;userData=new rL(null);clientTrustState;get status(){return this._status}set status(e){let a=this._status;this._status=e,e&&a!==e&&e7.debug("SignIn.status",{id:this.id,from:a,to:e})}__internal_future=new rO(this);__internal_basePost=this._basePost.bind(this);__internal_baseGet=this._baseGet.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=e=>{e7.debug("SignIn.create",{id:this.id,strategy:"strategy"in e?e.strategy:void 0});let a=am();return this._basePost({path:this.pathRoot,body:a?{locale:a,...e}:e})};resetPassword=e=>this._basePost({body:e,action:"reset_password"});prepareFirstFactor=e=>{let a;switch(e7.debug("SignIn.prepareFirstFactor",{id:this.id,strategy:e.strategy}),e.strategy){case"passkey":a={};break;case"email_link":a={emailAddressId:e.emailAddressId,redirectUrl:e.redirectUrl};break;case"email_code":case"reset_password_email_code":a={emailAddressId:e.emailAddressId};break;case"phone_code":a={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":a={web3WalletId:e.web3WalletId};break;case"reset_password_phone_code":a={phoneNumberId:e.phoneNumberId};break;case"enterprise_sso":a={redirectUrl:e.redirectUrl,actionCompleteRedirectUrl:e.actionCompleteRedirectUrl,oidcPrompt:e.oidcPrompt,enterpriseConnectionId:e.enterpriseConnectionId};break;default:aS("SignIn.prepareFirstFactor",e.strategy)}return this._basePost({body:{...a,strategy:e.strategy},action:"prepare_first_factor"})};attemptFirstFactor=e=>{let a;return e7.debug("SignIn.attemptFirstFactor",{id:this.id,strategy:e.strategy}),a="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(tB(e.publicKeyCredential))}:{...e},this._basePost({body:{...a,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:a}=tM();return{startEmailLinkFlow:async({emailAddressId:t,redirectUrl:r})=>{this.id||aq("SignIn");let i={strategy:"email_link",emailAddressId:t,redirectUrl:r},n="needs_second_factor"===this.status,s=n?"secondFactorVerification":"firstFactorVerification";return n?await this.prepareSecondFactor(i):await this.prepareFirstFactor(i),new Promise((t,r)=>{e(()=>this.reload().then(e=>{let r=e[s].status;("verified"===r||"expired"===r)&&(a(),t(e))}).catch(e=>{a(),r(e)}))})},cancelEmailLinkFlow:a}};prepareSecondFactor=e=>(e7.debug("SignIn.prepareSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_second_factor"}));attemptSecondFactor=e=>(e7.debug("SignIn.attemptSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_second_factor"}));authenticateWithRedirectOrPopup=async(e,a)=>{let{strategy:t,redirectUrlComplete:r,identifier:i,oidcPrompt:n,continueSignIn:s,enterpriseConnectionId:o}=e||{},l=rP.clerk.buildUrlWithAuth(e.redirectUrl);this.id&&s||await this.create({strategy:t,identifier:i,redirectUrl:l,actionCompleteRedirectUrl:r}),"enterprise_sso"===t&&await this.prepareFirstFactor({strategy:t,redirectUrl:l,actionCompleteRedirectUrl:r,oidcPrompt:n,enterpriseConnectionId:o});let{status:c,externalVerificationRedirectURL:d}=this.firstFactorVerification;"unverified"===c&&d?a(d):aC(c,rP.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eW);authenticateWithPopup=async e=>{let{popup:a}=e||{};return a||aA("popup"),rS(rP.clerk,"signIn",this.authenticateWithRedirectOrPopup,e,e=>{a.location.href=e.toString()})};authenticateWithWeb3=async e=>{let a,{identifier:t,generateSignature:r,strategy:i="web3_metamask_signature"}=e||{},n=i.replace("web3_","").replace("_signature","");"function"!=typeof r&&aA("generateSignature"),await this.create({identifier:t});let s=this.supportedFirstFactors?.find(e=>e.strategy===i);s||aU("SignIn"),await this.prepareFirstFactor(s);let{message:o}=this.firstFactorVerification;o||aU("SignIn");try{a=await r({identifier:t,nonce:o,provider:n})}catch(e){if("coinbase_wallet"===n&&4001===e.code)a=await r({identifier:t,nonce:o,provider:n});else throw e}return this.attemptFirstFactor({signature:a,strategy:i})};authenticateWithMetamask=async()=>{let e=await af().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:af().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await af().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:af().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await af().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:af().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await af().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:af().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithPasskey=async e=>{let{flow:a}=e||{},t=rP.clerk.__internal_isWebAuthnSupported||rd,r=rP.clerk.__internal_getPublicCredentials||tW,i=rP.clerk.__internal_isWebAuthnAutofillSupported||ru;if(!t())throw new A("Passkeys are not supported",{code:"passkey_not_supported"});if("autofill"===a||"discoverable"===a)await this.create({strategy:"passkey"});else{let e=this.supportedFirstFactors.find(e=>"passkey"===e.strategy);e||function(){throw Error(`${aj} You need to start a SignIn flow by calling SignIn.create({ strategy: 'passkey' }) first`)}(),await this.prepareFirstFactor(e)}let{nonce:n}=this.firstFactorVerification,s=n?t$(JSON.parse(n)):null;s||aI("get");let o=!1;"autofill"===a&&(o=await i());let{publicKeyCredential:l,error:c}=await r({publicKeyOptions:s,conditionalUI:o});if(!l)throw c;return this.attemptFirstFactor({publicKeyCredential:l,strategy:"passkey"})};validatePassword=(e,a)=>{if(rP.clerk.__unstable__environment?.userSettings.passwordSettings)return rx(rI(),{...rP.clerk.__unstable__environment?.userSettings.passwordSettings,validatePassword:!0})(e,a)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.supportedIdentifiers=e.supported_identifiers,this.identifier=e.identifier,this.supportedFirstFactors=ea(e.supported_first_factors),this.supportedSecondFactors=ea(e.supported_second_factors),this.firstFactorVerification=new tG(e.first_factor_verification),this.secondFactorVerification=new tG(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new rL(e.user_data),this.clientTrustState=e.client_trust_state??void 0),t3.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:ee(this.supportedFirstFactors),supported_second_factors:ee(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 rO{resource;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(!s())return null;const e=eI("__clerk_status"),a=eI("__clerk_created_session");if(!e||!a)return null;const t="verified"===e&&void 0!==rP.clerk.client&&rP.clerk.client.sessions.some(e=>e.id===a);return{status:e,createdSessionId:a,verifiedFromTheSameClient:t}}};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)};#el=!1;constructor(e){this.resource=e}get id(){return this.resource.id}get identifier(){return this.resource.identifier}get createdSessionId(){return this.resource.createdSessionId}get userData(){return this.resource.userData}get status(){return this.resource.status||"needs_identifier"}get supportedFirstFactors(){return this.resource.supportedFirstFactors??[]}get supportedSecondFactors(){return this.resource.supportedSecondFactors??[]}get isTransferable(){return"transferable"===this.resource.firstFactorVerification.status}get existingSession(){if("failed"===this.resource.firstFactorVerification.status&&this.resource.firstFactorVerification.error?.code==="identifier_already_signed_in"&&this.resource.firstFactorVerification.error?.meta?.sessionId)return{sessionId:this.resource.firstFactorVerification.error?.meta?.sessionId}}get firstFactorVerification(){return this.resource.firstFactorVerification}get secondFactorVerification(){return this.resource.secondFactorVerification}get hasBeenFinalized(){return this.#el}async sendResetPasswordEmailCode(){if(!this.resource.id)throw Error("Cannot reset password without a sign in.");return rC(this.resource,async()=>{let e=this.resource.supportedFirstFactors?.find(e=>"reset_password_email_code"===e.strategy);if(!e)throw new S("Reset password email code factor not found",{code:"factor_not_found"});let{emailAddressId:a}=e;await this.resource.__internal_basePost({body:{emailAddressId:a,strategy:"reset_password_email_code"},action:"prepare_first_factor"})})}async verifyResetPasswordEmailCode(e){let{code:a}=e;return rC(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"reset_password_email_code"},action:"attempt_first_factor"})})}async submitResetPassword(e){let{password:a,signOutOfOtherSessions:t=!0}=e;return rC(this.resource,async()=>{await this.resource.__internal_basePost({body:{password:a,signOutOfOtherSessions:t},action:"reset_password"})})}async _create(e){let a=am();await this.resource.__internal_basePost({path:this.resource.pathRoot,body:a?{locale:a,...e}:e})}async create(e){return rC(this.resource,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 rC(this.resource,async()=>{let a=e.identifier||e.emailAddress||e.phoneNumber,t=this.resource.identifier,r=am();await this.resource.__internal_basePost({path:this.resource.pathRoot,body:{identifier:a||t,password:e.password,...r?{locale:r}:{}}})})}async sendEmailCode(e={}){let{emailAddress:a,emailAddressId:t}=e;if(!this.resource.id&&t)throw Error("signIn.emailCode.sendCode() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.resource.id&&!a)throw Error("signIn.emailCode.sendCode() cannot be called without an emailAddress if an existing signIn does not exist.");return rC(this.resource,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"email_code",emailAddressId:t});if(!e)throw new S("Email code factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{emailAddressId:e.emailAddressId,strategy:"email_code"},action:"prepare_first_factor"})})}async verifyEmailCode(e){let{code:a}=e;return rC(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"email_code"},action:"attempt_first_factor"})})}async sendEmailLink(e){let{emailAddress:a,verificationUrl:t,emailAddressId:r}=e;if(!this.resource.id&&r)throw Error("signIn.emailLink.sendLink() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.resource.id&&!a)throw Error("signIn.emailLink.sendLink() cannot be called without an emailAddress if an existing signIn does not exist.");return rC(this.resource,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"email_link",emailAddressId:r});if(!e)throw new S("Email link factor not found",{code:"factor_not_found"});let i=t;try{new URL(t)}catch{i=window.location.origin+t}await this.resource.__internal_basePost({body:{emailAddressId:e.emailAddressId,redirectUrl:i,strategy:"email_link"},action:"prepare_first_factor"})})}async waitForEmailLinkVerification(){return rC(this.resource,async()=>{let{run:e,stop:a}=tM();await new Promise((t,r)=>{e(async()=>{try{let e=await this.resource.__internal_baseGet(),r=e.firstFactorVerification.status;("verified"===r||"expired"===r)&&(a(),t(e))}catch(e){a(),r(e)}})})})}async sendPhoneCode(e={}){let{phoneNumber:a,phoneNumberId:t,channel:r="sms"}=e;if(!this.resource.id&&t)throw Error("signIn.phoneCode.sendCode() cannot be called with an phoneNumberId if an existing signIn does not exist.");if(!this.resource.id&&!a)throw Error("signIn.phoneCode.sendCode() cannot be called without an phoneNumber if an existing signIn does not exist.");return rC(this.resource,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"phone_code",phoneNumberId:t});if(!e)throw new S("Phone code factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{phoneNumberId:e.phoneNumberId,strategy:"phone_code",channel:r},action:"prepare_first_factor"})})}async verifyPhoneCode(e){let{code:a}=e;return rC(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"phone_code"},action:"attempt_first_factor"})})}async sso(e){let{strategy:a,redirectUrl:t,redirectCallbackUrl:r,popup:i,oidcPrompt:n,enterpriseConnectionId:s,identifier:o}=e;return rC(this.resource,async()=>{let e=t;try{new URL(t)}catch{e=window.location.origin+t}let l={redirectUrl:rP.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:e};if(i){let a=rU(rP.clerk,{redirectCallbackUrl:l.redirectUrl,redirectUrl:e});l.redirectUrl=a.redirectCallbackUrl,l.actionCompleteRedirectUrl=a.redirectUrl}await this._create({strategy:a,...l,identifier:o}),"enterprise_sso"===a&&await this.resource.__internal_basePost({body:{...l,oidcPrompt:n,enterpriseConnectionId:s,strategy:"enterprise_sso"},action:"prepare_first_factor"});let{status:c,externalVerificationRedirectURL:d}=this.resource.firstFactorVerification;"unverified"===c&&d&&(i?(await rA(rP.clerk,{popup:i,externalVerificationRedirectURL:d}),await this.resource.reload()):eW(d))})}async web3(e){let{strategy:a}=e,t=a.replace("web3_","").replace("_signature","");return rC(this.resource,async()=>{let e,r,i;switch(t){case"metamask":e=await af().getMetamaskIdentifier(),r=af().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await af().getCoinbaseWalletIdentifier(),r=af().generateSignatureWithCoinbaseWallet;break;case"base":e=await af().getBaseIdentifier(),r=af().generateSignatureWithBase;break;case"okx_wallet":e=await af().getOKXWalletIdentifier(),r=af().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${t}`)}await this._create({identifier:e});let n=this.resource.supportedFirstFactors?.find(e=>e.strategy===a);if(!n)throw new S("Web3 first factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{web3WalletId:n.web3WalletId,strategy:a},action:"prepare_first_factor"});let{message:s}=this.firstFactorVerification;if(!s)throw new S("Web3 nonce not found",{code:"web3_nonce_not_found"});try{i=await r({identifier:e,nonce:s})}catch(a){if("coinbase_wallet"===t&&4001===a.code)i=await r({identifier:e,nonce:s});else throw a}await this.resource.__internal_basePost({body:{signature:i,strategy:a},action:"attempt_first_factor"})})}async passkey(e){let{flow:a}=e||{},t=rP.clerk.__internal_isWebAuthnSupported||rd,r=rP.clerk.__internal_getPublicCredentials||tW,i=rP.clerk.__internal_isWebAuthnAutofillSupported||ru;if(!t())throw new A("Passkeys are not supported",{code:"passkey_not_supported"});return rC(this.resource,async()=>{if("autofill"===a||"discoverable"===a)await this._create({strategy:"passkey"});else{if(!this.supportedFirstFactors.find(e=>"passkey"===e.strategy))throw new S("Passkey factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{strategy:"passkey"},action:"prepare_first_factor"})}let{nonce:e}=this.firstFactorVerification,t=e?t$(JSON.parse(e)):null;if(!t)throw new S("Missing public key options",{code:"missing_public_key_options"});let n=!1;"autofill"===a&&(n=await i());let{publicKeyCredential:s,error:o}=await r({publicKeyOptions:t,conditionalUI:n});if(!s)throw new A(o.message,{code:"passkey_retrieval_failed"});await this.resource.__internal_basePost({body:{publicKeyCredential:JSON.stringify(tB(s)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return rC(this.resource,async()=>{let e=this.resource.supportedSecondFactors?.find(e=>"phone_code"===e.strategy);if(!e)throw new S("Phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:a}=e;await this.resource.__internal_basePost({body:{phoneNumberId:a,strategy:"phone_code"},action:"prepare_second_factor"})})}async verifyMFAPhoneCode(e){let{code:a}=e;return rC(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"phone_code"},action:"attempt_second_factor"})})}async verifyTOTP(e){let{code:a}=e;return rC(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"totp"},action:"attempt_second_factor"})})}async verifyBackupCode(e){let{code:a}=e;return rC(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"backup_code"},action:"attempt_second_factor"})})}async ticket(e){let a=e?.ticket??eI("__clerk_ticket");return this.create({ticket:a??void 0})}async finalize(e){let{navigate:a}=e||{};if(!this.resource.createdSessionId)throw Error("Cannot finalize sign-in without a created session.");return rC(this.resource,async()=>{rP.clerk.client&&!rP.clerk.client.sessions.some(e=>e.id===this.resource.createdSessionId)&&await rP.clerk.client.reload(),this.#el=!0,await rP.clerk.setActive({session:this.resource.createdSessionId,navigate:a})})}selectFirstFactor({strategy:e,emailAddressId:a,phoneNumberId:t}){if(!this.resource.supportedFirstFactors)return null;if(a){let t=this.resource.supportedFirstFactors.find(t=>t.strategy===e&&t.emailAddressId===a);if(t)return t}if(t){let a=this.resource.supportedFirstFactors.find(a=>a.strategy===e&&a.phoneNumberId===t);if(a)return a}let r=this.resource.supportedFirstFactors.find(a=>a.strategy===e&&a.safeIdentifier===this.resource.identifier);if(r)return r;let i=this.resource.supportedFirstFactors.find(a=>a.strategy===e);return i||null}}function rT(e){let{unsafeMetadata:a}={...e},t=a?"object"==typeof a?JSON.stringify(a):a:"";return{...e,...a?{unsafeMetadata:t}:{}}}class rE extends aM{pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new tQ(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 a=this._status;this._status=e,e&&a!==e&&e7.debug("SignUp.status",{id:this.id,from:a,to:e})}__internal_future=new rM(this);__internal_basePost=this._basePost.bind(this);__internal_basePatch=this._basePatch.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{e7.debug("SignUp.create",{id:this.id,strategy:e.strategy});let a={...e};if(!a.locale){let e=am();e&&(a.locale=e)}if(a.transfer&&this.shouldBypassCaptchaForAttempt(a)){let e=rE.clerk.client?.signIn.firstFactorVerification.strategy;e&&(a={...a,strategy:e})}return this._basePost({path:this.pathRoot,body:rT(a)})};prepareVerification=e=>(e7.debug("SignUp.prepareVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_verification"}));attemptVerification=e=>(e7.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:a}=tM();return{startEmailLinkFlow:async({redirectUrl:t})=>(this.id||aq("SignUp"),await this.prepareEmailAddressVerification({strategy:"email_link",redirectUrl:t}),new Promise((t,r)=>{e(()=>this.reload().then(e=>{let r=e.verifications.emailAddress.status;("verified"===r||"expired"===r)&&(a(),t(e))}).catch(e=>{a(),r(e)}))})),cancelEmailLinkFlow:a}};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:a,strategy:t="web3_metamask_signature"}=e;return this.attemptVerification({signature:a,strategy:t})};authenticateWithWeb3=async e=>{let a,{generateSignature:t,identifier:r,unsafeMetadata:i,strategy:n="web3_metamask_signature",legalAccepted:s}=e||{},o=n.replace("web3_","").replace("_signature","");"function"!=typeof t&&aA("generateSignature");let l=r||this.web3wallet;await this.create({web3Wallet:l,unsafeMetadata:i,legalAccepted:s}),await this.prepareWeb3WalletVerification({strategy:n});let{message:c}=this.verifications.web3Wallet;c||aU("SignUp");try{a=await t({identifier:r,nonce:c,provider:o})}catch(e){if("coinbase_wallet"===o&&4001===e.code)a=await t({identifier:r,nonce:c,provider:o});else throw e}return this.attemptWeb3WalletVerification({signature:a,strategy:n})};authenticateWithMetamask=async e=>{let a=await af().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:af().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let a=await af().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:af().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let a=await af().getBaseIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:af().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let a=await af().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:af().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithRedirectOrPopup=async(e,a)=>{let{redirectUrl:t,redirectUrlComplete:r,strategy:i,continueSignUp:n=!1,unsafeMetadata:s,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:d}=e,u=rE.clerk.buildUrlWithAuth(t),h=()=>{let e={strategy:i,redirectUrl:u,actionCompleteRedirectUrl:r,unsafeMetadata:s,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:d};return n&&this.id?this.update(e):this.create(e)},{verifications:m}=await h().catch(async e=>{if(O(e)&&C(e))return await rE.clerk.__unstable__environment.reload(),h();throw e}),{externalAccount:p}=m,{status:g,externalVerificationRedirectURL:b}=p;"unverified"===g&&b?a(b):aC(g,rE.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eW);authenticateWithPopup=async e=>{let{popup:a}=e||{};return a||aA("popup"),rS(rE.clerk,"signUp",this.authenticateWithRedirectOrPopup,e,e=>{a.location.href=e instanceof URL?e.toString():e})};update=e=>this._basePatch({body:rT(e)});upsert=e=>this.id?this.update(e):this.create(e);validatePassword=(e,a)=>{if(rE.clerk.__unstable__environment?.userSettings.passwordSettings)return rx(rI(),{...rE.clerk.__unstable__environment?.userSettings.passwordSettings,validatePassword:!0})(e,a)};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 tQ(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),t3.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 rE.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){if(!e.strategy)return!1;let a=rE.clerk.__unstable__environment.displayConfig.captchaOauthBypass;return!!(a.some(a=>a===e.strategy)||e.transfer&&a.some(e=>e===rE.clerk.client.signIn.firstFactorVerification.strategy))}__experimental_getEnterpriseConnections=()=>aM._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new rR(e)))}class rM{resource;verifications={sendEmailCode:this.sendEmailCode.bind(this),verifyEmailCode:this.verifyEmailCode.bind(this),sendPhoneCode:this.sendPhoneCode.bind(this),verifyPhoneCode:this.verifyPhoneCode.bind(this)};#el=!1;constructor(e){this.resource=e}get id(){return this.resource.id}get requiredFields(){return this.resource.requiredFields}get optionalFields(){return this.resource.optionalFields}get missingFields(){return this.resource.missingFields}get status(){return this.resource.status||"missing_requirements"}get username(){return this.resource.username}get firstName(){return this.resource.firstName}get lastName(){return this.resource.lastName}get emailAddress(){return this.resource.emailAddress}get phoneNumber(){return this.resource.phoneNumber}get web3Wallet(){return this.resource.web3wallet}get hasPassword(){return this.resource.hasPassword}get unsafeMetadata(){return this.resource.unsafeMetadata}get createdSessionId(){return this.resource.createdSessionId}get createdUserId(){return this.resource.createdUserId}get abandonAt(){return this.resource.abandonAt}get legalAcceptedAt(){return this.resource.legalAcceptedAt}get locale(){return this.resource.locale}get unverifiedFields(){return this.resource.unverifiedFields}get isTransferable(){return"transferable"===this.resource.verifications.externalAccount.status&&this.resource.verifications.externalAccount.error?.code==="external_account_exists"}get existingSession(){if(("failed"===this.resource.verifications.externalAccount.status||"unverified"===this.resource.verifications.externalAccount.status)&&this.resource.verifications.externalAccount.error?.code==="identifier_already_signed_in"&&this.resource.verifications.externalAccount.error?.meta?.sessionId)return{sessionId:this.resource.verifications.externalAccount.error?.meta?.sessionId}}get hasBeenFinalized(){return this.#el}async getCaptchaToken(){let e=new aT(rE.clerk),a=await e.managedOrInvisible({action:"signup"});if(!a)throw Error("Captcha challenge failed");let{captchaError:t,captchaToken:r,captchaWidgetType:i}=a;return{captchaToken:r,captchaWidgetType:i,captchaError:t}}async _create(e){let{captchaToken:a,captchaWidgetType:t,captchaError:r}=await this.getCaptchaToken(),i={transfer:e.transfer,captchaToken:a,captchaWidgetType:t,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rT(e.unsafeMetadata):void 0,locale:e.locale??am()};await this.resource.__internal_basePost({path:this.resource.pathRoot,body:i})}async create(e){return rC(this.resource,async()=>{await this._create(e)})}async update(e){return rC(this.resource,async()=>{let a={...e,unsafeMetadata:e.unsafeMetadata?rT(e.unsafeMetadata):void 0};await this.resource.__internal_basePatch({path:this.resource.pathRoot,body:a})})}async password(e){return rC(this.resource,async()=>{let{captchaToken:a,captchaWidgetType:t,captchaError:r}=await this.getCaptchaToken(),i={strategy:"password",captchaToken:a,captchaWidgetType:t,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rT(e.unsafeMetadata):void 0};await this.resource.__internal_basePost({path:this.resource.pathRoot,body:i})})}async sendEmailCode(){return rC(this.resource,async()=>{await this.resource.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification"})})}async verifyEmailCode(e){let{code:a}=e;return rC(this.resource,async()=>{await this.resource.__internal_basePost({body:{strategy:"email_code",code:a},action:"attempt_verification"})})}async sendPhoneCode(e){let{phoneNumber:a,channel:t="sms"}=e;return rC(this.resource,async()=>{if(!this.resource.id){let{captchaToken:e,captchaWidgetType:t,captchaError:r}=await this.getCaptchaToken();await this.resource.__internal_basePost({path:this.resource.pathRoot,body:{phoneNumber:a,captchaToken:e,captchaWidgetType:t,captchaError:r}})}await this.resource.__internal_basePost({body:{strategy:"phone_code",channel:t},action:"prepare_verification"})})}async verifyPhoneCode(e){let{code:a}=e;return rC(this.resource,async()=>{await this.resource.__internal_basePost({body:{strategy:"phone_code",code:a},action:"attempt_verification"})})}async sso(e){let{strategy:a,redirectUrl:t,redirectCallbackUrl:r,unsafeMetadata:i,legalAccepted:n,oidcPrompt:s,enterpriseConnectionId:o,emailAddress:l,popup:c}=e;return rC(this.resource,async()=>{let{captchaToken:e,captchaWidgetType:d,captchaError:u}=await this.getCaptchaToken(),h=t;try{new URL(t)}catch{h=window.location.origin+t}let m={redirectUrl:rE.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:h};if(c){let e=rU(rE.clerk,{redirectCallbackUrl:m.redirectUrl,redirectUrl:h});m.redirectUrl=e.redirectCallbackUrl,m.actionCompleteRedirectUrl=e.redirectUrl}let p=()=>this.resource.__internal_basePost({path:this.resource.pathRoot,body:{strategy:a,...m,unsafeMetadata:i,legalAccepted:n,oidcPrompt:s,enterpriseConnectionId:o,emailAddress:l,captchaToken:e,captchaWidgetType:d,captchaError:u}});await p().catch(async e=>{if(O(e)&&C(e))return await rE.clerk.__unstable__environment.reload(),p();throw e});let{status:g,externalVerificationRedirectURL:b}=this.resource.verifications.externalAccount;"unverified"===g&&b&&(c?(await rA(rE.clerk,{popup:c,externalVerificationRedirectURL:b}),await this.resource.reload()):eW(b))})}async web3(e){let{strategy:a,unsafeMetadata:t,legalAccepted:r}=e,i=a.replace("web3_","").replace("_signature","");return rC(this.resource,async()=>{let e,n,s;switch(i){case"metamask":e=await af().getMetamaskIdentifier(),n=af().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await af().getCoinbaseWalletIdentifier(),n=af().generateSignatureWithCoinbaseWallet;break;case"base":e=await af().getBaseIdentifier(),n=af().generateSignatureWithBase;break;case"okx_wallet":e=await af().getOKXWalletIdentifier(),n=af().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${i}`)}let o=e||this.resource.web3wallet;await this._create({web3Wallet:o,unsafeMetadata:t,legalAccepted:r}),await this.resource.__internal_basePost({body:{strategy:a},action:"prepare_verification"});let{message:l}=this.resource.verifications.web3Wallet;l||aU("SignUp");try{s=await n({identifier:e,nonce:l})}catch(a){if("coinbase_wallet"===i&&4001===a.code)s=await n({identifier:e,nonce:l});else throw a}await this.resource.__internal_basePost({body:{signature:s,strategy:a},action:"attempt_verification"})})}async ticket(e){let a=e?.ticket??eI("__clerk_ticket");return this.create({...e,ticket:a??void 0})}async finalize(e){let{navigate:a}=e||{};return rC(this.resource,async()=>{if(!this.resource.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#el=!0,await rE.clerk.setActive({session:this.resource.createdSessionId,navigate:a})})}}class rR extends aM{id;name;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name),this}}class rF extends aM{pathRoot="tokens";jwt;static async create(e,a={},t=!1){return new rF(await aM._fetch({body:a,method:"POST",path:e,search:t?"debug=skip_cache":void 0}),e)}constructor(e,a){super(),a&&(this.pathRoot=a),e?.jwt&&(this.jwt=ah(e.jwt))}getRawString=()=>this.jwt?.claims.__raw||"";fromJSON(e){return e&&(this.jwt=ah(e.jwt)),this}__internal_toSnapshot(){return{object:"token",id:this.id||"",jwt:this.getRawString()}}}class rD extends aM{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=aR(e.updated_at),this.createdAt=aR(e.created_at)),this}}class rN extends aM{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=aR(e.updated_at),this.createdAt=aR(e.created_at)),this}}class rW extends aM{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 rW}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case tR:return this.primaryEmailAddressId===e.id;case rp:return this.primaryPhoneNumberId===e.id;case rV:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:a}=e||{};return new tR({email_address:a},this.path()+"/email_addresses/").create()};createPasskey=()=>rm.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:a}=e||{};return new rp({phone_number:a},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:a}=e||{};return new rV({web3_wallet:a},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:a,redirectUrl:t,additionalScopes:r}=e||{};return new t6((await aM._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:a,redirect_url:t,additional_scope:r}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new rD((await aM._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new rD((await aM._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new tI((await aM._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new rN((await aM._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);update=e=>this._basePatch({body:rT(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=>(t3.emit(t2,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await r_.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:a}=e||{};return null===a?ra.delete(`${this.path()}/profile_image`):ra.create(`${this.path()}/profile_image`,{file:a})};getOrganizationInvitations=e=>r$.retrieve(e);getOrganizationSuggestions=e=>rc.retrieve(e);getOrganizationMemberships=e=>rl.retrieve(e);leaveOrganization=async e=>new tI((await aM._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);initializePaymentMethod=e=>tm(e);addPaymentMethod=e=>tp(e);getPaymentMethods=e=>tg(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:a,name:t})=>t||[e,a].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 tR(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 rp(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 rV(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 t6(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new rm(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new rl(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new tX(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=aR(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=aR(e.legal_accepted_at)),this.updatedAt=aR(e.updated_at||void 0),this.createdAt=aR(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 rL{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 r$ extends aM{id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await aM._fetch({path:"/me/organization_invitations",method:"GET",search:a4(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new r$(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=aR(e.created_at),this.updatedAt=aR(e.updated_at)),this}}let rK={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 rB extends aM{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:{...rK,name:"phone_number"},username:{...rK,name:"username"},web3_wallet:{...rK,name:"web3_wallet"},first_name:{...rK,name:"first_name"},last_name:{...rK,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:{...rK,name:"authenticator_app"},backup_code:{...rK,name:"backup_code"},passkey:{...rK,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,a])=>a.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,a])=>a.used_for_first_factor&&e.startsWith("web3")).map(([,e])=>e.first_factors).flat():[]}get alternativePhoneCodeChannels(){return this.attributes?Object.entries(this.attributes).filter(([e,a])=>a.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 rJ extends aM{pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=aR(e.updated_at),this.createdAt=aR(e.created_at)),this}static async join(e){return new rJ((await aM._fetch({path:"/waitlist",method:"POST",body:e}))?.response)}}class rV extends aM{id;web3Wallet="";verification;constructor(e,a){super(),this.pathRoot=a,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:a}=e;return this._basePost({action:"attempt_verification",body:{signature:a}})};destroy(){return this._baseDelete()}toString(){return this.web3Wallet}fromJSON(e){return e&&(this.id=e.id,this.web3Wallet=e.web3_wallet,this.verification=new tG(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}function rG(e,a){var t,r;return e.id!==a.id||e.updatedAt.getTime()<a.updatedAt.getTime()||(t=a,r=e,t.organizationMemberships.length!==r.organizationMemberships.length||t.organizationMemberships[0]?.updatedAt!==r.organizationMemberships[0]?.updatedAt)}function rH(e,a){return!function(e,a){if(!e&&a||e&&!a)return!0;if(!e&&e===a)return!1;if(!e||!a)return!0;try{if(tA.isClientResource(e))return e.id!==a.id||e.updatedAt.getTime()<a.updatedAt.getTime()||e.sessions.length!==a.sessions.length;if(rz.isSessionResource(e)){var t,r;return e.id!==a.id||e.updatedAt.getTime()<a.updatedAt.getTime()||e.lastActiveToken?.jwt?.claims?.__raw!==a.lastActiveToken?.jwt?.claims?.__raw||function(e,a){if(e.lastActiveOrganizationId!==a.lastActiveOrganizationId)return!0;let t=e.user?.organizationMemberships?.find(a=>a.organization.id===e.lastActiveOrganizationId),r=a.user?.organizationMemberships?.find(a=>a.organization.id===e.lastActiveOrganizationId);return t?.permissions?.length!==r?.permissions?.length}(e,a)||(t=e,r=a,!!t.user!=!!r.user||!!t.user&&!!r.user&&rG(t.user,r.user))}if(rW.isUserResource(e))return rG(e,a)}catch{}return!0}(e,a)?e:a}let rQ="__clerk_db_jwt";function rY(e,a){let t=new URL(e),r=t.searchParams.get(rQ);t.searchParams.delete(rQ);let i=r||a;return i&&t.searchParams.set(rQ,i),t}let rX=e=>{let a=new URL(e);return a.searchParams.delete(rQ),a},rZ=e=>{let a=new URL(e);return a.searchParams.delete("__dev_session"),a.hash=decodeURI(a.hash).replace(/__clerk_db_jwt\[(.*)\]/,""),a.href.endsWith("#")&&(a.hash=""),a};function r1(e){for(var a=1;a<arguments.length;a++){var t=arguments[a];for(var r in t)e[r]=t[r]}return e}var r2=function e(a,t){function r(e,r,i){if("undefined"!=typeof document){"number"==typeof(i=r1({},t,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var n="";for(var s in i)i[s]&&(n+="; "+s,!0!==i[s]&&(n+="="+i[s].split(";")[0]));return document.cookie=e+"="+a.write(r,e)+n}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var t=document.cookie?document.cookie.split("; "):[],r={},i=0;i<t.length;i++){var n=t[i].split("="),s=n.slice(1).join("=");try{var o=decodeURIComponent(n[0]);if(r[o]=a.read(s,o),e===o)break}catch(e){}}return e?r[e]:r}},remove:function(e,a){r(e,"",r1({},a,{expires:-1}))},withAttributes:function(a){return e(this.converter,r1({},this.attributes,a))},withConverter:function(a){return e(r1({},this.converter,a),this.attributes)}},{attributes:{value:Object.freeze(t)},converter:{value:Object.freeze(a)}})}({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 r0(e){return{get:()=>r2.get(e),set(a,t={}){r2.set(e,a,t)},remove(a){r2.remove(e,a)}}}let r9=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function r3(e,a){let t=function(e){try{return new Date(e||new Date)}catch{return new Date}}(e);return t.setFullYear(t.getFullYear()+a),t}let r8=r0("__clerk_test_etld"),r5="__client_uat",r4="__session",r6=()=>{let e=ag()?"None":"Lax",a=r9(e);return{sameSite:e,secure:a,partitioned:!1}};async function r7(e){let a;try{a=await eh(e)}catch(o){var t;t=`Suffixed cookie failed due to ${o.message} (secure-context: ${window.isSecureContext}, url: ${window.location.href})`,V.has(t)||(console.log(t),V.add(t));let{default:r}=await Promise.resolve().then(i.t.bind(i,180,23)),{default:n}=await Promise.resolve().then(i.t.bind(i,413,23)),s=r(e);a=n.stringify(s).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}return a}let ie=()=>{let e=ag()?"None":"Lax",a=r9(e);return{sameSite:e,secure:a}};var ia=i(945),it=i.n(ia);class ir{lock=(function(e){let a=new(it());return window.addEventListener("beforeunload",async()=>{await a.releaseLock(e)}),{acquireLockAndRun:async t=>{if("locks"in navigator&&isSecureContext){let a=new AbortController,r=setTimeout(()=>a.abort(),4999);return await navigator.locks.request(e,{signal:a.signal},async()=>(clearTimeout(r),await t())).catch(()=>!1)}if(await a.acquireLock(e,5e3))try{return await t()}finally{await a.releaseLock(e)}}}})("clerk.lock.refreshSessionToken");workerTimers=tE();timerId=null;initiated=!1;startPollingForSessionToken(e){if(this.timerId||this.initiated)return;let a=async()=>{this.initiated=!0,await this.lock.acquireLockAndRun(e),this.timerId=this.workerTimers.setTimeout(a,5e3)};a()}stopPollingForSessionToken(){null!=this.timerId&&(this.workerTimers.clearTimeout(this.timerId),this.timerId=null),this.initiated=!1}}class ii{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,a,t,r){let i=await r7(e.publishableKey),n=new ii(e,a,i,t,r);return await n.setup(),n}constructor(e,a,r,i,n){this.clerk=e,this.instanceType=i,this.clerkEventBus=n,t3.on(t1,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),t3.on(t2,()=>this.handleSignOut()),this.refreshTokenOnFocus(),this.startPollingForToken(),this.clientUat=(e=>{let a=r0(r5),r=r0(em(r5,e));return{set:e=>{let i=r3(Date.now(),1),n=ag()?"None":"Strict",s=r9(n),o=function(e=window.location.hostname,a=r8){if(t)return t;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 i=r.slice(e).join(".");if(a.set("1",{domain:i}),"1"===a.get())return a.remove({domain:i}),t=i,i;a.remove({domain:i})}}(),l="0";e&&e.updatedAt&&e.signedInSessions.length>0&&(l=Math.floor(e.updatedAt.getTime()/1e3).toString()),r.remove(),a.remove(),r.set(l,{domain:o,expires:i,partitioned:!1,sameSite:n,secure:s}),a.set(l,{domain:o,expires:i,partitioned:!1,sameSite:n,secure:s})},get:()=>parseInt(r.get()||a.get()||"0",10)}})(r),this.sessionCookie=(e=>{let a=r0(r4),t=r0(em(r4,e)),r=()=>{let e=r6();a.remove(e),t.remove(e)};return{set:e=>{let i=r3(Date.now(),1),{sameSite:n,secure:s,partitioned:o}=r6();o&&r(),a.set(e,{expires:i,sameSite:n,secure:s,partitioned:o}),t.set(e,{expires:i,sameSite:n,secure:s,partitioned:o})},remove:r,get:()=>t.get()||a.get()}})(r),this.activeCookie=(()=>{let e=r0("clerk_active_context"),a={secure:r9("None")};return{set:t=>{e.set(t,a)},get:()=>e.get(),remove:()=>e.remove(a)}})(),this.devBrowser=function({cookieSuffix:e,frontendApi:a,fapiClient:t}){let r,i,n=(r=r0(rQ),i=r0(em(rQ,e)),{get:()=>i.get()||r.get(),set:e=>{let a=r3(Date.now(),1),{sameSite:t,secure:n}=ie();i.set(e,{expires:a,sameSite:t,secure:n}),r.set(e,{expires:a,sameSite:t,secure:n})},remove:()=>{let e=ie();i.remove(e),r.remove(e)}});function s(){return n.get()}function o(e){n.set(e)}function l(){n.remove()}return{clear:function(){l()},setup:async function(){var e;let r;if(!ey(a))return;t.onBeforeRequest(e=>{let a=s();a&&e?.url&&(e.url=rY(e.url,a))}),t.onAfterResponse((e,a)=>{let t=a?.headers?.get("Clerk-Db-Jwt");t&&o(t)});let i=(r=(e=new URL(window.location.href)).searchParams.get(rQ)||"",rX(rZ(e)).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",rX(rZ(e))),r);if(i)return void o(i);if(n.get())return;let l=t.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 k(e)):[]}((await c.json()).errors);e[0]?a_(e[0].longMessage):a_()}let d=await c.json();o(d?.id)},getDevBrowserJWT:s,setDevBrowserJWT:o,removeDevBrowserJWT:l}}({frontendApi:e.frontendApi,fapiClient:a,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 a=this.devBrowser.getDevBrowserJWT();if(!a)throw Error(`${aj} Missing dev browser jwt. Please contact support.`);return rY(e,a)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new ir,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 a=await this.clerk.session.getToken();e&&this.updateSessionCookie(a)}catch(e){return this.handleGetTokenError(e)}}updateSessionCookie(e){if(document.hasFocus()||this.isCurrentContextActive())return e||d()||e7.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(O(e)||T(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(I(e))return void this.clerk.handleUnauthenticated().catch(e0);this.clerkEventBus.emit(g,"degraded")}}handleSignOut(){this.activeCookie.remove(),this.sessionCookie.remove(),this.setClientUatCookieForDevelopmentInstances()}setActiveContextInStorage(){let e=this.clerk.session?.id||"",a=this.clerk.organization?.id||"",t=`${e}:${a}`;":"!==t?this.activeCookie.set(t):this.activeCookie.remove()}isCurrentContextActive(){let e=this.activeCookie.get();if(!e)return!0;let[a,t]=e.split(":"),r=this.clerk.session?.id||"",i=this.clerk.organization?.id||"";return a===r&&t===i}getSessionCookie(){return this.sessionCookie.get()}}class is{clerk;captchaChallenge;timers;constructor(e,a=new aT(e),t=tE()){this.clerk=e,this.captchaChallenge=a,this.timers=t}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.__unstable__environment?.displayConfig?.captchaHeartbeat}clientBypass(){return this.clerk.client?.captchaBypass}intervalInMs(){return this.clerk.__unstable__environment?.displayConfig?.captchaHeartbeatIntervalMs??6e5}}let io=["/client","/waitlist"];class il{async getBaseFapiProxyOptions(){let e=await aM.clerk.session?.getToken();if(!e)throw new S("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 aM._fetch({...await this.getBaseFapiProxyOptions(),method:"GET",path:"/api_keys",search:a4({...e,subject:e?.subject??aM.clerk.organization?.id??aM.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new aF(e))}})}async create(e){return new aF(await aM._fetch({...await this.getBaseFapiProxyOptions(),path:"/api_keys",method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??aM.clerk.organization?.id??aM.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new aF(await aM._fetch({...await this.getBaseFapiProxyOptions(),method:"POST",path:`/api_keys/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let ic=new Map;class id{#ec=!1;load(e){let a=e?.protectConfig;if(a?.loaders&&Array.isArray(a.loaders)&&0!==a.loaders.length&&!this.#ec){if(s())for(let e of(this.#ec=!0,a.loaders))try{this.applyLoader(e)}catch(e){G(`[protect] failed to apply loader: ${e}`)}}}applyLoader(e){if(void 0!==e.rollout){let a=e.rollout;if("number"!=typeof a||a<0)return void G(`[protect] loader rollout value is invalid: ${a}`);if(0===a||Math.random()>a)return}let a=e.type||"script",t=e.target||"body",r=document.createElement(a);if(e.attributes)for(let[a,t]of Object.entries(e.attributes))switch(typeof t){case"string":case"number":case"boolean":r.setAttribute(a,String(t));break;default:G(`[protect] loader attribute is invalid type: ${a}=${t}`)}switch(e.textContent&&"string"==typeof e.textContent&&(r.textContent=e.textContent),t){case"head":document.head.appendChild(r);break;case"body":document.body.appendChild(r);break;default:if(t?.startsWith("#")){let e=document.getElementById(t.substring(1));if(!e)return void G(`[protect] loader target element not found: ${t}`);e.appendChild(r);return}G(`[protect] loader target is invalid: ${t}`)}}}class iu{signInResourceSignal=a7;signInErrorSignal=te;signInFetchSignal=ta;signInSignal=tt;signUpResourceSignal=tr;signUpErrorSignal=ti;signUpFetchSignal=tn;signUpSignal=ts;__internal_effect=a1;__internal_computed=aZ;constructor(){t3.on("resource:update",this.onResourceUpdated),t3.on("resource:error",this.onResourceError),t3.on("resource:fetch",this.onResourceFetch)}onResourceError=e=>{e.resource instanceof rP&&this.signInErrorSignal({error:e.error}),e.resource instanceof rE&&this.signUpErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof rP){if(ih(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof rE){if(ih(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}};onResourceFetch=e=>{e.resource instanceof rP&&this.signInFetchSignal({status:e.status}),e.resource instanceof rE&&this.signUpFetchSignal({status:e.status})}}function ih(e,a){return!a?.id&&e&&e.__internal_future?.hasBeenFinalized===!1}let im="cannot_render_billing_disabled",ip="cannot_render_user_missing",ig="cannot_render_organizations_disabled",ib="cannot_render_organization_missing",iy="cannot_render_single_session_enabled",ik={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 iw{static version="6.0.0-canary-core3.v20251203181537";static sdkMetadata={name:"@clerk/clerk-js",version:"6.0.0-canary-core3.v20251203181537"};static _billing;static _apiKeys;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new iu;internal_last_error=null;environment;#ed;#eu="";#eh;#em;#ep;#eg;#eb;#ef=null;#ey;#ek;#ew;#ev="loading";#ej=[];#ez=[];#e_={};#ex=null;#eq=0;#eS=p();get __internal_queryClient(){return this.#ed||Promise.resolve().then(i.bind(i,303)).then(e=>e.QueryClient).then(e=>{this.#ed||(this.#ed=new e,this.#eS.emit("queryClientStatus","ready"))}),this.#ed?{__tag:"clerk-rq-client",client:this.#ed}:void 0}__internal_getCachedResources;__internal_createPublicCredentials;__internal_getPublicCredentials;__internal_isWebAuthnSupported;__internal_isWebAuthnAutofillSupported;__internal_isWebAuthnPlatformAuthenticatorSupported;__internal_setActiveInProgress=!1;get publishableKey(){return this.#eu}get version(){return iw.version}set sdkMetadata(e){iw.sdkMetadata=e}get sdkMetadata(){return iw.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#ev}get isSatellite(){return!!ap()&&e2(this.#e_.isSatellite,new URL(window.location.href),!1)}get domain(){if(ap()){let e=function(e=""){return(e||"").replace(/^.+:\/\//,"")}(e2(this.#eh,new URL(window.location.href)));if("production"===this.#ew){let a;if(!e)return"";if(e.match(/^(clerk\.)+\w*$/))a=/(clerk\.)*(?=clerk\.)/;else{if(e.match(/\.clerk.accounts/))return e;a=/^(clerk\.)*/gi}return`clerk.${e.replace(a,"")}`}return e}return""}get proxyUrl(){if(ap()){let e=e2(this.#em,new URL(window.location.href));return!e||eL(e)||e$(e)||ad.throwInvalidProxyUrl({url:e}),e?e$(e)?new URL(e,window.location.origin).toString():e:""}return""}get frontendApi(){let e=ed(this.publishableKey);return e?e.frontendApi:ad.throwInvalidPublishableKeyError({key:this.publishableKey})}get instanceType(){return this.#ew}get isStandardBrowser(){return this.#e_.standardBrowser||!1}get billing(){return iw._billing||(iw._billing=new a6),iw._billing}get apiKeys(){return iw._apiKeys||(iw._apiKeys=new il),iw._apiKeys}__experimental_checkout(e){return this._checkout||(this._checkout=e=>(function(e,a){let t,r,i,n,{for:s,planId:o,planPeriod:l}=a;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:a,orgId:t,planId:r,planPeriod:i}=e;return`${a}-${t||"user"}-${r}-${i}`}({userId:e.user?.id||"",orgId:"organization"===s?e.organization?.id:void 0,planId:o,planPeriod:l}),d=ic.get(c);if(d)return d.signals.computedSignal();let u=(t=aX({resource:null}),r=aX({error:null}),i=aX({status:"idle"}),n=aZ(()=>{let e=t().resource,a=r().error,n=i().status;return{errors:to(a,{}),fetchStatus:n,checkout:e}}),{resourceSignal:t,errorSignal:r,fetchSignal:i,computedSignal:n}),h=new td(u,{..."organization"===s?{orgId:e.organization?.id}:{},planId:o,planPeriod:l});return ic.set(c,{resource:h,signals:u}),u.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#e_[e]}get isSignedIn(){return this?.session?.status!=="pending"&&!!this.session}constructor(e,a){if(!(e=(e||"").trim()))return ad.throwMissingPublishableKeyError();const t=ed(e);if(!t)return ad.throwInvalidPublishableKeyError({key:e});this.#eh=a?.domain,this.#em=a?.proxyUrl,this.environment=t4.getInstance(),this.#ew=t.instanceType,this.#eu=e,this.#ek=function(e){let a=[],t=[];async function r(e){for await(let t of["undefined"!=typeof window&&window.__unstable__onBeforeRequest,...a].filter(e=>e))if(await t(e)===!1)return!1;return!0}async function i(e,a){for await(let r of["undefined"!=typeof window&&window.__unstable__onAfterResponse,...t].filter(e=>e))if(await r(e,a)===!1)return!1;return!0}function n({method:a,path:t,sessionId:r,search:i,rotatingTokenNonce:n}){let s=new URLSearchParams(i);return s.append("__clerk_api_version","2025-11-10"),s.append("_clerk_js_version","6.0.0-canary-core3.v20251203181537"),n&&s.append("rotating_token_nonce",n),e.domain&&"development"===e.instanceType&&e.isSatellite&&s.append("__domain",e.domain),a&&"GET"!==a&&"POST"!==a&&s.append("_method",a),t&&!io.some(e=>t.startsWith(e))&&r&&s.append("_clerk_session_id",r),eg([...s.entries()].reduce((e,[a,t])=>(e[a]=t.includes(",")?t.split(","):t,e),{}))}function s(a){let{path:t,pathPrefix:r="v1"}=a;if(e.proxyUrl){let i=new URL(e.proxyUrl),s=i.pathname.slice(1);return s.endsWith("/")&&(s=s.slice(0,-1)),ev({base:i.origin,pathname:`${s}/${r}${t}`,search:n(a)},{stringify:!1})}let i="production"===e.instanceType?e.domain:"";return ev({base:`https://${i||e.frontendApi}`,pathname:`${r}${t}`,search:n(a)},{stringify:!1})}async function o(a,t){let n,o={...a},{method:l="GET",body:d}=o;!d||"object"!=typeof d||d instanceof FormData||(o.body=function(e){if(!e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype)return e;let a={};for(let[t,r]of Object.entries(e))void 0!==r&&(a[t]=r);return a}(d)),o.url=s({...o,sessionId:e.getSessionId()}),o.headers=new Headers(o.headers),"GET"===l||d 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=d?eg(d,{keyEncoder:X}):d);let u=await r(o),h="GET"===l?"GET":"POST",m=o.url,p={...o,method:h,credentials:o.credentials||"include"};try{if(u){let e=t?.fetchMaxTries??(c()?4:11);n=await ar(()=>fetch(m,p),{retryImmediately:!0,initialDelay:700,maxDelayBetweenRetries:5e3,shouldRetry:(a,t)=>"GET"===h&&t<e,onBeforeRetry:e=>{m.searchParams.set("_clerk_retry_attempt",e.toString())}})}else n=new Response("{}",o)}catch(a){let e=m.toString();e7.error("network error",{error:a,url:e,method:l},"fapiClient");throw Error(`${aj} Network error at "${e}" - ${a}. Please try again.`)}let g=204!==n.status?await n.json():null,b=Object.assign(n,{payload:g});return n.ok||e7.error("request failed",{method:l,path:o.path,status:n.status},"fapiClient"),await i(o,b),b}return{buildEmailAddress:function(a){return function({localPart:e,frontendApi:a}){return`${e}@${a?a.replace("clerk.",""):"clerk.com"}`}({localPart:a,frontendApi:e.frontendApi})},buildUrl:s,onAfterResponse:function(e){t.push(e)},onBeforeRequest:function(e){a.push(e)},request:o}}({domain:this.domain,frontendApi:this.frontendApi,instanceType:this.instanceType,isSatellite:this.isSatellite,getSessionId:()=>this.session?.id,proxyUrl:this.proxyUrl}),this.#eS.emit(g,"loading"),this.#eS.prioritizedOn(g,e=>this.#ev=e),aM.clerk=this,this.#eg=new id}getFapiClient=()=>this.#ek;load=async e=>{if(e7.info("load() start",{},"clerk"),!this.loaded){if("development"===this.#ew&&G("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.#e_=this.#eU(e),this.#e_.clerkUiCtor&&(this.#ey=Promise.resolve(this.#e_.clerkUiCtor).then(e=>new e(()=>this,()=>this.environment,this.#e_,new an))),"development"===this.#ew&&(this.#e_.routerPush||this.#e_.routerReplace)&&(!this.#e_.routerPush||!this.#e_.routerReplace)){let e=this.#e_.routerPush?"routerReplace":"routerPush";G(`Clerk: Both \`routerPush\` and \`routerReplace\` need to be defined, but \`${e}\` is not defined. This may cause issues with navigation in your application.`)}t3.on(t9,()=>{this.#eA(this.session),this.#eC()}),this.#e_.sdkMetadata&&(iw.sdkMetadata=this.#e_.sdkMetadata),!1!==this.#e_.telemetry&&(this.telemetry=new eG({clerkVersion:iw.version,samplingRate:1,perEventSampling:!this.#e_.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#e_.telemetry}),this.#e_.appearance&&this.telemetry.record({event:"THEME_USAGE",eventSamplingRate:1,payload:function(e){let a;if(!e||"object"!=typeof e)return{};let t=e.theme||e.baseTheme;if(!t)return{};if(Array.isArray(t))for(let e of t){let t=e1(e);if(t){a=t;break}}else a=e1(t);return{themeName:a}}(this.#e_.appearance)}));try{this.#e_.standardBrowser?await this.#eI():await this.#eP();let e=this.#e_.telemetry,a=!1!==e&&!e?.disabled,t=!!this.#e_.__internal_keyless_claimKeylessApplicationUrl,r=!!this.environment?.clientDebugMode,i=this.environment?.isProduction?.()??!1,n=r||t&&!i,s=t&&!r?"error":void 0;n&&function(e={}){if(e8)return;let{enabled:a=!1,...t}=e;a&&(e9=!0,e8=!0,e6(t))}({enabled:!0,...s?{logLevel:s}:{},...a&&this.telemetry?{telemetryCollector:this.telemetry}:{}}),this.#eg?.load(this.environment),e7.info("load() complete",{},"clerk")}catch(e){throw this.#eS.emit(g,"error"),e7.error("load() failed",{error:e},"clerk"),e}}};#eO(){let e;return!!(!this.#e_.signUpUrl&&this.#e_.signInUrl&&(e=this.#e_.signInUrl,!ep.test(e)))}signOut=async(e,a)=>{if(!this.client||0===this.client.sessions.length)return;let t="undefined"!=typeof window&&"function"==typeof window.__unstable__onBeforeSetActive?window.__unstable__onBeforeSetActive:e0,r="undefined"!=typeof window&&"function"==typeof window.__unstable__onAfterSetActive?window.__unstable__onAfterSetActive:e0,i=e&&"object"==typeof e?e:a||{},n=i?.redirectUrl||this.buildAfterSignOutUrl();e7.debug("signOut() start",{hasClient:!!this.client,multiSessionCount:this.client?.signedInSessions.length??0,redirectUrl:n,sessionTarget:i?.sessionId??null},"clerk");let s="function"==typeof e?e:void 0,o=async()=>{let e=as(this.#e_.standardBrowser);t3.emit(t2,null),this.#eT(),await e.track(async()=>{s?await s():await this.navigate(n)}),e.isUnloading()||(this.#eA(),this.#eC(),await r())};if(await t(),!i.sessionId||1===this.client.signedInSessions.length){this.#e_.experimental?.persistClient??!0?await this.client.removeSessions():await this.client.destroy(),await o(),e7.info("signOut() complete",{redirectUrl:ej(n)},"clerk");return}let l=this.client.signedInSessions.find(e=>e.id===i.sessionId),c=l?.id&&this.session?.id===l.id;await l?.remove(),c&&(await o(),e7.info("signOut() complete",{redirectUrl:ej(n)},"clerk"))};openGoogleOneTap=e=>{this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("googleOneTap",e||{})),this.telemetry?.record(eZ("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(D(this,this.environment)){if("development"===this.#ew)throw new S(eF.cannotOpenSignInOrSignUp,{code:iy});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("signIn",e||{}));let a={withSignUp:e?.withSignUp??this.#eO()};this.telemetry?.record(eZ("SignIn",e,a))};closeSignIn=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(N(this,this.environment)){if("development"===this.#ew)throw new S(eF.cannotRenderAnyBillingComponent("Checkout"),{code:im});return}if(!this.user){if("development"===this.#ew)throw new S(eF.cannotOpenCheckout,{code:ip});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openDrawer("checkout",e||{}))};__internal_closeCheckout=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("checkout"))};__internal_openPlanDetails=e=>{if(N(this,this.environment)){if("development"===this.#ew)throw new S(eF.cannotRenderAnyBillingComponent("PlanDetails"),{code:im});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openDrawer("planDetails",e||{})),this.telemetry?.record(eZ("PlanDetails",e))};__internal_closePlanDetails=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("planDetails"))};__internal_openSubscriptionDetails=e=>{this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openDrawer("subscriptionDetails",e||{}))};__internal_closeSubscriptionDetails=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("subscriptionDetails"))};__internal_openReverification=e=>{if(!this.user){if("development"===this.#ew)throw new S(eF.cannotOpenUserProfile,{code:ip});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("userVerification",e||{})),this.telemetry?.record(eZ("UserVerification",e))};__internal_closeReverification=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userVerification"))};__internal_attemptToEnableEnvironmentSetting=e=>{let{for:a,caller:t}=e;if(this.user||"development"!==this.#ew||G(`Clerk: "${t}" requires an active user session. Ensure a user is signed in before executing ${t}.`),"organizations"===a){let a;return(a=this.environment,a?.organizationSettings.enabled||this.session?.currentTask?.key==="choose-organization")?{isEnabled:!0}:("development"===this.#ew&&this.__internal_openEnableOrganizationsPrompt({caller:t,onSuccess:()=>window.location.reload(),onClose:e.onClose}),{isEnabled:!1})}throw Error(`Attempted to enable an unknown or unsupported setting "${a}".`)};__internal_openEnableOrganizationsPrompt=e=>(this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("enableOrganizationsPrompt",e||{})));__internal_closeEnableOrganizationsPrompt=()=>(this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(e=>e.closeModal("enableOrganizationsPrompt")));__internal_openBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(e=>e.openModal("blankCaptcha",{})));__internal_closeBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(e=>e.closeModal("blankCaptcha")));__internal_loadStripeJs=async()=>(az("Stripe"),{loadStripe:()=>Promise.resolve(null)});openSignUp=e=>{if(D(this,this.environment)){if("development"===this.#ew)throw new S(eF.cannotOpenSignInOrSignUp,{code:iy});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("signUp",e||{})),this.telemetry?.record(eZ("SignUp",e))};closeSignUp=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signUp"))};openUserProfile=e=>{if(!this.user){if("development"===this.#ew)throw new S(eF.cannotOpenUserProfile,{code:ip});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("userProfile",e||{}));let a=(e?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(eZ("UserProfile",e,a))};closeUserProfile=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userProfile"))};openOrganizationProfile=e=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new S(eF.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:ig})}});if(a){if(!this.organization){if("development"===this.#ew)throw new S(eF.cannotRenderComponentWhenOrgDoesNotExist,{code:ib});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("organizationProfile",e||{})),this.telemetry?.record(eZ("OrganizationProfile",e))}};closeOrganizationProfile=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("organizationProfile"))};openCreateOrganization=e=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new S(eF.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:ig})}});a&&(this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("createOrganization",e||{})),this.telemetry?.record(eZ("CreateOrganization",e)))};closeCreateOrganization=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("createOrganization"))};openWaitlist=e=>{this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("waitlist",e||{})),this.telemetry?.record(eZ("Waitlist",e))};closeWaitlist=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("waitlist"))};mountSignIn=(e,a)=>{this.assertComponentsReady(this.#ey);let t="SignIn";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"signIn",node:e,props:a}));let r={withSignUp:a?.withSignUp??this.#eO()};this.telemetry?.record(eX(t,a,r))};unmountSignIn=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserAvatar=(e,a)=>{this.assertComponentsReady(this.#ey);let t="UserAvatar";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"userAvatar",node:e,props:a})),this.telemetry?.record(eX(t,a))};unmountUserAvatar=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountSignUp=(e,a)=>{this.assertComponentsReady(this.#ey);let t="SignUp";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"signUp",node:e,props:a})),this.telemetry?.record(eX(t,a))};unmountSignUp=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserProfile=(e,a)=>{if(!this.user){if("development"===this.#ew)throw new S(eF.cannotRenderComponentWhenUserDoesNotExist,{code:ip});return}this.assertComponentsReady(this.#ey);let t="UserProfile";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"userProfile",node:e,props:a}));let r=(a?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(eX(t,a,r))};unmountUserProfile=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountOrganizationProfile=(e,a)=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new S(eF.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:ig})}});if(!t)return;let r=!!this.user;if(!this.organization&&r){if("development"===this.#ew)throw new S(eF.cannotRenderComponentWhenOrgDoesNotExist,{code:ib});return}this.assertComponentsReady(this.#ey);let i="OrganizationProfile";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:i,appearanceKey:"userProfile",node:e,props:a})),this.telemetry?.record(eX(i,a))};unmountOrganizationProfile=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountCreateOrganization=(e,a)=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new S(eF.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:ig})}});if(!t)return;this.assertComponentsReady(this.#ey);let r="CreateOrganization";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"createOrganization",node:e,props:a})),this.telemetry?.record(eX(r,a))};unmountCreateOrganization=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountOrganizationSwitcher=(e,a)=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationSwitcher",onClose:()=>{throw new S(eF.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:ig})}});if(!t)return;this.assertComponentsReady(this.#ey);let r="OrganizationSwitcher";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"organizationSwitcher",node:e,props:a})),this.telemetry?.record(eX(r,{...a,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationSwitcher=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};__experimental_prefetchOrganizationSwitcher=()=>{this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(e=>e.prefetch("organizationSwitcher"))};mountOrganizationList=(e,a)=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationList",onClose:()=>{throw new S(eF.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:ig})}});if(!t)return;this.assertComponentsReady(this.#ey);let r="OrganizationList";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"organizationList",node:e,props:a})),this.telemetry?.record(eX(r,{...a,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationList=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserButton=(e,a)=>{this.assertComponentsReady(this.#ey);let t="UserButton";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"userButton",node:e,props:a}));let r={...a?.customMenuItems?.length||0?{customItems:!0}:void 0,...a?.__experimental_asStandalone?{standalone:!0}:void 0};this.telemetry?.record(eX(t,a,r))};unmountUserButton=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountWaitlist=(e,a)=>{this.assertComponentsReady(this.#ey);let t="Waitlist";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"waitlist",node:e,props:a})),this.telemetry?.record(eX(t,a))};unmountWaitlist=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountPricingTable=(e,a)=>{if(N(this,this.environment)){if("development"===this.#ew)throw new S(eF.cannotRenderAnyBillingComponent("PricingTable"),{code:im});return}this.assertComponentsReady(this.#ey);let t="PricingTable";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"pricingTable",node:e,props:a})),this.telemetry?.record(eX(t,a))};unmountPricingTable=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};__internal_mountOAuthConsent=(e,a)=>{this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:"OAuthConsent",appearanceKey:"__internal_oauthConsent",node:e,props:a}))};__internal_unmountOAuthConsent=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountAPIKeys=(e,a)=>{let t;if(G("Clerk: <APIKeys /> component is in early access and not yet recommended for production use."),W(this,t=this.environment)&&L(this,t)){if("development"===this.#ew)throw new S(eF.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&L(this,this.environment)){if("development"===this.#ew)throw new S(eF.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if(W(this,this.environment)){if("development"===this.#ew)throw new S(eF.cannotRenderAPIKeysComponentForUserWhenDisabled,{code:"cannot_render_api_keys_user_disabled"});return}this.assertComponentsReady(this.#ey);let r="APIKeys";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"apiKeys",node:e,props:a})),this.telemetry?.record(eX(r,a))};unmountAPIKeys=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountTaskChooseOrganization=(e,a)=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"TaskChooseOrganization",onClose:()=>{throw new S(eF.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:ig})}});if(!t)return;this.assertComponentsReady(this.#ey);let r="TaskChooseOrganization";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"taskChooseOrganization",node:e,props:a})),this.telemetry?.record(eX(r,a))};unmountTaskChooseOrganization=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};setActive=async e=>{let{organization:a,redirectUrl:t,navigate:r}=e,{session:i}=e;this.__internal_setActiveInProgress=!0,e7.debug("setActive() start",{hasClient:!!this.client,sessionTarget:"string"==typeof i?i:i?.id??i??null,organizationTarget:"string"==typeof a?a:a?.id??a??null,redirectUrl:t??null},"clerk");try{var n;let s;if(!this.client)throw e7.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===i&&!this.session)throw e7.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 i&&(i=this.client.sessions.find(e=>e.id===i)||null);let o="undefined"!=typeof window&&"function"==typeof window.__unstable__onBeforeSetActive?window.__unstable__onBeforeSetActive:e0,l="undefined"!=typeof window&&"function"==typeof window.__unstable__onAfterSetActive?window.__unstable__onAfterSetActive:e0,c=void 0===i?this.session:i;c?.status==="pending"&&(n={...this.#e_,...e},s=["taskUrls","navigate"],Object.keys(n).some(e=>s.includes(e))||G('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!==a;if(c&&u){let e="string"==typeof a?a:a?.id;if("string"==typeof e&&e.startsWith("org_"))c.lastActiveOrganizationId=e||null;else{let a=c.user.organizationMemberships.find(a=>a.organization.slug===e),t=a?.organization.id||null,r=null===t;if(this.environment?.organizationSettings?.forceOrganizationSelection&&r)return;c.lastActiveOrganizationId=t}}c?.status!=="pending"&&await o(null===c?"sign-out":void 0),(ap()&&globalThis.document.hasFocus()||!this.#e_.standardBrowser)&&(await this.#eE(c),c=this.#eM(c?.id)),await c?.getToken()||(d()||e7.warn("Token is null when setting active session (offline)",{sessionId:c?.id},"clerk"),t3.emit(t1,{token:null}));let h=as(this.#e_.standardBrowser),m=c?.status==="pending"&&c?.currentTask&&this.#e_.taskUrls?.[c?.currentTask.key];if((t||m||r)&&await h.track(async()=>{if(this.client){if(c?.status!=="pending"&&this.#eT(),m){let e=t?ev({base:m,hashSearchParams:{redirectUrl:t}},{stringify:!0}):m;await this.navigate(e)}else if(r&&c)await r({session:c});else if(t){if(this.client.isEligibleForTouch()){let e=new URL(t,window.location.href),a=this.buildUrlWithAuth(this.client.buildTouchUrl({redirectUrl:e}));await this.navigate(a)}await this.navigate(t)}}}),h.isUnloading())return;this.#eA(c),this.#eC(),c?.status!=="pending"&&await l()}finally{this.__internal_setActiveInProgress=!1}};addListener=e=>{var a;let t;return a=e,e=e=>{var r;t||={...e},a(t={...{client:rH((r=t).client,e.client),session:rH(r.session,e.session),user:rH(r.user,e.user),organization:rH(r.organization,e.organization)}})},this.#ej.push(e),this.client&&e({client:this.client,session:this.session,user:this.user,organization:this.organization}),()=>{this.#ej=this.#ej.filter(a=>a!==e)}};on=(...e)=>{this.#eS.on(...e)};off=(...e)=>{this.#eS.off(...e)};__internal_addNavigationListener=e=>(this.#ez.push(e),()=>{this.#ez=this.#ez.filter(a=>a!==e)});navigate=async(e,a)=>{if(!e||!ap())return;setTimeout(()=>{this.#eR()},0);let t=new URL(e,window.location.href);this.#eF.includes(t.protocol)||(console.warn(`Clerk: "${t.protocol}" is not a valid protocol. Redirecting to "/" instead. If you think this is a mistake, please open an issue.`),t=new URL("/",window.location.href));let r=a?.replace&&this.#e_.routerReplace?this.#e_.routerReplace:this.#e_.routerPush;if(e7.info(`Clerk is navigating to: ${t}`),this.#e_.routerDebug&&console.log(`Clerk is navigating to: ${t}`),"null"!==t.origin&&t.origin!==window.location.origin||!r)return void eW(t);let i={...a?.metadata?{__internal_metadata:a?.metadata}:{},windowNavigate:eW};return await r(ej(t),i)};buildUrlWithAuth(e){if("production"===this.#ew)return e;let a=new URL(e,window.location.origin);return a.origin!==window.location.origin&&this.#ep?this.#ep.decorateUrlWithDevBrowserToken(a).href:a.href}buildSignInUrl(e){return this.#eD("signInUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildSignUpUrl(e){return this.#eD("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 eU(this.#e_,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eU(this.#e_,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#e_.afterSignOutUrl?this.buildUrlWithAuth(this.#e_.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#e_.newSubscriptionRedirectUrl?this.#e_.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?ev({base:this.#e_.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#e_.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#e_.afterMultiSessionSingleSignOutUrl):this.#e_.signInUrl?this.buildUrlWithAuth(ev({base:this.#e_.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 a=this.session?.currentTask;if(!a)return"";let t=this.#e_.taskUrls?.[a.key];return t||ev({base:this.buildSignInUrl(e),hashPath:eE(a)},{stringify:!0})}#eN=async()=>{if(!ap())return;let e=new URLSearchParams({[$]:"true"}),a=eI(B);a&&eL(a)||function(){throw Error(`${aj} Invalid redirect_url. A valid http or https url should be used for the redirection.`)}();let t=ev({base:eI(B),searchParams:e},{stringify:!0});return this.navigate(this.buildUrlWithAuth(t))};redirectWithAuth=async e=>{if(ap())return this.navigate(this.buildUrlWithAuth(e))};redirectToSignIn=async e=>{if(ap())return this.navigate(this.buildSignInUrl(e))};redirectToSignUp=async e=>{if(ap())return this.navigate(this.buildSignUpUrl(e))};redirectToUserProfile=async()=>{if(ap())return this.navigate(this.buildUserProfileUrl())};redirectToCreateOrganization=async()=>{if(ap())return this.navigate(this.buildCreateOrganizationUrl())};redirectToOrganizationProfile=async()=>{if(ap())return this.navigate(this.buildOrganizationProfileUrl())};redirectToAfterSignIn=async()=>{if(ap())return this.navigate(this.buildAfterSignInUrl())};redirectToAfterSignUp=async()=>{if(ap())return this.navigate(this.buildAfterSignUpUrl())};redirectToAfterSignOut=async()=>{if(ap())return this.navigate(this.buildAfterSignOutUrl())};redirectToWaitlist=async()=>{if(ap())return this.navigate(this.buildWaitlistUrl())};redirectToTasks=async e=>{if(ap())return this.navigate(this.buildTasksUrl(e))};handleEmailLinkVerification=async(e,a)=>{if(!this.client)return;let t=eI("__clerk_status");if("expired"===t)throw new _(q.Expired);if("client_mismatch"===t)throw new _(q.ClientMismatch);if("verified"!==t)throw new _(q.Failed);let r=eI("__clerk_created_session"),{signIn:i,signUp:n,sessions:s}=this.client,o=s.some(e=>e.id===r),l="needs_second_factor"===i.status||"missing_requirements"===n.status,c=e=>a&&"function"==typeof a?a(e):this.navigate(e),d=e.redirectUrl?()=>c(e.redirectUrl):e0;return o?this.setActive({session:r,redirectUrl:e.redirectUrlComplete}):l?d():("function"==typeof e.onVerifiedOnOtherDevice&&e.onVerifiedOnOtherDevice(),null)};handleGoogleOneTapCallback=async(e,a,t)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:r,signUp:i}=this.client,n="identifier"in(e||{})?e:r,s="missingFields"in(e||{})?e:i,o=e=>t&&"function"==typeof t?t(this.buildUrlWithAuth(e)):this.navigate(this.buildUrlWithAuth(e));return this._handleRedirectCallback(a,{signUp:s,signIn:n,navigate:o})};_handleRedirectCallback=async(e,{signIn:a,signUp:t,navigate:r})=>{if(!this.loaded||!this.environment||!this.client)return;if(!window.opener&&e.reloadResource)try{"signIn"===e.reloadResource?await a.reload():"signUp"===e.reloadResource&&await t.reload()}catch{}let{displayConfig:i}=this.environment,{firstFactorVerification:n}=a,{externalAccount:s}=t.verifications,o={status:t.status,missingFields:t.missingFields,externalAccountStatus:s.status,externalAccountErrorCode:s.error?.code,externalAccountSessionId:s.error?.meta?.sessionId,sessionId:t.createdSessionId},l={status:a.status,firstFactorVerificationStatus:n.status,firstFactorVerificationErrorCode:n.error?.code,firstFactorVerificationSessionId:n.error?.meta?.sessionId,sessionId:a.createdSessionId},c=e=>()=>r(e),d=c(e.signInUrl||i.signInUrl),u=c(e.signUpUrl||i.signUpUrl),h=c(e.firstFactorUrl||ev({base:i.signInUrl,hashPath:"/factor-one"},{stringify:!0})),m=c(e.secondFactorUrl||ev({base:i.signInUrl,hashPath:"/factor-two"},{stringify:!0})),p=c(e.resetPasswordUrl||ev({base:i.signInUrl,hashPath:"/reset-password"},{stringify:!0})),g=new eU(this.#e_,e),b=c(e.continueSignUpUrl||ev({base:i.signUpUrl,hashPath:"/continue"},{stringify:!0})),f=({missingFields:a})=>a.length?b():(({signUp:e,verifyEmailPath:a,verifyPhonePath:t,continuePath:r,navigate:i,handleComplete:n,redirectUrl:s="",redirectUrlComplete:o="",oidcPrompt:l})=>{if("complete"===e.status)return n&&n();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 n=eO();if(e.unverifiedFields?.includes("email_address")&&a)return i(a,{searchParams:n});if(e.unverifiedFields?.includes("phone_number")&&t)return i(t,{searchParams:n});if(r)return i(r,{searchParams:n})}})({signUp:t,verifyEmailPath:e.verifyEmailAddressUrl||ev({base:i.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),verifyPhonePath:e.verifyPhoneNumberUrl||ev({base:i.signUpUrl,hashPath:"/verify-phone-number"},{stringify:!0}),navigate:r}),y=e.signInUrl||i.signInUrl,k=e.signUpUrl||i.signUpUrl,w=async({session:e,baseUrl:a,redirectUrl:t})=>{e.currentTask?await eM(e,{baseUrl:a,navigate:this.navigate}):await this.navigate(t)};if("complete"===l.status)return this.setActive({session:l.sessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:y,redirectUrl:g.getAfterSignInUrl()})}});if("transferable"===o.externalAccountStatus&&"external_account_exists"===o.externalAccountErrorCode){let e=await a.create({transfer:!0});switch(e.status){case"complete":return this.setActive({session:e.createdSessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:k,redirectUrl:g.getAfterSignInUrl()})}});case"needs_first_factor":return h();case"needs_second_factor":return m();case"needs_new_password":return p();default:ax("sign in")}}let v="user_locked"===o.externalAccountErrorCode,j="user_locked"===l.firstFactorVerificationErrorCode;if(v)return u();if(j)return d();if("needs_first_factor"===l.status&&!a.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 d();let a=await t.create({transfer:!0});switch(a.status){case"complete":return this.setActive({session:a.createdSessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:k,redirectUrl:g.getAfterSignUpUrl()})}});case"missing_requirements":return f({missingFields:a.missingFields});default:ax("sign in")}}if("complete"===o.status)return this.setActive({session:o.sessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:k,redirectUrl:g.getAfterSignUpUrl()})}});if("needs_second_factor"===l.status)return m();let z=("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(z||_){let e=l.firstFactorVerificationSessionId||o.externalAccountSessionId;if(e)return this.setActive({session:e,navigate:async({session:e})=>{await w({session:e,baseUrl:z?k:y,redirectUrl:g.getAfterSignInUrl()})}})}return(e=>{let{externalAccount:a}=e.verifications;return!!a.error})(t)?u():"verified"===o.externalAccountStatus&&"missing_requirements"===o.status?f({missingFields:t.missingFields}):this.session?.currentTask?void await this.redirectToTasks({redirectUrl:this.buildAfterSignInUrl()}):d()};handleRedirectCallback=async(e={},a)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:t,signUp:r}=this.client,i=e=>a&&"function"==typeof a?a(e):this.navigate(e);return this._handleRedirectCallback(e,{signUp:r,signIn:t,navigate:i})};handleUnauthenticated=async(e={broadcast:!0})=>{if(this.client&&this.session)try{let a=await tA.getOrCreateInstance().fetch();if(this.updateClient(a),this.session)return;return e.broadcast&&t3.emit(t2,null),this.setActive({session:null})}catch(e){if(O(e)&&[403,500].includes(e.status))return this.setActive({session:null});throw e}};authenticateWithGoogleOneTap=async e=>(az("Google One Tap"),this.client.signIn);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"})};authenticateWithWeb3=async({redirectUrl:e,signUpContinueUrl:a,customNavigate:t,unsafeMetadata:r,strategy:i,legalAccepted:n,secondFactorUrl:s})=>{let o,l;if(!this.client||!this.environment)return;let{displayConfig:c}=this.environment,d=i.replace("web3_","").replace("_signature",""),u=await af().getWeb3Identifier({provider:d});switch(d){case"metamask":o=af().generateSignatureWithMetamask;break;case"base":o=af().generateSignatureWithBase;break;case"coinbase_wallet":o=af().generateSignatureWithCoinbaseWallet;break;default:o=af().generateSignatureWithOKXWallet}let h=e=>()=>t&&"function"==typeof t?t(e):this.navigate(e),m=h(s||ev({base:c.signInUrl,hashPath:"/factor-two"},{stringify:!0})),p=h(a||ev({base:c.signUpUrl,hashPath:"/continue"},{stringify:!0}));try{l=await this.client.signIn.authenticateWithWeb3({identifier:u,generateSignature:o,strategy:i})}catch(e){if(ac(e,"form_identifier_not_found"))l=await this.client.signUp.authenticateWithWeb3({identifier:u,generateSignature:o,unsafeMetadata:r,strategy:i,legalAccepted:n}),a&&"missing_requirements"===l.status&&"verified"===l.verifications.web3Wallet.status&&await p();else throw e}let g=async({session:e,redirectUrl:a})=>{e.currentTask?await eM(e,{baseUrl:c.signInUrl,navigate:this.navigate}):await this.navigate(a)};switch(l.status){case"needs_second_factor":await m();break;case"complete":l.createdSessionId&&await this.setActive({session:l.createdSessionId,navigate:async({session:a})=>{await g({session:a,redirectUrl:e??this.buildAfterSignInUrl()})}});break;default:return}};createOrganization=async({name:e,slug:a})=>rs.create({name:e,slug:a});getOrganization=async e=>rs.get(e);joinWaitlist=async({emailAddress:e})=>rJ.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 a=this.#e_.selectInitialSession?this.#e_.selectInitialSession(e):this.#eW(e);this.#eA(a)}if(this.client=e,this.session){let e=this.#eM(this.session.id);"active"===this.session.status&&e?.status==="pending"&&("undefined"!=typeof window&&"function"==typeof window.__unstable__onAfterSetActive?window.__unstable__onAfterSetActive:e0)(),this.#eA(e),this.session?.lastActiveToken||d()||e7.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),t3.emit(t1,{token:this.session?.lastActiveToken})}this.#eC()};get __unstable__environment(){return this.environment}__unstable__setEnvironment=async e=>{this.environment=new t4(e)};__unstable__onBeforeRequest=e=>{this.#ek.onBeforeRequest(e)};__unstable__onAfterResponse=e=>{this.#ek.onAfterResponse(e)};__unstable__updateProps=e=>{let a={...e,options:this.#eU({...this.#e_,...e.options})};return this.#ey?.then(e=>e.ensureMounted()).then(e=>e.updateProps(a))};__internal_navigateWithError(e,a){return this.__internal_last_error=a,this.navigate(e)}#eL=()=>{let e=new URLSearchParams({[B]:window.location.href});return ev({base:this.#e_.signInUrl,searchParams:e},{stringify:!0})};#e$=()=>{let e;if(this.proxyUrl){let a=new URL(this.proxyUrl);e=new URL(`${a.pathname}/v1/client/sync`,a.origin)}else this.domain&&(e=new URL("/v1/client/sync",`https://${this.domain}`));return e?.searchParams.append("redirect_url",window.location.href),e?.toString()||""};#eK=()=>"true"!==eI($)&&!!this.isSatellite&&!!this.#ep?.isSignedOut();#eB=()=>"production"!==this.#ew&&!this.isSatellite&&!!eI(B);#eJ=async()=>{"development"===this.instanceType?await this.navigate(this.#eL()):"production"===this.instanceType&&await this.navigate(this.#e$())};#eV=(e,a)=>{let t;try{t=new URL(e)}catch{throw Error(`${aj} The signInUrl needs to have a absolute url format.`)}t.origin===a&&function(){throw Error(`${aj} The signInUrl needs to be on a different origin than your satellite application.`)}()};#eG=()=>{this.isSatellite&&("development"!==this.#ew||this.#e_.signInUrl||function(){throw Error(`${aj} Missing signInUrl. A satellite application needs to specify the signInUrl for development instances.`)}(),this.proxyUrl||this.domain||function(){throw Error(`${aj} Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl.`)}(),this.#e_.signInUrl&&this.#eV(this.#e_.signInUrl,window.location.origin))};#eI=async()=>{if(this.#ep=await ii.create(this,this.#ek,this.#ew,this.#eS),this.#eG(),this.#eK())return void await this.#eJ();if(this.#eB())return void await this.#eN();this.#ex=(()=>{if(!s())return{onPageFocus:e0};let e=[];return window.addEventListener("focus",()=>{"visible"===document.visibilityState&&e.forEach(e=>e())}),{onPageFocus:a=>{e.push(a)}}})(),"undefined"!=typeof BroadcastChannel&&(this.#ef=new BroadcastChannel("clerk")),this.#eH();let e=function(e=window.location.hostname){if(!e)return!1;let a=ek.get(e);void 0===a&&(a=ei.some(a=>e.startsWith("accounts.")&&e.endsWith(a))||en.some(a=>e.endsWith(a)&&!e.endsWith(".clerk"+a)),ek.set(e,a));return a}(window?.location.hostname),a="development"===this.#ew&&!e,t=0,r=0;for(;r<2;){r++;try{var i;let e=t4.getInstance().fetch({touch:a}).then(e=>this.updateEnvironment(e)).catch(()=>{++t;let e=av.getItem(ay,null);e&&this.updateEnvironment(new t4(e))}),r=async()=>tA.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(async e=>{if(I(e))throw e;++t;let a=this.#ep?.getSessionCookie(),r=function(e){let a;try{a=new rF({jwt:e||"",object:"token",id:void 0})}catch{a=null}if(tA.clearInstance(),!a?.jwt)return tA.getOrCreateInstance({object:"client",last_active_session_id:null,id:"client_init",sessions:[]});let{sessionId:t,userId:r,orgId:i,orgRole:n,orgPermissions:s,orgSlug:o,factorVerificationAge:l}=(e=>{let a,t,r,i,n=e.fva??null,s=e.sts??null;if(2===e.v){if(e.o){a=e.o?.id,r=e.o?.slg,e.o?.rol&&(t=`org:${e.o?.rol}`);let{org:n}=rv(e.fea),{permissions:s,featurePermissionMap:o}=(({per:e,fpm:a})=>{if(!e||!a)return{permissions:[],featurePermissionMap:[]};let t=e.split(",").map(e=>e.trim());return{permissions:t,featurePermissionMap:a.split(",").map(e=>Number.parseInt(e.trim(),10)).map(e=>e.toString(2).padStart(t.length,"0").split("").map(e=>Number.parseInt(e,10)).reverse()).filter(Boolean)}})({per:e.o?.per,fpm:e.o?.fpm});i=function({features:e,permissions:a,featurePermissionMap:t}){if(!e||!a||!t)return[];let r=[];for(let i=0;i<e.length;i++){let n=e[i];if(i>=t.length)continue;let s=t[i];if(s)for(let e=0;e<s.length;e++)1===s[e]&&r.push(`org:${n}:${a[e]}`)}return r}({features:n,featurePermissionMap:o,permissions:s})}}else a=e.org_id,t=e.org_role,r=e.org_slug,i=e.org_permissions;return{sessionClaims:e,sessionId:e.sid,sessionStatus:s,actor:e.act,userId:e.sub,orgId:a,orgRole:t,orgSlug:r,orgPermissions:i,factorVerificationAge:n}})(a.jwt.claims),c={object:"client",last_active_session_id:t,id:"client_init",sessions:[{object:"session",id:t,status:"active",last_active_organization_id:i||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:i&&o&&n?[{object:"organization_membership",id:i,role:n,permissions:s||[],organization:{object:"organization",id:i,name:o,slug:o,members_count:1,max_allowed_memberships:1}}]:[]}}]};return tA.getOrCreateInstance(c)}(a);return this.updateClient(r),this.#ep?.stopPollingForToken(),await this.session?.getToken({skipCache:!0}).catch(()=>null).finally(()=>{this.#ep?.startPollingForToken()}),null}),[,n]=await (i=[e,r()],Promise.all(Array.from(i).map(e=>e.then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e})))));if("rejected"===n.status){let e=n.reason;if(ac(e,"requires_captcha"))await r();else throw e}if(this.#ep?.setClientUatCookieForDevelopmentInstances(),await this.#eQ())return;break}catch(e){if(ac(e,"dev_browser_unauthenticated"))await this.#ep.handleUnauthenticatedDevBrowser();else if(!d())return void console.warn(e);else throw e}r>=2&&function(){throw Error(`${aj} Something went wrong initializing Clerk.`)}()}this.#eb=new is(this),this.#eb.start(),this.#eY(),this.#eX(),this.#eZ(),this.#eS.emit(g,t>0?"degraded":"ready")};shouldFallbackToCachedResources=()=>!!this.__internal_getCachedResources;#eP=async()=>{let e,a,t=this.shouldFallbackToCachedResources()?1:void 0,r=0;try{[e,a]=await Promise.all([t4.getInstance().fetch({touch:!1,fetchMaxTries:t}),tA.getOrCreateInstance().fetch({fetchMaxTries:t})])}catch(t){if(T(t)&&"network_error"===t.code&&this.shouldFallbackToCachedResources()){let t=await this.__internal_getCachedResources?.();e=new t4(t?.environment),tA.clearInstance(),a=tA.getOrCreateInstance(t?.client),++r}else throw t}this.updateClient(a),this.updateEnvironment(e),this.#eS.emit(g,r>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,a]=await Promise.all([t4.getInstance().fetch({touch:!1,fetchMaxTries:1}),tA.getOrCreateInstance().fetch({fetchMaxTries:1})]);this.updateClient(a),this.updateEnvironment(e),this.#eC()};#eW=e=>{if(e.lastActiveSessionId){let a=e.signedInSessions.find(a=>a.id===e.lastActiveSessionId);if(a)return a}return e.signedInSessions[0]||null};#eH=()=>{s()&&(this.#ex?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#eq>Date.now())&&(this.#eq=Date.now()+5e3,this.#e_.touchSession&&this.#eE(this.session))}),this.#ef?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),t3.on(t2,()=>{this.#ef?.postMessage({type:"signout"})}),t3.on(t0,()=>{av.setItem(ay,this.environment?.__internal_toSnapshot(),864e5)}))};#eE=async e=>{if(!e)return Promise.resolve();await e.touch().catch(e=>{I(e)&&this.handleUnauthenticated()})};#eC=()=>{if(this.client)for(let e of this.#ej)e({client:this.client,session:this.session,user:this.user,organization:this.organization})};#eR=()=>{for(let e of this.#ez)e()};#eT=()=>{this.session=void 0,this.organization=void 0,this.user=void 0,this.#eC()};#e1=()=>(this.session?.user.organizationMemberships||[]).map(e=>e.organization).find(e=>e.id===this.session?.lastActiveOrganizationId)||null;#eA=e=>{this.session=e||null,this.organization=this.#e1(),this.user=this.session?this.session.user:null};#eM=e=>this.client?.signedInSessions.find(a=>a.id===e)||null;#eX=()=>{this.addListener(({session:e})=>{e?.actor&&this.#ey?.then(e=>e.ensureMounted()).then(e=>e.mountImpersonationFab())})};#eZ=()=>{this.#e_.__internal_keyless_claimKeylessApplicationUrl&&this.#ey?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#e_.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#e_.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#e_.__internal_keyless_dismissPrompt}})})};#eD=(e,a,t)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let r=this.#e_[e]||this.environment.displayConfig[e];this.#eO()&&(r=this.#e_.signInUrl);let i=new eU(this.#e_,a).toSearchParams(),n=new URLSearchParams(t||{}),s=ev({base:r,hashPath:this.#eO()&&"signUpUrl"===e?"/create":"",hashSearchParams:[n,i]},{stringify:!0});return this.buildUrlWithAuth(s)};assertComponentsReady(e){if(!e)throw Error("Clerk was not loaded with Ui components")}#eQ=async()=>{var e;let a,t,r,i,n=new URLSearchParams(window.location.search).get("redirect_url"),s="production"===this.instanceType,o=null!==n&&(e=this.frontendApi,t=(a=new URL(n,eb)).pathname,r=eq.includes(t)||eS.includes(t),e===a.host&&r);if(s||!o)return!1;let l=this.session,c=this.#e_.signInUrl||this.environment?.displayConfig.signInUrl,d=c&&window.location.href.startsWith(c),u=this.#e_.signUpUrl||this.environment?.displayConfig.signUpUrl,h=u&&window.location.href.startsWith(u);return i=new URL(n,eb),(!eq.includes(i.pathname)||!!l||!d&&!h)&&(await this.navigate(this.buildUrlWithAuth(n)),!0)};#eU=e=>({...ik,...e,allowedRedirectOrigins:function(e,a,t){if(Array.isArray(e)&&e.length)return e;let r=[];return"undefined"!=typeof window&&window.location&&r.push(window.location.origin),r.push(`https://${ew(a)}`),r.push(`https://*.${ew(a)}`),"development"===t&&r.push(`https://${a}`),r}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)});#eY=()=>{try{eP($),eP(eA),eP(K),eP("__clerk_handshake"),eP("__clerk_handshake_nonce"),eP("__clerk_help")}catch{}};get #eF(){let e=eN;return this.#e_.allowedRedirectProtocols&&(e=e.concat(this.#e_.allowedRedirectProtocols)),e}}})();var s=exports;for(var o in n)s[o]=n[o];n.__esModule&&Object.defineProperty(s,"__esModule",{value:!0})})();
|
|
19
|
+
API Error: ${i}`,{data:a,status:e})}}(n,e);let r={data:e,status:n};if(429===n&&o){let e=o.get("retry-after");if(e){let a=parseInt(e,10);isNaN(a)||(r.retryAfter=a)}}throw new v(a||s,r)}return null}static _updateClient(e){if(!e)return;let a=e.client||e.meta?.client;a&&aM.clerk&&aM.clerk.updateClient(tA.getOrCreateInstance().fromJSON(a))}path(e){let a=this.pathRoot;if(this.isNew())return a;let t=a.replace(/[^/]$/,"$&/")+encodeURIComponent(this.id);return e?t.replace(/[^/]$/,"$&/")+encodeURIComponent(e):t}withDefault(e,a){return e??a}async _baseGet(e={}){let a=await aM._fetch({method:"GET",path:this.path(),rotatingTokenNonce:e.rotatingTokenNonce},e);return this.fromJSON(a?.response||a)}async _baseMutate(e){let{action:a,body:t,method:r,path:i}=e,n=await aM._fetch({method:r,path:i||this.path(a),body:t});return this.fromJSON(n?.response||n)}async _baseMutateBypass(e){let{action:a,body:t,method:r,path:i}=e,n=await aM._baseFetch({method:r,path:i||this.path(a),body:t});return this.fromJSON(n?.response||n)}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=aM.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}function aR(e){let a=new Date(e||new Date);return a instanceof Date&&!isNaN(a.getTime())?a:new Date}class aF extends aM{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?aR(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?aR(e.last_used_at):null,this.updatedAt=aR(e.updated_at),this.createdAt=aR(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 aD extends aM{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?aR(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}}}(f=y||(y={}))[f.None=0]="None",f[f.Mutable=1]="Mutable",f[f.Watching=2]="Watching",f[f.RecursedCheck=4]="RecursedCheck",f[f.Recursed=8]="Recursed",f[f.Dirty=16]="Dirty",f[f.Pending=32]="Pending";let aN=[],{link:aW,unlink:aL,propagate:a$,checkDirty:aK,endTracking:aB,startTracking:aJ,shallowPropagate:aV}=function({update:e,notify:a,unwatched:t}){let r=0;return{link:function(e,a){let t,i=a.depsTail;if(void 0!==i&&i.dep===e)return;if(4&a.flags&&void 0!==(t=void 0!==i?i.nextDep:a.deps)&&t.dep===e){t.version=r,a.depsTail=t;return}let n=e.subsTail;if(void 0!==n&&n.version===r&&n.sub===a)return;let s=a.depsTail=e.subsTail={version:r,dep:e,sub:a,prevDep:i,nextDep:t,prevSub:n,nextSub:void 0};void 0!==t&&(t.prevDep=s),void 0!==i?i.nextDep=s:a.deps=s,void 0!==n?n.nextSub=s:e.subs=s},unlink:i,propagate:function(e){let t,r=e.nextSub;e:for(;;){let i=e.sub,n=i.flags;if(3&n&&(60&n?12&n?4&n?!(48&n)&&function(e,a){let t=a.depsTail;if(void 0!==t){let r=a.deps;do{if(r===e)return!0;if(r===t)break;r=r.nextDep}while(void 0!==r)}return!1}(e,i)?(i.flags=40|n,n&=1):n=0:i.flags=-9&n|32:n=0:i.flags=32|n,2&n&&a(i),1&n)){let a=i.subs;if(void 0!==a){e=a,void 0!==a.nextSub&&(t={value:r,prev:t},r=e.nextSub);continue}}if(void 0!==(e=r)){r=e.nextSub;continue}for(;void 0!==t;)if(e=t.value,t=t.prev,void 0!==e){r=e.nextSub;continue e}break}},checkDirty:function(a,t){let r,i=0;e:for(;;){let s=a.dep,o=s.flags,l=!1;if(16&t.flags)l=!0;else if((17&o)==17){if(e(s)){let e=s.subs;void 0!==e.nextSub&&n(e),l=!0}}else if((33&o)==33){(void 0!==a.nextSub||void 0!==a.prevSub)&&(r={value:a,prev:r}),a=s.deps,t=s,++i;continue}if(!l&&void 0!==a.nextDep){a=a.nextDep;continue}for(;i;){--i;let s=t.subs,o=void 0!==s.nextSub;if(o?(a=r.value,r=r.prev):a=s,l){if(e(t)){o&&n(s),t=a.sub;continue}}else t.flags&=-33;if(t=a.sub,void 0!==a.nextDep){a=a.nextDep;continue e}l=!1}return l}},endTracking:function(e){let a=e.depsTail,t=void 0!==a?a.nextDep:e.deps;for(;void 0!==t;)t=i(t,e);e.flags&=-5},startTracking:function(e){++r,e.depsTail=void 0,e.flags=-57&e.flags|4},shallowPropagate:n};function i(e,a=e.sub){let r=e.dep,n=e.prevDep,s=e.nextDep,o=e.nextSub,l=e.prevSub;return void 0!==s?s.prevDep=n:a.depsTail=n,void 0!==n?n.nextDep=s:a.deps=s,void 0!==o?o.prevSub=l:r.subsTail=l,void 0!==l?l.nextSub=o:void 0===(r.subs=o)&&t(r),s}function n(e){do{let t=e.sub,r=e.nextSub,i=t.flags;(48&i)==32&&(t.flags=16|i,2&i&&a(t)),e=r}while(void 0!==e)}}({update:e=>"getter"in e?a2(e):a0(e,e.value),notify:function e(a){let t=a.flags;if(!(64&t)){a.flags=64|t;let r=a.subs;void 0!==r?e(r.sub):aN[aQ++]=a}},unwatched(e){if("getter"in e){let a=e.deps;if(void 0!==a){e.flags=17;do a=aL(a,e);while(void 0!==a)}}else"previousValue"in e||a5.call(e)}}),aG=0,aH=0,aQ=0;function aY(a){let t=e;return e=a,t}function aX(e){return a8.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function aZ(e){return a3.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function a1(t){let r={fn:t,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==e?aW(r,e):void 0!==a&&aW(r,a);let i=aY(r);try{r.fn()}finally{aY(i)}return a5.bind(r)}function a2(e){let a=aY(e);aJ(e);try{let a=e.value;return a!==(e.value=e.getter(a))}finally{aY(a),aB(e)}}function a0(e,a){return e.flags=1,e.previousValue!==(e.previousValue=a)}function a9(){for(;aH<aQ;){let e=aN[aH];aN[aH++]=void 0,function e(a,t){if(16&t||32&t&&aK(a.deps,a)){let e=aY(a);aJ(a);try{a.fn()}finally{aY(e),aB(a)}return}32&t&&(a.flags=-33&t);let r=a.deps;for(;void 0!==r;){let a=r.dep,t=a.flags;64&t&&e(a,a.flags=-65&t),r=r.nextDep}}(e,e.flags&=-65)}aH=0,aQ=0}function a3(){let t=this.flags;if(16&t||32&t&&aK(this.deps,this)){if(a2(this)){let e=this.subs;void 0!==e&&aV(e)}}else 32&t&&(this.flags=-33&t);return void 0!==e?aW(this,e):void 0!==a&&aW(this,a),this.value}function a8(...a){if(a.length){let e=a[0];if(this.value!==(this.value=e)){this.flags=17;let e=this.subs;void 0!==e&&(a$(e),aG||a9())}}else{let a=this.value;if(16&this.flags&&a0(this,a)){let e=this.subs;void 0!==e&&aV(e)}return void 0!==e&&aW(this,e),a}}function a5(){let e=this.deps;for(;void 0!==e;)e=aL(e,this);let a=this.subs;void 0!==a&&aL(a),this.flags=0}function a4(e){let{pageSize:a,initialPage:t,...r}=e||{},i=a??10;return new URLSearchParams({...Object.entries(r).reduce((e,[a,t])=>(void 0!==t&&(e[a]=t),e),{}),limit:i+"",offset:((t??1)-1)*i+""})}class a6{static #en="/billing";static path(e,a){let{orgId:t}=a||{},r=t?`/organizations/${t}`:"/me";return`${r}${a6.#en}${e}`}getPlans=async e=>{let{for:a,...t}=e||{},r={...t,payer_type:"organization"===a?"org":"user"};return await aM._fetch({path:`${a6.#en}/plans`,method:"GET",search:a4(r)}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new ty(e))}})};getPlan=async e=>new ty(await aM._fetch({path:`${a6.#en}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await aM._fetch({path:a6.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new tv(e?.response));getStatements=async e=>{let{orgId:a,...t}=e;return await aM._fetch({path:a6.path("/statements",{orgId:a}),method:"GET",search:a4(t)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new tk(e))}})};getStatement=async e=>new tk((await aM._fetch({path:a6.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:a,...t}=e;return await aM._fetch({path:a6.path("/payment_attempts",{orgId:a}),method:"GET",search:a4(t)}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new tu(e))}})};getPaymentAttempt=async e=>new tu(await aM._fetch({path:a6.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:a,...t}=e;return new tc((await aM._fetch({path:a6.path("/checkouts",{orgId:a}),method:"POST",body:t}))?.response)}}let a7=aX({resource:null}),te=aX({error:null}),ta=aX({status:"idle"}),tt=aZ(()=>{let e=a7().resource,a=te().error,t=ta().status;return{errors:to(a,{identifier:null,password:null,code:null}),fetchStatus:t,signIn:e?e.__internal_future:null}}),tr=aX({resource:null}),ti=aX({error:null}),tn=aX({status:"idle"}),ts=aZ(()=>{let e=tr().resource,a=ti().error,t=tn().status;return{errors:to(a,{firstName:null,lastName:null,emailAddress:null,phoneNumber:null,password:null,username:null,code:null,captcha:null,legalAccepted:null}),fetchStatus:t,signUp:e?e.__internal_future:null}});function to(e,a){let t={fields:{...a},raw:null,global:null};if(!e)return t;if(!O(e))return t.raw=[e],t.global=[F(e)],t;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(t.raw?t.raw.push(e):t.raw=[e],r(e)){let a=Y(e.meta.paramName);a in t.fields&&(t.fields[a]=e)}}):(t.raw=[e],t.global=[F(e)]),t}class tl extends aM{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=aR(e.created_at)),e.updated_at&&(this.updatedAt=aR(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 tc extends aM{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 tb(e.payment_method):void 0,this.plan=new ty(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=al(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change,e.free_trial_ends_at&&(this.freeTrialEndsAt=aR(e.free_trial_ends_at)),this.payer=new tl(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>ar(()=>this._basePatch({path:a6.path(`/checkouts/${this.id}/confirm`,{orgId:this.payer.organizationId}),body:e}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,a){if(!O(e)||a>=4)return!1;let t=e?.status,r=409===t&&e.errors?.[0]?.code==="checkout_already_in_progress";return t>=500||r}})}class td{resource=new tc(null);config;signals;pendingOperations=new Map;constructor(e,a){this.config=a,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 tc.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new tc(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:a}=e||{};return this.runAsyncCheckoutTask("finalize",async()=>{if("completed"!==this.resource.status)throw Error("Clerk: `confirm()` must be called before `finalize()`");await tc.clerk.setActive({session:tc.clerk.session?.id,navigate:a})})}runAsyncCheckoutTask(e,a,t){var r,i,n;return void 0===tc.clerk.user?(console.warn("Clerk: Checkout operations cannot be performed during transitive state"),{error:null}):(r=this,i=this.signals,n=this.pendingOperations,async(e,a,t)=>{if(n.get(e))return n.get(e);let s=(async()=>{++aG,i.errorSignal({error:null}),i.fetchSignal({status:"fetching"}),t?.(),--aG||a9(),++aG;try{return await a(),i.resourceSignal({resource:r}),{error:null}}catch(e){return i.errorSignal({error:e}),{error:e}}finally{n.delete(e),i.fetchSignal({status:"idle"}),--aG||a9()}})();return n.set(e,s),s})(e,a,t)}}class tu extends aM{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=ao(e.amount),this.paidAt=e.paid_at?aR(e.paid_at):null,this.failedAt=e.failed_at?aR(e.failed_at):null,this.updatedAt=aR(e.updated_at),this.paymentMethod=e.payment_method?new tb(e.payment_method):null,this.subscriptionItem=new tj(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status),this}}let th="/payment_methods",tm=async e=>{let{orgId:a,...t}=e;return new tf((await aM._fetch({path:a6.path(`${th}/initialize`,{orgId:a}),method:"POST",body:t}))?.response)},tp=async e=>{let{orgId:a,...t}=e;return new tb((await aM._fetch({path:a6.path(th,{orgId:a}),method:"POST",body:t}))?.response)},tg=async e=>{let{orgId:a,...t}=e??{};return await aM._fetch({path:a6.path(th,{orgId:a}),method:"GET",search:a4(t)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new tb(e))}})};class tb extends aM{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:aR(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:aR(e.updated_at)),this}async remove(e){let{orgId:a}=e??{};return new tI((await aM._fetch({path:a6.path(`/payment_methods/${this.id}`,{orgId:a}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:a}=e??{};return await aM._fetch({path:a6.path("/payers/default_payment_method",{orgId:a}),method:"PUT",body:{payment_method_id:this.id}}),null}}class tf extends aM{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 ty extends aM{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=ao(e.fee),this.annualFee=e.annual_fee?ao(e.annual_fee):null,this.annualMonthlyFee=e.annual_monthly_fee?ao(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 t7(e))),this}}class tk extends aM{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=aR(e.timestamp),this.totals=al(e.totals),this.groups=e.groups.map(e=>new tw(e))),this}}class tw{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=aR(e.timestamp),this.items=e.items.map(e=>new tu(e))),this}}class tv extends aM{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=aR(e.created_at),this.updatedAt=e.updated_at?aR(e.updated_at):null,this.activeAt=aR(e.active_at),this.pastDueAt=e.past_due_at?aR(e.past_due_at):null,e.next_payment&&(this.nextPayment={amount:ao(e.next_payment.amount),date:aR(e.next_payment.date)}),this.subscriptionItems=(e.subscription_items||[]).map(e=>new tj(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1)),this}}class tj extends aM{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 ty(e.plan),this.planPeriod=e.plan_period,this.status=e.status,this.createdAt=aR(e.created_at),this.pastDueAt=e.past_due_at?aR(e.past_due_at):null,this.periodStart=aR(e.period_start),this.periodEnd=e.period_end?aR(e.period_end):null,this.canceledAt=e.canceled_at?aR(e.canceled_at):null,this.amount=e.amount?ao(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:ao(e.credit.amount)}:void 0,this.isFreeTrial=this.withDefault(e.is_free_trial,!1)),this}async cancel(e){let{orgId:a}=e;return new tI((await aM._fetch({path:a6.path(`/subscription_items/${this.id}`,{orgId:a}),method:"DELETE"}))?.response)}}let tz={build:(e,a,t)=>[e,a,t].filter(Boolean).join("-"),parse:(e,a,t)=>{let r=tz.extractTemplate(e,a,t);return{organizationId:t,sessionId:a,template:r}},extractTemplate:(e,a,t)=>{if(e===a||t&&e===`${a}-${t}`)return;let r=e.slice(a.length+1);return t&&r.endsWith(`-${t}`)&&(r=r.slice(0,-(t.length+1))),r||void 0}},t_="clerk",tx=10,tq={broadcast:!0};class tS{prefix;data;static fromKey(e){let[a,t,r=""]=e.split("::");return new tS(a,{audience:r,tokenId:t})}constructor(e,a){this.prefix=e,this.data=a,this.prefix=e,this.data=a}toKey(){let{tokenId:e,audience:a}=this.data;return[this.prefix,e,a||""].join("::")}}let tU=((e=t_)=>{let a=new Map,t=Math.random().toString(36).slice(2),r=null;return{clear:()=>{a.forEach(e=>{void 0!==e.timeoutId&&clearTimeout(e.timeoutId)}),a.clear()},close:()=>{r&&(r.close(),r=null)},get:(t,r=tx)=>{let i=new tS(e,t),n=a.get(i.toKey());if(!n)return;let s=Math.floor(Date.now()/1e3)-n.createdAt;if(n.expiresIn-s<(r||1)+5){void 0!==n.timeoutId&&clearTimeout(n.timeoutId),a.delete(i.toKey());return}return n.entry},set:i=>{((i,n=tq)=>{let s=new tS(e,{audience:i.audience,tokenId:i.tokenId}).toKey(),o=Math.floor(Date.now()/1e3),l={createdAt:i.createdAt??o,entry:i,expiresIn:void 0},c=()=>{let e=a.get(s);e===l&&(void 0!==e.timeoutId&&clearTimeout(e.timeoutId),a.delete(s))};i.tokenResolver.then(e=>{let a=e.jwt?.claims;if(!a||"number"!=typeof a.exp||"number"!=typeof a.iat)return c();let s=a.exp-a.iat;l.expiresIn=s;let o=setTimeout(c,1e3*s);l.timeoutId=o,"function"==typeof o.unref&&o.unref();let d=r;if(d&&n.broadcast){let r=e.getRawString();if(r&&a.sid){let e=a.sid,n=a.org_id||a.o?.id,s=tz.extractTemplate(i.tokenId,e,n),o=tz.build(e,s,n);if(i.tokenId===o){let a=`bc_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;e7.info("Broadcasting token update to other tabs",{organizationId:n,sessionId:e,tabId:t,template:s,tokenId:i.tokenId,traceId:a},"tokenCache");let o={organizationId:n,sessionId:e,template:s,tokenId:i.tokenId,tokenRaw:r,traceId:a};d.postMessage(o)}}}}).catch(()=>{c()}),a.set(s,l)})(i,tq)},size:()=>a.size}})();class tA extends aM{static instance;pathRoot="/client";sessions=[];signUp=new rE;signIn=new rP;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return tA.instance||(tA.instance=new tA(e)),tA.instance}static clearInstance(){tA.instance=null}static isClientResource(e){return!!e&&e instanceof tA}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(()=>{tU.clear(),this.id="",this.sessions=[],this.signUp=new rE(null),this.signIn=new rP(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=>(tU.clear(),e))}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return aM.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 rz(e)),this.signUp=new rE(e.sign_up),this.signIn=new rP(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?aR(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=aR(e.created_at||void 0),this.updatedAt=aR(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 tC extends aM{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 tI{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 tP extends aM{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="";experimental__forceOauthFirst;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 tO='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 tT=(e,a={})=>{if("undefined"==typeof Worker)return null;try{let t=new Blob([e],{type:"application/javascript; charset=utf-8"}),r=globalThis.URL.createObjectURL(t);return new Worker(r,a)}catch{return console.warn("Clerk: Cannot create worker from blob. Consider adding worker-src blob:; to your CSP"),null}},tE=()=>{let e=0,a=()=>e++,t=new Map,r=(e,a)=>e?.postMessage(a),i=e=>{t.get(e.data.id)?.()},n=tT(tO,{name:"clerk-timers"});if(n?.addEventListener("message",i),!n)return{setTimeout:globalThis.setTimeout.bind(globalThis),setInterval:globalThis.setInterval.bind(globalThis),clearTimeout:globalThis.clearTimeout.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis),cleanup:e0};let s=()=>{n||(n=tT(tO,{name:"clerk-timers"}),n?.addEventListener("message",i))};return{setTimeout:(e,i)=>{s();let o=a();return t.set(o,()=>{e(),t.delete(o)}),r(n,{type:"setTimeout",id:o,ms:i}),o},setInterval:(e,i)=>{s();let o=a();return t.set(o,e),r(n,{type:"setInterval",id:o,ms:i}),o},clearTimeout:e=>{s(),t.delete(e),r(n,{type:"clearTimeout",id:e})},clearInterval:e=>{s(),t.delete(e),r(n,{type:"clearInterval",id:e})},cleanup:()=>{n&&(n.terminate(),n=null,t.clear())}}};function tM({delayInMs:e}={delayInMs:1e3}){let a,t=tE(),r=!1,i=()=>{a&&(t.clearTimeout(a),t.cleanup()),r=!0},n=async s=>{r=!1,await s(i),r||(a=t.setTimeout(()=>{n(s)},e))};return{run:n,stop:i}}class tR extends aM{id;emailAddress="";matchesSsoConnection=!1;linkedTo=[];verification;constructor(e,a){super(),this.pathRoot=a,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:a}=e||{};return this._basePost({action:"attempt_verification",body:{code:a}})};createEmailLinkFlow=()=>{let{run:e,stop:a}=tM();return{startEmailLinkFlow:async({redirectUrl:t})=>(await this.prepareVerification({strategy:"email_link",redirectUrl:t}),new Promise((t,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(a(),t(e))}).catch(e=>{a(),r(e)}))})),cancelEmailLinkFlow:a}};createEnterpriseSSOLinkFlow=()=>{let{run:e,stop:a}=tM();return{startEnterpriseSSOLinkFlow:async({redirectUrl:t})=>{if(!(await this.prepareVerification({strategy:"enterprise_sso",redirectUrl:t})).verification.externalVerificationRedirectURL)throw Error("Unexpected: External verification redirect URL is missing");return new Promise((t,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(a(),t(e))}).catch(e=>{a(),r(e)}))})},cancelEnterpriseSSOLinkFlow:a}};destroy=()=>this._baseDelete();toString=()=>this.emailAddress;fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.verification=new tG(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new re(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 tF=class{static encode(e){return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}static decode(e){let a=atob(e.replace(/-/g,"+").replace(/_/g,"/")),t=a.length,r=new Uint8Array(t);for(let e=0;e<t;e++)r[e]=a.charCodeAt(e);return r.buffer}};async function tD(e){try{let a=await navigator.credentials.create({publicKey:e});if(!a)return{error:new A("Browser failed to create credential",{code:"passkey_registration_failed"}),publicKeyCredential:null};return{publicKeyCredential:a,error:null}}catch(e){var a;return{error:"InvalidStateError"===(a=e).name?new A(a.message,{code:"passkey_already_exists"}):"NotAllowedError"===a.name?new A(a.message,{code:"passkey_registration_cancelled"}):tL(a),publicKeyCredential:null}}}let tN=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 tW({publicKeyOptions:e,conditionalUI:a}){try{let t=await navigator.credentials.get({publicKey:e,mediation:a?"conditional":"optional",signal:tN.createAbortSignal()});if(!t)return{error:new A("Browser failed to get credential",{code:"passkey_retrieval_failed"}),publicKeyCredential:null};return{publicKeyCredential:t,error:null}}catch(e){var t;return{error:"NotAllowedError"===(t=e).name?new A(t.message,{code:"passkey_retrieval_cancelled"}):tL(t),publicKeyCredential:null}}}function tL(e){return"AbortError"===e.name?new A(e.message,{code:"passkey_operation_aborted"}):"SecurityError"===e.name?new A(e.message,{code:"passkey_invalid_rpID_or_domain"}):e}function t$(e){let a=tV(e.challenge),t=(e.allowCredentials||[]).map(e=>({...e,id:tV(e.id)}));return{...e,allowCredentials:t,challenge:a}}function tK(e){return{type:e.type,id:e.id,rawId:tJ(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function tB(e){let a=e.response;return{...tK(e),response:{clientDataJSON:tJ(a.clientDataJSON),authenticatorData:tJ(a.authenticatorData),signature:tJ(a.signature),userHandle:a.userHandle?tJ(a.userHandle):null}}}let tJ=tF.encode.bind(tF),tV=tF.decode.bind(tF);class tG extends aM{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===aM.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=aR(e.expire_at||void 0),this.error=e.error?new k(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 tH extends tG{publicKey=null;constructor(e){super(e),this.fromJSON(e)}fromJSON(e){var a;let t,r,i;return super.fromJSON(e),e?.nonce&&(this.publicKey=(t=tV((a=JSON.parse(e.nonce)).user.id),r=tV(a.challenge),i=(a.excludeCredentials||[]).map(e=>({...e,id:tV(e.id)})),{...a,excludeCredentials:i,challenge:r,user:{...a.user,id:t}})),this}}class tQ{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new tY(e.email_address),this.phoneNumber=new tY(e.phone_number),this.web3Wallet=new tY(e.web3_wallet),this.externalAccount=new tG(e.external_account)):(this.emailAddress=new tY(null),this.phoneNumber=new tY(null),this.web3Wallet=new tY(null),this.externalAccount=new tG(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 tY extends tG{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 tX extends aM{id;protocol;provider;providerUserId=null;active;emailAddress="";firstName="";lastName="";publicMetadata={};verification=null;enterpriseConnection=null;lastAuthenticatedAt=null;enterpriseConnectionId=null;constructor(e,a){super(),this.pathRoot=a,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?aR(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new tG(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new tZ(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 tZ extends aM{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=aR(e.created_at),this.updatedAt=aR(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 t1="token:update",t2="user:signOut",t0="environment:update",t9="session:tokenResolved",t3=p();class t8 extends aM{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 t5 extends aM{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 t4 extends aM{static instance;authConfig=new aD;displayConfig=new tP;maintenanceMode=!1;clientDebugMode=!1;pathRoot="/environment";userSettings=new rB;organizationSettings=new t5;commerceSettings=new tC;apiKeysSettings=new t8;protectConfig=new rg;static getInstance(){return t4.instance||(t4.instance=new t4),t4.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new aD(e.auth_config),this.displayConfig=new tP(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 t5(e.organization_settings),this.userSettings=new rB(e.user_settings),this.commerceSettings=new tC(e.commerce_settings),this.apiKeysSettings=new t8(e.api_keys_settings),this.protectConfig=new rg(e.protect_config)),this}fetch({touch:e,fetchMaxTries:a}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:a})).then(e=>(t3.emit(t0,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()}}}class t6 extends aM{id;identificationId;provider;providerUserId="";emailAddress="";approvedScopes="";firstName="";lastName="";imageUrl="";username="";phoneNumber="";publicMetadata={};label="";verification=null;constructor(e,a){super(),this.pathRoot=a,this.fromJSON(e)}reauthorize=e=>{let{additionalScopes:a,redirectUrl:t}=e||{};return this._basePatch({action:"reauthorize",body:{additional_scope:a,redirect_url:t}})};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 tG(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 t7 extends aM{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 re extends aM{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 ra extends aM{id;name=null;publicUrl=null;static async create(e,a={}){let t,r=a;return"string"==typeof a.file?(r=a.file,t=new Headers({"Content-Type":"application/octet-stream"})):a.file&&(r=new FormData).append("file",a.file),new ra((await aM._fetch({path:e,method:"POST",body:r,headers:t}))?.response)}static async delete(e){return new ra((await aM._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 rt extends aM{id;name;organizationId;enrollmentMode;verification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:a}){return new rt((await aM._fetch({path:`/organizations/${e}/domains`,method:"POST",body:{name:a}}))?.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:aR(e.verification.expires_at)}:this.verification=null),this}}class rr extends aM{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=aR(e.created_at),this.updatedAt=aR(e.updated_at),e.public_user_data&&(this.publicUserData=new rb(e.public_user_data))),this}}class ri extends aM{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=aR(e.created_at),this.updatedAt=aR(e.updated_at)),this}}class rn extends aM{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 ri(e)),this.createdAt=aR(e.created_at),this.updatedAt=aR(e.updated_at)),this}}class rs extends aM{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 rs((await aM._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new rs((await aM._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await aM._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:a4(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rn(e))}});getDomains=async e=>await aM._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:a4(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rt(e))}});getDomain=async({domainId:e})=>new rt((await aM._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getMembershipRequests=async e=>await aM._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:a4(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rr(e))}});createDomain=async e=>rt.create(this.id,{name:e});getMemberships=async e=>await aM._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:a4({...e,paginated:!0})}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rl(e))}});getInvitations=async e=>await aM._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:a4(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new ro(e))}});addMember=async({userId:e,role:a})=>await aM._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:a}}).then(e=>new rl(e?.response));inviteMember=async e=>ro.create(this.id,e);inviteMembers=async e=>ro.createBulk(this.id,e);updateMember=async({userId:e,role:a})=>await aM._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:a}}).then(e=>new rl(e?.response));removeMember=async e=>await aM._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new rl(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let a,t;return null===e?await aM._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new rs(e?.response)):("string"==typeof e?(a=e,t=new Headers({"Content-Type":"application/octet-stream"})):(a=new FormData).append("file",e),await aM._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:a,headers:t}).then(e=>new rs(e?.response)))};initializePaymentMethod=e=>tm({...e,orgId:this.id});addPaymentMethod=e=>tp({...e,orgId:this.id});getPaymentMethods=e=>tg({...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=aR(e.created_at),this.updatedAt=aR(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:a}=e||{},t=(await aM._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:a},{forceUpdateClient:!0}))?.response;return this.fromJSON(t)}}class ro extends aM{id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:a,role:t}){return new ro((await aM._fetch({path:`/organizations/${e}/invitations`,method:"POST",body:{email_address:a,role:t}}))?.response)}static async createBulk(e,a){let{emailAddresses:t,role:r}=a;return((await aM._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:t,role:r}}))?.response).map(e=>new ro(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=aR(e.created_at),this.updatedAt=aR(e.updated_at)),this}}class rl extends aM{id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await aM._fetch({path:"/me/organization_memberships",method:"GET",search:a4({...e,paginated:!0})}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rl(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 rs(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new rb(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=aR(e.created_at),this.updatedAt=aR(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(`${aj} Calling OrganizationMembership.reload is not currently supported. Please contact support.`)}}class rc extends aM{id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await aM._fetch({path:"/me/organization_suggestions",method:"GET",search:a4(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rc(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=aR(e.created_at),this.updatedAt=aR(e.updated_at)),this}}function rd(){return l()&&"function"==typeof window.PublicKeyCredential}async function ru(){try{return rd()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function rh(){try{return"undefined"!=typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class rm extends aM{id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return aM._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new rm(e?.response))}static async attemptVerification(e,a){let t,r=(t=a.response,{...tK(a),response:{clientDataJSON:tJ(t.clientDataJSON),attestationObject:tJ(t.attestationObject),transports:t.getTransports()}});return aM._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(r)}}).then(e=>new rm(e?.response))}static async registerPasskey(){let e=rm.clerk.__internal_isWebAuthnSupported||rd,a=rm.clerk.__internal_createPublicCredentials||tD,t=rm.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||rh;if(!e())throw new A("Passkeys are not supported on this device.",{code:"passkey_not_supported"});let r=await this.create(),{verification:i}=r,n=i?.publicKey;if(n||aI("create"),n.authenticatorSelection?.authenticatorAttachment==="platform"&&!await t())throw new A("Registration requires a platform authenticator but the device does not support it.",{code:"passkey_pa_not_supported"});let{publicKeyCredential:s,error:o}=await a(n);if(!s)throw o;return this.attemptVerification(r.id,s)}update=e=>this._basePatch({body:e});delete=async()=>new tI((await aM._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?aR(e.last_used_at):null,this.createdAt=aR(e.created_at),this.updatedAt=aR(e.updated_at),e.verification&&(this.verification=new tH(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 rp extends aM{id;phoneNumber="";reservedForSecondFactor=!1;defaultSecondFactor=!1;linkedTo=[];verification;backupCodes;constructor(e,a){super(),this.pathRoot=a,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:a}=e||{};return this._basePost({action:"attempt_verification",body:{code:a}})};setReservedForSecondFactor=e=>{let{reserved:a}=e||{};return this._basePatch({body:{reserved_for_second_factor:a}})};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 tG(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new re(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 rg extends aM{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 rb{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 rf={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"}},ry=new Set(["first_factor","second_factor","multi_factor"]),rk=new Set(["strict_mfa","strict","moderate","lax"]),rw=(e,a)=>{let{org:t,user:r}=rv(e),[i,n]=a.split(":"),s=n||i;return"org"===i?t.includes(s):"user"===i?r.includes(s):[...t,...r].includes(s)},rv=e=>{let a=e?e.split(",").map(e=>e.trim()):[];return{org:a.filter(e=>e.split(":")[0].includes("o")).map(e=>e.split(":")[1]),user:a.filter(e=>e.split(":")[0].includes("u")).map(e=>e.split(":")[1])}};class rj extends aM{status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new tG(null);secondFactorVerification=new tG(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new rz(e.session),this.level=e.level,this.supportedFirstFactors=ea(e.supported_first_factors),this.supportedSecondFactors=ea(e.supported_second_factors),this.firstFactorVerification=new tG(e.first_factor_verification),this.secondFactorVerification=new tG(e.second_factor_verification)),this}}class rz extends aM{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 rz}constructor(e){super(),this.fromJSON(e),this.#es(this.lastActiveToken)}end=()=>(tU.clear(),this._basePost({action:"end"}));remove=()=>(tU.clear(),this._basePost({action:"remove"}));touch=()=>this._basePost({action:"touch",body:{active_organization_id:this.lastActiveOrganizationId}}).then(e=>(e.lastActiveToken&&t3.emit(t1,{token:e.lastActiveToken}),e));clearCache=()=>tU.clear();getToken=async e=>ar(()=>this._getToken(e),{factor:1.55,initialDelay:3e3,maxDelayBetweenRetries:5e4,jitter:!1,shouldRetry:(e,a)=>!I(e)&&a<=8});checkAuthorization=e=>{let a,t=(this.user?.organizationMemberships||[]).find(e=>e.organization.id===this.lastActiveOrganizationId);return(a={userId:this.user?.id,factorVerificationAge:this.factorVerificationAge,orgId:t?.id,orgRole:t?.role,orgPermissions:t?.permissions,features:this.lastActiveToken?.jwt?.claims.fea||"",plans:this.lastActiveToken?.jwt?.claims.pla||""},e=>{if(!a.userId)return!1;let t=((e,a)=>{let{features:t,plans:r}=a;return e.feature&&t?rw(t,e.feature):e.plan&&r?rw(r,e.plan):null})(e,a),r=((e,a)=>{let{orgId:t,orgRole:r,orgPermissions:i}=a;return(e.role||e.permission)&&t&&r&&i?e.permission?i.includes(e.permission.replace(/^(org:)*/,"org:")):e.role?r.replace(/^(org:)*/,"org:")===e.role.replace(/^(org:)*/,"org:"):null:null})(e,a),i=((e,{factorVerificationAge:a})=>{if(!e.reverification||!a)return null;let t=(e=>{let a,t;if(!e)return!1;let r="string"==typeof e&&rk.has(e),i="object"==typeof e&&(a=e.level,ry.has(a))&&"number"==typeof(t=e.afterMinutes)&&t>0;return(!!r||!!i)&&(e=>"string"==typeof e?rf[e]:e).bind(null,e)})(e.reverification);if(!t)return null;let{level:r,afterMinutes:i}=t(),[n,s]=a,o=-1!==n?i>n:null,l=-1!==s?i>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,a);return[t||r,i].some(e=>null===e)?[t||r,i].some(e=>!0===e):[t||r,i].every(e=>!0===e)})(e)};#es=e=>{e&&tU.set({tokenId:this.#eo(),tokenResolver:Promise.resolve(e)})};#eo(e,a){let t=void 0===a?this.lastActiveOrganizationId:a;return tz.build(this.id,e,t)}startVerification=async({level:e})=>new rj((await aM._fetch({method:"POST",path:`/client/sessions/${this.id}/verify`,body:{level:e}}))?.response);prepareFirstFactorVerification=async e=>{let a;switch(e.strategy){case"email_code":a={emailAddressId:e.emailAddressId};break;case"phone_code":a={phoneNumberId:e.phoneNumberId,default:e.default};break;case"passkey":a={};break;case"enterprise_sso":a={emailAddressId:e.emailAddressId,enterpriseConnectionId:e.enterpriseConnectionId,redirectUrl:e.redirectUrl};break;default:aS("Session.prepareFirstFactorVerification",e.strategy)}return new rj((await aM._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_first_factor`,body:{...a,strategy:e.strategy}}))?.response)};attemptFirstFactorVerification=async e=>{let a;return a="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(tB(e.publicKeyCredential))}:{...e},new rj((await aM._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_first_factor`,body:{...a,strategy:e.strategy}}))?.response)};verifyWithPasskey=async()=>{let{nonce:e=null}=(await this.prepareFirstFactorVerification({strategy:"passkey"})).firstFactorVerification,a=rz.clerk.__internal_isWebAuthnSupported||rd,t=rz.clerk.__internal_getPublicCredentials||tW;if(!a())throw new A("Passkeys are not supported",{code:"passkey_not_supported"});let r=e?t$(JSON.parse(e)):null;r||aI("get");let{publicKeyCredential:i,error:n}=await t({publicKeyOptions:r,conditionalUI:!1});if(!i)throw n;return this.attemptFirstFactorVerification({strategy:"passkey",publicKeyCredential:i})};prepareSecondFactorVerification=async e=>new rj((await aM._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>new rj((await aM._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=aR(e.expire_at),this.abandonAt=aR(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=aR(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.createdAt=aR(e.created_at),this.updatedAt=aR(e.updated_at),this.user=new rW(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new rb(e.public_user_data)),this.lastActiveToken=e.last_active_token?new rF(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:a,template:t,skipCache:r=!1}=e||{},i=void 0===e?.organizationId?this.lastActiveOrganizationId:e?.organizationId;if(!t&&Number(a)>=60)throw Error("Leeway can not exceed the token lifespan (60 seconds)");let n=this.#eo(t,i),s=r?void 0:tU.get({tokenId:n},a),o=!t&&i===this.lastActiveOrganizationId;if(s){e7.debug("Using cached token (no fetch needed)",{tokenId:n},"session");let e=await s.tokenResolver;return o&&t3.emit(t1,{token:e}),e.getRawString()||null}e7.info("Fetching new token from API",{organizationId:i,template:t,tokenId:n},"session");let l=t?`${this.path()}/tokens/${t}`:`${this.path()}/tokens`,c=t?{}:{organizationId:i},d=rF.create(l,c,r);return tU.set({tokenId:n,tokenResolver:d}),d.then(e=>(o&&(t3.emit(t1,{token:e}),e.jwt&&(this.lastActiveToken=e,t3.emit(t9,null))),e.getRawString()||null))}get currentTask(){let[e]=this.tasks??[];return e}}class r_ extends aM{pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,a){super(),this.pathRoot=a,this.fromJSON(e)}static retrieve(){let e=aM.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new r_(e,"/me/sessions"))).catch(()=>[])}revoke(){return this._basePost({action:"revoke",body:{}})}fromJSON(e){let a;return e?(this.id=e.id,this.status=e.status,this.expireAt=aR(e.expire_at),this.abandonAt=aR(e.abandon_at),this.lastActiveAt=aR(e.last_active_at||void 0),this.latestActivity={id:(a=e.latest_activity??{}).id,deviceType:a.device_type,browserName:a.browser_name,browserVersion:a.browser_version,country:a.country,city:a.city,isMobile:a.is_mobile,ipAddress:a.ip_address},this.actor=e.actor,this):this}}let rx=(e,a,t)=>{let{onValidation:r=e0,onValidationComplexity:i=e0}=t||{},{show_zxcvbn:n,validatePassword:s}=a,o=e=>((e,a)=>{let{max_length:t,min_length:r,require_special_char:i,require_lowercase:n,require_numbers:s,require_uppercase:o}=a,l=(e=>{let a;if(e.allowed_special_characters){let t=e.allowed_special_characters.replace("[","\\[");t=t.replace("]","\\]"),a=RegExp(`[${t}]`)}else a=/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/;return(e,{minLength:t,maxLength:r})=>({max_length:e.length<r,min_length:e.length>=t,require_numbers:/\d/.test(e),require_lowercase:/[a-z]/.test(e),require_uppercase:/[A-Z]/.test(e),require_special_char:a.test(e)})})(a)(e,{maxLength:a.max_length,minLength:a.min_length}),c={max_length:t,min_length:r,require_special_char:i,require_lowercase:n,require_numbers:s,require_uppercase:o},d=new Map;for(let e in c)c[e]&&!l[e]&&d.set(e,!0);return Object.freeze(Object.fromEntries(d))})(e,a),l=(({min_zxcvbn_strength:e,onResult:a})=>t=>r=>{let i=t(r);return(a?.(i),i.score>=e&&i.score<3)?{state:"pass",keys:["unstable__errors.zxcvbn.couldBeStronger"],result:i}:i.score>=e?{state:"excellent",result:i}:{state:"fail",keys:["unstable__errors.zxcvbn.notEnough",...i.feedback.suggestions.map(e=>`unstable__errors.zxcvbn.suggestions.${e}`)],result:i}})(a),c={};return(a,t)=>{let{onValidation:d=r,onValidationComplexity:u=i}=t||{};if(!s)return;let h=o(a);u(0===Object.keys(h).length),c={...c,complexity:h},n&&e().then(e=>{let t=l(e)(a);d({...c={...c,strength:t},strength:t})}),c.complexity&&0===Object.keys(c.complexity).length&&n||d(c)}};function rq(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function rS(e,a,t,r,i){if(!e.client||!r.popup)return;let n=rq(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",a);let l=e.buildUrlWithAuth(o.toString()),c=e.buildUrlWithAuth(`${n}/popup-callback`),d=e.buildUrlWithAuth(`${n}/popup-callback?return_url=${encodeURIComponent(l)}`),u=async a=>{if(a.origin!==n)return;let t=!1;if(a.data.session){if(!e.client?.sessions.find(e=>e.id===a.data.session))try{await e.client?.reload()}catch(e){console.error(e)}await e.setActive({session:a.data.session,redirectUrl:r.redirectUrlComplete}),t=!0}else a.data.return_url&&(e.navigate(a.data.return_url),t=!0);t&&window.removeEventListener("message",u)};window.addEventListener("message",u),await t({...r,redirectUrlComplete:c,redirectUrl:d},i)}function rU(e,{redirectCallbackUrl:a,redirectUrl:t}){let r=rq(e.frontendApi),i=new URL(a);i.searchParams.set("sign_in_force_redirect_url",t),i.searchParams.set("sign_up_force_redirect_url",t);let n=e.buildUrlWithAuth(i.toString()),s=e.buildUrlWithAuth(`${r}/popup-callback`);return{redirectCallbackUrl:e.buildUrlWithAuth(`${r}/popup-callback?return_url=${encodeURIComponent(n)}`),redirectUrl:s}}function rA(e,a){return new Promise((t,r)=>{if(!e.client||!a.popup)return void r();let i=async a=>{a.origin===rq(e.frontendApi)&&(a.data.session||a.data.return_url?(window.removeEventListener("message",i),t()):r())};window.addEventListener("message",i),a.popup.location.href=a.externalVerificationRedirectURL.toString()})}async function rC(e,a){t3.emit("resource:error",{resource:e,error:null}),t3.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await a(),error:null}}catch(a){return t3.emit("resource:error",{resource:e,error:a}),{error:a}}finally{t3.emit("resource:fetch",{resource:e,status:"idle"})}}let rI=()=>{var e;return(e=new an,{loadZxcvbn:()=>Promise.all([e.import("@zxcvbn-ts/core"),e.import("@zxcvbn-ts/language-common")]).then(([e,a])=>{if(!e||!a)throw Error("Failed to load zxcvbn modules");let{zxcvbnOptions:t,zxcvbn:r}=e,{dictionary:i,adjacencyGraphs:n}=a;return t.setOptions({dictionary:{...i},graphs:n}),r})}).loadZxcvbn};class rP extends aM{pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;firstFactorVerification=new tG(null);secondFactorVerification=new tG(null);identifier=null;createdSessionId=null;userData=new rL(null);clientTrustState;get status(){return this._status}set status(e){let a=this._status;this._status=e,e&&a!==e&&e7.debug("SignIn.status",{id:this.id,from:a,to:e})}__internal_future=new rO(this);__internal_basePost=this._basePost.bind(this);__internal_baseGet=this._baseGet.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=e=>{e7.debug("SignIn.create",{id:this.id,strategy:"strategy"in e?e.strategy:void 0});let a=am();return this._basePost({path:this.pathRoot,body:a?{locale:a,...e}:e})};resetPassword=e=>this._basePost({body:e,action:"reset_password"});prepareFirstFactor=e=>{let a;switch(e7.debug("SignIn.prepareFirstFactor",{id:this.id,strategy:e.strategy}),e.strategy){case"passkey":a={};break;case"email_link":a={emailAddressId:e.emailAddressId,redirectUrl:e.redirectUrl};break;case"email_code":case"reset_password_email_code":a={emailAddressId:e.emailAddressId};break;case"phone_code":a={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":a={web3WalletId:e.web3WalletId};break;case"reset_password_phone_code":a={phoneNumberId:e.phoneNumberId};break;case"enterprise_sso":a={redirectUrl:e.redirectUrl,actionCompleteRedirectUrl:e.actionCompleteRedirectUrl,oidcPrompt:e.oidcPrompt,enterpriseConnectionId:e.enterpriseConnectionId};break;default:aS("SignIn.prepareFirstFactor",e.strategy)}return this._basePost({body:{...a,strategy:e.strategy},action:"prepare_first_factor"})};attemptFirstFactor=e=>{let a;return e7.debug("SignIn.attemptFirstFactor",{id:this.id,strategy:e.strategy}),a="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(tB(e.publicKeyCredential))}:{...e},this._basePost({body:{...a,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:a}=tM();return{startEmailLinkFlow:async({emailAddressId:t,redirectUrl:r})=>{this.id||aq("SignIn");let i={strategy:"email_link",emailAddressId:t,redirectUrl:r},n="needs_second_factor"===this.status,s=n?"secondFactorVerification":"firstFactorVerification";return n?await this.prepareSecondFactor(i):await this.prepareFirstFactor(i),new Promise((t,r)=>{e(()=>this.reload().then(e=>{let r=e[s].status;("verified"===r||"expired"===r)&&(a(),t(e))}).catch(e=>{a(),r(e)}))})},cancelEmailLinkFlow:a}};prepareSecondFactor=e=>(e7.debug("SignIn.prepareSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_second_factor"}));attemptSecondFactor=e=>(e7.debug("SignIn.attemptSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_second_factor"}));authenticateWithRedirectOrPopup=async(e,a)=>{let{strategy:t,redirectUrlComplete:r,identifier:i,oidcPrompt:n,continueSignIn:s,enterpriseConnectionId:o}=e||{},l=rP.clerk.buildUrlWithAuth(e.redirectUrl);this.id&&s||await this.create({strategy:t,identifier:i,redirectUrl:l,actionCompleteRedirectUrl:r}),"enterprise_sso"===t&&await this.prepareFirstFactor({strategy:t,redirectUrl:l,actionCompleteRedirectUrl:r,oidcPrompt:n,enterpriseConnectionId:o});let{status:c,externalVerificationRedirectURL:d}=this.firstFactorVerification;"unverified"===c&&d?a(d):aC(c,rP.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eW);authenticateWithPopup=async e=>{let{popup:a}=e||{};return a||aA("popup"),rS(rP.clerk,"signIn",this.authenticateWithRedirectOrPopup,e,e=>{a.location.href=e.toString()})};authenticateWithWeb3=async e=>{let a,{identifier:t,generateSignature:r,strategy:i="web3_metamask_signature"}=e||{},n=i.replace("web3_","").replace("_signature","");"function"!=typeof r&&aA("generateSignature"),await this.create({identifier:t});let s=this.supportedFirstFactors?.find(e=>e.strategy===i);s||aU("SignIn"),await this.prepareFirstFactor(s);let{message:o}=this.firstFactorVerification;o||aU("SignIn");try{a=await r({identifier:t,nonce:o,provider:n})}catch(e){if("coinbase_wallet"===n&&4001===e.code)a=await r({identifier:t,nonce:o,provider:n});else throw e}return this.attemptFirstFactor({signature:a,strategy:i})};authenticateWithMetamask=async()=>{let e=await af().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:af().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await af().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:af().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await af().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:af().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await af().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:af().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithPasskey=async e=>{let{flow:a}=e||{},t=rP.clerk.__internal_isWebAuthnSupported||rd,r=rP.clerk.__internal_getPublicCredentials||tW,i=rP.clerk.__internal_isWebAuthnAutofillSupported||ru;if(!t())throw new A("Passkeys are not supported",{code:"passkey_not_supported"});if("autofill"===a||"discoverable"===a)await this.create({strategy:"passkey"});else{let e=this.supportedFirstFactors.find(e=>"passkey"===e.strategy);e||function(){throw Error(`${aj} You need to start a SignIn flow by calling SignIn.create({ strategy: 'passkey' }) first`)}(),await this.prepareFirstFactor(e)}let{nonce:n}=this.firstFactorVerification,s=n?t$(JSON.parse(n)):null;s||aI("get");let o=!1;"autofill"===a&&(o=await i());let{publicKeyCredential:l,error:c}=await r({publicKeyOptions:s,conditionalUI:o});if(!l)throw c;return this.attemptFirstFactor({publicKeyCredential:l,strategy:"passkey"})};validatePassword=(e,a)=>{if(rP.clerk.__unstable__environment?.userSettings.passwordSettings)return rx(rI(),{...rP.clerk.__unstable__environment?.userSettings.passwordSettings,validatePassword:!0})(e,a)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.supportedIdentifiers=e.supported_identifiers,this.identifier=e.identifier,this.supportedFirstFactors=ea(e.supported_first_factors),this.supportedSecondFactors=ea(e.supported_second_factors),this.firstFactorVerification=new tG(e.first_factor_verification),this.secondFactorVerification=new tG(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new rL(e.user_data),this.clientTrustState=e.client_trust_state??void 0),t3.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:ee(this.supportedFirstFactors),supported_second_factors:ee(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 rO{resource;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(!s())return null;const e=eI("__clerk_status"),a=eI("__clerk_created_session");if(!e||!a)return null;const t="verified"===e&&void 0!==rP.clerk.client&&rP.clerk.client.sessions.some(e=>e.id===a);return{status:e,createdSessionId:a,verifiedFromTheSameClient:t}}};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)};#el=!1;constructor(e){this.resource=e}get id(){return this.resource.id}get identifier(){return this.resource.identifier}get createdSessionId(){return this.resource.createdSessionId}get userData(){return this.resource.userData}get status(){return this.resource.status||"needs_identifier"}get supportedFirstFactors(){return this.resource.supportedFirstFactors??[]}get supportedSecondFactors(){return this.resource.supportedSecondFactors??[]}get isTransferable(){return"transferable"===this.resource.firstFactorVerification.status}get existingSession(){if("failed"===this.resource.firstFactorVerification.status&&this.resource.firstFactorVerification.error?.code==="identifier_already_signed_in"&&this.resource.firstFactorVerification.error?.meta?.sessionId)return{sessionId:this.resource.firstFactorVerification.error?.meta?.sessionId}}get firstFactorVerification(){return this.resource.firstFactorVerification}get secondFactorVerification(){return this.resource.secondFactorVerification}get hasBeenFinalized(){return this.#el}async sendResetPasswordEmailCode(){if(!this.resource.id)throw Error("Cannot reset password without a sign in.");return rC(this.resource,async()=>{let e=this.resource.supportedFirstFactors?.find(e=>"reset_password_email_code"===e.strategy);if(!e)throw new S("Reset password email code factor not found",{code:"factor_not_found"});let{emailAddressId:a}=e;await this.resource.__internal_basePost({body:{emailAddressId:a,strategy:"reset_password_email_code"},action:"prepare_first_factor"})})}async verifyResetPasswordEmailCode(e){let{code:a}=e;return rC(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"reset_password_email_code"},action:"attempt_first_factor"})})}async submitResetPassword(e){let{password:a,signOutOfOtherSessions:t=!0}=e;return rC(this.resource,async()=>{await this.resource.__internal_basePost({body:{password:a,signOutOfOtherSessions:t},action:"reset_password"})})}async _create(e){let a=am();await this.resource.__internal_basePost({path:this.resource.pathRoot,body:a?{locale:a,...e}:e})}async create(e){return rC(this.resource,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 rC(this.resource,async()=>{let a=e.identifier||e.emailAddress||e.phoneNumber,t=this.resource.identifier,r=am();await this.resource.__internal_basePost({path:this.resource.pathRoot,body:{identifier:a||t,password:e.password,...r?{locale:r}:{}}})})}async sendEmailCode(e={}){let{emailAddress:a,emailAddressId:t}=e;if(!this.resource.id&&t)throw Error("signIn.emailCode.sendCode() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.resource.id&&!a)throw Error("signIn.emailCode.sendCode() cannot be called without an emailAddress if an existing signIn does not exist.");return rC(this.resource,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"email_code",emailAddressId:t});if(!e)throw new S("Email code factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{emailAddressId:e.emailAddressId,strategy:"email_code"},action:"prepare_first_factor"})})}async verifyEmailCode(e){let{code:a}=e;return rC(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"email_code"},action:"attempt_first_factor"})})}async sendEmailLink(e){let{emailAddress:a,verificationUrl:t,emailAddressId:r}=e;if(!this.resource.id&&r)throw Error("signIn.emailLink.sendLink() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.resource.id&&!a)throw Error("signIn.emailLink.sendLink() cannot be called without an emailAddress if an existing signIn does not exist.");return rC(this.resource,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"email_link",emailAddressId:r});if(!e)throw new S("Email link factor not found",{code:"factor_not_found"});let i=t;try{new URL(t)}catch{i=window.location.origin+t}await this.resource.__internal_basePost({body:{emailAddressId:e.emailAddressId,redirectUrl:i,strategy:"email_link"},action:"prepare_first_factor"})})}async waitForEmailLinkVerification(){return rC(this.resource,async()=>{let{run:e,stop:a}=tM();await new Promise((t,r)=>{e(async()=>{try{let e=await this.resource.__internal_baseGet(),r=e.firstFactorVerification.status;("verified"===r||"expired"===r)&&(a(),t(e))}catch(e){a(),r(e)}})})})}async sendPhoneCode(e={}){let{phoneNumber:a,phoneNumberId:t,channel:r="sms"}=e;if(!this.resource.id&&t)throw Error("signIn.phoneCode.sendCode() cannot be called with an phoneNumberId if an existing signIn does not exist.");if(!this.resource.id&&!a)throw Error("signIn.phoneCode.sendCode() cannot be called without an phoneNumber if an existing signIn does not exist.");return rC(this.resource,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"phone_code",phoneNumberId:t});if(!e)throw new S("Phone code factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{phoneNumberId:e.phoneNumberId,strategy:"phone_code",channel:r},action:"prepare_first_factor"})})}async verifyPhoneCode(e){let{code:a}=e;return rC(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"phone_code"},action:"attempt_first_factor"})})}async sso(e){let{strategy:a,redirectUrl:t,redirectCallbackUrl:r,popup:i,oidcPrompt:n,enterpriseConnectionId:s,identifier:o}=e;return rC(this.resource,async()=>{let e=t;try{new URL(t)}catch{e=window.location.origin+t}let l={redirectUrl:rP.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:e};if(i){let a=rU(rP.clerk,{redirectCallbackUrl:l.redirectUrl,redirectUrl:e});l.redirectUrl=a.redirectCallbackUrl,l.actionCompleteRedirectUrl=a.redirectUrl}await this._create({strategy:a,...l,identifier:o}),"enterprise_sso"===a&&await this.resource.__internal_basePost({body:{...l,oidcPrompt:n,enterpriseConnectionId:s,strategy:"enterprise_sso"},action:"prepare_first_factor"});let{status:c,externalVerificationRedirectURL:d}=this.resource.firstFactorVerification;"unverified"===c&&d&&(i?(await rA(rP.clerk,{popup:i,externalVerificationRedirectURL:d}),await this.resource.reload()):eW(d))})}async web3(e){let{strategy:a}=e,t=a.replace("web3_","").replace("_signature","");return rC(this.resource,async()=>{let e,r,i;switch(t){case"metamask":e=await af().getMetamaskIdentifier(),r=af().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await af().getCoinbaseWalletIdentifier(),r=af().generateSignatureWithCoinbaseWallet;break;case"base":e=await af().getBaseIdentifier(),r=af().generateSignatureWithBase;break;case"okx_wallet":e=await af().getOKXWalletIdentifier(),r=af().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${t}`)}await this._create({identifier:e});let n=this.resource.supportedFirstFactors?.find(e=>e.strategy===a);if(!n)throw new S("Web3 first factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{web3WalletId:n.web3WalletId,strategy:a},action:"prepare_first_factor"});let{message:s}=this.firstFactorVerification;if(!s)throw new S("Web3 nonce not found",{code:"web3_nonce_not_found"});try{i=await r({identifier:e,nonce:s})}catch(a){if("coinbase_wallet"===t&&4001===a.code)i=await r({identifier:e,nonce:s});else throw a}await this.resource.__internal_basePost({body:{signature:i,strategy:a},action:"attempt_first_factor"})})}async passkey(e){let{flow:a}=e||{},t=rP.clerk.__internal_isWebAuthnSupported||rd,r=rP.clerk.__internal_getPublicCredentials||tW,i=rP.clerk.__internal_isWebAuthnAutofillSupported||ru;if(!t())throw new A("Passkeys are not supported",{code:"passkey_not_supported"});return rC(this.resource,async()=>{if("autofill"===a||"discoverable"===a)await this._create({strategy:"passkey"});else{if(!this.supportedFirstFactors.find(e=>"passkey"===e.strategy))throw new S("Passkey factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{strategy:"passkey"},action:"prepare_first_factor"})}let{nonce:e}=this.firstFactorVerification,t=e?t$(JSON.parse(e)):null;if(!t)throw new S("Missing public key options",{code:"missing_public_key_options"});let n=!1;"autofill"===a&&(n=await i());let{publicKeyCredential:s,error:o}=await r({publicKeyOptions:t,conditionalUI:n});if(!s)throw new A(o.message,{code:"passkey_retrieval_failed"});await this.resource.__internal_basePost({body:{publicKeyCredential:JSON.stringify(tB(s)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return rC(this.resource,async()=>{let e=this.resource.supportedSecondFactors?.find(e=>"phone_code"===e.strategy);if(!e)throw new S("Phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:a}=e;await this.resource.__internal_basePost({body:{phoneNumberId:a,strategy:"phone_code"},action:"prepare_second_factor"})})}async verifyMFAPhoneCode(e){let{code:a}=e;return rC(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"phone_code"},action:"attempt_second_factor"})})}async verifyTOTP(e){let{code:a}=e;return rC(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"totp"},action:"attempt_second_factor"})})}async verifyBackupCode(e){let{code:a}=e;return rC(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:a,strategy:"backup_code"},action:"attempt_second_factor"})})}async ticket(e){let a=e?.ticket??eI("__clerk_ticket");return this.create({ticket:a??void 0})}async finalize(e){let{navigate:a}=e||{};if(!this.resource.createdSessionId)throw Error("Cannot finalize sign-in without a created session.");return rC(this.resource,async()=>{rP.clerk.client&&!rP.clerk.client.sessions.some(e=>e.id===this.resource.createdSessionId)&&await rP.clerk.client.reload(),this.#el=!0,await rP.clerk.setActive({session:this.resource.createdSessionId,navigate:a})})}selectFirstFactor({strategy:e,emailAddressId:a,phoneNumberId:t}){if(!this.resource.supportedFirstFactors)return null;if(a){let t=this.resource.supportedFirstFactors.find(t=>t.strategy===e&&t.emailAddressId===a);if(t)return t}if(t){let a=this.resource.supportedFirstFactors.find(a=>a.strategy===e&&a.phoneNumberId===t);if(a)return a}let r=this.resource.supportedFirstFactors.find(a=>a.strategy===e&&a.safeIdentifier===this.resource.identifier);if(r)return r;let i=this.resource.supportedFirstFactors.find(a=>a.strategy===e);return i||null}}function rT(e){let{unsafeMetadata:a}={...e},t=a?"object"==typeof a?JSON.stringify(a):a:"";return{...e,...a?{unsafeMetadata:t}:{}}}class rE extends aM{pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new tQ(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 a=this._status;this._status=e,e&&a!==e&&e7.debug("SignUp.status",{id:this.id,from:a,to:e})}__internal_future=new rM(this);__internal_basePost=this._basePost.bind(this);__internal_basePatch=this._basePatch.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{e7.debug("SignUp.create",{id:this.id,strategy:e.strategy});let a={...e};if(!a.locale){let e=am();e&&(a.locale=e)}if(a.transfer&&this.shouldBypassCaptchaForAttempt(a)){let e=rE.clerk.client?.signIn.firstFactorVerification.strategy;e&&(a={...a,strategy:e})}return this._basePost({path:this.pathRoot,body:rT(a)})};prepareVerification=e=>(e7.debug("SignUp.prepareVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_verification"}));attemptVerification=e=>(e7.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:a}=tM();return{startEmailLinkFlow:async({redirectUrl:t})=>(this.id||aq("SignUp"),await this.prepareEmailAddressVerification({strategy:"email_link",redirectUrl:t}),new Promise((t,r)=>{e(()=>this.reload().then(e=>{let r=e.verifications.emailAddress.status;("verified"===r||"expired"===r)&&(a(),t(e))}).catch(e=>{a(),r(e)}))})),cancelEmailLinkFlow:a}};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:a,strategy:t="web3_metamask_signature"}=e;return this.attemptVerification({signature:a,strategy:t})};authenticateWithWeb3=async e=>{let a,{generateSignature:t,identifier:r,unsafeMetadata:i,strategy:n="web3_metamask_signature",legalAccepted:s}=e||{},o=n.replace("web3_","").replace("_signature","");"function"!=typeof t&&aA("generateSignature");let l=r||this.web3wallet;await this.create({web3Wallet:l,unsafeMetadata:i,legalAccepted:s}),await this.prepareWeb3WalletVerification({strategy:n});let{message:c}=this.verifications.web3Wallet;c||aU("SignUp");try{a=await t({identifier:r,nonce:c,provider:o})}catch(e){if("coinbase_wallet"===o&&4001===e.code)a=await t({identifier:r,nonce:c,provider:o});else throw e}return this.attemptWeb3WalletVerification({signature:a,strategy:n})};authenticateWithMetamask=async e=>{let a=await af().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:af().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let a=await af().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:af().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let a=await af().getBaseIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:af().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let a=await af().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:af().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithRedirectOrPopup=async(e,a)=>{let{redirectUrl:t,redirectUrlComplete:r,strategy:i,continueSignUp:n=!1,unsafeMetadata:s,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:d}=e,u=rE.clerk.buildUrlWithAuth(t),h=()=>{let e={strategy:i,redirectUrl:u,actionCompleteRedirectUrl:r,unsafeMetadata:s,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:d};return n&&this.id?this.update(e):this.create(e)},{verifications:m}=await h().catch(async e=>{if(O(e)&&C(e))return await rE.clerk.__unstable__environment.reload(),h();throw e}),{externalAccount:p}=m,{status:g,externalVerificationRedirectURL:b}=p;"unverified"===g&&b?a(b):aC(g,rE.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eW);authenticateWithPopup=async e=>{let{popup:a}=e||{};return a||aA("popup"),rS(rE.clerk,"signUp",this.authenticateWithRedirectOrPopup,e,e=>{a.location.href=e instanceof URL?e.toString():e})};update=e=>this._basePatch({body:rT(e)});upsert=e=>this.id?this.update(e):this.create(e);validatePassword=(e,a)=>{if(rE.clerk.__unstable__environment?.userSettings.passwordSettings)return rx(rI(),{...rE.clerk.__unstable__environment?.userSettings.passwordSettings,validatePassword:!0})(e,a)};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 tQ(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),t3.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 rE.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){if(!e.strategy)return!1;let a=rE.clerk.__unstable__environment.displayConfig.captchaOauthBypass;return!!(a.some(a=>a===e.strategy)||e.transfer&&a.some(e=>e===rE.clerk.client.signIn.firstFactorVerification.strategy))}__experimental_getEnterpriseConnections=()=>aM._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new rR(e)))}class rM{resource;verifications={sendEmailCode:this.sendEmailCode.bind(this),verifyEmailCode:this.verifyEmailCode.bind(this),sendPhoneCode:this.sendPhoneCode.bind(this),verifyPhoneCode:this.verifyPhoneCode.bind(this)};#el=!1;constructor(e){this.resource=e}get id(){return this.resource.id}get requiredFields(){return this.resource.requiredFields}get optionalFields(){return this.resource.optionalFields}get missingFields(){return this.resource.missingFields}get status(){return this.resource.status||"missing_requirements"}get username(){return this.resource.username}get firstName(){return this.resource.firstName}get lastName(){return this.resource.lastName}get emailAddress(){return this.resource.emailAddress}get phoneNumber(){return this.resource.phoneNumber}get web3Wallet(){return this.resource.web3wallet}get hasPassword(){return this.resource.hasPassword}get unsafeMetadata(){return this.resource.unsafeMetadata}get createdSessionId(){return this.resource.createdSessionId}get createdUserId(){return this.resource.createdUserId}get abandonAt(){return this.resource.abandonAt}get legalAcceptedAt(){return this.resource.legalAcceptedAt}get locale(){return this.resource.locale}get unverifiedFields(){return this.resource.unverifiedFields}get isTransferable(){return"transferable"===this.resource.verifications.externalAccount.status&&this.resource.verifications.externalAccount.error?.code==="external_account_exists"}get existingSession(){if(("failed"===this.resource.verifications.externalAccount.status||"unverified"===this.resource.verifications.externalAccount.status)&&this.resource.verifications.externalAccount.error?.code==="identifier_already_signed_in"&&this.resource.verifications.externalAccount.error?.meta?.sessionId)return{sessionId:this.resource.verifications.externalAccount.error?.meta?.sessionId}}get hasBeenFinalized(){return this.#el}async getCaptchaToken(){let e=new aT(rE.clerk),a=await e.managedOrInvisible({action:"signup"});if(!a)throw Error("Captcha challenge failed");let{captchaError:t,captchaToken:r,captchaWidgetType:i}=a;return{captchaToken:r,captchaWidgetType:i,captchaError:t}}async _create(e){let{captchaToken:a,captchaWidgetType:t,captchaError:r}=await this.getCaptchaToken(),i={transfer:e.transfer,captchaToken:a,captchaWidgetType:t,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rT(e.unsafeMetadata):void 0,locale:e.locale??am()};await this.resource.__internal_basePost({path:this.resource.pathRoot,body:i})}async create(e){return rC(this.resource,async()=>{await this._create(e)})}async update(e){return rC(this.resource,async()=>{let a={...e,unsafeMetadata:e.unsafeMetadata?rT(e.unsafeMetadata):void 0};await this.resource.__internal_basePatch({path:this.resource.pathRoot,body:a})})}async password(e){return rC(this.resource,async()=>{let{captchaToken:a,captchaWidgetType:t,captchaError:r}=await this.getCaptchaToken(),i={strategy:"password",captchaToken:a,captchaWidgetType:t,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rT(e.unsafeMetadata):void 0};await this.resource.__internal_basePost({path:this.resource.pathRoot,body:i})})}async sendEmailCode(){return rC(this.resource,async()=>{await this.resource.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification"})})}async verifyEmailCode(e){let{code:a}=e;return rC(this.resource,async()=>{await this.resource.__internal_basePost({body:{strategy:"email_code",code:a},action:"attempt_verification"})})}async sendPhoneCode(e){let{phoneNumber:a,channel:t="sms"}=e;return rC(this.resource,async()=>{if(!this.resource.id){let{captchaToken:e,captchaWidgetType:t,captchaError:r}=await this.getCaptchaToken();await this.resource.__internal_basePost({path:this.resource.pathRoot,body:{phoneNumber:a,captchaToken:e,captchaWidgetType:t,captchaError:r}})}await this.resource.__internal_basePost({body:{strategy:"phone_code",channel:t},action:"prepare_verification"})})}async verifyPhoneCode(e){let{code:a}=e;return rC(this.resource,async()=>{await this.resource.__internal_basePost({body:{strategy:"phone_code",code:a},action:"attempt_verification"})})}async sso(e){let{strategy:a,redirectUrl:t,redirectCallbackUrl:r,unsafeMetadata:i,legalAccepted:n,oidcPrompt:s,enterpriseConnectionId:o,emailAddress:l,popup:c}=e;return rC(this.resource,async()=>{let{captchaToken:e,captchaWidgetType:d,captchaError:u}=await this.getCaptchaToken(),h=t;try{new URL(t)}catch{h=window.location.origin+t}let m={redirectUrl:rE.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:h};if(c){let e=rU(rE.clerk,{redirectCallbackUrl:m.redirectUrl,redirectUrl:h});m.redirectUrl=e.redirectCallbackUrl,m.actionCompleteRedirectUrl=e.redirectUrl}let p=()=>this.resource.__internal_basePost({path:this.resource.pathRoot,body:{strategy:a,...m,unsafeMetadata:i,legalAccepted:n,oidcPrompt:s,enterpriseConnectionId:o,emailAddress:l,captchaToken:e,captchaWidgetType:d,captchaError:u}});await p().catch(async e=>{if(O(e)&&C(e))return await rE.clerk.__unstable__environment.reload(),p();throw e});let{status:g,externalVerificationRedirectURL:b}=this.resource.verifications.externalAccount;"unverified"===g&&b&&(c?(await rA(rE.clerk,{popup:c,externalVerificationRedirectURL:b}),await this.resource.reload()):eW(b))})}async web3(e){let{strategy:a,unsafeMetadata:t,legalAccepted:r}=e,i=a.replace("web3_","").replace("_signature","");return rC(this.resource,async()=>{let e,n,s;switch(i){case"metamask":e=await af().getMetamaskIdentifier(),n=af().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await af().getCoinbaseWalletIdentifier(),n=af().generateSignatureWithCoinbaseWallet;break;case"base":e=await af().getBaseIdentifier(),n=af().generateSignatureWithBase;break;case"okx_wallet":e=await af().getOKXWalletIdentifier(),n=af().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${i}`)}let o=e||this.resource.web3wallet;await this._create({web3Wallet:o,unsafeMetadata:t,legalAccepted:r}),await this.resource.__internal_basePost({body:{strategy:a},action:"prepare_verification"});let{message:l}=this.resource.verifications.web3Wallet;l||aU("SignUp");try{s=await n({identifier:e,nonce:l})}catch(a){if("coinbase_wallet"===i&&4001===a.code)s=await n({identifier:e,nonce:l});else throw a}await this.resource.__internal_basePost({body:{signature:s,strategy:a},action:"attempt_verification"})})}async ticket(e){let a=e?.ticket??eI("__clerk_ticket");return this.create({...e,ticket:a??void 0})}async finalize(e){let{navigate:a}=e||{};return rC(this.resource,async()=>{if(!this.resource.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#el=!0,await rE.clerk.setActive({session:this.resource.createdSessionId,navigate:a})})}}class rR extends aM{id;name;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name),this}}class rF extends aM{pathRoot="tokens";jwt;static async create(e,a={},t=!1){return new rF(await aM._fetch({body:a,method:"POST",path:e,search:t?"debug=skip_cache":void 0}),e)}constructor(e,a){super(),a&&(this.pathRoot=a),e?.jwt&&(this.jwt=ah(e.jwt))}getRawString=()=>this.jwt?.claims.__raw||"";fromJSON(e){return e&&(this.jwt=ah(e.jwt)),this}__internal_toSnapshot(){return{object:"token",id:this.id||"",jwt:this.getRawString()}}}class rD extends aM{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=aR(e.updated_at),this.createdAt=aR(e.created_at)),this}}class rN extends aM{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=aR(e.updated_at),this.createdAt=aR(e.created_at)),this}}class rW extends aM{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 rW}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case tR:return this.primaryEmailAddressId===e.id;case rp:return this.primaryPhoneNumberId===e.id;case rV:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:a}=e||{};return new tR({email_address:a},this.path()+"/email_addresses/").create()};createPasskey=()=>rm.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:a}=e||{};return new rp({phone_number:a},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:a}=e||{};return new rV({web3_wallet:a},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:a,redirectUrl:t,additionalScopes:r}=e||{};return new t6((await aM._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:a,redirect_url:t,additional_scope:r}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new rD((await aM._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new rD((await aM._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new tI((await aM._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new rN((await aM._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);update=e=>this._basePatch({body:rT(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=>(t3.emit(t2,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await r_.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:a}=e||{};return null===a?ra.delete(`${this.path()}/profile_image`):ra.create(`${this.path()}/profile_image`,{file:a})};getOrganizationInvitations=e=>r$.retrieve(e);getOrganizationSuggestions=e=>rc.retrieve(e);getOrganizationMemberships=e=>rl.retrieve(e);leaveOrganization=async e=>new tI((await aM._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);initializePaymentMethod=e=>tm(e);addPaymentMethod=e=>tp(e);getPaymentMethods=e=>tg(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:a,name:t})=>t||[e,a].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 tR(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 rp(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 rV(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 t6(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new rm(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new rl(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new tX(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=aR(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=aR(e.legal_accepted_at)),this.updatedAt=aR(e.updated_at||void 0),this.createdAt=aR(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 rL{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 r$ extends aM{id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await aM._fetch({path:"/me/organization_invitations",method:"GET",search:a4(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new r$(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=aR(e.created_at),this.updatedAt=aR(e.updated_at)),this}}let rK={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 rB extends aM{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:{...rK,name:"phone_number"},username:{...rK,name:"username"},web3_wallet:{...rK,name:"web3_wallet"},first_name:{...rK,name:"first_name"},last_name:{...rK,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:{...rK,name:"authenticator_app"},backup_code:{...rK,name:"backup_code"},passkey:{...rK,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,a])=>a.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,a])=>a.used_for_first_factor&&e.startsWith("web3")).map(([,e])=>e.first_factors).flat():[]}get alternativePhoneCodeChannels(){return this.attributes?Object.entries(this.attributes).filter(([e,a])=>a.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 rJ extends aM{pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=aR(e.updated_at),this.createdAt=aR(e.created_at)),this}static async join(e){return new rJ((await aM._fetch({path:"/waitlist",method:"POST",body:e}))?.response)}}class rV extends aM{id;web3Wallet="";verification;constructor(e,a){super(),this.pathRoot=a,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:a}=e;return this._basePost({action:"attempt_verification",body:{signature:a}})};destroy(){return this._baseDelete()}toString(){return this.web3Wallet}fromJSON(e){return e&&(this.id=e.id,this.web3Wallet=e.web3_wallet,this.verification=new tG(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}function rG(e,a){var t,r;return e.id!==a.id||e.updatedAt.getTime()<a.updatedAt.getTime()||(t=a,r=e,t.organizationMemberships.length!==r.organizationMemberships.length||t.organizationMemberships[0]?.updatedAt!==r.organizationMemberships[0]?.updatedAt)}function rH(e,a){return!function(e,a){if(!e&&a||e&&!a)return!0;if(!e&&e===a)return!1;if(!e||!a)return!0;try{if(tA.isClientResource(e))return e.id!==a.id||e.updatedAt.getTime()<a.updatedAt.getTime()||e.sessions.length!==a.sessions.length;if(rz.isSessionResource(e)){var t,r;return e.id!==a.id||e.updatedAt.getTime()<a.updatedAt.getTime()||e.lastActiveToken?.jwt?.claims?.__raw!==a.lastActiveToken?.jwt?.claims?.__raw||function(e,a){if(e.lastActiveOrganizationId!==a.lastActiveOrganizationId)return!0;let t=e.user?.organizationMemberships?.find(a=>a.organization.id===e.lastActiveOrganizationId),r=a.user?.organizationMemberships?.find(a=>a.organization.id===e.lastActiveOrganizationId);return t?.permissions?.length!==r?.permissions?.length}(e,a)||(t=e,r=a,!!t.user!=!!r.user||!!t.user&&!!r.user&&rG(t.user,r.user))}if(rW.isUserResource(e))return rG(e,a)}catch{}return!0}(e,a)?e:a}let rQ="__clerk_db_jwt";function rY(e,a){let t=new URL(e),r=t.searchParams.get(rQ);t.searchParams.delete(rQ);let i=r||a;return i&&t.searchParams.set(rQ,i),t}let rX=e=>{let a=new URL(e);return a.searchParams.delete(rQ),a},rZ=e=>{let a=new URL(e);return a.searchParams.delete("__dev_session"),a.hash=decodeURI(a.hash).replace(/__clerk_db_jwt\[(.*)\]/,""),a.href.endsWith("#")&&(a.hash=""),a};function r1(e){for(var a=1;a<arguments.length;a++){var t=arguments[a];for(var r in t)e[r]=t[r]}return e}var r2=function e(a,t){function r(e,r,i){if("undefined"!=typeof document){"number"==typeof(i=r1({},t,i)).expires&&(i.expires=new Date(Date.now()+864e5*i.expires)),i.expires&&(i.expires=i.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var n="";for(var s in i)i[s]&&(n+="; "+s,!0!==i[s]&&(n+="="+i[s].split(";")[0]));return document.cookie=e+"="+a.write(r,e)+n}}return Object.create({set:r,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var t=document.cookie?document.cookie.split("; "):[],r={},i=0;i<t.length;i++){var n=t[i].split("="),s=n.slice(1).join("=");try{var o=decodeURIComponent(n[0]);if(r[o]=a.read(s,o),e===o)break}catch(e){}}return e?r[e]:r}},remove:function(e,a){r(e,"",r1({},a,{expires:-1}))},withAttributes:function(a){return e(this.converter,r1({},this.attributes,a))},withConverter:function(a){return e(r1({},this.converter,a),this.attributes)}},{attributes:{value:Object.freeze(t)},converter:{value:Object.freeze(a)}})}({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 r0(e){return{get:()=>r2.get(e),set(a,t={}){r2.set(e,a,t)},remove(a){r2.remove(e,a)}}}let r9=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function r3(e,a){let t=function(e){try{return new Date(e||new Date)}catch{return new Date}}(e);return t.setFullYear(t.getFullYear()+a),t}let r8=r0("__clerk_test_etld"),r5="__client_uat",r4="__session",r6=()=>{let e=ag()?"None":"Lax",a=r9(e);return{sameSite:e,secure:a,partitioned:!1}};async function r7(e){let a;try{a=await eh(e)}catch(o){var t;t=`Suffixed cookie failed due to ${o.message} (secure-context: ${window.isSecureContext}, url: ${window.location.href})`,V.has(t)||(console.log(t),V.add(t));let{default:r}=await Promise.resolve().then(i.t.bind(i,180,23)),{default:n}=await Promise.resolve().then(i.t.bind(i,413,23)),s=r(e);a=n.stringify(s).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}return a}let ie=()=>{let e=ag()?"None":"Lax",a=r9(e);return{sameSite:e,secure:a}};var ia=i(945),it=i.n(ia);class ir{lock=(function(e){let a=new(it());return window.addEventListener("beforeunload",async()=>{await a.releaseLock(e)}),{acquireLockAndRun:async t=>{if("locks"in navigator&&isSecureContext){let a=new AbortController,r=setTimeout(()=>a.abort(),4999);return await navigator.locks.request(e,{signal:a.signal},async()=>(clearTimeout(r),await t())).catch(()=>!1)}if(await a.acquireLock(e,5e3))try{return await t()}finally{await a.releaseLock(e)}}}})("clerk.lock.refreshSessionToken");workerTimers=tE();timerId=null;initiated=!1;startPollingForSessionToken(e){if(this.timerId||this.initiated)return;let a=async()=>{this.initiated=!0,await this.lock.acquireLockAndRun(e),this.timerId=this.workerTimers.setTimeout(a,5e3)};a()}stopPollingForSessionToken(){null!=this.timerId&&(this.workerTimers.clearTimeout(this.timerId),this.timerId=null),this.initiated=!1}}class ii{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,a,t,r){let i=await r7(e.publishableKey),n=new ii(e,a,i,t,r);return await n.setup(),n}constructor(e,a,r,i,n){this.clerk=e,this.instanceType=i,this.clerkEventBus=n,t3.on(t1,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),t3.on(t2,()=>this.handleSignOut()),this.refreshTokenOnFocus(),this.startPollingForToken(),this.clientUat=(e=>{let a=r0(r5),r=r0(em(r5,e));return{set:e=>{let i=r3(Date.now(),1),n=ag()?"None":"Strict",s=r9(n),o=function(e=window.location.hostname,a=r8){if(t)return t;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 i=r.slice(e).join(".");if(a.set("1",{domain:i}),"1"===a.get())return a.remove({domain:i}),t=i,i;a.remove({domain:i})}}(),l="0";e&&e.updatedAt&&e.signedInSessions.length>0&&(l=Math.floor(e.updatedAt.getTime()/1e3).toString()),r.remove(),a.remove(),r.set(l,{domain:o,expires:i,partitioned:!1,sameSite:n,secure:s}),a.set(l,{domain:o,expires:i,partitioned:!1,sameSite:n,secure:s})},get:()=>parseInt(r.get()||a.get()||"0",10)}})(r),this.sessionCookie=(e=>{let a=r0(r4),t=r0(em(r4,e)),r=()=>{let e=r6();a.remove(e),t.remove(e)};return{set:e=>{let i=r3(Date.now(),1),{sameSite:n,secure:s,partitioned:o}=r6();o&&r(),a.set(e,{expires:i,sameSite:n,secure:s,partitioned:o}),t.set(e,{expires:i,sameSite:n,secure:s,partitioned:o})},remove:r,get:()=>t.get()||a.get()}})(r),this.activeCookie=(()=>{let e=r0("clerk_active_context"),a={secure:r9("None")};return{set:t=>{e.set(t,a)},get:()=>e.get(),remove:()=>e.remove(a)}})(),this.devBrowser=function({cookieSuffix:e,frontendApi:a,fapiClient:t}){let r,i,n=(r=r0(rQ),i=r0(em(rQ,e)),{get:()=>i.get()||r.get(),set:e=>{let a=r3(Date.now(),1),{sameSite:t,secure:n}=ie();i.set(e,{expires:a,sameSite:t,secure:n}),r.set(e,{expires:a,sameSite:t,secure:n})},remove:()=>{let e=ie();i.remove(e),r.remove(e)}});function s(){return n.get()}function o(e){n.set(e)}function l(){n.remove()}return{clear:function(){l()},setup:async function(){var e;let r;if(!ey(a))return;t.onBeforeRequest(e=>{let a=s();a&&e?.url&&(e.url=rY(e.url,a))}),t.onAfterResponse((e,a)=>{let t=a?.headers?.get("Clerk-Db-Jwt");t&&o(t)});let i=(r=(e=new URL(window.location.href)).searchParams.get(rQ)||"",rX(rZ(e)).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",rX(rZ(e))),r);if(i)return void o(i);if(n.get())return;let l=t.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 k(e)):[]}((await c.json()).errors);e[0]?a_(e[0].longMessage):a_()}let d=await c.json();o(d?.id)},getDevBrowserJWT:s,setDevBrowserJWT:o,removeDevBrowserJWT:l}}({frontendApi:e.frontendApi,fapiClient:a,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 a=this.devBrowser.getDevBrowserJWT();if(!a)throw Error(`${aj} Missing dev browser jwt. Please contact support.`);return rY(e,a)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new ir,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 a=await this.clerk.session.getToken();e&&this.updateSessionCookie(a)}catch(e){return this.handleGetTokenError(e)}}updateSessionCookie(e){if(document.hasFocus()||this.isCurrentContextActive())return e||d()||e7.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(O(e)||T(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(I(e))return void this.clerk.handleUnauthenticated().catch(e0);this.clerkEventBus.emit(g,"degraded")}}handleSignOut(){this.activeCookie.remove(),this.sessionCookie.remove(),this.setClientUatCookieForDevelopmentInstances()}setActiveContextInStorage(){let e=this.clerk.session?.id||"",a=this.clerk.organization?.id||"",t=`${e}:${a}`;":"!==t?this.activeCookie.set(t):this.activeCookie.remove()}isCurrentContextActive(){let e=this.activeCookie.get();if(!e)return!0;let[a,t]=e.split(":"),r=this.clerk.session?.id||"",i=this.clerk.organization?.id||"";return a===r&&t===i}getSessionCookie(){return this.sessionCookie.get()}}class is{clerk;captchaChallenge;timers;constructor(e,a=new aT(e),t=tE()){this.clerk=e,this.captchaChallenge=a,this.timers=t}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.__unstable__environment?.displayConfig?.captchaHeartbeat}clientBypass(){return this.clerk.client?.captchaBypass}intervalInMs(){return this.clerk.__unstable__environment?.displayConfig?.captchaHeartbeatIntervalMs??6e5}}let io=["/client","/waitlist"];class il{async getBaseFapiProxyOptions(){let e=await aM.clerk.session?.getToken();if(!e)throw new S("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 aM._fetch({...await this.getBaseFapiProxyOptions(),method:"GET",path:"/api_keys",search:a4({...e,subject:e?.subject??aM.clerk.organization?.id??aM.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new aF(e))}})}async create(e){return new aF(await aM._fetch({...await this.getBaseFapiProxyOptions(),path:"/api_keys",method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??aM.clerk.organization?.id??aM.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new aF(await aM._fetch({...await this.getBaseFapiProxyOptions(),method:"POST",path:`/api_keys/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let ic=new Map;class id{#ec=!1;load(e){let a=e?.protectConfig;if(a?.loaders&&Array.isArray(a.loaders)&&0!==a.loaders.length&&!this.#ec){if(s())for(let e of(this.#ec=!0,a.loaders))try{this.applyLoader(e)}catch(e){G(`[protect] failed to apply loader: ${e}`)}}}applyLoader(e){if(void 0!==e.rollout){let a=e.rollout;if("number"!=typeof a||a<0)return void G(`[protect] loader rollout value is invalid: ${a}`);if(0===a||Math.random()>a)return}let a=e.type||"script",t=e.target||"body",r=document.createElement(a);if(e.attributes)for(let[a,t]of Object.entries(e.attributes))switch(typeof t){case"string":case"number":case"boolean":r.setAttribute(a,String(t));break;default:G(`[protect] loader attribute is invalid type: ${a}=${t}`)}switch(e.textContent&&"string"==typeof e.textContent&&(r.textContent=e.textContent),t){case"head":document.head.appendChild(r);break;case"body":document.body.appendChild(r);break;default:if(t?.startsWith("#")){let e=document.getElementById(t.substring(1));if(!e)return void G(`[protect] loader target element not found: ${t}`);e.appendChild(r);return}G(`[protect] loader target is invalid: ${t}`)}}}class iu{signInResourceSignal=a7;signInErrorSignal=te;signInFetchSignal=ta;signInSignal=tt;signUpResourceSignal=tr;signUpErrorSignal=ti;signUpFetchSignal=tn;signUpSignal=ts;__internal_effect=a1;__internal_computed=aZ;constructor(){t3.on("resource:update",this.onResourceUpdated),t3.on("resource:error",this.onResourceError),t3.on("resource:fetch",this.onResourceFetch)}onResourceError=e=>{e.resource instanceof rP&&this.signInErrorSignal({error:e.error}),e.resource instanceof rE&&this.signUpErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof rP){if(ih(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof rE){if(ih(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}};onResourceFetch=e=>{e.resource instanceof rP&&this.signInFetchSignal({status:e.status}),e.resource instanceof rE&&this.signUpFetchSignal({status:e.status})}}function ih(e,a){return!a?.id&&e&&e.__internal_future?.hasBeenFinalized===!1}let im="cannot_render_billing_disabled",ip="cannot_render_user_missing",ig="cannot_render_organizations_disabled",ib="cannot_render_organization_missing",iy="cannot_render_single_session_enabled",ik={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 iw{static version="6.0.0-snapshot.v20251203203405";static sdkMetadata={name:"@clerk/clerk-js",version:"6.0.0-snapshot.v20251203203405"};static _billing;static _apiKeys;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new iu;internal_last_error=null;environment;#ed;#eu="";#eh;#em;#ep;#eg;#eb;#ef=null;#ey;#ek;#ew;#ev="loading";#ej=[];#ez=[];#e_={};#ex=null;#eq=0;#eS=p();get __internal_queryClient(){return this.#ed||Promise.resolve().then(i.bind(i,303)).then(e=>e.QueryClient).then(e=>{this.#ed||(this.#ed=new e,this.#eS.emit("queryClientStatus","ready"))}),this.#ed?{__tag:"clerk-rq-client",client:this.#ed}:void 0}__internal_getCachedResources;__internal_createPublicCredentials;__internal_getPublicCredentials;__internal_isWebAuthnSupported;__internal_isWebAuthnAutofillSupported;__internal_isWebAuthnPlatformAuthenticatorSupported;__internal_setActiveInProgress=!1;get publishableKey(){return this.#eu}get version(){return iw.version}set sdkMetadata(e){iw.sdkMetadata=e}get sdkMetadata(){return iw.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#ev}get isSatellite(){return!!ap()&&e2(this.#e_.isSatellite,new URL(window.location.href),!1)}get domain(){if(ap()){let e=function(e=""){return(e||"").replace(/^.+:\/\//,"")}(e2(this.#eh,new URL(window.location.href)));if("production"===this.#ew){let a;if(!e)return"";if(e.match(/^(clerk\.)+\w*$/))a=/(clerk\.)*(?=clerk\.)/;else{if(e.match(/\.clerk.accounts/))return e;a=/^(clerk\.)*/gi}return`clerk.${e.replace(a,"")}`}return e}return""}get proxyUrl(){if(ap()){let e=e2(this.#em,new URL(window.location.href));return!e||eL(e)||e$(e)||ad.throwInvalidProxyUrl({url:e}),e?e$(e)?new URL(e,window.location.origin).toString():e:""}return""}get frontendApi(){let e=ed(this.publishableKey);return e?e.frontendApi:ad.throwInvalidPublishableKeyError({key:this.publishableKey})}get instanceType(){return this.#ew}get isStandardBrowser(){return this.#e_.standardBrowser||!1}get billing(){return iw._billing||(iw._billing=new a6),iw._billing}get apiKeys(){return iw._apiKeys||(iw._apiKeys=new il),iw._apiKeys}__experimental_checkout(e){return this._checkout||(this._checkout=e=>(function(e,a){let t,r,i,n,{for:s,planId:o,planPeriod:l}=a;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:a,orgId:t,planId:r,planPeriod:i}=e;return`${a}-${t||"user"}-${r}-${i}`}({userId:e.user?.id||"",orgId:"organization"===s?e.organization?.id:void 0,planId:o,planPeriod:l}),d=ic.get(c);if(d)return d.signals.computedSignal();let u=(t=aX({resource:null}),r=aX({error:null}),i=aX({status:"idle"}),n=aZ(()=>{let e=t().resource,a=r().error,n=i().status;return{errors:to(a,{}),fetchStatus:n,checkout:e}}),{resourceSignal:t,errorSignal:r,fetchSignal:i,computedSignal:n}),h=new td(u,{..."organization"===s?{orgId:e.organization?.id}:{},planId:o,planPeriod:l});return ic.set(c,{resource:h,signals:u}),u.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#e_[e]}get isSignedIn(){return this?.session?.status!=="pending"&&!!this.session}constructor(e,a){if(!(e=(e||"").trim()))return ad.throwMissingPublishableKeyError();const t=ed(e);if(!t)return ad.throwInvalidPublishableKeyError({key:e});this.#eh=a?.domain,this.#em=a?.proxyUrl,this.environment=t4.getInstance(),this.#ew=t.instanceType,this.#eu=e,this.#ek=function(e){let a=[],t=[];async function r(e){for await(let t of["undefined"!=typeof window&&window.__unstable__onBeforeRequest,...a].filter(e=>e))if(await t(e)===!1)return!1;return!0}async function i(e,a){for await(let r of["undefined"!=typeof window&&window.__unstable__onAfterResponse,...t].filter(e=>e))if(await r(e,a)===!1)return!1;return!0}function n({method:a,path:t,sessionId:r,search:i,rotatingTokenNonce:n}){let s=new URLSearchParams(i);return s.append("__clerk_api_version","2025-11-10"),s.append("_clerk_js_version","6.0.0-snapshot.v20251203203405"),n&&s.append("rotating_token_nonce",n),e.domain&&"development"===e.instanceType&&e.isSatellite&&s.append("__domain",e.domain),a&&"GET"!==a&&"POST"!==a&&s.append("_method",a),t&&!io.some(e=>t.startsWith(e))&&r&&s.append("_clerk_session_id",r),eg([...s.entries()].reduce((e,[a,t])=>(e[a]=t.includes(",")?t.split(","):t,e),{}))}function s(a){let{path:t,pathPrefix:r="v1"}=a;if(e.proxyUrl){let i=new URL(e.proxyUrl),s=i.pathname.slice(1);return s.endsWith("/")&&(s=s.slice(0,-1)),ev({base:i.origin,pathname:`${s}/${r}${t}`,search:n(a)},{stringify:!1})}let i="production"===e.instanceType?e.domain:"";return ev({base:`https://${i||e.frontendApi}`,pathname:`${r}${t}`,search:n(a)},{stringify:!1})}async function o(a,t){let n,o={...a},{method:l="GET",body:d}=o;!d||"object"!=typeof d||d instanceof FormData||(o.body=function(e){if(!e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype)return e;let a={};for(let[t,r]of Object.entries(e))void 0!==r&&(a[t]=r);return a}(d)),o.url=s({...o,sessionId:e.getSessionId()}),o.headers=new Headers(o.headers),"GET"===l||d 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=d?eg(d,{keyEncoder:X}):d);let u=await r(o),h="GET"===l?"GET":"POST",m=o.url,p={...o,method:h,credentials:o.credentials||"include"};try{if(u){let e=t?.fetchMaxTries??(c()?4:11);n=await ar(()=>fetch(m,p),{retryImmediately:!0,initialDelay:700,maxDelayBetweenRetries:5e3,shouldRetry:(a,t)=>"GET"===h&&t<e,onBeforeRetry:e=>{m.searchParams.set("_clerk_retry_attempt",e.toString())}})}else n=new Response("{}",o)}catch(a){let e=m.toString();e7.error("network error",{error:a,url:e,method:l},"fapiClient");throw Error(`${aj} Network error at "${e}" - ${a}. Please try again.`)}let g=204!==n.status?await n.json():null,b=Object.assign(n,{payload:g});return n.ok||e7.error("request failed",{method:l,path:o.path,status:n.status},"fapiClient"),await i(o,b),b}return{buildEmailAddress:function(a){return function({localPart:e,frontendApi:a}){return`${e}@${a?a.replace("clerk.",""):"clerk.com"}`}({localPart:a,frontendApi:e.frontendApi})},buildUrl:s,onAfterResponse:function(e){t.push(e)},onBeforeRequest:function(e){a.push(e)},request:o}}({domain:this.domain,frontendApi:this.frontendApi,instanceType:this.instanceType,isSatellite:this.isSatellite,getSessionId:()=>this.session?.id,proxyUrl:this.proxyUrl}),this.#eS.emit(g,"loading"),this.#eS.prioritizedOn(g,e=>this.#ev=e),aM.clerk=this,this.#eg=new id}getFapiClient=()=>this.#ek;load=async e=>{if(e7.info("load() start",{},"clerk"),!this.loaded){if("development"===this.#ew&&G("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.#e_=this.#eU(e),this.#e_.clerkUiCtor&&(this.#ey=Promise.resolve(this.#e_.clerkUiCtor).then(e=>new e(()=>this,()=>this.environment,this.#e_,new an))),"development"===this.#ew&&(this.#e_.routerPush||this.#e_.routerReplace)&&(!this.#e_.routerPush||!this.#e_.routerReplace)){let e=this.#e_.routerPush?"routerReplace":"routerPush";G(`Clerk: Both \`routerPush\` and \`routerReplace\` need to be defined, but \`${e}\` is not defined. This may cause issues with navigation in your application.`)}t3.on(t9,()=>{this.#eA(this.session),this.#eC()}),this.#e_.sdkMetadata&&(iw.sdkMetadata=this.#e_.sdkMetadata),!1!==this.#e_.telemetry&&(this.telemetry=new eG({clerkVersion:iw.version,samplingRate:1,perEventSampling:!this.#e_.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#e_.telemetry}),this.#e_.appearance&&this.telemetry.record({event:"THEME_USAGE",eventSamplingRate:1,payload:function(e){let a;if(!e||"object"!=typeof e)return{};let t=e.theme||e.baseTheme;if(!t)return{};if(Array.isArray(t))for(let e of t){let t=e1(e);if(t){a=t;break}}else a=e1(t);return{themeName:a}}(this.#e_.appearance)}));try{this.#e_.standardBrowser?await this.#eI():await this.#eP();let e=this.#e_.telemetry,a=!1!==e&&!e?.disabled,t=!!this.#e_.__internal_keyless_claimKeylessApplicationUrl,r=!!this.environment?.clientDebugMode,i=this.environment?.isProduction?.()??!1,n=r||t&&!i,s=t&&!r?"error":void 0;n&&function(e={}){if(e8)return;let{enabled:a=!1,...t}=e;a&&(e9=!0,e8=!0,e6(t))}({enabled:!0,...s?{logLevel:s}:{},...a&&this.telemetry?{telemetryCollector:this.telemetry}:{}}),this.#eg?.load(this.environment),e7.info("load() complete",{},"clerk")}catch(e){throw this.#eS.emit(g,"error"),e7.error("load() failed",{error:e},"clerk"),e}}};#eO(){let e;return!!(!this.#e_.signUpUrl&&this.#e_.signInUrl&&(e=this.#e_.signInUrl,!ep.test(e)))}signOut=async(e,a)=>{if(!this.client||0===this.client.sessions.length)return;let t="undefined"!=typeof window&&"function"==typeof window.__unstable__onBeforeSetActive?window.__unstable__onBeforeSetActive:e0,r="undefined"!=typeof window&&"function"==typeof window.__unstable__onAfterSetActive?window.__unstable__onAfterSetActive:e0,i=e&&"object"==typeof e?e:a||{},n=i?.redirectUrl||this.buildAfterSignOutUrl();e7.debug("signOut() start",{hasClient:!!this.client,multiSessionCount:this.client?.signedInSessions.length??0,redirectUrl:n,sessionTarget:i?.sessionId??null},"clerk");let s="function"==typeof e?e:void 0,o=async()=>{let e=as(this.#e_.standardBrowser);t3.emit(t2,null),this.#eT(),await e.track(async()=>{s?await s():await this.navigate(n)}),e.isUnloading()||(this.#eA(),this.#eC(),await r())};if(await t(),!i.sessionId||1===this.client.signedInSessions.length){this.#e_.experimental?.persistClient??!0?await this.client.removeSessions():await this.client.destroy(),await o(),e7.info("signOut() complete",{redirectUrl:ej(n)},"clerk");return}let l=this.client.signedInSessions.find(e=>e.id===i.sessionId),c=l?.id&&this.session?.id===l.id;await l?.remove(),c&&(await o(),e7.info("signOut() complete",{redirectUrl:ej(n)},"clerk"))};openGoogleOneTap=e=>{this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("googleOneTap",e||{})),this.telemetry?.record(eZ("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(D(this,this.environment)){if("development"===this.#ew)throw new S(eF.cannotOpenSignInOrSignUp,{code:iy});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("signIn",e||{}));let a={withSignUp:e?.withSignUp??this.#eO()};this.telemetry?.record(eZ("SignIn",e,a))};closeSignIn=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(N(this,this.environment)){if("development"===this.#ew)throw new S(eF.cannotRenderAnyBillingComponent("Checkout"),{code:im});return}if(!this.user){if("development"===this.#ew)throw new S(eF.cannotOpenCheckout,{code:ip});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openDrawer("checkout",e||{}))};__internal_closeCheckout=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("checkout"))};__internal_openPlanDetails=e=>{if(N(this,this.environment)){if("development"===this.#ew)throw new S(eF.cannotRenderAnyBillingComponent("PlanDetails"),{code:im});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openDrawer("planDetails",e||{})),this.telemetry?.record(eZ("PlanDetails",e))};__internal_closePlanDetails=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("planDetails"))};__internal_openSubscriptionDetails=e=>{this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openDrawer("subscriptionDetails",e||{}))};__internal_closeSubscriptionDetails=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("subscriptionDetails"))};__internal_openReverification=e=>{if(!this.user){if("development"===this.#ew)throw new S(eF.cannotOpenUserProfile,{code:ip});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("userVerification",e||{})),this.telemetry?.record(eZ("UserVerification",e))};__internal_closeReverification=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userVerification"))};__internal_attemptToEnableEnvironmentSetting=e=>{let{for:a,caller:t}=e;if(this.user||"development"!==this.#ew||G(`Clerk: "${t}" requires an active user session. Ensure a user is signed in before executing ${t}.`),"organizations"===a){let a;return(a=this.environment,a?.organizationSettings.enabled||this.session?.currentTask?.key==="choose-organization")?{isEnabled:!0}:("development"===this.#ew&&this.__internal_openEnableOrganizationsPrompt({caller:t,onSuccess:()=>window.location.reload(),onClose:e.onClose}),{isEnabled:!1})}throw Error(`Attempted to enable an unknown or unsupported setting "${a}".`)};__internal_openEnableOrganizationsPrompt=e=>(this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("enableOrganizationsPrompt",e||{})));__internal_closeEnableOrganizationsPrompt=()=>(this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(e=>e.closeModal("enableOrganizationsPrompt")));__internal_openBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(e=>e.openModal("blankCaptcha",{})));__internal_closeBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(e=>e.closeModal("blankCaptcha")));__internal_loadStripeJs=async()=>(az("Stripe"),{loadStripe:()=>Promise.resolve(null)});openSignUp=e=>{if(D(this,this.environment)){if("development"===this.#ew)throw new S(eF.cannotOpenSignInOrSignUp,{code:iy});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("signUp",e||{})),this.telemetry?.record(eZ("SignUp",e))};closeSignUp=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signUp"))};openUserProfile=e=>{if(!this.user){if("development"===this.#ew)throw new S(eF.cannotOpenUserProfile,{code:ip});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("userProfile",e||{}));let a=(e?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(eZ("UserProfile",e,a))};closeUserProfile=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userProfile"))};openOrganizationProfile=e=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new S(eF.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:ig})}});if(a){if(!this.organization){if("development"===this.#ew)throw new S(eF.cannotRenderComponentWhenOrgDoesNotExist,{code:ib});return}this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("organizationProfile",e||{})),this.telemetry?.record(eZ("OrganizationProfile",e))}};closeOrganizationProfile=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("organizationProfile"))};openCreateOrganization=e=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new S(eF.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:ig})}});a&&(this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("createOrganization",e||{})),this.telemetry?.record(eZ("CreateOrganization",e)))};closeCreateOrganization=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("createOrganization"))};openWaitlist=e=>{this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(a=>a.openModal("waitlist",e||{})),this.telemetry?.record(eZ("Waitlist",e))};closeWaitlist=()=>{this.#ey?.then(e=>e.ensureMounted()).then(e=>e.closeModal("waitlist"))};mountSignIn=(e,a)=>{this.assertComponentsReady(this.#ey);let t="SignIn";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"signIn",node:e,props:a}));let r={withSignUp:a?.withSignUp??this.#eO()};this.telemetry?.record(eX(t,a,r))};unmountSignIn=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserAvatar=(e,a)=>{this.assertComponentsReady(this.#ey);let t="UserAvatar";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"userAvatar",node:e,props:a})),this.telemetry?.record(eX(t,a))};unmountUserAvatar=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountSignUp=(e,a)=>{this.assertComponentsReady(this.#ey);let t="SignUp";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"signUp",node:e,props:a})),this.telemetry?.record(eX(t,a))};unmountSignUp=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserProfile=(e,a)=>{if(!this.user){if("development"===this.#ew)throw new S(eF.cannotRenderComponentWhenUserDoesNotExist,{code:ip});return}this.assertComponentsReady(this.#ey);let t="UserProfile";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"userProfile",node:e,props:a}));let r=(a?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(eX(t,a,r))};unmountUserProfile=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountOrganizationProfile=(e,a)=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new S(eF.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:ig})}});if(!t)return;let r=!!this.user;if(!this.organization&&r){if("development"===this.#ew)throw new S(eF.cannotRenderComponentWhenOrgDoesNotExist,{code:ib});return}this.assertComponentsReady(this.#ey);let i="OrganizationProfile";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:i,appearanceKey:"userProfile",node:e,props:a})),this.telemetry?.record(eX(i,a))};unmountOrganizationProfile=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountCreateOrganization=(e,a)=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new S(eF.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:ig})}});if(!t)return;this.assertComponentsReady(this.#ey);let r="CreateOrganization";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"createOrganization",node:e,props:a})),this.telemetry?.record(eX(r,a))};unmountCreateOrganization=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountOrganizationSwitcher=(e,a)=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationSwitcher",onClose:()=>{throw new S(eF.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:ig})}});if(!t)return;this.assertComponentsReady(this.#ey);let r="OrganizationSwitcher";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"organizationSwitcher",node:e,props:a})),this.telemetry?.record(eX(r,{...a,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationSwitcher=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};__experimental_prefetchOrganizationSwitcher=()=>{this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(e=>e.prefetch("organizationSwitcher"))};mountOrganizationList=(e,a)=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationList",onClose:()=>{throw new S(eF.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:ig})}});if(!t)return;this.assertComponentsReady(this.#ey);let r="OrganizationList";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"organizationList",node:e,props:a})),this.telemetry?.record(eX(r,{...a,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationList=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserButton=(e,a)=>{this.assertComponentsReady(this.#ey);let t="UserButton";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"userButton",node:e,props:a}));let r={...a?.customMenuItems?.length||0?{customItems:!0}:void 0,...a?.__experimental_asStandalone?{standalone:!0}:void 0};this.telemetry?.record(eX(t,a,r))};unmountUserButton=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountWaitlist=(e,a)=>{this.assertComponentsReady(this.#ey);let t="Waitlist";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"waitlist",node:e,props:a})),this.telemetry?.record(eX(t,a))};unmountWaitlist=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountPricingTable=(e,a)=>{if(N(this,this.environment)){if("development"===this.#ew)throw new S(eF.cannotRenderAnyBillingComponent("PricingTable"),{code:im});return}this.assertComponentsReady(this.#ey);let t="PricingTable";this.#ey.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"pricingTable",node:e,props:a})),this.telemetry?.record(eX(t,a))};unmountPricingTable=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};__internal_mountOAuthConsent=(e,a)=>{this.assertComponentsReady(this.#ey),this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:"OAuthConsent",appearanceKey:"__internal_oauthConsent",node:e,props:a}))};__internal_unmountOAuthConsent=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountAPIKeys=(e,a)=>{let t;if(G("Clerk: <APIKeys /> component is in early access and not yet recommended for production use."),W(this,t=this.environment)&&L(this,t)){if("development"===this.#ew)throw new S(eF.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&L(this,this.environment)){if("development"===this.#ew)throw new S(eF.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if(W(this,this.environment)){if("development"===this.#ew)throw new S(eF.cannotRenderAPIKeysComponentForUserWhenDisabled,{code:"cannot_render_api_keys_user_disabled"});return}this.assertComponentsReady(this.#ey);let r="APIKeys";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"apiKeys",node:e,props:a})),this.telemetry?.record(eX(r,a))};unmountAPIKeys=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountTaskChooseOrganization=(e,a)=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"TaskChooseOrganization",onClose:()=>{throw new S(eF.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:ig})}});if(!t)return;this.assertComponentsReady(this.#ey);let r="TaskChooseOrganization";this.#ey.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"taskChooseOrganization",node:e,props:a})),this.telemetry?.record(eX(r,a))};unmountTaskChooseOrganization=e=>{this.#ey?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};setActive=async e=>{let{organization:a,redirectUrl:t,navigate:r}=e,{session:i}=e;this.__internal_setActiveInProgress=!0,e7.debug("setActive() start",{hasClient:!!this.client,sessionTarget:"string"==typeof i?i:i?.id??i??null,organizationTarget:"string"==typeof a?a:a?.id??a??null,redirectUrl:t??null},"clerk");try{var n;let s;if(!this.client)throw e7.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===i&&!this.session)throw e7.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 i&&(i=this.client.sessions.find(e=>e.id===i)||null);let o="undefined"!=typeof window&&"function"==typeof window.__unstable__onBeforeSetActive?window.__unstable__onBeforeSetActive:e0,l="undefined"!=typeof window&&"function"==typeof window.__unstable__onAfterSetActive?window.__unstable__onAfterSetActive:e0,c=void 0===i?this.session:i;c?.status==="pending"&&(n={...this.#e_,...e},s=["taskUrls","navigate"],Object.keys(n).some(e=>s.includes(e))||G('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!==a;if(c&&u){let e="string"==typeof a?a:a?.id;if("string"==typeof e&&e.startsWith("org_"))c.lastActiveOrganizationId=e||null;else{let a=c.user.organizationMemberships.find(a=>a.organization.slug===e),t=a?.organization.id||null,r=null===t;if(this.environment?.organizationSettings?.forceOrganizationSelection&&r)return;c.lastActiveOrganizationId=t}}c?.status!=="pending"&&await o(null===c?"sign-out":void 0),(ap()&&globalThis.document.hasFocus()||!this.#e_.standardBrowser)&&(await this.#eE(c),c=this.#eM(c?.id)),await c?.getToken()||(d()||e7.warn("Token is null when setting active session (offline)",{sessionId:c?.id},"clerk"),t3.emit(t1,{token:null}));let h=as(this.#e_.standardBrowser),m=c?.status==="pending"&&c?.currentTask&&this.#e_.taskUrls?.[c?.currentTask.key];if((t||m||r)&&await h.track(async()=>{if(this.client){if(c?.status!=="pending"&&this.#eT(),m){let e=t?ev({base:m,hashSearchParams:{redirectUrl:t}},{stringify:!0}):m;await this.navigate(e)}else if(r&&c)await r({session:c});else if(t){if(this.client.isEligibleForTouch()){let e=new URL(t,window.location.href),a=this.buildUrlWithAuth(this.client.buildTouchUrl({redirectUrl:e}));await this.navigate(a)}await this.navigate(t)}}}),h.isUnloading())return;this.#eA(c),this.#eC(),c?.status!=="pending"&&await l()}finally{this.__internal_setActiveInProgress=!1}};addListener=e=>{var a;let t;return a=e,e=e=>{var r;t||={...e},a(t={...{client:rH((r=t).client,e.client),session:rH(r.session,e.session),user:rH(r.user,e.user),organization:rH(r.organization,e.organization)}})},this.#ej.push(e),this.client&&e({client:this.client,session:this.session,user:this.user,organization:this.organization}),()=>{this.#ej=this.#ej.filter(a=>a!==e)}};on=(...e)=>{this.#eS.on(...e)};off=(...e)=>{this.#eS.off(...e)};__internal_addNavigationListener=e=>(this.#ez.push(e),()=>{this.#ez=this.#ez.filter(a=>a!==e)});navigate=async(e,a)=>{if(!e||!ap())return;setTimeout(()=>{this.#eR()},0);let t=new URL(e,window.location.href);this.#eF.includes(t.protocol)||(console.warn(`Clerk: "${t.protocol}" is not a valid protocol. Redirecting to "/" instead. If you think this is a mistake, please open an issue.`),t=new URL("/",window.location.href));let r=a?.replace&&this.#e_.routerReplace?this.#e_.routerReplace:this.#e_.routerPush;if(e7.info(`Clerk is navigating to: ${t}`),this.#e_.routerDebug&&console.log(`Clerk is navigating to: ${t}`),"null"!==t.origin&&t.origin!==window.location.origin||!r)return void eW(t);let i={...a?.metadata?{__internal_metadata:a?.metadata}:{},windowNavigate:eW};return await r(ej(t),i)};buildUrlWithAuth(e){if("production"===this.#ew)return e;let a=new URL(e,window.location.origin);return a.origin!==window.location.origin&&this.#ep?this.#ep.decorateUrlWithDevBrowserToken(a).href:a.href}buildSignInUrl(e){return this.#eD("signInUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildSignUpUrl(e){return this.#eD("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 eU(this.#e_,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eU(this.#e_,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#e_.afterSignOutUrl?this.buildUrlWithAuth(this.#e_.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#e_.newSubscriptionRedirectUrl?this.#e_.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?ev({base:this.#e_.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#e_.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#e_.afterMultiSessionSingleSignOutUrl):this.#e_.signInUrl?this.buildUrlWithAuth(ev({base:this.#e_.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 a=this.session?.currentTask;if(!a)return"";let t=this.#e_.taskUrls?.[a.key];return t||ev({base:this.buildSignInUrl(e),hashPath:eE(a)},{stringify:!0})}#eN=async()=>{if(!ap())return;let e=new URLSearchParams({[$]:"true"}),a=eI(B);a&&eL(a)||function(){throw Error(`${aj} Invalid redirect_url. A valid http or https url should be used for the redirection.`)}();let t=ev({base:eI(B),searchParams:e},{stringify:!0});return this.navigate(this.buildUrlWithAuth(t))};redirectWithAuth=async e=>{if(ap())return this.navigate(this.buildUrlWithAuth(e))};redirectToSignIn=async e=>{if(ap())return this.navigate(this.buildSignInUrl(e))};redirectToSignUp=async e=>{if(ap())return this.navigate(this.buildSignUpUrl(e))};redirectToUserProfile=async()=>{if(ap())return this.navigate(this.buildUserProfileUrl())};redirectToCreateOrganization=async()=>{if(ap())return this.navigate(this.buildCreateOrganizationUrl())};redirectToOrganizationProfile=async()=>{if(ap())return this.navigate(this.buildOrganizationProfileUrl())};redirectToAfterSignIn=async()=>{if(ap())return this.navigate(this.buildAfterSignInUrl())};redirectToAfterSignUp=async()=>{if(ap())return this.navigate(this.buildAfterSignUpUrl())};redirectToAfterSignOut=async()=>{if(ap())return this.navigate(this.buildAfterSignOutUrl())};redirectToWaitlist=async()=>{if(ap())return this.navigate(this.buildWaitlistUrl())};redirectToTasks=async e=>{if(ap())return this.navigate(this.buildTasksUrl(e))};handleEmailLinkVerification=async(e,a)=>{if(!this.client)return;let t=eI("__clerk_status");if("expired"===t)throw new _(q.Expired);if("client_mismatch"===t)throw new _(q.ClientMismatch);if("verified"!==t)throw new _(q.Failed);let r=eI("__clerk_created_session"),{signIn:i,signUp:n,sessions:s}=this.client,o=s.some(e=>e.id===r),l="needs_second_factor"===i.status||"missing_requirements"===n.status,c=e=>a&&"function"==typeof a?a(e):this.navigate(e),d=e.redirectUrl?()=>c(e.redirectUrl):e0;return o?this.setActive({session:r,redirectUrl:e.redirectUrlComplete}):l?d():("function"==typeof e.onVerifiedOnOtherDevice&&e.onVerifiedOnOtherDevice(),null)};handleGoogleOneTapCallback=async(e,a,t)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:r,signUp:i}=this.client,n="identifier"in(e||{})?e:r,s="missingFields"in(e||{})?e:i,o=e=>t&&"function"==typeof t?t(this.buildUrlWithAuth(e)):this.navigate(this.buildUrlWithAuth(e));return this._handleRedirectCallback(a,{signUp:s,signIn:n,navigate:o})};_handleRedirectCallback=async(e,{signIn:a,signUp:t,navigate:r})=>{if(!this.loaded||!this.environment||!this.client)return;if(!window.opener&&e.reloadResource)try{"signIn"===e.reloadResource?await a.reload():"signUp"===e.reloadResource&&await t.reload()}catch{}let{displayConfig:i}=this.environment,{firstFactorVerification:n}=a,{externalAccount:s}=t.verifications,o={status:t.status,missingFields:t.missingFields,externalAccountStatus:s.status,externalAccountErrorCode:s.error?.code,externalAccountSessionId:s.error?.meta?.sessionId,sessionId:t.createdSessionId},l={status:a.status,firstFactorVerificationStatus:n.status,firstFactorVerificationErrorCode:n.error?.code,firstFactorVerificationSessionId:n.error?.meta?.sessionId,sessionId:a.createdSessionId},c=e=>()=>r(e),d=c(e.signInUrl||i.signInUrl),u=c(e.signUpUrl||i.signUpUrl),h=c(e.firstFactorUrl||ev({base:i.signInUrl,hashPath:"/factor-one"},{stringify:!0})),m=c(e.secondFactorUrl||ev({base:i.signInUrl,hashPath:"/factor-two"},{stringify:!0})),p=c(e.resetPasswordUrl||ev({base:i.signInUrl,hashPath:"/reset-password"},{stringify:!0})),g=new eU(this.#e_,e),b=c(e.continueSignUpUrl||ev({base:i.signUpUrl,hashPath:"/continue"},{stringify:!0})),f=({missingFields:a})=>a.length?b():(({signUp:e,verifyEmailPath:a,verifyPhonePath:t,continuePath:r,navigate:i,handleComplete:n,redirectUrl:s="",redirectUrlComplete:o="",oidcPrompt:l})=>{if("complete"===e.status)return n&&n();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 n=eO();if(e.unverifiedFields?.includes("email_address")&&a)return i(a,{searchParams:n});if(e.unverifiedFields?.includes("phone_number")&&t)return i(t,{searchParams:n});if(r)return i(r,{searchParams:n})}})({signUp:t,verifyEmailPath:e.verifyEmailAddressUrl||ev({base:i.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),verifyPhonePath:e.verifyPhoneNumberUrl||ev({base:i.signUpUrl,hashPath:"/verify-phone-number"},{stringify:!0}),navigate:r}),y=e.signInUrl||i.signInUrl,k=e.signUpUrl||i.signUpUrl,w=async({session:e,baseUrl:a,redirectUrl:t})=>{e.currentTask?await eM(e,{baseUrl:a,navigate:this.navigate}):await this.navigate(t)};if("complete"===l.status)return this.setActive({session:l.sessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:y,redirectUrl:g.getAfterSignInUrl()})}});if("transferable"===o.externalAccountStatus&&"external_account_exists"===o.externalAccountErrorCode){let e=await a.create({transfer:!0});switch(e.status){case"complete":return this.setActive({session:e.createdSessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:k,redirectUrl:g.getAfterSignInUrl()})}});case"needs_first_factor":return h();case"needs_second_factor":return m();case"needs_new_password":return p();default:ax("sign in")}}let v="user_locked"===o.externalAccountErrorCode,j="user_locked"===l.firstFactorVerificationErrorCode;if(v)return u();if(j)return d();if("needs_first_factor"===l.status&&!a.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 d();let a=await t.create({transfer:!0});switch(a.status){case"complete":return this.setActive({session:a.createdSessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:k,redirectUrl:g.getAfterSignUpUrl()})}});case"missing_requirements":return f({missingFields:a.missingFields});default:ax("sign in")}}if("complete"===o.status)return this.setActive({session:o.sessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:k,redirectUrl:g.getAfterSignUpUrl()})}});if("needs_second_factor"===l.status)return m();let z=("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(z||_){let e=l.firstFactorVerificationSessionId||o.externalAccountSessionId;if(e)return this.setActive({session:e,navigate:async({session:e})=>{await w({session:e,baseUrl:z?k:y,redirectUrl:g.getAfterSignInUrl()})}})}return(e=>{let{externalAccount:a}=e.verifications;return!!a.error})(t)?u():"verified"===o.externalAccountStatus&&"missing_requirements"===o.status?f({missingFields:t.missingFields}):this.session?.currentTask?void await this.redirectToTasks({redirectUrl:this.buildAfterSignInUrl()}):d()};handleRedirectCallback=async(e={},a)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:t,signUp:r}=this.client,i=e=>a&&"function"==typeof a?a(e):this.navigate(e);return this._handleRedirectCallback(e,{signUp:r,signIn:t,navigate:i})};handleUnauthenticated=async(e={broadcast:!0})=>{if(this.client&&this.session)try{let a=await tA.getOrCreateInstance().fetch();if(this.updateClient(a),this.session)return;return e.broadcast&&t3.emit(t2,null),this.setActive({session:null})}catch(e){if(O(e)&&[403,500].includes(e.status))return this.setActive({session:null});throw e}};authenticateWithGoogleOneTap=async e=>(az("Google One Tap"),this.client.signIn);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"})};authenticateWithWeb3=async({redirectUrl:e,signUpContinueUrl:a,customNavigate:t,unsafeMetadata:r,strategy:i,legalAccepted:n,secondFactorUrl:s})=>{let o,l;if(!this.client||!this.environment)return;let{displayConfig:c}=this.environment,d=i.replace("web3_","").replace("_signature",""),u=await af().getWeb3Identifier({provider:d});switch(d){case"metamask":o=af().generateSignatureWithMetamask;break;case"base":o=af().generateSignatureWithBase;break;case"coinbase_wallet":o=af().generateSignatureWithCoinbaseWallet;break;default:o=af().generateSignatureWithOKXWallet}let h=e=>()=>t&&"function"==typeof t?t(e):this.navigate(e),m=h(s||ev({base:c.signInUrl,hashPath:"/factor-two"},{stringify:!0})),p=h(a||ev({base:c.signUpUrl,hashPath:"/continue"},{stringify:!0}));try{l=await this.client.signIn.authenticateWithWeb3({identifier:u,generateSignature:o,strategy:i})}catch(e){if(ac(e,"form_identifier_not_found"))l=await this.client.signUp.authenticateWithWeb3({identifier:u,generateSignature:o,unsafeMetadata:r,strategy:i,legalAccepted:n}),a&&"missing_requirements"===l.status&&"verified"===l.verifications.web3Wallet.status&&await p();else throw e}let g=async({session:e,redirectUrl:a})=>{e.currentTask?await eM(e,{baseUrl:c.signInUrl,navigate:this.navigate}):await this.navigate(a)};switch(l.status){case"needs_second_factor":await m();break;case"complete":l.createdSessionId&&await this.setActive({session:l.createdSessionId,navigate:async({session:a})=>{await g({session:a,redirectUrl:e??this.buildAfterSignInUrl()})}});break;default:return}};createOrganization=async({name:e,slug:a})=>rs.create({name:e,slug:a});getOrganization=async e=>rs.get(e);joinWaitlist=async({emailAddress:e})=>rJ.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 a=this.#e_.selectInitialSession?this.#e_.selectInitialSession(e):this.#eW(e);this.#eA(a)}if(this.client=e,this.session){let e=this.#eM(this.session.id);"active"===this.session.status&&e?.status==="pending"&&("undefined"!=typeof window&&"function"==typeof window.__unstable__onAfterSetActive?window.__unstable__onAfterSetActive:e0)(),this.#eA(e),this.session?.lastActiveToken||d()||e7.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),t3.emit(t1,{token:this.session?.lastActiveToken})}this.#eC()};get __unstable__environment(){return this.environment}__unstable__setEnvironment=async e=>{this.environment=new t4(e)};__unstable__onBeforeRequest=e=>{this.#ek.onBeforeRequest(e)};__unstable__onAfterResponse=e=>{this.#ek.onAfterResponse(e)};__unstable__updateProps=e=>{let a={...e,options:this.#eU({...this.#e_,...e.options})};return this.#ey?.then(e=>e.ensureMounted()).then(e=>e.updateProps(a))};__internal_navigateWithError(e,a){return this.__internal_last_error=a,this.navigate(e)}#eL=()=>{let e=new URLSearchParams({[B]:window.location.href});return ev({base:this.#e_.signInUrl,searchParams:e},{stringify:!0})};#e$=()=>{let e;if(this.proxyUrl){let a=new URL(this.proxyUrl);e=new URL(`${a.pathname}/v1/client/sync`,a.origin)}else this.domain&&(e=new URL("/v1/client/sync",`https://${this.domain}`));return e?.searchParams.append("redirect_url",window.location.href),e?.toString()||""};#eK=()=>"true"!==eI($)&&!!this.isSatellite&&!!this.#ep?.isSignedOut();#eB=()=>"production"!==this.#ew&&!this.isSatellite&&!!eI(B);#eJ=async()=>{"development"===this.instanceType?await this.navigate(this.#eL()):"production"===this.instanceType&&await this.navigate(this.#e$())};#eV=(e,a)=>{let t;try{t=new URL(e)}catch{throw Error(`${aj} The signInUrl needs to have a absolute url format.`)}t.origin===a&&function(){throw Error(`${aj} The signInUrl needs to be on a different origin than your satellite application.`)}()};#eG=()=>{this.isSatellite&&("development"!==this.#ew||this.#e_.signInUrl||function(){throw Error(`${aj} Missing signInUrl. A satellite application needs to specify the signInUrl for development instances.`)}(),this.proxyUrl||this.domain||function(){throw Error(`${aj} Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl.`)}(),this.#e_.signInUrl&&this.#eV(this.#e_.signInUrl,window.location.origin))};#eI=async()=>{if(this.#ep=await ii.create(this,this.#ek,this.#ew,this.#eS),this.#eG(),this.#eK())return void await this.#eJ();if(this.#eB())return void await this.#eN();this.#ex=(()=>{if(!s())return{onPageFocus:e0};let e=[];return window.addEventListener("focus",()=>{"visible"===document.visibilityState&&e.forEach(e=>e())}),{onPageFocus:a=>{e.push(a)}}})(),"undefined"!=typeof BroadcastChannel&&(this.#ef=new BroadcastChannel("clerk")),this.#eH();let e=function(e=window.location.hostname){if(!e)return!1;let a=ek.get(e);void 0===a&&(a=ei.some(a=>e.startsWith("accounts.")&&e.endsWith(a))||en.some(a=>e.endsWith(a)&&!e.endsWith(".clerk"+a)),ek.set(e,a));return a}(window?.location.hostname),a="development"===this.#ew&&!e,t=0,r=0;for(;r<2;){r++;try{var i;let e=t4.getInstance().fetch({touch:a}).then(e=>this.updateEnvironment(e)).catch(()=>{++t;let e=av.getItem(ay,null);e&&this.updateEnvironment(new t4(e))}),r=async()=>tA.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(async e=>{if(I(e))throw e;++t;let a=this.#ep?.getSessionCookie(),r=function(e){let a;try{a=new rF({jwt:e||"",object:"token",id:void 0})}catch{a=null}if(tA.clearInstance(),!a?.jwt)return tA.getOrCreateInstance({object:"client",last_active_session_id:null,id:"client_init",sessions:[]});let{sessionId:t,userId:r,orgId:i,orgRole:n,orgPermissions:s,orgSlug:o,factorVerificationAge:l}=(e=>{let a,t,r,i,n=e.fva??null,s=e.sts??null;if(2===e.v){if(e.o){a=e.o?.id,r=e.o?.slg,e.o?.rol&&(t=`org:${e.o?.rol}`);let{org:n}=rv(e.fea),{permissions:s,featurePermissionMap:o}=(({per:e,fpm:a})=>{if(!e||!a)return{permissions:[],featurePermissionMap:[]};let t=e.split(",").map(e=>e.trim());return{permissions:t,featurePermissionMap:a.split(",").map(e=>Number.parseInt(e.trim(),10)).map(e=>e.toString(2).padStart(t.length,"0").split("").map(e=>Number.parseInt(e,10)).reverse()).filter(Boolean)}})({per:e.o?.per,fpm:e.o?.fpm});i=function({features:e,permissions:a,featurePermissionMap:t}){if(!e||!a||!t)return[];let r=[];for(let i=0;i<e.length;i++){let n=e[i];if(i>=t.length)continue;let s=t[i];if(s)for(let e=0;e<s.length;e++)1===s[e]&&r.push(`org:${n}:${a[e]}`)}return r}({features:n,featurePermissionMap:o,permissions:s})}}else a=e.org_id,t=e.org_role,r=e.org_slug,i=e.org_permissions;return{sessionClaims:e,sessionId:e.sid,sessionStatus:s,actor:e.act,userId:e.sub,orgId:a,orgRole:t,orgSlug:r,orgPermissions:i,factorVerificationAge:n}})(a.jwt.claims),c={object:"client",last_active_session_id:t,id:"client_init",sessions:[{object:"session",id:t,status:"active",last_active_organization_id:i||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:i&&o&&n?[{object:"organization_membership",id:i,role:n,permissions:s||[],organization:{object:"organization",id:i,name:o,slug:o,members_count:1,max_allowed_memberships:1}}]:[]}}]};return tA.getOrCreateInstance(c)}(a);return this.updateClient(r),this.#ep?.stopPollingForToken(),await this.session?.getToken({skipCache:!0}).catch(()=>null).finally(()=>{this.#ep?.startPollingForToken()}),null}),[,n]=await (i=[e,r()],Promise.all(Array.from(i).map(e=>e.then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e})))));if("rejected"===n.status){let e=n.reason;if(ac(e,"requires_captcha"))await r();else throw e}if(this.#ep?.setClientUatCookieForDevelopmentInstances(),await this.#eQ())return;break}catch(e){if(ac(e,"dev_browser_unauthenticated"))await this.#ep.handleUnauthenticatedDevBrowser();else if(!d())return void console.warn(e);else throw e}r>=2&&function(){throw Error(`${aj} Something went wrong initializing Clerk.`)}()}this.#eb=new is(this),this.#eb.start(),this.#eY(),this.#eX(),this.#eZ(),this.#eS.emit(g,t>0?"degraded":"ready")};shouldFallbackToCachedResources=()=>!!this.__internal_getCachedResources;#eP=async()=>{let e,a,t=this.shouldFallbackToCachedResources()?1:void 0,r=0;try{[e,a]=await Promise.all([t4.getInstance().fetch({touch:!1,fetchMaxTries:t}),tA.getOrCreateInstance().fetch({fetchMaxTries:t})])}catch(t){if(T(t)&&"network_error"===t.code&&this.shouldFallbackToCachedResources()){let t=await this.__internal_getCachedResources?.();e=new t4(t?.environment),tA.clearInstance(),a=tA.getOrCreateInstance(t?.client),++r}else throw t}this.updateClient(a),this.updateEnvironment(e),this.#eS.emit(g,r>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,a]=await Promise.all([t4.getInstance().fetch({touch:!1,fetchMaxTries:1}),tA.getOrCreateInstance().fetch({fetchMaxTries:1})]);this.updateClient(a),this.updateEnvironment(e),this.#eC()};#eW=e=>{if(e.lastActiveSessionId){let a=e.signedInSessions.find(a=>a.id===e.lastActiveSessionId);if(a)return a}return e.signedInSessions[0]||null};#eH=()=>{s()&&(this.#ex?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#eq>Date.now())&&(this.#eq=Date.now()+5e3,this.#e_.touchSession&&this.#eE(this.session))}),this.#ef?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),t3.on(t2,()=>{this.#ef?.postMessage({type:"signout"})}),t3.on(t0,()=>{av.setItem(ay,this.environment?.__internal_toSnapshot(),864e5)}))};#eE=async e=>{if(!e)return Promise.resolve();await e.touch().catch(e=>{I(e)&&this.handleUnauthenticated()})};#eC=()=>{if(this.client)for(let e of this.#ej)e({client:this.client,session:this.session,user:this.user,organization:this.organization})};#eR=()=>{for(let e of this.#ez)e()};#eT=()=>{this.session=void 0,this.organization=void 0,this.user=void 0,this.#eC()};#e1=()=>(this.session?.user.organizationMemberships||[]).map(e=>e.organization).find(e=>e.id===this.session?.lastActiveOrganizationId)||null;#eA=e=>{this.session=e||null,this.organization=this.#e1(),this.user=this.session?this.session.user:null};#eM=e=>this.client?.signedInSessions.find(a=>a.id===e)||null;#eX=()=>{this.addListener(({session:e})=>{e?.actor&&this.#ey?.then(e=>e.ensureMounted()).then(e=>e.mountImpersonationFab())})};#eZ=()=>{this.#e_.__internal_keyless_claimKeylessApplicationUrl&&this.#ey?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#e_.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#e_.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#e_.__internal_keyless_dismissPrompt}})})};#eD=(e,a,t)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let r=this.#e_[e]||this.environment.displayConfig[e];this.#eO()&&(r=this.#e_.signInUrl);let i=new eU(this.#e_,a).toSearchParams(),n=new URLSearchParams(t||{}),s=ev({base:r,hashPath:this.#eO()&&"signUpUrl"===e?"/create":"",hashSearchParams:[n,i]},{stringify:!0});return this.buildUrlWithAuth(s)};assertComponentsReady(e){if(!e)throw Error("Clerk was not loaded with Ui components")}#eQ=async()=>{var e;let a,t,r,i,n=new URLSearchParams(window.location.search).get("redirect_url"),s="production"===this.instanceType,o=null!==n&&(e=this.frontendApi,t=(a=new URL(n,eb)).pathname,r=eq.includes(t)||eS.includes(t),e===a.host&&r);if(s||!o)return!1;let l=this.session,c=this.#e_.signInUrl||this.environment?.displayConfig.signInUrl,d=c&&window.location.href.startsWith(c),u=this.#e_.signUpUrl||this.environment?.displayConfig.signUpUrl,h=u&&window.location.href.startsWith(u);return i=new URL(n,eb),(!eq.includes(i.pathname)||!!l||!d&&!h)&&(await this.navigate(this.buildUrlWithAuth(n)),!0)};#eU=e=>({...ik,...e,allowedRedirectOrigins:function(e,a,t){if(Array.isArray(e)&&e.length)return e;let r=[];return"undefined"!=typeof window&&window.location&&r.push(window.location.origin),r.push(`https://${ew(a)}`),r.push(`https://*.${ew(a)}`),"development"===t&&r.push(`https://${a}`),r}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)});#eY=()=>{try{eP($),eP(eA),eP(K),eP("__clerk_handshake"),eP("__clerk_handshake_nonce"),eP("__clerk_help")}catch{}};get #eF(){let e=eN;return this.#e_.allowedRedirectProtocols&&(e=e.concat(this.#e_.allowedRedirectProtocols)),e}}})();var s=exports;for(var o in n)s[o]=n[o];n.__esModule&&Object.defineProperty(s,"__esModule",{value:!0})})();
|