@clerk/clerk-js 6.0.0-canary-core3.v20251203181537 → 6.0.0-snapshot.v20251203203405
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/clerk.browser.js +4 -4
- package/dist/clerk.channel.browser.js +4 -4
- package/dist/clerk.chips.browser.js +4 -4
- package/dist/clerk.headless.browser.js +4 -4
- package/dist/clerk.headless.js +2 -2
- package/dist/clerk.js +1 -1
- package/dist/clerk.legacy.browser.js +1 -1
- package/dist/clerk.mjs +1 -1
- package/dist/clerk.no-rhc.js +1 -1
- package/dist/clerk.no-rhc.mjs +1 -1
- package/dist/types/utils/errorThrower.d.ts +1 -1
- package/dist/types/utils/web3.d.ts +2 -2
- package/package.json +3 -3
- /package/dist/{308_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 308_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{415_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 415_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{507_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → 507_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{507_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → 507_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{507_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → 507_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{507_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → 507_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{507_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 507_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{507_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → 507_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{521_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 521_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{527_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → 527_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{527_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → 527_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{527_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → 527_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{527_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → 527_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{527_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → 527_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{604_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 604_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{694_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 694_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{783_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 783_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{973_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → 973_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{base-account-sdk_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → base-account-sdk_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{base-account-sdk_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → base-account-sdk_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{base-account-sdk_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → base-account-sdk_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{base-account-sdk_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → base-account-sdk_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{base-account-sdk_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → base-account-sdk_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → coinbase-wallet-sdk_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → coinbase-wallet-sdk_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → coinbase-wallet-sdk_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → coinbase-wallet-sdk_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{coinbase-wallet-sdk_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → coinbase-wallet-sdk_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{cookieSuffix_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → cookieSuffix_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{cookieSuffix_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → cookieSuffix_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{cookieSuffix_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → cookieSuffix_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{cookieSuffix_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → cookieSuffix_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{cookieSuffix_clerk.headless_035ce8_6.0.0-canary-core3.v20251203181537.js → cookieSuffix_clerk.headless_fea342_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{cookieSuffix_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → cookieSuffix_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{query-core-vendors_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → query-core-vendors_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{query-core-vendors_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → query-core-vendors_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{query-core-vendors_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → query-core-vendors_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{query-core-vendors_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → query-core-vendors_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{query-core-vendors_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → query-core-vendors_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{stripe-vendors_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → stripe-vendors_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{stripe-vendors_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → stripe-vendors_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{stripe-vendors_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → stripe-vendors_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{stripe-vendors_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → stripe-vendors_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{stripe-vendors_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → stripe-vendors_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{vendors_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → vendors_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{vendors_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → vendors_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{vendors_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → vendors_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{vendors_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → vendors_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{vendors_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → vendors_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → zxcvbn-common_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → zxcvbn-common_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → zxcvbn-common_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → zxcvbn-common_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-common_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → zxcvbn-common_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.browser_c08e29_6.0.0-canary-core3.v20251203181537.js → zxcvbn-ts-core_clerk.browser_747d7c_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.channel.browser_25749f_6.0.0-canary-core3.v20251203181537.js → zxcvbn-ts-core_clerk.channel.browser_07dda1_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.chips.browser_60d465_6.0.0-canary-core3.v20251203181537.js → zxcvbn-ts-core_clerk.chips.browser_b105ae_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.headless.browser_640a2c_6.0.0-canary-core3.v20251203181537.js → zxcvbn-ts-core_clerk.headless.browser_6dfe05_6.0.0-snapshot.v20251203203405.js} +0 -0
- /package/dist/{zxcvbn-ts-core_clerk.legacy.browser_115a20_6.0.0-canary-core3.v20251203181537.js → zxcvbn-ts-core_clerk.legacy.browser_d5034a_6.0.0-snapshot.v20251203203405.js} +0 -0
|
@@ -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={5945:function(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(6599),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,f;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))&&(f=JSON.parse(p)).id===this.id&&f.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}()},6599:function(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()}},1006:function(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)}}},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)=>{for(var i in t)s.o(t,i)&&!s.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},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.chips.browser_"+s.h().slice(0,6)+"_6.0.0-canary-core3.v20251203181537.js",s.h=()=>"60d4659a8eaa34b3",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-webpack")=="@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-webpack","@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=>{"undefined"!=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={264: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=i[0],o=i[1],l=i[2],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.webpackChunk_clerk_clerk_js=globalThis.webpackChunk_clerk_clerk_js||[]).forEach(t.bind(null,0)),i.push=t.bind(null,i.push.bind(i)),(()=>{"use strict";let e,t,i,r;try{let e=new URL(document.currentScript.src),t=new URL(e.href.split("/").slice(0,-1).join("/")).href;s.p=(t+=t.endsWith("/")?"":"/").replace(/(^.*\/@clerk\/clerk-js@)(.+?)(\/dist.*)/,"$16.0.0-canary-core3.v20251203181537$3")}catch{}function n(){return"undefined"!=typeof window}let 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 o(){var e;let t=n()?window?.navigator:null;return!!t&&!((e=t?.userAgent)&&a.test(e))&&!t?.webdriver}function l(){let e=n()?window?.navigator:null;if(!e)return!1;let t=e?.onLine;return e?.connection?.rtt!==0&&e?.connection?.downlink!==0&&t}function c(){return l()&&o()}let d=(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))},h=(e,t,i)=>(e.get(t)||[]).map(e=>e(i)),u=(e,t,i)=>{let r=e.get(t);r&&(i?r.splice(r.indexOf(i)>>>0,1):e.set(t,[]))},p=()=>{let e=new Map,t=new Map,i=new Map;return{on:(...i)=>d(e,t,...i),prioritizedOn:(...e)=>d(i,t,...e),emit:(r,n)=>{t.set(r,n),h(i,r,n),h(e,r,n)},off:(...t)=>u(e,...t),prioritizedOff:(...e)=>u(i,...e),internal:{retrieveListeners:t=>e.get(t)||[]}}},f="status";function m(e){return function(t){let i=t??this;if(!i)throw TypeError(`${e.kind||e.name} type guard requires an error object`);return i instanceof e}}var g,_,b=class{static kind="ClerkApiError";code;message;longMessage;meta;constructor(e){const t={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}};this.code=t.code,this.message=t.message,this.longMessage=t.longMessage,this.meta=t.meta}};m(b);var y=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}]
|
|
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={5945:function(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(6599),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,f;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))&&(f=JSON.parse(p)).id===this.id&&f.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}()},6599:function(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()}},1006:function(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)}}},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)=>{for(var i in t)s.o(t,i)&&!s.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},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.chips.browser_"+s.h().slice(0,6)+"_6.0.0-snapshot.v20251203203405.js",s.h=()=>"b105aeef2a252569",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-webpack")=="@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-webpack","@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=>{"undefined"!=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={264: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=i[0],o=i[1],l=i[2],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.webpackChunk_clerk_clerk_js=globalThis.webpackChunk_clerk_clerk_js||[]).forEach(t.bind(null,0)),i.push=t.bind(null,i.push.bind(i)),(()=>{"use strict";let e,t,i,r;try{let e=new URL(document.currentScript.src),t=new URL(e.href.split("/").slice(0,-1).join("/")).href;s.p=(t+=t.endsWith("/")?"":"/").replace(/(^.*\/@clerk\/clerk-js@)(.+?)(\/dist.*)/,"$16.0.0-snapshot.v20251203203405$3")}catch{}function n(){return"undefined"!=typeof window}let 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 o(){var e;let t=n()?window?.navigator:null;return!!t&&!((e=t?.userAgent)&&a.test(e))&&!t?.webdriver}function l(){let e=n()?window?.navigator:null;if(!e)return!1;let t=e?.onLine;return e?.connection?.rtt!==0&&e?.connection?.downlink!==0&&t}function c(){return l()&&o()}let d=(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))},h=(e,t,i)=>(e.get(t)||[]).map(e=>e(i)),u=(e,t,i)=>{let r=e.get(t);r&&(i?r.splice(r.indexOf(i)>>>0,1):e.set(t,[]))},p=()=>{let e=new Map,t=new Map,i=new Map;return{on:(...i)=>d(e,t,...i),prioritizedOn:(...e)=>d(i,t,...e),emit:(r,n)=>{t.set(r,n),h(i,r,n),h(e,r,n)},off:(...t)=>u(e,...t),prioritizedOff:(...e)=>u(i,...e),internal:{retrieveListeners:t=>e.get(t)||[]}}},f="status";function m(e){return function(t){let i=t??this;if(!i)throw TypeError(`${e.kind||e.name} type guard requires an error object`);return i instanceof e}}var g,_,b=class{static kind="ClerkApiError";code;message;longMessage;meta;constructor(e){const t={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}};this.code=t.code,this.message=t.message,this.longMessage=t.longMessage,this.meta=t.meta}};m(b);var y=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}")
|
|
@@ -13,6 +13,6 @@ Clerk Trace ID: ${this.clerkTraceId}`),e}static formatMessage(e,t,i,r){return t}
|
|
|
13
13
|
Consult the documentation of glob-to-regexp here: https://www.npmjs.com/package/glob-to-regexp.
|
|
14
14
|
${t.message}`)}})(eb(e)):e).some(e=>e.test(eb(r.origin))));return s||B(`Clerk: Redirect URL ${r} is not on one of the allowedRedirectOrigins, falling back to the default redirect URL.`),s}))}};let eU="__clerk_netlify_cache_bust",eA=["__clerk_status","__clerk_created_session","__clerk_invitation_token","__clerk_ticket","__clerk_modal_state","__clerk_handshake","__clerk_handshake_nonce","__clerk_help",eU,F,W,N];function eI(e){return new URL(window.location.href).searchParams.get(e)||null}function eC(e){let t=new URL(window.location.href);t.searchParams.has(e)&&(t.searchParams.delete(e),window.history.replaceState(window.history.state,"",t))}function eP(e){let t=new URLSearchParams(window.location.search),i=e||new URLSearchParams;for(let e of eA){let r=t.get(e);r&&i.set(e,r)}return i}let eO={"choose-organization":"choose-organization","reset-password":"reset-password"},eT=e=>`/tasks/${eO[e.key]}`;function eE(e,{navigate:t,baseUrl:i}){let r=e.currentTask;if(r){var n;let e;return t((n={base:i},e=eP(),eg({base:n.base,hashPath:eT(r),searchParams:e},{stringify:!0})))}}let ex=e=>`🔒 Clerk:
|
|
15
15
|
${e.trim()}
|
|
16
|
-
(This notice only appears in development)`,eR={cannotRenderComponentWhenSessionExists:"The <SignUp/> and <SignIn/> components cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the Home URL instead.",cannotRenderSignUpComponentWhenSessionExists:"The <SignUp/> component cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the value set in `afterSignUp` URL instead.",cannotRenderSignUpComponentWhenTaskExists:"The <SignUp/> component cannot render when a user has a pending task, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the task instead.",cannotRenderComponentWhenTaskDoesNotExist:"<TaskChooseOrganization/> cannot render unless a session task is pending. Clerk is redirecting to the value set in `redirectUrlComplete` instead.",cannotRenderSignInComponentWhenSessionExists:"The <SignIn/> component cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the `afterSignIn` URL instead.",cannotRenderSignInComponentWhenTaskExists:"The <SignIn/> component cannot render when a user has a pending task, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the task instead.",cannotRenderComponentWhenUserDoesNotExist:"<UserProfile/> cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotRenderComponentWhenOrgDoesNotExist:"<OrganizationProfile/> cannot render unless an organization is active. Since no organization is currently active, this is no-op.",cannotRenderAnyOrganizationComponent:e=>ex(`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=>ex(`The <${e}/> component cannot be rendered when billing is disabled. Visit 'https://dashboard.clerk.com/last-active?path=billing/settings' to follow the necessary steps to enable billing. Since billing is disabled, this is no-op.`),cannotOpenUserProfile:"The UserProfile modal cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotOpenCheckout:"The Checkout drawer cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotOpenSignInOrSignUp:"The SignIn or SignUp modals do not render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, this is no-op.",cannotRenderAPIKeysComponent:"The <APIKeys/> component cannot be rendered when API keys is disabled. Since API keys is disabled, this is no-op.",cannotRenderAPIKeysComponentForOrgWhenUnauthorized:"The <APIKeys/> component cannot be rendered for an organization unless a user has the required permissions. Since the user does not have the necessary permissions, this is no-op.",cannotRenderAPIKeysComponentForUserWhenDisabled:"The <APIKeys/> component cannot be rendered when user API keys are disabled. Since user API keys are disabled, this is no-op.",cannotRenderAPIKeysComponentForOrgWhenDisabled:"The <APIKeys/> component cannot be rendered when organization API keys are disabled. Since organization API keys are disabled, this is no-op."};for(let e of Object.keys(eR)){let t=eR[e];"function"!=typeof t&&(eR[e]=ex(t))}let ez="clerk:beforeunload",eM=["http:","https:","wails:","chrome-extension:"];function eF(e){let t=new URL(e,window.location.href);window.dispatchEvent(new CustomEvent(ez)),window.location.href=t.href}function eN(e){return/^http(s)?:\/\//.test(e||"")}function eW(e){return e.startsWith("/")}var eD=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]))}},e$=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"undefined"!=typeof window&&!!window.localStorage}},eL=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 ej=new Set(["error","warn","info","debug","trace"]);var eB=class{#f;#m;#g={};#_=[];#b=null;constructor(e){this.#f={maxBufferSize:e.maxBufferSize??5,samplingRate:e.samplingRate??1,perEventSampling:e.perEventSampling??!0,disabled:e.disabled??!1,debug:e.debug??!1,endpoint:"https://clerk-telemetry.com"},e.clerkVersion||"undefined"!=typeof window?this.#g.clerkVersion=e.clerkVersion??"":this.#g.clerkVersion="",this.#g.sdk=e.sdk,this.#g.sdkVersion=e.sdkVersion,this.#g.publishableKey=e.publishableKey??"";const t=es(e.publishableKey);t&&(this.#g.instanceType=t.instanceType),e.secretKey&&(this.#g.secretKey=e.secretKey.substring(0,16)),this.#m=new eD(e$.isSupported()?new e$:new eL)}get isEnabled(){return!("development"!==this.#g.instanceType||this.#f.disabled||"undefined"!=typeof process&&process.env&&Y(process.env.CLERK_TELEMETRY_DISABLED)||"undefined"!=typeof window&&window?.navigator?.webdriver)}get isDebug(){return this.#f.debug||"undefined"!=typeof process&&process.env&&Y(process.env.CLERK_TELEMETRY_DEBUG)}record(e){try{let t=this.#y(e.event,e.payload);if(this.#w(t.event,t),!this.#v(t,e.eventSamplingRate))return;this.#_.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&&ej.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&&"undefined"!=typeof console&&console.warn("[clerk/telemetry] Dropping invalid telemetry log entry",{levelIsValid:t,messageIsValid:i,timestampIsValid:null!==r});return}let s=this.#U(),a={sdk:s.name,sdkv:s.version,cv:this.#g.clerkVersion??"",lvl:e.level,msg:e.message,ts:r.toISOString(),pk:this.#g.publishableKey||null,payload:this.#A(e.context)};this.#_.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.#I(e,t)}#S(e){return!0}#I(e,t){let i=Math.random();return!!(i<=this.#f.samplingRate&&(!1===this.#f.perEventSampling||void 0===t||i<=t))&&!this.#m.isEventThrottled(e)}#k(){if("undefined"==typeof window)return void this.#C();if(this.#_.length>=this.#f.maxBufferSize){this.#b&&("undefined"!=typeof cancelIdleCallback?cancelIdleCallback(Number(this.#b)):clearTimeout(Number(this.#b))),this.#C();return}this.#b||("requestIdleCallback"in window?this.#b=requestIdleCallback(()=>{this.#C(),this.#b=null}):this.#b=setTimeout(()=>{this.#C(),this.#b=null},0))}#C(){let e=[...this.#_];if(this.#_=[],this.#b=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.#f.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.#f.endpoint),{headers:{"Content-Type":"application/json"},keepalive:!0,method:"POST",body:JSON.stringify({logs:i})}).catch(()=>void 0)}#w(e,t){this.isDebug&&(void 0!==console.groupCollapsed?(console.groupCollapsed("[clerk/telemetry]",e),console.log(t),console.groupEnd()):console.log("[clerk/telemetry]",e,t))}#U(){let e={name:this.#g.sdk,version:this.#g.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:r}=i.constructor.sdkMetadata;void 0!==t&&(e.name=t),void 0!==r&&(e.version=r)}}}return e}#y(e,t){let i=this.#U();return{event:e,cv:this.#g.clerkVersion??"",it:this.#g.instanceType??"",sdk:i.name,sdkv:i.version,...this.#g.publishableKey?{pk:this.#g.publishableKey}:{},...this.#g.secretKey?{sk:this.#g.secretKey}:{},payload:t}}#A(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 eJ="COMPONENT_MOUNTED",eK=new Set(["SignIn","SignUp"]);function eV(e){return function(t,i,r){return{event:e,eventSamplingRate:e===eJ?eK.has(t)?1:.1:.1,payload:{component:t,appearanceProp:!!i?.appearance,baseTheme:!!i?.appearance?.baseTheme,elements:!!i?.appearance?.elements,variables:!!i?.appearance?.variables,...r}}}}function eq(e,t,i){return eV(eJ)(e,t,i)}function eG(e,t,i){return eV("COMPONENT_OPENED")(e,t,i)}function eH(e){return"string"==typeof e?e:"object"==typeof e&&null!==e&&"name"in e&&"string"==typeof e.name?e.name:void 0}function eX(e,t,i){return"function"==typeof e?e(t):void 0!==e?e:void 0!==i?i:void 0}let eY=(...e)=>{},eQ=!1,eZ=null,e0=!1,e1=[];function e3(e,t,i,r){eQ&&(e1.push({level:e,message:t,context:i,source:r,ts:Date.now()}),e1.length>200&&e1.shift())}async function e2(e){try{if(!eQ||eZ)return;let{getDebugLogger:t}=await s.e("507").then(s.bind(s,9854)),i=await t({logLevel:e?.logLevel,telemetryCollector:e?.telemetryCollector});if(i&&(eZ=i)&&0!==e1.length){for(let e of e1){let t={...e.context||{},__preInit:!0,__preInitTs:e.ts};switch(e.level){case"error":eZ.error(e.message,t,e.source);break;case"warn":eZ.warn(e.message,t,e.source);break;case"info":eZ.info(e.message,t,e.source);break;case"debug":eZ.debug(e.message,t,e.source)}}e1.length=0}}catch(e){try{console.debug?.("Debug logger initialization failed",e)}catch{}return}}let e4={debug(e,t,i){eZ?eZ.debug(e,t,i):e3("debug",e,t,i)},error(e,t,i){eZ?eZ.error(e,t,i):e3("error",e,t,i)},info(e,t,i){eZ?eZ.info(e,t,i):e3("info",e,t,i)},warn(e,t,i){eZ?eZ.warn(e,t,i):e3("warn",e,t,i)}},e5={initialDelay:125,maxDelayBetweenRetries:0,factor:2,shouldRetry:(e,t)=>t<5,retryImmediately:!1,jitter:!0},e6=async e=>new Promise(t=>setTimeout(t,e)),e9=(e,t)=>t?e*(1+Math.random()):e,e8=async(e,t={})=>{var i;let r,n=0,{shouldRetry:s,initialDelay:a,maxDelayBetweenRetries:o,factor:l,retryImmediately:c,jitter:d,onBeforeRetry:h}={...e5,...t},u=(i={initialDelay:a,maxDelayBetweenRetries:o,factor:l,jitter:d},r=0,async()=>{let e;await e6((e=e9(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 e6(e9(100,d)):await u()}},e7=async e=>e8(e,{initialDelay:100,shouldRetry:(e,t)=>t<=3,retryImmediately:!0,factor:2});class te{#P={"@zxcvbn-ts/core":()=>e7(()=>s.e("729").then(s.bind(s,7010))),"@zxcvbn-ts/language-common":()=>e7(()=>s.e("873").then(s.bind(s,655))),"@base-org/account":()=>e7(()=>Promise.all([s.e("994"),s.e("929"),s.e("545")]).then(s.bind(s,4013))),"@coinbase/wallet-sdk":()=>e7(()=>Promise.all([s.e("994"),s.e("929"),s.e("545")]).then(s.bind(s,5537))),"@stripe/stripe-js":()=>e7(()=>s.e("279").then(s.bind(s,5608)))};import(e){return this.#P[e]?this.#P[e]():Promise.resolve(void 0)}}let tt=(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(ez,i)},stopListening:()=>{window.removeEventListener("beforeunload",i),window.removeEventListener(ez,i)},isUnloading:()=>t});return{track:async e=>{r.startListening(),await e(),r.stopListening()},isUnloading:r.isUnloading}},ti=e=>({amount:e.amount,amountFormatted:e.amount_formatted,currency:e.currency,currencySymbol:e.currency_symbol}),tr=e=>{let t={grandTotal:ti(e.grand_total),subtotal:ti(e.subtotal),taxTotal:ti(e.tax_total)};return"past_due"in e&&(t.pastDue=e.past_due?ti(e.past_due):null),"credit"in e&&(t.credit=e.credit?ti(e.credit):null),"total_due_now"in e&&(t.totalDueNow=ti(e.total_due_now)),"total_due_after_free_trial"in e&&(t.totalDueAfterFreeTrial=e.total_due_after_free_trial?ti(e.total_due_after_free_trial):null),t};function tn(e,t=""){return e.errors&&!!e.errors.find(e=>e.code===t)}let ts=function({packageName:e,customMessages:t}){let i=e;function r(e,t){if(!t)return`${i}: ${e}`;let r=e;for(let i of e.matchAll(/{{([a-zA-Z0-9-_]+)}}/g)){let e=(t[i[1]]||"").toString();r=r.replace(`{{${i[1]}}}`,e)}return`${i}: ${r}`}let n={...k,...t};return{setPackageName({packageName:e}){return"string"==typeof e&&(i=e),this},setMessages({customMessages:e}){return Object.assign(n,e||{}),this},throwInvalidPublishableKeyError(e){throw Error(r(n.InvalidPublishableKeyErrorMessage,e))},throwInvalidProxyUrl(e){throw Error(r(n.InvalidProxyUrlErrorMessage,e))},throwMissingPublishableKeyError(){throw Error(r(n.MissingPublishableKeyErrorMessage))},throwMissingSecretKeyError(){throw Error(r(n.MissingSecretKeyErrorMessage))},throwMissingClerkProviderError(e){throw Error(r(n.MissingClerkProvider,e))},throw(e){throw Error(r(e))}}}({packageName:"@clerk/clerk-js"});function ta(e){return decodeURIComponent(globalThis.atob(e.replace(/_/g,"/").replace(/-/g,"+")).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""))}function to(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(ta(r)),a={__raw:e};return Object.keys(s).forEach(e=>{a[e]=s[e]}),{encoded:{header:i,payload:r,signature:n},header:JSON.parse(ta(i)),claims:a}}function tl(){if(!n())return null;try{let e=navigator?.language;if(!e||"string"!=typeof e||""===e.trim())return null;return e}catch{return null}}function tc(){return void 0!==globalThis.document}var td=class e{#O=[];#T={metamask:"MetaMask",okx_wallet:"OKX Wallet"};static #E=null;constructor(){if("undefined"==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.#O.find(t=>t.info.name===this.#T[e])?.provider;return void 0!==t?t:window.ethereum};#x=e=>{this.#O.some(t=>t.info.uuid===e.detail.info.uuid)||this.#O.push(e.detail)}};let th=()=>(function(e){async function t(e){let{provider:t}=e,i=await h(t);if(!i)return"";let r=await i.request({method:"eth_requestAccounts"});return r&&r[0]||""}async function i(e){let{identifier:t,nonce:i,provider:r}=e,n=await h(r);return n?await n.request({method:"personal_sign",params:[`0x${i.split("").map(e=>e.charCodeAt(0).toString(16).padStart(2,"0")).join("")}`,t]}):""}async function r(){return await t({provider:"metamask"})}async function n(){return await t({provider:"coinbase_wallet"})}async function s(){return await t({provider:"okx_wallet"})}async function a(){return await t({provider:"base"})}async function o(e){return await i({...e,provider:"metamask"})}async function l(e){return await i({...e,provider:"coinbase_wallet"})}async function c(e){return await i({...e,provider:"okx_wallet"})}async function d(e){return await i({...e,provider:"base"})}async function h(t){if("coinbase_wallet"===t){let t=await e.import("@coinbase/wallet-sdk");return t?t.createCoinbaseWalletSDK({preference:{options:"all"}}).getProvider():null}if("base"===t)try{let t=await e.import("@base-org/account");if(!t)return null;return t.createBaseAccountSDK({appName:"undefined"!=typeof window&&window.Clerk?.__unstable__environment?.displayConfig?.applicationName||"undefined"!=typeof document&&document.title||"Web3 Application"}).getProvider()}catch{return null}return td.getInstance().get(t)}return{getWeb3Identifier:t,generateWeb3Signature:i,getMetamaskIdentifier:r,getCoinbaseWalletIdentifier:n,getOKXWalletIdentifier:s,getBaseIdentifier:a,generateSignatureWithMetamask:o,generateSignatureWithCoinbaseWallet:l,generateSignatureWithOKXWallet:c,generateSignatureWithBase:d}})(new te),tu="environment",tp=JSON.stringify,tf=JSON.parse;class tm{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),tp(r))}catch{}}static getItem(e,t){try{let i=window.localStorage.getItem(this._key(e));if(!i)return t;let r=tf(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 tg="ClerkJS:";function t_(e=""){throw Error(`${tg} Something went wrong initializing Clerk in development mode.${e&&` ${e}`}`)}function tb(e){throw Error(`${tg} Something went wrong initializing Clerk during the ${e} flow. Please contact support.`)}function ty(e){throw Error(`${tg} You need to start a ${e} flow by calling ${e}.create() first.`)}function tw(e,t){throw Error(`${tg} Strategy "${t}" is not a valid strategy for ${e}.`)}function tv(e){throw Error(`${tg} You need to start a ${e} flow by calling ${e}.create({ identifier: 'your web3 wallet address' }) first`)}function tk(e=""){throw Error(`${tg} Missing '${e}' option`)}function tS(e,t){throw Error(`${tg} Response: ${e||0} not supported yet.
|
|
17
|
-
For more information contact us at ${t}`)}function tU(e){throw Error(`${tg} Missing publicKey. When calling 'navigator.credentials.${e}()' it is required to pass a publicKey object.`)}async function tA(e="",t){let{async:i,defer:r,beforeLoad:n,crossOrigin:s,nonce:a}=t||{};return
|
|
18
|
-
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 w(t||a,r)}return null}static _updateClient(e){if(!e)return;let t=e.client||e.meta?.client;t&&tR.clerk&&tR.clerk.updateClient(iP.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 tR._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:r,path:n}=e,s=await tR._fetch({method:r,path:n||this.path(t),body:i});return this.fromJSON(s?.response||s)}async _baseMutateBypass(e){let{action:t,body:i,method:r,path:n}=e,s=await tR._baseFetch({method:r,path:n||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=tR.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}function tz(e){let t=new Date(e||new Date);return t instanceof Date&&!isNaN(t.getTime())?t:new Date}class tM extends tR{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?tz(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?tz(e.last_used_at):null,this.updatedAt=tz(e.updated_at),this.createdAt=tz(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 tF extends tR{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?tz(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}}}(g=_||(_={}))[g.None=0]="None",g[g.Mutable=1]="Mutable",g[g.Watching=2]="Watching",g[g.RecursedCheck=4]="RecursedCheck",g[g.Recursed=8]="Recursed",g[g.Dirty=16]="Dirty",g[g.Pending=32]="Pending";let tN=[],{link:tW,unlink:tD,propagate:t$,checkDirty:tL,endTracking:tj,startTracking:tB,shallowPropagate:tJ}=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?tQ(e):tZ(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):tN[tq++]=t}},unwatched(e){if("getter"in e){let t=e.deps;if(void 0!==t){e.flags=17;do t=tD(t,e);while(void 0!==t)}}else"previousValue"in e||t2.call(e)}}),tK=0,tV=0,tq=0;function tG(t){let i=e;return e=t,i}function tH(e){return t3.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function tX(e){return t1.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function tY(i){let r={fn:i,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==e?tW(r,e):void 0!==t&&tW(r,t);let n=tG(r);try{r.fn()}finally{tG(n)}return t2.bind(r)}function tQ(e){let t=tG(e);tB(e);try{let t=e.value;return t!==(e.value=e.getter(t))}finally{tG(t),tj(e)}}function tZ(e,t){return e.flags=1,e.previousValue!==(e.previousValue=t)}function t0(){for(;tV<tq;){let e=tN[tV];tN[tV++]=void 0,function e(t,i){if(16&i||32&i&&tL(t.deps,t)){let e=tG(t);tB(t);try{t.fn()}finally{tG(e),tj(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)}tV=0,tq=0}function t1(){let i=this.flags;if(16&i||32&i&&tL(this.deps,this)){if(tQ(this)){let e=this.subs;void 0!==e&&tJ(e)}}else 32&i&&(this.flags=-33&i);return void 0!==e?tW(this,e):void 0!==t&&tW(this,t),this.value}function t3(...t){if(t.length){let e=t[0];if(this.value!==(this.value=e)){this.flags=17;let e=this.subs;void 0!==e&&(t$(e),tK||t0())}}else{let t=this.value;if(16&this.flags&&tZ(this,t)){let e=this.subs;void 0!==e&&tJ(e)}return void 0!==e&&tW(this,e),t}}function t2(){let e=this.deps;for(;void 0!==e;)e=tD(e,this);let t=this.subs;void 0!==t&&tD(t),this.flags=0}function t4(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 t5{static #R="/billing";static path(e,t){let{orgId:i}=t||{},r=i?`/organizations/${i}`:"/me";return`${r}${t5.#R}${e}`}getPlans=async e=>{let{for:t,...i}=e||{},r={...i,payer_type:"organization"===t?"org":"user"};return await tR._fetch({path:`${t5.#R}/plans`,method:"GET",search:t4(r)}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new i_(e))}})};getPlan=async e=>new i_(await tR._fetch({path:`${t5.#R}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await tR._fetch({path:t5.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new iw(e?.response));getStatements=async e=>{let{orgId:t,...i}=e;return await tR._fetch({path:t5.path("/statements",{orgId:t}),method:"GET",search:t4(i)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new ib(e))}})};getStatement=async e=>new ib((await tR._fetch({path:t5.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:t,...i}=e;return await tR._fetch({path:t5.path("/payment_attempts",{orgId:t}),method:"GET",search:t4(i)}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new ic(e))}})};getPaymentAttempt=async e=>new ic(await tR._fetch({path:t5.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:t,...i}=e;return new io((await tR._fetch({path:t5.path("/checkouts",{orgId:t}),method:"POST",body:i}))?.response)}}let t6=tH({resource:null}),t9=tH({error:null}),t8=tH({status:"idle"}),t7=tX(()=>{let e=t6().resource,t=t9().error,i=t8().status;return{errors:is(t,{identifier:null,password:null,code:null}),fetchStatus:i,signIn:e?e.__internal_future:null}}),ie=tH({resource:null}),it=tH({error:null}),ii=tH({status:"idle"}),ir=tX(()=>{let e=ie().resource,t=it().error,i=ii().status;return{errors:is(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}});function is(e,t){let i={fields:{...t},raw:null,global:null};if(!e)return i;if(!O(e))return i.raw=[e],i.global=[E(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=V(e.meta.paramName);t in i.fields&&(i.fields[t]=e)}}):(i.raw=[e],i.global=[E(e)]),i}class ia extends tR{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=tz(e.created_at)),e.updated_at&&(this.updatedAt=tz(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 io extends tR{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 im(e.payment_method):void 0,this.plan=new i_(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=tr(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change,e.free_trial_ends_at&&(this.freeTrialEndsAt=tz(e.free_trial_ends_at)),this.payer=new ia(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>e8(()=>this._basePatch({path:t5.path(`/checkouts/${this.id}/confirm`,{orgId:this.payer.organizationId}),body:e}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,t){if(!O(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 il{resource=new io(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 io.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new io(null),this.signals.resourceSignal({resource:this})})}async confirm(e){if(!this.resource.id)throw Error("Clerk: `start()` must be called before `confirm()`");return this.runAsyncCheckoutTask("confirm",async()=>{await this.resource.confirm(e)})}async finalize(e){let{navigate:t}=e||{};return this.runAsyncCheckoutTask("finalize",async()=>{if("completed"!==this.resource.status)throw Error("Clerk: `confirm()` must be called before `finalize()`");await io.clerk.setActive({session:io.clerk.session?.id,navigate:t})})}runAsyncCheckoutTask(e,t,i){var r,n,s;return void 0===io.clerk.user?(console.warn("Clerk: Checkout operations cannot be performed during transitive state"),{error:null}):(r=this,n=this.signals,s=this.pendingOperations,async(e,t,i)=>{if(s.get(e))return s.get(e);let a=(async()=>{++tK,n.errorSignal({error:null}),n.fetchSignal({status:"fetching"}),i?.(),--tK||t0(),++tK;try{return await t(),n.resourceSignal({resource:r}),{error:null}}catch(e){return n.errorSignal({error:e}),{error:e}}finally{s.delete(e),n.fetchSignal({status:"idle"}),--tK||t0()}})();return s.set(e,a),a})(e,t,i)}}class ic extends tR{id;amount;failedAt=null;paidAt=null;updatedAt;paymentMethod=null;subscriptionItem;chargeType;status;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.amount=ti(e.amount),this.paidAt=e.paid_at?tz(e.paid_at):null,this.failedAt=e.failed_at?tz(e.failed_at):null,this.updatedAt=tz(e.updated_at),this.paymentMethod=e.payment_method?new im(e.payment_method):null,this.subscriptionItem=new iv(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status),this}}let id="/payment_methods",ih=async e=>{let{orgId:t,...i}=e;return new ig((await tR._fetch({path:t5.path(`${id}/initialize`,{orgId:t}),method:"POST",body:i}))?.response)},iu=async e=>{let{orgId:t,...i}=e;return new im((await tR._fetch({path:t5.path(id,{orgId:t}),method:"POST",body:i}))?.response)},ip=async e=>{let{orgId:t,...i}=e??{};return await tR._fetch({path:t5.path(id,{orgId:t}),method:"GET",search:t4(i)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new im(e))}})};class im extends tR{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:tz(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:tz(e.updated_at)),this}async remove(e){let{orgId:t}=e??{};return new iT((await tR._fetch({path:t5.path(`/payment_methods/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:t}=e??{};return await tR._fetch({path:t5.path("/payers/default_payment_method",{orgId:t}),method:"PUT",body:{payment_method_id:this.id}}),null}}class ig extends tR{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 i_ extends tR{id;name;fee;annualFee=null;annualMonthlyFee=null;description=null;isDefault;isRecurring;hasBaseFee;forPayerType;publiclyVisible;slug;avatarUrl=null;features;freeTrialDays;freeTrialEnabled;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.fee=ti(e.fee),this.annualFee=e.annual_fee?ti(e.annual_fee):null,this.annualMonthlyFee=e.annual_monthly_fee?ti(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 i8(e))),this}}class ib extends tR{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=tz(e.timestamp),this.totals=tr(e.totals),this.groups=e.groups.map(e=>new iy(e))),this}}class iy{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=tz(e.timestamp),this.items=e.items.map(e=>new ic(e))),this}}class iw extends tR{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=tz(e.created_at),this.updatedAt=e.updated_at?tz(e.updated_at):null,this.activeAt=tz(e.active_at),this.pastDueAt=e.past_due_at?tz(e.past_due_at):null,e.next_payment&&(this.nextPayment={amount:ti(e.next_payment.amount),date:tz(e.next_payment.date)}),this.subscriptionItems=(e.subscription_items||[]).map(e=>new iv(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1)),this}}class iv extends tR{id;plan;planPeriod;status;createdAt;periodStart;periodEnd;canceledAt;pastDueAt;amount;credit;isFreeTrial;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.plan=new i_(e.plan),this.planPeriod=e.plan_period,this.status=e.status,this.createdAt=tz(e.created_at),this.pastDueAt=e.past_due_at?tz(e.past_due_at):null,this.periodStart=tz(e.period_start),this.periodEnd=e.period_end?tz(e.period_end):null,this.canceledAt=e.canceled_at?tz(e.canceled_at):null,this.amount=e.amount?ti(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:ti(e.credit.amount)}:void 0,this.isFreeTrial=this.withDefault(e.is_free_trial,!1)),this}async cancel(e){let{orgId:t}=e;return new iT((await tR._fetch({path:t5.path(`/subscription_items/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}}let ik={build:(e,t,i)=>[e,t,i].filter(Boolean).join("-"),parse:(e,t,i)=>{let r=ik.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}},iS="clerk",iU=10,iA={broadcast:!0};class iI{prefix;data;static fromKey(e){let[t,i,r=""]=e.split("::");return new iI(t,{audience:r,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 iC=((e=iS)=>{let t=new Map,i=Math.random().toString(36).slice(2),r=null;return{clear:()=>{t.forEach(e=>{void 0!==e.timeoutId&&clearTimeout(e.timeoutId)}),t.clear()},close:()=>{r&&(r.close(),r=null)},get:(i,r=iU)=>{let n=new iI(e,i),s=t.get(n.toKey());if(!s)return;let a=Math.floor(Date.now()/1e3)-s.createdAt;if(s.expiresIn-a<(r||1)+5){void 0!==s.timeoutId&&clearTimeout(s.timeoutId),t.delete(n.toKey());return}return s.entry},set:n=>{((n,s=iA)=>{let a=new iI(e,{audience:n.audience,tokenId:n.tokenId}).toKey(),o=Math.floor(Date.now()/1e3),l={createdAt:n.createdAt??o,entry:n,expiresIn:void 0},c=()=>{let e=t.get(a);e===l&&(void 0!==e.timeoutId&&clearTimeout(e.timeoutId),t.delete(a))};n.tokenResolver.then(e=>{let t=e.jwt?.claims;if(!t||"number"!=typeof t.exp||"number"!=typeof t.iat)return c();let a=t.exp-t.iat;l.expiresIn=a;let o=setTimeout(c,1e3*a);l.timeoutId=o,"function"==typeof o.unref&&o.unref();let d=r;if(d&&s.broadcast){let r=e.getRawString();if(r&&t.sid){let e=t.sid,s=t.org_id||t.o?.id,a=ik.extractTemplate(n.tokenId,e,s),o=ik.build(e,a,s);if(n.tokenId===o){let t=`bc_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;e4.info("Broadcasting token update to other tabs",{organizationId:s,sessionId:e,tabId:i,template:a,tokenId:n.tokenId,traceId:t},"tokenCache");let o={organizationId:s,sessionId:e,template:a,tokenId:n.tokenId,tokenRaw:r,traceId:t};d.postMessage(o)}}}}).catch(()=>{c()}),t.set(a,l)})(n,iA)},size:()=>t.size}})();class iP extends tR{static instance;pathRoot="/client";sessions=[];signUp=new rz;signIn=new rE;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return iP.instance||(iP.instance=new iP(e)),iP.instance}static clearInstance(){iP.instance=null}static isClientResource(e){return!!e&&e instanceof iP}constructor(e=null){super(),this.fromJSON(e)}get signUpAttempt(){return this.signUp}get signInAttempt(){return this.signIn}get signedInSessions(){return this.sessions.filter(e=>"active"===e.status||"pending"===e.status)}create(){return this._basePut()}fetch({fetchMaxTries:e}={}){return this._baseGet({fetchMaxTries:e})}async destroy(){return this._baseDelete({path:"/client"}).then(()=>{iC.clear(),this.id="",this.sessions=[],this.signUp=new rz(null),this.signIn=new rE(null),this.lastActiveSessionId=null,this.lastAuthenticationStrategy=null,this.cookieExpiresAt=null,this.createdAt=null,this.updatedAt=null})}removeSessions(){return this._baseDelete({path:this.path()+"/sessions"}).then(e=>(iC.clear(),e))}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return tR.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 rk(e)),this.signUp=new rz(e.sign_up),this.signIn=new rE(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?tz(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=tz(e.created_at||void 0),this.updatedAt=tz(e.updated_at||void 0)),this}__internal_toSnapshot(){return{object:"client",id:this.id||"",sessions:this.sessions.map(e=>e.__internal_toSnapshot()),sign_up:this.signUp.__internal_toSnapshot(),sign_in:this.signIn.__internal_toSnapshot(),last_active_session_id:this.lastActiveSessionId,captcha_bypass:this.captchaBypass,cookie_expires_at:this.cookieExpiresAt?this.cookieExpiresAt.getTime():null,last_authentication_strategy:this.lastAuthenticationStrategy??null,created_at:this.createdAt?.getTime()??null,updated_at:this.updatedAt?.getTime()??null}}path(){return this.pathRoot}}class iO extends tR{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 iT{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 iE extends tR{afterCreateOrganizationUrl="";afterJoinWaitlistUrl="";afterLeaveOrganizationUrl="";afterSignInUrl="";afterSignOutAllUrl="";afterSignOutOneUrl="";afterSignOutUrl="";afterSignUpUrl="";afterSwitchSessionUrl="";applicationName="";backendHost="";branded=!1;captchaHeartbeat=!1;captchaHeartbeatIntervalMs;captchaOauthBypass=["oauth_google","oauth_microsoft","oauth_apple"];captchaProvider="turnstile";captchaPublicKey=null;captchaPublicKeyInvisible=null;captchaWidgetType=null;clerkJSVersion;createOrganizationUrl="";experimental__forceOauthFirst;faviconImageUrl="";googleOneTapClientId;homeUrl="";id="";instanceEnvironmentType="";logoImageUrl="";organizationProfileUrl="";preferredSignInStrategy="password";privacyPolicyUrl="";showDevModeWarning=!1;signInUrl="";signUpUrl="";supportEmail="";termsUrl="";theme={};userProfileUrl="";waitlistUrl="";constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.afterCreateOrganizationUrl=this.withDefault(e.after_create_organization_url,this.afterCreateOrganizationUrl),this.afterJoinWaitlistUrl=this.withDefault(e.after_join_waitlist_url,this.afterJoinWaitlistUrl),this.afterLeaveOrganizationUrl=this.withDefault(e.after_leave_organization_url,this.afterLeaveOrganizationUrl),this.afterSignInUrl=this.withDefault(e.after_sign_in_url,this.afterSignInUrl),this.afterSignOutAllUrl=this.withDefault(e.after_sign_out_all_url,this.afterSignOutAllUrl),this.afterSignOutOneUrl=this.withDefault(e.after_sign_out_one_url,this.afterSignOutOneUrl),this.afterSignUpUrl=this.withDefault(e.after_sign_up_url,this.afterSignUpUrl),this.afterSwitchSessionUrl=this.withDefault(e.after_switch_session_url,this.afterSwitchSessionUrl),this.applicationName=this.withDefault(e.application_name,this.applicationName),this.branded=this.withDefault(e.branded,this.branded),this.captchaHeartbeat=this.withDefault(e.captcha_heartbeat,this.captchaHeartbeat),this.captchaHeartbeatIntervalMs=this.withDefault(e.captcha_heartbeat_interval_ms,this.captchaHeartbeatIntervalMs),this.captchaOauthBypass=this.withDefault(e.captcha_oauth_bypass,this.captchaOauthBypass),this.captchaProvider=this.withDefault(e.captcha_provider,this.captchaProvider),this.captchaPublicKey=this.withDefault(e.captcha_public_key,this.captchaPublicKey),this.captchaPublicKeyInvisible=this.withDefault(e.captcha_public_key_invisible,this.captchaPublicKeyInvisible),this.captchaWidgetType=this.withDefault(e.captcha_widget_type,this.captchaWidgetType),this.clerkJSVersion=this.withDefault(e.clerk_js_version,this.clerkJSVersion),this.createOrganizationUrl=this.withDefault(e.create_organization_url,this.createOrganizationUrl),this.faviconImageUrl=this.withDefault(e.favicon_image_url,this.faviconImageUrl),this.googleOneTapClientId=this.withDefault(e.google_one_tap_client_id,this.googleOneTapClientId),this.homeUrl=this.withDefault(e.home_url,this.homeUrl),this.id=this.withDefault(e.id,this.id),this.instanceEnvironmentType=this.withDefault(e.instance_environment_type,this.instanceEnvironmentType),this.logoImageUrl=this.withDefault(e.logo_image_url,this.logoImageUrl),this.organizationProfileUrl=this.withDefault(e.organization_profile_url,this.organizationProfileUrl),this.preferredSignInStrategy=this.withDefault(e.preferred_sign_in_strategy,this.preferredSignInStrategy),this.privacyPolicyUrl=this.withDefault(e.privacy_policy_url,this.privacyPolicyUrl),this.showDevModeWarning=this.withDefault(e.show_devmode_warning,this.showDevModeWarning),this.signInUrl=this.withDefault(e.sign_in_url,this.signInUrl),this.signUpUrl=this.withDefault(e.sign_up_url,this.signUpUrl),this.supportEmail=this.withDefault(e.support_email,this.supportEmail),this.termsUrl=this.withDefault(e.terms_url,this.termsUrl),this.theme=this.withDefault(e.theme,this.theme),this.userProfileUrl=this.withDefault(e.user_profile_url,this.userProfileUrl),this.waitlistUrl=this.withDefault(e.waitlist_url,this.waitlistUrl)),this}__internal_toSnapshot(){return{object:"display_config",after_create_organization_url:this.afterCreateOrganizationUrl,after_join_waitlist_url:this.afterJoinWaitlistUrl,after_leave_organization_url:this.afterLeaveOrganizationUrl,after_sign_in_url:this.afterSignInUrl,after_sign_out_all_url:this.afterSignOutAllUrl,after_sign_out_one_url:this.afterSignOutOneUrl,after_sign_up_url:this.afterSignUpUrl,after_switch_session_url:this.afterSwitchSessionUrl,application_name:this.applicationName,branded:this.branded,captcha_heartbeat_interval_ms:this.captchaHeartbeatIntervalMs,captcha_heartbeat:this.captchaHeartbeat,captcha_oauth_bypass:this.captchaOauthBypass,captcha_provider:this.captchaProvider,captcha_public_key_invisible:this.captchaPublicKeyInvisible,captcha_public_key:this.captchaPublicKey,captcha_widget_type:this.captchaWidgetType,clerk_js_version:this.clerkJSVersion,create_organization_url:this.createOrganizationUrl,favicon_image_url:this.faviconImageUrl,google_one_tap_client_id:this.googleOneTapClientId,home_url:this.homeUrl,id:this.id,instance_environment_type:this.instanceEnvironmentType,logo_image_url:this.logoImageUrl,organization_profile_url:this.organizationProfileUrl,preferred_sign_in_strategy:this.preferredSignInStrategy,privacy_policy_url:this.privacyPolicyUrl,show_devmode_warning:this.showDevModeWarning,sign_in_url:this.signInUrl,sign_up_url:this.signUpUrl,support_email:this.supportEmail,terms_url:this.termsUrl,theme:this.theme,user_profile_url:this.userProfileUrl,waitlist_url:this.waitlistUrl}}}var ix='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 iR=(e,t={})=>{if("undefined"==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}},iz=()=>{let e=0,t=()=>e++,i=new Map,r=(e,t)=>e?.postMessage(t),n=e=>{i.get(e.data.id)?.()},s=iR(ix,{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:eY};let a=()=>{s||(s=iR(ix,{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 iM({delayInMs:e}={delayInMs:1e3}){let t,i=iz(),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 iF extends tR{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",body:{...e}});attemptVerification=e=>{let{code:t}=e||{};return this._basePost({action:"attempt_verification",body:{code:t}})};createEmailLinkFlow=()=>{let{run:e,stop:t}=iM();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}=iM();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 iq(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new i7(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 iN=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 iW(e){try{let t=await navigator.credentials.create({publicKey:e});if(!t)return{error:new I("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 I(t.message,{code:"passkey_already_exists"}):"NotAllowedError"===t.name?new I(t.message,{code:"passkey_registration_cancelled"}):iL(t),publicKeyCredential:null}}}let iD=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 i$({publicKeyOptions:e,conditionalUI:t}){try{let i=await navigator.credentials.get({publicKey:e,mediation:t?"conditional":"optional",signal:iD.createAbortSignal()});if(!i)return{error:new I("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 I(i.message,{code:"passkey_retrieval_cancelled"}):iL(i),publicKeyCredential:null}}}function iL(e){return"AbortError"===e.name?new I(e.message,{code:"passkey_operation_aborted"}):"SecurityError"===e.name?new I(e.message,{code:"passkey_invalid_rpID_or_domain"}):e}function ij(e){let t=iV(e.challenge),i=(e.allowCredentials||[]).map(e=>({...e,id:iV(e.id)}));return{...e,allowCredentials:i,challenge:t}}function iB(e){return{type:e.type,id:e.id,rawId:iK(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function iJ(e){let t=e.response;return{...iB(e),response:{clientDataJSON:iK(t.clientDataJSON),authenticatorData:iK(t.authenticatorData),signature:iK(t.signature),userHandle:t.userHandle?iK(t.userHandle):null}}}let iK=iN.encode.bind(iN),iV=iN.decode.bind(iN);class iq extends tR{pathRoot="";status=null;strategy=null;nonce=null;message=null;externalVerificationRedirectURL=null;attempts=null;expireAt=null;error=null;verifiedAtClient=null;channel;constructor(e){super(),this.fromJSON(e)}verifiedFromTheSameClient=()=>this.verifiedAtClient===tR.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=tz(e.expire_at||void 0),this.error=e.error?new b(e.error):null,this.channel=e.channel||void 0),this}__internal_toSnapshot(){var e;return{object:"verification",id:this.id||"",status:this.status,strategy:this.strategy,nonce:this.nonce,message:this.message,external_verification_redirect_url:this.externalVerificationRedirectURL?.toString()||null,attempts:this.attempts,expire_at:this.expireAt?.getTime()||null,error:(e=this.error,{code:e?.code||"",message:e?.message||"",long_message:e?.longMessage,meta:{param_name:e?.meta?.paramName,session_id:e?.meta?.sessionId,email_addresses:e?.meta?.emailAddresses,identifiers:e?.meta?.identifiers,zxcvbn:e?.meta?.zxcvbn,plan:e?.meta?.plan,is_plan_upgrade_possible:e?.meta?.isPlanUpgradePossible}}),verified_at_client:this.verifiedAtClient}}}class iG extends iq{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=iV((t=JSON.parse(e.nonce)).user.id),r=iV(t.challenge),n=(t.excludeCredentials||[]).map(e=>({...e,id:iV(e.id)})),{...t,excludeCredentials:n,challenge:r,user:{...t.user,id:i}})),this}}class iH{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new iX(e.email_address),this.phoneNumber=new iX(e.phone_number),this.web3Wallet=new iX(e.web3_wallet),this.externalAccount=new iq(e.external_account)):(this.emailAddress=new iX(null),this.phoneNumber=new iX(null),this.web3Wallet=new iX(null),this.externalAccount=new iq(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 iX extends iq{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 iY extends tR{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?tz(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new iq(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new iQ(e.enterprise_connection))),this}__internal_toSnapshot(){return{object:"enterprise_account",id:this.id,provider:this.provider,protocol:this.protocol,provider_user_id:this.providerUserId,active:this.active,email_address:this.emailAddress,first_name:this.firstName,last_name:this.lastName,public_metadata:this.publicMetadata,verification:this.verification?.__internal_toSnapshot()||null,enterprise_connection:this.enterpriseConnection?.__internal_toSnapshot()||null,last_authenticated_at:this.lastAuthenticatedAt?this.lastAuthenticatedAt.getTime():null,enterprise_connection_id:this.enterpriseConnectionId}}}class iQ extends tR{id;active;allowIdpInitiated;allowSubdomains;disableAdditionalIdentifications;domain;logoPublicUrl="";name;protocol;provider;syncUserAttributes;createdAt;updatedAt;enterpriseConnectionId="";constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.domain=e.domain,this.active=e.active,this.provider=e.provider,this.logoPublicUrl=e.logo_public_url,this.syncUserAttributes=e.sync_user_attributes,this.allowSubdomains=e.allow_subdomains,this.allowIdpInitiated=e.allow_idp_initiated,this.disableAdditionalIdentifications=e.disable_additional_identifications,this.createdAt=tz(e.created_at),this.updatedAt=tz(e.updated_at),this.enterpriseConnectionId=e.enterprise_connection_id),this}__internal_toSnapshot(){return{object:"enterprise_account_connection",id:this.id,name:this.name,domain:this.domain,active:this.active,protocol:this.protocol,provider:this.provider,logo_public_url:this.logoPublicUrl,sync_user_attributes:this.syncUserAttributes,allow_subdomains:this.allowSubdomains,allow_idp_initiated:this.allowIdpInitiated,disable_additional_identifications:this.disableAdditionalIdentifications,enterprise_connection_id:this.enterpriseConnectionId,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}let iZ="token:update",i0="user:signOut",i1="environment:update",i3="session:tokenResolved",i2=p();class i4 extends tR{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 i5 extends tR{actions={adminDelete:!1};domains={enabled:!1,enrollmentModes:[],defaultRole:null};slug={disabled:!1};enabled=!1;maxAllowedMemberships=1;forceOrganizationSelection;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(e.actions&&(this.actions.adminDelete=this.withDefault(e.actions.admin_delete,this.actions.adminDelete)),e.domains&&(this.domains.enabled=this.withDefault(e.domains.enabled,this.domains.enabled),this.domains.enrollmentModes=this.withDefault(e.domains.enrollment_modes,this.domains.enrollmentModes),this.domains.defaultRole=this.withDefault(e.domains.default_role,this.domains.defaultRole)),e.slug&&(this.slug.disabled=this.withDefault(e.slug.disabled,this.slug.disabled)),this.enabled=this.withDefault(e.enabled,this.enabled),this.maxAllowedMemberships=this.withDefault(e.max_allowed_memberships,this.maxAllowedMemberships),this.forceOrganizationSelection=this.withDefault(e.force_organization_selection,this.forceOrganizationSelection)),this}__internal_toSnapshot(){return{actions:{admin_delete:this.actions.adminDelete},domains:{enabled:this.domains.enabled,enrollment_modes:this.domains.enrollmentModes,default_role:this.domains.defaultRole},enabled:this.enabled,max_allowed_memberships:this.maxAllowedMemberships}}}class i6 extends tR{static instance;authConfig=new tF;displayConfig=new iE;maintenanceMode=!1;clientDebugMode=!1;pathRoot="/environment";userSettings=new rJ;organizationSettings=new i5;commerceSettings=new iO;apiKeysSettings=new i4;protectConfig=new rf;static getInstance(){return i6.instance||(i6.instance=new i6),i6.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new tF(e.auth_config),this.displayConfig=new iE(e.display_config),this.maintenanceMode=this.withDefault(e.maintenance_mode,this.maintenanceMode),this.clientDebugMode=this.withDefault(e.client_debug_mode,this.clientDebugMode),this.organizationSettings=new i5(e.organization_settings),this.userSettings=new rJ(e.user_settings),this.commerceSettings=new iO(e.commerce_settings),this.apiKeysSettings=new i4(e.api_keys_settings),this.protectConfig=new rf(e.protect_config)),this}fetch({touch:e,fetchMaxTries:t}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:t})).then(e=>(i2.emit(i1,null),e))}isDevelopmentOrStaging=()=>!this.isProduction();isProduction=()=>"production"===this.displayConfig.instanceEnvironmentType;isSingleSession=()=>this.authConfig.singleSessionMode;onWindowLocationHost=()=>this.displayConfig.backendHost===window.location.host;__internal_toSnapshot(){return{object:"environment",auth_config:this.authConfig.__internal_toSnapshot(),display_config:this.displayConfig.__internal_toSnapshot(),id:this.id??"",maintenance_mode:this.maintenanceMode,client_debug_mode:this.clientDebugMode,organization_settings:this.organizationSettings.__internal_toSnapshot(),user_settings:this.userSettings.__internal_toSnapshot(),commerce_settings:this.commerceSettings.__internal_toSnapshot(),api_keys_settings:this.apiKeysSettings.__internal_toSnapshot(),protect_config:this.protectConfig.__internal_toSnapshot()}}}class i9 extends tR{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}=e||{};return this._basePatch({action:"reauthorize",body:{additional_scope:t,redirect_url:i}})};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 iq(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 i8 extends tR{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 i7 extends tR{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 re extends tR{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 re((await tR._fetch({path:e,method:"POST",body:r,headers:i}))?.response)}static async delete(e){return new re((await tR._fetch({path:e,method:"DELETE"}))?.response)}constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.publicUrl=e.public_url),this}}class rt extends tR{id;name;organizationId;enrollmentMode;verification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:t}){return new rt((await tR._fetch({path:`/organizations/${e}/domains`,method:"POST",body:{name:t}}))?.response)}prepareAffiliationVerification=async e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/prepare_affiliation_verification`,method:"POST",body:e});attemptAffiliationVerification=async e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/attempt_affiliation_verification`,method:"POST",body:e});updateEnrollmentMode=e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/update_enrollment_mode`,body:e});delete=()=>this._baseDelete({path:`/organizations/${this.organizationId}/domains/${this.id}`});fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.organizationId=e.organization_id,this.enrollmentMode=e.enrollment_mode,this.affiliationEmailAddress=e.affiliation_email_address,this.totalPendingSuggestions=e.total_pending_suggestions,this.totalPendingInvitations=e.total_pending_invitations,e.verification?this.verification={status:e.verification.status,strategy:e.verification.strategy,attempts:e.verification.attempts,expiresAt:tz(e.verification.expires_at)}:this.verification=null),this}}class ri extends tR{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=tz(e.created_at),this.updatedAt=tz(e.updated_at),e.public_user_data&&(this.publicUserData=new rm(e.public_user_data))),this}}class rr extends tR{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=tz(e.created_at),this.updatedAt=tz(e.updated_at)),this}}class rn extends tR{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 rr(e)),this.createdAt=tz(e.created_at),this.updatedAt=tz(e.updated_at)),this}}class rs extends tR{pathRoot="/organizations";id;name;slug;imageUrl;hasImage;publicMetadata={};adminDeleteEnabled;createdAt;updatedAt;membersCount=0;pendingInvitationsCount=0;maxAllowedMemberships;constructor(e){super(),this.fromJSON(e)}static async create(e){return new rs((await tR._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new rs((await tR._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await tR._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:t4(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new rn(e))}});getDomains=async e=>await tR._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:t4(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new rt(e))}});getDomain=async({domainId:e})=>new rt((await tR._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getMembershipRequests=async e=>await tR._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:t4(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new ri(e))}});createDomain=async e=>rt.create(this.id,{name:e});getMemberships=async e=>await tR._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:t4({...e,paginated:!0})}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new ro(e))}});getInvitations=async e=>await tR._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:t4(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new ra(e))}});addMember=async({userId:e,role:t})=>await tR._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:t}}).then(e=>new ro(e?.response));inviteMember=async e=>ra.create(this.id,e);inviteMembers=async e=>ra.createBulk(this.id,e);updateMember=async({userId:e,role:t})=>await tR._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:t}}).then(e=>new ro(e?.response));removeMember=async e=>await tR._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new ro(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let t,i;return null===e?await tR._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new rs(e?.response)):("string"==typeof e?(t=e,i=new Headers({"Content-Type":"application/octet-stream"})):(t=new FormData).append("file",e),await tR._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:t,headers:i}).then(e=>new rs(e?.response)))};initializePaymentMethod=e=>ih({...e,orgId:this.id});addPaymentMethod=e=>iu({...e,orgId:this.id});getPaymentMethods=e=>ip({...e,orgId:this.id});fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.slug=e.slug,this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.publicMetadata=e.public_metadata||{},this.membersCount=e.members_count||0,this.pendingInvitationsCount=e.pending_invitations_count||0,this.maxAllowedMemberships=e.max_allowed_memberships||0,this.adminDeleteEnabled=e.admin_delete_enabled||!1,this.createdAt=tz(e.created_at),this.updatedAt=tz(e.updated_at)),this}__internal_toSnapshot(){return{object:"organization",id:this.id,name:this.name,slug:this.slug,image_url:this.imageUrl,has_image:this.hasImage,public_metadata:this.publicMetadata,members_count:this.membersCount,pending_invitations_count:this.pendingInvitationsCount,max_allowed_memberships:this.maxAllowedMemberships,admin_delete_enabled:this.adminDeleteEnabled,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}async reload(e){let{rotatingTokenNonce:t}=e||{},i=(await tR._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:t},{forceUpdateClient:!0}))?.response;return this.fromJSON(i)}}class ra extends tR{id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:t,role:i}){return new ra((await tR._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 tR._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:i,role:r}}))?.response).map(e=>new ra(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=tz(e.created_at),this.updatedAt=tz(e.updated_at)),this}}class ro extends tR{id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await tR._fetch({path:"/me/organization_memberships",method:"GET",search:t4({...e,paginated:!0})}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new ro(e))}});destroy=async()=>await this._baseDelete({path:`/organizations/${this.organization.id}/memberships/${this.publicUserData?.userId}`});update=async({role:e})=>await this._basePatch({path:`/organizations/${this.organization.id}/memberships/${this.publicUserData?.userId}`,body:{role:e}});fromJSON(e){return e&&(this.id=e.id,this.organization=new rs(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new rm(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=tz(e.created_at),this.updatedAt=tz(e.updated_at)),this}__internal_toSnapshot(){return{object:"organization_membership",id:this.id,organization:this.organization.__internal_toSnapshot(),public_metadata:this.publicMetadata,public_user_data:this.publicUserData?.__internal_toSnapshot(),permissions:this.permissions,role:this.role,role_name:this.roleName,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}reload(e){throw Error(`${tg} Calling OrganizationMembership.reload is not currently supported. Please contact support.`)}}class rl extends tR{id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await tR._fetch({path:"/me/organization_suggestions",method:"GET",search:t4(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new rl(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=tz(e.created_at),this.updatedAt=tz(e.updated_at)),this}}function rc(){return o()&&"function"==typeof window.PublicKeyCredential}async function rd(){try{return rc()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function rh(){try{return"undefined"!=typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class ru extends tR{id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return tR._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new ru(e?.response))}static async attemptVerification(e,t){let i,r=(i=t.response,{...iB(t),response:{clientDataJSON:iK(i.clientDataJSON),attestationObject:iK(i.attestationObject),transports:i.getTransports()}});return tR._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(r)}}).then(e=>new ru(e?.response))}static async registerPasskey(){let e=ru.clerk.__internal_isWebAuthnSupported||rc,t=ru.clerk.__internal_createPublicCredentials||iW,i=ru.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||rh;if(!e())throw new I("Passkeys are not supported on this device.",{code:"passkey_not_supported"});let r=await this.create(),{verification:n}=r,s=n?.publicKey;if(s||tU("create"),s.authenticatorSelection?.authenticatorAttachment==="platform"&&!await i())throw new I("Registration requires a platform authenticator but the device does not support it.",{code:"passkey_pa_not_supported"});let{publicKeyCredential:a,error:o}=await t(s);if(!a)throw o;return this.attemptVerification(r.id,a)}update=e=>this._basePatch({body:e});delete=async()=>new iT((await tR._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?tz(e.last_used_at):null,this.createdAt=tz(e.created_at),this.updatedAt=tz(e.updated_at),e.verification&&(this.verification=new iG(e.verification))),this}__internal_toSnapshot(){return{object:"passkey",id:this.id,name:this.name,verification:this.verification?.__internal_toSnapshot()||null,last_used_at:this.lastUsedAt?.getTime()||null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}class rp extends tR{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",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 iq(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new i7(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 rf extends tR{id="";loaders;rollout;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=this.withDefault(e.id,this.id),this.loaders=this.withDefault(e.loaders,this.loaders)),this}__internal_toSnapshot(){return{object:"protect_config",id:this.id,loaders:this.loaders}}}class rm{firstName;lastName;imageUrl;hasImage;identifier;userId;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.firstName=e.first_name||null,this.lastName=e.last_name||null,this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.identifier=e.identifier||"",this.userId=e.user_id),this}__internal_toSnapshot(){return{first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl,has_image:this.hasImage,identifier:this.identifier,user_id:this.userId}}}let rg={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"}},r_=new Set(["first_factor","second_factor","multi_factor"]),rb=new Set(["strict_mfa","strict","moderate","lax"]),ry=(e,t)=>{let{org:i,user:r}=rw(e),[n,s]=t.split(":"),a=s||n;return"org"===n?i.includes(a):"user"===n?r.includes(a):[...i,...r].includes(a)},rw=e=>{let t=e?e.split(",").map(e=>e.trim()):[];return{org:t.filter(e=>e.split(":")[0].includes("o")).map(e=>e.split(":")[1]),user:t.filter(e=>e.split(":")[0].includes("u")).map(e=>e.split(":")[1])}};class rv extends tR{status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new iq(null);secondFactorVerification=new iq(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new rk(e.session),this.level=e.level,this.supportedFirstFactors=X(e.supported_first_factors),this.supportedSecondFactors=X(e.supported_second_factors),this.firstFactorVerification=new iq(e.first_factor_verification),this.secondFactorVerification=new iq(e.second_factor_verification)),this}}class rk extends tR{pathRoot="/client/sessions";id;status;lastActiveAt;lastActiveToken;lastActiveOrganizationId;actor;user;publicUserData;factorVerificationAge=null;tasks=null;expireAt;abandonAt;createdAt;updatedAt;static isSessionResource(e){return!!e&&e instanceof rk}constructor(e){super(),this.fromJSON(e),this.#z(this.lastActiveToken)}end=()=>(iC.clear(),this._basePost({action:"end"}));remove=()=>(iC.clear(),this._basePost({action:"remove"}));touch=()=>this._basePost({action:"touch",body:{active_organization_id:this.lastActiveOrganizationId}}).then(e=>(e.lastActiveToken&&i2.emit(iZ,{token:e.lastActiveToken}),e));clearCache=()=>iC.clear();getToken=async e=>e8(()=>this._getToken(e),{factor:1.55,initialDelay:3e3,maxDelayBetweenRetries:5e4,jitter:!1,shouldRetry:(e,t)=>!P(e)&&t<=8});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?.id,orgRole:i?.role,orgPermissions:i?.permissions,features:this.lastActiveToken?.jwt?.claims.fea||"",plans:this.lastActiveToken?.jwt?.claims.pla||""},e=>{if(!t.userId)return!1;let i=((e,t)=>{let{features:i,plans:r}=t;return e.feature&&i?ry(i,e.feature):e.plan&&r?ry(r,e.plan):null})(e,t),r=((e,t)=>{let{orgId:i,orgRole:r,orgPermissions:n}=t;return(e.role||e.permission)&&i&&r&&n?e.permission?n.includes(e.permission.replace(/^(org:)*/,"org:")):e.role?r.replace(/^(org:)*/,"org:")===e.role.replace(/^(org:)*/,"org:"):null:null})(e,t),n=((e,{factorVerificationAge:t})=>{if(!e.reverification||!t)return null;let i=(e=>{let t,i;if(!e)return!1;let r="string"==typeof e&&rb.has(e),n="object"==typeof e&&(t=e.level,r_.has(t))&&"number"==typeof(i=e.afterMinutes)&&i>0;return(!!r||!!n)&&(e=>"string"==typeof e?rg[e]:e).bind(null,e)})(e.reverification);if(!i)return null;let{level:r,afterMinutes:n}=i(),[s,a]=t,o=-1!==s?n>s:null,l=-1!==a?n>a:null;switch(r){case"first_factor":return o;case"second_factor":return -1!==a?l:o;case"multi_factor":return -1===a?o:o&&l}})(e,t);return[i||r,n].some(e=>null===e)?[i||r,n].some(e=>!0===e):[i||r,n].every(e=>!0===e)})(e)};#z=e=>{e&&iC.set({tokenId:this.#M(),tokenResolver:Promise.resolve(e)})};#M(e,t){let i=void 0===t?this.lastActiveOrganizationId:t;return ik.build(this.id,e,i)}startVerification=async({level:e})=>new rv((await tR._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"enterprise_sso":t={emailAddressId:e.emailAddressId,enterpriseConnectionId:e.enterpriseConnectionId,redirectUrl:e.redirectUrl};break;default:tw("Session.prepareFirstFactorVerification",e.strategy)}return new rv((await tR._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(iJ(e.publicKeyCredential))}:{...e},new rv((await tR._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_first_factor`,body:{...t,strategy:e.strategy}}))?.response)};verifyWithPasskey=async()=>{let{nonce:e=null}=(await this.prepareFirstFactorVerification({strategy:"passkey"})).firstFactorVerification,t=rk.clerk.__internal_isWebAuthnSupported||rc,i=rk.clerk.__internal_getPublicCredentials||i$;if(!t())throw new I("Passkeys are not supported",{code:"passkey_not_supported"});let r=e?ij(JSON.parse(e)):null;r||tU("get");let{publicKeyCredential:n,error:s}=await i({publicKeyOptions:r,conditionalUI:!1});if(!n)throw s;return this.attemptFirstFactorVerification({strategy:"passkey",publicKeyCredential:n})};prepareSecondFactorVerification=async e=>new rv((await tR._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>new rv((await tR._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_second_factor`,body:e}))?.response);fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.expireAt=tz(e.expire_at),this.abandonAt=tz(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=tz(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.createdAt=tz(e.created_at),this.updatedAt=tz(e.updated_at),this.user=new r$(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new rm(e.public_user_data)),this.lastActiveToken=e.last_active_token?new rN(e.last_active_token):null),this}__internal_toSnapshot(){return{object:"session",id:this.id,status:this.status,expire_at:this.expireAt.getTime(),abandon_at:this.abandonAt.getTime(),factor_verification_age:this.factorVerificationAge,last_active_at:this.lastActiveAt.getTime(),last_active_organization_id:this.lastActiveOrganizationId,actor:this.actor,tasks:this.tasks,user:this.user?.__internal_toSnapshot()||null,public_user_data:this.publicUserData.__internal_toSnapshot(),last_active_token:this.lastActiveToken?.__internal_toSnapshot()||null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}async _getToken(e){if(!this.user)return null;let{leewayInSeconds:t,template:i,skipCache:r=!1}=e||{},n=void 0===e?.organizationId?this.lastActiveOrganizationId:e?.organizationId;if(!i&&Number(t)>=60)throw Error("Leeway can not exceed the token lifespan (60 seconds)");let s=this.#M(i,n),a=r?void 0:iC.get({tokenId:s},t),o=!i&&n===this.lastActiveOrganizationId;if(a){e4.debug("Using cached token (no fetch needed)",{tokenId:s},"session");let e=await a.tokenResolver;return o&&i2.emit(iZ,{token:e}),e.getRawString()||null}e4.info("Fetching new token from API",{organizationId:n,template:i,tokenId:s},"session");let l=i?`${this.path()}/tokens/${i}`:`${this.path()}/tokens`,c=i?{}:{organizationId:n},d=rN.create(l,c,r);return iC.set({tokenId:s,tokenResolver:d}),d.then(e=>(o&&(i2.emit(iZ,{token:e}),e.jwt&&(this.lastActiveToken=e,i2.emit(i3,null))),e.getRawString()||null))}get currentTask(){let[e]=this.tasks??[];return e}}class rS extends tR{pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}static retrieve(){let e=tR.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new rS(e,"/me/sessions"))).catch(()=>[])}revoke(){return this._basePost({action:"revoke",body:{}})}fromJSON(e){let t;return e?(this.id=e.id,this.status=e.status,this.expireAt=tz(e.expire_at),this.abandonAt=tz(e.abandon_at),this.lastActiveAt=tz(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 rU=(e,t,i)=>{let{onValidation:r=eY,onValidationComplexity:n=eY}=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 rA(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function rI(e,t,i,r,n){if(!e.client||!r.popup)return;let s=rA(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 rC(e,{redirectCallbackUrl:t,redirectUrl:i}){let r=rA(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 rP(e,t){return new Promise((i,r)=>{if(!e.client||!t.popup)return void r();let n=async t=>{t.origin===rA(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()})}async function rO(e,t){i2.emit("resource:error",{resource:e,error:null}),i2.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await t(),error:null}}catch(t){return i2.emit("resource:error",{resource:e,error:t}),{error:t}}finally{i2.emit("resource:fetch",{resource:e,status:"idle"})}}let rT=()=>{var e;return(e=new te,{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 rE extends tR{pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;firstFactorVerification=new iq(null);secondFactorVerification=new iq(null);identifier=null;createdSessionId=null;userData=new rL(null);clientTrustState;get status(){return this._status}set status(e){let t=this._status;this._status=e,e&&t!==e&&e4.debug("SignIn.status",{id:this.id,from:t,to:e})}__internal_future=new rx(this);__internal_basePost=this._basePost.bind(this);__internal_baseGet=this._baseGet.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=e=>{e4.debug("SignIn.create",{id:this.id,strategy:"strategy"in e?e.strategy:void 0});let t=tl();return this._basePost({path:this.pathRoot,body:t?{locale:t,...e}:e})};resetPassword=e=>this._basePost({body:e,action:"reset_password"});prepareFirstFactor=e=>{let t;switch(e4.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":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:tw("SignIn.prepareFirstFactor",e.strategy)}return this._basePost({body:{...t,strategy:e.strategy},action:"prepare_first_factor"})};attemptFirstFactor=e=>{let t;return e4.debug("SignIn.attemptFirstFactor",{id:this.id,strategy:e.strategy}),t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(iJ(e.publicKeyCredential))}:{...e},this._basePost({body:{...t,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:t}=iM();return{startEmailLinkFlow:async({emailAddressId:i,redirectUrl:r})=>{this.id||ty("SignIn");let n={strategy:"email_link",emailAddressId:i,redirectUrl:r},s="needs_second_factor"===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=>{let r=e[a].status;("verified"===r||"expired"===r)&&(t(),i(e))}).catch(e=>{t(),r(e)}))})},cancelEmailLinkFlow:t}};prepareSecondFactor=e=>(e4.debug("SignIn.prepareSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_second_factor"}));attemptSecondFactor=e=>(e4.debug("SignIn.attemptSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_second_factor"}));authenticateWithRedirectOrPopup=async(e,t)=>{let{strategy:i,redirectUrlComplete:r,identifier:n,oidcPrompt:s,continueSignIn:a,enterpriseConnectionId:o}=e||{},l=rE.clerk.buildUrlWithAuth(e.redirectUrl);this.id&&a||await this.create({strategy:i,identifier:n,redirectUrl:l,actionCompleteRedirectUrl:r}),"enterprise_sso"===i&&await this.prepareFirstFactor({strategy:i,redirectUrl:l,actionCompleteRedirectUrl:r,oidcPrompt:s,enterpriseConnectionId:o});let{status:c,externalVerificationRedirectURL:d}=this.firstFactorVerification;"unverified"===c&&d?t(d):tS(c,rE.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eF);authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||tk("popup"),rI(rE.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"}=e||{},s=n.replace("web3_","").replace("_signature","");"function"!=typeof r&&tk("generateSignature"),await this.create({identifier:i});let a=this.supportedFirstFactors?.find(e=>e.strategy===n);a||tv("SignIn"),await this.prepareFirstFactor(a);let{message:o}=this.firstFactorVerification;o||tv("SignIn");try{t=await r({identifier:i,nonce:o,provider:s})}catch(e){if("coinbase_wallet"===s&&4001===e.code)t=await r({identifier:i,nonce:o,provider:s});else throw e}return this.attemptFirstFactor({signature:t,strategy:n})};authenticateWithMetamask=async()=>{let e=await th().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:th().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await th().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:th().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await th().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:th().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await th().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:th().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithPasskey=async e=>{let{flow:t}=e||{},i=rE.clerk.__internal_isWebAuthnSupported||rc,r=rE.clerk.__internal_getPublicCredentials||i$,n=rE.clerk.__internal_isWebAuthnAutofillSupported||rd;if(!i())throw new I("Passkeys are not supported",{code:"passkey_not_supported"});if("autofill"===t||"discoverable"===t)await this.create({strategy:"passkey"});else{let e=this.supportedFirstFactors.find(e=>"passkey"===e.strategy);e||function(){throw Error(`${tg} You need to start a SignIn flow by calling SignIn.create({ strategy: 'passkey' }) first`)}(),await this.prepareFirstFactor(e)}let{nonce:s}=this.firstFactorVerification,a=s?ij(JSON.parse(s)):null;a||tU("get");let o=!1;"autofill"===t&&(o=await n());let{publicKeyCredential:l,error:c}=await r({publicKeyOptions:a,conditionalUI:o});if(!l)throw c;return this.attemptFirstFactor({publicKeyCredential:l,strategy:"passkey"})};validatePassword=(e,t)=>{if(rE.clerk.__unstable__environment?.userSettings.passwordSettings)return rU(rT(),{...rE.clerk.__unstable__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=X(e.supported_first_factors),this.supportedSecondFactors=X(e.supported_second_factors),this.firstFactorVerification=new iq(e.first_factor_verification),this.secondFactorVerification=new iq(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new rL(e.user_data),this.clientTrustState=e.client_trust_state??void 0),i2.emit("resource:update",{resource:this}),this}__internal_toSnapshot(){return{object:"sign_in",id:this.id||"",status:this.status||null,supported_identifiers:this.supportedIdentifiers,supported_first_factors:H(this.supportedFirstFactors),supported_second_factors:H(this.supportedSecondFactors),first_factor_verification:this.firstFactorVerification.__internal_toSnapshot(),second_factor_verification:this.secondFactorVerification.__internal_toSnapshot(),identifier:this.identifier,created_session_id:this.createdSessionId,user_data:this.userData.__internal_toSnapshot()}}}class rx{resource;emailCode={sendCode:this.sendEmailCode.bind(this),verifyCode:this.verifyEmailCode.bind(this)};emailLink={sendLink:this.sendEmailLink.bind(this),waitForVerification:this.waitForEmailLinkVerification.bind(this),get verification(){if(!n())return null;const e=eI("__clerk_status"),t=eI("__clerk_created_session");if(!e||!t)return null;const i="verified"===e&&void 0!==rE.clerk.client&&rE.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)};phoneCode={sendCode:this.sendPhoneCode.bind(this),verifyCode:this.verifyPhoneCode.bind(this)};mfa={sendPhoneCode:this.sendMFAPhoneCode.bind(this),verifyPhoneCode:this.verifyMFAPhoneCode.bind(this),verifyTOTP:this.verifyTOTP.bind(this),verifyBackupCode:this.verifyBackupCode.bind(this)};#F=!1;constructor(e){this.resource=e}get id(){return this.resource.id}get identifier(){return this.resource.identifier}get createdSessionId(){return this.resource.createdSessionId}get userData(){return this.resource.userData}get status(){return this.resource.status||"needs_identifier"}get supportedFirstFactors(){return this.resource.supportedFirstFactors??[]}get supportedSecondFactors(){return this.resource.supportedSecondFactors??[]}get isTransferable(){return"transferable"===this.resource.firstFactorVerification.status}get existingSession(){if("failed"===this.resource.firstFactorVerification.status&&this.resource.firstFactorVerification.error?.code==="identifier_already_signed_in"&&this.resource.firstFactorVerification.error?.meta?.sessionId)return{sessionId:this.resource.firstFactorVerification.error?.meta?.sessionId}}get firstFactorVerification(){return this.resource.firstFactorVerification}get secondFactorVerification(){return this.resource.secondFactorVerification}get hasBeenFinalized(){return this.#F}async sendResetPasswordEmailCode(){if(!this.resource.id)throw Error("Cannot reset password without a sign in.");return rO(this.resource,async()=>{let e=this.resource.supportedFirstFactors?.find(e=>"reset_password_email_code"===e.strategy);if(!e)throw new U("Reset password email code factor not found",{code:"factor_not_found"});let{emailAddressId:t}=e;await this.resource.__internal_basePost({body:{emailAddressId:t,strategy:"reset_password_email_code"},action:"prepare_first_factor"})})}async verifyResetPasswordEmailCode(e){let{code:t}=e;return rO(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:t,strategy:"reset_password_email_code"},action:"attempt_first_factor"})})}async submitResetPassword(e){let{password:t,signOutOfOtherSessions:i=!0}=e;return rO(this.resource,async()=>{await this.resource.__internal_basePost({body:{password:t,signOutOfOtherSessions:i},action:"reset_password"})})}async _create(e){let t=tl();await this.resource.__internal_basePost({path:this.resource.pathRoot,body:t?{locale:t,...e}:e})}async create(e){return rO(this.resource,async()=>{await this._create(e)})}async password(e){if([e.identifier,e.emailAddress,e.phoneNumber].filter(Boolean).length>1)throw Error("Only one of identifier, emailAddress, or phoneNumber can be provided");return rO(this.resource,async()=>{let t=e.identifier||e.emailAddress||e.phoneNumber,i=this.resource.identifier,r=tl();await this.resource.__internal_basePost({path:this.resource.pathRoot,body:{identifier:t||i,password:e.password,...r?{locale:r}:{}}})})}async sendEmailCode(e={}){let{emailAddress:t,emailAddressId:i}=e;if(!this.resource.id&&i)throw Error("signIn.emailCode.sendCode() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.resource.id&&!t)throw Error("signIn.emailCode.sendCode() cannot be called without an emailAddress if an existing signIn does not exist.");return rO(this.resource,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_code",emailAddressId:i});if(!e)throw new U("Email code factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{emailAddressId:e.emailAddressId,strategy:"email_code"},action:"prepare_first_factor"})})}async verifyEmailCode(e){let{code:t}=e;return rO(this.resource,async()=>{await this.resource.__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.resource.id&&r)throw Error("signIn.emailLink.sendLink() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.resource.id&&!t)throw Error("signIn.emailLink.sendLink() cannot be called without an emailAddress if an existing signIn does not exist.");return rO(this.resource,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_link",emailAddressId:r});if(!e)throw new U("Email link factor not found",{code:"factor_not_found"});let n=i;try{new URL(i)}catch{n=window.location.origin+i}await this.resource.__internal_basePost({body:{emailAddressId:e.emailAddressId,redirectUrl:n,strategy:"email_link"},action:"prepare_first_factor"})})}async waitForEmailLinkVerification(){return rO(this.resource,async()=>{let{run:e,stop:t}=iM();await new Promise((i,r)=>{e(async()=>{try{let e=await this.resource.__internal_baseGet(),r=e.firstFactorVerification.status;("verified"===r||"expired"===r)&&(t(),i(e))}catch(e){t(),r(e)}})})})}async sendPhoneCode(e={}){let{phoneNumber:t,phoneNumberId:i,channel:r="sms"}=e;if(!this.resource.id&&i)throw Error("signIn.phoneCode.sendCode() cannot be called with an phoneNumberId if an existing signIn does not exist.");if(!this.resource.id&&!t)throw Error("signIn.phoneCode.sendCode() cannot be called without an phoneNumber if an existing signIn does not exist.");return rO(this.resource,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"phone_code",phoneNumberId:i});if(!e)throw new U("Phone code factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{phoneNumberId:e.phoneNumberId,strategy:"phone_code",channel:r},action:"prepare_first_factor"})})}async verifyPhoneCode(e){let{code:t}=e;return rO(this.resource,async()=>{await this.resource.__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,enterpriseConnectionId:a,identifier:o}=e;return rO(this.resource,async()=>{let e=i;try{new URL(i)}catch{e=window.location.origin+i}let l={redirectUrl:rE.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:e};if(n){let t=rC(rE.clerk,{redirectCallbackUrl:l.redirectUrl,redirectUrl:e});l.redirectUrl=t.redirectCallbackUrl,l.actionCompleteRedirectUrl=t.redirectUrl}await this._create({strategy:t,...l,identifier:o}),"enterprise_sso"===t&&await this.resource.__internal_basePost({body:{...l,oidcPrompt:s,enterpriseConnectionId:a,strategy:"enterprise_sso"},action:"prepare_first_factor"});let{status:c,externalVerificationRedirectURL:d}=this.resource.firstFactorVerification;"unverified"===c&&d&&(n?(await rP(rE.clerk,{popup:n,externalVerificationRedirectURL:d}),await this.resource.reload()):eF(d))})}async web3(e){let{strategy:t}=e,i=t.replace("web3_","").replace("_signature","");return rO(this.resource,async()=>{let e,r,n;switch(i){case"metamask":e=await th().getMetamaskIdentifier(),r=th().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await th().getCoinbaseWalletIdentifier(),r=th().generateSignatureWithCoinbaseWallet;break;case"base":e=await th().getBaseIdentifier(),r=th().generateSignatureWithBase;break;case"okx_wallet":e=await th().getOKXWalletIdentifier(),r=th().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${i}`)}await this._create({identifier:e});let s=this.resource.supportedFirstFactors?.find(e=>e.strategy===t);if(!s)throw new U("Web3 first factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{web3WalletId:s.web3WalletId,strategy:t},action:"prepare_first_factor"});let{message:a}=this.firstFactorVerification;if(!a)throw new U("Web3 nonce not found",{code:"web3_nonce_not_found"});try{n=await r({identifier:e,nonce:a})}catch(t){if("coinbase_wallet"===i&&4001===t.code)n=await r({identifier:e,nonce:a});else throw t}await this.resource.__internal_basePost({body:{signature:n,strategy:t},action:"attempt_first_factor"})})}async passkey(e){let{flow:t}=e||{},i=rE.clerk.__internal_isWebAuthnSupported||rc,r=rE.clerk.__internal_getPublicCredentials||i$,n=rE.clerk.__internal_isWebAuthnAutofillSupported||rd;if(!i())throw new I("Passkeys are not supported",{code:"passkey_not_supported"});return rO(this.resource,async()=>{if("autofill"===t||"discoverable"===t)await this._create({strategy:"passkey"});else{if(!this.supportedFirstFactors.find(e=>"passkey"===e.strategy))throw new U("Passkey factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{strategy:"passkey"},action:"prepare_first_factor"})}let{nonce:e}=this.firstFactorVerification,i=e?ij(JSON.parse(e)):null;if(!i)throw new U("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 I(o.message,{code:"passkey_retrieval_failed"});await this.resource.__internal_basePost({body:{publicKeyCredential:JSON.stringify(iJ(a)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return rO(this.resource,async()=>{let e=this.resource.supportedSecondFactors?.find(e=>"phone_code"===e.strategy);if(!e)throw new U("Phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:t}=e;await this.resource.__internal_basePost({body:{phoneNumberId:t,strategy:"phone_code"},action:"prepare_second_factor"})})}async verifyMFAPhoneCode(e){let{code:t}=e;return rO(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_second_factor"})})}async verifyTOTP(e){let{code:t}=e;return rO(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:t,strategy:"totp"},action:"attempt_second_factor"})})}async verifyBackupCode(e){let{code:t}=e;return rO(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:t,strategy:"backup_code"},action:"attempt_second_factor"})})}async ticket(e){let t=e?.ticket??eI("__clerk_ticket");return this.create({ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};if(!this.resource.createdSessionId)throw Error("Cannot finalize sign-in without a created session.");return rO(this.resource,async()=>{rE.clerk.client&&!rE.clerk.client.sessions.some(e=>e.id===this.resource.createdSessionId)&&await rE.clerk.client.reload(),this.#F=!0,await rE.clerk.setActive({session:this.resource.createdSessionId,navigate:t})})}selectFirstFactor({strategy:e,emailAddressId:t,phoneNumberId:i}){if(!this.resource.supportedFirstFactors)return null;if(t){let i=this.resource.supportedFirstFactors.find(i=>i.strategy===e&&i.emailAddressId===t);if(i)return i}if(i){let t=this.resource.supportedFirstFactors.find(t=>t.strategy===e&&t.phoneNumberId===i);if(t)return t}let r=this.resource.supportedFirstFactors.find(t=>t.strategy===e&&t.safeIdentifier===this.resource.identifier);if(r)return r;let n=this.resource.supportedFirstFactors.find(t=>t.strategy===e);return n||null}}function rR(e){let{unsafeMetadata:t}={...e},i=t?"object"==typeof t?JSON.stringify(t):t:"";return{...e,...t?{unsafeMetadata:i}:{}}}class rz extends tR{pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new iH(null);username=null;firstName=null;lastName=null;emailAddress=null;phoneNumber=null;web3wallet=null;externalAccount;hasPassword=!1;unsafeMetadata={};createdSessionId=null;createdUserId=null;abandonAt=null;legalAcceptedAt=null;locale=null;get status(){return this._status}set status(e){let t=this._status;this._status=e,e&&t!==e&&e4.debug("SignUp.status",{id:this.id,from:t,to:e})}__internal_future=new rM(this);__internal_basePost=this._basePost.bind(this);__internal_basePatch=this._basePatch.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{e4.debug("SignUp.create",{id:this.id,strategy:e.strategy});let t={...e};if(!t.locale){let e=tl();e&&(t.locale=e)}if(!this.clientBypass()&&!this.shouldBypassCaptchaForAttempt(e)){let e=new tE(rz.clerk),i=await e.managedOrInvisible({action:"signup"});if(!i)throw new U("",{code:"captcha_unavailable"});t={...t,...i}}if(t.transfer&&this.shouldBypassCaptchaForAttempt(t)){let e=rz.clerk.client?.signIn.firstFactorVerification.strategy;e&&(t={...t,strategy:e})}return this._basePost({path:this.pathRoot,body:rR(t)})};prepareVerification=e=>(e4.debug("SignUp.prepareVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_verification"}));attemptVerification=e=>(e4.debug("SignUp.attemptVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_verification"}));prepareEmailAddressVerification=e=>this.prepareVerification(e||{strategy:"email_code"});attemptEmailAddressVerification=e=>this.attemptVerification({...e,strategy:"email_code"});createEmailLinkFlow=()=>{let{run:e,stop:t}=iM();return{startEmailLinkFlow:async({redirectUrl:i})=>(this.id||ty("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}=e||{},o=s.replace("web3_","").replace("_signature","");"function"!=typeof i&&tk("generateSignature");let l=r||this.web3wallet;await this.create({web3Wallet:l,unsafeMetadata:n,legalAccepted:a}),await this.prepareWeb3WalletVerification({strategy:s});let{message:c}=this.verifications.web3Wallet;c||tv("SignUp");try{t=await i({identifier:r,nonce:c,provider:o})}catch(e){if("coinbase_wallet"===o&&4001===e.code)t=await i({identifier:r,nonce:c,provider:o});else throw e}return this.attemptWeb3WalletVerification({signature:t,strategy:s})};authenticateWithMetamask=async e=>{let t=await th().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:th().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let t=await th().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:th().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let t=await th().getBaseIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:th().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let t=await th().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:th().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithRedirectOrPopup=async(e,t)=>{let{redirectUrl:i,redirectUrlComplete:r,strategy:n,continueSignUp:s=!1,unsafeMetadata:a,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:d}=e,h=rz.clerk.buildUrlWithAuth(i),u=()=>{let e={strategy:n,redirectUrl:h,actionCompleteRedirectUrl:r,unsafeMetadata:a,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:d};return s&&this.id?this.update(e):this.create(e)},{verifications:p}=await u().catch(async e=>{if(O(e)&&C(e))return await rz.clerk.__unstable__environment.reload(),u();throw e}),{externalAccount:f}=p,{status:m,externalVerificationRedirectURL:g}=f;"unverified"===m&&g?t(g):tS(m,rz.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eF);authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||tk("popup"),rI(rz.clerk,"signUp",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e instanceof URL?e.toString():e})};update=e=>this._basePatch({body:rR(e)});upsert=e=>this.id?this.update(e):this.create(e);validatePassword=(e,t)=>{if(rz.clerk.__unstable__environment?.userSettings.passwordSettings)return rU(rT(),{...rz.clerk.__unstable__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 iH(e.verifications),this.username=e.username,this.firstName=e.first_name,this.lastName=e.last_name,this.emailAddress=e.email_address,this.phoneNumber=e.phone_number,this.hasPassword=e.has_password,this.unsafeMetadata=e.unsafe_metadata,this.createdSessionId=e.created_session_id,this.createdUserId=e.created_user_id,this.abandonAt=e.abandon_at,this.web3wallet=e.web3_wallet,this.legalAcceptedAt=e.legal_accepted_at,this.locale=e.locale),i2.emit("resource:update",{resource:this}),this}__internal_toSnapshot(){return{object:"sign_up",id:this.id||"",status:this.status||null,required_fields:this.requiredFields,optional_fields:this.optionalFields,missing_fields:this.missingFields,unverified_fields:this.unverifiedFields,verifications:this.verifications.__internal_toSnapshot(),username:this.username,first_name:this.firstName,last_name:this.lastName,email_address:this.emailAddress,phone_number:this.phoneNumber,has_password:this.hasPassword,unsafe_metadata:this.unsafeMetadata,created_session_id:this.createdSessionId,created_user_id:this.createdUserId,abandon_at:this.abandonAt,web3_wallet:this.web3wallet,legal_accepted_at:this.legalAcceptedAt,locale:this.locale,external_account:this.externalAccount,external_account_strategy:this.externalAccount?.strategy}}clientBypass(){return rz.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){if(!e.strategy)return!1;let t=rz.clerk.__unstable__environment.displayConfig.captchaOauthBypass;return!!(t.some(t=>t===e.strategy)||e.transfer&&t.some(e=>e===rz.clerk.client.signIn.firstFactorVerification.strategy))}__experimental_getEnterpriseConnections=()=>tR._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new rF(e)))}class rM{resource;verifications={sendEmailCode:this.sendEmailCode.bind(this),verifyEmailCode:this.verifyEmailCode.bind(this),sendPhoneCode:this.sendPhoneCode.bind(this),verifyPhoneCode:this.verifyPhoneCode.bind(this)};#F=!1;constructor(e){this.resource=e}get id(){return this.resource.id}get requiredFields(){return this.resource.requiredFields}get optionalFields(){return this.resource.optionalFields}get missingFields(){return this.resource.missingFields}get status(){return this.resource.status||"missing_requirements"}get username(){return this.resource.username}get firstName(){return this.resource.firstName}get lastName(){return this.resource.lastName}get emailAddress(){return this.resource.emailAddress}get phoneNumber(){return this.resource.phoneNumber}get web3Wallet(){return this.resource.web3wallet}get hasPassword(){return this.resource.hasPassword}get unsafeMetadata(){return this.resource.unsafeMetadata}get createdSessionId(){return this.resource.createdSessionId}get createdUserId(){return this.resource.createdUserId}get abandonAt(){return this.resource.abandonAt}get legalAcceptedAt(){return this.resource.legalAcceptedAt}get locale(){return this.resource.locale}get unverifiedFields(){return this.resource.unverifiedFields}get isTransferable(){return"transferable"===this.resource.verifications.externalAccount.status&&this.resource.verifications.externalAccount.error?.code==="external_account_exists"}get existingSession(){if(("failed"===this.resource.verifications.externalAccount.status||"unverified"===this.resource.verifications.externalAccount.status)&&this.resource.verifications.externalAccount.error?.code==="identifier_already_signed_in"&&this.resource.verifications.externalAccount.error?.meta?.sessionId)return{sessionId:this.resource.verifications.externalAccount.error?.meta?.sessionId}}get hasBeenFinalized(){return this.#F}async getCaptchaToken(){let e=new tE(rz.clerk),t=await e.managedOrInvisible({action:"signup"});if(!t)throw Error("Captcha challenge failed");let{captchaError:i,captchaToken:r,captchaWidgetType:n}=t;return{captchaToken:r,captchaWidgetType:n,captchaError:i}}async _create(e){let{captchaToken:t,captchaWidgetType:i,captchaError:r}=await this.getCaptchaToken(),n={transfer:e.transfer,captchaToken:t,captchaWidgetType:i,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rR(e.unsafeMetadata):void 0,locale:e.locale??tl()};await this.resource.__internal_basePost({path:this.resource.pathRoot,body:n})}async create(e){return rO(this.resource,async()=>{await this._create(e)})}async update(e){return rO(this.resource,async()=>{let t={...e,unsafeMetadata:e.unsafeMetadata?rR(e.unsafeMetadata):void 0};await this.resource.__internal_basePatch({path:this.resource.pathRoot,body:t})})}async password(e){return rO(this.resource,async()=>{let{captchaToken:t,captchaWidgetType:i,captchaError:r}=await this.getCaptchaToken(),n={strategy:"password",captchaToken:t,captchaWidgetType:i,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rR(e.unsafeMetadata):void 0};await this.resource.__internal_basePost({path:this.resource.pathRoot,body:n})})}async sendEmailCode(){return rO(this.resource,async()=>{await this.resource.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification"})})}async verifyEmailCode(e){let{code:t}=e;return rO(this.resource,async()=>{await this.resource.__internal_basePost({body:{strategy:"email_code",code:t},action:"attempt_verification"})})}async sendPhoneCode(e){let{phoneNumber:t,channel:i="sms"}=e;return rO(this.resource,async()=>{if(!this.resource.id){let{captchaToken:e,captchaWidgetType:i,captchaError:r}=await this.getCaptchaToken();await this.resource.__internal_basePost({path:this.resource.pathRoot,body:{phoneNumber:t,captchaToken:e,captchaWidgetType:i,captchaError:r}})}await this.resource.__internal_basePost({body:{strategy:"phone_code",channel:i},action:"prepare_verification"})})}async verifyPhoneCode(e){let{code:t}=e;return rO(this.resource,async()=>{await this.resource.__internal_basePost({body:{strategy:"phone_code",code:t},action:"attempt_verification"})})}async sso(e){let{strategy:t,redirectUrl:i,redirectCallbackUrl:r,unsafeMetadata:n,legalAccepted:s,oidcPrompt:a,enterpriseConnectionId:o,emailAddress:l,popup:c}=e;return rO(this.resource,async()=>{let{captchaToken:e,captchaWidgetType:d,captchaError:h}=await this.getCaptchaToken(),u=i;try{new URL(i)}catch{u=window.location.origin+i}let p={redirectUrl:rz.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:u};if(c){let e=rC(rz.clerk,{redirectCallbackUrl:p.redirectUrl,redirectUrl:u});p.redirectUrl=e.redirectCallbackUrl,p.actionCompleteRedirectUrl=e.redirectUrl}let f=()=>this.resource.__internal_basePost({path:this.resource.pathRoot,body:{strategy:t,...p,unsafeMetadata:n,legalAccepted:s,oidcPrompt:a,enterpriseConnectionId:o,emailAddress:l,captchaToken:e,captchaWidgetType:d,captchaError:h}});await f().catch(async e=>{if(O(e)&&C(e))return await rz.clerk.__unstable__environment.reload(),f();throw e});let{status:m,externalVerificationRedirectURL:g}=this.resource.verifications.externalAccount;"unverified"===m&&g&&(c?(await rP(rz.clerk,{popup:c,externalVerificationRedirectURL:g}),await this.resource.reload()):eF(g))})}async web3(e){let{strategy:t,unsafeMetadata:i,legalAccepted:r}=e,n=t.replace("web3_","").replace("_signature","");return rO(this.resource,async()=>{let e,s,a;switch(n){case"metamask":e=await th().getMetamaskIdentifier(),s=th().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await th().getCoinbaseWalletIdentifier(),s=th().generateSignatureWithCoinbaseWallet;break;case"base":e=await th().getBaseIdentifier(),s=th().generateSignatureWithBase;break;case"okx_wallet":e=await th().getOKXWalletIdentifier(),s=th().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${n}`)}let o=e||this.resource.web3wallet;await this._create({web3Wallet:o,unsafeMetadata:i,legalAccepted:r}),await this.resource.__internal_basePost({body:{strategy:t},action:"prepare_verification"});let{message:l}=this.resource.verifications.web3Wallet;l||tv("SignUp");try{a=await s({identifier:e,nonce:l})}catch(t){if("coinbase_wallet"===n&&4001===t.code)a=await s({identifier:e,nonce:l});else throw t}await this.resource.__internal_basePost({body:{signature:a,strategy:t},action:"attempt_verification"})})}async ticket(e){let t=e?.ticket??eI("__clerk_ticket");return this.create({...e,ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};return rO(this.resource,async()=>{if(!this.resource.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#F=!0,await rz.clerk.setActive({session:this.resource.createdSessionId,navigate:t})})}}class rF extends tR{id;name;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name),this}}class rN extends tR{pathRoot="tokens";jwt;static async create(e,t={},i=!1){return new rN(await tR._fetch({body:t,method:"POST",path:e,search:i?"debug=skip_cache":void 0}),e)}constructor(e,t){super(),t&&(this.pathRoot=t),e?.jwt&&(this.jwt=to(e.jwt))}getRawString=()=>this.jwt?.claims.__raw||"";fromJSON(e){return e&&(this.jwt=to(e.jwt)),this}__internal_toSnapshot(){return{object:"token",id:this.id||"",jwt:this.getRawString()}}}class rW extends tR{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=tz(e.updated_at),this.createdAt=tz(e.created_at)),this}}class rD extends tR{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=tz(e.updated_at),this.createdAt=tz(e.created_at)),this}}class r$ extends tR{pathRoot="/me";id="";externalId=null;username=null;emailAddresses=[];phoneNumbers=[];web3Wallets=[];externalAccounts=[];enterpriseAccounts=[];passkeys=[];organizationMemberships=[];passwordEnabled=!1;firstName=null;lastName=null;fullName=null;primaryEmailAddressId=null;primaryEmailAddress=null;primaryPhoneNumberId=null;primaryPhoneNumber=null;primaryWeb3WalletId=null;primaryWeb3Wallet=null;imageUrl="";hasImage=!1;twoFactorEnabled=!1;totpEnabled=!1;backupCodeEnabled=!1;publicMetadata={};unsafeMetadata={};createOrganizationEnabled=!1;createOrganizationsLimit=null;deleteSelfEnabled=!1;lastSignInAt=null;legalAcceptedAt=null;updatedAt=null;createdAt=null;cachedSessionsWithActivities=null;static isUserResource(e){return!!e&&e instanceof r$}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case iF:return this.primaryEmailAddressId===e.id;case rp:return this.primaryPhoneNumberId===e.id;case rV:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:t}=e||{};return new iF({email_address:t},this.path()+"/email_addresses/").create()};createPasskey=()=>ru.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:t}=e||{};return new rp({phone_number:t},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:t}=e||{};return new rV({web3_wallet:t},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:t,redirectUrl:i,additionalScopes:r}=e||{};return new i9((await tR._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:t,redirect_url:i,additional_scope:r}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new rW((await tR._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new rW((await tR._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new iT((await tR._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new rD((await tR._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);update=e=>this._basePatch({body:rR(e)});updatePassword=e=>this._basePost({body:e,path:`${this.path()}/change_password`});removePassword=e=>this._basePost({body:e,path:`${this.path()}/remove_password`});delete=()=>this._baseDelete({path:"/me"}).then(e=>(i2.emit(i0,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await rS.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:t}=e||{};return null===t?re.delete(`${this.path()}/profile_image`):re.create(`${this.path()}/profile_image`,{file:t})};getOrganizationInvitations=e=>rj.retrieve(e);getOrganizationSuggestions=e=>rl.retrieve(e);getOrganizationMemberships=e=>ro.retrieve(e);leaveOrganization=async e=>new iT((await tR._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);initializePaymentMethod=e=>ih(e);addPaymentMethod=e=>iu(e);getPaymentMethods=e=>ip(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 iF(e,this.path()+"/email_addresses")),this.primaryEmailAddressId=e.primary_email_address_id||null,this.primaryEmailAddress=this.emailAddresses.find(({id:e})=>e===this.primaryEmailAddressId)||null,this.phoneNumbers=(e.phone_numbers||[]).map(e=>new rp(e,this.path()+"/phone_numbers")),this.primaryPhoneNumberId=e.primary_phone_number_id||null,this.primaryPhoneNumber=this.phoneNumbers.find(({id:e})=>e===this.primaryPhoneNumberId)||null,this.web3Wallets=(e.web3_wallets||[]).map(e=>new rV(e,this.path()+"/web3_wallets")),this.primaryWeb3WalletId=e.primary_web3_wallet_id||null,this.primaryWeb3Wallet=this.web3Wallets.find(({id:e})=>e===this.primaryWeb3WalletId)||null,this.externalAccounts=(e.external_accounts||[]).map(e=>new i9(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new ru(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new ro(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new iY(e,this.path()+"/enterprise_accounts")),this.publicMetadata=e.public_metadata||{},this.unsafeMetadata=e.unsafe_metadata||{},this.totpEnabled=e.totp_enabled||!1,this.backupCodeEnabled=e.backup_code_enabled||!1,this.twoFactorEnabled=e.two_factor_enabled||!1,this.createOrganizationEnabled=e.create_organization_enabled||!1,this.createOrganizationsLimit=e.create_organizations_limit||null,this.deleteSelfEnabled=e.delete_self_enabled||!1,e.last_sign_in_at&&(this.lastSignInAt=tz(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=tz(e.legal_accepted_at)),this.updatedAt=tz(e.updated_at||void 0),this.createdAt=tz(e.created_at||void 0)),this}__internal_toSnapshot(){return{object:"user",id:this.id,external_id:this.externalId,first_name:this.firstName,last_name:this.lastName,username:this.username,public_metadata:this.publicMetadata,unsafe_metadata:this.unsafeMetadata,image_url:this.imageUrl,has_image:this.hasImage,email_addresses:this.emailAddresses.map(e=>e.__internal_toSnapshot()),phone_numbers:this.phoneNumbers.map(e=>e.__internal_toSnapshot()),web3_wallets:this.web3Wallets.map(e=>e.__internal_toSnapshot()),external_accounts:this.externalAccounts.map(e=>e.__internal_toSnapshot()),passkeys:this.passkeys.map(e=>e.__internal_toSnapshot()),organization_memberships:this.organizationMemberships.map(e=>e.__internal_toSnapshot()),enterprise_accounts:this.enterpriseAccounts.map(e=>e.__internal_toSnapshot()),totp_enabled:this.totpEnabled,backup_code_enabled:this.backupCodeEnabled,two_factor_enabled:this.twoFactorEnabled,create_organization_enabled:this.createOrganizationEnabled,create_organizations_limit:this.createOrganizationsLimit,delete_self_enabled:this.deleteSelfEnabled,primary_email_address_id:this.primaryEmailAddressId,primary_phone_number_id:this.primaryPhoneNumberId,primary_web3_wallet_id:this.primaryWeb3WalletId,password_enabled:this.passwordEnabled,profile_image_id:this.imageUrl,last_sign_in_at:this.lastSignInAt?.getTime()||null,legal_accepted_at:this.legalAcceptedAt?.getTime()||null,updated_at:this.updatedAt?.getTime()||null,created_at:this.createdAt?.getTime()||null}}}class rL{firstName;lastName;imageUrl;hasImage;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.firstName=e.first_name,this.lastName=e.last_name,this.imageUrl=e.image_url??void 0,this.hasImage=e.has_image??void 0),this}__internal_toSnapshot(){return{first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl||null,has_image:this.hasImage||null}}}class rj extends tR{id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await tR._fetch({path:"/me/organization_invitations",method:"GET",search:t4(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new rj(e))}})}constructor(e){super(),this.fromJSON(e)}accept=async()=>await this._basePost({path:`/me/organization_invitations/${this.id}/accept`});fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.publicOrganizationData={hasImage:e.public_organization_data.has_image,imageUrl:e.public_organization_data.image_url,name:e.public_organization_data.name,id:e.public_organization_data.id,slug:e.public_organization_data.slug},this.publicMetadata=e.public_metadata,this.role=e.role,this.status=e.status,this.createdAt=tz(e.created_at),this.updatedAt=tz(e.updated_at)),this}}let rB={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 rJ extends tR{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:{...rB,name:"phone_number"},username:{...rB,name:"username"},web3_wallet:{...rB,name:"web3_wallet"},first_name:{...rB,name:"first_name"},last_name:{...rB,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:{...rB,name:"authenticator_app"},backup_code:{...rB,name:"backup_code"},passkey:{...rB,name:"passkey"}};enterpriseSSO={enabled:!1};passkeySettings={allow_autofill:!1,show_sign_in_button:!1};passwordSettings={};signIn={second_factor:{required:!1,enabled:!1}};signUp={allowlist_only:!1,captcha_enabled:!1,legal_consent_enabled:!1,mode:"public",progressive:!0};social={};usernameSettings={};get authenticatableSocialStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled&&e.authenticatable).map(([,e])=>e.strategy).sort():[]}get enabledFirstFactorIdentifiers(){return this.attributes?Object.entries(this.attributes).filter(([e,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.signIn=this.withDefault(e.sign_in,this.signIn),this.signUp=this.withDefault(e.sign_up,this.signUp),this.social=this.withDefault(e.social,this.social),this.usernameSettings=e.username_settings?{...e.username_settings,min_length:Math.max(e.username_settings?.min_length??4,4),max_length:Math.min(e.username_settings?.max_length??64,64)}:this.usernameSettings),this}__internal_toSnapshot(){return{actions:this.actions,attributes:this.attributes,passkey_settings:this.passkeySettings,password_settings:this.passwordSettings,sign_in:this.signIn,sign_up:this.signUp,social:this.social}}}class rK extends tR{pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=tz(e.updated_at),this.createdAt=tz(e.created_at)),this}static async join(e){return new rK((await tR._fetch({path:"/waitlist",method:"POST",body:e}))?.response)}}class rV extends tR{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",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 iq(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}function rq(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 rG(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(iP.isClientResource(e))return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.sessions.length!==t.sessions.length;if(rk.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&&rq(i.user,r.user))}if(r$.isUserResource(e))return rq(e,t)}catch{}return!0}(e,t)?e:t}let rH="__clerk_db_jwt";function rX(e,t){let i=new URL(e),r=i.searchParams.get(rH);i.searchParams.delete(rH);let n=r||t;return n&&i.searchParams.set(rH,n),i}let rY=e=>{let t=new URL(e);return t.searchParams.delete(rH),t},rQ=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 rZ(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)e[r]=i[r]}return e}var r0=function e(t,i){function r(e,r,n){if("undefined"!=typeof document){"number"==typeof(n=rZ({},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("undefined"!=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(r[o]=t.read(a,o),e===o)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",rZ({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,rZ({},this.attributes,t))},withConverter:function(t){return e(rZ({},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 r1(e){return{get:()=>r0.get(e),set(t,i={}){r0.set(e,t,i)},remove(t){r0.remove(e,t)}}}let r3=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function r2(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 r4=r1("__clerk_test_etld"),r5="__client_uat",r6="__session",r9=()=>{let e="None",t=r3(e);return{sameSite:e,secure:t,partitioned:t}};async function r8(e){let t;try{t=await eo(e)}catch(o){var i;i=`Suffixed cookie failed due to ${o.message} (secure-context: ${window.isSecureContext}, url: ${window.location.href})`,j.has(i)||(console.log(i),j.add(i));let{default:r}=await Promise.all([s.e("545"),s.e("811")]).then(s.t.bind(s,180,23)),{default:n}=await Promise.all([s.e("545"),s.e("811")]).then(s.t.bind(s,3413,23)),a=r(e);t=n.stringify(a).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}return t}let r7=()=>{let e=!function(){if(!function(){if(!tc())return!1;try{return window.self!==window.top}catch{return!0}}())return!1;try{return window.top?.location.href,!1}catch{return!0}}()?"Lax":"None",t=r3(e);return{sameSite:e,secure:t}};var ne=s(5945),nt=s.n(ne);class ni{lock=(function(e){let t=new(nt());return window.addEventListener("beforeunload",async()=>{await t.releaseLock(e)}),{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)}}}})("clerk.lock.refreshSessionToken");workerTimers=iz();timerId=null;initiated=!1;startPollingForSessionToken(e){if(this.timerId||this.initiated)return;let t=async()=>{this.initiated=!0,await this.lock.acquireLockAndRun(e),this.timerId=this.workerTimers.setTimeout(t,5e3)};t()}stopPollingForSessionToken(){null!=this.timerId&&(this.workerTimers.clearTimeout(this.timerId),this.timerId=null),this.initiated=!1}}class nr{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,t,i,r){let n=await r8(e.publishableKey),s=new nr(e,t,n,i,r);return await s.setup(),s}constructor(e,t,r,n,s){this.clerk=e,this.instanceType=n,this.clerkEventBus=s,i2.on(iZ,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),i2.on(i0,()=>this.handleSignOut()),this.refreshTokenOnFocus(),this.startPollingForToken(),this.clientUat=(e=>{let t=r1(r5),r=r1(el(r5,e));return{set:e=>{let n=r2(Date.now(),1),s="None",a=r3(s),o=function(e=window.location.hostname,t=r4){if(i)return i;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",{domain:n}),"1"===t.get())return t.remove({domain:n}),i=n,n;t.remove({domain:n})}}(),l="0";e&&e.updatedAt&&e.signedInSessions.length>0&&(l=Math.floor(e.updatedAt.getTime()/1e3).toString()),r.remove(),t.remove(),r.set(l,{domain:o,expires:n,partitioned:a,sameSite:s,secure:a}),t.set(l,{domain:o,expires:n,partitioned:a,sameSite:s,secure:a})},get:()=>parseInt(r.get()||t.get()||"0",10)}})(r),this.sessionCookie=(e=>{let t=r1(r6),i=r1(el(r6,e)),r=()=>{let e=r9();t.remove(e),i.remove(e)};return{set:e=>{let n=r2(Date.now(),1),{sameSite:s,secure:a,partitioned:o}=r9();o&&r(),t.set(e,{expires:n,sameSite:s,secure:a,partitioned:o}),i.set(e,{expires:n,sameSite:s,secure:a,partitioned:o})},remove:r,get:()=>i.get()||t.get()}})(r),this.activeCookie=(()=>{let e=r1("clerk_active_context"),t={secure:r3("None")};return{set:i=>{e.set(i,t)},get:()=>e.get(),remove:()=>e.remove(t)}})(),this.devBrowser=function({cookieSuffix:e,frontendApi:t,fapiClient:i}){let r,n,s=(r=r1(rH),n=r1(el(rH,e)),{get:()=>n.get()||r.get(),set:e=>{let t=r2(Date.now(),1),{sameSite:i,secure:s}=r7();n.set(e,{expires:t,sameSite:i,secure:s}),r.set(e,{expires:t,sameSite:i,secure:s})},remove:()=>{let e=r7();n.remove(e),r.remove(e)}});function a(){return s.get()}function o(e){s.set(e)}function l(){s.remove()}return{clear:function(){l()},setup:async function(){var e;let r;if(!ep(t))return;i.onBeforeRequest(e=>{let t=a();t&&e?.url&&(e.url=rX(e.url,t))}),i.onAfterResponse((e,t)=>{let i=t?.headers?.get("Clerk-Db-Jwt");i&&o(i)});let n=(r=(e=new URL(window.location.href)).searchParams.get(rH)||"",rY(rQ(e)).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",rY(rQ(e))),r);if(n)return void o(n);if(s.get())return;let l=i.buildUrl({path:"/dev_browser"}),c=await fetch(l.toString(),{method:"POST"});if(!c.ok){let e=function(e=[]){return e.length>0?e.map(e=>new b(e)):[]}((await c.json()).errors);e[0]?t_(e[0].longMessage):t_()}let d=await c.json();o(d?.id)},getDevBrowserJWT:a,setDevBrowserJWT:o,removeDevBrowserJWT:l}}({frontendApi:e.frontendApi,fapiClient:t,cookieSuffix:r})}async setup(){return"production"===this.instanceType?this.setupProduction():this.setupDevelopment()}isSignedOut(){return this.clerk.loaded?!!this.clerk.user:0>=this.clientUat.get()}async handleUnauthenticatedDevBrowser(){this.devBrowser.clear(),await this.devBrowser.setup()}decorateUrlWithDevBrowserToken(e){let t=this.devBrowser.getDevBrowserJWT();if(!t)throw Error(`${tg} Missing dev browser jwt. Please contact support.`);return rX(e,t)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new ni,this.poller.startPollingForSessionToken(()=>this.refreshSessionToken()))}stopPollingForToken(){this.poller&&(this.poller.stopPollingForSessionToken(),this.poller=null)}refreshTokenOnFocus(){window.addEventListener("focus",()=>{"visible"===document.visibilityState&&this.refreshSessionToken({updateCookieImmediately:!0})})}async refreshSessionToken({updateCookieImmediately:e=!1}={}){if(this.clerk.session)try{let t=await this.clerk.session.getToken();e&&this.updateSessionCookie(t)}catch(e){return this.handleGetTokenError(e)}}updateSessionCookie(e){if(document.hasFocus()||this.isCurrentContextActive())return e||c()||e4.warn("Removing session cookie (offline)",{sessionId:this.clerk.session?.id},"authCookieService"),this.setActiveContextInStorage(),e?this.sessionCookie.set(e):this.sessionCookie.remove()}setClientUatCookieForDevelopmentInstances(){"production"!==this.instanceType&&this.inCustomDevelopmentDomain()&&this.clientUat.set(this.clerk.client)}inCustomDevelopmentDomain(){let e=this.clerk.frontendApi.replace("clerk.","");return!window.location.host.endsWith(e)}handleGetTokenError(e){if(O(e)||T(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(P(e))return void this.clerk.handleUnauthenticated().catch(eY);this.clerkEventBus.emit(f,"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()}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 nn{clerk;captchaChallenge;timers;constructor(e,t=new tE(e),i=iz()){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.__unstable__environment?.displayConfig?.captchaHeartbeat}clientBypass(){return this.clerk.client?.captchaBypass}intervalInMs(){return this.clerk.__unstable__environment?.displayConfig?.captchaHeartbeatIntervalMs??6e5}}let ns=["/client","/waitlist"];class na{async getBaseFapiProxyOptions(){let e=await tR.clerk.session?.getToken();if(!e)throw new U("No valid session token available",{code:"no_session_token"});return{pathPrefix:"",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},credentials:"same-origin"}}async getAll(e){return tR._fetch({...await this.getBaseFapiProxyOptions(),method:"GET",path:"/api_keys",search:t4({...e,subject:e?.subject??tR.clerk.organization?.id??tR.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new tM(e))}})}async create(e){return new tM(await tR._fetch({...await this.getBaseFapiProxyOptions(),path:"/api_keys",method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??tR.clerk.organization?.id??tR.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new tM(await tR._fetch({...await this.getBaseFapiProxyOptions(),method:"POST",path:`/api_keys/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let no=new Map;class nl{#N=!1;load(e){let t=e?.protectConfig;if(t?.loaders&&Array.isArray(t.loaders)&&0!==t.loaders.length&&!this.#N){if(n())for(let e of(this.#N=!0,t.loaders))try{this.applyLoader(e)}catch(e){B(`[protect] failed to apply loader: ${e}`)}}}applyLoader(e){if(void 0!==e.rollout){let t=e.rollout;if("number"!=typeof t||t<0)return void B(`[protect] loader rollout value is invalid: ${t}`);if(0===t||Math.random()>t)return}let t=e.type||"script",i=e.target||"body",r=document.createElement(t);if(e.attributes)for(let[t,i]of Object.entries(e.attributes))switch(typeof i){case"string":case"number":case"boolean":r.setAttribute(t,String(i));break;default:B(`[protect] loader attribute is invalid type: ${t}=${i}`)}switch(e.textContent&&"string"==typeof e.textContent&&(r.textContent=e.textContent),i){case"head":document.head.appendChild(r);break;case"body":document.body.appendChild(r);break;default:if(i?.startsWith("#")){let e=document.getElementById(i.substring(1));if(!e)return void B(`[protect] loader target element not found: ${i}`);e.appendChild(r);return}B(`[protect] loader target is invalid: ${i}`)}}}class nc{signInResourceSignal=t6;signInErrorSignal=t9;signInFetchSignal=t8;signInSignal=t7;signUpResourceSignal=ie;signUpErrorSignal=it;signUpFetchSignal=ii;signUpSignal=ir;__internal_effect=tY;__internal_computed=tX;constructor(){i2.on("resource:update",this.onResourceUpdated),i2.on("resource:error",this.onResourceError),i2.on("resource:fetch",this.onResourceFetch)}onResourceError=e=>{e.resource instanceof rE&&this.signInErrorSignal({error:e.error}),e.resource instanceof rz&&this.signUpErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof rE){if(nd(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof rz){if(nd(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}};onResourceFetch=e=>{e.resource instanceof rE&&this.signInFetchSignal({status:e.status}),e.resource instanceof rz&&this.signUpFetchSignal({status:e.status})}}function nd(e,t){return!t?.id&&e&&e.__internal_future?.hasBeenFinalized===!1}let nh="cannot_render_billing_disabled",nu="cannot_render_user_missing",np="cannot_render_organizations_disabled",nf="cannot_render_organization_missing",nm="cannot_render_single_session_enabled",ng={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 n_{static version="6.0.0-canary-core3.v20251203181537";static sdkMetadata={name:"@clerk/clerk-js",version:"6.0.0-canary-core3.v20251203181537"};static _billing;static _apiKeys;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new nc;internal_last_error=null;environment;#W;#D="";#$;#L;#j;#B;#J;#K=null;#V;#q;#G;#H="loading";#X=[];#Y=[];#Q={};#Z=null;#ee=0;#et=p();get __internal_queryClient(){return this.#W||Promise.all([s.e("662"),s.e("527")]).then(s.bind(s,250)).then(e=>e.QueryClient).then(e=>{this.#W||(this.#W=new e,this.#et.emit("queryClientStatus","ready"))}),this.#W?{__tag:"clerk-rq-client",client:this.#W}:void 0}__internal_getCachedResources;__internal_createPublicCredentials;__internal_getPublicCredentials;__internal_isWebAuthnSupported;__internal_isWebAuthnAutofillSupported;__internal_isWebAuthnPlatformAuthenticatorSupported;__internal_setActiveInProgress=!1;get publishableKey(){return this.#D}get version(){return n_.version}set sdkMetadata(e){n_.sdkMetadata=e}get sdkMetadata(){return n_.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#H}get isSatellite(){return!!tc()&&eX(this.#Q.isSatellite,new URL(window.location.href),!1)}get domain(){if(tc()){let e=function(e=""){return(e||"").replace(/^.+:\/\//,"")}(eX(this.#$,new URL(window.location.href)));if("production"===this.#G){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""}get proxyUrl(){if(tc()){let e=eX(this.#L,new URL(window.location.href));return!e||eN(e)||eW(e)||ts.throwInvalidProxyUrl({url:e}),e?eW(e)?new URL(e,window.location.origin).toString():e:""}return""}get frontendApi(){let e=es(this.publishableKey);return e?e.frontendApi:ts.throwInvalidPublishableKeyError({key:this.publishableKey})}get instanceType(){return this.#G}get isStandardBrowser(){return this.#Q.standardBrowser||!1}get billing(){return n_._billing||(n_._billing=new t5),n_._billing}get apiKeys(){return n_._apiKeys||(n_._apiKeys=new na),n_._apiKeys}__experimental_checkout(e){return this._checkout||(this._checkout=e=>(function(e,t){let i,r,n,s,{for:a,planId:o,planPeriod:l}=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 c=function(e){let{userId:t,orgId:i,planId:r,planPeriod:n}=e;return`${t}-${i||"user"}-${r}-${n}`}({userId:e.user?.id||"",orgId:"organization"===a?e.organization?.id:void 0,planId:o,planPeriod:l}),d=no.get(c);if(d)return d.signals.computedSignal();let h=(i=tH({resource:null}),r=tH({error:null}),n=tH({status:"idle"}),s=tX(()=>{let e=i().resource,t=r().error,s=n().status;return{errors:is(t,{}),fetchStatus:s,checkout:e}}),{resourceSignal:i,errorSignal:r,fetchSignal:n,computedSignal:s}),u=new il(h,{..."organization"===a?{orgId:e.organization?.id}:{},planId:o,planPeriod:l});return no.set(c,{resource:u,signals:h}),h.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#Q[e]}get isSignedIn(){return this?.session?.status!=="pending"&&!!this.session}constructor(e,t){if(!(e=(e||"").trim()))return ts.throwMissingPublishableKeyError();const i=es(e);if(!i)return ts.throwInvalidPublishableKeyError({key:e});this.#$=t?.domain,this.#L=t?.proxyUrl,this.environment=i6.getInstance(),this.#G=i.instanceType,this.#D=e,this.#q=function(e){let t=[],i=[];async function r(e){for await(let i of["undefined"!=typeof window&&window.__unstable__onBeforeRequest,...t].filter(e=>e))if(await i(e)===!1)return!1;return!0}async function n(e,t){for await(let r of["undefined"!=typeof window&&window.__unstable__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:s}){let a=new URLSearchParams(n);return a.append("__clerk_api_version","2025-11-10"),a.append("_clerk_js_version","6.0.0-canary-core3.v20251203181537"),s&&a.append("rotating_token_nonce",s),e.domain&&"development"===e.instanceType&&e.isSatellite&&a.append("__domain",e.domain),t&&"GET"!==t&&"POST"!==t&&a.append("_method",t),i&&!ns.some(e=>i.startsWith(e))&&r&&a.append("_clerk_session_id",r),ed([...a.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)),eg({base:n.origin,pathname:`${a}/${r}${i}`,search:s(t)},{stringify:!1})}let n="production"===e.instanceType?e.domain:"";return eg({base:`https://${n||e.frontendApi}`,pathname:`${r}${i}`,search:s(t)},{stringify:!1})}async function o(t,i){let s,o={...t},{method:c="GET",body:d}=o;!d||"object"!=typeof d||d instanceof FormData||(o.body=function(e){if(!e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype)return e;let t={};for(let[i,r]of Object.entries(e))void 0!==r&&(t[i]=r);return t}(d)),o.url=a({...o,sessionId:e.getSessionId()}),o.headers=new Headers(o.headers),"GET"===c||d instanceof FormData||o.headers.has("content-type")||o.headers.set("content-type","application/x-www-form-urlencoded"),"application/x-www-form-urlencoded"===o.headers.get("content-type")&&(o.body=d?ed(d,{keyEncoder:q}):d);let h=await r(o),u="GET"===c?"GET":"POST",p=o.url,f={...o,method:u,credentials:o.credentials||"include"};try{if(h){let e=i?.fetchMaxTries??(l()?4:11);s=await e8(()=>fetch(p,f),{retryImmediately:!0,initialDelay:700,maxDelayBetweenRetries:5e3,shouldRetry:(t,i)=>"GET"===u&&i<e,onBeforeRetry:e=>{p.searchParams.set("_clerk_retry_attempt",e.toString())}})}else s=new Response("{}",o)}catch(t){let e=p.toString();e4.error("network error",{error:t,url:e,method:c},"fapiClient");throw Error(`${tg} Network error at "${e}" - ${t}. Please try again.`)}let m=204!==s.status?await s.json():null,g=Object.assign(s,{payload:m});return s.ok||e4.error("request failed",{method:c,path:o.path,status:s.status},"fapiClient"),await n(o,g),g}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,proxyUrl:this.proxyUrl}),this.#et.emit(f,"loading"),this.#et.prioritizedOn(f,e=>this.#H=e),tR.clerk=this,this.#B=new nl}getFapiClient=()=>this.#q;load=async e=>{if(e4.info("load() start",{},"clerk"),!this.loaded){if("development"===this.#G&&B("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.#Q=this.#ei(e),this.#Q.clerkUiCtor&&(this.#V=Promise.resolve(this.#Q.clerkUiCtor).then(e=>new e(()=>this,()=>this.environment,this.#Q,new te))),"development"===this.#G&&(this.#Q.routerPush||this.#Q.routerReplace)&&(!this.#Q.routerPush||!this.#Q.routerReplace)){let e=this.#Q.routerPush?"routerReplace":"routerPush";B(`Clerk: Both \`routerPush\` and \`routerReplace\` need to be defined, but \`${e}\` is not defined. This may cause issues with navigation in your application.`)}i2.on(i3,()=>{this.#er(this.session),this.#en()}),this.#Q.sdkMetadata&&(n_.sdkMetadata=this.#Q.sdkMetadata),!1!==this.#Q.telemetry&&(this.telemetry=new eB({clerkVersion:n_.version,samplingRate:1,perEventSampling:!this.#Q.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#Q.telemetry}),this.#Q.appearance&&this.telemetry.record({event:"THEME_USAGE",eventSamplingRate:1,payload:function(e){let t;if(!e||"object"!=typeof e)return{};let i=e.theme||e.baseTheme;if(!i)return{};if(Array.isArray(i))for(let e of i){let i=eH(e);if(i){t=i;break}}else t=eH(i);return{themeName:t}}(this.#Q.appearance)}));try{this.#Q.standardBrowser?await this.#es():await this.#ea();let e=this.#Q.telemetry,t=!1!==e&&!e?.disabled,i=!!this.#Q.__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(e0)return;let{enabled:t=!1,...i}=e;t&&(eQ=!0,e0=!0,e2(i))}({enabled:!0,...a?{logLevel:a}:{},...t&&this.telemetry?{telemetryCollector:this.telemetry}:{}}),this.#B?.load(this.environment),e4.info("load() complete",{},"clerk")}catch(e){throw this.#et.emit(f,"error"),e4.error("load() failed",{error:e},"clerk"),e}}};#eo(){let e;return!!(!this.#Q.signUpUrl&&this.#Q.signInUrl&&(e=this.#Q.signInUrl,!ec.test(e)))}signOut=async(e,t)=>{if(!this.client||0===this.client.sessions.length)return;let i="undefined"!=typeof window&&"function"==typeof window.__unstable__onBeforeSetActive?window.__unstable__onBeforeSetActive:eY,r="undefined"!=typeof window&&"function"==typeof window.__unstable__onAfterSetActive?window.__unstable__onAfterSetActive:eY,n=e&&"object"==typeof e?e:t||{},s=n?.redirectUrl||this.buildAfterSignOutUrl();e4.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=tt(this.#Q.standardBrowser);i2.emit(i0,null),this.#el(),await e.track(async()=>{a?await a():await this.navigate(s)}),e.isUnloading()||(this.#er(),this.#en(),await r())};if(await i(),!n.sessionId||1===this.client.signedInSessions.length){this.#Q.experimental?.persistClient??!0?await this.client.removeSessions():await this.client.destroy(),await o(),e4.info("signOut() complete",{redirectUrl:e_(s)},"clerk");return}let l=this.client.signedInSessions.find(e=>e.id===n.sessionId),c=l?.id&&this.session?.id===l.id;await l?.remove(),c&&(await o(),e4.info("signOut() complete",{redirectUrl:e_(s)},"clerk"))};openGoogleOneTap=e=>{this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openModal("googleOneTap",e||{})),this.telemetry?.record(eG("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#V?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(x(this,this.environment)){if("development"===this.#G)throw new U(eR.cannotOpenSignInOrSignUp,{code:nm});return}this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openModal("signIn",e||{}));let t={withSignUp:e?.withSignUp??this.#eo()};this.telemetry?.record(eG("SignIn",e,t))};closeSignIn=()=>{this.#V?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(R(this,this.environment)){if("development"===this.#G)throw new U(eR.cannotRenderAnyBillingComponent("Checkout"),{code:nh});return}if(!this.user){if("development"===this.#G)throw new U(eR.cannotOpenCheckout,{code:nu});return}this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openDrawer("checkout",e||{}))};__internal_closeCheckout=()=>{this.#V?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("checkout"))};__internal_openPlanDetails=e=>{if(R(this,this.environment)){if("development"===this.#G)throw new U(eR.cannotRenderAnyBillingComponent("PlanDetails"),{code:nh});return}this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openDrawer("planDetails",e||{})),this.telemetry?.record(eG("PlanDetails",e))};__internal_closePlanDetails=()=>{this.#V?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("planDetails"))};__internal_openSubscriptionDetails=e=>{this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openDrawer("subscriptionDetails",e||{}))};__internal_closeSubscriptionDetails=()=>{this.#V?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("subscriptionDetails"))};__internal_openReverification=e=>{if(!this.user){if("development"===this.#G)throw new U(eR.cannotOpenUserProfile,{code:nu});return}this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openModal("userVerification",e||{})),this.telemetry?.record(eG("UserVerification",e))};__internal_closeReverification=()=>{this.#V?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userVerification"))};__internal_attemptToEnableEnvironmentSetting=e=>{let{for:t,caller:i}=e;if(this.user||"development"!==this.#G||B(`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.#G&&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.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openModal("enableOrganizationsPrompt",e||{})));__internal_closeEnableOrganizationsPrompt=()=>(this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(e=>e.closeModal("enableOrganizationsPrompt")));__internal_openBlankCaptchaModal=()=>(this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(e=>e.openModal("blankCaptcha",{})));__internal_closeBlankCaptchaModal=()=>(this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(e=>e.closeModal("blankCaptcha")));__internal_loadStripeJs=async()=>{let{loadStripe:e}=await s.e("279").then(s.bind(s,5608));return e};openSignUp=e=>{if(x(this,this.environment)){if("development"===this.#G)throw new U(eR.cannotOpenSignInOrSignUp,{code:nm});return}this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openModal("signUp",e||{})),this.telemetry?.record(eG("SignUp",e))};closeSignUp=()=>{this.#V?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signUp"))};openUserProfile=e=>{if(!this.user){if("development"===this.#G)throw new U(eR.cannotOpenUserProfile,{code:nu});return}this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openModal("userProfile",e||{}));let t=(e?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(eG("UserProfile",e,t))};closeUserProfile=()=>{this.#V?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userProfile"))};openOrganizationProfile=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new U(eR.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:np})}});if(t){if(!this.organization){if("development"===this.#G)throw new U(eR.cannotRenderComponentWhenOrgDoesNotExist,{code:nf});return}this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openModal("organizationProfile",e||{})),this.telemetry?.record(eG("OrganizationProfile",e))}};closeOrganizationProfile=()=>{this.#V?.then(e=>e.ensureMounted()).then(e=>e.closeModal("organizationProfile"))};openCreateOrganization=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new U(eR.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:np})}});t&&(this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openModal("createOrganization",e||{})),this.telemetry?.record(eG("CreateOrganization",e)))};closeCreateOrganization=()=>{this.#V?.then(e=>e.ensureMounted()).then(e=>e.closeModal("createOrganization"))};openWaitlist=e=>{this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openModal("waitlist",e||{})),this.telemetry?.record(eG("Waitlist",e))};closeWaitlist=()=>{this.#V?.then(e=>e.ensureMounted()).then(e=>e.closeModal("waitlist"))};mountSignIn=(e,t)=>{this.assertComponentsReady(this.#V);let i="SignIn";this.#V.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:i,appearanceKey:"signIn",node:e,props:t}));let r={withSignUp:t?.withSignUp??this.#eo()};this.telemetry?.record(eq(i,t,r))};unmountSignIn=e=>{this.#V?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserAvatar=(e,t)=>{this.assertComponentsReady(this.#V);let i="UserAvatar";this.#V.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:i,appearanceKey:"userAvatar",node:e,props:t})),this.telemetry?.record(eq(i,t))};unmountUserAvatar=e=>{this.#V?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountSignUp=(e,t)=>{this.assertComponentsReady(this.#V);let i="SignUp";this.#V.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:i,appearanceKey:"signUp",node:e,props:t})),this.telemetry?.record(eq(i,t))};unmountSignUp=e=>{this.#V?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserProfile=(e,t)=>{if(!this.user){if("development"===this.#G)throw new U(eR.cannotRenderComponentWhenUserDoesNotExist,{code:nu});return}this.assertComponentsReady(this.#V);let i="UserProfile";this.#V.then(e=>e.ensureMounted()).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(eq(i,t,r))};unmountUserProfile=e=>{this.#V?.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 U(eR.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:np})}});if(!i)return;let r=!!this.user;if(!this.organization&&r){if("development"===this.#G)throw new U(eR.cannotRenderComponentWhenOrgDoesNotExist,{code:nf});return}this.assertComponentsReady(this.#V);let n="OrganizationProfile";this.#V.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:n,appearanceKey:"userProfile",node:e,props:t})),this.telemetry?.record(eq(n,t))};unmountOrganizationProfile=e=>{this.#V?.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 U(eR.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:np})}});if(!i)return;this.assertComponentsReady(this.#V);let r="CreateOrganization";this.#V.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:r,appearanceKey:"createOrganization",node:e,props:t})),this.telemetry?.record(eq(r,t))};unmountCreateOrganization=e=>{this.#V?.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 U(eR.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:np})}});if(!i)return;this.assertComponentsReady(this.#V);let r="OrganizationSwitcher";this.#V.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:r,appearanceKey:"organizationSwitcher",node:e,props:t})),this.telemetry?.record(eq(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationSwitcher=e=>{this.#V?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__experimental_prefetchOrganizationSwitcher=()=>{this.assertComponentsReady(this.#V),this.#V.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 U(eR.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:np})}});if(!i)return;this.assertComponentsReady(this.#V);let r="OrganizationList";this.#V.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:r,appearanceKey:"organizationList",node:e,props:t})),this.telemetry?.record(eq(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationList=e=>{this.#V?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserButton=(e,t)=>{this.assertComponentsReady(this.#V);let i="UserButton";this.#V.then(e=>e.ensureMounted()).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(eq(i,t,r))};unmountUserButton=e=>{this.#V?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountWaitlist=(e,t)=>{this.assertComponentsReady(this.#V);let i="Waitlist";this.#V.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:i,appearanceKey:"waitlist",node:e,props:t})),this.telemetry?.record(eq(i,t))};unmountWaitlist=e=>{this.#V?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountPricingTable=(e,t)=>{if(R(this,this.environment)){if("development"===this.#G)throw new U(eR.cannotRenderAnyBillingComponent("PricingTable"),{code:nh});return}this.assertComponentsReady(this.#V);let i="PricingTable";this.#V.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:i,appearanceKey:"pricingTable",node:e,props:t})),this.telemetry?.record(eq(i,t))};unmountPricingTable=e=>{this.#V?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__internal_mountOAuthConsent=(e,t)=>{this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:"OAuthConsent",appearanceKey:"__internal_oauthConsent",node:e,props:t}))};__internal_unmountOAuthConsent=e=>{this.#V?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountAPIKeys=(e,t)=>{let i;if(B("Clerk: <APIKeys /> component is in early access and not yet recommended for production use."),z(this,i=this.environment)&&M(this,i)){if("development"===this.#G)throw new U(eR.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&M(this,this.environment)){if("development"===this.#G)throw new U(eR.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if(z(this,this.environment)){if("development"===this.#G)throw new U(eR.cannotRenderAPIKeysComponentForUserWhenDisabled,{code:"cannot_render_api_keys_user_disabled"});return}this.assertComponentsReady(this.#V);let r="APIKeys";this.#V.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:r,appearanceKey:"apiKeys",node:e,props:t})),this.telemetry?.record(eq(r,t))};unmountAPIKeys=e=>{this.#V?.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 U(eR.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:np})}});if(!i)return;this.assertComponentsReady(this.#V);let r="TaskChooseOrganization";this.#V.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:r,appearanceKey:"taskChooseOrganization",node:e,props:t})),this.telemetry?.record(eq(r,t))};unmountTaskChooseOrganization=e=>{this.#V?.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,e4.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 e4.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 e4.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="undefined"!=typeof window&&"function"==typeof window.__unstable__onBeforeSetActive?window.__unstable__onBeforeSetActive:eY,l="undefined"!=typeof window&&"function"==typeof window.__unstable__onAfterSetActive?window.__unstable__onAfterSetActive:eY,d=void 0===n?this.session:n;d?.status==="pending"&&(s={...this.#Q,...e},a=["taskUrls","navigate"],Object.keys(s).some(e=>a.includes(e))||B('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 h=void 0!==t;if(d&&h){let e="string"==typeof t?t:t?.id;if("string"==typeof e&&e.startsWith("org_"))d.lastActiveOrganizationId=e||null;else{let t=d.user.organizationMemberships.find(t=>t.organization.slug===e),i=t?.organization.id||null,r=null===i;if(this.environment?.organizationSettings?.forceOrganizationSelection&&r)return;d.lastActiveOrganizationId=i}}d?.status!=="pending"&&await o(null===d?"sign-out":void 0),(tc()&&globalThis.document.hasFocus()||!this.#Q.standardBrowser)&&(await this.#ec(d),d=this.#ed(d?.id)),await d?.getToken()||(c()||e4.warn("Token is null when setting active session (offline)",{sessionId:d?.id},"clerk"),i2.emit(iZ,{token:null}));let u=tt(this.#Q.standardBrowser),p=d?.status==="pending"&&d?.currentTask&&this.#Q.taskUrls?.[d?.currentTask.key];if((i||p||r)&&await u.track(async()=>{if(this.client){if(d?.status!=="pending"&&this.#el(),p){let e=i?eg({base:p,hashSearchParams:{redirectUrl:i}},{stringify:!0}):p;await this.navigate(e)}else if(r&&d)await r({session:d});else if(i){if(this.client.isEligibleForTouch()){let e=new URL(i,window.location.href),t=this.buildUrlWithAuth(this.client.buildTouchUrl({redirectUrl:e}));await this.navigate(t)}await this.navigate(i)}}}),u.isUnloading())return;this.#er(d),this.#en(),d?.status!=="pending"&&await l()}finally{this.__internal_setActiveInProgress=!1}};addListener=e=>{var t;let i;return t=e,e=e=>{var r;i||={...e},t(i={...{client:rG((r=i).client,e.client),session:rG(r.session,e.session),user:rG(r.user,e.user),organization:rG(r.organization,e.organization)}})},this.#X.push(e),this.client&&e({client:this.client,session:this.session,user:this.user,organization:this.organization}),()=>{this.#X=this.#X.filter(t=>t!==e)}};on=(...e)=>{this.#et.on(...e)};off=(...e)=>{this.#et.off(...e)};__internal_addNavigationListener=e=>(this.#Y.push(e),()=>{this.#Y=this.#Y.filter(t=>t!==e)});navigate=async(e,t)=>{if(!e||!tc())return;setTimeout(()=>{this.#eh()},0);let i=new URL(e,window.location.href);this.#eu.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.#Q.routerReplace?this.#Q.routerReplace:this.#Q.routerPush;if(e4.info(`Clerk is navigating to: ${i}`),this.#Q.routerDebug&&console.log(`Clerk is navigating to: ${i}`),"null"!==i.origin&&i.origin!==window.location.origin||!r)return void eF(i);let n={...t?.metadata?{__internal_metadata:t?.metadata}:{},windowNavigate:eF};return await r(e_(i),n)};buildUrlWithAuth(e){if("production"===this.#G)return e;let t=new URL(e,window.location.origin);return t.origin!==window.location.origin&&this.#j?this.#j.decorateUrlWithDevBrowserToken(t).href:t.href}buildSignInUrl(e){return this.#ep("signInUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildSignUpUrl(e){return this.#ep("signUpUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildUserProfileUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.userProfileUrl):""}buildHomeUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.homeUrl):""}buildAfterSignInUrl({params:e}={}){return this.buildUrlWithAuth(new eS(this.#Q,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eS(this.#Q,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#Q.afterSignOutUrl?this.buildUrlWithAuth(this.#Q.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#Q.newSubscriptionRedirectUrl?this.#Q.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?eg({base:this.#Q.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#Q.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#Q.afterMultiSessionSingleSignOutUrl):this.#Q.signInUrl?this.buildUrlWithAuth(eg({base:this.#Q.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.#Q.taskUrls?.[t.key];return i||eg({base:this.buildSignInUrl(e),hashPath:eT(t)},{stringify:!0})}#ef=async()=>{if(!tc())return;let e=new URLSearchParams({[F]:"true"}),t=eI(W);t&&eN(t)||function(){throw Error(`${tg} Invalid redirect_url. A valid http or https url should be used for the redirection.`)}();let i=eg({base:eI(W),searchParams:e},{stringify:!0});return this.navigate(this.buildUrlWithAuth(i))};redirectWithAuth=async e=>{if(tc())return this.navigate(this.buildUrlWithAuth(e))};redirectToSignIn=async e=>{if(tc())return this.navigate(this.buildSignInUrl(e))};redirectToSignUp=async e=>{if(tc())return this.navigate(this.buildSignUpUrl(e))};redirectToUserProfile=async()=>{if(tc())return this.navigate(this.buildUserProfileUrl())};redirectToCreateOrganization=async()=>{if(tc())return this.navigate(this.buildCreateOrganizationUrl())};redirectToOrganizationProfile=async()=>{if(tc())return this.navigate(this.buildOrganizationProfileUrl())};redirectToAfterSignIn=async()=>{if(tc())return this.navigate(this.buildAfterSignInUrl())};redirectToAfterSignUp=async()=>{if(tc())return this.navigate(this.buildAfterSignUpUrl())};redirectToAfterSignOut=async()=>{if(tc())return this.navigate(this.buildAfterSignOutUrl())};redirectToWaitlist=async()=>{if(tc())return this.navigate(this.buildWaitlistUrl())};redirectToTasks=async e=>{if(tc())return this.navigate(this.buildTasksUrl(e))};handleEmailLinkVerification=async(e,t)=>{if(!this.client)return;let i=eI("__clerk_status");if("expired"===i)throw new S("expired");if("client_mismatch"===i)throw new S("client_mismatch");if("verified"!==i)throw new S("failed");let r=eI("__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):eY;return o?this.setActive({session:r,redirectUrl:e.redirectUrlComplete}):l?d():("function"==typeof e.onVerifiedOnOtherDevice&&e.onVerifiedOnOtherDevice(),null)};handleGoogleOneTapCallback=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)):this.navigate(this.buildUrlWithAuth(e));return this._handleRedirectCallback(t,{signUp:a,signIn:s,navigate:o})};_handleRedirectCallback=async(e,{signIn:t,signUp:i,navigate:r})=>{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:n}=this.environment,{firstFactorVerification:s}=t,{externalAccount:a}=i.verifications,o={status:i.status,missingFields:i.missingFields,externalAccountStatus:a.status,externalAccountErrorCode:a.error?.code,externalAccountSessionId:a.error?.meta?.sessionId,sessionId:i.createdSessionId},l={status:t.status,firstFactorVerificationStatus:s.status,firstFactorVerificationErrorCode:s.error?.code,firstFactorVerificationSessionId:s.error?.meta?.sessionId,sessionId:t.createdSessionId},c=e=>()=>r(e),d=c(e.signInUrl||n.signInUrl),h=c(e.signUpUrl||n.signUpUrl),u=c(e.firstFactorUrl||eg({base:n.signInUrl,hashPath:"/factor-one"},{stringify:!0})),p=c(e.secondFactorUrl||eg({base:n.signInUrl,hashPath:"/factor-two"},{stringify:!0})),f=c(e.resetPasswordUrl||eg({base:n.signInUrl,hashPath:"/reset-password"},{stringify:!0})),m=new eS(this.#Q,e),g=c(e.continueSignUpUrl||eg({base:n.signUpUrl,hashPath:"/continue"},{stringify:!0})),_=({missingFields:t})=>t.length?g():(({signUp:e,verifyEmailPath:t,verifyPhonePath:i,continuePath:r,navigate:n,handleComplete:s,redirectUrl:a="",redirectUrlComplete:o="",oidcPrompt:l})=>{if("complete"===e.status)return s&&s();if("missing_requirements"===e.status){if(e.missingFields.some(e=>"enterprise_sso"===e))return e.authenticateWithRedirect({strategy:"enterprise_sso",redirectUrl:a,redirectUrlComplete:o,continueSignUp:!0,oidcPrompt:l});let s=eP();if(e.unverifiedFields?.includes("email_address")&&t)return n(t,{searchParams:s});if(e.unverifiedFields?.includes("phone_number")&&i)return n(i,{searchParams:s});if(r)return n(r,{searchParams:s})}})({signUp:i,verifyEmailPath:e.verifyEmailAddressUrl||eg({base:n.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),verifyPhonePath:e.verifyPhoneNumberUrl||eg({base:n.signUpUrl,hashPath:"/verify-phone-number"},{stringify:!0}),navigate:r}),b=e.signInUrl||n.signInUrl,y=e.signUpUrl||n.signUpUrl,w=async({session:e,baseUrl:t,redirectUrl:i})=>{e.currentTask?await eE(e,{baseUrl:t,navigate:this.navigate}):await this.navigate(i)};if("complete"===l.status)return this.setActive({session:l.sessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:b,redirectUrl:m.getAfterSignInUrl()})}});if("transferable"===o.externalAccountStatus&&"external_account_exists"===o.externalAccountErrorCode){let e=await t.create({transfer:!0});switch(e.status){case"complete":return this.setActive({session:e.createdSessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:y,redirectUrl:m.getAfterSignInUrl()})}});case"needs_first_factor":return u();case"needs_second_factor":return p();case"needs_new_password":return f();default:tb("sign in")}}let v="user_locked"===o.externalAccountErrorCode,k="user_locked"===l.firstFactorVerificationErrorCode;if(v)return h();if(k)return d();if("needs_first_factor"===l.status&&!t.supportedFirstFactors?.every(e=>"enterprise_sso"===e.strategy))return u();if("needs_new_password"===l.status)return f();if("transferable"===l.firstFactorVerificationStatus){if(!1===e.transferable)return d();let t=await i.create({transfer:!0});switch(t.status){case"complete":return this.setActive({session:t.createdSessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:y,redirectUrl:m.getAfterSignUpUrl()})}});case"missing_requirements":return _({missingFields:t.missingFields});default:tb("sign in")}}if("complete"===o.status)return this.setActive({session:o.sessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:y,redirectUrl:m.getAfterSignUpUrl()})}});if("needs_second_factor"===l.status)return p();let S=("failed"===o.externalAccountStatus||"unverified"===o.externalAccountStatus)&&"identifier_already_signed_in"===o.externalAccountErrorCode&&o.externalAccountSessionId,U="failed"===l.firstFactorVerificationStatus&&"identifier_already_signed_in"===l.firstFactorVerificationErrorCode&&l.firstFactorVerificationSessionId;if(S||U){let e=l.firstFactorVerificationSessionId||o.externalAccountSessionId;if(e)return this.setActive({session:e,navigate:async({session:e})=>{await w({session:e,baseUrl:S?y:b,redirectUrl:m.getAfterSignInUrl()})}})}return(e=>{let{externalAccount:t}=e.verifications;return!!t.error})(i)?h():"verified"===o.externalAccountStatus&&"missing_requirements"===o.status?_({missingFields:i.missingFields}):this.session?.currentTask?void await this.redirectToTasks({redirectUrl:this.buildAfterSignInUrl()}):d()};handleRedirectCallback=async(e={},t)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:i,signUp:r}=this.client,n=e=>t&&"function"==typeof t?t(e):this.navigate(e);return this._handleRedirectCallback(e,{signUp:r,signIn:i,navigate:n})};handleUnauthenticated=async(e={broadcast:!0})=>{if(this.client&&this.session)try{let t=await iP.getOrCreateInstance().fetch();if(this.updateClient(t),this.session)return;return e.broadcast&&i2.emit(i0,null),this.setActive({session:null})}catch(e){if(O(e)&&[403,500].includes(e.status))return this.setActive({session:null});throw e}};authenticateWithGoogleOneTap=async e=>this.client?.signIn.create({strategy:"google_one_tap",token:e.token}).catch(t=>{if(O(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"})};authenticateWithWeb3=async({redirectUrl:e,signUpContinueUrl:t,customNavigate:i,unsafeMetadata:r,strategy:n,legalAccepted:s,secondFactorUrl:a})=>{let o,l;if(!this.client||!this.environment)return;let{displayConfig:c}=this.environment,d=n.replace("web3_","").replace("_signature",""),h=await th().getWeb3Identifier({provider:d});switch(d){case"metamask":o=th().generateSignatureWithMetamask;break;case"base":o=th().generateSignatureWithBase;break;case"coinbase_wallet":o=th().generateSignatureWithCoinbaseWallet;break;default:o=th().generateSignatureWithOKXWallet}let u=e=>()=>i&&"function"==typeof i?i(e):this.navigate(e),p=u(a||eg({base:c.signInUrl,hashPath:"/factor-two"},{stringify:!0})),f=u(t||eg({base:c.signUpUrl,hashPath:"/continue"},{stringify:!0}));try{l=await this.client.signIn.authenticateWithWeb3({identifier:h,generateSignature:o,strategy:n})}catch(e){if(tn(e,"form_identifier_not_found"))l=await this.client.signUp.authenticateWithWeb3({identifier:h,generateSignature:o,unsafeMetadata:r,strategy:n,legalAccepted:s}),t&&"missing_requirements"===l.status&&"verified"===l.verifications.web3Wallet.status&&await f();else throw e}let m=async({session:e,redirectUrl:t})=>{e.currentTask?await eE(e,{baseUrl:c.signInUrl,navigate:this.navigate}):await this.navigate(t)};switch(l.status){case"needs_second_factor":await p();break;case"complete":l.createdSessionId&&await this.setActive({session:l.createdSessionId,navigate:async({session:t})=>{await m({session:t,redirectUrl:e??this.buildAfterSignInUrl()})}});break;default:return}};createOrganization=async({name:e,slug:t})=>rs.create({name:e,slug:t});getOrganization=async e=>rs.get(e);joinWaitlist=async({emailAddress:e})=>rK.join({emailAddress:e});updateEnvironment(e){this.environment=e}__internal_setCountry=e=>{this.__internal_country||(this.__internal_country=e)};get __internal_last_error(){let e=this.internal_last_error;return this.internal_last_error=null,e}set __internal_last_error(e){this.internal_last_error=e}updateClient=e=>{if(!this.client){let t=this.#Q.selectInitialSession?this.#Q.selectInitialSession(e):this.#em(e);this.#er(t)}if(this.client=e,this.session){let e=this.#ed(this.session.id);"active"===this.session.status&&e?.status==="pending"&&("undefined"!=typeof window&&"function"==typeof window.__unstable__onAfterSetActive?window.__unstable__onAfterSetActive:eY)(),this.#er(e),this.session?.lastActiveToken||c()||e4.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),i2.emit(iZ,{token:this.session?.lastActiveToken})}this.#en()};get __unstable__environment(){return this.environment}__unstable__setEnvironment=async e=>{this.environment=new i6(e)};__unstable__onBeforeRequest=e=>{this.#q.onBeforeRequest(e)};__unstable__onAfterResponse=e=>{this.#q.onAfterResponse(e)};__unstable__updateProps=e=>{let t={...e,options:this.#ei({...this.#Q,...e.options})};return this.#V?.then(e=>e.ensureMounted()).then(e=>e.updateProps(t))};__internal_navigateWithError(e,t){return this.__internal_last_error=t,this.navigate(e)}#eg=()=>{let e=new URLSearchParams({[W]:window.location.href});return eg({base:this.#Q.signInUrl,searchParams:e},{stringify:!0})};#e_=()=>{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()||""};#eb=()=>"true"!==eI(F)&&!!this.isSatellite&&!!this.#j?.isSignedOut();#ey=()=>"production"!==this.#G&&!this.isSatellite&&!!eI(W);#ew=async()=>{"development"===this.instanceType?await this.navigate(this.#eg()):"production"===this.instanceType&&await this.navigate(this.#e_())};#ev=(e,t)=>{let i;try{i=new URL(e)}catch{throw Error(`${tg} The signInUrl needs to have a absolute url format.`)}i.origin===t&&function(){throw Error(`${tg} The signInUrl needs to be on a different origin than your satellite application.`)}()};#ek=()=>{this.isSatellite&&("development"!==this.#G||this.#Q.signInUrl||function(){throw Error(`${tg} Missing signInUrl. A satellite application needs to specify the signInUrl for development instances.`)}(),this.proxyUrl||this.domain||function(){throw Error(`${tg} Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl.`)}(),this.#Q.signInUrl&&this.#ev(this.#Q.signInUrl,window.location.origin))};#es=async()=>{if(this.#j=await nr.create(this,this.#q,this.#G,this.#et),this.#ek(),this.#eb())return void await this.#ew();if(this.#ey())return void await this.#ef();this.#Z=(()=>{if(!n())return{onPageFocus:eY};let e=[];return window.addEventListener("focus",()=>{"visible"===document.visibilityState&&e.forEach(e=>e())}),{onPageFocus:t=>{e.push(t)}}})(),"undefined"!=typeof BroadcastChannel&&(this.#K=new BroadcastChannel("clerk")),this.#eS();let e=function(e=window.location.hostname){if(!e)return!1;let t=ef.get(e);void 0===t&&(t=Z.some(t=>e.startsWith("accounts.")&&e.endsWith(t))||ee.some(t=>e.endsWith(t)&&!e.endsWith(".clerk"+t)),ef.set(e,t));return t}(window?.location.hostname),t="development"===this.#G&&!e,i=0,r=0;for(;r<2;){r++;try{var s;let e=i6.getInstance().fetch({touch:t}).then(e=>this.updateEnvironment(e)).catch(()=>{++i;let e=tm.getItem(tu,null);e&&this.updateEnvironment(new i6(e))}),r=async()=>iP.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(async e=>{if(P(e))throw e;++i;let t=this.#j?.getSessionCookie(),r=function(e){let t;try{t=new rN({jwt:e||"",object:"token",id:void 0})}catch{t=null}if(iP.clearInstance(),!t?.jwt)return iP.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}=rw(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=>Number.parseInt(e.trim(),10)).map(e=>e.toString(2).padStart(i.length,"0").split("").map(e=>Number.parseInt(e,10)).reverse()).filter(Boolean)}})({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++)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,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 iP.getOrCreateInstance(c)}(t);return this.updateClient(r),this.#j?.stopPollingForToken(),await this.session?.getToken({skipCache:!0}).catch(()=>null).finally(()=>{this.#j?.startPollingForToken()}),null}),[,n]=await (s=[e,r()],Promise.all(Array.from(s).map(e=>e.then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e})))));if("rejected"===n.status){let e=n.reason;if(tn(e,"requires_captcha"))await r();else throw e}if(this.#j?.setClientUatCookieForDevelopmentInstances(),await this.#eU())return;break}catch(e){if(tn(e,"dev_browser_unauthenticated"))await this.#j.handleUnauthenticatedDevBrowser();else if(!c())return void console.warn(e);else throw e}r>=2&&function(){throw Error(`${tg} Something went wrong initializing Clerk.`)}()}this.#J=new nn(this),this.#J.start(),this.#eA(),this.#eI(),this.#eC(),this.#et.emit(f,i>0?"degraded":"ready")};shouldFallbackToCachedResources=()=>!!this.__internal_getCachedResources;#ea=async()=>{let e,t,i=this.shouldFallbackToCachedResources()?1:void 0,r=0;try{[e,t]=await Promise.all([i6.getInstance().fetch({touch:!1,fetchMaxTries:i}),iP.getOrCreateInstance().fetch({fetchMaxTries:i})])}catch(i){if(T(i)&&"network_error"===i.code&&this.shouldFallbackToCachedResources()){let i=await this.__internal_getCachedResources?.();e=new i6(i?.environment),iP.clearInstance(),t=iP.getOrCreateInstance(i?.client),++r}else throw i}this.updateClient(t),this.updateEnvironment(e),this.#et.emit(f,r>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,t]=await Promise.all([i6.getInstance().fetch({touch:!1,fetchMaxTries:1}),iP.getOrCreateInstance().fetch({fetchMaxTries:1})]);this.updateClient(t),this.updateEnvironment(e),this.#en()};#em=e=>{if(e.lastActiveSessionId){let t=e.signedInSessions.find(t=>t.id===e.lastActiveSessionId);if(t)return t}return e.signedInSessions[0]||null};#eS=()=>{n()&&(this.#Z?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#ee>Date.now())&&(this.#ee=Date.now()+5e3,this.#Q.touchSession&&this.#ec(this.session))}),this.#K?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),i2.on(i0,()=>{this.#K?.postMessage({type:"signout"})}),i2.on(i1,()=>{tm.setItem(tu,this.environment?.__internal_toSnapshot(),864e5)}))};#ec=async e=>{if(!e)return Promise.resolve();await e.touch().catch(e=>{P(e)&&this.handleUnauthenticated()})};#en=()=>{if(this.client)for(let e of this.#X)e({client:this.client,session:this.session,user:this.user,organization:this.organization})};#eh=()=>{for(let e of this.#Y)e()};#el=()=>{this.session=void 0,this.organization=void 0,this.user=void 0,this.#en()};#eP=()=>(this.session?.user.organizationMemberships||[]).map(e=>e.organization).find(e=>e.id===this.session?.lastActiveOrganizationId)||null;#er=e=>{this.session=e||null,this.organization=this.#eP(),this.user=this.session?this.session.user:null};#ed=e=>this.client?.signedInSessions.find(t=>t.id===e)||null;#eI=()=>{this.addListener(({session:e})=>{e?.actor&&this.#V?.then(e=>e.ensureMounted()).then(e=>e.mountImpersonationFab())})};#eC=()=>{this.#Q.__internal_keyless_claimKeylessApplicationUrl&&this.#V?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#Q.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#Q.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#Q.__internal_keyless_dismissPrompt}})})};#ep=(e,t,i)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let r=this.#Q[e]||this.environment.displayConfig[e];this.#eo()&&(r=this.#Q.signInUrl);let n=new eS(this.#Q,t).toSearchParams(),s=new URLSearchParams(i||{}),a=eg({base:r,hashPath:this.#eo()&&"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")}#eU=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,eh)).pathname,r=ev.includes(i)||ek.includes(i),e===t.host&&r);if(a||!o)return!1;let l=this.session,c=this.#Q.signInUrl||this.environment?.displayConfig.signInUrl,d=c&&window.location.href.startsWith(c),h=this.#Q.signUpUrl||this.environment?.displayConfig.signUpUrl,u=h&&window.location.href.startsWith(h);return n=new URL(s,eh),(!ev.includes(n.pathname)||!!l||!d&&!u)&&(await this.navigate(this.buildUrlWithAuth(s)),!0)};#ei=e=>({...ng,...e,allowedRedirectOrigins:function(e,t,i){if(Array.isArray(e)&&e.length)return e;let r=[];return"undefined"!=typeof window&&window.location&&r.push(window.location.origin),r.push(`https://${em(t)}`),r.push(`https://*.${em(t)}`),"development"===i&&r.push(`https://${t}`),r}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)});#eA=()=>{try{eC(F),eC(eU),eC(N),eC("__clerk_handshake"),eC("__clerk_handshake_nonce"),eC("__clerk_help")}catch{}};get #eu(){let e=eM;return this.#Q.allowedRedirectProtocols&&(e=e.concat(this.#Q.allowedRedirectProtocols)),e}}let nb=document.querySelector("script[data-clerk-publishable-key]")?.getAttribute("data-clerk-publishable-key")||window.__clerk_publishable_key||"",ny=document.querySelector("script[data-clerk-proxy-url]")?.getAttribute("data-clerk-proxy-url")||window.__clerk_proxy_url||"",nw=document.querySelector("script[data-clerk-domain]")?.getAttribute("data-clerk-domain")||window.__clerk_domain||"";window.Clerk||(window.Clerk=new n_(nb,{proxyUrl:ny,domain:nw}))})(),{}})());
|
|
16
|
+
(This notice only appears in development)`,eR={cannotRenderComponentWhenSessionExists:"The <SignUp/> and <SignIn/> components cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the Home URL instead.",cannotRenderSignUpComponentWhenSessionExists:"The <SignUp/> component cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the value set in `afterSignUp` URL instead.",cannotRenderSignUpComponentWhenTaskExists:"The <SignUp/> component cannot render when a user has a pending task, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the task instead.",cannotRenderComponentWhenTaskDoesNotExist:"<TaskChooseOrganization/> cannot render unless a session task is pending. Clerk is redirecting to the value set in `redirectUrlComplete` instead.",cannotRenderSignInComponentWhenSessionExists:"The <SignIn/> component cannot render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the `afterSignIn` URL instead.",cannotRenderSignInComponentWhenTaskExists:"The <SignIn/> component cannot render when a user has a pending task, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, Clerk is redirecting to the task instead.",cannotRenderComponentWhenUserDoesNotExist:"<UserProfile/> cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotRenderComponentWhenOrgDoesNotExist:"<OrganizationProfile/> cannot render unless an organization is active. Since no organization is currently active, this is no-op.",cannotRenderAnyOrganizationComponent:e=>ex(`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=>ex(`The <${e}/> component cannot be rendered when billing is disabled. Visit 'https://dashboard.clerk.com/last-active?path=billing/settings' to follow the necessary steps to enable billing. Since billing is disabled, this is no-op.`),cannotOpenUserProfile:"The UserProfile modal cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotOpenCheckout:"The Checkout drawer cannot render unless a user is signed in. Since no user is signed in, this is no-op.",cannotOpenSignInOrSignUp:"The SignIn or SignUp modals do not render when a user is already signed in, unless the application allows multiple sessions. Since a user is signed in and this application only allows a single session, this is no-op.",cannotRenderAPIKeysComponent:"The <APIKeys/> component cannot be rendered when API keys is disabled. Since API keys is disabled, this is no-op.",cannotRenderAPIKeysComponentForOrgWhenUnauthorized:"The <APIKeys/> component cannot be rendered for an organization unless a user has the required permissions. Since the user does not have the necessary permissions, this is no-op.",cannotRenderAPIKeysComponentForUserWhenDisabled:"The <APIKeys/> component cannot be rendered when user API keys are disabled. Since user API keys are disabled, this is no-op.",cannotRenderAPIKeysComponentForOrgWhenDisabled:"The <APIKeys/> component cannot be rendered when organization API keys are disabled. Since organization API keys are disabled, this is no-op."};for(let e of Object.keys(eR)){let t=eR[e];"function"!=typeof t&&(eR[e]=ex(t))}let ez="clerk:beforeunload",eM=["http:","https:","wails:","chrome-extension:"];function eF(e){let t=new URL(e,window.location.href);window.dispatchEvent(new CustomEvent(ez)),window.location.href=t.href}function eN(e){return/^http(s)?:\/\//.test(e||"")}function eW(e){return e.startsWith("/")}var eD=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]))}},e$=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"undefined"!=typeof window&&!!window.localStorage}},eL=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 ej=new Set(["error","warn","info","debug","trace"]);var eB=class{#f;#m;#g={};#_=[];#b=null;constructor(e){this.#f={maxBufferSize:e.maxBufferSize??5,samplingRate:e.samplingRate??1,perEventSampling:e.perEventSampling??!0,disabled:e.disabled??!1,debug:e.debug??!1,endpoint:"https://clerk-telemetry.com"},e.clerkVersion||"undefined"!=typeof window?this.#g.clerkVersion=e.clerkVersion??"":this.#g.clerkVersion="",this.#g.sdk=e.sdk,this.#g.sdkVersion=e.sdkVersion,this.#g.publishableKey=e.publishableKey??"";const t=es(e.publishableKey);t&&(this.#g.instanceType=t.instanceType),e.secretKey&&(this.#g.secretKey=e.secretKey.substring(0,16)),this.#m=new eD(e$.isSupported()?new e$:new eL)}get isEnabled(){return!("development"!==this.#g.instanceType||this.#f.disabled||"undefined"!=typeof process&&process.env&&Y(process.env.CLERK_TELEMETRY_DISABLED)||"undefined"!=typeof window&&window?.navigator?.webdriver)}get isDebug(){return this.#f.debug||"undefined"!=typeof process&&process.env&&Y(process.env.CLERK_TELEMETRY_DEBUG)}record(e){try{let t=this.#y(e.event,e.payload);if(this.#w(t.event,t),!this.#v(t,e.eventSamplingRate))return;this.#_.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&&ej.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&&"undefined"!=typeof console&&console.warn("[clerk/telemetry] Dropping invalid telemetry log entry",{levelIsValid:t,messageIsValid:i,timestampIsValid:null!==r});return}let s=this.#U(),a={sdk:s.name,sdkv:s.version,cv:this.#g.clerkVersion??"",lvl:e.level,msg:e.message,ts:r.toISOString(),pk:this.#g.publishableKey||null,payload:this.#A(e.context)};this.#_.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.#I(e,t)}#S(e){return!0}#I(e,t){let i=Math.random();return!!(i<=this.#f.samplingRate&&(!1===this.#f.perEventSampling||void 0===t||i<=t))&&!this.#m.isEventThrottled(e)}#k(){if("undefined"==typeof window)return void this.#C();if(this.#_.length>=this.#f.maxBufferSize){this.#b&&("undefined"!=typeof cancelIdleCallback?cancelIdleCallback(Number(this.#b)):clearTimeout(Number(this.#b))),this.#C();return}this.#b||("requestIdleCallback"in window?this.#b=requestIdleCallback(()=>{this.#C(),this.#b=null}):this.#b=setTimeout(()=>{this.#C(),this.#b=null},0))}#C(){let e=[...this.#_];if(this.#_=[],this.#b=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.#f.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.#f.endpoint),{headers:{"Content-Type":"application/json"},keepalive:!0,method:"POST",body:JSON.stringify({logs:i})}).catch(()=>void 0)}#w(e,t){this.isDebug&&(void 0!==console.groupCollapsed?(console.groupCollapsed("[clerk/telemetry]",e),console.log(t),console.groupEnd()):console.log("[clerk/telemetry]",e,t))}#U(){let e={name:this.#g.sdk,version:this.#g.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:r}=i.constructor.sdkMetadata;void 0!==t&&(e.name=t),void 0!==r&&(e.version=r)}}}return e}#y(e,t){let i=this.#U();return{event:e,cv:this.#g.clerkVersion??"",it:this.#g.instanceType??"",sdk:i.name,sdkv:i.version,...this.#g.publishableKey?{pk:this.#g.publishableKey}:{},...this.#g.secretKey?{sk:this.#g.secretKey}:{},payload:t}}#A(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 eJ="COMPONENT_MOUNTED",eK=new Set(["SignIn","SignUp"]);function eV(e){return function(t,i,r){return{event:e,eventSamplingRate:e===eJ?eK.has(t)?1:.1:.1,payload:{component:t,appearanceProp:!!i?.appearance,baseTheme:!!i?.appearance?.baseTheme,elements:!!i?.appearance?.elements,variables:!!i?.appearance?.variables,...r}}}}function eq(e,t,i){return eV(eJ)(e,t,i)}function eG(e,t,i){return eV("COMPONENT_OPENED")(e,t,i)}function eH(e){return"string"==typeof e?e:"object"==typeof e&&null!==e&&"name"in e&&"string"==typeof e.name?e.name:void 0}function eX(e,t,i){return"function"==typeof e?e(t):void 0!==e?e:void 0!==i?i:void 0}let eY=(...e)=>{},eQ=!1,eZ=null,e0=!1,e1=[];function e3(e,t,i,r){eQ&&(e1.push({level:e,message:t,context:i,source:r,ts:Date.now()}),e1.length>200&&e1.shift())}async function e2(e){try{if(!eQ||eZ)return;let{getDebugLogger:t}=await s.e("507").then(s.bind(s,9854)),i=await t({logLevel:e?.logLevel,telemetryCollector:e?.telemetryCollector});if(i&&(eZ=i)&&0!==e1.length){for(let e of e1){let t={...e.context||{},__preInit:!0,__preInitTs:e.ts};switch(e.level){case"error":eZ.error(e.message,t,e.source);break;case"warn":eZ.warn(e.message,t,e.source);break;case"info":eZ.info(e.message,t,e.source);break;case"debug":eZ.debug(e.message,t,e.source)}}e1.length=0}}catch(e){try{console.debug?.("Debug logger initialization failed",e)}catch{}return}}let e4={debug(e,t,i){eZ?eZ.debug(e,t,i):e3("debug",e,t,i)},error(e,t,i){eZ?eZ.error(e,t,i):e3("error",e,t,i)},info(e,t,i){eZ?eZ.info(e,t,i):e3("info",e,t,i)},warn(e,t,i){eZ?eZ.warn(e,t,i):e3("warn",e,t,i)}},e5={initialDelay:125,maxDelayBetweenRetries:0,factor:2,shouldRetry:(e,t)=>t<5,retryImmediately:!1,jitter:!0},e6=async e=>new Promise(t=>setTimeout(t,e)),e9=(e,t)=>t?e*(1+Math.random()):e,e7=async(e,t={})=>{var i;let r,n=0,{shouldRetry:s,initialDelay:a,maxDelayBetweenRetries:o,factor:l,retryImmediately:c,jitter:d,onBeforeRetry:h}={...e5,...t},u=(i={initialDelay:a,maxDelayBetweenRetries:o,factor:l,jitter:d},r=0,async()=>{let e;await e6((e=e9(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 e6(e9(100,d)):await u()}},e8=async e=>e7(e,{initialDelay:100,shouldRetry:(e,t)=>t<=3,retryImmediately:!0,factor:2});class te{#P={"@zxcvbn-ts/core":()=>e8(()=>s.e("729").then(s.bind(s,7010))),"@zxcvbn-ts/language-common":()=>e8(()=>s.e("873").then(s.bind(s,655))),"@base-org/account":()=>e8(()=>Promise.all([s.e("994"),s.e("929"),s.e("545")]).then(s.bind(s,4013))),"@coinbase/wallet-sdk":()=>e8(()=>Promise.all([s.e("994"),s.e("929"),s.e("545")]).then(s.bind(s,5537))),"@stripe/stripe-js":()=>e8(()=>s.e("279").then(s.bind(s,5608)))};import(e){return this.#P[e]?this.#P[e]():Promise.resolve(void 0)}}let tt=(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(ez,i)},stopListening:()=>{window.removeEventListener("beforeunload",i),window.removeEventListener(ez,i)},isUnloading:()=>t});return{track:async e=>{r.startListening(),await e(),r.stopListening()},isUnloading:r.isUnloading}},ti=e=>({amount:e.amount,amountFormatted:e.amount_formatted,currency:e.currency,currencySymbol:e.currency_symbol}),tr=e=>{let t={grandTotal:ti(e.grand_total),subtotal:ti(e.subtotal),taxTotal:ti(e.tax_total)};return"past_due"in e&&(t.pastDue=e.past_due?ti(e.past_due):null),"credit"in e&&(t.credit=e.credit?ti(e.credit):null),"total_due_now"in e&&(t.totalDueNow=ti(e.total_due_now)),"total_due_after_free_trial"in e&&(t.totalDueAfterFreeTrial=e.total_due_after_free_trial?ti(e.total_due_after_free_trial):null),t};function tn(e,t=""){return e.errors&&!!e.errors.find(e=>e.code===t)}let ts=function({packageName:e,customMessages:t}){let i=e;function r(e,t){if(!t)return`${i}: ${e}`;let r=e;for(let i of e.matchAll(/{{([a-zA-Z0-9-_]+)}}/g)){let e=(t[i[1]]||"").toString();r=r.replace(`{{${i[1]}}}`,e)}return`${i}: ${r}`}let n={...k,...t};return{setPackageName({packageName:e}){return"string"==typeof e&&(i=e),this},setMessages({customMessages:e}){return Object.assign(n,e||{}),this},throwInvalidPublishableKeyError(e){throw Error(r(n.InvalidPublishableKeyErrorMessage,e))},throwInvalidProxyUrl(e){throw Error(r(n.InvalidProxyUrlErrorMessage,e))},throwMissingPublishableKeyError(){throw Error(r(n.MissingPublishableKeyErrorMessage))},throwMissingSecretKeyError(){throw Error(r(n.MissingSecretKeyErrorMessage))},throwMissingClerkProviderError(e){throw Error(r(n.MissingClerkProvider,e))},throw(e){throw Error(r(e))}}}({packageName:"@clerk/clerk-js"});function ta(e){return decodeURIComponent(globalThis.atob(e.replace(/_/g,"/").replace(/-/g,"+")).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""))}function to(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(ta(r)),a={__raw:e};return Object.keys(s).forEach(e=>{a[e]=s[e]}),{encoded:{header:i,payload:r,signature:n},header:JSON.parse(ta(i)),claims:a}}function tl(){if(!n())return null;try{let e=navigator?.language;if(!e||"string"!=typeof e||""===e.trim())return null;return e}catch{return null}}function tc(){return void 0!==globalThis.document}var td=class e{#O=[];#T={metamask:"MetaMask",okx_wallet:"OKX Wallet"};static #E=null;constructor(){if("undefined"==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.#O.find(t=>t.info.name===this.#T[e])?.provider;return void 0!==t?t:window.ethereum};#x=e=>{this.#O.some(t=>t.info.uuid===e.detail.info.uuid)||this.#O.push(e.detail)}};let th=()=>(function(e){async function t(e){let{provider:t}=e,i=await h(t);if(!i)return"";let r=await i.request({method:"eth_requestAccounts"});return r&&r[0]||""}async function i(e){let{identifier:t,nonce:i,provider:r}=e,n=await h(r);return n?await n.request({method:"personal_sign",params:[`0x${i.split("").map(e=>e.charCodeAt(0).toString(16).padStart(2,"0")).join("")}`,t]}):""}async function r(){return await t({provider:"metamask"})}async function n(){return await t({provider:"coinbase_wallet"})}async function s(){return await t({provider:"okx_wallet"})}async function a(){return await t({provider:"base"})}async function o(e){return await i({...e,provider:"metamask"})}async function l(e){return await i({...e,provider:"coinbase_wallet"})}async function c(e){return await i({...e,provider:"okx_wallet"})}async function d(e){return await i({...e,provider:"base"})}async function h(t){if("coinbase_wallet"===t){let t=await e.import("@coinbase/wallet-sdk");return t?t.createCoinbaseWalletSDK({preference:{options:"all"}}).getProvider():null}if("base"===t)try{let t=await e.import("@base-org/account");if(!t)return null;return t.createBaseAccountSDK({appName:"undefined"!=typeof window&&window.Clerk?.__unstable__environment?.displayConfig?.applicationName||"undefined"!=typeof document&&document.title||"Web3 Application"}).getProvider()}catch{return null}return td.getInstance().get(t)}return{getWeb3Identifier:t,generateWeb3Signature:i,getMetamaskIdentifier:r,getCoinbaseWalletIdentifier:n,getOKXWalletIdentifier:s,getBaseIdentifier:a,generateSignatureWithMetamask:o,generateSignatureWithCoinbaseWallet:l,generateSignatureWithOKXWallet:c,generateSignatureWithBase:d}})(new te),tu="environment",tp=JSON.stringify,tf=JSON.parse;class tm{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),tp(r))}catch{}}static getItem(e,t){try{let i=window.localStorage.getItem(this._key(e));if(!i)return t;let r=tf(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 tg="ClerkJS:";function t_(e=""){throw Error(`${tg} Something went wrong initializing Clerk in development mode.${e&&` ${e}`}`)}function tb(e){throw Error(`${tg} Something went wrong initializing Clerk during the ${e} flow. Please contact support.`)}function ty(e){throw Error(`${tg} You need to start a ${e} flow by calling ${e}.create() first.`)}function tw(e,t){throw Error(`${tg} Strategy "${t}" is not a valid strategy for ${e}.`)}function tv(e){throw Error(`${tg} You need to start a ${e} flow by calling ${e}.create({ identifier: 'your web3 wallet address' }) first`)}function tk(e=""){throw Error(`${tg} Missing '${e}' option`)}function tS(e,t){throw Error(`${tg} Response: ${e||0} not supported yet.
|
|
17
|
+
For more information contact us at ${t}`)}function tU(e){throw Error(`${tg} Missing publicKey. When calling 'navigator.credentials.${e}()' it is required to pass a publicKey object.`)}async function tA(e="",t){let{async:i,defer:r,beforeLoad:n,crossOrigin:s,nonce:a}=t||{};return e7(()=>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",()=>{console.log("this loaded ",e),l.remove(),t(l)}),l.addEventListener("error",t=>{l.remove(),o(t.error??Error(`failed to load script: ${e}`))}),l.src=e,l.nonce=a,n?.(l),document.body.appendChild(l)}),{shouldRetry:(e,t)=>(console.log("nikos 3",e,t),t<=5)})}async function tI(e){return window.turnstile||await tC(e).catch(()=>{throw{captchaError:"captcha_script_failed_to_load"}}),window.turnstile}async function tC(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,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 tO=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 tI(l),f=[],m="",g="",_=s,b=0,y=null,w="invisible";if(c&&d){y=a,n=c,w="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}=tP(e);t=n,r=s,i=a}}if(!n&&"smart"===a){let e=document.getElementById(D);if(e){w="smart",y="smart",n=`#${D}`,e.style.maxHeight="0";let{theme:s,language:a,size:o}=tP(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/bot-sign-up-protection for instructions")}if(!n){w="invisible",_=o,y="invisible",n=`.${$}`;let e=document.createElement("div");e.classList.add($),e.style.display="none",document.body.appendChild(e)}let v=async()=>new Promise((s,a)=>{try{let o=p.render(n,{sitekey:_,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(D);e&&(e.style.maxHeight="unset",e.style.minHeight="compact"===i?"140px":"68px",e.style.marginBottom="1.5rem")}},"error-callback":function(e){var t;(f.push(e),b<2&&(t=e.toString(),["crashed","undefined_error","102","103","104","106","110600","300","600"].find(e=>t.startsWith(e))))?setTimeout(()=>{p.reset(o),b++},250):a([f.join(","),o])},"unsupported-callback":function(){return a(["This browser is not supported by the CAPTCHA.",o]),!0}})}catch(e){a([e,void 0])}});try{[m,g]=await v(),p.remove(g)}catch([e,t]){throw t&&p.remove(t),{captchaError:e}}finally{if("modal"===w&&h?.(),"invisible"===w){let e=document.querySelector(`.${$}`);e&&document.body.removeChild(e)}if("smart"===w){let e=document.getElementById(D);e&&(e.style.maxHeight="0",e.style.minHeight="unset",e.style.marginBottom="unset")}}return{captchaToken:m,captchaWidgetType:y}},tT=e=>{let t=e.__unstable__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 tE{clerk;constructor(e){this.clerk=e}async invisible(e){let{captchaSiteKey:t,canUseCaptcha:i,captchaPublicKeyInvisible:r,nonce:n}=tT(this.clerk);return i&&t&&r?{...await tO({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}=tT(this.clerk);if(i&&t&&s){let i=await tO({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){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 tx{client;CaptchaChallengeImpl;static instance;inflightException=null;captchaRetryCount=0;MAX_RETRY_ATTEMPTS=3;static getInstance(){return tx.instance||(tx.instance=new tx(iP,tE)),tx.instance}constructor(e,t){this.client=e,this.CaptchaChallengeImpl=t}async execute(e,t){if(this.captchaAttemptsExceeded())throw new U("Security verification failed. Please try again by refreshing the page, clearing your browser cookies, or using a different web browser.",{code:"captcha_client_attempts_exceeded"});try{return this.inflightException&&await this.inflightException,await t()}catch(r){let i;if(!O(r)||T(r)&&"network_error"===r.code||r.errors[0]?.code!=="requires_captcha")throw r;if(this.inflightException)return await this.inflightException,await 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 tR{static clerk;id;pathRoot="";static get fapiClient(){return tR.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 tx.getInstance().execute(this.clerk,()=>this._baseFetch(e,t))}static async _baseFetch(e,t={}){let i;tR.fapiClient||function(){throw Error(`${tg} Missing FAPI client in resources.`)}();let{fetchMaxTries:r}=t;try{i=await tR.fapiClient.request(e,{fetchMaxTries:r})}catch(t){if(this.shouldRethrowOfflineNetworkErrors())throw new U(t?.message||t,{code:"network_error"});if(!c())return e4.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)&&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&&"requires_captcha"!==i&&await tR.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=tR.clerk.publishableKey).startsWith("live_")||i.startsWith("pk_live_"))){let i=tR.clerk.frontendApi.replace("clerk.","");throw new w(`Clerk: Production Keys are only allowed for domain "${i}".
|
|
18
|
+
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 w(t||a,r)}return null}static _updateClient(e){if(!e)return;let t=e.client||e.meta?.client;t&&tR.clerk&&tR.clerk.updateClient(iP.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 tR._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:r,path:n}=e,s=await tR._fetch({method:r,path:n||this.path(t),body:i});return this.fromJSON(s?.response||s)}async _baseMutateBypass(e){let{action:t,body:i,method:r,path:n}=e,s=await tR._baseFetch({method:r,path:n||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=tR.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}function tz(e){let t=new Date(e||new Date);return t instanceof Date&&!isNaN(t.getTime())?t:new Date}class tM extends tR{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?tz(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?tz(e.last_used_at):null,this.updatedAt=tz(e.updated_at),this.createdAt=tz(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 tF extends tR{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?tz(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}}}(g=_||(_={}))[g.None=0]="None",g[g.Mutable=1]="Mutable",g[g.Watching=2]="Watching",g[g.RecursedCheck=4]="RecursedCheck",g[g.Recursed=8]="Recursed",g[g.Dirty=16]="Dirty",g[g.Pending=32]="Pending";let tN=[],{link:tW,unlink:tD,propagate:t$,checkDirty:tL,endTracking:tj,startTracking:tB,shallowPropagate:tJ}=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?tQ(e):tZ(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):tN[tq++]=t}},unwatched(e){if("getter"in e){let t=e.deps;if(void 0!==t){e.flags=17;do t=tD(t,e);while(void 0!==t)}}else"previousValue"in e||t2.call(e)}}),tK=0,tV=0,tq=0;function tG(t){let i=e;return e=t,i}function tH(e){return t3.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function tX(e){return t1.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function tY(i){let r={fn:i,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==e?tW(r,e):void 0!==t&&tW(r,t);let n=tG(r);try{r.fn()}finally{tG(n)}return t2.bind(r)}function tQ(e){let t=tG(e);tB(e);try{let t=e.value;return t!==(e.value=e.getter(t))}finally{tG(t),tj(e)}}function tZ(e,t){return e.flags=1,e.previousValue!==(e.previousValue=t)}function t0(){for(;tV<tq;){let e=tN[tV];tN[tV++]=void 0,function e(t,i){if(16&i||32&i&&tL(t.deps,t)){let e=tG(t);tB(t);try{t.fn()}finally{tG(e),tj(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)}tV=0,tq=0}function t1(){let i=this.flags;if(16&i||32&i&&tL(this.deps,this)){if(tQ(this)){let e=this.subs;void 0!==e&&tJ(e)}}else 32&i&&(this.flags=-33&i);return void 0!==e?tW(this,e):void 0!==t&&tW(this,t),this.value}function t3(...t){if(t.length){let e=t[0];if(this.value!==(this.value=e)){this.flags=17;let e=this.subs;void 0!==e&&(t$(e),tK||t0())}}else{let t=this.value;if(16&this.flags&&tZ(this,t)){let e=this.subs;void 0!==e&&tJ(e)}return void 0!==e&&tW(this,e),t}}function t2(){let e=this.deps;for(;void 0!==e;)e=tD(e,this);let t=this.subs;void 0!==t&&tD(t),this.flags=0}function t4(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 t5{static #R="/billing";static path(e,t){let{orgId:i}=t||{},r=i?`/organizations/${i}`:"/me";return`${r}${t5.#R}${e}`}getPlans=async e=>{let{for:t,...i}=e||{},r={...i,payer_type:"organization"===t?"org":"user"};return await tR._fetch({path:`${t5.#R}/plans`,method:"GET",search:t4(r)}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new i_(e))}})};getPlan=async e=>new i_(await tR._fetch({path:`${t5.#R}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await tR._fetch({path:t5.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new iw(e?.response));getStatements=async e=>{let{orgId:t,...i}=e;return await tR._fetch({path:t5.path("/statements",{orgId:t}),method:"GET",search:t4(i)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new ib(e))}})};getStatement=async e=>new ib((await tR._fetch({path:t5.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:t,...i}=e;return await tR._fetch({path:t5.path("/payment_attempts",{orgId:t}),method:"GET",search:t4(i)}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new ic(e))}})};getPaymentAttempt=async e=>new ic(await tR._fetch({path:t5.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:t,...i}=e;return new io((await tR._fetch({path:t5.path("/checkouts",{orgId:t}),method:"POST",body:i}))?.response)}}let t6=tH({resource:null}),t9=tH({error:null}),t7=tH({status:"idle"}),t8=tX(()=>{let e=t6().resource,t=t9().error,i=t7().status;return{errors:is(t,{identifier:null,password:null,code:null}),fetchStatus:i,signIn:e?e.__internal_future:null}}),ie=tH({resource:null}),it=tH({error:null}),ii=tH({status:"idle"}),ir=tX(()=>{let e=ie().resource,t=it().error,i=ii().status;return{errors:is(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}});function is(e,t){let i={fields:{...t},raw:null,global:null};if(!e)return i;if(!O(e))return i.raw=[e],i.global=[E(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=V(e.meta.paramName);t in i.fields&&(i.fields[t]=e)}}):(i.raw=[e],i.global=[E(e)]),i}class ia extends tR{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=tz(e.created_at)),e.updated_at&&(this.updatedAt=tz(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 io extends tR{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 im(e.payment_method):void 0,this.plan=new i_(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=tr(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change,e.free_trial_ends_at&&(this.freeTrialEndsAt=tz(e.free_trial_ends_at)),this.payer=new ia(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>e7(()=>this._basePatch({path:t5.path(`/checkouts/${this.id}/confirm`,{orgId:this.payer.organizationId}),body:e}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,t){if(!O(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 il{resource=new io(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 io.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new io(null),this.signals.resourceSignal({resource:this})})}async confirm(e){if(!this.resource.id)throw Error("Clerk: `start()` must be called before `confirm()`");return this.runAsyncCheckoutTask("confirm",async()=>{await this.resource.confirm(e)})}async finalize(e){let{navigate:t}=e||{};return this.runAsyncCheckoutTask("finalize",async()=>{if("completed"!==this.resource.status)throw Error("Clerk: `confirm()` must be called before `finalize()`");await io.clerk.setActive({session:io.clerk.session?.id,navigate:t})})}runAsyncCheckoutTask(e,t,i){var r,n,s;return void 0===io.clerk.user?(console.warn("Clerk: Checkout operations cannot be performed during transitive state"),{error:null}):(r=this,n=this.signals,s=this.pendingOperations,async(e,t,i)=>{if(s.get(e))return s.get(e);let a=(async()=>{++tK,n.errorSignal({error:null}),n.fetchSignal({status:"fetching"}),i?.(),--tK||t0(),++tK;try{return await t(),n.resourceSignal({resource:r}),{error:null}}catch(e){return n.errorSignal({error:e}),{error:e}}finally{s.delete(e),n.fetchSignal({status:"idle"}),--tK||t0()}})();return s.set(e,a),a})(e,t,i)}}class ic extends tR{id;amount;failedAt=null;paidAt=null;updatedAt;paymentMethod=null;subscriptionItem;chargeType;status;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.amount=ti(e.amount),this.paidAt=e.paid_at?tz(e.paid_at):null,this.failedAt=e.failed_at?tz(e.failed_at):null,this.updatedAt=tz(e.updated_at),this.paymentMethod=e.payment_method?new im(e.payment_method):null,this.subscriptionItem=new iv(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status),this}}let id="/payment_methods",ih=async e=>{let{orgId:t,...i}=e;return new ig((await tR._fetch({path:t5.path(`${id}/initialize`,{orgId:t}),method:"POST",body:i}))?.response)},iu=async e=>{let{orgId:t,...i}=e;return new im((await tR._fetch({path:t5.path(id,{orgId:t}),method:"POST",body:i}))?.response)},ip=async e=>{let{orgId:t,...i}=e??{};return await tR._fetch({path:t5.path(id,{orgId:t}),method:"GET",search:t4(i)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new im(e))}})};class im extends tR{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:tz(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:tz(e.updated_at)),this}async remove(e){let{orgId:t}=e??{};return new iT((await tR._fetch({path:t5.path(`/payment_methods/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:t}=e??{};return await tR._fetch({path:t5.path("/payers/default_payment_method",{orgId:t}),method:"PUT",body:{payment_method_id:this.id}}),null}}class ig extends tR{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 i_ extends tR{id;name;fee;annualFee=null;annualMonthlyFee=null;description=null;isDefault;isRecurring;hasBaseFee;forPayerType;publiclyVisible;slug;avatarUrl=null;features;freeTrialDays;freeTrialEnabled;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.fee=ti(e.fee),this.annualFee=e.annual_fee?ti(e.annual_fee):null,this.annualMonthlyFee=e.annual_monthly_fee?ti(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 i7(e))),this}}class ib extends tR{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=tz(e.timestamp),this.totals=tr(e.totals),this.groups=e.groups.map(e=>new iy(e))),this}}class iy{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=tz(e.timestamp),this.items=e.items.map(e=>new ic(e))),this}}class iw extends tR{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=tz(e.created_at),this.updatedAt=e.updated_at?tz(e.updated_at):null,this.activeAt=tz(e.active_at),this.pastDueAt=e.past_due_at?tz(e.past_due_at):null,e.next_payment&&(this.nextPayment={amount:ti(e.next_payment.amount),date:tz(e.next_payment.date)}),this.subscriptionItems=(e.subscription_items||[]).map(e=>new iv(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1)),this}}class iv extends tR{id;plan;planPeriod;status;createdAt;periodStart;periodEnd;canceledAt;pastDueAt;amount;credit;isFreeTrial;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.plan=new i_(e.plan),this.planPeriod=e.plan_period,this.status=e.status,this.createdAt=tz(e.created_at),this.pastDueAt=e.past_due_at?tz(e.past_due_at):null,this.periodStart=tz(e.period_start),this.periodEnd=e.period_end?tz(e.period_end):null,this.canceledAt=e.canceled_at?tz(e.canceled_at):null,this.amount=e.amount?ti(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:ti(e.credit.amount)}:void 0,this.isFreeTrial=this.withDefault(e.is_free_trial,!1)),this}async cancel(e){let{orgId:t}=e;return new iT((await tR._fetch({path:t5.path(`/subscription_items/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}}let ik={build:(e,t,i)=>[e,t,i].filter(Boolean).join("-"),parse:(e,t,i)=>{let r=ik.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}},iS="clerk",iU=10,iA={broadcast:!0};class iI{prefix;data;static fromKey(e){let[t,i,r=""]=e.split("::");return new iI(t,{audience:r,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 iC=((e=iS)=>{let t=new Map,i=Math.random().toString(36).slice(2),r=null;return{clear:()=>{t.forEach(e=>{void 0!==e.timeoutId&&clearTimeout(e.timeoutId)}),t.clear()},close:()=>{r&&(r.close(),r=null)},get:(i,r=iU)=>{let n=new iI(e,i),s=t.get(n.toKey());if(!s)return;let a=Math.floor(Date.now()/1e3)-s.createdAt;if(s.expiresIn-a<(r||1)+5){void 0!==s.timeoutId&&clearTimeout(s.timeoutId),t.delete(n.toKey());return}return s.entry},set:n=>{((n,s=iA)=>{let a=new iI(e,{audience:n.audience,tokenId:n.tokenId}).toKey(),o=Math.floor(Date.now()/1e3),l={createdAt:n.createdAt??o,entry:n,expiresIn:void 0},c=()=>{let e=t.get(a);e===l&&(void 0!==e.timeoutId&&clearTimeout(e.timeoutId),t.delete(a))};n.tokenResolver.then(e=>{let t=e.jwt?.claims;if(!t||"number"!=typeof t.exp||"number"!=typeof t.iat)return c();let a=t.exp-t.iat;l.expiresIn=a;let o=setTimeout(c,1e3*a);l.timeoutId=o,"function"==typeof o.unref&&o.unref();let d=r;if(d&&s.broadcast){let r=e.getRawString();if(r&&t.sid){let e=t.sid,s=t.org_id||t.o?.id,a=ik.extractTemplate(n.tokenId,e,s),o=ik.build(e,a,s);if(n.tokenId===o){let t=`bc_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;e4.info("Broadcasting token update to other tabs",{organizationId:s,sessionId:e,tabId:i,template:a,tokenId:n.tokenId,traceId:t},"tokenCache");let o={organizationId:s,sessionId:e,template:a,tokenId:n.tokenId,tokenRaw:r,traceId:t};d.postMessage(o)}}}}).catch(()=>{c()}),t.set(a,l)})(n,iA)},size:()=>t.size}})();class iP extends tR{static instance;pathRoot="/client";sessions=[];signUp=new rz;signIn=new rE;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return iP.instance||(iP.instance=new iP(e)),iP.instance}static clearInstance(){iP.instance=null}static isClientResource(e){return!!e&&e instanceof iP}constructor(e=null){super(),this.fromJSON(e)}get signUpAttempt(){return this.signUp}get signInAttempt(){return this.signIn}get signedInSessions(){return this.sessions.filter(e=>"active"===e.status||"pending"===e.status)}create(){return this._basePut()}fetch({fetchMaxTries:e}={}){return this._baseGet({fetchMaxTries:e})}async destroy(){return this._baseDelete({path:"/client"}).then(()=>{iC.clear(),this.id="",this.sessions=[],this.signUp=new rz(null),this.signIn=new rE(null),this.lastActiveSessionId=null,this.lastAuthenticationStrategy=null,this.cookieExpiresAt=null,this.createdAt=null,this.updatedAt=null})}removeSessions(){return this._baseDelete({path:this.path()+"/sessions"}).then(e=>(iC.clear(),e))}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return tR.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 rk(e)),this.signUp=new rz(e.sign_up),this.signIn=new rE(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?tz(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=tz(e.created_at||void 0),this.updatedAt=tz(e.updated_at||void 0)),this}__internal_toSnapshot(){return{object:"client",id:this.id||"",sessions:this.sessions.map(e=>e.__internal_toSnapshot()),sign_up:this.signUp.__internal_toSnapshot(),sign_in:this.signIn.__internal_toSnapshot(),last_active_session_id:this.lastActiveSessionId,captcha_bypass:this.captchaBypass,cookie_expires_at:this.cookieExpiresAt?this.cookieExpiresAt.getTime():null,last_authentication_strategy:this.lastAuthenticationStrategy??null,created_at:this.createdAt?.getTime()??null,updated_at:this.updatedAt?.getTime()??null}}path(){return this.pathRoot}}class iO extends tR{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 iT{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 iE extends tR{afterCreateOrganizationUrl="";afterJoinWaitlistUrl="";afterLeaveOrganizationUrl="";afterSignInUrl="";afterSignOutAllUrl="";afterSignOutOneUrl="";afterSignOutUrl="";afterSignUpUrl="";afterSwitchSessionUrl="";applicationName="";backendHost="";branded=!1;captchaHeartbeat=!1;captchaHeartbeatIntervalMs;captchaOauthBypass=["oauth_google","oauth_microsoft","oauth_apple"];captchaProvider="turnstile";captchaPublicKey=null;captchaPublicKeyInvisible=null;captchaWidgetType=null;clerkJSVersion;createOrganizationUrl="";experimental__forceOauthFirst;faviconImageUrl="";googleOneTapClientId;homeUrl="";id="";instanceEnvironmentType="";logoImageUrl="";organizationProfileUrl="";preferredSignInStrategy="password";privacyPolicyUrl="";showDevModeWarning=!1;signInUrl="";signUpUrl="";supportEmail="";termsUrl="";theme={};userProfileUrl="";waitlistUrl="";constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.afterCreateOrganizationUrl=this.withDefault(e.after_create_organization_url,this.afterCreateOrganizationUrl),this.afterJoinWaitlistUrl=this.withDefault(e.after_join_waitlist_url,this.afterJoinWaitlistUrl),this.afterLeaveOrganizationUrl=this.withDefault(e.after_leave_organization_url,this.afterLeaveOrganizationUrl),this.afterSignInUrl=this.withDefault(e.after_sign_in_url,this.afterSignInUrl),this.afterSignOutAllUrl=this.withDefault(e.after_sign_out_all_url,this.afterSignOutAllUrl),this.afterSignOutOneUrl=this.withDefault(e.after_sign_out_one_url,this.afterSignOutOneUrl),this.afterSignUpUrl=this.withDefault(e.after_sign_up_url,this.afterSignUpUrl),this.afterSwitchSessionUrl=this.withDefault(e.after_switch_session_url,this.afterSwitchSessionUrl),this.applicationName=this.withDefault(e.application_name,this.applicationName),this.branded=this.withDefault(e.branded,this.branded),this.captchaHeartbeat=this.withDefault(e.captcha_heartbeat,this.captchaHeartbeat),this.captchaHeartbeatIntervalMs=this.withDefault(e.captcha_heartbeat_interval_ms,this.captchaHeartbeatIntervalMs),this.captchaOauthBypass=this.withDefault(e.captcha_oauth_bypass,this.captchaOauthBypass),this.captchaProvider=this.withDefault(e.captcha_provider,this.captchaProvider),this.captchaPublicKey=this.withDefault(e.captcha_public_key,this.captchaPublicKey),this.captchaPublicKeyInvisible=this.withDefault(e.captcha_public_key_invisible,this.captchaPublicKeyInvisible),this.captchaWidgetType=this.withDefault(e.captcha_widget_type,this.captchaWidgetType),this.clerkJSVersion=this.withDefault(e.clerk_js_version,this.clerkJSVersion),this.createOrganizationUrl=this.withDefault(e.create_organization_url,this.createOrganizationUrl),this.faviconImageUrl=this.withDefault(e.favicon_image_url,this.faviconImageUrl),this.googleOneTapClientId=this.withDefault(e.google_one_tap_client_id,this.googleOneTapClientId),this.homeUrl=this.withDefault(e.home_url,this.homeUrl),this.id=this.withDefault(e.id,this.id),this.instanceEnvironmentType=this.withDefault(e.instance_environment_type,this.instanceEnvironmentType),this.logoImageUrl=this.withDefault(e.logo_image_url,this.logoImageUrl),this.organizationProfileUrl=this.withDefault(e.organization_profile_url,this.organizationProfileUrl),this.preferredSignInStrategy=this.withDefault(e.preferred_sign_in_strategy,this.preferredSignInStrategy),this.privacyPolicyUrl=this.withDefault(e.privacy_policy_url,this.privacyPolicyUrl),this.showDevModeWarning=this.withDefault(e.show_devmode_warning,this.showDevModeWarning),this.signInUrl=this.withDefault(e.sign_in_url,this.signInUrl),this.signUpUrl=this.withDefault(e.sign_up_url,this.signUpUrl),this.supportEmail=this.withDefault(e.support_email,this.supportEmail),this.termsUrl=this.withDefault(e.terms_url,this.termsUrl),this.theme=this.withDefault(e.theme,this.theme),this.userProfileUrl=this.withDefault(e.user_profile_url,this.userProfileUrl),this.waitlistUrl=this.withDefault(e.waitlist_url,this.waitlistUrl)),this}__internal_toSnapshot(){return{object:"display_config",after_create_organization_url:this.afterCreateOrganizationUrl,after_join_waitlist_url:this.afterJoinWaitlistUrl,after_leave_organization_url:this.afterLeaveOrganizationUrl,after_sign_in_url:this.afterSignInUrl,after_sign_out_all_url:this.afterSignOutAllUrl,after_sign_out_one_url:this.afterSignOutOneUrl,after_sign_up_url:this.afterSignUpUrl,after_switch_session_url:this.afterSwitchSessionUrl,application_name:this.applicationName,branded:this.branded,captcha_heartbeat_interval_ms:this.captchaHeartbeatIntervalMs,captcha_heartbeat:this.captchaHeartbeat,captcha_oauth_bypass:this.captchaOauthBypass,captcha_provider:this.captchaProvider,captcha_public_key_invisible:this.captchaPublicKeyInvisible,captcha_public_key:this.captchaPublicKey,captcha_widget_type:this.captchaWidgetType,clerk_js_version:this.clerkJSVersion,create_organization_url:this.createOrganizationUrl,favicon_image_url:this.faviconImageUrl,google_one_tap_client_id:this.googleOneTapClientId,home_url:this.homeUrl,id:this.id,instance_environment_type:this.instanceEnvironmentType,logo_image_url:this.logoImageUrl,organization_profile_url:this.organizationProfileUrl,preferred_sign_in_strategy:this.preferredSignInStrategy,privacy_policy_url:this.privacyPolicyUrl,show_devmode_warning:this.showDevModeWarning,sign_in_url:this.signInUrl,sign_up_url:this.signUpUrl,support_email:this.supportEmail,terms_url:this.termsUrl,theme:this.theme,user_profile_url:this.userProfileUrl,waitlist_url:this.waitlistUrl}}}var ix='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 iR=(e,t={})=>{if("undefined"==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}},iz=()=>{let e=0,t=()=>e++,i=new Map,r=(e,t)=>e?.postMessage(t),n=e=>{i.get(e.data.id)?.()},s=iR(ix,{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:eY};let a=()=>{s||(s=iR(ix,{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 iM({delayInMs:e}={delayInMs:1e3}){let t,i=iz(),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 iF extends tR{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",body:{...e}});attemptVerification=e=>{let{code:t}=e||{};return this._basePost({action:"attempt_verification",body:{code:t}})};createEmailLinkFlow=()=>{let{run:e,stop:t}=iM();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}=iM();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 iq(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new i8(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 iN=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 iW(e){try{let t=await navigator.credentials.create({publicKey:e});if(!t)return{error:new I("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 I(t.message,{code:"passkey_already_exists"}):"NotAllowedError"===t.name?new I(t.message,{code:"passkey_registration_cancelled"}):iL(t),publicKeyCredential:null}}}let iD=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 i$({publicKeyOptions:e,conditionalUI:t}){try{let i=await navigator.credentials.get({publicKey:e,mediation:t?"conditional":"optional",signal:iD.createAbortSignal()});if(!i)return{error:new I("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 I(i.message,{code:"passkey_retrieval_cancelled"}):iL(i),publicKeyCredential:null}}}function iL(e){return"AbortError"===e.name?new I(e.message,{code:"passkey_operation_aborted"}):"SecurityError"===e.name?new I(e.message,{code:"passkey_invalid_rpID_or_domain"}):e}function ij(e){let t=iV(e.challenge),i=(e.allowCredentials||[]).map(e=>({...e,id:iV(e.id)}));return{...e,allowCredentials:i,challenge:t}}function iB(e){return{type:e.type,id:e.id,rawId:iK(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function iJ(e){let t=e.response;return{...iB(e),response:{clientDataJSON:iK(t.clientDataJSON),authenticatorData:iK(t.authenticatorData),signature:iK(t.signature),userHandle:t.userHandle?iK(t.userHandle):null}}}let iK=iN.encode.bind(iN),iV=iN.decode.bind(iN);class iq extends tR{pathRoot="";status=null;strategy=null;nonce=null;message=null;externalVerificationRedirectURL=null;attempts=null;expireAt=null;error=null;verifiedAtClient=null;channel;constructor(e){super(),this.fromJSON(e)}verifiedFromTheSameClient=()=>this.verifiedAtClient===tR.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=tz(e.expire_at||void 0),this.error=e.error?new b(e.error):null,this.channel=e.channel||void 0),this}__internal_toSnapshot(){var e;return{object:"verification",id:this.id||"",status:this.status,strategy:this.strategy,nonce:this.nonce,message:this.message,external_verification_redirect_url:this.externalVerificationRedirectURL?.toString()||null,attempts:this.attempts,expire_at:this.expireAt?.getTime()||null,error:(e=this.error,{code:e?.code||"",message:e?.message||"",long_message:e?.longMessage,meta:{param_name:e?.meta?.paramName,session_id:e?.meta?.sessionId,email_addresses:e?.meta?.emailAddresses,identifiers:e?.meta?.identifiers,zxcvbn:e?.meta?.zxcvbn,plan:e?.meta?.plan,is_plan_upgrade_possible:e?.meta?.isPlanUpgradePossible}}),verified_at_client:this.verifiedAtClient}}}class iG extends iq{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=iV((t=JSON.parse(e.nonce)).user.id),r=iV(t.challenge),n=(t.excludeCredentials||[]).map(e=>({...e,id:iV(e.id)})),{...t,excludeCredentials:n,challenge:r,user:{...t.user,id:i}})),this}}class iH{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new iX(e.email_address),this.phoneNumber=new iX(e.phone_number),this.web3Wallet=new iX(e.web3_wallet),this.externalAccount=new iq(e.external_account)):(this.emailAddress=new iX(null),this.phoneNumber=new iX(null),this.web3Wallet=new iX(null),this.externalAccount=new iq(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 iX extends iq{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 iY extends tR{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?tz(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new iq(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new iQ(e.enterprise_connection))),this}__internal_toSnapshot(){return{object:"enterprise_account",id:this.id,provider:this.provider,protocol:this.protocol,provider_user_id:this.providerUserId,active:this.active,email_address:this.emailAddress,first_name:this.firstName,last_name:this.lastName,public_metadata:this.publicMetadata,verification:this.verification?.__internal_toSnapshot()||null,enterprise_connection:this.enterpriseConnection?.__internal_toSnapshot()||null,last_authenticated_at:this.lastAuthenticatedAt?this.lastAuthenticatedAt.getTime():null,enterprise_connection_id:this.enterpriseConnectionId}}}class iQ extends tR{id;active;allowIdpInitiated;allowSubdomains;disableAdditionalIdentifications;domain;logoPublicUrl="";name;protocol;provider;syncUserAttributes;createdAt;updatedAt;enterpriseConnectionId="";constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.domain=e.domain,this.active=e.active,this.provider=e.provider,this.logoPublicUrl=e.logo_public_url,this.syncUserAttributes=e.sync_user_attributes,this.allowSubdomains=e.allow_subdomains,this.allowIdpInitiated=e.allow_idp_initiated,this.disableAdditionalIdentifications=e.disable_additional_identifications,this.createdAt=tz(e.created_at),this.updatedAt=tz(e.updated_at),this.enterpriseConnectionId=e.enterprise_connection_id),this}__internal_toSnapshot(){return{object:"enterprise_account_connection",id:this.id,name:this.name,domain:this.domain,active:this.active,protocol:this.protocol,provider:this.provider,logo_public_url:this.logoPublicUrl,sync_user_attributes:this.syncUserAttributes,allow_subdomains:this.allowSubdomains,allow_idp_initiated:this.allowIdpInitiated,disable_additional_identifications:this.disableAdditionalIdentifications,enterprise_connection_id:this.enterpriseConnectionId,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}let iZ="token:update",i0="user:signOut",i1="environment:update",i3="session:tokenResolved",i2=p();class i4 extends tR{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 i5 extends tR{actions={adminDelete:!1};domains={enabled:!1,enrollmentModes:[],defaultRole:null};slug={disabled:!1};enabled=!1;maxAllowedMemberships=1;forceOrganizationSelection;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(e.actions&&(this.actions.adminDelete=this.withDefault(e.actions.admin_delete,this.actions.adminDelete)),e.domains&&(this.domains.enabled=this.withDefault(e.domains.enabled,this.domains.enabled),this.domains.enrollmentModes=this.withDefault(e.domains.enrollment_modes,this.domains.enrollmentModes),this.domains.defaultRole=this.withDefault(e.domains.default_role,this.domains.defaultRole)),e.slug&&(this.slug.disabled=this.withDefault(e.slug.disabled,this.slug.disabled)),this.enabled=this.withDefault(e.enabled,this.enabled),this.maxAllowedMemberships=this.withDefault(e.max_allowed_memberships,this.maxAllowedMemberships),this.forceOrganizationSelection=this.withDefault(e.force_organization_selection,this.forceOrganizationSelection)),this}__internal_toSnapshot(){return{actions:{admin_delete:this.actions.adminDelete},domains:{enabled:this.domains.enabled,enrollment_modes:this.domains.enrollmentModes,default_role:this.domains.defaultRole},enabled:this.enabled,max_allowed_memberships:this.maxAllowedMemberships}}}class i6 extends tR{static instance;authConfig=new tF;displayConfig=new iE;maintenanceMode=!1;clientDebugMode=!1;pathRoot="/environment";userSettings=new rJ;organizationSettings=new i5;commerceSettings=new iO;apiKeysSettings=new i4;protectConfig=new rf;static getInstance(){return i6.instance||(i6.instance=new i6),i6.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new tF(e.auth_config),this.displayConfig=new iE(e.display_config),this.maintenanceMode=this.withDefault(e.maintenance_mode,this.maintenanceMode),this.clientDebugMode=this.withDefault(e.client_debug_mode,this.clientDebugMode),this.organizationSettings=new i5(e.organization_settings),this.userSettings=new rJ(e.user_settings),this.commerceSettings=new iO(e.commerce_settings),this.apiKeysSettings=new i4(e.api_keys_settings),this.protectConfig=new rf(e.protect_config)),this}fetch({touch:e,fetchMaxTries:t}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:t})).then(e=>(i2.emit(i1,null),e))}isDevelopmentOrStaging=()=>!this.isProduction();isProduction=()=>"production"===this.displayConfig.instanceEnvironmentType;isSingleSession=()=>this.authConfig.singleSessionMode;onWindowLocationHost=()=>this.displayConfig.backendHost===window.location.host;__internal_toSnapshot(){return{object:"environment",auth_config:this.authConfig.__internal_toSnapshot(),display_config:this.displayConfig.__internal_toSnapshot(),id:this.id??"",maintenance_mode:this.maintenanceMode,client_debug_mode:this.clientDebugMode,organization_settings:this.organizationSettings.__internal_toSnapshot(),user_settings:this.userSettings.__internal_toSnapshot(),commerce_settings:this.commerceSettings.__internal_toSnapshot(),api_keys_settings:this.apiKeysSettings.__internal_toSnapshot(),protect_config:this.protectConfig.__internal_toSnapshot()}}}class i9 extends tR{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}=e||{};return this._basePatch({action:"reauthorize",body:{additional_scope:t,redirect_url:i}})};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 iq(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 i7 extends tR{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 i8 extends tR{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 re extends tR{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 re((await tR._fetch({path:e,method:"POST",body:r,headers:i}))?.response)}static async delete(e){return new re((await tR._fetch({path:e,method:"DELETE"}))?.response)}constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.publicUrl=e.public_url),this}}class rt extends tR{id;name;organizationId;enrollmentMode;verification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:t}){return new rt((await tR._fetch({path:`/organizations/${e}/domains`,method:"POST",body:{name:t}}))?.response)}prepareAffiliationVerification=async e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/prepare_affiliation_verification`,method:"POST",body:e});attemptAffiliationVerification=async e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/attempt_affiliation_verification`,method:"POST",body:e});updateEnrollmentMode=e=>this._basePost({path:`/organizations/${this.organizationId}/domains/${this.id}/update_enrollment_mode`,body:e});delete=()=>this._baseDelete({path:`/organizations/${this.organizationId}/domains/${this.id}`});fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.organizationId=e.organization_id,this.enrollmentMode=e.enrollment_mode,this.affiliationEmailAddress=e.affiliation_email_address,this.totalPendingSuggestions=e.total_pending_suggestions,this.totalPendingInvitations=e.total_pending_invitations,e.verification?this.verification={status:e.verification.status,strategy:e.verification.strategy,attempts:e.verification.attempts,expiresAt:tz(e.verification.expires_at)}:this.verification=null),this}}class ri extends tR{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=tz(e.created_at),this.updatedAt=tz(e.updated_at),e.public_user_data&&(this.publicUserData=new rm(e.public_user_data))),this}}class rr extends tR{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=tz(e.created_at),this.updatedAt=tz(e.updated_at)),this}}class rn extends tR{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 rr(e)),this.createdAt=tz(e.created_at),this.updatedAt=tz(e.updated_at)),this}}class rs extends tR{pathRoot="/organizations";id;name;slug;imageUrl;hasImage;publicMetadata={};adminDeleteEnabled;createdAt;updatedAt;membersCount=0;pendingInvitationsCount=0;maxAllowedMemberships;constructor(e){super(),this.fromJSON(e)}static async create(e){return new rs((await tR._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new rs((await tR._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await tR._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:t4(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new rn(e))}});getDomains=async e=>await tR._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:t4(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new rt(e))}});getDomain=async({domainId:e})=>new rt((await tR._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getMembershipRequests=async e=>await tR._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:t4(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new ri(e))}});createDomain=async e=>rt.create(this.id,{name:e});getMemberships=async e=>await tR._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:t4({...e,paginated:!0})}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new ro(e))}});getInvitations=async e=>await tR._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:t4(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new ra(e))}});addMember=async({userId:e,role:t})=>await tR._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:t}}).then(e=>new ro(e?.response));inviteMember=async e=>ra.create(this.id,e);inviteMembers=async e=>ra.createBulk(this.id,e);updateMember=async({userId:e,role:t})=>await tR._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:t}}).then(e=>new ro(e?.response));removeMember=async e=>await tR._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new ro(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let t,i;return null===e?await tR._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new rs(e?.response)):("string"==typeof e?(t=e,i=new Headers({"Content-Type":"application/octet-stream"})):(t=new FormData).append("file",e),await tR._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:t,headers:i}).then(e=>new rs(e?.response)))};initializePaymentMethod=e=>ih({...e,orgId:this.id});addPaymentMethod=e=>iu({...e,orgId:this.id});getPaymentMethods=e=>ip({...e,orgId:this.id});fromJSON(e){return e&&(this.id=e.id,this.name=e.name,this.slug=e.slug,this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.publicMetadata=e.public_metadata||{},this.membersCount=e.members_count||0,this.pendingInvitationsCount=e.pending_invitations_count||0,this.maxAllowedMemberships=e.max_allowed_memberships||0,this.adminDeleteEnabled=e.admin_delete_enabled||!1,this.createdAt=tz(e.created_at),this.updatedAt=tz(e.updated_at)),this}__internal_toSnapshot(){return{object:"organization",id:this.id,name:this.name,slug:this.slug,image_url:this.imageUrl,has_image:this.hasImage,public_metadata:this.publicMetadata,members_count:this.membersCount,pending_invitations_count:this.pendingInvitationsCount,max_allowed_memberships:this.maxAllowedMemberships,admin_delete_enabled:this.adminDeleteEnabled,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}async reload(e){let{rotatingTokenNonce:t}=e||{},i=(await tR._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:t},{forceUpdateClient:!0}))?.response;return this.fromJSON(i)}}class ra extends tR{id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:t,role:i}){return new ra((await tR._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 tR._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:i,role:r}}))?.response).map(e=>new ra(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=tz(e.created_at),this.updatedAt=tz(e.updated_at)),this}}class ro extends tR{id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await tR._fetch({path:"/me/organization_memberships",method:"GET",search:t4({...e,paginated:!0})}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new ro(e))}});destroy=async()=>await this._baseDelete({path:`/organizations/${this.organization.id}/memberships/${this.publicUserData?.userId}`});update=async({role:e})=>await this._basePatch({path:`/organizations/${this.organization.id}/memberships/${this.publicUserData?.userId}`,body:{role:e}});fromJSON(e){return e&&(this.id=e.id,this.organization=new rs(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new rm(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=tz(e.created_at),this.updatedAt=tz(e.updated_at)),this}__internal_toSnapshot(){return{object:"organization_membership",id:this.id,organization:this.organization.__internal_toSnapshot(),public_metadata:this.publicMetadata,public_user_data:this.publicUserData?.__internal_toSnapshot(),permissions:this.permissions,role:this.role,role_name:this.roleName,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}reload(e){throw Error(`${tg} Calling OrganizationMembership.reload is not currently supported. Please contact support.`)}}class rl extends tR{id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await tR._fetch({path:"/me/organization_suggestions",method:"GET",search:t4(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new rl(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=tz(e.created_at),this.updatedAt=tz(e.updated_at)),this}}function rc(){return o()&&"function"==typeof window.PublicKeyCredential}async function rd(){try{return rc()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function rh(){try{return"undefined"!=typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class ru extends tR{id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return tR._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new ru(e?.response))}static async attemptVerification(e,t){let i,r=(i=t.response,{...iB(t),response:{clientDataJSON:iK(i.clientDataJSON),attestationObject:iK(i.attestationObject),transports:i.getTransports()}});return tR._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(r)}}).then(e=>new ru(e?.response))}static async registerPasskey(){let e=ru.clerk.__internal_isWebAuthnSupported||rc,t=ru.clerk.__internal_createPublicCredentials||iW,i=ru.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||rh;if(!e())throw new I("Passkeys are not supported on this device.",{code:"passkey_not_supported"});let r=await this.create(),{verification:n}=r,s=n?.publicKey;if(s||tU("create"),s.authenticatorSelection?.authenticatorAttachment==="platform"&&!await i())throw new I("Registration requires a platform authenticator but the device does not support it.",{code:"passkey_pa_not_supported"});let{publicKeyCredential:a,error:o}=await t(s);if(!a)throw o;return this.attemptVerification(r.id,a)}update=e=>this._basePatch({body:e});delete=async()=>new iT((await tR._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?tz(e.last_used_at):null,this.createdAt=tz(e.created_at),this.updatedAt=tz(e.updated_at),e.verification&&(this.verification=new iG(e.verification))),this}__internal_toSnapshot(){return{object:"passkey",id:this.id,name:this.name,verification:this.verification?.__internal_toSnapshot()||null,last_used_at:this.lastUsedAt?.getTime()||null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}}class rp extends tR{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",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 iq(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new i8(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 rf extends tR{id="";loaders;rollout;constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=this.withDefault(e.id,this.id),this.loaders=this.withDefault(e.loaders,this.loaders)),this}__internal_toSnapshot(){return{object:"protect_config",id:this.id,loaders:this.loaders}}}class rm{firstName;lastName;imageUrl;hasImage;identifier;userId;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.firstName=e.first_name||null,this.lastName=e.last_name||null,this.imageUrl=e.image_url||"",this.hasImage=e.has_image||!1,this.identifier=e.identifier||"",this.userId=e.user_id),this}__internal_toSnapshot(){return{first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl,has_image:this.hasImage,identifier:this.identifier,user_id:this.userId}}}let rg={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"}},r_=new Set(["first_factor","second_factor","multi_factor"]),rb=new Set(["strict_mfa","strict","moderate","lax"]),ry=(e,t)=>{let{org:i,user:r}=rw(e),[n,s]=t.split(":"),a=s||n;return"org"===n?i.includes(a):"user"===n?r.includes(a):[...i,...r].includes(a)},rw=e=>{let t=e?e.split(",").map(e=>e.trim()):[];return{org:t.filter(e=>e.split(":")[0].includes("o")).map(e=>e.split(":")[1]),user:t.filter(e=>e.split(":")[0].includes("u")).map(e=>e.split(":")[1])}};class rv extends tR{status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new iq(null);secondFactorVerification=new iq(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new rk(e.session),this.level=e.level,this.supportedFirstFactors=X(e.supported_first_factors),this.supportedSecondFactors=X(e.supported_second_factors),this.firstFactorVerification=new iq(e.first_factor_verification),this.secondFactorVerification=new iq(e.second_factor_verification)),this}}class rk extends tR{pathRoot="/client/sessions";id;status;lastActiveAt;lastActiveToken;lastActiveOrganizationId;actor;user;publicUserData;factorVerificationAge=null;tasks=null;expireAt;abandonAt;createdAt;updatedAt;static isSessionResource(e){return!!e&&e instanceof rk}constructor(e){super(),this.fromJSON(e),this.#z(this.lastActiveToken)}end=()=>(iC.clear(),this._basePost({action:"end"}));remove=()=>(iC.clear(),this._basePost({action:"remove"}));touch=()=>this._basePost({action:"touch",body:{active_organization_id:this.lastActiveOrganizationId}}).then(e=>(e.lastActiveToken&&i2.emit(iZ,{token:e.lastActiveToken}),e));clearCache=()=>iC.clear();getToken=async e=>e7(()=>this._getToken(e),{factor:1.55,initialDelay:3e3,maxDelayBetweenRetries:5e4,jitter:!1,shouldRetry:(e,t)=>!P(e)&&t<=8});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?.id,orgRole:i?.role,orgPermissions:i?.permissions,features:this.lastActiveToken?.jwt?.claims.fea||"",plans:this.lastActiveToken?.jwt?.claims.pla||""},e=>{if(!t.userId)return!1;let i=((e,t)=>{let{features:i,plans:r}=t;return e.feature&&i?ry(i,e.feature):e.plan&&r?ry(r,e.plan):null})(e,t),r=((e,t)=>{let{orgId:i,orgRole:r,orgPermissions:n}=t;return(e.role||e.permission)&&i&&r&&n?e.permission?n.includes(e.permission.replace(/^(org:)*/,"org:")):e.role?r.replace(/^(org:)*/,"org:")===e.role.replace(/^(org:)*/,"org:"):null:null})(e,t),n=((e,{factorVerificationAge:t})=>{if(!e.reverification||!t)return null;let i=(e=>{let t,i;if(!e)return!1;let r="string"==typeof e&&rb.has(e),n="object"==typeof e&&(t=e.level,r_.has(t))&&"number"==typeof(i=e.afterMinutes)&&i>0;return(!!r||!!n)&&(e=>"string"==typeof e?rg[e]:e).bind(null,e)})(e.reverification);if(!i)return null;let{level:r,afterMinutes:n}=i(),[s,a]=t,o=-1!==s?n>s:null,l=-1!==a?n>a:null;switch(r){case"first_factor":return o;case"second_factor":return -1!==a?l:o;case"multi_factor":return -1===a?o:o&&l}})(e,t);return[i||r,n].some(e=>null===e)?[i||r,n].some(e=>!0===e):[i||r,n].every(e=>!0===e)})(e)};#z=e=>{e&&iC.set({tokenId:this.#M(),tokenResolver:Promise.resolve(e)})};#M(e,t){let i=void 0===t?this.lastActiveOrganizationId:t;return ik.build(this.id,e,i)}startVerification=async({level:e})=>new rv((await tR._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"enterprise_sso":t={emailAddressId:e.emailAddressId,enterpriseConnectionId:e.enterpriseConnectionId,redirectUrl:e.redirectUrl};break;default:tw("Session.prepareFirstFactorVerification",e.strategy)}return new rv((await tR._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(iJ(e.publicKeyCredential))}:{...e},new rv((await tR._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_first_factor`,body:{...t,strategy:e.strategy}}))?.response)};verifyWithPasskey=async()=>{let{nonce:e=null}=(await this.prepareFirstFactorVerification({strategy:"passkey"})).firstFactorVerification,t=rk.clerk.__internal_isWebAuthnSupported||rc,i=rk.clerk.__internal_getPublicCredentials||i$;if(!t())throw new I("Passkeys are not supported",{code:"passkey_not_supported"});let r=e?ij(JSON.parse(e)):null;r||tU("get");let{publicKeyCredential:n,error:s}=await i({publicKeyOptions:r,conditionalUI:!1});if(!n)throw s;return this.attemptFirstFactorVerification({strategy:"passkey",publicKeyCredential:n})};prepareSecondFactorVerification=async e=>new rv((await tR._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>new rv((await tR._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/attempt_second_factor`,body:e}))?.response);fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.expireAt=tz(e.expire_at),this.abandonAt=tz(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=tz(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.createdAt=tz(e.created_at),this.updatedAt=tz(e.updated_at),this.user=new r$(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new rm(e.public_user_data)),this.lastActiveToken=e.last_active_token?new rN(e.last_active_token):null),this}__internal_toSnapshot(){return{object:"session",id:this.id,status:this.status,expire_at:this.expireAt.getTime(),abandon_at:this.abandonAt.getTime(),factor_verification_age:this.factorVerificationAge,last_active_at:this.lastActiveAt.getTime(),last_active_organization_id:this.lastActiveOrganizationId,actor:this.actor,tasks:this.tasks,user:this.user?.__internal_toSnapshot()||null,public_user_data:this.publicUserData.__internal_toSnapshot(),last_active_token:this.lastActiveToken?.__internal_toSnapshot()||null,created_at:this.createdAt.getTime(),updated_at:this.updatedAt.getTime()}}async _getToken(e){if(!this.user)return null;let{leewayInSeconds:t,template:i,skipCache:r=!1}=e||{},n=void 0===e?.organizationId?this.lastActiveOrganizationId:e?.organizationId;if(!i&&Number(t)>=60)throw Error("Leeway can not exceed the token lifespan (60 seconds)");let s=this.#M(i,n),a=r?void 0:iC.get({tokenId:s},t),o=!i&&n===this.lastActiveOrganizationId;if(a){e4.debug("Using cached token (no fetch needed)",{tokenId:s},"session");let e=await a.tokenResolver;return o&&i2.emit(iZ,{token:e}),e.getRawString()||null}e4.info("Fetching new token from API",{organizationId:n,template:i,tokenId:s},"session");let l=i?`${this.path()}/tokens/${i}`:`${this.path()}/tokens`,c=i?{}:{organizationId:n},d=rN.create(l,c,r);return iC.set({tokenId:s,tokenResolver:d}),d.then(e=>(o&&(i2.emit(iZ,{token:e}),e.jwt&&(this.lastActiveToken=e,i2.emit(i3,null))),e.getRawString()||null))}get currentTask(){let[e]=this.tasks??[];return e}}class rS extends tR{pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}static retrieve(){let e=tR.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new rS(e,"/me/sessions"))).catch(()=>[])}revoke(){return this._basePost({action:"revoke",body:{}})}fromJSON(e){let t;return e?(this.id=e.id,this.status=e.status,this.expireAt=tz(e.expire_at),this.abandonAt=tz(e.abandon_at),this.lastActiveAt=tz(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 rU=(e,t,i)=>{let{onValidation:r=eY,onValidationComplexity:n=eY}=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 rA(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function rI(e,t,i,r,n){if(!e.client||!r.popup)return;let s=rA(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 rC(e,{redirectCallbackUrl:t,redirectUrl:i}){let r=rA(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 rP(e,t){return new Promise((i,r)=>{if(!e.client||!t.popup)return void r();let n=async t=>{t.origin===rA(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()})}async function rO(e,t){i2.emit("resource:error",{resource:e,error:null}),i2.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await t(),error:null}}catch(t){return i2.emit("resource:error",{resource:e,error:t}),{error:t}}finally{i2.emit("resource:fetch",{resource:e,status:"idle"})}}let rT=()=>{var e;return(e=new te,{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 rE extends tR{pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;firstFactorVerification=new iq(null);secondFactorVerification=new iq(null);identifier=null;createdSessionId=null;userData=new rL(null);clientTrustState;get status(){return this._status}set status(e){let t=this._status;this._status=e,e&&t!==e&&e4.debug("SignIn.status",{id:this.id,from:t,to:e})}__internal_future=new rx(this);__internal_basePost=this._basePost.bind(this);__internal_baseGet=this._baseGet.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=e=>{e4.debug("SignIn.create",{id:this.id,strategy:"strategy"in e?e.strategy:void 0});let t=tl();return this._basePost({path:this.pathRoot,body:t?{locale:t,...e}:e})};resetPassword=e=>this._basePost({body:e,action:"reset_password"});prepareFirstFactor=e=>{let t;switch(e4.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":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:tw("SignIn.prepareFirstFactor",e.strategy)}return this._basePost({body:{...t,strategy:e.strategy},action:"prepare_first_factor"})};attemptFirstFactor=e=>{let t;return e4.debug("SignIn.attemptFirstFactor",{id:this.id,strategy:e.strategy}),t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(iJ(e.publicKeyCredential))}:{...e},this._basePost({body:{...t,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:t}=iM();return{startEmailLinkFlow:async({emailAddressId:i,redirectUrl:r})=>{this.id||ty("SignIn");let n={strategy:"email_link",emailAddressId:i,redirectUrl:r},s="needs_second_factor"===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=>{let r=e[a].status;("verified"===r||"expired"===r)&&(t(),i(e))}).catch(e=>{t(),r(e)}))})},cancelEmailLinkFlow:t}};prepareSecondFactor=e=>(e4.debug("SignIn.prepareSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_second_factor"}));attemptSecondFactor=e=>(e4.debug("SignIn.attemptSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_second_factor"}));authenticateWithRedirectOrPopup=async(e,t)=>{let{strategy:i,redirectUrlComplete:r,identifier:n,oidcPrompt:s,continueSignIn:a,enterpriseConnectionId:o}=e||{},l=rE.clerk.buildUrlWithAuth(e.redirectUrl);this.id&&a||await this.create({strategy:i,identifier:n,redirectUrl:l,actionCompleteRedirectUrl:r}),"enterprise_sso"===i&&await this.prepareFirstFactor({strategy:i,redirectUrl:l,actionCompleteRedirectUrl:r,oidcPrompt:s,enterpriseConnectionId:o});let{status:c,externalVerificationRedirectURL:d}=this.firstFactorVerification;"unverified"===c&&d?t(d):tS(c,rE.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eF);authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||tk("popup"),rI(rE.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"}=e||{},s=n.replace("web3_","").replace("_signature","");"function"!=typeof r&&tk("generateSignature"),await this.create({identifier:i});let a=this.supportedFirstFactors?.find(e=>e.strategy===n);a||tv("SignIn"),await this.prepareFirstFactor(a);let{message:o}=this.firstFactorVerification;o||tv("SignIn");try{t=await r({identifier:i,nonce:o,provider:s})}catch(e){if("coinbase_wallet"===s&&4001===e.code)t=await r({identifier:i,nonce:o,provider:s});else throw e}return this.attemptFirstFactor({signature:t,strategy:n})};authenticateWithMetamask=async()=>{let e=await th().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:th().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await th().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:th().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await th().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:th().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await th().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:th().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithPasskey=async e=>{let{flow:t}=e||{},i=rE.clerk.__internal_isWebAuthnSupported||rc,r=rE.clerk.__internal_getPublicCredentials||i$,n=rE.clerk.__internal_isWebAuthnAutofillSupported||rd;if(!i())throw new I("Passkeys are not supported",{code:"passkey_not_supported"});if("autofill"===t||"discoverable"===t)await this.create({strategy:"passkey"});else{let e=this.supportedFirstFactors.find(e=>"passkey"===e.strategy);e||function(){throw Error(`${tg} You need to start a SignIn flow by calling SignIn.create({ strategy: 'passkey' }) first`)}(),await this.prepareFirstFactor(e)}let{nonce:s}=this.firstFactorVerification,a=s?ij(JSON.parse(s)):null;a||tU("get");let o=!1;"autofill"===t&&(o=await n());let{publicKeyCredential:l,error:c}=await r({publicKeyOptions:a,conditionalUI:o});if(!l)throw c;return this.attemptFirstFactor({publicKeyCredential:l,strategy:"passkey"})};validatePassword=(e,t)=>{if(rE.clerk.__unstable__environment?.userSettings.passwordSettings)return rU(rT(),{...rE.clerk.__unstable__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=X(e.supported_first_factors),this.supportedSecondFactors=X(e.supported_second_factors),this.firstFactorVerification=new iq(e.first_factor_verification),this.secondFactorVerification=new iq(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new rL(e.user_data),this.clientTrustState=e.client_trust_state??void 0),i2.emit("resource:update",{resource:this}),this}__internal_toSnapshot(){return{object:"sign_in",id:this.id||"",status:this.status||null,supported_identifiers:this.supportedIdentifiers,supported_first_factors:H(this.supportedFirstFactors),supported_second_factors:H(this.supportedSecondFactors),first_factor_verification:this.firstFactorVerification.__internal_toSnapshot(),second_factor_verification:this.secondFactorVerification.__internal_toSnapshot(),identifier:this.identifier,created_session_id:this.createdSessionId,user_data:this.userData.__internal_toSnapshot()}}}class rx{resource;emailCode={sendCode:this.sendEmailCode.bind(this),verifyCode:this.verifyEmailCode.bind(this)};emailLink={sendLink:this.sendEmailLink.bind(this),waitForVerification:this.waitForEmailLinkVerification.bind(this),get verification(){if(!n())return null;const e=eI("__clerk_status"),t=eI("__clerk_created_session");if(!e||!t)return null;const i="verified"===e&&void 0!==rE.clerk.client&&rE.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)};phoneCode={sendCode:this.sendPhoneCode.bind(this),verifyCode:this.verifyPhoneCode.bind(this)};mfa={sendPhoneCode:this.sendMFAPhoneCode.bind(this),verifyPhoneCode:this.verifyMFAPhoneCode.bind(this),verifyTOTP:this.verifyTOTP.bind(this),verifyBackupCode:this.verifyBackupCode.bind(this)};#F=!1;constructor(e){this.resource=e}get id(){return this.resource.id}get identifier(){return this.resource.identifier}get createdSessionId(){return this.resource.createdSessionId}get userData(){return this.resource.userData}get status(){return this.resource.status||"needs_identifier"}get supportedFirstFactors(){return this.resource.supportedFirstFactors??[]}get supportedSecondFactors(){return this.resource.supportedSecondFactors??[]}get isTransferable(){return"transferable"===this.resource.firstFactorVerification.status}get existingSession(){if("failed"===this.resource.firstFactorVerification.status&&this.resource.firstFactorVerification.error?.code==="identifier_already_signed_in"&&this.resource.firstFactorVerification.error?.meta?.sessionId)return{sessionId:this.resource.firstFactorVerification.error?.meta?.sessionId}}get firstFactorVerification(){return this.resource.firstFactorVerification}get secondFactorVerification(){return this.resource.secondFactorVerification}get hasBeenFinalized(){return this.#F}async sendResetPasswordEmailCode(){if(!this.resource.id)throw Error("Cannot reset password without a sign in.");return rO(this.resource,async()=>{let e=this.resource.supportedFirstFactors?.find(e=>"reset_password_email_code"===e.strategy);if(!e)throw new U("Reset password email code factor not found",{code:"factor_not_found"});let{emailAddressId:t}=e;await this.resource.__internal_basePost({body:{emailAddressId:t,strategy:"reset_password_email_code"},action:"prepare_first_factor"})})}async verifyResetPasswordEmailCode(e){let{code:t}=e;return rO(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:t,strategy:"reset_password_email_code"},action:"attempt_first_factor"})})}async submitResetPassword(e){let{password:t,signOutOfOtherSessions:i=!0}=e;return rO(this.resource,async()=>{await this.resource.__internal_basePost({body:{password:t,signOutOfOtherSessions:i},action:"reset_password"})})}async _create(e){let t=tl();await this.resource.__internal_basePost({path:this.resource.pathRoot,body:t?{locale:t,...e}:e})}async create(e){return rO(this.resource,async()=>{await this._create(e)})}async password(e){if([e.identifier,e.emailAddress,e.phoneNumber].filter(Boolean).length>1)throw Error("Only one of identifier, emailAddress, or phoneNumber can be provided");return rO(this.resource,async()=>{let t=e.identifier||e.emailAddress||e.phoneNumber,i=this.resource.identifier,r=tl();await this.resource.__internal_basePost({path:this.resource.pathRoot,body:{identifier:t||i,password:e.password,...r?{locale:r}:{}}})})}async sendEmailCode(e={}){let{emailAddress:t,emailAddressId:i}=e;if(!this.resource.id&&i)throw Error("signIn.emailCode.sendCode() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.resource.id&&!t)throw Error("signIn.emailCode.sendCode() cannot be called without an emailAddress if an existing signIn does not exist.");return rO(this.resource,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_code",emailAddressId:i});if(!e)throw new U("Email code factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{emailAddressId:e.emailAddressId,strategy:"email_code"},action:"prepare_first_factor"})})}async verifyEmailCode(e){let{code:t}=e;return rO(this.resource,async()=>{await this.resource.__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.resource.id&&r)throw Error("signIn.emailLink.sendLink() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.resource.id&&!t)throw Error("signIn.emailLink.sendLink() cannot be called without an emailAddress if an existing signIn does not exist.");return rO(this.resource,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_link",emailAddressId:r});if(!e)throw new U("Email link factor not found",{code:"factor_not_found"});let n=i;try{new URL(i)}catch{n=window.location.origin+i}await this.resource.__internal_basePost({body:{emailAddressId:e.emailAddressId,redirectUrl:n,strategy:"email_link"},action:"prepare_first_factor"})})}async waitForEmailLinkVerification(){return rO(this.resource,async()=>{let{run:e,stop:t}=iM();await new Promise((i,r)=>{e(async()=>{try{let e=await this.resource.__internal_baseGet(),r=e.firstFactorVerification.status;("verified"===r||"expired"===r)&&(t(),i(e))}catch(e){t(),r(e)}})})})}async sendPhoneCode(e={}){let{phoneNumber:t,phoneNumberId:i,channel:r="sms"}=e;if(!this.resource.id&&i)throw Error("signIn.phoneCode.sendCode() cannot be called with an phoneNumberId if an existing signIn does not exist.");if(!this.resource.id&&!t)throw Error("signIn.phoneCode.sendCode() cannot be called without an phoneNumber if an existing signIn does not exist.");return rO(this.resource,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"phone_code",phoneNumberId:i});if(!e)throw new U("Phone code factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{phoneNumberId:e.phoneNumberId,strategy:"phone_code",channel:r},action:"prepare_first_factor"})})}async verifyPhoneCode(e){let{code:t}=e;return rO(this.resource,async()=>{await this.resource.__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,enterpriseConnectionId:a,identifier:o}=e;return rO(this.resource,async()=>{let e=i;try{new URL(i)}catch{e=window.location.origin+i}let l={redirectUrl:rE.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:e};if(n){let t=rC(rE.clerk,{redirectCallbackUrl:l.redirectUrl,redirectUrl:e});l.redirectUrl=t.redirectCallbackUrl,l.actionCompleteRedirectUrl=t.redirectUrl}await this._create({strategy:t,...l,identifier:o}),"enterprise_sso"===t&&await this.resource.__internal_basePost({body:{...l,oidcPrompt:s,enterpriseConnectionId:a,strategy:"enterprise_sso"},action:"prepare_first_factor"});let{status:c,externalVerificationRedirectURL:d}=this.resource.firstFactorVerification;"unverified"===c&&d&&(n?(await rP(rE.clerk,{popup:n,externalVerificationRedirectURL:d}),await this.resource.reload()):eF(d))})}async web3(e){let{strategy:t}=e,i=t.replace("web3_","").replace("_signature","");return rO(this.resource,async()=>{let e,r,n;switch(i){case"metamask":e=await th().getMetamaskIdentifier(),r=th().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await th().getCoinbaseWalletIdentifier(),r=th().generateSignatureWithCoinbaseWallet;break;case"base":e=await th().getBaseIdentifier(),r=th().generateSignatureWithBase;break;case"okx_wallet":e=await th().getOKXWalletIdentifier(),r=th().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${i}`)}await this._create({identifier:e});let s=this.resource.supportedFirstFactors?.find(e=>e.strategy===t);if(!s)throw new U("Web3 first factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{web3WalletId:s.web3WalletId,strategy:t},action:"prepare_first_factor"});let{message:a}=this.firstFactorVerification;if(!a)throw new U("Web3 nonce not found",{code:"web3_nonce_not_found"});try{n=await r({identifier:e,nonce:a})}catch(t){if("coinbase_wallet"===i&&4001===t.code)n=await r({identifier:e,nonce:a});else throw t}await this.resource.__internal_basePost({body:{signature:n,strategy:t},action:"attempt_first_factor"})})}async passkey(e){let{flow:t}=e||{},i=rE.clerk.__internal_isWebAuthnSupported||rc,r=rE.clerk.__internal_getPublicCredentials||i$,n=rE.clerk.__internal_isWebAuthnAutofillSupported||rd;if(!i())throw new I("Passkeys are not supported",{code:"passkey_not_supported"});return rO(this.resource,async()=>{if("autofill"===t||"discoverable"===t)await this._create({strategy:"passkey"});else{if(!this.supportedFirstFactors.find(e=>"passkey"===e.strategy))throw new U("Passkey factor not found",{code:"factor_not_found"});await this.resource.__internal_basePost({body:{strategy:"passkey"},action:"prepare_first_factor"})}let{nonce:e}=this.firstFactorVerification,i=e?ij(JSON.parse(e)):null;if(!i)throw new U("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 I(o.message,{code:"passkey_retrieval_failed"});await this.resource.__internal_basePost({body:{publicKeyCredential:JSON.stringify(iJ(a)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return rO(this.resource,async()=>{let e=this.resource.supportedSecondFactors?.find(e=>"phone_code"===e.strategy);if(!e)throw new U("Phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:t}=e;await this.resource.__internal_basePost({body:{phoneNumberId:t,strategy:"phone_code"},action:"prepare_second_factor"})})}async verifyMFAPhoneCode(e){let{code:t}=e;return rO(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_second_factor"})})}async verifyTOTP(e){let{code:t}=e;return rO(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:t,strategy:"totp"},action:"attempt_second_factor"})})}async verifyBackupCode(e){let{code:t}=e;return rO(this.resource,async()=>{await this.resource.__internal_basePost({body:{code:t,strategy:"backup_code"},action:"attempt_second_factor"})})}async ticket(e){let t=e?.ticket??eI("__clerk_ticket");return this.create({ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};if(!this.resource.createdSessionId)throw Error("Cannot finalize sign-in without a created session.");return rO(this.resource,async()=>{rE.clerk.client&&!rE.clerk.client.sessions.some(e=>e.id===this.resource.createdSessionId)&&await rE.clerk.client.reload(),this.#F=!0,await rE.clerk.setActive({session:this.resource.createdSessionId,navigate:t})})}selectFirstFactor({strategy:e,emailAddressId:t,phoneNumberId:i}){if(!this.resource.supportedFirstFactors)return null;if(t){let i=this.resource.supportedFirstFactors.find(i=>i.strategy===e&&i.emailAddressId===t);if(i)return i}if(i){let t=this.resource.supportedFirstFactors.find(t=>t.strategy===e&&t.phoneNumberId===i);if(t)return t}let r=this.resource.supportedFirstFactors.find(t=>t.strategy===e&&t.safeIdentifier===this.resource.identifier);if(r)return r;let n=this.resource.supportedFirstFactors.find(t=>t.strategy===e);return n||null}}function rR(e){let{unsafeMetadata:t}={...e},i=t?"object"==typeof t?JSON.stringify(t):t:"";return{...e,...t?{unsafeMetadata:i}:{}}}class rz extends tR{pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new iH(null);username=null;firstName=null;lastName=null;emailAddress=null;phoneNumber=null;web3wallet=null;externalAccount;hasPassword=!1;unsafeMetadata={};createdSessionId=null;createdUserId=null;abandonAt=null;legalAcceptedAt=null;locale=null;get status(){return this._status}set status(e){let t=this._status;this._status=e,e&&t!==e&&e4.debug("SignUp.status",{id:this.id,from:t,to:e})}__internal_future=new rM(this);__internal_basePost=this._basePost.bind(this);__internal_basePatch=this._basePatch.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{e4.debug("SignUp.create",{id:this.id,strategy:e.strategy});let t={...e};if(!t.locale){let e=tl();e&&(t.locale=e)}if(!this.clientBypass()&&!this.shouldBypassCaptchaForAttempt(e)){let e=new tE(rz.clerk),i=await e.managedOrInvisible({action:"signup"});if(!i)throw new U("",{code:"captcha_unavailable"});t={...t,...i}}if(t.transfer&&this.shouldBypassCaptchaForAttempt(t)){let e=rz.clerk.client?.signIn.firstFactorVerification.strategy;e&&(t={...t,strategy:e})}return this._basePost({path:this.pathRoot,body:rR(t)})};prepareVerification=e=>(e4.debug("SignUp.prepareVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_verification"}));attemptVerification=e=>(e4.debug("SignUp.attemptVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"attempt_verification"}));prepareEmailAddressVerification=e=>this.prepareVerification(e||{strategy:"email_code"});attemptEmailAddressVerification=e=>this.attemptVerification({...e,strategy:"email_code"});createEmailLinkFlow=()=>{let{run:e,stop:t}=iM();return{startEmailLinkFlow:async({redirectUrl:i})=>(this.id||ty("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}=e||{},o=s.replace("web3_","").replace("_signature","");"function"!=typeof i&&tk("generateSignature");let l=r||this.web3wallet;await this.create({web3Wallet:l,unsafeMetadata:n,legalAccepted:a}),await this.prepareWeb3WalletVerification({strategy:s});let{message:c}=this.verifications.web3Wallet;c||tv("SignUp");try{t=await i({identifier:r,nonce:c,provider:o})}catch(e){if("coinbase_wallet"===o&&4001===e.code)t=await i({identifier:r,nonce:c,provider:o});else throw e}return this.attemptWeb3WalletVerification({signature:t,strategy:s})};authenticateWithMetamask=async e=>{let t=await th().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:th().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let t=await th().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:th().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let t=await th().getBaseIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:th().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let t=await th().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:th().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithRedirectOrPopup=async(e,t)=>{let{redirectUrl:i,redirectUrlComplete:r,strategy:n,continueSignUp:s=!1,unsafeMetadata:a,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:d}=e,h=rz.clerk.buildUrlWithAuth(i),u=()=>{let e={strategy:n,redirectUrl:h,actionCompleteRedirectUrl:r,unsafeMetadata:a,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:d};return s&&this.id?this.update(e):this.create(e)},{verifications:p}=await u().catch(async e=>{if(O(e)&&C(e))return await rz.clerk.__unstable__environment.reload(),u();throw e}),{externalAccount:f}=p,{status:m,externalVerificationRedirectURL:g}=f;"unverified"===m&&g?t(g):tS(m,rz.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eF);authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||tk("popup"),rI(rz.clerk,"signUp",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e instanceof URL?e.toString():e})};update=e=>this._basePatch({body:rR(e)});upsert=e=>this.id?this.update(e):this.create(e);validatePassword=(e,t)=>{if(rz.clerk.__unstable__environment?.userSettings.passwordSettings)return rU(rT(),{...rz.clerk.__unstable__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 iH(e.verifications),this.username=e.username,this.firstName=e.first_name,this.lastName=e.last_name,this.emailAddress=e.email_address,this.phoneNumber=e.phone_number,this.hasPassword=e.has_password,this.unsafeMetadata=e.unsafe_metadata,this.createdSessionId=e.created_session_id,this.createdUserId=e.created_user_id,this.abandonAt=e.abandon_at,this.web3wallet=e.web3_wallet,this.legalAcceptedAt=e.legal_accepted_at,this.locale=e.locale),i2.emit("resource:update",{resource:this}),this}__internal_toSnapshot(){return{object:"sign_up",id:this.id||"",status:this.status||null,required_fields:this.requiredFields,optional_fields:this.optionalFields,missing_fields:this.missingFields,unverified_fields:this.unverifiedFields,verifications:this.verifications.__internal_toSnapshot(),username:this.username,first_name:this.firstName,last_name:this.lastName,email_address:this.emailAddress,phone_number:this.phoneNumber,has_password:this.hasPassword,unsafe_metadata:this.unsafeMetadata,created_session_id:this.createdSessionId,created_user_id:this.createdUserId,abandon_at:this.abandonAt,web3_wallet:this.web3wallet,legal_accepted_at:this.legalAcceptedAt,locale:this.locale,external_account:this.externalAccount,external_account_strategy:this.externalAccount?.strategy}}clientBypass(){return rz.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){if(!e.strategy)return!1;let t=rz.clerk.__unstable__environment.displayConfig.captchaOauthBypass;return!!(t.some(t=>t===e.strategy)||e.transfer&&t.some(e=>e===rz.clerk.client.signIn.firstFactorVerification.strategy))}__experimental_getEnterpriseConnections=()=>tR._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new rF(e)))}class rM{resource;verifications={sendEmailCode:this.sendEmailCode.bind(this),verifyEmailCode:this.verifyEmailCode.bind(this),sendPhoneCode:this.sendPhoneCode.bind(this),verifyPhoneCode:this.verifyPhoneCode.bind(this)};#F=!1;constructor(e){this.resource=e}get id(){return this.resource.id}get requiredFields(){return this.resource.requiredFields}get optionalFields(){return this.resource.optionalFields}get missingFields(){return this.resource.missingFields}get status(){return this.resource.status||"missing_requirements"}get username(){return this.resource.username}get firstName(){return this.resource.firstName}get lastName(){return this.resource.lastName}get emailAddress(){return this.resource.emailAddress}get phoneNumber(){return this.resource.phoneNumber}get web3Wallet(){return this.resource.web3wallet}get hasPassword(){return this.resource.hasPassword}get unsafeMetadata(){return this.resource.unsafeMetadata}get createdSessionId(){return this.resource.createdSessionId}get createdUserId(){return this.resource.createdUserId}get abandonAt(){return this.resource.abandonAt}get legalAcceptedAt(){return this.resource.legalAcceptedAt}get locale(){return this.resource.locale}get unverifiedFields(){return this.resource.unverifiedFields}get isTransferable(){return"transferable"===this.resource.verifications.externalAccount.status&&this.resource.verifications.externalAccount.error?.code==="external_account_exists"}get existingSession(){if(("failed"===this.resource.verifications.externalAccount.status||"unverified"===this.resource.verifications.externalAccount.status)&&this.resource.verifications.externalAccount.error?.code==="identifier_already_signed_in"&&this.resource.verifications.externalAccount.error?.meta?.sessionId)return{sessionId:this.resource.verifications.externalAccount.error?.meta?.sessionId}}get hasBeenFinalized(){return this.#F}async getCaptchaToken(){let e=new tE(rz.clerk),t=await e.managedOrInvisible({action:"signup"});if(!t)throw Error("Captcha challenge failed");let{captchaError:i,captchaToken:r,captchaWidgetType:n}=t;return{captchaToken:r,captchaWidgetType:n,captchaError:i}}async _create(e){let{captchaToken:t,captchaWidgetType:i,captchaError:r}=await this.getCaptchaToken(),n={transfer:e.transfer,captchaToken:t,captchaWidgetType:i,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rR(e.unsafeMetadata):void 0,locale:e.locale??tl()};await this.resource.__internal_basePost({path:this.resource.pathRoot,body:n})}async create(e){return rO(this.resource,async()=>{await this._create(e)})}async update(e){return rO(this.resource,async()=>{let t={...e,unsafeMetadata:e.unsafeMetadata?rR(e.unsafeMetadata):void 0};await this.resource.__internal_basePatch({path:this.resource.pathRoot,body:t})})}async password(e){return rO(this.resource,async()=>{let{captchaToken:t,captchaWidgetType:i,captchaError:r}=await this.getCaptchaToken(),n={strategy:"password",captchaToken:t,captchaWidgetType:i,captchaError:r,...e,unsafeMetadata:e.unsafeMetadata?rR(e.unsafeMetadata):void 0};await this.resource.__internal_basePost({path:this.resource.pathRoot,body:n})})}async sendEmailCode(){return rO(this.resource,async()=>{await this.resource.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification"})})}async verifyEmailCode(e){let{code:t}=e;return rO(this.resource,async()=>{await this.resource.__internal_basePost({body:{strategy:"email_code",code:t},action:"attempt_verification"})})}async sendPhoneCode(e){let{phoneNumber:t,channel:i="sms"}=e;return rO(this.resource,async()=>{if(!this.resource.id){let{captchaToken:e,captchaWidgetType:i,captchaError:r}=await this.getCaptchaToken();await this.resource.__internal_basePost({path:this.resource.pathRoot,body:{phoneNumber:t,captchaToken:e,captchaWidgetType:i,captchaError:r}})}await this.resource.__internal_basePost({body:{strategy:"phone_code",channel:i},action:"prepare_verification"})})}async verifyPhoneCode(e){let{code:t}=e;return rO(this.resource,async()=>{await this.resource.__internal_basePost({body:{strategy:"phone_code",code:t},action:"attempt_verification"})})}async sso(e){let{strategy:t,redirectUrl:i,redirectCallbackUrl:r,unsafeMetadata:n,legalAccepted:s,oidcPrompt:a,enterpriseConnectionId:o,emailAddress:l,popup:c}=e;return rO(this.resource,async()=>{let{captchaToken:e,captchaWidgetType:d,captchaError:h}=await this.getCaptchaToken(),u=i;try{new URL(i)}catch{u=window.location.origin+i}let p={redirectUrl:rz.clerk.buildUrlWithAuth(r),actionCompleteRedirectUrl:u};if(c){let e=rC(rz.clerk,{redirectCallbackUrl:p.redirectUrl,redirectUrl:u});p.redirectUrl=e.redirectCallbackUrl,p.actionCompleteRedirectUrl=e.redirectUrl}let f=()=>this.resource.__internal_basePost({path:this.resource.pathRoot,body:{strategy:t,...p,unsafeMetadata:n,legalAccepted:s,oidcPrompt:a,enterpriseConnectionId:o,emailAddress:l,captchaToken:e,captchaWidgetType:d,captchaError:h}});await f().catch(async e=>{if(O(e)&&C(e))return await rz.clerk.__unstable__environment.reload(),f();throw e});let{status:m,externalVerificationRedirectURL:g}=this.resource.verifications.externalAccount;"unverified"===m&&g&&(c?(await rP(rz.clerk,{popup:c,externalVerificationRedirectURL:g}),await this.resource.reload()):eF(g))})}async web3(e){let{strategy:t,unsafeMetadata:i,legalAccepted:r}=e,n=t.replace("web3_","").replace("_signature","");return rO(this.resource,async()=>{let e,s,a;switch(n){case"metamask":e=await th().getMetamaskIdentifier(),s=th().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await th().getCoinbaseWalletIdentifier(),s=th().generateSignatureWithCoinbaseWallet;break;case"base":e=await th().getBaseIdentifier(),s=th().generateSignatureWithBase;break;case"okx_wallet":e=await th().getOKXWalletIdentifier(),s=th().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${n}`)}let o=e||this.resource.web3wallet;await this._create({web3Wallet:o,unsafeMetadata:i,legalAccepted:r}),await this.resource.__internal_basePost({body:{strategy:t},action:"prepare_verification"});let{message:l}=this.resource.verifications.web3Wallet;l||tv("SignUp");try{a=await s({identifier:e,nonce:l})}catch(t){if("coinbase_wallet"===n&&4001===t.code)a=await s({identifier:e,nonce:l});else throw t}await this.resource.__internal_basePost({body:{signature:a,strategy:t},action:"attempt_verification"})})}async ticket(e){let t=e?.ticket??eI("__clerk_ticket");return this.create({...e,ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};return rO(this.resource,async()=>{if(!this.resource.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#F=!0,await rz.clerk.setActive({session:this.resource.createdSessionId,navigate:t})})}}class rF extends tR{id;name;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name),this}}class rN extends tR{pathRoot="tokens";jwt;static async create(e,t={},i=!1){return new rN(await tR._fetch({body:t,method:"POST",path:e,search:i?"debug=skip_cache":void 0}),e)}constructor(e,t){super(),t&&(this.pathRoot=t),e?.jwt&&(this.jwt=to(e.jwt))}getRawString=()=>this.jwt?.claims.__raw||"";fromJSON(e){return e&&(this.jwt=to(e.jwt)),this}__internal_toSnapshot(){return{object:"token",id:this.id||"",jwt:this.getRawString()}}}class rW extends tR{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=tz(e.updated_at),this.createdAt=tz(e.created_at)),this}}class rD extends tR{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=tz(e.updated_at),this.createdAt=tz(e.created_at)),this}}class r$ extends tR{pathRoot="/me";id="";externalId=null;username=null;emailAddresses=[];phoneNumbers=[];web3Wallets=[];externalAccounts=[];enterpriseAccounts=[];passkeys=[];organizationMemberships=[];passwordEnabled=!1;firstName=null;lastName=null;fullName=null;primaryEmailAddressId=null;primaryEmailAddress=null;primaryPhoneNumberId=null;primaryPhoneNumber=null;primaryWeb3WalletId=null;primaryWeb3Wallet=null;imageUrl="";hasImage=!1;twoFactorEnabled=!1;totpEnabled=!1;backupCodeEnabled=!1;publicMetadata={};unsafeMetadata={};createOrganizationEnabled=!1;createOrganizationsLimit=null;deleteSelfEnabled=!1;lastSignInAt=null;legalAcceptedAt=null;updatedAt=null;createdAt=null;cachedSessionsWithActivities=null;static isUserResource(e){return!!e&&e instanceof r$}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case iF:return this.primaryEmailAddressId===e.id;case rp:return this.primaryPhoneNumberId===e.id;case rV:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:t}=e||{};return new iF({email_address:t},this.path()+"/email_addresses/").create()};createPasskey=()=>ru.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:t}=e||{};return new rp({phone_number:t},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:t}=e||{};return new rV({web3_wallet:t},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:t,redirectUrl:i,additionalScopes:r}=e||{};return new i9((await tR._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:t,redirect_url:i,additional_scope:r}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new rW((await tR._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new rW((await tR._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new iT((await tR._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new rD((await tR._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);update=e=>this._basePatch({body:rR(e)});updatePassword=e=>this._basePost({body:e,path:`${this.path()}/change_password`});removePassword=e=>this._basePost({body:e,path:`${this.path()}/remove_password`});delete=()=>this._baseDelete({path:"/me"}).then(e=>(i2.emit(i0,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await rS.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:t}=e||{};return null===t?re.delete(`${this.path()}/profile_image`):re.create(`${this.path()}/profile_image`,{file:t})};getOrganizationInvitations=e=>rj.retrieve(e);getOrganizationSuggestions=e=>rl.retrieve(e);getOrganizationMemberships=e=>ro.retrieve(e);leaveOrganization=async e=>new iT((await tR._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);initializePaymentMethod=e=>ih(e);addPaymentMethod=e=>iu(e);getPaymentMethods=e=>ip(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 iF(e,this.path()+"/email_addresses")),this.primaryEmailAddressId=e.primary_email_address_id||null,this.primaryEmailAddress=this.emailAddresses.find(({id:e})=>e===this.primaryEmailAddressId)||null,this.phoneNumbers=(e.phone_numbers||[]).map(e=>new rp(e,this.path()+"/phone_numbers")),this.primaryPhoneNumberId=e.primary_phone_number_id||null,this.primaryPhoneNumber=this.phoneNumbers.find(({id:e})=>e===this.primaryPhoneNumberId)||null,this.web3Wallets=(e.web3_wallets||[]).map(e=>new rV(e,this.path()+"/web3_wallets")),this.primaryWeb3WalletId=e.primary_web3_wallet_id||null,this.primaryWeb3Wallet=this.web3Wallets.find(({id:e})=>e===this.primaryWeb3WalletId)||null,this.externalAccounts=(e.external_accounts||[]).map(e=>new i9(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new ru(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new ro(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new iY(e,this.path()+"/enterprise_accounts")),this.publicMetadata=e.public_metadata||{},this.unsafeMetadata=e.unsafe_metadata||{},this.totpEnabled=e.totp_enabled||!1,this.backupCodeEnabled=e.backup_code_enabled||!1,this.twoFactorEnabled=e.two_factor_enabled||!1,this.createOrganizationEnabled=e.create_organization_enabled||!1,this.createOrganizationsLimit=e.create_organizations_limit||null,this.deleteSelfEnabled=e.delete_self_enabled||!1,e.last_sign_in_at&&(this.lastSignInAt=tz(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=tz(e.legal_accepted_at)),this.updatedAt=tz(e.updated_at||void 0),this.createdAt=tz(e.created_at||void 0)),this}__internal_toSnapshot(){return{object:"user",id:this.id,external_id:this.externalId,first_name:this.firstName,last_name:this.lastName,username:this.username,public_metadata:this.publicMetadata,unsafe_metadata:this.unsafeMetadata,image_url:this.imageUrl,has_image:this.hasImage,email_addresses:this.emailAddresses.map(e=>e.__internal_toSnapshot()),phone_numbers:this.phoneNumbers.map(e=>e.__internal_toSnapshot()),web3_wallets:this.web3Wallets.map(e=>e.__internal_toSnapshot()),external_accounts:this.externalAccounts.map(e=>e.__internal_toSnapshot()),passkeys:this.passkeys.map(e=>e.__internal_toSnapshot()),organization_memberships:this.organizationMemberships.map(e=>e.__internal_toSnapshot()),enterprise_accounts:this.enterpriseAccounts.map(e=>e.__internal_toSnapshot()),totp_enabled:this.totpEnabled,backup_code_enabled:this.backupCodeEnabled,two_factor_enabled:this.twoFactorEnabled,create_organization_enabled:this.createOrganizationEnabled,create_organizations_limit:this.createOrganizationsLimit,delete_self_enabled:this.deleteSelfEnabled,primary_email_address_id:this.primaryEmailAddressId,primary_phone_number_id:this.primaryPhoneNumberId,primary_web3_wallet_id:this.primaryWeb3WalletId,password_enabled:this.passwordEnabled,profile_image_id:this.imageUrl,last_sign_in_at:this.lastSignInAt?.getTime()||null,legal_accepted_at:this.legalAcceptedAt?.getTime()||null,updated_at:this.updatedAt?.getTime()||null,created_at:this.createdAt?.getTime()||null}}}class rL{firstName;lastName;imageUrl;hasImage;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.firstName=e.first_name,this.lastName=e.last_name,this.imageUrl=e.image_url??void 0,this.hasImage=e.has_image??void 0),this}__internal_toSnapshot(){return{first_name:this.firstName,last_name:this.lastName,image_url:this.imageUrl||null,has_image:this.hasImage||null}}}class rj extends tR{id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await tR._fetch({path:"/me/organization_invitations",method:"GET",search:t4(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new rj(e))}})}constructor(e){super(),this.fromJSON(e)}accept=async()=>await this._basePost({path:`/me/organization_invitations/${this.id}/accept`});fromJSON(e){return e&&(this.id=e.id,this.emailAddress=e.email_address,this.publicOrganizationData={hasImage:e.public_organization_data.has_image,imageUrl:e.public_organization_data.image_url,name:e.public_organization_data.name,id:e.public_organization_data.id,slug:e.public_organization_data.slug},this.publicMetadata=e.public_metadata,this.role=e.role,this.status=e.status,this.createdAt=tz(e.created_at),this.updatedAt=tz(e.updated_at)),this}}let rB={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 rJ extends tR{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:{...rB,name:"phone_number"},username:{...rB,name:"username"},web3_wallet:{...rB,name:"web3_wallet"},first_name:{...rB,name:"first_name"},last_name:{...rB,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:{...rB,name:"authenticator_app"},backup_code:{...rB,name:"backup_code"},passkey:{...rB,name:"passkey"}};enterpriseSSO={enabled:!1};passkeySettings={allow_autofill:!1,show_sign_in_button:!1};passwordSettings={};signIn={second_factor:{required:!1,enabled:!1}};signUp={allowlist_only:!1,captcha_enabled:!1,legal_consent_enabled:!1,mode:"public",progressive:!0};social={};usernameSettings={};get authenticatableSocialStrategies(){return this.social?Object.entries(this.social).filter(([,e])=>e.enabled&&e.authenticatable).map(([,e])=>e.strategy).sort():[]}get enabledFirstFactorIdentifiers(){return this.attributes?Object.entries(this.attributes).filter(([e,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.signIn=this.withDefault(e.sign_in,this.signIn),this.signUp=this.withDefault(e.sign_up,this.signUp),this.social=this.withDefault(e.social,this.social),this.usernameSettings=e.username_settings?{...e.username_settings,min_length:Math.max(e.username_settings?.min_length??4,4),max_length:Math.min(e.username_settings?.max_length??64,64)}:this.usernameSettings),this}__internal_toSnapshot(){return{actions:this.actions,attributes:this.attributes,passkey_settings:this.passkeySettings,password_settings:this.passwordSettings,sign_in:this.signIn,sign_up:this.signUp,social:this.social}}}class rK extends tR{pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=tz(e.updated_at),this.createdAt=tz(e.created_at)),this}static async join(e){return new rK((await tR._fetch({path:"/waitlist",method:"POST",body:e}))?.response)}}class rV extends tR{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",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 iq(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}function rq(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 rG(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(iP.isClientResource(e))return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.sessions.length!==t.sessions.length;if(rk.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&&rq(i.user,r.user))}if(r$.isUserResource(e))return rq(e,t)}catch{}return!0}(e,t)?e:t}let rH="__clerk_db_jwt";function rX(e,t){let i=new URL(e),r=i.searchParams.get(rH);i.searchParams.delete(rH);let n=r||t;return n&&i.searchParams.set(rH,n),i}let rY=e=>{let t=new URL(e);return t.searchParams.delete(rH),t},rQ=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 rZ(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var r in i)e[r]=i[r]}return e}var r0=function e(t,i){function r(e,r,n){if("undefined"!=typeof document){"number"==typeof(n=rZ({},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("undefined"!=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(r[o]=t.read(a,o),e===o)break}catch(e){}}return e?r[e]:r}},remove:function(e,t){r(e,"",rZ({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,rZ({},this.attributes,t))},withConverter:function(t){return e(rZ({},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 r1(e){return{get:()=>r0.get(e),set(t,i={}){r0.set(e,t,i)},remove(t){r0.remove(e,t)}}}let r3=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function r2(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 r4=r1("__clerk_test_etld"),r5="__client_uat",r6="__session",r9=()=>{let e="None",t=r3(e);return{sameSite:e,secure:t,partitioned:t}};async function r7(e){let t;try{t=await eo(e)}catch(o){var i;i=`Suffixed cookie failed due to ${o.message} (secure-context: ${window.isSecureContext}, url: ${window.location.href})`,j.has(i)||(console.log(i),j.add(i));let{default:r}=await Promise.all([s.e("545"),s.e("811")]).then(s.t.bind(s,180,23)),{default:n}=await Promise.all([s.e("545"),s.e("811")]).then(s.t.bind(s,3413,23)),a=r(e);t=n.stringify(a).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}return t}let r8=()=>{let e=!function(){if(!function(){if(!tc())return!1;try{return window.self!==window.top}catch{return!0}}())return!1;try{return window.top?.location.href,!1}catch{return!0}}()?"Lax":"None",t=r3(e);return{sameSite:e,secure:t}};var ne=s(5945),nt=s.n(ne);class ni{lock=(function(e){let t=new(nt());return window.addEventListener("beforeunload",async()=>{await t.releaseLock(e)}),{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)}}}})("clerk.lock.refreshSessionToken");workerTimers=iz();timerId=null;initiated=!1;startPollingForSessionToken(e){if(this.timerId||this.initiated)return;let t=async()=>{this.initiated=!0,await this.lock.acquireLockAndRun(e),this.timerId=this.workerTimers.setTimeout(t,5e3)};t()}stopPollingForSessionToken(){null!=this.timerId&&(this.workerTimers.clearTimeout(this.timerId),this.timerId=null),this.initiated=!1}}class nr{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,t,i,r){let n=await r7(e.publishableKey),s=new nr(e,t,n,i,r);return await s.setup(),s}constructor(e,t,r,n,s){this.clerk=e,this.instanceType=n,this.clerkEventBus=s,i2.on(iZ,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),i2.on(i0,()=>this.handleSignOut()),this.refreshTokenOnFocus(),this.startPollingForToken(),this.clientUat=(e=>{let t=r1(r5),r=r1(el(r5,e));return{set:e=>{let n=r2(Date.now(),1),s="None",a=r3(s),o=function(e=window.location.hostname,t=r4){if(i)return i;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",{domain:n}),"1"===t.get())return t.remove({domain:n}),i=n,n;t.remove({domain:n})}}(),l="0";e&&e.updatedAt&&e.signedInSessions.length>0&&(l=Math.floor(e.updatedAt.getTime()/1e3).toString()),r.remove(),t.remove(),r.set(l,{domain:o,expires:n,partitioned:a,sameSite:s,secure:a}),t.set(l,{domain:o,expires:n,partitioned:a,sameSite:s,secure:a})},get:()=>parseInt(r.get()||t.get()||"0",10)}})(r),this.sessionCookie=(e=>{let t=r1(r6),i=r1(el(r6,e)),r=()=>{let e=r9();t.remove(e),i.remove(e)};return{set:e=>{let n=r2(Date.now(),1),{sameSite:s,secure:a,partitioned:o}=r9();o&&r(),t.set(e,{expires:n,sameSite:s,secure:a,partitioned:o}),i.set(e,{expires:n,sameSite:s,secure:a,partitioned:o})},remove:r,get:()=>i.get()||t.get()}})(r),this.activeCookie=(()=>{let e=r1("clerk_active_context"),t={secure:r3("None")};return{set:i=>{e.set(i,t)},get:()=>e.get(),remove:()=>e.remove(t)}})(),this.devBrowser=function({cookieSuffix:e,frontendApi:t,fapiClient:i}){let r,n,s=(r=r1(rH),n=r1(el(rH,e)),{get:()=>n.get()||r.get(),set:e=>{let t=r2(Date.now(),1),{sameSite:i,secure:s}=r8();n.set(e,{expires:t,sameSite:i,secure:s}),r.set(e,{expires:t,sameSite:i,secure:s})},remove:()=>{let e=r8();n.remove(e),r.remove(e)}});function a(){return s.get()}function o(e){s.set(e)}function l(){s.remove()}return{clear:function(){l()},setup:async function(){var e;let r;if(!ep(t))return;i.onBeforeRequest(e=>{let t=a();t&&e?.url&&(e.url=rX(e.url,t))}),i.onAfterResponse((e,t)=>{let i=t?.headers?.get("Clerk-Db-Jwt");i&&o(i)});let n=(r=(e=new URL(window.location.href)).searchParams.get(rH)||"",rY(rQ(e)).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",rY(rQ(e))),r);if(n)return void o(n);if(s.get())return;let l=i.buildUrl({path:"/dev_browser"}),c=await fetch(l.toString(),{method:"POST"});if(!c.ok){let e=function(e=[]){return e.length>0?e.map(e=>new b(e)):[]}((await c.json()).errors);e[0]?t_(e[0].longMessage):t_()}let d=await c.json();o(d?.id)},getDevBrowserJWT:a,setDevBrowserJWT:o,removeDevBrowserJWT:l}}({frontendApi:e.frontendApi,fapiClient:t,cookieSuffix:r})}async setup(){return"production"===this.instanceType?this.setupProduction():this.setupDevelopment()}isSignedOut(){return this.clerk.loaded?!!this.clerk.user:0>=this.clientUat.get()}async handleUnauthenticatedDevBrowser(){this.devBrowser.clear(),await this.devBrowser.setup()}decorateUrlWithDevBrowserToken(e){let t=this.devBrowser.getDevBrowserJWT();if(!t)throw Error(`${tg} Missing dev browser jwt. Please contact support.`);return rX(e,t)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new ni,this.poller.startPollingForSessionToken(()=>this.refreshSessionToken()))}stopPollingForToken(){this.poller&&(this.poller.stopPollingForSessionToken(),this.poller=null)}refreshTokenOnFocus(){window.addEventListener("focus",()=>{"visible"===document.visibilityState&&this.refreshSessionToken({updateCookieImmediately:!0})})}async refreshSessionToken({updateCookieImmediately:e=!1}={}){if(this.clerk.session)try{let t=await this.clerk.session.getToken();e&&this.updateSessionCookie(t)}catch(e){return this.handleGetTokenError(e)}}updateSessionCookie(e){if(document.hasFocus()||this.isCurrentContextActive())return e||c()||e4.warn("Removing session cookie (offline)",{sessionId:this.clerk.session?.id},"authCookieService"),this.setActiveContextInStorage(),e?this.sessionCookie.set(e):this.sessionCookie.remove()}setClientUatCookieForDevelopmentInstances(){"production"!==this.instanceType&&this.inCustomDevelopmentDomain()&&this.clientUat.set(this.clerk.client)}inCustomDevelopmentDomain(){let e=this.clerk.frontendApi.replace("clerk.","");return!window.location.host.endsWith(e)}handleGetTokenError(e){if(O(e)||T(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(P(e))return void this.clerk.handleUnauthenticated().catch(eY);this.clerkEventBus.emit(f,"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()}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 nn{clerk;captchaChallenge;timers;constructor(e,t=new tE(e),i=iz()){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.__unstable__environment?.displayConfig?.captchaHeartbeat}clientBypass(){return this.clerk.client?.captchaBypass}intervalInMs(){return this.clerk.__unstable__environment?.displayConfig?.captchaHeartbeatIntervalMs??6e5}}let ns=["/client","/waitlist"];class na{async getBaseFapiProxyOptions(){let e=await tR.clerk.session?.getToken();if(!e)throw new U("No valid session token available",{code:"no_session_token"});return{pathPrefix:"",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},credentials:"same-origin"}}async getAll(e){return tR._fetch({...await this.getBaseFapiProxyOptions(),method:"GET",path:"/api_keys",search:t4({...e,subject:e?.subject??tR.clerk.organization?.id??tR.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new tM(e))}})}async create(e){return new tM(await tR._fetch({...await this.getBaseFapiProxyOptions(),path:"/api_keys",method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??tR.clerk.organization?.id??tR.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new tM(await tR._fetch({...await this.getBaseFapiProxyOptions(),method:"POST",path:`/api_keys/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let no=new Map;class nl{#N=!1;load(e){let t=e?.protectConfig;if(t?.loaders&&Array.isArray(t.loaders)&&0!==t.loaders.length&&!this.#N){if(n())for(let e of(this.#N=!0,t.loaders))try{this.applyLoader(e)}catch(e){B(`[protect] failed to apply loader: ${e}`)}}}applyLoader(e){if(void 0!==e.rollout){let t=e.rollout;if("number"!=typeof t||t<0)return void B(`[protect] loader rollout value is invalid: ${t}`);if(0===t||Math.random()>t)return}let t=e.type||"script",i=e.target||"body",r=document.createElement(t);if(e.attributes)for(let[t,i]of Object.entries(e.attributes))switch(typeof i){case"string":case"number":case"boolean":r.setAttribute(t,String(i));break;default:B(`[protect] loader attribute is invalid type: ${t}=${i}`)}switch(e.textContent&&"string"==typeof e.textContent&&(r.textContent=e.textContent),i){case"head":document.head.appendChild(r);break;case"body":document.body.appendChild(r);break;default:if(i?.startsWith("#")){let e=document.getElementById(i.substring(1));if(!e)return void B(`[protect] loader target element not found: ${i}`);e.appendChild(r);return}B(`[protect] loader target is invalid: ${i}`)}}}class nc{signInResourceSignal=t6;signInErrorSignal=t9;signInFetchSignal=t7;signInSignal=t8;signUpResourceSignal=ie;signUpErrorSignal=it;signUpFetchSignal=ii;signUpSignal=ir;__internal_effect=tY;__internal_computed=tX;constructor(){i2.on("resource:update",this.onResourceUpdated),i2.on("resource:error",this.onResourceError),i2.on("resource:fetch",this.onResourceFetch)}onResourceError=e=>{e.resource instanceof rE&&this.signInErrorSignal({error:e.error}),e.resource instanceof rz&&this.signUpErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof rE){if(nd(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof rz){if(nd(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}};onResourceFetch=e=>{e.resource instanceof rE&&this.signInFetchSignal({status:e.status}),e.resource instanceof rz&&this.signUpFetchSignal({status:e.status})}}function nd(e,t){return!t?.id&&e&&e.__internal_future?.hasBeenFinalized===!1}let nh="cannot_render_billing_disabled",nu="cannot_render_user_missing",np="cannot_render_organizations_disabled",nf="cannot_render_organization_missing",nm="cannot_render_single_session_enabled",ng={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 n_{static version="6.0.0-snapshot.v20251203203405";static sdkMetadata={name:"@clerk/clerk-js",version:"6.0.0-snapshot.v20251203203405"};static _billing;static _apiKeys;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new nc;internal_last_error=null;environment;#W;#D="";#$;#L;#j;#B;#J;#K=null;#V;#q;#G;#H="loading";#X=[];#Y=[];#Q={};#Z=null;#ee=0;#et=p();get __internal_queryClient(){return this.#W||Promise.all([s.e("662"),s.e("527")]).then(s.bind(s,250)).then(e=>e.QueryClient).then(e=>{this.#W||(this.#W=new e,this.#et.emit("queryClientStatus","ready"))}),this.#W?{__tag:"clerk-rq-client",client:this.#W}:void 0}__internal_getCachedResources;__internal_createPublicCredentials;__internal_getPublicCredentials;__internal_isWebAuthnSupported;__internal_isWebAuthnAutofillSupported;__internal_isWebAuthnPlatformAuthenticatorSupported;__internal_setActiveInProgress=!1;get publishableKey(){return this.#D}get version(){return n_.version}set sdkMetadata(e){n_.sdkMetadata=e}get sdkMetadata(){return n_.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#H}get isSatellite(){return!!tc()&&eX(this.#Q.isSatellite,new URL(window.location.href),!1)}get domain(){if(tc()){let e=function(e=""){return(e||"").replace(/^.+:\/\//,"")}(eX(this.#$,new URL(window.location.href)));if("production"===this.#G){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""}get proxyUrl(){if(tc()){let e=eX(this.#L,new URL(window.location.href));return!e||eN(e)||eW(e)||ts.throwInvalidProxyUrl({url:e}),e?eW(e)?new URL(e,window.location.origin).toString():e:""}return""}get frontendApi(){let e=es(this.publishableKey);return e?e.frontendApi:ts.throwInvalidPublishableKeyError({key:this.publishableKey})}get instanceType(){return this.#G}get isStandardBrowser(){return this.#Q.standardBrowser||!1}get billing(){return n_._billing||(n_._billing=new t5),n_._billing}get apiKeys(){return n_._apiKeys||(n_._apiKeys=new na),n_._apiKeys}__experimental_checkout(e){return this._checkout||(this._checkout=e=>(function(e,t){let i,r,n,s,{for:a,planId:o,planPeriod:l}=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 c=function(e){let{userId:t,orgId:i,planId:r,planPeriod:n}=e;return`${t}-${i||"user"}-${r}-${n}`}({userId:e.user?.id||"",orgId:"organization"===a?e.organization?.id:void 0,planId:o,planPeriod:l}),d=no.get(c);if(d)return d.signals.computedSignal();let h=(i=tH({resource:null}),r=tH({error:null}),n=tH({status:"idle"}),s=tX(()=>{let e=i().resource,t=r().error,s=n().status;return{errors:is(t,{}),fetchStatus:s,checkout:e}}),{resourceSignal:i,errorSignal:r,fetchSignal:n,computedSignal:s}),u=new il(h,{..."organization"===a?{orgId:e.organization?.id}:{},planId:o,planPeriod:l});return no.set(c,{resource:u,signals:h}),h.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#Q[e]}get isSignedIn(){return this?.session?.status!=="pending"&&!!this.session}constructor(e,t){if(!(e=(e||"").trim()))return ts.throwMissingPublishableKeyError();const i=es(e);if(!i)return ts.throwInvalidPublishableKeyError({key:e});this.#$=t?.domain,this.#L=t?.proxyUrl,this.environment=i6.getInstance(),this.#G=i.instanceType,this.#D=e,this.#q=function(e){let t=[],i=[];async function r(e){for await(let i of["undefined"!=typeof window&&window.__unstable__onBeforeRequest,...t].filter(e=>e))if(await i(e)===!1)return!1;return!0}async function n(e,t){for await(let r of["undefined"!=typeof window&&window.__unstable__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:s}){let a=new URLSearchParams(n);return a.append("__clerk_api_version","2025-11-10"),a.append("_clerk_js_version","6.0.0-snapshot.v20251203203405"),s&&a.append("rotating_token_nonce",s),e.domain&&"development"===e.instanceType&&e.isSatellite&&a.append("__domain",e.domain),t&&"GET"!==t&&"POST"!==t&&a.append("_method",t),i&&!ns.some(e=>i.startsWith(e))&&r&&a.append("_clerk_session_id",r),ed([...a.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)),eg({base:n.origin,pathname:`${a}/${r}${i}`,search:s(t)},{stringify:!1})}let n="production"===e.instanceType?e.domain:"";return eg({base:`https://${n||e.frontendApi}`,pathname:`${r}${i}`,search:s(t)},{stringify:!1})}async function o(t,i){let s,o={...t},{method:c="GET",body:d}=o;!d||"object"!=typeof d||d instanceof FormData||(o.body=function(e){if(!e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype)return e;let t={};for(let[i,r]of Object.entries(e))void 0!==r&&(t[i]=r);return t}(d)),o.url=a({...o,sessionId:e.getSessionId()}),o.headers=new Headers(o.headers),"GET"===c||d instanceof FormData||o.headers.has("content-type")||o.headers.set("content-type","application/x-www-form-urlencoded"),"application/x-www-form-urlencoded"===o.headers.get("content-type")&&(o.body=d?ed(d,{keyEncoder:q}):d);let h=await r(o),u="GET"===c?"GET":"POST",p=o.url,f={...o,method:u,credentials:o.credentials||"include"};try{if(h){let e=i?.fetchMaxTries??(l()?4:11);s=await e7(()=>fetch(p,f),{retryImmediately:!0,initialDelay:700,maxDelayBetweenRetries:5e3,shouldRetry:(t,i)=>"GET"===u&&i<e,onBeforeRetry:e=>{p.searchParams.set("_clerk_retry_attempt",e.toString())}})}else s=new Response("{}",o)}catch(t){let e=p.toString();e4.error("network error",{error:t,url:e,method:c},"fapiClient");throw Error(`${tg} Network error at "${e}" - ${t}. Please try again.`)}let m=204!==s.status?await s.json():null,g=Object.assign(s,{payload:m});return s.ok||e4.error("request failed",{method:c,path:o.path,status:s.status},"fapiClient"),await n(o,g),g}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,proxyUrl:this.proxyUrl}),this.#et.emit(f,"loading"),this.#et.prioritizedOn(f,e=>this.#H=e),tR.clerk=this,this.#B=new nl}getFapiClient=()=>this.#q;load=async e=>{if(e4.info("load() start",{},"clerk"),!this.loaded){if("development"===this.#G&&B("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.#Q=this.#ei(e),this.#Q.clerkUiCtor&&(this.#V=Promise.resolve(this.#Q.clerkUiCtor).then(e=>new e(()=>this,()=>this.environment,this.#Q,new te))),"development"===this.#G&&(this.#Q.routerPush||this.#Q.routerReplace)&&(!this.#Q.routerPush||!this.#Q.routerReplace)){let e=this.#Q.routerPush?"routerReplace":"routerPush";B(`Clerk: Both \`routerPush\` and \`routerReplace\` need to be defined, but \`${e}\` is not defined. This may cause issues with navigation in your application.`)}i2.on(i3,()=>{this.#er(this.session),this.#en()}),this.#Q.sdkMetadata&&(n_.sdkMetadata=this.#Q.sdkMetadata),!1!==this.#Q.telemetry&&(this.telemetry=new eB({clerkVersion:n_.version,samplingRate:1,perEventSampling:!this.#Q.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#Q.telemetry}),this.#Q.appearance&&this.telemetry.record({event:"THEME_USAGE",eventSamplingRate:1,payload:function(e){let t;if(!e||"object"!=typeof e)return{};let i=e.theme||e.baseTheme;if(!i)return{};if(Array.isArray(i))for(let e of i){let i=eH(e);if(i){t=i;break}}else t=eH(i);return{themeName:t}}(this.#Q.appearance)}));try{this.#Q.standardBrowser?await this.#es():await this.#ea();let e=this.#Q.telemetry,t=!1!==e&&!e?.disabled,i=!!this.#Q.__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(e0)return;let{enabled:t=!1,...i}=e;t&&(eQ=!0,e0=!0,e2(i))}({enabled:!0,...a?{logLevel:a}:{},...t&&this.telemetry?{telemetryCollector:this.telemetry}:{}}),this.#B?.load(this.environment),e4.info("load() complete",{},"clerk")}catch(e){throw this.#et.emit(f,"error"),e4.error("load() failed",{error:e},"clerk"),e}}};#eo(){let e;return!!(!this.#Q.signUpUrl&&this.#Q.signInUrl&&(e=this.#Q.signInUrl,!ec.test(e)))}signOut=async(e,t)=>{if(!this.client||0===this.client.sessions.length)return;let i="undefined"!=typeof window&&"function"==typeof window.__unstable__onBeforeSetActive?window.__unstable__onBeforeSetActive:eY,r="undefined"!=typeof window&&"function"==typeof window.__unstable__onAfterSetActive?window.__unstable__onAfterSetActive:eY,n=e&&"object"==typeof e?e:t||{},s=n?.redirectUrl||this.buildAfterSignOutUrl();e4.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=tt(this.#Q.standardBrowser);i2.emit(i0,null),this.#el(),await e.track(async()=>{a?await a():await this.navigate(s)}),e.isUnloading()||(this.#er(),this.#en(),await r())};if(await i(),!n.sessionId||1===this.client.signedInSessions.length){this.#Q.experimental?.persistClient??!0?await this.client.removeSessions():await this.client.destroy(),await o(),e4.info("signOut() complete",{redirectUrl:e_(s)},"clerk");return}let l=this.client.signedInSessions.find(e=>e.id===n.sessionId),c=l?.id&&this.session?.id===l.id;await l?.remove(),c&&(await o(),e4.info("signOut() complete",{redirectUrl:e_(s)},"clerk"))};openGoogleOneTap=e=>{this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openModal("googleOneTap",e||{})),this.telemetry?.record(eG("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#V?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(x(this,this.environment)){if("development"===this.#G)throw new U(eR.cannotOpenSignInOrSignUp,{code:nm});return}this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openModal("signIn",e||{}));let t={withSignUp:e?.withSignUp??this.#eo()};this.telemetry?.record(eG("SignIn",e,t))};closeSignIn=()=>{this.#V?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(R(this,this.environment)){if("development"===this.#G)throw new U(eR.cannotRenderAnyBillingComponent("Checkout"),{code:nh});return}if(!this.user){if("development"===this.#G)throw new U(eR.cannotOpenCheckout,{code:nu});return}this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openDrawer("checkout",e||{}))};__internal_closeCheckout=()=>{this.#V?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("checkout"))};__internal_openPlanDetails=e=>{if(R(this,this.environment)){if("development"===this.#G)throw new U(eR.cannotRenderAnyBillingComponent("PlanDetails"),{code:nh});return}this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openDrawer("planDetails",e||{})),this.telemetry?.record(eG("PlanDetails",e))};__internal_closePlanDetails=()=>{this.#V?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("planDetails"))};__internal_openSubscriptionDetails=e=>{this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openDrawer("subscriptionDetails",e||{}))};__internal_closeSubscriptionDetails=()=>{this.#V?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("subscriptionDetails"))};__internal_openReverification=e=>{if(!this.user){if("development"===this.#G)throw new U(eR.cannotOpenUserProfile,{code:nu});return}this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openModal("userVerification",e||{})),this.telemetry?.record(eG("UserVerification",e))};__internal_closeReverification=()=>{this.#V?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userVerification"))};__internal_attemptToEnableEnvironmentSetting=e=>{let{for:t,caller:i}=e;if(this.user||"development"!==this.#G||B(`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.#G&&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.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openModal("enableOrganizationsPrompt",e||{})));__internal_closeEnableOrganizationsPrompt=()=>(this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(e=>e.closeModal("enableOrganizationsPrompt")));__internal_openBlankCaptchaModal=()=>(this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(e=>e.openModal("blankCaptcha",{})));__internal_closeBlankCaptchaModal=()=>(this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(e=>e.closeModal("blankCaptcha")));__internal_loadStripeJs=async()=>{let{loadStripe:e}=await s.e("279").then(s.bind(s,5608));return e};openSignUp=e=>{if(x(this,this.environment)){if("development"===this.#G)throw new U(eR.cannotOpenSignInOrSignUp,{code:nm});return}this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openModal("signUp",e||{})),this.telemetry?.record(eG("SignUp",e))};closeSignUp=()=>{this.#V?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signUp"))};openUserProfile=e=>{if(!this.user){if("development"===this.#G)throw new U(eR.cannotOpenUserProfile,{code:nu});return}this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openModal("userProfile",e||{}));let t=(e?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(eG("UserProfile",e,t))};closeUserProfile=()=>{this.#V?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userProfile"))};openOrganizationProfile=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new U(eR.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:np})}});if(t){if(!this.organization){if("development"===this.#G)throw new U(eR.cannotRenderComponentWhenOrgDoesNotExist,{code:nf});return}this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openModal("organizationProfile",e||{})),this.telemetry?.record(eG("OrganizationProfile",e))}};closeOrganizationProfile=()=>{this.#V?.then(e=>e.ensureMounted()).then(e=>e.closeModal("organizationProfile"))};openCreateOrganization=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new U(eR.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:np})}});t&&(this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openModal("createOrganization",e||{})),this.telemetry?.record(eG("CreateOrganization",e)))};closeCreateOrganization=()=>{this.#V?.then(e=>e.ensureMounted()).then(e=>e.closeModal("createOrganization"))};openWaitlist=e=>{this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(t=>t.openModal("waitlist",e||{})),this.telemetry?.record(eG("Waitlist",e))};closeWaitlist=()=>{this.#V?.then(e=>e.ensureMounted()).then(e=>e.closeModal("waitlist"))};mountSignIn=(e,t)=>{this.assertComponentsReady(this.#V);let i="SignIn";this.#V.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:i,appearanceKey:"signIn",node:e,props:t}));let r={withSignUp:t?.withSignUp??this.#eo()};this.telemetry?.record(eq(i,t,r))};unmountSignIn=e=>{this.#V?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserAvatar=(e,t)=>{this.assertComponentsReady(this.#V);let i="UserAvatar";this.#V.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:i,appearanceKey:"userAvatar",node:e,props:t})),this.telemetry?.record(eq(i,t))};unmountUserAvatar=e=>{this.#V?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountSignUp=(e,t)=>{this.assertComponentsReady(this.#V);let i="SignUp";this.#V.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:i,appearanceKey:"signUp",node:e,props:t})),this.telemetry?.record(eq(i,t))};unmountSignUp=e=>{this.#V?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserProfile=(e,t)=>{if(!this.user){if("development"===this.#G)throw new U(eR.cannotRenderComponentWhenUserDoesNotExist,{code:nu});return}this.assertComponentsReady(this.#V);let i="UserProfile";this.#V.then(e=>e.ensureMounted()).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(eq(i,t,r))};unmountUserProfile=e=>{this.#V?.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 U(eR.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:np})}});if(!i)return;let r=!!this.user;if(!this.organization&&r){if("development"===this.#G)throw new U(eR.cannotRenderComponentWhenOrgDoesNotExist,{code:nf});return}this.assertComponentsReady(this.#V);let n="OrganizationProfile";this.#V.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:n,appearanceKey:"userProfile",node:e,props:t})),this.telemetry?.record(eq(n,t))};unmountOrganizationProfile=e=>{this.#V?.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 U(eR.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:np})}});if(!i)return;this.assertComponentsReady(this.#V);let r="CreateOrganization";this.#V.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:r,appearanceKey:"createOrganization",node:e,props:t})),this.telemetry?.record(eq(r,t))};unmountCreateOrganization=e=>{this.#V?.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 U(eR.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:np})}});if(!i)return;this.assertComponentsReady(this.#V);let r="OrganizationSwitcher";this.#V.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:r,appearanceKey:"organizationSwitcher",node:e,props:t})),this.telemetry?.record(eq(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationSwitcher=e=>{this.#V?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__experimental_prefetchOrganizationSwitcher=()=>{this.assertComponentsReady(this.#V),this.#V.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 U(eR.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:np})}});if(!i)return;this.assertComponentsReady(this.#V);let r="OrganizationList";this.#V.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:r,appearanceKey:"organizationList",node:e,props:t})),this.telemetry?.record(eq(r,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationList=e=>{this.#V?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserButton=(e,t)=>{this.assertComponentsReady(this.#V);let i="UserButton";this.#V.then(e=>e.ensureMounted()).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(eq(i,t,r))};unmountUserButton=e=>{this.#V?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountWaitlist=(e,t)=>{this.assertComponentsReady(this.#V);let i="Waitlist";this.#V.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:i,appearanceKey:"waitlist",node:e,props:t})),this.telemetry?.record(eq(i,t))};unmountWaitlist=e=>{this.#V?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountPricingTable=(e,t)=>{if(R(this,this.environment)){if("development"===this.#G)throw new U(eR.cannotRenderAnyBillingComponent("PricingTable"),{code:nh});return}this.assertComponentsReady(this.#V);let i="PricingTable";this.#V.then(e=>e.ensureMounted()).then(r=>r.mountComponent({name:i,appearanceKey:"pricingTable",node:e,props:t})),this.telemetry?.record(eq(i,t))};unmountPricingTable=e=>{this.#V?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__internal_mountOAuthConsent=(e,t)=>{this.assertComponentsReady(this.#V),this.#V.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:"OAuthConsent",appearanceKey:"__internal_oauthConsent",node:e,props:t}))};__internal_unmountOAuthConsent=e=>{this.#V?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountAPIKeys=(e,t)=>{let i;if(B("Clerk: <APIKeys /> component is in early access and not yet recommended for production use."),z(this,i=this.environment)&&M(this,i)){if("development"===this.#G)throw new U(eR.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&M(this,this.environment)){if("development"===this.#G)throw new U(eR.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if(z(this,this.environment)){if("development"===this.#G)throw new U(eR.cannotRenderAPIKeysComponentForUserWhenDisabled,{code:"cannot_render_api_keys_user_disabled"});return}this.assertComponentsReady(this.#V);let r="APIKeys";this.#V.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:r,appearanceKey:"apiKeys",node:e,props:t})),this.telemetry?.record(eq(r,t))};unmountAPIKeys=e=>{this.#V?.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 U(eR.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:np})}});if(!i)return;this.assertComponentsReady(this.#V);let r="TaskChooseOrganization";this.#V.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:r,appearanceKey:"taskChooseOrganization",node:e,props:t})),this.telemetry?.record(eq(r,t))};unmountTaskChooseOrganization=e=>{this.#V?.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,e4.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 e4.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 e4.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="undefined"!=typeof window&&"function"==typeof window.__unstable__onBeforeSetActive?window.__unstable__onBeforeSetActive:eY,l="undefined"!=typeof window&&"function"==typeof window.__unstable__onAfterSetActive?window.__unstable__onAfterSetActive:eY,d=void 0===n?this.session:n;d?.status==="pending"&&(s={...this.#Q,...e},a=["taskUrls","navigate"],Object.keys(s).some(e=>a.includes(e))||B('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 h=void 0!==t;if(d&&h){let e="string"==typeof t?t:t?.id;if("string"==typeof e&&e.startsWith("org_"))d.lastActiveOrganizationId=e||null;else{let t=d.user.organizationMemberships.find(t=>t.organization.slug===e),i=t?.organization.id||null,r=null===i;if(this.environment?.organizationSettings?.forceOrganizationSelection&&r)return;d.lastActiveOrganizationId=i}}d?.status!=="pending"&&await o(null===d?"sign-out":void 0),(tc()&&globalThis.document.hasFocus()||!this.#Q.standardBrowser)&&(await this.#ec(d),d=this.#ed(d?.id)),await d?.getToken()||(c()||e4.warn("Token is null when setting active session (offline)",{sessionId:d?.id},"clerk"),i2.emit(iZ,{token:null}));let u=tt(this.#Q.standardBrowser),p=d?.status==="pending"&&d?.currentTask&&this.#Q.taskUrls?.[d?.currentTask.key];if((i||p||r)&&await u.track(async()=>{if(this.client){if(d?.status!=="pending"&&this.#el(),p){let e=i?eg({base:p,hashSearchParams:{redirectUrl:i}},{stringify:!0}):p;await this.navigate(e)}else if(r&&d)await r({session:d});else if(i){if(this.client.isEligibleForTouch()){let e=new URL(i,window.location.href),t=this.buildUrlWithAuth(this.client.buildTouchUrl({redirectUrl:e}));await this.navigate(t)}await this.navigate(i)}}}),u.isUnloading())return;this.#er(d),this.#en(),d?.status!=="pending"&&await l()}finally{this.__internal_setActiveInProgress=!1}};addListener=e=>{var t;let i;return t=e,e=e=>{var r;i||={...e},t(i={...{client:rG((r=i).client,e.client),session:rG(r.session,e.session),user:rG(r.user,e.user),organization:rG(r.organization,e.organization)}})},this.#X.push(e),this.client&&e({client:this.client,session:this.session,user:this.user,organization:this.organization}),()=>{this.#X=this.#X.filter(t=>t!==e)}};on=(...e)=>{this.#et.on(...e)};off=(...e)=>{this.#et.off(...e)};__internal_addNavigationListener=e=>(this.#Y.push(e),()=>{this.#Y=this.#Y.filter(t=>t!==e)});navigate=async(e,t)=>{if(!e||!tc())return;setTimeout(()=>{this.#eh()},0);let i=new URL(e,window.location.href);this.#eu.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.#Q.routerReplace?this.#Q.routerReplace:this.#Q.routerPush;if(e4.info(`Clerk is navigating to: ${i}`),this.#Q.routerDebug&&console.log(`Clerk is navigating to: ${i}`),"null"!==i.origin&&i.origin!==window.location.origin||!r)return void eF(i);let n={...t?.metadata?{__internal_metadata:t?.metadata}:{},windowNavigate:eF};return await r(e_(i),n)};buildUrlWithAuth(e){if("production"===this.#G)return e;let t=new URL(e,window.location.origin);return t.origin!==window.location.origin&&this.#j?this.#j.decorateUrlWithDevBrowserToken(t).href:t.href}buildSignInUrl(e){return this.#ep("signInUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildSignUpUrl(e){return this.#ep("signUpUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildUserProfileUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.userProfileUrl):""}buildHomeUrl(){return this.environment&&this.environment.displayConfig?this.buildUrlWithAuth(this.environment.displayConfig.homeUrl):""}buildAfterSignInUrl({params:e}={}){return this.buildUrlWithAuth(new eS(this.#Q,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eS(this.#Q,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#Q.afterSignOutUrl?this.buildUrlWithAuth(this.#Q.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#Q.newSubscriptionRedirectUrl?this.#Q.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?eg({base:this.#Q.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#Q.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#Q.afterMultiSessionSingleSignOutUrl):this.#Q.signInUrl?this.buildUrlWithAuth(eg({base:this.#Q.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.#Q.taskUrls?.[t.key];return i||eg({base:this.buildSignInUrl(e),hashPath:eT(t)},{stringify:!0})}#ef=async()=>{if(!tc())return;let e=new URLSearchParams({[F]:"true"}),t=eI(W);t&&eN(t)||function(){throw Error(`${tg} Invalid redirect_url. A valid http or https url should be used for the redirection.`)}();let i=eg({base:eI(W),searchParams:e},{stringify:!0});return this.navigate(this.buildUrlWithAuth(i))};redirectWithAuth=async e=>{if(tc())return this.navigate(this.buildUrlWithAuth(e))};redirectToSignIn=async e=>{if(tc())return this.navigate(this.buildSignInUrl(e))};redirectToSignUp=async e=>{if(tc())return this.navigate(this.buildSignUpUrl(e))};redirectToUserProfile=async()=>{if(tc())return this.navigate(this.buildUserProfileUrl())};redirectToCreateOrganization=async()=>{if(tc())return this.navigate(this.buildCreateOrganizationUrl())};redirectToOrganizationProfile=async()=>{if(tc())return this.navigate(this.buildOrganizationProfileUrl())};redirectToAfterSignIn=async()=>{if(tc())return this.navigate(this.buildAfterSignInUrl())};redirectToAfterSignUp=async()=>{if(tc())return this.navigate(this.buildAfterSignUpUrl())};redirectToAfterSignOut=async()=>{if(tc())return this.navigate(this.buildAfterSignOutUrl())};redirectToWaitlist=async()=>{if(tc())return this.navigate(this.buildWaitlistUrl())};redirectToTasks=async e=>{if(tc())return this.navigate(this.buildTasksUrl(e))};handleEmailLinkVerification=async(e,t)=>{if(!this.client)return;let i=eI("__clerk_status");if("expired"===i)throw new S("expired");if("client_mismatch"===i)throw new S("client_mismatch");if("verified"!==i)throw new S("failed");let r=eI("__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):eY;return o?this.setActive({session:r,redirectUrl:e.redirectUrlComplete}):l?d():("function"==typeof e.onVerifiedOnOtherDevice&&e.onVerifiedOnOtherDevice(),null)};handleGoogleOneTapCallback=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)):this.navigate(this.buildUrlWithAuth(e));return this._handleRedirectCallback(t,{signUp:a,signIn:s,navigate:o})};_handleRedirectCallback=async(e,{signIn:t,signUp:i,navigate:r})=>{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:n}=this.environment,{firstFactorVerification:s}=t,{externalAccount:a}=i.verifications,o={status:i.status,missingFields:i.missingFields,externalAccountStatus:a.status,externalAccountErrorCode:a.error?.code,externalAccountSessionId:a.error?.meta?.sessionId,sessionId:i.createdSessionId},l={status:t.status,firstFactorVerificationStatus:s.status,firstFactorVerificationErrorCode:s.error?.code,firstFactorVerificationSessionId:s.error?.meta?.sessionId,sessionId:t.createdSessionId},c=e=>()=>r(e),d=c(e.signInUrl||n.signInUrl),h=c(e.signUpUrl||n.signUpUrl),u=c(e.firstFactorUrl||eg({base:n.signInUrl,hashPath:"/factor-one"},{stringify:!0})),p=c(e.secondFactorUrl||eg({base:n.signInUrl,hashPath:"/factor-two"},{stringify:!0})),f=c(e.resetPasswordUrl||eg({base:n.signInUrl,hashPath:"/reset-password"},{stringify:!0})),m=new eS(this.#Q,e),g=c(e.continueSignUpUrl||eg({base:n.signUpUrl,hashPath:"/continue"},{stringify:!0})),_=({missingFields:t})=>t.length?g():(({signUp:e,verifyEmailPath:t,verifyPhonePath:i,continuePath:r,navigate:n,handleComplete:s,redirectUrl:a="",redirectUrlComplete:o="",oidcPrompt:l})=>{if("complete"===e.status)return s&&s();if("missing_requirements"===e.status){if(e.missingFields.some(e=>"enterprise_sso"===e))return e.authenticateWithRedirect({strategy:"enterprise_sso",redirectUrl:a,redirectUrlComplete:o,continueSignUp:!0,oidcPrompt:l});let s=eP();if(e.unverifiedFields?.includes("email_address")&&t)return n(t,{searchParams:s});if(e.unverifiedFields?.includes("phone_number")&&i)return n(i,{searchParams:s});if(r)return n(r,{searchParams:s})}})({signUp:i,verifyEmailPath:e.verifyEmailAddressUrl||eg({base:n.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),verifyPhonePath:e.verifyPhoneNumberUrl||eg({base:n.signUpUrl,hashPath:"/verify-phone-number"},{stringify:!0}),navigate:r}),b=e.signInUrl||n.signInUrl,y=e.signUpUrl||n.signUpUrl,w=async({session:e,baseUrl:t,redirectUrl:i})=>{e.currentTask?await eE(e,{baseUrl:t,navigate:this.navigate}):await this.navigate(i)};if("complete"===l.status)return this.setActive({session:l.sessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:b,redirectUrl:m.getAfterSignInUrl()})}});if("transferable"===o.externalAccountStatus&&"external_account_exists"===o.externalAccountErrorCode){let e=await t.create({transfer:!0});switch(e.status){case"complete":return this.setActive({session:e.createdSessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:y,redirectUrl:m.getAfterSignInUrl()})}});case"needs_first_factor":return u();case"needs_second_factor":return p();case"needs_new_password":return f();default:tb("sign in")}}let v="user_locked"===o.externalAccountErrorCode,k="user_locked"===l.firstFactorVerificationErrorCode;if(v)return h();if(k)return d();if("needs_first_factor"===l.status&&!t.supportedFirstFactors?.every(e=>"enterprise_sso"===e.strategy))return u();if("needs_new_password"===l.status)return f();if("transferable"===l.firstFactorVerificationStatus){if(!1===e.transferable)return d();let t=await i.create({transfer:!0});switch(t.status){case"complete":return this.setActive({session:t.createdSessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:y,redirectUrl:m.getAfterSignUpUrl()})}});case"missing_requirements":return _({missingFields:t.missingFields});default:tb("sign in")}}if("complete"===o.status)return this.setActive({session:o.sessionId,navigate:async({session:e})=>{await w({session:e,baseUrl:y,redirectUrl:m.getAfterSignUpUrl()})}});if("needs_second_factor"===l.status)return p();let S=("failed"===o.externalAccountStatus||"unverified"===o.externalAccountStatus)&&"identifier_already_signed_in"===o.externalAccountErrorCode&&o.externalAccountSessionId,U="failed"===l.firstFactorVerificationStatus&&"identifier_already_signed_in"===l.firstFactorVerificationErrorCode&&l.firstFactorVerificationSessionId;if(S||U){let e=l.firstFactorVerificationSessionId||o.externalAccountSessionId;if(e)return this.setActive({session:e,navigate:async({session:e})=>{await w({session:e,baseUrl:S?y:b,redirectUrl:m.getAfterSignInUrl()})}})}return(e=>{let{externalAccount:t}=e.verifications;return!!t.error})(i)?h():"verified"===o.externalAccountStatus&&"missing_requirements"===o.status?_({missingFields:i.missingFields}):this.session?.currentTask?void await this.redirectToTasks({redirectUrl:this.buildAfterSignInUrl()}):d()};handleRedirectCallback=async(e={},t)=>{if(!this.loaded||!this.environment||!this.client)return;let{signIn:i,signUp:r}=this.client,n=e=>t&&"function"==typeof t?t(e):this.navigate(e);return this._handleRedirectCallback(e,{signUp:r,signIn:i,navigate:n})};handleUnauthenticated=async(e={broadcast:!0})=>{if(this.client&&this.session)try{let t=await iP.getOrCreateInstance().fetch();if(this.updateClient(t),this.session)return;return e.broadcast&&i2.emit(i0,null),this.setActive({session:null})}catch(e){if(O(e)&&[403,500].includes(e.status))return this.setActive({session:null});throw e}};authenticateWithGoogleOneTap=async e=>this.client?.signIn.create({strategy:"google_one_tap",token:e.token}).catch(t=>{if(O(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"})};authenticateWithWeb3=async({redirectUrl:e,signUpContinueUrl:t,customNavigate:i,unsafeMetadata:r,strategy:n,legalAccepted:s,secondFactorUrl:a})=>{let o,l;if(!this.client||!this.environment)return;let{displayConfig:c}=this.environment,d=n.replace("web3_","").replace("_signature",""),h=await th().getWeb3Identifier({provider:d});switch(d){case"metamask":o=th().generateSignatureWithMetamask;break;case"base":o=th().generateSignatureWithBase;break;case"coinbase_wallet":o=th().generateSignatureWithCoinbaseWallet;break;default:o=th().generateSignatureWithOKXWallet}let u=e=>()=>i&&"function"==typeof i?i(e):this.navigate(e),p=u(a||eg({base:c.signInUrl,hashPath:"/factor-two"},{stringify:!0})),f=u(t||eg({base:c.signUpUrl,hashPath:"/continue"},{stringify:!0}));try{l=await this.client.signIn.authenticateWithWeb3({identifier:h,generateSignature:o,strategy:n})}catch(e){if(tn(e,"form_identifier_not_found"))l=await this.client.signUp.authenticateWithWeb3({identifier:h,generateSignature:o,unsafeMetadata:r,strategy:n,legalAccepted:s}),t&&"missing_requirements"===l.status&&"verified"===l.verifications.web3Wallet.status&&await f();else throw e}let m=async({session:e,redirectUrl:t})=>{e.currentTask?await eE(e,{baseUrl:c.signInUrl,navigate:this.navigate}):await this.navigate(t)};switch(l.status){case"needs_second_factor":await p();break;case"complete":l.createdSessionId&&await this.setActive({session:l.createdSessionId,navigate:async({session:t})=>{await m({session:t,redirectUrl:e??this.buildAfterSignInUrl()})}});break;default:return}};createOrganization=async({name:e,slug:t})=>rs.create({name:e,slug:t});getOrganization=async e=>rs.get(e);joinWaitlist=async({emailAddress:e})=>rK.join({emailAddress:e});updateEnvironment(e){this.environment=e}__internal_setCountry=e=>{this.__internal_country||(this.__internal_country=e)};get __internal_last_error(){let e=this.internal_last_error;return this.internal_last_error=null,e}set __internal_last_error(e){this.internal_last_error=e}updateClient=e=>{if(!this.client){let t=this.#Q.selectInitialSession?this.#Q.selectInitialSession(e):this.#em(e);this.#er(t)}if(this.client=e,this.session){let e=this.#ed(this.session.id);"active"===this.session.status&&e?.status==="pending"&&("undefined"!=typeof window&&"function"==typeof window.__unstable__onAfterSetActive?window.__unstable__onAfterSetActive:eY)(),this.#er(e),this.session?.lastActiveToken||c()||e4.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),i2.emit(iZ,{token:this.session?.lastActiveToken})}this.#en()};get __unstable__environment(){return this.environment}__unstable__setEnvironment=async e=>{this.environment=new i6(e)};__unstable__onBeforeRequest=e=>{this.#q.onBeforeRequest(e)};__unstable__onAfterResponse=e=>{this.#q.onAfterResponse(e)};__unstable__updateProps=e=>{let t={...e,options:this.#ei({...this.#Q,...e.options})};return this.#V?.then(e=>e.ensureMounted()).then(e=>e.updateProps(t))};__internal_navigateWithError(e,t){return this.__internal_last_error=t,this.navigate(e)}#eg=()=>{let e=new URLSearchParams({[W]:window.location.href});return eg({base:this.#Q.signInUrl,searchParams:e},{stringify:!0})};#e_=()=>{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()||""};#eb=()=>"true"!==eI(F)&&!!this.isSatellite&&!!this.#j?.isSignedOut();#ey=()=>"production"!==this.#G&&!this.isSatellite&&!!eI(W);#ew=async()=>{"development"===this.instanceType?await this.navigate(this.#eg()):"production"===this.instanceType&&await this.navigate(this.#e_())};#ev=(e,t)=>{let i;try{i=new URL(e)}catch{throw Error(`${tg} The signInUrl needs to have a absolute url format.`)}i.origin===t&&function(){throw Error(`${tg} The signInUrl needs to be on a different origin than your satellite application.`)}()};#ek=()=>{this.isSatellite&&("development"!==this.#G||this.#Q.signInUrl||function(){throw Error(`${tg} Missing signInUrl. A satellite application needs to specify the signInUrl for development instances.`)}(),this.proxyUrl||this.domain||function(){throw Error(`${tg} Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl.`)}(),this.#Q.signInUrl&&this.#ev(this.#Q.signInUrl,window.location.origin))};#es=async()=>{if(this.#j=await nr.create(this,this.#q,this.#G,this.#et),this.#ek(),this.#eb())return void await this.#ew();if(this.#ey())return void await this.#ef();this.#Z=(()=>{if(!n())return{onPageFocus:eY};let e=[];return window.addEventListener("focus",()=>{"visible"===document.visibilityState&&e.forEach(e=>e())}),{onPageFocus:t=>{e.push(t)}}})(),"undefined"!=typeof BroadcastChannel&&(this.#K=new BroadcastChannel("clerk")),this.#eS();let e=function(e=window.location.hostname){if(!e)return!1;let t=ef.get(e);void 0===t&&(t=Z.some(t=>e.startsWith("accounts.")&&e.endsWith(t))||ee.some(t=>e.endsWith(t)&&!e.endsWith(".clerk"+t)),ef.set(e,t));return t}(window?.location.hostname),t="development"===this.#G&&!e,i=0,r=0;for(;r<2;){r++;try{var s;let e=i6.getInstance().fetch({touch:t}).then(e=>this.updateEnvironment(e)).catch(()=>{++i;let e=tm.getItem(tu,null);e&&this.updateEnvironment(new i6(e))}),r=async()=>iP.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(async e=>{if(P(e))throw e;++i;let t=this.#j?.getSessionCookie(),r=function(e){let t;try{t=new rN({jwt:e||"",object:"token",id:void 0})}catch{t=null}if(iP.clearInstance(),!t?.jwt)return iP.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}=rw(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=>Number.parseInt(e.trim(),10)).map(e=>e.toString(2).padStart(i.length,"0").split("").map(e=>Number.parseInt(e,10)).reverse()).filter(Boolean)}})({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++)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,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 iP.getOrCreateInstance(c)}(t);return this.updateClient(r),this.#j?.stopPollingForToken(),await this.session?.getToken({skipCache:!0}).catch(()=>null).finally(()=>{this.#j?.startPollingForToken()}),null}),[,n]=await (s=[e,r()],Promise.all(Array.from(s).map(e=>e.then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e})))));if("rejected"===n.status){let e=n.reason;if(tn(e,"requires_captcha"))await r();else throw e}if(this.#j?.setClientUatCookieForDevelopmentInstances(),await this.#eU())return;break}catch(e){if(tn(e,"dev_browser_unauthenticated"))await this.#j.handleUnauthenticatedDevBrowser();else if(!c())return void console.warn(e);else throw e}r>=2&&function(){throw Error(`${tg} Something went wrong initializing Clerk.`)}()}this.#J=new nn(this),this.#J.start(),this.#eA(),this.#eI(),this.#eC(),this.#et.emit(f,i>0?"degraded":"ready")};shouldFallbackToCachedResources=()=>!!this.__internal_getCachedResources;#ea=async()=>{let e,t,i=this.shouldFallbackToCachedResources()?1:void 0,r=0;try{[e,t]=await Promise.all([i6.getInstance().fetch({touch:!1,fetchMaxTries:i}),iP.getOrCreateInstance().fetch({fetchMaxTries:i})])}catch(i){if(T(i)&&"network_error"===i.code&&this.shouldFallbackToCachedResources()){let i=await this.__internal_getCachedResources?.();e=new i6(i?.environment),iP.clearInstance(),t=iP.getOrCreateInstance(i?.client),++r}else throw i}this.updateClient(t),this.updateEnvironment(e),this.#et.emit(f,r>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,t]=await Promise.all([i6.getInstance().fetch({touch:!1,fetchMaxTries:1}),iP.getOrCreateInstance().fetch({fetchMaxTries:1})]);this.updateClient(t),this.updateEnvironment(e),this.#en()};#em=e=>{if(e.lastActiveSessionId){let t=e.signedInSessions.find(t=>t.id===e.lastActiveSessionId);if(t)return t}return e.signedInSessions[0]||null};#eS=()=>{n()&&(this.#Z?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#ee>Date.now())&&(this.#ee=Date.now()+5e3,this.#Q.touchSession&&this.#ec(this.session))}),this.#K?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),i2.on(i0,()=>{this.#K?.postMessage({type:"signout"})}),i2.on(i1,()=>{tm.setItem(tu,this.environment?.__internal_toSnapshot(),864e5)}))};#ec=async e=>{if(!e)return Promise.resolve();await e.touch().catch(e=>{P(e)&&this.handleUnauthenticated()})};#en=()=>{if(this.client)for(let e of this.#X)e({client:this.client,session:this.session,user:this.user,organization:this.organization})};#eh=()=>{for(let e of this.#Y)e()};#el=()=>{this.session=void 0,this.organization=void 0,this.user=void 0,this.#en()};#eP=()=>(this.session?.user.organizationMemberships||[]).map(e=>e.organization).find(e=>e.id===this.session?.lastActiveOrganizationId)||null;#er=e=>{this.session=e||null,this.organization=this.#eP(),this.user=this.session?this.session.user:null};#ed=e=>this.client?.signedInSessions.find(t=>t.id===e)||null;#eI=()=>{this.addListener(({session:e})=>{e?.actor&&this.#V?.then(e=>e.ensureMounted()).then(e=>e.mountImpersonationFab())})};#eC=()=>{this.#Q.__internal_keyless_claimKeylessApplicationUrl&&this.#V?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#Q.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#Q.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#Q.__internal_keyless_dismissPrompt}})})};#ep=(e,t,i)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let r=this.#Q[e]||this.environment.displayConfig[e];this.#eo()&&(r=this.#Q.signInUrl);let n=new eS(this.#Q,t).toSearchParams(),s=new URLSearchParams(i||{}),a=eg({base:r,hashPath:this.#eo()&&"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")}#eU=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,eh)).pathname,r=ev.includes(i)||ek.includes(i),e===t.host&&r);if(a||!o)return!1;let l=this.session,c=this.#Q.signInUrl||this.environment?.displayConfig.signInUrl,d=c&&window.location.href.startsWith(c),h=this.#Q.signUpUrl||this.environment?.displayConfig.signUpUrl,u=h&&window.location.href.startsWith(h);return n=new URL(s,eh),(!ev.includes(n.pathname)||!!l||!d&&!u)&&(await this.navigate(this.buildUrlWithAuth(s)),!0)};#ei=e=>({...ng,...e,allowedRedirectOrigins:function(e,t,i){if(Array.isArray(e)&&e.length)return e;let r=[];return"undefined"!=typeof window&&window.location&&r.push(window.location.origin),r.push(`https://${em(t)}`),r.push(`https://*.${em(t)}`),"development"===i&&r.push(`https://${t}`),r}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)});#eA=()=>{try{eC(F),eC(eU),eC(N),eC("__clerk_handshake"),eC("__clerk_handshake_nonce"),eC("__clerk_help")}catch{}};get #eu(){let e=eM;return this.#Q.allowedRedirectProtocols&&(e=e.concat(this.#Q.allowedRedirectProtocols)),e}}let nb=document.querySelector("script[data-clerk-publishable-key]")?.getAttribute("data-clerk-publishable-key")||window.__clerk_publishable_key||"",ny=document.querySelector("script[data-clerk-proxy-url]")?.getAttribute("data-clerk-proxy-url")||window.__clerk_proxy_url||"",nw=document.querySelector("script[data-clerk-domain]")?.getAttribute("data-clerk-domain")||window.__clerk_domain||"";window.Clerk||(window.Clerk=new n_(nb,{proxyUrl:ny,domain:nw}))})(),{}})());
|