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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/dist/197_clerk.legacy.browser_bb01de_6.0.0-snapshot.v20251224145055.js +1 -0
  2. package/dist/507_clerk.legacy.browser_bb01de_6.0.0-snapshot.v20251224145055.js +1 -0
  3. package/dist/base-account-sdk_clerk.legacy.browser_bb01de_6.0.0-snapshot.v20251224145055.js +1 -0
  4. package/dist/clerk.browser.js +6 -6
  5. package/dist/clerk.chips.browser.js +6 -6
  6. package/dist/clerk.headless.browser.js +6 -6
  7. package/dist/clerk.headless.js +6 -6
  8. package/dist/clerk.js +6 -6
  9. package/dist/clerk.legacy.browser.js +1 -1
  10. package/dist/clerk.mjs +6 -6
  11. package/dist/clerk.no-rhc.js +6 -6
  12. package/dist/clerk.no-rhc.mjs +6 -6
  13. package/dist/coinbase-wallet-sdk_clerk.legacy.browser_bb01de_6.0.0-snapshot.v20251224145055.js +1 -0
  14. package/dist/query-core-vendors_clerk.legacy.browser_bb01de_6.0.0-snapshot.v20251224145055.js +1 -0
  15. package/dist/stripe-vendors_clerk.legacy.browser_bb01de_6.0.0-snapshot.v20251224145055.js +1 -0
  16. package/dist/types/core/resources/Token.d.ts +1 -1
  17. package/dist/types/utils/errorThrower.d.ts +1 -1
  18. package/dist/types/utils/web3.d.ts +2 -2
  19. package/dist/vendors_clerk.legacy.browser_bb01de_6.0.0-snapshot.v20251224145055.js +1 -0
  20. package/dist/{zxcvbn-common_clerk.legacy.browser_6e74bb_6.0.0-snapshot.v20251218183643.js → zxcvbn-common_clerk.legacy.browser_bb01de_6.0.0-snapshot.v20251224145055.js} +1 -1
  21. package/dist/zxcvbn-ts-core_clerk.legacy.browser_bb01de_6.0.0-snapshot.v20251224145055.js +1 -0
  22. package/package.json +5 -5
  23. package/dist/197_clerk.legacy.browser_6e74bb_6.0.0-snapshot.v20251218183643.js +0 -1
  24. package/dist/507_clerk.legacy.browser_6e74bb_6.0.0-snapshot.v20251218183643.js +0 -1
  25. package/dist/base-account-sdk_clerk.legacy.browser_6e74bb_6.0.0-snapshot.v20251218183643.js +0 -1
  26. package/dist/coinbase-wallet-sdk_clerk.legacy.browser_6e74bb_6.0.0-snapshot.v20251218183643.js +0 -1
  27. package/dist/query-core-vendors_clerk.legacy.browser_6e74bb_6.0.0-snapshot.v20251218183643.js +0 -1
  28. package/dist/stripe-vendors_clerk.legacy.browser_6e74bb_6.0.0-snapshot.v20251218183643.js +0 -1
  29. package/dist/vendors_clerk.legacy.browser_6e74bb_6.0.0-snapshot.v20251218183643.js +0 -1
  30. package/dist/zxcvbn-ts-core_clerk.legacy.browser_6e74bb_6.0.0-snapshot.v20251218183643.js +0 -1
  31. /package/dist/{197_clerk.browser_834334_6.0.0-snapshot.v20251218183643.js → 197_clerk.browser_d21971_6.0.0-snapshot.v20251224145055.js} +0 -0
  32. /package/dist/{197_clerk.chips.browser_5e7a74_6.0.0-snapshot.v20251218183643.js → 197_clerk.chips.browser_fe6fe8_6.0.0-snapshot.v20251224145055.js} +0 -0
  33. /package/dist/{197_clerk.headless.browser_45a74c_6.0.0-snapshot.v20251218183643.js → 197_clerk.headless.browser_a98629_6.0.0-snapshot.v20251224145055.js} +0 -0
  34. /package/dist/{197_clerk.headless_38bd55_6.0.0-snapshot.v20251218183643.js → 197_clerk.headless_ac5c19_6.0.0-snapshot.v20251224145055.js} +0 -0
  35. /package/dist/{308_clerk.headless_38bd55_6.0.0-snapshot.v20251218183643.js → 308_clerk.headless_ac5c19_6.0.0-snapshot.v20251224145055.js} +0 -0
  36. /package/dist/{507_clerk.browser_834334_6.0.0-snapshot.v20251218183643.js → 507_clerk.browser_d21971_6.0.0-snapshot.v20251224145055.js} +0 -0
  37. /package/dist/{507_clerk.chips.browser_5e7a74_6.0.0-snapshot.v20251218183643.js → 507_clerk.chips.browser_fe6fe8_6.0.0-snapshot.v20251224145055.js} +0 -0
  38. /package/dist/{507_clerk.headless.browser_45a74c_6.0.0-snapshot.v20251218183643.js → 507_clerk.headless.browser_a98629_6.0.0-snapshot.v20251224145055.js} +0 -0
  39. /package/dist/{507_clerk.headless_38bd55_6.0.0-snapshot.v20251218183643.js → 507_clerk.headless_ac5c19_6.0.0-snapshot.v20251224145055.js} +0 -0
  40. /package/dist/{521_clerk.headless_38bd55_6.0.0-snapshot.v20251218183643.js → 521_clerk.headless_ac5c19_6.0.0-snapshot.v20251224145055.js} +0 -0
  41. /package/dist/{527_clerk.browser_834334_6.0.0-snapshot.v20251218183643.js → 527_clerk.browser_d21971_6.0.0-snapshot.v20251224145055.js} +0 -0
  42. /package/dist/{527_clerk.chips.browser_5e7a74_6.0.0-snapshot.v20251218183643.js → 527_clerk.chips.browser_fe6fe8_6.0.0-snapshot.v20251224145055.js} +0 -0
  43. /package/dist/{527_clerk.headless.browser_45a74c_6.0.0-snapshot.v20251218183643.js → 527_clerk.headless.browser_a98629_6.0.0-snapshot.v20251224145055.js} +0 -0
  44. /package/dist/{527_clerk.legacy.browser_6e74bb_6.0.0-snapshot.v20251218183643.js → 527_clerk.legacy.browser_bb01de_6.0.0-snapshot.v20251224145055.js} +0 -0
  45. /package/dist/{537_clerk.headless_38bd55_6.0.0-snapshot.v20251218183643.js → 537_clerk.headless_ac5c19_6.0.0-snapshot.v20251224145055.js} +0 -0
  46. /package/dist/{604_clerk.headless_38bd55_6.0.0-snapshot.v20251218183643.js → 604_clerk.headless_ac5c19_6.0.0-snapshot.v20251224145055.js} +0 -0
  47. /package/dist/{783_clerk.headless_38bd55_6.0.0-snapshot.v20251218183643.js → 783_clerk.headless_ac5c19_6.0.0-snapshot.v20251224145055.js} +0 -0
  48. /package/dist/{896_clerk.headless_38bd55_6.0.0-snapshot.v20251218183643.js → 896_clerk.headless_ac5c19_6.0.0-snapshot.v20251224145055.js} +0 -0
  49. /package/dist/{973_clerk.headless_38bd55_6.0.0-snapshot.v20251218183643.js → 973_clerk.headless_ac5c19_6.0.0-snapshot.v20251224145055.js} +0 -0
  50. /package/dist/{base-account-sdk_clerk.browser_834334_6.0.0-snapshot.v20251218183643.js → base-account-sdk_clerk.browser_d21971_6.0.0-snapshot.v20251224145055.js} +0 -0
  51. /package/dist/{base-account-sdk_clerk.chips.browser_5e7a74_6.0.0-snapshot.v20251218183643.js → base-account-sdk_clerk.chips.browser_fe6fe8_6.0.0-snapshot.v20251224145055.js} +0 -0
  52. /package/dist/{base-account-sdk_clerk.headless.browser_45a74c_6.0.0-snapshot.v20251218183643.js → base-account-sdk_clerk.headless.browser_a98629_6.0.0-snapshot.v20251224145055.js} +0 -0
  53. /package/dist/{coinbase-wallet-sdk_clerk.browser_834334_6.0.0-snapshot.v20251218183643.js → coinbase-wallet-sdk_clerk.browser_d21971_6.0.0-snapshot.v20251224145055.js} +0 -0
  54. /package/dist/{coinbase-wallet-sdk_clerk.chips.browser_5e7a74_6.0.0-snapshot.v20251218183643.js → coinbase-wallet-sdk_clerk.chips.browser_fe6fe8_6.0.0-snapshot.v20251224145055.js} +0 -0
  55. /package/dist/{coinbase-wallet-sdk_clerk.headless.browser_45a74c_6.0.0-snapshot.v20251218183643.js → coinbase-wallet-sdk_clerk.headless.browser_a98629_6.0.0-snapshot.v20251224145055.js} +0 -0
  56. /package/dist/{cookieSuffix_clerk.browser_834334_6.0.0-snapshot.v20251218183643.js → cookieSuffix_clerk.browser_d21971_6.0.0-snapshot.v20251224145055.js} +0 -0
  57. /package/dist/{cookieSuffix_clerk.chips.browser_5e7a74_6.0.0-snapshot.v20251218183643.js → cookieSuffix_clerk.chips.browser_fe6fe8_6.0.0-snapshot.v20251224145055.js} +0 -0
  58. /package/dist/{cookieSuffix_clerk.headless.browser_45a74c_6.0.0-snapshot.v20251218183643.js → cookieSuffix_clerk.headless.browser_a98629_6.0.0-snapshot.v20251224145055.js} +0 -0
  59. /package/dist/{cookieSuffix_clerk.headless_38bd55_6.0.0-snapshot.v20251218183643.js → cookieSuffix_clerk.headless_ac5c19_6.0.0-snapshot.v20251224145055.js} +0 -0
  60. /package/dist/{cookieSuffix_clerk.legacy.browser_6e74bb_6.0.0-snapshot.v20251218183643.js → cookieSuffix_clerk.legacy.browser_bb01de_6.0.0-snapshot.v20251224145055.js} +0 -0
  61. /package/dist/{query-core-vendors_clerk.browser_834334_6.0.0-snapshot.v20251218183643.js → query-core-vendors_clerk.browser_d21971_6.0.0-snapshot.v20251224145055.js} +0 -0
  62. /package/dist/{query-core-vendors_clerk.chips.browser_5e7a74_6.0.0-snapshot.v20251218183643.js → query-core-vendors_clerk.chips.browser_fe6fe8_6.0.0-snapshot.v20251224145055.js} +0 -0
  63. /package/dist/{query-core-vendors_clerk.headless.browser_45a74c_6.0.0-snapshot.v20251218183643.js → query-core-vendors_clerk.headless.browser_a98629_6.0.0-snapshot.v20251224145055.js} +0 -0
  64. /package/dist/{stripe-vendors_clerk.browser_834334_6.0.0-snapshot.v20251218183643.js → stripe-vendors_clerk.browser_d21971_6.0.0-snapshot.v20251224145055.js} +0 -0
  65. /package/dist/{stripe-vendors_clerk.chips.browser_5e7a74_6.0.0-snapshot.v20251218183643.js → stripe-vendors_clerk.chips.browser_fe6fe8_6.0.0-snapshot.v20251224145055.js} +0 -0
  66. /package/dist/{stripe-vendors_clerk.headless.browser_45a74c_6.0.0-snapshot.v20251218183643.js → stripe-vendors_clerk.headless.browser_a98629_6.0.0-snapshot.v20251224145055.js} +0 -0
  67. /package/dist/{vendors_clerk.browser_834334_6.0.0-snapshot.v20251218183643.js → vendors_clerk.browser_d21971_6.0.0-snapshot.v20251224145055.js} +0 -0
  68. /package/dist/{vendors_clerk.chips.browser_5e7a74_6.0.0-snapshot.v20251218183643.js → vendors_clerk.chips.browser_fe6fe8_6.0.0-snapshot.v20251224145055.js} +0 -0
  69. /package/dist/{vendors_clerk.headless.browser_45a74c_6.0.0-snapshot.v20251218183643.js → vendors_clerk.headless.browser_a98629_6.0.0-snapshot.v20251224145055.js} +0 -0
  70. /package/dist/{zxcvbn-common_clerk.browser_834334_6.0.0-snapshot.v20251218183643.js → zxcvbn-common_clerk.browser_d21971_6.0.0-snapshot.v20251224145055.js} +0 -0
  71. /package/dist/{zxcvbn-common_clerk.chips.browser_5e7a74_6.0.0-snapshot.v20251218183643.js → zxcvbn-common_clerk.chips.browser_fe6fe8_6.0.0-snapshot.v20251224145055.js} +0 -0
  72. /package/dist/{zxcvbn-common_clerk.headless.browser_45a74c_6.0.0-snapshot.v20251218183643.js → zxcvbn-common_clerk.headless.browser_a98629_6.0.0-snapshot.v20251224145055.js} +0 -0
  73. /package/dist/{zxcvbn-ts-core_clerk.browser_834334_6.0.0-snapshot.v20251218183643.js → zxcvbn-ts-core_clerk.browser_d21971_6.0.0-snapshot.v20251224145055.js} +0 -0
  74. /package/dist/{zxcvbn-ts-core_clerk.chips.browser_5e7a74_6.0.0-snapshot.v20251218183643.js → zxcvbn-ts-core_clerk.chips.browser_fe6fe8_6.0.0-snapshot.v20251224145055.js} +0 -0
  75. /package/dist/{zxcvbn-ts-core_clerk.headless.browser_45a74c_6.0.0-snapshot.v20251218183643.js → zxcvbn-ts-core_clerk.headless.browser_a98629_6.0.0-snapshot.v20251224145055.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 n in i)("object"==typeof exports?exports:e)[n]=i[n]}}(globalThis,()=>(()=>{var e,t,i,n={5945:function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))(function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){e.done?r(e.value):new i(function(t){t(e.value)}).then(a,o)}l((n=n.apply(e,t||[])).next())})},r=this&&this.__generator||function(e,t){var i,n,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[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,n&&(r=2&l[0]?n.return:l[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,l[1])).done)return r;switch(n=0,r&&(l=[2&l[0],r.value]),l[0]){case 0:case 1:r=l;break;case 4:return a.label++,{value:l[1],done:!1};case 5:a.label++,n=l[1],l=[0];continue;case 7:l=a.ops.pop(),a.trys.pop();continue;default:if(!(r=(r=a.trys).length>0&&r[r.length-1])&&(6===l[0]||2===l[0])){a=0;continue}if(3===l[0]&&(!r||l[1]>r[0]&&l[1]<r[3])){a.label=l[1];break}if(6===l[0]&&a.label<r[1]){a.label=r[1],r=l;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(l);break}r[2]&&a.ops.pop(),a.trys.pop();continue}l=t.call(e,a)}catch(e){l=[6,e],n=0}finally{i=r=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 n(s,void 0,void 0,function(){return r(this,function(e){throw Error("Unsupported")})})},getItem:function(e){return n(s,void 0,void 0,function(){return r(this,function(e){throw Error("Unsupported")})})},clear:function(){return n(s,void 0,void 0,function(){return r(this,function(e){return[2,window.localStorage.clear()]})})},removeItem:function(e){return n(s,void 0,void 0,function(){return r(this,function(e){throw Error("Unsupported")})})},setItem:function(e,t){return n(s,void 0,void 0,function(){return r(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="",n=0;n<e;n++){var r=Math.floor(Math.random()*t.length);i+=t[r]}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),n(this,void 0,void 0,function(){var n,s,a,h,u,p,f;return r(this,function(r){switch(r.label){case 0:n=Date.now()+d(4),s=Date.now()+i,a=o+"-"+t,h=void 0===this.storageHandler?l:this.storageHandler,r.label=1;case 1:if(!(Date.now()<s))return[3,8];return[4,c(30)];case 2:if(r.sent(),null!==h.getItemSync(a))return[3,5];return u=this.id+"-"+t+"-"+n,[4,c(Math.floor(25*Math.random()))];case 3:return r.sent(),h.setItemSync(a,JSON.stringify({id:this.id,iat:n,timeoutKey:u,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,c(30)];case 4:if(r.sent(),null!==(p=h.getItemSync(a))&&(f=JSON.parse(p)).id===this.id&&f.iat===n)return this.acquiredIatSet.add(n),this.refreshLockWhileAcquired(a,n),[2,!0];return[3,7];case 5:return e.lockCorrector(void 0===this.storageHandler?l:this.storageHandler),[4,this.waitForSomethingToChange(s)];case 6:r.sent(),r.label=7;case 7:return n=Date.now()+d(4),[3,1];case 8:return[2,!1]}})})},e.prototype.refreshLockWhileAcquired=function(e,t){return n(this,void 0,void 0,function(){var i=this;return r(this,function(s){return setTimeout(function(){return n(i,void 0,void 0,function(){var i,n,s;return r(this,function(r){switch(r.label){case 0:return[4,a.default().lock(t)];case 1:if(r.sent(),!this.acquiredIatSet.has(t)||null===(n=(i=void 0===this.storageHandler?l:this.storageHandler).getItemSync(e)))return a.default().unlock(t),[2];return(s=JSON.parse(n)).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 n(this,void 0,void 0,function(){return r(this,function(i){switch(i.label){case 0:return[4,new Promise(function(i){var n=!1,r=Date.now(),s=!1;function a(){if(s||(window.removeEventListener("storage",a),e.removeFromWaiting(a),clearTimeout(o),s=!0),!n){n=!0;var t=50-(Date.now()-r);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 n(this,void 0,void 0,function(){return r(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 n(this,void 0,void 0,function(){var i,n,s,c;return r(this,function(r){switch(r.label){case 0:if(i=void 0===this.storageHandler?l:this.storageHandler,n=o+"-"+t,null===(s=i.getItemSync(n)))return[2];if((c=JSON.parse(s)).id!==this.id)return[3,2];return[4,a.default().lock(c.iat)];case 1:r.sent(),this.acquiredIatSet.delete(c.iat),i.removeItemSync(n),a.default().unlock(c.iat),e.notifyWaiters(),r.label=2;case 2:return[2]}})})},e.lockCorrector=function(t){for(var i=Date.now()-5e3,n=[],r=0;;){var s=t.keySync(r);if(null===s)break;n.push(s),r++}for(var a=!1,l=0;l<n.length;l++){var c=n[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 n=e.locked.get(t);void 0===n?void 0===i?e.locked.set(t,[]):e.locked.set(t,[i]):void 0!==i&&(n.unshift(i),e.locked.set(t,n))},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise(function(i,n){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 n=i.pop();e.locked.set(t,i),void 0!==n&&setTimeout(n,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,n=String(e),r="",s=!!t&&!!t.extended,a=!!t&&!!t.globstar,o=!1,l=t&&"string"==typeof t.flags?t.flags:"",c=0,d=n.length;c<d;c++)switch(i=n[c]){case"/":case"$":case"^":case"+":case".":case"(":case")":case"=":case"!":case"|":r+="\\"+i;break;case"?":if(s){r+=".";break}case"[":case"]":if(s){r+=i;break}case"{":if(s){o=!0,r+="(";break}case"}":if(s){o=!1,r+=")";break}case",":if(o){r+="|";break}r+="\\"+i;break;case"*":for(var h=n[c-1],u=1;"*"===n[c+1];)u++,c++;var p=n[c+1];a?u>1&&("/"===h||void 0===h)&&("/"===p||void 0===p)?(r+="((?:[^/]*(?:/|$))*)",c++):r+="([^/]*)":r+=".*";break;default:r+=i}return l&&~l.indexOf("g")||(r="^"+r+"$"),new RegExp(r,l)}}},r={};function s(e){var t=r[e];if(void 0!==t)return t.exports;var i=r[e]={exports:{}};return n[e].call(i.exports,i,i.exports,s),i.exports}s.m=n,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 n={};a=a||[null,o({}),o([]),o(o)];for(var r=2&t&&e;("object"==typeof r||"function"==typeof r)&&!~a.indexOf(r);r=o(r))Object.getOwnPropertyNames(r).forEach(t=>{n[t]=()=>e[t]});return n.default=()=>e,s.d(i,n),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.v20251218183643.js",s.h=()=>"5e7a743b3c7989db",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,n){if(l[e])return void l[e].push(t);if(void 0!==i)for(var r,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){r=d;break}}r||(a=!0,(r=document.createElement("script")).timeout=120,s.nc&&r.setAttribute("nonce",s.nc),r.setAttribute("data-webpack","@clerk/clerk-js:"+i),r.src=e),l[e]=[t];var h=function(t,i){r.onerror=r.onload=null,clearTimeout(u);var n=l[e];if(delete l[e],r.parentNode&&r.parentNode.removeChild(r),n&&n.forEach(function(e){return e(i)}),t)return t(i)},u=setTimeout(h.bind(null,void 0,{type:"timeout",target:r}),12e4);r.onerror=h.bind(null,r.onerror),r.onload=h.bind(null,r.onload),a&&document.head.appendChild(r)},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 n=s.o(e,t)?e[t]:void 0;if(0!==n)if(n)i.push(n[2]);else{var r=new Promise((i,r)=>n=e[t]=[i,r]);i.push(n[2]=r);var a=s.p+s.u(t),o=Error();s.l(a,function(i){if(s.o(e,t)&&(0!==(n=e[t])&&(e[t]=void 0),n)){var r=i&&("load"===i.type?"missing":i.type),a=i&&i.target&&i.target.src;o.message="Loading chunk "+t+" failed.\n("+r+": "+a+")",o.name="ChunkLoadError",o.type=r,o.request=a,n[1](o)}},"chunk-"+t,t)}},t=(t,i)=>{var n,r,a=i[0],o=i[1],l=i[2],c=0;if(a.some(t=>0!==e[t])){for(n in o)s.o(o,n)&&(s.m[n]=o[n]);l&&l(s)}for(t&&t(i);c<a.length;c++)r=a[c],s.o(e,r)&&e[r]&&e[r][0](),e[r]=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,n;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.v20251218183643$3")}catch{}function r(){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=r()?window?.navigator:null;return!!t&&!((e=t?.userAgent)&&a.test(e))&&!t?.webdriver}function l(){let e=r()?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,n,r)=>{let{notify:s}=r||{},a=e.get(i);a||(a=[],e.set(i,a)),a.push(n),s&&t.has(i)&&n(t.get(i))},h=(e,t,i)=>(e.get(t)||[]).map(e=>e(i)),u=(e,t,i)=>{let n=e.get(t);n&&(i?n.splice(n.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:(n,r)=>{t.set(n,r),h(i,n,r),h(e,n,r)},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,_,w=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(w);var b=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 n in i)("object"==typeof exports?exports:e)[n]=i[n]}}(globalThis,()=>(()=>{var e,t,i,n={5945:function(e,t,i){"use strict";var n=this&&this.__awaiter||function(e,t,i,n){return new(i||(i=Promise))(function(r,s){function a(e){try{l(n.next(e))}catch(e){s(e)}}function o(e){try{l(n.throw(e))}catch(e){s(e)}}function l(e){e.done?r(e.value):new i(function(t){t(e.value)}).then(a,o)}l((n=n.apply(e,t||[])).next())})},r=this&&this.__generator||function(e,t){var i,n,r,s,a={label:0,sent:function(){if(1&r[0])throw r[1];return r[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,n&&(r=2&l[0]?n.return:l[0]?n.throw||((r=n.return)&&r.call(n),0):n.next)&&!(r=r.call(n,l[1])).done)return r;switch(n=0,r&&(l=[2&l[0],r.value]),l[0]){case 0:case 1:r=l;break;case 4:return a.label++,{value:l[1],done:!1};case 5:a.label++,n=l[1],l=[0];continue;case 7:l=a.ops.pop(),a.trys.pop();continue;default:if(!(r=(r=a.trys).length>0&&r[r.length-1])&&(6===l[0]||2===l[0])){a=0;continue}if(3===l[0]&&(!r||l[1]>r[0]&&l[1]<r[3])){a.label=l[1];break}if(6===l[0]&&a.label<r[1]){a.label=r[1],r=l;break}if(r&&a.label<r[2]){a.label=r[2],a.ops.push(l);break}r[2]&&a.ops.pop(),a.trys.pop();continue}l=t.call(e,a)}catch(e){l=[6,e],n=0}finally{i=r=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 n(s,void 0,void 0,function(){return r(this,function(e){throw Error("Unsupported")})})},getItem:function(e){return n(s,void 0,void 0,function(){return r(this,function(e){throw Error("Unsupported")})})},clear:function(){return n(s,void 0,void 0,function(){return r(this,function(e){return[2,window.localStorage.clear()]})})},removeItem:function(e){return n(s,void 0,void 0,function(){return r(this,function(e){throw Error("Unsupported")})})},setItem:function(e,t){return n(s,void 0,void 0,function(){return r(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="",n=0;n<e;n++){var r=Math.floor(Math.random()*t.length);i+=t[r]}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),n(this,void 0,void 0,function(){var n,s,a,h,u,p,f;return r(this,function(r){switch(r.label){case 0:n=Date.now()+d(4),s=Date.now()+i,a=o+"-"+t,h=void 0===this.storageHandler?l:this.storageHandler,r.label=1;case 1:if(!(Date.now()<s))return[3,8];return[4,c(30)];case 2:if(r.sent(),null!==h.getItemSync(a))return[3,5];return u=this.id+"-"+t+"-"+n,[4,c(Math.floor(25*Math.random()))];case 3:return r.sent(),h.setItemSync(a,JSON.stringify({id:this.id,iat:n,timeoutKey:u,timeAcquired:Date.now(),timeRefreshed:Date.now()})),[4,c(30)];case 4:if(r.sent(),null!==(p=h.getItemSync(a))&&(f=JSON.parse(p)).id===this.id&&f.iat===n)return this.acquiredIatSet.add(n),this.refreshLockWhileAcquired(a,n),[2,!0];return[3,7];case 5:return e.lockCorrector(void 0===this.storageHandler?l:this.storageHandler),[4,this.waitForSomethingToChange(s)];case 6:r.sent(),r.label=7;case 7:return n=Date.now()+d(4),[3,1];case 8:return[2,!1]}})})},e.prototype.refreshLockWhileAcquired=function(e,t){return n(this,void 0,void 0,function(){var i=this;return r(this,function(s){return setTimeout(function(){return n(i,void 0,void 0,function(){var i,n,s;return r(this,function(r){switch(r.label){case 0:return[4,a.default().lock(t)];case 1:if(r.sent(),!this.acquiredIatSet.has(t)||null===(n=(i=void 0===this.storageHandler?l:this.storageHandler).getItemSync(e)))return a.default().unlock(t),[2];return(s=JSON.parse(n)).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 n(this,void 0,void 0,function(){return r(this,function(i){switch(i.label){case 0:return[4,new Promise(function(i){var n=!1,r=Date.now(),s=!1;function a(){if(s||(window.removeEventListener("storage",a),e.removeFromWaiting(a),clearTimeout(o),s=!0),!n){n=!0;var t=50-(Date.now()-r);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 n(this,void 0,void 0,function(){return r(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 n(this,void 0,void 0,function(){var i,n,s,c;return r(this,function(r){switch(r.label){case 0:if(i=void 0===this.storageHandler?l:this.storageHandler,n=o+"-"+t,null===(s=i.getItemSync(n)))return[2];if((c=JSON.parse(s)).id!==this.id)return[3,2];return[4,a.default().lock(c.iat)];case 1:r.sent(),this.acquiredIatSet.delete(c.iat),i.removeItemSync(n),a.default().unlock(c.iat),e.notifyWaiters(),r.label=2;case 2:return[2]}})})},e.lockCorrector=function(t){for(var i=Date.now()-5e3,n=[],r=0;;){var s=t.keySync(r);if(null===s)break;n.push(s),r++}for(var a=!1,l=0;l<n.length;l++){var c=n[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 n=e.locked.get(t);void 0===n?void 0===i?e.locked.set(t,[]):e.locked.set(t,[i]):void 0!==i&&(n.unshift(i),e.locked.set(t,n))},this.isLocked=function(t){return e.locked.has(t)},this.lock=function(t){return new Promise(function(i,n){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 n=i.pop();e.locked.set(t,i),void 0!==n&&setTimeout(n,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,n=String(e),r="",s=!!t&&!!t.extended,a=!!t&&!!t.globstar,o=!1,l=t&&"string"==typeof t.flags?t.flags:"",c=0,d=n.length;c<d;c++)switch(i=n[c]){case"/":case"$":case"^":case"+":case".":case"(":case")":case"=":case"!":case"|":r+="\\"+i;break;case"?":if(s){r+=".";break}case"[":case"]":if(s){r+=i;break}case"{":if(s){o=!0,r+="(";break}case"}":if(s){o=!1,r+=")";break}case",":if(o){r+="|";break}r+="\\"+i;break;case"*":for(var h=n[c-1],u=1;"*"===n[c+1];)u++,c++;var p=n[c+1];a?u>1&&("/"===h||void 0===h)&&("/"===p||void 0===p)?(r+="((?:[^/]*(?:/|$))*)",c++):r+="([^/]*)":r+=".*";break;default:r+=i}return l&&~l.indexOf("g")||(r="^"+r+"$"),new RegExp(r,l)}}},r={};function s(e){var t=r[e];if(void 0!==t)return t.exports;var i=r[e]={exports:{}};return n[e].call(i.exports,i,i.exports,s),i.exports}s.m=n,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 n={};a=a||[null,o({}),o([]),o(o)];for(var r=2&t&&e;("object"==typeof r||"function"==typeof r)&&!~a.indexOf(r);r=o(r))Object.getOwnPropertyNames(r).forEach(t=>{n[t]=()=>e[t]});return n.default=()=>e,s.d(i,n),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.v20251224145055.js",s.h=()=>"fe6fe8abb3a02ec2",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,n){if(l[e])return void l[e].push(t);if(void 0!==i)for(var r,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){r=d;break}}r||(a=!0,(r=document.createElement("script")).timeout=120,s.nc&&r.setAttribute("nonce",s.nc),r.setAttribute("data-webpack","@clerk/clerk-js:"+i),r.src=e),l[e]=[t];var h=function(t,i){r.onerror=r.onload=null,clearTimeout(u);var n=l[e];if(delete l[e],r.parentNode&&r.parentNode.removeChild(r),n&&n.forEach(function(e){return e(i)}),t)return t(i)},u=setTimeout(h.bind(null,void 0,{type:"timeout",target:r}),12e4);r.onerror=h.bind(null,r.onerror),r.onload=h.bind(null,r.onload),a&&document.head.appendChild(r)},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 n=s.o(e,t)?e[t]:void 0;if(0!==n)if(n)i.push(n[2]);else{var r=new Promise((i,r)=>n=e[t]=[i,r]);i.push(n[2]=r);var a=s.p+s.u(t),o=Error();s.l(a,function(i){if(s.o(e,t)&&(0!==(n=e[t])&&(e[t]=void 0),n)){var r=i&&("load"===i.type?"missing":i.type),a=i&&i.target&&i.target.src;o.message="Loading chunk "+t+" failed.\n("+r+": "+a+")",o.name="ChunkLoadError",o.type=r,o.request=a,n[1](o)}},"chunk-"+t,t)}},t=(t,i)=>{var n,r,a=i[0],o=i[1],l=i[2],c=0;if(a.some(t=>0!==e[t])){for(n in o)s.o(o,n)&&(s.m[n]=o[n]);l&&l(s)}for(t&&t(i);c<a.length;c++)r=a[c],s.o(e,r)&&e[r]&&e[r][0](),e[r]=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,n;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.v20251224145055$3")}catch{}function r(){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=r()?window?.navigator:null;return!!t&&!((e=t?.userAgent)&&a.test(e))&&!t?.webdriver}function l(){let e=r()?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,n,r)=>{let{notify:s}=r||{},a=e.get(i);a||(a=[],e.set(i,a)),a.push(n),s&&t.has(i)&&n(t.get(i))},h=(e,t,i)=>(e.get(t)||[]).map(e=>e(i)),u=(e,t,i)=>{let n=e.get(t);n&&(i?n.splice(n.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:(n,r)=>{t.set(n,r),h(i,n,r),h(e,n,r)},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!!e.kind&&"object"==typeof i&&null!==i&&"constructor"in i&&i.constructor?.kind===e.kind||i instanceof e}}var g,_,w=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(w);var b=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,n){let r="Clerk:",s=RegExp(r.replace(" ","\\s*"),"i");return t=t.replace(s,""),t=`${r} ${t.trim()}
3
3
 
4
4
  (code="${i}")
@@ -9,10 +9,10 @@ Docs: ${n}`),t}},y=class e extends b{static kind="ClerkAPIResponseError";status;
9
9
  Message:${this.message}
10
10
  Status:${this.status}
11
11
  Serialized errors: ${this.errors.map(e=>JSON.stringify(e))}`;return this.clerkTraceId&&(e+=`
12
- Clerk Trace ID: ${this.clerkTraceId}`),e}static formatMessage(e,t,i,n){return t}};let v=m(y),k=Object.freeze({InvalidProxyUrlErrorMessage:"The proxyUrl passed to Clerk is invalid. The expected value for proxyUrl is an absolute URL or a relative path with a leading '/'. (key={{url}})",InvalidPublishableKeyErrorMessage:"The publishableKey passed to Clerk is invalid. You can get your Publishable key at https://dashboard.clerk.com/last-active?path=api-keys. (key={{key}})",MissingPublishableKeyErrorMessage:"Missing publishableKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.",MissingSecretKeyErrorMessage:"Missing secretKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.",MissingClerkProvider:"{{source}} can only be used within the <ClerkProvider /> component. Learn more: https://clerk.com/docs/components/clerk-provider"});function S({packageName:e,customMessages:t}){let i=e;function n(e,t){if(!t)return`${i}: ${e}`;let n=e;for(let i of e.matchAll(/{{([a-zA-Z0-9-_]+)}}/g)){let e=(t[i[1]]||"").toString();n=n.replace(`{{${i[1]}}}`,e)}return`${i}: ${n}`}let r={...k,...t};return{setPackageName({packageName:e}){return"string"==typeof e&&(i=e),this},setMessages({customMessages:e}){return Object.assign(r,e||{}),this},throwInvalidPublishableKeyError(e){throw Error(n(r.InvalidPublishableKeyErrorMessage,e))},throwInvalidProxyUrl(e){throw Error(n(r.InvalidProxyUrlErrorMessage,e))},throwMissingPublishableKeyError(){throw Error(n(r.MissingPublishableKeyErrorMessage))},throwMissingSecretKeyError(){throw Error(n(r.MissingSecretKeyErrorMessage))},throwMissingClerkProviderError(e){throw Error(n(r.MissingClerkProvider,e))},throw(e){throw Error(n(e))}}}var U=class e extends Error{code;constructor(t){super(t),this.code=t,this.name="EmailLinkError",Object.setPrototypeOf(this,e.prototype)}},A=class e extends b{static kind="ClerkRuntimeError";clerkRuntimeError=!0;constructor(t,i){super({...i,message:t}),Object.setPrototypeOf(this,e.prototype)}};let I=m(A);var C=class extends A{code;constructor(e,{code:t}){super(e,{code:t}),this.code=t}};function P(e){return["captcha_invalid","captcha_not_enabled","captcha_missing_token"].includes(e.errors[0].code)}function T(e){let t=e?.status;return!!t&&t>=400&&t<500}function O(e){return e&&"clerkError"in e}function E(e){return"clerkRuntimeError"in e}function x(e){for(let[t,i]of Object.entries({isClerkApiResponseError:v,isClerkRuntimeError:I}))Object.assign(e,{[t]:i});return e}let R=(e,t)=>!!(e.isSignedIn&&t?.authConfig.singleSessionMode),z=(e,t)=>!t?.commerceSettings.billing.user.enabled&&!t?.commerceSettings.billing.organization.enabled,M=(e,t)=>!t?.apiKeysSettings?.user_api_keys_enabled,F=(e,t)=>!t?.apiKeysSettings?.orgs_api_keys_enabled,N="__clerk_synced",W="suffixed_cookies",D="__clerk_satellite_url",$="clerk-captcha",L="clerk-invisible-captcha";var j=s(1006);let B=new Set,J=e=>{B.has(e)||(B.add(e),console.warn(e))},K=(e,t)=>{let i={};for(let n in e)i[n]=t(e[n],n);return i},V=(e,t)=>{let i={};for(let n in e)e[n]&&t(e[n])&&(i[n]=e[n]);return i};function q(e){return e?e.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace(/-|_/,"")):""}function G(e){return e?e.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`):""}let H=e=>{let t=i=>{if(!i)return i;if(Array.isArray(i))return i.map(e=>"object"==typeof e||Array.isArray(e)?t(e):e);let n={...i};for(let i of Object.keys(n)){let r=e(i.toString());r!==i&&(n[r]=n[i],delete n[i]),"object"==typeof n[r]&&(n[r]=t(n[r]))}return n};return t},X=H(G),Y=H(q);function Q(e){if("boolean"==typeof e)return e;if(null==e)return!1;if("string"==typeof e){if("true"===e.toLowerCase())return!0;if("false"===e.toLowerCase())return!1}let t=parseInt(e,10);return!isNaN(t)&&t>0}let Z=RegExp("/{1,}","g"),ee=[".lcl.dev",".lclstage.dev",".lclclerk.com"],et=[".accounts.dev",".accountsstage.dev",".accounts.lclclerk.com"],ei=[".lcl.dev",".stg.dev",".lclstage.dev",".stgstage.dev",".dev.lclclerk.com",".stg.lclclerk.com",".accounts.lclclerk.com","accountsstage.dev","accounts.dev"],en=e=>"undefined"!=typeof atob&&"function"==typeof atob?atob(e):"undefined"!=typeof global&&global.Buffer?new global.Buffer(e,"base64").toString():e,er="pk_live_";function es(e){if(!e.endsWith("$"))return!1;let t=e.slice(0,-1);return!t.includes("$")&&t.includes(".")}function ea(e,t={}){let i;if(!(e=e||"")||!eo(e)){if(t.fatal&&!e)throw Error("Publishable key is missing. Ensure that your publishable key is correctly configured. Double-check your environment configuration for your keys, or access them here: https://dashboard.clerk.com/last-active?path=api-keys");if(t.fatal&&!eo(e))throw Error("Publishable key not valid.");return null}let n=e.startsWith(er)?"production":"development";try{i=en(e.split("_")[2])}catch{if(t.fatal)throw Error("Publishable key not valid: Failed to decode key.");return null}if(!es(i)){if(t.fatal)throw Error("Publishable key not valid: Decoded key has invalid format.");return null}let r=i.slice(0,-1);return t.proxyUrl?r=t.proxyUrl:"development"!==n&&t.domain&&t.isSatellite&&(r=`clerk.${t.domain}`),{instanceType:n,frontendApi:r}}function eo(e=""){try{if(!(e.startsWith(er)||e.startsWith("pk_test_")))return!1;let t=e.split("_");if(3!==t.length)return!1;let i=t[2];if(!i)return!1;return es(en(i))}catch{return!1}}async function el(e,t=globalThis.crypto.subtle){var i;let n=new TextEncoder().encode(e);return(i=String.fromCharCode(...new Uint8Array(await t.digest("sha-1",n))),"undefined"!=typeof btoa&&"function"==typeof btoa?btoa(i):"undefined"!=typeof global&&global.Buffer?new global.Buffer(i).toString("base64"):i).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}let ec=(e,t)=>`${e}_${t}`,ed=/^[a-zA-Z][a-zA-Z\d+\-.]*?:/,eh=(e,t={})=>{if(null==e||!e||"object"!=typeof e)return"";let i=new URLSearchParams;return Object.keys(e).forEach(n=>{let r=t.keyEncoder?t.keyEncoder(n):n,s=e[n];if(Array.isArray(s))s.forEach(e=>void 0!==e&&i.append(r,e||""));else{if(void 0===s)return;"object"==typeof s&&null!==s?i.append(r,JSON.stringify(s)):i.append(r,String(s??""))}}),i.toString()},eu="http://clerk-dummy",ep=["javascript:"],{isDevOrStagingUrl:ef}=(n=new Map,{isDevOrStagingUrl:e=>{if(!e)return!1;let t="string"==typeof e?e:e.hostname,i=n.get(t);return void 0===i&&(i=ei.some(e=>t.endsWith(e)),n.set(t,i)),i}}),em=new Map;function eg(e){return e.replace("clerk.","")}function e_(e,t={}){let{base:i,hashPath:n,hashSearch:r,searchParams:s,hashSearchParams:a,...o}=e,l=new URL(i||"","undefined"!=typeof window&&window.location?window.location.href:"http://react-native-fake-base-url");if(s instanceof URLSearchParams&&s.forEach((e,t)=>{null!=e&&l.searchParams.set(G(t),e)}),Object.assign(l,o),n||r||a){var c;let e,t=new URL(eu+l.hash.substring(1));for(let[i,s]of(c=t.pathname,t.pathname=[c,n||""].filter(e=>e).join("/").replace(Z,"/"),Object.entries((e={},new URLSearchParams(r||"").forEach((t,i)=>{if(i in e){let n=e[i];Array.isArray(n)?n.push(t):e[i]=[n,t]}else e[i]=t}),e))))t.searchParams.append(i,s);if(a)for(let e of Array.isArray(a)?a:[a])(e instanceof URLSearchParams||"object"==typeof e)&&new URLSearchParams(e).forEach((e,i)=>{null!=e&&t.searchParams.set(G(i),e)});let i=t.href.replace(eu,"");"/"!==i&&(l.hash=i)}let{stringify:d,skipOrigin:h}=t;return d?h?l.href.replace(l.origin,""):l.href:l}function ew(e){return void 0===window.location&&"string"==typeof e?e:(e=new URL(e.toString(),window.location.origin)).href.replace(e.origin,"")}let eb=e=>(e||"").replace(/\/+$/,"");function ey(e,t){try{return new URL(e)}catch{return new URL(e,t)}}let ev=[/\0/,/^\/\//,/[\x00-\x1F]/],ek=["/oauth/authorize"],eS=["/v1/verify","/v1/tickets/accept","/oauth/authorize-with-immediate-redirect","/oauth/end_session"];var eU=class e{static keys=["signInForceRedirectUrl","signInFallbackRedirectUrl","signUpForceRedirectUrl","signUpFallbackRedirectUrl","redirectUrl"];static preserved=["redirectUrl"];options;fromOptions;fromProps;fromSearchParams;mode;constructor(e,t={},i={},n){this.options=e,this.fromOptions=this.#e(e||{}),this.fromProps=this.#e(t||{}),this.fromSearchParams=this.#t(i||{}),this.mode=n}getAfterSignInUrl(){return this.#i("signIn")}getAfterSignUpUrl(){return this.#i("signUp")}getPreservedSearchParams(){return this.#n(this.#r())}toSearchParams(){return this.#n(this.#s())}#n(e){return new URLSearchParams(Object.entries(Object.fromEntries(Object.entries(e).map(([e,t])=>[G(e),t]))).reduce((e,[t,i])=>(null!=i&&(e[t]=i),e),{}))}#r(){return Object.fromEntries(Object.entries({...this.fromSearchParams}).filter(([t])=>e.preserved.includes(t)))}#s(){let e=this.fromSearchParams.signUpForceRedirectUrl||this.fromProps.signUpForceRedirectUrl||this.fromOptions.signUpForceRedirectUrl,t=this.fromSearchParams.signUpFallbackRedirectUrl||this.fromProps.signUpFallbackRedirectUrl||this.fromOptions.signUpFallbackRedirectUrl,i=this.fromSearchParams.signInForceRedirectUrl||this.fromProps.signInForceRedirectUrl||this.fromOptions.signInForceRedirectUrl,n={signUpForceRedirectUrl:e,signUpFallbackRedirectUrl:t,signInFallbackRedirectUrl:this.fromSearchParams.signInFallbackRedirectUrl||this.fromProps.signInFallbackRedirectUrl||this.fromOptions.signInFallbackRedirectUrl,signInForceRedirectUrl:i,redirectUrl:this.fromSearchParams.redirectUrl};return e&&delete n.signUpFallbackRedirectUrl,i&&delete n.signInFallbackRedirectUrl,n}#i(e){let t,i=`${e}ForceRedirectUrl`,n=`${e}FallbackRedirectUrl`;return(t=this.fromSearchParams[i]||this.fromProps[i]||this.fromOptions[i],t||=this.fromSearchParams.redirectUrl,(t||=this.fromSearchParams[n]||this.fromProps[n]||this.fromOptions[n])||"modal"!==this.mode)?t||"/":window.location.href}#e(t){let i={};return e.keys.forEach(e=>{i[e]=t[e]}),K(this.#a(this.#o(V(i,Boolean))),e=>e.toString())}#t(t){let i={};return e.keys.forEach(e=>{t instanceof URLSearchParams?i[e]=t.get(G(e)):i[e]=t[G(e)]}),K(this.#a(this.#o(V(i,Boolean))),e=>e.toString())}#o(e){return K(e,e=>ey(e,window.location.origin))}#a=e=>{let t,i;return V(e,(t=this.options?.allowedRedirectOrigins,i=window.location.origin,e=>{let n=e;if("string"==typeof n&&(n=ey(n,i)),!t)return!0;let r=i===n.origin,s=!function(e){if(function(e){if(!function(e){if(!e)return!1;try{return new URL(e),!0}catch{return!1}}(e))return!1;let t=new URL(e).protocol;return ep.some(e=>e===t)}(e))return!0;for(let t of ev)if(t.test(e.pathname))return!0;return!1}(n)&&(r||t.map(e=>"string"==typeof e?(e=>{try{return j(e)}catch(t){throw Error(`Invalid pattern: ${e}.
12
+ Clerk Trace ID: ${this.clerkTraceId}`),e}static formatMessage(e,t,i,n){return t}};let v=m(y);var k=class e extends y{static kind="MissingExpiredTokenError";static ERROR_CODE="missing_expired_token";static STATUS=422;static is(t){return v(t)&&t.status===e.STATUS&&t.errors.length>0&&t.errors[0].code===e.ERROR_CODE}};let S=Object.freeze({InvalidProxyUrlErrorMessage:"The proxyUrl passed to Clerk is invalid. The expected value for proxyUrl is an absolute URL or a relative path with a leading '/'. (key={{url}})",InvalidPublishableKeyErrorMessage:"The publishableKey passed to Clerk is invalid. You can get your Publishable key at https://dashboard.clerk.com/last-active?path=api-keys. (key={{key}})",MissingPublishableKeyErrorMessage:"Missing publishableKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.",MissingSecretKeyErrorMessage:"Missing secretKey. You can get your key at https://dashboard.clerk.com/last-active?path=api-keys.",MissingClerkProvider:"{{source}} can only be used within the <ClerkProvider /> component. Learn more: https://clerk.com/docs/components/clerk-provider"});function U({packageName:e,customMessages:t}){let i=e;function n(e,t){if(!t)return`${i}: ${e}`;let n=e;for(let i of e.matchAll(/{{([a-zA-Z0-9-_]+)}}/g)){let e=(t[i[1]]||"").toString();n=n.replace(`{{${i[1]}}}`,e)}return`${i}: ${n}`}let r={...S,...t};return{setPackageName({packageName:e}){return"string"==typeof e&&(i=e),this},setMessages({customMessages:e}){return Object.assign(r,e||{}),this},throwInvalidPublishableKeyError(e){throw Error(n(r.InvalidPublishableKeyErrorMessage,e))},throwInvalidProxyUrl(e){throw Error(n(r.InvalidProxyUrlErrorMessage,e))},throwMissingPublishableKeyError(){throw Error(n(r.MissingPublishableKeyErrorMessage))},throwMissingSecretKeyError(){throw Error(n(r.MissingSecretKeyErrorMessage))},throwMissingClerkProviderError(e){throw Error(n(r.MissingClerkProvider,e))},throw(e){throw Error(n(e))}}}var A=class e extends Error{code;constructor(t){super(t),this.code=t,this.name="EmailLinkError",Object.setPrototypeOf(this,e.prototype)}},I=class e extends b{static kind="ClerkRuntimeError";clerkRuntimeError=!0;constructor(t,i){super({...i,message:t}),Object.setPrototypeOf(this,e.prototype)}};let C=m(I);var P=class extends I{code;constructor(e,{code:t}){super(e,{code:t}),this.code=t}};function T(e){return["captcha_invalid","captcha_not_enabled","captcha_missing_token"].includes(e.errors[0].code)}function O(e){let t=e?.status;return!!t&&t>=400&&t<500}function E(e){for(let[t,i]of Object.entries({isClerkAPIResponseError:v,isClerkRuntimeError:C}))Object.assign(e,{[t]:i});return e}let x=(e,t)=>!!(e.isSignedIn&&t?.authConfig.singleSessionMode),R=(e,t)=>!t?.commerceSettings.billing.user.enabled&&!t?.commerceSettings.billing.organization.enabled,z=(e,t)=>!t?.apiKeysSettings?.user_api_keys_enabled,M=(e,t)=>!t?.apiKeysSettings?.orgs_api_keys_enabled,F="__clerk_synced",N="suffixed_cookies",W="__clerk_satellite_url",D="clerk-captcha",$="clerk-invisible-captcha";var L=s(1006);let j=new Set,B=e=>{j.has(e)||(j.add(e),console.warn(e))},J=(e,t)=>{let i={};for(let n in e)i[n]=t(e[n],n);return i},K=(e,t)=>{let i={};for(let n in e)e[n]&&t(e[n])&&(i[n]=e[n]);return i};function V(e){return e?e.replace(/([-_][a-z])/g,e=>e.toUpperCase().replace(/-|_/,"")):""}function q(e){return e?e.replace(/[A-Z]/g,e=>`_${e.toLowerCase()}`):""}let G=e=>{let t=i=>{if(!i)return i;if(Array.isArray(i))return i.map(e=>"object"==typeof e||Array.isArray(e)?t(e):e);let n={...i};for(let i of Object.keys(n)){let r=e(i.toString());r!==i&&(n[r]=n[i],delete n[i]),"object"==typeof n[r]&&(n[r]=t(n[r]))}return n};return t},H=G(q),X=G(V);function Y(e){if("boolean"==typeof e)return e;if(null==e)return!1;if("string"==typeof e){if("true"===e.toLowerCase())return!0;if("false"===e.toLowerCase())return!1}let t=parseInt(e,10);return!isNaN(t)&&t>0}let Q=RegExp("/{1,}","g"),Z=[".lcl.dev",".lclstage.dev",".lclclerk.com"],ee=[".accounts.dev",".accountsstage.dev",".accounts.lclclerk.com"],et=[".lcl.dev",".stg.dev",".lclstage.dev",".stgstage.dev",".dev.lclclerk.com",".stg.lclclerk.com",".accounts.lclclerk.com","accountsstage.dev","accounts.dev"],ei=e=>"undefined"!=typeof atob&&"function"==typeof atob?atob(e):"undefined"!=typeof global&&global.Buffer?new global.Buffer(e,"base64").toString():e,en="pk_live_";function er(e){if(!e.endsWith("$"))return!1;let t=e.slice(0,-1);return!t.includes("$")&&t.includes(".")}function es(e,t={}){let i;if(!(e=e||"")||!ea(e)){if(t.fatal&&!e)throw Error("Publishable key is missing. Ensure that your publishable key is correctly configured. Double-check your environment configuration for your keys, or access them here: https://dashboard.clerk.com/last-active?path=api-keys");if(t.fatal&&!ea(e))throw Error("Publishable key not valid.");return null}let n=e.startsWith(en)?"production":"development";try{i=ei(e.split("_")[2])}catch{if(t.fatal)throw Error("Publishable key not valid: Failed to decode key.");return null}if(!er(i)){if(t.fatal)throw Error("Publishable key not valid: Decoded key has invalid format.");return null}let r=i.slice(0,-1);return t.proxyUrl?r=t.proxyUrl:"development"!==n&&t.domain&&t.isSatellite&&(r=`clerk.${t.domain}`),{instanceType:n,frontendApi:r}}function ea(e=""){try{if(!(e.startsWith(en)||e.startsWith("pk_test_")))return!1;let t=e.split("_");if(3!==t.length)return!1;let i=t[2];if(!i)return!1;return er(ei(i))}catch{return!1}}async function eo(e,t=globalThis.crypto.subtle){var i;let n=new TextEncoder().encode(e);return(i=String.fromCharCode(...new Uint8Array(await t.digest("sha-1",n))),"undefined"!=typeof btoa&&"function"==typeof btoa?btoa(i):"undefined"!=typeof global&&global.Buffer?new global.Buffer(i).toString("base64"):i).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}let el=(e,t)=>`${e}_${t}`,ec=/^[a-zA-Z][a-zA-Z\d+\-.]*?:/,ed=(e,t={})=>{if(null==e||!e||"object"!=typeof e)return"";let i=new URLSearchParams;return Object.keys(e).forEach(n=>{let r=t.keyEncoder?t.keyEncoder(n):n,s=e[n];if(Array.isArray(s))s.forEach(e=>void 0!==e&&i.append(r,e||""));else{if(void 0===s)return;"object"==typeof s&&null!==s?i.append(r,JSON.stringify(s)):i.append(r,String(s??""))}}),i.toString()},eh="http://clerk-dummy",eu=["javascript:"],{isDevOrStagingUrl:ep}=(n=new Map,{isDevOrStagingUrl:e=>{if(!e)return!1;let t="string"==typeof e?e:e.hostname,i=n.get(t);return void 0===i&&(i=et.some(e=>t.endsWith(e)),n.set(t,i)),i}}),ef=new Map;function em(e){return e.replace("clerk.","")}function eg(e,t={}){let{base:i,hashPath:n,hashSearch:r,searchParams:s,hashSearchParams:a,...o}=e,l=new URL(i||"","undefined"!=typeof window&&window.location?window.location.href:"http://react-native-fake-base-url");if(s instanceof URLSearchParams&&s.forEach((e,t)=>{null!=e&&l.searchParams.set(q(t),e)}),Object.assign(l,o),n||r||a){var c;let e,t=new URL(eh+l.hash.substring(1));for(let[i,s]of(c=t.pathname,t.pathname=[c,n||""].filter(e=>e).join("/").replace(Q,"/"),Object.entries((e={},new URLSearchParams(r||"").forEach((t,i)=>{if(i in e){let n=e[i];Array.isArray(n)?n.push(t):e[i]=[n,t]}else e[i]=t}),e))))t.searchParams.append(i,s);if(a)for(let e of Array.isArray(a)?a:[a])(e instanceof URLSearchParams||"object"==typeof e)&&new URLSearchParams(e).forEach((e,i)=>{null!=e&&t.searchParams.set(q(i),e)});let i=t.href.replace(eh,"");"/"!==i&&(l.hash=i)}let{stringify:d,skipOrigin:h}=t;return d?h?l.href.replace(l.origin,""):l.href:l}function e_(e){return void 0===window.location&&"string"==typeof e?e:(e=new URL(e.toString(),window.location.origin)).href.replace(e.origin,"")}let ew=e=>(e||"").replace(/\/+$/,"");function eb(e,t){try{return new URL(e)}catch{return new URL(e,t)}}let ey=[/\0/,/^\/\//,/[\x00-\x1F]/],ev=["/oauth/authorize"],ek=["/v1/verify","/v1/tickets/accept","/oauth/authorize-with-immediate-redirect","/oauth/end_session"];var eS=class e{static keys=["signInForceRedirectUrl","signInFallbackRedirectUrl","signUpForceRedirectUrl","signUpFallbackRedirectUrl","redirectUrl"];static preserved=["redirectUrl"];options;fromOptions;fromProps;fromSearchParams;mode;constructor(e,t={},i={},n){this.options=e,this.fromOptions=this.#e(e||{}),this.fromProps=this.#e(t||{}),this.fromSearchParams=this.#t(i||{}),this.mode=n}getAfterSignInUrl(){return this.#i("signIn")}getAfterSignUpUrl(){return this.#i("signUp")}getPreservedSearchParams(){return this.#n(this.#r())}toSearchParams(){return this.#n(this.#s())}#n(e){return new URLSearchParams(Object.entries(Object.fromEntries(Object.entries(e).map(([e,t])=>[q(e),t]))).reduce((e,[t,i])=>(null!=i&&(e[t]=i),e),{}))}#r(){return Object.fromEntries(Object.entries({...this.fromSearchParams}).filter(([t])=>e.preserved.includes(t)))}#s(){let e=this.fromSearchParams.signUpForceRedirectUrl||this.fromProps.signUpForceRedirectUrl||this.fromOptions.signUpForceRedirectUrl,t=this.fromSearchParams.signUpFallbackRedirectUrl||this.fromProps.signUpFallbackRedirectUrl||this.fromOptions.signUpFallbackRedirectUrl,i=this.fromSearchParams.signInForceRedirectUrl||this.fromProps.signInForceRedirectUrl||this.fromOptions.signInForceRedirectUrl,n={signUpForceRedirectUrl:e,signUpFallbackRedirectUrl:t,signInFallbackRedirectUrl:this.fromSearchParams.signInFallbackRedirectUrl||this.fromProps.signInFallbackRedirectUrl||this.fromOptions.signInFallbackRedirectUrl,signInForceRedirectUrl:i,redirectUrl:this.fromSearchParams.redirectUrl};return e&&delete n.signUpFallbackRedirectUrl,i&&delete n.signInFallbackRedirectUrl,n}#i(e){let t,i=`${e}ForceRedirectUrl`,n=`${e}FallbackRedirectUrl`;return(t=this.fromSearchParams[i]||this.fromProps[i]||this.fromOptions[i],t||=this.fromSearchParams.redirectUrl,(t||=this.fromSearchParams[n]||this.fromProps[n]||this.fromOptions[n])||"modal"!==this.mode)?t||"/":window.location.href}#e(t){let i={};return e.keys.forEach(e=>{i[e]=t[e]}),J(this.#a(this.#o(K(i,Boolean))),e=>e.toString())}#t(t){let i={};return e.keys.forEach(e=>{t instanceof URLSearchParams?i[e]=t.get(q(e)):i[e]=t[q(e)]}),J(this.#a(this.#o(K(i,Boolean))),e=>e.toString())}#o(e){return J(e,e=>eb(e,window.location.origin))}#a=e=>{let t,i;return K(e,(t=this.options?.allowedRedirectOrigins,i=window.location.origin,e=>{let n=e;if("string"==typeof n&&(n=eb(n,i)),!t)return!0;let r=i===n.origin,s=!function(e){if(function(e){if(!function(e){if(!e)return!1;try{return new URL(e),!0}catch{return!1}}(e))return!1;let t=new URL(e).protocol;return eu.some(e=>e===t)}(e))return!0;for(let t of ey)if(t.test(e.pathname))return!0;return!1}(n)&&(r||t.map(e=>"string"==typeof e?(e=>{try{return L(e)}catch(t){throw Error(`Invalid pattern: ${e}.
13
13
  Consult the documentation of glob-to-regexp here: https://www.npmjs.com/package/glob-to-regexp.
14
- ${t.message}`)}})(eb(e)):e).some(e=>e.test(eb(n.origin))));return s||J(`Clerk: Redirect URL ${n} is not on one of the allowedRedirectOrigins, falling back to the default redirect URL.`),s}))}};let eA="__clerk_netlify_cache_bust",eI=["__clerk_status","__clerk_created_session","__clerk_invitation_token","__clerk_ticket","__clerk_modal_state","__clerk_handshake","__clerk_handshake_nonce","__clerk_help",eA,N,D,W];function eC(e){return new URL(window.location.href).searchParams.get(e)||null}function eP(e){let t=new URL(window.location.href);t.searchParams.has(e)&&(t.searchParams.delete(e),window.history.replaceState(window.history.state,"",t))}function eT(e){let t=new URLSearchParams(window.location.search),i=e||new URLSearchParams;for(let e of eI){let n=t.get(e);n&&i.set(e,n)}return i}let eO={"choose-organization":"choose-organization","reset-password":"reset-password"},eE=e=>`/tasks/${eO[e.key]}`;function ex(e,{navigate:t,baseUrl:i}){let n=e.currentTask;if(n){var r;let e;return t((r={base:i},e=eT(),e_({base:r.base,hashPath:eE(n),searchParams:e},{stringify:!0})))}}let eR=e=>`🔒 Clerk:
14
+ ${t.message}`)}})(ew(e)):e).some(e=>e.test(ew(n.origin))));return s||B(`Clerk: Redirect URL ${n} 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 n=t.get(e);n&&i.set(e,n)}return i}let eT={"choose-organization":"choose-organization","reset-password":"reset-password"},eO=e=>`/tasks/${eT[e.key]}`;function eE(e,{navigate:t,baseUrl:i}){let n=e.currentTask;if(n){var r;let e;return t((r={base:i},e=eP(),eg({base:r.base,hashPath:eO(n),searchParams:e},{stringify:!0})))}}let ex=e=>`🔒 Clerk:
15
15
  ${e.trim()}
16
- (This notice only appears in development)`,ez={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=>eR(`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=>eR(`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(ez)){let t=ez[e];"function"!=typeof t&&(ez[e]=eR(t))}let eM="clerk:beforeunload",eF=["http:","https:","wails:","chrome-extension:"];function eN(e){let t=new URL(e,window.location.href);window.dispatchEvent(new CustomEvent(eM)),window.location.href=t.href}function eW(e){return/^http(s)?:\/\//.test(e||"")}function eD(e){return e.startsWith("/")}var e$=class{#l;#c=864e5;constructor(e){this.#l=e}isEventThrottled(e){let t=Date.now(),i=this.#d(e),n=this.#l.getItem(i);return!!n&&!(t-n>this.#c)||(this.#l.setItem(i,t),!1)}#d(e){let{sk:t,pk:i,payload:n,...r}=e,s={...n,...r};return JSON.stringify(Object.keys({...n,...r}).sort().map(e=>s[e]))}},eL=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}},ej=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 eB=new Set(["error","warn","info","debug","trace"]);var eJ=class{#f;#m;#g={};#_=[];#w=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=ea(e.publishableKey);t&&(this.#g.instanceType=t.instanceType),e.secretKey&&(this.#g.secretKey=e.secretKey.substring(0,16)),this.#m=new e$(eL.isSupported()?new eL:new ej)}get isEnabled(){return!("development"!==this.#g.instanceType||this.#f.disabled||"undefined"!=typeof process&&process.env&&Q(process.env.CLERK_TELEMETRY_DISABLED)||"undefined"!=typeof window&&window?.navigator?.webdriver)}get isDebug(){return this.#f.debug||"undefined"!=typeof process&&process.env&&Q(process.env.CLERK_TELEMETRY_DEBUG)}record(e){try{let t=this.#b(e.event,e.payload);if(this.#y(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&&eB.has(e.level),i="string"==typeof e?.message&&e.message.trim().length>0,n=null,r=e?.timestamp;if("number"==typeof r||"string"==typeof r){let e=new Date(r);Number.isNaN(e.getTime())||(n=e)}if(!t||!i||null===n){this.isDebug&&"undefined"!=typeof console&&console.warn("[clerk/telemetry] Dropping invalid telemetry log entry",{levelIsValid:t,messageIsValid:i,timestampIsValid:null!==n});return}let s=this.#U(),a={sdk:s.name,sdkv:s.version,cv:this.#g.clerkVersion??"",lvl:e.level,msg:e.message,ts:n.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.#w&&("undefined"!=typeof cancelIdleCallback?cancelIdleCallback(Number(this.#w)):clearTimeout(Number(this.#w))),this.#C();return}this.#w||("requestIdleCallback"in window?this.#w=requestIdleCallback(()=>{this.#C(),this.#w=null}):this.#w=setTimeout(()=>{this.#C(),this.#w=null},0))}#C(){let e=[...this.#_];if(this.#_=[],this.#w=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)}#y(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:n}=i.constructor.sdkMetadata;void 0!==t&&(e.name=t),void 0!==n&&(e.version=n)}}}return e}#b(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 eK="COMPONENT_MOUNTED",eV=new Set(["SignIn","SignUp"]);function eq(e){return function(t,i,n){return{event:e,eventSamplingRate:e===eK?eV.has(t)?1:.1:.1,payload:{component:t,appearanceProp:!!i?.appearance,theme:!!i?.appearance?.theme,elements:!!i?.appearance?.elements,variables:!!i?.appearance?.variables,...n}}}}function eG(e,t,i){return eq(eK)(e,t,i)}function eH(e,t,i){return eq("COMPONENT_OPENED")(e,t,i)}function eX(e){return"string"==typeof e?e:"object"==typeof e&&null!==e&&"name"in e&&"string"==typeof e.name?e.name:void 0}function eY(e,t,i){return"function"==typeof e?e(t):void 0!==e?e:void 0!==i?i:void 0}let eQ=(...e)=>{},eZ=!1,e0=null,e1=!1,e3=[];function e2(e,t,i,n){eZ&&(e3.push({level:e,message:t,context:i,source:n,ts:Date.now()}),e3.length>200&&e3.shift())}async function e4(e){try{if(!eZ||e0)return;let{getDebugLogger:t}=await s.e("507").then(s.bind(s,9854)),i=await t({logLevel:e?.logLevel,telemetryCollector:e?.telemetryCollector});if(i&&(e0=i)&&0!==e3.length){for(let e of e3){let t={...e.context||{},__preInit:!0,__preInitTs:e.ts};switch(e.level){case"error":e0.error(e.message,t,e.source);break;case"warn":e0.warn(e.message,t,e.source);break;case"info":e0.info(e.message,t,e.source);break;case"debug":e0.debug(e.message,t,e.source)}}e3.length=0}}catch(e){try{console.debug?.("Debug logger initialization failed",e)}catch{}return}}let e5={debug(e,t,i){e0?e0.debug(e,t,i):e2("debug",e,t,i)},error(e,t,i){e0?e0.error(e,t,i):e2("error",e,t,i)},info(e,t,i){e0?e0.info(e,t,i):e2("info",e,t,i)},warn(e,t,i){e0?e0.warn(e,t,i):e2("warn",e,t,i)}},e6={initialDelay:125,maxDelayBetweenRetries:0,factor:2,shouldRetry:(e,t)=>t<5,retryImmediately:!1,jitter:!0},e8=async e=>new Promise(t=>setTimeout(t,e)),e9=(e,t)=>t?e*(1+Math.random()):e,e7=async(e,t={})=>{var i;let n,r=0,{shouldRetry:s,initialDelay:a,maxDelayBetweenRetries:o,factor:l,retryImmediately:c,jitter:d,onBeforeRetry:h}={...e6,...t},u=(i={initialDelay:a,maxDelayBetweenRetries:o,factor:l,jitter:d},n=0,async()=>{let e;await e8((e=e9(e=i.initialDelay*Math.pow(i.factor,n),i.jitter),Math.min(i.maxDelayBetweenRetries||e,e))),n++});for(;;)try{return await e()}catch(e){if(!s(e,++r))throw e;h&&await h(r),c&&1===r?await e8(e9(100,d)):await u()}},te=async e=>e7(e,{initialDelay:100,shouldRetry:(e,t)=>t<=3,retryImmediately:!0,factor:2});class tt{#P={"@zxcvbn-ts/core":()=>te(()=>s.e("729").then(s.bind(s,7010))),"@zxcvbn-ts/language-common":()=>te(()=>s.e("873").then(s.bind(s,655))),"@base-org/account":()=>te(()=>Promise.all([s.e("994"),s.e("929"),s.e("545")]).then(s.bind(s,71))),"@coinbase/wallet-sdk":()=>te(()=>Promise.all([s.e("994"),s.e("929"),s.e("545")]).then(s.bind(s,5537))),"@stripe/stripe-js":()=>te(()=>s.e("279").then(s.bind(s,5608)))};import(e){return this.#P[e]?this.#P[e]():Promise.resolve(void 0)}}let ti=(e=!1)=>{let t,i;if(!e)return{track:async e=>{await e()},isUnloading:()=>!1};let n=(t=!1,i=()=>t=!0,{startListening:()=>{window.addEventListener("beforeunload",i),window.addEventListener(eM,i)},stopListening:()=>{window.removeEventListener("beforeunload",i),window.removeEventListener(eM,i)},isUnloading:()=>t});return{track:async e=>{n.startListening(),await e(),n.stopListening()},isUnloading:n.isUnloading}},tn=e=>({amount:e.amount,amountFormatted:e.amount_formatted,currency:e.currency,currencySymbol:e.currency_symbol}),tr=e=>{let t={grandTotal:tn(e.grand_total),subtotal:tn(e.subtotal),taxTotal:tn(e.tax_total)};return"past_due"in e&&(t.pastDue=e.past_due?tn(e.past_due):null),"credit"in e&&(t.credit=e.credit?tn(e.credit):null),"total_due_now"in e&&(t.totalDueNow=tn(e.total_due_now)),"total_due_after_free_trial"in e&&(t.totalDueAfterFreeTrial=e.total_due_after_free_trial?tn(e.total_due_after_free_trial):null),t};function ts(e,t=""){return e.errors&&!!e.errors.find(e=>e.code===t)}let ta=S({packageName:"@clerk/clerk-js"});function to(e){return decodeURIComponent(globalThis.atob(e.replace(/_/g,"/").replace(/-/g,"+")).split("").map(e=>"%"+("00"+e.charCodeAt(0).toString(16)).slice(-2)).join(""))}function tl(e){let t=(e||"").split("."),[i,n,r]=t;if(3!==t.length||!i||!n||!r)throw Error("JWT could not be decoded");let s=JSON.parse(to(n)),a={__raw:e};return Object.keys(s).forEach(e=>{a[e]=s[e]}),{encoded:{header:i,payload:n,signature:r},header:JSON.parse(to(i)),claims:a}}function tc(){if(!r())return null;try{let e=navigator?.language;if(!e||"string"!=typeof e||""===e.trim())return null;return e}catch{return null}}function td(){return void 0!==globalThis.document}var th=class e{#T=[];#O={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.#T.find(t=>t.info.name===this.#O[e])?.provider;return void 0!==t?t:window.ethereum};#x=e=>{this.#T.some(t=>t.info.uuid===e.detail.info.uuid)||this.#T.push(e.detail)}},tu=class e{#R=void 0;#z=!1;static #E=null;constructor(){}async #M(){if(this.#z)return;this.#z=!0;let e=await s.e("197").then(s.bind(s,4076)).then(e=>e.getWallets());this.#R=e.get(),e.on("register",()=>{this.#R=e.get()}),e.on("unregister",()=>{this.#R=e.get()})}#F(e){return e.chains?.some(e=>e.startsWith("solana:"))??!1}#N(e){return"solana:signMessage"in e.features}static getInstance(){return e.#E||(e.#E=new e),e.#E}get=async e=>{await this.#M();let t=(this.#R||[]).find(t=>t.name===e&&this.#F(t)&&this.#N(t));if(t&&this.#F(t))return t;if("undefined"==typeof window)return;let i=window.solana;if(i&&"function"==typeof i.connect&&"function"==typeof i.signMessage)return i}};let tp=()=>(function(e){let t=S({packageName:"@clerk/shared"});async function i(e){let{provider:t,walletName:i}=e,n=await f(t,i);if(!n)return"";if("solana"===t){let e=await n.features["standard:connect"].connect();return e&&e.accounts[0].address||""}let r=await n.request({method:"eth_requestAccounts"});return r&&r[0]||""}let n=async e=>{let{identifier:t,nonce:i,provider:n,walletName:r=""}=e,s=await f(n,r);if(!s)return"";if("solana"===n)try{let e=s.accounts.find(e=>e.address===t);if(!e)return console.warn(`Wallet account with address ${t} not found`),"";let n=await s.features["solana:signMessage"]?.signMessage({account:e,message:new TextEncoder().encode(i)});return n?.[0]?.signature?btoa(String.fromCharCode(...n[0].signature)):""}catch(e){if(e instanceof Error&&e.message.includes("User rejected the request."))throw new A("Web3 signature request was rejected by the user.",{code:"web3_signature_request_rejected"});throw new A("An error occurred while generating the Solana signature.",{code:"web3_solana_signature_generation_failed",cause:e instanceof Error?e:void 0})}return await s.request({method:"personal_sign",params:[`0x${i.split("").map(e=>e.charCodeAt(0).toString(16).padStart(2,"0")).join("")}`,t]})};async function r(){return await i({provider:"metamask"})}async function s(){return await i({provider:"coinbase_wallet"})}async function a(){return await i({provider:"okx_wallet"})}async function o(){return await i({provider:"base"})}async function l(e){return await i({provider:"solana",walletName:e})}async function c(e){return await n({...e,provider:"metamask"})}async function d(e){return await n({...e,provider:"coinbase_wallet"})}async function h(e){return await n({...e,provider:"okx_wallet"})}async function u(e){return await n({...e,provider:"base"})}async function p(e){return await n({...e,provider:"solana"})}async function f(i,n){if("coinbase_wallet"===i){let t=await e.import("@coinbase/wallet-sdk");return t?t.createCoinbaseWalletSDK({preference:{options:"all"}}).getProvider():null}if("base"===i)try{let t=await e.import("@base-org/account");if(!t)return null;return t.createBaseAccountSDK({appName:"undefined"!=typeof window&&window.Clerk?.__internal_environment?.displayConfig?.applicationName||"undefined"!=typeof document&&document.title||"Web3 Application"}).getProvider()}catch{return null}return"solana"===i?n&&0!==n.length?await tu.getInstance().get(n):void t.throw("Wallet name must be provided to get Solana wallet provider"):th.getInstance().get(i)}return{getWeb3Identifier:i,generateWeb3Signature:n,getMetamaskIdentifier:r,getCoinbaseWalletIdentifier:s,getOKXWalletIdentifier:a,getBaseIdentifier:o,getSolanaIdentifier:l,generateSignatureWithMetamask:c,generateSignatureWithCoinbaseWallet:d,generateSignatureWithOKXWallet:h,generateSignatureWithBase:u,generateSignatureWithSolana:p}})(new tt),tf="environment",tm=JSON.stringify,tg=JSON.parse;class t_{static _key(e){return`__clerk_${e}`}static isExpired(e){return!!e.exp&&Date.now()>e.exp}static setItem(e,t,i){try{let n={value:t,...i&&{exp:Date.now()+i}};window.localStorage.setItem(this._key(e),tm(n))}catch{}}static getItem(e,t){try{let i=window.localStorage.getItem(this._key(e));if(!i)return t;let n=tg(i);if(!n)return t;if(this.isExpired(n))return this.removeItem(e),t;return n?.value??t}catch{return t}}static removeItem(e){try{window.localStorage.removeItem(this._key(e))}catch{}}}let tw="ClerkJS:";function tb(e=""){throw Error(`${tw} Something went wrong initializing Clerk in development mode.${e&&` ${e}`}`)}function ty(e){throw Error(`${tw} Something went wrong initializing Clerk during the ${e} flow. Please contact support.`)}function tv(e){throw Error(`${tw} You need to start a ${e} flow by calling ${e}.create() first.`)}function tk(e,t){throw Error(`${tw} Strategy "${t}" is not a valid strategy for ${e}.`)}function tS(e){throw Error(`${tw} You need to start a ${e} flow by calling ${e}.create({ identifier: 'your web3 wallet address' }) first`)}function tU(e=""){throw Error(`${tw} Missing '${e}' option`)}function tA(e,t){throw Error(`${tw} Response: ${e||0} not supported yet.
17
- For more information contact us at ${t}`)}function tI(e){throw Error(`${tw} Missing publicKey. When calling 'navigator.credentials.${e}()' it is required to pass a publicKey object.`)}async function tC(e="",t){let{async:i,defer:n,beforeLoad:r,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=n||!1,l.addEventListener("load",()=>{l.remove(),t(l)}),l.addEventListener("error",t=>{l.remove(),o(t.error??Error(`failed to load script: ${e}`))}),l.src=e,l.nonce=a,r?.(l),document.body.appendChild(l)}),{shouldRetry:(e,t)=>t<=5})}async function tP(e){return window.turnstile||await tT(e).catch(()=>{throw{captchaError:"captcha_script_failed_to_load"}}),window.turnstile}async function tT(e){try{return await tC("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 tO(e){try{let t=e.getAttribute("data-cl-theme")||void 0,i=e.getAttribute("data-cl-language")||void 0,n=e.getAttribute("data-cl-size")||void 0;return{theme:t,language:i,size:n}}catch{return{theme:void 0,language:void 0,size:void 0}}}let tE=async e=>{let t,i,n,r,{siteKey:s,widgetType:a,invisibleSiteKey:o,nonce:l}=e,{modalContainerQuerySelector:c,modalWrapperQuerySelector:d,closeModal:h,openModal:u}=e,p=await tP(l),f=[],m="",g="",_=s,w=0,b=null,y="invisible";if(c&&d){b=a,r=c,y="modal";try{await u?.()}catch{throw{captchaError:"modal_component_not_ready"}}let e=await new Promise(e=>{if(document.querySelector(c))return e(document.querySelector(c));let t=new MutationObserver(()=>{document.querySelector(c)&&(t.disconnect(),e(document.querySelector(c)))});t.observe(document.body,{childList:!0,subtree:!0})});if(e){let{theme:r,language:s,size:a}=tO(e);t=r,n=s,i=a}}if(!r&&"smart"===a){let e=document.getElementById($);if(e){y="smart",b="smart",r=`#${$}`,e.style.maxHeight="0";let{theme:s,language:a,size:o}=tO(e);t=s,n=a,i=o}else console.error("Cannot initialize Smart CAPTCHA widget because the `clerk-captcha` DOM element was not found; falling back to Invisible CAPTCHA widget. If you are using a custom flow, visit https://clerk.com/docs/guides/development/custom-flows/authentication/bot-sign-up-protection for instructions")}if(!r){y="invisible",_=o,b="invisible",r=`.${L}`;let e=document.createElement("div");e.classList.add(L),e.style.display="none",document.body.appendChild(e)}let v=async()=>new Promise((s,a)=>{try{let o=p.render(r,{sitekey:_,appearance:"interaction-only",theme:t||"auto",size:i||"normal",language:n||"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($);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),w<2&&(t=e.toString(),["crashed","undefined_error","102","103","104","106","110600","300","600"].find(e=>t.startsWith(e))))?setTimeout(()=>{p.reset(o),w++},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"===y&&h?.(),"invisible"===y){let e=document.querySelector(`.${L}`);e&&document.body.removeChild(e)}if("smart"===y){let e=document.getElementById($);e&&(e.style.maxHeight="0",e.style.minHeight="unset",e.style.marginBottom="unset")}}return{captchaToken:m,captchaWidgetType:b}},tx=e=>{let t=e.__internal_environment,i=t?t.displayConfig.captchaProvider:"turnstile",n=e.__internal_getOption?.("nonce");return{captchaSiteKey:t?t.displayConfig.captchaPublicKey:null,captchaWidgetType:t?t.displayConfig.captchaWidgetType:null,captchaProvider:i,captchaPublicKeyInvisible:t?t.displayConfig.captchaPublicKeyInvisible:null,canUseCaptcha:t?t.userSettings.signUp.captcha_enabled&&e.isStandardBrowser:null,nonce:n||void 0}};class tR{clerk;constructor(e){this.clerk=e}async invisible(e){let{captchaSiteKey:t,canUseCaptcha:i,captchaPublicKeyInvisible:n,nonce:r}=tx(this.clerk);return i&&t&&n?{...await tE({action:e?.action,captchaProvider:"turnstile",invisibleSiteKey:n,nonce:e?.nonce||r||void 0,siteKey:n,widgetType:"invisible"}).catch(e=>e.captchaError?{captchaError:e.captchaError}:{captchaError:e?.message||e||"unexpected_captcha_error"}),captchaAction:e?.action}:{captchaError:"captcha_unavailable",captchaAction:e?.action}}async managedOrInvisible(e){let{captchaSiteKey:t,canUseCaptcha:i,captchaWidgetType:n,captchaProvider:r,captchaPublicKeyInvisible:s,nonce:a}=tx(this.clerk);if(i&&t&&s){let i=await tE({captchaProvider:r,invisibleSiteKey:s,nonce:a||void 0,siteKey:t,widgetType:n,...e}).catch(t=>t.captchaError?{captchaError:t.captchaError}:e?.action==="verify"?{captchaError:t?.message||t||"unexpected_captcha_error"}:void 0);return e?.action==="verify"?{...i,captchaAction:"verify"}:i}return e?.action==="verify"?{captchaError:"captcha_unavailable",captchaAction:e?.action}:{}}async managedInModal(e){return this.managedOrInvisible({modalWrapperQuerySelector:"#cl-modal-captcha-wrapper",modalContainerQuerySelector:"#cl-modal-captcha-container",openModal:()=>this.clerk.__internal_openBlankCaptchaModal(),closeModal:()=>this.clerk.__internal_closeBlankCaptchaModal(),action:e?.action})}}class tz{client;CaptchaChallengeImpl;static instance;inflightException=null;captchaRetryCount=0;MAX_RETRY_ATTEMPTS=3;static getInstance(){return tz.instance||(tz.instance=new tz(iE,tR)),tz.instance}constructor(e,t){this.client=e,this.CaptchaChallengeImpl=t}async execute(e,t){if(this.captchaAttemptsExceeded())throw new A("Security verification failed. Please try again by refreshing the page, clearing your browser cookies, or using a different web browser.",{code:"captcha_client_attempts_exceeded"});try{return this.inflightException&&await this.inflightException,await t()}catch(n){let i;if(!O(n)||E(n)&&"network_error"===n.code||n.errors[0]?.code!=="requires_captcha")throw n;if(this.inflightException)return await this.inflightException,await t();this.inflightException=new Promise(e=>i=e);try{let t=await this.managedChallenge(e);t?.captchaError!=="modal_component_not_ready"&&(await this.client.getOrCreateInstance().__internal_sendCaptchaToken(t),this.captchaRetryCount=0)}catch(e){throw this.captchaRetryCount++,e}finally{i(),this.inflightException=null}return await t()}}managedChallenge(e){return new this.CaptchaChallengeImpl(e).managedInModal({action:"verify"})}captchaAttemptsExceeded=()=>this.captchaRetryCount>=this.MAX_RETRY_ATTEMPTS}class tM{static clerk;id;pathRoot="";static get fapiClient(){return tM.clerk.getFapiClient()}async reload(e){let{rotatingTokenNonce:t}=e||{};return this._baseGet({forceUpdateClient:!0,rotatingTokenNonce:t})}isNew(){return!this.id}static async _fetch(e,t={}){return tz.getInstance().execute(this.clerk,()=>this._baseFetch(e,t))}static async _baseFetch(e,t={}){let i;tM.fapiClient||function(){throw Error(`${tw} Missing FAPI client in resources.`)}();let{fetchMaxTries:n}=t;try{i=await tM.fapiClient.request(e,{fetchMaxTries:n})}catch(t){if(this.shouldRethrowOfflineNetworkErrors())throw new A(t?.message||t,{code:"network_error"});if(!c())return e5.warn("Network request failed while offline, returning null",{method:e.method,path:e.path},"baseResource"),null;throw t}let{payload:r,status:s,statusText:a,headers:o}=i;if(o){let e=o.get("x-country");this.clerk.__internal_setCountry(e?e.toLowerCase():null)}if(("GET"!==e.method||t.forceUpdateClient)&&this._updateClient(r),s>=200&&s<=299)return r;if(s>=400){let e=r?.errors,t=e?.[0]?.long_message,i=e?.[0]?.code;401===s&&"requires_captcha"!==i&&await tM.clerk.handleUnauthenticated(),function(e,t){var i;if(!t||!t[0])return;let n=t[0],r=n.long_message;if("origin_invalid"===n.code&&((i=tM.clerk.publishableKey).startsWith("live_")||i.startsWith("pk_live_"))){let i=tM.clerk.frontendApi.replace("clerk.","");throw new y(`Clerk: Production Keys are only allowed for domain "${i}".
18
- API Error: ${r}`,{data:t,status:e})}}(s,e);let n={data:e,status:s};if(429===s&&o){let e=o.get("retry-after");if(e){let t=parseInt(e,10);isNaN(t)||(n.retryAfter=t)}}throw new y(t||a,n)}return null}static _updateClient(e){if(!e)return;let t=e.client||e.meta?.client;t&&tM.clerk&&tM.clerk.updateClient(iE.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 tM._fetch({method:"GET",path:this.path(),rotatingTokenNonce:e.rotatingTokenNonce},e);return this.fromJSON(t?.response||t)}async _baseMutate(e){let{action:t,body:i,method:n,path:r}=e,s=await tM._fetch({method:n,path:r||this.path(t),body:i});return this.fromJSON(s?.response||s)}async _baseMutateBypass(e){let{action:t,body:i,method:n,path:r}=e,s=await tM._baseFetch({method:n,path:r||this.path(t),body:i});return this.fromJSON(s?.response||s)}async _basePost(e={}){return this._baseMutate({...e,method:"POST"})}async _basePostBypass(e={}){return this._baseMutateBypass({...e,method:"POST"})}async _basePut(e={}){return this._baseMutate({...e,method:"PUT"})}async _basePatch(e={}){return this._baseMutate({...e,method:"PATCH"})}async _baseDelete(e={}){await this._baseMutate({...e,method:"DELETE"})}static shouldRethrowOfflineNetworkErrors(){let e=tM.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}function tF(e){let t=new Date(e||new Date);return t instanceof Date&&!isNaN(t.getTime())?t:new Date}class tN extends tM{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?tF(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?tF(e.last_used_at):null,this.updatedAt=tF(e.updated_at),this.createdAt=tF(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 tW extends tM{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?tF(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 tD=[],{link:t$,unlink:tL,propagate:tj,checkDirty:tB,endTracking:tJ,startTracking:tK,shallowPropagate:tV}=function({update:e,notify:t,unwatched:i}){let n=0;return{link:function(e,t){let i,r=t.depsTail;if(void 0!==r&&r.dep===e)return;if(4&t.flags&&void 0!==(i=void 0!==r?r.nextDep:t.deps)&&i.dep===e){i.version=n,t.depsTail=i;return}let s=e.subsTail;if(void 0!==s&&s.version===n&&s.sub===t)return;let a=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:s,nextSub:void 0};void 0!==i&&(i.prevDep=a),void 0!==r?r.nextDep=a:t.deps=a,void 0!==s?s.nextSub=a:e.subs=a},unlink:r,propagate:function(e){let i,n=e.nextSub;e:for(;;){let r=e.sub,s=r.flags;if(3&s&&(60&s?12&s?4&s?!(48&s)&&function(e,t){let i=t.depsTail;if(void 0!==i){let n=t.deps;do{if(n===e)return!0;if(n===i)break;n=n.nextDep}while(void 0!==n)}return!1}(e,r)?(r.flags=40|s,s&=1):s=0:r.flags=-9&s|32:s=0:r.flags=32|s,2&s&&t(r),1&s)){let t=r.subs;if(void 0!==t){e=t,void 0!==t.nextSub&&(i={value:n,prev:i},n=e.nextSub);continue}}if(void 0!==(e=n)){n=e.nextSub;continue}for(;void 0!==i;)if(e=i.value,i=i.prev,void 0!==e){n=e.nextSub;continue e}break}},checkDirty:function(t,i){let n,r=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)&&(n={value:t,prev:n}),t=a.deps,i=a,++r;continue}if(!l&&void 0!==t.nextDep){t=t.nextDep;continue}for(;r;){--r;let a=i.subs,o=void 0!==a.nextSub;if(o?(t=n.value,n=n.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=r(i,e);e.flags&=-5},startTracking:function(e){++n,e.depsTail=void 0,e.flags=-57&e.flags|4},shallowPropagate:s};function r(e,t=e.sub){let n=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:n.subsTail=l,void 0!==l?l.nextSub=o:void 0===(n.subs=o)&&i(n),a}function s(e){do{let i=e.sub,n=e.nextSub,r=i.flags;(48&r)==32&&(i.flags=16|r,2&r&&t(i)),e=n}while(void 0!==e)}}({update:e=>"getter"in e?t0(e):t1(e,e.value),notify:function e(t){let i=t.flags;if(!(64&i)){t.flags=64|i;let n=t.subs;void 0!==n?e(n.sub):tD[tH++]=t}},unwatched(e){if("getter"in e){let t=e.deps;if(void 0!==t){e.flags=17;do t=tL(t,e);while(void 0!==t)}}else"previousValue"in e||t5.call(e)}}),tq=0,tG=0,tH=0;function tX(t){let i=e;return e=t,i}function tY(e){return t4.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function tQ(e){return t2.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function tZ(i){let n={fn:i,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==e?t$(n,e):void 0!==t&&t$(n,t);let r=tX(n);try{n.fn()}finally{tX(r)}return t5.bind(n)}function t0(e){let t=tX(e);tK(e);try{let t=e.value;return t!==(e.value=e.getter(t))}finally{tX(t),tJ(e)}}function t1(e,t){return e.flags=1,e.previousValue!==(e.previousValue=t)}function t3(){for(;tG<tH;){let e=tD[tG];tD[tG++]=void 0,function e(t,i){if(16&i||32&i&&tB(t.deps,t)){let e=tX(t);tK(t);try{t.fn()}finally{tX(e),tJ(t)}return}32&i&&(t.flags=-33&i);let n=t.deps;for(;void 0!==n;){let t=n.dep,i=t.flags;64&i&&e(t,t.flags=-65&i),n=n.nextDep}}(e,e.flags&=-65)}tG=0,tH=0}function t2(){let i=this.flags;if(16&i||32&i&&tB(this.deps,this)){if(t0(this)){let e=this.subs;void 0!==e&&tV(e)}}else 32&i&&(this.flags=-33&i);return void 0!==e?t$(this,e):void 0!==t&&t$(this,t),this.value}function t4(...t){if(t.length){let e=t[0];if(this.value!==(this.value=e)){this.flags=17;let e=this.subs;void 0!==e&&(tj(e),tq||t3())}}else{let t=this.value;if(16&this.flags&&t1(this,t)){let e=this.subs;void 0!==e&&tV(e)}return void 0!==e&&t$(this,e),t}}function t5(){let e=this.deps;for(;void 0!==e;)e=tL(e,this);let t=this.subs;void 0!==t&&tL(t),this.flags=0}function t6(e){let{pageSize:t,initialPage:i,...n}=e||{},r=t??10;return new URLSearchParams({...Object.entries(n).reduce((e,[t,i])=>(void 0!==i&&(e[t]=i),e),{}),limit:r+"",offset:((i??1)-1)*r+""})}class t8{static #W="/billing";static path(e,t){let{orgId:i}=t||{},n=i?`/organizations/${i}`:"/me";return`${n}${t8.#W}${e}`}getPlans=async e=>{let{for:t,...i}=e||{},n={...i,payer_type:"organization"===t?"org":"user"};return await tM._fetch({path:`${t8.#W}/plans`,method:"GET",search:t6(n)}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new ib(e))}})};getPlan=async e=>new ib(await tM._fetch({path:`${t8.#W}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await tM._fetch({path:t8.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new ik(e?.response));getStatements=async e=>{let{orgId:t,...i}=e;return await tM._fetch({path:t8.path("/statements",{orgId:t}),method:"GET",search:t6(i)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new iy(e))}})};getStatement=async e=>new iy((await tM._fetch({path:t8.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:t,...i}=e;return await tM._fetch({path:t8.path("/payment_attempts",{orgId:t}),method:"GET",search:t6(i)}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new ih(e))}})};getPaymentAttempt=async e=>new ih(await tM._fetch({path:t8.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:t,...i}=e;return new ic((await tM._fetch({path:t8.path("/checkouts",{orgId:t}),method:"POST",body:i}))?.response)}}let t9=tY({resource:null}),t7=tY({error:null}),ie=tY({status:"idle"}),it=tQ(()=>{let e=t9().resource,t=t7().error,i=ie().status;return{errors:io(t,{identifier:null,password:null,code:null}),fetchStatus:i,signIn:e?e.__internal_future:null}}),ii=tY({resource:null}),ir=tY({error:null}),is=tY({status:"idle"}),ia=tQ(()=>{let e=ii().resource,t=ir().error,i=is().status;return{errors:io(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 io(e,t){let i={fields:{...t},raw:null,global:null};if(!e)return i;if(!O(e))return i.raw=[e],i.global=[x(e)],i;function n(e){return"meta"in e&&e.meta&&"paramName"in e.meta&&void 0!==e.meta.paramName}return e.errors.some(n)?e.errors.forEach(e=>{if(i.raw?i.raw.push(e):i.raw=[e],n(e)){let t=q(e.meta.paramName);t in i.fields&&(i.fields[t]=e)}}):(i.raw=[e],i.global=[x(e)]),i}class il extends tM{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=tF(e.created_at)),e.updated_at&&(this.updatedAt=tF(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 ic extends tM{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 i_(e.payment_method):void 0,this.plan=new ib(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=tF(e.free_trial_ends_at)),this.payer=new il(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>e7(()=>this._basePatch({path:t8.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,n=409===i&&e.errors?.[0]?.code==="checkout_already_in_progress";return i>=500||n}})}class id{resource=new ic(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 ic.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new ic(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 ic.clerk.setActive({session:ic.clerk.session?.id,navigate:t})})}runAsyncCheckoutTask(e,t,i){var n,r,s;return void 0===ic.clerk.user?(console.warn("Clerk: Checkout operations cannot be performed during transitive state"),{error:null}):(n=this,r=this.signals,s=this.pendingOperations,async(e,t,i)=>{if(s.get(e))return s.get(e);let a=(async()=>{++tq,r.errorSignal({error:null}),r.fetchSignal({status:"fetching"}),i?.(),--tq||t3(),++tq;try{return await t(),r.resourceSignal({resource:n}),{error:null}}catch(e){return r.errorSignal({error:e}),{error:e}}finally{s.delete(e),r.fetchSignal({status:"idle"}),--tq||t3()}})();return s.set(e,a),a})(e,t,i)}}class ih extends tM{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=tn(e.amount),this.paidAt=e.paid_at?tF(e.paid_at):null,this.failedAt=e.failed_at?tF(e.failed_at):null,this.updatedAt=tF(e.updated_at),this.paymentMethod=e.payment_method?new i_(e.payment_method):null,this.subscriptionItem=new iS(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status),this}}let iu="/payment_methods",ip=async e=>{let{orgId:t,...i}=e;return new iw((await tM._fetch({path:t8.path(`${iu}/initialize`,{orgId:t}),method:"POST",body:i}))?.response)},im=async e=>{let{orgId:t,...i}=e;return new i_((await tM._fetch({path:t8.path(iu,{orgId:t}),method:"POST",body:i}))?.response)},ig=async e=>{let{orgId:t,...i}=e??{};return await tM._fetch({path:t8.path(iu,{orgId:t}),method:"GET",search:t6(i)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new i_(e))}})};class i_ extends tM{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:tF(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:tF(e.updated_at)),this}async remove(e){let{orgId:t}=e??{};return new iR((await tM._fetch({path:t8.path(`/payment_methods/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:t}=e??{};return await tM._fetch({path:t8.path("/payers/default_payment_method",{orgId:t}),method:"PUT",body:{payment_method_id:this.id}}),null}}class iw extends tM{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 ib extends tM{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=tn(e.fee),this.annualFee=e.annual_fee?tn(e.annual_fee):null,this.annualMonthlyFee=e.annual_monthly_fee?tn(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 nt(e))),this}}class iy extends tM{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=tF(e.timestamp),this.totals=tr(e.totals),this.groups=e.groups.map(e=>new iv(e))),this}}class iv{id;timestamp;items;constructor(e){this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.timestamp=tF(e.timestamp),this.items=e.items.map(e=>new ih(e))),this}}class ik extends tM{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=tF(e.created_at),this.updatedAt=e.updated_at?tF(e.updated_at):null,this.activeAt=tF(e.active_at),this.pastDueAt=e.past_due_at?tF(e.past_due_at):null,e.next_payment&&(this.nextPayment={amount:tn(e.next_payment.amount),date:tF(e.next_payment.date)}),this.subscriptionItems=(e.subscription_items||[]).map(e=>new iS(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1)),this}}class iS extends tM{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 ib(e.plan),this.planPeriod=e.plan_period,this.status=e.status,this.createdAt=tF(e.created_at),this.pastDueAt=e.past_due_at?tF(e.past_due_at):null,this.periodStart=tF(e.period_start),this.periodEnd=e.period_end?tF(e.period_end):null,this.canceledAt=e.canceled_at?tF(e.canceled_at):null,this.amount=e.amount?tn(e.amount):void 0,this.credit=e.credit&&e.credit.amount?{amount:tn(e.credit.amount)}:void 0,this.isFreeTrial=this.withDefault(e.is_free_trial,!1)),this}async cancel(e){let{orgId:t}=e;return new iR((await tM._fetch({path:t8.path(`/subscription_items/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}}let iU={build:(e,t,i)=>[e,t,i].filter(Boolean).join("-"),parse:(e,t,i)=>{let n=iU.extractTemplate(e,t,i);return{organizationId:i,sessionId:t,template:n}},extractTemplate:(e,t,i)=>{if(e===t||i&&e===`${t}-${i}`)return;let n=e.slice(t.length+1);return i&&n.endsWith(`-${i}`)&&(n=n.slice(0,-(i.length+1))),n||void 0}},iA="clerk",iI=10,iC={broadcast:!0},iP={broadcast:!1};class iT{prefix;data;static fromKey(e){let[t,i,n=""]=e.split("::");return new iT(t,{audience:n,tokenId:i})}constructor(e,t){this.prefix=e,this.data=t,this.prefix=e,this.data=t}toKey(){let{tokenId:e,audience:t}=this.data;return[this.prefix,e,t||""].join("::")}}let iO=((e=iA)=>{let t=new Map,i=Math.random().toString(36).slice(2),n=null,r=()=>n||("undefined"==typeof BroadcastChannel?null:((n=new BroadcastChannel("clerk:session_token")).addEventListener("message",e=>{a(e)}),n));r();let s=(i,n=iI)=>{r();let s=new iT(e,i),a=t.get(s.toKey());if(!a)return;let o=Math.floor(Date.now()/1e3)-a.createdAt;if(a.expiresIn-o<(n||1)+5){void 0!==a.timeoutId&&clearTimeout(a.timeoutId),t.delete(s.toKey());return}return a.entry},a=async({data:e})=>{let t,n=iU.build(e.sessionId,e.template,e.organizationId);if(e.tokenId!==n)return void e5.warn("Ignoring token broadcast with mismatched tokenId",{expectedTokenId:n,organizationId:e.organizationId,receivedTokenId:e.tokenId,tabId:i,template:e.template,traceId:e.traceId},"tokenCache");try{t=new n$({id:e.tokenId,jwt:e.tokenRaw,object:"token"})}catch(t){e5.warn("Failed to parse token from broadcast, skipping cache update",{error:t,tabId:i,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");return}let r=t.jwt?.claims?.iat,a=t.jwt?.claims?.exp;if(!r||!a)return void e5.warn("Token missing iat/exp claim, skipping cache update",{tabId:i,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");try{let t=s({tokenId:e.tokenId});if(t){let n=await t.tokenResolver,s=n.jwt?.claims?.iat;if(s&&s>=r)return void e5.debug("Ignoring older token broadcast",{existingIat:s,incomingIat:r,tabId:i,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}}catch(t){e5.warn("Existing entry compare failed; proceeding with broadcast update",{error:t,tabId:i,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}e5.info("Updating token cache from broadcast",{iat:r,organizationId:e.organizationId,tabId:i,template:e.template,tokenId:e.tokenId,traceId:e.traceId},"tokenCache"),o({createdAt:r,tokenId:e.tokenId,tokenResolver:Promise.resolve(t)},iP)},o=(r,s=iC)=>{let a=new iT(e,{audience:r.audience,tokenId:r.tokenId}).toKey(),o=Math.floor(Date.now()/1e3),l={createdAt:r.createdAt??o,entry:r,expiresIn:void 0},c=()=>{let e=t.get(a);e===l&&(void 0!==e.timeoutId&&clearTimeout(e.timeoutId),t.delete(a))};r.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=n;if(d&&s.broadcast){let n=e.getRawString();if(n&&t.sid){let e=t.sid,s=t.org_id||t.o?.id,a=iU.extractTemplate(r.tokenId,e,s),o=iU.build(e,a,s);if(r.tokenId===o){let t=`bc_${Date.now()}_${Math.random().toString(36).substring(2,11)}`;e5.info("Broadcasting token update to other tabs",{organizationId:s,sessionId:e,tabId:i,template:a,tokenId:r.tokenId,traceId:t},"tokenCache");let o={organizationId:s,sessionId:e,template:a,tokenId:r.tokenId,tokenRaw:n,traceId:t};d.postMessage(o)}}}}).catch(()=>{c()}),t.set(a,l)};return{clear:()=>{t.forEach(e=>{void 0!==e.timeoutId&&clearTimeout(e.timeoutId)}),t.clear()},close:()=>{n&&(n.close(),n=null)},get:s,set:e=>{r(),o(e,iC)},size:()=>t.size}})();class iE extends tM{static instance;pathRoot="/client";sessions=[];signUp=new nN;signIn=new nz;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return iE.instance||(iE.instance=new iE(e)),iE.instance}static clearInstance(){iE.instance=null}static isClientResource(e){return!!e&&e instanceof iE}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(()=>{iO.clear(),this.id="",this.sessions=[],this.signUp=new nN(null),this.signIn=new nz(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=>(iO.clear(),e))}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return tM.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 nA(e)),this.signUp=new nN(e.sign_up),this.signIn=new nz(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?tF(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=tF(e.created_at||void 0),this.updatedAt=tF(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 ix extends tM{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 iR{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 iz extends tM{afterCreateOrganizationUrl="";afterJoinWaitlistUrl="";afterLeaveOrganizationUrl="";afterSignInUrl="";afterSignOutAllUrl="";afterSignOutOneUrl="";afterSignOutUrl="";afterSignUpUrl="";afterSwitchSessionUrl="";applicationName="";backendHost="";branded=!1;captchaHeartbeat=!1;captchaHeartbeatIntervalMs;captchaOauthBypass=["oauth_google","oauth_microsoft","oauth_apple"];captchaProvider="turnstile";captchaPublicKey=null;captchaPublicKeyInvisible=null;captchaWidgetType=null;clerkJSVersion;createOrganizationUrl="";faviconImageUrl="";googleOneTapClientId;homeUrl="";id="";instanceEnvironmentType="";logoImageUrl="";organizationProfileUrl="";preferredSignInStrategy="password";privacyPolicyUrl="";showDevModeWarning=!1;signInUrl="";signUpUrl="";supportEmail="";termsUrl="";theme={};userProfileUrl="";waitlistUrl="";constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.afterCreateOrganizationUrl=this.withDefault(e.after_create_organization_url,this.afterCreateOrganizationUrl),this.afterJoinWaitlistUrl=this.withDefault(e.after_join_waitlist_url,this.afterJoinWaitlistUrl),this.afterLeaveOrganizationUrl=this.withDefault(e.after_leave_organization_url,this.afterLeaveOrganizationUrl),this.afterSignInUrl=this.withDefault(e.after_sign_in_url,this.afterSignInUrl),this.afterSignOutAllUrl=this.withDefault(e.after_sign_out_all_url,this.afterSignOutAllUrl),this.afterSignOutOneUrl=this.withDefault(e.after_sign_out_one_url,this.afterSignOutOneUrl),this.afterSignUpUrl=this.withDefault(e.after_sign_up_url,this.afterSignUpUrl),this.afterSwitchSessionUrl=this.withDefault(e.after_switch_session_url,this.afterSwitchSessionUrl),this.applicationName=this.withDefault(e.application_name,this.applicationName),this.branded=this.withDefault(e.branded,this.branded),this.captchaHeartbeat=this.withDefault(e.captcha_heartbeat,this.captchaHeartbeat),this.captchaHeartbeatIntervalMs=this.withDefault(e.captcha_heartbeat_interval_ms,this.captchaHeartbeatIntervalMs),this.captchaOauthBypass=this.withDefault(e.captcha_oauth_bypass,this.captchaOauthBypass),this.captchaProvider=this.withDefault(e.captcha_provider,this.captchaProvider),this.captchaPublicKey=this.withDefault(e.captcha_public_key,this.captchaPublicKey),this.captchaPublicKeyInvisible=this.withDefault(e.captcha_public_key_invisible,this.captchaPublicKeyInvisible),this.captchaWidgetType=this.withDefault(e.captcha_widget_type,this.captchaWidgetType),this.clerkJSVersion=this.withDefault(e.clerk_js_version,this.clerkJSVersion),this.createOrganizationUrl=this.withDefault(e.create_organization_url,this.createOrganizationUrl),this.faviconImageUrl=this.withDefault(e.favicon_image_url,this.faviconImageUrl),this.googleOneTapClientId=this.withDefault(e.google_one_tap_client_id,this.googleOneTapClientId),this.homeUrl=this.withDefault(e.home_url,this.homeUrl),this.id=this.withDefault(e.id,this.id),this.instanceEnvironmentType=this.withDefault(e.instance_environment_type,this.instanceEnvironmentType),this.logoImageUrl=this.withDefault(e.logo_image_url,this.logoImageUrl),this.organizationProfileUrl=this.withDefault(e.organization_profile_url,this.organizationProfileUrl),this.preferredSignInStrategy=this.withDefault(e.preferred_sign_in_strategy,this.preferredSignInStrategy),this.privacyPolicyUrl=this.withDefault(e.privacy_policy_url,this.privacyPolicyUrl),this.showDevModeWarning=this.withDefault(e.show_devmode_warning,this.showDevModeWarning),this.signInUrl=this.withDefault(e.sign_in_url,this.signInUrl),this.signUpUrl=this.withDefault(e.sign_up_url,this.signUpUrl),this.supportEmail=this.withDefault(e.support_email,this.supportEmail),this.termsUrl=this.withDefault(e.terms_url,this.termsUrl),this.theme=this.withDefault(e.theme,this.theme),this.userProfileUrl=this.withDefault(e.user_profile_url,this.userProfileUrl),this.waitlistUrl=this.withDefault(e.waitlist_url,this.waitlistUrl)),this}__internal_toSnapshot(){return{object:"display_config",after_create_organization_url:this.afterCreateOrganizationUrl,after_join_waitlist_url:this.afterJoinWaitlistUrl,after_leave_organization_url:this.afterLeaveOrganizationUrl,after_sign_in_url:this.afterSignInUrl,after_sign_out_all_url:this.afterSignOutAllUrl,after_sign_out_one_url:this.afterSignOutOneUrl,after_sign_up_url:this.afterSignUpUrl,after_switch_session_url:this.afterSwitchSessionUrl,application_name:this.applicationName,branded:this.branded,captcha_heartbeat_interval_ms:this.captchaHeartbeatIntervalMs,captcha_heartbeat:this.captchaHeartbeat,captcha_oauth_bypass:this.captchaOauthBypass,captcha_provider:this.captchaProvider,captcha_public_key_invisible:this.captchaPublicKeyInvisible,captcha_public_key:this.captchaPublicKey,captcha_widget_type:this.captchaWidgetType,clerk_js_version:this.clerkJSVersion,create_organization_url:this.createOrganizationUrl,favicon_image_url:this.faviconImageUrl,google_one_tap_client_id:this.googleOneTapClientId,home_url:this.homeUrl,id:this.id,instance_environment_type:this.instanceEnvironmentType,logo_image_url:this.logoImageUrl,organization_profile_url:this.organizationProfileUrl,preferred_sign_in_strategy:this.preferredSignInStrategy,privacy_policy_url:this.privacyPolicyUrl,show_devmode_warning:this.showDevModeWarning,sign_in_url:this.signInUrl,sign_up_url:this.signUpUrl,support_email:this.supportEmail,terms_url:this.termsUrl,theme:this.theme,user_profile_url:this.userProfileUrl,waitlist_url:this.waitlistUrl}}}var iM='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 iF=(e,t={})=>{if("undefined"==typeof Worker)return null;try{let i=new Blob([e],{type:"application/javascript; charset=utf-8"}),n=globalThis.URL.createObjectURL(i);return new Worker(n,t)}catch{return console.warn("Clerk: Cannot create worker from blob. Consider adding worker-src blob:; to your CSP"),null}},iN=()=>{let e=0,t=()=>e++,i=new Map,n=(e,t)=>e?.postMessage(t),r=e=>{i.get(e.data.id)?.()},s=iF(iM,{name:"clerk-timers"});if(s?.addEventListener("message",r),!s)return{setTimeout:globalThis.setTimeout.bind(globalThis),setInterval:globalThis.setInterval.bind(globalThis),clearTimeout:globalThis.clearTimeout.bind(globalThis),clearInterval:globalThis.clearInterval.bind(globalThis),cleanup:eQ};let a=()=>{s||(s=iF(iM,{name:"clerk-timers"}),s?.addEventListener("message",r))};return{setTimeout:(e,r)=>{a();let o=t();return i.set(o,()=>{e(),i.delete(o)}),n(s,{type:"setTimeout",id:o,ms:r}),o},setInterval:(e,r)=>{a();let o=t();return i.set(o,e),n(s,{type:"setInterval",id:o,ms:r}),o},clearTimeout:e=>{a(),i.delete(e),n(s,{type:"clearTimeout",id:e})},clearInterval:e=>{a(),i.delete(e),n(s,{type:"clearInterval",id:e})},cleanup:()=>{s&&(s.terminate(),s=null,i.clear())}}};function iW({delayInMs:e}={delayInMs:1e3}){let t,i=iN(),n=!1,r=()=>{t&&(i.clearTimeout(t),i.cleanup()),n=!0},s=async a=>{n=!1,await a(r),n||(t=i.setTimeout(()=>{s(a)},e))};return{run:s,stop:r}}class iD extends tM{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}=iW();return{startEmailLinkFlow:async({redirectUrl:i})=>(await this.prepareVerification({strategy:"email_link",redirectUrl:i}),new Promise((i,n)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),i(e))}).catch(e=>{t(),n(e)}))})),cancelEmailLinkFlow:t}};createEnterpriseSSOLinkFlow=()=>{let{run:e,stop:t}=iW();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,n)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),i(e))}).catch(e=>{t(),n(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 iX(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new ni(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 i$=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,n=new Uint8Array(i);for(let e=0;e<i;e++)n[e]=t.charCodeAt(e);return n.buffer}};async function iL(e){try{let t=await navigator.credentials.create({publicKey:e});if(!t)return{error:new C("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 C(t.message,{code:"passkey_already_exists"}):"NotAllowedError"===t.name?new C(t.message,{code:"passkey_registration_cancelled"}):iJ(t),publicKeyCredential:null}}}let ij=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 iB({publicKeyOptions:e,conditionalUI:t}){try{let i=await navigator.credentials.get({publicKey:e,mediation:t?"conditional":"optional",signal:ij.createAbortSignal()});if(!i)return{error:new C("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 C(i.message,{code:"passkey_retrieval_cancelled"}):iJ(i),publicKeyCredential:null}}}function iJ(e){return"AbortError"===e.name?new C(e.message,{code:"passkey_operation_aborted"}):"SecurityError"===e.name?new C(e.message,{code:"passkey_invalid_rpID_or_domain"}):e}function iK(e){let t=iH(e.challenge),i=(e.allowCredentials||[]).map(e=>({...e,id:iH(e.id)}));return{...e,allowCredentials:i,challenge:t}}function iV(e){return{type:e.type,id:e.id,rawId:iG(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function iq(e){let t=e.response;return{...iV(e),response:{clientDataJSON:iG(t.clientDataJSON),authenticatorData:iG(t.authenticatorData),signature:iG(t.signature),userHandle:t.userHandle?iG(t.userHandle):null}}}let iG=i$.encode.bind(i$),iH=i$.decode.bind(i$);class iX extends tM{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===tM.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=tF(e.expire_at||void 0),this.error=e.error?new w(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 iY extends iX{publicKey=null;constructor(e){super(e),this.fromJSON(e)}fromJSON(e){var t;let i,n,r;return super.fromJSON(e),e?.nonce&&(this.publicKey=(i=iH((t=JSON.parse(e.nonce)).user.id),n=iH(t.challenge),r=(t.excludeCredentials||[]).map(e=>({...e,id:iH(e.id)})),{...t,excludeCredentials:r,challenge:n,user:{...t.user,id:i}})),this}}class iQ{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new iZ(e.email_address),this.phoneNumber=new iZ(e.phone_number),this.web3Wallet=new iZ(e.web3_wallet),this.externalAccount=new iX(e.external_account)):(this.emailAddress=new iZ(null),this.phoneNumber=new iZ(null),this.web3Wallet=new iZ(null),this.externalAccount=new iX(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 iZ extends iX{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 i0 extends tM{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?tF(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new iX(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new i1(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 i1 extends tM{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=tF(e.created_at),this.updatedAt=tF(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 i3="token:update",i2="user:signOut",i4="environment:update",i5="session:tokenResolved",i6=p();class i8 extends tM{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 i9 extends tM{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 i7 extends tM{static instance;authConfig=new tW;displayConfig=new iz;maintenanceMode=!1;clientDebugMode=!1;pathRoot="/environment";userSettings=new nq;organizationSettings=new i9;commerceSettings=new ix;apiKeysSettings=new i8;protectConfig=new n_;static getInstance(){return i7.instance||(i7.instance=new i7),i7.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new tW(e.auth_config),this.displayConfig=new iz(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 i9(e.organization_settings),this.userSettings=new nq(e.user_settings),this.commerceSettings=new ix(e.commerce_settings),this.apiKeysSettings=new i8(e.api_keys_settings),this.protectConfig=new n_(e.protect_config)),this}fetch({touch:e,fetchMaxTries:t}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:t})).then(e=>(i6.emit(i4,null),e))}isDevelopmentOrStaging=()=>!this.isProduction();isProduction=()=>"production"===this.displayConfig.instanceEnvironmentType;isSingleSession=()=>this.authConfig.singleSessionMode;onWindowLocationHost=()=>this.displayConfig.backendHost===window.location.host;__internal_toSnapshot(){return{object:"environment",auth_config:this.authConfig.__internal_toSnapshot(),display_config:this.displayConfig.__internal_toSnapshot(),id:this.id??"",maintenance_mode:this.maintenanceMode,client_debug_mode:this.clientDebugMode,organization_settings:this.organizationSettings.__internal_toSnapshot(),user_settings:this.userSettings.__internal_toSnapshot(),commerce_settings:this.commerceSettings.__internal_toSnapshot(),api_keys_settings:this.apiKeysSettings.__internal_toSnapshot(),protect_config:this.protectConfig.__internal_toSnapshot()}}async __internal_enableEnvironmentSetting(e){await this._basePatch({path:"/dev_tools/enable_environment_setting",body:e})}}class ne extends tM{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 iX(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 nt extends tM{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 ni extends tM{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 nn extends tM{id;name=null;publicUrl=null;static async create(e,t={}){let i,n=t;return"string"==typeof t.file?(n=t.file,i=new Headers({"Content-Type":"application/octet-stream"})):t.file&&(n=new FormData).append("file",t.file),new nn((await tM._fetch({path:e,method:"POST",body:n,headers:i}))?.response)}static async delete(e){return new nn((await tM._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 nr extends tM{id;name;organizationId;enrollmentMode;verification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:t}){return new nr((await tM._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:tF(e.verification.expires_at)}:this.verification=null),this}}class ns extends tM{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=tF(e.created_at),this.updatedAt=tF(e.updated_at),e.public_user_data&&(this.publicUserData=new nw(e.public_user_data))),this}}class na extends tM{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=tF(e.created_at),this.updatedAt=tF(e.updated_at)),this}}class no extends tM{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 na(e)),this.createdAt=tF(e.created_at),this.updatedAt=tF(e.updated_at)),this}}class nl extends tM{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 nl((await tM._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new nl((await tM._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await tM._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:t6(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new no(e))}});getDomains=async e=>await tM._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:t6(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new nr(e))}});getDomain=async({domainId:e})=>new nr((await tM._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getMembershipRequests=async e=>await tM._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:t6(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new ns(e))}});createDomain=async e=>nr.create(this.id,{name:e});getMemberships=async e=>await tM._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:t6({...e,paginated:!0})}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new nd(e))}});getInvitations=async e=>await tM._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:t6(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new nc(e))}});addMember=async({userId:e,role:t})=>await tM._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:t}}).then(e=>new nd(e?.response));inviteMember=async e=>nc.create(this.id,e);inviteMembers=async e=>nc.createBulk(this.id,e);updateMember=async({userId:e,role:t})=>await tM._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:t}}).then(e=>new nd(e?.response));removeMember=async e=>await tM._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new nd(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let t,i;return null===e?await tM._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new nl(e?.response)):("string"==typeof e?(t=e,i=new Headers({"Content-Type":"application/octet-stream"})):(t=new FormData).append("file",e),await tM._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:t,headers:i}).then(e=>new nl(e?.response)))};initializePaymentMethod=e=>ip({...e,orgId:this.id});addPaymentMethod=e=>im({...e,orgId:this.id});getPaymentMethods=e=>ig({...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=tF(e.created_at),this.updatedAt=tF(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 tM._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:t},{forceUpdateClient:!0}))?.response;return this.fromJSON(i)}}class nc extends tM{id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:t,role:i}){return new nc((await tM._fetch({path:`/organizations/${e}/invitations`,method:"POST",body:{email_address:t,role:i}}))?.response)}static async createBulk(e,t){let{emailAddresses:i,role:n}=t;return((await tM._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:i,role:n}}))?.response).map(e=>new nc(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=tF(e.created_at),this.updatedAt=tF(e.updated_at)),this}}class nd extends tM{id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await tM._fetch({path:"/me/organization_memberships",method:"GET",search:t6({...e,paginated:!0})}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new nd(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 nl(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new nw(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=tF(e.created_at),this.updatedAt=tF(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(`${tw} Calling OrganizationMembership.reload is not currently supported. Please contact support.`)}}class nh extends tM{id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await tM._fetch({path:"/me/organization_suggestions",method:"GET",search:t6(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new nh(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=tF(e.created_at),this.updatedAt=tF(e.updated_at)),this}}function nu(){return o()&&"function"==typeof window.PublicKeyCredential}async function np(){try{return nu()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function nf(){try{return"undefined"!=typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class nm extends tM{id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return tM._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new nm(e?.response))}static async attemptVerification(e,t){let i,n=(i=t.response,{...iV(t),response:{clientDataJSON:iG(i.clientDataJSON),attestationObject:iG(i.attestationObject),transports:i.getTransports()}});return tM._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(n)}}).then(e=>new nm(e?.response))}static async registerPasskey(){let e=nm.clerk.__internal_isWebAuthnSupported||nu,t=nm.clerk.__internal_createPublicCredentials||iL,i=nm.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||nf;if(!e())throw new C("Passkeys are not supported on this device.",{code:"passkey_not_supported"});let n=await this.create(),{verification:r}=n,s=r?.publicKey;if(s||tI("create"),s.authenticatorSelection?.authenticatorAttachment==="platform"&&!await i())throw new C("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(n.id,a)}update=e=>this._basePatch({body:e});delete=async()=>new iR((await tM._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?tF(e.last_used_at):null,this.createdAt=tF(e.created_at),this.updatedAt=tF(e.updated_at),e.verification&&(this.verification=new iY(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 ng extends tM{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 iX(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new ni(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 n_ extends tM{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 nw{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 nb={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"}},ny=new Set(["first_factor","second_factor","multi_factor"]),nv=new Set(["strict_mfa","strict","moderate","lax"]),nk=(e,t)=>{let{org:i,user:n}=nS(e),[r,s]=t.split(":"),a=s||r;return"org"===r?i.includes(a):"user"===r?n.includes(a):[...i,...n].includes(a)},nS=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 nU extends tM{status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new iX(null);secondFactorVerification=new iX(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new nA(e.session),this.level=e.level,this.supportedFirstFactors=Y(e.supported_first_factors),this.supportedSecondFactors=Y(e.supported_second_factors),this.firstFactorVerification=new iX(e.first_factor_verification),this.secondFactorVerification=new iX(e.second_factor_verification)),this}}class nA extends tM{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 nA}constructor(e){super(),this.fromJSON(e),this.#D(this.lastActiveToken)}end=()=>(iO.clear(),this._basePost({action:"end"}));remove=()=>(iO.clear(),this._basePost({action:"remove"}));touch=()=>this._basePost({action:"touch",body:{active_organization_id:this.lastActiveOrganizationId}}).then(e=>(e.lastActiveToken&&i6.emit(i3,{token:e.lastActiveToken}),e));clearCache=()=>iO.clear();getToken=async e=>e7(()=>this._getToken(e),{factor:1.55,initialDelay:3e3,maxDelayBetweenRetries:5e4,jitter:!1,shouldRetry:(e,t)=>!T(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:n}=t;return e.feature&&i?nk(i,e.feature):e.plan&&n?nk(n,e.plan):null})(e,t),n=((e,t)=>{let{orgId:i,orgRole:n,orgPermissions:r}=t;return(e.role||e.permission)&&i&&n&&r?e.permission?r.includes(e.permission.replace(/^(org:)*/,"org:")):e.role?n.replace(/^(org:)*/,"org:")===e.role.replace(/^(org:)*/,"org:"):null:null})(e,t),r=((e,{factorVerificationAge:t})=>{if(!e.reverification||!t)return null;let i=(e=>{let t,i;if(!e)return!1;let n="string"==typeof e&&nv.has(e),r="object"==typeof e&&(t=e.level,ny.has(t))&&"number"==typeof(i=e.afterMinutes)&&i>0;return(!!n||!!r)&&(e=>"string"==typeof e?nb[e]:e).bind(null,e)})(e.reverification);if(!i)return null;let{level:n,afterMinutes:r}=i(),[s,a]=t,o=-1!==s?r>s:null,l=-1!==a?r>a:null;switch(n){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||n,r].some(e=>null===e)?[i||n,r].some(e=>!0===e):[i||n,r].every(e=>!0===e)})(e)};#D=e=>{e&&iO.set({tokenId:this.#$(),tokenResolver:Promise.resolve(e)})};#$(e,t){let i=void 0===t?this.lastActiveOrganizationId:t;return iU.build(this.id,e,i)}startVerification=async({level:e})=>new nU((await tM._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:tk("Session.prepareFirstFactorVerification",e.strategy)}return new nU((await tM._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(iq(e.publicKeyCredential))}:{...e},new nU((await tM._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=nA.clerk.__internal_isWebAuthnSupported||nu,i=nA.clerk.__internal_getPublicCredentials||iB;if(!t())throw new C("Passkeys are not supported",{code:"passkey_not_supported"});let n=e?iK(JSON.parse(e)):null;n||tI("get");let{publicKeyCredential:r,error:s}=await i({publicKeyOptions:n,conditionalUI:!1});if(!r)throw s;return this.attemptFirstFactorVerification({strategy:"passkey",publicKeyCredential:r})};prepareSecondFactorVerification=async e=>new nU((await tM._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>new nU((await tM._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=tF(e.expire_at),this.abandonAt=tF(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=tF(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.createdAt=tF(e.created_at),this.updatedAt=tF(e.updated_at),this.user=new nB(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new nw(e.public_user_data)),this.lastActiveToken=e.last_active_token?new n$(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:n=!1}=e||{},r=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.#$(i,r),a=n?void 0:iO.get({tokenId:s},t),o=!i&&r===this.lastActiveOrganizationId;if(a){e5.debug("Using cached token (no fetch needed)",{tokenId:s},"session");let e=await a.tokenResolver;return o&&i6.emit(i3,{token:e}),e.getRawString()||null}e5.info("Fetching new token from API",{organizationId:r,template:i,tokenId:s},"session");let l=i?`${this.path()}/tokens/${i}`:`${this.path()}/tokens`,c=i?{}:{organizationId:r},d=n$.create(l,c,n);return iO.set({tokenId:s,tokenResolver:d}),d.then(e=>(o&&(i6.emit(i3,{token:e}),e.jwt&&(this.lastActiveToken=e,i6.emit(i5,null))),e.getRawString()||null))}get currentTask(){let[e]=this.tasks??[];return e}}class nI extends tM{pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}static retrieve(){let e=tM.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new nI(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=tF(e.expire_at),this.abandonAt=tF(e.abandon_at),this.lastActiveAt=tF(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 nC=(e,t,i)=>{let{onValidation:n=eQ,onValidationComplexity:r=eQ}=i||{},{show_zxcvbn:s,validatePassword:a}=t,o=e=>((e,t)=>{let{max_length:i,min_length:n,require_special_char:r,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:n})=>({max_length:e.length<n,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:n,require_special_char:r,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=>n=>{let r=i(n);return(t?.(r),r.score>=e&&r.score<3)?{state:"pass",keys:["unstable__errors.zxcvbn.couldBeStronger"],result:r}:r.score>=e?{state:"excellent",result:r}:{state:"fail",keys:["unstable__errors.zxcvbn.notEnough",...r.feedback.suggestions.map(e=>`unstable__errors.zxcvbn.suggestions.${e}`)],result:r}})(t),c={};return(t,i)=>{let{onValidation:d=n,onValidationComplexity:h=r}=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 nP(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function nT(e,t,i,n,r){if(!e.client||!n.popup)return;let s=nP(e.frontendApi),{redirectUrl:a}=n,o=new URL(a);o.searchParams.set("sign_in_force_redirect_url",n.redirectUrlComplete),o.searchParams.set("sign_up_force_redirect_url",n.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:n.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({...n,redirectUrlComplete:c,redirectUrl:d},r)}function nO(e,{redirectCallbackUrl:t,redirectUrl:i}){let n=nP(e.frontendApi),r=new URL(t);r.searchParams.set("sign_in_force_redirect_url",i),r.searchParams.set("sign_up_force_redirect_url",i);let s=e.buildUrlWithAuth(r.toString()),a=e.buildUrlWithAuth(`${n}/popup-callback`);return{redirectCallbackUrl:e.buildUrlWithAuth(`${n}/popup-callback?return_url=${encodeURIComponent(s)}`),redirectUrl:a}}function nE(e,t){return new Promise((i,n)=>{if(!e.client||!t.popup)return void n();let r=async t=>{t.origin===nP(e.frontendApi)&&(t.data.session||t.data.return_url?(window.removeEventListener("message",r),i()):n())};window.addEventListener("message",r),t.popup.location.href=t.externalVerificationRedirectURL.toString()})}async function nx(e,t){i6.emit("resource:error",{resource:e,error:null}),i6.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await t(),error:null}}catch(t){return i6.emit("resource:error",{resource:e,error:t}),{error:t}}finally{i6.emit("resource:fetch",{resource:e,status:"idle"})}}let nR=()=>{var e;return(e=new tt,{loadZxcvbn:()=>Promise.all([e.import("@zxcvbn-ts/core"),e.import("@zxcvbn-ts/language-common")]).then(([e,t])=>{if(!e||!t)throw Error("Failed to load zxcvbn modules");let{zxcvbnOptions:i,zxcvbn:n}=e,{dictionary:r,adjacencyGraphs:s}=t;return i.setOptions({dictionary:{...r},graphs:s}),n})}).loadZxcvbn};class nz extends tM{pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;firstFactorVerification=new iX(null);secondFactorVerification=new iX(null);identifier=null;createdSessionId=null;userData=new nJ(null);clientTrustState;get status(){return this._status}set status(e){let t=this._status;this._status=e,e&&t!==e&&e5.debug("SignIn.status",{id:this.id,from:t,to:e})}__internal_future=new nM(this);__internal_basePost=this._basePost.bind(this);__internal_baseGet=this._baseGet.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=e=>{e5.debug("SignIn.create",{id:this.id,strategy:"strategy"in e?e.strategy:void 0});let t=tc();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(e5.debug("SignIn.prepareFirstFactor",{id:this.id,strategy:e.strategy}),e.strategy){case"passkey":t={};break;case"email_link":t={emailAddressId:e.emailAddressId,redirectUrl:e.redirectUrl};break;case"email_code":case"reset_password_email_code":t={emailAddressId:e.emailAddressId};break;case"phone_code":t={phoneNumberId:e.phoneNumberId,default:e.default,channel:e.channel};break;case"web3_metamask_signature":case"web3_base_signature":case"web3_coinbase_wallet_signature":case"web3_okx_wallet_signature":case"web3_solana_signature":t={web3WalletId:e.web3WalletId};break;case"reset_password_phone_code":t={phoneNumberId:e.phoneNumberId};break;case"enterprise_sso":t={redirectUrl:e.redirectUrl,actionCompleteRedirectUrl:e.actionCompleteRedirectUrl,oidcPrompt:e.oidcPrompt,enterpriseConnectionId:e.enterpriseConnectionId};break;default:tk("SignIn.prepareFirstFactor",e.strategy)}return this._basePost({body:{...t,strategy:e.strategy},action:"prepare_first_factor"})};attemptFirstFactor=e=>{let t;return e5.debug("SignIn.attemptFirstFactor",{id:this.id,strategy:e.strategy}),t="passkey"===e.strategy?{publicKeyCredential:JSON.stringify(iq(e.publicKeyCredential))}:{...e},this._basePost({body:{...t,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:t}=iW();return{startEmailLinkFlow:async({emailAddressId:i,redirectUrl:n})=>{this.id||tv("SignIn");let r={strategy:"email_link",emailAddressId:i,redirectUrl:n},s="needs_second_factor"===this.status||"needs_client_trust"===this.status,a=s?"secondFactorVerification":"firstFactorVerification";return s?await this.prepareSecondFactor(r):await this.prepareFirstFactor(r),new Promise((i,n)=>{e(()=>this.reload().then(e=>{let n=e[a].status;("verified"===n||"expired"===n)&&(t(),i(e))}).catch(e=>{t(),n(e)}))})},cancelEmailLinkFlow:t}};prepareSecondFactor=e=>(e5.debug("SignIn.prepareSecondFactor",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_second_factor"}));attemptSecondFactor=e=>(e5.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:n,identifier:r,oidcPrompt:s,continueSignIn:a,enterpriseConnectionId:o}=e||{},l=nz.clerk.buildUrlWithAuth(e.redirectUrl);this.id&&a||await this.create({strategy:i,identifier:r,redirectUrl:l,actionCompleteRedirectUrl:n}),"enterprise_sso"===i&&await this.prepareFirstFactor({strategy:i,redirectUrl:l,actionCompleteRedirectUrl:n,oidcPrompt:s,enterpriseConnectionId:o});let{status:c,externalVerificationRedirectURL:d}=this.firstFactorVerification;"unverified"===c&&d?t(d):tA(c,nz.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eN);authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||tU("popup"),nT(nz.clerk,"signIn",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e.toString()})};authenticateWithWeb3=async e=>{let t,{identifier:i,generateSignature:n,strategy:r="web3_metamask_signature",walletName:s}=e||{},a=r.replace("web3_","").replace("_signature","");"function"!=typeof n&&tU("generateSignature"),"solana"!==a||s||tU("walletName"),await this.create({identifier:i});let o=this.supportedFirstFactors?.find(e=>e.strategy===r);o||tS("SignIn"),await this.prepareFirstFactor(o);let{message:l}=this.firstFactorVerification;l||tS("SignIn");try{t=await n({identifier:i,nonce:l,walletName:s,provider:a})}catch(e){if("coinbase_wallet"===a&&4001===e.code)t=await n({identifier:i,nonce:l,provider:a,walletName:s});else throw e}return this.attemptFirstFactor({signature:t,strategy:r})};authenticateWithMetamask=async()=>{let e=await tp().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tp().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await tp().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tp().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await tp().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tp().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await tp().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tp().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithSolana=async({walletName:e})=>{let t=await tp().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:t,generateSignature:t=>tp().generateSignatureWithSolana({...t,walletName:e}),strategy:"web3_solana_signature",walletName:e})};authenticateWithPasskey=async e=>{let{flow:t}=e||{},i=nz.clerk.__internal_isWebAuthnSupported||nu,n=nz.clerk.__internal_getPublicCredentials||iB,r=nz.clerk.__internal_isWebAuthnAutofillSupported||np;if(!i())throw new C("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(`${tw} 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?iK(JSON.parse(s)):null;a||tI("get");let o=!1;"autofill"===t&&(o=await r());let{publicKeyCredential:l,error:c}=await n({publicKeyOptions:a,conditionalUI:o});if(!l)throw c;return this.attemptFirstFactor({publicKeyCredential:l,strategy:"passkey"})};validatePassword=(e,t)=>{if(nz.clerk.__internal_environment?.userSettings.passwordSettings)return nC(nR(),{...nz.clerk.__internal_environment?.userSettings.passwordSettings,validatePassword:!0})(e,t)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.supportedIdentifiers=e.supported_identifiers,this.identifier=e.identifier,this.supportedFirstFactors=Y(e.supported_first_factors),this.supportedSecondFactors=Y(e.supported_second_factors),this.firstFactorVerification=new iX(e.first_factor_verification),this.secondFactorVerification=new iX(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new nJ(e.user_data),this.clientTrustState=e.client_trust_state??void 0),i6.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:X(this.supportedFirstFactors),supported_second_factors:X(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 nM{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(!r())return null;const e=eC("__clerk_status"),t=eC("__clerk_created_session");if(!e||!t)return null;const i="verified"===e&&void 0!==nz.clerk.client&&nz.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)};#L=!1;#j;constructor(e){this.#j=e}get id(){return this.#j.id}get identifier(){return this.#j.identifier}get createdSessionId(){return this.#j.createdSessionId}get userData(){return this.#j.userData}get status(){return this.#j.status||"needs_identifier"}get supportedFirstFactors(){return this.#j.supportedFirstFactors??[]}get supportedSecondFactors(){return this.#j.supportedSecondFactors??[]}get isTransferable(){return"transferable"===this.#j.firstFactorVerification.status}get existingSession(){if("failed"===this.#j.firstFactorVerification.status&&this.#j.firstFactorVerification.error?.code==="identifier_already_signed_in"&&this.#j.firstFactorVerification.error?.meta?.sessionId)return{sessionId:this.#j.firstFactorVerification.error?.meta?.sessionId}}get firstFactorVerification(){return this.#j.firstFactorVerification}get secondFactorVerification(){return this.#j.secondFactorVerification}get hasBeenFinalized(){return this.#L}async sendResetPasswordEmailCode(){if(!this.#j.id)throw Error("Cannot reset password without a sign in.");return nx(this.#j,async()=>{let e=this.#j.supportedFirstFactors?.find(e=>"reset_password_email_code"===e.strategy);if(!e)throw new A("Reset password email code factor not found",{code:"factor_not_found"});let{emailAddressId:t}=e;await this.#j.__internal_basePost({body:{emailAddressId:t,strategy:"reset_password_email_code"},action:"prepare_first_factor"})})}async verifyResetPasswordEmailCode(e){let{code:t}=e;return nx(this.#j,async()=>{await this.#j.__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 nx(this.#j,async()=>{await this.#j.__internal_basePost({body:{password:t,signOutOfOtherSessions:i},action:"reset_password"})})}async _create(e){let t=tc();await this.#j.__internal_basePost({path:this.#j.pathRoot,body:t?{locale:t,...e}:e})}async create(e){return nx(this.#j,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 nx(this.#j,async()=>{let t=e.identifier||e.emailAddress||e.phoneNumber,i=this.#j.identifier,n=tc();await this.#j.__internal_basePost({path:this.#j.pathRoot,body:{identifier:t||i,password:e.password,...n?{locale:n}:{}}})})}async sendEmailCode(e={}){let{emailAddress:t,emailAddressId:i}=e;if(!this.#j.id&&i)throw Error("signIn.emailCode.sendCode() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#j.id&&!t)throw Error("signIn.emailCode.sendCode() cannot be called without an emailAddress if an existing signIn does not exist.");return nx(this.#j,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_code",emailAddressId:i});if(!e)throw new A("Email code factor not found",{code:"factor_not_found"});await this.#j.__internal_basePost({body:{emailAddressId:e.emailAddressId,strategy:"email_code"},action:"prepare_first_factor"})})}async verifyEmailCode(e){let{code:t}=e;return nx(this.#j,async()=>{await this.#j.__internal_basePost({body:{code:t,strategy:"email_code"},action:"attempt_first_factor"})})}async sendEmailLink(e){let{emailAddress:t,verificationUrl:i,emailAddressId:n}=e;if(!this.#j.id&&n)throw Error("signIn.emailLink.sendLink() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#j.id&&!t)throw Error("signIn.emailLink.sendLink() cannot be called without an emailAddress if an existing signIn does not exist.");return nx(this.#j,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_link",emailAddressId:n});if(!e)throw new A("Email link factor not found",{code:"factor_not_found"});let r=i;try{new URL(i)}catch{r=window.location.origin+i}await this.#j.__internal_basePost({body:{emailAddressId:e.emailAddressId,redirectUrl:r,strategy:"email_link"},action:"prepare_first_factor"})})}async waitForEmailLinkVerification(){return nx(this.#j,async()=>{let{run:e,stop:t}=iW();await new Promise((i,n)=>{e(async()=>{try{let e=await this.#j.__internal_baseGet(),n=e.firstFactorVerification.status;("verified"===n||"expired"===n)&&(t(),i(e))}catch(e){t(),n(e)}})})})}async sendPhoneCode(e={}){let{phoneNumber:t,phoneNumberId:i,channel:n="sms"}=e;if(!this.#j.id&&i)throw Error("signIn.phoneCode.sendCode() cannot be called with an phoneNumberId if an existing signIn does not exist.");if(!this.#j.id&&!t)throw Error("signIn.phoneCode.sendCode() cannot be called without an phoneNumber if an existing signIn does not exist.");return nx(this.#j,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"phone_code",phoneNumberId:i});if(!e)throw new A("Phone code factor not found",{code:"factor_not_found"});await this.#j.__internal_basePost({body:{phoneNumberId:e.phoneNumberId,strategy:"phone_code",channel:n},action:"prepare_first_factor"})})}async verifyPhoneCode(e){let{code:t}=e;return nx(this.#j,async()=>{await this.#j.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_first_factor"})})}async sso(e){let{strategy:t,redirectUrl:i,redirectCallbackUrl:n,popup:r,oidcPrompt:s,enterpriseConnectionId:a,identifier:o}=e;return nx(this.#j,async()=>{let e=i;try{new URL(i)}catch{e=window.location.origin+i}let l={redirectUrl:nz.clerk.buildUrlWithAuth(n),actionCompleteRedirectUrl:e};if(r){let t=nO(nz.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.#j.__internal_basePost({body:{...l,oidcPrompt:s,enterpriseConnectionId:a,strategy:"enterprise_sso"},action:"prepare_first_factor"});let{status:c,externalVerificationRedirectURL:d}=this.#j.firstFactorVerification;"unverified"===c&&d&&(r?(await nE(nz.clerk,{popup:r,externalVerificationRedirectURL:d}),await this.#j.reload()):eN(d))})}async web3(e){let{strategy:t}=e,i=t.replace("web3_","").replace("_signature","");return nx(this.#j,async()=>{let n,r,s;switch(i){case"metamask":n=await tp().getMetamaskIdentifier(),r=tp().generateSignatureWithMetamask;break;case"coinbase_wallet":n=await tp().getCoinbaseWalletIdentifier(),r=tp().generateSignatureWithCoinbaseWallet;break;case"base":n=await tp().getBaseIdentifier(),r=tp().generateSignatureWithBase;break;case"okx_wallet":n=await tp().getOKXWalletIdentifier(),r=tp().generateSignatureWithOKXWallet;break;case"solana":if(!e.walletName)throw new A("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});n=await tp().getSolanaIdentifier(e.walletName),r=t=>tp().generateSignatureWithSolana({...t,walletName:e.walletName});break;default:throw Error(`Unsupported Web3 provider: ${i}`)}await this._create({identifier:n});let a=this.#j.supportedFirstFactors?.find(e=>e.strategy===t);if(!a)throw new A("Web3 first factor not found",{code:"factor_not_found"});await this.#j.__internal_basePost({body:{web3WalletId:a.web3WalletId,strategy:t},action:"prepare_first_factor"});let{message:o}=this.firstFactorVerification;if(!o)throw new A("Web3 nonce not found",{code:"web3_nonce_not_found"});try{s=await r({identifier:n,nonce:o,walletName:e?.walletName,provider:i})}catch(e){if("coinbase_wallet"===i&&4001===e.code)s=await r({identifier:n,nonce:o,provider:i});else throw e}await this.#j.__internal_basePost({body:{signature:s,strategy:t},action:"attempt_first_factor"})})}async passkey(e){let{flow:t}=e||{},i=nz.clerk.__internal_isWebAuthnSupported||nu,n=nz.clerk.__internal_getPublicCredentials||iB,r=nz.clerk.__internal_isWebAuthnAutofillSupported||np;if(!i())throw new C("Passkeys are not supported",{code:"passkey_not_supported"});return nx(this.#j,async()=>{if("autofill"===t||"discoverable"===t)await this._create({strategy:"passkey"});else{if(!this.supportedFirstFactors.find(e=>"passkey"===e.strategy))throw new A("Passkey factor not found",{code:"factor_not_found"});await this.#j.__internal_basePost({body:{strategy:"passkey"},action:"prepare_first_factor"})}let{nonce:e}=this.firstFactorVerification,i=e?iK(JSON.parse(e)):null;if(!i)throw new A("Missing public key options",{code:"missing_public_key_options"});let s=!1;"autofill"===t&&(s=await r());let{publicKeyCredential:a,error:o}=await n({publicKeyOptions:i,conditionalUI:s});if(!a)throw new C(o.message,{code:"passkey_retrieval_failed"});await this.#j.__internal_basePost({body:{publicKeyCredential:JSON.stringify(iq(a)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return nx(this.#j,async()=>{let e=this.#j.supportedSecondFactors?.find(e=>"phone_code"===e.strategy);if(!e)throw new A("Phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:t}=e;await this.#j.__internal_basePost({body:{phoneNumberId:t,strategy:"phone_code"},action:"prepare_second_factor"})})}async verifyMFAPhoneCode(e){let{code:t}=e;return nx(this.#j,async()=>{await this.#j.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_second_factor"})})}async verifyTOTP(e){let{code:t}=e;return nx(this.#j,async()=>{await this.#j.__internal_basePost({body:{code:t,strategy:"totp"},action:"attempt_second_factor"})})}async verifyBackupCode(e){let{code:t}=e;return nx(this.#j,async()=>{await this.#j.__internal_basePost({body:{code:t,strategy:"backup_code"},action:"attempt_second_factor"})})}async ticket(e){let t=e?.ticket??eC("__clerk_ticket");return this.create({ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};if(!this.#j.createdSessionId)throw Error("Cannot finalize sign-in without a created session.");return nx(this.#j,async()=>{nz.clerk.client&&!nz.clerk.client.sessions.some(e=>e.id===this.#j.createdSessionId)&&await nz.clerk.client.reload(),this.#L=!0,await nz.clerk.setActive({session:this.#j.createdSessionId,navigate:t})})}selectFirstFactor({strategy:e,emailAddressId:t,phoneNumberId:i}){if(!this.#j.supportedFirstFactors)return null;if(t){let i=this.#j.supportedFirstFactors.find(i=>i.strategy===e&&i.emailAddressId===t);if(i)return i}if(i){let t=this.#j.supportedFirstFactors.find(t=>t.strategy===e&&t.phoneNumberId===i);if(t)return t}let n=this.#j.supportedFirstFactors.find(t=>t.strategy===e&&t.safeIdentifier===this.#j.identifier);if(n)return n;let r=this.#j.supportedFirstFactors.find(t=>t.strategy===e);return r||null}}function nF(e){let{unsafeMetadata:t}={...e},i=t?"object"==typeof t?JSON.stringify(t):t:"";return{...e,...t?{unsafeMetadata:i}:{}}}class nN extends tM{pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new iQ(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&&e5.debug("SignUp.status",{id:this.id,from:t,to:e})}__internal_future=new nW(this);__internal_basePost=this._basePost.bind(this);__internal_basePatch=this._basePatch.bind(this);constructor(e=null){super(),this.fromJSON(e)}create=async e=>{e5.debug("SignUp.create",{id:this.id,strategy:e.strategy});let t={...e};if(!t.locale){let e=tc();e&&(t.locale=e)}if(!this.clientBypass()&&!this.shouldBypassCaptchaForAttempt(e)){let e=new tR(nN.clerk),i=await e.managedOrInvisible({action:"signup"});if(!i)throw new A("",{code:"captcha_unavailable"});t={...t,...i}}if(t.transfer&&this.shouldBypassCaptchaForAttempt(t)){let e=nN.clerk.client?.signIn.firstFactorVerification.strategy;e&&(t={...t,strategy:e})}return this._basePost({path:this.pathRoot,body:nF(t)})};prepareVerification=e=>(e5.debug("SignUp.prepareVerification",{id:this.id,strategy:e.strategy}),this._basePost({body:e,action:"prepare_verification"}));attemptVerification=e=>(e5.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}=iW();return{startEmailLinkFlow:async({redirectUrl:i})=>(this.id||tv("SignUp"),await this.prepareEmailAddressVerification({strategy:"email_link",redirectUrl:i}),new Promise((i,n)=>{e(()=>this.reload().then(e=>{let n=e.verifications.emailAddress.status;("verified"===n||"expired"===n)&&(t(),i(e))}).catch(e=>{t(),n(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:n,unsafeMetadata:r,strategy:s="web3_metamask_signature",legalAccepted:a,walletName:o}=e||{},l=s.replace("web3_","").replace("_signature","");"function"!=typeof i&&tU("generateSignature");let c=n||this.web3wallet;await this.create({web3Wallet:c,unsafeMetadata:r,legalAccepted:a}),await this.prepareWeb3WalletVerification({strategy:s});let{message:d}=this.verifications.web3Wallet;d||tS("SignUp");try{t=await i({identifier:n,nonce:d,provider:l,walletName:o})}catch(e){if("coinbase_wallet"===l&&4001===e.code)t=await i({identifier:n,nonce:d,provider:l});else throw e}return this.attemptWeb3WalletVerification({signature:t,strategy:s})};authenticateWithMetamask=async e=>{let t=await tp().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tp().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let t=await tp().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tp().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let t=await tp().getBaseIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tp().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let t=await tp().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tp().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithSolana=async({walletName:e,unsafeMetadata:t,legalAccepted:i})=>{let n=await tp().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:n,generateSignature:t=>tp().generateSignatureWithSolana({...t,walletName:e}),unsafeMetadata:t,strategy:"web3_solana_signature",legalAccepted:i,walletName:e})};authenticateWithRedirectOrPopup=async(e,t)=>{let{redirectUrl:i,redirectUrlComplete:n,strategy:r,continueSignUp:s=!1,unsafeMetadata:a,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:d}=e,h=nN.clerk.buildUrlWithAuth(i),u=()=>{let e={strategy:r,redirectUrl:h,actionCompleteRedirectUrl:n,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)&&P(e))return await nN.clerk.__internal_environment.reload(),u();throw e}),{externalAccount:f}=p,{status:m,externalVerificationRedirectURL:g}=f;"unverified"===m&&g?t(g):tA(m,nN.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eN);authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||tU("popup"),nT(nN.clerk,"signUp",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e instanceof URL?e.toString():e})};update=e=>this._basePatch({body:nF(e)});upsert=e=>this.id?this.update(e):this.create(e);validatePassword=(e,t)=>{if(nN.clerk.__internal_environment?.userSettings.passwordSettings)return nC(nR(),{...nN.clerk.__internal_environment?.userSettings.passwordSettings,validatePassword:!0})(e,t)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.requiredFields=e.required_fields,this.optionalFields=e.optional_fields,this.missingFields=e.missing_fields,this.unverifiedFields=e.unverified_fields,this.verifications=new iQ(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),i6.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 nN.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){if(!e.strategy)return!1;let t=nN.clerk.__internal_environment.displayConfig.captchaOauthBypass;return!!(t.some(t=>t===e.strategy)||e.transfer&&t.some(e=>e===nN.clerk.client.signIn.firstFactorVerification.strategy))}__experimental_getEnterpriseConnections=()=>tM._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new nD(e)))}class nW{verifications={sendEmailCode:this.sendEmailCode.bind(this),verifyEmailCode:this.verifyEmailCode.bind(this),sendPhoneCode:this.sendPhoneCode.bind(this),verifyPhoneCode:this.verifyPhoneCode.bind(this)};#L=!1;#j;constructor(e){this.#j=e}get id(){return this.#j.id}get requiredFields(){return this.#j.requiredFields}get optionalFields(){return this.#j.optionalFields}get missingFields(){return this.#j.missingFields}get status(){return this.#j.status||"missing_requirements"}get username(){return this.#j.username}get firstName(){return this.#j.firstName}get lastName(){return this.#j.lastName}get emailAddress(){return this.#j.emailAddress}get phoneNumber(){return this.#j.phoneNumber}get web3Wallet(){return this.#j.web3wallet}get hasPassword(){return this.#j.hasPassword}get unsafeMetadata(){return this.#j.unsafeMetadata}get createdSessionId(){return this.#j.createdSessionId}get createdUserId(){return this.#j.createdUserId}get abandonAt(){return this.#j.abandonAt}get legalAcceptedAt(){return this.#j.legalAcceptedAt}get locale(){return this.#j.locale}get unverifiedFields(){return this.#j.unverifiedFields}get isTransferable(){return"transferable"===this.#j.verifications.externalAccount.status&&this.#j.verifications.externalAccount.error?.code==="external_account_exists"}get existingSession(){if(("failed"===this.#j.verifications.externalAccount.status||"unverified"===this.#j.verifications.externalAccount.status)&&this.#j.verifications.externalAccount.error?.code==="identifier_already_signed_in"&&this.#j.verifications.externalAccount.error?.meta?.sessionId)return{sessionId:this.#j.verifications.externalAccount.error?.meta?.sessionId}}get hasBeenFinalized(){return this.#L}async getCaptchaToken(){let e=new tR(nN.clerk),t=await e.managedOrInvisible({action:"signup"});if(!t)throw Error("Captcha challenge failed");let{captchaError:i,captchaToken:n,captchaWidgetType:r}=t;return{captchaToken:n,captchaWidgetType:r,captchaError:i}}async _create(e){let{captchaToken:t,captchaWidgetType:i,captchaError:n}=await this.getCaptchaToken(),r={transfer:e.transfer,captchaToken:t,captchaWidgetType:i,captchaError:n,...e,unsafeMetadata:e.unsafeMetadata?nF(e.unsafeMetadata):void 0,locale:e.locale??tc()};await this.#j.__internal_basePost({path:this.#j.pathRoot,body:r})}async create(e){return nx(this.#j,async()=>{await this._create(e)})}async update(e){return nx(this.#j,async()=>{let t={...e,unsafeMetadata:e.unsafeMetadata?nF(e.unsafeMetadata):void 0};await this.#j.__internal_basePatch({path:this.#j.pathRoot,body:t})})}async password(e){return nx(this.#j,async()=>{let{captchaToken:t,captchaWidgetType:i,captchaError:n}=await this.getCaptchaToken(),r={strategy:"password",captchaToken:t,captchaWidgetType:i,captchaError:n,...e,unsafeMetadata:e.unsafeMetadata?nF(e.unsafeMetadata):void 0};await this.#j.__internal_basePost({path:this.#j.pathRoot,body:r})})}async sendEmailCode(){return nx(this.#j,async()=>{await this.#j.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification"})})}async verifyEmailCode(e){let{code:t}=e;return nx(this.#j,async()=>{await this.#j.__internal_basePost({body:{strategy:"email_code",code:t},action:"attempt_verification"})})}async sendPhoneCode(e){let{phoneNumber:t,channel:i="sms"}=e;return nx(this.#j,async()=>{if(!this.#j.id){let{captchaToken:e,captchaWidgetType:i,captchaError:n}=await this.getCaptchaToken();await this.#j.__internal_basePost({path:this.#j.pathRoot,body:{phoneNumber:t,captchaToken:e,captchaWidgetType:i,captchaError:n}})}await this.#j.__internal_basePost({body:{strategy:"phone_code",channel:i},action:"prepare_verification"})})}async verifyPhoneCode(e){let{code:t}=e;return nx(this.#j,async()=>{await this.#j.__internal_basePost({body:{strategy:"phone_code",code:t},action:"attempt_verification"})})}async sso(e){let{strategy:t,redirectUrl:i,redirectCallbackUrl:n,unsafeMetadata:r,legalAccepted:s,oidcPrompt:a,enterpriseConnectionId:o,emailAddress:l,popup:c}=e;return nx(this.#j,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:nN.clerk.buildUrlWithAuth(n),actionCompleteRedirectUrl:u};if(c){let e=nO(nN.clerk,{redirectCallbackUrl:p.redirectUrl,redirectUrl:u});p.redirectUrl=e.redirectCallbackUrl,p.actionCompleteRedirectUrl=e.redirectUrl}let f=()=>this.#j.__internal_basePost({path:this.#j.pathRoot,body:{strategy:t,...p,unsafeMetadata:r,legalAccepted:s,oidcPrompt:a,enterpriseConnectionId:o,emailAddress:l,captchaToken:e,captchaWidgetType:d,captchaError:h}});await f().catch(async e=>{if(O(e)&&P(e))return await nN.clerk.__internal_environment.reload(),f();throw e});let{status:m,externalVerificationRedirectURL:g}=this.#j.verifications.externalAccount;"unverified"===m&&g&&(c?(await nE(nN.clerk,{popup:c,externalVerificationRedirectURL:g}),await this.#j.reload()):eN(g))})}async web3(e){let{strategy:t,unsafeMetadata:i,legalAccepted:n}=e,r=t.replace("web3_","").replace("_signature","");return nx(this.#j,async()=>{let e,s,a;switch(r){case"metamask":e=await tp().getMetamaskIdentifier(),s=tp().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await tp().getCoinbaseWalletIdentifier(),s=tp().generateSignatureWithCoinbaseWallet;break;case"base":e=await tp().getBaseIdentifier(),s=tp().generateSignatureWithBase;break;case"okx_wallet":e=await tp().getOKXWalletIdentifier(),s=tp().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${r}`)}let o=e||this.#j.web3wallet;await this._create({web3Wallet:o,unsafeMetadata:i,legalAccepted:n}),await this.#j.__internal_basePost({body:{strategy:t},action:"prepare_verification"});let{message:l}=this.#j.verifications.web3Wallet;l||tS("SignUp");try{a=await s({identifier:e,nonce:l})}catch(t){if("coinbase_wallet"===r&&4001===t.code)a=await s({identifier:e,nonce:l});else throw t}await this.#j.__internal_basePost({body:{signature:a,strategy:t},action:"attempt_verification"})})}async ticket(e){let t=e?.ticket??eC("__clerk_ticket");return this.create({...e,ticket:t??void 0})}async finalize(e){let{navigate:t}=e||{};return nx(this.#j,async()=>{if(!this.#j.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#L=!0,await nN.clerk.setActive({session:this.#j.createdSessionId,navigate:t})})}}class nD extends tM{id;name;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name),this}}class n$ extends tM{pathRoot="tokens";jwt;static async create(e,t={},i=!1){return new n$(await tM._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=tl(e.jwt))}getRawString=()=>this.jwt?.claims.__raw||"";fromJSON(e){return e&&(this.jwt=tl(e.jwt)),this}__internal_toSnapshot(){return{object:"token",id:this.id||"",jwt:this.getRawString()}}}class nL extends tM{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=tF(e.updated_at),this.createdAt=tF(e.created_at)),this}}class nj extends tM{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=tF(e.updated_at),this.createdAt=tF(e.created_at)),this}}class nB extends tM{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 nB}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case iD:return this.primaryEmailAddressId===e.id;case ng:return this.primaryPhoneNumberId===e.id;case nG:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:t}=e||{};return new iD({email_address:t},this.path()+"/email_addresses/").create()};createPasskey=()=>nm.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:t}=e||{};return new ng({phone_number:t},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:t}=e||{};return new nG({web3_wallet:t},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:t,redirectUrl:i,additionalScopes:n}=e||{};return new ne((await tM._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:t,redirect_url:i,additional_scope:n}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new nL((await tM._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new nL((await tM._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new iR((await tM._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new nj((await tM._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);update=e=>this._basePatch({body:nF(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=>(i6.emit(i2,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await nI.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:t}=e||{};return null===t?nn.delete(`${this.path()}/profile_image`):nn.create(`${this.path()}/profile_image`,{file:t})};getOrganizationInvitations=e=>nK.retrieve(e);getOrganizationSuggestions=e=>nh.retrieve(e);getOrganizationMemberships=e=>nd.retrieve(e);leaveOrganization=async e=>new iR((await tM._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);initializePaymentMethod=e=>ip(e);addPaymentMethod=e=>im(e);getPaymentMethods=e=>ig(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 iD(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 ng(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 nG(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 ne(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new nm(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new nd(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new i0(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=tF(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=tF(e.legal_accepted_at)),this.updatedAt=tF(e.updated_at||void 0),this.createdAt=tF(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 nJ{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 nK extends tM{id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await tM._fetch({path:"/me/organization_invitations",method:"GET",search:t6(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new nK(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=tF(e.created_at),this.updatedAt=tF(e.updated_at)),this}}let nV={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 nq extends tM{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:{...nV,name:"phone_number"},username:{...nV,name:"username"},web3_wallet:{...nV,name:"web3_wallet"},first_name:{...nV,name:"first_name"},last_name:{...nV,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:{...nV,name:"authenticator_app"},backup_code:{...nV,name:"backup_code"},passkey:{...nV,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 nG extends tM{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 iX(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}class nH extends tM{pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=tF(e.updated_at),this.createdAt=tF(e.created_at)),this}static async join(e){return new nH((await tM._fetch({path:"/waitlist",method:"POST",body:e}))?.response)}}function nX(e,t){var i,n;return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||(i=t,n=e,i.organizationMemberships.length!==n.organizationMemberships.length||i.organizationMemberships[0]?.updatedAt!==n.organizationMemberships[0]?.updatedAt)}function nY(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(iE.isClientResource(e))return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.sessions.length!==t.sessions.length;if(nA.isSessionResource(e)){var i,n;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),n=t.user?.organizationMemberships?.find(t=>t.organization.id===e.lastActiveOrganizationId);return i?.permissions?.length!==n?.permissions?.length}(e,t)||(i=e,n=t,!!i.user!=!!n.user||!!i.user&&!!n.user&&nX(i.user,n.user))}if(nB.isUserResource(e))return nX(e,t)}catch{}return!0}(e,t)?e:t}let nQ="__clerk_db_jwt";function nZ(e,t){let i=new URL(e),n=i.searchParams.get(nQ);i.searchParams.delete(nQ);let r=n||t;return r&&i.searchParams.set(nQ,r),i}let n0=e=>{let t=new URL(e);return t.searchParams.delete(nQ),t},n1=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 n3(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var n in i)e[n]=i[n]}return e}var n2=function e(t,i){function n(e,n,r){if("undefined"!=typeof document){"number"==typeof(r=n3({},i,r)).expires&&(r.expires=new Date(Date.now()+864e5*r.expires)),r.expires&&(r.expires=r.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var s="";for(var a in r)r[a]&&(s+="; "+a,!0!==r[a]&&(s+="="+r[a].split(";")[0]));return document.cookie=e+"="+t.write(n,e)+s}}return Object.create({set:n,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var i=document.cookie?document.cookie.split("; "):[],n={},r=0;r<i.length;r++){var s=i[r].split("="),a=s.slice(1).join("=");try{var o=decodeURIComponent(s[0]);if(n[o]=t.read(a,o),e===o)break}catch(e){}}return e?n[e]:n}},remove:function(e,t){n(e,"",n3({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,n3({},this.attributes,t))},withConverter:function(t){return e(n3({},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 n4(e){return{get:()=>n2.get(e),set(t,i={}){n2.set(e,t,i)},remove(t){n2.remove(e,t)}}}let n5=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function n6(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 n8=n4("__clerk_test_etld"),n9="__client_uat",n7="__session",re=()=>{let e="None",t=n5(e);return{sameSite:e,secure:t,partitioned:t}};async function rt(e){let t;try{t=await el(e)}catch(o){var i;i=`Suffixed cookie failed due to ${o.message} (secure-context: ${window.isSecureContext}, url: ${window.location.href})`,B.has(i)||(console.log(i),B.add(i));let{default:n}=await Promise.all([s.e("545"),s.e("811")]).then(s.t.bind(s,180,23)),{default:r}=await Promise.all([s.e("545"),s.e("811")]).then(s.t.bind(s,3413,23)),a=n(e);t=r.stringify(a).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}return t}let ri=()=>{let e=!function(){if(!function(){if(!td())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=n5(e);return{sameSite:e,secure:t}};var rn=s(5945),rr=s.n(rn);class rs{lock=(function(e){let t=new(rr());return window.addEventListener("beforeunload",async()=>{await t.releaseLock(e)}),{acquireLockAndRun:async i=>{if("locks"in navigator&&isSecureContext){let t=new AbortController,n=setTimeout(()=>t.abort(),4999);return await navigator.locks.request(e,{signal:t.signal},async()=>(clearTimeout(n),await i())).catch(()=>!1)}if(await t.acquireLock(e,5e3))try{return await i()}finally{await t.releaseLock(e)}}}})("clerk.lock.refreshSessionToken");workerTimers=iN();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 ra{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,t,i,n){let r=await rt(e.publishableKey),s=new ra(e,t,r,i,n);return await s.setup(),s}constructor(e,t,n,r,s){this.clerk=e,this.instanceType=r,this.clerkEventBus=s,i6.on(i3,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),i6.on(i2,()=>this.handleSignOut()),this.refreshTokenOnFocus(),this.startPollingForToken(),this.clientUat=(e=>{let t=n4(n9),n=n4(ec(n9,e));return{set:e=>{let r=n6(Date.now(),1),s="None",a=n5(s),o=function(e=window.location.hostname,t=n8){if(i)return i;if(["localhost","127.0.0.1","0.0.0.0"].includes(e))return e;let n=e.split(".");if(1===n.length)return e;for(let e=n.length-2;e>=0;e--){let r=n.slice(e).join(".");if(t.set("1",{domain:r}),"1"===t.get())return t.remove({domain:r}),i=r,r;t.remove({domain:r})}}(),l="0";e&&e.updatedAt&&e.signedInSessions.length>0&&(l=Math.floor(e.updatedAt.getTime()/1e3).toString()),n.remove(),t.remove(),n.set(l,{domain:o,expires:r,partitioned:a,sameSite:s,secure:a}),t.set(l,{domain:o,expires:r,partitioned:a,sameSite:s,secure:a})},get:()=>parseInt(n.get()||t.get()||"0",10)}})(n),this.sessionCookie=(e=>{let t=n4(n7),i=n4(ec(n7,e)),n=()=>{let e=re();t.remove(e),i.remove(e)};return{set:e=>{let r=n6(Date.now(),1),{sameSite:s,secure:a,partitioned:o}=re();o&&n(),t.set(e,{expires:r,sameSite:s,secure:a,partitioned:o}),i.set(e,{expires:r,sameSite:s,secure:a,partitioned:o})},remove:n,get:()=>i.get()||t.get()}})(n),this.activeCookie=(()=>{let e=n4("clerk_active_context"),t={secure:n5("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 n,r,s=(n=n4(nQ),r=n4(ec(nQ,e)),{get:()=>r.get()||n.get(),set:e=>{let t=n6(Date.now(),1),{sameSite:i,secure:s}=ri();r.set(e,{expires:t,sameSite:i,secure:s}),n.set(e,{expires:t,sameSite:i,secure:s})},remove:()=>{let e=ri();r.remove(e),n.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 n;if(!ef(t))return;i.onBeforeRequest(e=>{let t=a();t&&e?.url&&(e.url=nZ(e.url,t))}),i.onAfterResponse((e,t)=>{let i=t?.headers?.get("Clerk-Db-Jwt");i&&o(i)});let r=(n=(e=new URL(window.location.href)).searchParams.get(nQ)||"",n0(n1(e)).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",n0(n1(e))),n);if(r)return void o(r);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 w(e)):[]}((await c.json()).errors);e[0]?tb(e[0].longMessage):tb()}let d=await c.json();o(d?.id)},getDevBrowserJWT:a,setDevBrowserJWT:o,removeDevBrowserJWT:l}}({frontendApi:e.frontendApi,fapiClient:t,cookieSuffix:n})}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(`${tw} Missing dev browser jwt. Please contact support.`);return nZ(e,t)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new rs,this.poller.startPollingForSessionToken(()=>this.refreshSessionToken()))}stopPollingForToken(){this.poller&&(this.poller.stopPollingForSessionToken(),this.poller=null)}refreshTokenOnFocus(){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()||e5.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)||E(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(T(e))return void this.clerk.handleUnauthenticated().catch(eQ);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(":"),n=this.clerk.session?.id||"",r=this.clerk.organization?.id||"";return t===n&&i===r}getSessionCookie(){return this.sessionCookie.get()}}class ro{clerk;captchaChallenge;timers;constructor(e,t=new tR(e),i=iN()){this.clerk=e,this.captchaChallenge=t,this.timers=i}async start(){this.isEnabled()&&(await this.challengeAndSend(),this.timers.setInterval(()=>{this.challengeAndSend()},this.intervalInMs()))}async challengeAndSend(){if(!(!this.clerk.client||this.clientBypass()))try{let e=await this.captchaChallenge.invisible({action:"heartbeat"});await this.clerk.client.__internal_sendCaptchaToken(e)}catch{}}isEnabled(){return!!this.clerk.__internal_environment?.displayConfig?.captchaHeartbeat}clientBypass(){return this.clerk.client?.captchaBypass}intervalInMs(){return this.clerk.__internal_environment?.displayConfig?.captchaHeartbeatIntervalMs??6e5}}let rl=["/client","/waitlist"];class rc{async getBaseFapiProxyOptions(){let e=await tM.clerk.session?.getToken();if(!e)throw new A("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 tM._fetch({...await this.getBaseFapiProxyOptions(),method:"GET",path:"/api_keys",search:t6({...e,subject:e?.subject??tM.clerk.organization?.id??tM.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new tN(e))}})}async create(e){return new tN(await tM._fetch({...await this.getBaseFapiProxyOptions(),path:"/api_keys",method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??tM.clerk.organization?.id??tM.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new tN(await tM._fetch({...await this.getBaseFapiProxyOptions(),method:"POST",path:`/api_keys/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let rd=new Map;class rh{#z=!1;load(e){let t=e?.protectConfig;if(t?.loaders&&Array.isArray(t.loaders)&&0!==t.loaders.length&&!this.#z){if(r())for(let e of(this.#z=!0,t.loaders))try{this.applyLoader(e)}catch(e){J(`[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 J(`[protect] loader rollout value is invalid: ${t}`);if(0===t||Math.random()>t)return}let t=e.type||"script",i=e.target||"body",n=document.createElement(t);if(e.attributes)for(let[t,i]of Object.entries(e.attributes))switch(typeof i){case"string":case"number":case"boolean":n.setAttribute(t,String(i));break;default:J(`[protect] loader attribute is invalid type: ${t}=${i}`)}switch(e.textContent&&"string"==typeof e.textContent&&(n.textContent=e.textContent),i){case"head":document.head.appendChild(n);break;case"body":document.body.appendChild(n);break;default:if(i?.startsWith("#")){let e=document.getElementById(i.substring(1));if(!e)return void J(`[protect] loader target element not found: ${i}`);e.appendChild(n);return}J(`[protect] loader target is invalid: ${i}`)}}}class ru{signInResourceSignal=t9;signInErrorSignal=t7;signInFetchSignal=ie;signInSignal=it;signUpResourceSignal=ii;signUpErrorSignal=ir;signUpFetchSignal=is;signUpSignal=ia;__internal_effect=tZ;__internal_computed=tQ;constructor(){i6.on("resource:update",this.onResourceUpdated),i6.on("resource:error",this.onResourceError),i6.on("resource:fetch",this.onResourceFetch)}onResourceError=e=>{e.resource instanceof nz&&this.signInErrorSignal({error:e.error}),e.resource instanceof nN&&this.signUpErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof nz){if(rp(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof nN){if(rp(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}};onResourceFetch=e=>{e.resource instanceof nz&&this.signInFetchSignal({status:e.status}),e.resource instanceof nN&&this.signUpFetchSignal({status:e.status})}}function rp(e,t){return!t?.id&&e&&e.__internal_future?.hasBeenFinalized===!1}let rf="cannot_render_billing_disabled",rm="cannot_render_user_missing",rg="cannot_render_organizations_disabled",r_="cannot_render_organization_missing",rw="cannot_render_single_session_enabled",rb={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 ry{static version="6.0.0-snapshot.v20251218183643";static sdkMetadata={name:"@clerk/clerk-js",version:"6.0.0-snapshot.v20251218183643"};static _billing;static _apiKeys;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new ru;internal_last_error=null;environment;#B;#J="";#K;#V;#q;#G;#H;#X=null;#Y;#Q;#Z;#ee="loading";#et=[];#ei=[];#en={};#er=null;#es=0;#ea=p();get __internal_queryClient(){return this.#B||Promise.all([s.e("662"),s.e("527")]).then(s.bind(s,250)).then(e=>e.QueryClient).then(e=>{this.#B||(this.#B=new e,this.#ea.emit("queryClientStatus","ready"))}),this.#B?{__tag:"clerk-rq-client",client:this.#B}:void 0}__internal_getCachedResources;__internal_createPublicCredentials;__internal_getPublicCredentials;__internal_isWebAuthnSupported;__internal_isWebAuthnAutofillSupported;__internal_isWebAuthnPlatformAuthenticatorSupported;__internal_setActiveInProgress=!1;get publishableKey(){return this.#J}get version(){return ry.version}set sdkMetadata(e){ry.sdkMetadata=e}get sdkMetadata(){return ry.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#ee}get isSatellite(){return!!td()&&eY(this.#en.isSatellite,new URL(window.location.href),!1)}get domain(){if(td()){let e=function(e=""){return(e||"").replace(/^.+:\/\//,"")}(eY(this.#K,new URL(window.location.href)));if("production"===this.#Z){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(td()){let e=eY(this.#V,new URL(window.location.href));return!e||eW(e)||eD(e)||ta.throwInvalidProxyUrl({url:e}),e?eD(e)?new URL(e,window.location.origin).toString():e:""}return""}get frontendApi(){let e=ea(this.publishableKey);return e?e.frontendApi:ta.throwInvalidPublishableKeyError({key:this.publishableKey})}get instanceType(){return this.#Z}get isStandardBrowser(){return this.#en.standardBrowser||!1}get billing(){return ry._billing||(ry._billing=new t8),ry._billing}get apiKeys(){return ry._apiKeys||(ry._apiKeys=new rc),ry._apiKeys}__experimental_checkout(e){return this._checkout||(this._checkout=e=>(function(e,t){let i,n,r,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:n,planPeriod:r}=e;return`${t}-${i||"user"}-${n}-${r}`}({userId:e.user?.id||"",orgId:"organization"===a?e.organization?.id:void 0,planId:o,planPeriod:l}),d=rd.get(c);if(d)return d.signals.computedSignal();let h=(i=tY({resource:null}),n=tY({error:null}),r=tY({status:"idle"}),s=tQ(()=>{let e=i().resource,t=n().error,s=r().status;return{errors:io(t,{}),fetchStatus:s,checkout:e}}),{resourceSignal:i,errorSignal:n,fetchSignal:r,computedSignal:s}),u=new id(h,{..."organization"===a?{orgId:e.organization?.id}:{},planId:o,planPeriod:l});return rd.set(c,{resource:u,signals:h}),h.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#en[e]}get isSignedIn(){return this?.session?.status!=="pending"&&!!this.session}constructor(e,t){if(!(e=(e||"").trim()))return ta.throwMissingPublishableKeyError();const i=ea(e);if(!i)return ta.throwInvalidPublishableKeyError({key:e});this.#K=t?.domain,this.#V=t?.proxyUrl,this.environment=i7.getInstance(),this.#Z=i.instanceType,this.#J=e,this.#Q=function(e){let t=[],i=[];async function n(e){for await(let i of["undefined"!=typeof window&&window.__internal_onBeforeRequest,...t].filter(e=>e))if(await i(e)===!1)return!1;return!0}async function r(e,t){for await(let n of["undefined"!=typeof window&&window.__internal_onAfterResponse,...i].filter(e=>e))if(await n(e,t)===!1)return!1;return!0}function s({method:t,path:i,sessionId:n,search:r,rotatingTokenNonce:s}){let a=new URLSearchParams(r);return a.append("__clerk_api_version","2025-11-10"),a.append("_clerk_js_version","6.0.0-snapshot.v20251218183643"),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&&!rl.some(e=>i.startsWith(e))&&n&&a.append("_clerk_session_id",n),eh([...a.entries()].reduce((e,[t,i])=>(e[t]=i.includes(",")?i.split(","):i,e),{}))}function a(t){let{path:i,pathPrefix:n="v1"}=t;if(e.proxyUrl){let r=new URL(e.proxyUrl),a=r.pathname.slice(1);return a.endsWith("/")&&(a=a.slice(0,-1)),e_({base:r.origin,pathname:`${a}/${n}${i}`,search:s(t)},{stringify:!1})}let r="production"===e.instanceType?e.domain:"";return e_({base:`https://${r||e.frontendApi}`,pathname:`${n}${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,n]of Object.entries(e))void 0!==n&&(t[i]=n);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?eh(d,{keyEncoder:G}):d);let h=await n(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();e5.error("network error",{error:t,url:e,method:c},"fapiClient");throw Error(`${tw} 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||e5.error("request failed",{method:c,path:o.path,status:s.status},"fapiClient"),await r(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.#ea.emit(f,"loading"),this.#ea.prioritizedOn(f,e=>this.#ee=e),tM.clerk=this,this.#G=new rh}getFapiClient=()=>this.#Q;load=async e=>{if(e5.info("load() start",{},"clerk"),!this.loaded){if("development"!==this.#Z||e?.unsafe_disableDevelopmentModeConsoleWarning||J("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.#en=this.#eo(e),this.#en.clerkUiCtor&&(this.#Y=Promise.resolve(this.#en.clerkUiCtor).then(e=>new e(()=>this,()=>this.environment,this.#en,new tt))),"development"===this.#Z&&(this.#en.routerPush||this.#en.routerReplace)&&(!this.#en.routerPush||!this.#en.routerReplace)){let e=this.#en.routerPush?"routerReplace":"routerPush";J(`Clerk: Both \`routerPush\` and \`routerReplace\` need to be defined, but \`${e}\` is not defined. This may cause issues with navigation in your application.`)}i6.on(i5,()=>{this.#el(this.session),this.#ec()}),this.#en.sdkMetadata&&(ry.sdkMetadata=this.#en.sdkMetadata),!1!==this.#en.telemetry&&(this.telemetry=new eJ({clerkVersion:ry.version,samplingRate:1,perEventSampling:!this.#en.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#en.telemetry}),this.#en.appearance&&this.telemetry.record({event:"THEME_USAGE",eventSamplingRate:1,payload:function(e){let t;if(!e||"object"!=typeof e)return{};let i=e.theme;if(!i)return{};if(Array.isArray(i))for(let e of i){let i=eX(e);if(i){t=i;break}}else t=eX(i);return{themeName:t}}(this.#en.appearance)}));try{this.#en.standardBrowser?await this.#ed():await this.#eh();let e=this.#en.telemetry,t=!1!==e&&!e?.disabled,i=!!this.#en.__internal_keyless_claimKeylessApplicationUrl,n=!!this.environment?.clientDebugMode,r=this.environment?.isProduction?.()??!1,s=n||i&&!r,a=i&&!n?"error":void 0;s&&function(e={}){if(e1)return;let{enabled:t=!1,...i}=e;t&&(eZ=!0,e1=!0,e4(i))}({enabled:!0,...a?{logLevel:a}:{},...t&&this.telemetry?{telemetryCollector:this.telemetry}:{}}),this.#G?.load(this.environment),e5.info("load() complete",{},"clerk")}catch(e){throw this.#ea.emit(f,"error"),e5.error("load() failed",{error:e},"clerk"),e}}};#eu(){let e;return!!(!this.#en.signUpUrl&&this.#en.signInUrl&&(e=this.#en.signInUrl,!ed.test(e)))}signOut=async(e,t)=>{if(!this.client||0===this.client.sessions.length)return;let i="undefined"!=typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:eQ,n="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:eQ,r=e&&"object"==typeof e?e:t||{},s=r?.redirectUrl||this.buildAfterSignOutUrl();e5.debug("signOut() start",{hasClient:!!this.client,multiSessionCount:this.client?.signedInSessions.length??0,redirectUrl:s,sessionTarget:r?.sessionId??null},"clerk");let a="function"==typeof e?e:void 0,o=async()=>{let e=ti(this.#en.standardBrowser);i6.emit(i2,null),this.#ep(),await e.track(async()=>{a?await a():await this.navigate(s)}),e.isUnloading()||(this.#el(),this.#ec(),await n())};if(await i(),!r.sessionId||1===this.client.signedInSessions.length){this.#en.experimental?.persistClient??!0?await this.client.removeSessions():await this.client.destroy(),await o(),e5.info("signOut() complete",{redirectUrl:ew(s)},"clerk");return}let l=this.client.signedInSessions.find(e=>e.id===r.sessionId),c=l?.id&&this.session?.id===l.id;await l?.remove(),c&&(await o(),e5.info("signOut() complete",{redirectUrl:ew(s)},"clerk"))};openGoogleOneTap=e=>{this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(t=>t.openModal("googleOneTap",e||{})),this.telemetry?.record(eH("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(R(this,this.environment)){if("development"===this.#Z)throw new A(ez.cannotOpenSignInOrSignUp,{code:rw});return}this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(t=>t.openModal("signIn",e||{}));let t={withSignUp:e?.withSignUp??this.#eu()};this.telemetry?.record(eH("SignIn",e,t))};closeSignIn=()=>{this.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(z(this,this.environment)){if("development"===this.#Z)throw new A(ez.cannotRenderAnyBillingComponent("Checkout"),{code:rf});return}if(!this.user){if("development"===this.#Z)throw new A(ez.cannotOpenCheckout,{code:rm});return}this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(t=>t.openDrawer("checkout",e||{}))};__internal_closeCheckout=()=>{this.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("checkout"))};__internal_openPlanDetails=e=>{if(z(this,this.environment)){if("development"===this.#Z)throw new A(ez.cannotRenderAnyBillingComponent("PlanDetails"),{code:rf});return}this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(t=>t.openDrawer("planDetails",e||{})),this.telemetry?.record(eH("PlanDetails",e))};__internal_closePlanDetails=()=>{this.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("planDetails"))};__internal_openSubscriptionDetails=e=>{this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(t=>t.openDrawer("subscriptionDetails",e||{}))};__internal_closeSubscriptionDetails=()=>{this.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("subscriptionDetails"))};__internal_openReverification=e=>{if(!this.user){if("development"===this.#Z)throw new A(ez.cannotOpenUserProfile,{code:rm});return}this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(t=>t.openModal("userVerification",e||{})),this.telemetry?.record(eH("UserVerification",e))};__internal_closeReverification=()=>{this.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userVerification"))};__internal_attemptToEnableEnvironmentSetting=e=>{let{for:t,caller:i}=e;if(this.user||"development"!==this.#Z||J(`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.#Z&&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.#Y),this.#Y.then(e=>e.ensureMounted({preloadHint:"EnableOrganizationsPrompt"})).then(t=>t.openModal("enableOrganizationsPrompt",e||{})),this.telemetry?.record(eG("EnableOrganizationsPrompt",e))};__internal_closeEnableOrganizationsPrompt=()=>{this.assertComponentsReady(this.#Y),this.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeModal("enableOrganizationsPrompt"))};__internal_openBlankCaptchaModal=()=>(this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(e=>e.openModal("blankCaptcha",{})));__internal_closeBlankCaptchaModal=()=>(this.assertComponentsReady(this.#Y),this.#Y.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(R(this,this.environment)){if("development"===this.#Z)throw new A(ez.cannotOpenSignInOrSignUp,{code:rw});return}this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(t=>t.openModal("signUp",e||{})),this.telemetry?.record(eH("SignUp",e))};closeSignUp=()=>{this.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signUp"))};openUserProfile=e=>{if(!this.user){if("development"===this.#Z)throw new A(ez.cannotOpenUserProfile,{code:rm});return}this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(t=>t.openModal("userProfile",e||{}));let t=(e?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(eH("UserProfile",e,t))};closeUserProfile=()=>{this.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userProfile"))};openOrganizationProfile=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new A(ez.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:rg})}});if(t){if(!this.organization){if("development"===this.#Z)throw new A(ez.cannotRenderComponentWhenOrgDoesNotExist,{code:r_});return}this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(t=>t.openModal("organizationProfile",e||{})),this.telemetry?.record(eH("OrganizationProfile",e))}};closeOrganizationProfile=()=>{this.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeModal("organizationProfile"))};openCreateOrganization=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new A(ez.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:rg})}});t&&(this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(t=>t.openModal("createOrganization",e||{})),this.telemetry?.record(eH("CreateOrganization",e)))};closeCreateOrganization=()=>{this.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeModal("createOrganization"))};openWaitlist=e=>{this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(t=>t.openModal("waitlist",e||{})),this.telemetry?.record(eH("Waitlist",e))};closeWaitlist=()=>{this.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeModal("waitlist"))};mountSignIn=(e,t)=>{this.assertComponentsReady(this.#Y);let i="SignIn";this.#Y.then(e=>e.ensureMounted()).then(n=>n.mountComponent({name:i,appearanceKey:"signIn",node:e,props:t}));let n={withSignUp:t?.withSignUp??this.#eu()};this.telemetry?.record(eG(i,t,n))};unmountSignIn=e=>{this.#Y?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserAvatar=(e,t)=>{this.assertComponentsReady(this.#Y);let i="UserAvatar";this.#Y.then(e=>e.ensureMounted()).then(n=>n.mountComponent({name:i,appearanceKey:"userAvatar",node:e,props:t})),this.telemetry?.record(eG(i,t))};unmountUserAvatar=e=>{this.#Y?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountSignUp=(e,t)=>{this.assertComponentsReady(this.#Y);let i="SignUp";this.#Y.then(e=>e.ensureMounted()).then(n=>n.mountComponent({name:i,appearanceKey:"signUp",node:e,props:t})),this.telemetry?.record(eG(i,t))};unmountSignUp=e=>{this.#Y?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserProfile=(e,t)=>{if(!this.user){if("development"===this.#Z)throw new A(ez.cannotRenderComponentWhenUserDoesNotExist,{code:rm});return}this.assertComponentsReady(this.#Y);let i="UserProfile";this.#Y.then(e=>e.ensureMounted()).then(n=>n.mountComponent({name:i,appearanceKey:"userProfile",node:e,props:t}));let n=(t?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(eG(i,t,n))};unmountUserProfile=e=>{this.#Y?.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 A(ez.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:rg})}});if(!i)return;let n=!!this.user;if(!this.organization&&n){if("development"===this.#Z)throw new A(ez.cannotRenderComponentWhenOrgDoesNotExist,{code:r_});return}this.assertComponentsReady(this.#Y);let r="OrganizationProfile";this.#Y.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:r,appearanceKey:"userProfile",node:e,props:t})),this.telemetry?.record(eG(r,t))};unmountOrganizationProfile=e=>{this.#Y?.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 A(ez.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:rg})}});if(!i)return;this.assertComponentsReady(this.#Y);let n="CreateOrganization";this.#Y.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:n,appearanceKey:"createOrganization",node:e,props:t})),this.telemetry?.record(eG(n,t))};unmountCreateOrganization=e=>{this.#Y?.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 A(ez.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:rg})}});if(!i)return;this.assertComponentsReady(this.#Y);let n="OrganizationSwitcher";this.#Y.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:n,appearanceKey:"organizationSwitcher",node:e,props:t})),this.telemetry?.record(eG(n,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationSwitcher=e=>{this.#Y?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__experimental_prefetchOrganizationSwitcher=()=>{this.assertComponentsReady(this.#Y),this.#Y.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 A(ez.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:rg})}});if(!i)return;this.assertComponentsReady(this.#Y);let n="OrganizationList";this.#Y.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:n,appearanceKey:"organizationList",node:e,props:t})),this.telemetry?.record(eG(n,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationList=e=>{this.#Y?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserButton=(e,t)=>{this.assertComponentsReady(this.#Y);let i="UserButton";this.#Y.then(e=>e.ensureMounted()).then(n=>n.mountComponent({name:i,appearanceKey:"userButton",node:e,props:t}));let n={...t?.customMenuItems?.length||0?{customItems:!0}:void 0,...t?.__experimental_asStandalone?{standalone:!0}:void 0};this.telemetry?.record(eG(i,t,n))};unmountUserButton=e=>{this.#Y?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountWaitlist=(e,t)=>{this.assertComponentsReady(this.#Y);let i="Waitlist";this.#Y.then(e=>e.ensureMounted()).then(n=>n.mountComponent({name:i,appearanceKey:"waitlist",node:e,props:t})),this.telemetry?.record(eG(i,t))};unmountWaitlist=e=>{this.#Y?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountPricingTable=(e,t)=>{if(z(this,this.environment)){if("development"===this.#Z)throw new A(ez.cannotRenderAnyBillingComponent("PricingTable"),{code:rf});return}this.assertComponentsReady(this.#Y);let i="PricingTable";this.#Y.then(e=>e.ensureMounted()).then(n=>n.mountComponent({name:i,appearanceKey:"pricingTable",node:e,props:t})),this.telemetry?.record(eG(i,t))};unmountPricingTable=e=>{this.#Y?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__internal_mountOAuthConsent=(e,t)=>{this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:"OAuthConsent",appearanceKey:"__internal_oauthConsent",node:e,props:t}))};__internal_unmountOAuthConsent=e=>{this.#Y?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountAPIKeys=(e,t)=>{let i;if(J("Clerk: <APIKeys /> component is in early access and not yet recommended for production use."),M(this,i=this.environment)&&F(this,i)){if("development"===this.#Z)throw new A(ez.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&F(this,this.environment)){if("development"===this.#Z)throw new A(ez.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if(M(this,this.environment)){if("development"===this.#Z)throw new A(ez.cannotRenderAPIKeysComponentForUserWhenDisabled,{code:"cannot_render_api_keys_user_disabled"});return}this.assertComponentsReady(this.#Y);let n="APIKeys";this.#Y.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:n,appearanceKey:"apiKeys",node:e,props:t})),this.telemetry?.record(eG(n,t))};unmountAPIKeys=e=>{this.#Y?.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 A(ez.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:rg})}});if(!i)return;this.assertComponentsReady(this.#Y);let n="TaskChooseOrganization";this.#Y.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:n,appearanceKey:"taskChooseOrganization",node:e,props:t})),this.telemetry?.record(eG(n,t))};unmountTaskChooseOrganization=e=>{this.#Y?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskResetPassword=(e,t)=>{this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:"TaskResetPassword",appearanceKey:"taskResetPassword",node:e,props:t})),this.telemetry?.record(eG("TaskResetPassword",t))};unmountTaskResetPassword=e=>{this.#Y?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};setActive=async e=>{let{organization:t,redirectUrl:i,navigate:n}=e,{session:r}=e;this.__internal_setActiveInProgress=!0,e5.debug("setActive() start",{hasClient:!!this.client,sessionTarget:"string"==typeof r?r:r?.id??r??null,organizationTarget:"string"==typeof t?t:t?.id??t??null,redirectUrl:i??null},"clerk");try{var s;let a;if(!this.client)throw e5.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===r&&!this.session)throw e5.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 r&&(r=this.client.sessions.find(e=>e.id===r)||null);let o="undefined"!=typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:eQ,l="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:eQ,d=void 0===r?this.session:r;d?.status==="pending"&&(s={...this.#en,...e},a=["taskUrls","navigate"],Object.keys(s).some(e=>a.includes(e))||J('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,n=null===i;if(this.environment?.organizationSettings?.forceOrganizationSelection&&n)return;d.lastActiveOrganizationId=i}}d?.status!=="pending"&&await o(null===d?"sign-out":void 0),(td()&&globalThis.document.hasFocus()||!this.#en.standardBrowser)&&(await this.#ef(d),d=this.#em(d?.id)),await d?.getToken()||(c()||e5.warn("Token is null when setting active session (offline)",{sessionId:d?.id},"clerk"),i6.emit(i3,{token:null}));let u=ti(this.#en.standardBrowser),p=d?.status==="pending"&&d?.currentTask&&this.#en.taskUrls?.[d?.currentTask.key];if((i||p||n)&&await u.track(async()=>{if(this.client){if(d?.status!=="pending"&&this.#ep(),p){let e=i?e_({base:p,hashSearchParams:{redirectUrl:i}},{stringify:!0}):p;await this.navigate(e)}else if(n&&d)await n({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.#el(d),this.#ec(),d?.status!=="pending"&&await l()}finally{this.__internal_setActiveInProgress=!1}};addListener=e=>{var t;let i;return t=e,e=e=>{var n;i||={...e},t(i={...{client:nY((n=i).client,e.client),session:nY(n.session,e.session),user:nY(n.user,e.user),organization:nY(n.organization,e.organization)}})},this.#et.push(e),this.client&&e({client:this.client,session:this.session,user:this.user,organization:this.organization}),()=>{this.#et=this.#et.filter(t=>t!==e)}};on=(...e)=>{this.#ea.on(...e)};off=(...e)=>{this.#ea.off(...e)};__internal_addNavigationListener=e=>(this.#ei.push(e),()=>{this.#ei=this.#ei.filter(t=>t!==e)});navigate=async(e,t)=>{if(!e||!td())return;setTimeout(()=>{this.#eg()},0);let i=new URL(e,window.location.href);this.#e_.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 n=t?.replace&&this.#en.routerReplace?this.#en.routerReplace:this.#en.routerPush;if(e5.info(`Clerk is navigating to: ${i}`),this.#en.routerDebug&&console.log(`Clerk is navigating to: ${i}`),"null"!==i.origin&&i.origin!==window.location.origin||!n)return void eN(i);let r={...t?.metadata?{__internal_metadata:t?.metadata}:{},windowNavigate:eN};return await n(ew(i),r)};buildUrlWithAuth(e){if("production"===this.#Z)return e;let t=new URL(e,window.location.origin);return t.origin!==window.location.origin&&this.#q?this.#q.decorateUrlWithDevBrowserToken(t).href:t.href}buildSignInUrl(e){return this.#ew("signInUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildSignUpUrl(e){return this.#ew("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 eU(this.#en,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eU(this.#en,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#en.afterSignOutUrl?this.buildUrlWithAuth(this.#en.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#en.newSubscriptionRedirectUrl?this.#en.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?e_({base:this.#en.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#en.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#en.afterMultiSessionSingleSignOutUrl):this.#en.signInUrl?this.buildUrlWithAuth(e_({base:this.#en.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.#en.taskUrls?.[t.key];return i||e_({base:this.buildSignInUrl(e),hashPath:eE(t)},{stringify:!0})}#eb=async()=>{if(!td())return;let e=new URLSearchParams({[N]:"true"}),t=eC(D);t&&eW(t)||function(){throw Error(`${tw} Invalid redirect_url. A valid http or https url should be used for the redirection.`)}();let i=e_({base:eC(D),searchParams:e},{stringify:!0});return this.navigate(this.buildUrlWithAuth(i))};redirectWithAuth=async e=>{if(td())return this.navigate(this.buildUrlWithAuth(e))};redirectToSignIn=async e=>{if(td())return this.navigate(this.buildSignInUrl(e))};redirectToSignUp=async e=>{if(td())return this.navigate(this.buildSignUpUrl(e))};redirectToUserProfile=async()=>{if(td())return this.navigate(this.buildUserProfileUrl())};redirectToCreateOrganization=async()=>{if(td())return this.navigate(this.buildCreateOrganizationUrl())};redirectToOrganizationProfile=async()=>{if(td())return this.navigate(this.buildOrganizationProfileUrl())};redirectToAfterSignIn=async()=>{if(td())return this.navigate(this.buildAfterSignInUrl())};redirectToAfterSignUp=async()=>{if(td())return this.navigate(this.buildAfterSignUpUrl())};redirectToAfterSignOut=async()=>{if(td())return this.navigate(this.buildAfterSignOutUrl())};redirectToWaitlist=async()=>{if(td())return this.navigate(this.buildWaitlistUrl())};redirectToTasks=async e=>{if(td())return this.navigate(this.buildTasksUrl(e))};handleEmailLinkVerification=async(e,t)=>{if(!this.client)return;let i=eC("__clerk_status");if("expired"===i)throw new U("expired");if("client_mismatch"===i)throw new U("client_mismatch");if("verified"!==i)throw new U("failed");let n=eC("__clerk_created_session"),{signIn:r,signUp:s,sessions:a}=this.client,o=a.some(e=>e.id===n),l="needs_second_factor"===r.status||"missing_requirements"===s.status,c=e=>t&&"function"==typeof t?t(e):this.navigate(e),d=e.redirectUrl?()=>c(e.redirectUrl):eQ;return o?this.setActive({session:n,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:n,signUp:r}=this.client,s="identifier"in(e||{})?e:n,a="missingFields"in(e||{})?e:r,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:n})=>{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:r}=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=>()=>n(e),d=c(e.signInUrl||r.signInUrl),h=c(e.signUpUrl||r.signUpUrl),u=c(e.firstFactorUrl||e_({base:r.signInUrl,hashPath:"/factor-one"},{stringify:!0})),p=c(e.secondFactorUrl||e_({base:r.signInUrl,hashPath:"/factor-two"},{stringify:!0})),f=c(e.resetPasswordUrl||e_({base:r.signInUrl,hashPath:"/reset-password"},{stringify:!0})),m=new eU(this.#en,e),g=c(e.continueSignUpUrl||e_({base:r.signUpUrl,hashPath:"/continue"},{stringify:!0})),_=({missingFields:t})=>t.length?g():(({signUp:e,verifyEmailPath:t,verifyPhonePath:i,continuePath:n,navigate:r,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=eT();if(e.unverifiedFields?.includes("email_address")&&t)return r(t,{searchParams:s});if(e.unverifiedFields?.includes("phone_number")&&i)return r(i,{searchParams:s});if(n)return r(n,{searchParams:s})}})({signUp:i,verifyEmailPath:e.verifyEmailAddressUrl||e_({base:r.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),verifyPhonePath:e.verifyPhoneNumberUrl||e_({base:r.signUpUrl,hashPath:"/verify-phone-number"},{stringify:!0}),navigate:n}),w=e.signInUrl||r.signInUrl,b=e.signUpUrl||r.signUpUrl,y=async({session:e,baseUrl:t,redirectUrl:i})=>{e.currentTask?await ex(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 y({session:e,baseUrl:w,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 y({session:e,baseUrl:b,redirectUrl:m.getAfterSignInUrl()})}});case"needs_first_factor":return u();case"needs_second_factor":return p();case"needs_new_password":return f();default:ty("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 y({session:e,baseUrl:b,redirectUrl:m.getAfterSignUpUrl()})}});case"missing_requirements":return _({missingFields:t.missingFields});default:ty("sign in")}}if("complete"===o.status)return this.setActive({session:o.sessionId,navigate:async({session:e})=>{await y({session:e,baseUrl:b,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 y({session:e,baseUrl:S?b:w,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:n}=this.client,r=e=>t&&"function"==typeof t?t(e):this.navigate(e);return this._handleRedirectCallback(e,{signUp:n,signIn:i,navigate:r})};handleUnauthenticated=async(e={broadcast:!0})=>{if(this.client&&this.session)try{let t=await iE.getOrCreateInstance().fetch();if(this.updateClient(t),this.session)return;return e.broadcast&&i6.emit(i2,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"})};authenticateWithSolana=async e=>{await this.authenticateWithWeb3({...e,strategy:"web3_solana_signature"})};authenticateWithWeb3=async({redirectUrl:e,signUpContinueUrl:t,customNavigate:i,unsafeMetadata:n,strategy:r,legalAccepted:s,secondFactorUrl:a,walletName:o})=>{let l,c;if(!this.client||!this.environment)return;let{displayConfig:d}=this.environment,h=r.replace("web3_","").replace("_signature",""),u=await tp().getWeb3Identifier({provider:h,walletName:o});switch(h){case"metamask":l=tp().generateSignatureWithMetamask;break;case"base":l=tp().generateSignatureWithBase;break;case"coinbase_wallet":l=tp().generateSignatureWithCoinbaseWallet;break;case"solana":if(!o)throw new A("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});l=e=>tp().generateSignatureWithSolana({...e,walletName:o});break;default:l=tp().generateSignatureWithOKXWallet}let p=e=>()=>i&&"function"==typeof i?i(e):this.navigate(e),f=p(a||e_({base:d.signInUrl,hashPath:"/factor-two"},{stringify:!0})),m=p(t||e_({base:d.signUpUrl,hashPath:"/continue"},{stringify:!0}));try{c=await this.client.signIn.authenticateWithWeb3({identifier:u,generateSignature:l,strategy:r,walletName:o})}catch(e){if(ts(e,"form_identifier_not_found"))c=await this.client.signUp.authenticateWithWeb3({identifier:u,generateSignature:l,unsafeMetadata:n,strategy:r,legalAccepted:s,walletName:o}),t&&"missing_requirements"===c.status&&"verified"===c.verifications.web3Wallet.status&&await m();else throw e}let g=async({session:e,redirectUrl:t})=>{e.currentTask?await ex(e,{baseUrl:d.signInUrl,navigate:this.navigate}):await this.navigate(t)};switch(c.status){case"needs_second_factor":await f();break;case"complete":c.createdSessionId&&await this.setActive({session:c.createdSessionId,navigate:async({session:t})=>{await g({session:t,redirectUrl:e??this.buildAfterSignInUrl()})}});break;default:return}};createOrganization=async({name:e,slug:t})=>nl.create({name:e,slug:t});getOrganization=async e=>nl.get(e);joinWaitlist=async({emailAddress:e})=>nH.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.#en.selectInitialSession?this.#en.selectInitialSession(e):this.#ey(e);this.#el(t)}if(this.client=e,this.session){let e=this.#em(this.session.id);"active"===this.session.status&&e?.status==="pending"&&("undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:eQ)(),this.#el(e),this.session?.lastActiveToken||c()||e5.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),i6.emit(i3,{token:this.session?.lastActiveToken})}this.#ec()};get __internal_environment(){return this.environment}__internal_setEnvironment=async e=>{this.environment=new i7(e)};__internal_onBeforeRequest=e=>{this.#Q.onBeforeRequest(e)};__internal_onAfterResponse=e=>{this.#Q.onAfterResponse(e)};__internal_updateProps=e=>{let t={...e,options:this.#eo({...this.#en,...e.options})};return this.#Y?.then(e=>e.ensureMounted()).then(e=>e.updateProps(t))};__internal_navigateWithError(e,t){return this.__internal_last_error=t,this.navigate(e)}#ev=()=>{let e=new URLSearchParams({[D]:window.location.href});return e_({base:this.#en.signInUrl,searchParams:e},{stringify:!0})};#ek=()=>{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()||""};#eS=()=>"true"!==eC(N)&&!!this.isSatellite&&!!this.#q?.isSignedOut();#eU=()=>"production"!==this.#Z&&!this.isSatellite&&!!eC(D);#eA=async()=>{"development"===this.instanceType?await this.navigate(this.#ev()):"production"===this.instanceType&&await this.navigate(this.#ek())};#eI=(e,t)=>{let i;try{i=new URL(e)}catch{throw Error(`${tw} The signInUrl needs to have a absolute url format.`)}i.origin===t&&function(){throw Error(`${tw} The signInUrl needs to be on a different origin than your satellite application.`)}()};#eC=()=>{this.isSatellite&&("development"!==this.#Z||this.#en.signInUrl||function(){throw Error(`${tw} Missing signInUrl. A satellite application needs to specify the signInUrl for development instances.`)}(),this.proxyUrl||this.domain||function(){throw Error(`${tw} Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl.`)}(),this.#en.signInUrl&&this.#eI(this.#en.signInUrl,window.location.origin))};#ed=async()=>{if(this.#q=await ra.create(this,this.#Q,this.#Z,this.#ea),this.#eC(),this.#eS())return void await this.#eA();if(this.#eU())return void await this.#eb();this.#er=(()=>{if(!r())return{onPageFocus:eQ};let e=[];return window.addEventListener("focus",()=>{"visible"===document.visibilityState&&e.forEach(e=>e())}),{onPageFocus:t=>{e.push(t)}}})(),"undefined"!=typeof BroadcastChannel&&(this.#X=new BroadcastChannel("clerk")),this.#eP();let e=function(e=window.location.hostname){if(!e)return!1;let t=em.get(e);void 0===t&&(t=ee.some(t=>e.startsWith("accounts.")&&e.endsWith(t))||et.some(t=>e.endsWith(t)&&!e.endsWith(".clerk"+t)),em.set(e,t));return t}(window?.location.hostname),t="development"===this.#Z&&!e,i=0,n=0;for(;n<2;){n++;try{var s;let e=i7.getInstance().fetch({touch:t}).then(e=>this.updateEnvironment(e)).catch(()=>{++i;let e=t_.getItem(tf,null);e&&this.updateEnvironment(new i7(e))}),n=async()=>iE.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(async e=>{if(T(e))throw e;++i;let t=this.#q?.getSessionCookie(),n=function(e){let t;try{t=new n$({jwt:e||"",object:"token",id:void 0})}catch{t=null}if(iE.clearInstance(),!t?.jwt)return iE.getOrCreateInstance({object:"client",last_active_session_id:null,id:"client_init",sessions:[]});let{sessionId:i,userId:n,orgId:r,orgRole:s,orgPermissions:a,orgSlug:o,factorVerificationAge:l}=(e=>{let t,i,n,r,s=e.fva??null,a=e.sts??null;if(2===e.v){if(e.o){t=e.o?.id,n=e.o?.slg,e.o?.rol&&(i=`org:${e.o?.rol}`);let{org:s}=nS(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});r=function({features:e,permissions:t,featurePermissionMap:i}){if(!e||!t||!i)return[];let n=[];for(let r=0;r<e.length;r++){let s=e[r];if(r>=i.length)continue;let a=i[r];if(a)for(let e=0;e<a.length;e++)1===a[e]&&n.push(`org:${s}:${t[e]}`)}return n}({features:s,featurePermissionMap:o,permissions:a})}}else t=e.org_id,i=e.org_role,n=e.org_slug,r=e.org_permissions;return{sessionClaims:e,sessionId:e.sid,sessionStatus:a,actor:e.act,userId:e.sub,orgId:t,orgRole:i,orgSlug:n,orgPermissions:r,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:r||null,last_active_token:{id:void 0,object:"token",jwt:e},factor_verification_age:l||null,public_user_data:{user_id:n},user:{object:"user",id:n,organization_memberships:r&&o&&s?[{object:"organization_membership",id:r,role:s,permissions:a||[],organization:{object:"organization",id:r,name:o,slug:o,members_count:1,max_allowed_memberships:1}}]:[]}}]};return iE.getOrCreateInstance(c)}(t);return this.updateClient(n),this.#q?.stopPollingForToken(),await this.session?.getToken({skipCache:!0}).catch(()=>null).finally(()=>{this.#q?.startPollingForToken()}),null}),[,r]=await (s=[e,n()],Promise.all(Array.from(s).map(e=>e.then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e})))));if("rejected"===r.status){let e=r.reason;if(ts(e,"requires_captcha"))await n();else throw e}if(this.#q?.setClientUatCookieForDevelopmentInstances(),await this.#eT())return;break}catch(e){if(ts(e,"dev_browser_unauthenticated"))await this.#q.handleUnauthenticatedDevBrowser();else if(!c())return void console.warn(e);else throw e}n>=2&&function(){throw Error(`${tw} Something went wrong initializing Clerk.`)}()}this.#H=new ro(this),this.#H.start(),this.#eO(),this.#eE(),this.#ex(),this.#ea.emit(f,i>0?"degraded":"ready")};shouldFallbackToCachedResources=()=>!!this.__internal_getCachedResources;#eh=async()=>{let e,t,i=this.shouldFallbackToCachedResources()?1:void 0,n=0;try{[e,t]=await Promise.all([i7.getInstance().fetch({touch:!1,fetchMaxTries:i}),iE.getOrCreateInstance().fetch({fetchMaxTries:i})])}catch(i){if(E(i)&&"network_error"===i.code&&this.shouldFallbackToCachedResources()){let i=await this.__internal_getCachedResources?.();e=new i7(i?.environment),iE.clearInstance(),t=iE.getOrCreateInstance(i?.client),++n}else throw i}this.updateClient(t),this.updateEnvironment(e),this.#ea.emit(f,n>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,t]=await Promise.all([i7.getInstance().fetch({touch:!1,fetchMaxTries:1}),iE.getOrCreateInstance().fetch({fetchMaxTries:1})]);this.updateClient(t),this.updateEnvironment(e),this.#ec()};#ey=e=>{if(e.lastActiveSessionId){let t=e.signedInSessions.find(t=>t.id===e.lastActiveSessionId);if(t)return t}return e.signedInSessions[0]||null};#eP=()=>{r()&&(this.#er?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#es>Date.now())&&(this.#es=Date.now()+5e3,this.#en.touchSession&&this.#ef(this.session))}),this.#X?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),i6.on(i2,()=>{this.#X?.postMessage({type:"signout"})}),i6.on(i4,()=>{t_.setItem(tf,this.environment?.__internal_toSnapshot(),864e5)}))};#ef=async e=>{if(!e)return Promise.resolve();await e.touch().catch(e=>{T(e)&&this.handleUnauthenticated()})};#ec=()=>{if(this.client)for(let e of this.#et)e({client:this.client,session:this.session,user:this.user,organization:this.organization})};#eg=()=>{for(let e of this.#ei)e()};#ep=()=>{this.session=void 0,this.organization=void 0,this.user=void 0,this.#ec()};#eR=()=>(this.session?.user.organizationMemberships||[]).map(e=>e.organization).find(e=>e.id===this.session?.lastActiveOrganizationId)||null;#el=e=>{this.session=e||null,this.organization=this.#eR(),this.user=this.session?this.session.user:null};#em=e=>this.client?.signedInSessions.find(t=>t.id===e)||null;#eE=()=>{this.addListener(({session:e})=>{e?.actor&&this.#Y?.then(e=>e.ensureMounted()).then(e=>e.mountImpersonationFab())})};#ex=()=>{this.#en.__internal_keyless_claimKeylessApplicationUrl&&this.#Y?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#en.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#en.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#en.__internal_keyless_dismissPrompt}})})};#ew=(e,t,i)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let n=this.#en[e]||this.environment.displayConfig[e];this.#eu()&&(n=this.#en.signInUrl);let r=new eU(this.#en,t).toSearchParams(),s=new URLSearchParams(i||{}),a=e_({base:n,hashPath:this.#eu()&&"signUpUrl"===e?"/create":"",hashSearchParams:[s,r]},{stringify:!0});return this.buildUrlWithAuth(a)};assertComponentsReady(e){if(!e)throw Error("Clerk was not loaded with Ui components")}#eT=async()=>{var e;let t,i,n,r,s=new URLSearchParams(window.location.search).get("redirect_url"),a="production"===this.instanceType,o=null!==s&&(e=this.frontendApi,i=(t=new URL(s,eu)).pathname,n=ek.includes(i)||eS.includes(i),e===t.host&&n);if(a||!o)return!1;let l=this.session,c=this.#en.signInUrl||this.environment?.displayConfig.signInUrl,d=c&&window.location.href.startsWith(c),h=this.#en.signUpUrl||this.environment?.displayConfig.signUpUrl,u=h&&window.location.href.startsWith(h);return r=new URL(s,eu),(!ek.includes(r.pathname)||!!l||!d&&!u)&&(await this.navigate(this.buildUrlWithAuth(s)),!0)};#eo=e=>({...rb,...e,allowedRedirectOrigins:function(e,t,i){if(Array.isArray(e)&&e.length)return e;let n=[];return"undefined"!=typeof window&&window.location&&n.push(window.location.origin),n.push(`https://${eg(t)}`),n.push(`https://*.${eg(t)}`),"development"===i&&n.push(`https://${t}`),n}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)});#eO=()=>{try{eP(N),eP(eA),eP(W),eP("__clerk_handshake"),eP("__clerk_handshake_nonce"),eP("__clerk_help")}catch{}};get #e_(){let e=eF;return this.#en.allowedRedirectProtocols&&(e=e.concat(this.#en.allowedRedirectProtocols)),e}}let rv=document.querySelector("script[data-clerk-publishable-key]")?.getAttribute("data-clerk-publishable-key")||window.__clerk_publishable_key||"",rk=document.querySelector("script[data-clerk-proxy-url]")?.getAttribute("data-clerk-proxy-url")||window.__clerk_proxy_url||"",rS=document.querySelector("script[data-clerk-domain]")?.getAttribute("data-clerk-domain")||window.__clerk_domain||"";window.Clerk||(window.Clerk=new ry(rv,{proxyUrl:rk,domain:rS}))})(),{}})());
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),n=this.#l.getItem(i);return!!n&&!(t-n>this.#c)||(this.#l.setItem(i,t),!1)}#d(e){let{sk:t,pk:i,payload:n,...r}=e,s={...n,...r};return JSON.stringify(Object.keys({...n,...r}).sort().map(e=>s[e]))}},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={};#_=[];#w=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.#b(e.event,e.payload);if(this.#y(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,n=null,r=e?.timestamp;if("number"==typeof r||"string"==typeof r){let e=new Date(r);Number.isNaN(e.getTime())||(n=e)}if(!t||!i||null===n){this.isDebug&&"undefined"!=typeof console&&console.warn("[clerk/telemetry] Dropping invalid telemetry log entry",{levelIsValid:t,messageIsValid:i,timestampIsValid:null!==n});return}let s=this.#U(),a={sdk:s.name,sdkv:s.version,cv:this.#g.clerkVersion??"",lvl:e.level,msg:e.message,ts:n.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.#w&&("undefined"!=typeof cancelIdleCallback?cancelIdleCallback(Number(this.#w)):clearTimeout(Number(this.#w))),this.#C();return}this.#w||("requestIdleCallback"in window?this.#w=requestIdleCallback(()=>{this.#C(),this.#w=null}):this.#w=setTimeout(()=>{this.#C(),this.#w=null},0))}#C(){let e=[...this.#_];if(this.#_=[],this.#w=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)}#y(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:n}=i.constructor.sdkMetadata;void 0!==t&&(e.name=t),void 0!==n&&(e.version=n)}}}return e}#b(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,n){return{event:e,eventSamplingRate:e===eJ?eK.has(t)?1:.1:.1,payload:{component:t,appearanceProp:!!i?.appearance,theme:!!i?.appearance?.theme,elements:!!i?.appearance?.elements,variables:!!i?.appearance?.variables,...n}}}}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,n){eQ&&(e1.push({level:e,message:t,context:i,source:n,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 n,r=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},n=0,async()=>{let e;await e6((e=e9(e=i.initialDelay*Math.pow(i.factor,n),i.jitter),Math.min(i.maxDelayBetweenRetries||e,e))),n++});for(;;)try{return await e()}catch(e){if(!s(e,++r))throw e;h&&await h(r),c&&1===r?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,71))),"@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 n=(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=>{n.startListening(),await e(),n.stopListening()},isUnloading:n.isUnloading}},ti=e=>({amount:e.amount,amountFormatted:e.amount_formatted,currency:e.currency,currencySymbol:e.currency_symbol}),tn=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 tr(e,t=""){return e.errors&&!!e.errors.find(e=>e.code===t)}let ts=U({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,n,r]=t;if(3!==t.length||!i||!n||!r)throw Error("JWT could not be decoded");let s=JSON.parse(ta(n)),a={__raw:e};return Object.keys(s).forEach(e=>{a[e]=s[e]}),{encoded:{header:i,payload:n,signature:r},header:JSON.parse(ta(i)),claims:a}}function tl(){if(!r())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{#T=[];#O={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.#T.find(t=>t.info.name===this.#O[e])?.provider;return void 0!==t?t:window.ethereum};#x=e=>{this.#T.some(t=>t.info.uuid===e.detail.info.uuid)||this.#T.push(e.detail)}},th=class e{#R=void 0;#z=!1;static #E=null;constructor(){}async #M(){if(this.#z)return;this.#z=!0;let e=await s.e("197").then(s.bind(s,4076)).then(e=>e.getWallets());this.#R=e.get(),e.on("register",()=>{this.#R=e.get()}),e.on("unregister",()=>{this.#R=e.get()})}#F(e){return e.chains?.some(e=>e.startsWith("solana:"))??!1}#N(e){return"solana:signMessage"in e.features}static getInstance(){return e.#E||(e.#E=new e),e.#E}get=async e=>{await this.#M();let t=(this.#R||[]).find(t=>t.name===e&&this.#F(t)&&this.#N(t));if(t&&this.#F(t))return t;if("undefined"==typeof window)return;let i=window.solana;if(i&&"function"==typeof i.connect&&"function"==typeof i.signMessage)return i}};let tu=()=>(function(e){let t=U({packageName:"@clerk/shared"});async function i(e){let{provider:t,walletName:i}=e,n=await f(t,i);if(!n)return"";if("solana"===t){let e=await n.features["standard:connect"].connect();return e&&e.accounts[0].address||""}let r=await n.request({method:"eth_requestAccounts"});return r&&r[0]||""}let n=async e=>{let{identifier:t,nonce:i,provider:n,walletName:r=""}=e,s=await f(n,r);if(!s)return"";if("solana"===n)try{let e=s.accounts.find(e=>e.address===t);if(!e)return console.warn(`Wallet account with address ${t} not found`),"";let n=await s.features["solana:signMessage"]?.signMessage({account:e,message:new TextEncoder().encode(i)});return n?.[0]?.signature?btoa(String.fromCharCode(...n[0].signature)):""}catch(e){if(e instanceof Error&&e.message.includes("User rejected the request."))throw new I("Web3 signature request was rejected by the user.",{code:"web3_signature_request_rejected"});throw new I("An error occurred while generating the Solana signature.",{code:"web3_solana_signature_generation_failed",cause:e instanceof Error?e:void 0})}return await s.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 i({provider:"metamask"})}async function s(){return await i({provider:"coinbase_wallet"})}async function a(){return await i({provider:"okx_wallet"})}async function o(){return await i({provider:"base"})}async function l(e){return await i({provider:"solana",walletName:e})}async function c(e){return await n({...e,provider:"metamask"})}async function d(e){return await n({...e,provider:"coinbase_wallet"})}async function h(e){return await n({...e,provider:"okx_wallet"})}async function u(e){return await n({...e,provider:"base"})}async function p(e){return await n({...e,provider:"solana"})}async function f(i,n){if("coinbase_wallet"===i){let t=await e.import("@coinbase/wallet-sdk");return t?t.createCoinbaseWalletSDK({preference:{options:"all"}}).getProvider():null}if("base"===i)try{let t=await e.import("@base-org/account");if(!t)return null;return t.createBaseAccountSDK({appName:"undefined"!=typeof window&&window.Clerk?.__internal_environment?.displayConfig?.applicationName||"undefined"!=typeof document&&document.title||"Web3 Application"}).getProvider()}catch{return null}return"solana"===i?n&&0!==n.length?await th.getInstance().get(n):void t.throw("Wallet name must be provided to get Solana wallet provider"):td.getInstance().get(i)}return{getWeb3Identifier:i,generateWeb3Signature:n,getMetamaskIdentifier:r,getCoinbaseWalletIdentifier:s,getOKXWalletIdentifier:a,getBaseIdentifier:o,getSolanaIdentifier:l,generateSignatureWithMetamask:c,generateSignatureWithCoinbaseWallet:d,generateSignatureWithOKXWallet:h,generateSignatureWithBase:u,generateSignatureWithSolana:p}})(new te),tp="environment",tf=JSON.stringify,tm=JSON.parse;class tg{static _key(e){return`__clerk_${e}`}static isExpired(e){return!!e.exp&&Date.now()>e.exp}static setItem(e,t,i){try{let n={value:t,...i&&{exp:Date.now()+i}};window.localStorage.setItem(this._key(e),tf(n))}catch{}}static getItem(e,t){try{let i=window.localStorage.getItem(this._key(e));if(!i)return t;let n=tm(i);if(!n)return t;if(this.isExpired(n))return this.removeItem(e),t;return n?.value??t}catch{return t}}static removeItem(e){try{window.localStorage.removeItem(this._key(e))}catch{}}}let t_="ClerkJS:";function tw(e=""){throw Error(`${t_} Something went wrong initializing Clerk in development mode.${e&&` ${e}`}`)}function tb(e){throw Error(`${t_} Something went wrong initializing Clerk during the ${e} flow. Please contact support.`)}function ty(e){throw Error(`${t_} You need to start a ${e} flow by calling ${e}.create() first.`)}function tv(e,t){throw Error(`${t_} Strategy "${t}" is not a valid strategy for ${e}.`)}function tk(e){throw Error(`${t_} You need to start a ${e} flow by calling ${e}.create({ identifier: 'your web3 wallet address' }) first`)}function tS(e=""){throw Error(`${t_} Missing '${e}' option`)}function tU(e,t){throw Error(`${t_} Response: ${e||0} not supported yet.
17
+ For more information contact us at ${t}`)}function tA(e){throw Error(`${t_} Missing publicKey. When calling 'navigator.credentials.${e}()' it is required to pass a publicKey object.`)}async function tI(e="",t){let{async:i,defer:n,beforeLoad:r,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=n||!1,l.addEventListener("load",()=>{l.remove(),t(l)}),l.addEventListener("error",t=>{l.remove(),o(t.error??Error(`failed to load script: ${e}`))}),l.src=e,l.nonce=a,r?.(l),document.body.appendChild(l)}),{shouldRetry:(e,t)=>t<=5})}async function tC(e){return window.turnstile||await tP(e).catch(()=>{throw{captchaError:"captcha_script_failed_to_load"}}),window.turnstile}async function tP(e){try{return await tI("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 tT(e){try{let t=e.getAttribute("data-cl-theme")||void 0,i=e.getAttribute("data-cl-language")||void 0,n=e.getAttribute("data-cl-size")||void 0;return{theme:t,language:i,size:n}}catch{return{theme:void 0,language:void 0,size:void 0}}}let tO=async e=>{let t,i,n,r,{siteKey:s,widgetType:a,invisibleSiteKey:o,nonce:l}=e,{modalContainerQuerySelector:c,modalWrapperQuerySelector:d,closeModal:h,openModal:u}=e,p=await tC(l),f=[],m="",g="",_=s,w=0,b=null,y="invisible";if(c&&d){b=a,r=c,y="modal";try{await u?.()}catch{throw{captchaError:"modal_component_not_ready"}}let e=await new Promise(e=>{if(document.querySelector(c))return e(document.querySelector(c));let t=new MutationObserver(()=>{document.querySelector(c)&&(t.disconnect(),e(document.querySelector(c)))});t.observe(document.body,{childList:!0,subtree:!0})});if(e){let{theme:r,language:s,size:a}=tT(e);t=r,n=s,i=a}}if(!r&&"smart"===a){let e=document.getElementById(D);if(e){y="smart",b="smart",r=`#${D}`,e.style.maxHeight="0";let{theme:s,language:a,size:o}=tT(e);t=s,n=a,i=o}else console.error("Cannot initialize Smart CAPTCHA widget because the `clerk-captcha` DOM element was not found; falling back to Invisible CAPTCHA widget. If you are using a custom flow, visit https://clerk.com/docs/guides/development/custom-flows/authentication/bot-sign-up-protection for instructions")}if(!r){y="invisible",_=o,b="invisible",r=`.${$}`;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(r,{sitekey:_,appearance:"interaction-only",theme:t||"auto",size:i||"normal",language:n||"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),w<2&&(t=e.toString(),["crashed","undefined_error","102","103","104","106","110600","300","600"].find(e=>t.startsWith(e))))?setTimeout(()=>{p.reset(o),w++},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"===y&&h?.(),"invisible"===y){let e=document.querySelector(`.${$}`);e&&document.body.removeChild(e)}if("smart"===y){let e=document.getElementById(D);e&&(e.style.maxHeight="0",e.style.minHeight="unset",e.style.marginBottom="unset")}}return{captchaToken:m,captchaWidgetType:b}},tE=e=>{let t=e.__internal_environment,i=t?t.displayConfig.captchaProvider:"turnstile",n=e.__internal_getOption?.("nonce");return{captchaSiteKey:t?t.displayConfig.captchaPublicKey:null,captchaWidgetType:t?t.displayConfig.captchaWidgetType:null,captchaProvider:i,captchaPublicKeyInvisible:t?t.displayConfig.captchaPublicKeyInvisible:null,canUseCaptcha:t?t.userSettings.signUp.captcha_enabled&&e.isStandardBrowser:null,nonce:n||void 0}};class tx{clerk;constructor(e){this.clerk=e}async invisible(e){let{captchaSiteKey:t,canUseCaptcha:i,captchaPublicKeyInvisible:n,nonce:r}=tE(this.clerk);return i&&t&&n?{...await tO({action:e?.action,captchaProvider:"turnstile",invisibleSiteKey:n,nonce:e?.nonce||r||void 0,siteKey:n,widgetType:"invisible"}).catch(e=>e.captchaError?{captchaError:e.captchaError}:{captchaError:e?.message||e||"unexpected_captcha_error"}),captchaAction:e?.action}:{captchaError:"captcha_unavailable",captchaAction:e?.action}}async managedOrInvisible(e){let{captchaSiteKey:t,canUseCaptcha:i,captchaWidgetType:n,captchaProvider:r,captchaPublicKeyInvisible:s,nonce:a}=tE(this.clerk);if(i&&t&&s){let i=await tO({captchaProvider:r,invisibleSiteKey:s,nonce:a||void 0,siteKey:t,widgetType:n,...e}).catch(t=>t.captchaError?{captchaError:t.captchaError}:e?.action==="verify"?{captchaError:t?.message||t||"unexpected_captcha_error"}:void 0);return e?.action==="verify"?{...i,captchaAction:"verify"}:i}return e?.action==="verify"?{captchaError:"captcha_unavailable",captchaAction:e?.action}:{}}async managedInModal(e){return this.managedOrInvisible({modalWrapperQuerySelector:"#cl-modal-captcha-wrapper",modalContainerQuerySelector:"#cl-modal-captcha-container",openModal:()=>this.clerk.__internal_openBlankCaptchaModal(),closeModal:()=>this.clerk.__internal_closeBlankCaptchaModal(),action:e?.action})}}class tR{client;CaptchaChallengeImpl;static instance;inflightException=null;captchaRetryCount=0;MAX_RETRY_ATTEMPTS=3;static getInstance(){return tR.instance||(tR.instance=new tR(iO,tx)),tR.instance}constructor(e,t){this.client=e,this.CaptchaChallengeImpl=t}async execute(e,t){if(this.captchaAttemptsExceeded())throw new I("Security verification failed. Please try again by refreshing the page, clearing your browser cookies, or using a different web browser.",{code:"captcha_client_attempts_exceeded"});try{return this.inflightException&&await this.inflightException,await t()}catch(n){let i;if(!v(n)||C(n)&&"network_error"===n.code||n.errors[0]?.code!=="requires_captcha")throw n;if(this.inflightException)return await this.inflightException,await t();this.inflightException=new Promise(e=>i=e);try{let t=await this.managedChallenge(e);t?.captchaError!=="modal_component_not_ready"&&(await this.client.getOrCreateInstance().__internal_sendCaptchaToken(t),this.captchaRetryCount=0)}catch(e){throw this.captchaRetryCount++,e}finally{i(),this.inflightException=null}return await t()}}managedChallenge(e){return new this.CaptchaChallengeImpl(e).managedInModal({action:"verify"})}captchaAttemptsExceeded=()=>this.captchaRetryCount>=this.MAX_RETRY_ATTEMPTS}class tz{static clerk;id;pathRoot="";static get fapiClient(){return tz.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 tR.getInstance().execute(this.clerk,()=>this._baseFetch(e,t))}static async _baseFetch(e,t={}){let i;tz.fapiClient||function(){throw Error(`${t_} Missing FAPI client in resources.`)}();let{fetchMaxTries:n}=t;try{i=await tz.fapiClient.request(e,{fetchMaxTries:n})}catch(t){if(this.shouldRethrowOfflineNetworkErrors())throw new I(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:r,status:s,statusText:a,headers:o}=i;if(o){let e=o.get("x-country");this.clerk.__internal_setCountry(e?e.toLowerCase():null)}if(("GET"!==e.method||t.forceUpdateClient)&&this._updateClient(r),s>=200&&s<=299)return r;if(s>=400){let e=r?.errors,t=e?.[0]?.long_message,i=e?.[0]?.code;401===s&&"requires_captcha"!==i&&await tz.clerk.handleUnauthenticated(),function(e,t){var i;if(!t||!t[0])return;let n=t[0],r=n.long_message;if("origin_invalid"===n.code&&((i=tz.clerk.publishableKey).startsWith("live_")||i.startsWith("pk_live_"))){let i=tz.clerk.frontendApi.replace("clerk.","");throw new y(`Clerk: Production Keys are only allowed for domain "${i}".
18
+ API Error: ${r}`,{data:t,status:e})}}(s,e);let n={data:e,status:s};if(429===s&&o){let e=o.get("retry-after");if(e){let t=parseInt(e,10);isNaN(t)||(n.retryAfter=t)}}throw new y(t||a,n)}return null}static _updateClient(e){if(!e)return;let t=e.client||e.meta?.client;t&&tz.clerk&&tz.clerk.updateClient(iO.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 tz._fetch({method:"GET",path:this.path(),rotatingTokenNonce:e.rotatingTokenNonce},e);return this.fromJSON(t?.response||t)}async _baseMutate(e){let{action:t,body:i,method:n,path:r}=e,s=await tz._fetch({method:n,path:r||this.path(t),body:i});return this.fromJSON(s?.response||s)}async _baseMutateBypass(e){let{action:t,body:i,method:n,path:r}=e,s=await tz._baseFetch({method:n,path:r||this.path(t),body:i});return this.fromJSON(s?.response||s)}async _basePost(e={}){return this._baseMutate({...e,method:"POST"})}async _basePostBypass(e={}){return this._baseMutateBypass({...e,method:"POST"})}async _basePut(e={}){return this._baseMutate({...e,method:"PUT"})}async _basePatch(e={}){return this._baseMutate({...e,method:"PATCH"})}async _baseDelete(e={}){await this._baseMutate({...e,method:"DELETE"})}static shouldRethrowOfflineNetworkErrors(){let e=tz.clerk?.__internal_getOption?.("experimental");return e?.rethrowOfflineNetworkErrors||!1}}function tM(e){let t=new Date(e||new Date);return t instanceof Date&&!isNaN(t.getTime())?t:new Date}class tF extends tz{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?tM(e.expiration):null,this.createdBy=e.created_by,this.description=e.description,this.secret=e.secret,this.lastUsedAt=e.last_used_at?tM(e.last_used_at):null,this.updatedAt=tM(e.updated_at),this.createdAt=tM(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 tN extends tz{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?tM(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 tW=[],{link:tD,unlink:t$,propagate:tL,checkDirty:tj,endTracking:tB,startTracking:tJ,shallowPropagate:tK}=function({update:e,notify:t,unwatched:i}){let n=0;return{link:function(e,t){let i,r=t.depsTail;if(void 0!==r&&r.dep===e)return;if(4&t.flags&&void 0!==(i=void 0!==r?r.nextDep:t.deps)&&i.dep===e){i.version=n,t.depsTail=i;return}let s=e.subsTail;if(void 0!==s&&s.version===n&&s.sub===t)return;let a=t.depsTail=e.subsTail={version:n,dep:e,sub:t,prevDep:r,nextDep:i,prevSub:s,nextSub:void 0};void 0!==i&&(i.prevDep=a),void 0!==r?r.nextDep=a:t.deps=a,void 0!==s?s.nextSub=a:e.subs=a},unlink:r,propagate:function(e){let i,n=e.nextSub;e:for(;;){let r=e.sub,s=r.flags;if(3&s&&(60&s?12&s?4&s?!(48&s)&&function(e,t){let i=t.depsTail;if(void 0!==i){let n=t.deps;do{if(n===e)return!0;if(n===i)break;n=n.nextDep}while(void 0!==n)}return!1}(e,r)?(r.flags=40|s,s&=1):s=0:r.flags=-9&s|32:s=0:r.flags=32|s,2&s&&t(r),1&s)){let t=r.subs;if(void 0!==t){e=t,void 0!==t.nextSub&&(i={value:n,prev:i},n=e.nextSub);continue}}if(void 0!==(e=n)){n=e.nextSub;continue}for(;void 0!==i;)if(e=i.value,i=i.prev,void 0!==e){n=e.nextSub;continue e}break}},checkDirty:function(t,i){let n,r=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)&&(n={value:t,prev:n}),t=a.deps,i=a,++r;continue}if(!l&&void 0!==t.nextDep){t=t.nextDep;continue}for(;r;){--r;let a=i.subs,o=void 0!==a.nextSub;if(o?(t=n.value,n=n.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=r(i,e);e.flags&=-5},startTracking:function(e){++n,e.depsTail=void 0,e.flags=-57&e.flags|4},shallowPropagate:s};function r(e,t=e.sub){let n=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:n.subsTail=l,void 0!==l?l.nextSub=o:void 0===(n.subs=o)&&i(n),a}function s(e){do{let i=e.sub,n=e.nextSub,r=i.flags;(48&r)==32&&(i.flags=16|r,2&r&&t(i)),e=n}while(void 0!==e)}}({update:e=>"getter"in e?tZ(e):t0(e,e.value),notify:function e(t){let i=t.flags;if(!(64&i)){t.flags=64|i;let n=t.subs;void 0!==n?e(n.sub):tW[tG++]=t}},unwatched(e){if("getter"in e){let t=e.deps;if(void 0!==t){e.flags=17;do t=t$(t,e);while(void 0!==t)}}else"previousValue"in e||t4.call(e)}}),tV=0,tq=0,tG=0;function tH(t){let i=e;return e=t,i}function tX(e){return t2.bind({previousValue:e,value:e,subs:void 0,subsTail:void 0,flags:1})}function tY(e){return t3.bind({value:void 0,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:17,getter:e})}function tQ(i){let n={fn:i,subs:void 0,subsTail:void 0,deps:void 0,depsTail:void 0,flags:2};void 0!==e?tD(n,e):void 0!==t&&tD(n,t);let r=tH(n);try{n.fn()}finally{tH(r)}return t4.bind(n)}function tZ(e){let t=tH(e);tJ(e);try{let t=e.value;return t!==(e.value=e.getter(t))}finally{tH(t),tB(e)}}function t0(e,t){return e.flags=1,e.previousValue!==(e.previousValue=t)}function t1(){for(;tq<tG;){let e=tW[tq];tW[tq++]=void 0,function e(t,i){if(16&i||32&i&&tj(t.deps,t)){let e=tH(t);tJ(t);try{t.fn()}finally{tH(e),tB(t)}return}32&i&&(t.flags=-33&i);let n=t.deps;for(;void 0!==n;){let t=n.dep,i=t.flags;64&i&&e(t,t.flags=-65&i),n=n.nextDep}}(e,e.flags&=-65)}tq=0,tG=0}function t3(){let i=this.flags;if(16&i||32&i&&tj(this.deps,this)){if(tZ(this)){let e=this.subs;void 0!==e&&tK(e)}}else 32&i&&(this.flags=-33&i);return void 0!==e?tD(this,e):void 0!==t&&tD(this,t),this.value}function t2(...t){if(t.length){let e=t[0];if(this.value!==(this.value=e)){this.flags=17;let e=this.subs;void 0!==e&&(tL(e),tV||t1())}}else{let t=this.value;if(16&this.flags&&t0(this,t)){let e=this.subs;void 0!==e&&tK(e)}return void 0!==e&&tD(this,e),t}}function t4(){let e=this.deps;for(;void 0!==e;)e=t$(e,this);let t=this.subs;void 0!==t&&t$(t),this.flags=0}function t5(e){let{pageSize:t,initialPage:i,...n}=e||{},r=t??10;return new URLSearchParams({...Object.entries(n).reduce((e,[t,i])=>(void 0!==i&&(e[t]=i),e),{}),limit:r+"",offset:((i??1)-1)*r+""})}class t6{static #W="/billing";static path(e,t){let{orgId:i}=t||{},n=i?`/organizations/${i}`:"/me";return`${n}${t6.#W}${e}`}getPlans=async e=>{let{for:t,...i}=e||{},n={...i,payer_type:"organization"===t?"org":"user"};return await tz._fetch({path:`${t6.#W}/plans`,method:"GET",search:t5(n)}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new iw(e))}})};getPlan=async e=>new iw(await tz._fetch({path:`${t6.#W}/plans/${e.id}`,method:"GET"}));getSubscription=async e=>await tz._fetch({path:t6.path("/subscription",{orgId:e.orgId}),method:"GET"}).then(e=>new iv(e?.response));getStatements=async e=>{let{orgId:t,...i}=e;return await tz._fetch({path:t6.path("/statements",{orgId:t}),method:"GET",search:t5(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 tz._fetch({path:t6.path(`/statements/${e.id}`,{orgId:e.orgId}),method:"GET"}))?.response);getPaymentAttempts=async e=>{let{orgId:t,...i}=e;return await tz._fetch({path:t6.path("/payment_attempts",{orgId:t}),method:"GET",search:t5(i)}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new id(e))}})};getPaymentAttempt=async e=>new id(await tz._fetch({path:t6.path(`/payment_attempts/${e.id}`,{orgId:e.orgId}),method:"GET"}));startCheckout=async e=>{let{orgId:t,...i}=e;return new il((await tz._fetch({path:t6.path("/checkouts",{orgId:t}),method:"POST",body:i}))?.response)}}let t9=tX({resource:null}),t7=tX({error:null}),t8=tX({status:"idle"}),ie=tY(()=>{let e=t9().resource,t=t7().error,i=t8().status;return{errors:ia(t,{identifier:null,password:null,code:null}),fetchStatus:i,signIn:e?e.__internal_future:null}}),it=tX({resource:null}),ii=tX({error:null}),ir=tX({status:"idle"}),is=tY(()=>{let e=it().resource,t=ii().error,i=ir().status;return{errors:ia(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 ia(e,t){let i={fields:{...t},raw:null,global:null};if(!e)return i;if(!v(e))return i.raw=[e],i.global=[E(e)],i;function n(e){return"meta"in e&&e.meta&&"paramName"in e.meta&&void 0!==e.meta.paramName}return e.errors.some(n)?e.errors.forEach(e=>{if(i.raw?i.raw.push(e):i.raw=[e],n(e)){let t=V(e.meta.paramName);t in i.fields&&(i.fields[t]=e)}}):(i.raw=[e],i.global=[E(e)]),i}class io extends tz{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=tM(e.created_at)),e.updated_at&&(this.updatedAt=tM(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 il extends tz{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 ig(e.payment_method):void 0,this.plan=new iw(e.plan),this.planPeriod=e.plan_period,this.planPeriodStart=e.plan_period_start,this.status=e.status,this.totals=tn(e.totals),this.isImmediatePlanChange=e.is_immediate_plan_change,e.free_trial_ends_at&&(this.freeTrialEndsAt=tM(e.free_trial_ends_at)),this.payer=new io(e.payer),this.needsPaymentMethod=e.needs_payment_method),this}confirm=e=>e7(()=>this._basePatch({path:t6.path(`/checkouts/${this.id}/confirm`,{orgId:this.payer.organizationId}),body:e}),{factor:1.1,maxDelayBetweenRetries:2e3,initialDelay:2e3,jitter:!1,shouldRetry(e,t){if(!v(e)||t>=4)return!1;let i=e?.status,n=409===i&&e.errors?.[0]?.code==="checkout_already_in_progress";return i>=500||n}})}class ic{resource=new il(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 il.clerk.billing?.startCheckout(this.config);this.resource=e},()=>{this.resource=new il(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 il.clerk.setActive({session:il.clerk.session?.id,navigate:t})})}runAsyncCheckoutTask(e,t,i){var n,r,s;return void 0===il.clerk.user?(console.warn("Clerk: Checkout operations cannot be performed during transitive state"),{error:null}):(n=this,r=this.signals,s=this.pendingOperations,async(e,t,i)=>{if(s.get(e))return s.get(e);let a=(async()=>{++tV,r.errorSignal({error:null}),r.fetchSignal({status:"fetching"}),i?.(),--tV||t1(),++tV;try{return await t(),r.resourceSignal({resource:n}),{error:null}}catch(e){return r.errorSignal({error:e}),{error:e}}finally{s.delete(e),r.fetchSignal({status:"idle"}),--tV||t1()}})();return s.set(e,a),a})(e,t,i)}}class id extends tz{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?tM(e.paid_at):null,this.failedAt=e.failed_at?tM(e.failed_at):null,this.updatedAt=tM(e.updated_at),this.paymentMethod=e.payment_method?new ig(e.payment_method):null,this.subscriptionItem=new ik(e.subscription_item),this.chargeType=e.charge_type,this.status=e.status),this}}let ih="/payment_methods",iu=async e=>{let{orgId:t,...i}=e;return new i_((await tz._fetch({path:t6.path(`${ih}/initialize`,{orgId:t}),method:"POST",body:i}))?.response)},ip=async e=>{let{orgId:t,...i}=e;return new ig((await tz._fetch({path:t6.path(ih,{orgId:t}),method:"POST",body:i}))?.response)},im=async e=>{let{orgId:t,...i}=e??{};return await tz._fetch({path:t6.path(ih,{orgId:t}),method:"GET",search:t5(i)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new ig(e))}})};class ig extends tz{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:tM(e.created_at),this.updatedAt=null==e.updated_at?e.updated_at:tM(e.updated_at)),this}async remove(e){let{orgId:t}=e??{};return new ix((await tz._fetch({path:t6.path(`/payment_methods/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}async makeDefault(e){let{orgId:t}=e??{};return await tz._fetch({path:t6.path("/payers/default_payment_method",{orgId:t}),method:"PUT",body:{payment_method_id:this.id}}),null}}class i_ extends tz{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 iw extends tz{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 ne(e))),this}}class ib extends tz{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=tM(e.timestamp),this.totals=tn(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=tM(e.timestamp),this.items=e.items.map(e=>new id(e))),this}}class iv extends tz{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=tM(e.created_at),this.updatedAt=e.updated_at?tM(e.updated_at):null,this.activeAt=tM(e.active_at),this.pastDueAt=e.past_due_at?tM(e.past_due_at):null,e.next_payment&&(this.nextPayment={amount:ti(e.next_payment.amount),date:tM(e.next_payment.date)}),this.subscriptionItems=(e.subscription_items||[]).map(e=>new ik(e)),this.eligibleForFreeTrial=this.withDefault(e.eligible_for_free_trial,!1)),this}}class ik extends tz{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 iw(e.plan),this.planPeriod=e.plan_period,this.status=e.status,this.createdAt=tM(e.created_at),this.pastDueAt=e.past_due_at?tM(e.past_due_at):null,this.periodStart=tM(e.period_start),this.periodEnd=e.period_end?tM(e.period_end):null,this.canceledAt=e.canceled_at?tM(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 ix((await tz._fetch({path:t6.path(`/subscription_items/${this.id}`,{orgId:t}),method:"DELETE"}))?.response)}}let iS={build:(e,t,i)=>[e,t,i].filter(Boolean).join("-"),parse:(e,t,i)=>{let n=iS.extractTemplate(e,t,i);return{organizationId:i,sessionId:t,template:n}},extractTemplate:(e,t,i)=>{if(e===t||i&&e===`${t}-${i}`)return;let n=e.slice(t.length+1);return i&&n.endsWith(`-${i}`)&&(n=n.slice(0,-(i.length+1))),n||void 0}},iU="clerk",iA=10,iI={broadcast:!0},iC={broadcast:!1};class iP{prefix;data;static fromKey(e){let[t,i,n=""]=e.split("::");return new iP(t,{audience:n,tokenId:i})}constructor(e,t){this.prefix=e,this.data=t,this.prefix=e,this.data=t}toKey(){let{tokenId:e,audience:t}=this.data;return[this.prefix,e,t||""].join("::")}}let iT=((e=iU)=>{let t=new Map,i=Math.random().toString(36).slice(2),n=null,r=()=>n||("undefined"==typeof BroadcastChannel?null:((n=new BroadcastChannel("clerk:session_token")).addEventListener("message",e=>{a(e)}),n));r();let s=(i,n=iA)=>{r();let s=new iP(e,i),a=t.get(s.toKey());if(!a)return;let o=Math.floor(Date.now()/1e3)-a.createdAt;if(a.expiresIn-o<(n||1)+5){void 0!==a.timeoutId&&clearTimeout(a.timeoutId),t.delete(s.toKey());return}return a.entry},a=async({data:e})=>{let t,n=iS.build(e.sessionId,e.template,e.organizationId);if(e.tokenId!==n)return void e4.warn("Ignoring token broadcast with mismatched tokenId",{expectedTokenId:n,organizationId:e.organizationId,receivedTokenId:e.tokenId,tabId:i,template:e.template,traceId:e.traceId},"tokenCache");try{t=new nD({id:e.tokenId,jwt:e.tokenRaw,object:"token"})}catch(t){e4.warn("Failed to parse token from broadcast, skipping cache update",{error:t,tabId:i,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");return}let r=t.jwt?.claims?.iat,a=t.jwt?.claims?.exp;if(!r||!a)return void e4.warn("Token missing iat/exp claim, skipping cache update",{tabId:i,tokenId:e.tokenId,traceId:e.traceId},"tokenCache");try{let t=s({tokenId:e.tokenId});if(t){let n=await t.tokenResolver,s=n.jwt?.claims?.iat;if(s&&s>=r)return void e4.debug("Ignoring older token broadcast",{existingIat:s,incomingIat:r,tabId:i,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}}catch(t){e4.warn("Existing entry compare failed; proceeding with broadcast update",{error:t,tabId:i,tokenId:e.tokenId,traceId:e.traceId},"tokenCache")}e4.info("Updating token cache from broadcast",{iat:r,organizationId:e.organizationId,tabId:i,template:e.template,tokenId:e.tokenId,traceId:e.traceId},"tokenCache"),o({createdAt:r,tokenId:e.tokenId,tokenResolver:Promise.resolve(t)},iC)},o=(r,s=iI)=>{let a=new iP(e,{audience:r.audience,tokenId:r.tokenId}).toKey(),o=Math.floor(Date.now()/1e3),l={createdAt:r.createdAt??o,entry:r,expiresIn:void 0},c=()=>{let e=t.get(a);e===l&&(void 0!==e.timeoutId&&clearTimeout(e.timeoutId),t.delete(a))};r.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=n;if(d&&s.broadcast){let n=e.getRawString();if(n&&t.sid){let e=t.sid,s=t.org_id||t.o?.id,a=iS.extractTemplate(r.tokenId,e,s),o=iS.build(e,a,s);if(r.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:r.tokenId,traceId:t},"tokenCache");let o={organizationId:s,sessionId:e,template:a,tokenId:r.tokenId,tokenRaw:n,traceId:t};d.postMessage(o)}}}}).catch(()=>{c()}),t.set(a,l)};return{clear:()=>{t.forEach(e=>{void 0!==e.timeoutId&&clearTimeout(e.timeoutId)}),t.clear()},close:()=>{n&&(n.close(),n=null)},get:s,set:e=>{r(),o(e,iI)},size:()=>t.size}})();class iO extends tz{static instance;pathRoot="/client";sessions=[];signUp=new nF;signIn=new nR;lastActiveSessionId=null;captchaBypass=!1;cookieExpiresAt=null;lastAuthenticationStrategy=null;createdAt=null;updatedAt=null;static getOrCreateInstance(e=null){return iO.instance||(iO.instance=new iO(e)),iO.instance}static clearInstance(){iO.instance=null}static isClientResource(e){return!!e&&e instanceof iO}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(()=>{iT.clear(),this.id="",this.sessions=[],this.signUp=new nF(null),this.signIn=new nR(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=>(iT.clear(),e))}clearCache(){return this.sessions.forEach(e=>e.clearCache())}isEligibleForTouch(){return!!this.cookieExpiresAt&&this.cookieExpiresAt.getTime()-Date.now()<=6912e5}buildTouchUrl({redirectUrl:e}){return tz.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 nU(e)),this.signUp=new nF(e.sign_up),this.signIn=new nR(e.sign_in),this.lastActiveSessionId=e.last_active_session_id,this.captchaBypass=e.captcha_bypass||!1,this.cookieExpiresAt=e.cookie_expires_at?tM(e.cookie_expires_at):null,this.lastAuthenticationStrategy=e.last_authentication_strategy||null,this.createdAt=tM(e.created_at||void 0),this.updatedAt=tM(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 iE extends tz{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 ix{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 iR extends tz{afterCreateOrganizationUrl="";afterJoinWaitlistUrl="";afterLeaveOrganizationUrl="";afterSignInUrl="";afterSignOutAllUrl="";afterSignOutOneUrl="";afterSignOutUrl="";afterSignUpUrl="";afterSwitchSessionUrl="";applicationName="";backendHost="";branded=!1;captchaHeartbeat=!1;captchaHeartbeatIntervalMs;captchaOauthBypass=["oauth_google","oauth_microsoft","oauth_apple"];captchaProvider="turnstile";captchaPublicKey=null;captchaPublicKeyInvisible=null;captchaWidgetType=null;clerkJSVersion;createOrganizationUrl="";faviconImageUrl="";googleOneTapClientId;homeUrl="";id="";instanceEnvironmentType="";logoImageUrl="";organizationProfileUrl="";preferredSignInStrategy="password";privacyPolicyUrl="";showDevModeWarning=!1;signInUrl="";signUpUrl="";supportEmail="";termsUrl="";theme={};userProfileUrl="";waitlistUrl="";constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.afterCreateOrganizationUrl=this.withDefault(e.after_create_organization_url,this.afterCreateOrganizationUrl),this.afterJoinWaitlistUrl=this.withDefault(e.after_join_waitlist_url,this.afterJoinWaitlistUrl),this.afterLeaveOrganizationUrl=this.withDefault(e.after_leave_organization_url,this.afterLeaveOrganizationUrl),this.afterSignInUrl=this.withDefault(e.after_sign_in_url,this.afterSignInUrl),this.afterSignOutAllUrl=this.withDefault(e.after_sign_out_all_url,this.afterSignOutAllUrl),this.afterSignOutOneUrl=this.withDefault(e.after_sign_out_one_url,this.afterSignOutOneUrl),this.afterSignUpUrl=this.withDefault(e.after_sign_up_url,this.afterSignUpUrl),this.afterSwitchSessionUrl=this.withDefault(e.after_switch_session_url,this.afterSwitchSessionUrl),this.applicationName=this.withDefault(e.application_name,this.applicationName),this.branded=this.withDefault(e.branded,this.branded),this.captchaHeartbeat=this.withDefault(e.captcha_heartbeat,this.captchaHeartbeat),this.captchaHeartbeatIntervalMs=this.withDefault(e.captcha_heartbeat_interval_ms,this.captchaHeartbeatIntervalMs),this.captchaOauthBypass=this.withDefault(e.captcha_oauth_bypass,this.captchaOauthBypass),this.captchaProvider=this.withDefault(e.captcha_provider,this.captchaProvider),this.captchaPublicKey=this.withDefault(e.captcha_public_key,this.captchaPublicKey),this.captchaPublicKeyInvisible=this.withDefault(e.captcha_public_key_invisible,this.captchaPublicKeyInvisible),this.captchaWidgetType=this.withDefault(e.captcha_widget_type,this.captchaWidgetType),this.clerkJSVersion=this.withDefault(e.clerk_js_version,this.clerkJSVersion),this.createOrganizationUrl=this.withDefault(e.create_organization_url,this.createOrganizationUrl),this.faviconImageUrl=this.withDefault(e.favicon_image_url,this.faviconImageUrl),this.googleOneTapClientId=this.withDefault(e.google_one_tap_client_id,this.googleOneTapClientId),this.homeUrl=this.withDefault(e.home_url,this.homeUrl),this.id=this.withDefault(e.id,this.id),this.instanceEnvironmentType=this.withDefault(e.instance_environment_type,this.instanceEnvironmentType),this.logoImageUrl=this.withDefault(e.logo_image_url,this.logoImageUrl),this.organizationProfileUrl=this.withDefault(e.organization_profile_url,this.organizationProfileUrl),this.preferredSignInStrategy=this.withDefault(e.preferred_sign_in_strategy,this.preferredSignInStrategy),this.privacyPolicyUrl=this.withDefault(e.privacy_policy_url,this.privacyPolicyUrl),this.showDevModeWarning=this.withDefault(e.show_devmode_warning,this.showDevModeWarning),this.signInUrl=this.withDefault(e.sign_in_url,this.signInUrl),this.signUpUrl=this.withDefault(e.sign_up_url,this.signUpUrl),this.supportEmail=this.withDefault(e.support_email,this.supportEmail),this.termsUrl=this.withDefault(e.terms_url,this.termsUrl),this.theme=this.withDefault(e.theme,this.theme),this.userProfileUrl=this.withDefault(e.user_profile_url,this.userProfileUrl),this.waitlistUrl=this.withDefault(e.waitlist_url,this.waitlistUrl)),this}__internal_toSnapshot(){return{object:"display_config",after_create_organization_url:this.afterCreateOrganizationUrl,after_join_waitlist_url:this.afterJoinWaitlistUrl,after_leave_organization_url:this.afterLeaveOrganizationUrl,after_sign_in_url:this.afterSignInUrl,after_sign_out_all_url:this.afterSignOutAllUrl,after_sign_out_one_url:this.afterSignOutOneUrl,after_sign_up_url:this.afterSignUpUrl,after_switch_session_url:this.afterSwitchSessionUrl,application_name:this.applicationName,branded:this.branded,captcha_heartbeat_interval_ms:this.captchaHeartbeatIntervalMs,captcha_heartbeat:this.captchaHeartbeat,captcha_oauth_bypass:this.captchaOauthBypass,captcha_provider:this.captchaProvider,captcha_public_key_invisible:this.captchaPublicKeyInvisible,captcha_public_key:this.captchaPublicKey,captcha_widget_type:this.captchaWidgetType,clerk_js_version:this.clerkJSVersion,create_organization_url:this.createOrganizationUrl,favicon_image_url:this.faviconImageUrl,google_one_tap_client_id:this.googleOneTapClientId,home_url:this.homeUrl,id:this.id,instance_environment_type:this.instanceEnvironmentType,logo_image_url:this.logoImageUrl,organization_profile_url:this.organizationProfileUrl,preferred_sign_in_strategy:this.preferredSignInStrategy,privacy_policy_url:this.privacyPolicyUrl,show_devmode_warning:this.showDevModeWarning,sign_in_url:this.signInUrl,sign_up_url:this.signUpUrl,support_email:this.supportEmail,terms_url:this.termsUrl,theme:this.theme,user_profile_url:this.userProfileUrl,waitlist_url:this.waitlistUrl}}}var iz='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 iM=(e,t={})=>{if("undefined"==typeof Worker)return null;try{let i=new Blob([e],{type:"application/javascript; charset=utf-8"}),n=globalThis.URL.createObjectURL(i);return new Worker(n,t)}catch{return console.warn("Clerk: Cannot create worker from blob. Consider adding worker-src blob:; to your CSP"),null}},iF=()=>{let e=0,t=()=>e++,i=new Map,n=(e,t)=>e?.postMessage(t),r=e=>{i.get(e.data.id)?.()},s=iM(iz,{name:"clerk-timers"});if(s?.addEventListener("message",r),!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=iM(iz,{name:"clerk-timers"}),s?.addEventListener("message",r))};return{setTimeout:(e,r)=>{a();let o=t();return i.set(o,()=>{e(),i.delete(o)}),n(s,{type:"setTimeout",id:o,ms:r}),o},setInterval:(e,r)=>{a();let o=t();return i.set(o,e),n(s,{type:"setInterval",id:o,ms:r}),o},clearTimeout:e=>{a(),i.delete(e),n(s,{type:"clearTimeout",id:e})},clearInterval:e=>{a(),i.delete(e),n(s,{type:"clearInterval",id:e})},cleanup:()=>{s&&(s.terminate(),s=null,i.clear())}}};function iN({delayInMs:e}={delayInMs:1e3}){let t,i=iF(),n=!1,r=()=>{t&&(i.clearTimeout(t),i.cleanup()),n=!0},s=async a=>{n=!1,await a(r),n||(t=i.setTimeout(()=>{s(a)},e))};return{run:s,stop:r}}class iW extends tz{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}=iN();return{startEmailLinkFlow:async({redirectUrl:i})=>(await this.prepareVerification({strategy:"email_link",redirectUrl:i}),new Promise((i,n)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),i(e))}).catch(e=>{t(),n(e)}))})),cancelEmailLinkFlow:t}};createEnterpriseSSOLinkFlow=()=>{let{run:e,stop:t}=iN();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,n)=>{e(()=>this.reload().then(e=>{"verified"===e.verification.status&&(t(),i(e))}).catch(e=>{t(),n(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 iH(e.verification),this.matchesSsoConnection=e.matches_sso_connection,this.linkedTo=(e.linked_to||[]).map(e=>new nt(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 iD=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,n=new Uint8Array(i);for(let e=0;e<i;e++)n[e]=t.charCodeAt(e);return n.buffer}};async function i$(e){try{let t=await navigator.credentials.create({publicKey:e});if(!t)return{error:new P("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 P(t.message,{code:"passkey_already_exists"}):"NotAllowedError"===t.name?new P(t.message,{code:"passkey_registration_cancelled"}):iB(t),publicKeyCredential:null}}}let iL=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 ij({publicKeyOptions:e,conditionalUI:t}){try{let i=await navigator.credentials.get({publicKey:e,mediation:t?"conditional":"optional",signal:iL.createAbortSignal()});if(!i)return{error:new P("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 P(i.message,{code:"passkey_retrieval_cancelled"}):iB(i),publicKeyCredential:null}}}function iB(e){return"AbortError"===e.name?new P(e.message,{code:"passkey_operation_aborted"}):"SecurityError"===e.name?new P(e.message,{code:"passkey_invalid_rpID_or_domain"}):e}function iJ(e){let t=iG(e.challenge),i=(e.allowCredentials||[]).map(e=>({...e,id:iG(e.id)}));return{...e,allowCredentials:i,challenge:t}}function iK(e){return{type:e.type,id:e.id,rawId:iq(e.rawId),authenticatorAttachment:e.authenticatorAttachment}}function iV(e){let t=e.response;return{...iK(e),response:{clientDataJSON:iq(t.clientDataJSON),authenticatorData:iq(t.authenticatorData),signature:iq(t.signature),userHandle:t.userHandle?iq(t.userHandle):null}}}let iq=iD.encode.bind(iD),iG=iD.decode.bind(iD);class iH extends tz{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===tz.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=tM(e.expire_at||void 0),this.error=e.error?new w(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 iX extends iH{publicKey=null;constructor(e){super(e),this.fromJSON(e)}fromJSON(e){var t;let i,n,r;return super.fromJSON(e),e?.nonce&&(this.publicKey=(i=iG((t=JSON.parse(e.nonce)).user.id),n=iG(t.challenge),r=(t.excludeCredentials||[]).map(e=>({...e,id:iG(e.id)})),{...t,excludeCredentials:r,challenge:n,user:{...t.user,id:i}})),this}}class iY{emailAddress;phoneNumber;web3Wallet;externalAccount;constructor(e){e?(this.emailAddress=new iQ(e.email_address),this.phoneNumber=new iQ(e.phone_number),this.web3Wallet=new iQ(e.web3_wallet),this.externalAccount=new iH(e.external_account)):(this.emailAddress=new iQ(null),this.phoneNumber=new iQ(null),this.web3Wallet=new iQ(null),this.externalAccount=new iH(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 iQ extends iH{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 iZ extends tz{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?tM(e.last_authenticated_at):null,this.enterpriseConnectionId=e.enterprise_connection_id,e.verification&&(this.verification=new iH(e.verification)),e.enterprise_connection&&(this.enterpriseConnection=new i0(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 i0 extends tz{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=tM(e.created_at),this.updatedAt=tM(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 i1="token:update",i3="user:signOut",i2="environment:update",i4="session:tokenResolved",i5=p();class i6 extends tz{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 i9 extends tz{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 i7 extends tz{static instance;authConfig=new tN;displayConfig=new iR;maintenanceMode=!1;clientDebugMode=!1;pathRoot="/environment";userSettings=new nV;organizationSettings=new i9;commerceSettings=new iE;apiKeysSettings=new i6;protectConfig=new ng;static getInstance(){return i7.instance||(i7.instance=new i7),i7.instance}constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.authConfig=new tN(e.auth_config),this.displayConfig=new iR(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 i9(e.organization_settings),this.userSettings=new nV(e.user_settings),this.commerceSettings=new iE(e.commerce_settings),this.apiKeysSettings=new i6(e.api_keys_settings),this.protectConfig=new ng(e.protect_config)),this}fetch({touch:e,fetchMaxTries:t}={touch:!1}){return(e?this._basePatch({}):this._baseGet({fetchMaxTries:t})).then(e=>(i5.emit(i2,null),e))}isDevelopmentOrStaging=()=>!this.isProduction();isProduction=()=>"production"===this.displayConfig.instanceEnvironmentType;isSingleSession=()=>this.authConfig.singleSessionMode;onWindowLocationHost=()=>this.displayConfig.backendHost===window.location.host;__internal_toSnapshot(){return{object:"environment",auth_config:this.authConfig.__internal_toSnapshot(),display_config:this.displayConfig.__internal_toSnapshot(),id:this.id??"",maintenance_mode:this.maintenanceMode,client_debug_mode:this.clientDebugMode,organization_settings:this.organizationSettings.__internal_toSnapshot(),user_settings:this.userSettings.__internal_toSnapshot(),commerce_settings:this.commerceSettings.__internal_toSnapshot(),api_keys_settings:this.apiKeysSettings.__internal_toSnapshot(),protect_config:this.protectConfig.__internal_toSnapshot()}}async __internal_enableEnvironmentSetting(e){await this._basePatch({path:"/dev_tools/enable_environment_setting",body:e})}}class i8 extends tz{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 iH(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 ne extends tz{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 nt extends tz{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 ni extends tz{id;name=null;publicUrl=null;static async create(e,t={}){let i,n=t;return"string"==typeof t.file?(n=t.file,i=new Headers({"Content-Type":"application/octet-stream"})):t.file&&(n=new FormData).append("file",t.file),new ni((await tz._fetch({path:e,method:"POST",body:n,headers:i}))?.response)}static async delete(e){return new ni((await tz._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 nn extends tz{id;name;organizationId;enrollmentMode;verification;affiliationEmailAddress;createdAt;updatedAt;totalPendingInvitations;totalPendingSuggestions;constructor(e){super(),this.fromJSON(e)}static async create(e,{name:t}){return new nn((await tz._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:tM(e.verification.expires_at)}:this.verification=null),this}}class nr extends tz{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=tM(e.created_at),this.updatedAt=tM(e.updated_at),e.public_user_data&&(this.publicUserData=new n_(e.public_user_data))),this}}class ns extends tz{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=tM(e.created_at),this.updatedAt=tM(e.updated_at)),this}}class na extends tz{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 ns(e)),this.createdAt=tM(e.created_at),this.updatedAt=tM(e.updated_at)),this}}class no extends tz{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 no((await tz._fetch({path:"/organizations",method:"POST",body:e}))?.response)}static async get(e){return new no((await tz._fetch({path:`/organizations/${e}`,method:"GET"}))?.response)}update=async e=>this._basePatch({body:e});getRoles=async e=>await tz._fetch({path:`/organizations/${this.id}/roles`,method:"GET",search:t5(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new na(e))}});getDomains=async e=>await tz._fetch({path:`/organizations/${this.id}/domains`,method:"GET",search:t5(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new nn(e))}});getDomain=async({domainId:e})=>new nn((await tz._fetch({path:`/organizations/${this.id}/domains/${e}`,method:"GET"}))?.response);getMembershipRequests=async e=>await tz._fetch({path:`/organizations/${this.id}/membership_requests`,method:"GET",search:t5(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new nr(e))}});createDomain=async e=>nn.create(this.id,{name:e});getMemberships=async e=>await tz._fetch({path:`/organizations/${this.id}/memberships`,method:"GET",search:t5({...e,paginated:!0})}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new nc(e))}});getInvitations=async e=>await tz._fetch({path:`/organizations/${this.id}/invitations`,method:"GET",search:t5(e)},{forceUpdateClient:!0}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new nl(e))}});addMember=async({userId:e,role:t})=>await tz._fetch({method:"POST",path:`/organizations/${this.id}/memberships`,body:{userId:e,role:t}}).then(e=>new nc(e?.response));inviteMember=async e=>nl.create(this.id,e);inviteMembers=async e=>nl.createBulk(this.id,e);updateMember=async({userId:e,role:t})=>await tz._fetch({method:"PATCH",path:`/organizations/${this.id}/memberships/${e}`,body:{role:t}}).then(e=>new nc(e?.response));removeMember=async e=>await tz._fetch({method:"DELETE",path:`/organizations/${this.id}/memberships/${e}`}).then(e=>new nc(e?.response));destroy=async()=>this._baseDelete();setLogo=async({file:e})=>{let t,i;return null===e?await tz._fetch({path:`/organizations/${this.id}/logo`,method:"DELETE"}).then(e=>new no(e?.response)):("string"==typeof e?(t=e,i=new Headers({"Content-Type":"application/octet-stream"})):(t=new FormData).append("file",e),await tz._fetch({path:`/organizations/${this.id}/logo`,method:"PUT",body:t,headers:i}).then(e=>new no(e?.response)))};initializePaymentMethod=e=>iu({...e,orgId:this.id});addPaymentMethod=e=>ip({...e,orgId:this.id});getPaymentMethods=e=>im({...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=tM(e.created_at),this.updatedAt=tM(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 tz._fetch({path:`/organizations/${this.id}`,method:"GET",rotatingTokenNonce:t},{forceUpdateClient:!0}))?.response;return this.fromJSON(i)}}class nl extends tz{id;emailAddress;organizationId;publicMetadata={};status;role;roleName;createdAt;updatedAt;static async create(e,{emailAddress:t,role:i}){return new nl((await tz._fetch({path:`/organizations/${e}/invitations`,method:"POST",body:{email_address:t,role:i}}))?.response)}static async createBulk(e,t){let{emailAddresses:i,role:n}=t;return((await tz._fetch({path:`/organizations/${e}/invitations/bulk`,method:"POST",body:{email_address:i,role:n}}))?.response).map(e=>new nl(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=tM(e.created_at),this.updatedAt=tM(e.updated_at)),this}}class nc extends tz{id;publicMetadata={};publicUserData;organization;permissions=[];role;roleName;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static retrieve=async e=>await tz._fetch({path:"/me/organization_memberships",method:"GET",search:t5({...e,paginated:!0})}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new nc(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 no(e.organization),this.publicMetadata=e.public_metadata||{},e.public_user_data&&(this.publicUserData=new n_(e.public_user_data)),this.permissions=Array.isArray(e.permissions)?[...e.permissions]:[],this.role=e.role,this.roleName=e.role_name,this.createdAt=tM(e.created_at),this.updatedAt=tM(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(`${t_} Calling OrganizationMembership.reload is not currently supported. Please contact support.`)}}class nd extends tz{id;publicOrganizationData;status;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async retrieve(e){return await tz._fetch({path:"/me/organization_suggestions",method:"GET",search:t5(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new nd(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=tM(e.created_at),this.updatedAt=tM(e.updated_at)),this}}function nh(){return o()&&"function"==typeof window.PublicKeyCredential}async function nu(){try{return nh()&&await window.PublicKeyCredential.isConditionalMediationAvailable()}catch{return!1}}async function np(){try{return"undefined"!=typeof window&&await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable()}catch{return!1}}class nf extends tz{id;pathRoot="/me/passkeys";verification=null;name=null;lastUsedAt=null;createdAt;updatedAt;constructor(e){super(),this.fromJSON(e)}static async create(){return tz._fetch({path:"/me/passkeys",method:"POST"}).then(e=>new nf(e?.response))}static async attemptVerification(e,t){let i,n=(i=t.response,{...iK(t),response:{clientDataJSON:iq(i.clientDataJSON),attestationObject:iq(i.attestationObject),transports:i.getTransports()}});return tz._fetch({path:`/me/passkeys/${e}/attempt_verification`,method:"POST",body:{strategy:"passkey",publicKeyCredential:JSON.stringify(n)}}).then(e=>new nf(e?.response))}static async registerPasskey(){let e=nf.clerk.__internal_isWebAuthnSupported||nh,t=nf.clerk.__internal_createPublicCredentials||i$,i=nf.clerk.__internal_isWebAuthnPlatformAuthenticatorSupported||np;if(!e())throw new P("Passkeys are not supported on this device.",{code:"passkey_not_supported"});let n=await this.create(),{verification:r}=n,s=r?.publicKey;if(s||tA("create"),s.authenticatorSelection?.authenticatorAttachment==="platform"&&!await i())throw new P("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(n.id,a)}update=e=>this._basePatch({body:e});delete=async()=>new ix((await tz._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?tM(e.last_used_at):null,this.createdAt=tM(e.created_at),this.updatedAt=tM(e.updated_at),e.verification&&(this.verification=new iX(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 nm extends tz{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 iH(e.verification),this.linkedTo=(e.linked_to||[]).map(e=>new nt(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 ng extends tz{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 n_{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 nw={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"}},nb=new Set(["first_factor","second_factor","multi_factor"]),ny=new Set(["strict_mfa","strict","moderate","lax"]),nv=(e,t)=>{let{org:i,user:n}=nk(e),[r,s]=t.split(":"),a=s||r;return"org"===r?i.includes(a):"user"===r?n.includes(a):[...i,...n].includes(a)},nk=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 nS extends tz{status;level;session;supportedFirstFactors=[];supportedSecondFactors=[];firstFactorVerification=new iH(null);secondFactorVerification=new iH(null);constructor(e=null){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.session=new nU(e.session),this.level=e.level,this.supportedFirstFactors=X(e.supported_first_factors),this.supportedSecondFactors=X(e.supported_second_factors),this.firstFactorVerification=new iH(e.first_factor_verification),this.secondFactorVerification=new iH(e.second_factor_verification)),this}}class nU extends tz{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 nU}constructor(e){super(),this.fromJSON(e),this.#D(this.lastActiveToken)}end=()=>(iT.clear(),this._basePost({action:"end"}));remove=()=>(iT.clear(),this._basePost({action:"remove"}));touch=()=>this._basePost({action:"touch",body:{active_organization_id:this.lastActiveOrganizationId}}).then(e=>(e.lastActiveToken&&i5.emit(i1,{token:e.lastActiveToken}),e));clearCache=()=>iT.clear();getToken=async e=>e7(()=>this._getToken(e),{factor:1.55,initialDelay:3e3,maxDelayBetweenRetries:5e4,jitter:!1,shouldRetry:(e,t)=>!O(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:n}=t;return e.feature&&i?nv(i,e.feature):e.plan&&n?nv(n,e.plan):null})(e,t),n=((e,t)=>{let{orgId:i,orgRole:n,orgPermissions:r}=t;return(e.role||e.permission)&&i&&n&&r?e.permission?r.includes(e.permission.replace(/^(org:)*/,"org:")):e.role?n.replace(/^(org:)*/,"org:")===e.role.replace(/^(org:)*/,"org:"):null:null})(e,t),r=((e,{factorVerificationAge:t})=>{if(!e.reverification||!t)return null;let i=(e=>{let t,i;if(!e)return!1;let n="string"==typeof e&&ny.has(e),r="object"==typeof e&&(t=e.level,nb.has(t))&&"number"==typeof(i=e.afterMinutes)&&i>0;return(!!n||!!r)&&(e=>"string"==typeof e?nw[e]:e).bind(null,e)})(e.reverification);if(!i)return null;let{level:n,afterMinutes:r}=i(),[s,a]=t,o=-1!==s?r>s:null,l=-1!==a?r>a:null;switch(n){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||n,r].some(e=>null===e)?[i||n,r].some(e=>!0===e):[i||n,r].every(e=>!0===e)})(e)};#D=e=>{e&&iT.set({tokenId:this.#$(),tokenResolver:Promise.resolve(e)})};#$(e,t){let i=void 0===t?this.lastActiveOrganizationId:t;return iS.build(this.id,e,i)}startVerification=async({level:e})=>new nS((await tz._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:tv("Session.prepareFirstFactorVerification",e.strategy)}return new nS((await tz._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(iV(e.publicKeyCredential))}:{...e},new nS((await tz._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=nU.clerk.__internal_isWebAuthnSupported||nh,i=nU.clerk.__internal_getPublicCredentials||ij;if(!t())throw new P("Passkeys are not supported",{code:"passkey_not_supported"});let n=e?iJ(JSON.parse(e)):null;n||tA("get");let{publicKeyCredential:r,error:s}=await i({publicKeyOptions:n,conditionalUI:!1});if(!r)throw s;return this.attemptFirstFactorVerification({strategy:"passkey",publicKeyCredential:r})};prepareSecondFactorVerification=async e=>new nS((await tz._fetch({method:"POST",path:`/client/sessions/${this.id}/verify/prepare_second_factor`,body:e}))?.response);attemptSecondFactorVerification=async e=>new nS((await tz._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=tM(e.expire_at),this.abandonAt=tM(e.abandon_at),this.factorVerificationAge=e.factor_verification_age,this.lastActiveAt=tM(e.last_active_at||void 0),this.lastActiveOrganizationId=e.last_active_organization_id,this.actor=e.actor||null,this.createdAt=tM(e.created_at),this.updatedAt=tM(e.updated_at),this.user=new nj(e.user),this.tasks=e.tasks||null,e.public_user_data&&(this.publicUserData=new n_(e.public_user_data)),this.lastActiveToken=e.last_active_token?new nD(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:n=!1}=e||{},r=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.#$(i,r),a=n?void 0:iT.get({tokenId:s},t),o=!i&&r===this.lastActiveOrganizationId;if(a){e4.debug("Using cached token (no fetch needed)",{tokenId:s},"session");let e=await a.tokenResolver;return o&&i5.emit(i1,{token:e}),e.getRawString()||null}e4.info("Fetching new token from API",{organizationId:r,template:i,tokenId:s},"session");let l=i?`${this.path()}/tokens/${i}`:`${this.path()}/tokens`,c=i?{}:{organizationId:r},d=this.lastActiveToken?.getRawString(),h=nD.create(l,c,n?{debug:"skip_cache"}:void 0).catch(e=>{if(k.is(e)&&d)return nD.create(l,{...c},{expired_token:d});throw e});return iT.set({tokenId:s,tokenResolver:h}),h.then(e=>(o&&(i5.emit(i1,{token:e}),e.jwt&&(this.lastActiveToken=e,i5.emit(i4,null))),e.getRawString()||null))}get currentTask(){let[e]=this.tasks??[];return e}}class nA extends tz{pathRoot="";id;status;abandonAt;expireAt;lastActiveAt;latestActivity;actor;constructor(e,t){super(),this.pathRoot=t,this.fromJSON(e)}static retrieve(){let e=tz.clerk.session?.id;return this.clerk.getFapiClient().request({method:"GET",path:"/me/sessions/active",sessionId:e}).then(e=>e.payload.map(e=>new nA(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=tM(e.expire_at),this.abandonAt=tM(e.abandon_at),this.lastActiveAt=tM(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 nI=(e,t,i)=>{let{onValidation:n=eY,onValidationComplexity:r=eY}=i||{},{show_zxcvbn:s,validatePassword:a}=t,o=e=>((e,t)=>{let{max_length:i,min_length:n,require_special_char:r,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:n})=>({max_length:e.length<n,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:n,require_special_char:r,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=>n=>{let r=i(n);return(t?.(r),r.score>=e&&r.score<3)?{state:"pass",keys:["unstable__errors.zxcvbn.couldBeStronger"],result:r}:r.score>=e?{state:"excellent",result:r}:{state:"fail",keys:["unstable__errors.zxcvbn.notEnough",...r.feedback.suggestions.map(e=>`unstable__errors.zxcvbn.suggestions.${e}`)],result:r}})(t),c={};return(t,i)=>{let{onValidation:d=n,onValidationComplexity:h=r}=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 nC(e){return e?`https://${e.replace(/clerk\.accountsstage\./,"accountsstage.").replace(/clerk\.accounts\.|clerk\./,"accounts.")}`:""}async function nP(e,t,i,n,r){if(!e.client||!n.popup)return;let s=nC(e.frontendApi),{redirectUrl:a}=n,o=new URL(a);o.searchParams.set("sign_in_force_redirect_url",n.redirectUrlComplete),o.searchParams.set("sign_up_force_redirect_url",n.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:n.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({...n,redirectUrlComplete:c,redirectUrl:d},r)}function nT(e,{redirectCallbackUrl:t,redirectUrl:i}){let n=nC(e.frontendApi),r=new URL(t);r.searchParams.set("sign_in_force_redirect_url",i),r.searchParams.set("sign_up_force_redirect_url",i);let s=e.buildUrlWithAuth(r.toString()),a=e.buildUrlWithAuth(`${n}/popup-callback`);return{redirectCallbackUrl:e.buildUrlWithAuth(`${n}/popup-callback?return_url=${encodeURIComponent(s)}`),redirectUrl:a}}function nO(e,t){return new Promise((i,n)=>{if(!e.client||!t.popup)return void n();let r=async t=>{t.origin===nC(e.frontendApi)&&(t.data.session||t.data.return_url?(window.removeEventListener("message",r),i()):n())};window.addEventListener("message",r),t.popup.location.href=t.externalVerificationRedirectURL.toString()})}async function nE(e,t){i5.emit("resource:error",{resource:e,error:null}),i5.emit("resource:fetch",{resource:e,status:"fetching"});try{return{result:await t(),error:null}}catch(t){return i5.emit("resource:error",{resource:e,error:t}),{error:t}}finally{i5.emit("resource:fetch",{resource:e,status:"idle"})}}let nx=()=>{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:n}=e,{dictionary:r,adjacencyGraphs:s}=t;return i.setOptions({dictionary:{...r},graphs:s}),n})}).loadZxcvbn};class nR extends tz{pathRoot="/client/sign_ins";id;_status=null;supportedIdentifiers=[];supportedFirstFactors=[];supportedSecondFactors=null;firstFactorVerification=new iH(null);secondFactorVerification=new iH(null);identifier=null;createdSessionId=null;userData=new nB(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 nz(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":case"web3_solana_signature":t={web3WalletId:e.web3WalletId};break;case"reset_password_phone_code":t={phoneNumberId:e.phoneNumberId};break;case"enterprise_sso":t={redirectUrl:e.redirectUrl,actionCompleteRedirectUrl:e.actionCompleteRedirectUrl,oidcPrompt:e.oidcPrompt,enterpriseConnectionId:e.enterpriseConnectionId};break;default:tv("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(iV(e.publicKeyCredential))}:{...e},this._basePost({body:{...t,strategy:e.strategy},action:"attempt_first_factor"})};createEmailLinkFlow=()=>{let{run:e,stop:t}=iN();return{startEmailLinkFlow:async({emailAddressId:i,redirectUrl:n})=>{this.id||ty("SignIn");let r={strategy:"email_link",emailAddressId:i,redirectUrl:n},s="needs_second_factor"===this.status||"needs_client_trust"===this.status,a=s?"secondFactorVerification":"firstFactorVerification";return s?await this.prepareSecondFactor(r):await this.prepareFirstFactor(r),new Promise((i,n)=>{e(()=>this.reload().then(e=>{let n=e[a].status;("verified"===n||"expired"===n)&&(t(),i(e))}).catch(e=>{t(),n(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:n,identifier:r,oidcPrompt:s,continueSignIn:a,enterpriseConnectionId:o}=e||{},l=nR.clerk.buildUrlWithAuth(e.redirectUrl);this.id&&a||await this.create({strategy:i,identifier:r,redirectUrl:l,actionCompleteRedirectUrl:n}),"enterprise_sso"===i&&await this.prepareFirstFactor({strategy:i,redirectUrl:l,actionCompleteRedirectUrl:n,oidcPrompt:s,enterpriseConnectionId:o});let{status:c,externalVerificationRedirectURL:d}=this.firstFactorVerification;"unverified"===c&&d?t(d):tU(c,nR.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eF);authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||tS("popup"),nP(nR.clerk,"signIn",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e.toString()})};authenticateWithWeb3=async e=>{let t,{identifier:i,generateSignature:n,strategy:r="web3_metamask_signature",walletName:s}=e||{},a=r.replace("web3_","").replace("_signature","");"function"!=typeof n&&tS("generateSignature"),"solana"!==a||s||tS("walletName"),await this.create({identifier:i});let o=this.supportedFirstFactors?.find(e=>e.strategy===r);o||tk("SignIn"),await this.prepareFirstFactor(o);let{message:l}=this.firstFactorVerification;l||tk("SignIn");try{t=await n({identifier:i,nonce:l,walletName:s,provider:a})}catch(e){if("coinbase_wallet"===a&&4001===e.code)t=await n({identifier:i,nonce:l,provider:a,walletName:s});else throw e}return this.attemptFirstFactor({signature:t,strategy:r})};authenticateWithMetamask=async()=>{let e=await tu().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tu().generateSignatureWithMetamask,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async()=>{let e=await tu().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tu().generateSignatureWithCoinbaseWallet,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async()=>{let e=await tu().getBaseIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tu().generateSignatureWithBase,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async()=>{let e=await tu().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:e,generateSignature:tu().generateSignatureWithOKXWallet,strategy:"web3_okx_wallet_signature"})};authenticateWithSolana=async({walletName:e})=>{let t=await tu().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:t,generateSignature:t=>tu().generateSignatureWithSolana({...t,walletName:e}),strategy:"web3_solana_signature",walletName:e})};authenticateWithPasskey=async e=>{let{flow:t}=e||{},i=nR.clerk.__internal_isWebAuthnSupported||nh,n=nR.clerk.__internal_getPublicCredentials||ij,r=nR.clerk.__internal_isWebAuthnAutofillSupported||nu;if(!i())throw new P("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(`${t_} 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||tA("get");let o=!1;"autofill"===t&&(o=await r());let{publicKeyCredential:l,error:c}=await n({publicKeyOptions:a,conditionalUI:o});if(!l)throw c;return this.attemptFirstFactor({publicKeyCredential:l,strategy:"passkey"})};validatePassword=(e,t)=>{if(nR.clerk.__internal_environment?.userSettings.passwordSettings)return nI(nx(),{...nR.clerk.__internal_environment?.userSettings.passwordSettings,validatePassword:!0})(e,t)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.supportedIdentifiers=e.supported_identifiers,this.identifier=e.identifier,this.supportedFirstFactors=X(e.supported_first_factors),this.supportedSecondFactors=X(e.supported_second_factors),this.firstFactorVerification=new iH(e.first_factor_verification),this.secondFactorVerification=new iH(e.second_factor_verification),this.createdSessionId=e.created_session_id,this.userData=new nB(e.user_data),this.clientTrustState=e.client_trust_state??void 0),i5.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 nz{emailCode={sendCode:this.sendEmailCode.bind(this),verifyCode:this.verifyEmailCode.bind(this)};emailLink={sendLink:this.sendEmailLink.bind(this),waitForVerification:this.waitForEmailLinkVerification.bind(this),get verification(){if(!r())return null;const e=eI("__clerk_status"),t=eI("__clerk_created_session");if(!e||!t)return null;const i="verified"===e&&void 0!==nR.clerk.client&&nR.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)};#L=!1;#j;constructor(e){this.#j=e}get id(){return this.#j.id}get identifier(){return this.#j.identifier}get createdSessionId(){return this.#j.createdSessionId}get userData(){return this.#j.userData}get status(){return this.#j.status||"needs_identifier"}get supportedFirstFactors(){return this.#j.supportedFirstFactors??[]}get supportedSecondFactors(){return this.#j.supportedSecondFactors??[]}get isTransferable(){return"transferable"===this.#j.firstFactorVerification.status}get existingSession(){if("failed"===this.#j.firstFactorVerification.status&&this.#j.firstFactorVerification.error?.code==="identifier_already_signed_in"&&this.#j.firstFactorVerification.error?.meta?.sessionId)return{sessionId:this.#j.firstFactorVerification.error?.meta?.sessionId}}get firstFactorVerification(){return this.#j.firstFactorVerification}get secondFactorVerification(){return this.#j.secondFactorVerification}get hasBeenFinalized(){return this.#L}async sendResetPasswordEmailCode(){if(!this.#j.id)throw Error("Cannot reset password without a sign in.");return nE(this.#j,async()=>{let e=this.#j.supportedFirstFactors?.find(e=>"reset_password_email_code"===e.strategy);if(!e)throw new I("Reset password email code factor not found",{code:"factor_not_found"});let{emailAddressId:t}=e;await this.#j.__internal_basePost({body:{emailAddressId:t,strategy:"reset_password_email_code"},action:"prepare_first_factor"})})}async verifyResetPasswordEmailCode(e){let{code:t}=e;return nE(this.#j,async()=>{await this.#j.__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 nE(this.#j,async()=>{await this.#j.__internal_basePost({body:{password:t,signOutOfOtherSessions:i},action:"reset_password"})})}async _create(e){let t=tl();await this.#j.__internal_basePost({path:this.#j.pathRoot,body:t?{locale:t,...e}:e})}async create(e){return nE(this.#j,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 nE(this.#j,async()=>{let t=e.identifier||e.emailAddress||e.phoneNumber,i=this.#j.identifier,n=tl();await this.#j.__internal_basePost({path:this.#j.pathRoot,body:{identifier:t||i,password:e.password,...n?{locale:n}:{}}})})}async sendEmailCode(e={}){let{emailAddress:t,emailAddressId:i}=e;if(!this.#j.id&&i)throw Error("signIn.emailCode.sendCode() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#j.id&&!t)throw Error("signIn.emailCode.sendCode() cannot be called without an emailAddress if an existing signIn does not exist.");return nE(this.#j,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_code",emailAddressId:i});if(!e)throw new I("Email code factor not found",{code:"factor_not_found"});await this.#j.__internal_basePost({body:{emailAddressId:e.emailAddressId,strategy:"email_code"},action:"prepare_first_factor"})})}async verifyEmailCode(e){let{code:t}=e;return nE(this.#j,async()=>{await this.#j.__internal_basePost({body:{code:t,strategy:"email_code"},action:"attempt_first_factor"})})}async sendEmailLink(e){let{emailAddress:t,verificationUrl:i,emailAddressId:n}=e;if(!this.#j.id&&n)throw Error("signIn.emailLink.sendLink() cannot be called with an emailAddressId if an existing signIn does not exist.");if(!this.#j.id&&!t)throw Error("signIn.emailLink.sendLink() cannot be called without an emailAddress if an existing signIn does not exist.");return nE(this.#j,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"email_link",emailAddressId:n});if(!e)throw new I("Email link factor not found",{code:"factor_not_found"});let r=i;try{new URL(i)}catch{r=window.location.origin+i}await this.#j.__internal_basePost({body:{emailAddressId:e.emailAddressId,redirectUrl:r,strategy:"email_link"},action:"prepare_first_factor"})})}async waitForEmailLinkVerification(){return nE(this.#j,async()=>{let{run:e,stop:t}=iN();await new Promise((i,n)=>{e(async()=>{try{let e=await this.#j.__internal_baseGet(),n=e.firstFactorVerification.status;("verified"===n||"expired"===n)&&(t(),i(e))}catch(e){t(),n(e)}})})})}async sendPhoneCode(e={}){let{phoneNumber:t,phoneNumberId:i,channel:n="sms"}=e;if(!this.#j.id&&i)throw Error("signIn.phoneCode.sendCode() cannot be called with an phoneNumberId if an existing signIn does not exist.");if(!this.#j.id&&!t)throw Error("signIn.phoneCode.sendCode() cannot be called without an phoneNumber if an existing signIn does not exist.");return nE(this.#j,async()=>{t&&await this._create({identifier:t});let e=this.selectFirstFactor({strategy:"phone_code",phoneNumberId:i});if(!e)throw new I("Phone code factor not found",{code:"factor_not_found"});await this.#j.__internal_basePost({body:{phoneNumberId:e.phoneNumberId,strategy:"phone_code",channel:n},action:"prepare_first_factor"})})}async verifyPhoneCode(e){let{code:t}=e;return nE(this.#j,async()=>{await this.#j.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_first_factor"})})}async sso(e){let{strategy:t,redirectUrl:i,redirectCallbackUrl:n,popup:r,oidcPrompt:s,enterpriseConnectionId:a,identifier:o}=e;return nE(this.#j,async()=>{let e=i;try{new URL(i)}catch{e=window.location.origin+i}let l={redirectUrl:nR.clerk.buildUrlWithAuth(n),actionCompleteRedirectUrl:e};if(r){let t=nT(nR.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.#j.__internal_basePost({body:{...l,oidcPrompt:s,enterpriseConnectionId:a,strategy:"enterprise_sso"},action:"prepare_first_factor"});let{status:c,externalVerificationRedirectURL:d}=this.#j.firstFactorVerification;"unverified"===c&&d&&(r?(await nO(nR.clerk,{popup:r,externalVerificationRedirectURL:d}),await this.#j.reload()):eF(d))})}async web3(e){let{strategy:t}=e,i=t.replace("web3_","").replace("_signature","");return nE(this.#j,async()=>{let n,r,s;switch(i){case"metamask":n=await tu().getMetamaskIdentifier(),r=tu().generateSignatureWithMetamask;break;case"coinbase_wallet":n=await tu().getCoinbaseWalletIdentifier(),r=tu().generateSignatureWithCoinbaseWallet;break;case"base":n=await tu().getBaseIdentifier(),r=tu().generateSignatureWithBase;break;case"okx_wallet":n=await tu().getOKXWalletIdentifier(),r=tu().generateSignatureWithOKXWallet;break;case"solana":if(!e.walletName)throw new I("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});n=await tu().getSolanaIdentifier(e.walletName),r=t=>tu().generateSignatureWithSolana({...t,walletName:e.walletName});break;default:throw Error(`Unsupported Web3 provider: ${i}`)}await this._create({identifier:n});let a=this.#j.supportedFirstFactors?.find(e=>e.strategy===t);if(!a)throw new I("Web3 first factor not found",{code:"factor_not_found"});await this.#j.__internal_basePost({body:{web3WalletId:a.web3WalletId,strategy:t},action:"prepare_first_factor"});let{message:o}=this.firstFactorVerification;if(!o)throw new I("Web3 nonce not found",{code:"web3_nonce_not_found"});try{s=await r({identifier:n,nonce:o,walletName:e?.walletName,provider:i})}catch(e){if("coinbase_wallet"===i&&4001===e.code)s=await r({identifier:n,nonce:o,provider:i});else throw e}await this.#j.__internal_basePost({body:{signature:s,strategy:t},action:"attempt_first_factor"})})}async passkey(e){let{flow:t}=e||{},i=nR.clerk.__internal_isWebAuthnSupported||nh,n=nR.clerk.__internal_getPublicCredentials||ij,r=nR.clerk.__internal_isWebAuthnAutofillSupported||nu;if(!i())throw new P("Passkeys are not supported",{code:"passkey_not_supported"});return nE(this.#j,async()=>{if("autofill"===t||"discoverable"===t)await this._create({strategy:"passkey"});else{if(!this.supportedFirstFactors.find(e=>"passkey"===e.strategy))throw new I("Passkey factor not found",{code:"factor_not_found"});await this.#j.__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 I("Missing public key options",{code:"missing_public_key_options"});let s=!1;"autofill"===t&&(s=await r());let{publicKeyCredential:a,error:o}=await n({publicKeyOptions:i,conditionalUI:s});if(!a)throw new P(o.message,{code:"passkey_retrieval_failed"});await this.#j.__internal_basePost({body:{publicKeyCredential:JSON.stringify(iV(a)),strategy:"passkey"},action:"attempt_first_factor"})})}async sendMFAPhoneCode(){return nE(this.#j,async()=>{let e=this.#j.supportedSecondFactors?.find(e=>"phone_code"===e.strategy);if(!e)throw new I("Phone code factor not found",{code:"factor_not_found"});let{phoneNumberId:t}=e;await this.#j.__internal_basePost({body:{phoneNumberId:t,strategy:"phone_code"},action:"prepare_second_factor"})})}async verifyMFAPhoneCode(e){let{code:t}=e;return nE(this.#j,async()=>{await this.#j.__internal_basePost({body:{code:t,strategy:"phone_code"},action:"attempt_second_factor"})})}async verifyTOTP(e){let{code:t}=e;return nE(this.#j,async()=>{await this.#j.__internal_basePost({body:{code:t,strategy:"totp"},action:"attempt_second_factor"})})}async verifyBackupCode(e){let{code:t}=e;return nE(this.#j,async()=>{await this.#j.__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.#j.createdSessionId)throw Error("Cannot finalize sign-in without a created session.");return nE(this.#j,async()=>{nR.clerk.client&&!nR.clerk.client.sessions.some(e=>e.id===this.#j.createdSessionId)&&await nR.clerk.client.reload(),this.#L=!0,await nR.clerk.setActive({session:this.#j.createdSessionId,navigate:t})})}selectFirstFactor({strategy:e,emailAddressId:t,phoneNumberId:i}){if(!this.#j.supportedFirstFactors)return null;if(t){let i=this.#j.supportedFirstFactors.find(i=>i.strategy===e&&i.emailAddressId===t);if(i)return i}if(i){let t=this.#j.supportedFirstFactors.find(t=>t.strategy===e&&t.phoneNumberId===i);if(t)return t}let n=this.#j.supportedFirstFactors.find(t=>t.strategy===e&&t.safeIdentifier===this.#j.identifier);if(n)return n;let r=this.#j.supportedFirstFactors.find(t=>t.strategy===e);return r||null}}function nM(e){let{unsafeMetadata:t}={...e},i=t?"object"==typeof t?JSON.stringify(t):t:"";return{...e,...t?{unsafeMetadata:i}:{}}}class nF extends tz{pathRoot="/client/sign_ups";id;_status=null;requiredFields=[];missingFields=[];optionalFields=[];unverifiedFields=[];verifications=new iY(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 nN(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 tx(nF.clerk),i=await e.managedOrInvisible({action:"signup"});if(!i)throw new I("",{code:"captcha_unavailable"});t={...t,...i}}if(t.transfer&&this.shouldBypassCaptchaForAttempt(t)){let e=nF.clerk.client?.signIn.firstFactorVerification.strategy;e&&(t={...t,strategy:e})}return this._basePost({path:this.pathRoot,body:nM(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}=iN();return{startEmailLinkFlow:async({redirectUrl:i})=>(this.id||ty("SignUp"),await this.prepareEmailAddressVerification({strategy:"email_link",redirectUrl:i}),new Promise((i,n)=>{e(()=>this.reload().then(e=>{let n=e.verifications.emailAddress.status;("verified"===n||"expired"===n)&&(t(),i(e))}).catch(e=>{t(),n(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:n,unsafeMetadata:r,strategy:s="web3_metamask_signature",legalAccepted:a,walletName:o}=e||{},l=s.replace("web3_","").replace("_signature","");"function"!=typeof i&&tS("generateSignature");let c=n||this.web3wallet;await this.create({web3Wallet:c,unsafeMetadata:r,legalAccepted:a}),await this.prepareWeb3WalletVerification({strategy:s});let{message:d}=this.verifications.web3Wallet;d||tk("SignUp");try{t=await i({identifier:n,nonce:d,provider:l,walletName:o})}catch(e){if("coinbase_wallet"===l&&4001===e.code)t=await i({identifier:n,nonce:d,provider:l});else throw e}return this.attemptWeb3WalletVerification({signature:t,strategy:s})};authenticateWithMetamask=async e=>{let t=await tu().getMetamaskIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tu().generateSignatureWithMetamask,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_metamask_signature",legalAccepted:e?.legalAccepted})};authenticateWithCoinbaseWallet=async e=>{let t=await tu().getCoinbaseWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tu().generateSignatureWithCoinbaseWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_coinbase_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithBase=async e=>{let t=await tu().getBaseIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tu().generateSignatureWithBase,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_base_signature",legalAccepted:e?.legalAccepted})};authenticateWithOKXWallet=async e=>{let t=await tu().getOKXWalletIdentifier();return this.authenticateWithWeb3({identifier:t,generateSignature:tu().generateSignatureWithOKXWallet,unsafeMetadata:e?.unsafeMetadata,strategy:"web3_okx_wallet_signature",legalAccepted:e?.legalAccepted})};authenticateWithSolana=async({walletName:e,unsafeMetadata:t,legalAccepted:i})=>{let n=await tu().getSolanaIdentifier(e);return this.authenticateWithWeb3({identifier:n,generateSignature:t=>tu().generateSignatureWithSolana({...t,walletName:e}),unsafeMetadata:t,strategy:"web3_solana_signature",legalAccepted:i,walletName:e})};authenticateWithRedirectOrPopup=async(e,t)=>{let{redirectUrl:i,redirectUrlComplete:n,strategy:r,continueSignUp:s=!1,unsafeMetadata:a,emailAddress:o,legalAccepted:l,oidcPrompt:c,enterpriseConnectionId:d}=e,h=nF.clerk.buildUrlWithAuth(i),u=()=>{let e={strategy:r,redirectUrl:h,actionCompleteRedirectUrl:n,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(v(e)&&T(e))return await nF.clerk.__internal_environment.reload(),u();throw e}),{externalAccount:f}=p,{status:m,externalVerificationRedirectURL:g}=f;"unverified"===m&&g?t(g):tU(m,nF.fapiClient.buildEmailAddress("support"))};authenticateWithRedirect=async e=>this.authenticateWithRedirectOrPopup(e,eF);authenticateWithPopup=async e=>{let{popup:t}=e||{};return t||tS("popup"),nP(nF.clerk,"signUp",this.authenticateWithRedirectOrPopup,e,e=>{t.location.href=e instanceof URL?e.toString():e})};update=e=>this._basePatch({body:nM(e)});upsert=e=>this.id?this.update(e):this.create(e);validatePassword=(e,t)=>{if(nF.clerk.__internal_environment?.userSettings.passwordSettings)return nI(nx(),{...nF.clerk.__internal_environment?.userSettings.passwordSettings,validatePassword:!0})(e,t)};fromJSON(e){return e&&(this.id=e.id,this.status=e.status,this.requiredFields=e.required_fields,this.optionalFields=e.optional_fields,this.missingFields=e.missing_fields,this.unverifiedFields=e.unverified_fields,this.verifications=new iY(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),i5.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 nF.clerk.client?.captchaBypass}shouldBypassCaptchaForAttempt(e){if(!e.strategy)return!1;let t=nF.clerk.__internal_environment.displayConfig.captchaOauthBypass;return!!(t.some(t=>t===e.strategy)||e.transfer&&t.some(e=>e===nF.clerk.client.signIn.firstFactorVerification.strategy))}__experimental_getEnterpriseConnections=()=>tz._fetch({path:`/client/sign_ups/${this.id}/enterprise_connections`,method:"GET"}).then(e=>(e?.response).map(e=>new nW(e)))}class nN{verifications={sendEmailCode:this.sendEmailCode.bind(this),verifyEmailCode:this.verifyEmailCode.bind(this),sendPhoneCode:this.sendPhoneCode.bind(this),verifyPhoneCode:this.verifyPhoneCode.bind(this)};#L=!1;#j;constructor(e){this.#j=e}get id(){return this.#j.id}get requiredFields(){return this.#j.requiredFields}get optionalFields(){return this.#j.optionalFields}get missingFields(){return this.#j.missingFields}get status(){return this.#j.status||"missing_requirements"}get username(){return this.#j.username}get firstName(){return this.#j.firstName}get lastName(){return this.#j.lastName}get emailAddress(){return this.#j.emailAddress}get phoneNumber(){return this.#j.phoneNumber}get web3Wallet(){return this.#j.web3wallet}get hasPassword(){return this.#j.hasPassword}get unsafeMetadata(){return this.#j.unsafeMetadata}get createdSessionId(){return this.#j.createdSessionId}get createdUserId(){return this.#j.createdUserId}get abandonAt(){return this.#j.abandonAt}get legalAcceptedAt(){return this.#j.legalAcceptedAt}get locale(){return this.#j.locale}get unverifiedFields(){return this.#j.unverifiedFields}get isTransferable(){return"transferable"===this.#j.verifications.externalAccount.status&&this.#j.verifications.externalAccount.error?.code==="external_account_exists"}get existingSession(){if(("failed"===this.#j.verifications.externalAccount.status||"unverified"===this.#j.verifications.externalAccount.status)&&this.#j.verifications.externalAccount.error?.code==="identifier_already_signed_in"&&this.#j.verifications.externalAccount.error?.meta?.sessionId)return{sessionId:this.#j.verifications.externalAccount.error?.meta?.sessionId}}get hasBeenFinalized(){return this.#L}async getCaptchaToken(){let e=new tx(nF.clerk),t=await e.managedOrInvisible({action:"signup"});if(!t)throw Error("Captcha challenge failed");let{captchaError:i,captchaToken:n,captchaWidgetType:r}=t;return{captchaToken:n,captchaWidgetType:r,captchaError:i}}async _create(e){let{captchaToken:t,captchaWidgetType:i,captchaError:n}=await this.getCaptchaToken(),r={transfer:e.transfer,captchaToken:t,captchaWidgetType:i,captchaError:n,...e,unsafeMetadata:e.unsafeMetadata?nM(e.unsafeMetadata):void 0,locale:e.locale??tl()};await this.#j.__internal_basePost({path:this.#j.pathRoot,body:r})}async create(e){return nE(this.#j,async()=>{await this._create(e)})}async update(e){return nE(this.#j,async()=>{let t={...e,unsafeMetadata:e.unsafeMetadata?nM(e.unsafeMetadata):void 0};await this.#j.__internal_basePatch({path:this.#j.pathRoot,body:t})})}async password(e){return nE(this.#j,async()=>{let{captchaToken:t,captchaWidgetType:i,captchaError:n}=await this.getCaptchaToken(),r={strategy:"password",captchaToken:t,captchaWidgetType:i,captchaError:n,...e,unsafeMetadata:e.unsafeMetadata?nM(e.unsafeMetadata):void 0};await this.#j.__internal_basePost({path:this.#j.pathRoot,body:r})})}async sendEmailCode(){return nE(this.#j,async()=>{await this.#j.__internal_basePost({body:{strategy:"email_code"},action:"prepare_verification"})})}async verifyEmailCode(e){let{code:t}=e;return nE(this.#j,async()=>{await this.#j.__internal_basePost({body:{strategy:"email_code",code:t},action:"attempt_verification"})})}async sendPhoneCode(e){let{phoneNumber:t,channel:i="sms"}=e;return nE(this.#j,async()=>{if(!this.#j.id){let{captchaToken:e,captchaWidgetType:i,captchaError:n}=await this.getCaptchaToken();await this.#j.__internal_basePost({path:this.#j.pathRoot,body:{phoneNumber:t,captchaToken:e,captchaWidgetType:i,captchaError:n}})}await this.#j.__internal_basePost({body:{strategy:"phone_code",channel:i},action:"prepare_verification"})})}async verifyPhoneCode(e){let{code:t}=e;return nE(this.#j,async()=>{await this.#j.__internal_basePost({body:{strategy:"phone_code",code:t},action:"attempt_verification"})})}async sso(e){let{strategy:t,redirectUrl:i,redirectCallbackUrl:n,unsafeMetadata:r,legalAccepted:s,oidcPrompt:a,enterpriseConnectionId:o,emailAddress:l,popup:c}=e;return nE(this.#j,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:nF.clerk.buildUrlWithAuth(n),actionCompleteRedirectUrl:u};if(c){let e=nT(nF.clerk,{redirectCallbackUrl:p.redirectUrl,redirectUrl:u});p.redirectUrl=e.redirectCallbackUrl,p.actionCompleteRedirectUrl=e.redirectUrl}let f=()=>this.#j.__internal_basePost({path:this.#j.pathRoot,body:{strategy:t,...p,unsafeMetadata:r,legalAccepted:s,oidcPrompt:a,enterpriseConnectionId:o,emailAddress:l,captchaToken:e,captchaWidgetType:d,captchaError:h}});await f().catch(async e=>{if(v(e)&&T(e))return await nF.clerk.__internal_environment.reload(),f();throw e});let{status:m,externalVerificationRedirectURL:g}=this.#j.verifications.externalAccount;"unverified"===m&&g&&(c?(await nO(nF.clerk,{popup:c,externalVerificationRedirectURL:g}),await this.#j.reload()):eF(g))})}async web3(e){let{strategy:t,unsafeMetadata:i,legalAccepted:n}=e,r=t.replace("web3_","").replace("_signature","");return nE(this.#j,async()=>{let e,s,a;switch(r){case"metamask":e=await tu().getMetamaskIdentifier(),s=tu().generateSignatureWithMetamask;break;case"coinbase_wallet":e=await tu().getCoinbaseWalletIdentifier(),s=tu().generateSignatureWithCoinbaseWallet;break;case"base":e=await tu().getBaseIdentifier(),s=tu().generateSignatureWithBase;break;case"okx_wallet":e=await tu().getOKXWalletIdentifier(),s=tu().generateSignatureWithOKXWallet;break;default:throw Error(`Unsupported Web3 provider: ${r}`)}let o=e||this.#j.web3wallet;await this._create({web3Wallet:o,unsafeMetadata:i,legalAccepted:n}),await this.#j.__internal_basePost({body:{strategy:t},action:"prepare_verification"});let{message:l}=this.#j.verifications.web3Wallet;l||tk("SignUp");try{a=await s({identifier:e,nonce:l})}catch(t){if("coinbase_wallet"===r&&4001===t.code)a=await s({identifier:e,nonce:l});else throw t}await this.#j.__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 nE(this.#j,async()=>{if(!this.#j.createdSessionId)throw Error("Cannot finalize sign-up without a created session.");this.#L=!0,await nF.clerk.setActive({session:this.#j.createdSessionId,navigate:t})})}}class nW extends tz{id;name;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.name=e.name),this}}class nD extends tz{pathRoot="tokens";jwt;static async create(e,t={},i={}){return new nD(await tz._fetch({method:"POST",path:e,body:t,search:i}),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 n$ extends tz{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=tM(e.updated_at),this.createdAt=tM(e.created_at)),this}}class nL extends tz{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=tM(e.updated_at),this.createdAt=tM(e.created_at)),this}}class nj extends tz{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 nj}constructor(e){super(),this.fromJSON(e)}path(){return this.pathRoot}isPrimaryIdentification=e=>{switch(e.constructor){case iW:return this.primaryEmailAddressId===e.id;case nm:return this.primaryPhoneNumberId===e.id;case nq:return this.primaryWeb3WalletId===e.id;default:return!1}};createEmailAddress=e=>{let{email:t}=e||{};return new iW({email_address:t},this.path()+"/email_addresses/").create()};createPasskey=()=>nf.registerPasskey();createPhoneNumber=e=>{let{phoneNumber:t}=e||{};return new nm({phone_number:t},this.path()+"/phone_numbers/").create()};createWeb3Wallet=e=>{let{web3Wallet:t}=e||{};return new nq({web3_wallet:t},this.path()+"/web3_wallets/").create()};createExternalAccount=async e=>{let{strategy:t,redirectUrl:i,additionalScopes:n}=e||{};return new i8((await tz._fetch({path:"/me/external_accounts",method:"POST",body:{strategy:t,redirect_url:i,additional_scope:n}}))?.response,this.path()+"/external_accounts")};createTOTP=async()=>new n$((await tz._fetch({path:"/me/totp",method:"POST"}))?.response);verifyTOTP=async({code:e})=>new n$((await tz._fetch({path:"/me/totp/attempt_verification",method:"POST",body:{code:e}}))?.response);disableTOTP=async()=>new ix((await tz._fetch({path:"/me/totp",method:"DELETE"}))?.response);createBackupCode=async()=>new nL((await tz._fetch({path:this.path()+"/backup_codes/",method:"POST"}))?.response);update=e=>this._basePatch({body:nM(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=>(i5.emit(i3,null),e));getSessions=async()=>{if(this.cachedSessionsWithActivities)return this.cachedSessionsWithActivities;let e=await nA.retrieve();return this.cachedSessionsWithActivities=e,e};setProfileImage=e=>{let{file:t}=e||{};return null===t?ni.delete(`${this.path()}/profile_image`):ni.create(`${this.path()}/profile_image`,{file:t})};getOrganizationInvitations=e=>nJ.retrieve(e);getOrganizationSuggestions=e=>nd.retrieve(e);getOrganizationMemberships=e=>nc.retrieve(e);leaveOrganization=async e=>new ix((await tz._fetch({path:`${this.path()}/organization_memberships/${e}`,method:"DELETE"}))?.response);initializePaymentMethod=e=>iu(e);addPaymentMethod=e=>ip(e);getPaymentMethods=e=>im(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 iW(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 nm(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 nq(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 i8(e,this.path()+"/external_accounts")),this.passkeys=(e.passkeys||[]).map(e=>new nf(e)),this.organizationMemberships=(e.organization_memberships||[]).map(e=>new nc(e)),this.enterpriseAccounts=(e.enterprise_accounts||[]).map(e=>new iZ(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=tM(e.last_sign_in_at)),e.legal_accepted_at&&(this.legalAcceptedAt=tM(e.legal_accepted_at)),this.updatedAt=tM(e.updated_at||void 0),this.createdAt=tM(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 nB{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 nJ extends tz{id;emailAddress;publicOrganizationData;publicMetadata={};status;role;createdAt;updatedAt;static async retrieve(e){return await tz._fetch({path:"/me/organization_invitations",method:"GET",search:t5(e)}).then(e=>{let{data:t,total_count:i}=e?.response;return{total_count:i,data:t.map(e=>new nJ(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=tM(e.created_at),this.updatedAt=tM(e.updated_at)),this}}let nK={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 nV extends tz{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:{...nK,name:"phone_number"},username:{...nK,name:"username"},web3_wallet:{...nK,name:"web3_wallet"},first_name:{...nK,name:"first_name"},last_name:{...nK,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:{...nK,name:"authenticator_app"},backup_code:{...nK,name:"backup_code"},passkey:{...nK,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 nq extends tz{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 iH(e.verification)),this}__internal_toSnapshot(){return{object:"web3_wallet",id:this.id,web3_wallet:this.web3Wallet,verification:this.verification.__internal_toSnapshot()}}}class nG extends tz{pathRoot="/waitlist";id="";updatedAt=null;createdAt=null;constructor(e){super(),this.fromJSON(e)}fromJSON(e){return e&&(this.id=e.id,this.updatedAt=tM(e.updated_at),this.createdAt=tM(e.created_at)),this}static async join(e){return new nG((await tz._fetch({path:"/waitlist",method:"POST",body:e}))?.response)}}function nH(e,t){var i,n;return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||(i=t,n=e,i.organizationMemberships.length!==n.organizationMemberships.length||i.organizationMemberships[0]?.updatedAt!==n.organizationMemberships[0]?.updatedAt)}function nX(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(iO.isClientResource(e))return e.id!==t.id||e.updatedAt.getTime()<t.updatedAt.getTime()||e.sessions.length!==t.sessions.length;if(nU.isSessionResource(e)){var i,n;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),n=t.user?.organizationMemberships?.find(t=>t.organization.id===e.lastActiveOrganizationId);return i?.permissions?.length!==n?.permissions?.length}(e,t)||(i=e,n=t,!!i.user!=!!n.user||!!i.user&&!!n.user&&nH(i.user,n.user))}if(nj.isUserResource(e))return nH(e,t)}catch{}return!0}(e,t)?e:t}let nY="__clerk_db_jwt";function nQ(e,t){let i=new URL(e),n=i.searchParams.get(nY);i.searchParams.delete(nY);let r=n||t;return r&&i.searchParams.set(nY,r),i}let nZ=e=>{let t=new URL(e);return t.searchParams.delete(nY),t},n0=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 n1(e){for(var t=1;t<arguments.length;t++){var i=arguments[t];for(var n in i)e[n]=i[n]}return e}var n3=function e(t,i){function n(e,n,r){if("undefined"!=typeof document){"number"==typeof(r=n1({},i,r)).expires&&(r.expires=new Date(Date.now()+864e5*r.expires)),r.expires&&(r.expires=r.expires.toUTCString()),e=encodeURIComponent(e).replace(/%(2[346B]|5E|60|7C)/g,decodeURIComponent).replace(/[()]/g,escape);var s="";for(var a in r)r[a]&&(s+="; "+a,!0!==r[a]&&(s+="="+r[a].split(";")[0]));return document.cookie=e+"="+t.write(n,e)+s}}return Object.create({set:n,get:function(e){if("undefined"!=typeof document&&(!arguments.length||e)){for(var i=document.cookie?document.cookie.split("; "):[],n={},r=0;r<i.length;r++){var s=i[r].split("="),a=s.slice(1).join("=");try{var o=decodeURIComponent(s[0]);if(n[o]=t.read(a,o),e===o)break}catch(e){}}return e?n[e]:n}},remove:function(e,t){n(e,"",n1({},t,{expires:-1}))},withAttributes:function(t){return e(this.converter,n1({},this.attributes,t))},withConverter:function(t){return e(n1({},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 n2(e){return{get:()=>n3.get(e),set(t,i={}){n3.set(e,t,i)},remove(t){n3.remove(e,t)}}}let n4=e=>"https:"===window.location.protocol||"None"===e&&void 0===window.safari&&(void 0!==window.isSecureContext?window.isSecureContext:"localhost"===window.location.hostname);function n5(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 n6=n2("__clerk_test_etld"),n9="__client_uat",n7="__session",n8=()=>{let e="None",t=n4(e);return{sameSite:e,secure:t,partitioned:t}};async function re(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:n}=await Promise.all([s.e("545"),s.e("811")]).then(s.t.bind(s,180,23)),{default:r}=await Promise.all([s.e("545"),s.e("811")]).then(s.t.bind(s,3413,23)),a=n(e);t=r.stringify(a).replace(/\+/gi,"-").replace(/\//gi,"_").substring(0,8)}return t}let rt=()=>{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=n4(e);return{sameSite:e,secure:t}};var ri=s(5945),rn=s.n(ri);class rr{lock=(function(e){let t=new(rn());return window.addEventListener("beforeunload",async()=>{await t.releaseLock(e)}),{acquireLockAndRun:async i=>{if("locks"in navigator&&isSecureContext){let t=new AbortController,n=setTimeout(()=>t.abort(),4999);return await navigator.locks.request(e,{signal:t.signal},async()=>(clearTimeout(n),await i())).catch(()=>!1)}if(await t.acquireLock(e,5e3))try{return await i()}finally{await t.releaseLock(e)}}}})("clerk.lock.refreshSessionToken");workerTimers=iF();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 rs{clerk;instanceType;clerkEventBus;poller=null;clientUat;sessionCookie;activeCookie;devBrowser;static async create(e,t,i,n){let r=await re(e.publishableKey),s=new rs(e,t,r,i,n);return await s.setup(),s}constructor(e,t,n,r,s){this.clerk=e,this.instanceType=r,this.clerkEventBus=s,i5.on(i1,({token:e})=>{this.updateSessionCookie(e&&e.getRawString()),this.setClientUatCookieForDevelopmentInstances()}),i5.on(i3,()=>this.handleSignOut()),this.refreshTokenOnFocus(),this.startPollingForToken(),this.clientUat=(e=>{let t=n2(n9),n=n2(el(n9,e));return{set:e=>{let r=n5(Date.now(),1),s="None",a=n4(s),o=function(e=window.location.hostname,t=n6){if(i)return i;if(["localhost","127.0.0.1","0.0.0.0"].includes(e))return e;let n=e.split(".");if(1===n.length)return e;for(let e=n.length-2;e>=0;e--){let r=n.slice(e).join(".");if(t.set("1",{domain:r}),"1"===t.get())return t.remove({domain:r}),i=r,r;t.remove({domain:r})}}(),l="0";e&&e.updatedAt&&e.signedInSessions.length>0&&(l=Math.floor(e.updatedAt.getTime()/1e3).toString()),n.remove(),t.remove(),n.set(l,{domain:o,expires:r,partitioned:a,sameSite:s,secure:a}),t.set(l,{domain:o,expires:r,partitioned:a,sameSite:s,secure:a})},get:()=>parseInt(n.get()||t.get()||"0",10)}})(n),this.sessionCookie=(e=>{let t=n2(n7),i=n2(el(n7,e)),n=()=>{let e=n8();t.remove(e),i.remove(e)};return{set:e=>{let r=n5(Date.now(),1),{sameSite:s,secure:a,partitioned:o}=n8();o&&n(),t.set(e,{expires:r,sameSite:s,secure:a,partitioned:o}),i.set(e,{expires:r,sameSite:s,secure:a,partitioned:o})},remove:n,get:()=>i.get()||t.get()}})(n),this.activeCookie=(()=>{let e=n2("clerk_active_context"),t={secure:n4("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 n,r,s=(n=n2(nY),r=n2(el(nY,e)),{get:()=>r.get()||n.get(),set:e=>{let t=n5(Date.now(),1),{sameSite:i,secure:s}=rt();r.set(e,{expires:t,sameSite:i,secure:s}),n.set(e,{expires:t,sameSite:i,secure:s})},remove:()=>{let e=rt();r.remove(e),n.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 n;if(!ep(t))return;i.onBeforeRequest(e=>{let t=a();t&&e?.url&&(e.url=nQ(e.url,t))}),i.onAfterResponse((e,t)=>{let i=t?.headers?.get("Clerk-Db-Jwt");i&&o(i)});let r=(n=(e=new URL(window.location.href)).searchParams.get(nY)||"",nZ(n0(e)).href!==e.href&&void 0!==globalThis.history&&globalThis.history.replaceState(null,"",nZ(n0(e))),n);if(r)return void o(r);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 w(e)):[]}((await c.json()).errors);e[0]?tw(e[0].longMessage):tw()}let d=await c.json();o(d?.id)},getDevBrowserJWT:a,setDevBrowserJWT:o,removeDevBrowserJWT:l}}({frontendApi:e.frontendApi,fapiClient:t,cookieSuffix:n})}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(`${t_} Missing dev browser jwt. Please contact support.`);return nQ(e,t)}async setupDevelopment(){await this.devBrowser.setup()}setupProduction(){this.devBrowser.clear()}startPollingForToken(){this.poller||(this.poller=new rr,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(v(e)||C(e)||(`${e.message}${e.name}`||"").toLowerCase().replace(/\s+/g,"").includes("networkerror")){if(O(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(":"),n=this.clerk.session?.id||"",r=this.clerk.organization?.id||"";return t===n&&i===r}getSessionCookie(){return this.sessionCookie.get()}}class ra{clerk;captchaChallenge;timers;constructor(e,t=new tx(e),i=iF()){this.clerk=e,this.captchaChallenge=t,this.timers=i}async start(){this.isEnabled()&&(await this.challengeAndSend(),this.timers.setInterval(()=>{this.challengeAndSend()},this.intervalInMs()))}async challengeAndSend(){if(!(!this.clerk.client||this.clientBypass()))try{let e=await this.captchaChallenge.invisible({action:"heartbeat"});await this.clerk.client.__internal_sendCaptchaToken(e)}catch{}}isEnabled(){return!!this.clerk.__internal_environment?.displayConfig?.captchaHeartbeat}clientBypass(){return this.clerk.client?.captchaBypass}intervalInMs(){return this.clerk.__internal_environment?.displayConfig?.captchaHeartbeatIntervalMs??6e5}}let ro=["/client","/waitlist"];class rl{async getBaseFapiProxyOptions(){let e=await tz.clerk.session?.getToken();if(!e)throw new I("No valid session token available",{code:"no_session_token"});return{pathPrefix:"",headers:{Authorization:`Bearer ${e}`,"Content-Type":"application/json"},credentials:"same-origin"}}async getAll(e){return tz._fetch({...await this.getBaseFapiProxyOptions(),method:"GET",path:"/api_keys",search:t5({...e,subject:e?.subject??tz.clerk.organization?.id??tz.clerk.user?.id??"",query:e?.query??""})}).then(e=>{let{data:t,total_count:i}=e;return{total_count:i,data:t.map(e=>new tF(e))}})}async create(e){return new tF(await tz._fetch({...await this.getBaseFapiProxyOptions(),path:"/api_keys",method:"POST",body:JSON.stringify({type:"api_key",name:e.name,subject:e.subject??tz.clerk.organization?.id??tz.clerk.user?.id??"",description:e.description,seconds_until_expiration:e.secondsUntilExpiration})}))}async revoke(e){return new tF(await tz._fetch({...await this.getBaseFapiProxyOptions(),method:"POST",path:`/api_keys/${e.apiKeyID}/revoke`,body:JSON.stringify({revocation_reason:e.revocationReason})}))}}let rc=new Map;class rd{#z=!1;load(e){let t=e?.protectConfig;if(t?.loaders&&Array.isArray(t.loaders)&&0!==t.loaders.length&&!this.#z){if(r())for(let e of(this.#z=!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",n=document.createElement(t);if(e.attributes)for(let[t,i]of Object.entries(e.attributes))switch(typeof i){case"string":case"number":case"boolean":n.setAttribute(t,String(i));break;default:B(`[protect] loader attribute is invalid type: ${t}=${i}`)}switch(e.textContent&&"string"==typeof e.textContent&&(n.textContent=e.textContent),i){case"head":document.head.appendChild(n);break;case"body":document.body.appendChild(n);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(n);return}B(`[protect] loader target is invalid: ${i}`)}}}class rh{signInResourceSignal=t9;signInErrorSignal=t7;signInFetchSignal=t8;signInSignal=ie;signUpResourceSignal=it;signUpErrorSignal=ii;signUpFetchSignal=ir;signUpSignal=is;__internal_effect=tQ;__internal_computed=tY;constructor(){i5.on("resource:update",this.onResourceUpdated),i5.on("resource:error",this.onResourceError),i5.on("resource:fetch",this.onResourceFetch)}onResourceError=e=>{e.resource instanceof nR&&this.signInErrorSignal({error:e.error}),e.resource instanceof nF&&this.signUpErrorSignal({error:e.error})};onResourceUpdated=e=>{if(e.resource instanceof nR){if(ru(this.signInResourceSignal().resource,e.resource))return;this.signInResourceSignal({resource:e.resource})}if(e.resource instanceof nF){if(ru(this.signUpResourceSignal().resource,e.resource))return;this.signUpResourceSignal({resource:e.resource})}};onResourceFetch=e=>{e.resource instanceof nR&&this.signInFetchSignal({status:e.status}),e.resource instanceof nF&&this.signUpFetchSignal({status:e.status})}}function ru(e,t){return!t?.id&&e&&e.__internal_future?.hasBeenFinalized===!1}let rp="cannot_render_billing_disabled",rf="cannot_render_user_missing",rm="cannot_render_organizations_disabled",rg="cannot_render_organization_missing",r_="cannot_render_single_session_enabled",rw={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 rb{static version="6.0.0-snapshot.v20251224145055";static sdkMetadata={name:"@clerk/clerk-js",version:"6.0.0-snapshot.v20251224145055"};static _billing;static _apiKeys;_checkout;client;session;organization;user;__internal_country;telemetry;__internal_state=new rh;internal_last_error=null;environment;#B;#J="";#K;#V;#q;#G;#H;#X=null;#Y;#Q;#Z;#ee="loading";#et=[];#ei=[];#en={};#er=null;#es=0;#ea=p();get __internal_queryClient(){return this.#B||Promise.all([s.e("662"),s.e("527")]).then(s.bind(s,250)).then(e=>e.QueryClient).then(e=>{this.#B||(this.#B=new e,this.#ea.emit("queryClientStatus","ready"))}),this.#B?{__tag:"clerk-rq-client",client:this.#B}:void 0}__internal_getCachedResources;__internal_createPublicCredentials;__internal_getPublicCredentials;__internal_isWebAuthnSupported;__internal_isWebAuthnAutofillSupported;__internal_isWebAuthnPlatformAuthenticatorSupported;__internal_setActiveInProgress=!1;get publishableKey(){return this.#J}get version(){return rb.version}set sdkMetadata(e){rb.sdkMetadata=e}get sdkMetadata(){return rb.sdkMetadata}get loaded(){return"degraded"===this.status||"ready"===this.status}get status(){return this.#ee}get isSatellite(){return!!tc()&&eX(this.#en.isSatellite,new URL(window.location.href),!1)}get domain(){if(tc()){let e=function(e=""){return(e||"").replace(/^.+:\/\//,"")}(eX(this.#K,new URL(window.location.href)));if("production"===this.#Z){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.#V,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.#Z}get isStandardBrowser(){return this.#en.standardBrowser||!1}get billing(){return rb._billing||(rb._billing=new t6),rb._billing}get apiKeys(){return rb._apiKeys||(rb._apiKeys=new rl),rb._apiKeys}__experimental_checkout(e){return this._checkout||(this._checkout=e=>(function(e,t){let i,n,r,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:n,planPeriod:r}=e;return`${t}-${i||"user"}-${n}-${r}`}({userId:e.user?.id||"",orgId:"organization"===a?e.organization?.id:void 0,planId:o,planPeriod:l}),d=rc.get(c);if(d)return d.signals.computedSignal();let h=(i=tX({resource:null}),n=tX({error:null}),r=tX({status:"idle"}),s=tY(()=>{let e=i().resource,t=n().error,s=r().status;return{errors:ia(t,{}),fetchStatus:s,checkout:e}}),{resourceSignal:i,errorSignal:n,fetchSignal:r,computedSignal:s}),u=new ic(h,{..."organization"===a?{orgId:e.organization?.id}:{},planId:o,planPeriod:l});return rc.set(c,{resource:u,signals:h}),h.computedSignal()})(this,e)),this._checkout(e)}__internal_getOption(e){return this.#en[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.#K=t?.domain,this.#V=t?.proxyUrl,this.environment=i7.getInstance(),this.#Z=i.instanceType,this.#J=e,this.#Q=function(e){let t=[],i=[];async function n(e){for await(let i of["undefined"!=typeof window&&window.__internal_onBeforeRequest,...t].filter(e=>e))if(await i(e)===!1)return!1;return!0}async function r(e,t){for await(let n of["undefined"!=typeof window&&window.__internal_onAfterResponse,...i].filter(e=>e))if(await n(e,t)===!1)return!1;return!0}function s({method:t,path:i,sessionId:n,search:r,rotatingTokenNonce:s}){let a=new URLSearchParams(r);return a.append("__clerk_api_version","2025-11-10"),a.append("_clerk_js_version","6.0.0-snapshot.v20251224145055"),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&&!ro.some(e=>i.startsWith(e))&&n&&a.append("_clerk_session_id",n),ed([...a.entries()].reduce((e,[t,i])=>(e[t]=i.includes(",")?i.split(","):i,e),{}))}function a(t){let{path:i,pathPrefix:n="v1"}=t;if(e.proxyUrl){let r=new URL(e.proxyUrl),a=r.pathname.slice(1);return a.endsWith("/")&&(a=a.slice(0,-1)),eg({base:r.origin,pathname:`${a}/${n}${i}`,search:s(t)},{stringify:!1})}let r="production"===e.instanceType?e.domain:"";return eg({base:`https://${r||e.frontendApi}`,pathname:`${n}${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,n]of Object.entries(e))void 0!==n&&(t[i]=n);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 n(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(`${t_} 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 r(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.#ea.emit(f,"loading"),this.#ea.prioritizedOn(f,e=>this.#ee=e),tz.clerk=this,this.#G=new rd}getFapiClient=()=>this.#Q;load=async e=>{if(e4.info("load() start",{},"clerk"),!this.loaded){if("development"!==this.#Z||e?.unsafe_disableDevelopmentModeConsoleWarning||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.#en=this.#eo(e),this.#en.clerkUiCtor&&(this.#Y=Promise.resolve(this.#en.clerkUiCtor).then(e=>new e(()=>this,()=>this.environment,this.#en,new te))),"development"===this.#Z&&(this.#en.routerPush||this.#en.routerReplace)&&(!this.#en.routerPush||!this.#en.routerReplace)){let e=this.#en.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.`)}i5.on(i4,()=>{this.#el(this.session),this.#ec()}),this.#en.sdkMetadata&&(rb.sdkMetadata=this.#en.sdkMetadata),!1!==this.#en.telemetry&&(this.telemetry=new eB({clerkVersion:rb.version,samplingRate:1,perEventSampling:!this.#en.__internal_keyless_claimKeylessApplicationUrl&&void 0,publishableKey:this.publishableKey,...this.#en.telemetry}),this.#en.appearance&&this.telemetry.record({event:"THEME_USAGE",eventSamplingRate:1,payload:function(e){let t;if(!e||"object"!=typeof e)return{};let i=e.theme;if(!i)return{};if(Array.isArray(i))for(let e of i){let i=eH(e);if(i){t=i;break}}else t=eH(i);return{themeName:t}}(this.#en.appearance)}));try{this.#en.standardBrowser?await this.#ed():await this.#eh();let e=this.#en.telemetry,t=!1!==e&&!e?.disabled,i=!!this.#en.__internal_keyless_claimKeylessApplicationUrl,n=!!this.environment?.clientDebugMode,r=this.environment?.isProduction?.()??!1,s=n||i&&!r,a=i&&!n?"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.#G?.load(this.environment),e4.info("load() complete",{},"clerk")}catch(e){throw this.#ea.emit(f,"error"),e4.error("load() failed",{error:e},"clerk"),e}}};#eu(){let e;return!!(!this.#en.signUpUrl&&this.#en.signInUrl&&(e=this.#en.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.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:eY,n="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:eY,r=e&&"object"==typeof e?e:t||{},s=r?.redirectUrl||this.buildAfterSignOutUrl();e4.debug("signOut() start",{hasClient:!!this.client,multiSessionCount:this.client?.signedInSessions.length??0,redirectUrl:s,sessionTarget:r?.sessionId??null},"clerk");let a="function"==typeof e?e:void 0,o=async()=>{let e=tt(this.#en.standardBrowser);i5.emit(i3,null),this.#ep(),await e.track(async()=>{a?await a():await this.navigate(s)}),e.isUnloading()||(this.#el(),this.#ec(),await n())};if(await i(),!r.sessionId||1===this.client.signedInSessions.length){this.#en.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===r.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.#Y),this.#Y.then(e=>e.ensureMounted()).then(t=>t.openModal("googleOneTap",e||{})),this.telemetry?.record(eG("GoogleOneTap",e))};closeGoogleOneTap=()=>{this.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeModal("googleOneTap"))};openSignIn=e=>{if(x(this,this.environment)){if("development"===this.#Z)throw new I(eR.cannotOpenSignInOrSignUp,{code:r_});return}this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(t=>t.openModal("signIn",e||{}));let t={withSignUp:e?.withSignUp??this.#eu()};this.telemetry?.record(eG("SignIn",e,t))};closeSignIn=()=>{this.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signIn"))};__internal_openCheckout=e=>{if(R(this,this.environment)){if("development"===this.#Z)throw new I(eR.cannotRenderAnyBillingComponent("Checkout"),{code:rp});return}if(!this.user){if("development"===this.#Z)throw new I(eR.cannotOpenCheckout,{code:rf});return}this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(t=>t.openDrawer("checkout",e||{}))};__internal_closeCheckout=()=>{this.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("checkout"))};__internal_openPlanDetails=e=>{if(R(this,this.environment)){if("development"===this.#Z)throw new I(eR.cannotRenderAnyBillingComponent("PlanDetails"),{code:rp});return}this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(t=>t.openDrawer("planDetails",e||{})),this.telemetry?.record(eG("PlanDetails",e))};__internal_closePlanDetails=()=>{this.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("planDetails"))};__internal_openSubscriptionDetails=e=>{this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(t=>t.openDrawer("subscriptionDetails",e||{}))};__internal_closeSubscriptionDetails=()=>{this.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeDrawer("subscriptionDetails"))};__internal_openReverification=e=>{if(!this.user){if("development"===this.#Z)throw new I(eR.cannotOpenUserProfile,{code:rf});return}this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(t=>t.openModal("userVerification",e||{})),this.telemetry?.record(eG("UserVerification",e))};__internal_closeReverification=()=>{this.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userVerification"))};__internal_attemptToEnableEnvironmentSetting=e=>{let{for:t,caller:i}=e;if(this.user||"development"!==this.#Z||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.#Z&&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.#Y),this.#Y.then(e=>e.ensureMounted({preloadHint:"EnableOrganizationsPrompt"})).then(t=>t.openModal("enableOrganizationsPrompt",e||{})),this.telemetry?.record(eq("EnableOrganizationsPrompt",e))};__internal_closeEnableOrganizationsPrompt=()=>{this.assertComponentsReady(this.#Y),this.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeModal("enableOrganizationsPrompt"))};__internal_openBlankCaptchaModal=()=>(this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(e=>e.openModal("blankCaptcha",{})));__internal_closeBlankCaptchaModal=()=>(this.assertComponentsReady(this.#Y),this.#Y.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.#Z)throw new I(eR.cannotOpenSignInOrSignUp,{code:r_});return}this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(t=>t.openModal("signUp",e||{})),this.telemetry?.record(eG("SignUp",e))};closeSignUp=()=>{this.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeModal("signUp"))};openUserProfile=e=>{if(!this.user){if("development"===this.#Z)throw new I(eR.cannotOpenUserProfile,{code:rf});return}this.assertComponentsReady(this.#Y),this.#Y.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.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeModal("userProfile"))};openOrganizationProfile=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"OrganizationProfile",onClose:()=>{throw new I(eR.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:rm})}});if(t){if(!this.organization){if("development"===this.#Z)throw new I(eR.cannotRenderComponentWhenOrgDoesNotExist,{code:rg});return}this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(t=>t.openModal("organizationProfile",e||{})),this.telemetry?.record(eG("OrganizationProfile",e))}};closeOrganizationProfile=()=>{this.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeModal("organizationProfile"))};openCreateOrganization=e=>{let{isEnabled:t}=this.__internal_attemptToEnableEnvironmentSetting({for:"organizations",caller:"CreateOrganization",onClose:()=>{throw new I(eR.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:rm})}});t&&(this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(t=>t.openModal("createOrganization",e||{})),this.telemetry?.record(eG("CreateOrganization",e)))};closeCreateOrganization=()=>{this.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeModal("createOrganization"))};openWaitlist=e=>{this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(t=>t.openModal("waitlist",e||{})),this.telemetry?.record(eG("Waitlist",e))};closeWaitlist=()=>{this.#Y?.then(e=>e.ensureMounted()).then(e=>e.closeModal("waitlist"))};mountSignIn=(e,t)=>{this.assertComponentsReady(this.#Y);let i="SignIn";this.#Y.then(e=>e.ensureMounted()).then(n=>n.mountComponent({name:i,appearanceKey:"signIn",node:e,props:t}));let n={withSignUp:t?.withSignUp??this.#eu()};this.telemetry?.record(eq(i,t,n))};unmountSignIn=e=>{this.#Y?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserAvatar=(e,t)=>{this.assertComponentsReady(this.#Y);let i="UserAvatar";this.#Y.then(e=>e.ensureMounted()).then(n=>n.mountComponent({name:i,appearanceKey:"userAvatar",node:e,props:t})),this.telemetry?.record(eq(i,t))};unmountUserAvatar=e=>{this.#Y?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountSignUp=(e,t)=>{this.assertComponentsReady(this.#Y);let i="SignUp";this.#Y.then(e=>e.ensureMounted()).then(n=>n.mountComponent({name:i,appearanceKey:"signUp",node:e,props:t})),this.telemetry?.record(eq(i,t))};unmountSignUp=e=>{this.#Y?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserProfile=(e,t)=>{if(!this.user){if("development"===this.#Z)throw new I(eR.cannotRenderComponentWhenUserDoesNotExist,{code:rf});return}this.assertComponentsReady(this.#Y);let i="UserProfile";this.#Y.then(e=>e.ensureMounted()).then(n=>n.mountComponent({name:i,appearanceKey:"userProfile",node:e,props:t}));let n=(t?.customPages?.length||0)>0?{customPages:!0}:void 0;this.telemetry?.record(eq(i,t,n))};unmountUserProfile=e=>{this.#Y?.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 I(eR.cannotRenderAnyOrganizationComponent("OrganizationProfile"),{code:rm})}});if(!i)return;let n=!!this.user;if(!this.organization&&n){if("development"===this.#Z)throw new I(eR.cannotRenderComponentWhenOrgDoesNotExist,{code:rg});return}this.assertComponentsReady(this.#Y);let r="OrganizationProfile";this.#Y.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:r,appearanceKey:"userProfile",node:e,props:t})),this.telemetry?.record(eq(r,t))};unmountOrganizationProfile=e=>{this.#Y?.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 I(eR.cannotRenderAnyOrganizationComponent("CreateOrganization"),{code:rm})}});if(!i)return;this.assertComponentsReady(this.#Y);let n="CreateOrganization";this.#Y.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:n,appearanceKey:"createOrganization",node:e,props:t})),this.telemetry?.record(eq(n,t))};unmountCreateOrganization=e=>{this.#Y?.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 I(eR.cannotRenderAnyOrganizationComponent("OrganizationSwitcher"),{code:rm})}});if(!i)return;this.assertComponentsReady(this.#Y);let n="OrganizationSwitcher";this.#Y.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:n,appearanceKey:"organizationSwitcher",node:e,props:t})),this.telemetry?.record(eq(n,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationSwitcher=e=>{this.#Y?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__experimental_prefetchOrganizationSwitcher=()=>{this.assertComponentsReady(this.#Y),this.#Y.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 I(eR.cannotRenderAnyOrganizationComponent("OrganizationList"),{code:rm})}});if(!i)return;this.assertComponentsReady(this.#Y);let n="OrganizationList";this.#Y.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:n,appearanceKey:"organizationList",node:e,props:t})),this.telemetry?.record(eq(n,{...t,forceOrganizationSelection:this.environment?.organizationSettings.forceOrganizationSelection}))};unmountOrganizationList=e=>{this.#Y?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountUserButton=(e,t)=>{this.assertComponentsReady(this.#Y);let i="UserButton";this.#Y.then(e=>e.ensureMounted()).then(n=>n.mountComponent({name:i,appearanceKey:"userButton",node:e,props:t}));let n={...t?.customMenuItems?.length||0?{customItems:!0}:void 0,...t?.__experimental_asStandalone?{standalone:!0}:void 0};this.telemetry?.record(eq(i,t,n))};unmountUserButton=e=>{this.#Y?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountWaitlist=(e,t)=>{this.assertComponentsReady(this.#Y);let i="Waitlist";this.#Y.then(e=>e.ensureMounted()).then(n=>n.mountComponent({name:i,appearanceKey:"waitlist",node:e,props:t})),this.telemetry?.record(eq(i,t))};unmountWaitlist=e=>{this.#Y?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountPricingTable=(e,t)=>{if(R(this,this.environment)){if("development"===this.#Z)throw new I(eR.cannotRenderAnyBillingComponent("PricingTable"),{code:rp});return}this.assertComponentsReady(this.#Y);let i="PricingTable";this.#Y.then(e=>e.ensureMounted()).then(n=>n.mountComponent({name:i,appearanceKey:"pricingTable",node:e,props:t})),this.telemetry?.record(eq(i,t))};unmountPricingTable=e=>{this.#Y?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};__internal_mountOAuthConsent=(e,t)=>{this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:"OAuthConsent",appearanceKey:"__internal_oauthConsent",node:e,props:t}))};__internal_unmountOAuthConsent=e=>{this.#Y?.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.#Z)throw new I(eR.cannotRenderAPIKeysComponent,{code:"cannot_render_api_keys_disabled"});return}if(this.organization&&M(this,this.environment)){if("development"===this.#Z)throw new I(eR.cannotRenderAPIKeysComponentForOrgWhenDisabled,{code:"cannot_render_api_keys_org_disabled"});return}if(z(this,this.environment)){if("development"===this.#Z)throw new I(eR.cannotRenderAPIKeysComponentForUserWhenDisabled,{code:"cannot_render_api_keys_user_disabled"});return}this.assertComponentsReady(this.#Y);let n="APIKeys";this.#Y.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:n,appearanceKey:"apiKeys",node:e,props:t})),this.telemetry?.record(eq(n,t))};unmountAPIKeys=e=>{this.#Y?.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 I(eR.cannotRenderAnyOrganizationComponent("TaskChooseOrganization"),{code:rm})}});if(!i)return;this.assertComponentsReady(this.#Y);let n="TaskChooseOrganization";this.#Y.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:n,appearanceKey:"taskChooseOrganization",node:e,props:t})),this.telemetry?.record(eq(n,t))};unmountTaskChooseOrganization=e=>{this.#Y?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};mountTaskResetPassword=(e,t)=>{this.assertComponentsReady(this.#Y),this.#Y.then(e=>e.ensureMounted()).then(i=>i.mountComponent({name:"TaskResetPassword",appearanceKey:"taskResetPassword",node:e,props:t})),this.telemetry?.record(eq("TaskResetPassword",t))};unmountTaskResetPassword=e=>{this.#Y?.then(e=>e.ensureMounted()).then(t=>t.unmountComponent({node:e}))};setActive=async e=>{let{organization:t,redirectUrl:i,navigate:n}=e,{session:r}=e;this.__internal_setActiveInProgress=!0,e4.debug("setActive() start",{hasClient:!!this.client,sessionTarget:"string"==typeof r?r:r?.id??r??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===r&&!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 r&&(r=this.client.sessions.find(e=>e.id===r)||null);let o="undefined"!=typeof window&&"function"==typeof window.__internal_onBeforeSetActive?window.__internal_onBeforeSetActive:eY,l="undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:eY,d=void 0===r?this.session:r;d?.status==="pending"&&(s={...this.#en,...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,n=null===i;if(this.environment?.organizationSettings?.forceOrganizationSelection&&n)return;d.lastActiveOrganizationId=i}}d?.status!=="pending"&&await o(null===d?"sign-out":void 0),(tc()&&globalThis.document.hasFocus()||!this.#en.standardBrowser)&&(await this.#ef(d),d=this.#em(d?.id)),await d?.getToken()||(c()||e4.warn("Token is null when setting active session (offline)",{sessionId:d?.id},"clerk"),i5.emit(i1,{token:null}));let u=tt(this.#en.standardBrowser),p=d?.status==="pending"&&d?.currentTask&&this.#en.taskUrls?.[d?.currentTask.key];if((i||p||n)&&await u.track(async()=>{if(this.client){if(d?.status!=="pending"&&this.#ep(),p){let e=i?eg({base:p,hashSearchParams:{redirectUrl:i}},{stringify:!0}):p;await this.navigate(e)}else if(n&&d)await n({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.#el(d),this.#ec(),d?.status!=="pending"&&await l()}finally{this.__internal_setActiveInProgress=!1}};addListener=e=>{var t;let i;return t=e,e=e=>{var n;i||={...e},t(i={...{client:nX((n=i).client,e.client),session:nX(n.session,e.session),user:nX(n.user,e.user),organization:nX(n.organization,e.organization)}})},this.#et.push(e),this.client&&e({client:this.client,session:this.session,user:this.user,organization:this.organization}),()=>{this.#et=this.#et.filter(t=>t!==e)}};on=(...e)=>{this.#ea.on(...e)};off=(...e)=>{this.#ea.off(...e)};__internal_addNavigationListener=e=>(this.#ei.push(e),()=>{this.#ei=this.#ei.filter(t=>t!==e)});navigate=async(e,t)=>{if(!e||!tc())return;setTimeout(()=>{this.#eg()},0);let i=new URL(e,window.location.href);this.#e_.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 n=t?.replace&&this.#en.routerReplace?this.#en.routerReplace:this.#en.routerPush;if(e4.info(`Clerk is navigating to: ${i}`),this.#en.routerDebug&&console.log(`Clerk is navigating to: ${i}`),"null"!==i.origin&&i.origin!==window.location.origin||!n)return void eF(i);let r={...t?.metadata?{__internal_metadata:t?.metadata}:{},windowNavigate:eF};return await n(e_(i),r)};buildUrlWithAuth(e){if("production"===this.#Z)return e;let t=new URL(e,window.location.origin);return t.origin!==window.location.origin&&this.#q?this.#q.decorateUrlWithDevBrowserToken(t).href:t.href}buildSignInUrl(e){return this.#ew("signInUrl",{...e,redirectUrl:e?.redirectUrl||window.location.href},e?.initialValues)}buildSignUpUrl(e){return this.#ew("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.#en,{},e).getAfterSignInUrl())}buildAfterSignUpUrl({params:e}={}){return this.buildUrlWithAuth(new eS(this.#en,{},e).getAfterSignUpUrl())}buildAfterSignOutUrl(){return this.#en.afterSignOutUrl?this.buildUrlWithAuth(this.#en.afterSignOutUrl):"/"}buildNewSubscriptionRedirectUrl(){return this.#en.newSubscriptionRedirectUrl?this.#en.newSubscriptionRedirectUrl:this.buildAfterSignInUrl()}buildWaitlistUrl(e){return this.environment&&this.environment.displayConfig?eg({base:this.#en.waitlistUrl||this.environment.displayConfig.waitlistUrl,hashSearchParams:[new URLSearchParams(e?.initialValues||{})]},{stringify:!0}):""}buildAfterMultiSessionSingleSignOutUrl(){return this.environment?this.#en.afterMultiSessionSingleSignOutUrl?this.buildUrlWithAuth(this.#en.afterMultiSessionSingleSignOutUrl):this.#en.signInUrl?this.buildUrlWithAuth(eg({base:this.#en.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.#en.taskUrls?.[t.key];return i||eg({base:this.buildSignInUrl(e),hashPath:eO(t)},{stringify:!0})}#eb=async()=>{if(!tc())return;let e=new URLSearchParams({[F]:"true"}),t=eI(W);t&&eN(t)||function(){throw Error(`${t_} 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 A("expired");if("client_mismatch"===i)throw new A("client_mismatch");if("verified"!==i)throw new A("failed");let n=eI("__clerk_created_session"),{signIn:r,signUp:s,sessions:a}=this.client,o=a.some(e=>e.id===n),l="needs_second_factor"===r.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:n,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:n,signUp:r}=this.client,s="identifier"in(e||{})?e:n,a="missingFields"in(e||{})?e:r,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:n})=>{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:r}=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=>()=>n(e),d=c(e.signInUrl||r.signInUrl),h=c(e.signUpUrl||r.signUpUrl),u=c(e.firstFactorUrl||eg({base:r.signInUrl,hashPath:"/factor-one"},{stringify:!0})),p=c(e.secondFactorUrl||eg({base:r.signInUrl,hashPath:"/factor-two"},{stringify:!0})),f=c(e.resetPasswordUrl||eg({base:r.signInUrl,hashPath:"/reset-password"},{stringify:!0})),m=new eS(this.#en,e),g=c(e.continueSignUpUrl||eg({base:r.signUpUrl,hashPath:"/continue"},{stringify:!0})),_=({missingFields:t})=>t.length?g():(({signUp:e,verifyEmailPath:t,verifyPhonePath:i,continuePath:n,navigate:r,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 r(t,{searchParams:s});if(e.unverifiedFields?.includes("phone_number")&&i)return r(i,{searchParams:s});if(n)return r(n,{searchParams:s})}})({signUp:i,verifyEmailPath:e.verifyEmailAddressUrl||eg({base:r.signUpUrl,hashPath:"/verify-email-address"},{stringify:!0}),verifyPhonePath:e.verifyPhoneNumberUrl||eg({base:r.signUpUrl,hashPath:"/verify-phone-number"},{stringify:!0}),navigate:n}),w=e.signInUrl||r.signInUrl,b=e.signUpUrl||r.signUpUrl,y=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 y({session:e,baseUrl:w,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 y({session:e,baseUrl:b,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 y({session:e,baseUrl:b,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 y({session:e,baseUrl:b,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 y({session:e,baseUrl:S?b:w,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:n}=this.client,r=e=>t&&"function"==typeof t?t(e):this.navigate(e);return this._handleRedirectCallback(e,{signUp:n,signIn:i,navigate:r})};handleUnauthenticated=async(e={broadcast:!0})=>{if(this.client&&this.session)try{let t=await iO.getOrCreateInstance().fetch();if(this.updateClient(t),this.session)return;return e.broadcast&&i5.emit(i3,null),this.setActive({session:null})}catch(e){if(v(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(v(t)&&"external_account_not_found"===t.errors[0].code)return this.client?.signUp.create({strategy:"google_one_tap",token:e.token,legalAccepted:e.legalAccepted});throw t});authenticateWithMetamask=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_metamask_signature"})};authenticateWithCoinbaseWallet=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_coinbase_wallet_signature"})};authenticateWithBase=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_base_signature"})};authenticateWithOKXWallet=async(e={})=>{await this.authenticateWithWeb3({...e,strategy:"web3_okx_wallet_signature"})};authenticateWithSolana=async e=>{await this.authenticateWithWeb3({...e,strategy:"web3_solana_signature"})};authenticateWithWeb3=async({redirectUrl:e,signUpContinueUrl:t,customNavigate:i,unsafeMetadata:n,strategy:r,legalAccepted:s,secondFactorUrl:a,walletName:o})=>{let l,c;if(!this.client||!this.environment)return;let{displayConfig:d}=this.environment,h=r.replace("web3_","").replace("_signature",""),u=await tu().getWeb3Identifier({provider:h,walletName:o});switch(h){case"metamask":l=tu().generateSignatureWithMetamask;break;case"base":l=tu().generateSignatureWithBase;break;case"coinbase_wallet":l=tu().generateSignatureWithCoinbaseWallet;break;case"solana":if(!o)throw new I("Wallet name is required for Solana authentication.",{code:"web3_solana_wallet_name_required"});l=e=>tu().generateSignatureWithSolana({...e,walletName:o});break;default:l=tu().generateSignatureWithOKXWallet}let p=e=>()=>i&&"function"==typeof i?i(e):this.navigate(e),f=p(a||eg({base:d.signInUrl,hashPath:"/factor-two"},{stringify:!0})),m=p(t||eg({base:d.signUpUrl,hashPath:"/continue"},{stringify:!0}));try{c=await this.client.signIn.authenticateWithWeb3({identifier:u,generateSignature:l,strategy:r,walletName:o})}catch(e){if(tr(e,"form_identifier_not_found"))c=await this.client.signUp.authenticateWithWeb3({identifier:u,generateSignature:l,unsafeMetadata:n,strategy:r,legalAccepted:s,walletName:o}),t&&"missing_requirements"===c.status&&"verified"===c.verifications.web3Wallet.status&&await m();else throw e}let g=async({session:e,redirectUrl:t})=>{e.currentTask?await eE(e,{baseUrl:d.signInUrl,navigate:this.navigate}):await this.navigate(t)};switch(c.status){case"needs_second_factor":await f();break;case"complete":c.createdSessionId&&await this.setActive({session:c.createdSessionId,navigate:async({session:t})=>{await g({session:t,redirectUrl:e??this.buildAfterSignInUrl()})}});break;default:return}};createOrganization=async({name:e,slug:t})=>no.create({name:e,slug:t});getOrganization=async e=>no.get(e);joinWaitlist=async({emailAddress:e})=>nG.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.#en.selectInitialSession?this.#en.selectInitialSession(e):this.#ey(e);this.#el(t)}if(this.client=e,this.session){let e=this.#em(this.session.id);"active"===this.session.status&&e?.status==="pending"&&("undefined"!=typeof window&&"function"==typeof window.__internal_onAfterSetActive?window.__internal_onAfterSetActive:eY)(),this.#el(e),this.session?.lastActiveToken||c()||e4.warn("No last active token when updating client (offline)",{sessionId:this.session?.id},"clerk"),i5.emit(i1,{token:this.session?.lastActiveToken})}this.#ec()};get __internal_environment(){return this.environment}__internal_setEnvironment=async e=>{this.environment=new i7(e)};__internal_onBeforeRequest=e=>{this.#Q.onBeforeRequest(e)};__internal_onAfterResponse=e=>{this.#Q.onAfterResponse(e)};__internal_updateProps=e=>{let t={...e,options:this.#eo({...this.#en,...e.options})};return this.#Y?.then(e=>e.ensureMounted()).then(e=>e.updateProps(t))};__internal_navigateWithError(e,t){return this.__internal_last_error=t,this.navigate(e)}#ev=()=>{let e=new URLSearchParams({[W]:window.location.href});return eg({base:this.#en.signInUrl,searchParams:e},{stringify:!0})};#ek=()=>{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()||""};#eS=()=>"true"!==eI(F)&&!!this.isSatellite&&!!this.#q?.isSignedOut();#eU=()=>"production"!==this.#Z&&!this.isSatellite&&!!eI(W);#eA=async()=>{"development"===this.instanceType?await this.navigate(this.#ev()):"production"===this.instanceType&&await this.navigate(this.#ek())};#eI=(e,t)=>{let i;try{i=new URL(e)}catch{throw Error(`${t_} The signInUrl needs to have a absolute url format.`)}i.origin===t&&function(){throw Error(`${t_} The signInUrl needs to be on a different origin than your satellite application.`)}()};#eC=()=>{this.isSatellite&&("development"!==this.#Z||this.#en.signInUrl||function(){throw Error(`${t_} Missing signInUrl. A satellite application needs to specify the signInUrl for development instances.`)}(),this.proxyUrl||this.domain||function(){throw Error(`${t_} Missing domain and proxyUrl. A satellite application needs to specify a domain or a proxyUrl.`)}(),this.#en.signInUrl&&this.#eI(this.#en.signInUrl,window.location.origin))};#ed=async()=>{if(this.#q=await rs.create(this,this.#Q,this.#Z,this.#ea),this.#eC(),this.#eS())return void await this.#eA();if(this.#eU())return void await this.#eb();this.#er=(()=>{if(!r())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.#X=new BroadcastChannel("clerk")),this.#eP();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.#Z&&!e,i=0,n=0;for(;n<2;){n++;try{var s;let e=i7.getInstance().fetch({touch:t}).then(e=>this.updateEnvironment(e)).catch(()=>{++i;let e=tg.getItem(tp,null);e&&this.updateEnvironment(new i7(e))}),n=async()=>iO.getOrCreateInstance().fetch().then(e=>this.updateClient(e)).catch(async e=>{if(O(e))throw e;++i;let t=this.#q?.getSessionCookie(),n=function(e){let t;try{t=new nD({jwt:e||"",object:"token",id:void 0})}catch{t=null}if(iO.clearInstance(),!t?.jwt)return iO.getOrCreateInstance({object:"client",last_active_session_id:null,id:"client_init",sessions:[]});let{sessionId:i,userId:n,orgId:r,orgRole:s,orgPermissions:a,orgSlug:o,factorVerificationAge:l}=(e=>{let t,i,n,r,s=e.fva??null,a=e.sts??null;if(2===e.v){if(e.o){t=e.o?.id,n=e.o?.slg,e.o?.rol&&(i=`org:${e.o?.rol}`);let{org:s}=nk(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});r=function({features:e,permissions:t,featurePermissionMap:i}){if(!e||!t||!i)return[];let n=[];for(let r=0;r<e.length;r++){let s=e[r];if(r>=i.length)continue;let a=i[r];if(a)for(let e=0;e<a.length;e++)1===a[e]&&n.push(`org:${s}:${t[e]}`)}return n}({features:s,featurePermissionMap:o,permissions:a})}}else t=e.org_id,i=e.org_role,n=e.org_slug,r=e.org_permissions;return{sessionClaims:e,sessionId:e.sid,sessionStatus:a,actor:e.act,userId:e.sub,orgId:t,orgRole:i,orgSlug:n,orgPermissions:r,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:r||null,last_active_token:{id:void 0,object:"token",jwt:e},factor_verification_age:l||null,public_user_data:{user_id:n},user:{object:"user",id:n,organization_memberships:r&&o&&s?[{object:"organization_membership",id:r,role:s,permissions:a||[],organization:{object:"organization",id:r,name:o,slug:o,members_count:1,max_allowed_memberships:1}}]:[]}}]};return iO.getOrCreateInstance(c)}(t);return this.updateClient(n),this.#q?.stopPollingForToken(),await this.session?.getToken({skipCache:!0}).catch(()=>null).finally(()=>{this.#q?.startPollingForToken()}),null}),[,r]=await (s=[e,n()],Promise.all(Array.from(s).map(e=>e.then(e=>({status:"fulfilled",value:e}),e=>({status:"rejected",reason:e})))));if("rejected"===r.status){let e=r.reason;if(tr(e,"requires_captcha"))await n();else throw e}if(this.#q?.setClientUatCookieForDevelopmentInstances(),await this.#eT())return;break}catch(e){if(tr(e,"dev_browser_unauthenticated"))await this.#q.handleUnauthenticatedDevBrowser();else if(!c())return void console.warn(e);else throw e}n>=2&&function(){throw Error(`${t_} Something went wrong initializing Clerk.`)}()}this.#H=new ra(this),this.#H.start(),this.#eO(),this.#eE(),this.#ex(),this.#ea.emit(f,i>0?"degraded":"ready")};shouldFallbackToCachedResources=()=>!!this.__internal_getCachedResources;#eh=async()=>{let e,t,i=this.shouldFallbackToCachedResources()?1:void 0,n=0;try{[e,t]=await Promise.all([i7.getInstance().fetch({touch:!1,fetchMaxTries:i}),iO.getOrCreateInstance().fetch({fetchMaxTries:i})])}catch(i){if(C(i)&&"network_error"===i.code&&this.shouldFallbackToCachedResources()){let i=await this.__internal_getCachedResources?.();e=new i7(i?.environment),iO.clearInstance(),t=iO.getOrCreateInstance(i?.client),++n}else throw i}this.updateClient(t),this.updateEnvironment(e),this.#ea.emit(f,n>0?"degraded":"ready")};__internal_reloadInitialResources=async()=>{let[e,t]=await Promise.all([i7.getInstance().fetch({touch:!1,fetchMaxTries:1}),iO.getOrCreateInstance().fetch({fetchMaxTries:1})]);this.updateClient(t),this.updateEnvironment(e),this.#ec()};#ey=e=>{if(e.lastActiveSessionId){let t=e.signedInSessions.find(t=>t.id===e.lastActiveSessionId);if(t)return t}return e.signedInSessions[0]||null};#eP=()=>{r()&&(this.#er?.onPageFocus(()=>{this.session&&!(!(this.environment&&!this.environment.authConfig.singleSessionMode)&&this.#es>Date.now())&&(this.#es=Date.now()+5e3,this.#en.touchSession&&this.#ef(this.session))}),this.#X?.addEventListener("message",e=>{e.data?.type==="signout"&&this.handleUnauthenticated({broadcast:!1})}),i5.on(i3,()=>{this.#X?.postMessage({type:"signout"})}),i5.on(i2,()=>{tg.setItem(tp,this.environment?.__internal_toSnapshot(),864e5)}))};#ef=async e=>{if(!e)return Promise.resolve();await e.touch().catch(e=>{O(e)&&this.handleUnauthenticated()})};#ec=()=>{if(this.client)for(let e of this.#et)e({client:this.client,session:this.session,user:this.user,organization:this.organization})};#eg=()=>{for(let e of this.#ei)e()};#ep=()=>{this.session=void 0,this.organization=void 0,this.user=void 0,this.#ec()};#eR=()=>(this.session?.user.organizationMemberships||[]).map(e=>e.organization).find(e=>e.id===this.session?.lastActiveOrganizationId)||null;#el=e=>{this.session=e||null,this.organization=this.#eR(),this.user=this.session?this.session.user:null};#em=e=>this.client?.signedInSessions.find(t=>t.id===e)||null;#eE=()=>{this.addListener(({session:e})=>{e?.actor&&this.#Y?.then(e=>e.ensureMounted()).then(e=>e.mountImpersonationFab())})};#ex=()=>{this.#en.__internal_keyless_claimKeylessApplicationUrl&&this.#Y?.then(e=>e.ensureMounted()).then(e=>{e.updateProps({options:{__internal_keyless_claimKeylessApplicationUrl:this.#en.__internal_keyless_claimKeylessApplicationUrl,__internal_keyless_copyInstanceKeysUrl:this.#en.__internal_keyless_copyInstanceKeysUrl,__internal_keyless_dismissPrompt:this.#en.__internal_keyless_dismissPrompt}})})};#ew=(e,t,i)=>{if(!e||!this.loaded||!this.environment||!this.environment.displayConfig)return"";let n=this.#en[e]||this.environment.displayConfig[e];this.#eu()&&(n=this.#en.signInUrl);let r=new eS(this.#en,t).toSearchParams(),s=new URLSearchParams(i||{}),a=eg({base:n,hashPath:this.#eu()&&"signUpUrl"===e?"/create":"",hashSearchParams:[s,r]},{stringify:!0});return this.buildUrlWithAuth(a)};assertComponentsReady(e){if(!e)throw Error("Clerk was not loaded with Ui components")}#eT=async()=>{var e;let t,i,n,r,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,n=ev.includes(i)||ek.includes(i),e===t.host&&n);if(a||!o)return!1;let l=this.session,c=this.#en.signInUrl||this.environment?.displayConfig.signInUrl,d=c&&window.location.href.startsWith(c),h=this.#en.signUpUrl||this.environment?.displayConfig.signUpUrl,u=h&&window.location.href.startsWith(h);return r=new URL(s,eh),(!ev.includes(r.pathname)||!!l||!d&&!u)&&(await this.navigate(this.buildUrlWithAuth(s)),!0)};#eo=e=>({...rw,...e,allowedRedirectOrigins:function(e,t,i){if(Array.isArray(e)&&e.length)return e;let n=[];return"undefined"!=typeof window&&window.location&&n.push(window.location.origin),n.push(`https://${em(t)}`),n.push(`https://*.${em(t)}`),"development"===i&&n.push(`https://${t}`),n}(e?.allowedRedirectOrigins,this.frontendApi,this.instanceType)});#eO=()=>{try{eC(F),eC(eU),eC(N),eC("__clerk_handshake"),eC("__clerk_handshake_nonce"),eC("__clerk_help")}catch{}};get #e_(){let e=eM;return this.#en.allowedRedirectProtocols&&(e=e.concat(this.#en.allowedRedirectProtocols)),e}}let ry=document.querySelector("script[data-clerk-publishable-key]")?.getAttribute("data-clerk-publishable-key")||window.__clerk_publishable_key||"",rv=document.querySelector("script[data-clerk-proxy-url]")?.getAttribute("data-clerk-proxy-url")||window.__clerk_proxy_url||"",rk=document.querySelector("script[data-clerk-domain]")?.getAttribute("data-clerk-domain")||window.__clerk_domain||"";window.Clerk||(window.Clerk=new rb(ry,{proxyUrl:rv,domain:rk}))})(),{}})());