@clerk/clerk-js 6.0.0-canary.v20260109133726 → 6.0.0-canary.v20260109180221
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/clerk.browser.js +4 -4
- package/dist/clerk.chips.browser.js +4 -4
- package/dist/clerk.headless.browser.js +4 -4
- package/dist/clerk.headless.js +3 -3
- package/dist/clerk.js +1 -1
- package/dist/clerk.legacy.browser.js +1 -1
- package/dist/clerk.mjs +1 -1
- package/dist/clerk.no-rhc.js +1 -1
- package/dist/clerk.no-rhc.mjs +1 -1
- package/package.json +4 -4
- /package/dist/{197_clerk.browser_7b17d3_6.0.0-canary.v20260109133726.js → 197_clerk.browser_2557c6_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{197_clerk.chips.browser_7e2500_6.0.0-canary.v20260109133726.js → 197_clerk.chips.browser_daf61a_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{197_clerk.headless.browser_6b64fb_6.0.0-canary.v20260109133726.js → 197_clerk.headless.browser_8bb9ee_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{197_clerk.headless_f6663b_6.0.0-canary.v20260109133726.js → 197_clerk.headless_fb59f3_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{197_clerk.legacy.browser_c20864_6.0.0-canary.v20260109133726.js → 197_clerk.legacy.browser_7a8f70_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{308_clerk.headless_f6663b_6.0.0-canary.v20260109133726.js → 308_clerk.headless_fb59f3_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{507_clerk.browser_7b17d3_6.0.0-canary.v20260109133726.js → 507_clerk.browser_2557c6_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{507_clerk.chips.browser_7e2500_6.0.0-canary.v20260109133726.js → 507_clerk.chips.browser_daf61a_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{507_clerk.headless.browser_6b64fb_6.0.0-canary.v20260109133726.js → 507_clerk.headless.browser_8bb9ee_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{507_clerk.headless_f6663b_6.0.0-canary.v20260109133726.js → 507_clerk.headless_fb59f3_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{507_clerk.legacy.browser_c20864_6.0.0-canary.v20260109133726.js → 507_clerk.legacy.browser_7a8f70_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{521_clerk.headless_f6663b_6.0.0-canary.v20260109133726.js → 521_clerk.headless_fb59f3_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{527_clerk.browser_7b17d3_6.0.0-canary.v20260109133726.js → 527_clerk.browser_2557c6_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{527_clerk.chips.browser_7e2500_6.0.0-canary.v20260109133726.js → 527_clerk.chips.browser_daf61a_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{527_clerk.headless.browser_6b64fb_6.0.0-canary.v20260109133726.js → 527_clerk.headless.browser_8bb9ee_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{527_clerk.legacy.browser_c20864_6.0.0-canary.v20260109133726.js → 527_clerk.legacy.browser_7a8f70_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{537_clerk.headless_f6663b_6.0.0-canary.v20260109133726.js → 537_clerk.headless_fb59f3_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{604_clerk.headless_f6663b_6.0.0-canary.v20260109133726.js → 604_clerk.headless_fb59f3_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{783_clerk.headless_f6663b_6.0.0-canary.v20260109133726.js → 783_clerk.headless_fb59f3_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{896_clerk.headless_f6663b_6.0.0-canary.v20260109133726.js → 896_clerk.headless_fb59f3_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{973_clerk.headless_f6663b_6.0.0-canary.v20260109133726.js → 973_clerk.headless_fb59f3_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{base-account-sdk_clerk.browser_7b17d3_6.0.0-canary.v20260109133726.js → base-account-sdk_clerk.browser_2557c6_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{base-account-sdk_clerk.chips.browser_7e2500_6.0.0-canary.v20260109133726.js → base-account-sdk_clerk.chips.browser_daf61a_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{base-account-sdk_clerk.headless.browser_6b64fb_6.0.0-canary.v20260109133726.js → base-account-sdk_clerk.headless.browser_8bb9ee_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{base-account-sdk_clerk.legacy.browser_c20864_6.0.0-canary.v20260109133726.js → base-account-sdk_clerk.legacy.browser_7a8f70_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.browser_7b17d3_6.0.0-canary.v20260109133726.js → coinbase-wallet-sdk_clerk.browser_2557c6_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.chips.browser_7e2500_6.0.0-canary.v20260109133726.js → coinbase-wallet-sdk_clerk.chips.browser_daf61a_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.headless.browser_6b64fb_6.0.0-canary.v20260109133726.js → coinbase-wallet-sdk_clerk.headless.browser_8bb9ee_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.legacy.browser_c20864_6.0.0-canary.v20260109133726.js → coinbase-wallet-sdk_clerk.legacy.browser_7a8f70_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{cookieSuffix_clerk.browser_7b17d3_6.0.0-canary.v20260109133726.js → cookieSuffix_clerk.browser_2557c6_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{cookieSuffix_clerk.chips.browser_7e2500_6.0.0-canary.v20260109133726.js → cookieSuffix_clerk.chips.browser_daf61a_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{cookieSuffix_clerk.headless.browser_6b64fb_6.0.0-canary.v20260109133726.js → cookieSuffix_clerk.headless.browser_8bb9ee_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{cookieSuffix_clerk.headless_f6663b_6.0.0-canary.v20260109133726.js → cookieSuffix_clerk.headless_fb59f3_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{cookieSuffix_clerk.legacy.browser_c20864_6.0.0-canary.v20260109133726.js → cookieSuffix_clerk.legacy.browser_7a8f70_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{query-core-vendors_clerk.browser_7b17d3_6.0.0-canary.v20260109133726.js → query-core-vendors_clerk.browser_2557c6_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{query-core-vendors_clerk.chips.browser_7e2500_6.0.0-canary.v20260109133726.js → query-core-vendors_clerk.chips.browser_daf61a_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{query-core-vendors_clerk.headless.browser_6b64fb_6.0.0-canary.v20260109133726.js → query-core-vendors_clerk.headless.browser_8bb9ee_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{query-core-vendors_clerk.legacy.browser_c20864_6.0.0-canary.v20260109133726.js → query-core-vendors_clerk.legacy.browser_7a8f70_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{stripe-vendors_clerk.browser_7b17d3_6.0.0-canary.v20260109133726.js → stripe-vendors_clerk.browser_2557c6_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{stripe-vendors_clerk.chips.browser_7e2500_6.0.0-canary.v20260109133726.js → stripe-vendors_clerk.chips.browser_daf61a_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{stripe-vendors_clerk.headless.browser_6b64fb_6.0.0-canary.v20260109133726.js → stripe-vendors_clerk.headless.browser_8bb9ee_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{stripe-vendors_clerk.legacy.browser_c20864_6.0.0-canary.v20260109133726.js → stripe-vendors_clerk.legacy.browser_7a8f70_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{vendors_clerk.browser_7b17d3_6.0.0-canary.v20260109133726.js → vendors_clerk.browser_2557c6_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{vendors_clerk.chips.browser_7e2500_6.0.0-canary.v20260109133726.js → vendors_clerk.chips.browser_daf61a_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{vendors_clerk.headless.browser_6b64fb_6.0.0-canary.v20260109133726.js → vendors_clerk.headless.browser_8bb9ee_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{vendors_clerk.legacy.browser_c20864_6.0.0-canary.v20260109133726.js → vendors_clerk.legacy.browser_7a8f70_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.browser_7b17d3_6.0.0-canary.v20260109133726.js → zxcvbn-common_clerk.browser_2557c6_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.chips.browser_7e2500_6.0.0-canary.v20260109133726.js → zxcvbn-common_clerk.chips.browser_daf61a_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.headless.browser_6b64fb_6.0.0-canary.v20260109133726.js → zxcvbn-common_clerk.headless.browser_8bb9ee_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.legacy.browser_c20864_6.0.0-canary.v20260109133726.js → zxcvbn-common_clerk.legacy.browser_7a8f70_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.browser_7b17d3_6.0.0-canary.v20260109133726.js → zxcvbn-ts-core_clerk.browser_2557c6_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.chips.browser_7e2500_6.0.0-canary.v20260109133726.js → zxcvbn-ts-core_clerk.chips.browser_daf61a_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.headless.browser_6b64fb_6.0.0-canary.v20260109133726.js → zxcvbn-ts-core_clerk.headless.browser_8bb9ee_6.0.0-canary.v20260109180221.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.legacy.browser_c20864_6.0.0-canary.v20260109133726.js → zxcvbn-ts-core_clerk.legacy.browser_7a8f70_6.0.0-canary.v20260109180221.js} +0 -0
package/dist/clerk.no-rhc.mjs
CHANGED
|
@@ -16,4 +16,4 @@ ${a.message}`)}})(ex(e)):e).some(e=>e.test(ex(r.origin))));return n||Q(`Clerk: R
|
|
|
16
16
|
${e.trim()}
|
|
17
17
|
(This notice only appears in development)`,eN={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=>eD(`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=>eD(`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(eN)){let a=eN[e];"function"!=typeof a&&(eN[e]=eD(a))}let eW="clerk:beforeunload",eL=["http:","https:","wails:","chrome-extension:"];function e$(e){let a=new URL(e,window.location.href);window.dispatchEvent(new CustomEvent(eW)),window.location.href=a.href}function eK(e){return/^http(s)?:\/\//.test(e||"")}function eB(e){return e.startsWith("/")}var eJ=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]))}},eV=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}},eG=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 eH=new Set(["error","warn","info","debug","trace"]);var eQ=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??"";let a=eh(e.publishableKey);a&&(this.#L.instanceType=a.instanceType),e.secretKey&&(this.#L.secretKey=e.secretKey.substring(0,16)),this.#W=new eJ(eV.isSupported()?new eV:new eG)}get isEnabled(){return!("development"!==this.#L.instanceType||this.#N.disabled||"undefined"!=typeof process&&process.env&&ei(process.env.CLERK_TELEMETRY_DISABLED)||"undefined"!=typeof window&&window?.navigator?.webdriver)}get isDebug(){return this.#N.debug||"undefined"!=typeof process&&process.env&&ei(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&&eH.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.#Z(e,a)}#H(e){return!0}#Z(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.#X();if(this.#$.length>=this.#N.maxBufferSize){this.#K&&("undefined"!=typeof cancelIdleCallback?cancelIdleCallback(Number(this.#K)):clearTimeout(Number(this.#K))),this.#X();return}this.#K||("requestIdleCallback"in window?this.#K=requestIdleCallback(()=>{this.#X(),this.#K=null}):this.#K=setTimeout(()=>{this.#X(),this.#K=null},0))}#X(){let e=[...this.#$];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 eY="COMPONENT_MOUNTED",eZ=new Set(["SignIn","SignUp"]);function eX(e){return function(a,t,r){return{event:e,eventSamplingRate:e===eY?eZ.has(a)?1:.1:.1,payload:{component:a,appearanceProp:!!t?.appearance,theme:!!t?.appearance?.theme,elements:!!t?.appearance?.elements,variables:!!t?.appearance?.variables,...r}}}}function e1(e,a,t){return eX(eY)(e,a,t)}function e2(e,a,t){return eX("COMPONENT_OPENED")(e,a,t)}function e0(e){return"string"==typeof e?e:"object"==typeof e&&null!==e&&"name"in e&&"string"==typeof e.name?e.name:void 0}function e9(e,a,t){return"function"==typeof e?e(a):void 0!==e?e:void 0!==t?t:void 0}let e3=(...e)=>{},e8=!1,e5=null,e4=!1,e6=[];function e7(e,a,t,r){e8&&(e6.push({level:e,message:a,context:t,source:r,ts:Date.now()}),e6.length>200&&e6.shift())}async function ae(e){try{if(!e8||e5)return;let{getDebugLogger:a}=await Promise.resolve().then(i.bind(i,854)),t=await a({logLevel:e?.logLevel,telemetryCollector:e?.telemetryCollector});if(t&&(e5=t)&&0!==e6.length){for(let e of e6){let a={...e.context||{},__preInit:!0,__preInitTs:e.ts};switch(e.level){case"error":e5.error(e.message,a,e.source);break;case"warn":e5.warn(e.message,a,e.source);break;case"info":e5.info(e.message,a,e.source);break;case"debug":e5.debug(e.message,a,e.source)}}e6.length=0}}catch(e){try{console.debug?.("Debug logger initialization failed",e)}catch{}return}}let aa={debug(e,a,t){e5?e5.debug(e,a,t):e7("debug",e,a,t)},error(e,a,t){e5?e5.error(e,a,t):e7("error",e,a,t)},info(e,a,t){e5?e5.info(e,a,t):e7("info",e,a,t)},warn(e,a,t){e5?e5.warn(e,a,t):e7("warn",e,a,t)}},at={initialDelay:125,maxDelayBetweenRetries:0,factor:2,shouldRetry:(e,a)=>a<5,retryImmediately:!1,jitter:!0},ar=async e=>new Promise(a=>setTimeout(a,e)),ai=(e,a)=>a?e*(1+Math.random()):e,an=async(e,a={})=>{var t;let r,i=0,{shouldRetry:n,initialDelay:s,maxDelayBetweenRetries:o,factor:l,retryImmediately:c,jitter:d,onBeforeRetry:u}={...at,...a},h=(t={initialDelay:s,maxDelayBetweenRetries:o,factor:l,jitter:d},r=0,async()=>{let e;await ar((e=ai(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 ar(ai(100,d)):await h()}},as=async e=>an(e,{initialDelay:100,shouldRetry:(e,a)=>a<=3,retryImmediately:!0,factor:2});class ao{#ee={"@zxcvbn-ts/core":()=>as(()=>Promise.resolve().then(i.bind(i,10))),"@zxcvbn-ts/language-common":()=>as(()=>Promise.resolve().then(i.bind(i,655))),"@base-org/account":()=>as(()=>Promise.resolve().then(function(){var e=Error("Cannot find module '@base-org/account'");throw e.code="MODULE_NOT_FOUND",e})),"@coinbase/wallet-sdk":()=>as(()=>Promise.resolve().then(function(){var e=Error("Cannot find module '@coinbase/wallet-sdk'");throw e.code="MODULE_NOT_FOUND",e})),"@stripe/stripe-js":()=>as(()=>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 al=(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(eW,t)},stopListening:()=>{window.removeEventListener("beforeunload",t),window.removeEventListener(eW,t)},isUnloading:()=>a});return{track:async e=>{r.startListening(),await e(),r.stopListening()},isUnloading:r.isUnloading}},ac=e=>({amount:e.amount,amountFormatted:e.amount_formatted,currency:e.currency,currencySymbol:e.currency_symbol}),ad=e=>{let a={grandTotal:ac(e.grand_total),subtotal:ac(e.subtotal),taxTotal:ac(e.tax_total)};return"past_due"in e&&(a.pastDue=e.past_due?ac(e.past_due):null),"credit"in e&&(a.credit=e.credit?ac(e.credit):null),"total_due_now"in e&&(a.totalDueNow=ac(e.total_due_now)),"total_due_after_free_trial"in e&&(a.totalDueAfterFreeTrial=e.total_due_after_free_trial?ac(e.total_due_after_free_trial):null),a};function au(e,a=""){return e.errors&&!!e.errors.find(e=>e.code===a)}let ah=S({packageName:"@clerk/clerk-js"});function am(e){return decodeURIComponent(globalThis.atob(e.replace(/_/g,"/").replace(/-/g,"+")).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""))}function ap(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(am(r)),s={__raw:e};return Object.keys(n).forEach(e=>{s[e]=n[e]}),{encoded:{header:t,payload:r,signature:i},header:JSON.parse(am(t)),claims:s}}function ag(){if(!o())return null;try{let e=navigator?.language;if(!e||"string"!=typeof e||""===e.trim())return null;return e}catch{return null}}function ab(){return void 0!==globalThis.document}function af(){if(!function(){if(!ab())return!1;try{return window.self!==window.top}catch{return!0}}())return!1;try{return window.top?.location.href,!1}catch{return!0}}var ay=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)}},ak=class e{#en=void 0;#es=!1;static #er=null;constructor(){}async #eo(){if(this.#es)return;this.#es=!0;let e=await Promise.resolve().then(i.bind(i,76)).then(e=>e.getWallets());this.#en=e.get(),e.on("register",()=>{this.#en=e.get()}),e.on("unregister",()=>{this.#en=e.get()})}#el(e){return e.chains?.some(e=>e.startsWith("solana:"))??!1}#ec(e){return"solana:signMessage"in e.features}static getInstance(){return e.#er||(e.#er=new e),e.#er}get=async e=>{await this.#eo();let a=(this.#en||[]).find(a=>a.name===e&&this.#el(a)&&this.#ec(a));if(a&&this.#el(a))return a;if("undefined"==typeof window)return;let t=window.solana;if(t&&"function"==typeof t.connect&&"function"==typeof t.signMessage)return t}};let aw=()=>(function(e){let a=S({packageName:"@clerk/shared"});async function t(e){let{provider:a,walletName:t}=e,r=await p(a,t);if(!r)return"";if("solana"===a){let e=await r.features["standard:connect"].connect();return e&&e.accounts[0].address||""}let i=await r.request({method:"eth_requestAccounts"});return i&&i[0]||""}let r=async e=>{let{identifier:a,nonce:t,provider:r,walletName:i=""}=e,n=await p(r,i);if(!n)return"";if("solana"===r)try{let e=n.accounts.find(e=>e.address===a);if(!e)return console.warn(`Wallet account with address ${a} not found`),"";let r=await n.features["solana:signMessage"]?.signMessage({account:e,message:new TextEncoder().encode(t)});return r?.[0]?.signature?btoa(String.fromCharCode(...r[0].signature)):""}catch(e){if(e instanceof Error&&e.message.includes("User rejected the request."))throw new I("Web3 signature request was rejected by the user.",{code:"web3_signature_request_rejected"});throw new I("An error occurred while generating the Solana signature.",{code:"web3_solana_signature_generation_failed",cause:e instanceof Error?e:void 0})}return await n.request({method:"personal_sign",params:[`0x${t.split("").map(e=>e.charCodeAt(0).toString(16).padStart(2,"0")).join("")}`,a]})};async function i(){return await t({provider:"metamask"})}async function n(){return await t({provider:"coinbase_wallet"})}async function s(){return await t({provider:"okx_wallet"})}async function o(){return await t({provider:"base"})}async function l(e){return await t({provider:"solana",walletName:e})}async function c(e){return await r({...e,provider:"metamask"})}async function d(e){return await r({...e,provider:"coinbase_wallet"})}async function u(e){return await r({...e,provider:"okx_wallet"})}async function h(e){return await r({...e,provider:"base"})}async function m(e){return await r({...e,provider:"solana"})}async function p(t,r){if("coinbase_wallet"===t){let a=await e.import("@coinbase/wallet-sdk");return a?a.createCoinbaseWalletSDK({appName:"undefined"!=typeof window&&window.Clerk?.__internal_environment?.displayConfig?.applicationName||"undefined"!=typeof document&&document.title||"Web3 Application",preference:{options:"all"}}).getProvider():null}if("base"===t)try{let a=await e.import("@base-org/account");if(!a)return null;return a.createBaseAccountSDK({appName:"undefined"!=typeof window&&window.Clerk?.__internal_environment?.displayConfig?.applicationName||"undefined"!=typeof document&&document.title||"Web3 Application"}).getProvider()}catch{return null}return"solana"===t?r&&0!==r.length?await ak.getInstance().get(r):void a.throw("Wallet name must be provided to get Solana wallet provider"):ay.getInstance().get(t)}return{getWeb3Identifier:t,generateWeb3Signature:r,getMetamaskIdentifier:i,getCoinbaseWalletIdentifier:n,getOKXWalletIdentifier:s,getBaseIdentifier:o,getSolanaIdentifier:l,generateSignatureWithMetamask:c,generateSignatureWithCoinbaseWallet:d,generateSignatureWithOKXWallet:u,generateSignatureWithBase:h,generateSignatureWithSolana:m}})(new ao),av="environment",aj=JSON.stringify,az=JSON.parse;class a_{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),aj(r))}catch{}}static getItem(e,a){try{let t=window.localStorage.getItem(this._key(e));if(!t)return a;let r=az(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 ax="ClerkJS:";function aq(e){console.warn(`${ax} ${e} is not supported in this environment.`)}function aS(e=""){throw Error(`${ax} Something went wrong initializing Clerk in development mode.${e&&` ${e}`}`)}function aU(e){throw Error(`${ax} Something went wrong initializing Clerk during the ${e} flow. Please contact support.`)}function aC(e){throw Error(`${ax} You need to start a ${e} flow by calling ${e}.create() first.`)}function aA(e,a){throw Error(`${ax} Strategy "${a}" is not a valid strategy for ${e}.`)}function aI(e){throw Error(`${ax} You need to start a ${e} flow by calling ${e}.create({ identifier: 'your web3 wallet address' }) first`)}function aP(e=""){throw Error(`${ax} Missing '${e}' option`)}function aO(e,a){throw Error(`${ax} Response: ${e||0} not supported yet.
|
|
18
18
|
For more information contact us at ${a}`)}function aT(e){throw Error(`${ax} Missing publicKey. When calling 'navigator.credentials.${e}()' it is required to pass a publicKey object.`)}let aE=e=>Promise.reject(Error("Captcha not supported in this environment")),aM=e=>{let a=e.__internal_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 aR{clerk;constructor(e){this.clerk=e}async invisible(e){let{captchaSiteKey:a,canUseCaptcha:t,captchaPublicKeyInvisible:r,nonce:i}=aM(this.clerk);return t&&a&&r?{...await aE({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}=aM(this.clerk);if(t&&a&&n){let t=await aE({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 aF{client;CaptchaChallengeImpl;static instance;inflightException=null;captchaRetryCount=0;MAX_RETRY_ATTEMPTS=3;static getInstance(){return aF.instance||(aF.instance=new aF(tR,aR)),aF.instance}constructor(e,a){this.client=e,this.CaptchaChallengeImpl=a}async execute(e,a){if(this.captchaAttemptsExceeded())throw new I("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(!_(r)||P(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 aD{static clerk;id;pathRoot="";static get fapiClient(){return aD.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 aF.getInstance().execute(this.clerk,()=>this._baseFetch(e,a))}static async _baseFetch(e,a={}){let t;aD.fapiClient||function(){throw Error(`${ax} Missing FAPI client in resources.`)}();let{fetchMaxTries:r}=a;try{t=await aD.fapiClient.request(e,{fetchMaxTries:r})}catch(a){if(this.shouldRethrowOfflineNetworkErrors())throw new I(a?.message||a,{code:"network_error"});if(!u())return aa.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 aD.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=aD.clerk.publishableKey).startsWith("live_")||t.startsWith("pk_live_"))){let t=aD.clerk.frontendApi.replace("clerk.","");throw new z(`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 z(a||s,r)}return null}static _updateClient(e){if(!e)return;let a=e.client||e.meta?.client;a&&aD.clerk&&aD.clerk.updateClient(tR.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 aD._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 aD._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 aD._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=aD.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}function aN(e){let a=new Date(e||new Date);return a instanceof Date&&!isNaN(a.getTime())?a:new Date}class aW extends aD{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?aN(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?aN(e.last_used_at):null,this.updatedAt=aN(e.updated_at),this.createdAt=aN(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 aL extends aD{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?aN(e.claimed_at):null,this.claimedAt),this.reverification=this.withDefault(e.reverification,this.reverification),this.singleSessionMode=this.withDefault(e.single_session_mode,this.singleSessionMode),this.preferredChannels=this.withDefault(e.preferred_channels,this.preferredChannels)),this}__internal_toSnapshot(){return{claimed_at:this.claimedAt?this.claimedAt.getTime():null,id:this.id??"",object:"auth_config",reverification:this.reverification,single_session_mode:this.singleSessionMode}}}(y=w||(w={}))[y.None=0]="None",y[y.Mutable=1]="Mutable",y[y.Watching=2]="Watching",y[y.RecursedCheck=4]="RecursedCheck",y[y.Recursed=8]="Recursed",y[y.Dirty=16]="Dirty",y[y.Pending=32]="Pending";let a$=[],{link:aK,unlink:aB,propagate:aJ,checkDirty:aV,endTracking:aG,startTracking:aH,shallowPropagate:aQ}=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?a3(e):a8(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):a$[aX++]=a}},unwatched(e){if("getter"in e){let a=e.deps;if(void 0!==a){e.flags=17;do a=aB(a,e);while(void 0!==a)}}else"previousValue"in e||a7.call(e)}}),aY=0,aZ=0,aX=0;function a1(a){let t=e;return e=a,t}function a2(e){return a6.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function a0(e){return a4.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function a9(t){let r={fn:t,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==e?aK(r,e):void 0!==a&&aK(r,a);let i=a1(r);try{r.fn()}finally{a1(i)}return a7.bind(r)}function a3(e){let a=a1(e);aH(e);try{let a=e.value;return a!==(e.value=e.getter(a))}finally{a1(a),aG(e)}}function a8(e,a){return e.flags=1,e.previousValue!==(e.previousValue=a)}function a5(){for(;aZ<aX;){let e=a$[aZ];a$[aZ++]=void 0,function e(a,t){if(16&t||32&t&&aV(a.deps,a)){let e=a1(a);aH(a);try{a.fn()}finally{a1(e),aG(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)}aZ=0,aX=0}function a4(){let t=this.flags;if(16&t||32&t&&aV(this.deps,this)){if(a3(this)){let e=this.subs;void 0!==e&&aQ(e)}}else 32&t&&(this.flags=-33&t);return void 0!==e?aK(this,e):void 0!==a&&aK(this,a),this.value}function a6(...a){if(a.length){let e=a[0];if(this.value!==(this.value=e)){this.flags=17;let e=this.subs;void 0!==e&&(aJ(e),aY||a5())}}else{let a=this.value;if(16&this.flags&&a8(this,a)){let e=this.subs;void 0!==e&&aQ(e)}return void 0!==e&&aK(this,e),a}}function a7(){let e=this.deps;for(;void 0!==e;)e=aB(e,this);let a=this.subs;void 0!==a&&aB(a),this.flags=0}function te(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 ta{static #ed="/billing";static path(e,a){let{orgId:t}=a||{},r=t?`/organizations/${t}`:"/me";return`${r}${ta.#ed}${e}`}getPlans=async e=>{let{for:a,...t}=e||{},r={...t,payer_type:"organization"===a?"org":"user"};return await aD._fetch({path:`${ta.#ed}/plans`,method:"GET",search:te(r)}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new tx(e))}})};getPlan=async e=>new tx(await aD._fetch({path:`${ta.#ed}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await aD._fetch({path:ta.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new tU(e?.response));getStatements=async e=>{let{orgId:a,...t}=e;return await aD._fetch({path:ta.path("/statements",{orgId:a}),method:"GET",search:te(t)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new tq(e))}})};getStatement=async e=>new tq((await aD._fetch({path:ta.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:a,...t}=e;return await aD._fetch({path:ta.path("/payment_attempts",{orgId:a}),method:"GET",search:te(t)}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new ty(e))}})};getPaymentAttempt=async e=>new ty(await aD._fetch({path:ta.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:a,...t}=e;return new tb((await aD._fetch({path:ta.path("/checkouts",{orgId:a}),method:"POST",body:t}))?.response)}}let tt=a2({resource:null}),tr=a2({error:null}),ti=a2({status:"idle"}),tn=a0(()=>{let e=tt().resource,a=tr().error,t=ti().status;return{errors:tp(a,{identifier:null,password:null,code:null}),fetchStatus:t,signIn:e?e.__internal_future:null}}),ts=a2({resource:null}),to=a2({error:null}),tl=a2({status:"idle"}),tc=a0(()=>{let e=ts().resource,a=to().error,t=tl().status;return{errors:tp(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}}),td=a2({resource:null}),tu=a2({error:null}),th=a2({status:"idle"}),tm=a0(()=>{let e=td().resource,a=tu().error,t=th().status;return{errors:tp(a,{emailAddress:null}),fetchStatus:t,waitlist:e}});function tp(e,a){let t={fields:{...a},raw:null,global:null};if(!e)return t;if(!_(e))return t.raw=[e],t.global=[N(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=X(e.meta.paramName);a in t.fields&&(t.fields[a]=e)}}):(t.raw=[e],t.global=[N(e)]),t}class tg extends aD{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=aN(e.created_at)),e.updated_at&&(this.updatedAt=aN(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 tb extends aD{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 tz(e.payment_method):void 0,this.plan=new tx(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=ad(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change,e.free_trial_ends_at&&(this.freeTrialEndsAt=aN(e.free_trial_ends_at)),this.payer=new tg(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>an(()=>this._basePatch({path:ta.path(`/checkouts/${this.id}/confirm`,{orgId:this.payer.organizationId}),body:e}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,a){if(!_(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 tf{resource=new tb(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 tb.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new tb(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 tb.clerk.setActive({session:tb.clerk.session?.id,navigate:a})})}runAsyncCheckoutTask(e,a,t){var r,i,n;return void 0===tb.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()=>{++aY,i.errorSignal({error:null}),i.fetchSignal({status:"fetching"}),t?.(),--aY||a5(),++aY;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"}),--aY||a5()}})();return n.set(e,s),s})(e,a,t)}}class ty extends aD{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=ac(e.amount),this.paidAt=e.paid_at?aN(e.paid_at):null,this.failedAt=e.failed_at?aN(e.failed_at):null,this.updatedAt=aN(e.updated_at),this.paymentMethod=e.payment_method?new tz(e.payment_method):null,this.subscriptionItem=new tC(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status),this}}let tk="/payment_methods",tw=async e=>{let{orgId:a,...t}=e;return new t_((await aD._fetch({path:ta.path(`${tk}/initialize`,{orgId:a}),method:"POST",body:t}))?.response)},tv=async e=>{let{orgId:a,...t}=e;return new tz((await aD._fetch({path:ta.path(tk,{orgId:a}),method:"POST",body:t}))?.response)},tj=async e=>{let{orgId:a,...t}=e??{};return await aD._fetch({path:ta.path(tk,{orgId:a}),method:"GET",search:te(t)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new tz(e))}})};class tz extends aD{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:aN(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:aN(e.updated_at)),this}async remove(e){let{orgId:a}=e??{};return new tD((await aD._fetch({path:ta.path(`/payment_methods/${this.id}`,{orgId:a}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:a}=e??{};return await aD._fetch({path:ta.path("/payers/default_payment_method",{orgId:a}),method:"PUT",body:{payment_method_id:this.id}}),null}}class t_ extends aD{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 tx extends aD{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=ac(e.fee),this.annualFee=e.annual_fee?ac(e.annual_fee):null,this.annualMonthlyFee=e.annual_monthly_fee?ac(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 ro(e))),this}}class tq extends aD{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=aN(e.timestamp),this.totals=ad(e.totals),this.groups=e.groups.map(e=>new tS(e))),this}}class tS{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=aN(e.timestamp),this.items=e.items.map(e=>new ty(e))),this}}class tU extends aD{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=aN(e.created_at),this.updatedAt=e.updated_at?aN(e.updated_at):null,this.activeAt=aN(e.active_at),this.pastDueAt=e.past_due_at?aN(e.past_due_at):null,e.next_payment&&(this.nextPayment={amount:ac(e.next_payment.amount),date:aN(e.next_payment.date)}),this.subscriptionItems=(e.subscription_items||[]).map(e=>new tC(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1)),this}}class tC extends aD{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 tx(e.plan),this.planPeriod=e.plan_period,this.status=e.status,this.createdAt=aN(e.created_at),this.pastDueAt=e.past_due_at?aN(e.past_due_at):null,this.periodStart=aN(e.period_start),this.periodEnd=e.period_end?aN(e.period_end):null,this.canceledAt=e.canceled_at?aN(e.canceled_at):null,this.amount=e.amount?ac(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:ac(e.credit.amount)}:void 0,this.isFreeTrial=this.withDefault(e.is_free_trial,!1)),this}async cancel(e){let{orgId:a}=e;return new tD((await aD._fetch({path:ta.path(`/subscription_items/${this.id}`,{orgId:a}),method:"DELETE"}))?.response)}}let tA={build:(e,a,t)=>[e,a,t].filter(Boolean).join("-"),parse:(e,a,t)=>{let r=tA.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}},tI="clerk",tP=10,tO={broadcast:!0},tT={broadcast:!1};class tE{prefix;data;static fromKey(e){let[a,t,r=""]=e.split("::");return new tE(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 tM=((e=tI)=>{let a=new Map,t=Math.random().toString(36).slice(2),r=null,i=()=>r||("undefined"==typeof BroadcastChannel?null:((r=new BroadcastChannel("clerk:session_token")).addEventListener("message",e=>{s(e)}),r));i();let n=(t,r=tP)=>{i();let n=new tE(e,t),s=a.get(n.toKey());if(!s)return;let o=Math.floor(Date.now()/1e3)-s.createdAt;if(s.expiresIn-o<(r||1)+5){void 0!==s.timeoutId&&clearTimeout(s.timeoutId),a.delete(n.toKey());return}return s.entry},s=async({data:e})=>{let a,r=tA.build(e.sessionId,e.template,e.organizationId);if(e.tokenId!==r)return void aa.warn("Ignoring token broadcast with mismatched tokenId",{expectedTokenId:r,organizationId:e.organizationId,receivedTokenId:e.tokenId,tabId:t,template:e.template,traceId:e.traceId},"tokenCache");try{a=new rJ({id:e.tokenId,jwt:e.tokenRaw,object:"token"})}catch(a){aa.warn("Failed to parse token from broadcast, skipping cache update",{error:a,tabId:t,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");return}let i=a.jwt?.claims?.iat,s=a.jwt?.claims?.exp;if(!i||!s)return void aa.warn("Token missing iat/exp claim, skipping cache update",{tabId:t,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");try{let a=n({tokenId:e.tokenId});if(a){let r=await a.tokenResolver,n=r.jwt?.claims?.iat;if(n&&n>=i)return void aa.debug("Ignoring older token broadcast",{existingIat:n,incomingIat:i,tabId:t,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}}catch(a){aa.warn("Existing entry compare failed; proceeding with broadcast update",{error:a,tabId:t,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}aa.info("Updating token cache from broadcast",{iat:i,organizationId:e.organizationId,tabId:t,template:e.template,tokenId:e.tokenId,traceId:e.traceId},"tokenCache"),o({createdAt:i,tokenId:e.tokenId,tokenResolver:Promise.resolve(a)},tT)},o=(i,n=tO)=>{let s=new tE(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=tA.extractTemplate(i.tokenId,e,n),o=tA.build(e,s,n);if(i.tokenId===o){let a=`bc_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;aa.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)};return{clear:()=>{a.forEach(e=>{void 0!==e.timeoutId&&clearTimeout(e.timeoutId)}),a.clear()},close:()=>{r&&(r.close(),r=null)},get:n,set:e=>{i(),o(e,tO)},size:()=>a.size}})();class tR extends aD{static instance;pathRoot="/client";sessions=[];signUp=new r$;signIn=new rN;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return tR.instance||(tR.instance=new tR(e)),tR.instance}static clearInstance(){tR.instance=null}static isClientResource(e){return!!e&&e instanceof tR}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(()=>{tM.clear(),this.id="",this.sessions=[],this.signUp=new r$(null),this.signIn=new rN(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=>(tM.clear(),e))}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return aD.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 rI(e)),this.signUp=new r$(e.sign_up),this.signIn=new rN(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?aN(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=aN(e.created_at||void 0),this.updatedAt=aN(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 tF extends aD{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 tD{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 tN extends aD{afterCreateOrganizationUrl="";afterJoinWaitlistUrl="";afterLeaveOrganizationUrl="";afterSignInUrl="";afterSignOutAllUrl="";afterSignOutOneUrl="";afterSignOutUrl="";afterSignUpUrl="";afterSwitchSessionUrl="";applicationName="";backendHost="";branded=!1;captchaHeartbeat=!1;captchaHeartbeatIntervalMs;captchaOauthBypass=["oauth_google","oauth_microsoft","oauth_apple"];captchaProvider="turnstile";captchaPublicKey=null;captchaPublicKeyInvisible=null;captchaWidgetType=null;clerkJSVersion;createOrganizationUrl="";faviconImageUrl="";googleOneTapClientId;homeUrl="";id="";instanceEnvironmentType="";logoImageUrl="";organizationProfileUrl="";preferredSignInStrategy="password";privacyPolicyUrl="";showDevModeWarning=!1;signInUrl="";signUpUrl="";supportEmail="";termsUrl="";theme={};userProfileUrl="";waitlistUrl="";constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.afterCreateOrganizationUrl=this.withDefault(e.after_create_organization_url,this.afterCreateOrganizationUrl),this.afterJoinWaitlistUrl=this.withDefault(e.after_join_waitlist_url,this.afterJoinWaitlistUrl),this.afterLeaveOrganizationUrl=this.withDefault(e.after_leave_organization_url,this.afterLeaveOrganizationUrl),this.afterSignInUrl=this.withDefault(e.after_sign_in_url,this.afterSignInUrl),this.afterSignOutAllUrl=this.withDefault(e.after_sign_out_all_url,this.afterSignOutAllUrl),this.afterSignOutOneUrl=this.withDefault(e.after_sign_out_one_url,this.afterSignOutOneUrl),this.afterSignUpUrl=this.withDefault(e.after_sign_up_url,this.afterSignUpUrl),this.afterSwitchSessionUrl=this.withDefault(e.after_switch_session_url,this.afterSwitchSessionUrl),this.applicationName=this.withDefault(e.application_name,this.applicationName),this.branded=this.withDefault(e.branded,this.branded),this.captchaHeartbeat=this.withDefault(e.captcha_heartbeat,this.captchaHeartbeat),this.captchaHeartbeatIntervalMs=this.withDefault(e.captcha_heartbeat_interval_ms,this.captchaHeartbeatIntervalMs),this.captchaOauthBypass=this.withDefault(e.captcha_oauth_bypass,this.captchaOauthBypass),this.captchaProvider=this.withDefault(e.captcha_provider,this.captchaProvider),this.captchaPublicKey=this.withDefault(e.captcha_public_key,this.captchaPublicKey),this.captchaPublicKeyInvisible=this.withDefault(e.captcha_public_key_invisible,this.captchaPublicKeyInvisible),this.captchaWidgetType=this.withDefault(e.captcha_widget_type,this.captchaWidgetType),this.clerkJSVersion=this.withDefault(e.clerk_js_version,this.clerkJSVersion),this.createOrganizationUrl=this.withDefault(e.create_organization_url,this.createOrganizationUrl),this.faviconImageUrl=this.withDefault(e.favicon_image_url,this.faviconImageUrl),this.googleOneTapClientId=this.withDefault(e.google_one_tap_client_id,this.googleOneTapClientId),this.homeUrl=this.withDefault(e.home_url,this.homeUrl),this.id=this.withDefault(e.id,this.id),this.instanceEnvironmentType=this.withDefault(e.instance_environment_type,this.instanceEnvironmentType),this.logoImageUrl=this.withDefault(e.logo_image_url,this.logoImageUrl),this.organizationProfileUrl=this.withDefault(e.organization_profile_url,this.organizationProfileUrl),this.preferredSignInStrategy=this.withDefault(e.preferred_sign_in_strategy,this.preferredSignInStrategy),this.privacyPolicyUrl=this.withDefault(e.privacy_policy_url,this.privacyPolicyUrl),this.showDevModeWarning=this.withDefault(e.show_devmode_warning,this.showDevModeWarning),this.signInUrl=this.withDefault(e.sign_in_url,this.signInUrl),this.signUpUrl=this.withDefault(e.sign_up_url,this.signUpUrl),this.supportEmail=this.withDefault(e.support_email,this.supportEmail),this.termsUrl=this.withDefault(e.terms_url,this.termsUrl),this.theme=this.withDefault(e.theme,this.theme),this.userProfileUrl=this.withDefault(e.user_profile_url,this.userProfileUrl),this.waitlistUrl=this.withDefault(e.waitlist_url,this.waitlistUrl)),this}__internal_toSnapshot(){return{object:"display_config",after_create_organization_url:this.afterCreateOrganizationUrl,after_join_waitlist_url:this.afterJoinWaitlistUrl,after_leave_organization_url:this.afterLeaveOrganizationUrl,after_sign_in_url:this.afterSignInUrl,after_sign_out_all_url:this.afterSignOutAllUrl,after_sign_out_one_url:this.afterSignOutOneUrl,after_sign_up_url:this.afterSignUpUrl,after_switch_session_url:this.afterSwitchSessionUrl,application_name:this.applicationName,branded:this.branded,captcha_heartbeat_interval_ms:this.captchaHeartbeatIntervalMs,captcha_heartbeat:this.captchaHeartbeat,captcha_oauth_bypass:this.captchaOauthBypass,captcha_provider:this.captchaProvider,captcha_public_key_invisible:this.captchaPublicKeyInvisible,captcha_public_key:this.captchaPublicKey,captcha_widget_type:this.captchaWidgetType,clerk_js_version:this.clerkJSVersion,create_organization_url:this.createOrganizationUrl,favicon_image_url:this.faviconImageUrl,google_one_tap_client_id:this.googleOneTapClientId,home_url:this.homeUrl,id:this.id,instance_environment_type:this.instanceEnvironmentType,logo_image_url:this.logoImageUrl,organization_profile_url:this.organizationProfileUrl,preferred_sign_in_strategy:this.preferredSignInStrategy,privacy_policy_url:this.privacyPolicyUrl,show_devmode_warning:this.showDevModeWarning,sign_in_url:this.signInUrl,sign_up_url:this.signUpUrl,support_email:this.supportEmail,terms_url:this.termsUrl,theme:this.theme,user_profile_url:this.userProfileUrl,waitlist_url:this.waitlistUrl}}}var tW='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 tL=(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}},t$=()=>{let e=0,a=()=>e++,t=new Map,r=(e,a)=>e?.postMessage(a),i=e=>{t.get(e.data.id)?.()},n=tL(tW,{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:e3};let s=()=>{n||(n=tL(tW,{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 tK({delayInMs:e}={delayInMs:1e3}){let a,t=t$(),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 tB extends aD{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}=tK();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}=tK();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 t0(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new rl(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 tJ=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 tV(e){try{let a=await navigator.credentials.create({publicKey:e});if(!a)return{error:new O("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 O(a.message,{code:"passkey_already_exists"}):"NotAllowedError"===a.name?new O(a.message,{code:"passkey_registration_cancelled"}):tQ(a),publicKeyCredential:null}}}let tG=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 tH({publicKeyOptions:e,conditionalUI:a}){try{let t=await navigator.credentials.get({publicKey:e,mediation:a?"conditional":"optional",signal:tG.createAbortSignal()});if(!t)return{error:new O("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 O(t.message,{code:"passkey_retrieval_cancelled"}):tQ(t),publicKeyCredential:null}}}function tQ(e){return"AbortError"===e.name?new O(e.message,{code:"passkey_operation_aborted"}):"SecurityError"===e.name?new O(e.message,{code:"passkey_invalid_rpID_or_domain"}):e}function tY(e){let a=t2(e.challenge),t=(e.allowCredentials||[]).map(e=>({...e,id:t2(e.id)}));return{...e,allowCredentials:t,challenge:a}}function tZ(e){return{type:e.type,id:e.id,rawId:t1(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function tX(e){let a=e.response;return{...tZ(e),response:{clientDataJSON:t1(a.clientDataJSON),authenticatorData:t1(a.authenticatorData),signature:t1(a.signature),userHandle:a.userHandle?t1(a.userHandle):null}}}let t1=tJ.encode.bind(tJ),t2=tJ.decode.bind(tJ);class t0 extends aD{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===aD.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=aN(e.expire_at||void 0),this.error=e.error?new v(e.error):null,this.channel=e.channel||void 0),this}__internal_toSnapshot(){var e;return{object:"verification",id:this.id||"",status:this.status,strategy:this.strategy,nonce:this.nonce,message:this.message,external_verification_redirect_url:this.externalVerificationRedirectURL?.toString()||null,attempts:this.attempts,expire_at:this.expireAt?.getTime()||null,error:(e=this.error,{code:e?.code||"",message:e?.message||"",long_message:e?.longMessage,meta:{param_name:e?.meta?.paramName,session_id:e?.meta?.sessionId,email_addresses:e?.meta?.emailAddresses,identifiers:e?.meta?.identifiers,zxcvbn:e?.meta?.zxcvbn,plan:e?.meta?.plan,is_plan_upgrade_possible:e?.meta?.isPlanUpgradePossible}}),verified_at_client:this.verifiedAtClient}}}class t9 extends t0{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=t2((a=JSON.parse(e.nonce)).user.id),r=t2(a.challenge),i=(a.excludeCredentials||[]).map(e=>({...e,id:t2(e.id)})),{...a,excludeCredentials:i,challenge:r,user:{...a.user,id:t}})),this}}class t3{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new t8(e.email_address),this.phoneNumber=new t8(e.phone_number),this.web3Wallet=new t8(e.web3_wallet),this.externalAccount=new t0(e.external_account)):(this.emailAddress=new t8(null),this.phoneNumber=new t8(null),this.web3Wallet=new t8(null),this.externalAccount=new t0(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 t8 extends t0{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 t5 extends aD{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?aN(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new t0(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new t4(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 t4 extends aD{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=aN(e.created_at),this.updatedAt=aN(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 t6="token:update",t7="user:signOut",re="environment:update",ra="session:tokenResolved",rt=g();class rr extends aD{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 ri extends aD{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 rn extends aD{static instance;authConfig=new aL;displayConfig=new tN;maintenanceMode=!1;clientDebugMode=!1;pathRoot="/environment";userSettings=new rX;organizationSettings=new ri;commerceSettings=new tF;apiKeysSettings=new rr;protectConfig=new rz;static getInstance(){return rn.instance||(rn.instance=new rn),rn.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new aL(e.auth_config),this.displayConfig=new tN(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 ri(e.organization_settings),this.userSettings=new rX(e.user_settings),this.commerceSettings=new tF(e.commerce_settings),this.apiKeysSettings=new rr(e.api_keys_settings),this.protectConfig=new rz(e.protect_config)),this}fetch({touch:e,fetchMaxTries:a}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:a})).then(e=>(rt.emit(re,null),e))}isDevelopmentOrStaging=()=>!this.isProduction();isProduction=()=>"production"===this.displayConfig.instanceEnvironmentType;isSingleSession=()=>this.authConfig.singleSessionMode;onWindowLocationHost=()=>this.displayConfig.backendHost===window.location.host;__internal_toSnapshot(){return{object:"environment",auth_config:this.authConfig.__internal_toSnapshot(),display_config:this.displayConfig.__internal_toSnapshot(),id:this.id??"",maintenance_mode:this.maintenanceMode,client_debug_mode:this.clientDebugMode,organization_settings:this.organizationSettings.__internal_toSnapshot(),user_settings:this.userSettings.__internal_toSnapshot(),commerce_settings:this.commerceSettings.__internal_toSnapshot(),api_keys_settings:this.apiKeysSettings.__internal_toSnapshot(),protect_config:this.protectConfig.__internal_toSnapshot()}}async __internal_enableEnvironmentSetting(e){await this._basePatch({path:"/dev_tools/enable_environment_setting",body:e})}}class rs extends aD{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 t0(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 ro extends aD{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 rl extends aD{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 rc extends aD{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 rc((await aD._fetch({path:e,method:"POST",body:r,headers:t}))?.response)}static async delete(e){return new rc((await aD._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 rd extends aD{id;name;organizationId;enrollmentMode;verification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:a}){return new rd((await aD._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:aN(e.verification.expires_at)}:this.verification=null),this}}class ru extends aD{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=aN(e.created_at),this.updatedAt=aN(e.updated_at),e.public_user_data&&(this.publicUserData=new r_(e.public_user_data))),this}}class rh extends aD{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=aN(e.created_at),this.updatedAt=aN(e.updated_at)),this}}class rm extends aD{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 rh(e)),this.createdAt=aN(e.created_at),this.updatedAt=aN(e.updated_at)),this}}class rp extends aD{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 rp((await aD._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new rp((await aD._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await aD._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:te(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t,has_role_set_migration:r}=e?.response;return{data:a.map(e=>new rm(e)),total_count:t,has_role_set_migration:r}});getDomains=async e=>await aD._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:te(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rd(e))}});getDomain=async({domainId:e})=>new rd((await aD._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getMembershipRequests=async e=>await aD._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:te(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new ru(e))}});createDomain=async e=>rd.create(this.id,{name:e});getMemberships=async e=>await aD._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:te({...e,paginated:!0})}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rb(e))}});getInvitations=async e=>await aD._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:te(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rg(e))}});addMember=async({userId:e,role:a})=>await aD._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:a}}).then(e=>new rb(e?.response));inviteMember=async e=>rg.create(this.id,e);inviteMembers=async e=>rg.createBulk(this.id,e);updateMember=async({userId:e,role:a})=>await aD._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:a}}).then(e=>new rb(e?.response));removeMember=async e=>await aD._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new rb(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let a,t;return null===e?await aD._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new rp(e?.response)):("string"==typeof e?(a=e,t=new Headers({"Content-Type":"application/octet-stream"})):(a=new FormData).append("file",e),await aD._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:a,headers:t}).then(e=>new rp(e?.response)))};initializePaymentMethod=e=>tw({...e,orgId:this.id});addPaymentMethod=e=>tv({...e,orgId:this.id});getPaymentMethods=e=>tj({...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=aN(e.created_at),this.updatedAt=aN(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 aD._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:a},{forceUpdateClient:!0}))?.response;return this.fromJSON(t)}}class rg extends aD{id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:a,role:t}){return new rg((await aD._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 aD._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:t,role:r}}))?.response).map(e=>new rg(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=aN(e.created_at),this.updatedAt=aN(e.updated_at)),this}}class rb extends aD{id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await aD._fetch({path:"/me/organization_memberships",method:"GET",search:te({...e,paginated:!0})}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rb(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 rp(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new r_(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=aN(e.created_at),this.updatedAt=aN(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(`${ax} Calling OrganizationMembership.reload is not currently supported. Please contact support.`)}}class rf extends aD{id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await aD._fetch({path:"/me/organization_suggestions",method:"GET",search:te(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rf(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=aN(e.created_at),this.updatedAt=aN(e.updated_at)),this}}function ry(){return c()&&"function"==typeof window.PublicKeyCredential}async function rk(){try{return ry()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function rw(){try{return"undefined"!=typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class rv extends aD{id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return aD._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new rv(e?.response))}static async attemptVerification(e,a){let t,r=(t=a.response,{...tZ(a),response:{clientDataJSON:t1(t.clientDataJSON),attestationObject:t1(t.attestationObject),transports:t.getTransports()}});return aD._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(r)}}).then(e=>new rv(e?.response))}static async registerPasskey(){let e=rv.clerk.__internal_isWebAuthnSupported||ry,a=rv.clerk.__internal_createPublicCredentials||tV,t=rv.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||rw;if(!e())throw new O("Passkeys are not supported on this device.",{code:"passkey_not_supported"});let r=await this.create(),{verification:i}=r,n=i?.publicKey;if(n||aT("create"),n.authenticatorSelection?.authenticatorAttachment==="platform"&&!await t())throw new O("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 tD((await aD._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?aN(e.last_used_at):null,this.createdAt=aN(e.created_at),this.updatedAt=aN(e.updated_at),e.verification&&(this.verification=new t9(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 rj extends aD{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 t0(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new rl(e)),this.backupCodes=e.backup_codes),this}__internal_toSnapshot(){return{object:"phone_number",id:this.id||"",phone_number:this.phoneNumber,reserved_for_second_factor:this.reservedForSecondFactor,default_second_factor:this.defaultSecondFactor,verification:this.verification.__internal_toSnapshot(),linked_to:this.linkedTo.map(e=>e.__internal_toSnapshot()),backup_codes:this.backupCodes}}}class rz extends aD{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 r_{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 rx={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"}},rq=new Set(["first_factor","second_factor","multi_factor"]),rS=new Set(["strict_mfa","strict","moderate","lax"]),rU=(e,a)=>{let{org:t,user:r}=rC(e),[i,n]=a.split(":"),s=n||i;return"org"===i?t.includes(s):"user"===i?r.includes(s):[...t,...r].includes(s)},rC=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 rA extends aD{status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new t0(null);secondFactorVerification=new t0(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new rI(e.session),this.level=e.level,this.supportedFirstFactors=er(e.supported_first_factors),this.supportedSecondFactors=er(e.supported_second_factors),this.firstFactorVerification=new t0(e.first_factor_verification),this.secondFactorVerification=new t0(e.second_factor_verification)),this}}class rI extends aD{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 rI}constructor(e){super(),this.fromJSON(e),this.#eu(this.lastActiveToken)}end=()=>(tM.clear(),this._basePost({action:"end"}));remove=()=>(tM.clear(),this._basePost({action:"remove"}));touch=()=>this._basePost({action:"touch",body:{active_organization_id:this.lastActiveOrganizationId}}).then(e=>(e.lastActiveToken&&rt.emit(t6,{token:e.lastActiveToken}),e));clearCache=()=>tM.clear();getToken=async e=>an(()=>this._getToken(e),{factor:1.55,initialDelay:3e3,maxDelayBetweenRetries:5e4,jitter:!1,shouldRetry:(e,a)=>!E(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?rU(t,e.feature):e.plan&&r?rU(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&&rS.has(e),i="object"==typeof e&&(a=e.level,rq.has(a))&&"number"==typeof(t=e.afterMinutes)&&t>0;return(!!r||!!i)&&(e=>"string"==typeof e?rx[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)};#eu=e=>{e&&tM.set({tokenId:this.#eh(),tokenResolver:Promise.resolve(e)})};#eh(e,a){let t=void 0===a?this.lastActiveOrganizationId:a;return tA.build(this.id,e,t)}startVerification=async({level:e})=>new rA((await aD._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:aA("Session.prepareFirstFactorVerification",e.strategy)}return new rA((await aD._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(tX(e.publicKeyCredential))}:{...e},new rA((await aD._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=rI.clerk.__internal_isWebAuthnSupported||ry,t=rI.clerk.__internal_getPublicCredentials||tH;if(!a())throw new O("Passkeys are not supported",{code:"passkey_not_supported"});let r=e?tY(JSON.parse(e)):null;r||aT("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 rA((await aD._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>new rA((await aD._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=aN(e.expire_at),this.abandonAt=aN(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=aN(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.createdAt=aN(e.created_at),this.updatedAt=aN(e.updated_at),this.user=new rH(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new r_(e.public_user_data)),this.lastActiveToken=e.last_active_token?new rJ(e.last_active_token):null),this}__internal_toSnapshot(){return{object:"session",id:this.id,status:this.status,expire_at:this.expireAt.getTime(),abandon_at:this.abandonAt.getTime(),factor_verification_age:this.factorVerificationAge,last_active_at:this.lastActiveAt.getTime(),last_active_organization_id:this.lastActiveOrganizationId,actor:this.actor,tasks:this.tasks,user:this.user?.__internal_toSnapshot()||null,public_user_data:this.publicUserData.__internal_toSnapshot(),last_active_token:this.lastActiveToken?.__internal_toSnapshot()||null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}async _getToken(e){if(!this.user)return null;let{leewayInSeconds: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.#eh(t,i),s=r?void 0:tM.get({tokenId:n},a),o=!t&&i===this.lastActiveOrganizationId;if(s){aa.debug("Using cached token (no fetch needed)",{tokenId:n},"session");let e=await s.tokenResolver;return o&&rt.emit(t6,{token:e}),e.getRawString()||null}aa.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=this.lastActiveToken?.getRawString(),u=rJ.create(l,c,r?{debug:"skip_cache"}:void 0).catch(e=>{if(x.is(e)&&d)return rJ.create(l,{...c},{expired_token:d});throw e});return tM.set({tokenId:n,tokenResolver:u}),u.then(e=>(o&&(rt.emit(t6,{token:e}),e.jwt&&(this.lastActiveToken=e,rt.emit(ra,null))),e.getRawString()||null))}get currentTask(){let[e]=this.tasks??[];return e}}class rP extends aD{pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,a){super(),this.pathRoot=a,this.fromJSON(e)}static retrieve(){let e=aD.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new rP(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=aN(e.expire_at),this.abandonAt=aN(e.abandon_at),this.lastActiveAt=aN(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 rO=(e,a,t)=>{let{onValidation:r=e3,onValidationComplexity:i=e3}=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 rT(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function rE(e,a,t,r,i){if(!e.client||!r.popup)return;let n=rT(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 rM(e,{redirectCallbackUrl:a,redirectUrl:t}){let r=rT(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 rR(e,a){return new Promise((t,r)=>{if(!e.client||!a.popup)return void r();let i=async a=>{a.origin===rT(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 rF(e,a){rt.emit("resource:error",{resource:e,error:null}),rt.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await a(),error:null}}catch(a){return rt.emit("resource:error",{resource:e,error:a}),{error:a}}finally{rt.emit("resource:fetch",{resource:e,status:"idle"})}}let rD=()=>{var e;return(e=new ao,{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 rN extends aD{pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;firstFactorVerification=new t0(null);secondFactorVerification=new t0(null);identifier=null;createdSessionId=null;userData=new rQ(null);clientTrustState;get status(){return this._status}set status(e){let a=this._status;this._status=e,e&&a!==e&&aa.debug("SignIn.status",{id:this.id,from:a,to:e})}__internal_future=new rW(this);__internal_basePost=this._basePost.bind(this);__internal_baseGet=this._baseGet.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=e=>{aa.debug("SignIn.create",{id:this.id,strategy:"strategy"in e?e.strategy:void 0});let a=ag();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(aa.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":case"web3_solana_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:aA("SignIn.prepareFirstFactor",e.strategy)}return this._basePost({body:{...a,strategy:e.strategy},action:"prepare_first_factor"})};attemptFirstFactor=e=>{let a;return aa.debug("SignIn.attemptFirstFactor",{id:this.id,strategy:e.strategy}),a="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(tX(e.publicKeyCredential))}:{...e},this._basePost({body:{...a,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:a}=tK();return{startEmailLinkFlow:async({emailAddressId:t,redirectUrl:r})=>{this.id||aC("SignIn");let i={strategy:"email_link",emailAddressId:t,redirectUrl:r},n="needs_second_factor"===this.status||"needs_client_trust"===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=>(aa.debug("SignIn.prepareSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_second_factor"}));attemptSecondFactor=e=>(aa.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=rN.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):aO(c,rN.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,e$);authenticateWithPopup=async e=>{let{popup:a}=e||{};return a||aP("popup"),rE(rN.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",walletName:n}=e||{},s=i.replace("web3_","").replace("_signature","");"function"!=typeof r&&aP("generateSignature"),"solana"!==s||n||aP("walletName"),await this.create({identifier:t});let o=this.supportedFirstFactors?.find(e=>e.strategy===i);o||aI("SignIn"),await this.prepareFirstFactor(o);let{message:l}=this.firstFactorVerification;l||aI("SignIn");try{a=await r({identifier:t,nonce:l,walletName:n,provider:s})}catch(e){if("coinbase_wallet"===s&&4001===e.code)a=await r({identifier:t,nonce:l,provider:s,walletName:n});else throw e}return this.attemptFirstFactor({signature:a,strategy:i})};authenticateWithMetamask=async()=>{let e=await aw().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:aw().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await aw().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:aw().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await aw().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:aw().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await aw().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:aw().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithSolana=async({walletName:e})=>{let a=await aw().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:a,generateSignature:a=>aw().generateSignatureWithSolana({...a,walletName:e}),strategy:"web3_solana_signature",walletName:e})};authenticateWithPasskey=async e=>{let{flow:a}=e||{},t=rN.clerk.__internal_isWebAuthnSupported||ry,r=rN.clerk.__internal_getPublicCredentials||tH,i=rN.clerk.__internal_isWebAuthnAutofillSupported||rk;if(!t())throw new O("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(`${ax} 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?tY(JSON.parse(n)):null;s||aT("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(rN.clerk.__internal_environment?.userSettings.passwordSettings)return rO(rD(),{...rN.clerk.__internal_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=er(e.supported_first_factors),this.supportedSecondFactors=er(e.supported_second_factors),this.firstFactorVerification=new t0(e.first_factor_verification),this.secondFactorVerification=new t0(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new rQ(e.user_data),this.clientTrustState=e.client_trust_state??void 0),rt.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:et(this.supportedFirstFactors),supported_second_factors:et(this.supportedSecondFactors),first_factor_verification:this.firstFactorVerification.__internal_toSnapshot(),second_factor_verification:this.secondFactorVerification.__internal_toSnapshot(),identifier:this.identifier,created_session_id:this.createdSessionId,user_data:this.userData.__internal_toSnapshot()}}}class rW{emailCode={sendCode:this.sendEmailCode.bind(this),verifyCode:this.verifyEmailCode.bind(this)};emailLink={sendLink:this.sendEmailLink.bind(this),waitForVerification:this.waitForEmailLinkVerification.bind(this),get verification(){if(!o())return null;let e=eO("__clerk_status"),a=eO("__clerk_created_session");if(!e||!a)return null;let t="verified"===e&&void 0!==rN.clerk.client&&rN.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)};#em=!1;#ep;constructor(e){this.#ep=e}get id(){return this.#ep.id}get identifier(){return this.#ep.identifier}get createdSessionId(){return this.#ep.createdSessionId}get userData(){return this.#ep.userData}get status(){return this.#ep.status||"needs_identifier"}get supportedFirstFactors(){return this.#ep.supportedFirstFactors??[]}get supportedSecondFactors(){return this.#ep.supportedSecondFactors??[]}get isTransferable(){return"transferable"===this.#ep.firstFactorVerification.status}get existingSession(){if("failed"===this.#ep.firstFactorVerification.status&&this.#ep.firstFactorVerification.error?.code==="identifier_already_signed_in"&&this.#ep.firstFactorVerification.error?.meta?.sessionId)return{sessionId:this.#ep.firstFactorVerification.error?.meta?.sessionId}}get firstFactorVerification(){return this.#ep.firstFactorVerification}get secondFactorVerification(){return this.#ep.secondFactorVerification}get hasBeenFinalized(){return this.#em}async sendResetPasswordEmailCode(){if(!this.#ep.id)throw Error("Cannot reset password without a sign in.");return rF(this.#ep,async()=>{let e=this.#ep.supportedFirstFactors?.find(e=>"reset_password_email_code"===e.strategy);if(!e)throw new I("Reset password email code factor not found",{code:"factor_not_found"});let{emailAddressId:a}=e;await this.#ep.__internal_basePost({body:{emailAddressId:a,strategy:"reset_password_email_code"},action:"prepare_first_factor"})})}async verifyResetPasswordEmailCode(e){let{code:a}=e;return rF(this.#ep,async()=>{await this.#ep.__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 rF(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{password:a,signOutOfOtherSessions:t},action:"reset_password"})})}async _create(e){let a=ag();await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:a?{locale:a,...e}:e})}async create(e){return rF(this.#ep,async()=>{await this._create(e)})}async password(e){if([e.identifier,e.emailAddress,e.phoneNumber].filter(Boolean).length>1)throw Error("Only one of identifier, emailAddress, or phoneNumber can be provided");return rF(this.#ep,async()=>{let a=e.identifier||e.emailAddress||e.phoneNumber,t=this.#ep.identifier,r=ag();await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:{identifier:a||t,password:e.password,...r?{locale:r}:{}}})})}async sendEmailCode(e={}){let{emailAddress:a,emailAddressId:t}=e;if(!this.#ep.id&&t)throw Error("signIn.emailCode.sendCode() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#ep.id&&!a)throw Error("signIn.emailCode.sendCode() cannot be called without an emailAddress if an existing signIn does not exist.");return rF(this.#ep,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"email_code",emailAddressId:t});if(!e)throw new I("Email code factor not found",{code:"factor_not_found"});await this.#ep.__internal_basePost({body:{emailAddressId:e.emailAddressId,strategy:"email_code"},action:"prepare_first_factor"})})}async verifyEmailCode(e){let{code:a}=e;return rF(this.#ep,async()=>{await this.#ep.__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.#ep.id&&r)throw Error("signIn.emailLink.sendLink() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#ep.id&&!a)throw Error("signIn.emailLink.sendLink() cannot be called without an emailAddress if an existing signIn does not exist.");return rF(this.#ep,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"email_link",emailAddressId:r});if(!e)throw new I("Email link factor not found",{code:"factor_not_found"});let i=t;try{new URL(t)}catch{i=window.location.origin+t}await this.#ep.__internal_basePost({body:{emailAddressId:e.emailAddressId,redirectUrl:i,strategy:"email_link"},action:"prepare_first_factor"})})}async waitForEmailLinkVerification(){return rF(this.#ep,async()=>{let{run:e,stop:a}=tK();await new Promise((t,r)=>{e(async()=>{try{let e=await this.#ep.__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.#ep.id&&t)throw Error("signIn.phoneCode.sendCode() cannot be called with an phoneNumberId if an existing signIn does not exist.");if(!this.#ep.id&&!a)throw Error("signIn.phoneCode.sendCode() cannot be called without an phoneNumber if an existing signIn does not exist.");return rF(this.#ep,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"phone_code",phoneNumberId:t});if(!e)throw new I("Phone code factor not found",{code:"factor_not_found"});await this.#ep.__internal_basePost({body:{phoneNumberId:e.phoneNumberId,strategy:"phone_code",channel:r},action:"prepare_first_factor"})})}async verifyPhoneCode(e){let{code:a}=e;return rF(this.#ep,async()=>{await this.#ep.__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 rF(this.#ep,async()=>{let e=t;try{new URL(t)}catch{e=window.location.origin+t}let l={redirectUrl:rN.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:e};if(i){let a=rM(rN.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.#ep.__internal_basePost({body:{...l,oidcPrompt:n,enterpriseConnectionId:s,strategy:"enterprise_sso"},action:"prepare_first_factor"});let{status:c,externalVerificationRedirectURL:d}=this.#ep.firstFactorVerification;"unverified"===c&&d&&(i?(await rR(rN.clerk,{popup:i,externalVerificationRedirectURL:d}),await this.#ep.reload()):e$(d))})}async web3(e){let{strategy:a}=e,t=a.replace("web3_","").replace("_signature","");return rF(this.#ep,async()=>{let r,i,n;switch(t){case"metamask":r=await aw().getMetamaskIdentifier(),i=aw().generateSignatureWithMetamask;break;case"coinbase_wallet":r=await aw().getCoinbaseWalletIdentifier(),i=aw().generateSignatureWithCoinbaseWallet;break;case"base":r=await aw().getBaseIdentifier(),i=aw().generateSignatureWithBase;break;case"okx_wallet":r=await aw().getOKXWalletIdentifier(),i=aw().generateSignatureWithOKXWallet;break;case"solana":if(!e.walletName)throw new I("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});r=await aw().getSolanaIdentifier(e.walletName),i=a=>aw().generateSignatureWithSolana({...a,walletName:e.walletName});break;default:throw Error(`Unsupported Web3 provider: ${t}`)}await this._create({identifier:r});let s=this.#ep.supportedFirstFactors?.find(e=>e.strategy===a);if(!s)throw new I("Web3 first factor not found",{code:"factor_not_found"});await this.#ep.__internal_basePost({body:{web3WalletId:s.web3WalletId,strategy:a},action:"prepare_first_factor"});let{message:o}=this.firstFactorVerification;if(!o)throw new I("Web3 nonce not found",{code:"web3_nonce_not_found"});try{n=await i({identifier:r,nonce:o,walletName:e?.walletName,provider:t})}catch(e){if("coinbase_wallet"===t&&4001===e.code)n=await i({identifier:r,nonce:o,provider:t});else throw e}await this.#ep.__internal_basePost({body:{signature:n,strategy:a},action:"attempt_first_factor"})})}async passkey(e){let{flow:a}=e||{},t=rN.clerk.__internal_isWebAuthnSupported||ry,r=rN.clerk.__internal_getPublicCredentials||tH,i=rN.clerk.__internal_isWebAuthnAutofillSupported||rk;if(!t())throw new O("Passkeys are not supported",{code:"passkey_not_supported"});return rF(this.#ep,async()=>{if("autofill"===a||"discoverable"===a)await this._create({strategy:"passkey"});else{if(!this.supportedFirstFactors.find(e=>"passkey"===e.strategy))throw new I("Passkey factor not found",{code:"factor_not_found"});await this.#ep.__internal_basePost({body:{strategy:"passkey"},action:"prepare_first_factor"})}let{nonce:e}=this.firstFactorVerification,t=e?tY(JSON.parse(e)):null;if(!t)throw new I("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 O(o.message,{code:"passkey_retrieval_failed"});await this.#ep.__internal_basePost({body:{publicKeyCredential:JSON.stringify(tX(s)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return rF(this.#ep,async()=>{let e=this.#ep.supportedSecondFactors?.find(e=>"phone_code"===e.strategy);if(!e)throw new I("Phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:a}=e;await this.#ep.__internal_basePost({body:{phoneNumberId:a,strategy:"phone_code"},action:"prepare_second_factor"})})}async verifyMFAPhoneCode(e){let{code:a}=e;return rF(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:a,strategy:"phone_code"},action:"attempt_second_factor"})})}async verifyTOTP(e){let{code:a}=e;return rF(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:a,strategy:"totp"},action:"attempt_second_factor"})})}async verifyBackupCode(e){let{code:a}=e;return rF(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:a,strategy:"backup_code"},action:"attempt_second_factor"})})}async ticket(e){let a=e?.ticket??eO("__clerk_ticket");return this.create({ticket:a??void 0})}async finalize(e){let{navigate:a}=e||{};if(!this.#ep.createdSessionId)throw Error("Cannot finalize sign-in without a created session.");return rF(this.#ep,async()=>{rN.clerk.client&&!rN.clerk.client.sessions.some(e=>e.id===this.#ep.createdSessionId)&&await rN.clerk.client.reload(),this.#em=!0,await rN.clerk.setActive({session:this.#ep.createdSessionId,navigate:a})})}selectFirstFactor({strategy:e,emailAddressId:a,phoneNumberId:t}){if(!this.#ep.supportedFirstFactors)return null;if(a){let t=this.#ep.supportedFirstFactors.find(t=>t.strategy===e&&t.emailAddressId===a);if(t)return t}if(t){let a=this.#ep.supportedFirstFactors.find(a=>a.strategy===e&&a.phoneNumberId===t);if(a)return a}let r=this.#ep.supportedFirstFactors.find(a=>a.strategy===e&&a.safeIdentifier===this.#ep.identifier);if(r)return r;let i=this.#ep.supportedFirstFactors.find(a=>a.strategy===e);return i||null}}function rL(e){let{unsafeMetadata:a}={...e},t=a?"object"==typeof a?JSON.stringify(a):a:"";return{...e,...a?{unsafeMetadata:t}:{}}}class r$ extends aD{pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new t3(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&&aa.debug("SignUp.status",{id:this.id,from:a,to:e})}__internal_future=new rK(this);__internal_basePost=this._basePost.bind(this);__internal_basePatch=this._basePatch.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{aa.debug("SignUp.create",{id:this.id,strategy:e.strategy});let a={...e};if(!a.locale){let e=ag();e&&(a.locale=e)}if(a.transfer&&this.shouldBypassCaptchaForAttempt(a)){let e=r$.clerk.client?.signIn.firstFactorVerification.strategy;e&&(a={...a,strategy:e})}return this._basePost({path:this.pathRoot,body:rL(a)})};prepareVerification=e=>(aa.debug("SignUp.prepareVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_verification"}));attemptVerification=e=>(aa.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}=tK();return{startEmailLinkFlow:async({redirectUrl:t})=>(this.id||aC("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,walletName:o}=e||{},l=n.replace("web3_","").replace("_signature","");"function"!=typeof t&&aP("generateSignature");let c=r||this.web3wallet;await this.create({web3Wallet:c,unsafeMetadata:i,legalAccepted:s}),await this.prepareWeb3WalletVerification({strategy:n});let{message:d}=this.verifications.web3Wallet;d||aI("SignUp");try{a=await t({identifier:r,nonce:d,provider:l,walletName:o})}catch(e){if("coinbase_wallet"===l&&4001===e.code)a=await t({identifier:r,nonce:d,provider:l});else throw e}return this.attemptWeb3WalletVerification({signature:a,strategy:n})};authenticateWithMetamask=async e=>{let a=await aw().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:aw().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let a=await aw().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:aw().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let a=await aw().getBaseIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:aw().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let a=await aw().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:aw().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithSolana=async({walletName:e,unsafeMetadata:a,legalAccepted:t})=>{let r=await aw().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:r,generateSignature:a=>aw().generateSignatureWithSolana({...a,walletName:e}),unsafeMetadata:a,strategy:"web3_solana_signature",legalAccepted:t,walletName:e})};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=r$.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(_(e)&&T(e))return await r$.clerk.__internal_environment.reload(),h();throw e}),{externalAccount:p}=m,{status:g,externalVerificationRedirectURL:b}=p;"unverified"===g&&b?a(b):aO(g,r$.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,e$);authenticateWithPopup=async e=>{let{popup:a}=e||{};return a||aP("popup"),rE(r$.clerk,"signUp",this.authenticateWithRedirectOrPopup,e,e=>{a.location.href=e instanceof URL?e.toString():e})};update=e=>this._basePatch({body:rL(e)});upsert=e=>this.id?this.update(e):this.create(e);validatePassword=(e,a)=>{if(r$.clerk.__internal_environment?.userSettings.passwordSettings)return rO(rD(),{...r$.clerk.__internal_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 t3(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),rt.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 r$.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){if(!e.strategy)return!1;let a=r$.clerk.__internal_environment.displayConfig.captchaOauthBypass;return!!(a.some(a=>a===e.strategy)||e.transfer&&a.some(e=>e===r$.clerk.client.signIn.firstFactorVerification.strategy))}__experimental_getEnterpriseConnections=()=>aD._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new rB(e)))}class rK{verifications={sendEmailCode:this.sendEmailCode.bind(this),verifyEmailCode:this.verifyEmailCode.bind(this),sendPhoneCode:this.sendPhoneCode.bind(this),verifyPhoneCode:this.verifyPhoneCode.bind(this)};#em=!1;#ep;constructor(e){this.#ep=e}get id(){return this.#ep.id}get requiredFields(){return this.#ep.requiredFields}get optionalFields(){return this.#ep.optionalFields}get missingFields(){return this.#ep.missingFields}get status(){return this.#ep.status||"missing_requirements"}get username(){return this.#ep.username}get firstName(){return this.#ep.firstName}get lastName(){return this.#ep.lastName}get emailAddress(){return this.#ep.emailAddress}get phoneNumber(){return this.#ep.phoneNumber}get web3Wallet(){return this.#ep.web3wallet}get hasPassword(){return this.#ep.hasPassword}get unsafeMetadata(){return this.#ep.unsafeMetadata}get createdSessionId(){return this.#ep.createdSessionId}get createdUserId(){return this.#ep.createdUserId}get abandonAt(){return this.#ep.abandonAt}get legalAcceptedAt(){return this.#ep.legalAcceptedAt}get locale(){return this.#ep.locale}get unverifiedFields(){return this.#ep.unverifiedFields}get isTransferable(){return"transferable"===this.#ep.verifications.externalAccount.status&&this.#ep.verifications.externalAccount.error?.code==="external_account_exists"}get existingSession(){if(("failed"===this.#ep.verifications.externalAccount.status||"unverified"===this.#ep.verifications.externalAccount.status)&&this.#ep.verifications.externalAccount.error?.code==="identifier_already_signed_in"&&this.#ep.verifications.externalAccount.error?.meta?.sessionId)return{sessionId:this.#ep.verifications.externalAccount.error?.meta?.sessionId}}get hasBeenFinalized(){return this.#em}async getCaptchaToken(){let e=new aR(r$.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?rL(e.unsafeMetadata):void 0,locale:e.locale??ag()};await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:i})}async create(e){return rF(this.#ep,async()=>{await this._create(e)})}async update(e){return rF(this.#ep,async()=>{let a={...e,unsafeMetadata:e.unsafeMetadata?rL(e.unsafeMetadata):void 0};await this.#ep.__internal_basePatch({path:this.#ep.pathRoot,body:a})})}async password(e){return rF(this.#ep,async()=>{let{captchaToken:a,captchaWidgetType:t,captchaError:r}=await this.getCaptchaToken(),i={strategy:"password",captchaToken:a,captchaWidgetType:t,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rL(e.unsafeMetadata):void 0};await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:i})})}async sendEmailCode(){return rF(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification"})})}async verifyEmailCode(e){let{code:a}=e;return rF(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{strategy:"email_code",code:a},action:"attempt_verification"})})}async sendPhoneCode(e){let{phoneNumber:a,channel:t="sms"}=e;return rF(this.#ep,async()=>{if(!this.#ep.id){let{captchaToken:e,captchaWidgetType:t,captchaError:r}=await this.getCaptchaToken();await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:{phoneNumber:a,captchaToken:e,captchaWidgetType:t,captchaError:r}})}await this.#ep.__internal_basePost({body:{strategy:"phone_code",channel:t},action:"prepare_verification"})})}async verifyPhoneCode(e){let{code:a}=e;return rF(this.#ep,async()=>{await this.#ep.__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 rF(this.#ep,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:r$.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:h};if(c){let e=rM(r$.clerk,{redirectCallbackUrl:m.redirectUrl,redirectUrl:h});m.redirectUrl=e.redirectCallbackUrl,m.actionCompleteRedirectUrl=e.redirectUrl}let p=()=>this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:{strategy:a,...m,unsafeMetadata:i,legalAccepted:n,oidcPrompt:s,enterpriseConnectionId:o,emailAddress:l,captchaToken:e,captchaWidgetType:d,captchaError:u}});await p().catch(async e=>{if(_(e)&&T(e))return await r$.clerk.__internal_environment.reload(),p();throw e});let{status:g,externalVerificationRedirectURL:b}=this.#ep.verifications.externalAccount;"unverified"===g&&b&&(c?(await rR(r$.clerk,{popup:c,externalVerificationRedirectURL:b}),await this.#ep.reload()):e$(b))})}async web3(e){let{strategy:a,unsafeMetadata:t,legalAccepted:r}=e,i=a.replace("web3_","").replace("_signature","");return rF(this.#ep,async()=>{let e,n,s;switch(i){case"metamask":e=await aw().getMetamaskIdentifier(),n=aw().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await aw().getCoinbaseWalletIdentifier(),n=aw().generateSignatureWithCoinbaseWallet;break;case"base":e=await aw().getBaseIdentifier(),n=aw().generateSignatureWithBase;break;case"okx_wallet":e=await aw().getOKXWalletIdentifier(),n=aw().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${i}`)}let o=e||this.#ep.web3wallet;await this._create({web3Wallet:o,unsafeMetadata:t,legalAccepted:r}),await this.#ep.__internal_basePost({body:{strategy:a},action:"prepare_verification"});let{message:l}=this.#ep.verifications.web3Wallet;l||aI("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.#ep.__internal_basePost({body:{signature:s,strategy:a},action:"attempt_verification"})})}async ticket(e){let a=e?.ticket??eO("__clerk_ticket");return this.create({...e,ticket:a??void 0})}async finalize(e){let{navigate:a}=e||{};return rF(this.#ep,async()=>{if(!this.#ep.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#em=!0,await r$.clerk.setActive({session:this.#ep.createdSessionId,navigate:a})})}}class rB extends aD{id;name;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name),this}}class rJ extends aD{pathRoot="tokens";jwt;static async create(e,a={},t={}){return new rJ(await aD._fetch({method:"POST",path:e,body:a,search:t}),e)}constructor(e,a){super(),a&&(this.pathRoot=a),e?.jwt&&(this.jwt=ap(e.jwt))}getRawString=()=>this.jwt?.claims.__raw||"";fromJSON(e){return e&&(this.jwt=ap(e.jwt)),this}__internal_toSnapshot(){return{object:"token",id:this.id||"",jwt:this.getRawString()}}}class rV extends aD{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=aN(e.updated_at),this.createdAt=aN(e.created_at)),this}}class rG extends aD{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=aN(e.updated_at),this.createdAt=aN(e.created_at)),this}}class rH extends aD{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 rH}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case tB:return this.primaryEmailAddressId===e.id;case rj:return this.primaryPhoneNumberId===e.id;case r1:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:a}=e||{};return new tB({email_address:a},this.path()+"/email_addresses/").create()};createPasskey=()=>rv.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:a}=e||{};return new rj({phone_number:a},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:a}=e||{};return new r1({web3_wallet:a},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:a,redirectUrl:t,additionalScopes:r}=e||{};return new rs((await aD._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:a,redirect_url:t,additional_scope:r}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new rV((await aD._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new rV((await aD._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new tD((await aD._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new rG((await aD._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);update=e=>this._basePatch({body:rL(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=>(rt.emit(t7,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await rP.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:a}=e||{};return null===a?rc.delete(`${this.path()}/profile_image`):rc.create(`${this.path()}/profile_image`,{file:a})};getOrganizationInvitations=e=>rY.retrieve(e);getOrganizationSuggestions=e=>rf.retrieve(e);getOrganizationMemberships=e=>rb.retrieve(e);leaveOrganization=async e=>new tD((await aD._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);initializePaymentMethod=e=>tw(e);addPaymentMethod=e=>tv(e);getPaymentMethods=e=>tj(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 tB(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 rj(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 r1(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 rs(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new rv(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new rb(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new t5(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=aN(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=aN(e.legal_accepted_at)),this.updatedAt=aN(e.updated_at||void 0),this.createdAt=aN(e.created_at||void 0)),this}__internal_toSnapshot(){return{object:"user",id:this.id,external_id:this.externalId,first_name:this.firstName,last_name:this.lastName,username:this.username,public_metadata:this.publicMetadata,unsafe_metadata:this.unsafeMetadata,image_url:this.imageUrl,has_image:this.hasImage,email_addresses:this.emailAddresses.map(e=>e.__internal_toSnapshot()),phone_numbers:this.phoneNumbers.map(e=>e.__internal_toSnapshot()),web3_wallets:this.web3Wallets.map(e=>e.__internal_toSnapshot()),external_accounts:this.externalAccounts.map(e=>e.__internal_toSnapshot()),passkeys:this.passkeys.map(e=>e.__internal_toSnapshot()),organization_memberships:this.organizationMemberships.map(e=>e.__internal_toSnapshot()),enterprise_accounts:this.enterpriseAccounts.map(e=>e.__internal_toSnapshot()),totp_enabled:this.totpEnabled,backup_code_enabled:this.backupCodeEnabled,two_factor_enabled:this.twoFactorEnabled,create_organization_enabled:this.createOrganizationEnabled,create_organizations_limit:this.createOrganizationsLimit,delete_self_enabled:this.deleteSelfEnabled,primary_email_address_id:this.primaryEmailAddressId,primary_phone_number_id:this.primaryPhoneNumberId,primary_web3_wallet_id:this.primaryWeb3WalletId,password_enabled:this.passwordEnabled,profile_image_id:this.imageUrl,last_sign_in_at:this.lastSignInAt?.getTime()||null,legal_accepted_at:this.legalAcceptedAt?.getTime()||null,updated_at:this.updatedAt?.getTime()||null,created_at:this.createdAt?.getTime()||null}}}class rQ{firstName;lastName;imageUrl;hasImage;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.firstName=e.first_name,this.lastName=e.last_name,this.imageUrl=e.image_url??void 0,this.hasImage=e.has_image??void 0),this}__internal_toSnapshot(){return{first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl||null,has_image:this.hasImage||null}}}class rY extends aD{id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await aD._fetch({path:"/me/organization_invitations",method:"GET",search:te(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rY(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=aN(e.created_at),this.updatedAt=aN(e.updated_at)),this}}let rZ={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 rX extends aD{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:{...rZ,name:"phone_number"},username:{...rZ,name:"username"},web3_wallet:{...rZ,name:"web3_wallet"},first_name:{...rZ,name:"first_name"},last_name:{...rZ,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:{...rZ,name:"authenticator_app"},backup_code:{...rZ,name:"backup_code"},passkey:{...rZ,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}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 r1 extends aD{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 t0(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}class r2 extends aD{pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=aN(e.updated_at),this.createdAt=aN(e.created_at),rt.emit("resource:update",{resource:this})),this}async join(e){return rF(this,async()=>{await r2.join(e)})}static async join(e){return new r2(await aD._fetch({path:"/waitlist",method:"POST",body:e}))}}function r0(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 r9(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(tR.isClientResource(e))return e.id!==a.id||e.updatedAt.getTime()<a.updatedAt.getTime()||e.sessions.length!==a.sessions.length;if(rI.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&&r0(t.user,r.user))}if(rH.isUserResource(e))return r0(e,a)}catch{}return!0}(e,a)?e:a}let r3="__clerk_db_jwt";function r8(e,a){let t=new URL(e),r=t.searchParams.get(r3);t.searchParams.delete(r3);let i=r||a;return i&&t.searchParams.set(r3,i),t}let r5=e=>{let a=new URL(e);return a.searchParams.delete(r3),a},r4=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 r6(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 r7=function e(a,t){function r(e,r,i){if("undefined"!=typeof document){"number"==typeof(i=r6({},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,"",r6({},a,{expires:-1}))},withAttributes:function(a){return e(this.converter,r6({},this.attributes,a))},withConverter:function(a){return e(r6({},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 ie(e){return{get:()=>r7.get(e),set(a,t={}){r7.set(e,a,t)},remove(a){r7.remove(e,a)}}}let ia=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function it(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 ir=ie("__clerk_test_etld"),ii="__client_uat",is="__session",io=()=>{let e=af()?"None":"Lax",a=ia(e);return{sameSite:e,secure:a,partitioned:!1}};async function il(e){let a;try{a=await ep(e)}catch(o){var t;t=`Suffixed cookie failed due to ${o.message} (secure-context: ${window.isSecureContext}, url: ${window.location.href})`,H.has(t)||(console.log(t),H.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 ic=()=>{let e=af()?"None":"Lax",a=ia(e);return{sameSite:e,secure:a}};var id=i(945),iu=i.n(id);class ih{lock=(k="clerk.lock.refreshSessionToken",s=new(iu()),window.addEventListener("beforeunload",async()=>{await s.releaseLock(k)}),{acquireLockAndRun:async e=>{if("locks"in navigator&&isSecureContext){let a=new AbortController,t=setTimeout(()=>a.abort(),4999);return await navigator.locks.request(k,{signal:a.signal},async()=>(clearTimeout(t),await e())).catch(()=>!1)}if(await s.acquireLock(k,5e3))try{return await e()}finally{await s.releaseLock(k)}}});workerTimers=t$();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 im{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,a,t,r){let i=await il(e.publishableKey),n=new im(e,a,i,t,r);return await n.setup(),n}constructor(e,a,r,i,n){let s,o,l,c,d,u,h;this.clerk=e,this.instanceType=i,this.clerkEventBus=n,rt.on(t6,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),rt.on(t7,()=>this.handleSignOut()),this.refreshTokenOnFocus(),this.startPollingForToken(),this.clientUat=(s=ie(ii),o=ie(eg(ii,r)),{set:e=>{let a=it(Date.now(),1),r=af()?"None":"Strict",i=ia(r),n=function(e=window.location.hostname,a=ir){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()),o.remove(),s.remove(),o.set(l,{domain:n,expires:a,partitioned:!1,sameSite:r,secure:i}),s.set(l,{domain:n,expires:a,partitioned:!1,sameSite:r,secure:i})},get:()=>parseInt(o.get()||s.get()||"0",10)}),this.sessionCookie=(l=ie(is),c=ie(eg(is,r)),{set:e=>{let a=it(Date.now(),1),{sameSite:t,secure:r,partitioned:i}=io();i&&d(),l.set(e,{expires:a,sameSite:t,secure:r,partitioned:i}),c.set(e,{expires:a,sameSite:t,secure:r,partitioned:i})},remove:d=()=>{let e=io();l.remove(e),c.remove(e)},get:()=>c.get()||l.get()}),this.activeCookie=(u=ie("clerk_active_context"),h={secure:ia("None")},{set:e=>{u.set(e,h)},get:()=>u.get(),remove:()=>u.remove(h)}),this.devBrowser=function({cookieSuffix:e,frontendApi:a,fapiClient:t}){let r,i,n=(r=ie(r3),i=ie(eg(r3,e)),{get:()=>i.get()||r.get(),set:e=>{let a=it(Date.now(),1),{sameSite:t,secure:n}=ic();i.set(e,{expires:a,sameSite:t,secure:n}),r.set(e,{expires:a,sameSite:t,secure:n})},remove:()=>{let e=ic();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(!ew(a))return;t.onBeforeRequest(e=>{let a=s();a&&e?.url&&(e.url=r8(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(r3)||"",r5(r4(e)).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",r5(r4(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 v(e)):[]}((await c.json()).errors);e[0]?aS(e[0].longMessage):aS()}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(`${ax} Missing dev browser jwt. Please contact support.`);return r8(e,a)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new ih,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||u()||aa.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(_(e)||P(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(E(e))return void this.clerk.handleUnauthenticated().catch(e3);this.clerkEventBus.emit(b,"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 ip{clerk;captchaChallenge;timers;constructor(e,a=new aR(e),t=t$()){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.__internal_environment?.displayConfig?.captchaHeartbeat}clientBypass(){return this.clerk.client?.captchaBypass}intervalInMs(){return this.clerk.__internal_environment?.displayConfig?.captchaHeartbeatIntervalMs??6e5}}let ig=["/client","/waitlist"];class ib{async getBaseFapiProxyOptions(){let e=await aD.clerk.session?.getToken();if(!e)throw new I("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 aD._fetch({...await this.getBaseFapiProxyOptions(),method:"GET",path:"/api_keys",search:te({...e,subject:e?.subject??aD.clerk.organization?.id??aD.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new aW(e))}})}async create(e){return new aW(await aD._fetch({...await this.getBaseFapiProxyOptions(),path:"/api_keys",method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??aD.clerk.organization?.id??aD.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new aW(await aD._fetch({...await this.getBaseFapiProxyOptions(),method:"POST",path:`/api_keys/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let iy=new Map;class ik{#es=!1;load(e){let a=e?.protectConfig;if(a?.loaders&&Array.isArray(a.loaders)&&0!==a.loaders.length&&!this.#es){if(o())for(let e of(this.#es=!0,a.loaders))try{this.applyLoader(e)}catch(e){Q(`[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 Q(`[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:Q(`[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 Q(`[protect] loader target element not found: ${t}`);e.appendChild(r);return}Q(`[protect] loader target is invalid: ${t}`)}}}class iw{signInResourceSignal=tt;signInErrorSignal=tr;signInFetchSignal=ti;signInSignal=tn;signUpResourceSignal=ts;signUpErrorSignal=to;signUpFetchSignal=tl;signUpSignal=tc;waitlistResourceSignal=td;waitlistErrorSignal=tu;waitlistFetchSignal=th;waitlistSignal=tm;_waitlistInstance;__internal_effect=a9;__internal_computed=a0;constructor(){rt.on("resource:update",this.onResourceUpdated),rt.on("resource:error",this.onResourceError),rt.on("resource:fetch",this.onResourceFetch),this._waitlistInstance=new r2(null),this.waitlistResourceSignal({resource:this._waitlistInstance})}get __internal_waitlist(){return this._waitlistInstance}onResourceError=e=>{e.resource instanceof rN&&this.signInErrorSignal({error:e.error}),e.resource instanceof r$&&this.signUpErrorSignal({error:e.error}),e.resource instanceof r2&&this.waitlistErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof rN){if(iv(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof r$){if(iv(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}e.resource instanceof r2&&(this._waitlistInstance=e.resource,this.waitlistResourceSignal({resource:e.resource}))};onResourceFetch=e=>{e.resource instanceof rN&&this.signInFetchSignal({status:e.status}),e.resource instanceof r$&&this.signUpFetchSignal({status:e.status}),e.resource instanceof r2&&this.waitlistFetchSignal({status:e.status})}}function iv(e,a){return!a?.id&&e&&e.__internal_future?.hasBeenFinalized===!1}let ij="cannot_render_billing_disabled",iz="cannot_render_user_missing",i_="cannot_render_organizations_disabled",ix="cannot_render_organization_missing",iq="cannot_render_single_session_enabled",iS={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 iU{static version="6.0.0-canary.v20260109133726";static sdkMetadata={name:"@clerk/clerk-js",version:"6.0.0-canary.v20260109133726"};static _billing;static _apiKeys;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new iw;internal_last_error=null;environment;#eg;#eb="";#ef;#ey;#ek;#ew;#ev;#ej=null;#ez;#e_;#ex;#eq="loading";#eS=[];#eU=[];#eC={};#eA=null;#eI=0;#eP=g();get __internal_queryClient(){return this.#eg||Promise.resolve().then(i.bind(i,303)).then(e=>e.QueryClient).then(e=>{this.#eg||(this.#eg=new e,this.#eP.emit("queryClientStatus","ready"))}),this.#eg?{__tag:"clerk-rq-client",client:this.#eg}:void 0}__internal_getCachedResources;__internal_createPublicCredentials;__internal_getPublicCredentials;__internal_isWebAuthnSupported;__internal_isWebAuthnAutofillSupported;__internal_isWebAuthnPlatformAuthenticatorSupported;__internal_setActiveInProgress=!1;get publishableKey(){return this.#eb}get version(){return iU.version}set sdkMetadata(e){iU.sdkMetadata=e}get sdkMetadata(){return iU.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#eq}get isSatellite(){return!!ab()&&e9(this.#eC.isSatellite,new URL(window.location.href),!1)}get domain(){if(ab()){let e=function(e=""){return(e||"").replace(/^.+:\/\//,"")}(e9(this.#ef,new URL(window.location.href)));if("production"===this.#ex){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(ab()){let e=e9(this.#ey,new URL(window.location.href));return!e||eK(e)||eB(e)||ah.throwInvalidProxyUrl({url:e}),e?eB(e)?new URL(e,window.location.origin).toString():e:""}return""}get frontendApi(){let e=eh(this.publishableKey);return e?e.frontendApi:ah.throwInvalidPublishableKeyError({key:this.publishableKey})}get instanceType(){return this.#ex}get isStandardBrowser(){return this.#eC.standardBrowser||!1}get billing(){return iU._billing||(iU._billing=new ta),iU._billing}get apiKeys(){return iU._apiKeys||(iU._apiKeys=new ib),iU._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=iy.get(c);if(d)return d.signals.computedSignal();let u=(t=a2({resource:null}),r=a2({error:null}),i=a2({status:"idle"}),n=a0(()=>{let e=t().resource,a=r().error,n=i().status;return{errors:tp(a,{}),fetchStatus:n,checkout:e}}),{resourceSignal:t,errorSignal:r,fetchSignal:i,computedSignal:n}),h=new tf(u,{..."organization"===s?{orgId:e.organization?.id}:{},planId:o,planPeriod:l});return iy.set(c,{resource:h,signals:u}),u.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#eC[e]}get isSignedIn(){return this?.session?.status!=="pending"&&!!this.session}constructor(e,a){if(!(e=(e||"").trim()))return ah.throwMissingPublishableKeyError();let t=eh(e);if(!t)return ah.throwInvalidPublishableKeyError({key:e});this.#ef=a?.domain,this.#ey=a?.proxyUrl,this.environment=rn.getInstance(),this.#ex=t.instanceType,this.#eb=e,this.#e_=function(e){let a=[],t=[];async function r(e){for await(let t of["undefined"!=typeof window&&window.__internal_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.__internal_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.v20260109133726"),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&&!ig.some(e=>t.startsWith(e))&&r&&s.append("_clerk_session_id",r),ef([...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)),ez({base:i.origin,pathname:`${s}/${r}${t}`,search:n(a)},{stringify:!1})}let i="production"===e.instanceType?e.domain:"";return ez({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:c}=o;!c||"object"!=typeof c||c instanceof FormData||(o.body=function(e){if(!e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype)return e;let a={};for(let[t,r]of Object.entries(e))void 0!==r&&(a[t]=r);return a}(c)),o.url=s({...o,sessionId:e.getSessionId()}),o.headers=new Headers(o.headers),"GET"===l||c instanceof FormData||o.headers.has("content-type")||o.headers.set("content-type","application/x-www-form-urlencoded"),"application/x-www-form-urlencoded"===o.headers.get("content-type")&&(o.body=c?ef(c,{keyEncoder:ee}):c);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??(d()?4:11);n=await an(()=>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();aa.error("network error",{error:a,url:e,method:l},"fapiClient");throw Error(`${ax} 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||aa.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.#eP.emit(b,"loading"),this.#eP.prioritizedOn(b,e=>this.#eq=e),aD.clerk=this,this.#ew=new ik}getFapiClient=()=>this.#e_;load=async e=>{if(aa.info("load() start",{},"clerk"),!this.loaded){if("development"!==this.#ex||e?.unsafe_disableDevelopmentModeConsoleWarning||Q("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.#eC=this.#eO(e),this.#eC.clerkUiCtor&&(this.#ez=Promise.resolve(this.#eC.clerkUiCtor).then(e=>new e(()=>this,()=>this.environment,this.#eC,new ao))),"development"===this.#ex&&(this.#eC.routerPush||this.#eC.routerReplace)&&(!this.#eC.routerPush||!this.#eC.routerReplace)){let e=this.#eC.routerPush?"routerReplace":"routerPush";Q(`Clerk: Both \`routerPush\` and \`routerReplace\` need to be defined, but \`${e}\` is not defined. This may cause issues with navigation in your application.`)}rt.on(ra,()=>{this.#eT(this.session),this.#eE()}),this.#eC.sdkMetadata&&(iU.sdkMetadata=this.#eC.sdkMetadata),!1!==this.#eC.telemetry&&(this.telemetry=new eQ({clerkVersion:iU.version,samplingRate:1,perEventSampling:!this.#eC.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#eC.telemetry}),this.#eC.appearance&&this.telemetry.record({event:"THEME_USAGE",eventSamplingRate:1,payload:function(e){let a;if(!e||"object"!=typeof e)return{};let t=e.theme;if(!t)return{};if(Array.isArray(t))for(let e of t){let t=e0(e);if(t){a=t;break}}else a=e0(t);return{themeName:a}}(this.#eC.appearance)}));try{this.#eC.standardBrowser?await this.#eM():await this.#eR();let e=this.#eC.telemetry,a=!1!==e&&!e?.disabled,t=!!this.#eC.__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(e4)return;let{enabled:a=!1,...t}=e;a&&(e8=!0,e4=!0,ae(t))}({enabled:!0,...s?{logLevel:s}:{},...a&&this.telemetry?{telemetryCollector:this.telemetry}:{}}),this.#ew?.load(this.environment),aa.info("load() complete",{},"clerk")}catch(e){throw this.#eP.emit(b,"error"),aa.error("load() failed",{error:e},"clerk"),e}}};#eF(){let e;return!!(!this.#eC.signUpUrl&&this.#eC.signInUrl&&(e=this.#eC.signInUrl,!eb.test(e)))}signOut=async(e,a)=>{if(!this.client||0===this.client.sessions.length)return;let t="undefined"!=typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:e3,r="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e3,i=e&&"object"==typeof e?e:a||{},n=i?.redirectUrl||this.buildAfterSignOutUrl();aa.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=al(this.#eC.standardBrowser);rt.emit(t7,null),this.#eD(),await e.track(async()=>{s?await s():await this.navigate(n)}),e.isUnloading()||(this.#eT(),this.#eE(),await r())};if(await t(),!i.sessionId||1===this.client.signedInSessions.length){this.#eC.experimental?.persistClient??!0?await this.client.removeSessions():await this.client.destroy(),await o(),aa.info("signOut() complete",{redirectUrl:e_(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(),aa.info("signOut() complete",{redirectUrl:e_(n)},"clerk"))};openGoogleOneTap=e=>{this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("googleOneTap",e||{})),this.telemetry?.record(e2("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(W(this,this.environment)){if("development"===this.#ex)throw new I(eN.cannotOpenSignInOrSignUp,{code:iq});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("signIn",e||{}));let a={withSignUp:e?.withSignUp??this.#eF()};this.telemetry?.record(e2("SignIn",e,a))};closeSignIn=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(L(this,this.environment)){if("development"===this.#ex)throw new I(eN.cannotRenderAnyBillingComponent("Checkout"),{code:ij});return}if(!this.user){if("development"===this.#ex)throw new I(eN.cannotOpenCheckout,{code:iz});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openDrawer("checkout",e||{}))};__internal_closeCheckout=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("checkout"))};__internal_openPlanDetails=e=>{if(L(this,this.environment)){if("development"===this.#ex)throw new I(eN.cannotRenderAnyBillingComponent("PlanDetails"),{code:ij});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openDrawer("planDetails",e||{})),this.telemetry?.record(e2("PlanDetails",e))};__internal_closePlanDetails=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("planDetails"))};__internal_openSubscriptionDetails=e=>{this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openDrawer("subscriptionDetails",e||{}))};__internal_closeSubscriptionDetails=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("subscriptionDetails"))};__internal_openReverification=e=>{if(!this.user){if("development"===this.#ex)throw new I(eN.cannotOpenUserProfile,{code:iz});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("userVerification",e||{})),this.telemetry?.record(e2("UserVerification",e))};__internal_closeReverification=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userVerification"))};__internal_attemptToEnableEnvironmentSetting=e=>{let{for:a,caller:t}=e;if(this.user||"development"!==this.#ex||Q(`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.#ex&&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.#ez),this.#ez.then(e=>e.ensureMounted({preloadHint:"EnableOrganizationsPrompt"})).then(a=>a.openModal("enableOrganizationsPrompt",e||{})),this.telemetry?.record(e1("EnableOrganizationsPrompt",e))};__internal_closeEnableOrganizationsPrompt=()=>{this.assertComponentsReady(this.#ez),this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("enableOrganizationsPrompt"))};__internal_openBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(e=>e.openModal("blankCaptcha",{})));__internal_closeBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(e=>e.closeModal("blankCaptcha")));__internal_loadStripeJs=async()=>(aq("Stripe"),{loadStripe:()=>Promise.resolve(null)});openSignUp=e=>{if(W(this,this.environment)){if("development"===this.#ex)throw new I(eN.cannotOpenSignInOrSignUp,{code:iq});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("signUp",e||{})),this.telemetry?.record(e2("SignUp",e))};closeSignUp=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signUp"))};openUserProfile=e=>{if(!this.user){if("development"===this.#ex)throw new I(eN.cannotOpenUserProfile,{code:iz});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("userProfile",e||{}));let a=(e?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(e2("UserProfile",e,a))};closeUserProfile=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userProfile"))};openOrganizationProfile=e=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new I(eN.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:i_})}});if(a){if(!this.organization){if("development"===this.#ex)throw new I(eN.cannotRenderComponentWhenOrgDoesNotExist,{code:ix});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("organizationProfile",e||{})),this.telemetry?.record(e2("OrganizationProfile",e))}};closeOrganizationProfile=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("organizationProfile"))};openCreateOrganization=e=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new I(eN.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:i_})}});a&&(this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("createOrganization",e||{})),this.telemetry?.record(e2("CreateOrganization",e)))};closeCreateOrganization=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("createOrganization"))};openWaitlist=e=>{this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("waitlist",e||{})),this.telemetry?.record(e2("Waitlist",e))};closeWaitlist=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("waitlist"))};mountSignIn=(e,a)=>{this.assertComponentsReady(this.#ez);let t="SignIn";this.#ez.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"signIn",node:e,props:a}));let r={withSignUp:a?.withSignUp??this.#eF()};this.telemetry?.record(e1(t,a,r))};unmountSignIn=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserAvatar=(e,a)=>{this.assertComponentsReady(this.#ez);let t="UserAvatar";this.#ez.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"userAvatar",node:e,props:a})),this.telemetry?.record(e1(t,a))};unmountUserAvatar=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountSignUp=(e,a)=>{this.assertComponentsReady(this.#ez);let t="SignUp";this.#ez.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"signUp",node:e,props:a})),this.telemetry?.record(e1(t,a))};unmountSignUp=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserProfile=(e,a)=>{if(!this.user){if("development"===this.#ex)throw new I(eN.cannotRenderComponentWhenUserDoesNotExist,{code:iz});return}this.assertComponentsReady(this.#ez);let t="UserProfile";this.#ez.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(e1(t,a,r))};unmountUserProfile=e=>{this.#ez?.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 I(eN.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:i_})}});if(!t)return;let r=!!this.user;if(!this.organization&&r){if("development"===this.#ex)throw new I(eN.cannotRenderComponentWhenOrgDoesNotExist,{code:ix});return}this.assertComponentsReady(this.#ez);let i="OrganizationProfile";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:i,appearanceKey:"userProfile",node:e,props:a})),this.telemetry?.record(e1(i,a))};unmountOrganizationProfile=e=>{this.#ez?.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 I(eN.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:i_})}});if(!t)return;this.assertComponentsReady(this.#ez);let r="CreateOrganization";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"createOrganization",node:e,props:a})),this.telemetry?.record(e1(r,a))};unmountCreateOrganization=e=>{this.#ez?.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 I(eN.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:i_})}});if(!t)return;this.assertComponentsReady(this.#ez);let r="OrganizationSwitcher";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"organizationSwitcher",node:e,props:a})),this.telemetry?.record(e1(r,{...a,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationSwitcher=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};__experimental_prefetchOrganizationSwitcher=()=>{this.assertComponentsReady(this.#ez),this.#ez.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 I(eN.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:i_})}});if(!t)return;this.assertComponentsReady(this.#ez);let r="OrganizationList";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"organizationList",node:e,props:a})),this.telemetry?.record(e1(r,{...a,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationList=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserButton=(e,a)=>{this.assertComponentsReady(this.#ez);let t="UserButton";this.#ez.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(e1(t,a,r))};unmountUserButton=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountWaitlist=(e,a)=>{this.assertComponentsReady(this.#ez);let t="Waitlist";this.#ez.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"waitlist",node:e,props:a})),this.telemetry?.record(e1(t,a))};unmountWaitlist=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountPricingTable=(e,a)=>{if(L(this,this.environment)){if("development"===this.#ex)throw new I(eN.cannotRenderAnyBillingComponent("PricingTable"),{code:ij});return}this.assertComponentsReady(this.#ez);let t="PricingTable";this.#ez.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"pricingTable",node:e,props:a})),this.telemetry?.record(e1(t,a))};unmountPricingTable=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};__internal_mountOAuthConsent=(e,a)=>{this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:"OAuthConsent",appearanceKey:"__internal_oauthConsent",node:e,props:a}))};__internal_unmountOAuthConsent=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountAPIKeys=(e,a)=>{let t;if(Q("Clerk: <APIKeys /> component is in early access and not yet recommended for production use."),$(this,t=this.environment)&&K(this,t)){if("development"===this.#ex)throw new I(eN.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&K(this,this.environment)){if("development"===this.#ex)throw new I(eN.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if($(this,this.environment)){if("development"===this.#ex)throw new I(eN.cannotRenderAPIKeysComponentForUserWhenDisabled,{code:"cannot_render_api_keys_user_disabled"});return}this.assertComponentsReady(this.#ez);let r="APIKeys";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"apiKeys",node:e,props:a})),this.telemetry?.record(e1(r,a))};unmountAPIKeys=e=>{this.#ez?.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 I(eN.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:i_})}});if(!t)return;this.assertComponentsReady(this.#ez);let r="TaskChooseOrganization";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"taskChooseOrganization",node:e,props:a})),this.telemetry?.record(e1(r,a))};unmountTaskChooseOrganization=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountTaskResetPassword=(e,a)=>{this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:"TaskResetPassword",appearanceKey:"taskResetPassword",node:e,props:a})),this.telemetry?.record(e1("TaskResetPassword",a))};unmountTaskResetPassword=e=>{this.#ez?.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,aa.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 aa.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 aa.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.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:e3,l="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e3,c=void 0===i?this.session:i;c?.status==="pending"&&(n={...this.#eC,...e},s=["taskUrls","navigate"],Object.keys(n).some(e=>s.includes(e))||Q('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 d=void 0!==a;if(c&&d){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),(ab()&&globalThis.document.hasFocus()||!this.#eC.standardBrowser)&&(await this.#eN(c),c=this.#eW(c?.id)),await c?.getToken()||(u()||aa.warn("Token is null when setting active session (offline)",{sessionId:c?.id},"clerk"),rt.emit(t6,{token:null}));let h=al(this.#eC.standardBrowser),m=c?.status==="pending"&&c?.currentTask&&this.#eC.taskUrls?.[c?.currentTask.key];if((t||m||r)&&await h.track(async()=>{if(this.client){if(c?.status!=="pending"&&this.#eD(),m){let e=t?ez({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.#eT(c),this.#eE(),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:r9((r=t).client,e.client),session:r9(r.session,e.session),user:r9(r.user,e.user),organization:r9(r.organization,e.organization)}})},this.#eS.push(e),this.client&&e({client:this.client,session:this.session,user:this.user,organization:this.organization}),()=>{this.#eS=this.#eS.filter(a=>a!==e)}};on=(...e)=>{this.#eP.on(...e)};off=(...e)=>{this.#eP.off(...e)};__internal_addNavigationListener=e=>(this.#eU.push(e),()=>{this.#eU=this.#eU.filter(a=>a!==e)});navigate=async(e,a)=>{if(!e||!ab())return;setTimeout(()=>{this.#eL()},0);let t=new URL(e,window.location.href);this.#e$.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.#eC.routerReplace?this.#eC.routerReplace:this.#eC.routerPush;if(aa.info(`Clerk is navigating to: ${t}`),this.#eC.routerDebug&&console.log(`Clerk is navigating to: ${t}`),"null"!==t.origin&&t.origin!==window.location.origin||!r)return void e$(t);let i={...a?.metadata?{__internal_metadata:a?.metadata}:{},windowNavigate:e$};return await r(e_(t),i)};buildUrlWithAuth(e){if("production"===this.#ex)return e;let a=new URL(e,window.location.origin);return a.origin!==window.location.origin&&this.#ek?this.#ek.decorateUrlWithDevBrowserToken(a).href:a.href}buildSignInUrl(e){return this.#eK("signInUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildSignUpUrl(e){return this.#eK("signUpUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildUserProfileUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.userProfileUrl):""}buildHomeUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.homeUrl):""}buildAfterSignInUrl({params:e}={}){return this.buildUrlWithAuth(new eA(this.#eC,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eA(this.#eC,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#eC.afterSignOutUrl?this.buildUrlWithAuth(this.#eC.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#eC.newSubscriptionRedirectUrl?this.#eC.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?ez({base:this.#eC.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#eC.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#eC.afterMultiSessionSingleSignOutUrl):this.#eC.signInUrl?this.buildUrlWithAuth(ez({base:this.#eC.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.#eC.taskUrls?.[a.key];return t||ez({base:this.buildSignInUrl(e),hashPath:eR(a)},{stringify:!0})}#eB=async()=>{if(!ab())return;let e=new URLSearchParams({[B]:"true"}),a=eO(V);a&&eK(a)||function(){throw Error(`${ax} Invalid redirect_url. A valid http or https url should be used for the redirection.`)}();let t=ez({base:eO(V),searchParams:e},{stringify:!0});return this.navigate(this.buildUrlWithAuth(t))};redirectWithAuth=async e=>{if(ab())return this.navigate(this.buildUrlWithAuth(e))};redirectToSignIn=async e=>{if(ab())return this.navigate(this.buildSignInUrl(e))};redirectToSignUp=async e=>{if(ab())return this.navigate(this.buildSignUpUrl(e))};redirectToUserProfile=async()=>{if(ab())return this.navigate(this.buildUserProfileUrl())};redirectToCreateOrganization=async()=>{if(ab())return this.navigate(this.buildCreateOrganizationUrl())};redirectToOrganizationProfile=async()=>{if(ab())return this.navigate(this.buildOrganizationProfileUrl())};redirectToAfterSignIn=async()=>{if(ab())return this.navigate(this.buildAfterSignInUrl())};redirectToAfterSignUp=async()=>{if(ab())return this.navigate(this.buildAfterSignUpUrl())};redirectToAfterSignOut=async()=>{if(ab())return this.navigate(this.buildAfterSignOutUrl())};redirectToWaitlist=async()=>{if(ab())return this.navigate(this.buildWaitlistUrl())};redirectToTasks=async e=>{if(ab())return this.navigate(this.buildTasksUrl(e))};handleEmailLinkVerification=async(e,a)=>{if(!this.client)return;let t=eO("__clerk_status");if("expired"===t)throw new U(A.Expired);if("client_mismatch"===t)throw new U(A.ClientMismatch);if("verified"!==t)throw new U(A.Failed);let r=eO("__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):e3;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||ez({base:i.signInUrl,hashPath:"/factor-one"},{stringify:!0})),m=c(e.secondFactorUrl||ez({base:i.signInUrl,hashPath:"/factor-two"},{stringify:!0})),p=c(e.resetPasswordUrl||ez({base:i.signInUrl,hashPath:"/reset-password"},{stringify:!0})),g=new eA(this.#eC,e),b=c(e.continueSignUpUrl||ez({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=eE();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||ez({base:i.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),verifyPhonePath:e.verifyPhoneNumberUrl||ez({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 eF(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:aU("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:aU("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 tR.getOrCreateInstance().fetch();if(this.updateClient(a),this.session)return;return e.broadcast&&rt.emit(t7,null),this.setActive({session:null})}catch(e){if(_(e)&&[403,500].includes(e.status))return this.setActive({session:null});throw e}};authenticateWithGoogleOneTap=async e=>(aq("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"})};authenticateWithSolana=async e=>{await this.authenticateWithWeb3({...e,strategy:"web3_solana_signature"})};authenticateWithWeb3=async({redirectUrl:e,signUpContinueUrl:a,customNavigate:t,unsafeMetadata:r,strategy:i,legalAccepted:n,secondFactorUrl:s,walletName:o})=>{let l,c;if(!this.client||!this.environment)return;let{displayConfig:d}=this.environment,u=i.replace("web3_","").replace("_signature",""),h=await aw().getWeb3Identifier({provider:u,walletName:o});switch(u){case"metamask":l=aw().generateSignatureWithMetamask;break;case"base":l=aw().generateSignatureWithBase;break;case"coinbase_wallet":l=aw().generateSignatureWithCoinbaseWallet;break;case"solana":if(!o)throw new I("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});l=e=>aw().generateSignatureWithSolana({...e,walletName:o});break;default:l=aw().generateSignatureWithOKXWallet}let m=e=>()=>t&&"function"==typeof t?t(e):this.navigate(e),p=m(s||ez({base:d.signInUrl,hashPath:"/factor-two"},{stringify:!0})),g=m(a||ez({base:d.signUpUrl,hashPath:"/continue"},{stringify:!0}));try{c=await this.client.signIn.authenticateWithWeb3({identifier:h,generateSignature:l,strategy:i,walletName:o})}catch(e){if(au(e,"form_identifier_not_found"))c=await this.client.signUp.authenticateWithWeb3({identifier:h,generateSignature:l,unsafeMetadata:r,strategy:i,legalAccepted:n,walletName:o}),a&&"missing_requirements"===c.status&&"verified"===c.verifications.web3Wallet.status&&await g();else throw e}let b=async({session:e,redirectUrl:a})=>{e.currentTask?await eF(e,{baseUrl:d.signInUrl,navigate:this.navigate}):await this.navigate(a)};switch(c.status){case"needs_second_factor":await p();break;case"complete":c.createdSessionId&&await this.setActive({session:c.createdSessionId,navigate:async({session:a})=>{await b({session:a,redirectUrl:e??this.buildAfterSignInUrl()})}});break;default:return}};createOrganization=async({name:e,slug:a})=>rp.create({name:e,slug:a});getOrganization=async e=>rp.get(e);joinWaitlist=async({emailAddress:e})=>r2.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.#eC.selectInitialSession?this.#eC.selectInitialSession(e):this.#eJ(e);this.#eT(a)}if(this.client=e,this.session){let e=this.#eW(this.session.id);"active"===this.session.status&&e?.status==="pending"&&("undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e3)(),this.#eT(e),this.session?.lastActiveToken||u()||aa.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),rt.emit(t6,{token:this.session?.lastActiveToken})}this.#eE()};get __internal_environment(){return this.environment}__internal_setEnvironment=async e=>{this.environment=new rn(e)};__internal_onBeforeRequest=e=>{this.#e_.onBeforeRequest(e)};__internal_onAfterResponse=e=>{this.#e_.onAfterResponse(e)};__internal_updateProps=e=>{let a={...e,options:this.#eO({...this.#eC,...e.options})};return this.#ez?.then(e=>e.ensureMounted()).then(e=>e.updateProps(a))};__internal_navigateWithError(e,a){return this.__internal_last_error=a,this.navigate(e)}#eV=()=>{let e=new URLSearchParams({[V]:window.location.href});return ez({base:this.#eC.signInUrl,searchParams:e},{stringify:!0})};#eG=()=>{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()||""};#eH=()=>"true"!==eO(B)&&!!this.isSatellite&&!!this.#ek?.isSignedOut();#eQ=()=>"production"!==this.#ex&&!this.isSatellite&&!!eO(V);#eY=async()=>{"development"===this.instanceType?await this.navigate(this.#eV()):"production"===this.instanceType&&await this.navigate(this.#eG())};#eZ=(e,a)=>{let t;try{t=new URL(e)}catch{throw Error(`${ax} The signInUrl needs to have a absolute url format.`)}t.origin===a&&function(){throw Error(`${ax} The signInUrl needs to be on a different origin than your satellite application.`)}()};#eX=()=>{this.isSatellite&&("development"!==this.#ex||this.#eC.signInUrl||function(){throw Error(`${ax} Missing signInUrl. A satellite application needs to specify the signInUrl for development instances.`)}(),this.proxyUrl||this.domain||function(){throw Error(`${ax} Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl.`)}(),this.#eC.signInUrl&&this.#eZ(this.#eC.signInUrl,window.location.origin))};#eM=async()=>{if(this.#ek=await im.create(this,this.#e_,this.#ex,this.#eP),this.#eX(),this.#eH())return void await this.#eY();if(this.#eQ())return void await this.#eB();this.#eA=(()=>{if(!o())return{onPageFocus:e3};let e=[];return window.addEventListener("focus",()=>{"visible"===document.visibilityState&&e.forEach(e=>e())}),{onPageFocus:a=>{e.push(a)}}})(),"undefined"!=typeof BroadcastChannel&&(this.#ej=new BroadcastChannel("clerk")),this.#e1();let e=function(e=window.location.hostname){if(!e)return!1;let a=ev.get(e);void 0===a&&(a=es.some(a=>e.startsWith("accounts.")&&e.endsWith(a))||eo.some(a=>e.endsWith(a)&&!e.endsWith(".clerk"+a)),ev.set(e,a));return a}(window?.location.hostname),a="development"===this.#ex&&!e,t=0,r=0;for(;r<2;){r++;try{var i;let e=rn.getInstance().fetch({touch:a}).then(e=>this.updateEnvironment(e)).catch(()=>{++t;let e=a_.getItem(av,null);e&&this.updateEnvironment(new rn(e))}),r=async()=>tR.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(async e=>{if(E(e))throw e;++t;let a=this.#ek?.getSessionCookie(),r=function(e){let a;try{a=new rJ({jwt:e||"",object:"token",id:void 0})}catch{a=null}if(tR.clearInstance(),!a?.jwt)return tR.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}=rC(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 tR.getOrCreateInstance(c)}(a);return this.updateClient(r),this.#ek?.stopPollingForToken(),await this.session?.getToken({skipCache:!0}).catch(()=>null).finally(()=>{this.#ek?.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(au(e,"requires_captcha"))await r();else throw e}if(this.#ek?.setClientUatCookieForDevelopmentInstances(),await this.#e2())return;break}catch(e){if(au(e,"dev_browser_unauthenticated"))await this.#ek.handleUnauthenticatedDevBrowser();else if(!u())return void console.warn(e);else throw e}r>=2&&function(){throw Error(`${ax} Something went wrong initializing Clerk.`)}()}this.#ev=new ip(this),this.#ev.start(),this.#e0(),this.#e9(),this.#e3(),this.#eP.emit(b,t>0?"degraded":"ready")};shouldFallbackToCachedResources=()=>!!this.__internal_getCachedResources;#eR=async()=>{let e,a,t=this.shouldFallbackToCachedResources()?1:void 0,r=0;try{[e,a]=await Promise.all([rn.getInstance().fetch({touch:!1,fetchMaxTries:t}),tR.getOrCreateInstance().fetch({fetchMaxTries:t})])}catch(t){if(P(t)&&"network_error"===t.code&&this.shouldFallbackToCachedResources()){let t=await this.__internal_getCachedResources?.();e=new rn(t?.environment),tR.clearInstance(),a=tR.getOrCreateInstance(t?.client),++r}else throw t}this.updateClient(a),this.updateEnvironment(e),this.#eP.emit(b,r>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,a]=await Promise.all([rn.getInstance().fetch({touch:!1,fetchMaxTries:1}),tR.getOrCreateInstance().fetch({fetchMaxTries:1})]);this.updateClient(a),this.updateEnvironment(e),this.#eE()};#eJ=e=>{if(e.lastActiveSessionId){let a=e.signedInSessions.find(a=>a.id===e.lastActiveSessionId);if(a)return a}return e.signedInSessions[0]||null};#e1=()=>{o()&&(this.#eA?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#eI>Date.now())&&(this.#eI=Date.now()+5e3,this.#eC.touchSession&&this.#eN(this.session))}),this.#ej?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),rt.on(t7,()=>{this.#ej?.postMessage({type:"signout"})}),rt.on(re,()=>{a_.setItem(av,this.environment?.__internal_toSnapshot(),864e5)}))};#eN=async e=>{if(!e)return Promise.resolve();await e.touch().catch(e=>{E(e)&&this.handleUnauthenticated()})};#eE=()=>{if(this.client)for(let e of this.#eS)e({client:this.client,session:this.session,user:this.user,organization:this.organization})};#eL=()=>{for(let e of this.#eU)e()};#eD=()=>{this.session=void 0,this.organization=void 0,this.user=void 0,this.#eE()};#e8=()=>(this.session?.user.organizationMemberships||[]).map(e=>e.organization).find(e=>e.id===this.session?.lastActiveOrganizationId)||null;#eT=e=>{this.session=e||null,this.organization=this.#e8(),this.user=this.session?this.session.user:null};#eW=e=>this.client?.signedInSessions.find(a=>a.id===e)||null;#e9=()=>{this.addListener(({session:e})=>{e?.actor&&this.#ez?.then(e=>e.ensureMounted()).then(e=>e.mountImpersonationFab())})};#e3=()=>{this.#eC.__internal_keyless_claimKeylessApplicationUrl&&this.#ez?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#eC.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#eC.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#eC.__internal_keyless_dismissPrompt}})})};#eK=(e,a,t)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let r=this.#eC[e]||this.environment.displayConfig[e];this.#eF()&&(r=this.#eC.signInUrl);let i=new eA(this.#eC,a).toSearchParams(),n=new URLSearchParams(t||{}),s=ez({base:r,hashPath:this.#eF()&&"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")}#e2=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,ey)).pathname,r=eU.includes(t)||eC.includes(t),e===a.host&&r);if(s||!o)return!1;let l=this.session,c=this.#eC.signInUrl||this.environment?.displayConfig.signInUrl,d=c&&window.location.href.startsWith(c),u=this.#eC.signUpUrl||this.environment?.displayConfig.signUpUrl,h=u&&window.location.href.startsWith(u);return i=new URL(n,ey),(!eU.includes(i.pathname)||!!l||!d&&!h)&&(await this.navigate(this.buildUrlWithAuth(n)),!0)};#eO=e=>({...iS,...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://${ej(a)}`),r.push(`https://*.${ej(a)}`),"development"===t&&r.push(`https://${a}`),r}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)});#e0=()=>{try{eT(B),eT(eI),eT(J),eT("__clerk_handshake"),eT("__clerk_handshake_nonce"),eT("__clerk_help")}catch{}};get #e$(){let e=eL;return this.#eC.allowedRedirectProtocols&&(e=e.concat(this.#eC.allowedRedirectProtocols)),e}}})();var s=n.c2,o=n.LR,l=n.cR,c=n.NZ,d=n.Ys,u=n.kl,h=n.$R,m=n.Cm,p=n.hl,g=n.ux,b=n.si,f=n._d;export{s as Clerk,o as ClerkAPIResponseError,l as ClerkRuntimeError,c as EmailLinkError,d as EmailLinkErrorCode,u as EmailLinkErrorCodeStatus,h as isClerkAPIResponseError,m as isClerkRuntimeError,p as isEmailLinkError,g as isKnownError,b as isMetamaskError,f as isUserLockedError};
|
|
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 z(a||s,r)}return null}static _updateClient(e){if(!e)return;let a=e.client||e.meta?.client;a&&aD.clerk&&aD.clerk.updateClient(tR.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 aD._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 aD._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 aD._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=aD.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}function aN(e){let a=new Date(e||new Date);return a instanceof Date&&!isNaN(a.getTime())?a:new Date}class aW extends aD{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?aN(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?aN(e.last_used_at):null,this.updatedAt=aN(e.updated_at),this.createdAt=aN(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 aL extends aD{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?aN(e.claimed_at):null,this.claimedAt),this.reverification=this.withDefault(e.reverification,this.reverification),this.singleSessionMode=this.withDefault(e.single_session_mode,this.singleSessionMode),this.preferredChannels=this.withDefault(e.preferred_channels,this.preferredChannels)),this}__internal_toSnapshot(){return{claimed_at:this.claimedAt?this.claimedAt.getTime():null,id:this.id??"",object:"auth_config",reverification:this.reverification,single_session_mode:this.singleSessionMode}}}(y=w||(w={}))[y.None=0]="None",y[y.Mutable=1]="Mutable",y[y.Watching=2]="Watching",y[y.RecursedCheck=4]="RecursedCheck",y[y.Recursed=8]="Recursed",y[y.Dirty=16]="Dirty",y[y.Pending=32]="Pending";let a$=[],{link:aK,unlink:aB,propagate:aJ,checkDirty:aV,endTracking:aG,startTracking:aH,shallowPropagate:aQ}=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?a3(e):a8(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):a$[aX++]=a}},unwatched(e){if("getter"in e){let a=e.deps;if(void 0!==a){e.flags=17;do a=aB(a,e);while(void 0!==a)}}else"previousValue"in e||a7.call(e)}}),aY=0,aZ=0,aX=0;function a1(a){let t=e;return e=a,t}function a2(e){return a6.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function a0(e){return a4.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function a9(t){let r={fn:t,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==e?aK(r,e):void 0!==a&&aK(r,a);let i=a1(r);try{r.fn()}finally{a1(i)}return a7.bind(r)}function a3(e){let a=a1(e);aH(e);try{let a=e.value;return a!==(e.value=e.getter(a))}finally{a1(a),aG(e)}}function a8(e,a){return e.flags=1,e.previousValue!==(e.previousValue=a)}function a5(){for(;aZ<aX;){let e=a$[aZ];a$[aZ++]=void 0,function e(a,t){if(16&t||32&t&&aV(a.deps,a)){let e=a1(a);aH(a);try{a.fn()}finally{a1(e),aG(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)}aZ=0,aX=0}function a4(){let t=this.flags;if(16&t||32&t&&aV(this.deps,this)){if(a3(this)){let e=this.subs;void 0!==e&&aQ(e)}}else 32&t&&(this.flags=-33&t);return void 0!==e?aK(this,e):void 0!==a&&aK(this,a),this.value}function a6(...a){if(a.length){let e=a[0];if(this.value!==(this.value=e)){this.flags=17;let e=this.subs;void 0!==e&&(aJ(e),aY||a5())}}else{let a=this.value;if(16&this.flags&&a8(this,a)){let e=this.subs;void 0!==e&&aQ(e)}return void 0!==e&&aK(this,e),a}}function a7(){let e=this.deps;for(;void 0!==e;)e=aB(e,this);let a=this.subs;void 0!==a&&aB(a),this.flags=0}function te(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 ta{static #ed="/billing";static path(e,a){let{orgId:t}=a||{},r=t?`/organizations/${t}`:"/me";return`${r}${ta.#ed}${e}`}getPlans=async e=>{let{for:a,...t}=e||{},r={...t,payer_type:"organization"===a?"org":"user"};return await aD._fetch({path:`${ta.#ed}/plans`,method:"GET",search:te(r)}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new tx(e))}})};getPlan=async e=>new tx(await aD._fetch({path:`${ta.#ed}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await aD._fetch({path:ta.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new tU(e?.response));getStatements=async e=>{let{orgId:a,...t}=e;return await aD._fetch({path:ta.path("/statements",{orgId:a}),method:"GET",search:te(t)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new tq(e))}})};getStatement=async e=>new tq((await aD._fetch({path:ta.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:a,...t}=e;return await aD._fetch({path:ta.path("/payment_attempts",{orgId:a}),method:"GET",search:te(t)}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new ty(e))}})};getPaymentAttempt=async e=>new ty(await aD._fetch({path:ta.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:a,...t}=e;return new tb((await aD._fetch({path:ta.path("/checkouts",{orgId:a}),method:"POST",body:t}))?.response)}}let tt=a2({resource:null}),tr=a2({error:null}),ti=a2({status:"idle"}),tn=a0(()=>{let e=tt().resource,a=tr().error,t=ti().status;return{errors:tp(a,{identifier:null,password:null,code:null}),fetchStatus:t,signIn:e?e.__internal_future:null}}),ts=a2({resource:null}),to=a2({error:null}),tl=a2({status:"idle"}),tc=a0(()=>{let e=ts().resource,a=to().error,t=tl().status;return{errors:tp(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}}),td=a2({resource:null}),tu=a2({error:null}),th=a2({status:"idle"}),tm=a0(()=>{let e=td().resource,a=tu().error,t=th().status;return{errors:tp(a,{emailAddress:null}),fetchStatus:t,waitlist:e}});function tp(e,a){let t={fields:{...a},raw:null,global:null};if(!e)return t;if(!_(e))return t.raw=[e],t.global=[N(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=X(e.meta.paramName);a in t.fields&&(t.fields[a]=e)}}):(t.raw=[e],t.global=[N(e)]),t}class tg extends aD{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=aN(e.created_at)),e.updated_at&&(this.updatedAt=aN(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 tb extends aD{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 tz(e.payment_method):void 0,this.plan=new tx(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=ad(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change,e.free_trial_ends_at&&(this.freeTrialEndsAt=aN(e.free_trial_ends_at)),this.payer=new tg(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>an(()=>this._basePatch({path:ta.path(`/checkouts/${this.id}/confirm`,{orgId:this.payer.organizationId}),body:e}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,a){if(!_(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 tf{resource=new tb(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 tb.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new tb(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 tb.clerk.setActive({session:tb.clerk.session?.id,navigate:a})})}runAsyncCheckoutTask(e,a,t){var r,i,n;return void 0===tb.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()=>{++aY,i.errorSignal({error:null}),i.fetchSignal({status:"fetching"}),t?.(),--aY||a5(),++aY;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"}),--aY||a5()}})();return n.set(e,s),s})(e,a,t)}}class ty extends aD{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=ac(e.amount),this.paidAt=e.paid_at?aN(e.paid_at):null,this.failedAt=e.failed_at?aN(e.failed_at):null,this.updatedAt=aN(e.updated_at),this.paymentMethod=e.payment_method?new tz(e.payment_method):null,this.subscriptionItem=new tC(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status),this}}let tk="/payment_methods",tw=async e=>{let{orgId:a,...t}=e;return new t_((await aD._fetch({path:ta.path(`${tk}/initialize`,{orgId:a}),method:"POST",body:t}))?.response)},tv=async e=>{let{orgId:a,...t}=e;return new tz((await aD._fetch({path:ta.path(tk,{orgId:a}),method:"POST",body:t}))?.response)},tj=async e=>{let{orgId:a,...t}=e??{};return await aD._fetch({path:ta.path(tk,{orgId:a}),method:"GET",search:te(t)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new tz(e))}})};class tz extends aD{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:aN(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:aN(e.updated_at)),this}async remove(e){let{orgId:a}=e??{};return new tD((await aD._fetch({path:ta.path(`/payment_methods/${this.id}`,{orgId:a}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:a}=e??{};return await aD._fetch({path:ta.path("/payers/default_payment_method",{orgId:a}),method:"PUT",body:{payment_method_id:this.id}}),null}}class t_ extends aD{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 tx extends aD{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=ac(e.fee),this.annualFee=e.annual_fee?ac(e.annual_fee):null,this.annualMonthlyFee=e.annual_monthly_fee?ac(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 ro(e))),this}}class tq extends aD{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=aN(e.timestamp),this.totals=ad(e.totals),this.groups=e.groups.map(e=>new tS(e))),this}}class tS{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=aN(e.timestamp),this.items=e.items.map(e=>new ty(e))),this}}class tU extends aD{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=aN(e.created_at),this.updatedAt=e.updated_at?aN(e.updated_at):null,this.activeAt=aN(e.active_at),this.pastDueAt=e.past_due_at?aN(e.past_due_at):null,e.next_payment&&(this.nextPayment={amount:ac(e.next_payment.amount),date:aN(e.next_payment.date)}),this.subscriptionItems=(e.subscription_items||[]).map(e=>new tC(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1)),this}}class tC extends aD{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 tx(e.plan),this.planPeriod=e.plan_period,this.status=e.status,this.createdAt=aN(e.created_at),this.pastDueAt=e.past_due_at?aN(e.past_due_at):null,this.periodStart=aN(e.period_start),this.periodEnd=e.period_end?aN(e.period_end):null,this.canceledAt=e.canceled_at?aN(e.canceled_at):null,this.amount=e.amount?ac(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:ac(e.credit.amount)}:void 0,this.isFreeTrial=this.withDefault(e.is_free_trial,!1)),this}async cancel(e){let{orgId:a}=e;return new tD((await aD._fetch({path:ta.path(`/subscription_items/${this.id}`,{orgId:a}),method:"DELETE"}))?.response)}}let tA={build:(e,a,t)=>[e,a,t].filter(Boolean).join("-"),parse:(e,a,t)=>{let r=tA.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}},tI="clerk",tP=10,tO={broadcast:!0},tT={broadcast:!1};class tE{prefix;data;static fromKey(e){let[a,t,r=""]=e.split("::");return new tE(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 tM=((e=tI)=>{let a=new Map,t=Math.random().toString(36).slice(2),r=null,i=()=>r||("undefined"==typeof BroadcastChannel?null:((r=new BroadcastChannel("clerk:session_token")).addEventListener("message",e=>{s(e)}),r));i();let n=(t,r=tP)=>{i();let n=new tE(e,t),s=a.get(n.toKey());if(!s)return;let o=Math.floor(Date.now()/1e3)-s.createdAt;if(s.expiresIn-o<(r||1)+5){void 0!==s.timeoutId&&clearTimeout(s.timeoutId),a.delete(n.toKey());return}return s.entry},s=async({data:e})=>{let a,r=tA.build(e.sessionId,e.template,e.organizationId);if(e.tokenId!==r)return void aa.warn("Ignoring token broadcast with mismatched tokenId",{expectedTokenId:r,organizationId:e.organizationId,receivedTokenId:e.tokenId,tabId:t,template:e.template,traceId:e.traceId},"tokenCache");try{a=new rJ({id:e.tokenId,jwt:e.tokenRaw,object:"token"})}catch(a){aa.warn("Failed to parse token from broadcast, skipping cache update",{error:a,tabId:t,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");return}let i=a.jwt?.claims?.iat,s=a.jwt?.claims?.exp;if(!i||!s)return void aa.warn("Token missing iat/exp claim, skipping cache update",{tabId:t,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");try{let a=n({tokenId:e.tokenId});if(a){let r=await a.tokenResolver,n=r.jwt?.claims?.iat;if(n&&n>=i)return void aa.debug("Ignoring older token broadcast",{existingIat:n,incomingIat:i,tabId:t,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}}catch(a){aa.warn("Existing entry compare failed; proceeding with broadcast update",{error:a,tabId:t,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}aa.info("Updating token cache from broadcast",{iat:i,organizationId:e.organizationId,tabId:t,template:e.template,tokenId:e.tokenId,traceId:e.traceId},"tokenCache"),o({createdAt:i,tokenId:e.tokenId,tokenResolver:Promise.resolve(a)},tT)},o=(i,n=tO)=>{let s=new tE(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=tA.extractTemplate(i.tokenId,e,n),o=tA.build(e,s,n);if(i.tokenId===o){let a=`bc_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;aa.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)};return{clear:()=>{a.forEach(e=>{void 0!==e.timeoutId&&clearTimeout(e.timeoutId)}),a.clear()},close:()=>{r&&(r.close(),r=null)},get:n,set:e=>{i(),o(e,tO)},size:()=>a.size}})();class tR extends aD{static instance;pathRoot="/client";sessions=[];signUp=new r$;signIn=new rN;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return tR.instance||(tR.instance=new tR(e)),tR.instance}static clearInstance(){tR.instance=null}static isClientResource(e){return!!e&&e instanceof tR}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(()=>{tM.clear(),this.id="",this.sessions=[],this.signUp=new r$(null),this.signIn=new rN(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=>(tM.clear(),e))}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return aD.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 rI(e)),this.signUp=new r$(e.sign_up),this.signIn=new rN(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?aN(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=aN(e.created_at||void 0),this.updatedAt=aN(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 tF extends aD{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 tD{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 tN extends aD{afterCreateOrganizationUrl="";afterJoinWaitlistUrl="";afterLeaveOrganizationUrl="";afterSignInUrl="";afterSignOutAllUrl="";afterSignOutOneUrl="";afterSignOutUrl="";afterSignUpUrl="";afterSwitchSessionUrl="";applicationName="";backendHost="";branded=!1;captchaHeartbeat=!1;captchaHeartbeatIntervalMs;captchaOauthBypass=["oauth_google","oauth_microsoft","oauth_apple"];captchaProvider="turnstile";captchaPublicKey=null;captchaPublicKeyInvisible=null;captchaWidgetType=null;clerkJSVersion;createOrganizationUrl="";faviconImageUrl="";googleOneTapClientId;homeUrl="";id="";instanceEnvironmentType="";logoImageUrl="";organizationProfileUrl="";preferredSignInStrategy="password";privacyPolicyUrl="";showDevModeWarning=!1;signInUrl="";signUpUrl="";supportEmail="";termsUrl="";theme={};userProfileUrl="";waitlistUrl="";constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.afterCreateOrganizationUrl=this.withDefault(e.after_create_organization_url,this.afterCreateOrganizationUrl),this.afterJoinWaitlistUrl=this.withDefault(e.after_join_waitlist_url,this.afterJoinWaitlistUrl),this.afterLeaveOrganizationUrl=this.withDefault(e.after_leave_organization_url,this.afterLeaveOrganizationUrl),this.afterSignInUrl=this.withDefault(e.after_sign_in_url,this.afterSignInUrl),this.afterSignOutAllUrl=this.withDefault(e.after_sign_out_all_url,this.afterSignOutAllUrl),this.afterSignOutOneUrl=this.withDefault(e.after_sign_out_one_url,this.afterSignOutOneUrl),this.afterSignUpUrl=this.withDefault(e.after_sign_up_url,this.afterSignUpUrl),this.afterSwitchSessionUrl=this.withDefault(e.after_switch_session_url,this.afterSwitchSessionUrl),this.applicationName=this.withDefault(e.application_name,this.applicationName),this.branded=this.withDefault(e.branded,this.branded),this.captchaHeartbeat=this.withDefault(e.captcha_heartbeat,this.captchaHeartbeat),this.captchaHeartbeatIntervalMs=this.withDefault(e.captcha_heartbeat_interval_ms,this.captchaHeartbeatIntervalMs),this.captchaOauthBypass=this.withDefault(e.captcha_oauth_bypass,this.captchaOauthBypass),this.captchaProvider=this.withDefault(e.captcha_provider,this.captchaProvider),this.captchaPublicKey=this.withDefault(e.captcha_public_key,this.captchaPublicKey),this.captchaPublicKeyInvisible=this.withDefault(e.captcha_public_key_invisible,this.captchaPublicKeyInvisible),this.captchaWidgetType=this.withDefault(e.captcha_widget_type,this.captchaWidgetType),this.clerkJSVersion=this.withDefault(e.clerk_js_version,this.clerkJSVersion),this.createOrganizationUrl=this.withDefault(e.create_organization_url,this.createOrganizationUrl),this.faviconImageUrl=this.withDefault(e.favicon_image_url,this.faviconImageUrl),this.googleOneTapClientId=this.withDefault(e.google_one_tap_client_id,this.googleOneTapClientId),this.homeUrl=this.withDefault(e.home_url,this.homeUrl),this.id=this.withDefault(e.id,this.id),this.instanceEnvironmentType=this.withDefault(e.instance_environment_type,this.instanceEnvironmentType),this.logoImageUrl=this.withDefault(e.logo_image_url,this.logoImageUrl),this.organizationProfileUrl=this.withDefault(e.organization_profile_url,this.organizationProfileUrl),this.preferredSignInStrategy=this.withDefault(e.preferred_sign_in_strategy,this.preferredSignInStrategy),this.privacyPolicyUrl=this.withDefault(e.privacy_policy_url,this.privacyPolicyUrl),this.showDevModeWarning=this.withDefault(e.show_devmode_warning,this.showDevModeWarning),this.signInUrl=this.withDefault(e.sign_in_url,this.signInUrl),this.signUpUrl=this.withDefault(e.sign_up_url,this.signUpUrl),this.supportEmail=this.withDefault(e.support_email,this.supportEmail),this.termsUrl=this.withDefault(e.terms_url,this.termsUrl),this.theme=this.withDefault(e.theme,this.theme),this.userProfileUrl=this.withDefault(e.user_profile_url,this.userProfileUrl),this.waitlistUrl=this.withDefault(e.waitlist_url,this.waitlistUrl)),this}__internal_toSnapshot(){return{object:"display_config",after_create_organization_url:this.afterCreateOrganizationUrl,after_join_waitlist_url:this.afterJoinWaitlistUrl,after_leave_organization_url:this.afterLeaveOrganizationUrl,after_sign_in_url:this.afterSignInUrl,after_sign_out_all_url:this.afterSignOutAllUrl,after_sign_out_one_url:this.afterSignOutOneUrl,after_sign_up_url:this.afterSignUpUrl,after_switch_session_url:this.afterSwitchSessionUrl,application_name:this.applicationName,branded:this.branded,captcha_heartbeat_interval_ms:this.captchaHeartbeatIntervalMs,captcha_heartbeat:this.captchaHeartbeat,captcha_oauth_bypass:this.captchaOauthBypass,captcha_provider:this.captchaProvider,captcha_public_key_invisible:this.captchaPublicKeyInvisible,captcha_public_key:this.captchaPublicKey,captcha_widget_type:this.captchaWidgetType,clerk_js_version:this.clerkJSVersion,create_organization_url:this.createOrganizationUrl,favicon_image_url:this.faviconImageUrl,google_one_tap_client_id:this.googleOneTapClientId,home_url:this.homeUrl,id:this.id,instance_environment_type:this.instanceEnvironmentType,logo_image_url:this.logoImageUrl,organization_profile_url:this.organizationProfileUrl,preferred_sign_in_strategy:this.preferredSignInStrategy,privacy_policy_url:this.privacyPolicyUrl,show_devmode_warning:this.showDevModeWarning,sign_in_url:this.signInUrl,sign_up_url:this.signUpUrl,support_email:this.supportEmail,terms_url:this.termsUrl,theme:this.theme,user_profile_url:this.userProfileUrl,waitlist_url:this.waitlistUrl}}}var tW='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 tL=(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}},t$=()=>{let e=0,a=()=>e++,t=new Map,r=(e,a)=>e?.postMessage(a),i=e=>{t.get(e.data.id)?.()},n=tL(tW,{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:e3};let s=()=>{n||(n=tL(tW,{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 tK({delayInMs:e}={delayInMs:1e3}){let a,t=t$(),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 tB extends aD{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}=tK();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}=tK();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 t0(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new rl(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 tJ=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 tV(e){try{let a=await navigator.credentials.create({publicKey:e});if(!a)return{error:new O("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 O(a.message,{code:"passkey_already_exists"}):"NotAllowedError"===a.name?new O(a.message,{code:"passkey_registration_cancelled"}):tQ(a),publicKeyCredential:null}}}let tG=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 tH({publicKeyOptions:e,conditionalUI:a}){try{let t=await navigator.credentials.get({publicKey:e,mediation:a?"conditional":"optional",signal:tG.createAbortSignal()});if(!t)return{error:new O("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 O(t.message,{code:"passkey_retrieval_cancelled"}):tQ(t),publicKeyCredential:null}}}function tQ(e){return"AbortError"===e.name?new O(e.message,{code:"passkey_operation_aborted"}):"SecurityError"===e.name?new O(e.message,{code:"passkey_invalid_rpID_or_domain"}):e}function tY(e){let a=t2(e.challenge),t=(e.allowCredentials||[]).map(e=>({...e,id:t2(e.id)}));return{...e,allowCredentials:t,challenge:a}}function tZ(e){return{type:e.type,id:e.id,rawId:t1(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function tX(e){let a=e.response;return{...tZ(e),response:{clientDataJSON:t1(a.clientDataJSON),authenticatorData:t1(a.authenticatorData),signature:t1(a.signature),userHandle:a.userHandle?t1(a.userHandle):null}}}let t1=tJ.encode.bind(tJ),t2=tJ.decode.bind(tJ);class t0 extends aD{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===aD.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=aN(e.expire_at||void 0),this.error=e.error?new v(e.error):null,this.channel=e.channel||void 0),this}__internal_toSnapshot(){var e;return{object:"verification",id:this.id||"",status:this.status,strategy:this.strategy,nonce:this.nonce,message:this.message,external_verification_redirect_url:this.externalVerificationRedirectURL?.toString()||null,attempts:this.attempts,expire_at:this.expireAt?.getTime()||null,error:(e=this.error,{code:e?.code||"",message:e?.message||"",long_message:e?.longMessage,meta:{param_name:e?.meta?.paramName,session_id:e?.meta?.sessionId,email_addresses:e?.meta?.emailAddresses,identifiers:e?.meta?.identifiers,zxcvbn:e?.meta?.zxcvbn,plan:e?.meta?.plan,is_plan_upgrade_possible:e?.meta?.isPlanUpgradePossible}}),verified_at_client:this.verifiedAtClient}}}class t9 extends t0{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=t2((a=JSON.parse(e.nonce)).user.id),r=t2(a.challenge),i=(a.excludeCredentials||[]).map(e=>({...e,id:t2(e.id)})),{...a,excludeCredentials:i,challenge:r,user:{...a.user,id:t}})),this}}class t3{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new t8(e.email_address),this.phoneNumber=new t8(e.phone_number),this.web3Wallet=new t8(e.web3_wallet),this.externalAccount=new t0(e.external_account)):(this.emailAddress=new t8(null),this.phoneNumber=new t8(null),this.web3Wallet=new t8(null),this.externalAccount=new t0(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 t8 extends t0{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 t5 extends aD{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?aN(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new t0(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new t4(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 t4 extends aD{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=aN(e.created_at),this.updatedAt=aN(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 t6="token:update",t7="user:signOut",re="environment:update",ra="session:tokenResolved",rt=g();class rr extends aD{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 ri extends aD{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 rn extends aD{static instance;authConfig=new aL;displayConfig=new tN;maintenanceMode=!1;clientDebugMode=!1;pathRoot="/environment";userSettings=new rX;organizationSettings=new ri;commerceSettings=new tF;apiKeysSettings=new rr;protectConfig=new rz;static getInstance(){return rn.instance||(rn.instance=new rn),rn.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new aL(e.auth_config),this.displayConfig=new tN(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 ri(e.organization_settings),this.userSettings=new rX(e.user_settings),this.commerceSettings=new tF(e.commerce_settings),this.apiKeysSettings=new rr(e.api_keys_settings),this.protectConfig=new rz(e.protect_config)),this}fetch({touch:e,fetchMaxTries:a}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:a})).then(e=>(rt.emit(re,null),e))}isDevelopmentOrStaging=()=>!this.isProduction();isProduction=()=>"production"===this.displayConfig.instanceEnvironmentType;isSingleSession=()=>this.authConfig.singleSessionMode;onWindowLocationHost=()=>this.displayConfig.backendHost===window.location.host;__internal_toSnapshot(){return{object:"environment",auth_config:this.authConfig.__internal_toSnapshot(),display_config:this.displayConfig.__internal_toSnapshot(),id:this.id??"",maintenance_mode:this.maintenanceMode,client_debug_mode:this.clientDebugMode,organization_settings:this.organizationSettings.__internal_toSnapshot(),user_settings:this.userSettings.__internal_toSnapshot(),commerce_settings:this.commerceSettings.__internal_toSnapshot(),api_keys_settings:this.apiKeysSettings.__internal_toSnapshot(),protect_config:this.protectConfig.__internal_toSnapshot()}}async __internal_enableEnvironmentSetting(e){await this._basePatch({path:"/dev_tools/enable_environment_setting",body:e})}}class rs extends aD{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 t0(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 ro extends aD{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 rl extends aD{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 rc extends aD{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 rc((await aD._fetch({path:e,method:"POST",body:r,headers:t}))?.response)}static async delete(e){return new rc((await aD._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 rd extends aD{id;name;organizationId;enrollmentMode;verification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:a}){return new rd((await aD._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:aN(e.verification.expires_at)}:this.verification=null),this}}class ru extends aD{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=aN(e.created_at),this.updatedAt=aN(e.updated_at),e.public_user_data&&(this.publicUserData=new r_(e.public_user_data))),this}}class rh extends aD{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=aN(e.created_at),this.updatedAt=aN(e.updated_at)),this}}class rm extends aD{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 rh(e)),this.createdAt=aN(e.created_at),this.updatedAt=aN(e.updated_at)),this}}class rp extends aD{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 rp((await aD._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new rp((await aD._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await aD._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:te(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t,has_role_set_migration:r}=e?.response;return{data:a.map(e=>new rm(e)),total_count:t,has_role_set_migration:r}});getDomains=async e=>await aD._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:te(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rd(e))}});getDomain=async({domainId:e})=>new rd((await aD._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getMembershipRequests=async e=>await aD._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:te(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new ru(e))}});createDomain=async e=>rd.create(this.id,{name:e});getMemberships=async e=>await aD._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:te({...e,paginated:!0})}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rb(e))}});getInvitations=async e=>await aD._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:te(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rg(e))}});addMember=async({userId:e,role:a})=>await aD._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:a}}).then(e=>new rb(e?.response));inviteMember=async e=>rg.create(this.id,e);inviteMembers=async e=>rg.createBulk(this.id,e);updateMember=async({userId:e,role:a})=>await aD._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:a}}).then(e=>new rb(e?.response));removeMember=async e=>await aD._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new rb(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let a,t;return null===e?await aD._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new rp(e?.response)):("string"==typeof e?(a=e,t=new Headers({"Content-Type":"application/octet-stream"})):(a=new FormData).append("file",e),await aD._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:a,headers:t}).then(e=>new rp(e?.response)))};initializePaymentMethod=e=>tw({...e,orgId:this.id});addPaymentMethod=e=>tv({...e,orgId:this.id});getPaymentMethods=e=>tj({...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=aN(e.created_at),this.updatedAt=aN(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 aD._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:a},{forceUpdateClient:!0}))?.response;return this.fromJSON(t)}}class rg extends aD{id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:a,role:t}){return new rg((await aD._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 aD._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:t,role:r}}))?.response).map(e=>new rg(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=aN(e.created_at),this.updatedAt=aN(e.updated_at)),this}}class rb extends aD{id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await aD._fetch({path:"/me/organization_memberships",method:"GET",search:te({...e,paginated:!0})}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rb(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 rp(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new r_(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=aN(e.created_at),this.updatedAt=aN(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(`${ax} Calling OrganizationMembership.reload is not currently supported. Please contact support.`)}}class rf extends aD{id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await aD._fetch({path:"/me/organization_suggestions",method:"GET",search:te(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rf(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=aN(e.created_at),this.updatedAt=aN(e.updated_at)),this}}function ry(){return c()&&"function"==typeof window.PublicKeyCredential}async function rk(){try{return ry()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function rw(){try{return"undefined"!=typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class rv extends aD{id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return aD._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new rv(e?.response))}static async attemptVerification(e,a){let t,r=(t=a.response,{...tZ(a),response:{clientDataJSON:t1(t.clientDataJSON),attestationObject:t1(t.attestationObject),transports:t.getTransports()}});return aD._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(r)}}).then(e=>new rv(e?.response))}static async registerPasskey(){let e=rv.clerk.__internal_isWebAuthnSupported||ry,a=rv.clerk.__internal_createPublicCredentials||tV,t=rv.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||rw;if(!e())throw new O("Passkeys are not supported on this device.",{code:"passkey_not_supported"});let r=await this.create(),{verification:i}=r,n=i?.publicKey;if(n||aT("create"),n.authenticatorSelection?.authenticatorAttachment==="platform"&&!await t())throw new O("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 tD((await aD._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?aN(e.last_used_at):null,this.createdAt=aN(e.created_at),this.updatedAt=aN(e.updated_at),e.verification&&(this.verification=new t9(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 rj extends aD{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 t0(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new rl(e)),this.backupCodes=e.backup_codes),this}__internal_toSnapshot(){return{object:"phone_number",id:this.id||"",phone_number:this.phoneNumber,reserved_for_second_factor:this.reservedForSecondFactor,default_second_factor:this.defaultSecondFactor,verification:this.verification.__internal_toSnapshot(),linked_to:this.linkedTo.map(e=>e.__internal_toSnapshot()),backup_codes:this.backupCodes}}}class rz extends aD{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 r_{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 rx={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"}},rq=new Set(["first_factor","second_factor","multi_factor"]),rS=new Set(["strict_mfa","strict","moderate","lax"]),rU=(e,a)=>{let{org:t,user:r}=rC(e),[i,n]=a.split(":"),s=n||i;return"org"===i?t.includes(s):"user"===i?r.includes(s):[...t,...r].includes(s)},rC=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 rA extends aD{status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new t0(null);secondFactorVerification=new t0(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new rI(e.session),this.level=e.level,this.supportedFirstFactors=er(e.supported_first_factors),this.supportedSecondFactors=er(e.supported_second_factors),this.firstFactorVerification=new t0(e.first_factor_verification),this.secondFactorVerification=new t0(e.second_factor_verification)),this}}class rI extends aD{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 rI}constructor(e){super(),this.fromJSON(e),this.#eu(this.lastActiveToken)}end=()=>(tM.clear(),this._basePost({action:"end"}));remove=()=>(tM.clear(),this._basePost({action:"remove"}));touch=()=>this._basePost({action:"touch",body:{active_organization_id:this.lastActiveOrganizationId}}).then(e=>(e.lastActiveToken&&rt.emit(t6,{token:e.lastActiveToken}),e));clearCache=()=>tM.clear();getToken=async e=>an(()=>this._getToken(e),{factor:1.55,initialDelay:3e3,maxDelayBetweenRetries:5e4,jitter:!1,shouldRetry:(e,a)=>!E(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?rU(t,e.feature):e.plan&&r?rU(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&&rS.has(e),i="object"==typeof e&&(a=e.level,rq.has(a))&&"number"==typeof(t=e.afterMinutes)&&t>0;return(!!r||!!i)&&(e=>"string"==typeof e?rx[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)};#eu=e=>{e&&tM.set({tokenId:this.#eh(),tokenResolver:Promise.resolve(e)})};#eh(e,a){let t=void 0===a?this.lastActiveOrganizationId:a;return tA.build(this.id,e,t)}startVerification=async({level:e})=>new rA((await aD._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:aA("Session.prepareFirstFactorVerification",e.strategy)}return new rA((await aD._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(tX(e.publicKeyCredential))}:{...e},new rA((await aD._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=rI.clerk.__internal_isWebAuthnSupported||ry,t=rI.clerk.__internal_getPublicCredentials||tH;if(!a())throw new O("Passkeys are not supported",{code:"passkey_not_supported"});let r=e?tY(JSON.parse(e)):null;r||aT("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 rA((await aD._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>new rA((await aD._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=aN(e.expire_at),this.abandonAt=aN(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=aN(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.createdAt=aN(e.created_at),this.updatedAt=aN(e.updated_at),this.user=new rH(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new r_(e.public_user_data)),this.lastActiveToken=e.last_active_token?new rJ(e.last_active_token):null),this}__internal_toSnapshot(){return{object:"session",id:this.id,status:this.status,expire_at:this.expireAt.getTime(),abandon_at:this.abandonAt.getTime(),factor_verification_age:this.factorVerificationAge,last_active_at:this.lastActiveAt.getTime(),last_active_organization_id:this.lastActiveOrganizationId,actor:this.actor,tasks:this.tasks,user:this.user?.__internal_toSnapshot()||null,public_user_data:this.publicUserData.__internal_toSnapshot(),last_active_token:this.lastActiveToken?.__internal_toSnapshot()||null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}async _getToken(e){if(!this.user)return null;let{leewayInSeconds: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.#eh(t,i),s=r?void 0:tM.get({tokenId:n},a),o=!t&&i===this.lastActiveOrganizationId;if(s){aa.debug("Using cached token (no fetch needed)",{tokenId:n},"session");let e=await s.tokenResolver;return o&&rt.emit(t6,{token:e}),e.getRawString()||null}aa.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=this.lastActiveToken?.getRawString(),u=rJ.create(l,c,r?{debug:"skip_cache"}:void 0).catch(e=>{if(x.is(e)&&d)return rJ.create(l,{...c},{expired_token:d});throw e});return tM.set({tokenId:n,tokenResolver:u}),u.then(e=>(o&&(rt.emit(t6,{token:e}),e.jwt&&(this.lastActiveToken=e,rt.emit(ra,null))),e.getRawString()||null))}get currentTask(){let[e]=this.tasks??[];return e}}class rP extends aD{pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,a){super(),this.pathRoot=a,this.fromJSON(e)}static retrieve(){let e=aD.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new rP(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=aN(e.expire_at),this.abandonAt=aN(e.abandon_at),this.lastActiveAt=aN(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 rO=(e,a,t)=>{let{onValidation:r=e3,onValidationComplexity:i=e3}=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 rT(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function rE(e,a,t,r,i){if(!e.client||!r.popup)return;let n=rT(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 rM(e,{redirectCallbackUrl:a,redirectUrl:t}){let r=rT(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 rR(e,a){return new Promise((t,r)=>{if(!e.client||!a.popup)return void r();let i=async a=>{a.origin===rT(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 rF(e,a){rt.emit("resource:error",{resource:e,error:null}),rt.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await a(),error:null}}catch(a){return rt.emit("resource:error",{resource:e,error:a}),{error:a}}finally{rt.emit("resource:fetch",{resource:e,status:"idle"})}}let rD=()=>{var e;return(e=new ao,{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 rN extends aD{pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;firstFactorVerification=new t0(null);secondFactorVerification=new t0(null);identifier=null;createdSessionId=null;userData=new rQ(null);clientTrustState;get status(){return this._status}set status(e){let a=this._status;this._status=e,e&&a!==e&&aa.debug("SignIn.status",{id:this.id,from:a,to:e})}__internal_future=new rW(this);__internal_basePost=this._basePost.bind(this);__internal_baseGet=this._baseGet.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=e=>{aa.debug("SignIn.create",{id:this.id,strategy:"strategy"in e?e.strategy:void 0});let a=ag();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(aa.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":case"web3_solana_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:aA("SignIn.prepareFirstFactor",e.strategy)}return this._basePost({body:{...a,strategy:e.strategy},action:"prepare_first_factor"})};attemptFirstFactor=e=>{let a;return aa.debug("SignIn.attemptFirstFactor",{id:this.id,strategy:e.strategy}),a="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(tX(e.publicKeyCredential))}:{...e},this._basePost({body:{...a,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:a}=tK();return{startEmailLinkFlow:async({emailAddressId:t,redirectUrl:r})=>{this.id||aC("SignIn");let i={strategy:"email_link",emailAddressId:t,redirectUrl:r},n="needs_second_factor"===this.status||"needs_client_trust"===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=>(aa.debug("SignIn.prepareSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_second_factor"}));attemptSecondFactor=e=>(aa.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=rN.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):aO(c,rN.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,e$);authenticateWithPopup=async e=>{let{popup:a}=e||{};return a||aP("popup"),rE(rN.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",walletName:n}=e||{},s=i.replace("web3_","").replace("_signature","");"function"!=typeof r&&aP("generateSignature"),"solana"!==s||n||aP("walletName"),await this.create({identifier:t});let o=this.supportedFirstFactors?.find(e=>e.strategy===i);o||aI("SignIn"),await this.prepareFirstFactor(o);let{message:l}=this.firstFactorVerification;l||aI("SignIn");try{a=await r({identifier:t,nonce:l,walletName:n,provider:s})}catch(e){if("coinbase_wallet"===s&&4001===e.code)a=await r({identifier:t,nonce:l,provider:s,walletName:n});else throw e}return this.attemptFirstFactor({signature:a,strategy:i})};authenticateWithMetamask=async()=>{let e=await aw().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:aw().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await aw().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:aw().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await aw().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:aw().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await aw().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:aw().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithSolana=async({walletName:e})=>{let a=await aw().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:a,generateSignature:a=>aw().generateSignatureWithSolana({...a,walletName:e}),strategy:"web3_solana_signature",walletName:e})};authenticateWithPasskey=async e=>{let{flow:a}=e||{},t=rN.clerk.__internal_isWebAuthnSupported||ry,r=rN.clerk.__internal_getPublicCredentials||tH,i=rN.clerk.__internal_isWebAuthnAutofillSupported||rk;if(!t())throw new O("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(`${ax} 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?tY(JSON.parse(n)):null;s||aT("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(rN.clerk.__internal_environment?.userSettings.passwordSettings)return rO(rD(),{...rN.clerk.__internal_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=er(e.supported_first_factors),this.supportedSecondFactors=er(e.supported_second_factors),this.firstFactorVerification=new t0(e.first_factor_verification),this.secondFactorVerification=new t0(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new rQ(e.user_data),this.clientTrustState=e.client_trust_state??void 0),rt.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:et(this.supportedFirstFactors),supported_second_factors:et(this.supportedSecondFactors),first_factor_verification:this.firstFactorVerification.__internal_toSnapshot(),second_factor_verification:this.secondFactorVerification.__internal_toSnapshot(),identifier:this.identifier,created_session_id:this.createdSessionId,user_data:this.userData.__internal_toSnapshot()}}}class rW{emailCode={sendCode:this.sendEmailCode.bind(this),verifyCode:this.verifyEmailCode.bind(this)};emailLink={sendLink:this.sendEmailLink.bind(this),waitForVerification:this.waitForEmailLinkVerification.bind(this),get verification(){if(!o())return null;let e=eO("__clerk_status"),a=eO("__clerk_created_session");if(!e||!a)return null;let t="verified"===e&&void 0!==rN.clerk.client&&rN.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)};#em=!1;#ep;constructor(e){this.#ep=e}get id(){return this.#ep.id}get identifier(){return this.#ep.identifier}get createdSessionId(){return this.#ep.createdSessionId}get userData(){return this.#ep.userData}get status(){return this.#ep.status||"needs_identifier"}get supportedFirstFactors(){return this.#ep.supportedFirstFactors??[]}get supportedSecondFactors(){return this.#ep.supportedSecondFactors??[]}get isTransferable(){return"transferable"===this.#ep.firstFactorVerification.status}get existingSession(){if("failed"===this.#ep.firstFactorVerification.status&&this.#ep.firstFactorVerification.error?.code==="identifier_already_signed_in"&&this.#ep.firstFactorVerification.error?.meta?.sessionId)return{sessionId:this.#ep.firstFactorVerification.error?.meta?.sessionId}}get firstFactorVerification(){return this.#ep.firstFactorVerification}get secondFactorVerification(){return this.#ep.secondFactorVerification}get hasBeenFinalized(){return this.#em}async sendResetPasswordEmailCode(){if(!this.#ep.id)throw Error("Cannot reset password without a sign in.");return rF(this.#ep,async()=>{let e=this.#ep.supportedFirstFactors?.find(e=>"reset_password_email_code"===e.strategy);if(!e)throw new I("Reset password email code factor not found",{code:"factor_not_found"});let{emailAddressId:a}=e;await this.#ep.__internal_basePost({body:{emailAddressId:a,strategy:"reset_password_email_code"},action:"prepare_first_factor"})})}async verifyResetPasswordEmailCode(e){let{code:a}=e;return rF(this.#ep,async()=>{await this.#ep.__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 rF(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{password:a,signOutOfOtherSessions:t},action:"reset_password"})})}async _create(e){let a=ag();await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:a?{locale:a,...e}:e})}async create(e){return rF(this.#ep,async()=>{await this._create(e)})}async password(e){if([e.identifier,e.emailAddress,e.phoneNumber].filter(Boolean).length>1)throw Error("Only one of identifier, emailAddress, or phoneNumber can be provided");return rF(this.#ep,async()=>{let a=e.identifier||e.emailAddress||e.phoneNumber,t=this.#ep.identifier,r=ag();await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:{identifier:a||t,password:e.password,...r?{locale:r}:{}}})})}async sendEmailCode(e={}){let{emailAddress:a,emailAddressId:t}=e;if(!this.#ep.id&&t)throw Error("signIn.emailCode.sendCode() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#ep.id&&!a)throw Error("signIn.emailCode.sendCode() cannot be called without an emailAddress if an existing signIn does not exist.");return rF(this.#ep,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"email_code",emailAddressId:t});if(!e)throw new I("Email code factor not found",{code:"factor_not_found"});await this.#ep.__internal_basePost({body:{emailAddressId:e.emailAddressId,strategy:"email_code"},action:"prepare_first_factor"})})}async verifyEmailCode(e){let{code:a}=e;return rF(this.#ep,async()=>{await this.#ep.__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.#ep.id&&r)throw Error("signIn.emailLink.sendLink() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#ep.id&&!a)throw Error("signIn.emailLink.sendLink() cannot be called without an emailAddress if an existing signIn does not exist.");return rF(this.#ep,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"email_link",emailAddressId:r});if(!e)throw new I("Email link factor not found",{code:"factor_not_found"});let i=t;try{new URL(t)}catch{i=window.location.origin+t}await this.#ep.__internal_basePost({body:{emailAddressId:e.emailAddressId,redirectUrl:i,strategy:"email_link"},action:"prepare_first_factor"})})}async waitForEmailLinkVerification(){return rF(this.#ep,async()=>{let{run:e,stop:a}=tK();await new Promise((t,r)=>{e(async()=>{try{let e=await this.#ep.__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.#ep.id&&t)throw Error("signIn.phoneCode.sendCode() cannot be called with an phoneNumberId if an existing signIn does not exist.");if(!this.#ep.id&&!a)throw Error("signIn.phoneCode.sendCode() cannot be called without an phoneNumber if an existing signIn does not exist.");return rF(this.#ep,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"phone_code",phoneNumberId:t});if(!e)throw new I("Phone code factor not found",{code:"factor_not_found"});await this.#ep.__internal_basePost({body:{phoneNumberId:e.phoneNumberId,strategy:"phone_code",channel:r},action:"prepare_first_factor"})})}async verifyPhoneCode(e){let{code:a}=e;return rF(this.#ep,async()=>{await this.#ep.__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 rF(this.#ep,async()=>{let e=t;try{new URL(t)}catch{e=window.location.origin+t}let l={redirectUrl:rN.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:e};if(i){let a=rM(rN.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.#ep.__internal_basePost({body:{...l,oidcPrompt:n,enterpriseConnectionId:s,strategy:"enterprise_sso"},action:"prepare_first_factor"});let{status:c,externalVerificationRedirectURL:d}=this.#ep.firstFactorVerification;"unverified"===c&&d&&(i?(await rR(rN.clerk,{popup:i,externalVerificationRedirectURL:d}),await this.#ep.reload()):e$(d))})}async web3(e){let{strategy:a}=e,t=a.replace("web3_","").replace("_signature","");return rF(this.#ep,async()=>{let r,i,n;switch(t){case"metamask":r=await aw().getMetamaskIdentifier(),i=aw().generateSignatureWithMetamask;break;case"coinbase_wallet":r=await aw().getCoinbaseWalletIdentifier(),i=aw().generateSignatureWithCoinbaseWallet;break;case"base":r=await aw().getBaseIdentifier(),i=aw().generateSignatureWithBase;break;case"okx_wallet":r=await aw().getOKXWalletIdentifier(),i=aw().generateSignatureWithOKXWallet;break;case"solana":if(!e.walletName)throw new I("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});r=await aw().getSolanaIdentifier(e.walletName),i=a=>aw().generateSignatureWithSolana({...a,walletName:e.walletName});break;default:throw Error(`Unsupported Web3 provider: ${t}`)}await this._create({identifier:r});let s=this.#ep.supportedFirstFactors?.find(e=>e.strategy===a);if(!s)throw new I("Web3 first factor not found",{code:"factor_not_found"});await this.#ep.__internal_basePost({body:{web3WalletId:s.web3WalletId,strategy:a},action:"prepare_first_factor"});let{message:o}=this.firstFactorVerification;if(!o)throw new I("Web3 nonce not found",{code:"web3_nonce_not_found"});try{n=await i({identifier:r,nonce:o,walletName:e?.walletName,provider:t})}catch(e){if("coinbase_wallet"===t&&4001===e.code)n=await i({identifier:r,nonce:o,provider:t});else throw e}await this.#ep.__internal_basePost({body:{signature:n,strategy:a},action:"attempt_first_factor"})})}async passkey(e){let{flow:a}=e||{},t=rN.clerk.__internal_isWebAuthnSupported||ry,r=rN.clerk.__internal_getPublicCredentials||tH,i=rN.clerk.__internal_isWebAuthnAutofillSupported||rk;if(!t())throw new O("Passkeys are not supported",{code:"passkey_not_supported"});return rF(this.#ep,async()=>{if("autofill"===a||"discoverable"===a)await this._create({strategy:"passkey"});else{if(!this.supportedFirstFactors.find(e=>"passkey"===e.strategy))throw new I("Passkey factor not found",{code:"factor_not_found"});await this.#ep.__internal_basePost({body:{strategy:"passkey"},action:"prepare_first_factor"})}let{nonce:e}=this.firstFactorVerification,t=e?tY(JSON.parse(e)):null;if(!t)throw new I("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 O(o.message,{code:"passkey_retrieval_failed"});await this.#ep.__internal_basePost({body:{publicKeyCredential:JSON.stringify(tX(s)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return rF(this.#ep,async()=>{let e=this.#ep.supportedSecondFactors?.find(e=>"phone_code"===e.strategy);if(!e)throw new I("Phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:a}=e;await this.#ep.__internal_basePost({body:{phoneNumberId:a,strategy:"phone_code"},action:"prepare_second_factor"})})}async verifyMFAPhoneCode(e){let{code:a}=e;return rF(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:a,strategy:"phone_code"},action:"attempt_second_factor"})})}async verifyTOTP(e){let{code:a}=e;return rF(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:a,strategy:"totp"},action:"attempt_second_factor"})})}async verifyBackupCode(e){let{code:a}=e;return rF(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{code:a,strategy:"backup_code"},action:"attempt_second_factor"})})}async ticket(e){let a=e?.ticket??eO("__clerk_ticket");return this.create({ticket:a??void 0})}async finalize(e){let{navigate:a}=e||{};if(!this.#ep.createdSessionId)throw Error("Cannot finalize sign-in without a created session.");return rF(this.#ep,async()=>{rN.clerk.client&&!rN.clerk.client.sessions.some(e=>e.id===this.#ep.createdSessionId)&&await rN.clerk.client.reload(),this.#em=!0,await rN.clerk.setActive({session:this.#ep.createdSessionId,navigate:a})})}selectFirstFactor({strategy:e,emailAddressId:a,phoneNumberId:t}){if(!this.#ep.supportedFirstFactors)return null;if(a){let t=this.#ep.supportedFirstFactors.find(t=>t.strategy===e&&t.emailAddressId===a);if(t)return t}if(t){let a=this.#ep.supportedFirstFactors.find(a=>a.strategy===e&&a.phoneNumberId===t);if(a)return a}let r=this.#ep.supportedFirstFactors.find(a=>a.strategy===e&&a.safeIdentifier===this.#ep.identifier);if(r)return r;let i=this.#ep.supportedFirstFactors.find(a=>a.strategy===e);return i||null}}function rL(e){let{unsafeMetadata:a}={...e},t=a?"object"==typeof a?JSON.stringify(a):a:"";return{...e,...a?{unsafeMetadata:t}:{}}}class r$ extends aD{pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new t3(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&&aa.debug("SignUp.status",{id:this.id,from:a,to:e})}__internal_future=new rK(this);__internal_basePost=this._basePost.bind(this);__internal_basePatch=this._basePatch.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{aa.debug("SignUp.create",{id:this.id,strategy:e.strategy});let a={...e};if(!a.locale){let e=ag();e&&(a.locale=e)}if(a.transfer&&this.shouldBypassCaptchaForAttempt(a)){let e=r$.clerk.client?.signIn.firstFactorVerification.strategy;e&&(a={...a,strategy:e})}return this._basePost({path:this.pathRoot,body:rL(a)})};prepareVerification=e=>(aa.debug("SignUp.prepareVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_verification"}));attemptVerification=e=>(aa.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}=tK();return{startEmailLinkFlow:async({redirectUrl:t})=>(this.id||aC("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,walletName:o}=e||{},l=n.replace("web3_","").replace("_signature","");"function"!=typeof t&&aP("generateSignature");let c=r||this.web3wallet;await this.create({web3Wallet:c,unsafeMetadata:i,legalAccepted:s}),await this.prepareWeb3WalletVerification({strategy:n});let{message:d}=this.verifications.web3Wallet;d||aI("SignUp");try{a=await t({identifier:r,nonce:d,provider:l,walletName:o})}catch(e){if("coinbase_wallet"===l&&4001===e.code)a=await t({identifier:r,nonce:d,provider:l});else throw e}return this.attemptWeb3WalletVerification({signature:a,strategy:n})};authenticateWithMetamask=async e=>{let a=await aw().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:aw().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let a=await aw().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:aw().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let a=await aw().getBaseIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:aw().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let a=await aw().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:aw().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithSolana=async({walletName:e,unsafeMetadata:a,legalAccepted:t})=>{let r=await aw().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:r,generateSignature:a=>aw().generateSignatureWithSolana({...a,walletName:e}),unsafeMetadata:a,strategy:"web3_solana_signature",legalAccepted:t,walletName:e})};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=r$.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(_(e)&&T(e))return await r$.clerk.__internal_environment.reload(),h();throw e}),{externalAccount:p}=m,{status:g,externalVerificationRedirectURL:b}=p;"unverified"===g&&b?a(b):aO(g,r$.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,e$);authenticateWithPopup=async e=>{let{popup:a}=e||{};return a||aP("popup"),rE(r$.clerk,"signUp",this.authenticateWithRedirectOrPopup,e,e=>{a.location.href=e instanceof URL?e.toString():e})};update=e=>this._basePatch({body:rL(e)});upsert=e=>this.id?this.update(e):this.create(e);validatePassword=(e,a)=>{if(r$.clerk.__internal_environment?.userSettings.passwordSettings)return rO(rD(),{...r$.clerk.__internal_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 t3(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),rt.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 r$.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){if(!e.strategy)return!1;let a=r$.clerk.__internal_environment.displayConfig.captchaOauthBypass;return!!(a.some(a=>a===e.strategy)||e.transfer&&a.some(e=>e===r$.clerk.client.signIn.firstFactorVerification.strategy))}__experimental_getEnterpriseConnections=()=>aD._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new rB(e)))}class rK{verifications={sendEmailCode:this.sendEmailCode.bind(this),verifyEmailCode:this.verifyEmailCode.bind(this),sendPhoneCode:this.sendPhoneCode.bind(this),verifyPhoneCode:this.verifyPhoneCode.bind(this)};#em=!1;#ep;constructor(e){this.#ep=e}get id(){return this.#ep.id}get requiredFields(){return this.#ep.requiredFields}get optionalFields(){return this.#ep.optionalFields}get missingFields(){return this.#ep.missingFields}get status(){return this.#ep.status||"missing_requirements"}get username(){return this.#ep.username}get firstName(){return this.#ep.firstName}get lastName(){return this.#ep.lastName}get emailAddress(){return this.#ep.emailAddress}get phoneNumber(){return this.#ep.phoneNumber}get web3Wallet(){return this.#ep.web3wallet}get hasPassword(){return this.#ep.hasPassword}get unsafeMetadata(){return this.#ep.unsafeMetadata}get createdSessionId(){return this.#ep.createdSessionId}get createdUserId(){return this.#ep.createdUserId}get abandonAt(){return this.#ep.abandonAt}get legalAcceptedAt(){return this.#ep.legalAcceptedAt}get locale(){return this.#ep.locale}get unverifiedFields(){return this.#ep.unverifiedFields}get isTransferable(){return"transferable"===this.#ep.verifications.externalAccount.status&&this.#ep.verifications.externalAccount.error?.code==="external_account_exists"}get existingSession(){if(("failed"===this.#ep.verifications.externalAccount.status||"unverified"===this.#ep.verifications.externalAccount.status)&&this.#ep.verifications.externalAccount.error?.code==="identifier_already_signed_in"&&this.#ep.verifications.externalAccount.error?.meta?.sessionId)return{sessionId:this.#ep.verifications.externalAccount.error?.meta?.sessionId}}get hasBeenFinalized(){return this.#em}async getCaptchaToken(){let e=new aR(r$.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?rL(e.unsafeMetadata):void 0,locale:e.locale??ag()};await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:i})}async create(e){return rF(this.#ep,async()=>{await this._create(e)})}async update(e){return rF(this.#ep,async()=>{let a={...e,unsafeMetadata:e.unsafeMetadata?rL(e.unsafeMetadata):void 0};await this.#ep.__internal_basePatch({path:this.#ep.pathRoot,body:a})})}async password(e){return rF(this.#ep,async()=>{let{captchaToken:a,captchaWidgetType:t,captchaError:r}=await this.getCaptchaToken(),i={strategy:"password",captchaToken:a,captchaWidgetType:t,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rL(e.unsafeMetadata):void 0};await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:i})})}async sendEmailCode(){return rF(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification"})})}async verifyEmailCode(e){let{code:a}=e;return rF(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{strategy:"email_code",code:a},action:"attempt_verification"})})}async sendPhoneCode(e){let{phoneNumber:a,channel:t="sms"}=e;return rF(this.#ep,async()=>{if(!this.#ep.id){let{captchaToken:e,captchaWidgetType:t,captchaError:r}=await this.getCaptchaToken();await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:{phoneNumber:a,captchaToken:e,captchaWidgetType:t,captchaError:r}})}await this.#ep.__internal_basePost({body:{strategy:"phone_code",channel:t},action:"prepare_verification"})})}async verifyPhoneCode(e){let{code:a}=e;return rF(this.#ep,async()=>{await this.#ep.__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 rF(this.#ep,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:r$.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:h};if(c){let e=rM(r$.clerk,{redirectCallbackUrl:m.redirectUrl,redirectUrl:h});m.redirectUrl=e.redirectCallbackUrl,m.actionCompleteRedirectUrl=e.redirectUrl}let p=()=>this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:{strategy:a,...m,unsafeMetadata:i,legalAccepted:n,oidcPrompt:s,enterpriseConnectionId:o,emailAddress:l,captchaToken:e,captchaWidgetType:d,captchaError:u}});await p().catch(async e=>{if(_(e)&&T(e))return await r$.clerk.__internal_environment.reload(),p();throw e});let{status:g,externalVerificationRedirectURL:b}=this.#ep.verifications.externalAccount;"unverified"===g&&b&&(c?(await rR(r$.clerk,{popup:c,externalVerificationRedirectURL:b}),await this.#ep.reload()):e$(b))})}async web3(e){let{strategy:a,unsafeMetadata:t,legalAccepted:r}=e,i=a.replace("web3_","").replace("_signature","");return rF(this.#ep,async()=>{let e,n,s;switch(i){case"metamask":e=await aw().getMetamaskIdentifier(),n=aw().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await aw().getCoinbaseWalletIdentifier(),n=aw().generateSignatureWithCoinbaseWallet;break;case"base":e=await aw().getBaseIdentifier(),n=aw().generateSignatureWithBase;break;case"okx_wallet":e=await aw().getOKXWalletIdentifier(),n=aw().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${i}`)}let o=e||this.#ep.web3wallet;await this._create({web3Wallet:o,unsafeMetadata:t,legalAccepted:r}),await this.#ep.__internal_basePost({body:{strategy:a},action:"prepare_verification"});let{message:l}=this.#ep.verifications.web3Wallet;l||aI("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.#ep.__internal_basePost({body:{signature:s,strategy:a},action:"attempt_verification"})})}async ticket(e){let a=e?.ticket??eO("__clerk_ticket");return this.create({...e,ticket:a??void 0})}async finalize(e){let{navigate:a}=e||{};return rF(this.#ep,async()=>{if(!this.#ep.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#em=!0,await r$.clerk.setActive({session:this.#ep.createdSessionId,navigate:a})})}}class rB extends aD{id;name;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name),this}}class rJ extends aD{pathRoot="tokens";jwt;static async create(e,a={},t={}){return new rJ(await aD._fetch({method:"POST",path:e,body:a,search:t}),e)}constructor(e,a){super(),a&&(this.pathRoot=a),e?.jwt&&(this.jwt=ap(e.jwt))}getRawString=()=>this.jwt?.claims.__raw||"";fromJSON(e){return e&&(this.jwt=ap(e.jwt)),this}__internal_toSnapshot(){return{object:"token",id:this.id||"",jwt:this.getRawString()}}}class rV extends aD{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=aN(e.updated_at),this.createdAt=aN(e.created_at)),this}}class rG extends aD{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=aN(e.updated_at),this.createdAt=aN(e.created_at)),this}}class rH extends aD{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 rH}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case tB:return this.primaryEmailAddressId===e.id;case rj:return this.primaryPhoneNumberId===e.id;case r1:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:a}=e||{};return new tB({email_address:a},this.path()+"/email_addresses/").create()};createPasskey=()=>rv.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:a}=e||{};return new rj({phone_number:a},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:a}=e||{};return new r1({web3_wallet:a},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:a,redirectUrl:t,additionalScopes:r}=e||{};return new rs((await aD._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:a,redirect_url:t,additional_scope:r}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new rV((await aD._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new rV((await aD._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new tD((await aD._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new rG((await aD._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);update=e=>this._basePatch({body:rL(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=>(rt.emit(t7,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await rP.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:a}=e||{};return null===a?rc.delete(`${this.path()}/profile_image`):rc.create(`${this.path()}/profile_image`,{file:a})};getOrganizationInvitations=e=>rY.retrieve(e);getOrganizationSuggestions=e=>rf.retrieve(e);getOrganizationMemberships=e=>rb.retrieve(e);leaveOrganization=async e=>new tD((await aD._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);initializePaymentMethod=e=>tw(e);addPaymentMethod=e=>tv(e);getPaymentMethods=e=>tj(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 tB(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 rj(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 r1(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 rs(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new rv(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new rb(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new t5(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=aN(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=aN(e.legal_accepted_at)),this.updatedAt=aN(e.updated_at||void 0),this.createdAt=aN(e.created_at||void 0)),this}__internal_toSnapshot(){return{object:"user",id:this.id,external_id:this.externalId,first_name:this.firstName,last_name:this.lastName,username:this.username,public_metadata:this.publicMetadata,unsafe_metadata:this.unsafeMetadata,image_url:this.imageUrl,has_image:this.hasImage,email_addresses:this.emailAddresses.map(e=>e.__internal_toSnapshot()),phone_numbers:this.phoneNumbers.map(e=>e.__internal_toSnapshot()),web3_wallets:this.web3Wallets.map(e=>e.__internal_toSnapshot()),external_accounts:this.externalAccounts.map(e=>e.__internal_toSnapshot()),passkeys:this.passkeys.map(e=>e.__internal_toSnapshot()),organization_memberships:this.organizationMemberships.map(e=>e.__internal_toSnapshot()),enterprise_accounts:this.enterpriseAccounts.map(e=>e.__internal_toSnapshot()),totp_enabled:this.totpEnabled,backup_code_enabled:this.backupCodeEnabled,two_factor_enabled:this.twoFactorEnabled,create_organization_enabled:this.createOrganizationEnabled,create_organizations_limit:this.createOrganizationsLimit,delete_self_enabled:this.deleteSelfEnabled,primary_email_address_id:this.primaryEmailAddressId,primary_phone_number_id:this.primaryPhoneNumberId,primary_web3_wallet_id:this.primaryWeb3WalletId,password_enabled:this.passwordEnabled,profile_image_id:this.imageUrl,last_sign_in_at:this.lastSignInAt?.getTime()||null,legal_accepted_at:this.legalAcceptedAt?.getTime()||null,updated_at:this.updatedAt?.getTime()||null,created_at:this.createdAt?.getTime()||null}}}class rQ{firstName;lastName;imageUrl;hasImage;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.firstName=e.first_name,this.lastName=e.last_name,this.imageUrl=e.image_url??void 0,this.hasImage=e.has_image??void 0),this}__internal_toSnapshot(){return{first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl||null,has_image:this.hasImage||null}}}class rY extends aD{id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await aD._fetch({path:"/me/organization_invitations",method:"GET",search:te(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rY(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=aN(e.created_at),this.updatedAt=aN(e.updated_at)),this}}let rZ={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 rX extends aD{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:{...rZ,name:"phone_number"},username:{...rZ,name:"username"},web3_wallet:{...rZ,name:"web3_wallet"},first_name:{...rZ,name:"first_name"},last_name:{...rZ,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:{...rZ,name:"authenticator_app"},backup_code:{...rZ,name:"backup_code"},passkey:{...rZ,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}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 r1 extends aD{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 t0(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}class r2 extends aD{pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=aN(e.updated_at),this.createdAt=aN(e.created_at),rt.emit("resource:update",{resource:this})),this}async join(e){return rF(this,async()=>{await r2.join(e)})}static async join(e){return new r2(await aD._fetch({path:"/waitlist",method:"POST",body:e}))}}function r0(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 r9(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(tR.isClientResource(e))return e.id!==a.id||e.updatedAt.getTime()<a.updatedAt.getTime()||e.sessions.length!==a.sessions.length;if(rI.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&&r0(t.user,r.user))}if(rH.isUserResource(e))return r0(e,a)}catch{}return!0}(e,a)?e:a}let r3="__clerk_db_jwt";function r8(e,a){let t=new URL(e),r=t.searchParams.get(r3);t.searchParams.delete(r3);let i=r||a;return i&&t.searchParams.set(r3,i),t}let r5=e=>{let a=new URL(e);return a.searchParams.delete(r3),a},r4=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 r6(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 r7=function e(a,t){function r(e,r,i){if("undefined"!=typeof document){"number"==typeof(i=r6({},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,"",r6({},a,{expires:-1}))},withAttributes:function(a){return e(this.converter,r6({},this.attributes,a))},withConverter:function(a){return e(r6({},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 ie(e){return{get:()=>r7.get(e),set(a,t={}){r7.set(e,a,t)},remove(a){r7.remove(e,a)}}}let ia=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function it(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 ir=ie("__clerk_test_etld"),ii="__client_uat",is="__session",io=()=>{let e=af()?"None":"Lax",a=ia(e);return{sameSite:e,secure:a,partitioned:!1}};async function il(e){let a;try{a=await ep(e)}catch(o){var t;t=`Suffixed cookie failed due to ${o.message} (secure-context: ${window.isSecureContext}, url: ${window.location.href})`,H.has(t)||(console.log(t),H.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 ic=()=>{let e=af()?"None":"Lax",a=ia(e);return{sameSite:e,secure:a}};var id=i(945),iu=i.n(id);class ih{lock=(k="clerk.lock.refreshSessionToken",s=new(iu()),window.addEventListener("beforeunload",async()=>{await s.releaseLock(k)}),{acquireLockAndRun:async e=>{if("locks"in navigator&&isSecureContext){let a=new AbortController,t=setTimeout(()=>a.abort(),4999);return await navigator.locks.request(k,{signal:a.signal},async()=>(clearTimeout(t),await e())).catch(()=>!1)}if(await s.acquireLock(k,5e3))try{return await e()}finally{await s.releaseLock(k)}}});workerTimers=t$();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 im{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,a,t,r){let i=await il(e.publishableKey),n=new im(e,a,i,t,r);return await n.setup(),n}constructor(e,a,r,i,n){let s,o,l,c,d,u,h;this.clerk=e,this.instanceType=i,this.clerkEventBus=n,rt.on(t6,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),rt.on(t7,()=>this.handleSignOut()),this.refreshTokenOnFocus(),this.startPollingForToken(),this.clientUat=(s=ie(ii),o=ie(eg(ii,r)),{set:e=>{let a=it(Date.now(),1),r=af()?"None":"Strict",i=ia(r),n=function(e=window.location.hostname,a=ir){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()),o.remove(),s.remove(),o.set(l,{domain:n,expires:a,partitioned:!1,sameSite:r,secure:i}),s.set(l,{domain:n,expires:a,partitioned:!1,sameSite:r,secure:i})},get:()=>parseInt(o.get()||s.get()||"0",10)}),this.sessionCookie=(l=ie(is),c=ie(eg(is,r)),{set:e=>{let a=it(Date.now(),1),{sameSite:t,secure:r,partitioned:i}=io();i&&d(),l.set(e,{expires:a,sameSite:t,secure:r,partitioned:i}),c.set(e,{expires:a,sameSite:t,secure:r,partitioned:i})},remove:d=()=>{let e=io();l.remove(e),c.remove(e)},get:()=>c.get()||l.get()}),this.activeCookie=(u=ie("clerk_active_context"),h={secure:ia("None")},{set:e=>{u.set(e,h)},get:()=>u.get(),remove:()=>u.remove(h)}),this.devBrowser=function({cookieSuffix:e,frontendApi:a,fapiClient:t}){let r,i,n=(r=ie(r3),i=ie(eg(r3,e)),{get:()=>i.get()||r.get(),set:e=>{let a=it(Date.now(),1),{sameSite:t,secure:n}=ic();i.set(e,{expires:a,sameSite:t,secure:n}),r.set(e,{expires:a,sameSite:t,secure:n})},remove:()=>{let e=ic();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(!ew(a))return;t.onBeforeRequest(e=>{let a=s();a&&e?.url&&(e.url=r8(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(r3)||"",r5(r4(e)).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",r5(r4(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 v(e)):[]}((await c.json()).errors);e[0]?aS(e[0].longMessage):aS()}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(`${ax} Missing dev browser jwt. Please contact support.`);return r8(e,a)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new ih,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||u()||aa.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(_(e)||P(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(E(e))return void this.clerk.handleUnauthenticated().catch(e3);this.clerkEventBus.emit(b,"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 ip{clerk;captchaChallenge;timers;constructor(e,a=new aR(e),t=t$()){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.__internal_environment?.displayConfig?.captchaHeartbeat}clientBypass(){return this.clerk.client?.captchaBypass}intervalInMs(){return this.clerk.__internal_environment?.displayConfig?.captchaHeartbeatIntervalMs??6e5}}let ig=["/client","/waitlist"];class ib{async getBaseFapiProxyOptions(){let e=await aD.clerk.session?.getToken();if(!e)throw new I("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 aD._fetch({...await this.getBaseFapiProxyOptions(),method:"GET",path:"/api_keys",search:te({...e,subject:e?.subject??aD.clerk.organization?.id??aD.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new aW(e))}})}async create(e){return new aW(await aD._fetch({...await this.getBaseFapiProxyOptions(),path:"/api_keys",method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??aD.clerk.organization?.id??aD.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new aW(await aD._fetch({...await this.getBaseFapiProxyOptions(),method:"POST",path:`/api_keys/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let iy=new Map;class ik{#es=!1;load(e){let a=e?.protectConfig;if(a?.loaders&&Array.isArray(a.loaders)&&0!==a.loaders.length&&!this.#es){if(o())for(let e of(this.#es=!0,a.loaders))try{this.applyLoader(e)}catch(e){Q(`[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 Q(`[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:Q(`[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 Q(`[protect] loader target element not found: ${t}`);e.appendChild(r);return}Q(`[protect] loader target is invalid: ${t}`)}}}class iw{signInResourceSignal=tt;signInErrorSignal=tr;signInFetchSignal=ti;signInSignal=tn;signUpResourceSignal=ts;signUpErrorSignal=to;signUpFetchSignal=tl;signUpSignal=tc;waitlistResourceSignal=td;waitlistErrorSignal=tu;waitlistFetchSignal=th;waitlistSignal=tm;_waitlistInstance;__internal_effect=a9;__internal_computed=a0;constructor(){rt.on("resource:update",this.onResourceUpdated),rt.on("resource:error",this.onResourceError),rt.on("resource:fetch",this.onResourceFetch),this._waitlistInstance=new r2(null),this.waitlistResourceSignal({resource:this._waitlistInstance})}get __internal_waitlist(){return this._waitlistInstance}onResourceError=e=>{e.resource instanceof rN&&this.signInErrorSignal({error:e.error}),e.resource instanceof r$&&this.signUpErrorSignal({error:e.error}),e.resource instanceof r2&&this.waitlistErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof rN){if(iv(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof r$){if(iv(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}e.resource instanceof r2&&(this._waitlistInstance=e.resource,this.waitlistResourceSignal({resource:e.resource}))};onResourceFetch=e=>{e.resource instanceof rN&&this.signInFetchSignal({status:e.status}),e.resource instanceof r$&&this.signUpFetchSignal({status:e.status}),e.resource instanceof r2&&this.waitlistFetchSignal({status:e.status})}}function iv(e,a){return!a?.id&&e&&e.__internal_future?.hasBeenFinalized===!1}let ij="cannot_render_billing_disabled",iz="cannot_render_user_missing",i_="cannot_render_organizations_disabled",ix="cannot_render_organization_missing",iq="cannot_render_single_session_enabled",iS={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 iU{static version="6.0.0-canary.v20260109180221";static sdkMetadata={name:"@clerk/clerk-js",version:"6.0.0-canary.v20260109180221"};static _billing;static _apiKeys;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new iw;internal_last_error=null;environment;#eg;#eb="";#ef;#ey;#ek;#ew;#ev;#ej=null;#ez;#e_;#ex;#eq="loading";#eS=[];#eU=[];#eC={};#eA=null;#eI=0;#eP=g();get __internal_queryClient(){return this.#eg||Promise.resolve().then(i.bind(i,303)).then(e=>e.QueryClient).then(e=>{this.#eg||(this.#eg=new e,this.#eP.emit("queryClientStatus","ready"))}),this.#eg?{__tag:"clerk-rq-client",client:this.#eg}:void 0}__internal_getCachedResources;__internal_createPublicCredentials;__internal_getPublicCredentials;__internal_isWebAuthnSupported;__internal_isWebAuthnAutofillSupported;__internal_isWebAuthnPlatformAuthenticatorSupported;__internal_setActiveInProgress=!1;get publishableKey(){return this.#eb}get version(){return iU.version}set sdkMetadata(e){iU.sdkMetadata=e}get sdkMetadata(){return iU.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#eq}get isSatellite(){return!!ab()&&e9(this.#eC.isSatellite,new URL(window.location.href),!1)}get domain(){if(ab()){let e=function(e=""){return(e||"").replace(/^.+:\/\//,"")}(e9(this.#ef,new URL(window.location.href)));if("production"===this.#ex){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(ab()){let e=e9(this.#ey,new URL(window.location.href));return!e||eK(e)||eB(e)||ah.throwInvalidProxyUrl({url:e}),e?eB(e)?new URL(e,window.location.origin).toString():e:""}return""}get frontendApi(){let e=eh(this.publishableKey);return e?e.frontendApi:ah.throwInvalidPublishableKeyError({key:this.publishableKey})}get instanceType(){return this.#ex}get isStandardBrowser(){return this.#eC.standardBrowser||!1}get billing(){return iU._billing||(iU._billing=new ta),iU._billing}get apiKeys(){return iU._apiKeys||(iU._apiKeys=new ib),iU._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=iy.get(c);if(d)return d.signals.computedSignal();let u=(t=a2({resource:null}),r=a2({error:null}),i=a2({status:"idle"}),n=a0(()=>{let e=t().resource,a=r().error,n=i().status;return{errors:tp(a,{}),fetchStatus:n,checkout:e}}),{resourceSignal:t,errorSignal:r,fetchSignal:i,computedSignal:n}),h=new tf(u,{..."organization"===s?{orgId:e.organization?.id}:{},planId:o,planPeriod:l});return iy.set(c,{resource:h,signals:u}),u.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#eC[e]}get isSignedIn(){return this?.session?.status!=="pending"&&!!this.session}constructor(e,a){if(!(e=(e||"").trim()))return ah.throwMissingPublishableKeyError();let t=eh(e);if(!t)return ah.throwInvalidPublishableKeyError({key:e});this.#ef=a?.domain,this.#ey=a?.proxyUrl,this.environment=rn.getInstance(),this.#ex=t.instanceType,this.#eb=e,this.#e_=function(e){let a=[],t=[];async function r(e){for await(let t of["undefined"!=typeof window&&window.__internal_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.__internal_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.v20260109180221"),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&&!ig.some(e=>t.startsWith(e))&&r&&s.append("_clerk_session_id",r),ef([...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)),ez({base:i.origin,pathname:`${s}/${r}${t}`,search:n(a)},{stringify:!1})}let i="production"===e.instanceType?e.domain:"";return ez({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:c}=o;!c||"object"!=typeof c||c instanceof FormData||(o.body=function(e){if(!e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype)return e;let a={};for(let[t,r]of Object.entries(e))void 0!==r&&(a[t]=r);return a}(c)),o.url=s({...o,sessionId:e.getSessionId()}),o.headers=new Headers(o.headers),"GET"===l||c instanceof FormData||o.headers.has("content-type")||o.headers.set("content-type","application/x-www-form-urlencoded"),"application/x-www-form-urlencoded"===o.headers.get("content-type")&&(o.body=c?ef(c,{keyEncoder:ee}):c);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??(d()?4:11);n=await an(()=>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();aa.error("network error",{error:a,url:e,method:l},"fapiClient");throw Error(`${ax} 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||aa.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.#eP.emit(b,"loading"),this.#eP.prioritizedOn(b,e=>this.#eq=e),aD.clerk=this,this.#ew=new ik}getFapiClient=()=>this.#e_;load=async e=>{if(aa.info("load() start",{},"clerk"),!this.loaded){if("development"!==this.#ex||e?.unsafe_disableDevelopmentModeConsoleWarning||Q("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.#eC=this.#eO(e),this.#eC.clerkUiCtor&&(this.#ez=Promise.resolve(this.#eC.clerkUiCtor).then(e=>new e(()=>this,()=>this.environment,this.#eC,new ao))),"development"===this.#ex&&(this.#eC.routerPush||this.#eC.routerReplace)&&(!this.#eC.routerPush||!this.#eC.routerReplace)){let e=this.#eC.routerPush?"routerReplace":"routerPush";Q(`Clerk: Both \`routerPush\` and \`routerReplace\` need to be defined, but \`${e}\` is not defined. This may cause issues with navigation in your application.`)}rt.on(ra,()=>{this.#eT(this.session),this.#eE()}),this.#eC.sdkMetadata&&(iU.sdkMetadata=this.#eC.sdkMetadata),!1!==this.#eC.telemetry&&(this.telemetry=new eQ({clerkVersion:iU.version,samplingRate:1,perEventSampling:!this.#eC.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#eC.telemetry}),this.#eC.appearance&&this.telemetry.record({event:"THEME_USAGE",eventSamplingRate:1,payload:function(e){let a;if(!e||"object"!=typeof e)return{};let t=e.theme;if(!t)return{};if(Array.isArray(t))for(let e of t){let t=e0(e);if(t){a=t;break}}else a=e0(t);return{themeName:a}}(this.#eC.appearance)}));try{this.#eC.standardBrowser?await this.#eM():await this.#eR();let e=this.#eC.telemetry,a=!1!==e&&!e?.disabled,t=!!this.#eC.__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(e4)return;let{enabled:a=!1,...t}=e;a&&(e8=!0,e4=!0,ae(t))}({enabled:!0,...s?{logLevel:s}:{},...a&&this.telemetry?{telemetryCollector:this.telemetry}:{}}),this.#ew?.load(this.environment),aa.info("load() complete",{},"clerk")}catch(e){throw this.#eP.emit(b,"error"),aa.error("load() failed",{error:e},"clerk"),e}}};#eF(){let e;return!!(!this.#eC.signUpUrl&&this.#eC.signInUrl&&(e=this.#eC.signInUrl,!eb.test(e)))}signOut=async(e,a)=>{if(!this.client||0===this.client.sessions.length)return;let t="undefined"!=typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:e3,r="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e3,i=e&&"object"==typeof e?e:a||{},n=i?.redirectUrl||this.buildAfterSignOutUrl();aa.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=al(this.#eC.standardBrowser);rt.emit(t7,null),this.#eD(),await e.track(async()=>{s?await s():await this.navigate(n)}),e.isUnloading()||(this.#eT(),this.#eE(),await r())};if(await t(),!i.sessionId||1===this.client.signedInSessions.length){this.#eC.experimental?.persistClient??!0?await this.client.removeSessions():await this.client.destroy(),await o(),aa.info("signOut() complete",{redirectUrl:e_(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(),aa.info("signOut() complete",{redirectUrl:e_(n)},"clerk"))};openGoogleOneTap=e=>{this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("googleOneTap",e||{})),this.telemetry?.record(e2("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(W(this,this.environment)){if("development"===this.#ex)throw new I(eN.cannotOpenSignInOrSignUp,{code:iq});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("signIn",e||{}));let a={withSignUp:e?.withSignUp??this.#eF()};this.telemetry?.record(e2("SignIn",e,a))};closeSignIn=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(L(this,this.environment)){if("development"===this.#ex)throw new I(eN.cannotRenderAnyBillingComponent("Checkout"),{code:ij});return}if(!this.user){if("development"===this.#ex)throw new I(eN.cannotOpenCheckout,{code:iz});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openDrawer("checkout",e||{}))};__internal_closeCheckout=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("checkout"))};__internal_openPlanDetails=e=>{if(L(this,this.environment)){if("development"===this.#ex)throw new I(eN.cannotRenderAnyBillingComponent("PlanDetails"),{code:ij});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openDrawer("planDetails",e||{})),this.telemetry?.record(e2("PlanDetails",e))};__internal_closePlanDetails=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("planDetails"))};__internal_openSubscriptionDetails=e=>{this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openDrawer("subscriptionDetails",e||{}))};__internal_closeSubscriptionDetails=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("subscriptionDetails"))};__internal_openReverification=e=>{if(!this.user){if("development"===this.#ex)throw new I(eN.cannotOpenUserProfile,{code:iz});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("userVerification",e||{})),this.telemetry?.record(e2("UserVerification",e))};__internal_closeReverification=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userVerification"))};__internal_attemptToEnableEnvironmentSetting=e=>{let{for:a,caller:t}=e;if(this.user||"development"!==this.#ex||Q(`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.#ex&&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.#ez),this.#ez.then(e=>e.ensureMounted({preloadHint:"EnableOrganizationsPrompt"})).then(a=>a.openModal("enableOrganizationsPrompt",e||{})),this.telemetry?.record(e1("EnableOrganizationsPrompt",e))};__internal_closeEnableOrganizationsPrompt=()=>{this.assertComponentsReady(this.#ez),this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("enableOrganizationsPrompt"))};__internal_openBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(e=>e.openModal("blankCaptcha",{})));__internal_closeBlankCaptchaModal=()=>(this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(e=>e.closeModal("blankCaptcha")));__internal_loadStripeJs=async()=>(aq("Stripe"),{loadStripe:()=>Promise.resolve(null)});openSignUp=e=>{if(W(this,this.environment)){if("development"===this.#ex)throw new I(eN.cannotOpenSignInOrSignUp,{code:iq});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("signUp",e||{})),this.telemetry?.record(e2("SignUp",e))};closeSignUp=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signUp"))};openUserProfile=e=>{if(!this.user){if("development"===this.#ex)throw new I(eN.cannotOpenUserProfile,{code:iz});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("userProfile",e||{}));let a=(e?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(e2("UserProfile",e,a))};closeUserProfile=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userProfile"))};openOrganizationProfile=e=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new I(eN.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:i_})}});if(a){if(!this.organization){if("development"===this.#ex)throw new I(eN.cannotRenderComponentWhenOrgDoesNotExist,{code:ix});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("organizationProfile",e||{})),this.telemetry?.record(e2("OrganizationProfile",e))}};closeOrganizationProfile=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("organizationProfile"))};openCreateOrganization=e=>{let{isEnabled:a}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new I(eN.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:i_})}});a&&(this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("createOrganization",e||{})),this.telemetry?.record(e2("CreateOrganization",e)))};closeCreateOrganization=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("createOrganization"))};openWaitlist=e=>{this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("waitlist",e||{})),this.telemetry?.record(e2("Waitlist",e))};closeWaitlist=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("waitlist"))};mountSignIn=(e,a)=>{this.assertComponentsReady(this.#ez);let t="SignIn";this.#ez.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"signIn",node:e,props:a}));let r={withSignUp:a?.withSignUp??this.#eF()};this.telemetry?.record(e1(t,a,r))};unmountSignIn=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserAvatar=(e,a)=>{this.assertComponentsReady(this.#ez);let t="UserAvatar";this.#ez.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"userAvatar",node:e,props:a})),this.telemetry?.record(e1(t,a))};unmountUserAvatar=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountSignUp=(e,a)=>{this.assertComponentsReady(this.#ez);let t="SignUp";this.#ez.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"signUp",node:e,props:a})),this.telemetry?.record(e1(t,a))};unmountSignUp=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserProfile=(e,a)=>{if(!this.user){if("development"===this.#ex)throw new I(eN.cannotRenderComponentWhenUserDoesNotExist,{code:iz});return}this.assertComponentsReady(this.#ez);let t="UserProfile";this.#ez.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(e1(t,a,r))};unmountUserProfile=e=>{this.#ez?.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 I(eN.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:i_})}});if(!t)return;let r=!!this.user;if(!this.organization&&r){if("development"===this.#ex)throw new I(eN.cannotRenderComponentWhenOrgDoesNotExist,{code:ix});return}this.assertComponentsReady(this.#ez);let i="OrganizationProfile";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:i,appearanceKey:"userProfile",node:e,props:a})),this.telemetry?.record(e1(i,a))};unmountOrganizationProfile=e=>{this.#ez?.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 I(eN.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:i_})}});if(!t)return;this.assertComponentsReady(this.#ez);let r="CreateOrganization";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"createOrganization",node:e,props:a})),this.telemetry?.record(e1(r,a))};unmountCreateOrganization=e=>{this.#ez?.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 I(eN.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:i_})}});if(!t)return;this.assertComponentsReady(this.#ez);let r="OrganizationSwitcher";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"organizationSwitcher",node:e,props:a})),this.telemetry?.record(e1(r,{...a,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationSwitcher=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};__experimental_prefetchOrganizationSwitcher=()=>{this.assertComponentsReady(this.#ez),this.#ez.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 I(eN.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:i_})}});if(!t)return;this.assertComponentsReady(this.#ez);let r="OrganizationList";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"organizationList",node:e,props:a})),this.telemetry?.record(e1(r,{...a,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationList=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountUserButton=(e,a)=>{this.assertComponentsReady(this.#ez);let t="UserButton";this.#ez.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(e1(t,a,r))};unmountUserButton=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountWaitlist=(e,a)=>{this.assertComponentsReady(this.#ez);let t="Waitlist";this.#ez.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"waitlist",node:e,props:a})),this.telemetry?.record(e1(t,a))};unmountWaitlist=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountPricingTable=(e,a)=>{if(L(this,this.environment)){if("development"===this.#ex)throw new I(eN.cannotRenderAnyBillingComponent("PricingTable"),{code:ij});return}this.assertComponentsReady(this.#ez);let t="PricingTable";this.#ez.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:t,appearanceKey:"pricingTable",node:e,props:a})),this.telemetry?.record(e1(t,a))};unmountPricingTable=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};__internal_mountOAuthConsent=(e,a)=>{this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:"OAuthConsent",appearanceKey:"__internal_oauthConsent",node:e,props:a}))};__internal_unmountOAuthConsent=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountAPIKeys=(e,a)=>{let t;if(Q("Clerk: <APIKeys /> component is in early access and not yet recommended for production use."),$(this,t=this.environment)&&K(this,t)){if("development"===this.#ex)throw new I(eN.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&K(this,this.environment)){if("development"===this.#ex)throw new I(eN.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if($(this,this.environment)){if("development"===this.#ex)throw new I(eN.cannotRenderAPIKeysComponentForUserWhenDisabled,{code:"cannot_render_api_keys_user_disabled"});return}this.assertComponentsReady(this.#ez);let r="APIKeys";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"apiKeys",node:e,props:a})),this.telemetry?.record(e1(r,a))};unmountAPIKeys=e=>{this.#ez?.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 I(eN.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:i_})}});if(!t)return;this.assertComponentsReady(this.#ez);let r="TaskChooseOrganization";this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:r,appearanceKey:"taskChooseOrganization",node:e,props:a})),this.telemetry?.record(e1(r,a))};unmountTaskChooseOrganization=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountTaskResetPassword=(e,a)=>{this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(t=>t.mountComponent({name:"TaskResetPassword",appearanceKey:"taskResetPassword",node:e,props:a})),this.telemetry?.record(e1("TaskResetPassword",a))};unmountTaskResetPassword=e=>{this.#ez?.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,aa.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 aa.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 aa.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.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:e3,l="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e3,c=void 0===i?this.session:i;c?.status==="pending"&&(n={...this.#eC,...e},s=["taskUrls","navigate"],Object.keys(n).some(e=>s.includes(e))||Q('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 d=void 0!==a;if(c&&d){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),(ab()&&globalThis.document.hasFocus()||!this.#eC.standardBrowser)&&(await this.#eN(c),c=this.#eW(c?.id)),await c?.getToken()||(u()||aa.warn("Token is null when setting active session (offline)",{sessionId:c?.id},"clerk"),rt.emit(t6,{token:null}));let h=al(this.#eC.standardBrowser),m=c?.status==="pending"&&c?.currentTask&&this.#eC.taskUrls?.[c?.currentTask.key];if((t||m||r)&&await h.track(async()=>{if(this.client){if(c?.status!=="pending"&&this.#eD(),m){let e=t?ez({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.#eT(c),this.#eE(),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:r9((r=t).client,e.client),session:r9(r.session,e.session),user:r9(r.user,e.user),organization:r9(r.organization,e.organization)}})},this.#eS.push(e),this.client&&e({client:this.client,session:this.session,user:this.user,organization:this.organization}),()=>{this.#eS=this.#eS.filter(a=>a!==e)}};on=(...e)=>{this.#eP.on(...e)};off=(...e)=>{this.#eP.off(...e)};__internal_addNavigationListener=e=>(this.#eU.push(e),()=>{this.#eU=this.#eU.filter(a=>a!==e)});navigate=async(e,a)=>{if(!e||!ab())return;setTimeout(()=>{this.#eL()},0);let t=new URL(e,window.location.href);this.#e$.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.#eC.routerReplace?this.#eC.routerReplace:this.#eC.routerPush;if(aa.info(`Clerk is navigating to: ${t}`),this.#eC.routerDebug&&console.log(`Clerk is navigating to: ${t}`),"null"!==t.origin&&t.origin!==window.location.origin||!r)return void e$(t);let i={...a?.metadata?{__internal_metadata:a?.metadata}:{},windowNavigate:e$};return await r(e_(t),i)};buildUrlWithAuth(e){if("production"===this.#ex)return e;let a=new URL(e,window.location.origin);return a.origin!==window.location.origin&&this.#ek?this.#ek.decorateUrlWithDevBrowserToken(a).href:a.href}buildSignInUrl(e){return this.#eK("signInUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildSignUpUrl(e){return this.#eK("signUpUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildUserProfileUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.userProfileUrl):""}buildHomeUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.homeUrl):""}buildAfterSignInUrl({params:e}={}){return this.buildUrlWithAuth(new eA(this.#eC,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eA(this.#eC,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#eC.afterSignOutUrl?this.buildUrlWithAuth(this.#eC.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#eC.newSubscriptionRedirectUrl?this.#eC.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?ez({base:this.#eC.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#eC.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#eC.afterMultiSessionSingleSignOutUrl):this.#eC.signInUrl?this.buildUrlWithAuth(ez({base:this.#eC.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.#eC.taskUrls?.[a.key];return t||ez({base:this.buildSignInUrl(e),hashPath:eR(a)},{stringify:!0})}#eB=async()=>{if(!ab())return;let e=new URLSearchParams({[B]:"true"}),a=eO(V);a&&eK(a)||function(){throw Error(`${ax} Invalid redirect_url. A valid http or https url should be used for the redirection.`)}();let t=ez({base:eO(V),searchParams:e},{stringify:!0});return this.navigate(this.buildUrlWithAuth(t))};redirectWithAuth=async e=>{if(ab())return this.navigate(this.buildUrlWithAuth(e))};redirectToSignIn=async e=>{if(ab())return this.navigate(this.buildSignInUrl(e))};redirectToSignUp=async e=>{if(ab())return this.navigate(this.buildSignUpUrl(e))};redirectToUserProfile=async()=>{if(ab())return this.navigate(this.buildUserProfileUrl())};redirectToCreateOrganization=async()=>{if(ab())return this.navigate(this.buildCreateOrganizationUrl())};redirectToOrganizationProfile=async()=>{if(ab())return this.navigate(this.buildOrganizationProfileUrl())};redirectToAfterSignIn=async()=>{if(ab())return this.navigate(this.buildAfterSignInUrl())};redirectToAfterSignUp=async()=>{if(ab())return this.navigate(this.buildAfterSignUpUrl())};redirectToAfterSignOut=async()=>{if(ab())return this.navigate(this.buildAfterSignOutUrl())};redirectToWaitlist=async()=>{if(ab())return this.navigate(this.buildWaitlistUrl())};redirectToTasks=async e=>{if(ab())return this.navigate(this.buildTasksUrl(e))};handleEmailLinkVerification=async(e,a)=>{if(!this.client)return;let t=eO("__clerk_status");if("expired"===t)throw new U(A.Expired);if("client_mismatch"===t)throw new U(A.ClientMismatch);if("verified"!==t)throw new U(A.Failed);let r=eO("__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):e3;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||ez({base:i.signInUrl,hashPath:"/factor-one"},{stringify:!0})),m=c(e.secondFactorUrl||ez({base:i.signInUrl,hashPath:"/factor-two"},{stringify:!0})),p=c(e.resetPasswordUrl||ez({base:i.signInUrl,hashPath:"/reset-password"},{stringify:!0})),g=new eA(this.#eC,e),b=c(e.continueSignUpUrl||ez({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=eE();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||ez({base:i.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),verifyPhonePath:e.verifyPhoneNumberUrl||ez({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 eF(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:aU("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:aU("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 tR.getOrCreateInstance().fetch();if(this.updateClient(a),this.session)return;return e.broadcast&&rt.emit(t7,null),this.setActive({session:null})}catch(e){if(_(e)&&[403,500].includes(e.status))return this.setActive({session:null});throw e}};authenticateWithGoogleOneTap=async e=>(aq("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"})};authenticateWithSolana=async e=>{await this.authenticateWithWeb3({...e,strategy:"web3_solana_signature"})};authenticateWithWeb3=async({redirectUrl:e,signUpContinueUrl:a,customNavigate:t,unsafeMetadata:r,strategy:i,legalAccepted:n,secondFactorUrl:s,walletName:o})=>{let l,c;if(!this.client||!this.environment)return;let{displayConfig:d}=this.environment,u=i.replace("web3_","").replace("_signature",""),h=await aw().getWeb3Identifier({provider:u,walletName:o});switch(u){case"metamask":l=aw().generateSignatureWithMetamask;break;case"base":l=aw().generateSignatureWithBase;break;case"coinbase_wallet":l=aw().generateSignatureWithCoinbaseWallet;break;case"solana":if(!o)throw new I("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});l=e=>aw().generateSignatureWithSolana({...e,walletName:o});break;default:l=aw().generateSignatureWithOKXWallet}let m=e=>()=>t&&"function"==typeof t?t(e):this.navigate(e),p=m(s||ez({base:d.signInUrl,hashPath:"/factor-two"},{stringify:!0})),g=m(a||ez({base:d.signUpUrl,hashPath:"/continue"},{stringify:!0}));try{c=await this.client.signIn.authenticateWithWeb3({identifier:h,generateSignature:l,strategy:i,walletName:o})}catch(e){if(au(e,"form_identifier_not_found"))c=await this.client.signUp.authenticateWithWeb3({identifier:h,generateSignature:l,unsafeMetadata:r,strategy:i,legalAccepted:n,walletName:o}),a&&"missing_requirements"===c.status&&"verified"===c.verifications.web3Wallet.status&&await g();else throw e}let b=async({session:e,redirectUrl:a})=>{e.currentTask?await eF(e,{baseUrl:d.signInUrl,navigate:this.navigate}):await this.navigate(a)};switch(c.status){case"needs_second_factor":await p();break;case"complete":c.createdSessionId&&await this.setActive({session:c.createdSessionId,navigate:async({session:a})=>{await b({session:a,redirectUrl:e??this.buildAfterSignInUrl()})}});break;default:return}};createOrganization=async({name:e,slug:a})=>rp.create({name:e,slug:a});getOrganization=async e=>rp.get(e);joinWaitlist=async({emailAddress:e})=>r2.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.#eC.selectInitialSession?this.#eC.selectInitialSession(e):this.#eJ(e);this.#eT(a)}if(this.client=e,this.session){let e=this.#eW(this.session.id);"active"===this.session.status&&e?.status==="pending"&&("undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e3)(),this.#eT(e),this.session?.lastActiveToken||u()||aa.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),rt.emit(t6,{token:this.session?.lastActiveToken})}this.#eE()};get __internal_environment(){return this.environment}__internal_setEnvironment=async e=>{this.environment=new rn(e)};__internal_onBeforeRequest=e=>{this.#e_.onBeforeRequest(e)};__internal_onAfterResponse=e=>{this.#e_.onAfterResponse(e)};__internal_updateProps=e=>{let a={...e,options:this.#eO({...this.#eC,...e.options})};return this.#ez?.then(e=>e.ensureMounted()).then(e=>e.updateProps(a))};__internal_navigateWithError(e,a){return this.__internal_last_error=a,this.navigate(e)}#eV=()=>{let e=new URLSearchParams({[V]:window.location.href});return ez({base:this.#eC.signInUrl,searchParams:e},{stringify:!0})};#eG=()=>{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()||""};#eH=()=>"true"!==eO(B)&&!!this.isSatellite&&!!this.#ek?.isSignedOut();#eQ=()=>"production"!==this.#ex&&!this.isSatellite&&!!eO(V);#eY=async()=>{"development"===this.instanceType?await this.navigate(this.#eV()):"production"===this.instanceType&&await this.navigate(this.#eG())};#eZ=(e,a)=>{let t;try{t=new URL(e)}catch{throw Error(`${ax} The signInUrl needs to have a absolute url format.`)}t.origin===a&&function(){throw Error(`${ax} The signInUrl needs to be on a different origin than your satellite application.`)}()};#eX=()=>{this.isSatellite&&("development"!==this.#ex||this.#eC.signInUrl||function(){throw Error(`${ax} Missing signInUrl. A satellite application needs to specify the signInUrl for development instances.`)}(),this.proxyUrl||this.domain||function(){throw Error(`${ax} Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl.`)}(),this.#eC.signInUrl&&this.#eZ(this.#eC.signInUrl,window.location.origin))};#eM=async()=>{if(this.#ek=await im.create(this,this.#e_,this.#ex,this.#eP),this.#eX(),this.#eH())return void await this.#eY();if(this.#eQ())return void await this.#eB();this.#eA=(()=>{if(!o())return{onPageFocus:e3};let e=[];return window.addEventListener("focus",()=>{"visible"===document.visibilityState&&e.forEach(e=>e())}),{onPageFocus:a=>{e.push(a)}}})(),"undefined"!=typeof BroadcastChannel&&(this.#ej=new BroadcastChannel("clerk")),this.#e1();let e=function(e=window.location.hostname){if(!e)return!1;let a=ev.get(e);void 0===a&&(a=es.some(a=>e.startsWith("accounts.")&&e.endsWith(a))||eo.some(a=>e.endsWith(a)&&!e.endsWith(".clerk"+a)),ev.set(e,a));return a}(window?.location.hostname),a="development"===this.#ex&&!e,t=0,r=0;for(;r<2;){r++;try{var i;let e=rn.getInstance().fetch({touch:a}).then(e=>this.updateEnvironment(e)).catch(()=>{++t;let e=a_.getItem(av,null);e&&this.updateEnvironment(new rn(e))}),r=async()=>tR.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(async e=>{if(E(e))throw e;++t;let a=this.#ek?.getSessionCookie(),r=function(e){let a;try{a=new rJ({jwt:e||"",object:"token",id:void 0})}catch{a=null}if(tR.clearInstance(),!a?.jwt)return tR.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}=rC(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 tR.getOrCreateInstance(c)}(a);return this.updateClient(r),this.#ek?.stopPollingForToken(),await this.session?.getToken({skipCache:!0}).catch(()=>null).finally(()=>{this.#ek?.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(au(e,"requires_captcha"))await r();else throw e}if(this.#ek?.setClientUatCookieForDevelopmentInstances(),await this.#e2())return;break}catch(e){if(au(e,"dev_browser_unauthenticated"))await this.#ek.handleUnauthenticatedDevBrowser();else if(!u())return void console.warn(e);else throw e}r>=2&&function(){throw Error(`${ax} Something went wrong initializing Clerk.`)}()}this.#ev=new ip(this),this.#ev.start(),this.#e0(),this.#e9(),this.#e3(),this.#eP.emit(b,t>0?"degraded":"ready")};shouldFallbackToCachedResources=()=>!!this.__internal_getCachedResources;#eR=async()=>{let e,a,t=this.shouldFallbackToCachedResources()?1:void 0,r=0;try{[e,a]=await Promise.all([rn.getInstance().fetch({touch:!1,fetchMaxTries:t}),tR.getOrCreateInstance().fetch({fetchMaxTries:t})])}catch(t){if(P(t)&&"network_error"===t.code&&this.shouldFallbackToCachedResources()){let t=await this.__internal_getCachedResources?.();e=new rn(t?.environment),tR.clearInstance(),a=tR.getOrCreateInstance(t?.client),++r}else throw t}this.updateClient(a),this.updateEnvironment(e),this.#eP.emit(b,r>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,a]=await Promise.all([rn.getInstance().fetch({touch:!1,fetchMaxTries:1}),tR.getOrCreateInstance().fetch({fetchMaxTries:1})]);this.updateClient(a),this.updateEnvironment(e),this.#eE()};#eJ=e=>{if(e.lastActiveSessionId){let a=e.signedInSessions.find(a=>a.id===e.lastActiveSessionId);if(a)return a}return e.signedInSessions[0]||null};#e1=()=>{o()&&(this.#eA?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#eI>Date.now())&&(this.#eI=Date.now()+5e3,this.#eC.touchSession&&this.#eN(this.session))}),this.#ej?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),rt.on(t7,()=>{this.#ej?.postMessage({type:"signout"})}),rt.on(re,()=>{a_.setItem(av,this.environment?.__internal_toSnapshot(),864e5)}))};#eN=async e=>{if(!e)return Promise.resolve();await e.touch().catch(e=>{E(e)&&this.handleUnauthenticated()})};#eE=()=>{if(this.client)for(let e of this.#eS)e({client:this.client,session:this.session,user:this.user,organization:this.organization})};#eL=()=>{for(let e of this.#eU)e()};#eD=()=>{this.session=void 0,this.organization=void 0,this.user=void 0,this.#eE()};#e8=()=>(this.session?.user.organizationMemberships||[]).map(e=>e.organization).find(e=>e.id===this.session?.lastActiveOrganizationId)||null;#eT=e=>{this.session=e||null,this.organization=this.#e8(),this.user=this.session?this.session.user:null};#eW=e=>this.client?.signedInSessions.find(a=>a.id===e)||null;#e9=()=>{this.addListener(({session:e})=>{e?.actor&&this.#ez?.then(e=>e.ensureMounted()).then(e=>e.mountImpersonationFab())})};#e3=()=>{this.#eC.__internal_keyless_claimKeylessApplicationUrl&&this.#ez?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#eC.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#eC.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#eC.__internal_keyless_dismissPrompt}})})};#eK=(e,a,t)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let r=this.#eC[e]||this.environment.displayConfig[e];this.#eF()&&(r=this.#eC.signInUrl);let i=new eA(this.#eC,a).toSearchParams(),n=new URLSearchParams(t||{}),s=ez({base:r,hashPath:this.#eF()&&"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")}#e2=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,ey)).pathname,r=eU.includes(t)||eC.includes(t),e===a.host&&r);if(s||!o)return!1;let l=this.session,c=this.#eC.signInUrl||this.environment?.displayConfig.signInUrl,d=c&&window.location.href.startsWith(c),u=this.#eC.signUpUrl||this.environment?.displayConfig.signUpUrl,h=u&&window.location.href.startsWith(u);return i=new URL(n,ey),(!eU.includes(i.pathname)||!!l||!d&&!h)&&(await this.navigate(this.buildUrlWithAuth(n)),!0)};#eO=e=>({...iS,...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://${ej(a)}`),r.push(`https://*.${ej(a)}`),"development"===t&&r.push(`https://${a}`),r}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)});#e0=()=>{try{eT(B),eT(eI),eT(J),eT("__clerk_handshake"),eT("__clerk_handshake_nonce"),eT("__clerk_help")}catch{}};get #e$(){let e=eL;return this.#eC.allowedRedirectProtocols&&(e=e.concat(this.#eC.allowedRedirectProtocols)),e}}})();var s=n.c2,o=n.LR,l=n.cR,c=n.NZ,d=n.Ys,u=n.kl,h=n.$R,m=n.Cm,p=n.hl,g=n.ux,b=n.si,f=n._d;export{s as Clerk,o as ClerkAPIResponseError,l as ClerkRuntimeError,c as EmailLinkError,d as EmailLinkErrorCode,u as EmailLinkErrorCodeStatus,h as isClerkAPIResponseError,m as isClerkRuntimeError,p as isEmailLinkError,g as isKnownError,b as isMetamaskError,f as isUserLockedError};
|