@clerk/clerk-js 6.0.0-snapshot.v20251218165926 → 6.0.0-snapshot.v20251218183643

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.
Files changed (64) hide show
  1. package/dist/clerk.browser.js +4 -4
  2. package/dist/clerk.chips.browser.js +4 -4
  3. package/dist/clerk.headless.browser.js +3 -3
  4. package/dist/clerk.headless.js +3 -3
  5. package/dist/clerk.js +5 -5
  6. package/dist/clerk.legacy.browser.js +1 -1
  7. package/dist/clerk.mjs +5 -5
  8. package/dist/clerk.no-rhc.js +1 -1
  9. package/dist/clerk.no-rhc.mjs +1 -1
  10. package/package.json +3 -3
  11. /package/dist/{197_clerk.browser_a90c48_6.0.0-snapshot.v20251218165926.js → 197_clerk.browser_834334_6.0.0-snapshot.v20251218183643.js} +0 -0
  12. /package/dist/{197_clerk.chips.browser_c16224_6.0.0-snapshot.v20251218165926.js → 197_clerk.chips.browser_5e7a74_6.0.0-snapshot.v20251218183643.js} +0 -0
  13. /package/dist/{197_clerk.headless.browser_1b17ca_6.0.0-snapshot.v20251218165926.js → 197_clerk.headless.browser_45a74c_6.0.0-snapshot.v20251218183643.js} +0 -0
  14. /package/dist/{197_clerk.headless_8d878a_6.0.0-snapshot.v20251218165926.js → 197_clerk.headless_38bd55_6.0.0-snapshot.v20251218183643.js} +0 -0
  15. /package/dist/{197_clerk.legacy.browser_ff5b6e_6.0.0-snapshot.v20251218165926.js → 197_clerk.legacy.browser_6e74bb_6.0.0-snapshot.v20251218183643.js} +0 -0
  16. /package/dist/{308_clerk.headless_8d878a_6.0.0-snapshot.v20251218165926.js → 308_clerk.headless_38bd55_6.0.0-snapshot.v20251218183643.js} +0 -0
  17. /package/dist/{507_clerk.browser_a90c48_6.0.0-snapshot.v20251218165926.js → 507_clerk.browser_834334_6.0.0-snapshot.v20251218183643.js} +0 -0
  18. /package/dist/{507_clerk.chips.browser_c16224_6.0.0-snapshot.v20251218165926.js → 507_clerk.chips.browser_5e7a74_6.0.0-snapshot.v20251218183643.js} +0 -0
  19. /package/dist/{507_clerk.headless.browser_1b17ca_6.0.0-snapshot.v20251218165926.js → 507_clerk.headless.browser_45a74c_6.0.0-snapshot.v20251218183643.js} +0 -0
  20. /package/dist/{507_clerk.headless_8d878a_6.0.0-snapshot.v20251218165926.js → 507_clerk.headless_38bd55_6.0.0-snapshot.v20251218183643.js} +0 -0
  21. /package/dist/{507_clerk.legacy.browser_ff5b6e_6.0.0-snapshot.v20251218165926.js → 507_clerk.legacy.browser_6e74bb_6.0.0-snapshot.v20251218183643.js} +0 -0
  22. /package/dist/{521_clerk.headless_8d878a_6.0.0-snapshot.v20251218165926.js → 521_clerk.headless_38bd55_6.0.0-snapshot.v20251218183643.js} +0 -0
  23. /package/dist/{527_clerk.browser_a90c48_6.0.0-snapshot.v20251218165926.js → 527_clerk.browser_834334_6.0.0-snapshot.v20251218183643.js} +0 -0
  24. /package/dist/{527_clerk.chips.browser_c16224_6.0.0-snapshot.v20251218165926.js → 527_clerk.chips.browser_5e7a74_6.0.0-snapshot.v20251218183643.js} +0 -0
  25. /package/dist/{527_clerk.headless.browser_1b17ca_6.0.0-snapshot.v20251218165926.js → 527_clerk.headless.browser_45a74c_6.0.0-snapshot.v20251218183643.js} +0 -0
  26. /package/dist/{527_clerk.legacy.browser_ff5b6e_6.0.0-snapshot.v20251218165926.js → 527_clerk.legacy.browser_6e74bb_6.0.0-snapshot.v20251218183643.js} +0 -0
  27. /package/dist/{537_clerk.headless_8d878a_6.0.0-snapshot.v20251218165926.js → 537_clerk.headless_38bd55_6.0.0-snapshot.v20251218183643.js} +0 -0
  28. /package/dist/{604_clerk.headless_8d878a_6.0.0-snapshot.v20251218165926.js → 604_clerk.headless_38bd55_6.0.0-snapshot.v20251218183643.js} +0 -0
  29. /package/dist/{783_clerk.headless_8d878a_6.0.0-snapshot.v20251218165926.js → 783_clerk.headless_38bd55_6.0.0-snapshot.v20251218183643.js} +0 -0
  30. /package/dist/{896_clerk.headless_8d878a_6.0.0-snapshot.v20251218165926.js → 896_clerk.headless_38bd55_6.0.0-snapshot.v20251218183643.js} +0 -0
  31. /package/dist/{973_clerk.headless_8d878a_6.0.0-snapshot.v20251218165926.js → 973_clerk.headless_38bd55_6.0.0-snapshot.v20251218183643.js} +0 -0
  32. /package/dist/{base-account-sdk_clerk.browser_a90c48_6.0.0-snapshot.v20251218165926.js → base-account-sdk_clerk.browser_834334_6.0.0-snapshot.v20251218183643.js} +0 -0
  33. /package/dist/{base-account-sdk_clerk.chips.browser_c16224_6.0.0-snapshot.v20251218165926.js → base-account-sdk_clerk.chips.browser_5e7a74_6.0.0-snapshot.v20251218183643.js} +0 -0
  34. /package/dist/{base-account-sdk_clerk.headless.browser_1b17ca_6.0.0-snapshot.v20251218165926.js → base-account-sdk_clerk.headless.browser_45a74c_6.0.0-snapshot.v20251218183643.js} +0 -0
  35. /package/dist/{base-account-sdk_clerk.legacy.browser_ff5b6e_6.0.0-snapshot.v20251218165926.js → base-account-sdk_clerk.legacy.browser_6e74bb_6.0.0-snapshot.v20251218183643.js} +0 -0
  36. /package/dist/{coinbase-wallet-sdk_clerk.browser_a90c48_6.0.0-snapshot.v20251218165926.js → coinbase-wallet-sdk_clerk.browser_834334_6.0.0-snapshot.v20251218183643.js} +0 -0
  37. /package/dist/{coinbase-wallet-sdk_clerk.chips.browser_c16224_6.0.0-snapshot.v20251218165926.js → coinbase-wallet-sdk_clerk.chips.browser_5e7a74_6.0.0-snapshot.v20251218183643.js} +0 -0
  38. /package/dist/{coinbase-wallet-sdk_clerk.headless.browser_1b17ca_6.0.0-snapshot.v20251218165926.js → coinbase-wallet-sdk_clerk.headless.browser_45a74c_6.0.0-snapshot.v20251218183643.js} +0 -0
  39. /package/dist/{coinbase-wallet-sdk_clerk.legacy.browser_ff5b6e_6.0.0-snapshot.v20251218165926.js → coinbase-wallet-sdk_clerk.legacy.browser_6e74bb_6.0.0-snapshot.v20251218183643.js} +0 -0
  40. /package/dist/{cookieSuffix_clerk.browser_a90c48_6.0.0-snapshot.v20251218165926.js → cookieSuffix_clerk.browser_834334_6.0.0-snapshot.v20251218183643.js} +0 -0
  41. /package/dist/{cookieSuffix_clerk.chips.browser_c16224_6.0.0-snapshot.v20251218165926.js → cookieSuffix_clerk.chips.browser_5e7a74_6.0.0-snapshot.v20251218183643.js} +0 -0
  42. /package/dist/{cookieSuffix_clerk.headless.browser_1b17ca_6.0.0-snapshot.v20251218165926.js → cookieSuffix_clerk.headless.browser_45a74c_6.0.0-snapshot.v20251218183643.js} +0 -0
  43. /package/dist/{cookieSuffix_clerk.headless_8d878a_6.0.0-snapshot.v20251218165926.js → cookieSuffix_clerk.headless_38bd55_6.0.0-snapshot.v20251218183643.js} +0 -0
  44. /package/dist/{cookieSuffix_clerk.legacy.browser_ff5b6e_6.0.0-snapshot.v20251218165926.js → cookieSuffix_clerk.legacy.browser_6e74bb_6.0.0-snapshot.v20251218183643.js} +0 -0
  45. /package/dist/{query-core-vendors_clerk.browser_a90c48_6.0.0-snapshot.v20251218165926.js → query-core-vendors_clerk.browser_834334_6.0.0-snapshot.v20251218183643.js} +0 -0
  46. /package/dist/{query-core-vendors_clerk.chips.browser_c16224_6.0.0-snapshot.v20251218165926.js → query-core-vendors_clerk.chips.browser_5e7a74_6.0.0-snapshot.v20251218183643.js} +0 -0
  47. /package/dist/{query-core-vendors_clerk.headless.browser_1b17ca_6.0.0-snapshot.v20251218165926.js → query-core-vendors_clerk.headless.browser_45a74c_6.0.0-snapshot.v20251218183643.js} +0 -0
  48. /package/dist/{query-core-vendors_clerk.legacy.browser_ff5b6e_6.0.0-snapshot.v20251218165926.js → query-core-vendors_clerk.legacy.browser_6e74bb_6.0.0-snapshot.v20251218183643.js} +0 -0
  49. /package/dist/{stripe-vendors_clerk.browser_a90c48_6.0.0-snapshot.v20251218165926.js → stripe-vendors_clerk.browser_834334_6.0.0-snapshot.v20251218183643.js} +0 -0
  50. /package/dist/{stripe-vendors_clerk.chips.browser_c16224_6.0.0-snapshot.v20251218165926.js → stripe-vendors_clerk.chips.browser_5e7a74_6.0.0-snapshot.v20251218183643.js} +0 -0
  51. /package/dist/{stripe-vendors_clerk.headless.browser_1b17ca_6.0.0-snapshot.v20251218165926.js → stripe-vendors_clerk.headless.browser_45a74c_6.0.0-snapshot.v20251218183643.js} +0 -0
  52. /package/dist/{stripe-vendors_clerk.legacy.browser_ff5b6e_6.0.0-snapshot.v20251218165926.js → stripe-vendors_clerk.legacy.browser_6e74bb_6.0.0-snapshot.v20251218183643.js} +0 -0
  53. /package/dist/{vendors_clerk.browser_a90c48_6.0.0-snapshot.v20251218165926.js → vendors_clerk.browser_834334_6.0.0-snapshot.v20251218183643.js} +0 -0
  54. /package/dist/{vendors_clerk.chips.browser_c16224_6.0.0-snapshot.v20251218165926.js → vendors_clerk.chips.browser_5e7a74_6.0.0-snapshot.v20251218183643.js} +0 -0
  55. /package/dist/{vendors_clerk.headless.browser_1b17ca_6.0.0-snapshot.v20251218165926.js → vendors_clerk.headless.browser_45a74c_6.0.0-snapshot.v20251218183643.js} +0 -0
  56. /package/dist/{vendors_clerk.legacy.browser_ff5b6e_6.0.0-snapshot.v20251218165926.js → vendors_clerk.legacy.browser_6e74bb_6.0.0-snapshot.v20251218183643.js} +0 -0
  57. /package/dist/{zxcvbn-common_clerk.browser_a90c48_6.0.0-snapshot.v20251218165926.js → zxcvbn-common_clerk.browser_834334_6.0.0-snapshot.v20251218183643.js} +0 -0
  58. /package/dist/{zxcvbn-common_clerk.chips.browser_c16224_6.0.0-snapshot.v20251218165926.js → zxcvbn-common_clerk.chips.browser_5e7a74_6.0.0-snapshot.v20251218183643.js} +0 -0
  59. /package/dist/{zxcvbn-common_clerk.headless.browser_1b17ca_6.0.0-snapshot.v20251218165926.js → zxcvbn-common_clerk.headless.browser_45a74c_6.0.0-snapshot.v20251218183643.js} +0 -0
  60. /package/dist/{zxcvbn-common_clerk.legacy.browser_ff5b6e_6.0.0-snapshot.v20251218165926.js → zxcvbn-common_clerk.legacy.browser_6e74bb_6.0.0-snapshot.v20251218183643.js} +0 -0
  61. /package/dist/{zxcvbn-ts-core_clerk.browser_a90c48_6.0.0-snapshot.v20251218165926.js → zxcvbn-ts-core_clerk.browser_834334_6.0.0-snapshot.v20251218183643.js} +0 -0
  62. /package/dist/{zxcvbn-ts-core_clerk.chips.browser_c16224_6.0.0-snapshot.v20251218165926.js → zxcvbn-ts-core_clerk.chips.browser_5e7a74_6.0.0-snapshot.v20251218183643.js} +0 -0
  63. /package/dist/{zxcvbn-ts-core_clerk.headless.browser_1b17ca_6.0.0-snapshot.v20251218165926.js → zxcvbn-ts-core_clerk.headless.browser_45a74c_6.0.0-snapshot.v20251218183643.js} +0 -0
  64. /package/dist/{zxcvbn-ts-core_clerk.legacy.browser_ff5b6e_6.0.0-snapshot.v20251218165926.js → zxcvbn-ts-core_clerk.legacy.browser_6e74bb_6.0.0-snapshot.v20251218183643.js} +0 -0
@@ -16,4 +16,4 @@ ${a.message}`)}})(e_(e)):e).some(e=>e.test(e_(r.origin))));return n||H(`Clerk: R
16
16
  ${e.trim()}
