UNPKG

@clerk/clerk-js

Version:
11 lines (10 loc) • 211 kB
!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 n in i)("object"==typeof exports?exports:e)[n]=i[n]}}(globalThis,()=>(()=>{var e={47:function(e,t,i){"use strict";let n;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.*)/,"$15.79.0$3")}catch{}function r(){return"undefined"!=typeof window}i(96);var s,a,o,l,c,h,d,u,p,m,f,_,g,y,w,b,v,S,k,A=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");function C(){var e;let t=r()?window?.navigator:null;return!!t&&!((e=t?.userAgent)&&A.test(e))&&!t?.webdriver}function U(){let e=r()?window?.navigator:null;if(!e)return!1;let t=e?.onLine;return e?.connection?.rtt!==0&&e?.connection?.downlink!==0&&t}Object.prototype.hasOwnProperty;var I=e=>{throw TypeError(e)},O=(e,t,i)=>t.has(e)||I("Cannot "+i),P=(e,t,i)=>(O(e,t,"read from private field"),i?i.call(e):t.get(e)),T=(e,t,i)=>t.has(e)?I("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,i),x=(e,t,i,n)=>(O(e,t,"write to private field"),n?n.call(e,i):t.set(e,i),i),E=(e,t,i)=>(O(e,t,"access private method"),i),R=(e,t,i,n,r)=>{let{notify:s}=r||{},a=e.get(i);a||(a=[],e.set(i,a)),a.push(n),s&&t.has(i)&&n(t.get(i))},z=(e,t,i)=>(e.get(t)||[]).map(e=>e(i)),N=(e,t,i)=>{let n=e.get(t);n&&(i?n.splice(n.indexOf(i)>>>0,1):e.set(t,[]))},M=()=>{let e=new Map,t=new Map,i=new Map;return{on:(...i)=>R(e,t,...i),prioritizedOn:(...e)=>R(i,t,...e),emit:(n,r)=>{t.set(n,r),z(i,n,r),z(e,n,r)},off:(...t)=>N(e,...t),prioritizedOff:(...e)=>N(i,...e),internal:{retrieveListeners:t=>e.get(t)||[]}}},F="status",D=new Set;function W(e){let t=e?.status;return!!t&&t>=400&&t<500}function L(e){return"clerkError"in e}function $(e){return"clerkRuntimeError"in e}function j(e=[]){return e.length>0?e.map(J):[]}function J(e){return{code:e.code,message:e.message,longMessage:e.long_message,meta:{paramName:e?.meta?.param_name,sessionId:e?.meta?.session_id,emailAddresses:e?.meta?.email_addresses,identifiers:e?.meta?.identifiers,zxcvbn:e?.meta?.zxcvbn,plan:e?.meta?.plan,isPlanUpgradePossible:e?.meta?.is_plan_upgrade_possible}}}var K=class e extends Error{constructor(t,{data:i,status:n,clerkTraceId:r,retryAfter:s}){super(t),this.toString=()=>{let e=`[${this.name}] Message:${this.message} Status:${this.status} Serialized errors: ${this.errors.map(e=>JSON.stringify(e))}`;return this.clerkTraceId&&(e+=` Clerk Trace ID: ${this.clerkTraceId}`),e},Object.setPrototypeOf(this,e.prototype),this.status=n,this.message=t,this.clerkTraceId=r,this.retryAfter=s,this.clerkError=!0,this.errors=j(i)}},B=class e extends Error{constructor(t,{code:i}){let n="\uD83D\uDD12 Clerk:",r=RegExp(n.replace(" ","\\s*"),"i"),s=t.replace(r,""),a=`${n} ${s.trim()} (code="${i}") `;super(a),this.toString=()=>`[${this.name}] Message:${this.message}`,Object.setPrototypeOf(this,e.prototype),this.code=i,this.message=a,this.clerkRuntimeError=!0,this.name="ClerkRuntimeError"}},V=class e extends Error{constructor(t){super(t),this.code=t,this.name="EmailLinkError",Object.setPrototypeOf(this,e.prototype)}},q=Object.freeze({InvalidProxyUrlErrorMessage:"The proxyUrl passed to Clerk is invalid. The expected value for proxyUrl is an absolute URL or a relative path with a leading '/'. (key={{url}})",InvalidPublishableKeyErrorMessage:"The publishableKey passed to Clerk is invalid. You can get your Publishable key at https://dashboard.clerk.com/last-active?path=api-keys. (key={{key}})",MissingPublishableKeyErrorMessage:"Missing publishableKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.",MissingSecretKeyErrorMessage:"Missing secretKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.",MissingClerkProvider:"{{source}} can only be used within the <ClerkProvider /> component. Learn more: https://clerk.com/docs/components/clerk-provider"}),H=class extends B{constructor(e,{code:t}){super(e,{code:t}),this.code=t}},G=e=>"undefined"!=typeof atob&&"function"==typeof atob?atob(e):"undefined"!=typeof global&&global.Buffer?new global.Buffer(e,"base64").toString():e,Y=[".lcl.dev",".lclstage.dev",".lclclerk.com"],Q=[".accounts.dev",".accountsstage.dev",".accounts.lclclerk.com"],X=[".lcl.dev",".stg.dev",".lclstage.dev",".stgstage.dev",".dev.lclclerk.com",".stg.lclclerk.com",".accounts.lclclerk.com","accountsstage.dev","accounts.dev"],Z="pk_live_";function ee(e){if(!e.endsWith("$"))return!1;let t=e.slice(0,-1);return!t.includes("$")&&t.includes(".")}function et(e,t={}){let i;if(!(e=e||"")||!ei(e)){if(t.fatal&&!e)throw Error("Publishable key is missing. Ensure that your publishable key is correctly configured. Double-check your environment configuration for your keys, or access them here: https://dashboard.clerk.com/last-active?path=api-keys");if(t.fatal&&!ei(e))throw Error("Publishable key not valid.");return null}let n=e.startsWith(Z)?"production":"development";try{i=G(e.split("_")[2])}catch{if(t.fatal)throw Error("Publishable key not valid: Failed to decode key.");return null}if(!ee(i)){if(t.fatal)throw Error("Publishable key not valid: Decoded key has invalid format.");return null}let r=i.slice(0,-1);return t.proxyUrl?r=t.proxyUrl:"development"!==n&&t.domain&&t.isSatellite&&(r=`clerk.${t.domain}`),{instanceType:n,frontendApi:r}}function ei(e=""){try{if(!(e.startsWith(Z)||e.startsWith("pk_test_")))return!1;let t=e.split("_");if(3!==t.length)return!1;let i=t[2];if(!i)return!1;let n=G(i);return ee(n)}catch{return!1}}async function en(e,t=globalThis.crypto.subtle){var i;let n=new TextEncoder().encode(e);return(i=String.fromCharCode(...new Uint8Array(await t.digest("sha-1",n))),"undefined"!=typeof btoa&&"function"==typeof btoa?btoa(i):"undefined"!=typeof global&&global.Buffer?new global.Buffer(i).toString("base64"):i).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}var er=(e,t)=>`${e}_${t}`,es=class{constructor(e){this.eventTarget=window,this.postMessage=e=>{if("undefined"!=typeof window)try{window.localStorage.setItem(this.channelKey,JSON.stringify(e)),window.localStorage.removeItem(this.channelKey)}catch{}},this.addEventListener=(e,t)=>{this.eventTarget.addEventListener(this.prefixEventName(e),e=>{t(e)})},this.setupLocalStorageListener=()=>{let e=e=>{if(e.key===this.channelKey&&e.newValue)try{let t=JSON.parse(e.newValue||""),i=new MessageEvent(this.prefixEventName("message"),{data:t});this.eventTarget.dispatchEvent(i)}catch{}};window.addEventListener("storage",e)},this.channelKey="__lsbc__"+e,this.setupLocalStorageListener()}prefixEventName(e){return this.channelKey+e}},ea=new Set,eo=e=>{ea.has(e)||(ea.add(e),console.warn(e))},el="__clerk_netlify_cache_bust";function ec(e){return/^http(s)?:\/\//.test(e||"")}function eh(e){return e.startsWith("/")}function ed(e){return e?e.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`):""}var eu=e=>{let t=i=>{if(!i)return i;if(Array.isArray(i))return i.map(e=>"object"==typeof e||Array.isArray(e)?t(e):e);let n={...i};for(let i of Object.keys(n)){let r=e(i.toString());r!==i&&(n[r]=n[i],delete n[i]),"object"==typeof n[r]&&(n[r]=t(n[r]))}return n};return t},ep=eu(ed),em=eu(function(e){return e?e.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace(/-|_/,"")):""});function ef(e){if("boolean"==typeof e)return e;if(null==e)return!1;if("string"==typeof e){if("true"===e.toLowerCase())return!0;if("false"===e.toLowerCase())return!1}let t=parseInt(e,10);return!isNaN(t)&&t>0}var e_=class{constructor(){T(this,o),T(this,s,"clerk_telemetry_throttler"),T(this,a,864e5)}isEventThrottled(e){if(!P(this,o,h))return!1;let t=Date.now(),i=E(this,o,l).call(this,e),n=P(this,o,c)?.[i];if(!n){let e={...P(this,o,c),[i]:t};localStorage.setItem(P(this,s),JSON.stringify(e))}if(n&&t-n>P(this,a)){let e=P(this,o,c);delete e[i],localStorage.setItem(P(this,s),JSON.stringify(e))}return!!n}};s=new WeakMap,a=new WeakMap,o=new WeakSet,l=function(e){let{sk:t,pk:i,payload:n,...r}=e,s={...n,...r};return JSON.stringify(Object.keys({...n,...r}).sort().map(e=>s[e]))},c=function(){let e=localStorage.getItem(P(this,s));return e?JSON.parse(e):{}},h=function(){if("undefined"==typeof window)return!1;let e=window.localStorage;if(!e)return!1;try{let t="test";return e.setItem(t,t),e.removeItem(t),!0}catch(t){return t instanceof DOMException&&("QuotaExceededError"===t.name||"NS_ERROR_DOM_QUOTA_REACHED"===t.name)&&e.length>0&&e.removeItem(P(this,s)),!1}};var eg=class{constructor(e){T(this,_),T(this,d),T(this,u),T(this,p,{}),T(this,m,[]),T(this,f),x(this,d,{maxBufferSize:e.maxBufferSize??5,samplingRate:e.samplingRate??1,disabled:e.disabled??!1,debug:e.debug??!1,endpoint:"https://clerk-telemetry.com"}),e.clerkVersion||"undefined"!=typeof window?P(this,p).clerkVersion=e.clerkVersion??"":P(this,p).clerkVersion="",P(this,p).sdk=e.sdk,P(this,p).sdkVersion=e.sdkVersion,P(this,p).publishableKey=e.publishableKey??"";let t=et(e.publishableKey);t&&(P(this,p).instanceType=t.instanceType),e.secretKey&&(P(this,p).secretKey=e.secretKey.substring(0,16)),x(this,u,new e_)}get isEnabled(){return!("development"!==P(this,p).instanceType||P(this,d).disabled||"undefined"!=typeof process&&process.env&&ef(process.env.CLERK_TELEMETRY_DISABLED)||"undefined"!=typeof window&&window?.navigator?.webdriver)}get isDebug(){return P(this,d).debug||"undefined"!=typeof process&&process.env&&ef(process.env.CLERK_TELEMETRY_DEBUG)}record(e){let t=E(this,_,k).call(this,e.event,e.payload);E(this,_,v).call(this,t.event,t),E(this,_,g).call(this,t,e.eventSamplingRate)&&(P(this,m).push(t),E(this,_,w).call(this))}};function ey(e){return function(t,i,n){return{event:e,eventSamplingRate:.1,payload:{component:t,appearanceProp:!!i?.appearance,baseTheme:!!i?.appearance?.baseTheme,elements:!!i?.appearance?.elements,variables:!!i?.appearance?.variables,...n}}}}function ew(e,t,i){return ey("COMPONENT_MOUNTED")(e,t,i)}function eb(e,t,i){return ey("COMPONENT_OPENED")(e,t,i)}d=new WeakMap,u=new WeakMap,p=new WeakMap,m=new WeakMap,f=new WeakMap,_=new WeakSet,g=function(e,t){return this.isEnabled&&!this.isDebug&&E(this,_,y).call(this,e,t)},y=function(e,t){let i=Math.random();return!!(i<=P(this,d).samplingRate&&(void 0===t||i<=t))&&!P(this,u).isEventThrottled(e)},w=function(){if("undefined"==typeof window)return void E(this,_,b).call(this);if(P(this,m).length>=P(this,d).maxBufferSize){P(this,f)&&("undefined"!=typeof cancelIdleCallback?cancelIdleCallback:clearTimeout)(P(this,f)),E(this,_,b).call(this);return}P(this,f)||("requestIdleCallback"in window?x(this,f,requestIdleCallback(()=>{E(this,_,b).call(this)})):x(this,f,setTimeout(()=>{E(this,_,b).call(this)},0)))},b=function(){fetch(new URL("/v1/event",P(this,d).endpoint),{method:"POST",body:JSON.stringify({events:P(this,m)}),headers:{"Content-Type":"application/json"}}).catch(()=>void 0).then(()=>{x(this,m,[])}).catch(()=>void 0)},v=function(e,t){this.isDebug&&(void 0!==console.groupCollapsed?(console.groupCollapsed("[clerk/telemetry]",e),console.log(t),console.groupEnd()):console.log("[clerk/telemetry]",e,t))},S=function(){let e={name:P(this,p).sdk,version:P(this,p).sdkVersion};if("undefined"!=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:n}=i.constructor.sdkMetadata;void 0!==t&&(e.name=t),void 0!==n&&(e.version=n)}}}return e},k=function(e,t){let i=E(this,_,S).call(this);return{event:e,cv:P(this,p).clerkVersion??"",it:P(this,p).instanceType??"",sdk:i.name,sdkv:i.version,...P(this,p).publishableKey?{pk:P(this,p).publishableKey}:{},...P(this,p).secretKey?{sk:P(this,p).secretKey}:{},payload:t}};var ev=/^[a-zA-Z][a-zA-Z\d+\-.]*?:/,eS=(...e)=>{};function ek(e,t,i){return"function"==typeof e?e(t):void 0!==e?e:void 0!==i?i:void 0}let eA="clerk:beforeunload",eC=["http:","https:","wails:","chrome-extension:"];function eU(e){let t=new URL(e,window.location.href);window.dispatchEvent(new CustomEvent(eA)),window.location.href=t.href}let eI=(e=!1)=>{if(!e)return{track:async e=>{await e()},isUnloading:()=>!1};let t=(()=>{let e=!1,t=()=>e=!0;return{startListening:()=>{window.addEventListener("beforeunload",t),window.addEventListener(eA,t)},stopListening:()=>{window.removeEventListener("beforeunload",t),window.removeEventListener(eA,t)},isUnloading:()=>e}})();return{track:async e=>{t.startListening(),await e(),t.stopListening()},isUnloading:t.isUnloading}},eO=e=>({amount:e.amount,amountFormatted:e.amount_formatted,currency:e.currency,currencySymbol:e.currency_symbol}),eP=e=>{let t={grandTotal:eO(e.grand_total),subtotal:eO(e.subtotal),taxTotal:eO(e.tax_total)};return"total_due_now"in e&&(t.totalDueNow=eO(e.total_due_now)),"credit"in e&&(t.credit=eO(e.credit)),"past_due"in e&&(t.pastDue=eO(e.past_due)),t},eT="__clerk_synced",ex="suffixed_cookies",eE="__clerk_satellite_url",eR=["__clerk_status","__clerk_created_session","__clerk_invitation_token","__clerk_ticket","__clerk_modal_state","__clerk_handshake","__clerk_handshake_nonce","__clerk_help",el,eT,eE,ex];function ez(e){return new URL(window.location.href).searchParams.get(e)||null}function eN(e){let t=new URL(window.location.href);t.searchParams.has(e)&&(t.searchParams.delete(e),window.history.replaceState(window.history.state,"",t))}let eM=(e,t)=>!!(e.session&&t?.authConfig.singleSessionMode),eF=(e,t)=>!t?.organizationSettings.enabled,eD=(e,t)=>!t?.commerceSettings.billing.user.enabled&&!t?.commerceSettings.billing.organization.enabled;function eW(e,t=""){return e.errors&&!!e.errors.find(e=>e.code===t)}let eL=function({packageName:e,customMessages:t}){let i=e;function n(e,t){if(!t)return`${i}: ${e}`;let n=e;for(let i of e.matchAll(/{{([a-zA-Z0-9-_]+)}}/g)){let e=(t[i[1]]||"").toString();n=n.replace(`{{${i[1]}}}`,e)}return`${i}: ${n}`}let r={...q,...t};return{setPackageName({packageName:e}){return"string"==typeof e&&(i=e),this},setMessages({customMessages:e}){return Object.assign(r,e||{}),this},throwInvalidPublishableKeyError(e){throw Error(n(r.InvalidPublishableKeyErrorMessage,e))},throwInvalidProxyUrl(e){throw Error(n(r.InvalidProxyUrlErrorMessage,e))},throwMissingPublishableKeyError(){throw Error(n(r.MissingPublishableKeyErrorMessage))},throwMissingSecretKeyError(){throw Error(n(r.MissingSecretKeyErrorMessage))},throwMissingClerkProviderError(e){throw Error(n(r.MissingClerkProvider,e))},throw(e){throw Error(n(e))}}}({packageName:"@clerk/clerk-js"});var e$=i(763);let ej=RegExp("/{1,}","g"),eJ=(e,t={})=>{if(null==e||!e||"object"!=typeof e)return"";let i=new URLSearchParams;return Object.keys(e).forEach(n=>{let r=t.keyEncoder?t.keyEncoder(n):n,s=e[n];if(Array.isArray(s))s.forEach(e=>void 0!==e&&i.append(r,e||""));else{if(void 0===s)return;"object"==typeof s&&null!==s?i.append(r,JSON.stringify(s)):i.append(r,String(s??""))}}),i.toString()},eK="http://clerk-dummy",eB=["javascript:"],{isDevOrStagingUrl:eV}=function(){let e=new Map;return{isDevOrStagingUrl:t=>{if(!t)return!1;let i="string"==typeof t?t:t.hostname,n=e.get(i);return void 0===n&&(n=X.some(e=>i.endsWith(e)),e.set(i,n)),n}}}(),eq=new Map;function eH(e){return e.replace("clerk.","")}function eG(e,t={}){let{base:i,hashPath:n,hashSearch:r,searchParams:s,hashSearchParams:a,...o}=e,l=new URL(i||"","undefined"!=typeof window&&window.location?window.location.href:"http://react-native-fake-base-url");if(s instanceof URLSearchParams&&s.forEach((e,t)=>{null!=e&&l.searchParams.set(ed(t),e)}),Object.assign(l,o),n||r||a){var c;let e=new URL(eK+l.hash.substring(1));for(let[t,i]of(c=e.pathname,e.pathname=[c,n||""].filter(e=>e).join("/").replace(ej,"/"),Object.entries((e=>{let t={};return new URLSearchParams(e).forEach((e,i)=>{if(i in t){let n=t[i];Array.isArray(n)?n.push(e):t[i]=[n,e]}else t[i]=e}),t})(r||""))))e.searchParams.append(t,i);if(a)for(let t of Array.isArray(a)?a:[a])(t instanceof URLSearchParams||"object"==typeof t)&&new URLSearchParams(t).forEach((t,i)=>{null!=t&&e.searchParams.set(ed(i),t)});let t=e.href.replace(eK,"");"/"!==t&&(l.hash=t)}let{stringify:h,skipOrigin:d}=t;return h?d?l.href.replace(l.origin,""):l.href:l}let eY=e=>(e||"").replace(/\/+$/,"");function eQ(e,t){try{return new URL(e)}catch{return new URL(e,t)}}let eX=[/\0/,/^\/\//,/[\x00-\x1F]/],eZ=["/oauth/authorize"],e0=["/v1/verify","/v1/tickets/accept"];function e1(e){var t;return t=e.replace(/_/g,"/").replace(/-/g,"+"),decodeURIComponent(i.g.atob(t).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""))}function e3(e){let t=(e||"").split("."),[i,n,r]=t;if(3!==t.length||!i||!n||!r)throw Error("JWT could not be decoded");let s=JSON.parse(e1(n)),a={__raw:e};return Object.keys(s).forEach(e=>{a[e]=s[e]}),{encoded:{header:i,payload:n,signature:r},header:JSON.parse(e1(i)),claims:a}}function e2(){return void 0!==globalThis.document}function e4(){return e2()&&globalThis.document.hasFocus()}function e5(){return e2()&&window.self!==window.top&&!window.frameElement}class e6{#e=[];#t={metamask:"MetaMask",okx_wallet:"OKX Wallet"};static #i=null;constructor(){if("undefined"==typeof window)return;window.addEventListener("eip6963:announceProvider",this.#n),window.dispatchEvent(new Event("eip6963:requestProvider"))}static getInstance(){return e6.#i||(e6.#i=new e6),e6.#i}get=e=>{let t=this.#e.find(t=>t.info.name===this.#t[e])?.provider;return void 0!==t?t:window.ethereum};#n=e=>{this.#e.some(t=>t.info.uuid===e.detail.info.uuid)||this.#e.push(e.detail)}}async function e9(e){let{provider:t}=e,i=await ts(t);if(!i)return"";let n=await i.request({method:"eth_requestAccounts"});return n&&n[0]||""}async function e8(e){let{identifier:t,nonce:i,provider:n}=e,r=await ts(n);return r?await r.request({method:"personal_sign",params:[`0x${i.split("").map(e=>e.charCodeAt(0).toString(16).padStart(2,"0")).join("")}`,t]}):""}async function e7(){return await e9({provider:"metamask"})}async function te(){return await e9({provider:"coinbase_wallet"})}async function tt(){return await e9({provider:"okx_wallet"})}async function ti(e){return await e8({...e,provider:"metamask"})}async function tn(e){return await e8({...e,provider:"coinbase_wallet"})}async function tr(e){return await e8({...e,provider:"okx_wallet"})}async function ts(e){return"coinbase_wallet"===e?(await Promise.all([i.e("956"),i.e("192")]).then(i.bind(i,453)).then(e=>e.createCoinbaseWalletSDK))({preference:{options:"all"}}).getProvider():e6.getInstance().get(e)}function ta(e){let t=["redirectUrl","afterSignInUrl","afterSignUpUrl","after_sign_in_url","after_sign_up_url"],i=Object.keys(e).find(e=>t.includes(e));i&&e[i]&&eo(`Clerk: The prop "${i}" is deprecated and should be replaced with the new "fallbackRedirectUrl" or "forceRedirectUrl" props instead. Learn more: https://clerk.com/docs/guides/custom-redirects#redirect-url-props`)}let to="environment",tl=JSON.stringify,tc=JSON.parse;class th{static _key(e){return`__clerk_${e}`}static isExpired(e){return!!e.exp&&Date.now()>e.exp}static setItem(e,t,i){try{let n={value:t,...i&&{exp:Date.now()+i}};window.localStorage.setItem(this._key(e),tl(n))}catch{}}static getItem(e,t){try{let i=window.localStorage.getItem(this._key(e));if(!i)return t;let n=tc(i);if(!n)return t;if(this.isExpired(n))return this.removeItem(e),t;return n?.value??t}catch{return t}}static removeItem(e){try{window.localStorage.removeItem(this._key(e))}catch{}}}let td="ClerkJS:";function tu(e=""){throw Error(`${td} Something went wrong initializing Clerk in development mode.${e&&` ${e}`}`)}function tp(e){throw Error(`${td} Something went wrong initializing Clerk during the ${e} flow. Please contact support.`)}function tm(e){throw Error(`${td} You need to start a ${e} flow by calling ${e}.create() first.`)}function tf(e,t){throw Error(`${td} Strategy "${t}" is not a valid strategy for ${e}.`)}function t_(e){throw Error(`${td} You need to start a ${e} flow by calling ${e}.create({ identifier: 'your web3 wallet address' }) first`)}function tg(e=""){throw Error(`${td} Missing '${e}' option`)}function ty(e,t){throw Error(`${td} Response: ${e||0} not supported yet. For more information contact us at ${t}`)}function tw(e){throw Error(`${td} Missing publicKey. When calling 'navigator.credentials.${e}()' it is required to pass a publicKey object.`)}var tb={initialDelay:125,maxDelayBetweenRetries:0,factor:2,shouldRetry:(e,t)=>t<5,retryImmediately:!1,jitter:!0},tv=async e=>new Promise(t=>setTimeout(t,e)),tS=(e,t)=>t?e*(1+Math.random()):e,tk=async(e,t={})=>{var i;let n,r=0,{shouldRetry:s,initialDelay:a,maxDelayBetweenRetries:o,factor:l,retryImmediately:c,jitter:h}={...tb,...t},d=(i={initialDelay:a,maxDelayBetweenRetries:o,factor:l,jitter:h},n=0,async()=>{let e;await tv((e=tS(e=i.initialDelay*Math.pow(i.factor,n),i.jitter),Math.min(i.maxDelayBetweenRetries||e,e))),n++});for(;;)try{return await e()}catch(e){if(!s(e,++r))throw e;c&&1===r?await tv(tS(100,h)):await d()}};async function tA(e="",t){let{async:i,defer:n,beforeLoad:r,crossOrigin:s,nonce:a}=t||{};return tk(()=>new Promise((t,o)=>{e||o(Error("loadScript cannot be called without a src")),document&&document.body||o("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=n||!1,l.addEventListener("load",()=>{l.remove(),t(l)}),l.addEventListener("error",()=>{l.remove(),o()}),l.src=e,l.nonce=a,r?.(l),document.body.appendChild(l)}),{shouldRetry:(e,t)=>t<=5})}let tC="clerk-captcha",tU="clerk-invisible-captcha";async function tI(e){return window.turnstile||await tO(e).catch(()=>{throw{captchaError:"captcha_script_failed_to_load"}}),window.turnstile}async function tO(e){try{return await tA("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 tP(e){try{let t=e.getAttribute("data-cl-theme")||void 0,i=e.getAttribute("data-cl-language")||void 0,n=e.getAttribute("data-cl-size")||void 0;return{theme:t,language:i,size:n}}catch{return{theme:void 0,language:void 0,size:void 0}}}let tT=async e=>{let t,i,n,r,{siteKey:s,widgetType:a,invisibleSiteKey:o,nonce:l}=e,{modalContainerQuerySelector:c,modalWrapperQuerySelector:h,closeModal:d,openModal:u}=e,p=await tI(l),m=[],f="",_="",g=s,y=0,w=null,b="invisible";if(c&&h){w=a,r=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:r,language:s,size:a}=tP(e);t=r,n=s,i=a}}if(!r&&"smart"===a){let e=document.getElementById(tC);if(e){b="smart",w="smart",r=`#${tC}`,e.style.maxHeight="0";let{theme:s,language:a,size:o}=tP(e);t=s,n=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/custom-flows/bot-sign-up-protection for instructions")}if(!r){b="invisible",g=o,w="invisible",r=`.${tU}`;let e=document.createElement("div");e.classList.add(tU),e.style.display="none",document.body.appendChild(e)}let v=async()=>new Promise((s,a)=>{try{let o=p.render(r,{sitekey:g,appearance:"interaction-only",theme:t||"auto",size:i||"normal",language:n||"auto",action:e.action,retry:"never","refresh-expired":"auto",callback:function(e){d?.(),s([e,o])},"before-interactive-callback":()=>{if(h){let e=document.querySelector(h);e?.style.setProperty("visibility","visible"),e?.style.setProperty("pointer-events","all")}else{let e=document.getElementById(tC);e&&(e.style.maxHeight="unset",e.style.minHeight="compact"===i?"140px":"68px",e.style.marginBottom="1.5rem")}},"error-callback":function(e){var t;if(m.push(e),y<2&&(t=e.toString(),["crashed","undefined_error","102","103","104","106","110600","300","600"].find(e=>t.startsWith(e))))return void setTimeout(()=>{p.reset(o),y++},250);a([m.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,_]=await v(),p.remove(_)}catch([e,t]){throw t&&p.remove(t),{captchaError:e}}finally{if("modal"===b&&d?.(),"invisible"===b){let e=document.querySelector(`.${tU}`);e&&document.body.removeChild(e)}if("smart"===b){let e=document.getElementById(tC);e&&(e.style.maxHeight="0",e.style.minHeight="unset",e.style.marginBottom="unset")}}return{captchaToken:f,captchaWidgetType:w}},tx=e=>tT(e),tE=e=>{let t=e.__unstable__environment,i=t?t.displayConfig.captchaProvider:"turnstile",n=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:n||void 0}};class tR{clerk;constructor(e){this.clerk=e}async invisible(e){let{captchaSiteKey:t,canUseCaptcha:i,captchaPublicKeyInvisible:n,nonce:r}=tE(this.clerk);return i&&t&&n?{...await tx({action:e?.action,captchaProvider:"turnstile",invisibleSiteKey:n,nonce:e?.nonce||r||void 0,siteKey:n,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:n,captchaProvider:r,captchaPublicKeyInvisible:s,nonce:a}=tE(this.clerk);if(i&&t&&s){let i=await tx({captchaProvider:r,invisibleSiteKey:s,nonce:a||void 0,siteKey:t,widgetType:n,...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){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 tz{client;CaptchaChallengeImpl;static instance;inflightException=null;captchaRetryCount=0;MAX_RETRY_ATTEMPTS=3;static getInstance(){return tz.instance||(tz.instance=new tz(tB,tR)),tz.instance}constructor(e,t){this.client=e,this.CaptchaChallengeImpl=t}async execute(e,t){if(this.captchaAttemptsExceeded())throw new B("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(n){let i;if(!L(n)||n.errors[0]?.code!=="requires_captcha")throw n;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 tN{static clerk;id;pathRoot="";static get fapiClient(){return tN.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 tz.getInstance().execute(this.clerk,()=>this._baseFetch(e,t))}static async _baseFetch(e,t={}){let i;tN.fapiClient||function(){throw Error(`${td} Missing FAPI client in resources.`)}();let{fetchMaxTries:n}=t;try{i=await tN.fapiClient.request(e,{fetchMaxTries:n})}catch(e){if(this.shouldRethrowOfflineNetworkErrors())throw new B(e?.message||e,{code:"network_error"});if(!(U()&&C()))return console.warn(e),null;throw e}let{payload:r,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)&&this._updateClient(r),s>=200&&s<=299)return r;if(s>=400){let e=r?.errors,t=e?.[0]?.long_message,i=e?.[0]?.code;401===s&&"requires_captcha"!==i&&await tN.clerk.handleUnauthenticated(),function(e,t){var i;if(!t||!t[0])return;let n=t[0],r=n.long_message;if("origin_invalid"===n.code&&((i=tN.clerk.publishableKey).startsWith("live_")||i.startsWith("pk_live_"))){let i=tN.clerk.frontendApi.replace("clerk.","");throw new K(`Clerk: Production Keys are only allowed for domain "${i}". API Error: ${r}`,{data:t,status:e})}}(s,e);let n={data:e,status:s};if(429===s&&o){let e=o.get("retry-after");if(e){let t=parseInt(e,10);isNaN(t)||(n.retryAfter=t)}}throw new K(t||a,n)}return null}static _updateClient(e){if(!e)return;let t=e.client||e.meta?.client;t&&tN.clerk&&tN.clerk.updateClient(tB.getOrCreateInstance().fromJSON(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 tN._fetch({method:"GET",path:this.path(),rotatingTokenNonce:e.rotatingTokenNonce},e);return this.fromJSON(t?.response||t)}async _baseMutate(e){let{action:t,body:i,method:n,path:r}=e,s=await tN._fetch({method:n,path:r||this.path(t),body:i});return this.fromJSON(s?.response||s)}async _baseMutateBypass(e){let{action:t,body:i,method:n,path:r}=e,s=await tN._baseFetch({method:n,path:r||this.path(t),body:i});return this.fromJSON(s?.response||s)}async _basePost(e={}){return this._baseMutate({...e,method:"POST"})}async _basePostBypass(e={}){return this._baseMutateBypass({...e,method:"POST"})}async _basePut(e={}){return this._baseMutate({...e,method:"PUT"})}async _basePatch(e={}){return this._baseMutate({...e,method:"PATCH"})}async _baseDelete(e={}){await this._baseMutate({...e,method:"DELETE"})}static shouldRethrowOfflineNetworkErrors(){let e=tN.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}let tM={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 tF extends tN{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:{...tM,name:"phone_number"},username:{...tM,name:"username"},web3_wallet:{...tM,name:"web3_wallet"},first_name:{...tM,name:"first_name"},last_name:{...tM,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:{...tM,name:"authenticator_app"},backup_code:{...tM,name:"backup_code"},passkey:{...tM,name:"passkey"}};enterpriseSSO={enabled:!1};passkeySettings={allow_autofill:!1,show_sign_in_button:!1};passwordSettings={};saml={enabled:!1};signIn={second_factor:{required:!1,enabled:!1}};signUp={allowlist_only:!1,captcha_enabled:!1,legal_consent_enabled:!1,mode:"public",progressive:!0};social={};usernameSettings={};get authenticatableSocialStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled&&e.authenticatable).map(([,e])=>e.strategy).sort():[]}get enabledFirstFactorIdentifiers(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&!e.startsWith("web3")).map(([e])=>e):[]}get socialProviderStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled).map(([,e])=>e.strategy).sort():[]}get web3FirstFactors(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&e.startsWith("web3")).map(([,e])=>e.first_factors).flat():[]}get alternativePhoneCodeChannels(){return this.attributes?Object.entries(this.attributes).filter(([e,t])=>t.used_for_first_factor&&"phone_number"===e).map(([,e])=>e?.channels?.filter(e=>"sms"!==e)||[]).flat():[]}constructor(e=null){super(),this.fromJSON(e)}get instanceIsPasswordBased(){return!!(this.attributes?.password?.enabled&&this.attributes.password?.required)}get hasValidAuthFactor(){return!!(this.attributes?.email_address?.enabled||this.attributes?.phone_number?.enabled||this.attributes.password?.required&&this.attributes.username?.required)}fromJSON(e){return e&&(this.attributes=this.withDefault(e.attributes?Object.fromEntries(Object.entries(e.attributes).map(e=>[e[0],{...e[1],name:e[0]}])):null,this.attributes),this.actions=this.withDefault(e.actions,this.actions),this.enterpriseSSO=this.withDefault(e.enterprise_sso,this.enterpriseSSO),this.passkeySettings=this.withDefault(e.passkey_settings,this.passkeySettings),this.passwordSettings=e.password_settings?{...e.password_settings,min_length:Math.max(e.password_settings?.min_length??8,8),max_length:e.password_settings?.max_length===0?72:Math.min(e.password_settings?.max_length??72,72)}:this.passwordSettings,this.saml=this.withDefault(e.saml,this.saml),this.signIn=this.withDefault(e.sign_in,this.signIn),this.signUp=this.withDefault(e.sign_up,this.signUp),this.social=this.withDefault(e.social,this.social),this.usernameSettings=e.username_settings?{...e.username_settings,min_length:Math.max(e.username_settings?.min_length??4,4),max_length:Math.min(e.username_settings?.max_length??64,64)}:this.usernameSettings),this}__internal_toSnapshot(){return{actions:this.actions,attributes:this.attributes,passkey_settings:this.passkeySettings,password_settings:this.passwordSettings,saml:this.saml,sign_in:this.signIn,sign_up:this.signUp,social:this.social}}}class tD extends tN{billing={stripePublishableKey:"",enabled:!1,hasPaidUserPlans:!1,hasPaidOrgPlans:!1,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.enabled=e.billing.enabled||!1,this.billing.hasPaidUserPlans=e.billing.has_paid_user_plans||!1,this.billing.hasPaidOrgPlans=e.billing.has_paid_org_plans||!1,this.billing.organization.enabled=e.billing.organization.enabled||!1,this.billing.organization.hasPaidPlans=e.billing.organization.has_paid_plans||!1,this.billing.user.enabled=e.billing.user.enabled||!1,this.billing.user.hasPaidPlans=e.billing.user.has_paid_plans||!1),this}__internal_toSnapshot(){return{billing:{stripe_publishable_key:this.billing.stripePublishableKey,enabled:this.billing.enabled,has_paid_user_plans:this.billing.hasPaidUserPlans,has_paid_org_plans:this.billing.hasPaidOrgPlans,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}}}}}function tW(e){let t=new Date(e||new Date);return t instanceof Date&&!isNaN(t.getTime())?t:new Date}class tL extends tN{claimedAt=null;reverification=!1;singleSessionMode=!1;preferredChannels=null;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.claimedAt=this.withDefault(e.claimed_at?tW(e.claimed_at):null,this.claimedAt),this.reverification=this.withDefault(e.reverification,this.reverification),this.singleSessionMode=this.withDefault(e.single_session_mode,this.singleSessionMode),this.preferredChannels=this.withDefault(e.preferred_channels,this.preferredChannels)),this}__internal_toSnapshot(){return{claimed_at:this.claimedAt?this.claimedAt.getTime():null,id:this.id??"",object:"auth_config",reverification:this.reverification,single_session_mode:this.singleSessionMode}}}let t$="clerk",tj=10;class tJ{prefix;data;static fromKey(e){let[t,i,n=""]=e.split("::");return new tJ(t,{audience:n,tokenId:i})}constructor(e,t){this.prefix=e,this.data=t,this.prefix=e,this.data=t}toKey(){let{tokenId:e,audience:t}=this.data;return[this.prefix,e,t||""].join("::")}}let tK=((e=t$)=>{let t,i=new Map;return{get:(t,n=tj)=>{let r=new tJ(e,t),s=i.get(r.toKey());if(!s)return;let a=Math.floor(Date.now()/1e3)-s.createdAt;return s.expiresIn-a<(n||1)+5?void i.delete(r.toKey()):s.entry},set:n=>{let r=new tJ(e,{audience:n.audience,tokenId:n.tokenId}).toKey(),s={entry:n,createdAt:Math.floor(Date.now()/1e3)},a=()=>{i.get(r)===s&&i.delete(r)};n.tokenResolver.then(e=>{if(!e.jwt)return a();let i=e.jwt.claims.exp-e.jwt.claims.iat;s.expiresIn=i,"function"==typeof(t=setTimeout(a,1e3*i)).unref&&t.unref()}).catch(()=>{a()}),i.set(r,s)},clear:()=>{clearTimeout(t),i.clear()},size:()=>i.size}})();class tB extends tN{static instance;pathRoot="/client";sessions=[];signUp=new i7;signIn=new i6;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return tB.instance||(tB.instance=new tB(e)),tB.instance}static clearInstance(){tB.instance=null}static isClientResource(e){return!!e&&e instanceof tB}constructor(e=null){super(),this.fromJSON(e)}get signUpAttempt(){return this.signUp}get signInAttempt(){return this.signIn}get activeSessions(){return this.sessions.filter(e=>"active"===e.status)}get signedInSessions(){return this.sessions.filter(e=>"active"===e.status||"pending"===e.status)}create(){return this._basePut()}fetch({fetchMaxTries:e}={}){return this._baseGet({fetchMaxTries:e})}async destroy(){return this._baseDelete({path:"/client"}).then(()=>{tK.clear(),this.id="",this.sessions=[],this.signUp=new i7(null),this.signIn=new i6(null),this.lastActiveSessionId=null,this.cookieExpiresAt=null,this.createdAt=null,this.updatedAt=null})}removeSessions(){return this._baseDelete({path:this.path()+"/sessions"}).then(e=>(tK.clear(),e))}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return tN.fapiClient.buildUrl({method:"GET",path:"/client/touch",pathPrefix:"v1",search:{redirect_url:e.toString()}}).toString()}__internal_sendCaptchaToken(e){return this._basePostBypass({body:e,path:this.path()+"/verify"})}fromJSON(e){return e&&(this.id=e.id,this.sessions=(e.sessions||[]).map(e=>new i0(e)),this.signUp=new i7(e.sign_up),this.signIn=new i6(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?tW(e.cookie_expires_at):null,this.createdAt=tW(e.created_at||void 0),this.updatedAt=tW(e.updated_at||void 0)),this}__internal_toSnapshot(){return{object:"client",id:this.id||"",sessions:this.sessions.map(e=>e.__internal_toSnapshot()),sign_up:this.signUp.__internal_toSnapshot(),sign_in:this.signIn.__internal_toSnapshot(),last_active_session_id:this.lastActiveSessionId,captcha_bypass:this.captchaBypass,cookie_expires_at:this.cookieExpiresAt?this.cookieExpiresAt.getTime():null,created_at:this.createdAt?.getTime()??null,updated_at:this.updatedAt?.getTime()??null}}path(){return this.pathRoot}}class tV extends tN{id;externalClientSecret;externalGatewayId;paymentSource;plan;planPeriod;planPeriodStart;status;totals;isImmediatePlanChange;constructor(e,t){super(),this.fromJSON(e),this.pathRoot=t?`/organizations/${t}/commerce/checkouts`:"/me/commerce/checkouts"}fromJSON(e){return e&&(this.id=e.id,this.externalClientSecret=e.external_client_secret,this.externalGatewayId=e.external_gateway_id,this.paymentSource=e.payment_source?new tQ(e.payment_source):void 0,this.plan=new tZ(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=eP(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change),this}confirm=e=>{let{orgId:t,...i}=e;return tk(()=>this._basePatch({path:t?`/organizations/${t}/commerce/checkouts/${this.id}/confirm`:`/me/commerce/checkouts/${this.id}/confirm`,body:i}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,t){if(!L(e)||t>=4)return!1;let i=e?.status,n=409===i&&e.errors?.[0]?.code==="checkout_already_in_progress";return i>=500||n}})}}class tq extends tN{id;name;description;slug;avatarUrl;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}__internal_toSnapshot(){return{object:"commerce_feature",id:this.id,name:this.name,description:this.description,slug:this.slug,avatar_url:this.avatarUrl}}}class tH extends tN{id;status;timestamp;totals;groups;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.timestamp=tW(e.timestamp),this.totals=eP(e.totals),this.groups=e.groups.map(e=>new tG(e))),this}}class tG{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=tW(e.timestamp),this.items=e.items.map(e=>new tY(e))),this}}class tY extends tN{id;amount;failedAt;paidAt;updatedAt;paymentSource;subscription;subscriptionItem;chargeType;status;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.amount=eO(e.amount),this.paidAt=e.paid_at?tW(e.paid_at):void 0,this.failedAt=e.failed_at?tW(e.failed_at):void 0,this.updatedAt=tW(e.updated_at),this.paymentSource=new tQ(e.payment_source),this.subscription=new t1(e.subscription),this.subscriptionItem=new t1(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status),this}}class tQ extends tN{id;last4;paymentMethod;cardType;isDefault;isRemovable;status;walletType;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.last4=e.last4,this.paymentMethod=e.payment_method,this.cardType=e.card_type,this.isDefault=e.is_default,this.isRemovable=e.is_removable,this.status=e.status,this.walletType=e.wallet_type??void 0),this}async remove(e){let{orgId:t}=e??{};return new t3((await tN._fetch({path:t?`/organizations/${t}/commerce/payment_sources/${this.id}`:`/me/commerce/payment_sources/${this.id}`,method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:t}=e??{};return await tN._fetch({path:t?`/organizations/${t}/commerce/payers/default_payment_source`:"/me/commerce/payers/default_payment_source",method:"PUT",body:{payment_source_id:this.id}}),null}}class tX extends tN{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 tZ extends tN{id;name;amount;amountFormatted;annualAmount;annualAmountFormatted;annualMonthlyAmount;annualMonthlyAmountFormatted;currencySymbol;currency;description;isDefault;isRecurring;hasBaseFee;forPayerType;publiclyVisible;slug;avatarUrl;features;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.amount=e.amount,this.amountFormatted=e.amount_formatted,this.annualAmount=e.annual_amount,this.annualAmountFormatted=e.annual_amount_formatted,this.annualMonthlyAmount=e.annual_monthly_amount,this.annualMonthlyAmountFormatted=e.annual_monthly_amount_formatted,this.currencySymbol=e.currency_symbol,this.currency=e.currency,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.features=(e.features||[]).map(e=>new tq(e))),this}__internal_toSnapshot(){return{object:"commerce_plan",id:this.id,name:this.name,amount:this.amount,amount_formatted:this.amountFormatted,annual_amount:this.annualAmount,annual_amount_formatted:this.annualAmountFormatted,annual_monthly_amount:this.annualMonthlyAmount,annual_monthly_amount_formatted:this.annualMonthlyAmountFormatted,currency:this.currency,currency_symbol:this.currencySymbol,description:this.description,is_default:this.isDefault,is_recurring:this.isRecurring,has_base_fee:this.hasBaseFee,for_payer_type:this.forPayerType,publicly_visible:this.publiclyVisible,slug:this.slug,avatar_url:this.avatarUrl,features:this.features.map(e=>e.__internal_toSnapshot())}}}class t0 extends tN{id;status;activeAt;createdAt;pastDueAt;updatedAt;nextPayment=null;subscriptionItems;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.createdAt=tW(e.created_at),this.updatedAt=e.updated_at?tW(e.updated_at):null,this.activeAt=tW(e.active_at),this.pastDueAt=e.past_due_at?tW(e.past_due_at):null,this.nextPayment=e.next_payment?{amount:eO(e.next_payment.amount),date:tW(e.next_payment.date)}:null,this.subscriptionItems=(e.subscription_items||[]).map(e=>new t1(e))),this}}class t1 extends tN{id;paymentSourceId;plan;planPeriod;status;createdAt;pastDueAt;periodStartDate;periodEndDate;canceledAtDate;periodStart;periodEnd;canceledAt;amount;credit;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.paymentSourceId=e.payment_source_id,this.plan=new tZ(e.plan),this.planPeriod=e.plan_period,this.status=e.status,this.periodStart=e.period_start,this.periodEnd=e.period_end,this.canceledAt=e.canceled_at,this.createdAt=tW(e.created_at),this.pastDueAt=e.past_due_at?tW(e.past_due_at):null,this.periodStartDate=tW(e.period_start),this.periodEndDate=e.period_end?tW(e.period_end):null,this.canceledAtDate=e.canceled_at?tW(e.canceled_at):null,this.amount=e.amount?eO(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:eO(e.credit.amount)}:void 0),this}async cancel(e){let{orgId:t}=e;return new t3((await tN._fetch({path:t?`/organizations/${t}/commerce/subscription_items/${this.id}`:`/me/commerce/subscription_items/${this.id}`,method:"DELETE"}))?.response)}}class t3{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 t2 extends tN{afterCreateOrganizationUrl="";afterJoinWaitlistUrl="";afterLeaveOrganizationUrl="";afterSignInUrl="";afterSignOutAllUrl="";afterSignOutOneUrl="";afterSignOutUrl="";afterSignUpUrl="";afterSwitchSessionUrl="";applicationName="";backendHost="";branded=!1;captchaHeartbeat=!1;captchaHeartbeatIntervalMs;captchaOauthBypass=["oauth_google","oauth_microsoft","oauth_apple"];captchaProvider="turnstile";captchaPublicKey=null;captchaPublicKeyInvisible=null;captchaWidgetType=null;clerkJSVersion;createOrganizationUrl="";experimental__forceOauthFirst;faviconImageUrl="";googleOneTapClientId;homeUrl="";id="";instanceEnvironmentType="";logoImageUrl="";organizationProfileUrl="";preferredSignInStrategy="password";privacyPolicyUrl="";showDevModeWarning=!1;signInUrl="";signUpUrl="";supportEmail="";termsUrl="";theme={};userProfileUrl="";waitlistUrl="";constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.afterCreateOrganizationUrl=this.withDefault(e.after_create_organization_url,this.afterCreateOrganizationUrl),this.afterJoinWaitlistUrl=this.withDefault(e.after_join_waitlist_url,this.afterJoinWaitlistUrl),this.afterLeaveOrganizationUrl=this.withDefault(e.after_leave_organization_url,this.afterLeaveOrganizationUrl),this.afterSignInUrl=this.withDefault(e.after_sign_in_url,this.afterSignInUrl),this.afterSignOutAllUrl=this.withDefault(e.after_sign_out_all_url,this.afterSignOutAllUrl),this.afterSignOutOneUrl=this.withDefault(e.after_sign_out_one_url,this.afterSignOutOneUrl),this.afterSignUpUrl=this.withDefault(e.after_sign_up_url,this.afterSignUpUrl),this.afterSwitchSessionUrl=this.withDefault(e.after_switch_session_url,this.afterSwitchSessionUrl),this.applicationName=this.withDefault(e.application_name,this.applicationName),this.branded=this.withDefault(e.branded,this.branded),this.captchaHeartbeat=this.withDefault(e.captcha_heartbeat,this.captchaHeartbeat),this.captchaHeartbeatIntervalMs=this.withDefault(e.captcha_heartbeat_interval_ms,this.captchaHeartbeatIntervalMs),this.captchaOauthBypass=this.withDefault(e.captcha_oauth_bypass,this.captchaOauthBypass),this.captchaProvider=this.withDefault(e.captcha_provider,this.captchaProvider),this.captchaPublicKey=this.withDefault(e.captcha_public_key,this.captchaPublicKey),this.captchaPublicKeyInvisible=this.withDefault(e.captcha_public_key_invisible,this.captchaPublicKeyInvisible),this.captchaWidgetType=this.withDefault(e.captcha_widget_type,this.captchaWidgetType),this.clerkJSVersion=this.withDefault(e.clerk_js_version,this.clerkJSVersion),this.createOrganizationUrl=this.withDefault(e.create_organization_url,this.createOrganizationUrl),this.faviconImageUrl=this.withDefault(e.favicon_image_url,this.faviconImageUrl),this.googleOneTapClientId=this.withDefault(e.google_one_tap_client_id,this.googleOneTapClientId),this.homeUrl=this.withDefault(e.home_url,this.homeUrl),this.id=this.withDefault(e.id,this.id),this.instanceEnvironmentType=this.withDefault(e.instance_environment_type,this.instanceEnvironmentType),this.logoImageUrl=this.withDefault(e.logo_image_url,this.logoImageUrl),this.organizationProfileUrl=this.withDefault(e.organization_profile_url,this.organizationProfileUrl