@clerk/clerk-js 6.42.0-canary.v20261027184321 → 6.42.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/clerk.browser.js +2 -2
- package/dist/clerk.js +1 -1
- package/dist/clerk.legacy.browser.js +1 -1
- package/dist/clerk.mjs +1 -1
- package/dist/clerk.native.js +4 -4
- package/dist/clerk.no-rhc.js +1 -1
- package/dist/clerk.no-rhc.mjs +1 -1
- package/package.json +4 -4
- /package/dist/{10_clerk.browser_e60823_6.42.0-canary.v20261027184321.js → 10_clerk.browser_5761f4_6.42.0.js} +0 -0
- /package/dist/{10_clerk.legacy.browser_ee7185_6.42.0-canary.v20261027184321.js → 10_clerk.legacy.browser_84ebb5_6.42.0.js} +0 -0
- /package/dist/{121_clerk.native_0ce9ac_6.42.0-canary.v20261027184321.js → 121_clerk.native_2e1f0f_6.42.0.js} +0 -0
- /package/dist/{174_clerk.native_0ce9ac_6.42.0-canary.v20261027184321.js → 174_clerk.native_2e1f0f_6.42.0.js} +0 -0
- /package/dist/{188_clerk.native_0ce9ac_6.42.0-canary.v20261027184321.js → 188_clerk.native_2e1f0f_6.42.0.js} +0 -0
- /package/dist/{321_clerk.browser_e60823_6.42.0-canary.v20261027184321.js → 321_clerk.browser_5761f4_6.42.0.js} +0 -0
- /package/dist/{321_clerk.legacy.browser_ee7185_6.42.0-canary.v20261027184321.js → 321_clerk.legacy.browser_84ebb5_6.42.0.js} +0 -0
- /package/dist/{321_clerk.native_0ce9ac_6.42.0-canary.v20261027184321.js → 321_clerk.native_2e1f0f_6.42.0.js} +0 -0
- /package/dist/{409_clerk.native_0ce9ac_6.42.0-canary.v20261027184321.js → 409_clerk.native_2e1f0f_6.42.0.js} +0 -0
- /package/dist/{494_clerk.browser_e60823_6.42.0-canary.v20261027184321.js → 494_clerk.browser_5761f4_6.42.0.js} +0 -0
- /package/dist/{494_clerk.legacy.browser_ee7185_6.42.0-canary.v20261027184321.js → 494_clerk.legacy.browser_84ebb5_6.42.0.js} +0 -0
- /package/dist/{494_clerk.native_0ce9ac_6.42.0-canary.v20261027184321.js → 494_clerk.native_2e1f0f_6.42.0.js} +0 -0
- /package/dist/{541_clerk.native_0ce9ac_6.42.0-canary.v20261027184321.js → 541_clerk.native_2e1f0f_6.42.0.js} +0 -0
- /package/dist/{569_clerk.native_0ce9ac_6.42.0-canary.v20261027184321.js → 569_clerk.native_2e1f0f_6.42.0.js} +0 -0
- /package/dist/{588_clerk.native_0ce9ac_6.42.0-canary.v20261027184321.js → 588_clerk.native_2e1f0f_6.42.0.js} +0 -0
- /package/dist/{base-account-sdk_clerk.browser_e60823_6.42.0-canary.v20261027184321.js → base-account-sdk_clerk.browser_5761f4_6.42.0.js} +0 -0
- /package/dist/{base-account-sdk_clerk.legacy.browser_ee7185_6.42.0-canary.v20261027184321.js → base-account-sdk_clerk.legacy.browser_84ebb5_6.42.0.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.browser_e60823_6.42.0-canary.v20261027184321.js → coinbase-wallet-sdk_clerk.browser_5761f4_6.42.0.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.legacy.browser_ee7185_6.42.0-canary.v20261027184321.js → coinbase-wallet-sdk_clerk.legacy.browser_84ebb5_6.42.0.js} +0 -0
- /package/dist/{cookieSuffix_clerk.browser_e60823_6.42.0-canary.v20261027184321.js → cookieSuffix_clerk.browser_5761f4_6.42.0.js} +0 -0
- /package/dist/{cookieSuffix_clerk.legacy.browser_ee7185_6.42.0-canary.v20261027184321.js → cookieSuffix_clerk.legacy.browser_84ebb5_6.42.0.js} +0 -0
- /package/dist/{cookieSuffix_clerk.native_0ce9ac_6.42.0-canary.v20261027184321.js → cookieSuffix_clerk.native_2e1f0f_6.42.0.js} +0 -0
- /package/dist/{query-core-vendors_clerk.browser_e60823_6.42.0-canary.v20261027184321.js → query-core-vendors_clerk.browser_5761f4_6.42.0.js} +0 -0
- /package/dist/{query-core-vendors_clerk.legacy.browser_ee7185_6.42.0-canary.v20261027184321.js → query-core-vendors_clerk.legacy.browser_84ebb5_6.42.0.js} +0 -0
- /package/dist/{stripe-vendors_clerk.browser_e60823_6.42.0-canary.v20261027184321.js → stripe-vendors_clerk.browser_5761f4_6.42.0.js} +0 -0
- /package/dist/{stripe-vendors_clerk.legacy.browser_ee7185_6.42.0-canary.v20261027184321.js → stripe-vendors_clerk.legacy.browser_84ebb5_6.42.0.js} +0 -0
- /package/dist/{vendors_clerk.browser_e60823_6.42.0-canary.v20261027184321.js → vendors_clerk.browser_5761f4_6.42.0.js} +0 -0
- /package/dist/{vendors_clerk.legacy.browser_ee7185_6.42.0-canary.v20261027184321.js → vendors_clerk.legacy.browser_84ebb5_6.42.0.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.browser_e60823_6.42.0-canary.v20261027184321.js → zxcvbn-common_clerk.browser_5761f4_6.42.0.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.legacy.browser_ee7185_6.42.0-canary.v20261027184321.js → zxcvbn-common_clerk.legacy.browser_84ebb5_6.42.0.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.browser_e60823_6.42.0-canary.v20261027184321.js → zxcvbn-ts-core_clerk.browser_5761f4_6.42.0.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.legacy.browser_ee7185_6.42.0-canary.v20261027184321.js → zxcvbn-ts-core_clerk.legacy.browser_84ebb5_6.42.0.js} +0 -0
package/dist/clerk.browser.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var i=t();for(var r in i)("object"==typeof exports?exports:e)[r]=i[r]}}(globalThis,()=>(()=>{var e,t,i,r={292(e,t,i){"use strict";let r,n,s,a,o,l,c,d,h,u,p,_,f;try{let e=new URL(document.currentScript.src),t=new URL(e.href.split("/").slice(0,-1).join("/")).href;i.p=(t+=t.endsWith("/")?"":"/").replace(/(^.*\/@clerk\/clerk-js@)(.+?)(\/dist.*)/,"$16.42.0
|
|
1
|
+
!function(e,t){if("object"==typeof exports&&"object"==typeof module)module.exports=t();else if("function"==typeof define&&define.amd)define([],t);else{var i=t();for(var r in i)("object"==typeof exports?exports:e)[r]=i[r]}}(globalThis,()=>(()=>{var e,t,i,r={292(e,t,i){"use strict";let r,n,s,a,o,l,c,d,h,u,p,_,f;try{let e=new URL(document.currentScript.src),t=new URL(e.href.split("/").slice(0,-1).join("/")).href;i.p=(t+=t.endsWith("/")?"":"/").replace(/(^.*\/@clerk\/clerk-js@)(.+?)(\/dist.*)/,"$16.42.0$3")}catch{}function m(){return"u">typeof window}let g=RegExp("bot|spider|crawl|APIs-Google|AdsBot|Googlebot|mediapartners|Google Favicon|FeedFetcher|Google-Read-Aloud|DuplexWeb-Google|googleweblight|bing|yandex|baidu|duckduck|yahoo|ecosia|ia_archiver|facebook|instagram|pinterest|reddit|slack|twitter|whatsapp|youtube|semrush","i"),y=/^(Cloudflare-Workers|Node\.js|Deno|Bun)\b/i;function w(){if("u">typeof window&&window.navigator)return window.navigator;let e=globalThis;return"function"==typeof e.WorkerGlobalScope&&e.self instanceof e.WorkerGlobalScope&&e.self.navigator&&!y.test(e.self.navigator.userAgent??"")?e.self.navigator:null}function b(){var e;let t=w();return!!t&&!((e=t?.userAgent)&&g.test(e))&&!t?.webdriver}function v(){let e=w();return!!e&&("boolean"!=typeof e.onLine||!!e.onLine)}function k(){return v()&&b()}let S=(e,t,i,r,n)=>{let{notify:s}=n||{},a=e.get(i);a||(a=[],e.set(i,a)),a.push(r),s&&t.has(i)&&r(t.get(i))},I=(e,t,i)=>(e.get(t)||[]).map(e=>e(i)),C=(e,t,i)=>{let r=e.get(t);r&&(i?r.splice(r.indexOf(i)>>>0,1):e.set(t,[]))},U=()=>{let e=new Map,t=new Map,i=new Map;return{on:(...i)=>S(e,t,...i),prioritizedOn:(...e)=>S(i,t,...e),emit:(r,n)=>{t.set(r,n),I(i,r,n),I(e,r,n)},off:(...t)=>C(e,...t),prioritizedOff:(...e)=>C(i,...e),internal:{retrieveListeners:t=>e.get(t)||[]}}},A="status";function P(e){return function(t){let i=t??this;if(!i)throw TypeError(`${e.kind||e.name} type guard requires an error object`);return!!e.kind&&"object"==typeof i&&null!==i&&"constructor"in i&&i.constructor?.kind===e.kind||i instanceof e}}var T,O,E,x=class e extends Error{static kind="ClerkError";clerkError=!0;code;longMessage;docsUrl;cause;get name(){return this.constructor.name}constructor(t){super(new.target.formatMessage(new.target.kind,t.message,t.code,t.docsUrl),{cause:t.cause}),Object.setPrototypeOf(this,e.prototype),this.code=t.code,this.docsUrl=t.docsUrl,this.longMessage=t.longMessage,this.cause=t.cause}toString(){return`[${this.name}]
|
|
2
2
|
Message:${this.message}`}static formatMessage(e,t,i,r){let n="Clerk:",s=RegExp(n.replace(" ","\\s*"),"i");return t=t.replace(s,""),t=`${n} ${t.trim()}
|
|
3
3
|
|
|
4
4
|
(code="${i}")
|
|
@@ -43,4 +43,4 @@ ${t.message}`)}})(eB(e)):e).some(e=>e.test(eB(r.origin))));return s||eR(`Clerk:
|
|
|
43
43
|
${e.trim()}
|
|
44
44
|
(This notice only appears in development)`,e4=e=>e2(`${e} as a function is not supported in this environment. The value will be ignored. Provide an absolute URL instead.`),e5={proxyUrlAsFunctionNotSupported:e4("proxyUrl"),domainAsFunctionNotSupported:e4("domain"),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.",createCannotRenderComponentWhenOrgDoesNotExist:e=>e2(`<${e}/> cannot render unless an organization is active. Since no organization is currently active, this is no-op.`),createCannotRenderComponentWhenPermissionIsMissing:(e,t)=>e2(`<${e}/> cannot render unless the current user has the \`${t}\` permission. Since the current user is missing this permission, this is no-op. Render it only for members who can manage memberships, for example by wrapping it in <Show when={{ permission: '${t}' }}>.`),cannotRenderAnyOrganizationComponent:e=>e2(`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=>e2(`The <${e}/> component cannot be rendered when billing is disabled. Visit 'https://dashboard.clerk.com/~/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/> and <SignUp/> modals are hidden because a user is already signed in and this application is configured for single-session mode. This is expected behavior — no action is needed. To allow rendering while signed in, enable multi-session mode in your Clerk Dashboard.",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.",cannotRenderOAuthConsentComponentWhenUserDoesNotExist:"<OAuthConsent/> cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotRenderOAuthDeviceVerificationComponentWhenUserDoesNotExist:"<OAuthDeviceVerification/> cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotRenderConfigureSSOComponentWhenUserDoesNotExist:"<ConfigureSSO/> cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotRenderConfigureSSOComponentWhenDisabled:"The <ConfigureSSO/> component cannot be rendered when self-serve SSO is disabled. Visit `https://dashboard.clerk.com` to enable the feature. Since self-serve SSO is disabled, this is no-op.",cannotRenderConfigureDirectorySyncComponentWhenDisabled:"The <ConfigureDirectorySync/> component cannot be rendered when self-serve Directory Sync is disabled. Since self-serve Directory Sync is disabled, this is no-op.",cannotRenderConfigureSSOComponentWhenEmailAddressDisabled:"The <ConfigureSSO/> component cannot be rendered when email addresses are disabled on the instance. Visit `https://dashboard.clerk.com` to enable email addresses. Since email addresses are disabled, this is no-op."};for(let e of Object.keys(e5)){let t=e5[e];"function"!=typeof t&&(e5[e]=e2(t))}let e6="clerk:beforeunload",e8=["http:","https:","wails:","chrome-extension:"],e9=/^[/\\][/\\]/;function e7(e){return/^http(s)?:\/\//.test(e||"")}function te(e){return e.startsWith("/")}let tt=[".vercel.app"],ti=["CI","CONTINUOUS_INTEGRATION","GITHUB_ACTIONS","GITLAB_CI","CIRCLECI","TRAVIS","BUILDKITE","BITBUCKET_BUILD_NUMBER","APPVEYOR","CODEBUILD_BUILD_ID","TF_BUILD","TEAMCITY_VERSION","JENKINS_URL","HUDSON_URL","BAMBOO_BUILDKEY","CF_PAGES"],tr=Symbol.for("@clerk/shared.telemetryNoticeShown"),tn=["Attention: Clerk collects telemetry data from its SDKs when connected to development instances.","The data collected is used to inform Clerk's product roadmap.","To learn more, including how to opt-out from the telemetry program, visit: https://clerk.com/docs/telemetry."];var ts=class{#l;#c=864e5;constructor(e){this.#l=e}isEventThrottled(e){let t=Date.now(),i=this.#d(e),r=this.#l.getItem(i);return!!r&&!(t-r>this.#c)||(this.#l.setItem(i,t),!1)}#d(e){let{sk:t,pk:i,payload:r,...n}=e,s={...r,...n};return JSON.stringify(Object.keys({...r,...n}).sort().map(e=>s[e]))}},ta=class{#h="clerk_telemetry_throttler";getItem(e){return this.#u()[e]}setItem(e,t){try{let i=this.#u();i[e]=t,localStorage.setItem(this.#h,JSON.stringify(i))}catch(e){e instanceof DOMException&&("QuotaExceededError"===e.name||"NS_ERROR_DOM_QUOTA_REACHED"===e.name)&&localStorage.length>0&&localStorage.removeItem(this.#h)}}removeItem(e){try{let t=this.#u();delete t[e],localStorage.setItem(this.#h,JSON.stringify(t))}catch{}}#u(){try{let e=localStorage.getItem(this.#h);if(!e)return{};return JSON.parse(e)}catch{return{}}}static isSupported(){return"u">typeof window&&!!window.localStorage}},to=class{#l=new Map;#p=1e4;getItem(e){return this.#l.size>this.#p?void this.#l.clear():this.#l.get(e)}setItem(e,t){this.#l.set(e,t)}removeItem(e){this.#l.delete(e)}};let tl=new Set(["error","warn","info","debug","trace"]);var tc=class{#_;#f;#m={};#g=[];#y=null;constructor(e){this.#_={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&&"u"<typeof window?this.#m.clerkVersion="":this.#m.clerkVersion=e.clerkVersion??"",this.#m.sdk=e.sdk,this.#m.sdkVersion=e.sdkVersion,this.#m.publishableKey=e.publishableKey??"";const t=eC(e.publishableKey);t&&(this.#m.instanceType=t.instanceType),e.secretKey&&(this.#m.secretKey=e.secretKey.substring(0,16));const i=ta.isSupported()?new ta:new to;this.#f=new ts(i),function(e={}){if(!e.skip)try{if("u">typeof window||void 0!==globalThis.EdgeRuntime||!("u"<typeof process)&&process.env&&ti.some(e=>em(process.env[e]))||globalThis[tr])return;if("u">typeof console&&"function"==typeof console.log){for(let e of tn)console.log(e);console.log("")}globalThis[tr]=!0}catch{}}({skip:!this.isEnabled})}get isEnabled(){return!("development"!==this.#m.instanceType||this.#_.disabled||"u">typeof process&&process.env&&em(process.env.CLERK_TELEMETRY_DISABLED)||"u">typeof window&&window?.navigator?.webdriver)}get isDebug(){return this.#_.debug||"u">typeof process&&process.env&&em(process.env.CLERK_TELEMETRY_DEBUG)}record(e){try{let t=this.#w(e.event,e.payload);if(this.#b(t.event,t),!this.#v(t,e.eventSamplingRate))return;this.#g.push({kind:"event",value:t}),this.#k()}catch(e){console.error("[clerk/telemetry] Error recording telemetry event",e)}}recordLog(e){try{if(!this.#S(e))return;let t="string"==typeof e?.level&&tl.has(e.level),i="string"==typeof e?.message&&e.message.trim().length>0,r=null,n=e?.timestamp;if("number"==typeof n||"string"==typeof n){let e=new Date(n);Number.isNaN(e.getTime())||(r=e)}if(!t||!i||null===r){this.isDebug&&"u">typeof console&&console.warn("[clerk/telemetry] Dropping invalid telemetry log entry",{levelIsValid:t,messageIsValid:i,timestampIsValid:null!==r});return}let s=this.#I(),a={sdk:s.name,sdkv:s.version,cv:this.#m.clerkVersion??"",lvl:e.level,msg:e.message,ts:r.toISOString(),pk:this.#m.publishableKey||null,payload:this.#C(e.context)};this.#g.push({kind:"log",value:a}),this.#k()}catch(e){console.error("[clerk/telemetry] Error recording telemetry log entry",e)}}#v(e,t){return this.isEnabled&&!this.isDebug&&this.#U(e,t)}#S(e){return!0}#U(e,t){let i=Math.random();return!!(i<=this.#_.samplingRate&&(!1===this.#_.perEventSampling||void 0===t||i<=t))&&!this.#f.isEventThrottled(e)}#k(){if("u"<typeof window)return void this.#A();if(this.#g.length>=this.#_.maxBufferSize){this.#y&&("u">typeof cancelIdleCallback?cancelIdleCallback(Number(this.#y)):clearTimeout(Number(this.#y))),this.#A();return}this.#y||("requestIdleCallback"in window?this.#y=requestIdleCallback(()=>{this.#A(),this.#y=null}):this.#y=setTimeout(()=>{this.#A(),this.#y=null},0))}#A(){let e=[...this.#g];if(this.#g=[],this.#y=null,0===e.length)return;let t=e.filter(e=>"event"===e.kind).map(e=>e.value),i=e.filter(e=>"log"===e.kind).map(e=>e.value);t.length>0&&fetch(new URL("/v1/event",this.#_.endpoint),{headers:{"Content-Type":"application/json"},keepalive:!0,method:"POST",body:JSON.stringify({events:t})}).catch(()=>void 0),i.length>0&&fetch(new URL("/v1/logs",this.#_.endpoint),{headers:{"Content-Type":"application/json"},keepalive:!0,method:"POST",body:JSON.stringify({logs:i})}).catch(()=>void 0)}#b(e,t){this.isDebug&&(void 0!==console.groupCollapsed?(console.groupCollapsed("[clerk/telemetry]",e),console.log(t),console.groupEnd()):console.log("[clerk/telemetry]",e,t))}#I(){let e={name:this.#m.sdk,version:this.#m.sdkVersion};if("u">typeof window){let t=window;if(t.Clerk){let i=t.Clerk;if("object"==typeof i&&null!==i&&"constructor"in i&&"function"==typeof i.constructor&&i.constructor.sdkMetadata){let{name:t,version:r}=i.constructor.sdkMetadata;void 0!==t&&(e.name=t),void 0!==r&&(e.version=r)}}}return e}#w(e,t){let i=this.#I();return{event:e,cv:this.#m.clerkVersion??"",it:this.#m.instanceType??"",sdk:i.name,sdkv:i.version,...this.#m.publishableKey?{pk:this.#m.publishableKey}:{},...this.#m.secretKey?{sk:this.#m.secretKey}:{},payload:t}}#C(e){if(null==e||"object"!=typeof e)return null;try{let t=JSON.parse(JSON.stringify(e));if(t&&"object"==typeof t&&!Array.isArray(t))return t;return null}catch{return null}}};let td="COMPONENT_MOUNTED",th=new Set(["SignIn","SignUp"]);function tu(e){return function(t,i,r){return{event:e,eventSamplingRate:e===td?th.has(t)?1:.1:.1,payload:{component:t,appearanceProp:!!i?.appearance,theme:!!i?.appearance?.theme,elements:!!i?.appearance?.elements,variables:!!i?.appearance?.variables,...r}}}}function tp(e,t,i){return tu(td)(e,t,i)}function t_(e,t,i){return tu("COMPONENT_OPENED")(e,t,i)}function tf(e){return"string"==typeof e?e:"object"==typeof e&&null!==e&&"name"in e&&"string"==typeof e.name?e.name:void 0}var tm=i(6100);let tg=!1,ty=null,tw=!1,tb=[];function tv(e,t,i,r){tg&&(tb.push({level:e,message:t,context:i,source:r,ts:Date.now()}),tb.length>200&&tb.shift())}async function tk(e){try{if(!tg||ty)return;let{getDebugLogger:t}=await i.e(321).then(i.bind(i,9296)),r=await t({logLevel:e?.logLevel,telemetryCollector:e?.telemetryCollector});if(r&&(ty=r)&&0!==tb.length){for(let e of tb){let t={...e.context||{},__preInit:!0,__preInitTs:e.ts};switch(e.level){case"error":ty.error(e.message,t,e.source);break;case"warn":ty.warn(e.message,t,e.source);break;case"info":ty.info(e.message,t,e.source);break;case"debug":ty.debug(e.message,t,e.source)}}tb.length=0}}catch(e){try{console.debug?.("Debug logger initialization failed",e)}catch{}return}}let tS={debug(e,t,i){ty?ty.debug(e,t,i):tv("debug",e,t,i)},error(e,t,i){ty?ty.error(e,t,i):tv("error",e,t,i)},info(e,t,i){ty?ty.info(e,t,i):tv("info",e,t,i)},warn(e,t,i){ty?ty.warn(e,t,i):tv("warn",e,t,i)}},tI={initialDelay:125,maxDelayBetweenRetries:0,factor:2,shouldRetry:(e,t)=>t<5,retryImmediately:!1,jitter:!0},tC=async e=>new Promise(t=>setTimeout(t,e)),tU=(e,t)=>t?e*(1+Math.random()):e,tA=async(e,t={})=>{var i;let r,n=0,{shouldRetry:s,initialDelay:a,maxDelayBetweenRetries:o,factor:l,retryImmediately:c,jitter:d,onBeforeRetry:h}={...tI,...t},u=(i={initialDelay:a,maxDelayBetweenRetries:o,factor:l,jitter:d},r=0,async()=>{let e;await tC((e=tU(e=i.initialDelay*Math.pow(i.factor,r),i.jitter),Math.min(i.maxDelayBetweenRetries||e,e))),r++});for(;;)try{return await e()}catch(e){if(!s(e,++n))throw e;h&&await h(n),c&&1===n?await tC(tU(100,d)):await u()}},tP=async e=>tA(e,{initialDelay:100,shouldRetry:(e,t)=>t<=3,retryImmediately:!0,factor:2});class tT{#P={"@zxcvbn-ts/core":()=>tP(()=>i.e(729).then(i.bind(i,3239))),"@zxcvbn-ts/language-common":()=>tP(()=>i.e(873).then(i.bind(i,9144))),"@base-org/account":()=>tP(()=>Promise.all([i.e(994),i.e(929),i.e(545)]).then(i.bind(i,8))),"@coinbase/wallet-sdk":()=>tP(()=>Promise.all([i.e(994),i.e(929),i.e(545)]).then(i.bind(i,76))),"@stripe/stripe-js":()=>tP(()=>i.e(279).then(i.bind(i,7544)))};import(e){return this.#P[e]?this.#P[e]():Promise.resolve(void 0)}}let tO=(e=!1)=>{let t,i;if(!e)return{track:async e=>{await e()},isUnloading:()=>!1};let r=(t=!1,i=()=>t=!0,{startListening:()=>{window.addEventListener("beforeunload",i),window.addEventListener(e6,i)},stopListening:()=>{window.removeEventListener("beforeunload",i),window.removeEventListener(e6,i)},isUnloading:()=>t});return{track:async e=>{r.startListening(),await e(),r.stopListening()},isUnloading:r.isUnloading}};function tE(e){let t=new Date(e||new Date);return t instanceof Date&&!isNaN(t.getTime())?t:new Date}let tx=e=>({amount:e.amount,amountFormatted:e.amount_formatted,currency:e.currency,currencySymbol:e.currency_symbol}),tR=e=>({quantity:e.quantity,feePerBlock:tx(e.fee_per_block),total:tx(e.total)}),tM=e=>e.map(e=>({name:e.name,blockSize:e.block_size,tiers:e.tiers.map(tR)})),tz=e=>({name:e.name,blockSize:e.block_size,tiers:e.tiers.map(e=>({id:e.id,startsAtBlock:e.starts_at_block,endsAfterBlock:e.ends_after_block,feePerBlock:tx(e.fee_per_block)}))}),tF=e=>({proration:e.proration?{amount:tx(e.proration.amount),cycleDaysRemaining:e.proration.cycle_days_remaining,cycleDaysTotal:e.proration.cycle_days_total,cycleRemainingPercent:e.proration.cycle_remaining_percent}:null,payer:e.payer?{remainingBalance:tx(e.payer.remaining_balance),appliedAmount:tx(e.payer.applied_amount)}:null,total:tx(e.total)}),tN=e=>({proration:e.proration?{amount:tx(e.proration.amount),cycleDaysPassed:e.proration.cycle_days_passed,cycleDaysTotal:e.proration.cycle_days_total,cyclePassedPercent:e.proration.cycle_passed_percent}:null,discount:e.discount?tD(e.discount):void 0,total:tx(e.total)}),tD=e=>({amount:tx(e.amount),discountId:e.discount_id,name:e.name,effect:e.effect,percentOff:e.percent_off,amountOff:e.amount_off?tx(e.amount_off):void 0,promoCode:e.promo_code,cyclesRemaining:e.cycles_remaining,durationInCycles:e.duration_in_cycles}),tW=e=>({subtotal:tx(e.subtotal),baseFee:tx(e.base_fee),taxTotal:tx(e.tax_total),grandTotal:tx(e.grand_total),perUnitTotals:e.per_unit_totals?tM(e.per_unit_totals):void 0}),tL=e=>({subtotal:tx(e.subtotal),baseFee:e.base_fee?tx(e.base_fee):null,taxTotal:tx(e.tax_total),grandTotal:tx(e.grand_total),totalDueAfterFreeTrial:e.total_due_after_free_trial?tx(e.total_due_after_free_trial):null,credit:e.credit?tx(e.credit):e.credit,credits:e.credits?tF(e.credits):null,discounts:e.discounts?tN(e.discounts):null,pastDue:e.past_due?tx(e.past_due):e.past_due,totalDueNow:e.total_due_now?tx(e.total_due_now):void 0,perUnitTotals:e.per_unit_totals?tM(e.per_unit_totals):void 0,totalsDuePerPeriod:e.totals_due_per_period?tW(e.totals_due_per_period):void 0,totalDuePerPeriod:e.total_due_per_period?tx(e.total_due_per_period):void 0}),t$=e=>({amount:tx(e.amount),date:tE(e.date),perUnitTotals:e.per_unit_totals?tM(e.per_unit_totals):void 0,totals:e.totals?tL(e.totals):void 0}),tj=({signUp:e,continueSignUpUrl:t,verifyEmailAddressUrl:i,verifyPhoneNumberUrl:r,signUpProtectCheckUrl:n,enterpriseConnectionsUrl:s,navigate:a})=>e.protectCheck||e.missingFields.includes("protect_check")?a(n):s&&e.missingFields.includes("enterprise_sso")?a(s):e.missingFields.length?a(t):(({signUp:e,verifyEmailPath:t,verifyPhonePath:i,protectCheckPath:r,continuePath:n,navigate:s,handleComplete:a,redirectUrl:o,redirectUrlComplete:l,oidcPrompt:c})=>{if("complete"===e.status)return eY("__clerk_ticket"),eY("__clerk_invitation_token"),a&&a();if("missing_requirements"===e.status){if((e.protectCheck||e.missingFields.some(e=>"protect_check"===e))&&r)return s(r,{searchParams:eZ()});if(e.missingFields.some(e=>"enterprise_sso"===e)){if(!o||!l)throw Error("completeSignUpFlow: `redirectUrl` and `redirectUrlComplete` are required to continue a sign-up that is missing `enterprise_sso`.");return e.authenticateWithRedirect({strategy:"enterprise_sso",redirectUrl:o,redirectUrlComplete:l,continueSignUp:!0,oidcPrompt:c})}let a=eZ();if(e.unverifiedFields?.includes("email_address")&&t)return s(t,{searchParams:a});if(e.unverifiedFields?.includes("phone_number")&&i)return s(i,{searchParams:a});if(n)return s(n,{searchParams:a})}})({signUp:e,verifyEmailPath:i,verifyPhonePath:r,protectCheckPath:n,navigate:a});function tB(e,t=""){return e.errors&&!!e.errors.find(e=>e.code===t)}let tJ=K({packageName:"@clerk/clerk-js"});function tK(e){return decodeURIComponent(globalThis.atob(e.replace(/_/g,"/").replace(/-/g,"+")).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""))}function tV(e){let t=(e||"").split("."),[i,r,n]=t;if(3!==t.length||!i||!r||!n)throw Error("JWT could not be decoded");let s=JSON.parse(tK(r)),a={__raw:e};return Object.keys(s).forEach(e=>{a[e]=s[e]}),{encoded:{header:i,payload:r,signature:n},header:JSON.parse(tK(i)),claims:a}}function tq(){if(!m())return null;try{let e=navigator?.language;if(!e||"string"!=typeof e||""===e.trim())return null;return e}catch{return null}}function tH(){return void 0!==globalThis.document}function tG(){if(!function(){if(!tH())return!1;try{return window.self!==window.top}catch{return!0}}())return!1;try{return window.top?.location.href,!1}catch{return!0}}var tQ=class e{#T=[];#O={metamask:"MetaMask",okx_wallet:"OKX Wallet"};static #E=null;constructor(){if("u"<typeof window)return;window.addEventListener("eip6963:announceProvider",this.#x),window.dispatchEvent(new Event("eip6963:requestProvider"))}static getInstance(){return e.#E||(e.#E=new e),e.#E}get=e=>{let t=this.#T.find(t=>t.info.name===this.#O[e])?.provider;return void 0!==t?t:window.ethereum};#x=e=>{this.#T.some(t=>t.info.uuid===e.detail.info.uuid)||this.#T.push(e.detail)}},tX=class e{#R=void 0;#M=!1;static #E=null;async #z(){if(this.#M)return;this.#M=!0;let e=await i.e(494).then(i.bind(i,1629)).then(e=>e.getWallets());this.#R=e.get(),e.on("register",()=>{this.#R=e.get()}),e.on("unregister",()=>{this.#R=e.get()})}#F(e){return e.chains?.some(e=>e.startsWith("solana:"))??!1}#N(e){return"solana:signMessage"in e.features}static getInstance(){return e.#E||(e.#E=new e),e.#E}get=async e=>{await this.#z();let t=(this.#R||[]).find(t=>t.name===e&&this.#F(t)&&this.#N(t));if(t&&this.#F(t))return t;if("u"<typeof window)return;let i=window.solana;if(i&&"function"==typeof i.connect&&"function"==typeof i.signMessage)return i}};let tY=()=>(function(e){let t=K({packageName:"@clerk/shared"});async function i(e){let{provider:t,walletName:i}=e,r=await _(t,i);if(!r)return"";if("solana"===t){let e=await r.features["standard:connect"].connect();return e&&e.accounts[0].address||""}let n=await r.request({method:"eth_requestAccounts"});return n&&n[0]||""}let r=async e=>{let{identifier:t,nonce:i,provider:r,walletName:n=""}=e,s=await _(r,n);if(!s)return"";if("solana"===r)try{let e=s.accounts.find(e=>e.address===t);if(!e)return console.warn(`Wallet account with address ${t} not found`),"";let r=await s.features["solana:signMessage"]?.signMessage({account:e,message:new TextEncoder().encode(i)});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 R("Web3 signature request was rejected by the user.",{code:"web3_signature_request_rejected"});throw new R("An error occurred while generating the Solana signature.",{code:"web3_solana_signature_generation_failed",cause:e instanceof Error?e:void 0})}return await s.request({method:"personal_sign",params:[`0x${i.split("").map(e=>e.charCodeAt(0).toString(16).padStart(2,"0")).join("")}`,t]})};async function n(){return await i({provider:"metamask"})}async function s(){return await i({provider:"coinbase_wallet"})}async function a(){return await i({provider:"okx_wallet"})}async function o(){return await i({provider:"base"})}async function l(e){return await i({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 h(e){return await r({...e,provider:"okx_wallet"})}async function u(e){return await r({...e,provider:"base"})}async function p(e){return await r({...e,provider:"solana"})}async function _(i,r){if("coinbase_wallet"===i){let t=await e.import("@coinbase/wallet-sdk");return t?t.createCoinbaseWalletSDK({appName:"u">typeof window&&window.Clerk?.__internal_environment?.displayConfig?.applicationName||"u">typeof document&&document.title||"Web3 Application",preference:{options:"all"}}).getProvider():null}if("base"===i)try{let t=await e.import("@base-org/account");if(!t)return null;return t.createBaseAccountSDK({appName:"u">typeof window&&window.Clerk?.__internal_environment?.displayConfig?.applicationName||"u">typeof document&&document.title||"Web3 Application"}).getProvider()}catch{return null}return"solana"===i?r&&0!==r.length?await tX.getInstance().get(r):void t.throw("Wallet name must be provided to get Solana wallet provider"):tQ.getInstance().get(i)}return{getWeb3Identifier:i,generateWeb3Signature:r,getMetamaskIdentifier:n,getCoinbaseWalletIdentifier:s,getOKXWalletIdentifier:a,getBaseIdentifier:o,getSolanaIdentifier:l,generateSignatureWithMetamask:c,generateSignatureWithCoinbaseWallet:d,generateSignatureWithOKXWallet:h,generateSignatureWithBase:u,generateSignatureWithSolana:p}})(new tT),tZ="environment",t0=JSON.stringify,t1=JSON.parse;class t3{static _key(e){return`__clerk_${e}`}static isExpired(e){return!!e.exp&&Date.now()>e.exp}static setItem(e,t,i){try{let r={value:t,...i&&{exp:Date.now()+i}};window.localStorage.setItem(this._key(e),t0(r))}catch{}}static getItem(e,t){try{let i=window.localStorage.getItem(this._key(e));if(!i)return t;let r=t1(i);if(!r)return t;if(this.isExpired(r))return this.removeItem(e),t;return r?.value??t}catch{return t}}static removeItem(e){try{window.localStorage.removeItem(this._key(e))}catch{}}}let t2="ClerkJS:";function t4(e=""){throw Error(`${t2} Something went wrong initializing Clerk in development mode.${e&&` ${e}`}`)}function t5(e){throw Error(`${t2} Something went wrong initializing Clerk during the ${e} flow. Please contact support.`)}function t6(e){throw Error(`${t2} You need to start a ${e} flow by calling ${e}.create() first.`)}function t8(e,t){throw Error(`${t2} Strategy "${t}" is not a valid strategy for ${e}.`)}function t9(e){throw Error(`${t2} You need to start a ${e} flow by calling ${e}.create({ identifier: 'your web3 wallet address' }) first`)}function t7(e=""){throw Error(`${t2} Missing '${e}' option`)}function ie(e,t){throw Error(`${t2} Response: ${e||0} not supported yet.
|
|
45
45
|
For more information contact us at ${t}`)}function it(e){throw Error(`${t2} Calling ${e}.reload is not currently supported. Please contact support.`)}function ii(e){throw Error(`${t2} Missing publicKey. When calling 'navigator.credentials.${e}()' it is required to pass a publicKey object.`)}async function ir(e="",t){let{async:i,defer:r,beforeLoad:n,crossOrigin:s,nonce:a}=t||{};return tA(()=>new Promise((t,o)=>{e||o(Error("loadScript cannot be called without a src")),document&&document.body||o(Error("loadScript cannot be called when document does not exist"));let l=document.createElement("script");s&&l.setAttribute("crossorigin",s),l.async=i||!1,l.defer=r||!1,l.addEventListener("load",()=>{l.remove(),t(l)}),l.addEventListener("error",t=>{l.remove(),o(t.error??Error(`failed to load script: ${e}`))}),l.src=e,a&&(l.nonce=a),n?.(l),document.body.appendChild(l)}),{shouldRetry:(e,t)=>t<=5})}async function is(e){return window.turnstile||await ia(e).catch(()=>{throw{captchaError:"captcha_script_failed_to_load"}}),window.turnstile}async function ia(e){try{return await ir("https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit",{defer:!0,nonce:e})}catch(e){throw console.warn("Clerk: Failed to load the CAPTCHA script from Cloudflare. If you see a CSP error in your browser, please add the necessary CSP rules to your app. Visit https://clerk.com/docs/security/clerk-csp for more information."),e}}function io(e){try{let t=e.getAttribute("data-cl-theme")||void 0,i=e.getAttribute("data-cl-language")||void 0,r=e.getAttribute("data-cl-size")||void 0;return{theme:t,language:i,size:r}}catch{return{theme:void 0,language:void 0,size:void 0}}}let il=async e=>{let t,i,r,n,{siteKey:s,widgetType:a,invisibleSiteKey:o,nonce:l}=e,{modalContainerQuerySelector:c,modalWrapperQuerySelector:d,closeModal:h,openModal:u}=e,p=await is(l),_=[],f="",m="",g=s,y=0,w=null,b="invisible";if(c&&d){w=a,n=c,b="modal";try{await u?.()}catch{throw{captchaError:"modal_component_not_ready"}}let e=await new Promise(e=>{if(document.querySelector(c))return e(document.querySelector(c));let t=new MutationObserver(()=>{document.querySelector(c)&&(t.disconnect(),e(document.querySelector(c)))});t.observe(document.body,{childList:!0,subtree:!0})});if(e){let{theme:n,language:s,size:a}=io(e);t=n,r=s,i=a}}if(!n&&"smart"===a){let e=document.getElementById(ec);if(e){b="smart",w="smart",n=`#${ec}`,e.style.maxHeight="0";let{theme:s,language:a,size:o}=io(e);t=s,r=a,i=o}else console.error("Cannot initialize Smart CAPTCHA widget because the `clerk-captcha` DOM element was not found; falling back to Invisible CAPTCHA widget. If you are using a custom flow, visit https://clerk.com/docs/guides/development/custom-flows/authentication/bot-sign-up-protection for instructions")}if(!n){b="invisible",g=o,w="invisible",n=`.${ed}`;let e=document.createElement("div");e.classList.add(ed),e.style.display="none",document.body.appendChild(e)}let v=async()=>new Promise((s,a)=>{try{let o=p.render(n,{sitekey:g,appearance:"interaction-only",theme:t||"auto",size:i||"normal",language:r||"auto",action:e.action,retry:"never","refresh-expired":"auto",callback:function(e){h?.(),s([e,o])},"before-interactive-callback":()=>{if(d){let e=document.querySelector(d);e?.style.setProperty("visibility","visible"),e?.style.setProperty("pointer-events","all")}else{let e=document.getElementById(ec);e&&(e.style.maxHeight="unset",e.style.minHeight="compact"===i?"140px":"68px",e.style.marginBottom="1.5rem",e.dataset.clInteractive="true")}},"error-callback":function(e){var t;(_.push(e),y<2&&(t=e.toString(),["crashed","undefined_error","102","103","104","106","110600","300","600"].find(e=>t.startsWith(e))))?setTimeout(()=>{n&&!document.querySelector(n)?a([_.join(","),o]):(p.reset(o),y++)},250):a([_.join(","),o])},"unsupported-callback":function(){return a(["This browser is not supported by the CAPTCHA.",o]),!0}})}catch(e){a([e,void 0])}});try{[f,m]=await v(),p.remove(m)}catch([e,t]){throw t&&p.remove(t),{captchaError:e}}finally{if("modal"===b&&h?.(),"invisible"===b){let e=document.querySelector(`.${ed}`);e&&document.body.removeChild(e)}if("smart"===b){let e=document.getElementById(ec);e&&(delete e.dataset.clInteractive,e.style.maxHeight="0",e.style.minHeight="unset",e.style.marginBottom="unset")}}return{captchaToken:f,captchaWidgetType:w}},ic=e=>{let t=e.__internal_environment,i=t?t.displayConfig.captchaProvider:"turnstile",r=e.__internal_getOption?.("nonce");return{captchaSiteKey:t?t.displayConfig.captchaPublicKey:null,captchaWidgetType:t?t.displayConfig.captchaWidgetType:null,captchaProvider:i,captchaPublicKeyInvisible:t?t.displayConfig.captchaPublicKeyInvisible:null,canUseCaptcha:t?t.userSettings.signUp.captcha_enabled&&e.isStandardBrowser:null,nonce:r||void 0}};class id{clerk;constructor(e){this.clerk=e}async invisible(e){let{captchaSiteKey:t,canUseCaptcha:i,captchaPublicKeyInvisible:r,nonce:n}=ic(this.clerk);return i&&t&&r?{...await il({action:e?.action,captchaProvider:"turnstile",invisibleSiteKey:r,nonce:e?.nonce||n||void 0,siteKey:r,widgetType:"invisible"}).catch(e=>e.captchaError?{captchaError:e.captchaError}:{captchaError:e?.message||e||"unexpected_captcha_error"}),captchaAction:e?.action}:{captchaError:"captcha_unavailable",captchaAction:e?.action}}async managedOrInvisible(e){let{captchaSiteKey:t,canUseCaptcha:i,captchaWidgetType:r,captchaProvider:n,captchaPublicKeyInvisible:s,nonce:a}=ic(this.clerk);if(i&&t&&s){let i=await il({captchaProvider:n,invisibleSiteKey:s,nonce:a||void 0,siteKey:t,widgetType:r,...e}).catch(t=>t.captchaError?{captchaError:t.captchaError}:e?.action==="verify"?{captchaError:t?.message||t||"unexpected_captcha_error"}:void 0);return e?.action==="verify"?{...i,captchaAction:"verify"}:i}return e?.action==="verify"?{captchaError:"captcha_unavailable",captchaAction:e?.action}:{}}async managedInModal(e){if("u"<typeof document)throw new R("Captcha is not supported in non-browser environments",{code:"captcha_unavailable"});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 ih{client;CaptchaChallengeImpl;static instance;inflightException=null;captchaRetryCount=0;MAX_RETRY_ATTEMPTS=3;static getInstance(){return ih.instance||(ih.instance=new ih(rz,id)),ih.instance}constructor(e,t){this.client=e,this.CaptchaChallengeImpl=t}async execute(e,t){if(this.captchaAttemptsExceeded())throw new R("Security verification failed. Please try again by refreshing the page, clearing your browser cookies, or using a different web browser.",{code:"captcha_client_attempts_exceeded"});try{return this.inflightException&&await this.inflightException,await t()}catch(r){let i;if(!$(r)||M(r)&&"network_error"===r.code||r.errors[0]?.code!=="requires_captcha")throw r;if(this.inflightException)return await this.inflightException,await t();this.inflightException=new Promise(e=>i=e);try{let t=await this.managedChallenge(e);t?.captchaError!=="modal_component_not_ready"&&(await this.client.getOrCreateInstance().__internal_sendCaptchaToken(t),this.captchaRetryCount=0)}catch(e){throw this.captchaRetryCount++,e}finally{i(),this.inflightException=null}return await t()}}managedChallenge(e){return new this.CaptchaChallengeImpl(e).managedInModal({action:"verify"})}captchaAttemptsExceeded=()=>this.captchaRetryCount>=this.MAX_RETRY_ATTEMPTS}class iu{static clerk;id;pathRoot="";#D;static get fapiClient(){return iu.clerk.getFapiClient()}async reload(e){let{rotatingTokenNonce:t}=e||{};return this._baseGet({forceUpdateClient:!0,rotatingTokenNonce:t})}isNew(){return!this.id}static async _fetch(e,t={}){return ih.getInstance().execute(this.clerk,()=>this._baseFetch(e,t))}static async _baseFetch(e,t={}){let i;iu.fapiClient||function(){throw Error(`${t2} Missing FAPI client in resources.`)}();let{fetchMaxTries:r}=t;try{i=await iu.fapiClient.request(e,{fetchMaxTries:r})}catch(t){if(this.shouldRethrowOfflineNetworkErrors())throw new R(t?.message||t,{code:"network_error"});if(!k())return tS.warn("Network request failed while offline, returning null",{method:e.method,path:e.path},"baseResource"),null;throw t}let{payload:n,status:s,statusText:a,headers:o}=i;if(o){let e=o.get("x-country");this.clerk.__internal_setCountry(e?e.toLowerCase():null)}if(("GET"!==e.method||t.forceUpdateClient)&&!t.skipUpdateClient&&this._updateClient(n),s>=200&&s<=299)return n;if(s>=400){let e=n?.errors,t=e?.[0]?.long_message,i=e?.[0]?.code;401===s&&"dev_browser_unauthenticated"===i?await iu.clerk.__internal_handleUnauthenticatedDevBrowser():401===s&&"requires_captcha"!==i&&await iu.clerk.handleUnauthenticated(),function(e,t){var i;if(!t||!t[0])return;let r=t[0],n=r.long_message;if("origin_invalid"===r.code&&((i=iu.clerk.publishableKey).startsWith("live_")||i.startsWith("pk_live_"))){let i=iu.clerk.frontendApi.replace("clerk.","");throw new L(`Clerk: Production Keys are only allowed for domain "${i}".
|
|
46
|
-
API Error: ${n}`,{data:t,status:e})}}(s,e);let r={data:e,status:s};if(429===s&&o){let e=o.get("retry-after");if(e){let t=parseInt(e,10);isNaN(t)||(r.retryAfter=t)}}throw new L(t||a,r)}return null}static _updateClient(e){let t=rM(e);t&&iu.clerk&&iu.clerk.updateClient(t)}path(e){let t=this.pathRoot;if(this.isNew())return t;let i=t.replace(/[^/]$/,"$&/")+encodeURIComponent(this.id);return e?i.replace(/[^/]$/,"$&/")+encodeURIComponent(e):i}withDefault(e,t){return e??t}async _baseGet(e={}){let t=await iu._fetch({method:"GET",path:this.path(),rotatingTokenNonce:e.rotatingTokenNonce,signal:e.abortSignal},e);return this.fromJSON(t?.response||t)}async _baseMutate(e){let{action:t,body:i,method:r,path:n,signal:s}=e,a=await iu._fetch({method:r,path:n||this.path(t),body:i,signal:s});return this.fromJSON(a?.response||a)}async _baseMutateBypass(e){let{action:t,body:i,method:r,path:n}=e,s=await iu._baseFetch({method:r,path:n||this.path(t),body:i});return this.fromJSON(s?.response||s)}async _basePost(e={}){if(!e.coalesce)return this._baseMutate({...e,method:"POST"});let t=this.#W(e),i=this.#D??=new Map,r=i.get(t);if(r&&Date.now()<r.expiresAt)return r.promise;let n=new AbortController,s=this._baseMutate({...e,method:"POST",signal:n.signal}).finally(()=>{i.get(t)?.promise===s&&i.delete(t)});return i.set(t,{promise:s,controller:n,expiresAt:Date.now()+3e4}),s}#W(e){let t=Object.entries(e.body??{}).filter(([,e])=>void 0!==e).sort(([e],[t])=>e<t?-1:1);return JSON.stringify([this.id,e.path,e.action,t])}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=iu.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}class ip extends iu{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?tE(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?tE(e.last_used_at):null,this.updatedAt=tE(e.updated_at),this.createdAt=tE(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 i_ extends iu{claimedAt=null;reverification=!1;singleSessionMode=!1;preferredChannels=null;sessionMinter=!1;nativeSettings=null;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){var t;return e&&(this.claimedAt=this.withDefault(e.claimed_at?tE(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.sessionMinter=this.withDefault(e.session_minter,this.sessionMinter),this.nativeSettings=this.withDefault((t=e.native_settings)?{apiEnabled:t.api_enabled,trustedDeviceSignInEnabled:t.trusted_device_sign_in_enabled,trustedDeviceEnrollmentPromptAfterSignInEnabled:t.trusted_device_enrollment_prompt_after_sign_in_enabled,trustedDeviceEnrollmentPromptAfterSignUpEnabled:t.trusted_device_enrollment_prompt_after_sign_up_enabled}:null,this.nativeSettings)),this}__internal_toSnapshot(){var e;return{claimed_at:this.claimedAt?this.claimedAt.getTime():null,id:this.id??"",object:"auth_config",reverification:this.reverification,single_session_mode:this.singleSessionMode,session_minter:this.sessionMinter,native_settings:(e=this.nativeSettings)?{object:"native_settings",api_enabled:e.apiEnabled,trusted_device_sign_in_enabled:e.trustedDeviceSignInEnabled,trusted_device_enrollment_prompt_after_sign_in_enabled:e.trustedDeviceEnrollmentPromptAfterSignInEnabled,trusted_device_enrollment_prompt_after_sign_up_enabled:e.trustedDeviceEnrollmentPromptAfterSignUpEnabled}:null}}}(T=E||(E={}))[T.None=0]="None",T[T.Mutable=1]="Mutable",T[T.Watching=2]="Watching",T[T.RecursedCheck=4]="RecursedCheck",T[T.Recursed=8]="Recursed",T[T.Dirty=16]="Dirty",T[T.Pending=32]="Pending";let im=[],{link:ig,unlink:iy,propagate:iw,checkDirty:ib,endTracking:iv,startTracking:ik,shallowPropagate:iS}=function({update:e,notify:t,unwatched:i}){let r=0;return{link:function(e,t){let i,n=t.depsTail;if(void 0!==n&&n.dep===e)return;if(4&t.flags&&void 0!==(i=void 0!==n?n.nextDep:t.deps)&&i.dep===e){i.version=r,t.depsTail=i;return}let s=e.subsTail;if(void 0!==s&&s.version===r&&s.sub===t)return;let a=t.depsTail=e.subsTail={version:r,dep:e,sub:t,prevDep:n,nextDep:i,prevSub:s,nextSub:void 0};void 0!==i&&(i.prevDep=a),void 0!==n?n.nextDep=a:t.deps=a,void 0!==s?s.nextSub=a:e.subs=a},unlink:n,propagate:function(e){let i,r=e.nextSub;e:for(;;){let n=e.sub,s=n.flags;if(3&s&&(60&s?12&s?4&s?!(48&s)&&function(e,t){let i=t.depsTail;if(void 0!==i){let r=t.deps;do{if(r===e)return!0;if(r===i)break;r=r.nextDep}while(void 0!==r)}return!1}(e,n)?(n.flags=40|s,s&=1):s=0:n.flags=-9&s|32:s=0:n.flags=32|s,2&s&&t(n),1&s)){let t=n.subs;if(void 0!==t){e=t,void 0!==t.nextSub&&(i={value:r,prev:i},r=e.nextSub);continue}}if(void 0!==(e=r)){r=e.nextSub;continue}for(;void 0!==i;)if(e=i.value,i=i.prev,void 0!==e){r=e.nextSub;continue e}break}},checkDirty:function(t,i){let r,n=0;e:for(;;){let a=t.dep,o=a.flags,l=!1;if(16&i.flags)l=!0;else if((17&o)==17){if(e(a)){let e=a.subs;void 0!==e.nextSub&&s(e),l=!0}}else if((33&o)==33){(void 0!==t.nextSub||void 0!==t.prevSub)&&(r={value:t,prev:r}),t=a.deps,i=a,++n;continue}if(!l&&void 0!==t.nextDep){t=t.nextDep;continue}for(;n;){--n;let a=i.subs,o=void 0!==a.nextSub;if(o?(t=r.value,r=r.prev):t=a,l){if(e(i)){o&&s(a),i=t.sub;continue}}else i.flags&=-33;if(i=t.sub,void 0!==t.nextDep){t=t.nextDep;continue e}l=!1}return l}},endTracking:function(e){let t=e.depsTail,i=void 0!==t?t.nextDep:e.deps;for(;void 0!==i;)i=n(i,e);e.flags&=-5},startTracking:function(e){++r,e.depsTail=void 0,e.flags=-57&e.flags|4},shallowPropagate:s};function n(e,t=e.sub){let r=e.dep,s=e.prevDep,a=e.nextDep,o=e.nextSub,l=e.prevSub;return void 0!==a?a.prevDep=s:t.depsTail=s,void 0!==s?s.nextDep=a:t.deps=a,void 0!==o?o.prevSub=l:r.subsTail=l,void 0!==l?l.nextSub=o:void 0===(r.subs=o)&&i(r),a}function s(e){do{let i=e.sub,r=e.nextSub,n=i.flags;(48&n)==32&&(i.flags=16|n,2&n&&t(i)),e=r}while(void 0!==e)}}({update:e=>"getter"in e?iE(e):ix(e,e.value),notify:function e(t){let i=t.flags;if(!(64&i)){t.flags=64|i;let r=t.subs;void 0!==r?e(r.sub):im[iU++]=t}},unwatched(e){if("getter"in e){let t=e.deps;if(void 0!==t){e.flags=17;do t=iy(t,e);while(void 0!==t)}}else"previousValue"in e||iF.call(e)}}),iI=0,iC=0,iU=0;function iA(e){let t=r;return r=e,t}function iP(e){return iz.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function iT(e){return iM.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function iO(e){let t={fn:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==r?ig(t,r):void 0!==n&&ig(t,n);let i=iA(t);try{t.fn()}finally{iA(i)}return iF.bind(t)}function iE(e){let t=iA(e);ik(e);try{let t=e.value;return t!==(e.value=e.getter(t))}finally{iA(t),iv(e)}}function ix(e,t){return e.flags=1,e.previousValue!==(e.previousValue=t)}function iR(){for(;iC<iU;){let e=im[iC];im[iC++]=void 0,function e(t,i){if(16&i||32&i&&ib(t.deps,t)){let e=iA(t);ik(t);try{t.fn()}finally{iA(e),iv(t)}return}32&i&&(t.flags=-33&i);let r=t.deps;for(;void 0!==r;){let t=r.dep,i=t.flags;64&i&&e(t,t.flags=-65&i),r=r.nextDep}}(e,e.flags&=-65)}iC=0,iU=0}function iM(){let e=this.flags;if(16&e||32&e&&ib(this.deps,this)){if(iE(this)){let e=this.subs;void 0!==e&&iS(e)}}else 32&e&&(this.flags=-33&e);return void 0!==r?ig(this,r):void 0!==n&&ig(this,n),this.value}function iz(...e){if(e.length){let t=e[0];if(this.value!==(this.value=t)){this.flags=17;let e=this.subs;void 0!==e&&(iw(e),iI||iR())}}else{let e=this.value;if(16&this.flags&&ix(this,e)){let e=this.subs;void 0!==e&&iS(e)}return void 0!==r&&ig(this,r),e}}function iF(){let e=this.deps;for(;void 0!==e;)e=iy(e,this);let t=this.subs;void 0!==t&&iy(t),this.flags=0}function iN(e){let{pageSize:t,initialPage:i,...r}=e||{},n=t??10;return new URLSearchParams({...Object.entries(r).reduce((e,[t,i])=>(void 0!==i&&(e[t]=i),e),{}),limit:n+"",offset:((i??1)-1)*n+""})}class iD{static #L="/billing";static path(e,t){let{orgId:i}=t||{},r=i?`/organizations/${i}`:"/me";return`${r}${iD.#L}${e}`}getPlans=async e=>{let{for:t,orgId:i,minSeats:r,...n}=e||{},s={...n,payer_type:"organization"===t?"org":"user",org_id:i,min_seats:r};return await iu._fetch({path:`${iD.#L}/plans`,method:"GET",search:iN(s)}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new re(e))}})};getPlan=async e=>new re(await iu._fetch({path:`${iD.#L}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await iu._fetch({path:iD.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new rr(e?.response));getStatements=async e=>{let{orgId:t,...i}=e;return await iu._fetch({path:iD.path("/statements",{orgId:t}),method:"GET",search:iN(i)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new rt(e))}})};getStatement=async e=>new rt((await iu._fetch({path:iD.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:t,...i}=e;return await iu._fetch({path:iD.path("/payment_attempts",{orgId:t}),method:"GET",search:iN(i)}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new i2(e))}})};getPaymentAttempt=async e=>new i2(await iu._fetch({path:iD.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:t,...i}=e;return new iZ((await iu._fetch({path:iD.path("/checkouts",{orgId:t}),method:"POST",body:i}))?.response)};updateCheckout=async e=>{let{id:t,orgId:i,...r}=e;return new iZ((await iu._fetch({path:iD.path(`/checkouts/${t}`,{orgId:i}),method:"PATCH",body:r}))?.response)};getCreditBalance=async e=>await iu._fetch({path:iD.path("/credits",{orgId:e.orgId}),method:"GET"}).then(e=>new i1(e?.response));getCreditHistory=async e=>await iu._fetch({path:iD.path("/credits/history",{orgId:e.orgId}),method:"GET"}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new i3(e))}})}let iW=iP({resource:null}),iL=iP({error:null}),i$=iP({status:"idle"}),ij=iT(()=>{let e=iW().resource,t=iL().error,i=i$().status;return{errors:iX(t,{identifier:null,password:null,code:null}),fetchStatus:i,signIn:e?e.__internal_future:null}}),iB=iP({resource:null}),iJ=iP({error:null}),iK=iP({status:"idle"}),iV=iT(()=>{let e=iB().resource,t=iJ().error,i=iK().status;return{errors:iX(t,{firstName:null,lastName:null,emailAddress:null,phoneNumber:null,password:null,username:null,code:null,captcha:null,legalAccepted:null}),fetchStatus:i,signUp:e?e.__internal_future:null}}),iq=iP({resource:null}),iH=iP({error:null}),iG=iP({status:"idle"}),iQ=iT(()=>{let e=iq().resource,t=iH().error,i=iG().status;return{errors:iX(t,{emailAddress:null}),fetchStatus:i,waitlist:e}});function iX(e,t){let i={fields:{...t},raw:null,global:null};if(!e)return i;if(!$(e))return i.raw=[e],i.global=[Y(e)],i;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(i.raw?i.raw.push(e):i.raw=[e],r(e)){let t=eh(e.meta.paramName);t in i.fields&&(i.fields[t]=e)}}):(i.raw=[e],i.global=[Y(e)]),i}class iY extends iu{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=tE(e.created_at)),e.updated_at&&(this.updatedAt=tE(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 iZ extends iu{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 i9(e.payment_method):void 0,this.plan=new re(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=tL(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change,e.free_trial_ends_at&&(this.freeTrialEndsAt=tE(e.free_trial_ends_at)),this.payer=new iY(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>tA(()=>this._basePatch({path:iD.path(`/checkouts/${this.id}/confirm`,{orgId:this.payer.organizationId}),body:e}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,t){if(!$(e)||t>=4)return!1;let i=e?.status,r=409===i&&e.errors?.[0]?.code==="checkout_already_in_progress";return i>=500||r}})}class i0{resource=new iZ(null);config;signals;pendingOperations=new Map;constructor(e,t){this.config=t,this.signals=e,this.signals.resourceSignal({resource:this})}get status(){return this.resource.status??"needs_initialization"}get externalClientSecret(){return this.resource.externalClientSecret}get externalGatewayId(){return this.resource.externalGatewayId}get plan(){return this.resource.plan}get planPeriod(){return this.resource.planPeriod}get totals(){return this.resource.totals}get isImmediatePlanChange(){return this.resource.isImmediatePlanChange}get freeTrialEndsAt(){return this.resource.freeTrialEndsAt}get payer(){return this.resource.payer}get paymentMethod(){return this.resource.paymentMethod??null}get planPeriodStart(){return this.resource.planPeriodStart}get needsPaymentMethod(){return this.resource.needsPaymentMethod}async start(){return this.runAsyncCheckoutTask("start",async()=>{let e=await iZ.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new iZ(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 update(e){if(!this.resource.id)throw Error("Clerk: `start()` must be called before `update()`");return this.runAsyncCheckoutTask("update",async()=>{this.resource=await iZ.clerk.billing?.updateCheckout({id:this.resource.id,orgId:this.resource.payer.organizationId||void 0,...e})},void 0,!1)}async finalize(e){let{navigate:t}=e||{};return this.runAsyncCheckoutTask("finalize",async()=>{if("completed"!==this.resource.status)throw Error("Clerk: `confirm()` must be called before `finalize()`");await iZ.clerk.setActive({session:iZ.clerk.session?.id,navigate:t})})}runAsyncCheckoutTask(e,t,i,r=!0){var n,s,a;return void 0===iZ.clerk.user?(console.warn("Clerk: Checkout operations cannot be performed during transitive state"),{error:null}):(n=this,s=this.signals,a=this.pendingOperations,async(e,t,i,r=!0)=>{if(a.get(e))return a.get(e);let o=(async()=>{++iI,s.errorSignal({error:null}),s.fetchSignal({status:"fetching"}),i?.(),--iI||iR(),++iI;try{return await t(),s.resourceSignal({resource:n}),{error:null}}catch(e){return r&&s.errorSignal({error:e}),{error:e}}finally{a.delete(e),s.fetchSignal({status:"idle"}),--iI||iR()}})();return a.set(e,o),o})(e,t,i,r)}}class i1{balance;constructor(e){this.balance=e.balance?tx(e.balance):null}}class i3 extends iu{id;amount;sourceType;sourceId;createdAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.amount=tx(e.amount),this.sourceType=e.source_type,this.sourceId=e.source_id,this.createdAt=tE(e.created_at)),this}}class i2 extends iu{id;amount;failedAt=null;paidAt=null;updatedAt;paymentMethod=null;subscriptionItem;chargeType;status;totals=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){let t;return e?(this.id=e.id,this.amount=tx(e.amount),this.paidAt=e.paid_at?tE(e.paid_at):null,this.failedAt=e.failed_at?tE(e.failed_at):null,this.updatedAt=tE(e.updated_at),this.paymentMethod=e.payment_method?new i9(e.payment_method):null,this.subscriptionItem=new rn(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status,this.totals=e.totals?{subtotal:tx((t=e.totals).subtotal),grandTotal:tx(t.grand_total),taxTotal:tx(t.tax_total),baseFee:t.base_fee?tx(t.base_fee):null,perUnitTotals:t.per_unit_totals?tM(t.per_unit_totals):void 0,discounts:t.discounts?tN(t.discounts):null}:null,this):this}}let i4="/payment_methods",i5=async e=>{let{orgId:t,...i}=e;return new i7((await iu._fetch({path:iD.path(`${i4}/initialize`,{orgId:t}),method:"POST",body:i}))?.response)},i6=async e=>{let{orgId:t,...i}=e;return new i9((await iu._fetch({path:iD.path(i4,{orgId:t}),method:"POST",body:i}))?.response)},i8=async e=>{let{orgId:t,...i}=e??{};return await iu._fetch({path:iD.path(i4,{orgId:t}),method:"GET",search:iN(i)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new i9(e))}})};class i9 extends iu{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:tE(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:tE(e.updated_at)),this}async remove(e){let{orgId:t}=e??{};return new rN((await iu._fetch({path:iD.path(`/payment_methods/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:t}=e??{};return await iu._fetch({path:iD.path("/payers/default_payment_method",{orgId:t}),method:"PUT",body:{payment_method_id:this.id}}),null}}class i7 extends iu{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 re extends iu{id;name;fee=null;annualFee=null;annualMonthlyFee=null;description=null;isDefault;isRecurring;hasBaseFee;forPayerType;publiclyVisible;slug;avatarUrl=null;features;unitPrices;availablePrices;freeTrialDays;freeTrialEnabled;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.fee=e.fee?tx(e.fee):null,this.annualFee=e.annual_fee?tx(e.annual_fee):null,this.annualMonthlyFee=e.annual_monthly_fee?tx(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 nl(e)),this.unitPrices=e.unit_prices?.map(tz),this.availablePrices=e.available_prices?.map(e=>({id:e.id,fee:e.fee?tx(e.fee):null,annualMonthlyFee:e.annual_monthly_fee?tx(e.annual_monthly_fee):null,isDefault:e.is_default,unitPrices:e.unit_prices?.map(tz)}))),this}}class rt extends iu{id;status;timestamp;totals;groups;constructor(e){super(),this.fromJSON(e)}fromJSON(e){var t;let i;return e?(this.id=e.id,this.status=e.status,this.timestamp=tE(e.timestamp),this.totals=(i={grandTotal:tx((t=e.totals).grand_total),subtotal:tx(t.subtotal),taxTotal:tx(t.tax_total)},"base_fee"in t&&t.base_fee&&(i.baseFee=tx(t.base_fee)),"past_due"in t&&(i.pastDue=t.past_due?tx(t.past_due):null),"credit"in t&&(i.credit=t.credit?tx(t.credit):null),"per_unit_totals"in t&&(i.perUnitTotals=t.per_unit_totals?tM(t.per_unit_totals):void 0),"credits"in t&&(i.credits=t.credits?tF(t.credits):null),"total_due_now"in t&&(i.totalDueNow=tx(t.total_due_now)),"total_due_after_free_trial"in t&&(i.totalDueAfterFreeTrial=t.total_due_after_free_trial?tx(t.total_due_after_free_trial):null),"discounts"in t&&(i.discounts=t.discounts?tN(t.discounts):null),"total_due_per_period"in t&&t.total_due_per_period&&(i.totalDuePerPeriod=tx(t.total_due_per_period)),"totals_due_per_period"in t&&t.totals_due_per_period&&(i.totalsDuePerPeriod=tW(t.totals_due_per_period)),i),this.groups=e.groups.map(e=>new ri(e)),this):this}}class ri{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=tE(e.timestamp),this.items=e.items.map(e=>new i2(e))),this}}class rr extends iu{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=tE(e.created_at),this.updatedAt=e.updated_at?tE(e.updated_at):null,this.activeAt=tE(e.active_at),this.pastDueAt=e.past_due_at?tE(e.past_due_at):null,this.nextPayment=void 0===e.next_payment?void 0:null===e.next_payment?null:t$(e.next_payment),this.subscriptionItems=(e.subscription_items||[]).map(e=>new rn(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1),this):this}}class rn extends iu{id;plan;planPeriod;priceId;status;createdAt;periodStart;periodEnd;canceledAt;pastDueAt;amount;credit;seats;credits;appliedDiscount;nextPayment;isFreeTrial;constructor(e){super(),this.fromJSON(e)}fromJSON(e){let t;return e?(this.id=e.id,this.plan=new re(e.plan),this.planPeriod=e.plan_period,this.priceId=e.price_id,this.status=e.status,this.createdAt=tE(e.created_at),this.pastDueAt=e.past_due_at?tE(e.past_due_at):null,this.periodStart=tE(e.period_start),this.periodEnd=e.period_end?tE(e.period_end):null,this.canceledAt=e.canceled_at?tE(e.canceled_at):null,this.amount=e.amount?tx(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:tx(e.credit.amount)}:void 0,this.seats=e.seats?{quantity:e.seats.quantity,...e.seats.tiers?{tiers:e.seats.tiers.map(tR)}:{}}:void 0,this.credits=e.credits?tF(e.credits):void 0,this.appliedDiscount=e.applied_discount?{id:(t=e.applied_discount).id,subscriptionItemId:t.subscription_item_id,discountId:t.discount_id,name:t.name,source:t.source,promoCode:t.promo_code,effect:t.effect,percentOff:t.percent_off,amountOff:t.amount_off?tx(t.amount_off):void 0,amount:t.amount?tx(t.amount):void 0,cyclesRemaining:t.cycles_remaining,cyclesApplied:t.cycles_applied,status:t.status,redeemedAt:tE(t.redeemed_at),redeemedBy:t.redeemed_by}:void 0,this.nextPayment=void 0===e.next_payment?void 0:null===e.next_payment?null:t$(e.next_payment),this.isFreeTrial=this.withDefault(e.is_free_trial,!1),this):this}async cancel(e){let{orgId:t}=e;return new rN((await iu._fetch({path:iD.path(`/subscription_items/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}}function rs(e){return e?{challenge:e.challenge,challengeId:e.challenge_id,trustedDeviceId:e.trusted_device_id??null,clientData:e.client_data,expiresAt:e.expires_at?new Date(1e3*e.expires_at):null,algorithm:e.algorithm}:null}let ra="/me/biometric_credentials";function ro(e){let{publicKeyJwk:t,...i}=e;return{...i,publicKeyJwk:"string"==typeof t?t:JSON.stringify(t)}}class rl extends iu{id;pathRoot=ra;platform;appIdentifier;name=null;algorithm;status;lastUsedAt=null;revokedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async list(){return((await iu._fetch({path:ra,method:"GET"}))?.response||[]).map(e=>new rl(e))}static async prepare(e){return rs((await iu._fetch({path:`${ra}/prepare`,method:"POST",body:ro(e)}))?.response)}static async attempt(e){return new rl((await iu._fetch({path:`${ra}/attempt`,method:"POST",body:ro(e)}))?.response)}static async revoke(e){return new rl((await iu._fetch({path:`${ra}/${e}`,method:"DELETE"}))?.response)}fromJSON(e){return e&&(this.id=e.id,this.platform=e.platform,this.appIdentifier=e.app_identifier,this.name=e.name??null,this.algorithm=e.algorithm,this.status=e.status,this.lastUsedAt=e.last_used_at?tE(e.last_used_at):null,this.revokedAt=e.revoked_at?tE(e.revoked_at):null,this.createdAt=tE(e.created_at),this.updatedAt=tE(e.updated_at)),this}__internal_toSnapshot(){return{object:"trusted_device",id:this.id,platform:this.platform,app_identifier:this.appIdentifier,name:this.name,algorithm:this.algorithm,status:this.status,last_used_at:this.lastUsedAt?.getTime()??null,revoked_at:this.revokedAt?.getTime()??null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}let rc="token:update",rd="user:signOut",rh="environment:update",ru="session:tokenResolved",rp=U(),r_={build:(e,t,i)=>[e,t,i].filter(Boolean).join("-"),parse:(e,t,i)=>{let r=r_.extractTemplate(e,t,i);return{organizationId:i,sessionId:t,template:r}},extractTemplate:(e,t,i)=>{if(e===t||i&&e===`${t}-${i}`)return;let r=e.slice(t.length+1);return i&&r.endsWith(`-${i}`)&&(r=r.slice(0,-(i.length+1))),r||void 0}};var rf=i(8591),rm='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 rg=(e,t={})=>{if("u"<typeof Worker)return null;try{let i=new Blob([e],{type:"application/javascript; charset=utf-8"}),r=globalThis.URL.createObjectURL(i);return new Worker(r,t)}catch{return console.warn("Clerk: Cannot create worker from blob. Consider adding worker-src blob:; to your CSP"),null}},ry=()=>{let e=0,t=()=>e++,i=new Map,r=(e,t)=>e?.postMessage(t),n=e=>{i.get(e.data.id)?.()},s=rg(rm,{name:"clerk-timers"});if(s?.addEventListener("message",n),!s)return{setTimeout:globalThis.setTimeout.bind(globalThis),setInterval:globalThis.setInterval.bind(globalThis),clearTimeout:globalThis.clearTimeout.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis),cleanup:rf.t};let a=()=>{s||(s=rg(rm,{name:"clerk-timers"}),s?.addEventListener("message",n))};return{setTimeout:(e,n)=>{a();let o=t();return i.set(o,()=>{e(),i.delete(o)}),r(s,{type:"setTimeout",id:o,ms:n}),o},setInterval:(e,n)=>{a();let o=t();return i.set(o,e),r(s,{type:"setInterval",id:o,ms:n}),o},clearTimeout:e=>{a(),i.delete(e),r(s,{type:"clearTimeout",id:e})},clearInterval:e=>{a(),i.delete(e),r(s,{type:"clearInterval",id:e})},cleanup:()=>{s&&(s.terminate(),s=null,i.clear())}}};function rw(){if("u">typeof document)try{if("function"!=typeof document.hasFocus)return;return document.hasFocus()}catch{return}}var rb=i(8388),rv=i.n(rb);function rk(e){let t=new(rv());return{acquireLockAndRun:async i=>{if("locks"in navigator&&isSecureContext){let t=new AbortController,r=setTimeout(()=>t.abort(),4999);return await navigator.locks.request(e,{signal:t.signal},async()=>(clearTimeout(r),await i())).catch(()=>!1)}if(await t.acquireLock(e,5e3))try{return await i()}finally{await t.releaseLock(e)}}}}class rS{lock=rk("clerk.lock.refreshSessionToken");workerTimers=ry();timerId=null;initiated=!1;startPollingForSessionToken(e){if(this.timerId||this.initiated)return;let t=async()=>{this.initiated=!0,await this.lock.acquireLockAndRun(e);let i=!0===rw()?1500:5e3;this.timerId=this.workerTimers.setTimeout(t,i)};t()}stopPollingForSessionToken(){null!=this.timerId&&(this.workerTimers.clearTimeout(this.timerId),this.timerId=null),this.initiated=!1}}let rI="clerk";function rC(e){return"getRawString"in e?e.jwt:e}function rU(e,t){if(null==e)return t;let i=rC(e)?.header?.oiat,r=rC(t)?.header?.oiat;return null==i&&null==r?t:null==r?e:null==i?t:i>r?e:i<r?t:(rC(e)?.claims?.iat??0)>(rC(t)?.claims?.iat??0)?e:t}function rA(e){return rC(e)?.header?.oiat}function rP(e){return rC(e)?.claims?.sid}function rT(e){let t=rC(e)?.claims;return t?.org_id||(t?.o?.id??"")}function rO(e,t){return!!e?.jwt&&rP(e)===rP(t)&&rT(e)===rT(t)&&rU(e,t)!==t}let rE={broadcast:!0},rx={broadcast:!1},rR=(o=new Map,l={get:e=>o.get(e),set:(e,t)=>{o.set(e,t)},delete:e=>{o.delete(e)},clear:()=>{o.clear()},forEach:e=>{o.forEach((t,i)=>e(t,i))},size:()=>o.size},c=((e=rI)=>({toKey:({tokenId:t,audience:i})=>[e,t,i||""].join("::")}))(O),d=Math.random().toString(36).slice(2),h=null,(u=()=>h||("u"<typeof BroadcastChannel?null:((h=new BroadcastChannel("clerk:session_token")).addEventListener("message",e=>{_(e)}),h)))(),p=e=>{u();let t=c.toKey(e),i=l.get(t);if(i){if((i.expiresAt??1/0)-Math.floor(Date.now()/1e3)<=5){void 0!==i.timeoutId&&clearTimeout(i.timeoutId),void 0!==i.refreshTimeoutId&&clearTimeout(i.refreshTimeoutId),l.delete(t);return}return{entry:i.entry}}},_=async({data:e})=>{let t,i=r_.build(e.sessionId,e.template,e.organizationId);if(e.tokenId!==i)return void tS.warn("Ignoring token broadcast with mismatched tokenId",{expectedTokenId:i,organizationId:e.organizationId,receivedTokenId:e.tokenId,tabId:d,template:e.template,traceId:e.traceId},"tokenCache");try{t=new n8({id:e.tokenId,jwt:e.tokenRaw,object:"token"})}catch(t){tS.warn("Failed to parse token from broadcast, skipping cache update",{error:t,tabId:d,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");return}let r=t.jwt?.claims?.iat,n=t.jwt?.claims?.exp;if(!r||!n)return void tS.warn("Token missing iat/exp claim, skipping cache update",{tabId:d,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");try{let i=p({tokenId:e.tokenId});if(i){let r=i.entry.resolvedToken??await i.entry.tokenResolver;if(rU(r,t)===r)return void tS.debug("Ignoring staler token broadcast",{tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}}catch(t){tS.warn("Existing entry compare failed; proceeding with broadcast update",{error:t,tabId:d,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}tS.info("Updating token cache from broadcast",{iat:r,organizationId:e.organizationId,tabId:d,template:e.template,tokenId:e.tokenId,traceId:e.traceId},"tokenCache"),f({tokenId:e.tokenId,tokenResolver:Promise.resolve(t)},rx)},f=(e,t=rE)=>{let i=c.toKey({audience:e.audience,tokenId:e.tokenId}),r=l.get(i);clearTimeout(r?.timeoutId),clearTimeout(r?.refreshTimeoutId);let n={cachedAt:Math.floor(Date.now()/1e3),entry:e},s=r?.entry.resolvedToken;n.baseline=s?rU(r?.baseline,s):r?.baseline;let a=e=>{l.get(i)===e&&(clearTimeout(e.timeoutId),clearTimeout(e.refreshTimeoutId),l.delete(i))};l.set(i,n),e.tokenResolver.then(r=>{let s=l.get(i);if(!s)return;let o=r.jwt?.claims,c=!!o&&"number"==typeof o.exp&&"number"==typeof o.iat,u=s===n;if(u&&!c)return void a(s);if(!c)return;let p=rU(s.baseline,r);if(s.baseline=p,!u&&void 0===s.entry.resolvedToken)return;let _=rU(s.entry.resolvedToken,p);if(_===s.entry.resolvedToken)return;s.entry.resolvedToken=_;let f=_.jwt?.claims;if(!f||"number"!=typeof f.exp||"number"!=typeof f.iat)return void a(s);clearTimeout(s.timeoutId),clearTimeout(s.refreshTimeoutId);let m=Math.min(f.exp,s.cachedAt+f.exp-f.iat),g=m-Math.floor(Date.now()/1e3);if(s.expiresAt=m,g<=0)return void a(s);let y=setTimeout(()=>a(s),1e3*g);s.timeoutId=y,"function"==typeof y.unref&&y.unref();let w=g-15-2;if(w>0&&s.entry.onRefresh){let e=setTimeout(()=>{s.entry.onRefresh?.()},1e3*w);s.refreshTimeoutId=e,"function"==typeof e.unref&&e.unref()}let b=h;if(b&&t.broadcast)try{let t=_.getRawString();if(t&&f.sid){let i=f.sid,r=f.org_id||f.o?.id,n=r_.extractTemplate(e.tokenId,i,r),s=r_.build(i,n,r);if(e.tokenId===s){let s=`bc_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;tS.info("Broadcasting token update to other tabs",{organizationId:r,sessionId:i,tabId:d,template:n,tokenId:e.tokenId,traceId:s},"tokenCache");let a={organizationId:r,sessionId:i,template:n,tokenId:e.tokenId,tokenRaw:t,traceId:s};b.postMessage(a)}}}catch(t){tS.warn("Failed to broadcast token update to other tabs",{error:t,tabId:d,tokenId:e.tokenId},"tokenCache")}}).catch(()=>{a(n)})},{clear:()=>{l.forEach(e=>{void 0!==e.timeoutId&&clearTimeout(e.timeoutId),void 0!==e.refreshTimeoutId&&clearTimeout(e.refreshTimeoutId)}),l.clear()},close:()=>{h&&(h.close(),h=null)},get:p,set:e=>{u(),f(e,rE)},size:()=>l.size()});function rM(e){if(!e)return;let t=e.client||e.meta?.client;return t?rz.getOrCreateInstance().fromJSON(t):void 0}class rz extends iu{static instance;pathRoot="/client";sessions=[];signUp=new n1;signIn=new nY;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return rz.instance||(rz.instance=new rz(e)),rz.instance}static clearInstance(){rz.instance=null}static isClientResource(e){return!!e&&e instanceof rz}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,abortSignal:t}={}){return this._baseGet({fetchMaxTries:e,abortSignal:t})}async destroy(){return this._baseDelete({path:"/client"}).then(()=>{rR.clear(),this.id="",this.sessions=[],this.signUp=new n1(null),this.signIn=new nY(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=>(rR.clear(),e))}resetSignIn(){this.signIn=new nY(null),rp.emit("resource:error",{resource:this.signIn,error:null})}resetSignUp(){this.signUp=new n1(null),rp.emit("resource:error",{resource:this.signUp,error:null})}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return iu.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){if(e){this.id=e.id;let t=new Map(this.sessions.map(e=>[e.id,e.lastActiveToken]));this.sessions=(e.sessions||[]).map(e=>{let i=new nz(e),r=t.get(i.id);return r&&i.lastActiveToken&&rO(r,i.lastActiveToken)&&(i.lastActiveToken=r),i}),e.sign_up&&this.signUp instanceof n1&&this.signUp.id===e.sign_up.id?this.signUp.__internal_updateFromJSON(e.sign_up):this.signUp=new n1(e.sign_up),e.sign_in&&this.signIn instanceof nY&&this.signIn.id===e.sign_in.id?this.signIn.__internal_updateFromJSON(e.sign_in):this.signIn=new nY(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?tE(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=tE(e.created_at||void 0),this.updatedAt=tE(e.updated_at||void 0)}return 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 rF extends iu{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 rN{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 rD extends iu{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}}}function rW({delayInMs:e}={delayInMs:1e3}){let t,i=ry(),r=!1,n=()=>{t&&(i.clearTimeout(t),i.cleanup()),r=!0},s=async a=>{r=!1,await a(n),r||(t=i.setTimeout(()=>{s(a)},e))};return{run:s,stop:n}}class rL extends iu{id;emailAddress="";matchesSsoConnection=!1;linkedTo=[];verification;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}create(){return this._basePost({body:{email_address:this.emailAddress}})}prepareVerification=e=>this._basePost({action:"prepare_verification",coalesce:!0,body:{...e}});attemptVerification=e=>{let{code:t}=e||{};return this._basePost({action:"attempt_verification",body:{code:t}})};createEmailLinkFlow=()=>{let{run:e,stop:t}=rW();return{startEmailLinkFlow:async({redirectUrl:i})=>(await this.prepareVerification({strategy:"email_link",redirectUrl:i}),new Promise((i,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),i(e))}).catch(e=>{t(),r(e)}))})),cancelEmailLinkFlow:t}};createEnterpriseSSOLinkFlow=()=>{let{run:e,stop:t}=rW();return{startEnterpriseSSOLinkFlow:async({redirectUrl:i})=>{if(!(await this.prepareVerification({strategy:"enterprise_sso",redirectUrl:i})).verification.externalVerificationRedirectURL)throw Error("Unexpected: External verification redirect URL is missing");return new Promise((i,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),i(e))}).catch(e=>{t(),r(e)}))})},cancelEnterpriseSSOLinkFlow:t}};destroy=()=>this._baseDelete();toString=()=>this.emailAddress;fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.verification=new rX(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new nc(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 r$=class{static encode(e){return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}static decode(e){let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),i=t.length,r=new Uint8Array(i);for(let e=0;e<i;e++)r[e]=t.charCodeAt(e);return r.buffer}};async function rj(e){try{let t=await navigator.credentials.create({publicKey:e});if(!t)return{error:new q("Browser failed to create credential",{code:"passkey_registration_failed"}),publicKeyCredential:null};return{publicKeyCredential:t,error:null}}catch(e){var t;return{error:"InvalidStateError"===(t=e).name?new q(t.message,{code:"passkey_already_exists"}):"NotAllowedError"===t.name?new q(t.message,{code:"passkey_registration_cancelled"}):rK(t),publicKeyCredential:null}}}let rB=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 rJ({publicKeyOptions:e,conditionalUI:t}){try{let i=await navigator.credentials.get({publicKey:e,mediation:t?"conditional":"optional",signal:rB.createAbortSignal()});if(!i)return{error:new q("Browser failed to get credential",{code:"passkey_retrieval_failed"}),publicKeyCredential:null};return{publicKeyCredential:i,error:null}}catch(e){var i;return{error:"NotAllowedError"===(i=e).name?new q(i.message,{code:"passkey_retrieval_cancelled"}):rK(i),publicKeyCredential:null}}}function rK(e){return"AbortError"===e.name?new q(e.message,{code:"passkey_operation_aborted"}):"SecurityError"===e.name?new q(e.message,{code:"passkey_invalid_rpID_or_domain",docsUrl:"https://clerk.com/docs/deployments/overview#authentication-across-subdomains"}):e}function rV(e){let t=rQ(e.challenge),i=(e.allowCredentials||[]).map(e=>({...e,id:rQ(e.id)}));return{...e,allowCredentials:i,challenge:t}}function rq(e){return{type:e.type,id:e.id,rawId:rG(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function rH(e){let t=e.response;return{...rq(e),response:{clientDataJSON:rG(t.clientDataJSON),authenticatorData:rG(t.authenticatorData),signature:rG(t.signature),userHandle:t.userHandle?rG(t.userHandle):null}}}let rG=r$.encode.bind(r$),rQ=r$.decode.bind(r$);class rX extends iu{pathRoot="";status=null;strategy=null;nonce=null;message=null;externalVerificationRedirectURL=null;attempts=null;expireAt=null;error=null;verifiedAtClient=null;channel;trustedDeviceChallenge=null;constructor(e){super(),this.fromJSON(e)}verifiedFromTheSameClient=()=>this.verifiedAtClient===iu.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=tE(e.expire_at||void 0),this.error=e.error?new W(e.error):null,this.channel=e.channel||void 0,this.trustedDeviceChallenge=rs(e.trusted_device_challenge)),this}__internal_toSnapshot(){var e,t;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,seats_quantity_to_add:e?.meta?.seatsQuantityToAdd,seats_quantity:e?.meta?.seatsQuantity,trace_id:e?.meta?.traceId,kind:e?.meta?.kind,title:e?.meta?.title,description:e?.meta?.description,link_url:e?.meta?.linkUrl,link_text:e?.meta?.linkText,data:e?.meta?.data}}),verified_at_client:this.verifiedAtClient,...this.trustedDeviceChallenge&&{trusted_device_challenge:(t=this.trustedDeviceChallenge)?{object:"trusted_device_challenge",challenge:t.challenge,challenge_id:t.challengeId,...t.trustedDeviceId?{trusted_device_id:t.trustedDeviceId}:{},client_data:t.clientData,expires_at:t.expiresAt?Math.floor(t.expiresAt.getTime()/1e3):0,algorithm:t.algorithm}:null}}}}class rY extends rX{publicKey=null;constructor(e){super(e),this.fromJSON(e)}fromJSON(e){var t;let i,r,n;return super.fromJSON(e),e?.nonce&&(this.publicKey=(i=rQ((t=JSON.parse(e.nonce)).user.id),r=rQ(t.challenge),n=(t.excludeCredentials||[]).map(e=>({...e,id:rQ(e.id)})),{...t,excludeCredentials:n,challenge:r,user:{...t.user,id:i}})),this}}class rZ{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new r0(e.email_address),this.phoneNumber=new r0(e.phone_number),this.web3Wallet=new r0(e.web3_wallet),this.externalAccount=new rX(e.external_account)):(this.emailAddress=new r0(null),this.phoneNumber=new r0(null),this.web3Wallet=new r0(null),this.externalAccount=new rX(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 r0 extends rX{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 r1 extends iu{id;protocol;provider;providerUserId=null;active;emailAddress="";firstName="";lastName="";publicMetadata={};verification=null;enterpriseConnection=null;lastAuthenticatedAt=null;enterpriseConnectionId=null;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.provider=e.provider,this.protocol=e.protocol,this.providerUserId=e.provider_user_id,this.active=e.active,this.emailAddress=e.email_address,this.firstName=e.first_name,this.lastName=e.last_name,this.publicMetadata=e.public_metadata,this.lastAuthenticatedAt=e.last_authenticated_at?tE(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new rX(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new r3(e.enterprise_connection))),this}destroy=()=>this._baseDelete();__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 r3 extends iu{id;active;allowIdpInitiated;allowSubdomains;disableAdditionalIdentifications;domain;logoPublicUrl="";name;protocol;provider;syncUserAttributes;allowOrganizationAccountLinking;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.allowOrganizationAccountLinking=e.allow_organization_account_linking,this.createdAt=tE(e.created_at),this.updatedAt=tE(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,allow_organization_account_linking:this.allowOrganizationAccountLinking,enterprise_connection_id:this.enterpriseConnectionId,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}class r2 extends iu{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=tE(e.created_at),this.updatedAt=tE(e.updated_at)),this}}class r4 extends iu{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 r2(e)),this.createdAt=tE(e.created_at),this.updatedAt=tE(e.updated_at)),this}}class r5 extends iu{id;name;organizationId;enterpriseConnectionId;endpointUrl;provider;enabled;groupRoleMappingEnabled;attributeMapping={};credentialsConfigured=null;apiKey=null;createdAt=null;updatedAt=null;constructor(e,t){super(),this.organizationId=t,this.fromJSON(e)}get directoryPath(){return`/organizations/${this.organizationId}/enterprise_connections/${this.enterpriseConnectionId}/directory`}update=async e=>{let t={};return void 0!==e.enabled&&(t.enabled=e.enabled),void 0!==e.groupRoleMappingEnabled&&(t.group_role_mapping_enabled=e.groupRoleMappingEnabled),void 0!==e.attributeMapping&&(t.attribute_mapping=JSON.stringify(e.attributeMapping)),new r5((await iu._fetch({path:this.directoryPath,method:"PATCH",body:t}))?.response,this.organizationId)};rotateToken=async()=>new r5((await iu._fetch({path:`${this.directoryPath}/rotate_api_key`,method:"POST"}))?.response,this.organizationId);delete=async()=>new rN((await iu._fetch({path:this.directoryPath,method:"DELETE"}))?.response);setCredentials=async e=>new r5((await iu._fetch({path:`${this.directoryPath}/credentials`,method:"POST",body:{service_account_json:e.serviceAccountJson,subject_email:e.subjectEmail}}))?.response,this.organizationId);sync=async()=>{await iu._fetch({path:`${this.directoryPath}/sync`,method:"POST"})};getSyncStatus=async()=>{let e=await iu._fetch({path:`${this.directoryPath}/sync_status`,method:"GET"}),t=e?.response;return{lastSyncedAt:t?.last_synced_at?tE(t.last_synced_at):null,lastSyncStatus:t?.last_sync_status??null,lastSyncError:t?.last_sync_error??null,lastSyncChangedUserCount:t?.last_sync_changed_user_count??null}};getGroups=async e=>{let t={};e?.limit!==void 0&&(t.limit=String(e.limit)),e?.startingAfter&&(t.starting_after=e.startingAfter);let i=await iu._fetch({path:`${this.directoryPath}/groups`,method:"GET",search:t}),r=i?.response;return{data:(r?.data??[]).map(e=>({id:e.id,displayName:e.display_name,updatedAt:e.updated_at?tE(e.updated_at):null})),startingAfter:r?.cursor?.starting_after??null,hasNextPage:r?.cursor?.has_next_page??!1}};getGroupRoleMappings=async()=>{let e=await iu._fetch({path:`${this.directoryPath}/group_role_mappings`,method:"GET"});return r8(e?.response)};replaceGroupRoleMappings=async e=>{let t=await iu._fetch({path:`${this.directoryPath}/group_role_mappings`,method:"PUT",body:{mappings:JSON.stringify(e.mappings.map(e=>({directory_group_id:e.directoryGroupId,role:e.role})))}});return r8(t?.response)};getUsers=async e=>{let t=await iu._fetch({path:`${this.directoryPath}/users`,method:"GET",search:iN(e)}),i=t?.response;return{total_count:i?.total_count??0,data:(i?.data??[]).map(e=>new r9(e))}};fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.enterpriseConnectionId=e.enterprise_connection_id,this.endpointUrl=e.endpoint_url,this.provider=e.provider,this.enabled=e.enabled,this.groupRoleMappingEnabled=e.group_role_mapping_enabled,this.attributeMapping=e.attribute_mapping??{},this.credentialsConfigured=e.credentials_configured??null,this.apiKey=e.api_key??null,this.createdAt=tE(e.created_at),this.updatedAt=tE(e.updated_at)),this}__internal_toSnapshot(){return{object:"directory",id:this.id,name:this.name,enterprise_connection_id:this.enterpriseConnectionId,endpoint_url:this.endpointUrl,provider:this.provider,enabled:this.enabled,group_role_mapping_enabled:this.groupRoleMappingEnabled,attribute_mapping:this.attributeMapping,credentials_configured:this.credentialsConfigured,created_at:this.createdAt?.getTime()??0,updated_at:this.updatedAt?.getTime()??0}}}let r6=e=>({id:e.id,directoryGroupId:e.directory_group_id,directoryGroupDisplayName:e.directory_group_display_name,role:e.role?new r4(e.role):null,precedence:e.precedence}),r8=e=>({data:(e?.data??[]).map(r6),defaultRole:e?.default_role?new r4(e.default_role):null});class r9 extends iu{id;userId;firstName=null;lastName=null;identifier=null;imageUrl;hasImage;active;provisionedAt=null;updatedAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.userId=e.user_id,this.firstName=e.first_name,this.lastName=e.last_name,this.identifier=e.identifier,this.imageUrl=e.image_url,this.hasImage=e.has_image,this.active=e.active,this.provisionedAt=tE(e.provisioned_at),this.updatedAt=tE(e.updated_at)),this}}class r7 extends iu{id;name;active;provider;logoPublicUrl=null;domains=[];organizationId=null;syncUserAttributes;disableAdditionalIdentifications;allowOrganizationAccountLinking;customAttributes=[];oauthConfig=null;samlConnection=null;createdAt=null;updatedAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){var t,i;return e?(this.id=e.id,this.name=e.name,this.active=e.active,this.provider=e.provider,this.logoPublicUrl=e.logo_public_url??null,this.domains=e.domains??[],this.organizationId=e.organization_id??null,this.syncUserAttributes=e.sync_user_attributes,this.disableAdditionalIdentifications=e.disable_additional_identifications,this.allowOrganizationAccountLinking=e.allow_organization_account_linking??!1,this.customAttributes=e.custom_attributes??[],this.createdAt=tE(e.created_at),this.updatedAt=tE(e.updated_at),this.samlConnection=e.saml_connection?{id:(t=e.saml_connection).id,name:t.name,active:t.active,idpEntityId:t.idp_entity_id,idpSsoUrl:t.idp_sso_url,idpCertificate:t.idp_certificate,idpCertificateIssuedAt:t.idp_certificate_issued_at,idpCertificateExpiresAt:t.idp_certificate_expires_at,idpCertificates:(t.idp_certificates??[]).map(e=>({certificate:e.certificate,issuedAt:e.issued_at,expiresAt:e.expires_at})),idpMetadataUrl:t.idp_metadata_url,idpMetadata:t.idp_metadata,acsUrl:t.acs_url,spEntityId:t.sp_entity_id,spMetadataUrl:t.sp_metadata_url,allowSubdomains:t.allow_subdomains,allowIdpInitiated:t.allow_idp_initiated,forceAuthn:t.force_authn}:null,this.oauthConfig=e.oauth_config?{id:(i=e.oauth_config).id,name:i.name,clientId:i.client_id,providerKey:i.provider_key,redirectUri:i.redirect_uri,discoveryUrl:i.discovery_url,authUrl:i.auth_url,tokenUrl:i.token_url,userInfoUrl:i.user_info_url,logoPublicUrl:i.logo_public_url,requiresPkce:i.requires_pkce,createdAt:tE(i.created_at),updatedAt:tE(i.updated_at)}:null,this):this}__internal_toSnapshot(){var e,t;return{object:"enterprise_connection",id:this.id,name:this.name,active:this.active,provider:this.provider,logo_public_url:this.logoPublicUrl,domains:this.domains,organization_id:this.organizationId,sync_user_attributes:this.syncUserAttributes,disable_additional_identifications:this.disableAdditionalIdentifications,allow_organization_account_linking:this.allowOrganizationAccountLinking,custom_attributes:this.customAttributes,saml_connection:this.samlConnection?{id:(e=this.samlConnection).id,name:e.name,active:e.active,idp_entity_id:e.idpEntityId,idp_sso_url:e.idpSsoUrl,idp_certificate:e.idpCertificate,idp_certificate_issued_at:e.idpCertificateIssuedAt,idp_certificate_expires_at:e.idpCertificateExpiresAt,idp_certificates:e.idpCertificates.map(e=>({certificate:e.certificate,issued_at:e.issuedAt,expires_at:e.expiresAt})),idp_metadata_url:e.idpMetadataUrl,idp_metadata:e.idpMetadata,acs_url:e.acsUrl,sp_entity_id:e.spEntityId,sp_metadata_url:e.spMetadataUrl,allow_subdomains:e.allowSubdomains,allow_idp_initiated:e.allowIdpInitiated,force_authn:e.forceAuthn}:void 0,oauth_config:this.oauthConfig?{id:(t=this.oauthConfig).id,name:t.name,client_id:t.clientId,provider_key:t.providerKey,redirect_uri:t.redirectUri,discovery_url:t.discoveryUrl,auth_url:t.authUrl,token_url:t.tokenUrl,user_info_url:t.userInfoUrl,logo_public_url:t.logoPublicUrl,requires_pkce:t.requiresPkce,created_at:t.createdAt?.getTime()??0,updated_at:t.updatedAt?.getTime()??0}:void 0,created_at:this.createdAt?.getTime()??0,updated_at:this.updatedAt?.getTime()??0}}}class ne{pathRoot="/me";id;status;connectionType;parsedUserInfo=null;logs=[];saml=null;oauth=null;createdAt=null;constructor(e){this.fromJSON(e)}reload(e){it("EnterpriseConnectionTestRun")}fromJSON(e){var t,i,r;return e&&(this.id=e.id,this.status=e.status,this.connectionType=e.connection_type,this.parsedUserInfo=(t=e.parsed_user_info??null)?{emailAddress:t.email_address,firstName:t.first_name,lastName:t.last_name,userId:t.user_id}:null,this.saml=(i=e.saml??null)?{samlRequest:i.saml_request,samlResponse:i.saml_response,relayState:i.relay_state}:null,this.oauth=(r=e.oauth??null)?{idToken:r.id_token,accessToken:r.access_token,userInfo:r.user_info}:null,this.createdAt=tE(e.created_at),this.logs=(e.logs??[]).map(e=>({level:e.level,code:e.code,shortMessage:e.short_message,message:e.message}))),this}__internal_toSnapshot(){var e,t,i;return{object:"enterprise_connection_test_run",id:this.id,status:this.status,connection_type:this.connectionType,parsed_user_info:(e=this.parsedUserInfo)?{email_address:e.emailAddress,first_name:e.firstName,last_name:e.lastName,user_id:e.userId}:null,saml:(t=this.saml)?{saml_request:t.samlRequest,saml_response:t.samlResponse,relay_state:t.relayState}:null,oauth:(i=this.oauth)?{id_token:i.idToken,access_token:i.accessToken,user_info:i.userInfo}:null,logs:this.logs.map(e=>({level:e.level,code:e.code,short_message:e.shortMessage,message:e.message})),created_at:this.createdAt?.getTime()??0}}}class nt{firstName;lastName;imageUrl;hasImage;identifier;userId;username;banned;deprovisioned;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.username=e.username,this.banned=e.banned??void 0,this.deprovisioned=e.deprovisioned??void 0),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,username:this.username,banned:this.banned,deprovisioned:this.deprovisioned}}}class ni{id;userId;publicUserData;createdAt;updatedAt;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.user_id,this.userId=e.user_id,this.publicUserData=new nt(e.public_user_data),this.createdAt=tE(e.created_at),this.updatedAt=tE(e.updated_at)),this}__internal_toSnapshot(){return{object:"sso_bypass_allowlist_user",user_id:this.userId,public_user_data:this.publicUserData.__internal_toSnapshot(),created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}class nr{constructor(e){Object.defineProperty(this,"organization",{value:e,enumerable:!1})}get path(){return`/organizations/${this.organization.id}/sso_bypass_allowlist_users`}getUsers=async()=>((await iu._fetch({path:this.path,method:"GET"}))?.response||[]).map(e=>new ni(e));addUser=async e=>new ni((await iu._fetch({path:this.path,method:"POST",body:{user_id:e.userId}}))?.response);addUsers=async e=>{let t={data:[],errors:[]};for(let i=0;i<e.userIds.length;i+=100){let r=(await iu._fetch({path:`${this.path}/bulk`,method:"POST",body:{user_id:e.userIds.slice(i,i+100)}}))?.response;t.data.push(...(r?.data??[]).map(e=>new ni(e))),t.errors.push(...(r?.errors??[]).map(e=>({userId:e.user_id,code:e.code})))}return t};removeUser=async e=>new rN((await iu._fetch({path:`${this.path}/${e}`,method:"DELETE"}))?.response)}class nn extends iu{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 ns extends iu{actions={adminDelete:!1};domains={enabled:!1,enrollmentModes:[],defaultRole:null};slug={disabled:!1};organizationCreationDefaults={enabled:!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)),e.organization_creation_defaults&&(this.organizationCreationDefaults.enabled=this.withDefault(e.organization_creation_defaults.enabled,this.organizationCreationDefaults.enabled)),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 na extends iu{static instance;authConfig=new i_;displayConfig=new rD;maintenanceMode=!1;clientDebugMode=!1;partitionedCookies=!1;pathRoot="/environment";userSettings=new sc;organizationSettings=new ns;commerceSettings=new rF;apiKeysSettings=new nn;protectConfig=new nI;static getInstance(){return na.instance||(na.instance=new na),na.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new i_(e.auth_config),this.displayConfig=new rD(e.display_config),this.maintenanceMode=this.withDefault(e.maintenance_mode,this.maintenanceMode),this.clientDebugMode=this.withDefault(e.client_debug_mode,this.clientDebugMode),this.partitionedCookies=this.withDefault(e.partitioned_cookies,this.partitionedCookies),this.organizationSettings=new ns(e.organization_settings),this.userSettings=new sc(e.user_settings),this.commerceSettings=new rF(e.commerce_settings),this.apiKeysSettings=new nn(e.api_keys_settings),this.protectConfig=new nI(e.protect_config)),this}fetch({touch:e,fetchMaxTries:t}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:t})).then(e=>(rp.emit(rh,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,partitioned_cookies:this.partitionedCookies,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 no extends iu{id;identificationId;provider;providerUserId="";emailAddress="";approvedScopes="";firstName="";lastName="";imageUrl="";username="";phoneNumber="";publicMetadata={};label="";verification=null;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}reauthorize=e=>{let{additionalScopes:t,redirectUrl:i,oidcPrompt:r,oidcLoginHint:n}=e||{};return this._basePatch({action:"reauthorize",body:{additional_scope:t,redirect_url:i,oidc_prompt:r,oidc_login_hint:n}})};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 rX(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 nl extends iu{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 nc extends iu{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 nd extends iu{id;name=null;publicUrl=null;static async create(e,t={}){let i,r=t;return"string"==typeof t.file?(r=t.file,i=new Headers({"Content-Type":"application/octet-stream"})):t.file&&(r=new FormData).append("file",t.file),new nd((await iu._fetch({path:e,method:"POST",body:r,headers:i}))?.response)}static async delete(e){return new nd((await iu._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}}function nh(e,t={}){let i={};nu(i,"provider",e.provider),nu(i,"name",e.name);let r=e.domains;return r&&r.length>0&&(i.domains=r),t.omitOrganizationId||nu(i,"organization_id",e.organizationId),nu(i,"active",e.active),nu(i,"sync_user_attributes",e.syncUserAttributes),nu(i,"disable_additional_identifications",e.disableAdditionalIdentifications),nu(i,"custom_attributes",e.customAttributes),e.saml&&(nu(i,"saml_idp_entity_id",e.saml.idpEntityId),nu(i,"saml_idp_sso_url",e.saml.idpSsoUrl),nu(i,"saml_idp_certificate",e.saml.idpCertificate),nu(i,"saml_idp_certificates",e.saml.idpCertificates),nu(i,"saml_idp_metadata_url",e.saml.idpMetadataUrl),nu(i,"saml_idp_metadata",e.saml.idpMetadata),nu(i,"saml_attribute_mapping",e.saml.attributeMapping),nu(i,"saml_allow_subdomains",e.saml.allowSubdomains),nu(i,"saml_allow_idp_initiated",e.saml.allowIdpInitiated),nu(i,"saml_force_authn",e.saml.forceAuthn)),e.oidc&&(nu(i,"oidc_client_id",e.oidc.clientId),nu(i,"oidc_client_secret",e.oidc.clientSecret),nu(i,"oidc_discovery_url",e.oidc.discoveryUrl),nu(i,"oidc_auth_url",e.oidc.authUrl),nu(i,"oidc_token_url",e.oidc.tokenUrl),nu(i,"oidc_user_info_url",e.oidc.userInfoUrl),nu(i,"oidc_requires_pkce",e.oidc.requiresPkce)),i}function nu(e,t,i){void 0!==i&&(e[t]=i)}class np extends iu{id;name;organizationId;enrollmentMode;verification;affiliationVerification;ownershipVerification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:t,enrollmentMode:i}){return new np((await iu._fetch({path:`/organizations/${e}/domains`,method:"POST",body:{name:t,enrollment_mode:i}}))?.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){if(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;let t=e.affiliation_verification??e.verification;if(t){let e={status:t.status,strategy:t.strategy,attempts:t.attempts,expiresAt:tE(t.expires_at)};this.affiliationVerification=e,this.verification=e}else this.affiliationVerification=null,this.verification=null;e.ownership_verification?this.ownershipVerification={status:e.ownership_verification.status,strategy:e.ownership_verification.strategy,attempts:e.ownership_verification.attempts,expiresAt:e.ownership_verification.expire_at?tE(e.ownership_verification.expire_at):null,verifiedAt:e.ownership_verification.verified_at?tE(e.ownership_verification.verified_at):null,txtRecordName:e.ownership_verification.txt_record_name??null,txtRecordValue:e.ownership_verification.txt_record_value??null}:this.ownershipVerification=null}return this}}class n_ extends iu{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=tE(e.created_at),this.updatedAt=tE(e.updated_at),e.public_user_data&&(this.publicUserData=new nt(e.public_user_data))),this}}class nf extends iu{pathRoot="/organizations";ssoBypassAllowlist=new nr(this);id;name;slug;imageUrl;hasImage;publicMetadata={};adminDeleteEnabled;createdAt;updatedAt;membersCount=0;pendingInvitationsCount=0;maxAllowedMemberships;selfServeSSOEnabled=!1;selfServeDirectorySyncEnabled=!1;exclusiveMembership=!1;constructor(e){super(),this.fromJSON(e)}static async create(e){return new nf((await iu._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new nf((await iu._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await iu._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:iN(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i,has_role_set_migration:r}=e?.response;return{data:t.map(e=>new r4(e)),total_count:i,has_role_set_migration:r}});getDomains=async e=>{let{enrollmentMode:t,...i}=e||{},r=iN(i);return t&&r.set("enrollment_mode",t),await iu._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:r},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new np(e))}})};getDomain=async({domainId:e})=>new np((await iu._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getEnterpriseConnections=async e=>{let{withOrganizationAccountLinking:t}=e||{};return((await iu._fetch({path:`/organizations/${this.id}/enterprise_connections`,method:"GET",...void 0!==t?{search:{with_organization_account_linking:String(t)}}:{}}))?.response||[]).map(e=>new r7(e))};createEnterpriseConnection=async e=>new r7((await iu._fetch({path:`/organizations/${this.id}/enterprise_connections`,method:"POST",body:nh(e,{omitOrganizationId:!0})}))?.response);updateEnterpriseConnection=async(e,t)=>new r7((await iu._fetch({path:`/organizations/${this.id}/enterprise_connections/${e}`,method:"PATCH",body:nh(t,{omitOrganizationId:!0})}))?.response);deleteEnterpriseConnection=async e=>new rN((await iu._fetch({path:`/organizations/${this.id}/enterprise_connections/${e}`,method:"DELETE"}))?.response);createEnterpriseConnectionTestRun=async e=>({url:((await iu._fetch({path:`/organizations/${this.id}/enterprise_connections/${e}/test_runs`,method:"POST"}))?.response).url});getEnterpriseConnectionTestRuns=async(e,t)=>{let{status:i,...r}=t||{},n=iN(r);if(i?.length)for(let e of i)n.append("status",e);let s=await iu._fetch({path:`/organizations/${this.id}/enterprise_connections/${e}/test_runs`,method:"GET",search:n}),a=s?.response;return{total_count:a?.total_count??0,data:(a?.data??[]).map(e=>new ne(e))}};getDirectorySync=async e=>new r5((await iu._fetch({path:`/organizations/${this.id}/enterprise_connections/${e}/directory`,method:"GET"}))?.response,this.id);createDirectorySync=async(e,t)=>new r5((await iu._fetch({path:`/organizations/${this.id}/enterprise_connections/${e}/directory`,method:"POST",body:{name:t?.name}}))?.response,this.id);getMembershipRequests=async e=>await iu._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:iN(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new n_(e))}});createDomain=async(e,t)=>np.create(this.id,{name:e,enrollmentMode:t?.enrollmentMode});prepareOwnershipVerification=async e=>this.bulkOwnershipVerification("prepare_ownership_verification",e);attemptOwnershipVerification=async e=>this.bulkOwnershipVerification("attempt_ownership_verification",e);bulkOwnershipVerification=async(e,t)=>{let{data:i,errors:r}=(await iu._fetch({path:`/organizations/${this.id}/domains/${e}/bulk`,method:"POST",body:{organization_domain_ids:t}},{forceUpdateClient:!0}))?.response;return{data:(i??[]).map(e=>new np(e)),errors:r??[]}};getMemberships=async e=>await iu._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:iN({...e,paginated:!0})}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new ng(e))}});getInvitations=async e=>await iu._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:iN(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new nm(e))}});addMember=async({userId:e,role:t})=>await iu._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:t}}).then(e=>new ng(e?.response));inviteMember=async e=>nm.create(this.id,e);inviteMembers=async e=>nm.createBulk(this.id,e);updateMember=async({userId:e,role:t})=>await iu._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:t}}).then(e=>new ng(e?.response));removeMember=async e=>await iu._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new ng(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let t,i;return null===e?await iu._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new nf(e?.response)):("string"==typeof e?(t=e,i=new Headers({"Content-Type":"application/octet-stream"})):(t=new FormData).append("file",e),await iu._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:t,headers:i}).then(e=>new nf(e?.response)))};initializePaymentMethod=e=>i5({...e,orgId:this.id});addPaymentMethod=e=>i6({...e,orgId:this.id});getPaymentMethods=e=>i8({...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.selfServeSSOEnabled=e.self_serve_sso_enabled||!1,this.selfServeDirectorySyncEnabled=e.self_serve_directory_sync_enabled||!1,this.exclusiveMembership=e.exclusive_membership||!1,this.createdAt=tE(e.created_at),this.updatedAt=tE(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,self_serve_sso_enabled:this.selfServeSSOEnabled,self_serve_directory_sync_enabled:this.selfServeDirectorySyncEnabled,exclusive_membership:this.exclusiveMembership,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}async reload(e){let{rotatingTokenNonce:t}=e||{},i=(await iu._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:t},{forceUpdateClient:!0}))?.response;return this.fromJSON(i)}}class nm extends iu{id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:t,role:i}){return new nm((await iu._fetch({path:`/organizations/${e}/invitations`,method:"POST",body:{email_address:t,role:i}}))?.response)}static async createBulk(e,t){let{emailAddresses:i,role:r}=t;return((await iu._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:i,role:r}}))?.response).map(e=>new nm(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=tE(e.created_at),this.updatedAt=tE(e.updated_at)),this}}class ng extends iu{id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await iu._fetch({path:"/me/organization_memberships",method:"GET",search:iN({...e,paginated:!0})}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new ng(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 nf(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new nt(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=tE(e.created_at),this.updatedAt=tE(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){it("OrganizationMembership")}}class ny extends iu{id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await iu._fetch({path:"/me/organization_suggestions",method:"GET",search:iN(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new ny(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=tE(e.created_at),this.updatedAt=tE(e.updated_at)),this}}function nw(){return"u">typeof window&&b()&&"function"==typeof window.PublicKeyCredential}async function nb(){try{return nw()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function nv(){try{return"u">typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class nk extends iu{id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return iu._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new nk(e?.response))}static async attemptVerification(e,t){let i,r=(i=t.response,{...rq(t),response:{clientDataJSON:rG(i.clientDataJSON),attestationObject:rG(i.attestationObject),transports:i.getTransports()}});return iu._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(r)}}).then(e=>new nk(e?.response))}static async registerPasskey(){let e,t=nk.clerk.__internal_isWebAuthnSupported||nw,i=nk.clerk.__internal_createPublicCredentials||rj,r=nk.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||nv;if(!t())throw new q("Passkeys are not supported on this device.",{code:"passkey_not_supported"});let n=await this.create();try{let{verification:t}=n,s=t?.publicKey;if(s||ii("create"),s.authenticatorSelection?.authenticatorAttachment==="platform"&&!await r())throw new q("Registration requires a platform authenticator but the device does not support it.",{code:"passkey_pa_not_supported"});let a=await i(s);if(!a.publicKeyCredential)throw a.error;e=a.publicKeyCredential}catch(e){throw n.id&&await n.delete().catch(tm.lQ),e}return this.attemptVerification(n.id,e)}update=e=>this._basePatch({body:e});delete=async()=>new rN((await iu._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?tE(e.last_used_at):null,this.createdAt=tE(e.created_at),this.updatedAt=tE(e.updated_at),e.verification&&(this.verification=new rY(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 nS extends iu{id;phoneNumber="";reservedForSecondFactor=!1;defaultSecondFactor=!1;linkedTo=[];verification;backupCodes;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}create=()=>this._basePost({body:{phone_number:this.phoneNumber}});prepareVerification=()=>this._basePost({action:"prepare_verification",coalesce:!0,body:{strategy:"phone_code"}});attemptVerification=e=>{let{code:t}=e||{};return this._basePost({action:"attempt_verification",body:{code:t}})};setReservedForSecondFactor=e=>{let{reserved:t}=e||{};return this._basePatch({body:{reserved_for_second_factor:t}})};makeDefaultSecondFactor=()=>this._basePatch({body:{default_second_factor:!0}});destroy=()=>this._baseDelete();toString=()=>{let e=this.phoneNumber.match(/^(\d{3})(\d{3})(\d{4})$/);return e?"("+e[1]+") "+e[2]+"-"+e[3]:this.phoneNumber};fromJSON(e){return e&&(this.id=e.id,this.phoneNumber=e.phone_number,this.reservedForSecondFactor=e.reserved_for_second_factor,this.defaultSecondFactor=e.default_second_factor,this.verification=new rX(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new nc(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 nI extends iu{id="";loaders;tokens_invalid_before;challenge_load_timeout_ms;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.tokens_invalid_before=this.withDefault(e.tokens_invalid_before,this.tokens_invalid_before),this.challenge_load_timeout_ms=this.withDefault(e.challenge_load_timeout_ms,this.challenge_load_timeout_ms)),this}__internal_toSnapshot(){return{object:"protect_config",id:this.id,loaders:this.loaders,tokens_invalid_before:this.tokens_invalid_before,challenge_load_timeout_ms:this.challenge_load_timeout_ms}}}let nC={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"}},nU=new Set(["first_factor","second_factor","multi_factor"]),nA=new Set(["strict_mfa","strict","moderate","lax"]),nP=new Set(["o","org","organization"]),nT=new Set(["u","user"]),nO=e=>"number"==typeof e&&Number.isFinite(e)&&(-1===e||e>=0),nE=(e,t)=>{let{org:i,user:r}=nx(e),[n,s]=t.split(":"),a=void 0!==s,o=s||n;if(a&&!nP.has(n)&&!nT.has(n))throw Error(`Invalid scope: ${n}`);if(a){if(nP.has(n))return i.includes(o);if(nT.has(n))return r.includes(o)}return[...i,...r].includes(o)},nx=e=>{let t=[],i=[];if(!e)return{org:t,user:i};let r=e.split(",");for(let e=0;e<r.length;e++){let n=r[e].trim(),s=n.indexOf(":");if(-1===s)throw Error(`Invalid claim element (missing colon): ${n}`);let a=n.slice(0,s),o=n.slice(s+1);"o"===a?t.push(o):"u"===a?i.push(o):("ou"===a||"uo"===a)&&(t.push(o),i.push(o))}return{org:t,user:i}};class nR extends iu{status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new rX(null);secondFactorVerification=new rX(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new nz(e.session),this.level=e.level,this.supportedFirstFactors=ef(e.supported_first_factors),this.supportedSecondFactors=ef(e.supported_second_factors),this.firstFactorVerification=new rX(e.first_factor_verification),this.secondFactorVerification=new rX(e.second_factor_verification)),this}}let nM=e=>!1===rw()?{}:{onRefresh:e};class nz extends iu{pathRoot="/client/sessions";static #$=new Set;id;status;lastActiveAt;lastActiveToken;lastActiveOrganizationId;actor;agent;user;publicUserData;factorVerificationAge=null;tasks=null;expireAt;abandonAt;createdAt;updatedAt;static isSessionResource(e){return!!e&&e instanceof nz}constructor(e){super(),this.fromJSON(e),this.#j(this.lastActiveToken)}end=()=>(rR.clear(),this._basePost({action:"end"}));remove=()=>(rR.clear(),this._basePost({action:"remove"}));_touchPost=async({intent:e,skipUpdateClient:t}={skipUpdateClient:!1})=>{let i=await iu._fetch({method:"POST",path:this.path("touch"),body:{active_organization_id:this.lastActiveOrganizationId,intent:e}},{skipUpdateClient:t});return this.fromJSON(i?.response||i),i};touch=async({intent:e}={})=>(await this._touchPost({intent:e,skipUpdateClient:!1}),this.lastActiveToken&&rp.emit(rc,{token:this.lastActiveToken}),this);__internal_touch=async({intent:e}={})=>rM(await this._touchPost({intent:e,skipUpdateClient:!0}));clearCache=()=>rR.clear();getToken=async e=>{try{let t=await tA(()=>this._getToken(e),{factor:1.55,initialDelay:3e3,maxDelayBetweenRetries:5e4,jitter:!1,shouldRetry:(e,t)=>(!G(e)||e?.status===429)&&(k()?t<=8:t<=3)});if(!t&&!k())throw new B("Network request failed while offline. The browser appears to be disconnected.");return t}catch(e){if(!$(e)&&!k())throw new B("Network request failed while offline. The browser appears to be disconnected.");throw e}};checkAuthorization=e=>{let t,i=(this.user?.organizationMemberships||[]).find(e=>e.organization.id===this.lastActiveOrganizationId);return(t={userId:this.user?.id,factorVerificationAge:this.factorVerificationAge,orgId:i?.organization?.id,orgRole:i?.role,orgPermissions:i?.permissions,features:this.lastActiveToken?.jwt?.claims.fea||"",plans:this.lastActiveToken?.jwt?.claims.pla||""},e=>{let i;return!!t.userId&&(i=[((e,t)=>{let{orgId:i,orgRole:r,orgPermissions:n}=t,s=void 0!==e.role,a=void 0!==e.permission;return s||a?s&&"string"!=typeof e.role||a&&"string"!=typeof e.permission||!i||s&&("string"!=typeof r||!r||r.replace(/^(org:)*/,"org:")!==e.role.replace(/^(org:)*/,"org:"))||a&&(!Array.isArray(n)||!n.includes(e.permission.replace(/^(org:)*/,"org:")))?"fail":"pass":"skip"})(e,t),((e,t)=>{let{features:i,plans:r}=t,n=void 0!==e.feature,s=void 0!==e.plan;if(!n&&!s)return"skip";if(n&&"string"!=typeof e.feature||s&&"string"!=typeof e.plan)return"fail";if(n){if("string"!=typeof i||!i)return"fail";try{if(!nE(i,e.feature))return"fail"}catch{return"fail"}}if(s){if("string"!=typeof r||!r)return"fail";try{if(!nE(r,e.plan))return"fail"}catch{return"fail"}}return"pass"})(e,t),((e,{factorVerificationAge:t})=>{if(void 0===e.reverification)return"skip";if(!t||!Array.isArray(t)||2!==t.length||!nO(t[0])||!nO(t[1]))return"fail";let i=(e=>{let t,i;if(!e)return!1;let r="string"==typeof e&&nA.has(e),n="object"==typeof e&&(t=e.level,nU.has(t))&&"number"==typeof(i=e.afterMinutes)&&i>0;return(!!r||!!n)&&(e=>"string"==typeof e?nC[e]:e).bind(null,e)})(e.reverification);if(!i)return"fail";let{level:r,afterMinutes:n}=i(),[s,a]=t;if(-1===s&&-1===a)return"fail";let o=-1!==s&&n>s,l=-1!==a&&n>a;switch(r){case"first_factor":return o?"pass":"fail";case"second_factor":if(-1===a)return o?"pass":"fail";return l?"pass":"fail";case"multi_factor":if(-1===a)return o?"pass":"fail";if(-1===s)return"fail";return o&&l?"pass":"fail"}})(e,t)]).some(e=>"pass"===e)&&i.every(e=>"pass"===e||"skip"===e)})(e)};#j=e=>{if(e){let t=this.#B();rR.set({tokenId:t,tokenResolver:Promise.resolve(e),...nM(()=>this.#J(void 0,this.lastActiveOrganizationId,t,!0))})}};#B(e,t){let i=void 0===t?this.lastActiveOrganizationId:t;return r_.build(this.id,e,i)}startVerification=async({level:e})=>new nR((await iu._fetch({method:"POST",path:`/client/sessions/${this.id}/verify`,body:{level:e}}))?.response);prepareFirstFactorVerification=async e=>{let t;switch(e.strategy){case"email_code":t={emailAddressId:e.emailAddressId};break;case"phone_code":t={phoneNumberId:e.phoneNumberId,default:e.default};break;case"passkey":t={};break;case"trusted_device":t={trustedDeviceId:e.trustedDeviceId};break;case"enterprise_sso":t={emailAddressId:e.emailAddressId,enterpriseConnectionId:e.enterpriseConnectionId,redirectUrl:e.redirectUrl};break;default:t8("Session.prepareFirstFactorVerification",e.strategy)}return new nR((await iu._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_first_factor`,body:{...t,strategy:e.strategy}}))?.response)};attemptFirstFactorVerification=async e=>{let t;return t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(rH(e.publicKeyCredential))}:{...e},new nR((await iu._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_first_factor`,body:{...t,strategy:e.strategy}}))?.response)};verifyWithPasskey=async e=>{let t=e?.level??"first_factor";"first_factor"!==t&&"second_factor"!==t&&function(e,t){throw Error(`${t2} "${t}" is not a valid verification level for ${e}. Use 'first_factor' or 'second_factor'.`)}("Session.verifyWithPasskey",t);let i="second_factor"===t?await this.prepareSecondFactorVerification({strategy:"passkey"}):await this.prepareFirstFactorVerification({strategy:"passkey"}),{nonce:r=null}="second_factor"===t?i.secondFactorVerification:i.firstFactorVerification,n=nz.clerk.__internal_isWebAuthnSupported||nw,s=nz.clerk.__internal_getPublicCredentials||rJ;if(!n())throw new q("Passkeys are not supported",{code:"passkey_not_supported"});let a=r?rV(JSON.parse(r)):null;a||ii("get");let{publicKeyCredential:o,error:l}=await s({publicKeyOptions:a,conditionalUI:!1});if(!o)throw l;return"second_factor"===t?this.attemptSecondFactorVerification({strategy:"passkey",publicKeyCredential:o}):this.attemptFirstFactorVerification({strategy:"passkey",publicKeyCredential:o})};prepareSecondFactorVerification=async e=>new nR((await iu._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>{let t;return t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(rH(e.publicKeyCredential))}:{...e},new nR((await iu._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_second_factor`,body:{...t,strategy:e.strategy}}))?.response)};fromJSON(e){if(!e)return this;this.id=e.id,this.status=e.status,this.expireAt=tE(e.expire_at),this.abandonAt=tE(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=tE(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.agent=e.actor?.type==="agent"?e.actor:null,this.createdAt=tE(e.created_at),this.updatedAt=tE(e.updated_at),this.user=new ss(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new nt(e.public_user_data));let t=e.last_active_token?new n8(e.last_active_token):null;return t&&rO(this.lastActiveToken,t)||(this.lastActiveToken=t),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){let t;if(!this.user)return null;let{skipCache:i=!1,template:r}=e||{},n=void 0===e?.organizationId?this.lastActiveOrganizationId:e?.organizationId,s=this.#B(r,n),a=i?void 0:rR.get({tokenId:s}),o=!r&&n===this.lastActiveOrganizationId;if(a){let e=a.entry.resolvedToken??await a.entry.tokenResolver;o&&e.getRawString()&&rp.emit(rc,{token:e}),t=e.getRawString()||null}else t=await this.#K(r,n,s,o,i);if(null===t&&!k())throw new R("Network request failed while offline",{code:"network_error"});return t}#V(e,t,i){let r=e?`${this.path()}/tokens/${e}`:`${this.path()}/tokens`,n=nz.clerk?.__internal_environment?.authConfig?.sessionMinter,s=e?void 0:(()=>{let e=rw();if(void 0!==e){if(e)return"focused";try{return"visible"===document.visibilityState?"visible":"hidden"}catch{return}}})(),a=e?{}:{organizationId:t??null,...s?{tabState:s}:{},...n&&this.lastActiveToken?{token:this.lastActiveToken.getRawString()}:{},...n&&i?{forceOrigin:"true"}:{}};if(n)return n8.create(r,a,i?{debug:"skip_cache"}:void 0);let o=this.lastActiveToken?.getRawString();return n8.create(r,a,i?{debug:"skip_cache"}:void 0).catch(e=>{if(j.is(e)&&o)return n8.create(r,{...a},{expired_token:o});throw e})}#q(e,t){!t||e.getRawString()&&(rp.emit(rc,{token:e}),e.jwt&&!rO(this.lastActiveToken,e)&&(this.lastActiveToken=e,rp.emit(ru,null)))}#K(e,t,i,r,n){tS.info("Fetching new token from API",{organizationId:t,template:e,tokenId:i},"session");let s=this.#V(e,t,n);return rR.set({tokenId:i,tokenResolver:s,...nM(()=>this.#J(e,t,i,r))}),s.then(e=>{let t=e.getRawString();if(!t)throw new R("Token fetch returned empty response",{code:"network_error"});return this.#q(e,r),t})}#J(e,t,i,r){if(nz.#$.has(i))return;nz.#$.add(i);let n=nz.clerk?.__internal_getOption?.("experimental"),s=n?.runtimeEnvironment==="headless",a=this.lastActiveToken?.jwt?.claims?.exp;s&&a&&Date.now()/1e3>a?nz.#$.delete(i):this.#V(e,t,!1).then(n=>{n.getRawString()&&(rR.set({tokenId:i,tokenResolver:Promise.resolve(n),...nM(()=>this.#J(e,t,i,r))}),this.#q(n,r))}).catch(e=>{tS.warn("Background token refresh failed",{error:e,tokenId:i},"session")}).finally(()=>{nz.#$.delete(i)})}get currentTask(){let[e]=this.tasks??[];return e}}class nF extends iu{pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}static retrieve(){let e=iu.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new nF(e,"/me/sessions"))).catch(()=>[])}revoke(){return this._basePost({action:"revoke",body:{}})}fromJSON(e){let t;return e?(this.id=e.id,this.status=e.status,this.expireAt=tE(e.expire_at),this.abandonAt=tE(e.abandon_at),this.lastActiveAt=tE(e.last_active_at||void 0),this.latestActivity={id:(t=e.latest_activity??{}).id,deviceType:t.device_type,browserName:t.browser_name,browserVersion:t.browser_version,country:t.country,city:t.city,isMobile:t.is_mobile,ipAddress:t.ip_address},this.actor=e.actor,this):this}}let nN=(e,t,i)=>{let{onValidation:r=rf.t,onValidationComplexity:n=rf.t}=i||{},{show_zxcvbn:s,validatePassword:a}=t,o=e=>((e,t)=>{let{max_length:i,min_length:r,require_special_char:n,require_lowercase:s,require_numbers:a,require_uppercase:o}=t,l=(e=>{let t;if(e.allowed_special_characters){let i=e.allowed_special_characters.replace("[","\\[");i=i.replace("]","\\]"),t=RegExp(`[${i}]`)}else t=/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/;return(e,{minLength:i,maxLength:r})=>({max_length:e.length<r,min_length:e.length>=i,require_numbers:/\d/.test(e),require_lowercase:/[a-z]/.test(e),require_uppercase:/[A-Z]/.test(e),require_special_char:t.test(e)})})(t)(e,{maxLength:t.max_length,minLength:t.min_length}),c={max_length:i,min_length:r,require_special_char:n,require_lowercase:s,require_numbers:a,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,t),l=(({min_zxcvbn_strength:e,onResult:t})=>i=>r=>{let n=i(r);return(t?.(n),n.score>=e&&n.score<3)?{state:"pass",keys:["unstable__errors.zxcvbn.couldBeStronger"],result:n}:n.score>=e?{state:"excellent",result:n}:{state:"fail",keys:["unstable__errors.zxcvbn.notEnough",...n.feedback.suggestions.map(e=>`unstable__errors.zxcvbn.suggestions.${e}`)],result:n}})(t),c={};return(t,i)=>{let{onValidation:d=r,onValidationComplexity:h=n}=i||{};if(!a)return;let u=o(t);h(0===Object.keys(u).length),c={...c,complexity:u},s&&e().then(e=>{let i=l(e)(t);d({...c={...c,strength:i},strength:i})}),c.complexity&&0===Object.keys(c.complexity).length&&s||d(c)}};function nD(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function nW(e,t,i,r,n){if(!e.client||!r.popup)return;let s=nD(e.frontendApi),{redirectUrl:a}=r,o=new URL(a);o.searchParams.set("sign_in_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("sign_up_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("intent",t);let l=e.buildUrlWithAuth(o.toString()),c=e.buildUrlWithAuth(`${s}/popup-callback`),d=e.buildUrlWithAuth(`${s}/popup-callback?return_url=${encodeURIComponent(l)}`),h=async t=>{if(t.origin!==s)return;let i=!1;if(t.data.session){if(!e.client?.sessions.find(e=>e.id===t.data.session))try{await e.client?.reload()}catch(e){console.error(e)}await e.setActive({session:t.data.session,redirectUrl:r.redirectUrlComplete}),i=!0}else t.data.return_url&&(e.navigate(t.data.return_url),i=!0);i&&window.removeEventListener("message",h)};window.addEventListener("message",h),await i({...r,redirectUrlComplete:c,redirectUrl:d},n)}function nL(e,{redirectCallbackUrl:t,redirectUrl:i}){let r=nD(e.frontendApi),n=new URL(t);n.searchParams.set("sign_in_force_redirect_url",i),n.searchParams.set("sign_up_force_redirect_url",i);let s=e.buildUrlWithAuth(n.toString()),a=e.buildUrlWithAuth(`${r}/popup-callback`);return{redirectCallbackUrl:e.buildUrlWithAuth(`${r}/popup-callback?return_url=${encodeURIComponent(s)}`),redirectUrl:a}}function n$(e,t){return new Promise((i,r)=>{if(!e.client||!t.popup)return void r();let n=async t=>{t.origin===nD(e.frontendApi)&&(t.data.session||t.data.return_url?(window.removeEventListener("message",n),i()):r())};window.addEventListener("message",n),t.popup.location.href=t.externalVerificationRedirectURL.toString()})}let nj="oauth_callback_failed",nB=new Set(["external_account_not_found",el]),nJ={oauth_access_denied:"You did not grant access to your account."};async function nK(e){try{await e.create({})}catch{}}async function nV(e){let t,i=String(await e.transport.getRedirectUrl());if(await e.authenticateMethod({...e.params,redirectUrl:i,redirectUrlComplete:i},e=>{t=e}),!t)throw new R("OAuth transport did not receive a verification URL.",{code:"oauth_transport_missing_verification_url"});let{callbackUrl:r}=await e.transport.open(new URL(t.toString())),n=function(e){let t=new URL(e).searchParams;if("failed"!==t.get("__clerk_status"))return null;let i=t.get("__clerk_error_code")||nj;if(nB.has(i))return null;let r=nJ[i]?i:nj;return{code:r,message:nJ[r]||"OAuth callback failed."}}(r);if(n)throw await nK(e.resource),new R(n.message,{code:n.code});let s=new URL(r).searchParams.get("rotating_token_nonce");s?await e.resource.reload({rotatingTokenNonce:s}):await e.resource.reload(),await e.clerk.__internal_handleResourceCallback(e.resource,e.callbackParams)}async function nq(e,t){rp.emit("resource:error",{resource:e,error:null}),rp.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await t(),error:null}}catch(t){return rp.emit("resource:error",{resource:e,error:t}),{error:t}}finally{rp.emit("resource:fetch",{resource:e,status:"idle"})}}function nH(){if(!m())return null;try{let e=Intl?.DateTimeFormat?.().resolvedOptions().timeZone;return"string"==typeof e&&e.trim()?e:null}catch{return null}}let nG=()=>{var e;return(e=new tT,{loadZxcvbn:()=>Promise.all([e.import("@zxcvbn-ts/core"),e.import("@zxcvbn-ts/language-common")]).then(([e,t])=>{if(!e||!t)throw Error("Failed to load zxcvbn modules");let{zxcvbnOptions:i,zxcvbn:r}=e,{dictionary:n,adjacencyGraphs:s}=t;return i.setOptions({dictionary:{...n},graphs:s}),r})}).loadZxcvbn};class nQ{static instance;inflight=null;static getInstance(){return nQ.instance||(nQ.instance=new nQ),nQ.instance}async resolve(e,t,i){if("protect_check"===i||!t.protectCheck)return;for(;this.inflight;){if(this.inflight.resourceId===t.id)return this.inflight.promise;await this.inflight.promise.catch(()=>{})}if(!t.protectCheck)return;let r=e.__internal_openProtectCheckModal({resource:t}).finally(()=>{this.inflight=null});this.inflight={resourceId:t.id,promise:r},await r}}let nX=e=>"verified"===e||"expired"===e||"transferable"===e;class nY extends iu{pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;ssoBypassFirstFactors=null;firstFactorVerification=new rX(null);secondFactorVerification=new rX(null);identifier=null;createdSessionId=null;userData=new sa(null);clientTrustState;protectCheck=null;timezone=null;get status(){return this._status}set status(e){let t=this._status;this._status=e,e&&t!==e&&tS.debug("SignIn.status",{id:this.id,from:t,to:e})}__internal_future=new nZ(this);__internal_basePost=async(e,{resolveProtectCheck:t=!0}={})=>(await this._basePost(e),t&&await nQ.getInstance().resolve(nY.clerk,this,e?.action),this);__internal_basePatch=async(e,{resolveProtectCheck:t=!0}={})=>(await this._basePatch(e),t&&await nQ.getInstance().resolve(nY.clerk,this,e?.action),this);__internal_baseGet=this._baseGet.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{tS.debug("SignIn.create",{id:this.id,strategy:"strategy"in e?e.strategy:void 0});let t={...e},i=tq();if(i&&(t.locale=i),void 0===t.timezone){let e=nH();e&&(t.timezone=e)}if(this.shouldRequireCaptcha(e)&&!this.clientBypass()&&!this.shouldBypassCaptchaForAttempt(e)){let e=new id(nY.clerk),i=await e.managedOrInvisible({action:"signin"});if(!i)throw new R("",{code:"captcha_unavailable"});t={...t,...i}}return this._basePost({path:this.pathRoot,body:t})};resetPassword=e=>this._basePost({body:e,action:"reset_password"});prepareFirstFactor=e=>{let t;switch(tS.debug("SignIn.prepareFirstFactor",{id:this.id,strategy:e.strategy}),e.strategy){case"passkey":t={};break;case"email_link":t={emailAddressId:e.emailAddressId,redirectUrl:e.redirectUrl};break;case"email_code":case"reset_password_email_code":t={emailAddressId:e.emailAddressId};break;case"phone_code":t={phoneNumberId:e.phoneNumberId,default:e.default,channel:e.channel};break;case"web3_metamask_signature":case"web3_base_signature":case"web3_coinbase_wallet_signature":case"web3_okx_wallet_signature":case"web3_solana_signature":t={web3WalletId:e.web3WalletId};break;case"reset_password_phone_code":t={phoneNumberId:e.phoneNumberId};break;case"enterprise_sso":t={redirectUrl:e.redirectUrl,actionCompleteRedirectUrl:e.actionCompleteRedirectUrl,oidcPrompt:e.oidcPrompt,enterpriseConnectionId:e.enterpriseConnectionId};break;default:t8("SignIn.prepareFirstFactor",e.strategy)}return this._basePost({body:{...t,strategy:e.strategy},action:"prepare_first_factor",coalesce:!0})};submitProtectCheck=e=>(tS.debug("SignIn.submitProtectCheck",{id:this.id}),this._basePatch({action:"protect_check",body:{proof_token:e.proofToken}}));attemptFirstFactor=e=>{let t;return tS.debug("SignIn.attemptFirstFactor",{id:this.id,strategy:e.strategy}),t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(rH(e.publicKeyCredential))}:{...e},this._basePost({body:{...t,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:t}=rW();return{startEmailLinkFlow:async({emailAddressId:i,redirectUrl:r})=>{this.id||t6("SignIn");let n={strategy:"email_link",emailAddressId:i,redirectUrl:r},s="needs_second_factor"===this.status||"needs_client_trust"===this.status,a=s?"secondFactorVerification":"firstFactorVerification";return s?await this.prepareSecondFactor(n):await this.prepareFirstFactor(n),new Promise((i,r)=>{e(()=>this.reload().then(e=>{nX(e[a].status)&&(t(),i(e))}).catch(e=>{t(),r(e)}))})},cancelEmailLinkFlow:t}};prepareSecondFactor=e=>(tS.debug("SignIn.prepareSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_second_factor",coalesce:!0}));attemptSecondFactor=e=>{let t;return tS.debug("SignIn.attemptSecondFactor",{id:this.id,strategy:e.strategy}),t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(rH(e.publicKeyCredential))}:{...e},this._basePost({body:{...t,strategy:e.strategy},action:"attempt_second_factor"})};authenticateWithRedirectOrPopup=async(e,t)=>{let{strategy:i,redirectUrlComplete:r,identifier:n,oidcPrompt:s,slackTeamIdHint:a,continueSignIn:o,enterpriseConnectionId:l}=e||{},c=nY.clerk.buildUrlWithAuth(e.redirectUrl),d=()=>!!this.protectCheck||"needs_protect_check"===this.status,h=()=>{let{status:e,externalVerificationRedirectURL:t}=this.firstFactorVerification;return"unverified"===e?t:null},u=()=>{throw new R("A verification challenge must be completed before this sign-in can continue.",{code:"protect_check_required"})},p=null,_=!this.id||!o;if(_&&(await this.create({strategy:i,identifier:n,redirectUrl:c,actionCompleteRedirectUrl:r,oidcPrompt:s,slackTeamIdHint:a}),d()&&((p=h())||u())),("enterprise_sso"===i||!_&&void 0!==a)&&(await this._basePost({body:{strategy:i,redirectUrl:c,actionCompleteRedirectUrl:r,oidcPrompt:s,slackTeamIdHint:a,enterpriseConnectionId:l},action:"prepare_first_factor",coalesce:!0}),d())){if(p)return void t(p);u()}let{status:f,externalVerificationRedirectURL:m}=this.firstFactorVerification;"unverified"===f&&m?t(m):ie(f,nY.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>{let t=nY.clerk.__internal_oauthTransport;return t?nV({clerk:nY.clerk,transport:t,resource:this,authenticateMethod:this.authenticateWithRedirectOrPopup,params:e,callbackParams:e.__internal_callbackParams??{}}):this.authenticateWithRedirectOrPopup(e,nY.clerk.__internal_windowNavigate)};authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||t7("popup"),nW(nY.clerk,"signIn",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e.toString()})};authenticateWithWeb3=async e=>{let t,{identifier:i,generateSignature:r,strategy:n="web3_metamask_signature",walletName:s}=e||{},a=n.replace("web3_","").replace("_signature","");"function"!=typeof r&&t7("generateSignature"),"solana"!==a||s||t7("walletName"),await this.create({identifier:i});let o=this.supportedFirstFactors?.find(e=>e.strategy===n);o||t9("SignIn"),await this.prepareFirstFactor(o);let{message:l}=this.firstFactorVerification;l||t9("SignIn");try{t=await r({identifier:i,nonce:l,walletName:s,provider:a})}catch(e){if("coinbase_wallet"===a&&4001===e.code)t=await r({identifier:i,nonce:l,provider:a,walletName:s});else throw e}return this.attemptFirstFactor({signature:t,strategy:n})};authenticateWithMetamask=async()=>{let e=await tY().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tY().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await tY().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tY().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await tY().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tY().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await tY().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tY().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithSolana=async({walletName:e})=>{let t=await tY().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:t,generateSignature:t=>tY().generateSignatureWithSolana({...t,walletName:e}),strategy:"web3_solana_signature",walletName:e})};authenticateWithPasskey=async e=>{let{flow:t}=e||{},i=nY.clerk.__internal_isWebAuthnSupported||nw,r=nY.clerk.__internal_getPublicCredentials||rJ,n=nY.clerk.__internal_isWebAuthnAutofillSupported||nb;if(!i())throw new q("Passkeys are not supported",{code:"passkey_not_supported"});let s="needs_second_factor"===this.status||"needs_client_trust"===this.status,a=(this.supportedSecondFactors||[]).some(e=>"passkey"===e.strategy);if(!t&&s&&a){await this.prepareSecondFactor({strategy:"passkey"});let{nonce:e}=this.secondFactorVerification,t=e?rV(JSON.parse(e)):null;t||ii("get");let{publicKeyCredential:i,error:n}=await r({publicKeyOptions:t,conditionalUI:!1});if(!i)throw n;return this.attemptSecondFactor({publicKeyCredential:i,strategy:"passkey"})}if("autofill"===t||"discoverable"===t)await this.create({strategy:"passkey"});else{let e=this.supportedFirstFactors.find(e=>"passkey"===e.strategy);e||function(){throw Error(`${t2} You need to start a SignIn flow by calling SignIn.create({ strategy: 'passkey' }) first`)}(),await this.prepareFirstFactor(e)}let{nonce:o}=this.firstFactorVerification,l=o?rV(JSON.parse(o)):null;l||ii("get");let c=!1;"autofill"===t&&(c=await n());let{publicKeyCredential:d,error:h}=await r({publicKeyOptions:l,conditionalUI:c});if(!d)throw h;return this.attemptFirstFactor({publicKeyCredential:d,strategy:"passkey"})};validatePassword=(e,t)=>{if(nY.clerk.__internal_environment?.userSettings.passwordSettings)return nN(nG(),{...nY.clerk.__internal_environment?.userSettings.passwordSettings,validatePassword:!0})(e,t)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.supportedIdentifiers=e.supported_identifiers,this.identifier=e.identifier,this.supportedFirstFactors=ef(e.supported_first_factors),this.supportedSecondFactors=ef(e.supported_second_factors),this.ssoBypassFirstFactors=ef(e.sso_bypass_first_factors??null),this.firstFactorVerification=new rX(e.first_factor_verification),this.secondFactorVerification=new rX(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new sa(e.user_data),this.clientTrustState=e.client_trust_state??void 0,this.protectCheck=e.protect_check?{status:e.protect_check.status,token:e.protect_check.token,sdkUrl:e.protect_check.sdk_url,expiresAt:e.protect_check.expires_at,uiHints:e.protect_check.ui_hints}:null,this.timezone=e.timezone??null),rp.emit("resource:update",{resource:this}),this}clientBypass(){return nY.clerk.client?.captchaBypass}shouldRequireCaptcha(e){return"signUpIfMissing"in e&&!!e.signUpIfMissing}shouldBypassCaptchaForAttempt(e){let t=nY.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer&&nY.clerk.client?.signUp?.verifications?.externalAccount?.status==="transferable"){let e=nY.clerk.client.signUp.verifications.externalAccount.strategy;return!!e&&t.some(t=>t===e)}return"strategy"in e&&!!e.strategy&&t.some(t=>t===e.strategy)}__internal_updateFromJSON(e){return this.fromJSON(e)}__internal_toSnapshot(){return{object:"sign_in",id:this.id||"",status:this.status||null,supported_identifiers:this.supportedIdentifiers,supported_first_factors:e_(this.supportedFirstFactors),supported_second_factors:e_(this.supportedSecondFactors),sso_bypass_first_factors:e_(this.ssoBypassFirstFactors)??void 0,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(),timezone:this.timezone,protect_check:this.protectCheck?{status:this.protectCheck.status,token:this.protectCheck.token,sdk_url:this.protectCheck.sdkUrl,...void 0!==this.protectCheck.expiresAt&&{expires_at:this.protectCheck.expiresAt},...void 0!==this.protectCheck.uiHints&&{ui_hints:this.protectCheck.uiHints}}:null}}}class nZ{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(!m())return null;const e=eX("__clerk_status"),t=eX("__clerk_created_session");if(!e||!t)return null;const i="verified"===e&&void 0!==nY.clerk.client&&nY.clerk.client.sessions.some(e=>e.id===t);return{status:e,createdSessionId:t,verifiedFromTheSameClient:i}}};resetPasswordEmailCode={sendCode:this.sendResetPasswordEmailCode.bind(this),verifyCode:this.verifyResetPasswordEmailCode.bind(this),submitPassword:this.submitResetPassword.bind(this)};resetPasswordPhoneCode={sendCode:this.sendResetPasswordPhoneCode.bind(this),verifyCode:this.verifyResetPasswordPhoneCode.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),sendEmailCode:this.sendMFAEmailCode.bind(this),verifyEmailCode:this.verifyMFAEmailCode.bind(this),verifyTOTP:this.verifyTOTP.bind(this),verifyBackupCode:this.verifyBackupCode.bind(this),passkey:this.verifyMFAPasskey.bind(this)};#H=!1;#G;constructor(e){this.#G=e}get id(){return this.#G.id}get identifier(){return this.#G.identifier}get timezone(){return this.#G.timezone}get createdSessionId(){return this.#G.createdSessionId}get userData(){return this.#G.userData}get status(){return this.#G.status||"needs_identifier"}get supportedFirstFactors(){return this.#G.supportedFirstFactors??[]}get supportedSecondFactors(){return this.#G.supportedSecondFactors??[]}get ssoBypassFirstFactors(){return this.#G.ssoBypassFirstFactors??[]}get isTransferable(){return"transferable"===this.#G.firstFactorVerification.status}get existingSession(){if("failed"===this.#G.firstFactorVerification.status&&this.#G.firstFactorVerification.error?.code==="identifier_already_signed_in"&&this.#G.firstFactorVerification.error?.meta?.sessionId)return{sessionId:this.#G.firstFactorVerification.error?.meta?.sessionId}}get firstFactorVerification(){return this.#G.firstFactorVerification}get secondFactorVerification(){return this.#G.secondFactorVerification}get protectCheck(){return this.#G.protectCheck}async submitProtectCheck(e){return nq(this.#G,async()=>{await this.#G.__internal_basePatch({action:"protect_check",body:{proof_token:e.proofToken}})})}get canBeDiscarded(){return this.#H}async sendResetPasswordEmailCode(){if(!this.#G.id)throw Error("Cannot reset password without a sign in.");return nq(this.#G,async()=>{let e=this.#G.supportedFirstFactors?.find(e=>"reset_password_email_code"===e.strategy);if(!e)throw new R("Reset password email code factor not found",{code:"factor_not_found"});let{emailAddressId:t}=e;await this.#G.__internal_basePost({body:{emailAddressId:t,strategy:"reset_password_email_code"},action:"prepare_first_factor",coalesce:!0})})}async verifyResetPasswordEmailCode(e){let{code:t}=e;return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{code:t,strategy:"reset_password_email_code"},action:"attempt_first_factor"})})}async sendResetPasswordPhoneCode(e={}){let{phoneNumber:t}=e;if(!this.#G.id&&!t)throw Error("signIn.resetPasswordPhoneCode.sendCode() cannot be called without a phoneNumber if an existing signIn does not exist.");return nq(this.#G,async()=>{t&&await this._create({identifier:t});let e=this.#G.supportedFirstFactors?.find(e=>"reset_password_phone_code"===e.strategy);if(!e)throw new R("Reset password phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:i}=e;await this.#G.__internal_basePost({body:{phoneNumberId:i,strategy:"reset_password_phone_code"},action:"prepare_first_factor",coalesce:!0})})}async verifyResetPasswordPhoneCode(e){let{code:t}=e;return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{code:t,strategy:"reset_password_phone_code"},action:"attempt_first_factor"})})}async submitResetPassword(e){let{password:t,signOutOfOtherSessions:i=!0}=e;return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{password:t,signOutOfOtherSessions:i},action:"reset_password"})})}shouldRequireCaptcha(e){return!!e.signUpIfMissing}shouldBypassCaptchaForAttempt(e){let t=nY.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer&&nY.clerk.client?.signUp?.verifications?.externalAccount?.status==="transferable"){let e=nY.clerk.client.signUp.verifications.externalAccount.strategy;return!!e&&t.some(t=>t===e)}return!!e.strategy&&t.some(t=>t===e.strategy)}async getCaptchaToken(e={}){if(!this.shouldRequireCaptcha(e)||nY.clerk.client?.captchaBypass||this.shouldBypassCaptchaForAttempt(e))return{captchaToken:void 0,captchaWidgetType:void 0,captchaError:void 0};let t=new id(nY.clerk),i=await t.managedOrInvisible({action:"signin"});if(!i)throw Error("Captcha challenge failed");let{captchaError:r,captchaToken:n,captchaWidgetType:s}=i;return{captchaToken:n,captchaWidgetType:s,captchaError:r}}async _create(e,t){let{captchaToken:i,captchaWidgetType:r,captchaError:n}=await this.getCaptchaToken(e),s=e.timezone??nH(),a={...e,captchaToken:i,captchaWidgetType:r,captchaError:n,locale:tq()||void 0,...null!==s?{timezone:s}:{}};await this.#G.__internal_basePost({path:this.#G.pathRoot,body:a},t)}async create(e){return nq(this.#G,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 nq(this.#G,async()=>{let t=e.identifier||e.emailAddress||e.phoneNumber,i=this.#G.identifier,r=tq(),n=e.timezone??this.#G.timezone??nH();await this.#G.__internal_basePost({path:this.#G.pathRoot,body:{identifier:t||i,password:e.password,...r?{locale:r}:{},...null!==n?{timezone:n}:{}}})})}async sendEmailCode(e={}){let{emailAddress:t,emailAddressId:i}=e;if(!this.#G.id&&i)throw Error("signIn.emailCode.sendCode() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#G.id&&!t)throw Error("signIn.emailCode.sendCode() cannot be called without an emailAddress if an existing signIn does not exist.");return nq(this.#G,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_code",emailAddressId:i});if(!e)throw new R("Email code factor not found",{code:"factor_not_found"});await this.#G.__internal_basePost({body:{emailAddressId:e.emailAddressId,strategy:"email_code"},action:"prepare_first_factor",coalesce:!0})})}async verifyEmailCode(e){let{code:t}=e;return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{code:t,strategy:"email_code"},action:"attempt_first_factor"})})}async sendEmailLink(e){let{emailAddress:t,verificationUrl:i,emailAddressId:r}=e;if(!this.#G.id&&r)throw Error("signIn.emailLink.sendLink() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#G.id&&!t)throw Error("signIn.emailLink.sendLink() cannot be called without an emailAddress if an existing signIn does not exist.");return nq(this.#G,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_link",emailAddressId:r});if(!e)throw new R("Email link factor not found",{code:"factor_not_found"});let n=i;try{new URL(i)}catch{n=window.location.origin+i}await this.#G.__internal_basePost({body:{emailAddressId:e.emailAddressId,redirectUrl:n,strategy:"email_link"},action:"prepare_first_factor",coalesce:!0})})}async waitForEmailLinkVerification(){return nq(this.#G,async()=>{let{run:e,stop:t}=rW();await new Promise((i,r)=>{e(async()=>{try{let e=await this.#G.__internal_baseGet();nX(e.firstFactorVerification.status)&&(t(),i(e))}catch(e){t(),r(e)}})})})}async sendPhoneCode(e={}){let{phoneNumber:t,phoneNumberId:i,channel:r="sms"}=e;if(!this.#G.id&&i)throw Error("signIn.phoneCode.sendCode() cannot be called with an phoneNumberId if an existing signIn does not exist.");if(!this.#G.id&&!t)throw Error("signIn.phoneCode.sendCode() cannot be called without an phoneNumber if an existing signIn does not exist.");return nq(this.#G,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"phone_code",phoneNumberId:i});if(!e)throw new R("Phone code factor not found",{code:"factor_not_found"});await this.#G.__internal_basePost({body:{phoneNumberId:e.phoneNumberId,strategy:"phone_code",channel:r},action:"prepare_first_factor",coalesce:!0})})}async verifyPhoneCode(e){let{code:t}=e;return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_first_factor"})})}async sso(e){let{strategy:t,redirectUrl:i,redirectCallbackUrl:r,popup:n,oidcPrompt:s,slackTeamIdHint:a,enterpriseConnectionId:o,identifier:l}=e;return nq(this.#G,async()=>{let e=i;try{new URL(i)}catch{e=window.location.origin+i}let c={redirectUrl:nY.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:e};if(n){let t=nL(nY.clerk,{redirectCallbackUrl:c.redirectUrl,redirectUrl:e});c.redirectUrl=t.redirectCallbackUrl,c.actionCompleteRedirectUrl=t.redirectUrl}let d=!!this.#G.firstFactorVerification.externalVerificationRedirectURL,h="enterprise_sso"!==t&&d,u=!this.#G.id||h,p=()=>!!this.#G.protectCheck||"needs_protect_check"===this.#G.status,_=()=>{let{status:e,externalVerificationRedirectURL:t}=this.#G.firstFactorVerification;return"unverified"===e?t:null},f=()=>nQ.getInstance().resolve(nY.clerk,this.#G),m=null;if(u&&(await this._create({strategy:t,...c,identifier:l,oidcPrompt:s,slackTeamIdHint:a},{resolveProtectCheck:!1}),p()&&((m=_())||await f())),"enterprise_sso"===t||!u&&void 0!==a){let e=e=>this.#G.__internal_basePost({body:{...c,oidcPrompt:s,slackTeamIdHint:a,enterpriseConnectionId:o,strategy:t},action:"prepare_first_factor",coalesce:!0},e);await e({resolveProtectCheck:!1}),p()&&!m&&(await f(),await e())}let g=m??_();g&&(n?(await n$(nY.clerk,{popup:n,externalVerificationRedirectURL:g}),await this.#G.reload(),await f()):nY.clerk.__internal_windowNavigate(g))})}async web3(e){let{strategy:t}=e,i=t.replace("web3_","").replace("_signature","");return nq(this.#G,async()=>{let r,n,s;switch(i){case"metamask":r=await tY().getMetamaskIdentifier(),n=tY().generateSignatureWithMetamask;break;case"coinbase_wallet":r=await tY().getCoinbaseWalletIdentifier(),n=tY().generateSignatureWithCoinbaseWallet;break;case"base":r=await tY().getBaseIdentifier(),n=tY().generateSignatureWithBase;break;case"okx_wallet":r=await tY().getOKXWalletIdentifier(),n=tY().generateSignatureWithOKXWallet;break;case"solana":if(!e.walletName)throw new R("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});r=await tY().getSolanaIdentifier(e.walletName),n=t=>tY().generateSignatureWithSolana({...t,walletName:e.walletName});break;default:throw Error(`Unsupported Web3 provider: ${i}`)}await this._create({identifier:r});let a=this.#G.supportedFirstFactors?.find(e=>e.strategy===t);if(!a)throw new R("Web3 first factor not found",{code:"factor_not_found"});await this.#G.__internal_basePost({body:{web3WalletId:a.web3WalletId,strategy:t},action:"prepare_first_factor",coalesce:!0});let{message:o}=this.firstFactorVerification;if(!o)throw new R("Web3 nonce not found",{code:"web3_nonce_not_found"});try{s=await n({identifier:r,nonce:o,walletName:e?.walletName,provider:i})}catch(e){if("coinbase_wallet"===i&&4001===e.code)s=await n({identifier:r,nonce:o,provider:i});else throw e}await this.#G.__internal_basePost({body:{signature:s,strategy:t},action:"attempt_first_factor"})})}async passkey(e){let{flow:t}=e||{},i=nY.clerk.__internal_isWebAuthnSupported||nw,r=nY.clerk.__internal_getPublicCredentials||rJ,n=nY.clerk.__internal_isWebAuthnAutofillSupported||nb;if(!i())throw new q("Passkeys are not supported",{code:"passkey_not_supported"});return nq(this.#G,async()=>{if("autofill"===t||"discoverable"===t)await this._create({strategy:"passkey"});else{if(!this.supportedFirstFactors.find(e=>"passkey"===e.strategy))throw new R("Passkey factor not found",{code:"factor_not_found"});await this.#G.__internal_basePost({body:{strategy:"passkey"},action:"prepare_first_factor",coalesce:!0})}let{nonce:e}=this.firstFactorVerification,i=e?rV(JSON.parse(e)):null;if(!i)throw new R("Missing public key options",{code:"missing_public_key_options"});let s=!1;"autofill"===t&&(s=await n());let{publicKeyCredential:a,error:o}=await r({publicKeyOptions:i,conditionalUI:s});if(!a)throw new q(o.message,{code:"passkey_retrieval_failed"});await this.#G.__internal_basePost({body:{publicKeyCredential:JSON.stringify(rH(a)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return nq(this.#G,async()=>{let e=this.#G.supportedSecondFactors?.find(e=>"phone_code"===e.strategy);if(!e)throw new R("Phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:t}=e;await this.#G.__internal_basePost({body:{phoneNumberId:t,strategy:"phone_code"},action:"prepare_second_factor",coalesce:!0})})}async verifyMFAPhoneCode(e){let{code:t}=e;return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_second_factor"})})}async sendMFAEmailCode(){return nq(this.#G,async()=>{let e=this.#G.supportedSecondFactors?.find(e=>"email_code"===e.strategy);if(!e)throw new R("Email code factor not found",{code:"factor_not_found"});let{emailAddressId:t}=e;await this.#G.__internal_basePost({body:{emailAddressId:t,strategy:"email_code"},action:"prepare_second_factor",coalesce:!0})})}async verifyMFAEmailCode(e){let{code:t}=e;return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{code:t,strategy:"email_code"},action:"attempt_second_factor"})})}async verifyTOTP(e){let{code:t}=e;return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{code:t,strategy:"totp"},action:"attempt_second_factor"})})}async verifyBackupCode(e){let{code:t}=e;return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{code:t,strategy:"backup_code"},action:"attempt_second_factor"})})}async verifyMFAPasskey(){let e=nY.clerk.__internal_isWebAuthnSupported||nw,t=nY.clerk.__internal_getPublicCredentials||rJ;if(!e())throw new q("Passkeys are not supported",{code:"passkey_not_supported"});return nq(this.#G,async()=>{if(!this.#G.supportedSecondFactors?.find(e=>"passkey"===e.strategy))throw new R("Passkey factor not found",{code:"factor_not_found"});await this.#G.__internal_basePost({body:{strategy:"passkey"},action:"prepare_second_factor",coalesce:!0});let{nonce:e}=this.#G.secondFactorVerification,i=e?rV(JSON.parse(e)):null;if(!i)throw new R("Missing public key options",{code:"missing_public_key_options"});let{publicKeyCredential:r,error:n}=await t({publicKeyOptions:i,conditionalUI:!1});if(!r)throw new q(n.message,{code:"passkey_retrieval_failed"});await this.#G.__internal_basePost({body:{publicKeyCredential:JSON.stringify(rH(r)),strategy:"passkey"},action:"attempt_second_factor"})})}async ticket(e){let t=e?.ticket??eX("__clerk_ticket");return this.create({strategy:"ticket",ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};if(!this.#G.createdSessionId)throw Error("Cannot finalize sign-in without a created session.");return nq(this.#G,async()=>{nY.clerk.client&&!nY.clerk.client.sessions.some(e=>e.id===this.#G.createdSessionId)&&await nY.clerk.client.reload(),this.#H=!0,await nY.clerk.setActive({session:this.#G.createdSessionId,navigate:t})})}reset(){if(!nY.clerk.client)throw Error("Cannot reset sign-in without a client.");return this.#H=!0,nY.clerk.client.resetSignIn(),Promise.resolve({error:null})}selectFirstFactor({strategy:e,emailAddressId:t,phoneNumberId:i}){if(!this.#G.supportedFirstFactors)return null;if(t){let i=this.#G.supportedFirstFactors.find(i=>i.strategy===e&&i.emailAddressId===t);if(i)return i}if(i){let t=this.#G.supportedFirstFactors.find(t=>t.strategy===e&&t.phoneNumberId===i);if(t)return t}let r=this.#G.supportedFirstFactors.find(t=>t.strategy===e&&t.safeIdentifier===this.#G.identifier);if(r)return r;let n=this.#G.supportedFirstFactors.find(t=>t.strategy===e);return n||null}}function n0(e){let{unsafeMetadata:t}={...e},i=t?"object"==typeof t?JSON.stringify(t):t:"";return{...e,...t?{unsafeMetadata:i}:{}}}class n1 extends iu{pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new rZ(null);username=null;firstName=null;lastName=null;emailAddress=null;phoneNumber=null;web3wallet=null;externalAccount;hasPassword=!1;unsafeMetadata={};protectCheck=null;createdSessionId=null;createdUserId=null;abandonAt=null;legalAcceptedAt=null;locale=null;timezone=null;get status(){return this._status}set status(e){let t=this._status;this._status=e,e&&t!==e&&tS.debug("SignUp.status",{id:this.id,from:t,to:e})}__internal_future=new n5(this);__internal_basePost=async(e,{resolveProtectCheck:t=!0}={})=>(await this._basePost(e),t&&await nQ.getInstance().resolve(n1.clerk,this,e?.action),this);__internal_basePatch=async(e,{resolveProtectCheck:t=!0}={})=>(await this._basePatch(e),t&&await nQ.getInstance().resolve(n1.clerk,this,e?.action),this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{tS.debug("SignUp.create",{id:this.id,strategy:e.strategy});let t={...e};if(!t.locale){let e=tq();e&&(t.locale=e)}if(void 0===t.timezone){let e=nH();e&&(t.timezone=e)}if(!this.clientBypass()&&!this.shouldBypassCaptchaForAttempt(e)){let e=new id(n1.clerk),i=await e.managedOrInvisible({action:"signup"});if(!i)throw new R("",{code:"captcha_unavailable"});t={...t,...i}}return this._basePost({path:this.pathRoot,body:n0(t)})};prepareVerification=e=>(tS.debug("SignUp.prepareVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_verification",coalesce:!0}));attemptVerification=e=>(tS.debug("SignUp.attemptVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_verification"}));submitProtectCheck=e=>(tS.debug("SignUp.submitProtectCheck",{id:this.id}),this._basePatch({action:"protect_check",body:{proof_token:e.proofToken}}));prepareEmailAddressVerification=e=>this.prepareVerification(e||{strategy:"email_code"});attemptEmailAddressVerification=e=>this.attemptVerification({...e,strategy:"email_code"});createEmailLinkFlow=()=>{let{run:e,stop:t}=rW();return{startEmailLinkFlow:async({redirectUrl:i})=>(this.id||t6("SignUp"),await this.prepareEmailAddressVerification({strategy:"email_link",redirectUrl:i}),new Promise((i,r)=>{e(()=>this.reload().then(e=>{let r=e.verifications.emailAddress.status;("verified"===r||"expired"===r)&&(t(),i(e))}).catch(e=>{t(),r(e)}))})),cancelEmailLinkFlow:t}};preparePhoneNumberVerification=e=>this.prepareVerification(e||{strategy:"phone_code"});attemptPhoneNumberVerification=e=>this.attemptVerification({...e,strategy:"phone_code"});prepareWeb3WalletVerification=e=>this.prepareVerification({strategy:"web3_metamask_signature",...e});attemptWeb3WalletVerification=async e=>{let{signature:t,strategy:i="web3_metamask_signature"}=e;return this.attemptVerification({signature:t,strategy:i})};authenticateWithWeb3=async e=>{let t,{generateSignature:i,identifier:r,unsafeMetadata:n,strategy:s="web3_metamask_signature",legalAccepted:a,walletName:o}=e||{},l=s.replace("web3_","").replace("_signature","");"function"!=typeof i&&t7("generateSignature");let c=r||this.web3wallet;await this.create({web3Wallet:c,unsafeMetadata:n,legalAccepted:a}),await this.prepareWeb3WalletVerification({strategy:s});let{message:d}=this.verifications.web3Wallet;d||t9("SignUp");try{t=await i({identifier:r,nonce:d,provider:l,walletName:o})}catch(e){if("coinbase_wallet"===l&&4001===e.code)t=await i({identifier:r,nonce:d,provider:l});else throw e}return this.attemptWeb3WalletVerification({signature:t,strategy:s})};authenticateWithMetamask=async e=>{let t=await tY().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tY().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let t=await tY().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tY().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let t=await tY().getBaseIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tY().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let t=await tY().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tY().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithSolana=async({walletName:e,unsafeMetadata:t,legalAccepted:i})=>{let r=await tY().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:r,generateSignature:t=>tY().generateSignatureWithSolana({...t,walletName:e}),unsafeMetadata:t,strategy:"web3_solana_signature",legalAccepted:i,walletName:e})};authenticateWithRedirectOrPopup=async(e,t)=>{let{redirectUrl:i,redirectUrlComplete:r,strategy:n,continueSignUp:s=!1,unsafeMetadata:a,emailAddress:o,legalAccepted:l,oidcPrompt:c,slackTeamIdHint:d,enterpriseConnectionId:h}=e,u=n1.clerk.buildUrlWithAuth(i),p=()=>{let e={strategy:n,redirectUrl:u,actionCompleteRedirectUrl:r,unsafeMetadata:a,emailAddress:o,legalAccepted:l,oidcPrompt:c,slackTeamIdHint:d,enterpriseConnectionId:h};return s&&this.id?this.update(e):this.create(e)},{verifications:_}=await p().catch(async e=>{if($(e)&&H(e))return await n1.clerk.__internal_environment.reload(),p();throw e}),{externalAccount:f}=_,{status:m,externalVerificationRedirectURL:g}=f;"unverified"===m&&g?t(g):ie(m,n1.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>{let t=n1.clerk.__internal_oauthTransport;return t?nV({clerk:n1.clerk,transport:t,resource:this,authenticateMethod:this.authenticateWithRedirectOrPopup,params:e,callbackParams:e.__internal_callbackParams??{}}):this.authenticateWithRedirectOrPopup(e,n1.clerk.__internal_windowNavigate)};authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||t7("popup"),nW(n1.clerk,"signUp",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e instanceof URL?e.toString():e})};update=e=>this._basePatch({body:n0(e)});upsert=e=>this.id?this.update(e):this.create(e);validatePassword=(e,t)=>{if(n1.clerk.__internal_environment?.userSettings.passwordSettings)return nN(nG(),{...n1.clerk.__internal_environment?.userSettings.passwordSettings,validatePassword:!0})(e,t)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.requiredFields=e.required_fields,this.optionalFields=e.optional_fields,this.missingFields=e.missing_fields,this.unverifiedFields=e.unverified_fields,this.verifications=new rZ(e.verifications),this.protectCheck=e.protect_check?{status:e.protect_check.status,token:e.protect_check.token,sdkUrl:e.protect_check.sdk_url,expiresAt:e.protect_check.expires_at,uiHints:e.protect_check.ui_hints}:null,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,this.timezone=e.timezone??null),rp.emit("resource:update",{resource:this}),this}__internal_updateFromJSON(e){return this.fromJSON(e)}__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(),protect_check:this.protectCheck?{status:this.protectCheck.status,token:this.protectCheck.token,sdk_url:this.protectCheck.sdkUrl,...void 0!==this.protectCheck.expiresAt&&{expires_at:this.protectCheck.expiresAt},...void 0!==this.protectCheck.uiHints&&{ui_hints:this.protectCheck.uiHints}}:null,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,timezone:this.timezone,external_account:this.externalAccount,external_account_strategy:this.externalAccount?.strategy}}clientBypass(){return n1.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){let t=n1.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer){let e=n1.clerk.client.signIn.firstFactorVerification.strategy;if(t.some(t=>t===e)||n2(e))return!0}return!!(e.strategy&&t.some(t=>t===e.strategy))}__experimental_getEnterpriseConnections=()=>iu._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new n6(e)))}let n3=new Set(["email_link","email_code","phone_code"]);function n2(e){return!!e&&(n3.has(e)||e.startsWith("web3_"))}class n4{#G;sendEmailCode;verifyEmailCode;sendEmailLink;waitForEmailLinkVerification;sendPhoneCode;verifyPhoneCode;constructor(e,t){this.#G=e,this.sendEmailCode=t.sendEmailCode,this.verifyEmailCode=t.verifyEmailCode,this.sendEmailLink=t.sendEmailLink,this.waitForEmailLinkVerification=t.waitForEmailLinkVerification,this.sendPhoneCode=t.sendPhoneCode,this.verifyPhoneCode=t.verifyPhoneCode}get emailAddress(){return this.#G.verifications.emailAddress}get phoneNumber(){return this.#G.verifications.phoneNumber}get web3Wallet(){return this.#G.verifications.web3Wallet}get externalAccount(){return this.#G.verifications.externalAccount}get emailLinkVerification(){if(!m())return null;let e=eX("__clerk_status"),t=eX("__clerk_created_session");if(!e||!t)return null;let i="verified"===e&&void 0!==n1.clerk.client&&n1.clerk.client.sessions.some(e=>e.id===t);return{status:e,createdSessionId:t,verifiedFromTheSameClient:i}}}class n5{verifications;#H=!1;#G;constructor(e){this.#G=e,this.verifications=new n4(this.#G,{sendEmailCode:this.sendEmailCode.bind(this),verifyEmailCode:this.verifyEmailCode.bind(this),sendEmailLink:this.sendEmailLink.bind(this),waitForEmailLinkVerification:this.waitForEmailLinkVerification.bind(this),sendPhoneCode:this.sendPhoneCode.bind(this),verifyPhoneCode:this.verifyPhoneCode.bind(this)})}get id(){return this.#G.id}get requiredFields(){return this.#G.requiredFields}get optionalFields(){return this.#G.optionalFields}get missingFields(){return this.#G.missingFields}get status(){return this.#G.status||"missing_requirements"}get username(){return this.#G.username}get firstName(){return this.#G.firstName}get lastName(){return this.#G.lastName}get emailAddress(){return this.#G.emailAddress}get phoneNumber(){return this.#G.phoneNumber}get web3Wallet(){return this.#G.web3wallet}get hasPassword(){return this.#G.hasPassword}get unsafeMetadata(){return this.#G.unsafeMetadata}get createdSessionId(){return this.#G.createdSessionId}get createdUserId(){return this.#G.createdUserId}get abandonAt(){return this.#G.abandonAt}get legalAcceptedAt(){return this.#G.legalAcceptedAt}get locale(){return this.#G.locale}get timezone(){return this.#G.timezone}get unverifiedFields(){return this.#G.unverifiedFields}get protectCheck(){return this.#G.protectCheck}get isTransferable(){return"transferable"===this.#G.verifications.externalAccount.status&&this.#G.verifications.externalAccount.error?.code===el}get existingSession(){if(("failed"===this.#G.verifications.externalAccount.status||"unverified"===this.#G.verifications.externalAccount.status)&&this.#G.verifications.externalAccount.error?.code==="identifier_already_signed_in"&&this.#G.verifications.externalAccount.error?.meta?.sessionId)return{sessionId:this.#G.verifications.externalAccount.error?.meta?.sessionId}}get canBeDiscarded(){return this.#H}shouldBypassCaptchaForAttempt(e){let t=n1.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer){let e=n1.clerk.client.signIn.firstFactorVerification.strategy;if(t.some(t=>t===e)||n2(e))return!0}return!!(e.strategy&&t.some(t=>t===e.strategy))}async getCaptchaToken(e={}){if(n1.clerk.client?.captchaBypass||this.shouldBypassCaptchaForAttempt(e))return{captchaToken:void 0,captchaWidgetType:void 0,captchaError:void 0};let t=new id(n1.clerk),i=await t.managedOrInvisible({action:"signup"});if(!i)throw Error("Captcha challenge failed");let{captchaError:r,captchaToken:n,captchaWidgetType:s}=i;return{captchaToken:n,captchaWidgetType:s,captchaError:r}}async _create(e){let{captchaToken:t,captchaWidgetType:i,captchaError:r}=await this.getCaptchaToken(e),n=e.timezone??nH(),s={transfer:e.transfer,captchaToken:t,captchaWidgetType:i,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?n0(e.unsafeMetadata):void 0,locale:e.locale??tq(),...null!==n?{timezone:n}:{}};await this.#G.__internal_basePost({path:this.#G.pathRoot,body:s})}async create(e){return nq(this.#G,async()=>{await this._create(e)})}async update(e){return nq(this.#G,async()=>{let t={...e,unsafeMetadata:e.unsafeMetadata?n0(e.unsafeMetadata):void 0};await this.#G.__internal_basePatch({body:t})})}async password(e){return nq(this.#G,async()=>{let{captchaToken:t,captchaWidgetType:i,captchaError:r}=await this.getCaptchaToken(),n={strategy:"password",captchaToken:t,captchaWidgetType:i,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?n0(e.unsafeMetadata):void 0};if(this.#G.id)await this.#G.__internal_basePatch({body:n});else{n.locale=e.locale??tq();let t=nH();null!==t&&(n.timezone=t),await this.#G.__internal_basePost({path:this.#G.pathRoot,body:n})}})}async sendEmailCode(){return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification",coalesce:!0})})}async verifyEmailCode(e){let{code:t}=e;return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{strategy:"email_code",code:t},action:"attempt_verification"})})}async sendPhoneCode(e){let{channel:t="sms"}=e||{};return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{strategy:"phone_code",channel:t},action:"prepare_verification",coalesce:!0})})}async verifyPhoneCode(e){let{code:t}=e;return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{strategy:"phone_code",code:t},action:"attempt_verification"})})}async sendEmailLink(e){let{verificationUrl:t}=e;return nq(this.#G,async()=>{let e=t;try{new URL(t)}catch{e=window.location.origin+t}await this.#G.__internal_basePost({body:{strategy:"email_link",redirectUrl:e},action:"prepare_verification",coalesce:!0})})}async waitForEmailLinkVerification(){return nq(this.#G,async()=>{let{run:e,stop:t}=rW();await new Promise((i,r)=>{e(()=>this.#G.reload().then(e=>{let r=e.verifications.emailAddress.status;("verified"===r||"expired"===r)&&(t(),i(e))}).catch(e=>{t(),r(e)}))})})}async sso(e){let{strategy:t,redirectUrl:i,redirectCallbackUrl:r,unsafeMetadata:n,legalAccepted:s,oidcPrompt:a,slackTeamIdHint:o,enterpriseConnectionId:l,emailAddress:c,popup:d,locale:h}=e;return nq(this.#G,async()=>{let{captchaToken:e,captchaWidgetType:u,captchaError:p}=await this.getCaptchaToken({strategy:t}),_=i;try{new URL(i)}catch{_=window.location.origin+i}let f={redirectUrl:n1.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:_};if(d){let e=nL(n1.clerk,{redirectCallbackUrl:f.redirectUrl,redirectUrl:_});f.redirectUrl=e.redirectCallbackUrl,f.actionCompleteRedirectUrl=e.redirectUrl}let m=()=>{let i={strategy:t,...f,unsafeMetadata:n,legalAccepted:s,oidcPrompt:a,slackTeamIdHint:o,enterpriseConnectionId:l,emailAddress:c,captchaToken:e,captchaWidgetType:u,captchaError:p,locale:h};if(this.#G.id)return this.#G.__internal_basePatch({body:i},{resolveProtectCheck:!1});i.locale=h??tq();let r=nH();return null!==r&&(i.timezone=r),this.#G.__internal_basePost({path:this.#G.pathRoot,body:i},{resolveProtectCheck:!1})};await m().catch(async e=>{if($(e)&&H(e))return await n1.clerk.__internal_environment.reload(),m();throw e});let g=()=>{let{status:e,externalVerificationRedirectURL:t}=this.#G.verifications.externalAccount;return"unverified"===e?t:null},y=()=>nQ.getInstance().resolve(n1.clerk,this.#G);this.#G.protectCheck&&!g()&&await y();let w=g();w&&(d?(await n$(n1.clerk,{popup:d,externalVerificationRedirectURL:w}),await this.#G.reload(),await y()):n1.clerk.__internal_windowNavigate(w))})}async web3(e){let{strategy:t,unsafeMetadata:i,legalAccepted:r,firstName:n,lastName:s,locale:a}=e,o=t.replace("web3_","").replace("_signature","");return nq(this.#G,async()=>{let e,l,c;switch(o){case"metamask":e=await tY().getMetamaskIdentifier(),l=tY().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await tY().getCoinbaseWalletIdentifier(),l=tY().generateSignatureWithCoinbaseWallet;break;case"base":e=await tY().getBaseIdentifier(),l=tY().generateSignatureWithBase;break;case"okx_wallet":e=await tY().getOKXWalletIdentifier(),l=tY().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${o}`)}let d=e||this.#G.web3wallet;await this._create({web3Wallet:d,unsafeMetadata:i,legalAccepted:r,firstName:n,lastName:s,locale:a}),await this.#G.__internal_basePost({body:{strategy:t},action:"prepare_verification",coalesce:!0});let{message:h}=this.#G.verifications.web3Wallet;h||t9("SignUp");try{c=await l({identifier:e,nonce:h})}catch(t){if("coinbase_wallet"===o&&4001===t.code)c=await l({identifier:e,nonce:h});else throw t}await this.#G.__internal_basePost({body:{signature:c,strategy:t},action:"attempt_verification"})})}async submitProtectCheck(e){return nq(this.#G,async()=>{await this.#G.__internal_basePatch({action:"protect_check",body:{proof_token:e.proofToken}})})}async ticket(e){let t=e?.ticket??eX("__clerk_ticket");return this.create({...e,strategy:"ticket",ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};return nq(this.#G,async()=>{if(!this.#G.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#H=!0,await n1.clerk.setActive({session:this.#G.createdSessionId,navigate:t})})}reset(){if(!n1.clerk.client)throw Error("Cannot reset sign-up without a client.");return this.#H=!0,n1.clerk.client.resetSignUp(),Promise.resolve({error:null})}}class n6 extends iu{id;name;provider;logoPublicUrl=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.provider=e.provider,this.logoPublicUrl=e.logo_public_url??null),this}}class n8 extends iu{pathRoot="tokens";jwt;static async create(e,t={},i={}){return new n8(await iu._fetch({method:"POST",path:e,body:t,search:i}),e)}constructor(e,t){super(),t&&(this.pathRoot=t),e?.jwt&&(this.jwt=tV(e.jwt))}getRawString=()=>this.jwt?.claims.__raw||"";fromJSON(e){return e&&(this.jwt=tV(e.jwt)),this}__internal_toSnapshot(){return{object:"token",id:this.id||"",jwt:this.getRawString()}}}class n9 extends iu{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=tE(e.updated_at),this.createdAt=tE(e.created_at)),this}}var n7=Object.prototype.hasOwnProperty;function se(e,t,i){for(i of e.keys())if(st(i,t))return i}function st(e,t){var i,r,n;if(e===t)return!0;if(e&&t&&(i=e.constructor)===t.constructor){if(i===Date)return e.getTime()===t.getTime();if(i===RegExp)return e.toString()===t.toString();if(i===Array){if((r=e.length)===t.length)for(;r--&&st(e[r],t[r]););return -1===r}if(i===Set){if(e.size!==t.size)return!1;for(r of e)if((n=r)&&"object"==typeof n&&!(n=se(t,n))||!t.has(n))return!1;return!0}if(i===Map){if(e.size!==t.size)return!1;for(r of e)if((n=r[0])&&"object"==typeof n&&!(n=se(t,n))||!st(r[1],t.get(n)))return!1;return!0}if(i===ArrayBuffer)e=new Uint8Array(e),t=new Uint8Array(t);else if(i===DataView){if((r=e.byteLength)===t.byteLength)for(;r--&&e.getInt8(r)===t.getInt8(r););return -1===r}if(ArrayBuffer.isView(e)){if((r=e.byteLength)===t.byteLength)for(;r--&&e[r]===t[r];);return -1===r}if(!i||"object"==typeof e){for(i in r=0,e)if(n7.call(e,i)&&++r&&!n7.call(t,i)||!(i in t)||!st(e[i],t[i]))return!1;return Object.keys(t).length===r}}return e!=e&&t!=t}function si(e){if("object"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}class sr extends iu{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=tE(e.updated_at),this.createdAt=tE(e.created_at)),this}}class sn extends iu{advisory=null;form={name:"",slug:"",logo:null,blurHash:null};constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(e.advisory&&(this.advisory=this.withDefault(e.advisory,this.advisory??null)),e.form&&(this.form.name=this.withDefault(e.form.name,this.form.name),this.form.slug=this.withDefault(e.form.slug,this.form.slug),this.form.logo=this.withDefault(e.form.logo,this.form.logo),this.form.blurHash=this.withDefault(e.form.blur_hash,this.form.blurHash))),this}static async retrieve(){return await iu._fetch({path:"/me/organization_creation_defaults",method:"GET"}).then(e=>new sn(e?.response))}__internal_toSnapshot(){return{advisory:this.advisory?{code:this.advisory.code,meta:this.advisory.meta,severity:this.advisory.severity}:null,form:{name:this.form.name,slug:this.form.slug,logo:this.form.logo,blur_hash:this.form.blurHash}}}}class ss extends iu{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;timezone=null;cachedSessionsWithActivities=null;static isUserResource(e){return!!e&&e instanceof ss}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case rL:return this.primaryEmailAddressId===e.id;case nS:return this.primaryPhoneNumberId===e.id;case sd:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:t}=e||{};return new rL({email_address:t},this.path()+"/email_addresses/").create()};createPasskey=()=>nk.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:t}=e||{};return new nS({phone_number:t},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:t}=e||{};return new sd({web3_wallet:t},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:t,redirectUrl:i,additionalScopes:r,enterpriseConnectionId:n,oidcPrompt:s,oidcLoginHint:a}=e||{};return new no((await iu._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:t,redirect_url:i,additional_scope:r,enterprise_connection_id:n,oidc_prompt:s,oidc_login_hint:a}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new n9((await iu._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new n9((await iu._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new rN((await iu._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new sr((await iu._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);__experimental_getBiometricCredentials=()=>rl.list();__experimental_prepareBiometricCredential=e=>rl.prepare(e);__experimental_attemptBiometricCredential=e=>rl.attempt(e);__experimental_revokeBiometricCredential=e=>rl.revoke(e);update=async e=>{var t;let{unsafeMetadata:i,...r}=e,n=void 0!==i,s=Object.keys(r).length>0;if(!n)return this._basePatch({body:n0(e)});((t=iu.clerk.publishableKey).startsWith("test_")||t.startsWith("pk_test_"))&&console.warn('Clerk - DEPRECATION WARNING: "user.update({ unsafeMetadata })" is deprecated and will be removed in the next major release.\nUse user.updateMetadata({ unsafeMetadata }) for partial updates (deep merge) instead.'),s?await this._basePatch({body:n0(r)}):await this.reload();let a=function e(t,i){if(null===i)return null;if(!si(t)||!si(i))return i;let r={};for(let n of Object.keys(i)){let s=t[n],a=i[n];if(!(n in t)){r[n]=a;continue}if(si(s)&&si(a)){let t=e(s,a);if(si(t)&&0===Object.keys(t).length)continue;r[n]=t}else st(s,a)||(r[n]=a)}for(let e of Object.keys(t))e in i||(r[e]=null);return r}(this.unsafeMetadata,i);return null!==a&&"object"==typeof a&&0===Object.keys(a).length?this:this.updateMetadata({unsafeMetadata:a})};updateMetadata=e=>this._basePatch({path:`${this.path()}/metadata`,body:n0(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=>(rp.emit(rd,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await nF.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:t}=e||{};return null===t?nd.delete(`${this.path()}/profile_image`):nd.create(`${this.path()}/profile_image`,{file:t})};getOrganizationInvitations=e=>so.retrieve(e);getOrganizationSuggestions=e=>ny.retrieve(e);getOrganizationMemberships=e=>ng.retrieve(e);getOrganizationCreationDefaults=()=>sn.retrieve();leaveOrganization=async e=>new rN((await iu._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);getEnterpriseConnections=async e=>{let{withOrganizationAccountLinking:t}=e||{};return((await iu._fetch({path:"/me/enterprise_connections",method:"GET",...void 0!==t?{search:{with_organization_account_linking:String(t)}}:{}}))?.response||[]).map(e=>new r7(e))};initializePaymentMethod=e=>i5(e);addPaymentMethod=e=>i6(e);getPaymentMethods=e=>i8(e);get verifiedExternalAccounts(){return this.externalAccounts.filter(e=>e.verification?.status=="verified")}get unverifiedExternalAccounts(){return this.externalAccounts.filter(e=>e.verification?.status!="verified")}get verifiedWeb3Wallets(){return this.web3Wallets.filter(e=>e.verification?.status=="verified")}get hasVerifiedEmailAddress(){return this.emailAddresses.filter(e=>"verified"===e.verification.status).length>0}get hasVerifiedPhoneNumber(){return this.phoneNumbers.filter(e=>"verified"===e.verification.status).length>0}fromJSON(e){return e&&(this.id=e.id,this.externalId=e.external_id||null,this.firstName=e.first_name||null,this.lastName=e.last_name||null,(this.firstName||this.lastName)&&(this.fullName=(({firstName:e,lastName:t,name:i})=>i||[e,t].join(" ").trim()||"")({firstName:this.firstName,lastName:this.lastName})),this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.username=e.username||null,this.passwordEnabled=e.password_enabled||!1,this.emailAddresses=(e.email_addresses||[]).map(e=>new rL(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 nS(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 sd(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 no(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new nk(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new ng(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new r1(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,this.timezone=e.timezone??null,e.last_sign_in_at&&(this.lastSignInAt=tE(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=tE(e.legal_accepted_at)),this.updatedAt=tE(e.updated_at||void 0),this.createdAt=tE(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,timezone:this.timezone}}}class sa{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 so extends iu{id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await iu._fetch({path:"/me/organization_invitations",method:"GET",search:iN(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new so(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=tE(e.created_at),this.updatedAt=tE(e.updated_at)),this}}let sl={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 sc extends iu{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:{...sl,name:"phone_number"},username:{...sl,name:"username"},web3_wallet:{...sl,name:"web3_wallet"},first_name:{...sl,name:"first_name"},last_name:{...sl,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:{...sl,name:"authenticator_app"},backup_code:{...sl,name:"backup_code"},passkey:{...sl,name:"passkey"}};attackProtection={enumeration_protection:{enabled:!1}};enterpriseSSO={enabled:!1,self_serve_sso:!1,self_serve_directory_sync:!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,mfa:{required:!1}};social={};usernameSettings={};get authenticatableSocialStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled&&e.authenticatable).map(([,e])=>e.strategy).sort():[]}get enabledFirstFactorIdentifiers(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&!e.startsWith("web3")).map(([e])=>e):[]}get socialProviderStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled).map(([,e])=>e.strategy).sort():[]}get web3FirstFactors(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&e.startsWith("web3")).map(([,e])=>e.first_factors).flat():[]}get alternativePhoneCodeChannels(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&"phone_number"===e).map(([,e])=>e?.channels?.filter(e=>"sms"!==e)||[]).flat():[]}constructor(e=null){super(),this.fromJSON(e)}get instanceIsPasswordBased(){return!!this.attributes?.password?.enabled}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.attackProtection={enumeration_protection:{enabled:e.attack_protection?.enumeration_protection?.enabled??this.attackProtection.enumeration_protection.enabled}},this.enterpriseSSO={...this.withDefault(e.enterprise_sso,this.enterpriseSSO),self_serve_directory_sync:e.enterprise_sso?.self_serve_directory_sync??!1},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,attack_protection:this.attackProtection,attributes:this.attributes,passkey_settings:this.passkeySettings,password_settings:this.passwordSettings,sign_in:this.signIn,sign_up:this.signUp,social:this.social}}}class sd extends iu{id;web3Wallet="";verification;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}create(){return this._basePost({body:{web3_wallet:this.web3Wallet}})}prepareVerification=e=>this._basePost({action:"prepare_verification",coalesce:!0,body:{...e}});attemptVerification=e=>{let{signature:t}=e;return this._basePost({action:"attempt_verification",body:{signature:t}})};destroy(){return this._baseDelete()}toString(){return this.web3Wallet}fromJSON(e){return e&&(this.id=e.id,this.web3Wallet=e.web3_wallet,this.verification=new rX(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}class sh extends iu{pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=tE(e.updated_at),this.createdAt=tE(e.created_at),rp.emit("resource:update",{resource:this})),this}async join(e){return nq(this,async()=>{await sh.join(e)})}static async join(e){return new sh(await iu._fetch({path:"/waitlist",method:"POST",body:e}))}}function su(e,t){var i,r;return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||(i=t,r=e,i.organizationMemberships.length!==r.organizationMemberships.length||i.organizationMemberships[0]?.updatedAt!==r.organizationMemberships[0]?.updatedAt)}function sp(e,t){return!function(e,t){if(!e&&t||e&&!t)return!0;if(!e&&e===t)return!1;if(!e||!t)return!0;try{if(rz.isClientResource(e))return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.sessions.length!==t.sessions.length;if(nz.isSessionResource(e)){var i,r;return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.lastActiveToken?.jwt?.claims?.__raw!==t.lastActiveToken?.jwt?.claims?.__raw||function(e,t){if(e.lastActiveOrganizationId!==t.lastActiveOrganizationId)return!0;let i=e.user?.organizationMemberships?.find(t=>t.organization.id===e.lastActiveOrganizationId),r=t.user?.organizationMemberships?.find(t=>t.organization.id===e.lastActiveOrganizationId);return i?.permissions?.length!==r?.permissions?.length}(e,t)||(i=e,r=t,!!i.user!=!!r.user||!!i.user&&!!r.user&&su(i.user,r.user))}if(ss.isUserResource(e))return su(e,t)}catch{}return!0}(e,t)?e:t}let s_="__clerk_db_jwt";function sf(e,t){let i=new URL(e),r=i.searchParams.get(s_);i.searchParams.delete(s_);let n=r||t;return n&&i.searchParams.set(s_,n),i}let sm=e=>{let t=new URL(e);return t.searchParams.delete(s_),t},sg=e=>{let t=new URL(e);return t.searchParams.delete("__dev_session"),t.hash=decodeURI(t.hash).replace(/__clerk_db_jwt\[(.*)\]/,""),t.href.endsWith("#")&&(t.hash=""),t};function sy(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)"__proto__"!==r&&(e[r]=i[r])}return e}var sw=function e(t,i){function r(e,r,n){if("u">typeof document){"number"==typeof(n=sy({},i,n)).expires&&(n.expires=new Date(Date.now()+864e5*n.expires)),n.expires&&(n.expires=n.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var s="";for(var a in n)n[a]&&(s+="; "+a,!0!==n[a]&&(s+="="+n[a].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+s}}return Object.create({set:r,get:function(e){if("u">typeof document&&(!arguments.length||e)){for(var i=document.cookie?document.cookie.split("; "):[],r={},n=0;n<i.length;n++){var s=i[n].split("="),a=s.slice(1).join("=");try{var o=decodeURIComponent(s[0]);if(o in r||(r[o]=t.read(a,o)),e===o)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",sy({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,sy({},this.attributes,t))},withConverter:function(t){return e(sy({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(i)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});function sb(e){return{get:()=>sw.get(e),set(t,i={}){sw.set(e,t,i)},remove(t){sw.remove(e,t)}}}let sv=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function sk(e,t){let i=function(e){try{return new Date(e||new Date)}catch{return new Date}}(e);return i.setFullYear(i.getFullYear()+t),i}let sS=sb("__clerk_test_etld"),sI=[".lovable.app",".lovableproject.com",".webcontainer-api.io",".vusercontent.net",".v0.dev",".v0.app",".lp.dev",".replit.dev"];function sC(){try{return sI.some(e=>window.location.hostname.endsWith(e))}catch{return!1}}let sU="__client_uat",sA="__session",sP=e=>{let t=e.usePartitionedCookies(),i=t||tG()||sC()?"None":"Lax",r=sv(i);return{sameSite:i,secure:r,partitioned:t&&r}};async function sT(e){let t;try{t=await eA(e)}catch(o){var r;r=`Suffixed cookie failed due to ${o.message} (secure-context: ${window.isSecureContext}, url: ${window.location.href})`,ex.has(r)||(console.log(r),ex.add(r));let{default:n}=await Promise.all([i.e(545),i.e(811)]).then(i.t.bind(i,3515,23)),{default:s}=await Promise.all([i.e(545),i.e(811)]).then(i.t.bind(i,5662,23)),a=n(e);t=s.stringify(a).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}return t}let sO=e=>{let t=e.usePartitionedCookies(),i=t||tG()||sC()?"None":"Lax",r=sv(i);return{sameSite:i,secure:r,partitioned:t&&r}},sE={sameSite:"None",secure:!0,partitioned:!0};class sx{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,t,i,r){let n=await sT(e.publishableKey),s=new sx(e,t,n,i,r);return await s.setup(),s}constructor(e,t,i,r,n){this.clerk=e,this.instanceType=r,this.clerkEventBus=n,rp.on(rc,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),rp.on(rd,()=>this.handleSignOut()),rp.on(rh,()=>{this.devBrowser.refreshCookies(),this.refreshSessionToken({updateCookieImmediately:!0}),this.setClientUatCookieForDevelopmentInstances()}),this.refreshTokenOnFocus(),this.startPollingForToken();const a={usePartitionedCookies:()=>na.getInstance().partitionedCookies};this.clientUat=((e,t)=>{let i=sb(sU),r=sb(eP(sU,e));return{set:e=>{let n=sk(Date.now(),1),a=t.usePartitionedCookies(),o=a||tG()||sC()?"None":"Strict",l=sv(o),c=a&&l,d=function(e=window.location.hostname,t=sS,i){if(s)return s;if(["localhost","127.0.0.1","0.0.0.0"].includes(e))return e;let r=e.split(".");if(1===r.length)return e;for(let e=r.length-2;e>=0;e--){let n=r.slice(e).join(".");if(t.set("1",{...i,domain:n}),"1"===t.get())return t.remove({...i,domain:n}),s=n,n;t.remove({...i,domain:n})}return s=e,e}(void 0,void 0,{sameSite:o,secure:l}),h="0";if(e&&e.updatedAt&&e.signedInSessions.length>0&&(h=Math.floor(e.updatedAt.getTime()/1e3).toString()),r.remove(),i.remove(),c)for(let e of[{domain:d,sameSite:"Strict",secure:sv("Strict"),partitioned:!1},{domain:d,sameSite:"None",secure:sv("None"),partitioned:!1}])r.remove(e),i.remove(e);r.set(h,{domain:d,expires:n,partitioned:c,sameSite:o,secure:l}),i.set(h,{domain:d,expires:n,partitioned:c,sameSite:o,secure:l})},get:()=>parseInt(r.get()||i.get()||"0",10)}})(i,a),this.sessionCookie=((e,t)=>{let i=sb(sA),r=sb(eP(sA,e)),n=()=>{for(let e of[{sameSite:"Lax",secure:sv("Lax"),partitioned:!1},{sameSite:"None",secure:sv("None"),partitioned:!1}])i.remove(e),r.remove(e)};return{set:e=>{let s=sk(Date.now(),1),{sameSite:a,secure:o,partitioned:l}=sP(t);l&&n(),i.set(e,{expires:s,sameSite:a,secure:o,partitioned:l}),r.set(e,{expires:s,sameSite:a,secure:o,partitioned:l})},remove:()=>{let e=sP(t);i.remove(e),r.remove(e),e.partitioned&&n()},get:()=>r.get()||i.get()}})(i,a),this.activeCookie=(()=>{let e=sb("clerk_active_context"),t={secure:sv("None")};return{set:i=>{e.set(i,t)},get:()=>e.get(),remove:()=>e.remove(t)}})(),this.devBrowser=function({cookieSuffix:e,frontendApi:t,fapiClient:i,cookieOptions:r}){let n,s,a,o,l=(s=sb(s_),a=sb(eP(s_,e)),o=()=>{let e=sO(r);for(let t of[a,s])t.remove(e),t.remove(),t.remove(sE)},{get:()=>a.get()||s.get(),set:e=>{let t=sk(Date.now(),1),{sameSite:i,secure:n,partitioned:l}=sO(r);o(),a.set(e,{expires:t,sameSite:i,secure:n,partitioned:l}),s.set(e,{expires:t,sameSite:i,secure:n,partitioned:l})},remove:()=>o()});function c(){return n||l.get()}function d(e){n=e,l.set(e)}function h(){n=void 0,l.remove()}return{clear:function(){h()},setup:async function e(){var e;let r,s;if(!eD(t))return;i.onBeforeRequest(e=>{let t=c();t&&e?.url&&(e.url=sf(e.url,t))}),i.onAfterResponse((e,t)=>{let i=t?.headers?.get("Clerk-Db-Jwt");i&&d(i)});let a=(r=(e=new URL(window.location.href)).searchParams.get("__clerk_db_jwt")||"",(s=sm(sg(e))).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",s),r);if(a)return void d(a);let o=l.get();if(o){n=o;return}let h=i.buildUrl({path:"/dev_browser"}),u=await fetch(h.toString(),{method:"POST"});if(!u.ok){let e=function(e=[]){return e.length>0?e.map(e=>new W(e)):[]}((await u.json()).errors);e[0]?t4(e[0].longMessage):t4()}let p=await u.json();d(p?.id)},getDevBrowser:c,setDevBrowser:d,removeDevBrowser:h,refreshCookies:function(){let e=c();e&&d(e)}}}({frontendApi:e.frontendApi,fapiClient:t,cookieSuffix:i,cookieOptions:a})}async setup(){return"production"===this.instanceType?this.setupProduction():this.setupDevelopment()}isSignedOut(){return this.clerk.loaded?!this.clerk.user:0>=this.clientUat.get()}async handleUnauthenticatedDevBrowser(){this.devBrowser.clear(),await this.devBrowser.setup()}decorateUrlWithDevBrowserToken(e){let t=this.devBrowser.getDevBrowser();if(!t)throw Error(`${t2} Missing dev browser. Please contact support.`);return sf(e,t)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new rS,this.poller.startPollingForSessionToken(()=>this.refreshSessionToken()))}stopPollingForToken(){this.poller&&(this.poller.stopPollingForSessionToken(),this.poller=null)}refreshTokenOnFocus(){let e=()=>{"visible"===document.visibilityState&&this.refreshSessionToken({updateCookieImmediately:!0})};window.addEventListener("focus",e),"u">typeof document&&document.addEventListener("visibilitychange",e)}async refreshSessionToken({updateCookieImmediately:e=!1}={}){if(this.clerk.session)try{let t=await this.clerk.session.getToken();e&&this.updateSessionCookie(t)}catch(e){return this.handleGetTokenError(e)}}updateSessionCookie(e){if((document.hasFocus()||this.inVisibleCrossOriginIframe()||this.isCurrentContextActive())&&!(e&&this.#Q(e)))return e||k()||tS.warn("Removing session cookie (offline)",{sessionId:this.clerk.session?.id},"authCookieService"),this.setActiveContextInStorage(),e?this.sessionCookie.set(e):this.sessionCookie.remove()}#Q(e){let t=this.#X(e);if(!t||null==rA(t))return!1;let i=this.#X(this.sessionCookie.get());if(!i||null==rA(i))return!1;let r=i.jwt?.claims?.exp;return!("number"!=typeof r||r<=Math.floor(Date.now()/1e3))&&rP(i)===rP(t)&&(rT(i)||"")===(rT(t)||"")&&rU(i,t)===i}#X(e){if(!e)return null;try{let t=new n8({id:"__session",jwt:e,object:"token"});return t.jwt?t:null}catch{return null}}setClientUatCookieForDevelopmentInstances(){this.clerk.client&&"production"!==this.instanceType&&this.inCustomDevelopmentDomain()&&this.clientUat.set(this.clerk.client)}inCustomDevelopmentDomain(){let e=this.clerk.frontendApi.replace("clerk.","");return!window.location.host.endsWith(e)}handleGetTokenError(e){if($(e)||M(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(X(e))return void this.clerk.handleUnauthenticated().catch(tm.lQ);this.clerkEventBus.emit(A,"degraded")}}handleSignOut(){this.activeCookie.remove(),this.sessionCookie.remove(),this.setClientUatCookieForDevelopmentInstances()}setActiveContextInStorage(){let e=this.clerk.session?.id||"",t=this.clerk.organization?.id||"",i=`${e}:${t}`;":"!==i?this.activeCookie.set(i):this.activeCookie.remove()}inVisibleCrossOriginIframe(){return tG()&&"visible"===document.visibilityState}isCurrentContextActive(){let e=this.activeCookie.get();if(!e)return!0;let[t,i]=e.split(":"),r=this.clerk.session?.id||"",n=this.clerk.organization?.id||"";return t===r&&i===n}getSessionCookie(){return this.sessionCookie.get()}}class sR{clerk;captchaChallenge;timers;constructor(e,t=new id(e),i=ry()){this.clerk=e,this.captchaChallenge=t,this.timers=i}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 sM=["/client","/waitlist"],sz=["/client/sign_ins","/client/sign_ups"];function sF(e){let t;try{t=new n8({jwt:e||"",object:"token",id:void 0})}catch{t=null}if(rz.clearInstance(),!t?.jwt)return rz.getOrCreateInstance({object:"client",last_active_session_id:null,id:"client_init",sessions:[]});let{sessionId:i,userId:r,orgId:n,orgRole:s,orgPermissions:a,orgSlug:o,factorVerificationAge:l}=(e=>{let t,i,r,n,s=e.fva??null,a=e.sts??null;if(2===e.v){if(e.o){t=e.o?.id,r=e.o?.slg,e.o?.rol&&(i=`org:${e.o?.rol}`);let{org:s}=nx(e.fea),{permissions:a,featurePermissionMap:o}=(({per:e,fpm:t})=>{if(!e||!t)return{permissions:[],featurePermissionMap:[]};let i=e.split(",").map(e=>e.trim());return{permissions:i,featurePermissionMap:t.split(",").map(e=>((e,t)=>{if(!/^\d+$/.test(e))return;let i=e.replace(/^0+/,"")||"0",r=[];for(;"0"!==i;){let e="",t=0;for(let r=0;r<i.length;r++){let n=10*t+i.charCodeAt(r)-48,s=Math.floor(n/2);(e||0!==s)&&(e+=s),t=n%2}r.push(t),i=e||"0"}for(0===r.length&&r.push(0);r.length<t;)r.push(0);return r})(e.trim(),i.length)??[])}})({per:e.o?.per,fpm:e.o?.fpm});n=function({features:e,permissions:t,featurePermissionMap:i}){if(!e||!t||!i)return[];let r=[];for(let n=0;n<e.length;n++){let s=e[n];if(n>=i.length)continue;let a=i[n];if(a)for(let e=0;e<a.length&&e<t.length;e++)1===a[e]&&r.push(`org:${s}:${t[e]}`)}return r}({features:s,featurePermissionMap:o,permissions:a})}}else t=e.org_id,i=e.org_role,r=e.org_slug,n=e.org_permissions;return{sessionClaims:e,sessionId:e.sid,sessionStatus:a,actor:e.act,userId:e.sub,orgId:t,orgRole:i,orgSlug:r,orgPermissions:n,factorVerificationAge:s}})(t.jwt.claims),c={object:"client",last_active_session_id:i,id:"client_init",sessions:[{object:"session",id:i,status:"active",last_active_organization_id:n||null,last_active_token:{id:void 0,object:"token",jwt:e},factor_verification_age:l||null,public_user_data:{user_id:r},user:{object:"user",id:r,updated_at:1,organization_memberships:n&&o&&s?[{object:"organization_membership",id:n,role:s,permissions:a||[],organization:{object:"organization",id:n,name:o,slug:o,members_count:1,max_allowed_memberships:1}}]:[]}}]};return rz.getOrCreateInstance(c)}class sN{static #L="/api_keys";async #Y(){let e=await iu.clerk.session?.getToken();if(!e)throw new R("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 iu._fetch({...await this.#Y(),method:"GET",path:sN.#L,search:iN({...e,subject:e?.subject??iu.clerk.organization?.id??iu.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new ip(e))}})}async create(e){return new ip(await iu._fetch({...await this.#Y(),path:sN.#L,method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??iu.clerk.organization?.id??iu.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new ip(await iu._fetch({...await this.#Y(),method:"POST",path:`${sN.#L}/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let sD=new Map;class sW{async getConsentInfo(e){let{oauthClientId:t,scope:i,redirectUri:r}=e,n={...void 0!==i&&{scope:i},...void 0!==r&&{redirect_uri:r}},s=await iu._fetch({method:"GET",path:`/me/oauth/consent/${encodeURIComponent(t)}`,search:Object.keys(n).length>0?n:void 0},{skipUpdateClient:!0});if(!s)throw new R("Network request failed while offline",{code:"network_error"});let a=s.response??s;return{oauthApplicationName:a.oauth_application_name,oauthApplicationLogoUrl:a.oauth_application_logo_url,oauthApplicationUrl:a.oauth_application_url,clientId:a.client_id,state:a.state,redirectDomain:a.redirect_domain,scopes:a.scopes?.map(e=>({scope:e.scope,description:e.description,requiresConsent:e.requires_consent}))??[]}}async lookupDeviceVerification(e){let t=await iu._fetch({method:"POST",path:"/me/oauth/device/lookup",body:{userCode:e.userCode}},{skipUpdateClient:!0});if(!t)throw new R("Network request failed while offline",{code:"network_error"});let i=t.response??t;return{oauthApplicationName:i.oauth_application_name,oauthApplicationLogoUrl:i.oauth_application_logo_url,clientId:i.client_id,scopes:i.scopes?.map(e=>({scope:e.scope,description:e.description,requiresConsent:e.requires_consent}))??[],status:i.status,expiresAt:i.expires_at}}async submitDeviceVerification(e){let t=await iu._fetch({method:"POST",path:"/me/oauth/device",body:{userCode:e.userCode,approved:e.approved,organizationId:e.organizationId}},{skipUpdateClient:!0});if(!t)throw new R("Network request failed while offline",{code:"network_error"});let i=t.response??t;return{object:i.object,status:i.status}}buildConsentActionUrl({clientId:e}){let t=iu.fapiClient.buildUrl({path:`/me/oauth/consent/${encodeURIComponent(e)}`,sessionId:iu.clerk.session?.id});return iu.clerk.buildUrlWithAuth(t.toString())}}let sL="__clerk_protect_pid",s$=/^v\d+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,sj="abcdefghijklmnopqrstuvwxyz234567",sB=/^[a-z2-7]{26}$/,sJ=/\{(cid|pid|rid|sdkver)\}/g,sK=/\{(?:cid|pid|rid|sdkver)\}/,sV=/\{(?:cid|pid|rid)\}/,sq=/\{cid\}/;function sH(e,t){return e.replace(sJ,(e,i)=>t[i]??e)}function sG(){let e="u">typeof crypto?crypto:void 0;if("function"!=typeof e?.getRandomValues)return null;try{return function(e){let t="",i=0,r=0;for(let n=0;n<e.length;n++)for(i=i<<8|e[n],r+=8;r>=5;)t+=sj[i>>>r-5&31],r-=5;return r>0&&(t+=sj[i<<5-r&31]),t}(e.getRandomValues(new Uint8Array(16)))}catch{return null}}let sQ=new Map;function sX(){try{return globalThis.localStorage??null}catch{return null}}function sY(e){try{let t=sX()?.getItem(e);if("string"==typeof t)return t}catch{}return sQ.get(e)??null}function sZ(e,t){try{let i=sX();if(i){i.setItem(e,t),sQ.delete(e);return}}catch{}sQ.set(e,t)}function s0(e,t,i){let r,n=sY(e);if(!n)return null;try{r=JSON.parse(n)}catch{return null}if(!r||"object"!=typeof r)return null;let{token:s,exp:a,rid:o,at:l,floor:c}=r;if("string"!=typeof o||!sB.test(o)||!function(e){if("number"!=typeof e||!Number.isFinite(e))return!1;let t=Date.now()-e;return t>=0&&t<864e5}(l)||s1(c)<i)return null;let d=s3(s,a,t);return d?{...d,rid:o,at:l,floor:s1(c)}:null}function s1(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:0}function s3(e,t,i){if("string"!=typeof e||e.length>4096||!s$.test(e)||"number"!=typeof t||!Number.isFinite(t))return null;let r=1e3*t;return r-i<=Date.now()||r>Date.now()+864e5?null:{token:e,exp:t}}function s2(e,t,i){sZ(e,JSON.stringify({...t,at:Date.now(),floor:i}))}let s4=Symbol("deadline");async function s5(e,t,i){let r=globalThis.__clerk_specter;if(!r||"object"!=typeof r)return"no_token";let{cid:n,ready:s}=r;if(n!==e||!(s&&("object"==typeof s||"function"==typeof s)&&"function"==typeof s.then))return"no_token";let a=await new Promise(e=>{let t=setTimeout(()=>e(s4),Math.max(0,i-Date.now())),r=i=>{clearTimeout(t),e(i)};s.then(r,()=>r(null))});if(a===s4)return"timeout";if(!a||"object"!=typeof a)return"no_token";let{token:o,exp:l}=a,c=s3(o,l,0);return c?{...c,rid:t}:"no_token"}function s6(e){return e>=100&&e<=599?`http_${e}`:"fetch_error"}function s8(e){let t=[];for(let i of("string"==typeof e.token_url&&t.push(e.token_url),"string"==typeof e.text_content&&t.push(e.text_content),Object.values(e.attributes??{})))"string"==typeof i&&t.push(i);return t}function s9(e){return s8(e).some(e=>sK.test(e))}function s7(e){return s8(e).some(e=>sV.test(e))}function ae(e){return s8(e).some(e=>sq.test(e))}class at{#Z;#ee;#et;#ei;#er;#en;#es;#ea;#eo=0;#el;#ec;#ed;#eh=!1;#eu=0;#ep=0;static create(e,t,i){let r=e.filter(s9);if(0!==r.length)return new at(r,t,i)}constructor(e,t,i){this.#ea=t,this.#eo=s1(i);const r=e.some(s7);this.#Z=r?function(){let e=sY(sL);if(e&&sB.test(e))return e;let t=sG();return t&&sZ(sL,t),t}():null,this.#ee=this.#Z?sG():null,this.#et=this.#Z&&this.#ee?function(e,t){return`1-${e}-${t}`}(this.#Z,this.#ee):null,this.#ei={...this.#et?{cid:this.#et}:{},...this.#Z?{pid:this.#Z}:{},...this.#ee?{rid:this.#ee}:{},sdkver:"6.42.0-canary.v20261027184321"};const n=e.find(ae);this.#er=n,this.#en=n?function(e,t){if("string"!=typeof e.token_url||!e.token_url)return;let i="u">typeof document?document.baseURI:void 0;try{return new URL(sH(e.token_url,t),i).href}catch{return}}(n,this.#ei):void 0,this.#es=function(e){return"number"!=typeof e||!Number.isFinite(e)||e<=0?5e3:Math.min(e,1e4)}(n?.token_timeout_ms),this.#el="__clerk_protect_st",this.#ec=rk("clerk.lock.protectSessionToken")}placeholders(){return this.#ei}isTokenLoader(e){return this.#er===e}start(){this.#er&&!this.#ed&&this.#e_()}async getRequestParams(){var e,t,i,r;if(!this.#er)return;if(!this.#et||!this.#Z)return{__clerk_protect_status:"unsupported"};this.#ef();let n=this.#ed?await (e=this.#ed,t=this.#es,new Promise(i=>{let r=setTimeout(()=>i("timeout"),t),n=e=>{clearTimeout(r),i(e)};e.then(n,()=>n("timeout"))})):"timeout",s=s0(this.#el,5e3,this.#eo);return s?{__clerk_protect_token:s.token,__clerk_protect_status:"ok",__clerk_protect_cid:(i=this.#Z,r=s.rid,`1-${i}-${r}`)}:{__clerk_protect_status:"ok"===n?"timeout":n,__clerk_protect_cid:this.#et}}hasFreshToken(){return!!this.#er&&null!==this.#em()}#em(){return s0(this.#el,6e4,this.#eo)}#ef(){this.#ed&&(!this.#eh||s0(this.#el,5e3,this.#eo)||Date.now()-this.#eu<this.#eg())||this.#e_()}#eg(){return this.#ep<=1?3e4:Math.min(3e4*2**(this.#ep-1),9e5)}#e_(){this.#eu=Date.now(),this.#eh=!1;let e=e=>(this.#eh=!0,this.#ep=s0(this.#el,5e3,this.#eo)?0:this.#ep+1,e);this.#ed=this.#ey().then(e,()=>e("timeout"))}async #ey(){if(!this.#et)return"unsupported";if(this.#em())return"ok";let e=await this.#ec.acquireLockAndRun(async()=>this.#em()?"ok":await this.#ew());return"string"==typeof e?e:this.#em()?"ok":"timeout"}async #ew(){let e=Date.now()+this.#es,t=await this.#eb(e);if("error"===t)return"script_error";if("timeout"===t)return"timeout";if(this.#en)return await this.#ev(e);let i=await s5(this.#et,this.#ee,e);return"string"==typeof i?i:(s2(this.#el,i,this.#eo),"ok")}#eb(e){var t;let i,r=this.#er;if(!r)return Promise.resolve("error");try{i=this.#ea(r,this.#ei)}catch{return Promise.resolve("error")}return i?(t=i).getAttribute("src")||t.getAttribute("href")||"SCRIPT"===t.tagName&&t.getAttribute("type")?.toLowerCase()==="module"?new Promise(t=>{let r=setTimeout(()=>t("timeout"),Math.max(0,e-Date.now())),n=e=>()=>{clearTimeout(r),t(e)};i.addEventListener("load",n("loaded"),{once:!0}),i.addEventListener("error",n("error"),{once:!0})}):Promise.resolve("loaded"):Promise.resolve("error")}async #ev(e){let t=this.#en,i=new AbortController,r=setTimeout(()=>i.abort(),Math.max(0,e-Date.now()));try{for(;;){var n;let r;if(Date.now()>=e)return"timeout";try{r=await fetch(t,{credentials:"omit",signal:i.signal})}catch{return i.signal.aborted?"timeout":"fetch_error"}if(200===r.status){let e=await ai(r,this.#ee);if(!e)return"fetch_error";return s2(this.#el,e,this.#eo),"ok"}let s=202===r.status;if(!s&&(n=r.status,408!==n&&429!==n&&!(n>=500)))return s6(r.status);let a=s?await ar(r):200;if(Date.now()+a>=e)return s?"timeout":s6(r.status);await function(e,t){return new Promise(i=>{let r=setTimeout(i,e);t.addEventListener("abort",()=>{clearTimeout(r),i()},{once:!0})})}(a,i.signal)}}finally{clearTimeout(r)}}}async function ai(e,t){let i;try{i=await e.json()}catch{return null}if(!i||"object"!=typeof i)return null;let{token:r,exp:n}=i,s=s3(r,n,0);return s?{...s,rid:t}:null}async function ar(e){try{let t=await e.json(),i=t?.retry_in_ms;if("number"==typeof i&&Number.isFinite(i))return Math.min(Math.max(i,50),1e3)}catch{}return 100}class an{#M=!1;#ek;#eS;get challengeLoadTimeoutMs(){return this.#eS}load(e){let t=e?.protectConfig;if(t?.loaders&&Array.isArray(t.loaders)&&0!==t.loaders.length&&!this.#M){if(m()){this.#M=!0;try{this.#eI(t.loaders,t.tokens_invalid_before)}catch(e){eR(`[protect] failed to load: ${e}`)}}}}#eI(e,t){let i=e.filter(e=>{var t;return(!!(t=e)&&"object"==typeof t||(eR(`[protect] loader entry is not an object: ${t}`),!1))&&function(e){if(void 0===e.rollout)return!0;let t=e.rollout;return"number"!=typeof t||t<0?(eR(`[protect] loader rollout value is invalid: ${t}`),!1):0!==t&&Math.random()<=t}(e)});this.#eS=i.find(e=>"number"==typeof e.challenge_load_timeout_ms&&Number.isFinite(e.challenge_load_timeout_ms)&&e.challenge_load_timeout_ms>0)?.challenge_load_timeout_ms;let r=(e,t)=>this.applyLoader(e,t);for(let e of(this.#ek=at.create(i,r,t),i))if(!this.#ek?.isTokenLoader(e))try{this.applyLoader(e,this.#ek?.placeholders())}catch(e){eR(`[protect] failed to apply loader: ${e}`)}this.#ek?.start()}getRequestParams(){try{return(this.#ek?.getRequestParams()??Promise.resolve(void 0)).catch(()=>void 0)}catch{return Promise.resolve(void 0)}}applyLoader(e,t){let i=e.type||"script",r=e.target||"body",n=document.createElement(i);if(e.attributes)for(let[i,r]of Object.entries(e.attributes))switch(typeof r){case"string":n.setAttribute(i,t?sH(r,t):r);break;case"number":case"boolean":n.setAttribute(i,String(r));break;default:eR(`[protect] loader attribute is invalid type: ${i}=${r}`)}switch(e.text_content&&"string"==typeof e.text_content&&(n.textContent=t?sH(e.text_content,t):e.text_content),r){case"head":return document.head.appendChild(n),n;case"body":return document.body.appendChild(n),n;default:if(r?.startsWith("#")){let e=document.getElementById(r.substring(1));if(!e)return void eR(`[protect] loader target element not found: ${r}`);return e.appendChild(n),n}eR(`[protect] loader target is invalid: ${r}`);return}}}async function as(e){if(void 0===e)return;let t=e;if("function"==typeof e)try{t=await e()}catch(e){eR(`Clerk: protectAssertion resolver failed, continuing without it: ${e}`);return}if(void 0!==t)return"string"!=typeof t||""===t.trim()?void eR("Clerk: protectAssertion must be a non-empty string; ignoring it."):t}async function aa(e){let t=await as(e);return t?{__clerk_protect_assertion:t}:void 0}class ao{signInResourceSignal=iW;signInErrorSignal=iL;signInFetchSignal=i$;signInSignal=ij;signUpResourceSignal=iB;signUpErrorSignal=iJ;signUpFetchSignal=iK;signUpSignal=iV;waitlistResourceSignal=iq;waitlistErrorSignal=iH;waitlistFetchSignal=iG;waitlistSignal=iQ;_waitlistInstance;__internal_effect=iO;__internal_computed=iT;constructor(){rp.on("resource:update",this.onResourceUpdated),rp.on("resource:error",this.onResourceError),rp.on("resource:fetch",this.onResourceFetch),this._waitlistInstance=new sh(null),this.waitlistResourceSignal({resource:this._waitlistInstance})}get __internal_waitlist(){return this._waitlistInstance}onResourceError=e=>{e.resource instanceof nY&&this.signInErrorSignal({error:e.error}),e.resource instanceof n1&&this.signUpErrorSignal({error:e.error}),e.resource instanceof sh&&this.waitlistErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof nY){if(al(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof n1){if(al(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}e.resource instanceof sh&&(this._waitlistInstance=e.resource,this.waitlistResourceSignal({resource:e.resource}))};onResourceFetch=e=>{e.resource instanceof nY&&this.signInFetchSignal({status:e.status}),e.resource instanceof n1&&this.signUpFetchSignal({status:e.status}),e.resource instanceof sh&&this.waitlistFetchSignal({status:e.status})}}function al(e,t){return!t?.id&&e&&e.__internal_future?.canBeDiscarded===!1}let ac="cannot_render_billing_disabled",ad="cannot_render_user_missing",ah="cannot_render_organizations_disabled",au="cannot_render_organization_missing",ap="cannot_render_single_session_enabled",a_="cannot_render_self_serve_sso_disabled",af={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 am{static version="6.42.0-canary.v20261027184321";static sdkMetadata={name:"@clerk/clerk-js",version:"6.42.0-canary.v20261027184321"};static _billing;static _apiKeys;static _oauthApplication;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new ao;internal_last_error=null;environment;#eC;#eU="";#eA;#eP;#eT;#eO;#eE;#ex=null;#eR;#eM;#ez;#eF="loading";#eN=[];#eD=[];#eW={};#eL;#e$=!1;#ej=null;#eB=null;#eJ=0;#eK=U();#eV=new tT;get __internal_moduleManager(){return this.#eV}get __internal_queryClient(){return this.#eC||Promise.all([i.e(662),i.e(10)]).then(i.bind(i,1753)).then(e=>e.QueryClient).then(e=>{this.#eC||(this.#eC=new e,this.#eK.emit("queryClientStatus","ready"))}),this.#eC?{__tag:"clerk-rq-client",client:this.#eC}:void 0}get __internal_hasOAuthTransport(){return null!==this.#ej}get __internal_oauthTransport(){return this.#ej}get __internal_protectChallengeLoadTimeoutMs(){return this.#eO?.challengeLoadTimeoutMs}__internal_getCachedResources;__internal_createPublicCredentials;__internal_getPublicCredentials;__internal_isWebAuthnSupported;__internal_isWebAuthnAutofillSupported;__internal_isWebAuthnPlatformAuthenticatorSupported;__internal_setActiveInProgress=!1;get publishableKey(){return this.#eU}get version(){return am.version}get uiVersion(){let e="u">typeof window?window.__internal_ClerkUICtor:void 0,t=this.#eW.ui?.ClerkUI;return e?.version??(t instanceof Promise?void 0:t?.version)}set sdkMetadata(e){am.sdkMetadata=e}get sdkMetadata(){return am.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#eF}get isSatellite(){return!!tH()&&(0,tm.VK)(this.#eW.isSatellite,new URL(window.location.href),!1)}get domain(){if(tH()){let e=eO((0,tm.VK)(this.#eA,new URL(window.location.href)));if("production"===this.#ez){let t;if(!e)return"";if(e.match(/^(clerk\.)+\w*$/))t=/(clerk\.)*(?=clerk\.)/;else{if(e.match(/\.clerk.accounts/))return e;t=/^(clerk\.)*/gi}return`clerk.${e.replace(t,"")}`}return e}return"function"==typeof this.#eA?(eR(e5.domainAsFunctionNotSupported),""):eO(this.#eA||"")}get proxyUrl(){if(tH()){var e;let t=(0,tm.VK)(this.#eP,new URL(window.location.href));!t||e7(t)||te(t)||tJ.throwInvalidProxyUrl({url:t});let i=t?!te(t)||"u"<typeof window||!window.location?.origin?t:new URL(t,window.location.origin).toString():"";if(i)return i;if(!this.#eA&&"production"===this.#ez&&(e=window.location.hostname,tt.some(t=>e?.endsWith(t))))return`${window.location.origin}/__clerk`}return"function"==typeof this.#eP?(eR(e5.proxyUrlAsFunctionNotSupported),""):this.#eP||""}get frontendApi(){let e=eC(this.publishableKey);return e?e.frontendApi:tJ.throwInvalidPublishableKeyError({key:this.publishableKey})}get instanceType(){return this.#ez}get isStandardBrowser(){return this.#eW.standardBrowser||!1}get billing(){return am._billing||(am._billing=new iD),am._billing}get apiKeys(){return am._apiKeys||(am._apiKeys=new sN),am._apiKeys}get oauthApplication(){return am._oauthApplication||(am._oauthApplication=new sW),am._oauthApplication}__experimental_checkout(e){return this._checkout||(this._checkout=e=>(function(e,t){let i,r,n,s,{for:a,planId:o,planPeriod:l,seatsQuantity:c,priceId:d}=t;if(null===e.user)throw Error("Clerk: User is not authenticated");if("organization"===a&&null===e.organization)throw Error("Clerk: The current session does not have an active organization. Use `setActive` to set the organization");let h=function(e){let{userId:t,orgId:i,planId:r,planPeriod:n,seatsQuantity:s,priceId:a}=e;return`${t}-${i||"user"}-${r}-${n}-${s}-${a}`}({userId:e.user?.id||"",orgId:"organization"===a?e.organization?.id:void 0,planId:o,planPeriod:l,seatsQuantity:c,priceId:d}),u=sD.get(h);if(u)return u.signals.computedSignal();let p=(i=iP({resource:null}),r=iP({error:null}),n=iP({status:"idle"}),s=iT(()=>{let e=i().resource,t=r().error,s=n().status;return{errors:iX(t,{}),fetchStatus:s,checkout:e}}),{resourceSignal:i,errorSignal:r,fetchSignal:n,computedSignal:s}),_=new i0(p,{..."organization"===a?{orgId:e.organization?.id}:{},planId:o,planPeriod:l,seatsQuantity:c,priceId:d});return sD.set(h,{resource:_,signals:p}),p.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#eW[e]}setProtectAssertion=e=>{this.#eL=e,this.#e$=!0};#eq(){return this.#e$?this.#eL:this.#eW.protectAssertion}async #eH(){let[e,t]=await Promise.all([aa(this.#eq()).catch(()=>void 0),this.#eO?.getRequestParams().catch(()=>void 0)]);if(e||t)return{...e,...t}}get isSignedIn(){return this?.session?.status!=="pending"&&!!this.session}constructor(e,t){if(!(e=(e||"").trim()))return tJ.throwMissingPublishableKeyError();const i=eC(e);if(!i)return tJ.throwInvalidPublishableKeyError({key:e});this.#eA=t?.domain,this.#eP=t?.proxyUrl,this.environment=na.getInstance(),this.#ez=i.instanceType,this.#eU=e,this.#eM=function(e){let t=[],i=[];async function r(e){for await(let i of["u">typeof window&&window.__internal_onBeforeRequest,...t].filter(e=>e))if(await i(e)===!1)return!1;return!0}async function n(e,t){for await(let r of["u">typeof window&&window.__internal_onAfterResponse,...i].filter(e=>e))if(await r(e,t)===!1)return!1;return!0}function s({method:t,path:i,sessionId:r,search:n,rotatingTokenNonce:a}){let o=new URLSearchParams(n);return o.append("__clerk_api_version","2026-08-20"),o.append("_clerk_js_version","6.42.0-canary.v20261027184321"),a&&o.append("rotating_token_nonce",a),e.domain&&"development"===e.instanceType&&e.isSatellite&&o.append("__domain",e.domain),t&&"GET"!==t&&"POST"!==t&&o.append("_method",t),i&&!sM.some(e=>i.startsWith(e))&&r&&o.append("_clerk_session_id",r),ez([...o.entries()].reduce((e,[t,i])=>(e[t]=i.includes(",")?i.split(","):i,e),{}))}function a(t){let{path:i,pathPrefix:r="v1"}=t;if(e.proxyUrl){let n=new URL(e.proxyUrl),a=n.pathname.slice(1);return a.endsWith("/")&&(a=a.slice(0,-1)),e$({base:n.origin,pathname:`${a}/${r}${i}`,search:s(t)},{stringify:!1})}let n="production"===e.instanceType?e.domain:"";return e$({base:`https://${n||e.frontendApi}`,pathname:`${r}${i}`,search:s(t)},{stringify:!1})}async function o(t,i){let s,o={...t},{method:l="GET"}=o,{body:c}=o;if(e.getProtectParams&&(_=o.path,"GET"!==l&&_&&sz.some(e=>_===e||_.startsWith(`${e}/`)))&&function(e){if(void 0===e)return!0;if("object"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}(c)){let t=await e.getProtectParams().catch(()=>void 0);t&&(o.body=c={...c??{},...t})}!c||"object"!=typeof c||c instanceof FormData||(o.body=function(e){if(!e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype)return e;let t={};for(let[i,r]of Object.entries(e))void 0!==r&&(t[i]=r);return t}(c)),o.url=a({...o,sessionId:e.getSessionId()}),o.headers=new Headers(o.headers),"GET"===l||c instanceof FormData||o.headers.has("content-type")||o.headers.set("content-type","application/x-www-form-urlencoded"),"application/x-www-form-urlencoded"===o.headers.get("content-type")&&(o.body=c?ez(c,{keyEncoder:eu}):c);let d=await r(o),h="GET"===l?"GET":"POST",u=o.url,p={...o,method:h,credentials:o.credentials||"include"};try{if(d){let e=i?.fetchMaxTries??(v()?4:11);s=await tA(()=>fetch(u,p),{retryImmediately:!0,initialDelay:700,maxDelayBetweenRetries:5e3,shouldRetry:(t,i)=>"GET"===h&&i<e&&!p.signal?.aborted,onBeforeRetry:e=>{u.searchParams.set("_clerk_retry_attempt",e.toString())}})}else s=new Response("{}",o)}catch(t){var _;let e=u.toString();throw tS.error("network error",{error:t,url:e,method:l},"fapiClient"),Error(`${t2} Network error at "${e}" - ${t}. Please try again.`)}let f=204===s.status?null:await s.json().catch(e=>{if(!(s.status>=500))throw e}),m=Object.assign(s,{payload:f??null});return s.ok||tS.error("request failed",{method:l,path:o.path,status:s.status},"fapiClient"),void 0!==f&&await n(o,m),m}return{buildEmailAddress:function(t){return function({localPart:e,frontendApi:t}){return`${e}@${t?t.replace("clerk.",""):"clerk.com"}`}({localPart:t,frontendApi:e.frontendApi})},buildUrl:a,onAfterResponse:function(e){i.push(e)},onBeforeRequest:function(e){t.push(e)},request:o}}({domain:this.domain,frontendApi:this.frontendApi,instanceType:this.instanceType,isSatellite:this.isSatellite,getSessionId:()=>this.session?.id,getProtectParams:()=>this.#eH(),proxyUrl:this.proxyUrl}),this.#eK.emit(A,"loading"),this.#eK.prioritizedOn(A,e=>this.#eF=e),this.#eK.on(A,e=>{tH()&&("ready"===e||"degraded"===e?window.__clerk_internal_ready?.__resolve&&this.#eG()&&window.__clerk_internal_ready.__resolve(this):"error"===e&&window.__clerk_internal_ready?.__reject&&window.__clerk_internal_ready.__reject(new R("Clerk failed to initialize.",{code:"clerk_init_failed"})))}),tH()&&("ready"===this.#eF||"degraded"===this.#eF)&&this.#eG()&&window.__clerk_internal_ready?.__resolve&&window.__clerk_internal_ready.__resolve(this),iu.clerk=this,this.#eO=new an}getFapiClient=()=>this.#eM;load=async e=>{if(tS.info("load() start",{},"clerk"),!this.loaded){if("development"!==this.#ez||e?.unsafe_disableDevelopmentModeConsoleWarning||eR("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.#eW=this.#eQ(e),this.#ej=this.#eW.__internal_oauthTransport??null,this.#eW.ui?.ClerkUI&&(this.#eR=Promise.resolve(this.#eW.ui.ClerkUI).then(e=>new e(()=>this,()=>this.environment,this.#eW,this.#eV))),"development"===this.#ez&&(this.#eW.routerPush||this.#eW.routerReplace)&&(!this.#eW.routerPush||!this.#eW.routerReplace)){let e=this.#eW.routerPush?"routerReplace":"routerPush";eR(`Clerk: Both \`routerPush\` and \`routerReplace\` need to be defined, but \`${e}\` is not defined. This may cause issues with navigation in your application.`)}rp.on(ru,()=>{this.#eX(this.session)}),this.#eW.sdkMetadata&&(am.sdkMetadata=this.#eW.sdkMetadata),!1!==this.#eW.telemetry&&(this.telemetry=new tc({clerkVersion:am.version,samplingRate:1,perEventSampling:!this.#eW.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#eW.telemetry}),this.#eW.appearance&&this.telemetry.record({event:"THEME_USAGE",eventSamplingRate:1,payload:function(e){let t;if(!e||"object"!=typeof e)return{};let i=e.theme;if(!i)return{};if(Array.isArray(i))for(let e of i){let i=tf(e);if(i){t=i;break}}else t=tf(i);return{themeName:t}}(this.#eW.appearance)}));try{this.#eW.standardBrowser?await this.#eY():await this.#eZ();let e=this.#eW.telemetry,t=!1!==e&&!e?.disabled,i=!!this.#eW.__internal_keyless_claimKeylessApplicationUrl,r=!!this.environment?.clientDebugMode,n=this.environment?.isProduction?.()??!1,s=r||i&&!n,a=i&&!r?"error":void 0;s&&function(e={}){if(tw)return;let{enabled:t=!1,...i}=e;t&&(tg=!0,tw=!0,tk(i))}({enabled:!0,...a?{logLevel:a}:{},...t&&this.telemetry?{telemetryCollector:this.telemetry}:{}}),this.#eO?.load(this.environment),tS.info("load() complete",{},"clerk")}catch(e){throw this.#eK.emit(A,"error"),tS.error("load() failed",{error:e},"clerk"),e}}};#e0(){let e;return!!(!this.#eW.signUpUrl&&this.#eW.signInUrl&&(e=this.#eW.signInUrl,!eE.test(e)))}#e1(e){return tH()&&void 0!==window.location&&this.client?.isEligibleForTouch()?this.buildUrlWithAuth(this.client.buildTouchUrl({redirectUrl:new URL(e,window.location.href)})):e}signOut=async(e,t)=>{if(!this.client||0===this.client.sessions.length)return;let i="u">typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:tm.lQ,r="u">typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:tm.lQ,n=e&&"object"==typeof e?e:t||{},s=n?.redirectUrl||this.buildAfterSignOutUrl();tS.debug("signOut() start",{hasClient:!!this.client,multiSessionCount:this.client?.signedInSessions.length??0,redirectUrl:s,sessionTarget:n?.sessionId??null},"clerk");let a="function"==typeof e?e:void 0,o=async()=>{let e=tO(this.#eW.standardBrowser);rp.emit(rd,null),await e.track(async()=>{a?await a():await this.navigate(this.#e1(s))}),e.isUnloading()||(this.#eX(),await r())};if(await i(),!n.sessionId||1===this.client.signedInSessions.length){this.#e3();try{this.#eW.experimental?.persistClient??!0?await this.client.removeSessions():await this.client.destroy()}catch(e){if(!M(e)||"network_error"!==e.code)throw e}await o(),tS.info("signOut() complete",{redirectUrl:ej(s)},"clerk");return}let l=this.client.signedInSessions.find(e=>e.id===n.sessionId);l?.id&&this.session?.id===l.id?(this.#e3(),await l?.remove(),await o(),tS.info("signOut() complete",{redirectUrl:ej(s)},"clerk")):await l?.remove()};openGoogleOneTap=e=>{this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted()).then(t=>t.openModal("googleOneTap",e||{})),this.telemetry?.record(t_("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(Z(this,this.environment)){if("development"===this.#ez)throw new R(e5.cannotOpenSignInOrSignUp,{code:ap});return}this.assertComponentsReady(this.#eR);let t="SignIn";this.#eR.then(e=>e.ensureMounted({preloadHint:t})).then(t=>t.openModal("signIn",e||{}));let i={withSignUp:e?.withSignUp??this.#e0()};this.telemetry?.record(t_(t,e,i))};closeSignIn=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(ee(this,this.environment)){if("development"===this.#ez)throw new R(e5.cannotRenderAnyBillingComponent("Checkout"),{code:ac});return}if(!this.user){if("development"===this.#ez)throw new R(e5.cannotOpenCheckout,{code:ad});return}this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted()).then(t=>t.openDrawer("checkout",e||{}))};__internal_closeCheckout=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("checkout"))};__internal_openPlanDetails=e=>{if(ee(this,this.environment)){if("development"===this.#ez)throw new R(e5.cannotRenderAnyBillingComponent("PlanDetails"),{code:ac});return}this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted()).then(t=>t.openDrawer("planDetails",e||{})),this.telemetry?.record(t_("PlanDetails",e))};__internal_closePlanDetails=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("planDetails"))};__internal_openSubscriptionDetails=e=>{this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted()).then(t=>t.openDrawer("subscriptionDetails",e||{}))};__internal_closeSubscriptionDetails=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("subscriptionDetails"))};__internal_openReverification=e=>{if(!this.user){if("development"===this.#ez)throw new R(e5.cannotOpenUserProfile,{code:ad});return}this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted()).then(t=>t.openModal("userVerification",e||{})),this.telemetry?.record(t_("UserVerification",e))};__internal_closeReverification=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userVerification"))};__internal_attemptToEnableEnvironmentSetting=e=>{let{for:t,caller:i}=e;if(this.user||"development"!==this.#ez||eR(`Clerk: "${i}" requires an active user session. Ensure a user is signed in before executing ${i}.`),"organizations"===t){let t;return(t=this.environment,t?.organizationSettings.enabled||this.session?.currentTask?.key==="choose-organization")?{isEnabled:!0}:("development"===this.#ez&&this.__internal_openEnableOrganizationsPrompt({caller:i,onSuccess:()=>window.location.reload(),onClose:e.onClose}),{isEnabled:!1})}throw Error(`Attempted to enable an unknown or unsupported setting "${t}".`)};__internal_openEnableOrganizationsPrompt=e=>{this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted({preloadHint:"EnableOrganizationsPrompt"})).then(t=>t.openModal("enableOrganizationsPrompt",e||{})),this.telemetry?.record(tp("EnableOrganizationsPrompt",e))};__internal_closeEnableOrganizationsPrompt=()=>{this.assertComponentsReady(this.#eR),this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeModal("enableOrganizationsPrompt"))};__internal_resolvePendingProtectCheck=async e=>{let t=this.client;if(!t||"complete"===t.signIn.status||"complete"===t.signUp.status)return;let i=nQ.getInstance(),r=async e=>{try{await i.resolve(this,e)}catch(t){throw rp.emit("resource:error",{resource:e,error:t}),t}};"signUp"!==e&&await r(t.signIn),"signIn"!==e&&await r(t.signUp)};__internal_openProtectCheckModal=e=>this.#eR?this.#eR.then(e=>e.ensureMounted()).then(t=>{if(t.openProtectCheckModal)return new Promise((i,r)=>{t.openProtectCheckModal?.({...e,onResolved:()=>{t.closeModal("protectCheck"),i()},onFailed:e=>{t.closeModal("protectCheck"),r(e)}})})}):Promise.resolve();__internal_openBlankCaptchaModal=()=>(this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted()).then(e=>e.openModal("blankCaptcha",{})));__internal_closeBlankCaptchaModal=()=>(this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted()).then(e=>e.closeModal("blankCaptcha")));__internal_loadStripeJs=async()=>{let{loadStripe:e}=await i.e(279).then(i.bind(i,7544));return e};openSignUp=e=>{if(Z(this,this.environment)){if("development"===this.#ez)throw new R(e5.cannotOpenSignInOrSignUp,{code:ap});return}this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted({preloadHint:"SignUp"})).then(t=>t.openModal("signUp",e||{})),this.telemetry?.record(t_("SignUp",e))};closeSignUp=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signUp"))};openUserProfile=e=>{if(!this.user){if("development"===this.#ez)throw new R(e5.cannotOpenUserProfile,{code:ad});return}this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted({preloadHint:"UserProfile"})).then(t=>t.openModal("userProfile",e||{}));let t=(e?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(t_("UserProfile",e,t))};closeUserProfile=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userProfile"))};openOrganizationProfile=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new R(e5.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:ah})}});if(t){if(!this.organization){if("development"===this.#ez)throw new R(e5.createCannotRenderComponentWhenOrgDoesNotExist("OrganizationProfile"),{code:au});return}this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted({preloadHint:"OrganizationProfile"})).then(t=>t.openModal("organizationProfile",e||{})),this.telemetry?.record(t_("OrganizationProfile",e))}};closeOrganizationProfile=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeModal("organizationProfile"))};openInviteMembers=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"InviteMembers",onClose:()=>{throw new R(e5.cannotRenderAnyOrganizationComponent("InviteMembers"),{code:ah})}});if(t){if(!this.organization){if("development"===this.#ez)throw new R(e5.createCannotRenderComponentWhenOrgDoesNotExist("InviteMembers"),{code:au});return}if(!this.session?.checkAuthorization({permission:"org:sys_memberships:manage"})){if("development"===this.#ez)throw new R(e5.createCannotRenderComponentWhenPermissionIsMissing("InviteMembers","org:sys_memberships:manage"),{code:"cannot_render_permission_missing"});return}this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted()).then(t=>t.openModal("inviteMembers",e||{})),this.telemetry?.record(t_("InviteMembers",e))}};closeInviteMembers=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeModal("inviteMembers"))};openCreateOrganization=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new R(e5.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:ah})}});t&&(this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted({preloadHint:"CreateOrganization"})).then(t=>t.openModal("createOrganization",e||{})),this.telemetry?.record(t_("CreateOrganization",e)))};closeCreateOrganization=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeModal("createOrganization"))};openWaitlist=e=>{this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted({preloadHint:"Waitlist"})).then(t=>t.openModal("waitlist",e||{})),this.telemetry?.record(t_("Waitlist",e))};closeWaitlist=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeModal("waitlist"))};mountSignIn=(e,t)=>{this.assertComponentsReady(this.#eR);let i="SignIn";this.#eR.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"signIn",node:e,props:t}));let r={withSignUp:t?.withSignUp??this.#e0()};this.telemetry?.record(tp(i,t,r))};unmountSignIn=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserAvatar=(e,t)=>{this.assertComponentsReady(this.#eR);let i="UserAvatar";this.#eR.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"userAvatar",node:e,props:t})),this.telemetry?.record(tp(i,t))};unmountUserAvatar=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountSignUp=(e,t)=>{this.assertComponentsReady(this.#eR);let i="SignUp";this.#eR.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"signUp",node:e,props:t})),this.telemetry?.record(tp(i,t))};unmountSignUp=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserProfile=(e,t)=>{if(!this.user){if("development"===this.#ez)throw new R(e5.cannotRenderComponentWhenUserDoesNotExist,{code:ad});return}this.assertComponentsReady(this.#eR);let i="UserProfile";this.#eR.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"userProfile",node:e,props:t}));let r=(t?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(tp(i,t,r))};unmountUserProfile=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOrganizationProfile=(e,t)=>{let{isEnabled:i}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new R(e5.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:ah})}});if(!i)return;let r=!!this.user;if(!this.organization&&r){if("development"===this.#ez)throw new R(e5.createCannotRenderComponentWhenOrgDoesNotExist("OrganizationProfile"),{code:au});return}this.assertComponentsReady(this.#eR);let n="OrganizationProfile";this.#eR.then(e=>e.ensureMounted({preloadHint:n})).then(i=>i.mountComponent({name:n,appearanceKey:"userProfile",node:e,props:t})),this.telemetry?.record(tp(n,t))};unmountOrganizationProfile=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountCreateOrganization=(e,t)=>{let{isEnabled:i}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new R(e5.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:ah})}});if(!i)return;this.assertComponentsReady(this.#eR);let r="CreateOrganization";this.#eR.then(e=>e.ensureMounted({preloadHint:r})).then(i=>i.mountComponent({name:r,appearanceKey:"createOrganization",node:e,props:t})),this.telemetry?.record(tp(r,t))};unmountCreateOrganization=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOrganizationSwitcher=(e,t)=>{let{isEnabled:i}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationSwitcher",onClose:()=>{throw new R(e5.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:ah})}});if(!i)return;this.assertComponentsReady(this.#eR);let r="OrganizationSwitcher";this.#eR.then(e=>e.ensureMounted({preloadHint:r})).then(i=>i.mountComponent({name:r,appearanceKey:"organizationSwitcher",node:e,props:t})),this.telemetry?.record(tp(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationSwitcher=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__experimental_prefetchOrganizationSwitcher=()=>{this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted()).then(e=>e.prefetch("organizationSwitcher"))};mountOrganizationList=(e,t)=>{let{isEnabled:i}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationList",onClose:()=>{throw new R(e5.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:ah})}});if(!i)return;this.assertComponentsReady(this.#eR);let r="OrganizationList";this.#eR.then(e=>e.ensureMounted({preloadHint:r})).then(i=>i.mountComponent({name:r,appearanceKey:"organizationList",node:e,props:t})),this.telemetry?.record(tp(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationList=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserButton=(e,t)=>{this.assertComponentsReady(this.#eR);let i="UserButton";this.#eR.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"userButton",node:e,props:t}));let r={...t?.customMenuItems?.length||0?{customItems:!0}:void 0,...t?.__experimental_asStandalone?{standalone:!0}:void 0};this.telemetry?.record(tp(i,t,r))};unmountUserButton=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountWaitlist=(e,t)=>{this.assertComponentsReady(this.#eR);let i="Waitlist";this.#eR.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"waitlist",node:e,props:t})),this.telemetry?.record(tp(i,t))};unmountWaitlist=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountPricingTable=(e,t)=>{if(ee(this,this.environment)){if("development"===this.#ez)throw new R(e5.cannotRenderAnyBillingComponent("PricingTable"),{code:ac});return}this.assertComponentsReady(this.#eR);let i="PricingTable";this.#eR.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"pricingTable",node:e,props:t})),this.telemetry?.record(tp(i,t))};unmountPricingTable=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOAuthConsent=(e,t)=>{if(null===this.user){if("development"===this.#ez)throw new R(e5.cannotRenderOAuthConsentComponentWhenUserDoesNotExist,{code:ad});return}this.assertComponentsReady(this.#eR);let i="OAuthConsent";this.#eR.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"__internal_oauthConsent",node:e,props:t}))};unmountOAuthConsent=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__internal_mountOAuthConsent=(e,t)=>this.mountOAuthConsent(e,t);__internal_unmountOAuthConsent=e=>this.unmountOAuthConsent(e);__internal_mountOAuthDeviceVerification=(e,t)=>{if(!this.user){if("development"===this.#ez)throw new R(e5.cannotRenderOAuthDeviceVerificationComponentWhenUserDoesNotExist,{code:ad});return}this.assertComponentsReady(this.#eR);let i="OAuthDeviceVerification";this.#eR.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"oauthDeviceVerification",node:e,props:t})),this.telemetry?.record(tp(i,t))};__internal_unmountOAuthDeviceVerification=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountAPIKeys=(e,t)=>{let i;if(et(this,i=this.environment)&&ei(this,i)){if("development"===this.#ez)throw new R(e5.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&ei(this,this.environment)){if("development"===this.#ez)throw new R(e5.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if(!this.organization&&et(this,this.environment)){if("development"===this.#ez)throw new R(e5.cannotRenderAPIKeysComponentForUserWhenDisabled,{code:"cannot_render_api_keys_user_disabled"});return}this.assertComponentsReady(this.#eR);let r="APIKeys";this.#eR.then(e=>e.ensureMounted({preloadHint:r})).then(i=>i.mountComponent({name:r,appearanceKey:"apiKeys",node:e,props:t})),this.telemetry?.record(tp(r,t))};unmountAPIKeys=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__internal_mountConfigureSSO=(e,t)=>{let i,r,{isEnabled:n}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"ConfigureSSO",onClose:()=>{throw new R(e5.cannotRenderAnyOrganizationComponent("ConfigureSSO"),{code:ah})}});if(!n)return;let s=!!this.user;if(!this.organization&&s){if("development"===this.#ez)throw new R(e5.createCannotRenderComponentWhenOrgDoesNotExist("ConfigureSSO"),{code:au});return}if(i=this.environment,!i?.userSettings.enterpriseSSO.self_serve_sso||!this.organization?.selfServeSSOEnabled){if("development"===this.#ez)throw new R(e5.cannotRenderConfigureSSOComponentWhenDisabled,{code:a_});return}if(r=this.environment,!r?.userSettings.attributes.email_address?.enabled){if("development"===this.#ez)throw new R(e5.cannotRenderConfigureSSOComponentWhenEmailAddressDisabled,{code:"cannot_render_configure_sso_email_address_disabled"});return}this.assertComponentsReady(this.#eR);let a="ConfigureSSO";this.#eR.then(e=>e.ensureMounted({preloadHint:a})).then(i=>i.mountComponent({name:a,appearanceKey:"configureSSO",node:e,props:t})),this.telemetry?.record(tp(a,t))};__internal_unmountConfigureSSO=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__internal_mountConfigureDirectorySync=(e,t)=>{let i,{isEnabled:r}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"ConfigureDirectorySync",onClose:()=>{throw new R(e5.cannotRenderAnyOrganizationComponent("ConfigureDirectorySync"),{code:ah})}});if(!r)return;let n=!!this.user;if(!this.organization&&n){if("development"===this.#ez)throw new R(e5.createCannotRenderComponentWhenOrgDoesNotExist("ConfigureDirectorySync"),{code:au});return}if(i=this.environment,!i?.userSettings.enterpriseSSO.self_serve_sso||!i?.userSettings.enterpriseSSO.self_serve_directory_sync||!this.organization?.selfServeDirectorySyncEnabled){if("development"===this.#ez)throw new R(e5.cannotRenderConfigureDirectorySyncComponentWhenDisabled,{code:a_});return}this.assertComponentsReady(this.#eR);let s="ConfigureDirectorySync";this.#eR.then(e=>e.ensureMounted({preloadHint:s})).then(i=>i.mountComponent({name:s,appearanceKey:"configureDirectorySync",node:e,props:t})),this.telemetry?.record(tp(s,t))};__internal_unmountConfigureDirectorySync=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskChooseOrganization=(e,t)=>{let{isEnabled:i}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"TaskChooseOrganization",onClose:()=>{throw new R(e5.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:ah})}});if(!i)return;this.assertComponentsReady(this.#eR);let r="TaskChooseOrganization";this.#eR.then(e=>e.ensureMounted({preloadHint:r})).then(i=>i.mountComponent({name:r,appearanceKey:"taskChooseOrganization",node:e,props:t})),this.telemetry?.record(tp(r,t))};unmountTaskChooseOrganization=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskResetPassword=(e,t)=>{this.assertComponentsReady(this.#eR);let i="TaskResetPassword";this.#eR.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"taskResetPassword",node:e,props:t})),this.telemetry?.record(tp("TaskResetPassword",t))};unmountTaskResetPassword=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskSetupMFA=(e,t)=>{this.assertComponentsReady(this.#eR);let i="TaskSetupMFA";this.#eR.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"taskSetupMfa",node:e,props:t})),this.telemetry?.record(tp("TaskSetupMFA",t))};unmountTaskSetupMFA=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};setActive=async e=>{let{organization:t,redirectUrl:i,navigate:r}=e,{session:n}=e;this.__internal_setActiveInProgress=!0,tS.debug("setActive() start",{hasClient:!!this.client,sessionTarget:"string"==typeof n?n:n?.id??n??null,organizationTarget:"string"==typeof t?t:t?.id??t??null,redirectUrl:i??null},"clerk");try{var s;let a;if(!this.client)throw tS.warn("Clerk setActive called before client is loaded",{},"clerk"),Error("setActive is being called before the client is loaded. Wait for init.");if(void 0===n&&!this.session)throw tS.warn("Clerk setActive precondition not met: no target session and no active session",{},"clerk"),Error("setActive should either be called with a session param or there should be already an active session.");"string"==typeof n&&(n=this.client.sessions.find(e=>e.id===n)||null);let o="u">typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:tm.lQ,l="u">typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:tm.lQ,c=void 0===n?this.session:n;c?.status==="pending"&&(s={...this.#eW,...e},a=["taskUrls","navigate"],Object.keys(s).some(e=>a.includes(e))||eR('Clerk: Session has pending tasks but no handling is configured. To handle pending tasks, provide either "taskUrls" for navigation to custom URLs or "navigate" for programmatic navigation. Without these options, users may get stuck on incomplete flows.'));let d=void 0!==t;if(c&&d){let e="string"==typeof t?t:t?.id;if("string"==typeof e&&e.startsWith("org_"))c.lastActiveOrganizationId=e||null;else{let t=c.user.organizationMemberships.find(t=>t.organization.slug===e),i=t?.organization.id||null,r=null===i;if(this.environment?.organizationSettings?.forceOrganizationSelection&&r)return;c.lastActiveOrganizationId=i}}c?.status!=="pending"&&await o(null===c?"sign-out":void 0);let h=c?.status==="pending"&&c?.currentTask&&this.#eW.taskUrls?.[c?.currentTask.key],u=!!(i||h||r),p=d?"select_org":"select_session";if(tH()&&globalThis.document.hasFocus()||!this.#eW.standardBrowser){let e;if(u&&c)try{(e=await c.__internal_touch({intent:p}))&&this.updateClient(e,{__internal_dangerouslySkipEmit:!0})}catch(e){if(X(e))this.handleUnauthenticated();else throw e}else await this.#e2(c,p);c=this.#e4(c?.id,e)}try{await c?.getToken()||rp.emit(rc,{token:null})}catch(e){if(B.is(e))tS.warn("Token fetch failed when setting active session (offline). Preserving existing auth state.",{sessionId:c?.id},"clerk");else throw e}let _=tO(this.#eW.standardBrowser);if(u&&await _.track(async()=>{if(this.client)if(c?.status!=="pending"&&this.#e3(),h){let e=i?e$({base:h,hashSearchParams:{redirectUrl:i}},{stringify:!0}):h;await this.navigate(e)}else if(r&&c){let e=!1,t=t=>(e=!0,this.#e1(t));await r({session:c,decorateUrl:t}),"development"===this.#ez&&!e&&this.client.isEligibleForTouch()&&eR("Clerk: The navigate callback in setActive() did not call decorateUrl(). In Safari, sessions may be limited to 7 days due to Intelligent Tracking Prevention (ITP). Use decorateUrl() to wrap your destination URL to enable the ITP workaround. Learn more: https://clerk.com/docs/troubleshooting/safari-itp")}else i&&await this.navigate(this.#e1(i))}),_.isUnloading())return;this.#eX(c),c?.status!=="pending"&&await l()}finally{this.__internal_setActiveInProgress=!1}};addListener=(e,t)=>{var i;let r;return i=e,e=e=>{var t;r||={...e},i(r={...{client:sp((t=r).client,e.client),session:sp(t.session,e.session),user:sp(t.user,e.user),organization:sp(t.organization,e.organization)}})},this.#eN.push(e),this.client&&!t?.skipInitialEmit&&e({client:this.client,session:this.session,user:this.user,organization:this.organization}),()=>{this.#eN=this.#eN.filter(t=>t!==e)}};on=(...e)=>{this.#eK.on(...e)};off=(...e)=>{this.#eK.off(...e)};__internal_addNavigationListener=e=>(this.#eD.push(e),()=>{this.#eD=this.#eD.filter(t=>t!==e)});navigate=async(e,t)=>{if(!e||!tH())return;if(void 0===window.location){let i=t?.replace&&this.#eW.routerReplace?this.#eW.routerReplace:this.#eW.routerPush;return i?(tS.info(`Clerk is navigating to: ${e}`),await i(e,{windowNavigate:this.__internal_windowNavigate})):void 0}setTimeout(()=>{this.#e5()},0);let i=new URL(e,window.location.href);this.#e6.includes(i.protocol)||(console.warn(`Clerk: "${i.protocol}" is not a valid protocol. Redirecting to "/" instead. If you think this is a mistake, please open an issue.`),i=new URL("/",window.location.href));let r=t?.replace&&this.#eW.routerReplace?this.#eW.routerReplace:this.#eW.routerPush;if(tS.info(`Clerk is navigating to: ${i}`),this.#eW.routerDebug&&console.log(`Clerk is navigating to: ${i}`),"null"!==i.origin&&i.origin!==window.location.origin||!r)return void this.__internal_windowNavigate(i);let n={...t?.metadata?{__internal_metadata:t?.metadata}:{},windowNavigate:this.__internal_windowNavigate};return await r(ej(i),n)};buildUrlWithAuth(e){if("production"===this.#ez)return e;let t=new URL(e,window.location.origin);return t.origin!==window.location.origin&&this.#eT?this.#eT.decorateUrlWithDevBrowserToken(t).href:t.href}buildSignInUrl(e){let t=e?.redirectUrl||window.location.href;this.isSatellite&&(t=this.#e8(t));let i=this.isSatellite?this.#e9(e):e;return this.#e7("signInUrl",{...i,redirectUrl:t},e?.initialValues)}buildSignUpUrl(e){let t=e?.redirectUrl||window.location.href;this.isSatellite&&(t=this.#e8(t));let i=this.isSatellite?this.#e9(e):e;return this.#e7("signUpUrl",{...i,redirectUrl:t},e?.initialValues)}#e8=e=>{try{let t=new URL(e,window.location.origin);return t.searchParams.set(er,en),t.toString()}catch{return e}};#e9=e=>{if(!e)return e;let t={...e};return t.signInForceRedirectUrl&&(t.signInForceRedirectUrl=this.#e8(t.signInForceRedirectUrl)),t.signInFallbackRedirectUrl&&(t.signInFallbackRedirectUrl=this.#e8(t.signInFallbackRedirectUrl)),t.signUpForceRedirectUrl&&(t.signUpForceRedirectUrl=this.#e8(t.signUpForceRedirectUrl)),t.signUpFallbackRedirectUrl&&(t.signUpFallbackRedirectUrl=this.#e8(t.signUpFallbackRedirectUrl)),t};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 eH(this.#eW,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eH(this.#eW,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#eW.afterSignOutUrl?this.buildUrlWithAuth(this.#eW.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#eW.newSubscriptionRedirectUrl?this.#eW.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?e$({base:this.#eW.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#eW.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#eW.afterMultiSessionSingleSignOutUrl):this.#eW.signInUrl?this.buildUrlWithAuth(e$({base:this.#eW.signInUrl,hashPath:"choose"},{stringify:!0})):this.buildUrlWithAuth(this.environment.displayConfig.afterSignOutOneUrl):""}buildCreateOrganizationUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.createOrganizationUrl):""}buildOrganizationProfileUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.organizationProfileUrl):""}buildTasksUrl(e){let t=this.session?.currentTask;if(!t)return"";let i=this.#eW.taskUrls?.[t.key];return i||e$({base:this.buildSignInUrl(e),hashPath:e1(t)},{stringify:!0})}#te=async()=>{if(!tH())return;let e=new URLSearchParams({[er]:es}),t=eX(eo);t&&e7(t)||function(){throw Error(`${t2} Invalid redirect_url. A valid http or https url should be used for the redirection.`)}();let i=e$({base:eX(eo),searchParams:e},{stringify:!0});return this.navigate(this.buildUrlWithAuth(i))};redirectWithAuth=async e=>{if(tH())return this.navigate(this.buildUrlWithAuth(e))};redirectToSignIn=async e=>{if(tH())return this.navigate(this.buildSignInUrl(e))};redirectToSignUp=async e=>{if(tH())return this.navigate(this.buildSignUpUrl(e))};redirectToUserProfile=async()=>{if(tH())return this.navigate(this.buildUserProfileUrl())};redirectToCreateOrganization=async()=>{if(tH())return this.navigate(this.buildCreateOrganizationUrl())};redirectToOrganizationProfile=async()=>{if(tH())return this.navigate(this.buildOrganizationProfileUrl())};redirectToAfterSignIn=async()=>{if(tH())return this.navigate(this.buildAfterSignInUrl())};redirectToAfterSignUp=async()=>{if(tH())return this.navigate(this.buildAfterSignUpUrl())};redirectToAfterSignOut=async()=>{if(tH())return this.navigate(this.buildAfterSignOutUrl())};redirectToWaitlist=async()=>{if(tH())return this.navigate(this.buildWaitlistUrl())};redirectToTasks=async e=>{if(tH())return this.navigate(this.buildTasksUrl(e))};handleEmailLinkVerification=async(e,t)=>{if(!this.client)return;let i=eX("__clerk_status");if("expired"===i)throw new V("expired");if("client_mismatch"===i)throw new V("client_mismatch");if("transferable"===i){"function"==typeof e.onVerifiedOnOtherDevice&&e.onVerifiedOnOtherDevice();return}if("verified"!==i)throw new V("failed");let r=eX("__clerk_created_session"),{signIn:n,signUp:s,sessions:a}=this.client,o=a.some(e=>e.id===r),l="needs_second_factor"===n.status||"missing_requirements"===s.status,c=e=>t&&"function"==typeof t?t(e):this.navigate(e),d=e.redirectUrl?()=>c(e.redirectUrl):tm.lQ;return o?this.setActive({session:r,redirectUrl:e.redirectUrlComplete}):l?d():("function"==typeof e.onVerifiedOnOtherDevice&&e.onVerifiedOnOtherDevice(),null)};__internal_handleResourceCallback=async(e,t,i)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:r,signUp:n}=this.client,s="identifier"in(e||{})?e:r,a="missingFields"in(e||{})?e:n,o=e=>i&&"function"==typeof i?i(this.buildUrlWithAuth(e)):t.__internal_navigate&&"function"==typeof t.__internal_navigate?t.__internal_navigate(e):this.navigate(this.buildUrlWithAuth(e));return this._handleRedirectCallback(t,{signUp:a,signIn:s,navigate:o})};handleGoogleOneTapCallback=async(e,t,i)=>this.__internal_handleResourceCallback(e,t,i);_handleRedirectCallback=async(e,{signIn:t,signUp:i,navigate:r,resuming:n=!1})=>{if(!this.loaded||!this.environment||!this.client)return;if(!window.opener&&e.reloadResource)try{"signIn"===e.reloadResource?await t.reload():"signUp"===e.reloadResource&&await i.reload()}catch{}let{displayConfig:s}=this.environment,{firstFactorVerification:a}=t,{externalAccount:o}=i.verifications,l={status:i.status,missingFields:i.missingFields,externalAccountStatus:o.status,externalAccountErrorCode:o.error?.code,externalAccountSessionId:o.error?.meta?.sessionId,sessionId:i.createdSessionId,protectCheck:i.protectCheck},c={status:t.status,firstFactorVerificationStatus:a.status,firstFactorVerificationErrorCode:a.error?.code,firstFactorVerificationSessionId:a.error?.meta?.sessionId,sessionId:t.createdSessionId,protectCheck:t.protectCheck},d=e=>()=>r(e),h=d(e.signInUrl||s.signInUrl),u=d(e.signUpUrl||s.signUpUrl),p=d(e.firstFactorUrl||e$({base:s.signInUrl,hashPath:"/factor-one"},{stringify:!0})),_=d(e.secondFactorUrl||e$({base:s.signInUrl,hashPath:"/factor-two"},{stringify:!0})),f=d(e.resetPasswordUrl||e$({base:s.signInUrl,hashPath:"/reset-password"},{stringify:!0})),m=d(e.signInProtectCheckUrl||e$({base:s.signInUrl,hashPath:"/protect-check"},{stringify:!0})),g=new eH(this.#eW,e),y=e.continueSignUpUrl||e$({base:s.signUpUrl,hashPath:"/continue"},{stringify:!0}),w=e.verifyEmailAddressUrl||e$({base:s.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),b=e.verifyPhoneNumberUrl||e$({base:s.signUpUrl,hashPath:"/verify-phone-number"},{stringify:!0}),v=e.signUpProtectCheckUrl||e$({base:s.signUpUrl,hashPath:"/protect-check"},{stringify:!0}),k=e.signInUrl||s.signInUrl,S=e.signUpUrl||s.signUpUrl,I=e.enterpriseConnectionsUrl||e$({base:S,hashPath:"/enterprise-connections"},{stringify:!0}),C=d(v),U=e.__internal_navigateOnSetActive,A=async({session:e,baseUrl:t,redirectUrl:i})=>{U?await U({session:e,redirectUrl:i,decorateUrl:e=>this.buildUrlWithAuth(e)}):e.currentTask?await e3(e,{baseUrl:t,navigate:this.navigate}):await this.navigate(i)};if("complete"===c.status)return this.setActive({session:c.sessionId,navigate:async({session:e})=>{await A({session:e,baseUrl:k,redirectUrl:g.getAfterSignInUrl()})}});if(!n&&"signUp"!==e.reloadResource&&(c.protectCheck||"needs_protect_check"===c.status))return m();if(!n&&"signIn"!==e.reloadResource&&l.protectCheck)return C();if("transferable"===l.externalAccountStatus&&l.externalAccountErrorCode===el){let e=await t.create({transfer:!0});if(e.protectCheck||"needs_protect_check"===e.status)return m();switch(e.status){case"complete":return this.setActive({session:e.createdSessionId,navigate:async({session:e})=>{await A({session:e,baseUrl:S,redirectUrl:g.getAfterSignInUrl()})}});case"needs_first_factor":return p();case"needs_second_factor":return _();case"needs_new_password":return f();default:t5("sign in")}}let P="user_locked"===l.externalAccountErrorCode,T="user_locked"===c.firstFactorVerificationErrorCode;if(P)return u();if(T)return h();if("needs_first_factor"===c.status&&!t.supportedFirstFactors?.every(e=>"enterprise_sso"===e.strategy))return p();if("needs_new_password"===c.status)return f();if("transferable"===c.firstFactorVerificationStatus||"transfer_to_sign_up"===e.continuation){if(!1===e.transferable)return h();let t=await i.create({transfer:!0,unsafeMetadata:e.unsafeMetadata});switch(t.status){case"complete":return this.setActive({session:t.createdSessionId,navigate:async({session:e})=>{await A({session:e,baseUrl:S,redirectUrl:g.getAfterSignUpUrl()})}});case"missing_requirements":return tj({signUp:t,continueSignUpUrl:y,verifyEmailAddressUrl:w,verifyPhoneNumberUrl:b,signUpProtectCheckUrl:v,enterpriseConnectionsUrl:I,navigate:r});default:t5("sign in")}}if("complete"===l.status)return this.setActive({session:l.sessionId,navigate:async({session:e})=>{await A({session:e,baseUrl:S,redirectUrl:g.getAfterSignUpUrl()})}});if("needs_second_factor"===c.status)return _();let O=("failed"===l.externalAccountStatus||"unverified"===l.externalAccountStatus)&&"identifier_already_signed_in"===l.externalAccountErrorCode&&l.externalAccountSessionId,E="failed"===c.firstFactorVerificationStatus&&"identifier_already_signed_in"===c.firstFactorVerificationErrorCode&&c.firstFactorVerificationSessionId;if(O||E){let e=c.firstFactorVerificationSessionId||l.externalAccountSessionId;if(e)return this.setActive({session:e,navigate:async({session:e})=>{await A({session:e,baseUrl:O?S:k,redirectUrl:g.getAfterSignInUrl()})}})}return(e=>{let{externalAccount:t}=e.verifications;return!!t.error})(i)?u():"verified"===l.externalAccountStatus&&"missing_requirements"===l.status?tj({signUp:i,continueSignUpUrl:y,verifyEmailAddressUrl:w,verifyPhoneNumberUrl:b,signUpProtectCheckUrl:v,enterpriseConnectionsUrl:I,navigate:r}):this.session?.currentTask?void await this.redirectToTasks({redirectUrl:this.buildAfterSignInUrl()}):"signUp"!==e.reloadResource&&"needs_first_factor"===c.status&&(t.supportedFirstFactors??[]).filter(e=>"enterprise_sso"===e.strategy&&"enterpriseConnectionId"in e&&"enterpriseConnectionName"in e).length>1?p():h()};__internal_resumeAfterProtectCheck=async(e={},t)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:i,signUp:r}=this.client,n=t??e.__internal_navigate,s=e=>n&&"function"==typeof n?n(e):this.navigate(e);return this._handleRedirectCallback(e,{signUp:r,signIn:i,navigate:s,resuming:!0})};handleRedirectCallback=async(e={},t)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:i,signUp:r}=this.client,n=t??e.__internal_navigate,s=e=>n&&"function"==typeof n?n(e):this.navigate(e);return this._handleRedirectCallback(e,{signUp:r,signIn:i,navigate:s})};handleUnauthenticated=async(e={broadcast:!0})=>{if(this.client&&this.session)try{let t=await rz.getOrCreateInstance().fetch();if(this.updateClient(t),this.session)return;return e.broadcast&&rp.emit(rd,null),this.setActive({session:null})}catch(e){if($(e)&&[403,500].includes(e.status))return this.setActive({session:null});throw e}};__internal_handleUnauthenticatedDevBrowser=async()=>{this.#eT&&await this.#eT.handleUnauthenticatedDevBrowser()};authenticateWithGoogleOneTap=async e=>this.client?.signIn.create({strategy:"google_one_tap",token:e.token}).catch(t=>{if($(t)&&"external_account_not_found"===t.errors[0].code)return this.client?.signUp.create({strategy:"google_one_tap",token:e.token,legalAccepted:e.legalAccepted});throw t});authenticateWithMetamask=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_okx_wallet_signature"})};authenticateWithSolana=async e=>{await this.authenticateWithWeb3({...e,strategy:"web3_solana_signature"})};authenticateWithWeb3=async({redirectUrl:e,signUpContinueUrl:t,customNavigate:i,unsafeMetadata:r,strategy:n,legalAccepted:s,secondFactorUrl:a,protectCheckUrl:o,signUpProtectCheckUrl:l,walletName:c})=>{let d,h;if(!this.client||!this.environment)return;let{displayConfig:u}=this.environment,p=n.replace("web3_","").replace("_signature",""),_=await tY().getWeb3Identifier({provider:p,walletName:c});switch(p){case"metamask":d=tY().generateSignatureWithMetamask;break;case"base":d=tY().generateSignatureWithBase;break;case"coinbase_wallet":d=tY().generateSignatureWithCoinbaseWallet;break;case"solana":if(!c)throw new R("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});d=e=>tY().generateSignatureWithSolana({...e,walletName:c});break;default:d=tY().generateSignatureWithOKXWallet}let f=e=>()=>i&&"function"==typeof i?i(e):this.navigate(e),m=f(a||e$({base:u.signInUrl,hashPath:"/factor-two"},{stringify:!0})),g=f(o||e$({base:u.signInUrl,hashPath:"/protect-check"},{stringify:!0})),y=f(l||e$({base:u.signUpUrl,hashPath:"/protect-check"},{stringify:!0})),w=f(t||e$({base:u.signUpUrl,hashPath:"/continue"},{stringify:!0})),b=!1;try{h=await this.client.signIn.authenticateWithWeb3({identifier:_,generateSignature:d,strategy:n,walletName:c})}catch(e){if(tB(e,"form_identifier_not_found"))b=!0,h=await this.client.signUp.authenticateWithWeb3({identifier:_,generateSignature:d,unsafeMetadata:r,strategy:n,legalAccepted:s,walletName:c}),t&&"missing_requirements"===h.status&&"verified"===h.verifications.web3Wallet.status&&!h.protectCheck&&await w();else throw e}let v=async({session:e,redirectUrl:t})=>{e.currentTask?await e3(e,{baseUrl:u.signInUrl,navigate:this.navigate}):await this.navigate(t)};if(h.protectCheck||"needs_protect_check"===h.status)return void await (b?y:g)();switch(h.status){case"needs_second_factor":await m();break;case"complete":h.createdSessionId&&await this.setActive({session:h.createdSessionId,navigate:async({session:t})=>{await v({session:t,redirectUrl:e??this.buildAfterSignInUrl()})}});break;default:return}};createOrganization=async({name:e,slug:t})=>nf.create({name:e,slug:t});getOrganization=async e=>nf.get(e);joinWaitlist=async({emailAddress:e})=>sh.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,t)=>{if(!this.client){let t=this.#eW.selectInitialSession?this.#eW.selectInitialSession(e):this.#tt(e);this.#eX(t,{dangerouslySkipEmit:!0})}if(this.client=e,this.session){let t=this.#e4(this.session.id,e);"active"===this.session.status&&t?.status==="pending"&&("u">typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:tm.lQ)(),this.#eX(t,{dangerouslySkipEmit:!0}),this.session?.lastActiveToken||k()||tS.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),rp.emit(rc,{token:this.session?.lastActiveToken})}t?.__internal_dangerouslySkipEmit||this.#ti()};get __internal_environment(){return this.environment}__internal_setEnvironment=async e=>{this.environment=new na(e)};__internal_onBeforeRequest=e=>{this.#eM.onBeforeRequest(e)};__internal_onAfterResponse=e=>{this.#eM.onAfterResponse(e)};__internal_updateProps=e=>{let t={...e,options:this.#eQ({...this.#eW,...e.options})};return this.#eR?.then(e=>e.ensureMounted()).then(e=>e.updateProps(t))};__internal_navigateWithError(e,t){return this.__internal_last_error=t,this.navigate(e)}#tr=()=>{let e=new URLSearchParams({[eo]:window.location.href});return e$({base:this.#eW.signInUrl,searchParams:e},{stringify:!0})};#tn=()=>{let e;if(this.proxyUrl){let t=new URL(this.proxyUrl);e=new URL(`${t.pathname}/v1/client/sync`,t.origin)}else this.domain&&(e=new URL("/v1/client/sync",`https://${this.domain}`));return e?.searchParams.append("redirect_url",window.location.href),e?.toString()||""};#ts=()=>{let e=eX(er);return e!==es&&!!this.isSatellite&&(e===en||!0===this.#eW.satelliteAutoSync&&!!this.#eT?.isSignedOut())};#ta=()=>"production"!==this.#ez&&!this.isSatellite&&!!eX(eo);#to=async()=>{"development"===this.instanceType?await this.navigate(this.#tr()):"production"===this.instanceType&&await this.navigate(this.#tn())};#tl=(e,t)=>{let i;try{i=new URL(e)}catch{throw Error(`${t2} The signInUrl needs to have a absolute url format.`)}i.origin===t&&function(){throw Error(`${t2} The signInUrl needs to be on a different origin than your satellite application.`)}()};#tc=()=>{this.isSatellite&&("development"!==this.#ez||this.#eW.signInUrl||function(){throw Error(`${t2} Missing signInUrl. A satellite application needs to specify the signInUrl for development instances.`)}(),this.proxyUrl||this.domain||function(){throw Error(`${t2} Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl.`)}(),this.#eW.signInUrl&&this.#tl(this.#eW.signInUrl,window.location.origin))};#eY=async()=>{if(this.#eT=await sx.create(this,this.#eM,this.#ez,this.#eK),this.#tc(),this.#ts())return void await this.#to();if(this.#ta())return void await this.#te();this.#eB=(()=>{if(!m())return{onPageFocus:tm.lQ};let e=[];return window.addEventListener("focus",()=>{"visible"===document.visibilityState&&e.forEach(e=>e())}),{onPageFocus:t=>{e.push(t)}}})(),"u">typeof BroadcastChannel&&(this.#ex=new BroadcastChannel("clerk")),this.#td();let e=function(e=window.location.hostname){if(!e)return!1;let t=eW.get(e);void 0===t&&(t=ew.some(t=>e.startsWith("accounts.")&&e.endsWith(t))||eb.some(t=>e.endsWith(t)&&!e.endsWith(".clerk"+t)),eW.set(e,t));return t}(window?.location.hostname),t="development"===this.#ez&&!e,i=0,r=0;for(;r<2;){r++;try{let e=na.getInstance().fetch({touch:t}).then(e=>this.updateEnvironment(e)).catch(e=>{if(tB(e,"dev_browser_unauthenticated"))throw e;++i;let t=t3.getItem(tZ,null);t&&this.updateEnvironment(new na(t))}),r=async()=>{let e=new AbortController;return(0,tm.zc)(rz.getOrCreateInstance().fetch({abortSignal:e.signal}),7e3,e).then(e=>this.updateClient(e)).catch(async e=>{if(G(e))throw e;++i,this.#eT?.stopPollingForToken();try{let e=this.#tt(sF(this.#eT?.getSessionCookie()));e?.clearCache();let t=e?await (0,tm.zc)(e.getToken(),7e3).catch(()=>(e.clearCache(),this.#eT?.getSessionCookie())):this.#eT?.getSessionCookie();this.updateClient(sF(t))}finally{this.#eT?.startPollingForToken()}return rz.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(tm.lQ),null})},[n,s]=await (0,tm.vd)([e,r()]);if("rejected"===n.status)throw n.reason;if("rejected"===s.status){let e=s.reason;if(tB(e,"requires_captcha"))await r();else throw e}if(this.#eT?.setClientUatCookieForDevelopmentInstances(),await this.#th())return;break}catch(e){if(tB(e,"dev_browser_unauthenticated"))await this.#eT.handleUnauthenticatedDevBrowser();else if(!k())return void console.warn(e);else throw e}r>=2&&function(){throw Error(`${t2} Something went wrong initializing Clerk.`)}()}this.#eE=new sR(this),this.#eE.start(),this.#tu(),this.#tp(),this.#t_(),this.#eK.emit(A,i>0?"degraded":"ready")};shouldFallbackToCachedResources=()=>!!this.__internal_getCachedResources;#eZ=async()=>{let e,t,i=this.shouldFallbackToCachedResources()?1:void 0,r=0;try{[e,t]=await Promise.all([na.getInstance().fetch({touch:!1,fetchMaxTries:i}),rz.getOrCreateInstance().fetch({fetchMaxTries:i})])}catch(i){if((M(i)&&"network_error"===i.code||$(i)&&i.status>=500)&&this.shouldFallbackToCachedResources()){let i=await this.__internal_getCachedResources?.();e=new na(i?.environment),rz.clearInstance(),t=rz.getOrCreateInstance(i?.client),++r}else throw i}this.updateClient(t),this.updateEnvironment(e),this.#eK.emit(A,r>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,t]=await Promise.all([na.getInstance().fetch({touch:!1,fetchMaxTries:1}),rz.getOrCreateInstance().fetch({fetchMaxTries:1})]);this.updateClient(t),this.updateEnvironment(e),this.#ti()};#tt=e=>{if(e.lastActiveSessionId){let t=e.signedInSessions.find(t=>t.id===e.lastActiveSessionId);if(t)return t}return e.signedInSessions[0]||null};#td=()=>{m()&&(this.#eB?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#eJ>Date.now())&&(this.#eJ=Date.now()+5e3,this.#eW.touchSession&&this.#e2(this.session,"focus").catch(e=>{tS.warn("Session touch on page focus failed",{error:e},"clerk")}))}),this.#ex?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),rp.on(rd,()=>{this.#ex?.postMessage({type:"signout"})}),rp.on(rh,()=>{t3.setItem(tZ,this.environment?.__internal_toSnapshot(),864e5)}))};#e2=async(e,t="focus")=>{if(!e)return Promise.resolve();await e.touch({intent:t}).catch(e=>{if(X(e))this.handleUnauthenticated();else throw e})};__internal_lastEmittedResources;#ti=()=>{if(this.client){let e={client:this.client,session:this.session,user:this.user,organization:this.organization};for(let t of(this.__internal_lastEmittedResources=e,this.#eN))t(e)}};#e5=()=>{for(let e of this.#eD)e()};#e3=()=>{this.session=void 0,this.organization=void 0,this.user=void 0,this.#ti()};#tf=(e=this.session)=>(e?.user.organizationMemberships||[]).map(e=>e.organization).find(t=>t.id===e?.lastActiveOrganizationId)||null;#tm=(e=this.session)=>({session:e||null,organization:this.#tf(e),user:e?e.user:null});#eX=(e,t)=>{let{session:i,organization:r,user:n}=this.#tm(e);this.session=i,this.organization=r,this.user=n,t?.dangerouslySkipEmit||this.#ti()};#e4=(e,t=this.client)=>t?.signedInSessions.find(t=>t.id===e)||null;#tp=()=>{this.addListener(({session:e})=>{e?.actor&&this.#eR?.then(e=>e.ensureMounted()).then(e=>e.mountImpersonationFab())})};#t_=()=>{this.#eW.__internal_keyless_claimKeylessApplicationUrl&&this.#eR?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#eW.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#eW.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#eW.__internal_keyless_dismissPrompt}})})};#e7=(e,t,i)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let r=this.#eW[e]||this.environment.displayConfig[e];this.#e0()&&(r=this.#eW.signInUrl);let n=new eH(this.#eW,t).toSearchParams(),s=new URLSearchParams(i||{}),a=e$({base:r,hashPath:this.#e0()&&"signUpUrl"===e?"/create":"",hashSearchParams:[s,n]},{stringify:!0});return this.buildUrlWithAuth(a)};assertComponentsReady(e){if(!e)throw Error("Clerk was not loaded with Ui components")}#th=async()=>{var e;let t,i,r,n,s=new URLSearchParams(window.location.search).get("redirect_url"),a="production"===this.instanceType,o=null!==s&&(e=this.frontendApi,i=(t=new URL(s,eF)).pathname,r=eV.includes(i)||eq.includes(i),e===t.host&&r);if(a||!o)return!1;let l=this.session,c=this.#eW.signInUrl||this.environment?.displayConfig.signInUrl,d=c&&window.location.href.startsWith(c),h=this.#eW.signUpUrl||this.environment?.displayConfig.signUpUrl,u=h&&window.location.href.startsWith(h);return n=new URL(s,eF),(!eV.includes(n.pathname)||!!l||!d&&!u)&&(await this.navigate(this.buildUrlWithAuth(s)),!0)};#eQ=e=>{let t=e?.clerkUICtor??e?.clerkUiCtor,i=t?{...e?.ui,ClerkUI:t}:e?.ui;return{...af,...e,ui:i,allowedRedirectOrigins:function(e,t,i){if(Array.isArray(e)&&e.length)return e;let r=[];return"u">typeof window&&window.location&&r.push(window.location.origin),r.push(`https://${eL(t)}`),r.push(`https://*.${eL(t)}`),"development"===i&&r.push(`https://${t}`),r}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)}};#tu=()=>{try{eY(er),eY(eG),eY(ea),eY("__clerk_handshake"),eY("__clerk_handshake_nonce"),eY("__clerk_help")}catch{}};get #e6(){let e=e8;return this.#eW.allowedRedirectProtocols&&(e=e.concat(this.#eW.allowedRedirectProtocols)),e}__internal_windowNavigate=(e,t)=>{!function(e,t){if("string"==typeof e&&e9.test(function(e){let t=0;for(;t<e.length&&32>=e.charCodeAt(t);)t++;let i="";for(let r=t;r<e.length;r++){let t=e.charCodeAt(r);9!==t&&10!==t&&13!==t&&(i+=e[r])}return i}(e)))return console.warn(`Clerk: scheme-relative navigation to "${e}" is not allowed. Provide a same-origin path or an absolute URL.`);let i=new URL(e,window.location.href);(t?.allowedProtocols??e8).includes(i.protocol)?(window.dispatchEvent(new CustomEvent(e6)),window.location.href=i.href):console.warn(`Clerk: "${i.protocol}" is not a valid navigation protocol. Aborting navigation. If you think this is a mistake, please open an issue.`)}(e,{allowedProtocols:t?.useStaticAllowlistOnly?e8:this.#e6})};#eG(){return void 0!==this.client}}let ag=document.querySelector("script[data-clerk-publishable-key]")?.getAttribute("data-clerk-publishable-key")||window.__clerk_publishable_key||"",ay=document.querySelector("script[data-clerk-proxy-url]")?.getAttribute("data-clerk-proxy-url")||window.__clerk_proxy_url||"",aw=document.querySelector("script[data-clerk-domain]")?.getAttribute("data-clerk-domain")||window.__clerk_domain||"";window.Clerk||(window.Clerk=new am(ag,{proxyUrl:ay,domain:aw}))},8388(e,t,i){"use strict";var r=this&&this.__awaiter||function(e,t,i,r){return new(i||(i=Promise))(function(n,s){function a(e){try{l(r.next(e))}catch(e){s(e)}}function o(e){try{l(r.throw(e))}catch(e){s(e)}}function l(e){e.done?n(e.value):new i(function(t){t(e.value)}).then(a,o)}l((r=r.apply(e,t||[])).next())})},n=this&&this.__generator||function(e,t){var i,r,n,s,a={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(s){return function(o){var l=[s,o];if(i)throw TypeError("Generator is already executing.");for(;a;)try{if(i=1,r&&(n=2&l[0]?r.return:l[0]?r.throw||((n=r.return)&&n.call(r),0):r.next)&&!(n=n.call(r,l[1])).done)return n;switch(r=0,n&&(l=[2&l[0],n.value]),l[0]){case 0:case 1:n=l;break;case 4:return a.label++,{value:l[1],done:!1};case 5:a.label++,r=l[1],l=[0];continue;case 7:l=a.ops.pop(),a.trys.pop();continue;default:if(!(n=(n=a.trys).length>0&&n[n.length-1])&&(6===l[0]||2===l[0])){a=0;continue}if(3===l[0]&&(!n||l[1]>n[0]&&l[1]<n[3])){a.label=l[1];break}if(6===l[0]&&a.label<n[1]){a.label=n[1],n=l;break}if(n&&a.label<n[2]){a.label=n[2],a.ops.push(l);break}n[2]&&a.ops.pop(),a.trys.pop();continue}l=t.call(e,a)}catch(e){l=[6,e],r=0}finally{i=n=0}if(5&l[0])throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}},s=this;Object.defineProperty(t,"__esModule",{value:!0});var a=i(8058),o="browser-tabs-lock-key",l={key:function(e){return r(s,void 0,void 0,function(){return n(this,function(e){throw Error("Unsupported")})})},getItem:function(e){return r(s,void 0,void 0,function(){return n(this,function(e){throw Error("Unsupported")})})},clear:function(){return r(s,void 0,void 0,function(){return n(this,function(e){return[2,window.localStorage.clear()]})})},removeItem:function(e){return r(s,void 0,void 0,function(){return n(this,function(e){throw Error("Unsupported")})})},setItem:function(e,t){return r(s,void 0,void 0,function(){return n(this,function(e){throw Error("Unsupported")})})},keySync:function(e){return window.localStorage.key(e)},getItemSync:function(e){return window.localStorage.getItem(e)},clearSync:function(){return window.localStorage.clear()},removeItemSync:function(e){return window.localStorage.removeItem(e)},setItemSync:function(e,t){return window.localStorage.setItem(e,t)}};function c(e){return new Promise(function(t){return setTimeout(t,e)})}function d(e){for(var t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",i="",r=0;r<e;r++){var n=Math.floor(Math.random()*t.length);i+=t[n]}return i}t.default=function(){function e(t){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+d(15),this.acquireLock=this.acquireLock.bind(this),this.releaseLock=this.releaseLock.bind(this),this.releaseLock__private__=this.releaseLock__private__.bind(this),this.waitForSomethingToChange=this.waitForSomethingToChange.bind(this),this.refreshLockWhileAcquired=this.refreshLockWhileAcquired.bind(this),this.storageHandler=t,void 0===e.waiters&&(e.waiters=[])}return e.prototype.acquireLock=function(t,i){return void 0===i&&(i=5e3),r(this,void 0,void 0,function(){var r,s,a,h,u,p,_;return n(this,function(n){switch(n.label){case 0:r=Date.now()+d(4),s=Date.now()+i,a=o+"-"+t,h=void 0===this.storageHandler?l:this.storageHandler,n.label=1;case 1:if(!(Date.now()<s))return[3,8];return[4,c(30)];case 2:if(n.sent(),null!==h.getItemSync(a))return[3,5];return u=this.id+"-"+t+"-"+r,[4,c(Math.floor(25*Math.random()))];case 3:return n.sent(),h.setItemSync(a,JSON.stringify({id:this.id,iat:r,timeoutKey:u,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,c(30)];case 4:if(n.sent(),null!==(p=h.getItemSync(a))&&(_=JSON.parse(p)).id===this.id&&_.iat===r)return this.acquiredIatSet.add(r),this.refreshLockWhileAcquired(a,r),[2,!0];return[3,7];case 5:return e.lockCorrector(void 0===this.storageHandler?l:this.storageHandler),[4,this.waitForSomethingToChange(s)];case 6:n.sent(),n.label=7;case 7:return r=Date.now()+d(4),[3,1];case 8:return[2,!1]}})})},e.prototype.refreshLockWhileAcquired=function(e,t){return r(this,void 0,void 0,function(){var i=this;return n(this,function(s){return setTimeout(function(){return r(i,void 0,void 0,function(){var i,r,s;return n(this,function(n){switch(n.label){case 0:return[4,a.default().lock(t)];case 1:if(n.sent(),!this.acquiredIatSet.has(t)||null===(r=(i=void 0===this.storageHandler?l:this.storageHandler).getItemSync(e)))return a.default().unlock(t),[2];return(s=JSON.parse(r)).timeRefreshed=Date.now(),i.setItemSync(e,JSON.stringify(s)),a.default().unlock(t),this.refreshLockWhileAcquired(e,t),[2]}})})},1e3),[2]})})},e.prototype.waitForSomethingToChange=function(t){return r(this,void 0,void 0,function(){return n(this,function(i){switch(i.label){case 0:return[4,new Promise(function(i){var r=!1,n=Date.now(),s=!1;function a(){if(s||(window.removeEventListener("storage",a),e.removeFromWaiting(a),clearTimeout(o),s=!0),!r){r=!0;var t=50-(Date.now()-n);t>0?setTimeout(i,t):i(null)}}window.addEventListener("storage",a),e.addToWaiting(a);var o=setTimeout(a,Math.max(0,t-Date.now()))})];case 1:return i.sent(),[2]}})})},e.addToWaiting=function(t){this.removeFromWaiting(t),void 0!==e.waiters&&e.waiters.push(t)},e.removeFromWaiting=function(t){void 0!==e.waiters&&(e.waiters=e.waiters.filter(function(e){return e!==t}))},e.notifyWaiters=function(){void 0!==e.waiters&&e.waiters.slice().forEach(function(e){return e()})},e.prototype.releaseLock=function(e){return r(this,void 0,void 0,function(){return n(this,function(t){switch(t.label){case 0:return[4,this.releaseLock__private__(e)];case 1:return[2,t.sent()]}})})},e.prototype.releaseLock__private__=function(t){return r(this,void 0,void 0,function(){var i,r,s,c;return n(this,function(n){switch(n.label){case 0:if(i=void 0===this.storageHandler?l:this.storageHandler,r=o+"-"+t,null===(s=i.getItemSync(r)))return[2];if((c=JSON.parse(s)).id!==this.id)return[3,2];return[4,a.default().lock(c.iat)];case 1:n.sent(),this.acquiredIatSet.delete(c.iat),i.removeItemSync(r),a.default().unlock(c.iat),e.notifyWaiters(),n.label=2;case 2:return[2]}})})},e.lockCorrector=function(t){for(var i=Date.now()-5e3,r=[],n=0;;){var s=t.keySync(n);if(null===s)break;r.push(s),n++}for(var a=!1,l=0;l<r.length;l++){var c=r[l];if(c.includes(o)){var d=t.getItemSync(c);if(null!==d){var h=JSON.parse(d);(void 0===h.timeRefreshed&&h.timeAcquired<i||void 0!==h.timeRefreshed&&h.timeRefreshed<i)&&(t.removeItemSync(c),a=!0)}}}a&&e.notifyWaiters()},e.waiters=void 0,e}()},8058(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(){var e=this;this.locked=new Map,this.addToLocked=function(t,i){var r=e.locked.get(t);void 0===r?void 0===i?e.locked.set(t,[]):e.locked.set(t,[i]):void 0!==i&&(r.unshift(i),e.locked.set(t,r))},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise(function(i,r){e.isLocked(t)?e.addToLocked(t,i):(e.addToLocked(t),i())})},this.unlock=function(t){var i=e.locked.get(t);if(void 0===i||0===i.length)return void e.locked.delete(t);var r=i.pop();e.locked.set(t,i),void 0!==r&&setTimeout(r,0)}}return e.getInstance=function(){return void 0===e.instance&&(e.instance=new e),e.instance},e}();t.default=function(){return i.getInstance()}},547(e){e.exports=function(e,t){if("string"!=typeof e)throw TypeError("Expected a string");for(var i,r=String(e),n="",s=!!t&&!!t.extended,a=!!t&&!!t.globstar,o=!1,l=t&&"string"==typeof t.flags?t.flags:"",c=0,d=r.length;c<d;c++)switch(i=r[c]){case"/":case"$":case"^":case"+":case".":case"(":case")":case"=":case"!":case"|":n+="\\"+i;break;case"?":if(s){n+=".";break}case"[":case"]":if(s){n+=i;break}case"{":if(s){o=!0,n+="(";break}case"}":if(s){o=!1,n+=")";break}case",":if(o){n+="|";break}n+="\\"+i;break;case"*":for(var h=r[c-1],u=1;"*"===r[c+1];)u++,c++;var p=r[c+1];a?u>1&&("/"===h||void 0===h)&&("/"===p||void 0===p)?(n+="((?:[^/]*(?:/|$))*)",c++):n+="([^/]*)":n+=".*";break;default:n+=i}return l&&~l.indexOf("g")||(n="^"+n+"$"),new RegExp(n,l)}},8591(e,t,i){"use strict";i.d(t,{},{t:(...e)=>{}})},6100(e,t,i){"use strict";function r(e,t,i){return"function"==typeof e?e(t):void 0!==e?e:void 0!==i?i:void 0}i.d(t,{vd:()=>s,VK:()=>r,lQ:()=>n.t,zc:()=>a});var n=i(8591);function s(e){return Promise.all(Array.from(e).map(e=>e.then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))}function a(e,t,i){let r,n=new Promise((e,n)=>{r=setTimeout(()=>{let e=Error(`Timed out after ${t}ms`);i?.abort(),n(e)},t),r.unref?.()});return Promise.race([Promise.resolve(e),n]).finally(()=>{clearTimeout(r)})}}},n={};function s(e){var t=n[e];if(void 0!==t)return t.exports;var i=n[e]={exports:{}};return r[e].call(i.exports,i,i.exports,s),i.exports}s.m=r,s.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return s.d(t,{a:t}),t},o=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,s.t=function(e,t){if(1&t&&(e=this(e)),8&t||"object"==typeof e&&e&&(4&t&&e.__esModule||16&t&&"function"==typeof e.then))return e;var i=Object.create(null);s.r(i);var r={};a=a||[null,o({}),o([]),o(o)];for(var n=2&t&&e;("object"==typeof n||"function"==typeof n)&&!~a.indexOf(n);n=o(n))Object.getOwnPropertyNames(n).forEach(t=>{r[t]=()=>e[t]});return r.default=()=>e,s.d(i,r),i},s.d=(e,t,i)=>{var r=(t,i)=>{for(var r in t)s.o(t,r)&&!s.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,[i]:t[r]})};r(t,"get"),r(i,"value")},s.f={},s.e=e=>Promise.all(Object.keys(s.f).reduce((t,i)=>(s.f[i](e,t),t),[])),s.u=e=>""+(({279:"stripe-vendors",545:"vendors",662:"query-core-vendors",729:"zxcvbn-ts-core",811:"cookieSuffix",873:"zxcvbn-common",929:"coinbase-wallet-sdk",994:"base-account-sdk"})[e]||e)+"_clerk.browser_"+s.h().slice(0,6)+"_6.42.0-canary.v20261027184321.js",s.h=()=>"e6082383adcc81ed",s.g=(()=>{if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}})(),s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),l={},s.l=function(e,t,i,r){if(l[e])return void l[e].push(t);if(void 0!==i)for(var n,a,o=document.getElementsByTagName("script"),c=0;c<o.length;c++){var d=o[c];if(d.getAttribute("src")==e||d.getAttribute("data-rspack")=="@clerk/clerk-js:"+i){n=d;break}}n||(a=!0,(n=document.createElement("script")).timeout=120,s.nc&&n.setAttribute("nonce",s.nc),n.setAttribute("data-rspack","@clerk/clerk-js:"+i),n.src=e),l[e]=[t];var h=function(t,i){n.onerror=n.onload=null,clearTimeout(u);var r=l[e];if(delete l[e],n.parentNode&&n.parentNode.removeChild(n),r&&r.forEach(function(e){return e(i)}),t)return t(i)},u=setTimeout(h.bind(null,void 0,{type:"timeout",target:n}),12e4);n.onerror=h.bind(null,n.onerror),n.onload=h.bind(null,n.onload),a&&document.head.appendChild(n)},s.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.g.importScripts&&(c=s.g.location+"");var a,o,l,c,d=s.g.document;if(!c&&d&&(d.currentScript&&"SCRIPT"===d.currentScript.tagName.toUpperCase()&&(c=d.currentScript.src),!c)){var h=d.getElementsByTagName("script");if(h.length)for(var u=h.length-1;u>-1&&(!c||!/^http(s?):/.test(c));)c=h[u--].src}if(!c)throw Error("Automatic publicPath is not supported in this browser");return s.p=c=c.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),e={349:0},s.f.j=function(t,i){var r=s.o(e,t)?e[t]:void 0;if(0!==r)if(r)i.push(r[2]);else{var n=new Promise((i,n)=>r=e[t]=[i,n]);i.push(r[2]=n);var a=s.p+s.u(t),o=Error();s.l(a,function(i){if(s.o(e,t)&&(0!==(r=e[t])&&(e[t]=void 0),r)){var n=i&&("load"===i.type?"missing":i.type),a=i&&i.target&&i.target.src;o.message="Loading chunk "+t+" failed.\n("+n+": "+a+")",o.name="ChunkLoadError",o.type=n,o.request=a,r[1](o)}},"chunk-"+t,t)}},t=(t,i)=>{var r,n,[a,o,l]=i,c=0;if(a.some(t=>0!==e[t])){for(r in o)s.o(o,r)&&(s.m[r]=o[r]);l&&l(s)}for(t&&t(i);c<a.length;c++)n=a[c],s.o(e,n)&&e[n]&&e[n][0](),e[n]=0},(i=globalThis.rspackChunk_clerk_clerk_js=globalThis.rspackChunk_clerk_clerk_js||[]).forEach(t.bind(null,0)),i.push=t.bind(null,i.push.bind(i)),s(292)})());
|
|
46
|
+
API Error: ${n}`,{data:t,status:e})}}(s,e);let r={data:e,status:s};if(429===s&&o){let e=o.get("retry-after");if(e){let t=parseInt(e,10);isNaN(t)||(r.retryAfter=t)}}throw new L(t||a,r)}return null}static _updateClient(e){let t=rM(e);t&&iu.clerk&&iu.clerk.updateClient(t)}path(e){let t=this.pathRoot;if(this.isNew())return t;let i=t.replace(/[^/]$/,"$&/")+encodeURIComponent(this.id);return e?i.replace(/[^/]$/,"$&/")+encodeURIComponent(e):i}withDefault(e,t){return e??t}async _baseGet(e={}){let t=await iu._fetch({method:"GET",path:this.path(),rotatingTokenNonce:e.rotatingTokenNonce,signal:e.abortSignal},e);return this.fromJSON(t?.response||t)}async _baseMutate(e){let{action:t,body:i,method:r,path:n,signal:s}=e,a=await iu._fetch({method:r,path:n||this.path(t),body:i,signal:s});return this.fromJSON(a?.response||a)}async _baseMutateBypass(e){let{action:t,body:i,method:r,path:n}=e,s=await iu._baseFetch({method:r,path:n||this.path(t),body:i});return this.fromJSON(s?.response||s)}async _basePost(e={}){if(!e.coalesce)return this._baseMutate({...e,method:"POST"});let t=this.#W(e),i=this.#D??=new Map,r=i.get(t);if(r&&Date.now()<r.expiresAt)return r.promise;let n=new AbortController,s=this._baseMutate({...e,method:"POST",signal:n.signal}).finally(()=>{i.get(t)?.promise===s&&i.delete(t)});return i.set(t,{promise:s,controller:n,expiresAt:Date.now()+3e4}),s}#W(e){let t=Object.entries(e.body??{}).filter(([,e])=>void 0!==e).sort(([e],[t])=>e<t?-1:1);return JSON.stringify([this.id,e.path,e.action,t])}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=iu.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}class ip extends iu{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?tE(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?tE(e.last_used_at):null,this.updatedAt=tE(e.updated_at),this.createdAt=tE(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 i_ extends iu{claimedAt=null;reverification=!1;singleSessionMode=!1;preferredChannels=null;sessionMinter=!1;nativeSettings=null;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){var t;return e&&(this.claimedAt=this.withDefault(e.claimed_at?tE(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.sessionMinter=this.withDefault(e.session_minter,this.sessionMinter),this.nativeSettings=this.withDefault((t=e.native_settings)?{apiEnabled:t.api_enabled,trustedDeviceSignInEnabled:t.trusted_device_sign_in_enabled,trustedDeviceEnrollmentPromptAfterSignInEnabled:t.trusted_device_enrollment_prompt_after_sign_in_enabled,trustedDeviceEnrollmentPromptAfterSignUpEnabled:t.trusted_device_enrollment_prompt_after_sign_up_enabled}:null,this.nativeSettings)),this}__internal_toSnapshot(){var e;return{claimed_at:this.claimedAt?this.claimedAt.getTime():null,id:this.id??"",object:"auth_config",reverification:this.reverification,single_session_mode:this.singleSessionMode,session_minter:this.sessionMinter,native_settings:(e=this.nativeSettings)?{object:"native_settings",api_enabled:e.apiEnabled,trusted_device_sign_in_enabled:e.trustedDeviceSignInEnabled,trusted_device_enrollment_prompt_after_sign_in_enabled:e.trustedDeviceEnrollmentPromptAfterSignInEnabled,trusted_device_enrollment_prompt_after_sign_up_enabled:e.trustedDeviceEnrollmentPromptAfterSignUpEnabled}:null}}}(T=E||(E={}))[T.None=0]="None",T[T.Mutable=1]="Mutable",T[T.Watching=2]="Watching",T[T.RecursedCheck=4]="RecursedCheck",T[T.Recursed=8]="Recursed",T[T.Dirty=16]="Dirty",T[T.Pending=32]="Pending";let im=[],{link:ig,unlink:iy,propagate:iw,checkDirty:ib,endTracking:iv,startTracking:ik,shallowPropagate:iS}=function({update:e,notify:t,unwatched:i}){let r=0;return{link:function(e,t){let i,n=t.depsTail;if(void 0!==n&&n.dep===e)return;if(4&t.flags&&void 0!==(i=void 0!==n?n.nextDep:t.deps)&&i.dep===e){i.version=r,t.depsTail=i;return}let s=e.subsTail;if(void 0!==s&&s.version===r&&s.sub===t)return;let a=t.depsTail=e.subsTail={version:r,dep:e,sub:t,prevDep:n,nextDep:i,prevSub:s,nextSub:void 0};void 0!==i&&(i.prevDep=a),void 0!==n?n.nextDep=a:t.deps=a,void 0!==s?s.nextSub=a:e.subs=a},unlink:n,propagate:function(e){let i,r=e.nextSub;e:for(;;){let n=e.sub,s=n.flags;if(3&s&&(60&s?12&s?4&s?!(48&s)&&function(e,t){let i=t.depsTail;if(void 0!==i){let r=t.deps;do{if(r===e)return!0;if(r===i)break;r=r.nextDep}while(void 0!==r)}return!1}(e,n)?(n.flags=40|s,s&=1):s=0:n.flags=-9&s|32:s=0:n.flags=32|s,2&s&&t(n),1&s)){let t=n.subs;if(void 0!==t){e=t,void 0!==t.nextSub&&(i={value:r,prev:i},r=e.nextSub);continue}}if(void 0!==(e=r)){r=e.nextSub;continue}for(;void 0!==i;)if(e=i.value,i=i.prev,void 0!==e){r=e.nextSub;continue e}break}},checkDirty:function(t,i){let r,n=0;e:for(;;){let a=t.dep,o=a.flags,l=!1;if(16&i.flags)l=!0;else if((17&o)==17){if(e(a)){let e=a.subs;void 0!==e.nextSub&&s(e),l=!0}}else if((33&o)==33){(void 0!==t.nextSub||void 0!==t.prevSub)&&(r={value:t,prev:r}),t=a.deps,i=a,++n;continue}if(!l&&void 0!==t.nextDep){t=t.nextDep;continue}for(;n;){--n;let a=i.subs,o=void 0!==a.nextSub;if(o?(t=r.value,r=r.prev):t=a,l){if(e(i)){o&&s(a),i=t.sub;continue}}else i.flags&=-33;if(i=t.sub,void 0!==t.nextDep){t=t.nextDep;continue e}l=!1}return l}},endTracking:function(e){let t=e.depsTail,i=void 0!==t?t.nextDep:e.deps;for(;void 0!==i;)i=n(i,e);e.flags&=-5},startTracking:function(e){++r,e.depsTail=void 0,e.flags=-57&e.flags|4},shallowPropagate:s};function n(e,t=e.sub){let r=e.dep,s=e.prevDep,a=e.nextDep,o=e.nextSub,l=e.prevSub;return void 0!==a?a.prevDep=s:t.depsTail=s,void 0!==s?s.nextDep=a:t.deps=a,void 0!==o?o.prevSub=l:r.subsTail=l,void 0!==l?l.nextSub=o:void 0===(r.subs=o)&&i(r),a}function s(e){do{let i=e.sub,r=e.nextSub,n=i.flags;(48&n)==32&&(i.flags=16|n,2&n&&t(i)),e=r}while(void 0!==e)}}({update:e=>"getter"in e?iE(e):ix(e,e.value),notify:function e(t){let i=t.flags;if(!(64&i)){t.flags=64|i;let r=t.subs;void 0!==r?e(r.sub):im[iU++]=t}},unwatched(e){if("getter"in e){let t=e.deps;if(void 0!==t){e.flags=17;do t=iy(t,e);while(void 0!==t)}}else"previousValue"in e||iF.call(e)}}),iI=0,iC=0,iU=0;function iA(e){let t=r;return r=e,t}function iP(e){return iz.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function iT(e){return iM.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function iO(e){let t={fn:e,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==r?ig(t,r):void 0!==n&&ig(t,n);let i=iA(t);try{t.fn()}finally{iA(i)}return iF.bind(t)}function iE(e){let t=iA(e);ik(e);try{let t=e.value;return t!==(e.value=e.getter(t))}finally{iA(t),iv(e)}}function ix(e,t){return e.flags=1,e.previousValue!==(e.previousValue=t)}function iR(){for(;iC<iU;){let e=im[iC];im[iC++]=void 0,function e(t,i){if(16&i||32&i&&ib(t.deps,t)){let e=iA(t);ik(t);try{t.fn()}finally{iA(e),iv(t)}return}32&i&&(t.flags=-33&i);let r=t.deps;for(;void 0!==r;){let t=r.dep,i=t.flags;64&i&&e(t,t.flags=-65&i),r=r.nextDep}}(e,e.flags&=-65)}iC=0,iU=0}function iM(){let e=this.flags;if(16&e||32&e&&ib(this.deps,this)){if(iE(this)){let e=this.subs;void 0!==e&&iS(e)}}else 32&e&&(this.flags=-33&e);return void 0!==r?ig(this,r):void 0!==n&&ig(this,n),this.value}function iz(...e){if(e.length){let t=e[0];if(this.value!==(this.value=t)){this.flags=17;let e=this.subs;void 0!==e&&(iw(e),iI||iR())}}else{let e=this.value;if(16&this.flags&&ix(this,e)){let e=this.subs;void 0!==e&&iS(e)}return void 0!==r&&ig(this,r),e}}function iF(){let e=this.deps;for(;void 0!==e;)e=iy(e,this);let t=this.subs;void 0!==t&&iy(t),this.flags=0}function iN(e){let{pageSize:t,initialPage:i,...r}=e||{},n=t??10;return new URLSearchParams({...Object.entries(r).reduce((e,[t,i])=>(void 0!==i&&(e[t]=i),e),{}),limit:n+"",offset:((i??1)-1)*n+""})}class iD{static #L="/billing";static path(e,t){let{orgId:i}=t||{},r=i?`/organizations/${i}`:"/me";return`${r}${iD.#L}${e}`}getPlans=async e=>{let{for:t,orgId:i,minSeats:r,...n}=e||{},s={...n,payer_type:"organization"===t?"org":"user",org_id:i,min_seats:r};return await iu._fetch({path:`${iD.#L}/plans`,method:"GET",search:iN(s)}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new re(e))}})};getPlan=async e=>new re(await iu._fetch({path:`${iD.#L}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await iu._fetch({path:iD.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new rr(e?.response));getStatements=async e=>{let{orgId:t,...i}=e;return await iu._fetch({path:iD.path("/statements",{orgId:t}),method:"GET",search:iN(i)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new rt(e))}})};getStatement=async e=>new rt((await iu._fetch({path:iD.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:t,...i}=e;return await iu._fetch({path:iD.path("/payment_attempts",{orgId:t}),method:"GET",search:iN(i)}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new i2(e))}})};getPaymentAttempt=async e=>new i2(await iu._fetch({path:iD.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:t,...i}=e;return new iZ((await iu._fetch({path:iD.path("/checkouts",{orgId:t}),method:"POST",body:i}))?.response)};updateCheckout=async e=>{let{id:t,orgId:i,...r}=e;return new iZ((await iu._fetch({path:iD.path(`/checkouts/${t}`,{orgId:i}),method:"PATCH",body:r}))?.response)};getCreditBalance=async e=>await iu._fetch({path:iD.path("/credits",{orgId:e.orgId}),method:"GET"}).then(e=>new i1(e?.response));getCreditHistory=async e=>await iu._fetch({path:iD.path("/credits/history",{orgId:e.orgId}),method:"GET"}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new i3(e))}})}let iW=iP({resource:null}),iL=iP({error:null}),i$=iP({status:"idle"}),ij=iT(()=>{let e=iW().resource,t=iL().error,i=i$().status;return{errors:iX(t,{identifier:null,password:null,code:null}),fetchStatus:i,signIn:e?e.__internal_future:null}}),iB=iP({resource:null}),iJ=iP({error:null}),iK=iP({status:"idle"}),iV=iT(()=>{let e=iB().resource,t=iJ().error,i=iK().status;return{errors:iX(t,{firstName:null,lastName:null,emailAddress:null,phoneNumber:null,password:null,username:null,code:null,captcha:null,legalAccepted:null}),fetchStatus:i,signUp:e?e.__internal_future:null}}),iq=iP({resource:null}),iH=iP({error:null}),iG=iP({status:"idle"}),iQ=iT(()=>{let e=iq().resource,t=iH().error,i=iG().status;return{errors:iX(t,{emailAddress:null}),fetchStatus:i,waitlist:e}});function iX(e,t){let i={fields:{...t},raw:null,global:null};if(!e)return i;if(!$(e))return i.raw=[e],i.global=[Y(e)],i;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(i.raw?i.raw.push(e):i.raw=[e],r(e)){let t=eh(e.meta.paramName);t in i.fields&&(i.fields[t]=e)}}):(i.raw=[e],i.global=[Y(e)]),i}class iY extends iu{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=tE(e.created_at)),e.updated_at&&(this.updatedAt=tE(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 iZ extends iu{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 i9(e.payment_method):void 0,this.plan=new re(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=tL(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change,e.free_trial_ends_at&&(this.freeTrialEndsAt=tE(e.free_trial_ends_at)),this.payer=new iY(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>tA(()=>this._basePatch({path:iD.path(`/checkouts/${this.id}/confirm`,{orgId:this.payer.organizationId}),body:e}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,t){if(!$(e)||t>=4)return!1;let i=e?.status,r=409===i&&e.errors?.[0]?.code==="checkout_already_in_progress";return i>=500||r}})}class i0{resource=new iZ(null);config;signals;pendingOperations=new Map;constructor(e,t){this.config=t,this.signals=e,this.signals.resourceSignal({resource:this})}get status(){return this.resource.status??"needs_initialization"}get externalClientSecret(){return this.resource.externalClientSecret}get externalGatewayId(){return this.resource.externalGatewayId}get plan(){return this.resource.plan}get planPeriod(){return this.resource.planPeriod}get totals(){return this.resource.totals}get isImmediatePlanChange(){return this.resource.isImmediatePlanChange}get freeTrialEndsAt(){return this.resource.freeTrialEndsAt}get payer(){return this.resource.payer}get paymentMethod(){return this.resource.paymentMethod??null}get planPeriodStart(){return this.resource.planPeriodStart}get needsPaymentMethod(){return this.resource.needsPaymentMethod}async start(){return this.runAsyncCheckoutTask("start",async()=>{let e=await iZ.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new iZ(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 update(e){if(!this.resource.id)throw Error("Clerk: `start()` must be called before `update()`");return this.runAsyncCheckoutTask("update",async()=>{this.resource=await iZ.clerk.billing?.updateCheckout({id:this.resource.id,orgId:this.resource.payer.organizationId||void 0,...e})},void 0,!1)}async finalize(e){let{navigate:t}=e||{};return this.runAsyncCheckoutTask("finalize",async()=>{if("completed"!==this.resource.status)throw Error("Clerk: `confirm()` must be called before `finalize()`");await iZ.clerk.setActive({session:iZ.clerk.session?.id,navigate:t})})}runAsyncCheckoutTask(e,t,i,r=!0){var n,s,a;return void 0===iZ.clerk.user?(console.warn("Clerk: Checkout operations cannot be performed during transitive state"),{error:null}):(n=this,s=this.signals,a=this.pendingOperations,async(e,t,i,r=!0)=>{if(a.get(e))return a.get(e);let o=(async()=>{++iI,s.errorSignal({error:null}),s.fetchSignal({status:"fetching"}),i?.(),--iI||iR(),++iI;try{return await t(),s.resourceSignal({resource:n}),{error:null}}catch(e){return r&&s.errorSignal({error:e}),{error:e}}finally{a.delete(e),s.fetchSignal({status:"idle"}),--iI||iR()}})();return a.set(e,o),o})(e,t,i,r)}}class i1{balance;constructor(e){this.balance=e.balance?tx(e.balance):null}}class i3 extends iu{id;amount;sourceType;sourceId;createdAt;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.amount=tx(e.amount),this.sourceType=e.source_type,this.sourceId=e.source_id,this.createdAt=tE(e.created_at)),this}}class i2 extends iu{id;amount;failedAt=null;paidAt=null;updatedAt;paymentMethod=null;subscriptionItem;chargeType;status;totals=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){let t;return e?(this.id=e.id,this.amount=tx(e.amount),this.paidAt=e.paid_at?tE(e.paid_at):null,this.failedAt=e.failed_at?tE(e.failed_at):null,this.updatedAt=tE(e.updated_at),this.paymentMethod=e.payment_method?new i9(e.payment_method):null,this.subscriptionItem=new rn(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status,this.totals=e.totals?{subtotal:tx((t=e.totals).subtotal),grandTotal:tx(t.grand_total),taxTotal:tx(t.tax_total),baseFee:t.base_fee?tx(t.base_fee):null,perUnitTotals:t.per_unit_totals?tM(t.per_unit_totals):void 0,discounts:t.discounts?tN(t.discounts):null}:null,this):this}}let i4="/payment_methods",i5=async e=>{let{orgId:t,...i}=e;return new i7((await iu._fetch({path:iD.path(`${i4}/initialize`,{orgId:t}),method:"POST",body:i}))?.response)},i6=async e=>{let{orgId:t,...i}=e;return new i9((await iu._fetch({path:iD.path(i4,{orgId:t}),method:"POST",body:i}))?.response)},i8=async e=>{let{orgId:t,...i}=e??{};return await iu._fetch({path:iD.path(i4,{orgId:t}),method:"GET",search:iN(i)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new i9(e))}})};class i9 extends iu{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:tE(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:tE(e.updated_at)),this}async remove(e){let{orgId:t}=e??{};return new rN((await iu._fetch({path:iD.path(`/payment_methods/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:t}=e??{};return await iu._fetch({path:iD.path("/payers/default_payment_method",{orgId:t}),method:"PUT",body:{payment_method_id:this.id}}),null}}class i7 extends iu{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 re extends iu{id;name;fee=null;annualFee=null;annualMonthlyFee=null;description=null;isDefault;isRecurring;hasBaseFee;forPayerType;publiclyVisible;slug;avatarUrl=null;features;unitPrices;availablePrices;freeTrialDays;freeTrialEnabled;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.fee=e.fee?tx(e.fee):null,this.annualFee=e.annual_fee?tx(e.annual_fee):null,this.annualMonthlyFee=e.annual_monthly_fee?tx(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 nl(e)),this.unitPrices=e.unit_prices?.map(tz),this.availablePrices=e.available_prices?.map(e=>({id:e.id,fee:e.fee?tx(e.fee):null,annualMonthlyFee:e.annual_monthly_fee?tx(e.annual_monthly_fee):null,isDefault:e.is_default,unitPrices:e.unit_prices?.map(tz)}))),this}}class rt extends iu{id;status;timestamp;totals;groups;constructor(e){super(),this.fromJSON(e)}fromJSON(e){var t;let i;return e?(this.id=e.id,this.status=e.status,this.timestamp=tE(e.timestamp),this.totals=(i={grandTotal:tx((t=e.totals).grand_total),subtotal:tx(t.subtotal),taxTotal:tx(t.tax_total)},"base_fee"in t&&t.base_fee&&(i.baseFee=tx(t.base_fee)),"past_due"in t&&(i.pastDue=t.past_due?tx(t.past_due):null),"credit"in t&&(i.credit=t.credit?tx(t.credit):null),"per_unit_totals"in t&&(i.perUnitTotals=t.per_unit_totals?tM(t.per_unit_totals):void 0),"credits"in t&&(i.credits=t.credits?tF(t.credits):null),"total_due_now"in t&&(i.totalDueNow=tx(t.total_due_now)),"total_due_after_free_trial"in t&&(i.totalDueAfterFreeTrial=t.total_due_after_free_trial?tx(t.total_due_after_free_trial):null),"discounts"in t&&(i.discounts=t.discounts?tN(t.discounts):null),"total_due_per_period"in t&&t.total_due_per_period&&(i.totalDuePerPeriod=tx(t.total_due_per_period)),"totals_due_per_period"in t&&t.totals_due_per_period&&(i.totalsDuePerPeriod=tW(t.totals_due_per_period)),i),this.groups=e.groups.map(e=>new ri(e)),this):this}}class ri{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=tE(e.timestamp),this.items=e.items.map(e=>new i2(e))),this}}class rr extends iu{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=tE(e.created_at),this.updatedAt=e.updated_at?tE(e.updated_at):null,this.activeAt=tE(e.active_at),this.pastDueAt=e.past_due_at?tE(e.past_due_at):null,this.nextPayment=void 0===e.next_payment?void 0:null===e.next_payment?null:t$(e.next_payment),this.subscriptionItems=(e.subscription_items||[]).map(e=>new rn(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1),this):this}}class rn extends iu{id;plan;planPeriod;priceId;status;createdAt;periodStart;periodEnd;canceledAt;pastDueAt;amount;credit;seats;credits;appliedDiscount;nextPayment;isFreeTrial;constructor(e){super(),this.fromJSON(e)}fromJSON(e){let t;return e?(this.id=e.id,this.plan=new re(e.plan),this.planPeriod=e.plan_period,this.priceId=e.price_id,this.status=e.status,this.createdAt=tE(e.created_at),this.pastDueAt=e.past_due_at?tE(e.past_due_at):null,this.periodStart=tE(e.period_start),this.periodEnd=e.period_end?tE(e.period_end):null,this.canceledAt=e.canceled_at?tE(e.canceled_at):null,this.amount=e.amount?tx(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:tx(e.credit.amount)}:void 0,this.seats=e.seats?{quantity:e.seats.quantity,...e.seats.tiers?{tiers:e.seats.tiers.map(tR)}:{}}:void 0,this.credits=e.credits?tF(e.credits):void 0,this.appliedDiscount=e.applied_discount?{id:(t=e.applied_discount).id,subscriptionItemId:t.subscription_item_id,discountId:t.discount_id,name:t.name,source:t.source,promoCode:t.promo_code,effect:t.effect,percentOff:t.percent_off,amountOff:t.amount_off?tx(t.amount_off):void 0,amount:t.amount?tx(t.amount):void 0,cyclesRemaining:t.cycles_remaining,cyclesApplied:t.cycles_applied,status:t.status,redeemedAt:tE(t.redeemed_at),redeemedBy:t.redeemed_by}:void 0,this.nextPayment=void 0===e.next_payment?void 0:null===e.next_payment?null:t$(e.next_payment),this.isFreeTrial=this.withDefault(e.is_free_trial,!1),this):this}async cancel(e){let{orgId:t}=e;return new rN((await iu._fetch({path:iD.path(`/subscription_items/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}}function rs(e){return e?{challenge:e.challenge,challengeId:e.challenge_id,trustedDeviceId:e.trusted_device_id??null,clientData:e.client_data,expiresAt:e.expires_at?new Date(1e3*e.expires_at):null,algorithm:e.algorithm}:null}let ra="/me/biometric_credentials";function ro(e){let{publicKeyJwk:t,...i}=e;return{...i,publicKeyJwk:"string"==typeof t?t:JSON.stringify(t)}}class rl extends iu{id;pathRoot=ra;platform;appIdentifier;name=null;algorithm;status;lastUsedAt=null;revokedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async list(){return((await iu._fetch({path:ra,method:"GET"}))?.response||[]).map(e=>new rl(e))}static async prepare(e){return rs((await iu._fetch({path:`${ra}/prepare`,method:"POST",body:ro(e)}))?.response)}static async attempt(e){return new rl((await iu._fetch({path:`${ra}/attempt`,method:"POST",body:ro(e)}))?.response)}static async revoke(e){return new rl((await iu._fetch({path:`${ra}/${e}`,method:"DELETE"}))?.response)}fromJSON(e){return e&&(this.id=e.id,this.platform=e.platform,this.appIdentifier=e.app_identifier,this.name=e.name??null,this.algorithm=e.algorithm,this.status=e.status,this.lastUsedAt=e.last_used_at?tE(e.last_used_at):null,this.revokedAt=e.revoked_at?tE(e.revoked_at):null,this.createdAt=tE(e.created_at),this.updatedAt=tE(e.updated_at)),this}__internal_toSnapshot(){return{object:"trusted_device",id:this.id,platform:this.platform,app_identifier:this.appIdentifier,name:this.name,algorithm:this.algorithm,status:this.status,last_used_at:this.lastUsedAt?.getTime()??null,revoked_at:this.revokedAt?.getTime()??null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}let rc="token:update",rd="user:signOut",rh="environment:update",ru="session:tokenResolved",rp=U(),r_={build:(e,t,i)=>[e,t,i].filter(Boolean).join("-"),parse:(e,t,i)=>{let r=r_.extractTemplate(e,t,i);return{organizationId:i,sessionId:t,template:r}},extractTemplate:(e,t,i)=>{if(e===t||i&&e===`${t}-${i}`)return;let r=e.slice(t.length+1);return i&&r.endsWith(`-${i}`)&&(r=r.slice(0,-(i.length+1))),r||void 0}};var rf=i(8591),rm='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 rg=(e,t={})=>{if("u"<typeof Worker)return null;try{let i=new Blob([e],{type:"application/javascript; charset=utf-8"}),r=globalThis.URL.createObjectURL(i);return new Worker(r,t)}catch{return console.warn("Clerk: Cannot create worker from blob. Consider adding worker-src blob:; to your CSP"),null}},ry=()=>{let e=0,t=()=>e++,i=new Map,r=(e,t)=>e?.postMessage(t),n=e=>{i.get(e.data.id)?.()},s=rg(rm,{name:"clerk-timers"});if(s?.addEventListener("message",n),!s)return{setTimeout:globalThis.setTimeout.bind(globalThis),setInterval:globalThis.setInterval.bind(globalThis),clearTimeout:globalThis.clearTimeout.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis),cleanup:rf.t};let a=()=>{s||(s=rg(rm,{name:"clerk-timers"}),s?.addEventListener("message",n))};return{setTimeout:(e,n)=>{a();let o=t();return i.set(o,()=>{e(),i.delete(o)}),r(s,{type:"setTimeout",id:o,ms:n}),o},setInterval:(e,n)=>{a();let o=t();return i.set(o,e),r(s,{type:"setInterval",id:o,ms:n}),o},clearTimeout:e=>{a(),i.delete(e),r(s,{type:"clearTimeout",id:e})},clearInterval:e=>{a(),i.delete(e),r(s,{type:"clearInterval",id:e})},cleanup:()=>{s&&(s.terminate(),s=null,i.clear())}}};function rw(){if("u">typeof document)try{if("function"!=typeof document.hasFocus)return;return document.hasFocus()}catch{return}}var rb=i(8388),rv=i.n(rb);function rk(e){let t=new(rv());return{acquireLockAndRun:async i=>{if("locks"in navigator&&isSecureContext){let t=new AbortController,r=setTimeout(()=>t.abort(),4999);return await navigator.locks.request(e,{signal:t.signal},async()=>(clearTimeout(r),await i())).catch(()=>!1)}if(await t.acquireLock(e,5e3))try{return await i()}finally{await t.releaseLock(e)}}}}class rS{lock=rk("clerk.lock.refreshSessionToken");workerTimers=ry();timerId=null;initiated=!1;startPollingForSessionToken(e){if(this.timerId||this.initiated)return;let t=async()=>{this.initiated=!0,await this.lock.acquireLockAndRun(e);let i=!0===rw()?1500:5e3;this.timerId=this.workerTimers.setTimeout(t,i)};t()}stopPollingForSessionToken(){null!=this.timerId&&(this.workerTimers.clearTimeout(this.timerId),this.timerId=null),this.initiated=!1}}let rI="clerk";function rC(e){return"getRawString"in e?e.jwt:e}function rU(e,t){if(null==e)return t;let i=rC(e)?.header?.oiat,r=rC(t)?.header?.oiat;return null==i&&null==r?t:null==r?e:null==i?t:i>r?e:i<r?t:(rC(e)?.claims?.iat??0)>(rC(t)?.claims?.iat??0)?e:t}function rA(e){return rC(e)?.header?.oiat}function rP(e){return rC(e)?.claims?.sid}function rT(e){let t=rC(e)?.claims;return t?.org_id||(t?.o?.id??"")}function rO(e,t){return!!e?.jwt&&rP(e)===rP(t)&&rT(e)===rT(t)&&rU(e,t)!==t}let rE={broadcast:!0},rx={broadcast:!1},rR=(o=new Map,l={get:e=>o.get(e),set:(e,t)=>{o.set(e,t)},delete:e=>{o.delete(e)},clear:()=>{o.clear()},forEach:e=>{o.forEach((t,i)=>e(t,i))},size:()=>o.size},c=((e=rI)=>({toKey:({tokenId:t,audience:i})=>[e,t,i||""].join("::")}))(O),d=Math.random().toString(36).slice(2),h=null,(u=()=>h||("u"<typeof BroadcastChannel?null:((h=new BroadcastChannel("clerk:session_token")).addEventListener("message",e=>{_(e)}),h)))(),p=e=>{u();let t=c.toKey(e),i=l.get(t);if(i){if((i.expiresAt??1/0)-Math.floor(Date.now()/1e3)<=5){void 0!==i.timeoutId&&clearTimeout(i.timeoutId),void 0!==i.refreshTimeoutId&&clearTimeout(i.refreshTimeoutId),l.delete(t);return}return{entry:i.entry}}},_=async({data:e})=>{let t,i=r_.build(e.sessionId,e.template,e.organizationId);if(e.tokenId!==i)return void tS.warn("Ignoring token broadcast with mismatched tokenId",{expectedTokenId:i,organizationId:e.organizationId,receivedTokenId:e.tokenId,tabId:d,template:e.template,traceId:e.traceId},"tokenCache");try{t=new n8({id:e.tokenId,jwt:e.tokenRaw,object:"token"})}catch(t){tS.warn("Failed to parse token from broadcast, skipping cache update",{error:t,tabId:d,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");return}let r=t.jwt?.claims?.iat,n=t.jwt?.claims?.exp;if(!r||!n)return void tS.warn("Token missing iat/exp claim, skipping cache update",{tabId:d,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");try{let i=p({tokenId:e.tokenId});if(i){let r=i.entry.resolvedToken??await i.entry.tokenResolver;if(rU(r,t)===r)return void tS.debug("Ignoring staler token broadcast",{tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}}catch(t){tS.warn("Existing entry compare failed; proceeding with broadcast update",{error:t,tabId:d,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}tS.info("Updating token cache from broadcast",{iat:r,organizationId:e.organizationId,tabId:d,template:e.template,tokenId:e.tokenId,traceId:e.traceId},"tokenCache"),f({tokenId:e.tokenId,tokenResolver:Promise.resolve(t)},rx)},f=(e,t=rE)=>{let i=c.toKey({audience:e.audience,tokenId:e.tokenId}),r=l.get(i);clearTimeout(r?.timeoutId),clearTimeout(r?.refreshTimeoutId);let n={cachedAt:Math.floor(Date.now()/1e3),entry:e},s=r?.entry.resolvedToken;n.baseline=s?rU(r?.baseline,s):r?.baseline;let a=e=>{l.get(i)===e&&(clearTimeout(e.timeoutId),clearTimeout(e.refreshTimeoutId),l.delete(i))};l.set(i,n),e.tokenResolver.then(r=>{let s=l.get(i);if(!s)return;let o=r.jwt?.claims,c=!!o&&"number"==typeof o.exp&&"number"==typeof o.iat,u=s===n;if(u&&!c)return void a(s);if(!c)return;let p=rU(s.baseline,r);if(s.baseline=p,!u&&void 0===s.entry.resolvedToken)return;let _=rU(s.entry.resolvedToken,p);if(_===s.entry.resolvedToken)return;s.entry.resolvedToken=_;let f=_.jwt?.claims;if(!f||"number"!=typeof f.exp||"number"!=typeof f.iat)return void a(s);clearTimeout(s.timeoutId),clearTimeout(s.refreshTimeoutId);let m=Math.min(f.exp,s.cachedAt+f.exp-f.iat),g=m-Math.floor(Date.now()/1e3);if(s.expiresAt=m,g<=0)return void a(s);let y=setTimeout(()=>a(s),1e3*g);s.timeoutId=y,"function"==typeof y.unref&&y.unref();let w=g-15-2;if(w>0&&s.entry.onRefresh){let e=setTimeout(()=>{s.entry.onRefresh?.()},1e3*w);s.refreshTimeoutId=e,"function"==typeof e.unref&&e.unref()}let b=h;if(b&&t.broadcast)try{let t=_.getRawString();if(t&&f.sid){let i=f.sid,r=f.org_id||f.o?.id,n=r_.extractTemplate(e.tokenId,i,r),s=r_.build(i,n,r);if(e.tokenId===s){let s=`bc_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;tS.info("Broadcasting token update to other tabs",{organizationId:r,sessionId:i,tabId:d,template:n,tokenId:e.tokenId,traceId:s},"tokenCache");let a={organizationId:r,sessionId:i,template:n,tokenId:e.tokenId,tokenRaw:t,traceId:s};b.postMessage(a)}}}catch(t){tS.warn("Failed to broadcast token update to other tabs",{error:t,tabId:d,tokenId:e.tokenId},"tokenCache")}}).catch(()=>{a(n)})},{clear:()=>{l.forEach(e=>{void 0!==e.timeoutId&&clearTimeout(e.timeoutId),void 0!==e.refreshTimeoutId&&clearTimeout(e.refreshTimeoutId)}),l.clear()},close:()=>{h&&(h.close(),h=null)},get:p,set:e=>{u(),f(e,rE)},size:()=>l.size()});function rM(e){if(!e)return;let t=e.client||e.meta?.client;return t?rz.getOrCreateInstance().fromJSON(t):void 0}class rz extends iu{static instance;pathRoot="/client";sessions=[];signUp=new n1;signIn=new nY;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return rz.instance||(rz.instance=new rz(e)),rz.instance}static clearInstance(){rz.instance=null}static isClientResource(e){return!!e&&e instanceof rz}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,abortSignal:t}={}){return this._baseGet({fetchMaxTries:e,abortSignal:t})}async destroy(){return this._baseDelete({path:"/client"}).then(()=>{rR.clear(),this.id="",this.sessions=[],this.signUp=new n1(null),this.signIn=new nY(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=>(rR.clear(),e))}resetSignIn(){this.signIn=new nY(null),rp.emit("resource:error",{resource:this.signIn,error:null})}resetSignUp(){this.signUp=new n1(null),rp.emit("resource:error",{resource:this.signUp,error:null})}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return iu.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){if(e){this.id=e.id;let t=new Map(this.sessions.map(e=>[e.id,e.lastActiveToken]));this.sessions=(e.sessions||[]).map(e=>{let i=new nz(e),r=t.get(i.id);return r&&i.lastActiveToken&&rO(r,i.lastActiveToken)&&(i.lastActiveToken=r),i}),e.sign_up&&this.signUp instanceof n1&&this.signUp.id===e.sign_up.id?this.signUp.__internal_updateFromJSON(e.sign_up):this.signUp=new n1(e.sign_up),e.sign_in&&this.signIn instanceof nY&&this.signIn.id===e.sign_in.id?this.signIn.__internal_updateFromJSON(e.sign_in):this.signIn=new nY(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?tE(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=tE(e.created_at||void 0),this.updatedAt=tE(e.updated_at||void 0)}return 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 rF extends iu{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 rN{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 rD extends iu{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}}}function rW({delayInMs:e}={delayInMs:1e3}){let t,i=ry(),r=!1,n=()=>{t&&(i.clearTimeout(t),i.cleanup()),r=!0},s=async a=>{r=!1,await a(n),r||(t=i.setTimeout(()=>{s(a)},e))};return{run:s,stop:n}}class rL extends iu{id;emailAddress="";matchesSsoConnection=!1;linkedTo=[];verification;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}create(){return this._basePost({body:{email_address:this.emailAddress}})}prepareVerification=e=>this._basePost({action:"prepare_verification",coalesce:!0,body:{...e}});attemptVerification=e=>{let{code:t}=e||{};return this._basePost({action:"attempt_verification",body:{code:t}})};createEmailLinkFlow=()=>{let{run:e,stop:t}=rW();return{startEmailLinkFlow:async({redirectUrl:i})=>(await this.prepareVerification({strategy:"email_link",redirectUrl:i}),new Promise((i,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),i(e))}).catch(e=>{t(),r(e)}))})),cancelEmailLinkFlow:t}};createEnterpriseSSOLinkFlow=()=>{let{run:e,stop:t}=rW();return{startEnterpriseSSOLinkFlow:async({redirectUrl:i})=>{if(!(await this.prepareVerification({strategy:"enterprise_sso",redirectUrl:i})).verification.externalVerificationRedirectURL)throw Error("Unexpected: External verification redirect URL is missing");return new Promise((i,r)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),i(e))}).catch(e=>{t(),r(e)}))})},cancelEnterpriseSSOLinkFlow:t}};destroy=()=>this._baseDelete();toString=()=>this.emailAddress;fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.verification=new rX(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new nc(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 r$=class{static encode(e){return btoa(String.fromCharCode(...new Uint8Array(e))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}static decode(e){let t=atob(e.replace(/-/g,"+").replace(/_/g,"/")),i=t.length,r=new Uint8Array(i);for(let e=0;e<i;e++)r[e]=t.charCodeAt(e);return r.buffer}};async function rj(e){try{let t=await navigator.credentials.create({publicKey:e});if(!t)return{error:new q("Browser failed to create credential",{code:"passkey_registration_failed"}),publicKeyCredential:null};return{publicKeyCredential:t,error:null}}catch(e){var t;return{error:"InvalidStateError"===(t=e).name?new q(t.message,{code:"passkey_already_exists"}):"NotAllowedError"===t.name?new q(t.message,{code:"passkey_registration_cancelled"}):rK(t),publicKeyCredential:null}}}let rB=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 rJ({publicKeyOptions:e,conditionalUI:t}){try{let i=await navigator.credentials.get({publicKey:e,mediation:t?"conditional":"optional",signal:rB.createAbortSignal()});if(!i)return{error:new q("Browser failed to get credential",{code:"passkey_retrieval_failed"}),publicKeyCredential:null};return{publicKeyCredential:i,error:null}}catch(e){var i;return{error:"NotAllowedError"===(i=e).name?new q(i.message,{code:"passkey_retrieval_cancelled"}):rK(i),publicKeyCredential:null}}}function rK(e){return"AbortError"===e.name?new q(e.message,{code:"passkey_operation_aborted"}):"SecurityError"===e.name?new q(e.message,{code:"passkey_invalid_rpID_or_domain",docsUrl:"https://clerk.com/docs/deployments/overview#authentication-across-subdomains"}):e}function rV(e){let t=rQ(e.challenge),i=(e.allowCredentials||[]).map(e=>({...e,id:rQ(e.id)}));return{...e,allowCredentials:i,challenge:t}}function rq(e){return{type:e.type,id:e.id,rawId:rG(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function rH(e){let t=e.response;return{...rq(e),response:{clientDataJSON:rG(t.clientDataJSON),authenticatorData:rG(t.authenticatorData),signature:rG(t.signature),userHandle:t.userHandle?rG(t.userHandle):null}}}let rG=r$.encode.bind(r$),rQ=r$.decode.bind(r$);class rX extends iu{pathRoot="";status=null;strategy=null;nonce=null;message=null;externalVerificationRedirectURL=null;attempts=null;expireAt=null;error=null;verifiedAtClient=null;channel;trustedDeviceChallenge=null;constructor(e){super(),this.fromJSON(e)}verifiedFromTheSameClient=()=>this.verifiedAtClient===iu.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=tE(e.expire_at||void 0),this.error=e.error?new W(e.error):null,this.channel=e.channel||void 0,this.trustedDeviceChallenge=rs(e.trusted_device_challenge)),this}__internal_toSnapshot(){var e,t;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,seats_quantity_to_add:e?.meta?.seatsQuantityToAdd,seats_quantity:e?.meta?.seatsQuantity,trace_id:e?.meta?.traceId,kind:e?.meta?.kind,title:e?.meta?.title,description:e?.meta?.description,link_url:e?.meta?.linkUrl,link_text:e?.meta?.linkText,data:e?.meta?.data}}),verified_at_client:this.verifiedAtClient,...this.trustedDeviceChallenge&&{trusted_device_challenge:(t=this.trustedDeviceChallenge)?{object:"trusted_device_challenge",challenge:t.challenge,challenge_id:t.challengeId,...t.trustedDeviceId?{trusted_device_id:t.trustedDeviceId}:{},client_data:t.clientData,expires_at:t.expiresAt?Math.floor(t.expiresAt.getTime()/1e3):0,algorithm:t.algorithm}:null}}}}class rY extends rX{publicKey=null;constructor(e){super(e),this.fromJSON(e)}fromJSON(e){var t;let i,r,n;return super.fromJSON(e),e?.nonce&&(this.publicKey=(i=rQ((t=JSON.parse(e.nonce)).user.id),r=rQ(t.challenge),n=(t.excludeCredentials||[]).map(e=>({...e,id:rQ(e.id)})),{...t,excludeCredentials:n,challenge:r,user:{...t.user,id:i}})),this}}class rZ{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new r0(e.email_address),this.phoneNumber=new r0(e.phone_number),this.web3Wallet=new r0(e.web3_wallet),this.externalAccount=new rX(e.external_account)):(this.emailAddress=new r0(null),this.phoneNumber=new r0(null),this.web3Wallet=new r0(null),this.externalAccount=new rX(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 r0 extends rX{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 r1 extends iu{id;protocol;provider;providerUserId=null;active;emailAddress="";firstName="";lastName="";publicMetadata={};verification=null;enterpriseConnection=null;lastAuthenticatedAt=null;enterpriseConnectionId=null;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.provider=e.provider,this.protocol=e.protocol,this.providerUserId=e.provider_user_id,this.active=e.active,this.emailAddress=e.email_address,this.firstName=e.first_name,this.lastName=e.last_name,this.publicMetadata=e.public_metadata,this.lastAuthenticatedAt=e.last_authenticated_at?tE(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new rX(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new r3(e.enterprise_connection))),this}destroy=()=>this._baseDelete();__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 r3 extends iu{id;active;allowIdpInitiated;allowSubdomains;disableAdditionalIdentifications;domain;logoPublicUrl="";name;protocol;provider;syncUserAttributes;allowOrganizationAccountLinking;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.allowOrganizationAccountLinking=e.allow_organization_account_linking,this.createdAt=tE(e.created_at),this.updatedAt=tE(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,allow_organization_account_linking:this.allowOrganizationAccountLinking,enterprise_connection_id:this.enterpriseConnectionId,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}class r2 extends iu{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=tE(e.created_at),this.updatedAt=tE(e.updated_at)),this}}class r4 extends iu{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 r2(e)),this.createdAt=tE(e.created_at),this.updatedAt=tE(e.updated_at)),this}}class r5 extends iu{id;name;organizationId;enterpriseConnectionId;endpointUrl;provider;enabled;groupRoleMappingEnabled;attributeMapping={};credentialsConfigured=null;apiKey=null;createdAt=null;updatedAt=null;constructor(e,t){super(),this.organizationId=t,this.fromJSON(e)}get directoryPath(){return`/organizations/${this.organizationId}/enterprise_connections/${this.enterpriseConnectionId}/directory`}update=async e=>{let t={};return void 0!==e.enabled&&(t.enabled=e.enabled),void 0!==e.groupRoleMappingEnabled&&(t.group_role_mapping_enabled=e.groupRoleMappingEnabled),void 0!==e.attributeMapping&&(t.attribute_mapping=JSON.stringify(e.attributeMapping)),new r5((await iu._fetch({path:this.directoryPath,method:"PATCH",body:t}))?.response,this.organizationId)};rotateToken=async()=>new r5((await iu._fetch({path:`${this.directoryPath}/rotate_api_key`,method:"POST"}))?.response,this.organizationId);delete=async()=>new rN((await iu._fetch({path:this.directoryPath,method:"DELETE"}))?.response);setCredentials=async e=>new r5((await iu._fetch({path:`${this.directoryPath}/credentials`,method:"POST",body:{service_account_json:e.serviceAccountJson,subject_email:e.subjectEmail}}))?.response,this.organizationId);sync=async()=>{await iu._fetch({path:`${this.directoryPath}/sync`,method:"POST"})};getSyncStatus=async()=>{let e=await iu._fetch({path:`${this.directoryPath}/sync_status`,method:"GET"}),t=e?.response;return{lastSyncedAt:t?.last_synced_at?tE(t.last_synced_at):null,lastSyncStatus:t?.last_sync_status??null,lastSyncError:t?.last_sync_error??null,lastSyncChangedUserCount:t?.last_sync_changed_user_count??null}};getGroups=async e=>{let t={};e?.limit!==void 0&&(t.limit=String(e.limit)),e?.startingAfter&&(t.starting_after=e.startingAfter);let i=await iu._fetch({path:`${this.directoryPath}/groups`,method:"GET",search:t}),r=i?.response;return{data:(r?.data??[]).map(e=>({id:e.id,displayName:e.display_name,updatedAt:e.updated_at?tE(e.updated_at):null})),startingAfter:r?.cursor?.starting_after??null,hasNextPage:r?.cursor?.has_next_page??!1}};getGroupRoleMappings=async()=>{let e=await iu._fetch({path:`${this.directoryPath}/group_role_mappings`,method:"GET"});return r8(e?.response)};replaceGroupRoleMappings=async e=>{let t=await iu._fetch({path:`${this.directoryPath}/group_role_mappings`,method:"PUT",body:{mappings:JSON.stringify(e.mappings.map(e=>({directory_group_id:e.directoryGroupId,role:e.role})))}});return r8(t?.response)};getUsers=async e=>{let t=await iu._fetch({path:`${this.directoryPath}/users`,method:"GET",search:iN(e)}),i=t?.response;return{total_count:i?.total_count??0,data:(i?.data??[]).map(e=>new r9(e))}};fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.enterpriseConnectionId=e.enterprise_connection_id,this.endpointUrl=e.endpoint_url,this.provider=e.provider,this.enabled=e.enabled,this.groupRoleMappingEnabled=e.group_role_mapping_enabled,this.attributeMapping=e.attribute_mapping??{},this.credentialsConfigured=e.credentials_configured??null,this.apiKey=e.api_key??null,this.createdAt=tE(e.created_at),this.updatedAt=tE(e.updated_at)),this}__internal_toSnapshot(){return{object:"directory",id:this.id,name:this.name,enterprise_connection_id:this.enterpriseConnectionId,endpoint_url:this.endpointUrl,provider:this.provider,enabled:this.enabled,group_role_mapping_enabled:this.groupRoleMappingEnabled,attribute_mapping:this.attributeMapping,credentials_configured:this.credentialsConfigured,created_at:this.createdAt?.getTime()??0,updated_at:this.updatedAt?.getTime()??0}}}let r6=e=>({id:e.id,directoryGroupId:e.directory_group_id,directoryGroupDisplayName:e.directory_group_display_name,role:e.role?new r4(e.role):null,precedence:e.precedence}),r8=e=>({data:(e?.data??[]).map(r6),defaultRole:e?.default_role?new r4(e.default_role):null});class r9 extends iu{id;userId;firstName=null;lastName=null;identifier=null;imageUrl;hasImage;active;provisionedAt=null;updatedAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.userId=e.user_id,this.firstName=e.first_name,this.lastName=e.last_name,this.identifier=e.identifier,this.imageUrl=e.image_url,this.hasImage=e.has_image,this.active=e.active,this.provisionedAt=tE(e.provisioned_at),this.updatedAt=tE(e.updated_at)),this}}class r7 extends iu{id;name;active;provider;logoPublicUrl=null;domains=[];organizationId=null;syncUserAttributes;disableAdditionalIdentifications;allowOrganizationAccountLinking;customAttributes=[];oauthConfig=null;samlConnection=null;createdAt=null;updatedAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){var t,i;return e?(this.id=e.id,this.name=e.name,this.active=e.active,this.provider=e.provider,this.logoPublicUrl=e.logo_public_url??null,this.domains=e.domains??[],this.organizationId=e.organization_id??null,this.syncUserAttributes=e.sync_user_attributes,this.disableAdditionalIdentifications=e.disable_additional_identifications,this.allowOrganizationAccountLinking=e.allow_organization_account_linking??!1,this.customAttributes=e.custom_attributes??[],this.createdAt=tE(e.created_at),this.updatedAt=tE(e.updated_at),this.samlConnection=e.saml_connection?{id:(t=e.saml_connection).id,name:t.name,active:t.active,idpEntityId:t.idp_entity_id,idpSsoUrl:t.idp_sso_url,idpCertificate:t.idp_certificate,idpCertificateIssuedAt:t.idp_certificate_issued_at,idpCertificateExpiresAt:t.idp_certificate_expires_at,idpCertificates:(t.idp_certificates??[]).map(e=>({certificate:e.certificate,issuedAt:e.issued_at,expiresAt:e.expires_at})),idpMetadataUrl:t.idp_metadata_url,idpMetadata:t.idp_metadata,acsUrl:t.acs_url,spEntityId:t.sp_entity_id,spMetadataUrl:t.sp_metadata_url,allowSubdomains:t.allow_subdomains,allowIdpInitiated:t.allow_idp_initiated,forceAuthn:t.force_authn}:null,this.oauthConfig=e.oauth_config?{id:(i=e.oauth_config).id,name:i.name,clientId:i.client_id,providerKey:i.provider_key,redirectUri:i.redirect_uri,discoveryUrl:i.discovery_url,authUrl:i.auth_url,tokenUrl:i.token_url,userInfoUrl:i.user_info_url,logoPublicUrl:i.logo_public_url,requiresPkce:i.requires_pkce,createdAt:tE(i.created_at),updatedAt:tE(i.updated_at)}:null,this):this}__internal_toSnapshot(){var e,t;return{object:"enterprise_connection",id:this.id,name:this.name,active:this.active,provider:this.provider,logo_public_url:this.logoPublicUrl,domains:this.domains,organization_id:this.organizationId,sync_user_attributes:this.syncUserAttributes,disable_additional_identifications:this.disableAdditionalIdentifications,allow_organization_account_linking:this.allowOrganizationAccountLinking,custom_attributes:this.customAttributes,saml_connection:this.samlConnection?{id:(e=this.samlConnection).id,name:e.name,active:e.active,idp_entity_id:e.idpEntityId,idp_sso_url:e.idpSsoUrl,idp_certificate:e.idpCertificate,idp_certificate_issued_at:e.idpCertificateIssuedAt,idp_certificate_expires_at:e.idpCertificateExpiresAt,idp_certificates:e.idpCertificates.map(e=>({certificate:e.certificate,issued_at:e.issuedAt,expires_at:e.expiresAt})),idp_metadata_url:e.idpMetadataUrl,idp_metadata:e.idpMetadata,acs_url:e.acsUrl,sp_entity_id:e.spEntityId,sp_metadata_url:e.spMetadataUrl,allow_subdomains:e.allowSubdomains,allow_idp_initiated:e.allowIdpInitiated,force_authn:e.forceAuthn}:void 0,oauth_config:this.oauthConfig?{id:(t=this.oauthConfig).id,name:t.name,client_id:t.clientId,provider_key:t.providerKey,redirect_uri:t.redirectUri,discovery_url:t.discoveryUrl,auth_url:t.authUrl,token_url:t.tokenUrl,user_info_url:t.userInfoUrl,logo_public_url:t.logoPublicUrl,requires_pkce:t.requiresPkce,created_at:t.createdAt?.getTime()??0,updated_at:t.updatedAt?.getTime()??0}:void 0,created_at:this.createdAt?.getTime()??0,updated_at:this.updatedAt?.getTime()??0}}}class ne{pathRoot="/me";id;status;connectionType;parsedUserInfo=null;logs=[];saml=null;oauth=null;createdAt=null;constructor(e){this.fromJSON(e)}reload(e){it("EnterpriseConnectionTestRun")}fromJSON(e){var t,i,r;return e&&(this.id=e.id,this.status=e.status,this.connectionType=e.connection_type,this.parsedUserInfo=(t=e.parsed_user_info??null)?{emailAddress:t.email_address,firstName:t.first_name,lastName:t.last_name,userId:t.user_id}:null,this.saml=(i=e.saml??null)?{samlRequest:i.saml_request,samlResponse:i.saml_response,relayState:i.relay_state}:null,this.oauth=(r=e.oauth??null)?{idToken:r.id_token,accessToken:r.access_token,userInfo:r.user_info}:null,this.createdAt=tE(e.created_at),this.logs=(e.logs??[]).map(e=>({level:e.level,code:e.code,shortMessage:e.short_message,message:e.message}))),this}__internal_toSnapshot(){var e,t,i;return{object:"enterprise_connection_test_run",id:this.id,status:this.status,connection_type:this.connectionType,parsed_user_info:(e=this.parsedUserInfo)?{email_address:e.emailAddress,first_name:e.firstName,last_name:e.lastName,user_id:e.userId}:null,saml:(t=this.saml)?{saml_request:t.samlRequest,saml_response:t.samlResponse,relay_state:t.relayState}:null,oauth:(i=this.oauth)?{id_token:i.idToken,access_token:i.accessToken,user_info:i.userInfo}:null,logs:this.logs.map(e=>({level:e.level,code:e.code,short_message:e.shortMessage,message:e.message})),created_at:this.createdAt?.getTime()??0}}}class nt{firstName;lastName;imageUrl;hasImage;identifier;userId;username;banned;deprovisioned;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.username=e.username,this.banned=e.banned??void 0,this.deprovisioned=e.deprovisioned??void 0),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,username:this.username,banned:this.banned,deprovisioned:this.deprovisioned}}}class ni{id;userId;publicUserData;createdAt;updatedAt;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.user_id,this.userId=e.user_id,this.publicUserData=new nt(e.public_user_data),this.createdAt=tE(e.created_at),this.updatedAt=tE(e.updated_at)),this}__internal_toSnapshot(){return{object:"sso_bypass_allowlist_user",user_id:this.userId,public_user_data:this.publicUserData.__internal_toSnapshot(),created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}class nr{constructor(e){Object.defineProperty(this,"organization",{value:e,enumerable:!1})}get path(){return`/organizations/${this.organization.id}/sso_bypass_allowlist_users`}getUsers=async()=>((await iu._fetch({path:this.path,method:"GET"}))?.response||[]).map(e=>new ni(e));addUser=async e=>new ni((await iu._fetch({path:this.path,method:"POST",body:{user_id:e.userId}}))?.response);addUsers=async e=>{let t={data:[],errors:[]};for(let i=0;i<e.userIds.length;i+=100){let r=(await iu._fetch({path:`${this.path}/bulk`,method:"POST",body:{user_id:e.userIds.slice(i,i+100)}}))?.response;t.data.push(...(r?.data??[]).map(e=>new ni(e))),t.errors.push(...(r?.errors??[]).map(e=>({userId:e.user_id,code:e.code})))}return t};removeUser=async e=>new rN((await iu._fetch({path:`${this.path}/${e}`,method:"DELETE"}))?.response)}class nn extends iu{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 ns extends iu{actions={adminDelete:!1};domains={enabled:!1,enrollmentModes:[],defaultRole:null};slug={disabled:!1};organizationCreationDefaults={enabled:!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)),e.organization_creation_defaults&&(this.organizationCreationDefaults.enabled=this.withDefault(e.organization_creation_defaults.enabled,this.organizationCreationDefaults.enabled)),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 na extends iu{static instance;authConfig=new i_;displayConfig=new rD;maintenanceMode=!1;clientDebugMode=!1;partitionedCookies=!1;pathRoot="/environment";userSettings=new sc;organizationSettings=new ns;commerceSettings=new rF;apiKeysSettings=new nn;protectConfig=new nI;static getInstance(){return na.instance||(na.instance=new na),na.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new i_(e.auth_config),this.displayConfig=new rD(e.display_config),this.maintenanceMode=this.withDefault(e.maintenance_mode,this.maintenanceMode),this.clientDebugMode=this.withDefault(e.client_debug_mode,this.clientDebugMode),this.partitionedCookies=this.withDefault(e.partitioned_cookies,this.partitionedCookies),this.organizationSettings=new ns(e.organization_settings),this.userSettings=new sc(e.user_settings),this.commerceSettings=new rF(e.commerce_settings),this.apiKeysSettings=new nn(e.api_keys_settings),this.protectConfig=new nI(e.protect_config)),this}fetch({touch:e,fetchMaxTries:t}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:t})).then(e=>(rp.emit(rh,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,partitioned_cookies:this.partitionedCookies,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 no extends iu{id;identificationId;provider;providerUserId="";emailAddress="";approvedScopes="";firstName="";lastName="";imageUrl="";username="";phoneNumber="";publicMetadata={};label="";verification=null;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}reauthorize=e=>{let{additionalScopes:t,redirectUrl:i,oidcPrompt:r,oidcLoginHint:n}=e||{};return this._basePatch({action:"reauthorize",body:{additional_scope:t,redirect_url:i,oidc_prompt:r,oidc_login_hint:n}})};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 rX(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 nl extends iu{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 nc extends iu{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 nd extends iu{id;name=null;publicUrl=null;static async create(e,t={}){let i,r=t;return"string"==typeof t.file?(r=t.file,i=new Headers({"Content-Type":"application/octet-stream"})):t.file&&(r=new FormData).append("file",t.file),new nd((await iu._fetch({path:e,method:"POST",body:r,headers:i}))?.response)}static async delete(e){return new nd((await iu._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}}function nh(e,t={}){let i={};nu(i,"provider",e.provider),nu(i,"name",e.name);let r=e.domains;return r&&r.length>0&&(i.domains=r),t.omitOrganizationId||nu(i,"organization_id",e.organizationId),nu(i,"active",e.active),nu(i,"sync_user_attributes",e.syncUserAttributes),nu(i,"disable_additional_identifications",e.disableAdditionalIdentifications),nu(i,"custom_attributes",e.customAttributes),e.saml&&(nu(i,"saml_idp_entity_id",e.saml.idpEntityId),nu(i,"saml_idp_sso_url",e.saml.idpSsoUrl),nu(i,"saml_idp_certificate",e.saml.idpCertificate),nu(i,"saml_idp_certificates",e.saml.idpCertificates),nu(i,"saml_idp_metadata_url",e.saml.idpMetadataUrl),nu(i,"saml_idp_metadata",e.saml.idpMetadata),nu(i,"saml_attribute_mapping",e.saml.attributeMapping),nu(i,"saml_allow_subdomains",e.saml.allowSubdomains),nu(i,"saml_allow_idp_initiated",e.saml.allowIdpInitiated),nu(i,"saml_force_authn",e.saml.forceAuthn)),e.oidc&&(nu(i,"oidc_client_id",e.oidc.clientId),nu(i,"oidc_client_secret",e.oidc.clientSecret),nu(i,"oidc_discovery_url",e.oidc.discoveryUrl),nu(i,"oidc_auth_url",e.oidc.authUrl),nu(i,"oidc_token_url",e.oidc.tokenUrl),nu(i,"oidc_user_info_url",e.oidc.userInfoUrl),nu(i,"oidc_requires_pkce",e.oidc.requiresPkce)),i}function nu(e,t,i){void 0!==i&&(e[t]=i)}class np extends iu{id;name;organizationId;enrollmentMode;verification;affiliationVerification;ownershipVerification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:t,enrollmentMode:i}){return new np((await iu._fetch({path:`/organizations/${e}/domains`,method:"POST",body:{name:t,enrollment_mode:i}}))?.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){if(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;let t=e.affiliation_verification??e.verification;if(t){let e={status:t.status,strategy:t.strategy,attempts:t.attempts,expiresAt:tE(t.expires_at)};this.affiliationVerification=e,this.verification=e}else this.affiliationVerification=null,this.verification=null;e.ownership_verification?this.ownershipVerification={status:e.ownership_verification.status,strategy:e.ownership_verification.strategy,attempts:e.ownership_verification.attempts,expiresAt:e.ownership_verification.expire_at?tE(e.ownership_verification.expire_at):null,verifiedAt:e.ownership_verification.verified_at?tE(e.ownership_verification.verified_at):null,txtRecordName:e.ownership_verification.txt_record_name??null,txtRecordValue:e.ownership_verification.txt_record_value??null}:this.ownershipVerification=null}return this}}class n_ extends iu{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=tE(e.created_at),this.updatedAt=tE(e.updated_at),e.public_user_data&&(this.publicUserData=new nt(e.public_user_data))),this}}class nf extends iu{pathRoot="/organizations";ssoBypassAllowlist=new nr(this);id;name;slug;imageUrl;hasImage;publicMetadata={};adminDeleteEnabled;createdAt;updatedAt;membersCount=0;pendingInvitationsCount=0;maxAllowedMemberships;selfServeSSOEnabled=!1;selfServeDirectorySyncEnabled=!1;exclusiveMembership=!1;constructor(e){super(),this.fromJSON(e)}static async create(e){return new nf((await iu._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new nf((await iu._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await iu._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:iN(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i,has_role_set_migration:r}=e?.response;return{data:t.map(e=>new r4(e)),total_count:i,has_role_set_migration:r}});getDomains=async e=>{let{enrollmentMode:t,...i}=e||{},r=iN(i);return t&&r.set("enrollment_mode",t),await iu._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:r},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new np(e))}})};getDomain=async({domainId:e})=>new np((await iu._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getEnterpriseConnections=async e=>{let{withOrganizationAccountLinking:t}=e||{};return((await iu._fetch({path:`/organizations/${this.id}/enterprise_connections`,method:"GET",...void 0!==t?{search:{with_organization_account_linking:String(t)}}:{}}))?.response||[]).map(e=>new r7(e))};createEnterpriseConnection=async e=>new r7((await iu._fetch({path:`/organizations/${this.id}/enterprise_connections`,method:"POST",body:nh(e,{omitOrganizationId:!0})}))?.response);updateEnterpriseConnection=async(e,t)=>new r7((await iu._fetch({path:`/organizations/${this.id}/enterprise_connections/${e}`,method:"PATCH",body:nh(t,{omitOrganizationId:!0})}))?.response);deleteEnterpriseConnection=async e=>new rN((await iu._fetch({path:`/organizations/${this.id}/enterprise_connections/${e}`,method:"DELETE"}))?.response);createEnterpriseConnectionTestRun=async e=>({url:((await iu._fetch({path:`/organizations/${this.id}/enterprise_connections/${e}/test_runs`,method:"POST"}))?.response).url});getEnterpriseConnectionTestRuns=async(e,t)=>{let{status:i,...r}=t||{},n=iN(r);if(i?.length)for(let e of i)n.append("status",e);let s=await iu._fetch({path:`/organizations/${this.id}/enterprise_connections/${e}/test_runs`,method:"GET",search:n}),a=s?.response;return{total_count:a?.total_count??0,data:(a?.data??[]).map(e=>new ne(e))}};getDirectorySync=async e=>new r5((await iu._fetch({path:`/organizations/${this.id}/enterprise_connections/${e}/directory`,method:"GET"}))?.response,this.id);createDirectorySync=async(e,t)=>new r5((await iu._fetch({path:`/organizations/${this.id}/enterprise_connections/${e}/directory`,method:"POST",body:{name:t?.name}}))?.response,this.id);getMembershipRequests=async e=>await iu._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:iN(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new n_(e))}});createDomain=async(e,t)=>np.create(this.id,{name:e,enrollmentMode:t?.enrollmentMode});prepareOwnershipVerification=async e=>this.bulkOwnershipVerification("prepare_ownership_verification",e);attemptOwnershipVerification=async e=>this.bulkOwnershipVerification("attempt_ownership_verification",e);bulkOwnershipVerification=async(e,t)=>{let{data:i,errors:r}=(await iu._fetch({path:`/organizations/${this.id}/domains/${e}/bulk`,method:"POST",body:{organization_domain_ids:t}},{forceUpdateClient:!0}))?.response;return{data:(i??[]).map(e=>new np(e)),errors:r??[]}};getMemberships=async e=>await iu._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:iN({...e,paginated:!0})}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new ng(e))}});getInvitations=async e=>await iu._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:iN(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new nm(e))}});addMember=async({userId:e,role:t})=>await iu._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:t}}).then(e=>new ng(e?.response));inviteMember=async e=>nm.create(this.id,e);inviteMembers=async e=>nm.createBulk(this.id,e);updateMember=async({userId:e,role:t})=>await iu._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:t}}).then(e=>new ng(e?.response));removeMember=async e=>await iu._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new ng(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let t,i;return null===e?await iu._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new nf(e?.response)):("string"==typeof e?(t=e,i=new Headers({"Content-Type":"application/octet-stream"})):(t=new FormData).append("file",e),await iu._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:t,headers:i}).then(e=>new nf(e?.response)))};initializePaymentMethod=e=>i5({...e,orgId:this.id});addPaymentMethod=e=>i6({...e,orgId:this.id});getPaymentMethods=e=>i8({...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.selfServeSSOEnabled=e.self_serve_sso_enabled||!1,this.selfServeDirectorySyncEnabled=e.self_serve_directory_sync_enabled||!1,this.exclusiveMembership=e.exclusive_membership||!1,this.createdAt=tE(e.created_at),this.updatedAt=tE(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,self_serve_sso_enabled:this.selfServeSSOEnabled,self_serve_directory_sync_enabled:this.selfServeDirectorySyncEnabled,exclusive_membership:this.exclusiveMembership,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}async reload(e){let{rotatingTokenNonce:t}=e||{},i=(await iu._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:t},{forceUpdateClient:!0}))?.response;return this.fromJSON(i)}}class nm extends iu{id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:t,role:i}){return new nm((await iu._fetch({path:`/organizations/${e}/invitations`,method:"POST",body:{email_address:t,role:i}}))?.response)}static async createBulk(e,t){let{emailAddresses:i,role:r}=t;return((await iu._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:i,role:r}}))?.response).map(e=>new nm(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=tE(e.created_at),this.updatedAt=tE(e.updated_at)),this}}class ng extends iu{id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await iu._fetch({path:"/me/organization_memberships",method:"GET",search:iN({...e,paginated:!0})}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new ng(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 nf(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new nt(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=tE(e.created_at),this.updatedAt=tE(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){it("OrganizationMembership")}}class ny extends iu{id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await iu._fetch({path:"/me/organization_suggestions",method:"GET",search:iN(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new ny(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=tE(e.created_at),this.updatedAt=tE(e.updated_at)),this}}function nw(){return"u">typeof window&&b()&&"function"==typeof window.PublicKeyCredential}async function nb(){try{return nw()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function nv(){try{return"u">typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class nk extends iu{id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return iu._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new nk(e?.response))}static async attemptVerification(e,t){let i,r=(i=t.response,{...rq(t),response:{clientDataJSON:rG(i.clientDataJSON),attestationObject:rG(i.attestationObject),transports:i.getTransports()}});return iu._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(r)}}).then(e=>new nk(e?.response))}static async registerPasskey(){let e,t=nk.clerk.__internal_isWebAuthnSupported||nw,i=nk.clerk.__internal_createPublicCredentials||rj,r=nk.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||nv;if(!t())throw new q("Passkeys are not supported on this device.",{code:"passkey_not_supported"});let n=await this.create();try{let{verification:t}=n,s=t?.publicKey;if(s||ii("create"),s.authenticatorSelection?.authenticatorAttachment==="platform"&&!await r())throw new q("Registration requires a platform authenticator but the device does not support it.",{code:"passkey_pa_not_supported"});let a=await i(s);if(!a.publicKeyCredential)throw a.error;e=a.publicKeyCredential}catch(e){throw n.id&&await n.delete().catch(tm.lQ),e}return this.attemptVerification(n.id,e)}update=e=>this._basePatch({body:e});delete=async()=>new rN((await iu._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?tE(e.last_used_at):null,this.createdAt=tE(e.created_at),this.updatedAt=tE(e.updated_at),e.verification&&(this.verification=new rY(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 nS extends iu{id;phoneNumber="";reservedForSecondFactor=!1;defaultSecondFactor=!1;linkedTo=[];verification;backupCodes;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}create=()=>this._basePost({body:{phone_number:this.phoneNumber}});prepareVerification=()=>this._basePost({action:"prepare_verification",coalesce:!0,body:{strategy:"phone_code"}});attemptVerification=e=>{let{code:t}=e||{};return this._basePost({action:"attempt_verification",body:{code:t}})};setReservedForSecondFactor=e=>{let{reserved:t}=e||{};return this._basePatch({body:{reserved_for_second_factor:t}})};makeDefaultSecondFactor=()=>this._basePatch({body:{default_second_factor:!0}});destroy=()=>this._baseDelete();toString=()=>{let e=this.phoneNumber.match(/^(\d{3})(\d{3})(\d{4})$/);return e?"("+e[1]+") "+e[2]+"-"+e[3]:this.phoneNumber};fromJSON(e){return e&&(this.id=e.id,this.phoneNumber=e.phone_number,this.reservedForSecondFactor=e.reserved_for_second_factor,this.defaultSecondFactor=e.default_second_factor,this.verification=new rX(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new nc(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 nI extends iu{id="";loaders;tokens_invalid_before;challenge_load_timeout_ms;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.tokens_invalid_before=this.withDefault(e.tokens_invalid_before,this.tokens_invalid_before),this.challenge_load_timeout_ms=this.withDefault(e.challenge_load_timeout_ms,this.challenge_load_timeout_ms)),this}__internal_toSnapshot(){return{object:"protect_config",id:this.id,loaders:this.loaders,tokens_invalid_before:this.tokens_invalid_before,challenge_load_timeout_ms:this.challenge_load_timeout_ms}}}let nC={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"}},nU=new Set(["first_factor","second_factor","multi_factor"]),nA=new Set(["strict_mfa","strict","moderate","lax"]),nP=new Set(["o","org","organization"]),nT=new Set(["u","user"]),nO=e=>"number"==typeof e&&Number.isFinite(e)&&(-1===e||e>=0),nE=(e,t)=>{let{org:i,user:r}=nx(e),[n,s]=t.split(":"),a=void 0!==s,o=s||n;if(a&&!nP.has(n)&&!nT.has(n))throw Error(`Invalid scope: ${n}`);if(a){if(nP.has(n))return i.includes(o);if(nT.has(n))return r.includes(o)}return[...i,...r].includes(o)},nx=e=>{let t=[],i=[];if(!e)return{org:t,user:i};let r=e.split(",");for(let e=0;e<r.length;e++){let n=r[e].trim(),s=n.indexOf(":");if(-1===s)throw Error(`Invalid claim element (missing colon): ${n}`);let a=n.slice(0,s),o=n.slice(s+1);"o"===a?t.push(o):"u"===a?i.push(o):("ou"===a||"uo"===a)&&(t.push(o),i.push(o))}return{org:t,user:i}};class nR extends iu{status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new rX(null);secondFactorVerification=new rX(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new nz(e.session),this.level=e.level,this.supportedFirstFactors=ef(e.supported_first_factors),this.supportedSecondFactors=ef(e.supported_second_factors),this.firstFactorVerification=new rX(e.first_factor_verification),this.secondFactorVerification=new rX(e.second_factor_verification)),this}}let nM=e=>!1===rw()?{}:{onRefresh:e};class nz extends iu{pathRoot="/client/sessions";static #$=new Set;id;status;lastActiveAt;lastActiveToken;lastActiveOrganizationId;actor;agent;user;publicUserData;factorVerificationAge=null;tasks=null;expireAt;abandonAt;createdAt;updatedAt;static isSessionResource(e){return!!e&&e instanceof nz}constructor(e){super(),this.fromJSON(e),this.#j(this.lastActiveToken)}end=()=>(rR.clear(),this._basePost({action:"end"}));remove=()=>(rR.clear(),this._basePost({action:"remove"}));_touchPost=async({intent:e,skipUpdateClient:t}={skipUpdateClient:!1})=>{let i=await iu._fetch({method:"POST",path:this.path("touch"),body:{active_organization_id:this.lastActiveOrganizationId,intent:e}},{skipUpdateClient:t});return this.fromJSON(i?.response||i),i};touch=async({intent:e}={})=>(await this._touchPost({intent:e,skipUpdateClient:!1}),this.lastActiveToken&&rp.emit(rc,{token:this.lastActiveToken}),this);__internal_touch=async({intent:e}={})=>rM(await this._touchPost({intent:e,skipUpdateClient:!0}));clearCache=()=>rR.clear();getToken=async e=>{try{let t=await tA(()=>this._getToken(e),{factor:1.55,initialDelay:3e3,maxDelayBetweenRetries:5e4,jitter:!1,shouldRetry:(e,t)=>(!G(e)||e?.status===429)&&(k()?t<=8:t<=3)});if(!t&&!k())throw new B("Network request failed while offline. The browser appears to be disconnected.");return t}catch(e){if(!$(e)&&!k())throw new B("Network request failed while offline. The browser appears to be disconnected.");throw e}};checkAuthorization=e=>{let t,i=(this.user?.organizationMemberships||[]).find(e=>e.organization.id===this.lastActiveOrganizationId);return(t={userId:this.user?.id,factorVerificationAge:this.factorVerificationAge,orgId:i?.organization?.id,orgRole:i?.role,orgPermissions:i?.permissions,features:this.lastActiveToken?.jwt?.claims.fea||"",plans:this.lastActiveToken?.jwt?.claims.pla||""},e=>{let i;return!!t.userId&&(i=[((e,t)=>{let{orgId:i,orgRole:r,orgPermissions:n}=t,s=void 0!==e.role,a=void 0!==e.permission;return s||a?s&&"string"!=typeof e.role||a&&"string"!=typeof e.permission||!i||s&&("string"!=typeof r||!r||r.replace(/^(org:)*/,"org:")!==e.role.replace(/^(org:)*/,"org:"))||a&&(!Array.isArray(n)||!n.includes(e.permission.replace(/^(org:)*/,"org:")))?"fail":"pass":"skip"})(e,t),((e,t)=>{let{features:i,plans:r}=t,n=void 0!==e.feature,s=void 0!==e.plan;if(!n&&!s)return"skip";if(n&&"string"!=typeof e.feature||s&&"string"!=typeof e.plan)return"fail";if(n){if("string"!=typeof i||!i)return"fail";try{if(!nE(i,e.feature))return"fail"}catch{return"fail"}}if(s){if("string"!=typeof r||!r)return"fail";try{if(!nE(r,e.plan))return"fail"}catch{return"fail"}}return"pass"})(e,t),((e,{factorVerificationAge:t})=>{if(void 0===e.reverification)return"skip";if(!t||!Array.isArray(t)||2!==t.length||!nO(t[0])||!nO(t[1]))return"fail";let i=(e=>{let t,i;if(!e)return!1;let r="string"==typeof e&&nA.has(e),n="object"==typeof e&&(t=e.level,nU.has(t))&&"number"==typeof(i=e.afterMinutes)&&i>0;return(!!r||!!n)&&(e=>"string"==typeof e?nC[e]:e).bind(null,e)})(e.reverification);if(!i)return"fail";let{level:r,afterMinutes:n}=i(),[s,a]=t;if(-1===s&&-1===a)return"fail";let o=-1!==s&&n>s,l=-1!==a&&n>a;switch(r){case"first_factor":return o?"pass":"fail";case"second_factor":if(-1===a)return o?"pass":"fail";return l?"pass":"fail";case"multi_factor":if(-1===a)return o?"pass":"fail";if(-1===s)return"fail";return o&&l?"pass":"fail"}})(e,t)]).some(e=>"pass"===e)&&i.every(e=>"pass"===e||"skip"===e)})(e)};#j=e=>{if(e){let t=this.#B();rR.set({tokenId:t,tokenResolver:Promise.resolve(e),...nM(()=>this.#J(void 0,this.lastActiveOrganizationId,t,!0))})}};#B(e,t){let i=void 0===t?this.lastActiveOrganizationId:t;return r_.build(this.id,e,i)}startVerification=async({level:e})=>new nR((await iu._fetch({method:"POST",path:`/client/sessions/${this.id}/verify`,body:{level:e}}))?.response);prepareFirstFactorVerification=async e=>{let t;switch(e.strategy){case"email_code":t={emailAddressId:e.emailAddressId};break;case"phone_code":t={phoneNumberId:e.phoneNumberId,default:e.default};break;case"passkey":t={};break;case"trusted_device":t={trustedDeviceId:e.trustedDeviceId};break;case"enterprise_sso":t={emailAddressId:e.emailAddressId,enterpriseConnectionId:e.enterpriseConnectionId,redirectUrl:e.redirectUrl};break;default:t8("Session.prepareFirstFactorVerification",e.strategy)}return new nR((await iu._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_first_factor`,body:{...t,strategy:e.strategy}}))?.response)};attemptFirstFactorVerification=async e=>{let t;return t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(rH(e.publicKeyCredential))}:{...e},new nR((await iu._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_first_factor`,body:{...t,strategy:e.strategy}}))?.response)};verifyWithPasskey=async e=>{let t=e?.level??"first_factor";"first_factor"!==t&&"second_factor"!==t&&function(e,t){throw Error(`${t2} "${t}" is not a valid verification level for ${e}. Use 'first_factor' or 'second_factor'.`)}("Session.verifyWithPasskey",t);let i="second_factor"===t?await this.prepareSecondFactorVerification({strategy:"passkey"}):await this.prepareFirstFactorVerification({strategy:"passkey"}),{nonce:r=null}="second_factor"===t?i.secondFactorVerification:i.firstFactorVerification,n=nz.clerk.__internal_isWebAuthnSupported||nw,s=nz.clerk.__internal_getPublicCredentials||rJ;if(!n())throw new q("Passkeys are not supported",{code:"passkey_not_supported"});let a=r?rV(JSON.parse(r)):null;a||ii("get");let{publicKeyCredential:o,error:l}=await s({publicKeyOptions:a,conditionalUI:!1});if(!o)throw l;return"second_factor"===t?this.attemptSecondFactorVerification({strategy:"passkey",publicKeyCredential:o}):this.attemptFirstFactorVerification({strategy:"passkey",publicKeyCredential:o})};prepareSecondFactorVerification=async e=>new nR((await iu._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>{let t;return t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(rH(e.publicKeyCredential))}:{...e},new nR((await iu._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_second_factor`,body:{...t,strategy:e.strategy}}))?.response)};fromJSON(e){if(!e)return this;this.id=e.id,this.status=e.status,this.expireAt=tE(e.expire_at),this.abandonAt=tE(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=tE(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.agent=e.actor?.type==="agent"?e.actor:null,this.createdAt=tE(e.created_at),this.updatedAt=tE(e.updated_at),this.user=new ss(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new nt(e.public_user_data));let t=e.last_active_token?new n8(e.last_active_token):null;return t&&rO(this.lastActiveToken,t)||(this.lastActiveToken=t),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){let t;if(!this.user)return null;let{skipCache:i=!1,template:r}=e||{},n=void 0===e?.organizationId?this.lastActiveOrganizationId:e?.organizationId,s=this.#B(r,n),a=i?void 0:rR.get({tokenId:s}),o=!r&&n===this.lastActiveOrganizationId;if(a){let e=a.entry.resolvedToken??await a.entry.tokenResolver;o&&e.getRawString()&&rp.emit(rc,{token:e}),t=e.getRawString()||null}else t=await this.#K(r,n,s,o,i);if(null===t&&!k())throw new R("Network request failed while offline",{code:"network_error"});return t}#V(e,t,i){let r=e?`${this.path()}/tokens/${e}`:`${this.path()}/tokens`,n=nz.clerk?.__internal_environment?.authConfig?.sessionMinter,s=e?void 0:(()=>{let e=rw();if(void 0!==e){if(e)return"focused";try{return"visible"===document.visibilityState?"visible":"hidden"}catch{return}}})(),a=e?{}:{organizationId:t??null,...s?{tabState:s}:{},...n&&this.lastActiveToken?{token:this.lastActiveToken.getRawString()}:{},...n&&i?{forceOrigin:"true"}:{}};if(n)return n8.create(r,a,i?{debug:"skip_cache"}:void 0);let o=this.lastActiveToken?.getRawString();return n8.create(r,a,i?{debug:"skip_cache"}:void 0).catch(e=>{if(j.is(e)&&o)return n8.create(r,{...a},{expired_token:o});throw e})}#q(e,t){!t||e.getRawString()&&(rp.emit(rc,{token:e}),e.jwt&&!rO(this.lastActiveToken,e)&&(this.lastActiveToken=e,rp.emit(ru,null)))}#K(e,t,i,r,n){tS.info("Fetching new token from API",{organizationId:t,template:e,tokenId:i},"session");let s=this.#V(e,t,n);return rR.set({tokenId:i,tokenResolver:s,...nM(()=>this.#J(e,t,i,r))}),s.then(e=>{let t=e.getRawString();if(!t)throw new R("Token fetch returned empty response",{code:"network_error"});return this.#q(e,r),t})}#J(e,t,i,r){if(nz.#$.has(i))return;nz.#$.add(i);let n=nz.clerk?.__internal_getOption?.("experimental"),s=n?.runtimeEnvironment==="headless",a=this.lastActiveToken?.jwt?.claims?.exp;s&&a&&Date.now()/1e3>a?nz.#$.delete(i):this.#V(e,t,!1).then(n=>{n.getRawString()&&(rR.set({tokenId:i,tokenResolver:Promise.resolve(n),...nM(()=>this.#J(e,t,i,r))}),this.#q(n,r))}).catch(e=>{tS.warn("Background token refresh failed",{error:e,tokenId:i},"session")}).finally(()=>{nz.#$.delete(i)})}get currentTask(){let[e]=this.tasks??[];return e}}class nF extends iu{pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}static retrieve(){let e=iu.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new nF(e,"/me/sessions"))).catch(()=>[])}revoke(){return this._basePost({action:"revoke",body:{}})}fromJSON(e){let t;return e?(this.id=e.id,this.status=e.status,this.expireAt=tE(e.expire_at),this.abandonAt=tE(e.abandon_at),this.lastActiveAt=tE(e.last_active_at||void 0),this.latestActivity={id:(t=e.latest_activity??{}).id,deviceType:t.device_type,browserName:t.browser_name,browserVersion:t.browser_version,country:t.country,city:t.city,isMobile:t.is_mobile,ipAddress:t.ip_address},this.actor=e.actor,this):this}}let nN=(e,t,i)=>{let{onValidation:r=rf.t,onValidationComplexity:n=rf.t}=i||{},{show_zxcvbn:s,validatePassword:a}=t,o=e=>((e,t)=>{let{max_length:i,min_length:r,require_special_char:n,require_lowercase:s,require_numbers:a,require_uppercase:o}=t,l=(e=>{let t;if(e.allowed_special_characters){let i=e.allowed_special_characters.replace("[","\\[");i=i.replace("]","\\]"),t=RegExp(`[${i}]`)}else t=/[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]/;return(e,{minLength:i,maxLength:r})=>({max_length:e.length<r,min_length:e.length>=i,require_numbers:/\d/.test(e),require_lowercase:/[a-z]/.test(e),require_uppercase:/[A-Z]/.test(e),require_special_char:t.test(e)})})(t)(e,{maxLength:t.max_length,minLength:t.min_length}),c={max_length:i,min_length:r,require_special_char:n,require_lowercase:s,require_numbers:a,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,t),l=(({min_zxcvbn_strength:e,onResult:t})=>i=>r=>{let n=i(r);return(t?.(n),n.score>=e&&n.score<3)?{state:"pass",keys:["unstable__errors.zxcvbn.couldBeStronger"],result:n}:n.score>=e?{state:"excellent",result:n}:{state:"fail",keys:["unstable__errors.zxcvbn.notEnough",...n.feedback.suggestions.map(e=>`unstable__errors.zxcvbn.suggestions.${e}`)],result:n}})(t),c={};return(t,i)=>{let{onValidation:d=r,onValidationComplexity:h=n}=i||{};if(!a)return;let u=o(t);h(0===Object.keys(u).length),c={...c,complexity:u},s&&e().then(e=>{let i=l(e)(t);d({...c={...c,strength:i},strength:i})}),c.complexity&&0===Object.keys(c.complexity).length&&s||d(c)}};function nD(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function nW(e,t,i,r,n){if(!e.client||!r.popup)return;let s=nD(e.frontendApi),{redirectUrl:a}=r,o=new URL(a);o.searchParams.set("sign_in_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("sign_up_force_redirect_url",r.redirectUrlComplete),o.searchParams.set("intent",t);let l=e.buildUrlWithAuth(o.toString()),c=e.buildUrlWithAuth(`${s}/popup-callback`),d=e.buildUrlWithAuth(`${s}/popup-callback?return_url=${encodeURIComponent(l)}`),h=async t=>{if(t.origin!==s)return;let i=!1;if(t.data.session){if(!e.client?.sessions.find(e=>e.id===t.data.session))try{await e.client?.reload()}catch(e){console.error(e)}await e.setActive({session:t.data.session,redirectUrl:r.redirectUrlComplete}),i=!0}else t.data.return_url&&(e.navigate(t.data.return_url),i=!0);i&&window.removeEventListener("message",h)};window.addEventListener("message",h),await i({...r,redirectUrlComplete:c,redirectUrl:d},n)}function nL(e,{redirectCallbackUrl:t,redirectUrl:i}){let r=nD(e.frontendApi),n=new URL(t);n.searchParams.set("sign_in_force_redirect_url",i),n.searchParams.set("sign_up_force_redirect_url",i);let s=e.buildUrlWithAuth(n.toString()),a=e.buildUrlWithAuth(`${r}/popup-callback`);return{redirectCallbackUrl:e.buildUrlWithAuth(`${r}/popup-callback?return_url=${encodeURIComponent(s)}`),redirectUrl:a}}function n$(e,t){return new Promise((i,r)=>{if(!e.client||!t.popup)return void r();let n=async t=>{t.origin===nD(e.frontendApi)&&(t.data.session||t.data.return_url?(window.removeEventListener("message",n),i()):r())};window.addEventListener("message",n),t.popup.location.href=t.externalVerificationRedirectURL.toString()})}let nj="oauth_callback_failed",nB=new Set(["external_account_not_found",el]),nJ={oauth_access_denied:"You did not grant access to your account."};async function nK(e){try{await e.create({})}catch{}}async function nV(e){let t,i=String(await e.transport.getRedirectUrl());if(await e.authenticateMethod({...e.params,redirectUrl:i,redirectUrlComplete:i},e=>{t=e}),!t)throw new R("OAuth transport did not receive a verification URL.",{code:"oauth_transport_missing_verification_url"});let{callbackUrl:r}=await e.transport.open(new URL(t.toString())),n=function(e){let t=new URL(e).searchParams;if("failed"!==t.get("__clerk_status"))return null;let i=t.get("__clerk_error_code")||nj;if(nB.has(i))return null;let r=nJ[i]?i:nj;return{code:r,message:nJ[r]||"OAuth callback failed."}}(r);if(n)throw await nK(e.resource),new R(n.message,{code:n.code});let s=new URL(r).searchParams.get("rotating_token_nonce");s?await e.resource.reload({rotatingTokenNonce:s}):await e.resource.reload(),await e.clerk.__internal_handleResourceCallback(e.resource,e.callbackParams)}async function nq(e,t){rp.emit("resource:error",{resource:e,error:null}),rp.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await t(),error:null}}catch(t){return rp.emit("resource:error",{resource:e,error:t}),{error:t}}finally{rp.emit("resource:fetch",{resource:e,status:"idle"})}}function nH(){if(!m())return null;try{let e=Intl?.DateTimeFormat?.().resolvedOptions().timeZone;return"string"==typeof e&&e.trim()?e:null}catch{return null}}let nG=()=>{var e;return(e=new tT,{loadZxcvbn:()=>Promise.all([e.import("@zxcvbn-ts/core"),e.import("@zxcvbn-ts/language-common")]).then(([e,t])=>{if(!e||!t)throw Error("Failed to load zxcvbn modules");let{zxcvbnOptions:i,zxcvbn:r}=e,{dictionary:n,adjacencyGraphs:s}=t;return i.setOptions({dictionary:{...n},graphs:s}),r})}).loadZxcvbn};class nQ{static instance;inflight=null;static getInstance(){return nQ.instance||(nQ.instance=new nQ),nQ.instance}async resolve(e,t,i){if("protect_check"===i||!t.protectCheck)return;for(;this.inflight;){if(this.inflight.resourceId===t.id)return this.inflight.promise;await this.inflight.promise.catch(()=>{})}if(!t.protectCheck)return;let r=e.__internal_openProtectCheckModal({resource:t}).finally(()=>{this.inflight=null});this.inflight={resourceId:t.id,promise:r},await r}}let nX=e=>"verified"===e||"expired"===e||"transferable"===e;class nY extends iu{pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;ssoBypassFirstFactors=null;firstFactorVerification=new rX(null);secondFactorVerification=new rX(null);identifier=null;createdSessionId=null;userData=new sa(null);clientTrustState;protectCheck=null;timezone=null;get status(){return this._status}set status(e){let t=this._status;this._status=e,e&&t!==e&&tS.debug("SignIn.status",{id:this.id,from:t,to:e})}__internal_future=new nZ(this);__internal_basePost=async(e,{resolveProtectCheck:t=!0}={})=>(await this._basePost(e),t&&await nQ.getInstance().resolve(nY.clerk,this,e?.action),this);__internal_basePatch=async(e,{resolveProtectCheck:t=!0}={})=>(await this._basePatch(e),t&&await nQ.getInstance().resolve(nY.clerk,this,e?.action),this);__internal_baseGet=this._baseGet.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{tS.debug("SignIn.create",{id:this.id,strategy:"strategy"in e?e.strategy:void 0});let t={...e},i=tq();if(i&&(t.locale=i),void 0===t.timezone){let e=nH();e&&(t.timezone=e)}if(this.shouldRequireCaptcha(e)&&!this.clientBypass()&&!this.shouldBypassCaptchaForAttempt(e)){let e=new id(nY.clerk),i=await e.managedOrInvisible({action:"signin"});if(!i)throw new R("",{code:"captcha_unavailable"});t={...t,...i}}return this._basePost({path:this.pathRoot,body:t})};resetPassword=e=>this._basePost({body:e,action:"reset_password"});prepareFirstFactor=e=>{let t;switch(tS.debug("SignIn.prepareFirstFactor",{id:this.id,strategy:e.strategy}),e.strategy){case"passkey":t={};break;case"email_link":t={emailAddressId:e.emailAddressId,redirectUrl:e.redirectUrl};break;case"email_code":case"reset_password_email_code":t={emailAddressId:e.emailAddressId};break;case"phone_code":t={phoneNumberId:e.phoneNumberId,default:e.default,channel:e.channel};break;case"web3_metamask_signature":case"web3_base_signature":case"web3_coinbase_wallet_signature":case"web3_okx_wallet_signature":case"web3_solana_signature":t={web3WalletId:e.web3WalletId};break;case"reset_password_phone_code":t={phoneNumberId:e.phoneNumberId};break;case"enterprise_sso":t={redirectUrl:e.redirectUrl,actionCompleteRedirectUrl:e.actionCompleteRedirectUrl,oidcPrompt:e.oidcPrompt,enterpriseConnectionId:e.enterpriseConnectionId};break;default:t8("SignIn.prepareFirstFactor",e.strategy)}return this._basePost({body:{...t,strategy:e.strategy},action:"prepare_first_factor",coalesce:!0})};submitProtectCheck=e=>(tS.debug("SignIn.submitProtectCheck",{id:this.id}),this._basePatch({action:"protect_check",body:{proof_token:e.proofToken}}));attemptFirstFactor=e=>{let t;return tS.debug("SignIn.attemptFirstFactor",{id:this.id,strategy:e.strategy}),t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(rH(e.publicKeyCredential))}:{...e},this._basePost({body:{...t,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:t}=rW();return{startEmailLinkFlow:async({emailAddressId:i,redirectUrl:r})=>{this.id||t6("SignIn");let n={strategy:"email_link",emailAddressId:i,redirectUrl:r},s="needs_second_factor"===this.status||"needs_client_trust"===this.status,a=s?"secondFactorVerification":"firstFactorVerification";return s?await this.prepareSecondFactor(n):await this.prepareFirstFactor(n),new Promise((i,r)=>{e(()=>this.reload().then(e=>{nX(e[a].status)&&(t(),i(e))}).catch(e=>{t(),r(e)}))})},cancelEmailLinkFlow:t}};prepareSecondFactor=e=>(tS.debug("SignIn.prepareSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_second_factor",coalesce:!0}));attemptSecondFactor=e=>{let t;return tS.debug("SignIn.attemptSecondFactor",{id:this.id,strategy:e.strategy}),t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(rH(e.publicKeyCredential))}:{...e},this._basePost({body:{...t,strategy:e.strategy},action:"attempt_second_factor"})};authenticateWithRedirectOrPopup=async(e,t)=>{let{strategy:i,redirectUrlComplete:r,identifier:n,oidcPrompt:s,slackTeamIdHint:a,continueSignIn:o,enterpriseConnectionId:l}=e||{},c=nY.clerk.buildUrlWithAuth(e.redirectUrl),d=()=>!!this.protectCheck||"needs_protect_check"===this.status,h=()=>{let{status:e,externalVerificationRedirectURL:t}=this.firstFactorVerification;return"unverified"===e?t:null},u=()=>{throw new R("A verification challenge must be completed before this sign-in can continue.",{code:"protect_check_required"})},p=null,_=!this.id||!o;if(_&&(await this.create({strategy:i,identifier:n,redirectUrl:c,actionCompleteRedirectUrl:r,oidcPrompt:s,slackTeamIdHint:a}),d()&&((p=h())||u())),("enterprise_sso"===i||!_&&void 0!==a)&&(await this._basePost({body:{strategy:i,redirectUrl:c,actionCompleteRedirectUrl:r,oidcPrompt:s,slackTeamIdHint:a,enterpriseConnectionId:l},action:"prepare_first_factor",coalesce:!0}),d())){if(p)return void t(p);u()}let{status:f,externalVerificationRedirectURL:m}=this.firstFactorVerification;"unverified"===f&&m?t(m):ie(f,nY.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>{let t=nY.clerk.__internal_oauthTransport;return t?nV({clerk:nY.clerk,transport:t,resource:this,authenticateMethod:this.authenticateWithRedirectOrPopup,params:e,callbackParams:e.__internal_callbackParams??{}}):this.authenticateWithRedirectOrPopup(e,nY.clerk.__internal_windowNavigate)};authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||t7("popup"),nW(nY.clerk,"signIn",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e.toString()})};authenticateWithWeb3=async e=>{let t,{identifier:i,generateSignature:r,strategy:n="web3_metamask_signature",walletName:s}=e||{},a=n.replace("web3_","").replace("_signature","");"function"!=typeof r&&t7("generateSignature"),"solana"!==a||s||t7("walletName"),await this.create({identifier:i});let o=this.supportedFirstFactors?.find(e=>e.strategy===n);o||t9("SignIn"),await this.prepareFirstFactor(o);let{message:l}=this.firstFactorVerification;l||t9("SignIn");try{t=await r({identifier:i,nonce:l,walletName:s,provider:a})}catch(e){if("coinbase_wallet"===a&&4001===e.code)t=await r({identifier:i,nonce:l,provider:a,walletName:s});else throw e}return this.attemptFirstFactor({signature:t,strategy:n})};authenticateWithMetamask=async()=>{let e=await tY().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tY().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await tY().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tY().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await tY().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tY().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await tY().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tY().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithSolana=async({walletName:e})=>{let t=await tY().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:t,generateSignature:t=>tY().generateSignatureWithSolana({...t,walletName:e}),strategy:"web3_solana_signature",walletName:e})};authenticateWithPasskey=async e=>{let{flow:t}=e||{},i=nY.clerk.__internal_isWebAuthnSupported||nw,r=nY.clerk.__internal_getPublicCredentials||rJ,n=nY.clerk.__internal_isWebAuthnAutofillSupported||nb;if(!i())throw new q("Passkeys are not supported",{code:"passkey_not_supported"});let s="needs_second_factor"===this.status||"needs_client_trust"===this.status,a=(this.supportedSecondFactors||[]).some(e=>"passkey"===e.strategy);if(!t&&s&&a){await this.prepareSecondFactor({strategy:"passkey"});let{nonce:e}=this.secondFactorVerification,t=e?rV(JSON.parse(e)):null;t||ii("get");let{publicKeyCredential:i,error:n}=await r({publicKeyOptions:t,conditionalUI:!1});if(!i)throw n;return this.attemptSecondFactor({publicKeyCredential:i,strategy:"passkey"})}if("autofill"===t||"discoverable"===t)await this.create({strategy:"passkey"});else{let e=this.supportedFirstFactors.find(e=>"passkey"===e.strategy);e||function(){throw Error(`${t2} You need to start a SignIn flow by calling SignIn.create({ strategy: 'passkey' }) first`)}(),await this.prepareFirstFactor(e)}let{nonce:o}=this.firstFactorVerification,l=o?rV(JSON.parse(o)):null;l||ii("get");let c=!1;"autofill"===t&&(c=await n());let{publicKeyCredential:d,error:h}=await r({publicKeyOptions:l,conditionalUI:c});if(!d)throw h;return this.attemptFirstFactor({publicKeyCredential:d,strategy:"passkey"})};validatePassword=(e,t)=>{if(nY.clerk.__internal_environment?.userSettings.passwordSettings)return nN(nG(),{...nY.clerk.__internal_environment?.userSettings.passwordSettings,validatePassword:!0})(e,t)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.supportedIdentifiers=e.supported_identifiers,this.identifier=e.identifier,this.supportedFirstFactors=ef(e.supported_first_factors),this.supportedSecondFactors=ef(e.supported_second_factors),this.ssoBypassFirstFactors=ef(e.sso_bypass_first_factors??null),this.firstFactorVerification=new rX(e.first_factor_verification),this.secondFactorVerification=new rX(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new sa(e.user_data),this.clientTrustState=e.client_trust_state??void 0,this.protectCheck=e.protect_check?{status:e.protect_check.status,token:e.protect_check.token,sdkUrl:e.protect_check.sdk_url,expiresAt:e.protect_check.expires_at,uiHints:e.protect_check.ui_hints}:null,this.timezone=e.timezone??null),rp.emit("resource:update",{resource:this}),this}clientBypass(){return nY.clerk.client?.captchaBypass}shouldRequireCaptcha(e){return"signUpIfMissing"in e&&!!e.signUpIfMissing}shouldBypassCaptchaForAttempt(e){let t=nY.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer&&nY.clerk.client?.signUp?.verifications?.externalAccount?.status==="transferable"){let e=nY.clerk.client.signUp.verifications.externalAccount.strategy;return!!e&&t.some(t=>t===e)}return"strategy"in e&&!!e.strategy&&t.some(t=>t===e.strategy)}__internal_updateFromJSON(e){return this.fromJSON(e)}__internal_toSnapshot(){return{object:"sign_in",id:this.id||"",status:this.status||null,supported_identifiers:this.supportedIdentifiers,supported_first_factors:e_(this.supportedFirstFactors),supported_second_factors:e_(this.supportedSecondFactors),sso_bypass_first_factors:e_(this.ssoBypassFirstFactors)??void 0,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(),timezone:this.timezone,protect_check:this.protectCheck?{status:this.protectCheck.status,token:this.protectCheck.token,sdk_url:this.protectCheck.sdkUrl,...void 0!==this.protectCheck.expiresAt&&{expires_at:this.protectCheck.expiresAt},...void 0!==this.protectCheck.uiHints&&{ui_hints:this.protectCheck.uiHints}}:null}}}class nZ{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(!m())return null;const e=eX("__clerk_status"),t=eX("__clerk_created_session");if(!e||!t)return null;const i="verified"===e&&void 0!==nY.clerk.client&&nY.clerk.client.sessions.some(e=>e.id===t);return{status:e,createdSessionId:t,verifiedFromTheSameClient:i}}};resetPasswordEmailCode={sendCode:this.sendResetPasswordEmailCode.bind(this),verifyCode:this.verifyResetPasswordEmailCode.bind(this),submitPassword:this.submitResetPassword.bind(this)};resetPasswordPhoneCode={sendCode:this.sendResetPasswordPhoneCode.bind(this),verifyCode:this.verifyResetPasswordPhoneCode.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),sendEmailCode:this.sendMFAEmailCode.bind(this),verifyEmailCode:this.verifyMFAEmailCode.bind(this),verifyTOTP:this.verifyTOTP.bind(this),verifyBackupCode:this.verifyBackupCode.bind(this),passkey:this.verifyMFAPasskey.bind(this)};#H=!1;#G;constructor(e){this.#G=e}get id(){return this.#G.id}get identifier(){return this.#G.identifier}get timezone(){return this.#G.timezone}get createdSessionId(){return this.#G.createdSessionId}get userData(){return this.#G.userData}get status(){return this.#G.status||"needs_identifier"}get supportedFirstFactors(){return this.#G.supportedFirstFactors??[]}get supportedSecondFactors(){return this.#G.supportedSecondFactors??[]}get ssoBypassFirstFactors(){return this.#G.ssoBypassFirstFactors??[]}get isTransferable(){return"transferable"===this.#G.firstFactorVerification.status}get existingSession(){if("failed"===this.#G.firstFactorVerification.status&&this.#G.firstFactorVerification.error?.code==="identifier_already_signed_in"&&this.#G.firstFactorVerification.error?.meta?.sessionId)return{sessionId:this.#G.firstFactorVerification.error?.meta?.sessionId}}get firstFactorVerification(){return this.#G.firstFactorVerification}get secondFactorVerification(){return this.#G.secondFactorVerification}get protectCheck(){return this.#G.protectCheck}async submitProtectCheck(e){return nq(this.#G,async()=>{await this.#G.__internal_basePatch({action:"protect_check",body:{proof_token:e.proofToken}})})}get canBeDiscarded(){return this.#H}async sendResetPasswordEmailCode(){if(!this.#G.id)throw Error("Cannot reset password without a sign in.");return nq(this.#G,async()=>{let e=this.#G.supportedFirstFactors?.find(e=>"reset_password_email_code"===e.strategy);if(!e)throw new R("Reset password email code factor not found",{code:"factor_not_found"});let{emailAddressId:t}=e;await this.#G.__internal_basePost({body:{emailAddressId:t,strategy:"reset_password_email_code"},action:"prepare_first_factor",coalesce:!0})})}async verifyResetPasswordEmailCode(e){let{code:t}=e;return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{code:t,strategy:"reset_password_email_code"},action:"attempt_first_factor"})})}async sendResetPasswordPhoneCode(e={}){let{phoneNumber:t}=e;if(!this.#G.id&&!t)throw Error("signIn.resetPasswordPhoneCode.sendCode() cannot be called without a phoneNumber if an existing signIn does not exist.");return nq(this.#G,async()=>{t&&await this._create({identifier:t});let e=this.#G.supportedFirstFactors?.find(e=>"reset_password_phone_code"===e.strategy);if(!e)throw new R("Reset password phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:i}=e;await this.#G.__internal_basePost({body:{phoneNumberId:i,strategy:"reset_password_phone_code"},action:"prepare_first_factor",coalesce:!0})})}async verifyResetPasswordPhoneCode(e){let{code:t}=e;return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{code:t,strategy:"reset_password_phone_code"},action:"attempt_first_factor"})})}async submitResetPassword(e){let{password:t,signOutOfOtherSessions:i=!0}=e;return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{password:t,signOutOfOtherSessions:i},action:"reset_password"})})}shouldRequireCaptcha(e){return!!e.signUpIfMissing}shouldBypassCaptchaForAttempt(e){let t=nY.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer&&nY.clerk.client?.signUp?.verifications?.externalAccount?.status==="transferable"){let e=nY.clerk.client.signUp.verifications.externalAccount.strategy;return!!e&&t.some(t=>t===e)}return!!e.strategy&&t.some(t=>t===e.strategy)}async getCaptchaToken(e={}){if(!this.shouldRequireCaptcha(e)||nY.clerk.client?.captchaBypass||this.shouldBypassCaptchaForAttempt(e))return{captchaToken:void 0,captchaWidgetType:void 0,captchaError:void 0};let t=new id(nY.clerk),i=await t.managedOrInvisible({action:"signin"});if(!i)throw Error("Captcha challenge failed");let{captchaError:r,captchaToken:n,captchaWidgetType:s}=i;return{captchaToken:n,captchaWidgetType:s,captchaError:r}}async _create(e,t){let{captchaToken:i,captchaWidgetType:r,captchaError:n}=await this.getCaptchaToken(e),s=e.timezone??nH(),a={...e,captchaToken:i,captchaWidgetType:r,captchaError:n,locale:tq()||void 0,...null!==s?{timezone:s}:{}};await this.#G.__internal_basePost({path:this.#G.pathRoot,body:a},t)}async create(e){return nq(this.#G,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 nq(this.#G,async()=>{let t=e.identifier||e.emailAddress||e.phoneNumber,i=this.#G.identifier,r=tq(),n=e.timezone??this.#G.timezone??nH();await this.#G.__internal_basePost({path:this.#G.pathRoot,body:{identifier:t||i,password:e.password,...r?{locale:r}:{},...null!==n?{timezone:n}:{}}})})}async sendEmailCode(e={}){let{emailAddress:t,emailAddressId:i}=e;if(!this.#G.id&&i)throw Error("signIn.emailCode.sendCode() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#G.id&&!t)throw Error("signIn.emailCode.sendCode() cannot be called without an emailAddress if an existing signIn does not exist.");return nq(this.#G,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_code",emailAddressId:i});if(!e)throw new R("Email code factor not found",{code:"factor_not_found"});await this.#G.__internal_basePost({body:{emailAddressId:e.emailAddressId,strategy:"email_code"},action:"prepare_first_factor",coalesce:!0})})}async verifyEmailCode(e){let{code:t}=e;return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{code:t,strategy:"email_code"},action:"attempt_first_factor"})})}async sendEmailLink(e){let{emailAddress:t,verificationUrl:i,emailAddressId:r}=e;if(!this.#G.id&&r)throw Error("signIn.emailLink.sendLink() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#G.id&&!t)throw Error("signIn.emailLink.sendLink() cannot be called without an emailAddress if an existing signIn does not exist.");return nq(this.#G,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_link",emailAddressId:r});if(!e)throw new R("Email link factor not found",{code:"factor_not_found"});let n=i;try{new URL(i)}catch{n=window.location.origin+i}await this.#G.__internal_basePost({body:{emailAddressId:e.emailAddressId,redirectUrl:n,strategy:"email_link"},action:"prepare_first_factor",coalesce:!0})})}async waitForEmailLinkVerification(){return nq(this.#G,async()=>{let{run:e,stop:t}=rW();await new Promise((i,r)=>{e(async()=>{try{let e=await this.#G.__internal_baseGet();nX(e.firstFactorVerification.status)&&(t(),i(e))}catch(e){t(),r(e)}})})})}async sendPhoneCode(e={}){let{phoneNumber:t,phoneNumberId:i,channel:r="sms"}=e;if(!this.#G.id&&i)throw Error("signIn.phoneCode.sendCode() cannot be called with an phoneNumberId if an existing signIn does not exist.");if(!this.#G.id&&!t)throw Error("signIn.phoneCode.sendCode() cannot be called without an phoneNumber if an existing signIn does not exist.");return nq(this.#G,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"phone_code",phoneNumberId:i});if(!e)throw new R("Phone code factor not found",{code:"factor_not_found"});await this.#G.__internal_basePost({body:{phoneNumberId:e.phoneNumberId,strategy:"phone_code",channel:r},action:"prepare_first_factor",coalesce:!0})})}async verifyPhoneCode(e){let{code:t}=e;return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_first_factor"})})}async sso(e){let{strategy:t,redirectUrl:i,redirectCallbackUrl:r,popup:n,oidcPrompt:s,slackTeamIdHint:a,enterpriseConnectionId:o,identifier:l}=e;return nq(this.#G,async()=>{let e=i;try{new URL(i)}catch{e=window.location.origin+i}let c={redirectUrl:nY.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:e};if(n){let t=nL(nY.clerk,{redirectCallbackUrl:c.redirectUrl,redirectUrl:e});c.redirectUrl=t.redirectCallbackUrl,c.actionCompleteRedirectUrl=t.redirectUrl}let d=!!this.#G.firstFactorVerification.externalVerificationRedirectURL,h="enterprise_sso"!==t&&d,u=!this.#G.id||h,p=()=>!!this.#G.protectCheck||"needs_protect_check"===this.#G.status,_=()=>{let{status:e,externalVerificationRedirectURL:t}=this.#G.firstFactorVerification;return"unverified"===e?t:null},f=()=>nQ.getInstance().resolve(nY.clerk,this.#G),m=null;if(u&&(await this._create({strategy:t,...c,identifier:l,oidcPrompt:s,slackTeamIdHint:a},{resolveProtectCheck:!1}),p()&&((m=_())||await f())),"enterprise_sso"===t||!u&&void 0!==a){let e=e=>this.#G.__internal_basePost({body:{...c,oidcPrompt:s,slackTeamIdHint:a,enterpriseConnectionId:o,strategy:t},action:"prepare_first_factor",coalesce:!0},e);await e({resolveProtectCheck:!1}),p()&&!m&&(await f(),await e())}let g=m??_();g&&(n?(await n$(nY.clerk,{popup:n,externalVerificationRedirectURL:g}),await this.#G.reload(),await f()):nY.clerk.__internal_windowNavigate(g))})}async web3(e){let{strategy:t}=e,i=t.replace("web3_","").replace("_signature","");return nq(this.#G,async()=>{let r,n,s;switch(i){case"metamask":r=await tY().getMetamaskIdentifier(),n=tY().generateSignatureWithMetamask;break;case"coinbase_wallet":r=await tY().getCoinbaseWalletIdentifier(),n=tY().generateSignatureWithCoinbaseWallet;break;case"base":r=await tY().getBaseIdentifier(),n=tY().generateSignatureWithBase;break;case"okx_wallet":r=await tY().getOKXWalletIdentifier(),n=tY().generateSignatureWithOKXWallet;break;case"solana":if(!e.walletName)throw new R("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});r=await tY().getSolanaIdentifier(e.walletName),n=t=>tY().generateSignatureWithSolana({...t,walletName:e.walletName});break;default:throw Error(`Unsupported Web3 provider: ${i}`)}await this._create({identifier:r});let a=this.#G.supportedFirstFactors?.find(e=>e.strategy===t);if(!a)throw new R("Web3 first factor not found",{code:"factor_not_found"});await this.#G.__internal_basePost({body:{web3WalletId:a.web3WalletId,strategy:t},action:"prepare_first_factor",coalesce:!0});let{message:o}=this.firstFactorVerification;if(!o)throw new R("Web3 nonce not found",{code:"web3_nonce_not_found"});try{s=await n({identifier:r,nonce:o,walletName:e?.walletName,provider:i})}catch(e){if("coinbase_wallet"===i&&4001===e.code)s=await n({identifier:r,nonce:o,provider:i});else throw e}await this.#G.__internal_basePost({body:{signature:s,strategy:t},action:"attempt_first_factor"})})}async passkey(e){let{flow:t}=e||{},i=nY.clerk.__internal_isWebAuthnSupported||nw,r=nY.clerk.__internal_getPublicCredentials||rJ,n=nY.clerk.__internal_isWebAuthnAutofillSupported||nb;if(!i())throw new q("Passkeys are not supported",{code:"passkey_not_supported"});return nq(this.#G,async()=>{if("autofill"===t||"discoverable"===t)await this._create({strategy:"passkey"});else{if(!this.supportedFirstFactors.find(e=>"passkey"===e.strategy))throw new R("Passkey factor not found",{code:"factor_not_found"});await this.#G.__internal_basePost({body:{strategy:"passkey"},action:"prepare_first_factor",coalesce:!0})}let{nonce:e}=this.firstFactorVerification,i=e?rV(JSON.parse(e)):null;if(!i)throw new R("Missing public key options",{code:"missing_public_key_options"});let s=!1;"autofill"===t&&(s=await n());let{publicKeyCredential:a,error:o}=await r({publicKeyOptions:i,conditionalUI:s});if(!a)throw new q(o.message,{code:"passkey_retrieval_failed"});await this.#G.__internal_basePost({body:{publicKeyCredential:JSON.stringify(rH(a)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return nq(this.#G,async()=>{let e=this.#G.supportedSecondFactors?.find(e=>"phone_code"===e.strategy);if(!e)throw new R("Phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:t}=e;await this.#G.__internal_basePost({body:{phoneNumberId:t,strategy:"phone_code"},action:"prepare_second_factor",coalesce:!0})})}async verifyMFAPhoneCode(e){let{code:t}=e;return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_second_factor"})})}async sendMFAEmailCode(){return nq(this.#G,async()=>{let e=this.#G.supportedSecondFactors?.find(e=>"email_code"===e.strategy);if(!e)throw new R("Email code factor not found",{code:"factor_not_found"});let{emailAddressId:t}=e;await this.#G.__internal_basePost({body:{emailAddressId:t,strategy:"email_code"},action:"prepare_second_factor",coalesce:!0})})}async verifyMFAEmailCode(e){let{code:t}=e;return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{code:t,strategy:"email_code"},action:"attempt_second_factor"})})}async verifyTOTP(e){let{code:t}=e;return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{code:t,strategy:"totp"},action:"attempt_second_factor"})})}async verifyBackupCode(e){let{code:t}=e;return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{code:t,strategy:"backup_code"},action:"attempt_second_factor"})})}async verifyMFAPasskey(){let e=nY.clerk.__internal_isWebAuthnSupported||nw,t=nY.clerk.__internal_getPublicCredentials||rJ;if(!e())throw new q("Passkeys are not supported",{code:"passkey_not_supported"});return nq(this.#G,async()=>{if(!this.#G.supportedSecondFactors?.find(e=>"passkey"===e.strategy))throw new R("Passkey factor not found",{code:"factor_not_found"});await this.#G.__internal_basePost({body:{strategy:"passkey"},action:"prepare_second_factor",coalesce:!0});let{nonce:e}=this.#G.secondFactorVerification,i=e?rV(JSON.parse(e)):null;if(!i)throw new R("Missing public key options",{code:"missing_public_key_options"});let{publicKeyCredential:r,error:n}=await t({publicKeyOptions:i,conditionalUI:!1});if(!r)throw new q(n.message,{code:"passkey_retrieval_failed"});await this.#G.__internal_basePost({body:{publicKeyCredential:JSON.stringify(rH(r)),strategy:"passkey"},action:"attempt_second_factor"})})}async ticket(e){let t=e?.ticket??eX("__clerk_ticket");return this.create({strategy:"ticket",ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};if(!this.#G.createdSessionId)throw Error("Cannot finalize sign-in without a created session.");return nq(this.#G,async()=>{nY.clerk.client&&!nY.clerk.client.sessions.some(e=>e.id===this.#G.createdSessionId)&&await nY.clerk.client.reload(),this.#H=!0,await nY.clerk.setActive({session:this.#G.createdSessionId,navigate:t})})}reset(){if(!nY.clerk.client)throw Error("Cannot reset sign-in without a client.");return this.#H=!0,nY.clerk.client.resetSignIn(),Promise.resolve({error:null})}selectFirstFactor({strategy:e,emailAddressId:t,phoneNumberId:i}){if(!this.#G.supportedFirstFactors)return null;if(t){let i=this.#G.supportedFirstFactors.find(i=>i.strategy===e&&i.emailAddressId===t);if(i)return i}if(i){let t=this.#G.supportedFirstFactors.find(t=>t.strategy===e&&t.phoneNumberId===i);if(t)return t}let r=this.#G.supportedFirstFactors.find(t=>t.strategy===e&&t.safeIdentifier===this.#G.identifier);if(r)return r;let n=this.#G.supportedFirstFactors.find(t=>t.strategy===e);return n||null}}function n0(e){let{unsafeMetadata:t}={...e},i=t?"object"==typeof t?JSON.stringify(t):t:"";return{...e,...t?{unsafeMetadata:i}:{}}}class n1 extends iu{pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new rZ(null);username=null;firstName=null;lastName=null;emailAddress=null;phoneNumber=null;web3wallet=null;externalAccount;hasPassword=!1;unsafeMetadata={};protectCheck=null;createdSessionId=null;createdUserId=null;abandonAt=null;legalAcceptedAt=null;locale=null;timezone=null;get status(){return this._status}set status(e){let t=this._status;this._status=e,e&&t!==e&&tS.debug("SignUp.status",{id:this.id,from:t,to:e})}__internal_future=new n5(this);__internal_basePost=async(e,{resolveProtectCheck:t=!0}={})=>(await this._basePost(e),t&&await nQ.getInstance().resolve(n1.clerk,this,e?.action),this);__internal_basePatch=async(e,{resolveProtectCheck:t=!0}={})=>(await this._basePatch(e),t&&await nQ.getInstance().resolve(n1.clerk,this,e?.action),this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{tS.debug("SignUp.create",{id:this.id,strategy:e.strategy});let t={...e};if(!t.locale){let e=tq();e&&(t.locale=e)}if(void 0===t.timezone){let e=nH();e&&(t.timezone=e)}if(!this.clientBypass()&&!this.shouldBypassCaptchaForAttempt(e)){let e=new id(n1.clerk),i=await e.managedOrInvisible({action:"signup"});if(!i)throw new R("",{code:"captcha_unavailable"});t={...t,...i}}return this._basePost({path:this.pathRoot,body:n0(t)})};prepareVerification=e=>(tS.debug("SignUp.prepareVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_verification",coalesce:!0}));attemptVerification=e=>(tS.debug("SignUp.attemptVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_verification"}));submitProtectCheck=e=>(tS.debug("SignUp.submitProtectCheck",{id:this.id}),this._basePatch({action:"protect_check",body:{proof_token:e.proofToken}}));prepareEmailAddressVerification=e=>this.prepareVerification(e||{strategy:"email_code"});attemptEmailAddressVerification=e=>this.attemptVerification({...e,strategy:"email_code"});createEmailLinkFlow=()=>{let{run:e,stop:t}=rW();return{startEmailLinkFlow:async({redirectUrl:i})=>(this.id||t6("SignUp"),await this.prepareEmailAddressVerification({strategy:"email_link",redirectUrl:i}),new Promise((i,r)=>{e(()=>this.reload().then(e=>{let r=e.verifications.emailAddress.status;("verified"===r||"expired"===r)&&(t(),i(e))}).catch(e=>{t(),r(e)}))})),cancelEmailLinkFlow:t}};preparePhoneNumberVerification=e=>this.prepareVerification(e||{strategy:"phone_code"});attemptPhoneNumberVerification=e=>this.attemptVerification({...e,strategy:"phone_code"});prepareWeb3WalletVerification=e=>this.prepareVerification({strategy:"web3_metamask_signature",...e});attemptWeb3WalletVerification=async e=>{let{signature:t,strategy:i="web3_metamask_signature"}=e;return this.attemptVerification({signature:t,strategy:i})};authenticateWithWeb3=async e=>{let t,{generateSignature:i,identifier:r,unsafeMetadata:n,strategy:s="web3_metamask_signature",legalAccepted:a,walletName:o}=e||{},l=s.replace("web3_","").replace("_signature","");"function"!=typeof i&&t7("generateSignature");let c=r||this.web3wallet;await this.create({web3Wallet:c,unsafeMetadata:n,legalAccepted:a}),await this.prepareWeb3WalletVerification({strategy:s});let{message:d}=this.verifications.web3Wallet;d||t9("SignUp");try{t=await i({identifier:r,nonce:d,provider:l,walletName:o})}catch(e){if("coinbase_wallet"===l&&4001===e.code)t=await i({identifier:r,nonce:d,provider:l});else throw e}return this.attemptWeb3WalletVerification({signature:t,strategy:s})};authenticateWithMetamask=async e=>{let t=await tY().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tY().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let t=await tY().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tY().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let t=await tY().getBaseIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tY().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let t=await tY().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tY().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithSolana=async({walletName:e,unsafeMetadata:t,legalAccepted:i})=>{let r=await tY().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:r,generateSignature:t=>tY().generateSignatureWithSolana({...t,walletName:e}),unsafeMetadata:t,strategy:"web3_solana_signature",legalAccepted:i,walletName:e})};authenticateWithRedirectOrPopup=async(e,t)=>{let{redirectUrl:i,redirectUrlComplete:r,strategy:n,continueSignUp:s=!1,unsafeMetadata:a,emailAddress:o,legalAccepted:l,oidcPrompt:c,slackTeamIdHint:d,enterpriseConnectionId:h}=e,u=n1.clerk.buildUrlWithAuth(i),p=()=>{let e={strategy:n,redirectUrl:u,actionCompleteRedirectUrl:r,unsafeMetadata:a,emailAddress:o,legalAccepted:l,oidcPrompt:c,slackTeamIdHint:d,enterpriseConnectionId:h};return s&&this.id?this.update(e):this.create(e)},{verifications:_}=await p().catch(async e=>{if($(e)&&H(e))return await n1.clerk.__internal_environment.reload(),p();throw e}),{externalAccount:f}=_,{status:m,externalVerificationRedirectURL:g}=f;"unverified"===m&&g?t(g):ie(m,n1.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>{let t=n1.clerk.__internal_oauthTransport;return t?nV({clerk:n1.clerk,transport:t,resource:this,authenticateMethod:this.authenticateWithRedirectOrPopup,params:e,callbackParams:e.__internal_callbackParams??{}}):this.authenticateWithRedirectOrPopup(e,n1.clerk.__internal_windowNavigate)};authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||t7("popup"),nW(n1.clerk,"signUp",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e instanceof URL?e.toString():e})};update=e=>this._basePatch({body:n0(e)});upsert=e=>this.id?this.update(e):this.create(e);validatePassword=(e,t)=>{if(n1.clerk.__internal_environment?.userSettings.passwordSettings)return nN(nG(),{...n1.clerk.__internal_environment?.userSettings.passwordSettings,validatePassword:!0})(e,t)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.requiredFields=e.required_fields,this.optionalFields=e.optional_fields,this.missingFields=e.missing_fields,this.unverifiedFields=e.unverified_fields,this.verifications=new rZ(e.verifications),this.protectCheck=e.protect_check?{status:e.protect_check.status,token:e.protect_check.token,sdkUrl:e.protect_check.sdk_url,expiresAt:e.protect_check.expires_at,uiHints:e.protect_check.ui_hints}:null,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,this.timezone=e.timezone??null),rp.emit("resource:update",{resource:this}),this}__internal_updateFromJSON(e){return this.fromJSON(e)}__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(),protect_check:this.protectCheck?{status:this.protectCheck.status,token:this.protectCheck.token,sdk_url:this.protectCheck.sdkUrl,...void 0!==this.protectCheck.expiresAt&&{expires_at:this.protectCheck.expiresAt},...void 0!==this.protectCheck.uiHints&&{ui_hints:this.protectCheck.uiHints}}:null,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,timezone:this.timezone,external_account:this.externalAccount,external_account_strategy:this.externalAccount?.strategy}}clientBypass(){return n1.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){let t=n1.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer){let e=n1.clerk.client.signIn.firstFactorVerification.strategy;if(t.some(t=>t===e)||n2(e))return!0}return!!(e.strategy&&t.some(t=>t===e.strategy))}__experimental_getEnterpriseConnections=()=>iu._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new n6(e)))}let n3=new Set(["email_link","email_code","phone_code"]);function n2(e){return!!e&&(n3.has(e)||e.startsWith("web3_"))}class n4{#G;sendEmailCode;verifyEmailCode;sendEmailLink;waitForEmailLinkVerification;sendPhoneCode;verifyPhoneCode;constructor(e,t){this.#G=e,this.sendEmailCode=t.sendEmailCode,this.verifyEmailCode=t.verifyEmailCode,this.sendEmailLink=t.sendEmailLink,this.waitForEmailLinkVerification=t.waitForEmailLinkVerification,this.sendPhoneCode=t.sendPhoneCode,this.verifyPhoneCode=t.verifyPhoneCode}get emailAddress(){return this.#G.verifications.emailAddress}get phoneNumber(){return this.#G.verifications.phoneNumber}get web3Wallet(){return this.#G.verifications.web3Wallet}get externalAccount(){return this.#G.verifications.externalAccount}get emailLinkVerification(){if(!m())return null;let e=eX("__clerk_status"),t=eX("__clerk_created_session");if(!e||!t)return null;let i="verified"===e&&void 0!==n1.clerk.client&&n1.clerk.client.sessions.some(e=>e.id===t);return{status:e,createdSessionId:t,verifiedFromTheSameClient:i}}}class n5{verifications;#H=!1;#G;constructor(e){this.#G=e,this.verifications=new n4(this.#G,{sendEmailCode:this.sendEmailCode.bind(this),verifyEmailCode:this.verifyEmailCode.bind(this),sendEmailLink:this.sendEmailLink.bind(this),waitForEmailLinkVerification:this.waitForEmailLinkVerification.bind(this),sendPhoneCode:this.sendPhoneCode.bind(this),verifyPhoneCode:this.verifyPhoneCode.bind(this)})}get id(){return this.#G.id}get requiredFields(){return this.#G.requiredFields}get optionalFields(){return this.#G.optionalFields}get missingFields(){return this.#G.missingFields}get status(){return this.#G.status||"missing_requirements"}get username(){return this.#G.username}get firstName(){return this.#G.firstName}get lastName(){return this.#G.lastName}get emailAddress(){return this.#G.emailAddress}get phoneNumber(){return this.#G.phoneNumber}get web3Wallet(){return this.#G.web3wallet}get hasPassword(){return this.#G.hasPassword}get unsafeMetadata(){return this.#G.unsafeMetadata}get createdSessionId(){return this.#G.createdSessionId}get createdUserId(){return this.#G.createdUserId}get abandonAt(){return this.#G.abandonAt}get legalAcceptedAt(){return this.#G.legalAcceptedAt}get locale(){return this.#G.locale}get timezone(){return this.#G.timezone}get unverifiedFields(){return this.#G.unverifiedFields}get protectCheck(){return this.#G.protectCheck}get isTransferable(){return"transferable"===this.#G.verifications.externalAccount.status&&this.#G.verifications.externalAccount.error?.code===el}get existingSession(){if(("failed"===this.#G.verifications.externalAccount.status||"unverified"===this.#G.verifications.externalAccount.status)&&this.#G.verifications.externalAccount.error?.code==="identifier_already_signed_in"&&this.#G.verifications.externalAccount.error?.meta?.sessionId)return{sessionId:this.#G.verifications.externalAccount.error?.meta?.sessionId}}get canBeDiscarded(){return this.#H}shouldBypassCaptchaForAttempt(e){let t=n1.clerk.__internal_environment.displayConfig.captchaOauthBypass;if(e.transfer){let e=n1.clerk.client.signIn.firstFactorVerification.strategy;if(t.some(t=>t===e)||n2(e))return!0}return!!(e.strategy&&t.some(t=>t===e.strategy))}async getCaptchaToken(e={}){if(n1.clerk.client?.captchaBypass||this.shouldBypassCaptchaForAttempt(e))return{captchaToken:void 0,captchaWidgetType:void 0,captchaError:void 0};let t=new id(n1.clerk),i=await t.managedOrInvisible({action:"signup"});if(!i)throw Error("Captcha challenge failed");let{captchaError:r,captchaToken:n,captchaWidgetType:s}=i;return{captchaToken:n,captchaWidgetType:s,captchaError:r}}async _create(e){let{captchaToken:t,captchaWidgetType:i,captchaError:r}=await this.getCaptchaToken(e),n=e.timezone??nH(),s={transfer:e.transfer,captchaToken:t,captchaWidgetType:i,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?n0(e.unsafeMetadata):void 0,locale:e.locale??tq(),...null!==n?{timezone:n}:{}};await this.#G.__internal_basePost({path:this.#G.pathRoot,body:s})}async create(e){return nq(this.#G,async()=>{await this._create(e)})}async update(e){return nq(this.#G,async()=>{let t={...e,unsafeMetadata:e.unsafeMetadata?n0(e.unsafeMetadata):void 0};await this.#G.__internal_basePatch({body:t})})}async password(e){return nq(this.#G,async()=>{let{captchaToken:t,captchaWidgetType:i,captchaError:r}=await this.getCaptchaToken(),n={strategy:"password",captchaToken:t,captchaWidgetType:i,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?n0(e.unsafeMetadata):void 0};if(this.#G.id)await this.#G.__internal_basePatch({body:n});else{n.locale=e.locale??tq();let t=nH();null!==t&&(n.timezone=t),await this.#G.__internal_basePost({path:this.#G.pathRoot,body:n})}})}async sendEmailCode(){return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification",coalesce:!0})})}async verifyEmailCode(e){let{code:t}=e;return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{strategy:"email_code",code:t},action:"attempt_verification"})})}async sendPhoneCode(e){let{channel:t="sms"}=e||{};return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{strategy:"phone_code",channel:t},action:"prepare_verification",coalesce:!0})})}async verifyPhoneCode(e){let{code:t}=e;return nq(this.#G,async()=>{await this.#G.__internal_basePost({body:{strategy:"phone_code",code:t},action:"attempt_verification"})})}async sendEmailLink(e){let{verificationUrl:t}=e;return nq(this.#G,async()=>{let e=t;try{new URL(t)}catch{e=window.location.origin+t}await this.#G.__internal_basePost({body:{strategy:"email_link",redirectUrl:e},action:"prepare_verification",coalesce:!0})})}async waitForEmailLinkVerification(){return nq(this.#G,async()=>{let{run:e,stop:t}=rW();await new Promise((i,r)=>{e(()=>this.#G.reload().then(e=>{let r=e.verifications.emailAddress.status;("verified"===r||"expired"===r)&&(t(),i(e))}).catch(e=>{t(),r(e)}))})})}async sso(e){let{strategy:t,redirectUrl:i,redirectCallbackUrl:r,unsafeMetadata:n,legalAccepted:s,oidcPrompt:a,slackTeamIdHint:o,enterpriseConnectionId:l,emailAddress:c,popup:d,locale:h}=e;return nq(this.#G,async()=>{let{captchaToken:e,captchaWidgetType:u,captchaError:p}=await this.getCaptchaToken({strategy:t}),_=i;try{new URL(i)}catch{_=window.location.origin+i}let f={redirectUrl:n1.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:_};if(d){let e=nL(n1.clerk,{redirectCallbackUrl:f.redirectUrl,redirectUrl:_});f.redirectUrl=e.redirectCallbackUrl,f.actionCompleteRedirectUrl=e.redirectUrl}let m=()=>{let i={strategy:t,...f,unsafeMetadata:n,legalAccepted:s,oidcPrompt:a,slackTeamIdHint:o,enterpriseConnectionId:l,emailAddress:c,captchaToken:e,captchaWidgetType:u,captchaError:p,locale:h};if(this.#G.id)return this.#G.__internal_basePatch({body:i},{resolveProtectCheck:!1});i.locale=h??tq();let r=nH();return null!==r&&(i.timezone=r),this.#G.__internal_basePost({path:this.#G.pathRoot,body:i},{resolveProtectCheck:!1})};await m().catch(async e=>{if($(e)&&H(e))return await n1.clerk.__internal_environment.reload(),m();throw e});let g=()=>{let{status:e,externalVerificationRedirectURL:t}=this.#G.verifications.externalAccount;return"unverified"===e?t:null},y=()=>nQ.getInstance().resolve(n1.clerk,this.#G);this.#G.protectCheck&&!g()&&await y();let w=g();w&&(d?(await n$(n1.clerk,{popup:d,externalVerificationRedirectURL:w}),await this.#G.reload(),await y()):n1.clerk.__internal_windowNavigate(w))})}async web3(e){let{strategy:t,unsafeMetadata:i,legalAccepted:r,firstName:n,lastName:s,locale:a}=e,o=t.replace("web3_","").replace("_signature","");return nq(this.#G,async()=>{let e,l,c;switch(o){case"metamask":e=await tY().getMetamaskIdentifier(),l=tY().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await tY().getCoinbaseWalletIdentifier(),l=tY().generateSignatureWithCoinbaseWallet;break;case"base":e=await tY().getBaseIdentifier(),l=tY().generateSignatureWithBase;break;case"okx_wallet":e=await tY().getOKXWalletIdentifier(),l=tY().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${o}`)}let d=e||this.#G.web3wallet;await this._create({web3Wallet:d,unsafeMetadata:i,legalAccepted:r,firstName:n,lastName:s,locale:a}),await this.#G.__internal_basePost({body:{strategy:t},action:"prepare_verification",coalesce:!0});let{message:h}=this.#G.verifications.web3Wallet;h||t9("SignUp");try{c=await l({identifier:e,nonce:h})}catch(t){if("coinbase_wallet"===o&&4001===t.code)c=await l({identifier:e,nonce:h});else throw t}await this.#G.__internal_basePost({body:{signature:c,strategy:t},action:"attempt_verification"})})}async submitProtectCheck(e){return nq(this.#G,async()=>{await this.#G.__internal_basePatch({action:"protect_check",body:{proof_token:e.proofToken}})})}async ticket(e){let t=e?.ticket??eX("__clerk_ticket");return this.create({...e,strategy:"ticket",ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};return nq(this.#G,async()=>{if(!this.#G.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#H=!0,await n1.clerk.setActive({session:this.#G.createdSessionId,navigate:t})})}reset(){if(!n1.clerk.client)throw Error("Cannot reset sign-up without a client.");return this.#H=!0,n1.clerk.client.resetSignUp(),Promise.resolve({error:null})}}class n6 extends iu{id;name;provider;logoPublicUrl=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.provider=e.provider,this.logoPublicUrl=e.logo_public_url??null),this}}class n8 extends iu{pathRoot="tokens";jwt;static async create(e,t={},i={}){return new n8(await iu._fetch({method:"POST",path:e,body:t,search:i}),e)}constructor(e,t){super(),t&&(this.pathRoot=t),e?.jwt&&(this.jwt=tV(e.jwt))}getRawString=()=>this.jwt?.claims.__raw||"";fromJSON(e){return e&&(this.jwt=tV(e.jwt)),this}__internal_toSnapshot(){return{object:"token",id:this.id||"",jwt:this.getRawString()}}}class n9 extends iu{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=tE(e.updated_at),this.createdAt=tE(e.created_at)),this}}var n7=Object.prototype.hasOwnProperty;function se(e,t,i){for(i of e.keys())if(st(i,t))return i}function st(e,t){var i,r,n;if(e===t)return!0;if(e&&t&&(i=e.constructor)===t.constructor){if(i===Date)return e.getTime()===t.getTime();if(i===RegExp)return e.toString()===t.toString();if(i===Array){if((r=e.length)===t.length)for(;r--&&st(e[r],t[r]););return -1===r}if(i===Set){if(e.size!==t.size)return!1;for(r of e)if((n=r)&&"object"==typeof n&&!(n=se(t,n))||!t.has(n))return!1;return!0}if(i===Map){if(e.size!==t.size)return!1;for(r of e)if((n=r[0])&&"object"==typeof n&&!(n=se(t,n))||!st(r[1],t.get(n)))return!1;return!0}if(i===ArrayBuffer)e=new Uint8Array(e),t=new Uint8Array(t);else if(i===DataView){if((r=e.byteLength)===t.byteLength)for(;r--&&e.getInt8(r)===t.getInt8(r););return -1===r}if(ArrayBuffer.isView(e)){if((r=e.byteLength)===t.byteLength)for(;r--&&e[r]===t[r];);return -1===r}if(!i||"object"==typeof e){for(i in r=0,e)if(n7.call(e,i)&&++r&&!n7.call(t,i)||!(i in t)||!st(e[i],t[i]))return!1;return Object.keys(t).length===r}}return e!=e&&t!=t}function si(e){if("object"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);return null===t||t===Object.prototype}class sr extends iu{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=tE(e.updated_at),this.createdAt=tE(e.created_at)),this}}class sn extends iu{advisory=null;form={name:"",slug:"",logo:null,blurHash:null};constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(e.advisory&&(this.advisory=this.withDefault(e.advisory,this.advisory??null)),e.form&&(this.form.name=this.withDefault(e.form.name,this.form.name),this.form.slug=this.withDefault(e.form.slug,this.form.slug),this.form.logo=this.withDefault(e.form.logo,this.form.logo),this.form.blurHash=this.withDefault(e.form.blur_hash,this.form.blurHash))),this}static async retrieve(){return await iu._fetch({path:"/me/organization_creation_defaults",method:"GET"}).then(e=>new sn(e?.response))}__internal_toSnapshot(){return{advisory:this.advisory?{code:this.advisory.code,meta:this.advisory.meta,severity:this.advisory.severity}:null,form:{name:this.form.name,slug:this.form.slug,logo:this.form.logo,blur_hash:this.form.blurHash}}}}class ss extends iu{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;timezone=null;cachedSessionsWithActivities=null;static isUserResource(e){return!!e&&e instanceof ss}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case rL:return this.primaryEmailAddressId===e.id;case nS:return this.primaryPhoneNumberId===e.id;case sd:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:t}=e||{};return new rL({email_address:t},this.path()+"/email_addresses/").create()};createPasskey=()=>nk.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:t}=e||{};return new nS({phone_number:t},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:t}=e||{};return new sd({web3_wallet:t},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:t,redirectUrl:i,additionalScopes:r,enterpriseConnectionId:n,oidcPrompt:s,oidcLoginHint:a}=e||{};return new no((await iu._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:t,redirect_url:i,additional_scope:r,enterprise_connection_id:n,oidc_prompt:s,oidc_login_hint:a}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new n9((await iu._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new n9((await iu._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new rN((await iu._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new sr((await iu._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);__experimental_getBiometricCredentials=()=>rl.list();__experimental_prepareBiometricCredential=e=>rl.prepare(e);__experimental_attemptBiometricCredential=e=>rl.attempt(e);__experimental_revokeBiometricCredential=e=>rl.revoke(e);update=async e=>{var t;let{unsafeMetadata:i,...r}=e,n=void 0!==i,s=Object.keys(r).length>0;if(!n)return this._basePatch({body:n0(e)});((t=iu.clerk.publishableKey).startsWith("test_")||t.startsWith("pk_test_"))&&console.warn('Clerk - DEPRECATION WARNING: "user.update({ unsafeMetadata })" is deprecated and will be removed in the next major release.\nUse user.updateMetadata({ unsafeMetadata }) for partial updates (deep merge) instead.'),s?await this._basePatch({body:n0(r)}):await this.reload();let a=function e(t,i){if(null===i)return null;if(!si(t)||!si(i))return i;let r={};for(let n of Object.keys(i)){let s=t[n],a=i[n];if(!(n in t)){r[n]=a;continue}if(si(s)&&si(a)){let t=e(s,a);if(si(t)&&0===Object.keys(t).length)continue;r[n]=t}else st(s,a)||(r[n]=a)}for(let e of Object.keys(t))e in i||(r[e]=null);return r}(this.unsafeMetadata,i);return null!==a&&"object"==typeof a&&0===Object.keys(a).length?this:this.updateMetadata({unsafeMetadata:a})};updateMetadata=e=>this._basePatch({path:`${this.path()}/metadata`,body:n0(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=>(rp.emit(rd,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await nF.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:t}=e||{};return null===t?nd.delete(`${this.path()}/profile_image`):nd.create(`${this.path()}/profile_image`,{file:t})};getOrganizationInvitations=e=>so.retrieve(e);getOrganizationSuggestions=e=>ny.retrieve(e);getOrganizationMemberships=e=>ng.retrieve(e);getOrganizationCreationDefaults=()=>sn.retrieve();leaveOrganization=async e=>new rN((await iu._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);getEnterpriseConnections=async e=>{let{withOrganizationAccountLinking:t}=e||{};return((await iu._fetch({path:"/me/enterprise_connections",method:"GET",...void 0!==t?{search:{with_organization_account_linking:String(t)}}:{}}))?.response||[]).map(e=>new r7(e))};initializePaymentMethod=e=>i5(e);addPaymentMethod=e=>i6(e);getPaymentMethods=e=>i8(e);get verifiedExternalAccounts(){return this.externalAccounts.filter(e=>e.verification?.status=="verified")}get unverifiedExternalAccounts(){return this.externalAccounts.filter(e=>e.verification?.status!="verified")}get verifiedWeb3Wallets(){return this.web3Wallets.filter(e=>e.verification?.status=="verified")}get hasVerifiedEmailAddress(){return this.emailAddresses.filter(e=>"verified"===e.verification.status).length>0}get hasVerifiedPhoneNumber(){return this.phoneNumbers.filter(e=>"verified"===e.verification.status).length>0}fromJSON(e){return e&&(this.id=e.id,this.externalId=e.external_id||null,this.firstName=e.first_name||null,this.lastName=e.last_name||null,(this.firstName||this.lastName)&&(this.fullName=(({firstName:e,lastName:t,name:i})=>i||[e,t].join(" ").trim()||"")({firstName:this.firstName,lastName:this.lastName})),this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.username=e.username||null,this.passwordEnabled=e.password_enabled||!1,this.emailAddresses=(e.email_addresses||[]).map(e=>new rL(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 nS(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 sd(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 no(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new nk(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new ng(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new r1(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,this.timezone=e.timezone??null,e.last_sign_in_at&&(this.lastSignInAt=tE(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=tE(e.legal_accepted_at)),this.updatedAt=tE(e.updated_at||void 0),this.createdAt=tE(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,timezone:this.timezone}}}class sa{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 so extends iu{id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await iu._fetch({path:"/me/organization_invitations",method:"GET",search:iN(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new so(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=tE(e.created_at),this.updatedAt=tE(e.updated_at)),this}}let sl={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 sc extends iu{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:{...sl,name:"phone_number"},username:{...sl,name:"username"},web3_wallet:{...sl,name:"web3_wallet"},first_name:{...sl,name:"first_name"},last_name:{...sl,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:{...sl,name:"authenticator_app"},backup_code:{...sl,name:"backup_code"},passkey:{...sl,name:"passkey"}};attackProtection={enumeration_protection:{enabled:!1}};enterpriseSSO={enabled:!1,self_serve_sso:!1,self_serve_directory_sync:!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,mfa:{required:!1}};social={};usernameSettings={};get authenticatableSocialStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled&&e.authenticatable).map(([,e])=>e.strategy).sort():[]}get enabledFirstFactorIdentifiers(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&!e.startsWith("web3")).map(([e])=>e):[]}get socialProviderStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled).map(([,e])=>e.strategy).sort():[]}get web3FirstFactors(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&e.startsWith("web3")).map(([,e])=>e.first_factors).flat():[]}get alternativePhoneCodeChannels(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&"phone_number"===e).map(([,e])=>e?.channels?.filter(e=>"sms"!==e)||[]).flat():[]}constructor(e=null){super(),this.fromJSON(e)}get instanceIsPasswordBased(){return!!this.attributes?.password?.enabled}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.attackProtection={enumeration_protection:{enabled:e.attack_protection?.enumeration_protection?.enabled??this.attackProtection.enumeration_protection.enabled}},this.enterpriseSSO={...this.withDefault(e.enterprise_sso,this.enterpriseSSO),self_serve_directory_sync:e.enterprise_sso?.self_serve_directory_sync??!1},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,attack_protection:this.attackProtection,attributes:this.attributes,passkey_settings:this.passkeySettings,password_settings:this.passwordSettings,sign_in:this.signIn,sign_up:this.signUp,social:this.social}}}class sd extends iu{id;web3Wallet="";verification;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}create(){return this._basePost({body:{web3_wallet:this.web3Wallet}})}prepareVerification=e=>this._basePost({action:"prepare_verification",coalesce:!0,body:{...e}});attemptVerification=e=>{let{signature:t}=e;return this._basePost({action:"attempt_verification",body:{signature:t}})};destroy(){return this._baseDelete()}toString(){return this.web3Wallet}fromJSON(e){return e&&(this.id=e.id,this.web3Wallet=e.web3_wallet,this.verification=new rX(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}class sh extends iu{pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=tE(e.updated_at),this.createdAt=tE(e.created_at),rp.emit("resource:update",{resource:this})),this}async join(e){return nq(this,async()=>{await sh.join(e)})}static async join(e){return new sh(await iu._fetch({path:"/waitlist",method:"POST",body:e}))}}function su(e,t){var i,r;return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||(i=t,r=e,i.organizationMemberships.length!==r.organizationMemberships.length||i.organizationMemberships[0]?.updatedAt!==r.organizationMemberships[0]?.updatedAt)}function sp(e,t){return!function(e,t){if(!e&&t||e&&!t)return!0;if(!e&&e===t)return!1;if(!e||!t)return!0;try{if(rz.isClientResource(e))return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.sessions.length!==t.sessions.length;if(nz.isSessionResource(e)){var i,r;return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.lastActiveToken?.jwt?.claims?.__raw!==t.lastActiveToken?.jwt?.claims?.__raw||function(e,t){if(e.lastActiveOrganizationId!==t.lastActiveOrganizationId)return!0;let i=e.user?.organizationMemberships?.find(t=>t.organization.id===e.lastActiveOrganizationId),r=t.user?.organizationMemberships?.find(t=>t.organization.id===e.lastActiveOrganizationId);return i?.permissions?.length!==r?.permissions?.length}(e,t)||(i=e,r=t,!!i.user!=!!r.user||!!i.user&&!!r.user&&su(i.user,r.user))}if(ss.isUserResource(e))return su(e,t)}catch{}return!0}(e,t)?e:t}let s_="__clerk_db_jwt";function sf(e,t){let i=new URL(e),r=i.searchParams.get(s_);i.searchParams.delete(s_);let n=r||t;return n&&i.searchParams.set(s_,n),i}let sm=e=>{let t=new URL(e);return t.searchParams.delete(s_),t},sg=e=>{let t=new URL(e);return t.searchParams.delete("__dev_session"),t.hash=decodeURI(t.hash).replace(/__clerk_db_jwt\[(.*)\]/,""),t.href.endsWith("#")&&(t.hash=""),t};function sy(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)"__proto__"!==r&&(e[r]=i[r])}return e}var sw=function e(t,i){function r(e,r,n){if("u">typeof document){"number"==typeof(n=sy({},i,n)).expires&&(n.expires=new Date(Date.now()+864e5*n.expires)),n.expires&&(n.expires=n.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var s="";for(var a in n)n[a]&&(s+="; "+a,!0!==n[a]&&(s+="="+n[a].split(";")[0]));return document.cookie=e+"="+t.write(r,e)+s}}return Object.create({set:r,get:function(e){if("u">typeof document&&(!arguments.length||e)){for(var i=document.cookie?document.cookie.split("; "):[],r={},n=0;n<i.length;n++){var s=i[n].split("="),a=s.slice(1).join("=");try{var o=decodeURIComponent(s[0]);if(o in r||(r[o]=t.read(a,o)),e===o)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",sy({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,sy({},this.attributes,t))},withConverter:function(t){return e(sy({},this.converter,t),this.attributes)}},{attributes:{value:Object.freeze(i)},converter:{value:Object.freeze(t)}})}({read:function(e){return'"'===e[0]&&(e=e.slice(1,-1)),e.replace(/(%[\dA-F]{2})+/gi,decodeURIComponent)},write:function(e){return encodeURIComponent(e).replace(/%(2[346BF]|3[AC-F]|40|5[BDE]|60|7[BCD])/g,decodeURIComponent)}},{path:"/"});function sb(e){return{get:()=>sw.get(e),set(t,i={}){sw.set(e,t,i)},remove(t){sw.remove(e,t)}}}let sv=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function sk(e,t){let i=function(e){try{return new Date(e||new Date)}catch{return new Date}}(e);return i.setFullYear(i.getFullYear()+t),i}let sS=sb("__clerk_test_etld"),sI=[".lovable.app",".lovableproject.com",".webcontainer-api.io",".vusercontent.net",".v0.dev",".v0.app",".lp.dev",".replit.dev"];function sC(){try{return sI.some(e=>window.location.hostname.endsWith(e))}catch{return!1}}let sU="__client_uat",sA="__session",sP=e=>{let t=e.usePartitionedCookies(),i=t||tG()||sC()?"None":"Lax",r=sv(i);return{sameSite:i,secure:r,partitioned:t&&r}};async function sT(e){let t;try{t=await eA(e)}catch(o){var r;r=`Suffixed cookie failed due to ${o.message} (secure-context: ${window.isSecureContext}, url: ${window.location.href})`,ex.has(r)||(console.log(r),ex.add(r));let{default:n}=await Promise.all([i.e(545),i.e(811)]).then(i.t.bind(i,3515,23)),{default:s}=await Promise.all([i.e(545),i.e(811)]).then(i.t.bind(i,5662,23)),a=n(e);t=s.stringify(a).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}return t}let sO=e=>{let t=e.usePartitionedCookies(),i=t||tG()||sC()?"None":"Lax",r=sv(i);return{sameSite:i,secure:r,partitioned:t&&r}},sE={sameSite:"None",secure:!0,partitioned:!0};class sx{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,t,i,r){let n=await sT(e.publishableKey),s=new sx(e,t,n,i,r);return await s.setup(),s}constructor(e,t,i,r,n){this.clerk=e,this.instanceType=r,this.clerkEventBus=n,rp.on(rc,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),rp.on(rd,()=>this.handleSignOut()),rp.on(rh,()=>{this.devBrowser.refreshCookies(),this.refreshSessionToken({updateCookieImmediately:!0}),this.setClientUatCookieForDevelopmentInstances()}),this.refreshTokenOnFocus(),this.startPollingForToken();const a={usePartitionedCookies:()=>na.getInstance().partitionedCookies};this.clientUat=((e,t)=>{let i=sb(sU),r=sb(eP(sU,e));return{set:e=>{let n=sk(Date.now(),1),a=t.usePartitionedCookies(),o=a||tG()||sC()?"None":"Strict",l=sv(o),c=a&&l,d=function(e=window.location.hostname,t=sS,i){if(s)return s;if(["localhost","127.0.0.1","0.0.0.0"].includes(e))return e;let r=e.split(".");if(1===r.length)return e;for(let e=r.length-2;e>=0;e--){let n=r.slice(e).join(".");if(t.set("1",{...i,domain:n}),"1"===t.get())return t.remove({...i,domain:n}),s=n,n;t.remove({...i,domain:n})}return s=e,e}(void 0,void 0,{sameSite:o,secure:l}),h="0";if(e&&e.updatedAt&&e.signedInSessions.length>0&&(h=Math.floor(e.updatedAt.getTime()/1e3).toString()),r.remove(),i.remove(),c)for(let e of[{domain:d,sameSite:"Strict",secure:sv("Strict"),partitioned:!1},{domain:d,sameSite:"None",secure:sv("None"),partitioned:!1}])r.remove(e),i.remove(e);r.set(h,{domain:d,expires:n,partitioned:c,sameSite:o,secure:l}),i.set(h,{domain:d,expires:n,partitioned:c,sameSite:o,secure:l})},get:()=>parseInt(r.get()||i.get()||"0",10)}})(i,a),this.sessionCookie=((e,t)=>{let i=sb(sA),r=sb(eP(sA,e)),n=()=>{for(let e of[{sameSite:"Lax",secure:sv("Lax"),partitioned:!1},{sameSite:"None",secure:sv("None"),partitioned:!1}])i.remove(e),r.remove(e)};return{set:e=>{let s=sk(Date.now(),1),{sameSite:a,secure:o,partitioned:l}=sP(t);l&&n(),i.set(e,{expires:s,sameSite:a,secure:o,partitioned:l}),r.set(e,{expires:s,sameSite:a,secure:o,partitioned:l})},remove:()=>{let e=sP(t);i.remove(e),r.remove(e),e.partitioned&&n()},get:()=>r.get()||i.get()}})(i,a),this.activeCookie=(()=>{let e=sb("clerk_active_context"),t={secure:sv("None")};return{set:i=>{e.set(i,t)},get:()=>e.get(),remove:()=>e.remove(t)}})(),this.devBrowser=function({cookieSuffix:e,frontendApi:t,fapiClient:i,cookieOptions:r}){let n,s,a,o,l=(s=sb(s_),a=sb(eP(s_,e)),o=()=>{let e=sO(r);for(let t of[a,s])t.remove(e),t.remove(),t.remove(sE)},{get:()=>a.get()||s.get(),set:e=>{let t=sk(Date.now(),1),{sameSite:i,secure:n,partitioned:l}=sO(r);o(),a.set(e,{expires:t,sameSite:i,secure:n,partitioned:l}),s.set(e,{expires:t,sameSite:i,secure:n,partitioned:l})},remove:()=>o()});function c(){return n||l.get()}function d(e){n=e,l.set(e)}function h(){n=void 0,l.remove()}return{clear:function(){h()},setup:async function e(){var e;let r,s;if(!eD(t))return;i.onBeforeRequest(e=>{let t=c();t&&e?.url&&(e.url=sf(e.url,t))}),i.onAfterResponse((e,t)=>{let i=t?.headers?.get("Clerk-Db-Jwt");i&&d(i)});let a=(r=(e=new URL(window.location.href)).searchParams.get("__clerk_db_jwt")||"",(s=sm(sg(e))).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",s),r);if(a)return void d(a);let o=l.get();if(o){n=o;return}let h=i.buildUrl({path:"/dev_browser"}),u=await fetch(h.toString(),{method:"POST"});if(!u.ok){let e=function(e=[]){return e.length>0?e.map(e=>new W(e)):[]}((await u.json()).errors);e[0]?t4(e[0].longMessage):t4()}let p=await u.json();d(p?.id)},getDevBrowser:c,setDevBrowser:d,removeDevBrowser:h,refreshCookies:function(){let e=c();e&&d(e)}}}({frontendApi:e.frontendApi,fapiClient:t,cookieSuffix:i,cookieOptions:a})}async setup(){return"production"===this.instanceType?this.setupProduction():this.setupDevelopment()}isSignedOut(){return this.clerk.loaded?!this.clerk.user:0>=this.clientUat.get()}async handleUnauthenticatedDevBrowser(){this.devBrowser.clear(),await this.devBrowser.setup()}decorateUrlWithDevBrowserToken(e){let t=this.devBrowser.getDevBrowser();if(!t)throw Error(`${t2} Missing dev browser. Please contact support.`);return sf(e,t)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new rS,this.poller.startPollingForSessionToken(()=>this.refreshSessionToken()))}stopPollingForToken(){this.poller&&(this.poller.stopPollingForSessionToken(),this.poller=null)}refreshTokenOnFocus(){let e=()=>{"visible"===document.visibilityState&&this.refreshSessionToken({updateCookieImmediately:!0})};window.addEventListener("focus",e),"u">typeof document&&document.addEventListener("visibilitychange",e)}async refreshSessionToken({updateCookieImmediately:e=!1}={}){if(this.clerk.session)try{let t=await this.clerk.session.getToken();e&&this.updateSessionCookie(t)}catch(e){return this.handleGetTokenError(e)}}updateSessionCookie(e){if((document.hasFocus()||this.inVisibleCrossOriginIframe()||this.isCurrentContextActive())&&!(e&&this.#Q(e)))return e||k()||tS.warn("Removing session cookie (offline)",{sessionId:this.clerk.session?.id},"authCookieService"),this.setActiveContextInStorage(),e?this.sessionCookie.set(e):this.sessionCookie.remove()}#Q(e){let t=this.#X(e);if(!t||null==rA(t))return!1;let i=this.#X(this.sessionCookie.get());if(!i||null==rA(i))return!1;let r=i.jwt?.claims?.exp;return!("number"!=typeof r||r<=Math.floor(Date.now()/1e3))&&rP(i)===rP(t)&&(rT(i)||"")===(rT(t)||"")&&rU(i,t)===i}#X(e){if(!e)return null;try{let t=new n8({id:"__session",jwt:e,object:"token"});return t.jwt?t:null}catch{return null}}setClientUatCookieForDevelopmentInstances(){this.clerk.client&&"production"!==this.instanceType&&this.inCustomDevelopmentDomain()&&this.clientUat.set(this.clerk.client)}inCustomDevelopmentDomain(){let e=this.clerk.frontendApi.replace("clerk.","");return!window.location.host.endsWith(e)}handleGetTokenError(e){if($(e)||M(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(X(e))return void this.clerk.handleUnauthenticated().catch(tm.lQ);this.clerkEventBus.emit(A,"degraded")}}handleSignOut(){this.activeCookie.remove(),this.sessionCookie.remove(),this.setClientUatCookieForDevelopmentInstances()}setActiveContextInStorage(){let e=this.clerk.session?.id||"",t=this.clerk.organization?.id||"",i=`${e}:${t}`;":"!==i?this.activeCookie.set(i):this.activeCookie.remove()}inVisibleCrossOriginIframe(){return tG()&&"visible"===document.visibilityState}isCurrentContextActive(){let e=this.activeCookie.get();if(!e)return!0;let[t,i]=e.split(":"),r=this.clerk.session?.id||"",n=this.clerk.organization?.id||"";return t===r&&i===n}getSessionCookie(){return this.sessionCookie.get()}}class sR{clerk;captchaChallenge;timers;constructor(e,t=new id(e),i=ry()){this.clerk=e,this.captchaChallenge=t,this.timers=i}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 sM=["/client","/waitlist"],sz=["/client/sign_ins","/client/sign_ups"];function sF(e){let t;try{t=new n8({jwt:e||"",object:"token",id:void 0})}catch{t=null}if(rz.clearInstance(),!t?.jwt)return rz.getOrCreateInstance({object:"client",last_active_session_id:null,id:"client_init",sessions:[]});let{sessionId:i,userId:r,orgId:n,orgRole:s,orgPermissions:a,orgSlug:o,factorVerificationAge:l}=(e=>{let t,i,r,n,s=e.fva??null,a=e.sts??null;if(2===e.v){if(e.o){t=e.o?.id,r=e.o?.slg,e.o?.rol&&(i=`org:${e.o?.rol}`);let{org:s}=nx(e.fea),{permissions:a,featurePermissionMap:o}=(({per:e,fpm:t})=>{if(!e||!t)return{permissions:[],featurePermissionMap:[]};let i=e.split(",").map(e=>e.trim());return{permissions:i,featurePermissionMap:t.split(",").map(e=>((e,t)=>{if(!/^\d+$/.test(e))return;let i=e.replace(/^0+/,"")||"0",r=[];for(;"0"!==i;){let e="",t=0;for(let r=0;r<i.length;r++){let n=10*t+i.charCodeAt(r)-48,s=Math.floor(n/2);(e||0!==s)&&(e+=s),t=n%2}r.push(t),i=e||"0"}for(0===r.length&&r.push(0);r.length<t;)r.push(0);return r})(e.trim(),i.length)??[])}})({per:e.o?.per,fpm:e.o?.fpm});n=function({features:e,permissions:t,featurePermissionMap:i}){if(!e||!t||!i)return[];let r=[];for(let n=0;n<e.length;n++){let s=e[n];if(n>=i.length)continue;let a=i[n];if(a)for(let e=0;e<a.length&&e<t.length;e++)1===a[e]&&r.push(`org:${s}:${t[e]}`)}return r}({features:s,featurePermissionMap:o,permissions:a})}}else t=e.org_id,i=e.org_role,r=e.org_slug,n=e.org_permissions;return{sessionClaims:e,sessionId:e.sid,sessionStatus:a,actor:e.act,userId:e.sub,orgId:t,orgRole:i,orgSlug:r,orgPermissions:n,factorVerificationAge:s}})(t.jwt.claims),c={object:"client",last_active_session_id:i,id:"client_init",sessions:[{object:"session",id:i,status:"active",last_active_organization_id:n||null,last_active_token:{id:void 0,object:"token",jwt:e},factor_verification_age:l||null,public_user_data:{user_id:r},user:{object:"user",id:r,updated_at:1,organization_memberships:n&&o&&s?[{object:"organization_membership",id:n,role:s,permissions:a||[],organization:{object:"organization",id:n,name:o,slug:o,members_count:1,max_allowed_memberships:1}}]:[]}}]};return rz.getOrCreateInstance(c)}class sN{static #L="/api_keys";async #Y(){let e=await iu.clerk.session?.getToken();if(!e)throw new R("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 iu._fetch({...await this.#Y(),method:"GET",path:sN.#L,search:iN({...e,subject:e?.subject??iu.clerk.organization?.id??iu.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new ip(e))}})}async create(e){return new ip(await iu._fetch({...await this.#Y(),path:sN.#L,method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??iu.clerk.organization?.id??iu.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new ip(await iu._fetch({...await this.#Y(),method:"POST",path:`${sN.#L}/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let sD=new Map;class sW{async getConsentInfo(e){let{oauthClientId:t,scope:i,redirectUri:r}=e,n={...void 0!==i&&{scope:i},...void 0!==r&&{redirect_uri:r}},s=await iu._fetch({method:"GET",path:`/me/oauth/consent/${encodeURIComponent(t)}`,search:Object.keys(n).length>0?n:void 0},{skipUpdateClient:!0});if(!s)throw new R("Network request failed while offline",{code:"network_error"});let a=s.response??s;return{oauthApplicationName:a.oauth_application_name,oauthApplicationLogoUrl:a.oauth_application_logo_url,oauthApplicationUrl:a.oauth_application_url,clientId:a.client_id,state:a.state,redirectDomain:a.redirect_domain,scopes:a.scopes?.map(e=>({scope:e.scope,description:e.description,requiresConsent:e.requires_consent}))??[]}}async lookupDeviceVerification(e){let t=await iu._fetch({method:"POST",path:"/me/oauth/device/lookup",body:{userCode:e.userCode}},{skipUpdateClient:!0});if(!t)throw new R("Network request failed while offline",{code:"network_error"});let i=t.response??t;return{oauthApplicationName:i.oauth_application_name,oauthApplicationLogoUrl:i.oauth_application_logo_url,clientId:i.client_id,scopes:i.scopes?.map(e=>({scope:e.scope,description:e.description,requiresConsent:e.requires_consent}))??[],status:i.status,expiresAt:i.expires_at}}async submitDeviceVerification(e){let t=await iu._fetch({method:"POST",path:"/me/oauth/device",body:{userCode:e.userCode,approved:e.approved,organizationId:e.organizationId}},{skipUpdateClient:!0});if(!t)throw new R("Network request failed while offline",{code:"network_error"});let i=t.response??t;return{object:i.object,status:i.status}}buildConsentActionUrl({clientId:e}){let t=iu.fapiClient.buildUrl({path:`/me/oauth/consent/${encodeURIComponent(e)}`,sessionId:iu.clerk.session?.id});return iu.clerk.buildUrlWithAuth(t.toString())}}let sL="__clerk_protect_pid",s$=/^v\d+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/,sj="abcdefghijklmnopqrstuvwxyz234567",sB=/^[a-z2-7]{26}$/,sJ=/\{(cid|pid|rid|sdkver)\}/g,sK=/\{(?:cid|pid|rid|sdkver)\}/,sV=/\{(?:cid|pid|rid)\}/,sq=/\{cid\}/;function sH(e,t){return e.replace(sJ,(e,i)=>t[i]??e)}function sG(){let e="u">typeof crypto?crypto:void 0;if("function"!=typeof e?.getRandomValues)return null;try{return function(e){let t="",i=0,r=0;for(let n=0;n<e.length;n++)for(i=i<<8|e[n],r+=8;r>=5;)t+=sj[i>>>r-5&31],r-=5;return r>0&&(t+=sj[i<<5-r&31]),t}(e.getRandomValues(new Uint8Array(16)))}catch{return null}}let sQ=new Map;function sX(){try{return globalThis.localStorage??null}catch{return null}}function sY(e){try{let t=sX()?.getItem(e);if("string"==typeof t)return t}catch{}return sQ.get(e)??null}function sZ(e,t){try{let i=sX();if(i){i.setItem(e,t),sQ.delete(e);return}}catch{}sQ.set(e,t)}function s0(e,t,i){let r,n=sY(e);if(!n)return null;try{r=JSON.parse(n)}catch{return null}if(!r||"object"!=typeof r)return null;let{token:s,exp:a,rid:o,at:l,floor:c}=r;if("string"!=typeof o||!sB.test(o)||!function(e){if("number"!=typeof e||!Number.isFinite(e))return!1;let t=Date.now()-e;return t>=0&&t<864e5}(l)||s1(c)<i)return null;let d=s3(s,a,t);return d?{...d,rid:o,at:l,floor:s1(c)}:null}function s1(e){return"number"==typeof e&&Number.isFinite(e)&&e>0?e:0}function s3(e,t,i){if("string"!=typeof e||e.length>4096||!s$.test(e)||"number"!=typeof t||!Number.isFinite(t))return null;let r=1e3*t;return r-i<=Date.now()||r>Date.now()+864e5?null:{token:e,exp:t}}function s2(e,t,i){sZ(e,JSON.stringify({...t,at:Date.now(),floor:i}))}let s4=Symbol("deadline");async function s5(e,t,i){let r=globalThis.__clerk_specter;if(!r||"object"!=typeof r)return"no_token";let{cid:n,ready:s}=r;if(n!==e||!(s&&("object"==typeof s||"function"==typeof s)&&"function"==typeof s.then))return"no_token";let a=await new Promise(e=>{let t=setTimeout(()=>e(s4),Math.max(0,i-Date.now())),r=i=>{clearTimeout(t),e(i)};s.then(r,()=>r(null))});if(a===s4)return"timeout";if(!a||"object"!=typeof a)return"no_token";let{token:o,exp:l}=a,c=s3(o,l,0);return c?{...c,rid:t}:"no_token"}function s6(e){return e>=100&&e<=599?`http_${e}`:"fetch_error"}function s8(e){let t=[];for(let i of("string"==typeof e.token_url&&t.push(e.token_url),"string"==typeof e.text_content&&t.push(e.text_content),Object.values(e.attributes??{})))"string"==typeof i&&t.push(i);return t}function s9(e){return s8(e).some(e=>sK.test(e))}function s7(e){return s8(e).some(e=>sV.test(e))}function ae(e){return s8(e).some(e=>sq.test(e))}class at{#Z;#ee;#et;#ei;#er;#en;#es;#ea;#eo=0;#el;#ec;#ed;#eh=!1;#eu=0;#ep=0;static create(e,t,i){let r=e.filter(s9);if(0!==r.length)return new at(r,t,i)}constructor(e,t,i){this.#ea=t,this.#eo=s1(i);const r=e.some(s7);this.#Z=r?function(){let e=sY(sL);if(e&&sB.test(e))return e;let t=sG();return t&&sZ(sL,t),t}():null,this.#ee=this.#Z?sG():null,this.#et=this.#Z&&this.#ee?function(e,t){return`1-${e}-${t}`}(this.#Z,this.#ee):null,this.#ei={...this.#et?{cid:this.#et}:{},...this.#Z?{pid:this.#Z}:{},...this.#ee?{rid:this.#ee}:{},sdkver:"6.42.0"};const n=e.find(ae);this.#er=n,this.#en=n?function(e,t){if("string"!=typeof e.token_url||!e.token_url)return;let i="u">typeof document?document.baseURI:void 0;try{return new URL(sH(e.token_url,t),i).href}catch{return}}(n,this.#ei):void 0,this.#es=function(e){return"number"!=typeof e||!Number.isFinite(e)||e<=0?5e3:Math.min(e,1e4)}(n?.token_timeout_ms),this.#el="__clerk_protect_st",this.#ec=rk("clerk.lock.protectSessionToken")}placeholders(){return this.#ei}isTokenLoader(e){return this.#er===e}start(){this.#er&&!this.#ed&&this.#e_()}async getRequestParams(){var e,t,i,r;if(!this.#er)return;if(!this.#et||!this.#Z)return{__clerk_protect_status:"unsupported"};this.#ef();let n=this.#ed?await (e=this.#ed,t=this.#es,new Promise(i=>{let r=setTimeout(()=>i("timeout"),t),n=e=>{clearTimeout(r),i(e)};e.then(n,()=>n("timeout"))})):"timeout",s=s0(this.#el,5e3,this.#eo);return s?{__clerk_protect_token:s.token,__clerk_protect_status:"ok",__clerk_protect_cid:(i=this.#Z,r=s.rid,`1-${i}-${r}`)}:{__clerk_protect_status:"ok"===n?"timeout":n,__clerk_protect_cid:this.#et}}hasFreshToken(){return!!this.#er&&null!==this.#em()}#em(){return s0(this.#el,6e4,this.#eo)}#ef(){this.#ed&&(!this.#eh||s0(this.#el,5e3,this.#eo)||Date.now()-this.#eu<this.#eg())||this.#e_()}#eg(){return this.#ep<=1?3e4:Math.min(3e4*2**(this.#ep-1),9e5)}#e_(){this.#eu=Date.now(),this.#eh=!1;let e=e=>(this.#eh=!0,this.#ep=s0(this.#el,5e3,this.#eo)?0:this.#ep+1,e);this.#ed=this.#ey().then(e,()=>e("timeout"))}async #ey(){if(!this.#et)return"unsupported";if(this.#em())return"ok";let e=await this.#ec.acquireLockAndRun(async()=>this.#em()?"ok":await this.#ew());return"string"==typeof e?e:this.#em()?"ok":"timeout"}async #ew(){let e=Date.now()+this.#es,t=await this.#eb(e);if("error"===t)return"script_error";if("timeout"===t)return"timeout";if(this.#en)return await this.#ev(e);let i=await s5(this.#et,this.#ee,e);return"string"==typeof i?i:(s2(this.#el,i,this.#eo),"ok")}#eb(e){var t;let i,r=this.#er;if(!r)return Promise.resolve("error");try{i=this.#ea(r,this.#ei)}catch{return Promise.resolve("error")}return i?(t=i).getAttribute("src")||t.getAttribute("href")||"SCRIPT"===t.tagName&&t.getAttribute("type")?.toLowerCase()==="module"?new Promise(t=>{let r=setTimeout(()=>t("timeout"),Math.max(0,e-Date.now())),n=e=>()=>{clearTimeout(r),t(e)};i.addEventListener("load",n("loaded"),{once:!0}),i.addEventListener("error",n("error"),{once:!0})}):Promise.resolve("loaded"):Promise.resolve("error")}async #ev(e){let t=this.#en,i=new AbortController,r=setTimeout(()=>i.abort(),Math.max(0,e-Date.now()));try{for(;;){var n;let r;if(Date.now()>=e)return"timeout";try{r=await fetch(t,{credentials:"omit",signal:i.signal})}catch{return i.signal.aborted?"timeout":"fetch_error"}if(200===r.status){let e=await ai(r,this.#ee);if(!e)return"fetch_error";return s2(this.#el,e,this.#eo),"ok"}let s=202===r.status;if(!s&&(n=r.status,408!==n&&429!==n&&!(n>=500)))return s6(r.status);let a=s?await ar(r):200;if(Date.now()+a>=e)return s?"timeout":s6(r.status);await function(e,t){return new Promise(i=>{let r=setTimeout(i,e);t.addEventListener("abort",()=>{clearTimeout(r),i()},{once:!0})})}(a,i.signal)}}finally{clearTimeout(r)}}}async function ai(e,t){let i;try{i=await e.json()}catch{return null}if(!i||"object"!=typeof i)return null;let{token:r,exp:n}=i,s=s3(r,n,0);return s?{...s,rid:t}:null}async function ar(e){try{let t=await e.json(),i=t?.retry_in_ms;if("number"==typeof i&&Number.isFinite(i))return Math.min(Math.max(i,50),1e3)}catch{}return 100}class an{#M=!1;#ek;#eS;get challengeLoadTimeoutMs(){return this.#eS}load(e){let t=e?.protectConfig;if(t?.loaders&&Array.isArray(t.loaders)&&0!==t.loaders.length&&!this.#M){if(m()){this.#M=!0;try{this.#eI(t.loaders,t.tokens_invalid_before)}catch(e){eR(`[protect] failed to load: ${e}`)}}}}#eI(e,t){let i=e.filter(e=>{var t;return(!!(t=e)&&"object"==typeof t||(eR(`[protect] loader entry is not an object: ${t}`),!1))&&function(e){if(void 0===e.rollout)return!0;let t=e.rollout;return"number"!=typeof t||t<0?(eR(`[protect] loader rollout value is invalid: ${t}`),!1):0!==t&&Math.random()<=t}(e)});this.#eS=i.find(e=>"number"==typeof e.challenge_load_timeout_ms&&Number.isFinite(e.challenge_load_timeout_ms)&&e.challenge_load_timeout_ms>0)?.challenge_load_timeout_ms;let r=(e,t)=>this.applyLoader(e,t);for(let e of(this.#ek=at.create(i,r,t),i))if(!this.#ek?.isTokenLoader(e))try{this.applyLoader(e,this.#ek?.placeholders())}catch(e){eR(`[protect] failed to apply loader: ${e}`)}this.#ek?.start()}getRequestParams(){try{return(this.#ek?.getRequestParams()??Promise.resolve(void 0)).catch(()=>void 0)}catch{return Promise.resolve(void 0)}}applyLoader(e,t){let i=e.type||"script",r=e.target||"body",n=document.createElement(i);if(e.attributes)for(let[i,r]of Object.entries(e.attributes))switch(typeof r){case"string":n.setAttribute(i,t?sH(r,t):r);break;case"number":case"boolean":n.setAttribute(i,String(r));break;default:eR(`[protect] loader attribute is invalid type: ${i}=${r}`)}switch(e.text_content&&"string"==typeof e.text_content&&(n.textContent=t?sH(e.text_content,t):e.text_content),r){case"head":return document.head.appendChild(n),n;case"body":return document.body.appendChild(n),n;default:if(r?.startsWith("#")){let e=document.getElementById(r.substring(1));if(!e)return void eR(`[protect] loader target element not found: ${r}`);return e.appendChild(n),n}eR(`[protect] loader target is invalid: ${r}`);return}}}async function as(e){if(void 0===e)return;let t=e;if("function"==typeof e)try{t=await e()}catch(e){eR(`Clerk: protectAssertion resolver failed, continuing without it: ${e}`);return}if(void 0!==t)return"string"!=typeof t||""===t.trim()?void eR("Clerk: protectAssertion must be a non-empty string; ignoring it."):t}async function aa(e){let t=await as(e);return t?{__clerk_protect_assertion:t}:void 0}class ao{signInResourceSignal=iW;signInErrorSignal=iL;signInFetchSignal=i$;signInSignal=ij;signUpResourceSignal=iB;signUpErrorSignal=iJ;signUpFetchSignal=iK;signUpSignal=iV;waitlistResourceSignal=iq;waitlistErrorSignal=iH;waitlistFetchSignal=iG;waitlistSignal=iQ;_waitlistInstance;__internal_effect=iO;__internal_computed=iT;constructor(){rp.on("resource:update",this.onResourceUpdated),rp.on("resource:error",this.onResourceError),rp.on("resource:fetch",this.onResourceFetch),this._waitlistInstance=new sh(null),this.waitlistResourceSignal({resource:this._waitlistInstance})}get __internal_waitlist(){return this._waitlistInstance}onResourceError=e=>{e.resource instanceof nY&&this.signInErrorSignal({error:e.error}),e.resource instanceof n1&&this.signUpErrorSignal({error:e.error}),e.resource instanceof sh&&this.waitlistErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof nY){if(al(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof n1){if(al(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}e.resource instanceof sh&&(this._waitlistInstance=e.resource,this.waitlistResourceSignal({resource:e.resource}))};onResourceFetch=e=>{e.resource instanceof nY&&this.signInFetchSignal({status:e.status}),e.resource instanceof n1&&this.signUpFetchSignal({status:e.status}),e.resource instanceof sh&&this.waitlistFetchSignal({status:e.status})}}function al(e,t){return!t?.id&&e&&e.__internal_future?.canBeDiscarded===!1}let ac="cannot_render_billing_disabled",ad="cannot_render_user_missing",ah="cannot_render_organizations_disabled",au="cannot_render_organization_missing",ap="cannot_render_single_session_enabled",a_="cannot_render_self_serve_sso_disabled",af={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 am{static version="6.42.0";static sdkMetadata={name:"@clerk/clerk-js",version:"6.42.0"};static _billing;static _apiKeys;static _oauthApplication;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new ao;internal_last_error=null;environment;#eC;#eU="";#eA;#eP;#eT;#eO;#eE;#ex=null;#eR;#eM;#ez;#eF="loading";#eN=[];#eD=[];#eW={};#eL;#e$=!1;#ej=null;#eB=null;#eJ=0;#eK=U();#eV=new tT;get __internal_moduleManager(){return this.#eV}get __internal_queryClient(){return this.#eC||Promise.all([i.e(662),i.e(10)]).then(i.bind(i,1753)).then(e=>e.QueryClient).then(e=>{this.#eC||(this.#eC=new e,this.#eK.emit("queryClientStatus","ready"))}),this.#eC?{__tag:"clerk-rq-client",client:this.#eC}:void 0}get __internal_hasOAuthTransport(){return null!==this.#ej}get __internal_oauthTransport(){return this.#ej}get __internal_protectChallengeLoadTimeoutMs(){return this.#eO?.challengeLoadTimeoutMs}__internal_getCachedResources;__internal_createPublicCredentials;__internal_getPublicCredentials;__internal_isWebAuthnSupported;__internal_isWebAuthnAutofillSupported;__internal_isWebAuthnPlatformAuthenticatorSupported;__internal_setActiveInProgress=!1;get publishableKey(){return this.#eU}get version(){return am.version}get uiVersion(){let e="u">typeof window?window.__internal_ClerkUICtor:void 0,t=this.#eW.ui?.ClerkUI;return e?.version??(t instanceof Promise?void 0:t?.version)}set sdkMetadata(e){am.sdkMetadata=e}get sdkMetadata(){return am.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#eF}get isSatellite(){return!!tH()&&(0,tm.VK)(this.#eW.isSatellite,new URL(window.location.href),!1)}get domain(){if(tH()){let e=eO((0,tm.VK)(this.#eA,new URL(window.location.href)));if("production"===this.#ez){let t;if(!e)return"";if(e.match(/^(clerk\.)+\w*$/))t=/(clerk\.)*(?=clerk\.)/;else{if(e.match(/\.clerk.accounts/))return e;t=/^(clerk\.)*/gi}return`clerk.${e.replace(t,"")}`}return e}return"function"==typeof this.#eA?(eR(e5.domainAsFunctionNotSupported),""):eO(this.#eA||"")}get proxyUrl(){if(tH()){var e;let t=(0,tm.VK)(this.#eP,new URL(window.location.href));!t||e7(t)||te(t)||tJ.throwInvalidProxyUrl({url:t});let i=t?!te(t)||"u"<typeof window||!window.location?.origin?t:new URL(t,window.location.origin).toString():"";if(i)return i;if(!this.#eA&&"production"===this.#ez&&(e=window.location.hostname,tt.some(t=>e?.endsWith(t))))return`${window.location.origin}/__clerk`}return"function"==typeof this.#eP?(eR(e5.proxyUrlAsFunctionNotSupported),""):this.#eP||""}get frontendApi(){let e=eC(this.publishableKey);return e?e.frontendApi:tJ.throwInvalidPublishableKeyError({key:this.publishableKey})}get instanceType(){return this.#ez}get isStandardBrowser(){return this.#eW.standardBrowser||!1}get billing(){return am._billing||(am._billing=new iD),am._billing}get apiKeys(){return am._apiKeys||(am._apiKeys=new sN),am._apiKeys}get oauthApplication(){return am._oauthApplication||(am._oauthApplication=new sW),am._oauthApplication}__experimental_checkout(e){return this._checkout||(this._checkout=e=>(function(e,t){let i,r,n,s,{for:a,planId:o,planPeriod:l,seatsQuantity:c,priceId:d}=t;if(null===e.user)throw Error("Clerk: User is not authenticated");if("organization"===a&&null===e.organization)throw Error("Clerk: The current session does not have an active organization. Use `setActive` to set the organization");let h=function(e){let{userId:t,orgId:i,planId:r,planPeriod:n,seatsQuantity:s,priceId:a}=e;return`${t}-${i||"user"}-${r}-${n}-${s}-${a}`}({userId:e.user?.id||"",orgId:"organization"===a?e.organization?.id:void 0,planId:o,planPeriod:l,seatsQuantity:c,priceId:d}),u=sD.get(h);if(u)return u.signals.computedSignal();let p=(i=iP({resource:null}),r=iP({error:null}),n=iP({status:"idle"}),s=iT(()=>{let e=i().resource,t=r().error,s=n().status;return{errors:iX(t,{}),fetchStatus:s,checkout:e}}),{resourceSignal:i,errorSignal:r,fetchSignal:n,computedSignal:s}),_=new i0(p,{..."organization"===a?{orgId:e.organization?.id}:{},planId:o,planPeriod:l,seatsQuantity:c,priceId:d});return sD.set(h,{resource:_,signals:p}),p.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#eW[e]}setProtectAssertion=e=>{this.#eL=e,this.#e$=!0};#eq(){return this.#e$?this.#eL:this.#eW.protectAssertion}async #eH(){let[e,t]=await Promise.all([aa(this.#eq()).catch(()=>void 0),this.#eO?.getRequestParams().catch(()=>void 0)]);if(e||t)return{...e,...t}}get isSignedIn(){return this?.session?.status!=="pending"&&!!this.session}constructor(e,t){if(!(e=(e||"").trim()))return tJ.throwMissingPublishableKeyError();const i=eC(e);if(!i)return tJ.throwInvalidPublishableKeyError({key:e});this.#eA=t?.domain,this.#eP=t?.proxyUrl,this.environment=na.getInstance(),this.#ez=i.instanceType,this.#eU=e,this.#eM=function(e){let t=[],i=[];async function r(e){for await(let i of["u">typeof window&&window.__internal_onBeforeRequest,...t].filter(e=>e))if(await i(e)===!1)return!1;return!0}async function n(e,t){for await(let r of["u">typeof window&&window.__internal_onAfterResponse,...i].filter(e=>e))if(await r(e,t)===!1)return!1;return!0}function s({method:t,path:i,sessionId:r,search:n,rotatingTokenNonce:a}){let o=new URLSearchParams(n);return o.append("__clerk_api_version","2026-08-20"),o.append("_clerk_js_version","6.42.0"),a&&o.append("rotating_token_nonce",a),e.domain&&"development"===e.instanceType&&e.isSatellite&&o.append("__domain",e.domain),t&&"GET"!==t&&"POST"!==t&&o.append("_method",t),i&&!sM.some(e=>i.startsWith(e))&&r&&o.append("_clerk_session_id",r),ez([...o.entries()].reduce((e,[t,i])=>(e[t]=i.includes(",")?i.split(","):i,e),{}))}function a(t){let{path:i,pathPrefix:r="v1"}=t;if(e.proxyUrl){let n=new URL(e.proxyUrl),a=n.pathname.slice(1);return a.endsWith("/")&&(a=a.slice(0,-1)),e$({base:n.origin,pathname:`${a}/${r}${i}`,search:s(t)},{stringify:!1})}let n="production"===e.instanceType?e.domain:"";return e$({base:`https://${n||e.frontendApi}`,pathname:`${r}${i}`,search:s(t)},{stringify:!1})}async function o(t,i){let s,o={...t},{method:l="GET"}=o,{body:c}=o;if(e.getProtectParams&&(_=o.path,"GET"!==l&&_&&sz.some(e=>_===e||_.startsWith(`${e}/`)))&&function(e){if(void 0===e)return!0;if("object"!=typeof e||null===e)return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||null===t}(c)){let t=await e.getProtectParams().catch(()=>void 0);t&&(o.body=c={...c??{},...t})}!c||"object"!=typeof c||c instanceof FormData||(o.body=function(e){if(!e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype)return e;let t={};for(let[i,r]of Object.entries(e))void 0!==r&&(t[i]=r);return t}(c)),o.url=a({...o,sessionId:e.getSessionId()}),o.headers=new Headers(o.headers),"GET"===l||c instanceof FormData||o.headers.has("content-type")||o.headers.set("content-type","application/x-www-form-urlencoded"),"application/x-www-form-urlencoded"===o.headers.get("content-type")&&(o.body=c?ez(c,{keyEncoder:eu}):c);let d=await r(o),h="GET"===l?"GET":"POST",u=o.url,p={...o,method:h,credentials:o.credentials||"include"};try{if(d){let e=i?.fetchMaxTries??(v()?4:11);s=await tA(()=>fetch(u,p),{retryImmediately:!0,initialDelay:700,maxDelayBetweenRetries:5e3,shouldRetry:(t,i)=>"GET"===h&&i<e&&!p.signal?.aborted,onBeforeRetry:e=>{u.searchParams.set("_clerk_retry_attempt",e.toString())}})}else s=new Response("{}",o)}catch(t){var _;let e=u.toString();throw tS.error("network error",{error:t,url:e,method:l},"fapiClient"),Error(`${t2} Network error at "${e}" - ${t}. Please try again.`)}let f=204===s.status?null:await s.json().catch(e=>{if(!(s.status>=500))throw e}),m=Object.assign(s,{payload:f??null});return s.ok||tS.error("request failed",{method:l,path:o.path,status:s.status},"fapiClient"),void 0!==f&&await n(o,m),m}return{buildEmailAddress:function(t){return function({localPart:e,frontendApi:t}){return`${e}@${t?t.replace("clerk.",""):"clerk.com"}`}({localPart:t,frontendApi:e.frontendApi})},buildUrl:a,onAfterResponse:function(e){i.push(e)},onBeforeRequest:function(e){t.push(e)},request:o}}({domain:this.domain,frontendApi:this.frontendApi,instanceType:this.instanceType,isSatellite:this.isSatellite,getSessionId:()=>this.session?.id,getProtectParams:()=>this.#eH(),proxyUrl:this.proxyUrl}),this.#eK.emit(A,"loading"),this.#eK.prioritizedOn(A,e=>this.#eF=e),this.#eK.on(A,e=>{tH()&&("ready"===e||"degraded"===e?window.__clerk_internal_ready?.__resolve&&this.#eG()&&window.__clerk_internal_ready.__resolve(this):"error"===e&&window.__clerk_internal_ready?.__reject&&window.__clerk_internal_ready.__reject(new R("Clerk failed to initialize.",{code:"clerk_init_failed"})))}),tH()&&("ready"===this.#eF||"degraded"===this.#eF)&&this.#eG()&&window.__clerk_internal_ready?.__resolve&&window.__clerk_internal_ready.__resolve(this),iu.clerk=this,this.#eO=new an}getFapiClient=()=>this.#eM;load=async e=>{if(tS.info("load() start",{},"clerk"),!this.loaded){if("development"!==this.#ez||e?.unsafe_disableDevelopmentModeConsoleWarning||eR("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.#eW=this.#eQ(e),this.#ej=this.#eW.__internal_oauthTransport??null,this.#eW.ui?.ClerkUI&&(this.#eR=Promise.resolve(this.#eW.ui.ClerkUI).then(e=>new e(()=>this,()=>this.environment,this.#eW,this.#eV))),"development"===this.#ez&&(this.#eW.routerPush||this.#eW.routerReplace)&&(!this.#eW.routerPush||!this.#eW.routerReplace)){let e=this.#eW.routerPush?"routerReplace":"routerPush";eR(`Clerk: Both \`routerPush\` and \`routerReplace\` need to be defined, but \`${e}\` is not defined. This may cause issues with navigation in your application.`)}rp.on(ru,()=>{this.#eX(this.session)}),this.#eW.sdkMetadata&&(am.sdkMetadata=this.#eW.sdkMetadata),!1!==this.#eW.telemetry&&(this.telemetry=new tc({clerkVersion:am.version,samplingRate:1,perEventSampling:!this.#eW.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#eW.telemetry}),this.#eW.appearance&&this.telemetry.record({event:"THEME_USAGE",eventSamplingRate:1,payload:function(e){let t;if(!e||"object"!=typeof e)return{};let i=e.theme;if(!i)return{};if(Array.isArray(i))for(let e of i){let i=tf(e);if(i){t=i;break}}else t=tf(i);return{themeName:t}}(this.#eW.appearance)}));try{this.#eW.standardBrowser?await this.#eY():await this.#eZ();let e=this.#eW.telemetry,t=!1!==e&&!e?.disabled,i=!!this.#eW.__internal_keyless_claimKeylessApplicationUrl,r=!!this.environment?.clientDebugMode,n=this.environment?.isProduction?.()??!1,s=r||i&&!n,a=i&&!r?"error":void 0;s&&function(e={}){if(tw)return;let{enabled:t=!1,...i}=e;t&&(tg=!0,tw=!0,tk(i))}({enabled:!0,...a?{logLevel:a}:{},...t&&this.telemetry?{telemetryCollector:this.telemetry}:{}}),this.#eO?.load(this.environment),tS.info("load() complete",{},"clerk")}catch(e){throw this.#eK.emit(A,"error"),tS.error("load() failed",{error:e},"clerk"),e}}};#e0(){let e;return!!(!this.#eW.signUpUrl&&this.#eW.signInUrl&&(e=this.#eW.signInUrl,!eE.test(e)))}#e1(e){return tH()&&void 0!==window.location&&this.client?.isEligibleForTouch()?this.buildUrlWithAuth(this.client.buildTouchUrl({redirectUrl:new URL(e,window.location.href)})):e}signOut=async(e,t)=>{if(!this.client||0===this.client.sessions.length)return;let i="u">typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:tm.lQ,r="u">typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:tm.lQ,n=e&&"object"==typeof e?e:t||{},s=n?.redirectUrl||this.buildAfterSignOutUrl();tS.debug("signOut() start",{hasClient:!!this.client,multiSessionCount:this.client?.signedInSessions.length??0,redirectUrl:s,sessionTarget:n?.sessionId??null},"clerk");let a="function"==typeof e?e:void 0,o=async()=>{let e=tO(this.#eW.standardBrowser);rp.emit(rd,null),await e.track(async()=>{a?await a():await this.navigate(this.#e1(s))}),e.isUnloading()||(this.#eX(),await r())};if(await i(),!n.sessionId||1===this.client.signedInSessions.length){this.#e3();try{this.#eW.experimental?.persistClient??!0?await this.client.removeSessions():await this.client.destroy()}catch(e){if(!M(e)||"network_error"!==e.code)throw e}await o(),tS.info("signOut() complete",{redirectUrl:ej(s)},"clerk");return}let l=this.client.signedInSessions.find(e=>e.id===n.sessionId);l?.id&&this.session?.id===l.id?(this.#e3(),await l?.remove(),await o(),tS.info("signOut() complete",{redirectUrl:ej(s)},"clerk")):await l?.remove()};openGoogleOneTap=e=>{this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted()).then(t=>t.openModal("googleOneTap",e||{})),this.telemetry?.record(t_("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(Z(this,this.environment)){if("development"===this.#ez)throw new R(e5.cannotOpenSignInOrSignUp,{code:ap});return}this.assertComponentsReady(this.#eR);let t="SignIn";this.#eR.then(e=>e.ensureMounted({preloadHint:t})).then(t=>t.openModal("signIn",e||{}));let i={withSignUp:e?.withSignUp??this.#e0()};this.telemetry?.record(t_(t,e,i))};closeSignIn=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(ee(this,this.environment)){if("development"===this.#ez)throw new R(e5.cannotRenderAnyBillingComponent("Checkout"),{code:ac});return}if(!this.user){if("development"===this.#ez)throw new R(e5.cannotOpenCheckout,{code:ad});return}this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted()).then(t=>t.openDrawer("checkout",e||{}))};__internal_closeCheckout=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("checkout"))};__internal_openPlanDetails=e=>{if(ee(this,this.environment)){if("development"===this.#ez)throw new R(e5.cannotRenderAnyBillingComponent("PlanDetails"),{code:ac});return}this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted()).then(t=>t.openDrawer("planDetails",e||{})),this.telemetry?.record(t_("PlanDetails",e))};__internal_closePlanDetails=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("planDetails"))};__internal_openSubscriptionDetails=e=>{this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted()).then(t=>t.openDrawer("subscriptionDetails",e||{}))};__internal_closeSubscriptionDetails=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("subscriptionDetails"))};__internal_openReverification=e=>{if(!this.user){if("development"===this.#ez)throw new R(e5.cannotOpenUserProfile,{code:ad});return}this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted()).then(t=>t.openModal("userVerification",e||{})),this.telemetry?.record(t_("UserVerification",e))};__internal_closeReverification=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userVerification"))};__internal_attemptToEnableEnvironmentSetting=e=>{let{for:t,caller:i}=e;if(this.user||"development"!==this.#ez||eR(`Clerk: "${i}" requires an active user session. Ensure a user is signed in before executing ${i}.`),"organizations"===t){let t;return(t=this.environment,t?.organizationSettings.enabled||this.session?.currentTask?.key==="choose-organization")?{isEnabled:!0}:("development"===this.#ez&&this.__internal_openEnableOrganizationsPrompt({caller:i,onSuccess:()=>window.location.reload(),onClose:e.onClose}),{isEnabled:!1})}throw Error(`Attempted to enable an unknown or unsupported setting "${t}".`)};__internal_openEnableOrganizationsPrompt=e=>{this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted({preloadHint:"EnableOrganizationsPrompt"})).then(t=>t.openModal("enableOrganizationsPrompt",e||{})),this.telemetry?.record(tp("EnableOrganizationsPrompt",e))};__internal_closeEnableOrganizationsPrompt=()=>{this.assertComponentsReady(this.#eR),this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeModal("enableOrganizationsPrompt"))};__internal_resolvePendingProtectCheck=async e=>{let t=this.client;if(!t||"complete"===t.signIn.status||"complete"===t.signUp.status)return;let i=nQ.getInstance(),r=async e=>{try{await i.resolve(this,e)}catch(t){throw rp.emit("resource:error",{resource:e,error:t}),t}};"signUp"!==e&&await r(t.signIn),"signIn"!==e&&await r(t.signUp)};__internal_openProtectCheckModal=e=>this.#eR?this.#eR.then(e=>e.ensureMounted()).then(t=>{if(t.openProtectCheckModal)return new Promise((i,r)=>{t.openProtectCheckModal?.({...e,onResolved:()=>{t.closeModal("protectCheck"),i()},onFailed:e=>{t.closeModal("protectCheck"),r(e)}})})}):Promise.resolve();__internal_openBlankCaptchaModal=()=>(this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted()).then(e=>e.openModal("blankCaptcha",{})));__internal_closeBlankCaptchaModal=()=>(this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted()).then(e=>e.closeModal("blankCaptcha")));__internal_loadStripeJs=async()=>{let{loadStripe:e}=await i.e(279).then(i.bind(i,7544));return e};openSignUp=e=>{if(Z(this,this.environment)){if("development"===this.#ez)throw new R(e5.cannotOpenSignInOrSignUp,{code:ap});return}this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted({preloadHint:"SignUp"})).then(t=>t.openModal("signUp",e||{})),this.telemetry?.record(t_("SignUp",e))};closeSignUp=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signUp"))};openUserProfile=e=>{if(!this.user){if("development"===this.#ez)throw new R(e5.cannotOpenUserProfile,{code:ad});return}this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted({preloadHint:"UserProfile"})).then(t=>t.openModal("userProfile",e||{}));let t=(e?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(t_("UserProfile",e,t))};closeUserProfile=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userProfile"))};openOrganizationProfile=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new R(e5.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:ah})}});if(t){if(!this.organization){if("development"===this.#ez)throw new R(e5.createCannotRenderComponentWhenOrgDoesNotExist("OrganizationProfile"),{code:au});return}this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted({preloadHint:"OrganizationProfile"})).then(t=>t.openModal("organizationProfile",e||{})),this.telemetry?.record(t_("OrganizationProfile",e))}};closeOrganizationProfile=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeModal("organizationProfile"))};openInviteMembers=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"InviteMembers",onClose:()=>{throw new R(e5.cannotRenderAnyOrganizationComponent("InviteMembers"),{code:ah})}});if(t){if(!this.organization){if("development"===this.#ez)throw new R(e5.createCannotRenderComponentWhenOrgDoesNotExist("InviteMembers"),{code:au});return}if(!this.session?.checkAuthorization({permission:"org:sys_memberships:manage"})){if("development"===this.#ez)throw new R(e5.createCannotRenderComponentWhenPermissionIsMissing("InviteMembers","org:sys_memberships:manage"),{code:"cannot_render_permission_missing"});return}this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted()).then(t=>t.openModal("inviteMembers",e||{})),this.telemetry?.record(t_("InviteMembers",e))}};closeInviteMembers=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeModal("inviteMembers"))};openCreateOrganization=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new R(e5.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:ah})}});t&&(this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted({preloadHint:"CreateOrganization"})).then(t=>t.openModal("createOrganization",e||{})),this.telemetry?.record(t_("CreateOrganization",e)))};closeCreateOrganization=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeModal("createOrganization"))};openWaitlist=e=>{this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted({preloadHint:"Waitlist"})).then(t=>t.openModal("waitlist",e||{})),this.telemetry?.record(t_("Waitlist",e))};closeWaitlist=()=>{this.#eR?.then(e=>e.ensureMounted()).then(e=>e.closeModal("waitlist"))};mountSignIn=(e,t)=>{this.assertComponentsReady(this.#eR);let i="SignIn";this.#eR.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"signIn",node:e,props:t}));let r={withSignUp:t?.withSignUp??this.#e0()};this.telemetry?.record(tp(i,t,r))};unmountSignIn=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserAvatar=(e,t)=>{this.assertComponentsReady(this.#eR);let i="UserAvatar";this.#eR.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"userAvatar",node:e,props:t})),this.telemetry?.record(tp(i,t))};unmountUserAvatar=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountSignUp=(e,t)=>{this.assertComponentsReady(this.#eR);let i="SignUp";this.#eR.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"signUp",node:e,props:t})),this.telemetry?.record(tp(i,t))};unmountSignUp=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserProfile=(e,t)=>{if(!this.user){if("development"===this.#ez)throw new R(e5.cannotRenderComponentWhenUserDoesNotExist,{code:ad});return}this.assertComponentsReady(this.#eR);let i="UserProfile";this.#eR.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"userProfile",node:e,props:t}));let r=(t?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(tp(i,t,r))};unmountUserProfile=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOrganizationProfile=(e,t)=>{let{isEnabled:i}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new R(e5.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:ah})}});if(!i)return;let r=!!this.user;if(!this.organization&&r){if("development"===this.#ez)throw new R(e5.createCannotRenderComponentWhenOrgDoesNotExist("OrganizationProfile"),{code:au});return}this.assertComponentsReady(this.#eR);let n="OrganizationProfile";this.#eR.then(e=>e.ensureMounted({preloadHint:n})).then(i=>i.mountComponent({name:n,appearanceKey:"userProfile",node:e,props:t})),this.telemetry?.record(tp(n,t))};unmountOrganizationProfile=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountCreateOrganization=(e,t)=>{let{isEnabled:i}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new R(e5.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:ah})}});if(!i)return;this.assertComponentsReady(this.#eR);let r="CreateOrganization";this.#eR.then(e=>e.ensureMounted({preloadHint:r})).then(i=>i.mountComponent({name:r,appearanceKey:"createOrganization",node:e,props:t})),this.telemetry?.record(tp(r,t))};unmountCreateOrganization=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOrganizationSwitcher=(e,t)=>{let{isEnabled:i}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationSwitcher",onClose:()=>{throw new R(e5.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:ah})}});if(!i)return;this.assertComponentsReady(this.#eR);let r="OrganizationSwitcher";this.#eR.then(e=>e.ensureMounted({preloadHint:r})).then(i=>i.mountComponent({name:r,appearanceKey:"organizationSwitcher",node:e,props:t})),this.telemetry?.record(tp(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationSwitcher=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__experimental_prefetchOrganizationSwitcher=()=>{this.assertComponentsReady(this.#eR),this.#eR.then(e=>e.ensureMounted()).then(e=>e.prefetch("organizationSwitcher"))};mountOrganizationList=(e,t)=>{let{isEnabled:i}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationList",onClose:()=>{throw new R(e5.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:ah})}});if(!i)return;this.assertComponentsReady(this.#eR);let r="OrganizationList";this.#eR.then(e=>e.ensureMounted({preloadHint:r})).then(i=>i.mountComponent({name:r,appearanceKey:"organizationList",node:e,props:t})),this.telemetry?.record(tp(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationList=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserButton=(e,t)=>{this.assertComponentsReady(this.#eR);let i="UserButton";this.#eR.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"userButton",node:e,props:t}));let r={...t?.customMenuItems?.length||0?{customItems:!0}:void 0,...t?.__experimental_asStandalone?{standalone:!0}:void 0};this.telemetry?.record(tp(i,t,r))};unmountUserButton=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountWaitlist=(e,t)=>{this.assertComponentsReady(this.#eR);let i="Waitlist";this.#eR.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"waitlist",node:e,props:t})),this.telemetry?.record(tp(i,t))};unmountWaitlist=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountPricingTable=(e,t)=>{if(ee(this,this.environment)){if("development"===this.#ez)throw new R(e5.cannotRenderAnyBillingComponent("PricingTable"),{code:ac});return}this.assertComponentsReady(this.#eR);let i="PricingTable";this.#eR.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"pricingTable",node:e,props:t})),this.telemetry?.record(tp(i,t))};unmountPricingTable=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountOAuthConsent=(e,t)=>{if(null===this.user){if("development"===this.#ez)throw new R(e5.cannotRenderOAuthConsentComponentWhenUserDoesNotExist,{code:ad});return}this.assertComponentsReady(this.#eR);let i="OAuthConsent";this.#eR.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"__internal_oauthConsent",node:e,props:t}))};unmountOAuthConsent=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__internal_mountOAuthConsent=(e,t)=>this.mountOAuthConsent(e,t);__internal_unmountOAuthConsent=e=>this.unmountOAuthConsent(e);__internal_mountOAuthDeviceVerification=(e,t)=>{if(!this.user){if("development"===this.#ez)throw new R(e5.cannotRenderOAuthDeviceVerificationComponentWhenUserDoesNotExist,{code:ad});return}this.assertComponentsReady(this.#eR);let i="OAuthDeviceVerification";this.#eR.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"oauthDeviceVerification",node:e,props:t})),this.telemetry?.record(tp(i,t))};__internal_unmountOAuthDeviceVerification=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountAPIKeys=(e,t)=>{let i;if(et(this,i=this.environment)&&ei(this,i)){if("development"===this.#ez)throw new R(e5.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&ei(this,this.environment)){if("development"===this.#ez)throw new R(e5.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if(!this.organization&&et(this,this.environment)){if("development"===this.#ez)throw new R(e5.cannotRenderAPIKeysComponentForUserWhenDisabled,{code:"cannot_render_api_keys_user_disabled"});return}this.assertComponentsReady(this.#eR);let r="APIKeys";this.#eR.then(e=>e.ensureMounted({preloadHint:r})).then(i=>i.mountComponent({name:r,appearanceKey:"apiKeys",node:e,props:t})),this.telemetry?.record(tp(r,t))};unmountAPIKeys=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__internal_mountConfigureSSO=(e,t)=>{let i,r,{isEnabled:n}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"ConfigureSSO",onClose:()=>{throw new R(e5.cannotRenderAnyOrganizationComponent("ConfigureSSO"),{code:ah})}});if(!n)return;let s=!!this.user;if(!this.organization&&s){if("development"===this.#ez)throw new R(e5.createCannotRenderComponentWhenOrgDoesNotExist("ConfigureSSO"),{code:au});return}if(i=this.environment,!i?.userSettings.enterpriseSSO.self_serve_sso||!this.organization?.selfServeSSOEnabled){if("development"===this.#ez)throw new R(e5.cannotRenderConfigureSSOComponentWhenDisabled,{code:a_});return}if(r=this.environment,!r?.userSettings.attributes.email_address?.enabled){if("development"===this.#ez)throw new R(e5.cannotRenderConfigureSSOComponentWhenEmailAddressDisabled,{code:"cannot_render_configure_sso_email_address_disabled"});return}this.assertComponentsReady(this.#eR);let a="ConfigureSSO";this.#eR.then(e=>e.ensureMounted({preloadHint:a})).then(i=>i.mountComponent({name:a,appearanceKey:"configureSSO",node:e,props:t})),this.telemetry?.record(tp(a,t))};__internal_unmountConfigureSSO=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__internal_mountConfigureDirectorySync=(e,t)=>{let i,{isEnabled:r}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"ConfigureDirectorySync",onClose:()=>{throw new R(e5.cannotRenderAnyOrganizationComponent("ConfigureDirectorySync"),{code:ah})}});if(!r)return;let n=!!this.user;if(!this.organization&&n){if("development"===this.#ez)throw new R(e5.createCannotRenderComponentWhenOrgDoesNotExist("ConfigureDirectorySync"),{code:au});return}if(i=this.environment,!i?.userSettings.enterpriseSSO.self_serve_sso||!i?.userSettings.enterpriseSSO.self_serve_directory_sync||!this.organization?.selfServeDirectorySyncEnabled){if("development"===this.#ez)throw new R(e5.cannotRenderConfigureDirectorySyncComponentWhenDisabled,{code:a_});return}this.assertComponentsReady(this.#eR);let s="ConfigureDirectorySync";this.#eR.then(e=>e.ensureMounted({preloadHint:s})).then(i=>i.mountComponent({name:s,appearanceKey:"configureDirectorySync",node:e,props:t})),this.telemetry?.record(tp(s,t))};__internal_unmountConfigureDirectorySync=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskChooseOrganization=(e,t)=>{let{isEnabled:i}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"TaskChooseOrganization",onClose:()=>{throw new R(e5.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:ah})}});if(!i)return;this.assertComponentsReady(this.#eR);let r="TaskChooseOrganization";this.#eR.then(e=>e.ensureMounted({preloadHint:r})).then(i=>i.mountComponent({name:r,appearanceKey:"taskChooseOrganization",node:e,props:t})),this.telemetry?.record(tp(r,t))};unmountTaskChooseOrganization=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskResetPassword=(e,t)=>{this.assertComponentsReady(this.#eR);let i="TaskResetPassword";this.#eR.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"taskResetPassword",node:e,props:t})),this.telemetry?.record(tp("TaskResetPassword",t))};unmountTaskResetPassword=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskSetupMFA=(e,t)=>{this.assertComponentsReady(this.#eR);let i="TaskSetupMFA";this.#eR.then(e=>e.ensureMounted({preloadHint:i})).then(r=>r.mountComponent({name:i,appearanceKey:"taskSetupMfa",node:e,props:t})),this.telemetry?.record(tp("TaskSetupMFA",t))};unmountTaskSetupMFA=e=>{this.#eR?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};setActive=async e=>{let{organization:t,redirectUrl:i,navigate:r}=e,{session:n}=e;this.__internal_setActiveInProgress=!0,tS.debug("setActive() start",{hasClient:!!this.client,sessionTarget:"string"==typeof n?n:n?.id??n??null,organizationTarget:"string"==typeof t?t:t?.id??t??null,redirectUrl:i??null},"clerk");try{var s;let a;if(!this.client)throw tS.warn("Clerk setActive called before client is loaded",{},"clerk"),Error("setActive is being called before the client is loaded. Wait for init.");if(void 0===n&&!this.session)throw tS.warn("Clerk setActive precondition not met: no target session and no active session",{},"clerk"),Error("setActive should either be called with a session param or there should be already an active session.");"string"==typeof n&&(n=this.client.sessions.find(e=>e.id===n)||null);let o="u">typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:tm.lQ,l="u">typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:tm.lQ,c=void 0===n?this.session:n;c?.status==="pending"&&(s={...this.#eW,...e},a=["taskUrls","navigate"],Object.keys(s).some(e=>a.includes(e))||eR('Clerk: Session has pending tasks but no handling is configured. To handle pending tasks, provide either "taskUrls" for navigation to custom URLs or "navigate" for programmatic navigation. Without these options, users may get stuck on incomplete flows.'));let d=void 0!==t;if(c&&d){let e="string"==typeof t?t:t?.id;if("string"==typeof e&&e.startsWith("org_"))c.lastActiveOrganizationId=e||null;else{let t=c.user.organizationMemberships.find(t=>t.organization.slug===e),i=t?.organization.id||null,r=null===i;if(this.environment?.organizationSettings?.forceOrganizationSelection&&r)return;c.lastActiveOrganizationId=i}}c?.status!=="pending"&&await o(null===c?"sign-out":void 0);let h=c?.status==="pending"&&c?.currentTask&&this.#eW.taskUrls?.[c?.currentTask.key],u=!!(i||h||r),p=d?"select_org":"select_session";if(tH()&&globalThis.document.hasFocus()||!this.#eW.standardBrowser){let e;if(u&&c)try{(e=await c.__internal_touch({intent:p}))&&this.updateClient(e,{__internal_dangerouslySkipEmit:!0})}catch(e){if(X(e))this.handleUnauthenticated();else throw e}else await this.#e2(c,p);c=this.#e4(c?.id,e)}try{await c?.getToken()||rp.emit(rc,{token:null})}catch(e){if(B.is(e))tS.warn("Token fetch failed when setting active session (offline). Preserving existing auth state.",{sessionId:c?.id},"clerk");else throw e}let _=tO(this.#eW.standardBrowser);if(u&&await _.track(async()=>{if(this.client)if(c?.status!=="pending"&&this.#e3(),h){let e=i?e$({base:h,hashSearchParams:{redirectUrl:i}},{stringify:!0}):h;await this.navigate(e)}else if(r&&c){let e=!1,t=t=>(e=!0,this.#e1(t));await r({session:c,decorateUrl:t}),"development"===this.#ez&&!e&&this.client.isEligibleForTouch()&&eR("Clerk: The navigate callback in setActive() did not call decorateUrl(). In Safari, sessions may be limited to 7 days due to Intelligent Tracking Prevention (ITP). Use decorateUrl() to wrap your destination URL to enable the ITP workaround. Learn more: https://clerk.com/docs/troubleshooting/safari-itp")}else i&&await this.navigate(this.#e1(i))}),_.isUnloading())return;this.#eX(c),c?.status!=="pending"&&await l()}finally{this.__internal_setActiveInProgress=!1}};addListener=(e,t)=>{var i;let r;return i=e,e=e=>{var t;r||={...e},i(r={...{client:sp((t=r).client,e.client),session:sp(t.session,e.session),user:sp(t.user,e.user),organization:sp(t.organization,e.organization)}})},this.#eN.push(e),this.client&&!t?.skipInitialEmit&&e({client:this.client,session:this.session,user:this.user,organization:this.organization}),()=>{this.#eN=this.#eN.filter(t=>t!==e)}};on=(...e)=>{this.#eK.on(...e)};off=(...e)=>{this.#eK.off(...e)};__internal_addNavigationListener=e=>(this.#eD.push(e),()=>{this.#eD=this.#eD.filter(t=>t!==e)});navigate=async(e,t)=>{if(!e||!tH())return;if(void 0===window.location){let i=t?.replace&&this.#eW.routerReplace?this.#eW.routerReplace:this.#eW.routerPush;return i?(tS.info(`Clerk is navigating to: ${e}`),await i(e,{windowNavigate:this.__internal_windowNavigate})):void 0}setTimeout(()=>{this.#e5()},0);let i=new URL(e,window.location.href);this.#e6.includes(i.protocol)||(console.warn(`Clerk: "${i.protocol}" is not a valid protocol. Redirecting to "/" instead. If you think this is a mistake, please open an issue.`),i=new URL("/",window.location.href));let r=t?.replace&&this.#eW.routerReplace?this.#eW.routerReplace:this.#eW.routerPush;if(tS.info(`Clerk is navigating to: ${i}`),this.#eW.routerDebug&&console.log(`Clerk is navigating to: ${i}`),"null"!==i.origin&&i.origin!==window.location.origin||!r)return void this.__internal_windowNavigate(i);let n={...t?.metadata?{__internal_metadata:t?.metadata}:{},windowNavigate:this.__internal_windowNavigate};return await r(ej(i),n)};buildUrlWithAuth(e){if("production"===this.#ez)return e;let t=new URL(e,window.location.origin);return t.origin!==window.location.origin&&this.#eT?this.#eT.decorateUrlWithDevBrowserToken(t).href:t.href}buildSignInUrl(e){let t=e?.redirectUrl||window.location.href;this.isSatellite&&(t=this.#e8(t));let i=this.isSatellite?this.#e9(e):e;return this.#e7("signInUrl",{...i,redirectUrl:t},e?.initialValues)}buildSignUpUrl(e){let t=e?.redirectUrl||window.location.href;this.isSatellite&&(t=this.#e8(t));let i=this.isSatellite?this.#e9(e):e;return this.#e7("signUpUrl",{...i,redirectUrl:t},e?.initialValues)}#e8=e=>{try{let t=new URL(e,window.location.origin);return t.searchParams.set(er,en),t.toString()}catch{return e}};#e9=e=>{if(!e)return e;let t={...e};return t.signInForceRedirectUrl&&(t.signInForceRedirectUrl=this.#e8(t.signInForceRedirectUrl)),t.signInFallbackRedirectUrl&&(t.signInFallbackRedirectUrl=this.#e8(t.signInFallbackRedirectUrl)),t.signUpForceRedirectUrl&&(t.signUpForceRedirectUrl=this.#e8(t.signUpForceRedirectUrl)),t.signUpFallbackRedirectUrl&&(t.signUpFallbackRedirectUrl=this.#e8(t.signUpFallbackRedirectUrl)),t};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 eH(this.#eW,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eH(this.#eW,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#eW.afterSignOutUrl?this.buildUrlWithAuth(this.#eW.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#eW.newSubscriptionRedirectUrl?this.#eW.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?e$({base:this.#eW.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#eW.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#eW.afterMultiSessionSingleSignOutUrl):this.#eW.signInUrl?this.buildUrlWithAuth(e$({base:this.#eW.signInUrl,hashPath:"choose"},{stringify:!0})):this.buildUrlWithAuth(this.environment.displayConfig.afterSignOutOneUrl):""}buildCreateOrganizationUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.createOrganizationUrl):""}buildOrganizationProfileUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.organizationProfileUrl):""}buildTasksUrl(e){let t=this.session?.currentTask;if(!t)return"";let i=this.#eW.taskUrls?.[t.key];return i||e$({base:this.buildSignInUrl(e),hashPath:e1(t)},{stringify:!0})}#te=async()=>{if(!tH())return;let e=new URLSearchParams({[er]:es}),t=eX(eo);t&&e7(t)||function(){throw Error(`${t2} Invalid redirect_url. A valid http or https url should be used for the redirection.`)}();let i=e$({base:eX(eo),searchParams:e},{stringify:!0});return this.navigate(this.buildUrlWithAuth(i))};redirectWithAuth=async e=>{if(tH())return this.navigate(this.buildUrlWithAuth(e))};redirectToSignIn=async e=>{if(tH())return this.navigate(this.buildSignInUrl(e))};redirectToSignUp=async e=>{if(tH())return this.navigate(this.buildSignUpUrl(e))};redirectToUserProfile=async()=>{if(tH())return this.navigate(this.buildUserProfileUrl())};redirectToCreateOrganization=async()=>{if(tH())return this.navigate(this.buildCreateOrganizationUrl())};redirectToOrganizationProfile=async()=>{if(tH())return this.navigate(this.buildOrganizationProfileUrl())};redirectToAfterSignIn=async()=>{if(tH())return this.navigate(this.buildAfterSignInUrl())};redirectToAfterSignUp=async()=>{if(tH())return this.navigate(this.buildAfterSignUpUrl())};redirectToAfterSignOut=async()=>{if(tH())return this.navigate(this.buildAfterSignOutUrl())};redirectToWaitlist=async()=>{if(tH())return this.navigate(this.buildWaitlistUrl())};redirectToTasks=async e=>{if(tH())return this.navigate(this.buildTasksUrl(e))};handleEmailLinkVerification=async(e,t)=>{if(!this.client)return;let i=eX("__clerk_status");if("expired"===i)throw new V("expired");if("client_mismatch"===i)throw new V("client_mismatch");if("transferable"===i){"function"==typeof e.onVerifiedOnOtherDevice&&e.onVerifiedOnOtherDevice();return}if("verified"!==i)throw new V("failed");let r=eX("__clerk_created_session"),{signIn:n,signUp:s,sessions:a}=this.client,o=a.some(e=>e.id===r),l="needs_second_factor"===n.status||"missing_requirements"===s.status,c=e=>t&&"function"==typeof t?t(e):this.navigate(e),d=e.redirectUrl?()=>c(e.redirectUrl):tm.lQ;return o?this.setActive({session:r,redirectUrl:e.redirectUrlComplete}):l?d():("function"==typeof e.onVerifiedOnOtherDevice&&e.onVerifiedOnOtherDevice(),null)};__internal_handleResourceCallback=async(e,t,i)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:r,signUp:n}=this.client,s="identifier"in(e||{})?e:r,a="missingFields"in(e||{})?e:n,o=e=>i&&"function"==typeof i?i(this.buildUrlWithAuth(e)):t.__internal_navigate&&"function"==typeof t.__internal_navigate?t.__internal_navigate(e):this.navigate(this.buildUrlWithAuth(e));return this._handleRedirectCallback(t,{signUp:a,signIn:s,navigate:o})};handleGoogleOneTapCallback=async(e,t,i)=>this.__internal_handleResourceCallback(e,t,i);_handleRedirectCallback=async(e,{signIn:t,signUp:i,navigate:r,resuming:n=!1})=>{if(!this.loaded||!this.environment||!this.client)return;if(!window.opener&&e.reloadResource)try{"signIn"===e.reloadResource?await t.reload():"signUp"===e.reloadResource&&await i.reload()}catch{}let{displayConfig:s}=this.environment,{firstFactorVerification:a}=t,{externalAccount:o}=i.verifications,l={status:i.status,missingFields:i.missingFields,externalAccountStatus:o.status,externalAccountErrorCode:o.error?.code,externalAccountSessionId:o.error?.meta?.sessionId,sessionId:i.createdSessionId,protectCheck:i.protectCheck},c={status:t.status,firstFactorVerificationStatus:a.status,firstFactorVerificationErrorCode:a.error?.code,firstFactorVerificationSessionId:a.error?.meta?.sessionId,sessionId:t.createdSessionId,protectCheck:t.protectCheck},d=e=>()=>r(e),h=d(e.signInUrl||s.signInUrl),u=d(e.signUpUrl||s.signUpUrl),p=d(e.firstFactorUrl||e$({base:s.signInUrl,hashPath:"/factor-one"},{stringify:!0})),_=d(e.secondFactorUrl||e$({base:s.signInUrl,hashPath:"/factor-two"},{stringify:!0})),f=d(e.resetPasswordUrl||e$({base:s.signInUrl,hashPath:"/reset-password"},{stringify:!0})),m=d(e.signInProtectCheckUrl||e$({base:s.signInUrl,hashPath:"/protect-check"},{stringify:!0})),g=new eH(this.#eW,e),y=e.continueSignUpUrl||e$({base:s.signUpUrl,hashPath:"/continue"},{stringify:!0}),w=e.verifyEmailAddressUrl||e$({base:s.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),b=e.verifyPhoneNumberUrl||e$({base:s.signUpUrl,hashPath:"/verify-phone-number"},{stringify:!0}),v=e.signUpProtectCheckUrl||e$({base:s.signUpUrl,hashPath:"/protect-check"},{stringify:!0}),k=e.signInUrl||s.signInUrl,S=e.signUpUrl||s.signUpUrl,I=e.enterpriseConnectionsUrl||e$({base:S,hashPath:"/enterprise-connections"},{stringify:!0}),C=d(v),U=e.__internal_navigateOnSetActive,A=async({session:e,baseUrl:t,redirectUrl:i})=>{U?await U({session:e,redirectUrl:i,decorateUrl:e=>this.buildUrlWithAuth(e)}):e.currentTask?await e3(e,{baseUrl:t,navigate:this.navigate}):await this.navigate(i)};if("complete"===c.status)return this.setActive({session:c.sessionId,navigate:async({session:e})=>{await A({session:e,baseUrl:k,redirectUrl:g.getAfterSignInUrl()})}});if(!n&&"signUp"!==e.reloadResource&&(c.protectCheck||"needs_protect_check"===c.status))return m();if(!n&&"signIn"!==e.reloadResource&&l.protectCheck)return C();if("transferable"===l.externalAccountStatus&&l.externalAccountErrorCode===el){let e=await t.create({transfer:!0});if(e.protectCheck||"needs_protect_check"===e.status)return m();switch(e.status){case"complete":return this.setActive({session:e.createdSessionId,navigate:async({session:e})=>{await A({session:e,baseUrl:S,redirectUrl:g.getAfterSignInUrl()})}});case"needs_first_factor":return p();case"needs_second_factor":return _();case"needs_new_password":return f();default:t5("sign in")}}let P="user_locked"===l.externalAccountErrorCode,T="user_locked"===c.firstFactorVerificationErrorCode;if(P)return u();if(T)return h();if("needs_first_factor"===c.status&&!t.supportedFirstFactors?.every(e=>"enterprise_sso"===e.strategy))return p();if("needs_new_password"===c.status)return f();if("transferable"===c.firstFactorVerificationStatus||"transfer_to_sign_up"===e.continuation){if(!1===e.transferable)return h();let t=await i.create({transfer:!0,unsafeMetadata:e.unsafeMetadata});switch(t.status){case"complete":return this.setActive({session:t.createdSessionId,navigate:async({session:e})=>{await A({session:e,baseUrl:S,redirectUrl:g.getAfterSignUpUrl()})}});case"missing_requirements":return tj({signUp:t,continueSignUpUrl:y,verifyEmailAddressUrl:w,verifyPhoneNumberUrl:b,signUpProtectCheckUrl:v,enterpriseConnectionsUrl:I,navigate:r});default:t5("sign in")}}if("complete"===l.status)return this.setActive({session:l.sessionId,navigate:async({session:e})=>{await A({session:e,baseUrl:S,redirectUrl:g.getAfterSignUpUrl()})}});if("needs_second_factor"===c.status)return _();let O=("failed"===l.externalAccountStatus||"unverified"===l.externalAccountStatus)&&"identifier_already_signed_in"===l.externalAccountErrorCode&&l.externalAccountSessionId,E="failed"===c.firstFactorVerificationStatus&&"identifier_already_signed_in"===c.firstFactorVerificationErrorCode&&c.firstFactorVerificationSessionId;if(O||E){let e=c.firstFactorVerificationSessionId||l.externalAccountSessionId;if(e)return this.setActive({session:e,navigate:async({session:e})=>{await A({session:e,baseUrl:O?S:k,redirectUrl:g.getAfterSignInUrl()})}})}return(e=>{let{externalAccount:t}=e.verifications;return!!t.error})(i)?u():"verified"===l.externalAccountStatus&&"missing_requirements"===l.status?tj({signUp:i,continueSignUpUrl:y,verifyEmailAddressUrl:w,verifyPhoneNumberUrl:b,signUpProtectCheckUrl:v,enterpriseConnectionsUrl:I,navigate:r}):this.session?.currentTask?void await this.redirectToTasks({redirectUrl:this.buildAfterSignInUrl()}):"signUp"!==e.reloadResource&&"needs_first_factor"===c.status&&(t.supportedFirstFactors??[]).filter(e=>"enterprise_sso"===e.strategy&&"enterpriseConnectionId"in e&&"enterpriseConnectionName"in e).length>1?p():h()};__internal_resumeAfterProtectCheck=async(e={},t)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:i,signUp:r}=this.client,n=t??e.__internal_navigate,s=e=>n&&"function"==typeof n?n(e):this.navigate(e);return this._handleRedirectCallback(e,{signUp:r,signIn:i,navigate:s,resuming:!0})};handleRedirectCallback=async(e={},t)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:i,signUp:r}=this.client,n=t??e.__internal_navigate,s=e=>n&&"function"==typeof n?n(e):this.navigate(e);return this._handleRedirectCallback(e,{signUp:r,signIn:i,navigate:s})};handleUnauthenticated=async(e={broadcast:!0})=>{if(this.client&&this.session)try{let t=await rz.getOrCreateInstance().fetch();if(this.updateClient(t),this.session)return;return e.broadcast&&rp.emit(rd,null),this.setActive({session:null})}catch(e){if($(e)&&[403,500].includes(e.status))return this.setActive({session:null});throw e}};__internal_handleUnauthenticatedDevBrowser=async()=>{this.#eT&&await this.#eT.handleUnauthenticatedDevBrowser()};authenticateWithGoogleOneTap=async e=>this.client?.signIn.create({strategy:"google_one_tap",token:e.token}).catch(t=>{if($(t)&&"external_account_not_found"===t.errors[0].code)return this.client?.signUp.create({strategy:"google_one_tap",token:e.token,legalAccepted:e.legalAccepted});throw t});authenticateWithMetamask=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_okx_wallet_signature"})};authenticateWithSolana=async e=>{await this.authenticateWithWeb3({...e,strategy:"web3_solana_signature"})};authenticateWithWeb3=async({redirectUrl:e,signUpContinueUrl:t,customNavigate:i,unsafeMetadata:r,strategy:n,legalAccepted:s,secondFactorUrl:a,protectCheckUrl:o,signUpProtectCheckUrl:l,walletName:c})=>{let d,h;if(!this.client||!this.environment)return;let{displayConfig:u}=this.environment,p=n.replace("web3_","").replace("_signature",""),_=await tY().getWeb3Identifier({provider:p,walletName:c});switch(p){case"metamask":d=tY().generateSignatureWithMetamask;break;case"base":d=tY().generateSignatureWithBase;break;case"coinbase_wallet":d=tY().generateSignatureWithCoinbaseWallet;break;case"solana":if(!c)throw new R("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});d=e=>tY().generateSignatureWithSolana({...e,walletName:c});break;default:d=tY().generateSignatureWithOKXWallet}let f=e=>()=>i&&"function"==typeof i?i(e):this.navigate(e),m=f(a||e$({base:u.signInUrl,hashPath:"/factor-two"},{stringify:!0})),g=f(o||e$({base:u.signInUrl,hashPath:"/protect-check"},{stringify:!0})),y=f(l||e$({base:u.signUpUrl,hashPath:"/protect-check"},{stringify:!0})),w=f(t||e$({base:u.signUpUrl,hashPath:"/continue"},{stringify:!0})),b=!1;try{h=await this.client.signIn.authenticateWithWeb3({identifier:_,generateSignature:d,strategy:n,walletName:c})}catch(e){if(tB(e,"form_identifier_not_found"))b=!0,h=await this.client.signUp.authenticateWithWeb3({identifier:_,generateSignature:d,unsafeMetadata:r,strategy:n,legalAccepted:s,walletName:c}),t&&"missing_requirements"===h.status&&"verified"===h.verifications.web3Wallet.status&&!h.protectCheck&&await w();else throw e}let v=async({session:e,redirectUrl:t})=>{e.currentTask?await e3(e,{baseUrl:u.signInUrl,navigate:this.navigate}):await this.navigate(t)};if(h.protectCheck||"needs_protect_check"===h.status)return void await (b?y:g)();switch(h.status){case"needs_second_factor":await m();break;case"complete":h.createdSessionId&&await this.setActive({session:h.createdSessionId,navigate:async({session:t})=>{await v({session:t,redirectUrl:e??this.buildAfterSignInUrl()})}});break;default:return}};createOrganization=async({name:e,slug:t})=>nf.create({name:e,slug:t});getOrganization=async e=>nf.get(e);joinWaitlist=async({emailAddress:e})=>sh.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,t)=>{if(!this.client){let t=this.#eW.selectInitialSession?this.#eW.selectInitialSession(e):this.#tt(e);this.#eX(t,{dangerouslySkipEmit:!0})}if(this.client=e,this.session){let t=this.#e4(this.session.id,e);"active"===this.session.status&&t?.status==="pending"&&("u">typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:tm.lQ)(),this.#eX(t,{dangerouslySkipEmit:!0}),this.session?.lastActiveToken||k()||tS.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),rp.emit(rc,{token:this.session?.lastActiveToken})}t?.__internal_dangerouslySkipEmit||this.#ti()};get __internal_environment(){return this.environment}__internal_setEnvironment=async e=>{this.environment=new na(e)};__internal_onBeforeRequest=e=>{this.#eM.onBeforeRequest(e)};__internal_onAfterResponse=e=>{this.#eM.onAfterResponse(e)};__internal_updateProps=e=>{let t={...e,options:this.#eQ({...this.#eW,...e.options})};return this.#eR?.then(e=>e.ensureMounted()).then(e=>e.updateProps(t))};__internal_navigateWithError(e,t){return this.__internal_last_error=t,this.navigate(e)}#tr=()=>{let e=new URLSearchParams({[eo]:window.location.href});return e$({base:this.#eW.signInUrl,searchParams:e},{stringify:!0})};#tn=()=>{let e;if(this.proxyUrl){let t=new URL(this.proxyUrl);e=new URL(`${t.pathname}/v1/client/sync`,t.origin)}else this.domain&&(e=new URL("/v1/client/sync",`https://${this.domain}`));return e?.searchParams.append("redirect_url",window.location.href),e?.toString()||""};#ts=()=>{let e=eX(er);return e!==es&&!!this.isSatellite&&(e===en||!0===this.#eW.satelliteAutoSync&&!!this.#eT?.isSignedOut())};#ta=()=>"production"!==this.#ez&&!this.isSatellite&&!!eX(eo);#to=async()=>{"development"===this.instanceType?await this.navigate(this.#tr()):"production"===this.instanceType&&await this.navigate(this.#tn())};#tl=(e,t)=>{let i;try{i=new URL(e)}catch{throw Error(`${t2} The signInUrl needs to have a absolute url format.`)}i.origin===t&&function(){throw Error(`${t2} The signInUrl needs to be on a different origin than your satellite application.`)}()};#tc=()=>{this.isSatellite&&("development"!==this.#ez||this.#eW.signInUrl||function(){throw Error(`${t2} Missing signInUrl. A satellite application needs to specify the signInUrl for development instances.`)}(),this.proxyUrl||this.domain||function(){throw Error(`${t2} Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl.`)}(),this.#eW.signInUrl&&this.#tl(this.#eW.signInUrl,window.location.origin))};#eY=async()=>{if(this.#eT=await sx.create(this,this.#eM,this.#ez,this.#eK),this.#tc(),this.#ts())return void await this.#to();if(this.#ta())return void await this.#te();this.#eB=(()=>{if(!m())return{onPageFocus:tm.lQ};let e=[];return window.addEventListener("focus",()=>{"visible"===document.visibilityState&&e.forEach(e=>e())}),{onPageFocus:t=>{e.push(t)}}})(),"u">typeof BroadcastChannel&&(this.#ex=new BroadcastChannel("clerk")),this.#td();let e=function(e=window.location.hostname){if(!e)return!1;let t=eW.get(e);void 0===t&&(t=ew.some(t=>e.startsWith("accounts.")&&e.endsWith(t))||eb.some(t=>e.endsWith(t)&&!e.endsWith(".clerk"+t)),eW.set(e,t));return t}(window?.location.hostname),t="development"===this.#ez&&!e,i=0,r=0;for(;r<2;){r++;try{let e=na.getInstance().fetch({touch:t}).then(e=>this.updateEnvironment(e)).catch(e=>{if(tB(e,"dev_browser_unauthenticated"))throw e;++i;let t=t3.getItem(tZ,null);t&&this.updateEnvironment(new na(t))}),r=async()=>{let e=new AbortController;return(0,tm.zc)(rz.getOrCreateInstance().fetch({abortSignal:e.signal}),7e3,e).then(e=>this.updateClient(e)).catch(async e=>{if(G(e))throw e;++i,this.#eT?.stopPollingForToken();try{let e=this.#tt(sF(this.#eT?.getSessionCookie()));e?.clearCache();let t=e?await (0,tm.zc)(e.getToken(),7e3).catch(()=>(e.clearCache(),this.#eT?.getSessionCookie())):this.#eT?.getSessionCookie();this.updateClient(sF(t))}finally{this.#eT?.startPollingForToken()}return rz.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(tm.lQ),null})},[n,s]=await (0,tm.vd)([e,r()]);if("rejected"===n.status)throw n.reason;if("rejected"===s.status){let e=s.reason;if(tB(e,"requires_captcha"))await r();else throw e}if(this.#eT?.setClientUatCookieForDevelopmentInstances(),await this.#th())return;break}catch(e){if(tB(e,"dev_browser_unauthenticated"))await this.#eT.handleUnauthenticatedDevBrowser();else if(!k())return void console.warn(e);else throw e}r>=2&&function(){throw Error(`${t2} Something went wrong initializing Clerk.`)}()}this.#eE=new sR(this),this.#eE.start(),this.#tu(),this.#tp(),this.#t_(),this.#eK.emit(A,i>0?"degraded":"ready")};shouldFallbackToCachedResources=()=>!!this.__internal_getCachedResources;#eZ=async()=>{let e,t,i=this.shouldFallbackToCachedResources()?1:void 0,r=0;try{[e,t]=await Promise.all([na.getInstance().fetch({touch:!1,fetchMaxTries:i}),rz.getOrCreateInstance().fetch({fetchMaxTries:i})])}catch(i){if((M(i)&&"network_error"===i.code||$(i)&&i.status>=500)&&this.shouldFallbackToCachedResources()){let i=await this.__internal_getCachedResources?.();e=new na(i?.environment),rz.clearInstance(),t=rz.getOrCreateInstance(i?.client),++r}else throw i}this.updateClient(t),this.updateEnvironment(e),this.#eK.emit(A,r>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,t]=await Promise.all([na.getInstance().fetch({touch:!1,fetchMaxTries:1}),rz.getOrCreateInstance().fetch({fetchMaxTries:1})]);this.updateClient(t),this.updateEnvironment(e),this.#ti()};#tt=e=>{if(e.lastActiveSessionId){let t=e.signedInSessions.find(t=>t.id===e.lastActiveSessionId);if(t)return t}return e.signedInSessions[0]||null};#td=()=>{m()&&(this.#eB?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#eJ>Date.now())&&(this.#eJ=Date.now()+5e3,this.#eW.touchSession&&this.#e2(this.session,"focus").catch(e=>{tS.warn("Session touch on page focus failed",{error:e},"clerk")}))}),this.#ex?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),rp.on(rd,()=>{this.#ex?.postMessage({type:"signout"})}),rp.on(rh,()=>{t3.setItem(tZ,this.environment?.__internal_toSnapshot(),864e5)}))};#e2=async(e,t="focus")=>{if(!e)return Promise.resolve();await e.touch({intent:t}).catch(e=>{if(X(e))this.handleUnauthenticated();else throw e})};__internal_lastEmittedResources;#ti=()=>{if(this.client){let e={client:this.client,session:this.session,user:this.user,organization:this.organization};for(let t of(this.__internal_lastEmittedResources=e,this.#eN))t(e)}};#e5=()=>{for(let e of this.#eD)e()};#e3=()=>{this.session=void 0,this.organization=void 0,this.user=void 0,this.#ti()};#tf=(e=this.session)=>(e?.user.organizationMemberships||[]).map(e=>e.organization).find(t=>t.id===e?.lastActiveOrganizationId)||null;#tm=(e=this.session)=>({session:e||null,organization:this.#tf(e),user:e?e.user:null});#eX=(e,t)=>{let{session:i,organization:r,user:n}=this.#tm(e);this.session=i,this.organization=r,this.user=n,t?.dangerouslySkipEmit||this.#ti()};#e4=(e,t=this.client)=>t?.signedInSessions.find(t=>t.id===e)||null;#tp=()=>{this.addListener(({session:e})=>{e?.actor&&this.#eR?.then(e=>e.ensureMounted()).then(e=>e.mountImpersonationFab())})};#t_=()=>{this.#eW.__internal_keyless_claimKeylessApplicationUrl&&this.#eR?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#eW.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#eW.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#eW.__internal_keyless_dismissPrompt}})})};#e7=(e,t,i)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let r=this.#eW[e]||this.environment.displayConfig[e];this.#e0()&&(r=this.#eW.signInUrl);let n=new eH(this.#eW,t).toSearchParams(),s=new URLSearchParams(i||{}),a=e$({base:r,hashPath:this.#e0()&&"signUpUrl"===e?"/create":"",hashSearchParams:[s,n]},{stringify:!0});return this.buildUrlWithAuth(a)};assertComponentsReady(e){if(!e)throw Error("Clerk was not loaded with Ui components")}#th=async()=>{var e;let t,i,r,n,s=new URLSearchParams(window.location.search).get("redirect_url"),a="production"===this.instanceType,o=null!==s&&(e=this.frontendApi,i=(t=new URL(s,eF)).pathname,r=eV.includes(i)||eq.includes(i),e===t.host&&r);if(a||!o)return!1;let l=this.session,c=this.#eW.signInUrl||this.environment?.displayConfig.signInUrl,d=c&&window.location.href.startsWith(c),h=this.#eW.signUpUrl||this.environment?.displayConfig.signUpUrl,u=h&&window.location.href.startsWith(h);return n=new URL(s,eF),(!eV.includes(n.pathname)||!!l||!d&&!u)&&(await this.navigate(this.buildUrlWithAuth(s)),!0)};#eQ=e=>{let t=e?.clerkUICtor??e?.clerkUiCtor,i=t?{...e?.ui,ClerkUI:t}:e?.ui;return{...af,...e,ui:i,allowedRedirectOrigins:function(e,t,i){if(Array.isArray(e)&&e.length)return e;let r=[];return"u">typeof window&&window.location&&r.push(window.location.origin),r.push(`https://${eL(t)}`),r.push(`https://*.${eL(t)}`),"development"===i&&r.push(`https://${t}`),r}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)}};#tu=()=>{try{eY(er),eY(eG),eY(ea),eY("__clerk_handshake"),eY("__clerk_handshake_nonce"),eY("__clerk_help")}catch{}};get #e6(){let e=e8;return this.#eW.allowedRedirectProtocols&&(e=e.concat(this.#eW.allowedRedirectProtocols)),e}__internal_windowNavigate=(e,t)=>{!function(e,t){if("string"==typeof e&&e9.test(function(e){let t=0;for(;t<e.length&&32>=e.charCodeAt(t);)t++;let i="";for(let r=t;r<e.length;r++){let t=e.charCodeAt(r);9!==t&&10!==t&&13!==t&&(i+=e[r])}return i}(e)))return console.warn(`Clerk: scheme-relative navigation to "${e}" is not allowed. Provide a same-origin path or an absolute URL.`);let i=new URL(e,window.location.href);(t?.allowedProtocols??e8).includes(i.protocol)?(window.dispatchEvent(new CustomEvent(e6)),window.location.href=i.href):console.warn(`Clerk: "${i.protocol}" is not a valid navigation protocol. Aborting navigation. If you think this is a mistake, please open an issue.`)}(e,{allowedProtocols:t?.useStaticAllowlistOnly?e8:this.#e6})};#eG(){return void 0!==this.client}}let ag=document.querySelector("script[data-clerk-publishable-key]")?.getAttribute("data-clerk-publishable-key")||window.__clerk_publishable_key||"",ay=document.querySelector("script[data-clerk-proxy-url]")?.getAttribute("data-clerk-proxy-url")||window.__clerk_proxy_url||"",aw=document.querySelector("script[data-clerk-domain]")?.getAttribute("data-clerk-domain")||window.__clerk_domain||"";window.Clerk||(window.Clerk=new am(ag,{proxyUrl:ay,domain:aw}))},8388(e,t,i){"use strict";var r=this&&this.__awaiter||function(e,t,i,r){return new(i||(i=Promise))(function(n,s){function a(e){try{l(r.next(e))}catch(e){s(e)}}function o(e){try{l(r.throw(e))}catch(e){s(e)}}function l(e){e.done?n(e.value):new i(function(t){t(e.value)}).then(a,o)}l((r=r.apply(e,t||[])).next())})},n=this&&this.__generator||function(e,t){var i,r,n,s,a={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return s={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function o(s){return function(o){var l=[s,o];if(i)throw TypeError("Generator is already executing.");for(;a;)try{if(i=1,r&&(n=2&l[0]?r.return:l[0]?r.throw||((n=r.return)&&n.call(r),0):r.next)&&!(n=n.call(r,l[1])).done)return n;switch(r=0,n&&(l=[2&l[0],n.value]),l[0]){case 0:case 1:n=l;break;case 4:return a.label++,{value:l[1],done:!1};case 5:a.label++,r=l[1],l=[0];continue;case 7:l=a.ops.pop(),a.trys.pop();continue;default:if(!(n=(n=a.trys).length>0&&n[n.length-1])&&(6===l[0]||2===l[0])){a=0;continue}if(3===l[0]&&(!n||l[1]>n[0]&&l[1]<n[3])){a.label=l[1];break}if(6===l[0]&&a.label<n[1]){a.label=n[1],n=l;break}if(n&&a.label<n[2]){a.label=n[2],a.ops.push(l);break}n[2]&&a.ops.pop(),a.trys.pop();continue}l=t.call(e,a)}catch(e){l=[6,e],r=0}finally{i=n=0}if(5&l[0])throw l[1];return{value:l[0]?l[1]:void 0,done:!0}}}},s=this;Object.defineProperty(t,"__esModule",{value:!0});var a=i(8058),o="browser-tabs-lock-key",l={key:function(e){return r(s,void 0,void 0,function(){return n(this,function(e){throw Error("Unsupported")})})},getItem:function(e){return r(s,void 0,void 0,function(){return n(this,function(e){throw Error("Unsupported")})})},clear:function(){return r(s,void 0,void 0,function(){return n(this,function(e){return[2,window.localStorage.clear()]})})},removeItem:function(e){return r(s,void 0,void 0,function(){return n(this,function(e){throw Error("Unsupported")})})},setItem:function(e,t){return r(s,void 0,void 0,function(){return n(this,function(e){throw Error("Unsupported")})})},keySync:function(e){return window.localStorage.key(e)},getItemSync:function(e){return window.localStorage.getItem(e)},clearSync:function(){return window.localStorage.clear()},removeItemSync:function(e){return window.localStorage.removeItem(e)},setItemSync:function(e,t){return window.localStorage.setItem(e,t)}};function c(e){return new Promise(function(t){return setTimeout(t,e)})}function d(e){for(var t="0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz",i="",r=0;r<e;r++){var n=Math.floor(Math.random()*t.length);i+=t[n]}return i}t.default=function(){function e(t){this.acquiredIatSet=new Set,this.storageHandler=void 0,this.id=Date.now().toString()+d(15),this.acquireLock=this.acquireLock.bind(this),this.releaseLock=this.releaseLock.bind(this),this.releaseLock__private__=this.releaseLock__private__.bind(this),this.waitForSomethingToChange=this.waitForSomethingToChange.bind(this),this.refreshLockWhileAcquired=this.refreshLockWhileAcquired.bind(this),this.storageHandler=t,void 0===e.waiters&&(e.waiters=[])}return e.prototype.acquireLock=function(t,i){return void 0===i&&(i=5e3),r(this,void 0,void 0,function(){var r,s,a,h,u,p,_;return n(this,function(n){switch(n.label){case 0:r=Date.now()+d(4),s=Date.now()+i,a=o+"-"+t,h=void 0===this.storageHandler?l:this.storageHandler,n.label=1;case 1:if(!(Date.now()<s))return[3,8];return[4,c(30)];case 2:if(n.sent(),null!==h.getItemSync(a))return[3,5];return u=this.id+"-"+t+"-"+r,[4,c(Math.floor(25*Math.random()))];case 3:return n.sent(),h.setItemSync(a,JSON.stringify({id:this.id,iat:r,timeoutKey:u,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,c(30)];case 4:if(n.sent(),null!==(p=h.getItemSync(a))&&(_=JSON.parse(p)).id===this.id&&_.iat===r)return this.acquiredIatSet.add(r),this.refreshLockWhileAcquired(a,r),[2,!0];return[3,7];case 5:return e.lockCorrector(void 0===this.storageHandler?l:this.storageHandler),[4,this.waitForSomethingToChange(s)];case 6:n.sent(),n.label=7;case 7:return r=Date.now()+d(4),[3,1];case 8:return[2,!1]}})})},e.prototype.refreshLockWhileAcquired=function(e,t){return r(this,void 0,void 0,function(){var i=this;return n(this,function(s){return setTimeout(function(){return r(i,void 0,void 0,function(){var i,r,s;return n(this,function(n){switch(n.label){case 0:return[4,a.default().lock(t)];case 1:if(n.sent(),!this.acquiredIatSet.has(t)||null===(r=(i=void 0===this.storageHandler?l:this.storageHandler).getItemSync(e)))return a.default().unlock(t),[2];return(s=JSON.parse(r)).timeRefreshed=Date.now(),i.setItemSync(e,JSON.stringify(s)),a.default().unlock(t),this.refreshLockWhileAcquired(e,t),[2]}})})},1e3),[2]})})},e.prototype.waitForSomethingToChange=function(t){return r(this,void 0,void 0,function(){return n(this,function(i){switch(i.label){case 0:return[4,new Promise(function(i){var r=!1,n=Date.now(),s=!1;function a(){if(s||(window.removeEventListener("storage",a),e.removeFromWaiting(a),clearTimeout(o),s=!0),!r){r=!0;var t=50-(Date.now()-n);t>0?setTimeout(i,t):i(null)}}window.addEventListener("storage",a),e.addToWaiting(a);var o=setTimeout(a,Math.max(0,t-Date.now()))})];case 1:return i.sent(),[2]}})})},e.addToWaiting=function(t){this.removeFromWaiting(t),void 0!==e.waiters&&e.waiters.push(t)},e.removeFromWaiting=function(t){void 0!==e.waiters&&(e.waiters=e.waiters.filter(function(e){return e!==t}))},e.notifyWaiters=function(){void 0!==e.waiters&&e.waiters.slice().forEach(function(e){return e()})},e.prototype.releaseLock=function(e){return r(this,void 0,void 0,function(){return n(this,function(t){switch(t.label){case 0:return[4,this.releaseLock__private__(e)];case 1:return[2,t.sent()]}})})},e.prototype.releaseLock__private__=function(t){return r(this,void 0,void 0,function(){var i,r,s,c;return n(this,function(n){switch(n.label){case 0:if(i=void 0===this.storageHandler?l:this.storageHandler,r=o+"-"+t,null===(s=i.getItemSync(r)))return[2];if((c=JSON.parse(s)).id!==this.id)return[3,2];return[4,a.default().lock(c.iat)];case 1:n.sent(),this.acquiredIatSet.delete(c.iat),i.removeItemSync(r),a.default().unlock(c.iat),e.notifyWaiters(),n.label=2;case 2:return[2]}})})},e.lockCorrector=function(t){for(var i=Date.now()-5e3,r=[],n=0;;){var s=t.keySync(n);if(null===s)break;r.push(s),n++}for(var a=!1,l=0;l<r.length;l++){var c=r[l];if(c.includes(o)){var d=t.getItemSync(c);if(null!==d){var h=JSON.parse(d);(void 0===h.timeRefreshed&&h.timeAcquired<i||void 0!==h.timeRefreshed&&h.timeRefreshed<i)&&(t.removeItemSync(c),a=!0)}}}a&&e.notifyWaiters()},e.waiters=void 0,e}()},8058(e,t){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var i=function(){function e(){var e=this;this.locked=new Map,this.addToLocked=function(t,i){var r=e.locked.get(t);void 0===r?void 0===i?e.locked.set(t,[]):e.locked.set(t,[i]):void 0!==i&&(r.unshift(i),e.locked.set(t,r))},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise(function(i,r){e.isLocked(t)?e.addToLocked(t,i):(e.addToLocked(t),i())})},this.unlock=function(t){var i=e.locked.get(t);if(void 0===i||0===i.length)return void e.locked.delete(t);var r=i.pop();e.locked.set(t,i),void 0!==r&&setTimeout(r,0)}}return e.getInstance=function(){return void 0===e.instance&&(e.instance=new e),e.instance},e}();t.default=function(){return i.getInstance()}},547(e){e.exports=function(e,t){if("string"!=typeof e)throw TypeError("Expected a string");for(var i,r=String(e),n="",s=!!t&&!!t.extended,a=!!t&&!!t.globstar,o=!1,l=t&&"string"==typeof t.flags?t.flags:"",c=0,d=r.length;c<d;c++)switch(i=r[c]){case"/":case"$":case"^":case"+":case".":case"(":case")":case"=":case"!":case"|":n+="\\"+i;break;case"?":if(s){n+=".";break}case"[":case"]":if(s){n+=i;break}case"{":if(s){o=!0,n+="(";break}case"}":if(s){o=!1,n+=")";break}case",":if(o){n+="|";break}n+="\\"+i;break;case"*":for(var h=r[c-1],u=1;"*"===r[c+1];)u++,c++;var p=r[c+1];a?u>1&&("/"===h||void 0===h)&&("/"===p||void 0===p)?(n+="((?:[^/]*(?:/|$))*)",c++):n+="([^/]*)":n+=".*";break;default:n+=i}return l&&~l.indexOf("g")||(n="^"+n+"$"),new RegExp(n,l)}},8591(e,t,i){"use strict";i.d(t,{},{t:(...e)=>{}})},6100(e,t,i){"use strict";function r(e,t,i){return"function"==typeof e?e(t):void 0!==e?e:void 0!==i?i:void 0}i.d(t,{vd:()=>s,VK:()=>r,lQ:()=>n.t,zc:()=>a});var n=i(8591);function s(e){return Promise.all(Array.from(e).map(e=>e.then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e}))))}function a(e,t,i){let r,n=new Promise((e,n)=>{r=setTimeout(()=>{let e=Error(`Timed out after ${t}ms`);i?.abort(),n(e)},t),r.unref?.()});return Promise.race([Promise.resolve(e),n]).finally(()=>{clearTimeout(r)})}}},n={};function s(e){var t=n[e];if(void 0!==t)return t.exports;var i=n[e]={exports:{}};return r[e].call(i.exports,i,i.exports,s),i.exports}s.m=r,s.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return s.d(t,{a:t}),t},o=Object.getPrototypeOf?e=>Object.getPrototypeOf(e):e=>e.__proto__,s.t=function(e,t){if(1&t&&(e=this(e)),8&t||"object"==typeof e&&e&&(4&t&&e.__esModule||16&t&&"function"==typeof e.then))return e;var i=Object.create(null);s.r(i);var r={};a=a||[null,o({}),o([]),o(o)];for(var n=2&t&&e;("object"==typeof n||"function"==typeof n)&&!~a.indexOf(n);n=o(n))Object.getOwnPropertyNames(n).forEach(t=>{r[t]=()=>e[t]});return r.default=()=>e,s.d(i,r),i},s.d=(e,t,i)=>{var r=(t,i)=>{for(var r in t)s.o(t,r)&&!s.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,[i]:t[r]})};r(t,"get"),r(i,"value")},s.f={},s.e=e=>Promise.all(Object.keys(s.f).reduce((t,i)=>(s.f[i](e,t),t),[])),s.u=e=>""+(({279:"stripe-vendors",545:"vendors",662:"query-core-vendors",729:"zxcvbn-ts-core",811:"cookieSuffix",873:"zxcvbn-common",929:"coinbase-wallet-sdk",994:"base-account-sdk"})[e]||e)+"_clerk.browser_"+s.h().slice(0,6)+"_6.42.0.js",s.h=()=>"5761f4f37f24ddbc",s.g=(()=>{if("object"==typeof globalThis)return globalThis;try{return this||Function("return this")()}catch(e){if("object"==typeof window)return window}})(),s.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),l={},s.l=function(e,t,i,r){if(l[e])return void l[e].push(t);if(void 0!==i)for(var n,a,o=document.getElementsByTagName("script"),c=0;c<o.length;c++){var d=o[c];if(d.getAttribute("src")==e||d.getAttribute("data-rspack")=="@clerk/clerk-js:"+i){n=d;break}}n||(a=!0,(n=document.createElement("script")).timeout=120,s.nc&&n.setAttribute("nonce",s.nc),n.setAttribute("data-rspack","@clerk/clerk-js:"+i),n.src=e),l[e]=[t];var h=function(t,i){n.onerror=n.onload=null,clearTimeout(u);var r=l[e];if(delete l[e],n.parentNode&&n.parentNode.removeChild(n),r&&r.forEach(function(e){return e(i)}),t)return t(i)},u=setTimeout(h.bind(null,void 0,{type:"timeout",target:n}),12e4);n.onerror=h.bind(null,n.onerror),n.onload=h.bind(null,n.onload),a&&document.head.appendChild(n)},s.r=e=>{"u">typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})},s.g.importScripts&&(c=s.g.location+"");var a,o,l,c,d=s.g.document;if(!c&&d&&(d.currentScript&&"SCRIPT"===d.currentScript.tagName.toUpperCase()&&(c=d.currentScript.src),!c)){var h=d.getElementsByTagName("script");if(h.length)for(var u=h.length-1;u>-1&&(!c||!/^http(s?):/.test(c));)c=h[u--].src}if(!c)throw Error("Automatic publicPath is not supported in this browser");return s.p=c=c.replace(/^blob:/,"").replace(/#.*$/,"").replace(/\?.*$/,"").replace(/\/[^\/]+$/,"/"),e={349:0},s.f.j=function(t,i){var r=s.o(e,t)?e[t]:void 0;if(0!==r)if(r)i.push(r[2]);else{var n=new Promise((i,n)=>r=e[t]=[i,n]);i.push(r[2]=n);var a=s.p+s.u(t),o=Error();s.l(a,function(i){if(s.o(e,t)&&(0!==(r=e[t])&&(e[t]=void 0),r)){var n=i&&("load"===i.type?"missing":i.type),a=i&&i.target&&i.target.src;o.message="Loading chunk "+t+" failed.\n("+n+": "+a+")",o.name="ChunkLoadError",o.type=n,o.request=a,r[1](o)}},"chunk-"+t,t)}},t=(t,i)=>{var r,n,[a,o,l]=i,c=0;if(a.some(t=>0!==e[t])){for(r in o)s.o(o,r)&&(s.m[r]=o[r]);l&&l(s)}for(t&&t(i);c<a.length;c++)n=a[c],s.o(e,n)&&e[n]&&e[n][0](),e[n]=0},(i=globalThis.rspackChunk_clerk_clerk_js=globalThis.rspackChunk_clerk_clerk_js||[]).forEach(t.bind(null,0)),i.push=t.bind(null,i.push.bind(i)),s(292)})());
|