17
17
  (This notice only appears in development)`,eD={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=>eF(`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=>eF(`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(eD)){let a=eD[e];"function"!=typeof a&&(eD[e]=eF(a))}let eN="clerk:beforeunload",eW=["http:","https:","wails:","chrome-extension:"];function eL(e){let a=new URL(e,window.location.href);window.dispatchEvent(new CustomEvent(eN)),window.location.href=a.href}function e$(e){return/^http(s)?:\/\//.test(e||"")}function eK(e){return e.startsWith("/")}var eB=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]))}},eJ=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}},eV=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 eG=new Set(["error","warn","info","debug","trace"]);var eH=class{#N;#W;#L={};#$=[];#K=null;constructor(e){this.#N={maxBufferSize:e.maxBufferSize??5,samplingRate:e.samplingRate??1,perEventSampling:e.perEventSampling??!0,disabled:e.disabled??!1,debug:e.debug??!1,endpoint:"https://clerk-telemetry.com"},e.clerkVersion||"undefined"!=typeof window?this.#L.clerkVersion=e.clerkVersion??"":this.#L.clerkVersion="",this.#L.sdk=e.sdk,this.#L.sdkVersion=e.sdkVersion,this.#L.publishableKey=e.publishableKey??"";const a=eu(e.publishableKey);a&&(this.#L.instanceType=a.instanceType),e.secretKey&&(this.#L.secretKey=e.secretKey.substring(0,16)),this.#W=new eB(eJ.isSupported()?new eJ:new eV)}get isEnabled(){return!("development"!==this.#L.instanceType||this.#N.disabled||"undefined"!=typeof process&&process.env&&er(process.env.CLERK_TELEMETRY_DISABLED)||"undefined"!=typeof window&&window?.navigator?.webdriver)}get isDebug(){return this.#N.debug||"undefined"!=typeof process&&process.env&&er(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&&eG.has(e.level),t="string"==typeof e?.message&&e.message.trim().length>0,r=null,i=e?.timestamp;if("number"==typeof i||"string"==typeof i){let e=new Date(i);Number.isNaN(e.getTime())||(r=e)}if(!a||!t||null===r){this.isDebug&&"undefined"!=typeof console&&console.warn("[clerk/telemetry] Dropping invalid telemetry log entry",{levelIsValid:a,messageIsValid:t,timestampIsValid:null!==r});return}let n=this.#Q(),s={sdk:n.name,sdkv:n.version,cv:this.#L.clerkVersion??"",lvl:e.level,msg:e.message,ts:r.toISOString(),pk:this.#L.publishableKey||null,payload:this.#Y(e.context)};this.#$.push({kind:"log",value:s}),this.#G()}catch(e){console.error("[clerk/telemetry] Error recording telemetry log entry",e)}}#V(e,a){return this.isEnabled&&!this.isDebug&&this.#X(e,a)}#H(e){return!0}#X(e,a){let t=Math.random();return!!(t<=this.#N.samplingRate&&(!1===this.#N.perEventSampling||void 0===a||t<=a))&&!this.#W.isEventThrottled(e)}#G(){if("undefined"==typeof window)return void this.#Z();if(this.#$.length>=this.#N.maxBufferSize){this.#K&&("undefined"!=typeof cancelIdleCallback?cancelIdleCallback(Number(this.#K)):clearTimeout(Number(this.#K))),this.#Z();return}this.#K||("requestIdleCallback"in window?this.#K=requestIdleCallback(()=>{this.#Z(),this.#K=null}):this.#K=setTimeout(()=>{this.#Z(),this.#K=null},0))}#Z(){let e=[...this.#$];if(this.#$=[],this.#K=null,0===e.length)return;let a=e.filter(e=>"event"===e.kind).map(e=>e.value),t=e.filter(e=>"log"===e.kind).map(e=>e.value);a.length>0&&fetch(new URL("/v1/event",this.#N.endpoint),{headers:{"Content-Type":"application/json"},keepalive:!0,method:"POST",body:JSON.stringify({events:a})}).catch(()=>void 0),t.length>0&&fetch(new URL("/v1/logs",this.#N.endpoint),{headers:{"Content-Type":"application/json"},keepalive:!0,method:"POST",body:JSON.stringify({logs:t})}).catch(()=>void 0)}#J(e,a){this.isDebug&&(void 0!==console.groupCollapsed?(console.groupCollapsed("[clerk/telemetry]",e),console.log(a),console.groupEnd()):console.log("[clerk/telemetry]",e,a))}#Q(){let e={name:this.#L.sdk,version:this.#L.sdkVersion};if("undefined"!=typeof window){let a=window;if(a.Clerk){let t=a.Clerk;if("object"==typeof t&&null!==t&&"constructor"in t&&"function"==typeof t.constructor&&t.constructor.sdkMetadata){let{name:a,version:r}=t.constructor.sdkMetadata;void 0!==a&&(e.name=a),void 0!==r&&(e.version=r)}}}return e}#B(e,a){let t=this.#Q();return{event:e,cv:this.#L.clerkVersion??"",it:this.#L.instanceType??"",sdk:t.name,sdkv:t.version,...this.#L.publishableKey?{pk:this.#L.publishableKey}:{},...this.#L.secretKey?{sk:this.#L.secretKey}:{},payload:a}}#Y(e){if(null==e||"object"!=typeof e)return null;try{let a=JSON.parse(JSON.stringify(e));if(a&&"object"==typeof a&&!Array.isArray(a))return a;return null}catch{return null}}};let eQ="COMPONENT_MOUNTED",eY=new Set(["SignIn","SignUp"]);function eX(e){return function(a,t,r){return{event:e,eventSamplingRate:e===eQ?eY.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 eZ(e,a,t){return eX(eQ)(e,a,t)}function e1(e,a,t){return eX("COMPONENT_OPENED")(e,a,t)}function e2(e){return"string"==typeof e?e:"object"==typeof e&&null!==e&&"name"in e&&"string"==typeof e.name?e.name:void 0}function e0(e,a,t){return"function"==typeof e?e(a):void 0!==e?e:void 0!==t?t:void 0}let e9=(...e)=>{},e3=!1,e8=null,e5=!1,e4=[];function e6(e,a,t,r){e3&&(e4.push({level:e,message:a,context:t,source:r,ts:Date.now()}),e4.length>200&&e4.shift())}async function e7(e){try{if(!e3||e8)return;let{getDebugLogger:a}=await Promise.resolve().then(i.bind(i,854)),t=await a({logLevel:e?.logLevel,telemetryCollector:e?.telemetryCollector});if(t&&(e8=t)&&0!==e4.length){for(let e of e4){let a={...e.context||{},__preInit:!0,__preInitTs:e.ts};switch(e.level){case"error":e8.error(e.message,a,e.source);break;case"warn":e8.warn(e.message,a,e.source);break;case"info":e8.info(e.message,a,e.source);break;case"debug":e8.debug(e.message,a,e.source)}}e4.length=0}}catch(e){try{console.debug?.("Debug logger initialization failed",e)}catch{}return}}let ae={debug(e,a,t){e8?e8.debug(e,a,t):e6("debug",e,a,t)},error(e,a,t){e8?e8.error(e,a,t):e6("error",e,a,t)},info(e,a,t){e8?e8.info(e,a,t):e6("info",e,a,t)},warn(e,a,t){e8?e8.warn(e,a,t):e6("warn",e,a,t)}},aa={initialDelay:125,maxDelayBetweenRetries:0,factor:2,shouldRetry:(e,a)=>a<5,retryImmediately:!1,jitter:!0},at=async e=>new Promise(a=>setTimeout(a,e)),ar=(e,a)=>a?e*(1+Math.random()):e,ai=async(e,a={})=>{var t;let r,i=0,{shouldRetry:n,initialDelay:s,maxDelayBetweenRetries:o,factor:l,retryImmediately:c,jitter:d,onBeforeRetry:u}={...aa,...a},h=(t={initialDelay:s,maxDelayBetweenRetries:o,factor:l,jitter:d},r=0,async()=>{let e;await at((e=ar(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 at(ar(100,d)):await h()}},an=async e=>ai(e,{initialDelay:100,shouldRetry:(e,a)=>a<=3,retryImmediately:!0,factor:2});class as{#ee={"@zxcvbn-ts/core":()=>an(()=>Promise.resolve().then(i.bind(i,10))),"@zxcvbn-ts/language-common":()=>an(()=>Promise.resolve().then(i.bind(i,655))),"@base-org/account":()=>an(()=>Promise.resolve().then(function(){var e=Error("Cannot find module '@base-org/account'");throw e.code="MODULE_NOT_FOUND",e})),"@coinbase/wallet-sdk":()=>an(()=>Promise.resolve().then(function(){var e=Error("Cannot find module '@coinbase/wallet-sdk'");throw e.code="MODULE_NOT_FOUND",e})),"@stripe/stripe-js":()=>an(()=>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 ao=(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(eN,t)},stopListening:()=>{window.removeEventListener("beforeunload",t),window.removeEventListener(eN,t)},isUnloading:()=>a});return{track:async e=>{r.startListening(),await e(),r.stopListening()},isUnloading:r.isUnloading}},al=e=>({amount:e.amount,amountFormatted:e.amount_formatted,currency:e.currency,currencySymbol:e.currency_symbol}),ac=e=>{let a={grandTotal:al(e.grand_total),subtotal:al(e.subtotal),taxTotal:al(e.tax_total)};return"past_due"in e&&(a.pastDue=e.past_due?al(e.past_due):null),"credit"in e&&(a.credit=e.credit?al(e.credit):null),"total_due_now"in e&&(a.totalDueNow=al(e.total_due_now)),"total_due_after_free_trial"in e&&(a.totalDueAfterFreeTrial=e.total_due_after_free_trial?al(e.total_due_after_free_trial):null),a};function ad(e,a=""){return e.errors&&!!e.errors.find(e=>e.code===a)}let au=_({packageName:"@clerk/clerk-js"});function ah(e){return decodeURIComponent(globalThis.atob(e.replace(/_/g,"/").replace(/-/g,"+")).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""))}function am(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(ah(r)),s={__raw:e};return Object.keys(n).forEach(e=>{s[e]=n[e]}),{encoded:{header:t,payload:r,signature:i},header:JSON.parse(ah(t)),claims:s}}function ap(){if(!s())return null;try{let e=navigator?.language;if(!e||"string"!=typeof e||""===e.trim())return null;return e}catch{return null}}function ag(){return void 0!==globalThis.document}function ab(){if(!function(){if(!ag())return!1;try{return window.self!==window.top}catch{return!0}}())return!1;try{return window.top?.location.href,!1}catch{return!0}}var af=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)}},ay=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 ak=()=>(function(e){let a=_({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 U("Web3 signature request was rejected by the user.",{code:"web3_signature_request_rejected"});throw new U("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({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 ay.getInstance().get(r):void a.throw("Wallet name must be provided to get Solana wallet provider"):af.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 as),aw="environment",av=JSON.stringify,aj=JSON.parse;class az{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),av(r))}catch{}}static getItem(e,a){try{let t=window.localStorage.getItem(this._key(e));if(!t)return a;let r=aj(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 a_="ClerkJS:";function ax(e){console.warn(`${a_} ${e} is not supported in this environment.`)}function aq(e=""){throw Error(`${a_} Something went wrong initializing Clerk in development mode.${e&&` ${e}`}`)}function aS(e){throw Error(`${a_} Something went wrong initializing Clerk during the ${e} flow. Please contact support.`)}function aU(e){throw Error(`${a_} You need to start a ${e} flow by calling ${e}.create() first.`)}function aA(e,a){throw Error(`${a_} Strategy "${a}" is not a valid strategy for ${e}.`)}function aC(e){throw Error(`${a_} You need to start a ${e} flow by calling ${e}.create({ identifier: 'your web3 wallet address' }) first`)}function aI(e=""){throw Error(`${a_} Missing '${e}' option`)}function aP(e,a){throw Error(`${a_} Response: ${e||0} not supported yet.
18
18
  For more information contact us at ${a}`)}function aO(e){throw Error(`${a_} Missing publicKey. When calling 'navigator.credentials.${e}()' it is required to pass a publicKey object.`)}let aT=e=>Promise.reject(Error("Captcha not supported in this environment")),aE=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 aM{clerk;constructor(e){this.clerk=e}async invisible(e){let{captchaSiteKey:a,canUseCaptcha:t,captchaPublicKeyInvisible:r,nonce:i}=aE(this.clerk);return t&&a&&r?{...await aT({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}=aE(this.clerk);if(t&&a&&n){let t=await aT({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 aR{client;CaptchaChallengeImpl;static instance;inflightException=null;captchaRetryCount=0;MAX_RETRY_ATTEMPTS=3;static getInstance(){return aR.instance||(aR.instance=new aR(tP,aM)),aR.instance}constructor(e,a){this.client=e,this.CaptchaChallengeImpl=a}async execute(e,a){if(this.captchaAttemptsExceeded())throw new U("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(!T(r)||E(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 aF{static clerk;id;pathRoot="";static get fapiClient(){return aF.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 aR.getInstance().execute(this.clerk,()=>this._baseFetch(e,a))}static async _baseFetch(e,a={}){let t;aF.fapiClient||function(){throw Error(`${a_} Missing FAPI client in resources.`)}();let{fetchMaxTries:r}=a;try{t=await aF.fapiClient.request(e,{fetchMaxTries:r})}catch(a){if(this.shouldRethrowOfflineNetworkErrors())throw new U(a?.message||a,{code:"network_error"});if(!d())return ae.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 aF.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=aF.clerk.publishableKey).startsWith("live_")||t.startsWith("pk_live_"))){let t=aF.clerk.frontendApi.replace("clerk.","");throw new v(`Clerk: Production Keys are only allowed for domain "${t}".
19
- API Error: ${i}`,{data:a,status:e})}}(n,e);let r={data:e,status:n};if(429===n&&o){let e=o.get("retry-after");if(e){let a=parseInt(e,10);isNaN(a)||(r.retryAfter=a)}}throw new v(a||s,r)}return null}static _updateClient(e){if(!e)return;let a=e.client||e.meta?.client;a&&aF.clerk&&aF.clerk.updateClient(tP.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 aF._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 aF._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 aF._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=aF.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}function aD(e){let a=new Date(e||new Date);return a instanceof Date&&!isNaN(a.getTime())?a:new Date}class aN extends aF{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?aD(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?aD(e.last_used_at):null,this.updatedAt=aD(e.updated_at),this.createdAt=aD(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 aW extends aF{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?aD(e.claimed_at):null,this.claimedAt),this.reverification=this.withDefault(e.reverification,this.reverification),this.singleSessionMode=this.withDefault(e.single_session_mode,this.singleSessionMode),this.preferredChannels=this.withDefault(e.preferred_channels,this.preferredChannels)),this}__internal_toSnapshot(){return{claimed_at:this.claimedAt?this.claimedAt.getTime():null,id:this.id??"",object:"auth_config",reverification:this.reverification,single_session_mode:this.singleSessionMode}}}(f=y||(y={}))[f.None=0]="None",f[f.Mutable=1]="Mutable",f[f.Watching=2]="Watching",f[f.RecursedCheck=4]="RecursedCheck",f[f.Recursed=8]="Recursed",f[f.Dirty=16]="Dirty",f[f.Pending=32]="Pending";let aL=[],{link:a$,unlink:aK,propagate:aB,checkDirty:aJ,endTracking:aV,startTracking:aG,shallowPropagate:aH}=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?a9(e):a3(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):aL[aX++]=a}},unwatched(e){if("getter"in e){let a=e.deps;if(void 0!==a){e.flags=17;do a=aK(a,e);while(void 0!==a)}}else"previousValue"in e||a6.call(e)}}),aQ=0,aY=0,aX=0;function aZ(a){let t=e;return e=a,t}function a1(e){return a4.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function a2(e){return a5.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function a0(t){let r={fn:t,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==e?a$(r,e):void 0!==a&&a$(r,a);let i=aZ(r);try{r.fn()}finally{aZ(i)}return a6.bind(r)}function a9(e){let a=aZ(e);aG(e);try{let a=e.value;return a!==(e.value=e.getter(a))}finally{aZ(a),aV(e)}}function a3(e,a){return e.flags=1,e.previousValue!==(e.previousValue=a)}function a8(){for(;aY<aX;){let e=aL[aY];aL[aY++]=void 0,function e(a,t){if(16&t||32&t&&aJ(a.deps,a)){let e=aZ(a);aG(a);try{a.fn()}finally{aZ(e),aV(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)}aY=0,aX=0}function a5(){let t=this.flags;if(16&t||32&t&&aJ(this.deps,this)){if(a9(this)){let e=this.subs;void 0!==e&&aH(e)}}else 32&t&&(this.flags=-33&t);return void 0!==e?a$(this,e):void 0!==a&&a$(this,a),this.value}function a4(...a){if(a.length){let e=a[0];if(this.value!==(this.value=e)){this.flags=17;let e=this.subs;void 0!==e&&(aB(e),aQ||a8())}}else{let a=this.value;if(16&this.flags&&a3(this,a)){let e=this.subs;void 0!==e&&aH(e)}return void 0!==e&&a$(this,e),a}}function a6(){let e=this.deps;for(;void 0!==e;)e=aK(e,this);let a=this.subs;void 0!==a&&aK(a),this.flags=0}function a7(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 te{static #ed="/billing";static path(e,a){let{orgId:t}=a||{},r=t?`/organizations/${t}`:"/me";return`${r}${te.#ed}${e}`}getPlans=async e=>{let{for:a,...t}=e||{},r={...t,payer_type:"organization"===a?"org":"user"};return await aF._fetch({path:`${te.#ed}/plans`,method:"GET",search:a7(r)}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new tw(e))}})};getPlan=async e=>new tw(await aF._fetch({path:`${te.#ed}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await aF._fetch({path:te.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new tz(e?.response));getStatements=async e=>{let{orgId:a,...t}=e;return await aF._fetch({path:te.path("/statements",{orgId:a}),method:"GET",search:a7(t)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new tv(e))}})};getStatement=async e=>new tv((await aF._fetch({path:te.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:a,...t}=e;return await aF._fetch({path:te.path("/payment_attempts",{orgId:a}),method:"GET",search:a7(t)}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new tm(e))}})};getPaymentAttempt=async e=>new tm(await aF._fetch({path:te.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:a,...t}=e;return new tu((await aF._fetch({path:te.path("/checkouts",{orgId:a}),method:"POST",body:t}))?.response)}}let ta=a1({resource:null}),tt=a1({error:null}),tr=a1({status:"idle"}),ti=a2(()=>{let e=ta().resource,a=tt().error,t=tr().status;return{errors:tc(a,{identifier:null,password:null,code:null}),fetchStatus:t,signIn:e?e.__internal_future:null}}),tn=a1({resource:null}),ts=a1({error:null}),to=a1({status:"idle"}),tl=a2(()=>{let e=tn().resource,a=ts().error,t=to().status;return{errors:tc(a,{firstName:null,lastName:null,emailAddress:null,phoneNumber:null,password:null,username:null,code:null,captcha:null,legalAccepted:null}),fetchStatus:t,signUp:e?e.__internal_future:null}});function tc(e,a){let t={fields:{...a},raw:null,global:null};if(!e)return t;if(!T(e))return t.raw=[e],t.global=[D(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=[D(e)]),t}class td extends aF{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=aD(e.created_at)),e.updated_at&&(this.updatedAt=aD(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 tu extends aF{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 ty(e.payment_method):void 0,this.plan=new tw(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=ac(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change,e.free_trial_ends_at&&(this.freeTrialEndsAt=aD(e.free_trial_ends_at)),this.payer=new td(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>ai(()=>this._basePatch({path:te.path(`/checkouts/${this.id}/confirm`,{orgId:this.payer.organizationId}),body:e}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,a){if(!T(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 th{resource=new tu(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 tu.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new tu(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 tu.clerk.setActive({session:tu.clerk.session?.id,navigate:a})})}runAsyncCheckoutTask(e,a,t){var r,i,n;return void 0===tu.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()=>{++aQ,i.errorSignal({error:null}),i.fetchSignal({status:"fetching"}),t?.(),--aQ||a8(),++aQ;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"}),--aQ||a8()}})();return n.set(e,s),s})(e,a,t)}}class tm extends aF{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=al(e.amount),this.paidAt=e.paid_at?aD(e.paid_at):null,this.failedAt=e.failed_at?aD(e.failed_at):null,this.updatedAt=aD(e.updated_at),this.paymentMethod=e.payment_method?new ty(e.payment_method):null,this.subscriptionItem=new t_(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status),this}}let tp="/payment_methods",tg=async e=>{let{orgId:a,...t}=e;return new tk((await aF._fetch({path:te.path(`${tp}/initialize`,{orgId:a}),method:"POST",body:t}))?.response)},tb=async e=>{let{orgId:a,...t}=e;return new ty((await aF._fetch({path:te.path(tp,{orgId:a}),method:"POST",body:t}))?.response)},tf=async e=>{let{orgId:a,...t}=e??{};return await aF._fetch({path:te.path(tp,{orgId:a}),method:"GET",search:a7(t)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new ty(e))}})};class ty extends aF{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:aD(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:aD(e.updated_at)),this}async remove(e){let{orgId:a}=e??{};return new tT((await aF._fetch({path:te.path(`/payment_methods/${this.id}`,{orgId:a}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:a}=e??{};return await aF._fetch({path:te.path("/payers/default_payment_method",{orgId:a}),method:"PUT",body:{payment_method_id:this.id}}),null}}class tk extends aF{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 tw extends aF{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=al(e.fee),this.annualFee=e.annual_fee?al(e.annual_fee):null,this.annualMonthlyFee=e.annual_monthly_fee?al(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 rt(e))),this}}class tv extends aF{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=aD(e.timestamp),this.totals=ac(e.totals),this.groups=e.groups.map(e=>new tj(e))),this}}class tj{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=aD(e.timestamp),this.items=e.items.map(e=>new tm(e))),this}}class tz extends aF{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=aD(e.created_at),this.updatedAt=e.updated_at?aD(e.updated_at):null,this.activeAt=aD(e.active_at),this.pastDueAt=e.past_due_at?aD(e.past_due_at):null,e.next_payment&&(this.nextPayment={amount:al(e.next_payment.amount),date:aD(e.next_payment.date)}),this.subscriptionItems=(e.subscription_items||[]).map(e=>new t_(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1)),this}}class t_ extends aF{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 tw(e.plan),this.planPeriod=e.plan_period,this.status=e.status,this.createdAt=aD(e.created_at),this.pastDueAt=e.past_due_at?aD(e.past_due_at):null,this.periodStart=aD(e.period_start),this.periodEnd=e.period_end?aD(e.period_end):null,this.canceledAt=e.canceled_at?aD(e.canceled_at):null,this.amount=e.amount?al(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:al(e.credit.amount)}:void 0,this.isFreeTrial=this.withDefault(e.is_free_trial,!1)),this}async cancel(e){let{orgId:a}=e;return new tT((await aF._fetch({path:te.path(`/subscription_items/${this.id}`,{orgId:a}),method:"DELETE"}))?.response)}}let tx={build:(e,a,t)=>[e,a,t].filter(Boolean).join("-"),parse:(e,a,t)=>{let r=tx.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}},tq="clerk",tS=10,tU={broadcast:!0},tA={broadcast:!1};class tC{prefix;data;static fromKey(e){let[a,t,r=""]=e.split("::");return new tC(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 tI=((e=tq)=>{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=tS)=>{i();let n=new tC(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=tx.build(e.sessionId,e.template,e.organizationId);if(e.tokenId!==r)return void ae.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 rW({id:e.tokenId,jwt:e.tokenRaw,object:"token"})}catch(a){ae.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 ae.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 ae.debug("Ignoring older token broadcast",{existingIat:n,incomingIat:i,tabId:t,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}}catch(a){ae.warn("Existing entry compare failed; proceeding with broadcast update",{error:a,tabId:t,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}ae.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)},tA)},o=(i,n=tU)=>{let s=new tC(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=tx.extractTemplate(i.tokenId,e,n),o=tx.build(e,s,n);if(i.tokenId===o){let a=`bc_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;ae.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,tU)},size:()=>a.size}})();class tP extends aF{static instance;pathRoot="/client";sessions=[];signUp=new rF;signIn=new rE;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return tP.instance||(tP.instance=new tP(e)),tP.instance}static clearInstance(){tP.instance=null}static isClientResource(e){return!!e&&e instanceof tP}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(()=>{tI.clear(),this.id="",this.sessions=[],this.signUp=new rF(null),this.signIn=new rE(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=>(tI.clear(),e))}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return aF.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 rq(e)),this.signUp=new rF(e.sign_up),this.signIn=new rE(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?aD(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=aD(e.created_at||void 0),this.updatedAt=aD(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 tO extends aF{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 tT{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 tE extends aF{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 tM='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 tR=(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}},tF=()=>{let e=0,a=()=>e++,t=new Map,r=(e,a)=>e?.postMessage(a),i=e=>{t.get(e.data.id)?.()},n=tR(tM,{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:e9};let s=()=>{n||(n=tR(tM,{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 tD({delayInMs:e}={delayInMs:1e3}){let a,t=tF(),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 tN extends aF{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}=tD();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}=tD();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 tY(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new rr(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 tW=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 tL(e){try{let a=await navigator.credentials.create({publicKey:e});if(!a)return{error:new C("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 C(a.message,{code:"passkey_already_exists"}):"NotAllowedError"===a.name?new C(a.message,{code:"passkey_registration_cancelled"}):tB(a),publicKeyCredential:null}}}let t$=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 tK({publicKeyOptions:e,conditionalUI:a}){try{let t=await navigator.credentials.get({publicKey:e,mediation:a?"conditional":"optional",signal:t$.createAbortSignal()});if(!t)return{error:new C("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 C(t.message,{code:"passkey_retrieval_cancelled"}):tB(t),publicKeyCredential:null}}}function tB(e){return"AbortError"===e.name?new C(e.message,{code:"passkey_operation_aborted"}):"SecurityError"===e.name?new C(e.message,{code:"passkey_invalid_rpID_or_domain"}):e}function tJ(e){let a=tQ(e.challenge),t=(e.allowCredentials||[]).map(e=>({...e,id:tQ(e.id)}));return{...e,allowCredentials:t,challenge:a}}function tV(e){return{type:e.type,id:e.id,rawId:tH(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function tG(e){let a=e.response;return{...tV(e),response:{clientDataJSON:tH(a.clientDataJSON),authenticatorData:tH(a.authenticatorData),signature:tH(a.signature),userHandle:a.userHandle?tH(a.userHandle):null}}}let tH=tW.encode.bind(tW),tQ=tW.decode.bind(tW);class tY extends aF{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===aF.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=aD(e.expire_at||void 0),this.error=e.error?new k(e.error):null,this.channel=e.channel||void 0),this}__internal_toSnapshot(){var e;return{object:"verification",id:this.id||"",status:this.status,strategy:this.strategy,nonce:this.nonce,message:this.message,external_verification_redirect_url:this.externalVerificationRedirectURL?.toString()||null,attempts:this.attempts,expire_at:this.expireAt?.getTime()||null,error:(e=this.error,{code:e?.code||"",message:e?.message||"",long_message:e?.longMessage,meta:{param_name:e?.meta?.paramName,session_id:e?.meta?.sessionId,email_addresses:e?.meta?.emailAddresses,identifiers:e?.meta?.identifiers,zxcvbn:e?.meta?.zxcvbn,plan:e?.meta?.plan,is_plan_upgrade_possible:e?.meta?.isPlanUpgradePossible}}),verified_at_client:this.verifiedAtClient}}}class tX extends tY{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=tQ((a=JSON.parse(e.nonce)).user.id),r=tQ(a.challenge),i=(a.excludeCredentials||[]).map(e=>({...e,id:tQ(e.id)})),{...a,excludeCredentials:i,challenge:r,user:{...a.user,id:t}})),this}}class tZ{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new t1(e.email_address),this.phoneNumber=new t1(e.phone_number),this.web3Wallet=new t1(e.web3_wallet),this.externalAccount=new tY(e.external_account)):(this.emailAddress=new t1(null),this.phoneNumber=new t1(null),this.web3Wallet=new t1(null),this.externalAccount=new tY(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 t1 extends tY{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 t2 extends aF{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?aD(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new tY(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new t0(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 t0 extends aF{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=aD(e.created_at),this.updatedAt=aD(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 t9="token:update",t3="user:signOut",t8="environment:update",t5="session:tokenResolved",t4=p();class t6 extends aF{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 t7 extends aF{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 re extends aF{static instance;authConfig=new aW;displayConfig=new tE;maintenanceMode=!1;clientDebugMode=!1;pathRoot="/environment";userSettings=new rG;organizationSettings=new t7;commerceSettings=new tO;apiKeysSettings=new t6;protectConfig=new ry;static getInstance(){return re.instance||(re.instance=new re),re.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new aW(e.auth_config),this.displayConfig=new tE(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 t7(e.organization_settings),this.userSettings=new rG(e.user_settings),this.commerceSettings=new tO(e.commerce_settings),this.apiKeysSettings=new t6(e.api_keys_settings),this.protectConfig=new ry(e.protect_config)),this}fetch({touch:e,fetchMaxTries:a}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:a})).then(e=>(t4.emit(t8,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 ra extends aF{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 tY(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 rt extends aF{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 rr extends aF{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 ri extends aF{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 ri((await aF._fetch({path:e,method:"POST",body:r,headers:t}))?.response)}static async delete(e){return new ri((await aF._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 rn extends aF{id;name;organizationId;enrollmentMode;verification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:a}){return new rn((await aF._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:aD(e.verification.expires_at)}:this.verification=null),this}}class rs extends aF{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=aD(e.created_at),this.updatedAt=aD(e.updated_at),e.public_user_data&&(this.publicUserData=new rk(e.public_user_data))),this}}class ro extends aF{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=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}}class rl extends aF{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 ro(e)),this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}}class rc extends aF{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 rc((await aF._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new rc((await aF._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await aF._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:a7(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rl(e))}});getDomains=async e=>await aF._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:a7(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rn(e))}});getDomain=async({domainId:e})=>new rn((await aF._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getMembershipRequests=async e=>await aF._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:a7(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rs(e))}});createDomain=async e=>rn.create(this.id,{name:e});getMemberships=async e=>await aF._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:a7({...e,paginated:!0})}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new ru(e))}});getInvitations=async e=>await aF._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:a7(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rd(e))}});addMember=async({userId:e,role:a})=>await aF._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:a}}).then(e=>new ru(e?.response));inviteMember=async e=>rd.create(this.id,e);inviteMembers=async e=>rd.createBulk(this.id,e);updateMember=async({userId:e,role:a})=>await aF._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:a}}).then(e=>new ru(e?.response));removeMember=async e=>await aF._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new ru(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let a,t;return null===e?await aF._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new rc(e?.response)):("string"==typeof e?(a=e,t=new Headers({"Content-Type":"application/octet-stream"})):(a=new FormData).append("file",e),await aF._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:a,headers:t}).then(e=>new rc(e?.response)))};initializePaymentMethod=e=>tg({...e,orgId:this.id});addPaymentMethod=e=>tb({...e,orgId:this.id});getPaymentMethods=e=>tf({...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=aD(e.created_at),this.updatedAt=aD(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 aF._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:a},{forceUpdateClient:!0}))?.response;return this.fromJSON(t)}}class rd extends aF{id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:a,role:t}){return new rd((await aF._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 aF._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:t,role:r}}))?.response).map(e=>new rd(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=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}}class ru extends aF{id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await aF._fetch({path:"/me/organization_memberships",method:"GET",search:a7({...e,paginated:!0})}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new ru(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 rc(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new rk(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=aD(e.created_at),this.updatedAt=aD(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(`${a_} Calling OrganizationMembership.reload is not currently supported. Please contact support.`)}}class rh extends aF{id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await aF._fetch({path:"/me/organization_suggestions",method:"GET",search:a7(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rh(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=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}}function rm(){return l()&&"function"==typeof window.PublicKeyCredential}async function rp(){try{return rm()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function rg(){try{return"undefined"!=typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class rb extends aF{id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return aF._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new rb(e?.response))}static async attemptVerification(e,a){let t,r=(t=a.response,{...tV(a),response:{clientDataJSON:tH(t.clientDataJSON),attestationObject:tH(t.attestationObject),transports:t.getTransports()}});return aF._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(r)}}).then(e=>new rb(e?.response))}static async registerPasskey(){let e=rb.clerk.__internal_isWebAuthnSupported||rm,a=rb.clerk.__internal_createPublicCredentials||tL,t=rb.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||rg;if(!e())throw new C("Passkeys are not supported on this device.",{code:"passkey_not_supported"});let r=await this.create(),{verification:i}=r,n=i?.publicKey;if(n||aO("create"),n.authenticatorSelection?.authenticatorAttachment==="platform"&&!await t())throw new C("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 tT((await aF._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?aD(e.last_used_at):null,this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at),e.verification&&(this.verification=new tX(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 rf extends aF{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 tY(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new rr(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 ry extends aF{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 rk{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 rw={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"}},rv=new Set(["first_factor","second_factor","multi_factor"]),rj=new Set(["strict_mfa","strict","moderate","lax"]),rz=(e,a)=>{let{org:t,user:r}=r_(e),[i,n]=a.split(":"),s=n||i;return"org"===i?t.includes(s):"user"===i?r.includes(s):[...t,...r].includes(s)},r_=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 rx extends aF{status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new tY(null);secondFactorVerification=new tY(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new rq(e.session),this.level=e.level,this.supportedFirstFactors=et(e.supported_first_factors),this.supportedSecondFactors=et(e.supported_second_factors),this.firstFactorVerification=new tY(e.first_factor_verification),this.secondFactorVerification=new tY(e.second_factor_verification)),this}}class rq extends aF{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 rq}constructor(e){super(),this.fromJSON(e),this.#eu(this.lastActiveToken)}end=()=>(tI.clear(),this._basePost({action:"end"}));remove=()=>(tI.clear(),this._basePost({action:"remove"}));touch=()=>this._basePost({action:"touch",body:{active_organization_id:this.lastActiveOrganizationId}}).then(e=>(e.lastActiveToken&&t4.emit(t9,{token:e.lastActiveToken}),e));clearCache=()=>tI.clear();getToken=async e=>ai(()=>this._getToken(e),{factor:1.55,initialDelay:3e3,maxDelayBetweenRetries:5e4,jitter:!1,shouldRetry:(e,a)=>!P(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?rz(t,e.feature):e.plan&&r?rz(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&&rj.has(e),i="object"==typeof e&&(a=e.level,rv.has(a))&&"number"==typeof(t=e.afterMinutes)&&t>0;return(!!r||!!i)&&(e=>"string"==typeof e?rw[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&&tI.set({tokenId:this.#eh(),tokenResolver:Promise.resolve(e)})};#eh(e,a){let t=void 0===a?this.lastActiveOrganizationId:a;return tx.build(this.id,e,t)}startVerification=async({level:e})=>new rx((await aF._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 rx((await aF._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(tG(e.publicKeyCredential))}:{...e},new rx((await aF._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=rq.clerk.__internal_isWebAuthnSupported||rm,t=rq.clerk.__internal_getPublicCredentials||tK;if(!a())throw new C("Passkeys are not supported",{code:"passkey_not_supported"});let r=e?tJ(JSON.parse(e)):null;r||aO("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 rx((await aF._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>new rx((await aF._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=aD(e.expire_at),this.abandonAt=aD(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=aD(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at),this.user=new rK(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new rk(e.public_user_data)),this.lastActiveToken=e.last_active_token?new rW(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:tI.get({tokenId:n},a),o=!t&&i===this.lastActiveOrganizationId;if(s){ae.debug("Using cached token (no fetch needed)",{tokenId:n},"session");let e=await s.tokenResolver;return o&&t4.emit(t9,{token:e}),e.getRawString()||null}ae.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=rW.create(l,c,r);return tI.set({tokenId:n,tokenResolver:d}),d.then(e=>(o&&(t4.emit(t9,{token:e}),e.jwt&&(this.lastActiveToken=e,t4.emit(t5,null))),e.getRawString()||null))}get currentTask(){let[e]=this.tasks??[];return e}}class rS extends aF{pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,a){super(),this.pathRoot=a,this.fromJSON(e)}static retrieve(){let e=aF.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new rS(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=aD(e.expire_at),this.abandonAt=aD(e.abandon_at),this.lastActiveAt=aD(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 rU=(e,a,t)=>{let{onValidation:r=e9,onValidationComplexity:i=e9}=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 rA(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function rC(e,a,t,r,i){if(!e.client||!r.popup)return;let n=rA(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 rI(e,{redirectCallbackUrl:a,redirectUrl:t}){let r=rA(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 rP(e,a){return new Promise((t,r)=>{if(!e.client||!a.popup)return void r();let i=async a=>{a.origin===rA(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 rO(e,a){t4.emit("resource:error",{resource:e,error:null}),t4.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await a(),error:null}}catch(a){return t4.emit("resource:error",{resource:e,error:a}),{error:a}}finally{t4.emit("resource:fetch",{resource:e,status:"idle"})}}let rT=()=>{var e;return(e=new as,{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 rE extends aF{pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;firstFactorVerification=new tY(null);secondFactorVerification=new tY(null);identifier=null;createdSessionId=null;userData=new rB(null);clientTrustState;get status(){return this._status}set status(e){let a=this._status;this._status=e,e&&a!==e&&ae.debug("SignIn.status",{id:this.id,from:a,to:e})}__internal_future=new rM(this);__internal_basePost=this._basePost.bind(this);__internal_baseGet=this._baseGet.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=e=>{ae.debug("SignIn.create",{id:this.id,strategy:"strategy"in e?e.strategy:void 0});let a=ap();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(ae.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 ae.debug("SignIn.attemptFirstFactor",{id:this.id,strategy:e.strategy}),a="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(tG(e.publicKeyCredential))}:{...e},this._basePost({body:{...a,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:a}=tD();return{startEmailLinkFlow:async({emailAddressId:t,redirectUrl:r})=>{this.id||aU("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=>(ae.debug("SignIn.prepareSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_second_factor"}));attemptSecondFactor=e=>(ae.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=rE.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):aP(c,rE.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eL);authenticateWithPopup=async e=>{let{popup:a}=e||{};return a||aI("popup"),rC(rE.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&&aI("generateSignature"),"solana"!==s||n||aI("walletName"),await this.create({identifier:t});let o=this.supportedFirstFactors?.find(e=>e.strategy===i);o||aC("SignIn"),await this.prepareFirstFactor(o);let{message:l}=this.firstFactorVerification;l||aC("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 ak().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ak().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await ak().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ak().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await ak().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ak().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await ak().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ak().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithSolana=async({walletName:e})=>{let a=await ak().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:a,generateSignature:a=>ak().generateSignatureWithSolana({...a,walletName:e}),strategy:"web3_solana_signature",walletName:e})};authenticateWithPasskey=async e=>{let{flow:a}=e||{},t=rE.clerk.__internal_isWebAuthnSupported||rm,r=rE.clerk.__internal_getPublicCredentials||tK,i=rE.clerk.__internal_isWebAuthnAutofillSupported||rp;if(!t())throw new C("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(`${a_} 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?tJ(JSON.parse(n)):null;s||aO("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(rE.clerk.__internal_environment?.userSettings.passwordSettings)return rU(rT(),{...rE.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=et(e.supported_first_factors),this.supportedSecondFactors=et(e.supported_second_factors),this.firstFactorVerification=new tY(e.first_factor_verification),this.secondFactorVerification=new tY(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new rB(e.user_data),this.clientTrustState=e.client_trust_state??void 0),t4.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:ea(this.supportedFirstFactors),supported_second_factors:ea(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 rM{emailCode={sendCode:this.sendEmailCode.bind(this),verifyCode:this.verifyEmailCode.bind(this)};emailLink={sendLink:this.sendEmailLink.bind(this),waitForVerification:this.waitForEmailLinkVerification.bind(this),get verification(){if(!s())return null;const e=eP("__clerk_status"),a=eP("__clerk_created_session");if(!e||!a)return null;const t="verified"===e&&void 0!==rE.clerk.client&&rE.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 rO(this.#ep,async()=>{let e=this.#ep.supportedFirstFactors?.find(e=>"reset_password_email_code"===e.strategy);if(!e)throw new U("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 rO(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 rO(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{password:a,signOutOfOtherSessions:t},action:"reset_password"})})}async _create(e){let a=ap();await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:a?{locale:a,...e}:e})}async create(e){return rO(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 rO(this.#ep,async()=>{let a=e.identifier||e.emailAddress||e.phoneNumber,t=this.#ep.identifier,r=ap();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 rO(this.#ep,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"email_code",emailAddressId:t});if(!e)throw new U("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 rO(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 rO(this.#ep,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"email_link",emailAddressId:r});if(!e)throw new U("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 rO(this.#ep,async()=>{let{run:e,stop:a}=tD();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 rO(this.#ep,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"phone_code",phoneNumberId:t});if(!e)throw new U("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 rO(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 rO(this.#ep,async()=>{let e=t;try{new URL(t)}catch{e=window.location.origin+t}let l={redirectUrl:rE.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:e};if(i){let a=rI(rE.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 rP(rE.clerk,{popup:i,externalVerificationRedirectURL:d}),await this.#ep.reload()):eL(d))})}async web3(e){let{strategy:a}=e,t=a.replace("web3_","").replace("_signature","");return rO(this.#ep,async()=>{let r,i,n;switch(t){case"metamask":r=await ak().getMetamaskIdentifier(),i=ak().generateSignatureWithMetamask;break;case"coinbase_wallet":r=await ak().getCoinbaseWalletIdentifier(),i=ak().generateSignatureWithCoinbaseWallet;break;case"base":r=await ak().getBaseIdentifier(),i=ak().generateSignatureWithBase;break;case"okx_wallet":r=await ak().getOKXWalletIdentifier(),i=ak().generateSignatureWithOKXWallet;break;case"solana":if(!e.walletName)throw new U("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});r=await ak().getSolanaIdentifier(e.walletName),i=a=>ak().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 U("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 U("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=rE.clerk.__internal_isWebAuthnSupported||rm,r=rE.clerk.__internal_getPublicCredentials||tK,i=rE.clerk.__internal_isWebAuthnAutofillSupported||rp;if(!t())throw new C("Passkeys are not supported",{code:"passkey_not_supported"});return rO(this.#ep,async()=>{if("autofill"===a||"discoverable"===a)await this._create({strategy:"passkey"});else{if(!this.supportedFirstFactors.find(e=>"passkey"===e.strategy))throw new U("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?tJ(JSON.parse(e)):null;if(!t)throw new U("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 C(o.message,{code:"passkey_retrieval_failed"});await this.#ep.__internal_basePost({body:{publicKeyCredential:JSON.stringify(tG(s)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return rO(this.#ep,async()=>{let e=this.#ep.supportedSecondFactors?.find(e=>"phone_code"===e.strategy);if(!e)throw new U("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 rO(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 rO(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 rO(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??eP("__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 rO(this.#ep,async()=>{rE.clerk.client&&!rE.clerk.client.sessions.some(e=>e.id===this.#ep.createdSessionId)&&await rE.clerk.client.reload(),this.#em=!0,await rE.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 rR(e){let{unsafeMetadata:a}={...e},t=a?"object"==typeof a?JSON.stringify(a):a:"";return{...e,...a?{unsafeMetadata:t}:{}}}class rF extends aF{pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new tZ(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&&ae.debug("SignUp.status",{id:this.id,from:a,to:e})}__internal_future=new rD(this);__internal_basePost=this._basePost.bind(this);__internal_basePatch=this._basePatch.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{ae.debug("SignUp.create",{id:this.id,strategy:e.strategy});let a={...e};if(!a.locale){let e=ap();e&&(a.locale=e)}if(a.transfer&&this.shouldBypassCaptchaForAttempt(a)){let e=rF.clerk.client?.signIn.firstFactorVerification.strategy;e&&(a={...a,strategy:e})}return this._basePost({path:this.pathRoot,body:rR(a)})};prepareVerification=e=>(ae.debug("SignUp.prepareVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_verification"}));attemptVerification=e=>(ae.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}=tD();return{startEmailLinkFlow:async({redirectUrl:t})=>(this.id||aU("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&&aI("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||aC("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 ak().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ak().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let a=await ak().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ak().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let a=await ak().getBaseIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ak().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let a=await ak().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ak().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithSolana=async({walletName:e,unsafeMetadata:a,legalAccepted:t})=>{let r=await ak().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:r,generateSignature:a=>ak().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=rF.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(T(e)&&I(e))return await rF.clerk.__internal_environment.reload(),h();throw e}),{externalAccount:p}=m,{status:g,externalVerificationRedirectURL:b}=p;"unverified"===g&&b?a(b):aP(g,rF.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eL);authenticateWithPopup=async e=>{let{popup:a}=e||{};return a||aI("popup"),rC(rF.clerk,"signUp",this.authenticateWithRedirectOrPopup,e,e=>{a.location.href=e instanceof URL?e.toString():e})};update=e=>this._basePatch({body:rR(e)});upsert=e=>this.id?this.update(e):this.create(e);validatePassword=(e,a)=>{if(rF.clerk.__internal_environment?.userSettings.passwordSettings)return rU(rT(),{...rF.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 tZ(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),t4.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 rF.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){if(!e.strategy)return!1;let a=rF.clerk.__internal_environment.displayConfig.captchaOauthBypass;return!!(a.some(a=>a===e.strategy)||e.transfer&&a.some(e=>e===rF.clerk.client.signIn.firstFactorVerification.strategy))}__experimental_getEnterpriseConnections=()=>aF._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new rN(e)))}class rD{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 aM(rF.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?rR(e.unsafeMetadata):void 0,locale:e.locale??ap()};await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:i})}async create(e){return rO(this.#ep,async()=>{await this._create(e)})}async update(e){return rO(this.#ep,async()=>{let a={...e,unsafeMetadata:e.unsafeMetadata?rR(e.unsafeMetadata):void 0};await this.#ep.__internal_basePatch({path:this.#ep.pathRoot,body:a})})}async password(e){return rO(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?rR(e.unsafeMetadata):void 0};await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:i})})}async sendEmailCode(){return rO(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification"})})}async verifyEmailCode(e){let{code:a}=e;return rO(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 rO(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 rO(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 rO(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:rF.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:h};if(c){let e=rI(rF.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(T(e)&&I(e))return await rF.clerk.__internal_environment.reload(),p();throw e});let{status:g,externalVerificationRedirectURL:b}=this.#ep.verifications.externalAccount;"unverified"===g&&b&&(c?(await rP(rF.clerk,{popup:c,externalVerificationRedirectURL:b}),await this.#ep.reload()):eL(b))})}async web3(e){let{strategy:a,unsafeMetadata:t,legalAccepted:r}=e,i=a.replace("web3_","").replace("_signature","");return rO(this.#ep,async()=>{let e,n,s;switch(i){case"metamask":e=await ak().getMetamaskIdentifier(),n=ak().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await ak().getCoinbaseWalletIdentifier(),n=ak().generateSignatureWithCoinbaseWallet;break;case"base":e=await ak().getBaseIdentifier(),n=ak().generateSignatureWithBase;break;case"okx_wallet":e=await ak().getOKXWalletIdentifier(),n=ak().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||aC("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??eP("__clerk_ticket");return this.create({...e,ticket:a??void 0})}async finalize(e){let{navigate:a}=e||{};return rO(this.#ep,async()=>{if(!this.#ep.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#em=!0,await rF.clerk.setActive({session:this.#ep.createdSessionId,navigate:a})})}}class rN extends aF{id;name;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name),this}}class rW extends aF{pathRoot="tokens";jwt;static async create(e,a={},t=!1){return new rW(await aF._fetch({body:a,method:"POST",path:e,search:t?"debug=skip_cache":void 0}),e)}constructor(e,a){super(),a&&(this.pathRoot=a),e?.jwt&&(this.jwt=am(e.jwt))}getRawString=()=>this.jwt?.claims.__raw||"";fromJSON(e){return e&&(this.jwt=am(e.jwt)),this}__internal_toSnapshot(){return{object:"token",id:this.id||"",jwt:this.getRawString()}}}class rL extends aF{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=aD(e.updated_at),this.createdAt=aD(e.created_at)),this}}class r$ extends aF{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=aD(e.updated_at),this.createdAt=aD(e.created_at)),this}}class rK extends aF{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 rK}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case tN:return this.primaryEmailAddressId===e.id;case rf:return this.primaryPhoneNumberId===e.id;case rH:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:a}=e||{};return new tN({email_address:a},this.path()+"/email_addresses/").create()};createPasskey=()=>rb.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:a}=e||{};return new rf({phone_number:a},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:a}=e||{};return new rH({web3_wallet:a},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:a,redirectUrl:t,additionalScopes:r}=e||{};return new ra((await aF._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:a,redirect_url:t,additional_scope:r}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new rL((await aF._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new rL((await aF._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new tT((await aF._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new r$((await aF._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);update=e=>this._basePatch({body:rR(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=>(t4.emit(t3,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await rS.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:a}=e||{};return null===a?ri.delete(`${this.path()}/profile_image`):ri.create(`${this.path()}/profile_image`,{file:a})};getOrganizationInvitations=e=>rJ.retrieve(e);getOrganizationSuggestions=e=>rh.retrieve(e);getOrganizationMemberships=e=>ru.retrieve(e);leaveOrganization=async e=>new tT((await aF._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);initializePaymentMethod=e=>tg(e);addPaymentMethod=e=>tb(e);getPaymentMethods=e=>tf(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 tN(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 rf(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 rH(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 ra(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new rb(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new ru(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new t2(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=aD(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=aD(e.legal_accepted_at)),this.updatedAt=aD(e.updated_at||void 0),this.createdAt=aD(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 rB{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 rJ extends aF{id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await aF._fetch({path:"/me/organization_invitations",method:"GET",search:a7(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rJ(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=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}}let rV={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 rG extends aF{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:{...rV,name:"phone_number"},username:{...rV,name:"username"},web3_wallet:{...rV,name:"web3_wallet"},first_name:{...rV,name:"first_name"},last_name:{...rV,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:{...rV,name:"authenticator_app"},backup_code:{...rV,name:"backup_code"},passkey:{...rV,name:"passkey"}};enterpriseSSO={enabled:!1};passkeySettings={allow_autofill:!1,show_sign_in_button:!1};passwordSettings={};signIn={second_factor:{required:!1,enabled:!1}};signUp={allowlist_only:!1,captcha_enabled:!1,legal_consent_enabled:!1,mode:"public",progressive:!0};social={};usernameSettings={};get authenticatableSocialStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled&&e.authenticatable).map(([,e])=>e.strategy).sort():[]}get enabledFirstFactorIdentifiers(){return this.attributes?Object.entries(this.attributes).filter(([e,a])=>a.used_for_first_factor&&!e.startsWith("web3")).map(([e])=>e):[]}get socialProviderStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled).map(([,e])=>e.strategy).sort():[]}get web3FirstFactors(){return this.attributes?Object.entries(this.attributes).filter(([e,a])=>a.used_for_first_factor&&e.startsWith("web3")).map(([,e])=>e.first_factors).flat():[]}get alternativePhoneCodeChannels(){return this.attributes?Object.entries(this.attributes).filter(([e,a])=>a.used_for_first_factor&&"phone_number"===e).map(([,e])=>e?.channels?.filter(e=>"sms"!==e)||[]).flat():[]}constructor(e=null){super(),this.fromJSON(e)}get instanceIsPasswordBased(){return!!(this.attributes?.password?.enabled&&this.attributes.password?.required)}get hasValidAuthFactor(){return!!(this.attributes?.email_address?.enabled||this.attributes?.phone_number?.enabled||this.attributes.password?.required&&this.attributes.username?.required)}fromJSON(e){return e&&(this.attributes=this.withDefault(e.attributes?Object.fromEntries(Object.entries(e.attributes).map(e=>[e[0],{...e[1],name:e[0]}])):null,this.attributes),this.actions=this.withDefault(e.actions,this.actions),this.enterpriseSSO=this.withDefault(e.enterprise_sso,this.enterpriseSSO),this.passkeySettings=this.withDefault(e.passkey_settings,this.passkeySettings),this.passwordSettings=e.password_settings?{...e.password_settings,min_length:Math.max(e.password_settings?.min_length??8,8),max_length:e.password_settings?.max_length===0?72:Math.min(e.password_settings?.max_length??72,72)}:this.passwordSettings,this.signIn=this.withDefault(e.sign_in,this.signIn),this.signUp=this.withDefault(e.sign_up,this.signUp),this.social=this.withDefault(e.social,this.social),this.usernameSettings=e.username_settings?{...e.username_settings,min_length:Math.max(e.username_settings?.min_length??4,4),max_length:Math.min(e.username_settings?.max_length??64,64)}:this.usernameSettings),this}__internal_toSnapshot(){return{actions:this.actions,attributes:this.attributes,passkey_settings:this.passkeySettings,password_settings:this.passwordSettings,sign_in:this.signIn,sign_up:this.signUp,social:this.social}}}class rH extends aF{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 tY(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}class rQ extends aF{pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=aD(e.updated_at),this.createdAt=aD(e.created_at)),this}static async join(e){return new rQ((await aF._fetch({path:"/waitlist",method:"POST",body:e}))?.response)}}function rY(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 rX(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(tP.isClientResource(e))return e.id!==a.id||e.updatedAt.getTime()<a.updatedAt.getTime()||e.sessions.length!==a.sessions.length;if(rq.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&&rY(t.user,r.user))}if(rK.isUserResource(e))return rY(e,a)}catch{}return!0}(e,a)?e:a}let rZ="__clerk_db_jwt";function r1(e,a){let t=new URL(e),r=t.searchParams.get(rZ);t.searchParams.delete(rZ);let i=r||a;return i&&t.searchParams.set(rZ,i),t}let r2=e=>{let a=new URL(e);return a.searchParams.delete(rZ),a},r0=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 r9(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 r3=function e(a,t){function r(e,r,i){if("undefined"!=typeof document){"number"==typeof(i=r9({},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,"",r9({},a,{expires:-1}))},withAttributes:function(a){return e(this.converter,r9({},this.attributes,a))},withConverter:function(a){return e(r9({},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 r8(e){return{get:()=>r3.get(e),set(a,t={}){r3.set(e,a,t)},remove(a){r3.remove(e,a)}}}let r5=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function r4(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 r6=r8("__clerk_test_etld"),r7="__client_uat",ie="__session",ia=()=>{let e=ab()?"None":"Lax",a=r5(e);return{sameSite:e,secure:a,partitioned:!1}};async function it(e){let a;try{a=await em(e)}catch(o){var t;t=`Suffixed cookie failed due to ${o.message} (secure-context: ${window.isSecureContext}, url: ${window.location.href})`,G.has(t)||(console.log(t),G.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 ir=()=>{let e=ab()?"None":"Lax",a=r5(e);return{sameSite:e,secure:a}};var ii=i(945),is=i.n(ii);class io{lock=(function(e){let a=new(is());return window.addEventListener("beforeunload",async()=>{await a.releaseLock(e)}),{acquireLockAndRun:async t=>{if("locks"in navigator&&isSecureContext){let a=new AbortController,r=setTimeout(()=>a.abort(),4999);return await navigator.locks.request(e,{signal:a.signal},async()=>(clearTimeout(r),await t())).catch(()=>!1)}if(await a.acquireLock(e,5e3))try{return await t()}finally{await a.releaseLock(e)}}}})("clerk.lock.refreshSessionToken");workerTimers=tF();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 il{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,a,t,r){let i=await it(e.publishableKey),n=new il(e,a,i,t,r);return await n.setup(),n}constructor(e,a,r,i,n){this.clerk=e,this.instanceType=i,this.clerkEventBus=n,t4.on(t9,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),t4.on(t3,()=>this.handleSignOut()),this.refreshTokenOnFocus(),this.startPollingForToken(),this.clientUat=(e=>{let a=r8(r7),r=r8(ep(r7,e));return{set:e=>{let i=r4(Date.now(),1),n=ab()?"None":"Strict",s=r5(n),o=function(e=window.location.hostname,a=r6){if(t)return t;if(["localhost","127.0.0.1","0.0.0.0"].includes(e))return e;let r=e.split(".");if(1===r.length)return e;for(let e=r.length-2;e>=0;e--){let i=r.slice(e).join(".");if(a.set("1",{domain:i}),"1"===a.get())return a.remove({domain:i}),t=i,i;a.remove({domain:i})}}(),l="0";e&&e.updatedAt&&e.signedInSessions.length>0&&(l=Math.floor(e.updatedAt.getTime()/1e3).toString()),r.remove(),a.remove(),r.set(l,{domain:o,expires:i,partitioned:!1,sameSite:n,secure:s}),a.set(l,{domain:o,expires:i,partitioned:!1,sameSite:n,secure:s})},get:()=>parseInt(r.get()||a.get()||"0",10)}})(r),this.sessionCookie=(e=>{let a=r8(ie),t=r8(ep(ie,e)),r=()=>{let e=ia();a.remove(e),t.remove(e)};return{set:e=>{let i=r4(Date.now(),1),{sameSite:n,secure:s,partitioned:o}=ia();o&&r(),a.set(e,{expires:i,sameSite:n,secure:s,partitioned:o}),t.set(e,{expires:i,sameSite:n,secure:s,partitioned:o})},remove:r,get:()=>t.get()||a.get()}})(r),this.activeCookie=(()=>{let e=r8("clerk_active_context"),a={secure:r5("None")};return{set:t=>{e.set(t,a)},get:()=>e.get(),remove:()=>e.remove(a)}})(),this.devBrowser=function({cookieSuffix:e,frontendApi:a,fapiClient:t}){let r,i,n=(r=r8(rZ),i=r8(ep(rZ,e)),{get:()=>i.get()||r.get(),set:e=>{let a=r4(Date.now(),1),{sameSite:t,secure:n}=ir();i.set(e,{expires:a,sameSite:t,secure:n}),r.set(e,{expires:a,sameSite:t,secure:n})},remove:()=>{let e=ir();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(!ek(a))return;t.onBeforeRequest(e=>{let a=s();a&&e?.url&&(e.url=r1(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(rZ)||"",r2(r0(e)).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",r2(r0(e))),r);if(i)return void o(i);if(n.get())return;let l=t.buildUrl({path:"/dev_browser"}),c=await fetch(l.toString(),{method:"POST"});if(!c.ok){let e=function(e=[]){return e.length>0?e.map(e=>new k(e)):[]}((await c.json()).errors);e[0]?aq(e[0].longMessage):aq()}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(`${a_} Missing dev browser jwt. Please contact support.`);return r1(e,a)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new io,this.poller.startPollingForSessionToken(()=>this.refreshSessionToken()))}stopPollingForToken(){this.poller&&(this.poller.stopPollingForSessionToken(),this.poller=null)}refreshTokenOnFocus(){window.addEventListener("focus",()=>{"visible"===document.visibilityState&&this.refreshSessionToken({updateCookieImmediately:!0})})}async refreshSessionToken({updateCookieImmediately:e=!1}={}){if(this.clerk.session)try{let a=await this.clerk.session.getToken();e&&this.updateSessionCookie(a)}catch(e){return this.handleGetTokenError(e)}}updateSessionCookie(e){if(document.hasFocus()||this.isCurrentContextActive())return e||d()||ae.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(T(e)||E(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(P(e))return void this.clerk.handleUnauthenticated().catch(e9);this.clerkEventBus.emit(g,"degraded")}}handleSignOut(){this.activeCookie.remove(),this.sessionCookie.remove(),this.setClientUatCookieForDevelopmentInstances()}setActiveContextInStorage(){let e=this.clerk.session?.id||"",a=this.clerk.organization?.id||"",t=`${e}:${a}`;":"!==t?this.activeCookie.set(t):this.activeCookie.remove()}isCurrentContextActive(){let e=this.activeCookie.get();if(!e)return!0;let[a,t]=e.split(":"),r=this.clerk.session?.id||"",i=this.clerk.organization?.id||"";return a===r&&t===i}getSessionCookie(){return this.sessionCookie.get()}}class ic{clerk;captchaChallenge;timers;constructor(e,a=new aM(e),t=tF()){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 id=["/client","/waitlist"];class iu{async getBaseFapiProxyOptions(){let e=await aF.clerk.session?.getToken();if(!e)throw new U("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 aF._fetch({...await this.getBaseFapiProxyOptions(),method:"GET",path:"/api_keys",search:a7({...e,subject:e?.subject??aF.clerk.organization?.id??aF.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new aN(e))}})}async create(e){return new aN(await aF._fetch({...await this.getBaseFapiProxyOptions(),path:"/api_keys",method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??aF.clerk.organization?.id??aF.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new aN(await aF._fetch({...await this.getBaseFapiProxyOptions(),method:"POST",path:`/api_keys/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let ih=new Map;class im{#es=!1;load(e){let a=e?.protectConfig;if(a?.loaders&&Array.isArray(a.loaders)&&0!==a.loaders.length&&!this.#es){if(s())for(let e of(this.#es=!0,a.loaders))try{this.applyLoader(e)}catch(e){H(`[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 H(`[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:H(`[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 H(`[protect] loader target element not found: ${t}`);e.appendChild(r);return}H(`[protect] loader target is invalid: ${t}`)}}}class ip{signInResourceSignal=ta;signInErrorSignal=tt;signInFetchSignal=tr;signInSignal=ti;signUpResourceSignal=tn;signUpErrorSignal=ts;signUpFetchSignal=to;signUpSignal=tl;__internal_effect=a0;__internal_computed=a2;constructor(){t4.on("resource:update",this.onResourceUpdated),t4.on("resource:error",this.onResourceError),t4.on("resource:fetch",this.onResourceFetch)}onResourceError=e=>{e.resource instanceof rE&&this.signInErrorSignal({error:e.error}),e.resource instanceof rF&&this.signUpErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof rE){if(ig(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof rF){if(ig(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}};onResourceFetch=e=>{e.resource instanceof rE&&this.signInFetchSignal({status:e.status}),e.resource instanceof rF&&this.signUpFetchSignal({status:e.status})}}function ig(e,a){return!a?.id&&e&&e.__internal_future?.hasBeenFinalized===!1}let ib="cannot_render_billing_disabled",iy="cannot_render_user_missing",ik="cannot_render_organizations_disabled",iw="cannot_render_organization_missing",iv="cannot_render_single_session_enabled",ij={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 iz{static version="6.0.0-snapshot.v20251218165926";static sdkMetadata={name:"@clerk/clerk-js",version:"6.0.0-snapshot.v20251218165926"};static _billing;static _apiKeys;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new ip;internal_last_error=null;environment;#eg;#eb="";#ef;#ey;#ek;#ew;#ev;#ej=null;#ez;#e_;#ex;#eq="loading";#eS=[];#eU=[];#eA={};#eC=null;#eI=0;#eP=p();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 iz.version}set sdkMetadata(e){iz.sdkMetadata=e}get sdkMetadata(){return iz.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#eq}get isSatellite(){return!!ag()&&e0(this.#eA.isSatellite,new URL(window.location.href),!1)}get domain(){if(ag()){let e=function(e=""){return(e||"").replace(/^.+:\/\//,"")}(e0(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(ag()){let e=e0(this.#ey,new URL(window.location.href));return!e||e$(e)||eK(e)||au.throwInvalidProxyUrl({url:e}),e?eK(e)?new URL(e,window.location.origin).toString():e:""}return""}get frontendApi(){let e=eu(this.publishableKey);return e?e.frontendApi:au.throwInvalidPublishableKeyError({key:this.publishableKey})}get instanceType(){return this.#ex}get isStandardBrowser(){return this.#eA.standardBrowser||!1}get billing(){return iz._billing||(iz._billing=new te),iz._billing}get apiKeys(){return iz._apiKeys||(iz._apiKeys=new iu),iz._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=ih.get(c);if(d)return d.signals.computedSignal();let u=(t=a1({resource:null}),r=a1({error:null}),i=a1({status:"idle"}),n=a2(()=>{let e=t().resource,a=r().error,n=i().status;return{errors:tc(a,{}),fetchStatus:n,checkout:e}}),{resourceSignal:t,errorSignal:r,fetchSignal:i,computedSignal:n}),h=new th(u,{..."organization"===s?{orgId:e.organization?.id}:{},planId:o,planPeriod:l});return ih.set(c,{resource:h,signals:u}),u.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#eA[e]}get isSignedIn(){return this?.session?.status!=="pending"&&!!this.session}constructor(e,a){if(!(e=(e||"").trim()))return au.throwMissingPublishableKeyError();const t=eu(e);if(!t)return au.throwInvalidPublishableKeyError({key:e});this.#ef=a?.domain,this.#ey=a?.proxyUrl,this.environment=re.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-snapshot.v20251218165926"),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&&!id.some(e=>t.startsWith(e))&&r&&s.append("_clerk_session_id",r),eb([...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)),ej({base:i.origin,pathname:`${s}/${r}${t}`,search:n(a)},{stringify:!1})}let i="production"===e.instanceType?e.domain:"";return ej({base:`https://${i||e.frontendApi}`,pathname:`${r}${t}`,search:n(a)},{stringify:!1})}async function o(a,t){let n,o={...a},{method:l="GET",body:d}=o;!d||"object"!=typeof d||d instanceof FormData||(o.body=function(e){if(!e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype)return e;let a={};for(let[t,r]of Object.entries(e))void 0!==r&&(a[t]=r);return a}(d)),o.url=s({...o,sessionId:e.getSessionId()}),o.headers=new Headers(o.headers),"GET"===l||d instanceof FormData||o.headers.has("content-type")||o.headers.set("content-type","application/x-www-form-urlencoded"),"application/x-www-form-urlencoded"===o.headers.get("content-type")&&(o.body=d?eb(d,{keyEncoder:Z}):d);let u=await r(o),h="GET"===l?"GET":"POST",m=o.url,p={...o,method:h,credentials:o.credentials||"include"};try{if(u){let e=t?.fetchMaxTries??(c()?4:11);n=await ai(()=>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();ae.error("network error",{error:a,url:e,method:l},"fapiClient");throw Error(`${a_} 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||ae.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(g,"loading"),this.#eP.prioritizedOn(g,e=>this.#eq=e),aF.clerk=this,this.#ew=new im}getFapiClient=()=>this.#e_;load=async e=>{if(ae.info("load() start",{},"clerk"),!this.loaded){if("development"!==this.#ex||e?.unsafe_disableDevelopmentModeConsoleWarning||H("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.#eA=this.#eO(e),this.#eA.clerkUiCtor&&(this.#ez=Promise.resolve(this.#eA.clerkUiCtor).then(e=>new e(()=>this,()=>this.environment,this.#eA,new as))),"development"===this.#ex&&(this.#eA.routerPush||this.#eA.routerReplace)&&(!this.#eA.routerPush||!this.#eA.routerReplace)){let e=this.#eA.routerPush?"routerReplace":"routerPush";H(`Clerk: Both \`routerPush\` and \`routerReplace\` need to be defined, but \`${e}\` is not defined. This may cause issues with navigation in your application.`)}t4.on(t5,()=>{this.#eT(this.session),this.#eE()}),this.#eA.sdkMetadata&&(iz.sdkMetadata=this.#eA.sdkMetadata),!1!==this.#eA.telemetry&&(this.telemetry=new eH({clerkVersion:iz.version,samplingRate:1,perEventSampling:!this.#eA.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#eA.telemetry}),this.#eA.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=e2(e);if(t){a=t;break}}else a=e2(t);return{themeName:a}}(this.#eA.appearance)}));try{this.#eA.standardBrowser?await this.#eM():await this.#eR();let e=this.#eA.telemetry,a=!1!==e&&!e?.disabled,t=!!this.#eA.__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(e5)return;let{enabled:a=!1,...t}=e;a&&(e3=!0,e5=!0,e7(t))}({enabled:!0,...s?{logLevel:s}:{},...a&&this.telemetry?{telemetryCollector:this.telemetry}:{}}),this.#ew?.load(this.environment),ae.info("load() complete",{},"clerk")}catch(e){throw this.#eP.emit(g,"error"),ae.error("load() failed",{error:e},"clerk"),e}}};#eF(){let e;return!!(!this.#eA.signUpUrl&&this.#eA.signInUrl&&(e=this.#eA.signInUrl,!eg.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:e9,r="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e9,i=e&&"object"==typeof e?e:a||{},n=i?.redirectUrl||this.buildAfterSignOutUrl();ae.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=ao(this.#eA.standardBrowser);t4.emit(t3,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.#eA.experimental?.persistClient??!0?await this.client.removeSessions():await this.client.destroy(),await o(),ae.info("signOut() complete",{redirectUrl:ez(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(),ae.info("signOut() complete",{redirectUrl:ez(n)},"clerk"))};openGoogleOneTap=e=>{this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("googleOneTap",e||{})),this.telemetry?.record(e1("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(N(this,this.environment)){if("development"===this.#ex)throw new U(eD.cannotOpenSignInOrSignUp,{code:iv});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(e1("SignIn",e,a))};closeSignIn=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(W(this,this.environment)){if("development"===this.#ex)throw new U(eD.cannotRenderAnyBillingComponent("Checkout"),{code:ib});return}if(!this.user){if("development"===this.#ex)throw new U(eD.cannotOpenCheckout,{code:iy});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(W(this,this.environment)){if("development"===this.#ex)throw new U(eD.cannotRenderAnyBillingComponent("PlanDetails"),{code:ib});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openDrawer("planDetails",e||{})),this.telemetry?.record(e1("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 U(eD.cannotOpenUserProfile,{code:iy});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("userVerification",e||{})),this.telemetry?.record(e1("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||H(`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(eZ("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()=>(ax("Stripe"),{loadStripe:()=>Promise.resolve(null)});openSignUp=e=>{if(N(this,this.environment)){if("development"===this.#ex)throw new U(eD.cannotOpenSignInOrSignUp,{code:iv});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("signUp",e||{})),this.telemetry?.record(e1("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 U(eD.cannotOpenUserProfile,{code:iy});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(e1("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 U(eD.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:ik})}});if(a){if(!this.organization){if("development"===this.#ex)throw new U(eD.cannotRenderComponentWhenOrgDoesNotExist,{code:iw});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("organizationProfile",e||{})),this.telemetry?.record(e1("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 U(eD.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:ik})}});a&&(this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("createOrganization",e||{})),this.telemetry?.record(e1("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(e1("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(eZ(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(eZ(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(eZ(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 U(eD.cannotRenderComponentWhenUserDoesNotExist,{code:iy});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(eZ(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 U(eD.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:ik})}});if(!t)return;let r=!!this.user;if(!this.organization&&r){if("development"===this.#ex)throw new U(eD.cannotRenderComponentWhenOrgDoesNotExist,{code:iw});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(eZ(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 U(eD.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:ik})}});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(eZ(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 U(eD.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:ik})}});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(eZ(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 U(eD.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:ik})}});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(eZ(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(eZ(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(eZ(t,a))};unmountWaitlist=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountPricingTable=(e,a)=>{if(W(this,this.environment)){if("development"===this.#ex)throw new U(eD.cannotRenderAnyBillingComponent("PricingTable"),{code:ib});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(eZ(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(H("Clerk: <APIKeys /> component is in early access and not yet recommended for production use."),L(this,t=this.environment)&&$(this,t)){if("development"===this.#ex)throw new U(eD.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&$(this,this.environment)){if("development"===this.#ex)throw new U(eD.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if(L(this,this.environment)){if("development"===this.#ex)throw new U(eD.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(eZ(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 U(eD.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:ik})}});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(eZ(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(eZ("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,ae.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 ae.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 ae.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:e9,l="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e9,c=void 0===i?this.session:i;c?.status==="pending"&&(n={...this.#eA,...e},s=["taskUrls","navigate"],Object.keys(n).some(e=>s.includes(e))||H('Clerk: Session has pending tasks but no handling is configured. To handle pending tasks, provide either "taskUrls" for navigation to custom URLs or "navigate" for programmatic navigation. Without these options, users may get stuck on incomplete flows.'));let u=void 0!==a;if(c&&u){let e="string"==typeof a?a:a?.id;if("string"==typeof e&&e.startsWith("org_"))c.lastActiveOrganizationId=e||null;else{let a=c.user.organizationMemberships.find(a=>a.organization.slug===e),t=a?.organization.id||null,r=null===t;if(this.environment?.organizationSettings?.forceOrganizationSelection&&r)return;c.lastActiveOrganizationId=t}}c?.status!=="pending"&&await o(null===c?"sign-out":void 0),(ag()&&globalThis.document.hasFocus()||!this.#eA.standardBrowser)&&(await this.#eN(c),c=this.#eW(c?.id)),await c?.getToken()||(d()||ae.warn("Token is null when setting active session (offline)",{sessionId:c?.id},"clerk"),t4.emit(t9,{token:null}));let h=ao(this.#eA.standardBrowser),m=c?.status==="pending"&&c?.currentTask&&this.#eA.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?ej({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:rX((r=t).client,e.client),session:rX(r.session,e.session),user:rX(r.user,e.user),organization:rX(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||!ag())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.#eA.routerReplace?this.#eA.routerReplace:this.#eA.routerPush;if(ae.info(`Clerk is navigating to: ${t}`),this.#eA.routerDebug&&console.log(`Clerk is navigating to: ${t}`),"null"!==t.origin&&t.origin!==window.location.origin||!r)return void eL(t);let i={...a?.metadata?{__internal_metadata:a?.metadata}:{},windowNavigate:eL};return await r(ez(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.#eA,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eA(this.#eA,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#eA.afterSignOutUrl?this.buildUrlWithAuth(this.#eA.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#eA.newSubscriptionRedirectUrl?this.#eA.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?ej({base:this.#eA.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#eA.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#eA.afterMultiSessionSingleSignOutUrl):this.#eA.signInUrl?this.buildUrlWithAuth(ej({base:this.#eA.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.#eA.taskUrls?.[a.key];return t||ej({base:this.buildSignInUrl(e),hashPath:eM(a)},{stringify:!0})}#eB=async()=>{if(!ag())return;let e=new URLSearchParams({[K]:"true"}),a=eP(J);a&&e$(a)||function(){throw Error(`${a_} Invalid redirect_url. A valid http or https url should be used for the redirection.`)}();let t=ej({base:eP(J),searchParams:e},{stringify:!0});return this.navigate(this.buildUrlWithAuth(t))};redirectWithAuth=async e=>{if(ag())return this.navigate(this.buildUrlWithAuth(e))};redirectToSignIn=async e=>{if(ag())return this.navigate(this.buildSignInUrl(e))};redirectToSignUp=async e=>{if(ag())return this.navigate(this.buildSignUpUrl(e))};redirectToUserProfile=async()=>{if(ag())return this.navigate(this.buildUserProfileUrl())};redirectToCreateOrganization=async()=>{if(ag())return this.navigate(this.buildCreateOrganizationUrl())};redirectToOrganizationProfile=async()=>{if(ag())return this.navigate(this.buildOrganizationProfileUrl())};redirectToAfterSignIn=async()=>{if(ag())return this.navigate(this.buildAfterSignInUrl())};redirectToAfterSignUp=async()=>{if(ag())return this.navigate(this.buildAfterSignUpUrl())};redirectToAfterSignOut=async()=>{if(ag())return this.navigate(this.buildAfterSignOutUrl())};redirectToWaitlist=async()=>{if(ag())return this.navigate(this.buildWaitlistUrl())};redirectToTasks=async e=>{if(ag())return this.navigate(this.buildTasksUrl(e))};handleEmailLinkVerification=async(e,a)=>{if(!this.client)return;let t=eP("__clerk_status");if("expired"===t)throw new x(S.Expired);if("client_mismatch"===t)throw new x(S.ClientMismatch);if("verified"!==t)throw new x(S.Failed);let r=eP("__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):e9;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||ej({base:i.signInUrl,hashPath:"/factor-one"},{stringify:!0})),m=c(e.secondFactorUrl||ej({base:i.signInUrl,hashPath:"/factor-two"},{stringify:!0})),p=c(e.resetPasswordUrl||ej({base:i.signInUrl,hashPath:"/reset-password"},{stringify:!0})),g=new eA(this.#eA,e),b=c(e.continueSignUpUrl||ej({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=eT();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||ej({base:i.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),verifyPhonePath:e.verifyPhoneNumberUrl||ej({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 eR(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:aS("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:aS("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 tP.getOrCreateInstance().fetch();if(this.updateClient(a),this.session)return;return e.broadcast&&t4.emit(t3,null),this.setActive({session:null})}catch(e){if(T(e)&&[403,500].includes(e.status))return this.setActive({session:null});throw e}};authenticateWithGoogleOneTap=async e=>(ax("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 ak().getWeb3Identifier({provider:u,walletName:o});switch(u){case"metamask":l=ak().generateSignatureWithMetamask;break;case"base":l=ak().generateSignatureWithBase;break;case"coinbase_wallet":l=ak().generateSignatureWithCoinbaseWallet;break;case"solana":if(!o)throw new U("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});l=e=>ak().generateSignatureWithSolana({...e,walletName:o});break;default:l=ak().generateSignatureWithOKXWallet}let m=e=>()=>t&&"function"==typeof t?t(e):this.navigate(e),p=m(s||ej({base:d.signInUrl,hashPath:"/factor-two"},{stringify:!0})),g=m(a||ej({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(ad(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 eR(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})=>rc.create({name:e,slug:a});getOrganization=async e=>rc.get(e);joinWaitlist=async({emailAddress:e})=>rQ.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.#eA.selectInitialSession?this.#eA.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:e9)(),this.#eT(e),this.session?.lastActiveToken||d()||ae.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),t4.emit(t9,{token:this.session?.lastActiveToken})}this.#eE()};get __internal_environment(){return this.environment}__internal_setEnvironment=async e=>{this.environment=new re(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.#eA,...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({[J]:window.location.href});return ej({base:this.#eA.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"!==eP(K)&&!!this.isSatellite&&!!this.#ek?.isSignedOut();#eQ=()=>"production"!==this.#ex&&!this.isSatellite&&!!eP(J);#eY=async()=>{"development"===this.instanceType?await this.navigate(this.#eV()):"production"===this.instanceType&&await this.navigate(this.#eG())};#eX=(e,a)=>{let t;try{t=new URL(e)}catch{throw Error(`${a_} The signInUrl needs to have a absolute url format.`)}t.origin===a&&function(){throw Error(`${a_} The signInUrl needs to be on a different origin than your satellite application.`)}()};#eZ=()=>{this.isSatellite&&("development"!==this.#ex||this.#eA.signInUrl||function(){throw Error(`${a_} Missing signInUrl. A satellite application needs to specify the signInUrl for development instances.`)}(),this.proxyUrl||this.domain||function(){throw Error(`${a_} Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl.`)}(),this.#eA.signInUrl&&this.#eX(this.#eA.signInUrl,window.location.origin))};#eM=async()=>{if(this.#ek=await il.create(this,this.#e_,this.#ex,this.#eP),this.#eZ(),this.#eH())return void await this.#eY();if(this.#eQ())return void await this.#eB();this.#eC=(()=>{if(!s())return{onPageFocus:e9};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=ew.get(e);void 0===a&&(a=en.some(a=>e.startsWith("accounts.")&&e.endsWith(a))||es.some(a=>e.endsWith(a)&&!e.endsWith(".clerk"+a)),ew.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=re.getInstance().fetch({touch:a}).then(e=>this.updateEnvironment(e)).catch(()=>{++t;let e=az.getItem(aw,null);e&&this.updateEnvironment(new re(e))}),r=async()=>tP.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(async e=>{if(P(e))throw e;++t;let a=this.#ek?.getSessionCookie(),r=function(e){let a;try{a=new rW({jwt:e||"",object:"token",id:void 0})}catch{a=null}if(tP.clearInstance(),!a?.jwt)return tP.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}=r_(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 tP.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(ad(e,"requires_captcha"))await r();else throw e}if(this.#ek?.setClientUatCookieForDevelopmentInstances(),await this.#e2())return;break}catch(e){if(ad(e,"dev_browser_unauthenticated"))await this.#ek.handleUnauthenticatedDevBrowser();else if(!d())return void console.warn(e);else throw e}r>=2&&function(){throw Error(`${a_} Something went wrong initializing Clerk.`)}()}this.#ev=new ic(this),this.#ev.start(),this.#e0(),this.#e9(),this.#e3(),this.#eP.emit(g,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([re.getInstance().fetch({touch:!1,fetchMaxTries:t}),tP.getOrCreateInstance().fetch({fetchMaxTries:t})])}catch(t){if(E(t)&&"network_error"===t.code&&this.shouldFallbackToCachedResources()){let t=await this.__internal_getCachedResources?.();e=new re(t?.environment),tP.clearInstance(),a=tP.getOrCreateInstance(t?.client),++r}else throw t}this.updateClient(a),this.updateEnvironment(e),this.#eP.emit(g,r>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,a]=await Promise.all([re.getInstance().fetch({touch:!1,fetchMaxTries:1}),tP.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=()=>{s()&&(this.#eC?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#eI>Date.now())&&(this.#eI=Date.now()+5e3,this.#eA.touchSession&&this.#eN(this.session))}),this.#ej?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),t4.on(t3,()=>{this.#ej?.postMessage({type:"signout"})}),t4.on(t8,()=>{az.setItem(aw,this.environment?.__internal_toSnapshot(),864e5)}))};#eN=async e=>{if(!e)return Promise.resolve();await e.touch().catch(e=>{P(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.#eA.__internal_keyless_claimKeylessApplicationUrl&&this.#ez?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#eA.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#eA.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#eA.__internal_keyless_dismissPrompt}})})};#eK=(e,a,t)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let r=this.#eA[e]||this.environment.displayConfig[e];this.#eF()&&(r=this.#eA.signInUrl);let i=new eA(this.#eA,a).toSearchParams(),n=new URLSearchParams(t||{}),s=ej({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,ef)).pathname,r=eS.includes(t)||eU.includes(t),e===a.host&&r);if(s||!o)return!1;let l=this.session,c=this.#eA.signInUrl||this.environment?.displayConfig.signInUrl,d=c&&window.location.href.startsWith(c),u=this.#eA.signUpUrl||this.environment?.displayConfig.signUpUrl,h=u&&window.location.href.startsWith(u);return i=new URL(n,ef),(!eS.includes(i.pathname)||!!l||!d&&!h)&&(await this.navigate(this.buildUrlWithAuth(n)),!0)};#eO=e=>({...ij,...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://${ev(a)}`),r.push(`https://*.${ev(a)}`),"development"===t&&r.push(`https://${a}`),r}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)});#e0=()=>{try{eO(K),eO(eC),eO(B),eO("__clerk_handshake"),eO("__clerk_handshake_nonce"),eO("__clerk_help")}catch{}};get #e$(){let e=eW;return this.#eA.allowedRedirectProtocols&&(e=e.concat(this.#eA.allowedRedirectProtocols)),e}}})();var s=exports;for(var o in n)s[o]=n[o];n.__esModule&&Object.defineProperty(s,"__esModule",{value:!0})})();
19
+ API Error: ${i}`,{data:a,status:e})}}(n,e);let r={data:e,status:n};if(429===n&&o){let e=o.get("retry-after");if(e){let a=parseInt(e,10);isNaN(a)||(r.retryAfter=a)}}throw new v(a||s,r)}return null}static _updateClient(e){if(!e)return;let a=e.client||e.meta?.client;a&&aF.clerk&&aF.clerk.updateClient(tP.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 aF._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 aF._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 aF._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=aF.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}function aD(e){let a=new Date(e||new Date);return a instanceof Date&&!isNaN(a.getTime())?a:new Date}class aN extends aF{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?aD(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?aD(e.last_used_at):null,this.updatedAt=aD(e.updated_at),this.createdAt=aD(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 aW extends aF{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?aD(e.claimed_at):null,this.claimedAt),this.reverification=this.withDefault(e.reverification,this.reverification),this.singleSessionMode=this.withDefault(e.single_session_mode,this.singleSessionMode),this.preferredChannels=this.withDefault(e.preferred_channels,this.preferredChannels)),this}__internal_toSnapshot(){return{claimed_at:this.claimedAt?this.claimedAt.getTime():null,id:this.id??"",object:"auth_config",reverification:this.reverification,single_session_mode:this.singleSessionMode}}}(f=y||(y={}))[f.None=0]="None",f[f.Mutable=1]="Mutable",f[f.Watching=2]="Watching",f[f.RecursedCheck=4]="RecursedCheck",f[f.Recursed=8]="Recursed",f[f.Dirty=16]="Dirty",f[f.Pending=32]="Pending";let aL=[],{link:a$,unlink:aK,propagate:aB,checkDirty:aJ,endTracking:aV,startTracking:aG,shallowPropagate:aH}=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?a9(e):a3(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):aL[aX++]=a}},unwatched(e){if("getter"in e){let a=e.deps;if(void 0!==a){e.flags=17;do a=aK(a,e);while(void 0!==a)}}else"previousValue"in e||a6.call(e)}}),aQ=0,aY=0,aX=0;function aZ(a){let t=e;return e=a,t}function a1(e){return a4.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function a2(e){return a5.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function a0(t){let r={fn:t,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==e?a$(r,e):void 0!==a&&a$(r,a);let i=aZ(r);try{r.fn()}finally{aZ(i)}return a6.bind(r)}function a9(e){let a=aZ(e);aG(e);try{let a=e.value;return a!==(e.value=e.getter(a))}finally{aZ(a),aV(e)}}function a3(e,a){return e.flags=1,e.previousValue!==(e.previousValue=a)}function a8(){for(;aY<aX;){let e=aL[aY];aL[aY++]=void 0,function e(a,t){if(16&t||32&t&&aJ(a.deps,a)){let e=aZ(a);aG(a);try{a.fn()}finally{aZ(e),aV(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)}aY=0,aX=0}function a5(){let t=this.flags;if(16&t||32&t&&aJ(this.deps,this)){if(a9(this)){let e=this.subs;void 0!==e&&aH(e)}}else 32&t&&(this.flags=-33&t);return void 0!==e?a$(this,e):void 0!==a&&a$(this,a),this.value}function a4(...a){if(a.length){let e=a[0];if(this.value!==(this.value=e)){this.flags=17;let e=this.subs;void 0!==e&&(aB(e),aQ||a8())}}else{let a=this.value;if(16&this.flags&&a3(this,a)){let e=this.subs;void 0!==e&&aH(e)}return void 0!==e&&a$(this,e),a}}function a6(){let e=this.deps;for(;void 0!==e;)e=aK(e,this);let a=this.subs;void 0!==a&&aK(a),this.flags=0}function a7(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 te{static #ed="/billing";static path(e,a){let{orgId:t}=a||{},r=t?`/organizations/${t}`:"/me";return`${r}${te.#ed}${e}`}getPlans=async e=>{let{for:a,...t}=e||{},r={...t,payer_type:"organization"===a?"org":"user"};return await aF._fetch({path:`${te.#ed}/plans`,method:"GET",search:a7(r)}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new tw(e))}})};getPlan=async e=>new tw(await aF._fetch({path:`${te.#ed}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await aF._fetch({path:te.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new tz(e?.response));getStatements=async e=>{let{orgId:a,...t}=e;return await aF._fetch({path:te.path("/statements",{orgId:a}),method:"GET",search:a7(t)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new tv(e))}})};getStatement=async e=>new tv((await aF._fetch({path:te.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:a,...t}=e;return await aF._fetch({path:te.path("/payment_attempts",{orgId:a}),method:"GET",search:a7(t)}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new tm(e))}})};getPaymentAttempt=async e=>new tm(await aF._fetch({path:te.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:a,...t}=e;return new tu((await aF._fetch({path:te.path("/checkouts",{orgId:a}),method:"POST",body:t}))?.response)}}let ta=a1({resource:null}),tt=a1({error:null}),tr=a1({status:"idle"}),ti=a2(()=>{let e=ta().resource,a=tt().error,t=tr().status;return{errors:tc(a,{identifier:null,password:null,code:null}),fetchStatus:t,signIn:e?e.__internal_future:null}}),tn=a1({resource:null}),ts=a1({error:null}),to=a1({status:"idle"}),tl=a2(()=>{let e=tn().resource,a=ts().error,t=to().status;return{errors:tc(a,{firstName:null,lastName:null,emailAddress:null,phoneNumber:null,password:null,username:null,code:null,captcha:null,legalAccepted:null}),fetchStatus:t,signUp:e?e.__internal_future:null}});function tc(e,a){let t={fields:{...a},raw:null,global:null};if(!e)return t;if(!T(e))return t.raw=[e],t.global=[D(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=[D(e)]),t}class td extends aF{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=aD(e.created_at)),e.updated_at&&(this.updatedAt=aD(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 tu extends aF{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 ty(e.payment_method):void 0,this.plan=new tw(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=ac(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change,e.free_trial_ends_at&&(this.freeTrialEndsAt=aD(e.free_trial_ends_at)),this.payer=new td(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>ai(()=>this._basePatch({path:te.path(`/checkouts/${this.id}/confirm`,{orgId:this.payer.organizationId}),body:e}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,a){if(!T(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 th{resource=new tu(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 tu.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new tu(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 tu.clerk.setActive({session:tu.clerk.session?.id,navigate:a})})}runAsyncCheckoutTask(e,a,t){var r,i,n;return void 0===tu.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()=>{++aQ,i.errorSignal({error:null}),i.fetchSignal({status:"fetching"}),t?.(),--aQ||a8(),++aQ;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"}),--aQ||a8()}})();return n.set(e,s),s})(e,a,t)}}class tm extends aF{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=al(e.amount),this.paidAt=e.paid_at?aD(e.paid_at):null,this.failedAt=e.failed_at?aD(e.failed_at):null,this.updatedAt=aD(e.updated_at),this.paymentMethod=e.payment_method?new ty(e.payment_method):null,this.subscriptionItem=new t_(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status),this}}let tp="/payment_methods",tg=async e=>{let{orgId:a,...t}=e;return new tk((await aF._fetch({path:te.path(`${tp}/initialize`,{orgId:a}),method:"POST",body:t}))?.response)},tb=async e=>{let{orgId:a,...t}=e;return new ty((await aF._fetch({path:te.path(tp,{orgId:a}),method:"POST",body:t}))?.response)},tf=async e=>{let{orgId:a,...t}=e??{};return await aF._fetch({path:te.path(tp,{orgId:a}),method:"GET",search:a7(t)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new ty(e))}})};class ty extends aF{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:aD(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:aD(e.updated_at)),this}async remove(e){let{orgId:a}=e??{};return new tT((await aF._fetch({path:te.path(`/payment_methods/${this.id}`,{orgId:a}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:a}=e??{};return await aF._fetch({path:te.path("/payers/default_payment_method",{orgId:a}),method:"PUT",body:{payment_method_id:this.id}}),null}}class tk extends aF{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 tw extends aF{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=al(e.fee),this.annualFee=e.annual_fee?al(e.annual_fee):null,this.annualMonthlyFee=e.annual_monthly_fee?al(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 rt(e))),this}}class tv extends aF{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=aD(e.timestamp),this.totals=ac(e.totals),this.groups=e.groups.map(e=>new tj(e))),this}}class tj{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=aD(e.timestamp),this.items=e.items.map(e=>new tm(e))),this}}class tz extends aF{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=aD(e.created_at),this.updatedAt=e.updated_at?aD(e.updated_at):null,this.activeAt=aD(e.active_at),this.pastDueAt=e.past_due_at?aD(e.past_due_at):null,e.next_payment&&(this.nextPayment={amount:al(e.next_payment.amount),date:aD(e.next_payment.date)}),this.subscriptionItems=(e.subscription_items||[]).map(e=>new t_(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1)),this}}class t_ extends aF{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 tw(e.plan),this.planPeriod=e.plan_period,this.status=e.status,this.createdAt=aD(e.created_at),this.pastDueAt=e.past_due_at?aD(e.past_due_at):null,this.periodStart=aD(e.period_start),this.periodEnd=e.period_end?aD(e.period_end):null,this.canceledAt=e.canceled_at?aD(e.canceled_at):null,this.amount=e.amount?al(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:al(e.credit.amount)}:void 0,this.isFreeTrial=this.withDefault(e.is_free_trial,!1)),this}async cancel(e){let{orgId:a}=e;return new tT((await aF._fetch({path:te.path(`/subscription_items/${this.id}`,{orgId:a}),method:"DELETE"}))?.response)}}let tx={build:(e,a,t)=>[e,a,t].filter(Boolean).join("-"),parse:(e,a,t)=>{let r=tx.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}},tq="clerk",tS=10,tU={broadcast:!0},tA={broadcast:!1};class tC{prefix;data;static fromKey(e){let[a,t,r=""]=e.split("::");return new tC(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 tI=((e=tq)=>{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=tS)=>{i();let n=new tC(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=tx.build(e.sessionId,e.template,e.organizationId);if(e.tokenId!==r)return void ae.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 rW({id:e.tokenId,jwt:e.tokenRaw,object:"token"})}catch(a){ae.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 ae.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 ae.debug("Ignoring older token broadcast",{existingIat:n,incomingIat:i,tabId:t,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}}catch(a){ae.warn("Existing entry compare failed; proceeding with broadcast update",{error:a,tabId:t,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}ae.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)},tA)},o=(i,n=tU)=>{let s=new tC(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=tx.extractTemplate(i.tokenId,e,n),o=tx.build(e,s,n);if(i.tokenId===o){let a=`bc_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;ae.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,tU)},size:()=>a.size}})();class tP extends aF{static instance;pathRoot="/client";sessions=[];signUp=new rF;signIn=new rE;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return tP.instance||(tP.instance=new tP(e)),tP.instance}static clearInstance(){tP.instance=null}static isClientResource(e){return!!e&&e instanceof tP}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(()=>{tI.clear(),this.id="",this.sessions=[],this.signUp=new rF(null),this.signIn=new rE(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=>(tI.clear(),e))}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return aF.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 rq(e)),this.signUp=new rF(e.sign_up),this.signIn=new rE(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?aD(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=aD(e.created_at||void 0),this.updatedAt=aD(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 tO extends aF{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 tT{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 tE extends aF{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 tM='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 tR=(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}},tF=()=>{let e=0,a=()=>e++,t=new Map,r=(e,a)=>e?.postMessage(a),i=e=>{t.get(e.data.id)?.()},n=tR(tM,{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:e9};let s=()=>{n||(n=tR(tM,{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 tD({delayInMs:e}={delayInMs:1e3}){let a,t=tF(),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 tN extends aF{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}=tD();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}=tD();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 tY(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new rr(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 tW=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 tL(e){try{let a=await navigator.credentials.create({publicKey:e});if(!a)return{error:new C("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 C(a.message,{code:"passkey_already_exists"}):"NotAllowedError"===a.name?new C(a.message,{code:"passkey_registration_cancelled"}):tB(a),publicKeyCredential:null}}}let t$=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 tK({publicKeyOptions:e,conditionalUI:a}){try{let t=await navigator.credentials.get({publicKey:e,mediation:a?"conditional":"optional",signal:t$.createAbortSignal()});if(!t)return{error:new C("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 C(t.message,{code:"passkey_retrieval_cancelled"}):tB(t),publicKeyCredential:null}}}function tB(e){return"AbortError"===e.name?new C(e.message,{code:"passkey_operation_aborted"}):"SecurityError"===e.name?new C(e.message,{code:"passkey_invalid_rpID_or_domain"}):e}function tJ(e){let a=tQ(e.challenge),t=(e.allowCredentials||[]).map(e=>({...e,id:tQ(e.id)}));return{...e,allowCredentials:t,challenge:a}}function tV(e){return{type:e.type,id:e.id,rawId:tH(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function tG(e){let a=e.response;return{...tV(e),response:{clientDataJSON:tH(a.clientDataJSON),authenticatorData:tH(a.authenticatorData),signature:tH(a.signature),userHandle:a.userHandle?tH(a.userHandle):null}}}let tH=tW.encode.bind(tW),tQ=tW.decode.bind(tW);class tY extends aF{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===aF.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=aD(e.expire_at||void 0),this.error=e.error?new k(e.error):null,this.channel=e.channel||void 0),this}__internal_toSnapshot(){var e;return{object:"verification",id:this.id||"",status:this.status,strategy:this.strategy,nonce:this.nonce,message:this.message,external_verification_redirect_url:this.externalVerificationRedirectURL?.toString()||null,attempts:this.attempts,expire_at:this.expireAt?.getTime()||null,error:(e=this.error,{code:e?.code||"",message:e?.message||"",long_message:e?.longMessage,meta:{param_name:e?.meta?.paramName,session_id:e?.meta?.sessionId,email_addresses:e?.meta?.emailAddresses,identifiers:e?.meta?.identifiers,zxcvbn:e?.meta?.zxcvbn,plan:e?.meta?.plan,is_plan_upgrade_possible:e?.meta?.isPlanUpgradePossible}}),verified_at_client:this.verifiedAtClient}}}class tX extends tY{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=tQ((a=JSON.parse(e.nonce)).user.id),r=tQ(a.challenge),i=(a.excludeCredentials||[]).map(e=>({...e,id:tQ(e.id)})),{...a,excludeCredentials:i,challenge:r,user:{...a.user,id:t}})),this}}class tZ{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new t1(e.email_address),this.phoneNumber=new t1(e.phone_number),this.web3Wallet=new t1(e.web3_wallet),this.externalAccount=new tY(e.external_account)):(this.emailAddress=new t1(null),this.phoneNumber=new t1(null),this.web3Wallet=new t1(null),this.externalAccount=new tY(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 t1 extends tY{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 t2 extends aF{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?aD(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new tY(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new t0(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 t0 extends aF{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=aD(e.created_at),this.updatedAt=aD(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 t9="token:update",t3="user:signOut",t8="environment:update",t5="session:tokenResolved",t4=p();class t6 extends aF{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 t7 extends aF{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 re extends aF{static instance;authConfig=new aW;displayConfig=new tE;maintenanceMode=!1;clientDebugMode=!1;pathRoot="/environment";userSettings=new rG;organizationSettings=new t7;commerceSettings=new tO;apiKeysSettings=new t6;protectConfig=new ry;static getInstance(){return re.instance||(re.instance=new re),re.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new aW(e.auth_config),this.displayConfig=new tE(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 t7(e.organization_settings),this.userSettings=new rG(e.user_settings),this.commerceSettings=new tO(e.commerce_settings),this.apiKeysSettings=new t6(e.api_keys_settings),this.protectConfig=new ry(e.protect_config)),this}fetch({touch:e,fetchMaxTries:a}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:a})).then(e=>(t4.emit(t8,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 ra extends aF{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 tY(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 rt extends aF{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 rr extends aF{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 ri extends aF{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 ri((await aF._fetch({path:e,method:"POST",body:r,headers:t}))?.response)}static async delete(e){return new ri((await aF._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 rn extends aF{id;name;organizationId;enrollmentMode;verification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:a}){return new rn((await aF._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:aD(e.verification.expires_at)}:this.verification=null),this}}class rs extends aF{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=aD(e.created_at),this.updatedAt=aD(e.updated_at),e.public_user_data&&(this.publicUserData=new rk(e.public_user_data))),this}}class ro extends aF{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=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}}class rl extends aF{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 ro(e)),this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}}class rc extends aF{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 rc((await aF._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new rc((await aF._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await aF._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:a7(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rl(e))}});getDomains=async e=>await aF._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:a7(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rn(e))}});getDomain=async({domainId:e})=>new rn((await aF._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getMembershipRequests=async e=>await aF._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:a7(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rs(e))}});createDomain=async e=>rn.create(this.id,{name:e});getMemberships=async e=>await aF._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:a7({...e,paginated:!0})}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new ru(e))}});getInvitations=async e=>await aF._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:a7(e)},{forceUpdateClient:!0}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rd(e))}});addMember=async({userId:e,role:a})=>await aF._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:a}}).then(e=>new ru(e?.response));inviteMember=async e=>rd.create(this.id,e);inviteMembers=async e=>rd.createBulk(this.id,e);updateMember=async({userId:e,role:a})=>await aF._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:a}}).then(e=>new ru(e?.response));removeMember=async e=>await aF._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new ru(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let a,t;return null===e?await aF._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new rc(e?.response)):("string"==typeof e?(a=e,t=new Headers({"Content-Type":"application/octet-stream"})):(a=new FormData).append("file",e),await aF._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:a,headers:t}).then(e=>new rc(e?.response)))};initializePaymentMethod=e=>tg({...e,orgId:this.id});addPaymentMethod=e=>tb({...e,orgId:this.id});getPaymentMethods=e=>tf({...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=aD(e.created_at),this.updatedAt=aD(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 aF._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:a},{forceUpdateClient:!0}))?.response;return this.fromJSON(t)}}class rd extends aF{id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:a,role:t}){return new rd((await aF._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 aF._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:t,role:r}}))?.response).map(e=>new rd(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=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}}class ru extends aF{id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await aF._fetch({path:"/me/organization_memberships",method:"GET",search:a7({...e,paginated:!0})}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new ru(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 rc(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new rk(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=aD(e.created_at),this.updatedAt=aD(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(`${a_} Calling OrganizationMembership.reload is not currently supported. Please contact support.`)}}class rh extends aF{id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await aF._fetch({path:"/me/organization_suggestions",method:"GET",search:a7(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rh(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=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}}function rm(){return l()&&"function"==typeof window.PublicKeyCredential}async function rp(){try{return rm()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function rg(){try{return"undefined"!=typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class rb extends aF{id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return aF._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new rb(e?.response))}static async attemptVerification(e,a){let t,r=(t=a.response,{...tV(a),response:{clientDataJSON:tH(t.clientDataJSON),attestationObject:tH(t.attestationObject),transports:t.getTransports()}});return aF._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(r)}}).then(e=>new rb(e?.response))}static async registerPasskey(){let e=rb.clerk.__internal_isWebAuthnSupported||rm,a=rb.clerk.__internal_createPublicCredentials||tL,t=rb.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||rg;if(!e())throw new C("Passkeys are not supported on this device.",{code:"passkey_not_supported"});let r=await this.create(),{verification:i}=r,n=i?.publicKey;if(n||aO("create"),n.authenticatorSelection?.authenticatorAttachment==="platform"&&!await t())throw new C("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 tT((await aF._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?aD(e.last_used_at):null,this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at),e.verification&&(this.verification=new tX(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 rf extends aF{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 tY(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new rr(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 ry extends aF{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 rk{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 rw={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"}},rv=new Set(["first_factor","second_factor","multi_factor"]),rj=new Set(["strict_mfa","strict","moderate","lax"]),rz=(e,a)=>{let{org:t,user:r}=r_(e),[i,n]=a.split(":"),s=n||i;return"org"===i?t.includes(s):"user"===i?r.includes(s):[...t,...r].includes(s)},r_=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 rx extends aF{status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new tY(null);secondFactorVerification=new tY(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new rq(e.session),this.level=e.level,this.supportedFirstFactors=et(e.supported_first_factors),this.supportedSecondFactors=et(e.supported_second_factors),this.firstFactorVerification=new tY(e.first_factor_verification),this.secondFactorVerification=new tY(e.second_factor_verification)),this}}class rq extends aF{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 rq}constructor(e){super(),this.fromJSON(e),this.#eu(this.lastActiveToken)}end=()=>(tI.clear(),this._basePost({action:"end"}));remove=()=>(tI.clear(),this._basePost({action:"remove"}));touch=()=>this._basePost({action:"touch",body:{active_organization_id:this.lastActiveOrganizationId}}).then(e=>(e.lastActiveToken&&t4.emit(t9,{token:e.lastActiveToken}),e));clearCache=()=>tI.clear();getToken=async e=>ai(()=>this._getToken(e),{factor:1.55,initialDelay:3e3,maxDelayBetweenRetries:5e4,jitter:!1,shouldRetry:(e,a)=>!P(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?rz(t,e.feature):e.plan&&r?rz(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&&rj.has(e),i="object"==typeof e&&(a=e.level,rv.has(a))&&"number"==typeof(t=e.afterMinutes)&&t>0;return(!!r||!!i)&&(e=>"string"==typeof e?rw[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&&tI.set({tokenId:this.#eh(),tokenResolver:Promise.resolve(e)})};#eh(e,a){let t=void 0===a?this.lastActiveOrganizationId:a;return tx.build(this.id,e,t)}startVerification=async({level:e})=>new rx((await aF._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 rx((await aF._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(tG(e.publicKeyCredential))}:{...e},new rx((await aF._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=rq.clerk.__internal_isWebAuthnSupported||rm,t=rq.clerk.__internal_getPublicCredentials||tK;if(!a())throw new C("Passkeys are not supported",{code:"passkey_not_supported"});let r=e?tJ(JSON.parse(e)):null;r||aO("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 rx((await aF._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>new rx((await aF._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=aD(e.expire_at),this.abandonAt=aD(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=aD(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.createdAt=aD(e.created_at),this.updatedAt=aD(e.updated_at),this.user=new rK(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new rk(e.public_user_data)),this.lastActiveToken=e.last_active_token?new rW(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:tI.get({tokenId:n},a),o=!t&&i===this.lastActiveOrganizationId;if(s){ae.debug("Using cached token (no fetch needed)",{tokenId:n},"session");let e=await s.tokenResolver;return o&&t4.emit(t9,{token:e}),e.getRawString()||null}ae.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=rW.create(l,c,r);return tI.set({tokenId:n,tokenResolver:d}),d.then(e=>(o&&(t4.emit(t9,{token:e}),e.jwt&&(this.lastActiveToken=e,t4.emit(t5,null))),e.getRawString()||null))}get currentTask(){let[e]=this.tasks??[];return e}}class rS extends aF{pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,a){super(),this.pathRoot=a,this.fromJSON(e)}static retrieve(){let e=aF.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new rS(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=aD(e.expire_at),this.abandonAt=aD(e.abandon_at),this.lastActiveAt=aD(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 rU=(e,a,t)=>{let{onValidation:r=e9,onValidationComplexity:i=e9}=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 rA(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function rC(e,a,t,r,i){if(!e.client||!r.popup)return;let n=rA(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 rI(e,{redirectCallbackUrl:a,redirectUrl:t}){let r=rA(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 rP(e,a){return new Promise((t,r)=>{if(!e.client||!a.popup)return void r();let i=async a=>{a.origin===rA(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 rO(e,a){t4.emit("resource:error",{resource:e,error:null}),t4.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await a(),error:null}}catch(a){return t4.emit("resource:error",{resource:e,error:a}),{error:a}}finally{t4.emit("resource:fetch",{resource:e,status:"idle"})}}let rT=()=>{var e;return(e=new as,{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 rE extends aF{pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;firstFactorVerification=new tY(null);secondFactorVerification=new tY(null);identifier=null;createdSessionId=null;userData=new rB(null);clientTrustState;get status(){return this._status}set status(e){let a=this._status;this._status=e,e&&a!==e&&ae.debug("SignIn.status",{id:this.id,from:a,to:e})}__internal_future=new rM(this);__internal_basePost=this._basePost.bind(this);__internal_baseGet=this._baseGet.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=e=>{ae.debug("SignIn.create",{id:this.id,strategy:"strategy"in e?e.strategy:void 0});let a=ap();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(ae.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 ae.debug("SignIn.attemptFirstFactor",{id:this.id,strategy:e.strategy}),a="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(tG(e.publicKeyCredential))}:{...e},this._basePost({body:{...a,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:a}=tD();return{startEmailLinkFlow:async({emailAddressId:t,redirectUrl:r})=>{this.id||aU("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=>(ae.debug("SignIn.prepareSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_second_factor"}));attemptSecondFactor=e=>(ae.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=rE.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):aP(c,rE.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eL);authenticateWithPopup=async e=>{let{popup:a}=e||{};return a||aI("popup"),rC(rE.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&&aI("generateSignature"),"solana"!==s||n||aI("walletName"),await this.create({identifier:t});let o=this.supportedFirstFactors?.find(e=>e.strategy===i);o||aC("SignIn"),await this.prepareFirstFactor(o);let{message:l}=this.firstFactorVerification;l||aC("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 ak().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ak().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await ak().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ak().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await ak().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ak().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await ak().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:ak().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithSolana=async({walletName:e})=>{let a=await ak().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:a,generateSignature:a=>ak().generateSignatureWithSolana({...a,walletName:e}),strategy:"web3_solana_signature",walletName:e})};authenticateWithPasskey=async e=>{let{flow:a}=e||{},t=rE.clerk.__internal_isWebAuthnSupported||rm,r=rE.clerk.__internal_getPublicCredentials||tK,i=rE.clerk.__internal_isWebAuthnAutofillSupported||rp;if(!t())throw new C("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(`${a_} 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?tJ(JSON.parse(n)):null;s||aO("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(rE.clerk.__internal_environment?.userSettings.passwordSettings)return rU(rT(),{...rE.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=et(e.supported_first_factors),this.supportedSecondFactors=et(e.supported_second_factors),this.firstFactorVerification=new tY(e.first_factor_verification),this.secondFactorVerification=new tY(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new rB(e.user_data),this.clientTrustState=e.client_trust_state??void 0),t4.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:ea(this.supportedFirstFactors),supported_second_factors:ea(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 rM{emailCode={sendCode:this.sendEmailCode.bind(this),verifyCode:this.verifyEmailCode.bind(this)};emailLink={sendLink:this.sendEmailLink.bind(this),waitForVerification:this.waitForEmailLinkVerification.bind(this),get verification(){if(!s())return null;const e=eP("__clerk_status"),a=eP("__clerk_created_session");if(!e||!a)return null;const t="verified"===e&&void 0!==rE.clerk.client&&rE.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 rO(this.#ep,async()=>{let e=this.#ep.supportedFirstFactors?.find(e=>"reset_password_email_code"===e.strategy);if(!e)throw new U("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 rO(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 rO(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{password:a,signOutOfOtherSessions:t},action:"reset_password"})})}async _create(e){let a=ap();await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:a?{locale:a,...e}:e})}async create(e){return rO(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 rO(this.#ep,async()=>{let a=e.identifier||e.emailAddress||e.phoneNumber,t=this.#ep.identifier,r=ap();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 rO(this.#ep,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"email_code",emailAddressId:t});if(!e)throw new U("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 rO(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 rO(this.#ep,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"email_link",emailAddressId:r});if(!e)throw new U("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 rO(this.#ep,async()=>{let{run:e,stop:a}=tD();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 rO(this.#ep,async()=>{a&&await this._create({identifier:a});let e=this.selectFirstFactor({strategy:"phone_code",phoneNumberId:t});if(!e)throw new U("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 rO(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 rO(this.#ep,async()=>{let e=t;try{new URL(t)}catch{e=window.location.origin+t}let l={redirectUrl:rE.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:e};if(i){let a=rI(rE.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 rP(rE.clerk,{popup:i,externalVerificationRedirectURL:d}),await this.#ep.reload()):eL(d))})}async web3(e){let{strategy:a}=e,t=a.replace("web3_","").replace("_signature","");return rO(this.#ep,async()=>{let r,i,n;switch(t){case"metamask":r=await ak().getMetamaskIdentifier(),i=ak().generateSignatureWithMetamask;break;case"coinbase_wallet":r=await ak().getCoinbaseWalletIdentifier(),i=ak().generateSignatureWithCoinbaseWallet;break;case"base":r=await ak().getBaseIdentifier(),i=ak().generateSignatureWithBase;break;case"okx_wallet":r=await ak().getOKXWalletIdentifier(),i=ak().generateSignatureWithOKXWallet;break;case"solana":if(!e.walletName)throw new U("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});r=await ak().getSolanaIdentifier(e.walletName),i=a=>ak().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 U("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 U("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=rE.clerk.__internal_isWebAuthnSupported||rm,r=rE.clerk.__internal_getPublicCredentials||tK,i=rE.clerk.__internal_isWebAuthnAutofillSupported||rp;if(!t())throw new C("Passkeys are not supported",{code:"passkey_not_supported"});return rO(this.#ep,async()=>{if("autofill"===a||"discoverable"===a)await this._create({strategy:"passkey"});else{if(!this.supportedFirstFactors.find(e=>"passkey"===e.strategy))throw new U("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?tJ(JSON.parse(e)):null;if(!t)throw new U("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 C(o.message,{code:"passkey_retrieval_failed"});await this.#ep.__internal_basePost({body:{publicKeyCredential:JSON.stringify(tG(s)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return rO(this.#ep,async()=>{let e=this.#ep.supportedSecondFactors?.find(e=>"phone_code"===e.strategy);if(!e)throw new U("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 rO(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 rO(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 rO(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??eP("__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 rO(this.#ep,async()=>{rE.clerk.client&&!rE.clerk.client.sessions.some(e=>e.id===this.#ep.createdSessionId)&&await rE.clerk.client.reload(),this.#em=!0,await rE.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 rR(e){let{unsafeMetadata:a}={...e},t=a?"object"==typeof a?JSON.stringify(a):a:"";return{...e,...a?{unsafeMetadata:t}:{}}}class rF extends aF{pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new tZ(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&&ae.debug("SignUp.status",{id:this.id,from:a,to:e})}__internal_future=new rD(this);__internal_basePost=this._basePost.bind(this);__internal_basePatch=this._basePatch.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{ae.debug("SignUp.create",{id:this.id,strategy:e.strategy});let a={...e};if(!a.locale){let e=ap();e&&(a.locale=e)}if(a.transfer&&this.shouldBypassCaptchaForAttempt(a)){let e=rF.clerk.client?.signIn.firstFactorVerification.strategy;e&&(a={...a,strategy:e})}return this._basePost({path:this.pathRoot,body:rR(a)})};prepareVerification=e=>(ae.debug("SignUp.prepareVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_verification"}));attemptVerification=e=>(ae.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}=tD();return{startEmailLinkFlow:async({redirectUrl:t})=>(this.id||aU("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&&aI("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||aC("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 ak().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ak().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let a=await ak().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ak().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let a=await ak().getBaseIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ak().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let a=await ak().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:a,generateSignature:ak().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithSolana=async({walletName:e,unsafeMetadata:a,legalAccepted:t})=>{let r=await ak().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:r,generateSignature:a=>ak().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=rF.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(T(e)&&I(e))return await rF.clerk.__internal_environment.reload(),h();throw e}),{externalAccount:p}=m,{status:g,externalVerificationRedirectURL:b}=p;"unverified"===g&&b?a(b):aP(g,rF.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eL);authenticateWithPopup=async e=>{let{popup:a}=e||{};return a||aI("popup"),rC(rF.clerk,"signUp",this.authenticateWithRedirectOrPopup,e,e=>{a.location.href=e instanceof URL?e.toString():e})};update=e=>this._basePatch({body:rR(e)});upsert=e=>this.id?this.update(e):this.create(e);validatePassword=(e,a)=>{if(rF.clerk.__internal_environment?.userSettings.passwordSettings)return rU(rT(),{...rF.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 tZ(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),t4.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 rF.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){if(!e.strategy)return!1;let a=rF.clerk.__internal_environment.displayConfig.captchaOauthBypass;return!!(a.some(a=>a===e.strategy)||e.transfer&&a.some(e=>e===rF.clerk.client.signIn.firstFactorVerification.strategy))}__experimental_getEnterpriseConnections=()=>aF._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new rN(e)))}class rD{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 aM(rF.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?rR(e.unsafeMetadata):void 0,locale:e.locale??ap()};await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:i})}async create(e){return rO(this.#ep,async()=>{await this._create(e)})}async update(e){return rO(this.#ep,async()=>{let a={...e,unsafeMetadata:e.unsafeMetadata?rR(e.unsafeMetadata):void 0};await this.#ep.__internal_basePatch({path:this.#ep.pathRoot,body:a})})}async password(e){return rO(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?rR(e.unsafeMetadata):void 0};await this.#ep.__internal_basePost({path:this.#ep.pathRoot,body:i})})}async sendEmailCode(){return rO(this.#ep,async()=>{await this.#ep.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification"})})}async verifyEmailCode(e){let{code:a}=e;return rO(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 rO(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 rO(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 rO(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:rF.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:h};if(c){let e=rI(rF.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(T(e)&&I(e))return await rF.clerk.__internal_environment.reload(),p();throw e});let{status:g,externalVerificationRedirectURL:b}=this.#ep.verifications.externalAccount;"unverified"===g&&b&&(c?(await rP(rF.clerk,{popup:c,externalVerificationRedirectURL:b}),await this.#ep.reload()):eL(b))})}async web3(e){let{strategy:a,unsafeMetadata:t,legalAccepted:r}=e,i=a.replace("web3_","").replace("_signature","");return rO(this.#ep,async()=>{let e,n,s;switch(i){case"metamask":e=await ak().getMetamaskIdentifier(),n=ak().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await ak().getCoinbaseWalletIdentifier(),n=ak().generateSignatureWithCoinbaseWallet;break;case"base":e=await ak().getBaseIdentifier(),n=ak().generateSignatureWithBase;break;case"okx_wallet":e=await ak().getOKXWalletIdentifier(),n=ak().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||aC("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??eP("__clerk_ticket");return this.create({...e,ticket:a??void 0})}async finalize(e){let{navigate:a}=e||{};return rO(this.#ep,async()=>{if(!this.#ep.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#em=!0,await rF.clerk.setActive({session:this.#ep.createdSessionId,navigate:a})})}}class rN extends aF{id;name;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name),this}}class rW extends aF{pathRoot="tokens";jwt;static async create(e,a={},t=!1){return new rW(await aF._fetch({body:a,method:"POST",path:e,search:t?"debug=skip_cache":void 0}),e)}constructor(e,a){super(),a&&(this.pathRoot=a),e?.jwt&&(this.jwt=am(e.jwt))}getRawString=()=>this.jwt?.claims.__raw||"";fromJSON(e){return e&&(this.jwt=am(e.jwt)),this}__internal_toSnapshot(){return{object:"token",id:this.id||"",jwt:this.getRawString()}}}class rL extends aF{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=aD(e.updated_at),this.createdAt=aD(e.created_at)),this}}class r$ extends aF{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=aD(e.updated_at),this.createdAt=aD(e.created_at)),this}}class rK extends aF{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 rK}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case tN:return this.primaryEmailAddressId===e.id;case rf:return this.primaryPhoneNumberId===e.id;case rH:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:a}=e||{};return new tN({email_address:a},this.path()+"/email_addresses/").create()};createPasskey=()=>rb.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:a}=e||{};return new rf({phone_number:a},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:a}=e||{};return new rH({web3_wallet:a},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:a,redirectUrl:t,additionalScopes:r}=e||{};return new ra((await aF._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:a,redirect_url:t,additional_scope:r}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new rL((await aF._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new rL((await aF._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new tT((await aF._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new r$((await aF._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);update=e=>this._basePatch({body:rR(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=>(t4.emit(t3,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await rS.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:a}=e||{};return null===a?ri.delete(`${this.path()}/profile_image`):ri.create(`${this.path()}/profile_image`,{file:a})};getOrganizationInvitations=e=>rJ.retrieve(e);getOrganizationSuggestions=e=>rh.retrieve(e);getOrganizationMemberships=e=>ru.retrieve(e);leaveOrganization=async e=>new tT((await aF._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);initializePaymentMethod=e=>tg(e);addPaymentMethod=e=>tb(e);getPaymentMethods=e=>tf(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 tN(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 rf(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 rH(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 ra(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new rb(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new ru(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new t2(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=aD(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=aD(e.legal_accepted_at)),this.updatedAt=aD(e.updated_at||void 0),this.createdAt=aD(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 rB{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 rJ extends aF{id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await aF._fetch({path:"/me/organization_invitations",method:"GET",search:a7(e)}).then(e=>{let{data:a,total_count:t}=e?.response;return{total_count:t,data:a.map(e=>new rJ(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=aD(e.created_at),this.updatedAt=aD(e.updated_at)),this}}let rV={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 rG extends aF{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:{...rV,name:"phone_number"},username:{...rV,name:"username"},web3_wallet:{...rV,name:"web3_wallet"},first_name:{...rV,name:"first_name"},last_name:{...rV,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:{...rV,name:"authenticator_app"},backup_code:{...rV,name:"backup_code"},passkey:{...rV,name:"passkey"}};enterpriseSSO={enabled:!1};passkeySettings={allow_autofill:!1,show_sign_in_button:!1};passwordSettings={};signIn={second_factor:{required:!1,enabled:!1}};signUp={allowlist_only:!1,captcha_enabled:!1,legal_consent_enabled:!1,mode:"public",progressive:!0};social={};usernameSettings={};get authenticatableSocialStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled&&e.authenticatable).map(([,e])=>e.strategy).sort():[]}get enabledFirstFactorIdentifiers(){return this.attributes?Object.entries(this.attributes).filter(([e,a])=>a.used_for_first_factor&&!e.startsWith("web3")).map(([e])=>e):[]}get socialProviderStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled).map(([,e])=>e.strategy).sort():[]}get web3FirstFactors(){return this.attributes?Object.entries(this.attributes).filter(([e,a])=>a.used_for_first_factor&&e.startsWith("web3")).map(([,e])=>e.first_factors).flat():[]}get alternativePhoneCodeChannels(){return this.attributes?Object.entries(this.attributes).filter(([e,a])=>a.used_for_first_factor&&"phone_number"===e).map(([,e])=>e?.channels?.filter(e=>"sms"!==e)||[]).flat():[]}constructor(e=null){super(),this.fromJSON(e)}get instanceIsPasswordBased(){return!!(this.attributes?.password?.enabled&&this.attributes.password?.required)}get hasValidAuthFactor(){return!!(this.attributes?.email_address?.enabled||this.attributes?.phone_number?.enabled||this.attributes.password?.required&&this.attributes.username?.required)}fromJSON(e){return e&&(this.attributes=this.withDefault(e.attributes?Object.fromEntries(Object.entries(e.attributes).map(e=>[e[0],{...e[1],name:e[0]}])):null,this.attributes),this.actions=this.withDefault(e.actions,this.actions),this.enterpriseSSO=this.withDefault(e.enterprise_sso,this.enterpriseSSO),this.passkeySettings=this.withDefault(e.passkey_settings,this.passkeySettings),this.passwordSettings=e.password_settings?{...e.password_settings,min_length:Math.max(e.password_settings?.min_length??8,8),max_length:e.password_settings?.max_length===0?72:Math.min(e.password_settings?.max_length??72,72)}:this.passwordSettings,this.signIn=this.withDefault(e.sign_in,this.signIn),this.signUp=this.withDefault(e.sign_up,this.signUp),this.social=this.withDefault(e.social,this.social),this.usernameSettings=e.username_settings?{...e.username_settings,min_length:Math.max(e.username_settings?.min_length??4,4),max_length:Math.min(e.username_settings?.max_length??64,64)}:this.usernameSettings),this}__internal_toSnapshot(){return{actions:this.actions,attributes:this.attributes,passkey_settings:this.passkeySettings,password_settings:this.passwordSettings,sign_in:this.signIn,sign_up:this.signUp,social:this.social}}}class rH extends aF{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 tY(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}class rQ extends aF{pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=aD(e.updated_at),this.createdAt=aD(e.created_at)),this}static async join(e){return new rQ((await aF._fetch({path:"/waitlist",method:"POST",body:e}))?.response)}}function rY(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 rX(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(tP.isClientResource(e))return e.id!==a.id||e.updatedAt.getTime()<a.updatedAt.getTime()||e.sessions.length!==a.sessions.length;if(rq.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&&rY(t.user,r.user))}if(rK.isUserResource(e))return rY(e,a)}catch{}return!0}(e,a)?e:a}let rZ="__clerk_db_jwt";function r1(e,a){let t=new URL(e),r=t.searchParams.get(rZ);t.searchParams.delete(rZ);let i=r||a;return i&&t.searchParams.set(rZ,i),t}let r2=e=>{let a=new URL(e);return a.searchParams.delete(rZ),a},r0=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 r9(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 r3=function e(a,t){function r(e,r,i){if("undefined"!=typeof document){"number"==typeof(i=r9({},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,"",r9({},a,{expires:-1}))},withAttributes:function(a){return e(this.converter,r9({},this.attributes,a))},withConverter:function(a){return e(r9({},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 r8(e){return{get:()=>r3.get(e),set(a,t={}){r3.set(e,a,t)},remove(a){r3.remove(e,a)}}}let r5=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function r4(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 r6=r8("__clerk_test_etld"),r7="__client_uat",ie="__session",ia=()=>{let e=ab()?"None":"Lax",a=r5(e);return{sameSite:e,secure:a,partitioned:!1}};async function it(e){let a;try{a=await em(e)}catch(o){var t;t=`Suffixed cookie failed due to ${o.message} (secure-context: ${window.isSecureContext}, url: ${window.location.href})`,G.has(t)||(console.log(t),G.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 ir=()=>{let e=ab()?"None":"Lax",a=r5(e);return{sameSite:e,secure:a}};var ii=i(945),is=i.n(ii);class io{lock=(function(e){let a=new(is());return window.addEventListener("beforeunload",async()=>{await a.releaseLock(e)}),{acquireLockAndRun:async t=>{if("locks"in navigator&&isSecureContext){let a=new AbortController,r=setTimeout(()=>a.abort(),4999);return await navigator.locks.request(e,{signal:a.signal},async()=>(clearTimeout(r),await t())).catch(()=>!1)}if(await a.acquireLock(e,5e3))try{return await t()}finally{await a.releaseLock(e)}}}})("clerk.lock.refreshSessionToken");workerTimers=tF();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 il{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,a,t,r){let i=await it(e.publishableKey),n=new il(e,a,i,t,r);return await n.setup(),n}constructor(e,a,r,i,n){this.clerk=e,this.instanceType=i,this.clerkEventBus=n,t4.on(t9,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),t4.on(t3,()=>this.handleSignOut()),this.refreshTokenOnFocus(),this.startPollingForToken(),this.clientUat=(e=>{let a=r8(r7),r=r8(ep(r7,e));return{set:e=>{let i=r4(Date.now(),1),n=ab()?"None":"Strict",s=r5(n),o=function(e=window.location.hostname,a=r6){if(t)return t;if(["localhost","127.0.0.1","0.0.0.0"].includes(e))return e;let r=e.split(".");if(1===r.length)return e;for(let e=r.length-2;e>=0;e--){let i=r.slice(e).join(".");if(a.set("1",{domain:i}),"1"===a.get())return a.remove({domain:i}),t=i,i;a.remove({domain:i})}}(),l="0";e&&e.updatedAt&&e.signedInSessions.length>0&&(l=Math.floor(e.updatedAt.getTime()/1e3).toString()),r.remove(),a.remove(),r.set(l,{domain:o,expires:i,partitioned:!1,sameSite:n,secure:s}),a.set(l,{domain:o,expires:i,partitioned:!1,sameSite:n,secure:s})},get:()=>parseInt(r.get()||a.get()||"0",10)}})(r),this.sessionCookie=(e=>{let a=r8(ie),t=r8(ep(ie,e)),r=()=>{let e=ia();a.remove(e),t.remove(e)};return{set:e=>{let i=r4(Date.now(),1),{sameSite:n,secure:s,partitioned:o}=ia();o&&r(),a.set(e,{expires:i,sameSite:n,secure:s,partitioned:o}),t.set(e,{expires:i,sameSite:n,secure:s,partitioned:o})},remove:r,get:()=>t.get()||a.get()}})(r),this.activeCookie=(()=>{let e=r8("clerk_active_context"),a={secure:r5("None")};return{set:t=>{e.set(t,a)},get:()=>e.get(),remove:()=>e.remove(a)}})(),this.devBrowser=function({cookieSuffix:e,frontendApi:a,fapiClient:t}){let r,i,n=(r=r8(rZ),i=r8(ep(rZ,e)),{get:()=>i.get()||r.get(),set:e=>{let a=r4(Date.now(),1),{sameSite:t,secure:n}=ir();i.set(e,{expires:a,sameSite:t,secure:n}),r.set(e,{expires:a,sameSite:t,secure:n})},remove:()=>{let e=ir();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(!ek(a))return;t.onBeforeRequest(e=>{let a=s();a&&e?.url&&(e.url=r1(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(rZ)||"",r2(r0(e)).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",r2(r0(e))),r);if(i)return void o(i);if(n.get())return;let l=t.buildUrl({path:"/dev_browser"}),c=await fetch(l.toString(),{method:"POST"});if(!c.ok){let e=function(e=[]){return e.length>0?e.map(e=>new k(e)):[]}((await c.json()).errors);e[0]?aq(e[0].longMessage):aq()}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(`${a_} Missing dev browser jwt. Please contact support.`);return r1(e,a)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new io,this.poller.startPollingForSessionToken(()=>this.refreshSessionToken()))}stopPollingForToken(){this.poller&&(this.poller.stopPollingForSessionToken(),this.poller=null)}refreshTokenOnFocus(){window.addEventListener("focus",()=>{"visible"===document.visibilityState&&this.refreshSessionToken({updateCookieImmediately:!0})})}async refreshSessionToken({updateCookieImmediately:e=!1}={}){if(this.clerk.session)try{let a=await this.clerk.session.getToken();e&&this.updateSessionCookie(a)}catch(e){return this.handleGetTokenError(e)}}updateSessionCookie(e){if(document.hasFocus()||this.isCurrentContextActive())return e||d()||ae.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(T(e)||E(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(P(e))return void this.clerk.handleUnauthenticated().catch(e9);this.clerkEventBus.emit(g,"degraded")}}handleSignOut(){this.activeCookie.remove(),this.sessionCookie.remove(),this.setClientUatCookieForDevelopmentInstances()}setActiveContextInStorage(){let e=this.clerk.session?.id||"",a=this.clerk.organization?.id||"",t=`${e}:${a}`;":"!==t?this.activeCookie.set(t):this.activeCookie.remove()}isCurrentContextActive(){let e=this.activeCookie.get();if(!e)return!0;let[a,t]=e.split(":"),r=this.clerk.session?.id||"",i=this.clerk.organization?.id||"";return a===r&&t===i}getSessionCookie(){return this.sessionCookie.get()}}class ic{clerk;captchaChallenge;timers;constructor(e,a=new aM(e),t=tF()){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 id=["/client","/waitlist"];class iu{async getBaseFapiProxyOptions(){let e=await aF.clerk.session?.getToken();if(!e)throw new U("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 aF._fetch({...await this.getBaseFapiProxyOptions(),method:"GET",path:"/api_keys",search:a7({...e,subject:e?.subject??aF.clerk.organization?.id??aF.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:a,total_count:t}=e;return{total_count:t,data:a.map(e=>new aN(e))}})}async create(e){return new aN(await aF._fetch({...await this.getBaseFapiProxyOptions(),path:"/api_keys",method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??aF.clerk.organization?.id??aF.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new aN(await aF._fetch({...await this.getBaseFapiProxyOptions(),method:"POST",path:`/api_keys/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let ih=new Map;class im{#es=!1;load(e){let a=e?.protectConfig;if(a?.loaders&&Array.isArray(a.loaders)&&0!==a.loaders.length&&!this.#es){if(s())for(let e of(this.#es=!0,a.loaders))try{this.applyLoader(e)}catch(e){H(`[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 H(`[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:H(`[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 H(`[protect] loader target element not found: ${t}`);e.appendChild(r);return}H(`[protect] loader target is invalid: ${t}`)}}}class ip{signInResourceSignal=ta;signInErrorSignal=tt;signInFetchSignal=tr;signInSignal=ti;signUpResourceSignal=tn;signUpErrorSignal=ts;signUpFetchSignal=to;signUpSignal=tl;__internal_effect=a0;__internal_computed=a2;constructor(){t4.on("resource:update",this.onResourceUpdated),t4.on("resource:error",this.onResourceError),t4.on("resource:fetch",this.onResourceFetch)}onResourceError=e=>{e.resource instanceof rE&&this.signInErrorSignal({error:e.error}),e.resource instanceof rF&&this.signUpErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof rE){if(ig(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof rF){if(ig(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}};onResourceFetch=e=>{e.resource instanceof rE&&this.signInFetchSignal({status:e.status}),e.resource instanceof rF&&this.signUpFetchSignal({status:e.status})}}function ig(e,a){return!a?.id&&e&&e.__internal_future?.hasBeenFinalized===!1}let ib="cannot_render_billing_disabled",iy="cannot_render_user_missing",ik="cannot_render_organizations_disabled",iw="cannot_render_organization_missing",iv="cannot_render_single_session_enabled",ij={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 iz{static version="6.0.0-snapshot.v20251218183643";static sdkMetadata={name:"@clerk/clerk-js",version:"6.0.0-snapshot.v20251218183643"};static _billing;static _apiKeys;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new ip;internal_last_error=null;environment;#eg;#eb="";#ef;#ey;#ek;#ew;#ev;#ej=null;#ez;#e_;#ex;#eq="loading";#eS=[];#eU=[];#eA={};#eC=null;#eI=0;#eP=p();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 iz.version}set sdkMetadata(e){iz.sdkMetadata=e}get sdkMetadata(){return iz.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#eq}get isSatellite(){return!!ag()&&e0(this.#eA.isSatellite,new URL(window.location.href),!1)}get domain(){if(ag()){let e=function(e=""){return(e||"").replace(/^.+:\/\//,"")}(e0(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(ag()){let e=e0(this.#ey,new URL(window.location.href));return!e||e$(e)||eK(e)||au.throwInvalidProxyUrl({url:e}),e?eK(e)?new URL(e,window.location.origin).toString():e:""}return""}get frontendApi(){let e=eu(this.publishableKey);return e?e.frontendApi:au.throwInvalidPublishableKeyError({key:this.publishableKey})}get instanceType(){return this.#ex}get isStandardBrowser(){return this.#eA.standardBrowser||!1}get billing(){return iz._billing||(iz._billing=new te),iz._billing}get apiKeys(){return iz._apiKeys||(iz._apiKeys=new iu),iz._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=ih.get(c);if(d)return d.signals.computedSignal();let u=(t=a1({resource:null}),r=a1({error:null}),i=a1({status:"idle"}),n=a2(()=>{let e=t().resource,a=r().error,n=i().status;return{errors:tc(a,{}),fetchStatus:n,checkout:e}}),{resourceSignal:t,errorSignal:r,fetchSignal:i,computedSignal:n}),h=new th(u,{..."organization"===s?{orgId:e.organization?.id}:{},planId:o,planPeriod:l});return ih.set(c,{resource:h,signals:u}),u.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#eA[e]}get isSignedIn(){return this?.session?.status!=="pending"&&!!this.session}constructor(e,a){if(!(e=(e||"").trim()))return au.throwMissingPublishableKeyError();const t=eu(e);if(!t)return au.throwInvalidPublishableKeyError({key:e});this.#ef=a?.domain,this.#ey=a?.proxyUrl,this.environment=re.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-snapshot.v20251218183643"),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&&!id.some(e=>t.startsWith(e))&&r&&s.append("_clerk_session_id",r),eb([...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)),ej({base:i.origin,pathname:`${s}/${r}${t}`,search:n(a)},{stringify:!1})}let i="production"===e.instanceType?e.domain:"";return ej({base:`https://${i||e.frontendApi}`,pathname:`${r}${t}`,search:n(a)},{stringify:!1})}async function o(a,t){let n,o={...a},{method:l="GET",body:d}=o;!d||"object"!=typeof d||d instanceof FormData||(o.body=function(e){if(!e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype)return e;let a={};for(let[t,r]of Object.entries(e))void 0!==r&&(a[t]=r);return a}(d)),o.url=s({...o,sessionId:e.getSessionId()}),o.headers=new Headers(o.headers),"GET"===l||d instanceof FormData||o.headers.has("content-type")||o.headers.set("content-type","application/x-www-form-urlencoded"),"application/x-www-form-urlencoded"===o.headers.get("content-type")&&(o.body=d?eb(d,{keyEncoder:Z}):d);let u=await r(o),h="GET"===l?"GET":"POST",m=o.url,p={...o,method:h,credentials:o.credentials||"include"};try{if(u){let e=t?.fetchMaxTries??(c()?4:11);n=await ai(()=>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();ae.error("network error",{error:a,url:e,method:l},"fapiClient");throw Error(`${a_} 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||ae.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(g,"loading"),this.#eP.prioritizedOn(g,e=>this.#eq=e),aF.clerk=this,this.#ew=new im}getFapiClient=()=>this.#e_;load=async e=>{if(ae.info("load() start",{},"clerk"),!this.loaded){if("development"!==this.#ex||e?.unsafe_disableDevelopmentModeConsoleWarning||H("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.#eA=this.#eO(e),this.#eA.clerkUiCtor&&(this.#ez=Promise.resolve(this.#eA.clerkUiCtor).then(e=>new e(()=>this,()=>this.environment,this.#eA,new as))),"development"===this.#ex&&(this.#eA.routerPush||this.#eA.routerReplace)&&(!this.#eA.routerPush||!this.#eA.routerReplace)){let e=this.#eA.routerPush?"routerReplace":"routerPush";H(`Clerk: Both \`routerPush\` and \`routerReplace\` need to be defined, but \`${e}\` is not defined. This may cause issues with navigation in your application.`)}t4.on(t5,()=>{this.#eT(this.session),this.#eE()}),this.#eA.sdkMetadata&&(iz.sdkMetadata=this.#eA.sdkMetadata),!1!==this.#eA.telemetry&&(this.telemetry=new eH({clerkVersion:iz.version,samplingRate:1,perEventSampling:!this.#eA.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#eA.telemetry}),this.#eA.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=e2(e);if(t){a=t;break}}else a=e2(t);return{themeName:a}}(this.#eA.appearance)}));try{this.#eA.standardBrowser?await this.#eM():await this.#eR();let e=this.#eA.telemetry,a=!1!==e&&!e?.disabled,t=!!this.#eA.__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(e5)return;let{enabled:a=!1,...t}=e;a&&(e3=!0,e5=!0,e7(t))}({enabled:!0,...s?{logLevel:s}:{},...a&&this.telemetry?{telemetryCollector:this.telemetry}:{}}),this.#ew?.load(this.environment),ae.info("load() complete",{},"clerk")}catch(e){throw this.#eP.emit(g,"error"),ae.error("load() failed",{error:e},"clerk"),e}}};#eF(){let e;return!!(!this.#eA.signUpUrl&&this.#eA.signInUrl&&(e=this.#eA.signInUrl,!eg.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:e9,r="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e9,i=e&&"object"==typeof e?e:a||{},n=i?.redirectUrl||this.buildAfterSignOutUrl();ae.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=ao(this.#eA.standardBrowser);t4.emit(t3,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.#eA.experimental?.persistClient??!0?await this.client.removeSessions():await this.client.destroy(),await o(),ae.info("signOut() complete",{redirectUrl:ez(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(),ae.info("signOut() complete",{redirectUrl:ez(n)},"clerk"))};openGoogleOneTap=e=>{this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("googleOneTap",e||{})),this.telemetry?.record(e1("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(N(this,this.environment)){if("development"===this.#ex)throw new U(eD.cannotOpenSignInOrSignUp,{code:iv});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(e1("SignIn",e,a))};closeSignIn=()=>{this.#ez?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(W(this,this.environment)){if("development"===this.#ex)throw new U(eD.cannotRenderAnyBillingComponent("Checkout"),{code:ib});return}if(!this.user){if("development"===this.#ex)throw new U(eD.cannotOpenCheckout,{code:iy});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(W(this,this.environment)){if("development"===this.#ex)throw new U(eD.cannotRenderAnyBillingComponent("PlanDetails"),{code:ib});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openDrawer("planDetails",e||{})),this.telemetry?.record(e1("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 U(eD.cannotOpenUserProfile,{code:iy});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("userVerification",e||{})),this.telemetry?.record(e1("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||H(`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(eZ("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()=>(ax("Stripe"),{loadStripe:()=>Promise.resolve(null)});openSignUp=e=>{if(N(this,this.environment)){if("development"===this.#ex)throw new U(eD.cannotOpenSignInOrSignUp,{code:iv});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("signUp",e||{})),this.telemetry?.record(e1("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 U(eD.cannotOpenUserProfile,{code:iy});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(e1("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 U(eD.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:ik})}});if(a){if(!this.organization){if("development"===this.#ex)throw new U(eD.cannotRenderComponentWhenOrgDoesNotExist,{code:iw});return}this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("organizationProfile",e||{})),this.telemetry?.record(e1("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 U(eD.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:ik})}});a&&(this.assertComponentsReady(this.#ez),this.#ez.then(e=>e.ensureMounted()).then(a=>a.openModal("createOrganization",e||{})),this.telemetry?.record(e1("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(e1("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(eZ(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(eZ(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(eZ(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 U(eD.cannotRenderComponentWhenUserDoesNotExist,{code:iy});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(eZ(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 U(eD.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:ik})}});if(!t)return;let r=!!this.user;if(!this.organization&&r){if("development"===this.#ex)throw new U(eD.cannotRenderComponentWhenOrgDoesNotExist,{code:iw});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(eZ(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 U(eD.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:ik})}});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(eZ(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 U(eD.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:ik})}});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(eZ(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 U(eD.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:ik})}});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(eZ(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(eZ(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(eZ(t,a))};unmountWaitlist=e=>{this.#ez?.then(e=>e.ensureMounted()).then(a=>a.unmountComponent({node:e}))};mountPricingTable=(e,a)=>{if(W(this,this.environment)){if("development"===this.#ex)throw new U(eD.cannotRenderAnyBillingComponent("PricingTable"),{code:ib});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(eZ(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(H("Clerk: <APIKeys /> component is in early access and not yet recommended for production use."),L(this,t=this.environment)&&$(this,t)){if("development"===this.#ex)throw new U(eD.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&$(this,this.environment)){if("development"===this.#ex)throw new U(eD.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if(L(this,this.environment)){if("development"===this.#ex)throw new U(eD.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(eZ(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 U(eD.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:ik})}});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(eZ(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(eZ("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,ae.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 ae.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 ae.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:e9,l="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:e9,c=void 0===i?this.session:i;c?.status==="pending"&&(n={...this.#eA,...e},s=["taskUrls","navigate"],Object.keys(n).some(e=>s.includes(e))||H('Clerk: Session has pending tasks but no handling is configured. To handle pending tasks, provide either "taskUrls" for navigation to custom URLs or "navigate" for programmatic navigation. Without these options, users may get stuck on incomplete flows.'));let u=void 0!==a;if(c&&u){let e="string"==typeof a?a:a?.id;if("string"==typeof e&&e.startsWith("org_"))c.lastActiveOrganizationId=e||null;else{let a=c.user.organizationMemberships.find(a=>a.organization.slug===e),t=a?.organization.id||null,r=null===t;if(this.environment?.organizationSettings?.forceOrganizationSelection&&r)return;c.lastActiveOrganizationId=t}}c?.status!=="pending"&&await o(null===c?"sign-out":void 0),(ag()&&globalThis.document.hasFocus()||!this.#eA.standardBrowser)&&(await this.#eN(c),c=this.#eW(c?.id)),await c?.getToken()||(d()||ae.warn("Token is null when setting active session (offline)",{sessionId:c?.id},"clerk"),t4.emit(t9,{token:null}));let h=ao(this.#eA.standardBrowser),m=c?.status==="pending"&&c?.currentTask&&this.#eA.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?ej({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:rX((r=t).client,e.client),session:rX(r.session,e.session),user:rX(r.user,e.user),organization:rX(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||!ag())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.#eA.routerReplace?this.#eA.routerReplace:this.#eA.routerPush;if(ae.info(`Clerk is navigating to: ${t}`),this.#eA.routerDebug&&console.log(`Clerk is navigating to: ${t}`),"null"!==t.origin&&t.origin!==window.location.origin||!r)return void eL(t);let i={...a?.metadata?{__internal_metadata:a?.metadata}:{},windowNavigate:eL};return await r(ez(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.#eA,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eA(this.#eA,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#eA.afterSignOutUrl?this.buildUrlWithAuth(this.#eA.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#eA.newSubscriptionRedirectUrl?this.#eA.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?ej({base:this.#eA.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#eA.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#eA.afterMultiSessionSingleSignOutUrl):this.#eA.signInUrl?this.buildUrlWithAuth(ej({base:this.#eA.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.#eA.taskUrls?.[a.key];return t||ej({base:this.buildSignInUrl(e),hashPath:eM(a)},{stringify:!0})}#eB=async()=>{if(!ag())return;let e=new URLSearchParams({[K]:"true"}),a=eP(J);a&&e$(a)||function(){throw Error(`${a_} Invalid redirect_url. A valid http or https url should be used for the redirection.`)}();let t=ej({base:eP(J),searchParams:e},{stringify:!0});return this.navigate(this.buildUrlWithAuth(t))};redirectWithAuth=async e=>{if(ag())return this.navigate(this.buildUrlWithAuth(e))};redirectToSignIn=async e=>{if(ag())return this.navigate(this.buildSignInUrl(e))};redirectToSignUp=async e=>{if(ag())return this.navigate(this.buildSignUpUrl(e))};redirectToUserProfile=async()=>{if(ag())return this.navigate(this.buildUserProfileUrl())};redirectToCreateOrganization=async()=>{if(ag())return this.navigate(this.buildCreateOrganizationUrl())};redirectToOrganizationProfile=async()=>{if(ag())return this.navigate(this.buildOrganizationProfileUrl())};redirectToAfterSignIn=async()=>{if(ag())return this.navigate(this.buildAfterSignInUrl())};redirectToAfterSignUp=async()=>{if(ag())return this.navigate(this.buildAfterSignUpUrl())};redirectToAfterSignOut=async()=>{if(ag())return this.navigate(this.buildAfterSignOutUrl())};redirectToWaitlist=async()=>{if(ag())return this.navigate(this.buildWaitlistUrl())};redirectToTasks=async e=>{if(ag())return this.navigate(this.buildTasksUrl(e))};handleEmailLinkVerification=async(e,a)=>{if(!this.client)return;let t=eP("__clerk_status");if("expired"===t)throw new x(S.Expired);if("client_mismatch"===t)throw new x(S.ClientMismatch);if("verified"!==t)throw new x(S.Failed);let r=eP("__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):e9;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||ej({base:i.signInUrl,hashPath:"/factor-one"},{stringify:!0})),m=c(e.secondFactorUrl||ej({base:i.signInUrl,hashPath:"/factor-two"},{stringify:!0})),p=c(e.resetPasswordUrl||ej({base:i.signInUrl,hashPath:"/reset-password"},{stringify:!0})),g=new eA(this.#eA,e),b=c(e.continueSignUpUrl||ej({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=eT();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||ej({base:i.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),verifyPhonePath:e.verifyPhoneNumberUrl||ej({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 eR(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:aS("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:aS("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 tP.getOrCreateInstance().fetch();if(this.updateClient(a),this.session)return;return e.broadcast&&t4.emit(t3,null),this.setActive({session:null})}catch(e){if(T(e)&&[403,500].includes(e.status))return this.setActive({session:null});throw e}};authenticateWithGoogleOneTap=async e=>(ax("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 ak().getWeb3Identifier({provider:u,walletName:o});switch(u){case"metamask":l=ak().generateSignatureWithMetamask;break;case"base":l=ak().generateSignatureWithBase;break;case"coinbase_wallet":l=ak().generateSignatureWithCoinbaseWallet;break;case"solana":if(!o)throw new U("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});l=e=>ak().generateSignatureWithSolana({...e,walletName:o});break;default:l=ak().generateSignatureWithOKXWallet}let m=e=>()=>t&&"function"==typeof t?t(e):this.navigate(e),p=m(s||ej({base:d.signInUrl,hashPath:"/factor-two"},{stringify:!0})),g=m(a||ej({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(ad(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 eR(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})=>rc.create({name:e,slug:a});getOrganization=async e=>rc.get(e);joinWaitlist=async({emailAddress:e})=>rQ.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.#eA.selectInitialSession?this.#eA.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:e9)(),this.#eT(e),this.session?.lastActiveToken||d()||ae.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),t4.emit(t9,{token:this.session?.lastActiveToken})}this.#eE()};get __internal_environment(){return this.environment}__internal_setEnvironment=async e=>{this.environment=new re(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.#eA,...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({[J]:window.location.href});return ej({base:this.#eA.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"!==eP(K)&&!!this.isSatellite&&!!this.#ek?.isSignedOut();#eQ=()=>"production"!==this.#ex&&!this.isSatellite&&!!eP(J);#eY=async()=>{"development"===this.instanceType?await this.navigate(this.#eV()):"production"===this.instanceType&&await this.navigate(this.#eG())};#eX=(e,a)=>{let t;try{t=new URL(e)}catch{throw Error(`${a_} The signInUrl needs to have a absolute url format.`)}t.origin===a&&function(){throw Error(`${a_} The signInUrl needs to be on a different origin than your satellite application.`)}()};#eZ=()=>{this.isSatellite&&("development"!==this.#ex||this.#eA.signInUrl||function(){throw Error(`${a_} Missing signInUrl. A satellite application needs to specify the signInUrl for development instances.`)}(),this.proxyUrl||this.domain||function(){throw Error(`${a_} Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl.`)}(),this.#eA.signInUrl&&this.#eX(this.#eA.signInUrl,window.location.origin))};#eM=async()=>{if(this.#ek=await il.create(this,this.#e_,this.#ex,this.#eP),this.#eZ(),this.#eH())return void await this.#eY();if(this.#eQ())return void await this.#eB();this.#eC=(()=>{if(!s())return{onPageFocus:e9};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=ew.get(e);void 0===a&&(a=en.some(a=>e.startsWith("accounts.")&&e.endsWith(a))||es.some(a=>e.endsWith(a)&&!e.endsWith(".clerk"+a)),ew.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=re.getInstance().fetch({touch:a}).then(e=>this.updateEnvironment(e)).catch(()=>{++t;let e=az.getItem(aw,null);e&&this.updateEnvironment(new re(e))}),r=async()=>tP.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(async e=>{if(P(e))throw e;++t;let a=this.#ek?.getSessionCookie(),r=function(e){let a;try{a=new rW({jwt:e||"",object:"token",id:void 0})}catch{a=null}if(tP.clearInstance(),!a?.jwt)return tP.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}=r_(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 tP.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(ad(e,"requires_captcha"))await r();else throw e}if(this.#ek?.setClientUatCookieForDevelopmentInstances(),await this.#e2())return;break}catch(e){if(ad(e,"dev_browser_unauthenticated"))await this.#ek.handleUnauthenticatedDevBrowser();else if(!d())return void console.warn(e);else throw e}r>=2&&function(){throw Error(`${a_} Something went wrong initializing Clerk.`)}()}this.#ev=new ic(this),this.#ev.start(),this.#e0(),this.#e9(),this.#e3(),this.#eP.emit(g,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([re.getInstance().fetch({touch:!1,fetchMaxTries:t}),tP.getOrCreateInstance().fetch({fetchMaxTries:t})])}catch(t){if(E(t)&&"network_error"===t.code&&this.shouldFallbackToCachedResources()){let t=await this.__internal_getCachedResources?.();e=new re(t?.environment),tP.clearInstance(),a=tP.getOrCreateInstance(t?.client),++r}else throw t}this.updateClient(a),this.updateEnvironment(e),this.#eP.emit(g,r>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,a]=await Promise.all([re.getInstance().fetch({touch:!1,fetchMaxTries:1}),tP.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=()=>{s()&&(this.#eC?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#eI>Date.now())&&(this.#eI=Date.now()+5e3,this.#eA.touchSession&&this.#eN(this.session))}),this.#ej?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),t4.on(t3,()=>{this.#ej?.postMessage({type:"signout"})}),t4.on(t8,()=>{az.setItem(aw,this.environment?.__internal_toSnapshot(),864e5)}))};#eN=async e=>{if(!e)return Promise.resolve();await e.touch().catch(e=>{P(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.#eA.__internal_keyless_claimKeylessApplicationUrl&&this.#ez?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#eA.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#eA.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#eA.__internal_keyless_dismissPrompt}})})};#eK=(e,a,t)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let r=this.#eA[e]||this.environment.displayConfig[e];this.#eF()&&(r=this.#eA.signInUrl);let i=new eA(this.#eA,a).toSearchParams(),n=new URLSearchParams(t||{}),s=ej({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,ef)).pathname,r=eS.includes(t)||eU.includes(t),e===a.host&&r);if(s||!o)return!1;let l=this.session,c=this.#eA.signInUrl||this.environment?.displayConfig.signInUrl,d=c&&window.location.href.startsWith(c),u=this.#eA.signUpUrl||this.environment?.displayConfig.signUpUrl,h=u&&window.location.href.startsWith(u);return i=new URL(n,ef),(!eS.includes(i.pathname)||!!l||!d&&!h)&&(await this.navigate(this.buildUrlWithAuth(n)),!0)};#eO=e=>({...ij,...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://${ev(a)}`),r.push(`https://*.${ev(a)}`),"development"===t&&r.push(`https://${a}`),r}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)});#e0=()=>{try{eO(K),eO(eC),eO(B),eO("__clerk_handshake"),eO("__clerk_handshake_nonce"),eO("__clerk_help")}catch{}};get #e$(){let e=eW;return this.#eA.allowedRedirectProtocols&&(e=e.concat(this.#eA.allowedRedirectProtocols)),e}}})();var s=exports;for(var o in n)s[o]=n[o];n.__esModule&&Object.defineProperty(s,"__esModule",{value:!0})})();